diff --git a/.vercel/output/functions/__server.func/_libs/@anthropic-ai/sdk+[...].mjs b/.vercel/output/functions/__server.func/_libs/@anthropic-ai/sdk+[...].mjs new file mode 100644 index 0000000..bef4224 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/@anthropic-ai/sdk+[...].mjs @@ -0,0 +1,11131 @@ +import { r as __exportAll, t as __commonJSMin } from "../../_runtime.mjs"; +import { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import * as crypto from "node:crypto"; +import { randomUUID } from "node:crypto"; +import * as cp from "node:child_process"; +import { execFile } from "node:child_process"; +import * as fs$2 from "node:fs/promises"; +import * as fssync from "node:fs"; +import * as path$1 from "node:path"; +import * as readline from "node:readline"; +import { promisify } from "node:util"; +//#region node_modules/@anthropic-ai/sdk/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/errors.mjs +function isAbortError(err) { + return typeof err === "object" && err !== null && ("name" in err && err.name === "AbortError" || "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError = (err) => { + if (err instanceof Error) return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) error.stack = err.stack; + if (err.cause && !error.cause) error.cause = err.cause; + if (err.name) error.name = err.name; + return error; + } + } catch {} + try { + return new Error(JSON.stringify(err)); + } catch {} + } + return new Error(err); +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/core/error.mjs +var AnthropicError = class extends Error {}; +var APIError = class APIError extends AnthropicError { + constructor(status, error, message, headers, type) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get("request-id"); + this.error = error; + this.type = type ?? null; + } + 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 || !headers) return new APIConnectionError({ + message, + cause: castToError(errorResponse) + }); + const error = errorResponse; + const type = error?.["error"]?.["type"]; + if (status === 400) return new BadRequestError(status, error, message, headers, type); + if (status === 401) return new AuthenticationError(status, error, message, headers, type); + if (status === 403) return new PermissionDeniedError(status, error, message, headers, type); + if (status === 404) return new NotFoundError(status, error, message, headers, type); + if (status === 409) return new ConflictError(status, error, message, headers, type); + if (status === 422) return new UnprocessableEntityError(status, error, message, headers, type); + if (status === 429) return new RateLimitError(status, error, message, headers, type); + if (status >= 500) return new InternalServerError(status, error, message, headers, type); + return new APIError(status, error, message, headers, type); + } +}; +var APIUserAbortError = class extends APIError { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } +}; +var APIConnectionError = class extends APIError { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) this.cause = cause; + } +}; +var APIConnectionTimeoutError = class extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +/** +* An error that opts into the SDK's retry policy: throw it (e.g. from +* middleware) to have the attempt retried. +* +* Note that the request will only be retried when `maxRetries` has not been exhausted. +*/ +var RetryableError = class extends AnthropicError { + constructor(message, { cause } = {}) { + super(message ?? "Retryable error."); + if (cause !== void 0) this.cause = cause; + } +}; +var BadRequestError = class extends APIError {}; +var AuthenticationError = class extends APIError {}; +var PermissionDeniedError = class extends APIError {}; +var NotFoundError = class extends APIError {}; +var ConflictError = class extends APIError {}; +var UnprocessableEntityError = class extends APIError {}; +var RateLimitError = class extends APIError {}; +var InternalServerError = class extends APIError {}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs +/** +* An error that can be thrown from a tool's `run` method to return structured +* content blocks as the error result, rather than just a string message. +* +* When the ToolRunner catches this error, it will use the `content` property +* as the tool result with `is_error: true`. +* +* @example +* ```ts +* const tool = { +* name: 'my_tool', +* run: async (input) => { +* if (somethingWentWrong) { +* throw new ToolError([ +* { type: 'text', text: 'Error details here' }, +* { type: 'image', source: { type: 'base64', data: '...', media_type: 'image/png' } }, +* ]); +* } +* return 'success'; +* }, +* }; +* ``` +*/ +var ToolError = class extends Error { + constructor(content) { + const message = typeof content === "string" ? content : content.map((block) => { + if (block.type === "text") return block.text; + return `[${block.type}]`; + }).join(" "); + super(message); + this.name = "ToolError"; + this.content = content; + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs +/** +* https://stackoverflow.com/a/2117523 +*/ +var uuid4 = function() { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); + } + const u8 = /* @__PURE__ */ new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/values.mjs +var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +var isArray = (val) => (isArray = Array.isArray, isArray(val)); +var isReadonlyArray = isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +function maybeObj(x) { + if (typeof x !== "object") return {}; + return x ?? {}; +} +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); +} +var validatePositiveInteger = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) throw new AnthropicError(`${name} must be an integer`); + if (n < 0) throw new AnthropicError(`${name} must be a positive integer`); + return n; +}; +var safeJSON = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return; + } +}; +var pop = (obj, key) => { + const value = obj[key]; + delete obj[key]; + return value; +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs +/** +* Resolve after `ms`, or immediately when `signal` aborts. +* +* When a `signal` is passed the abort listener is always removed so repeated +* calls do not accumulate listeners on a long-lived signal. Resolves (rather +* than rejects) on abort — callers treat abort as "wake up early," not as a +* failure; callers that want to unwind should check the signal themselves. +*/ +var sleep = (ms, signal) => new Promise((resolve) => { + if (signal?.aborted) return resolve(); + const onAbort = () => { + clearTimeout(timer); + resolve(); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal?.addEventListener("abort", onAbort, { once: true }); +}); +//#endregion +//#region node_modules/@anthropic-ai/sdk/version.mjs +var VERSION = "0.115.0"; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs +var isRunningInBrowser = () => { + return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined"; +}; +/** +* Note this does not detect 'browser'; for that, use getBrowserInfo(). +*/ +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) return "deno"; + if (typeof EdgeRuntime !== "undefined") return "edge"; + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") return "node"; + return "unknown"; +} +var getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") 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": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + 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": globalThis.process.version + }; + if (detectedPlatform === "node") return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + 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" + }; +}; +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) return null; + for (const { key, pattern } of [ + { + 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/ + } + ]) { + const match = pattern.exec(navigator.userAgent); + if (match) return { + browser: key, + version: `${match[1] || 0}.${match[2] || 0}.${match[3] || 0}` + }; + } + return null; +} +var 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"; +}; +var 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"; +}; +var _platformHeaders; +var getPlatformHeaders = () => { + return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/request-signal.mjs +/** +* Tracks the removal of the per-request abort listener that +* `fetchWithTimeout` attaches to a caller-provided signal, so the listener's +* lifetime matches the request instead of the signal. +* +* Without removal, a long-lived signal (e.g. one AbortController reused for +* a whole session) accumulates one `{ once: true }` listener plus its bound +* AbortController per HTTP attempt until the signal fires or is collected, +* and Node warns at the 11th listener. The listener must survive until the +* response body is settled - removing it when fetch resolves (headers) would +* break aborting an in-flight body read - so the code that finishes the body +* (response parsing, stream teardown, retry/error handling) calls +* `releaseRequestSignal` with the request's controller. +*/ +var cleanups = /* @__PURE__ */ new WeakMap(); +var registry = typeof globalThis.FinalizationRegistry === "function" ? new globalThis.FinalizationRegistry((controller) => releaseRequestSignal(controller)) : null; +function makeCleanup(signal, listener) { + return () => signal.removeEventListener("abort", listener); +} +function registerRequestSignalCleanup(controller, signal, listener) { + cleanups.set(controller, makeCleanup(signal, listener)); +} +function armAbandonmentBackstop(body, controller) { + if (cleanups.has(controller)) registry?.register(body, controller, controller); +} +function releaseRequestSignal(controller) { + const cleanup = cleanups.get(controller); + if (cleanup) { + cleanups.delete(controller); + registry?.unregister(controller); + cleanup(); + } +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/shims.mjs +function getDefaultFetch() { + if (typeof fetch !== "undefined") return fetch; + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() {}, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) controller.close(); + else controller.enqueue(value); + }, + async cancel() { + await iter.return?.(); + } + }); +} +/** +* Most browsers don't yet have async iterable support for ReadableStream, +* and Node has a very different way of reading bytes from its "ReadableStream". +* +* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 +*/ +function ReadableStreamToAsyncIterable(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 (e) { + reader.releaseLock(); + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { + done: true, + value: void 0 + }; + }, + [Symbol.asyncIterator]() { + return this; + } + }; +} +/** +* Cancels a ReadableStream we don't need to consume. +* See https://undici.nodejs.org/#/?id=garbage-collection +*/ +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== "object") return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/request-options.mjs +var FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { "content-type": "application/json" }, + body: JSON.stringify(body) + }; +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs +var default_format = "RFC3986"; +var default_formatter = (v) => String(v); +var formatters = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs +var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); +var hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + return array; +})(); +var limit = 1024; +var encode = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) return str; + let string = str; + if (typeof str === "symbol") string = Symbol.prototype.toString.call(str); + else if (typeof str !== "string") string = String(str); + if (charset === "iso-8859-1") return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + let out = ""; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === "RFC1738" && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hex_table[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + } + out += arr.join(""); + } + return out; +}; +function is_buffer(obj) { + if (!obj || typeof obj !== "object") return false; + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val, fn) { + if (isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) mapped.push(fn(val[i])); + return mapped; + } + return fn(val); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs +var array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } +}; +var push_to_array = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") if (pos === step) throw new RangeError("Cyclic object value"); + else find_flag = true; + if (typeof tmp_sc.get(sentinel) === "undefined") step = 0; + } + if (typeof filter === "function") obj = filter(prefix, obj); + else if (obj instanceof Date) obj = serializeDate?.(obj); + else if (generateArrayPrefix === "comma" && isArray(obj)) obj = maybe_map(obj, function(value) { + if (value instanceof Date) return serializeDate?.(value); + return value; + }); + if (obj === null) { + if (strictNullHandling) return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix; + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + return [formatter?.(key_value) + "=" + formatter?.(encoder(obj, defaults.encoder, charset, "value", format))]; + } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") return values; + let obj_keys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + if (encodeValuesOnly && encoder) obj = maybe_map(obj, encoder); + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) obj_keys = filter; + else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray(obj) && obj.length === 0) return adjusted_prefix + "[]"; + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]; + if (skipNulls && value === null) continue; + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); + } + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") throw new TypeError("Encoder has to be a function."); + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + let format = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) throw new TypeError("Unknown format option provided."); + format = opts.format; + } + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) filter = opts.filter; + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) arrayFormat = opts.arrayFormat; + else if ("indices" in opts) arrayFormat = opts.indices ? "indices" : "repeat"; + else arrayFormat = defaults.arrayFormat; + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; +} +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) return ""; + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) obj_keys = Object.keys(obj); + if (options.sort) obj_keys.sort(options.sort); + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) continue; + push_to_array(keys, inner_stringify(obj[key], key, generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) if (options.charset === "iso-8859-1") prefix += "utf8=%26%2310003%3B&"; + else prefix += "utf8=%E2%9C%93&"; + return joined.length > 0 ? prefix + joined : ""; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/query.mjs +function stringifyQuery(query) { + return stringify(query, { arrayFormat: "brackets" }); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs +var GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer"; +var GRANT_TYPE_REFRESH_TOKEN = "refresh_token"; +var TOKEN_ENDPOINT = "/v1/oauth/token"; +/** +* `anthropic-beta` value required on authenticated API requests using an +* OAuth bearer token, and on `refresh_token` grants against the token endpoint. +*/ +var OAUTH_API_BETA_HEADER = "oauth-2025-04-20"; +/** +* `anthropic-beta` value required on jwt-bearer exchanges against the token +* endpoint. It routes the request to the federation service; it must NOT be +* sent on `refresh_token` grants, which are handled by a different backend. +*/ +var FEDERATION_BETA_HEADER = "oidc-federation-2026-04-01"; +var MAX_TOKEN_RESPONSE_BYTES = 1 << 20; +/** +* Rejects base URLs that would cause a JWT assertion or refresh token to be +* sent over cleartext HTTP. Loopback hosts are allowed for local development. +*/ +function requireSecureTokenEndpoint(baseURL) { + if (!baseURL) return; + let u; + try { + u = new URL(baseURL); + } catch (err) { + throw new WorkloadIdentityError(`Invalid token endpoint base URL "${baseURL}": ${err}`); + } + if (u.protocol === "https:") return; + const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, ""); + if (u.protocol === "http:" && (host === "localhost" || host === "127.0.0.1" || host === "::1")) return; + throw new WorkloadIdentityError(`Refusing to send credential over non-https token endpoint "${baseURL}"`); +} +/** +* Reads the response body as text, parses it as a token-endpoint JSON +* response, validates `access_token` is present, and rejects a non-Bearer +* `token_type` when one is provided. Reads at most +* {@link MAX_TOKEN_RESPONSE_BYTES} from the body stream. +*/ +async function parseTokenResponse(resp, requestId) { + const text = await readLimitedText(resp); + let data; + try { + data = JSON.parse(text); + } catch { + throw new WorkloadIdentityError(`Token endpoint returned non-JSON response (status ${resp.status})`, resp.status, redactSensitive(text), requestId); + } + if (!data.access_token) throw new WorkloadIdentityError(`Token endpoint response missing access_token: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId); + if (data.token_type && data.token_type.toLowerCase() !== "bearer") throw new WorkloadIdentityError(`Token endpoint response: unsupported token_type "${data.token_type}" (want Bearer)`, resp.status, redactSensitive(data), requestId); + return data; +} +var MAX_ERROR_BODY_CHARS = 2e3; +var SAFE_ERROR_KEYS = /* @__PURE__ */ new Set([ + "error", + "error_description", + "error_uri" +]); +/** +* Returns a redacted copy of a token-endpoint error body for safe inclusion +* in an exception. Strings are truncated; objects keep only the RFC 6749 +* §5.2 error fields. +*/ +function redactSensitive(body) { + if (body == null) return body; + if (typeof body === "string") { + let parsed; + try { + parsed = JSON.parse(body); + } catch { + if (body.length <= MAX_ERROR_BODY_CHARS) return body; + return body.slice(0, MAX_ERROR_BODY_CHARS) + `... <${body.length - MAX_ERROR_BODY_CHARS} more chars>`; + } + return JSON.stringify(redactSensitive(parsed)); + } + if (typeof body === "object" && !Array.isArray(body)) { + const out = {}; + for (const [k, v] of Object.entries(body)) if (SAFE_ERROR_KEYS.has(k)) out[k] = v; + return out; + } + return null; +} +/** +* Best-effort safety check on a credentials file before reading it. +* +* On POSIX: resolves symlinks (so containerized deployments that mount the +* credential as a symlink to a tmpfs-backed file keep working), then rejects +* the resolved target if it is group- or world- readable or writable. A uid +* mismatch on the resolved target is surfaced via `onWarn` since +* root-written/app-read is common in init-container setups. No-op on Windows. +*/ +async function checkCredentialsFileSafety(path, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) { + if (typeof process === "undefined" || process.platform === "win32") return; + const fs = await import("node:fs"); + let resolved = path; + let st; + try { + resolved = await fs.promises.realpath(path); + st = await fs.promises.stat(resolved); + } catch { + return; + } + const mode = st.mode & 511; + if (mode & 18) throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-writable (mode 0o${mode.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${resolved}\`.`); + if (mode & 36) throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-readable (mode 0o${mode.toString(8)}); run \`chmod 600 ${resolved}\` before retrying.`); + if (typeof process.getuid === "function" && st.uid !== process.getuid()) onWarn(`credentials file at ${resolved} is owned by uid ${st.uid} (current process uid ${process.getuid()}); verify this is intentional.`); +} +/** +* Atomically writes JSON to `targetPath` via a `.tmp` sibling + rename, +* with fsync on the file and (best-effort) on the parent directory. +* Creates the parent directory with mode 0700 and the file with mode 0600. +*/ +async function writeCredentialsFileAtomic(targetPath, data) { + const fs = await import("node:fs"); + const dir = (await import("node:path")).dirname(targetPath); + await fs.promises.mkdir(dir, { + recursive: true, + mode: 448 + }); + const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + try { + const fh = await fs.promises.open(tmpPath, "w", 384); + try { + await fh.writeFile(JSON.stringify(data, null, 2)); + await fh.sync(); + } finally { + await fh.close(); + } + await fs.promises.rename(tmpPath, targetPath); + } catch (err) { + await fs.promises.unlink(tmpPath).catch(() => {}); + throw err; + } + try { + const dirFh = await fs.promises.open(dir, "r"); + try { + await dirFh.sync(); + } finally { + await dirFh.close(); + } + } catch {} +} +async function readLimitedText(resp) { + if (!resp.body) return ""; + const reader = resp.body.getReader(); + const chunks = []; + let received = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (received + value.length > MAX_TOKEN_RESPONSE_BYTES) { + const remaining = MAX_TOKEN_RESPONSE_BYTES - received; + if (remaining > 0) chunks.push(value.subarray(0, remaining)); + await reader.cancel(); + break; + } + chunks.push(value); + received += value.length; + } + let merged; + if (chunks.length === 1) merged = chunks[0]; + else { + merged = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0)); + let offset = 0; + for (const c of chunks) { + merged.set(c, offset); + offset += c.length; + } + } + return new TextDecoder("utf-8").decode(merged); +} +var WorkloadIdentityError = class extends AnthropicError { + constructor(message, statusCode = null, body = null, requestId = null) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.requestId = requestId; + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/time.mjs +/** Current time as unix epoch seconds. */ +function nowAsSeconds() { + return Math.floor(Date.now() / 1e3); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs +/** +* Wraps an {@link AccessTokenProvider} with two-tier proactive refresh +* and concurrent deduplication. +* +* Refresh policy on each {@link getToken} call: +* +* - No cached token → call provider (blocking), cache, return. +* - Cached with `expiresAt == null` → return cached forever. +* - More than 120s remaining → return cached. +* - 30–120s remaining (advisory window) → return stale token immediately, +* kick off background refresh. On failure, log and keep stale. +* - Less than 30s remaining or expired (mandatory) → block and refresh. +* On failure, throw. +* +* Concurrent mandatory callers coalesce into a single provider call. +*/ +var TokenCache = class { + constructor(provider, onAdvisoryRefreshError) { + this.cached = null; + this.pendingRefresh = null; + this.nextForce = false; + this.lastAdvisoryError = 0; + this.provider = provider; + this.onAdvisoryRefreshError = onAdvisoryRefreshError; + } + async getToken() { + const force = this.nextForce; + this.nextForce = false; + const cached = this.cached; + if (force || cached == null) return (await this.refresh(force)).token; + if (cached.expiresAt == null) return cached.token; + const remaining = cached.expiresAt - nowAsSeconds(); + if (remaining > 120) return cached.token; + if (remaining > 30) { + this.backgroundRefresh(); + return cached.token; + } + return (await this.refresh()).token; + } + /** + * Clears the cached token and marks the next {@link getToken} as a forced + * refresh, so the underlying provider bypasses any on-disk freshness check. + * Called after a 401 — the server has just told us the token is bad even + * if its `expires_at` still looks fresh. + */ + invalidate() { + this.cached = null; + this.nextForce = true; + } + /** + * Mandatory refresh. Joins any in-flight refresh unless forced — a forced + * refresh must not coalesce into a non-forced one that may re-serve the + * same stale disk token. + */ + refresh(force = false) { + if (this.pendingRefresh && !force) return this.pendingRefresh; + return this.doRefresh(force); + } + /** + * Advisory background refresh. Shares the same in-flight promise as + * mandatory refreshes for deduplication, but swallows errors so the + * stale cached token keeps being served. Backs off for + * {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure so an + * outage during the advisory window doesn't hammer the token endpoint. + */ + backgroundRefresh() { + if (this.pendingRefresh) return; + if (nowAsSeconds() - this.lastAdvisoryError < 5) return; + this.doRefresh().catch((err) => { + this.lastAdvisoryError = nowAsSeconds(); + this.onAdvisoryRefreshError?.(err); + }); + } + /** + * Core refresh. Sets {@link pendingRefresh} so concurrent callers + * (both advisory and mandatory) coalesce into a single provider call. + */ + doRefresh(force = false) { + this.pendingRefresh = this.provider(force ? { forceRefresh: true } : void 0).then((token) => { + this.cached = token; + this.pendingRefresh = null; + return token; + }, (err) => { + this.pendingRefresh = null; + throw err; + }); + return this.pendingRefresh; + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/env.mjs +/** +* Read an environment variable. +* +* Trims beginning and trailing whitespace. +* +* Will return undefined if the environment variable doesn't exist or cannot be accessed. +*/ +var readEnv = (env) => { + if (typeof globalThis.process !== "undefined") return globalThis.process.env?.[env]?.trim() || void 0; + if (typeof globalThis.Deno !== "undefined") return globalThis.Deno.env?.get?.(env)?.trim() || void 0; +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs +function concatBytes(buffers) { + let length = 0; + for (const buffer of buffers) length += buffer.length; + const output = new Uint8Array(length); + let index = 0; + for (const buffer of buffers) { + output.set(buffer, index); + index += buffer.length; + } + return output; +} +var encodeUTF8_; +function encodeUTF8(str) { + let encoder; + return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str); +} +var decodeUTF8_; +function decodeUTF8(bytes) { + let decoder; + return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/log.mjs +var defaultLogLevel = "warn"; +var levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel = (maybeLevel, sourceName, logger) => { + if (!maybeLevel) return; + if (hasOwn(levelNumbers, maybeLevel)) return maybeLevel; + logger.warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); +}; +function noop() {} +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) return noop; + else return logger[fnLevel].bind(logger); +} +var noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop +}; +var cachedLoggers = /* @__PURE__ */ new WeakMap(); +function filterLogger(logger, logLevel) { + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) return cachedLogger[1]; + const levelLogger = { + error: makeLogFn("error", logger, logLevel), + warn: makeLogFn("warn", logger, logLevel), + info: makeLogFn("info", logger, logLevel), + debug: makeLogFn("debug", logger, logLevel) + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger) return noopLogger; + return filterLogger(logger, logLevel); +} +var lastEnvLevel; +var cachedDefaultLogger; +/** +* A logger matching the client defaults — `console`, filtered to +* `ANTHROPIC_LOG` or {@link defaultLogLevel} — for contexts with no client to +* read the configured `logger`/`logLevel` from. +* +* Cached per `ANTHROPIC_LOG` value so an invalid value warns once, like a +* client construction does, rather than on every request. +*/ +function defaultLogger() { + const envLevel = readEnv("ANTHROPIC_LOG"); + if (!cachedDefaultLogger || envLevel !== lastEnvLevel) { + lastEnvLevel = envLevel; + cachedDefaultLogger = filterLogger(console, parseLogLevel(envLevel, "process.env['ANTHROPIC_LOG']", filterLogger(console, "warn")) ?? "warn"); + } + return cachedDefaultLogger; +} +var formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value])); + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) details.retryOf = details.retryOfRequestLogID; + delete details.retryOfRequestLogID; + } + return details; +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/core/credentials.mjs +var PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/; +function validateProfileName(name) { + if (!name) throw new Error("profile name is empty"); + if (name === "." || name === "..") throw new Error(`profile name "${name}" is not allowed`); + if (name.includes("/") || name.includes("\\")) throw new Error(`profile name "${name}" must not contain path separators`); + if (!PROFILE_NAME_PATTERN.test(name)) throw new Error(`profile name "${name}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`); +} +/** +* Same as {@link loadConfig}, but also reports whether the config was loaded +* from a profile file on disk (`fromFile: true`) or synthesized entirely from +* environment variables (`fromFile: false`). +*/ +var loadConfigWithSource = async (profile) => { + var _a, _b; + const rootConfigPath = await getRootConfigPath(); + if (rootConfigPath === null) return null; + const profileName = profile ?? await getActiveProfileName(); + if (profileName === null) return null; + validateProfileName(profileName); + const fs = await import("node:fs"); + const configPath = (await import("node:path")).join(rootConfigPath, "configs", `${profileName}.json`); + let configRaw; + try { + configRaw = await fs.promises.readFile(configPath, "utf-8"); + } catch (err) { + if (err?.code !== "ENOENT") throw new Error(`failed to read config file ${configPath}: ${err}`); + configRaw = null; + } + if (configRaw === null) { + const organizationId = readEnv("ANTHROPIC_ORGANIZATION_ID"); + const identityTokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); + const federationRuleId = readEnv("ANTHROPIC_FEDERATION_RULE_ID"); + if (federationRuleId && organizationId) return { + fromFile: false, + config: { + organization_id: organizationId, + workspace_id: readEnv("ANTHROPIC_WORKSPACE_ID"), + base_url: readEnv("ANTHROPIC_BASE_URL"), + authentication: { + type: "oidc_federation", + federation_rule_id: federationRuleId, + service_account_id: readEnv("ANTHROPIC_SERVICE_ACCOUNT_ID"), + identity_token: identityTokenFile ? { + source: "file", + path: identityTokenFile + } : void 0, + scope: readEnv("ANTHROPIC_SCOPE") + } + } + }; + return null; + } + let config; + try { + config = JSON.parse(configRaw); + } catch (err) { + throw new Error(`failed to parse config file ${configPath}: ${err}`); + } + if (!config.authentication) throw new Error(`config file ${configPath} is missing "authentication"`); + const authType = config.authentication.type; + if (authType !== "oidc_federation" && authType !== "user_oauth") throw new Error(`authentication.type "${authType}" is not a known authentication type`); + config.organization_id ?? (config.organization_id = readEnv("ANTHROPIC_ORGANIZATION_ID")); + config.workspace_id ?? (config.workspace_id = readEnv("ANTHROPIC_WORKSPACE_ID")); + config.base_url ?? (config.base_url = readEnv("ANTHROPIC_BASE_URL")); + (_a = config.authentication).scope ?? (_a.scope = readEnv("ANTHROPIC_SCOPE")); + if (config.authentication.type === "oidc_federation") { + if (!config.authentication.identity_token) { + const identityTokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); + if (identityTokenFile) config.authentication.identity_token = { + source: "file", + path: identityTokenFile + }; + } + if (!config.authentication.federation_rule_id) config.authentication.federation_rule_id = readEnv("ANTHROPIC_FEDERATION_RULE_ID") ?? ""; + (_b = config.authentication).service_account_id ?? (_b.service_account_id = readEnv("ANTHROPIC_SERVICE_ACCOUNT_ID")); + } + return { + config, + fromFile: true + }; +}; +/** +* Resolves the credentials file path for the given config. +* +* Uses `authentication.credentials_path` from the config if set, otherwise +* falls back to `/credentials/.json`. +* +* Returns `null` when running in a browser or the path cannot be resolved. +*/ +var getCredentialsPath = async (config, profile) => { + if (config?.authentication.credentials_path) return config.authentication.credentials_path; + const rootConfigPath = await getRootConfigPath(); + if (!rootConfigPath) return null; + const profileName = profile ?? await getActiveProfileName(); + if (!profileName) return null; + validateProfileName(profileName); + return (await import("node:path")).join(rootConfigPath, "credentials", `${profileName}.json`); +}; +var getRootConfigPath = async () => { + if (!supportsLocalConfigFiles()) return null; + const path = await import("node:path"); + const configDir = readEnv("ANTHROPIC_CONFIG_DIR"); + if (configDir) return configDir; + if (getPlatformHeaders()["X-Stainless-OS"] === "Windows") { + const appData = readEnv("APPDATA"); + if (appData) return path.join(appData, "Anthropic"); + const userProfile = readEnv("USERPROFILE"); + if (userProfile) return path.join(userProfile, "AppData", "Roaming", "Anthropic"); + return null; + } + const xdgConfigHome = readEnv("XDG_CONFIG_HOME"); + if (xdgConfigHome) return path.join(xdgConfigHome, "anthropic"); + const home = readEnv("HOME"); + if (home) return path.join(home, ".config", "anthropic"); + return null; +}; +var supportsLocalConfigFiles = () => { + const runtime = getPlatformHeaders()["X-Stainless-Runtime"]; + return runtime === "node" || runtime === "deno"; +}; +var getActiveProfileName = async () => { + const rootConfigPath = await getRootConfigPath(); + if (!rootConfigPath) return null; + const profileName = readEnv("ANTHROPIC_PROFILE"); + if (profileName) return profileName; + const fs = await import("node:fs"); + const filePath = (await import("node:path")).join(rootConfigPath, "active_config"); + try { + return (await fs.promises.readFile(filePath, "utf-8")).trim() || "default"; + } catch (err) { + if (err?.code !== "ENOENT") throw new Error(`failed to read ${filePath}: ${err}`); + return "default"; + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs +/** +* Reads a JWT from a file on every call. Supports automatic rotation +* (e.g. Kubernetes projected service-account tokens). +*/ +function identityTokenFromFile(path) { + if (!path) throw new AnthropicError("Identity token file path is empty"); + return async () => { + const fs = await import("node:fs"); + let content; + try { + content = await fs.promises.readFile(path, "utf-8"); + } catch (err) { + throw new AnthropicError(`Failed to read identity token file at ${path}: ${err}`); + } + const token = content.trim(); + if (!token) throw new AnthropicError(`Identity token file at ${path} is empty`); + return token; + }; +} +/** +* Wraps a static JWT string as an {@link IdentityTokenProvider}. +*/ +function identityTokenFromValue(token) { + if (!token) throw new AnthropicError("Identity token value is empty"); + return () => token; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs +/** +* Exchanges an external OIDC JWT for an Anthropic access token via the +* RFC 7523 jwt-bearer grant. +* +* Each invocation performs a fresh token exchange. Wrap in a +* {@link TokenCache} to avoid exchanging on every request. +* +* Federation grants do not return a refresh token — callers re-exchange +* their assertion on expiry. +*/ +function oidcFederationProvider(config) { + return async () => { + requireSecureTokenEndpoint(config.baseURL); + const jwt = await config.identityTokenProvider(); + if (jwt.length > 16 * 1024) throw new WorkloadIdentityError(`Identity token is ${Math.ceil(jwt.length / 1024)} KiB, exceeds the 16 KiB assertion limit`); + const body = { + grant_type: GRANT_TYPE_JWT_BEARER, + assertion: jwt, + federation_rule_id: config.federationRuleId, + organization_id: config.organizationId + }; + if (config.serviceAccountId) body["service_account_id"] = config.serviceAccountId; + if (config.workspaceId) body["workspace_id"] = config.workspaceId; + const url = `${config.baseURL}${TOKEN_ENDPOINT}`; + let resp; + try { + resp = await config.fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + "anthropic-beta": `${OAUTH_API_BETA_HEADER},${FEDERATION_BETA_HEADER}`, + "User-Agent": config.userAgent || `anthropic-sdk-typescript/0.115.0 oidcFederationProvider` + }, + body: JSON.stringify(body) + }); + } catch (err) { + throw new WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${err}`); + } + const requestId = resp.headers.get("Request-Id"); + if (!resp.ok) { + const redacted = redactSensitive(await resp.text().catch(() => "")); + let hint = ""; + if (resp.status === 401) hint = ` Ensure your federation rule matches your identity token. ${config.workspaceId ? "" : "If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`; + throw new WorkloadIdentityError(`Token exchange failed with status ${resp.status}${requestId ? ` (request-id ${requestId})` : ""}: ${redacted}${hint}`, resp.status, redacted, requestId); + } + const data = await parseTokenResponse(resp, requestId); + const expiresIn = Number(data.expires_in); + if (!Number.isFinite(expiresIn)) throw new WorkloadIdentityError(`Token endpoint response missing required fields: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId); + return { + token: data.access_token, + expiresAt: nowAsSeconds() + expiresIn + }; + }; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs +/** +* Reads a user-oauth credential file. Returns the cached access token while +* fresh; on expiry performs a `refresh_token` grant and writes the new +* tokens back to the credentials file (atomic replace, fsync'd). +* +* If `clientId` is empty, the access token is treated as static — the +* credentials file is read on every call but no refresh is attempted, and +* an expired token without a `refresh_token` raises. +*/ +function userOAuthProvider(config) { + return async (opts) => { + const fs = await import("node:fs"); + await checkCredentialsFileSafety(config.credentialsPath, config.onSafetyWarning); + let raw; + try { + raw = await fs.promises.readFile(config.credentialsPath, "utf-8"); + } catch (err) { + throw new WorkloadIdentityError(`Credentials file not found at ${config.credentialsPath}: ${err}`); + } + let creds; + try { + creds = JSON.parse(raw); + } catch (err) { + throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} is not valid JSON: ${err}`); + } + const accessToken = creds.access_token; + if (!accessToken) throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} must include 'access_token'`); + const expiresAt = creds.expires_at; + if (!opts?.forceRefresh && (expiresAt == null || nowAsSeconds() < expiresAt - 30)) return { + token: accessToken, + expiresAt: expiresAt ?? null + }; + const refreshToken = creds.refresh_token; + if (!config.clientId || !refreshToken) throw new WorkloadIdentityError(`Access token at ${config.credentialsPath} has expired and no refresh is available (client_id ${config.clientId ? "set" : "empty"}, refresh_token ${refreshToken ? "set" : "empty"})`); + requireSecureTokenEndpoint(config.baseURL); + const body = { + grant_type: GRANT_TYPE_REFRESH_TOKEN, + refresh_token: refreshToken, + client_id: config.clientId + }; + const url = `${config.baseURL}${TOKEN_ENDPOINT}`; + let resp; + try { + resp = await config.fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + "anthropic-beta": OAUTH_API_BETA_HEADER, + "User-Agent": config.userAgent || `anthropic-sdk-typescript/0.115.0 userOAuthProvider` + }, + body: JSON.stringify(body) + }); + } catch (err) { + throw new WorkloadIdentityError(`User OAuth refresh failed to reach token endpoint: ${err}`); + } + const requestId = resp.headers.get("Request-Id"); + if (!resp.ok) { + const text = await resp.text().catch(() => ""); + throw new WorkloadIdentityError(`User OAuth refresh failed (HTTP ${resp.status}): ${redactSensitive(text)}`, resp.status, redactSensitive(text), requestId); + } + const data = await parseTokenResponse(resp, requestId); + const expiresIn = Number(data.expires_in); + if (!Number.isFinite(expiresIn)) throw new WorkloadIdentityError(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId); + const newExpiresAt = nowAsSeconds() + expiresIn; + const newRefreshToken = data.refresh_token || refreshToken; + await writeCredentialsFileAtomic(config.credentialsPath, { + ...creds, + version: "1.0", + type: "oauth_token", + access_token: data.access_token, + expires_at: newExpiresAt, + refresh_token: newRefreshToken + }); + return { + token: data.access_token, + expiresAt: newExpiresAt + }; + }; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs +function resolveCredentialsFromConfig(config, options) { + const provider = buildProvider(config, config.authentication.credentials_path ?? null, (config.base_url || options.baseURL).replace(/\/+$/, ""), options); + const extraHeaders = {}; + if (config.workspace_id && config.authentication.type === "user_oauth") extraHeaders["anthropic-workspace-id"] = config.workspace_id; + return { + provider, + extraHeaders, + baseURL: config.base_url || void 0 + }; +} +/** +* Resolves a {@link CredentialResult} from the environment. Returns `null` +* when no credentials can be resolved. +* +* Resolution order: +* +* 1. Config file for the active profile (or the explicit `profile` argument) +* → dispatch on `authentication.type` (`oidc_federation`, `user_oauth`) +* 2. Environment variables `ANTHROPIC_FEDERATION_RULE_ID` + +* `ANTHROPIC_ORGANIZATION_ID` (+ identity token) → OIDC federation +* 3. Nothing matches → `null` +* +* Passing `profile` selects `/configs/.json` directly, +* skipping `ANTHROPIC_PROFILE` / `active_config` resolution. +*/ +async function defaultCredentials(options, profile) { + const loaded = await loadConfigWithSource(profile); + if (!loaded) return null; + const { config, fromFile } = loaded; + return resolveCredentialsFromConfig(config.authentication.credentials_path || !fromFile ? config : { + ...config, + authentication: { + ...config.authentication, + credentials_path: await getCredentialsPath(config, profile) ?? void 0 + } + }, options); +} +function buildProvider(config, credentialsPath, baseURL, options) { + switch (config.authentication.type) { + case "oidc_federation": { + const auth = config.authentication; + const identityProvider = resolveIdentityTokenProvider(auth); + if (!identityProvider) throw new WorkloadIdentityError("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)"); + if (!auth.federation_rule_id) throw new WorkloadIdentityError("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence)."); + if (!config.organization_id) throw new WorkloadIdentityError("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)"); + const exchange = oidcFederationProvider({ + identityTokenProvider: identityProvider, + federationRuleId: auth.federation_rule_id, + organizationId: config.organization_id, + serviceAccountId: auth.service_account_id, + workspaceId: config.workspace_id, + baseURL, + fetch: options.fetch, + userAgent: options.userAgent + }); + if (credentialsPath) return cachedExchangeProvider(exchange, credentialsPath, options.onCacheWriteError, options.onSafetyWarning); + return exchange; + } + case "user_oauth": + if (!credentialsPath) throw new WorkloadIdentityError("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to /credentials/.json)"); + return userOAuthProvider({ + credentialsPath, + clientId: config.authentication.client_id, + baseURL, + fetch: options.fetch, + userAgent: options.userAgent, + onSafetyWarning: options.onSafetyWarning + }); + default: { + const t = config.authentication.type; + throw new WorkloadIdentityError(`authentication.type "${t}" is not a known authentication type`); + } + } +} +/** +* Resolves the identity token provider from config fields or environment variables. +* +* Resolution order: +* 1. `identity_token.path` from the config (source: "file") +* 2. `ANTHROPIC_IDENTITY_TOKEN_FILE` env var +* 3. `ANTHROPIC_IDENTITY_TOKEN` env var (static value) +*/ +function resolveIdentityTokenProvider(auth) { + if (auth.identity_token) { + const source = auth.identity_token.source; + if (source !== "file") throw new WorkloadIdentityError(`identity_token.source "${source}" is not supported by this SDK version (only "file")`); + if (!auth.identity_token.path) throw new WorkloadIdentityError(`identity_token.source "file" requires a non-empty path`); + return identityTokenFromFile(auth.identity_token.path); + } + const tokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); + if (tokenFile) return identityTokenFromFile(tokenFile); + const tokenValue = readEnv("ANTHROPIC_IDENTITY_TOKEN"); + if (tokenValue) return identityTokenFromValue(tokenValue); + return null; +} +/** +* Wraps a federation exchange provider with credential file caching. +* Checks the file for a fresh token before exchanging, and writes the +* result back after a successful exchange (best-effort, atomic replace). +* +* Note: this is not cross-process serialized — two SDK instances that +* miss the cache simultaneously will both perform a full exchange and +* the last writer wins. That is acceptable: federation exchanges are +* idempotent and the cache is an optimization, not a correctness gate. +*/ +function cachedExchangeProvider(exchange, credentialsPath, onCacheWriteError, onSafetyWarning) { + return async (opts) => { + const fs = await import("node:fs"); + await checkCredentialsFileSafety(credentialsPath, onSafetyWarning); + let existing; + try { + const raw = await fs.promises.readFile(credentialsPath, "utf-8"); + existing = JSON.parse(raw); + const token = existing?.["access_token"]; + if (token && !opts?.forceRefresh) { + const expiresAt = existing?.["expires_at"]; + if (expiresAt == null || nowAsSeconds() < expiresAt - 30) return { + token, + expiresAt: expiresAt ?? null + }; + } + } catch (err) { + if (err?.code !== "ENOENT" && !(err instanceof SyntaxError)) onCacheWriteError?.(err); + } + const result = await exchange(opts); + try { + await writeCredentialsFileAtomic(credentialsPath, { + ...existing ?? {}, + version: "1.0", + type: "oauth_token", + access_token: result.token, + expires_at: result.expiresAt + }); + } catch (err) { + onCacheWriteError?.(err); + } + return result; + }; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs +var _LineDecoder_buffer; +var _LineDecoder_carriageReturnIndex; +/** +* A re-implementation of httpx's `LineDecoder` in Python that handles incrementally +* reading lines from text. +* +* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 +*/ +var LineDecoder = class { + constructor() { + _LineDecoder_buffer.set(this, void 0); + _LineDecoder_carriageReturnIndex.set(this, void 0); + __classPrivateFieldSet(this, _LineDecoder_buffer, /* @__PURE__ */ new Uint8Array(), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + decode(chunk) { + if (chunk == null) return []; + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; + __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + continue; + } + if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + continue; + } + const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); + lines.push(line); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + return lines; + } + flush() { + if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) return []; + return this.decode("\n"); + } +}; +_LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex = /* @__PURE__ */ new WeakMap(); +LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]); +LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +/** +* This function searches the buffer for the end patterns, (\r or \n) +* and returns an object with the index preceding the matched newline and the +* index after the newline char. `null` is returned if no new line is found. +* +* ```ts +* findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } +* ``` +*/ +function findNewlineIndex(buffer, startIndex) { + const newline = 10; + const carriage = 13; + for (let i = startIndex ?? 0; i < buffer.length; i++) { + if (buffer[i] === newline) return { + preceding: i, + index: i + 1, + carriage: false + }; + if (buffer[i] === carriage) return { + preceding: i, + index: i + 1, + carriage: true + }; + } + return null; +} +function findDoubleNewlineIndex(buffer) { + const newline = 10; + const carriage = 13; + for (let i = 0; i < buffer.length - 1; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) return i + 2; + if (buffer[i] === carriage && buffer[i + 1] === carriage) return i + 2; + if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) return i + 4; + } + return -1; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/core/streaming.mjs +var _Stream_client; +var Stream = class Stream { + constructor(iterator, controller, client) { + this.iterator = iterator; + _Stream_client.set(this, void 0); + this.controller = controller; + __classPrivateFieldSet(this, _Stream_client, client, "f"); + } + /** + * Iterate the raw Server-Sent Events from `response` — `{event, data, raw}` + * objects, before any JSON parsing or event-name filtering. + * + * This reads `response.body` directly (not a clone), so the response is + * consumed. Use this in middleware that fully replaces the stream body; for + * read-only observation of parsed events, use `ctx.parse()` instead. + */ + static rawEvents(response, controller = new AbortController()) { + return _iterSSEMessages(response, controller); + } + static fromSSEResponse(response, controller, client) { + let consumed = false; + const logger = client ? loggerFor(client) : console; + async function* iterator() { + if (consumed) throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (sse.event === "completion") try { + yield JSON.parse(sse.data); + } catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop" || sse.event === "message" || sse.event === "user.message" || sse.event === "user.interrupt" || sse.event === "user.tool_confirmation" || sse.event === "user.custom_tool_result" || sse.event === "user.tool_result" || sse.event === "agent.message" || sse.event === "agent.thinking" || sse.event === "agent.tool_use" || sse.event === "agent.tool_result" || sse.event === "agent.mcp_tool_use" || sse.event === "agent.mcp_tool_result" || sse.event === "agent.custom_tool_use" || sse.event === "agent.thread_context_compacted" || sse.event === "session.status_running" || sse.event === "session.status_idle" || sse.event === "session.status_rescheduled" || sse.event === "session.status_terminated" || sse.event === "session.error" || sse.event === "session.deleted" || sse.event === "session.updated" || sse.event === "span.model_request_start" || sse.event === "span.model_request_end" || sse.event === "span.outcome_evaluation_start" || sse.event === "span.outcome_evaluation_ongoing" || sse.event === "span.outcome_evaluation_end" || sse.event === "user.define_outcome" || sse.event === "agent.thread_message_received" || sse.event === "agent.thread_message_sent" || sse.event === "agent.session_thread_message_received" || sse.event === "agent.session_thread_message_sent" || sse.event === "session.thread_created" || sse.event === "session.thread_status_created" || sse.event === "session.thread_status_running" || sse.event === "session.thread_status_idle" || sse.event === "session.thread_status_rescheduled" || sse.event === "session.thread_status_terminated" || sse.event === "event_start" || sse.event === "event_delta" || sse.event === "system.message") try { + yield JSON.parse(sse.data); + } catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + if (sse.event === "ping") continue; + if (sse.event === "error") { + const body = safeJSON(sse.data) ?? sse.data; + const type = body?.error?.type; + throw new APIError(void 0, body, void 0, response.headers, type); + } + } + done = true; + } catch (e) { + if (isAbortError(e)) return; + throw e; + } finally { + if (!done) controller.abort(); + releaseRequestSignal(controller); + } + } + return new Stream(iterator, controller, client); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller, client) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(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 AnthropicError("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 (e) { + if (isAbortError(e)) return; + throw e; + } finally { + if (!done) controller.abort(); + releaseRequestSignal(controller); + } + } + return new Stream(iterator, controller, client); + } + [(_Stream_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + } }; + }; + return [new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f"))]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self = this; + let iter; + return makeReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) return ctrl.close(); + const bytes = encodeUTF8(JSON.stringify(value) + "\n"); + ctrl.enqueue(bytes); + } catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + } + }); + } +}; +async function* _iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + throw new AnthropicError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) yield sse; + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) yield sse; + } +} +/** +* Given an async iterable iterator, iterates over it and yields full +* SSE chunks, i.e. yields when a double new-line is encountered. +*/ +async function* iterSSEChunks(iterator) { + let data = /* @__PURE__ */ new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) continue; + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) yield data; +} +var 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, _, 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; + } +}; +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) return [ + str.substring(0, index), + delimiter, + str.substring(index + delimiter.length) + ]; + return [ + str, + "", + "" + ]; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/parse.mjs +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + loggerFor(client).debug("response", response.status, response.url, response.headers, response.body); + return Stream.fromSSEResponse(response, props.controller); + } + if (response.status === 204) return null; + if (props.options.__binaryResponse) return response; + const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim(); + if (mediaType?.includes("application/json") || mediaType?.endsWith("+json")) { + if (response.headers.get("content-length") === "0") return; + return addRequestID(await response.json(), response); + } + return await response.text(); + })().finally(() => { + if (!props.options.stream && !props.options.__binaryResponse) releaseRequestSignal(props.controller); + }); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} +function addRequestID(value, response) { + if (!value || typeof value !== "object" || Array.isArray(value)) return value; + return Object.defineProperty(value, "_request_id", { + value: response.headers.get("request-id"), + enumerable: false + }); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/core/middleware.mjs +/** +* Errors thrown by the underlying `fetch`, as opposed to by a middleware. +* +* Tracked so the client can apply its connection-error retry policy to +* transport failures while letting errors thrown by middleware propagate to +* the caller untouched. +*/ +var fetchOriginErrors = /* @__PURE__ */ new WeakSet(); +/** Whether `err` was thrown by the underlying `fetch` rather than by a middleware. */ +function isFetchOriginError(err) { + return typeof err === "object" && err !== null && fetchOriginErrors.has(err); +} +/** +* Whether an error thrown by middleware should stay on the SDK's +* connection-error retry policy: fetch-origin, abort, `APIConnectionError`, or +* `RetryableError` — checked through the error's `cause` chain. +*/ +function isRetryableError(err) { + const seen = /* @__PURE__ */ new Set(); + while (typeof err === "object" && err !== null && !seen.has(err)) { + seen.add(err); + if (isFetchOriginError(err) || isAbortError(err) || err instanceof APIConnectionError || err instanceof RetryableError) return true; + err = err.cause; + } + return false; +} +/** +* Wraps `fetchFn` so each call runs through `middleware`, keeping the same +* call signature as `fetch` itself. +* +* With no middleware, calls are passed straight through to `fetchFn`. +* Otherwise the arguments are normalized into an {@link APIRequest} (headers +* coerced to a `Headers` instance, URL stringified) before entering the +* chain. The chain is composed per call, so mutations of a `middleware` +* array are picked up by later requests. +* +* `options` — the SDK request options behind this call, when there are any — +* is surfaced to middleware as `ctx.options` and drives `ctx.parse`. +* +* `client` supplies `ctx.logger` (the client's level-filtered logger); +* without it, `ctx.logger` falls back to the client defaults: `console`, +* filtered to `ANTHROPIC_LOG` or `'warn'`. +*/ +function wrapFetchWithMiddleware(fetchFn, middleware, options, client) { + return async (url, init = {}) => { + if (middleware.length === 0) return fetchFn.call(void 0, url, init); + const headers = init.headers instanceof Headers ? init.headers : new Headers(init.headers); + const response = await applyMiddleware(fetchFn, middleware, options, client)({ + ...init, + headers, + url: typeof url === "string" ? url : url instanceof URL ? url.href : url.url + }); + if (response.bodyUsed || response.body?.locked) throw new AnthropicError("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it"); + return response; + }; +} +/** +* Creates the {@link MiddlewareContext} shared by every middleware in one chain. +*/ +function createMiddlewareContext(options, client) { + const cache = /* @__PURE__ */ new WeakMap(); + return { + options, + logger: client ? loggerFor(client) : defaultLogger(), + parse(response) { + if (options?.stream && response.ok) return parseMiddlewareResponse(response, options); + let parsed = cache.get(response); + if (!parsed) { + parsed = parseMiddlewareResponse(response, options); + cache.set(response, parsed); + } + return parsed; + } + }; +} +/** +* Mirrors the client's own response parsing (`defaultParseResponse` in +* `internal/parse.ts`), reading through a clone so the body stays available +* to the rest of the chain and the client itself. +*/ +async function parseMiddlewareResponse(response, options) { + if (response.bodyUsed || response.body?.locked) throw new AnthropicError("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()"); + if (options?.stream && response.ok) return Stream.fromSSEResponse(response.clone(), new AbortController()); + if (response.status === 204) return null; + if (options?.__binaryResponse) return response; + const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim(); + if (mediaType?.includes("application/json") || mediaType?.endsWith("+json")) { + if (response.headers.get("content-length") === "0") return; + return addRequestID(await response.clone().json(), response); + } + return await response.clone().text(); +} +/** +* Composes `middleware` around `fetchFn` and returns the entry point of the chain. +*/ +function applyMiddleware(fetchFn, middleware, options, client) { + let next = async ({ url, ...init }) => { + try { + return await fetchFn.call(void 0, url, init); + } catch (err) { + const error = castToError(err); + fetchOriginErrors.add(error); + throw error; + } + }; + const ctx = createMiddlewareContext(options, client); + for (let i = middleware.length - 1; i >= 0; i--) { + const mw = middleware[i]; + const nextInner = next; + next = async (request) => mw(request, nextInner, ctx); + } + return next; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/core/api-promise.mjs +var _APIPromise_client; +/** +* A subclass of `Promise` providing additional helper methods +* for interacting with the SDK. +*/ +var APIPromise = class APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { + data, + response, + request_id: response.headers.get("request-id") + }; + } + parse() { + if (!this.parsedPromise) this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + 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); + } +}; +_APIPromise_client = /* @__PURE__ */ new WeakMap(); +//#endregion +//#region node_modules/@anthropic-ai/sdk/core/pagination.mjs +var _AbstractPage_client; +var 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() { + if (!this.getPaginatedItems().length) return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + 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 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) for (const item of page.getPaginatedItems()) yield item; + } +}; +/** +* This subclass of Promise will resolve to an instantiated Page once the request completes. +* +* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: +* +* for await (const item of client.items.list()) { +* console.log(item) +* } +*/ +var PagePromise = class extends APIPromise { + constructor(client, request, Page) { + super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) yield item; + } +}; +var Page = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.first_id = body.first_id || null; + this.last_id = body.last_id || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) return false; + return super.hasNextPage(); + } + nextPageRequestOptions() { + if (this.options.query?.["before_id"]) { + const first_id = this.first_id; + if (!first_id) return null; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + before_id: first_id + } + }; + } + const cursor = this.last_id; + if (!cursor) return null; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after_id: cursor + } + }; + } +}; +var PageCursor = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.next_page = body.next_page || null; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_page; + if (!cursor) return null; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + page: cursor + } + }; + } +}; +var BidirectionalPageCursor = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.next_page = body.next_page || null; + this.prev_page = body.prev_page || null; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_page; + if (!cursor) return null; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + page: cursor + } + }; + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/uploads.mjs +var checkFileSupport = () => { + if (typeof File === "undefined") { + const { process } = globalThis; + const isOldNode = typeof process?.versions?.node === "string" && parseInt(process.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +/** +* Construct a `File` instance. This is used to ensure a helpful error is thrown +* for environments that don't define a global `File` yet. +*/ +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value, stripPath) { + const val = typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || ""; + return stripPath ? val.split(/[\\/]/).pop() || void 0 : val; +} +var isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; +var multipartFormRequestOptions = async (opts, fetch, stripFilenames = true) => { + return { + ...opts, + body: await createForm(opts.body, fetch, stripFilenames) + }; +}; +var supportsFormDataMap = /* @__PURE__ */ new WeakMap(); +/** +* node-fetch doesn't support the global FormData object in recent node versions. Instead of sending +* properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". +* This function detects if the fetch function provided supports the global FormData object to avoid +* confusing error messages later on. +*/ +function supportsFormData(fetchObject) { + const fetch = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap.get(fetch); + if (cached) return cached; + const promise = (async () => { + try { + const FetchResponse = "Response" in fetch ? fetch.Response : (await fetch("data:,")).constructor; + const data = new FormData(); + if (data.toString() === await new FetchResponse(data).text()) return false; + return true; + } catch { + return true; + } + })(); + supportsFormDataMap.set(fetch, promise); + return promise; +} +var createForm = async (body, fetch, stripFilenames = true) => { + if (!await supportsFormData(fetch)) throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, stripFilenames))); + return form; +}; +var isNamedBlob = (value) => value instanceof Blob && "name" in value; +var addFormValue = async (form, key, value, stripFilenames) => { + 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 (value instanceof Response) { + let options = {}; + const contentType = value.headers.get("Content-Type"); + if (contentType) options = { type: contentType }; + form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options)); + } else if (isAsyncIterable(value)) form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, stripFilenames))); + else if (isNamedBlob(value)) form.append(key, makeFile([value], getName(value, stripFilenames), { type: value.type })); + else if (Array.isArray(value)) await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry, stripFilenames))); + else if (typeof value === "object") await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, stripFilenames))); + else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/to-file.mjs +/** +* This check adds the arrayBuffer() method type because it is available and used at runtime +*/ +var 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"; +/** +* This check adds the arrayBuffer() method type because it is available and used at runtime +*/ +var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); +var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; +/** +* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats +* @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts +* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible +* @param {Object=} options additional properties +* @param {string=} options.type the MIME type of the content +* @param {number=} options.lastModified the last modified timestamp +* @returns a {@link File} with the given properties +*/ +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + name || (name = getName(value, true)); + if (isFileLike(value)) { + if (value instanceof File && name == null && options == null) return value; + return makeFile([await value.arrayBuffer()], name ?? value.name, { + type: value.type, + lastModified: value.lastModified, + ...options + }); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") options = { + ...options, + type + }; + } + return makeFile(parts, name, 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(value instanceof Blob ? value : await value.arrayBuffer()); + else if (isAsyncIterable(value)) for await (const chunk of value) parts.push(...await getBytes(chunk)); + else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) return ""; + return `; props: [${Object.getOwnPropertyNames(value).map((p) => `"${p}"`).join(", ")}]`; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/core/resource.mjs +var APIResource = class { + constructor(client) { + this._client = client; + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/headers.mjs +var brand_privateNullableHeaders = Symbol.for("brand.privateNullableHeaders"); +function* iterateHeaders(headers) { + if (!headers) return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) yield [name, null]; + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) iter = headers.entries(); + else if (isReadonlyArray(headers)) iter = headers; + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, clearSentinel]; + } + yield [name, value]; + } + } +} +/** Distinguishes iterateHeaders' synthetic clear-before-set from a user `null`. */ +var clearSentinel = Symbol("clear"); +/** +* Headers whose values accumulate across {@link buildHeaders} sources instead +* of the later source's value replacing the earlier one. Values are +* comma-appended (deduplicated, order-preserving) into a single header line. +*/ +var APPEND_HEADERS = /* @__PURE__ */ new Set(["x-stainless-helper"]); +var appendHeaderValue = (existing, addition) => { + const tokens = existing ? existing.split(",").map((t) => t.trim()).filter(Boolean) : []; + for (const tok of addition.split(",").map((t) => t.trim())) if (tok && !tokens.includes(tok)) tokens.push(tok); + return tokens.join(", "); +}; +var buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (APPEND_HEADERS.has(lowerName)) { + if (value === clearSentinel) continue; + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.set(name, appendHeaderValue(targetHeaders.get(name), value)); + nullHeaders.delete(lowerName); + } + continue; + } + if (value === clearSentinel || !seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + if (value === clearSentinel) continue; + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { + [brand_privateNullableHeaders]: true, + values: targetHeaders, + nulls: nullHeaders + }; +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/path.mjs +/** +* Percent-encode everything that isn't safe to have in a path without encoding safe chars. +* +* Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: +* > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" +* > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" +* > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" +*/ +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { + if (statics.length === 1) return statics[0]; + let postPath = false; + const invalidSegments = []; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) postPath = true; + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter` + }); + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments.map((e) => e.error).join("\n")}\n${path}\n${underline}`); + } + return path; +}; +/** +* URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. +*/ +var path$2 = /* @__PURE__ */ createPathTagFunction(encodeURIPath); +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/deployment-runs.mjs +var DeploymentRuns = class extends APIResource { + /** + * Get Deployment Run + * + * @example + * ```ts + * const betaManagedAgentsDeploymentRun = + * await client.beta.deploymentRuns.retrieve( + * 'deployment_run_id', + * ); + * ``` + */ + retrieve(deploymentRunID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/deployment_runs/${deploymentRunID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * List Deployment Runs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsDeploymentRun of client.beta.deploymentRuns.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/deployment_runs?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/deployments.mjs +var Deployments = class extends APIResource { + /** + * Create Deployment + * + * @example + * ```ts + * const betaManagedAgentsDeployment = + * await client.beta.deployments.create({ + * agent: 'string', + * environment_id: 'x', + * initial_events: [ + * { + * content: [ + * { + * text: 'Where is my order #1234?', + * type: 'text', + * }, + * ], + * type: 'user.message', + * }, + * ], + * name: 'x', + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/deployments?beta=true", { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Get Deployment + * + * @example + * ```ts + * const betaManagedAgentsDeployment = + * await client.beta.deployments.retrieve( + * 'depl_011CZkZcDH3vPqd7xnEfwTai', + * ); + * ``` + */ + retrieve(deploymentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/deployments/${deploymentID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Update Deployment + * + * @example + * ```ts + * const betaManagedAgentsDeployment = + * await client.beta.deployments.update( + * 'depl_011CZkZcDH3vPqd7xnEfwTai', + * ); + * ``` + */ + update(deploymentID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/deployments/${deploymentID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * List Deployments + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsDeployment of client.beta.deployments.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/deployments?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Archive Deployment + * + * @example + * ```ts + * const betaManagedAgentsDeployment = + * await client.beta.deployments.archive( + * 'depl_011CZkZcDH3vPqd7xnEfwTai', + * ); + * ``` + */ + archive(deploymentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/deployments/${deploymentID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Pause Deployment + * + * @example + * ```ts + * const betaManagedAgentsDeployment = + * await client.beta.deployments.pause( + * 'depl_011CZkZcDH3vPqd7xnEfwTai', + * ); + * ``` + */ + pause(deploymentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/deployments/${deploymentID}/pause?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Run Deployment Now + * + * @example + * ```ts + * const betaManagedAgentsDeploymentRun = + * await client.beta.deployments.run( + * 'depl_011CZkZcDH3vPqd7xnEfwTai', + * ); + * ``` + */ + run(deploymentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/deployments/${deploymentID}/run?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Unpause Deployment + * + * @example + * ```ts + * const betaManagedAgentsDeployment = + * await client.beta.deployments.unpause( + * 'depl_011CZkZcDH3vPqd7xnEfwTai', + * ); + * ``` + */ + unpause(deploymentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/deployments/${deploymentID}/unpause?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/dreams.mjs +var Dreams = class extends APIResource { + /** + * Create a Dream + * + * @example + * ```ts + * const betaDream = await client.beta.dreams.create({ + * inputs: [{ memory_store_id: 'x', type: 'memory_store' }], + * model: 'string', + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/dreams?beta=true", { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) + }); + } + /** + * Get a Dream + * + * @example + * ```ts + * const betaDream = await client.beta.dreams.retrieve( + * 'dream_id', + * ); + * ``` + */ + retrieve(dreamID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/dreams/${dreamID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) + }); + } + /** + * List Dreams + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaDream of client.beta.dreams.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/dreams?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) + }); + } + /** + * Archive a Dream + * + * @example + * ```ts + * const betaDream = await client.beta.dreams.archive( + * 'dream_id', + * ); + * ``` + */ + archive(dreamID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/dreams/${dreamID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) + }); + } + /** + * Cancel a Dream + * + * @example + * ```ts + * const betaDream = await client.beta.dreams.cancel( + * 'dream_id', + * ); + * ``` + */ + cancel(dreamID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/dreams/${dreamID}/cancel?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/stainless-helper-header.mjs +/** +* Single source of truth for the `x-stainless-helper` telemetry header — the +* key, the closed value vocabulary, and per-object helper tagging. The +* append-don't-clobber merge for the header itself lives in +* {@link import('../internal/headers').buildHeaders} via `APPEND_HEADERS`. +*/ +/** +* Telemetry header naming the SDK helper(s) a request came from. Always this +* lowercase form; `buildHeaders` matches it case-insensitively for its append +* semantics, but a single canonical casing keeps every call site greppable. +*/ +var STAINLESS_HELPER_HEADER = "x-stainless-helper"; +/** Telemetry header naming the SDK method (e.g. `stream`) in use. */ +var STAINLESS_HELPER_METHOD_HEADER = "x-stainless-helper-method"; +/** +* The `{ 'x-stainless-helper': value }` header dict, for passing into +* `buildHeaders` (which comma-appends `x-stainless-helper` across sources) +* or as `defaultHeaders`/per-request `headers`. +*/ +function helperHeader(value) { + return { [STAINLESS_HELPER_HEADER]: value }; +} +/** +* Symbol used to mark objects created by SDK helpers for tracking. +* The value is the helper name (e.g., 'mcpTool', 'betaZodTool'). +*/ +var SDK_HELPER_SYMBOL = Symbol("anthropic.sdk.stainlessHelper"); +function wasCreatedByStainlessHelper(value) { + return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL in value; +} +/** +* Collects helper names from tools and messages arrays. +* Returns a deduplicated array of helper names found. +*/ +function collectStainlessHelpers(tools, messages) { + const helpers = /* @__PURE__ */ new Set(); + if (tools) { + for (const tool of tools) if (wasCreatedByStainlessHelper(tool)) helpers.add(tool[SDK_HELPER_SYMBOL]); + } + if (messages) for (const message of messages) { + if (wasCreatedByStainlessHelper(message)) helpers.add(message[SDK_HELPER_SYMBOL]); + const content = message.content; + if (Array.isArray(content)) { + for (const block of content) if (wasCreatedByStainlessHelper(block)) helpers.add(block[SDK_HELPER_SYMBOL]); + } + } + return Array.from(helpers); +} +/** +* Builds x-stainless-helper header value from tools and messages. +* Returns an empty object if no helpers are found. +*/ +function stainlessHelperHeader(tools, messages) { + const helpers = collectStainlessHelpers(tools, messages); + if (helpers.length === 0) return {}; + return { [STAINLESS_HELPER_HEADER]: helpers.join(", ") }; +} +/** +* Builds x-stainless-helper header value from a file object. +* Returns an empty object if the file is not marked with a helper. +*/ +function stainlessHelperHeaderFromFile(file) { + if (wasCreatedByStainlessHelper(file)) return { [STAINLESS_HELPER_HEADER]: file[SDK_HELPER_SYMBOL] }; + return {}; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/files.mjs +var Files = class extends APIResource { + /** + * List Files + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fileMetadata of client.beta.files.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/files?beta=true", Page, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, options?.headers]) + }); + } + /** + * Delete File + * + * @example + * ```ts + * const deletedFile = await client.beta.files.delete( + * 'file_id', + * ); + * ``` + */ + delete(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path$2`/v1/files/${fileID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, options?.headers]) + }); + } + /** + * Download File + * + * @example + * ```ts + * const response = await client.beta.files.download( + * 'file_id', + * ); + * + * const content = await response.blob(); + * console.log(content); + * ``` + */ + download(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/files/${fileID}/content?beta=true`, { + ...options, + headers: buildHeaders([{ + "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(), + Accept: "application/binary" + }, options?.headers]), + __binaryResponse: true + }); + } + /** + * Get File Metadata + * + * @example + * ```ts + * const fileMetadata = + * await client.beta.files.retrieveMetadata('file_id'); + * ``` + */ + retrieveMetadata(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/files/${fileID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, options?.headers]) + }); + } + /** + * Upload File + * + * @example + * ```ts + * const fileMetadata = await client.beta.files.upload({ + * file: fs.createReadStream('path/to/file'), + * }); + * ``` + */ + upload(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/files?beta=true", multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, + stainlessHelperHeaderFromFile(body.file), + options?.headers + ]) + }, this._client)); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/models.mjs +var Models$1 = class extends APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + * + * @example + * ```ts + * const betaModelInfo = await client.beta.models.retrieve( + * 'model_id', + * ); + * ``` + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/models/${modelID}?beta=true`, { + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]) + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaModelInfo of client.beta.models.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/models?beta=true", Page, { + query, + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/user-profiles.mjs +var UserProfiles = class extends APIResource { + /** + * Create User Profile + * + * @example + * ```ts + * const betaUserProfile = + * await client.beta.userProfiles.create(); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/user_profiles?beta=true", { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) + }); + } + /** + * Get User Profile + * + * @example + * ```ts + * const betaUserProfile = + * await client.beta.userProfiles.retrieve( + * 'uprof_011CZkZCu8hGbp5mYRQgUmz9', + * ); + * ``` + */ + retrieve(userProfileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/user_profiles/${userProfileID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) + }); + } + /** + * Update User Profile + * + * @example + * ```ts + * const betaUserProfile = + * await client.beta.userProfiles.update( + * 'uprof_011CZkZCu8hGbp5mYRQgUmz9', + * ); + * ``` + */ + update(userProfileID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/user_profiles/${userProfileID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) + }); + } + /** + * List User Profiles + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaUserProfile of client.beta.userProfiles.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/user_profiles?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) + }); + } + /** + * Create Enrollment URL + * + * @example + * ```ts + * const betaUserProfileEnrollmentURL = + * await client.beta.userProfiles.createEnrollmentURL( + * 'uprof_011CZkZCu8hGbp5mYRQgUmz9', + * ); + * ``` + */ + createEnrollmentURL(userProfileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/user_profiles/${userProfileID}/enrollment_url?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/standardwebhooks/dist/timing_safe_equal.js +var require_timing_safe_equal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.timingSafeEqual = void 0; + function assert(expr, msg = "") { + if (!expr) throw new Error(msg); + } + function timingSafeEqual(a, b) { + if (a.byteLength !== b.byteLength) return false; + if (!(a instanceof DataView)) a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a); + if (!(b instanceof DataView)) b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b); + assert(a instanceof DataView); + assert(b instanceof DataView); + const length = a.byteLength; + let out = 0; + let i = -1; + while (++i < length) out |= a.getUint8(i) ^ b.getUint8(i); + return out === 0; + } + exports.timingSafeEqual = timingSafeEqual; +})); +//#endregion +//#region node_modules/@stablelib/base64/lib/base64.js +var require_base64 = /* @__PURE__ */ __commonJSMin(((exports) => { + var __extends = exports && exports.__extends || (function() { + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) { + d.__proto__ = b; + } || function(d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + }; + return extendStatics(d, b); + }; + return function(d, b) { + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + /** + * Package base64 implements Base64 encoding and decoding. + */ + var INVALID_BYTE = 256; + /** + * Implements standard Base64 encoding. + * + * Operates in constant time. + */ + var Coder = function() { + function Coder(_paddingCharacter) { + if (_paddingCharacter === void 0) _paddingCharacter = "="; + this._paddingCharacter = _paddingCharacter; + } + Coder.prototype.encodedLength = function(length) { + if (!this._paddingCharacter) return (length * 8 + 5) / 6 | 0; + return (length + 2) / 3 * 4 | 0; + }; + Coder.prototype.encode = function(data) { + var out = ""; + var i = 0; + for (; i < data.length - 2; i += 3) { + var c = data[i] << 16 | data[i + 1] << 8 | data[i + 2]; + out += this._encodeByte(c >>> 18 & 63); + out += this._encodeByte(c >>> 12 & 63); + out += this._encodeByte(c >>> 6 & 63); + out += this._encodeByte(c >>> 0 & 63); + } + var left = data.length - i; + if (left > 0) { + var c = data[i] << 16 | (left === 2 ? data[i + 1] << 8 : 0); + out += this._encodeByte(c >>> 18 & 63); + out += this._encodeByte(c >>> 12 & 63); + if (left === 2) out += this._encodeByte(c >>> 6 & 63); + else out += this._paddingCharacter || ""; + out += this._paddingCharacter || ""; + } + return out; + }; + Coder.prototype.maxDecodedLength = function(length) { + if (!this._paddingCharacter) return (length * 6 + 7) / 8 | 0; + return length / 4 * 3 | 0; + }; + Coder.prototype.decodedLength = function(s) { + return this.maxDecodedLength(s.length - this._getPaddingLength(s)); + }; + Coder.prototype.decode = function(s) { + if (s.length === 0) return /* @__PURE__ */ new Uint8Array(0); + var paddingLength = this._getPaddingLength(s); + var length = s.length - paddingLength; + var out = new Uint8Array(this.maxDecodedLength(length)); + var op = 0; + var i = 0; + var haveBad = 0; + var v0 = 0, v1 = 0, v2 = 0, v3 = 0; + for (; i < length - 4; i += 4) { + v0 = this._decodeChar(s.charCodeAt(i + 0)); + v1 = this._decodeChar(s.charCodeAt(i + 1)); + v2 = this._decodeChar(s.charCodeAt(i + 2)); + v3 = this._decodeChar(s.charCodeAt(i + 3)); + out[op++] = v0 << 2 | v1 >>> 4; + out[op++] = v1 << 4 | v2 >>> 2; + out[op++] = v2 << 6 | v3; + haveBad |= v0 & INVALID_BYTE; + haveBad |= v1 & INVALID_BYTE; + haveBad |= v2 & INVALID_BYTE; + haveBad |= v3 & INVALID_BYTE; + } + if (i < length - 1) { + v0 = this._decodeChar(s.charCodeAt(i)); + v1 = this._decodeChar(s.charCodeAt(i + 1)); + out[op++] = v0 << 2 | v1 >>> 4; + haveBad |= v0 & INVALID_BYTE; + haveBad |= v1 & INVALID_BYTE; + } + if (i < length - 2) { + v2 = this._decodeChar(s.charCodeAt(i + 2)); + out[op++] = v1 << 4 | v2 >>> 2; + haveBad |= v2 & INVALID_BYTE; + } + if (i < length - 3) { + v3 = this._decodeChar(s.charCodeAt(i + 3)); + out[op++] = v2 << 6 | v3; + haveBad |= v3 & INVALID_BYTE; + } + if (haveBad !== 0) throw new Error("Base64Coder: incorrect characters for decoding"); + return out; + }; + Coder.prototype._encodeByte = function(b) { + var result = b; + result += 65; + result += 25 - b >>> 8 & 6; + result += 51 - b >>> 8 & -75; + result += 61 - b >>> 8 & -15; + result += 62 - b >>> 8 & 3; + return String.fromCharCode(result); + }; + Coder.prototype._decodeChar = function(c) { + var result = INVALID_BYTE; + result += (42 - c & c - 44) >>> 8 & -INVALID_BYTE + c - 43 + 62; + result += (46 - c & c - 48) >>> 8 & -INVALID_BYTE + c - 47 + 63; + result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52; + result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0; + result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26; + return result; + }; + Coder.prototype._getPaddingLength = function(s) { + var paddingLength = 0; + if (this._paddingCharacter) { + for (var i = s.length - 1; i >= 0; i--) { + if (s[i] !== this._paddingCharacter) break; + paddingLength++; + } + if (s.length < 4 || paddingLength > 2) throw new Error("Base64Coder: incorrect padding"); + } + return paddingLength; + }; + return Coder; + }(); + exports.Coder = Coder; + var stdCoder = new Coder(); + function encode(data) { + return stdCoder.encode(data); + } + exports.encode = encode; + function decode(s) { + return stdCoder.decode(s); + } + exports.decode = decode; + /** + * Implements URL-safe Base64 encoding. + * (Same as Base64, but '+' is replaced with '-', and '/' with '_'). + * + * Operates in constant time. + */ + var URLSafeCoder = function(_super) { + __extends(URLSafeCoder, _super); + function URLSafeCoder() { + return _super !== null && _super.apply(this, arguments) || this; + } + URLSafeCoder.prototype._encodeByte = function(b) { + var result = b; + result += 65; + result += 25 - b >>> 8 & 6; + result += 51 - b >>> 8 & -75; + result += 61 - b >>> 8 & -13; + result += 62 - b >>> 8 & 49; + return String.fromCharCode(result); + }; + URLSafeCoder.prototype._decodeChar = function(c) { + var result = INVALID_BYTE; + result += (44 - c & c - 46) >>> 8 & -INVALID_BYTE + c - 45 + 62; + result += (94 - c & c - 96) >>> 8 & -INVALID_BYTE + c - 95 + 63; + result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52; + result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0; + result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26; + return result; + }; + return URLSafeCoder; + }(Coder); + exports.URLSafeCoder = URLSafeCoder; + var urlSafeCoder = new URLSafeCoder(); + function encodeURLSafe(data) { + return urlSafeCoder.encode(data); + } + exports.encodeURLSafe = encodeURLSafe; + function decodeURLSafe(s) { + return urlSafeCoder.decode(s); + } + exports.decodeURLSafe = decodeURLSafe; + exports.encodedLength = function(length) { + return stdCoder.encodedLength(length); + }; + exports.maxDecodedLength = function(length) { + return stdCoder.maxDecodedLength(length); + }; + exports.decodedLength = function(s) { + return stdCoder.decodedLength(s); + }; +})); +//#endregion +//#region node_modules/fast-sha256/sha256.js +var require_sha256 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + (function(root, factory) { + var exports$1 = {}; + factory(exports$1); + var sha256 = exports$1["default"]; + for (var k in exports$1) sha256[k] = exports$1[k]; + if (typeof module === "object" && typeof module.exports === "object") module.exports = sha256; + else if (typeof define === "function" && define.amd) define(function() { + return sha256; + }); + else root.sha256 = sha256; + })(exports, function(exports$2) { + "use strict"; + exports$2.__esModule = true; + exports$2.digestLength = 32; + exports$2.blockSize = 64; + var K = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + function hashBlocks(w, v, p, pos, len) { + var a, b, c, d, e, f, g, h, u, i, j, t1, t2; + while (len >= 64) { + a = v[0]; + b = v[1]; + c = v[2]; + d = v[3]; + e = v[4]; + f = v[5]; + g = v[6]; + h = v[7]; + for (i = 0; i < 16; i++) { + j = pos + i * 4; + w[i] = (p[j] & 255) << 24 | (p[j + 1] & 255) << 16 | (p[j + 2] & 255) << 8 | p[j + 3] & 255; + } + for (i = 16; i < 64; i++) { + u = w[i - 2]; + t1 = (u >>> 17 | u << 15) ^ (u >>> 19 | u << 13) ^ u >>> 10; + u = w[i - 15]; + t2 = (u >>> 7 | u << 25) ^ (u >>> 18 | u << 14) ^ u >>> 3; + w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0); + } + for (i = 0; i < 64; i++) { + t1 = (((e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7)) + (e & f ^ ~e & g) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0; + t2 = ((a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10)) + (a & b ^ a & c ^ b & c) | 0; + h = g; + g = f; + f = e; + e = d + t1 | 0; + d = c; + c = b; + b = a; + a = t1 + t2 | 0; + } + v[0] += a; + v[1] += b; + v[2] += c; + v[3] += d; + v[4] += e; + v[5] += f; + v[6] += g; + v[7] += h; + pos += 64; + len -= 64; + } + return pos; + } + var Hash = function() { + function Hash() { + this.digestLength = exports$2.digestLength; + this.blockSize = exports$2.blockSize; + this.state = /* @__PURE__ */ new Int32Array(8); + this.temp = /* @__PURE__ */ new Int32Array(64); + this.buffer = /* @__PURE__ */ new Uint8Array(128); + this.bufferLength = 0; + this.bytesHashed = 0; + this.finished = false; + this.reset(); + } + Hash.prototype.reset = function() { + this.state[0] = 1779033703; + this.state[1] = 3144134277; + this.state[2] = 1013904242; + this.state[3] = 2773480762; + this.state[4] = 1359893119; + this.state[5] = 2600822924; + this.state[6] = 528734635; + this.state[7] = 1541459225; + this.bufferLength = 0; + this.bytesHashed = 0; + this.finished = false; + return this; + }; + Hash.prototype.clean = function() { + for (var i = 0; i < this.buffer.length; i++) this.buffer[i] = 0; + for (var i = 0; i < this.temp.length; i++) this.temp[i] = 0; + this.reset(); + }; + Hash.prototype.update = function(data, dataLength) { + if (dataLength === void 0) dataLength = data.length; + if (this.finished) throw new Error("SHA256: can't update because hash was finished."); + var dataPos = 0; + this.bytesHashed += dataLength; + if (this.bufferLength > 0) { + while (this.bufferLength < 64 && dataLength > 0) { + this.buffer[this.bufferLength++] = data[dataPos++]; + dataLength--; + } + if (this.bufferLength === 64) { + hashBlocks(this.temp, this.state, this.buffer, 0, 64); + this.bufferLength = 0; + } + } + if (dataLength >= 64) { + dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength); + dataLength %= 64; + } + while (dataLength > 0) { + this.buffer[this.bufferLength++] = data[dataPos++]; + dataLength--; + } + return this; + }; + Hash.prototype.finish = function(out) { + if (!this.finished) { + var bytesHashed = this.bytesHashed; + var left = this.bufferLength; + var bitLenHi = bytesHashed / 536870912 | 0; + var bitLenLo = bytesHashed << 3; + var padLength = bytesHashed % 64 < 56 ? 64 : 128; + this.buffer[left] = 128; + for (var i = left + 1; i < padLength - 8; i++) this.buffer[i] = 0; + this.buffer[padLength - 8] = bitLenHi >>> 24 & 255; + this.buffer[padLength - 7] = bitLenHi >>> 16 & 255; + this.buffer[padLength - 6] = bitLenHi >>> 8 & 255; + this.buffer[padLength - 5] = bitLenHi >>> 0 & 255; + this.buffer[padLength - 4] = bitLenLo >>> 24 & 255; + this.buffer[padLength - 3] = bitLenLo >>> 16 & 255; + this.buffer[padLength - 2] = bitLenLo >>> 8 & 255; + this.buffer[padLength - 1] = bitLenLo >>> 0 & 255; + hashBlocks(this.temp, this.state, this.buffer, 0, padLength); + this.finished = true; + } + for (var i = 0; i < 8; i++) { + out[i * 4 + 0] = this.state[i] >>> 24 & 255; + out[i * 4 + 1] = this.state[i] >>> 16 & 255; + out[i * 4 + 2] = this.state[i] >>> 8 & 255; + out[i * 4 + 3] = this.state[i] >>> 0 & 255; + } + return this; + }; + Hash.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + Hash.prototype._saveState = function(out) { + for (var i = 0; i < this.state.length; i++) out[i] = this.state[i]; + }; + Hash.prototype._restoreState = function(from, bytesHashed) { + for (var i = 0; i < this.state.length; i++) this.state[i] = from[i]; + this.bytesHashed = bytesHashed; + this.finished = false; + this.bufferLength = 0; + }; + return Hash; + }(); + exports$2.Hash = Hash; + var HMAC = function() { + function HMAC(key) { + this.inner = new Hash(); + this.outer = new Hash(); + this.blockSize = this.inner.blockSize; + this.digestLength = this.inner.digestLength; + var pad = new Uint8Array(this.blockSize); + if (key.length > this.blockSize) new Hash().update(key).finish(pad).clean(); + else for (var i = 0; i < key.length; i++) pad[i] = key[i]; + for (var i = 0; i < pad.length; i++) pad[i] ^= 54; + this.inner.update(pad); + for (var i = 0; i < pad.length; i++) pad[i] ^= 106; + this.outer.update(pad); + this.istate = /* @__PURE__ */ new Uint32Array(8); + this.ostate = /* @__PURE__ */ new Uint32Array(8); + this.inner._saveState(this.istate); + this.outer._saveState(this.ostate); + for (var i = 0; i < pad.length; i++) pad[i] = 0; + } + HMAC.prototype.reset = function() { + this.inner._restoreState(this.istate, this.inner.blockSize); + this.outer._restoreState(this.ostate, this.outer.blockSize); + return this; + }; + HMAC.prototype.clean = function() { + for (var i = 0; i < this.istate.length; i++) this.ostate[i] = this.istate[i] = 0; + this.inner.clean(); + this.outer.clean(); + }; + HMAC.prototype.update = function(data) { + this.inner.update(data); + return this; + }; + HMAC.prototype.finish = function(out) { + if (this.outer.finished) this.outer.finish(out); + else { + this.inner.finish(out); + this.outer.update(out, this.digestLength).finish(out); + } + return this; + }; + HMAC.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + return HMAC; + }(); + exports$2.HMAC = HMAC; + function hash(data) { + var h = new Hash().update(data); + var digest = h.digest(); + h.clean(); + return digest; + } + exports$2.hash = hash; + exports$2["default"] = hash; + function hmac(key, data) { + var h = new HMAC(key).update(data); + var digest = h.digest(); + h.clean(); + return digest; + } + exports$2.hmac = hmac; + function fillBuffer(buffer, hmac, info, counter) { + var num = counter[0]; + if (num === 0) throw new Error("hkdf: cannot expand more"); + hmac.reset(); + if (num > 1) hmac.update(buffer); + if (info) hmac.update(info); + hmac.update(counter); + hmac.finish(buffer); + counter[0]++; + } + var hkdfSalt = new Uint8Array(exports$2.digestLength); + function hkdf(key, salt, info, length) { + if (salt === void 0) salt = hkdfSalt; + if (length === void 0) length = 32; + var counter = new Uint8Array([1]); + var hmac_ = new HMAC(hmac(salt, key)); + var buffer = new Uint8Array(hmac_.digestLength); + var bufpos = buffer.length; + var out = new Uint8Array(length); + for (var i = 0; i < length; i++) { + if (bufpos === buffer.length) { + fillBuffer(buffer, hmac_, info, counter); + bufpos = 0; + } + out[i] = buffer[bufpos++]; + } + hmac_.clean(); + buffer.fill(0); + counter.fill(0); + return out; + } + exports$2.hkdf = hkdf; + function pbkdf2(password, salt, iterations, dkLen) { + var prf = new HMAC(password); + var len = prf.digestLength; + var ctr = /* @__PURE__ */ new Uint8Array(4); + var t = new Uint8Array(len); + var u = new Uint8Array(len); + var dk = new Uint8Array(dkLen); + for (var i = 0; i * len < dkLen; i++) { + var c = i + 1; + ctr[0] = c >>> 24 & 255; + ctr[1] = c >>> 16 & 255; + ctr[2] = c >>> 8 & 255; + ctr[3] = c >>> 0 & 255; + prf.reset(); + prf.update(salt); + prf.update(ctr); + prf.finish(u); + for (var j = 0; j < len; j++) t[j] = u[j]; + for (var j = 2; j <= iterations; j++) { + prf.reset(); + prf.update(u).finish(u); + for (var k = 0; k < len; k++) t[k] ^= u[k]; + } + for (var j = 0; j < len && i * len + j < dkLen; j++) dk[i * len + j] = t[j]; + } + for (var i = 0; i < len; i++) t[i] = u[i] = 0; + for (var i = 0; i < 4; i++) ctr[i] = 0; + prf.clean(); + return dk; + } + exports$2.pbkdf2 = pbkdf2; + }); +})); +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/webhooks.mjs +var import_dist = (/* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Webhook = exports.WebhookVerificationError = void 0; + var timing_safe_equal_1 = require_timing_safe_equal(); + var base64 = require_base64(); + var sha256 = require_sha256(); + var WEBHOOK_TOLERANCE_IN_SECONDS = 300; + var ExtendableError = class ExtendableError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, ExtendableError.prototype); + this.name = "ExtendableError"; + this.stack = new Error(message).stack; + } + }; + var WebhookVerificationError = class WebhookVerificationError extends ExtendableError { + constructor(message) { + super(message); + Object.setPrototypeOf(this, WebhookVerificationError.prototype); + this.name = "WebhookVerificationError"; + } + }; + exports.WebhookVerificationError = WebhookVerificationError; + var Webhook = class Webhook { + constructor(secret, options) { + if (!secret) throw new Error("Secret can't be empty."); + if ((options === null || options === void 0 ? void 0 : options.format) === "raw") if (secret instanceof Uint8Array) this.key = secret; + else this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0)); + else { + if (typeof secret !== "string") throw new Error("Expected secret to be of type string"); + if (secret.startsWith(Webhook.prefix)) secret = secret.substring(Webhook.prefix.length); + this.key = base64.decode(secret); + } + } + verify(payload, headers_) { + const headers = {}; + for (const key of Object.keys(headers_)) headers[key.toLowerCase()] = headers_[key]; + const msgId = headers["webhook-id"]; + const msgSignature = headers["webhook-signature"]; + const msgTimestamp = headers["webhook-timestamp"]; + if (!msgSignature || !msgId || !msgTimestamp) throw new WebhookVerificationError("Missing required headers"); + const timestamp = this.verifyTimestamp(msgTimestamp); + const expectedSignature = this.sign(msgId, timestamp, payload).split(",")[1]; + const passedSignatures = msgSignature.split(" "); + const encoder = new globalThis.TextEncoder(); + for (const versionedSignature of passedSignatures) { + const [version, signature] = versionedSignature.split(","); + if (version !== "v1") continue; + if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) return JSON.parse(payload.toString()); + } + throw new WebhookVerificationError("No matching signature found"); + } + sign(msgId, timestamp, payload) { + if (typeof payload === "string") {} else if (payload.constructor.name === "Buffer") payload = payload.toString(); + else throw new Error("Expected payload to be of type string or Buffer."); + const encoder = new TextEncoder(); + const timestampNumber = Math.floor(timestamp.getTime() / 1e3); + const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`); + return `v1,${base64.encode(sha256.hmac(this.key, toSign))}`; + } + verifyTimestamp(timestampHeader) { + const now = Math.floor(Date.now() / 1e3); + const timestamp = parseInt(timestampHeader, 10); + if (isNaN(timestamp)) throw new WebhookVerificationError("Invalid Signature Headers"); + if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) throw new WebhookVerificationError("Message timestamp too old"); + if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) throw new WebhookVerificationError("Message timestamp too new"); + return /* @__PURE__ */ new Date(timestamp * 1e3); + } + }; + exports.Webhook = Webhook; + Webhook.prefix = "whsec_"; +})))(); +var Webhooks = class extends APIResource { + unwrap(body, { headers, key }) { + if (headers !== void 0) { + const keyStr = key === void 0 ? this._client.webhookKey : key; + if (keyStr === null) throw new Error("Webhook key must not be null in order to unwrap"); + new import_dist.Webhook(keyStr).verify(body, headers); + } + return JSON.parse(body); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/agents/versions.mjs +var Versions$1 = class extends APIResource { + /** + * List Agent Versions + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsAgent of client.beta.agents.versions.list( + * 'agent_011CZkYpogX7uDKUyvBTophP', + * )) { + * // ... + * } + * ``` + */ + list(agentID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/agents/${agentID}/versions?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/agents/agents.mjs +var Agents = class extends APIResource { + constructor() { + super(...arguments); + this.versions = new Versions$1(this._client); + } + /** + * Create Agent + * + * @example + * ```ts + * const betaManagedAgentsAgent = + * await client.beta.agents.create({ + * model: 'claude-sonnet-4-6', + * name: 'My First Agent', + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/agents?beta=true", { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Get Agent + * + * @example + * ```ts + * const betaManagedAgentsAgent = + * await client.beta.agents.retrieve( + * 'agent_011CZkYpogX7uDKUyvBTophP', + * ); + * ``` + */ + retrieve(agentID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.get(path$2`/v1/agents/${agentID}?beta=true`, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Update Agent + * + * @example + * ```ts + * const betaManagedAgentsAgent = + * await client.beta.agents.update( + * 'agent_011CZkYpogX7uDKUyvBTophP', + * { description: 'updated' }, + * ); + * ``` + */ + update(agentID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/agents/${agentID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * List Agents + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsAgent of client.beta.agents.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/agents?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Archive Agent + * + * @example + * ```ts + * const betaManagedAgentsAgent = + * await client.beta.agents.archive( + * 'agent_011CZkYpogX7uDKUyvBTophP', + * ); + * ``` + */ + archive(agentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/agents/${agentID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +Agents.Versions = Versions$1; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/abort.mjs +/** +* Chain an external {@link AbortSignal} into a local {@link AbortController}: +* the controller aborts whenever `external` aborts (synchronously if it is +* already aborted). +* +* Returns a cleanup function that detaches the listener. Callers MUST invoke it +* on their normal teardown path — `{ once: true }` only removes the listener if +* abort actually fires, so a long-lived `external` signal (e.g. a daemon-wide +* signal reused across many short-lived controllers) would otherwise leak one +* listener per controller. +*/ +function linkAbort(external, controller) { + if (!external) return () => {}; + if (external.aborted) { + controller.abort(); + return () => {}; + } + const onAbort = () => controller.abort(); + external.addEventListener("abort", onAbort); + return () => external.removeEventListener("abort", onAbort); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/backoff.mjs +/** True when `e` is an {@link APIError} whose HTTP status equals `code`. */ +function isStatus(e, code) { + return e instanceof APIError && e.status === code; +} +/** True when `e` is an {@link APIError} with a 4xx status. */ +function is4xx(e) { + return e instanceof APIError && typeof e.status === "number" && e.status >= 400 && e.status < 500; +} +/** +* True for a 4xx that the core client's retry policy would *not* retry, i.e. a +* permanent client error. 408 (request timeout), 409 (lock timeout) and 429 +* (rate limit) are retryable for the base client (`Anthropic.shouldRetry`), so +* they are not treated as fatal here — keeping helper retry behaviour aligned +* with the rest of the SDK. +*/ +function isFatal4xx(e) { + return is4xx(e) && !isStatus(e, 408) && !isStatus(e, 409) && !isStatus(e, 429); +} +/** Exponential backoff: `baseMs * 2 ** attempt`, clamped to `capMs`. */ +function backoff$1(attempt, baseMs, capMs) { + return Math.min(baseMs * 2 ** attempt, capMs); +} +/** Uniform random delay in the half-open interval `[lowMs, highMs)`. */ +function jitter(lowMs, highMs) { + return lowMs + Math.random() * (highMs - lowMs); +} +/** +* Trim up to 25% off `ms` at random so a fleet of clients backing off after a +* shared outage does not retry in lockstep — mirrors the jitter the core client +* applies to its own retry timeout. +*/ +function applyJitter(ms) { + return ms * (1 - Math.random() * .25); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/helper-client.mjs +/** +* Return a `withOptions()` clone of `client` set up for use *by* one of the +* runner helpers: authenticated with `authToken` as Bearer credentials, with +* the parent's `X-Api-Key` cleared, and tagged with the helper's +* `x-stainless-helper` value on every outgoing request. +* +* The returned sub-client inherits the parent's full configuration +* (`baseURL`, `timeout`, `maxRetries`, `fetch`, `fetchOptions`, custom +* `defaultHeaders`, `defaultQuery`). Overrides applied: +* +* - `authToken: authToken` — the new credential. +* - `apiKey: null` — the parent's `X-Api-Key` is cleared. `withOptions` +* inherits the parent's `apiKey` by default; without this, both +* `X-Api-Key` *and* `Authorization: Bearer …` would land on the wire. +* `client.ts` only triggers the env-var fallback when `apiKey === undefined`, +* so explicit `null` is honored. +* - `credentials: undefined` — opts the clone out of any inherited +* credentials/config/profile so the explicit bearer is the unambiguous auth. +* - `baseURL: client.baseURL` — pins the parent's resolved host (auth override otherwise resets it). +* - `defaultHeaders` is rebuilt as `parent._authState.extraHeaders ⊕ parent.defaultHeaders ⊕ +* {'x-stainless-helper': helper}`. `withOptions` *replaces* (does not +* merge) `defaultHeaders`, so we merge here so any custom headers the +* caller set on the parent client survive on the sub-client. +*/ +function copyClientForHelper(client, { authToken, helper }) { + if (!authToken) throw new AnthropicError(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(authToken)}`); + const internal = client; + const parentDefaults = internal._options.defaultHeaders; + const parentAuthExtraHeaders = internal._authState?.extraHeaders; + const defaultHeaders = buildHeaders([ + parentAuthExtraHeaders ? Object.fromEntries(Object.entries(parentAuthExtraHeaders).filter(([name]) => { + const lower = name.toLowerCase(); + return lower !== "authorization" && lower !== "x-api-key"; + })) : void 0, + parentDefaults, + { [STAINLESS_HELPER_HEADER]: helper } + ]); + return client.withOptions({ + apiKey: null, + authToken, + baseURL: client.baseURL, + credentials: void 0, + defaultHeaders + }); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/environments/poller.mjs +var _WorkPoller_runnerClient; +var _WorkPoller_consumed; +var _WorkPoller_controller; +var _WorkPoller_detachExternal; +var _WorkPoller_autoStop; +var _WorkPoller_drain; +var _WorkPoller_blockMs; +var _WorkPoller_reclaimOlderThanMs; +var _WorkPoller_requestOpts; +var POLL_BACKOFF_BASE_MS = 1e3; +var POLL_BACKOFF_CAP_MS = 6e4; +/** +* Async-iterable that long-polls a self-hosted environment for work, ack's +* each item, yields the {@link BetaSelfHostedWork} item, and posts `stop` after +* the consumer's loop body returns (or when the consumer `break`s). +* +* @example +* ```ts +* for await (const work of client.beta.environments.work.poller({ +* environmentId, +* environmentKey, +* })) { +* // ...service the work... +* } +* ``` +*/ +var WorkPoller = class { + constructor(opts) { + _WorkPoller_runnerClient.set(this, void 0); + _WorkPoller_consumed.set(this, false); + _WorkPoller_controller.set(this, void 0); + _WorkPoller_detachExternal.set(this, void 0); + _WorkPoller_autoStop.set(this, void 0); + _WorkPoller_drain.set(this, void 0); + _WorkPoller_blockMs.set(this, void 0); + _WorkPoller_reclaimOlderThanMs.set(this, void 0); + _WorkPoller_requestOpts.set(this, void 0); + this.client = opts.client; + this.environmentId = opts.environmentId; + this.environmentKey = opts.environmentKey; + this.workerId = opts.workerId ?? defaultWorkerId(); + __classPrivateFieldSet(this, _WorkPoller_runnerClient, copyClientForHelper(opts.client, { + authToken: opts.environmentKey, + helper: "environments-work-poller" + }), "f"); + __classPrivateFieldSet(this, _WorkPoller_autoStop, opts.autoStop ?? true, "f"); + __classPrivateFieldSet(this, _WorkPoller_drain, opts.drain ?? false, "f"); + __classPrivateFieldSet(this, _WorkPoller_blockMs, opts.blockMs === void 0 ? 999 : opts.blockMs, "f"); + __classPrivateFieldSet(this, _WorkPoller_reclaimOlderThanMs, opts.reclaimOlderThanMs ?? null, "f"); + __classPrivateFieldSet(this, _WorkPoller_requestOpts, opts.requestOptions, "f"); + __classPrivateFieldSet(this, _WorkPoller_controller, new AbortController(), "f"); + __classPrivateFieldSet(this, _WorkPoller_detachExternal, linkAbort(opts.signal, __classPrivateFieldGet(this, _WorkPoller_controller, "f")), "f"); + } + /** Read-only view of this iterator's abort signal. */ + get signal() { + return __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal; + } + /** Abort the iterator. The current `for await` will exit cleanly. */ + abort() { + __classPrivateFieldGet(this, _WorkPoller_controller, "f").abort(); + } + async *[(_WorkPoller_runnerClient = /* @__PURE__ */ new WeakMap(), _WorkPoller_consumed = /* @__PURE__ */ new WeakMap(), _WorkPoller_controller = /* @__PURE__ */ new WeakMap(), _WorkPoller_detachExternal = /* @__PURE__ */ new WeakMap(), _WorkPoller_autoStop = /* @__PURE__ */ new WeakMap(), _WorkPoller_drain = /* @__PURE__ */ new WeakMap(), _WorkPoller_blockMs = /* @__PURE__ */ new WeakMap(), _WorkPoller_reclaimOlderThanMs = /* @__PURE__ */ new WeakMap(), _WorkPoller_requestOpts = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + if (__classPrivateFieldGet(this, _WorkPoller_consumed, "f")) throw new AnthropicError("Cannot iterate over a consumed WorkPoller"); + __classPrivateFieldSet(this, _WorkPoller_consumed, true, "f"); + const log = loggerFor(this.client); + log.info("poller starting", { + component: "work-poller", + environment_id: this.environmentId + }); + try { + let attempt = 0; + while (!__classPrivateFieldGet(this, _WorkPoller_controller, "f").signal.aborted) { + let work; + try { + work = await __classPrivateFieldGet(this, _WorkPoller_runnerClient, "f").beta.environments.work.poll(this.environmentId, { + "Anthropic-Worker-ID": this.workerId, + ...__classPrivateFieldGet(this, _WorkPoller_blockMs, "f") !== null ? { block_ms: __classPrivateFieldGet(this, _WorkPoller_blockMs, "f") } : {}, + ...__classPrivateFieldGet(this, _WorkPoller_reclaimOlderThanMs, "f") !== null ? { reclaim_older_than_ms: __classPrivateFieldGet(this, _WorkPoller_reclaimOlderThanMs, "f") } : {} + }, { + headers: buildHeaders([__classPrivateFieldGet(this, _WorkPoller_requestOpts, "f")?.headers]), + signal: __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal + }); + } catch (e) { + if (__classPrivateFieldGet(this, _WorkPoller_controller, "f").signal.aborted) return; + if (isFatal4xx(e)) { + log.error("poll failed permanently, stopping poller", { error: String(e) }); + throw e; + } + const wait = applyJitter(backoff(attempt)); + log.warn("poll failed, backing off", { + error: String(e), + backoff_ms: wait + }); + attempt++; + await sleep(wait, __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal); + continue; + } + attempt = 0; + if (work == null) { + if (__classPrivateFieldGet(this, _WorkPoller_drain, "f")) return; + await sleep(jitter(1e3, 3e3), __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal); + continue; + } + log.info("claimed work", { + component: "work-poller", + environment_id: this.environmentId, + work_id: work.id, + work_type: work.data.type + }); + try { + await __classPrivateFieldGet(this, _WorkPoller_runnerClient, "f").beta.environments.work.ack(work.id, { environment_id: work.environment_id }, { + headers: buildHeaders([__classPrivateFieldGet(this, _WorkPoller_requestOpts, "f")?.headers]), + signal: __classPrivateFieldGet(this, _WorkPoller_controller, "f").signal + }); + } catch (e) { + log.error("ack failed", { + work_id: work.id, + error: String(e) + }); + continue; + } + try { + yield work; + } finally { + if (__classPrivateFieldGet(this, _WorkPoller_autoStop, "f")) try { + await __classPrivateFieldGet(this, _WorkPoller_runnerClient, "f").beta.environments.work.stop(work.id, { environment_id: work.environment_id }, { headers: buildHeaders([__classPrivateFieldGet(this, _WorkPoller_requestOpts, "f")?.headers]) }); + } catch (e) { + if (!isStatus(e, 409)) log.warn("stop failed", { + work_id: work.id, + error: String(e) + }); + } + } + } + } finally { + __classPrivateFieldGet(this, _WorkPoller_detachExternal, "f").call(this); + } + } +}; +/** Exponential poll backoff: 1s, 2s, 4s … clamped to a 60s cap. */ +function backoff(attempt) { + return backoff$1(attempt, POLL_BACKOFF_BASE_MS, POLL_BACKOFF_CAP_MS); +} +function defaultWorkerId() { + const host = (globalThis.process?.env)?.["HOSTNAME"]; + return host ? `${host}-${uuid4()}` : uuid4(); +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/async-queue.mjs +var _AsyncQueue_items; +var _AsyncQueue_waiters; +var _AsyncQueue_closed; +/** +* Single-consumer async queue that bridges background producers to an +* `AsyncIterator`-style reader. Producers `push()` items; the consumer awaits +* `next()`. `close()` is idempotent and wakes any pending `next()` with +* `done: true`. `tryShift()` synchronously drains remaining items after +* iteration has been signalled to stop. +*/ +var AsyncQueue = class { + constructor() { + _AsyncQueue_items.set(this, []); + _AsyncQueue_waiters.set(this, []); + _AsyncQueue_closed.set(this, false); + } + /** Enqueue an item, or hand it directly to a waiting reader. Returns `false` once closed. */ + push(item) { + if (__classPrivateFieldGet(this, _AsyncQueue_closed, "f")) return false; + const w = __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").shift(); + if (w) w({ + done: false, + value: item + }); + else __classPrivateFieldGet(this, _AsyncQueue_items, "f").push(item); + return true; + } + /** Mark the queue done. Idempotent; wakes every pending reader with `done: true`. */ + close() { + if (__classPrivateFieldGet(this, _AsyncQueue_closed, "f")) return; + __classPrivateFieldSet(this, _AsyncQueue_closed, true, "f"); + while (__classPrivateFieldGet(this, _AsyncQueue_waiters, "f").length > 0) __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").shift()({ + done: true, + value: void 0 + }); + } + /** + * Resolve with the next item, or `done: true` once the queue is closed and + * drained. When `signal` is supplied, aborting it resolves a pending read + * with `done: true` (cancellation is pushed down here rather than handled by + * an outer `Promise.race`). + */ + next(signal) { + if (__classPrivateFieldGet(this, _AsyncQueue_items, "f").length > 0) return Promise.resolve({ + done: false, + value: __classPrivateFieldGet(this, _AsyncQueue_items, "f").shift() + }); + if (__classPrivateFieldGet(this, _AsyncQueue_closed, "f") || signal?.aborted) return Promise.resolve({ + done: true, + value: void 0 + }); + return new Promise((resolve) => { + const waiter = (r) => { + signal?.removeEventListener("abort", onAbort); + resolve(r); + }; + const onAbort = () => { + const idx = __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").indexOf(waiter); + if (idx >= 0) __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").splice(idx, 1); + resolve({ + done: true, + value: void 0 + }); + }; + __classPrivateFieldGet(this, _AsyncQueue_waiters, "f").push(waiter); + signal?.addEventListener("abort", onAbort, { once: true }); + }); + } + /** Synchronously remove and return the next buffered item, or `undefined` if empty. */ + tryShift() { + return __classPrivateFieldGet(this, _AsyncQueue_items, "f").shift(); + } +}; +_AsyncQueue_items = /* @__PURE__ */ new WeakMap(), _AsyncQueue_waiters = /* @__PURE__ */ new WeakMap(), _AsyncQueue_closed = /* @__PURE__ */ new WeakMap(); +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/tools/BetaRunnableTool.mjs +/** +* Resolve the registry key for a tool — the name the model addresses it by. +* MCP toolsets are keyed on `mcp_server_name`; every other tool on `name`. +* Shared so the tool-name lookup is identical across `toolRunner()` surfaces. +*/ +function toolName(tool) { + return "name" in tool ? tool.name : tool.mcp_server_name; +} +/** +* Format a thrown value into tool-result content: a {@link ToolError} carries +* its own structured content, anything else becomes an `Error: ` +* string. Shared so every `toolRunner()` surface reports tool failures the +* same way to the model. +*/ +function toolErrorContent(e) { + return e instanceof ToolError ? e.content : `Error: ${e instanceof Error ? e.message : String(e)}`; +} +/** +* Run a {@link BetaRunnableTool} end-to-end: parse the raw input, invoke `run`, +* and format any thrown value via {@link toolErrorContent}. Shared so the +* parse → run → catch → format pipeline is identical across `toolRunner()` +* surfaces. +*/ +async function runRunnableTool(tool, rawInput, context) { + try { + const input = tool.parse ? tool.parse(rawInput) : rawInput; + return { + content: await tool.run(input, context), + isError: false + }; + } catch (e) { + return { + content: toolErrorContent(e), + isError: true + }; + } +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/tools/SessionToolRunner.mjs +var _IdleClock_maxIdleMs; +var _IdleClock_onExpire; +var _IdleClock_blockers; +var _IdleClock_armPending; +var _IdleClock_timer; +var _SessionToolRunner_instances; +var _SessionToolRunner_consumed; +var _SessionToolRunner_controller; +var _SessionToolRunner_detachExternal; +var _SessionToolRunner_requestOpts; +var _SessionToolRunner_toolByName; +var _SessionToolRunner_logger; +var _SessionToolRunner_seen; +var _SessionToolRunner_answered; +var _SessionToolRunner_confirmationVerdicts; +var _SessionToolRunner_awaitingConfirmation; +var _SessionToolRunner_results; +var _SessionToolRunner_inFlightCount; +var _SessionToolRunner_onIdle; +var _SessionToolRunner_idleClock; +var _SessionToolRunner_requestOptions; +var _SessionToolRunner_streamLoop; +var _SessionToolRunner_reconcile; +var _SessionToolRunner_ingestHistory; +var _SessionToolRunner_handleStreamEvent; +var _SessionToolRunner_routeToolEvent; +var _SessionToolRunner_noteConfirmation; +var _SessionToolRunner_applyVerdict; +var _SessionToolRunner_surfaceCall; +var _SessionToolRunner_execute; +var _SessionToolRunner_sendResult; +var _SessionToolRunner_drain; +var STREAM_BACKOFF_START_MS = 500; +var STREAM_BACKOFF_CAP_MS = 1e4; +var TOOL_TIMEOUT_MS = 12e4; +var DRAIN_TIMEOUT_MS = 3e4; +var SEND_RETRIES = 3; +/** Returns true if `ev` is a `session.status_idle` with `stop_reason` `end_turn`. */ +function isEndTurnIdle(ev) { + return ev.type === "session.status_idle" && ev.stop_reason?.type === "end_turn"; +} +/** +* The `maxIdleMs` stop-countdown, including its deferral. {@link noteEvent} +* arms on `session.status_idle` with `stop_reason: end_turn` and disarms on +* anything else. Gated tool work registered via {@link block} — a call held for +* user confirmation, or a user-approved call still dispatching — keeps +* {@link arm} pending until {@link unblock} retires the last blocker, at which +* point the countdown starts. Event-driven — there is no polling watchdog. +*/ +var IdleClock = class { + constructor(maxIdleMs, onExpire) { + _IdleClock_maxIdleMs.set(this, void 0); + _IdleClock_onExpire.set(this, void 0); + _IdleClock_blockers.set(this, /* @__PURE__ */ new Set()); + _IdleClock_armPending.set(this, false); + _IdleClock_timer.set(this, void 0); + __classPrivateFieldSet(this, _IdleClock_maxIdleMs, maxIdleMs, "f"); + __classPrivateFieldSet(this, _IdleClock_onExpire, onExpire, "f"); + } + /** + * Arm on `status_idle{end_turn}`; disarm otherwise. `user.tool_confirmation` + * is neutral: it signals neither agent activity nor an idle, and its effect + * on the clock flows through {@link block} / {@link unblock} instead — + * disarming here would discard the pending arm the verdict is about to + * settle. + */ + noteEvent(ev) { + if (ev.type === "user.tool_confirmation") return; + if (isEndTurnIdle(ev)) this.arm(); + else this.disarm(); + } + /** Register gated work that must resolve before an idle countdown starts. */ + block(toolUseId) { + __classPrivateFieldGet(this, _IdleClock_blockers, "f").add(toolUseId); + if (__classPrivateFieldGet(this, _IdleClock_timer, "f") !== void 0) { + __classPrivateFieldSet(this, _IdleClock_armPending, true, "f"); + clearTimeout(__classPrivateFieldGet(this, _IdleClock_timer, "f")); + __classPrivateFieldSet(this, _IdleClock_timer, void 0, "f"); + } + } + /** + * Retire gated work (a no-op for ids never blocked); applies a pending arm — + * with a fresh full `maxIdleMs` window — once the last blocker retires. + */ + unblock(toolUseId) { + __classPrivateFieldGet(this, _IdleClock_blockers, "f").delete(toolUseId); + if (__classPrivateFieldGet(this, _IdleClock_blockers, "f").size === 0 && __classPrivateFieldGet(this, _IdleClock_armPending, "f")) this.arm(); + } + /** + * (Re)start the idle countdown — or, while blockers are outstanding, hold + * the arm pending instead. Stopping then would drop a held call when its + * verdict later arrives, or cut the runner off before a released call's + * result can drive the next turn. + */ + arm() { + if (__classPrivateFieldGet(this, _IdleClock_maxIdleMs, "f") <= 0) return; + if (__classPrivateFieldGet(this, _IdleClock_blockers, "f").size > 0) { + __classPrivateFieldSet(this, _IdleClock_armPending, true, "f"); + return; + } + __classPrivateFieldSet(this, _IdleClock_armPending, false, "f"); + if (__classPrivateFieldGet(this, _IdleClock_timer, "f") !== void 0) clearTimeout(__classPrivateFieldGet(this, _IdleClock_timer, "f")); + __classPrivateFieldSet(this, _IdleClock_timer, setTimeout(__classPrivateFieldGet(this, _IdleClock_onExpire, "f"), __classPrivateFieldGet(this, _IdleClock_maxIdleMs, "f")), "f"); + } + /** + * Cancel the idle countdown and any pending arm. Blockers persist — they + * track real outstanding work, retired only by {@link unblock}. + */ + disarm() { + __classPrivateFieldSet(this, _IdleClock_armPending, false, "f"); + if (__classPrivateFieldGet(this, _IdleClock_timer, "f") !== void 0) { + clearTimeout(__classPrivateFieldGet(this, _IdleClock_timer, "f")); + __classPrivateFieldSet(this, _IdleClock_timer, void 0, "f"); + } + } +}; +_IdleClock_maxIdleMs = /* @__PURE__ */ new WeakMap(), _IdleClock_onExpire = /* @__PURE__ */ new WeakMap(), _IdleClock_blockers = /* @__PURE__ */ new WeakMap(), _IdleClock_armPending = /* @__PURE__ */ new WeakMap(), _IdleClock_timer = /* @__PURE__ */ new WeakMap(); +/** +* The sessions-side counterpart to `client.beta.messages.toolRunner`: an +* async-iterable that attaches to a managed-agents session, executes every +* incoming `agent.tool_use` and `agent.custom_tool_use` event against a local +* tool registry, posts the matching result back (`user.tool_result` for the +* former, `user.custom_tool_result` for the latter), and yields one +* {@link DispatchedToolCall} per completed call. Server-side `agent.mcp_tool_use` +* calls are not dispatched. Internally drives event-stream reconnect and result +* posting. +* +* A call the server gated with `evaluated_permission: "ask"` (the `always_ask` +* policy — or any value this SDK doesn't recognize, which fails closed) is held +* until its `user.tool_confirmation` arrives: only an explicit `allow` runs it; +* `deny` — or any verdict this SDK doesn't recognize, failing closed — is never +* executed and posts nothing (the denial resolves the call server-side), but is +* still yielded (`confirmation="deny"`, `posted=false`, `result=undefined`) so +* the consumer can observe it. A held call — and a user-approved one still +* dispatching — defers the `maxIdleMs` countdown, so an `end_turn` idle +* observed in the meantime cannot stop the runner: it waits until the verdict +* arrives, the session terminates, or the abort signal fires — pass +* `AbortSignal.timeout(...)` for a wall-clock bound. +* +* Iteration ends when the session terminates (`session.status_terminated` / +* `session.deleted`), when the consumer `break`s out of the loop or aborts the +* supplied signal, or — once the session has gone idle with +* `stop_reason.type === "end_turn"` — when `maxIdleMs` elapses with no new +* event (any new event resets that countdown; it re-arms on the next `end_turn` +* idle; `maxIdleMs <= 0` disables it). The `finally` branch drains any in-flight +* tool calls and runs each tool's `close()` cleanup hook. It does *not* touch +* the work-item lease — wrap it in an `EnvironmentWorker` if you need +* heartbeating / force-stop. +* +* @example +* ```ts +* import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node'; +* +* for await (const call of client.beta.sessions.events.toolRunner(work.data.id, { +* tools: [...betaAgentToolset20260401({ workdir }), myTool], +* })) { +* console.log(`${call.name} -> ${call.isError ? 'error' : 'ok'}`); +* } +* ``` +*/ +var SessionToolRunner = class { + constructor(sessionId, opts) { + _SessionToolRunner_instances.add(this); + _SessionToolRunner_consumed.set(this, false); + _SessionToolRunner_controller.set(this, void 0); + _SessionToolRunner_detachExternal.set(this, void 0); + _SessionToolRunner_requestOpts.set(this, void 0); + _SessionToolRunner_toolByName.set(this, void 0); + _SessionToolRunner_logger.set(this, void 0); + _SessionToolRunner_seen.set(this, /* @__PURE__ */ new Set()); + _SessionToolRunner_answered.set(this, /* @__PURE__ */ new Set()); + _SessionToolRunner_confirmationVerdicts.set(this, /* @__PURE__ */ new Map()); + _SessionToolRunner_awaitingConfirmation.set(this, /* @__PURE__ */ new Map()); + _SessionToolRunner_results.set(this, new AsyncQueue()); + _SessionToolRunner_inFlightCount.set(this, 0); + _SessionToolRunner_onIdle.set(this, null); + _SessionToolRunner_idleClock.set(this, void 0); + this.client = opts.client; + this.sessionId = sessionId; + this.tools = opts.tools; + this.maxIdleMs = opts.maxIdleMs ?? 6e4; + __classPrivateFieldSet(this, _SessionToolRunner_logger, loggerFor(opts.client), "f"); + __classPrivateFieldSet(this, _SessionToolRunner_toolByName, new Map(opts.tools.map((t) => [toolName(t), t])), "f"); + __classPrivateFieldSet(this, _SessionToolRunner_controller, new AbortController(), "f"); + __classPrivateFieldSet(this, _SessionToolRunner_detachExternal, linkAbort(opts.signal, __classPrivateFieldGet(this, _SessionToolRunner_controller, "f")), "f"); + __classPrivateFieldSet(this, _SessionToolRunner_requestOpts, opts.requestOptions, "f"); + __classPrivateFieldSet(this, _SessionToolRunner_idleClock, new IdleClock(this.maxIdleMs, () => { + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("session idle after end_turn; stopping", { + component: "session-tool-runner", + session_id: this.sessionId, + max_idle_ms: this.maxIdleMs + }); + __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); + }), "f"); + } + /** Read-only view of this runner's abort signal. */ + get signal() { + return __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal; + } + /** Abort the runner. Background tasks will wind down and `for await` will exit cleanly. */ + abort() { + __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); + } + async *[(_SessionToolRunner_consumed = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_controller = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_detachExternal = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_requestOpts = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_toolByName = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_logger = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_seen = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_answered = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_confirmationVerdicts = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_awaitingConfirmation = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_results = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_inFlightCount = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_onIdle = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_idleClock = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() { + if (__classPrivateFieldGet(this, _SessionToolRunner_consumed, "f")) throw new AnthropicError("Cannot iterate over a consumed SessionToolRunner"); + __classPrivateFieldSet(this, _SessionToolRunner_consumed, true, "f"); + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("session tool runner starting", { + component: "session-tool-runner", + session_id: this.sessionId + }); + const streamPromise = __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_streamLoop).call(this).catch((e) => { + if (!__classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal.aborted) __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").error("stream loop failed", { error: String(e) }); + __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); + }); + try { + while (true) { + const next = await __classPrivateFieldGet(this, _SessionToolRunner_results, "f").next(__classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal); + if (next.done) break; + yield next.value; + } + await streamPromise; + let pending; + while ((pending = __classPrivateFieldGet(this, _SessionToolRunner_results, "f").tryShift()) !== void 0) yield pending; + } finally { + __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); + __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").disarm(); + await streamPromise; + try { + await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_drain).call(this); + } catch (e) { + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("drain failed", { error: String(e) }); + } + __classPrivateFieldGet(this, _SessionToolRunner_results, "f").close(); + for (const t of this.tools) try { + await t.close?.(); + } catch (e) { + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("tool.close failed", { + tool: toolName(t), + error: String(e) + }); + } + __classPrivateFieldGet(this, _SessionToolRunner_detachExternal, "f").call(this); + } + } +}; +_SessionToolRunner_requestOptions = function _SessionToolRunner_requestOptions() { + return { + ...__classPrivateFieldGet(this, _SessionToolRunner_requestOpts, "f"), + headers: buildHeaders([helperHeader("session-tool-runner"), __classPrivateFieldGet(this, _SessionToolRunner_requestOpts, "f")?.headers]), + signal: __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal + }; +}, _SessionToolRunner_streamLoop = async function _SessionToolRunner_streamLoop() { + const ctrl = __classPrivateFieldGet(this, _SessionToolRunner_controller, "f"); + let backoff = STREAM_BACKOFF_START_MS; + while (!ctrl.signal.aborted) { + try { + const stream = await this.client.beta.sessions.events.stream(this.sessionId, {}, __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_requestOptions).call(this)); + await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_reconcile).call(this); + for await (const ev of stream) { + backoff = STREAM_BACKOFF_START_MS; + if (await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_handleStreamEvent).call(this, ev)) return; + } + } catch (e) { + ctrl.signal.throwIfAborted(); + if (isFatal4xx(e)) { + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").error("permanent stream failure, shutting down", { error: String(e) }); + ctrl.abort(); + throw e; + } + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("stream disconnected, reconnecting", { + error: String(e), + backoff_ms: backoff + }); + } + ctrl.signal.throwIfAborted(); + await sleep(backoff, ctrl.signal); + backoff = Math.min(backoff * 2, STREAM_BACKOFF_CAP_MS); + } +}, _SessionToolRunner_reconcile = async function _SessionToolRunner_reconcile() { + const ctrl = __classPrivateFieldGet(this, _SessionToolRunner_controller, "f"); + const pending = []; + let lastWasEndTurn = false; + try { + for await (const ev of this.client.beta.sessions.events.list(this.sessionId, { limit: 1e3 }, __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_requestOptions).call(this))) { + __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_ingestHistory).call(this, ev, pending); + lastWasEndTurn = isEndTurnIdle(ev); + } + } catch (e) { + ctrl.signal.throwIfAborted(); + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("reconcile list failed", { error: String(e) }); + for (const ev of pending) __classPrivateFieldGet(this, _SessionToolRunner_seen, "f").delete(ev.id); + return; + } + const unanswered = pending.filter((ev) => !__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.id)); + __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").disarm(); + for (const ev of unanswered) await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_routeToolEvent).call(this, ev); + for (const held of [...__classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").values()]) { + const verdict = __classPrivateFieldGet(this, _SessionToolRunner_confirmationVerdicts, "f").get(held.id); + if (verdict !== void 0) await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_applyVerdict).call(this, held, verdict); + } + const outstanding = unanswered.filter((ev) => !__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.id) && !__classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").has(ev.id)); + if (lastWasEndTurn && outstanding.length === 0) __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").arm(); + else __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").disarm(); +}, _SessionToolRunner_ingestHistory = function _SessionToolRunner_ingestHistory(ev, pending) { + if (ev.type === "agent.tool_use" || ev.type === "agent.custom_tool_use") { + __classPrivateFieldGet(this, _SessionToolRunner_seen, "f").add(ev.id); + if (!__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.id)) pending.push(ev); + } else if (ev.type === "user.tool_result") __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.tool_use_id); + else if (ev.type === "user.custom_tool_result") __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.custom_tool_use_id); + else if (ev.type === "user.tool_confirmation") { + if (!__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.tool_use_id)) __classPrivateFieldGet(this, _SessionToolRunner_confirmationVerdicts, "f").set(ev.tool_use_id, ev.result); + } +}, _SessionToolRunner_handleStreamEvent = async function _SessionToolRunner_handleStreamEvent(ev) { + __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").noteEvent(ev); + switch (ev.type) { + case "agent.tool_use": + case "agent.custom_tool_use": + if (!__classPrivateFieldGet(this, _SessionToolRunner_seen, "f").has(ev.id)) { + __classPrivateFieldGet(this, _SessionToolRunner_seen, "f").add(ev.id); + await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_routeToolEvent).call(this, ev); + } + return false; + case "user.tool_confirmation": + await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_noteConfirmation).call(this, ev); + return false; + case "user.tool_result": + __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.tool_use_id); + return false; + case "user.custom_tool_result": + __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.custom_tool_use_id); + return false; + case "session.status_terminated": + case "session.deleted": + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("session terminated", { + component: "session-tool-runner", + session_id: this.sessionId + }); + __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").abort(); + return true; + default: return false; + } +}, _SessionToolRunner_routeToolEvent = async function _SessionToolRunner_routeToolEvent(ev) { + const permission = ev.evaluated_permission; + const verdict = permission === "deny" ? "deny" : __classPrivateFieldGet(this, _SessionToolRunner_confirmationVerdicts, "f").get(ev.id); + if (verdict === void 0) { + if (permission === void 0 || permission === "allow") await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_execute).call(this, ev, void 0); + else if (!__classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").has(ev.id)) { + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("tool call awaiting confirmation; holding", { + component: "session-tool-runner", + session_id: this.sessionId, + tool: ev.name, + tool_use_id: ev.id + }); + __classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").set(ev.id, ev); + __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").block(ev.id); + } + return; + } + await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_applyVerdict).call(this, ev, verdict); +}, _SessionToolRunner_noteConfirmation = async function _SessionToolRunner_noteConfirmation(ev) { + __classPrivateFieldGet(this, _SessionToolRunner_confirmationVerdicts, "f").set(ev.tool_use_id, ev.result); + const held = __classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").get(ev.tool_use_id); + if (held === void 0) return; + await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_applyVerdict).call(this, held, ev.result); +}, _SessionToolRunner_applyVerdict = async function _SessionToolRunner_applyVerdict(ev, verdict) { + const wasHeld = __classPrivateFieldGet(this, _SessionToolRunner_awaitingConfirmation, "f").delete(ev.id); + if (verdict === "allow") { + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("tool call confirmed", { + component: "session-tool-runner", + session_id: this.sessionId, + tool: ev.name, + tool_use_id: ev.id + }); + if (!wasHeld) __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").block(ev.id); + try { + await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_execute).call(this, ev, "allow"); + } finally { + __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").unblock(ev.id); + } + return; + } + if (wasHeld) __classPrivateFieldGet(this, _SessionToolRunner_idleClock, "f").unblock(ev.id); + __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(ev.id); + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("tool call denied; not executing", { + component: "session-tool-runner", + session_id: this.sessionId, + tool: ev.name, + tool_use_id: ev.id + }); + __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_surfaceCall).call(this, { + event: ev, + toolUseId: ev.id, + name: ev.name, + isError: false, + posted: false, + confirmation: "deny" + }); +}, _SessionToolRunner_surfaceCall = function _SessionToolRunner_surfaceCall(call) { + __classPrivateFieldGet(this, _SessionToolRunner_results, "f").push(call); +}, _SessionToolRunner_execute = async function _SessionToolRunner_execute(ev, confirmation) { + var _a, _b; + if (__classPrivateFieldGet(this, _SessionToolRunner_answered, "f").has(ev.id)) return; + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("executing tool", { + component: "session-tool-runner", + session_id: this.sessionId, + tool: ev.name, + tool_use_id: ev.id + }); + __classPrivateFieldSet(this, _SessionToolRunner_inFlightCount, (_a = __classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f"), _a++, _a), "f"); + try { + const tool = __classPrivateFieldGet(this, _SessionToolRunner_toolByName, "f").get(ev.name); + if (!tool) { + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner", { + component: "session-tool-runner", + session_id: this.sessionId, + tool: ev.name, + tool_use_id: ev.id + }); + __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_surfaceCall).call(this, { + event: ev, + toolUseId: ev.id, + name: ev.name, + isError: false, + posted: false, + confirmation + }); + return; + } + let content; + let isError; + const toolCtrl = new AbortController(); + const detachTool = linkAbort(__classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal, toolCtrl); + const timer = setTimeout(() => toolCtrl.abort(), TOOL_TIMEOUT_MS); + try { + const outcome = await runRunnableTool(tool, ev.input, { + toolUse: ev, + toolUseBlock: ev, + signal: toolCtrl.signal + }); + content = outcome.content; + isError = outcome.isError; + } finally { + clearTimeout(timer); + detachTool(); + } + const result = buildResultEvent(ev, isError, toSessionContent(content)); + const posted = await __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_sendResult).call(this, result, ev.id); + __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_surfaceCall).call(this, { + event: ev, + result, + toolUseId: ev.id, + name: ev.name, + isError, + posted, + confirmation + }); + } finally { + __classPrivateFieldSet(this, _SessionToolRunner_inFlightCount, (_b = __classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f"), _b--, _b), "f"); + if (__classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f") === 0) __classPrivateFieldGet(this, _SessionToolRunner_onIdle, "f")?.call(this); + } +}, _SessionToolRunner_sendResult = async function _SessionToolRunner_sendResult(result, toolUseId) { + const ctrl = __classPrivateFieldGet(this, _SessionToolRunner_controller, "f"); + let lastErr; + for (let i = 0; i < SEND_RETRIES; i++) { + ctrl.signal.throwIfAborted(); + try { + await this.client.beta.sessions.events.send(this.sessionId, { events: [result] }, __classPrivateFieldGet(this, _SessionToolRunner_instances, "m", _SessionToolRunner_requestOptions).call(this)); + __classPrivateFieldGet(this, _SessionToolRunner_answered, "f").add(toolUseId); + return true; + } catch (e) { + lastErr = e; + if (isFatal4xx(e)) break; + if (i < SEND_RETRIES - 1) await sleep((i + 1) * 1e3, ctrl.signal); + } + } + __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").error("failed to send tool result", { + tool_use_id: toolUseId, + error: String(lastErr) + }); + return false; +}, _SessionToolRunner_drain = async function _SessionToolRunner_drain() { + if (__classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f") === 0) return; + await Promise.race([new Promise((r) => __classPrivateFieldSet(this, _SessionToolRunner_onIdle, r, "f")), sleep(DRAIN_TIMEOUT_MS)]); + __classPrivateFieldSet(this, _SessionToolRunner_onIdle, null, "f"); + if (__classPrivateFieldGet(this, _SessionToolRunner_inFlightCount, "f") > 0) __classPrivateFieldGet(this, _SessionToolRunner_logger, "f").warn("drain timeout exceeded"); +}; +/** +* Build the result event that answers `ev`: a `user.tool_result` for a builtin +* `agent.tool_use`, a `user.custom_tool_result` for a custom +* `agent.custom_tool_use`. The two `(use, result)` pairs are distinct API event +* types and must be matched exactly — a `user.tool_result` does not answer a +* custom tool call. +*/ +function buildResultEvent(ev, isError, content) { + if (ev.type === "agent.custom_tool_use") return { + type: "user.custom_tool_result", + custom_tool_use_id: ev.id, + is_error: isError, + content + }; + return { + type: "user.tool_result", + tool_use_id: ev.id, + is_error: isError, + content + }; +} +function toSessionContent(content) { + if (typeof content === "string") return [{ + type: "text", + text: content || "(no output)" + }]; + const out = content.map((b) => { + if (b.type === "text") return { + type: "text", + text: b.text || "(no output)" + }; + if (b.type === "image" || b.type === "document") return b; + if (b.type === "search_result") return { + type: "search_result", + source: b.source, + title: b.title, + content: b.content.map((c) => ({ + type: "text", + text: c.text + })), + citations: { enabled: b.citations?.enabled ?? false } + }; + return { + type: "text", + text: JSON.stringify(b) + }; + }); + return out.length > 0 ? out : [{ + type: "text", + text: "(no output)" + }]; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/environments/worker.mjs +var _EnvironmentWorker_instances; +var _EnvironmentWorker_signal; +var _EnvironmentWorker_handleItem; +var HEARTBEAT_DEFAULT_MS = 3e4; +var NO_HEARTBEAT_SENTINEL = "NO_HEARTBEAT"; +/** +* The self-hosted environment runner, composed from the control-plane +* {@link WorkPoller} and the per-session {@link SessionToolRunner}. +* +* For each claimed `session` work item it: builds the per-session +* {@link AgentToolContext}, downloads the session agent's skills +* (`setupSkills`), then runs a {@link SessionToolRunner} for the session +* *while* heartbeating the work-item lease in parallel; on exit it force-stops +* the work item, cleans up the downloaded skills, and loops to the next one. The +* lease heartbeat reports `state === "stopping"` / a lost lease back into the run +* by aborting the session runner. +* +* Use {@link EnvironmentWorker.handleItem} if you already hold a claimed work +* item (e.g. a `worker poll --on-work` script handed one to a fresh process) and +* just want the per-item flow without the poll loop — with no arguments it reads +* the `ANTHROPIC_*` env vars that command sets. +* +* Construct it via `client.beta.environments.work.worker({ ... })` (or +* `new EnvironmentWorker({ client, ... })` directly). +* +* @example +* ```ts +* // Long-running daemon: poll for work, serve each session, loop. +* await client.beta.environments.work +* .worker({ environmentId, environmentKey, workdir: '/workspace' }) +* .run(AbortSignal.timeout(60 * 60_000)); +* +* // Already-claimed item (e.g. inside `ant worker poll --on-work ...`): +* await client.beta.environments.work.worker({ workdir: '/workspace' }).handleItem(); +* ``` +*/ +var EnvironmentWorker = class { + constructor(opts) { + _EnvironmentWorker_instances.add(this); + _EnvironmentWorker_signal.set(this, void 0); + this.client = opts.client; + this.environmentId = opts.environmentId; + this.environmentKey = opts.environmentKey; + this.tools = opts.tools; + this.workdir = opts.workdir ?? process.cwd(); + this.unrestrictedPaths = opts.unrestrictedPaths; + this.maxFileBytes = opts.maxFileBytes; + this.maxIdleMs = opts.maxIdleMs; + this.workerId = opts.workerId; + this.requestOptions = opts.requestOptions; + __classPrivateFieldSet(this, _EnvironmentWorker_signal, opts.signal, "f"); + } + /** + * Poll the environment and service each claimed session until the supplied + * signal (or the one passed to the constructor) aborts. Throws if + * `environmentId` / `environmentKey` were not provided to the constructor. + */ + async run(signal) { + const { environmentId, environmentKey } = this; + if (environmentId === void 0 || environmentKey === void 0) throw new AnthropicError("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work"); + const externalSignal = signal ?? __classPrivateFieldGet(this, _EnvironmentWorker_signal, "f"); + const poller = new WorkPoller({ + client: this.client, + environmentId, + environmentKey, + ...this.workerId !== void 0 ? { workerId: this.workerId } : {}, + ...externalSignal ? { signal: externalSignal } : {}, + ...this.requestOptions !== void 0 ? { requestOptions: this.requestOptions } : {}, + autoStop: false + }); + for await (const work of poller) await __classPrivateFieldGet(this, _EnvironmentWorker_instances, "m", _EnvironmentWorker_handleItem).call(this, work, environmentKey, poller.signal); + } + /** + * Service a single, already-claimed work item without the poll loop: build the + * per-session {@link AgentToolContext} (workdir from this worker's options), + * download the session agent's skills (`setupSkills`), run a + * {@link SessionToolRunner} for the session while heartbeating the work-item + * lease in parallel, and force-stop the work item on exit (whether the runner + * finishes normally, throws, or the heartbeat loop signals shutdown). + * + * Use this when something else does the claiming — e.g. a `worker poll + * --on-work` script that hands an already-claimed item to a fresh process. The + * work id / environment id / session id each fall back to `ANTHROPIC_WORK_ID` / + * `ANTHROPIC_ENVIRONMENT_ID` / `ANTHROPIC_SESSION_ID` (the env vars that + * command sets) when not passed; the environment key resolves from this + * option, then the worker's own `environmentKey`, then + * `ANTHROPIC_ENVIRONMENT_KEY`. With no arguments inside that command it just + * works. Throws a clear error naming the first of the four required values + * still missing after resolution. + */ + async handleItem(opts) { + const workId = opts?.workId ?? readEnv("ANTHROPIC_WORK_ID"); + const environmentId = opts?.environmentId ?? readEnv("ANTHROPIC_ENVIRONMENT_ID"); + const sessionId = opts?.sessionId ?? readEnv("ANTHROPIC_SESSION_ID"); + const environmentKey = opts?.environmentKey ?? this.environmentKey ?? readEnv("ANTHROPIC_ENVIRONMENT_KEY"); + if (!workId) throw new AnthropicError("handleItem: workId is required — pass it or set ANTHROPIC_WORK_ID"); + if (!environmentId) throw new AnthropicError("handleItem: environmentId is required — pass it or set ANTHROPIC_ENVIRONMENT_ID"); + if (!sessionId) throw new AnthropicError("handleItem: sessionId is required — pass it or set ANTHROPIC_SESSION_ID"); + if (!environmentKey) throw new AnthropicError("handleItem: environmentKey is required — pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY"); + const work = { + id: workId, + environment_id: environmentId, + data: { + type: "session", + id: sessionId + } + }; + await __classPrivateFieldGet(this, _EnvironmentWorker_instances, "m", _EnvironmentWorker_handleItem).call(this, work, environmentKey, opts?.signal ?? __classPrivateFieldGet(this, _EnvironmentWorker_signal, "f")); + } +}; +_EnvironmentWorker_signal = /* @__PURE__ */ new WeakMap(), _EnvironmentWorker_instances = /* @__PURE__ */ new WeakSet(), _EnvironmentWorker_handleItem = async function _EnvironmentWorker_handleItem(work, environmentKey, externalSignal) { + const log = loggerFor(this.client); + const sessionClient = copyClientForHelper(this.client, { + authToken: environmentKey, + helper: "environments-worker" + }); + const sessionId = work.data.id; + const ctx = { + workdir: this.workdir, + client: this.client, + sessionId, + ...this.unrestrictedPaths !== void 0 ? { unrestrictedPaths: this.unrestrictedPaths } : {}, + ...this.maxFileBytes !== void 0 ? { maxFileBytes: this.maxFileBytes } : {} + }; + const agentToolset = await Promise.resolve().then(() => node_exports); + let cleanupSkills = async () => {}; + try { + cleanupSkills = await agentToolset.setupSkills(ctx); + } catch (e) { + log.warn("skill setup failed", { + session_id: sessionId, + work_id: work.id, + error: String(e) + }); + } + const tools = typeof this.tools === "function" ? this.tools(ctx) : this.tools ?? agentToolset.betaAgentToolset20260401(ctx); + const ctrl = new AbortController(); + const detachExternal = linkAbort(externalSignal, ctrl); + const heartbeatPromise = heartbeatLoop(sessionClient, work, ctrl, log, this.requestOptions).catch((e) => { + if (!ctrl.signal.aborted) log.error("heartbeat loop failed", { + work_id: work.id, + error: String(e) + }); + ctrl.abort(); + }); + try { + const runner = new SessionToolRunner(sessionId, { + client: sessionClient, + tools, + ...this.maxIdleMs !== void 0 ? { maxIdleMs: this.maxIdleMs } : {}, + ...this.requestOptions !== void 0 ? { requestOptions: this.requestOptions } : {}, + signal: ctrl.signal + }); + for await (const _ of runner); + } finally { + ctrl.abort(); + detachExternal(); + await heartbeatPromise; + await cleanupSkills().catch((e) => { + log.warn("skill cleanup failed", { + session_id: sessionId, + work_id: work.id, + error: String(e) + }); + }); + await forceStop(sessionClient, work, log, this.requestOptions); + } +}; +/** Force-stop a claimed work item, swallowing the 409 that means it's already stopped. */ +async function forceStop(client, work, log, requestOptions) { + try { + await client.beta.environments.work.stop(work.id, { + environment_id: work.environment_id, + force: true + }, { + ...requestOptions, + headers: buildHeaders([requestOptions?.headers]) + }); + } catch (e) { + if (!isStatus(e, 409)) log.error("force-stop on exit failed", { + work_id: work.id, + error: String(e) + }); + } +} +/** +* Keep the work-item lease alive while a session is being served. Aborts `ctrl` +* when the control plane reports the work is `stopping`/`stopped`, when the +* lease is no longer extended, or on a permanent heartbeat failure. +*/ +async function heartbeatLoop(client, work, ctrl, logger, requestOptions) { + let intervalMs = HEARTBEAT_DEFAULT_MS; + let last = NO_HEARTBEAT_SENTINEL; + const beat = async () => { + try { + const resp = await client.beta.environments.work.heartbeat(work.id, { + environment_id: work.environment_id, + expected_last_heartbeat: last + }, { + ...requestOptions, + headers: buildHeaders([requestOptions?.headers]), + signal: ctrl.signal + }); + last = resp.last_heartbeat; + if (resp.ttl_seconds > 0) intervalMs = Math.max(1e3, Math.min(resp.ttl_seconds * 1e3 / 2, HEARTBEAT_DEFAULT_MS)); + if (resp.state === "stopping" || resp.state === "stopped") { + logger.info("heartbeat signals shutdown", { + work_id: work.id, + state: resp.state + }); + ctrl.abort(); + } + if (!resp.lease_extended) { + logger.warn("lease not extended, shutting down", { work_id: work.id }); + ctrl.abort(); + } + } catch (e) { + ctrl.signal.throwIfAborted(); + if (isFatal4xx(e)) { + logger.error("permanent heartbeat failure", { + work_id: work.id, + error: String(e) + }); + ctrl.abort(); + throw e; + } + logger.warn("transient heartbeat failure", { + work_id: work.id, + error: String(e) + }); + } + }; + await beat(); + while (!ctrl.signal.aborted) { + await sleep(intervalMs, ctrl.signal); + ctrl.signal.throwIfAborted(); + await beat(); + } +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/environments/work.mjs +var Work = class extends APIResource { + /** + * Note: these endpoints are called automatically by the pre-built environment + * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted + * sandbox environments. They are included here as a reference; you do not need to + * invoke them directly. + * + * Retrieve detailed information about a specific work item. + * + * @example + * ```ts + * const betaSelfHostedWork = + * await client.beta.environments.work.retrieve('work_id', { + * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * }); + * ``` + */ + retrieve(workID, params, options) { + const { environment_id, betas } = params; + return this._client.get(path$2`/v1/environments/${environment_id}/work/${workID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Note: these endpoints are called automatically by the pre-built environment + * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted + * sandbox environments. They are included here as a reference; you do not need to + * invoke them directly. + * + * Update work item metadata with merge semantics. + * + * @example + * ```ts + * const betaSelfHostedWork = + * await client.beta.environments.work.update('work_id', { + * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * metadata: { foo: 'string' }, + * }); + * ``` + */ + update(workID, params, options) { + const { environment_id, betas, ...body } = params; + return this._client.post(path$2`/v1/environments/${environment_id}/work/${workID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Note: these endpoints are called automatically by the pre-built environment + * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted + * sandbox environments. They are included here as a reference; you do not need to + * invoke them directly. + * + * List work items in an environment. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaSelfHostedWork of client.beta.environments.work.list( + * 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * )) { + * // ... + * } + * ``` + */ + list(environmentID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/environments/${environmentID}/work?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Note: these endpoints are called automatically by the pre-built environment + * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted + * sandbox environments. They are included here as a reference; you do not need to + * invoke them directly. + * + * Acknowledge receipt of a work item, transitioning it from 'queued' to 'starting' + * and removing it from the queue. + * + * @example + * ```ts + * const betaSelfHostedWork = + * await client.beta.environments.work.ack('work_id', { + * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * }); + * ``` + */ + ack(workID, params, options) { + const { environment_id, betas } = params; + return this._client.post(path$2`/v1/environments/${environment_id}/work/${workID}/ack?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Note: these endpoints are called automatically by the pre-built environment + * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted + * sandbox environments. They are included here as a reference; you do not need to + * invoke them directly. + * + * Record a heartbeat for a work item to maintain the lease. + * + * @example + * ```ts + * const betaSelfHostedWorkHeartbeatResponse = + * await client.beta.environments.work.heartbeat('work_id', { + * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * }); + * ``` + */ + heartbeat(workID, params, options) { + const { environment_id, desired_ttl_seconds, expected_last_heartbeat, betas } = params; + return this._client.post(path$2`/v1/environments/${environment_id}/work/${workID}/heartbeat?beta=true`, { + query: { + desired_ttl_seconds, + expected_last_heartbeat + }, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Note: these endpoints are called automatically by the pre-built environment + * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted + * sandbox environments. They are included here as a reference; you do not need to + * invoke them directly. + * + * Long poll for work items in the queue. + * + * @example + * ```ts + * const betaSelfHostedWork = + * await client.beta.environments.work.poll( + * 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * ); + * ``` + */ + poll(environmentID, params = {}, options) { + const { betas, "Anthropic-Worker-ID": anthropicWorkerID, ...query } = params ?? {}; + return this._client.get(path$2`/v1/environments/${environmentID}/work/poll?beta=true`, { + query, + ...options, + headers: buildHeaders([{ + "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(), + ...anthropicWorkerID != null ? { "Anthropic-Worker-ID": anthropicWorkerID } : void 0 + }, options?.headers]) + }); + } + /** + * Get statistics about the work queue for an environment. + * + * @example + * ```ts + * const betaSelfHostedWorkQueueStats = + * await client.beta.environments.work.stats( + * 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * ); + * ``` + */ + stats(environmentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/environments/${environmentID}/work/stats?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Note: these endpoints are called automatically by the pre-built environment + * worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted + * sandbox environments. They are included here as a reference; you do not need to + * invoke them directly. + * + * Stop a work item, initiating graceful or forced shutdown. + * + * @example + * ```ts + * const betaSelfHostedWork = + * await client.beta.environments.work.stop('work_id', { + * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * }); + * ``` + */ + stop(workID, params, options) { + const { environment_id, betas, ...body } = params; + return this._client.post(path$2`/v1/environments/${environment_id}/work/${workID}/stop?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Continuously claim work from a self-hosted environment, ack each item, + * and yield it. Posts `stop` automatically when the consumer's loop body + * returns or when iteration ends. + * + * @example + * ```ts + * for await (const work of client.beta.environments.work.poller({ + * environmentId, + * environmentKey, + * })) { + * if (work.data.type !== 'session') continue; + * // ...service the work... + * } + * ``` + */ + poller(opts) { + return new WorkPoller({ + ...opts, + client: this._client + }); + } + /** + * The self-hosted environment runner: poll for work, and for each claimed + * session set up the workdir, download the agent's skills, run the tools while + * heartbeating the lease, and force-stop on exit. + * + * @example + * ```ts + * // Long-running daemon — poll, serve each session, loop: + * await client.beta.environments.work + * .worker({ environmentId, environmentKey, workdir: '/workspace' }) + * .run(); + * + * // Or service one already-claimed work item (e.g. inside a sandbox spawned + * // by `ant worker poll --on-work`) — handleItem() reads the ANTHROPIC_* env vars: + * await client.beta.environments.work.worker({ workdir: '/workspace' }).handleItem(); + * ``` + */ + worker(opts) { + return new EnvironmentWorker({ + ...opts, + client: this._client + }); + } +}; +Work.WorkPoller = WorkPoller; +Work.EnvironmentWorker = EnvironmentWorker; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/environments/environments.mjs +var Environments = class extends APIResource { + constructor() { + super(...arguments); + this.work = new Work(this._client); + } + /** + * Create a new environment with the specified configuration. + * + * @example + * ```ts + * const betaEnvironment = + * await client.beta.environments.create({ + * name: 'python-data-analysis', + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/environments?beta=true", { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Retrieve a specific environment by ID. + * + * @example + * ```ts + * const betaEnvironment = + * await client.beta.environments.retrieve( + * 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * ); + * ``` + */ + retrieve(environmentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/environments/${environmentID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Update an existing environment's configuration. + * + * @example + * ```ts + * const betaEnvironment = + * await client.beta.environments.update( + * 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * ); + * ``` + */ + update(environmentID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/environments/${environmentID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * List environments with pagination support. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaEnvironment of client.beta.environments.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/environments?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Delete an environment by ID. Returns a confirmation of the deletion. + * + * @example + * ```ts + * const betaEnvironmentDeleteResponse = + * await client.beta.environments.delete( + * 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * ); + * ``` + */ + delete(environmentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path$2`/v1/environments/${environmentID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Archive an environment by ID. Archived environments cannot be used to create new + * sessions. + * + * @example + * ```ts + * const betaEnvironment = + * await client.beta.environments.archive( + * 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * ); + * ``` + */ + archive(environmentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/environments/${environmentID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +Environments.Work = Work; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memories.mjs +var Memories = class extends APIResource { + /** + * Create a memory + * + * @example + * ```ts + * const betaManagedAgentsMemory = + * await client.beta.memoryStores.memories.create( + * 'memory_store_id', + * { content: 'content', path: 'xx' }, + * ); + * ``` + */ + create(memoryStoreID, params, options) { + const { view, betas, ...body } = params; + return this._client.post(path$2`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, { + query: { view }, + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * Retrieve a memory + * + * @example + * ```ts + * const betaManagedAgentsMemory = + * await client.beta.memoryStores.memories.retrieve( + * 'memory_id', + * { memory_store_id: 'memory_store_id' }, + * ); + * ``` + */ + retrieve(memoryID, params, options) { + const { memory_store_id, betas, ...query } = params; + return this._client.get(path$2`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * Update a memory + * + * @example + * ```ts + * const betaManagedAgentsMemory = + * await client.beta.memoryStores.memories.update( + * 'memory_id', + * { memory_store_id: 'memory_store_id' }, + * ); + * ``` + */ + update(memoryID, params, options) { + const { memory_store_id, view, betas, ...body } = params; + return this._client.post(path$2`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { + query: { view }, + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * List memories + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsMemoryListItem of client.beta.memoryStores.memories.list( + * 'memory_store_id', + * )) { + * // ... + * } + * ``` + */ + list(memoryStoreID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * Delete a memory + * + * @example + * ```ts + * const betaManagedAgentsDeletedMemory = + * await client.beta.memoryStores.memories.delete( + * 'memory_id', + * { memory_store_id: 'memory_store_id' }, + * ); + * ``` + */ + delete(memoryID, params, options) { + const { memory_store_id, expected_content_sha256, betas } = params; + return this._client.delete(path$2`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { + query: { expected_content_sha256 }, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-versions.mjs +var MemoryVersions = class extends APIResource { + /** + * Retrieve a memory version + * + * @example + * ```ts + * const betaManagedAgentsMemoryVersion = + * await client.beta.memoryStores.memoryVersions.retrieve( + * 'memory_version_id', + * { memory_store_id: 'memory_store_id' }, + * ); + * ``` + */ + retrieve(memoryVersionID, params, options) { + const { memory_store_id, betas, ...query } = params; + return this._client.get(path$2`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}?beta=true`, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * List memory versions + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsMemoryVersion of client.beta.memoryStores.memoryVersions.list( + * 'memory_store_id', + * )) { + * // ... + * } + * ``` + */ + list(memoryStoreID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/memory_stores/${memoryStoreID}/memory_versions?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * Redact a memory version + * + * @example + * ```ts + * const betaManagedAgentsMemoryVersion = + * await client.beta.memoryStores.memoryVersions.redact( + * 'memory_version_id', + * { memory_store_id: 'memory_store_id' }, + * ); + * ``` + */ + redact(memoryVersionID, params, options) { + const { memory_store_id, betas } = params; + return this._client.post(path$2`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}/redact?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-stores.mjs +var MemoryStores = class extends APIResource { + constructor() { + super(...arguments); + this.memories = new Memories(this._client); + this.memoryVersions = new MemoryVersions(this._client); + } + /** + * Create a memory store + * + * @example + * ```ts + * const betaManagedAgentsMemoryStore = + * await client.beta.memoryStores.create({ name: 'x' }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/memory_stores?beta=true", { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * Retrieve a memory store + * + * @example + * ```ts + * const betaManagedAgentsMemoryStore = + * await client.beta.memoryStores.retrieve( + * 'memory_store_id', + * ); + * ``` + */ + retrieve(memoryStoreID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/memory_stores/${memoryStoreID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * Update a memory store + * + * @example + * ```ts + * const betaManagedAgentsMemoryStore = + * await client.beta.memoryStores.update('memory_store_id'); + * ``` + */ + update(memoryStoreID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/memory_stores/${memoryStoreID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * List memory stores + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsMemoryStore of client.beta.memoryStores.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/memory_stores?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * Delete a memory store + * + * @example + * ```ts + * const betaManagedAgentsDeletedMemoryStore = + * await client.beta.memoryStores.delete('memory_store_id'); + * ``` + */ + delete(memoryStoreID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path$2`/v1/memory_stores/${memoryStoreID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } + /** + * Archive a memory store + * + * @example + * ```ts + * const betaManagedAgentsMemoryStore = + * await client.beta.memoryStores.archive('memory_store_id'); + * ``` + */ + archive(memoryStoreID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/memory_stores/${memoryStoreID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString() }, options?.headers]) + }); + } +}; +MemoryStores.Memories = Memories; +MemoryStores.MemoryVersions = MemoryVersions; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs +var JSONLDecoder = class JSONLDecoder { + constructor(iterator, controller) { + this.iterator = iterator; + this.controller = controller; + } + async *decoder() { + const lineDecoder = new LineDecoder(); + for await (const chunk of this.iterator) for (const line of lineDecoder.decode(chunk)) yield JSON.parse(line); + for (const line of lineDecoder.flush()) yield JSON.parse(line); + } + [Symbol.asyncIterator]() { + return this.decoder(); + } + static fromResponse(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + throw new AnthropicError(`Attempted to iterate over a response with no body`); + } + return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs +var Batches$1 = class extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-opus-4-6', + * }, + * }, + * ], + * }); + * ``` + */ + create(params, options) { + const { betas, user_profile_id, ...body } = params; + return this._client.post("/v1/messages/batches?beta=true", { + body, + ...options, + headers: buildHeaders([{ + "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(), + ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 + }, options?.headers]) + }); + } + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, options?.headers]) + }); + } + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaMessageBatch of client.beta.messages.batches.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/messages/batches?beta=true", Page, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, options?.headers]) + }); + } + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaDeletedMessageBatch = + * await client.beta.messages.batches.delete( + * 'message_batch_id', + * ); + * ``` + */ + delete(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path$2`/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, options?.headers]) + }); + } + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, options?.headers]) + }); + } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatchIndividualResponse = + * await client.beta.messages.batches.results( + * 'message_batch_id', + * ); + * ``` + */ + async results(messageBatchID, params = {}, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + const { betas } = params ?? {}; + return this._client.get(batch.results_url, { + ...options, + headers: buildHeaders([{ + "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(), + Accept: "application/binary" + }, options?.headers]), + stream: true, + __binaryResponse: true + })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/constants.mjs +/** +* Model-specific timeout constraints for non-streaming requests +*/ +var MODEL_NONSTREAMING_TOKENS = { + "claude-opus-4-20250514": 8192, + "claude-opus-4-0": 8192, + "claude-4-opus-20250514": 8192, + "anthropic.claude-opus-4-20250514-v1:0": 8192, + "claude-opus-4@20250514": 8192, + "claude-opus-4-1-20250805": 8192, + "anthropic.claude-opus-4-1-20250805-v1:0": 8192, + "claude-opus-4-1@20250805": 8192 +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs +function getOutputFormat$1(params) { + return params?.output_format ?? params?.output_config?.format; +} +function maybeParseBetaMessage(message, params, opts) { + const outputFormat = getOutputFormat$1(params); + if (!params || !("parse" in (outputFormat ?? {}))) return { + ...message, + content: message.content.map((block) => { + if (block.type === "text") { + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: null, + enumerable: false + }); + return Object.defineProperty(parsedBlock, "parsed", { + get() { + opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); + return null; + }, + enumerable: false + }); + } + return block; + }), + parsed_output: null + }; + return parseBetaMessage(message, params, opts); +} +function parseBetaMessage(message, params, opts) { + let firstParsedOutput = null; + const content = message.content.map((block) => { + if (block.type === "text") { + const parsedOutput = parseBetaOutputFormat(params, block.text); + if (firstParsedOutput === null) firstParsedOutput = parsedOutput; + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: parsedOutput, + enumerable: false + }); + return Object.defineProperty(parsedBlock, "parsed", { + get() { + opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); + return parsedOutput; + }, + enumerable: false + }); + } + return block; + }); + return { + ...message, + content, + parsed_output: firstParsedOutput + }; +} +function parseBetaOutputFormat(params, content) { + const outputFormat = getOutputFormat$1(params); + if (outputFormat?.type !== "json_schema") return null; + try { + if ("parse" in outputFormat) return outputFormat.parse(content); + return JSON.parse(content); + } catch (error) { + throw new AnthropicError(`Failed to parse structured output: ${error}`); + } +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs +var tokenize = (input) => { + let current = 0; + let tokens = []; + while (current < input.length) { + let char = input[current]; + if (char === "\\") { + current++; + continue; + } + if (char === "{") { + tokens.push({ + type: "brace", + value: "{" + }); + current++; + continue; + } + if (char === "}") { + tokens.push({ + type: "brace", + value: "}" + }); + current++; + continue; + } + if (char === "[") { + tokens.push({ + type: "paren", + value: "[" + }); + current++; + continue; + } + if (char === "]") { + tokens.push({ + type: "paren", + value: "]" + }); + current++; + continue; + } + if (char === ":") { + tokens.push({ + type: "separator", + value: ":" + }); + current++; + continue; + } + if (char === ",") { + tokens.push({ + type: "delimiter", + value: "," + }); + current++; + continue; + } + if (char === "\"") { + let value = ""; + let danglingQuote = false; + char = input[++current]; + while (char !== "\"") { + if (current === input.length) { + danglingQuote = true; + break; + } + if (char === "\\") { + current++; + if (current === input.length) { + danglingQuote = true; + break; + } + value += char + input[current]; + char = input[++current]; + } else { + value += char; + char = input[++current]; + } + } + char = input[++current]; + if (!danglingQuote) tokens.push({ + type: "string", + value + }); + continue; + } + if (char && /\s/.test(char)) { + current++; + continue; + } + let NUMBERS = /[0-9]/; + if (char && NUMBERS.test(char) || char === "-" || char === ".") { + let value = ""; + if (char === "-") { + value += char; + char = input[++current]; + } + while (char && (NUMBERS.test(char) || char === "." || char === "e" || char === "E" || (char === "-" || char === "+") && (value[value.length - 1] === "e" || value[value.length - 1] === "E"))) { + value += char; + char = input[++current]; + } + tokens.push({ + type: "number", + value + }); + continue; + } + let LETTERS = /[a-z]/i; + if (char && LETTERS.test(char)) { + let value = ""; + while (char && LETTERS.test(char)) { + if (current === input.length) break; + value += char; + char = input[++current]; + } + if (value == "true" || value == "false" || value === "null") tokens.push({ + type: "name", + value + }); + else { + current++; + continue; + } + continue; + } + current++; + } + return tokens; +}; +var strip = (tokens) => { + if (tokens.length === 0) return tokens; + let lastToken = tokens[tokens.length - 1]; + switch (lastToken.type) { + case "separator": + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + case "number": + let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; + if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-" || lastCharacterOfLastToken === "+" || lastCharacterOfLastToken === "e" || lastCharacterOfLastToken === "E") { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + case "string": + let tokenBeforeTheLastToken = tokens[tokens.length - 2]; + if (tokenBeforeTheLastToken?.type === "delimiter") { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + break; + case "delimiter": + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + return tokens; +}; +var unstrip = (tokens) => { + let tail = []; + tokens.map((token) => { + if (token.type === "brace") if (token.value === "{") tail.push("}"); + else tail.splice(tail.lastIndexOf("}"), 1); + if (token.type === "paren") if (token.value === "[") tail.push("]"); + else tail.splice(tail.lastIndexOf("]"), 1); + }); + if (tail.length > 0) tail.reverse().map((item) => { + if (item === "}") tokens.push({ + type: "brace", + value: "}" + }); + else if (item === "]") tokens.push({ + type: "paren", + value: "]" + }); + }); + return tokens; +}; +var generate = (tokens) => { + let output = ""; + tokens.map((token) => { + switch (token.type) { + case "string": + output += "\"" + token.value + "\""; + break; + default: + output += token.value; + break; + } + }); + return output; +}; +var partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input))))); +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/message-stream-utils.mjs +var JSON_BUF_PROPERTY = "__json_buf"; +/** +* Copies a tool-use block with an updated `__json_buf`, installing `.input` as +* a memoized getter so the partial-JSON parse happens on first read instead of +* on every delta. +*/ +function withLazyInput(prev, jsonBuf) { + const next = {}; + for (const key of Object.keys(prev)) if (key !== "input") next[key] = prev[key]; + Object.defineProperty(next, JSON_BUF_PROPERTY, { + value: jsonBuf, + enumerable: false, + writable: true + }); + let input; + let parsed = false; + Object.defineProperty(next, "input", { + enumerable: true, + configurable: true, + get() { + if (!parsed) { + input = jsonBuf ? partialParse(jsonBuf) : {}; + parsed = true; + } + return input; + } + }); + return next; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs +var _BetaMessageStream_instances; +var _BetaMessageStream_currentMessageSnapshot; +var _BetaMessageStream_params; +var _BetaMessageStream_connectedPromise; +var _BetaMessageStream_resolveConnectedPromise; +var _BetaMessageStream_rejectConnectedPromise; +var _BetaMessageStream_endPromise; +var _BetaMessageStream_resolveEndPromise; +var _BetaMessageStream_rejectEndPromise; +var _BetaMessageStream_listeners; +var _BetaMessageStream_ended; +var _BetaMessageStream_errored; +var _BetaMessageStream_aborted; +var _BetaMessageStream_catchingPromiseCreated; +var _BetaMessageStream_response; +var _BetaMessageStream_request_id; +var _BetaMessageStream_logger; +var _BetaMessageStream_getFinalMessage; +var _BetaMessageStream_getFinalText; +var _BetaMessageStream_handleError; +var _BetaMessageStream_beginRequest; +var _BetaMessageStream_addStreamEvent; +var _BetaMessageStream_endRequest; +var _BetaMessageStream_accumulateMessage; +var _BetaMessageStream_toolInputParseError; +function tracksToolInput$1(content) { + return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use"; +} +var BetaMessageStream = class BetaMessageStream { + constructor(params, opts) { + _BetaMessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _BetaMessageStream_currentMessageSnapshot.set(this, void 0); + _BetaMessageStream_params.set(this, null); + this.controller = new AbortController(); + _BetaMessageStream_connectedPromise.set(this, void 0); + _BetaMessageStream_resolveConnectedPromise.set(this, () => {}); + _BetaMessageStream_rejectConnectedPromise.set(this, () => {}); + _BetaMessageStream_endPromise.set(this, void 0); + _BetaMessageStream_resolveEndPromise.set(this, () => {}); + _BetaMessageStream_rejectEndPromise.set(this, () => {}); + _BetaMessageStream_listeners.set(this, {}); + _BetaMessageStream_ended.set(this, false); + _BetaMessageStream_errored.set(this, false); + _BetaMessageStream_aborted.set(this, false); + _BetaMessageStream_catchingPromiseCreated.set(this, false); + _BetaMessageStream_response.set(this, void 0); + _BetaMessageStream_request_id.set(this, void 0); + _BetaMessageStream_logger.set(this, void 0); + _BetaMessageStream_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); + if (isAbortError(error)) error = new APIUserAbortError(); + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); + return this._emit("abort", error); + } + if (error instanceof AnthropicError) return this._emit("error", error); + if (error instanceof Error) { + const anthropicError = new AnthropicError(error.message); + anthropicError.cause = error; + return this._emit("error", anthropicError); + } + return this._emit("error", new AnthropicError(String(error))); + }); + __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); + }), "f"); + __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => {}); + __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => {}); + __classPrivateFieldSet(this, _BetaMessageStream_params, params, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f"); + } + get response() { + return __classPrivateFieldGet(this, _BetaMessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); + } + /** + * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, + * returned vie the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * This is the same as the `APIPromise.withResponse()` method. + * + * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` + * as no `Response` is available. + */ + async withResponse() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); + if (!response) throw new Error("Could not resolve a `Response` object"); + return { + data: this, + response, + request_id: response.headers.get("request-id") + }; + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new BetaMessageStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createMessage(messages, params, options, { logger } = {}) { + const runner = new BetaMessageStream(params, { logger }); + for (const message of params.messages) runner._addMessageParam(message); + __classPrivateFieldSet(runner, _BetaMessageStream_params, { + ...params, + stream: true + }, "f"); + runner._run(() => runner._createMessage(messages, { + ...params, + stream: true + }, { + ...options, + headers: { + ...options?.headers, + [STAINLESS_HELPER_METHOD_HEADER]: "stream" + } + })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit("end"); + }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) this._emit("message", message); + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + const { response, data: stream } = await messages.create({ + ...params, + stream: true + }, { + ...options, + signal: this.controller.signal + }).withResponse(); + this._connected(response); + for await (const event of stream) __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) signal.removeEventListener("abort", abortHandler); + } + } + _connected(response) { + if (this.ended) return; + __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit("connect"); + } + get ended() { + return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this MessageStream, so that calls can be chained + */ + on(event, listener) { + (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = [])).push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this MessageStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (!listeners) return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this MessageStream, so that calls can be chained + */ + once(event, listener) { + (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = [])).push({ + listener, + once: true + }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + if (event !== "error") this.once("error", reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); + } + get currentMessage() { + return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + } + /** + * @returns a promise that resolves with the the final assistant Message response, + * or rejects if an error occurred or the stream ended prematurely without producing a Message. + * If structured outputs were used, this will be a ParsedMessage with a `parsed` field. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the the final assistant Message's text response, concatenated + * together if there are more than one text blocks. + * Rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) return; + if (event === "end") { + __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === "abort") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + return; + } + if (event === "error") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + } + } + _emitFinal() { + if (this.receivedMessages.at(-1)) this._emit("finalMessage", __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + this._connected(null); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) signal.removeEventListener("abort", abortHandler); + } + } + [(_BetaMessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_params = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_listeners = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_ended = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_errored = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_aborted = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_response = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_request_id = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_logger = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_handleError = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_instances = /* @__PURE__ */ new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() { + if (this.receivedMessages.length === 0) throw new AnthropicError("stream ended without producing a Message with role=assistant"); + return this.receivedMessages.at(-1); + }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() { + if (this.receivedMessages.length === 0) throw new AnthropicError("stream ended without producing a Message with role=assistant"); + const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); + if (textBlocks.length === 0) throw new AnthropicError("stream ended without producing a content block with type=text"); + return textBlocks.join(" "); + }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() { + if (this.ended) return; + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f"); + }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) { + if (this.ended) return; + const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); + this._emit("streamEvent", event, messageSnapshot); + switch (event.type) { + case "content_block_delta": { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case "text_delta": + if (content.type === "text") this._emit("text", event.delta.text, content.text || ""); + break; + case "citations_delta": + if (content.type === "text") this._emit("citation", event.delta.citation, content.citations ?? []); + break; + case "input_json_delta": + if (tracksToolInput$1(content) && __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f").inputJson?.length) { + let jsonSnapshot; + try { + jsonSnapshot = content.input; + } catch (err) { + __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_toolInputParseError).call(this, content, err)); + break; + } + this._emit("inputJson", event.delta.partial_json, jsonSnapshot); + } + break; + case "thinking_delta": + if (content.type === "thinking") this._emit("thinking", event.delta.thinking, content.thinking); + break; + case "signature_delta": + if (content.type === "thinking") this._emit("signature", content.signature); + break; + case "compaction_delta": + if (content.type === "compaction" && content.content) this._emit("compaction", content.content); + break; + default: event.delta; + } + break; + } + case "message_stop": + this._addMessageParam(messageSnapshot); + this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true); + break; + case "content_block_stop": + this._emit("contentBlock", messageSnapshot.content.at(-1)); + break; + case "message_start": + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + case "content_block_start": + case "message_delta": break; + } + }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() { + if (this.ended) throw new AnthropicError(`stream has ended, this shouldn't happen`); + const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (!snapshot) throw new AnthropicError(`request ended without sending any chunks`); + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f"); + return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }); + }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) { + let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (event.type === "message_start") { + if (snapshot) throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + return event.message; + } + if (!snapshot) throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + switch (event.type) { + case "message_stop": return snapshot; + case "message_delta": + snapshot.container = event.delta.container; + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + if (event.delta.stop_details != null) snapshot.stop_details = event.delta.stop_details; + snapshot.usage.output_tokens = event.usage.output_tokens; + snapshot.context_management = event.context_management; + if (event.usage.input_tokens != null) snapshot.usage.input_tokens = event.usage.input_tokens; + if (event.usage.cache_creation_input_tokens != null) snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + if (event.usage.cache_read_input_tokens != null) snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + if (event.usage.server_tool_use != null) snapshot.usage.server_tool_use = event.usage.server_tool_use; + if (event.usage.iterations != null) snapshot.usage.iterations = event.usage.iterations; + if (event.usage.fallback_credit != null) snapshot.usage.fallback_credit = event.usage.fallback_credit; + return snapshot; + case "content_block_start": + snapshot.content.push(event.content_block); + if (event.content_block.type === "fallback") snapshot.model = event.content_block.to.model; + return snapshot; + case "content_block_delta": { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case "text_delta": + if (snapshotContent?.type === "text") snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || "") + event.delta.text + }; + break; + case "citations_delta": + if (snapshotContent?.type === "text") snapshot.content[event.index] = { + ...snapshotContent, + citations: [...snapshotContent.citations ?? [], event.delta.citation] + }; + break; + case "input_json_delta": + if (snapshotContent && tracksToolInput$1(snapshotContent)) { + const jsonBuf = (snapshotContent["__json_buf"] || "") + event.delta.partial_json; + snapshot.content[event.index] = withLazyInput(snapshotContent, jsonBuf); + } + break; + case "thinking_delta": + if (snapshotContent?.type === "thinking") snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking + }; + break; + case "signature_delta": + if (snapshotContent?.type === "thinking") snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature + }; + break; + case "compaction_delta": + if (snapshotContent?.type === "compaction") snapshot.content[event.index] = { + ...snapshotContent, + content: (snapshotContent.content || "") + event.delta.content, + encrypted_content: event.delta.encrypted_content + }; + break; + default: event.delta; + } + return snapshot; + } + case "content_block_stop": { + const snapshotContent = snapshot.content.at(event.index); + if (snapshotContent && tracksToolInput$1(snapshotContent) && "__json_buf" in snapshotContent) { + let input; + try { + input = snapshotContent.input; + } catch (err) { + input = {}; + __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_toolInputParseError).call(this, snapshotContent, err)); + } + Object.defineProperty(snapshotContent, "input", { + value: input, + enumerable: true, + configurable: true, + writable: true + }); + } + return snapshot; + } + } + }, _BetaMessageStream_toolInputParseError = function _BetaMessageStream_toolInputParseError(block, err) { + const jsonBuf = block[JSON_BUF_PROPERTY]; + return new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("streamEvent", (event) => { + const reader = readQueue.shift(); + if (reader) reader.resolve(event); + else pushQueue.push(event); + }); + 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((chunk) => chunk ? { + value: chunk, + done: false + } : { + value: void 0, + done: true + }); + } + return { + value: pushQueue.shift(), + done: false + }; + }, + return: async () => { + this.abort(); + return { + value: void 0, + done: true + }; + } + }; + } + toReadableStream() { + return new Stream(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream(); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/internal/utils/promise.mjs +/** +* A deferred: a `Promise` together with its `resolve` / `reject` functions. +* This is `Promise.withResolvers()`, which is not available in all supported +* runtimes. +*/ +function promiseWithResolvers() { + let resolve; + let reject; + return { + promise: new Promise((res, rej) => { + resolve = res; + reject = rej; + }), + resolve, + reject + }; +} +var DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include: +1. Task Overview +The user's core request and success criteria +Any clarifications or constraints they specified +2. Current State +What has been completed so far +Files created, modified, or analyzed (with paths if relevant) +Key outputs or artifacts produced +3. Important Discoveries +Technical constraints or requirements uncovered +Decisions made and their rationale +Errors encountered and how they were resolved +What approaches were tried that didn't work (and why) +4. Next Steps +Specific actions needed to complete the task +Any blockers or open questions to resolve +Priority order if multiple steps remain +5. Context to Preserve +User preferences or style requirements +Domain-specific details that aren't obvious +Any promises made to the user +Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task. +Wrap your summary in tags.`; +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs +var _BetaToolRunner_instances; +var _BetaToolRunner_consumed; +var _BetaToolRunner_mutated; +var _BetaToolRunner_state; +var _BetaToolRunner_options; +var _BetaToolRunner_message; +var _BetaToolRunner_toolResponse; +var _BetaToolRunner_completion; +var _BetaToolRunner_iterationCount; +var _BetaToolRunner_checkAndCompact; +var _BetaToolRunner_generateToolResponse; +/** +* A ToolRunner handles the automatic conversation loop between the assistant and tools. +* +* A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects +* depending on the streaming configuration. +*/ +var BetaToolRunner = class { + constructor(client, params, options) { + _BetaToolRunner_instances.add(this); + this.client = client; + /** Whether the async iterator has been consumed */ + _BetaToolRunner_consumed.set(this, false); + /** Whether parameters have been mutated since the last API call */ + _BetaToolRunner_mutated.set(this, false); + /** Current state containing the request parameters */ + _BetaToolRunner_state.set(this, void 0); + _BetaToolRunner_options.set(this, void 0); + /** Promise for the last message received from the assistant */ + _BetaToolRunner_message.set(this, void 0); + /** Cached tool response to avoid redundant executions */ + _BetaToolRunner_toolResponse.set(this, void 0); + /** Promise resolvers for waiting on completion */ + _BetaToolRunner_completion.set(this, void 0); + /** Number of iterations (API requests) made so far */ + _BetaToolRunner_iterationCount.set(this, 0); + __classPrivateFieldSet(this, _BetaToolRunner_state, { params: { + ...params, + messages: structuredClone(params.messages) + } }, "f"); + const collected = collectStainlessHelpers(params.tools, params.messages); + __classPrivateFieldSet(this, _BetaToolRunner_options, { + ...options, + headers: buildHeaders([ + helperHeader("BetaToolRunner"), + collected.length ? { [STAINLESS_HELPER_HEADER]: collected.join(", ") } : void 0, + options?.headers + ]) + }, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + if (params.compactionControl?.enabled) console.warn("Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: \"compact_20260112\" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction"); + } + async *[(_BetaToolRunner_consumed = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_mutated = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_state = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_options = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_message = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_toolResponse = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_completion = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_iterationCount = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_instances = /* @__PURE__ */ new WeakSet(), _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact() { + const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl; + if (!compactionControl || !compactionControl.enabled) return false; + let tokensUsed = 0; + if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== void 0) try { + const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + tokensUsed = message.usage.input_tokens + (message.usage.cache_creation_input_tokens ?? 0) + (message.usage.cache_read_input_tokens ?? 0) + message.usage.output_tokens; + } catch { + return false; + } + const threshold = compactionControl.contextTokenThreshold ?? 1e5; + if (tokensUsed < threshold) return false; + const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model; + const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT; + const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages; + if (messages[messages.length - 1].role === "assistant") { + const lastMessage = messages[messages.length - 1]; + if (Array.isArray(lastMessage.content)) { + const nonToolBlocks = lastMessage.content.filter((block) => block.type !== "tool_use"); + if (nonToolBlocks.length === 0) messages.pop(); + else lastMessage.content = nonToolBlocks; + } + } + const response = await this.client.beta.messages.create({ + model, + messages: [...messages, { + role: "user", + content: [{ + type: "text", + text: summaryPrompt + }] + }], + max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens + }, { + signal: __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal, + headers: buildHeaders([__classPrivateFieldGet(this, _BetaToolRunner_options, "f").headers, helperHeader("compaction")]) + }); + if (response.content[0]?.type !== "text") throw new AnthropicError("Expected text response for compaction"); + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [{ + role: "user", + content: response.content + }]; + return true; + }, Symbol.asyncIterator)]() { + var _a; + if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) throw new AnthropicError("Cannot iterate over a consumed stream"); + __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f"); + try { + while (true) { + let stream; + try { + if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) break; + __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a++, _a), "f"); + __classPrivateFieldSet(this, _BetaToolRunner_message, void 0, "f"); + const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + if (params.stream) { + stream = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")); + __classPrivateFieldSet(this, _BetaToolRunner_message, stream.finalMessage(), "f"); + __classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => {}); + yield stream; + } else { + __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ + ...params, + stream: false + }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); + yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + } + if (!await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this)) { + if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { + const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ + role: message.role, + content: message.content + }); + if (message.stop_reason === "refusal") break; + } + const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1)); + if (toolMessage) __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage); + else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) break; + } + } finally { + if (stream) stream.abort(); + } + } + if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) throw new AnthropicError("ToolRunner concluded without a message from the server"); + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")); + } catch (error) { + __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f"); + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => {}); + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + throw error; + } + } + setMessagesParams(paramsOrMutator) { + if (typeof paramsOrMutator === "function") __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params); + else __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator; + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f"); + } + setRequestOptions(optionsOrMutator) { + if (typeof optionsOrMutator === "function") __classPrivateFieldSet(this, _BetaToolRunner_options, optionsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); + else __classPrivateFieldSet(this, _BetaToolRunner_options, { + ...__classPrivateFieldGet(this, _BetaToolRunner_options, "f"), + ...optionsOrMutator + }, "f"); + } + /** + * Get the tool response for the last message from the assistant. + * Avoids redundant tool executions by caching results. + * + * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed + * + * @example + * const toolResponse = await runner.generateToolResponse(); + * if (toolResponse) { + * console.log('Tool results:', toolResponse.content); + * } + */ + async generateToolResponse(signal = __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal) { + const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f") ?? this.params.messages.at(-1); + if (!message) return null; + return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message, signal); + } + /** + * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and + * will wait for an instance to start and go to completion. + * + * @returns A promise that resolves to the final BetaMessage when the iterator completes + * + * @example + * // Start consuming the iterator + * for await (const message of runner) { + * console.log('Message:', message.content); + * } + * + * // Meanwhile, wait for completion from another part of the code + * const finalMessage = await runner.done(); + * console.log('Final response:', finalMessage.content); + */ + done() { + return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise; + } + /** + * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream: + * * If the iterator has not been consumed, consume the entire iterator and return the final message from the + * assistant. + * * If the iterator has been consumed, waits for it to complete and returns the final message. + * + * @returns A promise that resolves to the final BetaMessage from the conversation + * @throws {AnthropicError} If no messages were processed during the conversation + * + * @example + * const finalMessage = await runner.runUntilDone(); + * console.log('Final response:', finalMessage.content); + */ + async runUntilDone() { + if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) for await (const _ of this); + return this.done(); + } + /** + * Get the current parameters being used by the ToolRunner. + * + * @returns A readonly view of the current ToolRunnerParams + * + * @example + * const currentParams = runner.params; + * console.log('Current model:', currentParams.model); + * console.log('Message count:', currentParams.messages.length); + */ + get params() { + return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + } + /** + * Add one or more messages to the conversation history. + * + * @param messages - One or more BetaMessageParam objects to add to the conversation + * + * @example + * runner.pushMessages( + * { role: 'user', content: 'Also, what about the weather in NYC?' } + * ); + * + * @example + * // Adding multiple messages + * runner.pushMessages( + * { role: 'user', content: 'What about NYC?' }, + * { role: 'user', content: 'And Boston?' } + * ); + */ + pushMessages(...messages) { + this.setMessagesParams((params) => ({ + ...params, + messages: [...params.messages, ...messages] + })); + } + /** + * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone() + * This allows using `await runner` instead of `await runner.runUntilDone()` + */ + then(onfulfilled, onrejected) { + return this.runUntilDone().then(onfulfilled, onrejected); + } +}; +_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse(lastMessage, signal = __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal) { + if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== void 0) return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage, { + ...__classPrivateFieldGet(this, _BetaToolRunner_options, "f"), + signal + }), "f"); + return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); +}; +async function generateToolResponse(params, lastMessage = params.messages.at(-1), requestOptions) { + if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") return null; + const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use"); + if (toolUseBlocks.length === 0) return null; + const available = availableToolNames(params); + return { + role: "user", + content: await Promise.all(toolUseBlocks.map(async (toolUse) => { + const tool = params.tools.find((t) => ("name" in t ? t.name : t.mcp_server_name) === toolUse.name); + if (!tool || !("run" in tool) || !available.has(toolUse.name)) return toolNotFoundResult(toolUse); + try { + let input = toolUse.input; + if ("parse" in tool && tool.parse) input = tool.parse(input); + const result = await tool.run(input, { + toolUse, + toolUseBlock: toolUse, + signal: requestOptions?.signal + }); + return { + type: "tool_result", + tool_use_id: toolUse.id, + content: result + }; + } catch (error) { + return { + type: "tool_result", + tool_use_id: toolUse.id, + content: error instanceof ToolError ? error.content : `Error: ${error instanceof Error ? error.message : String(error)}`, + is_error: true + }; + } + })) + }; +} +function toolNotFoundResult(toolUse) { + return { + type: "tool_result", + tool_use_id: toolUse.id, + content: `Error: Tool '${toolUse.name}' not found`, + is_error: true + }; +} +/** +* Computes the names of locally runnable tools that are still available for the assistant +* turn being answered, by folding `tool_removal` / `tool_addition` blocks from the +* `role: "system"` messages over the runnable tools. The assistant turn being answered is +* terminal-or-absent and only `system` messages are inspected, so folding the whole current +* history is exactly folding the messages preceding that turn — call this before appending +* anything after it. MCP references are ignored — those tools are executed server-side and +* never dispatched by this runner. +*/ +function availableToolNames(params) { + const available = /* @__PURE__ */ new Set(); + for (const tool of params.tools) if ("run" in tool) available.add(tool.name); + for (const message of params.messages) { + if (message.role !== "system" || typeof message.content === "string") continue; + for (const block of message.content) applyToolChange(block, available); + } + return available; +} +function applyToolChange(block, available) { + switch (block.type) { + case "tool_removal": + case "tool_addition": + applyToolReference(block, available); + break; + case "mid_conv_system": + for (const inner of block.content) if (inner.type === "tool_removal" || inner.type === "tool_addition") applyToolReference(inner, available); + break; + default: break; + } +} +function applyToolReference(block, available) { + const name = referencedToolName(block.tool); + if (name === void 0) return; + if (block.type === "tool_removal") available.delete(name); + else available.add(name); +} +function referencedToolName(ref) { + switch (ref.type) { + case "tool_reference": return ref.name; + default: return; + } +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs +var DEPRECATED_MODELS$1 = { + "claude-1.3": "November 6th, 2024", + "claude-1.3-100k": "November 6th, 2024", + "claude-instant-1.1": "November 6th, 2024", + "claude-instant-1.1-100k": "November 6th, 2024", + "claude-instant-1.2": "November 6th, 2024", + "claude-3-sonnet-20240229": "July 21st, 2025", + "claude-3-opus-20240229": "January 5th, 2026", + "claude-2.1": "July 21st, 2025", + "claude-2.0": "July 21st, 2025", + "claude-3-7-sonnet-latest": "February 19th, 2026", + "claude-3-7-sonnet-20250219": "February 19th, 2026", + "claude-3-5-haiku-latest": "February 19th, 2026", + "claude-3-5-haiku-20241022": "February 19th, 2026", + "claude-opus-4-0": "June 15th, 2026", + "claude-opus-4-20250514": "June 15th, 2026", + "claude-sonnet-4-0": "June 15th, 2026", + "claude-sonnet-4-20250514": "June 15th, 2026", + "claude-opus-4-1": "August 5th, 2026", + "claude-opus-4-1-20250805": "August 5th, 2026", + "claude-mythos-preview": "June 30th, 2026" +}; +var MODELS_TO_WARN_WITH_THINKING_ENABLED$1 = ["claude-mythos-preview", "claude-opus-4-6"]; +var Messages$1 = class extends APIResource { + constructor() { + super(...arguments); + this.batches = new Batches$1(this._client); + } + create(params, options) { + const modifiedParams = transformOutputFormat(params); + const { betas, user_profile_id, ...body } = modifiedParams; + if (body.model in DEPRECATED_MODELS$1) console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS$1[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + if (MODELS_TO_WARN_WITH_THINKING_ENABLED$1.includes(body.model) && body.thinking && body.thinking.type === "enabled") console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + const helperHeader = stainlessHelperHeader(body.tools, body.messages); + return this._client.post("/v1/messages?beta=true", { + body, + timeout: timeout ?? 6e5, + ...options, + headers: buildHeaders([ + { + ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0, + ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 + }, + helperHeader, + options?.headers + ]), + stream: modifiedParams.stream ?? false + }); + } + /** + * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and + * the response will be automatically parsed and available in the `parsed_output` property of the message. + * + * @example + * ```ts + * const message = await client.beta.messages.parse({ + * model: 'claude-3-5-sonnet-20241022', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'), + * }); + * + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + parse(params, options) { + options = { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() }, options?.headers]) + }; + return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console })); + } + /** + * Create a Message stream + */ + stream(body, options) { + return BetaMessageStream.createMessage(this, body, options); + } + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. + * + * Learn more about token counting in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting) + * + * @example + * ```ts + * const betaMessageTokensCount = + * await client.beta.messages.countTokens({ + * messages: [{ content: 'Hello, world', role: 'user' }], + * model: 'claude-opus-4-6', + * }); + * ``` + */ + countTokens(params, options) { + const { betas, user_profile_id, ...body } = transformOutputFormat(params); + return this._client.post("/v1/messages/count_tokens?beta=true", { + body, + ...options, + headers: buildHeaders([{ + "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString(), + ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 + }, options?.headers]) + }); + } + toolRunner(body, options) { + return new BetaToolRunner(this._client, body, options); + } +}; +/** +* Transform deprecated output_format to output_config.format +* Returns a modified copy of the params without mutating the original +*/ +function transformOutputFormat(params) { + if (!params.output_format) return params; + if (params.output_config?.format) throw new AnthropicError("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated)."); + const { output_format, ...rest } = params; + return { + ...rest, + output_config: { + ...params.output_config, + format: output_format + } + }; +} +Messages$1.Batches = Batches$1; +Messages$1.BetaToolRunner = BetaToolRunner; +Messages$1.ToolError = ToolError; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/events.mjs +var Events$1 = class extends APIResource { + /** + * List Events + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsSessionEvent of client.beta.sessions.events.list( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * )) { + * // ... + * } + * ``` + */ + list(sessionID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/sessions/${sessionID}/events?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Send Events + * + * @example + * ```ts + * const betaManagedAgentsSendSessionEvents = + * await client.beta.sessions.events.send( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * { + * events: [ + * { + * content: [ + * { + * text: 'Where is my order #1234?', + * type: 'text', + * }, + * ], + * type: 'user.message', + * }, + * ], + * }, + * ); + * ``` + */ + send(sessionID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/sessions/${sessionID}/events?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Stream Events + * + * @example + * ```ts + * const betaManagedAgentsStreamSessionEvents = + * await client.beta.sessions.events.stream( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * ); + * ``` + */ + stream(sessionID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.get(path$2`/v1/sessions/${sessionID}/events/stream?beta=true`, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]), + stream: true + }); + } + /** + * Attach to a session and dispatch every incoming `agent.tool_use` and + * `agent.custom_tool_use` event to a local tool registry, sending the matching + * result back (`user.tool_result` / `user.custom_tool_result`). The + * sessions-side counterpart to `client.beta.messages.toolRunner`: yields one + * entry per completed tool call so callers can observe each dispatch (and + * `break` to abort cleanly). + * + * @example + * ```ts + * import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node'; + * + * for await (const call of client.beta.sessions.events.toolRunner(work.data.id, { + * tools: [...betaAgentToolset20260401({ workdir }), myTool], + * })) { + * console.log(`${call.name} -> ${call.isError ? 'error' : 'ok'}`); + * } + * ``` + */ + toolRunner(sessionID, opts) { + return new SessionToolRunner(sessionID, { + ...opts, + client: this._client + }); + } +}; +Events$1.SessionToolRunner = SessionToolRunner; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/resources.mjs +var Resources = class extends APIResource { + /** + * Get Session Resource + * + * @example + * ```ts + * const resource = + * await client.beta.sessions.resources.retrieve( + * 'sesrsc_011CZkZBJq5dWxk9fVLNcPht', + * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, + * ); + * ``` + */ + retrieve(resourceID, params, options) { + const { session_id, betas } = params; + return this._client.get(path$2`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Update Session Resource + * + * @example + * ```ts + * const resource = + * await client.beta.sessions.resources.update( + * 'sesrsc_011CZkZBJq5dWxk9fVLNcPht', + * { + * session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * authorization_token: 'ghp_exampletoken', + * }, + * ); + * ``` + */ + update(resourceID, params, options) { + const { session_id, betas, ...body } = params; + return this._client.post(path$2`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * List Session Resources + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsSessionResource of client.beta.sessions.resources.list( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * )) { + * // ... + * } + * ``` + */ + list(sessionID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/sessions/${sessionID}/resources?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Delete Session Resource + * + * @example + * ```ts + * const betaManagedAgentsDeleteSessionResource = + * await client.beta.sessions.resources.delete( + * 'sesrsc_011CZkZBJq5dWxk9fVLNcPht', + * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, + * ); + * ``` + */ + delete(resourceID, params, options) { + const { session_id, betas } = params; + return this._client.delete(path$2`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Add Session Resource + * + * @example + * ```ts + * const betaManagedAgentsFileResource = + * await client.beta.sessions.resources.add( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * { + * file_id: 'file_011CNha8iCJcU1wXNR6q4V8w', + * type: 'file', + * }, + * ); + * ``` + */ + add(sessionID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/sessions/${sessionID}/resources?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/events.mjs +var Events = class extends APIResource { + /** + * List Session Thread Events + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsSessionEvent of client.beta.sessions.threads.events.list( + * 'sthr_011CZkZVWa6oIjw0rgXZpnBt', + * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, + * )) { + * // ... + * } + * ``` + */ + list(threadID, params, options) { + const { session_id, betas, ...query } = params; + return this._client.getAPIList(path$2`/v1/sessions/${session_id}/threads/${threadID}/events?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Stream Session Thread Events + * + * @example + * ```ts + * const betaManagedAgentsStreamSessionThreadEvents = + * await client.beta.sessions.threads.events.stream( + * 'sthr_011CZkZVWa6oIjw0rgXZpnBt', + * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, + * ); + * ``` + */ + stream(threadID, params, options) { + const { session_id, betas, ...query } = params; + return this._client.get(path$2`/v1/sessions/${session_id}/threads/${threadID}/stream?beta=true`, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]), + stream: true + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/threads.mjs +var Threads = class extends APIResource { + constructor() { + super(...arguments); + this.events = new Events(this._client); + } + /** + * Get Session Thread + * + * @example + * ```ts + * const betaManagedAgentsSessionThread = + * await client.beta.sessions.threads.retrieve( + * 'sthr_011CZkZVWa6oIjw0rgXZpnBt', + * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, + * ); + * ``` + */ + retrieve(threadID, params, options) { + const { session_id, betas } = params; + return this._client.get(path$2`/v1/sessions/${session_id}/threads/${threadID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * List Session Threads + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsSessionThread of client.beta.sessions.threads.list( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * )) { + * // ... + * } + * ``` + */ + list(sessionID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/sessions/${sessionID}/threads?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Archive Session Thread + * + * @example + * ```ts + * const betaManagedAgentsSessionThread = + * await client.beta.sessions.threads.archive( + * 'sthr_011CZkZVWa6oIjw0rgXZpnBt', + * { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' }, + * ); + * ``` + */ + archive(threadID, params, options) { + const { session_id, betas } = params; + return this._client.post(path$2`/v1/sessions/${session_id}/threads/${threadID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +Threads.Events = Events; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/sessions/sessions.mjs +var Sessions = class extends APIResource { + constructor() { + super(...arguments); + this.events = new Events$1(this._client); + this.resources = new Resources(this._client); + this.threads = new Threads(this._client); + } + /** + * Create Session + * + * @example + * ```ts + * const betaManagedAgentsSession = + * await client.beta.sessions.create({ + * agent: 'agent_011CZkYpogX7uDKUyvBTophP', + * environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW', + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/sessions?beta=true", { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Get Session + * + * @example + * ```ts + * const betaManagedAgentsSession = + * await client.beta.sessions.retrieve( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * ); + * ``` + */ + retrieve(sessionID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/sessions/${sessionID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Update Session + * + * @example + * ```ts + * const betaManagedAgentsSession = + * await client.beta.sessions.update( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * ); + * ``` + */ + update(sessionID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/sessions/${sessionID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * List Sessions + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsSession of client.beta.sessions.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/sessions?beta=true", BidirectionalPageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Delete Session + * + * @example + * ```ts + * const betaManagedAgentsDeletedSession = + * await client.beta.sessions.delete( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * ); + * ``` + */ + delete(sessionID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path$2`/v1/sessions/${sessionID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Archive Session + * + * @example + * ```ts + * const betaManagedAgentsSession = + * await client.beta.sessions.archive( + * 'sesn_011CZkZAtmR3yMPDzynEDxu7', + * ); + * ``` + */ + archive(sessionID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/sessions/${sessionID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +Sessions.Events = Events$1; +Sessions.Resources = Resources; +Sessions.Threads = Threads; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs +var Versions = class extends APIResource { + /** + * Create Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.create( + * 'skill_id', + * { files: [fs.createReadStream('path/to/file')] }, + * ); + * ``` + */ + create(skillID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) + }, this._client, false)); + } + /** + * Get Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.retrieve( + * 'version', + * { skill_id: 'skill_id' }, + * ); + * ``` + */ + retrieve(version, params, options) { + const { skill_id, betas } = params; + return this._client.get(path$2`/v1/skills/${skill_id}/versions/${version}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) + }); + } + /** + * List Skill Versions + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const versionListResponse of client.beta.skills.versions.list( + * 'skill_id', + * )) { + * // ... + * } + * ``` + */ + list(skillID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/skills/${skillID}/versions?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) + }); + } + /** + * Delete Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.delete( + * 'version', + * { skill_id: 'skill_id' }, + * ); + * ``` + */ + delete(version, params, options) { + const { skill_id, betas } = params; + return this._client.delete(path$2`/v1/skills/${skill_id}/versions/${version}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) + }); + } + /** + * Download a skill version's content as a zip archive. + * + * @example + * ```ts + * const response = await client.beta.skills.versions.download( + * 'version', + * { skill_id: 'skill_id' }, + * ); + * + * const content = await response.blob(); + * console.log(content); + * ``` + */ + download(version, params, options) { + const { skill_id, betas } = params; + return this._client.get(path$2`/v1/skills/${skill_id}/versions/${version}/content?beta=true`, { + ...options, + headers: buildHeaders([{ + "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString(), + Accept: "application/binary" + }, options?.headers]), + __binaryResponse: true + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs +var Skills = class extends APIResource { + constructor() { + super(...arguments); + this.versions = new Versions(this._client); + } + /** + * Create Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.create({ + * files: [fs.createReadStream('path/to/file')], + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) + }, this._client, false)); + } + /** + * Get Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.retrieve('skill_id'); + * ``` + */ + retrieve(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) + }); + } + /** + * List Skills + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const skillListResponse of client.beta.skills.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/skills?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) + }); + } + /** + * Delete Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.delete('skill_id'); + * ``` + */ + delete(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path$2`/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, options?.headers]) + }); + } +}; +Skills.Versions = Versions; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/tunnels/certificates.mjs +var Certificates = class extends APIResource { + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Registers a public CA certificate on a tunnel. Anthropic verifies the gateway's + * server certificate against this CA when it terminates the inner TLS session. A + * tunnel holds at most two non-archived certificates. + * + * @example + * ```ts + * const betaTunnelCertificate = + * await client.beta.tunnels.certificates.create( + * 'tunnel_id', + * { ca_certificate_pem: 'ca_certificate_pem' }, + * ); + * ``` + */ + create(tunnelID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/tunnels/${tunnelID}/certificates?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Fetches a tunnel certificate by ID. + * + * @example + * ```ts + * const betaTunnelCertificate = + * await client.beta.tunnels.certificates.retrieve( + * 'certificate_id', + * { tunnel_id: 'tunnel_id' }, + * ); + * ``` + */ + retrieve(certificateID, params, options) { + const { tunnel_id, betas } = params; + return this._client.get(path$2`/v1/tunnels/${tunnel_id}/certificates/${certificateID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Lists the certificates registered on a tunnel. Archived certificates are + * excluded unless include_archived is set. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaTunnelCertificate of client.beta.tunnels.certificates.list( + * 'tunnel_id', + * )) { + * // ... + * } + * ``` + */ + list(tunnelID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/tunnels/${tunnelID}/certificates?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Archives a tunnel certificate, removing it from the set Anthropic trusts for the + * tunnel. The certificate record is retained. Archiving the last non-archived + * certificate is permitted; the tunnel rejects MCP traffic until a new certificate + * is added. + * + * @example + * ```ts + * const betaTunnelCertificate = + * await client.beta.tunnels.certificates.archive( + * 'certificate_id', + * { tunnel_id: 'tunnel_id' }, + * ); + * ``` + */ + archive(certificateID, params, options) { + const { tunnel_id, betas } = params; + return this._client.post(path$2`/v1/tunnels/${tunnel_id}/certificates/${certificateID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/tunnels/tunnels.mjs +var Tunnels = class extends APIResource { + constructor() { + super(...arguments); + this.certificates = new Certificates(this._client); + } + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Creates a tunnel. Creation allocates a fresh hostname and provisions the tunnel; + * it is not idempotent. The new tunnel rejects MCP traffic until at least one CA + * certificate is added. + * + * @example + * ```ts + * const betaTunnel = await client.beta.tunnels.create(); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/tunnels?beta=true", { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Fetches a tunnel by ID. + * + * @example + * ```ts + * const betaTunnel = await client.beta.tunnels.retrieve( + * 'tunnel_id', + * ); + * ``` + */ + retrieve(tunnelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/tunnels/${tunnelID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Lists tunnels. Results are ordered by creation time, newest first; archived + * tunnels are excluded unless include_archived is set. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaTunnel of client.beta.tunnels.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/tunnels?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Archives a tunnel. Archival is irreversible: every non-archived certificate on + * the tunnel is archived in the same operation, the hostname is retired and never + * re-allocated, and the tunnel token is invalidated. Retrying against an + * already-archived tunnel returns the existing record unchanged. + * + * @example + * ```ts + * const betaTunnel = await client.beta.tunnels.archive( + * 'tunnel_id', + * ); + * ``` + */ + archive(tunnelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/tunnels/${tunnelID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Reveals a tunnel's connector token. The value is fetched live on each call; + * Anthropic does not store it. Repeated calls return the same value until the + * token is rotated. Exposed as POST so the token does not appear in intermediary + * access logs. + * + * @example + * ```ts + * const betaTunnelToken = + * await client.beta.tunnels.revealToken('tunnel_id'); + * ``` + */ + revealToken(tunnelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/tunnels/${tunnelID}/reveal_token?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } + /** + * The Tunnels API is in research preview. It requires the + * `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a + * deprecation period. It supersedes the Admin API endpoints at + * `/v1/organizations/tunnels`, which remain available during a migration window. + * + * Rotates a tunnel's connector token. Rotation invalidates the current token for + * new connections and returns a fresh value; established connections are not + * severed. A connector restarted after rotation must use the new value. + * + * @example + * ```ts + * const betaTunnelToken = + * await client.beta.tunnels.rotateToken('tunnel_id'); + * ``` + */ + rotateToken(tunnelID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/tunnels/${tunnelID}/rotate_token?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString() }, options?.headers]) + }); + } +}; +Tunnels.Certificates = Certificates; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/vaults/credentials.mjs +var Credentials = class extends APIResource { + /** + * Create Credential + * + * @example + * ```ts + * const betaManagedAgentsCredential = + * await client.beta.vaults.credentials.create( + * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', + * { + * auth: { + * token: 'bearer_exampletoken', + * mcp_server_url: + * 'https://example-server.modelcontextprotocol.io/sse', + * type: 'static_bearer', + * }, + * }, + * ); + * ``` + */ + create(vaultID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/vaults/${vaultID}/credentials?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Get Credential + * + * @example + * ```ts + * const betaManagedAgentsCredential = + * await client.beta.vaults.credentials.retrieve( + * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', + * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, + * ); + * ``` + */ + retrieve(credentialID, params, options) { + const { vault_id, betas } = params; + return this._client.get(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Update Credential + * + * @example + * ```ts + * const betaManagedAgentsCredential = + * await client.beta.vaults.credentials.update( + * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', + * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, + * ); + * ``` + */ + update(credentialID, params, options) { + const { vault_id, betas, ...body } = params; + return this._client.post(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * List Credentials + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsCredential of client.beta.vaults.credentials.list( + * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', + * )) { + * // ... + * } + * ``` + */ + list(vaultID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path$2`/v1/vaults/${vaultID}/credentials?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Delete Credential + * + * @example + * ```ts + * const betaManagedAgentsDeletedCredential = + * await client.beta.vaults.credentials.delete( + * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', + * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, + * ); + * ``` + */ + delete(credentialID, params, options) { + const { vault_id, betas } = params; + return this._client.delete(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Archive Credential + * + * @example + * ```ts + * const betaManagedAgentsCredential = + * await client.beta.vaults.credentials.archive( + * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', + * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, + * ); + * ``` + */ + archive(credentialID, params, options) { + const { vault_id, betas } = params; + return this._client.post(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Validate Credential + * + * @example + * ```ts + * const betaManagedAgentsCredentialValidation = + * await client.beta.vaults.credentials.mcpOAuthValidate( + * 'vcrd_011CZkZEMt8gZan2iYOQfSkw', + * { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' }, + * ); + * ``` + */ + mcpOAuthValidate(credentialID, params, options) { + const { vault_id, betas } = params; + return this._client.post(path$2`/v1/vaults/${vault_id}/credentials/${credentialID}/mcp_oauth_validate?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/vaults/vaults.mjs +var Vaults = class extends APIResource { + constructor() { + super(...arguments); + this.credentials = new Credentials(this._client); + } + /** + * Create Vault + * + * @example + * ```ts + * const betaManagedAgentsVault = + * await client.beta.vaults.create({ + * display_name: 'Example vault', + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/vaults?beta=true", { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Get Vault + * + * @example + * ```ts + * const betaManagedAgentsVault = + * await client.beta.vaults.retrieve( + * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', + * ); + * ``` + */ + retrieve(vaultID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/vaults/${vaultID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Update Vault + * + * @example + * ```ts + * const betaManagedAgentsVault = + * await client.beta.vaults.update( + * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', + * ); + * ``` + */ + update(vaultID, params, options) { + const { betas, ...body } = params; + return this._client.post(path$2`/v1/vaults/${vaultID}?beta=true`, { + body, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * List Vaults + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaManagedAgentsVault of client.beta.vaults.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/vaults?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Delete Vault + * + * @example + * ```ts + * const betaManagedAgentsDeletedVault = + * await client.beta.vaults.delete( + * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', + * ); + * ``` + */ + delete(vaultID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path$2`/v1/vaults/${vaultID}?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } + /** + * Archive Vault + * + * @example + * ```ts + * const betaManagedAgentsVault = + * await client.beta.vaults.archive( + * 'vlt_011CZkZDLs7fYzm1hXNPeRjv', + * ); + * ``` + */ + archive(vaultID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path$2`/v1/vaults/${vaultID}/archive?beta=true`, { + ...options, + headers: buildHeaders([{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, options?.headers]) + }); + } +}; +Vaults.Credentials = Credentials; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs +var Beta = class extends APIResource { + constructor() { + super(...arguments); + this.models = new Models$1(this._client); + this.messages = new Messages$1(this._client); + this.agents = new Agents(this._client); + this.environments = new Environments(this._client); + this.sessions = new Sessions(this._client); + this.deployments = new Deployments(this._client); + this.deploymentRuns = new DeploymentRuns(this._client); + this.vaults = new Vaults(this._client); + this.memoryStores = new MemoryStores(this._client); + this.files = new Files(this._client); + this.skills = new Skills(this._client); + this.webhooks = new Webhooks(this._client); + this.userProfiles = new UserProfiles(this._client); + this.dreams = new Dreams(this._client); + this.tunnels = new Tunnels(this._client); + } +}; +Beta.Models = Models$1; +Beta.Messages = Messages$1; +Beta.Agents = Agents; +Beta.Environments = Environments; +Beta.Sessions = Sessions; +Beta.Deployments = Deployments; +Beta.DeploymentRuns = DeploymentRuns; +Beta.Vaults = Vaults; +Beta.MemoryStores = MemoryStores; +Beta.Files = Files; +Beta.Skills = Skills; +Beta.Webhooks = Webhooks; +Beta.UserProfiles = UserProfiles; +Beta.Dreams = Dreams; +Beta.Tunnels = Tunnels; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/completions.mjs +var Completions = class extends APIResource { + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/complete", { + body, + timeout: this._client._options.timeout ?? 6e5, + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]), + stream: params.stream ?? false + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/parser.mjs +function getOutputFormat(params) { + return params?.output_config?.format; +} +function maybeParseMessage(message, params, opts) { + const outputFormat = getOutputFormat(params); + if (!params || !("parse" in (outputFormat ?? {}))) return { + ...message, + content: message.content.map((block) => { + if (block.type === "text") return Object.defineProperty({ ...block }, "parsed_output", { + value: null, + enumerable: false + }); + return block; + }), + parsed_output: null + }; + return parseMessage(message, params, opts); +} +function parseMessage(message, params, opts) { + let firstParsedOutput = null; + const content = message.content.map((block) => { + if (block.type === "text") { + const parsedOutput = parseOutputFormat(params, block.text); + if (firstParsedOutput === null) firstParsedOutput = parsedOutput; + return Object.defineProperty({ ...block }, "parsed_output", { + value: parsedOutput, + enumerable: false + }); + } + return block; + }); + return { + ...message, + content, + parsed_output: firstParsedOutput + }; +} +function parseOutputFormat(params, content) { + const outputFormat = getOutputFormat(params); + if (outputFormat?.type !== "json_schema") return null; + try { + if ("parse" in outputFormat) return outputFormat.parse(content); + return JSON.parse(content); + } catch (error) { + throw new AnthropicError(`Failed to parse structured output: ${error}`); + } +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs +var _MessageStream_instances; +var _MessageStream_currentMessageSnapshot; +var _MessageStream_params; +var _MessageStream_connectedPromise; +var _MessageStream_resolveConnectedPromise; +var _MessageStream_rejectConnectedPromise; +var _MessageStream_endPromise; +var _MessageStream_resolveEndPromise; +var _MessageStream_rejectEndPromise; +var _MessageStream_listeners; +var _MessageStream_ended; +var _MessageStream_errored; +var _MessageStream_aborted; +var _MessageStream_catchingPromiseCreated; +var _MessageStream_response; +var _MessageStream_request_id; +var _MessageStream_logger; +var _MessageStream_getFinalMessage; +var _MessageStream_getFinalText; +var _MessageStream_handleError; +var _MessageStream_beginRequest; +var _MessageStream_addStreamEvent; +var _MessageStream_endRequest; +var _MessageStream_accumulateMessage; +function tracksToolInput(content) { + return content.type === "tool_use" || content.type === "server_tool_use"; +} +var MessageStream = class MessageStream { + constructor(params, opts) { + _MessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _MessageStream_currentMessageSnapshot.set(this, void 0); + _MessageStream_params.set(this, null); + this.controller = new AbortController(); + _MessageStream_connectedPromise.set(this, void 0); + _MessageStream_resolveConnectedPromise.set(this, () => {}); + _MessageStream_rejectConnectedPromise.set(this, () => {}); + _MessageStream_endPromise.set(this, void 0); + _MessageStream_resolveEndPromise.set(this, () => {}); + _MessageStream_rejectEndPromise.set(this, () => {}); + _MessageStream_listeners.set(this, {}); + _MessageStream_ended.set(this, false); + _MessageStream_errored.set(this, false); + _MessageStream_aborted.set(this, false); + _MessageStream_catchingPromiseCreated.set(this, false); + _MessageStream_response.set(this, void 0); + _MessageStream_request_id.set(this, void 0); + _MessageStream_logger.set(this, void 0); + _MessageStream_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _MessageStream_errored, true, "f"); + if (isAbortError(error)) error = new APIUserAbortError(); + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); + return this._emit("abort", error); + } + if (error instanceof AnthropicError) return this._emit("error", error); + if (error instanceof Error) { + const anthropicError = new AnthropicError(error.message); + anthropicError.cause = error; + return this._emit("error", anthropicError); + } + return this._emit("error", new AnthropicError(String(error))); + }); + __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); + }), "f"); + __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => {}); + __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => {}); + __classPrivateFieldSet(this, _MessageStream_params, params, "f"); + __classPrivateFieldSet(this, _MessageStream_logger, opts?.logger ?? console, "f"); + } + get response() { + return __classPrivateFieldGet(this, _MessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _MessageStream_request_id, "f"); + } + /** + * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, + * returned vie the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * This is the same as the `APIPromise.withResponse()` method. + * + * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` + * as no `Response` is available. + */ + async withResponse() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); + if (!response) throw new Error("Could not resolve a `Response` object"); + return { + data: this, + response, + request_id: response.headers.get("request-id") + }; + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new MessageStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createMessage(messages, params, options, { logger } = {}) { + const runner = new MessageStream(params, { logger }); + for (const message of params.messages) runner._addMessageParam(message); + __classPrivateFieldSet(runner, _MessageStream_params, { + ...params, + stream: true + }, "f"); + runner._run(() => runner._createMessage(messages, { + ...params, + stream: true + }, { + ...options, + headers: { + ...options?.headers, + [STAINLESS_HELPER_METHOD_HEADER]: "stream" + } + })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit("end"); + }, __classPrivateFieldGet(this, _MessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) this._emit("message", message); + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + const { response, data: stream } = await messages.create({ + ...params, + stream: true + }, { + ...options, + signal: this.controller.signal + }).withResponse(); + this._connected(response); + for await (const event of stream) __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) signal.removeEventListener("abort", abortHandler); + } + } + _connected(response) { + if (this.ended) return; + __classPrivateFieldSet(this, _MessageStream_response, response, "f"); + __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get("request-id"), "f"); + __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit("connect"); + } + get ended() { + return __classPrivateFieldGet(this, _MessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _MessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _MessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this MessageStream, so that calls can be chained + */ + on(event, listener) { + (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = [])).push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this MessageStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (!listeners) return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this MessageStream, so that calls can be chained + */ + once(event, listener) { + (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = [])).push({ + listener, + once: true + }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + if (event !== "error") this.once("error", reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _MessageStream_endPromise, "f"); + } + get currentMessage() { + return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + } + /** + * @returns a promise that resolves with the the final assistant Message response, + * or rejects if an error occurred or the stream ended prematurely without producing a Message. + * If structured outputs were used, this will be a ParsedMessage with a `parsed_output` field. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the the final assistant Message's text response, concatenated + * together if there are more than one text blocks. + * Rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + if (__classPrivateFieldGet(this, _MessageStream_ended, "f")) return; + if (event === "end") { + __classPrivateFieldSet(this, _MessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === "abort") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + return; + } + if (event === "error") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + } + } + _emitFinal() { + if (this.receivedMessages.at(-1)) this._emit("finalMessage", __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + this._connected(null); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) signal.removeEventListener("abort", abortHandler); + } + } + [(_MessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _MessageStream_params = /* @__PURE__ */ new WeakMap(), _MessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_listeners = /* @__PURE__ */ new WeakMap(), _MessageStream_ended = /* @__PURE__ */ new WeakMap(), _MessageStream_errored = /* @__PURE__ */ new WeakMap(), _MessageStream_aborted = /* @__PURE__ */ new WeakMap(), _MessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _MessageStream_response = /* @__PURE__ */ new WeakMap(), _MessageStream_request_id = /* @__PURE__ */ new WeakMap(), _MessageStream_logger = /* @__PURE__ */ new WeakMap(), _MessageStream_handleError = /* @__PURE__ */ new WeakMap(), _MessageStream_instances = /* @__PURE__ */ new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() { + if (this.receivedMessages.length === 0) throw new AnthropicError("stream ended without producing a Message with role=assistant"); + return this.receivedMessages.at(-1); + }, _MessageStream_getFinalText = function _MessageStream_getFinalText() { + if (this.receivedMessages.length === 0) throw new AnthropicError("stream ended without producing a Message with role=assistant"); + const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); + if (textBlocks.length === 0) throw new AnthropicError("stream ended without producing a content block with type=text"); + return textBlocks.join(" "); + }, _MessageStream_beginRequest = function _MessageStream_beginRequest() { + if (this.ended) return; + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f"); + }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) { + if (this.ended) return; + const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); + this._emit("streamEvent", event, messageSnapshot); + switch (event.type) { + case "content_block_delta": { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case "text_delta": + if (content.type === "text") this._emit("text", event.delta.text, content.text || ""); + break; + case "citations_delta": + if (content.type === "text") this._emit("citation", event.delta.citation, content.citations ?? []); + break; + case "input_json_delta": + if (tracksToolInput(content) && __classPrivateFieldGet(this, _MessageStream_listeners, "f").inputJson?.length) this._emit("inputJson", event.delta.partial_json, content.input); + break; + case "thinking_delta": + if (content.type === "thinking") this._emit("thinking", event.delta.thinking, content.thinking); + break; + case "signature_delta": + if (content.type === "thinking") this._emit("signature", content.signature); + break; + default: event.delta; + } + break; + } + case "message_stop": + this._addMessageParam(messageSnapshot); + this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }), true); + break; + case "content_block_stop": + this._emit("contentBlock", messageSnapshot.content.at(-1)); + break; + case "message_start": + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + case "content_block_start": + case "message_delta": break; + } + }, _MessageStream_endRequest = function _MessageStream_endRequest() { + if (this.ended) throw new AnthropicError(`stream has ended, this shouldn't happen`); + const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (!snapshot) throw new AnthropicError(`request ended without sending any chunks`); + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f"); + return maybeParseMessage(snapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }); + }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) { + let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (event.type === "message_start") { + if (snapshot) throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + return event.message; + } + if (!snapshot) throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + switch (event.type) { + case "message_stop": return snapshot; + case "message_delta": + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + if (event.delta.stop_details != null) snapshot.stop_details = event.delta.stop_details; + snapshot.usage.output_tokens = event.usage.output_tokens; + if (event.usage.input_tokens != null) snapshot.usage.input_tokens = event.usage.input_tokens; + if (event.usage.cache_creation_input_tokens != null) snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + if (event.usage.cache_read_input_tokens != null) snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + if (event.usage.server_tool_use != null) snapshot.usage.server_tool_use = event.usage.server_tool_use; + return snapshot; + case "content_block_start": + snapshot.content.push({ ...event.content_block }); + return snapshot; + case "content_block_delta": { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case "text_delta": + if (snapshotContent?.type === "text") snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || "") + event.delta.text + }; + break; + case "citations_delta": + if (snapshotContent?.type === "text") snapshot.content[event.index] = { + ...snapshotContent, + citations: [...snapshotContent.citations ?? [], event.delta.citation] + }; + break; + case "input_json_delta": + if (snapshotContent && tracksToolInput(snapshotContent)) { + const jsonBuf = (snapshotContent["__json_buf"] || "") + event.delta.partial_json; + snapshot.content[event.index] = withLazyInput(snapshotContent, jsonBuf); + } + break; + case "thinking_delta": + if (snapshotContent?.type === "thinking") snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking + }; + break; + case "signature_delta": + if (snapshotContent?.type === "thinking") snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature + }; + break; + default: event.delta; + } + return snapshot; + } + case "content_block_stop": { + const snapshotContent = snapshot.content.at(event.index); + if (snapshotContent && tracksToolInput(snapshotContent) && "__json_buf" in snapshotContent) Object.defineProperty(snapshotContent, "input", { + value: snapshotContent.input, + enumerable: true, + configurable: true, + writable: true + }); + return snapshot; + } + } + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("streamEvent", (event) => { + const reader = readQueue.shift(); + if (reader) reader.resolve(event); + else pushQueue.push(event); + }); + 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((chunk) => chunk ? { + value: chunk, + done: false + } : { + value: void 0, + done: true + }); + } + return { + value: pushQueue.shift(), + done: false + }; + }, + return: async () => { + this.abort(); + return { + value: void 0, + done: true + }; + } + }; + } + toReadableStream() { + return new Stream(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream(); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs +var Batches = class extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-opus-4-6', + * }, + * }, + * ], + * }); + * ``` + */ + create(params, options) { + const { user_profile_id, ...body } = params; + return this._client.post("/v1/messages/batches", { + body, + ...options, + headers: buildHeaders([{ ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 }, options?.headers]) + }); + } + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID, options) { + return this._client.get(path$2`/v1/messages/batches/${messageBatchID}`, options); + } + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const messageBatch of client.messages.batches.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/v1/messages/batches", Page, { + query, + ...options + }); + } + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const deletedMessageBatch = + * await client.messages.batches.delete('message_batch_id'); + * ``` + */ + delete(messageBatchID, options) { + return this._client.delete(path$2`/v1/messages/batches/${messageBatchID}`, options); + } + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, options) { + return this._client.post(path$2`/v1/messages/batches/${messageBatchID}/cancel`, options); + } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatchIndividualResponse = + * await client.messages.batches.results('message_batch_id'); + * ``` + */ + async results(messageBatchID, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + return this._client.get(batch.results_url, { + ...options, + headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), + stream: true, + __binaryResponse: true + })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs +var Messages = class extends APIResource { + constructor() { + super(...arguments); + this.batches = new Batches(this._client); + } + create(params, options) { + const { user_profile_id, ...body } = params; + if (body.model in DEPRECATED_MODELS) console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + if (MODELS_TO_WARN_WITH_THINKING_ENABLED.includes(body.model) && body.thinking && body.thinking.type === "enabled") console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + const helperHeader = stainlessHelperHeader(body.tools, body.messages); + return this._client.post("/v1/messages", { + body, + timeout: timeout ?? 6e5, + ...options, + headers: buildHeaders([ + { ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 }, + helperHeader, + options?.headers + ]), + stream: params.stream ?? false + }); + } + /** + * Send a structured list of input messages with text and/or image content, along with an expected `output_config.format` and + * the response will be automatically parsed and available in the `parsed_output` property of the message. + * + * @example + * ```ts + * const message = await client.messages.parse({ + * model: 'claude-sonnet-4-5-20250929', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_config: { + * format: zodOutputFormat(z.object({ answer: z.number() })), + * }, + * }); + * + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + parse(params, options) { + return this.create(params, options).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console })); + } + /** + * Create a Message stream. + * + * If `output_config.format` is provided with a parseable format (like `zodOutputFormat()`), + * the final message will include a `parsed_output` property with the parsed content. + * + * @example + * ```ts + * const stream = client.messages.stream({ + * model: 'claude-sonnet-4-5-20250929', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_config: { + * format: zodOutputFormat(z.object({ answer: z.number() })), + * }, + * }); + * + * const message = await stream.finalMessage(); + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + stream(body, options) { + return MessageStream.createMessage(this, body, options, { logger: this._client.logger ?? console }); + } + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. + * + * Learn more about token counting in our + * [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting) + * + * @example + * ```ts + * const messageTokensCount = + * await client.messages.countTokens({ + * messages: [{ content: 'Hello, world', role: 'user' }], + * model: 'claude-opus-4-6', + * }); + * ``` + */ + countTokens(params, options) { + const { user_profile_id, ...body } = params; + return this._client.post("/v1/messages/count_tokens", { + body, + ...options, + headers: buildHeaders([{ ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0 }, options?.headers]) + }); + } +}; +var DEPRECATED_MODELS = { + "claude-1.3": "November 6th, 2024", + "claude-1.3-100k": "November 6th, 2024", + "claude-instant-1.1": "November 6th, 2024", + "claude-instant-1.1-100k": "November 6th, 2024", + "claude-instant-1.2": "November 6th, 2024", + "claude-3-sonnet-20240229": "July 21st, 2025", + "claude-3-opus-20240229": "January 5th, 2026", + "claude-2.1": "July 21st, 2025", + "claude-2.0": "July 21st, 2025", + "claude-3-7-sonnet-latest": "February 19th, 2026", + "claude-3-7-sonnet-20250219": "February 19th, 2026", + "claude-3-5-haiku-latest": "February 19th, 2026", + "claude-3-5-haiku-20241022": "February 19th, 2026", + "claude-opus-4-0": "June 15th, 2026", + "claude-opus-4-20250514": "June 15th, 2026", + "claude-sonnet-4-0": "June 15th, 2026", + "claude-sonnet-4-20250514": "June 15th, 2026", + "claude-opus-4-1": "August 5th, 2026", + "claude-opus-4-1-20250805": "August 5th, 2026", + "claude-mythos-preview": "June 30th, 2026" +}; +var MODELS_TO_WARN_WITH_THINKING_ENABLED = ["claude-mythos-preview", "claude-opus-4-6"]; +Messages.Batches = Batches; +//#endregion +//#region node_modules/@anthropic-ai/sdk/resources/models.mjs +var Models = class extends APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path$2`/v1/models/${modelID}`, { + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]) + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/models", Page, { + query, + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/@anthropic-ai/sdk/client.mjs +var _BaseAnthropic_instances; +var _a; +var _BaseAnthropic_encoder; +var _BaseAnthropic_baseURLOverridden; +var HUMAN_PROMPT = "\\n\\nHuman:"; +var AI_PROMPT = "\\n\\nAssistant:"; +/** +* Base class for Anthropic API clients. +*/ +var BaseAnthropic = class { + /** + * The active credential provider. Default credential resolution runs once + * at construction time. If it fails, the error is surfaced on every + * request and the client must be reconstructed — there is no retry path. + * + * Clones returned by {@link withOptions} share the parent's auth state + * (provider, token cache, pending resolution, and any resolution error) + * unless the caller passes an explicit `apiKey`, `authToken`, + * `credentials`, `config`, or `profile` override. + */ + get credentials() { + return this._authState.provider; + } + /** + * API Client for interfacing with the Anthropic API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null] + * @param {string | null | undefined} [opts.webhookKey=process.env['ANTHROPIC_WEBHOOK_SIGNING_KEY'] ?? null] + * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = readEnv("ANTHROPIC_BASE_URL"), apiKey, authToken, webhookKey = readEnv("ANTHROPIC_WEBHOOK_SIGNING_KEY") ?? null, ...opts } = {}) { + _BaseAnthropic_instances.add(this); + this._requestAuthFlags = /* @__PURE__ */ new WeakMap(); + _BaseAnthropic_encoder.set(this, void 0); + if (apiKey === void 0) apiKey = opts.profile != null ? null : readEnv("ANTHROPIC_API_KEY") ?? null; + if (authToken === void 0) authToken = opts.profile != null ? null : readEnv("ANTHROPIC_AUTH_TOKEN") ?? null; + if (opts.profile != null && (opts.credentials != null || opts.config != null)) throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`."); + const options = { + apiKey, + authToken, + webhookKey, + ...opts, + baseURL: baseURL || `https://api.anthropic.com` + }; + if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) throw new AnthropicError("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 Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); + this.baseURL = options.baseURL; + this._baseURLIsExplicit = opts.__baseURLIsExplicit ?? !!baseURL; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", loggerFor(this)) ?? parseLogLevel(readEnv("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", loggerFor(this)) ?? "warn"; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); + this.middleware = [...options.middleware ?? []]; + const customHeadersEnv = readEnv("ANTHROPIC_CUSTOM_HEADERS"); + if (customHeadersEnv) { + const parsed = {}; + for (const line of customHeadersEnv.split("\n")) { + const colon = line.indexOf(":"); + if (colon >= 0) parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim(); + } + options.defaultHeaders = { + ...parsed, + ...options.defaultHeaders + }; + } + const inherited = opts.__auth; + delete options.__auth; + delete options.__baseURLIsExplicit; + this._options = options; + this.apiKey = typeof apiKey === "string" ? apiKey : null; + this.authToken = authToken; + this.webhookKey = webhookKey; + if (inherited) { + this._authState = inherited; + if (!this._baseURLIsExplicit && inherited.baseURL) this.baseURL = inherited.baseURL; + } else { + this._authState = { + provider: null, + tokenCache: null, + resolution: null, + error: null, + extraHeaders: {} + }; + if (this.apiKey == null && this.authToken == null) { + const credentials = options.credentials ?? null; + if (credentials) { + this._authState.provider = credentials; + this._authState.tokenCache = this._makeTokenCache(credentials); + } else if (options.config != null) { + const result = resolveCredentialsFromConfig(options.config, this._credentialResolverOptions()); + this._authState.provider = result.provider; + this._authState.tokenCache = this._makeTokenCache(result.provider); + this._authState.extraHeaders = result.extraHeaders; + this._applyCredentialBaseURL(result.baseURL); + } else if (options.profile != null) this._authState.resolution = this._resolveDefaultCredentials(options.profile); + else if (this._shouldResolveDefaultCredentials()) this._authState.resolution = this._resolveDefaultCredentials(); + } + } + } + /** + * Whether to lazily resolve auth from the default credential chain when no + * explicit auth is configured. Called once from the constructor, so + * overrides must not depend on subclass instance state. Subclasses that + * bring their own auth scheme return false so unrelated local credentials + * are never resolved or allowed to supply a base URL. + */ + _shouldResolveDefaultCredentials() { + return true; + } + /** + * Stores a profile/config-supplied base URL on the shared auth state and, if + * the caller did not pin `baseURL` via constructor option or env, adopts it + * as this client's outbound API host. Precedence: ctor opt > env > profile > + * hardcoded default. + */ + _applyCredentialBaseURL(baseURL) { + if (!baseURL) return; + const normalized = baseURL.replace(/\/+$/, ""); + this._authState.baseURL = normalized; + if (!this._baseURLIsExplicit) this.baseURL = normalized; + } + /** + * Options bag passed into the credential chain. `baseURL` here is only the + * fallback host for the token-exchange POST when the config itself omits + * `base_url`; the chain returns the config's own `base_url` (if any) on + * {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL} + * then adopts for outbound API requests. The two are deliberately decoupled + * so this fallback never round-trips into precedence. + */ + _credentialResolverOptions() { + return { + baseURL: this.baseURL, + fetch: this._credentialsFetch(), + userAgent: this.getUserAgent(), + onCacheWriteError: (err) => { + loggerFor(this).debug("credential cache write failed (best-effort)", err); + }, + onSafetyWarning: (msg) => { + loggerFor(this).warn(msg); + } + }; + } + /** + * A `Fetch` for first-party credential token-exchange requests (OIDC + * federation jwt-bearer grants, user-OAuth refresh grants) that routes + * through this client's middleware chain, so middleware observes token + * traffic like any other request. Only client-level middleware applies: + * a minted token is shared across requests, so attributing the exchange + * to any one request's per-request middleware would be arbitrary. For the + * same reason, `ctx.options` is undefined for these requests. + */ + _credentialsFetch() { + return wrapFetchWithMiddleware(this.fetch, this.middleware, void 0, this); + } + _makeTokenCache(provider) { + return new TokenCache(provider, (err) => { + loggerFor(this).debug("advisory token refresh failed; serving cached token", err); + }); + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const overridesStructuredAuth = "credentials" in options || "config" in options || "profile" in options; + const overridesAuth = "apiKey" in options || "authToken" in options || overridesStructuredAuth; + const internal = { + ...this._options, + ...this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + middleware: this.middleware, + apiKey: this.apiKey, + authToken: this.authToken, + webhookKey: this.webhookKey, + credentials: this.credentials, + ...overridesStructuredAuth ? { + credentials: void 0, + config: void 0, + profile: void 0 + } : {}, + ...options, + __auth: overridesAuth ? void 0 : this._authState, + __baseURLIsExplicit: "baseURL" in options ? true : this._baseURLIsExplicit + }; + return new this.constructor(internal); + } + /** + * Lazily resolves credentials from config files or environment variables. + * Called once from the constructor when no explicit auth is provided, or + * when an explicit `profile` was passed (in which case a missing/unresolved + * profile is surfaced as an error instead of falling through to "no auth"). + * The returned promise is stored and awaited on the first request. + */ + async _resolveDefaultCredentials(profile) { + try { + const result = await defaultCredentials(this._credentialResolverOptions(), profile); + if (result) { + this._authState.provider = result.provider; + this._authState.tokenCache = this._makeTokenCache(result.provider); + this._authState.extraHeaders = result.extraHeaders; + this._applyCredentialBaseURL(result.baseURL); + } else if (profile != null) throw new AnthropicError(`Profile "${profile}" could not be resolved (no /configs/${profile}.json found).`); + } catch (err) { + this._authState.error = err; + } finally { + this._authState.resolution = null; + } + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + if (values.get("x-api-key") || values.get("authorization")) return; + if (this._authState.error) throw this._authState.error; + if (this._authState.tokenCache || this._authState.resolution) return; + if (this.apiKey && values.get("x-api-key")) return; + if (nulls.has("x-api-key")) return; + if (this.authToken && values.get("authorization")) return; + if (nulls.has("authorization")) return; + throw new Error("Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the \"X-Api-Key\" or \"Authorization\" headers to be explicitly omitted"); + } + _authFlags(opts) { + let flags = this._requestAuthFlags.get(opts); + if (!flags) { + flags = { + usedTokenCache: false, + didRefreshFor401: false + }; + this._requestAuthFlags.set(opts, flags); + } + return flags; + } + async authHeaders(opts) { + if (this._authState.resolution) await this._authState.resolution; + if (this._authState.error) return; + if (this._authState.tokenCache && this.apiKey == null) { + const token = await this._authState.tokenCache.getToken(); + this._authFlags(opts).usedTokenCache = true; + return buildHeaders([{ Authorization: `Bearer ${token}` }]); + } + return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); + } + async apiKeyAuth(opts) { + if (this.apiKey == null) return; + return buildHeaders([{ "X-Api-Key": this.apiKey }]); + } + async bearerAuth(opts) { + if (this.authToken == null) return; + return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); + } + stringifyQuery(query) { + return stringifyQuery(query); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + buildURL(path, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL(path) ? new URL(path) : new URL(baseURL + (baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + const pathQuery = Object.fromEntries(url.searchParams); + if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) query = { + ...pathQuery, + ...defaultQuery, + ...query + }; + if (typeof query === "object" && query && !Array.isArray(query)) url.search = this.stringifyQuery(query); + return url.toString(); + } + _calculateNonstreamingTimeout(maxTokens) { + const defaultTimeout = 600; + if (3600 * maxTokens / 128e3 > defaultTimeout) throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details"); + return defaultTimeout * 1e3; + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) {} + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + * + * Runs after all middleware (including {@link backendMiddleware}), + * immediately before each underlying fetch call, so it sees exactly what + * goes over the wire. Middleware may replay a request by calling `next()` + * more than once, so this hook can run multiple times per attempt: + * overrides must be idempotent and overwrite headers from a previous + * invocation rather than append to them. + */ + async prepareRequest(request, { url, options }) { + if (this._authState.tokenCache && this.apiKey == null) { + const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers); + for (const [k, v] of Object.entries(this._authState.extraHeaders)) if (!headers.has(k)) headers.set(k, v); + if (!(headers.get("anthropic-beta")?.split(",").map((s) => s.trim()))?.includes("oauth-2025-04-20")) headers.append("anthropic-beta", OAUTH_API_BETA_HEADER); + request.headers = headers; + } + } + /** + * Internal {@link Middleware} composed innermost in the chain — inside both + * client-level and per-request middleware, immediately around the underlying + * `fetch`. Subclasses for third-party backends override this to adapt the + * canonical Anthropic-shaped request to the backend's wire shape (URL/body + * rewriting, request signing) and to normalize the wire response back to the + * canonical shape (e.g. AWS EventStream to SSE). + * + * Running inside the user's middleware means user middleware always observes + * canonical Anthropic-shaped traffic, and the adaptation re-runs (e.g. + * re-signs) on every `next()` invocation, covering whatever the middleware + * mutated. + * + * Errors thrown here follow the middleware error policy: they propagate to + * the caller as-is — no retries, no `APIConnectionError` wrapping — unless + * retryable (see {@link Middleware}); throw a `RetryableError` to opt into + * the retry path. + */ + backendMiddleware() { + return []; + } + 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((opts) => { + return { + method, + path, + ...opts + }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + this._requestAuthFlags.delete(options); + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); + /** Not an API request ID, just for correlating local log entries. */ + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + if (options.signal?.aborted) throw new APIUserAbortError(); + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller, options, { + requestLogID, + retryOfRequestLogID + }).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + releaseRequestSignal(controller); + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) throw new APIUserAbortError(); + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + const hasMiddleware = this.middleware.length > 0 || !!options.middleware?.length || this.backendMiddleware().length > 0; + if (hasMiddleware && !isTimeout && !isRetryableError(response)) { + loggerFor(this).info(`[${requestLogID}] middleware error (not retryable)`); + loggerFor(this).debug(`[${requestLogID}] middleware error (not retryable)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + throw response; + } + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) throw new APIConnectionTimeoutError(); + if (hasMiddleware && !isFetchOriginError(response)) throw response; + throw new APIConnectionError({ cause: response }); + } + const responseInfo = `[${requestLogID}${retryLogStr}${[...response.headers.entries()].filter(([name]) => name === "request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("")}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response, options); + if (retriesRemaining && shouldRetry) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + releaseRequestSignal(controller); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err) => castToError(err).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + releaseRequestSignal(controller); + throw this.makeStatusError(response.status, errJSON, errMessage, response.headers); + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + armAbandonmentBackstop(response.body ?? response, controller); + return { + response, + options, + controller, + requestLogID, + retryOfRequestLogID, + startTime + }; + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, opts && "then" in opts ? opts.then((opts) => ({ + method: "get", + path, + ...opts + })) : { + method: "get", + path, + ...opts + }); + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise(this, request, Page); + } + async fetchWithTimeout(url, init, ms, controller, requestOptions, logCtx) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) { + signal.addEventListener("abort", abort, { once: true }); + registerRequestSignalCleanup(controller, signal, abort); + } + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) fetchOptions.method = method.toUpperCase(); + const baseFetch = this.fetch; + const timedFetch = async (innerUrl, innerInit) => { + const timeout = setTimeout(abort, ms); + try { + return await baseFetch.call(void 0, innerUrl, innerInit); + } finally { + clearTimeout(timeout); + } + }; + const innerFetch = requestOptions === void 0 ? timedFetch : (async (innerUrl, innerInit = {}) => { + const innerUrlStr = typeof innerUrl === "string" ? innerUrl : innerUrl instanceof URL ? innerUrl.href : innerUrl.url; + innerInit.headers = innerInit.headers instanceof Headers ? innerInit.headers : new Headers(innerInit.headers); + await this.prepareRequest(innerInit, { + url: innerUrlStr, + options: requestOptions + }); + if (logCtx) loggerFor(this).debug(`[${logCtx.requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID: logCtx.retryOfRequestLogID, + method: innerInit.method, + url: innerUrlStr, + options: requestOptions, + headers: innerInit.headers + })); + return timedFetch(innerUrl, innerInit); + }); + const requestMiddleware = requestOptions?.middleware; + const backendMiddleware = this.backendMiddleware(); + return await wrapFetchWithMiddleware(innerFetch, requestMiddleware?.length || backendMiddleware.length ? [ + ...this.middleware, + ...requestMiddleware ?? [], + ...backendMiddleware + ] : this.middleware, requestOptions, this)(url, fetchOptions); + } + async shouldRetry(response, options) { + const flags = this._authFlags(options); + if (response.status === 401 && this._authState.tokenCache && flags.usedTokenCache && !flags.didRefreshFor401) { + flags.didRefreshFor401 = true; + this._authState.tokenCache.invalidate(); + return true; + } + 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, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) timeoutMillis = timeoutMs; + } + const retryAfterHeader = responseHeaders?.get("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 === void 0) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = .5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + return Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay) * (1 - Math.random() * .25) * 1e3; + } + calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { + const maxTime = 3600 * 1e3; + const defaultTime = 600 * 1e3; + if (maxTime * maxTokens / 128e3 > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details"); + return defaultTime; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path, query, defaultBaseURL } = options; + if (this._authState.resolution) await this._authState.resolution; + if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) this.baseURL = this._authState.baseURL; + const url = this.buildURL(path, query, defaultBaseURL); + if ("timeout" in options) validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + return { + req: { + method, + headers: await this.buildHeaders({ + options: inputOptions, + method, + bodyHeaders, + retryCount + }), + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }, + url, + timeout: options.timeout + }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders(), + ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0, + "anthropic-version": "2023-06-01" + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) return { + bodyHeaders: void 0, + body: void 0 + }; + const headers = buildHeaders([rawHeaders]); + if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) return { + bodyHeaders: void 0, + body + }; + else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) return { + bodyHeaders: void 0, + body: ReadableStreamFrom(body) + }; + else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + else return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { + body, + headers + }); + } +}; +_a = BaseAnthropic, _BaseAnthropic_encoder = /* @__PURE__ */ new WeakMap(), _BaseAnthropic_instances = /* @__PURE__ */ new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() { + return this.baseURL !== "https://api.anthropic.com"; +}; +BaseAnthropic.Anthropic = _a; +BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT; +BaseAnthropic.AI_PROMPT = AI_PROMPT; +BaseAnthropic.DEFAULT_TIMEOUT = 6e5; +BaseAnthropic.AnthropicError = AnthropicError; +BaseAnthropic.APIError = APIError; +BaseAnthropic.APIConnectionError = APIConnectionError; +BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError; +BaseAnthropic.APIUserAbortError = APIUserAbortError; +BaseAnthropic.NotFoundError = NotFoundError; +BaseAnthropic.ConflictError = ConflictError; +BaseAnthropic.RateLimitError = RateLimitError; +BaseAnthropic.BadRequestError = BadRequestError; +BaseAnthropic.AuthenticationError = AuthenticationError; +BaseAnthropic.InternalServerError = InternalServerError; +BaseAnthropic.PermissionDeniedError = PermissionDeniedError; +BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError; +BaseAnthropic.toFile = toFile; +/** +* API Client for interfacing with the Anthropic API. +*/ +var Anthropic = class extends BaseAnthropic { + constructor() { + super(...arguments); + this.completions = new Completions(this); + this.messages = new Messages(this); + this.models = new Models(this); + this.beta = new Beta(this); + } +}; +Anthropic.Completions = Completions; +Anthropic.Messages = Messages; +Anthropic.Models = Models; +Anthropic.Beta = Beta; +new TextEncoder(); +//#endregion +//#region node_modules/@anthropic-ai/sdk/lib/transform-json-schema.mjs +var SUPPORTED_STRING_FORMATS = /* @__PURE__ */ new Set([ + "date-time", + "time", + "date", + "duration", + "email", + "hostname", + "uri", + "ipv4", + "ipv6", + "uuid" +]); +function deepClone(obj) { + return JSON.parse(JSON.stringify(obj)); +} +function transformJSONSchema(jsonSchema) { + return _transformJSONSchema(deepClone(jsonSchema)); +} +function _transformJSONSchema(jsonSchema) { + const strictSchema = {}; + const ref = pop(jsonSchema, "$ref"); + if (ref !== void 0) { + strictSchema["$ref"] = ref; + return strictSchema; + } + const defs = pop(jsonSchema, "$defs"); + if (defs !== void 0) { + const strictDefs = {}; + strictSchema["$defs"] = strictDefs; + for (const [name, defSchema] of Object.entries(defs)) strictDefs[name] = _transformJSONSchema(defSchema); + } + const type = pop(jsonSchema, "type"); + const anyOf = pop(jsonSchema, "anyOf"); + const oneOf = pop(jsonSchema, "oneOf"); + const allOf = pop(jsonSchema, "allOf"); + if (Array.isArray(anyOf)) strictSchema["anyOf"] = anyOf.map((variant) => _transformJSONSchema(variant)); + else if (Array.isArray(oneOf)) strictSchema["anyOf"] = oneOf.map((variant) => _transformJSONSchema(variant)); + else if (Array.isArray(allOf)) strictSchema["allOf"] = allOf.map((entry) => _transformJSONSchema(entry)); + else { + if (type === void 0) throw new Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used"); + strictSchema["type"] = type; + } + const description = pop(jsonSchema, "description"); + if (description !== void 0) strictSchema["description"] = description; + const title = pop(jsonSchema, "title"); + if (title !== void 0) strictSchema["title"] = title; + if (type === "object") { + const properties = pop(jsonSchema, "properties") || {}; + strictSchema["properties"] = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [key, _transformJSONSchema(propSchema)])); + pop(jsonSchema, "additionalProperties"); + strictSchema["additionalProperties"] = false; + const required = pop(jsonSchema, "required"); + if (required !== void 0) strictSchema["required"] = required; + } else if (type === "string") { + const format = pop(jsonSchema, "format"); + if (format !== void 0 && SUPPORTED_STRING_FORMATS.has(format)) strictSchema["format"] = format; + else if (format !== void 0) jsonSchema["format"] = format; + } else if (type === "array") { + const items = pop(jsonSchema, "items"); + if (items !== void 0) strictSchema["items"] = _transformJSONSchema(items); + const minItems = pop(jsonSchema, "minItems"); + if (minItems !== void 0 && (minItems === 0 || minItems === 1)) strictSchema["minItems"] = minItems; + else if (minItems !== void 0) jsonSchema["minItems"] = minItems; + } + if (Object.keys(jsonSchema).length > 0) { + const existingDescription = strictSchema["description"]; + strictSchema["description"] = (existingDescription ? existingDescription + "\n\n" : "") + "{" + Object.entries(jsonSchema).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ") + "}"; + } + return strictSchema; +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/helpers/beta/json-schema.mjs +/** +* Creates a Tool with a provided JSON schema that can be passed +* to the `.toolRunner()` method. The schema is used to automatically validate +* the input arguments for the tool. +*/ +function betaTool(options) { + if (options.inputSchema.type !== "object") throw new Error(`JSON schema for tool "${options.name}" must be an object, but got ${options.inputSchema.type}`); + return { + type: "custom", + name: options.name, + input_schema: options.inputSchema, + description: options.description, + run: options.run, + parse: (content) => content, + ...options.close ? { close: options.close } : {} + }; +} +/** `realpath` `p`, or return `p` unchanged when it cannot be resolved. */ +async function realpathOrSelf(p) { + try { + return await fs$2.realpath(p); + } catch { + return p; + } +} +/** +* Fully resolve `abs`: `realpath` the longest existing ancestor and re-append +* the rest, but never re-append a component that is itself a symlink — read the +* link and continue from its target instead. This handles paths being created +* (write/edit) without letting a symlink leaf (e.g. a dangling one pointing +* outside a confinement root) slip through unresolved. +*/ +async function canonicalize(abs) { + const tail = []; + let prefix = abs; + let hops = 0; + for (;;) { + let real; + try { + real = await fs$2.realpath(prefix); + } catch { + let isLink = false; + try { + isLink = (await fs$2.lstat(prefix)).isSymbolicLink(); + } catch {} + if (isLink) { + if (++hops > 40) throw new ToolError(`path ${JSON.stringify(abs)} has too many levels of symbolic links`); + prefix = path$1.resolve(path$1.dirname(prefix), await fs$2.readlink(prefix)); + continue; + } + const parent = path$1.dirname(prefix); + if (parent === prefix) return abs; + tail.push(path$1.basename(prefix)); + prefix = parent; + continue; + } + return tail.length ? path$1.join(real, ...tail.reverse()) : real; + } +} +/** +* Resolve `p` and confine it to `root`. +* +* Absolute and relative inputs go through the same canonicalise-then-contain +* check — an absolute path that lands inside `root` is permitted, only paths +* that resolve *outside* are rejected. Every symlink in `p` (including the +* leaf, even a dangling one) is resolved before the confinement check, and the +* resolved path is what the caller then operates on, so a symlink inside `root` +* that points outside it can neither pass the check nor be followed afterwards. +* +* Residual TOCTOU: a component could still be swapped for a symlink between this +* call and the eventual `fs` operation. Closing that fully needs per-component +* `O_NOFOLLOW`/`openat`, which Node does not expose ergonomically; this is why a +* sandbox is still recommended for the toolset as a whole. +*/ +async function confineToRoot(root, p, opts) { + const allowOutside = opts?.allowOutside ?? false; + const realRoot = await realpathOrSelf(path$1.resolve(root)); + const abs = path$1.resolve(realRoot, p); + if (allowOutside) return abs; + const real = await canonicalize(abs); + if (real !== realRoot && !real.startsWith(realRoot + path$1.sep)) throw new ToolError(`path ${JSON.stringify(p)} escapes workdir`); + return real; +} +/** +* Atomically write `content` to `targetPath`: write a sibling temp file, fsync +* it, then rename over the target. The rename is atomic on most filesystems, so +* a crash mid-write never leaves the target half-written. +*/ +async function atomicWriteFile(targetPath, content) { + const dir = path$1.dirname(targetPath); + const tempPath = path$1.join(dir, `.tmp-${process.pid}-${randomUUID()}`); + let handle; + try { + handle = await fs$2.open(tempPath, "wx", 420); + await handle.writeFile(content, "utf-8"); + await handle.sync(); + await handle.close(); + handle = void 0; + await fs$2.rename(tempPath, targetPath); + } catch (err) { + if (handle) await handle.close().catch(() => {}); + await fs$2.unlink(tempPath).catch(() => {}); + throw err; + } +} +/** +* Map a thrown filesystem error to a consistent, language-independent message, +* so the model sees the same wording regardless of the runtime (Node's raw +* `ENOENT: no such file...` text would otherwise leak through). Falls back to +* the raw error message for codes we don't special-case. +*/ +function fsErrorMessage(err, file) { + switch (err?.code) { + case "ENOENT": return `${file}: no such file or directory`; + case "EACCES": + case "EPERM": return `${file}: permission denied`; + case "ENOTDIR": return `${file}: not a directory`; + case "EISDIR": return `${file}: is a directory`; + case "ELOOP": return `${file}: too many levels of symbolic links`; + case "ENAMETOOLONG": return `${file}: file name too long`; + case "ENOSPC": return `${file}: no space left on device`; + case "EMFILE": + case "ENFILE": return `${file}: too many open files`; + default: return `${file}: ${err instanceof Error ? err.message : String(err)}`; + } +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/tools/agent-toolset/skills.mjs +/** +* Node-only skill plumbing for the agent toolset: downloading a session +* agent's skills into the workdir and extracting the archives. Kept in its own +* file because it is a distinct concern from the tool implementations in +* `node.ts` — distinct enough, and large enough, to review on its own. +*/ +var execFileAsync = promisify(execFile); +/** +* Download the session agent's skills into `{ctx.workdir}/skills//`. +* +* No-op (returns a no-op cleanup) unless both `ctx.client` and `ctx.sessionId` +* are set. Looks up the session's resolved agent and, for each skill, fetches +* its files via `client.beta.skills.versions.download` and extracts the archive +* (a zip or tar.* archive) into a directory named after the skill. A failure on +* one skill is logged and does not block the others. Call this before starting +* the session tool runner (e.g. right after the bash session / workdir is +* ready). +* +* Returns a cleanup function that removes the skill directories this call +* created — call it once the work item is done so downloaded skills do not +* accumulate in the workdir across sessions. +*/ +async function setupSkills(ctx) { + const { client, sessionId } = ctx; + if (!client || !sessionId) return async () => {}; + const log = loggerFor(client); + const session = await client.beta.sessions.retrieve(sessionId); + const skillsRoot = path$1.resolve(ctx.workdir, "skills"); + const created = []; + for (const skill of session.agent.skills) try { + const versionId = await resolveSkillVersion(client, skill.skill_id, skill.version); + const version = await client.beta.skills.versions.retrieve(versionId, { skill_id: skill.skill_id }); + let dirname = path$1.basename(version.name.trim()); + if (dirname === "" || dirname === "." || dirname === "..") dirname = skill.skill_id; + const dest = path$1.resolve(skillsRoot, dirname); + if (dest !== skillsRoot && !dest.startsWith(skillsRoot + path$1.sep)) { + log.warn("skill name escapes the skills dir; skipping", { + component: "agent-tool-context", + name: version.name + }); + continue; + } + const resp = await client.beta.skills.versions.download(versionId, { skill_id: skill.skill_id }); + await fs$2.rm(dest, { + recursive: true, + force: true + }); + await fs$2.mkdir(dest, { + recursive: true, + mode: 493 + }); + created.push(dest); + await extractSkillArchive(resp, dest); + log.info("downloaded skill", { + component: "agent-tool-context", + skill_id: skill.skill_id, + version: versionId, + dest + }); + } catch (e) { + log.warn("failed to download skill", { + component: "agent-tool-context", + skill_id: skill.skill_id, + error: String(e) + }); + } + return async () => { + for (const dest of created) await fs$2.rm(dest, { + recursive: true, + force: true + }).catch((e) => { + log.warn("failed to clean up skill", { + component: "agent-tool-context", + dest, + error: String(e) + }); + }); + }; +} +/** +* Resolve `version` to the concrete numeric timestamp the +* `/v1/skills/{id}/versions/{version}` endpoints require — `session.agent.skills[].version` +* can be an alias such as `"latest"`, which those endpoints reject. Numeric +* versions pass through unchanged. +*/ +async function resolveSkillVersion(client, skillId, version) { + if (/^\d+$/.test(version)) return version; + let newest; + for await (const v of client.beta.skills.versions.list(skillId)) if (/^\d+$/.test(v.version) && (newest === void 0 || BigInt(v.version) > BigInt(newest))) newest = v.version; + if (newest === void 0) throw new AnthropicError(`skill ${JSON.stringify(skillId)} has no concrete version to resolve ${JSON.stringify(version)} against`); + return newest; +} +/** Reject archive members that are absolute or contain a `..` component. */ +function assertSafeMemberNames(names) { + for (const raw of names.split("\n")) { + const entry = raw.trim(); + if (!entry) continue; + if (path$1.isAbsolute(entry) || entry.split(/[\\/]/).includes("..")) throw new AnthropicError(`refusing to extract unsafe archive member: ${entry}`); + } +} +/** +* Reject archives that contain anything other than regular files and +* directories. The type char is the first byte of each `ls`-style line emitted +* by `tar -tvf` / `unzip -Z`: `-` file, `d` dir, `l` symlink, `h` hardlink, +* `b`/`c` device, `p` fifo, `s` socket. A symlink/hardlink member is how an +* archive escapes its extraction dir even when no name contains `..`. +*/ +function assertNoSpecialMembers(verboseListing) { + for (const line of verboseListing.split("\n")) { + const type = line.trimStart()[0]; + if (type === "l" || type === "h" || type === "b" || type === "c" || type === "p" || type === "s") throw new AnthropicError("refusing to extract archive with symlink/hardlink/device member"); + } +} +/** +* Run an archive CLI (`unzip` for zip archives, `tar` for everything else), +* returning its stdout. Both binaries must be on `PATH`; a missing one would +* otherwise surface as an opaque `ENOENT` spawn failure, so it is turned into a +* clear, specific error naming the missing command. +*/ +async function runArchiveTool(cmd, args) { + try { + const { stdout } = await execFileAsync(cmd, args); + return stdout; + } catch (e) { + if (e != null && typeof e === "object" && e.code === "ENOENT") throw new AnthropicError(`skill extraction requires the \`${cmd}\` command, but it was not found on PATH`); + throw e; + } +} +/** +* The single top-level directory shared by every entry in a newline-separated +* archive listing, or `''` if entries don't all live under one common +* directory. Skill bundles are packaged wrapped in one directory named after +* the skill (e.g. `pdf/SKILL.md`, `pdf/scripts/...`); the extractor strips it +* so contents land directly in the skill's dir instead of a redundant nested +* `//` level. A flat or multi-root archive yields `''`. +*/ +function archiveTopDir(listing) { + let top; + let nested = false; + for (const raw of listing.split("\n")) { + const parts = raw.trim().split("/").filter((p) => p !== "" && p !== "."); + if (parts.length === 0) continue; + const first = parts[0]; + if (top === void 0) top = first; + else if (first !== top) return ""; + if (parts.length > 1) nested = true; + } + return top !== void 0 && nested ? top : ""; +} +/** +* Extract a skill download (a zip or tar.* archive) into `dest`. Streams the +* response body straight to a temp file beside `dest` (so the whole archive is +* never buffered in memory — skills can contain large binaries), then shells out +* to `unzip`/`tar` — consistent with the rest of the toolset, which already +* invokes `bash` and `rg`. Both `unzip` and `tar` must be available on `PATH`; a +* missing binary surfaces as a clear error (see {@link runArchiveTool}). Refuses +* any member that would escape `dest` (zip-slip / tar-slip), including +* symlink/hardlink members: skill archives come from the API, but skills can be +* third-party. +* +* The skill bundle's single wrapper directory is stripped: the archive is +* extracted into a staging dir and the wrapper's contents are promoted into +* `dest`, so files land at `dest/SKILL.md` rather than a doubled +* `dest//SKILL.md` (`unzip` has no `--strip-components`, so this is +* done uniformly by staging + promote rather than per-tool flags). +*/ +async function extractSkillArchive(resp, dest) { + const tmp = path$1.join(dest, `.skill-archive-${process.pid}-${Date.now()}`); + if (!resp.body) throw new AnthropicError("skill download response had no body"); + await pipeline(Readable.fromWeb(resp.body), fssync.createWriteStream(tmp)); + const stage = path$1.join(path$1.dirname(dest), `.skill-stage-${process.pid}-${Date.now()}`); + try { + const head = await readHead(tmp, 4); + const isZip = head.length >= 4 && head[0] === 80 && head[1] === 75 && head[2] === 3 && head[3] === 4; + const archiveCmd = isZip ? "unzip" : "tar"; + const listing = await runArchiveTool(archiveCmd, isZip ? ["-Z1", tmp] : ["-tf", tmp]); + assertSafeMemberNames(listing); + assertNoSpecialMembers(await runArchiveTool(archiveCmd, isZip ? ["-Z", tmp] : ["-tvf", tmp])); + const top = archiveTopDir(listing); + await fs$2.mkdir(stage, { + recursive: true, + mode: 493 + }); + await runArchiveTool(archiveCmd, isZip ? [ + "-oq", + tmp, + "-d", + stage + ] : [ + "-xf", + tmp, + "-C", + stage + ]); + const srcRoot = top ? path$1.join(stage, top) : stage; + for (const entry of await fs$2.readdir(srcRoot)) await fs$2.rename(path$1.join(srcRoot, entry), path$1.join(dest, entry)); + } finally { + await fs$2.rm(tmp, { force: true }); + await fs$2.rm(stage, { + recursive: true, + force: true + }); + } +} +/** Read the first `n` bytes of `file`. */ +async function readHead(file, n) { + const handle = await fs$2.open(file, "r"); + try { + const buf = Buffer.alloc(n); + const { bytesRead } = await handle.read(buf, 0, n, 0); + return buf.subarray(0, bytesRead); + } finally { + await handle.close(); + } +} +//#endregion +//#region node_modules/@anthropic-ai/sdk/tools/agent-toolset/node.mjs +var node_exports = /* @__PURE__ */ __exportAll({ + BashSession: () => BashSession, + betaAgentToolset20260401: () => betaAgentToolset20260401, + betaBashTool: () => betaBashTool, + betaEditTool: () => betaEditTool, + betaGlobTool: () => betaGlobTool, + betaGrepTool: () => betaGrepTool, + betaReadTool: () => betaReadTool, + betaWriteTool: () => betaWriteTool, + resolvePath: () => resolvePath, + setupSkills: () => setupSkills +}); +/** +* Node implementation of the `agent_toolset_20260401` tools — `bash`, `read`, +* `write`, `edit`, `glob`, `grep` — plus the workdir/skills +* {@link AgentToolContext}. +* +* This mirrors `@anthropic-ai/sdk/tools/memory/node`: it is the explicit, +* Node-only entry point for these implementations. Importing it pulls in +* `node:child_process`, `node:fs`, etc., so it is kept separate from the rest of +* the SDK — depending on it is an opt-in. +* +* **Node 22+ is required** for this module: the `glob` tool uses the native +* `fs.glob`, added in Node 22. The rest of the SDK still supports Node 18+; only +* the agent toolset has this requirement. +* +* The result of {@link betaAgentToolset20260401} is a plain `BetaRunnableTool[]`; +* hand it to any tool runner — `client.beta.messages.toolRunner({ …, tools })` +* for the Messages API, or `client.beta.sessions.events.toolRunner({ …, tools })` +* for a managed-agents session: +* +* ```ts +* import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node'; +* +* const tools = betaAgentToolset20260401({ workdir: '/work' }); +* const tools2 = betaAgentToolset20260401({ workdir: '/work' }).filter((t) => t.name !== 'bash'); +* ``` +* +* Trust model: the file tools confine to `workdir` (symlink-aware) and are safe +* without a sandbox; `bash` is unrestricted and should run inside one. See +* {@link AgentToolContext}. +*/ +var _BashSession_instances; +var _BashSession_proc; +var _BashSession_buf; +var _BashSession_truncated; +var _BashSession_closed; +var _BashSession_waiting; +var _BashSession_append; +var BASH_OUTPUT_LIMIT = 100 * 1024; +var BASH_DEFAULT_TIMEOUT_MS = 12e4; +var DEFAULT_MAX_FILE_BYTES = 256 * 1024; +var GREP_OUTPUT_LIMIT = 100 * 1024; +var GREP_MAX_LINE_LENGTH = 2e3; +var GLOB_RESULT_LIMIT = 200; +var ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g; +var fsGlob = fs$2.glob; +function resolveMaxBytes(configured) { + return configured === void 0 ? DEFAULT_MAX_FILE_BYTES : configured; +} +/** +* Returns the `agent_toolset_20260401` implementations bound to `ctx`. The +* result is a plain array of `BetaRunnableTool`; filter or extend it before +* handing it to a tool runner: +* +* ```ts +* const tools = [...betaAgentToolset20260401(ctx), myCustomTool]; +* const tools = betaAgentToolset20260401(ctx).filter((t) => t.name !== 'grep'); +* ``` +* +* Concurrency note: `client.beta.sessions.events.toolRunner` dispatches a +* session's tool calls serially (the sessions API delivers one `agent.tool_use` +* at a time). `client.beta.messages.toolRunner` runs a turn's `tool.run` calls +* via `Promise.all`. The toolset below is safe under either model — +* {@link betaBashTool} serializes its persistent shell internally and the FS +* tools are independent per call — but {@link betaEditTool}/{@link betaWriteTool} +* cannot synchronize concurrent writes to the *same* file across processes, so a +* multi-edit turn touching one path is still subject to inherent FS lost-update +* races. Custom tools that close over mutable state should do their own queueing. +*/ +function betaAgentToolset20260401(ctx) { + return [ + betaBashTool(ctx), + betaReadTool(ctx), + betaWriteTool(ctx), + betaEditTool(ctx), + betaGlobTool(ctx), + betaGrepTool(ctx) + ]; +} +/** +* Resolve `p` against `ctx.workdir`. Absolute and relative inputs go through +* the same canonicalise-then-contain check — an absolute path that lands inside +* the workdir is permitted, only paths that resolve *outside* are rejected. +* Every symlink in `p` (including the leaf, even a dangling one) is resolved +* before the workdir check, and the resolved path is what the tool then operates +* on, so a symlink inside the workdir that points outside it can neither pass +* the check nor be followed afterwards. See the trust model on +* {@link AgentToolContext}. +* +* Residual TOCTOU: a component could still be swapped for a symlink between this +* call and the eventual `fs` operation. Closing that fully needs per-component +* `O_NOFOLLOW`/`openat`, which Node does not expose ergonomically; the same +* residual exposure exists in `tools/memory/node` and is why a sandbox is still +* recommended for the toolset as a whole. +*/ +function resolvePath(ctx, p) { + return confineToRoot(ctx.workdir, p, { allowOutside: ctx.unrestrictedPaths ?? false }); +} +/** +* Build the environment for the spawned bash shell. The runner process holds +* Anthropic credentials in `ANTHROPIC_*` env vars — the API key, the auth token, +* and the per-work session token among them. `bash` runs an unrestricted shell, +* so any command the agent runs could read those straight out of `process.env`; +* strip the whole `ANTHROPIC_*` namespace from the child's environment. +* Everything else (PATH, HOME, locale, …) is passed through unchanged. +* +* Passing an explicit `env` to {@link AgentToolContext} does NOT add to this +* default — it FULLY REPLACES it. The provided mapping becomes the entire bash +* environment verbatim; nothing here is merged in, so callers who want the +* scrubbed process environment plus extras must build that mapping themselves. +*/ +function scrubbedShellEnv() { + const env = {}; + for (const [key, value] of Object.entries(process.env)) { + if (key.startsWith("ANTHROPIC_")) continue; + env[key] = value; + } + return env; +} +/** +* A persistent /bin/bash process. State (cwd, env, background jobs) survives +* across exec() calls. Uses pipes rather than a PTY so input is never echoed. +*/ +var BashSession = class { + constructor(dir, env = scrubbedShellEnv()) { + _BashSession_instances.add(this); + _BashSession_proc.set(this, void 0); + _BashSession_buf.set(this, ""); + _BashSession_truncated.set(this, false); + _BashSession_closed.set(this, false); + _BashSession_waiting.set(this, null); + __classPrivateFieldSet(this, _BashSession_proc, cp.spawn("/bin/bash", ["--noprofile", "--norc"], { + cwd: dir, + env: { + ...env, + PS1: "", + PS2: "", + TERM: "dumb" + }, + stdio: [ + "pipe", + "pipe", + "pipe" + ], + detached: true + }), "f"); + __classPrivateFieldGet(this, _BashSession_proc, "f").stdout.setEncoding("utf8"); + __classPrivateFieldGet(this, _BashSession_proc, "f").stderr.setEncoding("utf8"); + __classPrivateFieldGet(this, _BashSession_proc, "f").stdout.on("data", (d) => __classPrivateFieldGet(this, _BashSession_instances, "m", _BashSession_append).call(this, d)); + __classPrivateFieldGet(this, _BashSession_proc, "f").stderr.on("data", (d) => __classPrivateFieldGet(this, _BashSession_instances, "m", _BashSession_append).call(this, d)); + __classPrivateFieldGet(this, _BashSession_proc, "f").once("close", () => { + __classPrivateFieldSet(this, _BashSession_closed, true, "f"); + const w = __classPrivateFieldGet(this, _BashSession_waiting, "f"); + __classPrivateFieldSet(this, _BashSession_waiting, null, "f"); + w?.resolve(); + }); + } + /** Whether the underlying shell process has exited. */ + get closed() { + return __classPrivateFieldGet(this, _BashSession_closed, "f"); + } + async exec(command, opts = {}) { + if (__classPrivateFieldGet(this, _BashSession_closed, "f")) throw new AnthropicError("bash session terminated"); + const timeoutMs = opts.timeoutMs ?? BASH_DEFAULT_TIMEOUT_MS; + const signal = opts.signal; + if (signal?.aborted) throw new AnthropicError("bash command aborted"); + __classPrivateFieldSet(this, _BashSession_buf, "", "f"); + __classPrivateFieldSet(this, _BashSession_truncated, false, "f"); + const sentinel = `__ANT_CMD_${crypto.randomUUID()}_DONE__`; + const wrapped = `{ ${command}\n} &1; printf '\\n${`${sentinel.slice(0, 8)}''${sentinel.slice(8)}`}%d\\n' $?\n`; + __classPrivateFieldGet(this, _BashSession_proc, "f").stdin.write(wrapped); + if (__classPrivateFieldGet(this, _BashSession_buf, "f").indexOf(sentinel) < 0) { + const { promise: sentinelSeen, resolve } = promiseWithResolvers(); + __classPrivateFieldSet(this, _BashSession_waiting, { + sentinel, + resolve + }, "f"); + let timer; + let onAbort; + try { + await Promise.race([ + sentinelSeen, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new AnthropicError(`bash command timed out after ${timeoutMs}ms`)), timeoutMs); + }), + new Promise((_, reject) => { + if (!signal) return; + onAbort = () => reject(new AnthropicError("bash command aborted")); + signal.addEventListener("abort", onAbort, { once: true }); + }) + ]); + } finally { + if (timer) clearTimeout(timer); + if (onAbort && signal) signal.removeEventListener("abort", onAbort); + __classPrivateFieldSet(this, _BashSession_waiting, null, "f"); + } + } + const idx = __classPrivateFieldGet(this, _BashSession_buf, "f").indexOf(sentinel); + if (idx < 0) throw new AnthropicError("bash session terminated"); + const m = __classPrivateFieldGet(this, _BashSession_buf, "f").slice(idx + sentinel.length).match(/^(-?\d+)/); + const exitCode = m ? parseInt(m[1], 10) : -1; + let out = __classPrivateFieldGet(this, _BashSession_buf, "f").slice(0, idx).replace(ANSI_RE, "").replace(/\n+$/, ""); + if (__classPrivateFieldGet(this, _BashSession_truncated, "f")) out = `[output truncated]\n${out}`; + return { + output: out, + exitCode + }; + } + close() { + if (__classPrivateFieldGet(this, _BashSession_closed, "f")) return; + __classPrivateFieldSet(this, _BashSession_closed, true, "f"); + const w = __classPrivateFieldGet(this, _BashSession_waiting, "f"); + __classPrivateFieldSet(this, _BashSession_waiting, null, "f"); + w?.resolve(); + __classPrivateFieldGet(this, _BashSession_proc, "f").stdout.destroy(); + __classPrivateFieldGet(this, _BashSession_proc, "f").stderr.destroy(); + __classPrivateFieldGet(this, _BashSession_proc, "f").stdin.destroy(); + try { + process.kill(-__classPrivateFieldGet(this, _BashSession_proc, "f").pid, "SIGKILL"); + } catch { + __classPrivateFieldGet(this, _BashSession_proc, "f").kill("SIGKILL"); + } + __classPrivateFieldGet(this, _BashSession_proc, "f").unref(); + } +}; +_BashSession_proc = /* @__PURE__ */ new WeakMap(), _BashSession_buf = /* @__PURE__ */ new WeakMap(), _BashSession_truncated = /* @__PURE__ */ new WeakMap(), _BashSession_closed = /* @__PURE__ */ new WeakMap(), _BashSession_waiting = /* @__PURE__ */ new WeakMap(), _BashSession_instances = /* @__PURE__ */ new WeakSet(), _BashSession_append = function _BashSession_append(d) { + __classPrivateFieldSet(this, _BashSession_buf, __classPrivateFieldGet(this, _BashSession_buf, "f") + d, "f"); + if (__classPrivateFieldGet(this, _BashSession_buf, "f").length > BASH_OUTPUT_LIMIT) { + __classPrivateFieldSet(this, _BashSession_buf, __classPrivateFieldGet(this, _BashSession_buf, "f").slice(__classPrivateFieldGet(this, _BashSession_buf, "f").length - BASH_OUTPUT_LIMIT), "f"); + __classPrivateFieldSet(this, _BashSession_truncated, true, "f"); + } + if (__classPrivateFieldGet(this, _BashSession_waiting, "f") && __classPrivateFieldGet(this, _BashSession_buf, "f").indexOf(__classPrivateFieldGet(this, _BashSession_waiting, "f").sentinel) >= 0) { + const w = __classPrivateFieldGet(this, _BashSession_waiting, "f"); + __classPrivateFieldSet(this, _BashSession_waiting, null, "f"); + w.resolve(); + } +}; +function betaBashTool(ctx) { + let session; + let tail = Promise.resolve(); + return betaTool({ + name: "bash", + description: "Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.", + inputSchema: { + type: "object", + properties: { + command: { + type: "string", + description: "The command to run" + }, + restart: { + type: "boolean", + description: "Restart the persistent shell before running" + }, + timeout_ms: { + type: "integer", + description: "Per-call timeout in milliseconds" + } + } + }, + run: async ({ command, restart, timeout_ms }, context) => { + const prev = tail; + const gate = promiseWithResolvers(); + tail = gate.promise; + try { + await prev; + } catch {} + try { + if (restart) { + session?.close(); + session = void 0; + } + if (!command) { + if (restart) return "bash session restarted"; + throw new ToolError("bash: command is required"); + } + session ?? (session = new BashSession(ctx.workdir, ctx.env)); + try { + const { output, exitCode } = await session.exec(command, { + timeoutMs: timeout_ms ?? BASH_DEFAULT_TIMEOUT_MS, + signal: context?.signal + }); + if (exitCode !== 0) throw new ToolError(output || `exit ${exitCode}`); + return output; + } catch (e) { + if (e instanceof ToolError) throw e; + session.close(); + session = void 0; + throw new ToolError(`bash: ${e instanceof Error ? e.message : String(e)}`); + } + } finally { + gate.resolve(); + } + }, + close: () => { + session?.close(); + session = void 0; + } + }); +} +function betaReadTool(ctx) { + return betaTool({ + name: "read", + description: "Read a UTF-8 text file relative to the workdir.", + inputSchema: { + type: "object", + properties: { + file_path: { type: "string" }, + view_range: { + type: "array", + items: { type: "integer" }, + description: "[start_line, end_line] 1-indexed inclusive" + } + }, + required: ["file_path"] + }, + run: async ({ file_path, view_range }) => { + if (!file_path) throw new ToolError("read: file_path is required"); + const abs = await resolvePath(ctx, file_path); + let data; + try { + const st = await fs$2.stat(abs); + if (!st.isFile()) throw new ToolError(`read: ${file_path} is not a regular file`); + const limit = resolveMaxBytes(ctx.maxFileBytes); + if (limit !== null && st.size > limit) throw new ToolError(`read: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. Use bash (head/tail/sed) to read a slice.`); + data = await fs$2.readFile(abs, "utf8"); + } catch (e) { + if (e instanceof ToolError) throw e; + throw new ToolError(`read: ${fsErrorMessage(e, file_path)}`); + } + if (!view_range) return data; + if (view_range.length !== 2) throw new ToolError("read: view_range must be [start_line, end_line]"); + const [startLine, endLine] = view_range; + const lines = data.split("\n"); + const start = Math.max(0, startLine - 1); + const end = endLine > 0 ? endLine : lines.length; + return lines.slice(start, end).join("\n"); + } + }); +} +function betaWriteTool(ctx) { + return betaTool({ + name: "write", + description: "Write a UTF-8 text file relative to the workdir, creating parent directories as needed.", + inputSchema: { + type: "object", + properties: { + file_path: { type: "string" }, + content: { type: "string" } + }, + required: ["file_path", "content"] + }, + run: async ({ file_path, content }) => { + if (!file_path) throw new ToolError("write: file_path is required"); + const abs = await resolvePath(ctx, file_path); + try { + await fs$2.mkdir(path$1.dirname(abs), { + recursive: true, + mode: 493 + }); + await atomicWriteFile(abs, content ?? ""); + } catch (e) { + throw new ToolError(`write: ${fsErrorMessage(e, file_path)}`); + } + return `wrote ${Buffer.byteLength(content ?? "")} bytes to ${file_path}`; + } + }); +} +function betaEditTool(ctx) { + return betaTool({ + name: "edit", + description: "Replace old_string with new_string in a file. old_string must be unique unless replace_all.", + inputSchema: { + type: "object", + properties: { + file_path: { type: "string" }, + old_string: { type: "string" }, + new_string: { type: "string" }, + replace_all: { type: "boolean" } + }, + required: [ + "file_path", + "old_string", + "new_string" + ] + }, + run: async ({ file_path, old_string, new_string, replace_all }) => { + if (!file_path) throw new ToolError("edit: file_path is required"); + if (!old_string) throw new ToolError("edit: old_string is required"); + const abs = await resolvePath(ctx, file_path); + let data; + try { + const st = await fs$2.stat(abs); + if (!st.isFile()) throw new ToolError(`edit: ${file_path} is not a regular file`); + const limit = resolveMaxBytes(ctx.maxFileBytes); + if (limit !== null && st.size > limit) throw new ToolError(`edit: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. Use bash (sed/awk) to edit a large file.`); + data = await fs$2.readFile(abs, "utf8"); + } catch (e) { + if (e instanceof ToolError) throw e; + throw new ToolError(`edit: ${fsErrorMessage(e, file_path)}`); + } + const count = data.split(old_string).length - 1; + if (count === 0) throw new ToolError(`edit: old_string not found in ${file_path}`); + let updated; + if (replace_all) updated = data.split(old_string).join(new_string); + else { + if (count > 1) throw new ToolError(`edit: old_string appears ${count} times in ${file_path} (must be unique)`); + updated = data.replace(old_string, () => new_string); + } + try { + await atomicWriteFile(abs, updated); + } catch (e) { + throw new ToolError(`edit: write: ${fsErrorMessage(e, file_path)}`); + } + return `edited ${file_path} (${replace_all ? count : 1} replacement(s))`; + } + }); +} +function betaGlobTool(ctx) { + return betaTool({ + name: "glob", + description: "Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.", + inputSchema: { + type: "object", + properties: { + pattern: { type: "string" }, + path: { + type: "string", + description: "Directory to search in. Defaults to the workdir." + } + }, + required: ["pattern"] + }, + run: async ({ pattern, path: searchPath }) => { + if (!pattern) throw new ToolError("glob: pattern is required"); + let root = path$1.resolve(ctx.workdir); + let pat = pattern; + if (path$1.isAbsolute(pattern)) { + if (!ctx.unrestrictedPaths) throw new ToolError("glob: absolute pattern not permitted"); + root = path$1.parse(pattern).root; + pat = path$1.relative(root, pattern); + } else if (searchPath) root = await resolvePath(ctx, searchPath); + if (!ctx.unrestrictedPaths && pat.split(/[\\/]/).includes("..")) throw new ToolError("glob: \"..\" is not permitted in the pattern"); + const realRoot = ctx.unrestrictedPaths ? root : await fs$2.realpath(root).catch(() => root); + const matches = []; + try { + for await (const entry of fsGlob(pat, { + cwd: root, + withFileTypes: true, + exclude: (d) => d.name === ".git" || d.name === "node_modules" + })) { + if (!entry.isFile()) continue; + const full = path$1.join(entry.parentPath, entry.name); + if (!ctx.unrestrictedPaths) { + let real; + try { + real = await fs$2.realpath(full); + } catch { + continue; + } + if (!isWithin(realRoot, real)) continue; + } + let mtime = 0; + try { + mtime = (await fs$2.stat(full)).mtimeMs; + } catch {} + matches.push({ + path: full, + mtime + }); + } + } catch (e) { + throw new ToolError(`glob: ${e instanceof Error ? e.message : String(e)}`); + } + if (matches.length === 0) return "no matches"; + matches.sort((a, b) => b.mtime - a.mtime); + return matches.slice(0, GLOB_RESULT_LIMIT).map((m) => m.path).join("\n"); + } + }); +} +function betaGrepTool(ctx) { + return betaTool({ + name: "grep", + description: "Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.", + inputSchema: { + type: "object", + properties: { + pattern: { type: "string" }, + path: { type: "string" } + }, + required: ["pattern"] + }, + run: async ({ pattern, path: p }, context) => { + if (!pattern) throw new ToolError("grep: pattern is required"); + let searchPath = path$1.resolve(ctx.workdir); + if (p) searchPath = await resolvePath(ctx, p); + const rg = await findRg(); + return rg ? runRipgrep(rg, pattern, searchPath, context?.signal) : runWalkGrep(pattern, searchPath, context?.signal); + } + }); +} +function runRipgrep(rg, pattern, searchPath, signal) { + return new Promise((resolve, reject) => { + const proc = cp.spawn(rg, [ + "-n", + "--no-heading", + "-e", + pattern, + "--", + searchPath + ], { ...signal ? { signal } : {} }); + let out = ""; + let errOut = ""; + let truncated = false; + proc.stdout.on("data", (d) => { + if (truncated) return; + out += d; + if (out.length > GREP_OUTPUT_LIMIT) { + truncated = true; + out = out.slice(0, GREP_OUTPUT_LIMIT); + proc.kill("SIGKILL"); + } + }); + proc.stderr.on("data", (d) => errOut += d); + proc.on("close", (code) => { + if (signal?.aborted) return reject(new ToolError("grep: aborted")); + if (truncated) return resolve(out + `\n[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`); + if (code === 0) return resolve(out); + if (code === 1) return resolve("no matches"); + reject(new ToolError(`grep: rg failed: ${errOut || `exit ${code}`}`)); + }); + proc.on("error", (e) => { + if (signal?.aborted) return reject(new ToolError("grep: aborted")); + reject(new ToolError(`grep: rg failed: ${e.message}`)); + }); + }); +} +async function runWalkGrep(pattern, root, signal) { + let re; + try { + re = new RegExp(pattern); + } catch (e) { + throw new ToolError(`grep: invalid regex: ${e instanceof Error ? e.message : String(e)}`); + } + const hits = []; + let budget = GREP_OUTPUT_LIMIT; + const push = (line) => { + budget -= line.length + 1; + if (budget < 0) { + hits.push(`[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`); + return false; + } + hits.push(line); + return true; + }; + if ((await fs$2.stat(root).catch(() => null))?.isFile()) await grepFile(root, re, push); + else await walk(root, "", (rel) => grepFile(path$1.join(root, rel), re, push), signal); + if (signal?.aborted) throw new ToolError("grep: aborted"); + if (hits.length === 0) return "no matches"; + return hits.join("\n"); +} +async function grepFile(file, re, push) { + const stream = fssync.createReadStream(file, { encoding: "utf8" }); + const rl = readline.createInterface({ + input: stream, + crlfDelay: Infinity + }); + let i = 0; + try { + for await (const line of rl) { + i++; + if (line.length > GREP_MAX_LINE_LENGTH) continue; + if (re.test(line) && !push(`${file}:${i}:${line}`)) return false; + } + } catch {} finally { + stream.destroy(); + } + return true; +} +/** True when `p` is `root` itself or lexically contained within it. */ +function isWithin(root, p) { + const rel = path$1.relative(root, p); + return rel === "" || !rel.startsWith(".." + path$1.sep) && rel !== ".." && !path$1.isAbsolute(rel); +} +var WALK_MAX_DEPTH = 40; +var WALK_MAX_ENTRIES = 5e4; +/** +* Bounded recursive walk. `fn` may return `false` to abort. Only real +* directories are descended into and only real files are handed to `fn` — +* symlinks (and devices/fifos/sockets) are skipped entirely so a symlink inside +* the root cannot be followed out of it. +*/ +async function walk(root, rel, fn, signal) { + let remaining = WALK_MAX_ENTRIES; + async function inner(rel, depth) { + if (depth > WALK_MAX_DEPTH) return true; + if (signal?.aborted) return false; + let entries; + try { + entries = await fs$2.readdir(path$1.join(root, rel), { withFileTypes: true }); + } catch { + return true; + } + for (const e of entries) { + if (e.name === ".git" || e.name === "node_modules") continue; + if (remaining-- <= 0) return false; + if (signal?.aborted) return false; + const childRel = rel ? path$1.join(rel, e.name) : e.name; + if (e.isDirectory()) { + if (!await inner(childRel, depth + 1)) return false; + } else if (e.isFile()) { + if (await fn(childRel) === false) return false; + } + } + return true; + } + await inner(rel, 0); +} +async function findRg() { + const dirs = (process.env["PATH"] ?? "").split(path$1.delimiter); + for (const d of dirs) { + const candidate = path$1.join(d, "rg"); + try { + await fs$2.access(candidate, fssync.constants.X_OK); + return candidate; + } catch {} + } + return null; +} +//#endregion +export { Anthropic as n, transformJSONSchema as t }; diff --git a/.vercel/output/functions/__server.func/_libs/@better-auth/core+[...].mjs b/.vercel/output/functions/__server.func/_libs/@better-auth/core+[...].mjs index 3e090b0..61ba37b 100644 --- a/.vercel/output/functions/__server.func/_libs/@better-auth/core+[...].mjs +++ b/.vercel/output/functions/__server.func/_libs/@better-auth/core+[...].mjs @@ -1003,12945 +1003,13519 @@ function toKebabCase(input) { return splitWords(input).map((word) => word.toLowerCase()).join("-"); } //#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs -var initGetDefaultModelName = ({ usePlural, schema }) => { - /** - * This function helps us get the default model name from the schema defined by devs. - * Often times, the user will be using the `modelName` which could had been customized by the users. - * This function helps us get the actual model name useful to match against the schema. (eg: schema[model]) - * - * If it's still unclear what this does: - * - * 1. User can define a custom modelName. - * 2. When using a custom modelName, doing something like `schema[model]` will not work. - * 3. Using this function helps us get the actual model name based on the user's defined custom modelName. - */ - const getDefaultModelName = (model) => { - const resolve = (candidate) => { - if (schema[candidate]) return candidate; - return Object.entries(schema).find(([_, f]) => f.modelName === candidate)?.[0]; - }; - if (usePlural && model.charAt(model.length - 1) === "s") { - const m = resolve(model.slice(0, -1)); - if (m) return m; +//#region node_modules/zod/v4/core/core.js +var _a$1; +/** A special constant with type `never` */ +var NEVER = /*@__PURE__*/ Object.freeze({ status: "aborted" }); +function $constructor(name, initializer, params) { + function init(inst, def) { + if (!inst._zod) Object.defineProperty(inst, "_zod", { + value: { + def, + constr: _, + traits: /* @__PURE__ */ new Set() + }, + enumerable: false + }); + if (inst._zod.traits.has(name)) return; + inst._zod.traits.add(name); + initializer(inst, def); + const proto = _.prototype; + const keys = Object.keys(proto); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + if (!(k in inst)) inst[k] = proto[k].bind(inst); } - const m = resolve(model); - if (!m) throw new BetterAuthError(`Model "${model}" not found in schema`); - return m; - }; - return getDefaultModelName; + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent {} + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a = inst._zod).deferred ?? (_a.deferred = []); + for (const fn of inst._zod.deferred) fn(); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) return true; + return inst?._zod?.traits?.has(name); + } }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } }; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs -var initGetDefaultFieldName = ({ schema, usePlural }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema, - usePlural - }); - /** - * This function helps us get the default field name from the schema defined by devs. - * Often times, the user will be using the `fieldName` which could had been customized by the users. - * This function helps us get the actual field name useful to match against the schema. (eg: schema[model].fields[field]) - * - * If it's still unclear what this does: - * - * 1. User can define a custom fieldName. - * 2. When using a custom fieldName, doing something like `schema[model].fields[field]` will not work. - */ - const getDefaultFieldName = ({ field, model: unsafeModel }) => { - if (field === "id" || field === "_id") return "id"; - const model = getDefaultModelName(unsafeModel); - let f = schema[model]?.fields[field]; - if (!f) { - const result = Object.entries(schema[model].fields).find(([_, f]) => f.fieldName === field); - if (result) { - f = result[1]; - field = result[0]; - } - } - if (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`); - return field; - }; - return getDefaultFieldName; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } }; +(_a$1 = globalThis).__zod_globalConfig ?? (_a$1.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) Object.assign(globalConfig, newConfig); + return globalConfig; +} //#endregion -//#region node_modules/@better-auth/utils/dist/random.mjs -function expandAlphabet(alphabet) { - switch (alphabet) { - case "a-z": return "abcdefghijklmnopqrstuvwxyz"; - case "A-Z": return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - case "0-9": return "0123456789"; - case "-_": return "-_"; - default: throw new Error(`Unsupported alphabet: ${alphabet}`); - } +//#region node_modules/zod/v4/core/util.js +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); } -function createRandomStringGenerator(...baseAlphabets) { - const baseCharSet = baseAlphabets.map(expandAlphabet).join(""); - if (baseCharSet.length === 0) throw new Error("No valid characters provided for random string generation."); - const baseCharSetLength = baseCharSet.length; - return (length, ...alphabets) => { - if (length <= 0) throw new Error("Length must be a positive integer."); - let charSet = baseCharSet; - let charSetLength = baseCharSetLength; - if (alphabets.length > 0) { - charSet = alphabets.map(expandAlphabet).join(""); - charSetLength = charSet.length; +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") return value.toString(); + return value; +} +function cached(getter) { + return { get value() { + { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; } - const maxValid = Math.floor(256 / charSetLength) * charSetLength; - const buf = new Uint8Array(length * 2); - const bufLength = buf.length; - let result = ""; - let bufIndex = bufLength; - let rand; - while (result.length < length) { - if (bufIndex >= bufLength) { - crypto.getRandomValues(buf); - bufIndex = 0; + throw new Error("cached value already set"); + } }; +} +function nullish(input) { + return input === null || input === void 0; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) return 0; + return ratio - roundedRatio; +} +var EVALUATING = /* @__PURE__*/ Symbol("evaluating"); +function defineLazy(object, key, getter) { + let value = void 0; + Object.defineProperty(object, key, { + get() { + if (value === EVALUATING) return; + if (value === void 0) { + value = EVALUATING; + value = getter(); } - rand = buf[bufIndex++]; - if (rand < maxValid) result += charSet[rand % charSetLength]; - } - return result; - }; + return value; + }, + set(v) { + Object.defineProperty(object, key, { value: v }); + }, + configurable: true + }); } -//#endregion -//#region node_modules/@better-auth/core/dist/utils/id.mjs -var generateId = (size) => { - return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32); -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs -var initGetIdField = ({ usePlural, schema, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => { - const getDefaultModelName = initGetDefaultModelName({ - usePlural, - schema +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true }); - const idField = ({ customModelName, forceAllowId }) => { - const useNumberId = options.advanced?.database?.generateId === "serial"; - const useUUIDs = options.advanced?.database?.generateId === "uuid"; - const shouldGenerateId = (() => { - if (disableIdGeneration) return false; - else if (useNumberId && !forceAllowId) return false; - else if (useUUIDs) return !supportsUUIDs; - else return true; - })(); - const model = getDefaultModelName(customModelName ?? "id"); - return { - type: useNumberId ? "number" : "string", - required: shouldGenerateId ? true : false, - ...shouldGenerateId ? { defaultValue() { - if (disableIdGeneration) return void 0; - const generateId$1 = options.advanced?.database?.generateId; - if (generateId$1 === false || generateId$1 === "serial") return void 0; - if (typeof generateId$1 === "function") return generateId$1({ model }); - if (generateId$1 === "uuid") return crypto.randomUUID(); - if (customIdGenerator) return customIdGenerator({ model }); - return generateId(); - } } : {}, - transform: { - input: (value) => { - if (!value) return void 0; - if (useNumberId) { - const numberValue = Number(value); - if (isNaN(numberValue)) return; - return numberValue; - } - if (useUUIDs) { - if (shouldGenerateId && !forceAllowId) return value; - if (disableIdGeneration) return void 0; - if (forceAllowId && typeof value === "string") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value; - else { - const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", ""); - logger.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.", stack); - } - if (supportsUUIDs) return void 0; - if (typeof value !== "string" && !supportsUUIDs) return crypto.randomUUID(); - return; - } - return value; - }, - output: (value) => { - if (!value) return void 0; - return String(value); - } - } - }; - }; - return idField; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs -var initGetFieldAttributes = ({ usePlural, schema, options, customIdGenerator, disableIdGeneration }) => { - const getDefaultModelName = initGetDefaultModelName({ - usePlural, - schema - }); - const getDefaultFieldName = initGetDefaultFieldName({ - usePlural, - schema - }); - const idField = initGetIdField({ - usePlural, - schema, - options, - customIdGenerator, - disableIdGeneration - }); - const getFieldAttributes = ({ model, field }) => { - const defaultModelName = getDefaultModelName(model); - const defaultFieldName = getDefaultFieldName({ - field, - model: defaultModelName - }); - const fields = schema[defaultModelName].fields; - fields.id = idField({ customModelName: defaultModelName }); - const fieldAttributes = fields[defaultFieldName]; - if (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`); - return fieldAttributes; - }; - return getFieldAttributes; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs -var initGetFieldName = ({ schema, usePlural }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema, - usePlural - }); - const getDefaultFieldName = initGetDefaultFieldName({ - schema, - usePlural - }); - /** - * Get the field name which is expected to be saved in the database based on the user's schema. - * - * This function is useful if you need to save the field name to the database. - * - * For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema. - */ - function getFieldName({ model: modelName, field: fieldName }) { - const model = getDefaultModelName(modelName); - const field = getDefaultFieldName({ - model, - field: fieldName - }); - return schema[model]?.fields[field]?.fieldName || field; - } - return getFieldName; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs -var initGetModelName = ({ usePlural, schema }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema, - usePlural - }); - /** - * Users can overwrite the default model of some tables. This function helps find the correct model name. - * Furthermore, if the user passes `usePlural` as true in their adapter config, - * then we should return the model name ending with an `s`. - */ - const getModelName = (model) => { - const defaultModelKey = getDefaultModelName(model); - if (schema && schema[defaultModelKey] && schema[defaultModelKey].modelName !== model) return usePlural ? `${schema[defaultModelKey].modelName}s` : schema[defaultModelKey].modelName; - return usePlural ? `${model}s` : model; - }; - return getModelName; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/utils.mjs -function withApplyDefault(value, field, action) { - if (action === "update") { - if (value === void 0 && field.onUpdate !== void 0) { - if (typeof field.onUpdate === "function") return field.onUpdate(); - return field.onUpdate; - } - return value; - } - if (action === "create") { - if (value === void 0 || field.required === true && value === null) { - if (field.defaultValue !== void 0) { - if (typeof field.defaultValue === "function") return field.defaultValue(); - return field.defaultValue; - } - } - } - return value; } -//#endregion -//#region node_modules/@better-auth/core/dist/context/global.mjs -var symbol = Symbol.for("better-auth:global"); -var bind = null; -var __context = {}; -var __betterAuthVersion = "1.6.25"; -/** -* We store context instance in the globalThis. -* -* The reason we do this is that some bundlers, web framework, or package managers might -* create multiple copies of BetterAuth in the same process intentionally or unintentionally. -* -* For example, yarn v1, Next.js, SSR, Vite... -* -* @internal -*/ -function __getBetterAuthGlobal() { - if (!globalThis[symbol]) { - globalThis[symbol] = { - version: __betterAuthVersion, - epoch: 1, - context: __context - }; - bind = globalThis[symbol]; - } - bind = globalThis[symbol]; - if (bind.version !== __betterAuthVersion) { - bind.version = __betterAuthVersion; - bind.epoch++; +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); } - return globalThis[symbol]; + return Object.defineProperties({}, mergedDescriptors); } -function getBetterAuthVersion() { - return __getBetterAuthGlobal().version; +function esc(str) { + return JSON.stringify(str); } -//#endregion -//#region node_modules/@better-auth/core/dist/async_hooks/index.mjs -var AsyncLocalStoragePromise = import( - /* @vite-ignore */ - /* webpackIgnore: true */ - "node:async_hooks" -).then((mod) => mod.AsyncLocalStorage).catch((err) => { - if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage; - if (typeof window !== "undefined") return null; - console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."); - console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"); - console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"); - throw err; +function slugify(input) { + return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +} +var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {}; +function isObject$1(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +var allowsEval = /* @__PURE__*/ cached(() => { + if (globalConfig.jitless) return false; + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false; + try { + new Function(""); + return true; + } catch (_) { + return false; + } }); -async function getAsyncLocalStorage() { - const mod = await AsyncLocalStoragePromise; - if (mod === null) throw new Error("getAsyncLocalStorage is only available in server code"); - else return mod; +function isPlainObject(o) { + if (isObject$1(o) === false) return false; + const ctor = o.constructor; + if (ctor === void 0) return true; + if (typeof ctor !== "function") return true; + const prot = ctor.prototype; + if (isObject$1(prot) === false) return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false; + return true; } -//#endregion -//#region node_modules/@better-auth/core/dist/context/transaction.mjs -var ensureAsyncStorage$2 = async () => { - const betterAuthGlobal = __getBetterAuthGlobal(); - if (!betterAuthGlobal.context.adapterAsyncStorage) { - const AsyncLocalStorage = await getAsyncLocalStorage(); - betterAuthGlobal.context.adapterAsyncStorage = new AsyncLocalStorage(); +function shallowClone(o) { + if (isPlainObject(o)) return { ...o }; + if (Array.isArray(o)) return [...o]; + if (o instanceof Map) return new Map(o); + if (o instanceof Set) return new Set(o); + return o; +} +var propertyKeyTypes = /* @__PURE__*/ new Set([ + "string", + "number", + "symbol" +]); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) return {}; + if (typeof params === "string") return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; } - return betterAuthGlobal.context.adapterAsyncStorage; -}; -var getCurrentAdapter = async (fallback) => { - return ensureAsyncStorage$2().then((als) => { - return als.getStore()?.adapter || fallback; - }).catch(() => { - return fallback; + delete params.message; + if (typeof params.error === "string") return { + ...params, + error: () => params.error + }; + return params; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); +} +var NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; -var runWithAdapter = async (adapter, fn) => { - let called = false; - return ensureAsyncStorage$2().then(async (als) => { - called = true; - const pendingHooks = []; - let result; - let error; - let hasError = false; - try { - result = await als.run({ - adapter, - pendingHooks, - isTransactionActive: false - }, fn); - } catch (err) { - error = err; - hasError = true; - } - for (const hook of pendingHooks) await hook(); - if (hasError) throw error; - return result; - }).catch((err) => { - if (!called) return fn(); - throw err; - }); -}; -var runWithTransaction = async (adapter, fn) => { - let called = false; - return ensureAsyncStorage$2().then(async (als) => { - called = true; - if (als.getStore()?.isTransactionActive) return fn(); - const pendingHooks = []; - let result; - let error; - let hasError = false; - try { - result = await adapter.transaction(async (trx) => { - return als.run({ - adapter: trx, - pendingHooks, - isTransactionActive: true - }, fn); +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements"); + return clone(schema, mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + for (const key in mask) { + if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`); + if (!mask[key]) continue; + newShape[key] = currDef.shape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + })); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements"); + return clone(schema, mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key in mask) { + if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`); + if (!mask[key]) continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + })); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object"); + const checks = schema._zod.def.checks; + if (checks && checks.length > 0) { + const existingShape = schema._zod.def.shape; + for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + return clone(schema, mergeDefs(schema._zod.def, { get shape() { + const _shape = { + ...schema._zod.def.shape, + ...shape + }; + assignProp(this, "shape", _shape); + return _shape; + } })); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object"); + return clone(schema, mergeDefs(schema._zod.def, { get shape() { + const _shape = { + ...schema._zod.def.shape, + ...shape + }; + assignProp(this, "shape", _shape); + return _shape; + } })); +} +function merge(a, b) { + if (a._zod.def.checks?.length) throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + return clone(a, mergeDefs(a._zod.def, { + get shape() { + const _shape = { + ...a._zod.def.shape, + ...b._zod.def.shape + }; + assignProp(this, "shape", _shape); + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [] + })); +} +function partial(Class, schema, mask) { + const checks = schema._zod.def.checks; + if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements"); + return clone(schema, mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) for (const key in mask) { + if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`); + if (!mask[key]) continue; + shape[key] = Class ? new Class({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + else for (const key in oldShape) shape[key] = Class ? new Class({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + assignProp(this, "shape", shape); + return shape; + }, + checks: [] + })); +} +function required(Class, schema, mask) { + return clone(schema, mergeDefs(schema._zod.def, { get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) for (const key in mask) { + if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`); + if (!mask[key]) continue; + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key] }); - } catch (e) { - hasError = true; - error = e; } - for (const hook of pendingHooks) await hook(); - if (hasError) throw error; - return result; - }).catch((err) => { - if (!called) return fn(); - throw err; + else for (const key in oldShape) shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key] + }); + assignProp(this, "shape", shape); + return shape; + } })); +} +function aborted(x, startIndex = 0) { + if (x.aborted === true) return true; + for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true; + return false; +} +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) return true; + for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true; + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; }); -}; -/** -* Queue a hook to be executed after the current transaction commits. -* If not in a transaction, the hook will execute immediately. -*/ -var queueAfterTransactionHook = async (hook) => { - return ensureAsyncStorage$2().then((als) => { - const store = als.getStore(); - if (store) store.pendingHooks.push(hook); - else return hook(); - }).catch(() => { - return hook(); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +function finalizeIssue(iss, ctx, config) { + const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input"; + const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; + rest.path ?? (rest.path = []); + rest.message = message; + if (ctx?.reportInput) rest.input = _input; + return rest; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) return "array"; + if (typeof input === "string") return "string"; + return "unknown"; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") return { + message: iss, + code: "custom", + input, + inst + }; + return { ...iss }; +} +//#endregion +//#region node_modules/zod/v4/core/errors.js +var initializer$1 = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false }); }; -//#endregion -//#region node_modules/@better-auth/core/dist/db/get-tables.mjs -var getAuthTables = (options) => { - const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => { - const schema = plugin.schema; - if (!schema) return acc; - for (const [key, value] of Object.entries(schema)) acc[key] = { - fields: { - ...acc[key]?.fields, - ...value.fields - }, - modelName: value.modelName || key, - disableMigrations: value.disableMigration ?? acc[key]?.disableMigrations - }; - return acc; - }, {}); - const shouldAddRateLimitTable = options.rateLimit?.storage === "database"; - const rateLimitTable = { rateLimit: { - modelName: options.rateLimit?.modelName || "rateLimit", - fields: { - key: { - type: "string", - unique: true, - required: true, - fieldName: options.rateLimit?.fields?.key || "key" - }, - count: { - type: "number", - required: true, - fieldName: options.rateLimit?.fields?.count || "count" - }, - lastRequest: { - type: "number", - bigint: true, - required: true, - fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest", - defaultValue: () => Date.now() - } - } - } }; - const { user, session, account, verification, ...pluginTables } = pluginSchema; - const verificationTable = { verification: { - modelName: options.verification?.modelName || "verification", - fields: { - identifier: { - type: "string", - required: true, - fieldName: options.verification?.fields?.identifier || "identifier", - index: true - }, - value: { - type: "string", - required: true, - fieldName: options.verification?.fields?.value || "value" - }, - expiresAt: { - type: "date", - required: true, - fieldName: options.verification?.fields?.expiresAt || "expiresAt" - }, - createdAt: { - type: "date", - required: true, - defaultValue: () => /* @__PURE__ */ new Date(), - fieldName: options.verification?.fields?.createdAt || "createdAt" - }, - updatedAt: { - type: "date", - required: true, - defaultValue: () => /* @__PURE__ */ new Date(), - onUpdate: () => /* @__PURE__ */ new Date(), - fieldName: options.verification?.fields?.updatedAt || "updatedAt" - }, - ...verification?.fields, - ...options.verification?.additionalFields - }, - order: 4 - } }; - const sessionTable = { session: { - modelName: options.session?.modelName || "session", - fields: { - expiresAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.expiresAt || "expiresAt" - }, - token: { - type: "string", - required: true, - fieldName: options.session?.fields?.token || "token", - unique: true - }, - createdAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.createdAt || "createdAt", - defaultValue: () => /* @__PURE__ */ new Date() - }, - updatedAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.updatedAt || "updatedAt", - onUpdate: () => /* @__PURE__ */ new Date() - }, - ipAddress: { - type: "string", - required: false, - fieldName: options.session?.fields?.ipAddress || "ipAddress" - }, - userAgent: { - type: "string", - required: false, - fieldName: options.session?.fields?.userAgent || "userAgent" - }, - userId: { - type: "string", - fieldName: options.session?.fields?.userId || "userId", - references: { - model: "user", - field: "id", - onDelete: "cascade" - }, - required: true, - index: true - }, - ...session?.fields, - ...options.session?.additionalFields - }, - order: 2 - } }; +var $ZodError = $constructor("$ZodError", initializer$1); +var $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error }); +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.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 { - user: { - modelName: options.user?.modelName || "user", - fields: { - name: { - type: "string", - required: true, - fieldName: options.user?.fields?.name || "name", - sortable: true - }, - email: { - type: "string", - unique: true, - required: true, - fieldName: options.user?.fields?.email || "email", - sortable: true - }, - emailVerified: { - type: "boolean", - defaultValue: false, - required: true, - fieldName: options.user?.fields?.emailVerified || "emailVerified", - input: false - }, - image: { - type: "string", - required: false, - fieldName: options.user?.fields?.image || "image" - }, - createdAt: { - type: "date", - defaultValue: () => /* @__PURE__ */ new Date(), - required: true, - fieldName: options.user?.fields?.createdAt || "createdAt" - }, - updatedAt: { - type: "date", - defaultValue: () => /* @__PURE__ */ new Date(), - onUpdate: () => /* @__PURE__ */ new Date(), - required: true, - fieldName: options.user?.fields?.updatedAt || "updatedAt" - }, - ...user?.fields, - ...options.user?.additionalFields - }, - order: 1 - }, - ...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {}, - account: { - modelName: options.account?.modelName || "account", - fields: { - accountId: { - type: "string", - required: true, - fieldName: options.account?.fields?.accountId || "accountId" - }, - providerId: { - type: "string", - required: true, - fieldName: options.account?.fields?.providerId || "providerId" - }, - userId: { - type: "string", - references: { - model: "user", - field: "id", - onDelete: "cascade" - }, - required: true, - fieldName: options.account?.fields?.userId || "userId", - index: true - }, - accessToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.accessToken || "accessToken" - }, - refreshToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.refreshToken || "refreshToken" - }, - idToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.idToken || "idToken" - }, - accessTokenExpiresAt: { - type: "date", - required: false, - returned: false, - fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt" - }, - refreshTokenExpiresAt: { - type: "date", - required: false, - returned: false, - fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt" - }, - scope: { - type: "string", - required: false, - fieldName: options.account?.fields?.scope || "scope" - }, - password: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.password || "password" - }, - createdAt: { - type: "date", - required: true, - fieldName: options.account?.fields?.createdAt || "createdAt", - defaultValue: () => /* @__PURE__ */ new Date() - }, - updatedAt: { - type: "date", - required: true, - fieldName: options.account?.fields?.updatedAt || "updatedAt", - onUpdate: () => /* @__PURE__ */ new Date() - }, - ...account?.fields, - ...options.account?.additionalFields - }, - order: 3 - }, - ...!options.secondaryStorage || options.verification?.storeInDatabase ? verificationTable : {}, - ...pluginTables, - ...shouldAddRateLimitTable ? rateLimitTable : {} + formErrors, + fieldErrors }; -}; -//#endregion -//#region node_modules/@better-auth/core/dist/utils/json.mjs -var iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/; -function reviveDate(value) { - if (typeof value === "string" && iso8601Regex.test(value)) { - const date = new Date(value); - if (!isNaN(date.getTime())) return date; - } - return value; } -/** -* Recursively walk a pre-parsed object and convert ISO 8601 date strings -* to Date instances. This handles the case where a Redis client (or similar) -* returns already-parsed JSON objects whose date fields are still strings. +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error, path = []) => { + for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + else if (issue.code === "invalid_key") processError({ issues: issue.issues }, [...path, ...issue.path]); + else if (issue.code === "invalid_element") processError({ issues: issue.issues }, [...path, ...issue.path]); + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) fieldErrors._errors.push(mapper(issue)); + else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + if (!(i === fullpath.length - 1)) curr[el] = curr[el] || { _errors: [] }; + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(error); + return fieldErrors; +} +/** Format a ZodError as a human-readable string in the following form. +* +* From +* +* ```ts +* ZodError { +* issues: [ +* { +* expected: 'string', +* code: 'invalid_type', +* path: [ 'username' ], +* message: 'Invalid input: expected string' +* }, +* { +* expected: 'number', +* code: 'invalid_type', +* path: [ 'favoriteNumbers', 1 ], +* message: 'Invalid input: expected number' +* } +* ]; +* } +* ``` +* +* to +* +* ``` +* username +* ✖ Expected number, received string at "username +* favoriteNumbers[0] +* ✖ Invalid input: expected number +* ``` */ -function reviveDates(value) { - if (value === null || value === void 0) return value; - if (typeof value === "string") return reviveDate(value); - if (value instanceof Date) return value; - if (Array.isArray(value)) return value.map(reviveDates); - if (typeof value === "object") { - const result = {}; - for (const key of Object.keys(value)) result[key] = reviveDates(value[key]); - return result; +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg); + for (const seg of path) if (typeof seg === "number") segs.push(`[${seg}]`); + else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) segs.push("."); + segs.push(seg); } - return value; -} -function safeJSONParse(data) { - try { - if (typeof data !== "string") { - if (data === null || data === void 0) return null; - return reviveDates(data); - } - return JSON.parse(data, (_, value) => reviveDate(value)); - } catch (e) { - logger.error("Error parsing JSON", { error: e }); - return null; + return segs.join(""); +} +function prettifyError(error) { + const lines = []; + const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) lines.push(` → at ${toDotPath(issue.path)}`); } + return lines.join("\n"); } //#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js -var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createConstMap = void 0; - /** - * Creates a const map from the given values - * @param values - An array of values to be used as keys and values in the map. - * @returns A populated version of the map with the values and keys derived from the values. - */ - /*#__NO_SIDE_EFFECTS__*/ - function createConstMap(values) { - let res = {}; - const len = values.length; - for (let lp = 0; lp < len; lp++) { - const val = values[lp]; - if (val) res[String(val).toUpperCase().replace(/[-.]/g, "_")] = val; - } - return res; +//#region node_modules/zod/v4/core/parse.js +var _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? { + ..._ctx, + async: false + } : { async: false }; + const result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) throw new $ZodAsyncError(); + if (result.issues.length) { + const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee); + throw e; } - exports.createConstMap = createConstMap; -})); + return result.value; +}; +var parse$1 = /* @__PURE__*/ _parse($ZodRealError); +var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? { + ..._ctx, + async: true + } : { async: true }; + let result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) result = await result; + if (result.issues.length) { + const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; +}; +var parseAsync$1 = /* @__PURE__*/ _parseAsync($ZodRealError); +var _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + async: false + } : { async: false }; + const result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) throw new $ZodAsyncError(); + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { + success: true, + data: result.value + }; +}; +var safeParse$1 = /* @__PURE__*/ _safeParse($ZodRealError); +var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + async: true + } : { async: true }; + let result = schema._zod.run({ + value, + issues: [] + }, ctx); + if (result instanceof Promise) result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { + success: true, + data: result.value + }; +}; +var safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError); +var _encode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + direction: "backward" + } : { direction: "backward" }; + return _parse(_Err)(schema, value, ctx); +}; +var _decode = (_Err) => (schema, value, _ctx) => { + return _parse(_Err)(schema, value, _ctx); +}; +var _encodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + direction: "backward" + } : { direction: "backward" }; + return _parseAsync(_Err)(schema, value, ctx); +}; +var _decodeAsync = (_Err) => async (schema, value, _ctx) => { + return _parseAsync(_Err)(schema, value, _ctx); +}; +var _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + direction: "backward" + } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +var _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { + ..._ctx, + direction: "backward" + } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; //#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js -var require_SemanticAttributes = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SEMATTRS_NET_HOST_CARRIER_ICC = exports.SEMATTRS_NET_HOST_CARRIER_MNC = exports.SEMATTRS_NET_HOST_CARRIER_MCC = exports.SEMATTRS_NET_HOST_CARRIER_NAME = exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = exports.SEMATTRS_NET_HOST_NAME = exports.SEMATTRS_NET_HOST_PORT = exports.SEMATTRS_NET_HOST_IP = exports.SEMATTRS_NET_PEER_NAME = exports.SEMATTRS_NET_PEER_PORT = exports.SEMATTRS_NET_PEER_IP = exports.SEMATTRS_NET_TRANSPORT = exports.SEMATTRS_FAAS_INVOKED_REGION = exports.SEMATTRS_FAAS_INVOKED_PROVIDER = exports.SEMATTRS_FAAS_INVOKED_NAME = exports.SEMATTRS_FAAS_COLDSTART = exports.SEMATTRS_FAAS_CRON = exports.SEMATTRS_FAAS_TIME = exports.SEMATTRS_FAAS_DOCUMENT_NAME = exports.SEMATTRS_FAAS_DOCUMENT_TIME = exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = exports.SEMATTRS_FAAS_EXECUTION = exports.SEMATTRS_FAAS_TRIGGER = exports.SEMATTRS_EXCEPTION_ESCAPED = exports.SEMATTRS_EXCEPTION_STACKTRACE = exports.SEMATTRS_EXCEPTION_MESSAGE = exports.SEMATTRS_EXCEPTION_TYPE = exports.SEMATTRS_DB_SQL_TABLE = exports.SEMATTRS_DB_MONGODB_COLLECTION = exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = exports.SEMATTRS_DB_HBASE_NAMESPACE = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = exports.SEMATTRS_DB_CASSANDRA_TABLE = exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = exports.SEMATTRS_DB_OPERATION = exports.SEMATTRS_DB_STATEMENT = exports.SEMATTRS_DB_NAME = exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = exports.SEMATTRS_DB_USER = exports.SEMATTRS_DB_CONNECTION_STRING = exports.SEMATTRS_DB_SYSTEM = exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = void 0; - exports.SEMATTRS_MESSAGING_DESTINATION_KIND = exports.SEMATTRS_MESSAGING_DESTINATION = exports.SEMATTRS_MESSAGING_SYSTEM = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = exports.SEMATTRS_AWS_DYNAMODB_COUNT = exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_SELECT = exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = exports.SEMATTRS_AWS_DYNAMODB_LIMIT = exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = exports.SEMATTRS_HTTP_CLIENT_IP = exports.SEMATTRS_HTTP_ROUTE = exports.SEMATTRS_HTTP_SERVER_NAME = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = exports.SEMATTRS_HTTP_USER_AGENT = exports.SEMATTRS_HTTP_FLAVOR = exports.SEMATTRS_HTTP_STATUS_CODE = exports.SEMATTRS_HTTP_SCHEME = exports.SEMATTRS_HTTP_HOST = exports.SEMATTRS_HTTP_TARGET = exports.SEMATTRS_HTTP_URL = exports.SEMATTRS_HTTP_METHOD = exports.SEMATTRS_CODE_LINENO = exports.SEMATTRS_CODE_FILEPATH = exports.SEMATTRS_CODE_NAMESPACE = exports.SEMATTRS_CODE_FUNCTION = exports.SEMATTRS_THREAD_NAME = exports.SEMATTRS_THREAD_ID = exports.SEMATTRS_ENDUSER_SCOPE = exports.SEMATTRS_ENDUSER_ROLE = exports.SEMATTRS_ENDUSER_ID = exports.SEMATTRS_PEER_SERVICE = void 0; - exports.DBSYSTEMVALUES_FILEMAKER = exports.DBSYSTEMVALUES_DERBY = exports.DBSYSTEMVALUES_FIREBIRD = exports.DBSYSTEMVALUES_ADABAS = exports.DBSYSTEMVALUES_CACHE = exports.DBSYSTEMVALUES_EDB = exports.DBSYSTEMVALUES_FIRSTSQL = exports.DBSYSTEMVALUES_INGRES = exports.DBSYSTEMVALUES_HANADB = exports.DBSYSTEMVALUES_MAXDB = exports.DBSYSTEMVALUES_PROGRESS = exports.DBSYSTEMVALUES_HSQLDB = exports.DBSYSTEMVALUES_CLOUDSCAPE = exports.DBSYSTEMVALUES_HIVE = exports.DBSYSTEMVALUES_REDSHIFT = exports.DBSYSTEMVALUES_POSTGRESQL = exports.DBSYSTEMVALUES_DB2 = exports.DBSYSTEMVALUES_ORACLE = exports.DBSYSTEMVALUES_MYSQL = exports.DBSYSTEMVALUES_MSSQL = exports.DBSYSTEMVALUES_OTHER_SQL = exports.SemanticAttributes = exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_ID = exports.SEMATTRS_MESSAGE_TYPE = exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = exports.SEMATTRS_RPC_JSONRPC_VERSION = exports.SEMATTRS_RPC_GRPC_STATUS_CODE = exports.SEMATTRS_RPC_METHOD = exports.SEMATTRS_RPC_SERVICE = exports.SEMATTRS_RPC_SYSTEM = exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = exports.SEMATTRS_MESSAGING_CONSUMER_ID = exports.SEMATTRS_MESSAGING_OPERATION = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = exports.SEMATTRS_MESSAGING_CONVERSATION_ID = exports.SEMATTRS_MESSAGING_MESSAGE_ID = exports.SEMATTRS_MESSAGING_URL = exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = exports.SEMATTRS_MESSAGING_PROTOCOL = exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = void 0; - exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = exports.FaasDocumentOperationValues = exports.FAASDOCUMENTOPERATIONVALUES_DELETE = exports.FAASDOCUMENTOPERATIONVALUES_EDIT = exports.FAASDOCUMENTOPERATIONVALUES_INSERT = exports.FaasTriggerValues = exports.FAASTRIGGERVALUES_OTHER = exports.FAASTRIGGERVALUES_TIMER = exports.FAASTRIGGERVALUES_PUBSUB = exports.FAASTRIGGERVALUES_HTTP = exports.FAASTRIGGERVALUES_DATASOURCE = exports.DbCassandraConsistencyLevelValues = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = exports.DbSystemValues = exports.DBSYSTEMVALUES_COCKROACHDB = exports.DBSYSTEMVALUES_MEMCACHED = exports.DBSYSTEMVALUES_ELASTICSEARCH = exports.DBSYSTEMVALUES_GEODE = exports.DBSYSTEMVALUES_NEO4J = exports.DBSYSTEMVALUES_DYNAMODB = exports.DBSYSTEMVALUES_COSMOSDB = exports.DBSYSTEMVALUES_COUCHDB = exports.DBSYSTEMVALUES_COUCHBASE = exports.DBSYSTEMVALUES_REDIS = exports.DBSYSTEMVALUES_MONGODB = exports.DBSYSTEMVALUES_HBASE = exports.DBSYSTEMVALUES_CASSANDRA = exports.DBSYSTEMVALUES_COLDFUSION = exports.DBSYSTEMVALUES_H2 = exports.DBSYSTEMVALUES_VERTICA = exports.DBSYSTEMVALUES_TERADATA = exports.DBSYSTEMVALUES_SYBASE = exports.DBSYSTEMVALUES_SQLITE = exports.DBSYSTEMVALUES_POINTBASE = exports.DBSYSTEMVALUES_PERVASIVE = exports.DBSYSTEMVALUES_NETEZZA = exports.DBSYSTEMVALUES_MARIADB = exports.DBSYSTEMVALUES_INTERBASE = exports.DBSYSTEMVALUES_INSTANTDB = exports.DBSYSTEMVALUES_INFORMIX = void 0; - exports.MESSAGINGOPERATIONVALUES_RECEIVE = exports.MessagingDestinationKindValues = exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = exports.HttpFlavorValues = exports.HTTPFLAVORVALUES_QUIC = exports.HTTPFLAVORVALUES_SPDY = exports.HTTPFLAVORVALUES_HTTP_2_0 = exports.HTTPFLAVORVALUES_HTTP_1_1 = exports.HTTPFLAVORVALUES_HTTP_1_0 = exports.NetHostConnectionSubtypeValues = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = exports.NetHostConnectionTypeValues = exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = exports.NETHOSTCONNECTIONTYPEVALUES_CELL = exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = exports.NetTransportValues = exports.NETTRANSPORTVALUES_OTHER = exports.NETTRANSPORTVALUES_INPROC = exports.NETTRANSPORTVALUES_PIPE = exports.NETTRANSPORTVALUES_UNIX = exports.NETTRANSPORTVALUES_IP = exports.NETTRANSPORTVALUES_IP_UDP = exports.NETTRANSPORTVALUES_IP_TCP = exports.FaasInvokedProviderValues = exports.FAASINVOKEDPROVIDERVALUES_GCP = exports.FAASINVOKEDPROVIDERVALUES_AZURE = exports.FAASINVOKEDPROVIDERVALUES_AWS = void 0; - exports.MessageTypeValues = exports.MESSAGETYPEVALUES_RECEIVED = exports.MESSAGETYPEVALUES_SENT = exports.RpcGrpcStatusCodeValues = exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = exports.RPCGRPCSTATUSCODEVALUES_ABORTED = exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = exports.RPCGRPCSTATUSCODEVALUES_OK = exports.MessagingOperationValues = exports.MESSAGINGOPERATIONVALUES_PROCESS = void 0; - var utils_1 = require_utils(); - var TMP_AWS_LAMBDA_INVOKED_ARN = "aws.lambda.invoked_arn"; - var TMP_DB_SYSTEM = "db.system"; - var TMP_DB_CONNECTION_STRING = "db.connection_string"; - var TMP_DB_USER = "db.user"; - var TMP_DB_JDBC_DRIVER_CLASSNAME = "db.jdbc.driver_classname"; - var TMP_DB_NAME = "db.name"; - var TMP_DB_STATEMENT = "db.statement"; - var TMP_DB_OPERATION = "db.operation"; - var TMP_DB_MSSQL_INSTANCE_NAME = "db.mssql.instance_name"; - var TMP_DB_CASSANDRA_KEYSPACE = "db.cassandra.keyspace"; - var TMP_DB_CASSANDRA_PAGE_SIZE = "db.cassandra.page_size"; - var TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = "db.cassandra.consistency_level"; - var TMP_DB_CASSANDRA_TABLE = "db.cassandra.table"; - var TMP_DB_CASSANDRA_IDEMPOTENCE = "db.cassandra.idempotence"; - var TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = "db.cassandra.speculative_execution_count"; - var TMP_DB_CASSANDRA_COORDINATOR_ID = "db.cassandra.coordinator.id"; - var TMP_DB_CASSANDRA_COORDINATOR_DC = "db.cassandra.coordinator.dc"; - var TMP_DB_HBASE_NAMESPACE = "db.hbase.namespace"; - var TMP_DB_REDIS_DATABASE_INDEX = "db.redis.database_index"; - var TMP_DB_MONGODB_COLLECTION = "db.mongodb.collection"; - var TMP_DB_SQL_TABLE = "db.sql.table"; - var TMP_EXCEPTION_TYPE = "exception.type"; - var TMP_EXCEPTION_MESSAGE = "exception.message"; - var TMP_EXCEPTION_STACKTRACE = "exception.stacktrace"; - var TMP_EXCEPTION_ESCAPED = "exception.escaped"; - var TMP_FAAS_TRIGGER = "faas.trigger"; - var TMP_FAAS_EXECUTION = "faas.execution"; - var TMP_FAAS_DOCUMENT_COLLECTION = "faas.document.collection"; - var TMP_FAAS_DOCUMENT_OPERATION = "faas.document.operation"; - var TMP_FAAS_DOCUMENT_TIME = "faas.document.time"; - var TMP_FAAS_DOCUMENT_NAME = "faas.document.name"; - var TMP_FAAS_TIME = "faas.time"; - var TMP_FAAS_CRON = "faas.cron"; - var TMP_FAAS_COLDSTART = "faas.coldstart"; - var TMP_FAAS_INVOKED_NAME = "faas.invoked_name"; - var TMP_FAAS_INVOKED_PROVIDER = "faas.invoked_provider"; - var TMP_FAAS_INVOKED_REGION = "faas.invoked_region"; - var TMP_NET_TRANSPORT = "net.transport"; - var TMP_NET_PEER_IP = "net.peer.ip"; - var TMP_NET_PEER_PORT = "net.peer.port"; - var TMP_NET_PEER_NAME = "net.peer.name"; - var TMP_NET_HOST_IP = "net.host.ip"; - var TMP_NET_HOST_PORT = "net.host.port"; - var TMP_NET_HOST_NAME = "net.host.name"; - var TMP_NET_HOST_CONNECTION_TYPE = "net.host.connection.type"; - var TMP_NET_HOST_CONNECTION_SUBTYPE = "net.host.connection.subtype"; - var TMP_NET_HOST_CARRIER_NAME = "net.host.carrier.name"; - var TMP_NET_HOST_CARRIER_MCC = "net.host.carrier.mcc"; - var TMP_NET_HOST_CARRIER_MNC = "net.host.carrier.mnc"; - var TMP_NET_HOST_CARRIER_ICC = "net.host.carrier.icc"; - var TMP_PEER_SERVICE = "peer.service"; - var TMP_ENDUSER_ID = "enduser.id"; - var TMP_ENDUSER_ROLE = "enduser.role"; - var TMP_ENDUSER_SCOPE = "enduser.scope"; - var TMP_THREAD_ID = "thread.id"; - var TMP_THREAD_NAME = "thread.name"; - var TMP_CODE_FUNCTION = "code.function"; - var TMP_CODE_NAMESPACE = "code.namespace"; - var TMP_CODE_FILEPATH = "code.filepath"; - var TMP_CODE_LINENO = "code.lineno"; - var TMP_HTTP_METHOD = "http.method"; - var TMP_HTTP_URL = "http.url"; - var TMP_HTTP_TARGET = "http.target"; - var TMP_HTTP_HOST = "http.host"; - var TMP_HTTP_SCHEME = "http.scheme"; - var TMP_HTTP_STATUS_CODE = "http.status_code"; - var TMP_HTTP_FLAVOR = "http.flavor"; - var TMP_HTTP_USER_AGENT = "http.user_agent"; - var TMP_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length"; - var TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed"; - var TMP_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length"; - var TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed"; - var TMP_HTTP_SERVER_NAME = "http.server_name"; - var TMP_HTTP_ROUTE = "http.route"; - var TMP_HTTP_CLIENT_IP = "http.client_ip"; - var TMP_AWS_DYNAMODB_TABLE_NAMES = "aws.dynamodb.table_names"; - var TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = "aws.dynamodb.consumed_capacity"; - var TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = "aws.dynamodb.item_collection_metrics"; - var TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = "aws.dynamodb.provisioned_read_capacity"; - var TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = "aws.dynamodb.provisioned_write_capacity"; - var TMP_AWS_DYNAMODB_CONSISTENT_READ = "aws.dynamodb.consistent_read"; - var TMP_AWS_DYNAMODB_PROJECTION = "aws.dynamodb.projection"; - var TMP_AWS_DYNAMODB_LIMIT = "aws.dynamodb.limit"; - var TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = "aws.dynamodb.attributes_to_get"; - var TMP_AWS_DYNAMODB_INDEX_NAME = "aws.dynamodb.index_name"; - var TMP_AWS_DYNAMODB_SELECT = "aws.dynamodb.select"; - var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = "aws.dynamodb.global_secondary_indexes"; - var TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = "aws.dynamodb.local_secondary_indexes"; - var TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = "aws.dynamodb.exclusive_start_table"; - var TMP_AWS_DYNAMODB_TABLE_COUNT = "aws.dynamodb.table_count"; - var TMP_AWS_DYNAMODB_SCAN_FORWARD = "aws.dynamodb.scan_forward"; - var TMP_AWS_DYNAMODB_SEGMENT = "aws.dynamodb.segment"; - var TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = "aws.dynamodb.total_segments"; - var TMP_AWS_DYNAMODB_COUNT = "aws.dynamodb.count"; - var TMP_AWS_DYNAMODB_SCANNED_COUNT = "aws.dynamodb.scanned_count"; - var TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = "aws.dynamodb.attribute_definitions"; - var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = "aws.dynamodb.global_secondary_index_updates"; - var TMP_MESSAGING_SYSTEM = "messaging.system"; - var TMP_MESSAGING_DESTINATION = "messaging.destination"; - var TMP_MESSAGING_DESTINATION_KIND = "messaging.destination_kind"; - var TMP_MESSAGING_TEMP_DESTINATION = "messaging.temp_destination"; - var TMP_MESSAGING_PROTOCOL = "messaging.protocol"; - var TMP_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version"; - var TMP_MESSAGING_URL = "messaging.url"; - var TMP_MESSAGING_MESSAGE_ID = "messaging.message_id"; - var TMP_MESSAGING_CONVERSATION_ID = "messaging.conversation_id"; - var TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = "messaging.message_payload_size_bytes"; - var TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = "messaging.message_payload_compressed_size_bytes"; - var TMP_MESSAGING_OPERATION = "messaging.operation"; - var TMP_MESSAGING_CONSUMER_ID = "messaging.consumer_id"; - var TMP_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key"; - var TMP_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message_key"; - var TMP_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer_group"; - var TMP_MESSAGING_KAFKA_CLIENT_ID = "messaging.kafka.client_id"; - var TMP_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition"; - var TMP_MESSAGING_KAFKA_TOMBSTONE = "messaging.kafka.tombstone"; - var TMP_RPC_SYSTEM = "rpc.system"; - var TMP_RPC_SERVICE = "rpc.service"; - var TMP_RPC_METHOD = "rpc.method"; - var TMP_RPC_GRPC_STATUS_CODE = "rpc.grpc.status_code"; - var TMP_RPC_JSONRPC_VERSION = "rpc.jsonrpc.version"; - var TMP_RPC_JSONRPC_REQUEST_ID = "rpc.jsonrpc.request_id"; - var TMP_RPC_JSONRPC_ERROR_CODE = "rpc.jsonrpc.error_code"; - var TMP_RPC_JSONRPC_ERROR_MESSAGE = "rpc.jsonrpc.error_message"; - var TMP_MESSAGE_TYPE = "message.type"; - var TMP_MESSAGE_ID = "message.id"; - var TMP_MESSAGE_COMPRESSED_SIZE = "message.compressed_size"; - var TMP_MESSAGE_UNCOMPRESSED_SIZE = "message.uncompressed_size"; - /** - * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable). - * - * Note: This may be different from `faas.id` if an alias is involved. - * - * @deprecated Use ATTR_AWS_LAMBDA_INVOKED_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use ATTR_DB_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; - /** - * The connection string used to connect to the database. It is recommended to remove embedded credentials. - * - * @deprecated Use ATTR_DB_CONNECTION_STRING in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; - /** - * Username for accessing the database. - * - * @deprecated Use ATTR_DB_USER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_USER = TMP_DB_USER; - /** - * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect. - * - * @deprecated Use ATTR_DB_JDBC_DRIVER_CLASSNAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; - /** - * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails). - * - * Note: In some SQL databases, the database name to be used is called "schema name". - * - * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_NAME = TMP_DB_NAME; - /** - * The database statement being executed. - * - * Note: The value may be sanitized to exclude sensitive information. - * - * @deprecated Use ATTR_DB_STATEMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; - /** - * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword. - * - * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted. - * - * @deprecated Use ATTR_DB_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; - /** - * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance. - * - * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard). - * - * @deprecated Use ATTR_DB_MSSQL_INSTANCE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; - /** - * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute. - * - * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; - /** - * The fetch size used for paging, i.e. how many rows will be returned at once. - * - * @deprecated Use ATTR_DB_CASSANDRA_PAGE_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use ATTR_DB_CASSANDRA_CONSISTENCY_LEVEL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; - /** - * The name of the primary table that the operation is acting upon, including the schema name (if applicable). - * - * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. - * - * @deprecated Use ATTR_DB_CASSANDRA_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; - /** - * Whether or not the query is idempotent. - * - * @deprecated Use ATTR_DB_CASSANDRA_IDEMPOTENCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; - /** - * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively. - * - * @deprecated Use ATTR_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; - /** - * The ID of the coordinating node for a query. - * - * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; - /** - * The data center of the coordinating node for a query. - * - * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_DC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; - /** - * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute. - * - * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; - /** - * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute. - * - * @deprecated Use ATTR_DB_REDIS_DATABASE_INDEX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; - /** - * The collection being accessed within the database stated in `db.name`. - * - * @deprecated Use ATTR_DB_MONGODB_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; - /** - * The name of the primary table that the operation is acting upon, including the schema name (if applicable). - * - * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. - * - * @deprecated Use ATTR_DB_SQL_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; - /** - * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. - * - * @deprecated Use ATTR_EXCEPTION_TYPE. - */ - exports.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; - /** - * The exception message. - * - * @deprecated Use ATTR_EXCEPTION_MESSAGE. - */ - exports.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; - /** - * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. - * - * @deprecated Use ATTR_EXCEPTION_STACKTRACE. - */ - exports.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; - /** - * SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span. - * - * Note: An exception is considered to have escaped (or left) the scope of a span, - if that span is ended while the exception is still logically "in flight". - This may be actually "in flight" in some languages (e.g. if the exception - is passed to a Context manager's `__exit__` method in Python) but will - usually be caught at the point of recording the exception in most languages. - - It is usually not possible to determine at the point where an exception is thrown - whether it will escape the scope of a span. - However, it is trivial to know that an exception - will escape, if one checks for an active exception just before ending the span, - as done in the [example above](#exception-end-example). - - It follows that an exception may still escape the scope of the span - even if the `exception.escaped` attribute was not set or set to false, - since the event might have been recorded at a time where it was not - clear whether the exception will escape. - * - * @deprecated Use ATTR_EXCEPTION_ESCAPED. - */ - exports.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use ATTR_FAAS_TRIGGER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; - /** - * The execution ID of the current function execution. - * - * @deprecated Use ATTR_FAAS_INVOCATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; - /** - * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name. - * - * @deprecated Use ATTR_FAAS_DOCUMENT_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use ATTR_FAAS_DOCUMENT_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; - /** - * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - * - * @deprecated Use ATTR_FAAS_DOCUMENT_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; - /** - * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name. - * - * @deprecated Use ATTR_FAAS_DOCUMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; - /** - * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - * - * @deprecated Use ATTR_FAAS_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; - /** - * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). - * - * @deprecated Use ATTR_FAAS_CRON in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; - /** - * A boolean that is true if the serverless function is executed for the first time (aka cold-start). - * - * @deprecated Use ATTR_FAAS_COLDSTART in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; - /** - * The name of the invoked function. - * - * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function. - * - * @deprecated Use ATTR_FAAS_INVOKED_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use ATTR_FAAS_INVOKED_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; - /** - * The cloud region of the invoked function. - * - * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function. - * - * @deprecated Use ATTR_FAAS_INVOKED_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; - /** - * Transport protocol used. See note below. - * - * @deprecated Use ATTR_NET_TRANSPORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; - /** - * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6). - * - * @deprecated Use ATTR_NET_PEER_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; - /** - * Remote port number. - * - * @deprecated Use ATTR_NET_PEER_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; - /** - * Remote hostname or similar, see note below. - * - * @deprecated Use ATTR_NET_PEER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; - /** - * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host. - * - * @deprecated Use ATTR_NET_HOST_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; - /** - * Like `net.peer.port` but for the host port. - * - * @deprecated Use ATTR_NET_HOST_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; - /** - * Local hostname or similar, see note below. - * - * @deprecated Use ATTR_NET_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use ATTR_NETWORK_CONNECTION_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use ATTR_NETWORK_CONNECTION_SUBTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; - /** - * The name of the mobile carrier. - * - * @deprecated Use ATTR_NETWORK_CARRIER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; - /** - * The mobile carrier country code. - * - * @deprecated Use ATTR_NETWORK_CARRIER_MCC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; - /** - * The mobile carrier network code. - * - * @deprecated Use ATTR_NETWORK_CARRIER_MNC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; - /** - * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network. - * - * @deprecated Use ATTR_NETWORK_CARRIER_ICC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; - /** - * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any. - * - * @deprecated Use ATTR_PEER_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; - /** - * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system. - * - * @deprecated Use ATTR_ENDUSER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; - /** - * Actual/assumed role the client is making the request under extracted from token or application security context. - * - * @deprecated Use ATTR_ENDUSER_ROLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; - /** - * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). - * - * @deprecated Use ATTR_ENDUSER_SCOPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; - /** - * Current "managed" thread ID (as opposed to OS thread ID). - * - * @deprecated Use ATTR_THREAD_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_THREAD_ID = TMP_THREAD_ID; - /** - * Current thread name. - * - * @deprecated Use ATTR_THREAD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; - /** - * The method or function name, or equivalent (usually rightmost part of the code unit's name). - * - * @deprecated Use ATTR_CODE_FUNCTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; - /** - * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit. - * - * @deprecated Use ATTR_CODE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; - /** - * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). - * - * @deprecated Use ATTR_CODE_FILEPATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; - /** - * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`. - * - * @deprecated Use ATTR_CODE_LINENO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; - /** - * HTTP request method. - * - * @deprecated Use ATTR_HTTP_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; - /** - * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless. - * - * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`. - * - * @deprecated Use ATTR_HTTP_URL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_URL = TMP_HTTP_URL; - /** - * The full request target as passed in a HTTP request line or equivalent. - * - * @deprecated Use ATTR_HTTP_TARGET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; - /** - * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note. - * - * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set. - * - * @deprecated Use ATTR_HTTP_HOST in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; - /** - * The URI scheme identifying the used protocol. - * - * @deprecated Use ATTR_HTTP_SCHEME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; - /** - * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). - * - * @deprecated Use ATTR_HTTP_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use ATTR_HTTP_FLAVOR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; - /** - * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client. - * - * @deprecated Use ATTR_HTTP_USER_AGENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; - /** - * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. - * - * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; - /** - * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used. - * - * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; - /** - * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. - * - * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; - /** - * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used. - * - * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; - /** - * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead). - * - * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available. - * - * @deprecated Use ATTR_HTTP_SERVER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; - /** - * The matched route (path template). - * - * @deprecated Use ATTR_HTTP_ROUTE. - */ - exports.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; - /** - * The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). - * - * Note: This is not necessarily the same as `net.peer.ip`, which would - identify the network-level peer, which may be a proxy. - - This attribute should be set when a source of information different - from the one used for `net.peer.ip`, is available even if that other - source just confirms the same value as `net.peer.ip`. - Rationale: For `net.peer.ip`, one typically does not know if it - comes from a proxy, reverse proxy, or the actual client. Setting - `http.client_ip` when it's the same as `net.peer.ip` means that - one is at least somewhat confident that the address is not that of - the closest proxy. - * - * @deprecated Use ATTR_HTTP_CLIENT_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; - /** - * The keys in the `RequestItems` object field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; - /** - * The JSON-serialized value of each item in the `ConsumedCapacity` response field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; - /** - * The JSON-serialized value of the `ItemCollectionMetrics` response field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; - /** - * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; - /** - * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; - /** - * The value of the `ConsistentRead` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_CONSISTENT_READ in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; - /** - * The value of the `ProjectionExpression` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_PROJECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; - /** - * The value of the `Limit` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_LIMIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; - /** - * The value of the `AttributesToGet` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTES_TO_GET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; - /** - * The value of the `IndexName` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_INDEX_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; - /** - * The value of the `Select` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SELECT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; - /** - * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; - /** - * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; - /** - * The value of the `ExclusiveStartTableName` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; - /** - * The the number of items in the `TableNames` response parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; - /** - * The value of the `ScanIndexForward` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SCAN_FORWARD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; - /** - * The value of the `Segment` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SEGMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; - /** - * The value of the `TotalSegments` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; - /** - * The value of the `Count` response parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; - /** - * The value of the `ScannedCount` response parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SCANNED_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; - /** - * The JSON-serialized value of each item in the `AttributeDefinitions` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; - /** - * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; - /** - * A string identifying the messaging system. - * - * @deprecated Use ATTR_MESSAGING_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; - /** - * The message destination name. This might be equal to the span name but is required nevertheless. - * - * @deprecated Use ATTR_MESSAGING_DESTINATION_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; - /** - * The kind of message destination. - * - * @deprecated Removed in semconv v1.20.0. - */ - exports.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; - /** - * A boolean that is true if the message destination is temporary. - * - * @deprecated Use ATTR_MESSAGING_DESTINATION_TEMPORARY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; - /** - * The name of the transport protocol. - * - * @deprecated Use ATTR_NETWORK_PROTOCOL_NAME. - */ - exports.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; - /** - * The version of the transport protocol. - * - * @deprecated Use ATTR_NETWORK_PROTOCOL_VERSION. - */ - exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; - /** - * Connection string. - * - * @deprecated Removed in semconv v1.17.0. - */ - exports.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; - /** - * A value used by the messaging system as an identifier for the message, represented as a string. - * - * @deprecated Use ATTR_MESSAGING_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; - /** - * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID". - * - * @deprecated Use ATTR_MESSAGING_MESSAGE_CONVERSATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; - /** - * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported. - * - * @deprecated Use ATTR_MESSAGING_MESSAGE_BODY_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; - /** - * The compressed size of the message payload in bytes. - * - * @deprecated Removed in semconv v1.22.0. - */ - exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; - /** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use ATTR_MESSAGING_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; - /** - * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message. - * - * @deprecated Removed in semconv v1.21.0. - */ - exports.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; - /** - * RabbitMQ message routing key. - * - * @deprecated Use ATTR_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; - /** - * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set. - * - * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; - /** - * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_CONSUMER_GROUP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; - /** - * Client Id for the Consumer or Producer that is handling the message. - * - * @deprecated Use ATTR_MESSAGING_CLIENT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; - /** - * Partition the message is sent to. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_DESTINATION_PARTITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; - /** - * A boolean that is true if the message is a tombstone. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; - /** - * A string identifying the remoting system. - * - * @deprecated Use ATTR_RPC_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; - /** - * The full (logical) name of the service being called, including its package name, if applicable. - * - * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side). - * - * @deprecated Use ATTR_RPC_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; - /** - * The name of the (logical) method being called, must be equal to the $method part in the span name. - * - * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side). - * - * @deprecated Use ATTR_RPC_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use ATTR_RPC_GRPC_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; - /** - * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted. - * - * @deprecated Use ATTR_RPC_JSONRPC_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; - /** - * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification. - * - * @deprecated Use ATTR_RPC_JSONRPC_REQUEST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; - /** - * `error.code` property of response if it is an error response. - * - * @deprecated Use ATTR_RPC_JSONRPC_ERROR_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; - /** - * `error.message` property of response if it is an error response. - * - * @deprecated Use ATTR_RPC_JSONRPC_ERROR_MESSAGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; - /** - * Whether this is a received or sent message. - * - * @deprecated Use ATTR_MESSAGE_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; - /** - * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message. - * - * Note: This way we guarantee that the values will be consistent between different implementations. - * - * @deprecated Use ATTR_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; - /** - * Compressed size of the message in bytes. - * - * @deprecated Use ATTR_MESSAGE_COMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; - /** - * Uncompressed size of the message in bytes. - * - * @deprecated Use ATTR_MESSAGE_UNCOMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; - /** - * Create exported Value Map for SemanticAttributes values - * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification - */ - exports.SemanticAttributes = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_AWS_LAMBDA_INVOKED_ARN, - TMP_DB_SYSTEM, - TMP_DB_CONNECTION_STRING, - TMP_DB_USER, - TMP_DB_JDBC_DRIVER_CLASSNAME, - TMP_DB_NAME, - TMP_DB_STATEMENT, - TMP_DB_OPERATION, - TMP_DB_MSSQL_INSTANCE_NAME, - TMP_DB_CASSANDRA_KEYSPACE, - TMP_DB_CASSANDRA_PAGE_SIZE, - TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, - TMP_DB_CASSANDRA_TABLE, - TMP_DB_CASSANDRA_IDEMPOTENCE, - TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, - TMP_DB_CASSANDRA_COORDINATOR_ID, - TMP_DB_CASSANDRA_COORDINATOR_DC, - TMP_DB_HBASE_NAMESPACE, - TMP_DB_REDIS_DATABASE_INDEX, - TMP_DB_MONGODB_COLLECTION, - TMP_DB_SQL_TABLE, - TMP_EXCEPTION_TYPE, - TMP_EXCEPTION_MESSAGE, - TMP_EXCEPTION_STACKTRACE, - TMP_EXCEPTION_ESCAPED, - TMP_FAAS_TRIGGER, - TMP_FAAS_EXECUTION, - TMP_FAAS_DOCUMENT_COLLECTION, - TMP_FAAS_DOCUMENT_OPERATION, - TMP_FAAS_DOCUMENT_TIME, - TMP_FAAS_DOCUMENT_NAME, - TMP_FAAS_TIME, - TMP_FAAS_CRON, - TMP_FAAS_COLDSTART, - TMP_FAAS_INVOKED_NAME, - TMP_FAAS_INVOKED_PROVIDER, - TMP_FAAS_INVOKED_REGION, - TMP_NET_TRANSPORT, - TMP_NET_PEER_IP, - TMP_NET_PEER_PORT, - TMP_NET_PEER_NAME, - TMP_NET_HOST_IP, - TMP_NET_HOST_PORT, - TMP_NET_HOST_NAME, - TMP_NET_HOST_CONNECTION_TYPE, - TMP_NET_HOST_CONNECTION_SUBTYPE, - TMP_NET_HOST_CARRIER_NAME, - TMP_NET_HOST_CARRIER_MCC, - TMP_NET_HOST_CARRIER_MNC, - TMP_NET_HOST_CARRIER_ICC, - TMP_PEER_SERVICE, - TMP_ENDUSER_ID, - TMP_ENDUSER_ROLE, - TMP_ENDUSER_SCOPE, - TMP_THREAD_ID, - TMP_THREAD_NAME, - TMP_CODE_FUNCTION, - TMP_CODE_NAMESPACE, - TMP_CODE_FILEPATH, - TMP_CODE_LINENO, - TMP_HTTP_METHOD, - TMP_HTTP_URL, - TMP_HTTP_TARGET, - TMP_HTTP_HOST, - TMP_HTTP_SCHEME, - TMP_HTTP_STATUS_CODE, - TMP_HTTP_FLAVOR, - TMP_HTTP_USER_AGENT, - TMP_HTTP_REQUEST_CONTENT_LENGTH, - TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, - TMP_HTTP_RESPONSE_CONTENT_LENGTH, - TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, - TMP_HTTP_SERVER_NAME, - TMP_HTTP_ROUTE, - TMP_HTTP_CLIENT_IP, - TMP_AWS_DYNAMODB_TABLE_NAMES, - TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, - TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, - TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, - TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, - TMP_AWS_DYNAMODB_CONSISTENT_READ, - TMP_AWS_DYNAMODB_PROJECTION, - TMP_AWS_DYNAMODB_LIMIT, - TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, - TMP_AWS_DYNAMODB_INDEX_NAME, - TMP_AWS_DYNAMODB_SELECT, - TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, - TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, - TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, - TMP_AWS_DYNAMODB_TABLE_COUNT, - TMP_AWS_DYNAMODB_SCAN_FORWARD, - TMP_AWS_DYNAMODB_SEGMENT, - TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, - TMP_AWS_DYNAMODB_COUNT, - TMP_AWS_DYNAMODB_SCANNED_COUNT, - TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, - TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, - TMP_MESSAGING_SYSTEM, - TMP_MESSAGING_DESTINATION, - TMP_MESSAGING_DESTINATION_KIND, - TMP_MESSAGING_TEMP_DESTINATION, - TMP_MESSAGING_PROTOCOL, - TMP_MESSAGING_PROTOCOL_VERSION, - TMP_MESSAGING_URL, - TMP_MESSAGING_MESSAGE_ID, - TMP_MESSAGING_CONVERSATION_ID, - TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, - TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, - TMP_MESSAGING_OPERATION, - TMP_MESSAGING_CONSUMER_ID, - TMP_MESSAGING_RABBITMQ_ROUTING_KEY, - TMP_MESSAGING_KAFKA_MESSAGE_KEY, - TMP_MESSAGING_KAFKA_CONSUMER_GROUP, - TMP_MESSAGING_KAFKA_CLIENT_ID, - TMP_MESSAGING_KAFKA_PARTITION, - TMP_MESSAGING_KAFKA_TOMBSTONE, - TMP_RPC_SYSTEM, - TMP_RPC_SERVICE, - TMP_RPC_METHOD, - TMP_RPC_GRPC_STATUS_CODE, - TMP_RPC_JSONRPC_VERSION, - TMP_RPC_JSONRPC_REQUEST_ID, - TMP_RPC_JSONRPC_ERROR_CODE, - TMP_RPC_JSONRPC_ERROR_MESSAGE, - TMP_MESSAGE_TYPE, - TMP_MESSAGE_ID, - TMP_MESSAGE_COMPRESSED_SIZE, - TMP_MESSAGE_UNCOMPRESSED_SIZE - ]); - var TMP_DBSYSTEMVALUES_OTHER_SQL = "other_sql"; - var TMP_DBSYSTEMVALUES_MSSQL = "mssql"; - var TMP_DBSYSTEMVALUES_MYSQL = "mysql"; - var TMP_DBSYSTEMVALUES_ORACLE = "oracle"; - var TMP_DBSYSTEMVALUES_DB2 = "db2"; - var TMP_DBSYSTEMVALUES_POSTGRESQL = "postgresql"; - var TMP_DBSYSTEMVALUES_REDSHIFT = "redshift"; - var TMP_DBSYSTEMVALUES_HIVE = "hive"; - var TMP_DBSYSTEMVALUES_CLOUDSCAPE = "cloudscape"; - var TMP_DBSYSTEMVALUES_HSQLDB = "hsqldb"; - var TMP_DBSYSTEMVALUES_PROGRESS = "progress"; - var TMP_DBSYSTEMVALUES_MAXDB = "maxdb"; - var TMP_DBSYSTEMVALUES_HANADB = "hanadb"; - var TMP_DBSYSTEMVALUES_INGRES = "ingres"; - var TMP_DBSYSTEMVALUES_FIRSTSQL = "firstsql"; - var TMP_DBSYSTEMVALUES_EDB = "edb"; - var TMP_DBSYSTEMVALUES_CACHE = "cache"; - var TMP_DBSYSTEMVALUES_ADABAS = "adabas"; - var TMP_DBSYSTEMVALUES_FIREBIRD = "firebird"; - var TMP_DBSYSTEMVALUES_DERBY = "derby"; - var TMP_DBSYSTEMVALUES_FILEMAKER = "filemaker"; - var TMP_DBSYSTEMVALUES_INFORMIX = "informix"; - var TMP_DBSYSTEMVALUES_INSTANTDB = "instantdb"; - var TMP_DBSYSTEMVALUES_INTERBASE = "interbase"; - var TMP_DBSYSTEMVALUES_MARIADB = "mariadb"; - var TMP_DBSYSTEMVALUES_NETEZZA = "netezza"; - var TMP_DBSYSTEMVALUES_PERVASIVE = "pervasive"; - var TMP_DBSYSTEMVALUES_POINTBASE = "pointbase"; - var TMP_DBSYSTEMVALUES_SQLITE = "sqlite"; - var TMP_DBSYSTEMVALUES_SYBASE = "sybase"; - var TMP_DBSYSTEMVALUES_TERADATA = "teradata"; - var TMP_DBSYSTEMVALUES_VERTICA = "vertica"; - var TMP_DBSYSTEMVALUES_H2 = "h2"; - var TMP_DBSYSTEMVALUES_COLDFUSION = "coldfusion"; - var TMP_DBSYSTEMVALUES_CASSANDRA = "cassandra"; - var TMP_DBSYSTEMVALUES_HBASE = "hbase"; - var TMP_DBSYSTEMVALUES_MONGODB = "mongodb"; - var TMP_DBSYSTEMVALUES_REDIS = "redis"; - var TMP_DBSYSTEMVALUES_COUCHBASE = "couchbase"; - var TMP_DBSYSTEMVALUES_COUCHDB = "couchdb"; - var TMP_DBSYSTEMVALUES_COSMOSDB = "cosmosdb"; - var TMP_DBSYSTEMVALUES_DYNAMODB = "dynamodb"; - var TMP_DBSYSTEMVALUES_NEO4J = "neo4j"; - var TMP_DBSYSTEMVALUES_GEODE = "geode"; - var TMP_DBSYSTEMVALUES_ELASTICSEARCH = "elasticsearch"; - var TMP_DBSYSTEMVALUES_MEMCACHED = "memcached"; - var TMP_DBSYSTEMVALUES_COCKROACHDB = "cockroachdb"; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_OTHER_SQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MSSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MYSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ORACLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DB2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_POSTGRESQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_REDSHIFT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CLOUDSCAPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HSQLDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_PROGRESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MAXDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HANADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INGRES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FIRSTSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_EDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CACHE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ADABAS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FIREBIRD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DERBY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FILEMAKER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INFORMIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INSTANTDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INTERBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MARIADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_NETEZZA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_PERVASIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_POINTBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_SQLITE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_SYBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_TERADATA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_VERTICA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_H2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COLDFUSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CASSANDRA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MONGODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_REDIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COUCHBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COUCHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COSMOSDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DYNAMODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_NEO4J in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_GEODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ELASTICSEARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MEMCACHED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; - /** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COCKROACHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; - /** - * The constant map of values for DbSystemValues. - * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification. - */ - exports.DbSystemValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_DBSYSTEMVALUES_OTHER_SQL, - TMP_DBSYSTEMVALUES_MSSQL, - TMP_DBSYSTEMVALUES_MYSQL, - TMP_DBSYSTEMVALUES_ORACLE, - TMP_DBSYSTEMVALUES_DB2, - TMP_DBSYSTEMVALUES_POSTGRESQL, - TMP_DBSYSTEMVALUES_REDSHIFT, - TMP_DBSYSTEMVALUES_HIVE, - TMP_DBSYSTEMVALUES_CLOUDSCAPE, - TMP_DBSYSTEMVALUES_HSQLDB, - TMP_DBSYSTEMVALUES_PROGRESS, - TMP_DBSYSTEMVALUES_MAXDB, - TMP_DBSYSTEMVALUES_HANADB, - TMP_DBSYSTEMVALUES_INGRES, - TMP_DBSYSTEMVALUES_FIRSTSQL, - TMP_DBSYSTEMVALUES_EDB, - TMP_DBSYSTEMVALUES_CACHE, - TMP_DBSYSTEMVALUES_ADABAS, - TMP_DBSYSTEMVALUES_FIREBIRD, - TMP_DBSYSTEMVALUES_DERBY, - TMP_DBSYSTEMVALUES_FILEMAKER, - TMP_DBSYSTEMVALUES_INFORMIX, - TMP_DBSYSTEMVALUES_INSTANTDB, - TMP_DBSYSTEMVALUES_INTERBASE, - TMP_DBSYSTEMVALUES_MARIADB, - TMP_DBSYSTEMVALUES_NETEZZA, - TMP_DBSYSTEMVALUES_PERVASIVE, - TMP_DBSYSTEMVALUES_POINTBASE, - TMP_DBSYSTEMVALUES_SQLITE, - TMP_DBSYSTEMVALUES_SYBASE, - TMP_DBSYSTEMVALUES_TERADATA, - TMP_DBSYSTEMVALUES_VERTICA, - TMP_DBSYSTEMVALUES_H2, - TMP_DBSYSTEMVALUES_COLDFUSION, - TMP_DBSYSTEMVALUES_CASSANDRA, - TMP_DBSYSTEMVALUES_HBASE, - TMP_DBSYSTEMVALUES_MONGODB, - TMP_DBSYSTEMVALUES_REDIS, - TMP_DBSYSTEMVALUES_COUCHBASE, - TMP_DBSYSTEMVALUES_COUCHDB, - TMP_DBSYSTEMVALUES_COSMOSDB, - TMP_DBSYSTEMVALUES_DYNAMODB, - TMP_DBSYSTEMVALUES_NEO4J, - TMP_DBSYSTEMVALUES_GEODE, - TMP_DBSYSTEMVALUES_ELASTICSEARCH, - TMP_DBSYSTEMVALUES_MEMCACHED, - TMP_DBSYSTEMVALUES_COCKROACHDB - ]); - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = "all"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = "each_quorum"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = "quorum"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = "local_quorum"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = "one"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = "two"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = "three"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = "local_one"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = "any"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = "serial"; - var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = "local_serial"; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ALL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_EACH_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_TWO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_THREE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ANY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; - /** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; - /** - * The constant map of values for DbCassandraConsistencyLevelValues. - * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification. - */ - exports.DbCassandraConsistencyLevelValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL - ]); - var TMP_FAASTRIGGERVALUES_DATASOURCE = "datasource"; - var TMP_FAASTRIGGERVALUES_HTTP = "http"; - var TMP_FAASTRIGGERVALUES_PUBSUB = "pubsub"; - var TMP_FAASTRIGGERVALUES_TIMER = "timer"; - var TMP_FAASTRIGGERVALUES_OTHER = "other"; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_DATASOURCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_HTTP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_PUBSUB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_TIMER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; - /** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; - /** - * The constant map of values for FaasTriggerValues. - * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification. - */ - exports.FaasTriggerValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_FAASTRIGGERVALUES_DATASOURCE, - TMP_FAASTRIGGERVALUES_HTTP, - TMP_FAASTRIGGERVALUES_PUBSUB, - TMP_FAASTRIGGERVALUES_TIMER, - TMP_FAASTRIGGERVALUES_OTHER - ]); - var TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = "insert"; - var TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = "edit"; - var TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = "delete"; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_INSERT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_EDIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; - /** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_DELETE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; - /** - * The constant map of values for FaasDocumentOperationValues. - * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification. - */ - exports.FaasDocumentOperationValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, - TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, - TMP_FAASDOCUMENTOPERATIONVALUES_DELETE - ]); - var TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; - var TMP_FAASINVOKEDPROVIDERVALUES_AWS = "aws"; - var TMP_FAASINVOKEDPROVIDERVALUES_AZURE = "azure"; - var TMP_FAASINVOKEDPROVIDERVALUES_GCP = "gcp"; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; - /** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; - /** - * The constant map of values for FaasInvokedProviderValues. - * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification. - */ - exports.FaasInvokedProviderValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, - TMP_FAASINVOKEDPROVIDERVALUES_AWS, - TMP_FAASINVOKEDPROVIDERVALUES_AZURE, - TMP_FAASINVOKEDPROVIDERVALUES_GCP - ]); - var TMP_NETTRANSPORTVALUES_IP_TCP = "ip_tcp"; - var TMP_NETTRANSPORTVALUES_IP_UDP = "ip_udp"; - var TMP_NETTRANSPORTVALUES_IP = "ip"; - var TMP_NETTRANSPORTVALUES_UNIX = "unix"; - var TMP_NETTRANSPORTVALUES_PIPE = "pipe"; - var TMP_NETTRANSPORTVALUES_INPROC = "inproc"; - var TMP_NETTRANSPORTVALUES_OTHER = "other"; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_IP_TCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_IP_UDP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; - /** - * Transport protocol used. See note below. - * - * @deprecated Removed in v1.21.0. - */ - exports.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; - /** - * Transport protocol used. See note below. - * - * @deprecated Removed in v1.21.0. - */ - exports.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_PIPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_INPROC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; - /** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; - /** - * The constant map of values for NetTransportValues. - * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification. - */ - exports.NetTransportValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_NETTRANSPORTVALUES_IP_TCP, - TMP_NETTRANSPORTVALUES_IP_UDP, - TMP_NETTRANSPORTVALUES_IP, - TMP_NETTRANSPORTVALUES_UNIX, - TMP_NETTRANSPORTVALUES_PIPE, - TMP_NETTRANSPORTVALUES_INPROC, - TMP_NETTRANSPORTVALUES_OTHER - ]); - var TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = "wifi"; - var TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = "wired"; - var TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = "cell"; - var TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = "unavailable"; - var TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = "unknown"; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIFI in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIRED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_CELL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; - /** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; - /** - * The constant map of values for NetHostConnectionTypeValues. - * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification. - */ - exports.NetHostConnectionTypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, - TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, - TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, - TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, - TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN - ]); - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = "gprs"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = "edge"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = "umts"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = "cdma"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = "evdo_0"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = "evdo_a"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = "cdma2000_1xrtt"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = "hsdpa"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = "hsupa"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = "hspa"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = "iden"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = "evdo_b"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = "lte"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = "ehrpd"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = "hspap"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = "gsm"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = "td_scdma"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = "iwlan"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = "nr"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = "nrnsa"; - var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = "lte_ca"; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GPRS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EDGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_UMTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_A in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA2000_1XRTT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSDPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSUPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IDEN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_B in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EHRPD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPAP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GSM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_TD_SCDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IWLAN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NRNSA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; - /** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE_CA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; - /** - * The constant map of values for NetHostConnectionSubtypeValues. - * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification. - */ - exports.NetHostConnectionSubtypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA - ]); - var TMP_HTTPFLAVORVALUES_HTTP_1_0 = "1.0"; - var TMP_HTTPFLAVORVALUES_HTTP_1_1 = "1.1"; - var TMP_HTTPFLAVORVALUES_HTTP_2_0 = "2.0"; - var TMP_HTTPFLAVORVALUES_SPDY = "SPDY"; - var TMP_HTTPFLAVORVALUES_QUIC = "QUIC"; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_1 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_2_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_SPDY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; - /** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_QUIC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; - /** - * The constant map of values for HttpFlavorValues. - * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification. - */ - exports.HttpFlavorValues = { - HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, - HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, - HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, - SPDY: TMP_HTTPFLAVORVALUES_SPDY, - QUIC: TMP_HTTPFLAVORVALUES_QUIC - }; - var TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = "queue"; - var TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = "topic"; - /** - * The kind of message destination. - * - * @deprecated Removed in semconv v1.20.0. - */ - exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; - /** - * The kind of message destination. - * - * @deprecated Removed in semconv v1.20.0. - */ - exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; - /** - * The constant map of values for MessagingDestinationKindValues. - * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification. - */ - exports.MessagingDestinationKindValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC]); - var TMP_MESSAGINGOPERATIONVALUES_RECEIVE = "receive"; - var TMP_MESSAGINGOPERATIONVALUES_PROCESS = "process"; - /** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_RECEIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; - /** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_PROCESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; - /** - * The constant map of values for MessagingOperationValues. - * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification. - */ - exports.MessagingOperationValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_MESSAGINGOPERATIONVALUES_RECEIVE, TMP_MESSAGINGOPERATIONVALUES_PROCESS]); - var TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; - var TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; - var TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; - var TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; - var TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; - var TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; - var TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; - var TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; - var TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; - var TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; - var TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; - var TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; - var TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; - var TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; - var TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; - var TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; - var TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_CANCELLED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INVALID_ARGUMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DEADLINE_EXCEEDED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_NOT_FOUND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ALREADY_EXISTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_PERMISSION_DENIED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_RESOURCE_EXHAUSTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_FAILED_PRECONDITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ABORTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OUT_OF_RANGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNIMPLEMENTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INTERNAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DATA_LOSS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; - /** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAUTHENTICATED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; - /** - * The constant map of values for RpcGrpcStatusCodeValues. - * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification. - */ - exports.RpcGrpcStatusCodeValues = { - OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, - CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, - UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, - INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, - DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, - NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, - ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, - PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, - RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, - FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, - ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, - OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, - UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, - INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, - UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, - DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, - UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED - }; - var TMP_MESSAGETYPEVALUES_SENT = "SENT"; - var TMP_MESSAGETYPEVALUES_RECEIVED = "RECEIVED"; - /** - * Whether this is a received or sent message. - * - * @deprecated Use MESSAGE_TYPE_VALUE_SENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; - /** - * Whether this is a received or sent message. - * - * @deprecated Use MESSAGE_TYPE_VALUE_RECEIVED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; - /** - * The constant map of values for MessageTypeValues. - * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification. - */ - exports.MessageTypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_MESSAGETYPEVALUES_SENT, TMP_MESSAGETYPEVALUES_RECEIVED]); -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js -var require_trace = /* @__PURE__ */ __commonJSMin(((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { - enumerable: true, - get: function() { - return m[k]; - } - }; - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = exports && exports.__exportStar || function(m, exports$3) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$3, p)) __createBinding(exports$3, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - __exportStar(require_SemanticAttributes(), exports); -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js -var require_SemanticResourceAttributes = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SEMRESATTRS_K8S_STATEFULSET_NAME = exports.SEMRESATTRS_K8S_STATEFULSET_UID = exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = exports.SEMRESATTRS_K8S_REPLICASET_NAME = exports.SEMRESATTRS_K8S_REPLICASET_UID = exports.SEMRESATTRS_K8S_CONTAINER_NAME = exports.SEMRESATTRS_K8S_POD_NAME = exports.SEMRESATTRS_K8S_POD_UID = exports.SEMRESATTRS_K8S_NAMESPACE_NAME = exports.SEMRESATTRS_K8S_NODE_UID = exports.SEMRESATTRS_K8S_NODE_NAME = exports.SEMRESATTRS_K8S_CLUSTER_NAME = exports.SEMRESATTRS_HOST_IMAGE_VERSION = exports.SEMRESATTRS_HOST_IMAGE_ID = exports.SEMRESATTRS_HOST_IMAGE_NAME = exports.SEMRESATTRS_HOST_ARCH = exports.SEMRESATTRS_HOST_TYPE = exports.SEMRESATTRS_HOST_NAME = exports.SEMRESATTRS_HOST_ID = exports.SEMRESATTRS_FAAS_MAX_MEMORY = exports.SEMRESATTRS_FAAS_INSTANCE = exports.SEMRESATTRS_FAAS_VERSION = exports.SEMRESATTRS_FAAS_ID = exports.SEMRESATTRS_FAAS_NAME = exports.SEMRESATTRS_DEVICE_MODEL_NAME = exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = exports.SEMRESATTRS_DEVICE_ID = exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = exports.SEMRESATTRS_CONTAINER_RUNTIME = exports.SEMRESATTRS_CONTAINER_ID = exports.SEMRESATTRS_CONTAINER_NAME = exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = exports.SEMRESATTRS_AWS_ECS_TASK_ARN = exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = exports.SEMRESATTRS_CLOUD_PLATFORM = exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = exports.SEMRESATTRS_CLOUD_REGION = exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = exports.SEMRESATTRS_CLOUD_PROVIDER = void 0; - exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = exports.CLOUDPLATFORMVALUES_AZURE_AKS = exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = exports.CLOUDPLATFORMVALUES_AZURE_VM = exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = exports.CLOUDPLATFORMVALUES_AWS_EKS = exports.CLOUDPLATFORMVALUES_AWS_ECS = exports.CLOUDPLATFORMVALUES_AWS_EC2 = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = exports.CloudProviderValues = exports.CLOUDPROVIDERVALUES_GCP = exports.CLOUDPROVIDERVALUES_AZURE = exports.CLOUDPROVIDERVALUES_AWS = exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = exports.SemanticResourceAttributes = exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = exports.SEMRESATTRS_WEBENGINE_VERSION = exports.SEMRESATTRS_WEBENGINE_NAME = exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = exports.SEMRESATTRS_TELEMETRY_SDK_NAME = exports.SEMRESATTRS_SERVICE_VERSION = exports.SEMRESATTRS_SERVICE_INSTANCE_ID = exports.SEMRESATTRS_SERVICE_NAMESPACE = exports.SEMRESATTRS_SERVICE_NAME = exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = exports.SEMRESATTRS_PROCESS_OWNER = exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = exports.SEMRESATTRS_PROCESS_COMMAND_LINE = exports.SEMRESATTRS_PROCESS_COMMAND = exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = exports.SEMRESATTRS_PROCESS_PID = exports.SEMRESATTRS_OS_VERSION = exports.SEMRESATTRS_OS_NAME = exports.SEMRESATTRS_OS_DESCRIPTION = exports.SEMRESATTRS_OS_TYPE = exports.SEMRESATTRS_K8S_CRONJOB_NAME = exports.SEMRESATTRS_K8S_CRONJOB_UID = exports.SEMRESATTRS_K8S_JOB_NAME = exports.SEMRESATTRS_K8S_JOB_UID = exports.SEMRESATTRS_K8S_DAEMONSET_NAME = exports.SEMRESATTRS_K8S_DAEMONSET_UID = void 0; - exports.TelemetrySdkLanguageValues = exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = exports.TELEMETRYSDKLANGUAGEVALUES_PHP = exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = exports.TELEMETRYSDKLANGUAGEVALUES_GO = exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = exports.TELEMETRYSDKLANGUAGEVALUES_CPP = exports.OsTypeValues = exports.OSTYPEVALUES_Z_OS = exports.OSTYPEVALUES_SOLARIS = exports.OSTYPEVALUES_AIX = exports.OSTYPEVALUES_HPUX = exports.OSTYPEVALUES_DRAGONFLYBSD = exports.OSTYPEVALUES_OPENBSD = exports.OSTYPEVALUES_NETBSD = exports.OSTYPEVALUES_FREEBSD = exports.OSTYPEVALUES_DARWIN = exports.OSTYPEVALUES_LINUX = exports.OSTYPEVALUES_WINDOWS = exports.HostArchValues = exports.HOSTARCHVALUES_X86 = exports.HOSTARCHVALUES_PPC64 = exports.HOSTARCHVALUES_PPC32 = exports.HOSTARCHVALUES_IA64 = exports.HOSTARCHVALUES_ARM64 = exports.HOSTARCHVALUES_ARM32 = exports.HOSTARCHVALUES_AMD64 = exports.AwsEcsLaunchtypeValues = exports.AWSECSLAUNCHTYPEVALUES_FARGATE = exports.AWSECSLAUNCHTYPEVALUES_EC2 = exports.CloudPlatformValues = exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = void 0; - var utils_1 = require_utils(); - var TMP_CLOUD_PROVIDER = "cloud.provider"; - var TMP_CLOUD_ACCOUNT_ID = "cloud.account.id"; - var TMP_CLOUD_REGION = "cloud.region"; - var TMP_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone"; - var TMP_CLOUD_PLATFORM = "cloud.platform"; - var TMP_AWS_ECS_CONTAINER_ARN = "aws.ecs.container.arn"; - var TMP_AWS_ECS_CLUSTER_ARN = "aws.ecs.cluster.arn"; - var TMP_AWS_ECS_LAUNCHTYPE = "aws.ecs.launchtype"; - var TMP_AWS_ECS_TASK_ARN = "aws.ecs.task.arn"; - var TMP_AWS_ECS_TASK_FAMILY = "aws.ecs.task.family"; - var TMP_AWS_ECS_TASK_REVISION = "aws.ecs.task.revision"; - var TMP_AWS_EKS_CLUSTER_ARN = "aws.eks.cluster.arn"; - var TMP_AWS_LOG_GROUP_NAMES = "aws.log.group.names"; - var TMP_AWS_LOG_GROUP_ARNS = "aws.log.group.arns"; - var TMP_AWS_LOG_STREAM_NAMES = "aws.log.stream.names"; - var TMP_AWS_LOG_STREAM_ARNS = "aws.log.stream.arns"; - var TMP_CONTAINER_NAME = "container.name"; - var TMP_CONTAINER_ID = "container.id"; - var TMP_CONTAINER_RUNTIME = "container.runtime"; - var TMP_CONTAINER_IMAGE_NAME = "container.image.name"; - var TMP_CONTAINER_IMAGE_TAG = "container.image.tag"; - var TMP_DEPLOYMENT_ENVIRONMENT = "deployment.environment"; - var TMP_DEVICE_ID = "device.id"; - var TMP_DEVICE_MODEL_IDENTIFIER = "device.model.identifier"; - var TMP_DEVICE_MODEL_NAME = "device.model.name"; - var TMP_FAAS_NAME = "faas.name"; - var TMP_FAAS_ID = "faas.id"; - var TMP_FAAS_VERSION = "faas.version"; - var TMP_FAAS_INSTANCE = "faas.instance"; - var TMP_FAAS_MAX_MEMORY = "faas.max_memory"; - var TMP_HOST_ID = "host.id"; - var TMP_HOST_NAME = "host.name"; - var TMP_HOST_TYPE = "host.type"; - var TMP_HOST_ARCH = "host.arch"; - var TMP_HOST_IMAGE_NAME = "host.image.name"; - var TMP_HOST_IMAGE_ID = "host.image.id"; - var TMP_HOST_IMAGE_VERSION = "host.image.version"; - var TMP_K8S_CLUSTER_NAME = "k8s.cluster.name"; - var TMP_K8S_NODE_NAME = "k8s.node.name"; - var TMP_K8S_NODE_UID = "k8s.node.uid"; - var TMP_K8S_NAMESPACE_NAME = "k8s.namespace.name"; - var TMP_K8S_POD_UID = "k8s.pod.uid"; - var TMP_K8S_POD_NAME = "k8s.pod.name"; - var TMP_K8S_CONTAINER_NAME = "k8s.container.name"; - var TMP_K8S_REPLICASET_UID = "k8s.replicaset.uid"; - var TMP_K8S_REPLICASET_NAME = "k8s.replicaset.name"; - var TMP_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; - var TMP_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; - var TMP_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; - var TMP_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; - var TMP_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; - var TMP_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; - var TMP_K8S_JOB_UID = "k8s.job.uid"; - var TMP_K8S_JOB_NAME = "k8s.job.name"; - var TMP_K8S_CRONJOB_UID = "k8s.cronjob.uid"; - var TMP_K8S_CRONJOB_NAME = "k8s.cronjob.name"; - var TMP_OS_TYPE = "os.type"; - var TMP_OS_DESCRIPTION = "os.description"; - var TMP_OS_NAME = "os.name"; - var TMP_OS_VERSION = "os.version"; - var TMP_PROCESS_PID = "process.pid"; - var TMP_PROCESS_EXECUTABLE_NAME = "process.executable.name"; - var TMP_PROCESS_EXECUTABLE_PATH = "process.executable.path"; - var TMP_PROCESS_COMMAND = "process.command"; - var TMP_PROCESS_COMMAND_LINE = "process.command_line"; - var TMP_PROCESS_COMMAND_ARGS = "process.command_args"; - var TMP_PROCESS_OWNER = "process.owner"; - var TMP_PROCESS_RUNTIME_NAME = "process.runtime.name"; - var TMP_PROCESS_RUNTIME_VERSION = "process.runtime.version"; - var TMP_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description"; - var TMP_SERVICE_NAME = "service.name"; - var TMP_SERVICE_NAMESPACE = "service.namespace"; - var TMP_SERVICE_INSTANCE_ID = "service.instance.id"; - var TMP_SERVICE_VERSION = "service.version"; - var TMP_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; - var TMP_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; - var TMP_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; - var TMP_TELEMETRY_AUTO_VERSION = "telemetry.auto.version"; - var TMP_WEBENGINE_NAME = "webengine.name"; - var TMP_WEBENGINE_VERSION = "webengine.version"; - var TMP_WEBENGINE_DESCRIPTION = "webengine.description"; - /** - * Name of the cloud provider. - * - * @deprecated Use ATTR_CLOUD_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; - /** - * The cloud account ID the resource is assigned to. - * - * @deprecated Use ATTR_CLOUD_ACCOUNT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; - /** - * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations). - * - * @deprecated Use ATTR_CLOUD_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; - /** - * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running. - * - * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud. - * - * @deprecated Use ATTR_CLOUD_AVAILABILITY_ZONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use ATTR_CLOUD_PLATFORM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; - /** - * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). - * - * @deprecated Use ATTR_AWS_ECS_CONTAINER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; - /** - * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). - * - * @deprecated Use ATTR_AWS_ECS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; - /** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use ATTR_AWS_ECS_LAUNCHTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; - /** - * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). - * - * @deprecated Use ATTR_AWS_ECS_TASK_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; - /** - * The task definition family this task definition is a member of. - * - * @deprecated Use ATTR_AWS_ECS_TASK_FAMILY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; - /** - * The revision for this task definition. - * - * @deprecated Use ATTR_AWS_ECS_TASK_REVISION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; - /** - * The ARN of an EKS cluster. - * - * @deprecated Use ATTR_AWS_EKS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; - /** - * The name(s) of the AWS log group(s) an application is writing to. - * - * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group. - * - * @deprecated Use ATTR_AWS_LOG_GROUP_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; - /** - * The Amazon Resource Name(s) (ARN) of the AWS log group(s). - * - * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - * - * @deprecated Use ATTR_AWS_LOG_GROUP_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; - /** - * The name(s) of the AWS log stream(s) an application is writing to. - * - * @deprecated Use ATTR_AWS_LOG_STREAM_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; - /** - * The ARN(s) of the AWS log stream(s). - * - * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream. - * - * @deprecated Use ATTR_AWS_LOG_STREAM_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; - /** - * Container name. - * - * @deprecated Use ATTR_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; - /** - * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated. - * - * @deprecated Use ATTR_CONTAINER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; - /** - * The container runtime managing this container. - * - * @deprecated Use ATTR_CONTAINER_RUNTIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; - /** - * Name of the image the container was built on. - * - * @deprecated Use ATTR_CONTAINER_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; - /** - * Container image tag. - * - * @deprecated Use ATTR_CONTAINER_IMAGE_TAGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; - /** - * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier). - * - * @deprecated Use ATTR_DEPLOYMENT_ENVIRONMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; - /** - * A unique identifier representing the device. - * - * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence. - * - * @deprecated Use ATTR_DEVICE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; - /** - * The model identifier for the device. - * - * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device. - * - * @deprecated Use ATTR_DEVICE_MODEL_IDENTIFIER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; - /** - * The marketing name for the device model. - * - * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative. - * - * @deprecated Use ATTR_DEVICE_MODEL_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; - /** - * The name of the single function that this runtime instance executes. - * - * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes). - * - * @deprecated Use ATTR_FAAS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; - /** - * The unique ID of the single function that this runtime instance executes. - * - * Note: Depending on the cloud provider, use: - - * **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - Take care not to use the "invoked ARN" directly but replace any - [alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple - different aliases. - * **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names) - * **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id). - - On some providers, it may not be possible to determine the full ID at startup, - which is why this field cannot be made required. For example, on AWS the account ID - part of the ARN is not available without calling another AWS API - which may be deemed too slow for a short-running lambda function. - As an alternative, consider setting `faas.id` as a span attribute instead. - * - * @deprecated Use ATTR_CLOUD_RESOURCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; - /** - * The immutable version of the function being executed. - * - * Note: Depending on the cloud provider and platform, use: - - * **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) - (an integer represented as a decimal string). - * **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions) - (i.e., the function name plus the revision suffix). - * **Google Cloud Functions:** The value of the - [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). - * **Azure Functions:** Not applicable. Do not set this attribute. - * - * @deprecated Use ATTR_FAAS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; - /** - * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version. - * - * Note: * **AWS Lambda:** Use the (full) log stream name. - * - * @deprecated Use ATTR_FAAS_INSTANCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; - /** - * The amount of memory available to the serverless function in MiB. - * - * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information. - * - * @deprecated Use ATTR_FAAS_MAX_MEMORY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; - /** - * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. - * - * @deprecated Use ATTR_HOST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_ID = TMP_HOST_ID; - /** - * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user. - * - * @deprecated Use ATTR_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; - /** - * Type of host. For Cloud, this must be the machine type. - * - * @deprecated Use ATTR_HOST_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use ATTR_HOST_ARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; - /** - * Name of the VM image or OS install the host was instantiated from. - * - * @deprecated Use ATTR_HOST_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; - /** - * VM image ID. For Cloud, this value is from the provider. - * - * @deprecated Use ATTR_HOST_IMAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; - /** - * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes). - * - * @deprecated Use ATTR_HOST_IMAGE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; - /** - * The name of the cluster. - * - * @deprecated Use ATTR_K8S_CLUSTER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; - /** - * The name of the Node. - * - * @deprecated Use ATTR_K8S_NODE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; - /** - * The UID of the Node. - * - * @deprecated Use ATTR_K8S_NODE_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; - /** - * The name of the namespace that the pod is running in. - * - * @deprecated Use ATTR_K8S_NAMESPACE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; - /** - * The UID of the Pod. - * - * @deprecated Use ATTR_K8S_POD_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; - /** - * The name of the Pod. - * - * @deprecated Use ATTR_K8S_POD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; - /** - * The name of the Container in a Pod template. - * - * @deprecated Use ATTR_K8S_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; - /** - * The UID of the ReplicaSet. - * - * @deprecated Use ATTR_K8S_REPLICASET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; - /** - * The name of the ReplicaSet. - * - * @deprecated Use ATTR_K8S_REPLICASET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; - /** - * The UID of the Deployment. - * - * @deprecated Use ATTR_K8S_DEPLOYMENT_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; - /** - * The name of the Deployment. - * - * @deprecated Use ATTR_K8S_DEPLOYMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; - /** - * The UID of the StatefulSet. - * - * @deprecated Use ATTR_K8S_STATEFULSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; - /** - * The name of the StatefulSet. - * - * @deprecated Use ATTR_K8S_STATEFULSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; - /** - * The UID of the DaemonSet. - * - * @deprecated Use ATTR_K8S_DAEMONSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; - /** - * The name of the DaemonSet. - * - * @deprecated Use ATTR_K8S_DAEMONSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; - /** - * The UID of the Job. - * - * @deprecated Use ATTR_K8S_JOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; - /** - * The name of the Job. - * - * @deprecated Use ATTR_K8S_JOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; - /** - * The UID of the CronJob. - * - * @deprecated Use ATTR_K8S_CRONJOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; - /** - * The name of the CronJob. - * - * @deprecated Use ATTR_K8S_CRONJOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; - /** - * The operating system type. - * - * @deprecated Use ATTR_OS_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; - /** - * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands. - * - * @deprecated Use ATTR_OS_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; - /** - * Human readable operating system name. - * - * @deprecated Use ATTR_OS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_OS_NAME = TMP_OS_NAME; - /** - * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes). - * - * @deprecated Use ATTR_OS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; - /** - * Process identifier (PID). - * - * @deprecated Use ATTR_PROCESS_PID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; - /** - * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`. - * - * @deprecated Use ATTR_PROCESS_EXECUTABLE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; - /** - * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`. - * - * @deprecated Use ATTR_PROCESS_EXECUTABLE_PATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; - /** - * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`. - * - * @deprecated Use ATTR_PROCESS_COMMAND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; - /** - * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead. - * - * @deprecated Use ATTR_PROCESS_COMMAND_LINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; - /** - * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`. - * - * @deprecated Use ATTR_PROCESS_COMMAND_ARGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; - /** - * The username of the user that owns the process. - * - * @deprecated Use ATTR_PROCESS_OWNER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; - /** - * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler. - * - * @deprecated Use ATTR_PROCESS_RUNTIME_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; - /** - * The version of the runtime of this process, as returned by the runtime without modification. - * - * @deprecated Use ATTR_PROCESS_RUNTIME_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; - /** - * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment. - * - * @deprecated Use ATTR_PROCESS_RUNTIME_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; - /** - * Logical name of the service. - * - * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`. - * - * @deprecated Use ATTR_SERVICE_NAME. - */ - exports.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; - /** - * A namespace for `service.name`. - * - * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. - * - * @deprecated Use ATTR_SERVICE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; - /** - * The string ID of the service instance. - * - * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations). - * - * @deprecated Use ATTR_SERVICE_INSTANCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; - /** - * The version string of the service API or implementation. - * - * @deprecated Use ATTR_SERVICE_VERSION. - */ - exports.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; - /** - * The name of the telemetry SDK as defined above. - * - * @deprecated Use ATTR_TELEMETRY_SDK_NAME. - */ - exports.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; - /** - * The language of the telemetry SDK. - * - * @deprecated Use ATTR_TELEMETRY_SDK_LANGUAGE. - */ - exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; - /** - * The version string of the telemetry SDK. - * - * @deprecated Use ATTR_TELEMETRY_SDK_VERSION. - */ - exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; - /** - * The version string of the auto instrumentation agent, if used. - * - * @deprecated Use ATTR_TELEMETRY_DISTRO_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; - /** - * The name of the web engine. - * - * @deprecated Use ATTR_WEBENGINE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; - /** - * The version of the web engine. - * - * @deprecated Use ATTR_WEBENGINE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; - /** - * Additional description of the web engine (e.g. detailed version and edition information). - * - * @deprecated Use ATTR_WEBENGINE_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; - /** - * Create exported Value Map for SemanticResourceAttributes values - * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification - */ - exports.SemanticResourceAttributes = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUD_PROVIDER, - TMP_CLOUD_ACCOUNT_ID, - TMP_CLOUD_REGION, - TMP_CLOUD_AVAILABILITY_ZONE, - TMP_CLOUD_PLATFORM, - TMP_AWS_ECS_CONTAINER_ARN, - TMP_AWS_ECS_CLUSTER_ARN, - TMP_AWS_ECS_LAUNCHTYPE, - TMP_AWS_ECS_TASK_ARN, - TMP_AWS_ECS_TASK_FAMILY, - TMP_AWS_ECS_TASK_REVISION, - TMP_AWS_EKS_CLUSTER_ARN, - TMP_AWS_LOG_GROUP_NAMES, - TMP_AWS_LOG_GROUP_ARNS, - TMP_AWS_LOG_STREAM_NAMES, - TMP_AWS_LOG_STREAM_ARNS, - TMP_CONTAINER_NAME, - TMP_CONTAINER_ID, - TMP_CONTAINER_RUNTIME, - TMP_CONTAINER_IMAGE_NAME, - TMP_CONTAINER_IMAGE_TAG, - TMP_DEPLOYMENT_ENVIRONMENT, - TMP_DEVICE_ID, - TMP_DEVICE_MODEL_IDENTIFIER, - TMP_DEVICE_MODEL_NAME, - TMP_FAAS_NAME, - TMP_FAAS_ID, - TMP_FAAS_VERSION, - TMP_FAAS_INSTANCE, - TMP_FAAS_MAX_MEMORY, - TMP_HOST_ID, - TMP_HOST_NAME, - TMP_HOST_TYPE, - TMP_HOST_ARCH, - TMP_HOST_IMAGE_NAME, - TMP_HOST_IMAGE_ID, - TMP_HOST_IMAGE_VERSION, - TMP_K8S_CLUSTER_NAME, - TMP_K8S_NODE_NAME, - TMP_K8S_NODE_UID, - TMP_K8S_NAMESPACE_NAME, - TMP_K8S_POD_UID, - TMP_K8S_POD_NAME, - TMP_K8S_CONTAINER_NAME, - TMP_K8S_REPLICASET_UID, - TMP_K8S_REPLICASET_NAME, - TMP_K8S_DEPLOYMENT_UID, - TMP_K8S_DEPLOYMENT_NAME, - TMP_K8S_STATEFULSET_UID, - TMP_K8S_STATEFULSET_NAME, - TMP_K8S_DAEMONSET_UID, - TMP_K8S_DAEMONSET_NAME, - TMP_K8S_JOB_UID, - TMP_K8S_JOB_NAME, - TMP_K8S_CRONJOB_UID, - TMP_K8S_CRONJOB_NAME, - TMP_OS_TYPE, - TMP_OS_DESCRIPTION, - TMP_OS_NAME, - TMP_OS_VERSION, - TMP_PROCESS_PID, - TMP_PROCESS_EXECUTABLE_NAME, - TMP_PROCESS_EXECUTABLE_PATH, - TMP_PROCESS_COMMAND, - TMP_PROCESS_COMMAND_LINE, - TMP_PROCESS_COMMAND_ARGS, - TMP_PROCESS_OWNER, - TMP_PROCESS_RUNTIME_NAME, - TMP_PROCESS_RUNTIME_VERSION, - TMP_PROCESS_RUNTIME_DESCRIPTION, - TMP_SERVICE_NAME, - TMP_SERVICE_NAMESPACE, - TMP_SERVICE_INSTANCE_ID, - TMP_SERVICE_VERSION, - TMP_TELEMETRY_SDK_NAME, - TMP_TELEMETRY_SDK_LANGUAGE, - TMP_TELEMETRY_SDK_VERSION, - TMP_TELEMETRY_AUTO_VERSION, - TMP_WEBENGINE_NAME, - TMP_WEBENGINE_VERSION, - TMP_WEBENGINE_DESCRIPTION - ]); - var TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; - var TMP_CLOUDPROVIDERVALUES_AWS = "aws"; - var TMP_CLOUDPROVIDERVALUES_AZURE = "azure"; - var TMP_CLOUDPROVIDERVALUES_GCP = "gcp"; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; - /** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; - /** - * The constant map of values for CloudProviderValues. - * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification. - */ - exports.CloudProviderValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, - TMP_CLOUDPROVIDERVALUES_AWS, - TMP_CLOUDPROVIDERVALUES_AZURE, - TMP_CLOUDPROVIDERVALUES_GCP - ]); - var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs"; - var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = "alibaba_cloud_fc"; - var TMP_CLOUDPLATFORMVALUES_AWS_EC2 = "aws_ec2"; - var TMP_CLOUDPLATFORMVALUES_AWS_ECS = "aws_ecs"; - var TMP_CLOUDPLATFORMVALUES_AWS_EKS = "aws_eks"; - var TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = "aws_lambda"; - var TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk"; - var TMP_CLOUDPLATFORMVALUES_AZURE_VM = "azure_vm"; - var TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = "azure_container_instances"; - var TMP_CLOUDPLATFORMVALUES_AZURE_AKS = "azure_aks"; - var TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = "azure_functions"; - var TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = "azure_app_service"; - var TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = "gcp_compute_engine"; - var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = "gcp_cloud_run"; - var TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine"; - var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions"; - var TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = "gcp_app_engine"; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_FC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_LAMBDA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ELASTIC_BEANSTALK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_VM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_CONTAINER_INSTANCES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_AKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_APP_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_COMPUTE_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_RUN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_KUBERNETES_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; - /** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_APP_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; - /** - * The constant map of values for CloudPlatformValues. - * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification. - */ - exports.CloudPlatformValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, - TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, - TMP_CLOUDPLATFORMVALUES_AWS_EC2, - TMP_CLOUDPLATFORMVALUES_AWS_ECS, - TMP_CLOUDPLATFORMVALUES_AWS_EKS, - TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, - TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, - TMP_CLOUDPLATFORMVALUES_AZURE_VM, - TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, - TMP_CLOUDPLATFORMVALUES_AZURE_AKS, - TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, - TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, - TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, - TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, - TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, - TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, - TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE - ]); - var TMP_AWSECSLAUNCHTYPEVALUES_EC2 = "ec2"; - var TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = "fargate"; - /** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; - /** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_FARGATE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; - /** - * The constant map of values for AwsEcsLaunchtypeValues. - * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification. - */ - exports.AwsEcsLaunchtypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_AWSECSLAUNCHTYPEVALUES_EC2, TMP_AWSECSLAUNCHTYPEVALUES_FARGATE]); - var TMP_HOSTARCHVALUES_AMD64 = "amd64"; - var TMP_HOSTARCHVALUES_ARM32 = "arm32"; - var TMP_HOSTARCHVALUES_ARM64 = "arm64"; - var TMP_HOSTARCHVALUES_IA64 = "ia64"; - var TMP_HOSTARCHVALUES_PPC32 = "ppc32"; - var TMP_HOSTARCHVALUES_PPC64 = "ppc64"; - var TMP_HOSTARCHVALUES_X86 = "x86"; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_AMD64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_ARM32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_ARM64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_IA64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_PPC32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_PPC64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; - /** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_X86 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; - /** - * The constant map of values for HostArchValues. - * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification. - */ - exports.HostArchValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_HOSTARCHVALUES_AMD64, - TMP_HOSTARCHVALUES_ARM32, - TMP_HOSTARCHVALUES_ARM64, - TMP_HOSTARCHVALUES_IA64, - TMP_HOSTARCHVALUES_PPC32, - TMP_HOSTARCHVALUES_PPC64, - TMP_HOSTARCHVALUES_X86 - ]); - var TMP_OSTYPEVALUES_WINDOWS = "windows"; - var TMP_OSTYPEVALUES_LINUX = "linux"; - var TMP_OSTYPEVALUES_DARWIN = "darwin"; - var TMP_OSTYPEVALUES_FREEBSD = "freebsd"; - var TMP_OSTYPEVALUES_NETBSD = "netbsd"; - var TMP_OSTYPEVALUES_OPENBSD = "openbsd"; - var TMP_OSTYPEVALUES_DRAGONFLYBSD = "dragonflybsd"; - var TMP_OSTYPEVALUES_HPUX = "hpux"; - var TMP_OSTYPEVALUES_AIX = "aix"; - var TMP_OSTYPEVALUES_SOLARIS = "solaris"; - var TMP_OSTYPEVALUES_Z_OS = "z_os"; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_WINDOWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_LINUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_DARWIN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_FREEBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_NETBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_OPENBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_DRAGONFLYBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_HPUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_AIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_SOLARIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; - /** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_Z_OS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ - exports.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; - /** - * The constant map of values for OsTypeValues. - * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification. - */ - exports.OsTypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_OSTYPEVALUES_WINDOWS, - TMP_OSTYPEVALUES_LINUX, - TMP_OSTYPEVALUES_DARWIN, - TMP_OSTYPEVALUES_FREEBSD, - TMP_OSTYPEVALUES_NETBSD, - TMP_OSTYPEVALUES_OPENBSD, - TMP_OSTYPEVALUES_DRAGONFLYBSD, - TMP_OSTYPEVALUES_HPUX, - TMP_OSTYPEVALUES_AIX, - TMP_OSTYPEVALUES_SOLARIS, - TMP_OSTYPEVALUES_Z_OS - ]); - var TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = "cpp"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = "dotnet"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = "erlang"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_GO = "go"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = "java"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = "nodejs"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = "php"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = "python"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = "ruby"; - var TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = "webjs"; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_CPP. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_GO. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_JAVA. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PHP. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_RUBY. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; - /** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS. - */ - exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; - /** - * The constant map of values for TelemetrySdkLanguageValues. - * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification. - */ - exports.TelemetrySdkLanguageValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, - TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, - TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, - TMP_TELEMETRYSDKLANGUAGEVALUES_GO, - TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, - TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, - TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, - TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, - TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, - TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS - ]); -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js -var require_resource = /* @__PURE__ */ __commonJSMin(((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { - enumerable: true, - get: function() { - return m[k]; - } - }; - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = exports && exports.__exportStar || function(m, exports$2) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$2, p)) __createBinding(exports$2, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - __exportStar(require_SemanticResourceAttributes(), exports); -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js -var require_stable_attributes = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = exports.ATTR_DOTNET_GC_HEAP_GENERATION = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = exports.ATTR_DEPLOYMENT_ENVIRONMENT_NAME = exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = exports.DB_SYSTEM_NAME_VALUE_MYSQL = exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = exports.DB_SYSTEM_NAME_VALUE_MARIADB = exports.ATTR_DB_SYSTEM_NAME = exports.ATTR_DB_STORED_PROCEDURE_NAME = exports.ATTR_DB_RESPONSE_STATUS_CODE = exports.ATTR_DB_QUERY_TEXT = exports.ATTR_DB_QUERY_SUMMARY = exports.ATTR_DB_OPERATION_NAME = exports.ATTR_DB_OPERATION_BATCH_SIZE = exports.ATTR_DB_NAMESPACE = exports.ATTR_DB_COLLECTION_NAME = exports.ATTR_CONTAINER_IMAGE_TAGS = exports.ATTR_CONTAINER_IMAGE_REPO_DIGESTS = exports.ATTR_CONTAINER_IMAGE_NAME = exports.ATTR_CONTAINER_ID = exports.ATTR_CODE_STACKTRACE = exports.ATTR_CODE_LINE_NUMBER = exports.ATTR_CODE_FUNCTION_NAME = exports.ATTR_CODE_FILE_PATH = exports.ATTR_CODE_COLUMN_NUMBER = exports.ATTR_CLIENT_PORT = exports.ATTR_CLIENT_ADDRESS = exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = void 0; - exports.ATTR_K8S_DAEMONSET_LABEL = exports.ATTR_K8S_DAEMONSET_ANNOTATION = exports.ATTR_K8S_CRONJOB_UID = exports.ATTR_K8S_CRONJOB_NAME = exports.ATTR_K8S_CRONJOB_LABEL = exports.ATTR_K8S_CRONJOB_ANNOTATION = exports.ATTR_K8S_CONTAINER_RESTART_COUNT = exports.ATTR_K8S_CONTAINER_NAME = exports.ATTR_K8S_CLUSTER_UID = exports.ATTR_K8S_CLUSTER_NAME = exports.JVM_THREAD_STATE_VALUE_WAITING = exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = exports.JVM_THREAD_STATE_VALUE_TERMINATED = exports.JVM_THREAD_STATE_VALUE_RUNNABLE = exports.JVM_THREAD_STATE_VALUE_NEW = exports.JVM_THREAD_STATE_VALUE_BLOCKED = exports.ATTR_JVM_THREAD_STATE = exports.ATTR_JVM_THREAD_DAEMON = exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = exports.JVM_MEMORY_TYPE_VALUE_HEAP = exports.ATTR_JVM_MEMORY_TYPE = exports.ATTR_JVM_MEMORY_POOL_NAME = exports.ATTR_JVM_GC_NAME = exports.ATTR_JVM_GC_ACTION = exports.ATTR_HTTP_ROUTE = exports.ATTR_HTTP_RESPONSE_STATUS_CODE = exports.ATTR_HTTP_RESPONSE_HEADER = exports.ATTR_HTTP_REQUEST_RESEND_COUNT = exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = exports.HTTP_REQUEST_METHOD_VALUE_TRACE = exports.HTTP_REQUEST_METHOD_VALUE_PUT = exports.HTTP_REQUEST_METHOD_VALUE_POST = exports.HTTP_REQUEST_METHOD_VALUE_PATCH = exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = exports.HTTP_REQUEST_METHOD_VALUE_HEAD = exports.HTTP_REQUEST_METHOD_VALUE_GET = exports.HTTP_REQUEST_METHOD_VALUE_DELETE = exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = exports.HTTP_REQUEST_METHOD_VALUE_OTHER = exports.ATTR_HTTP_REQUEST_METHOD = exports.ATTR_HTTP_REQUEST_HEADER = exports.ATTR_EXCEPTION_TYPE = exports.ATTR_EXCEPTION_STACKTRACE = exports.ATTR_EXCEPTION_MESSAGE = exports.ATTR_EXCEPTION_ESCAPED = exports.ERROR_TYPE_VALUE_OTHER = exports.ATTR_ERROR_TYPE = exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = void 0; - exports.ATTR_OTEL_SCOPE_VERSION = exports.ATTR_OTEL_SCOPE_NAME = exports.ATTR_OTEL_EVENT_NAME = exports.NETWORK_TYPE_VALUE_IPV6 = exports.NETWORK_TYPE_VALUE_IPV4 = exports.ATTR_NETWORK_TYPE = exports.NETWORK_TRANSPORT_VALUE_UNIX = exports.NETWORK_TRANSPORT_VALUE_UDP = exports.NETWORK_TRANSPORT_VALUE_TCP = exports.NETWORK_TRANSPORT_VALUE_QUIC = exports.NETWORK_TRANSPORT_VALUE_PIPE = exports.ATTR_NETWORK_TRANSPORT = exports.ATTR_NETWORK_PROTOCOL_VERSION = exports.ATTR_NETWORK_PROTOCOL_NAME = exports.ATTR_NETWORK_PEER_PORT = exports.ATTR_NETWORK_PEER_ADDRESS = exports.ATTR_NETWORK_LOCAL_PORT = exports.ATTR_NETWORK_LOCAL_ADDRESS = exports.ATTR_K8S_STATEFULSET_UID = exports.ATTR_K8S_STATEFULSET_NAME = exports.ATTR_K8S_STATEFULSET_LABEL = exports.ATTR_K8S_STATEFULSET_ANNOTATION = exports.ATTR_K8S_REPLICASET_UID = exports.ATTR_K8S_REPLICASET_NAME = exports.ATTR_K8S_REPLICASET_LABEL = exports.ATTR_K8S_REPLICASET_ANNOTATION = exports.ATTR_K8S_POD_UID = exports.ATTR_K8S_POD_START_TIME = exports.ATTR_K8S_POD_NAME = exports.ATTR_K8S_POD_LABEL = exports.ATTR_K8S_POD_IP = exports.ATTR_K8S_POD_HOSTNAME = exports.ATTR_K8S_POD_ANNOTATION = exports.ATTR_K8S_NODE_UID = exports.ATTR_K8S_NODE_NAME = exports.ATTR_K8S_NODE_LABEL = exports.ATTR_K8S_NODE_ANNOTATION = exports.ATTR_K8S_NAMESPACE_NAME = exports.ATTR_K8S_NAMESPACE_LABEL = exports.ATTR_K8S_NAMESPACE_ANNOTATION = exports.ATTR_K8S_JOB_UID = exports.ATTR_K8S_JOB_NAME = exports.ATTR_K8S_JOB_LABEL = exports.ATTR_K8S_JOB_ANNOTATION = exports.ATTR_K8S_DEPLOYMENT_UID = exports.ATTR_K8S_DEPLOYMENT_NAME = exports.ATTR_K8S_DEPLOYMENT_LABEL = exports.ATTR_K8S_DEPLOYMENT_ANNOTATION = exports.ATTR_K8S_DAEMONSET_UID = exports.ATTR_K8S_DAEMONSET_NAME = void 0; - exports.ATTR_USER_AGENT_ORIGINAL = exports.ATTR_URL_SCHEME = exports.ATTR_URL_QUERY = exports.ATTR_URL_PATH = exports.ATTR_URL_FULL = exports.ATTR_URL_FRAGMENT = exports.ATTR_TELEMETRY_SDK_VERSION = exports.ATTR_TELEMETRY_SDK_NAME = exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN = exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = exports.ATTR_TELEMETRY_SDK_LANGUAGE = exports.ATTR_TELEMETRY_DISTRO_VERSION = exports.ATTR_TELEMETRY_DISTRO_NAME = exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = exports.ATTR_SIGNALR_TRANSPORT = exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = exports.ATTR_SIGNALR_CONNECTION_STATUS = exports.ATTR_SERVICE_VERSION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_NAME = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_SERVER_PORT = exports.ATTR_SERVER_ADDRESS = exports.ATTR_OTEL_STATUS_DESCRIPTION = exports.OTEL_STATUS_CODE_VALUE_OK = exports.OTEL_STATUS_CODE_VALUE_ERROR = exports.ATTR_OTEL_STATUS_CODE = void 0; - /** - * ASP.NET Core exception middleware handling result. - * - * @example handled - * @example unhandled - */ - exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = "aspnetcore.diagnostics.exception.result"; - /** - * Enum value "aborted" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception handling didn't run because the request was aborted. - */ - exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; - /** - * Enum value "handled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception was handled by the exception handling middleware. - */ - exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; - /** - * Enum value "skipped" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception handling was skipped because the response had started. - */ - exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; - /** - * Enum value "unhandled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception was not handled by the exception handling middleware. - */ - exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; - /** - * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception. - * - * @example Contoso.MyHandler - */ - exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = "aspnetcore.diagnostics.handler.type"; - /** - * Rate limiting policy name. - * - * @example fixed - * @example sliding - * @example token - */ - exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = "aspnetcore.rate_limiting.policy"; - /** - * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason - * - * @example acquired - * @example request_canceled - */ - exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = "aspnetcore.rate_limiting.result"; - /** - * Enum value "acquired" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease was acquired - */ - exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; - /** - * Enum value "endpoint_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease request was rejected by the endpoint limiter - */ - exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; - /** - * Enum value "global_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease request was rejected by the global limiter - */ - exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; - /** - * Enum value "request_canceled" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease request was canceled - */ - exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; - /** - * Flag indicating if request was handled by the application pipeline. - * - * @example true - */ - exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = "aspnetcore.request.is_unhandled"; - /** - * A value that indicates whether the matched route is a fallback route. - * - * @example true - */ - exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = "aspnetcore.routing.is_fallback"; - /** - * Match result - success or failure - * - * @example success - * @example failure - */ - exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = "aspnetcore.routing.match_status"; - /** - * Enum value "failure" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. - * - * Match failed - */ - exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; - /** - * Enum value "success" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. - * - * Match succeeded - */ - exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; - /** - * A value that indicates whether the user is authenticated. - * - * @example true - */ - exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = "aspnetcore.user.is_authenticated"; - /** - * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. - * - * @example client.example.com - * @example 10.1.2.80 - * @example /tmp/my.sock - * - * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available. - */ - exports.ATTR_CLIENT_ADDRESS = "client.address"; - /** - * Client port number. - * - * @example 65123 - * - * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available. - */ - exports.ATTR_CLIENT_PORT = "client.port"; - /** - * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example 16 - */ - exports.ATTR_CODE_COLUMN_NUMBER = "code.column.number"; - /** - * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example "/usr/local/MyApplication/content_root/app/index.php" - */ - exports.ATTR_CODE_FILE_PATH = "code.file.path"; - /** - * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example com.example.MyHttpService.serveRequest - * @example GuzzleHttp\\Client::transfer - * @example fopen - * - * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples. - * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in - * `code.stacktrace` without information on arguments. - * - * Examples: - * - * - Java method: `com.example.MyHttpService.serveRequest` - * - Java anonymous class method: `com.mycompany.Main$1.myMethod` - * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod` - * - PHP function: `GuzzleHttp\Client::transfer` - * - Go function: `github.com/my/repo/pkg.foo.func5` - * - Elixir: `OpenTelemetry.Ctx.new` - * - Erlang: `opentelemetry_ctx:new` - * - Rust: `playground::my_module::my_cool_func` - * - C function: `fopen` - */ - exports.ATTR_CODE_FUNCTION_NAME = "code.function.name"; - /** - * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example 42 - */ - exports.ATTR_CODE_LINE_NUMBER = "code.line.number"; - /** - * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example "at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" - */ - exports.ATTR_CODE_STACKTRACE = "code.stacktrace"; - /** - * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/containers/run/#container-identification). The UUID might be abbreviated. - * - * @example a3bf90e006b2 - */ - exports.ATTR_CONTAINER_ID = "container.id"; - /** - * Name of the image the container was built on. - * - * @example gcr.io/opentelemetry/operator - */ - exports.ATTR_CONTAINER_IMAGE_NAME = "container.image.name"; - /** - * Repo digests of the container image as provided by the container runtime. - * - * @example ["example@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb", "internal.registry.example.com:5000/example@sha256:b69959407d21e8a062e0416bf13405bb2b71ed7a84dde4158ebafacfa06f5578"] - * - * @note [Docker](https://docs.docker.com/reference/api/engine/version/v1.52/#tag/Image/operation/ImageInspect) and [CRI](https://github.com/kubernetes/cri-api/blob/c75ef5b473bbe2d0a4fc92f82235efd665ea8e9f/pkg/apis/runtime/v1/api.proto#L1237-L1238) report those under the `RepoDigests` field. - */ - exports.ATTR_CONTAINER_IMAGE_REPO_DIGESTS = "container.image.repo_digests"; - /** - * Container image tags. An example can be found in [Docker Image Inspect](https://docs.docker.com/reference/api/engine/version/v1.52/#tag/Image/operation/ImageInspect). Should be only the `` section of the full name for example from `registry.example.com/my-org/my-image:`. - * - * @example ["v1.27.1", "3.5.7-0"] - */ - exports.ATTR_CONTAINER_IMAGE_TAGS = "container.image.tags"; - /** - * The name of a collection (table, container) within the database. - * - * @example public.users - * @example customers - * - * @note It is **RECOMMENDED** to capture the value as provided by the application - * without attempting to do any case normalization. - * - * The collection name **SHOULD NOT** be extracted from `db.query.text`, - * when the database system supports query text with multiple collections - * in non-batch operations. - * - * For batch operations, if the individual operations are known to have the same - * collection name then that collection name **SHOULD** be used. - */ - exports.ATTR_DB_COLLECTION_NAME = "db.collection.name"; - /** - * The name of the database, fully qualified within the server address and port. - * - * @example customers - * @example test.users - * - * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted. - * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system. - * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization. - */ - exports.ATTR_DB_NAMESPACE = "db.namespace"; - /** - * The number of database operations included in a batch operation. - * - * @example 2 - * @example 3 - * @example 4 - * - * @note Except for empty batch requests described below, a batch operation contains two - * or more database operations explicitly submitted as separate operations in a single - * client call, protocol message, or database command. - * - * Requests to batch APIs that contain only one operation **SHOULD** be modeled as single - * operations, not as batch operations. - * - * A database call is not a batch operation solely because one operation accepts - * multiple operands, such as keys, rows, documents, points, or other data elements, - * including Redis [`MGET`](https://redis.io/docs/latest/commands/mget/) with - * multiple keys. - * - * In batch APIs that execute the same parameterized operation with parameter sets, - * each parameter set represents one database operation for determining whether the - * request is a batch operation. Requests with only one parameter set **SHOULD** be modeled - * as single operations, not as batch operations. - * - * `db.operation.batch.size` **SHOULD** be set to the number of operations in the batch. - * It **SHOULD NOT** be set for non-batch operations. - * - * A request to execute a batch operation with no operations **SHOULD** also be treated - * as a batch operation, and `db.operation.batch.size` **SHOULD** be set to `0`. - */ - exports.ATTR_DB_OPERATION_BATCH_SIZE = "db.operation.batch.size"; - /** - * The name of the operation or command being executed. - * - * @example findAndModify - * @example HMSET - * @example SELECT - * - * @note It is **RECOMMENDED** to capture the value as provided by the application - * without attempting to do any case normalization. - * - * The operation name **SHOULD NOT** be extracted from `db.query.text`, - * when the database system supports query text with multiple operations - * in non-batch operations. - * - * If spaces can occur in the operation name, multiple consecutive spaces - * **SHOULD** be normalized to a single space. - * - * For batch operations, if the individual operations are known to have the same operation name - * then that operation name **SHOULD** be used prepended by `BATCH `, - * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database - * system specific term if more applicable. - */ - exports.ATTR_DB_OPERATION_NAME = "db.operation.name"; - /** - * Low cardinality summary of a database query. - * - * @example SELECT wuser_table - * @example INSERT shipping_details SELECT orders - * @example get user by id - * - * @note The query summary describes a class of database queries and is useful - * as a grouping key, especially when analyzing telemetry for database - * calls involving complex queries. - * - * Summary may be available to the instrumentation through - * instrumentation hooks or other means. If it is not available, instrumentations - * that support query parsing **SHOULD** generate a summary following - * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query) - * section. - * - * For batch operations, if the individual operations are known to have the same query summary - * then that query summary **SHOULD** be used prepended by `BATCH `, - * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database - * system specific term if more applicable. - */ - exports.ATTR_DB_QUERY_SUMMARY = "db.query.summary"; - /** - * The database query being executed. - * - * @example SELECT * FROM wuser_table where username = ? - * @example SET mykey ? - * - * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext). - * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable. - * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk. - */ - exports.ATTR_DB_QUERY_TEXT = "db.query.text"; - /** - * Database response status code. - * - * @example 102 - * @example ORA-17002 - * @example 08P01 - * @example 404 - * - * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes. - * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system. - */ - exports.ATTR_DB_RESPONSE_STATUS_CODE = "db.response.status_code"; - /** - * The name of a stored procedure within the database. - * - * @example GetCustomer - * - * @note It is **RECOMMENDED** to capture the value as provided by the application - * without attempting to do any case normalization. - * - * For batch operations, if the individual operations are known to have the same - * stored procedure name then that stored procedure name **SHOULD** be used. - */ - exports.ATTR_DB_STORED_PROCEDURE_NAME = "db.stored_procedure.name"; - /** - * The database management system (DBMS) product as identified by the client instrumentation. - * - * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge. - */ - exports.ATTR_DB_SYSTEM_NAME = "db.system.name"; - /** - * Enum value "mariadb" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [MariaDB](https://mariadb.org/) - */ - exports.DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb"; - /** - * Enum value "microsoft.sql_server" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [Microsoft SQL Server](https://www.microsoft.com/sql-server) - */ - exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server"; - /** - * Enum value "mysql" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [MySQL](https://www.mysql.com/) - */ - exports.DB_SYSTEM_NAME_VALUE_MYSQL = "mysql"; - /** - * Enum value "postgresql" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [PostgreSQL](https://www.postgresql.org/) - */ - exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql"; - /** - * Name of the [deployment environment](https://wikipedia.org/wiki/Deployment_environment) (aka deployment tier). - * - * @example staging - * @example production - * - * @note `deployment.environment.name` does not affect the uniqueness constraints defined through - * the `service.namespace`, `service.name` and `service.instance.id` resource attributes. - * This implies that resources carrying the following attribute combinations **MUST** be - * considered to be identifying the same service: - * - * - `service.name=frontend`, `deployment.environment.name=production` - * - `service.name=frontend`, `deployment.environment.name=staging`. - */ - exports.ATTR_DEPLOYMENT_ENVIRONMENT_NAME = "deployment.environment.name"; - /** - * Enum value "development" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. - * - * Development environment - */ - exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = "development"; - /** - * Enum value "production" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. - * - * Production environment - */ - exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = "production"; - /** - * Enum value "staging" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. - * - * Staging environment - */ - exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = "staging"; - /** - * Enum value "test" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. - * - * Testing environment - */ - exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = "test"; - /** - * Name of the garbage collector managed heap generation. - * - * @example gen0 - * @example gen1 - * @example gen2 - */ - exports.ATTR_DOTNET_GC_HEAP_GENERATION = "dotnet.gc.heap.generation"; - /** - * Enum value "gen0" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Generation 0 - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0"; - /** - * Enum value "gen1" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Generation 1 - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1"; - /** - * Enum value "gen2" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Generation 2 - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2"; - /** - * Enum value "loh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Large Object Heap - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh"; - /** - * Enum value "poh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Pinned Object Heap - */ - exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh"; - /** - * Describes a class of error the operation ended with. - * - * @example timeout - * @example java.net.UnknownHostException - * @example server_certificate_invalid - * @example 500 - * - * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality. - * - * When `error.type` is set to a type (e.g., an exception type), its - * canonical class name identifying the type within the artifact **SHOULD** be used. - * - * If the recorded error type is a wrapper that is not meaningful for - * failure classification, instrumentation **MAY** use the type of the inner - * error instead. For example, in Go, errors created with `fmt.Errorf` - * using `%w` **MAY** be unwrapped when the wrapper type does not help - * classify the failure. - * - * Instrumentations **SHOULD** document the list of errors they report. - * - * The cardinality of `error.type` within one instrumentation library **SHOULD** be low. - * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications - * should be prepared for `error.type` to have high cardinality at query time when no - * additional filters are applied. - * - * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`. - * - * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes), - * it's **RECOMMENDED** to: - * - * - Use a domain-specific attribute - * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not. - */ - exports.ATTR_ERROR_TYPE = "error.type"; - /** - * Enum value "_OTHER" for attribute {@link ATTR_ERROR_TYPE}. - * - * A fallback error value to be used when the instrumentation doesn't define a custom value. - */ - exports.ERROR_TYPE_VALUE_OTHER = "_OTHER"; - /** - * Indicates that the exception is escaping the scope of the span. - * - * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span. - */ - exports.ATTR_EXCEPTION_ESCAPED = "exception.escaped"; - /** - * The exception message. - * - * @example Division by zero - * @example Can't convert 'int' object to str implicitly - * - * @note > [!WARNING] - * - * > This attribute may contain sensitive information. - */ - exports.ATTR_EXCEPTION_MESSAGE = "exception.message"; - /** - * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. - * - * @example "Exception in thread "main" java.lang.RuntimeException: Test exception\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" - */ - exports.ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace"; - /** - * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. - * - * @example java.net.ConnectException - * @example OSError - * - * @note If the recorded exception type is a wrapper that is not meaningful for - * failure classification, instrumentation **MAY** use the type of the inner - * exception instead. For example, in Go, errors created with `fmt.Errorf` - * using `%w` **MAY** be unwrapped when the wrapper type does not help - * classify the failure. - */ - exports.ATTR_EXCEPTION_TYPE = "exception.type"; - /** - * HTTP request headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. - * - * @example ["application/json"] - * @example ["1.2.3.4", "1.2.3.5"] - * - * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. - * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information. - * - * The `User-Agent` header is already captured in the `user_agent.original` attribute. - * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. - * - * The attribute value **MUST** consist of either multiple header values as an array of strings - * or a single-item array containing a possibly comma-concatenated string, depending on the way - * the HTTP library provides access to headers. - * - * Examples: - * - * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type` - * attribute with value `["application/json"]`. - * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for` - * attribute with value `["1.2.3.4", "1.2.3.5"]` or `["1.2.3.4, 1.2.3.5"]` depending on the HTTP library. - */ - var ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; - exports.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER; - /** - * HTTP request method. - * - * @example GET - * @example POST - * @example HEAD - * - * @note HTTP request method value **SHOULD** be "known" to the instrumentation. - * By default, this convention defines "known" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods), - * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html) - * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1). - * - * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`. - * - * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override - * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named - * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods. - * - * - * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property - * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or - * `.instrumentation/development.general.http.server`. - * - * In either case, this list **MUST** be a full override of the default known methods, - * it is not a list of known methods in addition to the defaults. - * - * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly. - * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent. - * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value. - */ - exports.ATTR_HTTP_REQUEST_METHOD = "http.request.method"; - /** - * Enum value "_OTHER" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * Any HTTP method that the instrumentation has no prior knowledge of. - */ - exports.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; - /** - * Enum value "CONNECT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * CONNECT method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; - /** - * Enum value "DELETE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * DELETE method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; - /** - * Enum value "GET" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * GET method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_GET = "GET"; - /** - * Enum value "HEAD" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * HEAD method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; - /** - * Enum value "OPTIONS" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * OPTIONS method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; - /** - * Enum value "PATCH" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * PATCH method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; - /** - * Enum value "POST" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * POST method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_POST = "POST"; - /** - * Enum value "PUT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * PUT method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; - /** - * Enum value "TRACE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * TRACE method. - */ - exports.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; - /** - * Original HTTP method sent by the client in the request line. - * - * @example GeT - * @example ACL - * @example foo - */ - exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original"; - /** - * The ordinal number of request resending attempt (for any reason, including redirects). - * - * @example 3 - * - * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other). - */ - exports.ATTR_HTTP_REQUEST_RESEND_COUNT = "http.request.resend_count"; - /** - * HTTP response headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. - * - * @example ["application/json"] - * @example ["abc", "def"] - * - * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. - * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information. - * - * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. - * - * The attribute value **MUST** consist of either multiple header values as an array of strings - * or a single-item array containing a possibly comma-concatenated string, depending on the way - * the HTTP library provides access to headers. - * - * Examples: - * - * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type` - * attribute with value `["application/json"]`. - * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header` - * attribute with value `["abc", "def"]` or `["abc, def"]` depending on the HTTP library. - */ - var ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; - exports.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER; - /** - * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). - * - * @example 200 - */ - exports.ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"; - /** - * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders. - * - * @example /users/:userID? - * @example my-controller/my-action/{id?} - * - * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it. - * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one. - * - * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that - * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`. - * - * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments. - * - * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY** - * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string. - */ - exports.ATTR_HTTP_ROUTE = "http.route"; - /** - * Name of the garbage collector action. - * - * @example end of minor GC - * @example end of major GC - * - * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()). - */ - exports.ATTR_JVM_GC_ACTION = "jvm.gc.action"; - /** - * Name of the garbage collector. - * - * @example G1 Young Generation - * @example G1 Old Generation - * - * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()). - */ - exports.ATTR_JVM_GC_NAME = "jvm.gc.name"; - /** - * Name of the memory pool. - * - * @example G1 Old Gen - * @example G1 Eden space - * @example G1 Survivor Space - * - * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()). - */ - exports.ATTR_JVM_MEMORY_POOL_NAME = "jvm.memory.pool.name"; - /** - * The type of memory. - * - * @example heap - * @example non_heap - */ - exports.ATTR_JVM_MEMORY_TYPE = "jvm.memory.type"; - /** - * Enum value "heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. - * - * Heap memory. - */ - exports.JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; - /** - * Enum value "non_heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. - * - * Non-heap memory - */ - exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; - /** - * Whether the thread is daemon or not. - */ - exports.ATTR_JVM_THREAD_DAEMON = "jvm.thread.daemon"; - /** - * State of the thread. - * - * @example runnable - * @example blocked - */ - exports.ATTR_JVM_THREAD_STATE = "jvm.thread.state"; - /** - * Enum value "blocked" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that is blocked waiting for a monitor lock is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; - /** - * Enum value "new" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that has not yet started is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_NEW = "new"; - /** - * Enum value "runnable" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread executing in the Java virtual machine is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; - /** - * Enum value "terminated" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that has exited is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; - /** - * Enum value "timed_waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; - /** - * Enum value "waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that is waiting indefinitely for another thread to perform a particular action is in this state. - */ - exports.JVM_THREAD_STATE_VALUE_WAITING = "waiting"; - /** - * The name of the cluster. - * - * @example opentelemetry-cluster - */ - exports.ATTR_K8S_CLUSTER_NAME = "k8s.cluster.name"; - /** - * A pseudo-ID for the cluster, set to the UID of the `kube-system` namespace. - * - * @example 218fc5a9-a5f1-4b54-aa05-46717d0ab26d - * - * @note K8s doesn't have support for obtaining a cluster ID. If this is ever - * added, we will recommend collecting the `k8s.cluster.uid` through the - * official APIs. In the meantime, we are able to use the `uid` of the - * `kube-system` namespace as a proxy for cluster ID. Read on for the - * rationale. - * - * Every object created in a K8s cluster is assigned a distinct UID. The - * `kube-system` namespace is used by Kubernetes itself and will exist - * for the lifetime of the cluster. Using the `uid` of the `kube-system` - * namespace is a reasonable proxy for the K8s ClusterID as it will only - * change if the cluster is rebuilt. Furthermore, Kubernetes UIDs are - * UUIDs as standardized by - * [ISO/IEC 9834-8 and ITU-T X.667](https://www.itu.int/ITU-T/studygroups/com17/oid.html). - * Which states: - * - * > If generated according to one of the mechanisms defined in Rec. - * > ITU-T X.667 | ISO/IEC 9834-8, a UUID is either guaranteed to be - * > different from all other UUIDs generated before 3603 A.D., or is - * > extremely likely to be different (depending on the mechanism chosen). - * - * Therefore, UIDs between clusters should be extremely unlikely to - * conflict. - */ - exports.ATTR_K8S_CLUSTER_UID = "k8s.cluster.uid"; - /** - * The name of the Container from Pod specification, must be unique within a Pod. Container runtime usually uses different globally unique name (`container.name`). - * - * @example redis - */ - exports.ATTR_K8S_CONTAINER_NAME = "k8s.container.name"; - /** - * Number of times the container was restarted. This attribute can be used to identify a particular container (running or stopped) within a container spec. - */ - exports.ATTR_K8S_CONTAINER_RESTART_COUNT = "k8s.container.restart_count"; - /** - * The cronjob annotation placed on the CronJob, the `` being the annotation name, the value being the annotation value. - * - * @example 4 - * @example - * - * @note Examples: - * - * - An annotation `retries` with value `4` **SHOULD** be recorded as the - * `k8s.cronjob.annotation.retries` attribute with value `"4"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.cronjob.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_CRONJOB_ANNOTATION = (key) => `k8s.cronjob.annotation.${key}`; - exports.ATTR_K8S_CRONJOB_ANNOTATION = ATTR_K8S_CRONJOB_ANNOTATION; - /** - * The label placed on the CronJob, the `` being the label name, the value being the label value. - * - * @example weekly - * @example - * - * @note Examples: - * - * - A label `type` with value `weekly` **SHOULD** be recorded as the - * `k8s.cronjob.label.type` attribute with value `"weekly"`. - * - A label `automated` with empty string value **SHOULD** be recorded as - * the `k8s.cronjob.label.automated` attribute with value `""`. - */ - var ATTR_K8S_CRONJOB_LABEL = (key) => `k8s.cronjob.label.${key}`; - exports.ATTR_K8S_CRONJOB_LABEL = ATTR_K8S_CRONJOB_LABEL; - /** - * The name of the CronJob. - * - * @example opentelemetry - */ - exports.ATTR_K8S_CRONJOB_NAME = "k8s.cronjob.name"; - /** - * The UID of the CronJob. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_CRONJOB_UID = "k8s.cronjob.uid"; - /** - * The annotation placed on the DaemonSet, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 1 - * @example - * - * @note - * Examples: - * - * - An annotation `replicas` with value `1` **SHOULD** be recorded - * as the `k8s.daemonset.annotation.replicas` attribute with value `"1"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.daemonset.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_DAEMONSET_ANNOTATION = (key) => `k8s.daemonset.annotation.${key}`; - exports.ATTR_K8S_DAEMONSET_ANNOTATION = ATTR_K8S_DAEMONSET_ANNOTATION; - /** - * The label placed on the DaemonSet, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example guestbook - * @example - * - * @note - * Examples: - * - * - A label `app` with value `guestbook` **SHOULD** be recorded - * as the `k8s.daemonset.label.app` attribute with value `"guestbook"`. - * - A label `injected` with empty string value **SHOULD** be recorded as - * the `k8s.daemonset.label.injected` attribute with value `""`. - */ - var ATTR_K8S_DAEMONSET_LABEL = (key) => `k8s.daemonset.label.${key}`; - exports.ATTR_K8S_DAEMONSET_LABEL = ATTR_K8S_DAEMONSET_LABEL; - /** - * The name of the DaemonSet. - * - * @example opentelemetry - */ - exports.ATTR_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; - /** - * The UID of the DaemonSet. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; - /** - * The annotation placed on the Deployment, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 1 - * @example - * - * @note - * Examples: - * - * - An annotation `replicas` with value `1` **SHOULD** be recorded - * as the `k8s.deployment.annotation.replicas` attribute with value `"1"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.deployment.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_DEPLOYMENT_ANNOTATION = (key) => `k8s.deployment.annotation.${key}`; - exports.ATTR_K8S_DEPLOYMENT_ANNOTATION = ATTR_K8S_DEPLOYMENT_ANNOTATION; - /** - * The label placed on the Deployment, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example guestbook - * @example - * - * @note - * Examples: - * - * - A label `app` with value `guestbook` **SHOULD** be recorded - * as the `k8s.deployment.label.app` attribute with value `"guestbook"`. - * - A label `injected` with empty string value **SHOULD** be recorded as - * the `k8s.deployment.label.injected` attribute with value `""`. - */ - var ATTR_K8S_DEPLOYMENT_LABEL = (key) => `k8s.deployment.label.${key}`; - exports.ATTR_K8S_DEPLOYMENT_LABEL = ATTR_K8S_DEPLOYMENT_LABEL; - /** - * The name of the Deployment. - * - * @example opentelemetry - */ - exports.ATTR_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; - /** - * The UID of the Deployment. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; - /** - * The annotation placed on the Job, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 1 - * @example - * - * @note - * Examples: - * - * - An annotation `number` with value `1` **SHOULD** be recorded - * as the `k8s.job.annotation.number` attribute with value `"1"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.job.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_JOB_ANNOTATION = (key) => `k8s.job.annotation.${key}`; - exports.ATTR_K8S_JOB_ANNOTATION = ATTR_K8S_JOB_ANNOTATION; - /** - * The label placed on the Job, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example ci - * @example - * - * @note - * Examples: - * - * - A label `jobtype` with value `ci` **SHOULD** be recorded - * as the `k8s.job.label.jobtype` attribute with value `"ci"`. - * - A label `automated` with empty string value **SHOULD** be recorded as - * the `k8s.job.label.automated` attribute with value `""`. - */ - var ATTR_K8S_JOB_LABEL = (key) => `k8s.job.label.${key}`; - exports.ATTR_K8S_JOB_LABEL = ATTR_K8S_JOB_LABEL; - /** - * The name of the Job. - * - * @example opentelemetry - */ - exports.ATTR_K8S_JOB_NAME = "k8s.job.name"; - /** - * The UID of the Job. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_JOB_UID = "k8s.job.uid"; - /** - * The annotation placed on the Namespace, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 0 - * @example - * - * @note - * Examples: - * - * - An annotation `ttl` with value `0` **SHOULD** be recorded - * as the `k8s.namespace.annotation.ttl` attribute with value `"0"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.namespace.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_NAMESPACE_ANNOTATION = (key) => `k8s.namespace.annotation.${key}`; - exports.ATTR_K8S_NAMESPACE_ANNOTATION = ATTR_K8S_NAMESPACE_ANNOTATION; - /** - * The label placed on the Namespace, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example default - * @example - * - * @note - * Examples: - * - * - A label `kubernetes.io/metadata.name` with value `default` **SHOULD** be recorded - * as the `k8s.namespace.label.kubernetes.io/metadata.name` attribute with value `"default"`. - * - A label `data` with empty string value **SHOULD** be recorded as - * the `k8s.namespace.label.data` attribute with value `""`. - */ - var ATTR_K8S_NAMESPACE_LABEL = (key) => `k8s.namespace.label.${key}`; - exports.ATTR_K8S_NAMESPACE_LABEL = ATTR_K8S_NAMESPACE_LABEL; - /** - * The name of the namespace that the pod is running in. - * - * @example default - */ - exports.ATTR_K8S_NAMESPACE_NAME = "k8s.namespace.name"; - /** - * The annotation placed on the Node, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 0 - * @example - * - * @note Examples: - * - * - An annotation `node.alpha.kubernetes.io/ttl` with value `0` **SHOULD** be recorded as - * the `k8s.node.annotation.node.alpha.kubernetes.io/ttl` attribute with value `"0"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.node.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_NODE_ANNOTATION = (key) => `k8s.node.annotation.${key}`; - exports.ATTR_K8S_NODE_ANNOTATION = ATTR_K8S_NODE_ANNOTATION; - /** - * The label placed on the Node, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example arm64 - * @example - * - * @note Examples: - * - * - A label `kubernetes.io/arch` with value `arm64` **SHOULD** be recorded - * as the `k8s.node.label.kubernetes.io/arch` attribute with value `"arm64"`. - * - A label `data` with empty string value **SHOULD** be recorded as - * the `k8s.node.label.data` attribute with value `""`. - */ - var ATTR_K8S_NODE_LABEL = (key) => `k8s.node.label.${key}`; - exports.ATTR_K8S_NODE_LABEL = ATTR_K8S_NODE_LABEL; - /** - * The name of the Node. - * - * @example node-1 - */ - exports.ATTR_K8S_NODE_NAME = "k8s.node.name"; - /** - * The UID of the Node. - * - * @example 1eb3a0c6-0477-4080-a9cb-0cb7db65c6a2 - */ - exports.ATTR_K8S_NODE_UID = "k8s.node.uid"; - /** - * The annotation placed on the Pod, the `` being the annotation name, the value being the annotation value. - * - * @example true - * @example x64 - * @example - * - * @note Examples: - * - * - An annotation `kubernetes.io/enforce-mountable-secrets` with value `true` **SHOULD** be recorded as - * the `k8s.pod.annotation.kubernetes.io/enforce-mountable-secrets` attribute with value `"true"`. - * - An annotation `mycompany.io/arch` with value `x64` **SHOULD** be recorded as - * the `k8s.pod.annotation.mycompany.io/arch` attribute with value `"x64"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.pod.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_POD_ANNOTATION = (key) => `k8s.pod.annotation.${key}`; - exports.ATTR_K8S_POD_ANNOTATION = ATTR_K8S_POD_ANNOTATION; - /** - * Specifies the hostname of the Pod. - * - * @example collector-gateway - * - * @note The K8s Pod spec has an optional hostname field, which can be used to specify a hostname. - * Refer to [K8s docs](https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-hostname-and-subdomain-field) - * for more information about this field. - * - * This attribute aligns with the `hostname` field of the - * [K8s PodSpec](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podspec-v1-core). - */ - exports.ATTR_K8S_POD_HOSTNAME = "k8s.pod.hostname"; - /** - * IP address allocated to the Pod. - * - * @example 172.18.0.2 - * - * @note This attribute aligns with the `podIP` field of the - * [K8s PodStatus](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podstatus-v1-core). - */ - exports.ATTR_K8S_POD_IP = "k8s.pod.ip"; - /** - * The label placed on the Pod, the `` being the label name, the value being the label value. - * - * @example my-app - * @example x64 - * @example - * - * @note Examples: - * - * - A label `app` with value `my-app` **SHOULD** be recorded as - * the `k8s.pod.label.app` attribute with value `"my-app"`. - * - A label `mycompany.io/arch` with value `x64` **SHOULD** be recorded as - * the `k8s.pod.label.mycompany.io/arch` attribute with value `"x64"`. - * - A label `data` with empty string value **SHOULD** be recorded as - * the `k8s.pod.label.data` attribute with value `""`. - */ - var ATTR_K8S_POD_LABEL = (key) => `k8s.pod.label.${key}`; - exports.ATTR_K8S_POD_LABEL = ATTR_K8S_POD_LABEL; - /** - * The name of the Pod. - * - * @example opentelemetry-pod-autoconf - */ - exports.ATTR_K8S_POD_NAME = "k8s.pod.name"; - /** - * The start timestamp of the Pod. - * - * @example 2025-12-04T08:41:03Z - * - * @note Date and time at which the object was acknowledged by the Kubelet. - * This is before the Kubelet pulled the container image(s) for the pod. - * - * This attribute aligns with the `startTime` field of the - * [K8s PodStatus](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podstatus-v1-core), - * in ISO 8601 (RFC 3339 compatible) format. - */ - exports.ATTR_K8S_POD_START_TIME = "k8s.pod.start_time"; - /** - * The UID of the Pod. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_POD_UID = "k8s.pod.uid"; - /** - * The annotation placed on the ReplicaSet, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 0 - * @example - * - * @note - * Examples: - * - * - An annotation `replicas` with value `0` **SHOULD** be recorded - * as the `k8s.replicaset.annotation.replicas` attribute with value `"0"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.replicaset.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_REPLICASET_ANNOTATION = (key) => `k8s.replicaset.annotation.${key}`; - exports.ATTR_K8S_REPLICASET_ANNOTATION = ATTR_K8S_REPLICASET_ANNOTATION; - /** - * The label placed on the ReplicaSet, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example guestbook - * @example - * - * @note - * Examples: - * - * - A label `app` with value `guestbook` **SHOULD** be recorded - * as the `k8s.replicaset.label.app` attribute with value `"guestbook"`. - * - A label `injected` with empty string value **SHOULD** be recorded as - * the `k8s.replicaset.label.injected` attribute with value `""`. - */ - var ATTR_K8S_REPLICASET_LABEL = (key) => `k8s.replicaset.label.${key}`; - exports.ATTR_K8S_REPLICASET_LABEL = ATTR_K8S_REPLICASET_LABEL; - /** - * The name of the ReplicaSet. - * - * @example opentelemetry - */ - exports.ATTR_K8S_REPLICASET_NAME = "k8s.replicaset.name"; - /** - * The UID of the ReplicaSet. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_REPLICASET_UID = "k8s.replicaset.uid"; - /** - * The annotation placed on the StatefulSet, the `` being the annotation name, the value being the annotation value, even if the value is empty. - * - * @example 1 - * @example - * - * @note - * Examples: - * - * - An annotation `replicas` with value `1` **SHOULD** be recorded - * as the `k8s.statefulset.annotation.replicas` attribute with value `"1"`. - * - An annotation `data` with empty string value **SHOULD** be recorded as - * the `k8s.statefulset.annotation.data` attribute with value `""`. - */ - var ATTR_K8S_STATEFULSET_ANNOTATION = (key) => `k8s.statefulset.annotation.${key}`; - exports.ATTR_K8S_STATEFULSET_ANNOTATION = ATTR_K8S_STATEFULSET_ANNOTATION; - /** - * The label placed on the StatefulSet, the `` being the label name, the value being the label value, even if the value is empty. - * - * @example guestbook - * @example - * - * @note - * Examples: - * - * - A label `app` with value `guestbook` **SHOULD** be recorded - * as the `k8s.statefulset.label.app` attribute with value `"guestbook"`. - * - A label `injected` with empty string value **SHOULD** be recorded as - * the `k8s.statefulset.label.injected` attribute with value `""`. - */ - var ATTR_K8S_STATEFULSET_LABEL = (key) => `k8s.statefulset.label.${key}`; - exports.ATTR_K8S_STATEFULSET_LABEL = ATTR_K8S_STATEFULSET_LABEL; - /** - * The name of the StatefulSet. - * - * @example opentelemetry - */ - exports.ATTR_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; - /** - * The UID of the StatefulSet. - * - * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff - */ - exports.ATTR_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; - /** - * Local address of the network connection - IP address or Unix domain socket name. - * - * @example 10.1.2.80 - * @example /tmp/my.sock - */ - exports.ATTR_NETWORK_LOCAL_ADDRESS = "network.local.address"; - /** - * Local port number of the network connection. - * - * @example 65123 - */ - exports.ATTR_NETWORK_LOCAL_PORT = "network.local.port"; - /** - * Peer address of the network connection - IP address or Unix domain socket name. - * - * @example 10.1.2.80 - * @example /tmp/my.sock - */ - exports.ATTR_NETWORK_PEER_ADDRESS = "network.peer.address"; - /** - * Peer port number of the network connection. - * - * @example 65123 - */ - exports.ATTR_NETWORK_PEER_PORT = "network.peer.port"; - /** - * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent. - * - * @example amqp - * @example http - * @example mqtt - * - * @note The value **SHOULD** be normalized to lowercase. - */ - exports.ATTR_NETWORK_PROTOCOL_NAME = "network.protocol.name"; - /** - * The actual version of the protocol used for network communication. - * - * @example 1.1 - * @example 2 - * - * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set. - */ - exports.ATTR_NETWORK_PROTOCOL_VERSION = "network.protocol.version"; - /** - * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication). - * - * @example tcp - * @example udp - * - * @note The value **SHOULD** be normalized to lowercase. - * - * Consider always setting the transport when setting a port number, since - * a port number is ambiguous without knowing the transport. For example - * different processes could be listening on TCP port 12345 and UDP port 12345. - */ - exports.ATTR_NETWORK_TRANSPORT = "network.transport"; - /** - * Enum value "pipe" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * Named or anonymous pipe. - */ - exports.NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; - /** - * Enum value "quic" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * QUIC - */ - exports.NETWORK_TRANSPORT_VALUE_QUIC = "quic"; - /** - * Enum value "tcp" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * TCP - */ - exports.NETWORK_TRANSPORT_VALUE_TCP = "tcp"; - /** - * Enum value "udp" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * UDP - */ - exports.NETWORK_TRANSPORT_VALUE_UDP = "udp"; - /** - * Enum value "unix" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * Unix domain socket - */ - exports.NETWORK_TRANSPORT_VALUE_UNIX = "unix"; - /** - * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent. - * - * @example ipv4 - * @example ipv6 - * - * @note The value **SHOULD** be normalized to lowercase. - */ - exports.ATTR_NETWORK_TYPE = "network.type"; - /** - * Enum value "ipv4" for attribute {@link ATTR_NETWORK_TYPE}. - * - * IPv4 - */ - exports.NETWORK_TYPE_VALUE_IPV4 = "ipv4"; - /** - * Enum value "ipv6" for attribute {@link ATTR_NETWORK_TYPE}. - * - * IPv6 - */ - exports.NETWORK_TYPE_VALUE_IPV6 = "ipv6"; - /** - * Identifies the class / type of event. - * - * @example browser.mouse.click - * @example device.app.lifecycle - * - * @note This attribute **SHOULD** be used by non-OTLP exporters when destination does not support `EventName` or equivalent field. This attribute **MAY** be used by applications using existing logging libraries so that it can be used to set the `EventName` field by Collector or SDK components. - */ - exports.ATTR_OTEL_EVENT_NAME = "otel.event.name"; - /** - * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP). - * - * @example io.opentelemetry.contrib.mongodb - */ - exports.ATTR_OTEL_SCOPE_NAME = "otel.scope.name"; - /** - * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP). - * - * @example 1.0.0 - */ - exports.ATTR_OTEL_SCOPE_VERSION = "otel.scope.version"; - /** - * Name of the code, either "OK" or "ERROR". **MUST NOT** be set if the status code is UNSET. - */ - exports.ATTR_OTEL_STATUS_CODE = "otel.status_code"; - /** - * Enum value "ERROR" for attribute {@link ATTR_OTEL_STATUS_CODE}. - * - * The operation contains an error. - */ - exports.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; - /** - * Enum value "OK" for attribute {@link ATTR_OTEL_STATUS_CODE}. - * - * The operation has been validated by an Application developer or Operator to have completed successfully. - */ - exports.OTEL_STATUS_CODE_VALUE_OK = "OK"; - /** - * Description of the Status if it has a value, otherwise not set. - * - * @example resource not found - */ - exports.ATTR_OTEL_STATUS_DESCRIPTION = "otel.status_description"; - /** - * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. - * - * @example example.com - * @example 10.1.2.80 - * @example /tmp/my.sock - * - * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available. - */ - exports.ATTR_SERVER_ADDRESS = "server.address"; - /** - * Server port number. - * - * @example 80 - * @example 8080 - * @example 443 - * - * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available. - */ - exports.ATTR_SERVER_PORT = "server.port"; - /** - * The string ID of the service instance. - * - * @example 627cc493-f310-47de-96bd-71410b7dec09 - * - * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words - * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to - * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled - * service). - * - * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC - * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of - * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and - * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`. - * - * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is - * needed. Similar to what can be seen in the man page for the - * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying - * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it - * or not via another resource attribute. - * - * For applications running behind an application server (like unicorn), we do not recommend using one identifier - * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker - * thread in unicorn) to have its own instance.id. - * - * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the - * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will - * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated. - * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance - * for that telemetry. This is typically the case for scraping receivers, as they know the target address and - * port. - */ - exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id"; - /** - * Logical name of the service. - * - * @example shoppingcart - * - * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with the process executable name, e.g. `unknown_service:bash`. If the process executable name is not available, the value **MUST** be set to `unknown_service`. - * The process executable name is the name of the process executable, the same value as described by the [`process.executable.name`](process.md) resource attribute. - */ - exports.ATTR_SERVICE_NAME = "service.name"; - /** - * A namespace for `service.name`. - * - * @example Shop - * - * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. - */ - exports.ATTR_SERVICE_NAMESPACE = "service.namespace"; - /** - * The version string of the service component. The format is not defined by these conventions. - * - * @example 2.0.0 - * @example a01dbef8a - */ - exports.ATTR_SERVICE_VERSION = "service.version"; - /** - * SignalR HTTP connection closure status. - * - * @example app_shutdown - * @example timeout - */ - exports.ATTR_SIGNALR_CONNECTION_STATUS = "signalr.connection.status"; - /** - * Enum value "app_shutdown" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - * - * The connection was closed because the app is shutting down. - */ - exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; - /** - * Enum value "normal_closure" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - * - * The connection was closed normally. - */ - exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; - /** - * Enum value "timeout" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - * - * The connection was closed due to a timeout. - */ - exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; - /** - * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md) - * - * @example web_sockets - * @example long_polling - */ - exports.ATTR_SIGNALR_TRANSPORT = "signalr.transport"; - /** - * Enum value "long_polling" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - * - * LongPolling protocol - */ - exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; - /** - * Enum value "server_sent_events" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - * - * ServerSentEvents protocol - */ - exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; - /** - * Enum value "web_sockets" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - * - * WebSockets protocol - */ - exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; - /** - * The name of the auto instrumentation agent or distribution, if used. - * - * @example parts-unlimited-java - * - * @note Official auto instrumentation agents and distributions **SHOULD** set the `telemetry.distro.name` attribute to - * a string starting with `opentelemetry-`, e.g. `opentelemetry-java-instrumentation`. - */ - exports.ATTR_TELEMETRY_DISTRO_NAME = "telemetry.distro.name"; - /** - * The version string of the auto instrumentation agent or distribution, if used. - * - * @example 1.2.3 - */ - exports.ATTR_TELEMETRY_DISTRO_VERSION = "telemetry.distro.version"; - /** - * The language of the telemetry SDK. - */ - exports.ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; - /** - * Enum value "cpp" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; - /** - * Enum value "dotnet" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; - /** - * Enum value "erlang" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; - /** - * Enum value "go" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; - /** - * Enum value "java" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; - /** - * Enum value "kotlin" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN = "kotlin"; - /** - * Enum value "nodejs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; - /** - * Enum value "php" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; - /** - * Enum value "python" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; - /** - * Enum value "ruby" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; - /** - * Enum value "rust" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; - /** - * Enum value "swift" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; - /** - * Enum value "webjs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ - exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; - /** - * The name of the telemetry SDK as defined above. - * - * @example opentelemetry - * - * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`. - * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the - * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point - * or another suitable identifier depending on the language. - * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case. - * All custom identifiers **SHOULD** be stable across different versions of an implementation. - */ - exports.ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; - /** - * The version string of the telemetry SDK. - * - * @example 1.2.3 - */ - exports.ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; - /** - * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component - * - * @example SemConv - */ - exports.ATTR_URL_FRAGMENT = "url.fragment"; - /** - * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) - * - * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv - * @example //localhost - * - * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment - * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless. - * - * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`. - * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`. - * - * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed). - * - * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it. - * - * - * Query string values for the following keys **SHOULD** be redacted by default and replaced by the - * value `REDACTED`: - * - * - [`X-Amz-Signature`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`X-Amz-Credential`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`X-Amz-Security-Token`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) - * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) - * - * This list is subject to change over time. - * - * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive. - * - * - * Instrumentation **MAY** provide a way to override this list via declarative configuration. - * If so, it **SHOULD** use the `sensitive_query_parameters` property - * (an array of case-sensitive strings with minimum items 0) under - * `.instrumentation/development.general.sanitization.url`. - * This list is a full override of the default sensitive query parameter keys, - * it is not a list of keys in addition to the defaults. - * - * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. - * `https://www.example.com/path?color=blue&sig=REDACTED`. - */ - exports.ATTR_URL_FULL = "url.full"; - /** - * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component - * - * @example /search - * - * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it. - */ - exports.ATTR_URL_PATH = "url.path"; - /** - * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component - * - * @example q=OpenTelemetry - * - * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it. - * - * - * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`: - * - * - [`X-Amz-Signature`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`X-Amz-Credential`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`X-Amz-Security-Token`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) - * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) - * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) - * - * This list is subject to change over time. - * - * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive. - * - * Instrumentation **MAY** provide a way to override this list via declarative configuration. - * If so, it **SHOULD** use the `sensitive_query_parameters` property - * (an array of case-sensitive strings with minimum items 0) under - * `.instrumentation/development.general.sanitization.url`. - * This list is a full override of the default sensitive query parameter keys, - * it is not a list of keys in addition to the defaults. - * - * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. - * `q=OpenTelemetry&sig=REDACTED`. - */ - exports.ATTR_URL_QUERY = "url.query"; - /** - * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol. - * - * @example https - * @example ftp - * @example telnet - */ - exports.ATTR_URL_SCHEME = "url.scheme"; - /** - * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client. - * - * @example CERN-LineMode/2.15 libwww/2.17b3 - * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1 - * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2 - */ - exports.ATTR_USER_AGENT_ORIGINAL = "user_agent.original"; -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js -var require_stable_metrics = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = exports.METRIC_KESTREL_REJECTED_CONNECTIONS = exports.METRIC_KESTREL_QUEUED_REQUESTS = exports.METRIC_KESTREL_QUEUED_CONNECTIONS = exports.METRIC_KESTREL_CONNECTION_DURATION = exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = exports.METRIC_JVM_THREAD_COUNT = exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = exports.METRIC_JVM_MEMORY_USED = exports.METRIC_JVM_MEMORY_LIMIT = exports.METRIC_JVM_MEMORY_COMMITTED = exports.METRIC_JVM_GC_DURATION = exports.METRIC_JVM_CPU_TIME = exports.METRIC_JVM_CPU_RECENT_UTILIZATION = exports.METRIC_JVM_CPU_COUNT = exports.METRIC_JVM_CLASS_UNLOADED = exports.METRIC_JVM_CLASS_LOADED = exports.METRIC_JVM_CLASS_COUNT = exports.METRIC_HTTP_SERVER_REQUEST_DURATION = exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = exports.METRIC_DOTNET_TIMER_COUNT = exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = exports.METRIC_DOTNET_PROCESS_CPU_TIME = exports.METRIC_DOTNET_PROCESS_CPU_COUNT = exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = exports.METRIC_DOTNET_JIT_COMPILED_METHODS = exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = exports.METRIC_DOTNET_JIT_COMPILATION_TIME = exports.METRIC_DOTNET_GC_PAUSE_TIME = exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = exports.METRIC_DOTNET_GC_COLLECTIONS = exports.METRIC_DOTNET_EXCEPTIONS = exports.METRIC_DOTNET_ASSEMBLY_COUNT = exports.METRIC_DB_CLIENT_OPERATION_DURATION = exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = void 0; - exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = void 0; - /** - * Number of exceptions caught by exception handling middleware. - * - * @note Meter name: `Microsoft.AspNetCore.Diagnostics`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = "aspnetcore.diagnostics.exceptions"; - /** - * Number of requests that are currently active on the server that hold a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = "aspnetcore.rate_limiting.active_request_leases"; - /** - * Number of requests that are currently queued, waiting to acquire a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = "aspnetcore.rate_limiting.queued_requests"; - /** - * The time the request spent in a queue waiting to acquire a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = "aspnetcore.rate_limiting.request.time_in_queue"; - /** - * The duration of rate limiting lease held by requests on the server. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = "aspnetcore.rate_limiting.request_lease.duration"; - /** - * Number of requests that tried to acquire a rate limiting lease. - * - * @note Requests could be: - * - * - Rejected by global or endpoint rate limiting policies - * - Canceled while waiting for the lease. - * - * Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = "aspnetcore.rate_limiting.requests"; - /** - * Number of requests that were attempted to be matched to an endpoint. - * - * @note Meter name: `Microsoft.AspNetCore.Routing`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = "aspnetcore.routing.match_attempts"; - /** - * Duration of database client operations. - * - * @note Batch operations **SHOULD** be recorded as a single operation. - */ - exports.METRIC_DB_CLIENT_OPERATION_DURATION = "db.client.operation.duration"; - /** - * The number of .NET assemblies that are currently loaded. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`AppDomain.CurrentDomain.GetAssemblies().Length`](https://learn.microsoft.com/dotnet/api/system.appdomain.getassemblies). - */ - exports.METRIC_DOTNET_ASSEMBLY_COUNT = "dotnet.assembly.count"; - /** - * The number of exceptions that have been thrown in managed code. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as counting calls to [`AppDomain.CurrentDomain.FirstChanceException`](https://learn.microsoft.com/dotnet/api/system.appdomain.firstchanceexception). - */ - exports.METRIC_DOTNET_EXCEPTIONS = "dotnet.exceptions"; - /** - * The number of garbage collections that have occurred since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric uses the [`GC.CollectionCount(int generation)`](https://learn.microsoft.com/dotnet/api/system.gc.collectioncount) API to calculate exclusive collections per generation. - */ - exports.METRIC_DOTNET_GC_COLLECTIONS = "dotnet.gc.collections"; - /** - * The *approximate* number of bytes allocated on the managed GC heap since the process has started. The returned value does not include any native allocations. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetTotalAllocatedBytes()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalallocatedbytes). - */ - exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = "dotnet.gc.heap.total_allocated"; - /** - * The heap fragmentation, as observed during the latest garbage collection. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.FragmentationAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.fragmentationafterbytes). - */ - exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = "dotnet.gc.last_collection.heap.fragmentation.size"; - /** - * The managed GC heap size (including fragmentation), as observed during the latest garbage collection. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.SizeAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.sizeafterbytes). - */ - exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = "dotnet.gc.last_collection.heap.size"; - /** - * The amount of committed virtual memory in use by the .NET GC, as observed during the latest garbage collection. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetGCMemoryInfo().TotalCommittedBytes`](https://learn.microsoft.com/dotnet/api/system.gcmemoryinfo.totalcommittedbytes). Committed virtual memory may be larger than the heap size because it includes both memory for storing existing objects (the heap size) and some extra memory that is ready to handle newly allocated objects in the future. - */ - exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = "dotnet.gc.last_collection.memory.committed_size"; - /** - * The total amount of time paused in GC since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetTotalPauseDuration()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalpauseduration). - */ - exports.METRIC_DOTNET_GC_PAUSE_TIME = "dotnet.gc.pause.time"; - /** - * The amount of time the JIT compiler has spent compiling methods since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`JitInfo.GetCompilationTime()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompilationtime). - */ - exports.METRIC_DOTNET_JIT_COMPILATION_TIME = "dotnet.jit.compilation.time"; - /** - * Count of bytes of intermediate language that have been compiled since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`JitInfo.GetCompiledILBytes()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledilbytes). - */ - exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = "dotnet.jit.compiled_il.size"; - /** - * The number of times the JIT compiler (re)compiled methods since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`JitInfo.GetCompiledMethodCount()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledmethodcount). - */ - exports.METRIC_DOTNET_JIT_COMPILED_METHODS = "dotnet.jit.compiled_methods"; - /** - * The number of times there was contention when trying to acquire a monitor lock since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`Monitor.LockContentionCount`](https://learn.microsoft.com/dotnet/api/system.threading.monitor.lockcontentioncount). - */ - exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = "dotnet.monitor.lock_contentions"; - /** - * The number of processors available to the process. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as accessing [`Environment.ProcessorCount`](https://learn.microsoft.com/dotnet/api/system.environment.processorcount). - */ - exports.METRIC_DOTNET_PROCESS_CPU_COUNT = "dotnet.process.cpu.count"; - /** - * CPU time used by the process. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as accessing the corresponding processor time properties on [`System.Diagnostics.Process`](https://learn.microsoft.com/dotnet/api/system.diagnostics.process). - */ - exports.METRIC_DOTNET_PROCESS_CPU_TIME = "dotnet.process.cpu.time"; - /** - * The number of bytes of physical memory mapped to the process context. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`Environment.WorkingSet`](https://learn.microsoft.com/dotnet/api/system.environment.workingset). - */ - exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = "dotnet.process.memory.working_set"; - /** - * The number of work items that are currently queued to be processed by the thread pool. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`ThreadPool.PendingWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.pendingworkitemcount). - */ - exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = "dotnet.thread_pool.queue.length"; - /** - * The number of thread pool threads that currently exist. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`ThreadPool.ThreadCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.threadcount). - */ - exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = "dotnet.thread_pool.thread.count"; - /** - * The number of work items that the thread pool has completed since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`ThreadPool.CompletedWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.completedworkitemcount). - */ - exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = "dotnet.thread_pool.work_item.count"; - /** - * The number of timer instances that are currently active. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`Timer.ActiveCount`](https://learn.microsoft.com/dotnet/api/system.threading.timer.activecount). - */ - exports.METRIC_DOTNET_TIMER_COUNT = "dotnet.timer.count"; - /** - * Duration of HTTP client requests. - */ - exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = "http.client.request.duration"; - /** - * Duration of HTTP server requests. - */ - exports.METRIC_HTTP_SERVER_REQUEST_DURATION = "http.server.request.duration"; - /** - * Number of classes currently loaded. - */ - exports.METRIC_JVM_CLASS_COUNT = "jvm.class.count"; - /** - * Number of classes loaded since JVM start. - */ - exports.METRIC_JVM_CLASS_LOADED = "jvm.class.loaded"; - /** - * Number of classes unloaded since JVM start. - */ - exports.METRIC_JVM_CLASS_UNLOADED = "jvm.class.unloaded"; - /** - * Number of processors available to the Java virtual machine. - */ - exports.METRIC_JVM_CPU_COUNT = "jvm.cpu.count"; - /** - * Recent CPU utilization for the process as reported by the JVM. - * - * @note The value range is [0.0,1.0]. This utilization is not defined as being for the specific interval since last measurement (unlike `system.cpu.utilization`). [Reference](https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad()). - */ - exports.METRIC_JVM_CPU_RECENT_UTILIZATION = "jvm.cpu.recent_utilization"; - /** - * CPU time used by the process as reported by the JVM. - */ - exports.METRIC_JVM_CPU_TIME = "jvm.cpu.time"; - /** - * Duration of JVM garbage collection actions. - */ - exports.METRIC_JVM_GC_DURATION = "jvm.gc.duration"; - /** - * Measure of memory committed. - */ - exports.METRIC_JVM_MEMORY_COMMITTED = "jvm.memory.committed"; - /** - * Measure of max obtainable memory. - */ - exports.METRIC_JVM_MEMORY_LIMIT = "jvm.memory.limit"; - /** - * Measure of memory used. - */ - exports.METRIC_JVM_MEMORY_USED = "jvm.memory.used"; - /** - * Measure of memory used, as measured after the most recent garbage collection event on this pool. - */ - exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = "jvm.memory.used_after_last_gc"; - /** - * Number of executing platform threads. - */ - exports.METRIC_JVM_THREAD_COUNT = "jvm.thread.count"; - /** - * Number of connections that are currently active on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = "kestrel.active_connections"; - /** - * Number of TLS handshakes that are currently in progress on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = "kestrel.active_tls_handshakes"; - /** - * The duration of connections on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_CONNECTION_DURATION = "kestrel.connection.duration"; - /** - * Number of connections that are currently queued and are waiting to start. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_QUEUED_CONNECTIONS = "kestrel.queued_connections"; - /** - * Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_QUEUED_REQUESTS = "kestrel.queued_requests"; - /** - * Number of connections rejected by the server. - * - * @note Connections are rejected when the currently active count exceeds the value configured with `MaxConcurrentConnections`. - * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_REJECTED_CONNECTIONS = "kestrel.rejected_connections"; - /** - * The duration of TLS handshakes on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = "kestrel.tls_handshake.duration"; - /** - * Number of connections that are currently upgraded (WebSockets). . - * - * @note The counter only tracks HTTP/1.1 connections. - * - * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = "kestrel.upgraded_connections"; - /** - * Number of connections that are currently active on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = "signalr.server.active_connections"; - /** - * The duration of connections on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 - */ - exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = "signalr.server.connection.duration"; -})); -//#endregion -//#region node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js -var require_stable_events = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.EVENT_EXCEPTION = void 0; - /** - * This event describes a single exception. - */ - exports.EVENT_EXCEPTION = "exception"; -})); -//#endregion -//#region node_modules/@better-auth/core/dist/instrumentation/attributes.mjs -var import_src = (/* @__PURE__ */ __commonJSMin(((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { - enumerable: true, - get: function() { - return m[k]; - } - }; - Object.defineProperty(o, k2, desc); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = exports && exports.__exportStar || function(m, exports$1) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - __exportStar(require_trace(), exports); - __exportStar(require_resource(), exports); - __exportStar(require_stable_attributes(), exports); - __exportStar(require_stable_metrics(), exports); - __exportStar(require_stable_events(), exports); -})))(); -/** Operation identifier (e.g. getSession, signUpWithEmailAndPassword). Uses endpoint operationId when set, otherwise the endpoint key. */ -var ATTR_OPERATION_ID = "better_auth.operation_id"; -/** Hook type (e.g. before, after, create.before). */ -var ATTR_HOOK_TYPE = "better_auth.hook.type"; -/** Execution context (e.g. user, plugin:id). */ -var ATTR_CONTEXT = "better_auth.context"; -//#endregion -//#region node_modules/@better-auth/core/dist/instrumentation/noop.mjs -function createNoopSpan() { - const span = { - end() {}, - setAttribute(_key, _value) {}, - setStatus(_status) {}, - recordException(_exception) {}, - updateName(_name) { - return span; - } - }; - return span; -} -function createNoopTracer(noopSpan) { - function startActiveSpan(_name, ...rest) { - const fn = rest[rest.length - 1]; - return fn(noopSpan); - } - return { startActiveSpan }; -} -function createNoopTraceAPI() { - const noopTracer = createNoopTracer(createNoopSpan()); - return { - getTracer(_name, _version) { - return noopTracer; - }, - getActiveSpan() {} - }; -} -function createNoopOpenTelemetryAPI() { - return { - SpanStatusCode: { - UNSET: 0, - OK: 1, - ERROR: 2 - }, - trace: createNoopTraceAPI() - }; -} -var noopOpenTelemetryAPI = createNoopOpenTelemetryAPI(); -//#endregion -//#region node_modules/@better-auth/core/dist/instrumentation/api.mjs -var openTelemetryAPIPromise; -var openTelemetryAPI; -function getOpenTelemetryAPI() { - if (!openTelemetryAPIPromise) openTelemetryAPIPromise = import("../../_chunks/core.mjs").then((mod) => { - openTelemetryAPI = mod; - }).catch(() => void 0); - return openTelemetryAPI ?? noopOpenTelemetryAPI; -} -//#endregion -//#region node_modules/@better-auth/core/dist/instrumentation/tracer.mjs -var INSTRUMENTATION_SCOPE = "better-auth"; -var INSTRUMENTATION_VERSION = "1.6.25"; -/** -* Better-auth uses `throw ctx.redirect(url)` for flow control (e.g. OAuth -* callbacks). These are APIErrors with 3xx status codes and should not be -* recorded as span errors. -*/ -function isRedirectError(err) { - if (err != null && typeof err === "object" && "name" in err && err.name === "APIError" && "statusCode" in err) { - const status = err.statusCode; - return status >= 300 && status < 400; - } - return false; -} -function endSpanWithError(span, err) { - const { SpanStatusCode } = getOpenTelemetryAPI(); - if (isRedirectError(err)) { - span.setAttribute(import_src.ATTR_HTTP_RESPONSE_STATUS_CODE, err.statusCode); - span.setStatus({ code: SpanStatusCode.OK }); - } else { - span.recordException(err); - span.setStatus({ - code: SpanStatusCode.ERROR, - message: String(err?.message ?? err) - }); - } - span.end(); -} -function withSpan(name, attributes, fn) { - const { trace } = getOpenTelemetryAPI(); - return trace.getTracer(INSTRUMENTATION_SCOPE, INSTRUMENTATION_VERSION).startActiveSpan(name, { attributes }, (span) => { - try { - const result = fn(); - if (result instanceof Promise) return result.then((value) => { - span.end(); - return value; - }).catch((err) => { - endSpanWithError(span, err); - throw err; - }); - span.end(); - return result; - } catch (err) { - endSpanWithError(span, err); - throw err; - } - }); -} -//#endregion -//#region node_modules/@better-auth/core/dist/db/adapter/factory.mjs -var debugLogs = []; -var transactionId = -1; -var createAsIsTransaction = (adapter) => (fn) => fn(adapter); -var createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => { - const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15); - const config = { - ...cfg, - supportsBooleans: cfg.supportsBooleans ?? true, - supportsDates: cfg.supportsDates ?? true, - supportsJSON: cfg.supportsJSON ?? false, - adapterName: cfg.adapterName ?? cfg.adapterId, - supportsNumericIds: cfg.supportsNumericIds ?? true, - supportsUUIDs: cfg.supportsUUIDs ?? false, - supportsArrays: cfg.supportsArrays ?? false, - transaction: cfg.transaction ?? false, - disableTransformInput: cfg.disableTransformInput ?? false, - disableTransformOutput: cfg.disableTransformOutput ?? false, - disableTransformJoin: cfg.disableTransformJoin ?? false - }; - if (options.advanced?.database?.generateId === "serial" && config.supportsNumericIds === false) throw new BetterAuthError(`[${config.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`); - const schema = getAuthTables(options); - const debugLog = (...args) => { - if (config.debugLogs === true || typeof config.debugLogs === "object") { - const logger = createLogger({ level: "info" }); - if (typeof config.debugLogs === "object" && "isRunningAdapterTests" in config.debugLogs) { - if (config.debugLogs.isRunningAdapterTests) { - args.shift(); - debugLogs.push({ - instance: uniqueAdapterFactoryInstanceId, - args - }); - } - return; - } - if (typeof config.debugLogs === "object" && config.debugLogs.logCondition && !config.debugLogs.logCondition?.()) return; - if (typeof args[0] === "object" && "method" in args[0]) { - const method = args.shift().method; - if (typeof config.debugLogs === "object") { - if (method === "create" && !config.debugLogs.create) return; - else if (method === "update" && !config.debugLogs.update) return; - else if (method === "updateMany" && !config.debugLogs.updateMany) return; - else if (method === "findOne" && !config.debugLogs.findOne) return; - else if (method === "findMany" && !config.debugLogs.findMany) return; - else if (method === "delete" && !config.debugLogs.delete) return; - else if (method === "deleteMany" && !config.debugLogs.deleteMany) return; - else if (method === "consumeOne" && !config.debugLogs.consumeOne) return; - else if (method === "incrementOne" && !config.debugLogs.incrementOne) return; - else if (method === "count" && !config.debugLogs.count) return; - } - logger.info(`[${config.adapterName}]`, ...args); - } else logger.info(`[${config.adapterName}]`, ...args); - } - }; - const logger = createLogger(options.logger); - const getDefaultModelName = initGetDefaultModelName({ - usePlural: config.usePlural, - schema - }); - const getDefaultFieldName = initGetDefaultFieldName({ - usePlural: config.usePlural, - schema - }); - const getModelName = initGetModelName({ - usePlural: config.usePlural, - schema - }); - const getFieldName = initGetFieldName({ - schema, - usePlural: config.usePlural - }); - const idField = initGetIdField({ - schema, - options, - usePlural: config.usePlural, - disableIdGeneration: config.disableIdGeneration, - customIdGenerator: config.customIdGenerator, - supportsUUIDs: config.supportsUUIDs - }); - const getFieldAttributes = initGetFieldAttributes({ - schema, - options, - usePlural: config.usePlural, - disableIdGeneration: config.disableIdGeneration, - customIdGenerator: config.customIdGenerator - }); - const transformInput = async (data, defaultModelName, action, forceAllowId) => { - const transformedData = {}; - const fields = schema[defaultModelName].fields; - const newMappedKeys = config.mapKeysTransformInput ?? {}; - const useNumberId = options.advanced?.database?.generateId === "serial"; - fields.id = idField({ - customModelName: defaultModelName, - forceAllowId: forceAllowId && "id" in data - }); - for (const field in fields) { - let value = data[field]; - const fieldAttributes = fields[field]; - const newFieldName = newMappedKeys[field] || fields[field].fieldName || field; - if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue; - if (fieldAttributes && fieldAttributes.type === "date" && !(value instanceof Date) && typeof value === "string") try { - value = new Date(value); - } catch { - logger.error("[Adapter Factory] Failed to convert string to date", { - value, - field - }); - } - let newValue = withApplyDefault(value, fieldAttributes, action); - if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue); - if (fieldAttributes.references?.field === "id" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null); - else newValue = newValue !== null ? Number(newValue) : null; - else if (config.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue); - else if (config.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue); - else if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString(); - else if (config.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0; - if (config.customTransformInput) newValue = config.customTransformInput({ - data: newValue, - action, - field: newFieldName, - fieldAttributes, - model: getModelName(defaultModelName), - schema, - options - }); - if (newValue !== void 0) transformedData[newFieldName] = newValue; - } - return transformedData; - }; - const transformOutput = async (data, unsafe_model, select = [], join) => { - const transformSingleOutput = async (data, unsafe_model, select = []) => { - if (!data) return null; - const newMappedKeys = config.mapKeysTransformOutput ?? {}; - const transformedData = {}; - const tableSchema = schema[getDefaultModelName(unsafe_model)].fields; - const idKey = Object.entries(newMappedKeys).find(([_, v]) => v === "id")?.[0]; - tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.generateId === "serial" ? "number" : "string" }; - for (const key in tableSchema) { - if (select.length && !select.includes(key)) continue; - const field = tableSchema[key]; - if (field) { - const originalKey = field.fieldName || key; - let newValue = data[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey]; - if (field.transform?.output) newValue = await field.transform.output(newValue); - const newFieldName = newMappedKeys[key] || key; - if (originalKey === "id" || field.references?.field === "id") { - if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue); - } else if (config.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue); - else if (config.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue); - else if (config.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue); - else if (config.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1; - if (config.customTransformOutput) newValue = config.customTransformOutput({ - data: newValue, - field: newFieldName, - fieldAttributes: field, - select, - model: getModelName(unsafe_model), - schema, - options - }); - transformedData[newFieldName] = newValue; - } - } - return transformedData; - }; - if (!join || Object.keys(join).length === 0) return await transformSingleOutput(data, unsafe_model, select); - unsafe_model = getDefaultModelName(unsafe_model); - const transformedData = await transformSingleOutput(data, unsafe_model, select); - const requiredModels = Object.entries(join).map(([model, joinConfig]) => ({ - modelName: getModelName(model), - defaultModelName: getDefaultModelName(model), - joinConfig - })); - if (!data) return null; - for (const { modelName, defaultModelName, joinConfig } of requiredModels) { - let joinedData = await (async () => { - if (options.experimental?.joins) return data[modelName]; - else return await handleFallbackJoin({ - baseModel: unsafe_model, - baseData: transformedData, - joinModel: modelName, - specificJoinConfig: joinConfig - }); - })(); - if (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === "one-to-one" ? null : []; - if (joinConfig.relation === "one-to-many" && !Array.isArray(joinedData)) joinedData = [joinedData]; - const transformed = []; - if (Array.isArray(joinedData)) for (const item of joinedData) { - const transformedItem = await transformSingleOutput(item, modelName, []); - transformed.push(transformedItem); - } - else { - const transformedItem = await transformSingleOutput(joinedData, modelName, []); - transformed.push(transformedItem); - } - transformedData[defaultModelName] = (joinConfig.relation === "one-to-one" ? transformed[0] : transformed) ?? null; - } - return transformedData; - }; - const transformWhereClause = ({ model, where, action }) => { - if (!where) return void 0; - const newMappedKeys = config.mapKeysTransformInput ?? {}; - return where.map((w) => { - const { field: unsafe_field, value, operator = "eq", connector = "AND", mode = "sensitive" } = w; - if (operator === "in") { - if (!Array.isArray(value)) throw new BetterAuthError("Value must be an array"); - } - let newValue = value; - const defaultModelName = getDefaultModelName(model); - const defaultFieldName = getDefaultFieldName({ - field: unsafe_field, - model - }); - const fieldName = newMappedKeys[defaultFieldName] || getFieldName({ - field: defaultFieldName, - model: defaultModelName - }); - const fieldAttr = getFieldAttributes({ - field: defaultFieldName, - model: defaultModelName - }); - const useNumberId = options.advanced?.database?.generateId === "serial"; - if (defaultFieldName === "id" || fieldAttr.references?.field === "id") { - if (useNumberId) if (Array.isArray(value)) newValue = value.map(Number); - else newValue = Number(value); - } - if (fieldAttr.type === "date" && value instanceof Date && !config.supportsDates) newValue = value.toISOString(); - if (fieldAttr.type === "boolean" && typeof newValue === "string") newValue = newValue === "true"; - if (fieldAttr.type === "number") { - if (typeof newValue === "string" && newValue.trim() !== "") { - const parsed = Number(newValue); - if (!Number.isNaN(parsed)) newValue = parsed; - } else if (Array.isArray(newValue)) { - const parsed = newValue.map((v) => typeof v === "string" && v.trim() !== "" ? Number(v) : NaN); - if (parsed.every((n) => !Number.isNaN(n))) newValue = parsed; - } - } - if (fieldAttr.type === "boolean" && typeof newValue === "boolean" && !config.supportsBooleans) newValue = newValue ? 1 : 0; - if (fieldAttr.type === "json" && typeof value === "object" && !config.supportsJSON) try { - newValue = JSON.stringify(value); - } catch (error) { - throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error }); - } - if (config.customTransformInput) newValue = config.customTransformInput({ - data: newValue, - fieldAttributes: fieldAttr, - field: fieldName, - model: getModelName(model), - schema, - options, - action - }); - return { - operator, - connector, - field: fieldName, - value: newValue, - mode - }; - }); - }; - const transformJoinClause = (baseModel, unsanitizedJoin, select) => { - if (!unsanitizedJoin) return void 0; - if (Object.keys(unsanitizedJoin).length === 0) return void 0; - const transformedJoin = {}; - for (const [model, join] of Object.entries(unsanitizedJoin)) { - if (!join) continue; - const defaultModelName = getDefaultModelName(model); - const defaultBaseModelName = getDefaultModelName(baseModel); - let foreignKeys = Object.entries(schema[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName); - let isForwardJoin = true; - if (!foreignKeys.length) { - foreignKeys = Object.entries(schema[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName); - isForwardJoin = false; - } - if (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`); - else if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`); - const [foreignKey, foreignKeyAttributes] = foreignKeys[0]; - if (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`); - let from; - let to; - let requiredSelectField; - if (isForwardJoin) { - requiredSelectField = foreignKeyAttributes.references.field; - from = getFieldName({ - model: baseModel, - field: requiredSelectField - }); - to = getFieldName({ - model, - field: foreignKey - }); - } else { - requiredSelectField = foreignKey; - from = getFieldName({ - model: baseModel, - field: requiredSelectField - }); - to = getFieldName({ - model, - field: foreignKeyAttributes.references.field - }); - } - if (select && !select.includes(requiredSelectField)) select.push(requiredSelectField); - const isUnique = to === "id" ? true : foreignKeyAttributes.unique ?? false; - let limit = options.advanced?.database?.defaultFindManyLimit ?? 100; - if (isUnique) limit = 1; - else if (typeof join === "object" && typeof join.limit === "number") limit = join.limit; - transformedJoin[getModelName(model)] = { - on: { - from, - to - }, - limit, - relation: isUnique ? "one-to-one" : "one-to-many" - }; - } - return { - join: transformedJoin, - select - }; - }; - /** - * Handle joins by making separate queries and combining results (fallback for adapters that don't support native joins). - */ - const handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => { - if (!baseData) return baseData; - const modelName = getModelName(joinModel); - const field = joinConfig.on.to; - const value = baseData[getDefaultFieldName({ - field: joinConfig.on.from, - model: baseModel - })]; - if (value === null || value === void 0) return joinConfig.relation === "one-to-one" ? null : []; - let result; - const where = transformWhereClause({ - model: modelName, - where: [{ - field, - value, - operator: "eq", - connector: "AND" - }], - action: "findOne" - }); - try { - if (joinConfig.relation === "one-to-one") result = await withSpan(`db findOne ${modelName}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "findOne", - [import_src.ATTR_DB_COLLECTION_NAME]: modelName - }, () => adapterInstance.findOne({ - model: modelName, - where - })); - else { - const limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - result = await withSpan(`db findMany ${modelName}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "findMany", - [import_src.ATTR_DB_COLLECTION_NAME]: modelName - }, () => adapterInstance.findMany({ - model: modelName, - where, - limit - })); - } - } catch (error) { - logger.error(`Failed to query fallback join for model ${modelName}:`, { - where, - limit: joinConfig.limit - }); - console.error(error); - throw error; - } - return result; - }; - const adapterInstance = customAdapter({ - options, - schema, - debugLog, - getFieldName, - getModelName, - getDefaultModelName, - getDefaultFieldName, - getFieldAttributes, - transformInput, - transformOutput, - transformWhereClause - }); - let lazyLoadTransaction = null; - const adapter = { - transaction: async (cb) => { - if (!lazyLoadTransaction) if (!config.transaction) lazyLoadTransaction = createAsIsTransaction(adapter); - else { - logger.debug(`[${config.adapterName}] - Using provided transaction implementation.`); - lazyLoadTransaction = config.transaction; - } - return lazyLoadTransaction(cb); - }, - create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - unsafeModel = getDefaultModelName(unsafeModel); - if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) { - logger.warn(`[${config.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`); - const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "Create method with `id` being called at:"); - console.log(stack); - unsafeData.id = void 0; - } - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data = unsafeData; - if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create", forceAllowId); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, { - model, - data - }); - const res = await withSpan(`db create ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "create", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.create({ - data, - model - })); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, { - model, - res - }); - let transformed = res; - if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, void 0); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { - transactionId++; - const thisTransactionId = transactionId; - unsafeModel = getDefaultModelName(unsafeModel); - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "update" - }); - if (where.length === 0) return null; - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data = unsafeData; - if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, { - model, - data - }); - const res = await withSpan(`db update ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "update", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.update({ - model, - where, - update: data - })); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "updateMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data = unsafeData; - if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, { - model, - data - }); - const updatedCount = await withSpan(`db updateMany ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "updateMany", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.updateMany({ - model, - where, - update: data - })); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, { - model, - data: updatedCount - }); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, { - model, - data: updatedCount - }); - return updatedCount; - }, - findOne: async ({ model: unsafeModel, where: unsafeWhere, select, join: unsafeJoin }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "findOne" - }); - unsafeModel = getDefaultModelName(unsafeModel); - let join; - let passJoinToAdapter = true; - if (!config.disableTransformJoin) { - const result = transformJoinClause(unsafeModel, unsafeJoin, select); - if (result) { - join = result.join; - select = result.select; - } - if (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false; - } else join = unsafeJoin; - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, { - model, - where, - select, - join - }); - const res = await withSpan(`db findOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "findOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.findOne({ - model, - where, - select, - join: passJoinToAdapter ? join : void 0 - })); - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, join); - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, select, sortBy, offset, join: unsafeJoin }) => { - transactionId++; - const thisTransactionId = transactionId; - const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "findMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - let join; - let passJoinToAdapter = true; - if (!config.disableTransformJoin) { - const result = transformJoinClause(unsafeModel, unsafeJoin, select); - if (result) { - join = result.join; - select = result.select; - } - if (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false; - } else join = unsafeJoin; - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, { - model, - where, - limit, - sortBy, - offset, - join - }); - const res = await withSpan(`db findMany ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "findMany", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.findMany({ - model, - where, - limit, - select, - sortBy, - offset, - join: passJoinToAdapter ? join : void 0 - })); - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => { - return await transformOutput(r, unsafeModel, void 0, join); - })); - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - delete: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "delete" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, { - model, - where - }); - await withSpan(`db delete ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "delete", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.delete({ - model, - where - })); - debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model }); - }, - deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "deleteMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, { - model, - where - }); - const res = await withSpan(`db deleteMany ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "deleteMany", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.deleteMany({ - model, - where - })); - debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - return res; - }, - consumeOne: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "consumeOne" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("consumeOne")} ${formatAction("ConsumeOne")}:`, { - model, - where - }); - let res; - let resultNeedsOutputTransform = true; - if (adapterInstance.consumeOne) res = await withSpan(`db consumeOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "consumeOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.consumeOne({ - model, - where - })); - else { - res = await withSpan(`db consumeOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "consumeOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => runWithTransaction(adapter, async () => { - const trx = await getCurrentAdapter(adapter); - const target = (await trx.findMany({ - model: unsafeModel, - where: unsafeWhere, - limit: 1 - }))[0]; - if (!target) return null; - const deleted = await trx.deleteMany({ - model: unsafeModel, - where: [...unsafeWhere, { - field: "id", - value: target.id, - operator: "eq", - connector: "AND", - mode: "sensitive" - }] - }); - if (typeof deleted !== "number") throw new BetterAuthError(`Adapter "${config.adapterId}" returned a non-numeric value from deleteMany during the consumeOne fallback. Return the number of deleted rows, or implement a native consumeOne for atomic single-use consumption.`); - return deleted > 0 ? target : null; - })); - resultNeedsOutputTransform = false; - } - debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("consumeOne")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput && resultNeedsOutputTransform && res) transformed = await transformOutput(res, unsafeModel, void 0, void 0); - debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("consumeOne")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - incrementOne: async ({ model: unsafeModel, where: unsafeWhere, increment: unsafeIncrement, set: unsafeSet }) => { - const hasIncrement = Object.keys(unsafeIncrement).length > 0; - const hasSet = !!unsafeSet && Object.keys(unsafeSet).length > 0; - if (!hasIncrement && !hasSet) throw new BetterAuthError("incrementOne requires a non-empty `increment` or `set`; both were empty."); - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "incrementOne" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("incrementOne")} ${formatAction("IncrementOne")}:`, { - model, - where, - increment: unsafeIncrement, - set: unsafeSet - }); - let res; - let resultNeedsOutputTransform = true; - if (adapterInstance.incrementOne) { - const mappedKeys = config.mapKeysTransformInput ?? {}; - const increment = {}; - for (const [field, delta] of Object.entries(unsafeIncrement)) increment[mappedKeys[field] || getFieldName({ - model: unsafeModel, - field - })] = delta; - let set; - if (unsafeSet && !config.disableTransformInput) set = await transformInput(unsafeSet, unsafeModel, "update"); - else set = unsafeSet; - if (Object.keys(increment).length === 0 && (!set || Object.keys(set).length === 0)) throw new BetterAuthError("incrementOne resolved to an empty update: every increment/set field was unknown to the schema or transformed away."); - res = await withSpan(`db incrementOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "incrementOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.incrementOne({ - model, - where, - increment, - set - })); - } else { - res = await withSpan(`db incrementOne ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "incrementOne", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => runWithTransaction(adapter, async () => { - const trx = await getCurrentAdapter(adapter); - const target = (await trx.findMany({ - model: unsafeModel, - where: unsafeWhere, - limit: 1 - }))[0]; - if (!target) return null; - const nextValues = { ...unsafeSet ?? {} }; - for (const [field, delta] of Object.entries(unsafeIncrement)) nextValues[field] = (typeof target[field] === "number" ? target[field] : 0) + delta; - const updated = await trx.updateMany({ - model: unsafeModel, - where: [...unsafeWhere, { - field: "id", - value: target.id, - operator: "eq", - connector: "AND", - mode: "sensitive" - }], - update: nextValues - }); - if (typeof updated !== "number") throw new BetterAuthError(`Adapter "${config.adapterId}" returned a non-numeric value from updateMany during the incrementOne fallback. Return the number of updated rows, or implement a native incrementOne for atomic guarded counter updates.`); - return updated > 0 ? { - ...target, - ...nextValues - } : null; - })); - resultNeedsOutputTransform = false; - } - debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("incrementOne")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config.disableTransformOutput && resultNeedsOutputTransform && res) transformed = await transformOutput(res, unsafeModel, void 0, void 0); - debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("incrementOne")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - count: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "count" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, { - model, - where - }); - const res = await withSpan(`db count ${model}`, { - [import_src.ATTR_DB_OPERATION_NAME]: "count", - [import_src.ATTR_DB_COLLECTION_NAME]: model - }, () => adapterInstance.count({ - model, - where - })); - debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, { - model, - data: res - }); - return res; - }, - createSchema: adapterInstance.createSchema ? async (_, file) => { - const tables = getAuthTables(options); - if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session; - return adapterInstance.createSchema({ - file, - tables - }); - } : void 0, - options: { - adapterConfig: config, - ...adapterInstance.options ?? {} - }, - id: config.adapterId, - ...config.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: { - resetDebugLogs() { - debugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId); - }, - printDebugLogs() { - const separator = `─`.repeat(80); - const logs = debugLogs.filter((log) => log.instance === uniqueAdapterFactoryInstanceId); - if (logs.length === 0) return; - const log = logs.reverse().map((log) => { - log.args[0] = `\n${log.args[0]}`; - return [...log.args, "\n"]; - }).reduce((prev, curr) => { - return [...curr, ...prev]; - }, [`\n${separator}`]); - console.log(...log); - } - } } : {} - }; - return adapter; -}; -function formatTransactionId(transactionId) { - if (getColorDepth() < 8) return `#${transactionId}`; - return `${TTY_COLORS.fg.magenta}#${transactionId}${TTY_COLORS.reset}`; -} -function formatStep(step, total) { - return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`; -} -function formatMethod(method) { - return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`; -} -function formatAction(action) { - return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`; -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/buffer_utils.js -var encoder = new TextEncoder(); -var decoder = new TextDecoder(); -var MAX_INT32 = 2 ** 32; -function concat(...buffers) { - const size = buffers.reduce((acc, { length }) => acc + length, 0); - const buf = new Uint8Array(size); - let i = 0; - for (const buffer of buffers) { - buf.set(buffer, i); - i += buffer.length; - } - return buf; -} -function writeUInt32BE(buf, value, offset) { - if (value < 0 || value >= MAX_INT32) throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); - buf.set([ - value >>> 24, - value >>> 16, - value >>> 8, - value & 255 - ], offset); -} -function uint64be(value) { - const high = Math.floor(value / MAX_INT32); - const low = value % MAX_INT32; - const buf = /* @__PURE__ */ new Uint8Array(8); - writeUInt32BE(buf, high, 0); - writeUInt32BE(buf, low, 4); - return buf; -} -function uint32be(value) { - const buf = /* @__PURE__ */ new Uint8Array(4); - writeUInt32BE(buf, value); - return buf; -} -function encode$2(string) { - const bytes = new Uint8Array(string.length); - for (let i = 0; i < string.length; i++) { - const code = string.charCodeAt(i); - if (code > 127) throw new TypeError("non-ASCII string encountered in encode()"); - bytes[i] = code; - } - return bytes; -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/base64.js -function encodeBase64(input) { - if (Uint8Array.prototype.toBase64) return input.toBase64(); - const CHUNK_SIZE = 32768; - const arr = []; - for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE))); - return btoa(arr.join("")); -} -function decodeBase64(encoded) { - if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded); - const binary = atob(encoded); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); - return bytes; -} -//#endregion -//#region node_modules/jose/dist/webapi/util/base64url.js -function decode$1(input) { - if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" }); - let encoded = input; - if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded); - encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); - try { - return decodeBase64(encoded); - } catch { - throw new TypeError("The input to be decoded is not correctly encoded."); - } -} -function encode$1(input) { - let unencoded = input; - if (typeof unencoded === "string") unencoded = encoder.encode(unencoded); - if (Uint8Array.prototype.toBase64) return unencoded.toBase64({ - alphabet: "base64url", - omitPadding: true - }); - return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/crypto_key.js -var unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); -var isAlgorithm = (algorithm, name) => algorithm.name === name; -function getHashLength(hash) { - return parseInt(hash.name.slice(4), 10); -} -function checkHashLength(algorithm, expected) { - if (getHashLength(algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); -} -function getNamedCurve(alg) { - switch (alg) { - case "ES256": return "P-256"; - case "ES384": return "P-384"; - case "ES512": return "P-521"; - default: throw new Error("unreachable"); - } -} -function checkUsage(key, usage) { - if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); -} -function checkSigCryptoKey(key, alg, usage) { - switch (alg) { - case "HS256": - case "HS384": - case "HS512": - if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC"); - checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); - break; - case "RS256": - case "RS384": - case "RS512": - if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5"); - checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); - break; - case "PS256": - case "PS384": - case "PS512": - if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS"); - checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); - break; - case "Ed25519": - case "EdDSA": - if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519"); - break; - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg); - break; - case "ES256": - case "ES384": - case "ES512": { - if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA"); - const expected = getNamedCurve(alg); - if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve"); - break; - } - default: throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} -function checkEncCryptoKey(key, alg, usage) { - switch (alg) { - case "A128GCM": - case "A192GCM": - case "A256GCM": { - if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM"); - const expected = parseInt(alg.slice(1, 4), 10); - if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length"); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW"); - const expected = parseInt(alg.slice(1, 4), 10); - if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length"); - break; - } - case "ECDH": - switch (key.algorithm.name) { - case "ECDH": - case "X25519": break; - default: throw unusable("ECDH or X25519"); - } - break; - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": - if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2"); - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP"); - checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1); - break; - default: throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/invalid_key_input.js -function message(msg, actual, ...types) { - types = types.filter(Boolean); - if (types.length > 2) { - const last = types.pop(); - msg += `one of type ${types.join(", ")}, or ${last}.`; - } else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`; - else msg += `of type ${types[0]}.`; - if (actual == null) msg += ` Received ${actual}`; - else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`; - else if (typeof actual === "object" && actual != null) { - if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`; - } - return msg; -} -var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types); -var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types); -//#endregion -//#region node_modules/jose/dist/webapi/util/errors.js -var JOSEError = class extends Error { - static code = "ERR_JOSE_GENERIC"; - code = "ERR_JOSE_GENERIC"; - constructor(message, options) { - super(message, options); - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } -}; -var JWTClaimValidationFailed = class extends JOSEError { - static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - claim; - reason; - payload; - constructor(message, payload, claim = "unspecified", reason = "unspecified") { - super(message, { cause: { - claim, - reason, - payload - } }); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -}; -var JWTExpired = class extends JOSEError { - static code = "ERR_JWT_EXPIRED"; - code = "ERR_JWT_EXPIRED"; - claim; - reason; - payload; - constructor(message, payload, claim = "unspecified", reason = "unspecified") { - super(message, { cause: { - claim, - reason, - payload - } }); - this.claim = claim; - this.reason = reason; - this.payload = payload; - } -}; -var JOSEAlgNotAllowed = class extends JOSEError { - static code = "ERR_JOSE_ALG_NOT_ALLOWED"; - code = "ERR_JOSE_ALG_NOT_ALLOWED"; -}; -var JOSENotSupported = class extends JOSEError { - static code = "ERR_JOSE_NOT_SUPPORTED"; - code = "ERR_JOSE_NOT_SUPPORTED"; -}; -var JWEDecryptionFailed = class extends JOSEError { - static code = "ERR_JWE_DECRYPTION_FAILED"; - code = "ERR_JWE_DECRYPTION_FAILED"; - constructor(message = "decryption operation failed", options) { - super(message, options); - } -}; -var JWEInvalid = class extends JOSEError { - static code = "ERR_JWE_INVALID"; - code = "ERR_JWE_INVALID"; -}; -var JWSInvalid = class extends JOSEError { - static code = "ERR_JWS_INVALID"; - code = "ERR_JWS_INVALID"; -}; -var JWTInvalid = class extends JOSEError { - static code = "ERR_JWT_INVALID"; - code = "ERR_JWT_INVALID"; -}; -var JWKInvalid = class extends JOSEError { - static code = "ERR_JWK_INVALID"; - code = "ERR_JWK_INVALID"; -}; -var JWKSInvalid = class extends JOSEError { - static code = "ERR_JWKS_INVALID"; - code = "ERR_JWKS_INVALID"; -}; -var JWKSNoMatchingKey = class extends JOSEError { - static code = "ERR_JWKS_NO_MATCHING_KEY"; - code = "ERR_JWKS_NO_MATCHING_KEY"; - constructor(message = "no applicable key found in the JSON Web Key Set", options) { - super(message, options); - } -}; -var JWKSMultipleMatchingKeys = class extends JOSEError { - [Symbol.asyncIterator]; - static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - constructor(message = "multiple matching keys found in the JSON Web Key Set", options) { - super(message, options); - } -}; -var JWKSTimeout = class extends JOSEError { - static code = "ERR_JWKS_TIMEOUT"; - code = "ERR_JWKS_TIMEOUT"; - constructor(message = "request timed out", options) { - super(message, options); - } -}; -var JWSSignatureVerificationFailed = class extends JOSEError { - static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - constructor(message = "signature verification failed", options) { - super(message, options); - } -}; -//#endregion -//#region node_modules/jose/dist/webapi/lib/is_key_like.js -function assertCryptoKey(key) { - if (!isCryptoKey(key)) throw new Error("CryptoKey instance expected"); -} -var isCryptoKey = (key) => { - if (key?.[Symbol.toStringTag] === "CryptoKey") return true; - try { - return key instanceof CryptoKey; - } catch { - return false; - } -}; -var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; -var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); -//#endregion -//#region node_modules/jose/dist/webapi/lib/helpers.js -var unprotected = Symbol(); -function assertNotSet(value, name) { - if (value) throw new TypeError(`${name} can only be called once`); -} -function decodeBase64url(value, label, ErrorClass) { - try { - return decode$1(value); - } catch { - throw new ErrorClass(`Failed to base64url decode the ${label}`); - } -} -async function digest(algorithm, data) { - const subtleDigest = `SHA-${algorithm.slice(-3)}`; - return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/type_checks.js -var isObjectLike = (value) => typeof value === "object" && value !== null; -function isObject$1(input) { - if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false; - if (Object.getPrototypeOf(input) === null) return true; - let proto = input; - while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto); - return Object.getPrototypeOf(input) === proto; -} -function isDisjoint(...headers) { - const sources = headers.filter(Boolean); - if (sources.length === 0 || sources.length === 1) return true; - let acc; - for (const header of sources) { - const parameters = Object.keys(header); - if (!acc || acc.size === 0) { - acc = new Set(parameters); - continue; - } - for (const parameter of parameters) { - if (acc.has(parameter)) return false; - acc.add(parameter); - } - } - return true; -} -var isJWK = (key) => isObject$1(key) && typeof key.kty === "string"; -var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"); -var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0; -var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string"; -//#endregion -//#region node_modules/jose/dist/webapi/lib/signing.js -function checkKeyLength(alg, key) { - if (alg.startsWith("RS") || alg.startsWith("PS")) { - const { modulusLength } = key.algorithm; - if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); - } -} -function subtleAlgorithm(alg, algorithm) { - const hash = `SHA-${alg.slice(-3)}`; - switch (alg) { - case "HS256": - case "HS384": - case "HS512": return { - hash, - name: "HMAC" - }; - case "PS256": - case "PS384": - case "PS512": return { - hash, - name: "RSA-PSS", - saltLength: parseInt(alg.slice(-3), 10) >> 3 - }; - case "RS256": - case "RS384": - case "RS512": return { - hash, - name: "RSASSA-PKCS1-v1_5" - }; - case "ES256": - case "ES384": - case "ES512": return { - hash, - name: "ECDSA", - namedCurve: algorithm.namedCurve - }; - case "Ed25519": - case "EdDSA": return { name: "Ed25519" }; - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": return { name: alg }; - default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } -} -async function getSigKey(alg, key, usage) { - if (key instanceof Uint8Array) { - if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); - return crypto.subtle.importKey("raw", key, { - hash: `SHA-${alg.slice(-3)}`, - name: "HMAC" - }, false, [usage]); - } - checkSigCryptoKey(key, alg, usage); - return key; -} -async function sign(alg, key, data) { - const cryptoKey = await getSigKey(alg, key, "sign"); - checkKeyLength(alg, cryptoKey); - const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data); - return new Uint8Array(signature); -} -async function verify(alg, key, signature, data) { - const cryptoKey = await getSigKey(alg, key, "verify"); - checkKeyLength(alg, cryptoKey); - const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm); - try { - return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); - } catch { - return false; - } -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/jwk_to_key.js -var unsupportedAlg = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value"; -function subtleMapping(jwk) { - let algorithm; - let keyUsages; - switch (jwk.kty) { - case "AKP": - switch (jwk.alg) { - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - algorithm = { name: jwk.alg }; - keyUsages = jwk.priv ? ["sign"] : ["verify"]; - break; - default: throw new JOSENotSupported(unsupportedAlg); - } - break; - case "RSA": - switch (jwk.alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm = { - name: "RSA-PSS", - hash: `SHA-${jwk.alg.slice(-3)}` - }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm = { - name: "RSASSA-PKCS1-v1_5", - hash: `SHA-${jwk.alg.slice(-3)}` - }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - algorithm = { - name: "RSA-OAEP", - hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` - }; - keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; - break; - default: throw new JOSENotSupported(unsupportedAlg); - } - break; - case "EC": - switch (jwk.alg) { - case "ES256": - case "ES384": - case "ES512": - algorithm = { - name: "ECDSA", - namedCurve: { - ES256: "P-256", - ES384: "P-384", - ES512: "P-521" - }[jwk.alg] - }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm = { - name: "ECDH", - namedCurve: jwk.crv - }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: throw new JOSENotSupported(unsupportedAlg); - } - break; - case "OKP": - switch (jwk.alg) { - case "Ed25519": - case "EdDSA": - algorithm = { name: "Ed25519" }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm = { name: jwk.crv }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: throw new JOSENotSupported(unsupportedAlg); - } - break; - default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value"); - } - return { - algorithm, - keyUsages - }; -} -async function jwkToKey(jwk) { - if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present"); - const { algorithm, keyUsages } = subtleMapping(jwk); - const keyData = { ...jwk }; - if (keyData.kty !== "AKP") delete keyData.alg; - delete keyData.use; - return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/normalize_key.js -var unusableForAlg = "given KeyObject instance cannot be used for this algorithm"; -var cache; -var handleJWK = async (key, jwk, alg, freeze = false) => { - cache ||= /* @__PURE__ */ new WeakMap(); - let cached = cache.get(key); - if (cached?.[alg]) return cached[alg]; - const cryptoKey = await jwkToKey({ - ...jwk, - alg - }); - if (freeze) Object.freeze(key); - if (!cached) cache.set(key, { [alg]: cryptoKey }); - else cached[alg] = cryptoKey; - return cryptoKey; -}; -var handleKeyObject = (keyObject, alg) => { - cache ||= /* @__PURE__ */ new WeakMap(); - let cached = cache.get(keyObject); - if (cached?.[alg]) return cached[alg]; - const isPublic = keyObject.type === "public"; - const extractable = isPublic ? true : false; - let cryptoKey; - if (keyObject.asymmetricKeyType === "x25519") { - switch (alg) { - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": break; - default: throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]); - } - if (keyObject.asymmetricKeyType === "ed25519") { - if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError(unusableForAlg); - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]); - } - switch (keyObject.asymmetricKeyType) { - case "ml-dsa-44": - case "ml-dsa-65": - case "ml-dsa-87": - if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError(unusableForAlg); - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]); - } - if (keyObject.asymmetricKeyType === "rsa") { - let hash; - switch (alg) { - case "RSA-OAEP": - hash = "SHA-1"; - break; - case "RS256": - case "PS256": - case "RSA-OAEP-256": - hash = "SHA-256"; - break; - case "RS384": - case "PS384": - case "RSA-OAEP-384": - hash = "SHA-384"; - break; - case "RS512": - case "PS512": - case "RSA-OAEP-512": - hash = "SHA-512"; - break; - default: throw new TypeError(unusableForAlg); - } - if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({ - name: "RSA-OAEP", - hash - }, extractable, isPublic ? ["encrypt"] : ["decrypt"]); - cryptoKey = keyObject.toCryptoKey({ - name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", - hash - }, extractable, [isPublic ? "verify" : "sign"]); - } - if (keyObject.asymmetricKeyType === "ec") { - const namedCurve = (/* @__PURE__ */ new Map([ - ["prime256v1", "P-256"], - ["secp384r1", "P-384"], - ["secp521r1", "P-521"] - ])).get(keyObject.asymmetricKeyDetails?.namedCurve); - if (!namedCurve) throw new TypeError(unusableForAlg); - const expectedCurve = { - ES256: "P-256", - ES384: "P-384", - ES512: "P-521" - }; - if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) cryptoKey = keyObject.toCryptoKey({ - name: "ECDSA", - namedCurve - }, extractable, [isPublic ? "verify" : "sign"]); - if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({ - name: "ECDH", - namedCurve - }, extractable, isPublic ? [] : ["deriveBits"]); - } - if (!cryptoKey) throw new TypeError(unusableForAlg); - if (!cached) cache.set(keyObject, { [alg]: cryptoKey }); - else cached[alg] = cryptoKey; - return cryptoKey; -}; -async function normalizeKey(key, alg) { - if (key instanceof Uint8Array) return key; - if (isCryptoKey(key)) return key; - if (isKeyObject(key)) { - if (key.type === "secret") return key.export(); - if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try { - return handleKeyObject(key, alg); - } catch (err) { - if (err instanceof TypeError) throw err; - } - return handleJWK(key, key.export({ format: "jwk" }), alg); - } - if (isJWK(key)) { - if (key.k) return decode$1(key.k); - return handleJWK(key, key, alg, true); - } - throw new Error("unreachable"); -} -//#endregion -//#region node_modules/jose/dist/webapi/key/import.js -async function importJWK(jwk, alg, options) { - if (!isObject$1(jwk)) throw new TypeError("JWK must be an object"); - let ext; - alg ??= jwk.alg; - ext ??= options?.extractable ?? jwk.ext; - switch (jwk.kty) { - case "oct": - if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value"); - return decode$1(jwk.k); - case "RSA": - if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported"); - return jwkToKey({ - ...jwk, - alg, - ext - }); - case "AKP": - if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value"); - if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch"); - return jwkToKey({ - ...jwk, - ext - }); - case "EC": - case "OKP": return jwkToKey({ - ...jwk, - alg, - ext - }); - default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value"); - } -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/validate_crit.js -function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { - if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected"); - if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set(); - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present"); - let recognized; - if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); - else recognized = recognizedDefault; - for (const parameter of protectedHeader.crit) { - if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); - if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`); - if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); - } - return new Set(protectedHeader.crit); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/validate_algorithms.js -function validateAlgorithms(option, algorithms) { - if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`); - if (!algorithms) return; - return new Set(algorithms); -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/check_key_type.js -var tag = (key) => key?.[Symbol.toStringTag]; -var jwkMatchesOp = (alg, key, usage) => { - if (key.use !== void 0) { - let expected; - switch (usage) { - case "sign": - case "verify": - expected = "sig"; - break; - case "encrypt": - case "decrypt": - expected = "enc"; - break; - } - if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); - } - if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`); - if (Array.isArray(key.key_ops)) { - let expectedKeyOp; - switch (true) { - case usage === "sign" || usage === "verify": - case alg === "dir": - case alg.includes("CBC-HS"): - expectedKeyOp = usage; - break; - case alg.startsWith("PBES2"): - expectedKeyOp = "deriveBits"; - break; - case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg): - if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; - else expectedKeyOp = usage; - break; - case usage === "encrypt" && alg.startsWith("RSA"): - expectedKeyOp = "wrapKey"; - break; - case usage === "decrypt": - expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits"; - break; - } - if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); - } - return true; -}; -var symmetricTypeCheck = (alg, key, usage) => { - if (key instanceof Uint8Array) return; - if (isJWK(key)) { - if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return; - throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); - } - if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array")); - if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); -}; -var asymmetricTypeCheck = (alg, key, usage) => { - if (isJWK(key)) switch (usage) { - case "decrypt": - case "sign": - if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return; - throw new TypeError(`JSON Web Key for this operation must be a private JWK`); - case "encrypt": - case "verify": - if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return; - throw new TypeError(`JSON Web Key for this operation must be a public JWK`); - } - if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key")); - if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - if (key.type === "public") switch (usage) { - case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - if (key.type === "private") switch (usage) { - case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } -}; -function checkKeyType(alg, key, usage) { - switch (alg.substring(0, 2)) { - case "A1": - case "A2": - case "di": - case "HS": - case "PB": - symmetricTypeCheck(alg, key, usage); - break; - default: asymmetricTypeCheck(alg, key, usage); - } -} -//#endregion -//#region node_modules/jose/dist/webapi/jws/flattened/verify.js -async function flattenedVerify(jws, key, options) { - if (!isObject$1(jws)) throw new JWSInvalid("Flattened JWS must be an object"); - if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members"); - if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type"); - if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing"); - if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type"); - if (jws.header !== void 0 && !isObject$1(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type"); - let parsedProt = {}; - if (jws.protected) try { - const protectedHeader = decode$1(jws.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } catch { - throw new JWSInvalid("JWS Protected Header is invalid"); - } - if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - const joseHeader = { - ...parsedProt, - ...jws.header - }; - const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = parsedProt.b64; - if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean"); - } - const { alg } = joseHeader; - if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid"); - const algorithms = options && validateAlgorithms("algorithms", options.algorithms); - if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed"); - if (b64) { - if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string"); - } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jws); - resolvedKey = true; - } - checkKeyType(alg, key, "verify"); - const data = concat(jws.protected !== void 0 ? encode$2(jws.protected) : /* @__PURE__ */ new Uint8Array(), encode$2("."), typeof jws.payload === "string" ? b64 ? encode$2(jws.payload) : encoder.encode(jws.payload) : jws.payload); - const signature = decodeBase64url(jws.signature, "signature", JWSInvalid); - const k = await normalizeKey(key, alg); - if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed(); - let payload; - if (b64) payload = decodeBase64url(jws.payload, "payload", JWSInvalid); - else if (typeof jws.payload === "string") payload = encoder.encode(jws.payload); - else payload = jws.payload; - const result = { payload }; - if (jws.protected !== void 0) result.protectedHeader = parsedProt; - if (jws.header !== void 0) result.unprotectedHeader = jws.header; - if (resolvedKey) return { - ...result, - key: k - }; - return result; -} -//#endregion -//#region node_modules/jose/dist/webapi/jws/compact/verify.js -async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) jws = decoder.decode(jws); - if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); - if (length !== 3) throw new JWSInvalid("Invalid Compact JWS"); - const verified = await flattenedVerify({ - payload, - protected: protectedHeader, - signature - }, key, options); - const result = { - payload: verified.payload, - protectedHeader: verified.protectedHeader - }; - if (typeof key === "function") return { - ...result, - key: verified.key - }; - return result; -} -//#endregion -//#region node_modules/jose/dist/webapi/lib/jwt_claims_set.js -var epoch = (date) => Math.floor(date.getTime() / 1e3); -var minute = 60; -var hour = minute * 60; -var day = hour * 24; -var week = day * 7; -var year = day * 365.25; -var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; -function secs(str) { - const matched = REGEX.exec(str); - if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format"); - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case "sec": - case "secs": - case "second": - case "seconds": - case "s": - numericDate = Math.round(value); - break; - case "minute": - case "minutes": - case "min": - case "mins": - case "m": - numericDate = Math.round(value * minute); - break; - case "hour": - case "hours": - case "hr": - case "hrs": - case "h": - numericDate = Math.round(value * hour); - break; - case "day": - case "days": - case "d": - numericDate = Math.round(value * day); - break; - case "week": - case "weeks": - case "w": - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; - } - if (matched[1] === "-" || matched[4] === "ago") return -numericDate; - return numericDate; -} -function validateInput(label, input) { - if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`); - return input; -} -var normalizeTyp = (value) => { - if (value.includes("/")) return value.toLowerCase(); - return `application/${value.toLowerCase()}`; -}; -var checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === "string") return audOption.includes(audPayload); - if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - return false; -}; -function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { - let payload; - try { - payload = JSON.parse(decoder.decode(encodedPayload)); - } catch {} - if (!isObject$1(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); - const { typ } = options; - if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed"); - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== void 0) presenceCheck.push("iat"); - if (audience !== void 0) presenceCheck.push("aud"); - if (subject !== void 0) presenceCheck.push("sub"); - if (issuer !== void 0) presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed"); - if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed"); - if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed"); - let tolerance; - switch (typeof options.clockTolerance) { - case "string": - tolerance = secs(options.clockTolerance); - break; - case "number": - tolerance = options.clockTolerance; - break; - case "undefined": - tolerance = 0; - break; - default: throw new TypeError("Invalid clockTolerance option type"); - } - const { currentDate } = options; - const now = epoch(currentDate || /* @__PURE__ */ new Date()); - if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid"); - if (payload.nbf !== void 0) { - if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid"); - if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed"); - } - if (payload.exp !== void 0) { - if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid"); - if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed"); - } - if (maxTokenAge) { - const age = now - payload.iat; - const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge); - if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed"); - if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed"); - } - return payload; -} -var JWTClaimsBuilder = class { - #payload; - constructor(payload) { - if (!isObject$1(payload)) throw new TypeError("JWT Claims Set MUST be an object"); - this.#payload = structuredClone(payload); - } - data() { - return encoder.encode(JSON.stringify(this.#payload)); - } - get iss() { - return this.#payload.iss; - } - set iss(value) { - this.#payload.iss = value; - } - get sub() { - return this.#payload.sub; - } - set sub(value) { - this.#payload.sub = value; - } - get aud() { - return this.#payload.aud; - } - set aud(value) { - this.#payload.aud = value; - } - set jti(value) { - this.#payload.jti = value; - } - set nbf(value) { - if (typeof value === "number") this.#payload.nbf = validateInput("setNotBefore", value); - else if (value instanceof Date) this.#payload.nbf = validateInput("setNotBefore", epoch(value)); - else this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - set exp(value) { - if (typeof value === "number") this.#payload.exp = validateInput("setExpirationTime", value); - else if (value instanceof Date) this.#payload.exp = validateInput("setExpirationTime", epoch(value)); - else this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - set iat(value) { - if (value === void 0) this.#payload.iat = epoch(/* @__PURE__ */ new Date()); - else if (value instanceof Date) this.#payload.iat = validateInput("setIssuedAt", epoch(value)); - else if (typeof value === "string") this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)); - else this.#payload.iat = validateInput("setIssuedAt", value); - } -}; -//#endregion -//#region node_modules/jose/dist/webapi/jwt/verify.js -async function jwtVerify(jwt, key, options) { - const verified = await compactVerify(jwt, key, options); - if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - const result = { - payload: validateClaimsSet(verified.protectedHeader, verified.payload, options), - protectedHeader: verified.protectedHeader - }; - if (typeof key === "function") return { - ...result, - key: verified.key - }; - return result; -} -//#endregion -//#region node_modules/jose/dist/webapi/jwks/local.js -function getKtyFromAlg(alg) { - switch (typeof alg === "string" && alg.slice(0, 2)) { - case "RS": - case "PS": return "RSA"; - case "ES": return "EC"; - case "Ed": return "OKP"; - case "ML": return "AKP"; - default: throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set"); - } -} -function isJWKSLike(jwks) { - return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); -} -function isJWKLike(key) { - return isObject$1(key); -} -var LocalJWKSet = class { - #jwks; - #cached = /* @__PURE__ */ new WeakMap(); - constructor(jwks) { - if (!isJWKSLike(jwks)) throw new JWKSInvalid("JSON Web Key Set malformed"); - this.#jwks = structuredClone(jwks); - } - jwks() { - return this.#jwks; - } - async getKey(protectedHeader, token) { - const { alg, kid } = { - ...protectedHeader, - ...token?.header - }; - const kty = getKtyFromAlg(alg); - const candidates = this.#jwks.keys.filter((jwk) => { - let candidate = kty === jwk.kty; - if (candidate && typeof kid === "string") candidate = kid === jwk.kid; - if (candidate && (typeof jwk.alg === "string" || kty === "AKP")) candidate = alg === jwk.alg; - if (candidate && typeof jwk.use === "string") candidate = jwk.use === "sig"; - if (candidate && Array.isArray(jwk.key_ops)) candidate = jwk.key_ops.includes("verify"); - if (candidate) switch (alg) { - case "ES256": - candidate = jwk.crv === "P-256"; - break; - case "ES384": - candidate = jwk.crv === "P-384"; - break; - case "ES512": - candidate = jwk.crv === "P-521"; - break; - case "Ed25519": - case "EdDSA": - candidate = jwk.crv === "Ed25519"; - break; - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) throw new JWKSNoMatchingKey(); - if (length !== 1) { - const error = new JWKSMultipleMatchingKeys(); - const _cached = this.#cached; - error[Symbol.asyncIterator] = async function* () { - for (const jwk of candidates) try { - yield await importWithAlgCache(_cached, jwk, alg); - } catch {} - }; - throw error; - } - return importWithAlgCache(this.#cached, jwk, alg); - } -}; -async function importWithAlgCache(cache, jwk, alg) { - const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); - if (cached[alg] === void 0) { - const key = await importJWK({ - ...jwk, - ext: true - }, alg); - if (key instanceof Uint8Array || key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); - cached[alg] = key; - } - return cached[alg]; -} -function createLocalJWKSet(jwks) { - const set = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { jwks: { - value: () => structuredClone(set.jwks()), - enumerable: false, - configurable: false, - writable: false - } }); - return localJWKSet; -} -//#endregion -//#region node_modules/jose/dist/webapi/jwks/remote.js -function isCloudflareWorkers() { - return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; -} -var USER_AGENT; -if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.2.4`; -var customFetch = Symbol(); -async function fetchJwks(url, headers, signal, fetchImpl = fetch) { - const response = await fetchImpl(url, { - method: "GET", - signal, - redirect: "manual", - headers - }).catch((err) => { - if (err.name === "TimeoutError") throw new JWKSTimeout(); - throw err; - }); - if (response.status !== 200) throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); - try { - return await response.json(); - } catch { - throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); - } -} -var jwksCache = Symbol(); -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== "object" || input === null) return false; - if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) return false; - if (!("jwks" in input) || !isObject$1(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject$1)) return false; - return true; -} -var RemoteJWKSet = class { - #url; - #timeoutDuration; - #cooldownDuration; - #cacheMaxAge; - #jwksTimestamp; - #pendingFetch; - #headers; - #customFetch; - #local; - #cache; - constructor(url, options) { - if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL"); - this.#url = new URL(url.href); - this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3; - this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4; - this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5; - this.#headers = new Headers(options?.headers); - if (USER_AGENT && !this.#headers.has("User-Agent")) this.#headers.set("User-Agent", USER_AGENT); - if (!this.#headers.has("accept")) { - this.#headers.set("accept", "application/json"); - this.#headers.append("accept", "application/jwk-set+json"); - } - this.#customFetch = options?.[customFetch]; - if (options?.[jwksCache] !== void 0) { - this.#cache = options?.[jwksCache]; - if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) { - this.#jwksTimestamp = this.#cache.uat; - this.#local = createLocalJWKSet(this.#cache.jwks); - } - } - } - pendingFetch() { - return !!this.#pendingFetch; - } - coolingDown() { - return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false; - } - fresh() { - return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false; - } - jwks() { - return this.#local?.jwks(); - } - async getKey(protectedHeader, token) { - if (!this.#local || !this.fresh()) await this.reload(); - try { - return await this.#local(protectedHeader, token); - } catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this.#local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this.#pendingFetch && isCloudflareWorkers()) this.#pendingFetch = void 0; - this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => { - this.#local = createLocalJWKSet(json); - if (this.#cache) { - this.#cache.uat = Date.now(); - this.#cache.jwks = json; - } - this.#jwksTimestamp = Date.now(); - this.#pendingFetch = void 0; - }).catch((err) => { - this.#pendingFetch = void 0; - throw err; - }); - await this.#pendingFetch; - } -}; -function createRemoteJWKSet(url, options) { - const set = new RemoteJWKSet(url, options); - const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set.coolingDown(), - enumerable: true, - configurable: false - }, - fresh: { - get: () => set.fresh(), - enumerable: true, - configurable: false - }, - reload: { - value: () => set.reload(), - enumerable: true, - configurable: false, - writable: false - }, - reloading: { - get: () => set.pendingFetch(), - enumerable: true, - configurable: false - }, - jwks: { - value: () => set.jwks(), - enumerable: true, - configurable: false, - writable: false - } - }); - return remoteJWKSet; -} -//#endregion -//#region node_modules/jose/dist/webapi/util/decode_protected_header.js -function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === "string") { - const parts = token.split("."); - if (parts.length === 3 || parts.length === 5) [protectedB64u] = parts; - } else if (typeof token === "object" && token) if ("protected" in token) protectedB64u = token.protected; - else throw new TypeError("Token does not contain a Protected Header"); - try { - if (typeof protectedB64u !== "string" || !protectedB64u) throw new Error(); - const result = JSON.parse(decoder.decode(decode$1(protectedB64u))); - if (!isObject$1(result)) throw new Error(); - return result; - } catch { - throw new TypeError("Invalid Token or Protected Header formatting"); - } -} -//#endregion -//#region node_modules/jose/dist/webapi/util/decode_jwt.js -function decodeJwt(jwt) { - if (typeof jwt !== "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); - const { 1: payload, length } = jwt.split("."); - if (length === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); - if (length !== 3) throw new JWTInvalid("Invalid JWT"); - if (!payload) throw new JWTInvalid("JWTs must contain a payload"); - let decoded; - try { - decoded = decode$1(payload); - } catch { - throw new JWTInvalid("Failed to base64url decode the payload"); - } - let result; - try { - result = JSON.parse(decoder.decode(decoded)); - } catch { - throw new JWTInvalid("Failed to parse the decoded payload as JSON"); - } - if (!isObject$1(result)) throw new JWTInvalid("Invalid JWT Claims Set"); - return result; -} -//#endregion -//#region node_modules/@better-auth/utils/dist/index.mjs -function getWebcryptoSubtle() { - const cr = typeof globalThis !== "undefined" && globalThis.crypto; - if (cr && typeof cr.subtle === "object" && cr.subtle != null) return cr.subtle; - throw new Error("crypto.subtle must be defined"); +//#region node_modules/zod/v4/core/regexes.js +/** +* @deprecated CUID v1 is deprecated by its authors due to information leakage +* (timestamps embedded in the id). Use {@link cuid2} instead. +* See https://github.com/paralleldrive/cuid. +*/ +var cuid = /^[cC][0-9a-z]{6,}$/; +var cuid2 = /^[0-9a-z]+$/; +var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var xid = /^[0-9a-vA-V]{20}$/; +var ksuid = /^[A-Za-z0-9]{27}$/; +var nanoid = /^[a-zA-Z0-9_-]{21}$/; +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +var duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. +* +* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +var uuid = (version) => { + if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +/** Practical email validation */ +var email$1 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +function emoji() { + return new RegExp(_emoji$1, "u"); } -//#endregion -//#region node_modules/@better-auth/utils/dist/base64.mjs -function getAlphabet(urlSafe) { - return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var ipv4$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +var ipv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; +var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64$1 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +var base64url = /^[A-Za-z0-9_-]*$/; +var httpProtocol = /^https?$/; +var e164 = /^\+[1-9]\d{6,14}$/; +var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; +var date$1 = /*@__PURE__*/ new RegExp(`^${dateSource}$`); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; } -function base64Encode(data, alphabet, padding) { - let result = ""; - let buffer = 0; - let shift = 0; - for (const byte of data) { - buffer = buffer << 8 | byte; - shift += 8; - while (shift >= 6) { - shift -= 6; - result += alphabet[buffer >> shift & 63]; - } - } - if (shift > 0) result += alphabet[buffer << 6 - shift & 63]; - if (padding) { - const padCount = (4 - result.length % 4) % 4; - result += "=".repeat(padCount); - } - return result; +function time$1(args) { + return new RegExp(`^${timeSource(args)}$`); } -function base64Decode(data, alphabet) { - const decodeMap = /* @__PURE__ */ new Map(); - for (let i = 0; i < alphabet.length; i++) decodeMap.set(alphabet[i], i); - const result = []; - let buffer = 0; - let bitsCollected = 0; - for (const char of data) { - if (char === "=") break; - const value = decodeMap.get(char); - if (value === void 0) throw new Error(`Invalid Base64 character: ${char}`); - buffer = buffer << 6 | value; - bitsCollected += 6; - if (bitsCollected >= 8) { - bitsCollected -= 8; - result.push(buffer >> bitsCollected & 255); - } - } - return Uint8Array.from(result); +function datetime$1(args) { + const time = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) opts.push(""); + if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + const timeRegex = `${time}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } -var base64$1 = { - encode(data, options = {}) { - const alphabet = getAlphabet(false); - return base64Encode(typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data), alphabet, options.padding ?? true); - }, - decode(data) { - if (typeof data !== "string") data = new TextDecoder().decode(data); - const alphabet = getAlphabet(data.includes("-") || data.includes("_")); - return base64Decode(data, alphabet); - } -}; -var base64Url = { - encode(data, options = {}) { - const alphabet = getAlphabet(true); - return base64Encode(typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data), alphabet, options.padding ?? true); - }, - decode(data) { - return base64Decode(data, getAlphabet(data.includes("-") || data.includes("_"))); - } +var string$1 = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); }; +var integer = /^-?\d+$/; +var number$1 = /^-?\d+(?:\.\d+)?$/; +var boolean$1 = /^(?:true|false)$/i; +var _null$2 = /^null$/i; +var lowercase = /^[^A-Z]*$/; +var uppercase = /^[^a-z]*$/; //#endregion -//#region node_modules/zod/v4/core/core.js -var _a$1; -function $constructor(name, initializer, params) { - function init(inst, def) { - if (!inst._zod) Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() +//#region node_modules/zod/v4/core/checks.js +var $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +var numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" +}; +var $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) if (def.inclusive) bag.maximum = def.value; + else bag.exclusiveMaximum = def.value; + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return; + payload.issues.push({ + origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) if (def.inclusive) bag.minimum = def.value; + else bag.exclusiveMinimum = def.value; + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return; + payload.issues.push({ + origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMultipleOf = /*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); + if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort + }); + else payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort + }); + return; + } + } + if (input < minimum) payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + if (input > maximum) payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst) => { + const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input.length <= def.maximum) return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst) => { + const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input.length >= def.minimum) return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...tooBig ? { + code: "too_big", + maximum: def.length + } : { + code: "too_small", + minimum: def.length }, - enumerable: false + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort }); - if (inst._zod.traits.has(name)) return; - inst._zod.traits.add(name); - initializer(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) inst[k] = proto[k].bind(inst); - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent {} - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a = inst._zod).deferred ?? (_a.deferred = []); - for (const fn of inst._zod.deferred) fn(); - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) return true; - return inst?._zod?.traits?.has(name); - } }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -}; -(_a$1 = globalThis).__zod_globalConfig ?? (_a$1.__zod_globalConfig = {}); -var globalConfig = globalThis.__zod_globalConfig; -function config(newConfig) { - if (newConfig) Object.assign(globalConfig, newConfig); - return globalConfig; -} -//#endregion -//#region node_modules/zod/v4/core/util.js -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") return value.toString(); - return value; -} -function cached(getter) { - return { get value() { - { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; + }; +}); +var $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(def.pattern); } - throw new Error("cached value already set"); - } }; -} -function nullish(input) { - return input === null || input === void 0; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const ratio = val / step; - const roundedRatio = Math.round(ratio); - const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); - if (Math.abs(ratio - roundedRatio) < tolerance) return 0; - return ratio - roundedRatio; -} -var EVALUATING = /* @__PURE__*/ Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = void 0; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) return; - if (value === void 0) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { value: v }); - }, - configurable: true }); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true + if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...def.pattern ? { pattern: def.pattern.toString() } : {}, + inst, + continue: !def.abort + }); + }); + else (_b = inst._zod).check ?? (_b.check = () => {}); +}); +var $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +var $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +var $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); +//#endregion +//#region node_modules/zod/v4/core/doc.js +var Doc = class { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) this.args = args; } - return Object.defineProperties({}, mergedDescriptors); -} -function esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); -} -var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {}; -function isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -var allowsEval = /* @__PURE__*/ cached(() => { - if (globalConfig.jitless) return false; - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false; - try { - new Function(""); - return true; - } catch (_) { - return false; + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; } -}); -function isPlainObject(o) { - if (isObject(o) === false) return false; - const ctor = o.constructor; - if (ctor === void 0) return true; - if (typeof ctor !== "function") return true; - const prot = ctor.prototype; - if (isObject(prot) === false) return false; - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false; - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) return { ...o }; - if (Array.isArray(o)) return [...o]; - if (o instanceof Map) return new Map(o); - if (o instanceof Set) return new Set(o); - return o; -} -var propertyKeyTypes = /* @__PURE__*/ new Set([ - "string", - "number", - "symbol" -]); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) return {}; - if (typeof params === "string") return { error: () => params }; - if (params?.message !== void 0) { - if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const lines = arg.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) this.content.push(line); + } + compile() { + const F = Function; + const args = this?.args; + const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)]; + return new F(...args, lines.join("\n")); } - delete params.message; - if (typeof params.error === "string") return { - ...params, - error: () => params.error - }; - return params; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; - }); -} -var NUMBER_FORMAT_RANGES = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-34028234663852886e22, 34028234663852886e22], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; -function pick(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements"); - return clone(schema, mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`); - if (!mask[key]) continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - })); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements"); - return clone(schema, mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`); - if (!mask[key]) continue; - delete newShape[key]; +//#endregion +//#region node_modules/zod/v4/core/versions.js +var version = { + major: 4, + minor: 4, + patch: 3 +}; +//#endregion +//#region node_modules/zod/v4/core/schemas.js +var $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version; + const checks = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst); + for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst); + if (checks.length === 0) { + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks, ctx) => { + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) continue; + if (!ch._zod.def.when(payload)) continue; + } else if (isAborted) continue; + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError(); + if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + if (payload.issues.length === currLen) return; + if (!isAborted) isAborted = aborted(payload, currLen); + }); + else { + if (payload.issues.length === currLen) continue; + if (!isAborted) isAborted = aborted(payload, currLen); + } } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - })); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object"); - const checks = schema._zod.def.checks; - if (checks && checks.length > 0) { - const existingShape = schema._zod.def.shape; - for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - return clone(schema, mergeDefs(schema._zod.def, { get shape() { - const _shape = { - ...schema._zod.def.shape, - ...shape + if (asyncResult) return asyncResult.then(() => { + return payload; + }); + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) throw new $ZodAsyncError(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); }; - assignProp(this, "shape", _shape); - return _shape; - } })); -} -function safeExtend(schema, shape) { - if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object"); - return clone(schema, mergeDefs(schema._zod.def, { get shape() { - const _shape = { - ...schema._zod.def.shape, - ...shape + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) return inst._zod.parse(payload, ctx); + if (ctx.direction === "backward") { + const canary = inst._zod.parse({ + value: payload.value, + issues: [] + }, { + ...ctx, + skipChecks: true + }); + if (canary instanceof Promise) return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + return handleCanaryResult(canary, payload, ctx); + } + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); }; - assignProp(this, "shape", _shape); - return _shape; - } })); -} -function merge(a, b) { - if (a._zod.def.checks?.length) throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); - return clone(a, mergeDefs(a._zod.def, { - get shape() { - const _shape = { - ...a._zod.def.shape, - ...b._zod.def.shape - }; - assignProp(this, "shape", _shape); - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: b._zod.def.checks ?? [] - })); -} -function partial(Class, schema, mask) { - const checks = schema._zod.def.checks; - if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements"); - return clone(schema, mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) for (const key in mask) { - if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`); - if (!mask[key]) continue; - shape[key] = Class ? new Class({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; + } + defineLazy(inst, "~standard", () => ({ + validate: (value) => { + try { + const r = safeParse$1(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_) { + return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } - else for (const key in oldShape) shape[key] = Class ? new Class({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - assignProp(this, "shape", shape); - return shape; }, - checks: [] + vendor: "zod", + version: 1 })); -} -function required(Class, schema, mask) { - return clone(schema, mergeDefs(schema._zod.def, { get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) for (const key in mask) { - if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`); - if (!mask[key]) continue; - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - else for (const key in oldShape) shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key] +}); +var $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) try { + payload.value = String(payload.value); + } catch (_) {} + if (typeof payload.value === "string") return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst }); - assignProp(this, "shape", shape); - return shape; - } })); -} -function aborted(x, startIndex = 0) { - if (x.aborted === true) return true; - for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true; - return false; -} -function explicitlyAborted(x, startIndex = 0) { - if (x.aborted === true) return true; - for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true; - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -function finalizeIssue(iss, ctx, config) { - const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input"; - const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message; - if (ctx?.reportInput) rest.input = _input; - return rest; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) return "array"; - if (typeof input === "string") return "string"; - return "unknown"; -} -function issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") return { - message: iss, - code: "custom", - input, - inst - }; - return { ...iss }; -} -//#endregion -//#region node_modules/zod/v4/core/errors.js -var initializer$1 = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false - }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false - }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false - }); -}; -var $ZodError = $constructor("$ZodError", initializer$1); -var $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error }); -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.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 + return payload; }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error, path = []) => { - for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - else if (issue.code === "invalid_key") processError({ issues: issue.issues }, [...path, ...issue.path]); - else if (issue.code === "invalid_element") processError({ issues: issue.issues }, [...path, ...issue.path]); - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) fieldErrors._errors.push(mapper(issue)); - else { - let curr = fieldErrors; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - if (!(i === fullpath.length - 1)) curr[el] = curr[el] || { _errors: [] }; - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; +}); +var $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +var $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +var $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const v = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }[def.version]; + if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } else def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +var $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email$1); + $ZodStringFormat.init(inst, def); +}); +var $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const trimmed = payload.value.trim(); + if (!def.normalize && def.protocol?.source === httpProtocol.source) { + if (!/^https?:\/\//i.test(trimmed)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort + }); + return; } } + const url = new URL(trimmed); + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url.hostname)) payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.normalize) payload.value = url.href; + else payload.value = trimmed; + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); } }; - processError(error); - return fieldErrors; -} -//#endregion -//#region node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? { - ..._ctx, - async: false - } : { async: false }; - const result = schema._zod.run({ - value, - issues: [] - }, ctx); - if (result instanceof Promise) throw new $ZodAsyncError(); - if (result.issues.length) { - const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; -}; -var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? { - ..._ctx, - async: true - } : { async: true }; - let result = schema._zod.run({ - value, - issues: [] - }, ctx); - if (result instanceof Promise) result = await result; - if (result.issues.length) { - const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; -}; -var _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - async: false - } : { async: false }; - const result = schema._zod.run({ - value, - issues: [] - }, ctx); - if (result instanceof Promise) throw new $ZodAsyncError(); - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { - success: true, - data: result.value - }; -}; -var safeParse$1 = /* @__PURE__*/ _safeParse($ZodRealError); -var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - async: true - } : { async: true }; - let result = schema._zod.run({ - value, - issues: [] - }, ctx); - if (result instanceof Promise) result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { - success: true, - data: result.value - }; -}; -var safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError); -var _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - direction: "backward" - } : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); -}; -var _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); -}; -var _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - direction: "backward" - } : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); -}; -var _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); -}; -var _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - direction: "backward" - } : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -var _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { - ..._ctx, - direction: "backward" - } : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -//#endregion -//#region node_modules/zod/v4/core/regexes.js +}); +var $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +var $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); +}); /** * @deprecated CUID v1 is deprecated by its authors due to information leakage -* (timestamps embedded in the id). Use {@link cuid2} instead. +* (timestamps embedded in the id). Use {@link $ZodCUID2} instead. * See https://github.com/paralleldrive/cuid. */ -var cuid = /^[cC][0-9a-z]{6,}$/; -var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; -var xid = /^[0-9a-vA-V]{20}$/; -var ksuid = /^[A-Za-z0-9]{27}$/; -var nanoid = /^[a-zA-Z0-9_-]{21}$/; -/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ -var duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ -var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; -/** Returns a regex for validating an RFC 9562/4122 UUID. -* -* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ -var uuid = (version) => { - if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -/** Practical email validation */ -var email$1 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -var _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -function emoji() { - return new RegExp(_emoji$1, "u"); -} -var ipv4$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -var ipv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; -var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; -var httpProtocol = /^https?$/; -var e164 = /^\+[1-9]\d{6,14}$/; -var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -var date$1 = /*@__PURE__*/ new RegExp(`^${dateSource}$`); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; -} -function time$1(args) { - return new RegExp(`^${timeSource(args)}$`); -} -function datetime$1(args) { - const time = timeSource({ precision: args.precision }); - const opts = ["Z"]; - if (args.local) opts.push(""); - if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -var string$1 = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -var integer = /^-?\d+$/; -var number$1 = /^-?\d+(?:\.\d+)?$/; -var boolean$1 = /^(?:true|false)$/i; -var lowercase = /^[^A-Z]*$/; -var uppercase = /^[^a-z]*$/; -//#endregion -//#region node_modules/zod/v4/core/checks.js -var $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); +var $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +var $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +var $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +var $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +var $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); }); -var numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date" -}; -var $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) if (def.inclusive) bag.maximum = def.value; - else bag.exclusiveMaximum = def.value; - }); +var $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime$1(def)); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date$1); + $ZodStringFormat.init(inst, def); +}); +var $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time$1(def)); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration$1); + $ZodStringFormat.init(inst, def); +}); +var $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4$1); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; +}); +var $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv6$1); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return; + try { + new URL(`http://[${payload.value}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +var $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +var $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + const parts = payload.value.split("/"); + try { + if (parts.length !== 2) throw new Error(); + const [address, prefix] = parts; + if (!prefix) throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) throw new Error(); + if (prefixNum < 0 || prefixNum > 128) throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +function isValidBase64(data) { + if (data === "") return true; + if (/\s/.test(data)) return false; + if (data.length % 4 !== 0) return false; + try { + atob(data); + return true; + } catch { + return false; + } +} +var $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64$1); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) return; payload.issues.push({ - origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + code: "invalid_format", + format: "base64", input: payload.value, - inclusive: def.inclusive, inst, continue: !def.abort }); }; }); -var $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) if (def.inclusive) bag.minimum = def.value; - else bag.exclusiveMinimum = def.value; - }); +function isValidBase64URL(data) { + if (!base64url.test(data)) return false; + const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")); +} +var $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return; + if (isValidBase64URL(payload.value)) return; payload.issues.push({ - origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + code: "invalid_format", + format: "base64url", input: payload.value, - inclusive: def.inclusive, inst, continue: !def.abort }); }; }); -var $ZodCheckMultipleOf = /*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); +var $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) return false; + const [header] = tokensParts; + if (!header) return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; + if (!parsedHeader.alg) return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; + return true; + } catch { + return false; + } +} +var $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); - if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return; + if (isValidJWT(payload.value, def.alg)) return; payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, + code: "invalid_format", + format: "jwt", input: payload.value, inst, continue: !def.abort }); }; }); -var $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) bag.pattern = integer; - }); - inst._zod.check = (payload) => { +var $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number$1; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) try { + payload.value = Number(payload.value); + } catch (_) {} const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst - }); - return; - } - if (!Number.isSafeInteger(input)) { - if (input > 0) payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort - }); - else payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort - }); - return; - } - } - if (input < minimum) payload.issues.push({ - origin: "number", + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload; + const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + payload.issues.push({ + expected: "number", + code: "invalid_type", input, - code: "too_small", - minimum, - inclusive: true, inst, - continue: !def.abort + ...received ? { received } : {} }); - if (input > maximum) payload.issues.push({ - origin: "number", + return payload; + }; +}); +var $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); +}); +var $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = boolean$1; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) try { + payload.value = Boolean(payload.value); + } catch (_) {} + const input = payload.value; + if (typeof input === "boolean") return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort + inst }); + return payload; }; }); -var $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst) => { - const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { +var $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null$2; + inst._zod.values = /* @__PURE__ */ new Set([null]); + inst._zod.parse = (payload, _ctx) => { const input = payload.value; - if (input.length <= def.maximum) return; - const origin = getLengthableOrigin(input); + if (input === null) return payload; payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, + expected: "null", + code: "invalid_type", input, - inst, - continue: !def.abort + inst + }); + return payload; + }; +}); +var $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +var $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +var $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +function handleArrayResult(result, final, index) { + if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues)); + final.value[index] = result.value; +} +var $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i))); + else handleArrayResult(result, payload, i); + } + if (proms.length) return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { + const isPresent = key in input; + if (result.issues.length) { + if (isOptionalIn && isOptionalOut && !isPresent) return; + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && !isOptionalIn) { + if (!result.issues.length) final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: void 0, + path: [key] }); + return; + } + if (result.value === void 0) { + if (isPresent) final.value[key] = void 0; + } else final.value[key] = result.value; +} +function normalizeDef(def) { + const keys = Object.keys(def.shape); + for (const k of keys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + const okeys = optionalKeys(def.shape); + return { + ...def, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const isOptionalIn = _catchall.optin === "optional"; + const isOptionalOut = _catchall.optout === "optional"; + for (const key in input) { + if (key === "__proto__") continue; + if (keySet.has(key)) continue; + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ + value: input[key], + issues: [] + }, ctx); + if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut))); + else handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + } + if (unrecognized.length) payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + if (!proms.length) return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +var $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { + $ZodType.init(inst, def); + if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) { + const sh = def.shape; + Object.defineProperty(def, "shape", { get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + return newSh; + } }); + } + const _normalized = cached(() => normalizeDef(def)); + defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + for (const v of field.values) propValues[key].add(v); + } + } + return propValues; + }); + const isObject = isObject$1; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = {}; + const proms = []; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const isOptionalIn = el._zod.optin === "optional"; + const isOptionalOut = el._zod.optout === "optional"; + const r = el._zod.run({ + value: input[key], + issues: [] + }, ctx); + if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut))); + else handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + } + if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload; + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +var $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = cached(() => normalizeDef(def)); + const generateFastpass = (shape) => { + const doc = new Doc([ + "shape", + "payload", + "ctx" + ]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k = esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.keys) ids[key] = `key_${counter++}`; + doc.write(`const newResult = {};`); + for (const key of normalized.keys) { + const id = ids[key]; + const k = esc(key); + const schema = shape[key]; + const isOptionalIn = schema?._zod?.optin === "optional"; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(key)};`); + if (isOptionalIn && isOptionalOut) doc.write(` + if (${id}.issues.length) { + if (${k} in input) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + else if (!isOptionalIn) doc.write(` + const ${id}_present = ${k} in input; + if (${id}.issues.length) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + } + + if (${id}_present) { + if (${id}.value === undefined) { + newResult[${k}] = undefined; + } else { + newResult[${k}] = ${id}.value; + } + } + + `); + else doc.write(` + if (${id}.issues.length) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); }; -}); -var $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst) => { - const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { + let fastpass; + const isObject = isObject$1; + const jit = !globalConfig.jitless; + const fastEnabled = jit && allowsEval.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); const input = payload.value; - if (input.length >= def.minimum) return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort - }); + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); }; }); -var $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) if (result.issues.length === 0) { + final.value = result.value; + return final; + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; + return final; +} +var $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length === def.length) return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...tooBig ? { - code: "too_big", - maximum: def.length - } : { - code: "too_small", - minimum: def.length - }, - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); + defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); } }); - if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...def.pattern ? { pattern: def.pattern.toString() } : {}, - inst, - continue: !def.abort - }); - }); - else (_b = inst._zod).check ?? (_b.check = () => {}); -}); -var $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) return first(payload, ctx); + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) return result; + results.push(result); + } + } + if (!async) return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); }); }; }); -var $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -var $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -var $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); +var $ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set(); + for (const val of v) propValues[k].add(val); + } + } + return propValues; }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); + const disc = cached(() => { + const opts = def.options; + const map = /* @__PURE__ */ new Map(); + for (const o of opts) { + const values = o._zod.propValues?.[def.discriminator]; + if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) throw new Error(`Duplicate discriminator value "${String(v)}"`); + map.set(v, o); + } + } + return map; }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) return; + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isObject$1(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) return opt._zod.run(payload, ctx); + if (def.unionFallback || ctx.direction === "backward") return _super(payload, ctx); payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + options: Array.from(disc.value.keys()), + input, + path: [def.discriminator], + inst }); + return payload; }; }); -var $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort +var $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ + value: input, + issues: [] + }, ctx); + const right = def.right._zod.run({ + value: input, + issues: [] + }, ctx); + if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); }); + return handleIntersectionResults(payload, left, right); }; }); -var $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); +function mergeValues(a, b) { + if (a === b) return { + valid: true, + data: a }; -}); -//#endregion -//#region node_modules/zod/v4/core/doc.js -var Doc = class { - constructor(args = []) { - this.content = []; - this.indent = 0; - if (this) this.args = args; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; + if (a instanceof Date && b instanceof Date && +a === +b) return { + valid: true, + data: a + }; + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { + ...a, + ...b + }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] + }; + newObj[key] = sharedValue.data; + } + return { + valid: true, + data: newObj + }; } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) return { + valid: false, + mergeErrorPath: [] + }; + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath] + }; + newArray.push(sharedValue.data); } - const lines = arg.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) this.content.push(line); + return { + valid: true, + data: newArray + }; } - compile() { - const F = Function; - const args = this?.args; - const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); + return { + valid: false, + mergeErrorPath: [] + }; +} +function handleIntersectionResults(result, left, right) { + const unrecKeys = /* @__PURE__ */ new Map(); + let unrecIssue; + for (const iss of left.issues) if (iss.code === "unrecognized_keys") { + unrecIssue ?? (unrecIssue = iss); + for (const k of iss.keys) { + if (!unrecKeys.has(k)) unrecKeys.set(k, {}); + unrecKeys.get(k).l = true; + } + } else result.issues.push(iss); + for (const iss of right.issues) if (iss.code === "unrecognized_keys") for (const k of iss.keys) { + if (!unrecKeys.has(k)) unrecKeys.set(k, {}); + unrecKeys.get(k).r = true; } -}; -//#endregion -//#region node_modules/zod/v4/core/versions.js -var version = { - major: 4, - minor: 4, - patch: 3 -}; -//#endregion -//#region node_modules/zod/v4/core/schemas.js -var $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; - inst._zod.bag = inst._zod.bag || {}; - inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst); - for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst); - if (checks.length === 0) { - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } else { - const runChecks = (payload, checks, ctx) => { - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - if (explicitlyAborted(payload)) continue; - if (!ch._zod.def.when(payload)) continue; - } else if (isAborted) continue; - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError(); - if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - if (payload.issues.length === currLen) return; - if (!isAborted) isAborted = aborted(payload, currLen); - }); - else { - if (payload.issues.length === currLen) continue; - if (!isAborted) isAborted = aborted(payload, currLen); - } - } - if (asyncResult) return asyncResult.then(() => { - return payload; + else result.issues.push(iss); + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length && unrecIssue) result.issues.push({ + ...unrecIssue, + keys: bothKeys + }); + if (aborted(result)) return result; + const merged = mergeValues(left.value, right.value); + if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + result.value = merged.data; + return result; +} +var $ZodTuple = /*@__PURE__*/ $constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type" }); return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) return inst._zod.parse(payload, ctx); - if (ctx.direction === "backward") { - const canary = inst._zod.parse({ - value: payload.value, - issues: [] - }, { - ...ctx, - skipChecks: true - }); - if (canary instanceof Promise) return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); + } + payload.value = []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array" }); - return handleCanaryResult(canary, payload, ctx); + return payload; + } + if (input.length > items.length) payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array" + }); + } + const itemResults = new Array(items.length); + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ + value: input[i], + issues: [] + }, ctx); + if (r instanceof Promise) proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + else itemResults[i] = r; + } + if (def.rest) { + let i = items.length - 1; + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ + value: el, + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((r) => handleTupleResult(r, payload, i))); + else handleTupleResult(result, payload, i); } - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); + } + if (proms.length) return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) if (items[i]._zod[key] !== "optional") return i + 1; + return 0; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues)); + final.value[index] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; } - return runChecks(result, checks, ctx); - }; + final.issues.push(...prefixIssues(i, r.issues)); + } + final.value[i] = r.value; } - defineLazy(inst, "~standard", () => ({ - validate: (value) => { - try { - const r = safeParse$1(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; - } catch (_) { - return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); - } - }, - vendor: "zod", - version: 1 - })); -}); -var $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + for (let i = final.value.length - 1; i >= input.length; i--) if (items[i]._zod.optout === "optional" && final.value[i] === void 0) final.value.length = i; + else break; + return final; +} +var $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) try { - payload.value = String(payload.value); - } catch (_) {} - if (typeof payload.value === "string") return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; -}); -var $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -var $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -var $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const v = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8 - }[def.version]; - if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } else def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -var $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email$1); - $ZodStringFormat.init(inst, def); -}); -var $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - const trimmed = payload.value.trim(); - if (!def.normalize && def.protocol?.source === httpProtocol.source) { - if (!/^https?:\/\//i.test(trimmed)) { + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values) { + payload.value = {}; + const recordKeys = /* @__PURE__ */ new Set(); + for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + const keyResult = def.keyType._zod.run({ + value: key, + issues: [] + }, ctx); + if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); + if (keyResult.issues.length) { payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst }); - return; + continue; + } + const outKey = keyResult.value; + const result = def.valueType._zod.run({ + value: input[key], + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result) => { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[outKey] = result.value; + })); + else { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[outKey] = result.value; } } - const url = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url.hostname)) payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); + let unrecognized; + for (const key in input) if (!recordKeys.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } - if (def.normalize) payload.value = url.href; - else payload.value = trimmed; - return; - } catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, + if (unrecognized && unrecognized.length > 0) payload.issues.push({ + code: "unrecognized_keys", + input, inst, - continue: !def.abort + keys: unrecognized }); + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue; + let keyResult = def.keyType._zod.run({ + value: key, + issues: [] + }, ctx); + if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); + if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) { + const retryResult = def.keyType._zod.run({ + value: Number(key), + issues: [] + }, ctx); + if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); + if (retryResult.issues.length === 0) keyResult = retryResult; + } + if (keyResult.issues.length) { + if (def.mode === "loose") payload.value[key] = input[key]; + else payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + continue; + } + const result = def.valueType._zod.run({ + value: input[key], + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result) => { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[keyResult.value] = result.value; + })); + else { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[keyResult.value] = result.value; + } + } } + if (proms.length) return Promise.all(proms).then(() => payload); + return payload; }; }); -var $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -var $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); - $ZodStringFormat.init(inst, def); -}); -/** -* @deprecated CUID v1 is deprecated by its authors due to information leakage -* (timestamps embedded in the id). Use {@link $ZodCUID2} instead. -* See https://github.com/paralleldrive/cuid. -*/ -var $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -var $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); +var $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) return payload; + payload.issues.push({ + code: "invalid_value", + values, + input, + inst + }); + return payload; + }; }); -var $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); +var $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + if (def.values.length === 0) throw new Error("Cannot create literal schema with no valid values"); + const values = new Set(def.values); + inst._zod.values = values; + inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) return payload; + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst + }); + return payload; + }; }); -var $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); +var $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name); + const _out = def.transform(payload.value, payload); + if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => { + payload.value = output; + payload.fallback = true; + return payload; + }); + if (_out instanceof Promise) throw new $ZodAsyncError(); + payload.value = _out; + payload.fallback = true; + return payload; + }; }); -var $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); +function handleOptionalResult(result, input) { + if (input === void 0 && (result.issues.length || result.fallback)) return { + issues: [], + value: void 0 + }; + return result; +} +var $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + const input = payload.value; + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, input)); + return handleOptionalResult(result, input); + } + if (payload.value === void 0) return payload; + return def.innerType._zod.run(payload, ctx); + }; }); -var $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime$1(def)); - $ZodStringFormat.init(inst, def); +var $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { + $ZodOptional.init(inst, def); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; }); -var $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = date$1); - $ZodStringFormat.init(inst, def); +var $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) return payload; + return def.innerType._zod.run(payload, ctx); + }; }); -var $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = time$1(def)); - $ZodStringFormat.init(inst, def); +var $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); + if (payload.value === void 0) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def)); + return handleDefaultResult(result, def); + }; }); -var $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration$1); - $ZodStringFormat.init(inst, def); +function handleDefaultResult(payload, def) { + if (payload.value === void 0) payload.value = def.defaultValue; + return payload; +} +var $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); + if (payload.value === void 0) payload.value = def.defaultValue; + return def.innerType._zod.run(payload, ctx); + }; }); -var $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4$1); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; +var $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst)); + return handleNonOptionalResult(result, inst); + }; }); -var $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = ipv6$1); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === void 0) payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); + return payload; +} +var $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((result) => { + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, + input: payload.value + }); + payload.issues = []; + payload.fallback = true; + } + return payload; + }); + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, + input: payload.value }); + payload.issues = []; + payload.fallback = true; } + return payload; }; }); -var $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); +var $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx)); + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx)); + return handlePipeResult(left, def.out, ctx); + }; }); -var $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); - $ZodStringFormat.init(inst, def); +function handlePipeResult(left, next, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return next._zod.run({ + value: left.value, + issues: left.issues, + fallback: left.fallback + }, ctx); +} +var $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { + $ZodPipe.init(inst, def); +}); +var $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); + defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then(handleReadonlyResult); + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +var $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) throw new Error(); - const [address, prefix] = parts; - if (!prefix) throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) throw new Error(); - if (prefixNum < 0 || prefixNum > 128) throw new Error(); - new URL(`http://[${address}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort - }); - } + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst)); + handleRefineResult(r, payload, input, inst); }; }); -function isValidBase64(data) { - if (data === "") return true; - if (/\s/.test(data)) return false; - if (data.length % 4 !== 0) return false; - try { - atob(data); - return true; - } catch { - return false; +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + path: [...inst._zod.def.path ?? []], + continue: !inst._zod.def.abort + }; + if (inst._zod.def.params) _iss.params = inst._zod.def.params; + payload.issues.push(issue(_iss)); + } +} +//#endregion +//#region node_modules/zod/v4/core/registries.js +var _a; +var $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema); + return this; + } + clear() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id); + this._map.delete(schema); + return this; + } + get(schema) { + const p = schema._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + const f = { + ...pm, + ...this._map.get(schema) + }; + return Object.keys(f).length ? f : void 0; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); } +}; +function registry() { + return new $ZodRegistry(); +} +(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); +var globalRegistry = globalThis.__zod_globalRegistry; +//#endregion +//#region node_modules/zod/v4/core/api.js +// @__NO_SIDE_EFFECTS__ +function _string(Class, params) { + return new Class({ + type: "string", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +/** +* @deprecated CUID v1 is deprecated by its authors due to information leakage +* (timestamps embedded in the id). Use {@link _cuid2} instead. +* See https://github.com/paralleldrive/cuid. +*/ +// @__NO_SIDE_EFFECTS__ +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _null$1(Class, params) { + return new Class({ + type: "null", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class) { + return new Class({ type: "any" }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class) { + return new Class({ type: "unknown" }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + return new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); } -var $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -function isValidBase64URL(data) { - if (!base64url.test(data)) return false; - const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); - return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")); +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); } -var $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) return false; - const [header] = tokensParts; - if (!header) return false; - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; - if (!parsedHeader.alg) return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; - return true; - } catch { - return false; - } +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); } -var $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number$1; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) try { - payload.value = Number(payload.value); - } catch (_) {} - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload; - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...received ? { received } : {} - }); - return payload; - }; -}); -var $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); -}); -var $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = boolean$1; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) try { - payload.value = Boolean(payload.value); - } catch (_) {} - const input = payload.value; - if (typeof input === "boolean") return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst - }); - return payload; - }; -}); -var $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -var $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -var $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; -}); -function handleArrayResult(result, final, index) { - if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues)); - final.value[index] = result.value; +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); } -var $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst - }); - return payload; - } - payload.value = Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [] - }, ctx); - if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i))); - else handleArrayResult(result, payload, i); - } - if (proms.length) return Promise.all(proms).then(() => payload); - return payload; - }; -}); -function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { - const isPresent = key in input; - if (result.issues.length) { - if (isOptionalIn && isOptionalOut && !isPresent) return; - final.issues.push(...prefixIssues(key, result.issues)); - } - if (!isPresent && !isOptionalIn) { - if (!result.issues.length) final.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: void 0, - path: [key] - }); - return; - } - if (result.value === void 0) { - if (isPresent) final.value[key] = void 0; - } else final.value[key] = result.value; +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); } -function normalizeDef(def) { - const keys = Object.keys(def.shape); - for (const k of keys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`); - const okeys = optionalKeys(def.shape); - return { - ...def, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys) - }; +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); +} +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); +} +// @__NO_SIDE_EFFECTS__ +function _trim() { + return /* @__PURE__ */ _overwrite((input) => input.trim()); +} +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); +} +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); +} +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return /* @__PURE__ */ _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + ...normalizeParams(params) + }); } -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const isOptionalIn = _catchall.optin === "optional"; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (key === "__proto__") continue; - if (keySet.has(key)) continue; - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ - value: input[key], - issues: [] - }, ctx); - if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut))); - else handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); - } - if (unrecognized.length) payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst +// @__NO_SIDE_EFFECTS__ +function _custom(Class, fn, _params) { + const norm = normalizeParams(_params); + norm.abort ?? (norm.abort = true); + return new Class({ + type: "custom", + check: "custom", + fn, + ...norm }); - if (!proms.length) return payload; - return Promise.all(proms).then(() => { - return payload; +} +// @__NO_SIDE_EFFECTS__ +function _refine(Class, fn, _params) { + return new Class({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params) }); } -var $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { - $ZodType.init(inst, def); - if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { value: newSh }); - return newSh; - } }); - } - const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); - for (const v of field.values) propValues[key].add(v); +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = /* @__PURE__ */ _check((payload) => { + payload.addIssue = (issue$2) => { + if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def)); + else { + const _issue = issue$2; + if (_issue.fatal) _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(issue(_issue)); } - } - return propValues; + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params) }); - const isObject$3 = isObject; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject$3(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; - } - payload.value = {}; - const proms = []; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const isOptionalIn = el._zod.optin === "optional"; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ - value: input[key], - issues: [] - }, ctx); - if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut))); - else handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); - } - if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload; - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + ch._zod.check = fn; + return ch; +} +//#endregion +//#region node_modules/zod/v4/core/to-json-schema.js +function initializeContext(params) { + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") target = "draft-04"; + if (target === "draft-7") target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => {}), + io: params?.io ?? "output", + counter: 0, + seen: /* @__PURE__ */ new Map(), + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + external: params?.external ?? void 0 }; -}); -var $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = cached(() => normalizeDef(def)); - const generateFastpass = (shape) => { - const doc = new Doc([ - "shape", - "payload", - "ctx" - ]); - const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.keys) ids[key] = `key_${counter++}`; - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { - const id = ids[key]; - const k = esc(key); - const schema = shape[key]; - const isOptionalIn = schema?._zod?.optin === "optional"; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); - if (isOptionalIn && isOptionalOut) doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); - } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - else if (!isOptionalIn) doc.write(` - const ${id}_present = ${k} in input; - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); - } - if (!${id}_present && !${id}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${k}] - }); - } - - if (${id}_present) { - if (${id}.value === undefined) { - newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } - } - - `); - else doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); +} +function process$1(schema, ctx, _params = { + path: [], + schemaPath: [] +}) { + var _a; + const def = schema._zod.def; + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + if (_params.schemaPath.includes(schema)) seen.cycle = _params.path; + return seen.schema; + } + const result = { + schema: {}, + count: 1, + cycle: void 0, + path: _params.path + }; + ctx.seen.set(schema, result); + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) result.schema = overrideSchema; + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path + }; + if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params); + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + processor(schema, ctx, _json, params); } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); + const parent = schema._zod.parent; + if (parent) { + if (!result.ref) result.ref = parent; + process$1(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + const meta = ctx.metadataRegistry.get(schema); + if (meta) Object.assign(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + delete result.schema.examples; + delete result.schema.default; + } + if (ctx.io === "input" && "_prefault" in result.schema) (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + return ctx.seen.get(schema).schema; +} +function extractDefs(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + const idToSchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + idToSchema.set(id, entry[0]); + } + } + const makeURI = (entry) => { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) return { ref: uriGenerator(externalId) }; + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; + return { + defId: id, + ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` + }; + } + if (entry[1] === root) return { ref: "#" }; + const defUriPrefix = `#/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { + defId, + ref: defUriPrefix + defId + }; }; - let fastpass; - const isObject$2 = isObject; - const jit = !globalConfig.jitless; - const fastEnabled = jit && allowsEval.value; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject$2(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) return; + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) seen.defId = defId; + const schema = seen.schema; + for (const key in schema) delete schema[key]; + schema.$ref = ref; + }; + if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - if (!fastpass) fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) return payload; - return handleCatchall([], input, payload, ctx, value, inst); + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } } - return superParse(payload, ctx); + if (ctx.metadataRegistry.get(entry[0])?.id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + continue; + } + } + } +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + if (seen.ref === null) return; + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } else Object.assign(schema, refSchema); + Object.assign(schema, _cached); + if (zodSchema._zod.parent === ref) for (const key in schema) { + if (key === "$ref" || key === "allOf") continue; + if (!(key in _cached)) delete schema[key]; + } + if (refSchema.$ref && refSeen.def) for (const key in schema) { + if (key === "$ref" || key === "allOf") continue; + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key]; + } + } + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + if (parentSeen.def) for (const key in schema) { + if (key === "$ref" || key === "allOf") continue; + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key]; + } + } + } + ctx.override({ + zodSchema, + jsonSchema: schema, + path: seen.path ?? [] + }); }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) if (result.issues.length === 0) { - final.value = result.value; - return final; + for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]); + const result = {}; + if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema"; + else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#"; + else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#"; + else if (ctx.target === "openapi-3.0") {} + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + Object.assign(result, root.def ?? root.schema); + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; + const defs = ctx.external?.defs ?? {}; + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) delete seen.def.id; + defs[seen.defId] = seen.def; + } + } + if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs; + else result.definitions = defs; + try { + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) + } + }, + enumerable: false, + writable: false + }); + return finalized; + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema)) return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") return true; + if (def.type === "array") return isTransforming(def.element, ctx); + if (def.type === "set") return isTransforming(def.valueType, ctx); + if (def.type === "lazy") return isTransforming(def.getter(), ctx); + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") return isTransforming(def.innerType, ctx); + if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true; + return false; + } + if (def.type === "union") { + for (const option of def.options) if (isTransforming(option, ctx)) return true; + return false; + } + if (def.type === "tuple") { + for (const item of def.items) if (isTransforming(item, ctx)) return true; + if (def.rest && isTransforming(def.rest, ctx)) return true; + return false; + } + return false; +} +/** +* Creates a toJSONSchema method for a schema instance. +* This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. +*/ +var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ + ...params, + processors + }); + process$1(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ + ...libraryOptions ?? {}, + target, + io, + processors + }); + process$1(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +//#endregion +//#region node_modules/zod/v4/core/json-schema-processors.js +var formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" +}; +var stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + if (typeof minimum === "number") json.minLength = minimum; + if (typeof maximum === "number") json.maxLength = maximum; + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") delete json.format; + if (format === "time") delete json.format; } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; + if (contentEncoding) json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) json.pattern = regexes[0].source; + else if (regexes.length > 1) json.allOf = [...regexes.map((regex) => ({ + ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, + pattern: regex.source + }))]; } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) +}; +var numberProcessor = (schema, ctx, _json, _params) => { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) json.type = "integer"; + else json.type = "number"; + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) if (legacy) { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } else json.exclusiveMinimum = exclusiveMinimum; + else if (typeof minimum === "number") json.minimum = minimum; + if (exMax) if (legacy) { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } else json.exclusiveMaximum = exclusiveMaximum; + else if (typeof maximum === "number") json.maximum = maximum; + if (typeof multipleOf === "number") json.multipleOf = multipleOf; +}; +var booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +var bigintProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema"); +}; +var symbolProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema"); +}; +var nullProcessor = (_schema, ctx, json, _params) => { + if (ctx.target === "openapi-3.0") { + json.type = "string"; + json.nullable = true; + json.enum = [null]; + } else json.type = "null"; +}; +var undefinedProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema"); +}; +var voidProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema"); +}; +var neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +var anyProcessor = (_schema, _ctx, _json, _params) => {}; +var unknownProcessor = (_schema, _ctx, _json, _params) => {}; +var dateProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema"); +}; +var enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + if (values.every((v) => typeof v === "number")) json.type = "number"; + if (values.every((v) => typeof v === "string")) json.type = "string"; + json.enum = values; +}; +var literalProcessor = (schema, ctx, json, _params) => { + const def = schema._zod.def; + const vals = []; + for (const val of def.values) if (val === void 0) { + if (ctx.unrepresentable === "throw") throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else if (typeof val === "bigint") if (ctx.unrepresentable === "throw") throw new Error("BigInt literals cannot be represented in JSON Schema"); + else vals.push(Number(val)); + else vals.push(val); + if (vals.length === 0) {} else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") json.enum = [val]; + else json.const = val; + } else { + if (vals.every((v) => typeof v === "number")) json.type = "number"; + if (vals.every((v) => typeof v === "string")) json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) json.type = "boolean"; + if (vals.every((v) => v === null)) json.type = "null"; + json.enum = vals; + } +}; +var nanProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema"); +}; +var templateLiteralProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +var fileProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== void 0) file.minLength = minimum; + if (maximum !== void 0) file.maxLength = maximum; + if (mime) if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(_json, file); + } else { + Object.assign(_json, file); + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); + } + else Object.assign(_json, file); +}; +var successProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +var customProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema"); +}; +var functionProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema"); +}; +var transformProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema"); +}; +var mapProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema"); +}; +var setProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema"); +}; +var arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") json.minItems = minimum; + if (typeof maximum === "number") json.maxItems = maximum; + json.type = "array"; + json.items = process$1(def.element, ctx, { + ...params, + path: [...params.path, "items"] }); - return final; -} -var $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); +}; +var objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + json.properties = {}; + const shape = def.shape; + for (const key in shape) json.properties[key] = process$1(shape[key], ctx, { + ...params, + path: [ + ...params.path, + "properties", + key + ] }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def.shape[key]._zod; + if (ctx.io === "input") return v.optin === void 0; + else return v.optout === void 0; + })); + if (requiredKeys.size > 0) json.required = Array.from(requiredKeys); + if (def.catchall?._zod.def.type === "never") json.additionalProperties = false; + else if (!def.catchall) { + if (ctx.io === "output") json.additionalProperties = false; + } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"] }); - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) return first(payload, ctx); - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [] - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } else { - if (result.issues.length === 0) return result; - results.push(result); - } - } - if (!async) return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); +}; +var unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => process$1(x, ctx, { + ...params, + path: [ + ...params.path, + isExclusive ? "oneOf" : "anyOf", + i + ] + })); + if (isExclusive) json.oneOf = options; + else json.anyOf = options; +}; +var intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = process$1(def.left, ctx, { + ...params, + path: [ + ...params.path, + "allOf", + 0 + ] + }); + const b = process$1(def.right, ctx, { + ...params, + path: [ + ...params.path, + "allOf", + 1 + ] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]]; +}; +var tupleProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => process$1(x, ctx, { + ...params, + path: [ + ...params.path, + prefixPath, + i + ] + })); + const rest = def.rest ? process$1(def.rest, ctx, { + ...params, + path: [ + ...params.path, + restPath, + ...ctx.target === "openapi-3.0" ? [def.items.length] : [] + ] + }) : null; + if (ctx.target === "draft-2020-12") { + json.prefixItems = prefixItems; + if (rest) json.items = rest; + } else if (ctx.target === "openapi-3.0") { + json.items = { anyOf: prefixItems }; + if (rest) json.items.anyOf.push(rest); + json.minItems = prefixItems.length; + if (!rest) json.maxItems = prefixItems.length; + } else { + json.items = prefixItems; + if (rest) json.additionalItems = rest; + } + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") json.minItems = minimum; + if (typeof maximum === "number") json.maxItems = maximum; +}; +var recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + const keyType = def.keyType; + const patterns = keyType._zod.bag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + const valueSchema = process$1(def.valueType, ctx, { + ...params, + path: [ + ...params.path, + "patternProperties", + "*" + ] }); - }; -}); -var $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ - value: input, - issues: [] - }, ctx); - const right = def.right._zod.run({ - value: input, - issues: [] - }, ctx); - if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); + json.patternProperties = {}; + for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema; + } else { + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$1(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"] + }); + json.additionalProperties = process$1(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"] }); - return handleIntersectionResults(payload, left, right); - }; -}); -function mergeValues(a, b) { - if (a === b) return { - valid: true, - data: a - }; - if (a instanceof Date && b instanceof Date && +a === +b) return { - valid: true, - data: a - }; - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { - ...a, - ...b - }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath] - }; - newObj[key] = sharedValue.data; - } - return { - valid: true, - data: newObj - }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) return { - valid: false, - mergeErrorPath: [] - }; - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath] - }; - newArray.push(sharedValue.data); - } - return { - valid: true, - data: newArray - }; } - return { - valid: false, - mergeErrorPath: [] - }; -} -function handleIntersectionResults(result, left, right) { - const unrecKeys = /* @__PURE__ */ new Map(); - let unrecIssue; - for (const iss of left.issues) if (iss.code === "unrecognized_keys") { - unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } - } else result.issues.push(iss); - for (const iss of right.issues) if (iss.code === "unrecognized_keys") for (const k of iss.keys) { - if (!unrecKeys.has(k)) unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; + const keyValues = keyType._zod.values; + if (keyValues) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) json.required = validKeyValues; } - else result.issues.push(iss); - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) result.issues.push({ - ...unrecIssue, - keys: bothKeys - }); - if (aborted(result)) return result; - const merged = mergeValues(left.value, right.value); - if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); - result.value = merged.data; - return result; -} -var $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values) { - payload.value = {}; - const recordKeys = /* @__PURE__ */ new Set(); - for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - const keyResult = def.keyType._zod.run({ - value: key, - issues: [] - }, ctx); - if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); - if (keyResult.issues.length) { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst - }); - continue; - } - const outKey = keyResult.value; - const result = def.valueType._zod.run({ - value: input[key], - issues: [] - }, ctx); - if (result instanceof Promise) proms.push(result.then((result) => { - if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); - payload.value[outKey] = result.value; - })); - else { - if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); - payload.value[outKey] = result.value; - } - } - let unrecognized; - for (const key in input) if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - if (unrecognized && unrecognized.length > 0) payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized - }); - } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue; - let keyResult = def.keyType._zod.run({ - value: key, - issues: [] - }, ctx); - if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); - if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) { - const retryResult = def.keyType._zod.run({ - value: Number(key), - issues: [] - }, ctx); - if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); - if (retryResult.issues.length === 0) keyResult = retryResult; - } - if (keyResult.issues.length) { - if (def.mode === "loose") payload.value[key] = input[key]; - else payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst - }); - continue; - } - const result = def.valueType._zod.run({ - value: input[key], - issues: [] - }, ctx); - if (result instanceof Promise) proms.push(result.then((result) => { - if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); - payload.value[keyResult.value] = result.value; - })); - else { - if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); - payload.value[keyResult.value] = result.value; - } - } - } - if (proms.length) return Promise.all(proms).then(() => payload); - return payload; - }; -}); -var $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) return payload; - payload.issues.push({ - code: "invalid_value", - values, - input, - inst - }); - return payload; - }; -}); -var $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name); - const _out = def.transform(payload.value, payload); - if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => { - payload.value = output; - payload.fallback = true; - return payload; +}; +var nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = process$1(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } else json.anyOf = [inner, { type: "null" }]; +}; +var nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process$1(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +var defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + process$1(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.default = JSON.parse(JSON.stringify(def.defaultValue)); +}; +var prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + process$1(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); +}; +var catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + process$1(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + json.default = catchValue; +}; +var pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; + process$1(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +var readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + process$1(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +var promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process$1(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +var optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process$1(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +var lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + process$1(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +var allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + const registry = input; + const ctx = initializeContext({ + ...params, + processors: allProcessors }); - if (_out instanceof Promise) throw new $ZodAsyncError(); - payload.value = _out; - payload.fallback = true; - return payload; - }; -}); -function handleOptionalResult(result, input) { - if (input === void 0 && (result.issues.length || result.fallback)) return { - issues: [], - value: void 0 - }; - return result; -} -var $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; - }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const input = payload.value; - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, input)); - return handleOptionalResult(result, input); + const defs = {}; + for (const entry of registry._idmap.entries()) { + const [_, schema] = entry; + process$1(schema, ctx); } - if (payload.value === void 0) return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { - $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; - }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === null) return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); - if (payload.value === void 0) { - payload.value = def.defaultValue; - /** - * $ZodDefault returns the default value immediately in forward direction. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; + const schemas = {}; + ctx.external = { + registry, + uri: params?.uri, + defs + }; + for (const entry of registry._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx, schema); + schemas[key] = finalize(ctx, schema); } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def)); - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === void 0) payload.value = def.defaultValue; - return payload; -} -var $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); - if (payload.value === void 0) payload.value = def.defaultValue; - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst)); - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === void 0) payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst + if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs }; + return { schemas }; + } + const ctx = initializeContext({ + ...params, + processors: allProcessors }); - return payload; + process$1(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); } -var $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then((result) => { - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }); - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) }, - input: payload.value - }); - payload.issues = []; - payload.fallback = true; - } - return payload; - }; +//#endregion +//#region node_modules/zod/v4/classic/iso.js +var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); }); -var $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx)); - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx)); - return handlePipeResult(left, def.out, ctx); - }; +function datetime(params) { + return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params); +} +var ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); }); -function handlePipeResult(left, next, ctx) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return next._zod.run({ - value: left.value, - issues: left.issues, - fallback: left.fallback - }, ctx); +function date(params) { + return /* @__PURE__ */ _isoDate(ZodISODate, params); } -var $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx); - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) return result.then(handleReadonlyResult); - return handleReadonlyResult(result); - }; +var ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); }); -function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); - return payload; +function time(params) { + return /* @__PURE__ */ _isoTime(ZodISOTime, params); } -var $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst)); - handleRefineResult(r, payload, input, inst); - }; +var ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); }); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, - path: [...inst._zod.def.path ?? []], - continue: !inst._zod.def.abort - }; - if (inst._zod.def.params) _iss.params = inst._zod.def.params; - payload.issues.push(issue(_iss)); - } +function duration(params) { + return /* @__PURE__ */ _isoDuration(ZodISODuration, params); } //#endregion -//#region node_modules/zod/v4/core/registries.js -var _a; -var $ZodRegistry = class { - constructor() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema); - return this; - } - clear() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - return this; +//#region node_modules/zod/v4/classic/errors.js +var initializer = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { value: (mapper) => formatError(inst, mapper) }, + flatten: { value: (mapper) => flattenError(inst, mapper) }, + addIssue: { value: (issue) => { + inst.issues.push(issue); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } }, + addIssues: { value: (issues) => { + inst.issues.push(...issues); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } }, + isEmpty: { get() { + return inst.issues.length === 0; + } } + }); +}; +var ZodError = /*@__PURE__*/ $constructor("ZodError", initializer); +var ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, { Parent: Error }); +//#endregion +//#region node_modules/zod/v4/classic/parse.js +var parse = /* @__PURE__ */ _parse(ZodRealError); +var parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError); +var safeParse = /* @__PURE__ */ _safeParse(ZodRealError); +var safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); +var encode$2 = /* @__PURE__ */ _encode(ZodRealError); +var decode$1 = /* @__PURE__ */ _decode(ZodRealError); +var encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError); +var decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError); +var safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); +var safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); +var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); +//#endregion +//#region node_modules/zod/v4/classic/schemas.js +var _installedGroups = /* @__PURE__ */ new WeakMap(); +function _installLazyMethods(inst, group, methods) { + const proto = Object.getPrototypeOf(inst); + let installed = _installedGroups.get(proto); + if (!installed) { + installed = /* @__PURE__ */ new Set(); + _installedGroups.set(proto, installed); } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id); - this._map.delete(schema); - return this; + if (installed.has(group)) return; + installed.add(group); + for (const key in methods) { + const fn = methods[key]; + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const bound = fn.bind(this); + Object.defineProperty(this, key, { + configurable: true, + writable: true, + enumerable: true, + value: bound + }); + return bound; + }, + set(v) { + Object.defineProperty(this, key, { + configurable: true, + writable: true, + enumerable: true, + value: v + }); + } + }); } - get(schema) { - const p = schema._zod.parent; - if (p) { - const pm = { ...this.get(p) ?? {} }; - delete pm.id; - const f = { - ...pm, - ...this._map.get(schema) - }; - return Object.keys(f).length ? f : void 0; +} +var ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { + $ZodType.init(inst, def); + Object.assign(inst["~standard"], { jsonSchema: { + input: createStandardJSONSchemaMethod(inst, "input"), + output: createStandardJSONSchemaMethod(inst, "output") + } }); + inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); + inst.def = def; + inst.type = def.type; + Object.defineProperty(inst, "_def", { value: def }); + inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params); + inst.spa = inst.safeParseAsync; + inst.encode = (data, params) => encode$2(inst, data, params); + inst.decode = (data, params) => decode$1(inst, data, params); + inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params); + inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params); + inst.safeEncode = (data, params) => safeEncode(inst, data, params); + inst.safeDecode = (data, params) => safeDecode(inst, data, params); + inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params); + inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params); + _installLazyMethods(inst, "ZodType", { + check(...chks) { + const def = this.def; + return this.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...chks.map((ch) => typeof ch === "function" ? { _zod: { + check: ch, + def: { check: "custom" }, + onattach: [] + } } : ch)] }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta) { + reg.add(this, meta); + return this; + }, + refine(check, params) { + return this.check(refine(check, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(/* @__PURE__ */ _overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn) { + return fn(this); } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -}; -function registry() { - return new $ZodRegistry(); -} -(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); -var globalRegistry = globalThis.__zod_globalRegistry; -//#endregion -//#region node_modules/zod/v4/core/api.js -// @__NO_SIDE_EFFECTS__ -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params) }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...normalizeParams(params) + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params) + return inst; +}); +/** @internal */ +var _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + _installLazyMethods(inst, "_ZodString", { + regex(...args) { + return this.check(/* @__PURE__ */ _regex(...args)); + }, + includes(...args) { + return this.check(/* @__PURE__ */ _includes(...args)); + }, + startsWith(...args) { + return this.check(/* @__PURE__ */ _startsWith(...args)); + }, + endsWith(...args) { + return this.check(/* @__PURE__ */ _endsWith(...args)); + }, + min(...args) { + return this.check(/* @__PURE__ */ _minLength(...args)); + }, + max(...args) { + return this.check(/* @__PURE__ */ _maxLength(...args)); + }, + length(...args) { + return this.check(/* @__PURE__ */ _length(...args)); + }, + nonempty(...args) { + return this.check(/* @__PURE__ */ _minLength(1, ...args)); + }, + lowercase(params) { + return this.check(/* @__PURE__ */ _lowercase(params)); + }, + uppercase(params) { + return this.check(/* @__PURE__ */ _uppercase(params)); + }, + trim() { + return this.check(/* @__PURE__ */ _trim()); + }, + normalize(...args) { + return this.check(/* @__PURE__ */ _normalize(...args)); + }, + toLowerCase() { + return this.check(/* @__PURE__ */ _toLowerCase()); + }, + toUpperCase() { + return this.check(/* @__PURE__ */ _toUpperCase()); + }, + slugify() { + return this.check(/* @__PURE__ */ _slugify()); + } }); +}); +var ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); + inst.email = (params) => inst.check(/* @__PURE__ */ _email(ZodEmail, params)); + inst.url = (params) => inst.check(/* @__PURE__ */ _url(ZodURL, params)); + inst.jwt = (params) => inst.check(/* @__PURE__ */ _jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(/* @__PURE__ */ _emoji(ZodEmoji, params)); + inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(/* @__PURE__ */ _uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(/* @__PURE__ */ _uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(/* @__PURE__ */ _uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(/* @__PURE__ */ _uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(/* @__PURE__ */ _nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(/* @__PURE__ */ _cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(/* @__PURE__ */ _cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(/* @__PURE__ */ _ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(/* @__PURE__ */ _base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(/* @__PURE__ */ _base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(/* @__PURE__ */ _xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(/* @__PURE__ */ _ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(/* @__PURE__ */ _ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(/* @__PURE__ */ _ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(/* @__PURE__ */ _cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(/* @__PURE__ */ _cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(/* @__PURE__ */ _e164(ZodE164, params)); + inst.datetime = (params) => inst.check(datetime(params)); + inst.date = (params) => inst.check(date(params)); + inst.time = (params) => inst.check(time(params)); + inst.duration = (params) => inst.check(duration(params)); +}); +function string(params) { + return /* @__PURE__ */ _string(ZodString, params); } -// @__NO_SIDE_EFFECTS__ -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); +var ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +var ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function email(params) { + return /* @__PURE__ */ _email(ZodEmail, params); } -// @__NO_SIDE_EFFECTS__ -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); +var ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function url(params) { + return /* @__PURE__ */ _url(ZodURL, params); } -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params) - }); +var ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +/** +* @deprecated CUID v1 is deprecated by its authors due to information leakage +* (timestamps embedded in the id). Use {@link ZodCUID2} instead. +* See https://github.com/paralleldrive/cuid. +*/ +var ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ipv4(params) { + return /* @__PURE__ */ _ipv4(ZodIPv4, params); } -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params) - }); +var ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ipv6(params) { + return /* @__PURE__ */ _ipv6(ZodIPv6, params); } -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params) +var ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); + _installLazyMethods(inst, "ZodNumber", { + gt(value, params) { + return this.check(/* @__PURE__ */ _gt(value, params)); + }, + gte(value, params) { + return this.check(/* @__PURE__ */ _gte(value, params)); + }, + min(value, params) { + return this.check(/* @__PURE__ */ _gte(value, params)); + }, + lt(value, params) { + return this.check(/* @__PURE__ */ _lt(value, params)); + }, + lte(value, params) { + return this.check(/* @__PURE__ */ _lte(value, params)); + }, + max(value, params) { + return this.check(/* @__PURE__ */ _lte(value, params)); + }, + int(params) { + return this.check(int(params)); + }, + safe(params) { + return this.check(int(params)); + }, + positive(params) { + return this.check(/* @__PURE__ */ _gt(0, params)); + }, + nonnegative(params) { + return this.check(/* @__PURE__ */ _gte(0, params)); + }, + negative(params) { + return this.check(/* @__PURE__ */ _lt(0, params)); + }, + nonpositive(params) { + return this.check(/* @__PURE__ */ _lte(0, params)); + }, + multipleOf(value, params) { + return this.check(/* @__PURE__ */ _multipleOf(value, params)); + }, + step(value, params) { + return this.check(/* @__PURE__ */ _multipleOf(value, params)); + }, + finite() { + return this; + } }); + const bag = inst._zod.bag; + inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}); +function number(params) { + return /* @__PURE__ */ _number(ZodNumber, params); } -// @__NO_SIDE_EFFECTS__ -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); +var ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); +}); +function int(params) { + return /* @__PURE__ */ _int(ZodNumberFormat, params); } -// @__NO_SIDE_EFFECTS__ -function _emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); +var ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); +}); +function boolean(params) { + return /* @__PURE__ */ _boolean(ZodBoolean, params); } -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); +var ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); +}); +function _null(params) { + return /* @__PURE__ */ _null$1(ZodNull, params); } -/** -* @deprecated CUID v1 is deprecated by its authors due to information leakage -* (timestamps embedded in the id). Use {@link _cuid2} instead. -* See https://github.com/paralleldrive/cuid. -*/ -// @__NO_SIDE_EFFECTS__ -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); +var ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => void 0; +}); +function any() { + return /* @__PURE__ */ _any(ZodAny); } -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); +var ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => void 0; +}); +function unknown() { + return /* @__PURE__ */ _unknown(ZodUnknown); } -// @__NO_SIDE_EFFECTS__ -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); +var ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); +}); +function never(params) { + return /* @__PURE__ */ _never(ZodNever, params); } -// @__NO_SIDE_EFFECTS__ -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params) +var ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); + inst.element = def.element; + _installLazyMethods(inst, "ZodArray", { + min(n, params) { + return this.check(/* @__PURE__ */ _minLength(n, params)); + }, + nonempty(params) { + return this.check(/* @__PURE__ */ _minLength(1, params)); + }, + max(n, params) { + return this.check(/* @__PURE__ */ _maxLength(n, params)); + }, + length(n, params) { + return this.check(/* @__PURE__ */ _length(n, params)); + }, + unwrap() { + return this.element; + } }); +}); +function array(element, params) { + return /* @__PURE__ */ _array(ZodArray, element, params); } -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params) +var ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); + defineLazy(inst, "shape", () => { + return def.shape; }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params) + _installLazyMethods(inst, "ZodObject", { + keyof() { + return _enum(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone({ + ...this._zod.def, + catchall + }); + }, + passthrough() { + return this.clone({ + ...this._zod.def, + catchall: unknown() + }); + }, + loose() { + return this.clone({ + ...this._zod.def, + catchall: unknown() + }); + }, + strict() { + return this.clone({ + ...this._zod.def, + catchall: never() + }); + }, + strip() { + return this.clone({ + ...this._zod.def, + catchall: void 0 + }); + }, + extend(incoming) { + return extend(this, incoming); + }, + safeExtend(incoming) { + return safeExtend(this, incoming); + }, + merge(other) { + return merge(this, other); + }, + pick(mask) { + return pick(this, mask); + }, + omit(mask) { + return omit(this, mask); + }, + partial(...args) { + return partial(ZodOptional, this, args[0]); + }, + required(...args) { + return required(ZodNonOptional, this, args[0]); + } }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, +}); +function object(shape, params) { + return new ZodObject({ + type: "object", + shape: shape ?? {}, ...normalizeParams(params) }); } -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), ...normalizeParams(params) }); } -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, +var ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +function union(options, params) { + return new ZodUnion({ + type: "union", + options, ...normalizeParams(params) }); } -// @__NO_SIDE_EFFECTS__ -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, +var ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + return new ZodDiscriminatedUnion({ + type: "union", + options, + discriminator, ...normalizeParams(params) }); } -// @__NO_SIDE_EFFECTS__ -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params) +var ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left, + right }); } -// @__NO_SIDE_EFFECTS__ -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params) +var ZodTuple = /*@__PURE__*/ $constructor("ZodTuple", (inst, def) => { + $ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => tupleProcessor(inst, ctx, json, params); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params) +}); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + return new ZodTuple({ + type: "tuple", + items, + rest: hasRest ? _paramsOrRest : null, + ...normalizeParams(hasRest ? _params : _paramsOrRest) }); } -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params) +var ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function record(keyType, valueType, params) { + if (!valueType || !valueType._zod) return new ZodRecord({ + type: "record", + keyType: string(), + valueType: keyType, + ...normalizeParams(valueType) }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", + return new ZodRecord({ + type: "record", + keyType, + valueType, ...normalizeParams(params) }); } -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, +var ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value]; + else throw new Error(`Key ${value} not found in enum`); + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) if (keys.has(value)) delete newEntries[value]; + else throw new Error(`Key ${value} not found in enum`); + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries + }); + }; +}); +function _enum(values, params) { + return new ZodEnum({ + type: "enum", + entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values, ...normalizeParams(params) }); } -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", +var ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { get() { + if (def.values.length > 1) throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + return def.values[0]; + } }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], ...normalizeParams(params) }); } -// @__NO_SIDE_EFFECTS__ -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params) +var ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name); + payload.addIssue = (issue$1) => { + if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def)); + else { + const _issue = issue$1; + if (_issue.fatal) _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + payload.issues.push(issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) return output.then((output) => { + payload.value = output; + payload.fallback = true; + return payload; + }); + payload.value = output; + payload.fallback = true; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn }); } -// @__NO_SIDE_EFFECTS__ -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params) +var ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType }); } -// @__NO_SIDE_EFFECTS__ -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params) +var ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType }); } -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...normalizeParams(params) +var ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType }); } -// @__NO_SIDE_EFFECTS__ -function _any(Class) { - return new Class({ type: "any" }); +var ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function _default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + } + }); } -// @__NO_SIDE_EFFECTS__ -function _unknown(Class) { - return new Class({ type: "unknown" }); +var ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + } + }); } -// @__NO_SIDE_EFFECTS__ -function _never(Class, params) { - return new Class({ - type: "never", +var ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, ...normalizeParams(params) }); } -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false +var ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function _catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true +var ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out }); } -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false +var ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { + ZodPipe.init(inst, def); + $ZodPreprocess.init(inst, def); +}); +var ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType }); } -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true - }); +var ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); +}); +function custom(fn, _params) { + return /* @__PURE__ */ _custom(ZodCustom, fn ?? (() => true), _params); } -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value - }); +function refine(fn, _params = {}) { + return /* @__PURE__ */ _refine(ZodCustom, fn, _params); } -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - return new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum +function superRefine(fn, params) { + return /* @__PURE__ */ _superRefine(fn, params); +} +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...normalizeParams(params) }); + inst._zod.bag.Class = cls; + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...inst._zod.def.path ?? []] + }); + }; + return inst; } -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema }); } -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length +//#endregion +//#region node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs +var initGetDefaultModelName = ({ usePlural, schema }) => { + /** + * This function helps us get the default model name from the schema defined by devs. + * Often times, the user will be using the `modelName` which could had been customized by the users. + * This function helps us get the actual model name useful to match against the schema. (eg: schema[model]) + * + * If it's still unclear what this does: + * + * 1. User can define a custom modelName. + * 2. When using a custom modelName, doing something like `schema[model]` will not work. + * 3. Using this function helps us get the actual model name based on the user's defined custom modelName. + */ + const getDefaultModelName = (model) => { + const resolve = (candidate) => { + if (schema[candidate]) return candidate; + return Object.entries(schema).find(([_, f]) => f.modelName === candidate)?.[0]; + }; + if (usePlural && model.charAt(model.length - 1) === "s") { + const m = resolve(model.slice(0, -1)); + if (m) return m; + } + const m = resolve(model); + if (!m) throw new BetterAuthError(`Model "${model}" not found in schema`); + return m; + }; + return getDefaultModelName; +}; +//#endregion +//#region node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs +var initGetDefaultFieldName = ({ schema, usePlural }) => { + const getDefaultModelName = initGetDefaultModelName({ + schema, + usePlural }); + /** + * This function helps us get the default field name from the schema defined by devs. + * Often times, the user will be using the `fieldName` which could had been customized by the users. + * This function helps us get the actual field name useful to match against the schema. (eg: schema[model].fields[field]) + * + * If it's still unclear what this does: + * + * 1. User can define a custom fieldName. + * 2. When using a custom fieldName, doing something like `schema[model].fields[field]` will not work. + */ + const getDefaultFieldName = ({ field, model: unsafeModel }) => { + if (field === "id" || field === "_id") return "id"; + const model = getDefaultModelName(unsafeModel); + let f = schema[model]?.fields[field]; + if (!f) { + const result = Object.entries(schema[model].fields).find(([_, f]) => f.fieldName === field); + if (result) { + f = result[1]; + field = result[0]; + } + } + if (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`); + return field; + }; + return getDefaultFieldName; +}; +//#endregion +//#region node_modules/@better-auth/utils/dist/random.mjs +function expandAlphabet(alphabet) { + switch (alphabet) { + case "a-z": return "abcdefghijklmnopqrstuvwxyz"; + case "A-Z": return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + case "0-9": return "0123456789"; + case "-_": return "-_"; + default: throw new Error(`Unsupported alphabet: ${alphabet}`); + } } -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern - }); +function createRandomStringGenerator(...baseAlphabets) { + const baseCharSet = baseAlphabets.map(expandAlphabet).join(""); + if (baseCharSet.length === 0) throw new Error("No valid characters provided for random string generation."); + const baseCharSetLength = baseCharSet.length; + return (length, ...alphabets) => { + if (length <= 0) throw new Error("Length must be a positive integer."); + let charSet = baseCharSet; + let charSetLength = baseCharSetLength; + if (alphabets.length > 0) { + charSet = alphabets.map(expandAlphabet).join(""); + charSetLength = charSet.length; + } + const maxValid = Math.floor(256 / charSetLength) * charSetLength; + const buf = new Uint8Array(length * 2); + const bufLength = buf.length; + let result = ""; + let bufIndex = bufLength; + let rand; + while (result.length < length) { + if (bufIndex >= bufLength) { + crypto.getRandomValues(buf); + bufIndex = 0; + } + rand = buf[bufIndex++]; + if (rand < maxValid) result += charSet[rand % charSetLength]; + } + return result; + }; } -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params) +//#endregion +//#region node_modules/@better-auth/core/dist/utils/id.mjs +var generateId = (size) => { + return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32); +}; +//#endregion +//#region node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs +var initGetIdField = ({ usePlural, schema, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => { + const getDefaultModelName = initGetDefaultModelName({ + usePlural, + schema }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params) + const idField = ({ customModelName, forceAllowId }) => { + const useNumberId = options.advanced?.database?.generateId === "serial"; + const useUUIDs = options.advanced?.database?.generateId === "uuid"; + const shouldGenerateId = (() => { + if (disableIdGeneration) return false; + else if (useNumberId && !forceAllowId) return false; + else if (useUUIDs) return !supportsUUIDs; + else return true; + })(); + const model = getDefaultModelName(customModelName ?? "id"); + return { + type: useNumberId ? "number" : "string", + required: shouldGenerateId ? true : false, + ...shouldGenerateId ? { defaultValue() { + if (disableIdGeneration) return void 0; + const generateId$1 = options.advanced?.database?.generateId; + if (generateId$1 === false || generateId$1 === "serial") return void 0; + if (typeof generateId$1 === "function") return generateId$1({ model }); + if (generateId$1 === "uuid") return crypto.randomUUID(); + if (customIdGenerator) return customIdGenerator({ model }); + return generateId(); + } } : {}, + transform: { + input: (value) => { + if (!value) return void 0; + if (useNumberId) { + const numberValue = Number(value); + if (isNaN(numberValue)) return; + return numberValue; + } + if (useUUIDs) { + if (shouldGenerateId && !forceAllowId) return value; + if (disableIdGeneration) return void 0; + if (forceAllowId && typeof value === "string") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value; + else { + const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", ""); + logger.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.", stack); + } + if (supportsUUIDs) return void 0; + if (typeof value !== "string" && !supportsUUIDs) return crypto.randomUUID(); + return; + } + return value; + }, + output: (value) => { + if (!value) return void 0; + return String(value); + } + } + }; + }; + return idField; +}; +//#endregion +//#region node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs +var initGetFieldAttributes = ({ usePlural, schema, options, customIdGenerator, disableIdGeneration }) => { + const getDefaultModelName = initGetDefaultModelName({ + usePlural, + schema }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes + const getDefaultFieldName = initGetDefaultFieldName({ + usePlural, + schema }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix + const idField = initGetIdField({ + usePlural, + schema, + options, + customIdGenerator, + disableIdGeneration }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix + const getFieldAttributes = ({ model, field }) => { + const defaultModelName = getDefaultModelName(model); + const defaultFieldName = getDefaultFieldName({ + field, + model: defaultModelName + }); + const fields = schema[defaultModelName].fields; + fields.id = idField({ customModelName: defaultModelName }); + const fieldAttributes = fields[defaultFieldName]; + if (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`); + return fieldAttributes; + }; + return getFieldAttributes; +}; +//#endregion +//#region node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs +var initGetFieldName = ({ schema, usePlural }) => { + const getDefaultModelName = initGetDefaultModelName({ + schema, + usePlural }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx + const getDefaultFieldName = initGetDefaultFieldName({ + schema, + usePlural }); + /** + * Get the field name which is expected to be saved in the database based on the user's schema. + * + * This function is useful if you need to save the field name to the database. + * + * For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema. + */ + function getFieldName({ model: modelName, field: fieldName }) { + const model = getDefaultModelName(modelName); + const field = getDefaultFieldName({ + model, + field: fieldName + }); + return schema[model]?.fields[field]?.fieldName || field; + } + return getFieldName; +}; +//#endregion +//#region node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs +var initGetModelName = ({ usePlural, schema }) => { + const getDefaultModelName = initGetDefaultModelName({ + schema, + usePlural + }); + /** + * Users can overwrite the default model of some tables. This function helps find the correct model name. + * Furthermore, if the user passes `usePlural` as true in their adapter config, + * then we should return the model name ending with an `s`. + */ + const getModelName = (model) => { + const defaultModelKey = getDefaultModelName(model); + if (schema && schema[defaultModelKey] && schema[defaultModelKey].modelName !== model) return usePlural ? `${schema[defaultModelKey].modelName}s` : schema[defaultModelKey].modelName; + return usePlural ? `${model}s` : model; + }; + return getModelName; +}; +//#endregion +//#region node_modules/@better-auth/core/dist/db/adapter/utils.mjs +function withApplyDefault(value, field, action) { + if (action === "update") { + if (value === void 0 && field.onUpdate !== void 0) { + if (typeof field.onUpdate === "function") return field.onUpdate(); + return field.onUpdate; + } + return value; + } + if (action === "create") { + if (value === void 0 || field.required === true && value === null) { + if (field.defaultValue !== void 0) { + if (typeof field.defaultValue === "function") return field.defaultValue(); + return field.defaultValue; + } + } + } + return value; } -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); -} -// @__NO_SIDE_EFFECTS__ -function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); -} -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); +//#endregion +//#region node_modules/@better-auth/core/dist/context/global.mjs +var symbol = Symbol.for("better-auth:global"); +var bind = null; +var __context = {}; +var __betterAuthVersion = "1.6.25"; +/** +* We store context instance in the globalThis. +* +* The reason we do this is that some bundlers, web framework, or package managers might +* create multiple copies of BetterAuth in the same process intentionally or unintentionally. +* +* For example, yarn v1, Next.js, SSR, Vite... +* +* @internal +*/ +function __getBetterAuthGlobal() { + if (!globalThis[symbol]) { + globalThis[symbol] = { + version: __betterAuthVersion, + epoch: 1, + context: __context + }; + bind = globalThis[symbol]; + } + bind = globalThis[symbol]; + if (bind.version !== __betterAuthVersion) { + bind.version = __betterAuthVersion; + bind.epoch++; + } + return globalThis[symbol]; } -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); +function getBetterAuthVersion() { + return __getBetterAuthGlobal().version; } -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify(input)); +//#endregion +//#region node_modules/@better-auth/core/dist/async_hooks/index.mjs +var AsyncLocalStoragePromise = import( + /* @vite-ignore */ + /* webpackIgnore: true */ + "node:async_hooks" +).then((mod) => mod.AsyncLocalStorage).catch((err) => { + if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage; + if (typeof window !== "undefined") return null; + console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."); + console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"); + console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"); + throw err; +}); +async function getAsyncLocalStorage() { + const mod = await AsyncLocalStoragePromise; + if (mod === null) throw new Error("getAsyncLocalStorage is only available in server code"); + else return mod; } -// @__NO_SIDE_EFFECTS__ -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - ...normalizeParams(params) +//#endregion +//#region node_modules/@better-auth/core/dist/context/transaction.mjs +var ensureAsyncStorage$2 = async () => { + const betterAuthGlobal = __getBetterAuthGlobal(); + if (!betterAuthGlobal.context.adapterAsyncStorage) { + const AsyncLocalStorage = await getAsyncLocalStorage(); + betterAuthGlobal.context.adapterAsyncStorage = new AsyncLocalStorage(); + } + return betterAuthGlobal.context.adapterAsyncStorage; +}; +var getCurrentAdapter = async (fallback) => { + return ensureAsyncStorage$2().then((als) => { + return als.getStore()?.adapter || fallback; + }).catch(() => { + return fallback; }); -} -// @__NO_SIDE_EFFECTS__ -function _refine(Class, fn, _params) { - return new Class({ - type: "custom", - check: "custom", - fn, - ...normalizeParams(_params) +}; +var runWithAdapter = async (adapter, fn) => { + let called = false; + return ensureAsyncStorage$2().then(async (als) => { + called = true; + const pendingHooks = []; + let result; + let error; + let hasError = false; + try { + result = await als.run({ + adapter, + pendingHooks, + isTransactionActive: false + }, fn); + } catch (err) { + error = err; + hasError = true; + } + for (const hook of pendingHooks) await hook(); + if (hasError) throw error; + return result; + }).catch((err) => { + if (!called) return fn(); + throw err; }); -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn, params) { - const ch = /* @__PURE__ */ _check((payload) => { - payload.addIssue = (issue$2) => { - if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def)); - else { - const _issue = issue$2; - if (_issue.fatal) _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); - payload.issues.push(issue(_issue)); - } - }; - return fn(payload.value, payload); - }, params); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params) +}; +var runWithTransaction = async (adapter, fn) => { + let called = false; + return ensureAsyncStorage$2().then(async (als) => { + called = true; + if (als.getStore()?.isTransactionActive) return fn(); + const pendingHooks = []; + let result; + let error; + let hasError = false; + try { + result = await adapter.transaction(async (trx) => { + return als.run({ + adapter: trx, + pendingHooks, + isTransactionActive: true + }, fn); + }); + } catch (e) { + hasError = true; + error = e; + } + for (const hook of pendingHooks) await hook(); + if (hasError) throw error; + return result; + }).catch((err) => { + if (!called) return fn(); + throw err; }); - ch._zod.check = fn; - return ch; -} +}; +/** +* Queue a hook to be executed after the current transaction commits. +* If not in a transaction, the hook will execute immediately. +*/ +var queueAfterTransactionHook = async (hook) => { + return ensureAsyncStorage$2().then((als) => { + const store = als.getStore(); + if (store) store.pendingHooks.push(hook); + else return hook(); + }).catch(() => { + return hook(); + }); +}; //#endregion -//#region node_modules/zod/v4/core/to-json-schema.js -function initializeContext(params) { - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") target = "draft-04"; - if (target === "draft-7") target = "draft-07"; +//#region node_modules/@better-auth/core/dist/db/get-tables.mjs +var getAuthTables = (options) => { + const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => { + const schema = plugin.schema; + if (!schema) return acc; + for (const [key, value] of Object.entries(schema)) acc[key] = { + fields: { + ...acc[key]?.fields, + ...value.fields + }, + modelName: value.modelName || key, + disableMigrations: value.disableMigration ?? acc[key]?.disableMigrations + }; + return acc; + }, {}); + const shouldAddRateLimitTable = options.rateLimit?.storage === "database"; + const rateLimitTable = { rateLimit: { + modelName: options.rateLimit?.modelName || "rateLimit", + fields: { + key: { + type: "string", + unique: true, + required: true, + fieldName: options.rateLimit?.fields?.key || "key" + }, + count: { + type: "number", + required: true, + fieldName: options.rateLimit?.fields?.count || "count" + }, + lastRequest: { + type: "number", + bigint: true, + required: true, + fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest", + defaultValue: () => Date.now() + } + } + } }; + const { user, session, account, verification, ...pluginTables } = pluginSchema; + const verificationTable = { verification: { + modelName: options.verification?.modelName || "verification", + fields: { + identifier: { + type: "string", + required: true, + fieldName: options.verification?.fields?.identifier || "identifier", + index: true + }, + value: { + type: "string", + required: true, + fieldName: options.verification?.fields?.value || "value" + }, + expiresAt: { + type: "date", + required: true, + fieldName: options.verification?.fields?.expiresAt || "expiresAt" + }, + createdAt: { + type: "date", + required: true, + defaultValue: () => /* @__PURE__ */ new Date(), + fieldName: options.verification?.fields?.createdAt || "createdAt" + }, + updatedAt: { + type: "date", + required: true, + defaultValue: () => /* @__PURE__ */ new Date(), + onUpdate: () => /* @__PURE__ */ new Date(), + fieldName: options.verification?.fields?.updatedAt || "updatedAt" + }, + ...verification?.fields, + ...options.verification?.additionalFields + }, + order: 4 + } }; + const sessionTable = { session: { + modelName: options.session?.modelName || "session", + fields: { + expiresAt: { + type: "date", + required: true, + fieldName: options.session?.fields?.expiresAt || "expiresAt" + }, + token: { + type: "string", + required: true, + fieldName: options.session?.fields?.token || "token", + unique: true + }, + createdAt: { + type: "date", + required: true, + fieldName: options.session?.fields?.createdAt || "createdAt", + defaultValue: () => /* @__PURE__ */ new Date() + }, + updatedAt: { + type: "date", + required: true, + fieldName: options.session?.fields?.updatedAt || "updatedAt", + onUpdate: () => /* @__PURE__ */ new Date() + }, + ipAddress: { + type: "string", + required: false, + fieldName: options.session?.fields?.ipAddress || "ipAddress" + }, + userAgent: { + type: "string", + required: false, + fieldName: options.session?.fields?.userAgent || "userAgent" + }, + userId: { + type: "string", + fieldName: options.session?.fields?.userId || "userId", + references: { + model: "user", + field: "id", + onDelete: "cascade" + }, + required: true, + index: true + }, + ...session?.fields, + ...options.session?.additionalFields + }, + order: 2 + } }; return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => {}), - io: params?.io ?? "output", - counter: 0, - seen: /* @__PURE__ */ new Map(), - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - external: params?.external ?? void 0 - }; -} -function process$1(schema, ctx, _params = { - path: [], - schemaPath: [] -}) { - var _a; - const def = schema._zod.def; - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - if (_params.schemaPath.includes(schema)) seen.cycle = _params.path; - return seen.schema; - } - const result = { - schema: {}, - count: 1, - cycle: void 0, - path: _params.path + user: { + modelName: options.user?.modelName || "user", + fields: { + name: { + type: "string", + required: true, + fieldName: options.user?.fields?.name || "name", + sortable: true + }, + email: { + type: "string", + unique: true, + required: true, + fieldName: options.user?.fields?.email || "email", + sortable: true + }, + emailVerified: { + type: "boolean", + defaultValue: false, + required: true, + fieldName: options.user?.fields?.emailVerified || "emailVerified", + input: false + }, + image: { + type: "string", + required: false, + fieldName: options.user?.fields?.image || "image" + }, + createdAt: { + type: "date", + defaultValue: () => /* @__PURE__ */ new Date(), + required: true, + fieldName: options.user?.fields?.createdAt || "createdAt" + }, + updatedAt: { + type: "date", + defaultValue: () => /* @__PURE__ */ new Date(), + onUpdate: () => /* @__PURE__ */ new Date(), + required: true, + fieldName: options.user?.fields?.updatedAt || "updatedAt" + }, + ...user?.fields, + ...options.user?.additionalFields + }, + order: 1 + }, + ...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {}, + account: { + modelName: options.account?.modelName || "account", + fields: { + accountId: { + type: "string", + required: true, + fieldName: options.account?.fields?.accountId || "accountId" + }, + providerId: { + type: "string", + required: true, + fieldName: options.account?.fields?.providerId || "providerId" + }, + userId: { + type: "string", + references: { + model: "user", + field: "id", + onDelete: "cascade" + }, + required: true, + fieldName: options.account?.fields?.userId || "userId", + index: true + }, + accessToken: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.accessToken || "accessToken" + }, + refreshToken: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.refreshToken || "refreshToken" + }, + idToken: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.idToken || "idToken" + }, + accessTokenExpiresAt: { + type: "date", + required: false, + returned: false, + fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt" + }, + refreshTokenExpiresAt: { + type: "date", + required: false, + returned: false, + fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt" + }, + scope: { + type: "string", + required: false, + fieldName: options.account?.fields?.scope || "scope" + }, + password: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.password || "password" + }, + createdAt: { + type: "date", + required: true, + fieldName: options.account?.fields?.createdAt || "createdAt", + defaultValue: () => /* @__PURE__ */ new Date() + }, + updatedAt: { + type: "date", + required: true, + fieldName: options.account?.fields?.updatedAt || "updatedAt", + onUpdate: () => /* @__PURE__ */ new Date() + }, + ...account?.fields, + ...options.account?.additionalFields + }, + order: 3 + }, + ...!options.secondaryStorage || options.verification?.storeInDatabase ? verificationTable : {}, + ...pluginTables, + ...shouldAddRateLimitTable ? rateLimitTable : {} }; - ctx.seen.set(schema, result); - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) result.schema = overrideSchema; - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path - }; - if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params); - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - processor(schema, ctx, _json, params); - } - const parent = schema._zod.parent; - if (parent) { - if (!result.ref) result.ref = parent; - process$1(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } +}; +//#endregion +//#region node_modules/@better-auth/core/dist/utils/json.mjs +var iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/; +function reviveDate(value) { + if (typeof value === "string" && iso8601Regex.test(value)) { + const date = new Date(value); + if (!isNaN(date.getTime())) return date; } - const meta = ctx.metadataRegistry.get(schema); - if (meta) Object.assign(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - delete result.schema.examples; - delete result.schema.default; + return value; +} +/** +* Recursively walk a pre-parsed object and convert ISO 8601 date strings +* to Date instances. This handles the case where a Redis client (or similar) +* returns already-parsed JSON objects whose date fields are still strings. +*/ +function reviveDates(value) { + if (value === null || value === void 0) return value; + if (typeof value === "string") return reviveDate(value); + if (value instanceof Date) return value; + if (Array.isArray(value)) return value.map(reviveDates); + if (typeof value === "object") { + const result = {}; + for (const key of Object.keys(value)) result[key] = reviveDates(value[key]); + return result; } - if (ctx.io === "input" && "_prefault" in result.schema) (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - return ctx.seen.get(schema).schema; + return value; } -function extractDefs(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); - const idToSchema = /* @__PURE__ */ new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - idToSchema.set(id, entry[0]); +function safeJSONParse(data) { + try { + if (typeof data !== "string") { + if (data === null || data === void 0) return null; + return reviveDates(data); } + return JSON.parse(data, (_, value) => reviveDate(value)); + } catch (e) { + logger.error("Error parsing JSON", { error: e }); + return null; } - const makeURI = (entry) => { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) return { ref: uriGenerator(externalId) }; - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; - return { - defId: id, - ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` - }; +} +//#endregion +//#region node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createConstMap = void 0; + /** + * Creates a const map from the given values + * @param values - An array of values to be used as keys and values in the map. + * @returns A populated version of the map with the values and keys derived from the values. + */ + /*#__NO_SIDE_EFFECTS__*/ + function createConstMap(values) { + let res = {}; + const len = values.length; + for (let lp = 0; lp < len; lp++) { + const val = values[lp]; + if (val) res[String(val).toUpperCase().replace(/[-.]/g, "_")] = val; } - if (entry[1] === root) return { ref: "#" }; - const defUriPrefix = `#/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { - defId, - ref: defUriPrefix + defId - }; + return res; + } + exports.createConstMap = createConstMap; +})); +//#endregion +//#region node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js +var require_SemanticAttributes = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SEMATTRS_NET_HOST_CARRIER_ICC = exports.SEMATTRS_NET_HOST_CARRIER_MNC = exports.SEMATTRS_NET_HOST_CARRIER_MCC = exports.SEMATTRS_NET_HOST_CARRIER_NAME = exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = exports.SEMATTRS_NET_HOST_NAME = exports.SEMATTRS_NET_HOST_PORT = exports.SEMATTRS_NET_HOST_IP = exports.SEMATTRS_NET_PEER_NAME = exports.SEMATTRS_NET_PEER_PORT = exports.SEMATTRS_NET_PEER_IP = exports.SEMATTRS_NET_TRANSPORT = exports.SEMATTRS_FAAS_INVOKED_REGION = exports.SEMATTRS_FAAS_INVOKED_PROVIDER = exports.SEMATTRS_FAAS_INVOKED_NAME = exports.SEMATTRS_FAAS_COLDSTART = exports.SEMATTRS_FAAS_CRON = exports.SEMATTRS_FAAS_TIME = exports.SEMATTRS_FAAS_DOCUMENT_NAME = exports.SEMATTRS_FAAS_DOCUMENT_TIME = exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = exports.SEMATTRS_FAAS_EXECUTION = exports.SEMATTRS_FAAS_TRIGGER = exports.SEMATTRS_EXCEPTION_ESCAPED = exports.SEMATTRS_EXCEPTION_STACKTRACE = exports.SEMATTRS_EXCEPTION_MESSAGE = exports.SEMATTRS_EXCEPTION_TYPE = exports.SEMATTRS_DB_SQL_TABLE = exports.SEMATTRS_DB_MONGODB_COLLECTION = exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = exports.SEMATTRS_DB_HBASE_NAMESPACE = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = exports.SEMATTRS_DB_CASSANDRA_TABLE = exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = exports.SEMATTRS_DB_OPERATION = exports.SEMATTRS_DB_STATEMENT = exports.SEMATTRS_DB_NAME = exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = exports.SEMATTRS_DB_USER = exports.SEMATTRS_DB_CONNECTION_STRING = exports.SEMATTRS_DB_SYSTEM = exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = void 0; + exports.SEMATTRS_MESSAGING_DESTINATION_KIND = exports.SEMATTRS_MESSAGING_DESTINATION = exports.SEMATTRS_MESSAGING_SYSTEM = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = exports.SEMATTRS_AWS_DYNAMODB_COUNT = exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_SELECT = exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = exports.SEMATTRS_AWS_DYNAMODB_LIMIT = exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = exports.SEMATTRS_HTTP_CLIENT_IP = exports.SEMATTRS_HTTP_ROUTE = exports.SEMATTRS_HTTP_SERVER_NAME = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = exports.SEMATTRS_HTTP_USER_AGENT = exports.SEMATTRS_HTTP_FLAVOR = exports.SEMATTRS_HTTP_STATUS_CODE = exports.SEMATTRS_HTTP_SCHEME = exports.SEMATTRS_HTTP_HOST = exports.SEMATTRS_HTTP_TARGET = exports.SEMATTRS_HTTP_URL = exports.SEMATTRS_HTTP_METHOD = exports.SEMATTRS_CODE_LINENO = exports.SEMATTRS_CODE_FILEPATH = exports.SEMATTRS_CODE_NAMESPACE = exports.SEMATTRS_CODE_FUNCTION = exports.SEMATTRS_THREAD_NAME = exports.SEMATTRS_THREAD_ID = exports.SEMATTRS_ENDUSER_SCOPE = exports.SEMATTRS_ENDUSER_ROLE = exports.SEMATTRS_ENDUSER_ID = exports.SEMATTRS_PEER_SERVICE = void 0; + exports.DBSYSTEMVALUES_FILEMAKER = exports.DBSYSTEMVALUES_DERBY = exports.DBSYSTEMVALUES_FIREBIRD = exports.DBSYSTEMVALUES_ADABAS = exports.DBSYSTEMVALUES_CACHE = exports.DBSYSTEMVALUES_EDB = exports.DBSYSTEMVALUES_FIRSTSQL = exports.DBSYSTEMVALUES_INGRES = exports.DBSYSTEMVALUES_HANADB = exports.DBSYSTEMVALUES_MAXDB = exports.DBSYSTEMVALUES_PROGRESS = exports.DBSYSTEMVALUES_HSQLDB = exports.DBSYSTEMVALUES_CLOUDSCAPE = exports.DBSYSTEMVALUES_HIVE = exports.DBSYSTEMVALUES_REDSHIFT = exports.DBSYSTEMVALUES_POSTGRESQL = exports.DBSYSTEMVALUES_DB2 = exports.DBSYSTEMVALUES_ORACLE = exports.DBSYSTEMVALUES_MYSQL = exports.DBSYSTEMVALUES_MSSQL = exports.DBSYSTEMVALUES_OTHER_SQL = exports.SemanticAttributes = exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_ID = exports.SEMATTRS_MESSAGE_TYPE = exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = exports.SEMATTRS_RPC_JSONRPC_VERSION = exports.SEMATTRS_RPC_GRPC_STATUS_CODE = exports.SEMATTRS_RPC_METHOD = exports.SEMATTRS_RPC_SERVICE = exports.SEMATTRS_RPC_SYSTEM = exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = exports.SEMATTRS_MESSAGING_CONSUMER_ID = exports.SEMATTRS_MESSAGING_OPERATION = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = exports.SEMATTRS_MESSAGING_CONVERSATION_ID = exports.SEMATTRS_MESSAGING_MESSAGE_ID = exports.SEMATTRS_MESSAGING_URL = exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = exports.SEMATTRS_MESSAGING_PROTOCOL = exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = void 0; + exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = exports.FaasDocumentOperationValues = exports.FAASDOCUMENTOPERATIONVALUES_DELETE = exports.FAASDOCUMENTOPERATIONVALUES_EDIT = exports.FAASDOCUMENTOPERATIONVALUES_INSERT = exports.FaasTriggerValues = exports.FAASTRIGGERVALUES_OTHER = exports.FAASTRIGGERVALUES_TIMER = exports.FAASTRIGGERVALUES_PUBSUB = exports.FAASTRIGGERVALUES_HTTP = exports.FAASTRIGGERVALUES_DATASOURCE = exports.DbCassandraConsistencyLevelValues = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = exports.DbSystemValues = exports.DBSYSTEMVALUES_COCKROACHDB = exports.DBSYSTEMVALUES_MEMCACHED = exports.DBSYSTEMVALUES_ELASTICSEARCH = exports.DBSYSTEMVALUES_GEODE = exports.DBSYSTEMVALUES_NEO4J = exports.DBSYSTEMVALUES_DYNAMODB = exports.DBSYSTEMVALUES_COSMOSDB = exports.DBSYSTEMVALUES_COUCHDB = exports.DBSYSTEMVALUES_COUCHBASE = exports.DBSYSTEMVALUES_REDIS = exports.DBSYSTEMVALUES_MONGODB = exports.DBSYSTEMVALUES_HBASE = exports.DBSYSTEMVALUES_CASSANDRA = exports.DBSYSTEMVALUES_COLDFUSION = exports.DBSYSTEMVALUES_H2 = exports.DBSYSTEMVALUES_VERTICA = exports.DBSYSTEMVALUES_TERADATA = exports.DBSYSTEMVALUES_SYBASE = exports.DBSYSTEMVALUES_SQLITE = exports.DBSYSTEMVALUES_POINTBASE = exports.DBSYSTEMVALUES_PERVASIVE = exports.DBSYSTEMVALUES_NETEZZA = exports.DBSYSTEMVALUES_MARIADB = exports.DBSYSTEMVALUES_INTERBASE = exports.DBSYSTEMVALUES_INSTANTDB = exports.DBSYSTEMVALUES_INFORMIX = void 0; + exports.MESSAGINGOPERATIONVALUES_RECEIVE = exports.MessagingDestinationKindValues = exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = exports.HttpFlavorValues = exports.HTTPFLAVORVALUES_QUIC = exports.HTTPFLAVORVALUES_SPDY = exports.HTTPFLAVORVALUES_HTTP_2_0 = exports.HTTPFLAVORVALUES_HTTP_1_1 = exports.HTTPFLAVORVALUES_HTTP_1_0 = exports.NetHostConnectionSubtypeValues = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = exports.NetHostConnectionTypeValues = exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = exports.NETHOSTCONNECTIONTYPEVALUES_CELL = exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = exports.NetTransportValues = exports.NETTRANSPORTVALUES_OTHER = exports.NETTRANSPORTVALUES_INPROC = exports.NETTRANSPORTVALUES_PIPE = exports.NETTRANSPORTVALUES_UNIX = exports.NETTRANSPORTVALUES_IP = exports.NETTRANSPORTVALUES_IP_UDP = exports.NETTRANSPORTVALUES_IP_TCP = exports.FaasInvokedProviderValues = exports.FAASINVOKEDPROVIDERVALUES_GCP = exports.FAASINVOKEDPROVIDERVALUES_AZURE = exports.FAASINVOKEDPROVIDERVALUES_AWS = void 0; + exports.MessageTypeValues = exports.MESSAGETYPEVALUES_RECEIVED = exports.MESSAGETYPEVALUES_SENT = exports.RpcGrpcStatusCodeValues = exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = exports.RPCGRPCSTATUSCODEVALUES_ABORTED = exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = exports.RPCGRPCSTATUSCODEVALUES_OK = exports.MessagingOperationValues = exports.MESSAGINGOPERATIONVALUES_PROCESS = void 0; + var utils_1 = require_utils(); + var TMP_AWS_LAMBDA_INVOKED_ARN = "aws.lambda.invoked_arn"; + var TMP_DB_SYSTEM = "db.system"; + var TMP_DB_CONNECTION_STRING = "db.connection_string"; + var TMP_DB_USER = "db.user"; + var TMP_DB_JDBC_DRIVER_CLASSNAME = "db.jdbc.driver_classname"; + var TMP_DB_NAME = "db.name"; + var TMP_DB_STATEMENT = "db.statement"; + var TMP_DB_OPERATION = "db.operation"; + var TMP_DB_MSSQL_INSTANCE_NAME = "db.mssql.instance_name"; + var TMP_DB_CASSANDRA_KEYSPACE = "db.cassandra.keyspace"; + var TMP_DB_CASSANDRA_PAGE_SIZE = "db.cassandra.page_size"; + var TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = "db.cassandra.consistency_level"; + var TMP_DB_CASSANDRA_TABLE = "db.cassandra.table"; + var TMP_DB_CASSANDRA_IDEMPOTENCE = "db.cassandra.idempotence"; + var TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = "db.cassandra.speculative_execution_count"; + var TMP_DB_CASSANDRA_COORDINATOR_ID = "db.cassandra.coordinator.id"; + var TMP_DB_CASSANDRA_COORDINATOR_DC = "db.cassandra.coordinator.dc"; + var TMP_DB_HBASE_NAMESPACE = "db.hbase.namespace"; + var TMP_DB_REDIS_DATABASE_INDEX = "db.redis.database_index"; + var TMP_DB_MONGODB_COLLECTION = "db.mongodb.collection"; + var TMP_DB_SQL_TABLE = "db.sql.table"; + var TMP_EXCEPTION_TYPE = "exception.type"; + var TMP_EXCEPTION_MESSAGE = "exception.message"; + var TMP_EXCEPTION_STACKTRACE = "exception.stacktrace"; + var TMP_EXCEPTION_ESCAPED = "exception.escaped"; + var TMP_FAAS_TRIGGER = "faas.trigger"; + var TMP_FAAS_EXECUTION = "faas.execution"; + var TMP_FAAS_DOCUMENT_COLLECTION = "faas.document.collection"; + var TMP_FAAS_DOCUMENT_OPERATION = "faas.document.operation"; + var TMP_FAAS_DOCUMENT_TIME = "faas.document.time"; + var TMP_FAAS_DOCUMENT_NAME = "faas.document.name"; + var TMP_FAAS_TIME = "faas.time"; + var TMP_FAAS_CRON = "faas.cron"; + var TMP_FAAS_COLDSTART = "faas.coldstart"; + var TMP_FAAS_INVOKED_NAME = "faas.invoked_name"; + var TMP_FAAS_INVOKED_PROVIDER = "faas.invoked_provider"; + var TMP_FAAS_INVOKED_REGION = "faas.invoked_region"; + var TMP_NET_TRANSPORT = "net.transport"; + var TMP_NET_PEER_IP = "net.peer.ip"; + var TMP_NET_PEER_PORT = "net.peer.port"; + var TMP_NET_PEER_NAME = "net.peer.name"; + var TMP_NET_HOST_IP = "net.host.ip"; + var TMP_NET_HOST_PORT = "net.host.port"; + var TMP_NET_HOST_NAME = "net.host.name"; + var TMP_NET_HOST_CONNECTION_TYPE = "net.host.connection.type"; + var TMP_NET_HOST_CONNECTION_SUBTYPE = "net.host.connection.subtype"; + var TMP_NET_HOST_CARRIER_NAME = "net.host.carrier.name"; + var TMP_NET_HOST_CARRIER_MCC = "net.host.carrier.mcc"; + var TMP_NET_HOST_CARRIER_MNC = "net.host.carrier.mnc"; + var TMP_NET_HOST_CARRIER_ICC = "net.host.carrier.icc"; + var TMP_PEER_SERVICE = "peer.service"; + var TMP_ENDUSER_ID = "enduser.id"; + var TMP_ENDUSER_ROLE = "enduser.role"; + var TMP_ENDUSER_SCOPE = "enduser.scope"; + var TMP_THREAD_ID = "thread.id"; + var TMP_THREAD_NAME = "thread.name"; + var TMP_CODE_FUNCTION = "code.function"; + var TMP_CODE_NAMESPACE = "code.namespace"; + var TMP_CODE_FILEPATH = "code.filepath"; + var TMP_CODE_LINENO = "code.lineno"; + var TMP_HTTP_METHOD = "http.method"; + var TMP_HTTP_URL = "http.url"; + var TMP_HTTP_TARGET = "http.target"; + var TMP_HTTP_HOST = "http.host"; + var TMP_HTTP_SCHEME = "http.scheme"; + var TMP_HTTP_STATUS_CODE = "http.status_code"; + var TMP_HTTP_FLAVOR = "http.flavor"; + var TMP_HTTP_USER_AGENT = "http.user_agent"; + var TMP_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length"; + var TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed"; + var TMP_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length"; + var TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed"; + var TMP_HTTP_SERVER_NAME = "http.server_name"; + var TMP_HTTP_ROUTE = "http.route"; + var TMP_HTTP_CLIENT_IP = "http.client_ip"; + var TMP_AWS_DYNAMODB_TABLE_NAMES = "aws.dynamodb.table_names"; + var TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = "aws.dynamodb.consumed_capacity"; + var TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = "aws.dynamodb.item_collection_metrics"; + var TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = "aws.dynamodb.provisioned_read_capacity"; + var TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = "aws.dynamodb.provisioned_write_capacity"; + var TMP_AWS_DYNAMODB_CONSISTENT_READ = "aws.dynamodb.consistent_read"; + var TMP_AWS_DYNAMODB_PROJECTION = "aws.dynamodb.projection"; + var TMP_AWS_DYNAMODB_LIMIT = "aws.dynamodb.limit"; + var TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = "aws.dynamodb.attributes_to_get"; + var TMP_AWS_DYNAMODB_INDEX_NAME = "aws.dynamodb.index_name"; + var TMP_AWS_DYNAMODB_SELECT = "aws.dynamodb.select"; + var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = "aws.dynamodb.global_secondary_indexes"; + var TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = "aws.dynamodb.local_secondary_indexes"; + var TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = "aws.dynamodb.exclusive_start_table"; + var TMP_AWS_DYNAMODB_TABLE_COUNT = "aws.dynamodb.table_count"; + var TMP_AWS_DYNAMODB_SCAN_FORWARD = "aws.dynamodb.scan_forward"; + var TMP_AWS_DYNAMODB_SEGMENT = "aws.dynamodb.segment"; + var TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = "aws.dynamodb.total_segments"; + var TMP_AWS_DYNAMODB_COUNT = "aws.dynamodb.count"; + var TMP_AWS_DYNAMODB_SCANNED_COUNT = "aws.dynamodb.scanned_count"; + var TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = "aws.dynamodb.attribute_definitions"; + var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = "aws.dynamodb.global_secondary_index_updates"; + var TMP_MESSAGING_SYSTEM = "messaging.system"; + var TMP_MESSAGING_DESTINATION = "messaging.destination"; + var TMP_MESSAGING_DESTINATION_KIND = "messaging.destination_kind"; + var TMP_MESSAGING_TEMP_DESTINATION = "messaging.temp_destination"; + var TMP_MESSAGING_PROTOCOL = "messaging.protocol"; + var TMP_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version"; + var TMP_MESSAGING_URL = "messaging.url"; + var TMP_MESSAGING_MESSAGE_ID = "messaging.message_id"; + var TMP_MESSAGING_CONVERSATION_ID = "messaging.conversation_id"; + var TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = "messaging.message_payload_size_bytes"; + var TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = "messaging.message_payload_compressed_size_bytes"; + var TMP_MESSAGING_OPERATION = "messaging.operation"; + var TMP_MESSAGING_CONSUMER_ID = "messaging.consumer_id"; + var TMP_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key"; + var TMP_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message_key"; + var TMP_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer_group"; + var TMP_MESSAGING_KAFKA_CLIENT_ID = "messaging.kafka.client_id"; + var TMP_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition"; + var TMP_MESSAGING_KAFKA_TOMBSTONE = "messaging.kafka.tombstone"; + var TMP_RPC_SYSTEM = "rpc.system"; + var TMP_RPC_SERVICE = "rpc.service"; + var TMP_RPC_METHOD = "rpc.method"; + var TMP_RPC_GRPC_STATUS_CODE = "rpc.grpc.status_code"; + var TMP_RPC_JSONRPC_VERSION = "rpc.jsonrpc.version"; + var TMP_RPC_JSONRPC_REQUEST_ID = "rpc.jsonrpc.request_id"; + var TMP_RPC_JSONRPC_ERROR_CODE = "rpc.jsonrpc.error_code"; + var TMP_RPC_JSONRPC_ERROR_MESSAGE = "rpc.jsonrpc.error_message"; + var TMP_MESSAGE_TYPE = "message.type"; + var TMP_MESSAGE_ID = "message.id"; + var TMP_MESSAGE_COMPRESSED_SIZE = "message.compressed_size"; + var TMP_MESSAGE_UNCOMPRESSED_SIZE = "message.uncompressed_size"; + /** + * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable). + * + * Note: This may be different from `faas.id` if an alias is involved. + * + * @deprecated Use ATTR_AWS_LAMBDA_INVOKED_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use ATTR_DB_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; + /** + * The connection string used to connect to the database. It is recommended to remove embedded credentials. + * + * @deprecated Use ATTR_DB_CONNECTION_STRING in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; + /** + * Username for accessing the database. + * + * @deprecated Use ATTR_DB_USER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_USER = TMP_DB_USER; + /** + * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect. + * + * @deprecated Use ATTR_DB_JDBC_DRIVER_CLASSNAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; + /** + * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails). + * + * Note: In some SQL databases, the database name to be used is called "schema name". + * + * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_NAME = TMP_DB_NAME; + /** + * The database statement being executed. + * + * Note: The value may be sanitized to exclude sensitive information. + * + * @deprecated Use ATTR_DB_STATEMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; + /** + * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword. + * + * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted. + * + * @deprecated Use ATTR_DB_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; + /** + * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance. + * + * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard). + * + * @deprecated Use ATTR_DB_MSSQL_INSTANCE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; + /** + * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute. + * + * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; + /** + * The fetch size used for paging, i.e. how many rows will be returned at once. + * + * @deprecated Use ATTR_DB_CASSANDRA_PAGE_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use ATTR_DB_CASSANDRA_CONSISTENCY_LEVEL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; + /** + * The name of the primary table that the operation is acting upon, including the schema name (if applicable). + * + * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. + * + * @deprecated Use ATTR_DB_CASSANDRA_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; + /** + * Whether or not the query is idempotent. + * + * @deprecated Use ATTR_DB_CASSANDRA_IDEMPOTENCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; + /** + * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively. + * + * @deprecated Use ATTR_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; + /** + * The ID of the coordinating node for a query. + * + * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; + /** + * The data center of the coordinating node for a query. + * + * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_DC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; + /** + * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute. + * + * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; + /** + * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute. + * + * @deprecated Use ATTR_DB_REDIS_DATABASE_INDEX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; + /** + * The collection being accessed within the database stated in `db.name`. + * + * @deprecated Use ATTR_DB_MONGODB_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; + /** + * The name of the primary table that the operation is acting upon, including the schema name (if applicable). + * + * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. + * + * @deprecated Use ATTR_DB_SQL_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; + /** + * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. + * + * @deprecated Use ATTR_EXCEPTION_TYPE. + */ + exports.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; + /** + * The exception message. + * + * @deprecated Use ATTR_EXCEPTION_MESSAGE. + */ + exports.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; + /** + * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. + * + * @deprecated Use ATTR_EXCEPTION_STACKTRACE. + */ + exports.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; + /** + * SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span. + * + * Note: An exception is considered to have escaped (or left) the scope of a span, + if that span is ended while the exception is still logically "in flight". + This may be actually "in flight" in some languages (e.g. if the exception + is passed to a Context manager's `__exit__` method in Python) but will + usually be caught at the point of recording the exception in most languages. + + It is usually not possible to determine at the point where an exception is thrown + whether it will escape the scope of a span. + However, it is trivial to know that an exception + will escape, if one checks for an active exception just before ending the span, + as done in the [example above](#exception-end-example). + + It follows that an exception may still escape the scope of the span + even if the `exception.escaped` attribute was not set or set to false, + since the event might have been recorded at a time where it was not + clear whether the exception will escape. + * + * @deprecated Use ATTR_EXCEPTION_ESCAPED. + */ + exports.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; + /** + * Type of the trigger on which the function is executed. + * + * @deprecated Use ATTR_FAAS_TRIGGER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; + /** + * The execution ID of the current function execution. + * + * @deprecated Use ATTR_FAAS_INVOCATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; + /** + * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name. + * + * @deprecated Use ATTR_FAAS_DOCUMENT_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; + /** + * Describes the type of the operation that was performed on the data. + * + * @deprecated Use ATTR_FAAS_DOCUMENT_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; + /** + * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). + * + * @deprecated Use ATTR_FAAS_DOCUMENT_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; + /** + * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name. + * + * @deprecated Use ATTR_FAAS_DOCUMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; + /** + * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). + * + * @deprecated Use ATTR_FAAS_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; + /** + * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). + * + * @deprecated Use ATTR_FAAS_CRON in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; + /** + * A boolean that is true if the serverless function is executed for the first time (aka cold-start). + * + * @deprecated Use ATTR_FAAS_COLDSTART in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; + /** + * The name of the invoked function. + * + * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function. + * + * @deprecated Use ATTR_FAAS_INVOKED_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; + /** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use ATTR_FAAS_INVOKED_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; + /** + * The cloud region of the invoked function. + * + * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function. + * + * @deprecated Use ATTR_FAAS_INVOKED_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; + /** + * Transport protocol used. See note below. + * + * @deprecated Use ATTR_NET_TRANSPORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; + /** + * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6). + * + * @deprecated Use ATTR_NET_PEER_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; + /** + * Remote port number. + * + * @deprecated Use ATTR_NET_PEER_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; + /** + * Remote hostname or similar, see note below. + * + * @deprecated Use ATTR_NET_PEER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; + /** + * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host. + * + * @deprecated Use ATTR_NET_HOST_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; + /** + * Like `net.peer.port` but for the host port. + * + * @deprecated Use ATTR_NET_HOST_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; + /** + * Local hostname or similar, see note below. + * + * @deprecated Use ATTR_NET_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; + /** + * The internet connection type currently being used by the host. + * + * @deprecated Use ATTR_NETWORK_CONNECTION_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use ATTR_NETWORK_CONNECTION_SUBTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; + /** + * The name of the mobile carrier. + * + * @deprecated Use ATTR_NETWORK_CARRIER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; + /** + * The mobile carrier country code. + * + * @deprecated Use ATTR_NETWORK_CARRIER_MCC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; + /** + * The mobile carrier network code. + * + * @deprecated Use ATTR_NETWORK_CARRIER_MNC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; + /** + * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network. + * + * @deprecated Use ATTR_NETWORK_CARRIER_ICC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; + /** + * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any. + * + * @deprecated Use ATTR_PEER_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; + /** + * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system. + * + * @deprecated Use ATTR_ENDUSER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; + /** + * Actual/assumed role the client is making the request under extracted from token or application security context. + * + * @deprecated Use ATTR_ENDUSER_ROLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; + /** + * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). + * + * @deprecated Use ATTR_ENDUSER_SCOPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; + /** + * Current "managed" thread ID (as opposed to OS thread ID). + * + * @deprecated Use ATTR_THREAD_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_THREAD_ID = TMP_THREAD_ID; + /** + * Current thread name. + * + * @deprecated Use ATTR_THREAD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; + /** + * The method or function name, or equivalent (usually rightmost part of the code unit's name). + * + * @deprecated Use ATTR_CODE_FUNCTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; + /** + * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit. + * + * @deprecated Use ATTR_CODE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; + /** + * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). + * + * @deprecated Use ATTR_CODE_FILEPATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; + /** + * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`. + * + * @deprecated Use ATTR_CODE_LINENO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; + /** + * HTTP request method. + * + * @deprecated Use ATTR_HTTP_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; + /** + * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless. + * + * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`. + * + * @deprecated Use ATTR_HTTP_URL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_URL = TMP_HTTP_URL; + /** + * The full request target as passed in a HTTP request line or equivalent. + * + * @deprecated Use ATTR_HTTP_TARGET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; + /** + * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note. + * + * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set. + * + * @deprecated Use ATTR_HTTP_HOST in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; + /** + * The URI scheme identifying the used protocol. + * + * @deprecated Use ATTR_HTTP_SCHEME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; + /** + * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). + * + * @deprecated Use ATTR_HTTP_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; + /** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use ATTR_HTTP_FLAVOR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; + /** + * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client. + * + * @deprecated Use ATTR_HTTP_USER_AGENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; + /** + * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. + * + * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; + /** + * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used. + * + * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; + /** + * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. + * + * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; + /** + * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used. + * + * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; + /** + * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead). + * + * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available. + * + * @deprecated Use ATTR_HTTP_SERVER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; + /** + * The matched route (path template). + * + * @deprecated Use ATTR_HTTP_ROUTE. + */ + exports.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; + /** + * The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). + * + * Note: This is not necessarily the same as `net.peer.ip`, which would + identify the network-level peer, which may be a proxy. + + This attribute should be set when a source of information different + from the one used for `net.peer.ip`, is available even if that other + source just confirms the same value as `net.peer.ip`. + Rationale: For `net.peer.ip`, one typically does not know if it + comes from a proxy, reverse proxy, or the actual client. Setting + `http.client_ip` when it's the same as `net.peer.ip` means that + one is at least somewhat confident that the address is not that of + the closest proxy. + * + * @deprecated Use ATTR_HTTP_CLIENT_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; + /** + * The keys in the `RequestItems` object field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; + /** + * The JSON-serialized value of each item in the `ConsumedCapacity` response field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; + /** + * The JSON-serialized value of the `ItemCollectionMetrics` response field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; + /** + * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; + /** + * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; + /** + * The value of the `ConsistentRead` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_CONSISTENT_READ in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; + /** + * The value of the `ProjectionExpression` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_PROJECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; + /** + * The value of the `Limit` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_LIMIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; + /** + * The value of the `AttributesToGet` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTES_TO_GET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; + /** + * The value of the `IndexName` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_INDEX_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; + /** + * The value of the `Select` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_SELECT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; + /** + * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; + /** + * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; + /** + * The value of the `ExclusiveStartTableName` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; + /** + * The the number of items in the `TableNames` response parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; + /** + * The value of the `ScanIndexForward` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_SCAN_FORWARD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; + /** + * The value of the `Segment` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_SEGMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; + /** + * The value of the `TotalSegments` request parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; + /** + * The value of the `Count` response parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; + /** + * The value of the `ScannedCount` response parameter. + * + * @deprecated Use ATTR_AWS_DYNAMODB_SCANNED_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; + /** + * The JSON-serialized value of each item in the `AttributeDefinitions` request field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; + /** + * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field. + * + * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; + /** + * A string identifying the messaging system. + * + * @deprecated Use ATTR_MESSAGING_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; + /** + * The message destination name. This might be equal to the span name but is required nevertheless. + * + * @deprecated Use ATTR_MESSAGING_DESTINATION_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; + /** + * The kind of message destination. + * + * @deprecated Removed in semconv v1.20.0. + */ + exports.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; + /** + * A boolean that is true if the message destination is temporary. + * + * @deprecated Use ATTR_MESSAGING_DESTINATION_TEMPORARY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; + /** + * The name of the transport protocol. + * + * @deprecated Use ATTR_NETWORK_PROTOCOL_NAME. + */ + exports.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; + /** + * The version of the transport protocol. + * + * @deprecated Use ATTR_NETWORK_PROTOCOL_VERSION. + */ + exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; + /** + * Connection string. + * + * @deprecated Removed in semconv v1.17.0. + */ + exports.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; + /** + * A value used by the messaging system as an identifier for the message, represented as a string. + * + * @deprecated Use ATTR_MESSAGING_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; + /** + * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID". + * + * @deprecated Use ATTR_MESSAGING_MESSAGE_CONVERSATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; + /** + * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported. + * + * @deprecated Use ATTR_MESSAGING_MESSAGE_BODY_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; + /** + * The compressed size of the message payload in bytes. + * + * @deprecated Removed in semconv v1.22.0. + */ + exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; + /** + * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. + * + * @deprecated Use ATTR_MESSAGING_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; + /** + * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message. + * + * @deprecated Removed in semconv v1.21.0. + */ + exports.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; + /** + * RabbitMQ message routing key. + * + * @deprecated Use ATTR_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; + /** + * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set. + * + * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value. + * + * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; + /** + * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers. + * + * @deprecated Use ATTR_MESSAGING_KAFKA_CONSUMER_GROUP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; + /** + * Client Id for the Consumer or Producer that is handling the message. + * + * @deprecated Use ATTR_MESSAGING_CLIENT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; + /** + * Partition the message is sent to. + * + * @deprecated Use ATTR_MESSAGING_KAFKA_DESTINATION_PARTITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; + /** + * A boolean that is true if the message is a tombstone. + * + * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; + /** + * A string identifying the remoting system. + * + * @deprecated Use ATTR_RPC_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; + /** + * The full (logical) name of the service being called, including its package name, if applicable. + * + * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side). + * + * @deprecated Use ATTR_RPC_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; + /** + * The name of the (logical) method being called, must be equal to the $method part in the span name. + * + * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side). + * + * @deprecated Use ATTR_RPC_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use ATTR_RPC_GRPC_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; + /** + * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted. + * + * @deprecated Use ATTR_RPC_JSONRPC_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; + /** + * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification. + * + * @deprecated Use ATTR_RPC_JSONRPC_REQUEST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; + /** + * `error.code` property of response if it is an error response. + * + * @deprecated Use ATTR_RPC_JSONRPC_ERROR_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; + /** + * `error.message` property of response if it is an error response. + * + * @deprecated Use ATTR_RPC_JSONRPC_ERROR_MESSAGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; + /** + * Whether this is a received or sent message. + * + * @deprecated Use ATTR_MESSAGE_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; + /** + * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message. + * + * Note: This way we guarantee that the values will be consistent between different implementations. + * + * @deprecated Use ATTR_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; + /** + * Compressed size of the message in bytes. + * + * @deprecated Use ATTR_MESSAGE_COMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; + /** + * Uncompressed size of the message in bytes. + * + * @deprecated Use ATTR_MESSAGE_UNCOMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; + /** + * Create exported Value Map for SemanticAttributes values + * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification + */ + exports.SemanticAttributes = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_AWS_LAMBDA_INVOKED_ARN, + TMP_DB_SYSTEM, + TMP_DB_CONNECTION_STRING, + TMP_DB_USER, + TMP_DB_JDBC_DRIVER_CLASSNAME, + TMP_DB_NAME, + TMP_DB_STATEMENT, + TMP_DB_OPERATION, + TMP_DB_MSSQL_INSTANCE_NAME, + TMP_DB_CASSANDRA_KEYSPACE, + TMP_DB_CASSANDRA_PAGE_SIZE, + TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, + TMP_DB_CASSANDRA_TABLE, + TMP_DB_CASSANDRA_IDEMPOTENCE, + TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, + TMP_DB_CASSANDRA_COORDINATOR_ID, + TMP_DB_CASSANDRA_COORDINATOR_DC, + TMP_DB_HBASE_NAMESPACE, + TMP_DB_REDIS_DATABASE_INDEX, + TMP_DB_MONGODB_COLLECTION, + TMP_DB_SQL_TABLE, + TMP_EXCEPTION_TYPE, + TMP_EXCEPTION_MESSAGE, + TMP_EXCEPTION_STACKTRACE, + TMP_EXCEPTION_ESCAPED, + TMP_FAAS_TRIGGER, + TMP_FAAS_EXECUTION, + TMP_FAAS_DOCUMENT_COLLECTION, + TMP_FAAS_DOCUMENT_OPERATION, + TMP_FAAS_DOCUMENT_TIME, + TMP_FAAS_DOCUMENT_NAME, + TMP_FAAS_TIME, + TMP_FAAS_CRON, + TMP_FAAS_COLDSTART, + TMP_FAAS_INVOKED_NAME, + TMP_FAAS_INVOKED_PROVIDER, + TMP_FAAS_INVOKED_REGION, + TMP_NET_TRANSPORT, + TMP_NET_PEER_IP, + TMP_NET_PEER_PORT, + TMP_NET_PEER_NAME, + TMP_NET_HOST_IP, + TMP_NET_HOST_PORT, + TMP_NET_HOST_NAME, + TMP_NET_HOST_CONNECTION_TYPE, + TMP_NET_HOST_CONNECTION_SUBTYPE, + TMP_NET_HOST_CARRIER_NAME, + TMP_NET_HOST_CARRIER_MCC, + TMP_NET_HOST_CARRIER_MNC, + TMP_NET_HOST_CARRIER_ICC, + TMP_PEER_SERVICE, + TMP_ENDUSER_ID, + TMP_ENDUSER_ROLE, + TMP_ENDUSER_SCOPE, + TMP_THREAD_ID, + TMP_THREAD_NAME, + TMP_CODE_FUNCTION, + TMP_CODE_NAMESPACE, + TMP_CODE_FILEPATH, + TMP_CODE_LINENO, + TMP_HTTP_METHOD, + TMP_HTTP_URL, + TMP_HTTP_TARGET, + TMP_HTTP_HOST, + TMP_HTTP_SCHEME, + TMP_HTTP_STATUS_CODE, + TMP_HTTP_FLAVOR, + TMP_HTTP_USER_AGENT, + TMP_HTTP_REQUEST_CONTENT_LENGTH, + TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_RESPONSE_CONTENT_LENGTH, + TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_SERVER_NAME, + TMP_HTTP_ROUTE, + TMP_HTTP_CLIENT_IP, + TMP_AWS_DYNAMODB_TABLE_NAMES, + TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, + TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, + TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, + TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, + TMP_AWS_DYNAMODB_CONSISTENT_READ, + TMP_AWS_DYNAMODB_PROJECTION, + TMP_AWS_DYNAMODB_LIMIT, + TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, + TMP_AWS_DYNAMODB_INDEX_NAME, + TMP_AWS_DYNAMODB_SELECT, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, + TMP_AWS_DYNAMODB_TABLE_COUNT, + TMP_AWS_DYNAMODB_SCAN_FORWARD, + TMP_AWS_DYNAMODB_SEGMENT, + TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, + TMP_AWS_DYNAMODB_COUNT, + TMP_AWS_DYNAMODB_SCANNED_COUNT, + TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, + TMP_MESSAGING_SYSTEM, + TMP_MESSAGING_DESTINATION, + TMP_MESSAGING_DESTINATION_KIND, + TMP_MESSAGING_TEMP_DESTINATION, + TMP_MESSAGING_PROTOCOL, + TMP_MESSAGING_PROTOCOL_VERSION, + TMP_MESSAGING_URL, + TMP_MESSAGING_MESSAGE_ID, + TMP_MESSAGING_CONVERSATION_ID, + TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, + TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, + TMP_MESSAGING_OPERATION, + TMP_MESSAGING_CONSUMER_ID, + TMP_MESSAGING_RABBITMQ_ROUTING_KEY, + TMP_MESSAGING_KAFKA_MESSAGE_KEY, + TMP_MESSAGING_KAFKA_CONSUMER_GROUP, + TMP_MESSAGING_KAFKA_CLIENT_ID, + TMP_MESSAGING_KAFKA_PARTITION, + TMP_MESSAGING_KAFKA_TOMBSTONE, + TMP_RPC_SYSTEM, + TMP_RPC_SERVICE, + TMP_RPC_METHOD, + TMP_RPC_GRPC_STATUS_CODE, + TMP_RPC_JSONRPC_VERSION, + TMP_RPC_JSONRPC_REQUEST_ID, + TMP_RPC_JSONRPC_ERROR_CODE, + TMP_RPC_JSONRPC_ERROR_MESSAGE, + TMP_MESSAGE_TYPE, + TMP_MESSAGE_ID, + TMP_MESSAGE_COMPRESSED_SIZE, + TMP_MESSAGE_UNCOMPRESSED_SIZE + ]); + var TMP_DBSYSTEMVALUES_OTHER_SQL = "other_sql"; + var TMP_DBSYSTEMVALUES_MSSQL = "mssql"; + var TMP_DBSYSTEMVALUES_MYSQL = "mysql"; + var TMP_DBSYSTEMVALUES_ORACLE = "oracle"; + var TMP_DBSYSTEMVALUES_DB2 = "db2"; + var TMP_DBSYSTEMVALUES_POSTGRESQL = "postgresql"; + var TMP_DBSYSTEMVALUES_REDSHIFT = "redshift"; + var TMP_DBSYSTEMVALUES_HIVE = "hive"; + var TMP_DBSYSTEMVALUES_CLOUDSCAPE = "cloudscape"; + var TMP_DBSYSTEMVALUES_HSQLDB = "hsqldb"; + var TMP_DBSYSTEMVALUES_PROGRESS = "progress"; + var TMP_DBSYSTEMVALUES_MAXDB = "maxdb"; + var TMP_DBSYSTEMVALUES_HANADB = "hanadb"; + var TMP_DBSYSTEMVALUES_INGRES = "ingres"; + var TMP_DBSYSTEMVALUES_FIRSTSQL = "firstsql"; + var TMP_DBSYSTEMVALUES_EDB = "edb"; + var TMP_DBSYSTEMVALUES_CACHE = "cache"; + var TMP_DBSYSTEMVALUES_ADABAS = "adabas"; + var TMP_DBSYSTEMVALUES_FIREBIRD = "firebird"; + var TMP_DBSYSTEMVALUES_DERBY = "derby"; + var TMP_DBSYSTEMVALUES_FILEMAKER = "filemaker"; + var TMP_DBSYSTEMVALUES_INFORMIX = "informix"; + var TMP_DBSYSTEMVALUES_INSTANTDB = "instantdb"; + var TMP_DBSYSTEMVALUES_INTERBASE = "interbase"; + var TMP_DBSYSTEMVALUES_MARIADB = "mariadb"; + var TMP_DBSYSTEMVALUES_NETEZZA = "netezza"; + var TMP_DBSYSTEMVALUES_PERVASIVE = "pervasive"; + var TMP_DBSYSTEMVALUES_POINTBASE = "pointbase"; + var TMP_DBSYSTEMVALUES_SQLITE = "sqlite"; + var TMP_DBSYSTEMVALUES_SYBASE = "sybase"; + var TMP_DBSYSTEMVALUES_TERADATA = "teradata"; + var TMP_DBSYSTEMVALUES_VERTICA = "vertica"; + var TMP_DBSYSTEMVALUES_H2 = "h2"; + var TMP_DBSYSTEMVALUES_COLDFUSION = "coldfusion"; + var TMP_DBSYSTEMVALUES_CASSANDRA = "cassandra"; + var TMP_DBSYSTEMVALUES_HBASE = "hbase"; + var TMP_DBSYSTEMVALUES_MONGODB = "mongodb"; + var TMP_DBSYSTEMVALUES_REDIS = "redis"; + var TMP_DBSYSTEMVALUES_COUCHBASE = "couchbase"; + var TMP_DBSYSTEMVALUES_COUCHDB = "couchdb"; + var TMP_DBSYSTEMVALUES_COSMOSDB = "cosmosdb"; + var TMP_DBSYSTEMVALUES_DYNAMODB = "dynamodb"; + var TMP_DBSYSTEMVALUES_NEO4J = "neo4j"; + var TMP_DBSYSTEMVALUES_GEODE = "geode"; + var TMP_DBSYSTEMVALUES_ELASTICSEARCH = "elasticsearch"; + var TMP_DBSYSTEMVALUES_MEMCACHED = "memcached"; + var TMP_DBSYSTEMVALUES_COCKROACHDB = "cockroachdb"; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_OTHER_SQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MSSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MYSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_ORACLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_DB2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_POSTGRESQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_REDSHIFT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_HIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_CLOUDSCAPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_HSQLDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_PROGRESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MAXDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_HANADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_INGRES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_FIRSTSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_EDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_CACHE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_ADABAS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_FIREBIRD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_DERBY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_FILEMAKER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_INFORMIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_INSTANTDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_INTERBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MARIADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_NETEZZA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_PERVASIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_POINTBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_SQLITE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_SYBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_TERADATA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_VERTICA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_H2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COLDFUSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_CASSANDRA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_HBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MONGODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_REDIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COUCHBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COUCHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COSMOSDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_DYNAMODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_NEO4J in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_GEODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_ELASTICSEARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_MEMCACHED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; + /** + * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. + * + * @deprecated Use DB_SYSTEM_VALUE_COCKROACHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; + /** + * The constant map of values for DbSystemValues. + * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification. + */ + exports.DbSystemValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_DBSYSTEMVALUES_OTHER_SQL, + TMP_DBSYSTEMVALUES_MSSQL, + TMP_DBSYSTEMVALUES_MYSQL, + TMP_DBSYSTEMVALUES_ORACLE, + TMP_DBSYSTEMVALUES_DB2, + TMP_DBSYSTEMVALUES_POSTGRESQL, + TMP_DBSYSTEMVALUES_REDSHIFT, + TMP_DBSYSTEMVALUES_HIVE, + TMP_DBSYSTEMVALUES_CLOUDSCAPE, + TMP_DBSYSTEMVALUES_HSQLDB, + TMP_DBSYSTEMVALUES_PROGRESS, + TMP_DBSYSTEMVALUES_MAXDB, + TMP_DBSYSTEMVALUES_HANADB, + TMP_DBSYSTEMVALUES_INGRES, + TMP_DBSYSTEMVALUES_FIRSTSQL, + TMP_DBSYSTEMVALUES_EDB, + TMP_DBSYSTEMVALUES_CACHE, + TMP_DBSYSTEMVALUES_ADABAS, + TMP_DBSYSTEMVALUES_FIREBIRD, + TMP_DBSYSTEMVALUES_DERBY, + TMP_DBSYSTEMVALUES_FILEMAKER, + TMP_DBSYSTEMVALUES_INFORMIX, + TMP_DBSYSTEMVALUES_INSTANTDB, + TMP_DBSYSTEMVALUES_INTERBASE, + TMP_DBSYSTEMVALUES_MARIADB, + TMP_DBSYSTEMVALUES_NETEZZA, + TMP_DBSYSTEMVALUES_PERVASIVE, + TMP_DBSYSTEMVALUES_POINTBASE, + TMP_DBSYSTEMVALUES_SQLITE, + TMP_DBSYSTEMVALUES_SYBASE, + TMP_DBSYSTEMVALUES_TERADATA, + TMP_DBSYSTEMVALUES_VERTICA, + TMP_DBSYSTEMVALUES_H2, + TMP_DBSYSTEMVALUES_COLDFUSION, + TMP_DBSYSTEMVALUES_CASSANDRA, + TMP_DBSYSTEMVALUES_HBASE, + TMP_DBSYSTEMVALUES_MONGODB, + TMP_DBSYSTEMVALUES_REDIS, + TMP_DBSYSTEMVALUES_COUCHBASE, + TMP_DBSYSTEMVALUES_COUCHDB, + TMP_DBSYSTEMVALUES_COSMOSDB, + TMP_DBSYSTEMVALUES_DYNAMODB, + TMP_DBSYSTEMVALUES_NEO4J, + TMP_DBSYSTEMVALUES_GEODE, + TMP_DBSYSTEMVALUES_ELASTICSEARCH, + TMP_DBSYSTEMVALUES_MEMCACHED, + TMP_DBSYSTEMVALUES_COCKROACHDB + ]); + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = "all"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = "each_quorum"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = "quorum"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = "local_quorum"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = "one"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = "two"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = "three"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = "local_one"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = "any"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = "serial"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = "local_serial"; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ALL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_EACH_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_TWO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_THREE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ANY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; + /** + * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). + * + * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; + /** + * The constant map of values for DbCassandraConsistencyLevelValues. + * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification. + */ + exports.DbCassandraConsistencyLevelValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL + ]); + var TMP_FAASTRIGGERVALUES_DATASOURCE = "datasource"; + var TMP_FAASTRIGGERVALUES_HTTP = "http"; + var TMP_FAASTRIGGERVALUES_PUBSUB = "pubsub"; + var TMP_FAASTRIGGERVALUES_TIMER = "timer"; + var TMP_FAASTRIGGERVALUES_OTHER = "other"; + /** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_DATASOURCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; + /** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_HTTP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; + /** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_PUBSUB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; + /** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_TIMER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; + /** + * Type of the trigger on which the function is executed. + * + * @deprecated Use FAAS_TRIGGER_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; + /** + * The constant map of values for FaasTriggerValues. + * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification. + */ + exports.FaasTriggerValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_FAASTRIGGERVALUES_DATASOURCE, + TMP_FAASTRIGGERVALUES_HTTP, + TMP_FAASTRIGGERVALUES_PUBSUB, + TMP_FAASTRIGGERVALUES_TIMER, + TMP_FAASTRIGGERVALUES_OTHER + ]); + var TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = "insert"; + var TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = "edit"; + var TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = "delete"; + /** + * Describes the type of the operation that was performed on the data. + * + * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_INSERT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; + /** + * Describes the type of the operation that was performed on the data. + * + * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_EDIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; + /** + * Describes the type of the operation that was performed on the data. + * + * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_DELETE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; + /** + * The constant map of values for FaasDocumentOperationValues. + * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification. + */ + exports.FaasDocumentOperationValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, + TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, + TMP_FAASDOCUMENTOPERATIONVALUES_DELETE + ]); + var TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + var TMP_FAASINVOKEDPROVIDERVALUES_AWS = "aws"; + var TMP_FAASINVOKEDPROVIDERVALUES_AZURE = "azure"; + var TMP_FAASINVOKEDPROVIDERVALUES_GCP = "gcp"; + /** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; + /** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; + /** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; + /** + * The cloud provider of the invoked function. + * + * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. + * + * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; + /** + * The constant map of values for FaasInvokedProviderValues. + * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification. + */ + exports.FaasInvokedProviderValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_FAASINVOKEDPROVIDERVALUES_AWS, + TMP_FAASINVOKEDPROVIDERVALUES_AZURE, + TMP_FAASINVOKEDPROVIDERVALUES_GCP + ]); + var TMP_NETTRANSPORTVALUES_IP_TCP = "ip_tcp"; + var TMP_NETTRANSPORTVALUES_IP_UDP = "ip_udp"; + var TMP_NETTRANSPORTVALUES_IP = "ip"; + var TMP_NETTRANSPORTVALUES_UNIX = "unix"; + var TMP_NETTRANSPORTVALUES_PIPE = "pipe"; + var TMP_NETTRANSPORTVALUES_INPROC = "inproc"; + var TMP_NETTRANSPORTVALUES_OTHER = "other"; + /** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_IP_TCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; + /** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_IP_UDP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; + /** + * Transport protocol used. See note below. + * + * @deprecated Removed in v1.21.0. + */ + exports.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; + /** + * Transport protocol used. See note below. + * + * @deprecated Removed in v1.21.0. + */ + exports.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; + /** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_PIPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; + /** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_INPROC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; + /** + * Transport protocol used. See note below. + * + * @deprecated Use NET_TRANSPORT_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; + /** + * The constant map of values for NetTransportValues. + * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification. + */ + exports.NetTransportValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_NETTRANSPORTVALUES_IP_TCP, + TMP_NETTRANSPORTVALUES_IP_UDP, + TMP_NETTRANSPORTVALUES_IP, + TMP_NETTRANSPORTVALUES_UNIX, + TMP_NETTRANSPORTVALUES_PIPE, + TMP_NETTRANSPORTVALUES_INPROC, + TMP_NETTRANSPORTVALUES_OTHER + ]); + var TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = "wifi"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = "wired"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = "cell"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = "unavailable"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = "unknown"; + /** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIFI in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; + /** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIRED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; + /** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_CELL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; + /** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; + /** + * The internet connection type currently being used by the host. + * + * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; + /** + * The constant map of values for NetHostConnectionTypeValues. + * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification. + */ + exports.NetHostConnectionTypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, + TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, + TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN + ]); + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = "gprs"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = "edge"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = "umts"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = "cdma"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = "evdo_0"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = "evdo_a"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = "cdma2000_1xrtt"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = "hsdpa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = "hsupa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = "hspa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = "iden"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = "evdo_b"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = "lte"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = "ehrpd"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = "hspap"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = "gsm"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = "td_scdma"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = "iwlan"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = "nr"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = "nrnsa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = "lte_ca"; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GPRS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EDGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_UMTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_A in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA2000_1XRTT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSDPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSUPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IDEN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_B in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EHRPD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPAP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GSM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_TD_SCDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IWLAN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NRNSA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; + /** + * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. + * + * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE_CA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; + /** + * The constant map of values for NetHostConnectionSubtypeValues. + * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification. + */ + exports.NetHostConnectionSubtypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA + ]); + var TMP_HTTPFLAVORVALUES_HTTP_1_0 = "1.0"; + var TMP_HTTPFLAVORVALUES_HTTP_1_1 = "1.1"; + var TMP_HTTPFLAVORVALUES_HTTP_2_0 = "2.0"; + var TMP_HTTPFLAVORVALUES_SPDY = "SPDY"; + var TMP_HTTPFLAVORVALUES_QUIC = "QUIC"; + /** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; + /** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_1 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; + /** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_2_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; + /** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_SPDY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; + /** + * Kind of HTTP protocol used. + * + * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. + * + * @deprecated Use HTTP_FLAVOR_VALUE_QUIC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; + /** + * The constant map of values for HttpFlavorValues. + * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification. + */ + exports.HttpFlavorValues = { + HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, + HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, + HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, + SPDY: TMP_HTTPFLAVORVALUES_SPDY, + QUIC: TMP_HTTPFLAVORVALUES_QUIC }; - const extractToDef = (entry) => { - if (entry[1].schema.$ref) return; - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - if (defId) seen.defId = defId; - const schema = seen.schema; - for (const key in schema) delete schema[key]; - schema.$ref = ref; + var TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = "queue"; + var TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = "topic"; + /** + * The kind of message destination. + * + * @deprecated Removed in semconv v1.20.0. + */ + exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; + /** + * The kind of message destination. + * + * @deprecated Removed in semconv v1.20.0. + */ + exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; + /** + * The constant map of values for MessagingDestinationKindValues. + * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification. + */ + exports.MessagingDestinationKindValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC]); + var TMP_MESSAGINGOPERATIONVALUES_RECEIVE = "receive"; + var TMP_MESSAGINGOPERATIONVALUES_PROCESS = "process"; + /** + * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. + * + * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_RECEIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; + /** + * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. + * + * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_PROCESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; + /** + * The constant map of values for MessagingOperationValues. + * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification. + */ + exports.MessagingOperationValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_MESSAGINGOPERATIONVALUES_RECEIVE, TMP_MESSAGINGOPERATIONVALUES_PROCESS]); + var TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; + var TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; + var TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; + var TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; + var TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; + var TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; + var TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; + var TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; + var TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; + var TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; + var TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; + var TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; + var TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; + var TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; + var TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; + var TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; + var TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_CANCELLED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INVALID_ARGUMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DEADLINE_EXCEEDED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_NOT_FOUND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ALREADY_EXISTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_PERMISSION_DENIED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_RESOURCE_EXHAUSTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_FAILED_PRECONDITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ABORTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OUT_OF_RANGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNIMPLEMENTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INTERNAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DATA_LOSS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; + /** + * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. + * + * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAUTHENTICATED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; + /** + * The constant map of values for RpcGrpcStatusCodeValues. + * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification. + */ + exports.RpcGrpcStatusCodeValues = { + OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, + CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, + UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, + INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, + DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, + NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, + ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, + PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, + RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, + FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, + ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, + OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, + UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, + INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, + UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, + DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, + UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED }; - if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); - } - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (schema === entry[0]) { - extractToDef(entry); - continue; - } - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - if (ctx.metadataRegistry.get(entry[0])?.id) { - extractToDef(entry); - continue; - } - if (seen.cycle) { - extractToDef(entry); - continue; - } - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - continue; - } - } - } -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - if (seen.ref === null) return; - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - const ref = seen.ref; - seen.ref = null; - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } else Object.assign(schema, refSchema); - Object.assign(schema, _cached); - if (zodSchema._zod.parent === ref) for (const key in schema) { - if (key === "$ref" || key === "allOf") continue; - if (!(key in _cached)) delete schema[key]; - } - if (refSchema.$ref && refSeen.def) for (const key in schema) { - if (key === "$ref" || key === "allOf") continue; - if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key]; + var TMP_MESSAGETYPEVALUES_SENT = "SENT"; + var TMP_MESSAGETYPEVALUES_RECEIVED = "RECEIVED"; + /** + * Whether this is a received or sent message. + * + * @deprecated Use MESSAGE_TYPE_VALUE_SENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; + /** + * Whether this is a received or sent message. + * + * @deprecated Use MESSAGE_TYPE_VALUE_RECEIVED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; + /** + * The constant map of values for MessageTypeValues. + * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification. + */ + exports.MessageTypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_MESSAGETYPEVALUES_SENT, TMP_MESSAGETYPEVALUES_RECEIVED]); +})); +//#endregion +//#region node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js +var require_trace = /* @__PURE__ */ __commonJSMin(((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { + enumerable: true, + get: function() { + return m[k]; } - } - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema.$ref = parentSeen.schema.$ref; - if (parentSeen.def) for (const key in schema) { - if (key === "$ref" || key === "allOf") continue; - if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key]; - } + }; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = exports && exports.__exportStar || function(m, exports$3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$3, p)) __createBinding(exports$3, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_SemanticAttributes(), exports); +})); +//#endregion +//#region node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js +var require_SemanticResourceAttributes = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SEMRESATTRS_K8S_STATEFULSET_NAME = exports.SEMRESATTRS_K8S_STATEFULSET_UID = exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = exports.SEMRESATTRS_K8S_REPLICASET_NAME = exports.SEMRESATTRS_K8S_REPLICASET_UID = exports.SEMRESATTRS_K8S_CONTAINER_NAME = exports.SEMRESATTRS_K8S_POD_NAME = exports.SEMRESATTRS_K8S_POD_UID = exports.SEMRESATTRS_K8S_NAMESPACE_NAME = exports.SEMRESATTRS_K8S_NODE_UID = exports.SEMRESATTRS_K8S_NODE_NAME = exports.SEMRESATTRS_K8S_CLUSTER_NAME = exports.SEMRESATTRS_HOST_IMAGE_VERSION = exports.SEMRESATTRS_HOST_IMAGE_ID = exports.SEMRESATTRS_HOST_IMAGE_NAME = exports.SEMRESATTRS_HOST_ARCH = exports.SEMRESATTRS_HOST_TYPE = exports.SEMRESATTRS_HOST_NAME = exports.SEMRESATTRS_HOST_ID = exports.SEMRESATTRS_FAAS_MAX_MEMORY = exports.SEMRESATTRS_FAAS_INSTANCE = exports.SEMRESATTRS_FAAS_VERSION = exports.SEMRESATTRS_FAAS_ID = exports.SEMRESATTRS_FAAS_NAME = exports.SEMRESATTRS_DEVICE_MODEL_NAME = exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = exports.SEMRESATTRS_DEVICE_ID = exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = exports.SEMRESATTRS_CONTAINER_RUNTIME = exports.SEMRESATTRS_CONTAINER_ID = exports.SEMRESATTRS_CONTAINER_NAME = exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = exports.SEMRESATTRS_AWS_ECS_TASK_ARN = exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = exports.SEMRESATTRS_CLOUD_PLATFORM = exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = exports.SEMRESATTRS_CLOUD_REGION = exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = exports.SEMRESATTRS_CLOUD_PROVIDER = void 0; + exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = exports.CLOUDPLATFORMVALUES_AZURE_AKS = exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = exports.CLOUDPLATFORMVALUES_AZURE_VM = exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = exports.CLOUDPLATFORMVALUES_AWS_EKS = exports.CLOUDPLATFORMVALUES_AWS_ECS = exports.CLOUDPLATFORMVALUES_AWS_EC2 = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = exports.CloudProviderValues = exports.CLOUDPROVIDERVALUES_GCP = exports.CLOUDPROVIDERVALUES_AZURE = exports.CLOUDPROVIDERVALUES_AWS = exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = exports.SemanticResourceAttributes = exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = exports.SEMRESATTRS_WEBENGINE_VERSION = exports.SEMRESATTRS_WEBENGINE_NAME = exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = exports.SEMRESATTRS_TELEMETRY_SDK_NAME = exports.SEMRESATTRS_SERVICE_VERSION = exports.SEMRESATTRS_SERVICE_INSTANCE_ID = exports.SEMRESATTRS_SERVICE_NAMESPACE = exports.SEMRESATTRS_SERVICE_NAME = exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = exports.SEMRESATTRS_PROCESS_OWNER = exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = exports.SEMRESATTRS_PROCESS_COMMAND_LINE = exports.SEMRESATTRS_PROCESS_COMMAND = exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = exports.SEMRESATTRS_PROCESS_PID = exports.SEMRESATTRS_OS_VERSION = exports.SEMRESATTRS_OS_NAME = exports.SEMRESATTRS_OS_DESCRIPTION = exports.SEMRESATTRS_OS_TYPE = exports.SEMRESATTRS_K8S_CRONJOB_NAME = exports.SEMRESATTRS_K8S_CRONJOB_UID = exports.SEMRESATTRS_K8S_JOB_NAME = exports.SEMRESATTRS_K8S_JOB_UID = exports.SEMRESATTRS_K8S_DAEMONSET_NAME = exports.SEMRESATTRS_K8S_DAEMONSET_UID = void 0; + exports.TelemetrySdkLanguageValues = exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = exports.TELEMETRYSDKLANGUAGEVALUES_PHP = exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = exports.TELEMETRYSDKLANGUAGEVALUES_GO = exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = exports.TELEMETRYSDKLANGUAGEVALUES_CPP = exports.OsTypeValues = exports.OSTYPEVALUES_Z_OS = exports.OSTYPEVALUES_SOLARIS = exports.OSTYPEVALUES_AIX = exports.OSTYPEVALUES_HPUX = exports.OSTYPEVALUES_DRAGONFLYBSD = exports.OSTYPEVALUES_OPENBSD = exports.OSTYPEVALUES_NETBSD = exports.OSTYPEVALUES_FREEBSD = exports.OSTYPEVALUES_DARWIN = exports.OSTYPEVALUES_LINUX = exports.OSTYPEVALUES_WINDOWS = exports.HostArchValues = exports.HOSTARCHVALUES_X86 = exports.HOSTARCHVALUES_PPC64 = exports.HOSTARCHVALUES_PPC32 = exports.HOSTARCHVALUES_IA64 = exports.HOSTARCHVALUES_ARM64 = exports.HOSTARCHVALUES_ARM32 = exports.HOSTARCHVALUES_AMD64 = exports.AwsEcsLaunchtypeValues = exports.AWSECSLAUNCHTYPEVALUES_FARGATE = exports.AWSECSLAUNCHTYPEVALUES_EC2 = exports.CloudPlatformValues = exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = void 0; + var utils_1 = require_utils(); + var TMP_CLOUD_PROVIDER = "cloud.provider"; + var TMP_CLOUD_ACCOUNT_ID = "cloud.account.id"; + var TMP_CLOUD_REGION = "cloud.region"; + var TMP_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone"; + var TMP_CLOUD_PLATFORM = "cloud.platform"; + var TMP_AWS_ECS_CONTAINER_ARN = "aws.ecs.container.arn"; + var TMP_AWS_ECS_CLUSTER_ARN = "aws.ecs.cluster.arn"; + var TMP_AWS_ECS_LAUNCHTYPE = "aws.ecs.launchtype"; + var TMP_AWS_ECS_TASK_ARN = "aws.ecs.task.arn"; + var TMP_AWS_ECS_TASK_FAMILY = "aws.ecs.task.family"; + var TMP_AWS_ECS_TASK_REVISION = "aws.ecs.task.revision"; + var TMP_AWS_EKS_CLUSTER_ARN = "aws.eks.cluster.arn"; + var TMP_AWS_LOG_GROUP_NAMES = "aws.log.group.names"; + var TMP_AWS_LOG_GROUP_ARNS = "aws.log.group.arns"; + var TMP_AWS_LOG_STREAM_NAMES = "aws.log.stream.names"; + var TMP_AWS_LOG_STREAM_ARNS = "aws.log.stream.arns"; + var TMP_CONTAINER_NAME = "container.name"; + var TMP_CONTAINER_ID = "container.id"; + var TMP_CONTAINER_RUNTIME = "container.runtime"; + var TMP_CONTAINER_IMAGE_NAME = "container.image.name"; + var TMP_CONTAINER_IMAGE_TAG = "container.image.tag"; + var TMP_DEPLOYMENT_ENVIRONMENT = "deployment.environment"; + var TMP_DEVICE_ID = "device.id"; + var TMP_DEVICE_MODEL_IDENTIFIER = "device.model.identifier"; + var TMP_DEVICE_MODEL_NAME = "device.model.name"; + var TMP_FAAS_NAME = "faas.name"; + var TMP_FAAS_ID = "faas.id"; + var TMP_FAAS_VERSION = "faas.version"; + var TMP_FAAS_INSTANCE = "faas.instance"; + var TMP_FAAS_MAX_MEMORY = "faas.max_memory"; + var TMP_HOST_ID = "host.id"; + var TMP_HOST_NAME = "host.name"; + var TMP_HOST_TYPE = "host.type"; + var TMP_HOST_ARCH = "host.arch"; + var TMP_HOST_IMAGE_NAME = "host.image.name"; + var TMP_HOST_IMAGE_ID = "host.image.id"; + var TMP_HOST_IMAGE_VERSION = "host.image.version"; + var TMP_K8S_CLUSTER_NAME = "k8s.cluster.name"; + var TMP_K8S_NODE_NAME = "k8s.node.name"; + var TMP_K8S_NODE_UID = "k8s.node.uid"; + var TMP_K8S_NAMESPACE_NAME = "k8s.namespace.name"; + var TMP_K8S_POD_UID = "k8s.pod.uid"; + var TMP_K8S_POD_NAME = "k8s.pod.name"; + var TMP_K8S_CONTAINER_NAME = "k8s.container.name"; + var TMP_K8S_REPLICASET_UID = "k8s.replicaset.uid"; + var TMP_K8S_REPLICASET_NAME = "k8s.replicaset.name"; + var TMP_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; + var TMP_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; + var TMP_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; + var TMP_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; + var TMP_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; + var TMP_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; + var TMP_K8S_JOB_UID = "k8s.job.uid"; + var TMP_K8S_JOB_NAME = "k8s.job.name"; + var TMP_K8S_CRONJOB_UID = "k8s.cronjob.uid"; + var TMP_K8S_CRONJOB_NAME = "k8s.cronjob.name"; + var TMP_OS_TYPE = "os.type"; + var TMP_OS_DESCRIPTION = "os.description"; + var TMP_OS_NAME = "os.name"; + var TMP_OS_VERSION = "os.version"; + var TMP_PROCESS_PID = "process.pid"; + var TMP_PROCESS_EXECUTABLE_NAME = "process.executable.name"; + var TMP_PROCESS_EXECUTABLE_PATH = "process.executable.path"; + var TMP_PROCESS_COMMAND = "process.command"; + var TMP_PROCESS_COMMAND_LINE = "process.command_line"; + var TMP_PROCESS_COMMAND_ARGS = "process.command_args"; + var TMP_PROCESS_OWNER = "process.owner"; + var TMP_PROCESS_RUNTIME_NAME = "process.runtime.name"; + var TMP_PROCESS_RUNTIME_VERSION = "process.runtime.version"; + var TMP_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description"; + var TMP_SERVICE_NAME = "service.name"; + var TMP_SERVICE_NAMESPACE = "service.namespace"; + var TMP_SERVICE_INSTANCE_ID = "service.instance.id"; + var TMP_SERVICE_VERSION = "service.version"; + var TMP_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + var TMP_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + var TMP_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + var TMP_TELEMETRY_AUTO_VERSION = "telemetry.auto.version"; + var TMP_WEBENGINE_NAME = "webengine.name"; + var TMP_WEBENGINE_VERSION = "webengine.version"; + var TMP_WEBENGINE_DESCRIPTION = "webengine.description"; + /** + * Name of the cloud provider. + * + * @deprecated Use ATTR_CLOUD_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; + /** + * The cloud account ID the resource is assigned to. + * + * @deprecated Use ATTR_CLOUD_ACCOUNT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; + /** + * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations). + * + * @deprecated Use ATTR_CLOUD_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; + /** + * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running. + * + * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud. + * + * @deprecated Use ATTR_CLOUD_AVAILABILITY_ZONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use ATTR_CLOUD_PLATFORM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; + /** + * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). + * + * @deprecated Use ATTR_AWS_ECS_CONTAINER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; + /** + * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). + * + * @deprecated Use ATTR_AWS_ECS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; + /** + * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. + * + * @deprecated Use ATTR_AWS_ECS_LAUNCHTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; + /** + * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). + * + * @deprecated Use ATTR_AWS_ECS_TASK_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; + /** + * The task definition family this task definition is a member of. + * + * @deprecated Use ATTR_AWS_ECS_TASK_FAMILY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; + /** + * The revision for this task definition. + * + * @deprecated Use ATTR_AWS_ECS_TASK_REVISION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; + /** + * The ARN of an EKS cluster. + * + * @deprecated Use ATTR_AWS_EKS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; + /** + * The name(s) of the AWS log group(s) an application is writing to. + * + * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group. + * + * @deprecated Use ATTR_AWS_LOG_GROUP_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; + /** + * The Amazon Resource Name(s) (ARN) of the AWS log group(s). + * + * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). + * + * @deprecated Use ATTR_AWS_LOG_GROUP_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; + /** + * The name(s) of the AWS log stream(s) an application is writing to. + * + * @deprecated Use ATTR_AWS_LOG_STREAM_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; + /** + * The ARN(s) of the AWS log stream(s). + * + * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream. + * + * @deprecated Use ATTR_AWS_LOG_STREAM_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; + /** + * Container name. + * + * @deprecated Use ATTR_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; + /** + * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated. + * + * @deprecated Use ATTR_CONTAINER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; + /** + * The container runtime managing this container. + * + * @deprecated Use ATTR_CONTAINER_RUNTIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; + /** + * Name of the image the container was built on. + * + * @deprecated Use ATTR_CONTAINER_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; + /** + * Container image tag. + * + * @deprecated Use ATTR_CONTAINER_IMAGE_TAGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; + /** + * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier). + * + * @deprecated Use ATTR_DEPLOYMENT_ENVIRONMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; + /** + * A unique identifier representing the device. + * + * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence. + * + * @deprecated Use ATTR_DEVICE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; + /** + * The model identifier for the device. + * + * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device. + * + * @deprecated Use ATTR_DEVICE_MODEL_IDENTIFIER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; + /** + * The marketing name for the device model. + * + * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative. + * + * @deprecated Use ATTR_DEVICE_MODEL_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; + /** + * The name of the single function that this runtime instance executes. + * + * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes). + * + * @deprecated Use ATTR_FAAS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; + /** + * The unique ID of the single function that this runtime instance executes. + * + * Note: Depending on the cloud provider, use: + + * **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). + Take care not to use the "invoked ARN" directly but replace any + [alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple + different aliases. + * **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names) + * **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id). + + On some providers, it may not be possible to determine the full ID at startup, + which is why this field cannot be made required. For example, on AWS the account ID + part of the ARN is not available without calling another AWS API + which may be deemed too slow for a short-running lambda function. + As an alternative, consider setting `faas.id` as a span attribute instead. + * + * @deprecated Use ATTR_CLOUD_RESOURCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; + /** + * The immutable version of the function being executed. + * + * Note: Depending on the cloud provider and platform, use: + + * **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) + (an integer represented as a decimal string). + * **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions) + (i.e., the function name plus the revision suffix). + * **Google Cloud Functions:** The value of the + [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). + * **Azure Functions:** Not applicable. Do not set this attribute. + * + * @deprecated Use ATTR_FAAS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; + /** + * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version. + * + * Note: * **AWS Lambda:** Use the (full) log stream name. + * + * @deprecated Use ATTR_FAAS_INSTANCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; + /** + * The amount of memory available to the serverless function in MiB. + * + * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information. + * + * @deprecated Use ATTR_FAAS_MAX_MEMORY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; + /** + * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. + * + * @deprecated Use ATTR_HOST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_HOST_ID = TMP_HOST_ID; + /** + * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user. + * + * @deprecated Use ATTR_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; + /** + * Type of host. For Cloud, this must be the machine type. + * + * @deprecated Use ATTR_HOST_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; + /** + * The CPU architecture the host system is running on. + * + * @deprecated Use ATTR_HOST_ARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; + /** + * Name of the VM image or OS install the host was instantiated from. + * + * @deprecated Use ATTR_HOST_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; + /** + * VM image ID. For Cloud, this value is from the provider. + * + * @deprecated Use ATTR_HOST_IMAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; + /** + * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes). + * + * @deprecated Use ATTR_HOST_IMAGE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; + /** + * The name of the cluster. + * + * @deprecated Use ATTR_K8S_CLUSTER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; + /** + * The name of the Node. + * + * @deprecated Use ATTR_K8S_NODE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; + /** + * The UID of the Node. + * + * @deprecated Use ATTR_K8S_NODE_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; + /** + * The name of the namespace that the pod is running in. + * + * @deprecated Use ATTR_K8S_NAMESPACE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; + /** + * The UID of the Pod. + * + * @deprecated Use ATTR_K8S_POD_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; + /** + * The name of the Pod. + * + * @deprecated Use ATTR_K8S_POD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; + /** + * The name of the Container in a Pod template. + * + * @deprecated Use ATTR_K8S_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; + /** + * The UID of the ReplicaSet. + * + * @deprecated Use ATTR_K8S_REPLICASET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; + /** + * The name of the ReplicaSet. + * + * @deprecated Use ATTR_K8S_REPLICASET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; + /** + * The UID of the Deployment. + * + * @deprecated Use ATTR_K8S_DEPLOYMENT_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; + /** + * The name of the Deployment. + * + * @deprecated Use ATTR_K8S_DEPLOYMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; + /** + * The UID of the StatefulSet. + * + * @deprecated Use ATTR_K8S_STATEFULSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; + /** + * The name of the StatefulSet. + * + * @deprecated Use ATTR_K8S_STATEFULSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; + /** + * The UID of the DaemonSet. + * + * @deprecated Use ATTR_K8S_DAEMONSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; + /** + * The name of the DaemonSet. + * + * @deprecated Use ATTR_K8S_DAEMONSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; + /** + * The UID of the Job. + * + * @deprecated Use ATTR_K8S_JOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; + /** + * The name of the Job. + * + * @deprecated Use ATTR_K8S_JOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; + /** + * The UID of the CronJob. + * + * @deprecated Use ATTR_K8S_CRONJOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; + /** + * The name of the CronJob. + * + * @deprecated Use ATTR_K8S_CRONJOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; + /** + * The operating system type. + * + * @deprecated Use ATTR_OS_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; + /** + * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands. + * + * @deprecated Use ATTR_OS_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; + /** + * Human readable operating system name. + * + * @deprecated Use ATTR_OS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_OS_NAME = TMP_OS_NAME; + /** + * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes). + * + * @deprecated Use ATTR_OS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; + /** + * Process identifier (PID). + * + * @deprecated Use ATTR_PROCESS_PID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; + /** + * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`. + * + * @deprecated Use ATTR_PROCESS_EXECUTABLE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; + /** + * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`. + * + * @deprecated Use ATTR_PROCESS_EXECUTABLE_PATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; + /** + * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`. + * + * @deprecated Use ATTR_PROCESS_COMMAND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; + /** + * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead. + * + * @deprecated Use ATTR_PROCESS_COMMAND_LINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; + /** + * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`. + * + * @deprecated Use ATTR_PROCESS_COMMAND_ARGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; + /** + * The username of the user that owns the process. + * + * @deprecated Use ATTR_PROCESS_OWNER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; + /** + * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler. + * + * @deprecated Use ATTR_PROCESS_RUNTIME_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; + /** + * The version of the runtime of this process, as returned by the runtime without modification. + * + * @deprecated Use ATTR_PROCESS_RUNTIME_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; + /** + * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment. + * + * @deprecated Use ATTR_PROCESS_RUNTIME_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; + /** + * Logical name of the service. + * + * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`. + * + * @deprecated Use ATTR_SERVICE_NAME. + */ + exports.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; + /** + * A namespace for `service.name`. + * + * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. + * + * @deprecated Use ATTR_SERVICE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; + /** + * The string ID of the service instance. + * + * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations). + * + * @deprecated Use ATTR_SERVICE_INSTANCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; + /** + * The version string of the service API or implementation. + * + * @deprecated Use ATTR_SERVICE_VERSION. + */ + exports.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; + /** + * The name of the telemetry SDK as defined above. + * + * @deprecated Use ATTR_TELEMETRY_SDK_NAME. + */ + exports.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; + /** + * The language of the telemetry SDK. + * + * @deprecated Use ATTR_TELEMETRY_SDK_LANGUAGE. + */ + exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; + /** + * The version string of the telemetry SDK. + * + * @deprecated Use ATTR_TELEMETRY_SDK_VERSION. + */ + exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; + /** + * The version string of the auto instrumentation agent, if used. + * + * @deprecated Use ATTR_TELEMETRY_DISTRO_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; + /** + * The name of the web engine. + * + * @deprecated Use ATTR_WEBENGINE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; + /** + * The version of the web engine. + * + * @deprecated Use ATTR_WEBENGINE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; + /** + * Additional description of the web engine (e.g. detailed version and edition information). + * + * @deprecated Use ATTR_WEBENGINE_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; + /** + * Create exported Value Map for SemanticResourceAttributes values + * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification + */ + exports.SemanticResourceAttributes = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_CLOUD_PROVIDER, + TMP_CLOUD_ACCOUNT_ID, + TMP_CLOUD_REGION, + TMP_CLOUD_AVAILABILITY_ZONE, + TMP_CLOUD_PLATFORM, + TMP_AWS_ECS_CONTAINER_ARN, + TMP_AWS_ECS_CLUSTER_ARN, + TMP_AWS_ECS_LAUNCHTYPE, + TMP_AWS_ECS_TASK_ARN, + TMP_AWS_ECS_TASK_FAMILY, + TMP_AWS_ECS_TASK_REVISION, + TMP_AWS_EKS_CLUSTER_ARN, + TMP_AWS_LOG_GROUP_NAMES, + TMP_AWS_LOG_GROUP_ARNS, + TMP_AWS_LOG_STREAM_NAMES, + TMP_AWS_LOG_STREAM_ARNS, + TMP_CONTAINER_NAME, + TMP_CONTAINER_ID, + TMP_CONTAINER_RUNTIME, + TMP_CONTAINER_IMAGE_NAME, + TMP_CONTAINER_IMAGE_TAG, + TMP_DEPLOYMENT_ENVIRONMENT, + TMP_DEVICE_ID, + TMP_DEVICE_MODEL_IDENTIFIER, + TMP_DEVICE_MODEL_NAME, + TMP_FAAS_NAME, + TMP_FAAS_ID, + TMP_FAAS_VERSION, + TMP_FAAS_INSTANCE, + TMP_FAAS_MAX_MEMORY, + TMP_HOST_ID, + TMP_HOST_NAME, + TMP_HOST_TYPE, + TMP_HOST_ARCH, + TMP_HOST_IMAGE_NAME, + TMP_HOST_IMAGE_ID, + TMP_HOST_IMAGE_VERSION, + TMP_K8S_CLUSTER_NAME, + TMP_K8S_NODE_NAME, + TMP_K8S_NODE_UID, + TMP_K8S_NAMESPACE_NAME, + TMP_K8S_POD_UID, + TMP_K8S_POD_NAME, + TMP_K8S_CONTAINER_NAME, + TMP_K8S_REPLICASET_UID, + TMP_K8S_REPLICASET_NAME, + TMP_K8S_DEPLOYMENT_UID, + TMP_K8S_DEPLOYMENT_NAME, + TMP_K8S_STATEFULSET_UID, + TMP_K8S_STATEFULSET_NAME, + TMP_K8S_DAEMONSET_UID, + TMP_K8S_DAEMONSET_NAME, + TMP_K8S_JOB_UID, + TMP_K8S_JOB_NAME, + TMP_K8S_CRONJOB_UID, + TMP_K8S_CRONJOB_NAME, + TMP_OS_TYPE, + TMP_OS_DESCRIPTION, + TMP_OS_NAME, + TMP_OS_VERSION, + TMP_PROCESS_PID, + TMP_PROCESS_EXECUTABLE_NAME, + TMP_PROCESS_EXECUTABLE_PATH, + TMP_PROCESS_COMMAND, + TMP_PROCESS_COMMAND_LINE, + TMP_PROCESS_COMMAND_ARGS, + TMP_PROCESS_OWNER, + TMP_PROCESS_RUNTIME_NAME, + TMP_PROCESS_RUNTIME_VERSION, + TMP_PROCESS_RUNTIME_DESCRIPTION, + TMP_SERVICE_NAME, + TMP_SERVICE_NAMESPACE, + TMP_SERVICE_INSTANCE_ID, + TMP_SERVICE_VERSION, + TMP_TELEMETRY_SDK_NAME, + TMP_TELEMETRY_SDK_LANGUAGE, + TMP_TELEMETRY_SDK_VERSION, + TMP_TELEMETRY_AUTO_VERSION, + TMP_WEBENGINE_NAME, + TMP_WEBENGINE_VERSION, + TMP_WEBENGINE_DESCRIPTION + ]); + var TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + var TMP_CLOUDPROVIDERVALUES_AWS = "aws"; + var TMP_CLOUDPROVIDERVALUES_AZURE = "azure"; + var TMP_CLOUDPROVIDERVALUES_GCP = "gcp"; + /** + * Name of the cloud provider. + * + * @deprecated Use CLOUD_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; + /** + * Name of the cloud provider. + * + * @deprecated Use CLOUD_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; + /** + * Name of the cloud provider. + * + * @deprecated Use CLOUD_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; + /** + * Name of the cloud provider. + * + * @deprecated Use CLOUD_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; + /** + * The constant map of values for CloudProviderValues. + * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification. + */ + exports.CloudProviderValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_CLOUDPROVIDERVALUES_AWS, + TMP_CLOUDPROVIDERVALUES_AZURE, + TMP_CLOUDPROVIDERVALUES_GCP + ]); + var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs"; + var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = "alibaba_cloud_fc"; + var TMP_CLOUDPLATFORMVALUES_AWS_EC2 = "aws_ec2"; + var TMP_CLOUDPLATFORMVALUES_AWS_ECS = "aws_ecs"; + var TMP_CLOUDPLATFORMVALUES_AWS_EKS = "aws_eks"; + var TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = "aws_lambda"; + var TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk"; + var TMP_CLOUDPLATFORMVALUES_AZURE_VM = "azure_vm"; + var TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = "azure_container_instances"; + var TMP_CLOUDPLATFORMVALUES_AZURE_AKS = "azure_aks"; + var TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = "azure_functions"; + var TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = "azure_app_service"; + var TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = "gcp_compute_engine"; + var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = "gcp_cloud_run"; + var TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine"; + var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions"; + var TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = "gcp_app_engine"; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_FC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_LAMBDA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ELASTIC_BEANSTALK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_VM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_CONTAINER_INSTANCES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_AKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_APP_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_COMPUTE_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_RUN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_KUBERNETES_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; + /** + * The cloud platform in use. + * + * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. + * + * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_APP_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; + /** + * The constant map of values for CloudPlatformValues. + * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification. + */ + exports.CloudPlatformValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, + TMP_CLOUDPLATFORMVALUES_AWS_EC2, + TMP_CLOUDPLATFORMVALUES_AWS_ECS, + TMP_CLOUDPLATFORMVALUES_AWS_EKS, + TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, + TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, + TMP_CLOUDPLATFORMVALUES_AZURE_VM, + TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, + TMP_CLOUDPLATFORMVALUES_AZURE_AKS, + TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, + TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, + TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE + ]); + var TMP_AWSECSLAUNCHTYPEVALUES_EC2 = "ec2"; + var TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = "fargate"; + /** + * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. + * + * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; + /** + * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. + * + * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_FARGATE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; + /** + * The constant map of values for AwsEcsLaunchtypeValues. + * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification. + */ + exports.AwsEcsLaunchtypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([TMP_AWSECSLAUNCHTYPEVALUES_EC2, TMP_AWSECSLAUNCHTYPEVALUES_FARGATE]); + var TMP_HOSTARCHVALUES_AMD64 = "amd64"; + var TMP_HOSTARCHVALUES_ARM32 = "arm32"; + var TMP_HOSTARCHVALUES_ARM64 = "arm64"; + var TMP_HOSTARCHVALUES_IA64 = "ia64"; + var TMP_HOSTARCHVALUES_PPC32 = "ppc32"; + var TMP_HOSTARCHVALUES_PPC64 = "ppc64"; + var TMP_HOSTARCHVALUES_X86 = "x86"; + /** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_AMD64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; + /** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_ARM32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; + /** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_ARM64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; + /** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_IA64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; + /** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_PPC32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; + /** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_PPC64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; + /** + * The CPU architecture the host system is running on. + * + * @deprecated Use HOST_ARCH_VALUE_X86 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; + /** + * The constant map of values for HostArchValues. + * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification. + */ + exports.HostArchValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_HOSTARCHVALUES_AMD64, + TMP_HOSTARCHVALUES_ARM32, + TMP_HOSTARCHVALUES_ARM64, + TMP_HOSTARCHVALUES_IA64, + TMP_HOSTARCHVALUES_PPC32, + TMP_HOSTARCHVALUES_PPC64, + TMP_HOSTARCHVALUES_X86 + ]); + var TMP_OSTYPEVALUES_WINDOWS = "windows"; + var TMP_OSTYPEVALUES_LINUX = "linux"; + var TMP_OSTYPEVALUES_DARWIN = "darwin"; + var TMP_OSTYPEVALUES_FREEBSD = "freebsd"; + var TMP_OSTYPEVALUES_NETBSD = "netbsd"; + var TMP_OSTYPEVALUES_OPENBSD = "openbsd"; + var TMP_OSTYPEVALUES_DRAGONFLYBSD = "dragonflybsd"; + var TMP_OSTYPEVALUES_HPUX = "hpux"; + var TMP_OSTYPEVALUES_AIX = "aix"; + var TMP_OSTYPEVALUES_SOLARIS = "solaris"; + var TMP_OSTYPEVALUES_Z_OS = "z_os"; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_WINDOWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_LINUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_DARWIN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_FREEBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_NETBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_OPENBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_DRAGONFLYBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_HPUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_AIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_SOLARIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; + /** + * The operating system type. + * + * @deprecated Use OS_TYPE_VALUE_Z_OS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). + */ + exports.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; + /** + * The constant map of values for OsTypeValues. + * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification. + */ + exports.OsTypeValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_OSTYPEVALUES_WINDOWS, + TMP_OSTYPEVALUES_LINUX, + TMP_OSTYPEVALUES_DARWIN, + TMP_OSTYPEVALUES_FREEBSD, + TMP_OSTYPEVALUES_NETBSD, + TMP_OSTYPEVALUES_OPENBSD, + TMP_OSTYPEVALUES_DRAGONFLYBSD, + TMP_OSTYPEVALUES_HPUX, + TMP_OSTYPEVALUES_AIX, + TMP_OSTYPEVALUES_SOLARIS, + TMP_OSTYPEVALUES_Z_OS + ]); + var TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = "cpp"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = "dotnet"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = "erlang"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_GO = "go"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = "java"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = "nodejs"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = "php"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = "python"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = "ruby"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = "webjs"; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_CPP. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_GO. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_JAVA. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PHP. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_RUBY. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; + /** + * The language of the telemetry SDK. + * + * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS. + */ + exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; + /** + * The constant map of values for TelemetrySdkLanguageValues. + * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification. + */ + exports.TelemetrySdkLanguageValues = /*#__PURE__*/ (0, utils_1.createConstMap)([ + TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, + TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, + TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, + TMP_TELEMETRYSDKLANGUAGEVALUES_GO, + TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, + TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, + TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, + TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, + TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, + TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS + ]); +})); +//#endregion +//#region node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js +var require_resource = /* @__PURE__ */ __commonJSMin(((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { + enumerable: true, + get: function() { + return m[k]; } - } - ctx.override({ - zodSchema, - jsonSchema: schema, - path: seen.path ?? [] - }); + }; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = exports && exports.__exportStar || function(m, exports$2) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$2, p)) __createBinding(exports$2, m, p); }; - for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]); - const result = {}; - if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema"; - else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#"; - else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#"; - else if (ctx.target === "openapi-3.0") {} - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - Object.assign(result, root.def ?? root.schema); - const rootMetaId = ctx.metadataRegistry.get(schema)?.id; - if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id; - const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) delete seen.def.id; - defs[seen.defId] = seen.def; - } - } - if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs; - else result.definitions = defs; - try { - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) - } - }, - enumerable: false, - writable: false - }); - return finalized; - } catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; - if (ctx.seen.has(_schema)) return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") return true; - if (def.type === "array") return isTransforming(def.element, ctx); - if (def.type === "set") return isTransforming(def.valueType, ctx); - if (def.type === "lazy") return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") return isTransforming(def.innerType, ctx); - if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - if (def.type === "pipe") { - if (_schema._zod.traits.has("$ZodCodec")) return true; - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true; - return false; - } - if (def.type === "union") { - for (const option of def.options) if (isTransforming(option, ctx)) return true; - return false; - } - if (def.type === "tuple") { - for (const item of def.items) if (isTransforming(item, ctx)) return true; - if (def.rest && isTransforming(def.rest, ctx)) return true; - return false; - } - return false; -} -/** -* Creates a toJSONSchema method for a schema instance. -* This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. -*/ -var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ - ...params, - processors - }); - process$1(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ - ...libraryOptions ?? {}, - target, - io, - processors - }); - process$1(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_SemanticResourceAttributes(), exports); +})); +//#endregion +//#region node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js +var require_stable_attributes = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = exports.ATTR_DOTNET_GC_HEAP_GENERATION = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = exports.ATTR_DEPLOYMENT_ENVIRONMENT_NAME = exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = exports.DB_SYSTEM_NAME_VALUE_MYSQL = exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = exports.DB_SYSTEM_NAME_VALUE_MARIADB = exports.ATTR_DB_SYSTEM_NAME = exports.ATTR_DB_STORED_PROCEDURE_NAME = exports.ATTR_DB_RESPONSE_STATUS_CODE = exports.ATTR_DB_QUERY_TEXT = exports.ATTR_DB_QUERY_SUMMARY = exports.ATTR_DB_OPERATION_NAME = exports.ATTR_DB_OPERATION_BATCH_SIZE = exports.ATTR_DB_NAMESPACE = exports.ATTR_DB_COLLECTION_NAME = exports.ATTR_CONTAINER_IMAGE_TAGS = exports.ATTR_CONTAINER_IMAGE_REPO_DIGESTS = exports.ATTR_CONTAINER_IMAGE_NAME = exports.ATTR_CONTAINER_ID = exports.ATTR_CODE_STACKTRACE = exports.ATTR_CODE_LINE_NUMBER = exports.ATTR_CODE_FUNCTION_NAME = exports.ATTR_CODE_FILE_PATH = exports.ATTR_CODE_COLUMN_NUMBER = exports.ATTR_CLIENT_PORT = exports.ATTR_CLIENT_ADDRESS = exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = void 0; + exports.ATTR_K8S_DAEMONSET_LABEL = exports.ATTR_K8S_DAEMONSET_ANNOTATION = exports.ATTR_K8S_CRONJOB_UID = exports.ATTR_K8S_CRONJOB_NAME = exports.ATTR_K8S_CRONJOB_LABEL = exports.ATTR_K8S_CRONJOB_ANNOTATION = exports.ATTR_K8S_CONTAINER_RESTART_COUNT = exports.ATTR_K8S_CONTAINER_NAME = exports.ATTR_K8S_CLUSTER_UID = exports.ATTR_K8S_CLUSTER_NAME = exports.JVM_THREAD_STATE_VALUE_WAITING = exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = exports.JVM_THREAD_STATE_VALUE_TERMINATED = exports.JVM_THREAD_STATE_VALUE_RUNNABLE = exports.JVM_THREAD_STATE_VALUE_NEW = exports.JVM_THREAD_STATE_VALUE_BLOCKED = exports.ATTR_JVM_THREAD_STATE = exports.ATTR_JVM_THREAD_DAEMON = exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = exports.JVM_MEMORY_TYPE_VALUE_HEAP = exports.ATTR_JVM_MEMORY_TYPE = exports.ATTR_JVM_MEMORY_POOL_NAME = exports.ATTR_JVM_GC_NAME = exports.ATTR_JVM_GC_ACTION = exports.ATTR_HTTP_ROUTE = exports.ATTR_HTTP_RESPONSE_STATUS_CODE = exports.ATTR_HTTP_RESPONSE_HEADER = exports.ATTR_HTTP_REQUEST_RESEND_COUNT = exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = exports.HTTP_REQUEST_METHOD_VALUE_TRACE = exports.HTTP_REQUEST_METHOD_VALUE_PUT = exports.HTTP_REQUEST_METHOD_VALUE_POST = exports.HTTP_REQUEST_METHOD_VALUE_PATCH = exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = exports.HTTP_REQUEST_METHOD_VALUE_HEAD = exports.HTTP_REQUEST_METHOD_VALUE_GET = exports.HTTP_REQUEST_METHOD_VALUE_DELETE = exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = exports.HTTP_REQUEST_METHOD_VALUE_OTHER = exports.ATTR_HTTP_REQUEST_METHOD = exports.ATTR_HTTP_REQUEST_HEADER = exports.ATTR_EXCEPTION_TYPE = exports.ATTR_EXCEPTION_STACKTRACE = exports.ATTR_EXCEPTION_MESSAGE = exports.ATTR_EXCEPTION_ESCAPED = exports.ERROR_TYPE_VALUE_OTHER = exports.ATTR_ERROR_TYPE = exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = void 0; + exports.ATTR_OTEL_SCOPE_VERSION = exports.ATTR_OTEL_SCOPE_NAME = exports.ATTR_OTEL_EVENT_NAME = exports.NETWORK_TYPE_VALUE_IPV6 = exports.NETWORK_TYPE_VALUE_IPV4 = exports.ATTR_NETWORK_TYPE = exports.NETWORK_TRANSPORT_VALUE_UNIX = exports.NETWORK_TRANSPORT_VALUE_UDP = exports.NETWORK_TRANSPORT_VALUE_TCP = exports.NETWORK_TRANSPORT_VALUE_QUIC = exports.NETWORK_TRANSPORT_VALUE_PIPE = exports.ATTR_NETWORK_TRANSPORT = exports.ATTR_NETWORK_PROTOCOL_VERSION = exports.ATTR_NETWORK_PROTOCOL_NAME = exports.ATTR_NETWORK_PEER_PORT = exports.ATTR_NETWORK_PEER_ADDRESS = exports.ATTR_NETWORK_LOCAL_PORT = exports.ATTR_NETWORK_LOCAL_ADDRESS = exports.ATTR_K8S_STATEFULSET_UID = exports.ATTR_K8S_STATEFULSET_NAME = exports.ATTR_K8S_STATEFULSET_LABEL = exports.ATTR_K8S_STATEFULSET_ANNOTATION = exports.ATTR_K8S_REPLICASET_UID = exports.ATTR_K8S_REPLICASET_NAME = exports.ATTR_K8S_REPLICASET_LABEL = exports.ATTR_K8S_REPLICASET_ANNOTATION = exports.ATTR_K8S_POD_UID = exports.ATTR_K8S_POD_START_TIME = exports.ATTR_K8S_POD_NAME = exports.ATTR_K8S_POD_LABEL = exports.ATTR_K8S_POD_IP = exports.ATTR_K8S_POD_HOSTNAME = exports.ATTR_K8S_POD_ANNOTATION = exports.ATTR_K8S_NODE_UID = exports.ATTR_K8S_NODE_NAME = exports.ATTR_K8S_NODE_LABEL = exports.ATTR_K8S_NODE_ANNOTATION = exports.ATTR_K8S_NAMESPACE_NAME = exports.ATTR_K8S_NAMESPACE_LABEL = exports.ATTR_K8S_NAMESPACE_ANNOTATION = exports.ATTR_K8S_JOB_UID = exports.ATTR_K8S_JOB_NAME = exports.ATTR_K8S_JOB_LABEL = exports.ATTR_K8S_JOB_ANNOTATION = exports.ATTR_K8S_DEPLOYMENT_UID = exports.ATTR_K8S_DEPLOYMENT_NAME = exports.ATTR_K8S_DEPLOYMENT_LABEL = exports.ATTR_K8S_DEPLOYMENT_ANNOTATION = exports.ATTR_K8S_DAEMONSET_UID = exports.ATTR_K8S_DAEMONSET_NAME = void 0; + exports.ATTR_USER_AGENT_ORIGINAL = exports.ATTR_URL_SCHEME = exports.ATTR_URL_QUERY = exports.ATTR_URL_PATH = exports.ATTR_URL_FULL = exports.ATTR_URL_FRAGMENT = exports.ATTR_TELEMETRY_SDK_VERSION = exports.ATTR_TELEMETRY_SDK_NAME = exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN = exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = exports.ATTR_TELEMETRY_SDK_LANGUAGE = exports.ATTR_TELEMETRY_DISTRO_VERSION = exports.ATTR_TELEMETRY_DISTRO_NAME = exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = exports.ATTR_SIGNALR_TRANSPORT = exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = exports.ATTR_SIGNALR_CONNECTION_STATUS = exports.ATTR_SERVICE_VERSION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_NAME = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_SERVER_PORT = exports.ATTR_SERVER_ADDRESS = exports.ATTR_OTEL_STATUS_DESCRIPTION = exports.OTEL_STATUS_CODE_VALUE_OK = exports.OTEL_STATUS_CODE_VALUE_ERROR = exports.ATTR_OTEL_STATUS_CODE = void 0; + /** + * ASP.NET Core exception middleware handling result. + * + * @example handled + * @example unhandled + */ + exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = "aspnetcore.diagnostics.exception.result"; + /** + * Enum value "aborted" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. + * + * Exception handling didn't run because the request was aborted. + */ + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; + /** + * Enum value "handled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. + * + * Exception was handled by the exception handling middleware. + */ + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; + /** + * Enum value "skipped" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. + * + * Exception handling was skipped because the response had started. + */ + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; + /** + * Enum value "unhandled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. + * + * Exception was not handled by the exception handling middleware. + */ + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; + /** + * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception. + * + * @example Contoso.MyHandler + */ + exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = "aspnetcore.diagnostics.handler.type"; + /** + * Rate limiting policy name. + * + * @example fixed + * @example sliding + * @example token + */ + exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = "aspnetcore.rate_limiting.policy"; + /** + * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason + * + * @example acquired + * @example request_canceled + */ + exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = "aspnetcore.rate_limiting.result"; + /** + * Enum value "acquired" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. + * + * Lease was acquired + */ + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; + /** + * Enum value "endpoint_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. + * + * Lease request was rejected by the endpoint limiter + */ + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; + /** + * Enum value "global_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. + * + * Lease request was rejected by the global limiter + */ + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; + /** + * Enum value "request_canceled" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. + * + * Lease request was canceled + */ + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; + /** + * Flag indicating if request was handled by the application pipeline. + * + * @example true + */ + exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = "aspnetcore.request.is_unhandled"; + /** + * A value that indicates whether the matched route is a fallback route. + * + * @example true + */ + exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = "aspnetcore.routing.is_fallback"; + /** + * Match result - success or failure + * + * @example success + * @example failure + */ + exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = "aspnetcore.routing.match_status"; + /** + * Enum value "failure" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. + * + * Match failed + */ + exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; + /** + * Enum value "success" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. + * + * Match succeeded + */ + exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; + /** + * A value that indicates whether the user is authenticated. + * + * @example true + */ + exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = "aspnetcore.user.is_authenticated"; + /** + * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. + * + * @example client.example.com + * @example 10.1.2.80 + * @example /tmp/my.sock + * + * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available. + */ + exports.ATTR_CLIENT_ADDRESS = "client.address"; + /** + * Client port number. + * + * @example 65123 + * + * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available. + */ + exports.ATTR_CLIENT_PORT = "client.port"; + /** + * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example 16 + */ + exports.ATTR_CODE_COLUMN_NUMBER = "code.column.number"; + /** + * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example "/usr/local/MyApplication/content_root/app/index.php" + */ + exports.ATTR_CODE_FILE_PATH = "code.file.path"; + /** + * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example com.example.MyHttpService.serveRequest + * @example GuzzleHttp\\Client::transfer + * @example fopen + * + * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples. + * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in + * `code.stacktrace` without information on arguments. + * + * Examples: + * + * - Java method: `com.example.MyHttpService.serveRequest` + * - Java anonymous class method: `com.mycompany.Main$1.myMethod` + * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod` + * - PHP function: `GuzzleHttp\Client::transfer` + * - Go function: `github.com/my/repo/pkg.foo.func5` + * - Elixir: `OpenTelemetry.Ctx.new` + * - Erlang: `opentelemetry_ctx:new` + * - Rust: `playground::my_module::my_cool_func` + * - C function: `fopen` + */ + exports.ATTR_CODE_FUNCTION_NAME = "code.function.name"; + /** + * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example 42 + */ + exports.ATTR_CODE_LINE_NUMBER = "code.line.number"; + /** + * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity. + * + * @example "at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" + */ + exports.ATTR_CODE_STACKTRACE = "code.stacktrace"; + /** + * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/containers/run/#container-identification). The UUID might be abbreviated. + * + * @example a3bf90e006b2 + */ + exports.ATTR_CONTAINER_ID = "container.id"; + /** + * Name of the image the container was built on. + * + * @example gcr.io/opentelemetry/operator + */ + exports.ATTR_CONTAINER_IMAGE_NAME = "container.image.name"; + /** + * Repo digests of the container image as provided by the container runtime. + * + * @example ["example@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb", "internal.registry.example.com:5000/example@sha256:b69959407d21e8a062e0416bf13405bb2b71ed7a84dde4158ebafacfa06f5578"] + * + * @note [Docker](https://docs.docker.com/reference/api/engine/version/v1.52/#tag/Image/operation/ImageInspect) and [CRI](https://github.com/kubernetes/cri-api/blob/c75ef5b473bbe2d0a4fc92f82235efd665ea8e9f/pkg/apis/runtime/v1/api.proto#L1237-L1238) report those under the `RepoDigests` field. + */ + exports.ATTR_CONTAINER_IMAGE_REPO_DIGESTS = "container.image.repo_digests"; + /** + * Container image tags. An example can be found in [Docker Image Inspect](https://docs.docker.com/reference/api/engine/version/v1.52/#tag/Image/operation/ImageInspect). Should be only the `` section of the full name for example from `registry.example.com/my-org/my-image:`. + * + * @example ["v1.27.1", "3.5.7-0"] + */ + exports.ATTR_CONTAINER_IMAGE_TAGS = "container.image.tags"; + /** + * The name of a collection (table, container) within the database. + * + * @example public.users + * @example customers + * + * @note It is **RECOMMENDED** to capture the value as provided by the application + * without attempting to do any case normalization. + * + * The collection name **SHOULD NOT** be extracted from `db.query.text`, + * when the database system supports query text with multiple collections + * in non-batch operations. + * + * For batch operations, if the individual operations are known to have the same + * collection name then that collection name **SHOULD** be used. + */ + exports.ATTR_DB_COLLECTION_NAME = "db.collection.name"; + /** + * The name of the database, fully qualified within the server address and port. + * + * @example customers + * @example test.users + * + * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted. + * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system. + * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization. + */ + exports.ATTR_DB_NAMESPACE = "db.namespace"; + /** + * The number of database operations included in a batch operation. + * + * @example 2 + * @example 3 + * @example 4 + * + * @note Except for empty batch requests described below, a batch operation contains two + * or more database operations explicitly submitted as separate operations in a single + * client call, protocol message, or database command. + * + * Requests to batch APIs that contain only one operation **SHOULD** be modeled as single + * operations, not as batch operations. + * + * A database call is not a batch operation solely because one operation accepts + * multiple operands, such as keys, rows, documents, points, or other data elements, + * including Redis [`MGET`](https://redis.io/docs/latest/commands/mget/) with + * multiple keys. + * + * In batch APIs that execute the same parameterized operation with parameter sets, + * each parameter set represents one database operation for determining whether the + * request is a batch operation. Requests with only one parameter set **SHOULD** be modeled + * as single operations, not as batch operations. + * + * `db.operation.batch.size` **SHOULD** be set to the number of operations in the batch. + * It **SHOULD NOT** be set for non-batch operations. + * + * A request to execute a batch operation with no operations **SHOULD** also be treated + * as a batch operation, and `db.operation.batch.size` **SHOULD** be set to `0`. + */ + exports.ATTR_DB_OPERATION_BATCH_SIZE = "db.operation.batch.size"; + /** + * The name of the operation or command being executed. + * + * @example findAndModify + * @example HMSET + * @example SELECT + * + * @note It is **RECOMMENDED** to capture the value as provided by the application + * without attempting to do any case normalization. + * + * The operation name **SHOULD NOT** be extracted from `db.query.text`, + * when the database system supports query text with multiple operations + * in non-batch operations. + * + * If spaces can occur in the operation name, multiple consecutive spaces + * **SHOULD** be normalized to a single space. + * + * For batch operations, if the individual operations are known to have the same operation name + * then that operation name **SHOULD** be used prepended by `BATCH `, + * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database + * system specific term if more applicable. + */ + exports.ATTR_DB_OPERATION_NAME = "db.operation.name"; + /** + * Low cardinality summary of a database query. + * + * @example SELECT wuser_table + * @example INSERT shipping_details SELECT orders + * @example get user by id + * + * @note The query summary describes a class of database queries and is useful + * as a grouping key, especially when analyzing telemetry for database + * calls involving complex queries. + * + * Summary may be available to the instrumentation through + * instrumentation hooks or other means. If it is not available, instrumentations + * that support query parsing **SHOULD** generate a summary following + * [Generating query summary](/docs/db/database-spans.md#generating-a-summary-of-the-query) + * section. + * + * For batch operations, if the individual operations are known to have the same query summary + * then that query summary **SHOULD** be used prepended by `BATCH `, + * otherwise `db.query.summary` **SHOULD** be `BATCH` or some other database + * system specific term if more applicable. + */ + exports.ATTR_DB_QUERY_SUMMARY = "db.query.summary"; + /** + * The database query being executed. + * + * @example SELECT * FROM wuser_table where username = ? + * @example SET mykey ? + * + * @note For sanitization see [Sanitization of `db.query.text`](/docs/db/database-spans.md#sanitization-of-dbquerytext). + * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable. + * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk. + */ + exports.ATTR_DB_QUERY_TEXT = "db.query.text"; + /** + * Database response status code. + * + * @example 102 + * @example ORA-17002 + * @example 08P01 + * @example 404 + * + * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes. + * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system. + */ + exports.ATTR_DB_RESPONSE_STATUS_CODE = "db.response.status_code"; + /** + * The name of a stored procedure within the database. + * + * @example GetCustomer + * + * @note It is **RECOMMENDED** to capture the value as provided by the application + * without attempting to do any case normalization. + * + * For batch operations, if the individual operations are known to have the same + * stored procedure name then that stored procedure name **SHOULD** be used. + */ + exports.ATTR_DB_STORED_PROCEDURE_NAME = "db.stored_procedure.name"; + /** + * The database management system (DBMS) product as identified by the client instrumentation. + * + * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge. + */ + exports.ATTR_DB_SYSTEM_NAME = "db.system.name"; + /** + * Enum value "mariadb" for attribute {@link ATTR_DB_SYSTEM_NAME}. + * + * [MariaDB](https://mariadb.org/) + */ + exports.DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb"; + /** + * Enum value "microsoft.sql_server" for attribute {@link ATTR_DB_SYSTEM_NAME}. + * + * [Microsoft SQL Server](https://www.microsoft.com/sql-server) + */ + exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server"; + /** + * Enum value "mysql" for attribute {@link ATTR_DB_SYSTEM_NAME}. + * + * [MySQL](https://www.mysql.com/) + */ + exports.DB_SYSTEM_NAME_VALUE_MYSQL = "mysql"; + /** + * Enum value "postgresql" for attribute {@link ATTR_DB_SYSTEM_NAME}. + * + * [PostgreSQL](https://www.postgresql.org/) + */ + exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql"; + /** + * Name of the [deployment environment](https://wikipedia.org/wiki/Deployment_environment) (aka deployment tier). + * + * @example staging + * @example production + * + * @note `deployment.environment.name` does not affect the uniqueness constraints defined through + * the `service.namespace`, `service.name` and `service.instance.id` resource attributes. + * This implies that resources carrying the following attribute combinations **MUST** be + * considered to be identifying the same service: + * + * - `service.name=frontend`, `deployment.environment.name=production` + * - `service.name=frontend`, `deployment.environment.name=staging`. + */ + exports.ATTR_DEPLOYMENT_ENVIRONMENT_NAME = "deployment.environment.name"; + /** + * Enum value "development" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. + * + * Development environment + */ + exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = "development"; + /** + * Enum value "production" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. + * + * Production environment + */ + exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = "production"; + /** + * Enum value "staging" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. + * + * Staging environment + */ + exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = "staging"; + /** + * Enum value "test" for attribute {@link ATTR_DEPLOYMENT_ENVIRONMENT_NAME}. + * + * Testing environment + */ + exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = "test"; + /** + * Name of the garbage collector managed heap generation. + * + * @example gen0 + * @example gen1 + * @example gen2 + */ + exports.ATTR_DOTNET_GC_HEAP_GENERATION = "dotnet.gc.heap.generation"; + /** + * Enum value "gen0" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Generation 0 + */ + exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0"; + /** + * Enum value "gen1" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Generation 1 + */ + exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1"; + /** + * Enum value "gen2" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Generation 2 + */ + exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2"; + /** + * Enum value "loh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Large Object Heap + */ + exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh"; + /** + * Enum value "poh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. + * + * Pinned Object Heap + */ + exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh"; + /** + * Describes a class of error the operation ended with. + * + * @example timeout + * @example java.net.UnknownHostException + * @example server_certificate_invalid + * @example 500 + * + * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality. + * + * When `error.type` is set to a type (e.g., an exception type), its + * canonical class name identifying the type within the artifact **SHOULD** be used. + * + * If the recorded error type is a wrapper that is not meaningful for + * failure classification, instrumentation **MAY** use the type of the inner + * error instead. For example, in Go, errors created with `fmt.Errorf` + * using `%w` **MAY** be unwrapped when the wrapper type does not help + * classify the failure. + * + * Instrumentations **SHOULD** document the list of errors they report. + * + * The cardinality of `error.type` within one instrumentation library **SHOULD** be low. + * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications + * should be prepared for `error.type` to have high cardinality at query time when no + * additional filters are applied. + * + * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`. + * + * If a specific domain defines its own set of error identifiers (such as HTTP or RPC status codes), + * it's **RECOMMENDED** to: + * + * - Use a domain-specific attribute + * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not. + */ + exports.ATTR_ERROR_TYPE = "error.type"; + /** + * Enum value "_OTHER" for attribute {@link ATTR_ERROR_TYPE}. + * + * A fallback error value to be used when the instrumentation doesn't define a custom value. + */ + exports.ERROR_TYPE_VALUE_OTHER = "_OTHER"; + /** + * Indicates that the exception is escaping the scope of the span. + * + * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span. + */ + exports.ATTR_EXCEPTION_ESCAPED = "exception.escaped"; + /** + * The exception message. + * + * @example Division by zero + * @example Can't convert 'int' object to str implicitly + * + * @note > [!WARNING] + * + * > This attribute may contain sensitive information. + */ + exports.ATTR_EXCEPTION_MESSAGE = "exception.message"; + /** + * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. + * + * @example "Exception in thread "main" java.lang.RuntimeException: Test exception\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" + */ + exports.ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace"; + /** + * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. + * + * @example java.net.ConnectException + * @example OSError + * + * @note If the recorded exception type is a wrapper that is not meaningful for + * failure classification, instrumentation **MAY** use the type of the inner + * exception instead. For example, in Go, errors created with `fmt.Errorf` + * using `%w` **MAY** be unwrapped when the wrapper type does not help + * classify the failure. + */ + exports.ATTR_EXCEPTION_TYPE = "exception.type"; + /** + * HTTP request headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. + * + * @example ["application/json"] + * @example ["1.2.3.4", "1.2.3.5"] + * + * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. + * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information. + * + * The `User-Agent` header is already captured in the `user_agent.original` attribute. + * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. + * + * The attribute value **MUST** consist of either multiple header values as an array of strings + * or a single-item array containing a possibly comma-concatenated string, depending on the way + * the HTTP library provides access to headers. + * + * Examples: + * + * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type` + * attribute with value `["application/json"]`. + * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for` + * attribute with value `["1.2.3.4", "1.2.3.5"]` or `["1.2.3.4, 1.2.3.5"]` depending on the HTTP library. + */ + var ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; + exports.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER; + /** + * HTTP request method. + * + * @example GET + * @example POST + * @example HEAD + * + * @note HTTP request method value **SHOULD** be "known" to the instrumentation. + * By default, this convention defines "known" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods), + * the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html) + * and the QUERY method defined in [httpbis-safe-method-w-body](https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/?include_text=1). + * + * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`. + * + * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override + * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named + * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods. + * + * + * If this override is done via declarative configuration, then the list **MUST** be configurable via the `known_methods` property + * (an array of case-sensitive strings with minimum items 0) under `.instrumentation/development.general.http.client` and/or + * `.instrumentation/development.general.http.server`. + * + * In either case, this list **MUST** be a full override of the default known methods, + * it is not a list of known methods in addition to the defaults. + * + * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly. + * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent. + * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value. + */ + exports.ATTR_HTTP_REQUEST_METHOD = "http.request.method"; + /** + * Enum value "_OTHER" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * Any HTTP method that the instrumentation has no prior knowledge of. + */ + exports.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; + /** + * Enum value "CONNECT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * CONNECT method. + */ + exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; + /** + * Enum value "DELETE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * DELETE method. + */ + exports.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; + /** + * Enum value "GET" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * GET method. + */ + exports.HTTP_REQUEST_METHOD_VALUE_GET = "GET"; + /** + * Enum value "HEAD" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * HEAD method. + */ + exports.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; + /** + * Enum value "OPTIONS" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * OPTIONS method. + */ + exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; + /** + * Enum value "PATCH" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * PATCH method. + */ + exports.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; + /** + * Enum value "POST" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * POST method. + */ + exports.HTTP_REQUEST_METHOD_VALUE_POST = "POST"; + /** + * Enum value "PUT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * PUT method. + */ + exports.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; + /** + * Enum value "TRACE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. + * + * TRACE method. + */ + exports.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; + /** + * Original HTTP method sent by the client in the request line. + * + * @example GeT + * @example ACL + * @example foo + */ + exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original"; + /** + * The ordinal number of request resending attempt (for any reason, including redirects). + * + * @example 3 + * + * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other). + */ + exports.ATTR_HTTP_REQUEST_RESEND_COUNT = "http.request.resend_count"; + /** + * HTTP response headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. + * + * @example ["application/json"] + * @example ["abc", "def"] + * + * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. + * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information. + * + * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. + * + * The attribute value **MUST** consist of either multiple header values as an array of strings + * or a single-item array containing a possibly comma-concatenated string, depending on the way + * the HTTP library provides access to headers. + * + * Examples: + * + * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type` + * attribute with value `["application/json"]`. + * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header` + * attribute with value `["abc", "def"]` or `["abc, def"]` depending on the HTTP library. + */ + var ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; + exports.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER; + /** + * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). + * + * @example 200 + */ + exports.ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"; + /** + * The matched route template for the request. This **MUST** be low-cardinality and include all static path segments, with dynamic path segments represented with placeholders. + * + * @example /users/:userID? + * @example my-controller/my-action/{id?} + * + * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it. + * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one. + * + * A static path segment is a part of the route template with a fixed, low-cardinality value. This includes literal strings like `/users/` and placeholders that + * are constrained to a finite, predefined set of values, e.g. `{controller}` or `{action}`. + * + * A dynamic path segment is a placeholder for a value that can have high cardinality and is not constrained to a predefined list like static path segments. + * + * Instrumentations **SHOULD** use routing information provided by the corresponding web framework. They **SHOULD** pick the most precise source of routing information and **MAY** + * support custom route formatting. Instrumentations **SHOULD** document the format and the API used to obtain the route string. + */ + exports.ATTR_HTTP_ROUTE = "http.route"; + /** + * Name of the garbage collector action. + * + * @example end of minor GC + * @example end of major GC + * + * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()). + */ + exports.ATTR_JVM_GC_ACTION = "jvm.gc.action"; + /** + * Name of the garbage collector. + * + * @example G1 Young Generation + * @example G1 Old Generation + * + * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()). + */ + exports.ATTR_JVM_GC_NAME = "jvm.gc.name"; + /** + * Name of the memory pool. + * + * @example G1 Old Gen + * @example G1 Eden space + * @example G1 Survivor Space + * + * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()). + */ + exports.ATTR_JVM_MEMORY_POOL_NAME = "jvm.memory.pool.name"; + /** + * The type of memory. + * + * @example heap + * @example non_heap + */ + exports.ATTR_JVM_MEMORY_TYPE = "jvm.memory.type"; + /** + * Enum value "heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. + * + * Heap memory. + */ + exports.JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; + /** + * Enum value "non_heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. + * + * Non-heap memory + */ + exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; + /** + * Whether the thread is daemon or not. + */ + exports.ATTR_JVM_THREAD_DAEMON = "jvm.thread.daemon"; + /** + * State of the thread. + * + * @example runnable + * @example blocked + */ + exports.ATTR_JVM_THREAD_STATE = "jvm.thread.state"; + /** + * Enum value "blocked" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that is blocked waiting for a monitor lock is in this state. + */ + exports.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; + /** + * Enum value "new" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that has not yet started is in this state. + */ + exports.JVM_THREAD_STATE_VALUE_NEW = "new"; + /** + * Enum value "runnable" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread executing in the Java virtual machine is in this state. + */ + exports.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; + /** + * Enum value "terminated" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that has exited is in this state. + */ + exports.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; + /** + * Enum value "timed_waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. + */ + exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; + /** + * Enum value "waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. + * + * A thread that is waiting indefinitely for another thread to perform a particular action is in this state. + */ + exports.JVM_THREAD_STATE_VALUE_WAITING = "waiting"; + /** + * The name of the cluster. + * + * @example opentelemetry-cluster + */ + exports.ATTR_K8S_CLUSTER_NAME = "k8s.cluster.name"; + /** + * A pseudo-ID for the cluster, set to the UID of the `kube-system` namespace. + * + * @example 218fc5a9-a5f1-4b54-aa05-46717d0ab26d + * + * @note K8s doesn't have support for obtaining a cluster ID. If this is ever + * added, we will recommend collecting the `k8s.cluster.uid` through the + * official APIs. In the meantime, we are able to use the `uid` of the + * `kube-system` namespace as a proxy for cluster ID. Read on for the + * rationale. + * + * Every object created in a K8s cluster is assigned a distinct UID. The + * `kube-system` namespace is used by Kubernetes itself and will exist + * for the lifetime of the cluster. Using the `uid` of the `kube-system` + * namespace is a reasonable proxy for the K8s ClusterID as it will only + * change if the cluster is rebuilt. Furthermore, Kubernetes UIDs are + * UUIDs as standardized by + * [ISO/IEC 9834-8 and ITU-T X.667](https://www.itu.int/ITU-T/studygroups/com17/oid.html). + * Which states: + * + * > If generated according to one of the mechanisms defined in Rec. + * > ITU-T X.667 | ISO/IEC 9834-8, a UUID is either guaranteed to be + * > different from all other UUIDs generated before 3603 A.D., or is + * > extremely likely to be different (depending on the mechanism chosen). + * + * Therefore, UIDs between clusters should be extremely unlikely to + * conflict. + */ + exports.ATTR_K8S_CLUSTER_UID = "k8s.cluster.uid"; + /** + * The name of the Container from Pod specification, must be unique within a Pod. Container runtime usually uses different globally unique name (`container.name`). + * + * @example redis + */ + exports.ATTR_K8S_CONTAINER_NAME = "k8s.container.name"; + /** + * Number of times the container was restarted. This attribute can be used to identify a particular container (running or stopped) within a container spec. + */ + exports.ATTR_K8S_CONTAINER_RESTART_COUNT = "k8s.container.restart_count"; + /** + * The cronjob annotation placed on the CronJob, the `` being the annotation name, the value being the annotation value. + * + * @example 4 + * @example + * + * @note Examples: + * + * - An annotation `retries` with value `4` **SHOULD** be recorded as the + * `k8s.cronjob.annotation.retries` attribute with value `"4"`. + * - An annotation `data` with empty string value **SHOULD** be recorded as + * the `k8s.cronjob.annotation.data` attribute with value `""`. + */ + var ATTR_K8S_CRONJOB_ANNOTATION = (key) => `k8s.cronjob.annotation.${key}`; + exports.ATTR_K8S_CRONJOB_ANNOTATION = ATTR_K8S_CRONJOB_ANNOTATION; + /** + * The label placed on the CronJob, the `` being the label name, the value being the label value. + * + * @example weekly + * @example + * + * @note Examples: + * + * - A label `type` with value `weekly` **SHOULD** be recorded as the + * `k8s.cronjob.label.type` attribute with value `"weekly"`. + * - A label `automated` with empty string value **SHOULD** be recorded as + * the `k8s.cronjob.label.automated` attribute with value `""`. + */ + var ATTR_K8S_CRONJOB_LABEL = (key) => `k8s.cronjob.label.${key}`; + exports.ATTR_K8S_CRONJOB_LABEL = ATTR_K8S_CRONJOB_LABEL; + /** + * The name of the CronJob. + * + * @example opentelemetry + */ + exports.ATTR_K8S_CRONJOB_NAME = "k8s.cronjob.name"; + /** + * The UID of the CronJob. + * + * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff + */ + exports.ATTR_K8S_CRONJOB_UID = "k8s.cronjob.uid"; + /** + * The annotation placed on the DaemonSet, the `` being the annotation name, the value being the annotation value, even if the value is empty. + * + * @example 1 + * @example + * + * @note + * Examples: + * + * - An annotation `replicas` with value `1` **SHOULD** be recorded + * as the `k8s.daemonset.annotation.replicas` attribute with value `"1"`. + * - An annotation `data` with empty string value **SHOULD** be recorded as + * the `k8s.daemonset.annotation.data` attribute with value `""`. + */ + var ATTR_K8S_DAEMONSET_ANNOTATION = (key) => `k8s.daemonset.annotation.${key}`; + exports.ATTR_K8S_DAEMONSET_ANNOTATION = ATTR_K8S_DAEMONSET_ANNOTATION; + /** + * The label placed on the DaemonSet, the `` being the label name, the value being the label value, even if the value is empty. + * + * @example guestbook + * @example + * + * @note + * Examples: + * + * - A label `app` with value `guestbook` **SHOULD** be recorded + * as the `k8s.daemonset.label.app` attribute with value `"guestbook"`. + * - A label `injected` with empty string value **SHOULD** be recorded as + * the `k8s.daemonset.label.injected` attribute with value `""`. + */ + var ATTR_K8S_DAEMONSET_LABEL = (key) => `k8s.daemonset.label.${key}`; + exports.ATTR_K8S_DAEMONSET_LABEL = ATTR_K8S_DAEMONSET_LABEL; + /** + * The name of the DaemonSet. + * + * @example opentelemetry + */ + exports.ATTR_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; + /** + * The UID of the DaemonSet. + * + * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff + */ + exports.ATTR_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; + /** + * The annotation placed on the Deployment, the `` being the annotation name, the value being the annotation value, even if the value is empty. + * + * @example 1 + * @example + * + * @note + * Examples: + * + * - An annotation `replicas` with value `1` **SHOULD** be recorded + * as the `k8s.deployment.annotation.replicas` attribute with value `"1"`. + * - An annotation `data` with empty string value **SHOULD** be recorded as + * the `k8s.deployment.annotation.data` attribute with value `""`. + */ + var ATTR_K8S_DEPLOYMENT_ANNOTATION = (key) => `k8s.deployment.annotation.${key}`; + exports.ATTR_K8S_DEPLOYMENT_ANNOTATION = ATTR_K8S_DEPLOYMENT_ANNOTATION; + /** + * The label placed on the Deployment, the `` being the label name, the value being the label value, even if the value is empty. + * + * @example guestbook + * @example + * + * @note + * Examples: + * + * - A label `app` with value `guestbook` **SHOULD** be recorded + * as the `k8s.deployment.label.app` attribute with value `"guestbook"`. + * - A label `injected` with empty string value **SHOULD** be recorded as + * the `k8s.deployment.label.injected` attribute with value `""`. + */ + var ATTR_K8S_DEPLOYMENT_LABEL = (key) => `k8s.deployment.label.${key}`; + exports.ATTR_K8S_DEPLOYMENT_LABEL = ATTR_K8S_DEPLOYMENT_LABEL; + /** + * The name of the Deployment. + * + * @example opentelemetry + */ + exports.ATTR_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; + /** + * The UID of the Deployment. + * + * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff + */ + exports.ATTR_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; + /** + * The annotation placed on the Job, the `` being the annotation name, the value being the annotation value, even if the value is empty. + * + * @example 1 + * @example + * + * @note + * Examples: + * + * - An annotation `number` with value `1` **SHOULD** be recorded + * as the `k8s.job.annotation.number` attribute with value `"1"`. + * - An annotation `data` with empty string value **SHOULD** be recorded as + * the `k8s.job.annotation.data` attribute with value `""`. + */ + var ATTR_K8S_JOB_ANNOTATION = (key) => `k8s.job.annotation.${key}`; + exports.ATTR_K8S_JOB_ANNOTATION = ATTR_K8S_JOB_ANNOTATION; + /** + * The label placed on the Job, the `` being the label name, the value being the label value, even if the value is empty. + * + * @example ci + * @example + * + * @note + * Examples: + * + * - A label `jobtype` with value `ci` **SHOULD** be recorded + * as the `k8s.job.label.jobtype` attribute with value `"ci"`. + * - A label `automated` with empty string value **SHOULD** be recorded as + * the `k8s.job.label.automated` attribute with value `""`. + */ + var ATTR_K8S_JOB_LABEL = (key) => `k8s.job.label.${key}`; + exports.ATTR_K8S_JOB_LABEL = ATTR_K8S_JOB_LABEL; + /** + * The name of the Job. + * + * @example opentelemetry + */ + exports.ATTR_K8S_JOB_NAME = "k8s.job.name"; + /** + * The UID of the Job. + * + * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff + */ + exports.ATTR_K8S_JOB_UID = "k8s.job.uid"; + /** + * The annotation placed on the Namespace, the `` being the annotation name, the value being the annotation value, even if the value is empty. + * + * @example 0 + * @example + * + * @note + * Examples: + * + * - An annotation `ttl` with value `0` **SHOULD** be recorded + * as the `k8s.namespace.annotation.ttl` attribute with value `"0"`. + * - An annotation `data` with empty string value **SHOULD** be recorded as + * the `k8s.namespace.annotation.data` attribute with value `""`. + */ + var ATTR_K8S_NAMESPACE_ANNOTATION = (key) => `k8s.namespace.annotation.${key}`; + exports.ATTR_K8S_NAMESPACE_ANNOTATION = ATTR_K8S_NAMESPACE_ANNOTATION; + /** + * The label placed on the Namespace, the `` being the label name, the value being the label value, even if the value is empty. + * + * @example default + * @example + * + * @note + * Examples: + * + * - A label `kubernetes.io/metadata.name` with value `default` **SHOULD** be recorded + * as the `k8s.namespace.label.kubernetes.io/metadata.name` attribute with value `"default"`. + * - A label `data` with empty string value **SHOULD** be recorded as + * the `k8s.namespace.label.data` attribute with value `""`. + */ + var ATTR_K8S_NAMESPACE_LABEL = (key) => `k8s.namespace.label.${key}`; + exports.ATTR_K8S_NAMESPACE_LABEL = ATTR_K8S_NAMESPACE_LABEL; + /** + * The name of the namespace that the pod is running in. + * + * @example default + */ + exports.ATTR_K8S_NAMESPACE_NAME = "k8s.namespace.name"; + /** + * The annotation placed on the Node, the `` being the annotation name, the value being the annotation value, even if the value is empty. + * + * @example 0 + * @example + * + * @note Examples: + * + * - An annotation `node.alpha.kubernetes.io/ttl` with value `0` **SHOULD** be recorded as + * the `k8s.node.annotation.node.alpha.kubernetes.io/ttl` attribute with value `"0"`. + * - An annotation `data` with empty string value **SHOULD** be recorded as + * the `k8s.node.annotation.data` attribute with value `""`. + */ + var ATTR_K8S_NODE_ANNOTATION = (key) => `k8s.node.annotation.${key}`; + exports.ATTR_K8S_NODE_ANNOTATION = ATTR_K8S_NODE_ANNOTATION; + /** + * The label placed on the Node, the `` being the label name, the value being the label value, even if the value is empty. + * + * @example arm64 + * @example + * + * @note Examples: + * + * - A label `kubernetes.io/arch` with value `arm64` **SHOULD** be recorded + * as the `k8s.node.label.kubernetes.io/arch` attribute with value `"arm64"`. + * - A label `data` with empty string value **SHOULD** be recorded as + * the `k8s.node.label.data` attribute with value `""`. + */ + var ATTR_K8S_NODE_LABEL = (key) => `k8s.node.label.${key}`; + exports.ATTR_K8S_NODE_LABEL = ATTR_K8S_NODE_LABEL; + /** + * The name of the Node. + * + * @example node-1 + */ + exports.ATTR_K8S_NODE_NAME = "k8s.node.name"; + /** + * The UID of the Node. + * + * @example 1eb3a0c6-0477-4080-a9cb-0cb7db65c6a2 + */ + exports.ATTR_K8S_NODE_UID = "k8s.node.uid"; + /** + * The annotation placed on the Pod, the `` being the annotation name, the value being the annotation value. + * + * @example true + * @example x64 + * @example + * + * @note Examples: + * + * - An annotation `kubernetes.io/enforce-mountable-secrets` with value `true` **SHOULD** be recorded as + * the `k8s.pod.annotation.kubernetes.io/enforce-mountable-secrets` attribute with value `"true"`. + * - An annotation `mycompany.io/arch` with value `x64` **SHOULD** be recorded as + * the `k8s.pod.annotation.mycompany.io/arch` attribute with value `"x64"`. + * - An annotation `data` with empty string value **SHOULD** be recorded as + * the `k8s.pod.annotation.data` attribute with value `""`. + */ + var ATTR_K8S_POD_ANNOTATION = (key) => `k8s.pod.annotation.${key}`; + exports.ATTR_K8S_POD_ANNOTATION = ATTR_K8S_POD_ANNOTATION; + /** + * Specifies the hostname of the Pod. + * + * @example collector-gateway + * + * @note The K8s Pod spec has an optional hostname field, which can be used to specify a hostname. + * Refer to [K8s docs](https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-hostname-and-subdomain-field) + * for more information about this field. + * + * This attribute aligns with the `hostname` field of the + * [K8s PodSpec](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podspec-v1-core). + */ + exports.ATTR_K8S_POD_HOSTNAME = "k8s.pod.hostname"; + /** + * IP address allocated to the Pod. + * + * @example 172.18.0.2 + * + * @note This attribute aligns with the `podIP` field of the + * [K8s PodStatus](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podstatus-v1-core). + */ + exports.ATTR_K8S_POD_IP = "k8s.pod.ip"; + /** + * The label placed on the Pod, the `` being the label name, the value being the label value. + * + * @example my-app + * @example x64 + * @example + * + * @note Examples: + * + * - A label `app` with value `my-app` **SHOULD** be recorded as + * the `k8s.pod.label.app` attribute with value `"my-app"`. + * - A label `mycompany.io/arch` with value `x64` **SHOULD** be recorded as + * the `k8s.pod.label.mycompany.io/arch` attribute with value `"x64"`. + * - A label `data` with empty string value **SHOULD** be recorded as + * the `k8s.pod.label.data` attribute with value `""`. + */ + var ATTR_K8S_POD_LABEL = (key) => `k8s.pod.label.${key}`; + exports.ATTR_K8S_POD_LABEL = ATTR_K8S_POD_LABEL; + /** + * The name of the Pod. + * + * @example opentelemetry-pod-autoconf + */ + exports.ATTR_K8S_POD_NAME = "k8s.pod.name"; + /** + * The start timestamp of the Pod. + * + * @example 2025-12-04T08:41:03Z + * + * @note Date and time at which the object was acknowledged by the Kubelet. + * This is before the Kubelet pulled the container image(s) for the pod. + * + * This attribute aligns with the `startTime` field of the + * [K8s PodStatus](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.34/#podstatus-v1-core), + * in ISO 8601 (RFC 3339 compatible) format. + */ + exports.ATTR_K8S_POD_START_TIME = "k8s.pod.start_time"; + /** + * The UID of the Pod. + * + * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff + */ + exports.ATTR_K8S_POD_UID = "k8s.pod.uid"; + /** + * The annotation placed on the ReplicaSet, the `` being the annotation name, the value being the annotation value, even if the value is empty. + * + * @example 0 + * @example + * + * @note + * Examples: + * + * - An annotation `replicas` with value `0` **SHOULD** be recorded + * as the `k8s.replicaset.annotation.replicas` attribute with value `"0"`. + * - An annotation `data` with empty string value **SHOULD** be recorded as + * the `k8s.replicaset.annotation.data` attribute with value `""`. + */ + var ATTR_K8S_REPLICASET_ANNOTATION = (key) => `k8s.replicaset.annotation.${key}`; + exports.ATTR_K8S_REPLICASET_ANNOTATION = ATTR_K8S_REPLICASET_ANNOTATION; + /** + * The label placed on the ReplicaSet, the `` being the label name, the value being the label value, even if the value is empty. + * + * @example guestbook + * @example + * + * @note + * Examples: + * + * - A label `app` with value `guestbook` **SHOULD** be recorded + * as the `k8s.replicaset.label.app` attribute with value `"guestbook"`. + * - A label `injected` with empty string value **SHOULD** be recorded as + * the `k8s.replicaset.label.injected` attribute with value `""`. + */ + var ATTR_K8S_REPLICASET_LABEL = (key) => `k8s.replicaset.label.${key}`; + exports.ATTR_K8S_REPLICASET_LABEL = ATTR_K8S_REPLICASET_LABEL; + /** + * The name of the ReplicaSet. + * + * @example opentelemetry + */ + exports.ATTR_K8S_REPLICASET_NAME = "k8s.replicaset.name"; + /** + * The UID of the ReplicaSet. + * + * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff + */ + exports.ATTR_K8S_REPLICASET_UID = "k8s.replicaset.uid"; + /** + * The annotation placed on the StatefulSet, the `` being the annotation name, the value being the annotation value, even if the value is empty. + * + * @example 1 + * @example + * + * @note + * Examples: + * + * - An annotation `replicas` with value `1` **SHOULD** be recorded + * as the `k8s.statefulset.annotation.replicas` attribute with value `"1"`. + * - An annotation `data` with empty string value **SHOULD** be recorded as + * the `k8s.statefulset.annotation.data` attribute with value `""`. + */ + var ATTR_K8S_STATEFULSET_ANNOTATION = (key) => `k8s.statefulset.annotation.${key}`; + exports.ATTR_K8S_STATEFULSET_ANNOTATION = ATTR_K8S_STATEFULSET_ANNOTATION; + /** + * The label placed on the StatefulSet, the `` being the label name, the value being the label value, even if the value is empty. + * + * @example guestbook + * @example + * + * @note + * Examples: + * + * - A label `app` with value `guestbook` **SHOULD** be recorded + * as the `k8s.statefulset.label.app` attribute with value `"guestbook"`. + * - A label `injected` with empty string value **SHOULD** be recorded as + * the `k8s.statefulset.label.injected` attribute with value `""`. + */ + var ATTR_K8S_STATEFULSET_LABEL = (key) => `k8s.statefulset.label.${key}`; + exports.ATTR_K8S_STATEFULSET_LABEL = ATTR_K8S_STATEFULSET_LABEL; + /** + * The name of the StatefulSet. + * + * @example opentelemetry + */ + exports.ATTR_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; + /** + * The UID of the StatefulSet. + * + * @example 275ecb36-5aa8-4c2a-9c47-d8bb681b9aff + */ + exports.ATTR_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; + /** + * Local address of the network connection - IP address or Unix domain socket name. + * + * @example 10.1.2.80 + * @example /tmp/my.sock + */ + exports.ATTR_NETWORK_LOCAL_ADDRESS = "network.local.address"; + /** + * Local port number of the network connection. + * + * @example 65123 + */ + exports.ATTR_NETWORK_LOCAL_PORT = "network.local.port"; + /** + * Peer address of the network connection - IP address or Unix domain socket name. + * + * @example 10.1.2.80 + * @example /tmp/my.sock + */ + exports.ATTR_NETWORK_PEER_ADDRESS = "network.peer.address"; + /** + * Peer port number of the network connection. + * + * @example 65123 + */ + exports.ATTR_NETWORK_PEER_PORT = "network.peer.port"; + /** + * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent. + * + * @example amqp + * @example http + * @example mqtt + * + * @note The value **SHOULD** be normalized to lowercase. + */ + exports.ATTR_NETWORK_PROTOCOL_NAME = "network.protocol.name"; + /** + * The actual version of the protocol used for network communication. + * + * @example 1.1 + * @example 2 + * + * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set. + */ + exports.ATTR_NETWORK_PROTOCOL_VERSION = "network.protocol.version"; + /** + * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication). + * + * @example tcp + * @example udp + * + * @note The value **SHOULD** be normalized to lowercase. + * + * Consider always setting the transport when setting a port number, since + * a port number is ambiguous without knowing the transport. For example + * different processes could be listening on TCP port 12345 and UDP port 12345. + */ + exports.ATTR_NETWORK_TRANSPORT = "network.transport"; + /** + * Enum value "pipe" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * Named or anonymous pipe. + */ + exports.NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; + /** + * Enum value "quic" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * QUIC + */ + exports.NETWORK_TRANSPORT_VALUE_QUIC = "quic"; + /** + * Enum value "tcp" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * TCP + */ + exports.NETWORK_TRANSPORT_VALUE_TCP = "tcp"; + /** + * Enum value "udp" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * UDP + */ + exports.NETWORK_TRANSPORT_VALUE_UDP = "udp"; + /** + * Enum value "unix" for attribute {@link ATTR_NETWORK_TRANSPORT}. + * + * Unix domain socket + */ + exports.NETWORK_TRANSPORT_VALUE_UNIX = "unix"; + /** + * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent. + * + * @example ipv4 + * @example ipv6 + * + * @note The value **SHOULD** be normalized to lowercase. + */ + exports.ATTR_NETWORK_TYPE = "network.type"; + /** + * Enum value "ipv4" for attribute {@link ATTR_NETWORK_TYPE}. + * + * IPv4 + */ + exports.NETWORK_TYPE_VALUE_IPV4 = "ipv4"; + /** + * Enum value "ipv6" for attribute {@link ATTR_NETWORK_TYPE}. + * + * IPv6 + */ + exports.NETWORK_TYPE_VALUE_IPV6 = "ipv6"; + /** + * Identifies the class / type of event. + * + * @example browser.mouse.click + * @example device.app.lifecycle + * + * @note This attribute **SHOULD** be used by non-OTLP exporters when destination does not support `EventName` or equivalent field. This attribute **MAY** be used by applications using existing logging libraries so that it can be used to set the `EventName` field by Collector or SDK components. + */ + exports.ATTR_OTEL_EVENT_NAME = "otel.event.name"; + /** + * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP). + * + * @example io.opentelemetry.contrib.mongodb + */ + exports.ATTR_OTEL_SCOPE_NAME = "otel.scope.name"; + /** + * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP). + * + * @example 1.0.0 + */ + exports.ATTR_OTEL_SCOPE_VERSION = "otel.scope.version"; + /** + * Name of the code, either "OK" or "ERROR". **MUST NOT** be set if the status code is UNSET. + */ + exports.ATTR_OTEL_STATUS_CODE = "otel.status_code"; + /** + * Enum value "ERROR" for attribute {@link ATTR_OTEL_STATUS_CODE}. + * + * The operation contains an error. + */ + exports.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; + /** + * Enum value "OK" for attribute {@link ATTR_OTEL_STATUS_CODE}. + * + * The operation has been validated by an Application developer or Operator to have completed successfully. + */ + exports.OTEL_STATUS_CODE_VALUE_OK = "OK"; + /** + * Description of the Status if it has a value, otherwise not set. + * + * @example resource not found + */ + exports.ATTR_OTEL_STATUS_DESCRIPTION = "otel.status_description"; + /** + * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. + * + * @example example.com + * @example 10.1.2.80 + * @example /tmp/my.sock + * + * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available. + */ + exports.ATTR_SERVER_ADDRESS = "server.address"; + /** + * Server port number. + * + * @example 80 + * @example 8080 + * @example 443 + * + * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available. + */ + exports.ATTR_SERVER_PORT = "server.port"; + /** + * The string ID of the service instance. + * + * @example 627cc493-f310-47de-96bd-71410b7dec09 + * + * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words + * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to + * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled + * service). + * + * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC + * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of + * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and + * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`. + * + * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is + * needed. Similar to what can be seen in the man page for the + * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying + * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it + * or not via another resource attribute. + * + * For applications running behind an application server (like unicorn), we do not recommend using one identifier + * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker + * thread in unicorn) to have its own instance.id. + * + * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the + * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will + * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated. + * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance + * for that telemetry. This is typically the case for scraping receivers, as they know the target address and + * port. + */ + exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id"; + /** + * Logical name of the service. + * + * @example shoppingcart + * + * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with the process executable name, e.g. `unknown_service:bash`. If the process executable name is not available, the value **MUST** be set to `unknown_service`. + * The process executable name is the name of the process executable, the same value as described by the [`process.executable.name`](process.md) resource attribute. + */ + exports.ATTR_SERVICE_NAME = "service.name"; + /** + * A namespace for `service.name`. + * + * @example Shop + * + * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. + */ + exports.ATTR_SERVICE_NAMESPACE = "service.namespace"; + /** + * The version string of the service component. The format is not defined by these conventions. + * + * @example 2.0.0 + * @example a01dbef8a + */ + exports.ATTR_SERVICE_VERSION = "service.version"; + /** + * SignalR HTTP connection closure status. + * + * @example app_shutdown + * @example timeout + */ + exports.ATTR_SIGNALR_CONNECTION_STATUS = "signalr.connection.status"; + /** + * Enum value "app_shutdown" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. + * + * The connection was closed because the app is shutting down. + */ + exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; + /** + * Enum value "normal_closure" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. + * + * The connection was closed normally. + */ + exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; + /** + * Enum value "timeout" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. + * + * The connection was closed due to a timeout. + */ + exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; + /** + * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md) + * + * @example web_sockets + * @example long_polling + */ + exports.ATTR_SIGNALR_TRANSPORT = "signalr.transport"; + /** + * Enum value "long_polling" for attribute {@link ATTR_SIGNALR_TRANSPORT}. + * + * LongPolling protocol + */ + exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; + /** + * Enum value "server_sent_events" for attribute {@link ATTR_SIGNALR_TRANSPORT}. + * + * ServerSentEvents protocol + */ + exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; + /** + * Enum value "web_sockets" for attribute {@link ATTR_SIGNALR_TRANSPORT}. + * + * WebSockets protocol + */ + exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; + /** + * The name of the auto instrumentation agent or distribution, if used. + * + * @example parts-unlimited-java + * + * @note Official auto instrumentation agents and distributions **SHOULD** set the `telemetry.distro.name` attribute to + * a string starting with `opentelemetry-`, e.g. `opentelemetry-java-instrumentation`. + */ + exports.ATTR_TELEMETRY_DISTRO_NAME = "telemetry.distro.name"; + /** + * The version string of the auto instrumentation agent or distribution, if used. + * + * @example 1.2.3 + */ + exports.ATTR_TELEMETRY_DISTRO_VERSION = "telemetry.distro.version"; + /** + * The language of the telemetry SDK. + */ + exports.ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + /** + * Enum value "cpp" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; + /** + * Enum value "dotnet" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; + /** + * Enum value "erlang" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; + /** + * Enum value "go" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; + /** + * Enum value "java" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; + /** + * Enum value "kotlin" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_KOTLIN = "kotlin"; + /** + * Enum value "nodejs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; + /** + * Enum value "php" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; + /** + * Enum value "python" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; + /** + * Enum value "ruby" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; + /** + * Enum value "rust" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; + /** + * Enum value "swift" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; + /** + * Enum value "webjs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. + */ + exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; + /** + * The name of the telemetry SDK as defined above. + * + * @example opentelemetry + * + * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`. + * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the + * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point + * or another suitable identifier depending on the language. + * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case. + * All custom identifiers **SHOULD** be stable across different versions of an implementation. + */ + exports.ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + /** + * The version string of the telemetry SDK. + * + * @example 1.2.3 + */ + exports.ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + /** + * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component + * + * @example SemConv + */ + exports.ATTR_URL_FRAGMENT = "url.fragment"; + /** + * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) + * + * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv + * @example //localhost + * + * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment + * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless. + * + * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`. + * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`. + * + * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed). + * + * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it. + * + * + * Query string values for the following keys **SHOULD** be redacted by default and replaced by the + * value `REDACTED`: + * + * - [`X-Amz-Signature`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) + * - [`X-Amz-Credential`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) + * - [`X-Amz-Security-Token`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) + * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) + * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) + * + * This list is subject to change over time. + * + * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive. + * + * + * Instrumentation **MAY** provide a way to override this list via declarative configuration. + * If so, it **SHOULD** use the `sensitive_query_parameters` property + * (an array of case-sensitive strings with minimum items 0) under + * `.instrumentation/development.general.sanitization.url`. + * This list is a full override of the default sensitive query parameter keys, + * it is not a list of keys in addition to the defaults. + * + * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. + * `https://www.example.com/path?color=blue&sig=REDACTED`. + */ + exports.ATTR_URL_FULL = "url.full"; + /** + * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component + * + * @example /search + * + * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it. + */ + exports.ATTR_URL_PATH = "url.path"; + /** + * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component + * + * @example q=OpenTelemetry + * + * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it. + * + * + * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`: + * + * - [`X-Amz-Signature`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) + * - [`X-Amz-Credential`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) + * - [`X-Amz-Security-Token`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-authentication-methods.html) + * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) + * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) + * + * This list is subject to change over time. + * + * Matching of query parameter keys against the sensitive list **SHOULD** be case-sensitive. + * + * Instrumentation **MAY** provide a way to override this list via declarative configuration. + * If so, it **SHOULD** use the `sensitive_query_parameters` property + * (an array of case-sensitive strings with minimum items 0) under + * `.instrumentation/development.general.sanitization.url`. + * This list is a full override of the default sensitive query parameter keys, + * it is not a list of keys in addition to the defaults. + * + * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. + * `q=OpenTelemetry&sig=REDACTED`. + */ + exports.ATTR_URL_QUERY = "url.query"; + /** + * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol. + * + * @example https + * @example ftp + * @example telnet + */ + exports.ATTR_URL_SCHEME = "url.scheme"; + /** + * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client. + * + * @example CERN-LineMode/2.15 libwww/2.17b3 + * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1 + * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2 + */ + exports.ATTR_USER_AGENT_ORIGINAL = "user_agent.original"; +})); //#endregion -//#region node_modules/zod/v4/core/json-schema-processors.js -var formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "" -}; -var stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; - if (typeof minimum === "number") json.minLength = minimum; - if (typeof maximum === "number") json.maxLength = maximum; - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") delete json.format; - if (format === "time") delete json.format; - } - if (contentEncoding) json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) json.pattern = regexes[0].source; - else if (regexes.length > 1) json.allOf = [...regexes.map((regex) => ({ - ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, - pattern: regex.source - }))]; - } -}; -var numberProcessor = (schema, ctx, _json, _params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) json.type = "integer"; - else json.type = "number"; - const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); - const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); - const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; - if (exMin) if (legacy) { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } else json.exclusiveMinimum = exclusiveMinimum; - else if (typeof minimum === "number") json.minimum = minimum; - if (exMax) if (legacy) { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } else json.exclusiveMaximum = exclusiveMaximum; - else if (typeof maximum === "number") json.maximum = maximum; - if (typeof multipleOf === "number") json.multipleOf = multipleOf; -}; -var booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -var neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -var enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - if (values.every((v) => typeof v === "number")) json.type = "number"; - if (values.every((v) => typeof v === "string")) json.type = "string"; - json.enum = values; -}; -var customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema"); -}; -var transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema"); -}; -var arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") json.minItems = minimum; - if (typeof maximum === "number") json.maxItems = maximum; - json.type = "array"; - json.items = process$1(def.element, ctx, { - ...params, - path: [...params.path, "items"] - }); -}; -var objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - json.properties = {}; - const shape = def.shape; - for (const key in shape) json.properties[key] = process$1(shape[key], ctx, { - ...params, - path: [ - ...params.path, - "properties", - key - ] - }); - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") return v.optin === void 0; - else return v.optout === void 0; - })); - if (requiredKeys.size > 0) json.required = Array.from(requiredKeys); - if (def.catchall?._zod.def.type === "never") json.additionalProperties = false; - else if (!def.catchall) { - if (ctx.io === "output") json.additionalProperties = false; - } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); -}; -var unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process$1(x, ctx, { - ...params, - path: [ - ...params.path, - isExclusive ? "oneOf" : "anyOf", - i - ] +//#region node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js +var require_stable_metrics = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = exports.METRIC_KESTREL_REJECTED_CONNECTIONS = exports.METRIC_KESTREL_QUEUED_REQUESTS = exports.METRIC_KESTREL_QUEUED_CONNECTIONS = exports.METRIC_KESTREL_CONNECTION_DURATION = exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = exports.METRIC_JVM_THREAD_COUNT = exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = exports.METRIC_JVM_MEMORY_USED = exports.METRIC_JVM_MEMORY_LIMIT = exports.METRIC_JVM_MEMORY_COMMITTED = exports.METRIC_JVM_GC_DURATION = exports.METRIC_JVM_CPU_TIME = exports.METRIC_JVM_CPU_RECENT_UTILIZATION = exports.METRIC_JVM_CPU_COUNT = exports.METRIC_JVM_CLASS_UNLOADED = exports.METRIC_JVM_CLASS_LOADED = exports.METRIC_JVM_CLASS_COUNT = exports.METRIC_HTTP_SERVER_REQUEST_DURATION = exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = exports.METRIC_DOTNET_TIMER_COUNT = exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = exports.METRIC_DOTNET_PROCESS_CPU_TIME = exports.METRIC_DOTNET_PROCESS_CPU_COUNT = exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = exports.METRIC_DOTNET_JIT_COMPILED_METHODS = exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = exports.METRIC_DOTNET_JIT_COMPILATION_TIME = exports.METRIC_DOTNET_GC_PAUSE_TIME = exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = exports.METRIC_DOTNET_GC_COLLECTIONS = exports.METRIC_DOTNET_EXCEPTIONS = exports.METRIC_DOTNET_ASSEMBLY_COUNT = exports.METRIC_DB_CLIENT_OPERATION_DURATION = exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = void 0; + exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = void 0; + /** + * Number of exceptions caught by exception handling middleware. + * + * @note Meter name: `Microsoft.AspNetCore.Diagnostics`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = "aspnetcore.diagnostics.exceptions"; + /** + * Number of requests that are currently active on the server that hold a rate limiting lease. + * + * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = "aspnetcore.rate_limiting.active_request_leases"; + /** + * Number of requests that are currently queued, waiting to acquire a rate limiting lease. + * + * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = "aspnetcore.rate_limiting.queued_requests"; + /** + * The time the request spent in a queue waiting to acquire a rate limiting lease. + * + * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = "aspnetcore.rate_limiting.request.time_in_queue"; + /** + * The duration of rate limiting lease held by requests on the server. + * + * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = "aspnetcore.rate_limiting.request_lease.duration"; + /** + * Number of requests that tried to acquire a rate limiting lease. + * + * @note Requests could be: + * + * - Rejected by global or endpoint rate limiting policies + * - Canceled while waiting for the lease. + * + * Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = "aspnetcore.rate_limiting.requests"; + /** + * Number of requests that were attempted to be matched to an endpoint. + * + * @note Meter name: `Microsoft.AspNetCore.Routing`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = "aspnetcore.routing.match_attempts"; + /** + * Duration of database client operations. + * + * @note Batch operations **SHOULD** be recorded as a single operation. + */ + exports.METRIC_DB_CLIENT_OPERATION_DURATION = "db.client.operation.duration"; + /** + * The number of .NET assemblies that are currently loaded. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`AppDomain.CurrentDomain.GetAssemblies().Length`](https://learn.microsoft.com/dotnet/api/system.appdomain.getassemblies). + */ + exports.METRIC_DOTNET_ASSEMBLY_COUNT = "dotnet.assembly.count"; + /** + * The number of exceptions that have been thrown in managed code. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as counting calls to [`AppDomain.CurrentDomain.FirstChanceException`](https://learn.microsoft.com/dotnet/api/system.appdomain.firstchanceexception). + */ + exports.METRIC_DOTNET_EXCEPTIONS = "dotnet.exceptions"; + /** + * The number of garbage collections that have occurred since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric uses the [`GC.CollectionCount(int generation)`](https://learn.microsoft.com/dotnet/api/system.gc.collectioncount) API to calculate exclusive collections per generation. + */ + exports.METRIC_DOTNET_GC_COLLECTIONS = "dotnet.gc.collections"; + /** + * The *approximate* number of bytes allocated on the managed GC heap since the process has started. The returned value does not include any native allocations. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetTotalAllocatedBytes()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalallocatedbytes). + */ + exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = "dotnet.gc.heap.total_allocated"; + /** + * The heap fragmentation, as observed during the latest garbage collection. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.FragmentationAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.fragmentationafterbytes). + */ + exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = "dotnet.gc.last_collection.heap.fragmentation.size"; + /** + * The managed GC heap size (including fragmentation), as observed during the latest garbage collection. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.SizeAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.sizeafterbytes). + */ + exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = "dotnet.gc.last_collection.heap.size"; + /** + * The amount of committed virtual memory in use by the .NET GC, as observed during the latest garbage collection. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetGCMemoryInfo().TotalCommittedBytes`](https://learn.microsoft.com/dotnet/api/system.gcmemoryinfo.totalcommittedbytes). Committed virtual memory may be larger than the heap size because it includes both memory for storing existing objects (the heap size) and some extra memory that is ready to handle newly allocated objects in the future. + */ + exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = "dotnet.gc.last_collection.memory.committed_size"; + /** + * The total amount of time paused in GC since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`GC.GetTotalPauseDuration()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalpauseduration). + */ + exports.METRIC_DOTNET_GC_PAUSE_TIME = "dotnet.gc.pause.time"; + /** + * The amount of time the JIT compiler has spent compiling methods since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`JitInfo.GetCompilationTime()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompilationtime). + */ + exports.METRIC_DOTNET_JIT_COMPILATION_TIME = "dotnet.jit.compilation.time"; + /** + * Count of bytes of intermediate language that have been compiled since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`JitInfo.GetCompiledILBytes()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledilbytes). + */ + exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = "dotnet.jit.compiled_il.size"; + /** + * The number of times the JIT compiler (re)compiled methods since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`JitInfo.GetCompiledMethodCount()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledmethodcount). + */ + exports.METRIC_DOTNET_JIT_COMPILED_METHODS = "dotnet.jit.compiled_methods"; + /** + * The number of times there was contention when trying to acquire a monitor lock since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`Monitor.LockContentionCount`](https://learn.microsoft.com/dotnet/api/system.threading.monitor.lockcontentioncount). + */ + exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = "dotnet.monitor.lock_contentions"; + /** + * The number of processors available to the process. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as accessing [`Environment.ProcessorCount`](https://learn.microsoft.com/dotnet/api/system.environment.processorcount). + */ + exports.METRIC_DOTNET_PROCESS_CPU_COUNT = "dotnet.process.cpu.count"; + /** + * CPU time used by the process. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as accessing the corresponding processor time properties on [`System.Diagnostics.Process`](https://learn.microsoft.com/dotnet/api/system.diagnostics.process). + */ + exports.METRIC_DOTNET_PROCESS_CPU_TIME = "dotnet.process.cpu.time"; + /** + * The number of bytes of physical memory mapped to the process context. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`Environment.WorkingSet`](https://learn.microsoft.com/dotnet/api/system.environment.workingset). + */ + exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = "dotnet.process.memory.working_set"; + /** + * The number of work items that are currently queued to be processed by the thread pool. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`ThreadPool.PendingWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.pendingworkitemcount). + */ + exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = "dotnet.thread_pool.queue.length"; + /** + * The number of thread pool threads that currently exist. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`ThreadPool.ThreadCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.threadcount). + */ + exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = "dotnet.thread_pool.thread.count"; + /** + * The number of work items that the thread pool has completed since the process has started. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`ThreadPool.CompletedWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.completedworkitemcount). + */ + exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = "dotnet.thread_pool.work_item.count"; + /** + * The number of timer instances that are currently active. + * + * @note Meter name: `System.Runtime`; Added in: .NET 9.0. + * This metric reports the same values as calling [`Timer.ActiveCount`](https://learn.microsoft.com/dotnet/api/system.threading.timer.activecount). + */ + exports.METRIC_DOTNET_TIMER_COUNT = "dotnet.timer.count"; + /** + * Duration of HTTP client requests. + */ + exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = "http.client.request.duration"; + /** + * Duration of HTTP server requests. + */ + exports.METRIC_HTTP_SERVER_REQUEST_DURATION = "http.server.request.duration"; + /** + * Number of classes currently loaded. + */ + exports.METRIC_JVM_CLASS_COUNT = "jvm.class.count"; + /** + * Number of classes loaded since JVM start. + */ + exports.METRIC_JVM_CLASS_LOADED = "jvm.class.loaded"; + /** + * Number of classes unloaded since JVM start. + */ + exports.METRIC_JVM_CLASS_UNLOADED = "jvm.class.unloaded"; + /** + * Number of processors available to the Java virtual machine. + */ + exports.METRIC_JVM_CPU_COUNT = "jvm.cpu.count"; + /** + * Recent CPU utilization for the process as reported by the JVM. + * + * @note The value range is [0.0,1.0]. This utilization is not defined as being for the specific interval since last measurement (unlike `system.cpu.utilization`). [Reference](https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad()). + */ + exports.METRIC_JVM_CPU_RECENT_UTILIZATION = "jvm.cpu.recent_utilization"; + /** + * CPU time used by the process as reported by the JVM. + */ + exports.METRIC_JVM_CPU_TIME = "jvm.cpu.time"; + /** + * Duration of JVM garbage collection actions. + */ + exports.METRIC_JVM_GC_DURATION = "jvm.gc.duration"; + /** + * Measure of memory committed. + */ + exports.METRIC_JVM_MEMORY_COMMITTED = "jvm.memory.committed"; + /** + * Measure of max obtainable memory. + */ + exports.METRIC_JVM_MEMORY_LIMIT = "jvm.memory.limit"; + /** + * Measure of memory used. + */ + exports.METRIC_JVM_MEMORY_USED = "jvm.memory.used"; + /** + * Measure of memory used, as measured after the most recent garbage collection event on this pool. + */ + exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = "jvm.memory.used_after_last_gc"; + /** + * Number of executing platform threads. + */ + exports.METRIC_JVM_THREAD_COUNT = "jvm.thread.count"; + /** + * Number of connections that are currently active on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = "kestrel.active_connections"; + /** + * Number of TLS handshakes that are currently in progress on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = "kestrel.active_tls_handshakes"; + /** + * The duration of connections on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_KESTREL_CONNECTION_DURATION = "kestrel.connection.duration"; + /** + * Number of connections that are currently queued and are waiting to start. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_KESTREL_QUEUED_CONNECTIONS = "kestrel.queued_connections"; + /** + * Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_KESTREL_QUEUED_REQUESTS = "kestrel.queued_requests"; + /** + * Number of connections rejected by the server. + * + * @note Connections are rejected when the currently active count exceeds the value configured with `MaxConcurrentConnections`. + * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_KESTREL_REJECTED_CONNECTIONS = "kestrel.rejected_connections"; + /** + * The duration of TLS handshakes on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = "kestrel.tls_handshake.duration"; + /** + * Number of connections that are currently upgraded (WebSockets). . + * + * @note The counter only tracks HTTP/1.1 connections. + * + * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = "kestrel.upgraded_connections"; + /** + * Number of connections that are currently active on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = "signalr.server.active_connections"; + /** + * The duration of connections on the server. + * + * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 + */ + exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = "signalr.server.connection.duration"; +})); +//#endregion +//#region node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js +var require_stable_events = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EVENT_EXCEPTION = void 0; + /** + * This event describes a single exception. + */ + exports.EVENT_EXCEPTION = "exception"; +})); +//#endregion +//#region node_modules/@better-auth/core/dist/instrumentation/attributes.mjs +var import_src = (/* @__PURE__ */ __commonJSMin(((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { + enumerable: true, + get: function() { + return m[k]; + } + }; + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; })); - if (isExclusive) json.oneOf = options; - else json.anyOf = options; -}; -var intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = process$1(def.left, ctx, { - ...params, - path: [ - ...params.path, - "allOf", - 0 - ] - }); - const b = process$1(def.right, ctx, { - ...params, - path: [ - ...params.path, - "allOf", - 1 - ] - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]]; -}; -var recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - const keyType = def.keyType; - const patterns = keyType._zod.bag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process$1(def.valueType, ctx, { - ...params, - path: [ - ...params.path, - "patternProperties", - "*" - ] - }); - json.patternProperties = {}; - for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema; - } else { - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$1(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"] - }); - json.additionalProperties = process$1(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - const keyValues = keyType._zod.values; - if (keyValues) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) json.required = validKeyValues; - } -}; -var nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } else json.anyOf = [inner, { type: "null" }]; -}; -var nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -var defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.default = JSON.parse(JSON.stringify(def.defaultValue)); -}; -var prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); -}; -var catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(void 0); - } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - json.default = catchValue; -}; -var pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const inIsTransform = def.in._zod.traits.has("$ZodTransform"); - const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out; - process$1(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -var readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -var optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; + var __exportStar = exports && exports.__exportStar || function(m, exports$1) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_trace(), exports); + __exportStar(require_resource(), exports); + __exportStar(require_stable_attributes(), exports); + __exportStar(require_stable_metrics(), exports); + __exportStar(require_stable_events(), exports); +})))(); +/** Operation identifier (e.g. getSession, signUpWithEmailAndPassword). Uses endpoint operationId when set, otherwise the endpoint key. */ +var ATTR_OPERATION_ID = "better_auth.operation_id"; +/** Hook type (e.g. before, after, create.before). */ +var ATTR_HOOK_TYPE = "better_auth.hook.type"; +/** Execution context (e.g. user, plugin:id). */ +var ATTR_CONTEXT = "better_auth.context"; //#endregion -//#region node_modules/zod/v4/classic/iso.js -var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime(params) { - return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params); +//#region node_modules/@better-auth/core/dist/instrumentation/noop.mjs +function createNoopSpan() { + const span = { + end() {}, + setAttribute(_key, _value) {}, + setStatus(_status) {}, + recordException(_exception) {}, + updateName(_name) { + return span; + } + }; + return span; } -var ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date(params) { - return /* @__PURE__ */ _isoDate(ZodISODate, params); +function createNoopTracer(noopSpan) { + function startActiveSpan(_name, ...rest) { + const fn = rest[rest.length - 1]; + return fn(noopSpan); + } + return { startActiveSpan }; +} +function createNoopTraceAPI() { + const noopTracer = createNoopTracer(createNoopSpan()); + return { + getTracer(_name, _version) { + return noopTracer; + }, + getActiveSpan() {} + }; +} +function createNoopOpenTelemetryAPI() { + return { + SpanStatusCode: { + UNSET: 0, + OK: 1, + ERROR: 2 + }, + trace: createNoopTraceAPI() + }; +} +var noopOpenTelemetryAPI = createNoopOpenTelemetryAPI(); +//#endregion +//#region node_modules/@better-auth/core/dist/instrumentation/api.mjs +var openTelemetryAPIPromise; +var openTelemetryAPI; +function getOpenTelemetryAPI() { + if (!openTelemetryAPIPromise) openTelemetryAPIPromise = import("../../_chunks/core.mjs").then((mod) => { + openTelemetryAPI = mod; + }).catch(() => void 0); + return openTelemetryAPI ?? noopOpenTelemetryAPI; } -var ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time(params) { - return /* @__PURE__ */ _isoTime(ZodISOTime, params); +//#endregion +//#region node_modules/@better-auth/core/dist/instrumentation/tracer.mjs +var INSTRUMENTATION_SCOPE = "better-auth"; +var INSTRUMENTATION_VERSION = "1.6.25"; +/** +* Better-auth uses `throw ctx.redirect(url)` for flow control (e.g. OAuth +* callbacks). These are APIErrors with 3xx status codes and should not be +* recorded as span errors. +*/ +function isRedirectError(err) { + if (err != null && typeof err === "object" && "name" in err && err.name === "APIError" && "statusCode" in err) { + const status = err.statusCode; + return status >= 300 && status < 400; + } + return false; } -var ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration(params) { - return /* @__PURE__ */ _isoDuration(ZodISODuration, params); +function endSpanWithError(span, err) { + const { SpanStatusCode } = getOpenTelemetryAPI(); + if (isRedirectError(err)) { + span.setAttribute(import_src.ATTR_HTTP_RESPONSE_STATUS_CODE, err.statusCode); + span.setStatus({ code: SpanStatusCode.OK }); + } else { + span.recordException(err); + span.setStatus({ + code: SpanStatusCode.ERROR, + message: String(err?.message ?? err) + }); + } + span.end(); } -//#endregion -//#region node_modules/zod/v4/classic/errors.js -var initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { value: (mapper) => formatError(inst, mapper) }, - flatten: { value: (mapper) => flattenError(inst, mapper) }, - addIssue: { value: (issue) => { - inst.issues.push(issue); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } }, - addIssues: { value: (issues) => { - inst.issues.push(...issues); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } }, - isEmpty: { get() { - return inst.issues.length === 0; - } } +function withSpan(name, attributes, fn) { + const { trace } = getOpenTelemetryAPI(); + return trace.getTracer(INSTRUMENTATION_SCOPE, INSTRUMENTATION_VERSION).startActiveSpan(name, { attributes }, (span) => { + try { + const result = fn(); + if (result instanceof Promise) return result.then((value) => { + span.end(); + return value; + }).catch((err) => { + endSpanWithError(span, err); + throw err; + }); + span.end(); + return result; + } catch (err) { + endSpanWithError(span, err); + throw err; + } }); -}; -var ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, { Parent: Error }); -//#endregion -//#region node_modules/zod/v4/classic/parse.js -var parse = /* @__PURE__ */ _parse(ZodRealError); -var parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError); -var safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -var safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); -var encode = /* @__PURE__ */ _encode(ZodRealError); -var decode = /* @__PURE__ */ _decode(ZodRealError); -var encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError); -var decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError); -var safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); -var safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); -var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); -var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); +} //#endregion -//#region node_modules/zod/v4/classic/schemas.js -var _installedGroups = /* @__PURE__ */ new WeakMap(); -function _installLazyMethods(inst, group, methods) { - const proto = Object.getPrototypeOf(inst); - let installed = _installedGroups.get(proto); - if (!installed) { - installed = /* @__PURE__ */ new Set(); - _installedGroups.set(proto, installed); - } - if (installed.has(group)) return; - installed.add(group); - for (const key in methods) { - const fn = methods[key]; - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const bound = fn.bind(this); - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: bound +//#region node_modules/@better-auth/core/dist/db/adapter/factory.mjs +var debugLogs = []; +var transactionId = -1; +var createAsIsTransaction = (adapter) => (fn) => fn(adapter); +var createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => { + const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15); + const config = { + ...cfg, + supportsBooleans: cfg.supportsBooleans ?? true, + supportsDates: cfg.supportsDates ?? true, + supportsJSON: cfg.supportsJSON ?? false, + adapterName: cfg.adapterName ?? cfg.adapterId, + supportsNumericIds: cfg.supportsNumericIds ?? true, + supportsUUIDs: cfg.supportsUUIDs ?? false, + supportsArrays: cfg.supportsArrays ?? false, + transaction: cfg.transaction ?? false, + disableTransformInput: cfg.disableTransformInput ?? false, + disableTransformOutput: cfg.disableTransformOutput ?? false, + disableTransformJoin: cfg.disableTransformJoin ?? false + }; + if (options.advanced?.database?.generateId === "serial" && config.supportsNumericIds === false) throw new BetterAuthError(`[${config.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`); + const schema = getAuthTables(options); + const debugLog = (...args) => { + if (config.debugLogs === true || typeof config.debugLogs === "object") { + const logger = createLogger({ level: "info" }); + if (typeof config.debugLogs === "object" && "isRunningAdapterTests" in config.debugLogs) { + if (config.debugLogs.isRunningAdapterTests) { + args.shift(); + debugLogs.push({ + instance: uniqueAdapterFactoryInstanceId, + args + }); + } + return; + } + if (typeof config.debugLogs === "object" && config.debugLogs.logCondition && !config.debugLogs.logCondition?.()) return; + if (typeof args[0] === "object" && "method" in args[0]) { + const method = args.shift().method; + if (typeof config.debugLogs === "object") { + if (method === "create" && !config.debugLogs.create) return; + else if (method === "update" && !config.debugLogs.update) return; + else if (method === "updateMany" && !config.debugLogs.updateMany) return; + else if (method === "findOne" && !config.debugLogs.findOne) return; + else if (method === "findMany" && !config.debugLogs.findMany) return; + else if (method === "delete" && !config.debugLogs.delete) return; + else if (method === "deleteMany" && !config.debugLogs.deleteMany) return; + else if (method === "consumeOne" && !config.debugLogs.consumeOne) return; + else if (method === "incrementOne" && !config.debugLogs.incrementOne) return; + else if (method === "count" && !config.debugLogs.count) return; + } + logger.info(`[${config.adapterName}]`, ...args); + } else logger.info(`[${config.adapterName}]`, ...args); + } + }; + const logger = createLogger(options.logger); + const getDefaultModelName = initGetDefaultModelName({ + usePlural: config.usePlural, + schema + }); + const getDefaultFieldName = initGetDefaultFieldName({ + usePlural: config.usePlural, + schema + }); + const getModelName = initGetModelName({ + usePlural: config.usePlural, + schema + }); + const getFieldName = initGetFieldName({ + schema, + usePlural: config.usePlural + }); + const idField = initGetIdField({ + schema, + options, + usePlural: config.usePlural, + disableIdGeneration: config.disableIdGeneration, + customIdGenerator: config.customIdGenerator, + supportsUUIDs: config.supportsUUIDs + }); + const getFieldAttributes = initGetFieldAttributes({ + schema, + options, + usePlural: config.usePlural, + disableIdGeneration: config.disableIdGeneration, + customIdGenerator: config.customIdGenerator + }); + const transformInput = async (data, defaultModelName, action, forceAllowId) => { + const transformedData = {}; + const fields = schema[defaultModelName].fields; + const newMappedKeys = config.mapKeysTransformInput ?? {}; + const useNumberId = options.advanced?.database?.generateId === "serial"; + fields.id = idField({ + customModelName: defaultModelName, + forceAllowId: forceAllowId && "id" in data + }); + for (const field in fields) { + let value = data[field]; + const fieldAttributes = fields[field]; + const newFieldName = newMappedKeys[field] || fields[field].fieldName || field; + if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue; + if (fieldAttributes && fieldAttributes.type === "date" && !(value instanceof Date) && typeof value === "string") try { + value = new Date(value); + } catch { + logger.error("[Adapter Factory] Failed to convert string to date", { + value, + field + }); + } + let newValue = withApplyDefault(value, fieldAttributes, action); + if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue); + if (fieldAttributes.references?.field === "id" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null); + else newValue = newValue !== null ? Number(newValue) : null; + else if (config.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue); + else if (config.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue); + else if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString(); + else if (config.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0; + if (config.customTransformInput) newValue = config.customTransformInput({ + data: newValue, + action, + field: newFieldName, + fieldAttributes, + model: getModelName(defaultModelName), + schema, + options + }); + if (newValue !== void 0) transformedData[newFieldName] = newValue; + } + return transformedData; + }; + const transformOutput = async (data, unsafe_model, select = [], join) => { + const transformSingleOutput = async (data, unsafe_model, select = []) => { + if (!data) return null; + const newMappedKeys = config.mapKeysTransformOutput ?? {}; + const transformedData = {}; + const tableSchema = schema[getDefaultModelName(unsafe_model)].fields; + const idKey = Object.entries(newMappedKeys).find(([_, v]) => v === "id")?.[0]; + tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.generateId === "serial" ? "number" : "string" }; + for (const key in tableSchema) { + if (select.length && !select.includes(key)) continue; + const field = tableSchema[key]; + if (field) { + const originalKey = field.fieldName || key; + let newValue = data[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey]; + if (field.transform?.output) newValue = await field.transform.output(newValue); + const newFieldName = newMappedKeys[key] || key; + if (originalKey === "id" || field.references?.field === "id") { + if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue); + } else if (config.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue); + else if (config.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue); + else if (config.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue); + else if (config.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1; + if (config.customTransformOutput) newValue = config.customTransformOutput({ + data: newValue, + field: newFieldName, + fieldAttributes: field, + select, + model: getModelName(unsafe_model), + schema, + options + }); + transformedData[newFieldName] = newValue; + } + } + return transformedData; + }; + if (!join || Object.keys(join).length === 0) return await transformSingleOutput(data, unsafe_model, select); + unsafe_model = getDefaultModelName(unsafe_model); + const transformedData = await transformSingleOutput(data, unsafe_model, select); + const requiredModels = Object.entries(join).map(([model, joinConfig]) => ({ + modelName: getModelName(model), + defaultModelName: getDefaultModelName(model), + joinConfig + })); + if (!data) return null; + for (const { modelName, defaultModelName, joinConfig } of requiredModels) { + let joinedData = await (async () => { + if (options.experimental?.joins) return data[modelName]; + else return await handleFallbackJoin({ + baseModel: unsafe_model, + baseData: transformedData, + joinModel: modelName, + specificJoinConfig: joinConfig }); - return bound; - }, - set(v) { - Object.defineProperty(this, key, { - configurable: true, - writable: true, - enumerable: true, - value: v + })(); + if (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === "one-to-one" ? null : []; + if (joinConfig.relation === "one-to-many" && !Array.isArray(joinedData)) joinedData = [joinedData]; + const transformed = []; + if (Array.isArray(joinedData)) for (const item of joinedData) { + const transformedItem = await transformSingleOutput(item, modelName, []); + transformed.push(transformedItem); + } + else { + const transformedItem = await transformSingleOutput(joinedData, modelName, []); + transformed.push(transformedItem); + } + transformedData[defaultModelName] = (joinConfig.relation === "one-to-one" ? transformed[0] : transformed) ?? null; + } + return transformedData; + }; + const transformWhereClause = ({ model, where, action }) => { + if (!where) return void 0; + const newMappedKeys = config.mapKeysTransformInput ?? {}; + return where.map((w) => { + const { field: unsafe_field, value, operator = "eq", connector = "AND", mode = "sensitive" } = w; + if (operator === "in") { + if (!Array.isArray(value)) throw new BetterAuthError("Value must be an array"); + } + let newValue = value; + const defaultModelName = getDefaultModelName(model); + const defaultFieldName = getDefaultFieldName({ + field: unsafe_field, + model + }); + const fieldName = newMappedKeys[defaultFieldName] || getFieldName({ + field: defaultFieldName, + model: defaultModelName + }); + const fieldAttr = getFieldAttributes({ + field: defaultFieldName, + model: defaultModelName + }); + const useNumberId = options.advanced?.database?.generateId === "serial"; + if (defaultFieldName === "id" || fieldAttr.references?.field === "id") { + if (useNumberId) if (Array.isArray(value)) newValue = value.map(Number); + else newValue = Number(value); + } + if (fieldAttr.type === "date" && value instanceof Date && !config.supportsDates) newValue = value.toISOString(); + if (fieldAttr.type === "boolean" && typeof newValue === "string") newValue = newValue === "true"; + if (fieldAttr.type === "number") { + if (typeof newValue === "string" && newValue.trim() !== "") { + const parsed = Number(newValue); + if (!Number.isNaN(parsed)) newValue = parsed; + } else if (Array.isArray(newValue)) { + const parsed = newValue.map((v) => typeof v === "string" && v.trim() !== "" ? Number(v) : NaN); + if (parsed.every((n) => !Number.isNaN(n))) newValue = parsed; + } + } + if (fieldAttr.type === "boolean" && typeof newValue === "boolean" && !config.supportsBooleans) newValue = newValue ? 1 : 0; + if (fieldAttr.type === "json" && typeof value === "object" && !config.supportsJSON) try { + newValue = JSON.stringify(value); + } catch (error) { + throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error }); + } + if (config.customTransformInput) newValue = config.customTransformInput({ + data: newValue, + fieldAttributes: fieldAttr, + field: fieldName, + model: getModelName(model), + schema, + options, + action + }); + return { + operator, + connector, + field: fieldName, + value: newValue, + mode + }; + }); + }; + const transformJoinClause = (baseModel, unsanitizedJoin, select) => { + if (!unsanitizedJoin) return void 0; + if (Object.keys(unsanitizedJoin).length === 0) return void 0; + const transformedJoin = {}; + for (const [model, join] of Object.entries(unsanitizedJoin)) { + if (!join) continue; + const defaultModelName = getDefaultModelName(model); + const defaultBaseModelName = getDefaultModelName(baseModel); + let foreignKeys = Object.entries(schema[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName); + let isForwardJoin = true; + if (!foreignKeys.length) { + foreignKeys = Object.entries(schema[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName); + isForwardJoin = false; + } + if (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`); + else if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`); + const [foreignKey, foreignKeyAttributes] = foreignKeys[0]; + if (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`); + let from; + let to; + let requiredSelectField; + if (isForwardJoin) { + requiredSelectField = foreignKeyAttributes.references.field; + from = getFieldName({ + model: baseModel, + field: requiredSelectField + }); + to = getFieldName({ + model, + field: foreignKey + }); + } else { + requiredSelectField = foreignKey; + from = getFieldName({ + model: baseModel, + field: requiredSelectField + }); + to = getFieldName({ + model, + field: foreignKeyAttributes.references.field }); } - }); - } -} -var ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - $ZodType.init(inst, def); - Object.assign(inst["~standard"], { jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); - inst.def = def; - inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode(inst, data, params); - inst.decode = (data, params) => decode(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params); - inst.safeEncode = (data, params) => safeEncode(inst, data, params); - inst.safeDecode = (data, params) => safeDecode(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params); - _installLazyMethods(inst, "ZodType", { - check(...chks) { - const def = this.def; - return this.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...chks.map((ch) => typeof ch === "function" ? { _zod: { - check: ch, - def: { check: "custom" }, - onattach: [] - } } : ch)] }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def, params) { - return clone(this, def, params); - }, - brand() { - return this; - }, - register(reg, meta) { - reg.add(this, meta); - return this; - }, - refine(check, params) { - return this.check(refine(check, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(/* @__PURE__ */ _overwrite(fn)); - }, - optional() { - return optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return array(this); - }, - or(arg) { - return union([this, arg]); - }, - and(arg) { - return intersection(this, arg); + if (select && !select.includes(requiredSelectField)) select.push(requiredSelectField); + const isUnique = to === "id" ? true : foreignKeyAttributes.unique ?? false; + let limit = options.advanced?.database?.defaultFindManyLimit ?? 100; + if (isUnique) limit = 1; + else if (typeof join === "object" && typeof join.limit === "number") limit = join.limit; + transformedJoin[getModelName(model)] = { + on: { + from, + to + }, + limit, + relation: isUnique ? "one-to-one" : "one-to-many" + }; + } + return { + join: transformedJoin, + select + }; + }; + /** + * Handle joins by making separate queries and combining results (fallback for adapters that don't support native joins). + */ + const handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => { + if (!baseData) return baseData; + const modelName = getModelName(joinModel); + const field = joinConfig.on.to; + const value = baseData[getDefaultFieldName({ + field: joinConfig.on.from, + model: baseModel + })]; + if (value === null || value === void 0) return joinConfig.relation === "one-to-one" ? null : []; + let result; + const where = transformWhereClause({ + model: modelName, + where: [{ + field, + value, + operator: "eq", + connector: "AND" + }], + action: "findOne" + }); + try { + if (joinConfig.relation === "one-to-one") result = await withSpan(`db findOne ${modelName}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "findOne", + [import_src.ATTR_DB_COLLECTION_NAME]: modelName + }, () => adapterInstance.findOne({ + model: modelName, + where + })); + else { + const limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; + result = await withSpan(`db findMany ${modelName}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "findMany", + [import_src.ATTR_DB_COLLECTION_NAME]: modelName + }, () => adapterInstance.findMany({ + model: modelName, + where, + limit + })); + } + } catch (error) { + logger.error(`Failed to query fallback join for model ${modelName}:`, { + where, + limit: joinConfig.limit + }); + console.error(error); + throw error; + } + return result; + }; + const adapterInstance = customAdapter({ + options, + schema, + debugLog, + getFieldName, + getModelName, + getDefaultModelName, + getDefaultFieldName, + getFieldAttributes, + transformInput, + transformOutput, + transformWhereClause + }); + let lazyLoadTransaction = null; + const adapter = { + transaction: async (cb) => { + if (!lazyLoadTransaction) if (!config.transaction) lazyLoadTransaction = createAsIsTransaction(adapter); + else { + logger.debug(`[${config.adapterName}] - Using provided transaction implementation.`); + lazyLoadTransaction = config.transaction; + } + return lazyLoadTransaction(cb); }, - transform(tx) { - return pipe(this, transform(tx)); + create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + unsafeModel = getDefaultModelName(unsafeModel); + if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) { + logger.warn(`[${config.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`); + const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "Create method with `id` being called at:"); + console.log(stack); + unsafeData.id = void 0; + } + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, { + model, + data: unsafeData + }); + let data = unsafeData; + if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create", forceAllowId); + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, { + model, + data + }); + const res = await withSpan(`db create ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "create", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.create({ + data, + model + })); + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, { + model, + res + }); + let transformed = res; + if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, void 0); + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; }, - default(d) { - return _default(this, d); + update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { + transactionId++; + const thisTransactionId = transactionId; + unsafeModel = getDefaultModelName(unsafeModel); + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "update" + }); + if (where.length === 0) return null; + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, { + model, + data: unsafeData + }); + let data = unsafeData; + if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, { + model, + data + }); + const res = await withSpan(`db update ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "update", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.update({ + model, + where, + update: data + })); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; }, - prefault(d) { - return prefault(this, d); + updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "updateMany" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, { + model, + data: unsafeData + }); + let data = unsafeData; + if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update"); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, { + model, + data + }); + const updatedCount = await withSpan(`db updateMany ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "updateMany", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.updateMany({ + model, + where, + update: data + })); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, { + model, + data: updatedCount + }); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, { + model, + data: updatedCount + }); + return updatedCount; }, - catch(params) { - return _catch(this, params); + findOne: async ({ model: unsafeModel, where: unsafeWhere, select, join: unsafeJoin }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "findOne" + }); + unsafeModel = getDefaultModelName(unsafeModel); + let join; + let passJoinToAdapter = true; + if (!config.disableTransformJoin) { + const result = transformJoinClause(unsafeModel, unsafeJoin, select); + if (result) { + join = result.join; + select = result.select; + } + if (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false; + } else join = unsafeJoin; + debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, { + model, + where, + select, + join + }); + const res = await withSpan(`db findOne ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "findOne", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.findOne({ + model, + where, + select, + join: passJoinToAdapter ? join : void 0 + })); + debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, join); + debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; }, - pipe(target) { - return pipe(this, target); + findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, select, sortBy, offset, join: unsafeJoin }) => { + transactionId++; + const thisTransactionId = transactionId; + const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "findMany" + }); + unsafeModel = getDefaultModelName(unsafeModel); + let join; + let passJoinToAdapter = true; + if (!config.disableTransformJoin) { + const result = transformJoinClause(unsafeModel, unsafeJoin, select); + if (result) { + join = result.join; + select = result.select; + } + if (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false; + } else join = unsafeJoin; + debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, { + model, + where, + limit, + sortBy, + offset, + join + }); + const res = await withSpan(`db findMany ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "findMany", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.findMany({ + model, + where, + limit, + select, + sortBy, + offset, + join: passJoinToAdapter ? join : void 0 + })); + debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => { + return await transformOutput(r, unsafeModel, void 0, join); + })); + debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; }, - readonly() { - return readonly(this); + delete: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "delete" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, { + model, + where + }); + await withSpan(`db delete ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "delete", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.delete({ + model, + where + })); + debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model }); }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; + deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "deleteMany" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, { + model, + where + }); + const res = await withSpan(`db deleteMany ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "deleteMany", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.deleteMany({ + model, + where + })); + debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + return res; }, - meta(...args) { - if (args.length === 0) return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; + consumeOne: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "consumeOne" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("consumeOne")} ${formatAction("ConsumeOne")}:`, { + model, + where + }); + let res; + let resultNeedsOutputTransform = true; + if (adapterInstance.consumeOne) res = await withSpan(`db consumeOne ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "consumeOne", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.consumeOne({ + model, + where + })); + else { + res = await withSpan(`db consumeOne ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "consumeOne", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => runWithTransaction(adapter, async () => { + const trx = await getCurrentAdapter(adapter); + const target = (await trx.findMany({ + model: unsafeModel, + where: unsafeWhere, + limit: 1 + }))[0]; + if (!target) return null; + const deleted = await trx.deleteMany({ + model: unsafeModel, + where: [...unsafeWhere, { + field: "id", + value: target.id, + operator: "eq", + connector: "AND", + mode: "sensitive" + }] + }); + if (typeof deleted !== "number") throw new BetterAuthError(`Adapter "${config.adapterId}" returned a non-numeric value from deleteMany during the consumeOne fallback. Return the number of deleted rows, or implement a native consumeOne for atomic single-use consumption.`); + return deleted > 0 ? target : null; + })); + resultNeedsOutputTransform = false; + } + debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("consumeOne")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config.disableTransformOutput && resultNeedsOutputTransform && res) transformed = await transformOutput(res, unsafeModel, void 0, void 0); + debugLog({ method: "consumeOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("consumeOne")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; }, - isOptional() { - return this.safeParse(void 0).success; + incrementOne: async ({ model: unsafeModel, where: unsafeWhere, increment: unsafeIncrement, set: unsafeSet }) => { + const hasIncrement = Object.keys(unsafeIncrement).length > 0; + const hasSet = !!unsafeSet && Object.keys(unsafeSet).length > 0; + if (!hasIncrement && !hasSet) throw new BetterAuthError("incrementOne requires a non-empty `increment` or `set`; both were empty."); + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "incrementOne" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("incrementOne")} ${formatAction("IncrementOne")}:`, { + model, + where, + increment: unsafeIncrement, + set: unsafeSet + }); + let res; + let resultNeedsOutputTransform = true; + if (adapterInstance.incrementOne) { + const mappedKeys = config.mapKeysTransformInput ?? {}; + const increment = {}; + for (const [field, delta] of Object.entries(unsafeIncrement)) increment[mappedKeys[field] || getFieldName({ + model: unsafeModel, + field + })] = delta; + let set; + if (unsafeSet && !config.disableTransformInput) set = await transformInput(unsafeSet, unsafeModel, "update"); + else set = unsafeSet; + if (Object.keys(increment).length === 0 && (!set || Object.keys(set).length === 0)) throw new BetterAuthError("incrementOne resolved to an empty update: every increment/set field was unknown to the schema or transformed away."); + res = await withSpan(`db incrementOne ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "incrementOne", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.incrementOne({ + model, + where, + increment, + set + })); + } else { + res = await withSpan(`db incrementOne ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "incrementOne", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => runWithTransaction(adapter, async () => { + const trx = await getCurrentAdapter(adapter); + const target = (await trx.findMany({ + model: unsafeModel, + where: unsafeWhere, + limit: 1 + }))[0]; + if (!target) return null; + const nextValues = { ...unsafeSet ?? {} }; + for (const [field, delta] of Object.entries(unsafeIncrement)) nextValues[field] = (typeof target[field] === "number" ? target[field] : 0) + delta; + const updated = await trx.updateMany({ + model: unsafeModel, + where: [...unsafeWhere, { + field: "id", + value: target.id, + operator: "eq", + connector: "AND", + mode: "sensitive" + }], + update: nextValues + }); + if (typeof updated !== "number") throw new BetterAuthError(`Adapter "${config.adapterId}" returned a non-numeric value from updateMany during the incrementOne fallback. Return the number of updated rows, or implement a native incrementOne for atomic guarded counter updates.`); + return updated > 0 ? { + ...target, + ...nextValues + } : null; + })); + resultNeedsOutputTransform = false; + } + debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("incrementOne")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config.disableTransformOutput && resultNeedsOutputTransform && res) transformed = await transformOutput(res, unsafeModel, void 0, void 0); + debugLog({ method: "incrementOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("incrementOne")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; }, - isNullable() { - return this.safeParse(null).success; + count: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "count" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, { + model, + where + }); + const res = await withSpan(`db count ${model}`, { + [import_src.ATTR_DB_OPERATION_NAME]: "count", + [import_src.ATTR_DB_COLLECTION_NAME]: model + }, () => adapterInstance.count({ + model, + where + })); + debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, { + model, + data: res + }); + return res; }, - apply(fn) { - return fn(this); - } - }); - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; + createSchema: adapterInstance.createSchema ? async (_, file) => { + const tables = getAuthTables(options); + if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session; + return adapterInstance.createSchema({ + file, + tables + }); + } : void 0, + options: { + adapterConfig: config, + ...adapterInstance.options ?? {} }, - configurable: true + id: config.adapterId, + ...config.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: { + resetDebugLogs() { + debugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId); + }, + printDebugLogs() { + const separator = `─`.repeat(80); + const logs = debugLogs.filter((log) => log.instance === uniqueAdapterFactoryInstanceId); + if (logs.length === 0) return; + const log = logs.reverse().map((log) => { + log.args[0] = `\n${log.args[0]}`; + return [...log.args, "\n"]; + }).reduce((prev, curr) => { + return [...curr, ...prev]; + }, [`\n${separator}`]); + console.log(...log); + } + } } : {} + }; + return adapter; +}; +function formatTransactionId(transactionId) { + if (getColorDepth() < 8) return `#${transactionId}`; + return `${TTY_COLORS.fg.magenta}#${transactionId}${TTY_COLORS.reset}`; +} +function formatStep(step, total) { + return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`; +} +function formatMethod(method) { + return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`; +} +function formatAction(action) { + return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`; +} +//#endregion +//#region node_modules/jose/dist/webapi/lib/buffer_utils.js +var encoder = new TextEncoder(); +var decoder = new TextDecoder(); +var MAX_INT32 = 2 ** 32; +function concat(...buffers) { + const size = buffers.reduce((acc, { length }) => acc + length, 0); + const buf = new Uint8Array(size); + let i = 0; + for (const buffer of buffers) { + buf.set(buffer, i); + i += buffer.length; + } + return buf; +} +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + buf.set([ + value >>> 24, + value >>> 16, + value >>> 8, + value & 255 + ], offset); +} +function uint64be(value) { + const high = Math.floor(value / MAX_INT32); + const low = value % MAX_INT32; + const buf = /* @__PURE__ */ new Uint8Array(8); + writeUInt32BE(buf, high, 0); + writeUInt32BE(buf, low, 4); + return buf; +} +function uint32be(value) { + const buf = /* @__PURE__ */ new Uint8Array(4); + writeUInt32BE(buf, value); + return buf; +} +function encode$1(string) { + const bytes = new Uint8Array(string.length); + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code > 127) throw new TypeError("non-ASCII string encountered in encode()"); + bytes[i] = code; + } + return bytes; +} +//#endregion +//#region node_modules/jose/dist/webapi/lib/base64.js +function encodeBase64(input) { + if (Uint8Array.prototype.toBase64) return input.toBase64(); + const CHUNK_SIZE = 32768; + const arr = []; + for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE))); + return btoa(arr.join("")); +} +function decodeBase64(encoded) { + if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded); + const binary = atob(encoded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} +//#endregion +//#region node_modules/jose/dist/webapi/util/base64url.js +function decode(input) { + if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" }); + let encoded = input; + if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded); + encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); + try { + return decodeBase64(encoded); + } catch { + throw new TypeError("The input to be decoded is not correctly encoded."); + } +} +function encode(input) { + let unencoded = input; + if (typeof unencoded === "string") unencoded = encoder.encode(unencoded); + if (Uint8Array.prototype.toBase64) return unencoded.toBase64({ + alphabet: "base64url", + omitPadding: true }); - return inst; -}); -/** @internal */ -var _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - _installLazyMethods(inst, "_ZodString", { - regex(...args) { - return this.check(/* @__PURE__ */ _regex(...args)); - }, - includes(...args) { - return this.check(/* @__PURE__ */ _includes(...args)); - }, - startsWith(...args) { - return this.check(/* @__PURE__ */ _startsWith(...args)); - }, - endsWith(...args) { - return this.check(/* @__PURE__ */ _endsWith(...args)); - }, - min(...args) { - return this.check(/* @__PURE__ */ _minLength(...args)); - }, - max(...args) { - return this.check(/* @__PURE__ */ _maxLength(...args)); - }, - length(...args) { - return this.check(/* @__PURE__ */ _length(...args)); - }, - nonempty(...args) { - return this.check(/* @__PURE__ */ _minLength(1, ...args)); - }, - lowercase(params) { - return this.check(/* @__PURE__ */ _lowercase(params)); - }, - uppercase(params) { - return this.check(/* @__PURE__ */ _uppercase(params)); - }, - trim() { - return this.check(/* @__PURE__ */ _trim()); - }, - normalize(...args) { - return this.check(/* @__PURE__ */ _normalize(...args)); - }, - toLowerCase() { - return this.check(/* @__PURE__ */ _toLowerCase()); - }, - toUpperCase() { - return this.check(/* @__PURE__ */ _toUpperCase()); - }, - slugify() { - return this.check(/* @__PURE__ */ _slugify()); + return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); +} +//#endregion +//#region node_modules/jose/dist/webapi/lib/crypto_key.js +var unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); +var isAlgorithm = (algorithm, name) => algorithm.name === name; +function getHashLength(hash) { + return parseInt(hash.name.slice(4), 10); +} +function checkHashLength(algorithm, expected) { + if (getHashLength(algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); +} +function getNamedCurve(alg) { + switch (alg) { + case "ES256": return "P-256"; + case "ES384": return "P-384"; + case "ES512": return "P-521"; + default: throw new Error("unreachable"); + } +} +function checkUsage(key, usage) { + if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); +} +function checkSigCryptoKey(key, alg, usage) { + switch (alg) { + case "HS256": + case "HS384": + case "HS512": + if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC"); + checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); + break; + case "RS256": + case "RS384": + case "RS512": + if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5"); + checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); + break; + case "PS256": + case "PS384": + case "PS512": + if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS"); + checkHashLength(key.algorithm, parseInt(alg.slice(2), 10)); + break; + case "Ed25519": + case "EdDSA": + if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519"); + break; + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": + if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg); + break; + case "ES256": + case "ES384": + case "ES512": { + if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA"); + const expected = getNamedCurve(alg); + if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve"); + break; } - }); -}); -var ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); - inst.email = (params) => inst.check(/* @__PURE__ */ _email(ZodEmail, params)); - inst.url = (params) => inst.check(/* @__PURE__ */ _url(ZodURL, params)); - inst.jwt = (params) => inst.check(/* @__PURE__ */ _jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(/* @__PURE__ */ _emoji(ZodEmoji, params)); - inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(/* @__PURE__ */ _uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(/* @__PURE__ */ _uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(/* @__PURE__ */ _uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(/* @__PURE__ */ _uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(/* @__PURE__ */ _nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(/* @__PURE__ */ _cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(/* @__PURE__ */ _cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(/* @__PURE__ */ _ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(/* @__PURE__ */ _base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(/* @__PURE__ */ _base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(/* @__PURE__ */ _xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(/* @__PURE__ */ _ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(/* @__PURE__ */ _ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(/* @__PURE__ */ _ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(/* @__PURE__ */ _cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(/* @__PURE__ */ _cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(/* @__PURE__ */ _e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime(params)); - inst.date = (params) => inst.check(date(params)); - inst.time = (params) => inst.check(time(params)); - inst.duration = (params) => inst.check(duration(params)); -}); -function string(params) { - return /* @__PURE__ */ _string(ZodString, params); + default: throw new TypeError("CryptoKey does not support this operation"); + } + checkUsage(key, usage); } -var ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -var ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function email(params) { - return /* @__PURE__ */ _email(ZodEmail, params); +function checkEncCryptoKey(key, alg, usage) { + switch (alg) { + case "A128GCM": + case "A192GCM": + case "A256GCM": { + if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM"); + const expected = parseInt(alg.slice(1, 4), 10); + if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length"); + break; + } + case "A128KW": + case "A192KW": + case "A256KW": { + if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW"); + const expected = parseInt(alg.slice(1, 4), 10); + if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length"); + break; + } + case "ECDH": + switch (key.algorithm.name) { + case "ECDH": + case "X25519": break; + default: throw unusable("ECDH or X25519"); + } + break; + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": + if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2"); + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP"); + checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1); + break; + default: throw new TypeError("CryptoKey does not support this operation"); + } + checkUsage(key, usage); +} +//#endregion +//#region node_modules/jose/dist/webapi/lib/invalid_key_input.js +function message(msg, actual, ...types) { + types = types.filter(Boolean); + if (types.length > 2) { + const last = types.pop(); + msg += `one of type ${types.join(", ")}, or ${last}.`; + } else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`; + else msg += `of type ${types[0]}.`; + if (actual == null) msg += ` Received ${actual}`; + else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`; + else if (typeof actual === "object" && actual != null) { + if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`; + } + return msg; +} +var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types); +var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types); +//#endregion +//#region node_modules/jose/dist/webapi/util/errors.js +var JOSEError = class extends Error { + static code = "ERR_JOSE_GENERIC"; + code = "ERR_JOSE_GENERIC"; + constructor(message, options) { + super(message, options); + this.name = this.constructor.name; + Error.captureStackTrace?.(this, this.constructor); + } +}; +var JWTClaimValidationFailed = class extends JOSEError { + static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + claim; + reason; + payload; + constructor(message, payload, claim = "unspecified", reason = "unspecified") { + super(message, { cause: { + claim, + reason, + payload + } }); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } +}; +var JWTExpired = class extends JOSEError { + static code = "ERR_JWT_EXPIRED"; + code = "ERR_JWT_EXPIRED"; + claim; + reason; + payload; + constructor(message, payload, claim = "unspecified", reason = "unspecified") { + super(message, { cause: { + claim, + reason, + payload + } }); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } +}; +var JOSEAlgNotAllowed = class extends JOSEError { + static code = "ERR_JOSE_ALG_NOT_ALLOWED"; + code = "ERR_JOSE_ALG_NOT_ALLOWED"; +}; +var JOSENotSupported = class extends JOSEError { + static code = "ERR_JOSE_NOT_SUPPORTED"; + code = "ERR_JOSE_NOT_SUPPORTED"; +}; +var JWEDecryptionFailed = class extends JOSEError { + static code = "ERR_JWE_DECRYPTION_FAILED"; + code = "ERR_JWE_DECRYPTION_FAILED"; + constructor(message = "decryption operation failed", options) { + super(message, options); + } +}; +var JWEInvalid = class extends JOSEError { + static code = "ERR_JWE_INVALID"; + code = "ERR_JWE_INVALID"; +}; +var JWSInvalid = class extends JOSEError { + static code = "ERR_JWS_INVALID"; + code = "ERR_JWS_INVALID"; +}; +var JWTInvalid = class extends JOSEError { + static code = "ERR_JWT_INVALID"; + code = "ERR_JWT_INVALID"; +}; +var JWKInvalid = class extends JOSEError { + static code = "ERR_JWK_INVALID"; + code = "ERR_JWK_INVALID"; +}; +var JWKSInvalid = class extends JOSEError { + static code = "ERR_JWKS_INVALID"; + code = "ERR_JWKS_INVALID"; +}; +var JWKSNoMatchingKey = class extends JOSEError { + static code = "ERR_JWKS_NO_MATCHING_KEY"; + code = "ERR_JWKS_NO_MATCHING_KEY"; + constructor(message = "no applicable key found in the JSON Web Key Set", options) { + super(message, options); + } +}; +var JWKSMultipleMatchingKeys = class extends JOSEError { + [Symbol.asyncIterator]; + static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + constructor(message = "multiple matching keys found in the JSON Web Key Set", options) { + super(message, options); + } +}; +var JWKSTimeout = class extends JOSEError { + static code = "ERR_JWKS_TIMEOUT"; + code = "ERR_JWKS_TIMEOUT"; + constructor(message = "request timed out", options) { + super(message, options); + } +}; +var JWSSignatureVerificationFailed = class extends JOSEError { + static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + constructor(message = "signature verification failed", options) { + super(message, options); + } +}; +//#endregion +//#region node_modules/jose/dist/webapi/lib/is_key_like.js +function assertCryptoKey(key) { + if (!isCryptoKey(key)) throw new Error("CryptoKey instance expected"); +} +var isCryptoKey = (key) => { + if (key?.[Symbol.toStringTag] === "CryptoKey") return true; + try { + return key instanceof CryptoKey; + } catch { + return false; + } +}; +var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; +var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); +//#endregion +//#region node_modules/jose/dist/webapi/lib/helpers.js +var unprotected = Symbol(); +function assertNotSet(value, name) { + if (value) throw new TypeError(`${name} can only be called once`); } -var ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -/** -* @deprecated CUID v1 is deprecated by its authors due to information leakage -* (timestamps embedded in the id). Use {@link ZodCUID2} instead. -* See https://github.com/paralleldrive/cuid. -*/ -var ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function ipv4(params) { - return /* @__PURE__ */ _ipv4(ZodIPv4, params); +function decodeBase64url(value, label, ErrorClass) { + try { + return decode(value); + } catch { + throw new ErrorClass(`Failed to base64url decode the ${label}`); + } } -var ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function ipv6(params) { - return /* @__PURE__ */ _ipv6(ZodIPv6, params); +async function digest(algorithm, data) { + const subtleDigest = `SHA-${algorithm.slice(-3)}`; + return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); } -var ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); - _installLazyMethods(inst, "ZodNumber", { - gt(value, params) { - return this.check(/* @__PURE__ */ _gt(value, params)); - }, - gte(value, params) { - return this.check(/* @__PURE__ */ _gte(value, params)); - }, - min(value, params) { - return this.check(/* @__PURE__ */ _gte(value, params)); - }, - lt(value, params) { - return this.check(/* @__PURE__ */ _lt(value, params)); - }, - lte(value, params) { - return this.check(/* @__PURE__ */ _lte(value, params)); - }, - max(value, params) { - return this.check(/* @__PURE__ */ _lte(value, params)); - }, - int(params) { - return this.check(int(params)); - }, - safe(params) { - return this.check(int(params)); - }, - positive(params) { - return this.check(/* @__PURE__ */ _gt(0, params)); - }, - nonnegative(params) { - return this.check(/* @__PURE__ */ _gte(0, params)); - }, - negative(params) { - return this.check(/* @__PURE__ */ _lt(0, params)); - }, - nonpositive(params) { - return this.check(/* @__PURE__ */ _lte(0, params)); - }, - multipleOf(value, params) { - return this.check(/* @__PURE__ */ _multipleOf(value, params)); - }, - step(value, params) { - return this.check(/* @__PURE__ */ _multipleOf(value, params)); - }, - finite() { - return this; +//#endregion +//#region node_modules/jose/dist/webapi/lib/type_checks.js +var isObjectLike = (value) => typeof value === "object" && value !== null; +function isObject(input) { + if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false; + if (Object.getPrototypeOf(input) === null) return true; + let proto = input; + while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto); + return Object.getPrototypeOf(input) === proto; +} +function isDisjoint(...headers) { + const sources = headers.filter(Boolean); + if (sources.length === 0 || sources.length === 1) return true; + let acc; + for (const header of sources) { + const parameters = Object.keys(header); + if (!acc || acc.size === 0) { + acc = new Set(parameters); + continue; } - }); - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); -function number(params) { - return /* @__PURE__ */ _number(ZodNumber, params); + for (const parameter of parameters) { + if (acc.has(parameter)) return false; + acc.add(parameter); + } + } + return true; } -var ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); -}); -function int(params) { - return /* @__PURE__ */ _int(ZodNumberFormat, params); +var isJWK = (key) => isObject(key) && typeof key.kty === "string"; +var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"); +var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0; +var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string"; +//#endregion +//#region node_modules/jose/dist/webapi/lib/signing.js +function checkKeyLength(alg, key) { + if (alg.startsWith("RS") || alg.startsWith("PS")) { + const { modulusLength } = key.algorithm; + if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); + } } -var ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); -}); -function boolean(params) { - return /* @__PURE__ */ _boolean(ZodBoolean, params); +function subtleAlgorithm(alg, algorithm) { + const hash = `SHA-${alg.slice(-3)}`; + switch (alg) { + case "HS256": + case "HS384": + case "HS512": return { + hash, + name: "HMAC" + }; + case "PS256": + case "PS384": + case "PS512": return { + hash, + name: "RSA-PSS", + saltLength: parseInt(alg.slice(-3), 10) >> 3 + }; + case "RS256": + case "RS384": + case "RS512": return { + hash, + name: "RSASSA-PKCS1-v1_5" + }; + case "ES256": + case "ES384": + case "ES512": return { + hash, + name: "ECDSA", + namedCurve: algorithm.namedCurve + }; + case "Ed25519": + case "EdDSA": return { name: "Ed25519" }; + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": return { name: alg }; + default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } } -var ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => void 0; -}); -function any() { - return /* @__PURE__ */ _any(ZodAny); +async function getSigKey(alg, key, usage) { + if (key instanceof Uint8Array) { + if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); + return crypto.subtle.importKey("raw", key, { + hash: `SHA-${alg.slice(-3)}`, + name: "HMAC" + }, false, [usage]); + } + checkSigCryptoKey(key, alg, usage); + return key; +} +async function sign(alg, key, data) { + const cryptoKey = await getSigKey(alg, key, "sign"); + checkKeyLength(alg, cryptoKey); + const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data); + return new Uint8Array(signature); +} +async function verify(alg, key, signature, data) { + const cryptoKey = await getSigKey(alg, key, "verify"); + checkKeyLength(alg, cryptoKey); + const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm); + try { + return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); + } catch { + return false; + } } -var ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => void 0; -}); -function unknown() { - return /* @__PURE__ */ _unknown(ZodUnknown); +//#endregion +//#region node_modules/jose/dist/webapi/lib/jwk_to_key.js +var unsupportedAlg = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value"; +function subtleMapping(jwk) { + let algorithm; + let keyUsages; + switch (jwk.kty) { + case "AKP": + switch (jwk.alg) { + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": + algorithm = { name: jwk.alg }; + keyUsages = jwk.priv ? ["sign"] : ["verify"]; + break; + default: throw new JOSENotSupported(unsupportedAlg); + } + break; + case "RSA": + switch (jwk.alg) { + case "PS256": + case "PS384": + case "PS512": + algorithm = { + name: "RSA-PSS", + hash: `SHA-${jwk.alg.slice(-3)}` + }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "RS256": + case "RS384": + case "RS512": + algorithm = { + name: "RSASSA-PKCS1-v1_5", + hash: `SHA-${jwk.alg.slice(-3)}` + }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + algorithm = { + name: "RSA-OAEP", + hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` + }; + keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; + break; + default: throw new JOSENotSupported(unsupportedAlg); + } + break; + case "EC": + switch (jwk.alg) { + case "ES256": + case "ES384": + case "ES512": + algorithm = { + name: "ECDSA", + namedCurve: { + ES256: "P-256", + ES384: "P-384", + ES512: "P-521" + }[jwk.alg] + }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + algorithm = { + name: "ECDH", + namedCurve: jwk.crv + }; + keyUsages = jwk.d ? ["deriveBits"] : []; + break; + default: throw new JOSENotSupported(unsupportedAlg); + } + break; + case "OKP": + switch (jwk.alg) { + case "Ed25519": + case "EdDSA": + algorithm = { name: "Ed25519" }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + algorithm = { name: jwk.crv }; + keyUsages = jwk.d ? ["deriveBits"] : []; + break; + default: throw new JOSENotSupported(unsupportedAlg); + } + break; + default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value"); + } + return { + algorithm, + keyUsages + }; } -var ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); -}); -function never(params) { - return /* @__PURE__ */ _never(ZodNever, params); +async function jwkToKey(jwk) { + if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present"); + const { algorithm, keyUsages } = subtleMapping(jwk); + const keyData = { ...jwk }; + if (keyData.kty !== "AKP") delete keyData.alg; + delete keyData.use; + return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); } -var ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; - _installLazyMethods(inst, "ZodArray", { - min(n, params) { - return this.check(/* @__PURE__ */ _minLength(n, params)); - }, - nonempty(params) { - return this.check(/* @__PURE__ */ _minLength(1, params)); - }, - max(n, params) { - return this.check(/* @__PURE__ */ _maxLength(n, params)); - }, - length(n, params) { - return this.check(/* @__PURE__ */ _length(n, params)); - }, - unwrap() { - return this.element; +//#endregion +//#region node_modules/jose/dist/webapi/lib/normalize_key.js +var unusableForAlg = "given KeyObject instance cannot be used for this algorithm"; +var cache; +var handleJWK = async (key, jwk, alg, freeze = false) => { + cache ||= /* @__PURE__ */ new WeakMap(); + let cached = cache.get(key); + if (cached?.[alg]) return cached[alg]; + const cryptoKey = await jwkToKey({ + ...jwk, + alg + }); + if (freeze) Object.freeze(key); + if (!cached) cache.set(key, { [alg]: cryptoKey }); + else cached[alg] = cryptoKey; + return cryptoKey; +}; +var handleKeyObject = (keyObject, alg) => { + cache ||= /* @__PURE__ */ new WeakMap(); + let cached = cache.get(keyObject); + if (cached?.[alg]) return cached[alg]; + const isPublic = keyObject.type === "public"; + const extractable = isPublic ? true : false; + let cryptoKey; + if (keyObject.asymmetricKeyType === "x25519") { + switch (alg) { + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": break; + default: throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]); + } + if (keyObject.asymmetricKeyType === "ed25519") { + if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError(unusableForAlg); + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]); + } + switch (keyObject.asymmetricKeyType) { + case "ml-dsa-44": + case "ml-dsa-65": + case "ml-dsa-87": + if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError(unusableForAlg); + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]); + } + if (keyObject.asymmetricKeyType === "rsa") { + let hash; + switch (alg) { + case "RSA-OAEP": + hash = "SHA-1"; + break; + case "RS256": + case "PS256": + case "RSA-OAEP-256": + hash = "SHA-256"; + break; + case "RS384": + case "PS384": + case "RSA-OAEP-384": + hash = "SHA-384"; + break; + case "RS512": + case "PS512": + case "RSA-OAEP-512": + hash = "SHA-512"; + break; + default: throw new TypeError(unusableForAlg); + } + if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({ + name: "RSA-OAEP", + hash + }, extractable, isPublic ? ["encrypt"] : ["decrypt"]); + cryptoKey = keyObject.toCryptoKey({ + name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", + hash + }, extractable, [isPublic ? "verify" : "sign"]); + } + if (keyObject.asymmetricKeyType === "ec") { + const namedCurve = (/* @__PURE__ */ new Map([ + ["prime256v1", "P-256"], + ["secp384r1", "P-384"], + ["secp521r1", "P-521"] + ])).get(keyObject.asymmetricKeyDetails?.namedCurve); + if (!namedCurve) throw new TypeError(unusableForAlg); + const expectedCurve = { + ES256: "P-256", + ES384: "P-384", + ES512: "P-521" + }; + if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) cryptoKey = keyObject.toCryptoKey({ + name: "ECDSA", + namedCurve + }, extractable, [isPublic ? "verify" : "sign"]); + if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({ + name: "ECDH", + namedCurve + }, extractable, isPublic ? [] : ["deriveBits"]); + } + if (!cryptoKey) throw new TypeError(unusableForAlg); + if (!cached) cache.set(keyObject, { [alg]: cryptoKey }); + else cached[alg] = cryptoKey; + return cryptoKey; +}; +async function normalizeKey(key, alg) { + if (key instanceof Uint8Array) return key; + if (isCryptoKey(key)) return key; + if (isKeyObject(key)) { + if (key.type === "secret") return key.export(); + if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try { + return handleKeyObject(key, alg); + } catch (err) { + if (err instanceof TypeError) throw err; } - }); -}); -function array(element, params) { - return /* @__PURE__ */ _array(ZodArray, element, params); + return handleJWK(key, key.export({ format: "jwk" }), alg); + } + if (isJWK(key)) { + if (key.k) return decode(key.k); + return handleJWK(key, key, alg, true); + } + throw new Error("unreachable"); } -var ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - defineLazy(inst, "shape", () => { - return def.shape; - }); - _installLazyMethods(inst, "ZodObject", { - keyof() { - return _enum(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ - ...this._zod.def, - catchall - }); - }, - passthrough() { - return this.clone({ - ...this._zod.def, - catchall: unknown() - }); - }, - loose() { - return this.clone({ - ...this._zod.def, - catchall: unknown() - }); - }, - strict() { - return this.clone({ - ...this._zod.def, - catchall: never() +//#endregion +//#region node_modules/jose/dist/webapi/key/import.js +async function importJWK(jwk, alg, options) { + if (!isObject(jwk)) throw new TypeError("JWK must be an object"); + let ext; + alg ??= jwk.alg; + ext ??= options?.extractable ?? jwk.ext; + switch (jwk.kty) { + case "oct": + if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value"); + return decode(jwk.k); + case "RSA": + if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported"); + return jwkToKey({ + ...jwk, + alg, + ext }); - }, - strip() { - return this.clone({ - ...this._zod.def, - catchall: void 0 + case "AKP": + if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value"); + if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch"); + return jwkToKey({ + ...jwk, + ext }); - }, - extend(incoming) { - return extend(this, incoming); - }, - safeExtend(incoming) { - return safeExtend(this, incoming); - }, - merge(other) { - return merge(this, other); - }, - pick(mask) { - return pick(this, mask); - }, - omit(mask) { - return omit(this, mask); - }, - partial(...args) { - return partial(ZodOptional, this, args[0]); - }, - required(...args) { - return required(ZodNonOptional, this, args[0]); + case "EC": + case "OKP": return jwkToKey({ + ...jwk, + alg, + ext + }); + default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value"); + } +} +//#endregion +//#region node_modules/jose/dist/webapi/lib/validate_crit.js +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected"); + if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set(); + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present"); + let recognized; + if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); + else recognized = recognizedDefault; + for (const parameter of protectedHeader.crit) { + if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`); + if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + return new Set(protectedHeader.crit); +} +//#endregion +//#region node_modules/jose/dist/webapi/lib/validate_algorithms.js +function validateAlgorithms(option, algorithms) { + if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`); + if (!algorithms) return; + return new Set(algorithms); +} +//#endregion +//#region node_modules/jose/dist/webapi/lib/check_key_type.js +var tag = (key) => key?.[Symbol.toStringTag]; +var jwkMatchesOp = (alg, key, usage) => { + if (key.use !== void 0) { + let expected; + switch (usage) { + case "sign": + case "verify": + expected = "sig"; + break; + case "encrypt": + case "decrypt": + expected = "enc"; + break; } - }); -}); -function object(shape, params) { - return new ZodObject({ - type: "object", - shape: shape ?? {}, - ...normalizeParams(params) - }); + if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); + } + if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`); + if (Array.isArray(key.key_ops)) { + let expectedKeyOp; + switch (true) { + case usage === "sign" || usage === "verify": + case alg === "dir": + case alg.includes("CBC-HS"): + expectedKeyOp = usage; + break; + case alg.startsWith("PBES2"): + expectedKeyOp = "deriveBits"; + break; + case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg): + if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; + else expectedKeyOp = usage; + break; + case usage === "encrypt" && alg.startsWith("RSA"): + expectedKeyOp = "wrapKey"; + break; + case usage === "decrypt": + expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits"; + break; + } + if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); + } + return true; +}; +var symmetricTypeCheck = (alg, key, usage) => { + if (key instanceof Uint8Array) return; + if (isJWK(key)) { + if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return; + throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); + } + if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array")); + if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); +}; +var asymmetricTypeCheck = (alg, key, usage) => { + if (isJWK(key)) switch (usage) { + case "decrypt": + case "sign": + if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return; + throw new TypeError(`JSON Web Key for this operation must be a private JWK`); + case "encrypt": + case "verify": + if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return; + throw new TypeError(`JSON Web Key for this operation must be a public JWK`); + } + if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key")); + if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); + if (key.type === "public") switch (usage) { + case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); + case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); + } + if (key.type === "private") switch (usage) { + case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); + case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); + } +}; +function checkKeyType(alg, key, usage) { + switch (alg.substring(0, 2)) { + case "A1": + case "A2": + case "di": + case "HS": + case "PB": + symmetricTypeCheck(alg, key, usage); + break; + default: asymmetricTypeCheck(alg, key, usage); + } +} +//#endregion +//#region node_modules/jose/dist/webapi/jws/flattened/verify.js +async function flattenedVerify(jws, key, options) { + if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object"); + if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members"); + if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type"); + if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing"); + if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type"); + if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type"); + let parsedProt = {}; + if (jws.protected) try { + const protectedHeader = decode(jws.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } catch { + throw new JWSInvalid("JWS Protected Header is invalid"); + } + if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); + const joseHeader = { + ...parsedProt, + ...jws.header + }; + const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); + let b64 = true; + if (extensions.has("b64")) { + b64 = parsedProt.b64; + if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean"); + } + const { alg } = joseHeader; + if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid"); + const algorithms = options && validateAlgorithms("algorithms", options.algorithms); + if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed"); + if (b64) { + if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string"); + } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); + let resolvedKey = false; + if (typeof key === "function") { + key = await key(parsedProt, jws); + resolvedKey = true; + } + checkKeyType(alg, key, "verify"); + const data = concat(jws.protected !== void 0 ? encode$1(jws.protected) : /* @__PURE__ */ new Uint8Array(), encode$1("."), typeof jws.payload === "string" ? b64 ? encode$1(jws.payload) : encoder.encode(jws.payload) : jws.payload); + const signature = decodeBase64url(jws.signature, "signature", JWSInvalid); + const k = await normalizeKey(key, alg); + if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed(); + let payload; + if (b64) payload = decodeBase64url(jws.payload, "payload", JWSInvalid); + else if (typeof jws.payload === "string") payload = encoder.encode(jws.payload); + else payload = jws.payload; + const result = { payload }; + if (jws.protected !== void 0) result.protectedHeader = parsedProt; + if (jws.header !== void 0) result.unprotectedHeader = jws.header; + if (resolvedKey) return { + ...result, + key: k + }; + return result; } -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params) - }); +//#endregion +//#region node_modules/jose/dist/webapi/jws/compact/verify.js +async function compactVerify(jws, key, options) { + if (jws instanceof Uint8Array) jws = decoder.decode(jws); + if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); + const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); + if (length !== 3) throw new JWSInvalid("Invalid Compact JWS"); + const verified = await flattenedVerify({ + payload, + protected: protectedHeader, + signature + }, key, options); + const result = { + payload: verified.payload, + protectedHeader: verified.protectedHeader + }; + if (typeof key === "function") return { + ...result, + key: verified.key + }; + return result; } -var ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function union(options, params) { - return new ZodUnion({ - type: "union", - options, - ...normalizeParams(params) - }); +//#endregion +//#region node_modules/jose/dist/webapi/lib/jwt_claims_set.js +var epoch = (date) => Math.floor(date.getTime() / 1e3); +var minute = 60; +var hour = minute * 60; +var day = hour * 24; +var week = day * 7; +var year = day * 365.25; +var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; +function secs(str) { + const matched = REGEX.exec(str); + if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format"); + const value = parseFloat(matched[2]); + const unit = matched[3].toLowerCase(); + let numericDate; + switch (unit) { + case "sec": + case "secs": + case "second": + case "seconds": + case "s": + numericDate = Math.round(value); + break; + case "minute": + case "minutes": + case "min": + case "mins": + case "m": + numericDate = Math.round(value * minute); + break; + case "hour": + case "hours": + case "hr": + case "hrs": + case "h": + numericDate = Math.round(value * hour); + break; + case "day": + case "days": + case "d": + numericDate = Math.round(value * day); + break; + case "week": + case "weeks": + case "w": + numericDate = Math.round(value * week); + break; + default: + numericDate = Math.round(value * year); + break; + } + if (matched[1] === "-" || matched[4] === "ago") return -numericDate; + return numericDate; } -var ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left, - right - }); +function validateInput(label, input) { + if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`); + return input; } -var ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function record(keyType, valueType, params) { - if (!valueType || !valueType._zod) return new ZodRecord({ - type: "record", - keyType: string(), - valueType: keyType, - ...normalizeParams(valueType) - }); - return new ZodRecord({ - type: "record", - keyType, - valueType, - ...normalizeParams(params) - }); +var normalizeTyp = (value) => { + if (value.includes("/")) return value.toLowerCase(); + return `application/${value.toLowerCase()}`; +}; +var checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === "string") return audOption.includes(audPayload); + if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload))); + return false; +}; +function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { + let payload; + try { + payload = JSON.parse(decoder.decode(encodedPayload)); + } catch {} + if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); + const { typ } = options; + if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed"); + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; + const presenceCheck = [...requiredClaims]; + if (maxTokenAge !== void 0) presenceCheck.push("iat"); + if (audience !== void 0) presenceCheck.push("aud"); + if (subject !== void 0) presenceCheck.push("sub"); + if (issuer !== void 0) presenceCheck.push("iss"); + for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); + if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed"); + if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed"); + if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed"); + let tolerance; + switch (typeof options.clockTolerance) { + case "string": + tolerance = secs(options.clockTolerance); + break; + case "number": + tolerance = options.clockTolerance; + break; + case "undefined": + tolerance = 0; + break; + default: throw new TypeError("Invalid clockTolerance option type"); + } + const { currentDate } = options; + const now = epoch(currentDate || /* @__PURE__ */ new Date()); + if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid"); + if (payload.nbf !== void 0) { + if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid"); + if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed"); + } + if (payload.exp !== void 0) { + if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid"); + if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed"); + } + if (maxTokenAge) { + const age = now - payload.iat; + const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge); + if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed"); + if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed"); + } + return payload; } -var ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value]; - else throw new Error(`Key ${value} not found in enum`); - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries - }); +var JWTClaimsBuilder = class { + #payload; + constructor(payload) { + if (!isObject(payload)) throw new TypeError("JWT Claims Set MUST be an object"); + this.#payload = structuredClone(payload); + } + data() { + return encoder.encode(JSON.stringify(this.#payload)); + } + get iss() { + return this.#payload.iss; + } + set iss(value) { + this.#payload.iss = value; + } + get sub() { + return this.#payload.sub; + } + set sub(value) { + this.#payload.sub = value; + } + get aud() { + return this.#payload.aud; + } + set aud(value) { + this.#payload.aud = value; + } + set jti(value) { + this.#payload.jti = value; + } + set nbf(value) { + if (typeof value === "number") this.#payload.nbf = validateInput("setNotBefore", value); + else if (value instanceof Date) this.#payload.nbf = validateInput("setNotBefore", epoch(value)); + else this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value); + } + set exp(value) { + if (typeof value === "number") this.#payload.exp = validateInput("setExpirationTime", value); + else if (value instanceof Date) this.#payload.exp = validateInput("setExpirationTime", epoch(value)); + else this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value); + } + set iat(value) { + if (value === void 0) this.#payload.iat = epoch(/* @__PURE__ */ new Date()); + else if (value instanceof Date) this.#payload.iat = validateInput("setIssuedAt", epoch(value)); + else if (typeof value === "string") this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)); + else this.#payload.iat = validateInput("setIssuedAt", value); + } +}; +//#endregion +//#region node_modules/jose/dist/webapi/jwt/verify.js +async function jwtVerify(jwt, key, options) { + const verified = await compactVerify(jwt, key, options); + if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); + const result = { + payload: validateClaimsSet(verified.protectedHeader, verified.payload, options), + protectedHeader: verified.protectedHeader }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) if (keys.has(value)) delete newEntries[value]; - else throw new Error(`Key ${value} not found in enum`); - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries - }); + if (typeof key === "function") return { + ...result, + key: verified.key }; -}); -function _enum(values, params) { - return new ZodEnum({ - type: "enum", - entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values, - ...normalizeParams(params) - }); + return result; } -var ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name); - payload.addIssue = (issue$1) => { - if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def)); - else { - const _issue = issue$1; - if (_issue.fatal) _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = inst); - payload.issues.push(issue(_issue)); - } +//#endregion +//#region node_modules/jose/dist/webapi/jwks/local.js +function getKtyFromAlg(alg) { + switch (typeof alg === "string" && alg.slice(0, 2)) { + case "RS": + case "PS": return "RSA"; + case "ES": return "EC"; + case "Ed": return "OKP"; + case "ML": return "AKP"; + default: throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set"); + } +} +function isJWKSLike(jwks) { + return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); +} +function isJWKLike(key) { + return isObject(key); +} +var LocalJWKSet = class { + #jwks; + #cached = /* @__PURE__ */ new WeakMap(); + constructor(jwks) { + if (!isJWKSLike(jwks)) throw new JWKSInvalid("JSON Web Key Set malformed"); + this.#jwks = structuredClone(jwks); + } + jwks() { + return this.#jwks; + } + async getKey(protectedHeader, token) { + const { alg, kid } = { + ...protectedHeader, + ...token?.header }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) return output.then((output) => { - payload.value = output; - payload.fallback = true; - return payload; + const kty = getKtyFromAlg(alg); + const candidates = this.#jwks.keys.filter((jwk) => { + let candidate = kty === jwk.kty; + if (candidate && typeof kid === "string") candidate = kid === jwk.kid; + if (candidate && (typeof jwk.alg === "string" || kty === "AKP")) candidate = alg === jwk.alg; + if (candidate && typeof jwk.use === "string") candidate = jwk.use === "sig"; + if (candidate && Array.isArray(jwk.key_ops)) candidate = jwk.key_ops.includes("verify"); + if (candidate) switch (alg) { + case "ES256": + candidate = jwk.crv === "P-256"; + break; + case "ES384": + candidate = jwk.crv === "P-384"; + break; + case "ES512": + candidate = jwk.crv === "P-521"; + break; + case "Ed25519": + case "EdDSA": + candidate = jwk.crv === "Ed25519"; + break; + } + return candidate; }); - payload.value = output; - payload.fallback = true; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn - }); + const { 0: jwk, length } = candidates; + if (length === 0) throw new JWKSNoMatchingKey(); + if (length !== 1) { + const error = new JWKSMultipleMatchingKeys(); + const _cached = this.#cached; + error[Symbol.asyncIterator] = async function* () { + for (const jwk of candidates) try { + yield await importWithAlgCache(_cached, jwk, alg); + } catch {} + }; + throw error; + } + return importWithAlgCache(this.#cached, jwk, alg); + } +}; +async function importWithAlgCache(cache, jwk, alg) { + const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); + if (cached[alg] === void 0) { + const key = await importJWK({ + ...jwk, + ext: true + }, alg); + if (key instanceof Uint8Array || key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys"); + cached[alg] = key; + } + return cached[alg]; } -var ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType - }); +function createLocalJWKSet(jwks) { + const set = new LocalJWKSet(jwks); + const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); + Object.defineProperties(localJWKSet, { jwks: { + value: () => structuredClone(set.jwks()), + enumerable: false, + configurable: false, + writable: false + } }); + return localJWKSet; } -var ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType - }); +//#endregion +//#region node_modules/jose/dist/webapi/jwks/remote.js +function isCloudflareWorkers() { + return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; } -var ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType +var USER_AGENT; +if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.2.4`; +var customFetch = Symbol(); +async function fetchJwks(url, headers, signal, fetchImpl = fetch) { + const response = await fetchImpl(url, { + method: "GET", + signal, + redirect: "manual", + headers + }).catch((err) => { + if (err.name === "TimeoutError") throw new JWKSTimeout(); + throw err; }); + if (response.status !== 200) throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); + try { + return await response.json(); + } catch { + throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); + } } -var ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function _default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); +var jwksCache = Symbol(); +function isFreshJwksCache(input, cacheMaxAge) { + if (typeof input !== "object" || input === null) return false; + if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) return false; + if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) return false; + return true; +} +var RemoteJWKSet = class { + #url; + #timeoutDuration; + #cooldownDuration; + #cacheMaxAge; + #jwksTimestamp; + #pendingFetch; + #headers; + #customFetch; + #local; + #cache; + constructor(url, options) { + if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL"); + this.#url = new URL(url.href); + this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3; + this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4; + this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5; + this.#headers = new Headers(options?.headers); + if (USER_AGENT && !this.#headers.has("User-Agent")) this.#headers.set("User-Agent", USER_AGENT); + if (!this.#headers.has("accept")) { + this.#headers.set("accept", "application/json"); + this.#headers.append("accept", "application/jwk-set+json"); } - }); -} -var ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + this.#customFetch = options?.[customFetch]; + if (options?.[jwksCache] !== void 0) { + this.#cache = options?.[jwksCache]; + if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) { + this.#jwksTimestamp = this.#cache.uat; + this.#local = createLocalJWKSet(this.#cache.jwks); + } + } + } + pendingFetch() { + return !!this.#pendingFetch; + } + coolingDown() { + return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false; + } + fresh() { + return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false; + } + jwks() { + return this.#local?.jwks(); + } + async getKey(protectedHeader, token) { + if (!this.#local || !this.fresh()) await this.reload(); + try { + return await this.#local(protectedHeader, token); + } catch (err) { + if (err instanceof JWKSNoMatchingKey) { + if (this.coolingDown() === false) { + await this.reload(); + return this.#local(protectedHeader, token); + } + } + throw err; + } + } + async reload() { + if (this.#pendingFetch && isCloudflareWorkers()) this.#pendingFetch = void 0; + this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => { + this.#local = createLocalJWKSet(json); + if (this.#cache) { + this.#cache.uat = Date.now(); + this.#cache.jwks = json; + } + this.#jwksTimestamp = Date.now(); + this.#pendingFetch = void 0; + }).catch((err) => { + this.#pendingFetch = void 0; + throw err; + }); + await this.#pendingFetch; + } +}; +function createRemoteJWKSet(url, options) { + const set = new RemoteJWKSet(url, options); + const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); + Object.defineProperties(remoteJWKSet, { + coolingDown: { + get: () => set.coolingDown(), + enumerable: true, + configurable: false + }, + fresh: { + get: () => set.fresh(), + enumerable: true, + configurable: false + }, + reload: { + value: () => set.reload(), + enumerable: true, + configurable: false, + writable: false + }, + reloading: { + get: () => set.pendingFetch(), + enumerable: true, + configurable: false + }, + jwks: { + value: () => set.jwks(), + enumerable: true, + configurable: false, + writable: false } }); + return remoteJWKSet; } -var ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType, - ...normalizeParams(params) - }); +//#endregion +//#region node_modules/jose/dist/webapi/util/decode_protected_header.js +function decodeProtectedHeader(token) { + let protectedB64u; + if (typeof token === "string") { + const parts = token.split("."); + if (parts.length === 3 || parts.length === 5) [protectedB64u] = parts; + } else if (typeof token === "object" && token) if ("protected" in token) protectedB64u = token.protected; + else throw new TypeError("Token does not contain a Protected Header"); + try { + if (typeof protectedB64u !== "string" || !protectedB64u) throw new Error(); + const result = JSON.parse(decoder.decode(decode(protectedB64u))); + if (!isObject(result)) throw new Error(); + return result; + } catch { + throw new TypeError("Invalid Token or Protected Header formatting"); + } } -var ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function _catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); +//#endregion +//#region node_modules/jose/dist/webapi/util/decode_jwt.js +function decodeJwt(jwt) { + if (typeof jwt !== "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); + const { 1: payload, length } = jwt.split("."); + if (length === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); + if (length !== 3) throw new JWTInvalid("Invalid JWT"); + if (!payload) throw new JWTInvalid("JWTs must contain a payload"); + let decoded; + try { + decoded = decode(payload); + } catch { + throw new JWTInvalid("Failed to base64url decode the payload"); + } + let result; + try { + result = JSON.parse(decoder.decode(decoded)); + } catch { + throw new JWTInvalid("Failed to parse the decoded payload as JSON"); + } + if (!isObject(result)) throw new JWTInvalid("Invalid JWT Claims Set"); + return result; } -var ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out - }); +//#endregion +//#region node_modules/@better-auth/utils/dist/index.mjs +function getWebcryptoSubtle() { + const cr = typeof globalThis !== "undefined" && globalThis.crypto; + if (cr && typeof cr.subtle === "object" && cr.subtle != null) return cr.subtle; + throw new Error("crypto.subtle must be defined"); } -var ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType - }); +//#endregion +//#region node_modules/@better-auth/utils/dist/base64.mjs +function getAlphabet(urlSafe) { + return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; } -var ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); -}); -function refine(fn, _params = {}) { - return /* @__PURE__ */ _refine(ZodCustom, fn, _params); +function base64Encode(data, alphabet, padding) { + let result = ""; + let buffer = 0; + let shift = 0; + for (const byte of data) { + buffer = buffer << 8 | byte; + shift += 8; + while (shift >= 6) { + shift -= 6; + result += alphabet[buffer >> shift & 63]; + } + } + if (shift > 0) result += alphabet[buffer << 6 - shift & 63]; + if (padding) { + const padCount = (4 - result.length % 4) % 4; + result += "=".repeat(padCount); + } + return result; } -function superRefine(fn, params) { - return /* @__PURE__ */ _superRefine(fn, params); +function base64Decode(data, alphabet) { + const decodeMap = /* @__PURE__ */ new Map(); + for (let i = 0; i < alphabet.length; i++) decodeMap.set(alphabet[i], i); + const result = []; + let buffer = 0; + let bitsCollected = 0; + for (const char of data) { + if (char === "=") break; + const value = decodeMap.get(char); + if (value === void 0) throw new Error(`Invalid Base64 character: ${char}`); + buffer = buffer << 6 | value; + bitsCollected += 6; + if (bitsCollected >= 8) { + bitsCollected -= 8; + result.push(buffer >> bitsCollected & 255); + } + } + return Uint8Array.from(result); } +var base64 = { + encode(data, options = {}) { + const alphabet = getAlphabet(false); + return base64Encode(typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data), alphabet, options.padding ?? true); + }, + decode(data) { + if (typeof data !== "string") data = new TextDecoder().decode(data); + const alphabet = getAlphabet(data.includes("-") || data.includes("_")); + return base64Decode(data, alphabet); + } +}; +var base64Url = { + encode(data, options = {}) { + const alphabet = getAlphabet(true); + return base64Encode(typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data), alphabet, options.padding ?? true); + }, + decode(data) { + return base64Decode(data, getAlphabet(data.includes("-") || data.includes("_"))); + } +}; //#endregion //#region node_modules/@better-auth/core/dist/utils/db.mjs /** @@ -15848,8 +16422,8 @@ function createRefreshAccessTokenRequest({ refreshToken, options, authentication body.set("refresh_token", refreshToken); if (authentication === "basic") { const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - if (primaryClientId) headers["authorization"] = "Basic " + base64$1.encode(`${primaryClientId}:${options.clientSecret ?? ""}`); - else headers["authorization"] = "Basic " + base64$1.encode(`:${options.clientSecret ?? ""}`); + if (primaryClientId) headers["authorization"] = "Basic " + base64.encode(`${primaryClientId}:${options.clientSecret ?? ""}`); + else headers["authorization"] = "Basic " + base64.encode(`:${options.clientSecret ?? ""}`); } else { const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; body.set("client_id", primaryClientId); @@ -15923,7 +16497,7 @@ function createAuthorizationCodeRequest({ code, codeVerifier, redirectURI, optio else for (const _resource of resource) body.append("resource", _resource); if (authentication === "basic") { const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - requestHeaders["authorization"] = `Basic ${base64$1.encode(`${primaryClientId}:${options.clientSecret ?? ""}`)}`; + requestHeaders["authorization"] = `Basic ${base64.encode(`${primaryClientId}:${options.clientSecret ?? ""}`)}`; } else { const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; body.set("client_id", primaryClientId); @@ -17467,7 +18041,7 @@ var microsoft = (options) => { if (options.disableProfilePhoto || !context.response.ok) return; try { const pictureBuffer = await context.response.clone().arrayBuffer(); - const pictureBase64 = base64$1.encode(pictureBuffer); + const pictureBase64 = base64.encode(pictureBuffer); user.picture = `data:image/jpeg;base64, ${pictureBase64}`; } catch (e) { logger.error(e && typeof e === "object" && "name" in e ? e.name : "", e); @@ -17763,7 +18337,7 @@ var paypal = (options) => { /** * PayPal requires Basic Auth for token exchange **/ - const credentials = base64$1.encode(`${options.clientId}:${options.clientSecret}`); + const credentials = base64.encode(`${options.clientId}:${options.clientSecret}`); try { const response = await betterFetch(tokenEndpoint, { method: "POST", @@ -17793,7 +18367,7 @@ var paypal = (options) => { } }, refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken) => { - const credentials = base64$1.encode(`${options.clientId}:${options.clientSecret}`); + const credentials = base64.encode(`${options.clientId}:${options.clientSecret}`); try { const response = await betterFetch(tokenEndpoint, { method: "POST", @@ -18066,7 +18640,7 @@ var reddit = (options) => { "content-type": "application/x-www-form-urlencoded", accept: "text/plain", "user-agent": "better-auth", - Authorization: `Basic ${base64$1.encode(`${options.clientId}:${options.clientSecret}`)}` + Authorization: `Basic ${base64.encode(`${options.clientId}:${options.clientSecret}`)}` }, body: body.toString() }); @@ -18885,4 +19459,4 @@ var socialProviders = { }; var SocialProviderListEnum = _enum(Object.keys(socialProviders)).or(string()); //#endregion -export { sign as $, logger as $t, email as A, withSpan as At, base64Url as B, runWithTransaction as Bt, toResponse as C, encode$1 as Ct, any as D, uint32be as Dt, ZodString as E, encode$2 as Et, record as F, safeJSONParse as Ft, JWTClaimsBuilder as G, createRandomStringGenerator as Gt, decodeJwt as H, initGetModelName as Ht, string as I, getAuthTables as It, validateAlgorithms as J, betterFetch as Jt, validateClaimsSet as K, capitalizeFirstLetter as Kt, _coercedBoolean as L, getCurrentAdapter as Lt, number as M, ATTR_HOOK_TYPE as Mt, object as N, ATTR_OPERATION_ID as Nt, array as O, uint64be as Ot, optional as P, import_src as Pt, checkKeyLength as Q, createLogger as Qt, _coercedString as R, queueAfterTransactionHook as Rt, serializeSignedCookie as S, decode$1 as St, ZodBoolean as T, decoder as Tt, decodeProtectedHeader as U, initGetFieldName as Ut, getWebcryptoSubtle as V, getBetterAuthVersion as Vt, jwtVerify as W, generateId as Wt, importJWK as X, isSafeUrlScheme as Xt, validateCrit as Y, createFetch as Yt, normalizeKey as Z, normalizePathname as Zt, runWithRequestState as _, JWTClaimValidationFailed as _t, createAuthorizationURL as a, isDevelopment as an, digest as at, createRouter$1 as b, invalidKeyInput as bt, createRateLimitKey as c, APIError as cn, isCryptoKey as ct, deprecate as d, BASE_ERROR_CODES as dn, JOSEAlgNotAllowed as dt, shouldPublishLog as en, isDisjoint as et, createAuthEndpoint as f, defineErrorCodes as fn, JOSENotSupported as ft, hasRequestState as g, JWSInvalid as gt, defineRequestState as h, JWKInvalid as ht, refreshAccessToken as i, getEnvVar as in, decodeBase64url as it, looseObject as j, ATTR_CONTEXT as jt, boolean as k, createAdapterFactory as kt, findInvalidTrustedProxies as l, BetterAuthError as ln, isKeyLike as lt, isAPIError as m, JWEInvalid as mt, socialProviders as n, env as nn, isObject$1 as nt, applyDefaultAccessTokenExpiry as o, isProduction as on, unprotected as ot, createAuthMiddleware as p, JWEDecryptionFailed as pt, checkKeyType as q, toKebabCase as qt, validateAuthorizationCode as r, getBooleanEnvVar as rn, assertNotSet as rt, isLoopbackHost as s, isTest as sn, assertCryptoKey as st, SocialProviderListEnum as t, ENV as tn, isJWK as tt, getIp as u, kAPIErrorHeaderSymbol as un, isKeyObject as ut, getCurrentAuthContext as v, JWTExpired as vt, filterOutputFields as w, concat as wt, serializeCookie as x, checkEncCryptoKey as xt, runWithEndpointContext as y, JWTInvalid as yt, base64$1 as z, runWithAdapter as zt }; +export { JWEDecryptionFailed as $, string as $t, jwtVerify as A, createFetch as An, generateId as At, isDisjoint as B, isDevelopment as Bn, array as Bt, toResponse as C, clone as Cn, getCurrentAdapter as Ct, getWebcryptoSubtle as D, capitalizeFirstLetter as Dn, getBetterAuthVersion as Dt, base64Url as E, NEVER as En, runWithTransaction as Et, validateCrit as F, shouldPublishLog as Fn, ZodType as Ft, digest as G, kAPIErrorHeaderSymbol as Gn, intersection as Gt, isObject as H, isTest as Hn, custom as Ht, importJWK as I, ENV as In, _enum as It, isCryptoKey as J, number as Jt, unprotected as K, BASE_ERROR_CODES as Kn, literal as Kt, normalizeKey as L, env as Ln, _instanceof as Lt, validateClaimsSet as M, normalizePathname as Mn, ZodBoolean as Mt, checkKeyType as N, createLogger as Nn, ZodNumber as Nt, decodeJwt as O, toKebabCase as On, initGetModelName as Ot, validateAlgorithms as P, logger as Pn, ZodString as Pt, JOSENotSupported as Q, record as Qt, checkKeyLength as R, getBooleanEnvVar as Rn, _null as Rt, serializeSignedCookie as S, prettifyError as Sn, getAuthTables as St, base64 as T, partial as Tn, runWithAdapter as Tt, assertNotSet as U, APIError as Un, discriminatedUnion as Ut, isJWK as V, isProduction as Vn, boolean as Vt, decodeBase64url as W, BetterAuthError as Wn, email as Wt, isKeyObject as X, optional as Xt, isKeyLike as Y, object as Yt, JOSEAlgNotAllowed as Z, preprocess as Zt, runWithRequestState as _, $ZodOptional as _n, ATTR_CONTEXT as _t, createAuthorizationURL as a, ZodError as an, JWTInvalid as at, createRouter$1 as b, parseAsync$1 as bn, import_src as bt, createRateLimitKey as c, _coercedBoolean as cn, decode as ct, deprecate as d, _never as dn, decoder as dt, tuple as en, JWEInvalid as et, createAuthEndpoint as f, _unknown as fn, encode$1 as ft, hasRequestState as g, $ZodNever as gn, withSpan as gt, defineRequestState as h, registry as hn, createAdapterFactory as ht, refreshAccessToken as i, parse as in, JWTExpired as it, JWTClaimsBuilder as j, isSafeUrlScheme as jn, createRandomStringGenerator as jt, decodeProtectedHeader as k, betterFetch as kn, initGetFieldName as kt, findInvalidTrustedProxies as l, _coercedNumber as ln, encode as lt, isAPIError as m, globalRegistry as mn, uint64be as mt, socialProviders as n, unknown as nn, JWSInvalid as nt, applyDefaultAccessTokenExpiry as o, datetime as on, invalidKeyInput as ot, createAuthMiddleware as p, $ZodRegistry as pn, uint32be as pt, assertCryptoKey as q, defineErrorCodes as qn, looseObject as qt, validateAuthorizationCode as r, url as rn, JWTClaimValidationFailed as rt, isLoopbackHost as s, toJSONSchema as sn, checkEncCryptoKey as st, SocialProviderListEnum as t, union as tn, JWKInvalid as tt, getIp as u, _coercedString as un, concat as ut, getCurrentAuthContext as v, $ZodUnknown as vn, ATTR_HOOK_TYPE as vt, filterOutputFields as w, extend as wn, queueAfterTransactionHook as wt, serializeCookie as x, safeParse$1 as xn, safeJSONParse as xt, runWithEndpointContext as y, parse$1 as yn, ATTR_OPERATION_ID as yt, sign as z, getEnvVar as zn, any as zt }; diff --git a/.vercel/output/functions/__server.func/_libs/@better-auth/kysely-adapter+[...].mjs b/.vercel/output/functions/__server.func/_libs/@better-auth/kysely-adapter+[...].mjs index 61ff0f3..b463b9b 100644 --- a/.vercel/output/functions/__server.func/_libs/@better-auth/kysely-adapter+[...].mjs +++ b/.vercel/output/functions/__server.func/_libs/@better-auth/kysely-adapter+[...].mjs @@ -1,5 +1,5 @@ import { r as __exportAll } from "../../_runtime.mjs"; -import { $t as logger, Kt as capitalizeFirstLetter, kt as createAdapterFactory } from "./core+[...].mjs"; +import { Dn as capitalizeFirstLetter, Pn as logger, ht as createAdapterFactory } from "./core+[...].mjs"; //#region node_modules/kysely/dist/esm/util/object-utils.js function isUndefined(obj) { return typeof obj === "undefined" || obj === void 0; diff --git a/.vercel/output/functions/__server.func/_libs/@better-auth/telemetry+[...].mjs b/.vercel/output/functions/__server.func/_libs/@better-auth/telemetry+[...].mjs index 4d513d1..2921ed5 100644 --- a/.vercel/output/functions/__server.func/_libs/@better-auth/telemetry+[...].mjs +++ b/.vercel/output/functions/__server.func/_libs/@better-auth/telemetry+[...].mjs @@ -1,8 +1,8 @@ -import { $t as logger, B as base64Url, Gt as createRandomStringGenerator, Jt as betterFetch, V as getWebcryptoSubtle, in as getEnvVar, nn as env, rn as getBooleanEnvVar, sn as isTest, tn as ENV, z as base64 } from "./core+[...].mjs"; +import { D as getWebcryptoSubtle, E as base64Url, Hn as isTest, In as ENV, Ln as env, Pn as logger, Rn as getBooleanEnvVar, T as base64, jt as createRandomStringGenerator, kn as betterFetch, zn as getEnvVar } from "./core+[...].mjs"; +import fs$1 from "node:fs/promises"; import fs from "node:fs"; -import fsPromises from "node:fs/promises"; -import os from "node:os"; import path from "node:path"; +import os from "node:os"; //#region node_modules/@better-auth/utils/dist/hash.mjs function createHash(algorithm, encoding) { return { digest: async (input) => { @@ -253,7 +253,7 @@ async function readRootPackageJson() { try { const cwd = process.cwd(); if (!cwd) return void 0; - const raw = await fsPromises.readFile(path.join(cwd, "package.json"), "utf-8"); + const raw = await fs$1.readFile(path.join(cwd, "package.json"), "utf-8"); packageJSONCache = JSON.parse(raw); return packageJSONCache; } catch {} @@ -264,7 +264,7 @@ async function getPackageVersion(pkg) { const cwd = process.cwd(); if (!cwd) throw new Error("no-cwd"); const pkgJsonPath = path.join(cwd, "node_modules", pkg, "package.json"); - const raw = await fsPromises.readFile(pkgJsonPath, "utf-8"); + const raw = await fs$1.readFile(pkgJsonPath, "utf-8"); return JSON.parse(raw).version || await getVersionFromLocalPackageJson(pkg) || void 0; } catch {} return getVersionFromLocalPackageJson(pkg); diff --git a/.vercel/output/functions/__server.func/_libs/@langchain/anthropic+[...].mjs b/.vercel/output/functions/__server.func/_libs/@langchain/anthropic+[...].mjs new file mode 100644 index 0000000..b5baf16 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/@langchain/anthropic+[...].mjs @@ -0,0 +1,35105 @@ +import { o as __toESM, r as __exportAll$1, t as __commonJSMin } from "../../_runtime.mjs"; +import { $t as string, Bt as array, Cn as clone, Ht as custom$1, It as _enum, Jt as number, Kt as literal, Sn as prettifyError, Tn as partial, Ut as discriminatedUnion, Vt as boolean, Yt as object, _n as $ZodOptional, bn as parseAsync, dn as _never, en as tuple, fn as _unknown, gn as $ZodNever, mn as globalRegistry, nn as unknown, sn as toJSONSchema, tn as union, vn as $ZodUnknown, wn as extend, yn as parse$3 } from "../@better-auth/core+[...].mjs"; +import { i as deepCompareStrict, n as validate$4, r as dereference, t as Validator } from "../cfworker__json-schema.mjs"; +import { n as Anthropic, t as transformJSONSchema } from "../@anthropic-ai/sdk+[...].mjs"; +import * as nodeFsPromises from "node:fs/promises"; +import * as nodeFs from "node:fs"; +import * as nodePath from "node:path"; +import { Worker } from "node:worker_threads"; +//#region node_modules/@langchain/core/dist/_virtual/_rolldown/runtime.js +var __defProp$1 = Object.defineProperty; +var __exportAll = (all, no_symbols) => { + let target = {}; + for (var name in all) __defProp$1(target, name, { + get: all[name], + enumerable: true + }); + if (!no_symbols) __defProp$1(target, Symbol.toStringTag, { value: "Module" }); + return target; +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/namespace.js +/** +* Create a symbol-based namespace for hierarchical `isInstance` checking. +* +* Each namespace level gets its own `Symbol.for(path)`. When a class is +* branded via `.brand()`, only the new symbol for that level is stamped +* on the prototype. Parent symbols are inherited implicitly through the +* class extension chain -- `symbol in obj` traverses the prototype chain, +* so a `ConfigError` instance is recognized by `LangChainError.isInstance()` +* because it extends `GoogleError` which extends `LangChainError`, whose +* prototype already carries the `langchain.error` symbol. +* +* @param path - The dot-separated namespace path (e.g. "langchain.error") +* @returns A Namespace object with `.brand()`, `.sub()`, and `.isInstance()` +* +* @example +* ```typescript +* const langchain = createNamespace("langchain"); +* const errorNs = langchain.sub("error"); +* const googleNs = errorNs.sub("google"); +* +* class LangChainError extends errorNs.brand(Error) {} +* class GoogleError extends googleNs.brand(LangChainError) {} +* class ConfigError extends googleNs.brand(GoogleError, "configuration") {} +* +* const err = new ConfigError("bad config"); +* LangChainError.isInstance(err); // true (checks langchain.error symbol) +* GoogleError.isInstance(err); // true (checks langchain.error.google symbol) +* ConfigError.isInstance(err); // true (checks langchain.error.google.configuration symbol) +* ``` +*/ +function createNamespace(path) { + const symbol = Symbol.for(path); + return { + brand(Base, marker) { + const brandSymbol = marker ? Symbol.for(`${path}.${marker}`) : symbol; + class _Branded extends Base { + [brandSymbol] = true; + constructor(...args) { + super(...args); + } + static isInstance(obj) { + return typeof obj === "object" && obj !== null && brandSymbol in obj && obj[brandSymbol] === true; + } + } + Object.defineProperty(_Branded, "name", { value: Base.name }); + return _Branded; + }, + sub(childPath) { + return createNamespace(`${path}.${childPath}`); + }, + isInstance(obj) { + return typeof obj === "object" && obj !== null && symbol in obj && obj[symbol] === true; + } + }; +} +/** Base namespace used throughout LangChain */ +var ns$1 = createNamespace("langchain"); +//#endregion +//#region node_modules/@langchain/core/dist/errors/index.js +var errors_exports = /* @__PURE__ */ __exportAll({ + ContextOverflowError: () => ContextOverflowError, + LangChainError: () => LangChainError, + ModelAbortError: () => ModelAbortError, + addLangChainErrorFields: () => addLangChainErrorFields$1, + ns: () => ns +}); +/** @deprecated Subclass LangChainError instead */ +function addLangChainErrorFields$1(error, lc_error_code) { + error.lc_error_code = lc_error_code; + error.message = `${error.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\n`; + return error; +} +/** The error namespace for all LangChain errors */ +var ns = ns$1.sub("error"); +/** +* Base error class for all LangChain errors. +* +* All LangChain error classes should extend this class (directly or +* indirectly). Use `LangChainError.isInstance(obj)` to check if an +* object is any LangChain error. +* +* @example +* ```typescript +* try { +* await model.invoke("hello"); +* } catch (error) { +* if (LangChainError.isInstance(error)) { +* console.log("Got a LangChain error:", error.message); +* } +* } +* ``` +*/ +var LangChainError = class extends ns.brand(Error) { + name = "LangChainError"; + constructor(message) { + super(message); + if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); + } +}; +/** +* Error class representing an aborted model operation in LangChain. +* +* This error is thrown when a model operation (such as invocation, streaming, or batching) +* is cancelled before it completes, commonly due to a user-initiated abort signal +* (e.g., via an AbortController) or an upstream cancellation event. +* +* The ModelAbortError provides access to any partial output the model may have produced +* before the operation was interrupted, which can be useful for resuming work, debugging, +* or presenting incomplete results to users. +* +* @remarks +* - The `partialOutput` field includes message content that was generated prior to the abort, +* such as a partial AIMessageChunk. +* - This error extends the {@link LangChainError} base class with the marker `"model-abort"`. +* +* @example +* ```typescript +* try { +* await model.invoke(input, { signal: abortController.signal }); +* } catch (err) { +* if (ModelAbortError.isInstance(err)) { +* // Handle user cancellation, check err.partialOutput if needed +* } else { +* throw err; +* } +* } +* ``` +*/ +var ModelAbortError = class extends ns.brand(LangChainError, "model-abort") { + name = "ModelAbortError"; + /** + * The partial message output that was produced before the operation was aborted. + * This is typically an AIMessageChunk, or could be undefined if no output was available. + */ + partialOutput; + /** + * Constructs a new ModelAbortError instance. + * + * @param message - A human-readable message describing the abort event. + * @param partialOutput - Any partial model output generated before the abort (optional). + */ + constructor(message, partialOutput) { + super(message); + this.partialOutput = partialOutput; + } +}; +/** +* Error class representing a context window overflow in a language model operation. +* +* This error is thrown when the combined input to a language model (such as prompt tokens, +* historical messages, and/or instructions) exceeds the maximum context window or token limit +* that the model can process in a single request. Most models have defined upper limits for the number of +* tokens or characters allowed in a context, and exceeding this limit will prevent +* the operation from proceeding. +* +* The {@link ContextOverflowError} extends the {@link LangChainError} base class with +* the marker `"context-overflow"`. +* +* @remarks +* - Use this error to programmatically identify cases where a user request, prompt, or input +* sequence is too long to be handled by the target model. +* - Model providers and framework integrations should throw this error if they detect +* a request cannot be processed due to its size. +* +* @example +* ```typescript +* try { +* await model.invoke(veryLongInput); +* } catch (err) { +* if (ContextOverflowError.isInstance(err)) { +* // Handle overflow, e.g., prompt user to shorten input or truncate text +* console.warn("Model context overflow:", err.message); +* } else { +* throw err; +* } +* } +* ``` +*/ +var ContextOverflowError = class ContextOverflowError extends ns.brand(LangChainError, "context-overflow") { + name = "ContextOverflowError"; + /** + * The underlying error that caused this {@link ContextOverflowError}, if any. + * + * This property is optionally set when wrapping a lower-level error using {@link ContextOverflowError.fromError}. + * It allows error handlers to access or inspect the original error that led to the context overflow. + */ + cause; + constructor(message) { + super(message ?? "Input exceeded the model's context window."); + } + /** + * Creates a new {@link ContextOverflowError} instance from an existing error. + * + * This static utility copies the message from the provided error and + * attaches the original error as the {@link ContextOverflowError.cause} property, + * enabling error handlers to inspect or propagate the original failure. + * + * @param obj - The original error object causing the context overflow. + * @returns A new {@link ContextOverflowError} instance with the original error set as its cause. + * + * @example + * ```typescript + * try { + * await model.invoke(input); + * } catch (err) { + * throw ContextOverflowError.fromError(err); + * } + * ``` + */ + static fromError(obj) { + const error = new ContextOverflowError(obj.message); + error.cause = obj; + return error; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/content/data.js +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isDataContentBlock(content_block) { + return typeof content_block === "object" && content_block !== null && "type" in content_block && typeof content_block.type === "string" && "source_type" in content_block && (content_block.source_type === "url" || content_block.source_type === "base64" || content_block.source_type === "text" || content_block.source_type === "id"); +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isURLContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "url" && "url" in content_block && typeof content_block.url === "string"; +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isBase64ContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "base64" && "data" in content_block && typeof content_block.data === "string"; +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isPlainTextContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "text" && "text" in content_block && typeof content_block.text === "string"; +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isIDContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "id" && "id" in content_block && typeof content_block.id === "string"; +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function convertToOpenAIImageBlock(content_block) { + if (isDataContentBlock(content_block)) { + if (content_block.source_type === "url") return { + type: "image_url", + image_url: { url: content_block.url } + }; + if (content_block.source_type === "base64") { + if (!content_block.mime_type) throw new Error("mime_type key is required for base64 data."); + return { + type: "image_url", + image_url: { url: `data:${content_block.mime_type};base64,${content_block.data}` } + }; + } + } + throw new Error("Unsupported source type. Only 'url' and 'base64' are supported."); +} +/** +* Utility function for ChatModelProviders. Parses a mime type into a type, subtype, and parameters. +* +* @param mime_type - The mime type to parse. +* @returns An object containing the type, subtype, and parameters. +* +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function parseMimeType(mime_type) { + const parts = mime_type.split(";")[0].split("/"); + if (parts.length !== 2) throw new Error(`Invalid mime type: "${mime_type}" - does not match type/subtype format.`); + const type = parts[0].trim(); + const subtype = parts[1].trim(); + if (type === "" || subtype === "") throw new Error(`Invalid mime type: "${mime_type}" - type or subtype is empty.`); + const parameters = {}; + for (const parameterKvp of mime_type.split(";").slice(1)) { + const parameterParts = parameterKvp.split("="); + if (parameterParts.length !== 2) throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); + const key = parameterParts[0].trim(); + const value = parameterParts[1].trim(); + if (key === "") throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); + parameters[key] = value; + } + return { + type, + subtype, + parameters + }; +} +/** +* Utility function for ChatModelProviders. Parses a base64 data URL into a typed array or string. +* +* @param dataUrl - The base64 data URL to parse. +* @param asTypedArray - Whether to return the data as a typed array. +* @returns The parsed data and mime type, or undefined if the data URL is invalid. +* +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function parseBase64DataUrl({ dataUrl: data_url, asTypedArray = false }) { + const formatMatch = data_url.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/); + let mime_type; + if (formatMatch) { + mime_type = formatMatch[1].toLowerCase(); + const data = asTypedArray ? Uint8Array.from(atob(formatMatch[2]), (c) => c.charCodeAt(0)) : formatMatch[2]; + return { + mime_type, + data + }; + } +} +/** +* Convert from a standard data content block to a provider's proprietary data content block format. +* +* Don't override this method. Instead, override the more specific conversion methods and use this +* method unmodified. +* +* @param block - The standard data content block to convert. +* @returns The provider data content block. +* @throws An error if the standard data content block type is not supported. +* +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function convertToProviderContentBlock(block, converter) { + if (block.type === "text") { + if (!converter.fromStandardTextBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardTextBlock\` method.`); + return converter.fromStandardTextBlock(block); + } + if (block.type === "image") { + if (!converter.fromStandardImageBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardImageBlock\` method.`); + return converter.fromStandardImageBlock(block); + } + if (block.type === "audio") { + if (!converter.fromStandardAudioBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardAudioBlock\` method.`); + return converter.fromStandardAudioBlock(block); + } + if (block.type === "file") { + if (!converter.fromStandardFileBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardFileBlock\` method.`); + return converter.fromStandardFileBlock(block); + } + throw new Error(`Unable to convert content block type '${block.type}' to provider-specific format: not recognized.`); +} +//#endregion +//#region node_modules/@langchain/core/dist/load/map_keys.js +var UPPER_TO_WORD_BOUNDARY = /([A-Z]+)([A-Z][a-z0-9]+)/g; +var LOWER_TO_UPPER_BOUNDARY = /([a-z0-9])([A-Z])/g; +var SEPARATORS = /[-_\s]+/g; +function snakeCase(key) { + return key.replace(UPPER_TO_WORD_BOUNDARY, "$1_$2").replace(LOWER_TO_UPPER_BOUNDARY, "$1_$2").replace(SEPARATORS, "_").toLowerCase(); +} +function camelCase(key) { + const trimmed = key.trim(); + if (!/[-_\s]/.test(trimmed)) return trimmed; + return trimmed.replace(SEPARATORS, "_").toLowerCase().replace(/_+([a-z0-9])/g, (_, char) => char.toUpperCase()); +} +function keyToJson(key, map) { + return map?.[key] || snakeCase(key); +} +function keyFromJson(key, map) { + return map?.[key] || camelCase(key); +} +function mapKeys(fields, mapper, map) { + const mapped = {}; + for (const key in fields) if (Object.hasOwn(fields, key)) mapped[mapper(key, map)] = fields[key]; + return mapped; +} +//#endregion +//#region node_modules/@langchain/core/dist/load/validation.js +/** +* Sentinel key used to mark escaped user objects during serialization. +* +* When a plain object contains 'lc' key (which could be confused with LC objects), +* we wrap it as `{"__lc_escaped__": {...original...}}`. +*/ +var LC_ESCAPED_KEY = "__lc_escaped__"; +/** +* Check if an object needs escaping to prevent confusion with LC objects. +* +* An object needs escaping if: +* 1. It has an `'lc'` key (could be confused with LC serialization format) +* 2. It has only the escape key (would be mistaken for an escaped object) +*/ +function needsEscaping(obj) { + return "lc" in obj || Object.keys(obj).length === 1 && "__lc_escaped__" in obj; +} +/** +* Wrap an object in the escape marker. +* +* @example +* ```typescript +* {"key": "value"} // becomes {"__lc_escaped__": {"key": "value"}} +* ``` +*/ +function escapeObject(obj) { + return { [LC_ESCAPED_KEY]: obj }; +} +/** +* Check if an object is an escaped user object. +* +* @example +* ```typescript +* {"__lc_escaped__": {...}} // is an escaped object +* ``` +*/ +function isEscapedObject(obj) { + return Object.keys(obj).length === 1 && "__lc_escaped__" in obj; +} +/** +* Check if an object looks like a Serializable instance (duck typing). +*/ +function isSerializableLike(obj) { + return obj !== null && typeof obj === "object" && "lc_serializable" in obj && typeof obj.toJSON === "function"; +} +/** +* Create a "not_implemented" serialization result for objects that cannot be serialized. +*/ +function createNotImplemented(obj) { + let id; + if (obj !== null && typeof obj === "object") if ("lc_id" in obj && Array.isArray(obj.lc_id)) id = obj.lc_id; + else id = [obj.constructor?.name ?? "Object"]; + else id = [typeof obj]; + return { + lc: 1, + type: "not_implemented", + id + }; +} +/** +* Escape a value if it needs escaping (contains `lc` key). +* +* This is a simpler version of `serializeValue` that doesn't handle Serializable +* objects - it's meant to be called on kwargs values that have already been +* processed by `toJSON()`. +* +* @param value - The value to potentially escape. +* @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references. +* Objects are removed after processing to allow shared references (same object in +* multiple places) while still detecting true circular references (ancestor in descendant). +* @returns The value with any `lc`-containing objects wrapped in escape markers. +*/ +function escapeIfNeeded(value, pathSet = /* @__PURE__ */ new WeakSet()) { + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + if (pathSet.has(value)) return createNotImplemented(value); + if (isSerializableLike(value)) return value; + pathSet.add(value); + const record = value; + if (needsEscaping(record)) { + pathSet.delete(value); + return escapeObject(record); + } + const result = {}; + for (const [key, val] of Object.entries(record)) result[key] = escapeIfNeeded(val, pathSet); + pathSet.delete(value); + return result; + } + if (Array.isArray(value)) return value.map((item) => escapeIfNeeded(item, pathSet)); + return value; +} +/** +* Unescape a value, processing escape markers in object values and arrays. +* +* When an escaped object is encountered (`{"__lc_escaped__": ...}`), it's +* unwrapped and the contents are returned AS-IS (no further processing). +* The contents represent user data that should not be modified. +* +* For regular objects and arrays, we recurse to find any nested escape markers. +* +* @param obj - The value to unescape. +* @returns The unescaped value. +*/ +function unescapeValue(obj) { + if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) { + const record = obj; + if (isEscapedObject(record)) return record[LC_ESCAPED_KEY]; + const result = {}; + for (const [key, value] of Object.entries(record)) result[key] = unescapeValue(value); + return result; + } + if (Array.isArray(obj)) return obj.map((item) => unescapeValue(item)); + return obj; +} +//#endregion +//#region node_modules/@langchain/core/dist/load/serializable.js +var serializable_exports = /* @__PURE__ */ __exportAll({ + Serializable: () => Serializable, + get_lc_unique_name: () => get_lc_unique_name +}); +function shallowCopy(obj) { + return Array.isArray(obj) ? [...obj] : { ...obj }; +} +function replaceSecrets(root, secretsMap) { + const result = shallowCopy(root); + 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; +} +/** +* Get a unique name for the module, rather than parent class implementations. +* Should not be subclassed, subclass lc_name above instead. +*/ +function get_lc_unique_name(serializableClass) { + const parentClass = Object.getPrototypeOf(serializableClass); + if (typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name())) return serializableClass.lc_name(); + else return serializableClass.name; +} +var Serializable = class Serializable { + lc_serializable = false; + lc_kwargs; + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [...this.lc_namespace, get_lc_unique_name(this.constructor)]; + } + /** + * A map of secrets, which will be omitted from serialization. + * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". + * Values are the secret ids, which will be used when deserializing. + */ + get lc_secrets() {} + /** + * A map of additional attributes to merge with constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the attribute values, which will be serialized. + * These attributes need to be accepted by the constructor as arguments. + */ + get lc_attributes() {} + /** + * A map of aliases for constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the alias that will replace the key in serialization. + * This is used to eg. make argument names match Python. + */ + get lc_aliases() {} + /** + * A manual list of keys that should be serialized. + * If not overridden, all fields passed into the constructor will be serialized. + */ + get lc_serializable_keys() {} + constructor(kwargs, ..._args) { + if (this.lc_serializable_keys !== void 0) this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key))); + else 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 read = this; + let write = kwargs; + const [last, ...partsReverse] = keyPath.split(".").reverse(); + for (const key of partsReverse.reverse()) { + if (!(key in read) || read[key] === void 0) return; + if (!(key in write) || write[key] === void 0) { + if (typeof read[key] === "object" && read[key] != null) write[key] = {}; + else if (Array.isArray(read[key])) write[key] = []; + } + read = read[key]; + write = write[key]; + } + if (last in read && read[last] !== void 0) write[last] = write[last] || read[last]; + }); + const escapedKwargs = {}; + const pathSet = /* @__PURE__ */ new WeakSet(); + pathSet.add(this); + for (const [key, value] of Object.entries(kwargs)) escapedKwargs[key] = escapeIfNeeded(value, pathSet); + const processedKwargs = mapKeys(Object.keys(secrets).length ? replaceSecrets(escapedKwargs, secrets) : escapedKwargs, keyToJson, aliases); + return { + lc: 1, + type: "constructor", + id: this.lc_id, + kwargs: processedKwargs + }; + } + toJSONNotImplemented() { + return { + lc: 1, + type: "not_implemented", + id: this.lc_id + }; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/utils.js +function _isContentBlock(block, type) { + return _isObject(block) && block.type === type; +} +function _isObject(value) { + return typeof value === "object" && value !== null; +} +function _isArray(value) { + return Array.isArray(value); +} +function _isString(value) { + return typeof value === "string"; +} +function _isNumber(value) { + return typeof value === "number"; +} +function _isBytesArray(value) { + return value instanceof Uint8Array; +} +function safeParseJson(value) { + try { + return JSON.parse(value); + } catch { + return; + } +} +var iife$3 = (fn) => fn(); +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/anthropic.js +function convertAnthropicAnnotation(citation) { + if (citation.type === "char_location" && _isString(citation.document_title) && _isNumber(citation.start_char_index) && _isNumber(citation.end_char_index) && _isString(citation.cited_text)) { + const { document_title, start_char_index, end_char_index, cited_text, ...rest } = citation; + return { + ...rest, + type: "citation", + source: "char", + title: document_title ?? void 0, + startIndex: start_char_index, + endIndex: end_char_index, + citedText: cited_text + }; + } + if (citation.type === "page_location" && _isString(citation.document_title) && _isNumber(citation.start_page_number) && _isNumber(citation.end_page_number) && _isString(citation.cited_text)) { + const { document_title, start_page_number, end_page_number, cited_text, ...rest } = citation; + return { + ...rest, + type: "citation", + source: "page", + title: document_title ?? void 0, + startIndex: start_page_number, + endIndex: end_page_number, + citedText: cited_text + }; + } + if (citation.type === "content_block_location" && _isString(citation.document_title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) { + const { document_title, start_block_index, end_block_index, cited_text, ...rest } = citation; + return { + ...rest, + type: "citation", + source: "block", + title: document_title ?? void 0, + startIndex: start_block_index, + endIndex: end_block_index, + citedText: cited_text + }; + } + if (citation.type === "web_search_result_location" && _isString(citation.url) && _isString(citation.title) && _isString(citation.encrypted_index) && _isString(citation.cited_text)) { + const { url, title, encrypted_index, cited_text, ...rest } = citation; + return { + ...rest, + type: "citation", + source: "url", + url, + title, + startIndex: Number(encrypted_index), + endIndex: Number(encrypted_index), + citedText: cited_text + }; + } + if (citation.type === "search_result_location" && _isString(citation.source) && _isString(citation.title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) { + const { source, title, start_block_index, end_block_index, cited_text, ...rest } = citation; + return { + ...rest, + type: "citation", + source: "search", + url: source, + title: title ?? void 0, + startIndex: start_block_index, + endIndex: end_block_index, + citedText: cited_text + }; + } +} +/** +* Converts an Anthropic content block to a standard V1 content block. +* +* This function handles the conversion of Anthropic-specific content blocks +* (document and image blocks) to the standardized V1 format. It supports +* various source types including base64 data, URLs, file IDs, and text data. +* +* @param block - The Anthropic content block to convert +* @returns A standard V1 content block if conversion is successful, undefined otherwise +* +* @example +* ```typescript +* const anthropicBlock = { +* type: "image", +* source: { +* type: "base64", +* media_type: "image/png", +* data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" +* } +* }; +* +* const standardBlock = convertToV1FromAnthropicContentBlock(anthropicBlock); +* // Returns: { type: "image", mimeType: "image/png", data: "..." } +* ``` +*/ +function convertToV1FromAnthropicContentBlock(block) { + if (_isContentBlock(block, "document") && _isObject(block.source) && "type" in block.source) { + if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return { + type: "file", + mimeType: block.source.media_type, + data: block.source.data + }; + else if (block.source.type === "url" && _isString(block.source.url)) return { + type: "file", + url: block.source.url + }; + else if (block.source.type === "file" && _isString(block.source.file_id)) return { + type: "file", + fileId: block.source.file_id + }; + else if (block.source.type === "text" && _isString(block.source.data)) return { + type: "file", + mimeType: String(block.source.media_type ?? "text/plain"), + data: block.source.data + }; + } else if (_isContentBlock(block, "image") && _isObject(block.source) && "type" in block.source) { + if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return { + type: "image", + mimeType: block.source.media_type, + data: block.source.data + }; + else if (block.source.type === "url" && _isString(block.source.url)) return { + type: "image", + url: block.source.url + }; + else if (block.source.type === "file" && _isString(block.source.file_id)) return { + type: "image", + fileId: block.source.file_id + }; + } +} +/** +* Converts an array of content blocks from Anthropic format to v1 standard format. +* +* This function processes each content block in the input array, attempting to convert +* Anthropic-specific block formats (like image blocks with source objects, document blocks, etc.) +* to the standardized v1 content block format. If a block cannot be converted, it is +* passed through as-is with a type assertion to ContentBlock.Standard. +* +* @param content - Array of content blocks in Anthropic format to be converted +* @returns Array of content blocks in v1 standard format +*/ +function convertToV1FromAnthropicInput(content) { + function* iterateContent() { + for (const block of content) { + const stdBlock = convertToV1FromAnthropicContentBlock(block); + if (stdBlock) yield stdBlock; + else yield block; + } + } + return Array.from(iterateContent()); +} +/** +* Converts an Anthropic AI message to an array of v1 standard content blocks. +* +* This function processes an AI message containing Anthropic-specific content blocks +* and converts them to the standardized v1 content block format. +* +* @param message - The AI message containing Anthropic-formatted content blocks +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const message = new AIMessage([ +* { type: "text", text: "Hello world" }, +* { type: "thinking", text: "Let me think about this..." }, +* { type: "tool_use", id: "123", name: "calculator", input: { a: 1, b: 2 } } +* ]); +* +* const standardBlocks = convertToV1FromAnthropicMessage(message); +* // Returns: +* // [ +* // { type: "text", text: "Hello world" }, +* // { type: "reasoning", reasoning: "Let me think about this..." }, +* // { type: "tool_call", id: "123", name: "calculator", args: { a: 1, b: 2 } } +* // ] +* ``` +*/ +function convertToV1FromAnthropicMessage(message) { + function* iterateContent() { + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) { + if (_isContentBlock(block, "text") && _isString(block.text)) { + const { text, citations, ...rest } = block; + if (_isArray(citations) && citations.length) { + const _citations = citations.reduce((acc, item) => { + const citation = convertAnthropicAnnotation(item); + if (citation) return [...acc, citation]; + return acc; + }, []); + yield { + ...rest, + type: "text", + text, + annotations: _citations + }; + continue; + } else { + yield { + ...rest, + type: "text", + text + }; + continue; + } + } else if (_isContentBlock(block, "thinking") && _isString(block.thinking)) { + const { thinking, signature, ...rest } = block; + yield { + ...rest, + type: "reasoning", + reasoning: thinking, + signature + }; + continue; + } else if (_isContentBlock(block, "redacted_thinking")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "tool_use") && _isString(block.name) && _isString(block.id)) { + yield { + type: "tool_call", + id: block.id, + name: block.name, + args: block.input + }; + continue; + } else if (_isContentBlock(block, "input_json_delta")) { + if (_isAIMessageChunk(message) && message.tool_call_chunks?.length) { + const tool_call_chunk = message.tool_call_chunks[0]; + yield { + type: "tool_call_chunk", + id: tool_call_chunk.id, + name: tool_call_chunk.name, + args: tool_call_chunk.args, + index: tool_call_chunk.index + }; + continue; + } + } else if (_isContentBlock(block, "server_tool_use") && _isString(block.name) && _isString(block.id)) { + const { name, id } = block; + if (name === "web_search") { + yield { + id, + type: "server_tool_call", + name: "web_search", + args: { query: iife$3(() => { + if (typeof block.input === "string") return block.input; + else if (_isObject(block.input) && _isString(block.input.query)) return block.input.query; + else if (_isString(block.partial_json)) { + const json = safeParseJson(block.partial_json); + if (json?.query) return json.query; + } + return ""; + }) } + }; + continue; + } else if (block.name === "code_execution") { + yield { + id, + type: "server_tool_call", + name: "code_execution", + args: { code: iife$3(() => { + if (typeof block.input === "string") return block.input; + else if (_isObject(block.input) && _isString(block.input.code)) return block.input.code; + else if (_isString(block.partial_json)) { + const json = safeParseJson(block.partial_json); + if (json?.code) return json.code; + } + return ""; + }) } + }; + continue; + } + } else if (_isContentBlock(block, "web_search_tool_result") && _isString(block.tool_use_id) && _isArray(block.content)) { + const { content, tool_use_id } = block; + yield { + type: "server_tool_call_result", + name: "web_search", + toolCallId: tool_use_id, + status: "success", + output: { urls: content.reduce((acc, content) => { + if (_isContentBlock(content, "web_search_result")) return [...acc, content.url]; + return acc; + }, []) } + }; + continue; + } else if (_isContentBlock(block, "code_execution_tool_result") && _isString(block.tool_use_id) && _isObject(block.content)) { + yield { + type: "server_tool_call_result", + name: "code_execution", + toolCallId: block.tool_use_id, + status: "success", + output: block.content + }; + continue; + } else if (_isContentBlock(block, "mcp_tool_use")) { + yield { + id: block.id, + type: "server_tool_call", + name: "mcp_tool_use", + args: block.input + }; + continue; + } else if (_isContentBlock(block, "mcp_tool_result") && _isString(block.tool_use_id) && _isObject(block.content)) { + yield { + type: "server_tool_call_result", + name: "mcp_tool_use", + toolCallId: block.tool_use_id, + status: "success", + output: block.content + }; + continue; + } else if (_isContentBlock(block, "container_upload")) { + yield { + type: "server_tool_call", + name: "container_upload", + args: block.input + }; + continue; + } else if (_isContentBlock(block, "search_result")) { + yield { + id: block.id, + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "tool_result")) { + yield { + id: block.id, + type: "non_standard", + value: block + }; + continue; + } else { + const stdBlock = convertToV1FromAnthropicContentBlock(block); + if (stdBlock) { + yield stdBlock; + continue; + } + } + yield { + type: "non_standard", + value: block + }; + } + } + return Array.from(iterateContent()); +} +var ChatAnthropicTranslator = { + translateContent: convertToV1FromAnthropicMessage, + translateContentChunk: convertToV1FromAnthropicMessage +}; +function _isAIMessageChunk(message) { + return typeof message?._getType === "function" && typeof message.concat === "function" && message._getType() === "ai"; +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/data.js +function convertToV1FromDataContentBlock(block) { + if (isURLContentBlock(block)) return { + type: block.type, + mimeType: block.mime_type, + url: block.url, + metadata: block.metadata + }; + if (isBase64ContentBlock(block)) return { + type: block.type, + mimeType: block.mime_type ?? "application/octet-stream", + data: block.data, + metadata: block.metadata + }; + if (isIDContentBlock(block)) return { + type: block.type, + mimeType: block.mime_type, + fileId: block.id, + metadata: block.metadata + }; + return block; +} +function convertToV1FromDataContent(content) { + return content.map(convertToV1FromDataContentBlock); +} +function isOpenAIDataBlock(block) { + if (_isContentBlock(block, "image_url") && _isObject(block.image_url)) return true; + if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio)) return true; + if (_isContentBlock(block, "file") && _isObject(block.file)) return true; + return false; +} +function convertToV1FromOpenAIDataBlock(block) { + if (_isContentBlock(block, "image_url") && _isObject(block.image_url) && _isString(block.image_url.url)) { + const parsed = parseBase64DataUrl({ dataUrl: block.image_url.url }); + if (parsed) return { + type: "image", + mimeType: parsed.mime_type, + data: parsed.data + }; + else return { + type: "image", + url: block.image_url.url + }; + } else if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio) && _isString(block.input_audio.data) && _isString(block.input_audio.format)) return { + type: "audio", + data: block.input_audio.data, + mimeType: `audio/${block.input_audio.format}` + }; + else if (_isContentBlock(block, "file") && _isObject(block.file) && _isString(block.file.data)) { + const parsed = parseBase64DataUrl({ dataUrl: block.file.data }); + if (parsed) return { + type: "file", + data: parsed.data, + mimeType: parsed.mime_type + }; + else if (_isString(block.file.file_id)) return { + type: "file", + fileId: block.file.file_id + }; + } + return block; +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/openai.js +/** +* Converts a ChatOpenAICompletions message to an array of v1 standard content blocks. +* +* This function processes an AI message from ChatOpenAICompletions API format +* and converts it to the standardized v1 content block format. It handles both +* string content and structured content blocks, as well as tool calls. +* +* @param message - The AI message containing ChatOpenAICompletions formatted content +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const message = new AIMessage("Hello world"); +* const standardBlocks = convertToV1FromChatCompletions(message); +* // Returns: [{ type: "text", text: "Hello world" }] +* ``` +* +* @example +* ```typescript +* const message = new AIMessage([ +* { type: "text", text: "Hello" }, +* { type: "image_url", image_url: { url: "https://example.com/image.png" } } +* ]); +* message.tool_calls = [ +* { id: "call_123", name: "calculator", args: { a: 1, b: 2 } } +* ]; +* +* const standardBlocks = convertToV1FromChatCompletions(message); +* // Returns: +* // [ +* // { type: "text", text: "Hello" }, +* // { type: "image", url: "https://example.com/image.png" }, +* // { type: "tool_call", id: "call_123", name: "calculator", args: { a: 1, b: 2 } } +* // ] +* ``` +*/ +function convertToV1FromChatCompletions(message) { + const blocks = []; + if (typeof message.content === "string") { + if (message.content.length > 0) blocks.push({ + type: "text", + text: message.content + }); + } else blocks.push(...convertToV1FromChatCompletionsInput(message.content)); + for (const toolCall of message.tool_calls ?? []) blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +/** +* Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks. +* +* This function processes an AI message chunk from OpenAI's chat completions API and converts +* it to the standardized v1 content block format. It handles both string and array content, +* as well as tool calls that may be present in the chunk. +* +* @param message - The AI message chunk containing OpenAI-formatted content blocks +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const chunk = new AIMessage("Hello"); +* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk); +* // Returns: [{ type: "text", text: "Hello" }] +* ``` +* +* @example +* ```typescript +* const chunk = new AIMessage([ +* { type: "text", text: "Processing..." } +* ]); +* chunk.tool_calls = [ +* { id: "call_456", name: "search", args: { query: "test" } } +* ]; +* +* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk); +* // Returns: +* // [ +* // { type: "text", text: "Processing..." }, +* // { type: "tool_call", id: "call_456", name: "search", args: { query: "test" } } +* // ] +* ``` +*/ +function convertToV1FromChatCompletionsChunk(message) { + const blocks = []; + if (typeof message.content === "string") { + if (message.content.length > 0) blocks.push({ + type: "text", + text: message.content + }); + } else blocks.push(...convertToV1FromChatCompletionsInput(message.content)); + for (const toolCall of message.tool_calls ?? []) blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +/** +* Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks. +* +* This function processes content blocks from OpenAI's Chat Completions API format +* and converts them to the standardized v1 content block format. It handles both +* OpenAI-specific data blocks (which require conversion) and standard blocks +* (which are passed through with type assertion). +* +* @param blocks - Array of content blocks in ChatOpenAICompletions format +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const openaiBlocks = [ +* { type: "text", text: "Hello world" }, +* { type: "image_url", image_url: { url: "https://example.com/image.png" } } +* ]; +* +* const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks); +* // Returns: +* // [ +* // { type: "text", text: "Hello world" }, +* // { type: "image", url: "https://example.com/image.png" } +* // ] +* ``` +*/ +function convertToV1FromChatCompletionsInput(blocks) { + const convertedBlocks = []; + for (const block of blocks) if (isOpenAIDataBlock(block)) convertedBlocks.push(convertToV1FromOpenAIDataBlock(block)); + else convertedBlocks.push(block); + return convertedBlocks; +} +function convertResponsesAnnotation(annotation) { + if (annotation.type === "url_citation") { + const { url, title, start_index, end_index } = annotation; + return { + type: "citation", + url, + title, + startIndex: start_index, + endIndex: end_index + }; + } + if (annotation.type === "file_citation") { + const { file_id, filename, index } = annotation; + return { + type: "citation", + title: filename, + startIndex: index, + endIndex: index, + fileId: file_id + }; + } + return annotation; +} +/** +* Converts a ChatOpenAIResponses message to an array of v1 standard content blocks. +* +* This function processes an AI message containing OpenAI Responses-specific content blocks +* and converts them to the standardized v1 content block format. It handles reasoning summaries, +* text content with annotations, tool calls, and various tool outputs including code interpreter, +* web search, file search, computer calls, and MCP-related blocks. +* +* @param message - The AI message containing OpenAI Responses-formatted content blocks +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const message = new AIMessage({ +* content: [{ type: "text", text: "Hello world", annotations: [] }], +* tool_calls: [{ id: "123", name: "calculator", args: { a: 1, b: 2 } }], +* additional_kwargs: { +* reasoning: { summary: [{ text: "Let me calculate this..." }] }, +* tool_outputs: [ +* { +* type: "code_interpreter_call", +* code: "print('hello')", +* outputs: [{ type: "logs", logs: "hello" }] +* } +* ] +* } +* }); +* +* const standardBlocks = convertToV1FromResponses(message); +* // Returns: +* // [ +* // { type: "reasoning", reasoning: "Let me calculate this..." }, +* // { type: "text", text: "Hello world", annotations: [] }, +* // { type: "tool_call", id: "123", name: "calculator", args: { a: 1, b: 2 } }, +* // { type: "code_interpreter_call", code: "print('hello')" }, +* // { type: "code_interpreter_result", output: [{ type: "code_interpreter_output", returnCode: 0, stdout: "hello" }] } +* // ] +* ``` +*/ +function convertToV1FromResponses(message) { + function* iterateContent() { + if (_isObject(message.additional_kwargs?.reasoning) && _isArray(message.additional_kwargs.reasoning.summary)) yield { + type: "reasoning", + reasoning: message.additional_kwargs.reasoning.summary.reduce((acc, item) => { + if (_isObject(item) && _isString(item.text)) return `${acc}${item.text}`; + return acc; + }, "") + }; + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) if (_isContentBlock(block, "text")) { + const { text, annotations, phase, extras: existingExtras, ...rest } = block; + const extras = _isObject(existingExtras) ? { ...existingExtras } : {}; + if (_isString(phase)) extras.phase = phase; + const extrasSpread = Object.keys(extras).length > 0 ? { extras } : {}; + if (Array.isArray(annotations)) yield { + ...rest, + ...extrasSpread, + type: "text", + text: String(text), + annotations: annotations.map(convertResponsesAnnotation) + }; + else yield { + ...rest, + ...extrasSpread, + type: "text", + text: String(text) + }; + } + for (const toolCall of message.tool_calls ?? []) yield { + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }; + if (_isObject(message.additional_kwargs) && _isArray(message.additional_kwargs.tool_outputs)) for (const toolOutput of message.additional_kwargs.tool_outputs) { + if (_isContentBlock(toolOutput, "web_search_call")) { + /** + * Build args from available action data. + * The ResponseFunctionWebSearch base type only has id, status, type. + * The action field (with query, sources, etc.) may be present at + * runtime when the `include` parameter includes "web_search_call.action.sources". + */ + const webSearchArgs = {}; + if (_isObject(toolOutput.action) && _isString(toolOutput.action.query)) webSearchArgs.query = toolOutput.action.query; + yield { + id: toolOutput.id, + type: "server_tool_call", + name: "web_search", + args: webSearchArgs + }; + if (toolOutput.status === "completed" || toolOutput.status === "failed") { + const output = {}; + if (_isObject(toolOutput.action)) output.action = toolOutput.action; + yield { + type: "server_tool_call_result", + toolCallId: _isString(toolOutput.id) ? toolOutput.id : "", + status: toolOutput.status === "completed" ? "success" : "error", + output + }; + } + continue; + } else if (_isContentBlock(toolOutput, "file_search_call")) { + yield { + id: toolOutput.id, + type: "server_tool_call", + name: "file_search", + args: { queries: _isArray(toolOutput.queries) ? toolOutput.queries : [] } + }; + if (toolOutput.status === "completed" || toolOutput.status === "failed") yield { + type: "server_tool_call_result", + toolCallId: _isString(toolOutput.id) ? toolOutput.id : "", + status: toolOutput.status === "completed" ? "success" : "error", + output: _isArray(toolOutput.results) ? { results: toolOutput.results } : {} + }; + continue; + } else if (_isContentBlock(toolOutput, "computer_call")) { + yield { + type: "non_standard", + value: toolOutput + }; + continue; + } else if (_isContentBlock(toolOutput, "code_interpreter_call")) { + if (_isString(toolOutput.code)) yield { + id: toolOutput.id, + type: "server_tool_call", + name: "code_interpreter", + args: { code: toolOutput.code } + }; + if (_isArray(toolOutput.outputs)) { + const returnCode = iife$3(() => { + if (toolOutput.status === "in_progress") return void 0; + if (toolOutput.status === "completed") return 0; + if (toolOutput.status === "incomplete") return 127; + if (toolOutput.status === "interpreting") return void 0; + if (toolOutput.status === "failed") return 1; + }); + for (const output of toolOutput.outputs) if (_isContentBlock(output, "logs")) { + yield { + type: "server_tool_call_result", + toolCallId: toolOutput.id ?? "", + status: "success", + output: { + type: "code_interpreter_output", + returnCode: returnCode ?? 0, + stderr: [0, void 0].includes(returnCode) ? void 0 : String(output.logs), + stdout: [0, void 0].includes(returnCode) ? String(output.logs) : void 0 + } + }; + continue; + } + } + continue; + } else if (_isContentBlock(toolOutput, "mcp_call")) { + yield { + id: toolOutput.id, + type: "server_tool_call", + name: "mcp_call", + args: toolOutput.input + }; + continue; + } else if (_isContentBlock(toolOutput, "mcp_list_tools")) { + yield { + id: toolOutput.id, + type: "server_tool_call", + name: "mcp_list_tools", + args: toolOutput.input + }; + continue; + } else if (_isContentBlock(toolOutput, "mcp_approval_request")) { + yield { + type: "non_standard", + value: toolOutput + }; + continue; + } else if (_isContentBlock(toolOutput, "tool_search_call")) { + const toolSearchArgs = {}; + if (_isObject(toolOutput.arguments)) Object.assign(toolSearchArgs, toolOutput.arguments); + const toolSearchCallExtras = {}; + if (_isString(toolOutput.execution)) toolSearchCallExtras.execution = toolOutput.execution; + if (_isString(toolOutput.status)) toolSearchCallExtras.status = toolOutput.status; + if (_isString(toolOutput.call_id)) toolSearchCallExtras.call_id = toolOutput.call_id; + yield { + id: _isString(toolOutput.id) ? toolOutput.id : "", + type: "server_tool_call", + name: "tool_search", + args: toolSearchArgs, + ...Object.keys(toolSearchCallExtras).length > 0 ? { extras: toolSearchCallExtras } : {} + }; + continue; + } else if (_isContentBlock(toolOutput, "tool_search_output")) { + const toolSearchOutputExtras = { name: "tool_search" }; + if (_isString(toolOutput.execution)) toolSearchOutputExtras.execution = toolOutput.execution; + yield { + type: "server_tool_call_result", + toolCallId: _isString(toolOutput.id) ? toolOutput.id : "", + status: toolOutput.status === "completed" ? "success" : toolOutput.status === "failed" ? "error" : "success", + output: { tools: _isArray(toolOutput.tools) ? toolOutput.tools : [] }, + extras: toolSearchOutputExtras + }; + continue; + } else if (_isContentBlock(toolOutput, "image_generation_call")) { + if (_isString(toolOutput.result)) yield { + type: "image", + mimeType: "image/png", + data: toolOutput.result, + id: _isString(toolOutput.id) ? toolOutput.id : void 0, + metadata: { status: _isString(toolOutput.status) ? toolOutput.status : void 0 } + }; + yield { + type: "non_standard", + value: toolOutput + }; + continue; + } + if (_isObject(toolOutput)) yield { + type: "non_standard", + value: toolOutput + }; + } + } + return Array.from(iterateContent()); +} +/** +* Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks. +* +* This function processes an AI message chunk containing OpenAI-specific content blocks +* and converts them to the standardized v1 content block format. It handles both the +* regular message content and tool call chunks that are specific to streaming responses. +* +* @param message - The AI message chunk containing OpenAI-formatted content blocks +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const messageChunk = new AIMessageChunk({ +* content: [{ type: "text", text: "Hello" }], +* tool_call_chunks: [ +* { id: "call_123", name: "calculator", args: '{"a": 1' } +* ] +* }); +* +* const standardBlocks = convertToV1FromResponsesChunk(messageChunk); +* // Returns: +* // [ +* // { type: "text", text: "Hello" }, +* // { type: "tool_call_chunk", id: "call_123", name: "calculator", args: '{"a": 1' } +* // ] +* ``` +*/ +function convertToV1FromResponsesChunk(message) { + function* iterateContent() { + yield* convertToV1FromResponses(message); + for (const toolCallChunk of message.tool_call_chunks ?? []) yield { + type: "tool_call_chunk", + id: toolCallChunk.id, + name: toolCallChunk.name, + args: toolCallChunk.args + }; + } + return Array.from(iterateContent()); +} +var ChatOpenAITranslator = { + translateContent: (message) => { + if (typeof message.content === "string") return convertToV1FromChatCompletions(message); + return convertToV1FromResponses(message); + }, + translateContentChunk: (message) => { + if (typeof message.content === "string") return convertToV1FromChatCompletionsChunk(message); + return convertToV1FromResponsesChunk(message); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/message.js +/** +* Type guard to check if a value is a valid Message object. +* +* @param message - The value to check +* @returns true if the value is a valid Message object, false otherwise +*/ +function isMessage(message) { + return typeof message === "object" && message !== null && "type" in message && "content" in message && (typeof message.content === "string" || Array.isArray(message.content)); +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/format.js +function convertToFormattedString(message, format = "pretty") { + if (format === "pretty") return convertToPrettyString(message); + return JSON.stringify(message); +} +function convertToPrettyString(message) { + const lines = []; + const title = ` ${message.type.charAt(0).toUpperCase() + message.type.slice(1)} Message `; + const sepLen = Math.floor((80 - title.length) / 2); + const sep = "=".repeat(sepLen); + const secondSep = title.length % 2 === 0 ? sep : `${sep}=`; + lines.push(`${sep}${title}${secondSep}`); + if (message.type === "ai") { + const aiMessage = message; + if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) { + lines.push("Tool Calls:"); + for (const tc of aiMessage.tool_calls) { + lines.push(` ${tc.name} (${tc.id})`); + lines.push(` Call ID: ${tc.id}`); + lines.push(" Args:"); + for (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`); + } + } + } + if (message.type === "tool") { + const toolMessage = message; + if (toolMessage.name) lines.push(`Name: ${toolMessage.name}`); + } + if (typeof message.content === "string" && message.content.trim()) { + if (lines.length > 1) lines.push(""); + lines.push(message.content); + } + return lines.join("\n"); +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/base.js +/** @internal */ +var MESSAGE_SYMBOL = Symbol.for("langchain.message"); +/** +* Normalize non-string `firstContent` to a block array for merge/spread. +* Some serializers (e.g. Anthropic-style) yield a single block object instead of a one-element array; +* spreading that object as an array throws ("is not iterable"). +*/ +function contentBlocksFromNonStringFirst(firstContent) { + if (Array.isArray(firstContent)) return firstContent; + if (typeof firstContent === "string") return firstContent === "" ? [] : [{ + type: "text", + text: firstContent + }]; + if (firstContent == null) return []; + return [firstContent]; +} +function mergeContent(firstContent, secondContent) { + if (typeof firstContent === "string") { + if (firstContent === "") return secondContent; + if (typeof secondContent === "string") return firstContent + secondContent; + else if (Array.isArray(secondContent) && secondContent.length === 0) return firstContent; + else if (Array.isArray(secondContent) && secondContent.some((c) => isDataContentBlock(c))) return [{ + type: "text", + source_type: "text", + text: firstContent + }, ...secondContent]; + else return [{ + type: "text", + text: firstContent + }, ...secondContent]; + } else if (Array.isArray(secondContent)) { + const left = contentBlocksFromNonStringFirst(firstContent); + return _mergeLists(left, secondContent) ?? [...left, ...secondContent]; + } else if (secondContent === "") return firstContent; + else if (Array.isArray(firstContent) && firstContent.some((c) => isDataContentBlock(c))) return [...firstContent, { + type: "file", + source_type: "text", + text: secondContent + }]; + else return [...contentBlocksFromNonStringFirst(firstContent), { + type: "text", + text: secondContent + }]; +} +/** +* 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else +* it will return 'success'. +* +* @param {"success" | "error" | undefined} left The existing value to 'merge' with the new value. +* @param {"success" | "error" | undefined} right The new value to 'merge' with the existing value +* @returns {"success" | "error"} The 'merged' value. +*/ +function _mergeStatus(left, right) { + if (left === "error" || right === "error") return "error"; + return "success"; +} +function stringifyWithDepthLimit(obj, depthLimit) { + function helper(obj, currentDepth) { + if (typeof obj !== "object" || obj === null || obj === void 0) return obj; + if (currentDepth >= depthLimit) { + if (Array.isArray(obj)) return "[Array]"; + return "[Object]"; + } + if (Array.isArray(obj)) return obj.map((item) => helper(item, currentDepth + 1)); + const result = {}; + for (const key of Object.keys(obj)) result[key] = helper(obj[key], currentDepth + 1); + return result; + } + return JSON.stringify(helper(obj, 0), null, 2); +} +/** +* Base class for all types of messages in a conversation. It includes +* properties like `content`, `name`, and `additional_kwargs`. It also +* includes methods like `toDict()` and `_getType()`. +*/ +var BaseMessage = class extends Serializable { + lc_namespace = ["langchain_core", "messages"]; + lc_serializable = true; + get lc_aliases() { + return { + additional_kwargs: "additional_kwargs", + response_metadata: "response_metadata" + }; + } + [MESSAGE_SYMBOL] = true; + id; + /** @inheritdoc */ + name; + content; + additional_kwargs; + response_metadata; + /** + * @deprecated Use .getType() instead or import the proper typeguard. + * For example: + * + * ```ts + * import { isAIMessage } from "@langchain/core/messages"; + * + * const message = new AIMessage("Hello!"); + * isAIMessage(message); // true + * ``` + */ + _getType() { + return this.type; + } + /** + * @deprecated Use .type instead + * The type of the message. + */ + getType() { + return this._getType(); + } + constructor(arg) { + const fields = typeof arg === "string" || Array.isArray(arg) ? { content: arg } : arg; + if (!fields.additional_kwargs) fields.additional_kwargs = {}; + if (!fields.response_metadata) fields.response_metadata = {}; + super(fields); + this.name = fields.name; + if (fields.content === void 0 && fields.contentBlocks !== void 0) { + this.content = fields.contentBlocks; + this.response_metadata = { + output_version: "v1", + ...fields.response_metadata + }; + } else if (fields.content !== void 0) { + this.content = fields.content ?? []; + this.response_metadata = fields.response_metadata; + } else { + this.content = []; + this.response_metadata = fields.response_metadata; + } + this.additional_kwargs = fields.additional_kwargs; + this.id = fields.id; + } + /** Get text content of the message. */ + get text() { + if (typeof this.content === "string") return this.content; + if (!Array.isArray(this.content)) return ""; + return this.content.map((c) => { + if (typeof c === "string") return c; + if (c.type === "text") return c.text; + return ""; + }).join(""); + } + get contentBlocks() { + const blocks = typeof this.content === "string" ? [{ + type: "text", + text: this.content + }] : this.content; + return [ + convertToV1FromDataContent, + convertToV1FromChatCompletionsInput, + convertToV1FromAnthropicInput + ].reduce((blocks, step) => step(blocks), blocks); + } + toDict() { + return { + type: this.getType(), + data: this.toJSON().kwargs + }; + } + static lc_name() { + return "BaseMessage"; + } + get _printableFields() { + return { + id: this.id, + content: this.content, + name: this.name, + additional_kwargs: this.additional_kwargs, + response_metadata: this.response_metadata + }; + } + static isInstance(obj) { + return typeof obj === "object" && obj !== null && MESSAGE_SYMBOL in obj && obj[MESSAGE_SYMBOL] === true && isMessage(obj); + } + _updateId(value) { + this.id = value; + this.lc_kwargs.id = value; + } + get [Symbol.toStringTag]() { + return this.constructor.lc_name(); + } + [Symbol.for("nodejs.util.inspect.custom")](depth) { + if (depth === null) return this; + const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth)); + return `${this.constructor.lc_name()} ${printable}`; + } + toFormattedString(format = "pretty") { + return convertToFormattedString(this, format); + } +}; +function isOpenAIToolCallArray(value) { + return Array.isArray(value) && value.every((v) => typeof v.index === "number"); +} +/** +* Default keys that should be preserved (not merged) when concatenating message chunks. +* These are identification and timestamp fields that shouldn't be summed or concatenated. +*/ +var DEFAULT_MERGE_IGNORE_KEYS = [ + "index", + "created", + "timestamp" +]; +function _mergeDicts(left, right, options) { + /** + * The keys to ignore during merging. + */ + const ignoreKeys = options?.ignoreKeys ?? DEFAULT_MERGE_IGNORE_KEYS; + if (left == null && right == null) return; + if (left == null || right == null) return 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") if (key === "type") continue; + else if ([ + "id", + "name", + "output_version", + "model_provider" + ].includes(key)) { + if (value) merged[key] = value; + } else if (ignoreKeys.includes(key)) continue; + else merged[key] += value; + else if (typeof merged[key] === "number") { + if (ignoreKeys.includes(key)) continue; + merged[key] = merged[key] + value; + } else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) merged[key] = _mergeDicts(merged[key], value, options); + else if (Array.isArray(merged[key])) merged[key] = _mergeLists(merged[key], value, options); + 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 isMergeableIndex(index) { + return typeof index === "number" || typeof index === "string"; +} +function hasMergeableIndex(value) { + if (typeof value !== "object" || value === null) return false; + if (!("index" in value)) return false; + return isMergeableIndex(value.index); +} +function hasMergeableId(value) { + if (typeof value !== "object" || value === null) return false; + if (!("id" in value)) return false; + const id = value.id; + return id != null && id !== ""; +} +function getMergeableTypeBase(type) { + return type.endsWith("_delta") ? type.slice(0, -6) : type; +} +function hasMismatchedMergeableType(left, right) { + if (typeof left !== "object" || left === null) return false; + if (typeof right !== "object" || right === null) return false; + if (!("type" in left) || !("type" in right)) return false; + return typeof left.type === "string" && typeof right.type === "string" && getMergeableTypeBase(left.type) !== getMergeableTypeBase(right.type); +} +/** +* Find the index of an existing item in `merged` that should be merged with +* `item`, based on index and/or id matching. +* +* Matching priority: +* 1. Both have index → match on index (+ id when both present) +* 2. Neither has index, both have id → match on id alone +* 3. Otherwise → no match (item should be appended) +*/ +function _findMergeTarget(merged, item) { + const itemHasIndex = hasMergeableIndex(item); + const itemHasId = hasMergeableId(item); + if (!itemHasIndex && !itemHasId) return -1; + return merged.findIndex((leftItem) => { + const leftHasIndex = hasMergeableIndex(leftItem); + const leftHasId = hasMergeableId(leftItem); + if (itemHasIndex && leftHasIndex) { + if (!(leftItem.index === item.index)) return false; + if (hasMismatchedMergeableType(leftItem, item)) return false; + if (leftHasId && itemHasId) return leftItem.id === item.id; + return true; + } + if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) return leftItem.id === item.id; + return false; + }); +} +function _mergeLists(left, right, options) { + if (left == null && right == null) return; + else if (left == null || right == null) return left || right; + else { + const merged = [...left]; + for (const item of right) { + const toMerge = _findMergeTarget(merged, item); + if (toMerge !== -1) merged[toMerge] = _mergeDicts(merged[toMerge], item, options); + else if (typeof item === "object" && item !== null && "text" in item && item.text === "") continue; + else merged.push(item); + } + return merged; + } +} +function _mergeObj(left, right, options) { + if (left == null && right == null) return; + if (left == null || right == null) return left ?? right; + else if (typeof left !== typeof right) throw new Error(`Cannot merge objects of different types.\nLeft ${typeof left}\nRight ${typeof right}`); + else if (typeof left === "string" && typeof right === "string") return left + right; + else if (Array.isArray(left) && Array.isArray(right)) return _mergeLists(left, right, options); + else if (typeof left === "object" && typeof right === "object") return _mergeDicts(left, right, options); + else if (left === right) return left; + else throw new Error(`Can not merge objects of different types.\nLeft ${left}\nRight ${right}`); +} +/** +* Represents a chunk of a message, which can be concatenated with other +* message chunks. It includes a method `_merge_kwargs_dict()` for merging +* additional keyword arguments from another `BaseMessageChunk` into this +* one. It also overrides the `__add__()` method to support concatenation +* of `BaseMessageChunk` instances. +*/ +var BaseMessageChunk = class BaseMessageChunk extends BaseMessage { + static isInstance(obj) { + if (!super.isInstance(obj)) return false; + let proto = Object.getPrototypeOf(obj); + while (proto !== null) { + if (proto === BaseMessageChunk.prototype) return true; + proto = Object.getPrototypeOf(proto); + } + return false; + } +}; +function _isMessageFieldWithRole(x) { + return typeof x.role === "string"; +} +/** +* @deprecated Use {@link BaseMessage.isInstance} instead +*/ +function isBaseMessage(messageLike) { + return typeof messageLike?._getType === "function"; +} +/** +* @deprecated Use {@link BaseMessageChunk.isInstance} instead +*/ +function isBaseMessageChunk(messageLike) { + return BaseMessageChunk.isInstance(messageLike); +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/bedrock_converse.js +function convertFileFormatToMimeType(format) { + switch (format) { + case "csv": return "text/csv"; + case "doc": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; + case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; + case "html": return "text/html"; + case "md": return "text/markdown"; + case "pdf": return "application/pdf"; + case "txt": return "text/plain"; + case "xls": return "application/vnd.ms-excel"; + case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + case "gif": return "image/gif"; + case "jpeg": return "image/jpeg"; + case "jpg": return "image/jpeg"; + case "png": return "image/png"; + case "webp": return "image/webp"; + case "flv": return "video/flv"; + case "mkv": return "video/mkv"; + case "mov": return "video/mov"; + case "mp4": return "video/mp4"; + case "mpeg": return "video/mpeg"; + case "mpg": return "video/mpg"; + case "three_gp": return "video/three_gp"; + case "webm": return "video/webm"; + case "wmv": return "video/wmv"; + default: return "application/octet-stream"; + } +} +function convertConverseDocumentBlock(block) { + if (_isObject(block.document) && _isObject(block.document.source)) { + const mimeType = convertFileFormatToMimeType(_isObject(block.document) && _isString(block.document.format) ? block.document.format : ""); + if (_isObject(block.document.source)) { + if (_isObject(block.document.source.s3Location) && _isString(block.document.source.s3Location.uri)) return { + type: "file", + mimeType, + fileId: block.document.source.s3Location.uri + }; + if (_isBytesArray(block.document.source.bytes)) return { + type: "file", + mimeType, + data: block.document.source.bytes + }; + if (_isString(block.document.source.text)) return { + type: "file", + mimeType, + data: Buffer.from(block.document.source.text).toString("base64") + }; + if (_isArray(block.document.source.content)) return { + type: "file", + mimeType, + data: block.document.source.content.reduce((acc, item) => { + if (_isObject(item) && _isString(item.text)) return acc + item.text; + return acc; + }, "") + }; + } + } + return { + type: "non_standard", + value: block + }; +} +function convertConverseImageBlock(block) { + if (_isContentBlock(block, "image") && _isObject(block.image)) { + const mimeType = convertFileFormatToMimeType(_isObject(block.image) && _isString(block.image.format) ? block.image.format : ""); + if (_isObject(block.image.source)) { + if (_isObject(block.image.source.s3Location) && _isString(block.image.source.s3Location.uri)) return { + type: "image", + mimeType, + fileId: block.image.source.s3Location.uri + }; + if (_isBytesArray(block.image.source.bytes)) return { + type: "image", + mimeType, + data: block.image.source.bytes + }; + } + } + return { + type: "non_standard", + value: block + }; +} +function convertConverseVideoBlock(block) { + if (_isContentBlock(block, "video") && _isObject(block.video)) { + const mimeType = convertFileFormatToMimeType(_isObject(block.video) && _isString(block.video.format) ? block.video.format : ""); + if (_isObject(block.video.source)) { + if (_isObject(block.video.source.s3Location) && _isString(block.video.source.s3Location.uri)) return { + type: "video", + mimeType, + fileId: block.video.source.s3Location.uri + }; + if (_isBytesArray(block.video.source.bytes)) return { + type: "video", + mimeType, + data: block.video.source.bytes + }; + } + } + return { + type: "non_standard", + value: block + }; +} +function convertToV1FromChatBedrockConverseMessage(message) { + function* iterateContent() { + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) { + if (_isContentBlock(block, "reasoning") && _isString(block.reasoning)) { + yield { + ...block, + type: "reasoning", + reasoning: block.reasoning + }; + continue; + } else if (_isContentBlock(block, "cache_point")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "citations_content") && _isObject(block.citationsContent)) { + yield { + type: "text", + text: _isArray(block.citationsContent.content) ? block.citationsContent.content.reduce((acc, item) => { + if (_isObject(item) && _isString(item.text)) return acc + item.text; + return acc; + }, "") : "", + annotations: _isArray(block.citationsContent.citations) ? block.citationsContent.citations.reduce((acc, item) => { + if (_isObject(item)) { + const citedText = _isArray(item.sourceContent) ? item.sourceContent.reduce((acc, item) => { + if (_isObject(item) && _isString(item.text)) return acc + item.text; + return acc; + }, "") : ""; + const properties = iife$3(() => { + if (_isObject(item.location)) { + const location = item.location.documentChar || item.location.documentPage || item.location.documentChunk; + if (_isObject(location)) return { + source: _isNumber(location.documentIndex) ? location.documentIndex.toString() : void 0, + startIndex: _isNumber(location.start) ? location.start : void 0, + endIndex: _isNumber(location.end) ? location.end : void 0 + }; + } + return {}; + }); + acc.push({ + type: "citation", + citedText, + ...properties + }); + } + return acc; + }, []) : [] + }; + continue; + } else if (_isContentBlock(block, "document") && _isObject(block.document)) { + yield convertConverseDocumentBlock(block); + continue; + } else if (_isContentBlock(block, "guard_content")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "image") && _isObject(block.image)) { + yield convertConverseImageBlock(block); + continue; + } else if (_isContentBlock(block, "reasoning_content") && _isObject(block.reasoningText) && _isString(block.reasoningText.text)) { + yield { + type: "reasoning", + reasoning: block.reasoningText.text, + ..._isString(block.reasoningText.signature) ? { signature: block.reasoningText.signature } : {} + }; + continue; + } else if (_isContentBlock(block, "reasoning_content") && _isString(block.reasoningText)) { + yield { + type: "reasoning", + reasoning: block.reasoningText + }; + continue; + } else if (_isContentBlock(block, "text") && _isString(block.text)) { + yield { + type: "text", + text: block.text + }; + continue; + } else if (_isContentBlock(block, "tool_result")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "tool_call")) continue; + else if (_isContentBlock(block, "video") && _isObject(block.video)) { + yield convertConverseVideoBlock(block); + continue; + } + yield { + type: "non_standard", + value: block + }; + } + } + return Array.from(iterateContent()); +} +var ChatBedrockConverseTranslator = { + translateContent: convertToV1FromChatBedrockConverseMessage, + translateContentChunk: convertToV1FromChatBedrockConverseMessage +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/deepseek.js +/** +* Converts a DeepSeek AI message to an array of v1 standard content blocks. +* +* This function processes an AI message from DeepSeek's API format +* and converts it to the standardized v1 content block format. It handles +* both string content and the reasoning_content in additional_kwargs. +* +* @param message - The AI message containing DeepSeek-formatted content +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const message = new AIMessage({ +* content: "The answer is 42", +* additional_kwargs: { reasoning_content: "Let me think about this..." } +* }); +* const standardBlocks = convertToV1FromDeepSeekMessage(message); +* // Returns: +* // [ +* // { type: "reasoning", reasoning: "Let me think about this..." }, +* // { type: "text", text: "The answer is 42" } +* // ] +* ``` +*/ +function convertToV1FromDeepSeekMessage(message) { + const blocks = []; + const reasoningContent = message.additional_kwargs?.reasoning_content; + if (_isString(reasoningContent) && reasoningContent.length > 0) blocks.push({ + type: "reasoning", + reasoning: reasoningContent + }); + if (typeof message.content === "string") { + if (message.content.length > 0) blocks.push({ + type: "text", + text: message.content + }); + } else for (const block of message.content) if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && _isString(block.text)) blocks.push({ + type: "text", + text: block.text + }); + for (const toolCall of message.tool_calls ?? []) blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +var ChatDeepSeekTranslator = { + translateContent: convertToV1FromDeepSeekMessage, + translateContentChunk: convertToV1FromDeepSeekMessage +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/google_genai.js +function convertToV1FromChatGoogleMessage$1(message) { + function* iterateContent() { + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) { + if (_isContentBlock(block, "text") && _isString(block.text)) { + yield { + type: "text", + text: block.text + }; + continue; + } else if (_isContentBlock(block, "thinking") && _isString(block.thinking)) { + yield { + type: "reasoning", + reasoning: block.thinking, + ...block.signature ? { signature: block.signature } : {} + }; + continue; + } else if (_isContentBlock(block, "inlineData") && _isObject(block.inlineData) && _isString(block.inlineData.mimeType) && _isString(block.inlineData.data)) { + yield { + type: "file", + mimeType: block.inlineData.mimeType, + data: block.inlineData.data + }; + continue; + } else if (_isContentBlock(block, "functionCall") && _isObject(block.functionCall) && _isString(block.functionCall.name) && _isObject(block.functionCall.args)) { + yield { + type: "tool_call", + id: message.id, + name: block.functionCall.name, + args: block.functionCall.args + }; + continue; + } else if (_isContentBlock(block, "functionResponse")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "fileData") && _isObject(block.fileData) && _isString(block.fileData.mimeType) && _isString(block.fileData.fileUri)) { + yield { + type: "file", + mimeType: block.fileData.mimeType, + fileId: block.fileData.fileUri + }; + continue; + } else if (_isContentBlock(block, "executableCode")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "codeExecutionResult")) { + yield { + type: "non_standard", + value: block + }; + continue; + } + yield { + type: "non_standard", + value: block + }; + } + } + return Array.from(iterateContent()); +} +var ChatGoogleGenAITranslator = { + translateContent: convertToV1FromChatGoogleMessage$1, + translateContentChunk: convertToV1FromChatGoogleMessage$1 +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/google_vertexai.js +function convertToV1FromChatVertexMessage(message) { + function* iterateContent() { + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) { + if (_isContentBlock(block, "reasoning") && _isString(block.reasoning)) { + const signature = iife$3(() => { + const reasoningIndex = content.indexOf(block); + if (_isArray(message.additional_kwargs?.signatures) && reasoningIndex >= 0) return message.additional_kwargs.signatures.at(reasoningIndex); + }); + if (_isString(signature)) yield { + type: "reasoning", + reasoning: block.reasoning, + signature + }; + else yield { + type: "reasoning", + reasoning: block.reasoning + }; + continue; + } else if (_isContentBlock(block, "thinking") && _isString(block.thinking)) { + yield { + type: "reasoning", + reasoning: block.thinking, + ...block.signature ? { signature: block.signature } : {} + }; + continue; + } else if (_isContentBlock(block, "text") && _isString(block.text)) { + yield { + type: "text", + text: block.text + }; + continue; + } else if (_isContentBlock(block, "image_url")) { + if (_isString(block.image_url)) if (block.image_url.startsWith("data:")) { + const match = block.image_url.match(/^data:([^;]+);base64,(.+)$/); + if (match) yield { + type: "image", + data: match[2], + mimeType: match[1] + }; + else yield { + type: "image", + url: block.image_url + }; + } else yield { + type: "image", + url: block.image_url + }; + continue; + } else if (_isContentBlock(block, "media") && _isString(block.mimeType) && _isString(block.data)) { + yield { + type: "file", + mimeType: block.mimeType, + data: block.data + }; + continue; + } + yield { + type: "non_standard", + value: block + }; + } + } + return Array.from(iterateContent()); +} +var ChatVertexTranslator = { + translateContent: convertToV1FromChatVertexMessage, + translateContentChunk: convertToV1FromChatVertexMessage +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/groq.js +/** +* Converts a Groq AI message to an array of v1 standard content blocks. +* +* This function processes an AI message from Groq's API format +* and converts it to the standardized v1 content block format. It handles +* both parsed reasoning (in additional_kwargs.reasoning) and raw reasoning +* (in tags within content). +* +* @param message - The AI message containing Groq-formatted content +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* // Parsed format (reasoning_format="parsed") +* const message = new AIMessage({ +* content: "The answer is 42", +* additional_kwargs: { reasoning: "Let me think about this..." } +* }); +* const standardBlocks = convertToV1FromGroqMessage(message); +* // Returns: +* // [ +* // { type: "reasoning", reasoning: "Let me think about this..." }, +* // { type: "text", text: "The answer is 42" } +* // ] +* ``` +* +* @example +* ```typescript +* // Raw format (reasoning_format="raw") +* const message = new AIMessage({ +* content: "Let me think...The answer is 42" +* }); +* const standardBlocks = convertToV1FromGroqMessage(message); +* // Returns: +* // [ +* // { type: "reasoning", reasoning: "Let me think..." }, +* // { type: "text", text: "The answer is 42" } +* // ] +* ``` +*/ +function convertToV1FromGroqMessage(message) { + const blocks = []; + const parsedReasoning = message.additional_kwargs?.reasoning; + if (_isString(parsedReasoning) && parsedReasoning.length > 0) blocks.push({ + type: "reasoning", + reasoning: parsedReasoning + }); + if (typeof message.content === "string") { + let textContent = message.content; + const thinkMatch = textContent.match(/([\s\S]*?)<\/think>/); + if (thinkMatch) { + const thinkingContent = thinkMatch[1].trim(); + if (thinkingContent.length > 0) blocks.push({ + type: "reasoning", + reasoning: thinkingContent + }); + textContent = textContent.replace(/[\s\S]*?<\/think>/, "").trim(); + } + if (textContent.length > 0) blocks.push({ + type: "text", + text: textContent + }); + } else for (const block of message.content) if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && _isString(block.text)) { + let textContent = block.text; + const thinkMatch = textContent.match(/([\s\S]*?)<\/think>/); + if (thinkMatch) { + const thinkingContent = thinkMatch[1].trim(); + if (thinkingContent.length > 0) blocks.push({ + type: "reasoning", + reasoning: thinkingContent + }); + textContent = textContent.replace(/[\s\S]*?<\/think>/, "").trim(); + } + if (textContent.length > 0) blocks.push({ + type: "text", + text: textContent + }); + } + for (const toolCall of message.tool_calls ?? []) blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +var ChatGroqTranslator = { + translateContent: convertToV1FromGroqMessage, + translateContentChunk: convertToV1FromGroqMessage +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/ollama.js +/** +* Converts an Ollama AI message to an array of v1 standard content blocks. +* +* This function processes an AI message from Ollama's API format +* and converts it to the standardized v1 content block format. It handles +* the reasoning_content in additional_kwargs (populated when think mode is enabled). +* +* @param message - The AI message containing Ollama-formatted content +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const message = new AIMessage({ +* content: "The answer is 42", +* additional_kwargs: { reasoning_content: "Let me think about this..." } +* }); +* const standardBlocks = convertToV1FromOllamaMessage(message); +* // Returns: +* // [ +* // { type: "reasoning", reasoning: "Let me think about this..." }, +* // { type: "text", text: "The answer is 42" } +* // ] +* ``` +*/ +function convertToV1FromOllamaMessage(message) { + const blocks = []; + const reasoningContent = message.additional_kwargs?.reasoning_content; + if (_isString(reasoningContent) && reasoningContent.length > 0) blocks.push({ + type: "reasoning", + reasoning: reasoningContent + }); + if (typeof message.content === "string") { + if (message.content.length > 0) blocks.push({ + type: "text", + text: message.content + }); + } else for (const block of message.content) if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && _isString(block.text)) blocks.push({ + type: "text", + text: block.text + }); + for (const toolCall of message.tool_calls ?? []) blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +var ChatOllamaTranslator = { + translateContent: convertToV1FromOllamaMessage, + translateContentChunk: convertToV1FromOllamaMessage +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/openrouter.js +/** +* Converts an OpenRouter AI message to an array of v1 standard content blocks. +* +* OpenRouter returns reasoning output through two places on the Chat +* Completions response: +* +* 1. `message.reasoning` / `delta.reasoning` — a flat string that summarizes +* the model's chain of thought. The `@langchain/openrouter` converter +* normalizes this into `additional_kwargs.reasoning_content` so it matches +* the DeepSeek convention already used elsewhere in LangChain. +* 2. `message.reasoning_details` / `delta.reasoning_details` — a structured +* array of provider-specific reasoning artifacts (see the +* `reasoning.summary` / `reasoning.encrypted` / `reasoning.text` union in +* the OpenRouter API types). The converter preserves these verbatim under +* `additional_kwargs.reasoning_details` for round-tripping back to the +* provider on subsequent turns (e.g. Anthropic extended thinking requires +* the original `signature` to be echoed back). +* +* When `reasoning_details` is present, visible blocks are emitted from +* `reasoning.summary` / `reasoning.text` entries. If the array contains only +* opaque artifacts (e.g. `reasoning.encrypted`), the flat `reasoning_content` +* string is used as a fallback when available. +* +* @param message - The AI message containing OpenRouter-formatted content +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const message = new AIMessage({ +* content: "The answer is 42", +* additional_kwargs: { reasoning_content: "Let me think about this..." }, +* response_metadata: { model_provider: "openrouter" }, +* }); +* message.contentBlocks; +* // [ +* // { type: "reasoning", reasoning: "Let me think about this..." }, +* // { type: "text", text: "The answer is 42" } +* // ] +* ``` +*/ +function convertToV1FromOpenRouterMessage(message) { + const blocks = []; + const reasoningDetails = message.additional_kwargs?.reasoning_details; + let hasVisibleReasoningFromDetails = false; + if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) for (const detail of reasoningDetails) { + if (detail == null || typeof detail !== "object") continue; + const type = detail.type; + if (type === "reasoning.summary") { + const summary = detail.summary; + if (_isString(summary) && summary.length > 0) { + blocks.push({ + type: "reasoning", + reasoning: summary + }); + hasVisibleReasoningFromDetails = true; + } + } else if (type === "reasoning.text") { + const text = detail.text; + if (_isString(text) && text.length > 0) { + blocks.push({ + type: "reasoning", + reasoning: text + }); + hasVisibleReasoningFromDetails = true; + } + } + } + if (!hasVisibleReasoningFromDetails) { + const reasoningContent = message.additional_kwargs?.reasoning_content; + if (_isString(reasoningContent) && reasoningContent.length > 0) blocks.push({ + type: "reasoning", + reasoning: reasoningContent + }); + } + if (typeof message.content === "string") { + if (message.content.length > 0) blocks.push({ + type: "text", + text: message.content + }); + } else for (const block of message.content) if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && _isString(block.text)) blocks.push({ + type: "text", + text: block.text + }); + for (const toolCall of message.tool_calls ?? []) blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +var ChatOpenRouterTranslator = { + translateContent: convertToV1FromOpenRouterMessage, + translateContentChunk: convertToV1FromOpenRouterMessage +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/xai.js +/** +* Converts an xAI AI message to an array of v1 standard content blocks. +* +* This function processes an AI message from xAI's API format +* and converts it to the standardized v1 content block format. It handles +* both the responses API (reasoning object with summary) and completions API +* (reasoning_content string) formats. +* +* @param message - The AI message containing xAI-formatted content +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* // Responses API format +* const message = new AIMessage({ +* content: "The answer is 42", +* additional_kwargs: { +* reasoning: { +* id: "reasoning_123", +* type: "reasoning", +* summary: [{ type: "summary_text", text: "Let me think..." }] +* } +* } +* }); +* const standardBlocks = convertToV1FromXAIMessage(message); +* // Returns: +* // [ +* // { type: "reasoning", reasoning: "Let me think..." }, +* // { type: "text", text: "The answer is 42" } +* // ] +* ``` +* +* @example +* ```typescript +* // Completions API format +* const message = new AIMessage({ +* content: "The answer is 42", +* additional_kwargs: { reasoning_content: "Let me think about this..." } +* }); +* const standardBlocks = convertToV1FromXAIMessage(message); +* // Returns: +* // [ +* // { type: "reasoning", reasoning: "Let me think about this..." }, +* // { type: "text", text: "The answer is 42" } +* // ] +* ``` +*/ +function convertToV1FromXAIMessage(message) { + const blocks = []; + if (_isObject(message.additional_kwargs?.reasoning)) { + const reasoning = message.additional_kwargs.reasoning; + if (_isArray(reasoning.summary)) { + const summaryText = reasoning.summary.reduce((acc, item) => { + if (_isObject(item) && _isString(item.text)) return `${acc}${item.text}`; + return acc; + }, ""); + if (summaryText.length > 0) blocks.push({ + type: "reasoning", + reasoning: summaryText + }); + } + } + const reasoningContent = message.additional_kwargs?.reasoning_content; + if (_isString(reasoningContent) && reasoningContent.length > 0) blocks.push({ + type: "reasoning", + reasoning: reasoningContent + }); + if (typeof message.content === "string") { + if (message.content.length > 0) blocks.push({ + type: "text", + text: message.content + }); + } else for (const block of message.content) if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && _isString(block.text)) blocks.push({ + type: "text", + text: block.text + }); + for (const toolCall of message.tool_calls ?? []) blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +var ChatXAITranslator = { + translateContent: convertToV1FromXAIMessage, + translateContentChunk: convertToV1FromXAIMessage +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/google.js +function convertToV1FromChatGoogleMessage(message) { + function* iterateContent() { + const content = iife$3(() => { + if (typeof message.content === "string") if (message.additional_kwargs.originalTextContentBlock) return [{ + ...message.additional_kwargs.originalTextContentBlock, + type: "text" + }]; + else return [{ + type: "text", + text: message.content + }]; + else { + const originalBlock = message.additional_kwargs?.originalTextContentBlock; + if (originalBlock?.thoughtSignature) { + if (!message.content.some((b) => "thoughtSignature" in b)) { + const result = [...message.content]; + for (let i = result.length - 1; i >= 0; i--) { + const block = result[i]; + if (block.type === "text" && !block.thought) { + block.thoughtSignature = originalBlock.thoughtSignature; + return result; + } + } + } + } + return message.content; + } + }); + for (const block of content) { + const contentBlockBase = iife$3(() => { + if (_isContentBlock(block, "text") && _isString(block.text)) return { + type: "text", + text: block.text + }; + else if (_isContentBlock(block, "inlineData") && _isObject(block.inlineData) && _isString(block.inlineData.mimeType) && _isString(block.inlineData.data)) return { + type: "file", + mimeType: block.inlineData.mimeType, + data: block.inlineData.data + }; + else if (_isContentBlock(block, "functionCall") && _isObject(block.functionCall) && _isString(block.functionCall.name) && _isObject(block.functionCall.args)) return { + type: "tool_call", + id: message.id, + name: block.functionCall.name, + args: block.functionCall.args + }; + else if (_isContentBlock(block, "functionResponse")) return { + type: "non_standard", + value: block + }; + else if (_isContentBlock(block, "fileData") && _isObject(block.fileData) && _isString(block.fileData.mimeType) && _isString(block.fileData.fileUri)) return { + type: "file", + mimeType: block.fileData.mimeType, + fileId: block.fileData.fileUri + }; + else if (_isContentBlock(block, "executableCode")) return { + type: "non_standard", + value: block + }; + else if (_isContentBlock(block, "codeExecutionResult")) return { + type: "non_standard", + value: block + }; + return { + type: "non_standard", + value: block + }; + }); + const contentBlock = iife$3(() => { + if ("thought" in block && block.thought) return { + type: "reasoning", + reasoning: contentBlockBase.type === "text" ? contentBlockBase.text : "", + reasoningContentBlock: contentBlockBase + }; + else return contentBlockBase; + }); + const ret = { + thought: block.thought, + thoughtSignature: block.thoughtSignature, + partMetadata: block.partMetadata, + ...contentBlock + }; + for (const attribute in ret) if (ret[attribute] === void 0) delete ret[attribute]; + yield ret; + } + } + return Array.from(iterateContent()); +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/block_translators/index.js +globalThis.lc_block_translators_registry ??= /* @__PURE__ */ new Map([ + ["anthropic", ChatAnthropicTranslator], + ["bedrock-converse", ChatBedrockConverseTranslator], + ["deepseek", ChatDeepSeekTranslator], + ["google", { + translateContent: convertToV1FromChatGoogleMessage, + translateContentChunk: convertToV1FromChatGoogleMessage + }], + ["google-genai", ChatGoogleGenAITranslator], + ["google-vertexai", ChatVertexTranslator], + ["groq", ChatGroqTranslator], + ["ollama", ChatOllamaTranslator], + ["openai", ChatOpenAITranslator], + ["openrouter", ChatOpenRouterTranslator], + ["xai", ChatXAITranslator] +]); +function getTranslator(modelProvider) { + return globalThis.lc_block_translators_registry.get(modelProvider); +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/metadata.js +function mergeResponseMetadata(a, b) { + return _mergeDicts(a, b) ?? {}; +} +function mergeModalitiesTokenDetails(a, b) { + const output = {}; + if (a?.audio !== void 0 || b?.audio !== void 0) output.audio = (a?.audio ?? 0) + (b?.audio ?? 0); + if (a?.image !== void 0 || b?.image !== void 0) output.image = (a?.image ?? 0) + (b?.image ?? 0); + if (a?.video !== void 0 || b?.video !== void 0) output.video = (a?.video ?? 0) + (b?.video ?? 0); + if (a?.document !== void 0 || b?.document !== void 0) output.document = (a?.document ?? 0) + (b?.document ?? 0); + if (a?.text !== void 0 || b?.text !== void 0) output.text = (a?.text ?? 0) + (b?.text ?? 0); + return output; +} +function mergeInputTokenDetails(a, b) { + const output = { ...mergeModalitiesTokenDetails(a, b) }; + if (a?.cache_read !== void 0 || b?.cache_read !== void 0) output.cache_read = (a?.cache_read ?? 0) + (b?.cache_read ?? 0); + if (a?.cache_creation !== void 0 || b?.cache_creation !== void 0) output.cache_creation = (a?.cache_creation ?? 0) + (b?.cache_creation ?? 0); + return output; +} +function mergeOutputTokenDetails(a, b) { + const output = { ...mergeModalitiesTokenDetails(a, b) }; + if (a?.reasoning !== void 0 || b?.reasoning !== void 0) output.reasoning = (a?.reasoning ?? 0) + (b?.reasoning ?? 0); + return output; +} +function mergeUsageMetadata(a, b) { + return { + input_tokens: (a?.input_tokens ?? 0) + (b?.input_tokens ?? 0), + output_tokens: (a?.output_tokens ?? 0) + (b?.output_tokens ?? 0), + total_tokens: (a?.total_tokens ?? 0) + (b?.total_tokens ?? 0), + input_token_details: mergeInputTokenDetails(a?.input_token_details, b?.input_token_details), + output_token_details: mergeOutputTokenDetails(a?.output_token_details, b?.output_token_details) + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/tool.js +var tool_exports = /* @__PURE__ */ __exportAll({ + ToolMessage: () => ToolMessage, + ToolMessageChunk: () => ToolMessageChunk, + defaultToolCallParser: () => defaultToolCallParser, + isDirectToolOutput: () => isDirectToolOutput, + isToolMessage: () => isToolMessage, + isToolMessageChunk: () => isToolMessageChunk +}); +function isDirectToolOutput(x) { + return x != null && typeof x === "object" && "lc_direct_tool_output" in x && x.lc_direct_tool_output === true; +} +/** +* Represents a tool message in a conversation. +*/ +var ToolMessage = class extends BaseMessage { + static lc_name() { + return "ToolMessage"; + } + get lc_aliases() { + return { tool_call_id: "tool_call_id" }; + } + lc_direct_tool_output = true; + type = "tool"; + /** + * Status of the tool invocation. + * @version 0.2.19 + */ + status; + tool_call_id; + metadata; + /** + * Artifact of the Tool execution which is not meant to be sent to the model. + * + * Should only be specified if it is different from the message content, e.g. if only + * a subset of the full tool output is being passed as message content but the full + * output is needed in other parts of the code. + */ + artifact; + constructor(fields, tool_call_id, name) { + const toolMessageFields = typeof fields === "string" || Array.isArray(fields) ? { + content: fields, + name, + tool_call_id + } : fields; + super(toolMessageFields); + this.tool_call_id = toolMessageFields.tool_call_id; + this.artifact = toolMessageFields.artifact; + this.status = toolMessageFields.status; + this.metadata = toolMessageFields.metadata; + } + static isInstance(message) { + return super.isInstance(message) && message.type === "tool"; + } + get _printableFields() { + return { + ...super._printableFields, + tool_call_id: this.tool_call_id, + artifact: this.artifact + }; + } +}; +/** +* Represents a chunk of a tool message, which can be concatenated +* with other tool message chunks. +*/ +var ToolMessageChunk = class extends BaseMessageChunk { + type = "tool"; + tool_call_id; + /** + * Status of the tool invocation. + * @version 0.2.19 + */ + status; + /** + * Artifact of the Tool execution which is not meant to be sent to the model. + * + * Should only be specified if it is different from the message content, e.g. if only + * a subset of the full tool output is being passed as message content but the full + * output is needed in other parts of the code. + */ + artifact; + constructor(fields) { + super(fields); + this.tool_call_id = fields.tool_call_id; + this.artifact = fields.artifact; + this.status = fields.status; + } + static lc_name() { + return "ToolMessageChunk"; + } + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + artifact: _mergeObj(this.artifact, chunk.artifact), + tool_call_id: this.tool_call_id, + id: this.id ?? chunk.id, + status: _mergeStatus(this.status, chunk.status) + }); + } + get _printableFields() { + return { + ...super._printableFields, + tool_call_id: this.tool_call_id, + artifact: this.artifact + }; + } +}; +function defaultToolCallParser(rawToolCalls) { + const toolCalls = []; + const invalidToolCalls = []; + for (const toolCall of rawToolCalls) if (!toolCall.function) continue; + else { + const functionName = toolCall.function.name; + try { + const functionArgs = JSON.parse(toolCall.function.arguments); + toolCalls.push({ + name: functionName || "", + args: functionArgs || {}, + id: toolCall.id + }); + } catch { + invalidToolCalls.push({ + name: functionName, + args: toolCall.function.arguments, + id: toolCall.id, + error: "Malformed args." + }); + } + } + return [toolCalls, invalidToolCalls]; +} +/** +* @deprecated Use {@link ToolMessage.isInstance} instead +*/ +function isToolMessage(x) { + return typeof x === "object" && x !== null && "getType" in x && typeof x.getType === "function" && x.getType() === "tool"; +} +/** +* @deprecated Use {@link ToolMessageChunk.isInstance} instead +*/ +function isToolMessageChunk(x) { + return x._getType() === "tool"; +} +//#endregion +//#region node_modules/@langchain/core/dist/tools/utils.js +function _isToolCall(toolCall) { + return !!(toolCall && typeof toolCall === "object" && "type" in toolCall && toolCall.type === "tool_call"); +} +function _configHasToolCallId(config) { + return !!(config && typeof config === "object" && "toolCall" in config && config.toolCall != null && typeof config.toolCall === "object" && "id" in config.toolCall && typeof config.toolCall.id === "string"); +} +/** +* Custom error class used to handle exceptions related to tool input parsing. +* It extends the built-in `Error` class and adds an optional `output` +* property that can hold the output that caused the exception. +*/ +var ToolInputParsingException = class extends Error { + output; + constructor(message, output) { + super(message); + this.output = output; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/json.js +function parseJsonMarkdown(s, parser = parsePartialJson) { + s = s.trim(); + const firstFenceIndex = s.indexOf("```"); + if (firstFenceIndex === -1) return parser(s); + let contentAfterFence = s.substring(firstFenceIndex + 3); + if (contentAfterFence.startsWith("json\n")) contentAfterFence = contentAfterFence.substring(5); + else if (contentAfterFence.startsWith("json")) contentAfterFence = contentAfterFence.substring(4); + else if (contentAfterFence.startsWith("\n")) contentAfterFence = contentAfterFence.substring(1); + const closingFenceIndex = contentAfterFence.indexOf("```"); + let finalContent = contentAfterFence; + if (closingFenceIndex !== -1) finalContent = contentAfterFence.substring(0, closingFenceIndex); + return parser(finalContent.trim()); +} +/** +* Recursive descent partial JSON parser. +* @param s - The string to parse. +* @returns The parsed value. +* @throws Error if the input is a malformed JSON string. +*/ +function strictParsePartialJson(s) { + try { + return JSON.parse(s); + } catch {} + const buffer = s.trim(); + if (buffer.length === 0) throw new Error("Unexpected end of JSON input"); + let pos = 0; + function skipWhitespace() { + while (pos < buffer.length && /\s/.test(buffer[pos])) pos += 1; + } + function parseString() { + if (buffer[pos] !== "\"") throw new Error(`Expected '"' at position ${pos}, got '${buffer[pos]}'`); + pos += 1; + let result = ""; + let escaped = false; + while (pos < buffer.length) { + const char = buffer[pos]; + if (escaped) { + if (char === "n") result += "\n"; + else if (char === "t") result += " "; + else if (char === "r") result += "\r"; + else if (char === "\\") result += "\\"; + else if (char === "\"") result += "\""; + else if (char === "b") result += "\b"; + else if (char === "f") result += "\f"; + else if (char === "/") result += "/"; + else if (char === "u") { + const hex = buffer.substring(pos + 1, pos + 5); + if (/^[0-9A-Fa-f]{0,4}$/.test(hex)) { + if (hex.length === 4) result += String.fromCharCode(Number.parseInt(hex, 16)); + else result += `u${hex}`; + pos += hex.length; + } else throw new Error(`Invalid unicode escape sequence '\\u${hex}' at position ${pos}`); + } else throw new Error(`Invalid escape sequence '\\${char}' at position ${pos}`); + escaped = false; + } else if (char === "\\") escaped = true; + else if (char === "\"") { + pos += 1; + return result; + } else result += char; + pos += 1; + } + if (escaped) result += "\\"; + return result; + } + function parseNumber() { + const start = pos; + let numStr = ""; + if (buffer[pos] === "-") { + numStr += "-"; + pos += 1; + } + if (pos < buffer.length && buffer[pos] === "0") { + numStr += "0"; + pos += 1; + if (buffer[pos] >= "0" && buffer[pos] <= "9") throw new Error(`Invalid number at position ${start}`); + } + if (pos < buffer.length && buffer[pos] >= "1" && buffer[pos] <= "9") while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") { + numStr += buffer[pos]; + pos += 1; + } + if (pos < buffer.length && buffer[pos] === ".") { + numStr += "."; + pos += 1; + while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") { + numStr += buffer[pos]; + pos += 1; + } + } + if (pos < buffer.length && (buffer[pos] === "e" || buffer[pos] === "E")) { + numStr += buffer[pos]; + pos += 1; + if (pos < buffer.length && (buffer[pos] === "+" || buffer[pos] === "-")) { + numStr += buffer[pos]; + pos += 1; + } + while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") { + numStr += buffer[pos]; + pos += 1; + } + } + if (numStr === "-") return -0; + const num = Number.parseFloat(numStr); + if (Number.isNaN(num)) { + pos = start; + throw new Error(`Invalid number '${numStr}' at position ${start}`); + } + return num; + } + function parseValue() { + skipWhitespace(); + if (pos >= buffer.length) throw new Error(`Unexpected end of input at position ${pos}`); + const char = buffer[pos]; + if (char === "{") return parseObject(); + if (char === "[") return parseArray(); + if (char === "\"") return parseString(); + if ("null".startsWith(buffer.substring(pos, pos + 4))) { + pos += Math.min(4, buffer.length - pos); + return null; + } + if ("true".startsWith(buffer.substring(pos, pos + 4))) { + pos += Math.min(4, buffer.length - pos); + return true; + } + if ("false".startsWith(buffer.substring(pos, pos + 5))) { + pos += Math.min(5, buffer.length - pos); + return false; + } + if (char === "-" || char >= "0" && char <= "9") return parseNumber(); + throw new Error(`Unexpected character '${char}' at position ${pos}`); + } + function parseArray() { + if (buffer[pos] !== "[") throw new Error(`Expected '[' at position ${pos}, got '${buffer[pos]}'`); + const arr = []; + pos += 1; + skipWhitespace(); + if (pos >= buffer.length) return arr; + if (buffer[pos] === "]") { + pos += 1; + return arr; + } + while (pos < buffer.length) { + skipWhitespace(); + if (pos >= buffer.length) return arr; + arr.push(parseValue()); + skipWhitespace(); + if (pos >= buffer.length) return arr; + if (buffer[pos] === "]") { + pos += 1; + return arr; + } else if (buffer[pos] === ",") { + pos += 1; + continue; + } + throw new Error(`Expected ',' or ']' at position ${pos}, got '${buffer[pos]}'`); + } + return arr; + } + function parseObject() { + if (buffer[pos] !== "{") throw new Error(`Expected '{' at position ${pos}, got '${buffer[pos]}'`); + const obj = {}; + pos += 1; + skipWhitespace(); + if (pos >= buffer.length) return obj; + if (buffer[pos] === "}") { + pos += 1; + return obj; + } + while (pos < buffer.length) { + skipWhitespace(); + if (pos >= buffer.length) return obj; + const key = parseString(); + skipWhitespace(); + if (pos >= buffer.length) return obj; + if (buffer[pos] !== ":") throw new Error(`Expected ':' at position ${pos}, got '${buffer[pos]}'`); + pos += 1; + skipWhitespace(); + if (pos >= buffer.length) return obj; + obj[key] = parseValue(); + skipWhitespace(); + if (pos >= buffer.length) return obj; + if (buffer[pos] === "}") { + pos += 1; + return obj; + } else if (buffer[pos] === ",") { + pos += 1; + continue; + } + throw new Error(`Expected ',' or '}' at position ${pos}, got '${buffer[pos]}'`); + } + return obj; + } + const value = parseValue(); + skipWhitespace(); + if (pos < buffer.length) throw new Error(`Unexpected character '${buffer[pos]}' at position ${pos}`); + return value; +} +function parsePartialJson(s) { + try { + if (typeof s === "undefined") return null; + return strictParsePartialJson(s); + } catch { + return null; + } +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/chat.js +/** +* Represents a chat message in a conversation. +*/ +var ChatMessage = class ChatMessage extends BaseMessage { + static lc_name() { + return "ChatMessage"; + } + type = "generic"; + role; + static _chatMessageClass() { + return ChatMessage; + } + constructor(fields, role) { + if (typeof fields === "string" || Array.isArray(fields)) fields = { + content: fields, + role + }; + super(fields); + this.role = fields.role; + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "generic"; + } + get _printableFields() { + return { + ...super._printableFields, + role: this.role + }; + } +}; +/** +* Represents a chunk of a chat message, which can be concatenated with +* other chat message chunks. +*/ +var ChatMessageChunk = class extends BaseMessageChunk { + static lc_name() { + return "ChatMessageChunk"; + } + type = "generic"; + role; + constructor(fields, role) { + if (typeof fields === "string" || Array.isArray(fields)) fields = { + content: fields, + role + }; + super(fields); + this.role = fields.role; + } + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + 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, + id: this.id ?? chunk.id + }); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "generic"; + } + get _printableFields() { + return { + ...super._printableFields, + role: this.role + }; + } +}; +/** +* @deprecated Use {@link ChatMessage.isInstance} instead +*/ +function isChatMessage(x) { + return x._getType() === "generic"; +} +/** +* @deprecated Use {@link ChatMessageChunk.isInstance} instead +*/ +function isChatMessageChunk(x) { + return x._getType() === "generic"; +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/function.js +/** +* Represents a function message in a conversation. +*/ +var FunctionMessage = class extends BaseMessage { + static lc_name() { + return "FunctionMessage"; + } + type = "function"; + name; + constructor(fields) { + super(fields); + this.name = fields.name; + } +}; +/** +* Represents a chunk of a function message, which can be concatenated +* with other function message chunks. +*/ +var FunctionMessageChunk = class extends BaseMessageChunk { + static lc_name() { + return "FunctionMessageChunk"; + } + type = "function"; + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + 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 ?? "", + id: this.id ?? chunk.id + }); + } +}; +function isFunctionMessage(x) { + return x._getType() === "function"; +} +function isFunctionMessageChunk(x) { + return x._getType() === "function"; +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/human.js +/** +* Represents a human message in a conversation. +*/ +var HumanMessage = class extends BaseMessage { + static lc_name() { + return "HumanMessage"; + } + type = "human"; + constructor(fields) { + super(fields); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "human"; + } +}; +/** +* Represents a chunk of a human message, which can be concatenated with +* other human message chunks. +*/ +var HumanMessageChunk = class extends BaseMessageChunk { + static lc_name() { + return "HumanMessageChunk"; + } + type = "human"; + constructor(fields) { + super(fields); + } + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + id: this.id ?? chunk.id + }); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "human"; + } +}; +/** +* @deprecated Use {@link HumanMessage.isInstance} instead +*/ +function isHumanMessage(x) { + return x.getType() === "human"; +} +/** +* @deprecated Use {@link HumanMessageChunk.isInstance} instead +*/ +function isHumanMessageChunk(x) { + return x.getType() === "human"; +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/modifier.js +/** +* Message responsible for deleting other messages. +* +* `RemoveMessage` is intentionally not generic over `MessageStructure`. +* Its content is always `[]` (empty), so carrying a structure type parameter +* would only cause unnecessary type incompatibilities when mixing messages +* from different structure configurations (e.g. passing a `RemoveMessage` +* into an API that expects `Message`). +*/ +var RemoveMessage = class extends BaseMessage { + type = "remove"; + /** + * The ID of the message to remove. + */ + id; + constructor(fields) { + super({ + ...fields, + content: [] + }); + this.id = fields.id; + } + get _printableFields() { + return { + ...super._printableFields, + id: this.id + }; + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "remove"; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/messages/system.js +/** +* Represents a system message in a conversation. +*/ +var SystemMessage = class SystemMessage extends BaseMessage { + static lc_name() { + return "SystemMessage"; + } + type = "system"; + constructor(fields) { + super(fields); + } + /** + * Concatenates a string or another system message with the current system message. + * @param chunk - The chunk to concatenate with the system message. + * @returns A new system message with the concatenated content. + */ + concat(chunk) { + if (typeof chunk === "string") return new SystemMessage({ + content: mergeContent(this.content, chunk), + additional_kwargs: this.additional_kwargs, + response_metadata: this.response_metadata, + id: this.id, + name: this.name + }); + if (SystemMessage.isInstance(chunk)) return new SystemMessage({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: { + ...this.additional_kwargs, + ...chunk.additional_kwargs + }, + response_metadata: { + ...this.response_metadata, + ...chunk.response_metadata + }, + id: this.id ?? chunk.id, + name: this.name ?? chunk.name + }); + throw new Error("Unexpected chunk type for system message"); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "system"; + } +}; +/** +* Represents a chunk of a system message, which can be concatenated with +* other system message chunks. +*/ +var SystemMessageChunk = class extends BaseMessageChunk { + static lc_name() { + return "SystemMessageChunk"; + } + type = "system"; + constructor(fields) { + super(fields); + } + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + id: this.id ?? chunk.id + }); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "system"; + } +}; +/** +* @deprecated Use {@link SystemMessage.isInstance} instead +*/ +function isSystemMessage(x) { + return x._getType() === "system"; +} +/** +* @deprecated Use {@link SystemMessageChunk.isInstance} instead +*/ +function isSystemMessageChunk(x) { + return x._getType() === "system"; +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/utils.js +function chunkUsesRawInputArgs(chunk) { + return chunk.isCustomTool === true; +} +/** +* Immediately-invoked function expression. +* +* @param fn - The function to execute +* @returns The result of the function +*/ +var iife$2 = (fn) => fn(); +function _coerceToolCall(toolCall) { + if (_isToolCall(toolCall)) return toolCall; + else if (typeof toolCall.id === "string" && toolCall.type === "function" && typeof toolCall.function === "object" && toolCall.function !== null && "arguments" in toolCall.function && typeof toolCall.function.arguments === "string" && "name" in toolCall.function && typeof toolCall.function.name === "string") return { + id: toolCall.id, + args: JSON.parse(toolCall.function.arguments), + name: toolCall.function.name, + type: "tool_call" + }; + else return toolCall; +} +function isSerializedConstructor(x) { + return typeof x === "object" && x != null && x.lc === 1 && Array.isArray(x.id) && x.kwargs != null && typeof x.kwargs === "object"; +} +function _constructMessageFromParams(params) { + let type; + let rest; + if (isSerializedConstructor(params)) { + const className = params.id.at(-1); + if (className === "HumanMessage" || className === "HumanMessageChunk") type = "user"; + else if (className === "AIMessage" || className === "AIMessageChunk") type = "assistant"; + else if (className === "SystemMessage" || className === "SystemMessageChunk") type = "system"; + else if (className === "FunctionMessage" || className === "FunctionMessageChunk") type = "function"; + else if (className === "ToolMessage" || className === "ToolMessageChunk") type = "tool"; + else type = "unknown"; + rest = params.kwargs; + } else { + const { type: extractedType, ...otherParams } = params; + type = extractedType; + rest = otherParams; + } + if (type === "human" || type === "user") return new HumanMessage(rest); + else if (type === "ai" || type === "assistant") { + const { tool_calls: rawToolCalls, ...other } = rest; + if (!Array.isArray(rawToolCalls)) return new AIMessage(rest); + const tool_calls = rawToolCalls.map(_coerceToolCall); + return new AIMessage({ + ...other, + tool_calls + }); + } else if (type === "system") return new SystemMessage(rest); + else if (type === "developer") return new SystemMessage({ + ...rest, + additional_kwargs: { + ...rest.additional_kwargs, + __openai_role__: "developer" + } + }); + else if (type === "tool" && "tool_call_id" in rest) return new ToolMessage({ + ...rest, + content: rest.content, + tool_call_id: rest.tool_call_id, + name: rest.name + }); + else if (type === "remove" && "id" in rest && typeof rest.id === "string") return new RemoveMessage({ + ...rest, + id: rest.id + }); + else throw addLangChainErrorFields$1(/* @__PURE__ */ new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE"); +} +function coerceMessageLikeToMessage(messageLike) { + if (typeof messageLike === "string") return new HumanMessage(messageLike); + else if (isBaseMessage(messageLike)) return messageLike; + if (Array.isArray(messageLike)) { + const [type, content] = messageLike; + return _constructMessageFromParams({ + type, + content + }); + } else if (_isMessageFieldWithRole(messageLike)) { + const { role: type, ...rest } = messageLike; + return _constructMessageFromParams({ + ...rest, + type + }); + } else return _constructMessageFromParams(messageLike); +} +/** +* Renders a single content block to a compact string representation. +* Text blocks are returned as-is; multimodal blocks (image, audio, video, file) +* become short placeholders like `[image]` so their existence is preserved +* without inflating token counts with base64 data or metadata. +*/ +function _contentBlockToString(block) { + if (typeof block === "string") return block; + switch (block.type) { + case "text": return block.text ?? ""; + case "text-plain": return block.text ?? "[text-plain file]"; + case "image": + case "image_url": return "[image]"; + case "audio": + case "input_audio": return "[audio]"; + case "video": return "[video]"; + case "file": return "[file]"; + case "reasoning": + case "tool_call": + case "tool_call_chunk": + case "invalid_tool_call": + case "server_tool_call": + case "server_tool_call_chunk": + case "server_tool_call_result": + case "non_standard": return ""; + default: return block.type ? `[${block.type}]` : ""; + } +} +/** +* This function is used by memory classes to get a string representation +* of the chat message history, based on the message content and role. +* +* Produces compact output like: +* ``` +* Human: What's the weather? +* AI: Let me check...[tool_calls] +* Tool: 72°F and sunny +* ``` +* +* This avoids token inflation from metadata when stringifying message objects directly. +*/ +function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { + const string_messages = []; + for (const m of messages) { + let role; + if (m.type === "human") role = humanPrefix; + else if (m.type === "ai") role = aiPrefix; + else if (m.type === "system") role = "System"; + else if (m.type === "tool") role = "Tool"; + else if (m.type === "generic") role = m.role; + else throw new Error(`Got unsupported message type: ${m.type}`); + const nameStr = m.name ? `${m.name}, ` : ""; + const readableContent = typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.map(_contentBlockToString).filter(Boolean).join("") : ""; + let message = `${role}: ${nameStr}${readableContent}`; + if (m.type === "ai") { + const aiMessage = m; + if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) message += JSON.stringify(aiMessage.tool_calls); + else if (aiMessage.additional_kwargs && "function_call" in aiMessage.additional_kwargs) message += JSON.stringify(aiMessage.additional_kwargs.function_call); + } + string_messages.push(message); + } + return string_messages.join("\n"); +} +/** +* Maps messages from an older format (V1) to the current `StoredMessage` +* format. If the message is already in the `StoredMessage` format, it is +* returned as is. Otherwise, it transforms the V1 message into a +* `StoredMessage`. This function is important for maintaining +* compatibility with older message formats. +*/ +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 "generic": + 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}`); + } +} +/** +* Transforms an array of `StoredMessage` instances into an array of +* `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage` +* function to ensure all messages are in the `StoredMessage` format, then +* creates new instances of the appropriate `BaseMessage` subclass based +* on the type of each message. This function is used to prepare stored +* messages for use in a chat context. +*/ +function mapStoredMessagesToChatMessages(messages) { + return messages.map(mapStoredMessageToChatMessage); +} +/** +* Transforms an array of `BaseMessage` instances into an array of +* `StoredMessage` instances. It does this by calling the `toDict` method +* on each `BaseMessage`, which returns a `StoredMessage`. This function +* is used to prepare chat messages for storage. +*/ +function mapChatMessagesToStoredMessages(messages) { + return messages.map((message) => message.toDict()); +} +function convertToChunk(message) { + const type = message._getType(); + if (type === "human") return new HumanMessageChunk({ ...message }); + else if (type === "ai") { + let aiChunkFields = { ...message }; + if ("tool_calls" in aiChunkFields) aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: void 0, + args: JSON.stringify(tc.args) + })) + }; + return new AIMessageChunk({ ...aiChunkFields }); + } else if (type === "system") return new SystemMessageChunk({ ...message }); + else if (type === "function") return new FunctionMessageChunk({ ...message }); + else if (ChatMessage.isInstance(message)) return new ChatMessageChunk({ ...message }); + else throw new Error("Unknown message type."); +} +/** +* Collapses an array of tool call chunks into complete tool calls. +* +* This function groups tool call chunks by their id and/or index, then attempts to +* parse and validate the accumulated arguments for each group. Successfully parsed +* tool calls are returned as valid `ToolCall` objects, while malformed ones are +* returned as `InvalidToolCall` objects. +* +* @param chunks - An array of `ToolCallChunk` objects to collapse +* @returns An object containing: +* - `tool_call_chunks`: The original input chunks +* - `tool_calls`: An array of successfully parsed and validated tool calls +* - `invalid_tool_calls`: An array of tool calls that failed parsing or validation +* +* @remarks +* Chunks are grouped using the following matching logic: +* - If a chunk has both an id and index, it matches chunks with the same id and index +* - If a chunk has only an id, it matches chunks with the same id +* - If a chunk has only an index, it matches chunks with the same index +* +* For each group, the function: +* 1. Concatenates all `args` strings from the chunks +* 2. Attempts to parse the concatenated string as JSON +* 3. Validates that the result is a non-null object with a valid id +* 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid) +*/ +function collapseToolCallChunks(chunks) { + const groupedToolCallChunks = chunks.reduce((acc, chunk) => { + const matchedChunkIndex = acc.findIndex(([match]) => { + if ("id" in chunk && chunk.id && "index" in chunk && chunk.index !== void 0) return chunk.id === match.id && chunk.index === match.index; + if ("id" in chunk && chunk.id) return chunk.id === match.id; + if ("index" in chunk && chunk.index !== void 0) return chunk.index === match.index; + return false; + }); + if (matchedChunkIndex !== -1) acc[matchedChunkIndex].push(chunk); + else acc.push([chunk]); + return acc; + }, []); + const toolCalls = []; + const invalidToolCalls = []; + for (const chunks of groupedToolCallChunks) { + let parsedArgs = null; + const usesRawInputArgs = chunks.some(chunkUsesRawInputArgs); + const name = chunks[0]?.name ?? ""; + const joinedArgsRaw = chunks.map((c) => c.args || "").join(""); + const joinedArgs = usesRawInputArgs ? joinedArgsRaw : joinedArgsRaw.trim(); + const argsStr = joinedArgs.length ? joinedArgs : "{}"; + const id = chunks.find((c) => c.id)?.id ?? chunks[0]?.id; + if (usesRawInputArgs && id) { + toolCalls.push({ + name, + args: { input: joinedArgs }, + id, + type: "tool_call" + }); + continue; + } + try { + parsedArgs = parsePartialJson(argsStr); + if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) throw new Error("Malformed tool call chunk args."); + toolCalls.push({ + name, + args: parsedArgs, + id, + type: "tool_call" + }); + } catch { + invalidToolCalls.push({ + name, + args: argsStr, + id, + error: "Malformed args.", + type: "invalid_tool_call" + }); + } + } + return { + tool_call_chunks: chunks, + tool_calls: toolCalls, + invalid_tool_calls: invalidToolCalls + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/ai.js +function coerceToContentBlocks(value) { + if (typeof value === "string") return value.length > 0 ? [{ + type: "text", + text: value + }] : []; + if (Array.isArray(value)) return value; + if (value == null) return []; + return [value]; +} +var AIMessage = class extends BaseMessage { + type = "ai"; + tool_calls = []; + invalid_tool_calls = []; + usage_metadata; + get lc_aliases() { + return { + ...super.lc_aliases, + tool_calls: "tool_calls", + invalid_tool_calls: "invalid_tool_calls", + usage_metadata: "usage_metadata" + }; + } + constructor(fields) { + let initParams; + if (typeof fields === "string" || Array.isArray(fields)) initParams = { + content: fields, + tool_calls: [], + invalid_tool_calls: [], + additional_kwargs: {} + }; + else { + initParams = fields; + const rawToolCalls = initParams.additional_kwargs?.tool_calls; + const toolCalls = initParams.tool_calls; + if (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === void 0 || toolCalls.length === 0)) console.warn([ + "New LangChain packages are available that more efficiently handle", + "tool calling.\n\nPlease upgrade your packages to versions that set", + "message tool calls. e.g., `pnpm install @langchain/anthropic`,", + "pnpm install @langchain/openai`, etc." + ].join(" ")); + try { + if (!(rawToolCalls == null) && toolCalls === void 0) { + const [parsedToolCalls, invalidToolCalls] = defaultToolCallParser(rawToolCalls); + initParams.tool_calls = parsedToolCalls ?? []; + initParams.invalid_tool_calls = invalidToolCalls ?? []; + } else { + initParams.tool_calls = initParams.tool_calls ?? []; + initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? []; + } + } catch { + initParams.tool_calls = []; + initParams.invalid_tool_calls = []; + } + if (initParams.response_metadata !== void 0 && "output_version" in initParams.response_metadata && initParams.response_metadata.output_version === "v1" && initParams.content !== void 0) { + initParams.contentBlocks = coerceToContentBlocks(initParams.content); + initParams.content = void 0; + } + if (initParams.contentBlocks !== void 0) { + if (!Array.isArray(initParams.contentBlocks)) initParams.contentBlocks = coerceToContentBlocks(initParams.contentBlocks); + if (initParams.tool_calls) { + const missingContentBlockToolCalls = initParams.tool_calls.filter((toolCall) => !initParams.contentBlocks?.some((block) => block.type === "tool_call" && block.id === toolCall.id && block.name === toolCall.name)); + initParams.contentBlocks.push(...missingContentBlockToolCalls.map((toolCall) => ({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }))); + } + const missingToolCalls = initParams.contentBlocks.filter((block) => block.type === "tool_call").filter((block) => !initParams.tool_calls?.some((toolCall) => toolCall.id === block.id && toolCall.name === block.name)); + if (missingToolCalls.length > 0) initParams.tool_calls = [...initParams.tool_calls ?? [], ...missingToolCalls.map((block) => ({ + type: "tool_call", + id: block.id, + name: block.name, + args: block.args + }))]; + } + } + super(initParams); + if (typeof initParams !== "string") { + this.tool_calls = initParams.tool_calls ?? this.tool_calls; + this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; + } + this.usage_metadata = initParams.usage_metadata; + } + static lc_name() { + return "AIMessage"; + } + get contentBlocks() { + if (this.response_metadata && "output_version" in this.response_metadata && this.response_metadata.output_version === "v1") return this.content; + if (this.response_metadata && "model_provider" in this.response_metadata && typeof this.response_metadata.model_provider === "string") { + const translator = getTranslator(this.response_metadata.model_provider); + if (translator) return translator.translateContent(this); + } + const blocks = super.contentBlocks; + if (this.tool_calls) { + const missingToolCalls = this.tool_calls.filter((block) => !blocks.some((b) => b.id === block.id && b.name === block.name)); + blocks.push(...missingToolCalls.map((block) => ({ + type: "tool_call", + id: block.id, + name: block.name, + args: block.args + }))); + } + return blocks; + } + get _printableFields() { + return { + ...super._printableFields, + tool_calls: this.tool_calls, + invalid_tool_calls: this.invalid_tool_calls, + usage_metadata: this.usage_metadata + }; + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "ai"; + } +}; +/** +* @deprecated Use {@link AIMessage.isInstance} instead +*/ +function isAIMessage(x) { + return x._getType() === "ai"; +} +/** +* @deprecated Use {@link AIMessageChunk.isInstance} instead +*/ +function isAIMessageChunk(x) { + return x._getType() === "ai"; +} +/** +* Represents a chunk of an AI message, which can be concatenated with +* other AI message chunks. +*/ +var AIMessageChunk = class extends BaseMessageChunk { + type = "ai"; + tool_calls = []; + invalid_tool_calls = []; + tool_call_chunks = []; + usage_metadata; + constructor(fields) { + let initParams; + if (typeof fields === "string" || Array.isArray(fields)) initParams = { + content: fields, + tool_calls: [], + invalid_tool_calls: [], + tool_call_chunks: [] + }; + else if (fields.tool_call_chunks === void 0 || fields.tool_call_chunks.length === 0) initParams = { + ...fields, + tool_calls: fields.tool_calls ?? [], + invalid_tool_calls: [], + tool_call_chunks: [], + usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 + }; + else { + const collapsed = collapseToolCallChunks(fields.tool_call_chunks ?? []); + initParams = { + ...fields, + tool_call_chunks: collapsed.tool_call_chunks, + tool_calls: collapsed.tool_calls, + invalid_tool_calls: collapsed.invalid_tool_calls, + usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 + }; + } + super(initParams); + this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks; + this.tool_calls = initParams.tool_calls ?? this.tool_calls; + this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; + this.usage_metadata = initParams.usage_metadata; + } + get lc_aliases() { + return { + ...super.lc_aliases, + tool_calls: "tool_calls", + invalid_tool_calls: "invalid_tool_calls", + tool_call_chunks: "tool_call_chunks", + usage_metadata: "usage_metadata" + }; + } + static lc_name() { + return "AIMessageChunk"; + } + get contentBlocks() { + if (this.response_metadata && "output_version" in this.response_metadata && this.response_metadata.output_version === "v1") return this.content; + if (this.response_metadata && "model_provider" in this.response_metadata && typeof this.response_metadata.model_provider === "string") { + const translator = getTranslator(this.response_metadata.model_provider); + if (translator) return translator.translateContent(this); + } + const blocks = super.contentBlocks; + if (this.tool_calls) { + if (typeof this.content !== "string") { + const contentToolCalls = this.content.filter((block) => block.type === "tool_call").map((block) => block.id); + for (const toolCall of this.tool_calls) if (toolCall.id && !contentToolCalls.includes(toolCall.id)) blocks.push({ + ...toolCall, + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + } + } + return blocks; + } + get _printableFields() { + return { + ...super._printableFields, + tool_calls: this.tool_calls, + tool_call_chunks: this.tool_call_chunks, + invalid_tool_calls: this.invalid_tool_calls, + usage_metadata: this.usage_metadata + }; + } + concat(chunk) { + const combinedFields = { + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: mergeResponseMetadata(this.response_metadata, chunk.response_metadata), + tool_call_chunks: [], + tool_calls: [], + id: this.id ?? chunk.id + }; + if (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) { + const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks); + if (rawToolCalls !== void 0 && rawToolCalls.length > 0) combinedFields.tool_call_chunks = rawToolCalls; + } + if (this.tool_calls !== void 0 || chunk.tool_calls !== void 0) { + const rawToolCalls = _mergeLists(this.tool_calls, chunk.tool_calls); + if (rawToolCalls !== void 0 && rawToolCalls.length > 0) combinedFields.tool_calls = rawToolCalls; + } + if (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) combinedFields.usage_metadata = mergeUsageMetadata(this.usage_metadata, chunk.usage_metadata); + const Cls = this.constructor; + return new Cls(combinedFields); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "ai"; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/env.js +var env_exports = /* @__PURE__ */ __exportAll({ + getEnv: () => getEnv$1, + getEnvironmentVariable: () => getEnvironmentVariable$1, + getRuntimeEnvironment: () => getRuntimeEnvironment$1, + isBrowser: () => isBrowser$1, + isDeno: () => isDeno$1, + isJsDom: () => isJsDom$1, + isNode: () => isNode$1, + isWebWorker: () => isWebWorker$1 +}); +var isBrowser$1 = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +var isWebWorker$1 = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +var isJsDom$1 = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom"); +var isDeno$1 = () => typeof Deno !== "undefined"; +var isNode$1 = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno$1(); +var getEnv$1 = () => { + let env; + if (isBrowser$1()) env = "browser"; + else if (isNode$1()) env = "node"; + else if (isWebWorker$1()) env = "webworker"; + else if (isJsDom$1()) env = "jsdom"; + else if (isDeno$1()) env = "deno"; + else env = "other"; + return env; +}; +var runtimeEnvironment$1; +function getRuntimeEnvironment$1() { + if (runtimeEnvironment$1 === void 0) runtimeEnvironment$1 = { + library: "langchain-js", + runtime: getEnv$1() + }; + return runtimeEnvironment$1; +} +function getEnvironmentVariable$1(name) { + try { + if (typeof process !== "undefined") return process.env?.[name]; + else if (isDeno$1()) return Deno?.env.get(name); + else return; + } catch { + return; + } +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/max.js +var max_default = "ffffffff-ffff-ffff-ffff-ffffffffffff"; +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/nil.js +var nil_default = "00000000-0000-0000-0000-000000000000"; +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/regex.js +var regex_default$1 = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/validate.js +function validate$3(uuid) { + return typeof uuid === "string" && regex_default$1.test(uuid); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/parse.js +function parse$2(uuid) { + if (!validate$3(uuid)) throw TypeError("Invalid UUID"); + let v; + return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, v >>> 16 & 255, v >>> 8 & 255, v & 255, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 255, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 255, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 255, (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255, v / 4294967296 & 255, v >>> 24 & 255, v >>> 16 & 255, v >>> 8 & 255, v & 255); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/stringify.js +/** +* Convert array of 16 byte values to UUID string format of the form: +* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX +*/ +var byteToHex$1 = []; +for (let i = 0; i < 256; ++i) byteToHex$1.push((i + 256).toString(16).slice(1)); +function unsafeStringify$1(arr, offset = 0) { + return (byteToHex$1[arr[offset + 0]] + byteToHex$1[arr[offset + 1]] + byteToHex$1[arr[offset + 2]] + byteToHex$1[arr[offset + 3]] + "-" + byteToHex$1[arr[offset + 4]] + byteToHex$1[arr[offset + 5]] + "-" + byteToHex$1[arr[offset + 6]] + byteToHex$1[arr[offset + 7]] + "-" + byteToHex$1[arr[offset + 8]] + byteToHex$1[arr[offset + 9]] + "-" + byteToHex$1[arr[offset + 10]] + byteToHex$1[arr[offset + 11]] + byteToHex$1[arr[offset + 12]] + byteToHex$1[arr[offset + 13]] + byteToHex$1[arr[offset + 14]] + byteToHex$1[arr[offset + 15]]).toLowerCase(); +} +function stringify$2(arr, offset = 0) { + const uuid = unsafeStringify$1(arr, offset); + if (!validate$3(uuid)) throw TypeError("Stringified UUID is invalid"); + return uuid; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/rng.js +var rnds8$1 = /* @__PURE__ */ new Uint8Array(16); +function rng$1() { + return crypto.getRandomValues(rnds8$1); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/v1.js +var _state$2 = {}; +function v1$1(options, buf, offset) { + let bytes; + const isV6 = options?._v6 ?? false; + if (options) { + const optionsKeys = Object.keys(options); + if (optionsKeys.length === 1 && optionsKeys[0] === "_v6") options = void 0; + } + if (options) bytes = v1Bytes(options.random ?? options.rng?.() ?? rng$1(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); + else { + const now = Date.now(); + const rnds = rng$1(); + updateV1State(_state$2, now, rnds); + bytes = v1Bytes(rnds, _state$2.msecs, _state$2.nsecs, isV6 ? void 0 : _state$2.clockseq, isV6 ? void 0 : _state$2.node, buf, offset); + } + return buf ?? unsafeStringify$1(bytes); +} +function updateV1State(state, now, rnds) { + state.msecs ??= -Infinity; + state.nsecs ??= 0; + if (now === state.msecs) { + state.nsecs++; + if (state.nsecs >= 1e4) { + state.node = void 0; + state.nsecs = 0; + } + } else if (now > state.msecs) state.nsecs = 0; + else if (now < state.msecs) state.node = void 0; + if (!state.node) { + state.node = rnds.slice(10, 16); + state.node[0] |= 1; + state.clockseq = (rnds[8] << 8 | rnds[9]) & 16383; + } + state.msecs = now; + return state; +} +function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { + if (rnds.length < 16) throw new Error("Random bytes length must be >= 16"); + if (!buf) { + buf = /* @__PURE__ */ new Uint8Array(16); + offset = 0; + } else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + msecs ??= Date.now(); + nsecs ??= 0; + clockseq ??= (rnds[8] << 8 | rnds[9]) & 16383; + node ??= rnds.slice(10, 16); + msecs += 0xb1d069b5400; + const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; + buf[offset++] = tl >>> 24 & 255; + buf[offset++] = tl >>> 16 & 255; + buf[offset++] = tl >>> 8 & 255; + buf[offset++] = tl & 255; + const tmh = msecs / 4294967296 * 1e4 & 268435455; + buf[offset++] = tmh >>> 8 & 255; + buf[offset++] = tmh & 255; + buf[offset++] = tmh >>> 24 & 15 | 16; + buf[offset++] = tmh >>> 16 & 255; + buf[offset++] = clockseq >>> 8 | 128; + buf[offset++] = clockseq & 255; + for (let n = 0; n < 6; ++n) buf[offset++] = node[n]; + return buf; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/v4.js +function v4$2(options, buf, offset) { + if (!buf && !options && crypto.randomUUID) return crypto.randomUUID(); + return _v4$1(options, buf, offset); +} +function _v4$1(options, buf, offset) { + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? rng$1(); + if (rnds.length < 16) throw new Error("Random bytes length must be >= 16"); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + for (let i = 0; i < 16; ++i) buf[offset + i] = rnds[i]; + return buf; + } + return unsafeStringify$1(rnds); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/sha1.js +function f$1(s, x, y, z) { + switch (s) { + case 0: return x & y ^ ~x & z; + case 1: return x ^ y ^ z; + case 2: return x & y ^ x & z ^ y & z; + case 3: return x ^ y ^ z; + } +} +function ROTL$1(x, n) { + return x << n | x >>> 32 - n; +} +function sha1$1(bytes) { + const K = [ + 1518500249, + 1859775393, + 2400959708, + 3395469782 + ]; + const H = [ + 1732584193, + 4023233417, + 2562383102, + 271733878, + 3285377520 + ]; + const newBytes = new Uint8Array(bytes.length + 1); + newBytes.set(bytes); + newBytes[bytes.length] = 128; + bytes = newBytes; + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + for (let i = 0; i < N; ++i) { + const arr = /* @__PURE__ */ new Uint32Array(16); + for (let j = 0; j < 16; ++j) arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + M[i] = arr; + } + M[N - 1][14] = (bytes.length - 1) * 8 / 2 ** 32; + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 4294967295; + for (let i = 0; i < N; ++i) { + const W = /* @__PURE__ */ new Uint32Array(80); + for (let t = 0; t < 16; ++t) W[t] = M[i][t]; + for (let t = 16; t < 80; ++t) W[t] = ROTL$1(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL$1(a, 5) + f$1(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL$1(b, 30) >>> 0; + b = a; + a = T; + } + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/v35.js +function stringToBytes$1(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) bytes[i] = str.charCodeAt(i); + return bytes; +} +var DNS$1 = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; +var URL$2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; +function v35$1(version, hash, value, namespace, buf, offset) { + const valueBytes = typeof value === "string" ? stringToBytes$1(value) : value; + const namespaceBytes = typeof namespace === "string" ? parse$2(namespace) : namespace; + if (typeof namespace === "string") namespace = parse$2(namespace); + if (namespace?.length !== 16) throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash(bytes); + bytes[6] = bytes[6] & 15 | version; + bytes[8] = bytes[8] & 63 | 128; + if (buf) { + offset ??= 0; + if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + for (let i = 0; i < 16; ++i) buf[offset + i] = bytes[i]; + return buf; + } + return unsafeStringify$1(bytes); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/v5.js +function v5$2(value, namespace, buf, offset) { + return v35$1(80, sha1$1, value, namespace, buf, offset); +} +v5$2.DNS = DNS$1; +v5$2.URL = URL$2; +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/v1ToV6.js +function v1ToV6(uuid) { + const v6Bytes = _v1ToV6(typeof uuid === "string" ? parse$2(uuid) : uuid); + return typeof uuid === "string" ? unsafeStringify$1(v6Bytes) : v6Bytes; +} +function _v1ToV6(v1Bytes) { + return Uint8Array.of((v1Bytes[6] & 15) << 4 | v1Bytes[7] >> 4 & 15, (v1Bytes[7] & 15) << 4 | (v1Bytes[4] & 240) >> 4, (v1Bytes[4] & 15) << 4 | (v1Bytes[5] & 240) >> 4, (v1Bytes[5] & 15) << 4 | (v1Bytes[0] & 240) >> 4, (v1Bytes[0] & 15) << 4 | (v1Bytes[1] & 240) >> 4, (v1Bytes[1] & 15) << 4 | (v1Bytes[2] & 240) >> 4, 96 | v1Bytes[2] & 15, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/v6.js +function v6$1(options, buf, offset) { + options ??= {}; + offset ??= 0; + let bytes = v1$1({ + ...options, + _v6: true + }, /* @__PURE__ */ new Uint8Array(16)); + bytes = v1ToV6(bytes); + if (buf) { + if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + for (let i = 0; i < 16; i++) buf[offset + i] = bytes[i]; + return buf; + } + return unsafeStringify$1(bytes); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/v7.js +var _state$1 = {}; +function v7$2(options, buf, offset) { + let bytes; + if (options) bytes = v7Bytes$1(options.random ?? options.rng?.() ?? rng$1(), options.msecs, options.seq, buf, offset); + else { + const now = Date.now(); + const rnds = rng$1(); + updateV7State$1(_state$1, now, rnds); + bytes = v7Bytes$1(rnds, _state$1.msecs, _state$1.seq, buf, offset); + } + return buf ?? unsafeStringify$1(bytes); +} +function updateV7State$1(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = rnds[6] << 23 | rnds[7] << 16 | rnds[8] << 8 | rnds[9]; + state.msecs = now; + } else { + state.seq = state.seq + 1 | 0; + if (state.seq === 0) state.msecs++; + } + return state; +} +function v7Bytes$1(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) throw new Error("Random bytes length must be >= 16"); + if (!buf) { + buf = /* @__PURE__ */ new Uint8Array(16); + offset = 0; + } else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + msecs ??= Date.now(); + seq ??= rnds[6] * 127 << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9]; + buf[offset++] = msecs / 1099511627776 & 255; + buf[offset++] = msecs / 4294967296 & 255; + buf[offset++] = msecs / 16777216 & 255; + buf[offset++] = msecs / 65536 & 255; + buf[offset++] = msecs / 256 & 255; + buf[offset++] = msecs & 255; + buf[offset++] = 112 | seq >>> 28 & 15; + buf[offset++] = seq >>> 20 & 255; + buf[offset++] = 128 | seq >>> 14 & 63; + buf[offset++] = seq >>> 6 & 255; + buf[offset++] = seq << 2 & 255 | rnds[10] & 3; + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/version.js +function version$1(uuid) { + if (!validate$3(uuid)) throw TypeError("Invalid UUID"); + return parseInt(uuid.slice(14, 15), 16); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/uuid/index.js +var uuid_exports = /* @__PURE__ */ __exportAll({ + MAX: () => MAX, + NIL: () => NIL, + parse: () => parse$1, + stringify: () => stringify$1, + v1: () => v1, + v4: () => v4$1, + v5: () => v5$1, + v6: () => v6, + v7: () => v7$1, + validate: () => validate$2, + version: () => version +}); +var MAX = max_default; +var NIL = nil_default; +var parse$1 = parse$2; +var stringify$1 = stringify$2; +var v1 = v1$1; +var v4$1 = v4$2; +var v5$1 = v5$2; +var v6 = v6$1; +var v7$1 = v7$2; +var validate$2 = validate$3; +var version = version$1; +//#endregion +//#region node_modules/@langchain/core/dist/callbacks/base.js +var base_exports$2 = /* @__PURE__ */ __exportAll({ + BaseCallbackHandler: () => BaseCallbackHandler, + callbackHandlerPrefersChatModelStreamEvents: () => callbackHandlerPrefersChatModelStreamEvents, + callbackHandlerPrefersStreaming: () => callbackHandlerPrefersStreaming, + isBaseCallbackHandler: () => isBaseCallbackHandler +}); +/** +* Abstract class that provides a set of optional methods that can be +* overridden in derived classes to handle various events during the +* execution of a LangChain application. +*/ +var BaseCallbackHandlerMethodsClass = class {}; +function callbackHandlerPrefersStreaming(x) { + return "lc_prefer_streaming" in x && x.lc_prefer_streaming; +} +function callbackHandlerPrefersChatModelStreamEvents(x) { + return "lc_prefer_chat_model_stream_events" in x && x.lc_prefer_chat_model_stream_events; +} +/** +* Abstract base class for creating callback handlers in the LangChain +* framework. It provides a set of optional methods that can be overridden +* in derived classes to handle various events during the execution of a +* LangChain application. +*/ +var BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass { + lc_serializable = false; + get lc_namespace() { + return [ + "langchain_core", + "callbacks", + this.name + ]; + } + get lc_secrets() {} + get lc_attributes() {} + get lc_aliases() {} + get lc_serializable_keys() {} + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [...this.lc_namespace, get_lc_unique_name(this.constructor)]; + } + lc_kwargs; + ignoreLLM = false; + ignoreChain = false; + ignoreAgent = false; + ignoreRetriever = false; + ignoreCustomEvent = false; + raiseError = false; + awaitHandlers = getEnvironmentVariable$1("LANGCHAIN_CALLBACKS_BACKGROUND") === "false"; + constructor(input) { + super(); + 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.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent; + this.raiseError = input.raiseError ?? this.raiseError; + this.awaitHandlers = this.raiseError || (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 { + name = v7$1(); + constructor() { + super(); + Object.assign(this, methods); + } + } + return new Handler(); + } +}; +var isBaseCallbackHandler = (x) => { + const callbackHandler = x; + return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean"; +}; +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/regex.js +var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/validate.js +function validate$1(uuid) { + return typeof uuid === "string" && regex_default.test(uuid); +} +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/parse.js +function parse(uuid) { + if (!validate$1(uuid)) throw TypeError("Invalid UUID"); + let v; + return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, v >>> 16 & 255, v >>> 8 & 255, v & 255, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 255, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 255, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 255, (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255, v / 4294967296 & 255, v >>> 24 & 255, v >>> 16 & 255, v >>> 8 & 255, v & 255); +} +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/stringify.js +/** +* Convert array of 16 byte values to UUID string format of the form: +* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX +*/ +var byteToHex = []; +for (let i = 0; i < 256; ++i) byteToHex.push((i + 256).toString(16).slice(1)); +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]]).toLowerCase(); +} +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/rng.js +var rnds8 = /* @__PURE__ */ new Uint8Array(16); +function rng() { + return crypto.getRandomValues(rnds8); +} +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/v4.js +function v4(options, buf, offset) { + if (!buf && !options && crypto.randomUUID) return crypto.randomUUID(); + return _v4(options, buf, offset); +} +function _v4(options, buf, offset) { + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? rng(); + if (rnds.length < 16) throw new Error("Random bytes length must be >= 16"); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + for (let i = 0; i < 16; ++i) buf[offset + i] = rnds[i]; + return buf; + } + return unsafeStringify(rnds); +} +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/sha1.js +function f(s, x, y, z) { + switch (s) { + case 0: return x & y ^ ~x & z; + case 1: return x ^ y ^ z; + case 2: return x & y ^ x & z ^ y & z; + case 3: return x ^ y ^ z; + } +} +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} +function sha1(bytes) { + const K = [ + 1518500249, + 1859775393, + 2400959708, + 3395469782 + ]; + const H = [ + 1732584193, + 4023233417, + 2562383102, + 271733878, + 3285377520 + ]; + const newBytes = new Uint8Array(bytes.length + 1); + newBytes.set(bytes); + newBytes[bytes.length] = 128; + bytes = newBytes; + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + for (let i = 0; i < N; ++i) { + const arr = /* @__PURE__ */ new Uint32Array(16); + for (let j = 0; j < 16; ++j) arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + M[i] = arr; + } + M[N - 1][14] = (bytes.length - 1) * 8 / 2 ** 32; + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 4294967295; + for (let i = 0; i < N; ++i) { + const W = /* @__PURE__ */ new Uint32Array(80); + for (let t = 0; t < 16; ++t) W[t] = M[i][t]; + for (let t = 16; t < 80; ++t) W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]); +} +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/v35.js +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) bytes[i] = str.charCodeAt(i); + return bytes; +} +var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; +var URL$1 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; +function v35(version, hash, value, namespace, buf, offset) { + const valueBytes = typeof value === "string" ? stringToBytes(value) : value; + const namespaceBytes = typeof namespace === "string" ? parse(namespace) : namespace; + if (typeof namespace === "string") namespace = parse(namespace); + if (namespace?.length !== 16) throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash(bytes); + bytes[6] = bytes[6] & 15 | version; + bytes[8] = bytes[8] & 63 | 128; + if (buf) { + offset ??= 0; + if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + for (let i = 0; i < 16; ++i) buf[offset + i] = bytes[i]; + return buf; + } + return unsafeStringify(bytes); +} +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/v5.js +function v5(value, namespace, buf, offset) { + return v35(80, sha1, value, namespace, buf, offset); +} +v5.DNS = DNS; +v5.URL = URL$1; +//#endregion +//#region node_modules/langsmith/dist/utils/uuid/src/v7.js +var _state = {}; +function v7(options, buf, offset) { + let bytes; + if (options) bytes = v7Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.seq, buf, offset); + else { + const now = Date.now(); + const rnds = rng(); + updateV7State(_state, now, rnds); + bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset); + } + return buf ?? unsafeStringify(bytes); +} +function updateV7State(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = rnds[6] << 23 | rnds[7] << 16 | rnds[8] << 8 | rnds[9]; + state.msecs = now; + } else { + state.seq = state.seq + 1 | 0; + if (state.seq === 0) state.msecs++; + } + return state; +} +function v7Bytes(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) throw new Error("Random bytes length must be >= 16"); + if (!buf) { + buf = /* @__PURE__ */ new Uint8Array(16); + offset = 0; + } else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + msecs ??= Date.now(); + seq ??= rnds[6] * 127 << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9]; + buf[offset++] = msecs / 1099511627776 & 255; + buf[offset++] = msecs / 4294967296 & 255; + buf[offset++] = msecs / 16777216 & 255; + buf[offset++] = msecs / 65536 & 255; + buf[offset++] = msecs / 256 & 255; + buf[offset++] = msecs & 255; + buf[offset++] = 112 | seq >>> 28 & 15; + buf[offset++] = seq >>> 20 & 255; + buf[offset++] = 128 | seq >>> 14 & 63; + buf[offset++] = seq >>> 6 & 255; + buf[offset++] = seq << 2 & 255 | rnds[10] & 3; + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +//#endregion +//#region node_modules/langsmith/dist/experimental/otel/constants.js +var GEN_AI_OPERATION_NAME = "gen_ai.operation.name"; +var GEN_AI_SYSTEM = "gen_ai.system"; +var GEN_AI_REQUEST_MODEL = "gen_ai.request.model"; +var GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"; +var GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"; +var GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"; +var GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"; +var GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"; +var GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"; +var GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"; +var GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"; +var GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"; +var GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"; +var GENAI_PROMPT = "gen_ai.prompt"; +var GENAI_COMPLETION = "gen_ai.completion"; +var GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query"; +var GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body"; +var GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"; +var GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"; +var GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"; +var GEN_AI_RESPONSE_ID = "gen_ai.response.id"; +var GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier"; +var GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint"; +var GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details"; +var GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details"; +var LANGSMITH_SESSION_ID = "langsmith.trace.session_id"; +var LANGSMITH_SESSION_NAME = "langsmith.trace.session_name"; +var LANGSMITH_RUN_TYPE = "langsmith.span.kind"; +var LANGSMITH_NAME = "langsmith.trace.name"; +var LANGSMITH_METADATA = "langsmith.metadata"; +var LANGSMITH_TAGS = "langsmith.span.tags"; +var LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming"; +var LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers"; +var LANGSMITH_USAGE_METADATA = "langsmith.usage_metadata"; +//#endregion +//#region node_modules/langsmith/dist/singletons/fetch.js +var DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); +var globalFetchSupportsWebStreaming = void 0; +var LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); +var _shouldStreamForGlobalFetchImplementation = () => { + if (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] === void 0) return true; + return globalFetchSupportsWebStreaming ?? false; +}; +/** +* @internal +*/ +var _getFetchImplementation = (debug) => { + return async (...args) => { + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + const [url, options] = args; + console.log(`→ ${options?.method || "GET"} ${url}`); + } + const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? DEFAULT_FETCH_IMPLEMENTATION)(...args); + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") console.log(`← ${res.status} ${res.statusText} ${res.url}`); + return res; + }; +}; +//#endregion +//#region node_modules/langsmith/dist/utils/project.js +var getDefaultProjectName = () => { + return getLangSmithEnvironmentVariable("PROJECT") ?? getEnvironmentVariable("LANGCHAIN_SESSION") ?? "default"; +}; +//#endregion +//#region node_modules/langsmith/dist/utils/warn.js +var warnedMessages = {}; +function warnOnce(message) { + if (!warnedMessages[message]) { + console.warn(message); + warnedMessages[message] = true; + } +} +//#endregion +//#region node_modules/langsmith/dist/utils/xxhash/xxhash.js +var n = (n) => BigInt(n); +var PRIME32_1 = n("0x9E3779B1"); +var PRIME32_2 = n("0x85EBCA77"); +var PRIME32_3 = n("0xC2B2AE3D"); +var PRIME64_1 = n("0x9E3779B185EBCA87"); +var PRIME64_2 = n("0xC2B2AE3D27D4EB4F"); +var PRIME64_3 = n("0x165667B19E3779F9"); +var PRIME64_4 = n("0x85EBCA77C2B2AE63"); +var PRIME64_5 = n("0x27D4EB2F165667C5"); +var PRIME_MX1 = n("0x165667919E3779F9"); +var PRIME_MX2 = n("0x9FB21C651E98DF25"); +function hexToBytes(hex) { + const bytes = new Uint8Array(hex.length / 2); + for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16); + return bytes; +} +var kkey = hexToBytes("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"); +var mask128 = (n(1) << n(128)) - n(1); +var mask64 = (n(1) << n(64)) - n(1); +var mask32 = (n(1) << n(32)) - n(1); +var STRIPE_LEN = 64; +var ACC_NB = STRIPE_LEN / 8; +var _U64 = 8; +var _U32 = 4; +function getView(buf, offset = 0) { + return new Uint8Array(buf.buffer, buf.byteOffset + offset, buf.length - offset); +} +function readBigUInt64LE(buf, offset = 0) { + return new DataView(buf.buffer, buf.byteOffset + offset).getBigUint64(0, true); +} +function readUInt32LE(buf, offset = 0) { + return new DataView(buf.buffer, buf.byteOffset + offset).getUint32(0, true); +} +function readUInt8(buf, offset = 0) { + return buf[offset]; +} +var bswap64 = (a) => { + return (a & n(255)) << n(56) | (a & n(65280)) << n(40) | (a & n(16711680)) << n(24) | (a & n(4278190080)) << n(8) | (a & n(0xff00000000)) >> n(8) | (a & n(0xff0000000000)) >> n(24) | (a & n(0xff000000000000)) >> n(40) | (a & n(0xff00000000000000)) >> n(56); +}; +var bswap32 = (a) => { + a = (a & n(65535)) << n(16) | (a & n(4294901760)) >> n(16); + a = (a & n(16711935)) << n(8) | (a & n(4278255360)) >> n(8); + return a; +}; +var XXH_mult32to64 = (a, b) => (a & mask32) * (b & mask32) & mask64; +var assert = (a) => { + if (!a) throw new Error("Assert failed"); +}; +function rotl32(a, b) { + return (a << b | a >> n(32) - b) & mask32; +} +function XXH3_accumulate_512(acc, data, key) { + for (let i = 0; i < ACC_NB; i++) { + const data_val = readBigUInt64LE(data, i * 8); + const data_key = data_val ^ readBigUInt64LE(key, i * 8); + acc[i ^ 1] += data_val; + acc[i] += XXH_mult32to64(data_key, data_key >> n(32)); + } + return acc; +} +function XXH3_accumulate(acc, data, key, nbStripes) { + for (let n = 0; n < nbStripes; n++) XXH3_accumulate_512(acc, getView(data, n * STRIPE_LEN), getView(key, n * 8)); + return acc; +} +function XXH3_scrambleAcc(acc, key) { + for (let i = 0; i < ACC_NB; i++) { + const key64 = readBigUInt64LE(key, i * 8); + let acc64 = acc[i]; + acc64 = xorshift64(acc64, n(47)); + acc64 ^= key64; + acc64 *= PRIME32_1; + acc[i] = acc64 & mask64; + } + return acc; +} +function XXH3_mix2Accs(acc, key) { + return XXH3_mul128_fold64(acc[0] ^ readBigUInt64LE(key, 0), acc[1] ^ readBigUInt64LE(key, _U64)); +} +function XXH3_mergeAccs(acc, key, start) { + let result64 = start; + result64 += XXH3_mix2Accs(acc.slice(0), getView(key, 0 * _U32)); + result64 += XXH3_mix2Accs(acc.slice(2), getView(key, 4 * _U32)); + result64 += XXH3_mix2Accs(acc.slice(4), getView(key, 8 * _U32)); + result64 += XXH3_mix2Accs(acc.slice(6), getView(key, 12 * _U32)); + return XXH3_avalanche(result64 & mask64); +} +function XXH3_hashLong(acc, data, secret, f_acc, f_scramble) { + const nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN) / 8); + const block_len = STRIPE_LEN * nbStripesPerBlock; + const nb_blocks = Math.floor((data.byteLength - 1) / block_len); + for (let n = 0; n < nb_blocks; n++) { + acc = XXH3_accumulate(acc, getView(data, n * block_len), secret, nbStripesPerBlock); + acc = f_scramble(acc, getView(secret, secret.byteLength - STRIPE_LEN)); + } + { + const nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN); + acc = XXH3_accumulate(acc, getView(data, nb_blocks * block_len), secret, nbStripes); + acc = f_acc(acc, getView(data, data.byteLength - STRIPE_LEN), getView(secret, secret.byteLength - STRIPE_LEN - 7)); + } + return acc; +} +function XXH3_hashLong_128b(data, secret, seed) { + let acc = new BigUint64Array([ + PRIME32_3, + PRIME64_1, + PRIME64_2, + PRIME64_3, + PRIME64_4, + PRIME32_2, + PRIME64_5, + PRIME32_1 + ]); + assert(data.length > 128); + acc = XXH3_hashLong(acc, data, secret, XXH3_accumulate_512, XXH3_scrambleAcc); + assert(acc.length * 8 == 64); + { + const low64 = XXH3_mergeAccs(acc, getView(secret, 11), n(data.byteLength) * PRIME64_1 & mask64); + return XXH3_mergeAccs(acc, getView(secret, secret.byteLength - STRIPE_LEN - 11), ~(n(data.byteLength) * PRIME64_2) & mask64) << n(64) | low64; + } +} +function XXH3_mul128_fold64(a, b) { + const lll = a * b & mask128; + return lll & mask64 ^ lll >> n(64); +} +function XXH3_mix16B(data, key, seed) { + return XXH3_mul128_fold64((readBigUInt64LE(data, 0) ^ readBigUInt64LE(key, 0) + seed) & mask64, (readBigUInt64LE(data, 8) ^ readBigUInt64LE(key, 8) - seed) & mask64); +} +function XXH3_mix32B(acc, data1, data2, key, seed) { + let accl = acc & mask64; + let acch = acc >> n(64) & mask64; + accl += XXH3_mix16B(data1, key, seed); + accl ^= readBigUInt64LE(data2, 0) + readBigUInt64LE(data2, 8); + accl &= mask64; + acch += XXH3_mix16B(data2, getView(key, 16), seed); + acch ^= readBigUInt64LE(data1, 0) + readBigUInt64LE(data1, 8); + acch &= mask64; + return acch << n(64) | accl; +} +function XXH3_avalanche(h64) { + h64 ^= h64 >> n(37); + h64 *= PRIME_MX1; + h64 &= mask64; + h64 ^= h64 >> n(32); + return h64; +} +function XXH3_avalanche64(h64) { + h64 ^= h64 >> n(33); + h64 *= PRIME64_2; + h64 &= mask64; + h64 ^= h64 >> n(29); + h64 *= PRIME64_3; + h64 &= mask64; + h64 ^= h64 >> n(32); + return h64; +} +function XXH3_len_1to3_128b(data, key32, seed) { + const len = data.byteLength; + assert(len > 0 && len <= 3); + const combined = n(readUInt8(data, len - 1)) | n(len << 8) | n(readUInt8(data, 0) << 16) | n(readUInt8(data, len >> 1) << 24); + const low = (combined ^ (n(readUInt32LE(key32, 0)) ^ n(readUInt32LE(key32, 4))) + seed) & mask64; + const bhigh = (n(readUInt32LE(key32, 8)) ^ n(readUInt32LE(key32, 12))) - seed; + return (XXH3_avalanche64((rotl32(bswap32(combined), n(13)) ^ bhigh) & mask64) & mask64) << n(64) | XXH3_avalanche64(low); +} +function xorshift64(b, shift) { + return b ^ b >> shift; +} +function XXH3_len_4to8_128b(data, key32, seed) { + const len = data.byteLength; + assert(len >= 4 && len <= 8); + { + const l1 = readUInt32LE(data, 0); + const l2 = readUInt32LE(data, len - 4); + let m128 = ((n(l1) | n(l2) << n(32)) ^ (readBigUInt64LE(key32, 16) ^ readBigUInt64LE(key32, 24)) + seed & mask64) * (PRIME64_1 + (n(len) << n(2))) & mask128; + m128 += (m128 & mask64) << n(65); + m128 &= mask128; + m128 ^= m128 >> n(67); + return xorshift64(xorshift64(m128 & mask64, n(35)) * PRIME_MX2 & mask64, n(28)) | XXH3_avalanche(m128 >> n(64)) << n(64); + } +} +function XXH3_len_9to16_128b(data, key64, seed) { + const len = data.byteLength; + assert(len >= 9 && len <= 16); + { + const bitflipl = (readBigUInt64LE(key64, 32) ^ readBigUInt64LE(key64, 40)) + seed & mask64; + const bitfliph = (readBigUInt64LE(key64, 48) ^ readBigUInt64LE(key64, 56)) - seed & mask64; + const ll1 = readBigUInt64LE(data); + let ll2 = readBigUInt64LE(data, len - 8); + let m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_1; + const m128_l = (m128 & mask64) + (n(len - 1) << n(54)); + m128 = m128 & (mask128 ^ mask64) | m128_l; + ll2 ^= bitfliph; + m128 += ll2 + (ll2 & mask32) * (PRIME32_2 - n(1)) << n(64); + m128 &= mask128; + m128 ^= bswap64(m128 >> n(64)); + let h128 = (m128 & mask64) * PRIME64_2; + h128 += (m128 >> n(64)) * PRIME64_2 << n(64); + h128 &= mask128; + return XXH3_avalanche(h128 & mask64) | XXH3_avalanche(h128 >> n(64)) << n(64); + } +} +function XXH3_len_0to16_128b(data, seed) { + const len = data.byteLength; + assert(len <= 16); + if (len > 8) return XXH3_len_9to16_128b(data, kkey, seed); + if (len >= 4) return XXH3_len_4to8_128b(data, kkey, seed); + if (len > 0) return XXH3_len_1to3_128b(data, kkey, seed); + return XXH3_avalanche64(seed ^ readBigUInt64LE(kkey, 64) ^ readBigUInt64LE(kkey, 72)) | XXH3_avalanche64(seed ^ readBigUInt64LE(kkey, 80) ^ readBigUInt64LE(kkey, 88)) << n(64); +} +function inv64(x) { + return ~x + n(1) & mask64; +} +function XXH3_len_17to128_128b(data, secret, seed) { + let acc = n(data.byteLength) * PRIME64_1 & mask64; + let i = n(data.byteLength - 1) / n(32); + while (i >= 0) { + const ni = Number(i); + acc = XXH3_mix32B(acc, getView(data, 16 * ni), getView(data, data.byteLength - 16 * (ni + 1)), getView(secret, 32 * ni), seed); + i--; + } + let h128l = acc + (acc >> n(64)) & mask64; + h128l = XXH3_avalanche(h128l); + let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; + h128h &= mask64; + h128h = inv64(XXH3_avalanche(h128h)); + return h128l | h128h << n(64); +} +function XXH3_len_129to240_128b(data, secret, seed) { + let acc = n(data.byteLength) * PRIME64_1 & mask64; + for (let i = 32; i < 160; i += 32) acc = XXH3_mix32B(acc, getView(data, i - 32), getView(data, i - 16), getView(secret, i - 32), seed); + acc = XXH3_avalanche(acc & mask64) | XXH3_avalanche(acc >> n(64)) << n(64); + for (let i = 160; i <= data.byteLength; i += 32) acc = XXH3_mix32B(acc, getView(data, i - 32), getView(data, i - 16), getView(secret, 3 + i - 160), seed); + acc = XXH3_mix32B(acc, getView(data, data.byteLength - 16), getView(data, data.byteLength - 32), getView(secret, 103), inv64(seed)); + let h128l = acc + (acc >> n(64)) & mask64; + h128l = XXH3_avalanche(h128l); + let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; + h128h &= mask64; + h128h = inv64(XXH3_avalanche(h128h)); + return h128l | h128h << n(64); +} +/** +* Compute XXH3 128-bit hash of the input data. +* +* @param data - Input data as Uint8Array +* @param seed - Optional seed value (default: 0) +* @returns 128-bit hash as a single BigInt (high 64 bits << 64 | low 64 bits) +*/ +function XXH3_128(data, seed = n(0)) { + const len = data.byteLength; + if (len <= 16) return XXH3_len_0to16_128b(data, seed); + if (len <= 128) return XXH3_len_17to128_128b(data, kkey, seed); + if (len <= 240) return XXH3_len_129to240_128b(data, kkey, seed); + return XXH3_hashLong_128b(data, kkey, seed); +} +/** +* Convert a 128-bit hash (BigInt) to a 16-byte Uint8Array. +* +* @param hash128 - 128-bit hash as BigInt +* @returns 16-byte Uint8Array in little-endian byte order +*/ +function xxh128ToBytes(hash128) { + const result = /* @__PURE__ */ new Uint8Array(16); + const view = new DataView(result.buffer); + const low64 = hash128 & mask64; + const high64 = hash128 >> n(64); + view.setBigUint64(0, high64, false); + view.setBigUint64(8, low64, false); + return result; +} +//#endregion +//#region node_modules/langsmith/dist/utils/_uuid.js +var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +function assertUuid(str, which) { + if (!UUID_REGEX.test(str)) { + const msg = which !== void 0 ? `Invalid UUID for ${which}: ${str}` : `Invalid UUID: ${str}`; + throw new Error(msg); + } + return str; +} +/** +* Generate a UUID v7 from a timestamp. +* +* @param timestamp - The timestamp in milliseconds +* @returns A UUID v7 string +*/ +function uuid7FromTime(timestamp) { + return v7({ + msecs: typeof timestamp === "string" ? Date.parse(timestamp) : timestamp, + seq: 0 + }); +} +/** +* Get the version of a UUID string. +* @param uuidStr - The UUID string to check +* @returns The version number (1-7) or null if invalid +*/ +function getUuidVersion(uuidStr) { + if (!UUID_REGEX.test(uuidStr)) return null; + const versionChar = uuidStr[14]; + return parseInt(versionChar, 16); +} +/** +* Convert a UUID string to its 16-byte representation. +* @param uuidStr - The UUID string (with or without dashes) +* @returns A Uint8Array containing the 16 bytes of the UUID +*/ +function uuidToBytes(uuidStr) { + const hex = uuidStr.replace(/-/g, ""); + const bytes = /* @__PURE__ */ new Uint8Array(16); + for (let i = 0; i < 16; i++) bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); + return bytes; +} +/** +* Convert 16 bytes to a UUID string. +* @param bytes - A Uint8Array containing 16 bytes +* @returns A UUID string in standard format +*/ +function bytesToUuid(bytes) { + const hex = Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +var _textEncoder = new TextEncoder(); +/** +* Generates a 16-byte fingerprint for deterministic UUID generation using XXH3-128. +* +* XXH3 is an extremely fast, non-cryptographic hash function that provides excellent +* collision resistance. It's widely used in production systems and compatible with +* xxHash implementations in other languages. +* +* See: https://github.com/Cyan4973/xxHash +* +* @param str - The input string to hash +* @returns A Uint8Array containing 16 bytes of hash output +*/ +function _fastHash128(str) { + return xxh128ToBytes(XXH3_128(_textEncoder.encode(str))); +} +/** +* Generate a deterministic UUID v7 derived from an original UUID and a key. +* +* This function creates a new UUID that: +* - Preserves the timestamp from the original UUID if it's UUID v7 +* - Uses current time if the original is not UUID v7 +* - Uses deterministic "random" bits derived from hashing the original + key +* - Is valid UUID v7 format +* +* This is used for creating replica IDs that maintain time-ordering properties +* while being deterministic across distributed systems. +* +* @param originalId - The source UUID string (ideally UUID v7 to preserve timestamp) +* @param key - A string key used for deterministic derivation (e.g., project name) +* @returns A new UUID v7 string with preserved timestamp (if original is v7) and +* deterministic random bits +* +* @example +* ```typescript +* const original = uuidv7(); +* const replicaId = nonCryptographicUuid7Deterministic(original, "replica-project"); +* // Same inputs always produce same output +* assert(nonCryptographicUuid7Deterministic(original, "replica-project") === replicaId); +* ``` +*/ +function nonCryptographicUuid7Deterministic(originalId, key) { + const h = _fastHash128(`${originalId}:${key}`); + const b = /* @__PURE__ */ new Uint8Array(16); + if (getUuidVersion(originalId) === 7) { + const originalBytes = uuidToBytes(originalId); + b.set(originalBytes.slice(0, 6), 0); + } else { + const msecs = Date.now(); + b[0] = msecs / 1099511627776 & 255; + b[1] = msecs / 4294967296 & 255; + b[2] = msecs / 16777216 & 255; + b[3] = msecs / 65536 & 255; + b[4] = msecs / 256 & 255; + b[5] = msecs & 255; + } + b[6] = 112 | h[0] & 15; + b[7] = h[1]; + b[8] = 128 | h[2] & 63; + b.set(h.slice(3, 10), 9); + return bytesToUuid(b); +} +//#endregion +//#region node_modules/langsmith/dist/env.js +var isEnvTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== void 0) return tracingEnabled; + return !!["TRACING_V2", "TRACING"].find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); +}; +//#endregion +//#region node_modules/langsmith/dist/singletons/traceable.js +var MockAsyncLocalStorage$1 = class { + getStore() {} + run(_, callback) { + return callback(); + } +}; +var TRACING_ALS_KEY$1 = Symbol.for("ls:tracing_async_local_storage"); +var mockAsyncLocalStorage$1 = new MockAsyncLocalStorage$1(); +var AsyncLocalStorageProvider$1 = class { + getInstance() { + return globalThis[TRACING_ALS_KEY$1] ?? mockAsyncLocalStorage$1; + } + initializeGlobalInstance(instance) { + if (globalThis[TRACING_ALS_KEY$1] === void 0) globalThis[TRACING_ALS_KEY$1] = instance; + } +}; +var AsyncLocalStorageProviderSingleton$1 = new AsyncLocalStorageProvider$1(); +function getCurrentRunTree(permitAbsentRunTree = false) { + const runTree = AsyncLocalStorageProviderSingleton$1.getInstance().getStore(); + if (!permitAbsentRunTree && runTree === void 0) throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); + return runTree; +} +function isTraceableFunction(x) { + return typeof x === "function" && "langsmith:traceable" in x; +} +//#endregion +//#region node_modules/langsmith/dist/utils/fs.js +/** +* File system abstraction (Node.js version). +* +* This file is swapped with fs.browser.ts for browser builds +* via the package.json browser field. +*/ +var path$2 = nodePath; +async function mkdir$1(dir) { + await nodeFsPromises.mkdir(dir, { recursive: true }); +} +async function writeFileAtomic(filePath, content) { + const tempPath = `${filePath}.tmp`; + await nodeFsPromises.writeFile(tempPath, content, { + encoding: "utf8", + mode: 384 + }); + await nodeFsPromises.rename(tempPath, filePath); +} +async function readdir$1(dir) { + return nodeFsPromises.readdir(dir); +} +async function stat$1(filePath) { + return nodeFsPromises.stat(filePath); +} +function existsSync(p) { + return nodeFs.existsSync(p); +} +function mkdirSync(dir) { + nodeFs.mkdirSync(dir, { recursive: true }); +} +function writeFileSync(filePath, content) { + nodeFs.writeFileSync(filePath, content); +} +function renameSync(oldPath, newPath) { + nodeFs.renameSync(oldPath, newPath); +} +function unlinkSync(filePath) { + nodeFs.unlinkSync(filePath); +} +function readFileSync(filePath) { + return nodeFs.readFileSync(filePath, "utf-8"); +} +async function mkdirExclusive(dir) { + await nodeFsPromises.mkdir(dir, { mode: 448 }); +} +function statMtimeMs(filePath) { + try { + return nodeFs.statSync(filePath).mtimeMs; + } catch { + return; + } +} +async function rmRecursive(filePath) { + await nodeFsPromises.rm(filePath, { + recursive: true, + force: true + }); +} +//#endregion +//#region node_modules/langsmith/dist/utils/prompt_cache/index.js +/** +* Prompt caching module for LangSmith SDK. +* +* Provides an LRU cache with background refresh for prompt caching. +* Uses stale-while-revalidate pattern for optimal performance. +* +* Works in all environments. File operations (dump/load) use the shared +* fs abstraction which is swapped for browser builds via package.json +* browser field (no-ops in browser — cache just doesn't persist). +*/ +/** +* Check if a cache entry is stale based on TTL. +*/ +function isStale(entry, ttlSeconds) { + if (ttlSeconds === null) return false; + return Date.now() - entry.createdAt > ttlSeconds * 1e3; +} +/** +* LRU cache with background refresh for prompts. +* +* Features: +* - In-memory LRU cache with configurable max size +* - Background refresh using setInterval +* - Stale-while-revalidate: returns stale data while refresh happens +* - Uses the most recently used client for a key for refreshes +* - JSON dump/load for offline use +* +* @example +* ```typescript +* const cache = new Cache({ +* maxSize: 100, +* ttlSeconds: 3600, +* }); +* +* // Use the cache +* cache.set("my-prompt:latest", promptCommit); +* const cached = cache.get("my-prompt:latest"); +* +* // Cleanup +* cache.stop(); +* ``` +*/ +var PromptCache = class { + constructor(config = {}) { + Object.defineProperty(this, "cache", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + Object.defineProperty(this, "maxSize", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "ttlSeconds", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "refreshIntervalSeconds", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "refreshTimer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_metrics", { + enumerable: true, + configurable: true, + writable: true, + value: { + hits: 0, + misses: 0, + refreshes: 0, + refreshErrors: 0 + } + }); + this.configure(config); + } + /** + * Get cache performance metrics. + */ + get metrics() { + return { ...this._metrics }; + } + /** + * Get total cache requests (hits + misses). + */ + get totalRequests() { + return this._metrics.hits + this._metrics.misses; + } + /** + * Get cache hit rate (0.0 to 1.0). + */ + get hitRate() { + const total = this.totalRequests; + return total > 0 ? this._metrics.hits / total : 0; + } + /** + * Reset all metrics to zero. + */ + resetMetrics() { + this._metrics = { + hits: 0, + misses: 0, + refreshes: 0, + refreshErrors: 0 + }; + } + /** + * Get a value from cache. + * + * Returns the cached value or undefined if not found. + * Stale entries are still returned (background refresh handles updates). + */ + get(key, refreshFunc) { + if (this.maxSize === 0) return; + const entry = this.cache.get(key); + if (!entry) { + this._metrics.misses += 1; + return; + } + this.cache.delete(key); + this.cache.set(key, { + ...entry, + refreshFunc + }); + this._metrics.hits += 1; + return entry.value; + } + /** + * Set a value in the cache. + */ + set(key, value, refreshFunc) { + if (this.maxSize === 0) return; + if (this.refreshTimer === void 0) this.startRefreshLoop(); + if (!this.cache.has(key) && this.cache.size >= this.maxSize) { + const oldestKey = this.cache.keys().next().value; + if (oldestKey !== void 0) this.cache.delete(oldestKey); + } + const entry = { + value, + createdAt: Date.now(), + refreshFunc + }; + this.cache.delete(key); + this.cache.set(key, entry); + } + /** + * Remove a specific entry from cache. + */ + invalidate(key) { + this.cache.delete(key); + } + /** + * Clear all cache entries. + */ + clear() { + this.cache.clear(); + } + /** + * Get the number of entries in the cache. + */ + get size() { + return this.cache.size; + } + /** + * Stop background refresh. + * Should be called when the client is being cleaned up. + */ + stop() { + if (this.refreshTimer) { + clearInterval(this.refreshTimer); + this.refreshTimer = void 0; + } + } + /** + * Dump cache contents to a JSON file for offline use. + */ + dump(filePath) { + const entries = {}; + for (const [key, entry] of this.cache.entries()) entries[key] = entry.value; + const dir = path$2.dirname(filePath); + if (!existsSync(dir)) mkdirSync(dir); + const tempPath = `${filePath}.tmp`; + try { + writeFileSync(tempPath, JSON.stringify({ entries }, null, 2)); + renameSync(tempPath, filePath); + } catch (e) { + if (existsSync(tempPath)) unlinkSync(tempPath); + throw e; + } + } + /** + * Load cache contents from a JSON file. + * + * Loaded entries get a fresh TTL starting from load time. + * + * @returns Number of entries loaded. + */ + load(filePath) { + if (!existsSync(filePath)) return 0; + let entries; + try { + const content = readFileSync(filePath); + entries = JSON.parse(content).entries ?? null; + } catch { + return 0; + } + if (!entries) return 0; + let loaded = 0; + const now = Date.now(); + for (const [key, value] of Object.entries(entries)) { + if (this.cache.size >= this.maxSize) break; + const entry = { + value, + createdAt: now + }; + this.cache.set(key, entry); + loaded += 1; + } + return loaded; + } + /** + * Start the background refresh loop. + */ + startRefreshLoop() { + this.stop(); + if (this.ttlSeconds !== null) { + this.refreshTimer = setInterval(() => { + this.refreshStaleEntries().catch((e) => { + console.warn("Unexpected error in cache refresh loop:", e); + }); + }, this.refreshIntervalSeconds * 1e3); + if (this.refreshTimer.unref) this.refreshTimer.unref(); + } + } + /** + * Get list of stale cache keys. + */ + getStaleEntries() { + const staleEntries = []; + for (const [key, value] of this.cache.entries()) if (isStale(value, this.ttlSeconds)) staleEntries.push([key, value]); + return staleEntries; + } + /** + * Check for stale entries and refresh them. + */ + async refreshStaleEntries() { + const staleEntries = this.getStaleEntries(); + if (staleEntries.length === 0) return; + for (const [key, value] of staleEntries) if (value.refreshFunc !== void 0) try { + const newValue = await value.refreshFunc(); + this.set(key, newValue, value.refreshFunc); + this._metrics.refreshes += 1; + } catch (e) { + this._metrics.refreshErrors += 1; + console.warn(`Failed to refresh cache entry ${key}:`, e); + } + } + configure(config) { + this.stop(); + this.refreshIntervalSeconds = config.refreshIntervalSeconds ?? 60; + this.maxSize = config.maxSize ?? 100; + this.ttlSeconds = config.ttlSeconds ?? 300; + } +}; +/** +* Global singleton instance of PromptCache. +* Use configureGlobalPromptCache(), enableGlobalPromptCache(), or disableGlobalPromptCache() instead. +*/ +var promptCacheSingleton = new PromptCache(); +//#endregion +//#region node_modules/langsmith/dist/index.js +var __version__ = "0.7.17"; +//#endregion +//#region node_modules/langsmith/dist/utils/env.js +var globalEnv; +var isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +var isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +var isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom"); +var isDeno = () => typeof globalThis.Deno !== "undefined"; +var isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno(); +var getEnv = () => { + if (globalEnv) return globalEnv; + if (typeof Bun !== "undefined") globalEnv = "bun"; + else if (isBrowser()) globalEnv = "browser"; + else if (isNode()) globalEnv = "node"; + else if (isWebWorker()) globalEnv = "webworker"; + else if (isJsDom()) globalEnv = "jsdom"; + else if (isDeno()) globalEnv = "deno"; + else globalEnv = "other"; + return globalEnv; +}; +var runtimeEnvironment; +function getRuntimeEnvironment() { + if (runtimeEnvironment === void 0) runtimeEnvironment = { + library: "langsmith", + runtime: getEnv(), + sdk: "langsmith-js", + sdk_version: __version__, + ...getShas() + }; + return runtimeEnvironment; +} +/** +* Retrieves the LangSmith-specific metadata from the current runtime environment. +* +* @returns {Record} +* - A record of LangSmith-specific metadata environment variables. +*/ +function getLangSmithEnvVarsMetadata() { + const allEnvVars = getLangSmithEnvironmentVariables(); + const envVars = {}; + const excluded = [ + "LANGCHAIN_API_KEY", + "LANGCHAIN_ENDPOINT", + "LANGCHAIN_TRACING_V2", + "LANGCHAIN_PROJECT", + "LANGCHAIN_SESSION", + "LANGSMITH_API_KEY", + "LANGSMITH_ENDPOINT", + "LANGSMITH_TRACING_V2", + "LANGSMITH_CONFIG_FILE", + "LANGSMITH_PROJECT", + "LANGSMITH_SESSION" + ]; + for (const [key, value] of Object.entries(allEnvVars)) if (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; +} +/** +* Retrieves only the LangChain/LangSmith-prefixed environment variables from the current runtime environment. +* This is more efficient than copying all environment variables. +* +* @returns {Record} +* - A record of LangChain/LangSmith environment variables. +*/ +function getLangSmithEnvironmentVariables() { + const envVars = {}; + try { + if (typeof process !== "undefined" && process.env) { + for (const [key, value] of Object.entries(process.env)) if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && value != null) if ((key.toLowerCase().includes("key") || key.toLowerCase().includes("secret") || key.toLowerCase().includes("token")) && typeof value === "string") envVars[key] = value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2); + else envVars[key] = value; + } + } catch (_e) {} + return envVars; +} +function getEnvironmentVariable(name) { + try { + return typeof process !== "undefined" ? process.env?.[name] : void 0; + } catch (_e) { + return; + } +} +function getLangSmithEnvironmentVariable(name) { + return getEnvironmentVariable(`LANGSMITH_${name}`) || getEnvironmentVariable(`LANGCHAIN_${name}`); +} +var cachedCommitSHAs; +/** +* Get the Git commit SHA from common environment variables +* used by different CI/CD platforms. +* @returns {string | undefined} The Git commit SHA or undefined if not found. +*/ +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 = getEnvironmentVariable(env); + if (envVar !== void 0) shas[env] = envVar; + } + cachedCommitSHAs = shas; + return shas; +} +function getOtelEnabled() { + return getEnvironmentVariable("OTEL_ENABLED") === "true" || getLangSmithEnvironmentVariable("OTEL_ENABLED") === "true"; +} +var _VALID_TRACING_MODES = /* @__PURE__ */ new Set(["langsmith", "otel"]); +/** +* Resolve the effective tracing mode from an explicit config value and +* environment variables. +* +* Priority: explicit argument > `LANGSMITH_TRACING_MODE` env var > +* legacy `OTEL_ENABLED` / `LANGSMITH_OTEL_ENABLED` env vars > `"langsmith"`. +*/ +function resolveTracingMode(configValue) { + if (configValue !== void 0) return configValue; + const envMode = getLangSmithEnvironmentVariable("TRACING_MODE"); + if (envMode !== void 0 && envMode !== "") { + const lower = envMode.toLowerCase(); + if (!_VALID_TRACING_MODES.has(lower)) throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(envMode)}. Must be one of: ${[..._VALID_TRACING_MODES].sort().join(", ")}`); + if (getOtelEnabled()) console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."); + return lower; + } + if (getOtelEnabled()) return "otel"; + return "langsmith"; +} +//#endregion +//#region node_modules/langsmith/dist/singletons/otel.js +var MockTracer = class { + constructor() { + Object.defineProperty(this, "hasWarned", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + startActiveSpan(_name, ...args) { + if (!this.hasWarned && resolveTracingMode() === "otel") { + console.warn("OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from \"langsmith/experimental/otel/setup\";\ninitializeOTEL();\n```\nat the beginning of your code."); + this.hasWarned = true; + } + let fn; + if (args.length === 1 && typeof args[0] === "function") fn = args[0]; + else if (args.length === 2 && typeof args[1] === "function") fn = args[1]; + else if (args.length === 3 && typeof args[2] === "function") fn = args[2]; + if (typeof fn === "function") return fn(); + } +}; +var MockOTELTrace = class { + constructor() { + Object.defineProperty(this, "mockTracer", { + enumerable: true, + configurable: true, + writable: true, + value: new MockTracer() + }); + } + getTracer(_name, _version) { + return this.mockTracer; + } + getActiveSpan() {} + setSpan(context, _span) { + return context; + } + getSpan(_context) {} + setSpanContext(context, _spanContext) { + return context; + } + getTracerProvider() {} + setGlobalTracerProvider(_tracerProvider) { + return false; + } +}; +var MockOTELContext = class { + active() { + return {}; + } + with(_context, fn) { + return fn(); + } +}; +var OTEL_TRACE_KEY = Symbol.for("ls:otel_trace"); +var OTEL_CONTEXT_KEY = Symbol.for("ls:otel_context"); +var OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY = Symbol.for("ls:otel_get_default_otlp_tracer_provider"); +var mockOTELTrace = new MockOTELTrace(); +var mockOTELContext = new MockOTELContext(); +var OTELProvider = class { + getTraceInstance() { + return globalThis[OTEL_TRACE_KEY] ?? mockOTELTrace; + } + getContextInstance() { + return globalThis[OTEL_CONTEXT_KEY] ?? mockOTELContext; + } + initializeGlobalInstances(otel) { + if (globalThis[OTEL_TRACE_KEY] === void 0) globalThis[OTEL_TRACE_KEY] = otel.trace; + if (globalThis[OTEL_CONTEXT_KEY] === void 0) globalThis[OTEL_CONTEXT_KEY] = otel.context; + } + setDefaultOTLPTracerComponents(components) { + globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] = components; + } + getDefaultOTLPTracerComponents() { + return globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] ?? void 0; + } +}; +var OTELProviderSingleton = new OTELProvider(); +/** +* Get the current OTEL trace instance. +* Returns a mock implementation if OTEL is not available. +*/ +function getOTELTrace() { + return OTELProviderSingleton.getTraceInstance(); +} +/** +* Get the current OTEL context instance. +* Returns a mock implementation if OTEL is not available. +*/ +function getOTELContext() { + return OTELProviderSingleton.getContextInstance(); +} +/** +* Get the default OTLP tracer provider instance. +* Returns undefined if not set. +*/ +function getDefaultOTLPTracerComponents() { + return OTELProviderSingleton.getDefaultOTLPTracerComponents(); +} +//#endregion +//#region node_modules/langsmith/dist/experimental/otel/translator.js +var WELL_KNOWN_OPERATION_NAMES = { + llm: "chat", + tool: "execute_tool", + retriever: "embeddings", + embedding: "embeddings", + prompt: "chat" +}; +function getOperationName(runType) { + return WELL_KNOWN_OPERATION_NAMES[runType] || runType; +} +function isPrimitive(value) { + return typeof value === "string" || typeof value === "number" || typeof value === "boolean"; +} +var LangSmithToOTELTranslator = class { + constructor() { + Object.defineProperty(this, "spans", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + } + exportBatch(operations, otelContextMap) { + for (const op of operations) try { + if (!op.run) continue; + if (op.operation === "post") { + const span = this.createSpanForRun(op, op.run, otelContextMap.get(op.id)); + if (span && !op.run.end_time) this.spans.set(op.id, span); + } else this.updateSpanForRun(op, op.run); + } catch (e) { + console.error(`Error processing operation ${op.id}:`, e); + } + } + createSpanForRun(op, runInfo, otelContext) { + const activeSpan = otelContext && getOTELTrace().getSpan(otelContext); + if (!activeSpan) return; + try { + return this.finishSpanSetup(activeSpan, runInfo, op); + } catch (e) { + console.error(`Failed to create span for run ${op.id}:`, e); + return; + } + } + finishSpanSetup(span, runInfo, op) { + this.setSpanAttributes(span, runInfo, op); + if (runInfo.error) { + span.setStatus({ code: 2 }); + span.recordException(new Error(runInfo.error)); + } else span.setStatus({ code: 1 }); + if (runInfo.end_time) span.end(new Date(runInfo.end_time)); + return span; + } + updateSpanForRun(op, runInfo) { + try { + const span = this.spans.get(op.id); + if (!span) { + console.debug(`No span found for run ${op.id} during update`); + return; + } + this.setSpanAttributes(span, runInfo, op); + if (runInfo.error) { + span.setStatus({ code: 2 }); + span.recordException(new Error(runInfo.error)); + } else span.setStatus({ code: 1 }); + const endTime = runInfo.end_time; + if (endTime) { + span.end(new Date(endTime)); + this.spans.delete(op.id); + } + } catch (e) { + console.error(`Failed to update span for run ${op.id}:`, e); + } + } + extractModelName(runInfo) { + if (runInfo.extra?.metadata) { + const metadata = runInfo.extra.metadata; + if (metadata.ls_model_name) return metadata.ls_model_name; + if (metadata.invocation_params) { + const invocationParams = metadata.invocation_params; + if (invocationParams.model) return invocationParams.model; + else if (invocationParams.model_name) return invocationParams.model_name; + } + } + } + setSpanAttributes(span, runInfo, op) { + if ("run_type" in runInfo && runInfo.run_type) { + span.setAttribute(LANGSMITH_RUN_TYPE, runInfo.run_type); + const operationName = getOperationName(runInfo.run_type || "chain"); + span.setAttribute(GEN_AI_OPERATION_NAME, operationName); + } + if ("name" in runInfo && runInfo.name) span.setAttribute(LANGSMITH_NAME, runInfo.name); + if ("session_id" in runInfo && runInfo.session_id) span.setAttribute(LANGSMITH_SESSION_ID, runInfo.session_id); + if ("session_name" in runInfo && runInfo.session_name) span.setAttribute(LANGSMITH_SESSION_NAME, runInfo.session_name); + this.setGenAiSystem(span, runInfo); + const modelName = this.extractModelName(runInfo); + if (modelName) span.setAttribute(GEN_AI_REQUEST_MODEL, modelName); + if (runInfo.extra?.metadata?.usage_metadata && typeof runInfo.extra.metadata.usage_metadata === "object") span.setAttribute(LANGSMITH_USAGE_METADATA, JSON.stringify(runInfo.extra.metadata.usage_metadata)); + if ("prompt_tokens" in runInfo && typeof runInfo.prompt_tokens === "number") span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, runInfo.prompt_tokens); + if ("completion_tokens" in runInfo && typeof runInfo.completion_tokens === "number") span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, runInfo.completion_tokens); + if ("total_tokens" in runInfo && typeof runInfo.total_tokens === "number") span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, runInfo.total_tokens); + this.setInvocationParameters(span, runInfo); + const metadata = runInfo.extra?.metadata || {}; + for (const [key, value] of Object.entries(metadata)) if (value !== null && value !== void 0) span.setAttribute(`${LANGSMITH_METADATA}.${key}`, isPrimitive(value) ? String(value) : JSON.stringify(value)); + const tags = runInfo.tags; + if (tags && Array.isArray(tags)) span.setAttribute(LANGSMITH_TAGS, tags.join(", ")); + else if (tags) span.setAttribute(LANGSMITH_TAGS, String(tags)); + if ("serialized" in runInfo && typeof runInfo.serialized === "object") { + const serialized = runInfo.serialized; + if (serialized.name) span.setAttribute(GEN_AI_SERIALIZED_NAME, String(serialized.name)); + if (serialized.signature) span.setAttribute(GEN_AI_SERIALIZED_SIGNATURE, String(serialized.signature)); + if (serialized.doc) span.setAttribute(GEN_AI_SERIALIZED_DOC, String(serialized.doc)); + } + this.setIOAttributes(span, op); + } + setGenAiSystem(span, runInfo) { + let system = "langchain"; + const modelName = this.extractModelName(runInfo); + if (modelName) { + const modelLower = modelName.toLowerCase(); + if (modelLower.includes("anthropic") || modelLower.startsWith("claude")) system = "anthropic"; + else if (modelLower.includes("bedrock")) system = "aws.bedrock"; + else if (modelLower.includes("azure") && modelLower.includes("openai")) system = "az.ai.openai"; + else if (modelLower.includes("azure") && modelLower.includes("inference")) system = "az.ai.inference"; + else if (modelLower.includes("cohere")) system = "cohere"; + else if (modelLower.includes("deepseek")) system = "deepseek"; + else if (modelLower.includes("gemini")) system = "gemini"; + else if (modelLower.includes("groq")) system = "groq"; + else if (modelLower.includes("watson") || modelLower.includes("ibm")) system = "ibm.watsonx.ai"; + else if (modelLower.includes("mistral")) system = "mistral_ai"; + else if (modelLower.includes("gpt") || modelLower.includes("openai")) system = "openai"; + else if (modelLower.includes("perplexity") || modelLower.includes("sonar")) system = "perplexity"; + else if (modelLower.includes("vertex")) system = "vertex_ai"; + else if (modelLower.includes("xai") || modelLower.includes("grok")) system = "xai"; + } + span.setAttribute(GEN_AI_SYSTEM, system); + } + setInvocationParameters(span, runInfo) { + if (!runInfo.extra?.metadata?.invocation_params) return; + const invocationParams = runInfo.extra.metadata.invocation_params; + if (invocationParams.max_tokens !== void 0) span.setAttribute(GEN_AI_REQUEST_MAX_TOKENS, invocationParams.max_tokens); + if (invocationParams.temperature !== void 0) span.setAttribute(GEN_AI_REQUEST_TEMPERATURE, invocationParams.temperature); + if (invocationParams.top_p !== void 0) span.setAttribute(GEN_AI_REQUEST_TOP_P, invocationParams.top_p); + if (invocationParams.frequency_penalty !== void 0) span.setAttribute(GEN_AI_REQUEST_FREQUENCY_PENALTY, invocationParams.frequency_penalty); + if (invocationParams.presence_penalty !== void 0) span.setAttribute(GEN_AI_REQUEST_PRESENCE_PENALTY, invocationParams.presence_penalty); + } + setIOAttributes(span, op) { + if (op.run.inputs) try { + const inputs = op.run.inputs; + if (typeof inputs === "object" && inputs !== null) { + if (inputs.model && Array.isArray(inputs.messages)) span.setAttribute(GEN_AI_REQUEST_MODEL, inputs.model); + if (inputs.stream !== void 0) span.setAttribute(LANGSMITH_REQUEST_STREAMING, inputs.stream); + if (inputs.extra_headers) span.setAttribute(LANGSMITH_REQUEST_HEADERS, JSON.stringify(inputs.extra_headers)); + if (inputs.extra_query) span.setAttribute(GEN_AI_REQUEST_EXTRA_QUERY, JSON.stringify(inputs.extra_query)); + if (inputs.extra_body) span.setAttribute(GEN_AI_REQUEST_EXTRA_BODY, JSON.stringify(inputs.extra_body)); + } + span.setAttribute(GENAI_PROMPT, JSON.stringify(inputs)); + } catch (e) { + console.debug(`Failed to process inputs for run ${op.id}`, e); + } + if (op.run.outputs) try { + const outputs = op.run.outputs; + const tokenUsage = this.getUnifiedRunTokens(outputs); + if (tokenUsage) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, tokenUsage[0]); + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, tokenUsage[1]); + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, tokenUsage[0] + tokenUsage[1]); + } + if (outputs && typeof outputs === "object") { + if (outputs.model) span.setAttribute(GEN_AI_RESPONSE_MODEL, String(outputs.model)); + if (outputs.id) span.setAttribute(GEN_AI_RESPONSE_ID, outputs.id); + if (outputs.choices && Array.isArray(outputs.choices)) { + const finishReasons = outputs.choices.map((choice) => choice.finish_reason).filter((reason) => reason).map(String); + if (finishReasons.length > 0) span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, finishReasons.join(", ")); + } + if (outputs.service_tier) span.setAttribute(GEN_AI_RESPONSE_SERVICE_TIER, outputs.service_tier); + if (outputs.system_fingerprint) span.setAttribute(GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, outputs.system_fingerprint); + if (outputs.usage_metadata && typeof outputs.usage_metadata === "object") { + const usageMetadata = outputs.usage_metadata; + span.setAttribute(LANGSMITH_USAGE_METADATA, JSON.stringify(usageMetadata)); + if (usageMetadata.input_token_details) span.setAttribute(GEN_AI_USAGE_INPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.input_token_details)); + if (usageMetadata.output_token_details) span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.output_token_details)); + } + } + span.setAttribute(GENAI_COMPLETION, JSON.stringify(outputs)); + } catch (e) { + console.debug(`Failed to process outputs for run ${op.id}`, e); + } + } + getUnifiedRunTokens(outputs) { + if (!outputs) return null; + let tokenUsage = this.extractUnifiedRunTokens(outputs.usage_metadata); + if (tokenUsage) return tokenUsage; + const keys = Object.keys(outputs); + for (const key of keys) { + const haystack = outputs[key]; + if (!haystack || typeof haystack !== "object") continue; + tokenUsage = this.extractUnifiedRunTokens(haystack.usage_metadata); + if (tokenUsage) return tokenUsage; + if (haystack.lc === 1 && haystack.kwargs && typeof haystack.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(haystack.kwargs.usage_metadata); + if (tokenUsage) return tokenUsage; + } + } + const generations = outputs.generations || []; + if (!Array.isArray(generations)) return null; + const flatGenerations = Array.isArray(generations[0]) ? generations.flat() : generations; + for (const generation of flatGenerations) if (typeof generation === "object" && generation.message && typeof generation.message === "object" && generation.message.kwargs && typeof generation.message.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(generation.message.kwargs.usage_metadata); + if (tokenUsage) return tokenUsage; + } + return null; + } + extractUnifiedRunTokens(outputs) { + if (!outputs || typeof outputs !== "object") return null; + if (typeof outputs.input_tokens !== "number" || typeof outputs.output_tokens !== "number") return null; + return [outputs.input_tokens, outputs.output_tokens]; + } +}; +//#endregion +//#region node_modules/langsmith/dist/utils/is-network-error/index.js +var objectToString$1 = Object.prototype.toString; +var isError$1 = (value) => objectToString$1.call(value) === "[object Error]"; +var errorMessages$1 = /* @__PURE__ */ new Set([ + "network error", + "Failed to fetch", + "NetworkError when attempting to fetch resource.", + "The Internet connection appears to be offline.", + "Network request failed", + "fetch failed", + "terminated", + " A network error occurred.", + "Network connection lost" +]); +function isNetworkError$1(error) { + if (!(error && isError$1(error) && error.name === "TypeError" && typeof error.message === "string")) return false; + const { message, stack } = error; + if (message === "Load failed") return stack === void 0 || "__sentry_captured__" in error; + if (message.startsWith("error sending request for url")) return true; + return errorMessages$1.has(message); +} +//#endregion +//#region node_modules/langsmith/dist/utils/p-retry/index.js +function validateRetries$1(retries) { + if (typeof retries === "number") { + if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number."); + if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); + } else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity."); +} +function validateNumberOption$1(name, value, { min = 0, allowInfinity = false } = {}) { + if (value === void 0) return; + if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); + if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`); + if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`); +} +var AbortError$1 = 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; + } +}; +function calculateDelay$1(retriesConsumed, options) { + const attempt = Math.max(1, retriesConsumed + 1); + const random = options.randomize ? Math.random() + 1 : 1; + let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); + timeout = Math.min(timeout, options.maxTimeout); + return timeout; +} +function calculateRemainingTime$1(start, max) { + if (!Number.isFinite(max)) return max; + return max - (performance.now() - start); +} +async function onAttemptFailure$1({ error, attemptNumber, retriesConsumed, startTime, options }) { + const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`); + if (normalizedError instanceof AbortError$1) throw normalizedError.originalError; + const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries; + const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; + const context = Object.freeze({ + error: normalizedError, + attemptNumber, + retriesLeft, + retriesConsumed + }); + await options.onFailedAttempt(context); + if (calculateRemainingTime$1(startTime, maxRetryTime) <= 0) throw normalizedError; + const consumeRetry = await options.shouldConsumeRetry(context); + const remainingTime = calculateRemainingTime$1(startTime, maxRetryTime); + if (remainingTime <= 0 || retriesLeft <= 0) throw normalizedError; + if (normalizedError instanceof TypeError && !isNetworkError$1(normalizedError)) { + if (consumeRetry) throw normalizedError; + options.signal?.throwIfAborted(); + return false; + } + if (!await options.shouldRetry(context)) throw normalizedError; + if (!consumeRetry) { + options.signal?.throwIfAborted(); + return false; + } + const delayTime = calculateDelay$1(retriesConsumed, options); + const finalDelay = Math.min(delayTime, remainingTime); + if (finalDelay > 0) await new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(timeoutToken); + options.signal?.removeEventListener("abort", onAbort); + reject(options.signal.reason); + }; + const timeoutToken = setTimeout(() => { + options.signal?.removeEventListener("abort", onAbort); + resolve(); + }, finalDelay); + if (options.unref) timeoutToken.unref?.(); + options.signal?.addEventListener("abort", onAbort, { once: true }); + }); + options.signal?.throwIfAborted(); + return true; +} +async function pRetry$1(input, options = {}) { + options = { ...options }; + validateRetries$1(options.retries); + if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); + options.retries ??= 10; + options.factor ??= 2; + options.minTimeout ??= 1e3; + options.maxTimeout ??= Number.POSITIVE_INFINITY; + options.maxRetryTime ??= Number.POSITIVE_INFINITY; + options.randomize ??= false; + options.onFailedAttempt ??= () => {}; + options.shouldRetry ??= () => true; + options.shouldConsumeRetry ??= () => true; + validateNumberOption$1("factor", options.factor, { + min: 0, + allowInfinity: false + }); + validateNumberOption$1("minTimeout", options.minTimeout, { + min: 0, + allowInfinity: false + }); + validateNumberOption$1("maxTimeout", options.maxTimeout, { + min: 0, + allowInfinity: true + }); + validateNumberOption$1("maxRetryTime", options.maxRetryTime, { + min: 0, + allowInfinity: true + }); + if (!(options.factor > 0)) options.factor = 1; + options.signal?.throwIfAborted(); + let attemptNumber = 0; + let retriesConsumed = 0; + const startTime = performance.now(); + while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { + attemptNumber++; + try { + options.signal?.throwIfAborted(); + const result = await input(attemptNumber); + options.signal?.throwIfAborted(); + return result; + } catch (error) { + if (await onAttemptFailure$1({ + error, + attemptNumber, + retriesConsumed, + startTime, + options + })) retriesConsumed++; + } + } + throw new Error("Retry attempts exhausted without throwing an error."); +} +//#endregion +//#region node_modules/eventemitter3/index.js +var require_eventemitter3 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var has = Object.prototype.hasOwnProperty; + var prefix = "~"; + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + if (Object.create) { + Events.prototype = Object.create(null); + if (!new Events().__proto__) prefix = false; + } + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, 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 + event : event; + 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; + } + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [], events, name; + if (this._eventsCount === 0) return names; + for (name in events = this._events) if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + if (Object.getOwnPropertySymbols) return names.concat(Object.getOwnPropertySymbols(events)); + return names; + }; + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) ee[i] = handlers[i].fn; + return ee; + }; + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt], len = arguments.length, args, i; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, 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 (i = 1, args = new Array(len - 1); i < len; i++) args[i - 1] = arguments[i]; + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); + switch (len) { + case 1: + listeners[i].fn.call(listeners[i].context); + break; + case 2: + listeners[i].fn.call(listeners[i].context, a1); + break; + case 3: + listeners[i].fn.call(listeners[i].context, a1, a2); + break; + case 4: + listeners[i].fn.call(listeners[i].context, a1, a2, a3); + break; + default: + if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) args[j - 1] = arguments[j]; + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + return true; + }; + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + 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 i = 0, events = [], length = listeners.length; i < length; i++) if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) events.push(listeners[i]); + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + return this; + }; + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + 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 ("undefined" !== typeof module) module.exports = EventEmitter; +})); +//#endregion +//#region node_modules/p-finally/index.js +var require_p_finally = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.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; + })); + }; +})); +//#endregion +//#region node_modules/p-timeout/index.js +var require_p_timeout = /* @__PURE__ */ __commonJSMin(((exports, module) => { + 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); + }); + }); + module.exports = pTimeout; + module.exports.default = pTimeout; + module.exports.TimeoutError = TimeoutError; +})); +//#endregion +//#region node_modules/p-queue/dist/lower-bound.js +var require_lower_bound = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__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; + } + exports.default = lowerBound; +})); +//#endregion +//#region node_modules/p-queue/dist/priority-queue.js +var require_priority_queue = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__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 index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); + this._queue.splice(index, 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; + } + }; + exports.default = PriorityQueue; +})); +//#endregion +//#region node_modules/langsmith/dist/utils/p-queue.js +var import_dist = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__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(); + /** + Promise queue with concurrency control. + */ + var PQueue = class extends EventEmitter { + constructor(options) { + var _a, _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 = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.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(); + } + /** + Executes all queued functions until it reaches the limit. + */ + _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(); + } + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + resolve(await (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); + }))); + } catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit("add"); + }); + } + /** + Same as `.add()`, but accepts an array of sync or async functions. + + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); + } + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) return this; + this._isPaused = false; + this._processQueue(); + return this; + } + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; + } + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); + } + /** + Can be called multiple times. Useful if you for example add additional items at a later time. + + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + if (this._queue.size === 0) return; + return new Promise((resolve) => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + if (this._pendingCount === 0 && this._queue.size === 0) return; + return new Promise((resolve) => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + Size of the queue. + */ + get size() { + return this._queue.size; + } + /** + Size of the queue, filtered by the given options. + + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + return this._queue.filter(options).length; + } + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; + } + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; + } + }; + exports.default = PQueue; +})))(), 1); +var PQueue = "default" in import_dist.default ? import_dist.default.default : import_dist.default; +//#endregion +//#region node_modules/langsmith/dist/utils/async_caller.js +var STATUS_RETRYABLE = [ + 408, + 425, + 429, + 500, + 502, + 503, + 504 +]; +/** +* A class that can be used to make async calls with concurrency and retry logic. +* +* This is useful for making calls to any kind of "expensive" external resource, +* be it because it's rate-limited, subject to network issues, etc. +* +* Concurrent calls are limited by the `maxConcurrency` parameter, which defaults +* to `Infinity`. This means that by default, all calls will be made in parallel. +* +* Retries are limited by the `maxRetries` parameter, which defaults to 6. This +* means that by default, each call will be retried up to 6 times, with an +* exponential backoff between each attempt. +*/ +var AsyncCaller$1 = 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, "maxQueueSizeBytes", { + 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 + }); + Object.defineProperty(this, "queueSizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.maxQueueSizeBytes = params.maxQueueSizeBytes; + this.queue = new PQueue({ concurrency: this.maxConcurrency }); + this.onFailedResponseHook = params?.onFailedResponseHook; + } + call(callable, ...args) { + return this.callWithOptions({}, callable, ...args); + } + callWithOptions(options, callable, ...args) { + const sizeBytes = options.sizeBytes ?? 0; + if (this.maxQueueSizeBytes !== void 0 && sizeBytes > 0 && this.queueSizeBytes + sizeBytes > this.maxQueueSizeBytes) return Promise.reject(/* @__PURE__ */ new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${sizeBytes} bytes.`)); + if (sizeBytes > 0) this.queueSizeBytes += sizeBytes; + const onFailedResponseHook = this.onFailedResponseHook; + let promise = this.queue.add(() => pRetry$1(() => callable(...args).catch((error) => { + if (error instanceof Error) throw error; + else throw new Error(error); + }), { + async onFailedAttempt({ error }) { + if (typeof error !== "object" || error == null) throw error; + const errorMessage = "message" in error && typeof error.message === "string" ? error.message : void 0; + if (errorMessage?.startsWith("Cancel") || errorMessage?.startsWith("TimeoutError") || errorMessage?.startsWith("AbortError")) throw error; + if ("name" in error && error.name === "TimeoutError") throw error; + if ("code" in error && error.code === "ECONNABORTED") throw error; + const response = "response" in error ? error.response : void 0; + if (onFailedResponseHook) { + if (await onFailedResponseHook(response)) return; + } + const status = response?.status ?? ("status" in error ? error.status : void 0); + if (status != null && (typeof status === "number" || typeof status === "string") && !STATUS_RETRYABLE.includes(+status)) throw error; + }, + retries: this.maxRetries, + randomize: true + }), { throwOnTimeout: true }); + if (sizeBytes > 0) promise = promise.finally(() => { + this.queueSizeBytes -= sizeBytes; + }); + if (options.signal) return Promise.race([promise, new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(/* @__PURE__ */ new Error("AbortError")); + }); + })]); + return promise; + } +}; +//#endregion +//#region 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; +} +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/utils/uuid.js +/** +* https://stackoverflow.com/a/2117523 +*/ +var uuid4 = function() { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); + } + const u8 = /* @__PURE__ */ new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/errors.js +function isAbortError(err) { + return typeof err === "object" && err !== null && ("name" in err && err.name === "AbortError" || "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError = (err) => { + if (err instanceof Error) return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) error.stack = err.stack; + if (err.cause && !error.cause) error.cause = err.cause; + if (err.name) error.name = err.name; + return error; + } + } catch {} + try { + return new Error(JSON.stringify(err)); + } catch {} + } + return new Error(err); +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/core/error.js +var LangsmithError = class extends Error {}; +var APIError = class APIError extends LangsmithError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + /** HTTP status for the response that caused the error */ + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** HTTP headers for the response that caused the error */ + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** JSON body of the response that caused the error */ + Object.defineProperty(this, "error", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.status = status; + this.headers = headers; + this.error = error; + } + 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 || !headers) return new APIConnectionError({ + message, + cause: castToError(errorResponse) + }); + const error = errorResponse; + 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); + } +}; +var APIUserAbortError = class extends APIError { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } +}; +var APIConnectionError = class extends APIError { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) this.cause = cause; + } +}; +var APIConnectionTimeoutError = class extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +var BadRequestError = class extends APIError {}; +var AuthenticationError = class extends APIError {}; +var PermissionDeniedError = class extends APIError {}; +var NotFoundError = class extends APIError {}; +var ConflictError = class extends APIError {}; +var UnprocessableEntityError = class extends APIError {}; +var RateLimitError = class extends APIError {}; +var InternalServerError = class extends APIError {}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/utils/values.js +var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +var isArray = (val) => (isArray = Array.isArray, isArray(val)); +var isReadonlyArray = isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +function maybeObj(x) { + if (typeof x !== "object") return {}; + return x ?? {}; +} +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); +} +var validatePositiveInteger = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) throw new LangsmithError(`${name} must be an integer`); + if (n < 0) throw new LangsmithError(`${name} must be a positive integer`); + return n; +}; +var safeJSON = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return; + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/utils/sleep.js +var sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/version.js +var VERSION = "0.0.1"; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/detect-platform.js +/** +* Note this does not detect 'browser'; for that, use getBrowserInfo(). +*/ +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) return "deno"; + if (typeof EdgeRuntime !== "undefined") return "edge"; + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") return "node"; + return "unknown"; +} +var getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") 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": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + 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": globalThis.process.version + }; + if (detectedPlatform === "node") return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + 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" + }; +}; +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) return null; + for (const { key, pattern } of [ + { + 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/ + } + ]) { + const match = pattern.exec(navigator.userAgent); + if (match) return { + browser: key, + version: `${match[1] || 0}.${match[2] || 0}.${match[3] || 0}` + }; + } + return null; +} +var 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"; +}; +var 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"; +}; +var _platformHeaders; +var getPlatformHeaders = () => { + return _platformHeaders ??= getPlatformProperties(); +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/shims.js +function getDefaultFetch() { + if (typeof fetch !== "undefined") return fetch; + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Langsmith({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() {}, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) controller.close(); + else controller.enqueue(value); + }, + async cancel() { + await iter.return?.(); + } + }); +} +/** +* Cancels a ReadableStream we don't need to consume. +* See https://undici.nodejs.org/#/?id=garbage-collection +*/ +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== "object") return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/request-options.js +var FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { "content-type": "application/json" }, + body: JSON.stringify(body) + }; +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/qs/formats.js +var default_format = "RFC3986"; +var default_formatter = (v) => String(v); +var formatters = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/qs/utils.js +var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); +var hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + return array; +})(); +var limit = 1024; +var encode = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) return str; + let string = str; + if (typeof str === "symbol") string = Symbol.prototype.toString.call(str); + else if (typeof str !== "string") string = String(str); + if (charset === "iso-8859-1") return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + let out = ""; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === "RFC1738" && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hex_table[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + } + out += arr.join(""); + } + return out; +}; +function is_buffer(obj) { + if (!obj || typeof obj !== "object") return false; + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val, fn) { + if (isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) mapped.push(fn(val[i])); + return mapped; + } + return fn(val); +} +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/qs/stringify.js +var array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } +}; +var push_to_array = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ??= Function.prototype.call.bind(Date.prototype.toISOString))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") if (pos === step) throw new RangeError("Cyclic object value"); + else find_flag = true; + if (typeof tmp_sc.get(sentinel) === "undefined") step = 0; + } + if (typeof filter === "function") obj = filter(prefix, obj); + else if (obj instanceof Date) obj = serializeDate?.(obj); + else if (generateArrayPrefix === "comma" && isArray(obj)) obj = maybe_map(obj, function(value) { + if (value instanceof Date) return serializeDate?.(value); + return value; + }); + if (obj === null) { + if (strictNullHandling) return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix; + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + return [formatter?.(key_value) + "=" + formatter?.(encoder(obj, defaults.encoder, charset, "value", format))]; + } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") return values; + let obj_keys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + if (encodeValuesOnly && encoder) obj = maybe_map(obj, encoder); + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) obj_keys = filter; + else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray(obj) && obj.length === 0) return adjusted_prefix + "[]"; + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]; + if (skipNulls && value === null) continue; + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); + } + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") throw new TypeError("Encoder has to be a function."); + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + let format = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) throw new TypeError("Unknown format option provided."); + format = opts.format; + } + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) filter = opts.filter; + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) arrayFormat = opts.arrayFormat; + else if ("indices" in opts) arrayFormat = opts.indices ? "indices" : "repeat"; + else arrayFormat = defaults.arrayFormat; + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; +} +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) return ""; + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) obj_keys = Object.keys(obj); + if (options.sort) obj_keys.sort(options.sort); + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) continue; + push_to_array(keys, inner_stringify(obj[key], key, generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) if (options.charset === "iso-8859-1") prefix += "utf8=%26%2310003%3B&"; + else prefix += "utf8=%E2%9C%93&"; + return joined.length > 0 ? prefix + joined : ""; +} +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/utils/query.js +function stringifyQuery(query) { + return stringify(query, { arrayFormat: "repeat" }); +} +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/utils/log.js +var levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) return; + if (hasOwn(levelNumbers, maybeLevel)) return maybeLevel; + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); +}; +function noop() {} +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) return noop; + else return logger[fnLevel].bind(logger); +} +var noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop +}; +var cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger) return noopLogger; + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) return cachedLogger[1]; + const levelLogger = { + error: makeLogFn("error", logger, logLevel), + warn: makeLogFn("warn", logger, logLevel), + info: makeLogFn("info", logger, logLevel), + debug: makeLogFn("debug", logger, logLevel) + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +var formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" || name.toLowerCase() === "x-tenant-id" ? "***" : value])); + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) details.retryOf = details.retryOfRequestLogID; + delete details.retryOfRequestLogID; + } + return details; +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/parse.js +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (response.status === 204) return null; + if (props.options.__binaryResponse) return response; + const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim(); + if (mediaType?.includes("application/json") || mediaType?.endsWith("+json")) { + if (response.headers.get("content-length") === "0") return; + return await response.json(); + } + return await response.text(); + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/core/api-promise.js +var __classPrivateFieldSet$2 = function(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +}; +var __classPrivateFieldGet$2 = function(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _APIPromise_client; +/** +* A subclass of `Promise` providing additional helper methods +* for interacting with the SDK. +*/ +var APIPromise = class APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + resolve(null); + }); + Object.defineProperty(this, "responsePromise", { + enumerable: true, + configurable: true, + writable: true, + value: responsePromise + }); + Object.defineProperty(this, "parseResponse", { + enumerable: true, + configurable: true, + writable: true, + value: parseResponse + }); + Object.defineProperty(this, "parsedPromise", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet$2(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new APIPromise(__classPrivateFieldGet$2(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { + data, + response + }; + } + parse() { + if (!this.parsedPromise) this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet$2(this, _APIPromise_client, "f"), data)); + 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); + } +}; +_APIPromise_client = /* @__PURE__ */ new WeakMap(); +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/core/pagination.js +var __classPrivateFieldSet$1 = function(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +}; +var __classPrivateFieldGet$1 = function(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractPage_client; +var AbstractPage = class { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + Object.defineProperty(this, "options", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "response", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "body", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + __classPrivateFieldSet$1(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + if (!this.getPaginatedItems().length) return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) throw new LangsmithError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + return await __classPrivateFieldGet$1(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 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) for (const item of page.getPaginatedItems()) yield item; + } +}; +/** +* This subclass of Promise will resolve to an instantiated Page once the request completes. +* +* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: +* +* for await (const item of client.items.list()) { +* console.log(item) +* } +*/ +var PagePromise = class extends APIPromise { + constructor(client, request, Page) { + super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) yield item; + } +}; +var OffsetPaginationIssues = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.items = body || []; + } + getPaginatedItems() { + return this.items ?? []; + } + nextPageRequestOptions() { + const currentCount = (this.options.query.offset ?? 0) + this.getPaginatedItems().length; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + offset: currentCount + } + }; + } +}; +var OffsetPaginationOnlineEvaluators = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + Object.defineProperty(this, "evaluators", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "total", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.evaluators = body.evaluators || []; + this.total = body.total || 0; + } + getPaginatedItems() { + return this.evaluators ?? []; + } + nextPageRequestOptions() { + const currentCount = (this.options.query.offset ?? 0) + this.getPaginatedItems().length; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + offset: currentCount + } + }; + } +}; +var ItemsCursorPostPagination = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "next_cursor", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.items = body.items || []; + this.next_cursor = body.next_cursor || ""; + } + getPaginatedItems() { + return this.items ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_cursor; + if (!cursor) return null; + return { + ...this.options, + body: { + ...maybeObj(this.options.body), + cursor + } + }; + } +}; +var ItemsCursorGetPagination = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "next_cursor", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.items = body.items || []; + this.next_cursor = body.next_cursor || ""; + } + getPaginatedItems() { + return this.items ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_cursor; + if (!cursor) return null; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + cursor + } + }; + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/uploads.js +var checkFileSupport = () => { + if (typeof File === "undefined") { + const { process } = globalThis; + const isOldNode = typeof process?.versions?.node === "string" && parseInt(process.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +/** +* Construct a `File` instance. This is used to ensure a helpful error is thrown +* for environments that don't define a global `File` yet. +*/ +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; +} +var isAsyncIterable$1 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/to-file.js +/** +* This check adds the arrayBuffer() method type because it is available and used at runtime +*/ +var 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"; +/** +* This check adds the arrayBuffer() method type because it is available and used at runtime +*/ +var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); +var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; +/** +* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats +* @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts +* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible +* @param {Object=} options additional properties +* @param {string=} options.type the MIME type of the content +* @param {number=} options.lastModified the last modified timestamp +* @returns a {@link File} with the given properties +*/ +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + if (isFileLike(value)) { + if (value instanceof File) return value; + return makeFile([await value.arrayBuffer()], value.name); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name ||= new URL(value.url).pathname.split(/[\\/]/).pop(); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + name ||= getName(value); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") options = { + ...options, + type + }; + } + return makeFile(parts, name, 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(value instanceof Blob ? value : await value.arrayBuffer()); + else if (isAsyncIterable$1(value)) for await (const chunk of value) parts.push(...await getBytes(chunk)); + else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) return ""; + return `; props: [${Object.getOwnPropertyNames(value).map((p) => `"${p}"`).join(", ")}]`; +} +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/core/resource.js +var APIResource = class { + constructor(client) { + Object.defineProperty(this, "_client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this._client = client; + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/utils/path.js +/** +* Percent-encode everything that isn't safe to have in a path without encoding safe chars. +* +* Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: +* > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" +* > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" +* > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" +*/ +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { + if (statics.length === 1) return statics[0]; + let postPath = false; + const invalidSegments = []; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) postPath = true; + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter` + }); + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new LangsmithError(`Path parameters result in path with invalid segments:\n${invalidSegments.map((e) => e.error).join("\n")}\n${path}\n${underline}`); + } + return path; +}; +/** +* URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. +*/ +var path$1 = /* @__PURE__ */ createPathTagFunction(encodeURIPath); +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/datasets/experiment-runs.js +var ExperimentRuns = class extends APIResource { + /** + * Returns a paginated page of dataset examples with runs from the requested + * experiments. Response uses the canonical `{items, next_cursor}` envelope. + */ + query(datasetID, body, options) { + return this._client.getAPIList(path$1`/v2/datasets/${datasetID}/experiment-runs`, ItemsCursorPostPagination, { + body, + method: "post", + ...options + }); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/datasets/datasets.js +var Datasets = class extends APIResource { + constructor() { + super(...arguments); + Object.defineProperty(this, "experimentRuns", { + enumerable: true, + configurable: true, + writable: true, + value: new ExperimentRuns(this._client) + }); + } +}; +Datasets.ExperimentRuns = ExperimentRuns; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/info.js +var Info = class extends APIResource { + /** + * Get information about the current deployment of LangSmith. + */ + list(options) { + return this._client.get("/api/v1/info", options); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/issues.js +var Issues = class extends APIResource { + /** + * **Beta:** This endpoint is in active development and may change without notice. + * + * Returns one issue for the authenticated tenant. + */ + retrieve(id, options) { + return this._client.get(path$1`/v1/platform/issues/${id}`, options); + } + /** + * **Beta:** This endpoint is in active development and may change without notice. + * + * Returns issues for the authenticated tenant, optionally filtered by session, + * status, severity, tag, or last modified time. + */ + list(query = {}, options) { + return this._client.getAPIList("/v1/platform/issues", OffsetPaginationIssues, { + query, + ...options + }); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/headers.js +var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +function* iterateHeaders(headers) { + if (!headers) return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) yield [name, null]; + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) iter = headers.entries(); + else if (isReadonlyArray(headers)) iter = headers; + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +var buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { + [brand_privateNullableHeaders]: true, + values: targetHeaders, + nulls: nullHeaders + }; +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/online-evaluators.js +var OnlineEvaluators = class extends APIResource { + /** + * Create a new LLM or code evaluator for the current workspace. + */ + create(body, options) { + return this._client.post("/v1/platform/evaluators", { + body, + ...options + }); + } + /** + * Retrieve a single evaluator by its ID. + */ + retrieve(evaluatorID, options) { + return this._client.get(path$1`/v1/platform/evaluators/${evaluatorID}`, options); + } + /** + * Update an existing evaluator's name, LLM configuration, or code configuration. + */ + update(evaluatorID, body, options) { + return this._client.patch(path$1`/v1/platform/evaluators/${evaluatorID}`, { + body, + ...options + }); + } + /** + * List evaluators for the current workspace, with optional filtering by type, + * name, tag, feedback key, or resource ID. + */ + list(query = {}, options) { + return this._client.getAPIList("/v1/platform/evaluators", OffsetPaginationOnlineEvaluators, { + query, + ...options + }); + } + /** + * Delete an evaluator. When delete_run_rules is true, all run rules referencing + * this evaluator are deleted first (same tenant). Associated llm_evaluators and + * code_evaluators rows are removed by foreign-key cascade when the evaluator row + * is deleted. + */ + delete(evaluatorID, params = {}, options) { + const { delete_run_rules } = params ?? {}; + return this._client.delete(path$1`/v1/platform/evaluators/${evaluatorID}`, { + query: { delete_run_rules }, + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Delete multiple evaluators by their IDs. Returns per-item success/failure. + */ + bulkDelete(params, options) { + const { evaluator_ids, delete_run_rules } = params; + return this._client.delete("/v1/platform/evaluators", { + query: { + evaluator_ids, + delete_run_rules + }, + ...options + }); + } + /** + * Returns per-day LLM evaluator spend for the requested 7-day period, grouped by + * evaluator, resource, or run rule. Exactly one of group_by, evaluator_id, + * session_id, or dataset_id is required. resource_id, type, and feedback_key may + * be supplied with group_by to narrow listing aggregations. + */ + spend(query, options) { + return this._client.get("/v1/platform/evaluators/spend", { + query, + ...options + }); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/runs.js +var Runs = class extends APIResource { + constructor() { + super(...arguments); + Object.defineProperty(this, "retrieve", { + enumerable: true, + configurable: true, + writable: true, + value: this.retrieveV2 + }); + Object.defineProperty(this, "query", { + enumerable: true, + configurable: true, + writable: true, + value: this.queryV2 + }); + } + /** + * **Alpha:** The request and response contract may change; Returns a paginated + * list of runs for the given projects within min/max start_time. Supports filters, + * cursor pagination, and `selects` to select fields to return. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const run of client.runs.queryV2()) { + * // ... + * } + * ``` + */ + queryV2(params, options) { + const { Accept, ...body } = params; + return this._client.getAPIList("/v2/runs/query", ItemsCursorPostPagination, { + body, + method: "post", + ...options, + headers: buildHeaders([{ ...Accept != null ? { Accept } : void 0 }, options?.headers]) + }); + } + /** + * **Alpha:** The request and response contract may change; Returns one run by ID + * for the given session and start_time. Use the `selects` query parameter + * (repeatable) to select fields to return. + * + * @example + * ```ts + * const run = await client.runs.retrieveV2( + * '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e', + * { + * project_id: '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e', + * start_time: '2019-12-27T18:11:19.117Z', + * }, + * ); + * ``` + */ + retrieveV2(runID, params, options) { + const { Accept, ...query } = params; + return this._client.get(path$1`/v2/runs/${runID}`, { + query, + ...options, + headers: buildHeaders([{ ...Accept != null ? { Accept } : void 0 }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/sandboxes/boxes.js +var Boxes = class extends APIResource { + /** + * Create a new sandbox from a snapshot. Provide at most one of `snapshot_id` or + * `snapshot_name`; if neither is provided, the server uses the default static + * blueprint. + */ + create(body, options) { + return this._client.post("/v2/sandboxes/boxes", { + body, + ...options + }); + } + /** + * Retrieve a sandbox by name. Stale provisioning sandboxes are auto-failed. + */ + retrieve(name, options) { + return this._client.get(path$1`/v2/sandboxes/boxes/${name}`, options); + } + /** + * Update a sandbox's display name. The name must be unique within the tenant. + */ + update(name, body, options) { + return this._client.patch(path$1`/v2/sandboxes/boxes/${name}`, { + body, + ...options + }); + } + /** + * List sandboxes for the authenticated tenant, with optional filtering, sorting, + * and pagination. + */ + list(query = {}, options) { + return this._client.get("/v2/sandboxes/boxes", { + query, + ...options + }); + } + /** + * Delete a sandbox by name or UUID. Tears down the sandbox runtime and removes the + * DB record. + */ + delete(name, options) { + return this._client.delete(path$1`/v2/sandboxes/boxes/${name}`, { + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Create a snapshot by capturing the current state of a sandbox or promoting an + * existing checkpoint. + */ + createSnapshot(name, body, options) { + return this._client.post(path$1`/v2/sandboxes/boxes/${name}/snapshot`, { + body, + ...options + }); + } + /** + * Create a short-lived JWT for accessing an HTTP service running on a specific + * port inside a sandbox. Returns a browser_url (sets auth cookie via redirect), a + * service_url (for use with the X-Langsmith-Sandbox-Service-Token header), the raw + * token, and its expiry. + */ + generateServiceURL(name, body, options) { + return this._client.post(path$1`/v2/sandboxes/boxes/${name}/service-url`, { + body, + ...options + }); + } + /** + * Retrieve the lightweight status of a sandbox for polling. + */ + getStatus(name, options) { + return this._client.get(path$1`/v2/sandboxes/boxes/${name}/status`, options); + } + /** + * Start a stopped or failed sandbox. This endpoint is not idempotent. + */ + start(name, options) { + return this._client.post(path$1`/v2/sandboxes/boxes/${name}/start`, options); + } + /** + * Stop a ready sandbox. This endpoint is not idempotent; the filesystem is + * preserved for later restart. + */ + stop(name, options) { + return this._client.post(path$1`/v2/sandboxes/boxes/${name}/stop`, { + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/sandboxes/registries.js +var Registries = class extends APIResource { + /** + * Create a sandbox registry for pulling private images. + */ + create(body, options) { + return this._client.post("/v2/sandboxes/registries", { + body, + ...options + }); + } + /** + * Get a sandbox registry by name. + */ + retrieve(name, options) { + return this._client.get(path$1`/v2/sandboxes/registries/${name}`, options); + } + /** + * Update a sandbox registry's name and/or credentials. + */ + update(name, body, options) { + return this._client.patch(path$1`/v2/sandboxes/registries/${name}`, { + body, + ...options + }); + } + /** + * List sandbox registries for pulling private images. + */ + list(query = {}, options) { + return this._client.get("/v2/sandboxes/registries", { + query, + ...options + }); + } + /** + * Delete a sandbox registry by name. + */ + delete(name, options) { + return this._client.delete(path$1`/v2/sandboxes/registries/${name}`, { + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/sandboxes/snapshots.js +var Snapshots = class extends APIResource { + /** + * Create a snapshot from a Docker image (async build). + */ + create(body, options) { + return this._client.post("/v2/sandboxes/snapshots", { + body, + ...options + }); + } + /** + * Get a sandbox snapshot by ID. + */ + retrieve(snapshotID, options) { + return this._client.get(path$1`/v2/sandboxes/snapshots/${snapshotID}`, options); + } + /** + * List sandbox snapshots for the authenticated tenant, with optional filtering, + * sorting, and pagination. + */ + list(query = {}, options) { + return this._client.get("/v2/sandboxes/snapshots", { + query, + ...options + }); + } + /** + * Delete a snapshot by ID. The underlying storage is reclaimed asynchronously. + */ + delete(snapshotID, options) { + return this._client.delete(path$1`/v2/sandboxes/snapshots/${snapshotID}`, { + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]) + }); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/sandboxes/sandboxes.js +var Sandboxes = class extends APIResource { + constructor() { + super(...arguments); + Object.defineProperty(this, "boxes", { + enumerable: true, + configurable: true, + writable: true, + value: new Boxes(this._client) + }); + Object.defineProperty(this, "registries", { + enumerable: true, + configurable: true, + writable: true, + value: new Registries(this._client) + }); + Object.defineProperty(this, "snapshots", { + enumerable: true, + configurable: true, + writable: true, + value: new Snapshots(this._client) + }); + } +}; +Sandboxes.Boxes = Boxes; +Sandboxes.Registries = Registries; +Sandboxes.Snapshots = Snapshots; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/threads.js +var Threads = class extends APIResource { + /** + * **Alpha:** The request and response contract may change; Retrieve all traces + * belonging to a specific thread within a project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const threadTraceListItem of client.threads.listTraces( + * 'thread_id', + * { project_id: '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e' }, + * )) { + * // ... + * } + * ``` + */ + listTraces(threadID, query, options) { + return this._client.getAPIList(path$1`/v2/threads/${threadID}/traces`, ItemsCursorGetPagination, { + query, + ...options + }); + } + /** + * **Alpha:** The request and response contract may change; Query threads within a + * project (session), with cursor-based pagination. Returns threads matching the + * given time range and optional filter. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const threadListItem of client.threads.query()) { + * // ... + * } + * ``` + */ + query(body, options) { + return this._client.getAPIList("/v2/threads/query", ItemsCursorPostPagination, { + body, + method: "post", + ...options + }); + } + /** + * **Alpha:** The request and response contract may change; Compute aggregate stats + * for a single thread (turn count, latency percentiles, token/cost sums, and + * detail breakdowns) within a project. + * + * @example + * ```ts + * const response = await client.threads.stats('thread_id', { + * selects: ['TURNS'], + * session_id: '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e', + * }); + * ``` + */ + stats(threadID, query, options) { + return this._client.get(path$1`/v2/threads/${threadID}/stats`, { + query, + ...options + }); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/resources/traces.js +var Traces = class extends APIResource { + /** + * **Alpha:** The request and response contract may change; Returns runs for a + * trace ID within min/max start time. Optional `filter`; repeatable `selects` to + * select fields to return. + * + * @example + * ```ts + * const response = await client.traces.listRuns( + * '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e', + * { project_id: '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e' }, + * ); + * ``` + */ + listRuns(traceID, params, options) { + const { Accept, ...query } = params; + return this._client.get(path$1`/v2/traces/${traceID}/runs`, { + query, + ...options, + headers: buildHeaders([{ ...Accept != null ? { Accept } : void 0 }, options?.headers]) + }); + } + /** + * Returns a paginated list of traces (root runs) for a single tracing project. + * Each item carries the trace's root run plus optional trace-wide aggregates + * (`total_tokens`, `total_cost`, `first_token_time`) under `trace_aggregates`, so + * clients never have to merge by `trace_id`. + * + * Traces are scanned within a `start_time` window: `min_start_time` defaults to 24 + * hours before the request, `max_start_time` defaults to the request time. Set + * either explicitly to widen or narrow the window. + * + * Supports filters (`trace_filter`, `tree_filter`), cursor pagination (`cursor`), + * and field projection (`selects`). + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const trace of client.traces.query()) { + * // ... + * } + * ``` + */ + query(body, options) { + return this._client.getAPIList("/v2/traces/query", ItemsCursorPostPagination, { + body, + method: "post", + ...options + }); + } +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/internal/utils/env.js +/** +* Read an environment variable. +* +* Trims beginning and trailing whitespace. +* +* Will return undefined if the environment variable doesn't exist or cannot be accessed. +*/ +var readEnv = (env) => { + if (typeof globalThis.process !== "undefined") return globalThis.process.env?.[env]?.trim() || void 0; + if (typeof globalThis.Deno !== "undefined") return globalThis.Deno.env?.get?.(env)?.trim() || void 0; +}; +//#endregion +//#region node_modules/langsmith/dist/_openapi_client/client.js +var __classPrivateFieldSet = function(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +}; +var __classPrivateFieldGet = function(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _Langsmith_instances; +var _a; +var _Langsmith_encoder; +var _Langsmith_baseURLOverridden; +/** +* API Client for interfacing with the LangChain API. +*/ +var Langsmith = class { + /** + * API Client for interfacing with the LangChain API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['LANGSMITH_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.tenantID=process.env['LANGSMITH_TENANT_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['LANGCHAIN_BASE_URL'] ?? https://api.smith.langchain.com/] - Override the default base URL for the API. + * @param {number} [opts.timeout=1.5 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + */ + constructor({ baseURL = readEnv("LANGCHAIN_BASE_URL"), apiKey = readEnv("LANGSMITH_API_KEY") ?? null, tenantID = readEnv("LANGSMITH_TENANT_ID") ?? null, ...opts } = {}) { + _Langsmith_instances.add(this); + Object.defineProperty(this, "apiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tenantID", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "baseURL", { + 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, "timeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "logger", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "logLevel", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetchOptions", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetch", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + _Langsmith_encoder.set(this, void 0); + Object.defineProperty(this, "idempotencyHeader", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_options", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "datasets", { + enumerable: true, + configurable: true, + writable: true, + value: new Datasets(this) + }); + Object.defineProperty(this, "runs", { + enumerable: true, + configurable: true, + writable: true, + value: new Runs(this) + }); + Object.defineProperty(this, "threads", { + enumerable: true, + configurable: true, + writable: true, + value: new Threads(this) + }); + Object.defineProperty(this, "traces", { + enumerable: true, + configurable: true, + writable: true, + value: new Traces(this) + }); + Object.defineProperty(this, "onlineEvaluators", { + enumerable: true, + configurable: true, + writable: true, + value: new OnlineEvaluators(this) + }); + Object.defineProperty(this, "info", { + enumerable: true, + configurable: true, + writable: true, + value: new Info(this) + }); + Object.defineProperty(this, "issues", { + enumerable: true, + configurable: true, + writable: true, + value: new Issues(this) + }); + Object.defineProperty(this, "sandboxes", { + enumerable: true, + configurable: true, + writable: true, + value: new Sandboxes(this) + }); + const options = { + apiKey, + tenantID, + ...opts, + baseURL: baseURL || `https://api.smith.langchain.com/` + }; + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("LANGCHAIN_LOG"), "process.env['LANGCHAIN_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _Langsmith_encoder, FallbackEncoder, "f"); + const customHeadersEnv = readEnv("LANGCHAIN_CUSTOM_HEADERS"); + if (customHeadersEnv) { + const parsed = {}; + for (const line of customHeadersEnv.split("\n")) { + const colon = line.indexOf(":"); + if (colon >= 0) parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim(); + } + options.defaultHeaders = { + ...parsed, + ...options.defaultHeaders + }; + } + this._options = options; + this.apiKey = apiKey; + this.tenantID = tenantID; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + return new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + tenantID: this.tenantID, + ...options + }); + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + if (this.apiKey && values.get("x-api-key")) return; + if (nulls.has("x-api-key")) return; + if (this.tenantID && values.get("x-tenant-id")) return; + if (nulls.has("x-tenant-id")) return; + throw new Error("Could not resolve authentication method. Expected either apiKey or tenantID to be set. Or for one of the \"X-API-Key\" or \"X-Tenant-Id\" headers to be explicitly omitted"); + } + async authHeaders(opts) { + return buildHeaders([await this.apiKeyAuth(opts), await this.tenantIDAuth(opts)]); + } + async apiKeyAuth(opts) { + if (this.apiKey == null) return; + return buildHeaders([{ "X-API-Key": this.apiKey }]); + } + async tenantIDAuth(opts) { + if (this.tenantID == null) return; + return buildHeaders([{ "X-Tenant-Id": this.tenantID }]); + } + stringifyQuery(query) { + return stringifyQuery(query); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + buildURL(path, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _Langsmith_instances, "m", _Langsmith_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL(path) ? new URL(path) : new URL(baseURL + (baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + const pathQuery = Object.fromEntries(url.searchParams); + if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) query = { + ...pathQuery, + ...defaultQuery, + ...query + }; + if (typeof query === "object" && query && !Array.isArray(query)) url.search = this.stringifyQuery(query); + return url.toString(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) {} + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) {} + 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((opts) => { + return { + method, + path, + ...opts + }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) retriesRemaining = maxRetries; + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); + await this.prepareRequest(req, { + url, + options + }); + /** Not an API request ID, just for correlating local log entries. */ + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) throw new APIUserAbortError(); + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) throw new APIUserAbortError(); + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) throw new APIConnectionTimeoutError(); + throw new APIConnectionError({ cause: response }); + } + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err) => castToError(err).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + throw this.makeStatusError(response.status, errJSON, errMessage, response.headers); + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { + response, + options, + controller, + requestLogID, + retryOfRequestLogID, + startTime + }; + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, opts && "then" in opts ? opts.then((opts) => ({ + method: "get", + path, + ...opts + })) : { + method: "get", + path, + ...opts + }); + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise(this, request, Page); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) fetchOptions.method = method.toUpperCase(); + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async 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, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) timeoutMillis = timeoutMs; + } + const retryAfterHeader = responseHeaders?.get("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 === void 0) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep$1(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = .5; + const maxRetryDelay = 16; + const numRetries = maxRetries - retriesRemaining; + return Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay) * (1 - Math.random() * .25) * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path, query, defaultBaseURL } = options; + const url = this.buildURL(path, query, defaultBaseURL); + if ("timeout" in options) validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + return { + req: { + method, + headers: await this.buildHeaders({ + options: inputOptions, + method, + bodyHeaders, + retryCount + }), + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }, + url, + timeout: options.timeout + }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders() + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) return { + bodyHeaders: void 0, + body: void 0 + }; + const headers = buildHeaders([rawHeaders]); + if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) return { + bodyHeaders: void 0, + body + }; + else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) return { + bodyHeaders: void 0, + body: ReadableStreamFrom(body) + }; + else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + else return __classPrivateFieldGet(this, _Langsmith_encoder, "f").call(this, { + body, + headers + }); + } +}; +_a = Langsmith, _Langsmith_encoder = /* @__PURE__ */ new WeakMap(), _Langsmith_instances = /* @__PURE__ */ new WeakSet(), _Langsmith_baseURLOverridden = function _Langsmith_baseURLOverridden() { + return this.baseURL !== "https://api.smith.langchain.com/"; +}; +Object.defineProperty(Langsmith, "Langsmith", { + enumerable: true, + configurable: true, + writable: true, + value: _a +}); +Object.defineProperty(Langsmith, "DEFAULT_TIMEOUT", { + enumerable: true, + configurable: true, + writable: true, + value: 9e4 +}); +Object.defineProperty(Langsmith, "LangsmithError", { + enumerable: true, + configurable: true, + writable: true, + value: LangsmithError +}); +Object.defineProperty(Langsmith, "APIError", { + enumerable: true, + configurable: true, + writable: true, + value: APIError +}); +Object.defineProperty(Langsmith, "APIConnectionError", { + enumerable: true, + configurable: true, + writable: true, + value: APIConnectionError +}); +Object.defineProperty(Langsmith, "APIConnectionTimeoutError", { + enumerable: true, + configurable: true, + writable: true, + value: APIConnectionTimeoutError +}); +Object.defineProperty(Langsmith, "APIUserAbortError", { + enumerable: true, + configurable: true, + writable: true, + value: APIUserAbortError +}); +Object.defineProperty(Langsmith, "NotFoundError", { + enumerable: true, + configurable: true, + writable: true, + value: NotFoundError +}); +Object.defineProperty(Langsmith, "ConflictError", { + enumerable: true, + configurable: true, + writable: true, + value: ConflictError +}); +Object.defineProperty(Langsmith, "RateLimitError", { + enumerable: true, + configurable: true, + writable: true, + value: RateLimitError +}); +Object.defineProperty(Langsmith, "BadRequestError", { + enumerable: true, + configurable: true, + writable: true, + value: BadRequestError +}); +Object.defineProperty(Langsmith, "AuthenticationError", { + enumerable: true, + configurable: true, + writable: true, + value: AuthenticationError +}); +Object.defineProperty(Langsmith, "InternalServerError", { + enumerable: true, + configurable: true, + writable: true, + value: InternalServerError +}); +Object.defineProperty(Langsmith, "PermissionDeniedError", { + enumerable: true, + configurable: true, + writable: true, + value: PermissionDeniedError +}); +Object.defineProperty(Langsmith, "UnprocessableEntityError", { + enumerable: true, + configurable: true, + writable: true, + value: UnprocessableEntityError +}); +Object.defineProperty(Langsmith, "toFile", { + enumerable: true, + configurable: true, + writable: true, + value: toFile +}); +Langsmith.Datasets = Datasets; +Langsmith.Runs = Runs; +Langsmith.Threads = Threads; +Langsmith.Traces = Traces; +Langsmith.OnlineEvaluators = OnlineEvaluators; +Langsmith.Info = Info; +Langsmith.Issues = Issues; +Langsmith.Sandboxes = Sandboxes; +//#endregion +//#region node_modules/langsmith/dist/utils/constants.js +var _MIN_BACKEND_VERSION = "0.16.10rc1"; +//#endregion +//#region node_modules/langsmith/dist/utils/error.js +/** +* Get the error message for an invalid prompt identifier. +* Used consistently across the codebase when parsing prompt identifiers fails. +* +* @param identifier - The invalid identifier that was provided +* @returns A formatted error message explaining the valid formats +*/ +function getInvalidPromptIdentifierMsg(identifier) { + return `Invalid prompt identifier format: "${identifier}". Expected one of:\n - "prompt-name" (for private prompts)\n - "owner/prompt-name" (for prompts with explicit owner)\n - "prompt-name:commit-hash" (with commit reference)\n - "owner/prompt-name:commit-hash" (with owner and commit)`; +} +/** +* LangSmithConflictError +* +* Represents an error that occurs when there's a conflict during an operation, +* typically corresponding to HTTP 409 status code responses. +* +* This error is thrown when an attempt to create or modify a resource conflicts +* with the current state of the resource on the server. Common scenarios include: +* - Attempting to create a resource that already exists +* - Trying to update a resource that has been modified by another process +* - Violating a uniqueness constraint in the data +* +* @extends Error +* +* @example +* try { +* await createProject("existingProject"); +* } catch (error) { +* if (error instanceof ConflictError) { +* console.log("A conflict occurred:", error.message); +* // Handle the conflict, e.g., by suggesting a different project name +* } else { +* // Handle other types of errors +* } +* } +* +* @property {string} name - Always set to 'ConflictError' for easy identification +* @property {string} message - Detailed error message including server response +* +* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 +*/ +var LangSmithConflictError = class extends Error { + constructor(message) { + super(message); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = "LangSmithConflictError"; + this.status = 409; + } +}; +/** +* LangSmithNotFoundError +* +* Represents an error that occurs when a requested resource is not found, +* typically corresponding to HTTP 404 status code responses. +* +* @extends Error +*/ +var LangSmithNotFoundError = class extends Error { + constructor(message) { + super(message); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = "LangSmithNotFoundError"; + this.status = 404; + } +}; +function isLangSmithNotFoundError(error) { + return error != null && typeof error === "object" && "name" in error && error?.name === "LangSmithNotFoundError"; +} +function isLangSmithConflictError(error) { + return error != null && typeof error === "object" && "name" in error && error?.name === "LangSmithConflictError"; +} +/** +* Throws an appropriate error based on the response status and body. +* +* @param response - The fetch Response object +* @param context - Additional context to include in the error message (e.g., operation being performed) +* @throws {LangSmithConflictError} When the response status is 409 +* @throws {Error} For all other non-ok responses +*/ +async function raiseForStatus(response, context, consumeOnSuccess) { + let errorBody; + if (response.ok) { + if (consumeOnSuccess) errorBody = await response.text(); + return; + } + if (response.status === 403) try { + if ((await response.json())?.error === "org_scoped_key_requires_workspace") errorBody = "This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable."; + } catch (_e) { + const errorWithStatus = /* @__PURE__ */ new Error(`${response.status} ${response.statusText}`); + errorWithStatus.status = response?.status; + throw errorWithStatus; + } + if (errorBody === void 0) try { + errorBody = await response.text(); + } catch (_e) { + errorBody = ""; + } + const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`; + if (response.status === 404) throw new LangSmithNotFoundError(fullMessage); + if (response.status === 409) throw new LangSmithConflictError(fullMessage); + const err = new Error(fullMessage); + err.status = response.status; + throw err; +} +var ERR_CONFLICTING_ENDPOINTS = "ERR_CONFLICTING_ENDPOINTS"; +var ConflictingEndpointsError = class extends Error { + constructor() { + super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: ERR_CONFLICTING_ENDPOINTS + }); + this.name = "ConflictingEndpointsError"; + } +}; +function isConflictingEndpointsError(err) { + return typeof err === "object" && err !== null && err.code === ERR_CONFLICTING_ENDPOINTS; +} +//#endregion +//#region node_modules/langsmith/dist/utils/prompts.js +/** +* Parse a hub repo identifier (owner/name:hash, name, etc.). +* +* Prompts, agents, and skills share the same identifier grammar on Hub. +*/ +function parseHubIdentifier(identifier) { + if (!identifier || identifier.split("/").length > 2 || identifier.startsWith("/") || identifier.endsWith("/") || identifier.split(":").length > 2) throw new Error(getInvalidPromptIdentifierMsg(identifier)); + const [ownerNamePart, commitPart] = identifier.split(":"); + const commit = commitPart || "latest"; + if (ownerNamePart.includes("/")) { + const [owner, name] = ownerNamePart.split("/", 2); + if (!owner || !name) throw new Error(getInvalidPromptIdentifierMsg(identifier)); + return [ + owner, + name, + commit + ]; + } else { + if (!ownerNamePart) throw new Error(getInvalidPromptIdentifierMsg(identifier)); + return [ + "-", + ownerNamePart, + commit + ]; + } +} +//#endregion +//#region node_modules/langsmith/dist/utils/profile-lock.js +var LOCK_POLL_INTERVAL_MS = 10; +var LOCK_STALE_AFTER_MS = 1e4; +var LOCK_METADATA_FILE = "created_at"; +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function isEEXIST(err) { + return typeof err === "object" && err !== null && err.code === "EEXIST"; +} +function lockMetadataLines(lockDir) { + try { + return readFileSync(path$2.join(lockDir, LOCK_METADATA_FILE)).split("\n"); + } catch { + return; + } +} +function lockCreatedAtMs(lockDir) { + const lines = lockMetadataLines(lockDir); + if (lines && lines[0] && lines[0].trim()) { + const parsed = Date.parse(lines[0].trim()); + if (!Number.isNaN(parsed)) return parsed; + } + return statMtimeMs(lockDir); +} +function lockOwner(lockDir) { + const lines = lockMetadataLines(lockDir); + if (lines && lines.length >= 2 && lines[1].trim()) return lines[1].trim(); +} +async function removeStaleLock(lockDir) { + const createdAt = lockCreatedAtMs(lockDir); + if (createdAt === void 0 || Date.now() - createdAt <= LOCK_STALE_AFTER_MS) return false; + await rmRecursive(lockDir); + return true; +} +/** +* Acquire an exclusive cross-process lock for refreshing OAuth tokens. +* +* Uses an atomic-`mkdir` directory lock at `.oauth.lock.lock` with a +* stale-break heuristic and owner-checked release, mirroring langsmith-go's +* non-POSIX path. `deadline` is a `Date.now()`-based timestamp; acquisition +* rejects once it passes. Callers treat any rejection as "skip refresh, use the +* current token". +*/ +async function acquireOAuthRefreshLock(configPath, deadline) { + const lockDir = `${configPath}.oauth.lock.lock`; + const parent = path$2.dirname(lockDir); + if (parent) await mkdir$1(parent); + const owner = globalThis.crypto.randomUUID(); + for (;;) { + try { + await mkdirExclusive(lockDir); + } catch (err) { + if (!isEEXIST(err)) throw err; + if (!await removeStaleLock(lockDir)) { + if (Date.now() >= deadline) throw new Error("timed out acquiring OAuth refresh lock"); + await sleep(Math.min(LOCK_POLL_INTERVAL_MS, Math.max(0, deadline - Date.now()))); + } + continue; + } + try { + await writeFileAtomic(path$2.join(lockDir, LOCK_METADATA_FILE), `${(/* @__PURE__ */ new Date()).toISOString()}\n${owner}\n`); + } catch (err) { + await rmRecursive(lockDir); + throw err; + } + break; + } + return { async release() { + if (lockOwner(lockDir) === owner) await rmRecursive(lockDir); + } }; +} +var OAUTH_CLIENT_ID = "langsmith-cli"; +var TOKEN_REFRESH_LEEWAY_MS = 6e4; +var TOKEN_REFRESH_TIMEOUT_MS = 1e4; +function isBrowserLikeRuntime() { + const env = getEnv(); + return env === "browser" || env === "webworker"; +} +function getProfileConfigPath() { + const explicitPath = getEnvironmentVariable("LANGSMITH_CONFIG_FILE"); + if (explicitPath) return explicitPath; + const home = getEnvironmentVariable("HOME") ?? getEnvironmentVariable("USERPROFILE"); + if (!home) return; + return path$2.join(home, ".langsmith", "config.json"); +} +function resolveProfileName(config) { + const envProfile = getEnvironmentVariable("LANGSMITH_PROFILE"); + if (envProfile) return envProfile; + if (config.current_profile) return config.current_profile; + if (config.profiles?.default) return "default"; +} +function loadProfileState() { + if (isBrowserLikeRuntime()) return; + const configPath = getProfileConfigPath(); + if (!configPath || !existsSync(configPath)) return; + try { + const config = JSON.parse(readFileSync(configPath)); + const profileName = resolveProfileName(config); + const profile = profileName ? config.profiles?.[profileName] : void 0; + if (!profileName || !profile) return; + return { + configPath, + config, + profileName, + profile + }; + } catch { + return; + } +} +function hasValue(value) { + return value !== void 0 && value !== null && value.trim() !== ""; +} +function trimConfigValue(value) { + return value?.trim().replace(/^["']|["']$/g, ""); +} +function shouldRefreshProfileToken(profile) { + const oauth = profile.oauth; + if (!oauth?.refresh_token) return false; + if (!oauth.access_token) return true; + if (!oauth.expires_at) return false; + const expiresAt = Date.parse(oauth.expires_at); + if (Number.isNaN(expiresAt)) return false; + return expiresAt <= Date.now() + TOKEN_REFRESH_LEEWAY_MS; +} +function normalizeConfigUrl(apiUrl) { + let normalized = apiUrl; + while (normalized.endsWith("/")) normalized = normalized.slice(0, -1); + return normalized.endsWith("/api/v1") ? normalized.slice(0, -7) : normalized; +} +function applyTokenResponse(profile, token) { + profile.oauth ??= {}; + if (token.access_token) profile.oauth.access_token = token.access_token; + if (token.refresh_token) profile.oauth.refresh_token = token.refresh_token; + if (typeof token.expires_in === "number" && token.expires_in > 0) profile.oauth.expires_at = new Date(Date.now() + token.expires_in * 1e3).toISOString(); +} +function getAbortReason(signal) { + return signal.reason ?? /* @__PURE__ */ new Error("The operation was aborted."); +} +async function waitForAbortSignal(promise, signal) { + if (!signal) return promise; + if (signal.aborted) throw getAbortReason(signal); + let cleanup; + const abortPromise = new Promise((_, reject) => { + const onAbort = () => { + reject(getAbortReason(signal)); + }; + signal.addEventListener("abort", onAbort, { once: true }); + cleanup = () => { + signal.removeEventListener("abort", onAbort); + }; + }); + try { + return await Promise.race([promise, abortPromise]); + } finally { + cleanup?.(); + } +} +function loadProfileClientConfig() { + const state = loadProfileState(); + const profile = state?.profile; + if (!state || !profile) return {}; + const apiKey = trimConfigValue(profile.api_key); + const oauthAccessToken = trimConfigValue(profile.oauth?.access_token); + const oauthRefreshToken = trimConfigValue(profile.oauth?.refresh_token); + return { + apiUrl: profile.api_url, + apiKey, + workspaceId: profile.workspace_id, + oauthAccessToken, + oauthRefreshToken, + profileAuth: apiKey || oauthAccessToken || oauthRefreshToken ? new ProfileAuth(state) : void 0 + }; +} +var ProfileAuth = class { + constructor(state) { + Object.defineProperty(this, "state", { + enumerable: true, + configurable: true, + writable: true, + value: state + }); + Object.defineProperty(this, "refreshPromise", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "managedAuthorizationValue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.rememberProfileAuthHeader(this.currentAuthHeader()); + } + currentAuthHeader() { + const header = currentAuthHeaderFromProfile(this.state.profile); + this.rememberProfileAuthHeader(header); + return header; + } + async getAuthHeader(fetchImplementation, signal) { + if (shouldRefreshProfileToken(this.state.profile)) { + if (!this.refreshPromise) this.refreshPromise = this.refreshOAuthToken(fetchImplementation).finally(() => { + this.refreshPromise = void 0; + }); + await waitForAbortSignal(this.refreshPromise, signal); + } + const header = authHeaderFromProfile(this.state.profile); + this.rememberProfileAuthHeader(header); + return header; + } + isProfileAuthorizationHeader(value) { + return value === this.managedAuthorizationValue; + } + reloadProfile() { + try { + const config = JSON.parse(readFileSync(this.state.configPath)); + const profile = config.profiles?.[this.state.profileName]; + if (!profile) return; + this.state.config = config; + this.state.profile = profile; + return profile; + } catch { + return; + } + } + async refreshOAuthToken(fetchImplementation) { + const refreshToken = this.state.profile.oauth?.refresh_token; + if (!refreshToken) return; + const refreshApiUrl = trimConfigValue(this.state.profile.api_url) ?? "https://api.smith.langchain.com"; + const deadline = Date.now() + TOKEN_REFRESH_TIMEOUT_MS; + let lock; + try { + lock = await acquireOAuthRefreshLock(this.state.configPath, deadline); + if (this.reloadProfile() && !shouldRefreshProfileToken(this.state.profile)) return; + const body = new URLSearchParams({ + grant_type: "refresh_token", + client_id: OAUTH_CLIENT_ID, + refresh_token: this.state.profile.oauth?.refresh_token ?? refreshToken + }); + const response = await fetchImplementation(`${normalizeConfigUrl(refreshApiUrl)}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: body.toString(), + signal: AbortSignal.timeout(Math.max(0, deadline - Date.now())) + }); + if (!response.ok) return; + const token = await response.json(); + if (!token.access_token) return; + applyTokenResponse(this.state.profile, token); + this.state.config.profiles ??= {}; + this.state.config.profiles[this.state.profileName] = this.state.profile; + await writeFileAtomic(this.state.configPath, `${JSON.stringify(this.state.config, null, 2)}\n`); + } catch { + return; + } finally { + await lock?.release(); + } + } + rememberProfileAuthHeader(header) { + this.managedAuthorizationValue = header?.name === "Authorization" ? header.value : void 0; + } +}; +function currentAuthHeaderFromProfile(profile) { + const oauthAccessToken = trimConfigValue(profile.oauth?.access_token); + if (oauthAccessToken) return { + name: "Authorization", + value: `Bearer ${oauthAccessToken}` + }; + if (trimConfigValue(profile.oauth?.refresh_token)) return; + return authHeaderFromProfile(profile); +} +function authHeaderFromProfile(profile) { + const oauthAccessToken = trimConfigValue(profile.oauth?.access_token); + if (oauthAccessToken) return { + name: "Authorization", + value: `Bearer ${oauthAccessToken}` + }; + const apiKey = trimConfigValue(profile.api_key); + if (apiKey) return { + name: "x-api-key", + value: apiKey + }; +} +//#endregion +//#region node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +var LIMIT_REPLACE_NODE = "[...]"; +var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; +var arr = []; +var replacerStack = []; +var encoder = new TextEncoder(); +function defaultOptions$1() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER + }; +} +function encodeString(str) { + return encoder.encode(str); +} +function serializeWellKnownTypes(val) { + if (val && typeof val === "object" && val !== null) { + if (val instanceof Map) return Object.fromEntries(val); + else if (val instanceof Set) return Array.from(val); + else if (val instanceof Date) return val.toISOString(); + else if (val instanceof RegExp) return val.toString(); + else if (val instanceof Error) return { + name: val.name, + message: val.message + }; + } else if (typeof val === "bigint") return val.toString(); + return val; +} +function createDefaultReplacer(userReplacer) { + return function(key, val) { + if (userReplacer) { + const userResult = userReplacer.call(this, key, val); + if (userResult !== void 0) return userResult; + } + return serializeWellKnownTypes(val); + }; +} +function estimateSerializedSize(value) { + try { + const ancestors = /* @__PURE__ */ new Set(); + let maxStringLen = 0; + const byteLen = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length; + function estimateString(s) { + const n = byteLen(s); + if (n > maxStringLen) maxStringLen = n; + return n + 2; + } + function estimateByteArrayJson(byteLength) { + if (byteLength === 0) return 2; + return 2 + byteLength * 4; + } + function isDropped(v) { + return v === void 0 || typeof v === "function" || typeof v === "symbol"; + } + function estimateInArray(v) { + if (v === void 0 || typeof v === "function" || typeof v === "symbol") return 4; + return estimate(v); + } + function estimate(val) { + if (val === null) return 4; + if (val === void 0) return 0; + const t = typeof val; + if (t === "boolean") return 5; + if (t === "number") { + if (!Number.isFinite(val)) return 4; + return val.toString().length; + } + if (t === "bigint") return val.toString().length + 2; + if (t === "string") return estimateString(val); + if (t === "function" || t === "symbol") return 0; + const obj = val; + if (obj instanceof Date) return 26; + if (obj instanceof RegExp) return byteLen(obj.toString()) + 2; + if (obj instanceof Error) { + const name = obj.name ?? ""; + const message = obj.message ?? ""; + return 22 + byteLen(name) + byteLen(message); + } + if (typeof Buffer !== "undefined" && obj instanceof Buffer) return 28 + estimateByteArrayJson(obj.byteLength); + if (ArrayBuffer.isView(obj)) { + if (obj instanceof DataView) return 2; + return 2 + (obj.length ?? 0) * (obj instanceof Float32Array || obj instanceof Float64Array ? 30 : 12); + } + if (obj instanceof ArrayBuffer) return 2; + if (ancestors.has(obj)) return 24; + if (typeof obj.toJSON === "function") { + let projected; + try { + projected = obj.toJSON(""); + } catch { + return 16; + } + ancestors.add(obj); + const size = estimate(projected); + ancestors.delete(obj); + return size; + } + ancestors.add(obj); + let size; + if (Array.isArray(obj)) { + size = 2; + const len = obj.length; + for (let i = 0; i < len; i++) { + size += estimateInArray(obj[i]); + if (i < len - 1) size += 1; + } + } else if (obj instanceof Map) { + size = 2; + let emitted = 0; + for (const [k, v] of obj) { + if (isDropped(v)) continue; + if (emitted > 0) size += 1; + size += byteLen(typeof k === "string" ? k : String(k)) + 3; + size += estimate(v); + emitted++; + } + } else if (obj instanceof Set) { + size = 2; + let emitted = 0; + for (const v of obj) { + if (emitted > 0) size += 1; + size += estimateInArray(v); + emitted++; + } + } else { + size = 2; + let emitted = 0; + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const v = obj[key]; + if (isDropped(v)) continue; + if (emitted > 0) size += 1; + size += byteLen(key) + 3; + size += estimate(v); + emitted++; + } + } + ancestors.delete(obj); + return size; + } + return { + size: estimate(value), + maxStringLen + }; + } catch { + return { + size: serialize(value).length, + maxStringLen: 0 + }; + } +} +function serialize(obj, errorContext, replacer, spacer, options) { + try { + return encodeString(JSON.stringify(obj, createDefaultReplacer(replacer), spacer)); + } catch (e) { + if (!e.message?.includes("Converting circular structure to JSON")) { + console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? `\nContext: ${errorContext}` : ""}`); + return encodeString("[Unserializable]"); + } + getLangSmithEnvironmentVariable("SUPPRESS_CIRCULAR_JSON_WARNINGS") !== "true" && console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\nContext: ${errorContext}` : ""}`); + if (typeof options === "undefined") options = defaultOptions$1(); + decirc(obj, "", 0, [], void 0, 0, options); + let res; + try { + if (replacerStack.length === 0) res = JSON.stringify(obj, replacer, spacer); + else res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + } catch (_) { + return encodeString("[unable to serialize, circular reference is too complex to analyze]"); + } finally { + while (arr.length !== 0) { + const part = arr.pop(); + if (part.length === 4) Object.defineProperty(part[0], part[1], part[3]); + else part[0][part[1]] = part[2]; + } + } + return encodeString(res); + } +} +function setReplace(replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== void 0) if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + arr.push([ + parent, + k, + val, + propertyDescriptor + ]); + } else replacerStack.push([ + val, + k, + replace + ]); + else { + parent[k] = replace; + arr.push([ + parent, + k, + val + ]); + } +} +function decirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + if (Array.isArray(val)) for (i = 0; i < val.length; i++) decirc(val[i], i, i, stack, val, depth, options); + else { + val = serializeWellKnownTypes(val); + var keys = Object.keys(val); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + decirc(val[key], key, i, stack, val, depth, options); + } + } + stack.pop(); + } +} +function replaceGetterValues(replacer) { + replacer = typeof replacer !== "undefined" ? replacer : function(k, v) { + return v; + }; + return function(key, val) { + if (replacerStack.length > 0) for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack.splice(i, 1); + break; + } + } + return replacer.call(this, key, val); + }; +} +//#endregion +//#region node_modules/langsmith/dist/utils/worker_threads.js +/** +* worker_threads abstraction (Node.js version). +* +* This file is swapped with worker_threads.browser.ts for browser / edge +* builds via the package.json `browser` field. Node gets the real module; +* browsers get a stub that signals unavailability. +* +* Only the surface actually used by SerializeWorker is re-exported. +*/ +var Worker$1 = Worker; +//#endregion +//#region node_modules/langsmith/dist/utils/serialize_worker.js +/** +* Off-thread serialization using Node worker_threads. +* +* Falls back silently to synchronous serialize() when: +* - worker_threads is unavailable (browsers, Deno, Bun without compat, +* Cloudflare Workers, Vercel Edge, React Native) +* - the worker cannot be constructed (bundler/runtime constraints) +* - DataCloneError is thrown for a payload containing non-cloneable +* values (functions, class instances with non-cloneable state, etc.) +* - the worker crashes or throws +* +* Protocol: +* main -> worker: { id, op, payload } +* op = "serialize" -> worker returns bytes as a transferable ArrayBuffer +* worker -> main: { id, bytes?: ArrayBuffer, error?: string } +* +* The worker source is inlined as a string so the library bundles cleanly +* under webpack/esbuild/ncc without requiring a separate asset file. +*/ +var WORKER_SOURCE = ` +const { parentPort } = require("worker_threads"); + +const CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; + +function serializeWellKnownTypes(val) { + if (val && typeof val === "object") { + if (val instanceof Map) return Object.fromEntries(val); + if (val instanceof Set) return Array.from(val); + if (val instanceof Date) return val.toISOString(); + if (val instanceof RegExp) return val.toString(); + if (val instanceof Error) return { name: val.name, message: val.message }; + } else if (typeof val === "bigint") { + return val.toString(); + } + return val; +} + +function defaultReplacer(_key, val) { + return serializeWellKnownTypes(val); +} + +// Decirculate in-place: replace circular refs with { result: "[Circular]" } +// then restore after stringify. Mirrors fast-safe-stringify's decirc(). +const restoreStack = []; +function decirc(val, k, stack, parent) { + if (typeof val === "object" && val !== null) { + for (let i = 0; i < stack.length; i++) { + if (stack[i] === val) { + const orig = parent[k]; + parent[k] = CIRCULAR_REPLACE_NODE; + restoreStack.push([parent, k, orig]); + return; + } + } + stack.push(val); + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) decirc(val[i], i, stack, val); + } else { + const normalized = serializeWellKnownTypes(val); + // Only recurse into normalized if it's still an object (arrays/objects), + // else it was replaced with a primitive (e.g. Date -> string). + if (normalized === val) { + const keys = Object.keys(val); + for (let i = 0; i < keys.length; i++) decirc(val[keys[i]], keys[i], stack, val); + } + } + stack.pop(); + } +} + +function serialize(obj) { + try { + return JSON.stringify(obj, defaultReplacer); + } catch (e) { + if (!String(e && e.message).includes("Converting circular structure to JSON")) { + return "[Unserializable]"; + } + decirc(obj, "", [], { "": obj }); + try { + return JSON.stringify(obj, defaultReplacer); + } catch (_) { + return "[unable to serialize, circular reference is too complex to analyze]"; + } finally { + while (restoreStack.length) { + const [p, k, v] = restoreStack.pop(); + p[k] = v; + } + } + } +} + +parentPort.on("message", (msg) => { + const { id, op, payload } = msg; + try { + if (op === "serialize") { + const str = serialize(payload); + const buf = Buffer.from(str, "utf8"); + // Slice into its own ArrayBuffer so we can transfer without dragging + // unrelated bytes from any shared pool buffer. + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + parentPort.postMessage({ id, bytes: ab, length: buf.byteLength }, [ab]); + } else if (op === "ping") { + parentPort.postMessage({ id }); + } else { + parentPort.postMessage({ id, error: "unknown op: " + op }); + } + } catch (e) { + parentPort.postMessage({ id, error: String((e && e.message) || e) }); + } +}); +`; +var SerializeWorker = class { + constructor() { + Object.defineProperty(this, "worker", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "nextId", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "pending", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + Object.defineProperty(this, "disabled", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "startPromise", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + } + /** + * Try to construct the worker. Returns false if the runtime can't support + * it -- in that case callers must fall back to synchronous serialization. + * Kept async so callers don't have to branch on runtime -- the promise + * resolves synchronously on the microtask queue when the worker module + * is available, which is the common Node CJS/ESM path. + */ + async ensureStarted() { + if (this.disabled) return false; + if (this.worker !== null) return true; + if (this.startPromise !== null) return this.startPromise; + this.startPromise = this._start(); + try { + return await this.startPromise; + } finally { + this.startPromise = null; + } + } + async _start() { + if (Worker$1 === null) { + this.disabled = true; + return false; + } + try { + const worker = new Worker$1(WORKER_SOURCE, { eval: true }); + worker.on("message", (msg) => { + const p = this.pending.get(msg.id); + if (!p) return; + this.pending.delete(msg.id); + if (msg.error) p.reject(new Error(msg.error)); + else if (msg.bytes && typeof msg.length === "number") p.resolve(new Uint8Array(msg.bytes, 0, msg.length)); + else p.reject(/* @__PURE__ */ new Error("worker returned malformed message")); + }); + worker.on("error", (err) => { + for (const [, p] of this.pending) p.reject(err); + this.pending.clear(); + this.disabled = true; + this.worker = null; + }); + worker.on("exit", (code) => { + for (const [, p] of this.pending) p.reject(/* @__PURE__ */ new Error(`worker exited with code ${code}`)); + this.pending.clear(); + this.worker = null; + }); + worker.unref(); + this.worker = worker; + return true; + } catch { + this.disabled = true; + return false; + } + } + /** + * Serialize a payload off-thread. Rejects with DataCloneError (or similar) + * if the payload contains non-cloneable values -- callers must catch and + * fall back to synchronous serialize(). + * + * Resolves with null if the worker subsystem is unavailable entirely, + * so the caller can fall back without paying try/catch overhead. + */ + async serialize(payload) { + if (!await this.ensureStarted()) return null; + const id = this.nextId++; + return new Promise((resolve, reject) => { + this.pending.set(id, { + resolve, + reject + }); + try { + this.worker.postMessage({ + id, + op: "serialize", + payload + }); + } catch (e) { + this.pending.delete(id); + reject(e); + } + }); + } + async terminate() { + if (this.worker) { + await this.worker.terminate(); + this.worker = null; + } + for (const [, p] of this.pending) p.reject(/* @__PURE__ */ new Error("worker terminated")); + this.pending.clear(); + } +}; +var sharedWorker = null; +/** +* Process-wide shared worker. One worker serves all Client instances to +* avoid spawning multiple threads per process. +*/ +function getSharedSerializeWorker() { + if (sharedWorker === null) sharedWorker = new SerializeWorker(); + return sharedWorker; +} +/** +* Minimum string length (in UTF-16 code units) that justifies the overhead +* of dispatching serialization to a worker thread. +* +* Rationale: V8's postMessage / structuredClone fast-paths large strings +* across isolates by refcounting their underlying storage rather than +* copying the bytes. This makes worker offload a big win for payloads +* dominated by a handful of multi-hundred-KB strings (the classic case is +* base64-encoded images or audio in LLM messages), but a net loss for +* payloads whose bulk is structural -- thousands of keys, deep nesting, +* many small strings -- because every object node must still be walked +* and cloned. +* +* 64KB sits comfortably above typical "chunk of agent state" or "long +* prompt" values (a few KB) and below typical base64 media payloads +* (hundreds of KB to several MB). +*/ +var LARGE_STRING_THRESHOLD = 64 * 1024; +/** +* Maximum number of nodes to inspect before giving up and assuming the +* payload is not worth offloading. Prevents the check itself from becoming +* expensive on pathologically structural payloads (many thousands of small +* keys / array elements). +* +* When the budget is exhausted without finding a large string we return +* false (do not offload). This is the conservative choice: such payloads +* are structural by nature and worker offload empirically regresses them. +*/ +var NODE_BUDGET = 2048; +/** +* Cheap, short-circuiting walk that returns true iff the payload contains +* at least one string of length >= threshold anywhere in its graph. +* +* - Terminates immediately on the first qualifying string. +* - Caps total nodes visited at `nodeBudget` so cost is bounded for huge +* structural payloads. +* - Avoids allocation in the common path: uses an array as a stack and a +* Set only for cycle detection. +* - Uses `string.length` (UTF-16 units), not UTF-8 byte length, because +* that's what V8's string-sharing fast path keys on and because it's +* an O(1) property access. For ASCII content this is identical to the +* UTF-8 byte count; for non-ASCII text the two differ by at most 4x, +* well within the safety margin of the threshold. +*/ +function hasLargeString(value, threshold = LARGE_STRING_THRESHOLD, nodeBudget = NODE_BUDGET) { + if (value === null || typeof value !== "object") return typeof value === "string" && value.length >= threshold; + const stack = [value]; + const seen = /* @__PURE__ */ new Set(); + let visited = 0; + while (stack.length > 0) { + if (visited++ >= nodeBudget) return false; + const cur = stack.pop(); + if (cur === null || cur === void 0) continue; + const t = typeof cur; + if (t === "string") { + if (cur.length >= threshold) return true; + continue; + } + if (t !== "object") continue; + const obj = cur; + if (seen.has(obj)) continue; + seen.add(obj); + if (obj instanceof Date || obj instanceof RegExp || obj instanceof Error || obj instanceof ArrayBuffer || ArrayBuffer.isView(obj)) continue; + if (Array.isArray(obj)) { + for (let i = obj.length - 1; i >= 0; i--) stack.push(obj[i]); + continue; + } + if (obj instanceof Map) { + for (const [, v] of obj) stack.push(v); + continue; + } + if (obj instanceof Set) { + for (const v of obj) stack.push(v); + continue; + } + const keys = Object.keys(obj); + for (let i = keys.length - 1; i >= 0; i--) stack.push(obj[keys[i]]); + } + return false; +} +//#endregion +//#region node_modules/langsmith/dist/client.js +function assertPullPublicPromptAllowed(promptIdentifier, dangerouslyPullPublicPrompt) { + const [owner] = parseHubIdentifier(promptIdentifier); + if (owner !== "-" && !dangerouslyPullPublicPrompt) throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk."); +} +/** +* Catches timestamps without a timezone suffix. +*/ +function _ensureUTCTimestamp(ts) { + if (typeof ts === "string" && ts.length > 0 && !ts.includes("Z") && !ts.includes("+") && !ts.includes("-", 10)) return ts + "Z"; + return ts; +} +function _normalizeRunTimestamps(run) { + return { + ...run, + start_time: _ensureUTCTimestamp(run.start_time), + end_time: _ensureUTCTimestamp(run.end_time) + }; +} +function mergeRuntimeEnvIntoRun(run, cachedEnvVars, omitTracedRuntimeInfo) { + if (omitTracedRuntimeInfo) return run; + const runtimeEnv = getRuntimeEnvironment(); + const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata(); + const extra = run.extra ?? {}; + const metadata = extra.metadata; + run.extra = { + ...extra, + runtime: { + ...runtimeEnv, + ...extra?.runtime + }, + metadata: { + ...envVars, + ...envVars.revision_id || "revision_id" in run && run.revision_id ? { revision_id: ("revision_id" in run ? run.revision_id : void 0) ?? envVars.revision_id } : {}, + ...metadata + } + }; + return run; +} +var getTracingSamplingRate = (configRate) => { + const samplingRateStr = configRate?.toString() ?? getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); + if (samplingRateStr === void 0) return; + const samplingRate = parseFloat(samplingRateStr); + if (samplingRate < 0 || samplingRate > 1) throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); + return samplingRate; +}; +var isLocalhost = (url) => { + const hostname = url.replace("http://", "").replace("https://", "").split("/")[0].split(":")[0]; + return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"; +}; +async function toArray(iterable) { + const result = []; + for await (const item of iterable) result.push(item); + return result; +} +function trimQuotes(str) { + if (str === void 0) return; + return str.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1"); +} +var handle429 = async (response) => { + if (response?.status === 429) { + const retryAfter = parseInt(response.headers.get("retry-after") ?? "10", 10) * 1e3; + if (retryAfter > 0) { + await new Promise((resolve) => setTimeout(resolve, retryAfter)); + return true; + } + } + return false; +}; +function _formatFeedbackScore(score) { + if (typeof score === "number") return Number(score.toFixed(4)); + return score; +} +function _checkBackendVersion(version, minVersion = _MIN_BACKEND_VERSION) { + const parse = (v) => v.split(".").map((s) => parseInt(s, 10)); + const [maj, min, pat] = parse(version); + const [rMaj, rMin, rPat] = parse(minVersion); + if (isNaN(maj) || isNaN(min) || isNaN(pat) || isNaN(rMaj) || isNaN(rMin) || isNaN(rPat)) { + console.warn(`[LANGSMITH]: Could not parse backend version ${JSON.stringify(version)} for compatibility check.`); + return; + } + if (maj < rMaj || maj === rMaj && min < rMin || maj === rMaj && min === rMin && pat < rPat) console.warn(`[LANGSMITH]: Backend version ${JSON.stringify(version)} is older than the minimum version required by this SDK (${JSON.stringify(minVersion)}). Some features may not work as expected.`); +} +var SERVER_INFO_REQUEST_TIMEOUT_MS = 1e4; +/** Maximum number of operations to batch in a single request. */ +var DEFAULT_BATCH_SIZE_LIMIT = 100; +var AutoBatchQueue = class { + constructor(maxSizeBytes) { + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "sizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "maxSizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxSizeBytes = maxSizeBytes ?? 1073741824; + } + peek() { + return this.items[0]; + } + push(item) { + let itemPromiseResolve; + const itemPromise = new Promise((resolve) => { + itemPromiseResolve = resolve; + }); + const size = estimateSerializedSize(item.item).size; + if (this.sizeBytes + size > this.maxSizeBytes && this.items.length > 0) { + console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${item.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${size} bytes.`); + itemPromiseResolve(); + return itemPromise; + } + this.items.push({ + action: item.action, + payload: item.item, + otelContext: item.otelContext, + apiKey: item.apiKey, + apiUrl: item.apiUrl, + itemPromiseResolve, + itemPromise, + size + }); + this.sizeBytes += size; + return itemPromise; + } + pop({ upToSizeBytes, upToSize }) { + if (upToSizeBytes < 1) throw new Error("Number of bytes to pop off may not be less than 1."); + const popped = []; + let poppedSizeBytes = 0; + while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && this.items.length > 0 && popped.length < upToSize) { + const item = this.items.shift(); + if (item) { + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + } + if (popped.length === 0 && this.items.length > 0) { + const item = this.items.shift(); + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + return [popped.map((it) => ({ + action: it.action, + item: it.payload, + otelContext: it.otelContext, + apiKey: it.apiKey, + apiUrl: it.apiUrl, + size: it.size + })), () => popped.forEach((it) => it.itemPromiseResolve())]; + } +}; +var Client = class Client { + get tracingMode() { + return this._tracingMode; + } + get _fetch() { + const fetchImplementation = this.fetchImplementation || _getFetchImplementation(this.debug); + return (async (input, init) => { + let authHeader; + const profileManagedAuthorization = this.getProfileManagedAuthorizationHeader(init); + if (this.apiKey !== void 0) authHeader = { + name: "x-api-key", + value: `${this.apiKey}` + }; + else if (!this.hasExplicitAuthHeader(init, profileManagedAuthorization)) authHeader = await this.profileAuth?.getAuthHeader(fetchImplementation, init?.signal); + return fetchImplementation(input, this.applyCurrentAuthHeaders(init, authHeader, profileManagedAuthorization)); + }); + } + getProfileManagedAuthorizationHeader(init) { + if (!init?.headers || !this.profileAuth) return; + const authorization = new Headers(init.headers).get("Authorization"); + if (!hasValue(authorization)) return; + return this.profileAuth.isProfileAuthorizationHeader(authorization ?? "") ? authorization ?? void 0 : void 0; + } + isProfileManagedAuthorizationHeader(value, profileManagedAuthorization) { + return value === profileManagedAuthorization || this.profileAuth?.isProfileAuthorizationHeader(value) === true; + } + hasExplicitAuthHeader(init, profileManagedAuthorization) { + if (!init?.headers) return false; + const headers = new Headers(init.headers); + if (hasValue(headers.get("x-api-key"))) return true; + const authorization = headers.get("Authorization"); + if (!hasValue(authorization)) return false; + return !this.isProfileManagedAuthorizationHeader(authorization ?? "", profileManagedAuthorization); + } + applyCurrentAuthHeaders(init, authHeader, profileManagedAuthorization) { + if (!authHeader) return init; + const applyAuth = (headers) => { + if (this.apiKey !== void 0 && authHeader.name === "x-api-key") { + headers.delete("Authorization"); + if (!headers.has("x-api-key")) headers.set("x-api-key", authHeader.value); + return headers; + } + if (authHeader.name === "Authorization") { + if (hasValue(headers.get("x-api-key"))) return headers; + const authorization = headers.get("Authorization"); + if (hasValue(authorization) && !this.isProfileManagedAuthorizationHeader(authorization ?? "", profileManagedAuthorization)) return headers; + headers.set("Authorization", authHeader.value); + return headers; + } + const authorization = headers.get("Authorization"); + if (hasValue(authorization) && !this.isProfileManagedAuthorizationHeader(authorization ?? "", profileManagedAuthorization)) return headers; + if (hasValue(authorization)) headers.delete("Authorization"); + if (!headers.has("x-api-key")) headers.set("x-api-key", authHeader.value); + return headers; + }; + if (!init) return { headers: { [authHeader.name]: authHeader.value } }; + if (init.headers instanceof Headers) return { + ...init, + headers: applyAuth(new Headers(init.headers)) + }; + if (Array.isArray(init.headers)) return { + ...init, + headers: applyAuth(new Headers(init.headers)) + }; + const headers = { ...init.headers ?? {} }; + const getHeaderKey = (name) => Object.keys(headers).find((key) => key.toLowerCase() === name); + const getHeader = (name) => { + const key = getHeaderKey(name); + return key ? headers[key] : void 0; + }; + const hasApiKey = hasValue(getHeader("x-api-key")); + const authorization = getHeader("authorization"); + const hasExplicitAuthorization = hasValue(authorization) && !this.isProfileManagedAuthorizationHeader(authorization ?? "", profileManagedAuthorization); + if (this.apiKey !== void 0 && authHeader.name === "x-api-key") { + const authorizationKey = getHeaderKey("authorization"); + if (authorizationKey) delete headers[authorizationKey]; + if (!hasApiKey) headers["x-api-key"] = authHeader.value; + return { + ...init, + headers + }; + } + if (authHeader.name === "Authorization") { + if (!hasApiKey && !hasExplicitAuthorization) { + const authorizationKey = getHeaderKey("authorization"); + if (authorizationKey && authorizationKey !== "Authorization") delete headers[authorizationKey]; + headers.Authorization = authHeader.value; + } + return { + ...init, + headers + }; + } + if (!hasExplicitAuthorization) { + const authorizationKey = getHeaderKey("authorization"); + if (authorizationKey) delete headers[authorizationKey]; + if (!hasApiKey) headers["x-api-key"] = authHeader.value; + } + return { + ...init, + headers + }; + } + /** + * Serialize a payload for tracing, optionally offloading the work to a + * Node worker thread when the runtime supports worker_threads. + * + * Falls back to synchronous serialization when: + * - manualFlushMode is enabled (serverless: worker boot cost > benefit) + * - worker_threads is unavailable (non-Node runtimes) + * - the payload contains values that can't be structured-cloned across + * threads (functions, non-cloneable class instances, streams, etc.) + * - the worker throws for any other reason + * + * In all fallback cases the returned bytes are identical to the sync path. + */ + _trackDrain(promise) { + this._pendingDrains.add(promise); + promise.finally(() => { + this._pendingDrains.delete(promise); + }); + } + async _serializeBody(payload, errorContext) { + if (this.manualFlushMode) return serialize(payload, errorContext); + if (!hasLargeString(payload)) return serialize(payload, errorContext); + if (this._serializeWorker === void 0) this._serializeWorker = getSharedSerializeWorker(); + if (this._serializeWorker === null) return serialize(payload, errorContext); + try { + const bytes = await this._serializeWorker.serialize(payload); + if (bytes === null) { + this._serializeWorker = null; + return serialize(payload, errorContext); + } + return bytes; + } catch { + return serialize(payload, errorContext); + } + } + 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, "workspaceId", { + 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, "hideMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "anonymizer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "omitTracedRuntimeInfo", { + 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, "filteredPostUuids", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Set() + }); + Object.defineProperty(this, "autoBatchTracing", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "autoBatchQueue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "autoBatchTimeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "autoBatchAggregationDelayMs", { + enumerable: true, + configurable: true, + writable: true, + value: 250 + }); + Object.defineProperty(this, "batchSizeBytesLimit", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "batchSizeLimit", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetchOptions", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "openAPIClient", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settings", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "blockOnRootRunFinalization", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" + }); + Object.defineProperty(this, "traceBatchConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: 5 + }); + Object.defineProperty(this, "_serverInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_getServerInfoPromise", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "manualFlushMode", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "_serializeWorker", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Tracks in-flight drainAutoBatchQueue promises so awaitPendingTraceBatches + * can wait on them even if the flush involves async work (worker-thread + * serialize) that hasn't yet registered with batchIngestCaller.queue. + */ + Object.defineProperty(this, "_pendingDrains", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Set() + }); + Object.defineProperty(this, "langSmithToOTELTranslator", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_tracingMode", { + enumerable: true, + configurable: true, + writable: true, + value: "langsmith" + }); + Object.defineProperty(this, "fetchImplementation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cachedLSEnvVarsForMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_promptCache", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "profileAuth", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "multipartStreamingDisabled", { + enumerable: true, + configurable: true, + writable: true, + value: getLangSmithEnvironmentVariable("DISABLE_MULTIPART_STREAMING") === "true" + }); + Object.defineProperty(this, "_multipartDisabled", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "_runCompressionDisabled", { + enumerable: true, + configurable: true, + writable: true, + value: getLangSmithEnvironmentVariable("DISABLE_RUN_COMPRESSION") === "true" + }); + Object.defineProperty(this, "failedTracesDir", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "failedTracesMaxBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 100 * 1024 * 1024 + }); + Object.defineProperty(this, "_customHeaders", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_DEBUG") === "true" + }); + const defaultConfig = Client.getDefaultClientConfig(); + this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); + this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; + if (this.apiUrl.endsWith("/")) this.apiUrl = this.apiUrl.slice(0, -1); + const configuredApiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); + this.apiKey = hasValue(configuredApiKey) ? configuredApiKey : void 0; + this.profileAuth = this.apiKey !== void 0 ? void 0 : defaultConfig.profileAuth; + this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); + if (this.webUrl?.endsWith("/")) this.webUrl = this.webUrl.slice(0, -1); + this.workspaceId = trimQuotes(config.workspaceId ?? defaultConfig.workspaceId); + this.timeout_ms = config.timeout_ms ?? 9e4; + this.caller = new AsyncCaller$1({ + ...config.callerOptions ?? {}, + maxRetries: 4, + debug: config.debug ?? this.debug + }); + this.traceBatchConcurrency = config.traceBatchConcurrency ?? this.traceBatchConcurrency; + if (this.traceBatchConcurrency < 1) throw new Error("Trace batch concurrency must be positive."); + this.debug = config.debug ?? this.debug; + this.fetchImplementation = config.fetchImplementation; + this.failedTracesDir = getLangSmithEnvironmentVariable("FAILED_TRACES_DIR") || void 0; + const failedTracesMb = getLangSmithEnvironmentVariable("FAILED_TRACES_MAX_MB"); + if (failedTracesMb) { + const n = parseInt(failedTracesMb, 10); + if (Number.isFinite(n) && n > 0) this.failedTracesMaxBytes = n * 1024 * 1024; + } + const maxMemory = config.maxIngestMemoryBytes ?? 1073741824; + this.batchIngestCaller = new AsyncCaller$1({ + maxRetries: 4, + maxConcurrency: this.traceBatchConcurrency, + maxQueueSizeBytes: maxMemory, + ...config.callerOptions ?? {}, + onFailedResponseHook: handle429, + debug: config.debug ?? this.debug + }); + this.hideInputs = config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; + this.hideOutputs = config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; + this.hideMetadata = config.hideMetadata ?? defaultConfig.hideMetadata; + this.anonymizer = config.anonymizer; + this.omitTracedRuntimeInfo = config.omitTracedRuntimeInfo ?? false; + this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; + this.autoBatchQueue = new AutoBatchQueue(maxMemory); + this.blockOnRootRunFinalization = config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; + this.batchSizeBytesLimit = config.batchSizeBytesLimit; + this.batchSizeLimit = config.batchSizeLimit; + this.fetchOptions = config.fetchOptions || {}; + this.openAPIClient = this._newOpenAPIClient(); + this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; + this._tracingMode = resolveTracingMode(config.tracingMode); + if (this._tracingMode === "otel") this.langSmithToOTELTranslator = new LangSmithToOTELTranslator(); + this.cachedLSEnvVarsForMetadata = getLangSmithEnvVarsMetadata(); + if (config.cache !== void 0 && config.disablePromptCache) warnOnce("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."); + if (config.cache !== void 0) { + warnOnce("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."); + if (config.cache === false) this._promptCache = void 0; + else if (config.cache === true) this._promptCache = promptCacheSingleton; + else this._promptCache = config.cache; + } else if (!config.disablePromptCache) this._promptCache = promptCacheSingleton; + this._customHeaders = config.headers ?? {}; + } + static getDefaultClientConfig() { + const profileConfig = loadProfileClientConfig(); + const envApiKey = getLangSmithEnvironmentVariable("API_KEY"); + const envApiUrl = getLangSmithEnvironmentVariable("ENDPOINT"); + const envWorkspaceId = getLangSmithEnvironmentVariable("WORKSPACE_ID"); + const envAuthSet = hasValue(envApiKey); + const apiUrl = envApiUrl ?? profileConfig.apiUrl ?? "https://api.smith.langchain.com"; + const workspaceId = envWorkspaceId ?? profileConfig.workspaceId; + return { + apiUrl, + apiKey: envApiKey, + webUrl: void 0, + hideInputs: getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true", + hideOutputs: getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true", + hideMetadata: getLangSmithEnvironmentVariable("HIDE_METADATA") === "true", + workspaceId, + oauthAccessToken: !envAuthSet ? profileConfig.oauthAccessToken : void 0, + oauthRefreshToken: !envAuthSet ? profileConfig.oauthRefreshToken : void 0, + profileAuth: !envAuthSet ? profileConfig.profileAuth : void 0 + }; + } + getHostUrl() { + if (this.webUrl) return this.webUrl; + else if (isLocalhost(this.apiUrl)) { + this.webUrl = "http://localhost:3000"; + return this.webUrl; + } else if (this.apiUrl.endsWith("/api/v1")) { + this.webUrl = this.apiUrl.replace("/api/v1", ""); + return this.webUrl; + } 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 this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("eu")) { + this.webUrl = "https://eu.smith.langchain.com"; + return this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("aws")) { + this.webUrl = "https://aws.smith.langchain.com"; + return this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("apac")) { + this.webUrl = "https://apac.smith.langchain.com"; + return this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("beta")) { + this.webUrl = "https://beta.smith.langchain.com"; + return this.webUrl; + } else { + this.webUrl = "https://smith.langchain.com"; + return this.webUrl; + } + } + get _mergedHeaders() { + const headers = { + "User-Agent": `langsmith-js/${__version__}`, + ...this._customHeaders + }; + if (this.apiKey !== void 0) headers["x-api-key"] = `${this.apiKey}`; + else { + const profileAuthHeader = this.profileAuth?.currentAuthHeader(); + if (profileAuthHeader) headers[profileAuthHeader.name] = profileAuthHeader.value; + } + if (this.workspaceId) headers["x-tenant-id"] = this.workspaceId; + return headers; + } + /** + * Get or set custom headers for the client. + * Custom headers are merged with default headers (User-Agent, x-api-key, x-tenant-id). + * Custom headers will not override the default required headers. + */ + get headers() { + return this._customHeaders; + } + set headers(value) { + this._customHeaders = value ?? {}; + } + _getOpenAPIBaseUrl() { + return this.apiUrl.endsWith("/v1") ? this.apiUrl.slice(0, -3) : this.apiUrl; + } + _newOpenAPIClient() { + const defaultHeaders = this.apiKey === void 0 && this.workspaceId === void 0 ? { "X-API-Key": null } : void 0; + const { method: _method, headers: _headers, body: _body, signal: _signal, ...openAPIFetchOptions } = this.fetchOptions; + return new Langsmith({ + apiKey: this.apiKey, + tenantID: this.workspaceId, + baseURL: this._getOpenAPIBaseUrl(), + timeout: this.timeout_ms, + fetch: this._fetch, + fetchOptions: openAPIFetchOptions, + defaultHeaders + }); + } + _getPlatformEndpointPath(path) { + return this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/" ? `/v1/platform/${path}` : `/platform/${path}`; + } + get evaluators() { + return this.openAPIClient.onlineEvaluators; + } + get runs() { + return this.openAPIClient.runs; + } + /** Access the v2 sandboxes resource (registries, snapshots, boxes). */ + get sandboxes() { + return this.openAPIClient.sandboxes; + } + /** Access the v2 datasets resource (experimentRuns, etc.). */ + get datasets() { + return this.openAPIClient.datasets; + } + async processInputs(inputs) { + if (this.hideInputs === false) return inputs; + if (this.hideInputs === true) return {}; + if (typeof this.hideInputs === "function") return this.hideInputs(inputs); + return inputs; + } + async processOutputs(outputs) { + if (this.hideOutputs === false) return outputs; + if (this.hideOutputs === true) return {}; + if (typeof this.hideOutputs === "function") return this.hideOutputs(outputs); + return outputs; + } + async processMetadata(metadata) { + if (this.hideMetadata === false) return metadata; + if (this.hideMetadata === true) return {}; + if (typeof this.hideMetadata === "function") return this.hideMetadata(metadata); + return metadata; + } + /** + * Apply the configured anonymizer to a run's error string. + * + * Unlike inputs/outputs, `error` is a plain string (an exception message or + * traceback) that can carry credentials the user never explicitly logged -- + * e.g. an HTTP-client error whose message embeds an `Authorization` header. + * The anonymizer is typed `(KVMap) => KVMap`, so the string is wrapped as + * `{ error }`, scrubbed, and unwrapped. Mirrors the Python SDK's + * `Client._hide_run_error`. + * + * TODO: Update anonymizer to always nest inputs/outputs/error for consistency + */ + async processError(error) { + if (this.anonymizer == null) return error; + const result = await this.anonymizer({ error }); + return typeof result?.error === "string" ? result.error : error; + } + /** + * Filter content from new_token events to prevent streaming LLM output + * from being uploaded via events. + */ + _filterNewTokenEvents(events) { + if (!events || events.length === 0) return events; + return events.map((event) => { + if (event.name === "new_token") { + const { kwargs: _, ...rest } = event; + return rest; + } + return event; + }); + } + async prepareRunCreateOrUpdateInputs(run) { + const runParams = { ...run }; + if (runParams.inputs !== void 0) runParams.inputs = await this.processInputs(runParams.inputs); + if (runParams.outputs !== void 0) runParams.outputs = await this.processOutputs(runParams.outputs); + if (runParams.error !== void 0) runParams.error = await this.processError(runParams.error); + if (runParams.extra != null && "metadata" in runParams.extra) runParams.extra = { + ...runParams.extra, + metadata: await this.processMetadata(runParams.extra.metadata) + }; + if (runParams.events !== void 0) runParams.events = this._filterNewTokenEvents(runParams.events); + return runParams; + } + async _getResponse(path, queryParams) { + const paramsString = queryParams?.toString() ?? ""; + const url = `${this.apiUrl}${path}?${paramsString}`; + return await this.caller.call(async () => { + const res = await this._fetch(url, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, `fetch ${path}`); + return res; + }); + } + async _get(path, queryParams) { + return (await this._getResponse(path, queryParams)).json(); + } + async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { + 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(async () => { + const res = await this._fetch(url, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, `fetch ${path}`); + return res; + }); + const items = transform ? transform(await response.json()) : 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 body = JSON.stringify(bodyParams); + const responseBody = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${path}`, { + method: requestMethod, + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, `fetch ${path}`); + return res; + })).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; + } + } + _shouldSample() { + if (this.tracingSampleRate === void 0) return true; + return Math.random() < this.tracingSampleRate; + } + _filterForSampling(runs, patch = false) { + if (this.tracingSampleRate === void 0) return runs; + if (patch) { + const sampled = []; + for (const run of runs) if (!this.filteredPostUuids.has(run.trace_id)) sampled.push(run); + else if (run.id === run.trace_id) this.filteredPostUuids.delete(run.trace_id); + return sampled; + } else { + const sampled = []; + for (const run of runs) { + const traceId = run.trace_id ?? run.id; + if (this.filteredPostUuids.has(traceId)) continue; + if (run.id === traceId) if (this._shouldSample()) sampled.push(run); + else this.filteredPostUuids.add(traceId); + else sampled.push(run); + } + return sampled; + } + } + async _getBatchSizeLimitBytes() { + const serverInfo = await this._ensureServerInfo(); + return this.batchSizeBytesLimit ?? serverInfo?.batch_ingest_config?.size_limit_bytes ?? 25165824; + } + /** + * Get the maximum number of operations to batch in a single request. + */ + async _getBatchSizeLimit() { + const serverInfo = await this._ensureServerInfo(); + return this.batchSizeLimit ?? serverInfo?.batch_ingest_config?.size_limit ?? DEFAULT_BATCH_SIZE_LIMIT; + } + async _getDatasetExamplesMultiPartSupport() { + return (await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled ?? false; + } + drainAutoBatchQueue({ batchSizeLimitBytes, batchSizeLimit }) { + const promises = []; + while (this.autoBatchQueue.items.length > 0) { + const [batch, done] = this.autoBatchQueue.pop({ + upToSizeBytes: batchSizeLimitBytes, + upToSize: batchSizeLimit + }); + if (!batch.length) { + done(); + break; + } + const batchesByDestination = batch.reduce((acc, item) => { + const apiUrl = item.apiUrl ?? this.apiUrl; + const apiKey = item.apiKey ?? this.apiKey; + const batchKey = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl ? "default" : `${apiUrl}|${apiKey}`; + if (!acc[batchKey]) acc[batchKey] = []; + acc[batchKey].push(item); + return acc; + }, {}); + const batchPromises = []; + for (const [batchKey, batch] of Object.entries(batchesByDestination)) { + const batchPromise = this._processBatch(batch, { + apiUrl: batchKey === "default" ? void 0 : batchKey.split("|")[0], + apiKey: batchKey === "default" ? void 0 : batchKey.split("|")[1] + }); + batchPromises.push(batchPromise); + } + const allBatchesPromise = Promise.all(batchPromises).finally(done); + promises.push(allBatchesPromise); + } + return Promise.all(promises); + } + /** + * Persist a failed trace payload to a local fallback directory. + * + * Saves a self-contained JSON file containing the endpoint path, the HTTP + * headers required for replay, and the base64-encoded request body. + * Can be replayed later with a simple POST: + * + * POST / + * Content-Type: + * [Content-Encoding: ] + * + */ + static async _writeTraceToFallbackDir(directory, body, replayHeaders, endpoint, maxBytes) { + try { + const bodyBuffer = typeof body === "string" ? Buffer.from(body, "utf8") : Buffer.from(body); + const envelope = JSON.stringify({ + version: 1, + endpoint, + headers: replayHeaders, + body_base64: bodyBuffer.toString("base64") + }); + const filename = `trace_${Date.now()}_${v4().slice(0, 8)}.json`; + const filepath = path$2.join(directory, filename); + if (!Client._fallbackDirsCreated.has(directory)) { + await mkdir$1(directory); + Client._fallbackDirsCreated.add(directory); + } + if (maxBytes !== void 0 && maxBytes > 0) try { + const traceFiles = (await readdir$1(directory)).filter((f) => f.startsWith("trace_") && f.endsWith(".json")); + let total = 0; + for (const name of traceFiles) { + const { size } = await stat$1(path$2.join(directory, name)); + total += size; + } + if (total >= maxBytes) { + console.warn(`Could not write trace to fallback dir ${directory} as it's already over size limit (${total} bytes >= ${maxBytes} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`); + return; + } + } catch {} + await writeFileAtomic(filepath, envelope); + console.warn(`LangSmith trace upload failed; data saved to ${filepath} for later replay.`); + } catch (writeErr) { + console.error(`LangSmith tracing error: could not write trace to fallback dir ${directory}:`, writeErr); + } + } + async _processBatch(batch, options) { + if (!batch.length) return; + const batchSizeBytes = batch.reduce((sum, item) => sum + (item.size ?? 0), 0); + try { + if (this.langSmithToOTELTranslator !== void 0) this._sendBatchToOTELTranslator(batch); + else { + const ingestParams = { + runCreates: batch.filter((item) => item.action === "create").map((item) => item.item), + runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item) + }; + const serverInfo = await this._ensureServerInfo(); + if (!this._multipartDisabled && (serverInfo?.batch_ingest_config?.use_multipart_endpoint ?? true)) { + const useGzip = !this._runCompressionDisabled && serverInfo?.instance_flags?.gzip_body_enabled; + try { + await this.multipartIngestRuns(ingestParams, { + ...options, + useGzip, + sizeBytes: batchSizeBytes + }); + } catch (e) { + if (isLangSmithNotFoundError(e)) { + this._multipartDisabled = true; + await this.batchIngestRuns(ingestParams, { + ...options, + sizeBytes: batchSizeBytes + }); + } else throw e; + } + } else await this.batchIngestRuns(ingestParams, { + ...options, + sizeBytes: batchSizeBytes + }); + } + } catch (e) { + console.error("Error exporting batch:", e); + } + } + _sendBatchToOTELTranslator(batch) { + if (this.langSmithToOTELTranslator !== void 0) { + const otelContextMap = /* @__PURE__ */ new Map(); + const operations = []; + for (const item of batch) if (item.item.id && item.otelContext) { + otelContextMap.set(item.item.id, item.otelContext); + if (item.action === "create") operations.push({ + operation: "post", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item + }); + else operations.push({ + operation: "patch", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item + }); + } + this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap); + } + } + async processRunOperation(item) { + clearTimeout(this.autoBatchTimeout); + this.autoBatchTimeout = void 0; + item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo); + const itemPromise = this.autoBatchQueue.push(item); + if (this.manualFlushMode) return itemPromise; + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + const sizeLimit = await this._getBatchSizeLimit(); + if (this.autoBatchQueue.sizeBytes > sizeLimitBytes || this.autoBatchQueue.items.length > sizeLimit) this._trackDrain(this.drainAutoBatchQueue({ + batchSizeLimitBytes: sizeLimitBytes, + batchSizeLimit: sizeLimit + })); + if (this.autoBatchQueue.items.length > 0) this.autoBatchTimeout = setTimeout(() => { + this.autoBatchTimeout = void 0; + this._trackDrain(this.drainAutoBatchQueue({ + batchSizeLimitBytes: sizeLimitBytes, + batchSizeLimit: sizeLimit + })); + }, this.autoBatchAggregationDelayMs); + return itemPromise; + } + async _getServerInfo() { + const json = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/info`, { + method: "GET", + headers: { + ...this._mergedHeaders, + Accept: "application/json" + }, + signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT_MS), + ...this.fetchOptions + }); + await raiseForStatus(res, "get server info"); + return res; + })).json(); + if (this.debug) console.log("\n=== LangSmith Server Configuration ===\n" + JSON.stringify(json, null, 2) + "\n"); + return json; + } + async _ensureServerInfo() { + if (this._getServerInfoPromise === void 0) this._getServerInfoPromise = (async () => { + if (this._serverInfo === void 0) try { + this._serverInfo = await this._getServerInfo(); + if (this._serverInfo?.version) _checkBackendVersion(this._serverInfo.version); + } catch (e) { + console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status ?? "Unspecified status code"} ${e.message}`); + } + return this._serverInfo ?? {}; + })(); + return this._getServerInfoPromise.then((serverInfo) => { + if (this._serverInfo === void 0) this._getServerInfoPromise = void 0; + return serverInfo; + }); + } + async _getSettings() { + if (!this.settings) this.settings = this._get("/settings"); + return await this.settings; + } + /** + * Flushes current queued traces. + */ + async flush() { + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + const sizeLimit = await this._getBatchSizeLimit(); + await this.drainAutoBatchQueue({ + batchSizeLimitBytes: sizeLimitBytes, + batchSizeLimit: sizeLimit + }); + } + _cloneCurrentOTELContext() { + const otel_trace = getOTELTrace(); + const otel_context = getOTELContext(); + if (this.langSmithToOTELTranslator !== void 0) { + const currentSpan = otel_trace.getActiveSpan(); + if (currentSpan) return otel_trace.setSpan(otel_context.active(), currentSpan); + } + } + async createRun(run, options) { + if (!this._filterForSampling([run]).length) return; + const headers = { + ...this._mergedHeaders, + "Content-Type": "application/json" + }; + const session_name = run.project_name; + delete run.project_name; + const runCreate = await 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) { + const otelContext = this._cloneCurrentOTELContext(); + this.processRunOperation({ + action: "create", + item: runCreate, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl + }).catch(console.error); + return; + } + const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo); + if (options?.apiKey !== void 0) headers["x-api-key"] = options.apiKey; + if (options?.workspaceId !== void 0) headers["x-tenant-id"] = options.workspaceId; + const body = serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`); + await this.caller.call(async () => { + const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs`, { + method: "POST", + headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "create run", true); + return res; + }); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async batchIngestRuns({ runCreates, runUpdates }, options) { + if (runCreates === void 0 && runUpdates === void 0) return; + let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); + let preparedUpdateParams = await Promise.all(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: preparedCreateParams, + patch: preparedUpdateParams + }; + if (!rawBatch.post.length && !rawBatch.patch.length) return; + const batchChunks = { + post: [], + patch: [] + }; + for (const k of ["post", "patch"]) { + const key = k; + const batchItems = rawBatch[key].reverse(); + let batchItem = batchItems.pop(); + while (batchItem !== void 0) { + batchChunks[key].push(batchItem); + batchItem = batchItems.pop(); + } + } + if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { + const runIds = batchChunks.post.map((item) => item.id).concat(batchChunks.patch.map((item) => item.id)).join(","); + await this._postBatchIngestRuns(await this._serializeBody(batchChunks, `Ingesting runs with ids: ${runIds}`), options); + } + } + async _postBatchIngestRuns(body, options) { + const headers = { + ...this._mergedHeaders, + "Content-Type": "application/json", + Accept: "application/json" + }; + if (options?.apiKey !== void 0) headers["x-api-key"] = options.apiKey; + await this.batchIngestCaller.callWithOptions({ sizeBytes: options?.sizeBytes }, async () => { + const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/batch`, { + method: "POST", + headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "batch create run", true); + return res; + }); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async multipartIngestRuns({ runCreates, runUpdates }, options) { + if (runCreates === void 0 && runUpdates === void 0) return; + const allAttachments = {}; + let preparedCreateParams = []; + for (const create of runCreates ?? []) { + const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); + if (preparedCreate.id !== void 0 && preparedCreate.attachments !== void 0) allAttachments[preparedCreate.id] = preparedCreate.attachments; + delete preparedCreate.attachments; + preparedCreateParams.push(preparedCreate); + } + let preparedUpdateParams = []; + for (const update of runUpdates ?? []) preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); + if (preparedCreateParams.find((runCreate) => { + return runCreate.trace_id === void 0 || runCreate.dotted_order === void 0; + }) !== void 0) throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); + if (preparedUpdateParams.find((runUpdate) => { + return runUpdate.trace_id === void 0 || runUpdate.dotted_order === void 0; + }) !== void 0) throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); + 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; + } + if (preparedCreateParams.length === 0 && preparedUpdateParams.length === 0) return; + const accumulatedContext = []; + const accumulatedParts = []; + for (const [method, payloads] of [["post", preparedCreateParams], ["patch", preparedUpdateParams]]) for (const originalPayload of payloads) { + const { inputs, outputs, events, extra, error, serialized, attachments, ...payload } = originalPayload; + const fields = { + inputs, + outputs, + events, + extra, + error, + serialized + }; + const stringifiedPayload = await this._serializeBody(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}`, + payload: new Blob([stringifiedPayload], { type: `application/json; length=${stringifiedPayload.length}` }) + }); + for (const [key, value] of Object.entries(fields)) { + if (value === void 0) continue; + const stringifiedValue = await this._serializeBody(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}.${key}`, + payload: new Blob([stringifiedValue], { type: `application/json; length=${stringifiedValue.length}` }) + }); + } + if (payload.id !== void 0) { + const attachments = allAttachments[payload.id]; + if (attachments) { + delete allAttachments[payload.id]; + for (const [name, attachment] of Object.entries(attachments)) { + let contentType; + let content; + if (Array.isArray(attachment)) [contentType, content] = attachment; + else { + contentType = attachment.mimeType; + content = attachment.data; + } + if (name.includes(".")) { + console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); + continue; + } + accumulatedParts.push({ + name: `attachment.${payload.id}.${name}`, + payload: new Blob([content], { type: `${contentType}; length=${content.byteLength}` }) + }); + } + } + } + accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); + } + await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "), options); + } + async _createNodeFetchBody(parts, boundary) { + const chunks = []; + for (const part of parts) { + chunks.push(new Blob([`--${boundary}\r\n`])); + chunks.push(new Blob([`Content-Disposition: form-data; name="${part.name}"\r\n`, `Content-Type: ${part.payload.type}\r\n\r\n`])); + chunks.push(part.payload); + chunks.push(new Blob(["\r\n"])); + } + chunks.push(new Blob([`--${boundary}--\r\n`])); + return await new Blob(chunks).arrayBuffer(); + } + async _createMultipartStream(parts, boundary) { + const encoder = new TextEncoder(); + return new ReadableStream({ async start(controller) { + const writeChunk = async (chunk) => { + if (typeof chunk === "string") controller.enqueue(encoder.encode(chunk)); + else controller.enqueue(chunk); + }; + for (const part of parts) { + await writeChunk(`--${boundary}\r\n`); + await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r\n`); + await writeChunk(`Content-Type: ${part.payload.type}\r\n\r\n`); + const reader = part.payload.stream().getReader(); + try { + let result; + while (!(result = await reader.read()).done) controller.enqueue(result.value); + } finally { + reader.releaseLock(); + } + await writeChunk("\r\n"); + } + await writeChunk(`--${boundary}--\r\n`); + controller.close(); + } }); + } + async _sendMultipartRequest(parts, context, options) { + const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); + const buildBuffered = () => this._createNodeFetchBody(parts, boundary); + const buildStream = () => this._createMultipartStream(parts, boundary); + const sendWithRetry = async (bodyFactory) => { + return this.batchIngestCaller.callWithOptions({ sizeBytes: options?.sizeBytes }, async () => { + const body = await bodyFactory(); + const headers = { + ...this._mergedHeaders, + "Content-Type": `multipart/form-data; boundary=${boundary}` + }; + if (options?.apiKey !== void 0) headers["x-api-key"] = options.apiKey; + let transformedBody = body; + if (options?.useGzip && typeof body === "object" && "pipeThrough" in body) { + transformedBody = body.pipeThrough(new CompressionStream("gzip")); + headers["Content-Encoding"] = "gzip"; + } + const response = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/multipart`, { + method: "POST", + headers, + body: transformedBody, + duplex: "half", + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `Failed to send multipart request`, true); + return response; + }); + }; + try { + let res; + let streamedAttempt = false; + if (_shouldStreamForGlobalFetchImplementation() && !this.multipartStreamingDisabled && getEnv() !== "bun") { + streamedAttempt = true; + res = await sendWithRetry(buildStream); + } else res = await sendWithRetry(buildBuffered); + if ((!this.multipartStreamingDisabled || streamedAttempt) && res.status === 422 && (options?.apiUrl ?? this.apiUrl) !== "https://api.smith.langchain.com") { + console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${context}".`); + this.multipartStreamingDisabled = true; + res = await sendWithRetry(buildBuffered); + } + } catch (e) { + if (isLangSmithNotFoundError(e)) throw e; + console.warn(`${e.message.trim()}\n\nContext: ${context}`); + if (this.failedTracesDir) { + const bodyBuffer = await this._createNodeFetchBody(parts, boundary).catch(() => null); + if (bodyBuffer) await Client._writeTraceToFallbackDir(this.failedTracesDir, bodyBuffer, { "Content-Type": `multipart/form-data; boundary=${boundary}` }, "runs/multipart", this.failedTracesMaxBytes); + } + } + } + async updateRun(runId, run, options) { + assertUuid(runId); + if (run.inputs) run.inputs = await this.processInputs(run.inputs); + if (run.outputs) run.outputs = await this.processOutputs(run.outputs); + if (run.error) run.error = await this.processError(run.error); + if (run.extra != null && "metadata" in run.extra) run.extra = { + ...run.extra, + metadata: await this.processMetadata(run.extra.metadata) + }; + if (run.events) run.events = this._filterNewTokenEvents(run.events); + 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) { + const otelContext = this._cloneCurrentOTELContext(); + if (run.end_time !== void 0 && data.parent_run_id === void 0 && this.blockOnRootRunFinalization && !this.manualFlushMode) { + await this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl + }).catch(console.error); + return; + } else this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl + }).catch(console.error); + return; + } + const headers = { + ...this._mergedHeaders, + "Content-Type": "application/json" + }; + if (options?.apiKey !== void 0) headers["x-api-key"] = options.apiKey; + if (options?.workspaceId !== void 0) headers["x-tenant-id"] = options.workspaceId; + const body = serialize(run, `Serializing payload to update run with id: ${runId}`); + await this.caller.call(async () => { + const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, { + method: "PATCH", + headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "update run", true); + return res; + }); + } + async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { + assertUuid(runId); + let run = _normalizeRunTimestamps(await this._get(`/runs/${runId}`)); + if (loadChildRuns) 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 sessionId = (await this.readProject({ projectName: getLangSmithEnvironmentVariable("PROJECT") || "default" })).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`); + return `${this.getHostUrl()}${run_.app_path}`; + } else throw new Error("Must provide either runId or run"); + } + async _loadChildRuns(run) { + const childRuns = await toArray(this.listRuns({ + isRoot: false, + projectId: run.session_id, + traceId: run.trace_id + })); + const treemap = {}; + const runs = {}; + childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.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.dotted_order?.startsWith(run.dotted_order ?? "") && childRun.id !== run.id) { + 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; + } + /** + * List runs from the LangSmith server. + * @param projectId - The ID of the project to filter by. + * @param projectName - The name of the project to filter by. + * @param parentRunId - The ID of the parent run to filter by. + * @param traceId - The ID of the trace to filter by. + * @param referenceExampleId - The ID of the reference example to filter by. + * @param startTime - The start time to filter by. + * @param isRoot - Indicates whether to only return root runs. + * @param runType - The run type to filter by. + * @param error - Indicates whether to filter by error runs. + * @param id - The ID of the run to filter by. + * @param query - The query string to filter by. + * @param filter - The filter string to apply to the run spans. + * @param traceFilter - The filter string to apply on the root run of the trace. + * @param treeFilter - The filter string to apply on other runs in the trace. + * @param limit - The maximum number of runs to retrieve. + * @returns {AsyncIterable} - The runs. + * + * @example + * // List all runs in a project + * const projectRuns = client.listRuns({ projectName: "" }); + * + * @example + * // List LLM and Chat runs in the last 24 hours + * const todaysLLMRuns = client.listRuns({ + * projectName: "", + * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), + * run_type: "llm", + * }); + * + * @example + * // List traces in a project + * const rootRuns = client.listRuns({ + * projectName: "", + * execution_order: 1, + * }); + * + * @example + * // List runs without errors + * const correctRuns = client.listRuns({ + * projectName: "", + * error: false, + * }); + * + * @example + * // List runs by run ID + * const runIds = [ + * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", + * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", + * ]; + * const selectedRuns = client.listRuns({ run_ids: runIds }); + * + * @example + * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 + * const chainRuns = client.listRuns({ + * projectName: "", + * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', + * }); + * + * @example + * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 + * const goodExtractorRuns = client.listRuns({ + * projectName: "", + * filter: 'eq(name, "extractor")', + * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', + * }); + * + * @example + * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 + * const complexRuns = client.listRuns({ + * projectName: "", + * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', + * }); + * + * @example + * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds + * const taggedRuns = client.listRuns({ + * projectName: "", + * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', + * }); + */ + async *listRuns(props) { + const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order } = 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((name) => this.readProject({ projectName: name }).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, + limit, + trace: traceId, + select: select ? select : [ + "app_path", + "completion_cost", + "completion_tokens", + "dotted_order", + "end_time", + "error", + "events", + "extra", + "feedback_stats", + "first_token_time", + "id", + "inputs", + "name", + "outputs", + "parent_run_id", + "parent_run_ids", + "prompt_cost", + "prompt_tokens", + "reference_example_id", + "run_type", + "session_id", + "start_time", + "status", + "tags", + "total_cost", + "total_tokens", + "trace_id" + ], + is_root: isRoot, + order + }; + if (body.select.includes("child_run_ids")) warnOnce("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version."); + let runsYielded = 0; + for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { + const normalized = runs.map(_normalizeRunTimestamps); + if (limit) { + if (runsYielded >= limit) break; + if (normalized.length + runsYielded > limit) { + yield* normalized.slice(0, limit - runsYielded); + break; + } + runsYielded += normalized.length; + yield* normalized; + } else yield* normalized; + } + } + async *listGroupRuns(props) { + const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset } = props; + const baseBody = { + session_id: projectId || (await this.readProject({ projectName })).id, + group_by: groupBy, + filter, + start_time: startTime ? startTime.toISOString() : null, + end_time: endTime ? endTime.toISOString() : null, + limit: Number(limit) || 100 + }; + let currentOffset = Number(offset) || 0; + const path = "/runs/group"; + const url = `${this.apiUrl}${path}`; + while (true) { + const currentBody = { + ...baseBody, + offset: currentOffset + }; + const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== void 0)); + const body = JSON.stringify(filteredPayload); + const { groups, total } = await (await this.caller.call(async () => { + const res = await this._fetch(url, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, `Failed to fetch ${path}`); + return res; + })).json(); + if (groups.length === 0) break; + for (const thread of groups) yield thread; + currentOffset += groups.length; + if (currentOffset >= total) break; + } + } + async *readThread(props) { + const { threadId, projectId, projectName, isRoot = true, limit, filter: userFilter, order = "asc" } = props; + if (!projectId && !projectName) throw new Error("threadId requires projectId or projectName"); + const threadFilter = `eq(thread_id, ${JSON.stringify(threadId)})`; + const combinedFilter = userFilter ? `and(${threadFilter}, ${userFilter})` : threadFilter; + yield* this.listRuns({ + projectId: projectId ?? void 0, + projectName: projectName ?? void 0, + isRoot, + limit, + filter: combinedFilter, + order + }); + } + async listThreads(props) { + const { projectId, projectName, limit, offset = 0, filter, startTime, isRoot = true } = props; + if (!projectId && !projectName) throw new Error("Either projectId or projectName must be provided"); + if (projectId && projectName) throw new Error("Provide exactly one of projectId or projectName"); + const sessionId = projectId ?? (await this.readProject({ projectName })).id; + const startTimeResolved = startTime ?? /* @__PURE__ */ new Date(Date.now() - 1440 * 60 * 1e3); + const bodyQuery = { + session: [sessionId], + is_root: isRoot, + limit: 100, + order: "desc", + select: [ + "id", + "name", + "status", + "start_time", + "end_time", + "thread_id", + "trace_id", + "run_type", + "error", + "tags", + "session_id", + "parent_run_id", + "total_tokens", + "total_cost", + "dotted_order", + "reference_example_id", + "feedback_stats", + "app_path", + "completion_cost", + "completion_tokens", + "prompt_cost", + "prompt_tokens", + "first_token_time" + ], + start_time: startTimeResolved.toISOString() + }; + if (filter != null) bodyQuery.filter = filter; + const threadsMap = /* @__PURE__ */ new Map(); + for await (const runs of this._getCursorPaginatedList("/runs/query", bodyQuery)) for (const raw of runs) { + const run = _normalizeRunTimestamps(raw); + const tid = run.thread_id; + if (tid) { + const list = threadsMap.get(tid) ?? []; + list.push(run); + threadsMap.set(tid, list); + } + } + const result = []; + for (const [threadId, runs] of threadsMap.entries()) { + runs.sort((a, b) => { + const aRun = a; + const bRun = b; + const aStart = aRun.start_time ?? ""; + const bStart = bRun.start_time ?? ""; + if (aStart !== bStart) return aStart.localeCompare(bStart); + const aOrder = aRun.dotted_order ?? ""; + const bOrder = bRun.dotted_order ?? ""; + return aOrder.localeCompare(bOrder); + }); + const sortedTimes = [...runs.map((r) => r.start_time).filter(Boolean)].sort(); + const minStart = sortedTimes.length ? sortedTimes[0] : ""; + const maxStart = sortedTimes.length ? sortedTimes[sortedTimes.length - 1] : ""; + result.push({ + thread_id: threadId, + runs, + count: runs.length, + filter: "", + total_tokens: 0, + total_cost: null, + min_start_time: minStart, + max_start_time: maxStart, + latency_p50: 0, + latency_p99: 0, + feedback_stats: null, + first_inputs: "", + last_outputs: "", + last_error: null + }); + } + result.sort((a, b) => { + const aMax = a.max_start_time ?? ""; + return (b.max_start_time ?? "").localeCompare(aMax); + }); + const withOffset = offset > 0 ? result.slice(offset) : result; + return limit !== void 0 ? withOffset.slice(0, limit) : withOffset; + } + async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType }) { + let projectIds_ = projectIds || []; + if (projectNames) projectIds_ = [...projectIds || [], ...await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))]; + const filteredPayload = Object.fromEntries(Object.entries({ + id, + trace, + parent_run: parentRun, + run_type: runType, + session: projectIds_, + reference_example: referenceExampleIds, + start_time: startTime, + end_time: endTime, + error, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + is_root: isRoot, + data_source_type: dataSourceType + }).filter(([_, value]) => value !== void 0)); + const body = JSON.stringify(filteredPayload); + return await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/runs/stats`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "get run stats"); + return res; + })).json(); + } + async shareRun(runId, { shareId } = {}) { + const data = { + run_id: runId, + share_token: shareId || v4() + }; + assertUuid(runId); + const body = JSON.stringify(data); + const result = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { + method: "PUT", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "share run"); + return res; + })).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); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "unshare run", true); + return res; + }); + } + async readRunSharedLink(runId) { + assertUuid(runId); + const result = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "read run shared link"); + return res; + })).json(); + if (result === null || !("share_token" in result)) return; + 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); + return (await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "list shared runs"); + return res; + })).json()).map(_normalizeRunTimestamps); + } + async readDatasetSharedSchema(datasetId, datasetName) { + if (!datasetId && !datasetName) throw new Error("Either datasetId or datasetName must be given"); + if (!datasetId) datasetId = (await this.readDataset({ datasetName })).id; + assertUuid(datasetId); + const shareSchema = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "read dataset shared schema"); + return res; + })).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) datasetId = (await this.readDataset({ datasetName })).id; + const data = { dataset_id: datasetId }; + assertUuid(datasetId); + const body = JSON.stringify(data); + const shareSchema = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { + method: "PUT", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "share dataset"); + return res; + })).json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async unshareDataset(datasetId) { + assertUuid(datasetId); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "unshare dataset", true); + return res; + }); + } + async readSharedDataset(shareToken) { + assertUuid(shareToken); + return await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/datasets`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "read shared dataset"); + return res; + })).json(); + } + /** + * Get shared examples. + * + * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. + * @param {Object} [options] Additional options for listing the examples. + * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. + * @returns {Promise} The shared examples. + */ + async listSharedExamples(shareToken, options) { + const params = {}; + if (options?.exampleIds) params.id = options.exampleIds; + const urlParams = new URLSearchParams(); + Object.entries(params).forEach(([key, value]) => { + if (Array.isArray(value)) value.forEach((v) => urlParams.append(key, v)); + else urlParams.append(key, value); + }); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "list shared examples"); + return res; + }); + const result = await response.json(); + if (!response.ok) { + if ("detail" in result) throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecified error"}`); + throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); + } + return result.map((example) => ({ + ...example, + _hostUrl: this.getHostUrl() + })); + } + async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, numExamples = null, numRepetitions = null, evaluatorKeys = 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 + }; + if (referenceDatasetId !== null) body["reference_dataset_id"] = referenceDatasetId; + if (numExamples != null) body["num_examples"] = numExamples; + if (numRepetitions != null) body["num_repetitions"] = numRepetitions; + if (evaluatorKeys != null && evaluatorKeys.length > 0) body["evaluator_keys"] = evaluatorKeys; + const serializedBody = JSON.stringify(body); + return await (await this.caller.call(async () => { + const res = await this._fetch(endpoint, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody + }); + await raiseForStatus(res, "create project"); + return res; + })).json(); + } + async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null }) { + const endpoint = `${this.apiUrl}/sessions/${projectId}`; + let extra = projectExtra; + if (metadata) extra = { + ...extra || {}, + metadata + }; + const body = JSON.stringify({ + name, + extra, + description, + end_time: endTime ? new Date(endTime).toISOString() : null + }); + return await (await this.caller.call(async () => { + const res = await this._fetch(endpoint, { + method: "PATCH", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "update project"); + return res; + })).json(); + } + 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(async () => { + const res = await this._fetch(`${this.apiUrl}${path}?${params}`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "has project"); + return res; + }); + try { + const result = await response.json(); + if (!response.ok) return false; + if (Array.isArray(result)) return result.length > 0; + return true; + } catch (_e) { + 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 getProjectUrl({ projectId, projectName }) { + if (projectId === void 0 && projectName === void 0) throw new Error("Must provide either projectName or projectId"); + const project = await this.readProject({ + projectId, + projectName + }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; + } + async getDatasetUrl({ datasetId, datasetName }) { + if (datasetId === void 0 && datasetName === void 0) throw new Error("Must provide either datasetName or datasetId"); + const dataset = await this.readDataset({ + datasetId, + datasetName + }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; + } + 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, nameContains, referenceDatasetId, referenceDatasetName, includeStats, datasetVersion, referenceFree, metadata } = {}) { + const params = new URLSearchParams(); + if (projectIds !== void 0) for (const projectId of projectIds) params.append("id", projectId); + if (name !== void 0) params.append("name", name); + 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 (includeStats !== void 0) params.append("include_stats", includeStats.toString()); + if (datasetVersion !== void 0) params.append("dataset_version", datasetVersion); + if (referenceFree !== void 0) params.append("reference_free", referenceFree.toString()); + if (metadata !== void 0) params.append("metadata", JSON.stringify(metadata)); + 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_); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/sessions/${projectId_}`, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, `delete session ${projectId_} (${projectName})`, true); + return res; + }); + } + async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name }) { + const url = `${this.apiUrl}/datasets/upload`; + const formData = new FormData(); + const csvBlob = new Blob([csvFile], { type: "text/csv" }); + formData.append("file", csvBlob, fileName); + inputKeys.forEach((key) => { + formData.append("input_keys", key); + }); + outputKeys.forEach((key) => { + formData.append("output_keys", key); + }); + if (description) formData.append("description", description); + if (dataType) formData.append("data_type", dataType); + if (name) formData.append("name", name); + return await (await this.caller.call(async () => { + const res = await this._fetch(url, { + method: "POST", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: formData + }); + await raiseForStatus(res, "upload CSV"); + return res; + })).json(); + } + async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata } = {}) { + const body = { + name, + description, + extra: { + source: "sdk", + ...metadata ? { metadata } : {} + } + }; + if (dataType) body.data_type = dataType; + if (inputsSchema) body.inputs_schema_definition = inputsSchema; + if (outputsSchema) body.outputs_schema_definition = outputsSchema; + const serializedBody = JSON.stringify(body); + return await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody + }); + await raiseForStatus(res, "create dataset"); + return res; + })).json(); + } + async readDataset({ datasetId, datasetName }) { + let path = "/datasets"; + const params = new URLSearchParams({ limit: "1" }); + if (datasetId && datasetName) throw new Error("Must provide either datasetName or datasetId, not both"); + else if (datasetId) { + assertUuid(datasetId); + path += `/${datasetId}`; + } else if (datasetName) 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 hasDataset({ datasetId, datasetName }) { + try { + await this.readDataset({ + datasetId, + datasetName + }); + return true; + } catch (e) { + if (e instanceof Error && e.message.toLocaleLowerCase().includes("not found")) return false; + throw e; + } + } + 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) datasetId_ = (await this.readDataset({ datasetName })).id; + const urlParams = new URLSearchParams({ + from_version: typeof fromVersion === "string" ? fromVersion : fromVersion.toISOString(), + to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString() + }); + return await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); + } + 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 either datasetName or datasetId"); + return (await (await this._getResponse(`${path}/${datasetId}/openai_ft`)).text()).trim().split("\n").map((line) => JSON.parse(line)); + } + async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata } = {}) { + 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); + if (metadata !== void 0) params.append("metadata", JSON.stringify(metadata)); + for await (const datasets of this._getPaginated(path, params)) yield* datasets; + } + /** + * Update a dataset + * @param props The dataset details to update + * @returns The updated dataset + */ + async updateDataset(props) { + const { datasetId, datasetName, ...update } = props; + if (!datasetId && !datasetName) throw new Error("Must provide either datasetName or datasetId"); + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const body = JSON.stringify(update); + return await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}`, { + method: "PATCH", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "update dataset"); + return res; + })).json(); + } + /** + * Updates a tag on a dataset. + * + * If the tag is already assigned to a different version of this dataset, + * the tag will be moved to the new version. The as_of parameter is used to + * determine which version of the dataset to apply the new tags to. + * + * It must be an exact version of the dataset to succeed. You can + * use the "readDatasetVersion" method to find the exact version + * to apply the tags to. + * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. + * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. + * @param params.asOf The timestamp of the dataset to apply the new tags to. + * @param params.tag The new tag to apply to the dataset. + */ + async updateDatasetTag(props) { + const { datasetId, datasetName, asOf, tag } = props; + if (!datasetId && !datasetName) throw new Error("Must provide either datasetName or datasetId"); + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const body = JSON.stringify({ + as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), + tag + }); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}/tags`, { + method: "PUT", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "update dataset tags", true); + return res; + }); + } + 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) datasetId_ = (await this.readDataset({ datasetName })).id; + if (datasetId_ !== void 0) { + assertUuid(datasetId_); + path += `/${datasetId_}`; + } else throw new Error("Must provide datasetName or datasetId"); + await this.caller.call(async () => { + const res = await this._fetch(this.apiUrl + path, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, `delete ${path}`, true); + return res; + }); + } + async createExample(inputsOrUpdate, outputs, options) { + if (isExampleCreate(inputsOrUpdate)) { + if (outputs !== void 0 || options !== void 0) throw new Error("Cannot provide outputs or options when using ExampleCreate object"); + } + let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; + const datasetName_ = outputs ? options?.datasetName : inputsOrUpdate.dataset_name; + 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) datasetId_ = (await this.readDataset({ datasetName: datasetName_ })).id; + const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || /* @__PURE__ */ new Date(); + let data; + if (!isExampleCreate(inputsOrUpdate)) data = { + inputs: inputsOrUpdate, + outputs, + created_at: createdAt_?.toISOString(), + id: options?.exampleId, + metadata: options?.metadata, + split: options?.split, + source_run_id: options?.sourceRunId, + use_source_run_io: options?.useSourceRunIO, + use_source_run_attachments: options?.useSourceRunAttachments, + attachments: options?.attachments + }; + else data = inputsOrUpdate; + const response = await this._uploadExamplesMultipart(datasetId_, [data]); + return await this.readExample(response.example_ids?.[0] ?? v4()); + } + async createExamples(propsOrUploads) { + if (Array.isArray(propsOrUploads)) { + if (propsOrUploads.length === 0) return []; + const uploads = propsOrUploads; + let datasetId_ = uploads[0].dataset_id; + const datasetName_ = uploads[0].dataset_name; + 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) datasetId_ = (await this.readDataset({ datasetName: datasetName_ })).id; + const response = await this._uploadExamplesMultipart(datasetId_, uploads); + return await Promise.all(response.example_ids.map((id) => this.readExample(id))); + } + const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName } = propsOrUploads; + if (inputs === void 0) throw new Error("Must provide inputs when using legacy parameters"); + let datasetId_ = datasetId; + const datasetName_ = datasetName; + 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) datasetId_ = (await this.readDataset({ datasetName: datasetName_ })).id; + const formattedExamples = inputs.map((input, idx) => { + return { + dataset_id: datasetId_, + inputs: input, + outputs: outputs?.[idx], + metadata: metadata?.[idx], + split: splits?.[idx], + id: exampleIds?.[idx], + attachments: attachments?.[idx], + source_run_id: sourceRunIds?.[idx], + use_source_run_io: useSourceRunIOs?.[idx], + use_source_run_attachments: useSourceRunAttachments?.[idx] + }; + }); + const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); + return await Promise.all(response.example_ids.map((id) => this.readExample(id))); + } + 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}`; + const { attachment_urls, ...rest } = await this._get(path); + const example = rest; + if (attachment_urls) example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice(11)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type + }; + return acc; + }, {}); + return example; + } + async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments } = {}) { + 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) datasetId_ = (await this.readDataset({ datasetName })).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_); + if (splits !== void 0) for (const split of splits) params.append("splits", split); + if (metadata !== void 0) { + const serializedMetadata = JSON.stringify(metadata); + params.append("metadata", serializedMetadata); + } + if (limit !== void 0) params.append("limit", limit.toString()); + if (offset !== void 0) params.append("offset", offset.toString()); + if (filter !== void 0) params.append("filter", filter); + if (includeAttachments === true) [ + "attachment_urls", + "outputs", + "metadata" + ].forEach((field) => params.append("select", field)); + let i = 0; + for await (const rawExamples of this._getPaginated("/examples", params)) { + for (const rawExample of rawExamples) { + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice(11)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type || void 0 + }; + return acc; + }, {}); + yield example; + i++; + } + if (limit !== void 0 && i >= limit) break; + } + } + async deleteExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + await this.caller.call(async () => { + const res = await this._fetch(this.apiUrl + path, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, `delete ${path}`, true); + return res; + }); + } + /** + * Delete multiple examples by ID. + * @param exampleIds - The IDs of the examples to delete + * @param options - Optional settings for deletion + * @param options.hardDelete - If true, permanently delete examples. If false (default), soft delete them. + */ + async deleteExamples(exampleIds, options) { + exampleIds.forEach((id) => assertUuid(id)); + if (options?.hardDelete) { + const path = this._getPlatformEndpointPath("datasets/examples/delete"); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${path}`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + body: JSON.stringify({ + example_ids: exampleIds, + hard_delete: true + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "hard delete examples", true); + return res; + }); + } else { + const params = new URLSearchParams(); + exampleIds.forEach((id) => params.append("example_ids", id)); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/examples?${params.toString()}`, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "delete examples", true); + return res; + }); + } + } + async updateExample(exampleIdOrUpdate, update) { + let exampleId; + if (update) exampleId = exampleIdOrUpdate; + else exampleId = exampleIdOrUpdate.id; + assertUuid(exampleId); + let updateToUse; + if (update) updateToUse = { + id: exampleId, + ...update + }; + else updateToUse = exampleIdOrUpdate; + let datasetId; + if (updateToUse.dataset_id !== void 0) datasetId = updateToUse.dataset_id; + else datasetId = (await this.readExample(exampleId)).dataset_id; + return this._updateExamplesMultipart(datasetId, [updateToUse]); + } + async updateExamples(update) { + let datasetId; + if (update[0].dataset_id === void 0) datasetId = (await this.readExample(update[0].id)).dataset_id; + else datasetId = update[0].dataset_id; + return this._updateExamplesMultipart(datasetId, update); + } + /** + * Get dataset version by closest date or exact tag. + * + * Use this to resolve the nearest version to a given timestamp or for a given tag. + * + * @param options The options for getting the dataset version + * @param options.datasetId The ID of the dataset + * @param options.datasetName The name of the dataset + * @param options.asOf The timestamp of the dataset to retrieve + * @param options.tag The tag of the dataset to retrieve + * @returns The dataset version + */ + async readDatasetVersion({ datasetId, datasetName, asOf, tag }) { + let resolvedDatasetId; + if (!datasetId) resolvedDatasetId = (await this.readDataset({ datasetName })).id; + else resolvedDatasetId = datasetId; + assertUuid(resolvedDatasetId); + if (asOf && tag || !asOf && !tag) throw new Error("Exactly one of asOf and tag must be specified."); + const params = new URLSearchParams(); + if (asOf !== void 0) params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + if (tag !== void 0) params.append("tag", tag); + return await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { + method: "GET", + headers: { ...this._mergedHeaders }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "read dataset version"); + return res; + })).json(); + } + async listDatasetSplits({ datasetId, datasetName, asOf }) { + let datasetId_; + if (datasetId === void 0 && datasetName === void 0) throw new Error("Must provide dataset name or ID"); + else if (datasetId !== void 0 && datasetName !== void 0) throw new Error("Must provide either datasetName or datasetId, not both"); + else if (datasetId === void 0) datasetId_ = (await this.readDataset({ datasetName })).id; + else datasetId_ = datasetId; + assertUuid(datasetId_); + const params = new URLSearchParams(); + const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0; + if (dataset_version) params.append("as_of", dataset_version); + return await this._get(`/datasets/${datasetId_}/splits`, params); + } + async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false }) { + let datasetId_; + if (datasetId === void 0 && datasetName === void 0) throw new Error("Must provide dataset name or ID"); + else if (datasetId !== void 0 && datasetName !== void 0) throw new Error("Must provide either datasetName or datasetId, not both"); + else if (datasetId === void 0) datasetId_ = (await this.readDataset({ datasetName })).id; + else datasetId_ = datasetId; + assertUuid(datasetId_); + const data = { + split_name: splitName, + examples: exampleIds.map((id) => { + assertUuid(id); + return id; + }), + remove + }; + const body = JSON.stringify(data); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/splits`, { + method: "PUT", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "update dataset splits", true); + return res; + }); + } + async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, sessionId, startTime, extendTraceRetention }) { + if (!runId && !projectId) throw new Error("One of runId or projectId must be provided"); + if (runId && projectId) throw new Error("Only one of runId or projectId can be provided"); + 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 ?? v7(), + run_id: runId, + key, + score: _formatFeedbackScore(score), + value, + correction, + comment, + feedback_source, + comparative_experiment_id: comparativeExperimentId, + feedbackConfig, + session_id: sessionId ?? projectId, + start_time: startTime, + extend_trace_retention: extendTraceRetention + }; + const body = JSON.stringify(feedback); + const url = `${this.apiUrl}/feedback`; + await this.caller.call(async () => { + const res = await this._fetch(url, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "create feedback", true); + return res; + }); + return feedback; + } + async updateFeedback(feedbackId, { score, value, correction, comment }) { + const feedbackUpdate = {}; + if (score !== void 0 && score !== null) feedbackUpdate["score"] = _formatFeedbackScore(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 body = JSON.stringify(feedbackUpdate); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/feedback/${feedbackId}`, { + method: "PATCH", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "update feedback", true); + return res; + }); + } + async readFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + return await this._get(path); + } + async deleteFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + await this.caller.call(async () => { + const res = await this._fetch(this.apiUrl + path, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, `delete ${path}`, true); + return res; + }); + } + async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes } = {}) { + const queryParams = new URLSearchParams(); + if (runIds) for (const runId of runIds) { + assertUuid(runId); + queryParams.append("run", runId); + } + if (feedbackKeys) for (const key of feedbackKeys) queryParams.append("key", key); + if (feedbackSourceTypes) for (const type of feedbackSourceTypes) queryParams.append("source", type); + for await (const feedbacks of this._getPaginated("/feedback", queryParams)) yield* feedbacks; + } + /** + * Creates a presigned feedback token and URL. + * + * The token can be used to authorize feedback metrics without + * needing an API key. This is useful for giving browser-based + * applications the ability to submit feedback without needing + * to expose an API key. + * + * @param runId The ID of the run. + * @param feedbackKey The feedback key. + * @param options Additional options for the token. + * @param options.expiration The expiration time for the token. + * + * @returns A promise that resolves to a FeedbackIngestToken. + */ + 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 serializedBody = JSON.stringify(body); + return await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/feedback/tokens`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody + }); + await raiseForStatus(res, "create presigned feedback token"); + return res; + })).json(); + } + async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id }) { + if (experimentIds.length === 0) throw new Error("At least one experiment is required"); + if (!referenceDatasetId) referenceDatasetId = (await this.readProject({ projectId: experimentIds[0] })).reference_dataset_id; + if (!referenceDatasetId == null) throw new Error("A reference dataset is required"); + const body = { + id, + name, + experiment_ids: experimentIds, + reference_dataset_id: referenceDatasetId, + description, + created_at: (createdAt ?? /* @__PURE__ */ new Date())?.toISOString(), + extra: {} + }; + if (metadata) body.extra["metadata"] = metadata; + const serializedBody = JSON.stringify(body); + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/comparative`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody + }); + await raiseForStatus(res, "create comparative experiment"); + return res; + })).json(); + } + /** + * Retrieves a list of presigned feedback tokens for a given run ID. + * @param runId The ID of the run. + * @returns An async iterable of FeedbackIngestToken objects. + */ + async *listPresignedFeedbackTokens(runId) { + assertUuid(runId); + const params = new URLSearchParams({ run_id: runId }); + for await (const tokens of this._getPaginated("/feedback/tokens", params)) yield* tokens; + } + _selectEvalResults(results) { + let results_; + if ("results" in results) results_ = results.results; + else if (Array.isArray(results)) results_ = results; + else results_ = [results]; + return results_; + } + async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const evalResults = this._selectEvalResults(evaluatorResponse); + const feedbacks = []; + for (const res of evalResults) { + let sourceInfo_ = sourceInfo || {}; + if (res.evaluatorInfo) sourceInfo_ = { + ...res.evaluatorInfo, + ...sourceInfo_ + }; + let runId_ = null; + if (res.targetRunId) runId_ = res.targetRunId; + else if (run) runId_ = run.id; + feedbacks.push(await this.createFeedback(runId_, res.key, { + score: res.score, + value: res.value, + comment: res.comment, + correction: res.correction, + sourceInfo: sourceInfo_, + sourceRunId: res.sourceRunId, + feedbackConfig: res.feedbackConfig, + feedbackSourceType: "model", + sessionId: run?.session_id, + startTime: run?.start_time + })); + } + return [evalResults, feedbacks]; + } + async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); + return results; + } + /** + * API for managing feedback configs + */ + /** + * Create a feedback configuration on the LangSmith API. + * + * This upserts: if an identical config already exists, it returns it. + * If a conflicting config exists for the same key, a 400 error is raised. + * + * @param options - The options for creating a feedback config + * @param options.feedbackKey - The unique key for this feedback config + * @param options.feedbackConfig - The config specifying type, bounds, and categories + * @param options.isLowerScoreBetter - Whether a lower score is better + * @returns The created FeedbackConfigSchema object + */ + async createFeedbackConfig(options) { + const { feedbackKey, feedbackConfig, isLowerScoreBetter = false } = options; + const body = { + feedback_key: feedbackKey, + feedback_config: feedbackConfig, + is_lower_score_better: isLowerScoreBetter + }; + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/feedback-configs`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(body) + }); + await raiseForStatus(res, "create feedback config"); + return res; + })).json(); + } + /** + * List feedback configurations on the LangSmith API. + * @param options - The options for listing feedback configs + * @param options.feedbackKeys - Filter by specific feedback keys + * @param options.nameContains - Filter by name substring + * @param options.limit - The maximum number of configs to return + * @returns An async iterator of FeedbackConfigSchema objects + */ + async *listFeedbackConfigs(options = {}) { + const { feedbackKeys, nameContains, limit } = options; + const params = new URLSearchParams(); + if (feedbackKeys) feedbackKeys.forEach((key) => { + params.append("key", key); + }); + if (nameContains) params.append("name_contains", nameContains); + params.append("limit", (limit !== void 0 ? Math.min(limit, 100) : 100).toString()); + let count = 0; + for await (const configs of this._getPaginated("/feedback-configs", params)) { + yield* configs; + count += configs.length; + if (limit !== void 0 && count >= limit) break; + } + } + /** + * Update a feedback configuration on the LangSmith API. + * @param feedbackKey - The key of the feedback config to update + * @param options - The options for updating the feedback config + * @param options.feedbackConfig - The new feedback config + * @param options.isLowerScoreBetter - Whether a lower score is better + * @returns The updated FeedbackConfigSchema object + */ + async updateFeedbackConfig(feedbackKey, options = {}) { + const { feedbackConfig, isLowerScoreBetter } = options; + const body = { feedback_key: feedbackKey }; + if (feedbackConfig !== void 0) body.feedback_config = feedbackConfig; + if (isLowerScoreBetter !== void 0) body.is_lower_score_better = isLowerScoreBetter; + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/feedback-configs`, { + method: "PATCH", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(body) + }); + await raiseForStatus(res, "update feedback config"); + return res; + })).json(); + } + /** + * Delete a feedback configuration on the LangSmith API. + * @param feedbackKey - The key of the feedback config to delete + */ + async deleteFeedbackConfig(feedbackKey) { + const params = new URLSearchParams({ feedback_key: feedbackKey }); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/feedback-configs?${params}`, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "delete feedback config", true); + return res; + }); + } + /** + * API for managing annotation queues + */ + /** + * List the annotation queues on the LangSmith API. + * @param options - The options for listing annotation queues + * @param options.queueIds - The IDs of the queues to filter by + * @param options.name - The name of the queue to filter by + * @param options.nameContains - The substring that the queue name should contain + * @param options.limit - The maximum number of queues to return + * @returns An iterator of AnnotationQueue objects + */ + async *listAnnotationQueues(options = {}) { + const { queueIds, name, nameContains, limit } = options; + const params = new URLSearchParams(); + if (queueIds) queueIds.forEach((id, i) => { + assertUuid(id, `queueIds[${i}]`); + params.append("ids", id); + }); + if (name) params.append("name", name); + if (nameContains) params.append("name_contains", nameContains); + params.append("limit", (limit !== void 0 ? Math.min(limit, 100) : 100).toString()); + let count = 0; + for await (const queues of this._getPaginated("/annotation-queues", params)) { + yield* queues; + count++; + if (limit !== void 0 && count >= limit) break; + } + } + /** + * Create an annotation queue on the LangSmith API. + * @param options - The options for creating an annotation queue + * @param options.name - The name of the annotation queue + * @param options.description - The description of the annotation queue + * @param options.queueId - The ID of the annotation queue + * @returns The created AnnotationQueue object + */ + async createAnnotationQueue(options) { + const { name, description, queueId, rubricInstructions, rubricItems } = options; + const body = { + name, + description, + id: queueId || v4(), + rubric_instructions: rubricInstructions, + rubric_items: rubricItems + }; + const serializedBody = JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== void 0))); + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody + }); + await raiseForStatus(res, "create annotation queue"); + return res; + })).json(); + } + /** + * Read an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to read + * @returns The AnnotationQueueWithDetails object + */ + async readAnnotationQueue(queueId) { + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "read annotation queue"); + return res; + })).json(); + } + /** + * Update an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to update + * @param options - The options for updating the annotation queue + * @param options.name - The new name for the annotation queue + * @param options.description - The new description for the annotation queue + */ + async updateAnnotationQueue(queueId, options) { + const { name, description, rubricInstructions, rubricItems } = options; + const bodyObj = {}; + if (name !== void 0) bodyObj.name = name; + if (description !== void 0) bodyObj.description = description; + if (rubricInstructions !== void 0) bodyObj.rubric_instructions = rubricInstructions; + if (rubricItems !== void 0) bodyObj.rubric_items = rubricItems; + const body = JSON.stringify(bodyObj); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "PATCH", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "update annotation queue", true); + return res; + }); + } + /** + * Delete an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to delete + */ + async deleteAnnotationQueue(queueId) { + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "DELETE", + headers: { + ...this._mergedHeaders, + Accept: "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "delete annotation queue", true); + return res; + }); + } + /** + * Add runs to an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue + * @param runIds - The IDs of the runs to be added to the annotation queue + */ + async addRunsToAnnotationQueue(queueId, runIds) { + const body = JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "add runs to annotation queue", true); + return res; + }); + } + /** + * Get a run from an annotation queue at the specified index. + * @param queueId - The ID of the annotation queue + * @param index - The index of the run to retrieve + * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object + * @throws {Error} If the run is not found at the given index or for other API-related errors + */ + async getRunFromAnnotationQueue(queueId, index) { + const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; + return _normalizeRunTimestamps(await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${baseUrl}/${index}`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "get run from annotation queue"); + return res; + })).json()); + } + /** + * List the runs in an annotation queue. + * @param queueId - The ID of the annotation queue + * @param options - The options for listing runs in the annotation queue + * @param options.status - Filter runs by review status. If omitted, returns + * runs across all review states. + * @param options.limit - The maximum number of runs to return + * @returns An iterator of RunWithAnnotationQueueInfo objects + */ + async *listRunsFromAnnotationQueue(queueId, options = {}) { + const { status, limit: userLimit } = options; + const params = new URLSearchParams(); + const limit = userLimit !== void 0 && Number.isFinite(userLimit) ? Math.min(userLimit, 100) : 100; + if (status) params.append("status", status); + params.append("limit", limit.toString()); + let count = 0; + const path = `/annotation-queues/${assertUuid(queueId, "queueId")}/runs`; + for await (const runs of this._getPaginated(path, params)) for (const run of runs) { + yield _normalizeRunTimestamps(run); + count++; + if (count >= limit) return; + } + } + /** + * Delete a run from an an annotation queue. + * @param queueId - The ID of the annotation queue to delete the run from + * @param queueRunId - The ID of the run to delete from the annotation queue + */ + async deleteRunFromAnnotationQueue(queueId, queueRunId) { + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { + method: "DELETE", + headers: { + ...this._mergedHeaders, + Accept: "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "delete run from annotation queue", true); + return res; + }); + } + /** + * Get the size of an annotation queue. + * @param queueId - The ID of the annotation queue + */ + async getSizeFromAnnotationQueue(queueId) { + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "get size from annotation queue"); + return res; + })).json(); + } + async _currentTenantIsOwner(owner) { + const settings = await this._getSettings(); + return owner == "-" || settings.tenant_handle === owner; + } + async _ownerConflictError(action, owner) { + const settings = await this._getSettings(); + return /* @__PURE__ */ new Error(`Cannot ${action} for another tenant.\n + Current tenant: ${settings.tenant_handle}\n + Requested tenant: ${owner}`); + } + async _getLatestCommitHash(promptOwnerAndName) { + const json = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/commits/${promptOwnerAndName}/?limit=1&offset=0`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "get latest commit hash"); + return res; + })).json(); + if (json.commits.length === 0) return; + return json.commits[0].commit_hash; + } + async _createCommitTags(promptOwnerAndName, commitId, tags) { + const tagList = typeof tags === "string" ? [tags] : tags; + await Promise.all(tagList.map(async (tag) => this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/${promptOwnerAndName}/tags`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify({ + tag_name: tag, + commit_id: commitId + }) + }); + await raiseForStatus(res, "create commit tag"); + return res; + }))); + } + async _likeOrUnlikePrompt(promptIdentifier, like) { + const [owner, promptName, _] = parseHubIdentifier(promptIdentifier); + const body = JSON.stringify({ like }); + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/likes/${owner}/${promptName}`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, `${like ? "like" : "unlike"} prompt`); + return res; + })).json(); + } + async _getPromptUrl(promptIdentifier) { + const [owner, promptName, commitHash] = parseHubIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) if (commitHash !== "latest") return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; + else return `${this.getHostUrl()}/hub/${owner}/${promptName}`; + else { + const settings = await this._getSettings(); + if (commitHash !== "latest") return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; + else return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; + } + } + /** + * Check if a prompt exists. + * @param promptIdentifier - The identifier of the prompt. Can be in the format: + * - "promptName" (for private prompts, owner defaults to "-") + * - "owner/promptName" (for prompts with explicit owner) + * @returns A Promise that resolves to true if the prompt exists, false otherwise + * @example + * ```typescript + * // Check if a prompt exists before creating a commit + * if (await client.promptExists("my-prompt")) { + * await client.createCommit("my-prompt", template); + * } else { + * await client.createPrompt("my-prompt"); + * } + * ``` + */ + async promptExists(promptIdentifier) { + return !!await this.getPrompt(promptIdentifier); + } + /** + * Like a prompt. + * @param promptIdentifier - The identifier of the prompt. Can be in the format: + * - "promptName" (for private prompts, owner defaults to "-") + * - "owner/promptName" (for prompts with explicit owner) + * @returns A Promise that resolves to the like response containing the updated like count + * @example + * ```typescript + * // Like a prompt + * const response = await client.likePrompt("owner/useful-prompt"); + * console.log(`Prompt now has ${response.likes} likes`); + * ``` + */ + async likePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, true); + } + /** + * Unlike a prompt (remove a previously added like). + * @param promptIdentifier - The identifier of the prompt. Can be in the format: + * - "promptName" (for private prompts, owner defaults to "-") + * - "owner/promptName" (for prompts with explicit owner) + * @returns A Promise that resolves to the like response containing the updated like count + * @example + * ```typescript + * // Unlike a prompt + * const response = await client.unlikePrompt("owner/useful-prompt"); + * console.log(`Prompt now has ${response.likes} likes`); + * ``` + */ + async unlikePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, false); + } + /** + * List all commits for a prompt. + * @param promptIdentifier - The identifier of the prompt. Can be in the format: + * - "promptName" (for private prompts, owner defaults to "-") + * - "owner/promptName" (for prompts with explicit owner) + * - "promptName:commitHash" (commit hash is ignored, all commits are returned) + * @returns An async iterable iterator of PromptCommit objects + * @example + * ```typescript + * // List commits for a private prompt + * for await (const commit of client.listCommits("my-prompt")) { + * console.log(commit); + * } + * + * // List commits for a prompt with explicit owner + * for await (const commit of client.listCommits("owner/my-prompt")) { + * console.log(commit); + * } + * ``` + */ + async *listCommits(promptIdentifier) { + const [owner, promptName, _] = parseHubIdentifier(promptIdentifier); + for await (const commits of this._getPaginated(`/commits/${owner}/${promptName}/`, new URLSearchParams(), (res) => res.commits)) yield* commits; + } + /** + * List prompts by filter. + * @param options - Optional filters for listing prompts + * @param options.isPublic - Filter by public/private prompts. If undefined, returns all prompts. + * @param options.isArchived - Filter by archived status. Defaults to false (non-archived prompts only). + * @param options.sortField - Field to sort by. Defaults to "updated_at". + * @param options.query - Search query to filter prompts by name or description. + * @returns An async iterable iterator of Prompt objects + * @example + * ```typescript + * // List all prompts + * for await (const prompt of client.listPrompts()) { + * console.log(prompt); + * } + * + * // List only public prompts + * for await (const prompt of client.listPrompts({ isPublic: true })) { + * console.log(prompt); + * } + * + * // Search for prompts + * for await (const prompt of client.listPrompts({ query: "translation" })) { + * console.log(prompt); + * } + * ``` + */ + async *listPrompts(options) { + const params = new URLSearchParams(); + params.append("sort_field", options?.sortField ?? "updated_at"); + params.append("sort_direction", "desc"); + params.append("is_archived", (!!options?.isArchived).toString()); + if (options?.isPublic !== void 0) params.append("is_public", options.isPublic.toString()); + if (options?.query) params.append("query", options.query); + for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) yield* prompts; + } + /** + * Get a prompt by its identifier. + * @param promptIdentifier - The identifier of the prompt. Can be in the format: + * - "promptName" (for private prompts, owner defaults to "-") + * - "owner/promptName" (for prompts with explicit owner) + * - "promptName:commitHash" (commit hash is ignored, latest version is returned) + * @returns A Promise that resolves to the Prompt object, or null if not found + * @example + * ```typescript + * // Get a private prompt + * const prompt = await client.getPrompt("my-prompt"); + * + * // Get a public prompt + * const publicPrompt = await client.getPrompt("owner/public-prompt"); + * ``` + */ + async getPrompt(promptIdentifier) { + const [owner, promptName, _] = parseHubIdentifier(promptIdentifier); + const result = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + if (res?.status === 404) return null; + await raiseForStatus(res, "get prompt"); + return res; + }))?.json(); + if (result?.repo) return result.repo; + else return null; + } + /** + * Create a new prompt. + * @param promptIdentifier - The identifier for the new prompt. Can be in the format: + * - "promptName" (creates a private prompt) + * - "owner/promptName" (creates a prompt under a specific owner, must match your tenant) + * @param options - Optional configuration for the prompt + * @param options.description - A description of the prompt + * @param options.readme - Markdown content for the prompt's README + * @param options.tags - Array of tags to categorize the prompt + * @param options.isPublic - Whether the prompt should be public. Requires a LangChain Hub handle. + * @returns A Promise that resolves to the created Prompt object + * @throws {Error} If creating a public prompt without a LangChain Hub handle, or if owner doesn't match current tenant + * @example + * ```typescript + * // Create a private prompt + * const prompt = await client.createPrompt("my-new-prompt", { + * description: "A prompt for translations", + * tags: ["translation", "language"] + * }); + * + * // Create a public prompt + * const publicPrompt = await client.createPrompt("my-public-prompt", { + * description: "A public translation prompt", + * isPublic: true + * }); + * ``` + */ + async createPrompt(promptIdentifier, options) { + const settings = await this._getSettings(); + if (options?.isPublic && !settings.tenant_handle) throw new Error(`Cannot create a public prompt without first\n + creating a LangChain Hub handle. + You can add a handle by creating a public prompt at:\n + https://smith.langchain.com/prompts`); + const [owner, promptName, _] = parseHubIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) throw await this._ownerConflictError("create a prompt", owner); + const data = { + repo_handle: promptName, + ...options?.description && { description: options.description }, + ...options?.readme && { readme: options.readme }, + ...options?.tags && { tags: options.tags }, + is_public: !!options?.isPublic + }; + const body = JSON.stringify(data); + const { repo } = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "create prompt"); + return res; + })).json(); + return repo; + } + /** + * Create a new commit for an existing prompt. + * @param promptIdentifier - The identifier of the prompt. Can be in the format: + * - "promptName" (for private prompts, owner defaults to "-") + * - "owner/promptName" (for prompts with explicit owner) + * @param object - The prompt object/manifest to commit (e.g., ChatPromptTemplate, messages array, etc.) + * @param options - Optional configuration for the commit + * @param options.parentCommitHash - The parent commit hash. Defaults to "latest" (the most recent commit). + * @param options.tags - A tag or list of tags to apply to the commit. + * @param options.description - A description for the commit. + * @returns A Promise that resolves to the URL of the newly created commit + * @throws {Error} If the prompt does not exist + * @example + * ```typescript + * import { ChatPromptTemplate } from "@langchain/core/prompts"; + * + * // Create a commit with a new version of the prompt + * const template = ChatPromptTemplate.fromMessages([ + * ["system", "You are a helpful assistant."], + * ["human", "{input}"] + * ]); + * + * const commitUrl = await client.createCommit("my-prompt", template); + * console.log(`Commit created: ${commitUrl}`); + * + * // Create a commit with tags + * const commitUrl2 = await client.createCommit("my-prompt", template, { + * tags: ["production", "v1"] + * }); + * ``` + */ + async createCommit(promptIdentifier, object, options) { + if (!await this.promptExists(promptIdentifier)) throw new Error("Prompt does not exist, you must create it first."); + const [owner, promptName, _] = parseHubIdentifier(promptIdentifier); + const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash ? await this._getLatestCommitHash(`${owner}/${promptName}`) : options?.parentCommitHash; + const payload = { + manifest: JSON.parse(JSON.stringify(object)), + parent_commit: resolvedParentCommitHash, + ...options?.description !== void 0 && { description: options.description } + }; + const body = JSON.stringify(payload); + const result = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "create commit"); + return res; + })).json(); + const commit = result.commit ?? result; + if (options?.tags) await this._createCommitTags(`${owner}/${promptName}`, commit.id, options.tags); + return this._getPromptUrl(`${owner}/${promptName}${commit.commit_hash ? `:${commit.commit_hash}` : ""}`); + } + /** + * Update examples with attachments using multipart form data. + * @param updates List of ExampleUpdateWithAttachments objects to upsert + * @returns Promise with the update response + */ + async updateExamplesMultipart(datasetId, updates = []) { + return this._updateExamplesMultipart(datasetId, updates); + } + async _updateExamplesMultipart(datasetId, updates = []) { + if (!await this._getDatasetExamplesMultiPartSupport()) throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + const formData = new FormData(); + for (const example of updates) { + const exampleId = example.id; + const stringifiedExample = serialize({ + ...example.metadata && { metadata: example.metadata }, + ...example.split && { split: example.split } + }, `Serializing body for example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { type: "application/json" }); + formData.append(exampleId, exampleBlob); + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { type: "application/json" }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { type: "application/json" }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + if (example.attachments) for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) [mimeType, data] = attachment; + else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { type: `${mimeType}; length=${data.byteLength}` }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + if (example.attachments_operations) { + const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); + const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { type: "application/json" }); + formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); + } + } + const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, { + method: "PATCH", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: formData + }); + await raiseForStatus(res, "update examples"); + return res; + })).json(); + } + /** + * Upload examples with attachments using multipart form data. + * @param uploads List of ExampleUploadWithAttachments objects to upload + * @returns Promise with the upload response + * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead + */ + async uploadExamplesMultipart(datasetId, uploads = []) { + return this._uploadExamplesMultipart(datasetId, uploads); + } + async _uploadExamplesMultipart(datasetId, uploads = []) { + if (!await this._getDatasetExamplesMultiPartSupport()) throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + const formData = new FormData(); + for (const example of uploads) { + const exampleId = (example.id ?? v4()).toString(); + const stringifiedExample = serialize({ + created_at: example.created_at, + ...example.metadata && { metadata: example.metadata }, + ...example.split && { split: example.split }, + ...example.source_run_id && { source_run_id: example.source_run_id }, + ...example.use_source_run_io && { use_source_run_io: example.use_source_run_io }, + ...example.use_source_run_attachments && { use_source_run_attachments: example.use_source_run_attachments } + }, `Serializing body for uploaded example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { type: "application/json" }); + formData.append(exampleId, exampleBlob); + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { type: "application/json" }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { type: "application/json" }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + if (example.attachments) for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) [mimeType, data] = attachment; + else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { type: `${mimeType}; length=${data.byteLength}` }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, { + method: "POST", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: formData + }); + await raiseForStatus(res, "upload examples"); + return res; + })).json(); + } + async updatePrompt(promptIdentifier, options) { + if (!await this.promptExists(promptIdentifier)) throw new Error("Prompt does not exist, you must create it first."); + const [owner, promptName] = parseHubIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) throw await this._ownerConflictError("update a prompt", owner); + const payload = {}; + if (options?.description !== void 0) payload.description = options.description; + if (options?.readme !== void 0) payload.readme = options.readme; + if (options?.tags !== void 0) payload.tags = options.tags; + if (options?.isPublic !== void 0) payload.is_public = options.isPublic; + if (options?.isArchived !== void 0) payload.is_archived = options.isArchived; + if (Object.keys(payload).length === 0) throw new Error("No valid update options provided"); + const body = JSON.stringify(payload); + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "PATCH", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body + }); + await raiseForStatus(res, "update prompt"); + return res; + })).json(); + } + async deletePrompt(promptIdentifier) { + if (!await this.promptExists(promptIdentifier)) throw new Error("Prompt does not exist, you must create it first."); + const [owner, promptName, _] = parseHubIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) throw await this._ownerConflictError("delete a prompt", owner); + return (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "delete prompt"); + return res; + })).json(); + } + /** + * Generate a cache key for a prompt. + * Format: "{identifier}" or "{identifier}:with_model" + */ + _getPromptCacheKey(promptIdentifier, includeModel) { + return `${promptIdentifier}${includeModel ? ":with_model" : ""}`; + } + /** + * Fetch a prompt commit directly from the API (bypassing cache). + */ + async _fetchPromptFromApi(promptIdentifier, options) { + const [owner, promptName, commitHash] = parseHubIdentifier(promptIdentifier); + const result = await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "pull prompt commit"); + return res; + })).json(); + return { + owner, + repo: promptName, + commit_hash: result.commit_hash, + manifest: result.manifest, + examples: result.examples, + hub_model_config: result.model_config, + hub_model_provider: result.model_provider + }; + } + /** + * Pull a prompt commit from the LangSmith API. + * + * Public prompts referenced by owner/name cross a trust boundary because the + * prompt manifest may contain serialized LangChain objects and configuration + * that affect runtime behavior. For example, a prompt can intentionally + * configure a model with a custom base URL, headers, model name, or other + * constructor arguments. These are supported features, but they also mean the + * prompt contents should be treated as executable configuration rather than + * plain text. + * + * Set `dangerouslyPullPublicPrompt: true` only after reviewing and trusting + * the prompt contents, not merely the publishing account. Prompts from your + * own or your organization's account can still be unsafe if that account or + * prompt was compromised. + * + * When pulling a trusted external prompt, prefer pinning to a specific commit + * rather than following a mutable latest version. Using `includeModel: true` + * increases risk and should be avoided for public prompts or prompts outside + * your own organization. + */ + async pullPromptCommit(promptIdentifier, options) { + assertPullPublicPromptAllowed(promptIdentifier, options?.dangerouslyPullPublicPrompt); + const refreshFunc = this._fetchPromptFromApi.bind(this, promptIdentifier, options); + if (!options?.skipCache && this._promptCache) { + const cacheKey = this._getPromptCacheKey(promptIdentifier, options?.includeModel); + const cached = this._promptCache.get(cacheKey, refreshFunc); + if (cached) return cached; + const result = await refreshFunc(); + this._promptCache.set(cacheKey, result, refreshFunc); + return result; + } + return this._fetchPromptFromApi(promptIdentifier, options); + } + /** + * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. + * Using this method directly returns the JSON string of the prompt rather than a LangChain object. + * + * Public prompts referenced by owner/name cross a trust boundary because the + * prompt manifest may contain serialized LangChain objects and configuration + * that affect runtime behavior. For example, a prompt can intentionally + * configure a model with a custom base URL, headers, model name, or other + * constructor arguments. These are supported features, but they also mean the + * prompt contents should be treated as executable configuration rather than + * plain text. + * + * Set `dangerouslyPullPublicPrompt: true` only after reviewing and trusting + * the prompt contents, not merely the publishing account. Prompts from your + * own or your organization's account can still be unsafe if that account or + * prompt was compromised. + * + * When pulling a trusted external prompt, prefer pinning to a specific commit + * rather than following a mutable latest version. Using `includeModel: true` + * increases risk and should be avoided for public prompts or prompts outside + * your own organization. + * @private + */ + async _pullPrompt(promptIdentifier, options) { + const promptObject = await this.pullPromptCommit(promptIdentifier, { + includeModel: options?.includeModel, + skipCache: options?.skipCache, + dangerouslyPullPublicPrompt: options?.dangerouslyPullPublicPrompt + }); + return JSON.stringify(promptObject.manifest); + } + async pushPrompt(promptIdentifier, options) { + if (await this.promptExists(promptIdentifier)) { + if (options && [ + "description", + "readme", + "tags", + "isPublic" + ].some((key) => options[key] !== void 0)) await this.updatePrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic + }); + } else await this.createPrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic + }); + if (!options?.object) return await this._getPromptUrl(promptIdentifier); + return await this.createCommit(promptIdentifier, options?.object, { + parentCommitHash: options?.parentCommitHash, + tags: options?.commitTags, + description: options?.commitDescription + }); + } + /** + * Check if an agent repo exists. + */ + async agentExists(identifier) { + const [owner, name] = parseHubIdentifier(identifier); + return this._repoExists(owner, name); + } + /** + * Check if a skill repo exists. + */ + async skillExists(identifier) { + const [owner, name] = parseHubIdentifier(identifier); + return this._repoExists(owner, name); + } + /** + * Pull an agent directory from Hub. + * @param identifier The identifier (owner/name[:version]). + * @param options.version Commit hash or tag; overrides identifier's version. + */ + async pullAgent(identifier, options) { + return await this._pullDirectory(identifier, "agent", options?.version); + } + /** + * Pull a skill directory from Hub. + */ + async pullSkill(identifier, options) { + return await this._pullDirectory(identifier, "skill", options?.version); + } + /** + * Push an agent to Hub. Creates the repo if missing, patches metadata if + * provided, then commits the given files. + * @returns The URL of the resulting commit. + */ + async pushAgent(identifier, options) { + return this._pushDirectory(identifier, "agent", options); + } + /** + * Push a skill to Hub. + */ + async pushSkill(identifier, options) { + return this._pushDirectory(identifier, "skill", options); + } + /** + * Delete an agent and all its owned child file repos. + */ + async deleteAgent(identifier) { + return this._deleteDirectory(identifier); + } + /** + * Delete a skill and all its owned child file repos. + */ + async deleteSkill(identifier) { + return this._deleteDirectory(identifier); + } + /** + * List agent repos. Yields one at a time, auto-paginating. + */ + async *listAgents(options) { + yield* this._listReposByType("agent", options); + } + /** + * List skill repos. Yields one at a time, auto-paginating. + */ + async *listSkills(options) { + yield* this._listReposByType("skill", options); + } + async *_listReposByType(repoType, options) { + const params = new URLSearchParams(); + params.append("repo_type", repoType); + params.append("is_archived", (!!options?.isArchived).toString()); + if (options?.isPublic !== void 0) params.append("is_public", options.isPublic.toString()); + if (options?.query) params.append("query", options.query); + for await (const repos of this._getPaginated("/repos", params, (res) => res.repos)) yield* repos; + } + async _pullDirectory(identifier, repoType, version) { + const [owner, name, parsedVersion] = parseHubIdentifier(identifier); + const resolvedVersion = version ?? (parsedVersion !== "latest" ? parsedVersion : void 0); + const url = new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${owner}/${name}/directories`)}`); + url.searchParams.set("repo_type", repoType); + if (resolvedVersion) url.searchParams.set("commit", resolvedVersion); + return await (await this.caller.call(async () => { + const res = await this._fetch(url.toString(), { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "pull directory"); + return res; + })).json(); + } + async _pushDirectory(identifier, repoType, options) { + if (options.parentCommit !== void 0 && (options.parentCommit.length < 8 || options.parentCommit.length > 64)) throw new Error("parent_commit must be 8-64 characters"); + const [owner, name] = parseHubIdentifier(identifier); + if (!await this._currentTenantIsOwner(owner)) throw await this._ownerConflictError(`push ${repoType}`, owner); + if (await this._repoExists(owner, name)) { + if (options.description !== void 0 || options.readme !== void 0 || options.tags !== void 0 || options.isPublic !== void 0) await this._updateRepoMetadata(owner, name, options); + } else { + const REPO_HANDLE_PATTERN = /^[a-z][a-z0-9-_]*$/; + if (!REPO_HANDLE_PATTERN.test(name)) throw new Error(`Invalid repo_handle ${JSON.stringify(name)}: must match ${REPO_HANDLE_PATTERN}`); + await this._createRepo(name, repoType, options); + } + const body = { files: options.files }; + if (options.parentCommit) body.parent_commit = options.parentCommit; + const commitHash = (await (await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${owner}/${name}/directories/commits`)}`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(body) + }); + await raiseForStatus(res, `push ${repoType}`); + return res; + })).json()).commit.commit_hash; + const settings = await this._getSettings(); + const query = new URLSearchParams({ organizationId: settings.id }); + return `${this.getHostUrl()}/context/${name}/${commitHash.slice(0, 8)}?${query.toString()}`; + } + async _deleteDirectory(identifier) { + const [owner, name] = parseHubIdentifier(identifier); + if (!await this._currentTenantIsOwner(owner)) throw await this._ownerConflictError("delete", owner); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${owner}/${name}/directories`)}`, { + method: "DELETE", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "delete directory"); + return res; + }); + } + async _repoExists(owner, name) { + try { + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${name}`, { + method: "GET", + headers: this._mergedHeaders, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(res, "check repo exists"); + return res; + }); + return true; + } catch (e) { + if (isLangSmithNotFoundError(e)) return false; + throw e; + } + } + async _createRepo(name, repoType, options) { + const body = { + repo_handle: name, + repo_type: repoType, + is_public: !!options.isPublic + }; + if (options.description !== void 0) body.description = options.description; + if (options.readme !== void 0) body.readme = options.readme; + if (options.tags !== void 0) body.tags = options.tags; + try { + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/`, { + method: "POST", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(body) + }); + await raiseForStatus(res, `create ${repoType}`); + return res; + }); + } catch (e) { + if (isLangSmithConflictError(e)) return; + throw e; + } + } + async _updateRepoMetadata(owner, name, options) { + const body = {}; + if (options.description !== void 0) body.description = options.description; + if (options.readme !== void 0) body.readme = options.readme; + if (options.tags !== void 0) body.tags = options.tags; + if (options.isPublic !== void 0) body.is_public = options.isPublic; + if (Object.keys(body).length === 0) return; + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${name}`, { + method: "PATCH", + headers: { + ...this._mergedHeaders, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(body) + }); + await raiseForStatus(res, "update repo metadata"); + return res; + }); + } + /** + * Clone a public dataset to your own langsmith tenant. + * This operation is idempotent. If you already have a dataset with the given name, + * this function will do nothing. + + * @param {string} tokenOrUrl The token of the public dataset to clone. + * @param {Object} [options] Additional options for cloning the dataset. + * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. + * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. + * @returns {Promise} + */ + async clonePublicDataset(tokenOrUrl, options = {}) { + const { sourceApiUrl = this.apiUrl, datasetName } = options; + const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); + const sourceClient = new Client({ + apiUrl: parsedApiUrl, + apiKey: "placeholder" + }); + const ds = await sourceClient.readSharedDataset(tokenUuid); + const finalDatasetName = datasetName || ds.name; + try { + if (await this.hasDataset({ datasetId: finalDatasetName })) { + console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); + return; + } + } catch (_) {} + const examples = await sourceClient.listSharedExamples(tokenUuid); + const dataset = await this.createDataset(finalDatasetName, { + description: ds.description, + dataType: ds.data_type || "kv", + inputsSchema: ds.inputs_schema_definition ?? void 0, + outputsSchema: ds.outputs_schema_definition ?? void 0 + }); + try { + await this.createExamples({ + inputs: examples.map((e) => e.inputs), + outputs: examples.flatMap((e) => e.outputs ? [e.outputs] : []), + datasetId: dataset.id + }); + } catch (e) { + console.error(`An error occurred while creating dataset ${finalDatasetName}. You should delete it manually.`); + throw e; + } + } + parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { + try { + assertUuid(urlOrToken); + return [apiUrl, urlOrToken]; + } catch (_) {} + try { + const pathParts = new URL(urlOrToken).pathname.split("/").filter((part) => part !== ""); + if (pathParts.length >= numParts) return [apiUrl, pathParts[pathParts.length - numParts]]; + else throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); + } catch (_error) { + throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); + } + } + /** + * Cleanup resources held by the client. + * Stops the cache's background refresh timer. + */ + cleanup() { + if (this._promptCache) this._promptCache.stop(); + } + /** + * Awaits all pending trace batches. Useful for environments where + * you need to be sure that all tracing requests finish before execution ends, + * such as serverless environments. + * + * @example + * ``` + * import { Client } from "langsmith"; + * + * const client = new Client(); + * + * try { + * // Tracing happens here + * ... + * } finally { + * await client.awaitPendingTraceBatches(); + * } + * ``` + * + * @returns A promise that resolves once all currently pending traces have sent. + */ + async awaitPendingTraceBatches() { + if (this.manualFlushMode) { + console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); + return Promise.resolve(); + } + /** + * traceables use a backgrounded promise before updating runs to avoid blocking + * and to allow waiting for child runs to end. Waiting a small amount of time + * here ensures that they are able to enqueue their run operation before we await + * queued run operations below: + * + * ```ts + * const run = await traceable(async () => { + * return "Hello, world!"; + * }, { client })(); + * + * await client.awaitPendingTraceBatches(); + * ``` + */ + await new Promise((resolve) => setTimeout(resolve, 1)); + while (this._pendingDrains.size > 0) await Promise.all([...this._pendingDrains]); + await Promise.all([...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), this.batchIngestCaller.queue.onIdle()]); + if (this.langSmithToOTELTranslator !== void 0) await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush(); + } + /** + * Returns a string representation of the Client instance. + * This method is called when the object is converted to a string + * or logged, ensuring sensitive information like API keys is not exposed. + * + * @returns A string representation of the Client. + */ + toString() { + const params = [`apiUrl=${JSON.stringify(this.apiUrl)}`]; + if (this.webUrl !== void 0) params.push(`webUrl=${JSON.stringify(this.webUrl)}`); + if (this.workspaceId !== void 0) params.push(`workspaceId=${JSON.stringify(this.workspaceId)}`); + return `[LangSmithClient ${params.join(" ")}]`; + } + /** + * Custom inspect method for Node.js. + * This method is called when the object is inspected in the Node.js REPL + * or with console.log, ensuring sensitive information like API keys is not exposed. + * + * @returns A string representation of the Client for inspection. + */ + [Symbol.for("nodejs.util.inspect.custom")]() { + return this.toString(); + } +}; +Object.defineProperty(Client, "_fallbackDirsCreated", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Set() +}); +function isExampleCreate(input) { + return "dataset_id" in input || "dataset_name" in input; +} +//#endregion +//#region node_modules/langsmith/dist/singletons/constants.js +var _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); +var _REPLICA_TRACE_ROOTS_KEY = Symbol.for("langsmith:replica_trace_roots"); +//#endregion +//#region node_modules/langsmith/dist/utils/context_vars.js +/** +* Get a context variable from a run tree instance +*/ +function getContextVar(runTree, key) { + if (_LC_CONTEXT_VARIABLES_KEY in runTree) return runTree[_LC_CONTEXT_VARIABLES_KEY][key]; +} +/** +* Set a context variable on a run tree instance +*/ +function setContextVar(runTree, key, value) { + const contextVars = _LC_CONTEXT_VARIABLES_KEY in runTree ? runTree[_LC_CONTEXT_VARIABLES_KEY] : {}; + contextVars[key] = value; + runTree[_LC_CONTEXT_VARIABLES_KEY] = contextVars; +} +//#endregion +//#region node_modules/langsmith/dist/run_trees.js +var UUID_NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; +function getReplicaKey(replica) { + return v5(Object.keys(replica).sort().map((key) => `${key}:${replica[key] ?? ""}`).join("|"), UUID_NAMESPACE_DNS); +} +function stripNonAlphanumeric(input) { + return input.replace(/[-:.]/g, ""); +} +function getMicrosecondPrecisionDatestring(epoch, executionOrder = 1) { + const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); + return `${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`; +} +function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { + const microsecondPrecisionDatestring = getMicrosecondPrecisionDatestring(epoch, executionOrder); + return { + dottedOrder: stripNonAlphanumeric(microsecondPrecisionDatestring) + runId, + microsecondPrecisionDatestring + }; +} +var HEADER_SAFE_REPLICA_FIELDS = /* @__PURE__ */ new Set([ + "projectName", + "updates", + "reroot" +]); +function filterReplicaForHeaders(replica) { + const filtered = {}; + for (const key of Object.keys(replica)) if (HEADER_SAFE_REPLICA_FIELDS.has(key)) filtered[key] = replica[key]; + return filtered; +} +/** +* Baggage header information +*/ +var Baggage = class Baggage { + constructor(metadata, tags, project_name, replicas) { + Object.defineProperty(this, "metadata", { + 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, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.metadata = metadata; + this.tags = tags; + this.project_name = project_name; + this.replicas = replicas; + } + static fromHeader(value) { + const items = value.split(","); + let metadata = {}; + let tags = []; + let project_name; + let replicas; + for (const item of items) { + const [key, uriValue] = item.split("="); + const value = decodeURIComponent(uriValue); + if (key === "langsmith-metadata") metadata = JSON.parse(value); + else if (key === "langsmith-tags") tags = value.split(","); + else if (key === "langsmith-project") project_name = value; + else if (key === "langsmith-replicas") replicas = JSON.parse(value).map((replica) => { + if (Array.isArray(replica)) return replica; + return filterReplicaForHeaders(replica); + }); + } + return new Baggage(metadata, tags, project_name, replicas); + } + toHeader() { + const items = []; + if (this.metadata && Object.keys(this.metadata).length > 0) items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); + if (this.tags && this.tags.length > 0) items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); + if (this.project_name) items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); + return items.join(","); + } +}; +var RunTree = class RunTree { + constructor(originalConfig) { + 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, "parent_run_id", { + 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 + }); + Object.defineProperty(this, "tracingEnabled", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Attachments associated with the run. + * Each entry is a tuple of [mime_type, bytes] + */ + Object.defineProperty(this, "attachments", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Projects to replicate this run to with optional updates. + */ + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "distributedParentId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * @interface + */ + Object.defineProperty(this, "_serialized_start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * @internal + */ + Object.defineProperty(this, "_awaitInputsOnPost", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (isRunTree(originalConfig)) { + Object.assign(this, { ...originalConfig }); + return; + } + const defaultConfig = RunTree.getDefaultConfig(); + const { metadata, ...config } = originalConfig; + const client = config.client ?? RunTree.getSharedClient(); + const dedupedMetadata = { + ...metadata, + ...config?.extra?.metadata + }; + config.extra = { + ...config.extra, + metadata: dedupedMetadata + }; + if ("id" in config && config.id == null) delete config.id; + Object.assign(this, { + ...defaultConfig, + ...config, + client + }); + this.execution_order ??= 1; + this.child_execution_order ??= 1; + if (!this.dotted_order) this._serialized_start_time = getMicrosecondPrecisionDatestring(this.start_time, this.execution_order); + if (!this.id) this.id = uuid7FromTime(this._serialized_start_time ?? this.start_time); + if (!this.trace_id) if (this.parent_run) this.trace_id = this.parent_run.trace_id ?? this.id; + else this.trace_id = this.id; + this.replicas = _ensureWriteReplicas(this.replicas); + if (!this.dotted_order) { + const { dottedOrder } = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); + if (this.parent_run) this.dotted_order = this.parent_run.dotted_order + "." + dottedOrder; + else this.dotted_order = dottedOrder; + } + } + set metadata(metadata) { + this.extra = { + ...this.extra, + metadata: { + ...this.extra?.metadata, + ...metadata + } + }; + } + get metadata() { + return this.extra?.metadata; + } + static getDefaultConfig() { + const start_time = Date.now(); + return { + run_type: "chain", + project_name: getDefaultProjectName(), + child_runs: [], + api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", + api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), + caller_options: {}, + start_time, + serialized: {}, + inputs: {}, + extra: {} + }; + } + static getSharedClient() { + if (!RunTree.sharedClient) RunTree.sharedClient = new Client(); + return RunTree.sharedClient; + } + createChild(config) { + const child_execution_order = this.child_execution_order + 1; + const inheritedReplicas = this.replicas?.map((replica) => { + const { reroot, ...rest } = replica; + return rest; + }); + const childReplicas = config.replicas ?? inheritedReplicas; + const child = new RunTree({ + ...config, + parent_run: this, + project_name: this.project_name, + replicas: childReplicas, + client: this.client, + tracingEnabled: this.tracingEnabled, + execution_order: child_execution_order, + child_execution_order + }); + const parentMeta = this.extra?.metadata ?? {}; + const childMeta = child.extra?.metadata ?? {}; + if (Object.keys(parentMeta).length > 0) child.extra = { + ...child.extra, + metadata: { + ...parentMeta, + ...childMeta + } + }; + if (_LC_CONTEXT_VARIABLES_KEY in this) child[_LC_CONTEXT_VARIABLES_KEY] = this[_LC_CONTEXT_VARIABLES_KEY]; + const LC_CHILD = Symbol.for("lc:child_config"); + const presentConfig = config.extra?.[LC_CHILD] ?? this.extra[LC_CHILD]; + if (isRunnableConfigLike(presentConfig)) { + const newConfig = { ...presentConfig }; + const callbacks = isCallbackManagerLike(newConfig.callbacks) ? newConfig.callbacks.copy?.() : void 0; + if (callbacks) { + Object.assign(callbacks, { _parentRunId: child.id }); + callbacks.handlers?.find(isLangChainTracerLike)?.updateFromRunTree?.(child); + newConfig.callbacks = callbacks; + } + child.extra[LC_CHILD] = newConfig; + } + const visited = /* @__PURE__ */ new Set(); + let current = this; + while (current != null && !visited.has(current.id)) { + visited.add(current.id); + current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); + current = current.parent_run; + } + this.child_runs.push(child); + return child; + } + async end(outputs, error, endTime = Date.now(), metadata) { + this.outputs = this.outputs ?? outputs; + this.error = this.error ?? error; + this.end_time = this.end_time ?? endTime; + if (metadata && Object.keys(metadata).length > 0) this.extra = this.extra ? { + ...this.extra, + metadata: { + ...this.extra.metadata, + ...metadata + } + } : { metadata }; + } + _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { + const runExtra = run.extra ?? {}; + if (runExtra?.runtime?.library === void 0) { + if (!runExtra.runtime) runExtra.runtime = {}; + if (runtimeEnv) { + for (const [k, v] of Object.entries(runtimeEnv)) if (!runExtra.runtime[k]) runExtra.runtime[k] = v; + } + } + const parent_run_id = run.parent_run?.id ?? run.parent_run_id; + let child_runs; + if (!excludeChildRuns) child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); + else child_runs = []; + return { + id: run.id, + name: run.name, + start_time: run._serialized_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, + attachments: run.attachments, + events: run.events + }; + } + _sliceParentId(parentId, run) { + /** + * Slice the parent id from dotted order. + * Additionally check if the current run is a child of the parent. If so, update + * the parent_run_id to undefined, and set the trace id to the new root id after + * parent_id. + */ + if (run.dotted_order) { + const segs = run.dotted_order.split("."); + let startIdx = null; + for (let idx = 0; idx < segs.length; idx++) if (segs[idx].slice(-36) === parentId) { + startIdx = idx; + break; + } + if (startIdx !== null) { + const trimmedSegs = segs.slice(startIdx + 1); + run.dotted_order = trimmedSegs.join("."); + if (trimmedSegs.length > 0) run.trace_id = trimmedSegs[0].slice(-36); + else run.trace_id = run.id; + } + } + if (run.parent_run_id === parentId) run.parent_run_id = void 0; + } + _setReplicaTraceRoot(replicaKey, traceRootId) { + const replicaTraceRoots = getContextVar(this, _REPLICA_TRACE_ROOTS_KEY) ?? {}; + replicaTraceRoots[replicaKey] = traceRootId; + setContextVar(this, _REPLICA_TRACE_ROOTS_KEY, replicaTraceRoots); + for (const child of this.child_runs) child._setReplicaTraceRoot(replicaKey, traceRootId); + } + _remapForProject(params) { + const { projectName, runtimeEnv, excludeChildRuns = true, reroot = false, distributedParentId, apiUrl, apiKey, workspaceId } = params; + const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + if (projectName === this.project_name) return { + ...baseRun, + session_name: projectName + }; + if (reroot) { + if (distributedParentId) this._sliceParentId(distributedParentId, baseRun); + else { + baseRun.parent_run_id = void 0; + if (baseRun.dotted_order) { + const segs = baseRun.dotted_order.split("."); + if (segs.length > 0) { + baseRun.dotted_order = segs[segs.length - 1]; + baseRun.trace_id = baseRun.id; + } + } + } + const replicaKey = getReplicaKey({ + projectName, + apiUrl, + apiKey, + workspaceId + }); + this._setReplicaTraceRoot(replicaKey, baseRun.id); + } + let ancestorRerootedTraceId; + if (!reroot) { + ancestorRerootedTraceId = (getContextVar(this, _REPLICA_TRACE_ROOTS_KEY) ?? {})[getReplicaKey({ + projectName, + apiUrl, + apiKey, + workspaceId + })]; + if (ancestorRerootedTraceId) { + baseRun.trace_id = ancestorRerootedTraceId; + if (baseRun.dotted_order) { + const segs = baseRun.dotted_order.split("."); + let rootIdx = null; + for (let idx = 0; idx < segs.length; idx++) if (segs[idx].slice(-36) === ancestorRerootedTraceId) { + rootIdx = idx; + break; + } + if (rootIdx !== null) baseRun.dotted_order = segs.slice(rootIdx).join("."); + } + } + } + const oldId = baseRun.id; + const newId = nonCryptographicUuid7Deterministic(oldId, projectName); + let newTraceId; + if (baseRun.trace_id) newTraceId = nonCryptographicUuid7Deterministic(baseRun.trace_id, projectName); + else newTraceId = newId; + let newParentId; + if (baseRun.parent_run_id) newParentId = nonCryptographicUuid7Deterministic(baseRun.parent_run_id, projectName); + let newDottedOrder; + if (baseRun.dotted_order) newDottedOrder = baseRun.dotted_order.split(".").map((seg) => { + const remappedId = nonCryptographicUuid7Deterministic(seg.slice(-36), projectName); + return seg.slice(0, -36) + remappedId; + }).join("."); + return { + ...baseRun, + id: newId, + trace_id: newTraceId, + parent_run_id: newParentId, + dotted_order: newDottedOrder, + session_name: projectName + }; + } + async postRun(excludeChildRuns = true) { + if (this._awaitInputsOnPost) this.inputs = await this.inputs; + try { + const runtimeEnv = getRuntimeEnvironment(); + if (this.replicas && this.replicas.length > 0) for (const { projectName, apiKey, apiUrl, workspaceId, reroot, client: replicaClient } of this.replicas) { + const runCreate = this._remapForProject({ + projectName: projectName ?? this.project_name, + runtimeEnv, + excludeChildRuns: true, + reroot, + distributedParentId: this.distributedParentId, + apiUrl, + apiKey, + workspaceId + }); + await (replicaClient ?? this.client).createRun(runCreate, { + apiKey, + apiUrl, + workspaceId + }); + } + else { + const runCreate = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + 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); + } + this.child_runs = []; + } catch (error) { + console.error(`Error in postRun for run ${this.id}:`, error); + } + } + async patchRun(options) { + if (this.replicas && this.replicas.length > 0) for (const { projectName, apiKey, apiUrl, workspaceId, updates, reroot, client: replicaClient } of this.replicas) { + const runData = this._remapForProject({ + projectName: projectName ?? this.project_name, + runtimeEnv: void 0, + excludeChildRuns: true, + reroot, + distributedParentId: this.distributedParentId, + apiUrl, + apiKey, + workspaceId + }); + const updatePayload = { + id: runData.id, + name: runData.name, + run_type: runData.run_type, + start_time: runData.start_time, + outputs: runData.outputs, + error: runData.error, + parent_run_id: runData.parent_run_id, + session_name: runData.session_name, + reference_example_id: runData.reference_example_id, + end_time: runData.end_time, + dotted_order: runData.dotted_order, + trace_id: runData.trace_id, + events: runData.events, + tags: runData.tags, + extra: runData.extra, + attachments: this.attachments, + ...updates + }; + if (!options?.excludeInputs) updatePayload.inputs = runData.inputs; + await (replicaClient ?? this.client).updateRun(runData.id, updatePayload, { + apiKey, + apiUrl, + workspaceId + }); + } + else try { + const runUpdate = { + name: this.name, + run_type: this.run_type, + start_time: this._serialized_start_time ?? this.start_time, + end_time: this.end_time, + error: this.error, + outputs: this.outputs, + parent_run_id: this.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, + attachments: this.attachments, + session_name: this.project_name + }; + if (!options?.excludeInputs) runUpdate.inputs = this.inputs; + await this.client.updateRun(this.id, runUpdate); + } catch (error) { + console.error(`Error in patchRun for run ${this.id}`, error); + } + this.child_runs = []; + } + toJSON() { + return this._convertToCreate(this, void 0, false); + } + /** + * Add an event to the run tree. + * @param event - A single event or string to add + */ + addEvent(event) { + if (!this.events) this.events = []; + if (typeof event === "string") this.events.push({ + name: "event", + time: (/* @__PURE__ */ new Date()).toISOString(), + message: event + }); + else this.events.push({ + ...event, + time: event.time ?? (/* @__PURE__ */ new Date()).toISOString() + }); + } + static fromRunnableConfig(parentConfig, props) { + const callbackManager = parentConfig?.callbacks; + let parentRun; + let projectName; + let client; + let tracingEnabled = isEnvTracingEnabled(); + if (callbackManager) { + const parentRunId = callbackManager?.getParentRunId?.() ?? ""; + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); + parentRun = langChainTracer?.getRun?.(parentRunId); + projectName = langChainTracer?.projectName; + client = langChainTracer?.client; + tracingEnabled = tracingEnabled || !!langChainTracer; + } + if (!parentRun) return new RunTree({ + ...props, + client, + tracingEnabled, + project_name: projectName + }); + return new RunTree({ + name: parentRun.name, + id: parentRun.id, + trace_id: parentRun.trace_id, + dotted_order: parentRun.dotted_order, + client, + tracingEnabled, + project_name: projectName, + tags: [...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? []))], + extra: { metadata: { + ...parentRun?.extra?.metadata, + ...parentConfig?.metadata + } } + }).createChild(props); + } + static fromDottedOrder(dottedOrder) { + return this.fromHeaders({ "langsmith-trace": dottedOrder }); + } + static fromHeaders(headers, inheritArgs) { + const rawHeaders = "get" in headers && typeof headers.get === "function" ? { + "langsmith-trace": headers.get("langsmith-trace"), + baggage: headers.get("baggage") + } : headers; + const headerTrace = rawHeaders["langsmith-trace"]; + if (!headerTrace || typeof headerTrace !== "string") return void 0; + const parentDottedOrder = headerTrace.trim(); + const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { + const [strTime, uuid] = part.split("Z"); + return { + strTime, + time: Date.parse(strTime + "Z"), + uuid + }; + }); + const traceId = parsedDottedOrder[0].uuid; + const config = { + ...inheritArgs, + name: inheritArgs?.["name"] ?? "parent", + run_type: inheritArgs?.["run_type"] ?? "chain", + start_time: inheritArgs?.["start_time"] ?? Date.now(), + id: parsedDottedOrder.at(-1)?.uuid, + trace_id: traceId, + dotted_order: parentDottedOrder + }; + if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { + const baggage = Baggage.fromHeader(rawHeaders["baggage"]); + config.metadata = baggage.metadata; + config.tags = baggage.tags; + config.project_name = baggage.project_name; + config.replicas = baggage.replicas; + } + const runTree = new RunTree(config); + runTree.distributedParentId = runTree.id; + return runTree; + } + toHeaders(headers) { + const result = { + "langsmith-trace": this.dotted_order, + baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name, this.replicas).toHeader() + }; + if (headers) for (const [key, value] of Object.entries(result)) headers.set(key, value); + return result; + } +}; +Object.defineProperty(RunTree, "sharedClient", { + enumerable: true, + configurable: true, + writable: true, + value: null +}); +function isRunTree(x) { + return x != null && typeof x.createChild === "function" && typeof x.postRun === "function"; +} +function isLangChainTracerLike(x) { + return typeof x === "object" && x != null && typeof x.name === "string" && x.name === "langchain_tracer"; +} +function containsLangChainTracerLike(x) { + return Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback)); +} +function isCallbackManagerLike(x) { + return typeof x === "object" && x != null && Array.isArray(x.handlers); +} +function isRunnableConfigLike(x) { + const callbacks = x?.callbacks; + return x != null && typeof callbacks === "object" && (containsLangChainTracerLike(callbacks?.handlers) || containsLangChainTracerLike(callbacks)); +} +function _getWriteReplicasFromEnv() { + const envVar = getEnvironmentVariable("LANGSMITH_RUNS_ENDPOINTS"); + if (!envVar) return []; + try { + const parsed = JSON.parse(envVar); + if (Array.isArray(parsed)) { + const replicas = []; + for (const item of parsed) { + if (typeof item !== "object" || item === null) { + console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof item}`); + continue; + } + if (typeof item.api_url !== "string") { + console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof item.api_url}`); + continue; + } + if (typeof item.api_key !== "string") { + console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof item.api_key}`); + continue; + } + replicas.push({ + apiUrl: item.api_url.replace(/\/$/, ""), + apiKey: item.api_key + }); + } + return replicas; + } else if (typeof parsed === "object" && parsed !== null) { + _checkEndpointEnvUnset(parsed); + const replicas = []; + for (const [url, key] of Object.entries(parsed)) { + const cleanUrl = url.replace(/\/$/, ""); + if (typeof key === "string") replicas.push({ + apiUrl: cleanUrl, + apiKey: key + }); + else { + console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${url}: expected string, got ${typeof key}`); + continue; + } + } + return replicas; + } else { + console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof parsed}`); + return []; + } + } catch (e) { + if (isConflictingEndpointsError(e)) throw e; + console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"); + return []; + } +} +function _ensureWriteReplicas(replicas) { + if (replicas) return replicas.map((replica) => { + if (Array.isArray(replica)) return { + projectName: replica[0], + updates: replica[1] + }; + return replica; + }); + return _getWriteReplicasFromEnv(); +} +function _checkEndpointEnvUnset(parsed) { + if (Object.keys(parsed).length > 0 && getLangSmithEnvironmentVariable("ENDPOINT")) throw new ConflictingEndpointsError(); +} +//#endregion +//#region node_modules/@langchain/core/dist/tracers/base.js +var base_exports$1 = /* @__PURE__ */ __exportAll({ + BaseTracer: () => BaseTracer, + isBaseTracer: () => isBaseTracer +}); +var convertRunTreeToRun = (runTree) => { + if (!runTree) return; + runTree.events = runTree.events ?? []; + runTree.child_runs = runTree.child_runs ?? []; + return runTree; +}; +function convertRunToRunTree(run, parentRun) { + if (!run) return; + return new RunTree({ + ...run, + start_time: run._serialized_start_time ?? run.start_time, + parent_run: convertRunToRunTree(parentRun), + child_runs: run.child_runs.map((r) => convertRunToRunTree(r)).filter((r) => r !== void 0), + extra: { + ...run.extra, + runtime: getRuntimeEnvironment$1() + }, + tracingEnabled: false + }); +} +function _coerceToDict$1(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; +} +function isBaseTracer(x) { + return typeof x._addRunToRunMap === "function"; +} +var BaseTracer = class extends BaseCallbackHandler { + /** @deprecated Use `runTreeMap` instead. */ + runMap = /* @__PURE__ */ new Map(); + runTreeMap = /* @__PURE__ */ new Map(); + usesRunTreeMap = false; + constructor(_fields) { + super(...arguments); + } + copy() { + return this; + } + getRunById(runId) { + if (runId === void 0) return; + return this.usesRunTreeMap ? convertRunTreeToRun(this.runTreeMap.get(runId)) : this.runMap.get(runId); + } + stringifyError(error) { + if (error instanceof Error) return error.message + (error?.stack ? `\n\n${error.stack}` : ""); + if (typeof error === "string") return error; + return `${error}`; + } + _addChildRun(parentRun, childRun) { + parentRun.child_runs.push(childRun); + } + _addRunToRunMap(run) { + const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order); + const storedRun = { ...run }; + const parentRun = this.getRunById(storedRun.parent_run_id); + if (storedRun.parent_run_id !== void 0) 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("."); + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } + } else storedRun.parent_run_id = void 0; + else { + storedRun.trace_id = storedRun.id; + storedRun.dotted_order = currentDottedOrder; + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } + if (this.usesRunTreeMap) { + const runTree = convertRunToRunTree(storedRun, parentRun); + if (runTree !== void 0) this.runTreeMap.set(storedRun.id, runTree); + } else this.runMap.set(storedRun.id, storedRun); + return storedRun; + } + async _endTrace(run) { + const parentRun = run.parent_run_id !== void 0 && this.getRunById(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); + await this.onRunUpdate?.(run); + if (this.usesRunTreeMap) this.runTreeMap.delete(run.id); + else this.runMap.delete(run.id); + } + _getExecutionOrder(parentRunId) { + const parentRun = parentRunId !== void 0 && this.getRunById(parentRunId); + if (!parentRun) return 1; + return parentRun.child_execution_order + 1; + } + /** + * Create and add a run to the run map for LLM start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata ? { + ...extraParams, + metadata + } : extraParams; + const run = { + id: runId, + name: name ?? 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 || [] + }; + return this._addRunToRunMap(run); + } + async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + /** + * Create and add a run to the run map for chat model start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata ? { + ...extraParams, + metadata + } : extraParams; + const run = { + id: runId, + name: name ?? 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 }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(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() + }); + run.extra = { + ...run.extra, + ...extraParams + }; + await this.onLLMEnd?.(run); + await this._endTrace(run); + return run; + } + async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(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() + }); + run.extra = { + ...run.extra, + ...extraParams + }; + await this.onLLMError?.(run); + await this._endTrace(run); + return run; + } + /** + * Create and add a run to the run map for chain start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name, extra) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? 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 ? { + ...extra, + metadata + } : { ...extra }, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const run = this.getRunById(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); + await this.onRunCreate?.(run); + await this.onChainStart?.(run); + return run; + } + async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(runId); + if (!run) throw new Error("No chain run to end."); + run.end_time = Date.now(); + run.outputs = _coerceToDict$1(outputs, "output"); + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + if (kwargs?.inputs !== void 0) run.inputs = _coerceToDict$1(kwargs.inputs, "input"); + await this.onChainEnd?.(run); + await this._endTrace(run); + return run; + } + async handleChainError(error, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(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$1(kwargs.inputs, "input"); + await this.onChainError?.(run); + await this._endTrace(run); + return run; + } + /** + * Create and add a run to the run map for tool start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? 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 || [] + }; + return this._addRunToRunMap(run); + } + async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onToolStart?.(run); + return run; + } + async handleToolEnd(output, runId) { + const run = this.getRunById(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.getRunById(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.getRunById(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: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { action } + }); + await this.onAgentAction?.(run); + } + async handleAgentEnd(action, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") return; + run.events.push({ + name: "agent_end", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { action } + }); + await this.onAgentEnd?.(run); + } + /** + * Create and add a run to the run map for retriever start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? 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 || [] + }; + return this._addRunToRunMap(run); + } + async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onRetrieverStart?.(run); + return run; + } + async handleRetrieverEnd(documents, runId) { + const run = this.getRunById(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.getRunById(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.getRunById(runId); + if (!run || run?.run_type !== "chain") return; + run.events.push({ + name: "text", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { text } + }); + await this.onText?.(run); + } + async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); + run.events.push({ + name: "new_token", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { + token, + idx, + chunk: fields?.chunk + } + }); + await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); + return run; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/tracers/console.js +var console_exports = /* @__PURE__ */ __exportAll({ ConsoleCallbackHandler: () => ConsoleCallbackHandler }); +var styles = { + bold: { + open: "\x1B[1m", + close: "\x1B[22m" + }, + color: { + grey: { + open: "\x1B[90m", + close: "\x1B[39m" + }, + green: { + open: "\x1B[32m", + close: "\x1B[39m" + }, + cyan: { + open: "\x1B[36m", + close: "\x1B[39m" + }, + red: { + open: "\x1B[31m", + close: "\x1B[39m" + }, + blue: { + open: "\x1B[34m", + close: "\x1B[39m" + } + } +}; +function wrap(style, text) { + return `${style.open}${text}${style.close}`; +} +function tryJsonStringify(obj, fallback) { + try { + return JSON.stringify(obj, null, 2); + } catch { + return fallback; + } +} +function formatKVMapItem(value) { + if (typeof value === "string") return value.trim(); + if (value === null || value === void 0) return value; + return tryJsonStringify(value, value.toString()); +} +function elapsed(run) { + if (!run.end_time) return ""; + const elapsed = run.end_time - run.start_time; + if (elapsed < 1e3) return `${elapsed}ms`; + return `${(elapsed / 1e3).toFixed(2)}s`; +} +var { color } = styles; +/** +* A tracer that logs all events to the console. It extends from the +* `BaseTracer` class and overrides its methods to provide custom logging +* functionality. +* @example +* ```typescript +* +* const llm = new ChatAnthropic({ +* temperature: 0, +* tags: ["example", "callbacks", "constructor"], +* callbacks: [new ConsoleCallbackHandler()], +* }); +* +* ``` +*/ +var ConsoleCallbackHandler = class extends BaseTracer { + name = "console_callback_handler"; + /** + * Method used to persist the run. In this case, it simply returns a + * resolved promise as there's no persistence logic. + * @param _run The run to persist. + * @returns A resolved promise. + */ + persistRun(_run) { + return Promise.resolve(); + } + /** + * Method used to get all the parent runs of a given run. + * @param run The run whose parents are to be retrieved. + * @returns An array of parent runs. + */ + 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; + } + /** + * Method used to get a string representation of the run's lineage, which + * is used in logging. + * @param run The run whose lineage is to be retrieved. + * @returns A string representation of the run's lineage. + */ + getBreadcrumbs(run) { + const string = [...this.getParents(run).reverse(), run].map((parent, i, arr) => { + const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; + return i === arr.length - 1 ? wrap(styles.bold, name) : name; + }).join(" > "); + return wrap(color.grey, string); + } + /** + * Method used to log the start of a chain run. + * @param run The chain run that has started. + * @returns void + */ + onChainStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a chain run. + * @param run The chain run that has ended. + * @returns void + */ + 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]")}`); + } + /** + * Method used to log any errors of a chain run. + * @param run The chain run that has errored. + * @returns void + */ + 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]")}`); + } + /** + * Method used to log the start of an LLM run. + * @param run The LLM run that has started. + * @returns void + */ + onLLMStart(run) { + const crumbs = this.getBreadcrumbs(run); + const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p) => p.trim()) } : run.inputs; + console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); + } + /** + * Method used to log the end of an LLM run. + * @param run The LLM run that has ended. + * @returns void + */ + 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]")}`); + } + /** + * Method used to log any errors of an LLM run. + * @param run The LLM run that has errored. + * @returns void + */ + 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]")}`); + } + /** + * Method used to log the start of a tool run. + * @param run The tool run that has started. + * @returns void + */ + onToolStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); + } + /** + * Method used to log the end of a tool run. + * @param run The tool run that has ended. + * @returns void + */ + onToolEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); + } + /** + * Method used to log any errors of a tool run. + * @param run The tool run that has errored. + * @returns void + */ + 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]")}`); + } + /** + * Method used to log the start of a retriever run. + * @param run The retriever run that has started. + * @returns void + */ + onRetrieverStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a retriever run. + * @param run The retriever run that has ended. + * @returns void + */ + 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]")}`); + } + /** + * Method used to log any errors of a retriever run. + * @param run The retriever run that has errored. + * @returns void + */ + 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]")}`); + } + /** + * Method used to log the action selected by the agent. + * @param run The run in which the agent action occurred. + * @returns void + */ + 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]")}`); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/singletons/tracer.js +var client; +var getDefaultLangChainClientSingleton = () => { + if (client === void 0) client = new Client(getEnvironmentVariable$1("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { blockOnRootRunFinalization: true } : {}); + return client; +}; +//#endregion +//#region node_modules/@langchain/core/dist/tracers/tracer_langchain.js +var tracer_langchain_exports = /* @__PURE__ */ __exportAll({ + LangChainTracer: () => LangChainTracer, + OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS: () => OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS +}); +/** +* Keys that should be inherited from `tracerInheritableMetadata` even when +* the run already has a value for them. This lets nested contexts +* (e.g. a subagent invoked from inside a parent agent) override a +* LangSmith-only tracing metadata value that was set by an ancestor. +* +* Keep this list very small: every key here loses the default +* "first wins" protection and is always clobbered by the nearest +* enclosing tracer config. Only keys that are strictly for LangSmith +* tracing bookkeeping should be added. +*/ +var OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS = /* @__PURE__ */ new Set(["ls_agent_type"]); +/** +* Extract usage_metadata from chat generations. +* +* Iterates through generations to find and aggregates all usage_metadata +* found in chat messages. This is typically present in chat model outputs. +*/ +function _getUsageMetadataFromGenerations(generations) { + let output = void 0; + for (const generationBatch of generations) for (const generation of generationBatch) if (AIMessage.isInstance(generation.message) && generation.message.usage_metadata !== void 0) output = mergeUsageMetadata(output, generation.message.usage_metadata); + return output; +} +var LangChainTracer = class LangChainTracer extends BaseTracer { + name = "langchain_tracer"; + projectName; + exampleId; + client; + replicas; + usesRunTreeMap = true; + tracingMetadata; + tracingTags = []; + constructor(fields = {}) { + super(fields); + this.fields = fields; + const { exampleId, projectName, client, replicas, metadata, tags } = fields; + this.projectName = projectName ?? getDefaultProjectName(); + this.replicas = replicas; + this.exampleId = exampleId; + this.client = client ?? getDefaultLangChainClientSingleton(); + this.tracingMetadata = metadata ? { ...metadata } : void 0; + this.tracingTags = tags ?? []; + const traceableTree = LangChainTracer.getTraceableRunTree(); + if (traceableTree) this.updateFromRunTree(traceableTree); + } + async persistRun(_run) {} + async onRunCreate(run) { + _patchMissingTracingDefaults(this, run); + if (!run.extra?.lc_defers_inputs) await this.getRunTreeWithTracingConfig(run.id)?.postRun(); + } + async onRunUpdate(run) { + _patchMissingTracingDefaults(this, run); + const runTree = this.getRunTreeWithTracingConfig(run.id); + if (run.extra?.lc_defers_inputs) await runTree?.postRun(); + else await runTree?.patchRun(); + } + onLLMEnd(run) { + const outputs = run.outputs; + if (outputs?.generations) { + const usageMetadata = _getUsageMetadataFromGenerations(outputs.generations); + if (usageMetadata !== void 0) { + run.extra = run.extra ?? {}; + const metadata = run.extra.metadata ?? {}; + metadata.usage_metadata = usageMetadata; + run.extra.metadata = metadata; + } + } + } + copyWithTracingConfig({ metadata, tags }) { + let mergedMetadata; + if (metadata === void 0) mergedMetadata = this.tracingMetadata ? { ...this.tracingMetadata } : void 0; + else if (this.tracingMetadata === void 0) mergedMetadata = { ...metadata }; + else { + mergedMetadata = { ...this.tracingMetadata }; + for (const [key, value] of Object.entries(metadata)) if (!Object.prototype.hasOwnProperty.call(mergedMetadata, key) || OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS.has(key)) mergedMetadata[key] = value; + } + const mergedTags = tags ? Array.from(/* @__PURE__ */ new Set([...this.tracingTags, ...tags])) : [...this.tracingTags]; + const copied = new LangChainTracer({ + ...this.fields, + metadata: mergedMetadata, + tags: mergedTags + }); + copied.runMap = this.runMap; + copied.runTreeMap = this.runTreeMap; + return copied; + } + /** @internal */ + _getRunStoreKey() { + return this.runTreeMap; + } + getRun(id) { + return this.runTreeMap.get(id); + } + updateFromRunTree(runTree) { + this.runTreeMap.set(runTree.id, runTree); + let rootRun = runTree; + const visited = /* @__PURE__ */ new Set(); + while (rootRun.parent_run) { + if (visited.has(rootRun.id)) break; + visited.add(rootRun.id); + if (!rootRun.parent_run) break; + rootRun = rootRun.parent_run; + } + visited.clear(); + const queue = [rootRun]; + while (queue.length > 0) { + const current = queue.shift(); + if (!current || visited.has(current.id)) continue; + visited.add(current.id); + this.runTreeMap.set(current.id, current); + if (current.child_runs) queue.push(...current.child_runs); + } + this.client = runTree.client ?? this.client; + this.replicas = runTree.replicas ?? this.replicas; + this.projectName = runTree.project_name ?? this.projectName; + this.exampleId = runTree.reference_example_id ?? this.exampleId; + this.fields = { + ...this.fields, + client: this.client, + replicas: this.replicas, + projectName: this.projectName, + exampleId: this.exampleId + }; + } + getRunTreeWithTracingConfig(id) { + const runTree = this.runTreeMap.get(id); + if (!runTree) return void 0; + return new RunTree({ + ...runTree, + client: this.client, + project_name: this.projectName, + replicas: this.replicas, + reference_example_id: this.exampleId, + tracingEnabled: true + }); + } + static getTraceableRunTree() { + try { + return getCurrentRunTree(true); + } catch { + return; + } + } + static [Symbol.hasInstance](instance) { + if (typeof instance !== "object" || instance === null) return false; + const candidate = instance; + return "name" in candidate && candidate.name === "langchain_tracer" && "copyWithTracingConfig" in candidate && typeof candidate.copyWithTracingConfig === "function" && "getRunTreeWithTracingConfig" in candidate && typeof candidate.getRunTreeWithTracingConfig === "function"; + } +}; +function _patchMissingTracingDefaults(tracer, run) { + if (tracer.tracingMetadata) { + run.extra ??= {}; + const metadata = run.extra.metadata ?? {}; + let didPatchMetadata = false; + for (const [key, value] of Object.entries(tracer.tracingMetadata)) if (!Object.prototype.hasOwnProperty.call(metadata, key) || OVERRIDABLE_LANGSMITH_INHERITABLE_METADATA_KEYS.has(key)) { + if (metadata[key] !== value) { + metadata[key] = value; + didPatchMetadata = true; + } + } + if (didPatchMetadata) run.extra.metadata = metadata; + } + if (tracer.tracingTags.length > 0) run.tags = Array.from(/* @__PURE__ */ new Set([...run.tags ?? [], ...tracer.tracingTags])); +} +//#endregion +//#region node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js +var TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); +var _CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); +var setGlobalAsyncLocalStorageInstance = (instance) => { + globalThis[TRACING_ALS_KEY] = instance; +}; +var getGlobalAsyncLocalStorageInstance = () => { + return globalThis[TRACING_ALS_KEY]; +}; +//#endregion +//#region node_modules/@langchain/core/dist/singletons/callbacks.js +var queue; +/** +* Creates a queue using the p-queue library. The queue is configured to +* auto-start and has a concurrency of 1, meaning it will process tasks +* one at a time. +*/ +function createQueue() { + return new ("default" in import_dist.default ? import_dist.default.default : import_dist.default)({ + autoStart: true, + concurrency: 1 + }); +} +function getQueue() { + if (typeof queue === "undefined") queue = createQueue(); + return queue; +} +/** +* Consume a promise, either adding it to the queue or waiting for it to resolve +* @param promiseFn Promise to consume +* @param wait Whether to wait for the promise to resolve or resolve immediately +*/ +async function consumeCallback(promiseFn, wait) { + if (wait === true) { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); + else await promiseFn(); + } else { + queue = getQueue(); + queue.add(async () => { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); + else await promiseFn(); + }); + } +} +/** +* Waits for all promises in the queue to resolve. If the queue is +* undefined, it immediately resolves a promise. +*/ +async function awaitAllCallbacks() { + const defaultClient = getDefaultLangChainClientSingleton(); + await Promise.allSettled([typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(), defaultClient.awaitPendingTraceBatches()]); +} +//#endregion +//#region node_modules/@langchain/core/dist/callbacks/promises.js +var promises_exports = /* @__PURE__ */ __exportAll({ + awaitAllCallbacks: () => awaitAllCallbacks, + consumeCallback: () => consumeCallback +}); +//#endregion +//#region node_modules/@langchain/core/dist/utils/callbacks.js +var isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== void 0) return tracingEnabled; + return !![ + "LANGSMITH_TRACING_V2", + "LANGCHAIN_TRACING_V2", + "LANGSMITH_TRACING", + "LANGCHAIN_TRACING" + ].find((envVar) => getEnvironmentVariable$1(envVar) === "true"); +}; +//#endregion +//#region node_modules/@langchain/core/dist/singletons/async_local_storage/context.js +/** +* Get the value of a previously set context variable. Context variables +* are scoped to any child runnables called by the current runnable, +* or globally if set outside of any runnable. +* +* @remarks +* This function is only supported in environments that support AsyncLocalStorage, +* including Node.js, Deno, and Cloudflare Workers. +* +* @example +* ```ts +* import { RunnableLambda } from "@langchain/core/runnables"; +* import { +* getContextVariable, +* setContextVariable +* } from "@langchain/core/context"; +* +* const nested = RunnableLambda.from(() => { +* // "bar" because it was set by a parent +* console.log(getContextVariable("foo")); +* +* // Override to "baz", but only for child runnables +* setContextVariable("foo", "baz"); +* +* // Now "baz", but only for child runnables +* return getContextVariable("foo"); +* }); +* +* const runnable = RunnableLambda.from(async () => { +* // Set a context variable named "foo" +* setContextVariable("foo", "bar"); +* +* const res = await nested.invoke({}); +* +* // Still "bar" since child changes do not affect parents +* console.log(getContextVariable("foo")); +* +* return res; +* }); +* +* // undefined, because context variable has not been set yet +* console.log(getContextVariable("foo")); +* +* // Final return value is "baz" +* const result = await runnable.invoke({}); +* ``` +* +* @param name The name of the context variable. +*/ +function getContextVariable(name) { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance === void 0) return; + return asyncLocalStorageInstance.getStore()?.[_CONTEXT_VARIABLES_KEY]?.[name]; +} +var LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); +var _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; +//#endregion +//#region node_modules/@langchain/core/dist/callbacks/manager.js +var manager_exports = /* @__PURE__ */ __exportAll({ + BaseCallbackManager: () => BaseCallbackManager, + BaseRunManager: () => BaseRunManager, + CallbackManager: () => CallbackManager, + CallbackManagerForChainRun: () => CallbackManagerForChainRun, + CallbackManagerForLLMRun: () => CallbackManagerForLLMRun, + CallbackManagerForRetrieverRun: () => CallbackManagerForRetrieverRun, + CallbackManagerForToolRun: () => CallbackManagerForToolRun, + ensureHandler: () => ensureHandler, + parseCallbackConfigArg: () => parseCallbackConfigArg +}); +function getTracerRunStoreKey(tracer) { + return tracer._getRunStoreKey?.() ?? tracer; +} +function mergeTracerConfig(target, source) { + if (target === source) return target; + return target.copyWithTracingConfig({ + metadata: source.tracingMetadata, + tags: source.tracingTags + }); +} +function coalesceTracers(handlers, inheritableHandlers) { + const inheritableSet = new Set(inheritableHandlers); + const groups = /* @__PURE__ */ new Map(); + const coalescedHandlers = []; + const fold = (handler) => { + const key = getTracerRunStoreKey(handler); + const isInheritable = inheritableSet.has(handler); + const group = groups.get(key); + if (group === void 0) { + groups.set(key, { + index: coalescedHandlers.length, + tracer: handler, + hasInheritable: isInheritable + }); + coalescedHandlers.push(handler); + return; + } + if (isInheritable && !group.hasInheritable) { + group.tracer = handler; + group.hasInheritable = true; + } else if (isInheritable || !group.hasInheritable) group.tracer = mergeTracerConfig(group.tracer, handler); + coalescedHandlers[group.index] = group.tracer; + }; + for (const handler of handlers) if (handler instanceof LangChainTracer) fold(handler); + else coalescedHandlers.push(handler); + for (const handler of inheritableHandlers) if (handler instanceof LangChainTracer && !groups.has(getTracerRunStoreKey(handler))) fold(handler); + const seenTracerStores = /* @__PURE__ */ new Set(); + return { + handlers: coalescedHandlers, + inheritableHandlers: inheritableHandlers.flatMap((handler) => { + if (!(handler instanceof LangChainTracer)) return [handler]; + const key = getTracerRunStoreKey(handler); + if (seenTracerStores.has(key)) return []; + seenTracerStores.add(key); + return [groups.get(key)?.tracer ?? handler]; + }) + }; +} +function parseCallbackConfigArg(arg) { + if (!arg) return {}; + else if (Array.isArray(arg) || "name" in arg) return { callbacks: arg }; + else return arg; +} +/** +* Manage callbacks from different components of LangChain. +*/ +var BaseCallbackManager = class { + setHandler(handler) { + return this.setHandlers([handler]); + } +}; +/** +* Base class for run manager in LangChain. +*/ +var BaseRunManager = class { + constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { + this.runId = runId; + this.handlers = handlers; + this.inheritableHandlers = inheritableHandlers; + this.tags = tags; + this.inheritableTags = inheritableTags; + this.metadata = metadata; + this.inheritableMetadata = inheritableMetadata; + this._parentRunId = _parentRunId; + } + get parentRunId() { + return this._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) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleText: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleCustomEvent(eventName, data, _runId, _tags, _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +/** +* Manages callbacks for retriever runs. +*/ +var 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) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleRetriever`); + if (handler.raiseError) throw err; + } + }, 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) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +var CallbackManagerForLLMRun = class extends BaseRunManager { + async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { + 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, fields); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleChatModelStreamEvent(event) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) try { + await handler.handleChatModelStreamEvent?.(event, this.runId, this._parentRunId, this.tags); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleChatModelStreamEvent: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) try { + await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleLLMError: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) try { + await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +var 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 (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleChainError: ${err}`); + if (handler.raiseError) throw err; + } + }, 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) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); + if (handler.raiseError) throw 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) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); + if (handler.raiseError) throw 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) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +var 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 (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleToolError: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleToolEvent(chunk) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) try { + await handler.handleToolEvent?.(chunk, this.runId, this._parentRunId, this.tags); + } catch (err) { + if (handler.raiseError) throw err; + } + }, 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) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +/** +* @example +* ```typescript +* const prompt = PromptTemplate.fromTemplate("What is the answer to {question}?"); +* +* // Example of using LLMChain with OpenAI and a simple prompt +* const chain = new LLMChain({ +* llm: new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0.9 }), +* prompt, +* }); +* +* // Running the chain with a single question +* const result = await chain.call({ +* question: "What is the airspeed velocity of an unladen swallow?", +* }); +* console.log("The answer is:", result); +* ``` +*/ +var CallbackManager = class CallbackManager extends BaseCallbackManager { + handlers = []; + inheritableHandlers = []; + tags = []; + inheritableTags = []; + metadata = {}; + inheritableMetadata = {}; + name = "callback_manager"; + _parentRunId; + constructor(parentRunId, options) { + super(); + 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; + } + /** + * Gets the parent run ID, if any. + * + * @returns The parent run ID. + */ + 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, idx) => { + const runId_ = idx === 0 && runId ? runId : v7$1(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) return; + if (isBaseTracer(handler)) handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + return consumeCallback(async () => { + try { + await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChatModelStart(llm, messages, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + return Promise.all(messages.map(async (messageGroup, idx) => { + const runId_ = idx === 0 && runId ? runId : v7$1(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) return; + if (isBaseTracer(handler)) handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + return consumeCallback(async () => { + 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) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) throw 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 = v7$1(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0, _parentRunId = void 0, extra = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreChain) return; + if (isBaseTracer(handler)) handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra); + return consumeCallback(async () => { + try { + await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); + if (handler.raiseError) throw 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 = v7$1(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0, toolCallId = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreAgent) return; + if (isBaseTracer(handler)) handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); + return consumeCallback(async () => { + try { + await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName, toolCallId); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); + if (handler.raiseError) throw 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 = v7$1(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreRetriever) return; + if (isBaseTracer(handler)) handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + return consumeCallback(async () => { + try { + await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleCustomEvent(eventName, data, runId, _tags, _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreCustomEvent) try { + await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); + } catch (err) { + (handler.raiseError ? console.error : console.warn)(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + 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((h) => h.name === "console_callback_handler").some((h) => h.name === handler.name)) continue; + manager.addHandler(handler, inherit); + } + return manager; + } + static fromHandlers(handlers) { + class Handler extends BaseCallbackHandler { + name = v7$1(); + constructor() { + super(); + Object.assign(this, handlers); + } + } + const manager = new this(); + manager.addHandler(new Handler()); + return manager; + } + static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); + } + static _configureSync(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$1("LANGCHAIN_VERBOSE") === "true" || options?.verbose; + const traceableRunTree = LangChainTracer.getTraceableRunTree(); + const tracingV2Enabled = traceableRunTree?.tracingEnabled ?? isTracingEnabled(); + if (traceableRunTree?.tracingEnabled === false && callbackManager) { + const inheritedTracers = callbackManager.handlers.filter((handler) => handler.name === "langchain_tracer"); + for (const tracer of inheritedTracers) callbackManager.removeHandler(tracer); + } + const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable$1("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) { + const tracerV2 = new LangChainTracer(); + callbackManager.addHandler(tracerV2, true); + } + } + if (tracingV2Enabled) { + if (traceableRunTree && callbackManager._parentRunId === void 0) { + callbackManager._parentRunId = traceableRunTree.id; + callbackManager.handlers.find((handler) => handler.name === "langchain_tracer")?.updateFromRunTree(traceableRunTree); + } + } + } + for (const { contextVar, inheritable = true, handlerClass, envVar } of _getConfigureHooks()) { + const createIfNotInContext = envVar && getEnvironmentVariable$1(envVar) === "true" && handlerClass; + let handler; + const contextVarValue = contextVar !== void 0 ? getContextVariable(contextVar) : void 0; + if (contextVarValue && isBaseCallbackHandler(contextVarValue)) handler = contextVarValue; + else if (createIfNotInContext) handler = new handlerClass({}); + if (handler !== void 0) { + if (!callbackManager) callbackManager = new CallbackManager(); + if (!callbackManager.handlers.some((h) => h.name === handler.name)) callbackManager.addHandler(handler, inheritable); + } + } + if (inheritableTags || localTags) { + if (callbackManager) { + callbackManager.addTags(inheritableTags ?? []); + callbackManager.addTags(localTags ?? [], false); + } + } + if (inheritableMetadata || localMetadata) { + if (callbackManager) { + callbackManager.addMetadata(inheritableMetadata ?? {}); + callbackManager.addMetadata(localMetadata ?? {}, false); + } + } + const tracerInheritableMetadata = options?.tracerInheritableMetadata; + const tracerInheritableTags = options?.tracerInheritableTags; + if (callbackManager && (tracerInheritableMetadata || tracerInheritableTags)) { + const replacements = /* @__PURE__ */ new Map(); + const applyTracingConfig = (handler) => { + if (!(handler instanceof LangChainTracer)) return handler; + const existing = replacements.get(handler); + if (existing !== void 0) return existing; + const replacement = handler.copyWithTracingConfig({ + metadata: tracerInheritableMetadata, + tags: tracerInheritableTags + }); + replacements.set(handler, replacement); + return replacement; + }; + callbackManager.handlers = callbackManager.handlers.map(applyTracingConfig); + callbackManager.inheritableHandlers = callbackManager.inheritableHandlers.map(applyTracingConfig); + } + if (callbackManager) { + const coalesced = coalesceTracers(callbackManager.handlers, callbackManager.inheritableHandlers); + callbackManager.handlers = coalesced.handlers; + callbackManager.inheritableHandlers = coalesced.inheritableHandlers; + } + return callbackManager; + } +}; +function ensureHandler(handler) { + if ("name" in handler) return handler; + return BaseCallbackHandler.fromMethods(handler); +} +//#endregion +//#region node_modules/@langchain/core/dist/singletons/async_local_storage/index.js +var MockAsyncLocalStorage = class { + getStore() {} + run(_store, callback) { + return callback(); + } + enterWith(_store) {} +}; +var mockAsyncLocalStorage = new MockAsyncLocalStorage(); +var LC_CHILD_KEY = Symbol.for("lc:child_config"); +var AsyncLocalStorageProvider = class { + getInstance() { + return getGlobalAsyncLocalStorageInstance() ?? mockAsyncLocalStorage; + } + getRunnableConfig() { + return this.getInstance().getStore()?.extra?.[LC_CHILD_KEY]; + } + runWithConfig(config, callback, avoidCreatingRootRunTree) { + const callbackManager = CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); + const storage = this.getInstance(); + const previousValue = storage.getStore(); + const parentRunId = callbackManager?.getParentRunId(); + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); + let runTree; + if (langChainTracer && parentRunId) runTree = langChainTracer.getRunTreeWithTracingConfig(parentRunId); + else if (!avoidCreatingRootRunTree) runTree = new RunTree({ + name: "", + tracingEnabled: false + }); + if (runTree) runTree.extra = { + ...runTree.extra, + [LC_CHILD_KEY]: config + }; + if (previousValue !== void 0 && previousValue[_CONTEXT_VARIABLES_KEY] !== void 0) { + if (runTree === void 0) runTree = {}; + runTree[_CONTEXT_VARIABLES_KEY] = previousValue[_CONTEXT_VARIABLES_KEY]; + } + return storage.run(runTree, callback); + } + initializeGlobalInstance(instance) { + if (getGlobalAsyncLocalStorageInstance() === void 0) setGlobalAsyncLocalStorageInstance(instance); + } +}; +var AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); +//#endregion +//#region node_modules/@langchain/core/dist/singletons/index.js +var singletons_exports = /* @__PURE__ */ __exportAll({ + AsyncLocalStorageProviderSingleton: () => AsyncLocalStorageProviderSingleton, + MockAsyncLocalStorage: () => MockAsyncLocalStorage, + _CONTEXT_VARIABLES_KEY: () => _CONTEXT_VARIABLES_KEY +}); +//#endregion +//#region node_modules/@langchain/core/dist/runnables/config.js +var CONFIGURABLE_TO_TRACING_METADATA_EXCLUDED_KEYS = /* @__PURE__ */ new Set(["api_key"]); +var PRIMITIVES = /* @__PURE__ */ new Set([ + "string", + "number", + "boolean" +]); +function _getTracingInheritableMetadataFromConfig(config) { + const configurable = config.configurable ?? {}; + const metadata = config.metadata ?? {}; + const langSmithMetadata = {}; + for (const [key, value] of Object.entries(configurable)) if (!key.startsWith("__") && !Object.prototype.hasOwnProperty.call(metadata, key) && !CONFIGURABLE_TO_TRACING_METADATA_EXCLUDED_KEYS.has(key) && PRIMITIVES.has(typeof value)) langSmithMetadata[key] = value; + return Object.keys(langSmithMetadata).length > 0 ? langSmithMetadata : void 0; +} +async function getCallbackManagerForConfig(config) { + return CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata, void 0, { tracerInheritableMetadata: config ? _getTracingInheritableMetadataFromConfig(config) : void 0 }); +} +function mergeConfigs(...configs) { + const copy = {}; + for (const options of configs.filter((c) => !!c)) for (const key of Object.keys(options)) if (key === "metadata") copy[key] = { + ...copy[key], + ...options[key] + }; + else if (key === "tags") { + const baseKeys = copy[key] ?? []; + copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; + } else if (key === "configurable") copy[key] = { + ...copy[key], + ...options[key] + }; + else if (key === "timeout") { + if (copy.timeout === void 0) copy.timeout = options.timeout; + else if (options.timeout !== void 0) copy.timeout = Math.min(copy.timeout, options.timeout); + } else if (key === "signal") { + if (copy.signal === void 0) copy.signal = options.signal; + else if (options.signal !== void 0) if ("any" in AbortSignal) copy.signal = AbortSignal.any([copy.signal, options.signal]); + else copy.signal = options.signal; + } 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; +} +/** +* Ensure that a passed config is an object with all required keys present. +*/ +function ensureConfig(config) { + const implicitConfig = AsyncLocalStorageProviderSingleton.getRunnableConfig(); + let empty = { + tags: [], + metadata: {}, + recursionLimit: 25, + runId: void 0 + }; + if (implicitConfig) { + const { runId, runName, ...rest } = implicitConfig; + empty = Object.entries(rest).reduce((currentConfig, [key, value]) => { + if (value !== void 0) currentConfig[key] = value; + return currentConfig; + }, empty); + } + if (config) empty = Object.entries(config).reduce((currentConfig, [key, value]) => { + if (value !== void 0) currentConfig[key] = value; + return currentConfig; + }, empty); + if (empty?.configurable) { + if (typeof empty.configurable.model === "string" && empty.metadata?.model === void 0) { + if (!empty.metadata) empty.metadata = {}; + empty.metadata.model = empty.configurable.model; + } + } + if (empty.timeout !== void 0) { + if (empty.timeout <= 0) throw new Error("Timeout must be a positive number"); + const originalTimeoutMs = empty.timeout; + const timeoutSignal = AbortSignal.timeout(originalTimeoutMs); + if (!empty.metadata) empty.metadata = {}; + if (empty.metadata.timeoutMs === void 0) empty.metadata.timeoutMs = originalTimeoutMs; + if (empty.signal !== void 0) { + if ("any" in AbortSignal) empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); + } else empty.signal = timeoutSignal; + /** + * We are deleting the timeout key for the following reasons: + * - Idempotent normalization: ensureConfig may be called multiple times down the stack. If timeout remains, + * each call would synthesize new timeout signals and combine them, changing the effective timeout unpredictably. + * - Single enforcement path: downstream code relies on signal to enforce cancellation. Leaving timeout means two + * competing mechanisms (numeric timeout and signal) can be applied, sometimes with different semantics. + * - Propagation to children: pickRunnableConfigKeys would keep forwarding timeout to nested runnables, causing + * repeated re-normalization and stacked timeouts. + * - Backward compatibility: a lot of components and tests assume ensureConfig removes timeout post-normalization; + * changing that would be a breaking change. + */ + delete empty.timeout; + } + return empty; +} +/** +* Helper function that patches runnable configs with updated properties. +*/ +function patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId } = {}) { + const newConfig = ensureConfig(config); + if (callbacks !== void 0) { + /** + * If we're replacing callbacks we need to unset runName + * since that should apply only to the same run as the original callbacks + */ + 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 + }; + if (runId !== void 0) delete newConfig.runId; + return newConfig; +} +function pickRunnableConfigKeys(config) { + if (!config) return void 0; + return { + configurable: config.configurable, + recursionLimit: config.recursionLimit, + callbacks: config.callbacks, + tags: config.tags, + metadata: config.metadata, + maxConcurrency: config.maxConcurrency, + timeout: config.timeout, + signal: config.signal, + store: config.store + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/signal.js +/** +* Race a promise with an abort signal. If the signal is aborted, the promise will +* be rejected with the error from the signal. If the promise is rejected, the signal will be aborted. +* +* @param promise - The promise to race. +* @param signal - The abort signal. +* @returns The result of the promise. +*/ +async function raceWithSignal(promise, signal) { + if (signal === void 0) return promise; + let listener; + return Promise.race([promise.catch((err) => { + if (!signal?.aborted) throw err; + else return; + }), new Promise((_, reject) => { + listener = () => { + reject(getAbortSignalError(signal)); + }; + signal.addEventListener("abort", listener, { once: true }); + if (signal.aborted) reject(getAbortSignalError(signal)); + })]).finally(() => signal.removeEventListener("abort", listener)); +} +/** +* Get the error from an abort signal. Since you can set the reason to anything, +* we have to do some type gymnastics to get a proper error message. +* +* @param signal - The abort signal. +* @returns The error from the abort signal. +*/ +function getAbortSignalError(signal) { + if (signal?.reason instanceof Error) return signal.reason; + if (typeof signal?.reason === "string") return new Error(signal.reason); + return /* @__PURE__ */ new Error("Aborted"); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/stream.js +var stream_exports$1 = /* @__PURE__ */ __exportAll({ + AsyncGeneratorWithSetup: () => AsyncGeneratorWithSetup, + IterableReadableStream: () => IterableReadableStream, + atee: () => atee, + concat: () => concat, + pipeGeneratorWithSetup: () => pipeGeneratorWithSetup +}); +var IterableReadableStream = class IterableReadableStream extends ReadableStream { + reader; + 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 (e) { + this.reader.releaseLock(); + throw e; + } + } + 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(e) { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); + this.reader.releaseLock(); + await cancelPromise; + } + throw e; + } + [Symbol.asyncIterator]() { + return this; + } + async [Symbol.asyncDispose]() { + await this.return(); + } + 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); + } + }); + } +}; +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 buffer of buffers) buffer.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}`); +} +var AsyncGeneratorWithSetup = class { + generator; + setup; + config; + signal; + firstResult; + firstResultUsed = false; + constructor(params) { + this.generator = params.generator; + this.config = params.config; + this.signal = params.signal ?? this.config?.signal; + this.setup = new Promise((resolve, reject) => { + AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(params.config), async () => { + this.firstResult = this.signal ? raceWithSignal(params.generator.next(), this.signal) : params.generator.next(); + if (params.startSetup) this.firstResult.then(params.startSetup).then(resolve, reject); + else this.firstResult.then((_result) => resolve(void 0), reject); + }, true); + }); + } + async next(...args) { + this.signal?.throwIfAborted(); + if (!this.firstResultUsed) { + this.firstResultUsed = true; + return this.firstResult; + } + return AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(this.config), this.signal ? async () => { + return raceWithSignal(this.generator.next(...args), this.signal); + } : async () => { + return this.generator.next(...args); + }, true); + } + async return(value) { + return this.generator.return(value); + } + async throw(e) { + return this.generator.throw(e); + } + [Symbol.asyncIterator]() { + return this; + } + async [Symbol.asyncDispose]() { + await this.return(); + } +}; +async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { + const gen = new AsyncGeneratorWithSetup({ + generator, + startSetup, + signal + }); + const setup = await gen.setup; + return { + output: to(gen, setup, ...args), + setup + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/outputs.js +var outputs_exports = /* @__PURE__ */ __exportAll({ + ChatGenerationChunk: () => ChatGenerationChunk, + GenerationChunk: () => GenerationChunk, + RUN_KEY: () => RUN_KEY +}); +var RUN_KEY = "__run"; +/** +* Chunk of a single generation. Used for streaming. +*/ +var GenerationChunk = class GenerationChunk { + text; + generationInfo; + constructor(fields) { + this.text = fields.text; + this.generationInfo = fields.generationInfo; + } + concat(chunk) { + return new GenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo + } + }); + } +}; +var ChatGenerationChunk = class ChatGenerationChunk extends GenerationChunk { + message; + constructor(fields) { + super(fields); + this.message = fields.message; + } + concat(chunk) { + return new ChatGenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo + }, + message: this.message.concat(chunk.message) + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/types/zod.js +function isZodSchemaV4(schema) { + if (typeof schema !== "object" || schema === null) return false; + const obj = schema; + if (!("_zod" in obj)) return false; + const zod = obj._zod; + return typeof zod === "object" && zod !== null && "def" in zod; +} +function isZodSchemaV3(schema) { + if (typeof schema !== "object" || schema === null) return false; + const obj = schema; + if (!("_def" in obj) || "_zod" in obj) return false; + const def = obj._def; + return typeof def === "object" && def != null && "typeName" in def; +} +/** Backward compatible isZodSchema for Zod 3 */ +function isZodSchema(schema) { + if (isZodSchemaV4(schema)) console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."); + return isZodSchemaV3(schema); +} +/** +* Given either a Zod schema, or plain object, determine if the input is a Zod schema. +* +* @param {unknown} input +* @returns {boolean} Whether or not the provided input is a Zod schema. +*/ +function isInteropZodSchema(input) { + if (!input) return false; + if (typeof input !== "object") return false; + if (Array.isArray(input)) return false; + if (isZodSchemaV4(input) || isZodSchemaV3(input)) return true; + return false; +} +function isZodLiteralV3(obj) { + if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodLiteral") return true; + return false; +} +function isZodLiteralV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "literal") return true; + return false; +} +/** +* Determines if the provided value is an InteropZodLiteral (Zod v3 or v4 literal schema). +* +* @param obj The value to check. +* @returns {boolean} True if the value is a Zod v3 or v4 literal schema, false otherwise. +*/ +function isInteropZodLiteral(obj) { + if (isZodLiteralV3(obj)) return true; + if (isZodLiteralV4(obj)) return true; + return false; +} +/** +* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result. +* This function handles both Zod v3 and v4 schemas, returning a result object indicating success or failure. +* +* @template T - The expected output type of the schema. +* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. +* @param {unknown} input - The input value to parse. +* @returns {Promise>} A promise that resolves to a safe parse result object. +* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. +*/ +async function interopSafeParseAsync(schema, input) { + if (isZodSchemaV4(schema)) try { + return { + success: true, + data: await parseAsync(schema, input) + }; + } catch (error) { + return { + success: false, + error + }; + } + if (isZodSchemaV3(schema)) return await schema.safeParseAsync(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. +* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. +* +* @template T - The expected output type of the schema. +* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. +* @param {unknown} input - The input value to parse. +* @returns {Promise} A promise that resolves to the parsed value. +* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. +*/ +async function interopParseAsync(schema, input) { + if (isZodSchemaV4(schema)) return await parseAsync(schema, input); + if (isZodSchemaV3(schema)) return await schema.parseAsync(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object +* indicating success or failure. This function is compatible with both Zod v3 and v4 schemas. +* +* @template T - The expected output type of the schema. +* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. +* @param {unknown} input - The input value to parse. +* @returns {InteropZodSafeParseResult} An object with either the parsed data (on success) +* or the error (on failure). +* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. +*/ +function interopSafeParse(schema, input) { + if (isZodSchemaV4(schema)) try { + return { + success: true, + data: parse$3(schema, input) + }; + } catch (error) { + return { + success: false, + error + }; + } + if (isZodSchemaV3(schema)) return schema.safeParse(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. +* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. +* +* @template T - The expected output type of the schema. +* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. +* @param {unknown} input - The input value to parse. +* @returns {T} The parsed value. +* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. +*/ +function interopParse(schema, input) { + if (isZodSchemaV4(schema)) return parse$3(schema, input); + if (isZodSchemaV3(schema)) return schema.parse(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Retrieves the description from a schema definition (v3, v4, standard schema, or plain object), if available. +* +* @param {unknown} schema - The schema to extract the description from. +* @returns {string | undefined} The description of the schema, or undefined if not present. +*/ +function getSchemaDescription(schema) { + if (isZodSchemaV4(schema)) return globalRegistry.get(schema)?.description; + if (isZodSchemaV3(schema)) return schema.description; + if ("description" in schema && typeof schema.description === "string") return schema.description; +} +/** +* Determines if the provided Zod schema is "shapeless". +* A shapeless schema is one that does not define any object shape, +* such as ZodString, ZodNumber, ZodBoolean, ZodAny, etc. +* For ZodObject, it must have no shape keys to be considered shapeless. +* ZodRecord schemas are considered shapeless since they define dynamic +* key-value mappings without fixed keys. +* +* @param schema The Zod schema to check. +* @returns {boolean} True if the schema is shapeless, false otherwise. +*/ +function isShapelessZodSchema(schema) { + if (!isInteropZodSchema(schema)) return false; + if (isZodSchemaV3(schema)) { + const def = schema._def; + if (def.typeName === "ZodObject") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + if (def.typeName === "ZodRecord") return true; + } + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + if (def.type === "object") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + if (def.type === "record") return true; + } + if (typeof schema === "object" && schema !== null && !("shape" in schema)) return true; + return false; +} +/** +* Determines if the provided Zod schema should be treated as a simple string schema +* that maps to DynamicTool. This aligns with the type-level constraint of +* InteropZodType which only matches basic string schemas. +* If the provided schema is just z.string(), we can make the determination that +* the tool is just a generic string tool that doesn't require any input validation. +* +* This function only returns true for basic ZodString schemas, including: +* - Basic string schemas (z.string()) +* - String schemas with validations (z.string().min(1), z.string().email(), etc.) +* +* This function returns false for everything else, including: +* - String schemas with defaults (z.string().default("value")) +* - Branded string schemas (z.string().brand<"UserId">()) +* - String schemas with catch operations (z.string().catch("default")) +* - Optional/nullable string schemas (z.string().optional()) +* - Transformed schemas (z.string().transform() or z.object().transform()) +* - Object or record schemas, even if they're empty +* - Any other schema type +* +* @param schema The Zod schema to check. +* @returns {boolean} True if the schema is a basic ZodString, false otherwise. +*/ +function isSimpleStringZodSchema(schema) { + if (!isInteropZodSchema(schema)) return false; + if (isZodSchemaV3(schema)) return schema._def.typeName === "ZodString"; + if (isZodSchemaV4(schema)) return schema._zod.def.type === "string"; + return false; +} +function isZodObjectV3(obj) { + if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodObject") return true; + return false; +} +function isZodObjectV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "object") return true; + return false; +} +function isZodArrayV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "array") return true; + return false; +} +function isZodOptionalV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "optional") return true; + return false; +} +function isZodNullableV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "nullable") return true; + return false; +} +/** +* Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema). +* +* @param obj The value to check. +* @returns {boolean} True if the value is a Zod v3 or v4 object schema, false otherwise. +*/ +function isInteropZodObject(obj) { + if (isZodObjectV3(obj)) return true; + if (isZodObjectV4(obj)) return true; + return false; +} +/** +* Retrieves the shape (fields) of a Zod object schema, supporting both Zod v3 and v4. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @returns {InteropZodObjectShape} The shape of the object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function getInteropZodObjectShape(schema) { + if (isZodSchemaV3(schema)) return schema.shape; + if (isZodSchemaV4(schema)) return schema._zod.def.shape; + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Extends a Zod object schema with additional fields, supporting both Zod v3 and v4. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @param {InteropZodObjectShape} extension - The fields to add to the schema. +* @returns {InteropZodObject} The extended Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function extendInteropZodObject(schema, extension) { + if (isZodSchemaV3(schema)) return schema.extend(extension); + if (isZodSchemaV4(schema)) return extend(schema, extension); + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Returns a partial version of a Zod object schema, making all fields optional. +* Supports both Zod v3 and v4. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @returns {InteropZodObject} The partial Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function interopZodObjectPartial(schema) { + if (isZodSchemaV3(schema)) return schema.partial(); + if (isZodSchemaV4(schema)) return partial($ZodOptional, schema, void 0); + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Returns a strict version of a Zod object schema, disallowing unknown keys. +* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies strictness +* recursively to all nested object schemas and arrays of object schemas. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @param {boolean} [recursive=false] - Whether to apply strictness recursively to nested objects/arrays. +* @returns {InteropZodObject} The strict Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function interopZodObjectStrict(schema, recursive = false) { + if (isZodObjectV3(schema)) return schema.strict(); + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + if (isZodObjectV4(keySchema)) outputShape[key] = interopZodObjectStrict(keySchema, recursive); + else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectStrict(elementSchema, recursive); + outputShape[key] = clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema + }); + } else outputShape[key] = keySchema; + const meta = globalRegistry.get(keySchema); + if (meta) globalRegistry.add(outputShape[key], meta); + } + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: /* @__PURE__ */ _never($ZodNever) + }); + const meta = globalRegistry.get(schema); + if (meta) globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Returns a passthrough version of a Zod object schema, allowing unknown keys. +* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies passthrough +* recursively to all nested object schemas and arrays of object schemas. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @param {boolean} [recursive=false] - Whether to apply passthrough recursively to nested objects/arrays. +* @returns {InteropZodObject} The passthrough Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function interopZodObjectPassthrough(schema, recursive = false) { + if (isZodObjectV3(schema)) return schema.passthrough(); + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + if (isZodObjectV4(keySchema)) outputShape[key] = interopZodObjectPassthrough(keySchema, recursive); + else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectPassthrough(elementSchema, recursive); + outputShape[key] = clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema + }); + } else outputShape[key] = keySchema; + const meta = globalRegistry.get(keySchema); + if (meta) globalRegistry.add(outputShape[key], meta); + } + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: /* @__PURE__ */ _unknown($ZodUnknown) + }); + const meta = globalRegistry.get(schema); + if (meta) globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Returns a getter function for the default value of a Zod schema, if one is defined. +* Supports both Zod v3 and v4 schemas. If the schema has a default value, +* the returned function will return that value when called. If no default is defined, +* returns undefined. +* +* @template T - The type of the Zod schema. +* @param {T} schema - The Zod schema instance (either v3 or v4). +* @returns {(() => InferInteropZodOutput) | undefined} A function that returns the default value, or undefined if no default is set. +*/ +function getInteropZodDefaultGetter(schema) { + if (isZodSchemaV3(schema)) try { + const defaultValue = schema.parse(void 0); + return () => defaultValue; + } catch { + return; + } + if (isZodSchemaV4(schema)) try { + const defaultValue = parse$3(schema, void 0); + return () => defaultValue; + } catch { + return; + } +} +function isZodTransformV3(schema) { + return isZodSchemaV3(schema) && "typeName" in schema._def && schema._def.typeName === "ZodEffects"; +} +function isZodTransformV4(schema) { + return isZodSchemaV4(schema) && schema._zod.def.type === "pipe"; +} +function interopZodTransformInputSchemaImpl(schema, recursive, cache) { + const cached = cache.get(schema); + if (cached !== void 0) return cached; + if (isZodSchemaV3(schema)) { + if (isZodTransformV3(schema)) return interopZodTransformInputSchemaImpl(schema._def.schema, recursive, cache); + return schema; + } + if (isZodSchemaV4(schema)) { + let outputSchema = schema; + if (isZodTransformV4(schema)) outputSchema = interopZodTransformInputSchemaImpl(schema._zod.def.in, recursive, cache); + if (recursive) { + if (isZodObjectV4(outputSchema)) { + const outputShape = {}; + for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) outputShape[key] = interopZodTransformInputSchemaImpl(keySchema, recursive, cache); + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + shape: outputShape + }); + } else if (isZodArrayV4(outputSchema)) { + const elementSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.element, recursive, cache); + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + element: elementSchema + }); + } else if (isZodOptionalV4(outputSchema)) { + const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + innerType: innerSchema + }); + } else if (isZodNullableV4(outputSchema)) { + const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + innerType: innerSchema + }); + } + } + const meta = globalRegistry.get(schema); + if (meta) globalRegistry.add(outputSchema, meta); + cache.set(schema, outputSchema); + return outputSchema; + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Returns the input type of a Zod transform schema, for both v3 and v4. +* If the schema is not a transform, returns undefined. If `recursive` is true, +* recursively processes nested object schemas and arrays of object schemas. +* +* @param schema - The Zod schema instance (v3 or v4) +* @param {boolean} [recursive=false] - Whether to recursively process nested objects/arrays. +* @returns The input Zod schema of the transform, or undefined if not a transform +*/ +function interopZodTransformInputSchema(schema, recursive = false) { + return interopZodTransformInputSchemaImpl(schema, recursive, /* @__PURE__ */ new WeakMap()); +} +/** +* Creates a modified version of a Zod object schema where fields matching a predicate are made optional. +* Supports both Zod v3 and v4 schemas and preserves the original schema version. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @param {(key: string, value: InteropZodType) => boolean} predicate - Function to determine which fields should be optional. +* @returns {InteropZodObject} The modified Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function interopZodObjectMakeFieldsOptional(schema, predicate) { + if (isZodSchemaV3(schema)) { + const shape = getInteropZodObjectShape(schema); + const modifiedShape = {}; + for (const [key, value] of Object.entries(shape)) if (predicate(key, value)) modifiedShape[key] = value.optional(); + else modifiedShape[key] = value; + return schema.extend(modifiedShape); + } + if (isZodSchemaV4(schema)) { + const shape = getInteropZodObjectShape(schema); + const outputShape = { ...schema._zod.def.shape }; + for (const [key, value] of Object.entries(shape)) if (predicate(key, value)) outputShape[key] = new $ZodOptional({ + type: "optional", + innerType: value + }); + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape + }); + const meta = globalRegistry.get(schema); + if (meta) globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function isInteropZodError(e) { + return e instanceof Error && (e.constructor.name === "ZodError" || e.constructor.name === "$ZodError"); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/standard_schema.js +var standard_schema_exports = /* @__PURE__ */ __exportAll({ + isSerializableSchema: () => isSerializableSchema, + isStandardJsonSchema: () => isStandardJsonSchema, + isStandardSchema: () => isStandardSchema +}); +/** +* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate` +* interface, indicating it can validate unknown values at runtime (e.g. for parsing LLM output). +*/ +function isStandardSchema(schema) { + return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"]; +} +/** +* Type guard for Standard JSON Schema V1. Returns true if the value has a `~standard.jsonSchema` +* interface, indicating it can be converted to a JSON Schema object (e.g. for sending as a tool +* definition to an LLM). +*/ +function isStandardJsonSchema(schema) { + return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"]; +} +/** +* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate` interface, +* indicating it can validate unknown values at runtime (e.g. for parsing LLM output). +*/ +function isSerializableSchema(schema) { + return isStandardSchema(schema) && isStandardJsonSchema(schema); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/Options.js +var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); +var defaultOptions = { + name: void 0, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" +}; +var getDefaultOptions = (options) => typeof options === "string" ? { + ...defaultOptions, + name: options +} : { + ...defaultOptions, + ...options +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/Refs.js +var getRefs = (options) => { + const _options = getDefaultOptions(options); + const currentPath = _options.name !== void 0 ? [ + ..._options.basePath, + _options.definitionPath, + _options.name + ] : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath, + propertyPath: void 0, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, { + def: def._def, + path: [ + ..._options.basePath, + _options.definitionPath, + name + ], + jsonSchema: void 0 + }])) + }; +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/getRelativePath.js +var getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break; + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/any.js +function parseAnyDef(refs) { + if (refs.target !== "openAi") return {}; + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/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); +} +//#endregion +//#region node_modules/zod/v3/helpers/util.js +var util; +(function(util) { + util.assertEqual = (_) => {}; + function assertIs(_arg) {} + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) obj[item] = item; + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) filtered[k] = obj[k]; + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function(e) { + return obj[e]; + }); + }; + util.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; + }; + util.find = (arr, checker) => { + for (const item of arr) if (checker(item)) return item; + }; + util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") return value.toString(); + return value; + }; +})(util || (util = {})); +var objectUtil; +(function(objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second + }; + }; +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]); +var getParsedType = (data) => { + switch (typeof data) { + case "undefined": return ZodParsedType.undefined; + case "string": return ZodParsedType.string; + case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": return ZodParsedType.boolean; + case "function": return ZodParsedType.function; + case "bigint": return ZodParsedType.bigint; + case "symbol": return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) return ZodParsedType.array; + if (data === null) return ZodParsedType.null; + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") return ZodParsedType.promise; + if (typeof Map !== "undefined" && data instanceof Map) return ZodParsedType.map; + if (typeof Set !== "undefined" && data instanceof Set) return ZodParsedType.set; + if (typeof Date !== "undefined" && data instanceof Date) return ZodParsedType.date; + return ZodParsedType.object; + default: return ZodParsedType.unknown; + } +}; +//#endregion +//#region node_modules/zod/v3/ZodError.js +var ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]); +var ZodError = class ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto); + else this.__proto__ = actualProto; + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) if (issue.code === "invalid_union") issue.unionErrors.map(processError); + else if (issue.code === "invalid_return_type") processError(issue.returnTypeError); + else if (issue.code === "invalid_arguments") processError(issue.argumentsError); + else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue)); + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] }; + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`); + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = Object.create(null); + const formErrors = []; + for (const sub of this.issues) if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else formErrors.push(mapper(sub)); + return { + formErrors, + fieldErrors + }; + } + get formErrors() { + return this.flatten(); + } +}; +ZodError.create = (issues) => { + return new ZodError(issues); +}; +//#endregion +//#region node_modules/zod/v3/locales/en.js +var errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) message = "Required"; + else message = `Expected ${issue.expected}, received ${issue.received}`; + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`; + else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`; + else util.assertNever(issue.validation); + else if (issue.validation !== "regex") message = `Invalid ${issue.validation}`; + else message = "Invalid"; + break; + case ZodIssueCode.too_small: + if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "bigint") 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 }; +}; +//#endregion +//#region node_modules/zod/v3/errors.js +var overrideErrorMap = errorMap; +function getErrorMap() { + return overrideErrorMap; +} +//#endregion +//#region node_modules/zod/v3/helpers/parseUtil.js +var makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) return { + ...issueData, + path: fullPath, + message: issueData.message + }; + let errorMessage = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map of maps) errorMessage = map(fullIssue, { + data, + defaultError: errorMessage + }).message; + return { + ...issueData, + path: fullPath, + message: errorMessage + }; +}; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + overrideMap, + overrideMap === errorMap ? void 0 : errorMap + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue); +} +var ParseStatus = class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") return INVALID; + if (s.status === "dirty") status.dirty(); + arrayValue.push(s.value); + } + return { + status: status.value, + value: arrayValue + }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") return INVALID; + if (value.status === "aborted") return INVALID; + if (key.status === "dirty") status.dirty(); + if (value.status === "dirty") status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value; + } + return { + status: status.value, + value: finalObject + }; + } +}; +var INVALID = Object.freeze({ status: "aborted" }); +var DIRTY = (value) => ({ + status: "dirty", + value +}); +var OK = (value) => ({ + status: "valid", + value +}); +var isAborted = (x) => x.status === "aborted"; +var isDirty = (x) => x.status === "dirty"; +var isValid = (x) => x.status === "valid"; +var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +//#endregion +//#region node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +(function(errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); +//#endregion +//#region node_modules/zod/v3/types.js +var 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 (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key); + else this._cachedPath.push(...this._path, this._key); + return this._cachedPath; + } +}; +var handleResult = (ctx, result) => { + if (isValid(result)) return { + success: true, + data: result.value + }; + else { + if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected."); + return { + success: false, + get error() { + if (this._error) return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } +}; +function processCreateParams(params) { + if (!params) return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + if (errorMap) return { + errorMap, + description + }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") return { message: message ?? ctx.defaultError }; + if (typeof ctx.data === "undefined") return { message: message ?? required_error ?? ctx.defaultError }; + if (iss.code !== "invalid_type") return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { + errorMap: customMap, + description + }; +} +var ZodType = class { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) throw new Error("Synchronous parse encountered promise."); + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + return handleResult(ctx, this._parseSync({ + data, + path: ctx.path, + parent: ctx + })); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + if (!this["~standard"].async) try { + const result = this._parseSync({ + data, + path: [], + parent: ctx + }); + return isValid(result) ? { value: result.value } : { issues: ctx.common.issues }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true; + ctx.common = { + issues: [], + async: true + }; + } + return this._parseAsync({ + data, + path: [], + parent: ctx + }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const maybeAsyncResult = this._parse({ + data, + path: ctx.path, + parent: ctx + }); + return handleResult(ctx, await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult))); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") return { message }; + else if (typeof message === "function") return message(val); + else return message; + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data) => { + if (!data) { + setError(); + return false; + } else return true; + }); + if (!result) { + setError(); + return false; + } else return true; + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else return true; + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { + type: "refinement", + refinement + } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { + type: "transform", + transform + } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}; +var cuidRegex = /^c[^\s-]{8,}$/i; +var cuid2Regex = /^[0-9a-z]+$/; +var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +var nanoidRegex = /^[a-z0-9_-]{21}$/i; +var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var emojiRegex$1; +var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +var dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + else if (args.precision == null) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) return true; + if ((version === "v6" || !version) && ipv6Regex.test(ip)) return true; + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) return false; + try { + const [header] = jwt.split("."); + if (!header) return false; + const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) return false; + if ("typ" in decoded && decoded?.typ !== "JWT") return false; + if (!decoded.alg) return false; + if (alg && decoded.alg !== alg) return false; + return true; + } catch { + return false; + } +} +function isValidCidr(ip, version) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) return true; + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) return true; + return false; +} +var ZodString = class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) input.data = String(input.data); + if (this._getType(input) !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.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$1) emojiRegex$1 = new RegExp(_emojiRegex, "u"); + if (!emojiRegex$1.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "url") try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + if (!check.regex.test(input.data)) { + 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") { + if (!datetimeRegex(check).test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "date") { + if (!dateRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "time") { + if (!timeRegex(check).test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else util.assertNever(check); + return { + status: status.value, + value: input.data + }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }); + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ + kind: "email", + ...errorUtil.errToObj(message) + }); + } + url(message) { + return this._addCheck({ + kind: "url", + ...errorUtil.errToObj(message) + }); + } + emoji(message) { + return this._addCheck({ + kind: "emoji", + ...errorUtil.errToObj(message) + }); + } + uuid(message) { + return this._addCheck({ + kind: "uuid", + ...errorUtil.errToObj(message) + }); + } + nanoid(message) { + return this._addCheck({ + kind: "nanoid", + ...errorUtil.errToObj(message) + }); + } + cuid(message) { + return this._addCheck({ + kind: "cuid", + ...errorUtil.errToObj(message) + }); + } + cuid2(message) { + return this._addCheck({ + kind: "cuid2", + ...errorUtil.errToObj(message) + }); + } + ulid(message) { + return this._addCheck({ + kind: "ulid", + ...errorUtil.errToObj(message) + }); + } + base64(message) { + return this._addCheck({ + kind: "base64", + ...errorUtil.errToObj(message) + }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message) + }); + } + jwt(options) { + return this._addCheck({ + kind: "jwt", + ...errorUtil.errToObj(options) + }); + } + ip(options) { + return this._addCheck({ + kind: "ip", + ...errorUtil.errToObj(options) + }); + } + cidr(options) { + return this._addCheck({ + kind: "cidr", + ...errorUtil.errToObj(options) + }); + } + datetime(options) { + if (typeof options === "string") return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) + }); + } + date(message) { + return this._addCheck({ + kind: "date", + message + }); + } + time(options) { + if (typeof options === "string") return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ + kind: "duration", + ...errorUtil.errToObj(message) + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + return max; + } +}; +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount; +} +var ZodNumber = class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) input.data = Number(input.data); + if (this._getType(input) !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.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") { + if (check.inclusive ? input.data < check.value : input.data <= check.value) { + 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") { + if (check.inclusive ? input.data > check.value : input.data >= check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message + }); + status.dirty(); + } + } else util.assertNever(check); + return { + status: status.value, + value: input.data + }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, { + kind, + value, + inclusive, + message: errorUtil.toString(message) + }] + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true; + else if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + return Number.isFinite(min) && Number.isFinite(max); + } +}; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodBigInt = class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + if (this._getType(input) !== ZodParsedType.bigint) return this._getInvalidInput(input); + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) if (check.kind === "min") { + if (check.inclusive ? input.data < check.value : input.data <= check.value) { + 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") { + if (check.inclusive ? input.data > check.value : input.data >= check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else util.assertNever(check); + return { + status: status.value, + value: input.data + }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }); + return INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, { + kind, + value, + inclusive, + message: errorUtil.toString(message) + }] + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + return max; + } +}; +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +var ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce) input.data = Boolean(input.data); + if (this._getType(input) !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodDate = class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) input.data = new Date(input.data); + if (this._getType(input) !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + addIssueToContext(this._getOrReturnCtx(input), { 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?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); +}; +var ZodSymbol = class extends ZodType { + _parse(input) { + if (this._getType(input) !== 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) + }); +}; +var ZodUndefined = class extends ZodType { + _parse(input) { + if (this._getType(input) !== 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) + }); +}; +var ZodNull = class extends ZodType { + _parse(input) { + if (this._getType(input) !== 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) + }); +}; +var 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) + }); +}; +var 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) + }); +}; +var 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) + }); +}; +var ZodVoid = class extends ZodType { + _parse(input) { + if (this._getType(input) !== 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) + }); +}; +var ZodArray = class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : 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, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { + value: minLength, + message: errorUtil.toString(message) + } + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { + value: maxLength, + message: errorUtil.toString(message) + } + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { + value: len, + message: errorUtil.toString(message) + } + }); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray) return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }); + else if (schema instanceof ZodOptional) return ZodOptional.create(deepPartialify(schema.unwrap())); + else if (schema instanceof ZodNullable) return ZodNullable.create(deepPartialify(schema.unwrap())); + else if (schema instanceof ZodTuple) return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + else return schema; +} +var ZodObject = class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { + shape, + keys + }; + return this._cached; + } + _parse(input) { + if (this._getType(input) !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) if (!shapeKeys.includes(key)) extraKeys.push(key); + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { + status: "valid", + value: key + }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") for (const key of extraKeys) pairs.push({ + key: { + status: "valid", + value: key + }, + value: { + status: "valid", + value: ctx.data[key] + } + }); + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") {} else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { + status: "valid", + value: key + }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + else return ParseStatus.mergeObjectSync(status, pairs); + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError }; + return { message: defaultError }; + } } : {} + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + return new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) if (mask[key] && this.shape[key]) shape[key] = this.shape[key]; + return new ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) if (!mask[key]) shape[key] = this.shape[key]; + return new ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) newShape[key] = fieldSchema; + else newShape[key] = fieldSchema.optional(); + } + return new ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) if (mask && !mask[key]) newShape[key] = this.shape[key]; + else { + let newField = this.shape[key]; + 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) + }); +}; +var 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((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +}; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); +}; +var getDiscriminator = (type) => { + if (type instanceof ZodLazy) return getDiscriminator(type.schema); + else if (type instanceof ZodEffects) return getDiscriminator(type.innerType()); + else if (type instanceof ZodLiteral) return [type.value]; + else if (type instanceof ZodEnum) return type.options; + else if (type instanceof ZodNativeEnum) return util.objectValues(type.enum); + else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType); + else if (type instanceof ZodUndefined) return [void 0]; + else if (type instanceof ZodNull) return [null]; + else if (type instanceof ZodOptional) return [void 0, ...getDiscriminator(type.unwrap())]; + else if (type instanceof ZodNullable) return [null, ...getDiscriminator(type.unwrap())]; + else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap()); + else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap()); + else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType); + else return []; +}; +var ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + else return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + for (const value of discriminatorValues) { + if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) return { + valid: true, + data: a + }; + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { + ...a, + ...b + }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) return { valid: false }; + newObj[key] = sharedValue.data; + } + return { + valid: true, + data: newObj + }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) return { valid: false }; + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) return { valid: false }; + newArray.push(sharedValue.data); + } + return { + valid: true, + data: newArray + }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) return { + valid: true, + data: a + }; + else return { valid: false }; +} +var 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) + }); +}; +var ZodTuple = class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + if (!this._def.rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + else return ParseStatus.mergeArray(status, items); + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest + }); + } +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs); + else return ParseStatus.mergeObjectSync(status, pairs); + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } +}; +var 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 pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") return INVALID; + if (key.status === "dirty" || value.status === "dirty") status.dirty(); + finalMap.set(key.value, value.value); + } + return { + status: status.value, + value: finalMap + }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") return INVALID; + if (key.status === "dirty" || value.status === "dirty") status.dirty(); + finalMap.set(key.value, value.value); + } + return { + status: status.value, + value: finalMap + }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); +}; +var ZodSet = class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements) { + if (element.status === "aborted") return INVALID; + if (element.status === "dirty") status.dirty(); + parsedSet.add(element.value); + } + return { + status: status.value, + value: parsedSet + }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) return Promise.all(elements).then((elements) => finalizeSet(elements)); + 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) + }); +}; +var ZodFunction = class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return OK(async function(...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + return await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + return this.parse(func); + } + strictImplement(func) { + return this.parse(func); + } + 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) + }); + } +}; +var ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + return this._def.getter()._parse({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } +}; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); +}; +var 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) + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) this._cache = new Set(this._def.values); + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) enumValues[val] = val; + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) enumValues[val] = val; + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) enumValues[val] = val; + return enumValues; + } + extract(values, newDef = this._def) { + return ZodEnum.create(values, { + ...this._def, + ...newDef + }); + } + exclude(values, newDef = this._def) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef + }); + } +}; +ZodEnum.create = createZodEnum; +var 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 (!this._cache) this._cache = new Set(util.getValidEnumValues(this._def.values)); + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +}; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); +}; +var 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; + } + return OK((ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data)).then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } +}; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); +}; +var 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.async) return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") return INVALID; + if (result.status === "dirty") return DIRTY(result.value); + if (status.value === "dirty") return DIRTY(result.value); + return result; + }); + else { + if (status.value === "aborted") return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") return INVALID; + if (result.status === "dirty") return DIRTY(result.value); + if (status.value === "dirty") return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) return Promise.resolve(result); + if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") return INVALID; + if (inner.status === "dirty") status.dirty(); + executeRefinement(inner.value); + return { + status: status.value, + value: inner.value + }; + } else return this._def.schema._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }).then((inner) => { + if (inner.status === "aborted") return INVALID; + if (inner.status === "dirty") status.dirty(); + return executeRefinement(inner.value).then(() => { + return { + status: status.value, + value: inner.value + }; + }); + }); + } + if (effect.type === "transform") if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + return { + status: status.value, + value: result + }; + } else return this._def.schema._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }).then((base) => { + if (!isValid(base)) return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + util.assertNever(effect); + } +}; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { + type: "preprocess", + transform: preprocess + }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); +}; +var ZodOptional = class extends ZodType { + _parse(input) { + if (this._getType(input) === ZodParsedType.undefined) return OK(void 0); + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); +}; +var ZodNullable = class extends ZodType { + _parse(input) { + if (this._getType(input) === ZodParsedType.null) return OK(null); + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); +}; +var 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 = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); +}; +var 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((result) => { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + else return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + removeCatch() { + return this._def.innerType; + } +}; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); +}; +var ZodNaN = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { + status: "valid", + value: input.data + }; + } +}; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); +}; +var 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; + } +}; +var ZodPipeline = class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } +}; +var ZodReadonly = class extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) data.value = Object.freeze(data.value); + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } +}; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); +}; +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + return typeof p === "string" ? { message: p } : p; +} +function custom(check, _params = {}, fatal) { + if (check) return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ + code: "custom", + ...params, + fatal: _fatal + }); + } + }); + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ + code: "custom", + ...params, + fatal: _fatal + }); + } + }); + return ZodAny.create(); +} +ZodObject.lazycreate; +var ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data) => data instanceof cls, params); +var stringType = ZodString.create; +var numberType = ZodNumber.create; +ZodNaN.create; +ZodBigInt.create; +var booleanType = ZodBoolean.create; +ZodDate.create; +ZodSymbol.create; +ZodUndefined.create; +ZodNull.create; +var anyType = ZodAny.create; +var unknownType = ZodUnknown.create; +ZodNever.create; +var voidType = ZodVoid.create; +var arrayType = ZodArray.create; +var objectType = ZodObject.create; +ZodObject.strictCreate; +var unionType = ZodUnion.create; +ZodDiscriminatedUnion.create; +ZodIntersection.create; +var tupleType = ZodTuple.create; +var recordType = ZodRecord.create; +ZodMap.create; +ZodSet.create; +var functionType = ZodFunction.create; +ZodLazy.create; +var literalType = ZodLiteral.create; +var enumType = ZodEnum.create; +ZodNativeEnum.create; +var promiseType = ZodPromise.create; +ZodEffects.create; +var optionalType = ZodOptional.create; +ZodNullable.create; +ZodEffects.createWithPreprocess; +ZodPipeline.create; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/array.js +function parseArrayDef(def, refs) { + const res = { type: "array" }; + if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + if (def.minLength) setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); + if (def.maxLength) setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + if (def.exactLength) { + setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + } + return res; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/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; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/boolean.js +function parseBooleanDef() { + return { type: "boolean" }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/branded.js +function parseBrandedDef(_def, refs) { + return parseDef(_def.type._def, refs); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/catch.js +var parseCatchDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/date.js +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) }; + switch (strategy) { + case "string": + case "format:date-time": return { + type: "string", + format: "date-time" + }; + case "format:date": return { + type: "string", + format: "date" + }; + case "integer": return integerDateParser(def, refs); + } +} +var integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time" + }; + if (refs.target === "openApi3") return res; + for (const check of def.checks) switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + break; + } + return res; +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/default.js +function parseDefaultDef(_def, refs) { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue() + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/effects.js +function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/enum.js +function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values) + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/intersection.js +var isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") return false; + return "allOf" in type; +}; +function parseIntersectionDef(def, refs) { + const allOf = [parseDef(def.left._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "0" + ] + }), parseDef(def.right._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "1" + ] + })].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; + const mergedAllOf = []; + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === void 0) unevaluatedProperties = void 0; + } else { + let nestedSchema = schema; + if ("additionalProperties" in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } else unevaluatedProperties = void 0; + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? { + allOf: mergedAllOf, + ...unevaluatedProperties + } : void 0; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/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 + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/string.js +var emojiRegex = void 0; +/** +* Generated from the regular expressions found here as of 2024-05-22: +* https://github.com/colinhacks/zod/blob/master/src/types.ts. +* +* Expressions with /i flag have been changed accordingly. +*/ +var zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex === void 0) emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + return emojiRegex; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ +}; +function parseStringDef(def, refs) { + const res = { type: "string" }; + if (def.checks) for (const check of def.checks) switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.email, check.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check.message, refs); + break; + case "regex": + addPattern(res, check.regex, check.message, refs); + break; + case "cuid": + addPattern(res, zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern(res, zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check.message, refs); + break; + case "date": + addFormat(res, "date", check.message, refs); + break; + case "time": + addFormat(res, "time", check.message, refs); + break; + case "duration": + addFormat(res, "duration", check.message, refs); + break; + case "length": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "includes": + addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); + break; + case "ip": + if (check.version !== "v6") addFormat(res, "ipv4", check.message, refs); + if (check.version !== "v4") addFormat(res, "ipv6", check.message, refs); + break; + case "base64url": + addPattern(res, zodPatterns.base64url, check.message, refs); + break; + case "jwt": + addPattern(res, zodPatterns.jwt, check.message, refs); + break; + case "cidr": + if (check.version !== "v6") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); + if (check.version !== "v4") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); + break; + case "emoji": + addPattern(res, zodPatterns.emoji(), check.message, refs); + break; + case "ulid": + addPattern(res, zodPatterns.ulid, check.message, refs); + break; + case "base64": + switch (refs.base64Strategy) { + case "format:binary": + addFormat(res, "binary", check.message, refs); + break; + case "contentEncoding:base64": + setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + break; + case "nanoid": + addPattern(res, zodPatterns.nanoid, check.message, refs); + break; + case "toLowerCase": + case "toUpperCase": + case "trim": break; + default: + } + return res; +} +function escapeLiteralCheckValue(literal, refs) { + return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; +} +var ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); +function escapeNonAlphaNumeric(source) { + let result = ""; + for (let i = 0; i < source.length; i++) { + if (!ALPHA_NUMERIC.has(source[i])) result += "\\"; + result += source[i]; + } + return result; +} +function addFormat(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) schema.anyOf = []; + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; + } + } + schema.anyOf.push({ + format: value, + ...message && refs.errorMessages && { errorMessage: { format: message } } + }); + } else setResponseValueAndErrors(schema, "format", value, message, refs); +} +function addPattern(schema, regex, message, refs) { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) schema.allOf = []; + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; + } + } + schema.allOf.push({ + pattern: stringifyRegExpWithFlags(regex, refs), + ...message && refs.errorMessages && { errorMessage: { pattern: message } } + }); + } else setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); +} +function stringifyRegExpWithFlags(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) return regex.source; + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s") + }; + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } else pattern += `${source[i]}${source[i].toUpperCase()}`; + continue; + } + } else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === "^") { + pattern += `(^|(?<=[\r\n]))`; + continue; + } else if (source[i] === "$") { + pattern += `($|(?=[\r\n]))`; + continue; + } + } + if (flags.s && source[i] === ".") { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; + } + pattern += source[i]; + if (source[i] === "\\") isEscaped = true; + else if (inCharGroup && source[i] === "]") inCharGroup = false; + else if (!inCharGroup && source[i] === "[") inCharGroup = true; + } + try { + new RegExp(pattern); + } catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/record.js +function parseRecordDef(def, refs) { + if (refs.target === "openAi") console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef(def.valueType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "properties", + key + ] + }) ?? parseAnyDef(refs) + }), {}), + additionalProperties: refs.rejectedAdditionalProperties + }; + const schema = { + type: "object", + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? refs.allowedAdditionalProperties + }; + if (refs.target === "openApi3") return schema; + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const { type, ...keyType } = parseStringDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return { + ...schema, + propertyNames: { enum: def.keyType._def.values } + }; + else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { + const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } + return schema; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/map.js +function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") return parseRecordDef(def, refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [parseDef(def.keyType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + "items", + "0" + ] + }) || parseAnyDef(refs), parseDef(def.valueType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + "items", + "1" + ] + }) || parseAnyDef(refs)], + minItems: 2, + maxItems: 2 + } + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nativeEnum.js +function parseNativeEnumDef(def) { + const object = def.values; + const actualValues = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }).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 + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/never.js +function parseNeverDef(refs) { + return refs.target === "openAi" ? void 0 : { not: parseAnyDef({ + ...refs, + currentPath: [...refs.currentPath, "not"] + }) }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/null.js +function parseNullDef(refs) { + return refs.target === "openApi3" ? { + enum: ["null"], + nullable: true + } : { type: "null" }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/union.js +var primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null" +}; +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { + const types = options.reduce((types, x) => { + const type = primitiveMappings[x._def.typeName]; + return type && !types.includes(type) ? [...types, type] : types; + }, []); + return { type: types.length > 1 ? types : types[0] }; + } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case "string": + case "number": + case "boolean": return [...acc, type]; + case "bigint": return [...acc, "integer"]; + case "object": + if (x._def.value === null) return [...acc, "null"]; + return acc; + default: return acc; + } + }, []); + if (types.length === options.length) { + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []) + }; + } + } else if (options.every((x) => x._def.typeName === "ZodEnum")) return { + type: "string", + enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []) + }; + return asAnyOf(def, refs); +} +var asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + `${i}` + ] + })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); + return anyOf.length ? { anyOf } : void 0; +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/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 base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath] + }); + if (base && "$ref" in base) return { + allOf: [base], + nullable: true + }; + return base && { + ...base, + nullable: true + }; + } + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + "0" + ] + }); + return base && { anyOf: [base, { type: "null" }] }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/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; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/object.js +function parseObjectDef(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {} + }; + const required = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === void 0 || propDef._def === void 0) continue; + let propOptional = safeIsOptional(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") propDef = propDef._def.innerType; + if (!propDef.isNullable()) propDef = propDef.nullable(); + propOptional = false; + } + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "properties", + propName + ], + propertyPath: [ + ...refs.currentPath, + "properties", + propName + ] + }); + if (parsedDef === void 0) continue; + result.properties[propName] = parsedDef; + if (!propOptional) required.push(propName); + } + if (required.length) result.required = required; + const additionalProperties = decideAdditionalProperties(def, refs); + if (additionalProperties !== void 0) result.additionalProperties = additionalProperties; + return result; +} +function decideAdditionalProperties(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") return parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }); + switch (def.unknownKeys) { + case "passthrough": return refs.allowedAdditionalProperties; + case "strict": return refs.rejectedAdditionalProperties; + case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; + } +} +function safeIsOptional(schema) { + try { + return schema.isOptional(); + } catch { + return true; + } +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/optional.js +var parseOptionalDef = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef(def.innerType._def, refs); + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + "1" + ] + }); + return innerSchema ? { anyOf: [{ not: parseAnyDef(refs) }, innerSchema] } : parseAnyDef(refs); +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/pipeline.js +var parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") return parseDef(def.in._def, refs); + else if (refs.pipeStrategy === "output") return parseDef(def.out._def, refs); + const a = parseDef(def.in._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "0" + ] + }); + return { allOf: [a, parseDef(def.out._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + a ? "1" : "0" + ] + })].filter((x) => x !== void 0) }; +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/promise.js +function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/set.js +function parseSetDef(def, refs) { + const schema = { + type: "array", + uniqueItems: true, + items: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }) + }; + if (def.minSize) setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); + if (def.maxSize) setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + return schema; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/tuple.js +function parseTupleDef(def, refs) { + if (def.rest) return { + type: "array", + minItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + `${i}` + ] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"] + }) + }; + else return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + `${i}` + ] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/undefined.js +function parseUndefinedDef(refs) { + return { not: parseAnyDef(refs) }; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/unknown.js +function parseUnknownDef(refs) { + return parseAnyDef(refs); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/readonly.js +var parseReadonlyDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/selectParser.js +var selectParser = (def, typeName, refs) => { + switch (typeName) { + case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs); + case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef(); + case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); + case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(refs); + case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs); + case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind.ZodUnion: + case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; + case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(refs); + case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); + case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(refs); + case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(refs); + case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: return; + default: + /* c8 ignore next */ + return ((_) => void 0)(typeName); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/parseDef.js +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) return overrideResult; + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== void 0) return seenSchema; + } + const newItem = { + def, + path: refs.currentPath, + jsonSchema: void 0 + }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); + const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; + if (jsonSchema) addMeta(def, refs, jsonSchema); + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +var get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": return { $ref: item.path.join("/") }; + case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": + if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return parseAnyDef(refs); + } + return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; + } +}; +var addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) jsonSchema.markdownDescription = def.description; + } + return jsonSchema; +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/zod-to-json-schema/zodToJsonSchema.js +var zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ + ...acc, + [name]: parseDef(schema._def, { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + name + ] + }, true) ?? parseAnyDef(refs) + }), {}) : void 0; + const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; + const main = parseDef(schema._def, name === void 0 ? refs : { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + name + ] + }, false) ?? parseAnyDef(refs); + const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; + if (title !== void 0) main.title = title; + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) definitions = {}; + if (!definitions[refs.openAiAnyTypeName]) definitions[refs.openAiAnyTypeName] = { + type: [ + "string", + "number", + "integer", + "boolean", + "array", + "null" + ], + items: { $ref: refs.$refStrategy === "relative" ? "1" : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ].join("/") } + }; + } + const combined = name === void 0 ? definitions ? { + ...main, + [refs.definitionPath]: definitions + } : main : { + $ref: [ + ...refs.$refStrategy === "relative" ? [] : refs.basePath, + refs.definitionPath, + name + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main + } + }; + if (refs.target === "jsonSchema7") combined.$schema = "http://json-schema.org/draft-07/schema#"; + else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + return combined; +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/json_schema.js +var json_schema_exports = /* @__PURE__ */ __exportAll({ + Validator: () => Validator, + deepCompareStrict: () => deepCompareStrict, + toJsonSchema: () => toJsonSchema, + validatesOnlyStrings: () => validatesOnlyStrings +}); +/** +* WeakMap cache for Zod/Standard-Schema → JSON Schema conversions. +* +* Keyed on the schema object reference. Since Zod schemas are immutable and +* the same `tool.schema` reference is passed on every LLM call, this +* eliminates redundant serializations. For example, an agent with 6 tools +* doing 15 steps across 3 parallel subagents would otherwise run 270 +* identical conversions per invocation. +* +* Only used when no custom `params` are passed (the common case for tool +* binding). WeakMap ensures cached entries are GC'd when the schema goes +* out of scope. +* +* @internal +*/ +var _jsonSchemaCache = /* @__PURE__ */ new WeakMap(); +/** +* Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema. +* Results are cached by schema reference when no custom params are passed. +* @param schema - The schema to convert. +* @param params - The parameters to pass to the toJSONSchema function. +* @returns The converted schema. +*/ +function toJsonSchema(schema, params) { + const canCache = !params && schema != null && typeof schema === "object"; + if (canCache) { + const cached = _jsonSchemaCache.get(schema); + if (cached) return cached; + } + let result; + if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) result = schema["~standard"].jsonSchema.input({ target: "draft-07" }); + else if (isZodSchemaV4(schema)) { + const inputSchema = interopZodTransformInputSchema(schema, true); + if (isZodObjectV4(inputSchema)) result = toJSONSchema(interopZodObjectStrict(inputSchema, true), params); + else result = toJSONSchema(schema, params); + } else if (isZodSchemaV3(schema)) result = zodToJsonSchema(schema); + else result = schema; + if (canCache && result != null && typeof result === "object") _jsonSchemaCache.set(schema, result); + return result; +} +/** +* Validates if a JSON schema validates only strings. May return false negatives in some edge cases +* (like recursive or unresolvable refs). +* +* @param schema - The schema to validate. +* @returns `true` if the schema validates only strings, `false` otherwise. +*/ +function validatesOnlyStrings(schema) { + if (!schema || typeof schema !== "object" || Object.keys(schema).length === 0 || Array.isArray(schema)) return false; + if ("type" in schema) { + if (typeof schema.type === "string") return schema.type === "string"; + if (Array.isArray(schema.type)) return schema.type.every((t) => t === "string"); + return false; + } + if ("enum" in schema) return Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every((val) => typeof val === "string"); + if ("const" in schema) return typeof schema.const === "string"; + if ("allOf" in schema && Array.isArray(schema.allOf)) return schema.allOf.some((subschema) => validatesOnlyStrings(subschema)); + if ("anyOf" in schema && Array.isArray(schema.anyOf) || "oneOf" in schema && Array.isArray(schema.oneOf)) { + const subschemas = "anyOf" in schema ? schema.anyOf : schema.oneOf; + return subschemas.length > 0 && subschemas.every((subschema) => validatesOnlyStrings(subschema)); + } + if ("not" in schema) return false; + if ("$ref" in schema && typeof schema.$ref === "string") { + const ref = schema.$ref; + const resolved = dereference(schema); + if (resolved[ref]) return validatesOnlyStrings(resolved[ref]); + return false; + } + return false; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js +/*! +* https://github.com/Starcounter-Jack/JSON-Patch +* (c) 2017-2022 Joachim Wester +* MIT licensed +*/ +var _hasOwnProperty = Object.prototype.hasOwnProperty; +function hasOwnProperty(obj, key) { + return _hasOwnProperty.call(obj, key); +} +function _objectKeys(obj) { + if (Array.isArray(obj)) { + const keys = new Array(obj.length); + for (let k = 0; k < keys.length; k++) keys[k] = "" + k; + return keys; + } + if (Object.keys) return Object.keys(obj); + let keys = []; + for (let i in obj) if (hasOwnProperty(obj, i)) keys.push(i); + return keys; +} +/** +* Deeply clone the object. +* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) +* @param {any} obj value to clone +* @return {any} cloned obj +*/ +function _deepClone(obj) { + switch (typeof obj) { + case "object": return JSON.parse(JSON.stringify(obj)); + case "undefined": return null; + default: return obj; + } +} +function isInteger(str) { + let i = 0; + const len = str.length; + let charCode; + while (i < len) { + charCode = str.charCodeAt(i); + if (charCode >= 48 && charCode <= 57) { + i++; + continue; + } + return false; + } + return true; +} +/** +* Escapes a json pointer path +* @param path The raw pointer +* @return the Escaped path +*/ +function escapePathComponent(path) { + if (path.indexOf("/") === -1 && path.indexOf("~") === -1) return path; + return path.replace(/~/g, "~0").replace(/\//g, "~1"); +} +/** +* Unescapes a json pointer path +* @param path The escaped pointer +* @return The unescaped path +*/ +function unescapePathComponent(path) { + return path.replace(/~1/g, "/").replace(/~0/g, "~"); +} +/** +* Recursively checks whether an object has any undefined values inside. +*/ +function hasUndefined(obj) { + if (obj === void 0) return true; + if (obj) { + if (Array.isArray(obj)) { + for (let i = 0, len = obj.length; i < len; i++) if (hasUndefined(obj[i])) return true; + } else if (typeof obj === "object") { + const objKeys = _objectKeys(obj); + const objKeysLength = objKeys.length; + for (var i = 0; i < objKeysLength; i++) if (hasUndefined(obj[objKeys[i]])) 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 PatchError = class extends Error { + constructor(message, name, index, operation, tree) { + super(patchErrorMessageFormatter(message, { + name, + index, + operation, + tree + })); + this.name = name; + this.index = index; + this.operation = operation; + this.tree = tree; + Object.setPrototypeOf(this, new.target.prototype); + this.message = patchErrorMessageFormatter(message, { + name, + index, + operation, + tree + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js +var core_exports = /* @__PURE__ */ __exportAll({ + JsonPatchError: () => JsonPatchError, + _areEquals: () => _areEquals, + applyOperation: () => applyOperation, + applyPatch: () => applyPatch, + applyReducer: () => applyReducer, + deepClone: () => deepClone, + getValueByPointer: () => getValueByPointer, + validate: () => validate, + validator: () => validator +}); +var JsonPatchError = PatchError; +var deepClone = _deepClone; +var objOps = { + add: function(obj, key, document) { + if (key === "__proto__" || key === "constructor") throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons"); + obj[key] = this.value; + return { newDocument: document }; + }, + remove: function(obj, key, document) { + if (key === "__proto__" || key === "constructor") throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons"); + var removed = obj[key]; + delete obj[key]; + return { + newDocument: document, + removed + }; + }, + replace: function(obj, key, document) { + if (key === "__proto__" || key === "constructor") throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons"); + var removed = obj[key]; + obj[key] = this.value; + return { + newDocument: document, + removed + }; + }, + move: function(obj, key, document) { + let removed = getValueByPointer(document, this.path); + if (removed) removed = _deepClone(removed); + const originalValue = applyOperation(document, { + op: "remove", + path: this.from + }).removed; + applyOperation(document, { + op: "add", + path: this.path, + value: originalValue + }); + return { + newDocument: document, + removed + }; + }, + copy: function(obj, key, document) { + const valueToCopy = getValueByPointer(document, this.from); + applyOperation(document, { + op: "add", + path: this.path, + value: _deepClone(valueToCopy) + }); + return { newDocument: document }; + }, + test: function(obj, key, document) { + return { + newDocument: document, + test: _areEquals(obj[key], this.value) + }; + }, + _get: function(obj, key, document) { + this.value = obj[key]; + return { newDocument: document }; + } +}; +var arrOps = { + add: function(arr, i, document) { + if (isInteger(i)) arr.splice(i, 0, this.value); + else arr[i] = this.value; + return { + newDocument: document, + index: i + }; + }, + remove: function(arr, i, document) { + return { + newDocument: document, + removed: arr.splice(i, 1)[0] + }; + }, + replace: function(arr, i, document) { + var removed = arr[i]; + arr[i] = this.value; + return { + newDocument: document, + removed + }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get +}; +/** +* Retrieves a value from a JSON document by a JSON pointer. +* Returns the value. +* +* @param document The document to get the value from +* @param pointer an escaped JSON pointer +* @return The retrieved value +*/ +function getValueByPointer(document, pointer) { + if (pointer == "") return document; + var getOriginalDestination = { + op: "_get", + path: pointer + }; + applyOperation(document, getOriginalDestination); + return getOriginalDestination.value; +} +/** +* Apply a single JSON Patch Operation on a JSON document. +* Returns the {newDocument, result} of the operation. +* It modifies the `document` and `operation` objects - it gets the values by reference. +* If you would like to avoid touching your values, clone them: +* `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. +* +* @param document The document to patch +* @param operation The operation to apply +* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. +* @param mutateDocument Whether to mutate the original document or clone it before applying +* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. +* @return `{newDocument, result}` after the operation +*/ +function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { + if (validateOperation) if (typeof validateOperation == "function") validateOperation(operation, 0, document, operation.path); + else validator(operation, 0); + if (operation.path === "") { + let returnValue = { newDocument: document }; + if (operation.op === "add") { + returnValue.newDocument = operation.value; + return returnValue; + } else if (operation.op === "replace") { + returnValue.newDocument = operation.value; + returnValue.removed = document; + return returnValue; + } else if (operation.op === "move" || operation.op === "copy") { + returnValue.newDocument = getValueByPointer(document, operation.from); + if (operation.op === "move") returnValue.removed = document; + return returnValue; + } else if (operation.op === "test") { + returnValue.test = _areEquals(document, operation.value); + if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + returnValue.newDocument = document; + return returnValue; + } else if (operation.op === "remove") { + returnValue.removed = document; + returnValue.newDocument = null; + return returnValue; + } else if (operation.op === "_get") { + operation.value = document; + return returnValue; + } else if (validateOperation) throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + else return returnValue; + } else { + if (!mutateDocument) document = _deepClone(document); + const keys = (operation.path || "").split("/"); + let obj = document; + let t = 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[t]; + if (key && key.indexOf("~") != -1) key = unescapePathComponent(key); + if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t > 0 && keys[t - 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, t).join("/"); + else if (t == len - 1) existingPathFragment = operation.path; + if (existingPathFragment !== void 0) validateFunction(operation, 0, document, existingPathFragment); + } + } + t++; + 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", index, operation, document); + else if (isInteger(key)) key = ~~key; + if (t >= 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", index, operation, document); + const returnValue = arrOps[operation.op].call(operation, obj, key, document); + if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + return returnValue; + } + } else if (t >= len) { + const returnValue = objOps[operation.op].call(operation, obj, key, document); + if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + return returnValue; + } + obj = obj[key]; + if (validateOperation && t < len && (!obj || typeof obj !== "object")) throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); + } + } +} +/** +* Apply a full JSON Patch array on a JSON document. +* Returns the {newDocument, result} of the patch. +* It modifies the `document` object and `patch` - it gets the values by reference. +* If you would like to avoid touching your values, clone them: +* `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. +* +* @param document The document to patch +* @param patch The patch to apply +* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. +* @param mutateDocument Whether to mutate the original document or clone it before applying +* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. +* @return An array of `{newDocument, result}` after the patch +*/ +function applyPatch(document, 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) document = _deepClone(document); + const results = new Array(patch.length); + for (let i = 0, length = patch.length; i < length; i++) { + results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); + document = results[i].newDocument; + } + results.newDocument = document; + return results; +} +/** +* Apply a single JSON Patch Operation on a JSON document. +* Returns the updated document. +* Suitable as a reducer. +* +* @param document The document to patch +* @param operation The operation to apply +* @return The updated document +*/ +function applyReducer(document, operation, index) { + const operationResult = applyOperation(document, operation); + if (operationResult.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + return operationResult.newDocument; +} +/** +* Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. +* @param {object} operation - operation object (patch) +* @param {number} index - index of operation in the sequence +* @param {object} [document] - object where the operation is supposed to be applied +* @param {string} [existingPathFragment] - comes along with `document` +*/ +function validator(operation, index, document, existingPathFragment) { + if (typeof operation !== "object" || operation === null || Array.isArray(operation)) throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); + else if (!objOps[operation.op]) throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + else if (typeof operation.path !== "string") throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); + else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) throw new JsonPatchError("Operation `path` property must start with \"/\"", "OPERATION_PATH_INVALID", index, operation, document); + 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", index, operation, document); + 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", index, operation, document); + 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", index, operation, document); + else if (document) { + 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", index, operation, document); + } 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", index, operation, document); + } else if (operation.op === "move" || operation.op === "copy") { + var error = validate([{ + op: "_get", + path: operation.from, + value: void 0 + }], document); + if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); + } + } +} +/** +* Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. +* If error is encountered, returns a JsonPatchError object +* @param sequence +* @param document +* @returns {JsonPatchError|undefined} +*/ +function validate(sequence, document, externalValidator) { + try { + if (!Array.isArray(sequence)) throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + if (document) applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true); + else { + externalValidator = externalValidator || validator; + for (var i = 0; i < sequence.length; i++) externalValidator(sequence[i], i, document, void 0); + } + } catch (e) { + if (e instanceof JsonPatchError) return e; + else throw e; + } +} +function _areEquals(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; + if (arrA && arrB) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) if (!_areEquals(a[i], b[i])) return false; + return true; + } + if (arrA != arrB) return false; + var keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0;) if (!b.hasOwnProperty(keys[i])) return false; + for (i = length; i-- !== 0;) { + key = keys[i]; + if (!_areEquals(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js +/*! +* https://github.com/Starcounter-Jack/JSON-Patch +* (c) 2013-2021 Joachim Wester +* MIT license +*/ +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 deleted = false; + for (var t = oldKeys.length - 1; t >= 0; t--) { + var key = oldKeys[t]; + 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) { + 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 + }); + } + } + if (!deleted && newKeys.length == oldKeys.length) return; + for (var t = 0; t < newKeys.length; t++) { + var key = newKeys[t]; + if (!hasOwnProperty(mirror, key) && obj[key] !== void 0) patches.push({ + op: "add", + path: path + "/" + escapePathComponent(key), + value: _deepClone(obj[key]) + }); + } +} +/** +* Create an array of patches from the differences in two objects +*/ +function compare(tree1, tree2, invertible = false) { + var patches = []; + _generate(tree1, tree2, patches, "", invertible); + return patches; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/fast-json-patch/index.js +({ ...core_exports }); +//#endregion +//#region node_modules/@langchain/core/dist/tracers/log_stream.js +var log_stream_exports = /* @__PURE__ */ __exportAll({ + LogStreamCallbackHandler: () => LogStreamCallbackHandler, + RunLog: () => RunLog, + RunLogPatch: () => RunLogPatch, + isLogStreamHandler: () => isLogStreamHandler +}); +/** +* List of jsonpatch JSONPatchOperations, which describe how to create the run state +* from an empty dict. This is the minimal representation of the log, designed to +* be serialized as JSON and sent over the wire to reconstruct the log on the other +* side. Reconstruction of the state can be done with any jsonpatch-compliant library, +* see https://jsonpatch.com for more information. +*/ +var RunLogPatch = class { + ops; + constructor(fields) { + this.ops = fields.ops ?? []; + } + concat(other) { + const ops = this.ops.concat(other.ops); + const states = applyPatch({}, ops); + return new RunLog({ + ops, + state: states[states.length - 1].newDocument + }); + } +}; +var RunLog = class RunLog extends RunLogPatch { + state; + constructor(fields) { + super(fields); + this.state = fields.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 + }); + } +}; +var isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; +/** +* Extract standardized inputs from a run. +* +* Standardizes the inputs based on the type of the runnable used. +* +* @param run - Run object +* @param schemaFormat - The schema format to use. +* +* @returns Valid inputs are only dict. By conventions, inputs always represented +* invocation using named arguments. +* A null means that the input is not yet known! +*/ +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; + 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(x) { + return x !== void 0 && x.message !== void 0; +} +/** +* Class that extends the `BaseTracer` class from the +* `langchain.callbacks.tracers.base` module. It represents a callback +* handler that logs the execution of runs and emits `RunLog` instances to a +* `RunLogStream`. +*/ +var LogStreamCallbackHandler = class extends BaseTracer { + autoClose = true; + includeNames; + includeTypes; + includeTags; + excludeNames; + excludeTypes; + excludeTags; + _schemaFormat = "original"; + rootId; + keyMapByRunId = {}; + counterMapByRunName = {}; + transformStream; + writer; + receiveStream; + name = "log_stream_tracer"; + lc_prefer_streaming = true; + constructor(fields) { + super({ + _awaitHandler: true, + ...fields + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this._schemaFormat = fields?._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 isChatModel = run.inputs.messages !== void 0; + let streamedOutputValue; + if (isChatModel) if (isChatGenerationChunk(kwargs?.chunk)) streamedOutputValue = kwargs?.chunk; + else streamedOutputValue = new AIMessageChunk({ + id: `run-${run.id}`, + content: 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); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/tracers/event_stream.js +function assignName({ name, serialized }) { + if (name !== void 0) return name; + if (serialized?.name !== void 0) return serialized.name; + else if (serialized?.id !== void 0 && Array.isArray(serialized?.id)) return serialized.id[serialized.id.length - 1]; + return "Unnamed"; +} +var isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; +/** +* Class that extends the `BaseTracer` class from the +* `langchain.callbacks.tracers.base` module. It represents a callback +* handler that logs the execution of runs and emits `RunLog` instances to a +* `RunLogStream`. +*/ +var EventStreamCallbackHandler = class extends BaseTracer { + autoClose = true; + includeNames; + includeTypes; + includeTags; + excludeNames; + excludeTypes; + excludeTags; + runInfoMap = /* @__PURE__ */ new Map(); + tappedPromises = /* @__PURE__ */ new Map(); + transformStream; + writer; + receiveStream; + readableStreamClosed = false; + name = "event_stream_tracer"; + lc_prefer_streaming = true; + constructor(fields) { + super({ + _awaitHandler: true, + ...fields + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this.transformStream = new TransformStream({ flush: () => { + this.readableStreamClosed = true; + } }); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); + } + [Symbol.asyncIterator]() { + return this.receiveStream; + } + async persistRun(_run) {} + _includeRun(run) { + 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.runType); + 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.runType); + if (this.excludeTags !== void 0) include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + return include; + } + async *tapOutputIterable(runId, outputStream) { + const firstChunk = await outputStream.next(); + if (firstChunk.done) return; + const runInfo = this.runInfoMap.get(runId); + if (runInfo === void 0) { + yield firstChunk.value; + return; + } + function _formatOutputChunk(eventType, data) { + if (eventType === "llm" && typeof data === "string") return new GenerationChunk({ text: data }); + return data; + } + let tappedPromise = this.tappedPromises.get(runId); + if (tappedPromise === void 0) { + let tappedPromiseResolver; + tappedPromise = new Promise((resolve) => { + tappedPromiseResolver = resolve; + }); + this.tappedPromises.set(runId, tappedPromise); + try { + const event = { + event: `on_${runInfo.runType}_stream`, + run_id: runId, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + data: {} + }; + await this.send({ + ...event, + data: { chunk: _formatOutputChunk(runInfo.runType, firstChunk.value) } + }, runInfo); + yield firstChunk.value; + for await (const chunk of outputStream) { + if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") await this.send({ + ...event, + data: { chunk: _formatOutputChunk(runInfo.runType, chunk) } + }, runInfo); + yield chunk; + } + } finally { + tappedPromiseResolver?.(); + } + } else { + yield firstChunk.value; + for await (const chunk of outputStream) yield chunk; + } + } + async send(payload, run) { + if (this.readableStreamClosed) return; + if (this._includeRun(run)) await this.writer.write(payload); + } + async sendEndEvent(payload, run) { + const tappedPromise = this.tappedPromises.get(payload.run_id); + if (tappedPromise !== void 0) tappedPromise.then(() => { + this.send(payload, run); + }); + else await this.send(payload, run); + } + async onLLMStart(run) { + const runName = assignName(run); + const runType = run.inputs.messages !== void 0 ? "chat_model" : "llm"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType, + inputs: run.inputs + }; + this.runInfoMap.set(run.id, runInfo); + const eventName = `on_${runType}_start`; + await this.send({ + event: eventName, + data: { input: run.inputs }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onLLMNewToken(run, token, kwargs) { + const runInfo = this.runInfoMap.get(run.id); + let chunk; + let eventName; + if (runInfo === void 0) throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); + if (this.runInfoMap.size === 1) return; + if (runInfo.runType === "chat_model") { + eventName = "on_chat_model_stream"; + if (kwargs?.chunk === void 0) chunk = new AIMessageChunk({ + content: token, + id: `run-${run.id}` + }); + else chunk = kwargs.chunk.message; + } else if (runInfo.runType === "llm") { + eventName = "on_llm_stream"; + if (kwargs?.chunk === void 0) chunk = new GenerationChunk({ text: token }); + else chunk = kwargs.chunk; + } else throw new Error(`Unexpected run type ${runInfo.runType}`); + await this.send({ + event: eventName, + data: { chunk }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onLLMEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + let eventName; + if (runInfo === void 0) throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); + const generations = run.outputs?.generations; + let output; + if (runInfo.runType === "chat_model") { + for (const generation of generations ?? []) { + if (output !== void 0) break; + output = generation[0]?.message; + } + eventName = "on_chat_model_end"; + } else if (runInfo.runType === "llm") { + output = { + generations: generations?.map((generation) => { + return generation.map((chunk) => { + return { + text: chunk.text, + generationInfo: chunk.generationInfo + }; + }); + }), + llmOutput: run.outputs?.llmOutput ?? {} + }; + eventName = "on_llm_end"; + } else throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); + await this.sendEndEvent({ + event: eventName, + data: { + output, + input: runInfo.inputs + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onChainStart(run) { + const runName = assignName(run); + const runType = run.run_type ?? "chain"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: run.run_type + }; + let eventData = {}; + if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { + eventData = {}; + runInfo.inputs = {}; + } else if (run.inputs.input !== void 0) { + eventData.input = run.inputs.input; + runInfo.inputs = run.inputs.input; + } else { + eventData.input = run.inputs; + runInfo.inputs = run.inputs; + } + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: `on_${runType}_start`, + data: eventData, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onChainEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); + const eventName = `on_${run.run_type}_end`; + const inputs = run.inputs ?? runInfo.inputs ?? {}; + const data = { + output: run.outputs?.output ?? run.outputs, + input: inputs + }; + if (inputs.input && Object.keys(inputs).length === 1) { + data.input = inputs.input; + runInfo.inputs = inputs.input; + } + await this.sendEndEvent({ + event: eventName, + data, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata ?? {} + }, runInfo); + } + async onToolStart(run) { + const runName = assignName(run); + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: "tool", + inputs: run.inputs ?? {} + }; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_tool_start", + data: { input: run.inputs ?? {} }, + name: runName, + run_id: run.id, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onToolEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); + if (runInfo.inputs === void 0) throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); + const output = run.outputs?.output === void 0 ? run.outputs : run.outputs.output; + await this.sendEndEvent({ + event: "on_tool_end", + data: { + output, + input: runInfo.inputs + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onToolError(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); + if (runInfo.inputs === void 0) throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); + await this.sendEndEvent({ + event: "on_tool_error", + data: { + input: runInfo.inputs, + error: run.error + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onRetrieverStart(run) { + const runName = assignName(run); + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: "retriever", + inputs: { query: run.inputs.query } + }; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_retriever_start", + data: { input: { query: run.inputs.query } }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onRetrieverEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); + await this.sendEndEvent({ + event: "on_retriever_end", + data: { + output: run.outputs?.documents ?? run.outputs, + input: runInfo.inputs + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async handleCustomEvent(eventName, data, runId) { + const runInfo = this.runInfoMap.get(runId); + if (runInfo === void 0) throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); + await this.send({ + event: "on_custom_event", + run_id: runId, + name: eventName, + tags: runInfo.tags, + metadata: runInfo.metadata, + data + }, runInfo); + } + async finish() { + const pendingPromises = [...this.tappedPromises.values()]; + Promise.all(pendingPromises).finally(() => { + this.writer.close(); + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/is-network-error/index.js +var objectToString = Object.prototype.toString; +var isError = (value) => objectToString.call(value) === "[object Error]"; +var errorMessages = /* @__PURE__ */ new Set([ + "network error", + "Failed to fetch", + "NetworkError when attempting to fetch resource.", + "The Internet connection appears to be offline.", + "Network request failed", + "fetch failed", + "terminated", + " A network error occurred.", + "Network connection lost" +]); +function isNetworkError(error) { + if (!(error && isError(error) && error.name === "TypeError" && typeof error.message === "string")) return false; + const { message, stack } = error; + if (message === "Load failed") return stack === void 0 || "__sentry_captured__" in error; + if (message.startsWith("error sending request for url")) return true; + return errorMessages.has(message); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/p-retry/index.js +function validateRetries(retries) { + if (typeof retries === "number") { + if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number."); + if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); + } else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity."); +} +function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) { + if (value === void 0) return; + if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); + if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`); + if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`); +} +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; + } +}; +function calculateDelay(retriesConsumed, options) { + const attempt = Math.max(1, retriesConsumed + 1); + const random = options.randomize ? Math.random() + 1 : 1; + let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); + timeout = Math.min(timeout, options.maxTimeout); + return timeout; +} +function calculateRemainingTime(start, max) { + if (!Number.isFinite(max)) return max; + return max - (performance.now() - start); +} +async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) { + const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`); + if (normalizedError instanceof AbortError) throw normalizedError.originalError; + const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries; + const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; + const context = Object.freeze({ + error: normalizedError, + attemptNumber, + retriesLeft, + retriesConsumed + }); + await options.onFailedAttempt(context); + if (calculateRemainingTime(startTime, maxRetryTime) <= 0) throw normalizedError; + const consumeRetry = await options.shouldConsumeRetry(context); + const remainingTime = calculateRemainingTime(startTime, maxRetryTime); + if (remainingTime <= 0 || retriesLeft <= 0) throw normalizedError; + if (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) { + if (consumeRetry) throw normalizedError; + options.signal?.throwIfAborted(); + return false; + } + if (!await options.shouldRetry(context)) throw normalizedError; + if (!consumeRetry) { + options.signal?.throwIfAborted(); + return false; + } + let delayTime = calculateDelay(retriesConsumed, options); + const retryAfterMs = typeof normalizedError.retryAfterMs === "number" && normalizedError.retryAfterMs >= 0 ? normalizedError.retryAfterMs : void 0; + if (retryAfterMs !== void 0) delayTime = Math.max(delayTime, retryAfterMs); + const finalDelay = Math.min(delayTime, remainingTime); + if (finalDelay > 0) await new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(timeoutToken); + options.signal?.removeEventListener("abort", onAbort); + reject(options.signal.reason); + }; + const timeoutToken = setTimeout(() => { + options.signal?.removeEventListener("abort", onAbort); + resolve(); + }, finalDelay); + if (options.unref) timeoutToken.unref?.(); + options.signal?.addEventListener("abort", onAbort, { once: true }); + }); + options.signal?.throwIfAborted(); + return true; +} +async function pRetry(input, options = {}) { + options = { ...options }; + validateRetries(options.retries); + if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); + options.retries ??= 10; + options.factor ??= 2; + options.minTimeout ??= 1e3; + options.maxTimeout ??= Number.POSITIVE_INFINITY; + options.maxRetryTime ??= Number.POSITIVE_INFINITY; + options.randomize ??= false; + options.onFailedAttempt ??= () => {}; + options.shouldRetry ??= () => true; + options.shouldConsumeRetry ??= () => true; + validateNumberOption("factor", options.factor, { + min: 0, + allowInfinity: false + }); + validateNumberOption("minTimeout", options.minTimeout, { + min: 0, + allowInfinity: false + }); + validateNumberOption("maxTimeout", options.maxTimeout, { + min: 0, + allowInfinity: true + }); + validateNumberOption("maxRetryTime", options.maxRetryTime, { + min: 0, + allowInfinity: true + }); + if (!(options.factor > 0)) options.factor = 1; + options.signal?.throwIfAborted(); + let attemptNumber = 0; + let retriesConsumed = 0; + const startTime = performance.now(); + while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { + attemptNumber++; + try { + options.signal?.throwIfAborted(); + const result = await input(attemptNumber); + options.signal?.throwIfAborted(); + return result; + } catch (error) { + if (await onAttemptFailure({ + error, + attemptNumber, + retriesConsumed, + startTime, + options + })) retriesConsumed++; + } + } + throw new Error("Retry attempts exhausted without throwing an error."); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/async_caller.js +var async_caller_exports = /* @__PURE__ */ __exportAll({ + AsyncCaller: () => AsyncCaller, + classifyRateLimitError: () => classifyRateLimitError, + parseRetryAfterMs: () => parseRetryAfterMs +}); +var STATUS_NO_RETRY = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 409 +]; +var RETRY_AFTER_AUTO_RETRY_THRESHOLD_MS = 6e4; +var QUOTA_EXHAUSTED_MESSAGE_PATTERNS = [ + /insufficient[_ -]?quota/i, + /exceeded (?:your|the current|the available).+quota/i, + /usage quota/i, + /quota (?:has been )?exhausted/i, + /billing/i, + /credit balance/i, + /out of credits/i, + /will reset at/i +]; +var RETRY_AFTER_MESSAGE_PATTERN = /(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i; +function getResponseStatus(error) { + return typeof error === "object" && error !== null && "response" in error && typeof error.response === "object" && error.response !== null && "status" in error.response && typeof error.response.status === "number" ? error.response.status : void 0; +} +function getDirectStatus(error) { + if (typeof error !== "object" || error === null) return; + if ("status" in error && typeof error.status === "number") return error.status; + if ("statusCode" in error && typeof error.statusCode === "number") return error.statusCode; +} +function getErrorMessage(error) { + return typeof error === "object" && error !== null && "message" in error && typeof error.message === "string" ? error.message : void 0; +} +function getErrorCode(error) { + if (typeof error !== "object" || error === null) return; + if ("code" in error && typeof error.code === "string") return error.code; + return "error" in error && typeof error.error === "object" && error.error !== null && "code" in error.error && typeof error.error.code === "string" ? error.error.code : void 0; +} +function _getRetryAfterHeader(error) { + if (error?.headers) { + if (typeof error.headers.get === "function") return error.headers.get("retry-after"); + return error.headers["retry-after"] ?? error.headers["Retry-After"]; + } + if (error?.response?.headers) { + if (typeof error.response.headers.get === "function") return error.response.headers.get("retry-after"); + return error.response.headers["retry-after"] ?? error.response.headers["Retry-After"]; + } +} +function parseRetryAfterFromMessageMs(message) { + if (message == null) return; + const match = RETRY_AFTER_MESSAGE_PATTERN.exec(message); + if (!match) return; + const rawValue = Number(match[1]); + const unit = match[2]?.toLowerCase(); + if (Number.isNaN(rawValue) || !unit) return; + if (unit === "ms" || unit.startsWith("millisecond")) return rawValue; + if (unit === "m" || unit.startsWith("min")) return rawValue * 6e4; + if (unit === "h" || unit.startsWith("hr") || unit.startsWith("hour")) return rawValue * 36e5; + return rawValue * 1e3; +} +function coerceError(error, fallbackMessage) { + if (error instanceof Error) return error; + const coerced = new Error(fallbackMessage); + if (typeof error === "object" && error !== null) Object.assign(coerced, error); + return coerced; +} +function setRateLimitMetadata(error, classification) { + if (typeof error !== "object" || error === null) return; + const mutableError = error; + mutableError.rateLimitType = classification.action; + mutableError.rateLimitReason = classification.reason; + if (classification.retryAfterMs !== void 0) mutableError.retryAfterMs = classification.retryAfterMs; +} +function parseRetryAfterMs(headerValue) { + if (headerValue == null) return; + const trimmed = headerValue.trim(); + if (!trimmed) return; + const seconds = Number(trimmed); + if (!Number.isNaN(seconds) && seconds >= 0) return seconds * 1e3; + const date = Date.parse(trimmed); + if (!Number.isNaN(date)) { + const delayMs = date - Date.now(); + return delayMs > 0 ? delayMs : 0; + } +} +function classifyRateLimitError(error) { + if ((getResponseStatus(error) ?? getDirectStatus(error)) !== 429) return; + if (getErrorCode(error) === "insufficient_quota") return { + action: "stop", + reason: "insufficient_quota" + }; + const message = getErrorMessage(error); + if (message && QUOTA_EXHAUSTED_MESSAGE_PATTERNS.some((pattern) => pattern.test(message))) return { + action: "stop", + reason: "quota_message" + }; + const retryAfterMs = parseRetryAfterMs(_getRetryAfterHeader(error)) ?? parseRetryAfterFromMessageMs(message); + if (retryAfterMs !== void 0) { + if (retryAfterMs <= RETRY_AFTER_AUTO_RETRY_THRESHOLD_MS) return { + action: "wait", + retryAfterMs, + reason: "retry_after_hint" + }; + return { + action: "capacity", + retryAfterMs, + reason: "retry_after_too_large" + }; + } + return { + action: "capacity", + reason: "headerless_429" + }; +} +/** +* The default failed attempt handler for the AsyncCaller. +* @param error - The error to handle. +* @returns void +*/ +var defaultFailedAttemptHandler = (error) => { + if (typeof error !== "object" || error === null) return; + if ("message" in error && typeof error.message === "string" && (error.message.startsWith("Cancel") || error.message.startsWith("AbortError")) || "name" in error && typeof error.name === "string" && error.name === "AbortError") throw error; + if ("code" in error && typeof error.code === "string" && error.code === "ECONNABORTED") throw error; + const status = getResponseStatus(error) ?? getDirectStatus(error); + if (status && STATUS_NO_RETRY.includes(+status)) throw error; + if (getErrorCode(error) === "insufficient_quota") { + const err = coerceError(error, getErrorMessage(error) ?? "Insufficient quota"); + err.name = "InsufficientQuotaError"; + setRateLimitMetadata(err, { + action: "stop", + reason: "insufficient_quota" + }); + throw err; + } + const rateLimitClassification = classifyRateLimitError(error); + if (rateLimitClassification) { + if (rateLimitClassification.action === "wait") { + setRateLimitMetadata(error, rateLimitClassification); + return; + } + const err = coerceError(error, getErrorMessage(error) ?? "Rate limit exceeded"); + if (err.name === "Error") err.name = rateLimitClassification.action === "stop" ? "RateLimitQuotaExhaustedError" : "RateLimitCapacityError"; + setRateLimitMetadata(err, rateLimitClassification); + throw err; + } +}; +/** +* A class that can be used to make async calls with concurrency and retry logic. +* +* This is useful for making calls to any kind of "expensive" external resource, +* be it because it's rate-limited, subject to network issues, etc. +* +* Concurrent calls are limited by the `maxConcurrency` parameter, which defaults +* to `Infinity`. This means that by default, all calls will be made in parallel. +* +* Retries are limited by the `maxRetries` parameter, which defaults to 6. This +* means that by default, each call will be retried up to 6 times, with an +* exponential backoff between each attempt. +*/ +var AsyncCaller = class { + maxConcurrency; + maxRetries; + onFailedAttempt; + queue; + constructor(params) { + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; + const PQueue = "default" in import_dist.default ? import_dist.default.default : import_dist.default; + this.queue = new PQueue({ concurrency: this.maxConcurrency }); + } + async call(callable, ...args) { + return this.queue.add(() => pRetry(() => callable(...args).catch((error) => { + if (error instanceof Error) throw error; + else throw new Error(error); + }), { + onFailedAttempt: ({ error }) => this.onFailedAttempt?.(error), + retries: this.maxRetries, + randomize: true + }), { throwOnTimeout: true }); + } + callWithOptions(options, callable, ...args) { + if (options.signal) { + let listener; + return Promise.race([this.call(callable, ...args), new Promise((_, reject) => { + listener = () => { + reject(getAbortSignalError(options.signal)); + }; + options.signal?.addEventListener("abort", listener, { once: true }); + })]).finally(() => { + if (options.signal && listener) options.signal.removeEventListener("abort", listener); + }); + } + return this.call(callable, ...args); + } + fetch(...args) { + return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/tracers/root_listener.js +var RootListenersTracer = class extends BaseTracer { + name = "RootListenersTracer"; + /** The Run's ID. Type UUID */ + rootId; + config; + argOnStart; + argOnEnd; + argOnError; + constructor({ config, onStart, onEnd, onError }) { + super({ _awaitHandler: true }); + this.config = config; + this.argOnStart = onStart; + this.argOnEnd = onEnd; + this.argOnError = onError; + } + /** + * This is a legacy method only called once for an entire run tree + * therefore not useful here + * @param {Run} _ Not used + */ + persistRun(_) { + return Promise.resolve(); + } + async onRunCreate(run) { + if (this.rootId) return; + this.rootId = run.id; + if (this.argOnStart) await this.argOnStart(run, this.config); + } + async onRunUpdate(run) { + if (run.id !== this.rootId) return; + if (!run.error) { + if (this.argOnEnd) await this.argOnEnd(run, this.config); + } else if (this.argOnError) await this.argOnError(run, this.config); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/runnables/utils.js +function isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; +} +/** +* Utility to filter the root event in the streamEvents implementation. +* This is simply binding the arguments to the namespace to make save on +* a bit of typing in the streamEvents implementation. +* +* TODO: Refactor and remove. +*/ +var _RootEventFilter = class { + includeNames; + includeTypes; + includeTags; + excludeNames; + excludeTypes; + excludeTags; + constructor(fields) { + this.includeNames = fields.includeNames; + this.includeTypes = fields.includeTypes; + this.includeTags = fields.includeTags; + this.excludeNames = fields.excludeNames; + this.excludeTypes = fields.excludeTypes; + this.excludeTags = fields.excludeTags; + } + includeEvent(event, rootType) { + let include = this.includeNames === void 0 && this.includeTypes === void 0 && this.includeTags === void 0; + const eventTags = event.tags ?? []; + if (this.includeNames !== void 0) include = include || this.includeNames.includes(event.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(event.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; + } +}; +var toBase64Url = (str) => { + return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +}; +//#endregion +//#region node_modules/@langchain/core/dist/runnables/graph_mermaid.js +function _escapeNodeLabel(nodeLabel) { + return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); +} +var MARKDOWN_SPECIAL_CHARS = [ + "*", + "_", + "`" +]; +function _generateMermaidGraphStyles(nodeColors) { + let styles = ""; + for (const [className, color] of Object.entries(nodeColors)) styles += `\tclassDef ${className} ${color};\n`; + return styles; +} +/** +* Draws a Mermaid graph using the provided graph data +*/ +function drawMermaid(nodes, edges, config) { + const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9 } = config ?? {}; + let mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\ngraph TD;\n` : "graph TD;\n"; + if (withStyles) { + const defaultClassLabel = "default"; + const formatDict = { [defaultClassLabel]: "{0}({1})" }; + if (firstNode !== void 0) formatDict[firstNode] = "{0}([{1}]):::first"; + if (lastNode !== void 0) formatDict[lastNode] = "{0}([{1}]):::last"; + for (const [key, node] of Object.entries(nodes)) { + const nodeName = node.name.split(":").pop() ?? ""; + let finalLabel = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `

${nodeName}

` : nodeName; + if (Object.keys(node.metadata ?? {}).length) finalLabel += `
${Object.entries(node.metadata ?? {}).map(([k, v]) => `${k} = ${v}`).join("\n")}`; + const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel); + mermaidGraph += `\t${nodeLabel}\n`; + } + } + const edgeGroups = {}; + for (const edge of edges) { + const srcParts = edge.source.split(":"); + const tgtParts = edge.target.split(":"); + const commonPrefix = srcParts.filter((src, i) => src === tgtParts[i]).join(":"); + if (!edgeGroups[commonPrefix]) edgeGroups[commonPrefix] = []; + edgeGroups[commonPrefix].push(edge); + } + const seenSubgraphs = /* @__PURE__ */ new Set(); + function sortPrefixesByDepth(prefixes) { + return [...prefixes].sort((a, b) => { + return a.split(":").length - b.split(":").length; + }); + } + function addSubgraph(edges, prefix) { + const selfLoop = edges.length === 1 && edges[0].source === edges[0].target; + if (prefix && !selfLoop) { + const subgraph = prefix.split(":").pop(); + if (seenSubgraphs.has(prefix)) throw new Error(`Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`); + seenSubgraphs.add(prefix); + mermaidGraph += `\tsubgraph ${subgraph}\n`; + } + const nestedPrefixes = sortPrefixesByDepth(Object.keys(edgeGroups).filter((nestedPrefix) => nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix && nestedPrefix.split(":").length === prefix.split(":").length + 1)); + for (const nestedPrefix of nestedPrefixes) addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); + for (const edge of edges) { + const { source, target, data, conditional } = edge; + let edgeLabel = ""; + if (data !== void 0) { + let edgeData = data; + const words = edgeData.split(" "); + if (words.length > wrapLabelNWords) edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words.slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords).join(" ")).join(" 
 "); + edgeLabel = conditional ? ` -.  ${edgeData}  .-> ` : ` --  ${edgeData}  --> `; + } else edgeLabel = conditional ? " -.-> " : " --> "; + mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`; + } + if (prefix && !selfLoop) mermaidGraph += " end\n"; + } + addSubgraph(edgeGroups[""] ?? [], ""); + for (const prefix in edgeGroups) if (!prefix.includes(":") && prefix !== "") addSubgraph(edgeGroups[prefix], prefix); + if (withStyles) mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); + return mermaidGraph; +} +/** +* Renders Mermaid graph using the Mermaid.INK API. +* +* @example +* ```javascript +* const image = await drawMermaidImage(mermaidSyntax, { +* backgroundColor: "white", +* imageType: "png", +* }); +* fs.writeFileSync("image.png", image); +* ``` +* +* @param mermaidSyntax - The Mermaid syntax to render. +* @param config - The configuration for the image. +* @returns The image as a Blob. +*/ +async function drawMermaidImage(mermaidSyntax, config) { + let backgroundColor = config?.backgroundColor ?? "white"; + const imageType = config?.imageType ?? "png"; + const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax); + if (backgroundColor !== void 0) { + if (!/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(backgroundColor)) backgroundColor = `!${backgroundColor}`; + } + const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`; + const res = await fetch(imageUrl); + if (!res.ok) throw new Error([ + `Failed to render the graph using the Mermaid.INK API.`, + `Status code: ${res.status}`, + `Status text: ${res.statusText}` + ].join("\n")); + return await res.blob(); +} +//#endregion +//#region node_modules/@langchain/core/dist/runnables/graph.js +var graph_exports = /* @__PURE__ */ __exportAll({ Graph: () => Graph }); +function nodeDataStr(id, data) { + if (id !== void 0 && !validate$2(id)) return id; + else if (isRunnableInterface(data)) try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; + return dataStr; + } catch { + return data.getName(); + } + else return data.name ?? "UnknownSchema"; +} +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: { + ...toJsonSchema(node.data.schema), + title: node.data.name + } + }; +} +var Graph = class Graph { + nodes = {}; + edges = []; + constructor(params) { + this.nodes = params?.nodes ?? this.nodes; + this.edges = params?.edges ?? this.edges; + } + toJSON() { + const stableNodeIds = {}; + Object.values(this.nodes).forEach((node, i) => { + stableNodeIds[node.id] = validate$2(node.id) ? i : node.id; + }); + return { + nodes: Object.values(this.nodes).map((node) => ({ + id: stableNodeIds[node.id], + ...nodeDataJson(node) + })), + edges: this.edges.map((edge) => { + const item = { + source: stableNodeIds[edge.source], + target: stableNodeIds[edge.target] + }; + if (typeof edge.data !== "undefined") item.data = edge.data; + if (typeof edge.conditional !== "undefined") item.conditional = edge.conditional; + return item; + }) + }; + } + addNode(data, id, metadata) { + if (id !== void 0 && this.nodes[id] !== void 0) throw new Error(`Node with id ${id} already exists`); + const nodeId = id ?? v4$1(); + const node = { + id: nodeId, + data, + name: nodeDataStr(id, data), + metadata + }; + 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, conditional) { + 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, + conditional + }; + this.edges.push(edge); + return edge; + } + firstNode() { + return _firstNode(this); + } + lastNode() { + return _lastNode(this); + } + /** + * Add all nodes and edges from another graph. + * Note this doesn't check for duplicates, nor does it connect the graphs. + */ + extend(graph, prefix = "") { + let finalPrefix = prefix; + if (Object.values(graph.nodes).map((node) => node.id).every(validate$2)) finalPrefix = ""; + const prefixed = (id) => { + return finalPrefix ? `${finalPrefix}:${id}` : id; + }; + Object.entries(graph.nodes).forEach(([key, value]) => { + this.nodes[prefixed(key)] = { + ...value, + id: prefixed(key) + }; + }); + const newEdges = graph.edges.map((edge) => { + return { + ...edge, + source: prefixed(edge.source), + target: prefixed(edge.target) + }; + }); + this.edges = [...this.edges, ...newEdges]; + const first = graph.firstNode(); + const last = graph.lastNode(); + return [first ? { + id: prefixed(first.id), + data: first.data + } : void 0, last ? { + id: prefixed(last.id), + data: last.data + } : void 0]; + } + trimFirstNode() { + const firstNode = this.firstNode(); + if (firstNode && _firstNode(this, [firstNode.id])) this.removeNode(firstNode); + } + trimLastNode() { + const lastNode = this.lastNode(); + if (lastNode && _lastNode(this, [lastNode.id])) this.removeNode(lastNode); + } + /** + * Return a new graph with all nodes re-identified, + * using their unique, readable names where possible. + */ + reid() { + const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); + const nodeLabelCounts = /* @__PURE__ */ new Map(); + Object.values(nodeLabels).forEach((label) => { + nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); + }); + const getNodeId = (nodeId) => { + const label = nodeLabels[nodeId]; + if (validate$2(nodeId) && nodeLabelCounts.get(label) === 1) return label; + else return nodeId; + }; + return new Graph({ + nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [getNodeId(id), { + ...node, + id: getNodeId(id) + }])), + edges: this.edges.map((edge) => ({ + ...edge, + source: getNodeId(edge.source), + target: getNodeId(edge.target) + })) + }); + } + drawMermaid(params) { + const { withStyles, curveStyle, nodeColors = { + default: "fill:#f2f0ff,line-height:1.2", + first: "fill-opacity:0", + last: "fill:#bfb6fc" + }, wrapLabelNWords } = params ?? {}; + const graph = this.reid(); + const firstNode = graph.firstNode(); + const lastNode = graph.lastNode(); + return drawMermaid(graph.nodes, graph.edges, { + firstNode: firstNode?.id, + lastNode: lastNode?.id, + withStyles, + curveStyle, + nodeColors, + wrapLabelNWords + }); + } + async drawMermaidPng(params) { + return drawMermaidImage(this.drawMermaid(params), { backgroundColor: params?.backgroundColor }); + } +}; +/** +* Find the single node that is not a target of any edge. +* Exclude nodes/sources with ids in the exclude list. +* If there is no such node, or there are multiple, return undefined. +* When drawing the graph, this node would be the origin. +*/ +function _firstNode(graph, exclude = []) { + const targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target)); + const found = []; + for (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !targets.has(node.id)) found.push(node); + return found.length === 1 ? found[0] : void 0; +} +/** +* Find the single node that is not a source of any edge. +* Exclude nodes/targets with ids in the exclude list. +* If there is no such node, or there are multiple, return undefined. +* When drawing the graph, this node would be the destination. +*/ +function _lastNode(graph, exclude = []) { + const sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source)); + const found = []; + for (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !sources.has(node.id)) found.push(node); + return found.length === 1 ? found[0] : void 0; +} +//#endregion +//#region node_modules/@langchain/core/dist/runnables/wrappers.js +function convertToHttpEventStream(stream) { + const encoder = new TextEncoder(); + const finalStream = new ReadableStream({ async start(controller) { + for await (const chunk of stream) controller.enqueue(encoder.encode(`event: data\ndata: ${JSON.stringify(chunk)}\n\n`)); + controller.enqueue(encoder.encode("event: end\n\n")); + controller.close(); + } }); + return IterableReadableStream.fromReadableStream(finalStream); +} +//#endregion +//#region node_modules/@langchain/core/dist/runnables/iter.js +function isIterableIterator(thing) { + return typeof thing === "object" && thing !== null && typeof thing[Symbol.iterator] === "function" && typeof thing.next === "function"; +} +var isIterator = (x) => x != null && typeof x === "object" && "next" in x && typeof x.next === "function"; +function isAsyncIterable(thing) { + return typeof thing === "object" && thing !== null && typeof thing[Symbol.asyncIterator] === "function"; +} +function isAsyncGenerator(x) { + return x != null && typeof x === "object" && typeof x.next === "function"; +} +async function consumeAsyncGenerator(generator, onYield) { + try { + let iterResult = await generator.next(); + while (!iterResult.done) { + await onYield?.(iterResult.value); + iterResult = await generator.next(); + } + return iterResult.value; + } finally { + await generator.return?.(void 0); + } +} +function* consumeIteratorInContext(context, iter) { + while (true) { + const { value, done } = AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true); + if (done) break; + else yield value; + } +} +async function* consumeAsyncIterableInContext(context, iter) { + const iterator = iter[Symbol.asyncIterator](); + while (true) { + const { value, done } = await AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true); + if (done) break; + else yield value; + } +} +//#endregion +//#region node_modules/@langchain/core/dist/runnables/base.js +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; +} +/** +* A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or +* transformed. +*/ +var Runnable = class extends Serializable { + lc_runnable = true; + name; + getName(suffix) { + const name = this.name ?? this.constructor.lc_name() ?? this.constructor.name; + return suffix ? `${name}${suffix}` : name; + } + /** + * Add retry logic to an existing runnable. + * @param fields.stopAfterAttempt The number of attempts to retry. + * @param fields.onFailedAttempt A function that is called when a retry fails. + * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. + */ + withRetry(fields) { + return new RunnableRetry({ + bound: this, + kwargs: {}, + config: {}, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields + }); + } + /** + * Bind config to a Runnable, returning a new Runnable. + * @param config New configuration parameters to attach to the new runnable. + * @returns A new RunnableBinding with a config matching what's passed. + */ + withConfig(config) { + return new RunnableBinding({ + bound: this, + config, + kwargs: {} + }); + } + /** + * Create a new runnable from the current one that will try invoking + * other passed fallback runnables if the initial invocation fails. + * @param fields.fallbacks Other runnables to call if the runnable errors. + * @returns A new RunnableWithFallbacks. + */ + withFallbacks(fields) { + const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; + return new RunnableWithFallbacks({ + runnable: this, + fallbacks + }); + } + _getOptionsList(options, length = 0) { + if (Array.isArray(options) && 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`); + if (Array.isArray(options)) return options.map(ensureConfig); + if (length > 1 && !Array.isArray(options) && options.runId) { + console.warn("Provided runId will be used only for the first element of the batch."); + const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); + return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); + } + return Array.from({ length }, () => ensureConfig(options)); + } + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const caller = new AsyncCaller({ + maxConcurrency: configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency, + onFailedAttempt: (e) => { + throw e; + } + }); + const batchCalls = inputs.map((input, i) => caller.call(async () => { + try { + return await this.invoke(input, configList[i]); + } catch (e) { + if (batchOptions?.returnExceptions) return e; + throw e; + } + })); + return Promise.all(batchCalls); + } + /** + * Default streaming implementation. + * Subclasses should override this method if they support streaming output. + * @param input + * @param options + */ + async *_streamIterator(input, options) { + yield this.invoke(input, options); + } + /** + * Stream output in chunks. + * @param input + * @param options + * @returns A readable stream that is also an iterable. + */ + async stream(input, options) { + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this._streamIterator(input, config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + _separateRunnableConfigFromCallOptions(options) { + let runnableConfig; + if (options === void 0) runnableConfig = ensureConfig(options); + else runnableConfig = ensureConfig({ + callbacks: options.callbacks, + tags: options.tags, + metadata: options.metadata, + runName: options.runName, + configurable: options.configurable, + recursionLimit: options.recursionLimit, + maxConcurrency: options.maxConcurrency, + runId: options.runId, + timeout: options.timeout, + signal: options.signal + }); + const callOptions = { ...options }; + delete callOptions.callbacks; + delete callOptions.tags; + delete callOptions.metadata; + delete callOptions.runName; + delete callOptions.configurable; + delete callOptions.recursionLimit; + delete callOptions.maxConcurrency; + delete callOptions.runId; + delete callOptions.timeout; + delete callOptions.signal; + return [runnableConfig, callOptions]; + } + async _callWithConfig(func, input, options) { + const config = ensureConfig(options); + const runManager = await (await getCallbackManagerForConfig(config))?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, config?.runType, void 0, void 0, config?.runName ?? this.getName()); + delete config.runId; + let output; + try { + output = await raceWithSignal(func.call(this, input, config, runManager), config.signal); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict(output, "output")); + return output; + } + /** + * Internal method that handles batching and configuration for a runnable + * It takes a function, input values, and optional configuration, and + * returns a promise that resolves to the output values. + * @param func The function to be executed for each input value. + * @param input The input values to be processed. + * @param config Optional configuration for the function execution. + * @returns A promise that resolves to the output values. + */ + async _batchWithConfig(func, inputs, options, batchOptions) { + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, void 0, void 0, optionsList[i].runName ?? this.getName()); + delete optionsList[i].runId; + return handleStartRes; + })); + let outputs; + try { + outputs = await raceWithSignal(func.call(this, inputs, optionsList, runManagers, batchOptions), optionsList?.[0]?.signal); + } catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, "output")))); + return outputs; + } + /** @internal */ + _concatOutputChunks(first, second) { + return concat(first, second); + } + /** + * Helper method to transform an Iterator of Input values into an Iterator of + * Output values, with callbacks. + * Use this to implement `stream()` or `transform()` in Runnable subclasses. + */ + async *_transformStreamWithConfig(inputGenerator, transformer, options) { + let finalInput; + let finalInputSupported = true; + let finalOutput; + let finalOutputSupported = true; + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const outerThis = this; + async function* wrapInputForTracing() { + for await (const chunk of inputGenerator) { + if (finalInputSupported) if (finalInput === void 0) finalInput = chunk; + else try { + finalInput = outerThis._concatOutputChunks(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: "" }, config.runId, config.runType, void 0, void 0, config.runName ?? this.getName(), void 0, { lc_defers_inputs: true }), config.signal, config); + delete config.runId; + runManager = pipe.setup; + const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); + let iterator = pipe.output; + if (streamEventsHandler !== void 0 && runManager !== void 0) iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); + const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); + if (streamLogHandler !== void 0 && runManager !== void 0) iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); + for await (const chunk of iterator) { + yield chunk; + if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = void 0; + finalOutputSupported = false; + } + } + } catch (e) { + await runManager?.handleChainError(e, void 0, void 0, void 0, { inputs: _coerceToDict(finalInput, "input") }); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: _coerceToDict(finalInput, "input") }); + } + getGraph(_) { + const graph = new Graph(); + const inputNode = graph.addNode({ + name: `${this.getName()}Input`, + schema: anyType() + }); + const runnableNode = graph.addNode(this); + const outputNode = graph.addNode({ + name: `${this.getName()}Output`, + schema: anyType() + }); + graph.addEdge(inputNode, runnableNode); + graph.addEdge(runnableNode, outputNode); + return graph; + } + /** + * Create a new runnable sequence that runs each individual runnable in series, + * piping the output of one runnable into another runnable or runnable-like. + * @param coerceable A runnable, function, or object whose values are functions or runnables. + * @returns A new runnable sequence. + */ + pipe(coerceable) { + return new RunnableSequence({ + first: this, + last: _coerceToRunnable(coerceable) + }); + } + /** + * Pick keys from the dict output of this runnable. Returns a new runnable. + */ + pick(keys) { + return this.pipe(new RunnablePick(keys)); + } + /** + * Assigns new fields to the dict output of this runnable. Returns a new runnable. + */ + assign(mapping) { + return this.pipe(new RunnableAssign(new RunnableMap({ steps: mapping }))); + } + /** + * Default implementation of transform, which buffers input and then calls stream. + * Subclasses should override this method if they can start producing output while + * input is still being generated. + * @param generator + * @param options + */ + async *transform(generator, options) { + let finalChunk; + for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk; + else finalChunk = this._concatOutputChunks(finalChunk, chunk); + yield* this._streamIterator(finalChunk, ensureConfig(options)); + } + /** + * Stream all output from a runnable, as reported to the callback system. + * This includes all inner runs of LLMs, Retrievers, Tools, etc. + * Output is streamed as Log objects, which include a list of + * jsonpatch ops that describe how the state of the run has changed in each + * step, and the final state of the run. + * The jsonpatch ops can be applied in order to construct state. + * + * @deprecated Use `.stream()` instead. + * + * @param input + * @param options + * @param streamOptions + */ + 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.addHandler(logStreamCallbackHandler, true); + 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; + } + } + streamEvents(input, options, streamOptions) { + let stream; + if (options.version === "v1") stream = this._streamEventsV1(input, options, streamOptions); + else if (options.version === "v2") stream = this._streamEventsV2(input, options, streamOptions); + else throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); + if (options.encoding === "text/event-stream") return convertToHttpEventStream(stream); + else return IterableReadableStream.fromAsyncGenerator(stream); + } + async *_streamEventsV2(input, options, streamOptions) { + const eventStreamer = new EventStreamCallbackHandler({ + ...streamOptions, + autoClose: false + }); + const config = ensureConfig(options); + const runId = config.runId ?? v7$1(); + config.runId = runId; + const callbacks = config.callbacks; + if (callbacks === void 0) config.callbacks = [eventStreamer]; + else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(eventStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(eventStreamer, true); + config.callbacks = copiedCallbacks; + } + const abortController = new AbortController(); + const outerThis = this; + async function consumeRunnableStream() { + let signal; + try { + if (config.signal) if ("any" in AbortSignal) signal = AbortSignal.any([abortController.signal, config.signal]); + else { + const composed = new AbortController(); + config.signal.addEventListener("abort", () => composed.abort(), { once: true }); + abortController.signal.addEventListener("abort", () => composed.abort(), { once: true }); + signal = composed.signal; + } + else signal = abortController.signal; + const runnableStream = await outerThis.stream(input, { + ...config, + signal + }); + const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); + for await (const _ of tappedStream) if (abortController.signal.aborted) break; + } finally { + await eventStreamer.finish(); + } + } + const runnableStreamConsumePromise = consumeRunnableStream(); + let firstEventSent = false; + let firstEventRunId; + try { + for await (const event of eventStreamer) { + if (!firstEventSent) { + event.data.input = input; + firstEventSent = true; + firstEventRunId = event.run_id; + yield event; + continue; + } + if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { + if (event.data?.input) delete event.data.input; + } + yield event; + } + } finally { + abortController.abort(); + await runnableStreamConsumePromise; + } + } + async *_streamEventsV1(input, options, streamOptions) { + 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 state = { ...runLog.state }; + const event = { + run_id: state.id, + event: `on_${state.type}_start`, + name: rootName, + tags: rootTags, + metadata: rootMetadata, + data: { input } + }; + if (rootEventFilter.includeEvent(event, state.type)) yield event; + } + 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 } = runLog; + if (state.streamed_output.length > 0) { + const chunkCount = state.streamed_output.length; + if (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state.name}"`); + const data = { chunk: state.streamed_output[0] }; + state.streamed_output = []; + const event = { + event: `on_${state.type}_stream`, + run_id: state.id, + tags: rootTags, + metadata: rootMetadata, + name: rootName, + data + }; + if (rootEventFilter.includeEvent(event, state.type)) yield event; + } + } + const state = runLog?.state; + if (state !== void 0) { + const event = { + event: `on_${state.type}_end`, + name: rootName, + run_id: state.id, + tags: rootTags, + metadata: rootMetadata, + data: { output: state.final_output } + }; + if (rootEventFilter.includeEvent(event, state.type)) yield event; + } + } + static isRunnable(thing) { + return isRunnableInterface(thing); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError }) { + return new RunnableBinding({ + bound: this, + config: {}, + configFactories: [(config) => ({ callbacks: [new RootListenersTracer({ + config, + onStart, + onEnd, + onError + })] })] + }); + } + /** + * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` + * which contains the runnable, name, description and schema. + * + * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. + * + * @param fields + * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. + * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. + * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. + * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. + */ + asTool(fields) { + return convertRunnableToTool(this, fields); + } +}; +/** +* Wraps a runnable and applies partial config upon invocation. +* +* @example +* ```typescript +* import { +* type RunnableConfig, +* RunnableLambda, +* } from "@langchain/core/runnables"; +* +* const enhanceProfile = ( +* profile: Record, +* config?: RunnableConfig +* ) => { +* if (config?.configurable?.role) { +* return { ...profile, role: config.configurable.role }; +* } +* return profile; +* }; +* +* const runnable = RunnableLambda.from(enhanceProfile); +* +* // Bind configuration to the runnable to set the user's role dynamically +* const adminRunnable = runnable.withConfig({ configurable: { role: "Admin" } }); +* const userRunnable = runnable.withConfig({ configurable: { role: "User" } }); +* +* const result1 = await adminRunnable.invoke({ +* name: "Alice", +* email: "alice@example.com" +* }); +* +* // { name: "Alice", email: "alice@example.com", role: "Admin" } +* +* const result2 = await userRunnable.invoke({ +* name: "Bob", +* email: "bob@example.com" +* }); +* +* // { name: "Bob", email: "bob@example.com", role: "User" } +* ``` +*/ +var RunnableBinding = class RunnableBinding extends Runnable { + static lc_name() { + return "RunnableBinding"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + bound; + config; + kwargs; + configFactories; + constructor(fields) { + super(fields); + this.bound = fields.bound; + this.kwargs = fields.kwargs; + this.config = fields.config; + this.configFactories = fields.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))) : []); + } + withConfig(config) { + return new this.constructor({ + bound: this.bound, + kwargs: this.kwargs, + config: { + ...this.config, + ...config + } + }); + } + withRetry(fields) { + return new RunnableRetry({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields + }); + } + 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(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs); + return this.bound.batch(inputs, mergedOptions, batchOptions); + } + /** @internal */ + _concatOutputChunks(first, second) { + return this.bound._concatOutputChunks(first, second); + } + async *_streamIterator(input, options) { + yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + async stream(input, options) { + return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + async *transform(generator, options) { + yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + streamEvents(input, options, streamOptions) { + const outerThis = this; + const generator = async function* () { + yield* outerThis.bound.streamEvents(input, { + ...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs), + version: options.version + }, streamOptions); + }; + return IterableReadableStream.fromAsyncGenerator(generator()); + } + static isRunnableBinding(thing) { + return thing.bound && Runnable.isRunnable(thing.bound); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + 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 + })] })] + }); + } +}; +/** +* A runnable that delegates calls to another runnable +* with each element of the input sequence. +* @example +* ```typescript +* import { RunnableEach, RunnableLambda } from "@langchain/core/runnables"; +* +* const toUpperCase = (input: string): string => input.toUpperCase(); +* const addGreeting = (input: string): string => `Hello, ${input}!`; +* +* const upperCaseLambda = RunnableLambda.from(toUpperCase); +* const greetingLambda = RunnableLambda.from(addGreeting); +* +* const chain = new RunnableEach({ +* bound: upperCaseLambda.pipe(greetingLambda), +* }); +* +* const result = await chain.invoke(["alice", "bob", "carol"]) +* +* // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"] +* ``` +*/ +var RunnableEach = class RunnableEach extends Runnable { + static lc_name() { + return "RunnableEach"; + } + lc_serializable = true; + lc_namespace = ["langchain_core", "runnables"]; + bound; + constructor(fields) { + super(fields); + this.bound = fields.bound; + } + /** + * Invokes the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(inputs, config) { + return this._callWithConfig(this._invoke.bind(this), inputs, config); + } + /** + * A helper method that is used to invoke the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async _invoke(inputs, config, runManager) { + return this.bound.batch(inputs, patchConfig(config, { callbacks: runManager?.getChild() })); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError }) { + return new RunnableEach({ bound: this.bound.withListeners({ + onStart, + onEnd, + onError + }) }); + } +}; +/** +* Base class for runnables that can be retried a +* specified number of times. +* @example +* ```typescript +* import { +* RunnableLambda, +* RunnableRetry, +* } from "@langchain/core/runnables"; +* +* // Simulate an API call that fails +* const simulateApiCall = (input: string): string => { +* console.log(`Attempting API call with input: ${input}`); +* throw new Error("API call failed due to network issue"); +* }; +* +* const apiCallLambda = RunnableLambda.from(simulateApiCall); +* +* // Apply retry logic using the .withRetry() method +* const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 }); +* +* // Alternatively, create a RunnableRetry instance manually +* const manualRetry = new RunnableRetry({ +* bound: apiCallLambda, +* maxAttemptNumber: 3, +* config: {}, +* }); +* +* // Example invocation using the .withRetry() method +* const res = await apiCallWithRetry +* .invoke("Request 1") +* .catch((error) => { +* console.error("Failed after multiple retries:", error.message); +* }); +* +* // Example invocation using the manual retry instance +* const res2 = await manualRetry +* .invoke("Request 2") +* .catch((error) => { +* console.error("Failed after multiple retries:", error.message); +* }); +* ``` +*/ +var RunnableRetry = class extends RunnableBinding { + static lc_name() { + return "RunnableRetry"; + } + lc_namespace = ["langchain_core", "runnables"]; + maxAttemptNumber = 3; + onFailedAttempt = () => {}; + constructor(fields) { + super(fields); + this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; + this.onFailedAttempt = fields.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 pRetry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { + onFailedAttempt: ({ error }) => this.onFailedAttempt(error, input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true + }); + } + /** + * Method that invokes the runnable with the specified input, run manager, + * and config. It handles the retry logic by catching any errors and + * recursively invoking itself with the updated config for the next retry + * attempt. + * @param input The input for the runnable. + * @param runManager The run manager for the runnable. + * @param config The config for the runnable. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(input, config) { + return this._callWithConfig(this._invoke.bind(this), input, config); + } + async _batch(inputs, configs, runManagers, batchOptions) { + const resultsMap = {}; + try { + await pRetry(async (attemptNumber) => { + const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === void 0 || resultsMap[i.toString()] instanceof Error); + const remainingInputs = remainingIndexes.map((i) => inputs[i]); + const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); + const results = await super.batch(remainingInputs, patchedConfigs, { + ...batchOptions, + returnExceptions: true + }); + let firstException; + for (let i = 0; i < results.length; i += 1) { + const result = results[i]; + const resultMapIndex = remainingIndexes[i]; + if (result instanceof Error) { + if (firstException === void 0) { + firstException = result; + firstException.input = remainingInputs[i]; + } + } + resultsMap[resultMapIndex.toString()] = result; + } + if (firstException) throw firstException; + return results; + }, { + onFailedAttempt: ({ error }) => this.onFailedAttempt(error, error.input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true + }); + } catch (e) { + if (batchOptions?.returnExceptions !== true) throw e; + } + return Object.keys(resultsMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)).map((key) => resultsMap[parseInt(key, 10)]); + } + async batch(inputs, options, batchOptions) { + return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); + } +}; +/** +* A sequence of runnables, where the output of each is the input of the next. +* @example +* ```typescript +* const promptTemplate = PromptTemplate.fromTemplate( +* "Tell me a joke about {topic}", +* ); +* const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: "gpt-4o-mini" })]); +* const result = await chain.invoke({ topic: "bears" }); +* ``` +*/ +var RunnableSequence = class RunnableSequence extends Runnable { + static lc_name() { + return "RunnableSequence"; + } + first; + middle = []; + last; + omitSequenceTags = false; + lc_serializable = true; + lc_namespace = ["langchain_core", "runnables"]; + constructor(fields) { + super(fields); + this.first = fields.first; + this.middle = fields.middle ?? this.middle; + this.last = fields.last; + this.name = fields.name; + this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; + } + get steps() { + return [ + this.first, + ...this.middle, + this.last + ]; + } + async invoke(input, options) { + const config = ensureConfig(options); + const runManager = await (await getCallbackManagerForConfig(config))?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, void 0, void 0, void 0, config?.runName); + delete config.runId; + let nextStepInput = input; + let finalOutput; + try { + const initialSteps = [this.first, ...this.middle]; + for (let i = 0; i < initialSteps.length; i += 1) nextStepInput = await raceWithSignal(initialSteps[i].invoke(nextStepInput, patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) })), config.signal); + if (config.signal?.aborted) throw getAbortSignalError(config.signal); + finalOutput = await this.last.invoke(nextStepInput, patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${this.steps.length}`) })); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict(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(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + let nextStepInputs = inputs; + try { + for (let i = 0; i < this.steps.length; i += 1) nextStepInputs = await raceWithSignal(this.steps[i].batch(nextStepInputs, runManagers.map((runManager, j) => { + const childRunManager = runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`); + return patchConfig(configList[j], { callbacks: childRunManager }); + }), batchOptions), configList[0]?.signal); + } catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(nextStepInputs, "output")))); + return nextStepInputs; + } + /** @internal */ + _concatOutputChunks(first, second) { + return this.last._concatOutputChunks(first, second); + } + async *_streamIterator(input, options) { + const callbackManager_ = await getCallbackManagerForConfig(options); + const { runId, ...otherOptions } = options ?? {}; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherOptions?.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(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:1`) })); + for (let i = 1; i < steps.length; i += 1) finalGenerator = await steps[i].transform(finalGenerator, patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) })); + for await (const chunk of finalGenerator) { + options?.signal?.throwIfAborted(); + yield chunk; + if (concatSupported) if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = void 0; + concatSupported = false; + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output")); + } + getGraph(config) { + const graph = new Graph(); + let currentLastNode = null; + this.steps.forEach((step, index) => { + const stepGraph = step.getGraph(config); + if (index !== 0) stepGraph.trimFirstNode(); + if (index !== 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], nameOrFields) { + let extra = {}; + if (typeof nameOrFields === "string") extra.name = nameOrFields; + else if (nameOrFields !== void 0) extra = nameOrFields; + return new RunnableSequence({ + ...extra, + first: _coerceToRunnable(first), + middle: runnables.slice(0, -1).map(_coerceToRunnable), + last: _coerceToRunnable(runnables[runnables.length - 1]) + }); + } +}; +/** +* A runnable that runs a mapping of runnables in parallel, +* and returns a mapping of their outputs. +* @example +* ```typescript +* const mapChain = RunnableMap.from({ +* joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe( +* new ChatAnthropic({}), +* ), +* poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe( +* new ChatAnthropic({}), +* ), +* }); +* const result = await mapChain.invoke({ topic: "bear" }); +* ``` +*/ +var RunnableMap = class RunnableMap extends Runnable { + static lc_name() { + return "RunnableMap"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + steps; + getStepsKeys() { + return Object.keys(this.steps); + } + constructor(fields) { + super(fields); + this.steps = {}; + for (const [key, value] of Object.entries(fields.steps)) this.steps[key] = _coerceToRunnable(value); + } + static from(steps) { + return new RunnableMap({ steps }); + } + async invoke(input, options) { + const config = ensureConfig(options); + const runManager = await (await getCallbackManagerForConfig(config))?.handleChainStart(this.toJSON(), { input }, config.runId, void 0, void 0, void 0, config?.runName); + delete config.runId; + const output = {}; + try { + const promises = Object.entries(this.steps).map(async ([key, runnable]) => { + output[key] = await runnable.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`map:key:${key}`) })); + }); + await raceWithSignal(Promise.all(promises), config.signal); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(output); + return output; + } + async *_transform(generator, runManager, options) { + const steps = { ...this.steps }; + const inputCopies = atee(generator, Object.keys(steps).length); + const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { + const gen = runnable.transform(inputCopies[i], patchConfig(options, { callbacks: runManager?.getChild(`map:key:${key}`) })); + return [key, gen.next().then((result) => ({ + key, + gen, + result + }))]; + })); + while (tasks.size) { + const { key, result, gen } = await raceWithSignal(Promise.race(tasks.values()), options?.signal); + tasks.delete(key); + if (!result.done) { + yield { [key]: result.value }; + tasks.set(key, gen.next().then((result) => ({ + key, + gen, + result + }))); + } + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +}; +/** +* A runnable that wraps a traced LangSmith function. +*/ +var RunnableTraceable = class RunnableTraceable extends Runnable { + lc_serializable = false; + lc_namespace = ["langchain_core", "runnables"]; + func; + constructor(fields) { + super(fields); + if (!isTraceableFunction(fields.func)) throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); + this.func = fields.func; + } + async invoke(input, options) { + const [config] = this._getOptionsList(options ?? {}, 1); + const callbacks = await getCallbackManagerForConfig(config); + return raceWithSignal(this.func(patchConfig(config, { callbacks }), input), config?.signal); + } + async *_streamIterator(input, options) { + const [config] = this._getOptionsList(options ?? {}, 1); + const result = await this.invoke(input, options); + if (isAsyncIterable(result)) { + for await (const item of result) { + config?.signal?.throwIfAborted(); + yield item; + } + return; + } + if (isIterator(result)) { + while (true) { + config?.signal?.throwIfAborted(); + const state = result.next(); + if (state.done) break; + yield state.value; + } + return; + } + yield result; + } + static from(func) { + return new RunnableTraceable({ func }); + } +}; +function assertNonTraceableFunction(func) { + if (isTraceableFunction(func)) throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); +} +/** +* A runnable that wraps an arbitrary function that takes a single argument. +* @example +* ```typescript +* import { RunnableLambda } from "@langchain/core/runnables"; +* +* const add = (input: { x: number; y: number }) => input.x + input.y; +* +* const multiply = (input: { value: number; multiplier: number }) => +* input.value * input.multiplier; +* +* // Create runnables for the functions +* const addLambda = RunnableLambda.from(add); +* const multiplyLambda = RunnableLambda.from(multiply); +* +* // Chain the lambdas for a mathematical operation +* const chainedLambda = addLambda.pipe((result) => +* multiplyLambda.invoke({ value: result, multiplier: 2 }) +* ); +* +* // Example invocation of the chainedLambda +* const result = await chainedLambda.invoke({ x: 2, y: 3 }); +* +* // Will log "10" (since (2 + 3) * 2 = 10) +* ``` +*/ +var RunnableLambda = class RunnableLambda extends Runnable { + static lc_name() { + return "RunnableLambda"; + } + lc_namespace = ["langchain_core", "runnables"]; + func; + constructor(fields) { + if (isTraceableFunction(fields.func)) return RunnableTraceable.from(fields.func); + super(fields); + assertNonTraceableFunction(fields.func); + this.func = fields.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 ?? 25) - 1 + }); + AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + let output = await this.func(input, { ...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 ?? 25) - 1 + }); + } else if (isAsyncIterable(output)) { + let finalOutput; + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = chunk; + } + } + output = finalOutput; + } else if (isIterableIterator(output)) { + let finalOutput; + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = chunk; + } + } + output = finalOutput; + } + resolve(output); + } catch (e) { + reject(e); + } + }); + }); + } + async invoke(input, options) { + return this._callWithConfig(this._invoke.bind(this), input, options); + } + async *_transform(generator, runManager, config) { + let finalChunk; + for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk; + else try { + finalChunk = this._concatOutputChunks(finalChunk, chunk); + } catch { + finalChunk = chunk; + } + const childConfig = patchConfig(config, { + callbacks: runManager?.getChild(), + recursionLimit: (config?.recursionLimit ?? 25) - 1 + }); + const output = await new Promise((resolve, reject) => { + AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + resolve(await this.func(finalChunk, { + ...childConfig, + config: childConfig + })); + } catch (e) { + reject(e); + } + }); + }); + if (output && Runnable.isRunnable(output)) { + if (config?.recursionLimit === 0) throw new Error("Recursion limit reached."); + const stream = await output.stream(finalChunk, childConfig); + for await (const chunk of stream) yield chunk; + } else if (isAsyncIterable(output)) for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + yield chunk; + } + else if (isIterableIterator(output)) for (const chunk of consumeIteratorInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + 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 config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +}; +/** +* A runnable that runs a mapping of runnables in parallel, +* and returns a mapping of their outputs. +* @example +* ```typescript +* import { +* RunnableLambda, +* RunnableParallel, +* } from "@langchain/core/runnables"; +* +* const addYears = (age: number): number => age + 5; +* const yearsToFifty = (age: number): number => 50 - age; +* const yearsToHundred = (age: number): number => 100 - age; +* +* const addYearsLambda = RunnableLambda.from(addYears); +* const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty); +* const milestoneHundredLambda = RunnableLambda.from(yearsToHundred); +* +* // Pipe will coerce objects into RunnableParallel by default, but we +* // explicitly instantiate one here to demonstrate +* const sequence = addYearsLambda.pipe( +* RunnableParallel.from({ +* years_to_fifty: milestoneFiftyLambda, +* years_to_hundred: milestoneHundredLambda, +* }) +* ); +* +* // Invoke the sequence with a single age input +* const res = await sequence.invoke(25); +* +* // { years_to_fifty: 20, years_to_hundred: 70 } +* ``` +*/ +var RunnableParallel = class extends RunnableMap {}; +/** +* A Runnable that can fallback to other Runnables if it fails. +* External APIs (e.g., APIs for a language model) may at times experience +* degraded performance or even downtime. +* +* In these cases, it can be useful to have a fallback Runnable that can be +* used in place of the original Runnable (e.g., fallback to another LLM provider). +* +* Fallbacks can be defined at the level of a single Runnable, or at the level +* of a chain of Runnables. Fallbacks are tried in order until one succeeds or +* all fail. +* +* While you can instantiate a `RunnableWithFallbacks` directly, it is usually +* more convenient to use the `withFallbacks` method on an existing Runnable. +* +* When streaming, fallbacks will only be called on failures during the initial +* stream creation. Errors that occur after a stream starts will not fallback +* to the next Runnable. +* +* @example +* ```typescript +* import { +* RunnableLambda, +* RunnableWithFallbacks, +* } from "@langchain/core/runnables"; +* +* const primaryOperation = (input: string): string => { +* if (input !== "safe") { +* throw new Error("Primary operation failed due to unsafe input"); +* } +* return `Processed: ${input}`; +* }; +* +* // Define a fallback operation that processes the input differently +* const fallbackOperation = (input: string): string => +* `Fallback processed: ${input}`; +* +* const primaryRunnable = RunnableLambda.from(primaryOperation); +* const fallbackRunnable = RunnableLambda.from(fallbackOperation); +* +* // Apply the fallback logic using the .withFallbacks() method +* const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]); +* +* // Alternatively, create a RunnableWithFallbacks instance manually +* const manualFallbackChain = new RunnableWithFallbacks({ +* runnable: primaryRunnable, +* fallbacks: [fallbackRunnable], +* }); +* +* // Example invocation using .withFallbacks() +* const res = await runnableWithFallback +* .invoke("unsafe input") +* .catch((error) => { +* console.error("Failed after all attempts:", error.message); +* }); +* +* // "Fallback processed: unsafe input" +* +* // Example invocation using manual instantiation +* const res = await manualFallbackChain +* .invoke("safe") +* .catch((error) => { +* console.error("Failed after all attempts:", error.message); +* }); +* +* // "Processed: safe" +* ``` +*/ +var RunnableWithFallbacks = class extends Runnable { + static lc_name() { + return "RunnableWithFallbacks"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + runnable; + fallbacks; + constructor(fields) { + super(fields); + this.runnable = fields.runnable; + this.fallbacks = fields.fallbacks; + } + *runnables() { + yield this.runnable; + for (const fallback of this.fallbacks) yield fallback; + } + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const { runId, ...otherConfigFields } = config; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); + const childConfig = patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); + return await AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { + let firstError; + for (const runnable of this.runnables()) { + config?.signal?.throwIfAborted(); + try { + const output = await runnable.invoke(input, childConfig); + await runManager?.handleChainEnd(_coerceToDict(output, "output")); + return output; + } catch (e) { + if (firstError === void 0) firstError = e; + } + } + if (firstError === void 0) throw new Error("No error stored at end of fallback."); + await runManager?.handleChainError(firstError); + throw firstError; + }); + } + async *_streamIterator(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const { runId, ...otherConfigFields } = config; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); + let firstError; + let stream; + for (const runnable of this.runnables()) { + config?.signal?.throwIfAborted(); + const childConfig = patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); + try { + stream = consumeAsyncIterableInContext(childConfig, await runnable.stream(input, childConfig)); + break; + } catch (e) { + if (firstError === void 0) firstError = e; + } + } + if (stream === void 0) { + const error = firstError ?? /* @__PURE__ */ new Error("No error stored at end of fallback."); + await runManager?.handleChainError(error); + throw error; + } + let output; + try { + for await (const chunk of stream) { + yield chunk; + try { + output = output === void 0 ? output : this._concatOutputChunks(output, chunk); + } catch { + output = void 0; + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict(output, "output")); + } + 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) => getCallbackManagerForConfig(config))); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + let firstError; + for (const runnable of this.runnables()) { + configList[0].signal?.throwIfAborted(); + try { + const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => patchConfig(configList[j], { callbacks: runManager?.getChild() })), batchOptions); + await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(outputs[i], "output")))); + return outputs; + } catch (e) { + if (firstError === void 0) firstError = e; + } + } + if (!firstError) throw new Error("No error stored at end of fallbacks."); + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); + throw firstError; + } +}; +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.\nInstead got an unsupported type.`); +} +/** +* A runnable that assigns key-value pairs to inputs of type `Record`. +* @example +* ```typescript +* import { +* RunnableAssign, +* RunnableLambda, +* RunnableParallel, +* } from "@langchain/core/runnables"; +* +* const calculateAge = (x: { birthYear: number }): { age: number } => { +* const currentYear = new Date().getFullYear(); +* return { age: currentYear - x.birthYear }; +* }; +* +* const createGreeting = (x: { name: string }): { greeting: string } => { +* return { greeting: `Hello, ${x.name}!` }; +* }; +* +* const mapper = RunnableParallel.from({ +* age_step: RunnableLambda.from(calculateAge), +* greeting_step: RunnableLambda.from(createGreeting), +* }); +* +* const runnableAssign = new RunnableAssign({ mapper }); +* +* const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 }); +* +* // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } } +* ``` +*/ +var RunnableAssign = class extends Runnable { + static lc_name() { + return "RunnableAssign"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + mapper; + constructor(fields) { + if (fields instanceof RunnableMap) fields = { mapper: fields }; + super(fields); + this.mapper = fields.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 config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +}; +/** +* A runnable that assigns key-value pairs to inputs of type `Record`. +* Useful for streaming, can be automatically created and chained by calling `runnable.pick();`. +* @example +* ```typescript +* import { RunnablePick } from "@langchain/core/runnables"; +* +* const inputData = { +* name: "John", +* age: 30, +* city: "New York", +* country: "USA", +* email: "john.doe@example.com", +* phone: "+1234567890", +* }; +* +* const basicInfoRunnable = new RunnablePick(["name", "city"]); +* +* // Example invocation +* const res = await basicInfoRunnable.invoke(inputData); +* +* // { name: 'John', city: 'New York' } +* ``` +*/ +var RunnablePick = class extends Runnable { + static lc_name() { + return "RunnablePick"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + keys; + constructor(fields) { + if (typeof fields === "string" || Array.isArray(fields)) fields = { keys: fields }; + super(fields); + this.keys = fields.keys; + } + async _pick(input) { + if (typeof this.keys === "string") return input[this.keys]; + else { + const picked = this.keys.map((key) => [key, input[key]]).filter((v) => v[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 config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +}; +var RunnableToolLike = class extends RunnableBinding { + name; + description; + schema; + constructor(fields) { + const sequence = RunnableSequence.from([RunnableLambda.from(async (input) => { + let toolInput; + if (_isToolCall(input)) try { + toolInput = await interopParseAsync(this.schema, input.args); + } catch { + throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); + } + else toolInput = input; + return toolInput; + }).withConfig({ runName: `${fields.name}:parse_input` }), fields.bound]).withConfig({ runName: fields.name }); + super({ + bound: sequence, + config: fields.config ?? {} + }); + this.name = fields.name; + this.description = fields.description; + this.schema = fields.schema; + } + static lc_name() { + return "RunnableToolLike"; + } +}; +/** +* Given a runnable and a Zod schema, convert the runnable to a tool. +* +* @template RunInput The input type for the runnable. +* @template RunOutput The output type for the runnable. +* +* @param {Runnable} runnable The runnable to convert to a tool. +* @param fields +* @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. +* @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. +* @param {InteropZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. +* @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. +*/ +function convertRunnableToTool(runnable, fields) { + const name = fields.name ?? runnable.getName(); + const description = fields.description ?? getSchemaDescription(fields.schema); + if (isSimpleStringZodSchema(fields.schema)) return new RunnableToolLike({ + name, + description, + schema: objectType({ input: stringType() }).transform((input) => input.input), + bound: runnable + }); + return new RunnableToolLike({ + name, + description, + schema: fields.schema, + bound: runnable + }); +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/transformers.js +var _isMessageType = (msg, types) => { + const typesAsStrings = [...new Set(types?.map((t) => { + if (typeof t === "string") return t; + const instantiatedMsgClass = new t({}); + if (!("getType" in instantiatedMsgClass) || typeof instantiatedMsgClass.getType !== "function") throw new Error("Invalid type provided."); + return instantiatedMsgClass.getType(); + }))]; + const msgType = msg.getType(); + return typesAsStrings.some((t) => t === msgType); +}; +function filterMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) return _filterMessages(messagesOrOptions, options); + return RunnableLambda.from((input) => { + return _filterMessages(input, messagesOrOptions); + }); +} +function _filterMessages(messages, options = {}) { + const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds } = options; + const filtered = []; + for (const msg of messages) { + if (excludeNames && msg.name && excludeNames.includes(msg.name)) continue; + else if (excludeTypes && _isMessageType(msg, excludeTypes)) continue; + else if (excludeIds && msg.id && excludeIds.includes(msg.id)) continue; + if (!(includeTypes || includeIds || includeNames)) filtered.push(msg); + else if (includeNames && msg.name && includeNames.some((iName) => iName === msg.name)) filtered.push(msg); + else if (includeTypes && _isMessageType(msg, includeTypes)) filtered.push(msg); + else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) filtered.push(msg); + } + return filtered; +} +function mergeMessageRuns(messages) { + if (Array.isArray(messages)) return _mergeMessageRuns(messages); + return RunnableLambda.from(_mergeMessageRuns); +} +function _mergeMessageRuns(messages) { + if (!messages.length) return []; + const merged = []; + for (const msg of messages) { + const curr = msg; + const last = merged.pop(); + if (!last) merged.push(curr); + else if (curr.getType() === "tool" || !(curr.getType() === last.getType())) merged.push(last, curr); + else { + const lastChunk = convertToChunk(last); + const currChunk = convertToChunk(curr); + const mergedChunks = lastChunk.concat(currChunk); + if (typeof lastChunk.content === "string" && typeof currChunk.content === "string") mergedChunks.content = `${lastChunk.content}\n${currChunk.content}`; + merged.push(_chunkToMsg(mergedChunks)); + } + } + return merged; +} +function trimMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) { + const messages = messagesOrOptions; + if (!options) throw new Error("Options parameter is required when providing messages."); + return _trimMessagesHelper(messages, options); + } else { + const trimmerOptions = messagesOrOptions; + return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ runName: "trim_messages" }); + } +} +async function _trimMessagesHelper(messages, options) { + const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter } = options; + if (startOn && strategy === "first") throw new Error("`startOn` should only be specified if `strategy` is 'last'."); + if (includeSystem && strategy === "first") throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); + let listTokenCounter; + if ("getNumTokens" in tokenCounter) listTokenCounter = async (msgs) => { + return (await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content)))).reduce((sum, count) => sum + count, 0); + }; + else listTokenCounter = async (msgs) => tokenCounter(msgs); + let textSplitterFunc = defaultTextSplitter; + if (textSplitter) if ("splitText" in textSplitter) textSplitterFunc = textSplitter.splitText.bind(textSplitter); + else textSplitterFunc = async (text) => textSplitter(text); + if (strategy === "first") return _firstMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + partialStrategy: allowPartial ? "first" : void 0, + endOn + }); + else if (strategy === "last") return _lastMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + allowPartial, + includeSystem, + startOn, + endOn + }); + else throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); +} +async function _firstMaxTokens(messages, options) { + const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; + let messagesCopy = [...messages]; + let idx = 0; + for (let i = 0; i < messagesCopy.length; i += 1) if (await tokenCounter(i > 0 ? messagesCopy.slice(0, -i) : messagesCopy) <= maxTokens) { + idx = messagesCopy.length - i; + break; + } + if (idx < messagesCopy.length && partialStrategy) { + let includedPartial = false; + if (Array.isArray(messagesCopy[idx].content)) { + const excluded = messagesCopy[idx]; + if (typeof excluded.content === "string") throw new Error("Expected content to be an array."); + const numBlock = excluded.content.length; + const reversedContent = partialStrategy === "last" ? [...excluded.content].reverse() : excluded.content; + for (let i = 1; i <= numBlock; i += 1) { + const partialContent = partialStrategy === "first" ? reversedContent.slice(0, i) : reversedContent.slice(-i); + const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + const updatedMessage = _switchTypeToMessage(excluded.getType(), { + ...fields, + content: partialContent + }); + const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; + if (await tokenCounter(slicedMessages) <= maxTokens) { + messagesCopy = slicedMessages; + idx += 1; + includedPartial = true; + } else break; + } + if (includedPartial && partialStrategy === "last") excluded.content = [...reversedContent].reverse(); + } + if (!includedPartial) { + const excluded = messagesCopy[idx]; + let text; + if (Array.isArray(excluded.content) && excluded.content.some((block) => typeof block === "string" || block.type === "text")) text = excluded.content.find((block) => block.type === "text" && block.text)?.text; + else if (typeof excluded.content === "string") text = excluded.content; + if (text) { + const splitTexts = await textSplitter(text); + const numSplits = splitTexts.length; + if (partialStrategy === "last") splitTexts.reverse(); + for (let _ = 0; _ < numSplits - 1; _ += 1) { + splitTexts.pop(); + excluded.content = splitTexts.join(""); + if (await tokenCounter([...messagesCopy.slice(0, idx), excluded]) <= maxTokens) { + if (partialStrategy === "last") excluded.content = [...splitTexts].reverse().join(""); + messagesCopy = [...messagesCopy.slice(0, idx), excluded]; + idx += 1; + break; + } + } + } + } + } + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) idx -= 1; + } + return messagesCopy.slice(0, idx); +} +async function _lastMaxTokens(messages, options) { + const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options; + let messagesCopy = messages.map((message) => { + const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); + }); + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (messagesCopy.length > 0 && !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) messagesCopy = messagesCopy.slice(0, -1); + } + const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; + let reversed_ = swappedSystem ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) : messagesCopy.reverse(); + reversed_ = await _firstMaxTokens(reversed_, { + ...rest, + partialStrategy: allowPartial ? "last" : void 0, + endOn: startOn + }); + if (swappedSystem) return [reversed_[0], ...reversed_.slice(1).reverse()]; + else return reversed_.reverse(); +} +var _MSG_CHUNK_MAP = { + human: { + message: HumanMessage, + messageChunk: HumanMessageChunk + }, + ai: { + message: AIMessage, + messageChunk: AIMessageChunk + }, + system: { + message: SystemMessage, + messageChunk: SystemMessageChunk + }, + developer: { + message: SystemMessage, + messageChunk: SystemMessageChunk + }, + tool: { + message: ToolMessage, + messageChunk: ToolMessageChunk + }, + function: { + message: FunctionMessage, + messageChunk: FunctionMessageChunk + }, + generic: { + message: ChatMessage, + messageChunk: ChatMessageChunk + }, + remove: { + message: RemoveMessage, + messageChunk: RemoveMessage + } +}; +function _switchTypeToMessage(messageType, fields, returnChunk) { + let chunk; + let msg; + switch (messageType) { + case "human": + if (returnChunk) chunk = new HumanMessageChunk(fields); + else msg = new HumanMessage(fields); + break; + case "ai": + if (returnChunk) { + let aiChunkFields = { ...fields }; + if ("tool_calls" in aiChunkFields) aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: void 0, + args: JSON.stringify(tc.args) + })) + }; + chunk = new AIMessageChunk(aiChunkFields); + } else msg = new AIMessage(fields); + break; + case "system": + if (returnChunk) chunk = new SystemMessageChunk(fields); + else msg = new SystemMessage(fields); + break; + case "developer": + if (returnChunk) chunk = new SystemMessageChunk({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer" + } + }); + else msg = new SystemMessage({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer" + } + }); + break; + case "tool": + if ("tool_call_id" in fields) if (returnChunk) chunk = new ToolMessageChunk(fields); + else msg = new ToolMessage(fields); + else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); + break; + case "function": + if (returnChunk) chunk = new FunctionMessageChunk(fields); + else { + if (!fields.name) throw new Error("FunctionMessage must have a 'name' field"); + msg = new FunctionMessage(fields); + } + break; + case "generic": + if ("role" in fields) if (returnChunk) chunk = new ChatMessageChunk(fields); + else msg = new ChatMessage(fields); + else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); + break; + default: throw new Error(`Unrecognized message type ${messageType}`); + } + if (returnChunk && chunk) return chunk; + if (msg) return msg; + throw new Error(`Unrecognized message type ${messageType}`); +} +function _chunkToMsg(chunk) { + const chunkType = chunk.getType(); + let msg; + const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); + if (chunkType in _MSG_CHUNK_MAP) msg = _switchTypeToMessage(chunkType, fields); + if (!msg) throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); + return msg; +} +/** +* The default text splitter function that splits text by newlines. +* +* @param {string} text +* @returns A promise that resolves to an array of strings split by newlines. +*/ +function defaultTextSplitter(text) { + const splits = text.split("\n"); + return Promise.resolve([...splits.slice(0, -1).map((s) => `${s}\n`), splits[splits.length - 1]]); +} +//#endregion +//#region node_modules/@langchain/core/dist/messages/content/tools.js +var KNOWN_BLOCK_TYPES$2 = [ + "tool_call", + "tool_call_chunk", + "invalid_tool_call", + "server_tool_call", + "server_tool_call_chunk", + "server_tool_call_result" +]; +//#endregion +//#region node_modules/@langchain/core/dist/messages/content/multimodal.js +var KNOWN_BLOCK_TYPES$1 = [ + "image", + "video", + "audio", + "text-plain", + "file" +]; +//#endregion +//#region node_modules/@langchain/core/dist/messages/content/index.js +var KNOWN_BLOCK_TYPES = [ + "text", + "reasoning", + ...KNOWN_BLOCK_TYPES$2, + ...KNOWN_BLOCK_TYPES$1 +]; +//#endregion +//#region node_modules/@langchain/core/dist/messages/index.js +var messages_exports = /* @__PURE__ */ __exportAll({ + AIMessage: () => AIMessage, + AIMessageChunk: () => AIMessageChunk, + BaseMessage: () => BaseMessage, + BaseMessageChunk: () => BaseMessageChunk, + ChatMessage: () => ChatMessage, + ChatMessageChunk: () => ChatMessageChunk, + DEFAULT_MERGE_IGNORE_KEYS: () => DEFAULT_MERGE_IGNORE_KEYS, + FunctionMessage: () => FunctionMessage, + FunctionMessageChunk: () => FunctionMessageChunk, + HumanMessage: () => HumanMessage, + HumanMessageChunk: () => HumanMessageChunk, + KNOWN_BLOCK_TYPES: () => KNOWN_BLOCK_TYPES, + RemoveMessage: () => RemoveMessage, + SystemMessage: () => SystemMessage, + SystemMessageChunk: () => SystemMessageChunk, + ToolMessage: () => ToolMessage, + ToolMessageChunk: () => ToolMessageChunk, + _isMessageFieldWithRole: () => _isMessageFieldWithRole, + _mergeDicts: () => _mergeDicts, + _mergeLists: () => _mergeLists, + _mergeObj: () => _mergeObj, + _mergeStatus: () => _mergeStatus, + coerceMessageLikeToMessage: () => coerceMessageLikeToMessage, + collapseToolCallChunks: () => collapseToolCallChunks, + convertToChunk: () => convertToChunk, + convertToOpenAIImageBlock: () => convertToOpenAIImageBlock, + convertToProviderContentBlock: () => convertToProviderContentBlock, + defaultTextSplitter: () => defaultTextSplitter, + defaultToolCallParser: () => defaultToolCallParser, + filterMessages: () => filterMessages, + getBufferString: () => getBufferString, + iife: () => iife$2, + isAIMessage: () => isAIMessage, + isAIMessageChunk: () => isAIMessageChunk, + isBase64ContentBlock: () => isBase64ContentBlock, + isBaseMessage: () => isBaseMessage, + isBaseMessageChunk: () => isBaseMessageChunk, + isChatMessage: () => isChatMessage, + isChatMessageChunk: () => isChatMessageChunk, + isDataContentBlock: () => isDataContentBlock, + isDirectToolOutput: () => isDirectToolOutput, + isFunctionMessage: () => isFunctionMessage, + isFunctionMessageChunk: () => isFunctionMessageChunk, + isHumanMessage: () => isHumanMessage, + isHumanMessageChunk: () => isHumanMessageChunk, + isIDContentBlock: () => isIDContentBlock, + isMessage: () => isMessage, + isOpenAIToolCallArray: () => isOpenAIToolCallArray, + isPlainTextContentBlock: () => isPlainTextContentBlock, + isSystemMessage: () => isSystemMessage, + isSystemMessageChunk: () => isSystemMessageChunk, + isToolMessage: () => isToolMessage, + isToolMessageChunk: () => isToolMessageChunk, + isURLContentBlock: () => isURLContentBlock, + mapChatMessagesToStoredMessages: () => mapChatMessagesToStoredMessages, + mapStoredMessageToChatMessage: () => mapStoredMessageToChatMessage, + mapStoredMessagesToChatMessages: () => mapStoredMessagesToChatMessages, + mergeContent: () => mergeContent, + mergeMessageRuns: () => mergeMessageRuns, + mergeResponseMetadata: () => mergeResponseMetadata, + mergeUsageMetadata: () => mergeUsageMetadata, + parseBase64DataUrl: () => parseBase64DataUrl, + parseMimeType: () => parseMimeType, + trimMessages: () => trimMessages +}); +//#endregion +//#region node_modules/@langchain/core/dist/utils/js-sha256/hash.js +/** +* [js-sha256]{@link https://github.com/emn178/js-sha256} +* +* @version 0.11.1 +* @author Chen, Yi-Cyuan [emn178@gmail.com] +* @copyright Chen, Yi-Cyuan 2014-2025 +* @license MIT +*/ +var HEX_CHARS = "0123456789abcdef".split(""); +var EXTRA = [ + -2147483648, + 8388608, + 32768, + 128 +]; +var SHIFT = [ + 24, + 16, + 8, + 0 +]; +var K = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]; +var blocks = []; +function Sha256(is224, 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 + ]; + if (is224) { + this.h0 = 3238371032; + this.h1 = 914150663; + this.h2 = 812702999; + this.h3 = 4144912697; + this.h4 = 4290775857; + this.h5 = 1750603025; + this.h6 = 1694076839; + this.h7 = 3204075428; + } else { + this.h0 = 1779033703; + this.h1 = 3144134277; + this.h2 = 1013904242; + this.h3 = 2773480762; + this.h4 = 1359893119; + this.h5 = 2600822924; + this.h6 = 528734635; + this.h7 = 1541459225; + } + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + this.is224 = is224; +} +Sha256.prototype.update = function(message) { + if (this.finalized) return; + var notString, type = typeof message; + if (type !== "string") { + if (type === "object") { + if (message === null) throw new Error(ERROR); + else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) message = new Uint8Array(message); + else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) throw new Error(ERROR); + } + } else throw new Error(ERROR); + notString = true; + } + var code, index = 0, i, length = message.length, blocks = this.blocks; + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks[0] = this.block; + this.block = 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; + } + if (notString) for (i = this.start; index < length && i < 64; ++index) blocks[i >>> 2] |= message[index] << SHIFT[i++ & 3]; + else for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 128) blocks[i >>> 2] |= code << SHIFT[i++ & 3]; + else if (code < 2048) { + blocks[i >>> 2] |= (192 | code >>> 6) << SHIFT[i++ & 3]; + blocks[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else if (code < 55296 || code >= 57344) { + blocks[i >>> 2] |= (224 | code >>> 12) << SHIFT[i++ & 3]; + blocks[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; + blocks[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else { + code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); + blocks[i >>> 2] |= (240 | code >>> 18) << SHIFT[i++ & 3]; + blocks[i >>> 2] |= (128 | code >>> 12 & 63) << SHIFT[i++ & 3]; + blocks[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; + blocks[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } else this.start = i; + } + if (this.bytes > 4294967295) { + this.hBytes += this.bytes / 4294967296 << 0; + this.bytes = this.bytes % 4294967296; + } + return this; +}; +Sha256.prototype.finalize = function() { + if (this.finalized) return; + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex; + blocks[16] = this.block; + blocks[i >>> 2] |= EXTRA[i & 3]; + this.block = blocks[16]; + if (i >= 56) { + if (!this.hashed) this.hash(); + blocks[0] = this.block; + 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; + } + blocks[14] = this.hBytes << 3 | this.bytes >>> 29; + blocks[15] = this.bytes << 3; + this.hash(); +}; +Sha256.prototype.hash = function() { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; + for (j = 16; j < 64; ++j) { + t1 = blocks[j - 15]; + s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3; + t1 = blocks[j - 2]; + s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; + blocks[j] = blocks[j - 16] + s0 + blocks[j - 7] + s1 << 0; + } + bc = b & c; + for (j = 0; j < 64; j += 4) { + if (this.first) { + if (this.is224) { + ab = 300032; + t1 = blocks[0] - 1413257819; + h = t1 - 150054599 << 0; + d = t1 + 24177077 << 0; + } else { + ab = 704751109; + t1 = blocks[0] - 210244248; + h = t1 - 1521486534 << 0; + d = t1 + 143694565 << 0; + } + this.first = false; + } else { + s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); + s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); + ab = a & b; + maj = ab ^ a & c ^ bc; + ch = e & f ^ ~e & g; + t1 = h + s1 + ch + K[j] + blocks[j]; + t2 = s0 + maj; + h = d + t1 << 0; + d = t1 + t2 << 0; + } + s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10); + s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7); + da = d & a; + maj = da ^ d & b ^ ab; + ch = g & h ^ ~g & e; + t1 = f + s1 + ch + K[j + 1] + blocks[j + 1]; + t2 = s0 + maj; + g = c + t1 << 0; + c = t1 + t2 << 0; + s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10); + s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7); + cd = c & d; + maj = cd ^ c & a ^ da; + ch = f & g ^ ~f & h; + t1 = e + s1 + ch + K[j + 2] + blocks[j + 2]; + t2 = s0 + maj; + f = b + t1 << 0; + b = t1 + t2 << 0; + s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10); + s1 = (f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7); + bc = b & c; + maj = bc ^ b & d ^ cd; + ch = f & g ^ ~f & h; + t1 = e + s1 + ch + K[j + 3] + blocks[j + 3]; + t2 = s0 + maj; + e = a + t1 << 0; + a = t1 + t2 << 0; + this.chromeBugWorkAround = true; + } + this.h0 = this.h0 + a << 0; + this.h1 = this.h1 + b << 0; + this.h2 = this.h2 + c << 0; + this.h3 = this.h3 + d << 0; + this.h4 = this.h4 + e << 0; + this.h5 = this.h5 + f << 0; + this.h6 = this.h6 + g << 0; + this.h7 = this.h7 + h << 0; +}; +Sha256.prototype.hex = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var hex = 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] + HEX_CHARS[h5 >>> 28 & 15] + HEX_CHARS[h5 >>> 24 & 15] + HEX_CHARS[h5 >>> 20 & 15] + HEX_CHARS[h5 >>> 16 & 15] + HEX_CHARS[h5 >>> 12 & 15] + HEX_CHARS[h5 >>> 8 & 15] + HEX_CHARS[h5 >>> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >>> 28 & 15] + HEX_CHARS[h6 >>> 24 & 15] + HEX_CHARS[h6 >>> 20 & 15] + HEX_CHARS[h6 >>> 16 & 15] + HEX_CHARS[h6 >>> 12 & 15] + HEX_CHARS[h6 >>> 8 & 15] + HEX_CHARS[h6 >>> 4 & 15] + HEX_CHARS[h6 & 15]; + if (!this.is224) hex += HEX_CHARS[h7 >>> 28 & 15] + HEX_CHARS[h7 >>> 24 & 15] + HEX_CHARS[h7 >>> 20 & 15] + HEX_CHARS[h7 >>> 16 & 15] + HEX_CHARS[h7 >>> 12 & 15] + HEX_CHARS[h7 >>> 8 & 15] + HEX_CHARS[h7 >>> 4 & 15] + HEX_CHARS[h7 & 15]; + return hex; +}; +Sha256.prototype.toString = Sha256.prototype.hex; +Sha256.prototype.digest = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var arr = [ + 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, + h5 >>> 24 & 255, + h5 >>> 16 & 255, + h5 >>> 8 & 255, + h5 & 255, + h6 >>> 24 & 255, + h6 >>> 16 & 255, + h6 >>> 8 & 255, + h6 & 255 + ]; + if (!this.is224) arr.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255); + return arr; +}; +Sha256.prototype.array = Sha256.prototype.digest; +Sha256.prototype.arrayBuffer = function() { + this.finalize(); + var buffer = /* @__PURE__ */ new ArrayBuffer(this.is224 ? 28 : 32); + 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); + dataView.setUint32(20, this.h5); + dataView.setUint32(24, this.h6); + if (!this.is224) dataView.setUint32(28, this.h7); + return buffer; +}; +var sha256 = (...strings) => { + return new Sha256(false, true).update(strings.join("")).hex(); +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/hash.js +var hash_exports = /* @__PURE__ */ __exportAll({ sha256: () => sha256 }); +//#endregion +//#region node_modules/@langchain/core/dist/caches/index.js +var caches_exports = /* @__PURE__ */ __exportAll({ + BaseCache: () => BaseCache, + InMemoryCache: () => InMemoryCache, + defaultHashKeyEncoder: () => defaultHashKeyEncoder, + deserializeStoredGeneration: () => deserializeStoredGeneration, + serializeGeneration: () => serializeGeneration +}); +var defaultHashKeyEncoder = (...strings) => sha256(strings.join("_")); +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; +} +/** +* Base class for all caches. All caches should extend this class. +*/ +var BaseCache = class { + keyEncoder = defaultHashKeyEncoder; + /** + * Sets a custom key encoder function for the cache. + * This function should take a prompt and an LLM key and return a string + * that will be used as the cache key. + * @param keyEncoderFn The custom key encoder function. + */ + makeDefaultKeyEncoder(keyEncoderFn) { + this.keyEncoder = keyEncoderFn; + } +}; +var GLOBAL_MAP = /* @__PURE__ */ new Map(); +/** +* A cache for storing LLM generations that stores data in memory. +*/ +var InMemoryCache = class InMemoryCache extends BaseCache { + cache; + constructor(map) { + super(); + this.cache = map ?? /* @__PURE__ */ new Map(); + } + /** + * Retrieves data from the cache using a prompt and an LLM key. If the + * data is not found, it returns null. + * @param prompt The prompt used to find the data. + * @param llmKey The LLM key used to find the data. + * @returns The data corresponding to the prompt and LLM key, or null if not found. + */ + lookup(prompt, llmKey) { + return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null); + } + /** + * Updates the cache with new data using a prompt and an LLM key. + * @param prompt The prompt used to store the data. + * @param llmKey The LLM key used to store the data. + * @param value The data to be stored. + */ + async update(prompt, llmKey, value) { + this.cache.set(this.keyEncoder(prompt, llmKey), value); + } + /** + * Returns a global instance of InMemoryCache using a predefined global + * map as the initial cache. + * @returns A global instance of InMemoryCache. + */ + static global() { + return new InMemoryCache(GLOBAL_MAP); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/prompt_values.js +var prompt_values_exports = /* @__PURE__ */ __exportAll({ + BasePromptValue: () => BasePromptValue, + ChatPromptValue: () => ChatPromptValue, + ImagePromptValue: () => ImagePromptValue, + StringPromptValue: () => StringPromptValue +}); +/** +* Base PromptValue class. All prompt values should extend this class. +*/ +var BasePromptValue = class extends Serializable {}; +/** +* Represents a prompt value as a string. It extends the BasePromptValue +* class and overrides the toString and toChatMessages methods. +*/ +var StringPromptValue = class extends BasePromptValue { + static lc_name() { + return "StringPromptValue"; + } + lc_namespace = ["langchain_core", "prompt_values"]; + lc_serializable = true; + value; + constructor(value) { + super({ value }); + this.value = value; + } + toString() { + return this.value; + } + toChatMessages() { + return [new HumanMessage(this.value)]; + } +}; +/** +* Class that represents a chat prompt value. It extends the +* BasePromptValue and includes an array of BaseMessage instances. +*/ +var ChatPromptValue = class extends BasePromptValue { + lc_namespace = ["langchain_core", "prompt_values"]; + lc_serializable = true; + static lc_name() { + return "ChatPromptValue"; + } + messages; + constructor(fields) { + if (Array.isArray(fields)) fields = { messages: fields }; + super(fields); + this.messages = fields.messages; + } + toString() { + return getBufferString(this.messages); + } + toChatMessages() { + return this.messages; + } +}; +/** +* Class that represents an image prompt value. It extends the +* BasePromptValue and includes an ImageURL instance. +*/ +var ImagePromptValue = class extends BasePromptValue { + lc_namespace = ["langchain_core", "prompt_values"]; + lc_serializable = true; + static lc_name() { + return "ImagePromptValue"; + } + imageUrl; + /** @ignore */ + value; + constructor(fields) { + if (!("imageUrl" in fields)) fields = { imageUrl: fields }; + super(fields); + this.imageUrl = fields.imageUrl; + } + toString() { + return this.imageUrl.url; + } + toChatMessages() { + return [new HumanMessage({ content: [{ + type: "image_url", + image_url: { + detail: this.imageUrl.detail, + url: this.imageUrl.url + } + }] })]; + } +}; +//#endregion +//#region node_modules/js-tiktoken/dist/chunk-VL2OQCWN.js +var import_base64_js = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => { + exports.toByteArray = toByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; + function getLens(b64) { + var len = b64.length; + if (len % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4"); + var validLen = b64.indexOf("="); + if (validLen === -1) validLen = len; + var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; + return [validLen, 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 len = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i; + for (i = 0; i < len; i += 4) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + return arr; + } +})))(), 1); +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { + enumerable: true, + configurable: true, + writable: true, + value +}) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +function bytePairMerge(piece, ranks) { + let parts = Array.from({ length: piece.length }, (_, i) => ({ + start: i, + end: i + 1 + })); + while (parts.length > 1) { + let minRank = null; + for (let i = 0; i < parts.length - 1; i++) { + const slice = piece.slice(parts[i].start, parts[i + 1].end); + const rank = ranks.get(slice.join(",")); + if (rank == null) continue; + if (minRank == null || rank < minRank[0]) minRank = [rank, i]; + } + if (minRank != null) { + const i = minRank[1]; + parts[i] = { + start: parts[i].start, + end: parts[i + 1].end + }; + parts.splice(i + 1, 1); + } else break; + } + return parts; +} +function bytePairEncode(piece, ranks) { + if (piece.length === 1) return [ranks.get(piece.join(","))]; + return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); +} +function escapeRegex(str) { + return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); +} +var _Tiktoken = class { + /** @internal */ + specialTokens; + /** @internal */ + inverseSpecialTokens; + /** @internal */ + patStr; + /** @internal */ + textEncoder = new TextEncoder(); + /** @internal */ + textDecoder = new TextDecoder("utf-8"); + /** @internal */ + rankMap = /* @__PURE__ */ new Map(); + /** @internal */ + textMap = /* @__PURE__ */ new Map(); + constructor(ranks, extendedSpecialTokens) { + this.patStr = ranks.pat_str; + const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { + const [_, offsetStr, ...tokens] = x.split(" "); + const offset = Number.parseInt(offsetStr, 10); + tokens.forEach((token, i) => memo[token] = offset + i); + return memo; + }, {}); + for (const [token, rank] of Object.entries(uncompressed)) { + const bytes = import_base64_js.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((x) => !allowedSpecialSet.has(x)) : 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 i2 = 0; i2 < tokens.length; ++i2) { + const token = tokens[i2]; + const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; + if (bytes != null) { + res.push(bytes); + length += bytes.length; + } + } + const mergedArray = new Uint8Array(length); + let i = 0; + for (const bytes of res) { + mergedArray.set(bytes, i); + i += bytes.length; + } + return this.textDecoder.decode(mergedArray); + } +}; +var Tiktoken = _Tiktoken; +__publicField(Tiktoken, "specialTokenRegex", (tokens) => { + return new RegExp(tokens.map((i) => escapeRegex(i)).join("|"), "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": + case "gpt-4-turbo-2024-04-09": + case "gpt-4-turbo-preview": + case "gpt-4-0125-preview": + case "text-embedding-ada-002": + case "text-embedding-3-small": + case "text-embedding-3-large": return "cl100k_base"; + case "gpt-4o": + case "gpt-4o-2024-05-13": + case "gpt-4o-2024-08-06": + case "gpt-4o-2024-11-20": + case "gpt-4o-mini-2024-07-18": + case "gpt-4o-mini": + case "gpt-4o-search-preview": + case "gpt-4o-search-preview-2025-03-11": + case "gpt-4o-mini-search-preview": + case "gpt-4o-mini-search-preview-2025-03-11": + case "gpt-4o-audio-preview": + case "gpt-4o-audio-preview-2024-12-17": + case "gpt-4o-audio-preview-2024-10-01": + case "gpt-4o-mini-audio-preview": + case "gpt-4o-mini-audio-preview-2024-12-17": + case "o1": + case "o1-2024-12-17": + case "o1-mini": + case "o1-mini-2024-09-12": + case "o1-preview": + case "o1-preview-2024-09-12": + case "o1-pro": + case "o1-pro-2025-03-19": + case "o3": + case "o3-2025-04-16": + case "o3-mini": + case "o3-mini-2025-01-31": + case "o4-mini": + case "o4-mini-2025-04-16": + case "chatgpt-4o-latest": + case "gpt-4o-realtime": + case "gpt-4o-realtime-preview-2024-10-01": + case "gpt-4o-realtime-preview-2024-12-17": + case "gpt-4o-mini-realtime-preview": + case "gpt-4o-mini-realtime-preview-2024-12-17": + case "gpt-4.1": + case "gpt-4.1-2025-04-14": + case "gpt-4.1-mini": + case "gpt-4.1-mini-2025-04-14": + case "gpt-4.1-nano": + case "gpt-4.1-nano-2025-04-14": + case "gpt-4.5-preview": + case "gpt-4.5-preview-2025-02-27": + case "gpt-5": + case "gpt-5-2025-08-07": + case "gpt-5-nano": + case "gpt-5-nano-2025-08-07": + case "gpt-5-mini": + case "gpt-5-mini-2025-08-07": + case "gpt-5-chat-latest": return "o200k_base"; + default: throw new Error("Unknown model"); + } +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/tiktoken.js +var tiktoken_exports = /* @__PURE__ */ __exportAll({ + encodingForModel: () => encodingForModel, + getEncoding: () => getEncoding +}); +var cache = {}; +var caller = /* @__PURE__ */ new AsyncCaller({}); +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((e) => { + delete cache[encoding]; + throw e; + }); + return await cache[encoding]; +} +async function encodingForModel(model) { + return getEncoding(getEncodingNameForModel(model)); +} +//#endregion +//#region node_modules/@langchain/core/dist/language_models/base.js +var base_exports = /* @__PURE__ */ __exportAll({ + BaseLangChain: () => BaseLangChain, + BaseLanguageModel: () => BaseLanguageModel, + calculateMaxTokens: () => calculateMaxTokens, + getEmbeddingContextSize: () => getEmbeddingContextSize, + getModelContextSize: () => getModelContextSize, + getModelNameForTiktoken: () => getModelNameForTiktoken, + isOpenAITool: () => isOpenAITool +}); +var getModelNameForTiktoken = (modelName) => { + if (modelName.startsWith("gpt-5")) return "gpt-5"; + 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"; + if (modelName.startsWith("gpt-4o")) return "gpt-4o"; + return modelName; +}; +var getEmbeddingContextSize = (modelName) => { + switch (modelName) { + case "text-embedding-ada-002": return 8191; + default: return 2046; + } +}; +/** +* Get the context window size (max input tokens) for a given model. +* +* Context window sizes are sourced from official model documentation: +* - OpenAI: https://platform.openai.com/docs/models +* - Anthropic: https://docs.anthropic.com/claude/docs/models-overview +* - Google: https://ai.google.dev/gemini/docs/models/gemini +* +* @param modelName - The name of the model +* @returns The context window size in tokens +*/ +var getModelContextSize = (modelName) => { + switch (getModelNameForTiktoken(modelName)) { + case "gpt-5": + case "gpt-5-turbo": + case "gpt-5-turbo-preview": return 4e5; + case "gpt-4o": + case "gpt-4o-mini": + case "gpt-4o-2024-05-13": + case "gpt-4o-2024-08-06": return 128e3; + case "gpt-4-turbo": + case "gpt-4-turbo-preview": + case "gpt-4-turbo-2024-04-09": + case "gpt-4-0125-preview": + case "gpt-4-1106-preview": return 128e3; + case "gpt-4-32k": + case "gpt-4-32k-0314": + case "gpt-4-32k-0613": return 32768; + case "gpt-4": + case "gpt-4-0314": + case "gpt-4-0613": return 8192; + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-16k-0613": return 16384; + case "gpt-3.5-turbo": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-1106": + case "gpt-3.5-turbo-0125": return 4096; + case "text-davinci-003": + case "text-davinci-002": return 4097; + case "text-davinci-001": return 2049; + case "text-curie-001": + case "text-babbage-001": + case "text-ada-001": return 2048; + case "code-davinci-002": + case "code-davinci-001": return 8e3; + case "code-cushman-001": return 2048; + case "claude-3-5-sonnet-20241022": + case "claude-3-5-sonnet-20240620": + case "claude-3-opus-20240229": + case "claude-3-sonnet-20240229": + case "claude-3-haiku-20240307": + case "claude-2.1": return 2e5; + case "claude-2.0": + case "claude-instant-1.2": return 1e5; + case "gemini-1.5-pro": + case "gemini-1.5-pro-latest": + case "gemini-1.5-flash": + case "gemini-1.5-flash-latest": return 1e6; + case "gemini-pro": + case "gemini-pro-vision": return 32768; + default: return 4097; + } +}; +/** +* Whether or not the input matches the OpenAI tool definition. +* @param {unknown} tool The input to check. +* @returns {boolean} Whether the input is an OpenAI tool definition. +*/ +function isOpenAITool(tool) { + if (typeof tool !== "object" || !tool) return false; + if ("type" in tool && tool.type === "function" && "function" in tool && typeof tool.function === "object" && tool.function && "name" in tool.function && "parameters" in tool.function) return true; + return false; +} +var calculateMaxTokens = async ({ prompt, modelName }) => { + let numTokens; + try { + numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; + } catch { + console.warn("Failed to calculate number of tokens, falling back to approximate count"); + numTokens = Math.ceil(prompt.length / 4); + } + return getModelContextSize(modelName) - numTokens; +}; +var getVerbosity = () => false; +/** +* Base class for language models, chains, tools. +*/ +var BaseLangChain = class extends Runnable { + /** + * Whether to print out response text. + */ + verbose; + callbacks; + tags; + metadata; + get lc_attributes() { + return { + callbacks: void 0, + verbose: void 0 + }; + } + constructor(params) { + super(params); + this.verbose = params.verbose ?? getVerbosity(); + this.callbacks = params.callbacks; + this.tags = params.tags ?? []; + this.metadata = params.metadata ?? {}; + this._addVersion("@langchain/core", "1.2.4"); + } + _addVersion(pkg, version) { + const existing = this.metadata?.versions; + this.metadata = { + ...this.metadata, + versions: { + ...typeof existing === "object" && existing !== null ? existing : {}, + [pkg]: version + } + }; + } +}; +/** +* Base class for language models. +*/ +var BaseLanguageModel = class extends BaseLangChain { + /** + * Keys that the language model accepts as call options. + */ + get callKeys() { + return [ + "stop", + "timeout", + "signal", + "tags", + "metadata", + "callbacks" + ]; + } + /** + * The async caller should be used by subclasses to make any async calls, + * which will thus benefit from the concurrency and retry logic. + */ + caller; + cache; + constructor({ callbacks, callbackManager, ...params }) { + const { cache, ...rest } = params; + super({ + callbacks: callbacks ?? callbackManager, + ...rest + }); + if (typeof cache === "object") this.cache = cache; + else if (cache) this.cache = InMemoryCache.global(); + else this.cache = void 0; + this.caller = new AsyncCaller(params ?? {}); + } + _encoding; + /** + * Get the number of tokens in the content. + * @param content The content to get the number of tokens for. + * @returns The number of tokens in the content. + */ + async getNumTokens(content) { + let textContent; + if (typeof content === "string") textContent = content; + else + /** + * Content is an array of ContentBlock + * + * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content. + * We need to find a better way to do this. + * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116 + */ + textContent = content.map((item) => { + if (typeof item === "string") return item; + if (item.type === "text" && "text" in item) return item.text; + return ""; + }).join(""); + let numTokens = Math.ceil(textContent.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(textContent).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; + } + /** + * Get the identifying parameters of the LLM. + */ + _identifyingParams() { + return {}; + } + /** + * Create a unique cache key for a specific call to a specific language model. + * @param callOptions Call options for the model + * @returns A unique cache key. + */ + _getSerializedCacheKeyParametersForCall({ config, ...callOptions }) { + const params = { + ...this._identifyingParams(), + ...callOptions, + _type: this._llmType(), + _model: this._modelType() + }; + return Object.entries(params).filter(([_, value]) => value !== void 0).map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(","); + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType() + }; + } + /** + * @deprecated + * Load an LLM from a json-like object describing it. + */ + static async deserialize(_data) { + throw new Error("Use .toJSON() instead"); + } + /** + * Return profiling information for the model. + * + * @returns {ModelProfile} An object describing the model's capabilities and constraints + */ + get profile() { + return {}; + } + /** + * Filter out large/inappropriate fields from invocation params for tracing metadata. + * Removes fields like tools, functions, messages, response_format that can be large. + */ + _filterInvocationParamsForTracing(params) { + const { tools, functions, messages, response_format, ...rest } = params; + return rest; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/language_models/utils.js +var iife$1 = (fn) => fn(); +function castStandardMessageContent(message) { + const Cls = message.constructor; + return new Cls({ + ...message, + content: message.contentBlocks, + response_metadata: { + ...message.response_metadata, + output_version: "v1" + } + }); +} +//#endregion +//#region node_modules/@langchain/core/dist/runnables/passthrough.js +/** +* A runnable to passthrough inputs unchanged or with additional keys. +* +* This runnable behaves almost like the identity function, except that it +* can be configured to add additional keys to the output, if the input is +* an object. +* +* The example below demonstrates how to use `RunnablePassthrough to +* passthrough the input from the `.invoke()` +* +* @example +* ```typescript +* const chain = RunnableSequence.from([ +* { +* question: new RunnablePassthrough(), +* context: async () => loadContextFromStore(), +* }, +* prompt, +* llm, +* outputParser, +* ]); +* const response = await chain.invoke( +* "I can pass a single string instead of an object since I'm using `RunnablePassthrough`." +* ); +* ``` +*/ +var RunnablePassthrough = class extends Runnable { + static lc_name() { + return "RunnablePassthrough"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + func; + constructor(fields) { + super(fields); + if (fields) this.func = fields.func; + } + async invoke(input, options) { + const config = ensureConfig(options); + if (this.func) await this.func(input, config); + return this._callWithConfig((input) => Promise.resolve(input), 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); + } + /** + * A runnable that assigns key-value pairs to the input. + * + * The example below shows how you could use it with an inline function. + * + * @example + * ```typescript + * const prompt = + * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} + * Question: {question} + * SQL Query:`); + * + * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` + * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. + * // In this case, we're passing the schema. + * const sqlQueryGeneratorChain = RunnableSequence.from([ + * RunnablePassthrough.assign({ + * schema: async () => db.getTableInfo(), + * }), + * prompt, + * new ChatOpenAI({ model: "gpt-4o-mini" }).withConfig({ stop: ["\nSQLResult:"] }), + * new StringOutputParser(), + * ]); + * const result = await sqlQueryGeneratorChain.invoke({ + * question: "How many employees are there?", + * }); + * ``` + */ + static assign(mapping) { + return new RunnableAssign(new RunnableMap({ steps: mapping })); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/runnables/router.js +/** +* A runnable that routes to a set of runnables based on Input['key']. +* Returns the output of the selected runnable. +* @example +* ```typescript +* import { RouterRunnable, RunnableLambda } from "@langchain/core/runnables"; +* +* const router = new RouterRunnable({ +* runnables: { +* toUpperCase: RunnableLambda.from((text: string) => text.toUpperCase()), +* reverseText: RunnableLambda.from((text: string) => +* text.split("").reverse().join("") +* ), +* }, +* }); +* +* // Invoke the 'reverseText' runnable +* const result1 = router.invoke({ key: "reverseText", input: "Hello World" }); +* +* // "dlroW olleH" +* +* // Invoke the 'toUpperCase' runnable +* const result2 = router.invoke({ key: "toUpperCase", input: "Hello World" }); +* +* // "HELLO WORLD" +* ``` +*/ +var RouterRunnable = class extends Runnable { + static lc_name() { + return "RouterRunnable"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + runnables; + constructor(fields) { + super(fields); + this.runnables = fields.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); + if (keys.find((key) => this.runnables[key] === void 0) !== void 0) throw new Error(`One or more keys do not have a corresponding runnable.`); + const runnables = keys.map((key) => this.runnables[key]); + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; + const batchResults = []; + for (let i = 0; i < actualInputs.length; i += batchSize) { + const batchPromises = actualInputs.slice(i, i + batchSize).map((actualInput, i) => runnables[i].invoke(actualInput, optionsList[i])); + 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); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/runnables/branch.js +/** +* Class that represents a runnable branch. The RunnableBranch is +* initialized with an array of branches and a default branch. When invoked, +* it evaluates the condition of each branch in order and executes the +* corresponding branch if the condition is true. If none of the conditions +* are true, it executes the default branch. +* @example +* ```typescript +* const branch = RunnableBranch.from([ +* [ +* (x: { topic: string; question: string }) => +* x.topic.toLowerCase().includes("anthropic"), +* anthropicChain, +* ], +* [ +* (x: { topic: string; question: string }) => +* x.topic.toLowerCase().includes("langchain"), +* langChainChain, +* ], +* generalChain, +* ]); +* +* const fullChain = RunnableSequence.from([ +* { +* topic: classificationChain, +* question: (input: { question: string }) => input.question, +* }, +* branch, +* ]); +* +* const result = await fullChain.invoke({ +* question: "how do I use LangChain?", +* }); +* ``` +*/ +var RunnableBranch = class extends Runnable { + static lc_name() { + return "RunnableBranch"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + default; + branches; + constructor(fields) { + super(fields); + this.branches = fields.branches; + this.default = fields.default; + } + /** + * Convenience method for instantiating a RunnableBranch from + * RunnableLikes (objects, functions, or Runnables). + * + * Each item in the input except for the last one should be a + * tuple with two items. The first is a "condition" RunnableLike that + * returns "true" if the second RunnableLike in the tuple should run. + * + * The final item in the input should be a RunnableLike that acts as a + * default branch if no other branches match. + * + * @example + * ```ts + * import { RunnableBranch } from "@langchain/core/runnables"; + * + * const branch = RunnableBranch.from([ + * [(x: number) => x > 0, (x: number) => x + 1], + * [(x: number) => x < 0, (x: number) => x - 1], + * (x: number) => x + * ]); + * ``` + * @param branches An array where the every item except the last is a tuple of [condition, runnable] + * pairs. The last item is a default runnable which is invoked if no other condition matches. + * @returns A new RunnableBranch. + */ + static from(branches) { + if (branches.length < 1) throw new Error("RunnableBranch requires at least one branch"); + const coercedBranches = branches.slice(0, -1).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 i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + if (await condition.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) }))) { + result = await branchRunnable.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 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 runManager = await (await getCallbackManagerForConfig(config))?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config?.runId, void 0, void 0, void 0, config?.runName); + let finalOutput; + let finalOutputSupported = true; + let stream; + try { + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + if (await condition.invoke(input, patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) }))) { + stream = await branchRunnable.stream(input, patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); + for await (const chunk of stream) { + yield chunk; + if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = concat(finalOutput, chunk); + } catch { + 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 { + finalOutput = void 0; + finalOutputSupported = false; + } + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/runnables/history.js +/** +* Wraps a LCEL chain and manages history. It appends input messages +* and chain outputs as history, and adds the current history messages to +* the chain input. +* +* @deprecated Use LangGraph's built-in persistence instead. +* +* @example +* ```typescript +* // pnpm install @langchain/anthropic @langchain/classic +* +* import { +* ChatPromptTemplate, +* MessagesPlaceholder, +* } from "@langchain/core/prompts"; +* import { ChatAnthropic } from "@langchain/anthropic"; +* import { ChatMessageHistory } from "@langchain/classic/stores/message/in_memory"; +* +* const prompt = ChatPromptTemplate.fromMessages([ +* ["system", "You're an assistant who's good at {ability}"], +* new MessagesPlaceholder("history"), +* ["human", "{question}"], +* ]); +* +* const chain = prompt.pipe(new ChatAnthropic({})); +* +* const chainWithHistory = new RunnableWithMessageHistory({ +* runnable: chain, +* getMessageHistory: (sessionId) => +* new UpstashRedisChatMessageHistory({ +* sessionId, +* config: { +* url: process.env.UPSTASH_REDIS_REST_URL!, +* token: process.env.UPSTASH_REDIS_REST_TOKEN!, +* }, +* }), +* inputMessagesKey: "question", +* historyMessagesKey: "history", +* }); +* +* const result = await chainWithHistory.invoke( +* { +* ability: "math", +* question: "What does cosine mean?", +* }, +* { +* configurable: { +* sessionId: "some_string_identifying_a_user", +* }, +* } +* ); +* +* const result2 = await chainWithHistory.invoke( +* { +* ability: "math", +* question: "What's its inverse?", +* }, +* { +* configurable: { +* sessionId: "some_string_identifying_a_user", +* }, +* } +* ); +* ``` +*/ +var RunnableWithMessageHistory = class extends RunnableBinding { + runnable; + inputMessagesKey; + outputMessagesKey; + historyMessagesKey; + getMessageHistory; + constructor(fields) { + let historyChain = RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); + const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; + if (messagesKey) historyChain = RunnablePassthrough.assign({ [messagesKey]: historyChain }).withConfig({ runName: "insertHistory" }); + const bound = historyChain.pipe(fields.runnable.withListeners({ onEnd: (run, config) => this._exitHistory(run, config ?? {}) })).withConfig({ runName: "RunnableWithMessageHistory" }); + const config = fields.config ?? {}; + super({ + ...fields, + config, + bound + }); + this.runnable = fields.runnable; + this.getMessageHistory = fields.getMessageHistory; + this.inputMessagesKey = fields.inputMessagesKey; + this.outputMessagesKey = fields.outputMessagesKey; + this.historyMessagesKey = fields.historyMessagesKey; + } + _getInputMessages(inputValue) { + let parsedInputValue; + if (typeof inputValue === "object" && !Array.isArray(inputValue) && !isBaseMessage(inputValue)) { + let key; + if (this.inputMessagesKey) key = this.inputMessagesKey; + else if (Object.keys(inputValue).length === 1) key = Object.keys(inputValue)[0]; + else key = "input"; + if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) parsedInputValue = inputValue[key][0]; + else parsedInputValue = inputValue[key]; + } else parsedInputValue = inputValue; + if (typeof parsedInputValue === "string") return [new HumanMessage(parsedInputValue)]; + else if (Array.isArray(parsedInputValue)) return parsedInputValue; + else if (isBaseMessage(parsedInputValue)) return [parsedInputValue]; + else throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(parsedInputValue, null, 2)}`); + } + _getOutputMessages(outputValue) { + let parsedOutputValue; + if (!Array.isArray(outputValue) && !isBaseMessage(outputValue) && typeof outputValue !== "string") { + let key; + if (this.outputMessagesKey !== void 0) key = this.outputMessagesKey; + else if (Object.keys(outputValue).length === 1) key = Object.keys(outputValue)[0]; + else key = "output"; + if (outputValue.generations !== void 0) parsedOutputValue = outputValue.generations[0][0].message; + else parsedOutputValue = outputValue[key]; + } else parsedOutputValue = outputValue; + if (typeof parsedOutputValue === "string") return [new AIMessage(parsedOutputValue)]; + else if (Array.isArray(parsedOutputValue)) return parsedOutputValue; + else if (isBaseMessage(parsedOutputValue)) return [parsedOutputValue]; + else throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); + } + async _enterHistory(input, kwargs) { + const messages = await (kwargs?.configurable?.messageHistory).getMessages(); + if (this.historyMessagesKey === void 0) return messages.concat(this._getInputMessages(input)); + return messages; + } + async _exitHistory(run, config) { + const history = config.configurable?.messageHistory; + let inputs; + if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) inputs = run.inputs[0]; + else inputs = run.inputs; + let inputMessages = this._getInputMessages(inputs); + if (this.historyMessagesKey === void 0) { + const existingMessages = await history.getMessages(); + inputMessages = inputMessages.slice(existingMessages.length); + } + 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); + await history.addMessages([...inputMessages, ...outputMessages]); + } + async _mergeConfig(...configs) { + const config = await super._mergeConfig(...configs); + if (!config.configurable || !config.configurable.sessionId) { + const exampleInput = { [this.inputMessagesKey ?? "input"]: "foo" }; + throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify({ configurable: { sessionId: "123" } })})`); + } + const { sessionId } = config.configurable; + config.configurable.messageHistory = await this.getMessageHistory(sessionId); + return config; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/runnables/index.js +var runnables_exports = /* @__PURE__ */ __exportAll({ + 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, + RunnableToolLike: () => RunnableToolLike, + RunnableWithFallbacks: () => RunnableWithFallbacks, + RunnableWithMessageHistory: () => RunnableWithMessageHistory, + _coerceToRunnable: () => _coerceToRunnable, + ensureConfig: () => ensureConfig, + getCallbackManagerForConfig: () => getCallbackManagerForConfig, + mergeConfigs: () => mergeConfigs, + patchConfig: () => patchConfig, + pickRunnableConfigKeys: () => pickRunnableConfigKeys, + raceWithSignal: () => raceWithSignal +}); +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/base.js +/** +* Abstract base class for parsing the output of a Large Language Model +* (LLM) call. It provides methods for parsing the result of an LLM call +* and invoking the parser with a given input. +*/ +var BaseLLMOutputParser = class extends Runnable { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + 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); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") return this._callWithConfig(async (input, options) => this.parseResult([{ text: input }], options?.callbacks), input, { + ...options, + runType: "parser" + }); + else return this._callWithConfig(async (input, options) => this.parseResult([{ + message: input, + text: this._baseMessageToString(input) + }], options?.callbacks), input, { + ...options, + runType: "parser" + }); + } +}; +/** +* Class to parse the output of an LLM call. +*/ +var BaseOutputParser = class extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +}; +/** +* Exception that output parsers should raise to signify a parsing error. +* +* This exists to differentiate parsing errors from other code or execution errors +* that also may arise inside the output parser. OutputParserExceptions will be +* available to catch and handle in ways to fix the parsing error, while other +* errors will be raised. +* +* @param message - The error that's being re-raised or an error message. +* @param llmOutput - String model output which is error-ing. +* @param observation - String explanation of error which can be passed to a +* model to try and remediate the issue. +* @param sendToLLM - Whether to send the observation and llm_output back to an Agent +* after an OutputParserException has been raised. This gives the underlying +* model driving the agent the context that the previous output was improperly +* structured, in the hopes that it will update the output to the correct +* format. +*/ +var OutputParserException = class extends Error { + llmOutput; + observation; + sendToLLM; + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + 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"); + } + addLangChainErrorFields$1(this, "OUTPUT_PARSING_FAILURE"); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/transform.js +/** +* Class to parse the output of an LLM call that also allows streaming inputs. +*/ +var 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) + }]); + } + /** + * Transforms an asynchronous generator of input into an asynchronous + * generator of parsed output. + * @param inputGenerator An asynchronous generator of input. + * @param options A configuration object. + * @returns An asynchronous generator of parsed output. + */ + async *transform(inputGenerator, options) { + yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { + ...options, + runType: "parser" + }); + } +}; +/** +* A base class for output parsers that can handle streaming input. It +* extends the `BaseTransformOutputParser` class and provides a method for +* converting parsed outputs into a diff format. +*/ +var BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser { + diff = false; + constructor(fields) { + super(fields); + this.diff = fields?.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: convertToChunk(chunk), + 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; + } + } + } + getFormatInstructions() { + return ""; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/json_patch.js +var json_patch_exports = /* @__PURE__ */ __exportAll({ + applyPatch: () => applyPatch, + compare: () => compare +}); +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/json.js +/** +* Class for parsing the output of an LLM into a JSON object. +*/ +var JsonOutputParser = class extends BaseCumulativeTransformOutputParser { + static lc_name() { + return "JsonOutputParser"; + } + lc_namespace = ["langchain_core", "output_parsers"]; + lc_serializable = true; + /** @internal */ + _concatOutputChunks(first, second) { + if (this.diff) return super._concatOutputChunks(first, second); + return second; + } + _diff(prev, next) { + if (!next) return; + if (!prev) return [{ + op: "replace", + path: "", + value: next + }]; + return compare(prev, next); + } + async parsePartialResult(generations) { + return parseJsonMarkdown(generations[0].text); + } + async parse(text) { + return parseJsonMarkdown(text, JSON.parse); + } + getFormatInstructions() { + return ""; + } + /** + * Extracts text content from a message for JSON parsing. + * Uses the message's `.text` accessor which properly handles both + * string content and ContentBlock[] arrays (extracting text from text blocks). + * @param message The message to extract text from + * @returns The text content of the message + */ + _baseMessageToString(message) { + return message.text; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/standard_schema.js +var StandardSchemaOutputParser = class extends BaseOutputParser { + static lc_name() { + return "StandardSchemaOutputParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "standard_schema" + ]; + schema; + constructor(schema) { + super(); + this.schema = schema; + } + static fromSerializableSchema(schema) { + return new this(schema); + } + async parse(text) { + try { + const json = parseJsonMarkdown(text, JSON.parse); + const result = await this.schema["~standard"].validate(json); + if (result.issues) throw new Error(`Validation failed: ${JSON.stringify(result.issues)}`); + return result.value; + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); + } + } + _baseMessageToString(message) { + return message.text; + } + getFormatInstructions() { + return ""; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/structured.js +var StructuredOutputParser = class extends BaseOutputParser { + static lc_name() { + return "StructuredOutputParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "structured" + ]; + toJSON() { + return this.toJSONNotImplemented(); + } + constructor(schema) { + super(schema); + this.schema = schema; + } + /** + * Creates a new StructuredOutputParser from a Zod schema. + * @param schema The Zod schema which the output should match + * @returns A new instance of StructuredOutputParser. + */ + static fromZodSchema(schema) { + return new this(schema); + } + /** + * Creates a new StructuredOutputParser from a set of names and + * descriptions. + * @param schemas An object where each key is a name and each value is a description + * @returns A new instance of StructuredOutputParser. + */ + static fromNamesAndDescriptions(schemas) { + const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); + return new this(zodSchema); + } + /** + * Returns a markdown code snippet with a JSON object formatted according + * to the schema. + * @param options Optional. The options for formatting the instructions + * @returns A markdown code snippet with a JSON object formatted according to the schema. + */ + 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(toJsonSchema(this.schema))} +\`\`\` +`; + } + /** + * Parses the given text according to the schema. + * @param text The text to parse + * @returns The parsed output. + */ + async parse(text) { + try { + const trimmedText = text.trim(); + const escapedJson = (trimmedText.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1] || trimmedText.match(/```json\s*([\s\S]*?)```/)?.[1] || trimmedText).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => { + return `"${capturedGroup.replace(/\n/g, "\\n")}"`; + }).replace(/\n/g, ""); + return await interopParseAsync(this.schema, JSON.parse(escapedJson)); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); + } + } + _baseMessageToString(message) { + return message.text; + } +}; +/** +* A specific type of `StructuredOutputParser` that parses JSON data +* formatted as a markdown code snippet. +*/ +var 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:\n\`\`\`json\n${this._schemaToInstruction(toJsonSchema(this.schema)).replaceAll("{", "{".repeat(interpolationDepth)).replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``; + } + _schemaToInstruction(schemaInput, indent = 2) { + const schema = schemaInput; + if ("type" in schema) { + let nullable = false; + let type; + if (Array.isArray(schema.type)) { + const nullIdx = schema.type.findIndex((type) => type === "null"); + if (nullIdx !== -1) { + nullable = true; + schema.type.splice(nullIdx, 1); + } + type = schema.type.join(" | "); + } else type = schema.type; + if (schema.type === "object" && schema.properties) { + const description = schema.description ? ` // ${schema.description}` : ""; + return `{\n${Object.entries(schema.properties).map(([key, value]) => { + const isOptional = schema.required?.includes(key) ? "" : " (optional)"; + return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`; + }).join("\n")}\n${" ".repeat(indent - 2)}}${description}`; + } + if (schema.type === "array" && schema.items) { + const description = schema.description ? ` // ${schema.description}` : ""; + return `array[\n${" ".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)}\n${" ".repeat(indent - 2)}] ${description}`; + } + const isNullable = nullable ? " (nullable)" : ""; + const description = schema.description ? ` // ${schema.description}` : ""; + return `${type}${description}${isNullable}`; + } + if ("anyOf" in schema) return schema.anyOf.map((s) => this._schemaToInstruction(s, indent)).join(`\n${" ".repeat(indent - 2)}`); + throw new Error("unsupported schema type"); + } + static fromZodSchema(schema) { + return new this(schema); + } + static fromNamesAndDescriptions(schemas) { + const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); + return new this(zodSchema); + } +}; +/** +* A type of `StructuredOutputParser` that handles asymmetric input and +* output schemas. +*/ +var AsymmetricStructuredOutputParser = class extends BaseOutputParser { + structuredInputParser; + constructor({ inputSchema }) { + super(...arguments); + this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema); + } + async parse(text) { + let parsedInput; + try { + parsedInput = await this.structuredInputParser.parse(text); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); + } + return this.outputProcessor(parsedInput); + } + getFormatInstructions() { + return this.structuredInputParser.getFormatInstructions(); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/bytes.js +/** +* OutputParser that parses LLMResult into the top likely string and +* encodes it into bytes. +*/ +var BytesOutputParser = class extends BaseTransformOutputParser { + static lc_name() { + return "BytesOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "bytes" + ]; + lc_serializable = true; + textEncoder = new TextEncoder(); + parse(text) { + return Promise.resolve(this.textEncoder.encode(text)); + } + getFormatInstructions() { + return ""; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/list.js +/** +* Class to parse the output of an LLM call to a list. +* @augments BaseOutputParser +*/ +var ListOutputParser = class extends BaseTransformOutputParser { + re; + 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]; + } +}; +/** +* Class to parse the output of an LLM call as a comma-separated list. +* @augments ListOutputParser +*/ +var CommaSeparatedListOutputParser = class extends ListOutputParser { + static lc_name() { + return "CommaSeparatedListOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + lc_serializable = true; + /** + * Parses the given text into an array of strings, using a comma as the + * separator. If the parsing fails, throws an OutputParserException. + * @param text The text to parse. + * @returns An array of strings obtained by splitting the input text at each comma. + */ + async parse(text) { + try { + return text.trim().split(",").map((s) => s.trim()); + } catch { + throw new OutputParserException(`Could not parse output: ${text}`, text); + } + } + /** + * Provides instructions on the expected format of the response for the + * CommaSeparatedListOutputParser. + * @returns A string containing instructions on the expected format of the response. + */ + getFormatInstructions() { + return `Your response should be a list of comma separated values, eg: \`foo, bar, baz\``; + } +}; +/** +* Class to parse the output of an LLM call to a list with a specific length and separator. +* @augments ListOutputParser +*/ +var CustomListOutputParser = class extends ListOutputParser { + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + length; + separator; + constructor({ length, separator }) { + super(...arguments); + this.length = length; + this.separator = separator || ","; + } + /** + * Parses the given text into an array of strings, using the specified + * separator. If the parsing fails or the number of items in the list + * doesn't match the expected length, throws an OutputParserException. + * @param text The text to parse. + * @returns An array of strings obtained by splitting the input text at each occurrence of the specified separator. + */ + async parse(text) { + try { + const items = text.trim().split(this.separator).map((s) => s.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 (e) { + if (Object.getPrototypeOf(e) === OutputParserException.prototype) throw e; + throw new OutputParserException(`Could not parse output: ${text}`); + } + } + /** + * Provides instructions on the expected format of the response for the + * CustomListOutputParser, including the number of items and the + * separator. + * @returns A string containing instructions on the expected format of the response. + */ + 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\`)`; + } +}; +var NumberedListOutputParser = class extends ListOutputParser { + static lc_name() { + return "NumberedListOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + lc_serializable = true; + getFormatInstructions() { + return `Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`; + } + re = /\d+\.\s([^\n]+)/g; + async parse(text) { + return [...text.matchAll(this.re) ?? []].map((m) => m[1]); + } +}; +var MarkdownListOutputParser = class extends ListOutputParser { + static lc_name() { + return "NumberedListOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + lc_serializable = true; + getFormatInstructions() { + return `Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`; + } + re = /^\s*[-*]\s([^\n]+)$/gm; + async parse(text) { + return [...text.matchAll(this.re) ?? []].map((m) => m[1]); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/string.js +/** +* OutputParser that parses LLMResult into the top likely string. +* @example +* ```typescript +* const promptTemplate = PromptTemplate.fromTemplate( +* "Tell me a joke about {topic}", +* ); +* +* const chain = RunnableSequence.from([ +* promptTemplate, +* new ChatOpenAI({ model: "gpt-4o-mini" }), +* new StringOutputParser(), +* ]); +* +* const result = await chain.invoke({ topic: "bears" }); +* console.log("What do you call a bear with no teeth? A gummy bear!"); +* ``` +*/ +var StringOutputParser = class extends BaseTransformOutputParser { + static lc_name() { + return "StrOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "string" + ]; + lc_serializable = true; + /** + * Parses a string output from an LLM call. This method is meant to be + * implemented by subclasses to define how a string output from an LLM + * should be parsed. + * @param text The string output from an LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + 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.`); + } + _messageContentToString(content) { + switch (content.type) { + case "text": + case "text_delta": + if ("text" in content) return this._textContentToString(content); + break; + case "image_url": + if ("image_url" in content) return this._imageUrlContentToString(content); + break; + case "reasoning": + case "thinking": + case "redacted_thinking": return ""; + default: throw new Error(`Cannot coerce "${content.type}" message part into a string.`); + } + throw new Error(`Invalid content type: ${content.type}`); + } + _baseMessageContentToString(content) { + return content.reduce((acc, item) => acc + this._messageContentToString(item), ""); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/sax-js/sax.js +var initializeSax = function() { + const sax = {}; + sax.parser = function(strict, opt) { + return new SAXParser(strict, opt); + }; + sax.SAXParser = SAXParser; + sax.SAXStream = SAXStream; + sax.createStream = createStream; + sax.MAX_BUFFER_LENGTH = 64 * 1024; + const buffers = [ + "comment", + "sgmlDecl", + "textNode", + "tagName", + "doctype", + "procInstName", + "procInstBody", + "entity", + "attribName", + "attribValue", + "cdata", + "script" + ]; + sax.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 = sax.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 = S.BEGIN; + parser.strictEntities = parser.opt.strictEntities; + parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.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(o) { + function F() {} + F.prototype = o; + return new F(); + }; + if (!Object.keys) Object.keys = function(o) { + var a = []; + for (var i in o) if (o.hasOwnProperty(i)) a.push(i); + return a; + }; + function checkBufferLength(parser) { + var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10); + var maxActual = 0; + for (var i = 0, l = buffers.length; i < l; i++) { + var len = parser[buffers[i]].length; + if (len > maxAllowed) switch (buffers[i]) { + 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[i]); + } + maxActual = Math.max(maxActual, len); + } + parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH - maxActual + parser.position; + } + function clearBuffers(parser) { + for (var i = 0, l = buffers.length; i < l; i++) parser[buffers[i]] = ""; + } + 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 Stream = ReadableStream; + if (!Stream) Stream = function() {}; + var streamWraps = sax.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); + Stream.apply(this); + this._parser = new SAXParser(strict, opt); + this.writable = true; + this.readable = true; + var me = this; + this._parser.onend = function() { + me.emit("end"); + }; + this._parser.onerror = function(er) { + me.emit("error", er); + me._parser.error = null; + }; + this._decoder = null; + streamWraps.forEach(function(ev) { + Object.defineProperty(me, "on" + ev, { + get: function() { + return me._parser["on" + ev]; + }, + set: function(h) { + if (!h) { + me.removeAllListeners(ev); + me._parser["on" + ev] = h; + return h; + } + me.on(ev, h); + }, + enumerable: true, + configurable: false + }); + }); + } + SAXStream.prototype = Object.create(Stream.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 me = this; + if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) me._parser["on" + ev] = function() { + var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); + args.splice(0, 0, ev); + me.emit.apply(me, args); + }; + return Stream.prototype.on.call(me, 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 isWhitespace(c) { + return c === " " || c === "\n" || c === "\r" || c === " "; + } + function isQuote(c) { + return c === "\"" || c === "'"; + } + function isAttribEnd(c) { + return c === ">" || isWhitespace(c); + } + function isMatch(regex, c) { + return regex.test(c); + } + function notMatch(regex, c) { + return !isMatch(regex, c); + } + var S = 0; + sax.STATE = { + BEGIN: S++, + BEGIN_WHITESPACE: S++, + TEXT: S++, + TEXT_ENTITY: S++, + OPEN_WAKA: S++, + SGML_DECL: S++, + SGML_DECL_QUOTED: S++, + DOCTYPE: S++, + DOCTYPE_QUOTED: S++, + DOCTYPE_DTD: S++, + DOCTYPE_DTD_QUOTED: S++, + COMMENT_STARTING: S++, + COMMENT: S++, + COMMENT_ENDING: S++, + COMMENT_ENDED: S++, + CDATA: S++, + CDATA_ENDING: S++, + CDATA_ENDING_2: S++, + PROC_INST: S++, + PROC_INST_BODY: S++, + PROC_INST_ENDING: S++, + OPEN_TAG: S++, + OPEN_TAG_SLASH: S++, + ATTRIB: S++, + ATTRIB_NAME: S++, + ATTRIB_NAME_SAW_WHITE: S++, + ATTRIB_VALUE: S++, + ATTRIB_VALUE_QUOTED: S++, + ATTRIB_VALUE_CLOSED: S++, + ATTRIB_VALUE_UNQUOTED: S++, + ATTRIB_VALUE_ENTITY_Q: S++, + ATTRIB_VALUE_ENTITY_U: S++, + CLOSE_TAG: S++, + CLOSE_TAG_SAW_WHITE: S++, + SCRIPT: S++, + SCRIPT_ENDING: S++ + }; + sax.XML_ENTITIES = { + amp: "&", + gt: ">", + lt: "<", + quot: "\"", + apos: "'" + }; + sax.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(sax.ENTITIES).forEach(function(key) { + var e = sax.ENTITIES[key]; + var s = typeof e === "number" ? String.fromCharCode(e) : e; + sax.ENTITIES[key] = s; + }); + for (var s in sax.STATE) sax.STATE[sax.STATE[s]] = s; + S = sax.STATE; + function emit(parser, event, data) { + parser[event] && parser[event](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 !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.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(name, attribute) { + var qualName = name.indexOf(":") < 0 ? ["", name] : name.split(":"); + var prefix = qualName[0]; + var local = qualName[1]; + if (attribute && name === "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(p) { + emitNode(parser, "onopennamespace", { + prefix: p, + uri: tag.ns[p] + }); + }); + for (var i = 0, l = parser.attribList.length; i < l; i++) { + var nv = parser.attribList[i]; + var name = nv[0]; + var value = nv[1]; + var qualName = qname(name, true); + var prefix = qualName.prefix; + var local = qualName.local; + var uri = prefix === "" ? "" : tag.ns[prefix] || ""; + var a = { + name, + value, + prefix, + local, + uri + }; + if (prefix && prefix !== "xmlns" && !uri) { + strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix)); + a.uri = prefix; + } + parser.tag.attributes[name] = a; + emitNode(parser, "onattribute", a); + } + 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 = S.SCRIPT; + else parser.state = S.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 = S.TEXT; + return; + } + if (parser.script) { + if (parser.tagName !== "script") { + parser.script += ""; + parser.tagName = ""; + parser.state = S.SCRIPT; + return; + } + emitNode(parser, "onscript", parser.script); + parser.script = ""; + } + var t = parser.tags.length; + var tagName = parser.tagName; + if (!parser.strict) tagName = tagName[parser.looseCase](); + var closeTo = tagName; + while (t--) if (parser.tags[t].name !== closeTo) strictFail(parser, "Unexpected close tag"); + else break; + if (t < 0) { + strictFail(parser, "Unmatched closing tag: " + parser.tagName); + parser.textNode += ""; + parser.state = S.TEXT; + return; + } + parser.tagName = tagName; + var s = parser.tags.length; + while (s-- > t) { + var tag = parser.tag = parser.tags.pop(); + parser.tagName = parser.tag.name; + emitNode(parser, "onclosetag", parser.tagName); + var x = {}; + for (var i in tag.ns) x[i] = tag.ns[i]; + var parent = parser.tags[parser.tags.length - 1] || parser; + if (parser.opt.xmlns && tag.ns !== parent.ns) Object.keys(tag.ns).forEach(function(p) { + var n = tag.ns[p]; + emitNode(parser, "onclosenamespace", { + prefix: p, + uri: n + }); + }); + } + if (t === 0) parser.closedRoot = true; + parser.tagName = parser.attribValue = parser.attribName = ""; + parser.attribList.length = 0; + parser.state = S.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, c) { + if (c === "<") { + parser.state = S.OPEN_WAKA; + parser.startTagPosition = parser.position; + } else if (!isWhitespace(c)) { + strictFail(parser, "Non-whitespace before first tag."); + parser.textNode = c; + parser.state = S.TEXT; + } + } + function charAt(chunk, i) { + var result = ""; + if (i < chunk.length) result = chunk.charAt(i); + 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 i = 0; + var c = ""; + while (true) { + c = charAt(chunk, i++); + parser.c = c; + if (!c) break; + if (parser.trackPosition) { + parser.position++; + if (c === "\n") { + parser.line++; + parser.column = 0; + } else parser.column++; + } + switch (parser.state) { + case S.BEGIN: + parser.state = S.BEGIN_WHITESPACE; + if (c === "") continue; + beginWhiteSpace(parser, c); + continue; + case S.BEGIN_WHITESPACE: + beginWhiteSpace(parser, c); + continue; + case S.TEXT: + if (parser.sawRoot && !parser.closedRoot) { + var starti = i - 1; + while (c && c !== "<" && c !== "&") { + c = charAt(chunk, i++); + if (c && parser.trackPosition) { + parser.position++; + if (c === "\n") { + parser.line++; + parser.column = 0; + } else parser.column++; + } + } + parser.textNode += chunk.substring(starti, i - 1); + } + if (c === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) { + parser.state = S.OPEN_WAKA; + parser.startTagPosition = parser.position; + } else { + if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) strictFail(parser, "Text data outside of root node."); + if (c === "&") parser.state = S.TEXT_ENTITY; + else parser.textNode += c; + } + continue; + case S.SCRIPT: + if (c === "<") parser.state = S.SCRIPT_ENDING; + else parser.script += c; + continue; + case S.SCRIPT_ENDING: + if (c === "/") parser.state = S.CLOSE_TAG; + else { + parser.script += "<" + c; + parser.state = S.SCRIPT; + } + continue; + case S.OPEN_WAKA: + if (c === "!") { + parser.state = S.SGML_DECL; + parser.sgmlDecl = ""; + } else if (isWhitespace(c)) {} else if (isMatch(nameStart, c)) { + parser.state = S.OPEN_TAG; + parser.tagName = c; + } else if (c === "/") { + parser.state = S.CLOSE_TAG; + parser.tagName = ""; + } else if (c === "?") { + parser.state = S.PROC_INST; + parser.procInstName = parser.procInstBody = ""; + } else { + strictFail(parser, "Unencoded <"); + if (parser.startTagPosition + 1 < parser.position) { + var pad = parser.position - parser.startTagPosition; + c = new Array(pad).join(" ") + c; + } + parser.textNode += "<" + c; + parser.state = S.TEXT; + } + continue; + case S.SGML_DECL: + if ((parser.sgmlDecl + c).toUpperCase() === CDATA) { + emitNode(parser, "onopencdata"); + parser.state = S.CDATA; + parser.sgmlDecl = ""; + parser.cdata = ""; + } else if (parser.sgmlDecl + c === "--") { + parser.state = S.COMMENT; + parser.comment = ""; + parser.sgmlDecl = ""; + } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) { + parser.state = S.DOCTYPE; + if (parser.doctype || parser.sawRoot) strictFail(parser, "Inappropriately located doctype declaration"); + parser.doctype = ""; + parser.sgmlDecl = ""; + } else if (c === ">") { + emitNode(parser, "onsgmldeclaration", parser.sgmlDecl); + parser.sgmlDecl = ""; + parser.state = S.TEXT; + } else if (isQuote(c)) { + parser.state = S.SGML_DECL_QUOTED; + parser.sgmlDecl += c; + } else parser.sgmlDecl += c; + continue; + case S.SGML_DECL_QUOTED: + if (c === parser.q) { + parser.state = S.SGML_DECL; + parser.q = ""; + } + parser.sgmlDecl += c; + continue; + case S.DOCTYPE: + if (c === ">") { + parser.state = S.TEXT; + emitNode(parser, "ondoctype", parser.doctype); + parser.doctype = true; + } else { + parser.doctype += c; + if (c === "[") parser.state = S.DOCTYPE_DTD; + else if (isQuote(c)) { + parser.state = S.DOCTYPE_QUOTED; + parser.q = c; + } + } + continue; + case S.DOCTYPE_QUOTED: + parser.doctype += c; + if (c === parser.q) { + parser.q = ""; + parser.state = S.DOCTYPE; + } + continue; + case S.DOCTYPE_DTD: + parser.doctype += c; + if (c === "]") parser.state = S.DOCTYPE; + else if (isQuote(c)) { + parser.state = S.DOCTYPE_DTD_QUOTED; + parser.q = c; + } + continue; + case S.DOCTYPE_DTD_QUOTED: + parser.doctype += c; + if (c === parser.q) { + parser.state = S.DOCTYPE_DTD; + parser.q = ""; + } + continue; + case S.COMMENT: + if (c === "-") parser.state = S.COMMENT_ENDING; + else parser.comment += c; + continue; + case S.COMMENT_ENDING: + if (c === "-") { + parser.state = S.COMMENT_ENDED; + parser.comment = textopts(parser.opt, parser.comment); + if (parser.comment) emitNode(parser, "oncomment", parser.comment); + parser.comment = ""; + } else { + parser.comment += "-" + c; + parser.state = S.COMMENT; + } + continue; + case S.COMMENT_ENDED: + if (c !== ">") { + strictFail(parser, "Malformed comment"); + parser.comment += "--" + c; + parser.state = S.COMMENT; + } else parser.state = S.TEXT; + continue; + case S.CDATA: + if (c === "]") parser.state = S.CDATA_ENDING; + else parser.cdata += c; + continue; + case S.CDATA_ENDING: + if (c === "]") parser.state = S.CDATA_ENDING_2; + else { + parser.cdata += "]" + c; + parser.state = S.CDATA; + } + continue; + case S.CDATA_ENDING_2: + if (c === ">") { + if (parser.cdata) emitNode(parser, "oncdata", parser.cdata); + emitNode(parser, "onclosecdata"); + parser.cdata = ""; + parser.state = S.TEXT; + } else if (c === "]") parser.cdata += "]"; + else { + parser.cdata += "]]" + c; + parser.state = S.CDATA; + } + continue; + case S.PROC_INST: + if (c === "?") parser.state = S.PROC_INST_ENDING; + else if (isWhitespace(c)) parser.state = S.PROC_INST_BODY; + else parser.procInstName += c; + continue; + case S.PROC_INST_BODY: + if (!parser.procInstBody && isWhitespace(c)) continue; + else if (c === "?") parser.state = S.PROC_INST_ENDING; + else parser.procInstBody += c; + continue; + case S.PROC_INST_ENDING: + if (c === ">") { + emitNode(parser, "onprocessinginstruction", { + name: parser.procInstName, + body: parser.procInstBody + }); + parser.procInstName = parser.procInstBody = ""; + parser.state = S.TEXT; + } else { + parser.procInstBody += "?" + c; + parser.state = S.PROC_INST_BODY; + } + continue; + case S.OPEN_TAG: + if (isMatch(nameBody, c)) parser.tagName += c; + else { + newTag(parser); + if (c === ">") openTag(parser); + else if (c === "/") parser.state = S.OPEN_TAG_SLASH; + else { + if (!isWhitespace(c)) strictFail(parser, "Invalid character in tag name"); + parser.state = S.ATTRIB; + } + } + continue; + case S.OPEN_TAG_SLASH: + if (c === ">") { + openTag(parser, true); + closeTag(parser); + } else { + strictFail(parser, "Forward-slash in opening tag not followed by >"); + parser.state = S.ATTRIB; + } + continue; + case S.ATTRIB: + if (isWhitespace(c)) continue; + else if (c === ">") openTag(parser); + else if (c === "/") parser.state = S.OPEN_TAG_SLASH; + else if (isMatch(nameStart, c)) { + parser.attribName = c; + parser.attribValue = ""; + parser.state = S.ATTRIB_NAME; + } else strictFail(parser, "Invalid attribute name"); + continue; + case S.ATTRIB_NAME: + if (c === "=") parser.state = S.ATTRIB_VALUE; + else if (c === ">") { + strictFail(parser, "Attribute without value"); + parser.attribValue = parser.attribName; + attrib(parser); + openTag(parser); + } else if (isWhitespace(c)) parser.state = S.ATTRIB_NAME_SAW_WHITE; + else if (isMatch(nameBody, c)) parser.attribName += c; + else strictFail(parser, "Invalid attribute name"); + continue; + case S.ATTRIB_NAME_SAW_WHITE: + if (c === "=") parser.state = S.ATTRIB_VALUE; + else if (isWhitespace(c)) continue; + else { + strictFail(parser, "Attribute without value"); + parser.tag.attributes[parser.attribName] = ""; + parser.attribValue = ""; + emitNode(parser, "onattribute", { + name: parser.attribName, + value: "" + }); + parser.attribName = ""; + if (c === ">") openTag(parser); + else if (isMatch(nameStart, c)) { + parser.attribName = c; + parser.state = S.ATTRIB_NAME; + } else { + strictFail(parser, "Invalid attribute name"); + parser.state = S.ATTRIB; + } + } + continue; + case S.ATTRIB_VALUE: + if (isWhitespace(c)) continue; + else if (isQuote(c)) { + parser.q = c; + parser.state = S.ATTRIB_VALUE_QUOTED; + } else { + strictFail(parser, "Unquoted attribute value"); + parser.state = S.ATTRIB_VALUE_UNQUOTED; + parser.attribValue = c; + } + continue; + case S.ATTRIB_VALUE_QUOTED: + if (c !== parser.q) { + if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_Q; + else parser.attribValue += c; + continue; + } + attrib(parser); + parser.q = ""; + parser.state = S.ATTRIB_VALUE_CLOSED; + continue; + case S.ATTRIB_VALUE_CLOSED: + if (isWhitespace(c)) parser.state = S.ATTRIB; + else if (c === ">") openTag(parser); + else if (c === "/") parser.state = S.OPEN_TAG_SLASH; + else if (isMatch(nameStart, c)) { + strictFail(parser, "No whitespace between attributes"); + parser.attribName = c; + parser.attribValue = ""; + parser.state = S.ATTRIB_NAME; + } else strictFail(parser, "Invalid attribute name"); + continue; + case S.ATTRIB_VALUE_UNQUOTED: + if (!isAttribEnd(c)) { + if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_U; + else parser.attribValue += c; + continue; + } + attrib(parser); + if (c === ">") openTag(parser); + else parser.state = S.ATTRIB; + continue; + case S.CLOSE_TAG: + if (!parser.tagName) if (isWhitespace(c)) continue; + else if (notMatch(nameStart, c)) if (parser.script) { + parser.script += "") closeTag(parser); + else if (isMatch(nameBody, c)) parser.tagName += c; + else if (parser.script) { + parser.script += "") closeTag(parser); + else strictFail(parser, "Invalid characters in closing tag"); + continue; + case S.TEXT_ENTITY: + case S.ATTRIB_VALUE_ENTITY_Q: + case S.ATTRIB_VALUE_ENTITY_U: + var returnState; + var buffer; + switch (parser.state) { + case S.TEXT_ENTITY: + returnState = S.TEXT; + buffer = "textNode"; + break; + case S.ATTRIB_VALUE_ENTITY_Q: + returnState = S.ATTRIB_VALUE_QUOTED; + buffer = "attribValue"; + break; + case S.ATTRIB_VALUE_ENTITY_U: + returnState = S.ATTRIB_VALUE_UNQUOTED; + buffer = "attribValue"; + break; + } + if (c === ";") 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, c)) parser.entity += c; + else { + strictFail(parser, "Invalid character in entity name"); + parser[buffer] += "&" + parser.entity + c; + parser.entity = ""; + parser.state = returnState; + } + continue; + default: throw new Error(parser, "Unknown state: " + parser.state); + } + } + if (parser.position >= parser.bufferCheckPosition) checkBufferLength(parser); + return parser; + } + /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */ + /* istanbul ignore next */ + 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 index = -1; + var length = arguments.length; + if (!length) return ""; + var result = ""; + while (++index < length) { + var codePoint = Number(arguments[index]); + 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 (index + 1 === length || codeUnits.length > MAX_SIZE) { + result += stringFromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + }; + /* istanbul ignore next */ + if (Object.defineProperty) Object.defineProperty(String, "fromCodePoint", { + value: fromCodePoint, + configurable: true, + writable: true + }); + else String.fromCodePoint = fromCodePoint; + })(); + return sax; +}; +var sax = initializeSax(); +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/xml.js +var 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 "\n \n \n \n" is a well-formatted instance of the schema. +2. String "\n \n " is a badly-formatted instance. +3. String "\n \n \n" is a badly-formatted instance. + +Here are the output tags: +\`\`\` +{tags} +\`\`\``; +var XMLOutputParser = class extends BaseCumulativeTransformOutputParser { + tags; + constructor(fields) { + super(fields); + this.tags = fields?.tags; + } + static lc_name() { + return "XMLOutputParser"; + } + lc_namespace = ["langchain_core", "output_parsers"]; + lc_serializable = true; + _diff(prev, next) { + if (!next) return; + if (!prev) return [{ + op: "replace", + path: "", + value: next + }]; + return compare(prev, next); + } + async parsePartialResult(generations) { + return parseXMLMarkdown(generations[0].text); + } + async parse(text) { + return parseXMLMarkdown(text); + } + getFormatInstructions() { + return !!(this.tags && this.tags.length > 0) ? XML_FORMAT_INSTRUCTIONS.replace("{tags}", this.tags?.join(", ") ?? "") : XML_FORMAT_INSTRUCTIONS; + } +}; +var strip = (text) => text.split("\n").map((line) => line.replace(/^\s+/, "")).join("\n").trim(); +var 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; + } +}; +function parseXMLMarkdown(s) { + const cleanedString = strip(s); + 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) elementStack[elementStack.length - 1].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); +} +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/index.js +var output_parsers_exports = /* @__PURE__ */ __exportAll({ + 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, + StandardSchemaOutputParser: () => StandardSchemaOutputParser, + StringOutputParser: () => StringOutputParser, + StructuredOutputParser: () => StructuredOutputParser, + XMLOutputParser: () => XMLOutputParser, + XML_FORMAT_INSTRUCTIONS: () => XML_FORMAT_INSTRUCTIONS, + parseJsonMarkdown: () => parseJsonMarkdown, + parsePartialJson: () => parsePartialJson, + parseXMLMarkdown: () => parseXMLMarkdown +}); +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js +function parseToolCall(rawToolCall, options) { + if (rawToolCall.function === void 0) return; + let functionArgs; + if (options?.partial) try { + functionArgs = parsePartialJson(rawToolCall.function.arguments ?? "{}"); + } catch { + return; + } + else try { + functionArgs = JSON.parse(rawToolCall.function.arguments); + } catch (e) { + throw new OutputParserException([ + `Function "${rawToolCall.function.name}" arguments:`, + ``, + rawToolCall.function.arguments, + ``, + `are not valid JSON.`, + `Error: ${e.message}` + ].join("\n")); + } + const parsedToolCall = { + name: rawToolCall.function.name, + args: functionArgs, + type: "tool_call" + }; + if (options?.returnId) parsedToolCall.id = rawToolCall.id; + return parsedToolCall; +} +function convertLangChainToolCallToOpenAI(toolCall) { + if (toolCall.id === void 0) throw new Error(`All OpenAI tool calls must have an "id" field.`); + return { + id: toolCall.id, + type: "function", + function: { + name: toolCall.name, + arguments: JSON.stringify(toolCall.args) + } + }; +} +function makeInvalidToolCall(rawToolCall, errorMsg) { + return { + name: rawToolCall.function?.name, + args: rawToolCall.function?.arguments, + id: rawToolCall.id, + error: errorMsg, + type: "invalid_tool_call" + }; +} +/** +* Class for parsing the output of a tool-calling LLM into a JSON object. +*/ +var JsonOutputToolsParser = class extends BaseCumulativeTransformOutputParser { + static lc_name() { + return "JsonOutputToolsParser"; + } + returnId = false; + lc_namespace = [ + "langchain", + "output_parsers", + "openai_tools" + ]; + lc_serializable = true; + constructor(fields) { + super(fields); + this.returnId = fields?.returnId ?? this.returnId; + } + _diff() { + throw new Error("Not supported."); + } + async parse() { + throw new Error("Not implemented."); + } + async parseResult(generations) { + return await this.parsePartialResult(generations, false); + } + /** + * Parses the output and returns a JSON object. If `argsOnly` is true, + * only the arguments of the function call are returned. + * @param generations The output of the LLM to parse. + * @returns A JSON object representation of the function call or its arguments. + */ + async parsePartialResult(generations, partial = true) { + const message = generations[0].message; + let toolCalls; + if (isAIMessage(message) && message.tool_calls?.length) toolCalls = message.tool_calls.map((toolCall) => { + const { id, ...rest } = toolCall; + if (!this.returnId) return rest; + return { + id, + ...rest + }; + }); + else if (message.additional_kwargs.tool_calls !== void 0) toolCalls = JSON.parse(JSON.stringify(message.additional_kwargs.tool_calls)).map((rawToolCall) => { + return parseToolCall(rawToolCall, { + returnId: this.returnId, + partial + }); + }); + if (!toolCalls) return []; + const parsedToolCalls = []; + for (const toolCall of toolCalls) if (toolCall !== void 0) { + const backwardsCompatibleToolCall = { + type: toolCall.name, + args: toolCall.args, + id: toolCall.id + }; + parsedToolCalls.push(backwardsCompatibleToolCall); + } + return parsedToolCalls; + } +}; +/** +* Class for parsing the output of a tool-calling LLM into a JSON object if you are +* expecting only a single tool to be called. +*/ +var JsonOutputKeyToolsParser = class extends JsonOutputToolsParser { + static lc_name() { + return "JsonOutputKeyToolsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_tools" + ]; + lc_serializable = true; + returnId = false; + /** The type of tool calls to return. */ + keyName; + /** Whether to return only the first tool call. */ + returnSingle = false; + zodSchema; + serializableSchema; + constructor(params) { + super(params); + this.keyName = params.keyName; + this.returnSingle = params.returnSingle ?? this.returnSingle; + if ("zodSchema" in params) this.zodSchema = params.zodSchema; + if ("serializableSchema" in params) this.serializableSchema = params.serializableSchema; + } + async _validateResult(result) { + if (this.serializableSchema !== void 0) { + const validated = await this.serializableSchema["~standard"].validate(result); + if (validated.issues) throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(validated.issues)}`, JSON.stringify(result, null, 2)); + return validated.value; + } + if (this.zodSchema === void 0) return result; + const zodParsedResult = await interopSafeParseAsync(this.zodSchema, 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?.issues)}`, JSON.stringify(result, null, 2)); + } + async parsePartialResult(generations) { + const matchingResults = (await super.parsePartialResult(generations)).filter((result) => result.type === this.keyName); + let returnedValues = matchingResults; + if (!matchingResults.length) return; + if (!this.returnId) returnedValues = matchingResults.map((result) => result.args); + if (this.returnSingle) return returnedValues[0]; + return returnedValues; + } + async parseResult(generations) { + const matchingResults = (await super.parsePartialResult(generations, false)).filter((result) => result.type === this.keyName); + let returnedValues = matchingResults; + if (!matchingResults.length) return; + if (!this.returnId) returnedValues = matchingResults.map((result) => result.args); + if (this.returnSingle) return this._validateResult(returnedValues[0]); + return await Promise.all(returnedValues.map((value) => this._validateResult(value))); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/types/index.js +var types_exports = /* @__PURE__ */ __exportAll({ + extendInteropZodObject: () => extendInteropZodObject, + getInteropZodDefaultGetter: () => getInteropZodDefaultGetter, + getInteropZodObjectShape: () => getInteropZodObjectShape, + getSchemaDescription: () => getSchemaDescription, + interopParse: () => interopParse, + interopParseAsync: () => interopParseAsync, + interopSafeParse: () => interopSafeParse, + interopSafeParseAsync: () => interopSafeParseAsync, + interopZodObjectMakeFieldsOptional: () => interopZodObjectMakeFieldsOptional, + interopZodObjectPartial: () => interopZodObjectPartial, + interopZodObjectPassthrough: () => interopZodObjectPassthrough, + interopZodObjectStrict: () => interopZodObjectStrict, + interopZodTransformInputSchema: () => interopZodTransformInputSchema, + isInteropZodError: () => isInteropZodError, + isInteropZodLiteral: () => isInteropZodLiteral, + isInteropZodObject: () => isInteropZodObject, + isInteropZodSchema: () => isInteropZodSchema, + isShapelessZodSchema: () => isShapelessZodSchema, + isSimpleStringZodSchema: () => isSimpleStringZodSchema, + isZodArrayV4: () => isZodArrayV4, + isZodLiteralV3: () => isZodLiteralV3, + isZodLiteralV4: () => isZodLiteralV4, + isZodNullableV4: () => isZodNullableV4, + isZodObjectV3: () => isZodObjectV3, + isZodObjectV4: () => isZodObjectV4, + isZodOptionalV4: () => isZodOptionalV4, + isZodSchema: () => isZodSchema, + isZodSchemaV3: () => isZodSchemaV3, + isZodSchemaV4: () => isZodSchemaV4 +}); +//#endregion +//#region node_modules/@langchain/core/dist/language_models/structured_output.js +var structured_output_exports = /* @__PURE__ */ __exportAll({ + assembleStructuredOutputPipeline: () => assembleStructuredOutputPipeline, + createContentParser: () => createContentParser, + createFunctionCallingParser: () => createFunctionCallingParser +}); +/** +* Creates the appropriate content-based output parser for a schema. Use this for +* jsonMode/jsonSchema methods where the LLM returns JSON text. +* +* - Zod schema -> StructuredOutputParser (Zod validation) +* - Standard schema -> StandardSchemaOutputParser (standard schema validation) +* - Plain JSON schema -> JsonOutputParser (no validation) +*/ +function createContentParser(schema) { + if (isInteropZodSchema(schema)) return StructuredOutputParser.fromZodSchema(schema); + if (isSerializableSchema(schema)) return StandardSchemaOutputParser.fromSerializableSchema(schema); + return new JsonOutputParser(); +} +/** +* Creates the appropriate tool-calling output parser for a schema. Use this for +* function calling / tool use methods where the LLM returns structured tool calls. +* +* - Zod schema -> parser with Zod validation +* - Standard schema -> parser with standard schema validation +* - Plain JSON schema -> parser with no validation +*/ +function createFunctionCallingParser(schema, keyName, ParserClass) { + const Ctor = ParserClass ?? JsonOutputKeyToolsParser; + if (isInteropZodSchema(schema)) return new Ctor({ + returnSingle: true, + keyName, + zodSchema: schema + }); + if (isSerializableSchema(schema)) return new Ctor({ + returnSingle: true, + keyName, + serializableSchema: schema + }); + return new Ctor({ + returnSingle: true, + keyName + }); +} +/** +* Pipes an LLM through an output parser, optionally wrapping the result +* to include the raw LLM response alongside the parsed output. +* +* When `includeRaw` is true, returns `{ raw: BaseMessage, parsed: RunOutput }`. +* If parsing fails, `parsed` falls back to null. +*/ +function assembleStructuredOutputPipeline(llm, outputParser, includeRaw, runName) { + if (!includeRaw) { + const result = llm.pipe(outputParser); + return runName ? result.withConfig({ runName }) : result; + } + const parserAssign = RunnablePassthrough.assign({ parsed: (input, config) => outputParser.invoke(input.raw, config) }); + const parserNone = RunnablePassthrough.assign({ parsed: () => null }); + const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); + const result = RunnableSequence.from([{ raw: llm }, parsedWithFallback]); + return runName ? result.withConfig({ runName }) : result; +} +//#endregion +//#region node_modules/@langchain/core/dist/language_models/stream.js +/** +* Typed stream classes for chat model streaming. +* +* @module +*/ +var stream_exports = /* @__PURE__ */ __exportAll({ + ChatModelStream: () => ChatModelStream, + ReasoningContentStream: () => ReasoningContentStream, + TextContentStream: () => TextContentStream, + ToolCallsStream: () => ToolCallsStream, + UsageMetadataStream: () => UsageMetadataStream +}); +/** +* A buffer that caches emitted events for replay. +* +* Multiple consumers can independently iterate the same buffer — +* each gets its own cursor. Events are never consumed or removed. +* +* @internal +*/ +var ReplayBuffer = class { + events = []; + finished = false; + waiters = []; + error = null; + push(event) { + this.events.push(event); + const toWake = this.waiters.splice(0); + for (const waiter of toWake) waiter(); + } + finish() { + this.finished = true; + const toWake = this.waiters.splice(0); + for (const waiter of toWake) waiter(); + } + setError(err) { + this.error = err; + this.finished = true; + const toWake = this.waiters.splice(0); + for (const waiter of toWake) waiter(); + } + async *iterate() { + if (this.finished) { + if (this.error) throw this.error; + yield* this.events; + return; + } + let cursor = 0; + while (true) { + while (cursor < this.events.length) { + yield this.events[cursor]; + cursor++; + } + if (this.finished) { + if (this.error) throw this.error; + return; + } + await new Promise((resolve) => { + if (cursor < this.events.length || this.finished) { + resolve(); + return; + } + this.waiters.push(resolve); + }); + } + } +}; +/** +* Apply a typed delta to an accumulated content block. +* +* - `text-delta` → append text +* - `reasoning-delta` → append reasoning text +* - `data-delta` → append encoded data to `data` +* - `block-delta` → shallow merge fields +* +* @internal +*/ +function applyDelta(block, delta) { + switch (delta.type) { + case "text-delta": + if (block.type === "text") return { + ...block, + text: (block.text ?? "") + delta.text + }; + return block; + case "reasoning-delta": + if (block.type === "thinking") return { + ...block, + thinking: (block.thinking ?? "") + delta.reasoning + }; + if (block.type === "reasoning") return { + ...block, + reasoning: (block.reasoning ?? "") + delta.reasoning + }; + return block; + case "data-delta": return { + ...block, + data: (block.data ?? "") + delta.data + }; + case "block-delta": return { + ...block, + ...delta.fields + }; + default: throw new Error(`Unknown delta type: ${JSON.stringify(delta)}`); + } +} +/** +* Returns the typed delta carried by a content-block delta event. +* +* Stream protocol compliant language models store incremental updates in +* `event.delta`, e.g. `{ type: "text-delta", text: "hello" }`. Some models and +* adapters still emit the older content-shaped form on `event.content`, e.g. +* `{ type: "text", text: "hello" }`, which predates explicit delta event +* variants. +* +* Keep accepting that content-shaped form here so {@link ChatModelStream} +* remains a tolerant consumer while producers migrate to protocol compliant +* typed deltas. +* +* @internal +*/ +function getEventDelta(event) { + if (event.event !== "content-block-delta") return void 0; + if ("delta" in event && event.delta) return event.delta; + const content = event.content; + if (content == null || typeof content !== "object") return void 0; + const block = content; + if (block.type === "text" && typeof block.text === "string") return { + type: "text-delta", + text: block.text + }; + if (block.type === "reasoning" && typeof block.reasoning === "string") return { + type: "reasoning-delta", + reasoning: block.reasoning + }; + if (block.type === "thinking" && typeof block.thinking === "string") return { + type: "reasoning-delta", + reasoning: block.thinking + }; + if (typeof block.data === "string") return { + type: "data-delta", + data: block.data, + encoding: "base64" + }; + if (typeof block.type === "string") return { + type: "block-delta", + fields: { + ...block, + type: block.type + } + }; +} +function getReasoningDelta(content) { + if (content == null || typeof content !== "object") return void 0; + const block = content; + if (block.type === "reasoning" && typeof block.reasoning === "string") return block.reasoning; + if (block.type === "thinking" && typeof block.thinking === "string") return block.thinking; +} +function isReasoningContent(content) { + if (content == null || typeof content !== "object") return false; + const type = content.type; + return type === "reasoning" || type === "thinking"; +} +/** +* Normalize protocol-compatible partial usage into Core's concrete usage shape. +* +* Some stream sources emit usage snapshots without every aggregate token field. +* Keep the stream event input permissive, then normalize at read time so +* high-level Core consumers always receive a complete {@link UsageMetadata}. +*/ +function normalizeUsage(usage) { + if (!usage) return void 0; + return { + ...usage, + input_tokens: usage.input_tokens ?? 0, + output_tokens: usage.output_tokens ?? 0, + total_tokens: usage.total_tokens ?? 0 + }; +} +function parseToolArgs(value) { + if (value != null && typeof value === "object" && !Array.isArray(value)) return value; + if (typeof value !== "string" || value.length === 0) return {}; + try { + const parsed = JSON.parse(value); + return parsed != null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; + } +} +function standardizeToolBlock(block) { + const record = block; + if (block.type === "tool_call") return block; + if (block.type !== "tool_call_chunk" && block.type !== "tool_use" && block.type !== "input_json_delta") return block; + const name = typeof record.name === "string" ? record.name : void 0; + if (name == null) return block; + const args = record.args ?? record.input; + return { + ...record, + type: "tool_call", + name, + args: parseToolArgs(args) + }; +} +/** +* Typed stream for text content. +* +* - **Iterate**: yields incremental text deltas. +* - **Await**: resolves to the complete concatenated text. +* - **`.full`**: yields the running accumulated text after each delta. +*/ +var TextContentStream = class { + /** @internal */ + _buffer; + /** @internal */ + constructor(buffer) { + this._buffer = buffer; + } + /** Yields the accumulated text so far after each delta. */ + get full() { + const buffer = this._buffer; + return { async *[Symbol.asyncIterator]() { + let accumulated = ""; + for await (const event of buffer.iterate()) { + const delta = getEventDelta(event); + if (delta?.type === "text-delta") { + accumulated += delta.text; + yield accumulated; + } + } + } }; + } + /** Yields incremental text deltas. */ + [Symbol.asyncIterator]() { + const buffer = this._buffer; + async function* gen() { + for await (const event of buffer.iterate()) { + const delta = getEventDelta(event); + if (delta?.type === "text-delta") yield delta.text; + } + } + return gen(); + } + then(onfulfilled, onrejected) { + return (async () => { + let text = ""; + for await (const delta of this) text += delta; + return text; + })().then(onfulfilled, onrejected); + } +}; +/** +* Typed stream for tool calls. +* +* - **Iterate**: yields individual `ToolCall` objects as each completes. +* - **Await**: resolves to the full array. +* - **`.full`**: yields the accumulated array after each new tool call. +*/ +var ToolCallsStream = class { + /** @internal */ + _buffer; + /** @internal */ + constructor(buffer) { + this._buffer = buffer; + } + get full() { + const buffer = this._buffer; + return { async *[Symbol.asyncIterator]() { + const calls = []; + for await (const event of buffer.iterate()) if (event.event === "content-block-finish" && event.content.type === "tool_call") { + calls.push(event.content); + yield [...calls]; + } + } }; + } + [Symbol.asyncIterator]() { + const buffer = this._buffer; + async function* gen() { + for await (const event of buffer.iterate()) if (event.event === "content-block-finish" && event.content.type === "tool_call") yield event.content; + } + return gen(); + } + then(onfulfilled, onrejected) { + return (async () => { + const calls = []; + for await (const call of this) calls.push(call); + return calls; + })().then(onfulfilled, onrejected); + } +}; +/** +* Typed stream for reasoning content (chain-of-thought). +* Same interface as {@link TextContentStream} but for reasoning blocks. +*/ +var ReasoningContentStream = class { + /** @internal */ + _buffer; + /** @internal */ + constructor(buffer) { + this._buffer = buffer; + } + get full() { + const buffer = this._buffer; + return { async *[Symbol.asyncIterator]() { + let accumulated = ""; + let seenReasoning = false; + for await (const event of buffer.iterate()) if (event.event === "content-block-start") { + if (!isReasoningContent(event.content)) { + if (seenReasoning) return; + continue; + } + seenReasoning = true; + const delta = getReasoningDelta(event.content); + if (delta == null || delta.length === 0) continue; + accumulated += delta; + yield accumulated; + } else if (event.event === "content-block-delta") { + const eventDelta = getEventDelta(event); + if (eventDelta?.type !== "reasoning-delta") continue; + seenReasoning = true; + const delta = eventDelta.reasoning; + if (delta == null || delta.length === 0) continue; + accumulated += delta; + yield accumulated; + } else if (event.event === "content-block-finish" && isReasoningContent(event.content)) return; + else if (event.event === "message-finish") return; + } }; + } + [Symbol.asyncIterator]() { + const buffer = this._buffer; + async function* gen() { + let seenReasoning = false; + for await (const event of buffer.iterate()) if (event.event === "content-block-start") { + if (!isReasoningContent(event.content)) { + if (seenReasoning) return; + continue; + } + seenReasoning = true; + const delta = getReasoningDelta(event.content); + if (delta != null && delta.length > 0) yield delta; + } else if (event.event === "content-block-delta") { + const eventDelta = getEventDelta(event); + if (eventDelta?.type !== "reasoning-delta") continue; + seenReasoning = true; + const delta = eventDelta.reasoning; + if (delta != null && delta.length > 0) yield delta; + } else if (event.event === "content-block-finish" && isReasoningContent(event.content)) return; + else if (event.event === "message-finish") return; + } + return gen(); + } + then(onfulfilled, onrejected) { + return (async () => { + let text = ""; + for await (const delta of this) text += delta; + return text; + })().then(onfulfilled, onrejected); + } +}; +/** +* Typed stream for usage metadata. +*/ +var UsageMetadataStream = class { + /** @internal */ + _buffer; + /** @internal */ + constructor(buffer) { + this._buffer = buffer; + } + [Symbol.asyncIterator]() { + const buffer = this._buffer; + async function* gen() { + for await (const event of buffer.iterate()) if (event.event === "usage") { + const usage = normalizeUsage(event.usage); + if (usage) yield usage; + } else if (event.event === "message-start" && event.usage) { + const usage = normalizeUsage(event.usage); + if (usage) yield usage; + } else if (event.event === "message-finish" && event.usage) { + const usage = normalizeUsage(event.usage); + if (usage) yield usage; + } + } + return gen(); + } + then(onfulfilled, onrejected) { + return (async () => { + let latest; + for await (const usage of this) latest = usage; + return latest; + })().then(onfulfilled, onrejected); + } +}; +/** +* The main stream object returned by chat model streaming. +* +* Implements `AsyncIterable` for raw event access +* and `PromiseLike` for simple `await` usage. +*/ +var ChatModelStream = class { + /** @internal */ + _buffer; + /** @internal */ + constructor(source) { + this._buffer = new ReplayBuffer(); + this._consume(source); + } + /** @internal */ + async _consume(source) { + try { + for await (const event of source) this._buffer.push(event); + this._buffer.finish(); + } catch (err) { + this._buffer.setError(err instanceof Error ? err : new Error(String(err))); + } + } + [Symbol.asyncIterator]() { + return this._buffer.iterate(); + } + get text() { + return new TextContentStream(this._buffer); + } + get toolCalls() { + return new ToolCallsStream(this._buffer); + } + get reasoning() { + return new ReasoningContentStream(this._buffer); + } + get usage() { + return new UsageMetadataStream(this._buffer); + } + get output() { + return this._assembleMessage(); + } + then(onfulfilled, onrejected) { + return this._assembleMessage().then(onfulfilled, onrejected); + } + /** @internal */ + async _assembleMessage() { + const contentBlocks = []; + let id; + let usage; + let metadata = {}; + let finishReason; + for await (const event of this._buffer.iterate()) switch (event.event) { + case "message-start": + id = event.id ?? id; + if (event.usage) usage = normalizeUsage(event.usage); + break; + case "content-block-start": + contentBlocks[event.index] = event.content; + break; + case "content-block-delta": { + const current = contentBlocks[event.index]; + const delta = getEventDelta(event); + if (current) { + if (delta) contentBlocks[event.index] = applyDelta(current, delta); + } + break; + } + case "content-block-finish": + contentBlocks[event.index] = event.content; + break; + case "usage": + usage = normalizeUsage(event.usage); + break; + case "message-finish": + finishReason = event.reason; + if (event.usage) usage = normalizeUsage(event.usage); + if (event.responseMetadata) metadata = { + ...metadata, + ...event.responseMetadata + }; + break; + default: break; + } + const filteredBlocks = contentBlocks.filter((b) => b != null).map(standardizeToolBlock); + return new AIMessage({ + id, + content: filteredBlocks, + usage_metadata: usage, + response_metadata: { + ...metadata, + ...finishReason ? { finish_reason: finishReason } : {}, + output_version: "v1" + } + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/language_models/compat.js +/** +* Compatibility bridge: converts legacy `_streamResponseChunks` +* (`ChatGenerationChunk` / `AIMessageChunk`) output to the new +* `ChatModelStreamEvent` protocol. +* +* @module +*/ +var compat_exports = /* @__PURE__ */ __exportAll({ + convertChunksToEvents: () => convertChunksToEvents, + finalizeContentBlock: () => finalizeContentBlock +}); +var MIME_TYPE_BY_AUDIO_FORMAT = { + wav: "audio/wav", + mp3: "audio/mpeg", + flac: "audio/flac", + opus: "audio/opus", + aac: "audio/aac", + pcm16: "audio/pcm" +}; +var MIME_TYPE_BY_IMAGE_FORMAT = { + png: "image/png", + jpeg: "image/jpeg", + jpg: "image/jpeg", + webp: "image/webp", + gif: "image/gif" +}; +function nextBlockIndex(activeBlocks) { + let next = 0; + for (const index of activeBlocks.keys()) if (index >= next) next = index + 1; + return next; +} +function getAdditionalKwargs(message) { + const additional = message.additional_kwargs; + return additional != null && typeof additional === "object" ? additional : {}; +} +function extractImageBlocksFromToolOutputs(message) { + const toolOutputs = getAdditionalKwargs(message).tool_outputs; + if (!Array.isArray(toolOutputs)) return []; + const blocks = []; + for (const entry of toolOutputs) { + if (entry == null || typeof entry !== "object") continue; + const record = entry; + if (record.type !== "image_generation_call") continue; + const data = typeof record.result === "string" ? record.result : void 0; + const url = typeof record.url === "string" ? record.url : void 0; + if (data == null && url == null) continue; + const outputFormat = typeof record.output_format === "string" ? record.output_format.toLowerCase() : void 0; + const mimeType = (outputFormat != null ? MIME_TYPE_BY_IMAGE_FORMAT[outputFormat] : void 0) ?? "image/png"; + blocks.push({ + type: "image", + ...typeof record.id === "string" ? { id: record.id } : {}, + ...url != null ? { url } : {}, + ...data != null ? { data } : {}, + mimeType + }); + } + return blocks; +} +/** +* Get the audio payload from the message. +* +* This handles the OpenAI-shaped `additional_kwargs.audio` payload used by +* legacy chunk streams; other providers must normalize into this shape first. +* +* @param message - The message to get the audio payload from. +* @returns The audio payload. +* @internal +*/ +function getAudioPayload(message) { + const audio = getAdditionalKwargs(message).audio; + if (audio == null || typeof audio !== "object") return void 0; + const record = audio; + const data = typeof record.data === "string" ? record.data : void 0; + const url = typeof record.url === "string" ? record.url : void 0; + const transcript = typeof record.transcript === "string" ? record.transcript : void 0; + if (data == null && url == null && transcript == null) return void 0; + const explicitMimeType = typeof record.mime_type === "string" ? record.mime_type : typeof record.mimeType === "string" ? record.mimeType : void 0; + const format = typeof record.format === "string" ? record.format.toLowerCase() : void 0; + const mimeType = explicitMimeType ?? (format != null ? MIME_TYPE_BY_AUDIO_FORMAT[format] : void 0) ?? (data != null ? "audio/wav" : "audio/pcm"); + return { + ...typeof record.id === "string" ? { id: record.id } : {}, + ...data != null ? { data } : {}, + ...url != null ? { url } : {}, + ...transcript != null ? { transcript } : {}, + mimeType + }; +} +/** +* Convert an async iterable of legacy `ChatGenerationChunk`s into +* `ChatModelStreamEvent`s with typed deltas. +*/ +async function* convertChunksToEvents(chunks, options) { + const activeBlocks = /* @__PURE__ */ new Map(); + let messageStarted = false; + let lastUsage; + let audioStream; + const emittedImageKeys = /* @__PURE__ */ new Set(); + for await (const chunk of chunks) { + options?.signal?.throwIfAborted(); + const msg = chunk.message; + let usageHandledInStart = false; + if (!messageStarted) { + messageStarted = true; + const startEvent = { + event: "message-start", + id: msg.id ?? void 0 + }; + if (AIMessageChunk.isInstance(msg) && msg.usage_metadata) { + startEvent.usage = msg.usage_metadata; + lastUsage = { ...msg.usage_metadata }; + usageHandledInStart = true; + } + yield startEvent; + } + const content = msg.content; + if (typeof content === "string") { + if (content !== "") { + const blockIndex = 0; + if (!activeBlocks.has(blockIndex)) { + const initial = { + type: "text", + text: "" + }; + activeBlocks.set(blockIndex, { + type: "text", + accumulated: initial + }); + yield { + event: "content-block-start", + index: blockIndex, + content: initial + }; + } + const block = activeBlocks.get(blockIndex); + block.accumulated = { + ...block.accumulated, + text: (block.accumulated.text ?? "") + content + }; + yield { + event: "content-block-delta", + index: blockIndex, + delta: { + type: "text-delta", + text: content + } + }; + } + } else if (Array.isArray(content)) for (const part of content) { + const blockIndex = typeof part.index === "number" ? part.index : activeBlocks.size; + if (!activeBlocks.has(blockIndex)) { + activeBlocks.set(blockIndex, { + type: part.type, + accumulated: { ...part } + }); + yield { + event: "content-block-start", + index: blockIndex, + content: { ...part } + }; + } else { + const block = activeBlocks.get(blockIndex); + const delta = contentBlockToDelta(part); + block.accumulated = applyDeltaToBlock(block.accumulated, delta); + yield { + event: "content-block-delta", + index: blockIndex, + delta + }; + } + } + if (AIMessageChunk.isInstance(msg) && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) for (const toolChunk of msg.tool_call_chunks) { + const blockIndex = typeof toolChunk.index === "number" ? toolChunk.index : activeBlocks.size; + if (!activeBlocks.has(blockIndex)) { + const initial = { + type: "tool_call_chunk", + id: toolChunk.id, + name: toolChunk.name, + args: "", + index: blockIndex + }; + activeBlocks.set(blockIndex, { + type: "tool_call_chunk", + accumulated: initial + }); + yield { + event: "content-block-start", + index: blockIndex, + content: initial + }; + } + const acc = activeBlocks.get(blockIndex).accumulated; + if (toolChunk.id != null) acc.id = toolChunk.id; + if (toolChunk.name != null) acc.name = toolChunk.name; + acc.args = (acc.args ?? "") + (toolChunk.args ?? ""); + yield { + event: "content-block-delta", + index: blockIndex, + delta: { + type: "block-delta", + fields: { + type: "tool_call_chunk", + ..."id" in acc && acc.id != null ? { id: acc.id } : {}, + ..."name" in acc && acc.name != null ? { name: acc.name } : {}, + args: acc.args + } + } + }; + } + const audioPayload = getAudioPayload(msg); + if (audioPayload != null) { + if (audioStream == null) { + const index = nextBlockIndex(activeBlocks); + audioStream = { + index, + id: audioPayload.id, + mimeType: audioPayload.mimeType, + transcript: "" + }; + const initial = { + type: "audio", + ...audioPayload.id != null ? { id: audioPayload.id } : {}, + ...audioPayload.url != null ? { url: audioPayload.url } : {}, + data: "", + mimeType: audioPayload.mimeType + }; + activeBlocks.set(index, { + type: "audio", + accumulated: initial + }); + yield { + event: "content-block-start", + index, + content: initial + }; + } + const activeAudio = activeBlocks.get(audioStream.index); + if (activeAudio != null) { + const accumulated = activeAudio.accumulated; + if (audioPayload.id != null && audioStream.id == null) { + audioStream.id = audioPayload.id; + accumulated.id = audioPayload.id; + } + if (audioPayload.transcript != null) { + audioStream.transcript += audioPayload.transcript; + accumulated.transcript = audioStream.transcript; + yield { + event: "content-block-delta", + index: audioStream.index, + delta: { + type: "block-delta", + fields: { + type: "audio", + transcript: audioStream.transcript + } + } + }; + } + if (audioPayload.data != null && audioPayload.data.length > 0) { + accumulated.data = (accumulated.data ?? "") + audioPayload.data; + yield { + event: "content-block-delta", + index: audioStream.index, + delta: { + type: "data-delta", + data: audioPayload.data, + encoding: "base64" + } + }; + } + } + } + for (const imageBlock of extractImageBlocksFromToolOutputs(msg)) { + const imageRecord = imageBlock; + const imageKey = imageRecord.id ?? imageRecord.url ?? (imageRecord.data != null ? `${imageRecord.data.length}:${imageRecord.data.slice(0, 32)}` : void 0); + if (imageKey != null && emittedImageKeys.has(imageKey)) continue; + if (imageKey != null) emittedImageKeys.add(imageKey); + const index = nextBlockIndex(activeBlocks); + activeBlocks.set(index, { + type: "image", + accumulated: imageBlock + }); + yield { + event: "content-block-start", + index, + content: imageBlock + }; + } + if (!usageHandledInStart && AIMessageChunk.isInstance(msg) && msg.usage_metadata) { + const chunkUsage = msg.usage_metadata; + if (!lastUsage) lastUsage = { ...chunkUsage }; + else lastUsage = { + input_tokens: lastUsage.input_tokens + chunkUsage.input_tokens, + output_tokens: lastUsage.output_tokens + chunkUsage.output_tokens, + total_tokens: lastUsage.total_tokens + chunkUsage.total_tokens + }; + yield { + event: "usage", + usage: { ...lastUsage } + }; + } + } + for (const [index, block] of activeBlocks) yield { + event: "content-block-finish", + index, + content: finalizeContentBlock(block.accumulated) + }; + yield { + event: "message-finish", + reason: "stop", + ...lastUsage ? { usage: lastUsage } : {} + }; +} +/** +* Apply a typed delta to an accumulated content block. +* @internal +*/ +function applyDeltaToBlock(block, delta) { + switch (delta.type) { + case "text-delta": + if (block.type === "text") return { + ...block, + text: (block.text ?? "") + delta.text + }; + return block; + case "reasoning-delta": + if (block.type === "thinking") return { + ...block, + thinking: (block.thinking ?? "") + delta.reasoning + }; + if (block.type === "reasoning") return { + ...block, + reasoning: (block.reasoning ?? "") + delta.reasoning + }; + return block; + case "data-delta": return { + ...block, + data: (block.data ?? "") + delta.data + }; + case "block-delta": return { + ...block, + ...delta.fields + }; + default: throw new Error(`Unknown delta type: ${JSON.stringify(delta)}`); + } +} +function contentBlockToDelta(block) { + if (block.type === "text") return { + type: "text-delta", + text: block.text + }; + if (block.type === "reasoning") return { + type: "reasoning-delta", + reasoning: block.reasoning + }; + if (block.type === "thinking" && typeof block.thinking === "string") return { + type: "reasoning-delta", + reasoning: block.thinking + }; + if (typeof block.data === "string") return { + type: "data-delta", + data: block.data, + encoding: "base64" + }; + if (typeof block.type === "string") return { + type: "block-delta", + fields: { ...block } + }; + throw new Error(`Unsupported content block delta: ${JSON.stringify(block)}`); +} +/** +* Finalize a content block for the finish event. +* For tool calls, parse the accumulated JSON args string. +*/ +function finalizeContentBlock(block) { + if (block.type === "tool_call_chunk") { + const chunk = block; + let parsedArgs; + try { + parsedArgs = JSON.parse(chunk.args ?? "{}"); + } catch { + return { + type: "invalid_tool_call", + id: chunk.id, + name: chunk.name, + args: chunk.args, + error: "Failed to parse tool call arguments as JSON" + }; + } + return { + type: "tool_call", + id: chunk.id, + name: chunk.name, + args: parsedArgs + }; + } + return block; +} +//#endregion +//#region node_modules/@langchain/core/dist/language_models/chat_models.js +var chat_models_exports = /* @__PURE__ */ __exportAll({ + BaseChatModel: () => BaseChatModel, + SimpleChatModel: () => SimpleChatModel +}); +function _formatForTracing(messages) { + const messagesToTrace = []; + for (const message of messages) { + let messageToTrace = message; + if (Array.isArray(message.content)) for (let idx = 0; idx < message.content.length; idx++) { + const block = message.content[idx]; + if (isURLContentBlock(block) || isBase64ContentBlock(block)) { + if (messageToTrace === message) messageToTrace = new message.constructor({ + ...messageToTrace, + content: [ + ...message.content.slice(0, idx), + convertToOpenAIImageBlock(block), + ...message.content.slice(idx + 1) + ] + }); + } + } + messagesToTrace.push(messageToTrace); + } + return messagesToTrace; +} +/** +* Base class for chat models. It extends the BaseLanguageModel class and +* provides methods for generating chat based on input messages. +*/ +var BaseChatModel = class BaseChatModel extends BaseLanguageModel { + lc_namespace = [ + "langchain", + "chat_models", + this._llmType() + ]; + disableStreaming = false; + outputVersion; + get callKeys() { + return [...super.callKeys, "outputVersion"]; + } + constructor(fields) { + super(fields); + this.outputVersion = iife$1(() => { + const outputVersion = fields.outputVersion ?? getEnvironmentVariable$1("LC_OUTPUT_VERSION"); + if (outputVersion && ["v0", "v1"].includes(outputVersion)) return outputVersion; + return "v0"; + }); + } + _separateRunnableConfigFromCallOptionsCompat(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + return [runnableConfig, callOptions]; + } + /** + * Invokes the chat model with a single input. + * @param input The input for the language model. + * @param options The call options. + * @returns A Promise that resolves to a BaseMessageChunk. + */ + async invoke(input, options) { + const promptValue = BaseChatModel._convertInputToPromptValue(input); + return (await this.generatePrompt([promptValue], options, options?.callbacks)).generations[0][0].message; + } + async *_streamResponseChunks(_messages, _options, _runManager) { + throw new Error("Not implemented."); + } + /** + * Stream chat model events using the new content-block-centric protocol. + * + * Override this method to provide native event streaming from the provider SDK. + * The default implementation bridges from `_streamResponseChunks` by + * synthesizing lifecycle events from `ChatGenerationChunk` objects. + * + * ## Event lifecycle + * + * ``` + * MessageStart + * -> ContentBlockStart(index, contentBlock) + * -> ContentBlockDelta(index, delta) ... + * -> ContentBlockFinish(index, contentBlock) + * -> MessageFinish(reason, usage?) + * ``` + * + * Content blocks may interleave (e.g., parallel tool calls). The only + * invariant: a block's start precedes its deltas, and its deltas precede + * its finish. + * + * @param messages - The input messages. + * @param options - Parsed call options. + * @param runManager - Optional callback manager for the run. + * @returns An async generator of {@link ChatModelStreamEvent}. + */ + async *_streamChatModelEvents(messages, options, runManager) { + yield* convertChunksToEvents(this._streamResponseChunks(messages, options, runManager), { signal: options.signal }); + } + streamEvents(input, options, streamOptions) { + if (options?.version === "v1" || options?.version === "v2") return super.streamEvents(input, options, streamOptions); + const messages = BaseChatModel._convertInputToPromptValue(input).toChatMessages(); + const [, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + return new ChatModelStream(this._streamChatModelEvents(messages, callOptions)); + } + /** + * @deprecated Use {@link BaseChatModel.streamEvents} instead. This method will be removed in the next major version. + */ + streamV2(input, options) { + return this.streamEvents(input, options); + } + async *_streamIterator(input, options) { + if (this._streamResponseChunks === BaseChatModel.prototype._streamResponseChunks || this.disableStreaming) yield this.invoke(input, options); + else { + const messages = BaseChatModel._convertInputToPromptValue(input).toChatMessages(); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + const inheritableMetadata = { + ...runnableConfig.metadata, + ...this.getLsParamsWithDefaults(callOptions) + }; + const invocationParams = this.invocationParams(callOptions); + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: callOptions, + invocation_params: invocationParams, + batch_size: 1 + }; + const outputVersion = callOptions.outputVersion ?? this.outputVersion; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); + let generationChunk; + let llmOutput; + try { + for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { + callOptions.signal?.throwIfAborted(); + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) chunk.message._updateId(`run-${runId}`); + } + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata + }; + if (outputVersion === "v1") yield castStandardMessageContent(chunk.message); + else yield chunk.message; + if (!generationChunk) generationChunk = chunk; + else generationChunk = generationChunk.concat(chunk); + if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens + } }; + } + callOptions.signal?.throwIfAborted(); + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + generations: [[generationChunk]], + llmOutput + }))); + } + } + getLsParams(options) { + const providerName = this.getName().startsWith("Chat") ? this.getName().replace("Chat", "") : this.getName(); + return { + ls_model_type: "chat", + ls_stop: options.stop, + ls_provider: providerName + }; + } + /** + * Wraps getLsParams() and always appends ls_integration. + * This ensures the integration tag is present even when + * partner packages fully override getLsParams(). + */ + getLsParamsWithDefaults(options) { + return { + ...this.getLsParams(options), + ls_integration: "langchain_chat_model" + }; + } + /** @ignore */ + async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + let runManagers; + if (startedRunManagers !== void 0 && startedRunManagers.length === baseMessages.length) runManagers = startedRunManagers; + else { + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParamsWithDefaults(parsedOptions) + }; + const invocationParams = this.invocationParams(parsedOptions); + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: parsedOptions, + invocation_params: invocationParams, + batch_size: 1 + }; + runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); + } + const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; + const generations = []; + const llmOutputs = []; + const hasChatModelStreamEventHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersChatModelStreamEvents); + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + if (hasChatModelStreamEventHandler && !this.disableStreaming && baseMessages.length === 1 && (this._streamChatModelEvents !== BaseChatModel.prototype._streamChatModelEvents || this._streamResponseChunks !== BaseChatModel.prototype._streamResponseChunks)) try { + let sawEvent = false; + const runManager = runManagers?.[0]; + const events = this._streamChatModelEvents(baseMessages[0], parsedOptions); + const message = await new ChatModelStream({ async *[Symbol.asyncIterator]() { + for await (const event of events) { + parsedOptions.signal?.throwIfAborted(); + sawEvent = true; + const streamEvent = event.event === "message-start" && event.id == null && runManager?.runId != null ? { + ...event, + id: `run-${runManager.runId}` + } : event; + await runManager?.handleChatModelStreamEvent(streamEvent); + yield streamEvent; + } + } }); + parsedOptions.signal?.throwIfAborted(); + if (!sawEvent) throw new Error("Received empty response from chat model call."); + if (message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) message._updateId(`run-${runId}`); + } + const generation = { + text: message.text, + message + }; + generations.push([generation]); + const llmOutput = message.usage_metadata !== void 0 ? { tokenUsage: { + promptTokens: message.usage_metadata.input_tokens, + completionTokens: message.usage_metadata.output_tokens, + totalTokens: message.usage_metadata.total_tokens + } } : void 0; + await runManagers?.[0].handleLLMEnd({ + generations, + llmOutput + }); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + else if (hasStreamingHandler && !this.disableStreaming && baseMessages.length === 1 && this._streamResponseChunks !== BaseChatModel.prototype._streamResponseChunks) try { + const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); + let aggregated; + let llmOutput; + for await (const chunk of stream) { + if (parsedOptions.signal?.aborted) { + const partialMessage = aggregated?.message; + throw new ModelAbortError("Model invocation was aborted.", partialMessage); + } + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) chunk.message._updateId(`run-${runId}`); + } + if (aggregated === void 0) aggregated = chunk; + else aggregated = concat(aggregated, chunk); + if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens + } }; + } + if (parsedOptions.signal?.aborted) { + const partialMessage = aggregated?.message; + throw new ModelAbortError("Model invocation was aborted.", partialMessage); + } + if (aggregated === void 0) throw new Error("Received empty response from chat model call."); + if (outputVersion === "v1") aggregated.message = castStandardMessageContent(aggregated.message); + generations.push([aggregated]); + await runManagers?.[0].handleLLMEnd({ + generations, + llmOutput + }); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + else { + const results = await Promise.allSettled(baseMessages.map(async (messageList, i) => { + const generateResults = await this._generate(messageList, { + ...parsedOptions, + promptIndex: i + }, runManagers?.[i]); + if (outputVersion === "v1") for (const generation of generateResults.generations) generation.message = castStandardMessageContent(generation.message); + return generateResults; + })); + await Promise.all(results.map(async (pResult, i) => { + if (pResult.status === "fulfilled") { + const result = pResult.value; + for (const generation of result.generations) { + if (generation.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) generation.message._updateId(`run-${runId}`); + } + 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[i] = result.generations; + llmOutputs[i] = result.llmOutput; + return runManagers?.[i]?.handleLLMEnd({ + generations: [result.generations], + llmOutput: result.llmOutput + }); + } else { + await runManagers?.[i]?.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, cache, llmStringKey, parsedOptions, handledOptions }) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParamsWithDefaults(parsedOptions) + }; + const invocationParams = this.invocationParams(parsedOptions); + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: parsedOptions, + invocation_params: invocationParams, + batch_size: 1 + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); + const missingPromptIndices = []; + const cachedResults = (await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { + const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); + const result = await cache.lookup(prompt, llmStringKey); + if (result == null) missingPromptIndices.push(index); + return result; + }))).map((result, index) => ({ + result, + runManager: runManagers?.[index] + })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); + const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result) => { + if ("message" in result && isBaseMessage(result.message) && isAIMessage(result.message)) { + result.message.usage_metadata = { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0 + }; + if (outputVersion === "v1") result.message = castStandardMessageContent(result.message); + } + result.generationInfo = { + ...result.generationInfo, + tokenUsage: {} + }; + return result; + }); + if (result.length) await runManager?.handleLLMNewToken(result[0].text); + return runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true }); + } else { + await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true }); + return Promise.reject(promiseResult.reason); + } + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, + configurable: true + }); + return output; + } + /** + * Generates chat based on the input messages. + * @param messages An array of arrays of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generate(messages, options, callbacks) { + let parsedOptions; + if (Array.isArray(options)) parsedOptions = { stop: options }; + else parsedOptions = options; + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) return this._generateUncached(baseMessages, callOptions, runnableConfig); + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + messages: baseMessages, + cache, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig + }); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); + return cache.update(prompt, llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { + generations, + llmOutput + }; + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(_options) { + return {}; + } + _modelType() { + return "base_chat_model"; + } + /** + * Generates a prompt based on the input prompt values. + * @param promptValues An array of BasePromptValue instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generatePrompt(promptValues, options, callbacks) { + const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); + return this.generate(promptMessages, options, callbacks); + } + withStructuredOutput(outputSchema, config) { + if (typeof this.bindTools !== "function") throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); + if (config?.strict) throw new Error(`"strict" mode is not supported for this model by default.`); + const schema = outputSchema; + const name = config?.name; + const description = getSchemaDescription(schema) ?? "A function available to call."; + const method = config?.method; + const includeRaw = config?.includeRaw; + if (method === "jsonMode") throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); + let functionName = name ?? "extract"; + if (!isInteropZodSchema(schema) && !isSerializableSchema(schema) && "name" in schema) functionName = schema.name; + const asJsonSchema = isInteropZodSchema(schema) || isSerializableSchema(schema) ? toJsonSchema(schema) : schema; + const tools = [{ + type: "function", + function: { + name: functionName, + description, + parameters: asJsonSchema + } + }]; + return assembleStructuredOutputPipeline(this.bindTools(tools), RunnableLambda.from((input) => { + if (!AIMessageChunk.isInstance(input)) throw new Error("Input is not an AIMessageChunk."); + if (!input.tool_calls || input.tool_calls.length === 0) throw new Error("No tool calls found in the response."); + const toolCall = input.tool_calls.find((tc) => tc.name === functionName); + if (!toolCall) throw new Error(`No tool call found with name ${functionName}.`); + return toolCall.args; + }), includeRaw, includeRaw ? "StructuredOutputRunnable" : "StructuredOutput"); + } +}; +/** +* An abstract class that extends BaseChatModel and provides a simple +* implementation of _generate. +*/ +var SimpleChatModel = class extends BaseChatModel { + async _generate(messages, options, runManager) { + const message = new AIMessage(await this._call(messages, options, runManager)); + 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 + }] }; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/tools/types.js +/** +* Confirm whether the inputted tool is an instance of `StructuredToolInterface`. +* +* @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`. +* @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`. +*/ +function isStructuredTool(tool) { + return tool !== void 0 && Array.isArray(tool.lc_namespace); +} +/** +* Confirm whether the inputted tool is an instance of `RunnableToolLike`. +* +* @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`. +* @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`. +*/ +function isRunnableToolLike(tool) { + return tool !== void 0 && Runnable.isRunnable(tool) && "lc_name" in tool.constructor && typeof tool.constructor.lc_name === "function" && tool.constructor.lc_name() === "RunnableToolLike"; +} +/** +* Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`. +* +* @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`. +* @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`. +*/ +function isStructuredToolParams(tool) { + return !!tool && typeof tool === "object" && "name" in tool && "schema" in tool && (isInteropZodSchema(tool.schema) || tool.schema != null && typeof tool.schema === "object" && "type" in tool.schema && typeof tool.schema.type === "string" && [ + "null", + "boolean", + "object", + "array", + "number", + "string" + ].includes(tool.schema.type)); +} +/** +* Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams. +* It returns `is StructuredToolParams` since that is the most minimal interface of the three, +* while still containing the necessary properties to be passed to a LLM for tool calling. +* +* @param {unknown | undefined} tool The tool to check if it is a LangChain tool. +* @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool. +*/ +function isLangChainTool(tool) { + return isStructuredToolParams(tool) || isRunnableToolLike(tool) || isStructuredTool(tool); +} +//#endregion +//#region node_modules/@langchain/core/dist/tools/index.js +var tools_exports = /* @__PURE__ */ __exportAll({ + BaseToolkit: () => BaseToolkit, + DynamicStructuredTool: () => DynamicStructuredTool, + DynamicTool: () => DynamicTool, + StructuredTool: () => StructuredTool, + Tool: () => Tool, + ToolInputParsingException: () => ToolInputParsingException, + isLangChainTool: () => isLangChainTool, + isRunnableToolLike: () => isRunnableToolLike, + isStructuredTool: () => isStructuredTool, + isStructuredToolParams: () => isStructuredToolParams, + tool: () => tool +}); +/** +* Base class for Tools that accept input of any shape defined by a Zod schema. +*/ +var StructuredTool = class extends BaseLangChain { + /** + * Optional provider-specific extra fields for the tool. + * + * This is used to pass provider-specific configuration that doesn't fit into + * standard tool fields. + */ + extras; + /** + * Whether to return the tool's output directly. + * + * Setting this to true means that after the tool is called, + * an agent should stop looping. + */ + returnDirect = false; + verboseParsingErrors = false; + get lc_namespace() { + return ["langchain", "tools"]; + } + /** + * The tool response format. + * + * If "content" then the output of the tool is interpreted as the contents of a + * ToolMessage. If "content_and_artifact" then the output is expected to be a + * two-tuple corresponding to the (content, artifact) of a ToolMessage. + * + * @default "content" + */ + responseFormat = "content"; + /** + * Default config object for the tool runnable. + */ + defaultConfig; + constructor(fields) { + super(fields ?? {}); + this.verboseParsingErrors = fields?.verboseParsingErrors ?? this.verboseParsingErrors; + this.responseFormat = fields?.responseFormat ?? this.responseFormat; + this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig; + this.metadata = fields?.metadata ?? this.metadata; + this.extras = fields?.extras ?? this.extras; + } + /** + * Invokes the tool with the provided input and configuration. + * @param input The input for the tool. + * @param config Optional configuration for the tool. + * @returns A Promise that resolves with the tool's output. + */ + async invoke(input, config) { + let toolInput; + let enrichedConfig = ensureConfig(mergeConfigs(this.defaultConfig, config)); + if (_isToolCall(input)) { + toolInput = input.args; + enrichedConfig = { + ...enrichedConfig, + toolCall: input + }; + } else toolInput = input; + return this.call(toolInput, enrichedConfig); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.3.0. + * + * Calls the tool with the provided argument, configuration, and tags. It + * parses the input according to the schema, handles any errors, and + * manages callbacks. + * @param arg The input argument for the tool. + * @param configArg Optional configuration or callbacks for the tool. + * @param tags Optional tags for the tool. + * @returns A Promise that resolves with a string. + */ + async call(arg, configArg, tags) { + const inputForValidation = _isToolCall(arg) ? arg.args : arg; + let parsed; + if (isInteropZodSchema(this.schema)) try { + parsed = await interopParseAsync(this.schema, inputForValidation); + } catch (e) { + let message = `Received tool input did not match expected schema`; + if (this.verboseParsingErrors) message = `${message}\nDetails: ${e.message}`; + if (isInteropZodError(e)) message = `${message}\n\n${prettifyError(e)}`; + throw new ToolInputParsingException(message, JSON.stringify(arg)); + } + else { + const result = validate$4(inputForValidation, this.schema); + if (!result.valid) { + let message = `Received tool input did not match expected schema`; + if (this.verboseParsingErrors) message = `${message}\nDetails: ${result.errors.map((e) => `${e.keywordLocation}: ${e.error}`).join("\n")}`; + throw new ToolInputParsingException(message, JSON.stringify(arg)); + } + parsed = inputForValidation; + } + const config = parseCallbackConfigArg(configArg); + const callbackManager_ = CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose }); + let toolCallId; + if (_isToolCall(arg)) toolCallId = arg.id; + if (!toolCallId && _configHasToolCallId(config)) toolCallId = config.toolCall.id; + const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof arg === "string" ? arg : JSON.stringify(arg), config.runId, void 0, void 0, void 0, config.runName, toolCallId); + delete config.runId; + let result; + try { + const raw = await this._call(parsed, runManager, config); + result = isAsyncGenerator(raw) ? await consumeAsyncGenerator(raw, async (chunk) => { + try { + await runManager?.handleToolEvent(chunk); + } catch (streamError) { + await runManager?.handleToolError(streamError); + } + }) : raw; + } catch (e) { + await runManager?.handleToolError(e); + throw e; + } + let content; + let artifact; + if (this.responseFormat === "content_and_artifact") if (Array.isArray(result) && result.length === 2) [content, artifact] = result; + else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(result)}`); + else content = result; + const formattedOutput = _formatToolOutput({ + content, + artifact, + toolCallId, + name: this.name, + metadata: this.metadata + }); + await runManager?.handleToolEnd(formattedOutput); + return formattedOutput; + } +}; +/** +* Base class for Tools that accept input as a string. +*/ +var Tool = class extends StructuredTool { + schema = objectType({ input: stringType().optional() }).transform((obj) => obj.input); + constructor(fields) { + super(fields); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.3.0. + * + * Calls the tool with the provided argument and callbacks. It handles + * string inputs specifically. + * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema. + * @param callbacks Optional callbacks for the tool. + * @returns A Promise that resolves with a string. + */ + call(arg, callbacks) { + const structuredArg = typeof arg === "string" || arg == null ? { input: arg } : arg; + return super.call(structuredArg, callbacks); + } +}; +/** +* A tool that can be created dynamically from a function, name, and description. +*/ +var DynamicTool = class extends Tool { + static lc_name() { + return "DynamicTool"; + } + name; + description; + func; + constructor(fields) { + super(fields); + this.name = fields.name; + this.description = fields.description; + this.func = fields.func; + this.returnDirect = fields.returnDirect ?? this.returnDirect; + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.3.0. + */ + async call(arg, configArg) { + const config = parseCallbackConfigArg(configArg); + if (config.runName === void 0) config.runName = this.name; + return super.call(arg, config); + } + /** @ignore */ + _call(input, runManager, parentConfig) { + return this.func(input, runManager, parentConfig); + } +}; +/** +* A tool that can be created dynamically from a function, name, and +* description, designed to work with structured data. It extends the +* StructuredTool class and overrides the _call method to execute the +* provided function when the tool is called. +* +* Schema can be passed as Zod or JSON schema. The tool will not validate +* input if JSON schema is passed. +* +* @template SchemaT The input schema type for the tool (Zod schema or JSON schema). Defaults to `ToolInputSchemaBase`. +* @template SchemaOutputT The output type derived from the schema after parsing/validation. Defaults to `ToolInputSchemaOutputType`. +* @template SchemaInputT The input type derived from the schema before parsing. Defaults to `ToolInputSchemaInputType`. +* @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`. +* @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`. +*/ +var DynamicStructuredTool = class extends StructuredTool { + static lc_name() { + return "DynamicStructuredTool"; + } + description; + func; + schema; + constructor(fields) { + super(fields); + this.name = fields.name; + this.description = fields.description; + this.func = fields.func; + this.returnDirect = fields.returnDirect ?? this.returnDirect; + this.schema = fields.schema; + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.3.0. + */ + 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, parentConfig) { + return this.func(arg, runManager, parentConfig); + } +}; +/** +* Abstract base class for toolkits in LangChain. Toolkits are collections +* of tools that agents can use. Subclasses must implement the `tools` +* property to provide the specific tools for the toolkit. +*/ +var BaseToolkit = class { + getTools() { + return this.tools; + } +}; +function tool(func, fields) { + const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema); + const isStringJSONSchema = validatesOnlyStrings(fields.schema); + if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) return new DynamicTool({ + ...fields, + description: fields.description ?? fields.schema?.description ?? `${fields.name} tool`, + func: async (input, runManager, config) => { + return new Promise((resolve, reject) => { + const childConfig = patchConfig(config, { callbacks: runManager?.getChild() }); + AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + resolve(func(input, childConfig)); + } catch (e) { + reject(e); + } + }); + }); + } + }); + const schema = fields.schema; + const description = fields.description ?? fields.schema.description ?? `${fields.name} tool`; + return new DynamicStructuredTool({ + ...fields, + description, + schema, + func: async (input, runManager, config) => { + return new Promise((resolve, reject) => { + let listener; + const cleanup = () => { + if (config?.signal && listener) config.signal.removeEventListener("abort", listener); + }; + if (config?.signal) { + listener = () => { + cleanup(); + reject(getAbortSignalError(config.signal)); + }; + config.signal.addEventListener("abort", listener, { once: true }); + } + const childConfig = patchConfig(config, { callbacks: runManager?.getChild() }); + AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + const result = await func(input, childConfig); + if (isAsyncGenerator(result)) { + resolve(result); + return; + } + /** + * If the signal is aborted, we don't want to resolve the promise + * as the promise is already rejected. + */ + if (config?.signal?.aborted) { + cleanup(); + return; + } + cleanup(); + resolve(result); + } catch (e) { + cleanup(); + reject(e); + } + }); + }); + } + }); +} +function _isMessageContentBlockShaped(item) { + return typeof item === "object" && item !== null && "type" in item; +} +function _formatToolOutput(params) { + const { content, artifact, toolCallId, metadata } = params; + if (toolCallId && !isDirectToolOutput(content)) if (typeof content === "string" || Array.isArray(content) && content.every(_isMessageContentBlockShaped)) return new ToolMessage({ + status: "success", + content, + artifact, + tool_call_id: toolCallId, + name: params.name, + metadata + }); + else return new ToolMessage({ + status: "success", + content: _stringify(content), + artifact, + tool_call_id: toolCallId, + name: params.name, + metadata + }); + else return content; +} +function _stringify(content) { + try { + return JSON.stringify(content) ?? ""; + } catch (_noOp) { + return `${content}`; + } +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/function_calling.js +var function_calling_exports = /* @__PURE__ */ __exportAll({ + convertToOpenAIFunction: () => convertToOpenAIFunction, + convertToOpenAITool: () => convertToOpenAITool, + isLangChainTool: () => isLangChainTool, + isRunnableToolLike: () => isRunnableToolLike, + isStructuredTool: () => isStructuredTool, + isStructuredToolParams: () => isStructuredToolParams +}); +/** +* Formats a `StructuredTool` or `RunnableToolLike` instance into a format +* that is compatible with OpenAI function calling. If `StructuredTool` or +* `RunnableToolLike` has a zod schema, the output will be converted into a +* JSON schema, which is then used as the parameters for the OpenAI tool. +* +* @param {StructuredToolInterface | RunnableToolLike} tool The tool to convert to an OpenAI function. +* @returns {FunctionDefinition} The inputted tool in OpenAI function format. +*/ +function convertToOpenAIFunction(tool, fields) { + const fieldsCopy = typeof fields === "number" ? void 0 : fields; + return { + name: tool.name, + description: tool.description, + parameters: toJsonSchema(tool.schema), + ...fieldsCopy?.strict !== void 0 ? { strict: fieldsCopy.strict } : {} + }; +} +/** +* Formats a `StructuredTool` or `RunnableToolLike` instance into a +* format that is compatible with OpenAI tool calling. If `StructuredTool` or +* `RunnableToolLike` has a zod schema, the output will be converted into a +* JSON schema, which is then used as the parameters for the OpenAI tool. +* +* @param {StructuredToolInterface | Record | RunnableToolLike} tool The tool to convert to an OpenAI tool. +* @returns {ToolDefinition} The inputted tool in OpenAI tool format. +*/ +function convertToOpenAITool(tool, fields) { + const fieldsCopy = typeof fields === "number" ? void 0 : fields; + let toolDef; + if (isLangChainTool(tool)) toolDef = { + type: "function", + function: convertToOpenAIFunction(tool) + }; + else toolDef = tool; + if (fieldsCopy?.strict !== void 0) toolDef.function.strict = fieldsCopy.strict; + return toolDef; +} +//#endregion +//#region node_modules/@langchain/anthropic/dist/output_parsers.js +var AnthropicToolsOutputParser = class extends BaseLLMOutputParser { + static lc_name() { + return "AnthropicToolsOutputParser"; + } + lc_namespace = [ + "langchain", + "anthropic", + "output_parsers" + ]; + returnId = false; + /** The type of tool calls to return. */ + keyName; + /** Whether to return only the first tool call. */ + returnSingle = false; + zodSchema; + serializableSchema; + constructor(params) { + super(params); + this.keyName = params.keyName; + this.returnSingle = params.returnSingle ?? this.returnSingle; + this.zodSchema = params.zodSchema; + this.serializableSchema = params.serializableSchema; + } + async _validateResult(result) { + let parsedResult = result; + if (typeof result === "string") try { + parsedResult = JSON.parse(result); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(e.message)}`, result); + } + else parsedResult = result; + if (this.serializableSchema !== void 0) { + const validated = await this.serializableSchema["~standard"].validate(parsedResult); + if (validated.issues) throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(parsedResult, null, 2)}". Error: ${JSON.stringify(validated.issues)}`, JSON.stringify(parsedResult, null, 2)); + return validated.value; + } + if (this.zodSchema === void 0) return parsedResult; + const zodParsedResult = await interopSafeParseAsync(this.zodSchema, parsedResult); + if (zodParsedResult.success) return zodParsedResult.data; + else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(parsedResult, null, 2)); + } + async parseResult(generations) { + const tools = generations.flatMap((generation) => { + const { message } = generation; + if (!Array.isArray(message.content)) return []; + return extractToolCalls(message.content)[0]; + }); + if (tools[0] === void 0) throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser."); + const [tool] = tools; + return await this._validateResult(tool.args); + } +}; +function extractToolCalls(content) { + const toolCalls = []; + for (const block of content) if (block.type === "tool_use") toolCalls.push({ + name: block.name, + args: block.input, + id: block.id, + type: "tool_call" + }); + return toolCalls; +} +//#endregion +//#region node_modules/@langchain/anthropic/dist/utils/tools.js +function handleToolChoice(toolChoice) { + if (!toolChoice) return; + else if (toolChoice === "any" || toolChoice === "required") return { type: "any" }; + else if (toolChoice === "auto") return { type: "auto" }; + else if (toolChoice === "none") return { type: "none" }; + else if (typeof toolChoice === "string") return { + type: "tool", + name: toolChoice + }; + else return toolChoice; +} +var AnthropicToolExtrasSchema = object({ + cache_control: custom$1().optional().nullable(), + defer_loading: boolean().optional(), + input_examples: array(unknown()).optional(), + allowed_callers: array(unknown()).optional(), + strict: boolean().optional() +}); +/** +* Mapping of Anthropic tool types to their required beta feature flags. +* +* This constant defines which beta header is needed for specific tool types +* when making requests to the Anthropic API. Beta features are experimental +* capabilities that may change or be removed. +*/ +var ANTHROPIC_TOOL_BETAS = { + tool_search_tool_regex_20251119: "advanced-tool-use-2025-11-20", + tool_search_tool_bm25_20251119: "advanced-tool-use-2025-11-20", + memory_20250818: "context-management-2025-06-27", + web_fetch_20250910: "web-fetch-2025-09-10", + code_execution_20250825: "code-execution-2025-08-25", + computer_20251124: "computer-use-2025-11-24", + computer_20250124: "computer-use-2025-01-24", + mcp_toolset: "mcp-client-2025-11-20" +}; +//#endregion +//#region node_modules/@langchain/anthropic/dist/utils/content.js +function _isAnthropicThinkingBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "thinking"; +} +function _isAnthropicRedactedThinkingBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "redacted_thinking"; +} +function _isAnthropicCompactionBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "compaction"; +} +function _isAnthropicSearchResultBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "search_result"; +} +function _isAnthropicImageBlockParam(block) { + if (typeof block !== "object" || block == null) return false; + if (!("type" in block) || block.type !== "image") return false; + if (!("source" in block) || typeof block.source !== "object" || block.source == null) return false; + if (!("type" in block.source)) return false; + if (block.source.type === "base64") { + if (!("media_type" in block.source)) return false; + if (typeof block.source.media_type !== "string") return false; + if (!("data" in block.source)) return false; + if (typeof block.source.data !== "string") return false; + return true; + } + if (block.source.type === "url") { + if (!("url" in block.source)) return false; + if (typeof block.source.url !== "string") return false; + return true; + } + return false; +} +var standardContentBlockConverter = { + providerName: "anthropic", + fromStandardTextBlock(block) { + return { + type: "text", + text: block.text, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + }, + fromStandardImageBlock(block) { + if (block.source_type === "url") { + const data = parseBase64DataUrl({ + dataUrl: block.url, + asTypedArray: false + }); + if (data) return { + type: "image", + source: { + type: "base64", + data: data.data, + media_type: data.mime_type + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + else return { + type: "image", + source: { + type: "url", + url: block.url + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + } else if (block.source_type === "base64") return { + type: "image", + source: { + type: "base64", + data: block.data, + media_type: block.mime_type ?? "" + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + else throw new Error(`Unsupported image source type: ${block.source_type}`); + }, + fromStandardFileBlock(block) { + const mime_type = (block.mime_type ?? "").split(";")[0]; + if (block.source_type === "url") { + if (mime_type === "application/pdf" || mime_type === "") return { + type: "document", + source: { + type: "url", + url: block.url + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + throw new Error(`Unsupported file mime type for file url source: ${block.mime_type}`); + } else if (block.source_type === "text") if (mime_type === "text/plain" || mime_type === "") return { + type: "document", + source: { + type: "text", + data: block.text, + media_type: block.mime_type ?? "" + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + else throw new Error(`Unsupported file mime type for file text source: ${block.mime_type}`); + else if (block.source_type === "base64") if (mime_type === "application/pdf" || mime_type === "") return { + type: "document", + source: { + type: "base64", + data: block.data, + media_type: "application/pdf" + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + else if ([ + "image/jpeg", + "image/png", + "image/gif", + "image/webp" + ].includes(mime_type)) return { + type: "document", + source: { + type: "content", + content: [{ + type: "image", + source: { + type: "base64", + data: block.data, + media_type: mime_type + } + }] + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + else throw new Error(`Unsupported file mime type for file base64 source: ${block.mime_type}`); + else throw new Error(`Unsupported file source type: ${block.source_type}`); + } +}; +//#endregion +//#region node_modules/@langchain/anthropic/dist/utils/index.js +var iife = (fn) => fn(); +//#endregion +//#region node_modules/@langchain/anthropic/dist/utils/standard.js +function _isStandardAnnotation(annotation) { + return typeof annotation === "object" && annotation !== null && "type" in annotation && annotation.type === "citation"; +} +function _formatStandardCitations(annotations) { + function* iterateAnnotations() { + for (const annotation of annotations) if (_isStandardAnnotation(annotation)) { + if (annotation.source === "char") yield { + type: "char_location", + file_id: annotation.url ?? "", + start_char_index: annotation.startIndex ?? 0, + end_char_index: annotation.endIndex ?? 0, + document_title: annotation.title ?? null, + document_index: 0, + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "page") yield { + type: "page_location", + file_id: annotation.url ?? "", + start_page_number: annotation.startIndex ?? 0, + end_page_number: annotation.endIndex ?? 0, + document_title: annotation.title ?? null, + document_index: 0, + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "block") yield { + type: "content_block_location", + file_id: annotation.url ?? "", + start_block_index: annotation.startIndex ?? 0, + end_block_index: annotation.endIndex ?? 0, + document_title: annotation.title ?? null, + document_index: 0, + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "url") yield { + type: "web_search_result_location", + url: annotation.url ?? "", + title: annotation.title ?? null, + encrypted_index: String(annotation.startIndex ?? 0), + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "search") yield { + type: "search_result_location", + title: annotation.title ?? null, + start_block_index: annotation.startIndex ?? 0, + end_block_index: annotation.endIndex ?? 0, + search_result_index: 0, + source: annotation.source ?? "", + cited_text: annotation.citedText ?? "" + }; + } + } + return Array.from(iterateAnnotations()); +} +function _formatBase64Data(data) { + if (typeof data === "string") return data; + else return _encodeUint8Array(data); +} +function _encodeUint8Array(data) { + const output = []; + for (let i = 0, { length } = data; i < length; i++) output.push(String.fromCharCode(data[i])); + return btoa(output.join("")); +} +function _normalizeMimeType(mimeType) { + return (mimeType ?? "").split(";")[0].toLowerCase(); +} +function _extractMetadataValue(metadata, key) { + if (metadata !== void 0 && metadata !== null && typeof metadata === "object" && key in metadata) return metadata[key]; +} +function _applyDocumentMetadata(block, metadata) { + const cacheControl = _extractMetadataValue(metadata, "cache_control"); + if (cacheControl !== void 0) block.cache_control = cacheControl; + const citations = _extractMetadataValue(metadata, "citations"); + if (citations !== void 0) block.citations = citations; + const context = _extractMetadataValue(metadata, "context"); + if (context !== void 0) block.context = context; + const title = _extractMetadataValue(metadata, "title"); + if (title !== void 0) block.title = title; + return block; +} +function _applyImageMetadata(block, metadata) { + const cacheControl = _extractMetadataValue(metadata, "cache_control"); + if (cacheControl !== void 0) block.cache_control = cacheControl; + return block; +} +function _hasAllowedImageMimeType(mimeType) { + return (/* @__PURE__ */ new Set([ + "image/jpeg", + "image/png", + "image/gif", + "image/webp" + ])).has(mimeType); +} +function _formatStandardContent(message) { + const result = []; + const responseMetadata = message.response_metadata; + const isAnthropicMessage = "model_provider" in responseMetadata && responseMetadata?.model_provider === "anthropic"; + for (const block of message.contentBlocks) if (block.type === "text") if (block.annotations) result.push({ + type: "text", + text: block.text, + citations: _formatStandardCitations(block.annotations) + }); + else result.push({ + type: "text", + text: block.text + }); + else if (block.type === "tool_call") result.push({ + type: "tool_use", + id: block.id ?? "", + name: block.name, + input: block.args + }); + else if (block.type === "tool_call_chunk") { + const input = iife(() => { + if (typeof block.args !== "string") return block.args; + try { + return JSON.parse(block.args); + } catch { + return {}; + } + }); + result.push({ + type: "tool_use", + id: block.id ?? "", + name: block.name ?? "", + input + }); + } else if (block.type === "reasoning" && isAnthropicMessage) result.push({ + type: "thinking", + thinking: block.reasoning, + signature: String(block.signature) + }); + else if (block.type === "server_tool_call" && isAnthropicMessage) { + if (block.name === "web_search") result.push({ + type: "server_tool_use", + name: block.name, + id: block.id ?? "", + input: block.args + }); + else if (block.name === "code_execution") result.push({ + type: "server_tool_use", + name: block.name, + id: block.id ?? "", + input: block.args + }); + } else if (block.type === "server_tool_call_result" && isAnthropicMessage) { + if (block.name === "web_search" && Array.isArray(block.output.urls)) { + const content = block.output.urls.map((url) => ({ + type: "web_search_result", + title: "", + encrypted_content: "", + url + })); + result.push({ + type: "web_search_tool_result", + tool_use_id: block.toolCallId ?? "", + content + }); + } else if (block.name === "code_execution") result.push({ + type: "code_execution_tool_result", + tool_use_id: block.toolCallId ?? "", + content: block.output + }); + else if (block.name === "mcp_tool_result") result.push({ + type: "mcp_tool_result", + tool_use_id: block.toolCallId ?? "", + content: block.output + }); + } else if (block.type === "audio") throw new Error("Anthropic does not support audio content blocks."); + else if (block.type === "file") { + const metadata = block.metadata; + if (block.fileId) { + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "file", + file_id: block.fileId + } + }, metadata)); + continue; + } + if (block.url) { + const mimeType = _normalizeMimeType(block.mimeType); + if (mimeType === "application/pdf" || mimeType === "") { + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "url", + url: block.url + } + }, metadata)); + continue; + } + } + if (block.data) { + const mimeType = _normalizeMimeType(block.mimeType); + if (mimeType === "" || mimeType === "application/pdf") result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "base64", + data: _formatBase64Data(block.data), + media_type: "application/pdf" + } + }, metadata)); + else if (mimeType === "text/plain") result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "text", + data: _formatBase64Data(block.data), + media_type: "text/plain" + } + }, metadata)); + else if (_hasAllowedImageMimeType(mimeType)) result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "content", + content: [{ + type: "image", + source: { + type: "base64", + data: _formatBase64Data(block.data), + media_type: mimeType + } + }] + } + }, metadata)); + else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${mimeType}`); + continue; + } + throw new Error("File content block must include a fileId, url, or data property."); + } else if (block.type === "image") { + const metadata = block.metadata; + if (block.fileId) { + result.push(_applyImageMetadata({ + type: "image", + source: { + type: "file", + file_id: block.fileId + } + }, metadata)); + continue; + } + if (block.url) { + result.push(_applyImageMetadata({ + type: "image", + source: { + type: "url", + url: block.url + } + }, metadata)); + continue; + } + if (block.data) { + const mimeType = _normalizeMimeType(block.mimeType) || "image/png"; + if (_hasAllowedImageMimeType(mimeType)) result.push(_applyImageMetadata({ + type: "image", + source: { + type: "base64", + data: _formatBase64Data(block.data), + media_type: mimeType + } + }, metadata)); + continue; + } + throw new Error("Image content block must include a fileId, url, or data property."); + } else if (block.type === "video") {} else if (block.type === "text-plain") { + if (block.data) result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "text", + data: _formatBase64Data(block.data), + media_type: "text/plain" + } + }, block.metadata)); + } else if (block.type === "non_standard" && isAnthropicMessage) result.push(block.value); + return result; +} +//#endregion +//#region node_modules/@langchain/anthropic/dist/utils/message_inputs.js +function _formatImage(imageUrl) { + const parsed = parseBase64DataUrl({ dataUrl: imageUrl }); + if (parsed) return { + type: "base64", + media_type: parsed.mime_type, + data: parsed.data + }; + let parsedUrl; + try { + parsedUrl = new URL(imageUrl); + } catch { + throw new Error([ + `Malformed image URL: ${JSON.stringify(imageUrl)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`, + "Example: data:image/png;base64,/9j/4AAQSk...", + "Example: https://example.com/image.jpg" + ].join("\n\n")); + } + if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") return { + type: "url", + url: imageUrl + }; + throw new Error([ + `Invalid image URL protocol: ${JSON.stringify(parsedUrl.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`, + "Example: data:image/png;base64,/9j/4AAQSk...", + "Example: https://example.com/image.jpg" + ].join("\n\n")); +} +function _ensureMessageContents(messages) { + const updatedMsgs = []; + for (const message of messages) if (message._getType() === "tool") if (typeof message.content === "string") { + const previousMessage = updatedMsgs[updatedMsgs.length - 1]; + if (previousMessage?._getType() === "human" && Array.isArray(previousMessage.content) && "type" in previousMessage.content[0] && previousMessage.content[0].type === "tool_result") previousMessage.content.push({ + type: "tool_result", + content: message.content, + tool_use_id: message.tool_call_id + }); + else updatedMsgs.push(new HumanMessage({ content: [{ + type: "tool_result", + content: message.content, + tool_use_id: message.tool_call_id + }] })); + } else updatedMsgs.push(new HumanMessage({ content: [{ + type: "tool_result", + ...message.content != null ? { content: _formatContent(message) } : {}, + tool_use_id: message.tool_call_id + }] })); + else updatedMsgs.push(message); + return updatedMsgs; +} +function _convertLangChainToolCallToAnthropic(toolCall) { + if (toolCall.id === void 0) throw new Error(`Anthropic requires all tool calls to have an "id".`); + return { + type: "tool_use", + id: toolCall.id, + name: toolCall.name, + input: toolCall.args + }; +} +function* _formatContentBlocks(content, toolCalls) { + const toolTypes = [ + "bash_code_execution_tool_result", + "input_json_delta", + "server_tool_use", + "text_editor_code_execution_tool_result", + "tool_result", + "tool_use", + "web_search_result", + "web_search_tool_result" + ]; + const textTypes = ["text", "text_delta"]; + for (const contentPart of content) { + if (isDataContentBlock(contentPart)) yield convertToProviderContentBlock(contentPart, standardContentBlockConverter); + const cacheControl = "cache_control" in contentPart ? contentPart.cache_control : void 0; + if (contentPart.type === "image_url") { + let source; + if (typeof contentPart.image_url === "string") source = _formatImage(contentPart.image_url); + else if (typeof contentPart.image_url === "object" && contentPart.image_url !== null && "url" in contentPart.image_url && typeof contentPart.image_url.url === "string") source = _formatImage(contentPart.image_url.url); + if (source) yield { + type: "image", + source, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (_isAnthropicImageBlockParam(contentPart)) yield contentPart; + else if (contentPart.type === "image") { + let source; + if ("url" in contentPart && typeof contentPart.url === "string") source = _formatImage(contentPart.url); + else if ("data" in contentPart && (typeof contentPart.data === "string" || contentPart.data instanceof Uint8Array)) source = { + type: "base64", + media_type: "mimeType" in contentPart && typeof contentPart.mimeType === "string" ? contentPart.mimeType : "image/jpeg", + data: typeof contentPart.data === "string" ? contentPart.data : Buffer.from(contentPart.data).toString("base64") + }; + else if ("fileId" in contentPart && typeof contentPart.fileId === "string") source = { + type: "file", + file_id: contentPart.fileId + }; + if (source) yield { + type: "image", + source, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (contentPart.type === "file") { + let source; + if ("url" in contentPart && typeof contentPart.url === "string") source = { + type: "url", + url: contentPart.url + }; + else if ("data" in contentPart && (typeof contentPart.data === "string" || contentPart.data instanceof Uint8Array)) source = { + type: "base64", + media_type: "mimeType" in contentPart && typeof contentPart.mimeType === "string" ? contentPart.mimeType : "application/pdf", + data: typeof contentPart.data === "string" ? contentPart.data : Buffer.from(contentPart.data).toString("base64") + }; + else if ("fileId" in contentPart && typeof contentPart.fileId === "string") source = { + type: "file", + file_id: contentPart.fileId + }; + if (source) yield { + type: "document", + source, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (contentPart.type === "document") yield { + ...contentPart, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + else if (_isAnthropicThinkingBlock(contentPart)) yield { + type: "thinking", + thinking: contentPart.thinking, + signature: contentPart.signature, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + else if (_isAnthropicRedactedThinkingBlock(contentPart)) yield { + type: "redacted_thinking", + data: contentPart.data, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + else if (_isAnthropicCompactionBlock(contentPart)) yield { + type: "compaction", + content: contentPart.content, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + else if (_isAnthropicSearchResultBlock(contentPart)) yield { + type: "search_result", + title: contentPart.title, + source: contentPart.source, + ..."cache_control" in contentPart && contentPart.cache_control ? { cache_control: contentPart.cache_control } : {}, + ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {}, + content: contentPart.content + }; + else if (textTypes.find((t) => t === contentPart.type) && "text" in contentPart) yield { + type: "text", + text: contentPart.text, + ...cacheControl ? { cache_control: cacheControl } : {}, + ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {} + }; + else if (toolTypes.find((t) => t === contentPart.type)) { + const contentPartCopy = { ...contentPart }; + if (contentPartCopy.type === "input_json_delta") continue; + if (contentPartCopy.type === "tool_use" && typeof contentPartCopy.input === "string") { + const matchingToolCall = toolCalls?.find((tc) => tc.id === contentPartCopy.id); + if (matchingToolCall) contentPartCopy.input = matchingToolCall.args; + else contentPartCopy.input = content.filter((nestedContentPart) => nestedContentPart.index === contentPartCopy.index && nestedContentPart.type === "input_json_delta" && typeof nestedContentPart.input === "string").reduce((accumulator, nestedContentPart) => accumulator + nestedContentPart.input, contentPartCopy.input); + } + if ("index" in contentPartCopy) delete contentPartCopy.index; + if ("input" in contentPartCopy) { + if (typeof contentPartCopy.input === "string") try { + contentPartCopy.input = JSON.parse(contentPartCopy.input); + } catch { + contentPartCopy.input = {}; + } + } + yield { + ...contentPartCopy, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (contentPart.type === "container_upload") yield { + ...contentPart, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } +} +function _formatContent(message, toolCalls) { + const { content } = message; + if (typeof content === "string") return content; + else return Array.from(_formatContentBlocks(content, toolCalls)); +} +/** +* Formats messages as a prompt for the model. +* Used in LangSmith, export is important here. +* @param messages The base messages to format as a prompt. +* @returns The formatted prompt. +*/ +function _convertMessagesToAnthropicPayload(messages) { + const mergedMessages = _ensureMessageContents(messages); + let system; + if (mergedMessages.length > 0 && mergedMessages[0]._getType() === "system") system = messages[0].content; + return { + messages: mergeMessages((system !== void 0 ? mergedMessages.slice(1) : mergedMessages).map((message) => { + let role; + if (message._getType() === "human") role = "user"; + else if (message._getType() === "ai") role = "assistant"; + else if (message._getType() === "tool") role = "user"; + else if (message._getType() === "system") throw new Error("System messages are only permitted as the first passed message."); + else throw new Error(`Message type "${message.type}" is not supported.`); + if (AIMessage.isInstance(message) && message.response_metadata?.output_version === "v1") return { + role, + content: _formatStandardContent(message) + }; + if (AIMessage.isInstance(message) && !!message.tool_calls?.length) if (typeof message.content === "string") if (message.content === "") return { + role, + content: message.tool_calls.map(_convertLangChainToolCallToAnthropic) + }; + else return { + role, + content: [{ + type: "text", + text: message.content + }, ...message.tool_calls.map(_convertLangChainToolCallToAnthropic)] + }; + else { + const { content } = message; + const formattedContent = _formatContent(message, message.tool_calls); + const formattedContentArr = Array.isArray(formattedContent) ? formattedContent : [{ + type: "text", + text: formattedContent + }]; + const missingToolCalls = message.tool_calls.filter((toolCall) => !content.find((contentPart) => (contentPart.type === "tool_use" || contentPart.type === "input_json_delta" || contentPart.type === "server_tool_use") && contentPart.id === toolCall.id)); + return { + role, + content: [...formattedContentArr, ...missingToolCalls.map(_convertLangChainToolCallToAnthropic)] + }; + } + else return { + role, + content: _formatContent(message, AIMessage.isInstance(message) ? message.tool_calls : void 0) + }; + })), + system + }; +} +function mergeMessages(messages) { + if (!messages || messages.length <= 1) return messages; + const result = []; + let currentMessage = messages[0]; + const normalizeContent = (content) => { + if (typeof content === "string") return [{ + type: "text", + text: content + }]; + return content; + }; + const isToolResultMessage = (msg) => { + if (msg.role !== "user") return false; + if (typeof msg.content === "string") return false; + return Array.isArray(msg.content) && msg.content.every((item) => item.type === "tool_result"); + }; + for (let i = 1; i < messages.length; i += 1) { + const nextMessage = messages[i]; + if (isToolResultMessage(currentMessage) && isToolResultMessage(nextMessage)) currentMessage = { + ...currentMessage, + content: [...normalizeContent(currentMessage.content), ...normalizeContent(nextMessage.content)] + }; + else { + result.push(currentMessage); + currentMessage = nextMessage; + } + } + result.push(currentMessage); + return result; +} +//#endregion +//#region node_modules/@langchain/anthropic/dist/utils/params.js +var ADAPTIVE_ONLY_MODEL_PREFIXES = [ + "claude-opus-4-7", + "claude-opus-4-8", + "claude-opus-5", + "claude-fable-5", + "claude-mythos-5", + "claude-mythos-preview" +]; +function modelStartsWithAnyPrefix(model, prefixes) { + return model ? prefixes.some((prefix) => model.startsWith(prefix)) : false; +} +function isThinkingEnabled(thinking) { + return thinking.type === "enabled" || thinking.type === "adaptive"; +} +function isOpus47Model(model) { + return modelStartsWithAnyPrefix(model, ["claude-opus-4-7"]); +} +function isAdaptiveOnlyModel(model) { + return modelStartsWithAnyPrefix(model, ADAPTIVE_ONLY_MODEL_PREFIXES); +} +function getTaskBudgetBetas(model, outputConfig) { + const hasTaskBudget = outputConfig && typeof outputConfig === "object" && "task_budget" in outputConfig && outputConfig.task_budget != null; + return isOpus47Model(model) && hasTaskBudget ? ["task-budgets-2026-03-13"] : []; +} +function validateInvocationParamCompatibility(fields) { + const { model, thinking, outputConfig, topK, topP, temperature } = fields; + const adaptiveOnlyModel = isAdaptiveOnlyModel(model); + const modelName = model ?? "this model"; + if (adaptiveOnlyModel && thinking.type === "enabled") throw new Error(`thinking.type="enabled" is not supported for ${modelName}; use thinking.type="adaptive" instead`); + if (adaptiveOnlyModel && typeof thinking === "object" && thinking != null && "budget_tokens" in thinking) throw new Error(`thinking.budget_tokens is not supported for ${modelName}; use outputConfig.effort instead`); + if (modelStartsWithAnyPrefix(model, ["claude-opus-5"]) && thinking.type === "disabled" && (outputConfig?.effort === "xhigh" || outputConfig?.effort === "max")) throw new Error(`thinking.type="disabled" is not supported for ${modelName} with outputConfig.effort="${outputConfig.effort}"; use thinking.type="adaptive" or omit thinking instead`); + if (adaptiveOnlyModel) { + if (topK !== void 0) throw new Error(`topK is not supported for ${modelName}; omit topK/topP/temperature or use model prompting instead`); + if (topP !== void 0 && topP !== 1) throw new Error(`topP is not supported for ${modelName} when set to non-default values`); + if (temperature !== void 0 && temperature !== 1) throw new Error(`temperature is not supported for ${modelName} when set to non-default values`); + } + if (isThinkingEnabled(thinking)) { + if (topK !== void 0) throw new Error("topK is not supported when thinking is enabled"); + if (topP !== void 0) throw new Error("topP is not supported when thinking is enabled"); + if (temperature !== void 0 && temperature !== 1) throw new Error("temperature is not supported when thinking is enabled"); + } +} +function getSamplingParams(fields) { + const { model, thinking, topK, topP, temperature } = fields; + const output = {}; + if (isThinkingEnabled(thinking) || isAdaptiveOnlyModel(model)) return output; + if (temperature !== void 0) output.temperature = temperature; + if (topK !== void 0) output.top_k = topK; + if (topP !== void 0) output.top_p = topP; + return output; +} +//#endregion +//#region node_modules/@langchain/anthropic/dist/utils/message_outputs.js +function _makeMessageChunkFromAnthropicEvent(data, fields) { + const response_metadata = { model_provider: "anthropic" }; + if (data.type === "message_start") { + const { content, usage, ...additionalKwargs } = data.message; + const filteredAdditionalKwargs = {}; + for (const [key, value] of Object.entries(additionalKwargs)) if (value !== void 0 && value !== null) filteredAdditionalKwargs[key] = value; + const { input_tokens, output_tokens, ...rest } = usage ?? {}; + const usageMetadata = buildUsageMetadata(usage); + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [], + additional_kwargs: filteredAdditionalKwargs, + usage_metadata: fields.streamUsage ? usageMetadata : void 0, + response_metadata: { + ...response_metadata, + usage: { ...rest } + }, + id: data.message.id + }) }; + } else if (data.type === "message_delta") { + const usageMetadata = { + input_tokens: 0, + output_tokens: data.usage.output_tokens, + total_tokens: data.usage.output_tokens + }; + const responseMetadata = "context_management" in data.delta ? { context_management: data.delta.context_management } : void 0; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [], + response_metadata: responseMetadata, + additional_kwargs: { ...data.delta }, + usage_metadata: fields.streamUsage ? usageMetadata : void 0 + }) }; + } else if (data.type === "content_block_start" && [ + "tool_use", + "document", + "server_tool_use", + "web_search_tool_result" + ].includes(data.content_block.type)) { + const contentBlock = data.content_block; + let toolCallChunks; + if (contentBlock.type === "tool_use") toolCallChunks = [{ + id: contentBlock.id, + index: data.index, + name: contentBlock.name, + args: "" + }]; + else toolCallChunks = []; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.content_block, + input: contentBlock.type === "server_tool_use" || contentBlock.type === "tool_use" ? "" : void 0 + }], + response_metadata, + additional_kwargs: {}, + tool_call_chunks: toolCallChunks + }) }; + } else if (data.type === "content_block_delta" && [ + "text_delta", + "citations_delta", + "thinking_delta", + "signature_delta" + ].includes(data.delta.type)) if (fields.coerceContentToString && "text" in data.delta) return { chunk: new AIMessageChunk({ content: data.delta.text }) }; + else { + const contentBlock = data.delta; + if ("citation" in contentBlock) { + contentBlock.citations = [contentBlock.citation]; + delete contentBlock.citation; + } + if (contentBlock.type === "thinking_delta" || contentBlock.type === "signature_delta") return { chunk: new AIMessageChunk({ + content: [{ + index: data.index, + ...contentBlock, + type: "thinking" + }], + response_metadata + }) }; + return { chunk: new AIMessageChunk({ + content: [{ + index: data.index, + ...contentBlock, + type: "text" + }], + response_metadata + }) }; + } + else if (data.type === "content_block_delta" && data.delta.type === "input_json_delta") return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + input: data.delta.partial_json, + type: data.delta.type + }], + response_metadata, + additional_kwargs: {}, + tool_call_chunks: [{ + index: data.index, + args: data.delta.partial_json + }] + }) }; + else if (data.type === "content_block_start" && data.content_block.type === "text") { + const content = data.content_block?.text; + if (content !== void 0) return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? content : [{ + index: data.index, + ...data.content_block + }], + response_metadata, + additional_kwargs: {} + }) }; + } else if (data.type === "content_block_start" && data.content_block.type === "redacted_thinking") return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.content_block + }], + response_metadata + }) }; + else if (data.type === "content_block_start" && data.content_block.type === "thinking") { + const content = data.content_block.thinking; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? content : [{ + index: data.index, + ...data.content_block + }], + response_metadata + }) }; + } else if (data.type === "content_block_start" && _isAnthropicCompactionBlock(data.content_block)) return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.content_block + }], + response_metadata + }) }; + else if (data.type === "content_block_delta" && data.delta.type === "compaction_delta") return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.delta, + type: "compaction" + }], + response_metadata + }) }; + return null; +} +function anthropicResponseToChatMessages(messages, additionalKwargs) { + const response_metadata = { + ...additionalKwargs, + model_provider: "anthropic" + }; + const usage = additionalKwargs.usage; + const usageMetadata = usage != null ? buildUsageMetadata(usage) : void 0; + if (messages.length === 1 && messages[0].type === "text") return [{ + text: messages[0].text, + message: new AIMessage({ + content: messages[0].text, + additional_kwargs: additionalKwargs, + usage_metadata: usageMetadata, + response_metadata, + id: additionalKwargs.id + }) + }]; + else return [{ + text: "", + message: new AIMessage({ + content: messages, + additional_kwargs: additionalKwargs, + tool_calls: extractToolCalls(messages), + usage_metadata: usageMetadata, + response_metadata, + id: additionalKwargs.id + }) + }]; +} +function buildUsageMetadata(usage) { + const cacheCreationInputTokens = usage.cache_creation_input_tokens ?? 0; + const cacheReadInputTokens = usage.cache_read_input_tokens ?? 0; + const totalInputTokens = usage.input_tokens + cacheCreationInputTokens + cacheReadInputTokens; + return { + input_tokens: totalInputTokens, + output_tokens: usage.output_tokens, + total_tokens: totalInputTokens + usage.output_tokens, + input_token_details: { + cache_creation: cacheCreationInputTokens, + cache_read: cacheReadInputTokens + } + }; +} +//#endregion +//#region node_modules/@langchain/anthropic/dist/utils/errors.js +function addLangChainErrorFields(error, lc_error_code) { + error.lc_error_code = lc_error_code; + error.message = `${error.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\n`; + return error; +} +function wrapAnthropicClientError(e) { + let error; + if (e.status === 400 && typeof e.message === "string" && e.message.includes("prompt is too long")) error = addLangChainErrorFields(ContextOverflowError.fromError(e), "CONTEXT_OVERFLOW"); + else if (e.status === 400 && e.message.includes("tool")) error = addLangChainErrorFields(e, "INVALID_TOOL_RESULTS"); + else if (e.status === 401) error = addLangChainErrorFields(e, "MODEL_AUTHENTICATION"); + else if (e.status === 404) error = addLangChainErrorFields(e, "MODEL_NOT_FOUND"); + else if (e.status === 429) error = addLangChainErrorFields(e, "MODEL_RATE_LIMIT"); + else error = e; + return error; +} +//#endregion +//#region node_modules/@langchain/anthropic/dist/profiles.js +var PROFILES = { + "claude-sonnet-4-6": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-haiku-4-5": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-6": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-fable-5": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-8": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-1": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-5": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-5-20250929": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-5-20251101": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-haiku-4-5-20251001": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-7": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-5": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-5": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-5": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-1-20250805": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + } +}; +//#endregion +//#region node_modules/@langchain/anthropic/dist/utils/stream_events.js +/** +* Convert an async iterable of raw Anthropic stream events into +* LangChain `ChatModelStreamEvent`s with typed deltas. +*/ +async function* convertAnthropicStream(source, options = {}) { + const shouldStreamUsage = options.streamUsage ?? true; + const blockAccumulators = /* @__PURE__ */ new Map(); + let usageSnapshot; + let stopReason = null; + for await (const data of source) switch (data.type) { + case "message_start": { + const { usage, id, model } = data.message; + if (usage && shouldStreamUsage) usageSnapshot = buildUsageSnapshot(usage); + yield { + event: "message-start", + id, + ...usageSnapshot ? { usage: usageSnapshot } : {} + }; + yield { + event: "provider", + provider: "anthropic", + name: "message_start", + payload: { + model, + id + } + }; + break; + } + case "message_delta": + stopReason = data.delta.stop_reason; + if (shouldStreamUsage && data.usage) { + if (!usageSnapshot) usageSnapshot = { + input_tokens: 0, + output_tokens: data.usage.output_tokens, + total_tokens: data.usage.output_tokens + }; + else usageSnapshot = { + ...usageSnapshot, + output_tokens: usageSnapshot.output_tokens + data.usage.output_tokens, + total_tokens: usageSnapshot.input_tokens + usageSnapshot.output_tokens + data.usage.output_tokens + }; + yield { + event: "usage", + usage: usageSnapshot + }; + } + if ("context_management" in data.delta && data.delta.context_management) yield { + event: "provider", + provider: "anthropic", + name: "context_management", + payload: data.delta.context_management + }; + break; + case "message_stop": + yield { + event: "message-finish", + reason: mapStopReason(stopReason), + ...usageSnapshot ? { usage: usageSnapshot } : {}, + metadata: { model_provider: "anthropic" } + }; + break; + case "content_block_start": { + const { index, content_block } = data; + const mapped = mapBlockToContentBlock(content_block, index); + blockAccumulators.set(index, { ...mapped }); + yield { + event: "content-block-start", + index, + content: mapped + }; + break; + } + case "content_block_delta": { + const { index, delta } = data; + const acc = blockAccumulators.get(index); + if (!acc) break; + const { contentDelta, accumulated } = applyAnthropicDelta(acc, delta); + blockAccumulators.set(index, accumulated); + yield { + event: "content-block-delta", + index, + delta: contentDelta + }; + break; + } + case "content_block_stop": { + const { index } = data; + const acc = blockAccumulators.get(index); + if (!acc) break; + yield { + event: "content-block-finish", + index, + content: finalizeBlock(acc) + }; + blockAccumulators.delete(index); + break; + } + default: + yield { + event: "provider", + provider: "anthropic", + name: data.type, + payload: data + }; + break; + } +} +function mapStopReason(stopReason) { + switch (stopReason) { + case "end_turn": + case "stop_sequence": return "stop"; + case "tool_use": return "tool_use"; + case "max_tokens": return "length"; + default: return "stop"; + } +} +function buildUsageSnapshot(usage) { + const cacheCreation = usage.cache_creation_input_tokens ?? 0; + const cacheRead = usage.cache_read_input_tokens ?? 0; + const totalInput = usage.input_tokens + cacheCreation + cacheRead; + return { + input_tokens: totalInput, + output_tokens: usage.output_tokens, + total_tokens: totalInput + usage.output_tokens, + input_token_details: { + cache_creation: cacheCreation, + cache_read: cacheRead + } + }; +} +function mapBlockToContentBlock(block, index) { + switch (block.type) { + case "text": return { + type: "text", + text: block.text ?? "", + index + }; + case "thinking": return { + type: "reasoning", + reasoning: block.thinking ?? "", + index + }; + case "redacted_thinking": return { + type: "non_standard", + value: { ...block }, + index + }; + case "tool_use": return { + type: "tool_call_chunk", + id: block.id, + name: block.name, + args: "", + index + }; + case "server_tool_use": return { + type: "server_tool_call_chunk", + id: block.id, + name: block.name, + args: "", + index + }; + default: return { + type: "non_standard", + value: { ...block }, + index + }; + } +} +/** +* Map an Anthropic content_block_delta to a content block delta +* and update the accumulated state. +*/ +function applyAnthropicDelta(accumulated, delta) { + switch (delta.type) { + case "text_delta": return { + contentDelta: { + type: "text-delta", + text: delta.text + }, + accumulated: { + ...accumulated, + text: (accumulated.text ?? "") + delta.text + } + }; + case "thinking_delta": return { + contentDelta: { + type: "reasoning-delta", + reasoning: delta.thinking + }, + accumulated: { + ...accumulated, + reasoning: (accumulated.reasoning ?? "") + delta.thinking + } + }; + case "input_json_delta": { + const newArgs = (accumulated.args ?? "") + delta.partial_json; + return { + contentDelta: { + type: "block-delta", + fields: { + type: accumulated.type, + args: newArgs + } + }, + accumulated: { + ...accumulated, + args: newArgs + } + }; + } + case "citations_delta": { + const annotations = [...accumulated.annotations ?? [], delta.citation]; + return { + contentDelta: { + type: "block-delta", + fields: { + type: accumulated.type, + annotations + } + }, + accumulated: { + ...accumulated, + annotations + } + }; + } + case "signature_delta": return { + contentDelta: { + type: "block-delta", + fields: { + type: accumulated.type, + signature: delta.signature + } + }, + accumulated: { + ...accumulated, + signature: delta.signature + } + }; + case "compaction_delta": return { + contentDelta: { + type: "block-delta", + fields: { + type: "non_standard", + value: { + ...accumulated.value ?? {}, + compaction: delta + } + } + }, + accumulated: { + ...accumulated, + value: { + ...accumulated.value ?? {}, + compaction: delta + } + } + }; + default: return { + contentDelta: { + type: "block-delta", + fields: { + type: accumulated.type, + ...delta + } + }, + accumulated + }; + } +} +function finalizeBlock(accumulated) { + if (accumulated.type === "tool_call_chunk" || accumulated.type === "server_tool_call_chunk") { + const finalType = accumulated.type === "tool_call_chunk" ? "tool_call" : "server_tool_call"; + let parsedArgs; + try { + parsedArgs = JSON.parse(accumulated.args || "{}"); + } catch { + return { + type: "invalid_tool_call", + id: accumulated.id, + name: accumulated.name, + args: accumulated.args, + error: "Failed to parse tool call arguments as JSON" + }; + } + return { + type: finalType, + id: accumulated.id, + name: accumulated.name, + args: parsedArgs + }; + } + const { index: _index, ...rest } = accumulated; + return rest; +} +//#endregion +//#region node_modules/@langchain/anthropic/dist/chat_models.js +var MODEL_DEFAULT_MAX_OUTPUT_TOKENS = { + "claude-opus-5": 16384, + "claude-fable-5": 16384, + "claude-mythos-5": 16384, + "claude-mythos-preview": 16384, + "claude-opus-4-7": 16384, + "claude-opus-4-6": 16384, + "claude-sonnet-4-6": 16384, + "claude-opus-4-5": 16384, + "claude-sonnet-4-5": 16384, + "claude-haiku-4-5": 16384, + "claude-opus-4-1": 16384, + "claude-sonnet-4": 16384, + "claude-opus-4": 16384, + "claude-3-7-sonnet": 8192, + "claude-3-5-sonnet": 8192, + "claude-3-5-haiku": 8192, + "claude-3-opus": 4096, + "claude-3-sonnet": 4096, + "claude-3-haiku": 4096 +}; +var FALLBACK_MAX_OUTPUT_TOKENS = 4096; +function defaultMaxOutputTokensForModel(model) { + if (!model) return FALLBACK_MAX_OUTPUT_TOKENS; + return Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(([key]) => model.startsWith(key))?.[1] ?? FALLBACK_MAX_OUTPUT_TOKENS; +} +function _toolsInParams(params) { + return !!(params.tools && params.tools.length > 0); +} +function _documentsInParams(params) { + for (const message of params.messages ?? []) { + if (typeof message.content === "string") continue; + for (const block of message.content ?? []) if (typeof block === "object" && block != null && block.type === "document" && typeof block.citations === "object" && block.citations?.enabled) return true; + } + return false; +} +function _thinkingInParams(params) { + return !!(params.thinking && (params.thinking.type === "enabled" || params.thinking.type === "adaptive")); +} +function _compactionInParams(params) { + return !!params.context_management?.edits?.some((e) => e.type === "compact_20260112"); +} +function isAnthropicTool(tool) { + return "input_schema" in tool; +} +function isBuiltinTool(tool) { + return typeof tool === "object" && tool !== null && "type" in tool && ("name" in tool || "mcp_server_name" in tool) && typeof tool.type === "string" && [ + "text_editor_", + "computer_", + "bash_", + "web_search_", + "web_fetch_", + "str_replace_editor_", + "str_replace_based_edit_tool_", + "code_execution_", + "memory_", + "tool_search_", + "mcp_toolset" + ].some((prefix) => typeof tool.type === "string" && tool.type.startsWith(prefix)); +} +function _combineBetas(a, b, ...rest) { + return Array.from(/* @__PURE__ */ new Set([ + ...a ?? [], + ...b ?? [], + ...rest.flatMap((x) => Array.from(x)) + ])); +} +function extractToken(chunk) { + if (typeof chunk.content === "string") return chunk.content; + else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "input" in chunk.content[0]) return typeof chunk.content[0].input === "string" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input); + else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "text" in chunk.content[0] && typeof chunk.content[0].text === "string") return chunk.content[0].text; +} +/** +* Anthropic chat model integration. +* +* Setup: +* Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`. +* +* ```bash +* npm install @langchain/anthropic +* export ANTHROPIC_API_KEY="your-api-key" +* ``` +* +* ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor) +* +* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html) +* +* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. +* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below: +* +* ```typescript +* // When calling `.bind`, call options should be passed via the first argument +* const llmWithArgsBound = llm.bindTools([...]).withConfig({ +* stop: ["\n"], +* }); +* +* // When calling `.bindTools`, call options should be passed via the second argument +* const llmWithTools = llm.bindTools( +* [...], +* { +* tool_choice: "auto", +* } +* ); +* ``` +* +* ## Examples +* +*
+* Instantiate +* +* ```typescript +* import { ChatAnthropic } from '@langchain/anthropic'; +* +* const llm = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* temperature: 0, +* maxTokens: undefined, +* maxRetries: 2, +* // apiKey: "...", +* // baseUrl: "...", +* // other params... +* }); +* ``` +*
+* +*
+* +*
+* Invoking +* +* ```typescript +* const input = `Translate "I love programming" into French.`; +* +* // Models also accept a list of chat messages or a formatted prompt +* const result = await llm.invoke(input); +* console.log(result); +* ``` +* +* ```txt +* AIMessage { +* "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", +* "content": "Here's the translation to French:\n\nJ'adore la programmation.", +* "response_metadata": { +* "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", +* "model": "claude-sonnet-4-5-20250929", +* "stop_reason": "end_turn", +* "stop_sequence": null, +* "usage": { +* "input_tokens": 25, +* "output_tokens": 19 +* }, +* "type": "message", +* "role": "assistant" +* }, +* "usage_metadata": { +* "input_tokens": 25, +* "output_tokens": 19, +* "total_tokens": 44 +* } +* } +* ``` +*
+* +*
+* +*
+* Streaming Chunks +* +* ```typescript +* for await (const chunk of await llm.stream(input)) { +* console.log(chunk); +* } +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", +* "content": "", +* "additional_kwargs": { +* "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", +* "type": "message", +* "role": "assistant", +* "model": "claude-sonnet-4-5-20250929" +* }, +* "usage_metadata": { +* "input_tokens": 25, +* "output_tokens": 1, +* "total_tokens": 26 +* } +* } +* AIMessageChunk { +* "content": "", +* } +* AIMessageChunk { +* "content": "Here", +* } +* AIMessageChunk { +* "content": "'s", +* } +* AIMessageChunk { +* "content": " the translation to", +* } +* AIMessageChunk { +* "content": " French:\n\nJ", +* } +* AIMessageChunk { +* "content": "'adore la programmation", +* } +* AIMessageChunk { +* "content": ".", +* } +* AIMessageChunk { +* "content": "", +* "additional_kwargs": { +* "stop_reason": "end_turn", +* "stop_sequence": null +* }, +* "usage_metadata": { +* "input_tokens": 0, +* "output_tokens": 19, +* "total_tokens": 19 +* } +* } +* ``` +*
+* +*
+* +*
+* Aggregate Streamed Chunks +* +* ```typescript +* import { AIMessageChunk } from '@langchain/core/messages'; +* import { concat } from '@langchain/core/utils/stream'; +* +* const stream = await llm.stream(input); +* let full: AIMessageChunk | undefined; +* for await (const chunk of stream) { +* full = !full ? chunk : concat(full, chunk); +* } +* console.log(full); +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", +* "content": "Here's the translation to French:\n\nJ'adore la programmation.", +* "additional_kwargs": { +* "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", +* "type": "message", +* "role": "assistant", +* "model": "claude-sonnet-4-5-20250929", +* "stop_reason": "end_turn", +* "stop_sequence": null +* }, +* "usage_metadata": { +* "input_tokens": 25, +* "output_tokens": 20, +* "total_tokens": 45 +* } +* } +* ``` +*
+* +*
+* +*
+* Bind tools +* +* ```typescript +* import { z } from 'zod'; +* +* const GetWeather = { +* name: "GetWeather", +* description: "Get the current weather in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const GetPopulation = { +* name: "GetPopulation", +* description: "Get the current population in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); +* const aiMsg = await llmWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?" +* ); +* console.log(aiMsg.tool_calls); +* ``` +* +* ```txt +* [ +* { +* name: 'GetWeather', +* args: { location: 'Los Angeles, CA' }, +* id: 'toolu_01WjW3Dann6BPJVtLhovdBD5', +* type: 'tool_call' +* }, +* { +* name: 'GetWeather', +* args: { location: 'New York, NY' }, +* id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe', +* type: 'tool_call' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'Los Angeles, CA' }, +* id: 'toolu_0165qYWBA2VFyUst5RA18zew', +* type: 'tool_call' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'New York, NY' }, +* id: 'toolu_01PGNyP33vxr13tGqr7i3rDo', +* type: 'tool_call' +* } +* ] +* ``` +*
+* +*
+* +*
+* Tool Search +* +* Tool search enables Claude to dynamically discover and load tools on-demand +* instead of loading all tool definitions upfront. This is useful when you have +* many tools but want to avoid the overhead of sending all definitions with every request. +* +* ```typescript +* import { ChatAnthropic } from "@langchain/anthropic"; +* +* const model = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* }); +* +* const tools = [ +* // Tool search server tool +* { +* type: "tool_search_tool_regex_20251119", +* name: "tool_search_tool_regex", +* }, +* // Tools with defer_loading are loaded on-demand +* { +* name: "get_weather", +* description: "Get the current weather for a location", +* input_schema: { +* type: "object", +* properties: { +* location: { type: "string", description: "City name" }, +* unit: { +* type: "string", +* enum: ["celsius", "fahrenheit"], +* }, +* }, +* required: ["location"], +* }, +* defer_loading: true, // Tool is loaded on-demand +* }, +* { +* name: "search_files", +* description: "Search through files in the workspace", +* input_schema: { +* type: "object", +* properties: { +* query: { type: "string" }, +* }, +* required: ["query"], +* }, +* defer_loading: true, // Tool is loaded on-demand +* }, +* ]; +* +* const modelWithTools = model.bindTools(tools); +* const response = await modelWithTools.invoke("What's the weather in San Francisco?"); +* ``` +* +* You can also use the `tool()` helper with the `extras` field: +* +* ```typescript +* import { tool } from "@langchain/core/tools"; +* import { z } from "zod"; +* +* const getWeather = tool( +* async (input) => `Weather in ${input.location}`, +* { +* name: "get_weather", +* description: "Get weather for a location", +* schema: z.object({ location: z.string() }), +* extras: { defer_loading: true }, +* } +* ); +* ``` +* +* **Note:** The required `advanced-tool-use-2025-11-20` beta header is automatically +* appended to the request when using tool search tools. +* +* **Best practices:** +* - Tools with `defer_loading: true` are only loaded when Claude discovers them via search +* - Keep your 3-5 most frequently used tools as non-deferred for optimal performance +* - Both regex and bm25 variants search tool names, descriptions, and argument info +* +* See the {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool | Claude docs} +* for more information. +*
+* +*
+* +*
+* Structured Output +* +* ChatAnthropic supports structured output through two main approaches: +* +* 1. **Function Calling with `withStructuredOutput()`**: Uses Anthropic's tool calling +* under the hood to constrain outputs to a specific schema. +* 2. **JSON Schema Mode**: Uses Anthropic's native JSON schema support for direct +* structured output without tool calling overhead. +* +* **Using withStructuredOutput (Function Calling)** +* +* This method leverages Anthropic's tool calling capabilities to ensure the model +* returns data matching your schema: +* +* ```typescript +* import { z } from 'zod'; +* +* const Joke = z.object({ +* setup: z.string().describe("The setup of the joke"), +* punchline: z.string().describe("The punchline to the joke"), +* rating: z.number().optional().describe("How funny the joke is, from 1 to 10") +* }).describe('Joke to tell user.'); +* +* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); +* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); +* console.log(jokeResult); +* ``` +* +* ```txt +* { +* setup: "Why don't cats play poker in the jungle?", +* punchline: 'Too many cheetahs!', +* rating: 7 +* } +* ``` +* +* **Using JSON Schema Mode** +* +* For more direct control, you can use Anthropic's native JSON schema support by +* passing `method: "jsonSchema"`: +* +* ```typescript +* import { z } from 'zod'; +* +* const RecipeSchema = z.object({ +* recipeName: z.string().describe("Name of the recipe"), +* ingredients: z.array(z.string()).describe("List of ingredients needed"), +* steps: z.array(z.string()).describe("Cooking steps in order"), +* prepTime: z.number().describe("Preparation time in minutes") +* }); +* +* const structuredLlm = llm.withStructuredOutput(RecipeSchema, { +* method: "jsonSchema" +* }); +* +* const recipe = await structuredLlm.invoke( +* "Give me a simple recipe for chocolate chip cookies" +* ); +* console.log(recipe); +* ``` +* +* ```txt +* { +* recipeName: 'Classic Chocolate Chip Cookies', +* ingredients: [ +* '2 1/4 cups all-purpose flour', +* '1 cup butter, softened', +* ... +* ], +* steps: [ +* 'Preheat oven to 375°F', +* 'Mix butter and sugars until creamy', +* ... +* ], +* prepTime: 15 +* } +* ``` +*
+* +*
+* +*
+* Multimodal +* +* ```typescript +* import { HumanMessage } from '@langchain/core/messages'; +* +* const imageUrl = "https://example.com/image.jpg"; +* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); +* const base64Image = Buffer.from(imageData).toString('base64'); +* +* const message = new HumanMessage({ +* content: [ +* { type: "text", text: "describe the weather in this image" }, +* { +* type: "image_url", +* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, +* }, +* ] +* }); +* +* const imageDescriptionAiMsg = await llm.invoke([message]); +* console.log(imageDescriptionAiMsg.content); +* ``` +* +* ```txt +* The weather in this image appears to be beautiful and clear. The sky is a vibrant blue with scattered white clouds, suggesting a sunny and pleasant day. The clouds are wispy and light, indicating calm conditions without any signs of storms or heavy weather. The bright green grass on the rolling hills looks lush and well-watered, which could mean recent rainfall or good growing conditions. Overall, the scene depicts a perfect spring or early summer day with mild temperatures, plenty of sunshine, and gentle breezes - ideal weather for enjoying the outdoors or for plant growth. +* ``` +*
+* +*
+* +*
+* Usage Metadata +* +* ```typescript +* const aiMsgForMetadata = await llm.invoke(input); +* console.log(aiMsgForMetadata.usage_metadata); +* ``` +* +* ```txt +* { input_tokens: 25, output_tokens: 19, total_tokens: 44 } +* ``` +*
+* +*
+* +*
+* Stream Usage Metadata +* +* ```typescript +* const streamForMetadata = await llm.stream( +* input, +* { +* streamUsage: true +* } +* ); +* let fullForMetadata: AIMessageChunk | undefined; +* for await (const chunk of streamForMetadata) { +* fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk); +* } +* console.log(fullForMetadata?.usage_metadata); +* ``` +* +* ```txt +* { input_tokens: 25, output_tokens: 20, total_tokens: 45 } +* ``` +*
+* +*
+* +*
+* Response Metadata +* +* ```typescript +* const aiMsgForResponseMetadata = await llm.invoke(input); +* console.log(aiMsgForResponseMetadata.response_metadata); +* ``` +* +* ```txt +* { +* id: 'msg_01STxeQxJmp4sCSpioD6vK3L', +* model: 'claude-sonnet-4-5-20250929', +* stop_reason: 'end_turn', +* stop_sequence: null, +* usage: { input_tokens: 25, output_tokens: 19 }, +* type: 'message', +* role: 'assistant' +* } +* ``` +*
+* +*
+*/ +var ChatAnthropicMessages = class extends BaseChatModel { + static lc_name() { + return "ChatAnthropic"; + } + get lc_secrets() { + return { + anthropicApiKey: "ANTHROPIC_API_KEY", + apiKey: "ANTHROPIC_API_KEY" + }; + } + get lc_aliases() { + return { modelName: "model" }; + } + lc_serializable = true; + anthropicApiKey; + apiKey; + apiUrl; + temperature; + topK; + topP; + maxTokens; + modelName = "claude-sonnet-4-5-20250929"; + model = "claude-sonnet-4-5-20250929"; + invocationKwargs; + stopSequences; + streaming = false; + clientOptions; + thinking = { type: "disabled" }; + /** + * Whether `thinking` was explicitly configured by the user. When it was not, + * the default `{ type: "disabled" }` is kept off the request so that models + * which reject an explicit disabled value (e.g. adaptive-only models) are not + * sent an unsupported parameter. + */ + thinkingExplicitlySet = false; + contextManagement; + outputConfig; + inferenceGeo; + batchClient; + streamingClient; + streamUsage = true; + betas; + /** + * Optional method that returns an initialized underlying Anthropic client. + * Useful for accessing Anthropic models hosted on other cloud services + * such as Google Vertex. + */ + createClient; + constructor(modelOrFields, fieldsArg) { + const fields = typeof modelOrFields === "string" ? { + ...fieldsArg ?? {}, + model: modelOrFields + } : modelOrFields ?? {}; + super(fields ?? {}); + this._addVersion("@langchain/anthropic", "1.5.2"); + this.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? getEnvironmentVariable$1("ANTHROPIC_API_KEY"); + if (!this.anthropicApiKey && !fields?.createClient) throw new Error("Anthropic API key not found"); + this.clientOptions = fields?.clientOptions ?? {}; + /** Keep anthropicApiKey for backwards compatibility */ + this.apiKey = this.anthropicApiKey; + this.apiUrl = fields?.anthropicApiUrl; + /** Keep modelName for backwards compatibility */ + this.modelName = fields?.model ?? fields?.modelName ?? this.model; + this.model = this.modelName; + this.invocationKwargs = fields?.invocationKwargs ?? {}; + this.topP = fields?.topP ?? this.topP; + this.temperature = fields?.temperature ?? this.temperature; + this.topK = fields?.topK ?? this.topK; + this.maxTokens = fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model); + this.stopSequences = fields?.stopSequences ?? this.stopSequences; + this.streaming = fields?.streaming ?? false; + this.streamUsage = fields?.streamUsage ?? this.streamUsage; + if (fields?.thinking !== void 0) { + this.thinking = fields.thinking; + this.thinkingExplicitlySet = true; + } + this.contextManagement = fields?.contextManagement ?? this.contextManagement; + this.outputConfig = fields?.outputConfig ?? this.outputConfig; + this.inferenceGeo = fields?.inferenceGeo ?? this.inferenceGeo; + this.betas = fields?.betas ?? this.betas; + this.createClient = fields?.createClient ?? ((options) => new Anthropic(options)); + } + getLsParams(options) { + const params = this.invocationParams(options); + return { + ls_provider: "anthropic", + ls_model_name: this.model, + ls_model_type: "chat", + ls_temperature: params.temperature ?? void 0, + ls_max_tokens: params.max_tokens ?? void 0, + ls_stop: options.stop + }; + } + /** + * Formats LangChain StructuredTools to AnthropicTools. + * + * @param {ChatAnthropicCallOptions["tools"]} tools The tools to format + * @param fields Optional `strict` flag applied to every formatted custom tool. + * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed. + */ + formatStructuredToolToAnthropic(tools, fields) { + if (!tools) return; + return tools.map((tool) => { + if (isLangChainTool(tool) && tool.extras?.providerToolDefinition) return tool.extras.providerToolDefinition; + if (isBuiltinTool(tool)) return tool; + if (isAnthropicTool(tool)) { + if (fields?.strict !== void 0) return { + ...tool, + strict: fields.strict + }; + return tool; + } + if (isOpenAITool(tool)) { + const functionStrict = "strict" in tool.function && typeof tool.function.strict === "boolean" ? tool.function.strict : void 0; + const strict = fields?.strict ?? functionStrict; + return { + name: tool.function.name, + description: tool.function.description, + input_schema: tool.function.parameters, + ...strict !== void 0 ? { strict } : {} + }; + } + if (isLangChainTool(tool)) { + const { strict: extrasStrict, ...restExtras } = tool.extras ? AnthropicToolExtrasSchema.parse(tool.extras) : {}; + const strict = fields?.strict ?? extrasStrict; + return { + name: tool.name, + description: tool.description, + input_schema: isInteropZodSchema(tool.schema) ? toJsonSchema(tool.schema) : tool.schema, + ...restExtras, + ...strict !== void 0 ? { strict } : {} + }; + } + throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool, null, 2)}`); + }); + } + bindTools(tools, kwargs) { + return this.withConfig({ + tools: this.formatStructuredToolToAnthropic(tools, { strict: kwargs?.strict }), + ...kwargs + }); + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(options) { + const tool_choice = handleToolChoice(options?.tool_choice); + const toolBetas = options?.tools?.reduce((acc, tool) => { + if (typeof tool === "object" && "type" in tool && tool.type in ANTHROPIC_TOOL_BETAS) { + const beta = ANTHROPIC_TOOL_BETAS[tool.type]; + if (!acc.includes(beta)) return [...acc, beta]; + } + return acc; + }, []); + const mergedOutputConfig = (() => { + const base = { + ...this.outputConfig, + ...options?.outputConfig + }; + if (options?.outputFormat && !base.format) base.format = options.outputFormat; + return Object.keys(base).length > 0 ? base : void 0; + })(); + const compactionBetas = this.contextManagement?.edits?.some((e) => e.type === "compact_20260112") ? ["compact-2026-01-12"] : []; + const taskBudgetBetas = getTaskBudgetBetas(this.model, mergedOutputConfig); + const output = { + model: this.model, + stop_sequences: options?.stop ?? this.stopSequences, + stream: this.streaming, + max_tokens: this.maxTokens, + tools: this.formatStructuredToolToAnthropic(options?.tools, { strict: options?.strict }), + tool_choice, + thinking: this.thinkingExplicitlySet ? this.thinking : void 0, + context_management: this.contextManagement, + ...this.invocationKwargs, + container: options?.container, + betas: _combineBetas(this.betas, options?.betas, toolBetas ?? [], compactionBetas, taskBudgetBetas), + output_config: mergedOutputConfig, + inference_geo: options?.inferenceGeo ?? this.inferenceGeo, + mcp_servers: options?.mcp_servers, + cache_control: options?.cache_control + }; + validateInvocationParamCompatibility({ + model: this.model, + thinking: this.thinking, + outputConfig: mergedOutputConfig, + topK: this.topK, + topP: this.topP, + temperature: this.temperature + }); + Object.assign(output, getSamplingParams({ + model: this.model, + thinking: this.thinking, + topK: this.topK, + topP: this.topP, + temperature: this.temperature + })); + return output; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.model, + ...this.invocationParams() + }; + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return { + model_name: this.model, + ...this.invocationParams() + }; + } + async *_streamResponseChunks(messages, options, runManager) { + const params = this.invocationParams(options); + const formattedMessages = _convertMessagesToAnthropicPayload(messages); + const payload = { + ...params, + ...formattedMessages, + stream: true + }; + const coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload) && !_compactionInParams(payload); + const stream = await this.createStreamWithRetry(payload, { + headers: options.headers, + signal: options.signal + }); + for await (const data of stream) { + if (options.signal?.aborted) { + stream.controller.abort(); + return; + } + const shouldStreamUsage = this.streamUsage ?? options.streamUsage; + const result = _makeMessageChunkFromAnthropicEvent(data, { + streamUsage: shouldStreamUsage, + coerceContentToString + }); + if (!result) continue; + const { chunk } = result; + const token = extractToken(chunk); + const generationChunk = new ChatGenerationChunk({ + message: new AIMessageChunk({ + content: chunk.content, + additional_kwargs: chunk.additional_kwargs, + tool_call_chunks: chunk.tool_call_chunks, + usage_metadata: shouldStreamUsage ? chunk.usage_metadata : void 0, + response_metadata: chunk.response_metadata, + id: chunk.id + }), + text: token ?? "" + }); + yield generationChunk; + await runManager?.handleLLMNewToken(token ?? "", void 0, void 0, void 0, void 0, { chunk: generationChunk }); + } + } + /** + * Native implementation of the content-block-centric streaming protocol + * for Anthropic. + * + * Maps Anthropic's native SSE events directly to {@link ChatModelStreamEvent} + * without going through the legacy `_streamResponseChunks` bridge. This + * provides: + * - Explicit lifecycle events (start/delta/finish) for every content block + * - Fully-qualified accumulated content blocks on each delta + * - Usage snapshots as they become available + * - Provider passthrough for unrecognized Anthropic events + */ + async *_streamChatModelEvents(messages, options, _runManager) { + const params = this.invocationParams(options); + const formattedMessages = _convertMessagesToAnthropicPayload(messages); + const payload = { + ...params, + ...formattedMessages, + stream: true + }; + const stream = await this.createStreamWithRetry(payload, { + headers: options.headers, + signal: options.signal + }); + const shouldStreamUsage = this.streamUsage ?? options.streamUsage; + const abortableStream = async function* (source, signal) { + for await (const data of source) { + if (signal?.aborted) { + source.controller?.abort(); + return; + } + yield data; + } + }; + yield* convertAnthropicStream(abortableStream(stream, options.signal), { streamUsage: shouldStreamUsage ?? true }); + } + /** @ignore */ + async _generateNonStreaming(messages, params, requestOptions) { + const formattedMessages = _convertMessagesToAnthropicPayload(messages); + const { content, ...additionalKwargs } = await this.completionWithRetry({ + ...params, + stream: false, + ...formattedMessages + }, requestOptions); + const generations = anthropicResponseToChatMessages(content, additionalKwargs); + const { role: _role, type: _type, ...rest } = additionalKwargs; + return { + generations, + llmOutput: rest + }; + } + /** @ignore */ + async _generate(messages, options, runManager) { + options.signal?.throwIfAborted(); + if (this.stopSequences && options.stop) throw new Error(`"stopSequence" parameter found in input and default params`); + const params = this.invocationParams(options); + if (params.stream) { + let finalChunk; + const stream = this._streamResponseChunks(messages, options, runManager); + for await (const chunk of stream) if (finalChunk === void 0) finalChunk = chunk; + else finalChunk = finalChunk.concat(chunk); + if (finalChunk === void 0) throw new Error("No chunks returned from Anthropic API."); + return { generations: [{ + text: finalChunk.text, + message: finalChunk.message + }] }; + } else return this._generateNonStreaming(messages, params, { + signal: options.signal, + headers: options.headers + }); + } + /** + * Creates a streaming request with retry. + * @param request The parameters for creating a completion. + * @param options + * @returns A streaming request. + */ + async createStreamWithRetry(request, options) { + if (!this.streamingClient) { + const options_ = this.apiUrl ? { baseURL: this.apiUrl } : void 0; + this.streamingClient = this.createClient({ + dangerouslyAllowBrowser: true, + ...this.clientOptions, + ...options_, + apiKey: this.apiKey, + maxRetries: 0 + }); + } + const { betas, ...rest } = request; + const makeCompletionRequest = async () => { + try { + if (request?.betas?.length) return await this.streamingClient.beta.messages.create({ + ...rest, + betas, + ...this.invocationKwargs, + stream: true + }, options); + return await this.streamingClient.messages.create({ + ...rest, + ...this.invocationKwargs, + stream: true + }, options); + } catch (e) { + throw wrapAnthropicClientError(e); + } + }; + return this.caller.call(makeCompletionRequest); + } + /** @ignore */ + async completionWithRetry(request, options) { + if (!this.batchClient) { + const options = this.apiUrl ? { baseURL: this.apiUrl } : void 0; + this.batchClient = this.createClient({ + dangerouslyAllowBrowser: true, + ...this.clientOptions, + ...options, + apiKey: this.apiKey, + maxRetries: 0 + }); + } + const { betas, ...rest } = request; + const makeCompletionRequest = async () => { + try { + if (request?.betas?.length) return await this.batchClient.beta.messages.create({ + ...rest, + ...this.invocationKwargs, + betas + }, options); + return await this.batchClient.messages.create({ + ...rest, + ...this.invocationKwargs + }, options); + } catch (e) { + throw wrapAnthropicClientError(e); + } + }; + return this.caller.callWithOptions({ signal: options.signal ?? void 0 }, makeCompletionRequest); + } + _llmType() { + return "anthropic"; + } + /** + * Return profiling information for the model. + * + * Provides information about the model's capabilities and constraints, + * including token limits, multimodal support, and advanced features like + * tool calling and structured output. + * + * @returns {ModelProfile} An object describing the model's capabilities and constraints + * + * @example + * ```typescript + * const model = new ChatAnthropic({ model: "claude-opus-4-0" }); + * const profile = model.profile; + * console.log(profile.maxInputTokens); // 200000 + * console.log(profile.imageInputs); // true + * ``` + */ + get profile() { + return PROFILES[this.model] ?? {}; + } + withStructuredOutput(outputSchema, config) { + let llm; + let outputParser; + const { schema, name, includeRaw } = { + ...config, + schema: outputSchema + }; + let method = config?.method ?? "functionCalling"; + if (config?.strict !== void 0 && method !== "functionCalling") throw new Error(`Argument \`strict\` is only supported for \`method\` = "functionCalling" on Anthropic models. Got method = "${method}".`); + if (method === "jsonMode") { + console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`); + method = "jsonSchema"; + } + if (method === "jsonSchema") { + outputParser = createContentParser(schema); + const jsonSchema = transformJSONSchema(toJsonSchema(schema)); + llm = this.withConfig({ + outputVersion: "v0", + outputConfig: { format: { + type: "json_schema", + schema: jsonSchema + } }, + ls_structured_output_format: { + kwargs: { method: "json_schema" }, + schema: jsonSchema + } + }); + } else if (method === "functionCalling") { + let functionName = name ?? "extract"; + let tools; + if (isInteropZodSchema(schema) || isSerializableSchema(schema)) { + const jsonSchema = toJsonSchema(schema); + tools = [{ + name: functionName, + description: jsonSchema.description ?? "A function available to call.", + input_schema: jsonSchema + }]; + } else if (typeof schema.name === "string" && typeof schema.description === "string" && typeof schema.input_schema === "object" && schema.input_schema != null) { + tools = [schema]; + functionName = schema.name; + } else tools = [{ + name: functionName, + description: schema.description ?? "", + input_schema: schema + }]; + outputParser = createFunctionCallingParser(schema, functionName, AnthropicToolsOutputParser); + if (this.thinking?.type === "enabled" || this.thinking?.type === "adaptive") { + const thinkingAdmonition = "Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called."; + console.warn(thinkingAdmonition); + llm = this.withConfig({ + outputVersion: "v0", + tools, + ls_structured_output_format: { + kwargs: { method: "functionCalling" }, + schema: toJsonSchema(schema) + }, + ...config?.strict !== void 0 ? { strict: config.strict } : {} + }); + const raiseIfNoToolCalls = (message) => { + if (!message.tool_calls || message.tool_calls.length === 0) throw new Error(thinkingAdmonition); + return message; + }; + llm = llm.pipe(raiseIfNoToolCalls); + } else llm = this.withConfig({ + outputVersion: "v0", + tools, + tool_choice: { + type: "tool", + name: functionName + }, + ls_structured_output_format: { + kwargs: { method: "functionCalling" }, + schema: toJsonSchema(schema) + }, + ...config?.strict !== void 0 ? { strict: config.strict } : {} + }); + } else throw new TypeError(`Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`); + return assembleStructuredOutputPipeline(llm, outputParser, includeRaw, includeRaw ? "StructuredOutputRunnable" : "ChatAnthropicStructuredOutput"); + } +}; +var ChatAnthropic = class extends ChatAnthropicMessages {}; +discriminatedUnion("command", [ + object({ + command: literal("view"), + path: string() + }), + object({ + command: literal("create"), + path: string(), + file_text: string() + }), + object({ + command: literal("str_replace"), + path: string(), + old_str: string(), + new_str: string() + }), + object({ + command: literal("insert"), + path: string(), + insert_line: number(), + insert_text: string() + }), + object({ + command: literal("delete"), + path: string() + }), + object({ + command: literal("rename"), + old_path: string(), + new_path: string() + }) +]); +discriminatedUnion("command", [ + object({ + command: literal("view"), + path: string(), + view_range: tuple([number(), number()]).optional() + }), + object({ + command: literal("str_replace"), + path: string(), + old_str: string(), + new_str: string() + }), + object({ + command: literal("create"), + path: string(), + file_text: string() + }), + object({ + command: literal("insert"), + path: string(), + insert_line: number(), + new_str: string() + }) +]); +var coordinateSchema = tuple([number(), number()]); +var ComputerScreenshotActionSchema = object({ action: literal("screenshot") }); +var ComputerLeftClickActionSchema = object({ + action: literal("left_click"), + coordinate: coordinateSchema +}); +var ComputerRightClickActionSchema = object({ + action: literal("right_click"), + coordinate: coordinateSchema +}); +var ComputerMiddleClickActionSchema = object({ + action: literal("middle_click"), + coordinate: coordinateSchema +}); +var ComputerDoubleClickActionSchema = object({ + action: literal("double_click"), + coordinate: coordinateSchema +}); +var ComputerTripleClickActionSchema = object({ + action: literal("triple_click"), + coordinate: coordinateSchema +}); +var ComputerLeftClickDragActionSchema = object({ + action: literal("left_click_drag"), + start_coordinate: coordinateSchema, + end_coordinate: coordinateSchema +}); +var ComputerLeftMouseDownActionSchema = object({ + action: literal("left_mouse_down"), + coordinate: coordinateSchema +}); +var ComputerLeftMouseUpActionSchema = object({ + action: literal("left_mouse_up"), + coordinate: coordinateSchema +}); +var ComputerScrollActionSchema = object({ + action: literal("scroll"), + coordinate: coordinateSchema, + scroll_direction: _enum([ + "up", + "down", + "left", + "right" + ]), + scroll_amount: number() +}); +var ComputerTypeActionSchema = object({ + action: literal("type"), + text: string() +}); +var ComputerKeyActionSchema = object({ + action: literal("key"), + key: string() +}); +var ComputerMouseMoveActionSchema = object({ + action: literal("mouse_move"), + coordinate: coordinateSchema +}); +var ComputerHoldKeyActionSchema = object({ + action: literal("hold_key"), + key: string() +}); +var ComputerWaitActionSchema = object({ + action: literal("wait"), + duration: number().optional() +}); +var ComputerZoomActionSchema = object({ + action: literal("zoom"), + region: tuple([ + number(), + number(), + number(), + number() + ]) +}); +discriminatedUnion("action", [ + ComputerScreenshotActionSchema, + ComputerLeftClickActionSchema, + ComputerRightClickActionSchema, + ComputerMiddleClickActionSchema, + ComputerDoubleClickActionSchema, + ComputerTripleClickActionSchema, + ComputerLeftClickDragActionSchema, + ComputerLeftMouseDownActionSchema, + ComputerLeftMouseUpActionSchema, + ComputerScrollActionSchema, + ComputerTypeActionSchema, + ComputerKeyActionSchema, + ComputerMouseMoveActionSchema, + ComputerHoldKeyActionSchema, + ComputerWaitActionSchema +]); +discriminatedUnion("action", [ + ComputerScreenshotActionSchema, + ComputerLeftClickActionSchema, + ComputerRightClickActionSchema, + ComputerMiddleClickActionSchema, + ComputerDoubleClickActionSchema, + ComputerTripleClickActionSchema, + ComputerLeftClickDragActionSchema, + ComputerLeftMouseDownActionSchema, + ComputerLeftMouseUpActionSchema, + ComputerScrollActionSchema, + ComputerTypeActionSchema, + ComputerKeyActionSchema, + ComputerMouseMoveActionSchema, + ComputerHoldKeyActionSchema, + ComputerWaitActionSchema, + ComputerZoomActionSchema +]); +union([object({ command: string().describe("The bash command to run") }), object({ restart: literal(true).describe("Set to true to restart the bash session") })]); +//#endregion +//#region node_modules/@langchain/anthropic/dist/index.js +var dist_exports = /* @__PURE__ */ __exportAll$1({ ChatAnthropic: () => ChatAnthropic }); +//#endregion +export { async_caller_exports as $, isDataContentBlock as $n, CallbackManager as $t, BaseOutputParser as A, HumanMessage as An, getSchemaDescription as At, prompt_values_exports as B, tool_exports as Bn, GenerationChunk as Bt, makeInvalidToolCall as C, isAIMessage as Cn, voidType as Ct, json_patch_exports as D, SystemMessage as Dn, extendInteropZodObject as Dt, JsonOutputParser as E, iife$2 as En, standard_schema_exports as Et, isOpenAITool as F, parsePartialJson as Fn, isInteropZodObject as Ft, Runnable as G, Serializable as Gn, concat as Gt, hash_exports as H, BaseMessageChunk as Hn, outputs_exports as Ht, tiktoken_exports as I, ToolInputParsingException as In, isInteropZodSchema as It, RunnableSequence as J, isEscapedObject as Jn, ensureConfig as Jt, RunnableBinding as K, get_lc_unique_name as Kn, stream_exports$1 as Kt, ChatPromptValue as L, ToolMessage as Ln, isZodSchemaV3 as Lt, RunnablePassthrough as M, FunctionMessageChunk as Mn, interopSafeParseAsync as Mt, BaseLanguageModel as N, ChatMessage as Nn, interopZodObjectMakeFieldsOptional as Nt, BaseCumulativeTransformOutputParser as O, SystemMessageChunk as On, getInteropZodDefaultGetter as Ot, base_exports as P, ChatMessageChunk as Pn, interopZodObjectPartial as Pt, AsyncCaller as Q, convertToProviderContentBlock as Qn, AsyncLocalStorageProviderSingleton as Qt, ImagePromptValue as R, ToolMessageChunk as Rn, isZodSchemaV4 as Rt, convertLangChainToolCallToOpenAI as S, AIMessageChunk as Sn, unknownType as St, output_parsers_exports as T, getBufferString as Tn, isSerializableSchema as Tt, sha256 as U, isBaseMessage as Un, AsyncGeneratorWithSetup as Ut, caches_exports as V, BaseMessage as Vn, RUN_KEY as Vt, messages_exports as W, isBaseMessageChunk as Wn, IterableReadableStream as Wt, Graph as X, keyFromJson as Xn, patchConfig as Xt, _coerceToRunnable as Y, unescapeValue as Yn, mergeConfigs as Yt, graph_exports as Z, mapKeys as Zn, singletons_exports as Zt, createFunctionCallingParser as _, validate$2 as _n, promiseType as _t, StructuredTool as a, console_exports as an, __exportAll as ar, ZodType as at, JsonOutputKeyToolsParser as b, getEnvironmentVariable$1 as bn, tupleType as bt, isLangChainTool as c, Client as cn, booleanType as ct, compat_exports as d, callbackHandlerPrefersStreaming as dn, functionType as dt, ensureHandler as en, parseBase64DataUrl as er, log_stream_exports as et, finalizeContentBlock as f, uuid_exports as fn, instanceOfType as ft, createContentParser as g, v7$1 as gn, optionalType as gt, assembleStructuredOutputPipeline as h, v6 as hn, objectType as ht, DynamicStructuredTool as i, tracer_langchain_exports as in, errors_exports as ir, ZodFirstPartyTypeKind as it, runnables_exports as j, HumanMessageChunk as jn, interopParse as jt, BaseLLMOutputParser as k, RemoveMessage as kn, getInteropZodObjectShape as kt, BaseChatModel as l, BaseCallbackHandler as ln, custom as lt, stream_exports as m, v5$1 as mn, numberType as mt, convertToOpenAITool as n, parseCallbackConfigArg as nn, ContextOverflowError as nr, json_schema_exports as nt, tool as o, BaseTracer as on, anyType as ot, ChatModelStream as p, v4$1 as pn, literalType as pt, RunnableLambda as q, serializable_exports as qn, raceWithSignal as qt, function_calling_exports as r, promises_exports as rn, addLangChainErrorFields$1 as rr, toJsonSchema as rt, tools_exports as s, base_exports$1 as sn, arrayType as st, dist_exports as t, manager_exports as tn, parseMimeType as tr, compare as tt, chat_models_exports as u, base_exports$2 as un, enumType as ut, structured_output_exports as v, env_exports as vn, recordType as vt, parseToolCall as w, coerceMessageLikeToMessage as wn, ZodError as wt, JsonOutputToolsParser as x, AIMessage as xn, unionType as xt, types_exports as y, getEnv$1 as yn, stringType as yt, StringPromptValue as z, isToolMessage as zn, ChatGenerationChunk as zt }; diff --git a/.vercel/output/functions/__server.func/_libs/@langchain/langgraph+[...].mjs b/.vercel/output/functions/__server.func/_libs/@langchain/langgraph+[...].mjs new file mode 100644 index 0000000..308bb4c --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/@langchain/langgraph+[...].mjs @@ -0,0 +1,11977 @@ +import { r as __exportAll } from "../../_runtime.mjs"; +import { Ft as ZodType, Ht as custom, pn as $ZodRegistry, zt as any } from "../@better-auth/core+[...].mjs"; +import { $t as CallbackManager, At as getSchemaDescription, Dt as extendInteropZodObject, Ft as isInteropZodObject, G as Runnable, Hn as BaseMessageChunk, J as RunnableSequence, K as RunnableBinding, Ln as ToolMessage, Lt as isZodSchemaV3, M as RunnablePassthrough, Ot as getInteropZodDefaultGetter, Pt as interopZodObjectPartial, Qt as AsyncLocalStorageProviderSingleton, Sn as AIMessageChunk, Un as isBaseMessage, Vn as BaseMessage, Wn as isBaseMessageChunk, Wt as IterableReadableStream, X as Graph, Xt as patchConfig, Y as _coerceToRunnable, Yt as mergeConfigs, _n as validate, at as ZodType$1, en as ensureHandler, hn as v6, ht as objectType, jt as interopParse, kn as RemoveMessage, kt as getInteropZodObjectShape, ln as BaseCallbackHandler, lt as custom$1, mn as v5, p as ChatModelStream, pn as v4, wn as coerceMessageLikeToMessage, zn as isToolMessage } from "./anthropic+[...].mjs"; +import { t as load } from "../langchain__core+mustache.mjs"; +import { AsyncLocalStorage } from "node:async_hooks"; +//#region node_modules/@langchain/langgraph/dist/node.js +function initializeAsyncLocalStorageSingleton() { + AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new AsyncLocalStorage()); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/utils/timeout.js +function _coerceTimeoutMs(value, field) { + if (value === void 0 || value === null) return; + if (typeof value !== "number" || Number.isNaN(value) || value <= 0) throw new Error(`${field} must be greater than 0`); + return value; +} +/** +* Normalize a timeout value into a {@link TimeoutPolicy} with positive +* millisecond fields, or `undefined` if no timeout is configured. +* +* A bare number (or `undefined`) is treated as a hard {@link +* TimeoutPolicy.runTimeout}. Throws if any configured timeout is not greater +* than 0, or if `refreshOn` is not `"auto"` or `"heartbeat"`. +* +* @internal +*/ +function coerceTimeoutPolicy(value) { + if (value === void 0 || value === null) return; + const policy = typeof value === "number" ? { runTimeout: value } : value; + const refreshOn = policy.refreshOn ?? "auto"; + if (refreshOn !== "auto" && refreshOn !== "heartbeat") throw new Error("refreshOn must be \"auto\" or \"heartbeat\""); + const runTimeout = _coerceTimeoutMs(policy.runTimeout, "runTimeout"); + const idleTimeout = _coerceTimeoutMs(policy.idleTimeout, "idleTimeout"); + if (runTimeout === void 0 && idleTimeout === void 0) return; + return { + runTimeout, + idleTimeout, + refreshOn + }; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/constants.js +/** Special reserved node name denoting the start of a graph. */ +var START = "__start__"; +/** Special reserved node name denoting the end of a graph. */ +var END = "__end__"; +var INPUT = "__input__"; +var ERROR$1 = "__error__"; +/** +* Special reserved write key recording the name of the node whose execution +* failed, so node-level error handlers see the same failure provenance after a +* checkpoint resume. Value format in pending writes: +* `[taskId, ERROR_SOURCE_NODE, nodeName: string]`. +*/ +var ERROR_SOURCE_NODE = "__error_source_node__"; +/** Special reserved cache namespaces */ +var CACHE_NS_WRITES = "__pregel_ns_writes"; +/** +* System-wide upper bound on how many supersteps a {@link DeltaChannel} may go +* without writing a {@link DeltaSnapshot} blob. Once a channel's +* supersteps-since-snapshot counter reaches this value, a snapshot is forced +* even if the channel's own `snapshotFrequency` has not been reached — this +* prevents unbounded ancestor walks on threads where a delta channel exists +* but is no longer being updated. +* +* Overridable via the `LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT` +* environment variable. Read lazily so test/runtime overrides take effect. +* +* @remarks Beta. +*/ +function getDeltaMaxSuperstepsSinceSnapshot() { + const raw = typeof process !== "undefined" ? process.env?.LANGGRAPH_DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT : void 0; + if (raw !== void 0 && raw !== "") { + const parsed = Number.parseInt(raw, 10); + if (Number.isFinite(parsed) && parsed > 0) return parsed; + } + return 5e3; +} +var CONFIG_KEY_SEND = "__pregel_send"; +/** config key containing function used to call a node (push task) */ +var CONFIG_KEY_CALL = "__pregel_call"; +var CONFIG_KEY_READ = "__pregel_read"; +var CONFIG_KEY_CHECKPOINTER = "__pregel_checkpointer"; +var CONFIG_KEY_RESUMING = "__pregel_resuming"; +var CONFIG_KEY_TASK_ID = "__pregel_task_id"; +var CONFIG_KEY_STREAM = "__pregel_stream"; +var CONFIG_KEY_RESUME_VALUE = "__pregel_resume_value"; +var CONFIG_KEY_RESUME_MAP = "__pregel_resume_map"; +var CONFIG_KEY_SCRATCHPAD = "__pregel_scratchpad"; +/** config key containing state from previous invocation of graph for the given thread */ +var CONFIG_KEY_PREVIOUS_STATE = "__pregel_previous"; +var CONFIG_KEY_DURABILITY = "__pregel_durability"; +var CONFIG_KEY_CHECKPOINT_ID = "checkpoint_id"; +var CONFIG_KEY_CHECKPOINT_NS = "checkpoint_ns"; +var CONFIG_KEY_NODE_FINISHED = "__pregel_node_finished"; +/** +* Config key holding a {@link NodeError} (failed source node + error) for the +* current node-level error handler invocation. Injected when an error handler +* task is prepared after the failing node's retry policy is exhausted. +*/ +var CONFIG_KEY_NODE_ERROR = "__pregel_node_error"; +var CONFIG_KEY_CHECKPOINT_MAP = "checkpoint_map"; +var CONFIG_KEY_REPLAY_STATE = "__pregel_replay_state"; +var CONFIG_KEY_ABORT_SIGNALS = "__pregel_abort_signals"; +/** Special channel reserved for graph interrupts */ +var INTERRUPT$1 = "__interrupt__"; +/** Special channel reserved for graph resume */ +var RESUME$1 = "__resume__"; +/** Special channel reserved for cases when a task exits without any writes */ +var NO_WRITES = "__no_writes__"; +/** Special channel reserved for graph return */ +var RETURN = "__return__"; +/** Special channel reserved for graph previous state */ +var PREVIOUS = "__previous__"; +var TAG_HIDDEN = "langsmith:hidden"; +var SELF = "__self__"; +var TASKS = "__pregel_tasks"; +var PUSH = "__pregel_push"; +var PULL = "__pregel_pull"; +var NULL_TASK_ID = "00000000-0000-0000-0000-000000000000"; +var RESERVED = [ + TAG_HIDDEN, + INPUT, + INTERRUPT$1, + RESUME$1, + ERROR$1, + ERROR_SOURCE_NODE, + NO_WRITES, + CONFIG_KEY_SEND, + CONFIG_KEY_READ, + CONFIG_KEY_CHECKPOINTER, + CONFIG_KEY_DURABILITY, + CONFIG_KEY_STREAM, + CONFIG_KEY_RESUMING, + CONFIG_KEY_TASK_ID, + CONFIG_KEY_CALL, + CONFIG_KEY_RESUME_VALUE, + CONFIG_KEY_SCRATCHPAD, + CONFIG_KEY_PREVIOUS_STATE, + CONFIG_KEY_CHECKPOINT_MAP, + CONFIG_KEY_CHECKPOINT_NS, + CONFIG_KEY_CHECKPOINT_ID, + CONFIG_KEY_REPLAY_STATE +]; +/** +* Symbol used internally to identify Command instances. +* Exported to support cross-version type compatibility. +* @internal +*/ +var COMMAND_SYMBOL = Symbol.for("langgraph.command"); +/** +* Instance of a {@link Command} class. +* +* This is used to avoid IntelliSense suggesting public fields +* of {@link Command} class when a plain object is expected. +* +* @see {@link Command} +* @internal +*/ +var CommandInstance = class { + [COMMAND_SYMBOL]; + constructor(args) { + this[COMMAND_SYMBOL] = args; + } +}; +function _isSendInterface(x) { + const operation = x; + return operation !== null && operation !== void 0 && typeof operation.node === "string" && operation.args !== void 0; +} +/** +* +* A message or packet to send to a specific node in the graph. +* +* The `Send` class is used within a `StateGraph`'s conditional edges to +* dynamically invoke a node with a custom state at the next step. +* +* Importantly, the sent state can differ from the core graph's state, +* allowing for flexible and dynamic workflow management. +* +* One such example is a "map-reduce" workflow where your graph invokes +* the same node multiple times in parallel with different states, +* before aggregating the results back into the main graph's state. +* +* @example +* ```typescript +* import { Annotation, Send, StateGraph } from "@langchain/langgraph"; +* +* const ChainState = Annotation.Root({ +* subjects: Annotation, +* jokes: Annotation({ +* reducer: (a, b) => a.concat(b), +* }), +* }); +* +* const continueToJokes = async (state: typeof ChainState.State) => { +* return state.subjects.map((subject) => { +* return new Send("generate_joke", { subjects: [subject] }); +* }); +* }; +* +* @remarks +* A per-task timeout can be supplied via the third argument's `timeout` option +* to override the target node's configured timeout for this specific pushed task: +* +* ```typescript +* new Send("generate_joke", { subjects: [subject] }, { timeout: { idleTimeout: 5000 } }); +* ``` +* +* const graph = new StateGraph(ChainState) +* .addNode("generate_joke", (state) => ({ +* jokes: [`Joke about ${state.subjects}`], +* })) +* .addConditionalEdges("__start__", continueToJokes) +* .addEdge("generate_joke", "__end__") +* .compile(); +* +* const res = await graph.invoke({ subjects: ["cats", "dogs"] }); +* console.log(res); +* +* // Invoking with two subjects results in a generated joke for each +* // { subjects: ["cats", "dogs"], jokes: [`Joke about cats`, `Joke about dogs`] } +* ``` +*/ +var Send = class { + lg_name = "Send"; + node; + args; + /** + * Optional per-task timeout policy that overrides the target node's timeout + * for this specific pushed task. A bare number is treated as a hard + * `runTimeout` (in milliseconds). + */ + timeout; + constructor(node, args, options) { + this.node = node; + this.args = _deserializeCommandSendObjectGraph(args); + this.timeout = coerceTimeoutPolicy(options?.timeout); + } + toJSON() { + return { + lg_name: this.lg_name, + node: this.node, + args: this.args, + timeout: this.timeout + }; + } +}; +function _isSend(x) { + return x instanceof Send; +} +var OVERWRITE = "__overwrite__"; +/** +* Helper function to detect and extract the value from an Overwrite wrapper, +* supporting both the Overwrite class instance and the serialized object format. +* +* Use to check if a provided value represents an Overwrite: returns the +* unwrapped value if so, or undefined otherwise. +* +* - If the value is an Overwrite instance (preferred API), return its `.value`. +* - If the value is a wire-format object ({ [OVERWRITE]: value }), extract it. +* - If the value is the discriminator form ({ type: OVERWRITE, value }) that +* results from JSON-serializing a typed `Overwrite` in another runtime (e.g. +* a Python dataclass routed through the LangGraph API server, where the typed +* instance is erased), extract it. Keeps Overwrite semantics intact across +* cross-runtime JSON boundaries. +* - Otherwise, returns undefined. +* +* @template ValueType - The expected type of the Overwrite value. +* @param value - The value to check (may be anything). +* @returns The unwrapped value if value is an Overwrite, or undefined otherwise. +* @internal +*/ +function _getOverwriteValue(value) { + if (typeof value === "object" && value !== null) { + if ("__overwrite__" in value) return [true, value[OVERWRITE]]; + const rec = value; + if (rec.type === "__overwrite__" && "value" in rec) return [true, rec.value]; + } + return [false, void 0]; +} +/** +* Type guard to check if a value is an Overwrite value -- either the class +* instance or the wire format object. +* +* @template ValueType - The expected type of the Overwrite value. +* @param value - The value to check (may be anything). +* @returns `true` if the value is an Overwrite value, `false` otherwise. +* @internal +*/ +function _isOverwriteValue(value) { + return _getOverwriteValue(value)[0]; +} +/** +* Checks if the given graph invoke / stream chunk contains interrupt. +* +* @example +* ```ts +* import { INTERRUPT, isInterrupted } from "@langchain/langgraph"; +* +* const values = await graph.invoke({ foo: "bar" }); +* if (isInterrupted(values)) { +* const interrupt = values[INTERRUPT][0].value; +* } +* ``` +* +* @param values - The values to check. +* @returns `true` if the values contain an interrupt, `false` otherwise. +*/ +function isInterrupted(values) { + if (!values || typeof values !== "object") return false; + if (!("__interrupt__" in values)) return false; + return Array.isArray(values[INTERRUPT$1]); +} +/** +* One or more commands to update the graph's state and send messages to nodes. +* Can be used to combine routing logic with state updates in lieu of conditional edges +* +* @example +* ```ts +* import { Annotation, Command } from "@langchain/langgraph"; +* +* // Define graph state +* const StateAnnotation = Annotation.Root({ +* foo: Annotation, +* }); +* +* // Define the nodes +* const nodeA = async (_state: typeof StateAnnotation.State) => { +* console.log("Called A"); +* // this is a replacement for a real conditional edge function +* const goto = Math.random() > .5 ? "nodeB" : "nodeC"; +* // note how Command allows you to BOTH update the graph state AND route to the next node +* return new Command({ +* // this is the state update +* update: { +* foo: "a", +* }, +* // this is a replacement for an edge +* goto, +* }); +* }; +* +* // Nodes B and C are unchanged +* const nodeB = async (state: typeof StateAnnotation.State) => { +* console.log("Called B"); +* return { +* foo: state.foo + "|b", +* }; +* } +* +* const nodeC = async (state: typeof StateAnnotation.State) => { +* console.log("Called C"); +* return { +* foo: state.foo + "|c", +* }; +* } +* +* import { StateGraph } from "@langchain/langgraph"; + +* // NOTE: there are no edges between nodes A, B and C! +* const graph = new StateGraph(StateAnnotation) +* .addNode("nodeA", nodeA, { +* ends: ["nodeB", "nodeC"], +* }) +* .addNode("nodeB", nodeB) +* .addNode("nodeC", nodeC) +* .addEdge("__start__", "nodeA") +* .compile(); +* +* await graph.invoke({ foo: "" }); +* +* // Randomly oscillates between +* // { foo: 'a|c' } and { foo: 'a|b' } +* ``` +*/ +var Command = class extends CommandInstance { + lg_name = "Command"; + lc_direct_tool_output = true; + /** + * Graph to send the command to. Supported values are: + * - None: the current graph (default) + * - The specific name of the graph to send the command to + * - {@link Command.PARENT}: closest parent graph (only supported when returned from a node in a subgraph) + */ + graph; + /** + * Update to apply to the graph's state as a result of executing the node that is returning the command. + * Written to the state as if the node had simply returned this value instead of the Command object. + */ + update; + /** + * Value to resume execution with. To be used together with {@link interrupt}. + */ + resume; + /** + * Can be one of the following: + * - name of the node to navigate to next (any node that belongs to the specified `graph`) + * - sequence of node names to navigate to next + * - {@link Send} object (to execute a node with the exact input provided in the {@link Send} object) + * - sequence of {@link Send} objects + */ + goto = []; + static PARENT = "__parent__"; + constructor(args) { + super(args); + this.resume = args.resume; + this.graph = args.graph; + this.update = args.update; + if (args.goto) this.goto = Array.isArray(args.goto) ? _deserializeCommandSendObjectGraph(args.goto) : [_deserializeCommandSendObjectGraph(args.goto)]; + } + /** + * Convert the update field to a list of {@link PendingWrite} tuples + * @returns List of {@link PendingWrite} tuples of the form `[channelKey, value]`. + * @internal + */ + _updateAsTuples() { + if (this.update && typeof this.update === "object" && !Array.isArray(this.update)) return Object.entries(this.update); + else if (Array.isArray(this.update) && this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) return this.update; + else return [["__root__", this.update]]; + } + toJSON() { + let serializedGoto; + if (typeof this.goto === "string") serializedGoto = this.goto; + else if (_isSend(this.goto)) serializedGoto = this.goto.toJSON(); + else serializedGoto = this.goto?.map((innerGoto) => { + if (typeof innerGoto === "string") return innerGoto; + else return innerGoto.toJSON(); + }); + return { + lg_name: this.lg_name, + update: this.update, + resume: this.resume, + goto: serializedGoto + }; + } +}; +/** +* A type guard to check if the given value is a {@link Command}. +* +* Useful for type narrowing when working with the {@link Command} object. +* +* @param x - The value to check. +* @returns `true` if the value is a {@link Command}, `false` otherwise. +*/ +function isCommand(x) { + if (typeof x !== "object") return false; + if (x === null || x === void 0) return false; + if ("lg_name" in x && x.lg_name === "Command") return true; + return false; +} +function isPlainObject(value) { + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} +/** +* Reconstructs Command and Send objects from a deeply nested tree of anonymous objects +* matching their interfaces. +* +* This is only exported for testing purposes. It is NOT intended to be used outside of +* the Command and Send classes. +* +* @internal +* +* @param x - The command send tree to convert. +* @param seen - A map of seen objects to avoid infinite loops. +* @returns The converted command send tree. +*/ +function _deserializeCommandSendObjectGraph(x, seen = /* @__PURE__ */ new Map()) { + if (x !== void 0 && x !== null && typeof x === "object") { + if (seen.has(x)) return seen.get(x); + let result; + if (Array.isArray(x)) { + result = []; + seen.set(x, result); + x.forEach((item, index) => { + result[index] = _deserializeCommandSendObjectGraph(item, seen); + }); + } else if (x instanceof Command || x instanceof Send || !isPlainObject(x)) { + result = x; + seen.set(x, result); + } else if (isCommand(x)) { + result = new Command(x); + seen.set(x, result); + } else if (_isSendInterface(x)) { + result = new Send(x.node, x.args, x.timeout !== void 0 ? { timeout: x.timeout } : void 0); + seen.set(x, result); + } else if ("lc_serializable" in x && x.lc_serializable) { + result = x; + seen.set(x, result); + } else { + result = {}; + seen.set(x, result); + for (const [key, value] of Object.entries(x)) result[key] = _deserializeCommandSendObjectGraph(value, seen); + } + return result; + } + return x; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/errors.js +/** @category Errors */ +var BaseLangGraphError = class extends Error { + lc_error_code; + constructor(message, fields) { + let finalMessage = message ?? ""; + if (fields?.lc_error_code) finalMessage = `${finalMessage}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/\n`; + super(finalMessage); + this.lc_error_code = fields?.lc_error_code; + } +}; +var GraphBubbleUp = class extends BaseLangGraphError { + get is_bubble_up() { + return true; + } +}; +var GraphRecursionError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "GraphRecursionError"; + } + static get unminifiable_name() { + return "GraphRecursionError"; + } +}; +var GraphValueError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "GraphValueError"; + } + static get unminifiable_name() { + return "GraphValueError"; + } +}; +/** +* Raised when a graph run exits early due to a drain request. +* +* This indicates the graph stopped cooperatively at a superstep boundary +* because {@link RunControl#requestDrain} was called (e.g., in response to +* SIGTERM). The checkpoint is saved and the run can be resumed later. +*/ +var GraphDrained = class extends GraphBubbleUp { + reason; + constructor(reason = "shutdown", fields) { + super(`Graph drained: ${reason}`, fields); + this.name = "GraphDrained"; + this.reason = reason; + } + static get unminifiable_name() { + return "GraphDrained"; + } +}; +function isGraphDrained(e) { + return e !== void 0 && e.name === GraphDrained.unminifiable_name; +} +var GraphInterrupt = class extends GraphBubbleUp { + interrupts; + constructor(interrupts, fields) { + super(JSON.stringify(interrupts, null, 2), fields); + this.name = "GraphInterrupt"; + this.interrupts = interrupts ?? []; + } + static get unminifiable_name() { + return "GraphInterrupt"; + } +}; +/** Raised by a node to interrupt execution. */ +var NodeInterrupt = class extends GraphInterrupt { + constructor(message, fields) { + super([{ value: message }], fields); + this.name = "NodeInterrupt"; + } + static get unminifiable_name() { + return "NodeInterrupt"; + } +}; +/** +* Failure context passed to a node-level error handler. +* +* A node-level error handler is registered via +* `StateGraph.addNode(name, fn, { errorHandler })`. The handler runs ONLY after +* the failing node's {@link RetryPolicy} is exhausted, so retry and handling +* stay decoupled. The handler receives the failed node's name and the thrown +* error via a `NodeError` instance, can return a state update, and can route to +* a recovery branch via `new Command({ goto })` (saga / compensation flows). +* +* @example +* ```ts +* import { NodeError } from "@langchain/langgraph"; +* +* function handler(state: State, error: NodeError) { +* return new Command({ +* update: { status: `recovered from ${error.node}: ${error.error.message}` }, +* goto: "finalize", +* }); +* } +* ``` +*/ +var NodeError = class { + /** Name of the node whose execution failed. */ + node; + /** Error thrown by the failed node. */ + error; + constructor(node, error) { + this.node = node; + this.error = error; + } + static get unminifiable_name() { + return "NodeError"; + } +}; +var ParentCommand = class extends GraphBubbleUp { + command; + constructor(command) { + super(); + this.name = "ParentCommand"; + this.command = command; + } + static get unminifiable_name() { + return "ParentCommand"; + } +}; +function isParentCommand(e) { + return e !== void 0 && e.name === ParentCommand.unminifiable_name; +} +function isGraphBubbleUp(e) { + return e !== void 0 && e.is_bubble_up === true; +} +function isGraphInterrupt(e) { + return e !== void 0 && [GraphInterrupt.unminifiable_name, NodeInterrupt.unminifiable_name].includes(e.name); +} +/** +* Raised when a node invocation exceeds one of its configured timeouts. +* +* Does **not** extend {@link GraphBubbleUp} (so it flows through the normal node +* error path) and is intentionally treated as retryable by the default retry +* policy — its message/name do not match the default `retryOn` blocklist, so a +* configured {@link RetryPolicy} will retry it (see langchain-ai/langgraph#7659). +* +* Both {@link NodeTimeoutError.runTimeout} and {@link NodeTimeoutError.idleTimeout} +* reflect the configured policy at the time of the failure (each `undefined` if +* not configured). {@link NodeTimeoutError.kind} and {@link NodeTimeoutError.timeout} +* identify which one fired. +* +* @category Errors +*/ +var NodeTimeoutError = class extends BaseLangGraphError { + /** Name of the node/task that timed out. */ + node; + /** Which timeout fired: a hard `"run"` cap or a progress-resetting `"idle"` cap. */ + kind; + /** The value (ms) of the timeout that fired (`runTimeout` or `idleTimeout`). */ + timeout; + /** Elapsed time (ms) since the attempt started, at the moment the timeout fired. */ + elapsed; + /** Configured run timeout (ms), if any. */ + runTimeout; + /** Configured idle timeout (ms), if any. */ + idleTimeout; + constructor(fields, errorFields) { + const { node, elapsed, kind, runTimeout, idleTimeout } = fields; + let message; + let timeout; + if (kind === "idle") { + if (idleTimeout === void 0) throw new Error("idleTimeout is required when kind='idle'"); + timeout = idleTimeout; + message = `Node "${node}" exceeded its idle timeout of ${idleTimeout}ms without making progress (elapsed: ${elapsed}ms).`; + } else { + if (runTimeout === void 0) throw new Error("runTimeout is required when kind='run'"); + timeout = runTimeout; + message = `Node "${node}" exceeded its run timeout of ${runTimeout}ms (elapsed: ${elapsed}ms).`; + } + super(message, errorFields); + this.name = "NodeTimeoutError"; + this.node = node; + this.kind = kind; + this.timeout = timeout; + this.elapsed = elapsed; + this.runTimeout = runTimeout; + this.idleTimeout = idleTimeout; + } + static get unminifiable_name() { + return "NodeTimeoutError"; + } +}; +var EmptyInputError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "EmptyInputError"; + } + static get unminifiable_name() { + return "EmptyInputError"; + } +}; +var EmptyChannelError = class extends BaseLangGraphError { + constructor(message, fields) { + const prevLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + super(message, fields); + Error.stackTraceLimit = prevLimit; + this.name = "EmptyChannelError"; + } + static get unminifiable_name() { + return "EmptyChannelError"; + } +}; +var InvalidUpdateError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "InvalidUpdateError"; + } + static get unminifiable_name() { + return "InvalidUpdateError"; + } +}; +var UnreachableNodeError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "UnreachableNodeError"; + } + static get unminifiable_name() { + return "UnreachableNodeError"; + } +}; +/** +* Error thrown when invalid input is provided to a StateGraph. +* +* This typically means that the input to the StateGraph constructor or builder +* did not match the required types. A valid input should be a +* StateDefinition, an Annotation.Root, or a Zod schema. +* +* @example +* // Example of incorrect usage: +* try { +* new StateGraph({ foo: "bar" }); // Not a valid input +* } catch (err) { +* if (err instanceof StateGraphInputError) { +* console.error(err.message); +* } +* } +*/ +var StateGraphInputError = class extends BaseLangGraphError { + /** + * Create a new StateGraphInputError. + * @param message - Optional custom error message. + * @param fields - Optional additional error fields. + */ + constructor(message, fields) { + super(message, fields); + this.name = "StateGraphInputError"; + this.message = "Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."; + } + /** + * The unminifiable (static, human-readable) error name for this error class. + */ + static get unminifiable_name() { + return "StateGraphInputError"; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-checkpoint/dist/id.js +var lastMsecs = 0; +var lastNsecs = 0; +function uuid6(clockseq) { + let msecs = Date.now(); + if (msecs <= lastMsecs) { + lastNsecs += 1; + if (lastNsecs >= 1e4) { + lastNsecs = 0; + msecs = lastMsecs + 1; + } + } else lastNsecs = 0; + lastMsecs = msecs; + return v6({ + clockseq, + msecs, + nsecs: lastNsecs + }); +} +function uuid5(name, namespace) { + const namespaceBytes = namespace.replace(/-/g, "").match(/.{2}/g).map((byte) => parseInt(byte, 16)); + return v5(name, new Uint8Array(namespaceBytes)); +} +//#endregion +//#region node_modules/@langchain/langgraph-checkpoint/dist/serde/types.js +var ERROR = "__error__"; +var SCHEDULED = "__scheduled__"; +var INTERRUPT = "__interrupt__"; +var RESUME = "__resume__"; +/** +* Snapshot blob for a `DeltaChannel` with finite snapshot frequency. +* +* Stored directly in a checkpoint's `channel_values` in place of the full +* accumulated value. The ancestor walk in +* {@link BaseCheckpointSaver.getDeltaChannelHistory} terminates when it +* encounters a populated `channel_values` entry for a channel; a +* `DeltaSnapshot` value is the materialized state at that ancestor, so the +* channel reconstructs directly from `.value` without replaying earlier +* writes. +* +* @remarks Beta. The on-disk representation may change in future releases. +*/ +var DeltaSnapshot = class { + /** Marker used for structural detection across module/realm boundaries. */ + lg_name = "DeltaSnapshot"; + value; + constructor(value) { + this.value = value; + } +}; +/** +* Structural type guard for {@link DeltaSnapshot}. Uses the `lg_name` marker +* so it survives serialization round-trips and cross-package duplication. +*/ +function isDeltaSnapshot(value) { + return value != null && typeof value === "object" && value.lg_name === "DeltaSnapshot"; +} +//#endregion +//#region node_modules/@langchain/langgraph-checkpoint/dist/serde/utils/fast-safe-stringify/index.js +var LIMIT_REPLACE_NODE = "[...]"; +var CIRCULAR_REPLACE_NODE = "[Circular]"; +var arr = []; +var replacerStack = []; +function defaultOptions() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER + }; +} +function stringify(obj, replacer, spacer, options) { + if (typeof options === "undefined") options = defaultOptions(); + decirc(obj, "", 0, [], void 0, 0, options); + var res; + try { + if (replacerStack.length === 0) res = JSON.stringify(obj, replacer, spacer); + else res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + } catch (_) { + return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); + } finally { + while (arr.length !== 0) { + var part = arr.pop(); + if (part.length === 4) Object.defineProperty(part[0], part[1], part[3]); + else part[0][part[1]] = part[2]; + } + } + return res; +} +function setReplace(replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== void 0) if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + arr.push([ + parent, + k, + val, + propertyDescriptor + ]); + } else replacerStack.push([ + val, + k, + replace + ]); + else { + parent[k] = replace; + arr.push([ + parent, + k, + val + ]); + } +} +function decirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + if (Array.isArray(val)) for (i = 0; i < val.length; i++) decirc(val[i], i, i, stack, val, depth, options); + else { + var keys = Object.keys(val); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + decirc(val[key], key, i, stack, val, depth, options); + } + } + stack.pop(); + } +} +function replaceGetterValues(replacer) { + replacer = typeof replacer !== "undefined" ? replacer : function(k, v) { + return v; + }; + return function(key, val) { + if (replacerStack.length > 0) for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack.splice(i, 1); + break; + } + } + return replacer.call(this, key, val); + }; +} +//#endregion +//#region node_modules/@langchain/langgraph-checkpoint/dist/serde/jsonplus.js +function isLangChainSerializedObject(value) { + return value !== null && value.lc === 1 && value.type === "constructor" && Array.isArray(value.id); +} +/** +* The replacer in stringify does not allow delegation to built-in LangChain +* serialization methods, and instead immediately calls `.toJSON()` and +* continues to stringify subfields. +* +* We therefore must start from the most nested elements in the input and +* deserialize upwards rather than top-down. +*/ +async function _reviver(value) { + if (value && typeof value === "object") if (Array.isArray(value)) return await Promise.all(value.map((item) => _reviver(item))); + else { + const revivedObj = {}; + for (const [k, v] of Object.entries(value)) revivedObj[k] = await _reviver(v); + if (revivedObj.lc === 2 && revivedObj.type === "undefined") return; + else if (revivedObj.lc === 2 && revivedObj.type === "delta_snapshot") return new DeltaSnapshot(revivedObj.value); + else if (revivedObj.lc === 2 && revivedObj.type === "constructor" && Array.isArray(revivedObj.id)) try { + const constructorName = revivedObj.id[revivedObj.id.length - 1]; + let constructor; + switch (constructorName) { + case "Set": + constructor = Set; + break; + case "Map": + constructor = Map; + break; + case "RegExp": + constructor = RegExp; + break; + case "Error": + constructor = Error; + break; + case "Uint8Array": + constructor = Uint8Array; + break; + default: return revivedObj; + } + if (revivedObj.method) return constructor[revivedObj.method](...revivedObj.args || []); + else return new constructor(...revivedObj.args || []); + } catch { + return revivedObj; + } + else if (isLangChainSerializedObject(revivedObj)) return load(JSON.stringify(revivedObj)); + return revivedObj; + } + return value; +} +function _encodeConstructorArgs(constructor, method, args, kwargs) { + return { + lc: 2, + type: "constructor", + id: [constructor.name], + method: method ?? null, + args: args ?? [], + kwargs: kwargs ?? {} + }; +} +function _default(obj) { + if (obj === void 0) return { + lc: 2, + type: "undefined" + }; + else if (obj instanceof DeltaSnapshot) return { + lc: 2, + type: "delta_snapshot", + value: obj.value + }; + else if (obj instanceof Set || obj instanceof Map) return _encodeConstructorArgs(obj.constructor, void 0, [Array.from(obj)]); + else if (obj instanceof RegExp) return _encodeConstructorArgs(RegExp, void 0, [obj.source, obj.flags]); + else if (obj instanceof Error) return _encodeConstructorArgs(obj.constructor, void 0, [obj.message]); + else if (obj?.lg_name === "Send") return { + node: obj.node, + args: obj.args, + ...obj.timeout !== void 0 ? { timeout: obj.timeout } : {} + }; + else if (obj instanceof Uint8Array) return _encodeConstructorArgs(Uint8Array, "from", [Array.from(obj)]); + else return obj; +} +var JsonPlusSerializer = class { + _dumps(obj) { + return new TextEncoder().encode(stringify(obj, (_, value) => { + return _default(value); + })); + } + async dumpsTyped(obj) { + if (obj instanceof Uint8Array) return ["bytes", obj]; + else return ["json", this._dumps(obj)]; + } + async _loads(data) { + return _reviver(JSON.parse(data)); + } + async loadsTyped(type, data) { + if (type === "bytes") return typeof data === "string" ? new TextEncoder().encode(data) : data; + else if (type === "json") return this._loads(typeof data === "string" ? data : new TextDecoder().decode(data)); + else throw new Error(`Unknown serialization type: ${type}`); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-checkpoint/dist/base.js +function deepCopy(obj) { + if (typeof obj !== "object" || obj === null) return obj; + const newObj = Array.isArray(obj) ? [] : {}; + for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = deepCopy(obj[key]); + return newObj; +} +/** @hidden */ +function emptyCheckpoint() { + return { + v: 4, + id: uuid6(0), + ts: (/* @__PURE__ */ new Date()).toISOString(), + channel_values: {}, + channel_versions: {}, + versions_seen: {} + }; +} +/** @hidden */ +function copyCheckpoint(checkpoint) { + return { + v: checkpoint.v, + id: checkpoint.id, + ts: checkpoint.ts, + channel_values: { ...checkpoint.channel_values ?? {} }, + channel_versions: { ...checkpoint.channel_versions ?? {} }, + versions_seen: deepCopy(checkpoint.versions_seen ?? {}) + }; +} +function compareChannelVersions(a, b) { + if (typeof a === "number" && typeof b === "number") return Math.sign(a - b); + return String(a).localeCompare(String(b)); +} +function maxChannelVersion(...versions) { + return versions.reduce((max, version, idx) => { + if (idx === 0) return version; + return compareChannelVersions(max, version) >= 0 ? max : version; + }); +} +/** +* Mapping from error type to error index. +* Regular writes just map to their index in the list of writes being saved. +* Special writes (e.g. errors) map to negative indices, to avoid those writes from +* conflicting with regular writes. +* Each Checkpointer implementation should use this mapping in put_writes. +*/ +var WRITES_IDX_MAP = { + [ERROR]: -1, + [SCHEDULED]: -2, + [INTERRUPT]: -3, + [RESUME]: -4 +}; +/** +* Metadata keys that are LangGraph's internal framework bookkeeping and +* should not be surfaced as user-meaningful metadata. +* +* Consumed by stream handlers (e.g. the `tasks` debug stream) to drop +* framework keys — which are redundant with a task's own fields and +* namespace — while keeping keys like `lc_agent_name`, `ls_integration`, +* and user-supplied metadata. +*/ +var EXCLUDED_METADATA_KEYS = /* @__PURE__ */ new Set([ + "thread_id", + "checkpoint_id", + "checkpoint_ns", + "checkpoint_map", + "langgraph_step", + "langgraph_node", + "langgraph_triggers", + "langgraph_path", + "langgraph_checkpoint_ns" +]); +//#endregion +//#region node_modules/@langchain/langgraph-checkpoint/dist/store/base.js +/** +* Error thrown when an invalid namespace is provided. +*/ +var InvalidNamespaceError = class extends Error { + constructor(message) { + super(message); + this.name = "InvalidNamespaceError"; + } +}; +/** +* Validates the provided namespace. +* @param namespace The namespace to validate. +* @throws {InvalidNamespaceError} If the namespace is invalid. +*/ +function validateNamespace(namespace) { + if (namespace.length === 0) throw new InvalidNamespaceError("Namespace cannot be empty."); + for (const label of namespace) { + if (typeof label !== "string") throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels must be strings, but got ${typeof label}.`); + if (label.includes(".")) throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`); + if (label === "") throw new InvalidNamespaceError(`Namespace labels cannot be empty strings. Got ${label} in ${namespace}`); + } + if (namespace[0] === "langgraph") throw new InvalidNamespaceError(`Root label for namespace cannot be "langgraph". Got: ${namespace}`); +} +/** +* Abstract base class for persistent key-value stores. +* +* Stores enable persistence and memory that can be shared across threads, +* scoped to user IDs, assistant IDs, or other arbitrary namespaces. +* +* Features: +* - Hierarchical namespaces for organization +* - Key-value storage with metadata +* - Vector similarity search (if configured) +* - Filtering and pagination +*/ +var BaseStore = class { + /** + * Retrieve a single item by its namespace and key. + * + * @param namespace Hierarchical path for the item + * @param key Unique identifier within the namespace + * @returns Promise resolving to the item or null if not found + */ + async get(namespace, key) { + return (await this.batch([{ + namespace, + key + }]))[0]; + } + /** + * Search for items within a namespace prefix. + * Supports both metadata filtering and vector similarity search. + * + * @param namespacePrefix Hierarchical path prefix to search within + * @param options Search options for filtering and pagination + * @returns Promise resolving to list of matching items with relevance scores + * + * @example + * // Search with filters + * await store.search(["documents"], { + * filter: { type: "report", status: "active" }, + * limit: 5, + * offset: 10 + * }); + * + * // Vector similarity search + * await store.search(["users", "content"], { + * query: "technical documentation about APIs", + * limit: 20 + * }); + */ + async search(namespacePrefix, options = {}) { + const { filter, limit = 10, offset = 0, query } = options; + return (await this.batch([{ + namespacePrefix, + filter, + limit, + offset, + query + }]))[0]; + } + /** + * Store or update an item. + * + * @param namespace Hierarchical path for the item + * @param key Unique identifier within the namespace + * @param value Object containing the item's data + * @param index Optional indexing configuration + * + * @example + * // Simple storage + * await store.put(["docs"], "report", { title: "Annual Report" }); + * + * // With specific field indexing + * await store.put( + * ["docs"], + * "report", + * { + * title: "Q4 Report", + * chapters: [{ content: "..." }, { content: "..." }] + * }, + * ["title", "chapters[*].content"] + * ); + */ + async put(namespace, key, value, index) { + validateNamespace(namespace); + await this.batch([{ + namespace, + key, + value, + index + }]); + } + /** + * Delete an item from the store. + * + * @param namespace Hierarchical path for the item + * @param key Unique identifier within the namespace + */ + async delete(namespace, key) { + await this.batch([{ + namespace, + key, + value: null + }]); + } + /** + * List and filter namespaces in the store. + * Used to explore data organization and navigate the namespace hierarchy. + * + * @param options Options for listing namespaces + * @returns Promise resolving to list of namespace paths + * + * @example + * // List all namespaces under "documents" + * await store.listNamespaces({ + * prefix: ["documents"], + * maxDepth: 2 + * }); + * + * // List namespaces ending with "v1" + * await store.listNamespaces({ + * suffix: ["v1"], + * limit: 50 + * }); + */ + async listNamespaces(options = {}) { + const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options; + const matchConditions = []; + if (prefix) matchConditions.push({ + matchType: "prefix", + path: prefix + }); + if (suffix) matchConditions.push({ + matchType: "suffix", + path: suffix + }); + return (await this.batch([{ + matchConditions: matchConditions.length ? matchConditions : void 0, + maxDepth, + limit, + offset + }]))[0]; + } + /** + * Start the store. Override if initialization is needed. + */ + start() {} + /** + * Stop the store. Override if cleanup is needed. + */ + stop() {} +}; +//#endregion +//#region node_modules/@langchain/langgraph-checkpoint/dist/store/batch.js +/** +* Extracts and returns the underlying store from an `AsyncBatchedStore`, +* or returns the input if it is not an `AsyncBatchedStore`. +*/ +var extractStore = (input) => { + if ("lg_name" in input && input.lg_name === "AsyncBatchedStore") return input.store; + return input; +}; +var AsyncBatchedStore = class extends BaseStore { + lg_name = "AsyncBatchedStore"; + store; + queue = /* @__PURE__ */ new Map(); + nextKey = 0; + running = false; + processingTask = null; + constructor(store) { + super(); + this.store = extractStore(store); + } + get isRunning() { + return this.running; + } + /** + * @ignore + * Batch is not implemented here as we're only extending `BaseStore` + * to allow it to be passed where `BaseStore` is expected, and implement + * the convenience methods (get, search, put, delete). + */ + async batch(_operations) { + throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong."); + } + async get(namespace, key) { + return this.enqueueOperation({ + namespace, + key + }); + } + async search(namespacePrefix, options) { + const { filter, limit = 10, offset = 0, query } = options || {}; + return this.enqueueOperation({ + namespacePrefix, + filter, + limit, + offset, + query + }); + } + async put(namespace, key, value) { + return this.enqueueOperation({ + namespace, + key, + value + }); + } + async delete(namespace, key) { + return this.enqueueOperation({ + namespace, + key, + value: null + }); + } + start() { + if (!this.running) { + this.running = true; + this.processingTask = this.processBatchQueue(); + } + } + async stop() { + this.running = false; + if (this.processingTask) await this.processingTask; + } + enqueueOperation(operation) { + return new Promise((resolve, reject) => { + const key = this.nextKey; + this.nextKey += 1; + this.queue.set(key, { + operation, + resolve, + reject + }); + }); + } + async processBatchQueue() { + while (this.running) { + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); + if (this.queue.size === 0) continue; + const batch = new Map(this.queue); + this.queue.clear(); + try { + const operations = Array.from(batch.values()).map(({ operation }) => operation); + const results = await this.store.batch(operations); + batch.forEach(({ resolve }, key) => { + resolve(results[Array.from(batch.keys()).indexOf(key)]); + }); + } catch (e) { + batch.forEach(({ reject }) => { + reject(e); + }); + } + } + } + toJSON() { + return { + queue: this.queue, + nextKey: this.nextKey, + running: this.running, + store: "[LangGraphStore]" + }; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-checkpoint/dist/cache/base.js +var BaseCache = class { + serde = new JsonPlusSerializer(); + /** + * Initialize the cache with a serializer. + * + * @param serde - The serializer to use. + */ + constructor(serde) { + this.serde = serde || this.serde; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/channels/base.js +/** Matches Postgres `uuid` / Python `uuid.UUID` (128-bit, 8-4-4-4-12 hex). */ +var STRUCTURED_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +/** +* Structural check for a {@link DeltaChannel} without importing it (avoids an +* import cycle: `delta.ts` imports `base.ts`). +*/ +function isDeltaChannel$1(channel) { + return channel != null && channel.lc_graph_name === "DeltaChannel"; +} +function isBaseChannel(obj) { + return obj != null && obj.lg_is_channel === true; +} +/** @internal */ +var BaseChannel = class { + ValueType; + UpdateType; + /** @ignore */ + lg_is_channel = true; + /** + * Mark the current value of the channel as consumed. By default, no-op. + * A channel can use this method to modify its state, preventing the value + * from being consumed again. + * + * Returns True if the channel was updated, False otherwise. + */ + consume() { + return false; + } + /** + * Notify the channel that the Pregel run is finishing. By default, no-op. + * A channel can use this method to modify its state, preventing finish. + * + * Returns True if the channel was updated, False otherwise. + */ + finish() { + return false; + } + /** + * Return True if the channel is available (not empty), False otherwise. + * Subclasses should override this method to provide a more efficient + * implementation than calling get() and catching EmptyChannelError. + */ + isAvailable() { + try { + this.get(); + return true; + } catch (error) { + if (error.name === EmptyChannelError.unminifiable_name) return false; + throw error; + } + } + /** + * Compare this channel with another channel for equality. + * Used to determine if two channels with the same key are semantically equivalent. + * Subclasses should override this method to provide a meaningful comparison. + * + * @param {BaseChannel} other - The other channel to compare with. + * @returns {boolean} True if the channels are equal, false otherwise. + */ + equals(other) { + return this === other; + } +}; +var IS_ONLY_BASE_CHANNEL = Symbol.for("LG_IS_ONLY_BASE_CHANNEL"); +function getOnlyChannels(channels) { + if (channels[IS_ONLY_BASE_CHANNEL] === true) return channels; + const newChannels = {}; + for (const k in channels) { + if (!Object.prototype.hasOwnProperty.call(channels, k)) continue; + const value = channels[k]; + if (isBaseChannel(value)) newChannels[k] = value; + } + Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); + return newChannels; +} +function emptyChannels(channels, checkpoint) { + const filteredChannels = getOnlyChannels(channels); + const newChannels = {}; + for (const k in filteredChannels) { + if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) continue; + const channelValue = checkpoint.channel_values[k]; + newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue); + } + Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); + return newChannels; +} +/** +* Synthetic task id for exit-mode DeltaChannel writes. +* +* Embeds the superstep in the first UUID group so `ORDER BY task_id, idx` +* preserves chronological order while remaining a valid RFC UUID (required by +* Postgres `checkpoint_writes.task_id uuid` columns). +*/ +function exitDeltaTaskId(step, taskId) { + if (!STRUCTURED_UUID.test(taskId)) throw new TypeError(`Invalid task id for exit delta: ${taskId}`); + const parts = taskId.toLowerCase().split("-"); + return `${String(step).padStart(8, "0")}-${parts[1]}-${parts[2]}-${parts[3]}-${parts[4]}`; +} +/** +* Return the set of {@link DeltaChannel} names that should snapshot now. +* +* A channel snapshots when EITHER its accumulated update count reaches +* `snapshotFrequency` OR the total supersteps since its last snapshot reaches +* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT`. Pure predicate — no mutation. +*/ +function deltaChannelsToSnapshot(channels, countersSinceDeltaSnapshot) { + const result = /* @__PURE__ */ new Set(); + const maxSupersteps = getDeltaMaxSuperstepsSinceSnapshot(); + for (const name in channels) { + if (!Object.prototype.hasOwnProperty.call(channels, name)) continue; + const ch = channels[name]; + if (!isDeltaChannel$1(ch) || !ch.isAvailable()) continue; + const [updates, supersteps] = countersSinceDeltaSnapshot[name] ?? [0, 0]; + if (updates >= ch.snapshotFrequency || supersteps >= maxSupersteps) result.add(name); + } + return result; +} +function createCheckpoint(checkpoint, channels, step, options) { + const channelsToSnapshot = options?.channelsToSnapshot ?? /* @__PURE__ */ new Set(); + const { updatedChannels, getNextVersion } = options ?? {}; + let values; + let channelVersions = checkpoint.channel_versions; + if (channels === void 0) values = checkpoint.channel_values; + else { + values = {}; + channelVersions = { ...checkpoint.channel_versions }; + for (const k in channels) { + if (!Object.prototype.hasOwnProperty.call(channels, k)) continue; + const channel = channels[k]; + if (channelsToSnapshot.has(k)) { + if (getNextVersion !== void 0 && (updatedChannels === void 0 || !updatedChannels.has(k))) channelVersions[k] = getNextVersion(channelVersions[k]); + values[k] = new DeltaSnapshot(channel.get()); + continue; + } + if (isDeltaChannel$1(channel)) continue; + try { + values[k] = channel.checkpoint(); + } catch (error) { + if (error.name === EmptyChannelError.unminifiable_name) {} else throw error; + } + } + } + return { + v: 4, + id: options?.id ?? uuid6(step), + ts: (/* @__PURE__ */ new Date()).toISOString(), + channel_values: values, + channel_versions: channelVersions, + versions_seen: checkpoint.versions_seen + }; +} +/** +* Hydrate channels from a checkpoint, reconstructing any {@link DeltaChannel} +* whose value is absent from `channel_values` by replaying ancestor writes. +* +* For most channels (and for delta channels with a {@link DeltaSnapshot} or a +* migrated plain value in `channel_values`), {@link emptyChannels} is +* sufficient and no saver access is required. When a delta channel is absent +* from `channel_values`, an ancestor walk via `saver.getDeltaChannelHistory` +* finds the nearest seed and accumulates the writes between it and the +* target. All delta channels needing replay are batched into a single saver +* call. +*/ +async function channelsFromCheckpoint(specs, checkpoint, options) { + const channels = emptyChannels(specs, checkpoint); + const { saver, config } = options ?? {}; + const filteredSpecs = getOnlyChannels(specs); + const deltaKeys = []; + for (const k in filteredSpecs) { + if (!Object.prototype.hasOwnProperty.call(filteredSpecs, k)) continue; + if (isDeltaChannel$1(filteredSpecs[k]) && !Object.prototype.hasOwnProperty.call(checkpoint.channel_values, k)) deltaKeys.push(k); + } + if (deltaKeys.length === 0 || saver === void 0 || config === void 0) return channels; + const histories = await saver.getDeltaChannelHistory({ + config, + channels: deltaKeys + }); + for (const k of deltaKeys) { + const history = histories[k]; + if (history === void 0) continue; + const replayCh = filteredSpecs[k].fromCheckpoint(history.seed); + replayCh.replayWrites(history.writes); + channels[k] = replayCh; + } + return channels; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/channels/binop.js +var isBinaryOperatorAggregate = (value) => { + return value != null && value.lc_graph_name === "BinaryOperatorAggregate"; +}; +/** +* Stores the result of applying a binary operator to the current value and each new value. +*/ +var BinaryOperatorAggregate = class BinaryOperatorAggregate extends BaseChannel { + lc_graph_name = "BinaryOperatorAggregate"; + value; + operator; + initialValueFactory; + constructor(operator, initialValueFactory) { + super(); + this.operator = operator; + this.initialValueFactory = initialValueFactory; + this.value = initialValueFactory?.(); + } + fromCheckpoint(checkpoint) { + const empty = new BinaryOperatorAggregate(this.operator, this.initialValueFactory); + if (typeof checkpoint !== "undefined") empty.value = checkpoint; + return empty; + } + update(values) { + let newValues = values; + if (!newValues.length) return false; + if (this.value === void 0) { + const first = newValues[0]; + const [isOverwrite, overwriteVal] = _getOverwriteValue(first); + if (isOverwrite) this.value = overwriteVal; + else this.value = first; + newValues = newValues.slice(1); + } + let seenOverwrite = false; + for (const incoming of newValues) if (_isOverwriteValue(incoming)) { + if (seenOverwrite) throw new InvalidUpdateError("Can receive only one Overwrite value per step."); + const [, val] = _getOverwriteValue(incoming); + this.value = val; + seenOverwrite = true; + continue; + } else if (!seenOverwrite && this.value !== void 0) this.value = this.operator(this.value, incoming); + return true; + } + get() { + if (this.value === void 0) throw new EmptyChannelError(); + return this.value; + } + checkpoint() { + if (this.value === void 0) throw new EmptyChannelError(); + return this.value; + } + isAvailable() { + return this.value !== void 0; + } + /** + * Compare this channel with another channel for equality. + * Two BinaryOperatorAggregate channels are equal if they have the same operator function. + * This follows the Python implementation which compares operator references. + */ + equals(other) { + if (this === other) return true; + if (!isBinaryOperatorAggregate(other)) return false; + return this.operator === other.operator; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/channels/last_value.js +/** +* Stores the last value received, can receive at most one value per step. +* +* Since `update` is only called once per step and value can only be of length 1, +* LastValue always stores the last value of a single node. If multiple nodes attempt to +* write to this channel in a single step, an error will be thrown. +* @internal +*/ +var LastValue = class LastValue extends BaseChannel { + lc_graph_name = "LastValue"; + value = []; + constructor(initialValueFactory) { + super(); + this.initialValueFactory = initialValueFactory; + if (initialValueFactory) this.value = [initialValueFactory()]; + } + fromCheckpoint(checkpoint) { + const empty = new LastValue(this.initialValueFactory); + if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; + return empty; + } + update(values) { + if (values.length === 0) return false; + if (values.length !== 1) throw new InvalidUpdateError("LastValue can only receive one value per step.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); + this.value = [values[values.length - 1]]; + return true; + } + get() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + checkpoint() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + isAvailable() { + return this.value.length !== 0; + } +}; +/** +* Stores the last value received, but only made available after finish(). +* Once made available, clears the value. +*/ +var LastValueAfterFinish = class LastValueAfterFinish extends BaseChannel { + lc_graph_name = "LastValueAfterFinish"; + value = []; + finished = false; + fromCheckpoint(checkpoint) { + const empty = new LastValueAfterFinish(); + if (typeof checkpoint !== "undefined") { + const [value, finished] = checkpoint; + empty.value = [value]; + empty.finished = finished; + } + return empty; + } + update(values) { + if (values.length === 0) return false; + this.finished = false; + this.value = [values[values.length - 1]]; + return true; + } + get() { + if (this.value.length === 0 || !this.finished) throw new EmptyChannelError(); + return this.value[0]; + } + checkpoint() { + if (this.value.length === 0) return void 0; + return [this.value[0], this.finished]; + } + consume() { + if (this.finished) { + this.finished = false; + this.value = []; + return true; + } + return false; + } + finish() { + if (!this.finished && this.value.length > 0) { + this.finished = true; + return true; + } + return false; + } + isAvailable() { + return this.value.length !== 0 && this.finished; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/graph/annotation.js +/** +* Should not be instantiated directly. See {@link Annotation}. +*/ +var AnnotationRoot = class { + lc_graph_name = "AnnotationRoot"; + spec; + constructor(s) { + this.spec = s; + } + static isInstance(value) { + return typeof value === "object" && value !== null && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot"; + } +}; +/** +* Helper that instantiates channels within a StateGraph state. +* +* Can be used as a field in an {@link Annotation.Root} wrapper in one of two ways: +* 1. **Directly**: Creates a channel that stores the most recent value returned from a node. +* 2. **With a reducer**: Creates a channel that applies the reducer on a node's return value. +* +* @example +* ```ts +* import { StateGraph, Annotation } from "@langchain/langgraph"; +* +* // Define a state with a single string key named "currentOutput" +* const SimpleAnnotation = Annotation.Root({ +* currentOutput: Annotation, +* }); +* +* const graphBuilder = new StateGraph(SimpleAnnotation); +* +* // A node in the graph that returns an object with a "currentOutput" key +* // replaces the value in the state. You can get the state type as shown below: +* const myNode = (state: typeof SimpleAnnotation.State) => { +* return { +* currentOutput: "some_new_value", +* }; +* } +* +* const graph = graphBuilder +* .addNode("myNode", myNode) +* ... +* .compile(); +* ``` +* +* @example +* ```ts +* import { type BaseMessage, AIMessage } from "@langchain/core/messages"; +* import { StateGraph, Annotation } from "@langchain/langgraph"; +* +* // Define a state with a single key named "messages" that will +* // combine a returned BaseMessage or arrays of BaseMessages +* const AnnotationWithReducer = Annotation.Root({ +* messages: Annotation({ +* // Different types are allowed for updates +* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => { +* if (Array.isArray(right)) { +* return left.concat(right); +* } +* return left.concat([right]); +* }, +* default: () => [], +* }), +* }); +* +* const graphBuilder = new StateGraph(AnnotationWithReducer); +* +* // A node in the graph that returns an object with a "messages" key +* // will update the state by combining the existing value with the returned one. +* const myNode = (state: typeof AnnotationWithReducer.State) => { +* return { +* messages: [new AIMessage("Some new response")], +* }; +* }; +* +* const graph = graphBuilder +* .addNode("myNode", myNode) +* ... +* .compile(); +* ``` +* @namespace +* @property Root +* Helper function that instantiates a StateGraph state. See {@link Annotation} for usage. +*/ +var Annotation = function(annotation) { + if (annotation) return getChannel(annotation); + else return new LastValue(); +}; +Annotation.Root = (sd) => new AnnotationRoot(sd); +function getChannel(reducer) { + if (typeof reducer === "object" && reducer && "reducer" in reducer && reducer.reducer) return new BinaryOperatorAggregate(reducer.reducer, reducer.default); + if (typeof reducer === "object" && reducer && "value" in reducer && reducer.value) return new BinaryOperatorAggregate(reducer.value, reducer.default); + return new LastValue(); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/utils/config.js +var COPIABLE_KEYS = [ + "tags", + "metadata", + "callbacks", + "configurable" +]; +var CONFIG_KEYS = [ + "tags", + "metadata", + "callbacks", + "runName", + "maxConcurrency", + "recursionLimit", + "configurable", + "runId", + "outputKeys", + "streamMode", + "store", + "writer", + "interrupt", + "context", + "interruptBefore", + "interruptAfter", + "checkpointDuring", + "durability", + "signal", + "heartbeat", + "executionInfo", + "serverInfo", + "control" +]; +var DEFAULT_RECURSION_LIMIT = 25; +var PROPAGATE_TO_METADATA = /* @__PURE__ */ new Set([ + "thread_id", + "checkpoint_id", + "checkpoint_ns", + "task_id", + "run_id", + "assistant_id", + "graph_id" +]); +function propagateConfigurableToMetadata(configurable, metadata) { + if (!configurable) return metadata; + const result = metadata ?? {}; + for (const key of PROPAGATE_TO_METADATA) { + if (key in result) continue; + const value = configurable[key]; + if (value !== void 0) result[key] = value; + } + return result; +} +/** +* Drop langgraph's internal `seq:step*` bookkeeping tags. +* +* `seq:step:N` tags are added internally to mark sequence steps; everything +* else (user-supplied tags and any other framework tags) is kept. Returns the +* surviving tags, or `undefined` if none remain. Shared by the stream handlers +* (e.g. {@link mapDebugTasks}) so the same tag set is surfaced consistently. +*/ +function filterToUserTags(tags) { + if (tags == null || tags.length === 0) return void 0; + const filtered = tags.filter((tag) => !tag.startsWith("seq:step")); + return filtered.length > 0 ? filtered : void 0; +} +/** +* Merge two `callbacks` values across configs. +* +* A `callbacks` value may be `undefined`, an array of handlers, or a +* {@link CallbackManager}, so merging two of them has six cases. This +* mirrors the callbacks branch of langchain-core's `mergeConfigs` and +* langgraph's `_merge_callbacks`, so a handler bound via +* `.withConfig({ callbacks: [...] })` is preserved when a later config +* (e.g. `streamEvents` injecting its own internal handler) is merged on +* top instead of overwriting it. +*/ +function mergeCallbacks(base, provided) { + if (provided === void 0) return base; + if (base === void 0) return Array.isArray(provided) ? [...provided] : provided.copy(); + if (Array.isArray(provided)) { + if (Array.isArray(base)) return base.concat(provided); + const manager = base.copy(); + for (const callback of provided) manager.addHandler(ensureHandler(callback), true); + return manager; + } + if (Array.isArray(base)) { + const manager = provided.copy(); + for (const callback of base) manager.addHandler(ensureHandler(callback), true); + return manager; + } + return new CallbackManager(provided._parentRunId, { + handlers: base.handlers.concat(provided.handlers), + inheritableHandlers: base.inheritableHandlers.concat(provided.inheritableHandlers), + tags: Array.from(new Set(base.tags.concat(provided.tags))), + inheritableTags: Array.from(new Set(base.inheritableTags.concat(provided.inheritableTags))), + metadata: { + ...base.metadata, + ...provided.metadata + }, + inheritableMetadata: { + ...base.inheritableMetadata, + ...provided.inheritableMetadata + } + }); +} +/** +* True when the caller is starting a fresh top-level run (invoke-time +* `thread_id`, no active nesting keys). In that case the ambient `configurable` +* from `AsyncLocalStorage` cannot be trusted per-key — it may belong to another +* concurrent invocation on a shared singleton agent (scratchpad/task-input as +* well as arbitrary user keys like `tenant_id`/`user_id`). The whole ambient +* `configurable` is therefore ignored; any value the caller actually wants for +* this run arrives through the explicit (bound + invoke-time) configs instead. +* +* Only the last caller-supplied config is treated as invoke-time options. +* Earlier entries are graph-bound defaults from `.withConfig()` / compile and +* must not count — a child graph bound with `thread_id` and invoked from a +* parent task without a fresh config still needs ambient nesting keys from ALS. +*/ +function isRootLevelExplicitInvoke(configs) { + let invokeConfig; + for (let i = configs.length - 1; i >= 0; i -= 1) if (configs[i] !== void 0) { + invokeConfig = configs[i]; + break; + } + const hasInvokeTimeThreadId = invokeConfig?.configurable?.thread_id !== void 0; + const hasExplicitNesting = configs.some((c) => c?.configurable?.[CONFIG_KEY_READ] !== void 0); + const hasAmbientNesting = (AsyncLocalStorageProviderSingleton.getRunnableConfig()?.configurable)?.[CONFIG_KEY_READ] !== void 0; + return hasInvokeTimeThreadId && !hasExplicitNesting && !hasAmbientNesting; +} +function ensureLangGraphConfig(...configs) { + const empty = { + tags: [], + metadata: {}, + callbacks: void 0, + recursionLimit: DEFAULT_RECURSION_LIMIT, + configurable: {} + }; + const skipImplicitConfigurable = isRootLevelExplicitInvoke(configs); + const implicitConfig = AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (implicitConfig !== void 0) { + for (const [k, v] of Object.entries(implicitConfig)) if (v !== void 0) { + if (k === "configurable" && skipImplicitConfigurable) continue; + if (COPIABLE_KEYS.includes(k)) { + let copiedValue; + if (Array.isArray(v)) copiedValue = [...v]; + else if (typeof v === "object") if (k === "callbacks" && "copy" in v && typeof v.copy === "function") copiedValue = v.copy(); + else copiedValue = { ...v }; + else copiedValue = v; + empty[k] = copiedValue; + } else empty[k] = v; + } + } + for (const config of configs) { + if (config === void 0) continue; + for (const [k, v] of Object.entries(config)) { + if (v === void 0 || !CONFIG_KEYS.includes(k)) continue; + if (k === "configurable") empty.configurable = { + ...empty.configurable, + ...v + }; + else if (k === "metadata") empty.metadata = { + ...empty.metadata, + ...v + }; + else if (k === "tags") empty.tags = [...empty.tags ?? [], ...v]; + else if (k === "callbacks") empty.callbacks = mergeCallbacks(empty.callbacks, v); + else empty[k] = v; + } + } + empty.metadata = propagateConfigurableToMetadata(empty.configurable, empty.metadata) ?? {}; + return empty; +} +/** +* A helper utility function that returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized. +* +* Note: This only works when running in an environment that supports node:async_hooks and AsyncLocalStorage. If you're running this in a +* web environment, access the LangGraphRunnableConfig from the node function directly. +* +* @returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized +*/ +function getConfig() { + return AsyncLocalStorageProviderSingleton.getRunnableConfig(); +} +/** +* A helper utility function that returns the input for the currently executing +* task. +* +* Note: When called without arguments, this relies on `node:async_hooks` / +* `AsyncLocalStorage`, which is available in many JavaScript environments +* (Node.js, Deno, Cloudflare Workers) but not in web browsers. In environments +* without `AsyncLocalStorage` support, pass the `config` that your node/tool +* function receives directly, e.g. `getCurrentTaskInput(config)`. +* +* Tip: Inside a tool run by a `ToolNode`, prefer reading graph state from +* `runtime.state` on the second tool argument (typed as `ToolRuntime` from +* `@langchain/core/tools`). It works in every runtime, including web browsers. +* +* @param config - Optional {@link LangGraphRunnableConfig} to read the task +* input from. Provide this when running in an environment without +* `AsyncLocalStorage` support (e.g. web browsers). +* @returns the input for the currently executing task +*/ +function getCurrentTaskInput(config) { + const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join("\n")); + if (runConfig.configurable?.["__pregel_scratchpad"]?.currentTaskInput === void 0) throw new Error("BUG: internal scratchpad not initialized."); + return runConfig.configurable[CONFIG_KEY_SCRATCHPAD].currentTaskInput; +} +function recastCheckpointNamespace(namespace) { + return namespace.split("|").filter((part) => !part.match(/^\d+$/)).map((part) => part.split(":")[0]).join("|"); +} +function getParentCheckpointNamespace(namespace) { + const parts = namespace.split("|"); + while (parts.length > 1 && parts[parts.length - 1].match(/^\d+$/)) parts.pop(); + return parts.slice(0, -1).join("|"); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/runtime.js +/** +* Run-scoped control surface for cooperative draining. +* +* Intended for a single graph run. Create a fresh {@link RunControl} per run; +* reusing a control after {@link RunControl#requestDrain} leaves it drained. +* +* Safe to use from any concurrent context: the drain request is represented +* by a single field write, so no synchronization is needed for this signal. +* If more mutable state is added here, add synchronization. +* +* The intended use is hooking SIGTERM (or any external supervisor signal) to +* {@link RunControl#requestDrain} so an in-flight graph run can stop cleanly +* at the next superstep boundary and be resumed later from the saved +* checkpoint. +* +* @example +* ```typescript +* import { RunControl, GraphDrained } from "@langchain/langgraph"; +* +* const control = new RunControl(); +* +* // In a signal handler, supervisor, etc.: +* // control.requestDrain("sigterm"); +* +* try { +* const result = await graph.invoke(input, { ...config, control }); +* if (control.drainRequested) { +* // finished naturally on the same tick where drain was requested +* } +* } catch (e) { +* if (e instanceof GraphDrained) { +* // checkpoint saved; resume later with the same config +* } else { +* throw e; +* } +* } +* ``` +*/ +var RunControl = class { + #drainReason = void 0; + /** + * Request that the current run drain cooperatively, stopping at the next + * superstep boundary. Does not cancel work that is already running. + * + * @param reason - A short description of why the drain was requested. + * Surfaced on the resulting {@link GraphDrained} error. + */ + requestDrain(reason = "shutdown") { + this.#drainReason = reason; + } + /** Whether a drain has been requested for this run. */ + get drainRequested() { + return this.#drainReason !== void 0; + } + /** The reason passed to {@link RunControl#requestDrain}, if any. */ + get drainReason() { + return this.#drainReason; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/stream/convert.js +/** +* The set of stream modes requested by +* `streamEvents(..., { version: "v3" })` — every mode the protocol maps +* to a channel. +* +* The verbose `"debug"` mode is intentionally excluded: it was a thin +* re-wrap of `checkpoints` + `tasks` carrying no new information. +* +* The `"checkpoints"` mode is likewise excluded from the stream-mode +* request because the protocol's `checkpoints` channel carries only a +* lightweight envelope (`id`, `parent_id`, `step`, `source`) emitted as a +* separate ``[namespace, "checkpoints", envelope]`` chunk before each paired +* `values` chunk — not the full-state shape from Pregel's `checkpoints` +* stream mode when subscribed via `debug`. +*/ +var STREAM_EVENTS_V3_MODES = [ + "values", + "updates", + "messages", + "tools", + "custom", + "tasks" +]; +/** +* True when `payload` is a lightweight checkpoint envelope (not a full-state +* Pregel `checkpoints` debug payload). +*/ +function isCheckpointEnvelope(payload) { + if (payload == null || typeof payload !== "object") return false; + const p = payload; + return typeof p.id === "string" && ("source" in p || typeof p.step === "number") && !("values" in p) && !("config" in p); +} +function unwrapMessagesPayload(payload) { + if (!Array.isArray(payload) || payload.length !== 2) return { data: payload }; + const [data, metadata] = payload; + if (metadata == null || typeof metadata !== "object") return { data: payload }; + const record = metadata; + const node = typeof record.langgraph_node === "string" ? record.langgraph_node : void 0; + const runId = typeof record.run_id === "string" ? record.run_id : void 0; + return { + data: runId != null && data != null && typeof data === "object" ? { + ...data, + run_id: runId + } : data, + node + }; +} +function convertToProtocolEvent({ namespace: ns, mode, payload, seq }) { + const timestamp = Date.now(); + const base = { type: "event" }; + switch (mode) { + case "messages": { + const { data, node } = unwrapMessagesPayload(payload); + return [{ + ...base, + seq, + method: "messages", + params: { + namespace: ns, + timestamp, + ...node ? { node } : {}, + data + } + }]; + } + case "tools": return [{ + ...base, + seq, + method: "tools", + params: { + namespace: ns, + timestamp, + data: convertToolsPayload(payload) + } + }]; + case "checkpoints": + if (!isCheckpointEnvelope(payload)) return []; + return [{ + ...base, + seq, + method: "checkpoints", + params: { + namespace: ns, + timestamp, + data: payload + } + }]; + case "values": return [{ + ...base, + seq, + method: "values", + params: { + namespace: ns, + timestamp, + data: payload + } + }]; + case "updates": { + const data = convertUpdatesPayload(payload); + return [{ + ...base, + seq, + method: "updates", + params: { + namespace: ns, + timestamp, + ...typeof data.node === "string" ? { node: data.node } : {}, + data + } + }]; + } + case "custom": { + const data = typeof payload === "object" && payload !== null && !Array.isArray(payload) && "name" in payload ? payload : { payload }; + return [{ + ...base, + seq, + method: "custom", + params: { + namespace: ns, + timestamp, + data + } + }]; + } + case "tasks": return [{ + ...base, + seq, + method: "tasks", + params: { + namespace: ns, + timestamp, + data: payload + } + }]; + default: return []; + } +} +/** +* Normalises a raw tools-mode payload into a typed {@link ToolsEventData} +* discriminated union, mapping internal lifecycle events (`on_tool_start`, +* `on_tool_end`, etc.) to their protocol counterparts. +* +* @param payload - The raw payload from a `"tools"` stream chunk. +* @returns A {@link ToolsEventData} object with the appropriate `event` +* discriminant and associated fields. +*/ +function convertToolsPayload(payload) { + if (typeof payload !== "object" || payload === null) return { + event: "tool-error", + tool_call_id: "", + message: "Unexpected tools payload shape" + }; + const p = payload; + const tool_call_id = String(p.toolCallId ?? ""); + switch (p.event) { + case "on_tool_start": return { + event: "tool-started", + tool_call_id, + tool_name: String(p.name ?? "unknown"), + input: p.input + }; + case "on_tool_event": return { + event: "tool-output-delta", + tool_call_id, + delta: typeof p.data === "string" ? p.data : JSON.stringify(p.data ?? "") + }; + case "on_tool_end": return { + event: "tool-finished", + tool_call_id, + output: p.output + }; + case "on_tool_error": { + const err = p.error; + return { + event: "tool-error", + tool_call_id, + message: typeof err === "object" && err !== null && "message" in err && typeof err.message === "string" ? err.message : String(err ?? "unknown error") + }; + } + default: return { + event: "tool-error", + tool_call_id: "", + message: `Unknown tool event: ${String(p.event)}` + }; + } +} +/** +* Extracts the first `{node: delta}` entry from an updates-mode payload and +* reshapes it into an {@link UpdatesEventData} with explicit `node` and +* `values` fields. Non-object payloads are coerced to `{ values: {} }`. +* +* @param payload - The raw payload from an `"updates"` stream chunk, +* expected to be a `Record` keyed by node name. +* @returns An {@link UpdatesEventData} containing the extracted node name +* and its associated delta values. +*/ +function convertUpdatesPayload(payload) { + if (typeof payload !== "object" || payload === null) return { values: {} }; + const entries = Object.entries(payload); + if (entries.length === 0) return { values: {} }; + const [node, values] = entries[0]; + return { + node, + values: typeof values === "object" && values !== null ? values : { value: values } + }; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/stream/stream-channel.js +/** +* StreamChannel — projection channel for local or remote streaming. +* +* A `StreamChannel` is an append-only async stream with independent +* cursors. Local channels stay in-process only. Remote channels declare a +* protocol channel name; when registered with a {@link StreamMux} (via a +* transformer's `init()` return value), every {@link push} is automatically +* forwarded as a {@link ProtocolEvent} on `custom:` — making the +* data available both in-process (via `run.extensions`) and to remote clients +* (via `session.subscribe("custom:")`). +* +* Lifecycle (`close` / `fail`) is managed by the mux automatically; +* transformers do not need to call them. +*/ +/** +* Branded symbol placed on every {@link StreamChannel} instance. +* +* Uses `Symbol.for` so the same symbol is shared across multiple +* copies of this package that may coexist in a dependency graph +* (e.g. when a user app imports `@langchain/langgraph` directly and a +* wrapping library like `langchain` bundles its own copy). Using a +* symbol brand instead of `instanceof` lets channels created against +* one copy of the class be recognised by a mux from another. +* @internal +*/ +var STREAM_CHANNEL_BRAND = Symbol.for("langgraph.stream_channel"); +/** +* A projection channel for {@link StreamTransformer}s. +* +* Implements `AsyncIterable` so it can be iterated directly by +* in-process consumers via `run.extensions.`. Channels created with +* {@link StreamChannel.remote} or `new StreamChannel(name)` are also +* auto-forwarded to remote clients. +* +* @typeParam T - The type of items pushed into the channel. +*/ +var StreamChannel = class StreamChannel { + /** @internal Brand used by {@link StreamChannel.isInstance}. */ + [STREAM_CHANNEL_BRAND] = true; + /** Protocol channel name used for auto-forwarded events, if remote. */ + channelName; + #items = []; + #waiters = []; + #done = false; + #error; + #onPush; + constructor(name) { + this.channelName = name; + } + /** + * Create an in-process-only channel. Values remain available through + * `run.extensions.` but are not forwarded to remote clients. + */ + static local() { + return new StreamChannel(); + } + /** + * Create a channel whose pushes are forwarded to remote clients under + * the given protocol channel name. + */ + static remote(name) { + return new StreamChannel(name); + } + /** + * Brand-based type guard that recognises any {@link StreamChannel} + * instance, even ones originating from a different copy of this + * package. Prefer this over `instanceof StreamChannel` when code + * may observe channels that were constructed elsewhere. + */ + static isInstance(value) { + return typeof value === "object" && value !== null && STREAM_CHANNEL_BRAND in value && value[STREAM_CHANNEL_BRAND] === true; + } + /** + * Append an item to the channel. If this is a remote channel wired to a + * mux, the item is also injected into the main protocol event stream under + * {@link channelName}. + */ + push(item) { + this.#items.push(item); + this.#wake(); + this.#onPush?.(item); + } + /** + * Returns an async iterator starting at position {@link startAt}. Each call + * returns an independent cursor so multiple consumers can iterate the same + * channel concurrently. + */ + iterate(startAt = 0) { + let cursor = startAt; + return { next: async () => { + while (true) { + if (cursor < this.#items.length) return { + value: this.#items[cursor++], + done: false + }; + if (this.#done) { + if (this.#error) throw this.#error; + return { + value: void 0, + done: true + }; + } + await new Promise((resolve) => this.#waiters.push(resolve)); + } + } }; + } + /** + * Creates an {@link AsyncIterable} backed by this channel, starting from + * {@link startAt}. + */ + toAsyncIterable(startAt = 0) { + return { [Symbol.asyncIterator]: () => this.iterate(startAt) }; + } + /** + * Creates a web {@link ReadableStream} that emits channel items as + * Server-Sent Events. Useful for returning a channel directly from + * `new Response(channel.toEventStream())`. + */ + toEventStream(options = {}) { + const encoder = new TextEncoder(); + const iterator = this.iterate(options.startAt); + const event = options.event ?? this.channelName; + const serialize = options.serialize ?? ((item) => JSON.stringify(item) ?? "null"); + return new ReadableStream({ + async pull(controller) { + try { + const next = await iterator.next(); + if (next.done) { + controller.close(); + return; + } + const lines = []; + if (event != null) lines.push(`event: ${event}`); + for (const line of serialize(next.value).split(/\r\n|\r|\n/)) lines.push(`data: ${line}`); + controller.enqueue(encoder.encode(`${lines.join("\n")}\n\n`)); + } catch (error) { + controller.error(error); + } + }, + async cancel() { + await iterator.return?.(); + } + }); + } + /** + * Returns the item at the given zero-based index. + * + * @throws {RangeError} If the index is out of bounds. + */ + get(index) { + if (index < 0 || index >= this.#items.length) throw new RangeError(`StreamChannel index ${index} out of bounds (size=${this.#items.length})`); + return this.#items[index]; + } + /** The number of items currently buffered in the channel. */ + get size() { + return this.#items.length; + } + /** Whether the channel has been closed or failed. */ + get done() { + return this.#done; + } + /** Mark the channel as complete after all buffered items are consumed. */ + close() { + this.#done = true; + this.#wake(); + } + /** Mark the channel as failed after all buffered items are consumed. */ + fail(err) { + this.#error = err; + this.#done = true; + this.#wake(); + } + /** @internal Called by the mux to wire auto-forwarding. */ + _wire(fn) { + this.#onPush = fn; + } + /** @internal Called by the mux on normal completion. */ + _close() { + this.close(); + } + /** @internal Called by the mux on failure. */ + _fail(err) { + this.fail(err); + } + [Symbol.asyncIterator]() { + return this.iterate(); + } + #wake() { + const waiters = this.#waiters.splice(0); + for (const w of waiters) w(); + } +}; +/** +* Type guard that tests whether a value is a {@link StreamChannel}. +* +* Uses a symbol brand rather than `instanceof` so channels built +* against a different copy of this package (e.g. one bundled by the +* `langchain` umbrella package) are still recognised. +*/ +function isStreamChannel(value) { + return StreamChannel.isInstance(value); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/stream/mux.js +/** Wire prefix for user-defined {@link StreamChannel} auto-forwards. */ +var EXTENSION_CHANNEL_PREFIX = "custom:"; +/** +* Protocol method for a user-defined (extension) {@link StreamChannel}. +* Matches Python's `StreamMux._bind_and_wire` (`f"custom:{value.name}"`). +*/ +function extensionChannelMethod(channelName) { + return `${EXTENSION_CHANNEL_PREFIX}${channelName}`; +} +/** +* Structural `PromiseLike` predicate — true for thenables including +* native promises, user-constructed `{ then }` objects, and helper +* wrappers. Used by {@link StreamMux.wireChannels} to detect final-value +* projections distinctly from streaming `StreamChannel` values. +*/ +function isPromiseLike(value) { + return value != null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function"; +} +/** +* Symbol key used by {@link StreamMux} to resolve the values promise on a +* stream handle. Using a symbol keeps this off the public autocomplete surface. +*/ +var RESOLVE_VALUES = Symbol("resolveValues"); +/** +* Symbol key used by {@link StreamMux} to reject the values promise on a +* stream handle. Using a symbol keeps this off the public autocomplete surface. +*/ +var REJECT_VALUES = Symbol("rejectValues"); +/** +* Central event dispatcher that routes {@link ProtocolEvent}s through a +* pipeline of {@link StreamTransformer}s, manages namespace discovery for +* subgraph streams, and exposes async iteration over filtered event +* sequences. +* +* One `StreamMux` instance exists per top-level +* `streamEvents(..., { version: "v3" })` invocation. +*/ +var StreamMux = class { + /** @internal All protocol events in arrival order (after reducer pipeline). */ + _events = StreamChannel.local(); + /** @internal New-namespace discovery notifications. */ + _discoveries = StreamChannel.local(); + /** Monotonic counter for auto-forwarded channel events. */ + #nextEmitSeq = 0; + /** Whether the mux has been closed or failed. */ + #closed = false; + /** The error passed to {@link fail}, if any. */ + #error; + /** Whether the run was interrupted. */ + #interrupted = false; + /** + * Namespace of the event currently being processed by + * {@link push}. Read by {@link StreamChannel} wiring callbacks so + * auto-forwarded events inherit the triggering event's namespace. + */ + #currentNamespace = []; + #transformers = []; + #channels = []; + #streamMap = /* @__PURE__ */ new Map(); + #latestValues = /* @__PURE__ */ new Map(); + #interrupts = []; + /** + * Final-value projection keys tracked for remote surfacing. Populated + * by {@link wireChannels} when a transformer's projection contains a + * `PromiseLike` value. Each entry is flushed as a `custom:` + * protocol event during {@link close} so that remote clients can + * observe final-value transformers via `thread.extensions.`. + */ + #finalValues = []; + /** + * Associates a pre-existing stream handle with a namespace so that + * {@link close} can resolve its values promise later. + * + * @param path - The namespace path to register. + * @param stream - The run stream handle for that namespace. + */ + register(path, stream) { + this.#streamMap.set(nsKey(path), stream); + } + /** + * Registers a transformer and replays all buffered events through it so + * it catches up with events already processed by the mux. When the event + * log is empty (typical at construction time) the replay is a no-op. + * + * The transformer must already have been initialised (i.e. `init()` called + * and any projection wired). The sequence is: + * + * 1. Snapshot the current event log length. + * 2. Append the transformer so future {@link push} calls reach it. + * 3. Replay events `[0, snapshot)` through `process()`. + * 4. If the mux is already closed, call `finalize()` (or `fail()`) + * immediately so the transformer's log/channel terminates cleanly. + * + * @param transformer - An already-initialised transformer to register. + */ + addTransformer(transformer) { + const snapshot = this._events.size; + this.#transformers.push(transformer); + if (transformer.onRegister) transformer.onRegister({ push: (ns, event) => this.push(ns, event) }); + for (let i = 0; i < snapshot; i += 1) transformer.process(this._events.get(i)); + if (this.#closed) if (this.#error !== void 0) transformer.fail?.(this.#error); + else transformer.finalize?.(); + } + /** + * Scans a transformer projection for streaming and final-value primitives. + * Remote stream channels are wired to auto-forward to the protocol event + * stream; local stream channels are tracked for lifecycle only. + * + * Two projection shapes are recognised: + * + * - {@link StreamChannel} values — named channels forward each `push()` + * immediately as a `custom:` protocol event. Unnamed + * channels remain in-process-only. + * + * - `PromiseLike` values — tracked as final-value + * projections and flushed on {@link close} as a single + * `custom:` event, where `` is the projection key. + * This mirrors the in-process `await run.extensions.` + * ergonomics on remote clients via + * `await thread.extensions.`. + * + * Plain values that are neither are ignored — they remain in-process-only, + * matching prior behaviour. + * + * @param projection - The object returned by `transformer.init()`. + */ + wireChannels(projection) { + for (const [key, value] of Object.entries(projection)) { + if (isStreamChannel(value)) { + this.#channels.push(value); + if (typeof value.channelName !== "string") continue; + const method = extensionChannelMethod(value.channelName); + value._wire((item) => { + this._events.push({ + type: "event", + seq: this.#nextEmitSeq++, + method, + params: { + namespace: this.#currentNamespace, + timestamp: Date.now(), + data: item + } + }); + }); + continue; + } + if (isPromiseLike(value)) this.#finalValues.push({ + name: key, + promise: Promise.resolve(value) + }); + } + } + /** + * Distributes an event through the transformer pipeline, then appends it to + * the main event log. + * + * Subgraph discovery (materializing a {@link StreamHandle} for each + * newly observed top-level namespace) is handled by the + * {@link createSubgraphDiscoveryTransformer} when installed, not here. + * + * @param ns - The namespace path that produced the event. + * @param event - The protocol event to process and store. + */ + push(ns, event) { + if (event.method === "values") this.#latestValues.set(nsKey(ns), event.params.data); + const outerNamespace = this.#currentNamespace; + this.#currentNamespace = ns; + let keep = true; + for (const transformer of this.#transformers) if (!transformer.process(event)) keep = false; + this.#currentNamespace = outerNamespace; + if (keep) this._events.push({ + ...event, + seq: this.#nextEmitSeq++ + }); + } + /** + * Gracefully ends the stream: resolves values promises on all known + * streams, finalizes every transformer, auto-closes streaming + * channels, flushes any final-value projections as `custom:` + * events, and closes both event logs. + * + * When final-value projections are present, `_events.close()` is + * deferred until every tracked projection promise has settled so + * remote consumers observe the flushed values before their event + * stream ends. Callers do not need to await — `close()` returns + * synchronously and any downstream consumer iterating + * {@link _events} naturally waits for the final events. + */ + close() { + this.#closed = true; + for (const [key, values] of this.#latestValues.entries()) { + const ns = key ? key.split("\0") : []; + this.#streamMap.get(nsKey(ns))?.[RESOLVE_VALUES](values); + } + const finalizePromises = []; + for (const transformer of this.#transformers) { + const result = transformer.finalize?.(); + if (result != null && typeof result.then === "function") finalizePromises.push(result); + } + for (const channel of this.#channels) channel._close(); + const finalValues = this.#finalValues; + if (finalValues.length === 0 && finalizePromises.length === 0) { + this._events.close(); + this._discoveries.close(); + } else Promise.allSettled([...finalizePromises, ...finalValues.map(async ({ name, promise }) => { + try { + const resolved = await promise; + if (!this._events.done) this._events.push({ + type: "event", + seq: this.#nextEmitSeq++, + method: "custom", + params: { + namespace: [], + timestamp: Date.now(), + data: { + name, + payload: resolved + } + } + }); + } catch {} + })]).then(() => { + this._events.close(); + this._discoveries.close(); + }); + for (const stream of this.#streamMap.values()) stream[RESOLVE_VALUES](void 0); + } + /** + * Propagates a failure to all transformers, channels, event logs, and + * stream handles. + * + * @param err - The error that caused the run to fail. + */ + fail(err) { + this.#closed = true; + this.#error = err; + for (const transformer of this.#transformers) transformer.fail?.(err); + for (const channel of this.#channels) channel._fail(err); + this._events.fail(err); + this._discoveries.fail(err); + for (const stream of this.#streamMap.values()) stream[REJECT_VALUES](err); + } + /** + * Records that the run was interrupted, appending the supplied payloads + * for later retrieval. + * + * @param interrupts - The interrupt payloads to store. + */ + markInterrupted(interrupts) { + this.#interrupted = true; + this.#interrupts.push(...interrupts); + } + /** + * Whether the run ended due to an interrupt. + * + * @returns `true` if {@link markInterrupted} was called. + */ + get interrupted() { + return this.#interrupted; + } + /** + * All interrupt payloads collected during the run. + * + * @returns A readonly view of the accumulated interrupt payloads. + */ + get interrupts() { + return this.#interrupts; + } + /** + * Returns an async iterator that yields only events whose namespace + * starts with {@link path}. + * + * @param path - Namespace prefix to filter on. + * @param startAt - Zero-based index into the event log to begin from. + * @returns An async iterator over matching {@link ProtocolEvent}s. + */ + subscribeEvents(path, startAt = 0) { + const base = this._events.iterate(startAt); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) return result; + if (hasPrefix(result.value.params.namespace, path)) return result; + } + } }; + } +}; +/** +* Background consumer that drains a raw `graph.stream()` source into a +* {@link StreamMux}. Converts each chunk to a {@link ProtocolEvent} and +* pushes it; calls {@link StreamMux.close} on normal completion or +* {@link StreamMux.fail} on error. +* +* @param source - The async iterable of raw stream chunks from the engine. +* @param mux - The mux instance to feed. +* @returns A promise that resolves when the source is fully consumed. +*/ +async function pump(source, mux) { + let seq = 0; + try { + for await (const chunk of source) { + const [ns, mode, payload] = chunk; + if (mode === "values" && isInterrupted(payload)) { + const interrupts = payload[INTERRUPT$1]; + mux.markInterrupted(interrupts.map((i) => ({ + interruptId: i.id ?? "", + payload: i.value + }))); + } + const events = convertToProtocolEvent({ + namespace: ns, + mode, + payload, + seq + }); + seq += events.length; + for (const event of events) mux.push(ns, event); + } + } catch (err) { + mux.fail(err); + return; + } + mux.close(); +} +/** +* Serialises a {@link Namespace} array into a single string key using the +* null byte (`\x00`) as separator, suitable for `Map`/`Set` lookups. +* +* @param ns - The namespace segments to join. +* @returns A null-byte-joined string key. +*/ +function nsKey(ns) { + return ns.join("\0"); +} +/** +* Tests whether {@link ns} starts with every segment in {@link prefix}. +* +* @param ns - The full namespace to check. +* @param prefix - The prefix to match against. +* @returns `true` if `ns` begins with `prefix` segment-by-segment. +*/ +function hasPrefix(ns, prefix) { + if (prefix.length > ns.length) return false; + for (let i = 0; i < prefix.length; i += 1) if (ns[i] !== prefix[i]) return false; + return true; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/stream/transformers/lifecycle.js +/** +* Filter a lifecycle {@link StreamChannel} to only the entries whose +* namespace lies within the subtree rooted at {@link path}. +* +* Returns an `AsyncIterable` whose iterator yields every entry whose +* namespace either equals {@link path} or is a descendant of it. +* Iteration begins at {@link startAt}, so callers can capture the +* log's current size at construction time to skip entries emitted +* before the caller existed (e.g. a subgraph stream discovered +* mid-run shouldn't replay the root's `started`). +* +* @param log - The shared lifecycle log owned by the transformer. +* @param path - Namespace prefix to scope entries by (use `[]` for +* the root subtree, i.e. everything). +* @param startAt - Zero-based index into the log to begin from. +* @returns An async iterable of matching lifecycle entries. +*/ +function filterLifecycleEntries(log, path, startAt = 0) { + return { [Symbol.asyncIterator]() { + const base = log.iterate(startAt); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) return { + value: void 0, + done: true + }; + if (hasPrefix(result.value.namespace, path)) return { + value: result.value, + done: false + }; + } + } }; + } }; +} +var DEFAULT_ROOT_GRAPH_NAME = "root"; +function defaultGuessGraphName(ns) { + if (ns.length === 0) return DEFAULT_ROOT_GRAPH_NAME; + const last = ns[ns.length - 1]; + const colon = last.indexOf(":"); + return colon === -1 ? last : last.slice(0, colon); +} +function defaultSerializeError(err) { + if (err instanceof Error) return err.message; + if (typeof err === "string") return err; + try { + return JSON.stringify(err); + } catch { + return String(err); + } +} +function isRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +/** +* Extract an upstream `cause` from a `lifecycle.started` payload, if +* the shape matches one of the known variants. Shape validation is +* intentionally loose: any object with a string `type` is accepted, so +* future protocol variants flow through unchanged. +*/ +function extractCause(data) { + if (!isRecord(data)) return void 0; + if (data.event !== "started") return void 0; + const cause = data.cause; + if (!isRecord(cause)) return void 0; + if (typeof cause.type !== "string") return void 0; + return cause; +} +function extractTaskResultCompletion(data) { + if (!isRecord(data)) return void 0; + if (!("result" in data)) return void 0; + if (typeof data.name !== "string") return void 0; + if (typeof data.id !== "string") return void 0; + if (data.name.startsWith("__")) return void 0; + return { + name: data.name, + id: data.id + }; +} +/** +* Create the built-in lifecycle transformer. +* +* Marked as a {@link NativeStreamTransformer} so the run stream +* factory can expose `_lifecycleLog` via a dedicated getter +* (`run.lifecycle`) rather than through `run.extensions`. +*/ +function createLifecycleTransformer(options = {}) { + const rootGraphName = options.rootGraphName ?? DEFAULT_ROOT_GRAPH_NAME; + const initialStatus = options.initialStatus ?? "running"; + const emitRootOnRegister = options.emitRootOnRegister ?? true; + const getGraphName = options.getGraphName ?? defaultGuessGraphName; + const serializeError = options.serializeError ?? defaultSerializeError; + const getTerminalStatusOverride = options.getTerminalStatusOverride; + const log = StreamChannel.local(); + const namespaces = /* @__PURE__ */ new Map(); + const namespaceCause = /* @__PURE__ */ new Map(); + /** + * `lc_agent_name` observed at each namespace (first task event wins). A + * nested run carrying an `lc_agent_name` (set by `createAgent`) is treated + * as a named subagent: its `graph_name` becomes that name and a tool-call + * `cause` is recovered (see {@link deriveToolCallCause}). Namespaces without + * one fall back to the parsed namespace segment, preserving the prior + * product-agnostic behavior for plain subgraphs. + */ + const lcByNs = /* @__PURE__ */ new Map(); + /** + * Pregel task id -> triggering LLM `tool_call_id`, harvested from a task + * whose `input` is a `tool_call_with_context` dict (current shape) or a list + * of tool-call dicts (legacy shape). The child subgraph's namespace segment + * `node:` shares this task id, so a named subagent recovers the tool + * call that spawned it across payloads. + */ + const pendingToolCalls = /* @__PURE__ */ new Map(); + const pendingInterruptIds = /* @__PURE__ */ new Set(); + /** + * Child namespaces whose parent just saw an `updates` event with a + * `node` attribution. We defer the `lifecycle.completed` emission + * until the *next* inbound event (or `finalize`) so the parent's + * `updates` lands on the wire before its child is marked complete - + * matching the previous session behavior. + */ + const pendingCompletions = []; + let emitter; + let inSelfEmit = 0; + let finalized = false; + const resolveGraphName = (ns) => { + if (ns.length === 0) return rootGraphName; + const lc = lcByNs.get(nsKey(ns)); + if (typeof lc === "string" && lc.length > 0) return lc; + return getGraphName(ns); + }; + /** + * Record a namespace's `lc_agent_name` from a task-start payload (first + * event wins). The presence of a name is what marks the namespace a named + * subagent; the value may be `undefined` for unnamed runs (still recorded so + * a later event doesn't re-evaluate it). + */ + const recordIdentity = (ns, data) => { + const key = nsKey(ns); + if (lcByNs.has(key)) return; + const lc = (isRecord(data) && isRecord(data.metadata) ? data.metadata : void 0)?.lc_agent_name; + lcByNs.set(key, typeof lc === "string" ? lc : void 0); + }; + /** + * Harvest a task's triggering `tool_call_id` keyed by its task id. The + * spawned subgraph's namespace segment `node:` shares that id, so a + * subagent can later recover the tool call that caused it. Two input shapes + * are handled: a `tool_call_with_context` object (`input.tool_call.id`) and a + * legacy list of tool-call objects (first with a string `id`). + */ + const recordPendingToolCalls = (data) => { + if (!isRecord(data)) return; + const taskId = data.id; + if (typeof taskId !== "string") return; + const input = data.input; + let toolCallId; + if (isRecord(input) && isRecord(input.tool_call)) { + const candidate = input.tool_call.id; + if (typeof candidate === "string") toolCallId = candidate; + } else if (Array.isArray(input)) { + for (const toolCall of input) if (isRecord(toolCall) && typeof toolCall.id === "string") { + toolCallId = toolCall.id; + break; + } + } + if (toolCallId != null) pendingToolCalls.set(taskId, toolCallId); + }; + /** + * Derive a `toolCall` cause for a named subagent namespace by joining the + * namespace segment's task id (`node:`) to a previously harvested + * `tool_call_id`. Only fires for namespaces carrying an `lc_agent_name`, so + * plain subgraphs never get a spurious cause. + */ + const deriveToolCallCause = (ns) => { + if (ns.length === 0) return void 0; + const lc = lcByNs.get(nsKey(ns)); + if (typeof lc !== "string" || lc.length === 0) return void 0; + const segment = ns[ns.length - 1]; + const colon = segment.indexOf(":"); + if (colon === -1) return void 0; + const triggerCallId = segment.slice(colon + 1); + if (triggerCallId.length === 0) return void 0; + const toolCallId = pendingToolCalls.get(triggerCallId); + if (typeof toolCallId !== "string" || toolCallId.length === 0) return; + return { + type: "toolCall", + tool_call_id: toolCallId + }; + }; + /** + * Resolve the `cause` to attach to a namespace's `started`. An upstream + * `cause` stashed from a product-specific transformer (e.g. deepagents' + * SubagentTransformer) wins; otherwise a tool-call cause is recovered for + * named subagents. + */ + const resolveStartCause = (ns) => namespaceCause.get(nsKey(ns)) ?? deriveToolCallCause(ns); + const emit = (ns, status, extras) => { + const key = nsKey(ns); + let current = namespaces.get(key); + const graphName = current?.graphName ?? resolveGraphName(ns); + if (current != null && current.status === status && current.graphName === graphName && extras?.error == null) return; + if (current == null) { + current = { + namespace: ns, + graphName, + status + }; + namespaces.set(key, current); + } else current.status = status; + const data = { + event: status, + graph_name: graphName, + ...extras?.cause != null ? { cause: extras.cause } : {}, + ...extras?.error != null ? { error: extras.error } : {} + }; + const timestamp = Date.now(); + log.push({ + namespace: ns, + timestamp, + ...data + }); + if (ns.length === 0 && !emitRootOnRegister) return; + if (emitter == null) return; + inSelfEmit += 1; + try { + emitter.push(ns, { + type: "event", + seq: 0, + method: "lifecycle", + params: { + namespace: ns, + timestamp, + data + } + }); + } finally { + inSelfEmit -= 1; + } + }; + /** + * Ensures a record exists for `ns` without mutating its status. Used + * by hooks that need a canonical `graphName` for lookups before emit + * writes the first status. Status remains `undefined` until `emit` + * fires. + */ + const trackNamespace = (ns) => { + const key = nsKey(ns); + let rec = namespaces.get(key); + if (rec == null) { + rec = { + namespace: ns, + graphName: resolveGraphName(ns), + status: void 0 + }; + namespaces.set(key, rec); + } + return rec; + }; + const flushPendingCompletions = () => { + if (pendingCompletions.length === 0) return; + const toFlush = pendingCompletions.splice(0, pendingCompletions.length); + for (const completion of toFlush) { + const key = nsKey(completion.namespace); + const rec = namespaces.get(key); + if (rec == null || rec.status !== "started") continue; + emit(completion.namespace, "completed"); + } + }; + const enqueueCompletion = (completion) => { + const key = nsKey(completion.namespace); + const rec = namespaces.get(key); + if (rec == null || rec.status !== "started") return; + if (pendingCompletions.some((pending) => nsKey(pending.namespace) === key)) return; + pendingCompletions.push(completion); + }; + const removePendingNodeCompletions = (parent, node) => { + for (let index = pendingCompletions.length - 1; index >= 0; index -= 1) { + const pending = pendingCompletions[index]; + if (pending.source.type !== "node") continue; + if (pending.source.node !== node) continue; + if (nsKey(pending.source.parent) !== nsKey(parent)) continue; + pendingCompletions.splice(index, 1); + } + }; + const ensureStarted = (ns) => { + for (let length = 1; length <= ns.length; length += 1) { + const prefix = ns.slice(0, length); + const key = nsKey(prefix); + if (namespaces.has(key)) continue; + trackNamespace(prefix); + const cause = resolveStartCause(prefix); + emit(prefix, "started", cause != null ? { cause } : void 0); + } + }; + const defaultTerminalStatus = () => pendingInterruptIds.size > 0 ? "interrupted" : "completed"; + const cascadeTerminalStatus = (status) => { + for (const rec of namespaces.values()) { + if (rec.namespace.length === 0) continue; + if (rec.status !== "started") continue; + emit(rec.namespace, status); + } + emit([], status); + log.close(); + }; + const resolveTerminalStatusOverride = async () => { + if (getTerminalStatusOverride == null) return defaultTerminalStatus(); + try { + return await getTerminalStatusOverride() ?? defaultTerminalStatus(); + } catch { + return defaultTerminalStatus(); + } + }; + const findStartedChildForNode = (parentNamespace, node) => { + const prefix = `${node}:`; + for (const rec of namespaces.values()) { + if (rec.namespace.length !== parentNamespace.length + 1) continue; + if (rec.status !== "started") continue; + if (!hasPrefix(rec.namespace, parentNamespace)) continue; + const last = rec.namespace[rec.namespace.length - 1]; + if (last === node || last.startsWith(prefix)) return rec.namespace; + } + }; + const findStartedChildForTask = (parentNamespace, task) => { + const namespace = [...parentNamespace, `${task.name}:${task.id}`]; + return namespaces.get(nsKey(namespace))?.status === "started" ? namespace : void 0; + }; + return { + __native: true, + init() { + return { + _lifecycleLog: log, + lifecycle: filterLifecycleEntries(log, [], 0) + }; + }, + onRegister(handle) { + emitter = handle; + trackNamespace([]); + if (emitRootOnRegister) emit([], initialStatus); + }, + process(event) { + const ns = event.params.namespace; + if (inSelfEmit > 0) return true; + const taskCompletion = event.method === "tasks" ? extractTaskResultCompletion(event.params.data) : void 0; + if (taskCompletion != null) removePendingNodeCompletions(ns, taskCompletion.name); + else if (event.method === "tasks") { + recordIdentity(ns, event.params.data); + recordPendingToolCalls(event.params.data); + } + flushPendingCompletions(); + if (event.method === "lifecycle") { + const cause = extractCause(event.params.data); + if (cause != null) namespaceCause.set(nsKey(ns), cause); + ensureStarted(ns); + return false; + } + ensureStarted(ns); + if (event.method === "input" && isRecord(event.params.data) && event.params.data.event === "requested") { + const id = event.params.data.id; + if (typeof id === "string") pendingInterruptIds.add(id); + } + if (taskCompletion != null) { + const childNamespace = findStartedChildForTask(ns, taskCompletion); + if (childNamespace != null) enqueueCompletion({ + namespace: childNamespace, + source: { type: "task" } + }); + } + if (event.method === "updates") { + const node = event.params.node; + if (typeof node === "string" && !node.startsWith("__")) { + const childNamespace = findStartedChildForNode(ns, node); + if (childNamespace != null) enqueueCompletion({ + namespace: childNamespace, + source: { + type: "node", + parent: ns, + node + } + }); + } + } + return true; + }, + finalize() { + if (finalized) return; + finalized = true; + flushPendingCompletions(); + if (getTerminalStatusOverride == null) { + cascadeTerminalStatus(defaultTerminalStatus()); + return; + } + return resolveTerminalStatusOverride().then(cascadeTerminalStatus).catch((err) => { + log.fail(err); + }); + }, + fail(err) { + if (finalized) return; + finalized = true; + const errorMessage = serializeError(err); + for (const rec of namespaces.values()) { + if (rec.namespace.length === 0) continue; + if (rec.status !== "started") continue; + emit(rec.namespace, "failed"); + } + emit([], "failed", { error: errorMessage }); + log.fail(err); + } + }; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/stream/transformers/messages.js +function getMessageStreamKey(data) { + const record = data; + if (typeof record.run_id === "string") return `run:${record.run_id}`; + if (data.event === "message-start" && typeof record.id === "string") return `message:${record.id}`; + return "__default__"; +} +/** +* Creates a {@link StreamTransformer} that groups `messages` channel events into +* per-message {@link ChatModelStream} instances. +* +* A new `ChatModelStream` is created on `message-start` and closed on +* `message-finish`. Content-block events in between are forwarded to the +* active stream. Only events whose namespace exactly matches {@link path} +* are processed; child namespaces are ignored. +* +* @param path - Namespace prefix to match against incoming events. +* @param nodeFilter - If provided, only events emitted by this graph node +* are processed; all others are skipped. +* @returns A `StreamTransformer` whose projection contains the `messages` +* async iterable. +*/ +function createMessagesTransformer(path, nodeFilter) { + const log = StreamChannel.local(); + const active = /* @__PURE__ */ new Map(); + const ignored = /* @__PURE__ */ new Set(); + return { + init: () => ({ messages: log.toAsyncIterable() }), + process(event) { + if (event.method !== "messages") return true; + if (!hasPrefix(event.params.namespace, path)) return true; + if (event.params.namespace.length !== path.length + 1) return true; + if (nodeFilter !== void 0 && event.params.node !== nodeFilter) return true; + const data = event.params.data; + switch (data.event) { + case "message-start": { + const key = getMessageStreamKey(data); + if (data.role === "tool") { + ignored.add(key); + break; + } + const source = StreamChannel.local(); + const stream = Object.assign(new ChatModelStream(source.toAsyncIterable()), { + namespace: event.params.namespace, + node: event.params.node + }); + active.set(key, { + source, + stream + }); + source.push(data); + log.push(stream); + break; + } + case "content-block-start": + case "content-block-delta": + case "content-block-finish": + if (ignored.has(getMessageStreamKey(data))) break; + active.get(getMessageStreamKey(data))?.source.push(data); + break; + case "message-finish": { + const key = getMessageStreamKey(data); + if (ignored.delete(key)) break; + const stream = active.get(key); + if (stream) { + stream.source.push(data); + stream.source.close(); + active.delete(key); + } + break; + } + case "error": + if (ignored.has(getMessageStreamKey(data))) break; + active.get(getMessageStreamKey(data))?.source.push(data); + break; + } + return true; + }, + finalize() { + for (const [key, stream] of active) { + stream.source.push({ event: "message-finish" }); + stream.source.close(); + active.delete(key); + } + ignored.clear(); + log.close(); + }, + fail(err) { + for (const [key, stream] of active) { + stream.source.fail(err); + active.delete(key); + } + ignored.clear(); + log.fail(err); + } + }; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/stream/transformers/subgraphs.js +/** +* SubgraphDiscoveryTransformer - materializes a {@link StreamHandle} for +* each newly observed top-level subgraph namespace and announces it on +* the mux's shared {@link StreamMux._discoveries} channel. +* +* Previously this work was inlined in {@link StreamMux.push}. Extracting +* it into a transformer aligns discovery with the rest of the stream +* architecture (lifecycle, values, messages are all transformers), +* isolates the factory wiring, and makes discovery behavior +* independently testable. +* +* The transformer also owns the read-side of discovery: it exposes an +* `AsyncIterable` projection (`subgraphs`) scoped to the root +* namespace, and a {@link filterSubgraphHandles} helper that callers +* can use to scope the same channel to any descendant namespace. This +* lets `GraphRunStream` drop its bespoke `subscribeSubgraphs` +* delegation and surface child streams via the standard native +* projection pattern. +* +* Only first-level namespace segments are announced. Deeper segments +* (e.g. `["researcher:uuid", "tools:uuid"]`) are internal Pregel +* checkpoint namespaces for nodes inside a subgraph and should not +* appear as user-facing `SubgraphRunStream` instances; the mux still +* resolves their values via its own `#streamMap` when registered +* elsewhere. +*/ +/** +* Filter a {@link SubgraphDiscovery} channel to only the direct children +* of a given namespace. +* +* Returns an `AsyncIterable` whose iterator yields stream handles for +* discoveries whose namespace is exactly one segment deeper than +* {@link path} and shares it as a prefix. Iteration begins at +* {@link startAt} (so each caller picks up only discoveries added +* after its construction) and terminates when the underlying log +* closes or fails. +* +* @typeParam TStream - Concrete stream type recorded in the log. +* Callers may cast if the log was populated by a specific factory. +* @param log - The shared discovery channel (`mux._discoveries`). +* @param path - Parent namespace whose direct children should be +* yielded. +* @param startAt - Zero-based index into the discovery log to begin +* from. +* @returns An async iterable of stream handles. +*/ +function filterSubgraphHandles(log, path, startAt = 0) { + const targetDepth = path.length + 1; + return { [Symbol.asyncIterator]() { + const base = log.iterate(startAt); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) return { + value: void 0, + done: true + }; + const { ns, stream } = result.value; + if (ns.length === targetDepth && hasPrefix(ns, path)) return { + value: stream, + done: false + }; + } + } }; + } }; +} +/** +* Create the subgraph discovery transformer. +* +* Registering this transformer against a mux replaces the legacy +* inline behavior that previously lived in {@link StreamMux.push}. +* The mux no longer knows about the subgraph factory: instead, this +* transformer is the single component that materializes stream +* handles and announces them on `_discoveries`. +* +* Marked as a {@link NativeStreamTransformer} so the projection is +* treated as internal wiring (not merged into `run.extensions` and +* not auto-forwarded via {@link StreamMux.wireChannels}). +* +* @typeParam TStream - Concrete stream handle type produced by +* {@link SubgraphDiscoveryTransformerOptions.createStream}. +* Defaults to the base {@link StreamHandle} interface. +* @param mux - The mux whose `_discoveries` log should receive +* discovery entries and whose `register` will be called for each +* new stream handle. +* @param options - Factory and related wiring. +* @returns A native transformer that populates +* {@link StreamMux._discoveries} and exposes a root-scoped +* `subgraphs` iterable via its projection. +*/ +function createSubgraphDiscoveryTransformer(mux, options) { + const { createStream } = options; + const seen = /* @__PURE__ */ new Set(); + return { + __native: true, + init() { + return { + _discoveries: mux._discoveries, + subgraphs: filterSubgraphHandles(mux._discoveries, [], 0) + }; + }, + process(event) { + const ns = event.params.namespace; + if (ns.length === 0) return true; + const topNs = ns.slice(0, 1); + const topKey = nsKey(topNs); + if (seen.has(topKey)) return true; + seen.add(topKey); + const stream = createStream(topNs, mux._discoveries.size, mux._events.size); + mux.register(topNs, stream); + mux._discoveries.push({ + ns: topNs, + stream + }); + return true; + } + }; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/stream/transformers/values.js +/** +* Creates a {@link StreamTransformer} that captures `values` channel events +* into a local {@link StreamChannel}. Only events whose namespace exactly +* matches {@link path} are recorded; events from child or sibling namespaces +* are ignored. +* +* The final snapshot is resolved by {@link StreamMux.close} directly; +* this transformer only accumulates intermediate values. +* +* @param path - Namespace prefix to match against incoming events. +* @returns A `StreamTransformer` whose projection contains the internal +* `_valuesLog` local channel. +*/ +function createValuesTransformer(path) { + const valuesLog = StreamChannel.local(); + return { + init: () => ({ _valuesLog: valuesLog }), + process(event) { + if (event.method !== "values") return true; + if (event.params.namespace.length !== path.length) return true; + if (!hasPrefix(event.params.namespace, path)) return true; + valuesLog.push(event.params.data); + return true; + }, + finalize() { + valuesLog.close(); + }, + fail(err) { + valuesLog.fail(err); + } + }; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/stream/types.js +/** +* Type guard that tests whether a transformer is a {@link NativeStreamTransformer}. +*/ +function isNativeTransformer(t) { + return "__native" in t && t.__native === true; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/stream/run-stream.js +/** +* Symbol key for attaching the values log to a stream handle. +* Using a symbol keeps this off the public autocomplete surface. +*/ +var SET_VALUES_LOG = Symbol("setValuesLog"); +/** +* Symbol key for attaching the messages iterable to a stream handle. +* Using a symbol keeps this off the public autocomplete surface. +*/ +var SET_MESSAGES_ITERABLE = Symbol("setMessagesIterable"); +/** +* Symbol key for attaching the lifecycle iterable to a stream handle. +* Using a symbol keeps this off the public autocomplete surface. +*/ +var SET_LIFECYCLE_ITERABLE = Symbol("setLifecycleIterable"); +/** +* Symbol key for attaching the subgraphs iterable to a stream handle. +* Using a symbol keeps this off the public autocomplete surface. +*/ +var SET_SUBGRAPHS_ITERABLE = Symbol("setSubgraphsIterable"); +/** +* Shared empty async iterable, returned from getters that haven't +* been wired by {@link createGraphRunStream}. Avoids allocating a +* fresh empty iterable on every access. +*/ +var EMPTY_ASYNC_ITERABLE = { [Symbol.asyncIterator]() { + return { next: () => Promise.resolve({ + value: void 0, + done: true + }) }; +} }; +/** +* Primary run stream for a LangGraph execution. +* +* Implements {@link AsyncIterable} over {@link ProtocolEvent} and exposes +* ergonomic projections for values, messages, subgraphs, output, and +* interrupts. Created by {@link createGraphRunStream}. +* +* @typeParam TValues - Shape of the graph's state values. +* @typeParam TExtensions - Shape of additional transformer projections merged +* into {@link GraphRunStream.extensions}. +*/ +var GraphRunStream = class { + /** + * Namespace path identifying this stream's position in the agent tree. + * An empty array for the root stream. + */ + path; + /** + * Merged projections from user-supplied {@link StreamTransformer} factories. + * Each transformer's `init()` return value is spread into this object. + */ + extensions; + /** + * The central stream multiplexer that drives event dispatch and transformer + * pipelines. Accessible to subclasses for direct event subscription. + * + * @internal + */ + _mux; + #eventStart; + #discoveryStart; + #abortController; + #resolveValuesFn; + #rejectValuesFn; + #valuesDone; + #valuesLog; + #messagesIterable; + #lifecycleIterable; + #subgraphsIterable; + /** + * @param path - Namespace path for this stream (empty array for root). + * @param mux - The {@link StreamMux} driving this run. + * @param discoveryStart - Cursor offset into the mux discovery log. + * @param eventStart - Cursor offset into the mux event log. + * @param extensions - Pre-initialized transformer projections. + * @param abortController - Controller for programmatic cancellation. + */ + constructor(path, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { + this.path = path; + this._mux = mux; + this.#discoveryStart = discoveryStart; + this.#eventStart = eventStart; + this.extensions = extensions ?? {}; + this.#abortController = abortController ?? new AbortController(); + this.#valuesDone = new Promise((resolve, reject) => { + this.#resolveValuesFn = resolve; + this.#rejectValuesFn = reject; + }); + this.#valuesDone.catch(() => {}); + } + /** + * Async iterator over all {@link ProtocolEvent}s at or below this + * stream's namespace, starting from the configured event offset. + * + * @returns An async iterator yielding protocol events in arrival order. + */ + [Symbol.asyncIterator]() { + return this._mux.subscribeEvents(this.path, this.#eventStart); + } + /** + * Async iterable of child {@link SubgraphRunStream} instances discovered + * during the run. Each yielded stream represents a direct child namespace. + * + * Backed by the shared `_discoveries` log on the mux, populated by + * {@link createSubgraphDiscoveryTransformer}. For streams created + * through {@link createGraphRunStream} the iterable is pre-wired + * (via {@link SET_SUBGRAPHS_ITERABLE}) so iteration is cheap. + * Streams constructed directly (e.g. in unit tests) fall back to + * filtering `_mux._discoveries` on demand, preserving the original + * behavior without requiring explicit wiring. + * + * @returns An async iterable of subgraph run streams. + */ + get subgraphs() { + if (this.#subgraphsIterable) return this.#subgraphsIterable; + return filterSubgraphHandles(this._mux._discoveries, this.path, this.#discoveryStart); + } + /** + * Dual-interface accessor for graph state snapshots. + * + * As an {@link AsyncIterable}, yields each intermediate state snapshot + * as it arrives. As a {@link PromiseLike}, resolves with the final + * state value when the run completes. + * + * @returns A combined async iterable and promise-like for state values. + */ + get values() { + const log = this.#valuesLog; + const done = this.#valuesDone; + const mux = this._mux; + const eventStart = this.#eventStart; + const path = this.path; + const iterable = log ? log.toAsyncIterable() : { [Symbol.asyncIterator]: () => { + const base = mux.subscribeEvents(path, eventStart); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) return { + value: void 0, + done: true + }; + if (result.value.method === "values" && result.value.params.namespace.length === path.length) return { + value: result.value.params.data, + done: false + }; + } + } }; + } }; + return { + [Symbol.asyncIterator]: () => iterable[Symbol.asyncIterator](), + then: done.then.bind(done) + }; + } + /** + * All AI message lifecycles observed at this namespace level, in order. + * Each yielded {@link ChatModelStream} represents one message-start → + * message-finish lifecycle with streaming `.text`, `.reasoning`, and + * `.usage` projections. + * + * @returns An async iterable of chat model streams. + */ + get messages() { + if (this.#messagesIterable) return this.#messagesIterable; + const transformer = createMessagesTransformer(this.path); + const projection = transformer.init(); + this._mux.addTransformer(transformer); + this.#messagesIterable = projection.messages; + return this.#messagesIterable; + } + /** + * Sequence of {@link LifecycleEntry} records tracking the + * `lifecycle` channel: when the run starts, when each subgraph + * enters/exits, and the terminal status of the run as a whole. + * + * Backed by the built-in {@link createLifecycleTransformer}; the + * root stream's iterable is wired during + * {@link createGraphRunStream} setup, and each + * {@link SubgraphRunStream} is wired in the subgraph discovery + * factory with a subtree-scoped view (via + * {@link filterLifecycleEntries}). Streams constructed outside + * `createGraphRunStream` and not wired will yield nothing. + * + * @returns An async iterable of lifecycle entries in emission order. + */ + get lifecycle() { + return this.#lifecycleIterable ?? EMPTY_ASYNC_ITERABLE; + } + /** + * Messages produced by a specific graph node. Use when the run has + * multiple model-calling nodes and you only want messages from one. + * + * @param node - The graph node name to filter messages by. + * @returns An async iterable of chat model streams from the given node. + */ + messagesFrom(node) { + const transformer = createMessagesTransformer(this.path, node); + const projection = transformer.init(); + this._mux.addTransformer(transformer); + return projection.messages; + } + /** + * Promise that resolves with the final graph state when the run completes, + * or rejects if the run fails. + * + * @returns A promise resolving to the final state values. + */ + get output() { + return this.#valuesDone; + } + /** + * Whether the run ended due to a human-in-the-loop interrupt. + * + * @returns `true` if the run was interrupted. + */ + get interrupted() { + return this._mux.interrupted; + } + /** + * Interrupt payloads collected during the run, if any. + * + * @returns A readonly array of interrupt payloads. + */ + get interrupts() { + return this._mux.interrupts; + } + /** + * Programmatically abort this run. Equivalent to calling + * `signal.abort(reason)`. + * + * @param reason - Optional abort reason passed to the signal. + */ + abort(reason) { + this.#abortController.abort(reason); + } + /** + * The {@link AbortSignal} wired into this run for cancellation support. + * + * @returns The abort signal for this stream. + */ + get signal() { + return this.#abortController.signal; + } + /** + * Resolve the output/values promise with the final state snapshot. + * Called by {@link StreamMux.close}. + * + * @param values - The final state values, or `undefined` if none. + * @internal + */ + [RESOLVE_VALUES](values) { + this.#resolveValuesFn?.(values); + this.#resolveValuesFn = void 0; + } + /** + * Reject the output/values promise with a run error. + * Called by {@link StreamMux.fail}. + * + * @param err - The error that caused the run to fail. + * @internal + */ + [REJECT_VALUES](err) { + this.#rejectValuesFn?.(err); + this.#rejectValuesFn = void 0; + } + /** + * Attach the transformer-populated event log backing the `.values` iterable. + * Called during stream setup in {@link createGraphRunStream}. + * + * @param log - The event log from the values transformer projection. + * @internal + */ + [SET_VALUES_LOG](log) { + this.#valuesLog = log; + } + /** + * Attach the transformer-populated async iterable backing the `.messages` + * accessor. Called during stream setup in {@link createGraphRunStream}. + * + * @param iterable - The async iterable from the messages transformer projection. + * @internal + */ + [SET_MESSAGES_ITERABLE](iterable) { + this.#messagesIterable = iterable; + } + /** + * Attach the transformer-populated async iterable backing the + * `.lifecycle` accessor. Called during stream setup in + * {@link createGraphRunStream}. + * + * @param iterable - The async iterable from the lifecycle transformer projection. + * @internal + */ + [SET_LIFECYCLE_ITERABLE](iterable) { + this.#lifecycleIterable = iterable; + } + /** + * Attach the transformer-populated async iterable backing the + * `.subgraphs` accessor. Called during root stream setup in + * {@link createGraphRunStream} and during child stream + * construction in the discovery transformer factory. + * + * @param iterable - The async iterable of direct-child stream handles. + * @internal + */ + [SET_SUBGRAPHS_ITERABLE](iterable) { + this.#subgraphsIterable = iterable; + } +}; +/** +* A run stream for a child subgraph within a parent graph execution. +* +* Extends {@link GraphRunStream} with a parsed {@link name} and +* {@link index} extracted from the last segment of the namespace path. +* The segment is expected to follow the `"name:index"` convention; +* when no numeric suffix is present, {@link index} defaults to `0`. +* +* @typeParam TValues - Shape of the subgraph's state values. +* @typeParam TExtensions - Shape of additional transformer projections. +*/ +var SubgraphRunStream = class extends GraphRunStream { + /** + * The node name extracted from the last segment of the namespace path + * (everything before the final colon, or the full segment if no colon). + */ + name; + /** + * The invocation index parsed from the `"name:N"` suffix of the last + * namespace segment. Defaults to `0` when no numeric suffix is present. + */ + index; + /** + * @param path - Namespace path for this subgraph stream. + * @param mux - The {@link StreamMux} driving this run. + * @param discoveryStart - Cursor offset into the mux discovery log. + * @param eventStart - Cursor offset into the mux event log. + * @param extensions - Pre-initialized transformer projections. + * @param abortController - Controller for programmatic cancellation. + */ + constructor(path, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { + super(path, mux, discoveryStart, eventStart, extensions, abortController); + const lastSegment = path[path.length - 1] ?? ""; + const colonIdx = lastSegment.lastIndexOf(":"); + if (colonIdx >= 0) { + this.name = lastSegment.slice(0, colonIdx); + const suffix = lastSegment.slice(colonIdx + 1); + this.index = /^\d+$/.test(suffix) ? Number(suffix) : 0; + } else { + this.name = lastSegment; + this.index = 0; + } + } +}; +/** +* Creates a {@link GraphRunStream} with built-in transformers and kicks off the +* background pump that feeds raw stream chunks through the transformer pipeline. +* +* Built-in transformers are registered in this order: +* 1. subgraph discovery — materializes SubgraphRunStream handles +* for each newly observed top-level namespace and announces them +* on the mux `_discoveries` log. +* 2. lifecycle — synthesizes `lifecycle` channel events. +* 3. values — powers `run.values` / `run.output`. +* 4. messages — powers `run.messages` / `.messagesFrom`. +* +* Subgraph discovery is registered first so that downstream +* transformers (notably lifecycle) observe child namespaces with +* their stream handles already in place. User-supplied transformer +* factories are registered afterwards. +* +* @typeParam TValues - Shape of the graph's state values. +* @param source - Raw async iterable from `graph.stream(…, { subgraphs: true })`. +* @param transformers - User-supplied transformer factories. +* @param optionsOrAbortController - Either a full +* {@link CreateGraphRunStreamOptions} object or (for backward +* compatibility) a bare `AbortController`. +* @returns A {@link GraphRunStream} for the root namespace. +*/ +function createGraphRunStream(source, transformers = [], optionsOrAbortController) { + const { abortController } = optionsOrAbortController instanceof AbortController ? { abortController: optionsOrAbortController } : optionsOrAbortController ?? {}; + const mux = new StreamMux(); + const lifecycleTransformer = createLifecycleTransformer(); + const lifecycleProjection = lifecycleTransformer.init(); + const lifecycleLog = lifecycleProjection._lifecycleLog; + const subgraphDiscoveryTransformer = createSubgraphDiscoveryTransformer(mux, { createStream: (path, discoveryStart, eventStart) => { + const sub = new SubgraphRunStream(path, mux, discoveryStart, eventStart); + sub[SET_SUBGRAPHS_ITERABLE](filterSubgraphHandles(mux._discoveries, path, discoveryStart)); + sub[SET_LIFECYCLE_ITERABLE](filterLifecycleEntries(lifecycleLog, path, lifecycleLog.size)); + return sub; + } }); + const subgraphsProjection = subgraphDiscoveryTransformer.init(); + mux.addTransformer(subgraphDiscoveryTransformer); + mux.addTransformer(lifecycleTransformer); + const valuesTransformer = createValuesTransformer([]); + const messagesTransformer = createMessagesTransformer([]); + mux.addTransformer(valuesTransformer); + mux.addTransformer(messagesTransformer); + const extensions = {}; + const nativeProjections = []; + for (const factory of transformers) { + const transformer = factory(); + mux.addTransformer(transformer); + const projection = transformer.init(); + if (isNativeTransformer(transformer)) nativeProjections.push(projection); + else Object.assign(extensions, projection); + if (typeof projection === "object" && projection !== null && !isNativeTransformer(transformer)) mux.wireChannels(projection); + } + const root = new GraphRunStream([], mux, 0, 0, extensions, abortController); + /** + * Assign native transformer projections to the root stream. + */ + for (const proj of nativeProjections) Object.assign(root, proj); + const valuesProjection = valuesTransformer.init(); + root[SET_VALUES_LOG](valuesProjection._valuesLog); + const messagesProjection = messagesTransformer.init(); + root[SET_MESSAGES_ITERABLE](messagesProjection.messages); + root[SET_LIFECYCLE_ITERABLE](lifecycleProjection.lifecycle); + root[SET_SUBGRAPHS_ITERABLE](subgraphsProjection.subgraphs); + mux.register([], root); + pump(source, mux).catch((err) => {}); + return root; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/hash.js +var n = (n) => BigInt(n); +var view = (data, offset = 0) => new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset); +var PRIME32_1 = n("0x9E3779B1"); +var PRIME32_2 = n("0x85EBCA77"); +var PRIME32_3 = n("0xC2B2AE3D"); +var PRIME64_1 = n("0x9E3779B185EBCA87"); +var PRIME64_2 = n("0xC2B2AE3D27D4EB4F"); +var PRIME64_3 = n("0x165667B19E3779F9"); +var PRIME64_4 = n("0x85EBCA77C2B2AE63"); +var PRIME64_5 = n("0x27D4EB2F165667C5"); +var PRIME_MX1 = n("0x165667919E3779F9"); +var PRIME_MX2 = n("0x9FB21C651E98DF25"); +var hexToUint8Array = (hex) => { + const strLen = hex.length; + if (strLen % 2 !== 0) throw new Error("String should have an even number of characters"); + const maxLength = strLen / 2; + const bytes = new Uint8Array(maxLength); + let read = 0; + let write = 0; + while (write < maxLength) { + const slice = hex.slice(read, read += 2); + bytes[write] = Number.parseInt(slice, 16); + write += 1; + } + return view(bytes); +}; +var kkey = hexToUint8Array("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"); +var mask128 = (n(1) << n(128)) - n(1); +var mask64 = (n(1) << n(64)) - n(1); +var mask32 = (n(1) << n(32)) - n(1); +var STRIPE_LEN = 64; +var ACC_NB = STRIPE_LEN / 8; +var _U64 = 8; +var _U32 = 4; +function assert(a) { + if (!a) throw new Error("Assert failed"); +} +function bswap64(a) { + const scratchbuf = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)); + scratchbuf.setBigUint64(0, a, true); + return scratchbuf.getBigUint64(0, false); +} +function bswap32(input) { + let a = input; + a = (a & n(65535)) << n(16) | (a & n(4294901760)) >> n(16); + a = (a & n(16711935)) << n(8) | (a & n(4278255360)) >> n(8); + return a; +} +function XXH_mult32to64(a, b) { + return (a & mask32) * (b & mask32) & mask64; +} +function rotl32(a, b) { + return (a << b | a >> n(32) - b) & mask32; +} +function XXH3_accumulate_512(acc, dataView, keyView) { + for (let i = 0; i < ACC_NB; i += 1) { + const data_val = dataView.getBigUint64(i * 8, true); + const data_key = data_val ^ keyView.getBigUint64(i * 8, true); + acc[i ^ 1] += data_val; + acc[i] += XXH_mult32to64(data_key, data_key >> n(32)); + } + return acc; +} +function XXH3_accumulate(acc, dataView, keyView, nbStripes) { + for (let n = 0; n < nbStripes; n += 1) XXH3_accumulate_512(acc, view(dataView, n * STRIPE_LEN), view(keyView, n * 8)); + return acc; +} +function XXH3_scrambleAcc(acc, key) { + for (let i = 0; i < ACC_NB; i += 1) { + const key64 = key.getBigUint64(i * 8, true); + let acc64 = acc[i]; + acc64 = xorshift64(acc64, n(47)); + acc64 ^= key64; + acc64 *= PRIME32_1; + acc[i] = acc64 & mask64; + } + return acc; +} +function XXH3_mix2Accs(acc, key) { + return XXH3_mul128_fold64(acc[0] ^ key.getBigUint64(0, true), acc[1] ^ key.getBigUint64(_U64, true)); +} +function XXH3_mergeAccs(acc, key, start) { + let result64 = start; + result64 += XXH3_mix2Accs(acc.slice(0), view(key, 0 * _U32)); + result64 += XXH3_mix2Accs(acc.slice(2), view(key, 4 * _U32)); + result64 += XXH3_mix2Accs(acc.slice(4), view(key, 8 * _U32)); + result64 += XXH3_mix2Accs(acc.slice(6), view(key, 12 * _U32)); + return XXH3_avalanche(result64 & mask64); +} +function XXH3_hashLong(input, data, secret, f_acc, f_scramble) { + let acc = input; + const nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN) / 8); + const block_len = STRIPE_LEN * nbStripesPerBlock; + const nb_blocks = Math.floor((data.byteLength - 1) / block_len); + for (let n = 0; n < nb_blocks; n += 1) { + acc = XXH3_accumulate(acc, view(data, n * block_len), secret, nbStripesPerBlock); + acc = f_scramble(acc, view(secret, secret.byteLength - STRIPE_LEN)); + } + { + const nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN); + acc = XXH3_accumulate(acc, view(data, nb_blocks * block_len), secret, nbStripes); + acc = f_acc(acc, view(data, data.byteLength - STRIPE_LEN), view(secret, secret.byteLength - STRIPE_LEN - 7)); + } + return acc; +} +function XXH3_hashLong_128b(data, secret) { + let acc = new BigUint64Array([ + PRIME32_3, + PRIME64_1, + PRIME64_2, + PRIME64_3, + PRIME64_4, + PRIME32_2, + PRIME64_5, + PRIME32_1 + ]); + assert(data.byteLength > 128); + acc = XXH3_hashLong(acc, data, secret, XXH3_accumulate_512, XXH3_scrambleAcc); + assert(acc.length * 8 === 64); + { + const low64 = XXH3_mergeAccs(acc, view(secret, 11), n(data.byteLength) * PRIME64_1 & mask64); + return XXH3_mergeAccs(acc, view(secret, secret.byteLength - STRIPE_LEN - 11), ~(n(data.byteLength) * PRIME64_2) & mask64) << n(64) | low64; + } +} +function XXH3_mul128_fold64(a, b) { + const lll = a * b & mask128; + return lll & mask64 ^ lll >> n(64); +} +function XXH3_mix16B(dataView, keyView, seed) { + return XXH3_mul128_fold64((dataView.getBigUint64(0, true) ^ keyView.getBigUint64(0, true) + seed) & mask64, (dataView.getBigUint64(8, true) ^ keyView.getBigUint64(8, true) - seed) & mask64); +} +function XXH3_mix32B(acc, data1, data2, key, seed) { + let accl = acc & mask64; + let acch = acc >> n(64) & mask64; + accl += XXH3_mix16B(data1, key, seed); + accl ^= data2.getBigUint64(0, true) + data2.getBigUint64(8, true); + accl &= mask64; + acch += XXH3_mix16B(data2, view(key, 16), seed); + acch ^= data1.getBigUint64(0, true) + data1.getBigUint64(8, true); + acch &= mask64; + return acch << n(64) | accl; +} +function XXH3_avalanche(input) { + let h64 = input; + h64 ^= h64 >> n(37); + h64 *= PRIME_MX1; + h64 &= mask64; + h64 ^= h64 >> n(32); + return h64; +} +function XXH3_avalanche64(input) { + let h64 = input; + h64 ^= h64 >> n(33); + h64 *= PRIME64_2; + h64 &= mask64; + h64 ^= h64 >> n(29); + h64 *= PRIME64_3; + h64 &= mask64; + h64 ^= h64 >> n(32); + return h64; +} +function XXH3_len_1to3_128b(data, key32, seed) { + const len = data.byteLength; + assert(len > 0 && len <= 3); + const combined = n(data.getUint8(len - 1)) | n(len << 8) | n(data.getUint8(0) << 16) | n(data.getUint8(len >> 1) << 24); + const low = (combined ^ (n(key32.getUint32(0, true)) ^ n(key32.getUint32(4, true))) + seed) & mask64; + const bhigh = (n(key32.getUint32(8, true)) ^ n(key32.getUint32(12, true))) - seed; + return (XXH3_avalanche64((rotl32(bswap32(combined), n(13)) ^ bhigh) & mask64) & mask64) << n(64) | XXH3_avalanche64(low); +} +function xorshift64(b, shift) { + return b ^ b >> shift; +} +function XXH3_len_4to8_128b(data, key32, seed) { + const len = data.byteLength; + assert(len >= 4 && len <= 8); + { + const l1 = data.getUint32(0, true); + const l2 = data.getUint32(len - 4, true); + let m128 = ((n(l1) | n(l2) << n(32)) ^ (key32.getBigUint64(16, true) ^ key32.getBigUint64(24, true)) + seed & mask64) * (PRIME64_1 + (n(len) << n(2))) & mask128; + m128 += (m128 & mask64) << n(65); + m128 &= mask128; + m128 ^= m128 >> n(67); + return xorshift64(xorshift64(m128 & mask64, n(35)) * PRIME_MX2 & mask64, n(28)) | XXH3_avalanche(m128 >> n(64)) << n(64); + } +} +function XXH3_len_9to16_128b(data, key64, seed) { + const len = data.byteLength; + assert(len >= 9 && len <= 16); + { + const bitflipl = (key64.getBigUint64(32, true) ^ key64.getBigUint64(40, true)) + seed & mask64; + const bitfliph = (key64.getBigUint64(48, true) ^ key64.getBigUint64(56, true)) - seed & mask64; + const ll1 = data.getBigUint64(0, true); + let ll2 = data.getBigUint64(len - 8, true); + let m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_1; + const m128_l = (m128 & mask64) + (n(len - 1) << n(54)); + m128 = m128 & (mask128 ^ mask64) | m128_l; + ll2 ^= bitfliph; + m128 += ll2 + (ll2 & mask32) * (PRIME32_2 - n(1)) << n(64); + m128 &= mask128; + m128 ^= bswap64(m128 >> n(64)); + let h128 = (m128 & mask64) * PRIME64_2; + h128 += (m128 >> n(64)) * PRIME64_2 << n(64); + h128 &= mask128; + return XXH3_avalanche(h128 & mask64) | XXH3_avalanche(h128 >> n(64)) << n(64); + } +} +function XXH3_len_0to16_128b(data, seed) { + const len = data.byteLength; + assert(len <= 16); + if (len > 8) return XXH3_len_9to16_128b(data, kkey, seed); + if (len >= 4) return XXH3_len_4to8_128b(data, kkey, seed); + if (len > 0) return XXH3_len_1to3_128b(data, kkey, seed); + return XXH3_avalanche64(seed ^ kkey.getBigUint64(64, true) ^ kkey.getBigUint64(72, true)) | XXH3_avalanche64(seed ^ kkey.getBigUint64(80, true) ^ kkey.getBigUint64(88, true)) << n(64); +} +function inv64(x) { + return ~x + n(1) & mask64; +} +function XXH3_len_17to128_128b(data, secret, seed) { + let acc = n(data.byteLength) * PRIME64_1 & mask64; + let i = n(data.byteLength - 1) / n(32); + while (i >= 0) { + const ni = Number(i); + acc = XXH3_mix32B(acc, view(data, 16 * ni), view(data, data.byteLength - 16 * (ni + 1)), view(secret, 32 * ni), seed); + i -= n(1); + } + let h128l = acc + (acc >> n(64)) & mask64; + h128l = XXH3_avalanche(h128l); + let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; + h128h &= mask64; + h128h = inv64(XXH3_avalanche(h128h)); + return h128l | h128h << n(64); +} +function XXH3_len_129to240_128b(data, secret, seed) { + let acc = n(data.byteLength) * PRIME64_1 & mask64; + for (let i = 32; i < 160; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, i - 32), seed); + acc = XXH3_avalanche(acc & mask64) | XXH3_avalanche(acc >> n(64)) << n(64); + for (let i = 160; i <= data.byteLength; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, 3 + i - 160), seed); + acc = XXH3_mix32B(acc, view(data, data.byteLength - 16), view(data, data.byteLength - 32), view(secret, 103), inv64(seed)); + let h128l = acc + (acc >> n(64)) & mask64; + h128l = XXH3_avalanche(h128l); + let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; + h128h &= mask64; + h128h = inv64(XXH3_avalanche(h128h)); + return h128l | h128h << n(64); +} +function XXH3(input, seed = n(0)) { + const encoder = new TextEncoder(); + const data = view(typeof input === "string" ? encoder.encode(input) : input); + const len = data.byteLength; + const hexDigest = (data) => data.toString(16).padStart(32, "0"); + if (len <= 16) return hexDigest(XXH3_len_0to16_128b(data, seed)); + if (len <= 128) return hexDigest(XXH3_len_17to128_128b(data, kkey, seed)); + if (len <= 240) return hexDigest(XXH3_len_129to240_128b(data, kkey, seed)); + return hexDigest(XXH3_hashLong_128b(data, kkey)); +} +function isXXH3(value) { + return /^[0-9a-f]{32}$/.test(value); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/interrupt.js +/** +* Interrupts the execution of a graph node. +* This function can be used to pause execution of a node, and return the value of the `resume` +* input when the graph is re-invoked using `Command`. +* Multiple interrupts can be called within a single node, and each will be handled sequentially. +* +* When an interrupt is called: +* 1. If there's a `resume` value available (from a previous `Command`), it returns that value. +* 2. Otherwise, it throws a `GraphInterrupt` with the provided value +* 3. The graph can be resumed by passing a `Command` with a `resume` value +* +* Because the `interrupt` function propagates by throwing a special `GraphInterrupt` error, +* you should avoid using `try/catch` blocks around the `interrupt` function, +* or if you do, ensure that the `GraphInterrupt` error is thrown again within your `catch` block. +* +* @param value - The value to include in the interrupt. This will be available in task.interrupts[].value +* @returns The `resume` value provided when the graph is re-invoked with a Command +* +* @example +* ```typescript +* // Define a node that uses multiple interrupts +* const nodeWithInterrupts = () => { +* // First interrupt - will pause execution and include {value: 1} in task values +* const answer1 = interrupt({ value: 1 }); +* +* // Second interrupt - only called after first interrupt is resumed +* const answer2 = interrupt({ value: 2 }); +* +* // Use the resume values +* return { myKey: answer1 + " " + answer2 }; +* }; +* +* // Resume the graph after first interrupt +* await graph.stream(new Command({ resume: "answer 1" })); +* +* // Resume the graph after second interrupt +* await graph.stream(new Command({ resume: "answer 2" })); +* // Final result: { myKey: "answer 1 answer 2" } +* ``` +* +* @throws {Error} If called outside the context of a graph +* @throws {GraphInterrupt} When no resume value is available +*/ +function interrupt(value) { + const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (!config) throw new Error("Called interrupt() outside the context of a graph."); + const conf = config.configurable; + if (!conf) throw new Error("No configurable found in config"); + if (!conf["__pregel_checkpointer"]) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const scratchpad = conf[CONFIG_KEY_SCRATCHPAD]; + scratchpad.interruptCounter += 1; + const idx = scratchpad.interruptCounter; + if (scratchpad.resume.length > 0 && idx < scratchpad.resume.length) { + conf[CONFIG_KEY_SEND]?.([[RESUME$1, scratchpad.resume]]); + return scratchpad.resume[idx]; + } + if (scratchpad.nullResume !== void 0) { + if (scratchpad.resume.length !== idx) throw new Error(`Resume length mismatch: ${scratchpad.resume.length} !== ${idx}`); + const v = scratchpad.consumeNullResume(); + scratchpad.resume.push(v); + conf[CONFIG_KEY_SEND]?.([[RESUME$1, scratchpad.resume]]); + return v; + } + const ns = conf[CONFIG_KEY_CHECKPOINT_NS]?.split("|"); + throw new GraphInterrupt([{ + id: ns ? XXH3(ns.join("|")) : void 0, + value + }]); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/utils.js +var RunnableCallable = class extends Runnable { + lc_namespace = ["langgraph"]; + func; + tags; + config; + trace = true; + recurse = true; + constructor(fields) { + super(); + this.name = fields.name ?? fields.func.name; + this.func = fields.func; + this.config = fields.tags ? { tags: fields.tags } : void 0; + this.trace = fields.trace ?? this.trace; + this.recurse = fields.recurse ?? this.recurse; + } + async _tracedInvoke(input, config, runManager) { + return new Promise((resolve, reject) => { + const childConfig = patchConfig(config, { callbacks: runManager?.getChild() }); + AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { + try { + resolve(await this.func(input, childConfig)); + } catch (e) { + reject(e); + } + }); + }); + } + async invoke(input, options) { + let returnValue; + const config = ensureLangGraphConfig(options); + const mergedConfig = mergeConfigs(this.config, config); + if (this.trace) returnValue = await this._callWithConfig(this._tracedInvoke, input, mergedConfig); + else returnValue = await AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); + if (Runnable.isRunnable(returnValue) && this.recurse) return await AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); + return returnValue; + } +}; +function* prefixGenerator(generator, prefix) { + if (prefix === void 0) yield* generator; + else for (const value of generator) yield [prefix, value]; +} +async function gatherIterator(i) { + const out = []; + for await (const item of await i) out.push(item); + return out; +} +function gatherIteratorSync(i) { + const out = []; + for (const item of i) out.push(item); + return out; +} +function patchConfigurable$1(config, patch) { + if (!config) return { configurable: patch }; + else if (!("configurable" in config)) return { + ...config, + configurable: patch + }; + else return { + ...config, + configurable: { + ...config.configurable, + ...patch + } + }; +} +function isAsyncGeneratorFunction(val) { + return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(async function* () {}).constructor; +} +function isGeneratorFunction(val) { + return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(function* () {}).constructor; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/write.js +function _isSkipWrite(x) { + return typeof x === "object" && x?.[Symbol.for("LG_SKIP_WRITE")] !== void 0; +} +var PASSTHROUGH = { [Symbol.for("LG_PASSTHROUGH")]: true }; +function _isPassthrough(x) { + return typeof x === "object" && x?.[Symbol.for("LG_PASSTHROUGH")] !== void 0; +} +var IS_WRITER = Symbol("IS_WRITER"); +/** +* Mapping of write channels to Runnables that return the value to be written, +* or None to skip writing. +*/ +var ChannelWrite = class ChannelWrite extends RunnableCallable { + writes; + constructor(writes, tags) { + const name = `ChannelWrite<${writes.map((packet) => { + if (_isSend(packet)) return packet.node; + else if ("channel" in packet) return packet.channel; + return "..."; + }).join(",")}>`; + super({ + writes, + name, + tags, + trace: false, + func: async (input, config) => { + return this._write(input, config ?? {}); + } + }); + this.writes = writes; + } + async _write(input, config) { + const writes = this.writes.map((write) => { + if (_isChannelWriteTupleEntry(write) && _isPassthrough(write.value)) return { + mapper: write.mapper, + value: input + }; + else if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) return { + channel: write.channel, + value: input, + skipNone: write.skipNone, + mapper: write.mapper + }; + else return write; + }); + await ChannelWrite.doWrite(config, writes); + return input; + } + static async doWrite(config, writes) { + for (const w of writes) { + if (_isChannelWriteEntry(w)) { + if (w.channel === "__pregel_tasks") throw new InvalidUpdateError("Cannot write to the reserved channel TASKS"); + if (_isPassthrough(w.value)) throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); + } + if (_isChannelWriteTupleEntry(w)) { + if (_isPassthrough(w.value)) throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); + } + } + const writeEntries = []; + for (const w of writes) if (_isSend(w)) writeEntries.push([TASKS, w]); + else if (_isChannelWriteTupleEntry(w)) { + const mappedResult = await w.mapper.invoke(w.value, config); + if (mappedResult != null && mappedResult.length > 0) writeEntries.push(...mappedResult); + } else if (_isChannelWriteEntry(w)) { + const mappedValue = w.mapper !== void 0 ? await w.mapper.invoke(w.value, config) : w.value; + if (_isSkipWrite(mappedValue)) continue; + if (w.skipNone && mappedValue === void 0) continue; + writeEntries.push([w.channel, mappedValue]); + } else throw new Error(`Invalid write entry: ${JSON.stringify(w)}`); + const write = config.configurable?.[CONFIG_KEY_SEND]; + write(writeEntries); + } + static isWriter(runnable) { + return runnable instanceof ChannelWrite || IS_WRITER in runnable && !!runnable[IS_WRITER]; + } + static registerWriter(runnable) { + return Object.defineProperty(runnable, IS_WRITER, { value: true }); + } +}; +function _isChannelWriteEntry(x) { + return x !== void 0 && typeof x.channel === "string"; +} +function _isChannelWriteTupleEntry(x) { + return x !== void 0 && !_isChannelWriteEntry(x) && Runnable.isRunnable(x.mapper); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/read.js +var ChannelRead = class ChannelRead extends RunnableCallable { + lc_graph_name = "ChannelRead"; + channel; + fresh = false; + mapper; + constructor(channel, mapper, fresh = false) { + super({ + trace: false, + func: (_, config) => ChannelRead.doRead(config, this.channel, this.fresh, this.mapper) + }); + this.fresh = fresh; + this.mapper = mapper; + this.channel = channel; + this.name = Array.isArray(channel) ? `ChannelRead<${channel.join(",")}>` : `ChannelRead<${channel}>`; + } + static doRead(config, channel, fresh, mapper) { + const read = config.configurable?.[CONFIG_KEY_READ]; + if (!read) throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process"); + if (mapper) return mapper(read(channel, fresh)); + else return read(channel, fresh); + } +}; +var defaultRunnableBound = /* @__PURE__ */ new RunnablePassthrough(); +var PregelNode = class PregelNode extends RunnableBinding { + lc_graph_name = "PregelNode"; + channels; + triggers = []; + mapper; + writers = []; + bound = defaultRunnableBound; + kwargs = {}; + metadata = {}; + tags = []; + retryPolicy; + cachePolicy; + timeout; + subgraphs; + ends; + isErrorHandler; + errorHandlerNode; + constructor(fields) { + const { channels, triggers, mapper, writers, bound, kwargs, metadata, retryPolicy, cachePolicy, timeout, tags, subgraphs, ends, isErrorHandler, errorHandlerNode } = fields; + const mergedTags = [...fields.config?.tags ? fields.config.tags : [], ...tags ?? []]; + super({ + ...fields, + bound: fields.bound ?? defaultRunnableBound, + config: { + ...fields.config ? fields.config : {}, + tags: mergedTags + } + }); + this.channels = channels; + this.triggers = triggers; + this.mapper = mapper; + this.writers = writers ?? this.writers; + this.bound = bound ?? this.bound; + this.kwargs = kwargs ?? this.kwargs; + this.metadata = metadata ?? this.metadata; + this.tags = mergedTags; + this.retryPolicy = retryPolicy; + this.cachePolicy = cachePolicy; + this.timeout = timeout; + this.subgraphs = subgraphs; + this.ends = ends; + this.isErrorHandler = isErrorHandler; + this.errorHandlerNode = errorHandlerNode; + } + getWriters() { + const newWriters = [...this.writers]; + while (newWriters.length > 1 && newWriters[newWriters.length - 1] instanceof ChannelWrite && newWriters[newWriters.length - 2] instanceof ChannelWrite) { + const endWriters = newWriters.slice(-2); + const combinedWrites = endWriters[0].writes.concat(endWriters[1].writes); + newWriters[newWriters.length - 2] = new ChannelWrite(combinedWrites, endWriters[0].config?.tags); + newWriters.pop(); + } + return newWriters; + } + getNode() { + const writers = this.getWriters(); + if (this.bound === defaultRunnableBound && writers.length === 0) return; + else if (this.bound === defaultRunnableBound && writers.length === 1) return writers[0]; + else if (this.bound === defaultRunnableBound) return new RunnableSequence({ + first: writers[0], + middle: writers.slice(1, writers.length - 1), + last: writers[writers.length - 1], + omitSequenceTags: true + }); + else if (writers.length > 0) return new RunnableSequence({ + first: this.bound, + middle: writers.slice(0, writers.length - 1), + last: writers[writers.length - 1], + omitSequenceTags: true + }); + else return this.bound; + } + join(channels) { + if (!Array.isArray(channels)) throw new Error("channels must be a list"); + if (typeof this.channels !== "object") throw new Error("all channels must be named when using .join()"); + return new PregelNode({ + channels: { + ...this.channels, + ...Object.fromEntries(channels.map((chan) => [chan, chan])) + }, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy, + timeout: this.timeout + }); + } + pipe(coerceable) { + if (ChannelWrite.isWriter(coerceable)) return new PregelNode({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: [...this.writers, coerceable], + bound: this.bound, + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy, + timeout: this.timeout + }); + else if (this.bound === defaultRunnableBound) return new PregelNode({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: _coerceToRunnable(coerceable), + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy, + timeout: this.timeout + }); + else return new PregelNode({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: this.bound.pipe(coerceable), + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy, + timeout: this.timeout + }); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/utils/subgraph.js +function isRunnableSequence(x) { + return "steps" in x && Array.isArray(x.steps); +} +function isPregelLike(x) { + return "lg_is_pregel" in x && x.lg_is_pregel === true; +} +function findSubgraphPregel(candidate) { + const candidates = [candidate]; + for (const candidate of candidates) if (isPregelLike(candidate)) return candidate; + else if (isRunnableSequence(candidate)) candidates.push(...candidate.steps); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/io.js +function readChannel(channels, chan, catchErrors = true, returnException = false) { + try { + return channels[chan].get(); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) { + if (returnException) return e; + else if (catchErrors) return null; + } + throw e; + } +} +function readChannels(channels, select, skipEmpty = true) { + if (Array.isArray(select)) { + const values = {}; + for (const k of select) try { + values[k] = readChannel(channels, k, !skipEmpty); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) continue; + } + return values; + } else return readChannel(channels, select); +} +/** +* Map input chunk to a sequence of pending writes in the form (channel, value). +*/ +function* mapCommand(cmd, pendingWrites) { + if (cmd.graph === Command.PARENT) throw new InvalidUpdateError("There is no parent graph."); + if (cmd.goto) { + let sends; + if (Array.isArray(cmd.goto)) sends = cmd.goto; + else sends = [cmd.goto]; + for (const send of sends) if (_isSend(send)) yield [ + NULL_TASK_ID, + TASKS, + send + ]; + else if (typeof send === "string") yield [ + NULL_TASK_ID, + `branch:to:${send}`, + "__start__" + ]; + else throw new Error(`In Command.send, expected Send or string, got ${typeof send}`); + } + if (cmd.resume) if (typeof cmd.resume === "object" && Object.keys(cmd.resume).length && Object.keys(cmd.resume).every(isXXH3)) for (const [tid, resume] of Object.entries(cmd.resume)) { + const existing = pendingWrites.filter((w) => w[0] === tid && w[1] === "__resume__").map((w) => w[2]).slice(0, 1) ?? []; + existing.push(resume); + yield [ + tid, + RESUME$1, + existing + ]; + } + else yield [ + NULL_TASK_ID, + RESUME$1, + cmd.resume + ]; + if (cmd.update) { + if (typeof cmd.update !== "object" || !cmd.update) throw new Error("Expected cmd.update to be a dict mapping channel names to update values"); + if (Array.isArray(cmd.update)) for (const [k, v] of cmd.update) yield [ + NULL_TASK_ID, + k, + v + ]; + else for (const [k, v] of Object.entries(cmd.update)) yield [ + NULL_TASK_ID, + k, + v + ]; + } +} +/** +* Map input chunk to a sequence of pending writes in the form [channel, value]. +*/ +function* mapInput(inputChannels, chunk) { + if (chunk !== void 0 && chunk !== null) if (Array.isArray(inputChannels) && typeof chunk === "object" && !Array.isArray(chunk)) { + for (const k in chunk) if (inputChannels.includes(k)) yield [k, chunk[k]]; + } else if (Array.isArray(inputChannels)) throw new Error(`Input chunk must be an object when "inputChannels" is an array`); + else yield [inputChannels, chunk]; +} +/** +* Map pending writes (a sequence of tuples (channel, value)) to output chunk. +*/ +function* mapOutputValues(outputChannels, pendingWrites, channels) { + if (Array.isArray(outputChannels)) { + if (pendingWrites === true || pendingWrites.find(([chan, _]) => outputChannels.includes(chan))) yield readChannels(channels, outputChannels); + } else if (pendingWrites === true || pendingWrites.some(([chan, _]) => chan === outputChannels)) yield readChannel(channels, outputChannels); +} +/** +* Map pending writes (a sequence of tuples (channel, value)) to output chunk. +* @internal +* +* @param outputChannels - The channels to output. +* @param tasks - The tasks to output. +* @param cached - Whether the output is cached. +* +* @returns A generator that yields the output chunk (if any). +*/ +function* mapOutputUpdates(outputChannels, tasks, cached) { + const outputTasks = tasks.filter(([task, ww]) => { + return (task.config === void 0 || !task.config.tags?.includes("langsmith:hidden")) && ww[0][0] !== "__error__" && ww[0][0] !== "__interrupt__"; + }); + if (!outputTasks.length) return; + let updated; + if (outputTasks.some(([task]) => task.writes.some(([chan, _]) => chan === "__return__"))) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === RETURN).map(([_, value]) => [task.name, value])); + else if (!Array.isArray(outputChannels)) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === outputChannels).map(([_, value]) => [task.name, value])); + else updated = outputTasks.flatMap(([task]) => { + const { writes } = task; + const counts = {}; + for (const [chan] of writes) if (outputChannels.includes(chan)) counts[chan] = (counts[chan] || 0) + 1; + if (Object.values(counts).some((count) => count > 1)) return writes.filter(([chan]) => outputChannels.includes(chan)).map(([chan, value]) => [task.name, { [chan]: value }]); + else return [[task.name, Object.fromEntries(writes.filter(([chan]) => outputChannels.includes(chan)))]]; + }); + const grouped = {}; + for (const [node, value] of updated) { + if (!(node in grouped)) grouped[node] = []; + grouped[node].push(value); + } + const flattened = {}; + for (const node in grouped) if (grouped[node].length === 1) { + const [write] = grouped[node]; + flattened[node] = write; + } else flattened[node] = grouped[node]; + if (cached) flattened["__metadata__"] = { cached }; + yield flattened; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/utils/index.js +function getNullChannelVersion(currentVersions) { + const startVersion = typeof currentVersions[START]; + if (startVersion === "number") return 0; + if (startVersion === "string") return ""; + for (const key in currentVersions) { + if (!Object.prototype.hasOwnProperty.call(currentVersions, key)) continue; + const versionType = typeof currentVersions[key]; + if (versionType === "number") return 0; + if (versionType === "string") return ""; + break; + } +} +function getNewChannelVersions(previousVersions, currentVersions) { + if (Object.keys(previousVersions).length > 0) { + const nullVersion = getNullChannelVersion(currentVersions); + return Object.fromEntries(Object.entries(currentVersions).filter(([k, v]) => v > (previousVersions[k] ?? nullVersion))); + } else return currentVersions; +} +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; +} +function patchConfigurable(config, patch) { + if (config === null) return { configurable: patch }; + else if (config?.configurable === void 0) return { + ...config, + configurable: patch + }; + else return { + ...config, + configurable: { + ...config.configurable, + ...patch + } + }; +} +function patchCheckpointMap(config, metadata) { + const parents = metadata?.parents ?? {}; + if (Object.keys(parents).length > 0) return patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_MAP]: { + ...parents, + [config.configurable?.checkpoint_ns ?? ""]: config.configurable?.checkpoint_id + } }); + else return config; +} +/** +* Combine multiple abort signals into a single abort signal. +* @param signals - The abort signals to combine. +* @returns A combined abort signal and a dispose function to remove the abort listener if unused. +*/ +function combineAbortSignals(...x) { + const signals = [...new Set(x.filter(Boolean))]; + if (signals.length === 0) return { + signal: void 0, + dispose: void 0 + }; + if (signals.length === 1) return { + signal: signals[0], + dispose: void 0 + }; + const combinedController = new AbortController(); + const listener = () => { + const reason = signals.find((s) => s.aborted)?.reason; + combinedController.abort(reason); + signals.forEach((s) => s.removeEventListener("abort", listener)); + }; + signals.forEach((s) => s.addEventListener("abort", listener, { once: true })); + const hasAlreadyAbortedSignal = signals.find((s) => s.aborted); + if (hasAlreadyAbortedSignal) combinedController.abort(hasAlreadyAbortedSignal.reason); + return { + signal: combinedController.signal, + dispose: () => { + signals.forEach((s) => s.removeEventListener("abort", listener)); + } + }; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/types.js +var Call = class { + func; + name; + input; + retry; + cache; + timeout; + callbacks; + __lg_type = "call"; + constructor({ func, name, input, retry, cache, timeout, callbacks }) { + this.func = func; + this.name = name; + this.input = input; + this.retry = retry; + this.cache = cache; + this.timeout = timeout; + this.callbacks = callbacks; + } +}; +function isCall(value) { + return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "call"; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/call.js +/** +* Wraps a user function in a Runnable that writes the returned value to the RETURN channel. +*/ +function getRunnableForFunc(name, func) { + return new RunnableSequence({ + name, + first: new RunnableCallable({ + func: (input) => func(...input), + name, + trace: false, + recurse: false + }), + last: new ChannelWrite([{ + channel: RETURN, + value: PASSTHROUGH + }], [TAG_HIDDEN]) + }); +} +function getRunnableForEntrypoint(name, func) { + return new RunnableCallable({ + func: (input, config) => { + return func(input, config); + }, + name, + trace: false, + recurse: false + }); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/algo.js +var increment = (current) => { + return current !== void 0 ? current + 1 : 1; +}; +function triggersNextStep(updatedChannels, triggerToNodes) { + if (triggerToNodes == null) return false; + for (const chan of updatedChannels) if (triggerToNodes[chan]) return true; + return false; +} +function maxChannelMapVersion(channelVersions) { + let maxVersion; + for (const chan in channelVersions) { + if (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) continue; + if (maxVersion == null) maxVersion = channelVersions[chan]; + else maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]); + } + return maxVersion; +} +function shouldInterrupt(checkpoint, interruptNodes, tasks) { + const nullVersion = getNullChannelVersion(checkpoint.channel_versions); + const seen = checkpoint.versions_seen["__interrupt__"] ?? {}; + let anyChannelUpdated = false; + if ((checkpoint.channel_versions["__start__"] ?? nullVersion) > (seen["__start__"] ?? nullVersion)) anyChannelUpdated = true; + else for (const chan in checkpoint.channel_versions) { + if (!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)) continue; + if (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) { + anyChannelUpdated = true; + break; + } + } + const anyTriggeredNodeInInterruptNodes = tasks.some((task) => interruptNodes === "*" ? !task.config?.tags?.includes(TAG_HIDDEN) : interruptNodes.includes(task.name)); + return anyChannelUpdated && anyTriggeredNodeInInterruptNodes; +} +function _localRead(checkpoint, channels, task, select, fresh = false) { + let updated = /* @__PURE__ */ new Set(); + if (!Array.isArray(select)) { + for (const [c] of task.writes) if (c === select) { + updated = /* @__PURE__ */ new Set([c]); + break; + } + updated = updated || /* @__PURE__ */ new Set(); + } else updated = new Set(select.filter((c) => task.writes.some(([key, _]) => key === c))); + let values; + if (fresh && updated.size > 0) { + const localChannels = Object.fromEntries(Object.entries(channels).filter(([k, _]) => updated.has(k))); + const channelsToSnapshot = /* @__PURE__ */ new Set(); + for (const k in localChannels) { + if (!Object.prototype.hasOwnProperty.call(localChannels, k)) continue; + const ch = localChannels[k]; + if (isDeltaChannel$1(ch) && ch.isAvailable()) channelsToSnapshot.add(k); + } + const newCheckpoint = createCheckpoint(checkpoint, localChannels, -1, { channelsToSnapshot }); + const newChannels = emptyChannels(localChannels, newCheckpoint); + _applyWrites(copyCheckpoint(newCheckpoint), newChannels, [task], void 0, void 0); + values = readChannels({ + ...channels, + ...newChannels + }, select); + } else values = readChannels(channels, select); + return values; +} +function _localWrite(commit, processes, writes) { + for (const [chan, value] of writes) if (["__pregel_push", "__pregel_tasks"].includes(chan) && value != null) { + if (!_isSend(value)) throw new InvalidUpdateError(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`); + if (!(value.node in processes)) throw new InvalidUpdateError(`Invalid node name "${value.node}" in Send packet`); + } + commit(writes); +} +var IGNORE = /* @__PURE__ */ new Set([ + NO_WRITES, + PUSH, + RESUME$1, + INTERRUPT$1, + RETURN, + ERROR$1, + ERROR_SOURCE_NODE +]); +var RESERVED_SET = new Set(RESERVED); +function _applyWrites(checkpoint, channels, tasks, getNextVersion, triggerToNodes) { + const pathCache = /* @__PURE__ */ new Map(); + for (const task of tasks) pathCache.set(task, task.path?.slice(0, 3) || []); + tasks.sort((a, b) => { + const aPath = pathCache.get(a); + const bPath = pathCache.get(b); + for (let i = 0; i < Math.min(aPath.length, bPath.length); i += 1) { + if (aPath[i] < bPath[i]) return -1; + if (aPath[i] > bPath[i]) return 1; + } + return aPath.length - bPath.length; + }); + const onlyChannels = getOnlyChannels(channels); + let bumpStep = false; + const channelsToConsume = /* @__PURE__ */ new Set(); + for (const task of tasks) { + if (task.triggers.length > 0) bumpStep = true; + checkpoint.versions_seen[task.name] ??= {}; + for (const chan of task.triggers) { + if (chan in checkpoint.channel_versions) checkpoint.versions_seen[task.name][chan] = checkpoint.channel_versions[chan]; + if (!RESERVED_SET.has(chan)) channelsToConsume.add(chan); + } + } + let maxVersion = maxChannelMapVersion(checkpoint.channel_versions); + let usedNewVersion = false; + for (const chan of channelsToConsume) if (chan in onlyChannels && onlyChannels[chan].consume()) { + if (getNextVersion !== void 0) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + usedNewVersion = true; + } + } + const pendingWritesByChannel = {}; + const pendingWriteTaskIdsByChannel = {}; + for (const task of tasks) { + const taskId = task.id ?? ""; + for (const [chan, val] of task.writes) if (IGNORE.has(chan)) {} else if (chan in onlyChannels) { + pendingWritesByChannel[chan] ??= []; + pendingWritesByChannel[chan].push(val); + pendingWriteTaskIdsByChannel[chan] ??= []; + pendingWriteTaskIdsByChannel[chan].push(taskId); + } + } + for (const [chan, vals] of Object.entries(pendingWritesByChannel)) { + if (vals.length < 2) continue; + if (onlyChannels[chan]?.lc_graph_name !== "DeltaChannel") continue; + const taskIds = pendingWriteTaskIdsByChannel[chan]; + const paired = vals.map((val, i) => ({ + val, + taskId: taskIds[i] + })); + paired.sort((a, b) => a.taskId < b.taskId ? -1 : a.taskId > b.taskId ? 1 : 0); + pendingWritesByChannel[chan] = paired.map((p) => p.val); + } + if (maxVersion != null && getNextVersion != null) maxVersion = usedNewVersion ? getNextVersion(maxVersion) : maxVersion; + const updatedChannels = /* @__PURE__ */ new Set(); + for (const [chan, vals] of Object.entries(pendingWritesByChannel)) if (chan in onlyChannels) { + const channel = onlyChannels[chan]; + let updated; + try { + updated = channel.update(vals); + } catch (e) { + if (e.name === InvalidUpdateError.unminifiable_name) { + const wrappedError = new InvalidUpdateError(`Invalid update for channel "${chan}" with values ${JSON.stringify(vals)}: ${e.message}`); + wrappedError.lc_error_code = e.lc_error_code; + throw wrappedError; + } else throw e; + } + if (updated && getNextVersion !== void 0) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) updatedChannels.add(chan); + } + } + if (bumpStep) for (const chan in onlyChannels) { + if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue; + const channel = onlyChannels[chan]; + if (channel.isAvailable() && !updatedChannels.has(chan)) { + if (channel.update([]) && getNextVersion !== void 0) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) updatedChannels.add(chan); + } + } + } + if (bumpStep && !triggersNextStep(updatedChannels, triggerToNodes)) for (const chan in onlyChannels) { + if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue; + const channel = onlyChannels[chan]; + if (channel.finish() && getNextVersion !== void 0) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) updatedChannels.add(chan); + } + } + return updatedChannels; +} +function* candidateNodes(checkpoint, processes, extra) { + if (extra.updatedChannels != null && extra.triggerToNodes != null) { + const triggeredNodes = /* @__PURE__ */ new Set(); + for (const channel of extra.updatedChannels) { + const nodeIds = extra.triggerToNodes[channel]; + for (const id of nodeIds ?? []) triggeredNodes.add(id); + } + yield* [...triggeredNodes].sort(); + return; + } + if ((() => { + for (const chan in checkpoint.channel_versions) if (checkpoint.channel_versions[chan] !== null) return false; + return true; + })()) return; + for (const name in processes) { + if (!Object.prototype.hasOwnProperty.call(processes, name)) continue; + yield name; + } +} +/** +* Build an index over pendingWrites for O(1) lookups. +* +* @internal Exported for benchmarks and regression tests only. +*/ +function _indexPendingWrites(pendingWrites) { + let nullResume; + const resumeByTaskId = /* @__PURE__ */ new Map(); + const successfulWriteTaskIds = /* @__PURE__ */ new Set(); + if (pendingWrites) for (const [tid, chan, val] of pendingWrites) { + if (tid === "00000000-0000-0000-0000-000000000000" && chan === "__resume__" && nullResume === void 0) nullResume = val; + if (chan === "__resume__" && tid !== "00000000-0000-0000-0000-000000000000") { + let arr = resumeByTaskId.get(tid); + if (!arr) { + arr = []; + resumeByTaskId.set(tid, arr); + } + arr.push(val); + } + if (chan !== "__error__") successfulWriteTaskIds.add(tid); + } + return { + nullResume, + resumeByTaskId, + successfulWriteTaskIds + }; +} +/** +* Prepare the set of tasks that will make up the next Pregel step. +* This is the union of all PUSH tasks (Sends) and PULL tasks (nodes triggered +* by edges). +*/ +function _prepareNextTasks(checkpoint, pendingWrites, processes, channels, config, forExecution, extra) { + const tasks = {}; + const indexedExtra = extra.pendingWritesIndex ? extra : { + ...extra, + pendingWritesIndex: _indexPendingWrites(pendingWrites) + }; + const tasksChannel = channels[TASKS]; + if (tasksChannel?.isAvailable()) { + const len = tasksChannel.get().length; + for (let i = 0; i < len; i += 1) { + const task = _prepareSingleTask([PUSH, i], checkpoint, pendingWrites, processes, channels, config, forExecution, indexedExtra); + if (task !== void 0) tasks[task.id] = task; + } + } + for (const name of candidateNodes(checkpoint, processes, indexedExtra)) { + const task = _prepareSingleTask([PULL, name], checkpoint, pendingWrites, processes, channels, config, forExecution, indexedExtra); + if (task !== void 0) tasks[task.id] = task; + } + return tasks; +} +/** +* Prepares a single task for the next Pregel step, given a task path, which +* uniquely identifies a PUSH or PULL task within the graph. +*/ +function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processes, channels, config, forExecution, extra) { + const { step, checkpointer, manager } = extra; + const configurable = config.configurable ?? {}; + const parentNamespace = configurable.checkpoint_ns ?? ""; + if (taskPath[0] === "__pregel_push" && isCall(taskPath[taskPath.length - 1])) { + const call = taskPath[taskPath.length - 1]; + const proc = getRunnableForFunc(call.name, call.func); + const triggers = [PUSH]; + const checkpointNamespace = parentNamespace === "" ? call.name : `${parentNamespace}|${call.name}`; + const id = uuid5(JSON.stringify([ + checkpointNamespace, + step.toString(), + call.name, + PUSH, + taskPath[1], + taskPath[2] + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${id}`; + const outputTaskPath = [...taskPath.slice(0, 3), true]; + const metadata = { + langgraph_step: step, + langgraph_node: call.name, + langgraph_triggers: triggers, + langgraph_path: outputTaskPath, + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId: id, + threadId: configurable.thread_id, + runId: config.runId != null ? String(config.runId) : void 0, + nodeAttempt: 1 + }; + return { + name: call.name, + input: call.input, + proc, + writes, + config: { + ...patchConfig(mergeConfigs(config, { + metadata, + store: extra.store ?? config.store + }), { + runName: call.name, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: id, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name: call.name, + writes, + triggers, + path: outputTaskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId: id, + currentTaskInput: call.input, + resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace), + pendingWritesIndex: extra.pendingWritesIndex + }), + [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + checkpoint_id: void 0, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers, + retry_policy: call.retry, + cache_key: call.cache ? { + key: XXH3((call.cache.keyFunc ?? JSON.stringify)([call.input])), + ns: [CACHE_NS_WRITES, call.name ?? "__dynamic__"], + ttl: call.cache.ttl + } : void 0, + id, + path: outputTaskPath, + writers: [], + timeout: call.timeout + }; + } else return { + id, + name: call.name, + interrupts: [], + path: outputTaskPath + }; + } else if (taskPath[0] === "__pregel_push") { + const index = typeof taskPath[1] === "number" ? taskPath[1] : parseInt(taskPath[1], 10); + if (!channels["__pregel_tasks"]?.isAvailable()) return; + const sends = channels[TASKS].get(); + if (index < 0 || index >= sends.length) return; + const packet = _isSendInterface(sends[index]) && !_isSend(sends[index]) ? new Send(sends[index].node, sends[index].args, sends[index].timeout !== void 0 ? { timeout: sends[index].timeout } : void 0) : sends[index]; + if (!_isSendInterface(packet)) { + console.warn(`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`); + return; + } + if (!(packet.node in processes)) { + console.warn(`Ignoring unknown node name ${packet.node} in pending sends.`); + return; + } + const triggers = [PUSH]; + const checkpointNamespace = parentNamespace === "" ? packet.node : `${parentNamespace}|${packet.node}`; + const taskId = uuid5(JSON.stringify([ + checkpointNamespace, + step.toString(), + packet.node, + PUSH, + index.toString() + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; + let metadata = { + langgraph_step: step, + langgraph_node: packet.node, + langgraph_triggers: triggers, + langgraph_path: taskPath.slice(0, 3), + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const proc = processes[packet.node]; + const node = proc.getNode(); + if (node !== void 0) { + if (proc.metadata !== void 0) metadata = { + ...metadata, + ...proc.metadata + }; + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId, + threadId: configurable.thread_id, + runId: config.runId != null ? String(config.runId) : void 0, + nodeAttempt: 1 + }; + return { + name: packet.node, + input: packet.args, + proc: node, + subgraphs: proc.subgraphs, + writes, + config: { + ...patchConfig(mergeConfigs(config, { + metadata, + tags: proc.tags, + store: extra.store ?? config.store + }), { + runName: packet.node, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: taskId, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name: packet.node, + writes, + triggers, + path: taskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId, + currentTaskInput: packet.args, + resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace), + pendingWritesIndex: extra.pendingWritesIndex + }), + [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + checkpoint_id: void 0, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers, + retry_policy: proc.retryPolicy, + cache_key: proc.cachePolicy ? { + key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([packet.args])), + ns: [ + CACHE_NS_WRITES, + proc.name ?? "__dynamic__", + packet.node + ], + ttl: proc.cachePolicy.ttl + } : void 0, + id: taskId, + path: taskPath, + writers: proc.getWriters(), + timeout: packet.timeout ?? proc.timeout + }; + } + } else return { + id: taskId, + name: packet.node, + interrupts: [], + path: taskPath + }; + } else if (taskPath[0] === "__pregel_pull") { + const name = taskPath[1].toString(); + const proc = processes[name]; + if (proc === void 0) return; + if (pendingWrites?.length) { + const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; + const taskId = uuid5(JSON.stringify([ + checkpointNamespace, + step.toString(), + name, + PULL, + name + ]), checkpoint.id); + if (extra.pendingWritesIndex ? extra.pendingWritesIndex.successfulWriteTaskIds.has(taskId) : pendingWrites.some((w) => w[0] === taskId && w[1] !== "__error__")) return; + } + const nullVersion = getNullChannelVersion(checkpoint.channel_versions); + if (nullVersion === void 0) return; + const seen = checkpoint.versions_seen[name] ?? {}; + const trigger = proc.triggers.find((chan) => { + if (!channels[chan].isAvailable()) return false; + return (checkpoint.channel_versions[chan] ?? nullVersion) > (seen[chan] ?? nullVersion); + }); + if (trigger !== void 0) { + const val = _procInput(proc, channels, forExecution); + if (val === void 0) return; + const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; + const taskId = uuid5(JSON.stringify([ + checkpointNamespace, + step.toString(), + name, + PULL, + [trigger] + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; + let metadata = { + langgraph_step: step, + langgraph_node: name, + langgraph_triggers: [trigger], + langgraph_path: taskPath, + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const node = proc.getNode(); + if (node !== void 0) { + if (proc.metadata !== void 0) metadata = { + ...metadata, + ...proc.metadata + }; + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId, + threadId: configurable.thread_id, + runId: config.runId != null ? String(config.runId) : void 0, + nodeAttempt: 1 + }; + return { + name, + input: val, + proc: node, + subgraphs: proc.subgraphs, + writes, + config: { + ...patchConfig(mergeConfigs(config, { + metadata, + tags: proc.tags, + store: extra.store ?? config.store + }), { + runName: name, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: taskId, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => { + writes.push(...items); + }, processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name, + writes, + triggers: [trigger], + path: taskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId, + currentTaskInput: val, + resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace), + pendingWritesIndex: extra.pendingWritesIndex + }), + [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + checkpoint_id: void 0, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers: [trigger], + retry_policy: proc.retryPolicy, + cache_key: proc.cachePolicy ? { + key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([val])), + ns: [ + CACHE_NS_WRITES, + proc.name ?? "__dynamic__", + name + ], + ttl: proc.cachePolicy.ttl + } : void 0, + id: taskId, + path: taskPath, + writers: proc.getWriters(), + timeout: proc.timeout + }; + } + } else return { + id: taskId, + name, + interrupts: [], + path: taskPath + }; + } + } +} +/** +* Prepare an immediate node-level error handler task for a failed task. +* +* The handler runs only after the failed node's retry policy is exhausted (the +* runner schedules it once a non-bubble-up error settles). It is prepared like +* a PUSH task targeting the auto-generated handler node, receives the failed +* node's input, and is injected with a {@link NodeError} under +* {@link CONFIG_KEY_NODE_ERROR} so the handler can inspect the failure +* provenance (and route via `Command({ goto })`). +* +* @internal +*/ +function _prepareNodeErrorHandlerTask(failedTask, handlerNodeName, error, checkpoint, pendingWrites, processes, channels, config, extra) { + const { step, checkpointer, manager } = extra; + const proc = processes[handlerNodeName]; + if (proc === void 0) return; + const node = proc.getNode(); + if (node === void 0) return; + const configurable = config.configurable ?? {}; + const parentNamespace = configurable.checkpoint_ns ?? ""; + const triggers = [PUSH]; + const checkpointNamespace = parentNamespace === "" ? handlerNodeName : `${parentNamespace}|${handlerNodeName}`; + const taskId = uuid5(JSON.stringify([ + checkpointNamespace, + step.toString(), + handlerNodeName, + PUSH, + "node_error_handler", + failedTask.id + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; + const taskPath = [ + PUSH, + String(failedTask.name), + handlerNodeName, + false + ]; + let metadata = { + langgraph_step: step, + langgraph_node: handlerNodeName, + langgraph_triggers: triggers, + langgraph_path: taskPath, + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (proc.metadata !== void 0) metadata = { + ...metadata, + ...proc.metadata + }; + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId, + threadId: configurable.thread_id, + runId: config.runId != null ? String(config.runId) : void 0, + nodeAttempt: 1 + }; + return { + name: handlerNodeName, + input: failedTask.input, + proc: node, + subgraphs: proc.subgraphs, + writes, + config: { + ...patchConfig(mergeConfigs(config, { + metadata, + tags: proc.tags, + store: extra.store ?? config.store + }), { + runName: handlerNodeName, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: taskId, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name: handlerNodeName, + writes, + triggers, + path: taskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId, + currentTaskInput: failedTask.input, + resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace) + }), + [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + [CONFIG_KEY_NODE_ERROR]: new NodeError(String(failedTask.name), error), + checkpoint_id: void 0, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers, + retry_policy: proc.retryPolicy, + cache_key: void 0, + id: taskId, + path: taskPath, + writers: proc.getWriters() + }; +} +/** +* Function injected under CONFIG_KEY_READ in task config, to read current state. +* Used by conditional edges to read a copy of the state with reflecting the writes +* from that node only. +* +* @internal +*/ +function _procInput(proc, channels, forExecution) { + let val; + if (typeof proc.channels === "object" && !Array.isArray(proc.channels)) { + val = {}; + for (const [k, chan] of Object.entries(proc.channels)) if (proc.triggers.includes(chan)) try { + val[k] = readChannel(channels, chan, false); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) return; + else throw e; + } + else if (chan in channels) try { + val[k] = readChannel(channels, chan, false); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) continue; + else throw e; + } + } else if (Array.isArray(proc.channels)) { + let successfulRead = false; + for (const chan of proc.channels) try { + val = readChannel(channels, chan, false); + successfulRead = true; + break; + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) continue; + else throw e; + } + if (!successfulRead) return; + } else throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`); + if (forExecution && proc.mapper !== void 0) val = proc.mapper(val); + return val; +} +/** +* Remove any values belonging to UntrackedValue channels from a Send packet +* before checkpointing. +* +* Send is often called with state to be passed to the destination node, +* which may contain UntrackedValues at the top level. +* +* @internal +*/ +function sanitizeUntrackedValuesInSend(packet, channels) { + if (typeof packet.args !== "object" || packet.args === null) return packet; + const sanitizedArg = {}; + for (const [key, value] of Object.entries(packet.args)) { + const channel = channels[key]; + if (!channel || channel.lc_graph_name !== "UntrackedValue") sanitizedArg[key] = value; + } + return new Send(packet.node, sanitizedArg); +} +function _scratchpad({ pendingWrites, taskId, currentTaskInput, resumeMap, namespaceHash, pendingWritesIndex }) { + const nullResume = pendingWritesIndex ? pendingWritesIndex.nullResume : pendingWrites.find(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__")?.[2]; + const scratchpad = { + callCounter: 0, + interruptCounter: -1, + resume: (() => { + const result = pendingWritesIndex ? (pendingWritesIndex.resumeByTaskId.get(taskId) ?? []).flat() : pendingWrites.filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === "__resume__").flatMap(([_writeTaskId, _chan, resume]) => resume); + if (resumeMap != null && namespaceHash in resumeMap) { + const mappedResume = resumeMap[namespaceHash]; + result.push(mappedResume); + } + return result; + })(), + nullResume, + subgraphCounter: 0, + currentTaskInput, + consumeNullResume: () => { + if (scratchpad.nullResume) { + delete scratchpad.nullResume; + pendingWrites.splice(pendingWrites.findIndex(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__"), 1); + return nullResume; + } + } + }; + return scratchpad; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/debug.js +var COLORS_MAP = { + blue: { + start: "\x1B[34m", + end: "\x1B[0m" + }, + green: { + start: "\x1B[32m", + end: "\x1B[0m" + }, + yellow: { + start: "\x1B[33;1m", + end: "\x1B[0m" + } +}; +/** +* Wrap some text in a color for printing to the console. +*/ +var wrap = (color, text) => `${color.start}${text}${color.end}`; +/** +* Build the user-meaningful metadata to forward on a task's stream payload. +* +* Drops langgraph's internal framework keys ({@link EXCLUDED_METADATA_KEYS}) — +* which are redundant with the task's own fields and namespace — while keeping +* keys like `lc_agent_name`, `ls_integration`, and any user-supplied metadata. +* Filtered config tags are folded in under `tags`, mirroring the messages +* stream handler. Returns `undefined` when there is nothing to forward. +*/ +function buildTaskMetadata(config) { + if (config == null) return void 0; + const metadata = {}; + if (config.metadata != null) { + for (const [key, value] of Object.entries(config.metadata)) if (!EXCLUDED_METADATA_KEYS.has(key)) metadata[key] = value; + } + const filteredTags = filterToUserTags(config.tags); + if (filteredTags != null) metadata.tags = filteredTags; + return Object.keys(metadata).length > 0 ? metadata : void 0; +} +function* mapDebugTasks(tasks) { + for (const { id, name, input, config, triggers, writes } of tasks) { + if (config?.tags?.includes("langsmith:hidden")) continue; + const payload = { + id, + name, + input, + triggers, + interrupts: writes.filter(([writeId, n]) => { + return writeId === id && n === "__interrupt__"; + }).map(([, v]) => { + return v; + }) + }; + const metadata = buildTaskMetadata(config); + if (metadata != null) payload.metadata = metadata; + yield payload; + } +} +function isMultipleChannelWrite(value) { + if (typeof value !== "object" || value === null) return false; + return "$writes" in value && Array.isArray(value.$writes); +} +function mapTaskResultWrites(writes) { + const result = {}; + for (const [channel, value] of writes) { + const strChannel = String(channel); + if (strChannel in result) { + const channelWrites = isMultipleChannelWrite(result[strChannel]) ? result[strChannel].$writes : [result[strChannel]]; + channelWrites.push(value); + result[strChannel] = { $writes: channelWrites }; + } else result[strChannel] = value; + } + return result; +} +function* mapDebugTaskResults(tasks, streamChannels) { + for (const [{ id, name, config }, writes] of tasks) { + if (config?.tags?.includes("langsmith:hidden")) continue; + yield { + id, + name, + result: mapTaskResultWrites(writes.filter(([channel]) => { + return Array.isArray(streamChannels) ? streamChannels.includes(channel) : channel === streamChannels; + })), + interrupts: writes.filter((w) => w[0] === INTERRUPT$1).map((w) => w[1]) + }; + } +} +function* mapDebugCheckpoint(config, channels, streamChannels, metadata, tasks, pendingWrites, parentConfig, outputKeys) { + function formatConfig(config) { + const pyConfig = {}; + if (config.callbacks != null) pyConfig.callbacks = config.callbacks; + if (config.configurable != null) pyConfig.configurable = config.configurable; + if (config.maxConcurrency != null) pyConfig.max_concurrency = config.maxConcurrency; + if (config.metadata != null) pyConfig.metadata = config.metadata; + if (config.recursionLimit != null) pyConfig.recursion_limit = config.recursionLimit; + if (config.runId != null) pyConfig.run_id = config.runId; + if (config.runName != null) pyConfig.run_name = config.runName; + if (config.tags != null) pyConfig.tags = config.tags; + return pyConfig; + } + const parentNs = config.configurable?.checkpoint_ns; + const taskStates = {}; + for (const task of tasks) { + if (!(task.subgraphs?.length ? task.subgraphs : [task.proc]).find(findSubgraphPregel)) continue; + let taskNs = `${task.name}:${task.id}`; + if (parentNs) taskNs = `${parentNs}|${taskNs}`; + taskStates[task.id] = { configurable: { + thread_id: config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + } + yield { + config: formatConfig(config), + values: readChannels(channels, streamChannels), + metadata, + next: tasks.map((task) => task.name), + tasks: tasksWithWrites(tasks, pendingWrites, taskStates, outputKeys), + parentConfig: parentConfig ? formatConfig(parentConfig) : void 0 + }; +} +function tasksWithWrites(tasks, pendingWrites, states, outputKeys) { + return tasks.map((task) => { + const error = pendingWrites.find(([id, n]) => id === task.id && n === "__error__")?.[2]; + const interrupts = pendingWrites.filter(([id, n]) => id === task.id && n === "__interrupt__").map(([, , v]) => v); + const result = (() => { + if (error || interrupts.length || !pendingWrites.length) return void 0; + const idx = pendingWrites.findIndex(([tid, n]) => tid === task.id && n === "__return__"); + if (idx >= 0) return pendingWrites[idx][2]; + if (typeof outputKeys === "string") return pendingWrites.find(([tid, n]) => tid === task.id && n === outputKeys)?.[2]; + if (Array.isArray(outputKeys)) { + const results = pendingWrites.filter(([tid, n]) => tid === task.id && outputKeys.includes(n)).map(([, n, v]) => [n, v]); + if (!results.length) return void 0; + return mapTaskResultWrites(results); + } + })(); + if (error) return { + id: task.id, + name: task.name, + path: task.path, + error, + interrupts, + result + }; + const taskState = states?.[task.id]; + return { + id: task.id, + name: task.name, + path: task.path, + interrupts, + ...taskState !== void 0 ? { state: taskState } : {}, + result + }; + }); +} +function printStepCheckpoint(step, channels, whitelist) { + console.log([ + `${wrap(COLORS_MAP.blue, `[${step}:checkpoint]`)}`, + `\x1b[1m State at the end of step ${step}:\x1b[0m\n`, + JSON.stringify(readChannels(channels, whitelist), null, 2) + ].join("")); +} +function printStepTasks(step, nextTasks) { + const nTasks = nextTasks.length; + console.log([ + `${wrap(COLORS_MAP.blue, `[${step}:tasks]`)}`, + `\x1b[1m Starting step ${step} with ${nTasks} task${nTasks === 1 ? "" : "s"}:\x1b[0m\n`, + nextTasks.map((task) => `- ${wrap(COLORS_MAP.green, String(task.name))} -> ${JSON.stringify(task.input, null, 2)}`).join("\n") + ].join("")); +} +function printStepWrites(step, writes, whitelist) { + const byChannel = {}; + for (const [channel, value] of writes) if (whitelist.includes(channel)) { + if (!byChannel[channel]) byChannel[channel] = []; + byChannel[channel].push(value); + } + console.log([ + `${wrap(COLORS_MAP.blue, `[${step}:writes]`)}`, + `\x1b[1m Finished step ${step} with writes to ${Object.keys(byChannel).length} channel${Object.keys(byChannel).length !== 1 ? "s" : ""}:\x1b[0m\n`, + Object.entries(byChannel).map(([name, vals]) => `- ${wrap(COLORS_MAP.yellow, name)} -> ${vals.map((v) => JSON.stringify(v)).join(", ")}`).join("\n") + ].join("")); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/stream.js +/** +* A wrapper around an IterableReadableStream that allows for aborting the stream when +* {@link cancel} is called. +*/ +var IterableReadableStreamWithAbortSignal = class extends IterableReadableStream { + _abortController; + _innerReader; + /** + * @param readableStream - The stream to wrap. + * @param abortController - The abort controller to use. Optional. One will be created if not provided. + */ + constructor(readableStream, abortController) { + const reader = readableStream.getReader(); + const ac = abortController ?? new AbortController(); + super({ start(controller) { + return pump(); + function pump() { + return reader.read().then(({ done, value }) => { + if (done) { + controller.close(); + return; + } + controller.enqueue(value); + return pump(); + }); + } + } }); + this._abortController = ac; + this._innerReader = reader; + } + /** + * Aborts the stream, abandoning any pending operations in progress. Calling this triggers an + * {@link AbortSignal} that is propagated to the tasks that are producing the data for this stream. + * @param reason - The reason for aborting the stream. Optional. + */ + async cancel(reason) { + this._abortController.abort(reason); + this._innerReader.releaseLock(); + } + /** + * The {@link AbortSignal} for the stream. Aborted when {@link cancel} is called. + */ + get signal() { + return this._abortController.signal; + } +}; +var IterableReadableWritableStream = class extends IterableReadableStream { + modes; + controller; + passthroughFn; + _closed = false; + get closed() { + return this._closed; + } + constructor(params) { + let streamControllerPromiseResolver; + const streamControllerPromise = new Promise((resolve) => { + streamControllerPromiseResolver = resolve; + }); + super({ start: (controller) => { + streamControllerPromiseResolver(controller); + } }); + streamControllerPromise.then((controller) => { + this.controller = controller; + }); + this.passthroughFn = params.passthroughFn; + this.modes = params.modes; + } + push(chunk) { + if (this._closed || !this.controller) return; + this.passthroughFn?.(chunk); + this.controller.enqueue(chunk); + } + close() { + try { + this.controller.close(); + } catch {} finally { + this._closed = true; + } + } + error(e) { + try { + this.controller?.error(e); + } finally { + this._closed = true; + } + } +}; +/** +* A callback handler that implements stream_mode=tools. +* Emits on_tool_start, on_tool_event, on_tool_end, on_tool_error events. +*/ +var StreamToolsHandler = class extends BaseCallbackHandler { + name = "StreamToolsHandler"; + /** Ensure tool lifecycle callbacks run before tool.invoke returns/errors. */ + awaitHandlers = true; + streamFn; + runs = {}; + constructor(streamFn) { + super(); + this.streamFn = streamFn; + } + handleToolStart(_tool, input, runId, _parentRunId, tags, metadata, runName, toolCallId) { + if (!metadata || tags && tags.includes("langsmith:hidden")) return; + const ns = metadata.langgraph_checkpoint_ns?.split("|") ?? []; + const info = { + ns, + toolCallId, + toolName: runName ?? "unknown", + input + }; + this.runs[runId] = info; + this.streamFn([ + ns, + "tools", + { + event: "on_tool_start", + toolCallId: info.toolCallId, + name: info.toolName, + input + } + ]); + } + handleToolEvent(chunk, runId) { + const info = this.runs[runId]; + if (!info) return; + this.streamFn([ + info.ns, + "tools", + { + event: "on_tool_event", + toolCallId: info.toolCallId, + name: info.toolName, + data: chunk + } + ]); + } + handleToolEnd(output, runId) { + const info = this.runs[runId]; + delete this.runs[runId]; + if (!info) return; + this.streamFn([ + info.ns, + "tools", + { + event: "on_tool_end", + toolCallId: info.toolCallId, + name: info.toolName, + output + } + ]); + } + handleToolError(err, runId) { + const info = this.runs[runId]; + delete this.runs[runId]; + if (!info) return; + this.streamFn([ + info.ns, + "tools", + { + event: "on_tool_error", + toolCallId: info.toolCallId, + name: info.toolName, + error: err + } + ]); + } +}; +function _stringifyAsDict(obj) { + return JSON.stringify(obj, function(key, value) { + const rawValue = this[key]; + if (rawValue != null && typeof rawValue === "object" && "toDict" in rawValue && typeof rawValue.toDict === "function") { + const { type, data } = rawValue.toDict(); + return { + ...data, + type + }; + } + return value; + }); +} +function _serializeError(error) { + if (error instanceof Error) return { + error: error.name, + message: error.message + }; + return { + error: "Error", + message: JSON.stringify(error) + }; +} +function _isRunnableConfig(config) { + if (typeof config !== "object" || config == null) return false; + return "configurable" in config && typeof config.configurable === "object" && config.configurable != null; +} +function _extractCheckpointFromConfig(config) { + if (!_isRunnableConfig(config) || !config.configurable.thread_id) return null; + return { + thread_id: config.configurable.thread_id, + checkpoint_ns: config.configurable.checkpoint_ns || "", + checkpoint_id: config.configurable.checkpoint_id || null, + checkpoint_map: config.configurable.checkpoint_map || null + }; +} +function _serializeConfig(config) { + if (_isRunnableConfig(config)) { + const configurable = Object.fromEntries(Object.entries(config.configurable).filter(([key]) => !key.startsWith("__"))); + const newConfig = { + ...config, + configurable + }; + delete newConfig.callbacks; + return newConfig; + } + return config; +} +function _serializeCheckpoint(payload) { + const result = { + ...payload, + checkpoint: _extractCheckpointFromConfig(payload.config), + parent_checkpoint: _extractCheckpointFromConfig(payload.parentConfig), + config: _serializeConfig(payload.config), + parent_config: _serializeConfig(payload.parentConfig), + tasks: payload.tasks.map((task) => { + if (_isRunnableConfig(task.state)) { + const checkpoint = _extractCheckpointFromConfig(task.state); + if (checkpoint != null) { + const cloneTask = { + ...task, + checkpoint + }; + delete cloneTask.state; + return cloneTask; + } + } + return task; + }) + }; + delete result.parentConfig; + return result; +} +function toEventStream(stream) { + const encoder = new TextEncoder(); + return new ReadableStream({ async start(controller) { + const enqueueChunk = (sse) => { + controller.enqueue(encoder.encode(`event: ${sse.event}\ndata: ${_stringifyAsDict(sse.data)}\n\n`)); + }; + try { + for await (const payload of stream) { + const [ns, mode, chunk] = payload; + let data = chunk; + if (mode === "debug") { + const debugChunk = chunk; + if (debugChunk.type === "checkpoint") data = { + ...debugChunk, + payload: _serializeCheckpoint(debugChunk.payload) + }; + } + if (mode === "checkpoints") data = _serializeCheckpoint(chunk); + enqueueChunk({ + event: ns?.length ? `${mode}|${ns.join("|")}` : mode, + data + }); + } + } catch (error) { + enqueueChunk({ + event: "error", + data: _serializeError(error) + }); + } + controller.close(); + } }); +} +/** Multiplex subgraph stream chunks into the parent pregel stream. */ +function createDuplexStream(...streams) { + return new IterableReadableWritableStream({ + passthroughFn: (value) => { + const isEnvelope = value[1] === "checkpoints" && isCheckpointEnvelope(value[2]); + for (const stream of streams) if (stream.modes.has(value[1]) || isEnvelope) stream.push(value); + }, + modes: new Set(streams.flatMap((s) => Array.from(s.modes))) + }); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/replay.js +/** +* Tracks subgraph checkpoint loading during parent-graph time travel. +* +* When a parent replays from a historical checkpoint, nested subgraphs must +* load the checkpoint that existed *before* the replay point on their first +* visit, then fall back to normal latest-checkpoint loading on later visits +* within the same run. +*/ +var ReplayState = class { + /** Parent checkpoint ID used as the `before` cursor for subgraph lookups. */ + checkpointId; + #visitedNs = /* @__PURE__ */ new Set(); + /** + * @param checkpointId - Checkpoint ID from the parent graph at the replay point. + */ + constructor(checkpointId) { + this.checkpointId = checkpointId; + } + /** + * Whether this is the first visit to a logical subgraph namespace in the run. + * + * Task-id suffixes are stripped so the same subgraph invoked across loop + * iterations shares one visit record. + * + * @param checkpointNs - Subgraph checkpoint namespace. + */ + #isFirstVisit(checkpointNs) { + const stableNs = checkpointNs.includes(":") ? checkpointNs.slice(0, checkpointNs.lastIndexOf(":")) : checkpointNs; + if (this.#visitedNs.has(stableNs)) return false; + this.#visitedNs.add(stableNs); + return true; + } + /** + * Load the checkpoint tuple for a subgraph namespace during replay. + * + * On the first visit to `checkpointNs`, returns the latest checkpoint saved + * before {@link ReplayState.checkpointId}. On subsequent visits, delegates to + * `checkpointer.getTuple` for the current config. + * + * @param checkpointNs - Subgraph checkpoint namespace. + * @param checkpointer - Checkpointer shared with the parent graph. + * @param checkpointConfig - Runnable config for the subgraph lookup. + * @returns The resolved checkpoint tuple, if any. + */ + async getCheckpoint(checkpointNs, checkpointer, checkpointConfig) { + if (this.#isFirstVisit(checkpointNs)) { + const results = []; + for await (const saved of checkpointer.list(checkpointConfig, { + before: { configurable: { checkpoint_id: this.checkpointId } }, + limit: 1 + })) results.push(saved); + return results.length > 0 ? results[0] : void 0; + } + return await checkpointer.getTuple(checkpointConfig) ?? void 0; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/loop.js +var INPUT_DONE = Symbol.for("INPUT_DONE"); +var INPUT_RESUMING = Symbol.for("INPUT_RESUMING"); +var DEFAULT_LOOP_LIMIT = 25; +/** +* Recursively assign a stable UUID to any {@link BaseMessage} (in a value, an +* array, or an object's values) that is missing an `id`. Used so DeltaChannel +* writes — replayed on every read — reconstruct identical message identities. +*/ +function ensureMessageIds(value) { + if (value == null || typeof value !== "object") return; + if (BaseMessage.isInstance(value)) { + const msg = value; + if (msg.id == null) { + msg.id = v4(); + if (msg.lc_kwargs != null) msg.lc_kwargs.id = msg.id; + } + return; + } + if (Array.isArray(value)) { + for (const item of value) ensureMessageIds(item); + return; + } +} +/** +* Split a serialized checkpoint namespace into its path segments. +* +* Checkpoint namespaces are stored as a single string whose nested levels are +* joined by {@link CHECKPOINT_NAMESPACE_SEPARATOR} (e.g. `"parent|child"`). +* The root namespace — represented as `undefined` or the empty string — maps +* to an empty array. +* +* @param ns - The serialized checkpoint namespace, or `undefined`. +* @returns The namespace as an array of path segments (`[]` for the root). +*/ +function checkpointNamespaceFromNs(ns) { + if (ns === void 0 || ns === "") return []; + return ns.split("|"); +} +/** +* Find the most deeply nested namespace recorded in a checkpoint map. +* +* The checkpoint map ({@link CONFIG_KEY_CHECKPOINT_MAP}) associates every +* namespace seen on a thread with its checkpoint id. Because nested namespaces +* are built by appending segments to their parent, a deeper namespace always +* yields a longer key — so the longest non-empty key is the deepest one. +* +* Used by the loop's `#interruptStreamNamespace()` during subgraph +* time-travel: interrupt events must be emitted against the active (deepest) +* subgraph namespace rather than the root graph. +* +* @param map - The checkpoint map (namespace -> checkpoint id), or `undefined`. +* @returns The deepest namespace as path segments, or `[]` when the map is +* absent, empty, or only contains the root namespace. +*/ +function deepestCheckpointMapNamespace(map) { + if (!map) return []; + let deepest = ""; + for (const key of Object.keys(map)) if (key !== "" && key.length > deepest.length) deepest = key; + return checkpointNamespaceFromNs(deepest); +} +var AsyncBatchedCache = class extends BaseCache { + cache; + queue = Promise.resolve(); + constructor(cache) { + super(); + this.cache = cache; + } + async get(keys) { + return this.enqueueOperation("get", keys); + } + async set(pairs) { + return this.enqueueOperation("set", pairs); + } + async clear(namespaces) { + return this.enqueueOperation("clear", namespaces); + } + async stop() { + await this.queue; + } + enqueueOperation(type, ...args) { + const newPromise = this.queue.then(() => { + return this.cache[type](...args); + }); + this.queue = newPromise.then(() => void 0, () => void 0); + return newPromise; + } +}; +var PregelLoop = class PregelLoop { + input; + output; + config; + checkpointer; + checkpointerGetNextVersion; + channels; + checkpoint; + checkpointIdSaved; + /** + * Exit-mode accumulator of DeltaChannel writes across the whole run, as + * `[step, taskId, channel, value]`. `undefined` outside "exit" durability. + */ + _exitDeltaWrites; + /** + * DeltaChannels that saw an Overwrite since the last checkpoint. These + * channels are force-snapshotted at the next checkpoint so reconstruction + * starts from the post-overwrite value and never has to replay across the + * reset (the live `update` discards every sibling write in the overwriting + * super-step). Cleared once the channel snapshots. + */ + _deltaChannelsWithOverwrite = /* @__PURE__ */ new Set(); + /** Whether a real checkpoint was loaded from the saver at initialization. */ + _hasPersistedParent = false; + /** The checkpointConfig as captured at initialization (anchor for exit writes). */ + _initialCheckpointConfig; + checkpointConfig; + checkpointMetadata; + checkpointNamespace; + checkpointPendingWrites = []; + checkpointPreviousVersions; + step; + stop; + durability; + outputKeys; + streamKeys; + nodes; + skipDoneTasks; + prevCheckpointConfig; + updatedChannels; + status = "pending"; + /** + * Run-scoped control surface for cooperative draining. Populated from the + * run config. When `control.drainRequested` is true, the loop stops at the + * next superstep boundary instead of dispatching more tasks. + */ + control; + tasks = {}; + stream; + checkpointerPromises = /* @__PURE__ */ new Set(); + isNested; + /** True when an explicit checkpoint_id targets the latest saved checkpoint. */ + resumeAtHead; + _checkpointerChainedPromise = Promise.resolve(); + /** + * Track a checkpointer promise, removing it from the set on success. + * Failed promises are kept so that Promise.all() in the finally block + * of _streamIterator can surface the error. + * + * @internal + */ + _trackCheckpointerPromise(promise) { + const tracked = promise.then((value) => { + this.checkpointerPromises.delete(tracked); + return value; + }, (error) => { + throw error; + }); + this.checkpointerPromises.add(tracked); + } + /** + * Wait for persistence work scheduled by this run up to this point. + * + * Taking a snapshot keeps the barrier scoped to the completed superstep: + * persistence scheduled later cannot extend it, while failures from the + * captured work are propagated at the superstep boundary. + */ + async _awaitCheckpointerPromises() { + await Promise.all([...this.checkpointerPromises]); + } + store; + cache; + manager; + interruptAfter; + interruptBefore; + toInterrupt = []; + debug = false; + triggerToNodes; + get isResuming() { + let hasChannelVersions = false; + if ("__start__" in this.checkpoint.channel_versions) hasChannelVersions = true; + else for (const chan in this.checkpoint.channel_versions) if (Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions, chan)) { + hasChannelVersions = true; + break; + } + const configIsResuming = this.config.configurable?.["__pregel_resuming"] !== void 0 && this.config.configurable?.["__pregel_resuming"]; + const inputIsNullOrUndefined = this.input === null || this.input === void 0; + const inputIsCommandResuming = isCommand(this.input) && this.input.resume != null; + const inputIsResuming = this.input === INPUT_RESUMING; + const runIdMatchesPrevious = !this.isNested && this.config.metadata?.run_id !== void 0 && this.checkpointMetadata?.run_id !== void 0 && this.config.metadata.run_id === this.checkpointMetadata?.run_id; + return hasChannelVersions && (configIsResuming || inputIsNullOrUndefined || inputIsCommandResuming || inputIsResuming || runIdMatchesPrevious); + } + get isReplaying() { + return !this.skipDoneTasks; + } + constructor(params) { + this.input = params.input; + this.checkpointer = params.checkpointer; + if (this.checkpointer !== void 0) this.checkpointerGetNextVersion = this.checkpointer.getNextVersion.bind(this.checkpointer); + else this.checkpointerGetNextVersion = increment; + this.checkpoint = params.checkpoint; + this.checkpointMetadata = params.checkpointMetadata; + this.checkpointPreviousVersions = params.checkpointPreviousVersions; + this.channels = params.channels; + this.checkpointPendingWrites = params.checkpointPendingWrites; + this.step = params.step; + this.stop = params.stop; + this.config = params.config; + this.checkpointConfig = params.checkpointConfig; + this.isNested = params.isNested; + this.resumeAtHead = params.resumeAtHead; + this.manager = params.manager; + this.outputKeys = params.outputKeys; + this.streamKeys = params.streamKeys; + this.nodes = params.nodes; + this.skipDoneTasks = params.skipDoneTasks; + this.store = params.store; + this.cache = params.cache ? new AsyncBatchedCache(params.cache) : void 0; + this.stream = params.stream; + this.checkpointNamespace = params.checkpointNamespace; + this.prevCheckpointConfig = params.prevCheckpointConfig; + this.interruptAfter = params.interruptAfter; + this.interruptBefore = params.interruptBefore; + this.durability = params.durability; + this.debug = params.debug; + this.triggerToNodes = params.triggerToNodes; + this.control = this.config.control; + this._exitDeltaWrites = this.durability === "exit" && this.checkpointer != null ? [] : void 0; + this._hasPersistedParent = params.hasPersistedParent ?? false; + this._initialCheckpointConfig = params.checkpointConfig; + this.checkpointIdSaved = params.checkpoint.id; + } + static async initialize(params) { + let { config, stream } = params; + if (stream !== void 0 && config.configurable?.["__pregel_stream"] !== void 0) stream = createDuplexStream(stream, config.configurable[CONFIG_KEY_STREAM]); + const skipDoneTasks = config.configurable ? !("checkpoint_id" in config.configurable) : true; + const scratchpad = config.configurable?.[CONFIG_KEY_SCRATCHPAD]; + if (config.configurable && scratchpad) { + if (scratchpad.subgraphCounter > 0) config = patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_NS]: [config.configurable[CONFIG_KEY_CHECKPOINT_NS], scratchpad.subgraphCounter.toString()].join("|") }); + scratchpad.subgraphCounter += 1; + } + const requestedCheckpointId = config.configurable?.checkpoint_id; + const isNested = CONFIG_KEY_READ in (config.configurable ?? {}); + if (!isNested && config.configurable?.checkpoint_ns !== void 0 && config.configurable?.checkpoint_ns !== "") config = patchConfigurable(config, { + checkpoint_ns: "", + checkpoint_id: void 0 + }); + let checkpointConfig = config; + if (config.configurable?.checkpoint_id === void 0 && config.configurable?.["checkpoint_map"] !== void 0 && config.configurable?.["checkpoint_map"]?.[config.configurable?.checkpoint_ns]) checkpointConfig = patchConfigurable(config, { checkpoint_id: config.configurable[CONFIG_KEY_CHECKPOINT_MAP][config.configurable?.checkpoint_ns] }); + const checkpointNamespace = checkpointNamespaceFromNs(config.configurable?.checkpoint_ns); + let saved; + if (!params.checkpointer) saved = void 0; + else if (checkpointConfig.configurable?.["checkpoint_id"]) saved = await params.checkpointer.getTuple(checkpointConfig); + else if (config.configurable?.["__pregel_replay_state"]) { + saved = await config.configurable[CONFIG_KEY_REPLAY_STATE].getCheckpoint(config.configurable?.["checkpoint_ns"] ?? "", params.checkpointer, checkpointConfig); + if (config.configurable) delete config.configurable[CONFIG_KEY_RESUMING]; + } else saved = await params.checkpointer.getTuple(checkpointConfig); + const hasPersistedParent = saved !== void 0; + if (!saved) saved = { + config, + checkpoint: emptyCheckpoint(), + metadata: { + source: "input", + step: -2, + parents: {} + }, + pendingWrites: [] + }; + checkpointConfig = { + ...config, + ...saved.config, + configurable: { + checkpoint_ns: "", + ...config.configurable, + ...saved.config.configurable + } + }; + const prevCheckpointConfig = saved.parentConfig; + const checkpoint = copyCheckpoint(saved.checkpoint); + const checkpointMetadata = { ...saved.metadata }; + let checkpointPendingWrites = saved.pendingWrites ?? []; + const currentCheckpointNamespace = config.configurable?.checkpoint_ns; + const checkpointMap = config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP]; + if (typeof currentCheckpointNamespace === "string" && currentCheckpointNamespace !== "" && typeof checkpointMap === "object" && checkpointMap !== null && currentCheckpointNamespace in checkpointMap && checkpointPendingWrites.length > 0) checkpointPendingWrites = checkpointPendingWrites.filter(([, channel]) => channel !== RESUME$1); + let resumeAtHead = false; + const threadId = checkpointConfig.configurable?.thread_id; + const checkpointNs = checkpointConfig.configurable?.checkpoint_ns ?? ""; + if (params.checkpointer && requestedCheckpointId && typeof threadId === "string") resumeAtHead = (await params.checkpointer.getTuple({ configurable: { + thread_id: threadId, + checkpoint_ns: checkpointNs + } }))?.config.configurable?.checkpoint_id === requestedCheckpointId && checkpointMetadata.source !== "update" && checkpointMetadata.source !== "fork"; + const channels = await channelsFromCheckpoint(params.channelSpecs, checkpoint, { + saver: params.checkpointer, + config: checkpointConfig + }); + const step = (checkpointMetadata.step ?? 0) + 1; + const stop = step + (config.recursionLimit ?? DEFAULT_LOOP_LIMIT) + 1; + const checkpointPreviousVersions = { ...checkpoint.channel_versions }; + const store = params.store ? new AsyncBatchedStore(params.store) : void 0; + if (store) await store.start(); + return new PregelLoop({ + input: params.input, + config, + checkpointer: params.checkpointer, + checkpoint, + checkpointMetadata, + checkpointConfig, + prevCheckpointConfig, + checkpointNamespace, + channels, + isNested, + resumeAtHead, + manager: params.manager, + skipDoneTasks, + step, + stop, + checkpointPreviousVersions, + checkpointPendingWrites, + outputKeys: params.outputKeys ?? [], + streamKeys: params.streamKeys ?? [], + nodes: params.nodes, + stream, + store, + cache: params.cache, + interruptAfter: params.interruptAfter, + interruptBefore: params.interruptBefore, + durability: params.durability, + debug: params.debug, + triggerToNodes: params.triggerToNodes, + hasPersistedParent + }); + } + _checkpointerPutAfterPrevious(input) { + this._checkpointerChainedPromise = this._checkpointerChainedPromise.then(() => { + return this.checkpointer?.put(input.config, input.checkpoint, input.metadata, input.newVersions); + }); + this._trackCheckpointerPromise(this._checkpointerChainedPromise); + } + /** + * Put writes for a task, to be read by the next tick. + * @param taskId + * @param writes + */ + putWrites(taskId, writes) { + let writesCopy = writes; + if (writesCopy.length === 0) return; + if (writesCopy.every(([key]) => key in WRITES_IDX_MAP)) writesCopy = Array.from(new Map(writesCopy.map((w) => [w[0], w])).values()); + let hasUntrackedChannels = false; + for (const key in this.channels) if (Object.prototype.hasOwnProperty.call(this.channels, key)) { + if (this.channels[key].lc_graph_name === "UntrackedValue") { + hasUntrackedChannels = true; + break; + } + } + let writesToSave = writesCopy; + if (hasUntrackedChannels) writesToSave = writesCopy.filter(([c]) => { + const channel = this.channels[c]; + return !channel || channel.lc_graph_name !== "UntrackedValue"; + }).map(([c, v]) => { + if (c === "__pregel_tasks" && _isSend(v)) return [c, sanitizeUntrackedValuesInSend(v, this.channels)]; + return [c, v]; + }); + this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[0] !== taskId); + for (const [c, v] of writesToSave) this.checkpointPendingWrites.push([ + taskId, + c, + v + ]); + for (const [c, v] of writesToSave) { + const channel = this.channels[c]; + if (channel != null && isDeltaChannel$1(channel)) ensureMessageIds(v); + } + const config = patchConfigurable(this.checkpointConfig, { + [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", + [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id + }); + if (this.durability !== "exit" && this.checkpointer != null) this._trackCheckpointerPromise(this.checkpointer.putWrites(config, writesToSave, taskId)); + if (this.tasks) this._outputWrites(taskId, writesCopy); + if (!writes.length || !this.cache || !this.tasks) return; + const task = this.tasks[taskId]; + if (task == null || task.cache_key == null) return; + if (writes[0][0] === "__error__" || writes[0][0] === "__interrupt__") return; + this.cache.set([{ + key: [task.cache_key.ns, task.cache_key.key], + value: task.writes, + ttl: task.cache_key.ttl + }]); + } + _outputWrites(taskId, writes, cached = false) { + const task = this.tasks[taskId]; + if (task !== void 0) { + if (task.config !== void 0 && (task.config.tags ?? []).includes("langsmith:hidden")) return; + if (writes.length > 0) { + if (writes[0][0] === "__interrupt__") { + if (task.path?.[0] === "__pregel_push" && task.path?.[task.path.length - 1] === true) return; + const interruptWrites = writes.filter((w) => w[0] === INTERRUPT$1).flatMap((w) => w[1]); + this._emit([["updates", { [INTERRUPT$1]: interruptWrites }], ["values", { [INTERRUPT$1]: interruptWrites }]]); + } else if (writes[0][0] !== "__error__") this._emit(gatherIteratorSync(prefixGenerator(mapOutputUpdates(this.outputKeys, [[task, writes]], cached), "updates"))); + } + if (!cached) this._emit(gatherIteratorSync(prefixGenerator(mapDebugTaskResults([[task, writes]], this.streamKeys), "tasks"))); + } + } + async _matchCachedWrites() { + if (!this.cache) return []; + const matched = []; + const serializeKey = ([ns, key]) => { + return `ns:${ns.join(",")}|key:${key}`; + }; + const keys = []; + const keyMap = {}; + for (const task of Object.values(this.tasks)) if (task.cache_key != null && !task.writes.length) { + keys.push([task.cache_key.ns, task.cache_key.key]); + keyMap[serializeKey([task.cache_key.ns, task.cache_key.key])] = task; + } + if (keys.length === 0) return []; + const cache = await this.cache.get(keys); + for (const { key, value } of cache) { + const task = keyMap[serializeKey(key)]; + if (task != null) { + task.writes.push(...value); + matched.push({ + task, + result: value + }); + } + } + return matched; + } + /** + * Execute a single iteration of the Pregel loop. + * Returns true if more iterations are needed. + * @param params - The input keys to use for the tick. + * @returns True if more iterations are needed, false otherwise. + */ + async tick(params) { + if (this.store && !this.store.isRunning) await this.store?.start(); + const { inputKeys = [] } = params; + if (this.status !== "pending") throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`); + if (![INPUT_DONE, INPUT_RESUMING].includes(this.input)) await this._first(inputKeys); + else if (this.toInterrupt.length > 0) { + this.status = "interrupt_before"; + throw new GraphInterrupt(); + } else if (Object.values(this.tasks).every((task) => task.writes.length > 0)) { + const finishTaskList = Object.values(this.tasks); + const writes = finishTaskList.flatMap((t) => t.writes); + this.updatedChannels = _applyWrites(this.checkpoint, this.channels, finishTaskList, this.checkpointerGetNextVersion, this.triggerToNodes); + for (const [ch, v] of writes) { + const channel = this.channels[ch]; + if (channel != null && isDeltaChannel$1(channel) && _isOverwriteValue(v)) this._deltaChannelsWithOverwrite.add(ch); + } + const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, writes, this.channels), "values")); + if (this._exitDeltaWrites !== void 0) for (const [tid, ch, v] of this.checkpointPendingWrites) { + const channel = this.channels[ch]; + if (channel != null && isDeltaChannel$1(channel)) this._exitDeltaWrites.push([ + this.step, + tid, + ch, + v + ]); + } + this.checkpointPendingWrites = []; + await this._putCheckpoint({ source: "loop" }); + if (this.durability === "sync") await this._awaitCheckpointerPromises(); + this._emitValuesWithCheckpointMeta(valuesOutput); + if (shouldInterrupt(this.checkpoint, this.interruptAfter, finishTaskList)) { + this.status = "interrupt_after"; + throw new GraphInterrupt(); + } + if (this.config.configurable?.["__pregel_resuming"] !== void 0) delete this.config.configurable?.[CONFIG_KEY_RESUMING]; + } else return false; + if (this.step > this.stop) { + this.status = "out_of_steps"; + return false; + } + this.tasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { + step: this.step, + checkpointer: this.checkpointer, + isResuming: this.isResuming, + manager: this.manager, + store: this.store, + stream: this.stream, + triggerToNodes: this.triggerToNodes, + updatedChannels: this.updatedChannels + }); + let taskList = Object.values(this.tasks); + if (this.checkpointer && (this.stream.modes.has("checkpoints") || this.stream.modes.has("debug"))) this._emit(await gatherIterator(prefixGenerator(mapDebugCheckpoint(this.checkpointConfig, this.channels, this.streamKeys, this.checkpointMetadata, taskList, this.checkpointPendingWrites, this.prevCheckpointConfig, this.outputKeys), "checkpoints"))); + if (taskList.length === 0) { + this.status = "done"; + return false; + } + if (this.control != null && this.control.drainRequested) { + this.status = "draining"; + return false; + } + if (this.skipDoneTasks && this.checkpointPendingWrites.length > 0) { + for (const [tid, k, v] of this.checkpointPendingWrites) { + if (k === "__error__" || k === "__error_source_node__" || k === "__interrupt__" || k === "__resume__") continue; + const task = taskList.find((t) => t.id === tid); + if (task) task.writes.push([k, v]); + } + this._resumeErrorHandlersIfApplicable(); + taskList = Object.values(this.tasks); + for (const task of taskList) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true); + } + if (taskList.every((task) => task.writes.length > 0)) return this.tick({ inputKeys }); + if (shouldInterrupt(this.checkpoint, this.interruptBefore, taskList)) { + this.status = "interrupt_before"; + throw new GraphInterrupt(); + } + if (this.stream.modes.has("tasks") || this.stream.modes.has("debug")) { + const debugOutput = await gatherIterator(prefixGenerator(mapDebugTasks(taskList), "tasks")); + this._emit(debugOutput); + } + return true; + } + async finishAndHandleError(error) { + if (this.durability === "exit" && (!this.isNested || typeof error !== "undefined" || this.checkpointNamespace.every((part) => !part.includes(":")))) { + await this._putExitDeltaWrites(); + this._putCheckpoint(this.checkpointMetadata); + this._flushPendingWrites(); + } + const suppress = this._suppressInterrupt(error); + if (suppress || error === void 0) this.output = readChannels(this.channels, this.outputKeys); + if (suppress) { + if (this.tasks !== void 0 && this.checkpointPendingWrites.length > 0 && Object.values(this.tasks).some((task) => task.writes.length > 0)) { + this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); + this._emitValuesWithCheckpointMeta(gatherIteratorSync(prefixGenerator(mapOutputValues(this.outputKeys, Object.values(this.tasks).flatMap((t) => t.writes), this.channels), "values"))); + } + if (isGraphInterrupt(error) && !error.interrupts.length) this._emit([["updates", { [INTERRUPT$1]: [] }], ["values", { [INTERRUPT$1]: [] }]], this.#interruptStreamNamespace()); + } + return suppress; + } + async acceptPush(task, writeIdx, call) { + if (this.interruptAfter?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptAfter, [task])) { + this.toInterrupt.push(task); + return; + } + const pushed = _prepareSingleTask([ + PUSH, + task.path ?? [], + writeIdx, + task.id, + call + ], this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, task.config ?? {}, true, { + step: this.step, + checkpointer: this.checkpointer, + manager: this.manager, + store: this.store, + stream: this.stream + }); + if (!pushed) return; + if (this.interruptBefore?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptBefore, [pushed])) { + this.toInterrupt.push(pushed); + return; + } + if (this.stream.modes.has("tasks") || this.stream.modes.has("debug")) this._emit(gatherIteratorSync(prefixGenerator(mapDebugTasks([pushed]), "tasks"))); + if (this.debug) printStepTasks(this.step, [pushed]); + this.tasks[pushed.id] = pushed; + if (this.skipDoneTasks) this._matchWrites({ [pushed.id]: pushed }); + const tasks = await this._matchCachedWrites(); + for (const { task } of tasks) this._outputWrites(task.id, task.writes, true); + return pushed; + } + /** + * Returns the name of the error handler node registered for `nodeName`, or + * `undefined` if none is configured. + */ + getErrorHandlerNode(nodeName) { + return this.nodes[nodeName]?.errorHandlerNode; + } + /** + * Whether `nodeName` is itself an auto-generated error handler node. + */ + isErrorHandlerNode(nodeName) { + return this.nodes[nodeName]?.isErrorHandler === true; + } + /** + * Schedule a node-level error handler task for a task that failed after its + * retry policy was exhausted. Prepares the handler task (injecting a + * {@link NodeError}), registers it so the runner executes it within the + * current step, and returns it (or `undefined` if no handler applies). + * + * The failure provenance (`ERROR` + `ERROR_SOURCE_NODE`) is checkpointed by + * the runner via {@link PregelLoop#putWrites} so handlers observe the same + * context after a resume. + */ + scheduleErrorHandler(failedTask, error) { + const handlerNode = this.getErrorHandlerNode(String(failedTask.name)); + if (!handlerNode) return void 0; + const handlerTask = _prepareNodeErrorHandlerTask(failedTask, handlerNode, error, this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, failedTask.config ?? this.config, { + step: this.step, + checkpointer: this.checkpointer, + manager: this.manager, + store: this.store, + stream: this.stream + }); + if (handlerTask === void 0) return void 0; + this.tasks[handlerTask.id] = handlerTask; + this._emit(gatherIteratorSync(prefixGenerator(mapDebugTasks([handlerTask]), "tasks"))); + if (this.debug) printStepTasks(this.step, [handlerTask]); + return handlerTask; + } + /** + * On resume, re-schedule error handlers for tasks that failed in a prior run + * but had not finished being handled. Scans pending writes for + * `ERROR_SOURCE_NODE` markers (paired with `ERROR`), marks the originating + * task as done (so the runner won't re-run it), and prepares a fresh handler + * task so the runner picks it up. + */ + _resumeErrorHandlersIfApplicable() { + const failed = /* @__PURE__ */ new Map(); + for (const [tid, chan] of this.checkpointPendingWrites) { + if (chan !== "__error_source_node__") continue; + const errorWrite = this.checkpointPendingWrites.find(([t, c]) => t === tid && c === "__error__"); + if (errorWrite === void 0) continue; + const value = errorWrite[2]; + const error = new Error(value?.message ?? String(value)); + if (value?.name) error.name = value.name; + failed.set(tid, error); + } + for (const [tid, error] of failed) { + const task = this.tasks[tid]; + if (task === void 0) continue; + if (!this.getErrorHandlerNode(String(task.name))) continue; + if (task.writes.length === 0) task.writes.push([ERROR$1, { + message: error.message, + name: error.name + }]); + this.scheduleErrorHandler(task, error); + } + } + _suppressInterrupt(e) { + return isGraphInterrupt(e) && !this.isNested; + } + async _first(inputKeys) { + const { configurable } = this.config; + const scratchpad = configurable?.[CONFIG_KEY_SCRATCHPAD]; + if (scratchpad && scratchpad.nullResume !== void 0) this.putWrites(NULL_TASK_ID, [[RESUME$1, scratchpad.nullResume]]); + if (isCommand(this.input)) { + const hasResume = this.input.resume != null; + if (this.input.resume != null && typeof this.input.resume === "object" && Object.keys(this.input.resume).every(isXXH3)) { + this.config.configurable ??= {}; + this.config.configurable[CONFIG_KEY_RESUME_MAP] = this.input.resume; + } + if (hasResume && this.checkpointer == null) throw new Error("Cannot use Command(resume=...) without checkpointer"); + const writes = {}; + for (const [tid, key, value] of mapCommand(this.input, this.checkpointPendingWrites)) { + writes[tid] ??= []; + writes[tid].push([key, value]); + } + if (Object.keys(writes).length === 0) throw new EmptyInputError("Received empty Command input"); + for (const [tid, ws] of Object.entries(writes)) this.putWrites(tid, ws); + } + const nullWrites = (this.checkpointPendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); + if (nullWrites.length > 0) _applyWrites(this.checkpoint, this.channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], this.checkpointerGetNextVersion, this.triggerToNodes); + const inputIsCommand = isCommand(this.input); + const isCommandUpdateOrGoto = inputIsCommand && nullWrites.length > 0; + const isTimeTraveling = this.isReplaying && (this.isNested && configurable?.["checkpoint_ns"] !== void 0 && configurable?.["checkpoint_ns"] !== "" && configurable?.["checkpoint_map"] !== void 0 && configurable["checkpoint_ns"] in configurable["checkpoint_map"] || !(inputIsCommand && this.input.resume != null || configurable?.["__pregel_resuming"] === true || this.resumeAtHead)); + if (isTimeTraveling) this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[1] !== RESUME$1); + const cachedIsResuming = this.isResuming; + if (cachedIsResuming || isCommandUpdateOrGoto) { + const interruptSeen = { ...this.checkpoint.versions_seen[INTERRUPT$1] }; + for (const channelName in this.channels) { + if (!Object.prototype.hasOwnProperty.call(this.channels, channelName)) continue; + if (this.checkpoint.channel_versions[channelName] !== void 0) interruptSeen[channelName] = this.checkpoint.channel_versions[channelName]; + } + this.checkpoint.versions_seen[INTERRUPT$1] = interruptSeen; + if (isTimeTraveling && this.checkpointMetadata.source !== "update" && this.checkpointMetadata.source !== "fork") { + this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[1] !== INTERRUPT$1); + await this._putCheckpoint({ source: "fork" }); + } + const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, true, this.channels), "values")); + if (cachedIsResuming) this.input = INPUT_RESUMING; + else if (isCommandUpdateOrGoto) { + await this._putCheckpoint({ source: "input" }); + this.input = INPUT_DONE; + } + this._emitValuesWithCheckpointMeta(valuesOutput); + } else { + const inputWrites = await gatherIterator(mapInput(inputKeys, this.input)); + if (inputWrites.length > 0) { + const discardTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { step: this.step }); + this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(discardTasks).concat([{ + name: INPUT, + writes: inputWrites, + triggers: [] + }]), this.checkpointerGetNextVersion, this.triggerToNodes); + const deltaInput = inputWrites.filter(([c]) => { + const channel = this.channels[c]; + return channel != null && isDeltaChannel$1(channel); + }); + for (const [c, v] of deltaInput) if (_isOverwriteValue(v)) this._deltaChannelsWithOverwrite.add(c); + if (deltaInput.length > 0) { + if (this._exitDeltaWrites !== void 0) for (const [c, v] of deltaInput) this._exitDeltaWrites.push([ + this.step, + NULL_TASK_ID, + c, + v + ]); + else if (this.checkpointer != null) this.putWrites(NULL_TASK_ID, deltaInput); + } + await this._putCheckpoint({ source: "input" }); + this.input = INPUT_DONE; + } else if (!("__pregel_resuming" in (this.config.configurable ?? {}))) throw new EmptyInputError(`Received no input writes for ${JSON.stringify(inputKeys, null, 2)}`); + else this.input = INPUT_DONE; + } + if (!this.isNested) { + let replayState; + if (isTimeTraveling) { + let replayCheckpointId = this.checkpoint.id; + if ((this.checkpointMetadata.source === "update" || this.checkpointMetadata.source === "fork") && this.prevCheckpointConfig) replayCheckpointId = this.prevCheckpointConfig.configurable?.["checkpoint_id"] ?? replayCheckpointId; + replayState = new ReplayState(replayCheckpointId); + } + this.config = patchConfigurable(this.config, { + [CONFIG_KEY_RESUMING]: this.isResuming, + [CONFIG_KEY_REPLAY_STATE]: replayState + }); + } + } + #interruptStreamNamespace() { + const ns = this.checkpointNamespace; + if (!(ns.length === 0 || ns.length === 1 && ns[0] === "") || this.config.configurable?.["__pregel_stream"] === void 0) return ns; + const deepest = deepestCheckpointMapNamespace(this.config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP]); + return deepest.length > 0 ? deepest : ns; + } + _emit(values, namespace = this.checkpointNamespace) { + for (const [mode, payload] of values) { + if (this.stream.modes.has(mode)) this.stream.push([ + namespace, + mode, + payload + ]); + if ((mode === "checkpoints" || mode === "tasks") && this.stream.modes.has("debug")) { + const step = mode === "checkpoints" ? this.step - 1 : this.step; + const timestamp = (/* @__PURE__ */ new Date()).toISOString(); + const type = (() => { + if (mode === "checkpoints") return "checkpoint"; + else if (typeof payload === "object" && payload != null && "result" in payload) return "task_result"; + else return "task"; + })(); + this.stream.push([ + namespace, + "debug", + { + step, + type, + timestamp, + payload + } + ]); + } + } + } + /** + * Build a {@link StreamChunkMeta} describing the currently active checkpoint. + * Emitted as a separate ``[namespace, "checkpoints", envelope]`` chunk before + * the paired ``values`` chunk. Returns `undefined` if no checkpoint metadata + * is available yet. + */ + _currentCheckpointMeta() { + if (!this.checkpointMetadata || !this.checkpoint?.id) return void 0; + const parent_id = this.prevCheckpointConfig?.configurable?.checkpoint_id; + return { checkpoint: { + id: this.checkpoint.id, + ...parent_id ? { parent_id } : {}, + step: this.checkpointMetadata.step, + source: this.checkpointMetadata.source + } }; + } + /** + * Emit stream entries. When checkpoint meta is available, push a lightweight + * ``[namespace, "checkpoints", envelope]`` chunk before each ``values`` chunk. + */ + _emitValuesWithCheckpointMeta(entries) { + const meta = this._currentCheckpointMeta(); + for (const [mode, payload] of entries) { + if (mode === "values" && meta?.checkpoint != null && !this.stream.modes.has("checkpoints")) this.stream.push([ + this.checkpointNamespace, + "checkpoints", + meta.checkpoint + ]); + if (this.stream.modes.has(mode)) this.stream.push([ + this.checkpointNamespace, + mode, + payload + ]); + } + } + _putCheckpoint(inputMetadata) { + const exiting = this.checkpointMetadata === inputMetadata; + const doCheckpoint = this.checkpointer != null && (this.durability !== "exit" || exiting); + const storeCheckpoint = (checkpoint) => { + this.prevCheckpointConfig = this.checkpointConfig?.configurable?.checkpoint_id ? this.checkpointConfig : void 0; + this.checkpointConfig = patchConfigurable(this.checkpointConfig, { [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "" }); + const channelVersions = { ...this.checkpoint.channel_versions }; + const newVersions = getNewChannelVersions(this.checkpointPreviousVersions, channelVersions); + this.checkpointPreviousVersions = channelVersions; + this._checkpointerPutAfterPrevious({ + config: { ...this.checkpointConfig }, + checkpoint: copyCheckpoint(checkpoint), + metadata: { ...this.checkpointMetadata }, + newVersions + }); + this.checkpointConfig = { + ...this.checkpointConfig, + configurable: { + ...this.checkpointConfig.configurable, + checkpoint_id: this.checkpoint.id + } + }; + }; + let newCounters; + if (!exiting) { + const prevCounters = this.checkpointMetadata.counters_since_delta_snapshot ?? {}; + newCounters = {}; + const updated = this.updatedChannels ?? /* @__PURE__ */ new Set(); + for (const chName in this.channels) { + if (!Object.prototype.hasOwnProperty.call(this.channels, chName)) continue; + if (!isDeltaChannel$1(this.channels[chName])) continue; + const [u, s] = prevCounters[chName] ?? [0, 0]; + newCounters[chName] = [updated.has(chName) ? u + 1 : u, s + 1]; + } + this.checkpointMetadata = { + ...inputMetadata, + step: this.step, + parents: this.config.configurable?.["checkpoint_map"] ?? {} + }; + } else newCounters = { ...this.checkpointMetadata.counters_since_delta_snapshot ?? {} }; + const channelsToSnapshot = doCheckpoint ? deltaChannelsToSnapshot(this.channels, newCounters) : /* @__PURE__ */ new Set(); + if (doCheckpoint) for (const ch of this._deltaChannelsWithOverwrite) channelsToSnapshot.add(ch); + this.checkpoint = createCheckpoint(this.checkpoint, doCheckpoint ? this.channels : void 0, this.step, { + id: exiting ? this.checkpoint.id : void 0, + channelsToSnapshot, + updatedChannels: this.updatedChannels, + getNextVersion: doCheckpoint ? (current) => this.checkpointerGetNextVersion(current) : void 0 + }); + for (const k of channelsToSnapshot) { + newCounters[k] = [0, 0]; + this._deltaChannelsWithOverwrite.delete(k); + } + const nonZero = {}; + for (const k in newCounters) { + if (!Object.prototype.hasOwnProperty.call(newCounters, k)) continue; + const [u, s] = newCounters[k]; + if (u !== 0 || s !== 0) nonZero[k] = [u, s]; + } + if (Object.keys(nonZero).length > 0) this.checkpointMetadata.counters_since_delta_snapshot = nonZero; + else delete this.checkpointMetadata.counters_since_delta_snapshot; + if (doCheckpoint) storeCheckpoint(this.checkpoint); + if (!exiting) this.step += 1; + } + /** + * Stage the exit-mode accumulator of DeltaChannel writes so the final + * checkpoint can be reconstructed. In "exit" durability per-step writes are + * not persisted, so delta writes are accumulated across the run and anchored + * here — under the saved parent, or a freshly-created stub when this is a + * first run with no persisted parent. Channels that will snapshot in the + * final checkpoint are excluded (their full value lives in `channel_values`). + * + * Must run BEFORE the final `_putCheckpoint` so the stub branch can adjust + * `checkpointConfig` to anchor the final checkpoint on the stub. + */ + async _putExitDeltaWrites() { + if (this._exitDeltaWrites === void 0 || this._exitDeltaWrites.length === 0 || this.checkpointer == null || this._initialCheckpointConfig === void 0) return; + const counters = this.checkpointMetadata.counters_since_delta_snapshot ?? {}; + const channelsToSnapshot = deltaChannelsToSnapshot(this.channels, counters); + for (const ch of this._deltaChannelsWithOverwrite) channelsToSnapshot.add(ch); + const pending = this._exitDeltaWrites.filter(([, , ch]) => !channelsToSnapshot.has(ch)); + if (pending.length === 0) return; + let anchorConfig; + if (this._hasPersistedParent) anchorConfig = this._initialCheckpointConfig; + else { + const stubCp = emptyCheckpoint(); + stubCp.id = this.checkpointIdSaved ?? stubCp.id; + stubCp.ts = (/* @__PURE__ */ new Date()).toISOString(); + const stubPutConfig = patchConfigurable(this._initialCheckpointConfig, { [CONFIG_KEY_CHECKPOINT_ID]: void 0 }); + anchorConfig = patchConfigurable(this._initialCheckpointConfig, { [CONFIG_KEY_CHECKPOINT_ID]: stubCp.id }); + this._trackCheckpointerPromise(this.checkpointer.put(stubPutConfig, stubCp, { + source: "loop", + step: -2, + parents: {} + }, {})); + this.checkpointConfig = anchorConfig; + } + const anchorWriteConfig = patchConfigurable(anchorConfig, { + [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", + [CONFIG_KEY_CHECKPOINT_ID]: anchorConfig.configurable?.[CONFIG_KEY_CHECKPOINT_ID] + }); + const grouped = /* @__PURE__ */ new Map(); + const order = []; + for (const [step, tid, ch, v] of pending) { + const key = `${step}\u0000${tid}`; + let group = grouped.get(key); + if (group === void 0) { + group = []; + grouped.set(key, group); + order.push({ + key, + step, + tid + }); + } + group.push([ch, v]); + } + for (const { key, step, tid } of order) { + const synthTid = exitDeltaTaskId(step, tid); + this._trackCheckpointerPromise(this.checkpointer.putWrites(anchorWriteConfig, grouped.get(key), synthTid)); + } + } + _flushPendingWrites() { + if (this.checkpointer == null) return; + if (this.checkpointPendingWrites.length === 0) return; + const config = patchConfigurable(this.checkpointConfig, { + [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", + [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id + }); + const byTask = {}; + for (const [tid, key, value] of this.checkpointPendingWrites) { + byTask[tid] ??= []; + byTask[tid].push([key, value]); + } + for (const [tid, ws] of Object.entries(byTask)) this._trackCheckpointerPromise(this.checkpointer.putWrites(config, ws, tid)); + } + _matchWrites(tasks) { + for (const [tid, k, v] of this.checkpointPendingWrites) { + if (k === "__error__" || k === "__interrupt__" || k === "__resume__") continue; + const task = Object.values(tasks).find((t) => t.id === tid); + if (task) task.writes.push([k, v]); + } + for (const task of Object.values(tasks)) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/messages.js +function isChatGenerationChunk(x) { + return isBaseMessage(x?.message); +} +function normalizeStreamMetadata(metadata, tags, name) { + if (!metadata) return; + const streamNamespace = metadata.langgraph_checkpoint_ns; + const checkpointNs = metadata.checkpoint_ns; + const namespace = streamNamespace ?? checkpointNs; + if (!namespace) return; + return [namespace.split("|"), { + tags, + name, + ...metadata + }]; +} +/** +* A callback handler that implements stream_mode=messages. +* Collects messages from (1) chat model stream events and (2) node outputs. +*/ +var StreamMessagesHandler = class extends BaseCallbackHandler { + name = "StreamMessagesHandler"; + streamFn; + metadatas = {}; + seen = {}; + emittedChatModelRunIds = {}; + stableMessageIdMap = {}; + lc_prefer_streaming = true; + constructor(streamFn) { + super(); + this.streamFn = streamFn; + } + _emit(meta, message, runId, dedupe = false) { + if (dedupe && message.id !== void 0 && this.seen[message.id] !== void 0) return; + let messageId = message.id; + if (runId != null) if (isToolMessage(message)) messageId ??= `run-${runId}-tool-${message.tool_call_id}`; + else { + if (messageId == null || messageId === `run-${runId}`) messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; + this.stableMessageIdMap[runId] ??= messageId; + } + if (messageId !== message.id) { + message.id = messageId; + message.lc_kwargs.id = messageId; + } + if (message.id != null) this.seen[message.id] = message; + this.streamFn([ + meta[0], + "messages", + [message, meta[1]] + ]); + } + handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { + if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) this.metadatas[runId] = normalizeStreamMetadata(metadata, tags, name); + } + handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, fields) { + const chunk = fields?.chunk; + this.emittedChatModelRunIds[runId] = true; + if (this.metadatas[runId] !== void 0) if (isChatGenerationChunk(chunk)) this._emit(this.metadatas[runId], chunk.message, runId); + else this._emit(this.metadatas[runId], new AIMessageChunk({ content: token }), runId); + } + handleLLMEnd(output, runId) { + if (this.metadatas[runId] === void 0) return; + if (!this.emittedChatModelRunIds[runId]) { + const chatGeneration = output.generations?.[0]?.[0]; + if (isBaseMessage(chatGeneration?.message)) this._emit(this.metadatas[runId], chatGeneration?.message, runId, true); + delete this.emittedChatModelRunIds[runId]; + } + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; + } + handleLLMError(_err, runId) { + delete this.metadatas[runId]; + } + handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { + if (metadata !== void 0 && name === metadata.langgraph_node && (tags === void 0 || !tags.includes("langsmith:hidden"))) { + this.metadatas[runId] = normalizeStreamMetadata(metadata, tags, name); + if (typeof inputs === "object") { + for (const value of Object.values(inputs)) if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== void 0) this.seen[value.id] = value; + else if (Array.isArray(value)) { + for (const item of value) if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== void 0) this.seen[item.id] = item; + } + } + } + } + handleChainEnd(outputs, runId) { + const metadata = this.metadatas[runId]; + delete this.metadatas[runId]; + if (metadata !== void 0) { + if (isBaseMessage(outputs)) this._emit(metadata, outputs, runId, true); + else if (Array.isArray(outputs)) { + for (const value of outputs) if (isBaseMessage(value)) this._emit(metadata, value, runId, true); + } else if (outputs != null && typeof outputs === "object") { + for (const value of Object.values(outputs)) if (isBaseMessage(value)) this._emit(metadata, value, runId, true); + else if (Array.isArray(value)) { + for (const item of value) if (isBaseMessage(item)) this._emit(metadata, item, runId, true); + } + } + } + } + handleChainError(_err, runId) { + delete this.metadatas[runId]; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/messages-v2.js +function getResponseMetadata(message) { + if ("response_metadata" in message && typeof message.response_metadata === "object" && message.response_metadata != null) return message.response_metadata; +} +function getUsageMetadata(message) { + if ("usage_metadata" in message && typeof message.usage_metadata === "object" && message.usage_metadata != null) return message.usage_metadata; +} +function startBlockFor(block) { + switch (block.type) { + case "text": return { + type: "text", + text: "" + }; + case "reasoning": return { + type: "reasoning", + reasoning: "" + }; + case "tool_call": + case "tool_call_chunk": return { + type: "tool_call_chunk", + ...block.id != null ? { id: block.id } : {}, + ...block.name != null ? { name: block.name } : {}, + args: "" + }; + default: return block; + } +} +function deltaFor(block) { + switch (block.type) { + case "text": { + const text = typeof block.text === "string" ? block.text : ""; + return text.length > 0 ? { + event: "content-block-delta", + index: typeof block.index === "number" ? block.index : 0, + delta: { + type: "text-delta", + text + } + } : void 0; + } + case "reasoning": { + const reasoning = typeof block.reasoning === "string" ? block.reasoning : ""; + return reasoning.length > 0 ? { + event: "content-block-delta", + index: typeof block.index === "number" ? block.index : 0, + delta: { + type: "reasoning-delta", + reasoning + } + } : void 0; + } + case "tool_call_chunk": return { + event: "content-block-delta", + index: typeof block.index === "number" ? block.index : 0, + delta: { + type: "block-delta", + fields: { + ...block, + type: "tool_call_chunk" + } + } + }; + default: return; + } +} +/** +* A callback handler that implements protocol-native stream_mode=messages. +* +* LangChain Core owns chat model content-block event construction. This handler +* only captures LangGraph metadata, forwards Core events to the Pregel messages +* channel, and emits a small non-streaming fallback for models that cannot +* produce stream events. +*/ +var StreamProtocolMessagesHandler = class extends BaseCallbackHandler { + name = "StreamProtocolMessagesHandler"; + streamFn; + metadatas = {}; + seen = {}; + streamedRunIds = /* @__PURE__ */ new Set(); + stableMessageIdMap = {}; + lc_prefer_chat_model_stream_events = true; + awaitHandlers = true; + constructor(streamFn) { + super(); + this.streamFn = streamFn; + } + normalizeMessageId(message, runId) { + let messageId = message.id; + if (runId != null) if (ToolMessage.isInstance(message)) messageId ??= `run-${runId}-tool-${message.tool_call_id}`; + else { + if (messageId == null || messageId === `run-${runId}`) messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; + this.stableMessageIdMap[runId] ??= messageId; + } + if (messageId !== message.id) { + message.id = messageId; + message.lc_kwargs.id = messageId; + } + if (message.id != null) this.seen[message.id] = message; + return message.id; + } + emit(meta, data, runId) { + const metadata = runId != null ? { + ...meta[1], + run_id: runId + } : meta[1]; + this.streamFn([ + meta[0], + "messages", + [data, metadata] + ]); + } + emitFinalMessage(meta, message, runId, dedupe = false) { + const existingId = message.id ?? (runId != null ? this.stableMessageIdMap[runId] : void 0); + if (dedupe && existingId != null && this.seen[existingId] !== void 0) return; + const messageId = this.normalizeMessageId(message, runId); + const role = message.type === "human" ? "human" : message.type === "system" ? "system" : message.type === "tool" ? "tool" : "ai"; + const toolCallId = role === "tool" && ToolMessage.isInstance(message) ? message.tool_call_id : void 0; + this.emit(meta, { + event: "message-start", + ...messageId != null ? { id: messageId } : {}, + ...role !== "ai" ? { role } : {}, + ...typeof toolCallId === "string" ? { tool_call_id: toolCallId } : {} + }, runId); + (Array.isArray(message.content) ? message.content : typeof message.content === "string" && message.content.length > 0 ? [{ + type: "text", + text: message.content + }] : []).forEach((block, offset) => { + const index = typeof block.index === "number" ? block.index : offset; + this.emit(meta, { + event: "content-block-start", + index, + content: startBlockFor(block) + }, runId); + const delta = deltaFor({ + ...block, + index + }); + if (delta != null) this.emit(meta, delta, runId); + this.emit(meta, { + event: "content-block-finish", + index, + content: block + }, runId); + }); + this.emit(meta, { + event: "message-finish", + ...getUsageMetadata(message) != null ? { usage: getUsageMetadata(message) } : {}, + ...getResponseMetadata(message) != null ? { responseMetadata: getResponseMetadata(message) } : {} + }, runId); + } + handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { + if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { + tags, + name, + ...metadata + }]; + } + handleLLMNewToken() {} + handleChatModelStreamEvent(event, runId) { + const meta = this.metadatas[runId]; + if (meta === void 0) return; + let forwarded = event; + if (event.event === "message-start") { + this.streamedRunIds.add(runId); + const id = event.id ?? `run-${runId}`; + this.seen[id] = true; + this.stableMessageIdMap[runId] ??= id; + if (event.id == null) forwarded = { + ...event, + id + }; + } + this.emit(meta, forwarded, runId); + } + handleLLMEnd(output, runId) { + const meta = this.metadatas[runId]; + if (meta === void 0) return; + const chatGeneration = output.generations?.[0]?.[0]; + const message = BaseMessage.isInstance(chatGeneration?.message) ? chatGeneration.message : void 0; + if (message != null) if (this.streamedRunIds.has(runId)) { + const messageId = this.normalizeMessageId(message, runId); + if (messageId != null) this.seen[messageId] = message; + } else this.emitFinalMessage(meta, message, runId, true); + this.streamedRunIds.delete(runId); + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; + } + handleLLMError(_err, runId) { + this.streamedRunIds.delete(runId); + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; + } + handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { + if (metadata !== void 0 && name === metadata.langgraph_node && (tags === void 0 || !tags.includes("langsmith:hidden"))) { + this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { + tags, + name, + ...metadata + }]; + if (typeof inputs === "object") { + for (const value of Object.values(inputs)) if ((BaseMessage.isInstance(value) || BaseMessageChunk.isInstance(value)) && value.id !== void 0) this.seen[value.id] = value; + else if (Array.isArray(value)) { + for (const item of value) if ((BaseMessage.isInstance(item) || BaseMessageChunk.isInstance(item)) && item.id !== void 0) this.seen[item.id] = item; + } + } + } + } + handleChainEnd(outputs, runId) { + const meta = this.metadatas[runId]; + delete this.metadatas[runId]; + if (meta === void 0) return; + const emitMessage = (value) => { + if (BaseMessage.isInstance(value) && !ToolMessage.isInstance(value)) this.emitFinalMessage(meta, value, runId, true); + }; + if (BaseMessage.isInstance(outputs)) emitMessage(outputs); + else if (Array.isArray(outputs)) for (const value of outputs) emitMessage(value); + else if (outputs != null && typeof outputs === "object") for (const value of Object.values(outputs)) if (Array.isArray(value)) for (const item of value) emitMessage(item); + else emitMessage(value); + delete this.stableMessageIdMap[runId]; + } + handleChainError(_err, runId) { + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/timeout.js +/** +* Tracks the live progress state of a single timed node attempt. +* +* The scope guards observable-progress channels (writes, child-task +* scheduling, the custom stream writer, callbacks) so that: +* +* 1. `idleTimeout` is refreshed whenever the node makes progress, and +* 2. once the attempt is `close()`d after a timeout fires, late writes/calls +* from the still-running background task are dropped (Python parity: +* buffered writes from the failed attempt must not leak into the +* checkpoint). +* +* @internal +*/ +var TimedAttemptScope = class { + active = true; + lastProgress = Date.now(); + refreshOn; + constructor(refreshOn) { + this.refreshOn = refreshOn; + } + /** Record progress now. Always honored (used by `runtime.heartbeat()`). */ + touch() { + this.lastProgress = Date.now(); + } + /** + * Record progress for an automatic signal (write/call/stream/callback). + * No-op when `refreshOn === "heartbeat"`, where only explicit heartbeats + * count as progress. + */ + autoTouch() { + if (this.refreshOn === "auto") this.lastProgress = Date.now(); + } + close() { + this.active = false; + } +}; +/** +* Callback handler that refreshes a {@link TimedAttemptScope} on any LangChain +* callback event emitted under the node's run. Because it is attached via +* `config.callbacks`, it only observes events from runs descended from this +* node's attempt, not from sibling nodes. +* +* @internal +*/ +var IdleProgressCallbackHandler = class extends BaseCallbackHandler { + name = "IdleProgressCallbackHandler"; + awaitHandlers = false; + #scope; + constructor(scope) { + super(); + this.#scope = scope; + } + #touch = () => { + this.#scope.autoTouch(); + }; + handleLLMStart = this.#touch; + handleChatModelStart = this.#touch; + handleLLMNewToken = this.#touch; + handleLLMEnd = this.#touch; + handleLLMError = this.#touch; + handleChainStart = this.#touch; + handleChainEnd = this.#touch; + handleChainError = this.#touch; + handleToolStart = this.#touch; + handleToolEnd = this.#touch; + handleToolError = this.#touch; + handleText = this.#touch; + handleRetrieverStart = this.#touch; + handleRetrieverEnd = this.#touch; + handleRetrieverError = this.#touch; + handleCustomEvent = this.#touch; +}; +/** +* Wrap the node attempt config so observable-progress signals refresh the idle +* clock and are dropped once the scope is closed. Also injects +* {@link LangGraphRunnableConfig.heartbeat}. +*/ +function wrapConfig(config, scope, policy, taskName) { + const configurable = config.configurable ?? {}; + const patch = {}; + const send = configurable[CONFIG_KEY_SEND]; + if (typeof send === "function") patch[CONFIG_KEY_SEND] = (writes) => { + if (!scope.active) return void 0; + if (writes && writes.length) scope.autoTouch(); + return send(writes); + }; + const callFn = configurable[CONFIG_KEY_CALL]; + if (typeof callFn === "function") patch[CONFIG_KEY_CALL] = (...args) => { + if (!scope.active) throw new Error(`Node "${taskName}" attempt was cancelled after its timeout fired`); + scope.autoTouch(); + return callFn(...args); + }; + const wrapped = { ...Object.keys(patch).length > 0 ? patchConfigurable(config, patch) : config }; + wrapped.heartbeat = () => { + if (policy.idleTimeout !== void 0) scope.touch(); + }; + if (typeof wrapped.writer === "function") { + const writer = wrapped.writer; + wrapped.writer = ((chunk) => { + if (!scope.active) return void 0; + scope.autoTouch(); + return writer(chunk); + }); + } + if ((policy.refreshOn ?? "auto") === "auto" && policy.idleTimeout !== void 0) { + const handler = new IdleProgressCallbackHandler(scope); + const cb = wrapped.callbacks; + if (cb === void 0) wrapped.callbacks = [handler]; + else if (Array.isArray(cb)) wrapped.callbacks = [...cb, handler]; + else { + const copied = cb.copy(); + copied.addHandler(handler, true); + wrapped.callbacks = copied; + } + } + return wrapped; +} +/** +* Run a single node attempt under a {@link TimeoutPolicy}. +* +* Races the node invocation against per-attempt run/idle watchdogs. On +* successful completion (or node error), returns/rethrows normally. When a +* watchdog fires first, the scope is closed, the task's buffered writes are +* dropped, the attempt's {@link AbortSignal} is aborted, and a +* {@link NodeTimeoutError} is thrown. +* +* @internal +*/ +async function runAttemptWithTimeout(task, config, policy, invoke) { + const scope = new TimedAttemptScope(policy.refreshOn ?? "auto"); + const timeoutController = new AbortController(); + const { signal: composedSignal, dispose } = combineAbortSignals(config.signal, timeoutController.signal); + const scopedConfig = wrapConfig({ + ...config, + signal: composedSignal + }, scope, policy, String(task.name)); + const start = Date.now(); + const nodeOutcome = invoke(scopedConfig).then((value) => ({ + type: "ok", + value + }), (error) => ({ + type: "err", + error + })); + let runTimer; + let idleTimer; + const clearTimers = () => { + if (runTimer !== void 0) clearTimeout(runTimer); + if (idleTimer !== void 0) clearTimeout(idleTimer); + }; + const watchdog = new Promise((resolve) => { + if (policy.runTimeout !== void 0) runTimer = setTimeout(() => resolve({ + type: "timeout", + kind: "run" + }), policy.runTimeout); + if (policy.idleTimeout !== void 0) { + const idleMs = policy.idleTimeout; + const checkIdle = () => { + const remaining = scope.lastProgress + idleMs - Date.now(); + if (remaining <= 0) resolve({ + type: "timeout", + kind: "idle" + }); + else idleTimer = setTimeout(checkIdle, remaining); + }; + idleTimer = setTimeout(checkIdle, idleMs); + } + }); + let outcome; + try { + outcome = await Promise.race([nodeOutcome, watchdog]); + } finally { + clearTimers(); + } + if (outcome.type !== "timeout") { + const now = Date.now(); + if (policy.runTimeout !== void 0 && now - start >= policy.runTimeout) outcome = { + type: "timeout", + kind: "run" + }; + else if (policy.idleTimeout !== void 0 && now - scope.lastProgress >= policy.idleTimeout) outcome = { + type: "timeout", + kind: "idle" + }; + } + if (outcome.type === "ok") { + dispose?.(); + return outcome.value; + } + if (outcome.type === "err") { + dispose?.(); + throw outcome.error; + } + const elapsed = Date.now() - start; + scope.close(); + task.writes.splice(0, task.writes.length); + timeoutController.abort(); + dispose?.(); + throw new NodeTimeoutError({ + node: String(task.name), + elapsed, + kind: outcome.kind, + runTimeout: policy.runTimeout, + idleTimeout: policy.idleTimeout + }); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/retry.js +var DEFAULT_STATUS_NO_RETRY = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 409 +]; +var DEFAULT_RETRY_ON_HANDLER = (error) => { + if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") return false; + if (error.name === "GraphValueError") return false; + if (error?.code === "ECONNABORTED") return false; + const status = error?.response?.status ?? error?.status; + if (status && DEFAULT_STATUS_NO_RETRY.includes(+status)) return false; + if (error?.error?.code === "insufficient_quota") return false; + return true; +}; +async function _runWithRetry(pregelTask, retryPolicy, configurable, signal) { + const resolvedRetryPolicy = pregelTask.retry_policy ?? retryPolicy; + let attempts = 0; + let error; + let result; + let config = pregelTask.config ?? {}; + if (configurable) config = patchConfigurable(config, configurable); + config = { + ...config, + signal + }; + const firstAttemptTime = Date.now(); + if (config.executionInfo != null) config.executionInfo = { + ...config.executionInfo, + nodeFirstAttemptTime: firstAttemptTime + }; + while (true) { + if (signal?.aborted) break; + pregelTask.writes.splice(0, pregelTask.writes.length); + error = void 0; + try { + if (pregelTask.timeout !== void 0) result = await runAttemptWithTimeout(pregelTask, config, pregelTask.timeout, (scopedConfig) => pregelTask.proc.invoke(pregelTask.input, scopedConfig)); + else result = await pregelTask.proc.invoke(pregelTask.input, config); + break; + } catch (e) { + error = e; + error.pregelTaskId = pregelTask.id; + if (isParentCommand(error)) { + const ns = config?.configurable?.checkpoint_ns; + const cmd = error.command; + if (cmd.graph === ns) { + for (const writer of pregelTask.writers) await writer.invoke(cmd, config); + error = void 0; + break; + } else if (cmd.graph === Command.PARENT) { + const parentNs = getParentCheckpointNamespace(ns); + error.command = new Command({ + ...error.command, + graph: parentNs + }); + } + } + if (isGraphBubbleUp(error)) break; + if (resolvedRetryPolicy === void 0) break; + attempts += 1; + if (attempts >= (resolvedRetryPolicy.maxAttempts ?? 3)) break; + if (!(resolvedRetryPolicy.retryOn ?? DEFAULT_RETRY_ON_HANDLER)(error)) break; + const initialInterval = resolvedRetryPolicy.initialInterval ?? 500; + const interval = Math.min(resolvedRetryPolicy.maxInterval ?? 128e3, initialInterval * (resolvedRetryPolicy.backoffFactor ?? 2) ** (attempts - 1)); + const sleepMs = resolvedRetryPolicy.jitter ?? true ? interval + Math.random() * 1e3 : interval; + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + const errorName = error.name ?? error.constructor.unminifiable_name ?? error.constructor.name; + if (resolvedRetryPolicy?.logWarning ?? true) console.log(`Retrying task "${String(pregelTask.name)}" after ${sleepMs.toFixed(2)}ms (attempt ${attempts}) after ${errorName}: ${error}`); + config = patchConfigurable(config, { [CONFIG_KEY_RESUMING]: true }); + if (config.executionInfo != null) config.executionInfo = { + ...config.executionInfo, + nodeAttempt: attempts + 1, + nodeFirstAttemptTime: firstAttemptTime + }; + } + } + return { + task: pregelTask, + result, + error, + signalAborted: signal?.aborted + }; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/runner.js +var PROMISE_ADDED_SYMBOL = Symbol.for("promiseAdded"); +function createPromiseBarrier() { + const barrier = { + next: () => void 0, + wait: Promise.resolve(PROMISE_ADDED_SYMBOL) + }; + function waitHandler(resolve) { + barrier.next = () => { + barrier.wait = new Promise(waitHandler); + resolve(PROMISE_ADDED_SYMBOL); + }; + } + barrier.wait = new Promise(waitHandler); + return barrier; +} +/** +* Responsible for handling task execution on each tick of the {@link PregelLoop}. +*/ +var PregelRunner = class { + nodeFinished; + loop; + /** + * Exceptions already routed to a node-level error handler. Consulted when + * deciding whether a failed task should abort the run. + */ + handledExceptions = /* @__PURE__ */ new WeakSet(); + /** + * Construct a new PregelRunner, which executes tasks from the provided PregelLoop. + * @param loop - The PregelLoop that produces tasks for this runner to execute. + */ + constructor({ loop, nodeFinished }) { + this.loop = loop; + this.nodeFinished = nodeFinished; + } + /** + * Execute tasks from the current step of the PregelLoop. + * + * Note: this method does NOT call {@link PregelLoop}#tick. That must be handled externally. + * @param options - Options for the execution. + */ + async tick(options = {}) { + const { timeout, retryPolicy, onStepWrite, maxConcurrency } = options; + const nodeErrors = /* @__PURE__ */ new Set(); + let graphBubbleUp; + const exceptionSignalController = new AbortController(); + const exceptionSignal = exceptionSignalController.signal; + const stepTimeoutSignal = timeout ? AbortSignal.timeout(timeout) : void 0; + const allTasks = Object.values(this.loop.tasks); + const pendingTasks = allTasks.filter((t) => t.writes.length === 0); + const { signals, disposeCombinedSignal } = this._initializeAbortSignals({ + exceptionSignal, + stepTimeoutSignal, + signal: options.signal + }); + const taskStream = this._executeTasksWithRetry(pendingTasks, { + signals, + retryPolicy, + maxConcurrency + }); + for await (const { task, error, signalAborted } of taskStream) { + this._commit(task, error); + if (error !== void 0 && this.handledExceptions.has(error)) continue; + if (isGraphInterrupt(error)) graphBubbleUp = error; + else if (isGraphBubbleUp(error) && !isGraphInterrupt(graphBubbleUp)) graphBubbleUp = error; + else if (error && (nodeErrors.size === 0 || !signalAborted)) { + exceptionSignalController.abort(); + nodeErrors.add(error); + } + } + disposeCombinedSignal?.(); + onStepWrite?.(this.loop.step, allTasks.map((task) => task.writes).flat()); + if (nodeErrors.size === 1) throw Array.from(nodeErrors)[0]; + else if (nodeErrors.size > 1) throw new AggregateError(Array.from(nodeErrors), `Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`); + if (isGraphInterrupt(graphBubbleUp)) throw graphBubbleUp; + if (isGraphDrained(graphBubbleUp)) throw graphBubbleUp; + if (isGraphBubbleUp(graphBubbleUp) && this.loop.isNested) throw graphBubbleUp; + } + /** + * Initializes the current AbortSignals for the PregelRunner, handling the various ways that + * AbortSignals must be chained together so that the PregelLoop can be interrupted if necessary + * while still allowing nodes to gracefully exit. + * + * This method must only be called once per PregelRunner#tick. It has the side effect of updating + * the PregelLoop#config with the new AbortSignals so they may be propagated correctly to future + * ticks and subgraph calls. + * + * @param options - Options for the initialization. + * @returns The current abort signals. + * @internal + */ + _initializeAbortSignals({ exceptionSignal, stepTimeoutSignal, signal }) { + const previousSignals = this.loop.config.configurable?.["__pregel_abort_signals"] ?? {}; + const externalAbortSignal = previousSignals.externalAbortSignal ?? signal; + const timeoutAbortSignal = stepTimeoutSignal ?? previousSignals.timeoutAbortSignal; + const { signal: composedAbortSignal, dispose: disposeCombinedSignal } = combineAbortSignals(externalAbortSignal, timeoutAbortSignal, exceptionSignal); + const signals = { + externalAbortSignal, + timeoutAbortSignal, + composedAbortSignal + }; + this.loop.config = patchConfigurable(this.loop.config, { [CONFIG_KEY_ABORT_SIGNALS]: signals }); + return { + signals, + disposeCombinedSignal + }; + } + /** + * Concurrently executes tasks with the requested retry policy, yielding a {@link SettledPregelTask} for each task as it completes. + * @param tasks - The tasks to execute. + * @param options - Options for the execution. + */ + async *_executeTasksWithRetry(tasks, options) { + const { retryPolicy, maxConcurrency, signals } = options ?? {}; + const barrier = createPromiseBarrier(); + const executingTasksMap = {}; + const thisCall = { + executingTasksMap, + barrier, + retryPolicy, + scheduleTask: async (task, writeIdx, call) => this.loop.acceptPush(task, writeIdx, call) + }; + if (signals?.composedAbortSignal?.aborted) throw new Error("Abort"); + let startedTasksCount = 0; + let listener; + const timeoutOrCancelSignal = combineAbortSignals(signals?.externalAbortSignal, signals?.timeoutAbortSignal); + const abortPromise = timeoutOrCancelSignal.signal ? new Promise((_resolve, reject) => { + listener = () => reject(/* @__PURE__ */ new Error("Abort")); + timeoutOrCancelSignal.signal?.addEventListener("abort", listener, { once: true }); + }) : void 0; + while ((startedTasksCount === 0 || Object.keys(executingTasksMap).length > 0) && tasks.length) { + for (; Object.values(executingTasksMap).length < (maxConcurrency ?? tasks.length) && startedTasksCount < tasks.length; startedTasksCount += 1) { + const task = tasks[startedTasksCount]; + executingTasksMap[task.id] = _runWithRetry(task, retryPolicy, { [CONFIG_KEY_CALL]: call?.bind(thisCall, this, task) }, signals?.composedAbortSignal).catch((error) => { + return { + task, + error, + signalAborted: signals?.composedAbortSignal?.aborted + }; + }); + } + const settledTask = await Promise.race([ + ...Object.values(executingTasksMap), + ...abortPromise ? [abortPromise] : [], + barrier.wait + ]); + if (settledTask === PROMISE_ADDED_SYMBOL) continue; + const settled = settledTask; + const { task: settledPregelTask, error: settledError } = settled; + if (settledError !== void 0 && !isGraphBubbleUp(settledError) && !this.loop.isErrorHandlerNode(String(settledPregelTask.name)) && this.loop.getErrorHandlerNode(String(settledPregelTask.name)) !== void 0) { + const handlerTask = this.loop.scheduleErrorHandler(settledPregelTask, settledError); + if (handlerTask !== void 0) { + executingTasksMap[handlerTask.id] = _runWithRetry(handlerTask, retryPolicy, { [CONFIG_KEY_CALL]: call?.bind(thisCall, this, handlerTask) }, signals?.composedAbortSignal).catch((error) => { + return { + task: handlerTask, + error, + signalAborted: signals?.composedAbortSignal?.aborted + }; + }); + barrier.next(); + } + } + yield settled; + if (listener != null) { + timeoutOrCancelSignal.signal?.removeEventListener("abort", listener); + timeoutOrCancelSignal.dispose?.(); + } + delete executingTasksMap[settledTask.task.id]; + } + } + /** + * Whether a failed task should record {@link ERROR_SOURCE_NODE} provenance. + */ + _shouldRouteToErrorHandler(task) { + const name = String(task.name); + if (this.loop.isErrorHandlerNode(name)) return false; + return this.loop.getErrorHandlerNode(name) !== void 0; + } + /** + * Determines what writes to apply based on whether the task completed successfully, and what type of error occurred. + * + * Throws an error if the error is a {@link GraphBubbleUp} error and {@link PregelLoop}#isNested is true. + * + * @param task - The task to commit. + * @param error - The error that occurred, if any. + */ + _commit(task, error) { + if (error !== void 0) if (isGraphInterrupt(error)) { + if (error.interrupts.length) { + const interrupts = error.interrupts.map((interrupt) => [INTERRUPT$1, interrupt]); + const resumes = task.writes.filter((w) => w[0] === RESUME$1); + if (resumes.length) interrupts.push(...resumes); + this.loop.putWrites(task.id, interrupts); + } + } else if (isGraphDrained(error)) { + if (task.writes.length) this.loop.putWrites(task.id, task.writes); + } else if (isGraphBubbleUp(error) && task.writes.length) this.loop.putWrites(task.id, task.writes); + else { + task.writes.push([ERROR$1, { + message: error.message, + name: error.name + }]); + if (this._shouldRouteToErrorHandler(task)) { + task.writes.push([ERROR_SOURCE_NODE, String(task.name)]); + this.handledExceptions.add(error); + } + this.loop.putWrites(task.id, task.writes); + } + else { + if (this.nodeFinished && (task.config?.tags == null || !task.config.tags.includes("langsmith:hidden"))) this.nodeFinished(String(task.name)); + if (task.writes.length === 0) task.writes.push([NO_WRITES, null]); + this.loop.putWrites(task.id, task.writes); + } + } +}; +async function call(runner, task, func, name, input, options = {}) { + const scratchpad = task.config?.configurable?.[CONFIG_KEY_SCRATCHPAD]; + if (!scratchpad) throw new Error(`BUG: No scratchpad found on task ${task.name}__${task.id}`); + const cnt = scratchpad.callCounter; + scratchpad.callCounter += 1; + const wcall = new Call({ + func, + name, + input, + cache: options.cache, + retry: options.retry, + timeout: options.timeout, + callbacks: options.callbacks + }); + const nextTask = await this.scheduleTask(task, cnt, wcall); + if (!nextTask) return void 0; + const existingPromise = this.executingTasksMap[nextTask.id]; + if (existingPromise !== void 0) return existingPromise; + if (nextTask.writes.length > 0) { + const returns = nextTask.writes.filter(([c]) => c === RETURN); + const errors = nextTask.writes.filter(([c]) => c === ERROR$1); + if (returns.length > 0) { + if (returns.length === 1) return Promise.resolve(returns[0][1]); + throw new Error(`BUG: multiple returns found for task ${nextTask.name}__${nextTask.id}`); + } + if (errors.length > 0) { + if (errors.length === 1) { + const errorValue = errors[0][1]; + const error = errorValue instanceof Error ? errorValue : new Error(String(errorValue)); + return Promise.reject(error); + } + throw new Error(`BUG: multiple errors found for task ${nextTask.name}__${nextTask.id}`); + } + return; + } else { + const prom = _runWithRetry(nextTask, options.retry, { [CONFIG_KEY_CALL]: call.bind(this, runner, nextTask) }); + this.executingTasksMap[nextTask.id] = prom; + this.barrier.next(); + return prom.then(({ result, error }) => { + if (error) return Promise.reject(error); + return result; + }); + } +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/validate.js +var GraphValidationError = class extends Error { + constructor(message) { + super(message); + this.name = "GraphValidationError"; + } +}; +function validateGraph({ nodes, channels, inputChannels, outputChannels, streamChannels, interruptAfterNodes, interruptBeforeNodes }) { + if (!channels) throw new GraphValidationError("Channels not provided"); + const subscribedChannels = /* @__PURE__ */ new Set(); + const allOutputChannels = /* @__PURE__ */ new Set(); + for (const [name, node] of Object.entries(nodes)) { + if (name === "__interrupt__") throw new GraphValidationError(`"Node name ${INTERRUPT$1} is reserved"`); + if (node.constructor === PregelNode) node.triggers.forEach((trigger) => subscribedChannels.add(trigger)); + else throw new GraphValidationError(`Invalid node type ${typeof node}, expected PregelNode`); + } + for (const chan of subscribedChannels) if (!(chan in channels)) throw new GraphValidationError(`Subscribed channel '${String(chan)}' not in channels`); + if (!Array.isArray(inputChannels)) { + if (!subscribedChannels.has(inputChannels)) throw new GraphValidationError(`Input channel ${String(inputChannels)} is not subscribed to by any node`); + } else if (inputChannels.every((channel) => !subscribedChannels.has(channel))) throw new GraphValidationError(`None of the input channels ${inputChannels} are subscribed to by any node`); + if (!Array.isArray(outputChannels)) allOutputChannels.add(outputChannels); + else outputChannels.forEach((chan) => allOutputChannels.add(chan)); + if (streamChannels && !Array.isArray(streamChannels)) allOutputChannels.add(streamChannels); + else if (Array.isArray(streamChannels)) streamChannels.forEach((chan) => allOutputChannels.add(chan)); + for (const chan of allOutputChannels) if (!(chan in channels)) throw new GraphValidationError(`Output channel '${String(chan)}' not in channels`); + if (interruptAfterNodes && interruptAfterNodes !== "*") { + for (const node of interruptAfterNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`); + } + if (interruptBeforeNodes && interruptBeforeNodes !== "*") { + for (const node of interruptBeforeNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`); + } +} +function validateKeys(keys, channels) { + if (Array.isArray(keys)) { + for (const key of keys) if (!(key in channels)) throw new Error(`Key ${String(key)} not found in channels`); + } else if (!(keys in channels)) throw new Error(`Key ${String(keys)} not found in channels`); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/channels/topic.js +/** +* A configurable PubSub Topic. +*/ +var Topic = class Topic extends BaseChannel { + lc_graph_name = "Topic"; + unique = false; + accumulate = false; + seen; + values; + constructor(fields) { + super(); + this.unique = fields?.unique ?? this.unique; + this.accumulate = fields?.accumulate ?? this.accumulate; + this.seen = /* @__PURE__ */ new Set(); + this.values = []; + } + fromCheckpoint(checkpoint) { + const empty = new Topic({ + unique: this.unique, + accumulate: this.accumulate + }); + if (typeof checkpoint !== "undefined") { + empty.seen = new Set(checkpoint[0]); + empty.values = checkpoint[1]; + } + return empty; + } + update(values) { + let updated = false; + if (!this.accumulate) { + updated = this.values.length > 0; + this.values = []; + } + const flatValues = values.flat(); + if (flatValues.length > 0) if (this.unique) { + for (const value of flatValues) if (!this.seen.has(value)) { + updated = true; + this.seen.add(value); + this.values.push(value); + } + } else { + updated = true; + this.values.push(...flatValues); + } + return updated; + } + get() { + if (this.values.length === 0) throw new EmptyChannelError(); + return this.values; + } + checkpoint() { + return [[...this.seen], this.values]; + } + isAvailable() { + return this.values.length !== 0; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/pregel/index.js +function protocolEventsToEventStream(run) { + const encoder = new TextEncoder(); + return new ReadableStream({ async start(controller) { + try { + for await (const event of run) { + const namespace = event.params.namespace; + const eventName = namespace.length ? `${event.method}|${namespace.join("|")}` : event.method; + controller.enqueue(encoder.encode(`event: ${eventName}\ndata: ${JSON.stringify(event.params.data ?? {})}\n\n`)); + } + } catch (error) { + controller.enqueue(encoder.encode(`event: error\ndata: ${JSON.stringify({ message: String(error) })}\n\n`)); + } finally { + controller.close(); + } + } }); +} +/** +* Utility class for working with channels in the Pregel system. +* Provides static methods for subscribing to channels and writing to them. +* +* Channels are the communication pathways between nodes in a Pregel graph. +* They enable message passing and state updates between different parts of the graph. +*/ +var Channel = class { + static subscribeTo(channels, options) { + const { key, tags } = { + key: void 0, + tags: void 0, + ...options ?? {} + }; + if (Array.isArray(channels) && key !== void 0) throw new Error("Can't specify a key when subscribing to multiple channels"); + let channelMappingOrArray; + if (typeof channels === "string") if (key) channelMappingOrArray = { [key]: channels }; + else channelMappingOrArray = [channels]; + else channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan])); + return new PregelNode({ + channels: channelMappingOrArray, + triggers: Array.isArray(channels) ? channels : [channels], + tags + }); + } + /** + * Creates a ChannelWrite that specifies how to write values to channels. + * This is used to define how nodes send output to channels. + * + * @example + * ```typescript + * // Write to multiple channels + * const write = Channel.writeTo(["output", "state"]); + * + * // Write with specific values + * const write = Channel.writeTo(["output"], { + * state: "completed", + * result: calculateResult() + * }); + * + * // Write with a transformation function + * const write = Channel.writeTo(["output"], { + * result: (x) => processResult(x) + * }); + * ``` + * + * @param channels - Array of channel names to write to + * @param writes - Optional map of channel names to values or transformations + * @returns A ChannelWrite object that can be used to write to the specified channels + */ + static writeTo(channels, writes) { + const channelWriteEntries = []; + for (const channel of channels) channelWriteEntries.push({ + channel, + value: PASSTHROUGH, + skipNone: false + }); + for (const [key, value] of Object.entries(writes ?? {})) if (Runnable.isRunnable(value) || typeof value === "function") channelWriteEntries.push({ + channel: key, + value: PASSTHROUGH, + skipNone: true, + mapper: _coerceToRunnable(value) + }); + else channelWriteEntries.push({ + channel: key, + value, + skipNone: false + }); + return new ChannelWrite(channelWriteEntries); + } +}; +var PartialRunnable = class extends Runnable { + lc_namespace = ["langgraph", "pregel"]; + invoke(_input, _options) { + throw new Error("Not implemented"); + } + withConfig(_config) { + return super.withConfig(_config); + } + stream(input, options) { + return super.stream(input, options); + } +}; +/** +* The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model +* inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/). +* It provides the foundation for building reliable, controllable agent workflows that can evolve state over time. +* +* Key features: +* - Message passing between nodes in discrete "supersteps" +* - Built-in persistence layer through checkpointers +* - First-class streaming support for values, updates, and events +* - Human-in-the-loop capabilities via interrupts +* - Support for parallel node execution within supersteps +* +* The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs: +* - {@link StateGraph}: The main graph class for building agent workflows +* - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel` +* - Functional API: A declarative approach using tasks and entrypoints +* - A `Pregel` instance is returned by the {@link entrypoint} function +* +* @example +* ```typescript +* // Using StateGraph API +* const graph = new StateGraph(annotation) +* .addNode("nodeA", myNodeFunction) +* .addEdge("nodeA", "nodeB") +* .compile(); +* +* // The compiled graph is a Pregel instance +* const result = await graph.invoke(input); +* ``` +* +* @example +* ```typescript +* // Using Functional API +* import { task, entrypoint } from "@langchain/langgraph"; +* import { MemorySaver } from "@langchain/langgraph-checkpoint"; +* +* // Define tasks that can be composed +* const addOne = task("add", async (x: number) => x + 1); +* +* // Create a workflow using the entrypoint function +* const workflow = entrypoint({ +* name: "workflow", +* checkpointer: new MemorySaver() +* }, async (numbers: number[]) => { +* // Tasks can be run in parallel +* const results = await Promise.all(numbers.map(n => addOne(n))); +* return results; +* }); +* +* // The workflow is a Pregel instance +* const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4] +* ``` +* +* @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations +* @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations +* @typeParam ContextType - Type of context that can be passed to the graph +* @typeParam InputType - Type of input values accepted by the graph +* @typeParam OutputType - Type of output values produced by the graph +*/ +var Pregel = class extends PartialRunnable { + /** + * Name of the class when serialized + * @internal + */ + static lc_name() { + return "LangGraph"; + } + /** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */ + lc_namespace = ["langgraph", "pregel"]; + /** @internal Flag indicating this is a Pregel instance - necessary for serialization */ + lg_is_pregel = true; + /** The nodes in the graph, mapping node names to their PregelNode instances */ + nodes; + /** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */ + channels; + /** + * The input channels for the graph. These channels receive the initial input when the graph is invoked. + * Can be a single channel key or an array of channel keys. + */ + inputChannels; + /** + * The output channels for the graph. These channels contain the final output when the graph completes. + * Can be a single channel key or an array of channel keys. + */ + outputChannels; + /** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */ + autoValidate = true; + /** + * The streaming modes enabled for this graph. Defaults to ["values"]. + * Supported modes: + * - "values": Streams the full state after each step + * - "updates": Streams state updates after each step + * - "messages": Streams messages from within nodes + * - "custom": Streams custom events from within nodes + * - "tools": Streams tool-call lifecycle events (on_tool_start, on_tool_event, on_tool_end, on_tool_error) from LLM tool execution + * - "debug": Streams events related to the execution of the graph - useful for tracing & debugging graph execution + */ + streamMode = ["values"]; + /** + * Optional channels to stream. If not specified, all channels will be streamed. + * Can be a single channel key or an array of channel keys. + */ + streamChannels; + /** + * Optional array of node names or "all" to interrupt after executing these nodes. + * Used for implementing human-in-the-loop workflows. + */ + interruptAfter; + /** + * Optional array of node names or "all" to interrupt before executing these nodes. + * Used for implementing human-in-the-loop workflows. + */ + interruptBefore; + /** Optional timeout in milliseconds for the execution of each superstep */ + stepTimeout; + /** Whether to enable debug logging. Defaults to false. */ + debug = false; + /** + * Optional checkpointer for persisting graph state. + * When provided, saves a checkpoint of the graph state at every superstep. + * When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state. + */ + checkpointer; + /** Optional retry policy for handling failures in node execution */ + retryPolicy; + /** The default configuration for graph execution, can be overridden on a per-invocation basis */ + config; + /** + * Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads + */ + store; + /** + * Optional cache for the graph, useful for caching tasks. + */ + cache; + /** + * Optional interrupt helper function. + * @internal + */ + userInterrupt; + /** + * Stream reducer factories registered at compile time. These run + * automatically for every `streamEvents(..., { version: "v3" })` call, + * before any call-site transformers. + */ + streamTransformers; + /** + * The trigger to node mapping for the graph run. + * @internal + */ + triggerToNodes = {}; + /** + * Constructor for Pregel - meant for internal use only. + * + * @internal + */ + constructor(fields) { + super(fields); + let { streamMode } = fields; + if (streamMode != null && !Array.isArray(streamMode)) streamMode = [streamMode]; + this.nodes = fields.nodes; + this.channels = fields.channels; + if ("__pregel_tasks" in this.channels && "lc_graph_name" in this.channels["__pregel_tasks"] && this.channels["__pregel_tasks"].lc_graph_name !== "Topic") throw new Error(`Channel '${TASKS}' is reserved and cannot be used in the graph.`); + else this.channels[TASKS] = new Topic({ accumulate: false }); + this.autoValidate = fields.autoValidate ?? this.autoValidate; + this.streamMode = streamMode ?? this.streamMode; + this.inputChannels = fields.inputChannels; + this.outputChannels = fields.outputChannels; + this.streamChannels = fields.streamChannels ?? this.streamChannels; + this.interruptAfter = fields.interruptAfter; + this.interruptBefore = fields.interruptBefore; + this.stepTimeout = fields.stepTimeout ?? this.stepTimeout; + this.debug = fields.debug ?? this.debug; + this.checkpointer = fields.checkpointer; + this.retryPolicy = fields.retryPolicy; + this.config = fields.config; + this.store = fields.store; + this.cache = fields.cache; + this.name = fields.name; + this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes; + this.userInterrupt = fields.userInterrupt; + this.streamTransformers = fields.streamTransformers ?? []; + if (this.autoValidate) this.validate(); + } + withConfig(config) { + const { streamTransformers, ...restConfig } = config; + const mergedConfig = mergeConfigs(this.config, restConfig); + const mergedStreamTransformers = [...this.streamTransformers, ...streamTransformers ?? []]; + return new this.constructor({ + ...this, + config: mergedConfig, + streamTransformers: mergedStreamTransformers + }); + } + /** + * Validates the graph structure to ensure it is well-formed. + * Checks for: + * - No orphaned nodes + * - Valid input/output channel configurations + * - Valid interrupt configurations + * + * @returns this - The Pregel instance for method chaining + * @throws {GraphValidationError} If the graph structure is invalid + */ + validate() { + validateGraph({ + nodes: this.nodes, + channels: this.channels, + outputChannels: this.outputChannels, + inputChannels: this.inputChannels, + streamChannels: this.streamChannels, + interruptAfterNodes: this.interruptAfter, + interruptBeforeNodes: this.interruptBefore + }); + for (const [name, node] of Object.entries(this.nodes)) for (const trigger of node.triggers) { + this.triggerToNodes[trigger] ??= []; + this.triggerToNodes[trigger].push(name); + } + return this; + } + /** + * Gets a list of all channels that should be streamed. + * If streamChannels is specified, returns those channels. + * Otherwise, returns all channels in the graph. + * + * @returns Array of channel keys to stream + */ + get streamChannelsList() { + if (Array.isArray(this.streamChannels)) return this.streamChannels; + else if (this.streamChannels) return [this.streamChannels]; + else return Object.keys(this.channels); + } + /** + * Gets the channels to stream in their original format. + * If streamChannels is specified, returns it as-is (either single key or array). + * Otherwise, returns all channels in the graph as an array. + * + * @returns Channel keys to stream, either as a single key or array + */ + get streamChannelsAsIs() { + if (this.streamChannels) return this.streamChannels; + else return Object.keys(this.channels); + } + /** + * Gets a drawable representation of the graph structure. + * This is an async version of getGraph() and is the preferred method to use. + * + * @param config - Configuration for generating the graph visualization + * @returns A representation of the graph that can be visualized + */ + async getGraphAsync(config) { + return this.getGraph(config); + } + /** + * Gets all subgraphs within this graph. + * A subgraph is a Pregel instance that is nested within a node of this graph. + * + * @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release. + * @param namespace - Optional namespace to filter subgraphs + * @param recurse - Whether to recursively get subgraphs of subgraphs + * @returns Generator yielding tuples of [name, subgraph] + */ + *getSubgraphs(namespace, recurse) { + for (const [name, node] of Object.entries(this.nodes)) { + if (namespace !== void 0) { + if (!namespace.startsWith(name)) continue; + } + const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound]; + for (const candidate of candidates) { + const graph = findSubgraphPregel(candidate); + if (graph !== void 0) { + if (name === namespace) { + yield [name, graph]; + return; + } + if (namespace === void 0) yield [name, graph]; + if (recurse) { + let newNamespace = namespace; + if (namespace !== void 0) newNamespace = namespace.slice(name.length + 1); + for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) yield [`${name}|${subgraphName}`, subgraph]; + } + } + } + } + } + /** + * Gets all subgraphs within this graph asynchronously. + * A subgraph is a Pregel instance that is nested within a node of this graph. + * + * @param namespace - Optional namespace to filter subgraphs + * @param recurse - Whether to recursively get subgraphs of subgraphs + * @returns AsyncGenerator yielding tuples of [name, subgraph] + */ + async *getSubgraphsAsync(namespace, recurse) { + yield* this.getSubgraphs(namespace, recurse); + } + /** + * Prepares a state snapshot from saved checkpoint data. + * This is an internal method used by getState and getStateHistory. + * + * @param config - Configuration for preparing the snapshot + * @param saved - Optional saved checkpoint data + * @param subgraphCheckpointer - Optional checkpointer for subgraphs + * @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels + * @returns A snapshot of the graph state + * @internal + */ + async _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false }) { + if (saved === void 0) return { + values: {}, + next: [], + config, + tasks: [] + }; + const channels = await channelsFromCheckpoint(this.channels, saved.checkpoint, { + saver: typeof this.checkpointer === "object" ? this.checkpointer : void 0, + config: saved.config ?? config + }); + if (saved.pendingWrites?.length) { + const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]); + if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], void 0, this.triggerToNodes); + } + const nextTasks = Object.values(_prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { + step: (saved.metadata?.step ?? -1) + 1, + store: this.store + })); + const subgraphs = await gatherIterator(this.getSubgraphsAsync()); + const parentNamespace = saved.config.configurable?.checkpoint_ns ?? ""; + const taskStates = {}; + for (const task of nextTasks) { + const matchingSubgraph = subgraphs.find(([name]) => name === task.name); + if (!matchingSubgraph) continue; + let taskNs = `${String(task.name)}:${task.id}`; + if (parentNamespace) taskNs = `${parentNamespace}|${taskNs}`; + if (subgraphCheckpointer === void 0) { + const config = { configurable: { + thread_id: saved.config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + taskStates[task.id] = config; + } else { + const subgraphConfig = { configurable: { + [CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer, + thread_id: saved.config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + const pregel = matchingSubgraph[1]; + taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true }); + } + } + if (applyPendingWrites && saved.pendingWrites?.length) { + const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task])); + for (const [taskId, channel, value] of saved.pendingWrites) { + if ([ + "__error__", + "__interrupt__", + "__scheduled__" + ].includes(channel)) continue; + if (!(taskId in nextTaskById)) continue; + nextTaskById[taskId].writes.push([String(channel), value]); + } + const tasksWithWrites = nextTasks.filter((task) => task.writes.length > 0); + if (tasksWithWrites.length > 0) _applyWrites(saved.checkpoint, channels, tasksWithWrites, void 0, this.triggerToNodes); + } + let metadata = saved?.metadata; + if (metadata && saved?.config?.configurable?.thread_id) metadata = { + ...metadata, + thread_id: saved.config.configurable.thread_id + }; + const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name); + return { + values: readChannels(channels, this.streamChannelsAsIs), + next: nextList, + tasks: tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs), + metadata, + config: patchCheckpointMap(saved.config, saved.metadata), + createdAt: saved.checkpoint.ts, + parentConfig: saved.parentConfig + }; + } + /** + * Gets the current state of the graph. + * Requires a checkpointer to be configured. + * + * @param config - Configuration for retrieving the state + * @param options - Additional options + * @returns A snapshot of the current graph state + * @throws {GraphValueError} If no checkpointer is configured + */ + async getState(config, options) { + const checkpointer = config.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; + if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && config.configurable?.["__pregel_read"] === void 0 && config.configurable?.["__pregel_checkpointer"] === void 0) { + const recastNamespace = recastCheckpointNamespace(checkpointNamespace); + for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) return await subgraph.getState(patchConfigurable$1(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs }); + } + const mergedConfig = mergeConfigs(this.config, config); + const saved = await checkpointer.getTuple(config); + return await this._prepareStateSnapshot({ + config: mergedConfig, + saved, + subgraphCheckpointer: options?.subgraphs ? checkpointer : void 0, + applyPendingWrites: !config.configurable?.checkpoint_id + }); + } + /** + * Gets the history of graph states. + * Requires a checkpointer to be configured. + * Useful for: + * - Debugging execution history + * - Implementing time travel + * - Analyzing graph behavior + * + * @param config - Configuration for retrieving the history + * @param options - Options for filtering the history + * @returns An async iterator of state snapshots + * @throws {Error} If no checkpointer is configured + */ + async *getStateHistory(config, options) { + const checkpointer = config.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; + if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && config.configurable?.["__pregel_checkpointer"] === void 0) { + const recastNamespace = recastCheckpointNamespace(checkpointNamespace); + for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) { + yield* pregel.getStateHistory(patchConfigurable$1(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), options); + return; + } + } + const mergedConfig = mergeConfigs(this.config, config, { configurable: { checkpoint_ns: checkpointNamespace } }); + for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) yield this._prepareStateSnapshot({ + config: checkpointTuple.config, + saved: checkpointTuple + }); + } + /** + * Apply updates to the graph state in bulk. + * Requires a checkpointer to be configured. + * + * This method is useful for recreating a thread + * from a list of updates, especially if a checkpoint + * is created as a result of multiple tasks. + * + * @internal The API might change in the future. + * + * @param startConfig - Configuration for the update + * @param updates - The list of updates to apply to graph state + * @returns Updated configuration + * @throws {GraphValueError} If no checkpointer is configured + * @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence. + */ + async bulkUpdateState(startConfig, supersteps) { + const checkpointer = startConfig.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; + if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + if (supersteps.length === 0) throw new Error("No supersteps provided"); + if (supersteps.some((s) => s.updates.length === 0)) throw new Error("No updates provided"); + const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && startConfig.configurable?.["__pregel_checkpointer"] === void 0) { + const recastNamespace = recastCheckpointNamespace(checkpointNamespace); + for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) return await pregel.bulkUpdateState(patchConfigurable$1(startConfig, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps); + throw new Error(`Subgraph "${recastNamespace}" not found`); + } + const updateSuperStep = async (inputConfig, updates) => { + const config = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig; + const saved = await checkpointer.getTuple(config); + const checkpoint = saved !== void 0 ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint(); + const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions }; + const step = saved?.metadata?.step ?? -1; + let checkpointConfig = patchConfigurable$1(config, { checkpoint_ns: config.configurable?.checkpoint_ns ?? "" }); + let checkpointMetadata = config.metadata ?? {}; + if (saved?.config.configurable) { + checkpointConfig = patchConfigurable$1(config, saved.config.configurable); + checkpointMetadata = { + ...saved.metadata, + ...checkpointMetadata + }; + } + const { values, asNode } = updates[0]; + if (values == null && asNode === void 0) { + if (updates.length > 1) throw new InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`); + return patchCheckpointMap(await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, void 0, step), { + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, {}), saved ? saved.metadata : void 0); + } + const channels = await channelsFromCheckpoint(this.channels, checkpoint, { + saver: checkpointer, + config: saved?.config ?? checkpointConfig + }); + if (values === null && asNode === "__end__") { + if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when clearing state`); + if (saved) { + const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, { + step: (saved.metadata?.step ?? -1) + 1, + checkpointer, + store: this.store + }); + const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); + if (nullWrites.length > 0) _applyWrites(checkpoint, channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); + for (const [taskId, k, v] of saved.pendingWrites || []) { + if ([ + "__error__", + "__interrupt__", + "__scheduled__" + ].includes(k)) continue; + if (!(taskId in nextTasks)) continue; + nextTasks[taskId].writes.push([k, v]); + } + _applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); + } + return patchCheckpointMap(await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step), { + ...checkpointMetadata, + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)), saved ? saved.metadata : void 0); + } + if (asNode === "__copy__") { + if (updates.length > 1) throw new InvalidUpdateError(`Cannot copy checkpoint with multiple updates`); + if (saved == null) throw new InvalidUpdateError(`Cannot copy a non-existent checkpoint`); + const isCopyWithUpdates = (values) => { + if (!Array.isArray(values)) return false; + if (values.length === 0) return false; + return values.every((v) => Array.isArray(v) && v.length === 2); + }; + const nextCheckpoint = createCheckpoint(checkpoint, void 0, step); + const nextConfig = await checkpointer.put(saved.parentConfig ?? patchConfigurable$1(saved.config, { checkpoint_id: void 0 }), nextCheckpoint, { + source: "fork", + step: step + 1, + parents: saved.metadata?.parents ?? {} + }, {}); + if (isCopyWithUpdates(values)) { + const nextTasks = _prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig, false, { step: step + 2 }); + const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => { + acc[name] ??= []; + acc[name].push({ id }); + return acc; + }, {}); + const userGroupBy = values.reduce((acc, item) => { + const [values, asNode] = item; + acc[asNode] ??= []; + const targetIdx = acc[asNode].length; + const taskId = tasksGroupBy[asNode]?.[targetIdx]?.id; + acc[asNode].push({ + values, + asNode, + taskId + }); + return acc; + }, {}); + return updateSuperStep(patchCheckpointMap(nextConfig, saved.metadata), Object.values(userGroupBy).flat()); + } + return patchCheckpointMap(nextConfig, saved.metadata); + } + if (asNode === "__input__") { + if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when updating as input`); + const inputWrites = await gatherIterator(mapInput(this.inputChannels, values)); + if (inputWrites.length === 0) throw new InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`); + _applyWrites(checkpoint, channels, [{ + name: INPUT, + writes: inputWrites, + triggers: [] + }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); + const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1; + const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, nextStep), { + source: "input", + step: nextStep, + parents: saved?.metadata?.parents ?? {} + }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)); + await checkpointer.putWrites(nextConfig, inputWrites, uuid5(INPUT, checkpoint.id)); + return patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0); + } + if (config.configurable?.checkpoint_id === void 0 && saved?.pendingWrites !== void 0 && saved.pendingWrites.length > 0) { + const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { + store: this.store, + checkpointer: this.checkpointer, + step: (saved.metadata?.step ?? -1) + 1 + }); + const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); + if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], void 0, this.triggerToNodes); + for (const [tid, k, v] of saved.pendingWrites) { + if ([ + "__error__", + "__interrupt__", + "__scheduled__" + ].includes(k) || nextTasks[tid] === void 0) continue; + nextTasks[tid].writes.push([k, v]); + } + const tasks = Object.values(nextTasks).filter((task) => { + return task.writes.length > 0; + }); + if (tasks.length > 0) _applyWrites(checkpoint, channels, tasks, void 0, this.triggerToNodes); + } + const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => { + return Object.values(seenVersions); + }).flat().find((v) => !!v); + const validUpdates = []; + if (updates.length === 1) { + let { values, asNode, taskId } = updates[0]; + if (asNode === void 0 && Object.keys(this.nodes).length === 1) [asNode] = Object.keys(this.nodes); + else if (asNode === void 0 && nonNullVersion === void 0) { + if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== void 0) asNode = this.inputChannels; + } else if (asNode === void 0) { + const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n, seen]) => { + return Object.values(seen).map((v) => { + return [v, n]; + }); + }).flat().filter(([_, v]) => v !== INTERRUPT$1).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber)); + if (lastSeenByNode) { + if (lastSeenByNode.length === 1) asNode = lastSeenByNode[0][1]; + else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) asNode = lastSeenByNode[lastSeenByNode.length - 1][1]; + } + } + if (asNode === void 0) throw new InvalidUpdateError(`Ambiguous update, specify "asNode"`); + validUpdates.push({ + values, + asNode, + taskId + }); + } else for (const { asNode, values, taskId } of updates) { + if (asNode == null) throw new InvalidUpdateError(`"asNode" is required when applying multiple updates`); + validUpdates.push({ + values, + asNode, + taskId + }); + } + const tasks = []; + for (const { asNode, values, taskId } of validUpdates) { + if (this.nodes[asNode] === void 0) throw new InvalidUpdateError(`Node "${asNode.toString()}" does not exist`); + const writers = this.nodes[asNode].getWriters(); + if (!writers.length) throw new InvalidUpdateError(`No writers found for node "${asNode.toString()}"`); + tasks.push({ + name: asNode, + input: values, + proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0], + writes: [], + triggers: [INTERRUPT$1], + id: taskId ?? uuid5("__interrupt__", checkpoint.id), + writers: [] + }); + } + for (const task of tasks) await task.proc.invoke(task.input, patchConfig({ + ...config, + store: config?.store ?? this.store + }, { + runName: config.runName ?? `${this.getName()}UpdateState`, + configurable: { + [CONFIG_KEY_SEND]: (items) => task.writes.push(...items), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, task, select_, fresh_) + } + })); + for (const task of tasks) { + const channelWrites = task.writes.filter((w) => w[0] !== PUSH); + if (saved !== void 0 && channelWrites.length > 0) await checkpointer.putWrites(checkpointConfig, channelWrites, task.id); + } + _applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); + const newVersions = getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions); + const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step + 1), { + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, newVersions); + for (const task of tasks) { + const pushWrites = task.writes.filter((w) => w[0] === PUSH); + if (pushWrites.length > 0) await checkpointer.putWrites(nextConfig, pushWrites, task.id); + } + return patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0); + }; + let currentConfig = startConfig; + for (const { updates } of supersteps) currentConfig = await updateSuperStep(currentConfig, updates); + return currentConfig; + } + /** + * Updates the state of the graph with new values. + * Requires a checkpointer to be configured. + * + * This method can be used for: + * - Implementing human-in-the-loop workflows + * - Modifying graph state during breakpoints + * - Integrating external inputs into the graph + * + * @param inputConfig - Configuration for the update + * @param values - The values to update the state with + * @param asNode - Optional node name to attribute the update to + * @returns Updated configuration + * @throws {GraphValueError} If no checkpointer is configured + * @throws {InvalidUpdateError} If the update cannot be attributed to a node + */ + async updateState(inputConfig, values, asNode) { + return this.bulkUpdateState(inputConfig, [{ updates: [{ + values, + asNode + }] }]); + } + /** + * Gets the default values for various graph configuration options. + * This is an internal method used to process and normalize configuration options. + * + * @param config - The input configuration options + * @returns A tuple containing normalized values for: + * - debug mode + * - stream modes + * - input keys + * - output keys + * - remaining config + * - interrupt before nodes + * - interrupt after nodes + * - checkpointer + * - store + * - whether stream mode is single + * - node cache + * - whether checkpoint during is enabled + * @internal + */ + _defaults(config) { + const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore, ...rest } = config; + let streamModeSingle = true; + const defaultDebug = debug !== void 0 ? debug : this.debug; + let defaultOutputKeys = outputKeys; + if (defaultOutputKeys === void 0) defaultOutputKeys = this.streamChannelsAsIs; + else validateKeys(defaultOutputKeys, this.channels); + let defaultInputKeys = inputKeys; + if (defaultInputKeys === void 0) defaultInputKeys = this.inputChannels; + else validateKeys(defaultInputKeys, this.channels); + const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? []; + const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? []; + let defaultStreamMode; + if (streamMode !== void 0) { + defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode]; + streamModeSingle = typeof streamMode === "string"; + } else { + if (config.configurable?.["__pregel_task_id"] !== void 0) defaultStreamMode = ["values"]; + else defaultStreamMode = this.streamMode; + streamModeSingle = true; + } + let defaultCheckpointer; + if (this.checkpointer === false) defaultCheckpointer = void 0; + else if (config !== void 0 && config.configurable?.["__pregel_checkpointer"] !== void 0) defaultCheckpointer = config.configurable[CONFIG_KEY_CHECKPOINTER]; + else if (this.checkpointer === true) throw new Error("checkpointer: true cannot be used for root graphs."); + else defaultCheckpointer = this.checkpointer; + const defaultStore = config.store ?? this.store; + const defaultCache = config.cache ?? this.cache; + if (config.durability != null && config.checkpointDuring != null) throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time."); + const checkpointDuringDurability = (() => { + if (config.checkpointDuring == null) return void 0; + if (config.checkpointDuring === false) return "exit"; + return "async"; + })(); + const defaultDurability = config.durability ?? checkpointDuringDurability ?? config?.configurable?.["__pregel_durability"] ?? "async"; + return [ + defaultDebug, + defaultStreamMode, + defaultInputKeys, + defaultOutputKeys, + rest, + defaultInterruptBefore, + defaultInterruptAfter, + defaultCheckpointer, + defaultStore, + streamModeSingle, + defaultCache, + defaultDurability + ]; + } + /** + * Streams the execution of the graph, emitting state updates as they occur. + * This is the primary method for observing graph execution in real-time. + * + * Stream modes: + * - "values": Emits complete state after each step + * - "updates": Emits only state changes after each step + * - "debug": Emits detailed debug information + * - "messages": Emits messages from within nodes + * - "custom": Emits custom events from within nodes + * - "checkpoints": Emits checkpoints from within nodes + * - "tasks": Emits tasks from within nodes + * + * @param input - The input to start graph execution with + * @param options - Configuration options for streaming + * @returns An async iterable stream of graph state updates + */ + async stream(input, options) { + const abortController = new AbortController(); + const ambientConfigurable = getConfig()?.configurable; + if (ambientConfigurable?.["__pregel_read"] !== void 0 && options?.configurable?.["__pregel_read"] === void 0) options = { + ...options, + configurable: { + ...ambientConfigurable, + ...options?.configurable + } + }; + const config = { + recursionLimit: this.config?.recursionLimit, + ...options, + signal: combineAbortSignals(options?.signal, abortController.signal).signal + }; + const stream = await super.stream(input, config); + return new IterableReadableStreamWithAbortSignal(options?.encoding === "text/event-stream" ? toEventStream(stream) : stream, abortController); + } + async #streamEventsV3(input, options) { + const { version, encoding, transformers: userTransformers, ...restOptions } = options; + const streamOptions = { + recursionLimit: this.config?.recursionLimit, + ...restOptions, + configurable: { + ...this.config?.configurable, + ...restOptions?.configurable + }, + version, + streamMode: STREAM_EVENTS_V3_MODES, + subgraphs: true, + encoding: void 0 + }; + const sourcePromise = this.stream(input, streamOptions); + const graphRun = createGraphRunStream({ [Symbol.asyncIterator]: async function* () { + const src = await sourcePromise; + for await (const chunk of src) yield chunk; + } }, [...this.streamTransformers ?? [], ...userTransformers ?? []]); + if (encoding === "text/event-stream") { + const abortController = new AbortController(); + abortController.signal.addEventListener("abort", () => graphRun.abort(abortController.signal.reason), { once: true }); + return new IterableReadableStreamWithAbortSignal(protocolEventsToEventStream(graphRun), abortController); + } + return graphRun; + } + streamEvents(input, options, streamOptions) { + if (options.version === "v3") return this.#streamEventsV3(input, options); + const abortController = new AbortController(); + const config = { + recursionLimit: this.config?.recursionLimit, + ...options, + signal: combineAbortSignals(options?.signal, abortController.signal).signal + }; + return new IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController); + } + /** + * Validates the input for the graph. + * @param input - The input to validate + * @returns The validated input + * @internal + */ + async _validateInput(input) { + return input; + } + /** + * Validates the context options for the graph. + * @param context - The context options to validate + * @returns The validated context options + * @internal + */ + async _validateContext(context) { + return context; + } + /** + * Internal iterator used by stream() to generate state updates. + * This method handles the core logic of graph execution and streaming. + * + * @param input - The input to start graph execution with + * @param options - Configuration options for streaming + * @returns AsyncGenerator yielding state updates + * @internal + */ + async *_streamIterator(input, options) { + const streamEncoding = "version" in (options ?? {}) ? void 0 : options?.encoding ?? void 0; + const streamSubgraphs = options?.subgraphs; + const isV3 = options?.version === "v3"; + const inputConfig = ensureLangGraphConfig(this.config, options); + if (inputConfig.recursionLimit === void 0 || inputConfig.recursionLimit < 1) throw new Error(`Passed "recursionLimit" must be at least 1.`); + if (this.checkpointer !== void 0 && this.checkpointer !== false && inputConfig.configurable === void 0) throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`); + const validInput = await this._validateInput(input); + const { runId, ...restConfig } = inputConfig; + const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability] = this._defaults(restConfig); + config.metadata = { + ls_integration: "langgraph", + ...config.metadata + }; + if (typeof config.context !== "undefined") config.context = await this._validateContext(config.context); + else config.configurable = await this._validateContext(config.configurable); + const stream = new IterableReadableWritableStream({ modes: new Set(streamMode) }); + if (this.checkpointer === true) { + config.configurable ??= {}; + const ns = config.configurable["checkpoint_ns"] ?? ""; + config.configurable[CONFIG_KEY_CHECKPOINT_NS] = ns.split("|").map((part) => part.split(":")[0]).join("|"); + } + if (streamMode.includes("messages")) { + const messageStreamer = isV3 ? new StreamProtocolMessagesHandler((chunk) => stream.push(chunk)) : new StreamMessagesHandler((chunk) => stream.push(chunk)); + const { callbacks } = config; + if (callbacks === void 0) config.callbacks = [messageStreamer]; + else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(messageStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(messageStreamer, true); + config.callbacks = copiedCallbacks; + } + } + if (streamMode.includes("tools")) { + const toolStreamer = new StreamToolsHandler((chunk) => stream.push(chunk)); + const { callbacks } = config; + if (callbacks === void 0) config.callbacks = [toolStreamer]; + else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(toolStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(toolStreamer, true); + config.callbacks = copiedCallbacks; + } + } + config.writer ??= (chunk) => { + if (!streamMode.includes("custom")) return; + const ns = (getConfig()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS])?.split("|").slice(0, -1); + stream.push([ + ns ?? [], + "custom", + chunk + ]); + }; + config.interrupt ??= this.userInterrupt ?? interrupt; + if (config.serverInfo == null) config.serverInfo = _buildServerInfo(config); + config.control ??= new RunControl(); + const callbackManagerOptions = { tracerInheritableMetadata: _getTracingMetadataDefaults(config) }; + const runManager = await (await CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata, void 0, callbackManagerOptions))?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, void 0, void 0, void 0, config?.runName ?? this.getName()); + const channelSpecs = getOnlyChannels(this.channels); + let loop; + let loopError; + /** + * The PregelLoop will yield events from concurrent tasks as soon as they are + * generated. Each task can push multiple events onto the stream in any order. + * + * We use a separate background method and stream here in order to yield events + * from the loop to the main stream and therefore back to the user as soon as + * they are available. + */ + const createAndRunLoop = async () => { + try { + loop = await PregelLoop.initialize({ + input: validInput, + config, + checkpointer, + nodes: this.nodes, + channelSpecs, + outputKeys, + streamKeys: this.streamChannelsAsIs, + store, + cache, + stream, + interruptAfter, + interruptBefore, + manager: runManager, + debug: this.debug, + triggerToNodes: this.triggerToNodes, + durability + }); + const runner = new PregelRunner({ + loop, + nodeFinished: config.configurable?.[CONFIG_KEY_NODE_FINISHED] + }); + if (options?.subgraphs) loop.config.configurable = { + ...loop.config.configurable, + [CONFIG_KEY_STREAM]: loop.stream + }; + await this._runLoop({ + loop, + runner, + debug, + config + }); + if (durability === "sync") await Promise.all(loop?.checkpointerPromises ?? []); + } catch (e) { + loopError = e; + } finally { + try { + if (loop) { + await loop.store?.stop(); + await loop.cache?.stop(); + } + await Promise.all(loop?.checkpointerPromises ?? []); + } catch (e) { + loopError = loopError ?? e; + } + if (loopError) { + await new Promise((resolve) => { + queueMicrotask(resolve); + }); + stream.error(loopError); + } else stream.close(); + } + }; + const runLoopPromise = createAndRunLoop(); + try { + for await (const chunk of stream) { + if (chunk === void 0) throw new Error("Data structure error."); + const [namespace, mode, payload] = chunk; + const isStreamEvents = "version" in (options ?? {}); + if (streamMode.includes(mode) || mode === "checkpoints" && isCheckpointEnvelope(payload) && (isV3 || isStreamEvents && streamSubgraphs && streamMode.includes("values"))) { + if (streamEncoding === "text/event-stream") { + if (streamSubgraphs) yield [ + namespace, + mode, + payload + ]; + else yield [ + null, + mode, + payload + ]; + continue; + } + if (streamSubgraphs && !streamModeSingle) yield [ + namespace, + mode, + payload + ]; + else if (!streamModeSingle) yield [mode, payload]; + else if (streamSubgraphs) yield [namespace, payload]; + else yield payload; + } + } + } catch (e) { + await runManager?.handleChainError(loopError); + throw e; + } finally { + await runLoopPromise; + } + await runManager?.handleChainEnd(loop?.output ?? {}, runId, void 0, void 0, void 0); + } + /** + * Run the graph with a single input and config. + * @param input The input to the graph. + * @param options The configuration to use for the run. + */ + async invoke(input, options) { + const streamMode = options?.streamMode ?? "values"; + const config = { + ...options, + outputKeys: options?.outputKeys ?? this.outputChannels, + streamMode, + encoding: void 0 + }; + const chunks = []; + const stream = await this.stream(input, config); + const interruptChunks = []; + let latest; + for await (const chunk of stream) if (streamMode === "values") if (isInterrupted(chunk)) interruptChunks.push(chunk[INTERRUPT$1]); + else latest = chunk; + else chunks.push(chunk); + if (streamMode === "values") { + if (interruptChunks.length > 0) { + const interrupts = interruptChunks.flat(1); + if (latest == null) return { [INTERRUPT$1]: interrupts }; + if (typeof latest === "object") return { + ...latest, + [INTERRUPT$1]: interrupts + }; + } + return latest; + } + return chunks; + } + async _runLoop(params) { + const { loop, runner, debug, config } = params; + let tickError; + try { + while (await loop.tick({ inputKeys: this.inputChannels })) { + for (const { task } of await loop._matchCachedWrites()) loop._outputWrites(task.id, task.writes, true); + if (debug) printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList); + if (debug) printStepTasks(loop.step, Object.values(loop.tasks)); + await runner.tick({ + timeout: this.stepTimeout, + retryPolicy: this.retryPolicy, + onStepWrite: (step, writes) => { + if (debug) printStepWrites(step, writes, this.streamChannelsList); + }, + maxConcurrency: config.maxConcurrency, + signal: config.signal + }); + } + if (loop.status === "draining") { + if (loop.control == null) throw new Error("Draining status requires run control"); + throw new GraphDrained(loop.control.drainReason ?? "shutdown"); + } + if (loop.status === "out_of_steps") throw new GraphRecursionError([ + `Recursion limit of ${config.recursionLimit} reached`, + "without hitting a stop condition. You can increase the", + `limit by setting the "recursionLimit" config key.` + ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" }); + } catch (e) { + tickError = e; + if (!await loop.finishAndHandleError(tickError)) throw e; + } finally { + if (tickError === void 0) await loop.finishAndHandleError(); + } + } + async clearCache() { + await this.cache?.clear([]); + } +}; +function _buildServerInfo(config) { + const metadata = config.metadata ?? {}; + const configurable = config.configurable ?? {}; + const assistantId = configurable.assistant_id ?? metadata.assistant_id; + const graphId = configurable.graph_id ?? metadata.graph_id; + const authUserData = configurable.langgraph_auth_user; + let user; + if (authUserData != null && typeof authUserData === "object" && "identity" in authUserData) user = authUserData; + if (assistantId != null || graphId != null || user != null) return { + assistantId: assistantId != null ? String(assistantId) : "", + graphId: graphId != null ? String(graphId) : "", + user + }; +} +var OMITTED_KEYS = /* @__PURE__ */ new Set([ + "key", + "token", + "secret", + "password", + "auth" +]); +function _excludeAsMetadata(key, value) { + const keyLower = key.toLowerCase(); + let hasOmittedSubstring = false; + for (const substr of OMITTED_KEYS) if (keyLower.includes(substr)) { + hasOmittedSubstring = true; + break; + } + return key.startsWith("__") || !(typeof value === "string" || typeof value === "number" || typeof value === "boolean") || hasOmittedSubstring; +} +function _getTracingMetadataDefaults(config) { + const configurable = config.configurable; + if (!configurable) return; + const metadata = {}; + for (const [key, value] of Object.entries(configurable)) { + if (_excludeAsMetadata(key, value)) continue; + metadata[key] = value; + } + return Object.keys(metadata).length > 0 ? metadata : void 0; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/channels/ephemeral_value.js +/** +* Stores the value received in the step immediately preceding, clears after. +*/ +var EphemeralValue = class EphemeralValue extends BaseChannel { + lc_graph_name = "EphemeralValue"; + guard; + value = []; + constructor(guard = true) { + super(); + this.guard = guard; + } + fromCheckpoint(checkpoint) { + const empty = new EphemeralValue(this.guard); + if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; + return empty; + } + update(values) { + if (values.length === 0) { + const updated = this.value.length > 0; + this.value = []; + return updated; + } + if (values.length !== 1 && this.guard) throw new InvalidUpdateError("EphemeralValue can only receive one value per step."); + this.value = [values[values.length - 1]]; + return true; + } + get() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + checkpoint() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + isAvailable() { + return this.value.length !== 0; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/graph/graph.js +var Branch = class { + path; + ends; + constructor(options) { + if (Runnable.isRunnable(options.path)) this.path = options.path; + else this.path = _coerceToRunnable(options.path); + this.ends = Array.isArray(options.pathMap) ? options.pathMap.reduce((acc, n) => { + acc[n] = n; + return acc; + }, {}) : options.pathMap; + } + run(writer, reader) { + return ChannelWrite.registerWriter(new RunnableCallable({ + name: "", + trace: false, + func: async (input, config) => { + try { + return await this._route(input, config, writer, reader); + } catch (e) { + if (e.name === NodeInterrupt.unminifiable_name) console.warn("[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.\nNodeInterrupt should only be thrown inside a node, not in edge conditions."); + throw e; + } + } + })); + } + async _route(input, config, writer, reader) { + let result = await this.path.invoke(reader ? reader(config) : input, config); + if (!Array.isArray(result)) result = [result]; + let destinations; + if (this.ends) destinations = result.map((r) => _isSend(r) ? r : this.ends[r]); + else destinations = result; + if (destinations.some((dest) => !dest)) throw new Error("Branch condition returned unknown or null destination"); + if (destinations.filter(_isSend).some((packet) => packet.node === "__end__")) throw new InvalidUpdateError("Cannot send a packet to the END node"); + return await writer(destinations, config) ?? input; + } +}; +var Graph$1 = class { + nodes; + edges; + branches; + entryPoint; + compiled = false; + constructor() { + this.nodes = {}; + this.edges = /* @__PURE__ */ new Set(); + this.branches = {}; + } + warnIfCompiled(message) { + if (this.compiled) console.warn(message); + } + get allEdges() { + return this.edges; + } + addNode(...args) { + function isMutlipleNodes(args) { + return args.length >= 1 && typeof args[0] !== "string"; + } + const nodes = isMutlipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]) : [[ + args[0], + args[1], + args[2] + ]]; + if (nodes.length === 0) throw new Error("No nodes provided in `addNode`"); + for (const [key, action, options] of nodes) { + for (const reservedChar of ["|", ":"]) if (key.includes(reservedChar)) throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); + this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); + if (key in this.nodes) throw new Error(`Node \`${key}\` already present.`); + if (key === "__end__") throw new Error(`Node \`${key}\` is reserved.`); + const runnable = _coerceToRunnable(action); + this.nodes[key] = { + runnable, + metadata: options?.metadata, + subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, + ends: options?.ends + }; + } + return this; + } + addEdge(startKey, endKey) { + this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`); + if (startKey === "__end__") throw new Error("END cannot be a start node"); + if (endKey === "__start__") throw new Error("START cannot be an end node"); + if (Array.from(this.edges).some(([start]) => start === startKey) && !("channels" in this)) throw new Error(`Already found path for ${startKey}. For multiple edges, use StateGraph.`); + this.edges.add([startKey, endKey]); + return this; + } + addConditionalEdges(source, path, pathMap) { + const options = typeof source === "object" ? source : { + source, + path, + pathMap + }; + this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); + if (!Runnable.isRunnable(options.path)) options.path = _coerceToRunnable(options.path); + const name = options.path.getName() === "RunnableLambda" ? "condition" : options.path.getName(); + if (this.branches[options.source] && this.branches[options.source][name]) throw new Error(`Condition \`${name}\` already present for node \`${source}\``); + this.branches[options.source] ??= {}; + this.branches[options.source][name] = new Branch(options); + return this; + } + /** + * @deprecated use `addEdge(START, key)` instead + */ + setEntryPoint(key) { + this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."); + return this.addEdge(START, key); + } + /** + * @deprecated use `addEdge(key, END)` instead + */ + setFinishPoint(key) { + this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."); + return this.addEdge(key, END); + } + compile({ checkpointer, interruptBefore, interruptAfter, name, transformers } = {}) { + this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); + const compiled = new CompiledGraph({ + builder: this, + checkpointer, + interruptAfter, + interruptBefore, + autoValidate: false, + nodes: {}, + channels: { + [START]: new EphemeralValue(), + [END]: new EphemeralValue() + }, + inputChannels: START, + outputChannels: END, + streamChannels: [], + streamMode: "values", + name, + streamTransformers: transformers + }); + for (const [key, node] of Object.entries(this.nodes)) compiled.attachNode(key, node); + for (const [start, end] of this.edges) compiled.attachEdge(start, end); + for (const [start, branches] of Object.entries(this.branches)) for (const [name, branch] of Object.entries(branches)) compiled.attachBranch(start, name, branch); + return compiled.validate(); + } + validate(interrupt) { + const allSources = new Set([...this.allEdges].map(([src, _]) => src)); + for (const [start] of Object.entries(this.branches)) allSources.add(start); + for (const source of allSources) if (source !== "__start__" && !(source in this.nodes)) throw new Error(`Found edge starting at unknown node \`${source}\``); + const allTargets = new Set([...this.allEdges].map(([_, target]) => target)); + for (const [start, branches] of Object.entries(this.branches)) for (const branch of Object.values(branches)) if (branch.ends != null) for (const end of Object.values(branch.ends)) allTargets.add(end); + else { + allTargets.add(END); + for (const node of Object.keys(this.nodes)) if (node !== start) allTargets.add(node); + } + for (const node of Object.values(this.nodes)) for (const target of node.ends ?? []) allTargets.add(target); + if (Object.values(this.nodes).some((node) => node.isErrorHandler)) for (const node of Object.keys(this.nodes)) allTargets.add(node); + for (const node of Object.keys(this.nodes)) { + if (this.nodes[node].isErrorHandler) continue; + if (!allTargets.has(node)) throw new UnreachableNodeError([ + `Node \`${node}\` is not reachable.`, + "", + "If you are returning Command objects from your node,", + "make sure you are passing names of potential destination nodes as an \"ends\" array", + "into \".addNode(..., { ends: [\"node1\", \"node2\"] })\"." + ].join("\n"), { lc_error_code: "UNREACHABLE_NODE" }); + } + for (const target of allTargets) if (target !== "__end__" && !(target in this.nodes)) throw new Error(`Found edge ending at unknown node \`${target}\``); + if (interrupt) { + for (const node of interrupt) if (!(node in this.nodes)) throw new Error(`Interrupt node \`${node}\` is not present`); + } + this.compiled = true; + } +}; +var CompiledGraph = class extends Pregel { + builder; + constructor({ builder, ...rest }) { + super(rest); + this.builder = builder; + } + withConfig(config) { + return super.withConfig(config); + } + attachNode(key, node) { + this.channels[key] = new EphemeralValue(); + this.nodes[key] = new PregelNode({ + channels: [], + triggers: [], + metadata: node.metadata, + subgraphs: node.subgraphs, + ends: node.ends + }).pipe(node.runnable).pipe(new ChannelWrite([{ + channel: key, + value: PASSTHROUGH + }], [TAG_HIDDEN])); + this.streamChannels.push(key); + } + attachEdge(start, end) { + if (end === "__end__") { + if (start === "__start__") throw new Error("Cannot have an edge from START to END"); + this.nodes[start].writers.push(new ChannelWrite([{ + channel: END, + value: PASSTHROUGH + }], [TAG_HIDDEN])); + } else { + this.nodes[end].triggers.push(start); + this.nodes[end].channels.push(start); + } + } + attachBranch(start, name, branch) { + if (start === "__start__" && !this.nodes["__start__"]) this.nodes[START] = Channel.subscribeTo(START, { tags: [TAG_HIDDEN] }); + this.nodes[start].pipe(branch.run((dests) => { + return new ChannelWrite(dests.map((dest) => { + if (_isSend(dest)) return dest; + return { + channel: dest === "__end__" ? END : `branch:${start}:${name}:${dest}`, + value: PASSTHROUGH + }; + }), [TAG_HIDDEN]); + })); + const ends = branch.ends ? Object.values(branch.ends) : Object.keys(this.nodes); + for (const end of ends) if (end !== "__end__") { + const channelName = `branch:${start}:${name}:${end}`; + this.channels[channelName] = new EphemeralValue(); + this.nodes[end].triggers.push(channelName); + this.nodes[end].channels.push(channelName); + } + } + /** + * Returns a drawable representation of the computation graph. + */ + async getGraphAsync(config) { + const xray = config?.xray; + const graph = new Graph(); + const startNodes = { [START]: graph.addNode({ schema: any() }, START) }; + const endNodes = {}; + let subgraphs = {}; + if (xray) subgraphs = Object.fromEntries((await gatherIterator(this.getSubgraphsAsync())).filter((x) => isCompiledGraph(x[1]))); + const discoveredEdges = []; + function addEdge(start, end, label, conditional = false) { + if (end === "__end__" && endNodes["__end__"] === void 0) endNodes[END] = graph.addNode({ schema: any() }, END); + if (startNodes[start] === void 0) return; + if (endNodes[end] === void 0) throw new Error(`End node ${end} not found!`); + discoveredEdges.push({ + src: start, + dest: end, + conditional + }); + return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional); + } + for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { + const displayKey = _escapeMermaidKeywords(key); + const node = nodeSpec.runnable; + const metadata = nodeSpec.metadata ?? {}; + if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = "before,after"; + else if (this.interruptBefore?.includes(key)) metadata.__interrupt = "before"; + else if (this.interruptAfter?.includes(key)) metadata.__interrupt = "after"; + if (xray) { + const newXrayValue = typeof xray === "number" ? xray - 1 : xray; + const drawableSubgraph = subgraphs[key] !== void 0 ? await subgraphs[key].getGraphAsync({ + ...config, + xray: newXrayValue + }) : node.getGraph(config); + drawableSubgraph.trimFirstNode(); + drawableSubgraph.trimLastNode(); + if (Object.keys(drawableSubgraph.nodes).length > 1) { + const [e, s] = graph.extend(drawableSubgraph, displayKey); + if (e === void 0) throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); + function _isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; + } + function _nodeDataStr(id, data) { + if (id !== void 0 && !validate(id)) return id; + else if (_isRunnableInterface(data)) try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; + return dataStr; + } catch { + return data.getName(); + } + else return data.name ?? "UnknownSchema"; + } + if (s !== void 0) startNodes[displayKey] = { + name: _nodeDataStr(s.id, s.data), + ...s + }; + endNodes[displayKey] = { + name: _nodeDataStr(e.id, e.data), + ...e + }; + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } + const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { + if (a < b) return -1; + else if (b > a) return 1; + else return 0; + }); + for (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); + for (const [start, branches] of Object.entries(this.builder.branches)) { + const defaultEnds = { + ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), + [END]: END + }; + for (const branch of Object.values(branches)) { + let ends; + if (branch.ends !== void 0) ends = branch.ends; + else ends = defaultEnds; + for (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); + } + } + for (const [key, node] of Object.entries(this.builder.nodes)) if (node.ends !== void 0) for (const end of node.ends) addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), void 0, true); + addImplicitTerminalEndEdges(this.builder.nodes, discoveredEdges, addEdge); + return graph; + } + /** + * Returns a drawable representation of the computation graph. + * + * @deprecated Use getGraphAsync instead. The async method will be the default in the next minor core release. + */ + getGraph(config) { + const xray = config?.xray; + const graph = new Graph(); + const startNodes = { [START]: graph.addNode({ schema: any() }, START) }; + const endNodes = {}; + let subgraphs = {}; + if (xray) subgraphs = Object.fromEntries(gatherIteratorSync(this.getSubgraphs()).filter((x) => isCompiledGraph(x[1]))); + const discoveredEdges = []; + function addEdge(start, end, label, conditional = false) { + if (end === "__end__" && endNodes["__end__"] === void 0) endNodes[END] = graph.addNode({ schema: any() }, END); + if (startNodes[start] === void 0) return; + if (endNodes[end] === void 0) throw new Error(`End node ${end} not found!`); + discoveredEdges.push({ + src: start, + dest: end, + conditional + }); + return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional); + } + for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { + const displayKey = _escapeMermaidKeywords(key); + const node = nodeSpec.runnable; + const metadata = nodeSpec.metadata ?? {}; + if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = "before,after"; + else if (this.interruptBefore?.includes(key)) metadata.__interrupt = "before"; + else if (this.interruptAfter?.includes(key)) metadata.__interrupt = "after"; + if (xray) { + const newXrayValue = typeof xray === "number" ? xray - 1 : xray; + const drawableSubgraph = subgraphs[key] !== void 0 ? subgraphs[key].getGraph({ + ...config, + xray: newXrayValue + }) : node.getGraph(config); + drawableSubgraph.trimFirstNode(); + drawableSubgraph.trimLastNode(); + if (Object.keys(drawableSubgraph.nodes).length > 1) { + const [e, s] = graph.extend(drawableSubgraph, displayKey); + if (e === void 0) throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); + function _isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; + } + function _nodeDataStr(id, data) { + if (id !== void 0 && !validate(id)) return id; + else if (_isRunnableInterface(data)) try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; + return dataStr; + } catch { + return data.getName(); + } + else return data.name ?? "UnknownSchema"; + } + if (s !== void 0) startNodes[displayKey] = { + name: _nodeDataStr(s.id, s.data), + ...s + }; + endNodes[displayKey] = { + name: _nodeDataStr(e.id, e.data), + ...e + }; + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } + const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { + if (a < b) return -1; + else if (b > a) return 1; + else return 0; + }); + for (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); + for (const [start, branches] of Object.entries(this.builder.branches)) { + const defaultEnds = { + ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), + [END]: END + }; + for (const branch of Object.values(branches)) { + let ends; + if (branch.ends !== void 0) ends = branch.ends; + else ends = defaultEnds; + for (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); + } + } + for (const [key, node] of Object.entries(this.builder.nodes)) if (node.ends !== void 0) for (const end of node.ends) addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), void 0, true); + addImplicitTerminalEndEdges(this.builder.nodes, discoveredEdges, addEdge); + return graph; + } +}; +function isCompiledGraph(x) { + return typeof x.attachNode === "function" && typeof x.attachEdge === "function"; +} +function _escapeMermaidKeywords(key) { + if (key === "subgraph") return `"${key}"`; + return key; +} +/** +* Add implicit edges to END for terminal nodes (targets with no outgoing edges). +* +* Only nodes reached by a non-conditional edge are considered, so +* conditional-branch targets are not treated as implicit sinks. +*/ +function addImplicitTerminalEndEdges(nodes, discovered, addEdge) { + const sources = new Set(discovered.map((e) => e.src)); + const nonConditionalDestinations = [...new Set(discovered.filter((e) => !e.conditional && e.dest !== "__end__").map((e) => e.dest))].sort(); + for (const displayDest of nonConditionalDestinations) { + if (sources.has(displayDest)) continue; + const rawKey = Object.keys(nodes).find((k) => _escapeMermaidKeywords(k) === displayDest); + if (rawKey !== void 0 && nodes[rawKey]?.isErrorHandler) continue; + addEdge(displayDest, END); + } +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/state/types.js +function isStandardSchema(schema) { + return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"]; +} +function isStandardJSONSchema(schema) { + return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"]; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/state/adapter.js +/** +* Get the JSON schema from a SerializableSchema. +*/ +function getJsonSchemaFromSchema(schema) { + if (isStandardJSONSchema(schema)) try { + return schema["~standard"].jsonSchema.input({ target: "draft-07" }); + } catch { + return; + } +} +/** +* Detect if a schema has a default value by validating `undefined`. +* +* Uses the Standard Schema `~standard.validate` API to detect defaults. +* If the schema accepts `undefined` and returns a value, that value is the default. +* +* This approach is library-agnostic and works with any Standard Schema compliant +* library (Zod, Valibot, ArkType, etc.) without needing to introspect internals. +* +* @param schema - The schema to check for a default value. +* @returns A factory function returning the default, or undefined if no default exists. +* +* @example +* ```ts +* const getter = getSchemaDefaultGetter(z.string().default("hello")); +* getter?.(); // "hello" +* +* const noDefault = getSchemaDefaultGetter(z.string()); +* noDefault; // undefined +* ``` +*/ +function getSchemaDefaultGetter(schema) { + if (schema == null) return; + if (!isStandardSchema(schema)) return; + try { + const result = schema["~standard"].validate(void 0); + if (result && typeof result === "object" && !("then" in result && typeof result.then === "function")) { + const syncResult = result; + if (!syncResult.issues) { + const defaultValue = syncResult.value; + return () => defaultValue; + } + } + } catch {} +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/channels/delta.js +var isDeltaChannel = (value) => { + return value != null && value.lc_graph_name === "DeltaChannel"; +}; +/** +* Reducer channel that stores only a sentinel in checkpoint blobs and +* reconstructs state by replaying ancestor writes through the reducer. +* +* `DeltaChannel` avoids re-serializing the full accumulated value at every +* step. Instead of writing the value into `channel_values`, the channel is +* omitted entirely and its state is reconstructed on read by walking the +* ancestor chain and replaying the per-step writes through the reducer (see +* {@link BaseCheckpointSaver.getDeltaChannelHistory}). +* +* Snapshot cadence is driven by two counters: a per-channel update count and +* the total supersteps since the last snapshot. A full {@link DeltaSnapshot} +* blob is written when EITHER the update count reaches `snapshotFrequency` OR +* the supersteps count reaches the system-wide +* `DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT` bound (default 5000), bounding replay +* depth even for channels that stop receiving writes. +* +* @remarks Beta. The API and on-disk representation may change in future +* releases. Threads written with `DeltaChannel` today are expected to remain +* readable, but the surrounding contract (`getDeltaChannelHistory`, the +* `DeltaSnapshot` blob shape, the `counters_since_delta_snapshot` metadata +* field) is not yet stable. +* +* @example +* ```typescript +* import { Annotation } from "@langchain/langgraph"; +* import { DeltaChannel, messagesDeltaReducer } from "@langchain/langgraph"; +* +* const State = Annotation.Root({ +* messages: Annotation({ +* reducer: () => [], // ignored; DeltaChannel is supplied below +* }), +* }); +* ``` +*/ +var DeltaChannel = class DeltaChannel extends BaseChannel { + lc_graph_name = "DeltaChannel"; + /** `undefined` represents the Python `MISSING` sentinel (empty channel). */ + value; + reducer; + snapshotFrequency; + initialValueFactory; + constructor(reducer, options) { + super(); + const snapshotFrequency = options?.snapshotFrequency ?? 1e3; + if (!Number.isInteger(snapshotFrequency) || snapshotFrequency <= 0) throw new Error(`snapshotFrequency must be a positive integer, got ${snapshotFrequency}`); + this.reducer = reducer; + this.snapshotFrequency = snapshotFrequency; + this.initialValueFactory = options?.initialValueFactory ?? (() => []); + this.value = void 0; + } + fromCheckpoint(checkpoint) { + const empty = new DeltaChannel(this.reducer, { + snapshotFrequency: this.snapshotFrequency, + initialValueFactory: this.initialValueFactory + }); + if (checkpoint === void 0) empty.value = this.initialValueFactory(); + else if (isDeltaSnapshot(checkpoint)) empty.value = checkpoint.value; + else empty.value = checkpoint; + return empty; + } + /** + * Apply ancestor writes oldest-to-newest via a single reducer call. + * + * If any write is an Overwrite, the last one in the sequence acts as the + * reset point: its value becomes the new base and only writes after it are + * passed to the reducer. + */ + replayWrites(writes) { + const values = writes.map((w) => w[2]); + if (values.length === 0) return; + let base = this.value; + let start = 0; + for (let i = 0; i < values.length; i += 1) { + const [isOverwrite, overwriteValue] = _getOverwriteValue(values[i]); + if (isOverwrite) { + base = overwriteValue !== void 0 && overwriteValue !== null ? overwriteValue : this.initialValueFactory(); + start = i + 1; + } + } + const remaining = values.slice(start); + this.value = remaining.length > 0 ? this.reducer(base, remaining) : base; + } + update(values) { + if (values.length === 0) return false; + let overwriteValue; + let hasOverwrite = false; + for (const value of values) if (_isOverwriteValue(value)) { + if (hasOverwrite) throw new InvalidUpdateError("Can receive only one Overwrite value per step."); + hasOverwrite = true; + [, overwriteValue] = _getOverwriteValue(value); + } + if (hasOverwrite) { + this.value = overwriteValue !== void 0 && overwriteValue !== null ? overwriteValue : this.initialValueFactory(); + return true; + } + const base = this.value === void 0 ? this.initialValueFactory() : this.value; + this.value = this.reducer(base, values); + return true; + } + get() { + if (this.value === void 0) throw new EmptyChannelError(); + return this.value; + } + /** + * Always returns `undefined` (the Python `MISSING` sentinel). Snapshot + * decisions live in `createCheckpoint`, which has the channel version and + * writes a {@link DeltaSnapshot} directly into `channel_values`. For + * non-snapshot steps the channel does not appear in `channel_values`; + * reconstruction walks ancestor writes via the saver's + * `getDeltaChannelHistory`. + */ + checkpoint() {} + isAvailable() { + return this.value !== void 0; + } + equals(other) { + if (this === other) return true; + if (!isDeltaChannel(other)) return false; + if (this.snapshotFrequency !== other.snapshotFrequency) return false; + return this.reducer === other.reducer; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/channels/untracked_value.js +var MISSING = Symbol.for("langgraph.channel.missing"); +/** +* Stores the last value received, never checkpointed. +* +* This channel stores values during graph execution but does NOT persist +* the value to checkpoints. On restoration from a checkpoint, the value +* will be reset to empty (or the initial value if provided). +* +* Useful for transient state like: +* - Database connections +* - Temporary caches +* - Runtime-only configuration +* +* @internal +*/ +var UntrackedValueChannel = class UntrackedValueChannel extends BaseChannel { + lc_graph_name = "UntrackedValue"; + /** + * If true, throws an error when multiple values are received in a single step. + * If false, stores the last value received. + */ + guard; + /** + * The current value. MISSING sentinel indicates no value has been set. + */ + _value = MISSING; + /** + * Optional factory function for the initial value. + */ + initialValueFactory; + constructor(options) { + super(); + this.guard = options?.guard ?? true; + this.initialValueFactory = options?.initialValueFactory; + if (this.initialValueFactory) this._value = this.initialValueFactory(); + } + /** + * Return a new channel, ignoring the checkpoint since we don't persist. + * The initial value (if any) is restored. + */ + fromCheckpoint(_checkpoint) { + return new UntrackedValueChannel({ + guard: this.guard, + initialValueFactory: this.initialValueFactory + }); + } + /** + * Update the channel with the given values. + * If guard is true, throws if more than one value is received. + */ + update(values) { + if (values.length === 0) return false; + if (values.length !== 1 && this.guard) throw new InvalidUpdateError("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); + this._value = values[values.length - 1]; + return true; + } + /** + * Get the current value. + * @throws EmptyChannelError if no value has been set. + */ + get() { + if (this._value === MISSING) throw new EmptyChannelError(); + return this._value; + } + /** + * Always returns undefined - untracked values are never checkpointed. + */ + checkpoint() {} + /** + * Return true if a value has been set. + */ + isAvailable() { + return this._value !== MISSING; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/state/values/reduced.js +/** +* Symbol for runtime identification of ReducedValue instances. +*/ +var REDUCED_VALUE_SYMBOL = Symbol.for("langgraph.state.reduced_value"); +/** +* Represents a state field whose value is computed and updated using a reducer function. +* +* {@link ReducedValue} allows you to define accumulators, counters, aggregators, or other fields +* whose value is determined incrementally by applying a reducer to incoming updates. +* +* Each time a new input is provided, the reducer function is called with the current output +* and the new input, producing an updated value. Input validation can be controlled separately +* from output validation by providing an explicit input schema. +* +* @template Value - The type of the value stored in state and produced by reduction. +* @template Input - The type of updates accepted by the reducer. +* +* @example +* // Accumulator with distinct input validation +* const Sum = new ReducedValue(z.number(), { +* inputSchema: z.number().min(1), +* reducer: (total, toAdd) => total + toAdd +* }); +* +* @example +* // Simple running max, using only the value schema +* const Max = new ReducedValue(z.number(), { +* reducer: (current, next) => Math.max(current, next) +* }); +*/ +var ReducedValue = class { + /** + * Instance marker for runtime identification. + * @internal + */ + [REDUCED_VALUE_SYMBOL] = true; + /** + * The schema that describes the type of value stored in state (i.e., after reduction). + * Note: We use `unknown` for the input type to allow schemas with `.default()` wrappers, + * where the input type includes `undefined`. + */ + valueSchema; + /** + * The schema used to validate reducer inputs. + * If not specified explicitly, this defaults to `valueSchema`. + */ + inputSchema; + /** + * The reducer function that combines a current output value and an incoming input. + */ + reducer; + /** + * Optional extra fields to merge into the generated JSON Schema (e.g., for documentation or constraints). + */ + jsonSchemaExtra; + constructor(valueSchema, init) { + this.reducer = init.reducer; + this.jsonSchemaExtra = init.jsonSchemaExtra; + this.valueSchema = valueSchema; + this.inputSchema = "inputSchema" in init ? init.inputSchema : valueSchema; + this.jsonSchemaExtra = init.jsonSchemaExtra; + } + static isInstance(value) { + return typeof value === "object" && value !== null && REDUCED_VALUE_SYMBOL in value && value[REDUCED_VALUE_SYMBOL] === true; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/state/values/untracked.js +/** +* Symbol for runtime identification of UntrackedValue instances. +*/ +var UNTRACKED_VALUE_SYMBOL = Symbol.for("langgraph.state.untracked_value"); +/** +* Represents a state field whose value is transient and never checkpointed. +* +* Use {@link UntrackedValue} for state fields that should be tracked for the lifetime +* of the process, but should not participate in durable checkpoints or recovery. +* +* @typeParam Value - The type of value stored in this field. +* +* @example +* // Create an untracked in-memory cache +* const cache = new UntrackedValue>(); +* +* // Use with a type schema for basic runtime validation +* import { z } from "zod"; +* const tempSession = new UntrackedValue(z.object({ token: z.string() }), { guard: false }); +* +* // You can customize whether to throw on multiple updates per step: +* const session = new UntrackedValue(undefined, { guard: false }); +*/ +var UntrackedValue = class { + /** + * Instance marker for runtime identification. + * @internal + */ + [UNTRACKED_VALUE_SYMBOL] = true; + /** + * Optional schema describing the type and shape of the value stored in this field. + * + * If provided, this can be used for runtime validation or code generation. + */ + schema; + /** + * Whether to guard against multiple updates to this untracked value in a single step. + * + * - If `true` (default), throws an error if multiple updates are received in one step. + * - If `false`, only the last value from that step is kept, others are ignored. + * + * This helps prevent accidental state replacement within a step. + */ + guard; + /** + * Create a new untracked value state field. + * + * @param schema - Optional type schema describing the value (e.g. a Zod schema). + * @param init - Optional options for tracking updates or enabling multiple-writes-per-step. + */ + constructor(schema, init) { + this.schema = schema; + this.guard = init?.guard ?? true; + } + static isInstance(value) { + return typeof value === "object" && value !== null && UNTRACKED_VALUE_SYMBOL in value; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/state/values/delta.js +/** +* Symbol for runtime identification of DeltaValue instances. +*/ +var DELTA_VALUE_SYMBOL = Symbol.for("langgraph.state.delta_value"); +/** +* Represents a state field backed by a {@link DeltaChannel}. +* +* Unlike {@link ReducedValue} (which stores the full accumulated value in every +* checkpoint blob via `BinaryOperatorAggregate`), a `DeltaValue` field persists +* only per-step deltas (plus periodic snapshots) and reconstructs its state on +* read by replaying ancestor writes through a batch reducer. This avoids +* re-serializing large accumulators (e.g. long message histories) at every step. +* +* @remarks Beta. The on-disk representation backing `DeltaChannel` may change in +* future releases. +* +* @template Value - The type of the value stored in state and produced by reduction. +* @template Input - The type of updates accepted by the reducer. +* +* @example +* ```ts +* import { z } from "zod"; +* import { StateSchema, DeltaValue } from "@langchain/langgraph"; +* +* const State = new StateSchema({ +* history: new DeltaValue(z.array(z.string()).default(() => []), { +* inputSchema: z.string(), +* reducer: (current, writes) => [...current, ...writes], +* }), +* }); +* ``` +*/ +var DeltaValue = class { + /** + * Instance marker for runtime identification. + * @internal + */ + [DELTA_VALUE_SYMBOL] = true; + /** + * The schema that describes the type of value stored in state (after + * reduction). Its default (if any) seeds the channel's initial value. + */ + valueSchema; + /** + * The schema used to validate reducer inputs. Defaults to `valueSchema` when + * not specified explicitly. + */ + inputSchema; + /** + * The batch reducer that folds a list of incoming writes into the current + * accumulated value. + */ + reducer; + /** + * Snapshot cadence forwarded to the underlying {@link DeltaChannel}. + */ + snapshotFrequency; + /** + * Optional extra fields to merge into the generated JSON Schema. + */ + jsonSchemaExtra; + constructor(valueSchema, init) { + this.reducer = init.reducer; + this.valueSchema = valueSchema; + this.inputSchema = "inputSchema" in init ? init.inputSchema : valueSchema; + this.snapshotFrequency = init.snapshotFrequency; + this.jsonSchemaExtra = init.jsonSchemaExtra; + } + static isInstance(value) { + return typeof value === "object" && value !== null && DELTA_VALUE_SYMBOL in value && value[DELTA_VALUE_SYMBOL] === true; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/channels/named_barrier_value.js +var areSetsEqual = (a, b) => a.size === b.size && [...a].every((value) => b.has(value)); +/** +* A channel that waits until all named values are received before making the value available. +* +* This ensures that if node N and node M both write to channel C, the value of C will not be updated +* until N and M have completed updating. +*/ +var NamedBarrierValue = class NamedBarrierValue extends BaseChannel { + lc_graph_name = "NamedBarrierValue"; + names; + seen; + constructor(names) { + super(); + this.names = names; + this.seen = /* @__PURE__ */ new Set(); + } + fromCheckpoint(checkpoint) { + const empty = new NamedBarrierValue(this.names); + if (typeof checkpoint !== "undefined") empty.seen = new Set(checkpoint); + return empty; + } + update(values) { + let updated = false; + for (const nodeName of values) if (this.names.has(nodeName)) { + if (!this.seen.has(nodeName)) { + this.seen.add(nodeName); + updated = true; + } + } else throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); + return updated; + } + get() { + if (!areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); + } + checkpoint() { + return [...this.seen]; + } + consume() { + if (this.seen && this.names && areSetsEqual(this.seen, this.names)) { + this.seen = /* @__PURE__ */ new Set(); + return true; + } + return false; + } + isAvailable() { + return !!this.names && areSetsEqual(this.names, this.seen); + } +}; +/** +* A channel that waits until all named values are received before making the value ready to be made available. +* It is only made available after finish() is called. +* @internal +*/ +var NamedBarrierValueAfterFinish = class NamedBarrierValueAfterFinish extends BaseChannel { + lc_graph_name = "NamedBarrierValueAfterFinish"; + names; + seen; + finished; + constructor(names) { + super(); + this.names = names; + this.seen = /* @__PURE__ */ new Set(); + this.finished = false; + } + fromCheckpoint(checkpoint) { + const empty = new NamedBarrierValueAfterFinish(this.names); + if (typeof checkpoint !== "undefined") { + const [seen, finished] = checkpoint; + empty.seen = new Set(seen); + empty.finished = finished; + } + return empty; + } + update(values) { + let updated = false; + for (const nodeName of values) if (this.names.has(nodeName) && !this.seen.has(nodeName)) { + this.seen.add(nodeName); + updated = true; + } else if (!this.names.has(nodeName)) throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); + return updated; + } + get() { + if (!this.finished || !areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); + } + checkpoint() { + return [[...this.seen], this.finished]; + } + consume() { + if (this.finished && this.seen && this.names && areSetsEqual(this.seen, this.names)) { + this.seen = /* @__PURE__ */ new Set(); + this.finished = false; + return true; + } + return false; + } + finish() { + if (!this.finished && !!this.names && areSetsEqual(this.names, this.seen)) { + this.finished = true; + return true; + } + return false; + } + isAvailable() { + return this.finished && !!this.names && areSetsEqual(this.names, this.seen); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/state/schema.js +var STATE_SCHEMA_SYMBOL = Symbol.for("langgraph.state.state_schema"); +/** +* StateSchema provides a unified API for defining LangGraph state schemas. +* +* @example +* ```ts +* import { z } from "zod"; +* import { StateSchema, ReducedValue, MessagesValue } from "@langchain/langgraph"; +* +* const AgentState = new StateSchema({ +* // Prebuilt messages value +* messages: MessagesValue, +* // Basic LastValue channel from any standard schema +* currentStep: z.string(), +* // LastValue with native default +* count: z.number().default(0), +* // ReducedValue for fields needing reducers +* history: new ReducedValue( +* z.array(z.string()).default(() => []), +* { +* inputSchema: z.string(), +* reducer: (current, next) => [...current, next], +* } +* ), +* }); +* +* // Extract types +* type State = typeof AgentState.State; +* type Update = typeof AgentState.Update; +* +* // Use in StateGraph +* const graph = new StateGraph(AgentState); +* ``` +*/ +var StateSchema = class { + /** + * Symbol for runtime identification. + * @internal Used by isInstance for runtime type checking + */ + [STATE_SCHEMA_SYMBOL] = true; + constructor(fields) { + this.fields = fields; + } + /** + * Get the channel definitions for use with StateGraph. + * This converts the StateSchema fields into BaseChannel instances. + */ + getChannels() { + const channels = {}; + for (const [key, value] of Object.entries(this.fields)) if (DeltaValue.isInstance(value)) { + const defaultGetter = getSchemaDefaultGetter(value.valueSchema); + channels[key] = new DeltaChannel(value.reducer, { + snapshotFrequency: value.snapshotFrequency, + initialValueFactory: defaultGetter + }); + } else if (ReducedValue.isInstance(value)) { + const defaultGetter = getSchemaDefaultGetter(value.valueSchema); + channels[key] = new BinaryOperatorAggregate(value.reducer, defaultGetter); + } else if (UntrackedValue.isInstance(value)) { + const defaultGetter = value.schema ? getSchemaDefaultGetter(value.schema) : void 0; + channels[key] = new UntrackedValueChannel({ + guard: value.guard, + initialValueFactory: defaultGetter + }); + } else if (isStandardSchema(value)) channels[key] = new LastValue(getSchemaDefaultGetter(value)); + else throw new Error(`Invalid state field "${key}": must be a schema, ReducedValue, DeltaValue, UntrackedValue, or ManagedValue`); + return channels; + } + /** + * Get the JSON schema for the full state type. + * Used by Studio and API for schema introspection. + */ + getJsonSchema() { + const properties = {}; + const required = []; + for (const [key, value] of Object.entries(this.fields)) { + let fieldSchema; + if (DeltaValue.isInstance(value) || ReducedValue.isInstance(value)) { + fieldSchema = getJsonSchemaFromSchema(value.valueSchema); + if (value.jsonSchemaExtra) fieldSchema = { + ...fieldSchema ?? {}, + ...value.jsonSchemaExtra + }; + } else if (UntrackedValue.isInstance(value)) fieldSchema = value.schema ? getJsonSchemaFromSchema(value.schema) : void 0; + else if (isStandardSchema(value)) fieldSchema = getJsonSchemaFromSchema(value); + if (fieldSchema) { + properties[key] = fieldSchema; + let hasDefault = false; + if (DeltaValue.isInstance(value) || ReducedValue.isInstance(value)) hasDefault = getSchemaDefaultGetter(value.valueSchema) !== void 0; + else if (UntrackedValue.isInstance(value)) hasDefault = value.schema ? getSchemaDefaultGetter(value.schema) !== void 0 : false; + else hasDefault = getSchemaDefaultGetter(value) !== void 0; + if (!hasDefault) required.push(key); + } + } + return { + type: "object", + properties, + required: required.length > 0 ? required : void 0 + }; + } + /** + * Get the JSON schema for the update/input type. + * All fields are optional in updates. + */ + getInputJsonSchema() { + const properties = {}; + for (const [key, value] of Object.entries(this.fields)) { + let fieldSchema; + if (DeltaValue.isInstance(value) || ReducedValue.isInstance(value)) { + fieldSchema = getJsonSchemaFromSchema(value.inputSchema); + if (value.jsonSchemaExtra) fieldSchema = { + ...fieldSchema ?? {}, + ...value.jsonSchemaExtra + }; + } else if (UntrackedValue.isInstance(value)) fieldSchema = value.schema ? getJsonSchemaFromSchema(value.schema) : void 0; + else if (isStandardSchema(value)) fieldSchema = getJsonSchemaFromSchema(value); + if (fieldSchema) properties[key] = fieldSchema; + } + return { + type: "object", + properties + }; + } + /** + * Get the list of channel keys (excluding managed values). + */ + getChannelKeys() { + return Object.entries(this.fields).map(([key]) => key); + } + /** + * Get all keys (channels + managed values). + */ + getAllKeys() { + return Object.keys(this.fields); + } + /** + * Validate input data against the schema. + * This validates each field using its corresponding schema. + * + * @param data - The input data to validate + * @returns The validated data with coerced types + */ + async validateInput(data) { + if (data == null || typeof data !== "object") return data; + const result = {}; + for (const [key, value] of Object.entries(data)) { + const fieldDef = this.fields[key]; + if (fieldDef === void 0) { + result[key] = value; + continue; + } + let schema; + if (DeltaValue.isInstance(fieldDef) || ReducedValue.isInstance(fieldDef)) { + const [isOverwrite, overwriteValue] = _getOverwriteValue(value); + if (isOverwrite) { + schema = fieldDef.valueSchema; + const validationResult = await schema["~standard"].validate(overwriteValue); + if (validationResult.issues) throw new Error(`Validation failed for field "${key}": ${JSON.stringify(validationResult.issues)}`); + result[key] = { [OVERWRITE]: validationResult.value }; + continue; + } + schema = fieldDef.inputSchema; + } else if (UntrackedValue.isInstance(fieldDef)) schema = fieldDef.schema; + else if (isStandardSchema(fieldDef)) schema = fieldDef; + if (schema) { + const validationResult = await schema["~standard"].validate(value); + if (validationResult.issues) throw new Error(`Validation failed for field "${key}": ${JSON.stringify(validationResult.issues)}`); + result[key] = validationResult.value; + } else result[key] = value; + } + return result; + } + static isInstance(value) { + return typeof value === "object" && value !== null && STATE_SCHEMA_SYMBOL in value && value[STATE_SCHEMA_SYMBOL] === true; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph/dist/graph/messages_reducer.js +/** +* Special value that signifies the intent to remove all previous messages in the state reducer. +* Used as the unique identifier for a `RemoveMessage` instance which, when encountered, +* causes all prior messages to be discarded, leaving only those following this marker. +*/ +var REMOVE_ALL_MESSAGES = "__remove_all__"; +/** +* Reducer function for combining two sets of messages in LangGraph's state system. +* +* This reducer handles several tasks: +* 1. Normalizes both `left` and `right` message inputs to arrays. +* 2. Coerces any message-like objects into real `BaseMessage` instances. +* 3. Ensures all messages have unique, stable IDs by generating missing ones. +* 4. If a `RemoveMessage` instance is encountered in `right` with the ID `REMOVE_ALL_MESSAGES`, +* all previous messages are discarded and only the subsequent messages in `right` are returned. +* 5. Otherwise, merges `left` and `right` messages together following these rules: +* - If a message in `right` shares an ID with a message in `left`: +* - If it is a `RemoveMessage`, that message (by ID) is marked for removal. +* - If it is a normal message, it replaces the message with the same ID from `left`. +* - If a message in `right` **does not exist** in `left`: +* - If it is a `RemoveMessage`, this is considered an error (cannot remove non-existent ID). +* - Otherwise, the message is appended. +* - Messages flagged for removal are omitted from the final output. +* +* @param left - The existing array (or single message) of messages from current state. +* @param right - The new array (or single message) of messages to be applied. +* @returns A new array of `BaseMessage` objects representing the updated state. +* +* @throws Error if a `RemoveMessage` is used to delete a message with an ID that does not exist in the merged list. +* +* @example +* ```ts +* const msg1 = new AIMessage("hello"); +* const msg2 = new HumanMessage("hi"); +* const removal = new RemoveMessage({ id: msg1.id }); +* const newState = messagesStateReducer([msg1], [msg2, removal]); +* // newState will only contain msg2 (msg1 is removed) +* ``` +*/ +function messagesStateReducer(left, right) { + const leftArray = Array.isArray(left) ? left : [left]; + const rightArray = Array.isArray(right) ? right : [right]; + const leftMessages = leftArray.map(coerceMessageLikeToMessage); + const rightMessages = rightArray.map(coerceMessageLikeToMessage); + for (const m of leftMessages) if (m.id === null || m.id === void 0) { + m.id = v4(); + m.lc_kwargs.id = m.id; + } + let removeAllIdx; + for (let i = 0; i < rightMessages.length; i += 1) { + const m = rightMessages[i]; + if (m.id === null || m.id === void 0) { + m.id = v4(); + m.lc_kwargs.id = m.id; + } + if (RemoveMessage.isInstance(m) && m.id === "__remove_all__") removeAllIdx = i; + } + if (removeAllIdx != null) return rightMessages.slice(removeAllIdx + 1); + const merged = [...leftMessages]; + const mergedById = new Map(merged.map((m, i) => [m.id, i])); + const idsToRemove = /* @__PURE__ */ new Set(); + for (const m of rightMessages) { + const existingIdx = mergedById.get(m.id); + if (existingIdx !== void 0) if (RemoveMessage.isInstance(m)) idsToRemove.add(m.id); + else { + idsToRemove.delete(m.id); + merged[existingIdx] = m; + } + else { + if (RemoveMessage.isInstance(m)) throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${m.id}')`); + mergedById.set(m.id, merged.length); + merged.push(m); + } + } + return merged.filter((m) => !idsToRemove.has(m.id)); +} +/** +* **Experimental.** Batch reducer for use with `DeltaChannel`. +* +* Processes all writes in one pass — dedup by ID and `RemoveMessage` +* tombstoning — without calling {@link messagesStateReducer}. +* +* This reducer is batching-invariant, as required by `DeltaChannel`: +* `reducer(reducer(state, xs), ys) === reducer(state, xs.concat(ys))`. +* +* A `RemoveMessage` carrying the {@link REMOVE_ALL_MESSAGES} sentinel id +* clears all messages accumulated so far (prior state plus earlier writes in +* the same batch) and keeps only the messages that follow it, mirroring +* {@link messagesStateReducer}. Clearing happens in the same single linear +* pass, so the batching-invariant still holds. +* +* Raw object / string inputs are coerced to typed `BaseMessage` objects so +* that HTTP-driven graphs work without a separate coercion step. This is not +* full {@link messagesStateReducer} parity — unknown-id `RemoveMessage` +* errors and missing-id UUID assignment are not handled here. +* +* @param state - The current accumulated list of messages. +* @param writes - Batch of writes, each a single message-like or an array. +* @returns The new accumulated list of messages. +* +* @example +* ```typescript +* import { DeltaChannel, messagesDeltaReducer } from "@langchain/langgraph"; +* +* const channel = new DeltaChannel(messagesDeltaReducer); +* ``` +*/ +function messagesDeltaReducer(state, writes) { + const flat = []; + for (const w of writes) if (Array.isArray(w)) flat.push(...w); + else flat.push(w); + const stateMsgs = state.length > 0 && BaseMessage.isInstance(state[0]) ? state : state.map(coerceMessageLikeToMessage); + const msgs = flat.map(coerceMessageLikeToMessage); + const index = /* @__PURE__ */ new Map(); + for (let i = 0; i < stateMsgs.length; i += 1) { + const mid = stateMsgs[i].id; + if (mid != null) index.set(mid, i); + } + const result = [...stateMsgs]; + for (const msg of msgs) { + const mid = msg.id; + if (RemoveMessage.isInstance(msg) && mid === "__remove_all__") { + result.length = 0; + index.clear(); + } else if (mid == null) result.push(msg); + else if (RemoveMessage.isInstance(msg)) { + if (index.has(mid)) { + result[index.get(mid)] = null; + index.delete(mid); + } + } else if (index.has(mid)) result[index.get(mid)] = msg; + else { + index.set(mid, result.length); + result.push(msg); + } + } + return result.filter((m) => m !== null); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/state/prebuilt/messages.js +var messagesValueSchema = custom().default(() => []); +var messagesInputSchema = custom(); +var MessagesValue = new ReducedValue(messagesValueSchema, { + inputSchema: messagesInputSchema, + reducer: messagesStateReducer, + jsonSchemaExtra: { + langgraph_type: "messages", + description: "A list of chat messages" + } +}); +new DeltaValue(messagesValueSchema, { + inputSchema: messagesInputSchema, + reducer: messagesDeltaReducer, + jsonSchemaExtra: { + langgraph_type: "messages", + description: "A list of chat messages" + } +}); +//#endregion +//#region node_modules/@langchain/langgraph/dist/graph/zod/meta.js +/** +* A registry for storing and managing metadata associated with schemas. +* This class provides methods to get, extend, remove, and check metadata for a given schema. +*/ +var SchemaMetaRegistry = class { + /** + * Internal map storing schema metadata. + * @internal + */ + _map = /* @__PURE__ */ new Map(); + /** + * Cache for extended schemas. + * @internal + */ + _extensionCache = /* @__PURE__ */ new Map(); + /** + * Retrieves the metadata associated with a given schema. + * @template TValue The value type of the schema. + * @template TUpdate The update type of the schema (defaults to TValue). + * @param schema The schema to retrieve metadata for. + * @returns The associated SchemaMeta, or undefined if not present. + */ + get(schema) { + return this._map.get(schema); + } + /** + * Extends or sets the metadata for a given schema. + * @template TValue The value type of the schema. + * @template TUpdate The update type of the schema (defaults to TValue). + * @param schema The schema to extend metadata for. + * @param predicate A function that receives the existing metadata (or undefined) and returns the new metadata. + */ + extend(schema, predicate) { + const existingMeta = this.get(schema); + this._map.set(schema, predicate(existingMeta)); + } + /** + * Removes the metadata associated with a given schema. + * @param schema The schema to remove metadata for. + * @returns The SchemaMetaRegistry instance (for chaining). + */ + remove(schema) { + this._map.delete(schema); + return this; + } + /** + * Checks if metadata exists for a given schema. + * @param schema The schema to check. + * @returns True if metadata exists, false otherwise. + */ + has(schema) { + return this._map.has(schema); + } + /** + * Returns a mapping of channel instances for each property in the schema + * using the associated metadata in the registry. + * + * This is used to create the `channels` object that's passed to the `Graph` constructor. + * + * @template T The shape of the schema. + * @param schema The schema to extract channels from. + * @returns A mapping from property names to channel instances. + */ + getChannelsForSchema(schema) { + const channels = {}; + const shape = getInteropZodObjectShape(schema); + for (const [key, channelSchema] of Object.entries(shape)) { + const meta = this.get(channelSchema); + if (meta?.reducer) channels[key] = new BinaryOperatorAggregate(meta.reducer.fn, meta.default); + else channels[key] = new LastValue(meta?.default); + } + return channels; + } + /** + * Returns a modified schema that introspectively looks at all keys of the provided + * object schema, and applies the augmentations based on meta provided with those keys + * in the registry and the selectors provided in the `effects` parameter. + * + * This assumes that the passed in schema is the "root" schema object for a graph where + * the keys of the schema are the channels of the graph. Because we need to represent + * the input of a graph in a couple of different ways, the `effects` parameter allows + * us to apply those augmentations based on pre determined conditions. + * + * @param schema The root schema object to extend. + * @param effects The effects that are being applied. + * @returns The extended schema. + */ + getExtendedChannelSchemas(schema, effects) { + if (Object.keys(effects).length === 0) return schema; + const cacheKey = Object.entries(effects).filter(([, v]) => v === true).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join("|"); + const cache = this._extensionCache.get(cacheKey) ?? /* @__PURE__ */ new Map(); + if (cache.has(schema)) return cache.get(schema); + let modifiedSchema = schema; + if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) { + const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema]) => { + const meta = this.get(schema); + let outputSchema = effects.withReducerSchema ? meta?.reducer?.schema ?? schema : schema; + if (effects.withJsonSchemaExtrasAsDescription && meta?.jsonSchemaExtra) { + const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema); + const strExtras = JSON.stringify({ + ...meta.jsonSchemaExtra, + description + }); + outputSchema = outputSchema.describe(`lg:${strExtras}`); + } + return [key, outputSchema]; + }); + modifiedSchema = extendInteropZodObject(schema, Object.fromEntries(newShapeEntries)); + if (isZodSchemaV3(modifiedSchema)) modifiedSchema._def.unknownKeys = "strip"; + } + if (effects.asPartial) modifiedSchema = interopZodObjectPartial(modifiedSchema); + cache.set(schema, modifiedSchema); + this._extensionCache.set(cacheKey, cache); + return modifiedSchema; + } +}; +var schemaMetaRegistry = new SchemaMetaRegistry(); +function withLangGraph(schema, meta) { + if (meta.reducer && !meta.default) { + const defaultValueGetter = getInteropZodDefaultGetter(schema); + if (defaultValueGetter != null) meta.default = defaultValueGetter; + } + if (meta.reducer) { + const schemaWithReducer = Object.assign(schema, { lg_reducer_schema: meta.reducer?.schema ?? schema }); + schemaMetaRegistry.extend(schemaWithReducer, () => meta); + return schemaWithReducer; + } else { + schemaMetaRegistry.extend(schema, () => meta); + return schema; + } +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/graph/types.js +/** +* Check if a value is a valid StateDefinitionInit type. +* Supports: StateSchema, InteropZodObject (Zod), AnnotationRoot, StateDefinition +* +* @internal +*/ +function isStateDefinitionInit(value) { + if (value == null) return false; + if (StateSchema.isInstance(value)) return true; + if (isInteropZodObject(value)) return true; + if (typeof value === "object" && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot") return true; + if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.values(value).every((v) => typeof v === "function" || isBaseChannel(v))) return true; + return false; +} +/** +* Check if a value is a StateGraphInit object (has state, stateSchema, or input with valid schema). +* +* @internal +*/ +function isStateGraphInit(value) { + if (typeof value !== "object" || value == null) return false; + const obj = value; + const hasState = "state" in obj && isStateDefinitionInit(obj.state); + const hasStateSchema = "stateSchema" in obj && isStateDefinitionInit(obj.stateSchema); + const hasInput = "input" in obj && isStateDefinitionInit(obj.input); + if (!hasState && !hasStateSchema && !hasInput) return false; + if ("input" in obj && obj.input != null && !isStateDefinitionInit(obj.input)) return false; + if ("output" in obj && obj.output != null && !isStateDefinitionInit(obj.output)) return false; + return true; +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/graph/state.js +var ROOT = "__root__"; +/** +* Reserved node name for the single shared error handler that is materialized +* when a graph-wide default error handler is set via +* {@link StateGraph.setNodeDefaults}. Every regular node that lacks its own +* `errorHandler` routes failures to this node. Mirrors Python's +* `__default_error_handler__`. +*/ +var DEFAULT_ERROR_HANDLER_NODE = "__default_error_handler__"; +var PartialStateSchema = Symbol.for("langgraph.state.partial"); +/** +* A graph whose nodes communicate by reading and writing to a shared state. +* Each node takes a defined `State` as input and returns a `Partial`. +* +* Each state key can optionally be annotated with a reducer function that +* will be used to aggregate the values of that key received from multiple nodes. +* The signature of a reducer function is (left: Value, right: UpdateValue) => Value. +* +* See {@link Annotation} for more on defining state. +* +* After adding nodes and edges to your graph, you must call `.compile()` on it before +* you can use it. +* +* @typeParam SD - The state definition used to construct the graph. Can be an +* {@link AnnotationRoot}, {@link StateSchema}, or Zod object schema. This is the +* primary generic from which `S` and `U` are derived. +* +* @typeParam S - The full state type representing the complete shape of your graph's +* state after all reducers have been applied. Automatically inferred from `SD`. +* +* @typeParam U - The update type representing what nodes can return to modify state. +* Typically a partial of the state type. Automatically inferred from `SD`. +* +* @typeParam N - Union of all node names in the graph (e.g., `"agent" | "tool"`). +* Accumulated as you call `.addNode()`. Used for type-safe routing. +* +* @typeParam I - The input schema definition. Set via the `input` option in the +* constructor to restrict what data the graph accepts when invoked. +* +* @typeParam O - The output schema definition. Set via the `output` option in the +* constructor to restrict what data the graph returns after execution. +* +* @typeParam C - The config/context schema definition. Set via the `context` option +* to define additional configuration passed at runtime. +* +* @typeParam NodeReturnType - Constrains what types nodes in this graph can return. +* +* @typeParam InterruptType - The type for {@link interrupt} resume values. Set via +* the `interrupt` option for typed human-in-the-loop patterns. +* +* @typeParam WriterType - The type for custom stream writers. Set via the `writer` +* option to enable typed custom streaming from within nodes. +* +* @example +* ```ts +* import { +* type BaseMessage, +* AIMessage, +* HumanMessage, +* } from "@langchain/core/messages"; +* import { StateGraph, Annotation } from "@langchain/langgraph"; +* +* // Define a state with a single key named "messages" that will +* // combine a returned BaseMessage or arrays of BaseMessages +* const StateAnnotation = Annotation.Root({ +* sentiment: Annotation, +* messages: Annotation({ +* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => { +* if (Array.isArray(right)) { +* return left.concat(right); +* } +* return left.concat([right]); +* }, +* default: () => [], +* }), +* }); +* +* const graphBuilder = new StateGraph(StateAnnotation); +* +* // A node in the graph that returns an object with a "messages" key +* // will update the state by combining the existing value with the returned one. +* const myNode = (state: typeof StateAnnotation.State) => { +* return { +* messages: [new AIMessage("Some new response")], +* sentiment: "positive", +* }; +* }; +* +* const graph = graphBuilder +* .addNode("myNode", myNode) +* .addEdge("__start__", "myNode") +* .addEdge("myNode", "__end__") +* .compile(); +* +* await graph.invoke({ messages: [new HumanMessage("how are you?")] }); +* +* // { +* // messages: [HumanMessage("how are you?"), AIMessage("Some new response")], +* // sentiment: "positive", +* // } +* ``` +*/ +var StateGraph = class extends Graph$1 { + channels = {}; + waitingEdges = /* @__PURE__ */ new Set(); + /** @internal */ + _schemaDefinition; + /** @internal */ + _schemaRuntimeDefinition; + /** @internal */ + _inputDefinition; + /** @internal */ + _inputRuntimeDefinition; + /** @internal */ + _outputDefinition; + /** @internal */ + _outputRuntimeDefinition; + /** + * Map schemas to managed values + * @internal + */ + _schemaDefinitions = /* @__PURE__ */ new Map(); + /** @internal */ + _metaRegistry = schemaMetaRegistry; + /** @internal Used only for typing. */ + _configSchema; + /** @internal */ + _configRuntimeSchema; + /** @internal */ + _interrupt; + /** @internal */ + _writer; + /** + * Graph-wide default node policies, resolved at `compile()` time. + * @internal + */ + _nodeDefaults = {}; + constructor(stateOrInit, options) { + super(); + const init = this._normalizeToStateGraphInit(stateOrInit, options); + const stateSchema = init.state ?? init.stateSchema ?? init.input; + if (!stateSchema) throw new StateGraphInputError(); + const stateChannelDef = this._getChannelsFromSchema(stateSchema); + this._schemaDefinition = stateChannelDef; + if (StateSchema.isInstance(stateSchema)) this._schemaRuntimeDefinition = stateSchema; + else if (isInteropZodObject(stateSchema)) this._schemaRuntimeDefinition = stateSchema; + if (init.input) if (StateSchema.isInstance(init.input)) this._inputRuntimeDefinition = init.input; + else if (isInteropZodObject(init.input)) this._inputRuntimeDefinition = init.input; + else this._inputRuntimeDefinition = PartialStateSchema; + else this._inputRuntimeDefinition = PartialStateSchema; + if (init.output) if (StateSchema.isInstance(init.output)) this._outputRuntimeDefinition = init.output; + else if (isInteropZodObject(init.output)) this._outputRuntimeDefinition = init.output; + else this._outputRuntimeDefinition = this._schemaRuntimeDefinition; + else this._outputRuntimeDefinition = this._schemaRuntimeDefinition; + const inputChannelDef = init.input ? this._getChannelsFromSchema(init.input) : stateChannelDef; + const outputChannelDef = init.output ? this._getChannelsFromSchema(init.output) : stateChannelDef; + this._inputDefinition = inputChannelDef; + this._outputDefinition = outputChannelDef; + this._addSchema(this._schemaDefinition); + this._addSchema(this._inputDefinition); + this._addSchema(this._outputDefinition); + if (init.context) { + if (isInteropZodObject(init.context)) this._configRuntimeSchema = init.context; + } + this._interrupt = init.interrupt; + this._writer = init.writer; + } + /** + * Set graph-wide default node policies that apply to every node in this + * graph. + * + * Per-node values passed to {@link addNode} always take precedence over these + * defaults. Defaults are resolved at {@link compile} time, so call order does + * not matter — you may call this before or after `addNode`, including as the + * last step before `compile()`. Calling it multiple times merges the provided + * fields, with later calls overriding earlier ones on a per-field basis. + * + * Policies set here are **not** inherited by subgraphs. + * + * `retryPolicy` and `timeout` defaults apply to **all** nodes, including + * auto-generated error-handler nodes. `cachePolicy` and `errorHandler` + * defaults apply to **regular nodes only** — caching an error-handler result + * is unsafe, and a handler must never catch its own (or another handler's) + * failure. + * + * @param defaults - The default node policies to apply. + * @returns The builder instance, for chaining. + * + * @example Call before `addNode` + * ```ts + * const graph = new StateGraph(State) + * .setNodeDefaults({ + * retryPolicy: { maxAttempts: 3 }, + * cachePolicy: { ttl: 60 }, + * timeout: 60_000, + * errorHandler: (state, { node, error }) => ({ lastError: error.message }), + * }) + * .addNode("a", nodeA) + * .addNode("b", nodeB, { retryPolicy: { maxAttempts: 5 } }) // overrides default + * .addEdge(START, "a") + * .compile(); + * ``` + * + * @example Call after `addNode`, immediately before `compile()` + * ```ts + * const graph = new StateGraph(State) + * .addNode("a", nodeA) + * .addNode("b", nodeB, { retryPolicy: { maxAttempts: 5 } }) // overrides default + * .addEdge(START, "a") + * .setNodeDefaults({ + * retryPolicy: { maxAttempts: 3 }, + * cachePolicy: { ttl: 60 }, + * }) + * .compile(); + * ``` + */ + setNodeDefaults(defaults) { + if (defaults.retryPolicy !== void 0) this._nodeDefaults.retryPolicy = defaults.retryPolicy; + if (defaults.cachePolicy !== void 0) this._nodeDefaults.cachePolicy = typeof defaults.cachePolicy === "boolean" ? defaults.cachePolicy ? {} : void 0 : defaults.cachePolicy; + if (defaults.timeout !== void 0) this._nodeDefaults.timeout = coerceTimeoutPolicy(defaults.timeout); + if (defaults.errorHandler !== void 0) this._nodeDefaults.errorHandler = defaults.errorHandler; + return this; + } + /** + * Build the shared spec for a graph-wide default error handler, or + * `undefined` when {@link setNodeDefaults} did not configure one. The spec is + * installed under {@link DEFAULT_ERROR_HANDLER_NODE} for the duration of a + * single {@link compile} call and routes failures from every regular node + * that lacks its own handler. + * @internal + */ + _createDefaultErrorHandlerSpec() { + const userHandler = this._nodeDefaults.errorHandler; + if (userHandler === void 0) return; + return { + runnable: new RunnableCallable({ + func: (state, config) => { + const nodeError = config?.configurable?.[CONFIG_KEY_NODE_ERROR]; + return userHandler(state, nodeError, config); + }, + name: DEFAULT_ERROR_HANDLER_NODE, + trace: false + }), + metadata: void 0, + input: this._schemaDefinition, + retryPolicy: void 0, + cachePolicy: void 0, + isErrorHandler: true + }; + } + /** + * Normalize all constructor input patterns to a unified StateGraphInit object. + * @internal + */ + _normalizeToStateGraphInit(stateOrInit, options) { + if (isStateGraphInit(stateOrInit)) { + if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) return { + ...stateOrInit, + context: options + }; + const opts = options; + return { + ...stateOrInit, + input: stateOrInit.input ?? opts?.input, + output: stateOrInit.output ?? opts?.output, + context: stateOrInit.context ?? opts?.context, + interrupt: stateOrInit.interrupt ?? opts?.interrupt, + writer: stateOrInit.writer ?? opts?.writer, + nodes: stateOrInit.nodes ?? opts?.nodes + }; + } + if (isStateDefinitionInit(stateOrInit)) { + if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) return { + state: stateOrInit, + context: options + }; + const opts = options; + return { + state: stateOrInit, + input: opts?.input, + output: opts?.output, + context: opts?.context, + interrupt: opts?.interrupt, + writer: opts?.writer, + nodes: opts?.nodes + }; + } + if (isStateGraphArgs(stateOrInit)) return { state: _getChannels(stateOrInit.channels) }; + throw new StateGraphInputError(); + } + /** + * Convert any supported schema type to a StateDefinition (channel map). + * @internal + */ + _getChannelsFromSchema(schema) { + if (StateSchema.isInstance(schema)) return schema.getChannels(); + if (isInteropZodObject(schema)) return this._metaRegistry.getChannelsForSchema(schema); + if (typeof schema === "object" && "lc_graph_name" in schema && schema.lc_graph_name === "AnnotationRoot") return schema.spec; + if (typeof schema === "object" && !Array.isArray(schema) && Object.keys(schema).length > 0) return schema; + throw new StateGraphInputError("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition."); + } + get allEdges() { + return /* @__PURE__ */ new Set([...this.edges, ...Array.from(this.waitingEdges).flatMap(([starts, end]) => starts.map((start) => [start, end]))]); + } + _addSchema(stateDefinition) { + if (this._schemaDefinitions.has(stateDefinition)) return; + this._schemaDefinitions.set(stateDefinition, stateDefinition); + for (const [key, val] of Object.entries(stateDefinition)) { + let channel; + if (typeof val === "function") channel = val(); + else channel = val; + if (this.channels[key] !== void 0) { + if (!this.channels[key].equals(channel)) { + if (channel.lc_graph_name !== "LastValue") throw new Error(`Channel "${key}" already exists with a different type.`); + } + } else this.channels[key] = channel; + } + } + addNode(...args) { + function isMultipleNodes(args) { + return args.length >= 1 && typeof args[0] !== "string"; + } + const nodes = isMultipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]).map(([key, action]) => [key, action]) : [[ + args[0], + args[1], + args[2] + ]]; + if (nodes.length === 0) throw new Error("No nodes provided in `addNode`"); + for (const [key, action, options] of nodes) { + if (key in this.channels) throw new Error(`${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`); + for (const reservedChar of ["|", ":"]) if (key.includes(reservedChar)) throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); + this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); + if (key in this.nodes) throw new Error(`Node \`${key}\` already present.`); + if (key === "__end__" || key === "__start__") throw new Error(`Node \`${key}\` is reserved.`); + let inputSpec = this._schemaDefinition; + if (options?.input !== void 0) inputSpec = this._getChannelsFromSchema(options.input); + this._addSchema(inputSpec); + let runnable; + if (Runnable.isRunnable(action)) runnable = action; + else if (typeof action === "function") runnable = new RunnableCallable({ + func: action, + name: key, + trace: false + }); + else runnable = _coerceToRunnable(action); + const rawCachePolicy = options?.cachePolicy; + let cachePolicy; + if (rawCachePolicy !== void 0) cachePolicy = typeof rawCachePolicy === "boolean" ? rawCachePolicy ? {} : false : rawCachePolicy; + let errorHandlerNode; + if (options?.errorHandler !== void 0) { + errorHandlerNode = `__error_handler__${key}`; + if (errorHandlerNode in this.nodes) throw new Error(`Cannot add error handler to node \`${key}\`: the reserved name \`${errorHandlerNode}\` is already in use. StateGraph registers \`__error_handler__\` when you pass \`errorHandler\` in addNode options. Remove or rename the existing node with that name (for example, you may have added it manually).`); + const userHandler = options.errorHandler; + const handlerSpec = { + runnable: new RunnableCallable({ + func: (state, config) => { + const nodeError = config?.configurable?.[CONFIG_KEY_NODE_ERROR]; + return userHandler(state, nodeError, config); + }, + name: errorHandlerNode, + trace: false + }), + metadata: void 0, + input: inputSpec ?? this._schemaDefinition, + retryPolicy: void 0, + cachePolicy: void 0, + isErrorHandler: true + }; + this.nodes[errorHandlerNode] = handlerSpec; + } + const nodeSpec = { + runnable, + retryPolicy: options?.retryPolicy, + cachePolicy, + timeout: coerceTimeoutPolicy(options?.timeout), + metadata: options?.metadata, + input: inputSpec ?? this._schemaDefinition, + subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, + ends: options?.ends, + defer: options?.defer, + errorHandlerNode + }; + this.nodes[key] = nodeSpec; + } + return this; + } + addEdge(startKey, endKey) { + if (typeof startKey === "string") return super.addEdge(startKey, endKey); + if (this.compiled) console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); + for (const start of startKey) { + if (start === "__end__") throw new Error("END cannot be a start node"); + if (!Object.keys(this.nodes).some((node) => node === start)) throw new Error(`Need to add a node named "${start}" first`); + } + if (endKey === "__end__") throw new Error("END cannot be an end node"); + if (!Object.keys(this.nodes).some((node) => node === endKey)) throw new Error(`Need to add a node named "${endKey}" first`); + this.waitingEdges.add([startKey, endKey]); + return this; + } + addSequence(nodes) { + const parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes); + if (parsedNodes.length === 0) throw new Error("Sequence requires at least one node."); + let previousNode; + for (const [key, action, options] of parsedNodes) { + if (key in this.nodes) throw new Error(`Node names must be unique: node with the name "${key}" already exists.`); + const validKey = key; + this.addNode(key, action, options); + if (previousNode != null) this.addEdge(previousNode, validKey); + previousNode = validKey; + } + return this; + } + compile({ checkpointer, store, cache, interruptBefore, interruptAfter, name, description, transformers } = {}) { + const defaultErrorHandlerSpec = this._createDefaultErrorHandlerSpec(); + if (defaultErrorHandlerSpec !== void 0) { + if (DEFAULT_ERROR_HANDLER_NODE in this.nodes) throw new Error(`Cannot apply a default error handler: the reserved node name \`${DEFAULT_ERROR_HANDLER_NODE}\` is already in use. setNodeDefaults({ errorHandler }) registers a node with that name; rename the conflicting node.`); + this.nodes[DEFAULT_ERROR_HANDLER_NODE] = defaultErrorHandlerSpec; + } + try { + return this._compileResolved({ + checkpointer, + store, + cache, + interruptBefore, + interruptAfter, + name, + description, + transformers, + defaultErrorHandlerNode: defaultErrorHandlerSpec !== void 0 ? DEFAULT_ERROR_HANDLER_NODE : void 0 + }); + } finally { + if (defaultErrorHandlerSpec !== void 0) delete this.nodes[DEFAULT_ERROR_HANDLER_NODE]; + } + } + /** @internal */ + _compileResolved({ checkpointer, store, cache, interruptBefore, interruptAfter, name, description, transformers, defaultErrorHandlerNode }) { + this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); + const outputKeys = Object.keys(this._schemaDefinitions.get(this._outputDefinition)); + const outputChannels = outputKeys.length === 1 && outputKeys[0] === ROOT ? ROOT : outputKeys; + const streamKeys = Object.keys(this.channels); + const streamChannels = streamKeys.length === 1 && streamKeys[0] === ROOT ? ROOT : streamKeys; + const userInterrupt = this._interrupt; + const compiled = new CompiledStateGraph({ + builder: this, + checkpointer, + interruptAfter, + interruptBefore, + autoValidate: false, + nodes: {}, + channels: { + ...this.channels, + [START]: new EphemeralValue() + }, + inputChannels: START, + outputChannels, + streamChannels, + streamMode: "updates", + store, + cache, + name, + description, + userInterrupt, + streamTransformers: transformers + }); + compiled.attachNode(START); + const nodeDefaults = this._nodeDefaults; + const hasNodeDefaults = nodeDefaults.retryPolicy !== void 0 || nodeDefaults.cachePolicy !== void 0 || nodeDefaults.timeout !== void 0 || defaultErrorHandlerNode !== void 0; + for (const [key, node] of Object.entries(this.nodes)) { + const isErrorHandlerNode = node.isErrorHandler === true; + const resolvedNode = hasNodeDefaults ? { + ...node, + retryPolicy: node.retryPolicy ?? nodeDefaults.retryPolicy, + cachePolicy: isErrorHandlerNode ? void 0 : node.cachePolicy === false ? void 0 : node.cachePolicy ?? nodeDefaults.cachePolicy, + timeout: node.timeout ?? nodeDefaults.timeout, + errorHandlerNode: !isErrorHandlerNode && defaultErrorHandlerNode !== void 0 && node.errorHandlerNode === void 0 ? defaultErrorHandlerNode : node.errorHandlerNode + } : node; + compiled.attachNode(key, resolvedNode); + } + compiled.attachBranch(START, SELF, _getControlBranch(), { withReader: false }); + for (const [key] of Object.entries(this.nodes)) compiled.attachBranch(key, SELF, _getControlBranch(), { withReader: false }); + for (const [start, end] of this.edges) compiled.attachEdge(start, end); + for (const [starts, end] of this.waitingEdges) compiled.attachEdge(starts, end); + for (const [start, branches] of Object.entries(this.branches)) for (const [name, branch] of Object.entries(branches)) compiled.attachBranch(start, name, branch); + return compiled.validate(); + } +}; +function _getChannels(schema) { + const channels = {}; + for (const [name, val] of Object.entries(schema)) if (name === ROOT) channels[name] = getChannel(val); + else channels[name] = getChannel(val); + return channels; +} +/** +* Final result from building and compiling a {@link StateGraph}. +* Should not be instantiated directly, only using the StateGraph `.compile()` +* instance method. +* +* @typeParam S - The full state type representing the complete shape of your graph's +* state after all reducers have been applied. This is the type you receive when +* reading state in nodes or after invoking the graph. +* +* @typeParam U - The update type representing what nodes can return to modify state. +* Typically a partial of the state type, allowing nodes to update only specific fields. +* Can also include {@link Command} objects for advanced control flow. +* +* @typeParam N - Union of all node names in the graph (e.g., `"agent" | "tool"`). +* Used for type-safe routing with {@link Command.goto} and edge definitions. +* +* @typeParam I - The input schema definition. Determines what shape of data the graph +* accepts when invoked. Defaults to the main state schema if not explicitly set. +* +* @typeParam O - The output schema definition. Determines what shape of data the graph +* returns after execution. Defaults to the main state schema if not explicitly set. +* +* @typeParam C - The config/context schema definition. Defines additional configuration +* that can be passed to the graph at runtime via {@link LangGraphRunnableConfig}. +* +* @typeParam NodeReturnType - Constrains what types nodes in this graph can return. +* Useful for enforcing consistent return patterns across all nodes. +* +* @typeParam InterruptType - The type of values that can be passed when resuming from +* an {@link interrupt}. Used with human-in-the-loop patterns. +* +* @typeParam WriterType - The type for custom stream writers. Used with the `writer` +* option to enable typed custom streaming from within nodes. +* +* @typeParam TStreamTransformers - Stream transformer factories registered at +* compile time via the `transformers` option. Used to type extensions on +* `streamEvents(..., { version: "v3" })`. +*/ +var CompiledStateGraph = class extends CompiledGraph { + /** + * The description of the compiled graph. + * This is used by the supervisor agent to describe the handoff to the agent. + */ + description; + /** @internal */ + _metaRegistry = schemaMetaRegistry; + constructor({ description, ...rest }) { + super(rest); + this.description = description; + } + attachNode(key, node) { + let outputKeys; + if (key === "__start__") outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([k]) => k); + else outputKeys = Object.keys(this.builder.channels); + function _getRoot(input) { + if (isCommand(input)) { + if (input.graph === Command.PARENT) return null; + return input._updateAsTuples(); + } else if (Array.isArray(input) && input.length > 0 && input.some((i) => isCommand(i))) { + const updates = []; + for (const i of input) if (isCommand(i)) { + if (i.graph === Command.PARENT) continue; + updates.push(...i._updateAsTuples()); + } else updates.push([ROOT, i]); + return updates; + } else if (input != null) return [[ROOT, input]]; + return null; + } + const nodeKey = key; + const validateStateUpdates = async (updates) => { + if (updates == null || updates.length === 0) return updates; + const schemaDef = this.builder._schemaRuntimeDefinition; + if (StateSchema.isInstance(schemaDef)) { + const schemaKeys = new Set(schemaDef.getChannelKeys()); + return Promise.all(updates.map(async ([k, v]) => { + if (!schemaKeys.has(k)) return [k, v]; + const parsed = await schemaDef.validateInput({ [k]: v }); + return [k, Object.prototype.hasOwnProperty.call(parsed, k) ? parsed[k] : v]; + })); + } + if (isInteropZodObject(schemaDef)) { + const schemaKeys = new Set(Object.keys(getInteropZodObjectShape(schemaDef))); + if (updates.filter(([k]) => schemaKeys.has(k)).length === 0) return updates; + const updateSchema = interopZodObjectPartial(this._metaRegistry.getExtendedChannelSchemas(schemaDef, { withReducerSchema: true })); + const valueSchema = interopZodObjectPartial(schemaDef); + return updates.map(([k, v]) => { + if (!schemaKeys.has(k)) return [k, v]; + const [isOverwrite, overwriteValue] = _getOverwriteValue(v); + if (isOverwrite) { + const parsed = interopParse(valueSchema, { [k]: overwriteValue }); + return [k, Object.prototype.hasOwnProperty.call(parsed, k) ? { [OVERWRITE]: parsed[k] } : v]; + } + const parsed = interopParse(updateSchema, { [k]: v }); + return [k, Object.prototype.hasOwnProperty.call(parsed, k) ? parsed[k] : v]; + }); + } + return updates; + }; + async function _getUpdates(input) { + if (!input) return null; + else if (isCommand(input)) { + if (input.graph === Command.PARENT) return null; + return validateStateUpdates(input._updateAsTuples().filter(([k]) => outputKeys.includes(k))); + } else if (Array.isArray(input) && input.length > 0 && input.some(isCommand)) { + const updates = []; + for (const item of input) if (isCommand(item)) { + if (item.graph === Command.PARENT) continue; + updates.push(...item._updateAsTuples().filter(([k]) => outputKeys.includes(k))); + } else { + const itemUpdates = await _getUpdates(item); + if (itemUpdates) updates.push(...itemUpdates ?? []); + } + return validateStateUpdates(updates); + } else if (typeof input === "object" && !Array.isArray(input)) return validateStateUpdates(Object.entries(input).filter(([k]) => outputKeys.includes(k))); + else { + const typeofInput = Array.isArray(input) ? "array" : typeof input; + throw new InvalidUpdateError(`Expected node "${nodeKey.toString()}" to return an object or an array containing at least one Command object, received ${typeofInput}`, { lc_error_code: "INVALID_GRAPH_NODE_RETURN_VALUE" }); + } + } + const stateWriteEntries = [{ + value: PASSTHROUGH, + mapper: new RunnableCallable({ + func: outputKeys.length && outputKeys[0] === ROOT ? _getRoot : _getUpdates, + trace: false, + recurse: false + }) + }]; + if (key === "__start__") this.nodes[key] = new PregelNode({ + tags: [TAG_HIDDEN], + triggers: [START], + channels: [START], + writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])] + }); + else { + const inputDefinition = node?.input ?? this.builder._schemaDefinition; + const inputValues = Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map((k) => [k, k])); + const isSingleInput = Object.keys(inputValues).length === 1 && ROOT in inputValues; + const branchChannel = `branch:to:${key}`; + this.channels[branchChannel] = node?.defer ? new LastValueAfterFinish() : new EphemeralValue(false); + const nodeCachePolicy = node?.cachePolicy; + const cachePolicy = nodeCachePolicy === false ? void 0 : nodeCachePolicy; + this.nodes[key] = new PregelNode({ + triggers: [branchChannel], + channels: isSingleInput ? Object.keys(inputValues) : inputValues, + writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])], + mapper: isSingleInput ? void 0 : (input) => { + return Object.fromEntries(Object.entries(input).filter(([k]) => k in inputValues)); + }, + bound: node?.runnable, + metadata: node?.metadata, + retryPolicy: node?.retryPolicy, + cachePolicy, + timeout: node?.timeout, + subgraphs: node?.subgraphs, + ends: node?.ends, + isErrorHandler: node?.isErrorHandler, + errorHandlerNode: node?.errorHandlerNode + }); + } + } + attachEdge(starts, end) { + if (end === "__end__") return; + if (typeof starts === "string") this.nodes[starts].writers.push(new ChannelWrite([{ + channel: `branch:to:${end}`, + value: null + }], [TAG_HIDDEN])); + else if (Array.isArray(starts)) { + const channelName = `join:${starts.join("+")}:${end}`; + this.channels[channelName] = this.builder.nodes[end].defer ? new NamedBarrierValueAfterFinish(new Set(starts)) : new NamedBarrierValue(new Set(starts)); + this.nodes[end].triggers.push(channelName); + for (const start of starts) this.nodes[start].writers.push(new ChannelWrite([{ + channel: channelName, + value: start + }], [TAG_HIDDEN])); + } + } + attachBranch(start, _, branch, options = { withReader: true }) { + const branchWriter = async (packets, config) => { + const filteredPackets = packets.filter((p) => p !== END); + if (!filteredPackets.length) return; + const writes = filteredPackets.map((p) => { + if (_isSend(p)) return p; + return { + channel: p === "__end__" ? p : `branch:to:${p}`, + value: start + }; + }); + await ChannelWrite.doWrite({ + ...config, + tags: (config.tags ?? []).concat([TAG_HIDDEN]) + }, writes); + }; + this.nodes[start].writers.push(branch.run(branchWriter, options.withReader ? (config) => ChannelRead.doRead(config, this.streamChannels ?? this.outputChannels, true) : void 0)); + } + async _validateInput(input) { + if (input == null) return input; + const inputDef = this.builder._inputRuntimeDefinition; + const schemaDef = this.builder._schemaRuntimeDefinition; + if (StateSchema.isInstance(inputDef)) { + if (isCommand(input)) { + const parsedInput = input; + if (input.update) parsedInput.update = await inputDef.validateInput(Array.isArray(input.update) ? Object.fromEntries(input.update) : input.update); + return parsedInput; + } + return await inputDef.validateInput(input); + } + if (inputDef === PartialStateSchema && StateSchema.isInstance(schemaDef)) { + if (isCommand(input)) { + const parsedInput = input; + if (input.update) parsedInput.update = await schemaDef.validateInput(Array.isArray(input.update) ? Object.fromEntries(input.update) : input.update); + return parsedInput; + } + return await schemaDef.validateInput(input); + } + const schema = (() => { + const apply = (schema) => { + if (schema == null) return void 0; + return this._metaRegistry.getExtendedChannelSchemas(schema, { withReducerSchema: true }); + }; + if (isInteropZodObject(inputDef)) return apply(inputDef); + if (inputDef === PartialStateSchema) { + if (isInteropZodObject(schemaDef)) return interopZodObjectPartial(apply(schemaDef)); + return; + } + })(); + if (isCommand(input)) { + const parsedInput = input; + if (input.update && schema != null) { + const updateObj = Array.isArray(input.update) ? Object.fromEntries(input.update) : input.update; + const parsed = interopParse(schema, updateObj); + parsedInput.update = Object.fromEntries(Object.keys(updateObj).map((k) => [k, parsed[k]])); + } + return parsedInput; + } + if (schema != null) return interopParse(schema, input); + return input; + } + isInterrupted(input) { + return isInterrupted(input); + } + async _validateContext(config) { + const configSchema = this.builder._configRuntimeSchema; + if (isInteropZodObject(configSchema)) interopParse(configSchema, config); + return config; + } +}; +/** +* Check if value is a legacy StateGraphArgs with channels. +* @internal +* @deprecated Use StateGraphInit instead +*/ +function isStateGraphArgs(obj) { + return typeof obj === "object" && obj !== null && obj.channels !== void 0; +} +function _controlBranch(value) { + if (_isSend(value)) return [value]; + const commands = []; + if (isCommand(value)) commands.push(value); + else if (Array.isArray(value)) commands.push(...value.filter(isCommand)); + const destinations = []; + for (const command of commands) { + if (command.graph === Command.PARENT) throw new ParentCommand(command); + if (_isSend(command.goto)) destinations.push(command.goto); + else if (typeof command.goto === "string") destinations.push(command.goto); + else if (Array.isArray(command.goto)) destinations.push(...command.goto); + } + return destinations; +} +function _getControlBranch() { + return new Branch({ path: new RunnableCallable({ + func: _controlBranch, + tags: [TAG_HIDDEN], + trace: false, + recurse: false, + name: "" + }) }); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/func/index.js +/** +* Define a LangGraph workflow using the `entrypoint` function. +* +* ### Function signature +* +* The wrapped function must accept at most **two parameters**. The first parameter +* is the input to the function. The second (optional) parameter is a +* {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to +* the function, you can pass them as an object. +* +* ### Helper functions +* +* #### Streaming +* To write data to the "custom" stream, use the {@link getWriter} function, or the +* {@link LangGraphRunnableConfig.writer} property. +* +* #### State management +* The {@link getPreviousState} function can be used to access the previous state +* that was returned from the last invocation of the entrypoint on the same thread id. +* +* If you wish to save state other than the return value, you can use the +* {@link entrypoint.final} function. +* +* @typeParam InputT - The type of input the entrypoint accepts +* @typeParam OutputT - The type of output the entrypoint produces +* @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint +* @param func - The function that executes this entrypoint +* @returns A {@link Pregel} instance that can be run to execute the workflow +* +* @example Using entrypoint and tasks +* ```typescript +* import { task, entrypoint } from "@langchain/langgraph"; +* import { MemorySaver } from "@langchain/langgraph-checkpoint"; +* import { interrupt, Command } from "@langchain/langgraph"; +* +* const composeEssay = task("compose", async (topic: string) => { +* await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation +* return `An essay about ${topic}`; +* }); +* +* const reviewWorkflow = entrypoint({ +* name: "review", +* checkpointer: new MemorySaver() +* }, async (topic: string) => { +* const essay = await composeEssay(topic); +* const humanReview = await interrupt({ +* question: "Please provide a review", +* essay +* }); +* return { +* essay, +* review: humanReview +* }; +* }); +* +* // Example configuration for the workflow +* const config = { +* configurable: { +* thread_id: "some_thread" +* } +* }; +* +* // Topic for the essay +* const topic = "cats"; +* +* // Stream the workflow to generate the essay and await human review +* for await (const result of reviewWorkflow.stream(topic, config)) { +* console.log(result); +* } +* +* // Example human review provided after the interrupt +* const humanReview = "This essay is great."; +* +* // Resume the workflow with the provided human review +* for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) { +* console.log(result); +* } +* ``` +* +* @example Accessing the previous return value +* ```typescript +* import { entrypoint, getPreviousState } from "@langchain/langgraph"; +* import { MemorySaver } from "@langchain/langgraph-checkpoint"; +* +* const accumulator = entrypoint({ +* name: "accumulator", +* checkpointer: new MemorySaver() +* }, async (input: string) => { +* const previous = getPreviousState(); +* return previous !== undefined ? `${previous } ${input}` : input; +* }); +* +* const config = { +* configurable: { +* thread_id: "some_thread" +* } +* }; +* await accumulator.invoke("hello", config); // returns "hello" +* await accumulator.invoke("world", config); // returns "hello world" +* ``` +* +* @example Using entrypoint.final to save a value +* ```typescript +* import { entrypoint, getPreviousState } from "@langchain/langgraph"; +* import { MemorySaver } from "@langchain/langgraph-checkpoint"; +* +* const myWorkflow = entrypoint({ +* name: "accumulator", +* checkpointer: new MemorySaver() +* }, async (num: number) => { +* const previous = getPreviousState(); +* +* // This will return the previous value to the caller, saving +* // 2 * num to the checkpoint, which will be used in the next invocation +* // for the `previous` parameter. +* return entrypoint.final({ +* value: previous ?? 0, +* save: 2 * num +* }); +* }); +* +* const config = { +* configurable: { +* thread_id: "some_thread" +* } +* }; +* +* await myWorkflow.invoke(3, config); // 0 (previous was undefined) +* await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation) +* ``` +* @category Functional API +*/ +var entrypoint = function entrypoint(optionsOrName, func) { + const { name, checkpointer, store, cache } = typeof optionsOrName === "string" ? { + name: optionsOrName, + checkpointer: void 0, + store: void 0 + } : optionsOrName; + const timeout = coerceTimeoutPolicy(typeof optionsOrName === "string" ? void 0 : optionsOrName.timeout); + if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write."); + const streamMode = "updates"; + const bound = getRunnableForEntrypoint(name, func); + function isEntrypointFinal(value) { + return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "__pregel_final"; + } + const pluckReturnValue = new RunnableCallable({ + name: "pluckReturnValue", + func: (value) => { + return isEntrypointFinal(value) ? value.value : value; + } + }); + const pluckSaveValue = new RunnableCallable({ + name: "pluckSaveValue", + func: (value) => { + return isEntrypointFinal(value) ? value.save : value; + } + }); + const entrypointNode = new PregelNode({ + bound, + triggers: [START], + channels: [START], + timeout, + writers: [new ChannelWrite([{ + channel: END, + value: PASSTHROUGH, + mapper: pluckReturnValue + }, { + channel: PREVIOUS, + value: PASSTHROUGH, + mapper: pluckSaveValue + }], [TAG_HIDDEN])] + }); + return new Pregel({ + name, + checkpointer, + nodes: { [name]: entrypointNode }, + channels: { + [START]: new EphemeralValue(), + [END]: new LastValue(), + [PREVIOUS]: new LastValue() + }, + inputChannels: START, + outputChannels: END, + streamChannels: END, + streamMode, + store, + cache + }); +}; +entrypoint.final = function final({ value, save }) { + return { + value, + save, + __lg_type: "__pregel_final" + }; +}; +Annotation.Root({ messages: Annotation({ + reducer: messagesStateReducer, + default: () => [] +}) }); +/** +* Prebuilt schema meta for Zod state definition. +* +* @example +* ```ts +* import { z } from "zod/v4-mini"; +* import { MessagesZodState, StateGraph } from "@langchain/langgraph"; +* +* const AgentState = z.object({ +* messages: z.custom().register(registry, MessagesZodMeta), +* }); +* ``` +*/ +var MessagesZodMeta = { + reducer: { fn: messagesStateReducer }, + jsonSchemaExtra: { langgraph_type: "messages" }, + default: () => [] +}; +objectType({ messages: withLangGraph(custom$1(), MessagesZodMeta) }); +//#endregion +//#region node_modules/@langchain/langgraph/dist/index.js +var dist_exports = /* @__PURE__ */ __exportAll({ + END: () => END, + INTERRUPT: () => INTERRUPT$1, + REMOVE_ALL_MESSAGES: () => REMOVE_ALL_MESSAGES, + START: () => START, + interrupt: () => interrupt +}); +initializeAsyncLocalStorageSingleton(); +//#endregion +//#region node_modules/@langchain/langgraph/dist/graph/zod/plugin.js +var metaSymbol = Symbol.for("langgraph-zod"); +if (!(metaSymbol in globalThis)) globalThis[metaSymbol] = /* @__PURE__ */ new WeakSet(); +function applyPluginPrototype(prototype) { + const cache = globalThis[metaSymbol]; + if (cache.has(prototype)) return; + Object.defineProperty(prototype, "langgraph", { get() { + const zodThis = this; + return { + metadata(jsonSchemaExtra) { + return withLangGraph(zodThis, { jsonSchemaExtra }); + }, + reducer(fn, schema) { + return withLangGraph(zodThis, { + default: getInteropZodDefaultGetter(zodThis), + reducer: { + schema, + fn + } + }); + } + }; + } }); + cache.add(prototype); +} +try { + applyPluginPrototype(ZodType$1.prototype); + applyPluginPrototype(ZodType.prototype); +} catch (error) { + throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.", { cause: error }); +} +//#endregion +//#region node_modules/@langchain/langgraph/dist/graph/zod/zod-registry.js +/** +* A Zod v4-compatible meta registry that extends the base registry. +* +* This registry allows you to associate and retrieve metadata for Zod schemas, +* leveraging the base registry for storage. It is compatible with Zod v4 and +* interoperates with the base registry to ensure consistent metadata management +* across different Zod versions. +* +* @template Meta - The type of metadata associated with each schema. +* @template Schema - The Zod schema type. +*/ +var LanggraphZodMetaRegistry = class extends $ZodRegistry { + /** + * Creates a new LanggraphZodMetaRegistry instance. + * + * @param parent - The base SchemaMetaRegistry to use for metadata storage. + */ + constructor(parent) { + super(); + this.parent = parent; + this._map = this.parent._map; + } + add(schema, ..._meta) { + const firstMeta = _meta[0]; + if (firstMeta && !firstMeta?.default) { + const defaultValueGetter = getInteropZodDefaultGetter(schema); + if (defaultValueGetter != null) firstMeta.default = defaultValueGetter; + } + return super.add(schema, ..._meta); + } +}; +new LanggraphZodMetaRegistry(schemaMetaRegistry); +//#endregion +export { END as _, REMOVE_ALL_MESSAGES as a, isCommand as b, ReducedValue as c, StreamChannel as d, getConfig as f, Command as g, isGraphInterrupt as h, MessagesValue as i, interrupt as l, isGraphBubbleUp as m, StateGraph as n, StateSchema as o, getCurrentTaskInput as p, schemaMetaRegistry as r, UntrackedValue as s, dist_exports as t, createMessagesTransformer as u, START as v, Send as y }; diff --git a/.vercel/output/functions/__server.func/_libs/@langchain/langgraph-sdk+[...].mjs b/.vercel/output/functions/__server.func/_libs/@langchain/langgraph-sdk+[...].mjs new file mode 100644 index 0000000..df30cba --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/@langchain/langgraph-sdk+[...].mjs @@ -0,0 +1,7443 @@ +import { r as __exportAll } from "../../_runtime.mjs"; +import { An as HumanMessage, Dn as SystemMessage, Ln as ToolMessage, gn as v7, kn as RemoveMessage, wn as coerceMessageLikeToMessage, xn as AIMessage } from "./anthropic+[...].mjs"; +//#region node_modules/@langchain/langgraph-sdk/dist/singletons/fetch.js +var DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); +var LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("lg:fetch_implementation"); +/** +* @internal +*/ +var _getFetchImplementation = () => { + return globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? DEFAULT_FETCH_IMPLEMENTATION; +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/node_modules/.pnpm/is-network-error@1.3.1/node_modules/is-network-error/index.js +var objectToString = Object.prototype.toString; +var isError$1 = (value) => objectToString.call(value) === "[object Error]"; +var errorMessages = /* @__PURE__ */ new Set([ + "network error", + "NetworkError when attempting to fetch resource.", + "The Internet connection appears to be offline.", + "Network request failed", + "fetch failed", + "terminated", + " A network error occurred.", + "Network connection lost" +]); +function isNetworkError$1(error) { + if (!(error && isError$1(error) && error.name === "TypeError" && typeof error.message === "string")) return false; + const { message, stack } = error; + if (message === "Load failed") return stack === void 0 || "__sentry_captured__" in error; + if (message.startsWith("error sending request for url")) return true; + if (message === "Failed to fetch" || message.startsWith("Failed to fetch (") && message.endsWith(")")) return true; + return errorMessages.has(message); +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/node_modules/.pnpm/p-retry@7.1.1/node_modules/p-retry/index.js +function validateRetries(retries) { + if (typeof retries === "number") { + if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number."); + if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); + } else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity."); +} +function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) { + if (value === void 0) return; + if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); + if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`); + if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`); +} +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; + } +}; +function calculateDelay(retriesConsumed, options) { + const attempt = Math.max(1, retriesConsumed + 1); + const random = options.randomize ? Math.random() + 1 : 1; + let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); + timeout = Math.min(timeout, options.maxTimeout); + return timeout; +} +function calculateRemainingTime(start, max) { + if (!Number.isFinite(max)) return max; + return max - (performance.now() - start); +} +async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) { + const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`); + if (normalizedError instanceof AbortError) throw normalizedError.originalError; + const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries; + const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; + const context = Object.freeze({ + error: normalizedError, + attemptNumber, + retriesLeft, + retriesConsumed + }); + await options.onFailedAttempt(context); + if (calculateRemainingTime(startTime, maxRetryTime) <= 0) throw normalizedError; + const consumeRetry = await options.shouldConsumeRetry(context); + const remainingTime = calculateRemainingTime(startTime, maxRetryTime); + if (remainingTime <= 0 || retriesLeft <= 0) throw normalizedError; + if (normalizedError instanceof TypeError && !isNetworkError$1(normalizedError)) { + if (consumeRetry) throw normalizedError; + options.signal?.throwIfAborted(); + return false; + } + if (!await options.shouldRetry(context)) throw normalizedError; + if (!consumeRetry) { + options.signal?.throwIfAborted(); + return false; + } + const delayTime = calculateDelay(retriesConsumed, options); + const finalDelay = Math.min(delayTime, remainingTime); + options.signal?.throwIfAborted(); + if (finalDelay > 0) await new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(timeoutToken); + options.signal?.removeEventListener("abort", onAbort); + reject(options.signal.reason); + }; + const timeoutToken = setTimeout(() => { + options.signal?.removeEventListener("abort", onAbort); + resolve(); + }, finalDelay); + if (options.unref) timeoutToken.unref?.(); + options.signal?.addEventListener("abort", onAbort, { once: true }); + }); + options.signal?.throwIfAborted(); + return true; +} +async function pRetry$1(input, options = {}) { + options = { ...options }; + validateRetries(options.retries); + if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); + options.retries ??= 10; + options.factor ??= 2; + options.minTimeout ??= 1e3; + options.maxTimeout ??= Number.POSITIVE_INFINITY; + options.maxRetryTime ??= Number.POSITIVE_INFINITY; + options.randomize ??= false; + options.onFailedAttempt ??= () => {}; + options.shouldRetry ??= () => true; + options.shouldConsumeRetry ??= () => true; + validateNumberOption("factor", options.factor, { + min: 0, + allowInfinity: false + }); + validateNumberOption("minTimeout", options.minTimeout, { + min: 0, + allowInfinity: false + }); + validateNumberOption("maxTimeout", options.maxTimeout, { + min: 0, + allowInfinity: true + }); + validateNumberOption("maxRetryTime", options.maxRetryTime, { + min: 0, + allowInfinity: true + }); + if (!(options.factor > 0)) options.factor = 1; + options.signal?.throwIfAborted(); + let attemptNumber = 0; + let retriesConsumed = 0; + const startTime = performance.now(); + while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { + attemptNumber++; + try { + options.signal?.throwIfAborted(); + const result = await input(attemptNumber); + options.signal?.throwIfAborted(); + return result; + } catch (error) { + if (await onAttemptFailure({ + error, + attemptNumber, + retriesConsumed, + startTime, + options + })) retriesConsumed++; + } + } + throw new Error("Retry attempts exhausted without throwing an error."); +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/_virtual/_rolldown/runtime.js +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 __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.js +var require_eventemitter3 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var has = Object.prototype.hasOwnProperty, prefix = "~"; + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + if (Object.create) { + Events.prototype = Object.create(null); + if (!new Events().__proto__) prefix = false; + } + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, 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 + event : event; + 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; + } + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [], events, name; + if (this._eventsCount === 0) return names; + for (name in events = this._events) if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + if (Object.getOwnPropertySymbols) return names.concat(Object.getOwnPropertySymbols(events)); + return names; + }; + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) ee[i] = handlers[i].fn; + return ee; + }; + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt], len = arguments.length, args, i; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, 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 (i = 1, args = new Array(len - 1); i < len; i++) args[i - 1] = arguments[i]; + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j; + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); + switch (len) { + case 1: + listeners[i].fn.call(listeners[i].context); + break; + case 2: + listeners[i].fn.call(listeners[i].context, a1); + break; + case 3: + listeners[i].fn.call(listeners[i].context, a1, a2); + break; + case 4: + listeners[i].fn.call(listeners[i].context, a1, a2, a3); + break; + default: + if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) args[j - 1] = arguments[j]; + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + return true; + }; + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + 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 i = 0, events = [], length = listeners.length; i < length; i++) if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) events.push(listeners[i]); + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + return this; + }; + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + 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 ("undefined" !== typeof module) module.exports = EventEmitter; +})); +require_eventemitter3(); +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index2.js +var import_eventemitter3 = /* @__PURE__ */ __toESM(require_eventemitter3(), 1); +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/node_modules/.pnpm/p-timeout@7.0.1/node_modules/p-timeout/index.js +var TimeoutError = class TimeoutError extends Error { + name = "TimeoutError"; + constructor(message, options) { + super(message, options); + Error.captureStackTrace?.(this, TimeoutError); + } +}; +var getAbortedReason = (signal) => signal.reason ?? new DOMException("This operation was aborted.", "AbortError"); +function pTimeout(promise, options) { + const { milliseconds, fallback, message, customTimers = { + setTimeout, + clearTimeout + }, signal } = options; + let timer; + let abortHandler; + const cancelablePromise = new Promise((resolve, reject) => { + if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``); + if (signal?.aborted) { + reject(getAbortedReason(signal)); + return; + } + if (signal) { + abortHandler = () => { + reject(getAbortedReason(signal)); + }; + signal.addEventListener("abort", abortHandler, { once: true }); + } + promise.then(resolve, reject); + if (milliseconds === Number.POSITIVE_INFINITY) return; + const timeoutError = new TimeoutError(); + timer = customTimers.setTimeout.call(void 0, () => { + if (fallback) { + try { + resolve(fallback()); + } catch (error) { + reject(error); + } + return; + } + if (typeof promise.cancel === "function") promise.cancel(); + if (message === false) resolve(); + else if (message instanceof Error) reject(message); + else { + timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`; + reject(timeoutError); + } + }, milliseconds); + }).finally(() => { + cancelablePromise.clear(); + if (abortHandler && signal) signal.removeEventListener("abort", abortHandler); + }); + cancelablePromise.clear = () => { + customTimers.clearTimeout.call(void 0, timer); + timer = void 0; + }; + return cancelablePromise; +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/node_modules/.pnpm/p-queue@9.1.0/node_modules/p-queue/dist/lower-bound.js +function lowerBound(array, value, comparator) { + let first = 0; + let count = array.length; + while (count > 0) { + const step = Math.trunc(count / 2); + let it = first + step; + if (comparator(array[it], value) <= 0) { + first = ++it; + count -= step + 1; + } else count = step; + } + return first; +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/node_modules/.pnpm/p-queue@9.1.0/node_modules/p-queue/dist/priority-queue.js +var PriorityQueue = class { + #queue = []; + enqueue(run, options) { + const { priority = 0, id } = options ?? {}; + const element = { + priority, + id, + run + }; + if (this.size === 0 || this.#queue[this.size - 1].priority >= priority) { + this.#queue.push(element); + return; + } + const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority); + this.#queue.splice(index, 0, element); + } + setPriority(id, priority) { + const index = this.#queue.findIndex((element) => element.id === id); + if (index === -1) throw new ReferenceError(`No promise function with the id "${id}" exists in the queue.`); + const [item] = this.#queue.splice(index, 1); + this.enqueue(item.run, { + priority, + id + }); + } + dequeue() { + return this.#queue.shift()?.run; + } + filter(options) { + return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run); + } + get size() { + return this.#queue.length; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/node_modules/.pnpm/p-queue@9.1.0/node_modules/p-queue/dist/index.js +/** +Promise queue with concurrency control. +*/ +var PQueue = class extends import_eventemitter3.default { + #carryoverIntervalCount; + #isIntervalIgnored; + #intervalCount = 0; + #intervalCap; + #rateLimitedInInterval = false; + #rateLimitFlushScheduled = false; + #interval; + #intervalEnd = 0; + #lastExecutionTime = 0; + #intervalId; + #timeoutId; + #strict; + #strictTicks = []; + #strictTicksStartIndex = 0; + #queue; + #queueClass; + #pending = 0; + #concurrency; + #isPaused; + #idAssigner = 1n; + #runningTasks = /* @__PURE__ */ new Map(); + /** + Get or set the default timeout for all tasks. Can be changed at runtime. + + Operations will throw a `TimeoutError` if they don't complete within the specified time. + + The timeout begins when the operation is dequeued and starts execution, not while it's waiting in the queue. + + @example + ``` + const queue = new PQueue({timeout: 5000}); + + // Change timeout for all future tasks + queue.timeout = 10000; + ``` + */ + timeout; + constructor(options) { + super(); + options = { + carryoverIntervalCount: false, + intervalCap: Number.POSITIVE_INFINITY, + interval: 0, + concurrency: Number.POSITIVE_INFINITY, + autoStart: true, + queueClass: PriorityQueue, + strict: false, + ...options + }; + if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${options.intervalCap?.toString() ?? ""}\` (${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 \`${options.interval?.toString() ?? ""}\` (${typeof options.interval})`); + if (options.strict && options.interval === 0) throw new TypeError("The `strict` option requires a non-zero `interval`"); + if (options.strict && options.intervalCap === Number.POSITIVE_INFINITY) throw new TypeError("The `strict` option requires a finite `intervalCap`"); + this.#carryoverIntervalCount = options.carryoverIntervalCount ?? options.carryoverConcurrencyCount ?? false; + this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0; + this.#intervalCap = options.intervalCap; + this.#interval = options.interval; + this.#strict = options.strict; + this.#queue = new options.queueClass(); + this.#queueClass = options.queueClass; + this.concurrency = options.concurrency; + if (options.timeout !== void 0 && !(Number.isFinite(options.timeout) && options.timeout > 0)) throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${options.timeout}\` (${typeof options.timeout})`); + this.timeout = options.timeout; + this.#isPaused = options.autoStart === false; + this.#setupRateLimitTracking(); + } + #cleanupStrictTicks(now) { + while (this.#strictTicksStartIndex < this.#strictTicks.length) { + const oldestTick = this.#strictTicks[this.#strictTicksStartIndex]; + if (oldestTick !== void 0 && now - oldestTick >= this.#interval) this.#strictTicksStartIndex++; + else break; + } + if (this.#strictTicksStartIndex > 100 && this.#strictTicksStartIndex > this.#strictTicks.length / 2 || this.#strictTicksStartIndex === this.#strictTicks.length) { + this.#strictTicks = this.#strictTicks.slice(this.#strictTicksStartIndex); + this.#strictTicksStartIndex = 0; + } + } + #consumeIntervalSlot(now) { + if (this.#strict) this.#strictTicks.push(now); + else this.#intervalCount++; + } + #rollbackIntervalSlot() { + if (this.#strict) { + if (this.#strictTicks.length > this.#strictTicksStartIndex) this.#strictTicks.pop(); + } else if (this.#intervalCount > 0) this.#intervalCount--; + } + #getActiveTicksCount() { + return this.#strictTicks.length - this.#strictTicksStartIndex; + } + get #doesIntervalAllowAnother() { + if (this.#isIntervalIgnored) return true; + if (this.#strict) return this.#getActiveTicksCount() < this.#intervalCap; + return this.#intervalCount < this.#intervalCap; + } + get #doesConcurrentAllowAnother() { + return this.#pending < this.#concurrency; + } + #next() { + this.#pending--; + if (this.#pending === 0) this.emit("pendingZero"); + this.#tryToStartAnother(); + this.emit("next"); + } + #onResumeInterval() { + this.#timeoutId = void 0; + this.#onInterval(); + this.#initializeIntervalIfNeeded(); + } + #isIntervalPausedAt(now) { + if (this.#strict) { + this.#cleanupStrictTicks(now); + if (this.#getActiveTicksCount() >= this.#intervalCap) { + const oldestTick = this.#strictTicks[this.#strictTicksStartIndex]; + const delay = this.#interval - (now - oldestTick); + this.#createIntervalTimeout(delay); + return true; + } + return false; + } + if (this.#intervalId === void 0) { + const delay = this.#intervalEnd - now; + if (delay < 0) { + if (this.#lastExecutionTime > 0) { + const timeSinceLastExecution = now - this.#lastExecutionTime; + if (timeSinceLastExecution < this.#interval) { + this.#createIntervalTimeout(this.#interval - timeSinceLastExecution); + return true; + } + } + this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0; + } else { + this.#createIntervalTimeout(delay); + return true; + } + } + return false; + } + #createIntervalTimeout(delay) { + if (this.#timeoutId !== void 0) return; + this.#timeoutId = setTimeout(() => { + this.#onResumeInterval(); + }, delay); + } + #clearIntervalTimer() { + if (this.#intervalId) { + clearInterval(this.#intervalId); + this.#intervalId = void 0; + } + } + #clearTimeoutTimer() { + if (this.#timeoutId) { + clearTimeout(this.#timeoutId); + this.#timeoutId = void 0; + } + } + #tryToStartAnother() { + if (this.#queue.size === 0) { + this.#clearIntervalTimer(); + this.emit("empty"); + if (this.#pending === 0) { + this.#clearTimeoutTimer(); + if (this.#strict && this.#strictTicksStartIndex > 0) { + const now = Date.now(); + this.#cleanupStrictTicks(now); + } + this.emit("idle"); + } + return false; + } + let taskStarted = false; + if (!this.#isPaused) { + const now = Date.now(); + const canInitializeInterval = !this.#isIntervalPausedAt(now); + if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) { + const job = this.#queue.dequeue(); + if (!this.#isIntervalIgnored) { + this.#consumeIntervalSlot(now); + this.#scheduleRateLimitUpdate(); + } + this.emit("active"); + job(); + if (canInitializeInterval) this.#initializeIntervalIfNeeded(); + taskStarted = true; + } + } + return taskStarted; + } + #initializeIntervalIfNeeded() { + if (this.#isIntervalIgnored || this.#intervalId !== void 0) return; + if (this.#strict) return; + this.#intervalId = setInterval(() => { + this.#onInterval(); + }, this.#interval); + this.#intervalEnd = Date.now() + this.#interval; + } + #onInterval() { + if (!this.#strict) { + if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) this.#clearIntervalTimer(); + this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0; + } + this.#processQueue(); + this.#scheduleRateLimitUpdate(); + } + /** + Executes all queued functions until it reaches the limit. + */ + #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(); + } + /** + Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect. + + For example, this can be used to prioritize a promise function to run earlier. + + ```js + import PQueue from 'p-queue'; + + const queue = new PQueue({concurrency: 1}); + + queue.add(async () => '🦄', {priority: 1}); + queue.add(async () => '🦀', {priority: 0, id: '🦀'}); + queue.add(async () => '🦄', {priority: 1}); + queue.add(async () => '🦄', {priority: 1}); + + queue.setPriority('🦀', 2); + ``` + + In this case, the promise function with `id: '🦀'` runs second. + + You can also deprioritize a promise function to delay its execution: + + ```js + import PQueue from 'p-queue'; + + const queue = new PQueue({concurrency: 1}); + + queue.add(async () => '🦄', {priority: 1}); + queue.add(async () => '🦀', {priority: 1, id: '🦀'}); + queue.add(async () => '🦄'); + queue.add(async () => '🦄', {priority: 0}); + + queue.setPriority('🦀', -1); + ``` + Here, the promise function with `id: '🦀'` executes last. + */ + setPriority(id, priority) { + if (typeof priority !== "number" || !Number.isFinite(priority)) throw new TypeError(`Expected \`priority\` to be a finite number, got \`${priority}\` (${typeof priority})`); + this.#queue.setPriority(id, priority); + } + async add(function_, options = {}) { + options = { + timeout: this.timeout, + ...options, + id: options.id ?? (this.#idAssigner++).toString() + }; + return new Promise((resolve, reject) => { + const taskSymbol = Symbol(`task-${options.id}`); + this.#queue.enqueue(async () => { + this.#pending++; + this.#runningTasks.set(taskSymbol, { + id: options.id, + priority: options.priority ?? 0, + startTime: Date.now(), + timeout: options.timeout + }); + let eventListener; + try { + try { + options.signal?.throwIfAborted(); + } catch (error) { + this.#rollbackIntervalConsumption(); + this.#runningTasks.delete(taskSymbol); + throw error; + } + this.#lastExecutionTime = Date.now(); + let operation = function_({ signal: options.signal }); + if (options.timeout) operation = pTimeout(Promise.resolve(operation), { + milliseconds: options.timeout, + message: `Task timed out after ${options.timeout}ms (queue has ${this.#pending} running, ${this.#queue.size} waiting)` + }); + if (options.signal) { + const { signal } = options; + operation = Promise.race([operation, new Promise((_resolve, reject) => { + eventListener = () => { + reject(signal.reason); + }; + signal.addEventListener("abort", eventListener, { once: true }); + })]); + } + const result = await operation; + resolve(result); + this.emit("completed", result); + } catch (error) { + reject(error); + this.emit("error", error); + } finally { + if (eventListener) options.signal?.removeEventListener("abort", eventListener); + this.#runningTasks.delete(taskSymbol); + queueMicrotask(() => { + this.#next(); + }); + } + }, options); + this.emit("add"); + this.#tryToStartAnother(); + }); + } + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); + } + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this.#isPaused) return this; + this.#isPaused = false; + this.#processQueue(); + return this; + } + /** + Put queue execution on hold. + */ + pause() { + this.#isPaused = true; + } + /** + Clear the queue. + */ + clear() { + this.#queue = new this.#queueClass(); + this.#clearIntervalTimer(); + this.#updateRateLimitState(); + this.emit("empty"); + if (this.#pending === 0) { + this.#clearTimeoutTimer(); + this.emit("idle"); + } + this.emit("next"); + } + /** + Can be called multiple times. Useful if you for example add additional items at a later time. + + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + if (this.#queue.size === 0) return; + await this.#onEvent("empty"); + } + /** + @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`. + + If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item. + + Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation. + */ + async onSizeLessThan(limit) { + if (this.#queue.size < limit) return; + await this.#onEvent("next", () => this.#queue.size < limit); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + if (this.#pending === 0 && this.#queue.size === 0) return; + await this.#onEvent("idle"); + } + /** + The difference with `.onIdle` is that `.onPendingZero` only waits for currently running tasks to finish, ignoring queued tasks. + + @returns A promise that settles when all currently running tasks have completed; `queue.pending === 0`. + */ + async onPendingZero() { + if (this.#pending === 0) return; + await this.#onEvent("pendingZero"); + } + /** + @returns A promise that settles when the queue becomes rate-limited due to intervalCap. + */ + async onRateLimit() { + if (this.isRateLimited) return; + await this.#onEvent("rateLimit"); + } + /** + @returns A promise that settles when the queue is no longer rate-limited. + */ + async onRateLimitCleared() { + if (!this.isRateLimited) return; + await this.#onEvent("rateLimitCleared"); + } + /** + @returns A promise that rejects when any task in the queue errors. + + Use with `Promise.race([queue.onError(), queue.onIdle()])` to fail fast on the first error while still resolving normally when the queue goes idle. + + Important: The promise returned by `add()` still rejects. You must handle each `add()` promise (for example, `.catch(() => {})`) to avoid unhandled rejections. + + @example + ``` + import PQueue from 'p-queue'; + + const queue = new PQueue({concurrency: 2}); + + queue.add(() => fetchData(1)).catch(() => {}); + queue.add(() => fetchData(2)).catch(() => {}); + queue.add(() => fetchData(3)).catch(() => {}); + + // Stop processing on first error + try { + await Promise.race([ + queue.onError(), + queue.onIdle() + ]); + } catch (error) { + queue.pause(); // Stop processing remaining tasks + console.error('Queue failed:', error); + } + ``` + */ + onError() { + return new Promise((_resolve, reject) => { + const handleError = (error) => { + this.off("error", handleError); + reject(error); + }; + this.on("error", handleError); + }); + } + async #onEvent(event, filter) { + return new Promise((resolve) => { + const listener = () => { + if (filter && !filter()) return; + this.off(event, listener); + resolve(); + }; + this.on(event, listener); + }); + } + /** + Size of the queue, the number of queued items waiting to run. + */ + get size() { + return this.#queue.size; + } + /** + Size of the queue, filtered by the given options. + + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + return this.#queue.filter(options).length; + } + /** + Number of running items (no longer in the queue). + */ + get pending() { + return this.#pending; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this.#isPaused; + } + #setupRateLimitTracking() { + if (this.#isIntervalIgnored) return; + this.on("add", () => { + if (this.#queue.size > 0) this.#scheduleRateLimitUpdate(); + }); + this.on("next", () => { + this.#scheduleRateLimitUpdate(); + }); + } + #scheduleRateLimitUpdate() { + if (this.#isIntervalIgnored || this.#rateLimitFlushScheduled) return; + this.#rateLimitFlushScheduled = true; + queueMicrotask(() => { + this.#rateLimitFlushScheduled = false; + this.#updateRateLimitState(); + }); + } + #rollbackIntervalConsumption() { + if (this.#isIntervalIgnored) return; + this.#rollbackIntervalSlot(); + this.#scheduleRateLimitUpdate(); + } + #updateRateLimitState() { + const previous = this.#rateLimitedInInterval; + if (this.#isIntervalIgnored || this.#queue.size === 0) { + if (previous) { + this.#rateLimitedInInterval = false; + this.emit("rateLimitCleared"); + } + return; + } + let count; + if (this.#strict) { + const now = Date.now(); + this.#cleanupStrictTicks(now); + count = this.#getActiveTicksCount(); + } else count = this.#intervalCount; + const shouldBeRateLimited = count >= this.#intervalCap; + if (shouldBeRateLimited !== previous) { + this.#rateLimitedInInterval = shouldBeRateLimited; + this.emit(shouldBeRateLimited ? "rateLimit" : "rateLimitCleared"); + } + } + /** + Whether the queue is currently rate-limited due to intervalCap. + */ + get isRateLimited() { + return this.#rateLimitedInInterval; + } + /** + Whether the queue is saturated. Returns `true` when: + - All concurrency slots are occupied and tasks are waiting, OR + - The queue is rate-limited and tasks are waiting + + Useful for detecting backpressure and potential hanging tasks. + + ```js + import PQueue from 'p-queue'; + + const queue = new PQueue({concurrency: 2}); + + // Backpressure handling + if (queue.isSaturated) { + console.log('Queue is saturated, waiting for capacity...'); + await queue.onSizeLessThan(queue.concurrency); + } + + // Monitoring for stuck tasks + setInterval(() => { + if (queue.isSaturated) { + console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`); + } + }, 60000); + ``` + */ + get isSaturated() { + return this.#pending === this.#concurrency && this.#queue.size > 0 || this.isRateLimited && this.#queue.size > 0; + } + /** + The tasks currently being executed. Each task includes its `id`, `priority`, `startTime`, and `timeout` (if set). + + Returns an array of task info objects. + + ```js + import PQueue from 'p-queue'; + + const queue = new PQueue({concurrency: 2}); + + // Add tasks with IDs for better debugging + queue.add(() => fetchUser(123), {id: 'user-123'}); + queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1}); + + // Check what's running + console.log(queue.runningTasks); + // => [{ + // id: 'user-123', + // priority: 0, + // startTime: 1759253001716, + // timeout: undefined + // }, { + // id: 'posts-456', + // priority: 1, + // startTime: 1759253001916, + // timeout: undefined + // }] + ``` + */ + get runningTasks() { + return [...this.#runningTasks.values()].map((task) => ({ ...task })); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/utils/async_caller.js +/** +* `p-retry` is a pure-ESM module that we bundle into the build output (so the +* CJS artifact doesn't `require()` an ESM module). Depending on how a +* downstream transpiler/bundler (e.g. `tsx`/esbuild) resolves the default +* export of the bundled chunk, the import can come through either as the +* function itself or as a namespace-like `{ default: fn }`. Normalize to the +* callable, mirroring the `"default" in` interop guard used for `p-queue`. +*/ +var pRetry = typeof pRetry$1 === "function" ? pRetry$1 : pRetry$1.default; +var STATUS_NO_RETRY = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 408, + 409, + 422 +]; +/** +* Do not rely on globalThis.Response, rather just +* do duck typing +*/ +function isResponse(x) { + if (x == null || typeof x !== "object") return false; + return "status" in x && "statusText" in x && "text" in x; +} +/** +* Utility error to properly handle failed requests +*/ +var HTTPError = class HTTPError extends Error { + status; + text; + response; + constructor(status, message, response) { + super(`HTTP ${status}: ${message}`); + this.status = status; + this.text = message; + this.response = response; + } + static async fromResponse(response, options) { + try { + return new HTTPError(response.status, await response.text(), options?.includeResponse ? response : void 0); + } catch { + return new HTTPError(response.status, response.statusText, options?.includeResponse ? response : void 0); + } + } +}; +/** +* A class that can be used to make async calls with concurrency and retry logic. +* +* This is useful for making calls to any kind of "expensive" external resource, +* be it because it's rate-limited, subject to network issues, etc. +* +* Concurrent calls are limited by the `maxConcurrency` parameter, which defaults +* to `Infinity`. This means that by default, all calls will be made in parallel. +* +* Retries are limited by the `maxRetries` parameter, which defaults to 5. This +* means that by default, each call will be retried up to 5 times, with an +* exponential backoff between each attempt. +*/ +var AsyncCaller = class { + maxConcurrency; + maxRetries; + queue; + onFailedResponseHook; + customFetch; + constructor(params) { + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 4; + if ("default" in PQueue) this.queue = new PQueue.default({ concurrency: this.maxConcurrency }); + else this.queue = new PQueue({ concurrency: this.maxConcurrency }); + this.onFailedResponseHook = params?.onFailedResponseHook; + this.customFetch = params.fetch; + } + call(callable, ...args) { + const { onFailedResponseHook } = this; + return this.queue.add(() => pRetry(() => callable(...args).catch(async (error) => { + if (error instanceof Error) throw error; + else if (isResponse(error)) throw await HTTPError.fromResponse(error, { includeResponse: !!onFailedResponseHook }); + else throw new Error(error); + }), { + async onFailedAttempt({ error, retriesLeft }) { + const errorMessage = error.message ?? ""; + if (errorMessage.startsWith("Cancel") || errorMessage.startsWith("TimeoutError") || errorMessage.startsWith("AbortError")) throw error; + if (error?.code === "ECONNABORTED") throw error; + if (errorMessage.includes("ECONNREFUSED") || errorMessage.includes("fetch failed") || errorMessage.includes("Failed to fetch") || errorMessage.includes("NetworkError")) { + if (retriesLeft > 0) return; + const connectionError = /* @__PURE__ */ new Error(`Unable to connect to LangGraph server. Please ensure the server is running and accessible. Original error: ${errorMessage}`); + connectionError.name = "ConnectionError"; + throw connectionError; + } + if (error instanceof HTTPError) { + if (STATUS_NO_RETRY.includes(error.status)) throw error; + if (onFailedResponseHook && error.response) await onFailedResponseHook(error.response); + } + }, + retries: this.maxRetries, + randomize: true + }), { throwOnTimeout: true }); + } + callWithOptions(options, callable, ...args) { + if (options.signal) return Promise.race([this.call(callable, ...args), new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(/* @__PURE__ */ new Error("AbortError")); + }); + })]); + return this.call(callable, ...args); + } + fetch(...args) { + const fetchFn = this.customFetch ?? _getFetchImplementation(); + return this.call(() => fetchFn(...args).then((res) => res.ok ? res : Promise.reject(res))); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/utils/env.js +function getEnvironmentVariable(name) { + try { + return typeof process !== "undefined" ? process.env?.[name] : void 0; + } catch { + return; + } +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/utils/signals.js +function mergeSignals(...signals) { + const nonZeroSignals = signals.filter((signal) => signal != null); + if (nonZeroSignals.length === 0) return void 0; + if (nonZeroSignals.length === 1) return nonZeroSignals[0]; + const controller = new AbortController(); + for (const signal of signals) { + if (signal?.aborted) { + controller.abort(signal.reason); + return controller.signal; + } + signal?.addEventListener("abort", () => controller.abort(signal.reason), { once: true }); + } + return controller.signal; +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/utils/sse.js +var CR = "\r".charCodeAt(0); +var LF = "\n".charCodeAt(0); +var NULL = "\0".charCodeAt(0); +var COLON = ":".charCodeAt(0); +var SPACE = " ".charCodeAt(0); +var TRAILING_NEWLINE = [CR, LF]; +function BytesLineDecoder() { + let buffer = []; + let trailingCr = false; + return new TransformStream({ + start() { + buffer = []; + trailingCr = false; + }, + transform(chunk, controller) { + let text = chunk; + if (trailingCr) { + text = joinArrays([[CR], text]); + trailingCr = false; + } + if (text.length > 0 && text.at(-1) === CR) { + trailingCr = true; + text = text.subarray(0, -1); + } + if (!text.length) return; + const trailingNewline = TRAILING_NEWLINE.includes(text.at(-1)); + const lastIdx = text.length - 1; + const { lines } = text.reduce((acc, cur, idx) => { + if (acc.from > idx) return acc; + if (cur === CR || cur === LF) { + acc.lines.push(text.subarray(acc.from, idx)); + if (cur === CR && text[idx + 1] === LF) acc.from = idx + 2; + else acc.from = idx + 1; + } + if (idx === lastIdx && acc.from <= lastIdx) acc.lines.push(text.subarray(acc.from)); + return acc; + }, { + lines: [], + from: 0 + }); + if (lines.length === 1 && !trailingNewline) { + buffer.push(lines[0]); + return; + } + if (buffer.length) { + buffer.push(lines[0]); + lines[0] = joinArrays(buffer); + buffer = []; + } + if (!trailingNewline) { + if (lines.length) buffer = [lines.pop()]; + } + for (const line of lines) controller.enqueue(line); + }, + flush(controller) { + if (buffer.length) controller.enqueue(joinArrays(buffer)); + } + }); +} +function SSEDecoder() { + let event = ""; + let data = []; + let lastEventId = ""; + let retry = null; + const decoder = new TextDecoder(); + return new TransformStream({ + transform(chunk, controller) { + if (!chunk.length) { + if (!event && !data.length && !lastEventId && retry == null) return; + const sse = { + id: lastEventId || void 0, + event, + data: data.length ? decodeArraysToJson(decoder, data) : null + }; + event = ""; + data = []; + retry = null; + controller.enqueue(sse); + return; + } + if (chunk[0] === COLON) return; + const sepIdx = chunk.indexOf(COLON); + if (sepIdx === -1) return; + const fieldName = decoder.decode(chunk.subarray(0, sepIdx)); + let value = chunk.subarray(sepIdx + 1); + if (value[0] === SPACE) value = value.subarray(1); + if (fieldName === "event") event = decoder.decode(value); + else if (fieldName === "data") data.push(value); + else if (fieldName === "id") { + if (value.indexOf(NULL) === -1) lastEventId = decoder.decode(value); + } else if (fieldName === "retry") { + const retryNum = Number.parseInt(decoder.decode(value), 10); + if (!Number.isNaN(retryNum)) retry = retryNum; + } + }, + flush(controller) { + if (event) controller.enqueue({ + id: lastEventId || void 0, + event, + data: data.length ? decodeArraysToJson(decoder, data) : null + }); + } + }); +} +function joinArrays(data) { + const totalLength = data.reduce((acc, curr) => acc + curr.length, 0); + const merged = new Uint8Array(totalLength); + let offset = 0; + for (const c of data) { + merged.set(c, offset); + offset += c.length; + } + return merged; +} +function decodeArraysToJson(decoder, data) { + return JSON.parse(decoder.decode(joinArrays(data))); +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/utils/error.js +var isError = (error) => { + if ("isError" in Error && typeof Error.isError === "function") return Error.isError(error); + const stringTag = Object.prototype.toString.call(error); + return stringTag === "[object Error]" || stringTag === "[object DOMException]" || stringTag === "[object DOMError]" || stringTag === "[object Exception]"; +}; +var getCauseError = (error) => { + const { cause } = error; + if (typeof cause !== "object" || cause == null) return null; + if (!isError(cause)) return null; + return cause; +}; +var isNetworkError = (error) => { + if (!isError(error)) return false; + if (error.name !== "TypeError" || typeof error.message !== "string") return false; + const msg = error.message.toLowerCase(); + const causeMsg = getCauseError(error)?.message?.toLowerCase() ?? ""; + return msg.includes("fetch") || msg.includes("network") || msg.includes("connection") || msg.includes("error sending request") || msg.includes("load failed") || msg.includes("terminated") || causeMsg.includes("other side closed") || causeMsg.includes("socket"); +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/utils/reconnect.js +/** Base delay (ms) for exponential reconnect backoff (`base * 2^(attempt-1)`). */ +var DEFAULT_RECONNECT_BASE_DELAY_MS = 1e3; +/** Cap (ms) for exponential reconnect backoff before jitter. */ +var DEFAULT_RECONNECT_MAX_DELAY_MS = 5e3; +/** Max random jitter (ms) added on top of the capped base delay. */ +var DEFAULT_RECONNECT_JITTER_MS = 1e3; +/** +* Exponential backoff with jitter for stream reconnect. +* `min(base * 2^(attempt-1), max) + random(0, jitter)`. +*/ +function reconnectDelayMs(attempt) { + return Math.min(DEFAULT_RECONNECT_BASE_DELAY_MS * 2 ** (attempt - 1), DEFAULT_RECONNECT_MAX_DELAY_MS) + Math.random() * DEFAULT_RECONNECT_JITTER_MS; +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/utils/stream.js +/** +* Error thrown when maximum reconnection attempts are exceeded. +*/ +var MaxReconnectAttemptsError = class extends Error { + constructor(maxAttempts, cause) { + super(`Exceeded maximum SSE reconnection attempts (${maxAttempts})`); + this.name = "MaxReconnectAttemptsError"; + this.cause = cause; + } +}; +/** +* Error injected into the stream by {@link idleReconnectStream} when no lines +* arrive within the active idle window. Surfacing this during the read is what +* lets the reconnect loops in `streamWithRetry` and the protocol SSE transport +* recover from a half-open socket — one that was silently dropped (e.g. a hard +* pod kill on a platform revision rollover) without a TCP FIN/RST, so neither +* a `done` nor a thrown network error ever arrives. +*/ +var StreamIdleTimeoutError = class extends Error { + idleTimeoutMs; + constructor(idleTimeoutMs) { + super(`No SSE bytes received for ${idleTimeoutMs}ms; assuming the connection is half-open and reconnecting.`); + this.name = "StreamIdleTimeoutError"; + this.idleTimeoutMs = idleTimeoutMs; + } +}; +/** `":"` — first byte of an SSE comment / keep-alive line. */ +var SSE_COMMENT_BYTE = 58; +/** +* A pass-through {@link TransformStream} that errors the stream when it goes +* idle, so the surrounding reconnect logic can recover a half-open socket. +* +* MUST sit on the *line* stream — i.e. after +* {@link import("./sse.js").BytesLineDecoder} but before +* {@link import("./sse.js").SSEDecoder} (which discards `:` comment lines). +* Operating at the line level lets the watchdog both (a) reset on any line +* (data *or* heartbeat = liveness) and (b) recognise heartbeat comment lines +* to drive `"auto"` mode. +* +* In `"auto"` mode the watchdog is intentionally dormant until it has seen at +* least two heartbeats (so it can measure the cadence). This means a socket +* that dies inside the first heartbeat interval won't be caught until a +* heartbeat would have been due — an acceptable trade for never false-firing +* on heartbeat-less servers. Pass a fixed `number` if you need coverage from +* the very first byte. +*/ +function idleReconnectStream(options) { + const factor = options.timeoutFactor ?? 3; + const minTimeoutMs = options.minTimeoutMs ?? 6e3; + const maxTimeoutMs = options.maxTimeoutMs ?? 3e4; + const fixedTimeoutMs = typeof options.mode === "number" ? options.mode : null; + let timer; + let controllerRef; + let lastHeartbeatAt; + let derivedTimeoutMs = fixedTimeoutMs; + const clear = () => { + if (timer != null) { + clearTimeout(timer); + timer = void 0; + } + }; + const arm = () => { + clear(); + const timeoutMs = derivedTimeoutMs; + if (timeoutMs == null || timeoutMs <= 0) return; + timer = setTimeout(() => { + options.onIdle?.({ + timeoutMs, + source: fixedTimeoutMs != null ? "fixed" : "heartbeat" + }); + try { + controllerRef?.error(new StreamIdleTimeoutError(timeoutMs)); + } catch {} + }, timeoutMs); + timer.unref?.(); + }; + const noteHeartbeat = () => { + if (fixedTimeoutMs != null) return; + const now = Date.now(); + if (lastHeartbeatAt != null) { + const interval = now - lastHeartbeatAt; + if (interval > 0) { + const candidate = Math.min(Math.max(interval * factor, minTimeoutMs), maxTimeoutMs); + derivedTimeoutMs = derivedTimeoutMs == null ? candidate : Math.max(derivedTimeoutMs, candidate); + } + } + lastHeartbeatAt = now; + }; + return new TransformStream({ + start(controller) { + controllerRef = controller; + arm(); + }, + transform(line, controller) { + if (line.length > 0 && line[0] === SSE_COMMENT_BYTE) noteHeartbeat(); + arm(); + controller.enqueue(line); + }, + flush() { + clear(); + } + }); +} +/** +* Stream with automatic retry logic for SSE connections. +* Implements reconnection behavior similar to the Python SDK. +* +* @param makeRequest Function to make requests. When `params` is undefined/empty, it's the initial request. +* When `params.reconnectPath` is provided, it's a reconnection request. +* @param options Configuration options +* @returns AsyncGenerator yielding stream events +*/ +async function* streamWithRetry(makeRequest, options = {}) { + const maxRetries = options.maxRetries ?? 5; + let attempt = 0; + let lastEventId; + let reconnectPath; + while (true) { + let shouldRetry = false; + let lastError; + let reader; + try { + if (options.signal?.aborted) return; + const { response, stream } = await makeRequest(reconnectPath ? { + lastEventId, + reconnectPath + } : void 0); + const locationHeader = response.headers.get("location"); + if (locationHeader) reconnectPath = locationHeader; + const contentType = response.headers.get("content-type")?.split(";")[0]; + if (contentType && !contentType.includes("text/event-stream")) throw new Error(`Expected response header Content-Type to contain 'text/event-stream', got '${contentType}'`); + reader = stream.getReader(); + try { + while (true) { + if (options.signal?.aborted) { + await reader.cancel(); + return; + } + const { done, value } = await reader.read(); + if (done) break; + if (value.id) lastEventId = value.id; + yield value; + } + break; + } catch (error) { + if (reconnectPath && !options.signal?.aborted) shouldRetry = true; + else throw error; + } finally { + if (reader) try { + reader.releaseLock(); + } catch {} + } + } catch (error) { + lastError = error; + if (isNetworkError(error) && reconnectPath && !options.signal?.aborted) shouldRetry = true; + else throw error; + } + if (shouldRetry) { + attempt += 1; + if (attempt > maxRetries) throw new MaxReconnectAttemptsError(maxRetries, lastError); + options.onReconnect?.({ + attempt, + lastEventId, + cause: lastError + }); + const delay = reconnectDelayMs(attempt); + await new Promise((resolve) => { + setTimeout(resolve, delay); + }); + continue; + } + break; + } +} +var IterableReadableStream = class IterableReadableStream extends ReadableStream { + reader; + 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 (e) { + this.reader.releaseLock(); + throw e; + } + } + 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(e) { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); + this.reader.releaseLock(); + await cancelPromise; + } + throw e; + } + async [Symbol.asyncDispose]() { + await this.return(); + } + [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); + } + }); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/base.js +function* iterateHeaders(headers) { + let iter; + let shouldClear = false; + if (headers instanceof Headers) { + const entries = []; + headers.forEach((value, name) => { + entries.push([name, value]); + }); + iter = entries; + } else if (Array.isArray(headers)) iter = headers; + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (const item of iter) { + const name = item[0]; + if (typeof name !== "string") throw new TypeError(`Expected header name to be a string, got ${typeof name}`); + const values = Array.isArray(item[1]) ? item[1] : [item[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +function mergeHeaders$1(...headerObjects) { + const outputHeaders = new Headers(); + for (const headers of headerObjects) { + if (!headers) continue; + for (const [name, value] of iterateHeaders(headers)) if (value === null) outputHeaders.delete(name); + else outputHeaders.append(name, value); + } + const headerEntries = []; + outputHeaders.forEach((value, name) => { + headerEntries.push([name, value]); + }); + return Object.fromEntries(headerEntries); +} +/** +* Get the API key from the environment. +* Precedence: +* 1. explicit argument (if string) +* 2. LANGGRAPH_API_KEY +* 3. LANGSMITH_API_KEY +* 4. LANGCHAIN_API_KEY +* +* @param apiKey - API key provided as an argument. If null, skips environment lookup. If undefined, tries environment. +* @returns The API key if found, otherwise undefined +*/ +function getApiKey(apiKey) { + if (apiKey === null) return; + if (apiKey) return apiKey; + for (const prefix of [ + "LANGGRAPH", + "LANGSMITH", + "LANGCHAIN" + ]) { + const envKey = getEnvironmentVariable(`${prefix}_API_KEY`); + if (envKey) return envKey.trim().replace(/^["']|["']$/g, ""); + } +} +var BaseClient = class { + asyncCaller; + timeoutMs; + apiUrl; + defaultHeaders; + onRequest; + streamProtocol; + constructor(config) { + const callerOptions = { + maxRetries: 4, + maxConcurrency: 4, + ...config?.callerOptions + }; + let defaultApiUrl = "http://localhost:8123"; + if (!config?.apiUrl && typeof globalThis === "object" && globalThis != null) { + const fetchSmb = Symbol.for("langgraph_api:fetch"); + const urlSmb = Symbol.for("langgraph_api:url"); + const global = globalThis; + if (global[fetchSmb]) callerOptions.fetch ??= global[fetchSmb]; + if (global[urlSmb]) defaultApiUrl = global[urlSmb]; + } + this.asyncCaller = new AsyncCaller(callerOptions); + this.timeoutMs = config?.timeoutMs; + this.apiUrl = config?.apiUrl?.replace(/\/$/, "") || defaultApiUrl; + this.defaultHeaders = config?.defaultHeaders || {}; + this.onRequest = config?.onRequest; + this.streamProtocol = config?.streamProtocol ?? "legacy"; + const apiKey = getApiKey(config?.apiKey); + if (apiKey) this.defaultHeaders["x-api-key"] = apiKey; + } + prepareFetchOptions(path, options) { + const mutatedOptions = { + ...options, + headers: mergeHeaders$1(this.defaultHeaders, options?.headers) + }; + if (mutatedOptions.json) { + mutatedOptions.body = JSON.stringify(mutatedOptions.json); + mutatedOptions.headers = mergeHeaders$1(mutatedOptions.headers, { "content-type": "application/json" }); + delete mutatedOptions.json; + } + if (mutatedOptions.withResponse) delete mutatedOptions.withResponse; + if ("dedupe" in mutatedOptions) delete mutatedOptions.dedupe; + let timeoutSignal = null; + if (typeof options?.timeoutMs !== "undefined") { + if (options.timeoutMs != null) timeoutSignal = AbortSignal.timeout(options.timeoutMs); + } else if (this.timeoutMs != null) timeoutSignal = AbortSignal.timeout(this.timeoutMs); + mutatedOptions.signal = mergeSignals(timeoutSignal, mutatedOptions.signal); + const targetUrl = new URL(`${this.apiUrl}${path}`); + if (mutatedOptions.params) { + for (const [key, value] of Object.entries(mutatedOptions.params)) { + if (value == null) continue; + const strValue = typeof value === "string" || typeof value === "number" ? value.toString() : JSON.stringify(value); + targetUrl.searchParams.append(key, strValue); + } + delete mutatedOptions.params; + } + return [targetUrl, mutatedOptions]; + } + async fetch(path, options) { + const [url, init] = this.prepareFetchOptions(path, options); + if (options?.dedupe === true && options?.withResponse !== true && options?.signal == null && this.onRequest == null) { + const body = typeof init.body === "string" ? init.body : ""; + /** + * The key must capture the FULL request identity, including every + * prepared header. `inFlightReads` is module-scoped across all + * `Client` instances, so omitting headers would let two clients + * pointed at the same URL/thread but using different credentials + * (Authorization, custom auth headers, tenant-scoping defaults, …) + * share one in-flight promise — a cross-tenant data leak. + */ + const headers = serializeHeaders(init.headers); + const key = `${init.method ?? "GET"} ${url.toString()} ${body} ${headers}`; + const existing = inFlightReads.get(key); + if (existing != null) return existing; + const promise = this.#performFetch(url, init); + inFlightReads.set(key, promise); + const clear = () => { + if (inFlightReads.get(key) === promise) inFlightReads.delete(key); + }; + promise.then(clear, clear); + return promise; + } + const [body, response] = await this.#performFetchWithResponse(url, init); + if (options?.withResponse) return [body, response]; + return body; + } + /** + * Issue the prepared request (applying the `onRequest` hook) and + * resolve the parsed body. Shared by the deduped and direct paths. + */ + async #performFetch(url, init) { + const [body] = await this.#performFetchWithResponse(url, init); + return body; + } + async #performFetchWithResponse(url, init) { + let finalInit = init; + if (this.onRequest) finalInit = await this.onRequest(url, init); + const response = await this.asyncCaller.fetch(url.toString(), finalInit); + return [await (async () => { + if (response.status === 202 || response.status === 204) return; + return response.json(); + })(), response]; + } + async *streamWithRetry(config) { + const makeRequest = async (reconnectParams) => { + const requestEndpoint = reconnectParams?.reconnectPath || config.endpoint; + const isReconnect = !!reconnectParams?.reconnectPath; + const method = isReconnect ? "GET" : config.method || "GET"; + const requestHeaders = isReconnect && reconnectParams?.lastEventId ? { + ...config.headers, + "Last-Event-ID": reconnectParams.lastEventId + } : config.headers; + let [url, init] = this.prepareFetchOptions(requestEndpoint, { + method, + timeoutMs: null, + signal: config.signal, + headers: requestHeaders, + params: config.params, + json: isReconnect ? void 0 : config.json + }); + if (this.onRequest != null) init = await this.onRequest(url, init); + const response = await this.asyncCaller.fetch(url.toString(), init); + if (!response.body) throw new Error("Expected response body from stream endpoint"); + if (!isReconnect && config.onInitialResponse) await config.onInitialResponse(response); + const idleMode = config.idleReconnect ?? "auto"; + const enableIdle = idleMode === "auto" || idleMode > 0; + const lines = response.body.pipeThrough(BytesLineDecoder()); + return { + response, + stream: (enableIdle ? lines.pipeThrough(idleReconnectStream({ mode: idleMode })) : lines).pipeThrough(SSEDecoder()) + }; + }; + yield* streamWithRetry(makeRequest, { + maxRetries: config.maxRetries ?? 5, + signal: config.signal, + onReconnect: config.onReconnect + }); + } +}; +var REGEX_RUN_METADATA = /(\/threads\/(?.+))?\/runs\/(?.+)/; +function getRunMetadataFromResponse(response) { + const contentLocation = response.headers.get("Content-Location"); + if (!contentLocation) return void 0; + const match = REGEX_RUN_METADATA.exec(contentLocation); + if (!match?.groups?.run_id) return void 0; + return { + run_id: match.groups.run_id, + thread_id: match.groups.thread_id || void 0 + }; +} +/** +* Module-scoped, in-flight-only coalescing map for idempotent reads. +* +* Two independently-constructed clients (e.g. a React component that +* remounts under Suspense / a reachability state flip, each minting a +* fresh `Client`) can fire the *same* `getState` / `getHistory` read a +* few milliseconds apart, before the first has resolved. Without +* coalescing each pays the full round-trip — the duplicate +* `threads/{id}/state` and `threads/{id}/history` requests seen on +* reconnect. +* +* Keyed by `method + url + body + auth`, entries live only while a +* request is in flight and are removed the moment it settles. This is +* deliberately *not* a result cache: there is no TTL and no stored +* payload, so it cannot serve stale data — it only ever shares a +* promise that is already on the wire. Opt-in per call via +* `{ dedupe: true }`, and skipped whenever the caller supplies its own +* `AbortSignal` (so one consumer aborting can never cancel another's +* read). +*/ +var inFlightReads = /* @__PURE__ */ new Map(); +/** +* Deterministically serialize a prepared request's headers into a +* stable string for use in the {@link inFlightReads} dedupe key. Header +* names are normalized and sorted so ordering differences never produce +* a different key, and every header (not just `x-api-key`) is included +* so requests carrying different credentials never collide. +*/ +function serializeHeaders(headers) { + const normalized = mergeHeaders$1(headers); + return Object.keys(normalized).sort().map((name) => `${name}:${normalized[name]}`).join("\n"); +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/multi-cursor-buffer.js +/** +* Multi-cursor buffer that supports independent async iterators over a +* shared append-only log of items. Each `for await` loop gets its own +* cursor starting at position 0, so late consumers still see all +* previously buffered items. +* +* Mirrors the in-process multi-cursor buffering used by `GraphRunStream`. +*/ +var MultiCursorBuffer = class { + #items = []; + #wakeups = /* @__PURE__ */ new Set(); + #closed = false; + push(item) { + this.#items.push(item); + for (const cb of this.#wakeups) cb(); + this.#wakeups.clear(); + } + close() { + this.#closed = true; + for (const cb of this.#wakeups) cb(); + this.#wakeups.clear(); + } + get length() { + return this.#items.length; + } + [Symbol.asyncIterator]() { + let cursor = 0; + return { + next: async () => { + while (true) { + if (cursor < this.#items.length) return { + done: false, + value: this.#items[cursor++] + }; + if (this.#closed) return { + done: true, + value: void 0 + }; + await new Promise((resolve) => { + this.#wakeups.add(resolve); + }); + } + }, + return: async () => ({ + done: true, + value: void 0 + }) + }; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/messages.js +function applyCoreContentDelta(target, delta) { + if (target.type !== delta.type) return structuredClone(delta); + switch (delta.type) { + case "text": return { + ...target, + ...delta, + text: `${"text" in target ? target.text : ""}${delta.text}` + }; + case "reasoning": return { + ...target, + ...delta, + reasoning: `${"reasoning" in target ? target.reasoning : ""}${delta.reasoning}` + }; + case "tool_call_chunk": + case "server_tool_call_chunk": { + const merged = { + ...target, + ...delta + }; + if (delta.id == null && "id" in target && target.id != null) merged.id = target.id; + if (delta.name == null && "name" in target && target.name != null) merged.name = target.name; + merged.args = `${("args" in target ? target.args : "") ?? ""}${delta.args ?? ""}`; + return merged; + } + default: return { + ...target, + ...delta + }; + } +} +function coreContentBlockFromDelta(delta, current) { + switch (delta.type) { + case "text-delta": return { + type: "text", + text: delta.text + }; + case "reasoning-delta": return { + type: "reasoning", + reasoning: delta.reasoning + }; + case "data-delta": { + const merged = { + ...current ?? {}, + data: delta.data + }; + if (delta.encoding) merged.encoding = delta.encoding; + return merged; + } + case "block-delta": return delta.fields; + } +} +function applyCoreEventDelta(current, event) { + if (event.content) return current ? applyCoreContentDelta(current, event.content) : event.content; + switch (event.delta.type) { + case "text-delta": + if (current?.type === "text") return { + ...current, + text: `${"text" in current ? current.text : ""}${event.delta.text}` + }; + return coreContentBlockFromDelta(event.delta, current); + case "reasoning-delta": + if (current?.type === "reasoning") return { + ...current, + reasoning: `${"reasoning" in current ? current.reasoning : ""}${event.delta.reasoning}` + }; + return coreContentBlockFromDelta(event.delta, current); + case "data-delta": { + const merged = { ...current ?? {} }; + merged.data = `${merged.data ?? ""}${event.delta.data}`; + if (event.delta.encoding) merged.encoding = event.delta.encoding; + return merged; + } + case "block-delta": return { + ...current ?? {}, + ...event.delta.fields + }; + } +} +function normalizeUsage(usage) { + if (!usage) return void 0; + return { + ...usage, + input_tokens: usage.input_tokens ?? 0, + output_tokens: usage.output_tokens ?? 0, + total_tokens: usage.total_tokens ?? 0 + }; +} +/** +* Symbol keys for assembler → StreamingMessage communication. +* Module-private: invisible to external consumers, accessible to +* {@link StreamingMessageAssembler} within this file. +*/ +var PUSH_TEXT = Symbol("pushText"); +var PUSH_REASONING = Symbol("pushReasoning"); +var PUSH_EVENT = Symbol("pushEvent"); +var UPDATE_CONTEXT = Symbol("updateContext"); +var FINISH = Symbol("finish"); +var ERROR = Symbol("error"); +/** +* Live streaming view of a single message lifecycle, matching the +* in-process `ChatModelStream` dual-interface pattern. +* +* - `text` / `reasoning`: iterate for streaming deltas, or await for +* the full concatenated string after the message completes. +* - `usage`: promise that resolves with token usage on message-finish. +* - `blocks`: the assembled content blocks (updated as deltas arrive). +* +* Created by {@link StreamingMessageAssembler} and yielded by +* the `session.messages` lazy getter. +*/ +var StreamingMessage = class { + id; + namespace; + node; + metadata; + assembled; + #events = new MultiCursorBuffer(); + #textChunks = []; + #reasoningChunks = []; + #textWaiters = []; + #reasoningWaiters = []; + #textDone = false; + #reasoningDone = false; + #resolveText; + #resolveReasoning; + #textPromise; + #reasoningPromise; + constructor(assembled) { + this.id = assembled.id; + this.assembled = assembled; + this.namespace = assembled.namespace; + this.node = assembled.node; + this.metadata = assembled.metadata; + this.#textPromise = new Promise((r) => { + this.#resolveText = r; + }); + this.#reasoningPromise = new Promise((r) => { + this.#resolveReasoning = r; + }); + } + get text() { + const chunks = this.#textChunks; + const waiters = this.#textWaiters; + const getDone = () => this.#textDone; + let cursor = 0; + return { + [Symbol.asyncIterator]() { + return { async next() { + while (true) { + if (cursor < chunks.length) return { + done: false, + value: chunks[cursor++] + }; + if (getDone()) return { + done: true, + value: void 0 + }; + await new Promise((resolve) => { + waiters.push(resolve); + }); + } + } }; + }, + then: this.#textPromise.then.bind(this.#textPromise), + full: { async *[Symbol.asyncIterator]() { + let accumulated = ""; + for await (const chunk of { [Symbol.asyncIterator]: () => ({ next: async () => { + while (true) { + if (cursor < chunks.length) return { + done: false, + value: chunks[cursor++] + }; + if (getDone()) return { + done: true, + value: void 0 + }; + await new Promise((resolve) => { + waiters.push(resolve); + }); + } + } }) }) { + accumulated += chunk; + yield accumulated; + } + } } + }; + } + get reasoning() { + const chunks = this.#reasoningChunks; + const waiters = this.#reasoningWaiters; + const getDone = () => this.#reasoningDone; + let cursor = 0; + return { + [Symbol.asyncIterator]() { + return { async next() { + while (true) { + if (cursor < chunks.length) return { + done: false, + value: chunks[cursor++] + }; + if (getDone()) return { + done: true, + value: void 0 + }; + await new Promise((resolve) => { + waiters.push(resolve); + }); + } + } }; + }, + then: this.#reasoningPromise.then.bind(this.#reasoningPromise), + full: { async *[Symbol.asyncIterator]() { + let accumulated = ""; + for await (const chunk of { [Symbol.asyncIterator]: () => ({ next: async () => { + while (true) { + if (cursor < chunks.length) return { + done: false, + value: chunks[cursor++] + }; + if (getDone()) return { + done: true, + value: void 0 + }; + await new Promise((resolve) => { + waiters.push(resolve); + }); + } + } }) }) { + accumulated += chunk; + yield accumulated; + } + } } + }; + } + get usage() { + const promise = (async () => { + let usage; + for await (const snapshot of this.#usageIterator()) usage = snapshot; + return usage; + })(); + return { + [Symbol.asyncIterator]: () => this.#usageIterator(), + then: promise.then.bind(promise) + }; + } + get toolCalls() { + const events = this.#events; + const iterator = async function* () { + for await (const event of events) if (event.event === "content-block-finish" && event.content.type === "tool_call") yield event.content; + }; + return { + [Symbol.asyncIterator]: iterator, + then: async (onfulfilled, onrejected) => { + try { + const calls = []; + for await (const call of iterator()) calls.push(call); + return onfulfilled ? onfulfilled(calls) : calls; + } catch (err) { + if (onrejected) return onrejected(err); + throw err; + } + }, + full: { async *[Symbol.asyncIterator]() { + const calls = []; + for await (const call of iterator()) { + calls.push(call); + yield [...calls]; + } + } } + }; + } + get output() { + return { then: (onf, onr) => this.#assembleMessage().then(onf, onr) }; + } + get blocks() { + return this.assembled.blocks; + } + [Symbol.asyncIterator]() { + return this.#events[Symbol.asyncIterator](); + } + then(onfulfilled, onrejected) { + return this.#assembleMessage().then(onfulfilled, onrejected); + } + async *#usageIterator() { + for await (const event of this.#events) if (event.event === "message-start" && event.usage) yield normalizeUsage(event.usage); + else if (event.event === "message-finish" && event.usage) yield normalizeUsage(event.usage); + } + async #assembleMessage() { + const contentBlocks = []; + let id; + let usage; + let metadata = {}; + let finishReason; + for await (const event of this.#events) switch (event.event) { + case "message-start": + id = event.id ?? id; + if (event.usage) usage = normalizeUsage(event.usage); + break; + case "content-block-start": + contentBlocks[event.index] = event.content; + break; + case "content-block-delta": { + const current = contentBlocks[event.index]; + contentBlocks[event.index] = applyCoreEventDelta(current, event); + break; + } + case "content-block-finish": + contentBlocks[event.index] = event.content; + break; + case "message-finish": + finishReason = event.reason; + if (event.usage) usage = normalizeUsage(event.usage); + if (event.responseMetadata) metadata = { + ...metadata, + ...event.responseMetadata + }; + break; + default: break; + } + return new AIMessage({ + id, + content: contentBlocks.filter((block) => block != null), + usage_metadata: usage, + response_metadata: { + ...metadata, + ...finishReason ? { finish_reason: finishReason } : {}, + output_version: "v1" + } + }); + } + [PUSH_EVENT](event) { + this.#events.push(event); + } + [UPDATE_CONTEXT](event) { + this.node = event.params.node ?? this.node; + } + [PUSH_TEXT](delta) { + this.#textChunks.push(delta); + const pending = this.#textWaiters.splice(0, this.#textWaiters.length); + for (const waiter of pending) waiter(); + } + [PUSH_REASONING](delta) { + this.#reasoningChunks.push(delta); + const pending = this.#reasoningWaiters.splice(0, this.#reasoningWaiters.length); + for (const waiter of pending) waiter(); + } + [FINISH]() { + this.#textDone = true; + this.#reasoningDone = true; + this.#resolveText(this.#textChunks.join("")); + this.#resolveReasoning(this.#reasoningChunks.join("")); + const textPending = this.#textWaiters.splice(0, this.#textWaiters.length); + for (const waiter of textPending) waiter(); + const reasoningPending = this.#reasoningWaiters.splice(0, this.#reasoningWaiters.length); + for (const waiter of reasoningPending) waiter(); + this.#events.close(); + } + [ERROR]() { + this[FINISH](); + } +}; +function toStreamingMessageHandle(message) { + return new Proxy(message, { + get(target, prop) { + if (prop === "then") return void 0; + const value = Reflect.get(target, prop, target); + return typeof value === "function" ? value.bind(target) : value; + }, + has(target, prop) { + if (prop === "then") return false; + return prop in target; + } + }); +} +function cloneBlock(block) { + return structuredClone(block); +} +function blockFromDelta(delta, current) { + return coreContentBlockFromDelta(delta, current); +} +function applyContentDelta(target, delta) { + if (target.type !== delta.type) return cloneBlock(delta); + switch (delta.type) { + case "text": return { + ...target, + ...delta, + text: `${"text" in target ? target.text : ""}${delta.text}` + }; + case "reasoning": return { + ...target, + ...delta, + reasoning: `${"reasoning" in target ? target.reasoning : ""}${delta.reasoning}` + }; + case "tool_call_chunk": + case "server_tool_call_chunk": { + const merged = { + ...target, + ...delta + }; + if (delta.id == null && "id" in target && target.id != null) merged.id = target.id; + if (delta.name == null && "name" in target && target.name != null) merged.name = target.name; + merged.args = `${("args" in target ? target.args : "") ?? ""}${delta.args ?? ""}`; + return merged; + } + default: return { + ...target, + ...delta + }; + } +} +function messageKeyFor(event) { + const { namespace, node, data } = event.params; + const namespaceKey = namespace.join("/"); + const messageId = data.event === "message-start" ? data.id ?? "" : ""; + return `${namespaceKey}::${node ?? ""}::${messageId}`; +} +function toChatModelStreamEvent(event) { + return event.params.data; +} +/** +* Incrementally assembles `messages` events into complete message objects. +*/ +var MessageAssembler = class { + activeMessages = /* @__PURE__ */ new Map(); + activeByNamespaceNode = /* @__PURE__ */ new Map(); + blockIndexByProtocolIndexAndType = /* @__PURE__ */ new Map(); + /** + * Applies a single message event and returns the resulting assembly update. + * + * @param event - Incoming `messages` event to fold into the assembler state. + */ + consume(event) { + const data = event.params.data; + const namespaceNodeKey = `${event.params.namespace.join("/")}::${event.params.node ?? ""}`; + if (data.event === "message-start") { + const key = messageKeyFor(event); + this.activeByNamespaceNode.set(namespaceNodeKey, key); + const message = { + id: data.id, + namespace: [...event.params.namespace], + node: event.params.node, + metadata: data.metadata, + blocks: [] + }; + this.activeMessages.set(key, message); + return { + kind: "message-start", + key, + message, + event + }; + } + const activeKey = this.activeByNamespaceNode.get(namespaceNodeKey); + if (!activeKey) { + const syntheticKey = `${namespaceNodeKey}::`; + this.activeByNamespaceNode.set(namespaceNodeKey, syntheticKey); + const synthetic = { + id: data.id, + namespace: [...event.params.namespace], + node: event.params.node, + blocks: [] + }; + this.activeMessages.set(syntheticKey, synthetic); + return this.consume(event); + } + const message = this.activeMessages.get(activeKey); + if (!message) throw new Error(`No active message state found for key ${activeKey}`); + if (data.event === "usage") { + message.usage = data.usage; + return { + kind: "usage", + key: activeKey, + message, + event + }; + } + switch (data.event) { + case "content-block-start": + message.blocks[data.index] = cloneBlock(data.content); + this.blockIndexByProtocolIndexAndType.set(blockIndexKey(activeKey, data.index, data.content.type), data.index); + return { + kind: "content-block-start", + key: activeKey, + message, + index: data.index, + block: data.content, + event + }; + case "content-block-delta": { + const deltaEvent = data; + const deltaBlock = deltaEvent.content ?? (deltaEvent.delta != null ? blockFromDelta(deltaEvent.delta, message.blocks[data.index]) : void 0); + if (deltaBlock == null) throw new Error("Received content-block-delta without content"); + const targetIndex = this.resolveBlockIndex(activeKey, message.blocks, data.index, deltaBlock.type); + const current = message.blocks[targetIndex]; + message.blocks[targetIndex] = deltaEvent.content != null ? current == null ? cloneBlock(deltaEvent.content) : applyContentDelta(current, deltaEvent.content) : applyCoreEventDelta(current, data); + return { + kind: "content-block-delta", + key: activeKey, + message, + index: targetIndex, + block: deltaBlock, + event + }; + } + case "content-block-finish": { + const targetIndex = this.resolveFinishBlockIndex(activeKey, data.index, data.content.type); + message.blocks[targetIndex] = cloneBlock(data.content); + return { + kind: "content-block-finish", + key: activeKey, + message, + index: targetIndex, + block: data.content, + event + }; + } + case "message-finish": + message.usage = data.usage; + message.finishMetadata = data.responseMetadata; + this.activeMessages.delete(activeKey); + this.activeByNamespaceNode.delete(namespaceNodeKey); + this.clearBlockIndexAliases(activeKey); + return { + kind: "message-finish", + key: activeKey, + message: structuredClone(message), + event + }; + case "error": + message.error = { + message: data.message, + code: data.code + }; + this.activeMessages.delete(activeKey); + this.activeByNamespaceNode.delete(namespaceNodeKey); + this.clearBlockIndexAliases(activeKey); + return { + kind: "message-error", + key: activeKey, + message: structuredClone(message), + event + }; + } + } + resolveBlockIndex(activeKey, blocks, protocolIndex, blockType) { + const current = blocks[protocolIndex]; + if (current == null || current.type === blockType || areCompatibleBlockTypes(current.type, blockType)) { + this.blockIndexByProtocolIndexAndType.set(blockIndexKey(activeKey, protocolIndex, blockType), protocolIndex); + return protocolIndex; + } + const key = blockIndexKey(activeKey, protocolIndex, blockType); + const existing = this.blockIndexByProtocolIndexAndType.get(key); + if (existing != null) return existing; + const nextIndex = blocks.length; + this.blockIndexByProtocolIndexAndType.set(key, nextIndex); + return nextIndex; + } + resolveFinishBlockIndex(activeKey, protocolIndex, blockType) { + const key = blockIndexKey(activeKey, protocolIndex, blockType); + const existing = this.blockIndexByProtocolIndexAndType.get(key); + if (existing != null) return existing; + this.blockIndexByProtocolIndexAndType.set(key, protocolIndex); + return protocolIndex; + } + clearBlockIndexAliases(activeKey) { + const prefix = `${activeKey}::`; + for (const key of this.blockIndexByProtocolIndexAndType.keys()) if (key.startsWith(prefix)) this.blockIndexByProtocolIndexAndType.delete(key); + } +}; +function blockIndexKey(activeKey, protocolIndex, blockType) { + return `${activeKey}::${protocolIndex}::${blockType}`; +} +function areCompatibleBlockTypes(currentType, nextType) { + const toolCallTypes = /* @__PURE__ */ new Set([ + "tool_call", + "tool_call_chunk", + "tool_use", + "input_json_delta" + ]); + const serverToolCallTypes = /* @__PURE__ */ new Set(["server_tool_call", "server_tool_call_chunk"]); + return toolCallTypes.has(currentType) && toolCallTypes.has(nextType) || serverToolCallTypes.has(currentType) && serverToolCallTypes.has(nextType); +} +/** +* Assembles `messages` events into {@link StreamingMessage} instances +* with live text/reasoning delta streams, matching the in-process +* `ChatModelStream` dual-interface pattern. +*/ +var StreamingMessageAssembler = class { + #assembler = new MessageAssembler(); + #activeStreaming = /* @__PURE__ */ new Map(); + /** + * Folds a single event and returns a new {@link StreamingMessage} + * when a `message-start` is seen, or `undefined` for continuation + * events (deltas, finish, error). + */ + consume(event) { + const update = this.#assembler.consume(event); + if (update == null) return void 0; + switch (update.kind) { + case "message-start": { + const streaming = new StreamingMessage(update.message); + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + this.#activeStreaming.set(update.key, streaming); + return streaming; + } + case "content-block-start": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + } + if (streaming && update.block.type === "text" && "text" in update.block && update.block.text) streaming[PUSH_TEXT](update.block.text); + if (streaming && update.block.type === "reasoning" && "reasoning" in update.block && update.block.reasoning) streaming[PUSH_REASONING](update.block.reasoning); + return; + } + case "content-block-delta": { + const streaming = this.#activeStreaming.get(update.key); + if (!streaming) return void 0; + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + if (update.block.type === "text" && "text" in update.block) streaming[PUSH_TEXT](update.block.text); + if (update.block.type === "reasoning" && "reasoning" in update.block) streaming[PUSH_REASONING](update.block.reasoning); + return; + } + case "content-block-finish": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + } + return; + } + case "usage": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + } + return; + } + case "message-finish": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + streaming[FINISH](); + this.#activeStreaming.delete(update.key); + } + return; + } + case "message-error": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + streaming[ERROR](); + this.#activeStreaming.delete(update.key); + } + return; + } + } + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/media.js +var MEDIA_BLOCK_TYPES = /* @__PURE__ */ new Set([ + "audio", + "image", + "video", + "file" +]); +/** +* Typed error thrown through `media.stream` / rejected from +* `media.blob` / `media.objectURL` when a handle fails before its +* message completes. Carries the bytes accumulated up to the failure +* point on `partialBytes` for callers that want to salvage or diagnose. +*/ +var MediaAssemblyError = class extends Error { + kind; + messageId; + partialBytes; + cause; + constructor(kind, messageId, partialBytes, message, options) { + super(message ?? `media ${kind} for message ${messageId}`); + this.name = "MediaAssemblyError"; + this.kind = kind; + this.messageId = messageId; + this.partialBytes = partialBytes; + this.cause = options?.cause; + } +}; +function base64ToBytes(b64) { + const binary = atob(b64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} +function concatBytes(parts, totalLength) { + const out = new Uint8Array(totalLength); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.byteLength; + } + return out; +} +/** +* Concrete handle implementation shared by all four media types. +* +* One instance per `(messageId, blockType)` pair created by the +* assembler on first matching `content-block-start`. +*/ +var MediaHandleImpl = class { + type; + messageId; + namespace; + node; + id; + mimeType; + url; + width; + height; + filename; + monotonic = true; + error; + #parts = []; + #totalBytes = 0; + #partialSnapshot = /* @__PURE__ */ new Uint8Array(0); + #stream; + #streamController; + #blobResolve; + #blobReject; + #blobPromise; + #transcriptParts = []; + #transcriptResolve; + #transcriptReject; + #transcriptPromise; + #cachedObjectURL; + #urlSourced = false; + #urlFetchPromise; + #lastIndex = -1; + #finished = false; + #settled = false; + #fetchImpl; + constructor(options) { + this.type = options.type; + this.messageId = options.messageId; + this.namespace = options.namespace; + this.node = options.node; + this.id = options.id; + this.mimeType = options.mimeType; + this.url = options.url; + this.#fetchImpl = options.fetch; + this.#blobPromise = new Promise((resolve, reject) => { + this.#blobResolve = resolve; + this.#blobReject = reject; + }); + this.#blobPromise.catch(() => void 0); + this.#transcriptPromise = new Promise((resolve, reject) => { + this.#transcriptResolve = resolve; + this.#transcriptReject = reject; + }); + this.#transcriptPromise.catch(() => void 0); + } + /** Track a block index for the monotonic-ordering diagnostic. */ + observeIndex(index) { + if (index !== this.#lastIndex + 1 && index !== this.#lastIndex) this.monotonic = false; + if (index > this.#lastIndex) this.#lastIndex = index; + } + /** Absorb `mime_type` / per-type extras carried on an incoming block. */ + absorbBlock(block) { + if (this.#urlSourced) return; + if (block.type === "audio") this.#absorbAudio(block); + else if (block.type === "image") this.#absorbImage(block); + else if (block.type === "video") this.#absorbVideo(block); + else if (block.type === "file") this.#absorbFile(block); + } + /** Record that the originating block arrived with `url` not `data`. */ + enterUrlMode(url) { + this.#urlSourced = true; + this.url = url; + } + /** Push a fresh chunk of bytes into the handle. */ + pushBytes(bytes) { + if (this.#finished || this.#settled) return; + if (bytes.byteLength === 0) return; + this.#parts.push(bytes); + this.#totalBytes += bytes.byteLength; + this.#partialSnapshot = concatBytes(this.#parts, this.#totalBytes); + if (this.#streamController != null) try { + this.#streamController.enqueue(bytes); + } catch {} + } + /** Append a transcript fragment from an audio block. */ + pushTranscript(fragment) { + if (this.type !== "audio") return; + if (this.#finished || this.#settled) return; + if (fragment.length === 0) return; + this.#transcriptParts.push(fragment); + } + /** Called on `message-finish`. Settles blob/transcript/stream. */ + finish() { + if (this.#finished || this.#settled) return; + this.#finished = true; + this.#settled = true; + const blob = new Blob([this.#partialSnapshot], { type: this.mimeType ?? "" }); + this.#blobResolve(blob); + this.#transcriptResolve(this.#transcriptParts.length === 0 ? void 0 : this.#transcriptParts.join("")); + try { + this.#streamController?.close(); + } catch {} + } + /** Propagate an error through blob/transcript/stream. */ + fail(kind, reason, cause) { + if (this.#settled) return this.error ?? new MediaAssemblyError(kind, this.messageId, this.#partialSnapshot, reason, { cause }); + this.#settled = true; + const err = new MediaAssemblyError(kind, this.messageId, this.#partialSnapshot, reason, { cause }); + this.error = err; + this.#blobReject(err); + this.#transcriptReject(err); + try { + this.#streamController?.error(err); + } catch {} + return err; + } + get partialBytes() { + return this.#partialSnapshot; + } + get blob() { + if (this.#urlSourced) return this.#fetchUrlSourced().then((bytes) => new Blob([bytes], { type: this.mimeType ?? "" })); + return this.#blobPromise; + } + get transcript() { + return this.#transcriptPromise; + } + get objectURL() { + if (this.#cachedObjectURL != null) { + const cached = this.#cachedObjectURL; + return Promise.resolve(cached); + } + return this.blob.then((blob) => { + if (this.#cachedObjectURL != null) return this.#cachedObjectURL; + const url = URL.createObjectURL(blob); + this.#cachedObjectURL = url; + return url; + }); + } + revoke() { + const url = this.#cachedObjectURL; + if (url == null) return; + this.#cachedObjectURL = void 0; + try { + URL.revokeObjectURL(url); + } catch {} + } + get stream() { + if (this.#stream != null) return this.#stream; + if (this.#urlSourced) return this.#buildUrlStream(); + return this.#buildInlineStream(); + } + #absorbAudio(block) { + const mimeType = block.mime_type ?? block.mimeType; + if (this.mimeType == null && mimeType != null) this.mimeType = mimeType; + if (block.transcript != null && block.transcript.length > 0) this.pushTranscript(block.transcript); + } + #absorbImage(block) { + const mimeType = block.mime_type ?? block.mimeType; + if (this.mimeType == null && mimeType != null) this.mimeType = mimeType; + if (this.width == null && block.width != null) this.width = block.width; + if (this.height == null && block.height != null) this.height = block.height; + } + #absorbVideo(block) { + const mimeType = block.mime_type ?? block.mimeType; + if (this.mimeType == null && mimeType != null) this.mimeType = mimeType; + } + #absorbFile(block) { + const mimeType = block.mime_type ?? block.mimeType; + if (this.mimeType == null && mimeType != null) this.mimeType = mimeType; + if (this.filename == null && block.filename != null) this.filename = block.filename; + } + #buildInlineStream() { + const seed = this.#partialSnapshot; + const alreadyFinished = this.#finished; + const alreadyErrored = this.error; + this.#stream = new ReadableStream({ + start: (controller) => { + this.#streamController = controller; + if (seed.byteLength > 0) controller.enqueue(seed); + if (alreadyErrored != null) { + controller.error(alreadyErrored); + return; + } + if (alreadyFinished) controller.close(); + }, + cancel: () => { + this.#streamController = void 0; + } + }); + return this.#stream; + } + #buildUrlStream() { + const urlSourceFetch = this.#startUrlFetch(); + this.#stream = new ReadableStream({ + start: async (controller) => { + try { + const response = await urlSourceFetch; + if (response.body == null) { + const bytes = new Uint8Array(await response.arrayBuffer()); + if (bytes.byteLength > 0) controller.enqueue(bytes); + controller.close(); + return; + } + const reader = response.body.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value != null) controller.enqueue(value); + } + controller.close(); + } catch (err) { + controller.error(this.fail("fetch-failed", err?.message, err)); + } + }, + cancel: () => { + this.#streamController = void 0; + } + }); + return this.#stream; + } + /** Memoised fetch for URL-sourced blocks — returns one `Response`. */ + #startUrlFetch() { + const url = this.url; + return this.#fetchImpl(url).then((response) => { + if (!response.ok) throw new Error(`fetch(${url}) failed: ${response.status} ${response.statusText}`); + return response; + }); + } + /** Fetch + buffer for URL-sourced `blob` access. Memoised. */ + #fetchUrlSourced() { + if (this.#urlFetchPromise != null) return this.#urlFetchPromise; + this.#urlFetchPromise = (async () => { + try { + const response = await this.#startUrlFetch(); + const bytes = new Uint8Array(await response.arrayBuffer()); + this.#parts.length = 0; + this.#parts.push(bytes); + this.#totalBytes = bytes.byteLength; + this.#partialSnapshot = bytes; + this.#finished = true; + this.#settled = true; + return bytes; + } catch (err) { + throw this.fail("fetch-failed", err?.message, err); + } + })(); + return this.#urlFetchPromise; + } +}; +var MediaAssembler = class { + #callbacks; + #fetch; + #active = /* @__PURE__ */ new Map(); + #activeByNamespaceNode = /* @__PURE__ */ new Map(); + #syntheticCounter = 0; + constructor(options = {}) { + this.#callbacks = options; + if (options.fetch != null) this.#fetch = options.fetch; + else if (typeof fetch === "function") this.#fetch = fetch; + else this.#fetch = () => { + throw new Error("MediaAssembler: no fetch implementation available. Pass `fetch` in options."); + }; + } + /** + * Fold a single `messages` event. Non-media blocks and + * informational events (e.g. `content-block-finish`) are no-ops. + */ + consume(event) { + const data = event.params.data; + const namespace = event.params.namespace; + const node = event.params.node; + const nsNodeKey = `${namespace.join("/")}::${node ?? ""}`; + if (data.event === "message-start") { + this.#flushSlot(nsNodeKey, "finish"); + this.#activeByNamespaceNode.set(nsNodeKey, { + messageId: data.id ?? "", + keys: /* @__PURE__ */ new Set(), + indexKeys: /* @__PURE__ */ new Map() + }); + return; + } + if (data.event === "message-finish") { + this.#flushSlot(nsNodeKey, "finish"); + this.#activeByNamespaceNode.delete(nsNodeKey); + return; + } + if (data.event === "error") { + this.#flushSlot(nsNodeKey, "error", data.message); + this.#activeByNamespaceNode.delete(nsNodeKey); + return; + } + if (data.event !== "content-block-start" && data.event !== "content-block-delta" && data.event !== "content-block-finish") return; + const block = data.content; + const blockIndex = data.index ?? 0; + let active = this.#activeByNamespaceNode.get(nsNodeKey); + if (active == null) { + active = { + messageId: `__synthetic_${++this.#syntheticCounter}`, + keys: /* @__PURE__ */ new Set(), + indexKeys: /* @__PURE__ */ new Map() + }; + this.#activeByNamespaceNode.set(nsNodeKey, active); + } + if (block == null && data.event === "content-block-delta") { + const delta = data.delta; + const deltaKey = active.indexKeys.get(blockIndex); + const deltaHandle = deltaKey != null ? this.#active.get(deltaKey) : void 0; + if (delta == null || typeof delta !== "object") return; + const record = delta; + if (deltaHandle == null) { + if (record.type !== "block-delta" || record.fields == null || typeof record.fields !== "object") return; + const fields = record.fields; + if (!MEDIA_BLOCK_TYPES.has(fields.type)) return; + this.#consumeMediaBlock({ + active, + block: fields, + blockIndex, + dataEvent: data.event, + namespace, + node, + terminal: false, + createIfMissing: true + }); + return; + } + deltaHandle.observeIndex(blockIndex); + if (record.type === "data-delta" && typeof record.data === "string") { + try { + deltaHandle.pushBytes(base64ToBytes(record.data)); + } catch (err) { + deltaHandle.fail("message-error", "invalid base64 on delta", err); + } + return; + } + if (record.type === "block-delta" && record.fields != null && typeof record.fields === "object") { + const fields = record.fields; + deltaHandle.absorbBlock(fields); + if (!deltaHandle.error && fields.data != null) try { + deltaHandle.pushBytes(base64ToBytes(fields.data)); + } catch (err) { + deltaHandle.fail("message-error", "invalid base64 on delta", err); + } + } + return; + } + if (block == null) return; + const blockType = block.type; + if (!MEDIA_BLOCK_TYPES.has(blockType)) return; + this.#consumeMediaBlock({ + active, + block, + blockIndex, + dataEvent: data.event, + namespace, + node, + terminal: data.event === "content-block-finish", + createIfMissing: data.event === "content-block-start" || data.event === "content-block-finish" + }); + } + #consumeMediaBlock({ active, block, blockIndex, dataEvent, namespace, node, terminal, createIfMissing }) { + const blockType = block.type; + if (!MEDIA_BLOCK_TYPES.has(blockType)) return; + const mediaType = blockType; + const key = `${active.messageId}::${mediaType}::${blockIndex}`; + let handle = this.#active.get(key); + const isStart = dataEvent === "content-block-start"; + if (handle == null) { + const isTerminalBlock = terminal; + if (!isStart && !isTerminalBlock && !createIfMissing) return; + const mediaBlock = block; + handle = new MediaHandleImpl({ + type: mediaType, + messageId: active.messageId, + namespace: [...namespace], + node, + id: mediaBlock.id, + mimeType: mediaBlock.mime_type ?? mediaBlock.mimeType, + url: mediaBlock.url != null && mediaBlock.data == null ? mediaBlock.url : void 0, + fetch: this.#fetch + }); + if (mediaBlock.url != null && mediaBlock.data == null) handle.enterUrlMode(mediaBlock.url); + handle.observeIndex(blockIndex); + handle.absorbBlock(block); + if (mediaBlock.data != null) try { + handle.pushBytes(base64ToBytes(mediaBlock.data)); + } catch (err) { + handle.fail("message-error", "invalid base64 on initial block", err); + } + this.#active.set(key, handle); + active.keys.add(key); + active.indexKeys.set(blockIndex, key); + this.#emit(handle); + if (isTerminalBlock) { + handle.finish(); + this.#active.delete(key); + active.keys.delete(key); + active.indexKeys.delete(blockIndex); + } + return; + } + if (terminal) return; + const mediaBlock = block; + handle.observeIndex(blockIndex); + handle.absorbBlock(block); + if (!handle.error && mediaBlock.data != null) try { + handle.pushBytes(base64ToBytes(mediaBlock.data)); + } catch (err) { + handle.fail("message-error", "invalid base64 on delta", err); + } + } + /** + * Finish or fail every media handle currently active under the + * given `(namespace, node)` slot and clear its bookkeeping. Called + * on `message-finish`, `error`, and when a new `message-start` + * rebinds a still-open slot. + */ + #flushSlot(nsNodeKey, mode, errorMessage) { + const active = this.#activeByNamespaceNode.get(nsNodeKey); + if (active == null) return; + for (const key of active.keys) { + const handle = this.#active.get(key); + if (handle != null) if (mode === "finish") handle.finish(); + else handle.fail("message-error", errorMessage); + this.#active.delete(key); + } + active.keys.clear(); + active.indexKeys.clear(); + } + /** + * Abort all outstanding handles with a `stream-closed` error. + * Called when the upstream event source terminates before the + * messages it was assembling had a chance to finish. + */ + close() { + for (const handle of this.#active.values()) handle.fail("stream-closed", "upstream event stream closed"); + this.#active.clear(); + this.#activeByNamespaceNode.clear(); + } + #emit(handle) { + switch (handle.type) { + case "audio": + this.#callbacks.onAudio?.(handle); + break; + case "image": + this.#callbacks.onImage?.(handle); + break; + case "video": + this.#callbacks.onVideo?.(handle); + break; + case "file": + this.#callbacks.onFile?.(handle); + break; + } + this.#callbacks.onMedia?.(handle); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/error.js +/** +* Error wrapper for protocol-level error responses returned by the server. +*/ +var ProtocolError = class extends Error { + code; + response; + constructor(response) { + super(response.message); + this.name = "ProtocolError"; + this.code = response.error; + this.response = response; + } +}; +/** +* Thrown when the v2 WebSocket transport exhausts its automatic reconnect +* budget (`maxReconnectAttempts`) after an unexpected socket close or error. +* +* The transport closes its event queue with this error so consumers of +* `events()` can treat the stream as terminally failed. Set +* `maxReconnectAttempts` to `0` on `client.threads.stream({ transport: +* "websocket" })` to disable reconnect and fail fast on the first drop +* instead. +*/ +var MaxWebSocketReconnectAttemptsError = class extends Error { + /** The configured `maxReconnectAttempts` value that was exceeded. */ + maxAttempts; + constructor(maxAttempts, cause) { + super(`Exceeded maximum WebSocket reconnection attempts (${maxAttempts})`); + this.name = "MaxWebSocketReconnectAttemptsError"; + this.maxAttempts = maxAttempts; + this.cause = cause; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/headless-tools.js +/** +* Parses a headless-tool interrupt `value` from the graph. Accepts both +* `toolCall` (LangChain JS) and `tool_call` (Python / JSON snake_case). +*/ +function parseHeadlessToolInterruptPayload(value) { + if (typeof value !== "object" || value == null) return null; + const v = value; + if (v.type !== "tool") return null; + const rawTc = v.toolCall ?? v.tool_call; + if (typeof rawTc !== "object" || rawTc == null) return null; + const tc = rawTc; + if (typeof tc.name !== "string") return null; + return { + type: "tool", + toolCall: { + id: typeof tc.id === "string" ? tc.id : void 0, + name: tc.name, + args: tc.args + } + }; +} +function isHeadlessToolInterrupt(interrupt) { + return parseHeadlessToolInterruptPayload(interrupt) != null; +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/subscription.js +/** +* Strip dynamic suffixes (after `:`) from a namespace segment. +* +* Mirrors `normalize_namespace_segment` in +* `api/langgraph_api/protocol/namespace.py`. Server-emitted namespaces +* contain runtime-generated suffixes like `"fetcher:abc-uuid"`, while +* user-supplied filters are typically static names (`"fetcher"`). +*/ +function normalizeSegment(segment) { + const idx = segment.indexOf(":"); + return idx === -1 ? segment : segment.slice(0, idx); +} +/** +* Whether `eventNamespace` starts with `prefix`. +* +* Segments are compared literally first; if the prefix segment itself +* contains no `:`, the candidate segment is also compared after its +* dynamic suffix is stripped. This mirrors `is_prefix_match` in +* `api/langgraph_api/protocol/namespace.py` so server-side filtering +* and client-side per-subscription narrowing stay consistent. +*/ +function isPrefixMatch(eventNamespace, prefix) { + if (prefix.length > eventNamespace.length) return false; + for (let i = 0; i < prefix.length; i += 1) { + const segment = prefix[i]; + const candidate = eventNamespace[i]; + if (candidate === segment) continue; + if (segment.includes(":")) return false; + if (normalizeSegment(candidate) === segment) continue; + return false; + } + return true; +} +function namespaceMatches(eventNamespace, prefixes, depth) { + if (!prefixes || prefixes.length === 0) return true; + return prefixes.some((prefix) => { + if (!isPrefixMatch(eventNamespace, prefix)) return false; + if (depth === void 0) return true; + return eventNamespace.length - prefix.length <= depth; + }); +} +/** +* Maps a protocol event method to its subscription channel. +* +* Returns `undefined` for unrecognized methods so that new server-side +* channels (e.g. from extension transformers) don't break existing clients. +* +* @param event - Event whose method should be mapped to a channel. +*/ +function inferChannel(event) { + switch (event.method) { + case "values": return "values"; + case "checkpoints": return "checkpoints"; + case "updates": return "updates"; + case "messages": return "messages"; + case "tools": return "tools"; + case "custom": { + const data = event.params.data; + return data?.name != null ? `custom:${data.name}` : "custom"; + } + case "lifecycle": return "lifecycle"; + case "input.requested": return "input"; + case "tasks": return "tasks"; + default: return; + } +} +/** +* Returns whether an event should be delivered for a subscription definition. +* +* @param event - Event being checked for delivery. +* @param definition - Subscription filter definition to evaluate against. +*/ +function matchesSubscription(event, definition) { + const channel = inferChannel(event); + if (channel === void 0) return false; + const channels = definition.channels; + if (!(channels.includes(channel) || channel.startsWith("custom:") && channels.includes("custom"))) return false; + return namespaceMatches(event.params.namespace, definition.namespaces, definition.depth); +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/stream/message-coercion.js +/** +* Stream-local message coercion for serialized messages returned by +* `getState()`, `getHistory()`, and `values` events. +* +* LangGraph API payloads may carry v1 content blocks as snake_case +* `content_blocks`, while `@langchain/core` message constructors only +* understand camelCase `contentBlocks` (or `content`). Normalize that +* boundary here so stream consumers always see `BaseMessage.text`. +*/ +function tryCoerceMessageLikeToMessage(message) { + const normalized = normalizeAIMessageToolCalls(message); + if (normalized.type === "human" || normalized.type === "user") return new HumanMessage(normalized); + if (normalized.type === "ai" || normalized.type === "assistant") return new AIMessage(normalized); + if (normalized.type === "system") return new SystemMessage(normalized); + if (normalized.type === "tool" && "tool_call_id" in normalized) return new ToolMessage({ + ...normalized, + tool_call_id: normalized.tool_call_id + }); + if (normalized.type === "remove" && normalized.id != null) return new RemoveMessage({ + ...normalized, + id: normalized.id + }); + return coerceMessageLikeToMessage(normalized); +} +function normalizeSerializedContentBlocks(message) { + const record = message; + const contentBlocks = record.contentBlocks ?? record.content_blocks; + if (!Array.isArray(contentBlocks) || contentBlocks.length === 0) return message; + const shouldPreferContentBlocks = isEmptyContent(record.content) || !hasTextContent(record.content) && hasTextContent(contentBlocks); + if (!shouldPreferContentBlocks && record.contentBlocks === contentBlocks) return message; + return { + ...message, + content: shouldPreferContentBlocks ? contentBlocks : record.content, + contentBlocks + }; +} +function normalizeAIMessageToolCalls(message) { + const normalized = normalizeSerializedContentBlocks(message); + const record = normalized; + if (Array.isArray(record.tool_calls) && record.tool_calls.length > 0) return normalized; + const toolCalls = extractToolCallsFromContent(record.content); + if (toolCalls.length === 0) return normalized; + return { + ...normalized, + tool_calls: toolCalls + }; +} +function extractToolCallsFromContent(content) { + if (!Array.isArray(content)) return []; + return content.flatMap((block) => { + if (block == null || typeof block !== "object") return []; + const record = block; + if (record.type !== "tool_call" && record.type !== "tool_use") return []; + return [{ + id: record.id ?? "", + name: record.name ?? "", + args: normalizeToolCallArgs(record.args ?? record.input), + type: "tool_call" + }]; + }); +} +function normalizeToolCallArgs(value) { + if (value != null && typeof value === "object" && !Array.isArray(value)) return value; + if (typeof value === "string" && value.length > 0) try { + const parsed = JSON.parse(value); + if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed; + } catch {} + return {}; +} +function isEmptyContent(content) { + return content == null || content === "" || Array.isArray(content) && content.length === 0; +} +function hasTextContent(content) { + if (typeof content === "string") return content.length > 0; + if (!Array.isArray(content)) return false; + return content.some((block) => { + if (typeof block === "string") return block.length > 0; + if (block == null || typeof block !== "object") return false; + const record = block; + return record.type === "text" && typeof record.text === "string" && record.text.length > 0; + }); +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/ui/messages.js +/** +* Ensures all messages in an array are BaseMessage class instances. +* Messages that are already class instances pass through unchanged. +* Plain message objects (e.g. from API values/history) are converted +* via {@link tryCoerceMessageLikeToMessage}. +*/ +function ensureMessageInstances(messages) { + return messages.map((msg) => { + if (typeof msg.getType === "function") return msg; + return tryCoerceMessageLikeToMessage(msg); + }); +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/tools.js +/** +* Project a runtime handle to the client SDK surface (promise-only +* {@link output}, no {@link status} / {@link error} fields). +*/ +function toClientAssembledToolCall(handle) { + return { + name: handle.name, + callId: handle.callId, + id: handle.id, + namespace: handle.namespace, + input: handle.input, + args: handle.args, + output: handle.outputPromise + }; +} +/** +* Parse wire-format tool payloads into structured values. +* +* Tool events may carry JSON-encoded object strings on the wire; this +* helper normalises them to plain objects for consumers. Non-JSON strings +* are returned unchanged. +*/ +function parseToolPayload(value) { + if (typeof value !== "string") return value; + const trimmed = value.trim(); + if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return value; + try { + return JSON.parse(trimmed); + } catch { + return value; + } +} +/** +* Skip wrapper `task` tool events scoped to a subagent namespace. +* +* Deep-agent subagents are discovered from root-level `task` tool calls; +* replaying the same dispatch tool inside the worker namespace would +* otherwise surface as a spurious entry in `sub.toolCalls`. +*/ +function shouldIgnoreScopedTaskToolEvent(scopeNamespace, event) { + const data = event.params.data; + return scopeNamespace.length > 0 && event.params.namespace.length === scopeNamespace.length && event.params.namespace.every((segment, index) => segment === scopeNamespace[index]) && "tool_name" in data && data.tool_name === "task"; +} +function getWireMessageField(message, field) { + if (!message || typeof message !== "object" || Array.isArray(message)) return; + const record = message; + if (field in record) return record[field]; + const kwargs = record.kwargs; + if (kwargs != null && field in kwargs) return kwargs[field]; + const lcKwargs = record.lc_kwargs; + if (lcKwargs != null && field in lcKwargs) return lcKwargs[field]; +} +function isToolMessageLike(value) { + if (!value || typeof value !== "object") return false; + if (value.type === "tool") return true; + if (getWireMessageField(value, "type") === "tool") return true; + return typeof getWireMessageField(value, "tool_call_id") === "string" && getWireMessageField(value, "content") !== void 0; +} +function isCommandLike(value) { + return !!value && typeof value === "object" && value.lg_name === "Command"; +} +function textFromContentBlocks(content) { + let out = ""; + for (const block of content) { + if (!block || typeof block !== "object") continue; + const record = block; + if (record.type === "text" && typeof record.text === "string") out += record.text; + } + return out; +} +/** +* Normalise tool-result `content` from a wire ToolMessage into the value +* a tool implementation returned (object, string, etc.). +*/ +function parseToolResultContent(content) { + if (content == null) return null; + if (typeof content === "string") { + if (content.trim().length === 0) return null; + return parseToolPayload(content); + } + if (Array.isArray(content)) { + const text = textFromContentBlocks(content); + if (text.length === 0) return null; + return parseToolPayload(text); + } + if (typeof content === "object") return content; + return null; +} +function parseToolMessageRecord(message) { + return parseToolResultContent(getWireMessageField(message, "content")); +} +function parseCommandToolOutput(command, toolCallId) { + const update = command.update; + if (update == null || typeof update !== "object" || Array.isArray(update)) return { found: false }; + const messages = update.messages; + if (!Array.isArray(messages)) return { found: false }; + const toolMessages = messages.filter((message) => isToolMessageLike(message)); + if (toolMessages.length === 0) return { found: false }; + if (toolCallId != null) { + for (const message of toolMessages) { + if (getWireMessageField(message, "tool_call_id") !== toolCallId) continue; + return { + found: true, + value: parseToolMessageRecord(message) + }; + } + return { found: false }; + } + if (toolMessages.length === 1) return { + found: true, + value: parseToolMessageRecord(toolMessages[0]) + }; + for (let i = toolMessages.length - 1; i >= 0; i -= 1) { + const parsed = parseToolMessageRecord(toolMessages[i]); + if (parsed != null) return { + found: true, + value: parsed + }; + } + return { + found: true, + value: null + }; +} +/** +* Parse a `tool-finished` output payload into the tool's return value. +* +* Wire events often wrap structured tool results in a ToolMessage-shaped +* object (`{ type: "tool", content: "..." }`) or a LangGraph +* {@link Command} whose `update.messages` carries the ToolMessage. +* This unwraps those envelopes, JSON-decodes string content when possible, +* and leaves plain strings as-is. Returns `null` when a ToolMessage envelope +* is present but its content cannot be normalised. +*/ +function parseToolOutput(value, toolCallId) { + const parsed = parseToolPayload(value); + if (isCommandLike(parsed)) { + const commandOutput = parseCommandToolOutput(parsed, toolCallId); + return commandOutput.found ? commandOutput.value : parsed; + } + if (isToolMessageLike(parsed)) return parseToolResultContent(getWireMessageField(parsed, "content")); + return parsed ?? null; +} +/** +* Incrementally assembles `tools` events into mutable tool-call handles. +* +* Framework consumers store the handle directly; client SDK consumers +* should map with {@link toClientAssembledToolCall} before yielding. +*/ +var ToolCallAssembler = class { + active = /* @__PURE__ */ new Map(); + consume(event) { + const data = event.params.data; + if (data.event === "tool-started") return this.handleStarted(event, data); + if (data.event === "tool-finished") return this.handleFinished(data); + if (data.event === "tool-error") return this.handleError(data); + } + /** + * Reject any in-flight tool calls (e.g. on session close). + */ + failAll(reason) { + for (const entry of this.active.values()) { + entry.rejectOutput(reason); + entry.handle.status = "error"; + entry.handle.error = reason.message; + } + this.active.clear(); + } + handleStarted(event, data) { + let resolveOutput; + let rejectOutput; + const outputPromise = new Promise((resolve, reject) => { + resolveOutput = resolve; + rejectOutput = reject; + }); + outputPromise.catch(() => void 0); + const input = parseToolPayload(data.input); + const name = data.tool_name; + const callId = data.tool_call_id; + const handle = { + name, + callId, + id: callId, + namespace: [...event.params.namespace], + input, + args: input, + output: null, + status: "running", + error: void 0, + outputPromise + }; + this.active.set(callId, { + handle, + resolveOutput, + rejectOutput + }); + return handle; + } + handleFinished(data) { + const entry = this.active.get(data.tool_call_id); + if (!entry) return void 0; + this.active.delete(data.tool_call_id); + const value = parseToolOutput(data.output, data.tool_call_id); + entry.resolveOutput(value); + entry.handle.output = value; + entry.handle.status = "finished"; + entry.handle.error = void 0; + return entry.handle; + } + handleError(data) { + const entry = this.active.get(data.tool_call_id); + if (!entry) return void 0; + this.active.delete(data.tool_call_id); + entry.rejectOutput(new Error(data.message)); + entry.handle.output = null; + entry.handle.status = "error"; + entry.handle.error = data.message; + return entry.handle; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/subgraphs.js +/** +* Discovered subgraph within a streaming session. +* +* Mirrors the in-process `SubgraphRunStream` pattern: each subgraph +* has `name`, `index`, `namespace`, and lazy getters for projections +* scoped to this subgraph's namespace. +* +* ```ts +* for await (const sub of session.subgraphs) { +* for await (const msg of sub.messages) { ... } +* const state = await sub.output; +* } +* ``` +*/ +var SubgraphHandle = class { + name; + index; + namespace; + /** + * Non-empty when upstream attached a `cause` to this subgraph's + * `lifecycle.started` event. Population is product-specific and + * performed by stream transformers on the runtime side (e.g. + * deepagents' `SubagentTransformer` emits + * `{ type: "toolCall", tool_call_id }`). Generic clients should + * treat `cause.type` as an open enum — the protocol allows future + * variants (`send`, `edge`, ...) to be forwarded verbatim without + * a SDK bump. + */ + cause; + graphName; + /** + * Raw `tool-started` event that triggered this subgraph, when + * `cause.type === "toolCall"` and the matching event has been + * observed on the `tools` channel. + */ + toolStartedEvent; + #session; + #messagesIterable; + #valuesProjection; + #toolCallsIterable; + #subgraphsIterable; + #subagentsIterable; + #outputPromise; + #mediaDispatcherStarted = false; + #audioBuffer; + #imagesBuffer; + #videoBuffer; + #filesBuffer; + constructor(name, index, namespace, session, options) { + this.name = name; + this.index = index; + this.namespace = namespace; + this.cause = options?.cause; + this.graphName = options?.graphName; + this.toolStartedEvent = options?.toolStartedEvent; + this.#session = session; + } + get messages() { + if (this.#messagesIterable) return this.#messagesIterable; + const buffer = new MultiCursorBuffer(); + this.#messagesIterable = buffer; + const assembler = new StreamingMessageAssembler(); + this.#startProjection(["messages"], (event) => { + if (event.method !== "messages") return; + const msg = assembler.consume(event); + if (msg) buffer.push(msg); + }, () => buffer.close()); + return buffer; + } + get values() { + if (this.#valuesProjection) return this.#valuesProjection; + const buffer = new MultiCursorBuffer(); + let lastValue; + let resolveOutput; + const outputPromise = new Promise((resolve) => { + resolveOutput = resolve; + }); + this.#outputPromise = outputPromise; + const projection = Object.assign(buffer, { then: (onfulfilled, onrejected) => outputPromise.then(onfulfilled, onrejected) }); + this.#valuesProjection = projection; + this.#startProjection(["values"], (event) => { + if (event.method !== "values") return; + const data = event.params.data; + lastValue = data; + buffer.push(data); + }, () => { + resolveOutput(lastValue); + buffer.close(); + }); + return projection; + } + get toolCalls() { + if (this.#toolCallsIterable) return this.#toolCallsIterable; + const buffer = new MultiCursorBuffer(); + this.#toolCallsIterable = buffer; + const assembler = new ToolCallAssembler(); + this.#startProjection(["tools"], (event) => { + if (event.method !== "tools") return; + const tc = assembler.consume(event); + if (tc) buffer.push(toClientAssembledToolCall(tc)); + }, () => buffer.close()); + return buffer; + } + get subgraphs() { + if (this.#subgraphsIterable) return this.#subgraphsIterable; + const buffer = new MultiCursorBuffer(); + this.#subgraphsIterable = buffer; + (async () => { + const discovery = new SubgraphDiscoveryHandle(await this.#session.subscribe({ + channels: ["lifecycle", "tools"], + namespaces: [this.namespace] + }), this.#session, this.namespace); + for await (const sub of discovery) buffer.push(sub); + buffer.close(); + })(); + return buffer; + } + get subagents() { + if (this.#subagentsIterable) return this.#subagentsIterable; + const buffer = new MultiCursorBuffer(); + this.#subagentsIterable = buffer; + (async () => { + const rawHandle = await this.#session.subscribe({ + channels: ["tools", "lifecycle"], + namespaces: [this.namespace] + }); + const { SubagentDiscoveryHandle: Discovery } = await Promise.resolve().then(() => subagents_exports); + const discovery = new Discovery(rawHandle, this.#session); + for await (const sub of discovery) buffer.push(sub); + buffer.close(); + })(); + return buffer; + } + get audio() { + this.#ensureMediaDispatcher(); + return this.#audioBuffer; + } + get images() { + this.#ensureMediaDispatcher(); + return this.#imagesBuffer; + } + get video() { + this.#ensureMediaDispatcher(); + return this.#videoBuffer; + } + get files() { + this.#ensureMediaDispatcher(); + return this.#filesBuffer; + } + get output() { + this.values; + return this.#outputPromise; + } + #ensureMediaDispatcher() { + if (this.#mediaDispatcherStarted) return; + this.#mediaDispatcherStarted = true; + const audio = new MultiCursorBuffer(); + const images = new MultiCursorBuffer(); + const video = new MultiCursorBuffer(); + const files = new MultiCursorBuffer(); + this.#audioBuffer = audio; + this.#imagesBuffer = images; + this.#videoBuffer = video; + this.#filesBuffer = files; + const assembler = new MediaAssembler({ + onAudio: (m) => audio.push(m), + onImage: (m) => images.push(m), + onVideo: (m) => video.push(m), + onFile: (m) => files.push(m) + }); + this.#startProjection(["messages"], (event) => { + if (event.method !== "messages") return; + assembler.consume(event); + }, () => { + assembler.close(); + audio.close(); + images.close(); + video.close(); + files.close(); + }); + } + subscribe(paramsOrChannels, options = {}) { + if (typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels) return this.#session.subscribe({ + ...paramsOrChannels, + namespaces: paramsOrChannels.namespaces ?? [this.namespace] + }); + return this.#session.subscribe(paramsOrChannels, { + ...options, + namespaces: options.namespaces ?? [this.namespace] + }); + } + async #startProjection(channels, onEvent, onDone) { + try { + const rawHandle = await this.#session.subscribe({ + channels, + namespaces: [this.namespace] + }); + for await (const event of rawHandle) onEvent(event); + } finally { + onDone(); + } + } +}; +/** +* Async iterable that yields {@link SubgraphHandle} instances as new +* subgraph namespaces are discovered from `lifecycle` events. +* +* Mirrors the in-process `run.subgraphs` pattern. A new subgraph is +* discovered when a `lifecycle` event with `event: "started"` is +* received at a namespace depth of exactly `parentDepth + 1`. +*/ +var SubgraphDiscoveryHandle = class { + #source; + #session; + #parentNamespace; + #discovered = /* @__PURE__ */ new Set(); + #pendingToolStarts = /* @__PURE__ */ new Map(); + #pendingToolCallHandles = /* @__PURE__ */ new Map(); + #queue = []; + #waiters = []; + #sourcePump; + #closed = false; + constructor(source, session, parentNamespace = []) { + this.#source = source; + this.#session = session; + this.#parentNamespace = parentNamespace; + } + #emit(handle) { + const waiter = this.#waiters.shift(); + if (waiter) waiter({ + done: false, + value: handle + }); + else this.#queue.push(handle); + } + #processToolEvent(event) { + if (event.method !== "tools") return false; + const tools = event; + const data = tools.params.data; + if (data.event !== "tool-started") return true; + const toolCallId = data.tool_call_id; + if (!toolCallId) return true; + const pendingHandle = this.#pendingToolCallHandles.get(toolCallId); + if (pendingHandle) { + pendingHandle.toolStartedEvent = tools; + this.#pendingToolCallHandles.delete(toolCallId); + return true; + } + this.#pendingToolStarts.set(toolCallId, tools); + return true; + } + #processEvent(event) { + if (this.#processToolEvent(event)) return void 0; + if (event.method !== "lifecycle") return void 0; + const lifecycle = event; + if (lifecycle.params.data.event !== "started") return void 0; + const ns = event.params.namespace; + if (ns.length !== this.#parentNamespace.length + 1) return void 0; + if (!this.#parentNamespace.every((seg, i) => ns[i] === seg)) return void 0; + const nsKey = ns.join("/"); + if (this.#discovered.has(nsKey)) return void 0; + this.#discovered.add(nsKey); + const lastSegment = ns[ns.length - 1] ?? ""; + const colonIdx = lastSegment.lastIndexOf(":"); + let name; + let index; + if (colonIdx >= 0) { + name = lastSegment.slice(0, colonIdx); + const suffix = lastSegment.slice(colonIdx + 1); + index = /^\d+$/.test(suffix) ? Number(suffix) : 0; + } else { + name = lastSegment; + index = 0; + } + const data = lifecycle.params.data; + const cause = data.cause && typeof data.cause === "object" ? data.cause : void 0; + let toolStartedEvent; + if (cause?.type === "toolCall") { + const toolCallId = cause.tool_call_id; + if (toolCallId) { + toolStartedEvent = this.#pendingToolStarts.get(toolCallId); + this.#pendingToolStarts.delete(toolCallId); + } + } + const handle = new SubgraphHandle(name, index, [...ns], this.#session, { + cause, + graphName: data.graph_name, + toolStartedEvent + }); + if (cause?.type === "toolCall" && toolStartedEvent == null) { + const toolCallId = cause.tool_call_id; + if (toolCallId) this.#pendingToolCallHandles.set(toolCallId, handle); + } + return handle; + } + #start() { + if (this.#sourcePump) return; + this.#sourcePump = (async () => { + for await (const event of this.#source) { + const handle = this.#processEvent(event); + if (!handle) continue; + this.#emit(handle); + } + this.#pendingToolStarts.clear(); + this.#pendingToolCallHandles.clear(); + this.#closed = true; + while (this.#waiters.length > 0) this.#waiters.shift()?.({ + done: true, + value: void 0 + }); + })(); + } + async close() { + this.#closed = true; + await this.#source.unsubscribe(); + } + [Symbol.asyncIterator]() { + this.#start(); + return { + next: async () => { + if (this.#queue.length > 0) return { + done: false, + value: this.#queue.shift() + }; + if (this.#closed) return { + done: true, + value: void 0 + }; + return await new Promise((resolve) => { + this.#waiters.push(resolve); + }); + }, + return: async () => { + await this.close(); + return { + done: true, + value: void 0 + }; + } + }; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/subagents.js +var subagents_exports = /* @__PURE__ */ __exportAll({ + SubagentDiscoveryHandle: () => SubagentDiscoveryHandle, + SubagentHandle: () => SubagentHandle +}); +/** +* Discovered subagent within a streaming session. Mirrors the +* in-process `SubagentRunStream` from DeepAgent. +* +* Each subagent is discovered when a `tool-started` event with +* `tool_name === "task"` is observed. The `taskInput` and `output` +* promises resolve from the task tool's lifecycle events. +* +* Use lazy getters (`sub.messages`, `sub.toolCalls`, etc.) for +* namespace-scoped projections. +*/ +var SubagentHandle = class { + name; + callId; + taskInput; + output; + namespace; + #session; + #messagesIterable; + #toolCallsIterable; + #subgraphsIterable; + #mediaDispatcherStarted = false; + #audioBuffer; + #imagesBuffer; + #videoBuffer; + #filesBuffer; + constructor(name, callId, namespace, taskInput, output, session) { + this.name = name; + this.callId = callId; + this.namespace = namespace; + this.taskInput = taskInput; + this.output = output; + this.#session = session; + } + get messages() { + if (this.#messagesIterable) return this.#messagesIterable; + const buffer = new MultiCursorBuffer(); + this.#messagesIterable = buffer; + const assembler = new StreamingMessageAssembler(); + this.#startProjection(["messages"], (event) => { + if (event.method !== "messages") return; + const msg = assembler.consume(event); + if (msg) buffer.push(msg); + }, () => buffer.close()); + return buffer; + } + get toolCalls() { + if (this.#toolCallsIterable) return this.#toolCallsIterable; + const buffer = new MultiCursorBuffer(); + this.#toolCallsIterable = buffer; + const assembler = new ToolCallAssembler(); + this.#startProjection(["tools"], (event) => { + if (event.method !== "tools") return; + const toolsEvent = event; + if (shouldIgnoreScopedTaskToolEvent(this.namespace, toolsEvent)) return; + const tc = assembler.consume(toolsEvent); + if (tc) buffer.push(toClientAssembledToolCall(tc)); + }, () => buffer.close()); + return buffer; + } + get audio() { + this.#ensureMediaDispatcher(); + return this.#audioBuffer; + } + get images() { + this.#ensureMediaDispatcher(); + return this.#imagesBuffer; + } + get video() { + this.#ensureMediaDispatcher(); + return this.#videoBuffer; + } + get files() { + this.#ensureMediaDispatcher(); + return this.#filesBuffer; + } + #ensureMediaDispatcher() { + if (this.#mediaDispatcherStarted) return; + this.#mediaDispatcherStarted = true; + const audio = new MultiCursorBuffer(); + const images = new MultiCursorBuffer(); + const video = new MultiCursorBuffer(); + const files = new MultiCursorBuffer(); + this.#audioBuffer = audio; + this.#imagesBuffer = images; + this.#videoBuffer = video; + this.#filesBuffer = files; + const assembler = new MediaAssembler({ + onAudio: (m) => audio.push(m), + onImage: (m) => images.push(m), + onVideo: (m) => video.push(m), + onFile: (m) => files.push(m) + }); + this.#startProjection(["messages"], (event) => { + if (event.method !== "messages") return; + assembler.consume(event); + }, () => { + assembler.close(); + audio.close(); + images.close(); + video.close(); + files.close(); + }); + } + get subgraphs() { + if (this.#subgraphsIterable) return this.#subgraphsIterable; + const buffer = new MultiCursorBuffer(); + this.#subgraphsIterable = buffer; + (async () => { + const discovery = new SubgraphDiscoveryHandle(await this.#session.subscribe({ + channels: ["lifecycle"], + namespaces: [this.namespace] + }), this.#session, this.namespace); + for await (const sub of discovery) buffer.push(sub); + buffer.close(); + })(); + return buffer; + } + subscribe(paramsOrChannels, options = {}) { + if (typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels) return this.#session.subscribe({ + ...paramsOrChannels, + namespaces: paramsOrChannels.namespaces ?? [this.namespace] + }); + return this.#session.subscribe(paramsOrChannels, { + ...options, + namespaces: options.namespaces ?? [this.namespace] + }); + } + async #startProjection(channels, onEvent, onDone) { + try { + const rawHandle = await this.#session.subscribe({ + channels, + namespaces: [this.namespace] + }); + for await (const event of rawHandle) onEvent(event); + } finally { + onDone(); + } + } +}; +/** +* Async iterable that yields {@link SubagentHandle} instances as task +* tool calls are discovered from the `tools` channel. +* +* Mirrors the in-process `createSubagentTransformer` from DeepAgent: +* watches for `tool_name === "task"` with `tool-started`, extracts +* `subagent_type` and `description` from the input, and resolves +* `output` on `tool-finished`. +*/ +var SubagentDiscoveryHandle = class { + #source; + #session; + #queue = []; + #waiters = []; + #pending = /* @__PURE__ */ new Map(); + #sourcePump; + #closed = false; + constructor(source, session) { + this.#source = source; + this.#session = session; + } + #processEvent(event) { + if (event.method !== "tools") return void 0; + const tools = event; + const data = tools.params.data; + const toolCallId = data.tool_call_id; + if (data.tool_name === "task" && data.event === "tool-started") { + const rawInput = data.input; + const input = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput ?? {}; + const name = input.subagent_type ?? "unknown"; + const description = input.description ?? ""; + let resolveTaskInput; + let resolveOutput; + let rejectOutput; + const taskInput = new Promise((r) => { + resolveTaskInput = r; + }); + const output = new Promise((res, rej) => { + resolveOutput = res; + rejectOutput = rej; + }); + resolveTaskInput(description); + this.#pending.set(toolCallId, { + resolveOutput, + rejectOutput + }); + return new SubagentHandle(name, toolCallId, [...tools.params.namespace], taskInput, output, this.#session); + } + if (toolCallId) { + const pending = this.#pending.get(toolCallId); + if (pending) { + if (data.event === "tool-finished") { + pending.resolveOutput(data.output); + this.#pending.delete(toolCallId); + } else if (data.event === "tool-error") { + const message = data.message ?? "unknown error"; + pending.rejectOutput(new Error(message)); + this.#pending.delete(toolCallId); + } + } + } + } + #start() { + if (this.#sourcePump) return; + this.#sourcePump = (async () => { + for await (const event of this.#source) { + const handle = this.#processEvent(event); + if (!handle) continue; + const waiter = this.#waiters.shift(); + if (waiter) waiter({ + done: false, + value: handle + }); + else this.#queue.push(handle); + } + this.#closed = true; + for (const pending of this.#pending.values()) pending.resolveOutput(void 0); + this.#pending.clear(); + while (this.#waiters.length > 0) this.#waiters.shift()?.({ + done: true, + value: void 0 + }); + })(); + } + async close() { + this.#closed = true; + await this.#source.unsubscribe(); + } + [Symbol.asyncIterator]() { + this.#start(); + return { + next: async () => { + if (this.#queue.length > 0) return { + done: false, + value: this.#queue.shift() + }; + if (this.#closed) return { + done: true, + value: void 0 + }; + return await new Promise((resolve) => { + this.#waiters.push(resolve); + }); + }, + return: async () => { + await this.close(); + return { + done: true, + value: void 0 + }; + } + }; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/index.js +var MESSAGE_LIKE_TYPES = /* @__PURE__ */ new Set([ + "human", + "user", + "ai", + "assistant", + "tool", + "system", + "function", + "remove" +]); +/** +* When the state payload has a `messages` array containing plain +* serialized messages (objects with a recognized `type` field), coerce +* them into `@langchain/core/messages` class instances so remote runs +* expose the same shape as in-process runs. +* +* Returns the input unchanged when the payload is not an object, does +* not include a `messages` key, or contains entries that are already +* class instances / not message-like. +*/ +function coerceStateMessages(value) { + if (value == null || typeof value !== "object" || Array.isArray(value)) return value; + const state = value; + const messages = state.messages; + if (!Array.isArray(messages) || messages.length === 0) return value; + if (!messages.some((msg) => { + if (msg == null || typeof msg !== "object") return false; + if (typeof msg.getType === "function") return false; + const type = msg.type; + return typeof type === "string" && MESSAGE_LIKE_TYPES.has(type); + })) return value; + return { + ...state, + messages: ensureMessageInstances(messages) + }; +} +function namespaceKey(ns) { + return ns.join("\0"); +} +function maxSeq(current, next) { + if (next == null) return current; + if (current == null) return next; + return Math.max(current, next); +} +var ROOT_TERMINAL_LIFECYCLE_EVENTS = /* @__PURE__ */ new Set([ + "completed", + "failed", + "interrupted" +]); +/** +* Detect a root-namespace terminal lifecycle event. Used by +* `#startProjection`'s `endOnRootTerminal` guard to settle per-run +* dispatchers regardless of whether the shared-stream pause logic +* applies to their underlying subscription. +*/ +function isRootTerminalLifecycle(event) { + if (event.method !== "lifecycle") return false; + if (event.params.namespace.length !== 0) return false; + const data = event.params.data; + return data?.event != null && ROOT_TERMINAL_LIFECYCLE_EVENTS.has(data.event); +} +function namespaceListsEqual(a, b) { + if (a === b) return true; + if (a === void 0 || b === void 0) return false; + if (a.length !== b.length) return false; + const aKeys = /* @__PURE__ */ new Set(); + for (const ns of a) aKeys.add(namespaceKey(ns)); + for (const ns of b) if (!aKeys.has(namespaceKey(ns))) return false; + return true; +} +/** +* Structural equality on filters. Two filters are equal iff they +* request the same channel set, the same namespace prefix set +* (with `undefined` meaning wildcard), and the same depth +* (with `undefined` meaning unbounded). +*/ +function filterEqual(a, b) { + if (a === b) return true; + if (a == null || b == null) return false; + if (a.channels.length !== b.channels.length) return false; + const aChannels = new Set(a.channels); + for (const ch of b.channels) if (!aChannels.has(ch)) return false; + if (!namespaceListsEqual(a.namespaces, b.namespaces)) return false; + if ((a.depth ?? null) !== (b.depth ?? null)) return false; + return true; +} +function isPrefix(prefix, candidate) { + if (prefix.length > candidate.length) return false; + for (let i = 0; i < prefix.length; i += 1) if (prefix[i] !== candidate[i]) return false; + return true; +} +/** +* Whether the `coverer` filter delivers every event a subscription +* opened with `target` could want. +* +* Rules: +* - Channels: target.channels must be a subset of coverer.channels. +* - Namespaces: +* - coverer wildcard (`undefined`) → coverer covers all prefixes. +* - coverer explicit + target wildcard → not covered. +* - both explicit → every target prefix must have some coverer +* prefix that is its ancestor (coverer's prefix delivers events +* for all descendants, modulo depth). +* - Depth: +* - coverer unbounded (`undefined`) → depth is covered. +* - otherwise, for each target prefix `tp` covered by coverer +* prefix `cp`, the maximum event depth target wants +* (`tp.length + (target.depth ?? ∞) - cp.length`) must be +* `<= coverer.depth`. For a wildcard target with bounded depth, +* target's max absolute depth is `target.depth` (prefix is `[]`). +*/ +function filterCovers(coverer, target) { + const covererChannels = new Set(coverer.channels); + for (const ch of target.channels) if (!covererChannels.has(ch)) return false; + const covererDepth = coverer.depth; + const targetDepth = target.depth; + if (coverer.namespaces == null) { + if (covererDepth == null) return true; + if (targetDepth == null) return false; + return targetDepth <= covererDepth; + } + if (target.namespaces == null) return false; + for (const tp of target.namespaces) if (!coverer.namespaces.some((cp) => { + if (!isPrefix(cp, tp)) return false; + if (covererDepth == null) return true; + if (targetDepth == null) return false; + return tp.length - cp.length + targetDepth <= covererDepth; + })) return false; + return true; +} +function normalizeSubscribeParams(paramsOrChannels, options = {}) { + if (typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels) return paramsOrChannels; + const channels = Array.isArray(paramsOrChannels) ? [...paramsOrChannels] : [paramsOrChannels]; + return { + ...options, + channels + }; +} +/** +* Fold the ergonomic top-level `forkFrom` checkpoint id into +* `config.configurable.checkpoint_id` and strip `forkFrom` from the +* outgoing params. +* +* `forkFrom` is purely an SDK-side convenience: callers say +* `submit(input, { forkFrom })` instead of hand-building a nested +* RunnableConfig. The agent server only ever accepts the fork target via +* `config.configurable.checkpoint_id` (the same field the legacy run +* endpoints use), so we translate here — before the `run.start` message +* hits the wire — keeping a single, legacy-compliant way to provide it. +* +* `forkFrom` takes precedence over any `checkpoint_id` the caller already +* placed in `config.configurable`, matching the prior server-side merge. +*/ +function foldForkFromIntoConfig(params) { + const { forkFrom, ...rest } = params; + if (typeof forkFrom !== "string" || forkFrom.length === 0) return rest; + const config = rest.config != null && typeof rest.config === "object" ? rest.config : {}; + const configurable = config.configurable != null && typeof config.configurable === "object" ? config.configurable : {}; + return { + ...rest, + config: { + ...config, + configurable: { + ...configurable, + checkpoint_id: forkFrom + } + } + }; +} +/** +* Async iterable handle for raw event subscriptions. +* +* An optional `transform` maps each incoming event before it is queued +* or delivered to a waiting consumer. This is used by named custom +* channel subscriptions (e.g. `"custom:a2a"`) to unwrap the payload +* so callers receive the raw emitted data instead of the protocol +* event envelope. +*/ +var SubscriptionHandle = class { + subscriptionId; + params; + queue = []; + waiters = []; + closed = false; + paused = false; + resumeResolve; + onUnsubscribe; + transform; + constructor(subscriptionId, params, onUnsubscribe, transform) { + this.subscriptionId = subscriptionId; + this.params = params; + this.onUnsubscribe = onUnsubscribe; + this.transform = transform ?? ((event) => event); + } + push(event) { + if (this.closed) return; + const value = this.transform(event); + const waiter = this.waiters.shift(); + if (waiter) { + waiter({ + done: false, + value + }); + return; + } + this.queue.push(value); + } + /** + * Pause the subscription: resolve all waiting iterators with `done: true` + * so `for await` loops exit, but keep the subscription alive. New events + * arriving while paused are still buffered. Call `resume()` to allow + * iterators to consume again. + */ + pause() { + if (this.closed) return; + this.paused = true; + while (this.waiters.length > 0) this.waiters.shift()?.({ + done: true, + value: void 0 + }); + } + /** + * Resume a paused subscription so new `for await` loops can consume + * buffered and future events. + */ + resume() { + this.paused = false; + this.resumeResolve?.(); + this.resumeResolve = void 0; + } + /** + * Returns a promise that resolves when `resume()` is called. Resolves + * immediately if not currently paused. + */ + waitForResume() { + if (!this.paused) return Promise.resolve(); + return new Promise((resolve) => { + this.resumeResolve = resolve; + }); + } + get isPaused() { + return this.paused; + } + close() { + this.closed = true; + this.paused = false; + while (this.waiters.length > 0) this.waiters.shift()?.({ + done: true, + value: void 0 + }); + this.resumeResolve?.(); + this.resumeResolve = void 0; + } + async unsubscribe() { + if (this.closed) return; + this.close(); + await this.onUnsubscribe(this.subscriptionId); + } + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.queue.length > 0) return { + done: false, + value: this.queue.shift() + }; + if (this.closed || this.paused) return { + done: true, + value: void 0 + }; + return await new Promise((resolve) => { + this.waiters.push(resolve); + }); + }, + return: async () => { + this.close(); + return { + done: true, + value: void 0 + }; + } + }; + } +}; +/** +* High-level wrapper around a protocol connection to a specific thread. +* +* In the thread-centric protocol, threads are durable (backed by +* checkpoints) and connections are ephemeral. A `ThreadStream` is the +* client-side handle for interacting with a thread: starting runs, +* subscribing to events, consuming assembled projections (`messages`, +* `values`, `toolCalls`, etc.), and responding to interrupts. +* +* Construct via `client.threads.stream(threadId?, { assistantId? })`. +* +* @typeParam TExtensions - Optional map of `{ name: payload }` pairs +* describing the transformer projections the bound assistant exposes +* on `custom:` channels. Narrows `thread.extensions.` to +* `ThreadExtension`. Defaults to `Record`. +*/ +var ThreadStream = class { + threadId; + ordering = {}; + run; + agent; + input; + state; + /** + * Whether the run was interrupted (a lifecycle "interrupted" event + * was received). Mirrors the in-process `run.interrupted`. + */ + interrupted = false; + /** + * Interrupt payloads collected during the run, if any. + * Mirrors the in-process `run.interrupts`. + */ + interrupts = []; + assistantId; + #nextCommandId; + #transportAdapter; + #pending = /* @__PURE__ */ new Map(); + #subscriptions = /* @__PURE__ */ new Map(); + #seenEventIds = /* @__PURE__ */ new Set(); + /** + * Headless tool interrupts can be auto-resumed by the React hook before + * the shared SSE content pump has processed the root `interrupted` + * lifecycle event. `respondInput()` clears `interrupts`, so keep a + * short-lived marker here until that stale terminal passes through the + * content pump and we can avoid pausing it. + */ + #headlessInterruptsAwaitingTerminal = /* @__PURE__ */ new Set(); + #closed = false; + #opened = false; + #openPromise; + #sharedStream = null; + #sharedStreamFilter = null; + #rotationState = "idle"; + /** Pending `subscribe()` promises waiting for a covering rotation. */ + #pendingSubResolves = []; + #terminalPauseTimer; + #terminalPauseSeq; + #lifecycleSubId = null; + #lifecycleStartPromise; + #runStartReady = null; + #lifecycleWatcherHandle = null; + #lifecycleWatcherStartPromise; + #onEventListeners = /* @__PURE__ */ new Set(); + #messagesIterable; + #valuesProjection; + #toolCallsIterable; + #subgraphsIterable; + #subagentsIterable; + #outputPromise; + #extensionsProxy; + #extensionsCache = /* @__PURE__ */ new Map(); + /** + * Shared state for the single `"custom"` channel subscription that + * backs every `thread.extensions.` handle. + * + * One subscription is opened eagerly from {@link run.start} (mirroring + * the {@link values} eager-start pattern) so that per-name handles + * created before, during, or after the run can all resolve correctly. + * + * - `events` retains every custom event for backfill into + * late-constructed handles. + * - `eventListeners` fan new events out to live per-name handlers. + * - `endListeners` fire when the dispatcher's run terminates, so each + * handle can resolve its `PromiseLike` side with its last-seen + * payload. + */ + #extensionsDispatcherStarted = false; + #extensionsEnded = false; + #extensionsEvents = []; + #extensionsEventListeners = []; + #extensionsEndListeners = []; + /** + * Shared state for the single `messages`-channel subscription that + * backs every media handle iterable (`thread.audio`, `thread.images`, + * `thread.video`, `thread.files`). One subscription serves all four + * iterables; per-type buffers track the handles already emitted so + * late attachers replay through {@link MultiCursorBuffer}. + */ + #mediaDispatcherStarted = false; + #mediaAssembler; + /** Object URLs minted by media handles, tracked for {@link close} cleanup. */ + #mediaHandles = /* @__PURE__ */ new Set(); + #audioBuffer = new MultiCursorBuffer(); + #imagesBuffer = new MultiCursorBuffer(); + #videoBuffer = new MultiCursorBuffer(); + #filesBuffer = new MultiCursorBuffer(); + #fetchOption; + constructor(transportAdapter, options) { + if (!options?.assistantId) throw new Error("ThreadStream requires an assistantId option."); + this.#transportAdapter = transportAdapter; + this.threadId = transportAdapter.threadId; + this.assistantId = options.assistantId; + this.#nextCommandId = options.startingCommandId ?? 1; + this.#fetchOption = options.fetch; + this.run = { start: async (params) => { + this.#prepareForNextRun(); + return await this.#withRunStartGate(() => { + this.#ensureLifecycleTracking(); + this.values; + return this.#send("run.start", { + ...foldForkFromIntoConfig(params), + assistant_id: this.assistantId + }); + }); + } }; + this.agent = { getTree: async (params = {}) => await this.#send("agent.getTree", params) }; + this.input = { + respond: async (params) => { + this.#prepareForNextRun(); + this.#ensureLifecycleTracking(); + this.values; + await this.#send("input.respond", params); + }, + inject: async (params) => { + await this.#send("input.inject", params); + } + }; + this.state = { + get: async (params) => await this.#send("state.get", params), + listCheckpoints: async (params) => await this.#send("state.listCheckpoints", params), + fork: async (params) => await this.#send("state.fork", params) + }; + if (this.#transportAdapter.openEventStream == null) { + this.#transportAdapter.setOnReconnected?.(() => this.#resubscribeWebSocketSubscriptions()); + this.#consumeEvents(); + } + } + /** + * Ensure the underlying transport is connected. + * + * For HTTP/SSE this is a no-op. For WebSocket this performs the + * handshake. Called lazily on first command; safe to call multiple times. + */ + async #ensureOpen() { + if (this.#opened) return; + if (this.#openPromise == null) this.#openPromise = this.#transportAdapter.open().then(() => { + this.#opened = true; + }); + await this.#openPromise; + } + /** + * Channels bundled into every lazy getter's SSE filter so that + * interrupt tracking works without a separate lifecycle subscription. + */ + #lifecycleChannels() { + return ["lifecycle", "input"]; + } + /** + * Lazily start a dedicated lifecycle+input subscription so that + * `thread.interrupted` / `thread.interrupts` work even when the + * caller never accesses a lazy getter (e.g. they only call + * `run.start` and `subscribe({ channels: ["custom:..."] })`). + * + * Idempotent and fire-and-forget — invoked from `run.start` and + * `input.respond`. + */ + #ensureLifecycleTracking() { + if (this.#lifecycleStartPromise != null) return; + this.#lifecycleStartPromise = (async () => { + this.#lifecycleSubId = (await this.#subscribeRaw({ channels: this.#lifecycleChannels() })).subscriptionId; + })().catch(() => void 0); + } + /** + * Run `operation` (a `run.start` send) while holding the run-start + * gate. Sets `#runStartReady` before invoking `operation` so any + * subscription kicked off synchronously inside it (e.g. the lifecycle + * watcher and the values projection) sees the gate when it eventually + * reaches `#startLifecycleWatcherSse` / `#reconcileStream` / + * `#subscribeViaCommand` and awaits it. The gate resolves the moment + * `operation` settles, so server-side subscribes land immediately + * after the thread is committed. + */ + async #withRunStartGate(operation) { + let resolveGate; + let rejectGate; + const gate = new Promise((resolve, reject) => { + resolveGate = resolve; + rejectGate = reject; + }); + this.#runStartReady = gate; + gate.catch(() => void 0); + try { + const result = await operation(); + resolveGate(); + return result; + } catch (err) { + rejectGate(err); + throw err; + } finally { + if (this.#runStartReady === gate) this.#runStartReady = null; + } + } + /** + * Reset interrupt state and resume all paused user subscriptions. + * Called before `run.start()` and `input.respond()` so that + * iterators on the same handle pick up the next run's events. + * + * @param respondedInterruptId - When responding to one of several + * pending interrupts, only that entry is removed. Clearing the + * full list here would drop other headless-tool interrupts that + * are still awaiting client execution. + */ + #prepareForNextRun(respondedInterruptId) { + this.interrupted = false; + if (respondedInterruptId != null) { + const respondedIds = new Set(Array.isArray(respondedInterruptId) ? respondedInterruptId : [respondedInterruptId]); + for (let index = this.interrupts.length - 1; index >= 0; index -= 1) if (respondedIds.has(this.interrupts[index].interruptId)) this.interrupts.splice(index, 1); + } else this.interrupts.length = 0; + if (this.#terminalPauseTimer != null) { + clearTimeout(this.#terminalPauseTimer); + this.#terminalPauseTimer = void 0; + } + this.#terminalPauseSeq = void 0; + for (const [id, subscription] of this.#subscriptions) if (id !== this.#lifecycleSubId) subscription.resume(); + } + /** + * Streaming messages. Each `for await` loop gets an independent cursor + * over the shared buffer; late consumers see all previously emitted + * messages. Mirrors the in-process `run.messages`. + */ + get messages() { + if (this.#messagesIterable) return this.#messagesIterable; + const buffer = new MultiCursorBuffer(); + this.#messagesIterable = buffer; + const assembler = new StreamingMessageAssembler(); + this.#startProjection(["messages", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "messages") return; + const msg = assembler.consume(event); + if (msg) buffer.push(toStreamingMessageHandle(msg)); + }, () => buffer.close()); + return buffer; + } + /** + * State values. Iterable for intermediate snapshots; also + * `PromiseLike` — `await thread.values` resolves with the final + * state. Mirrors the in-process `run.values`. + */ + get values() { + if (this.#valuesProjection) return this.#valuesProjection; + const buffer = new MultiCursorBuffer(); + let lastValue; + let resolveOutput; + const outputPromise = new Promise((resolve) => { + resolveOutput = resolve; + }); + this.#outputPromise = outputPromise; + const projection = Object.assign(buffer, { then: (onfulfilled, onrejected) => outputPromise.then(onfulfilled, onrejected) }); + this.#valuesProjection = projection; + this.#startProjection(["values", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "values") return; + const data = coerceStateMessages(event.params.data); + lastValue = data; + buffer.push(data); + }, () => { + resolveOutput(lastValue); + buffer.close(); + }); + return projection; + } + /** + * Tool calls with a promise-based {@link output} for script consumers. + * Mirrors the in-process `run.toolCalls`. + */ + get toolCalls() { + if (this.#toolCallsIterable) return this.#toolCallsIterable; + const buffer = new MultiCursorBuffer(); + this.#toolCallsIterable = buffer; + const assembler = new ToolCallAssembler(); + this.#startProjection(["tools", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "tools") return; + const tc = assembler.consume(event); + if (tc) buffer.push(toClientAssembledToolCall(tc)); + }, () => buffer.close()); + return buffer; + } + /** + * Discovered subgraphs. Mirrors the in-process `run.subgraphs`. + */ + get subgraphs() { + if (this.#subgraphsIterable) return this.#subgraphsIterable; + const buffer = new MultiCursorBuffer(); + this.#subgraphsIterable = buffer; + (async () => { + const discovery = new SubgraphDiscoveryHandle(await this.#subscribeRaw({ channels: ["tools", ...this.#lifecycleChannels()] }), this, []); + for await (const sub of discovery) buffer.push(sub); + buffer.close(); + })(); + return buffer; + } + /** + * Discovered subagents. + */ + get subagents() { + if (this.#subagentsIterable) return this.#subagentsIterable; + const buffer = new MultiCursorBuffer(); + this.#subagentsIterable = buffer; + (async () => { + const discovery = new SubagentDiscoveryHandle(await this.#subscribeRaw({ channels: ["tools", ...this.#lifecycleChannels()] }), this); + for await (const sub of discovery) buffer.push(sub); + buffer.close(); + })(); + return buffer; + } + /** + * Audio media handles, one per message containing at least one + * `AudioBlock`. Each `for await` opens an independent cursor over + * the shared buffer; late consumers replay every previously emitted + * audio handle. + * + * Yields one item per message on the first matching + * `content-block-start` — messages with no audio blocks are skipped. + */ + get audio() { + this.#ensureMediaDispatcher(); + return this.#audioBuffer; + } + /** + * Image media handles, one per message containing at least one + * `ImageBlock`. See {@link audio} for shared semantics. + */ + get images() { + this.#ensureMediaDispatcher(); + return this.#imagesBuffer; + } + /** + * Video media handles, one per message containing at least one + * `VideoBlock`. See {@link audio} for shared semantics. + */ + get video() { + this.#ensureMediaDispatcher(); + return this.#videoBuffer; + } + /** + * File media handles, one per message containing at least one + * `FileBlock`. See {@link audio} for shared semantics. + */ + get files() { + this.#ensureMediaDispatcher(); + return this.#filesBuffer; + } + /** + * Promise that resolves with the final state value when the run + * completes. Shares the `values` getter's SSE connection. + * Mirrors the in-process `run.output`. + */ + get output() { + this.values; + return this.#outputPromise; + } + /** + * Proxy over compile-time {@link StreamTransformer} projections + * exposed by the bound assistant on `custom:` channels. + * + * Each access (e.g. `thread.extensions.toolActivity`) lazily opens a + * dedicated `custom:` subscription, returns a cached + * {@link ThreadExtension} handle that is both `AsyncIterable` + * (streaming items as they arrive) and `PromiseLike` (resolves + * with the final value when the run terminates), and reuses the same + * handle on subsequent access. + * + * Mirrors the in-process `run.extensions.` shape. + */ + get extensions() { + if (this.#extensionsProxy) return this.#extensionsProxy; + const cache = this.#extensionsCache; + const createExtension = (name) => this.#createExtension(name); + this.#extensionsProxy = new Proxy(Object.create(null), { + get: (_target, prop) => { + if (typeof prop !== "string") return void 0; + const cached = cache.get(prop); + if (cached) return cached; + const extension = createExtension(prop); + cache.set(prop, extension); + return extension; + }, + has: (_target, prop) => typeof prop === "string" + }); + return this.#extensionsProxy; + } + /** + * Lazily open one shared subscription on the `custom` channel that + * buffers every custom event for this run and fans it out to any + * per-name extension handles. + * + * Deliberately **lazy**: the dispatcher only starts on first access + * to `thread.extensions.`. Runs that never touch extensions + * pay no subscription cost. Runs that touch extensions after events + * have already fired rely on the server's per-session event buffer, + * which replays matching events to new subscriptions. + * + * Each handle retains a PromiseLike that resolves with the + * transformer's last-observed payload, independent of when the + * caller grabs the handle (before, during, or after the run), as + * long as the server still has the events buffered. + * + * Idempotent. Invoked only from {@link #createExtension}. + */ + #ensureExtensionsDispatcher() { + if (this.#extensionsDispatcherStarted) return; + this.#extensionsDispatcherStarted = true; + this.#startProjection(["custom", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "custom") return; + this.#extensionsEvents.push(event); + for (const listener of this.#extensionsEventListeners) listener(event); + }, () => { + this.#extensionsEnded = true; + const listeners = this.#extensionsEndListeners.splice(0); + for (const listener of listeners) listener(); + }, { endOnRootTerminal: true }); + } + /** + * Open the single shared `messages`-channel subscription that backs + * every media iterable (audio/images/video/files). Idempotent. + * + * The {@link MediaAssembler} fans out to four per-type + * {@link MultiCursorBuffer}s; each buffer feeds its corresponding + * lazy getter. One handle is yielded per `(messageId, blockType)` on + * the first matching `content-block-start`, so messages without any + * media blocks of a given type never appear on that iterable. + */ + #ensureMediaDispatcher() { + if (this.#mediaDispatcherStarted) return; + this.#mediaDispatcherStarted = true; + const assembler = new MediaAssembler({ + fetch: this.#fetchOption, + onAudio: (m) => { + this.#mediaHandles.add(m); + this.#audioBuffer.push(m); + }, + onImage: (m) => { + this.#mediaHandles.add(m); + this.#imagesBuffer.push(m); + }, + onVideo: (m) => { + this.#mediaHandles.add(m); + this.#videoBuffer.push(m); + }, + onFile: (m) => { + this.#mediaHandles.add(m); + this.#filesBuffer.push(m); + } + }); + this.#mediaAssembler = assembler; + this.#startProjection(["messages", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "messages") return; + assembler.consume(event); + }, () => { + assembler.close(); + this.#audioBuffer.close(); + this.#imagesBuffer.close(); + this.#videoBuffer.close(); + this.#filesBuffer.close(); + }); + } + /** + * Build a single {@link ThreadExtension} handle for a named + * `custom:` projection. + * + * The handle reads from the shared extensions dispatcher: past events + * matching {@link name} are backfilled on construction, future events + * arrive via a registered listener, and the handle's `PromiseLike` + * side resolves with its last-seen payload once the run terminates + * (which may already have happened, in which case it resolves on the + * next microtask). + */ + #createExtension(name) { + this.#ensureExtensionsDispatcher(); + const buffer = new MultiCursorBuffer(); + let lastValue; + let resolveFinal; + const finalPromise = new Promise((resolve) => { + resolveFinal = resolve; + }); + const handleEvent = (event) => { + const data = event.params.data; + if (data?.name !== name) return; + lastValue = data.payload; + buffer.push(data.payload); + }; + for (const event of this.#extensionsEvents) handleEvent(event); + this.#extensionsEventListeners.push(handleEvent); + const settle = () => { + resolveFinal(lastValue); + buffer.close(); + }; + if (this.#extensionsEnded) settle(); + else this.#extensionsEndListeners.push(settle); + return Object.assign(buffer, { then: (onfulfilled, onrejected) => finalPromise.then(onfulfilled, onrejected) }); + } + /** + * Generic projection starter: opens a raw subscription with the given + * channels, feeds events through the consumer, and calls onDone when + * the stream ends. + * + * When `endOnRootTerminal` is set, the projection unsubscribes its + * own handle one macrotask after observing a root-namespace terminal + * lifecycle event. This is needed by projections that may be opened + * AFTER a run already terminated: the shared-stream pause logic + * skips subscriptions whose `registeredAfterSeq` is past the + * terminal so raw `subscribe()` callers can keep draining replayed + * descendants — but a per-run dispatcher (e.g. the extensions + * pipeline) needs the projection to settle so its `PromiseLike` + * surface resolves. The macrotask deferral mirrors the deferred + * pause in `#handleIncoming`, giving trailing same-tick custom + * events (transformer `finalize()` flushes) a chance to drain. + */ + async #startProjection(channels, onEvent, onDone, options = {}) { + let endTimer; + let rawHandle; + try { + rawHandle = await this.#subscribeRaw({ channels }); + const handle = rawHandle; + for await (const event of handle) { + onEvent(event); + if (options.endOnRootTerminal && endTimer == null && isRootTerminalLifecycle(event)) endTimer = setTimeout(() => { + endTimer = void 0; + handle.unsubscribe().catch(() => void 0); + }, 0); + } + } catch {} finally { + if (endTimer != null) clearTimeout(endTimer); + onDone(); + } + } + /** + * Start a run without the v1 eager lazy-getter shims. + * + * `run.start` (the v1 entry point) eagerly opens a wildcard `values` + * projection so `thread.output` / `thread.values` resolve regardless + * of access order, and calls `#ensureLifecycleTracking` which opens + * another wildcard `["lifecycle", "input"]` subscription. Both + * subscriptions widen `#computeUnionFilter` to wildcard, defeating + * the progressive-expansion rotation strategy. + * + * `submitRun` skips those shims — callers that manage their own + * content subscriptions (such as `StreamController`) get the narrow + * union filter they asked for. Lifecycle / interrupt tracking is + * instead served by the dedicated `#startLifecycleWatcher`, which + * opens a wildcard `["lifecycle", "input"]` stream alongside the + * narrow content pump on both SSE and WebSocket transports. + */ + async submitRun(params) { + this.#prepareForNextRun(); + return await this.#withRunStartGate(() => { + this.#startLifecycleWatcher(); + return this.#send("run.start", { + ...foldForkFromIntoConfig(params), + assistant_id: this.assistantId + }); + }); + } + /** + * Respond to an interrupt without the v1 eager lazy-getter shims. + * See {@link submitRun} for why this exists alongside + * {@link input.respond}. + */ + async respondInput(params) { + const respondedIds = "responses" in params ? params.responses.map((entry) => entry.interrupt_id) : params.interrupt_id; + this.#prepareForNextRun(respondedIds); + this.#startLifecycleWatcher(); + await this.#send("input.respond", params); + } + /** + * Register a listener for every globally-unique event on the thread. + * + * Fires exactly once per `event_id` across both the content pump + * (user `subscribe()` calls) and the lifecycle watcher. Events + * without an `event_id` always fire through (dedup is best-effort). + * + * Returns an unsubscribe function. Primary consumer is + * `StreamController`, which uses the listener to feed discovery + * runners and pick up deeply-nested interrupts that the narrow + * content pump wouldn't deliver. + */ + onEvent(listener) { + this.#onEventListeners.add(listener); + return () => { + this.#onEventListeners.delete(listener); + }; + } + /** + * Lazily open the wildcard discovery watcher stream. + * + * Idempotent. Used by both transports, but through different + * mechanisms: + * + * - **SSE**: opens a dedicated event stream via + * {@link TransportAdapter.openEventStream}. The stream runs + * outside `#computeUnionFilter`, so the shared SSE stream's + * content pump can stay narrow (e.g. `depth: 1`) while we still + * capture every lifecycle/input event at any depth. + * - **WebSocket**: opens a wildcard watcher subscription + * subscription via the normal command path. The WS server + * delivers matching events on the shared command connection and + * `#handleIncoming` dispatches them through `#fireOnEvent` and + * the thread-level effects — same downstream semantics as the + * SSE watcher, just reusing the transport that's already open. + * + * Why this matters: consumers of {@link onEvent} (notably + * `StreamController`'s subgraph/subagent discovery runners and + * nested interrupt capture) depend on observing namespaced + * lifecycle events at any depth. Without this watcher, WS clients + * would only ever receive events matching the content pump's + * narrow filter (depth 1 from the root), breaking inference rules + * that require deeper descendants (e.g. the "has-descendants" + * signal used to promote a subgraph host). + */ + #startLifecycleWatcher() { + if (this.#lifecycleWatcherStartPromise != null) return; + if (this.#transportAdapter.openEventStream != null) { + this.#lifecycleWatcherStartPromise = this.#startLifecycleWatcherSse(); + return; + } + this.#lifecycleWatcherStartPromise = this.#startLifecycleWatcherWebSocket(); + } + /** + * Public, idempotent entry point to start the wildcard lifecycle + * watcher. + * + * The watcher is normally started lazily by `submitRun` / + * `respondInput` because for fresh (self-created) threads the SSE + * stream would 404 if opened before the server has the thread row. + * Callers that already know the thread exists server-side + * (`StreamController.hydrate` of an existing thread) can use this + * to start the watcher up front. The watcher subscribes to wildcard + * lifecycle events across every namespace, so it sees arbitrarily- + * nested subagent lifecycle messages that the narrow root content + * pump (running at `depth: 1`) wouldn't reach — that's what makes + * subagent discovery work for historical thread loads. + * + * Idempotent — repeat calls reuse the in-flight start promise. + */ + startLifecycleWatcher() { + this.#startLifecycleWatcher(); + } + async #startLifecycleWatcherSse() { + if (this.#runStartReady != null) try { + await this.#runStartReady; + } catch { + return; + } + const filter = { channels: ["lifecycle", "input"] }; + let handle; + try { + handle = this.#transportAdapter.openEventStream(filter); + } catch { + return; + } + try { + await handle.ready; + } catch { + try { + handle.close(); + } catch {} + return; + } + if (this.#closed) { + try { + handle.close(); + } catch {} + return; + } + this.#lifecycleWatcherHandle = handle; + try { + for await (const message of handle.events) { + if (this.#closed) break; + this.#handleLifecycleWatcherMessage(message); + } + } catch {} + } + async #startLifecycleWatcherWebSocket() { + let handle; + try { + handle = await this.#subscribeRaw({ channels: ["lifecycle", "input"] }); + } catch { + return; + } + if (this.#closed) { + try { + handle.close(); + } catch {} + return; + } + try { + for await (const _event of handle) if (this.#closed) break; + } catch {} + } + /** + * Process an event from the dedicated lifecycle watcher stream. + * + * Unlike `#handleIncoming`, this does NOT fan out to user + * subscriptions — user subs with namespace wildcards already widen + * `#computeUnionFilter` and therefore receive the event on the + * content pump. Delivering via both streams would only add per-sub + * dedup churn without expanding what the user can observe. + * + * We still run global-dedup thread-level side effects (interrupt + * capture, `onEvent` fan-out) so deeply-nested interrupts outside + * the content pump's narrow scope are recorded. + */ + #handleLifecycleWatcherMessage(message) { + if (message.type !== "event") return; + if (typeof message.seq === "number") this.ordering.lastSeenSeq = maxSeq(this.ordering.lastSeenSeq, message.seq); + if (message.event_id) this.ordering.lastEventId = message.event_id; + const eventId = message.event_id ?? void 0; + const globallyProcessed = eventId != null && this.#seenEventIds.has(eventId); + if (eventId != null) this.#seenEventIds.add(eventId); + if (globallyProcessed) return; + this.#applyThreadLevelEffects(message); + this.#fireOnEvent(message); + } + #applyThreadLevelEffects(event) { + if (event.method === "lifecycle") { + if (event.params.data.event === "interrupted") this.interrupted = true; + } + if (event.method === "input.requested") { + const data = event.params.data; + const interruptId = data.interrupt_id ?? `interrupt_${this.interrupts.length}`; + this.interrupts.push({ + interruptId, + payload: data.payload, + namespace: [...event.params.namespace] + }); + if (isHeadlessToolInterrupt(data.payload)) this.#headlessInterruptsAwaitingTerminal.add(interruptId); + } + } + #fireOnEvent(event) { + if (this.#onEventListeners.size === 0) return; + for (const listener of this.#onEventListeners) try { + listener(event); + } catch {} + } + async close() { + if (this.#closed) return; + this.#closed = true; + if (this.#terminalPauseTimer != null) { + clearTimeout(this.#terminalPauseTimer); + this.#terminalPauseTimer = void 0; + } + this.#terminalPauseSeq = void 0; + for (const pending of this.#pendingSubResolves) pending.reject(/* @__PURE__ */ new Error("ThreadStream closed")); + this.#pendingSubResolves.length = 0; + if (this.#sharedStream != null) { + try { + this.#sharedStream.close(); + } catch {} + this.#sharedStream = null; + this.#sharedStreamFilter = null; + } + if (this.#lifecycleWatcherHandle != null) { + try { + this.#lifecycleWatcherHandle.close(); + } catch {} + this.#lifecycleWatcherHandle = null; + } + const lifecycleWatcherStartPromise = this.#lifecycleWatcherStartPromise; + this.#lifecycleWatcherStartPromise = void 0; + this.#onEventListeners.clear(); + for (const subscription of this.#subscriptions.values()) subscription.close(); + this.#subscriptions.clear(); + try { + await lifecycleWatcherStartPromise; + } catch {} + for (const handle of this.#mediaHandles) try { + handle.revoke(); + } catch {} + this.#mediaHandles.clear(); + this.#mediaAssembler?.close(); + this.#audioBuffer.close(); + this.#imagesBuffer.close(); + this.#videoBuffer.close(); + this.#filesBuffer.close(); + await this.#transportAdapter.close(); + } + async subscribe(paramsOrChannels, options = {}) { + const isParamsObject = typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels; + const params = normalizeSubscribeParams(paramsOrChannels, options); + return await this.#subscribeRaw(params, { unwrapNamedCustom: !isParamsObject }); + } + async #subscribeRaw(params, options = {}) { + await this.#ensureOpen(); + const { unwrapNamedCustom = true } = options; + const hasOnlyNamedCustom = params.channels.length > 0 && params.channels.every((ch) => ch.startsWith("custom:")); + const transform = unwrapNamedCustom && hasOnlyNamedCustom ? (event) => event.params.data?.payload ?? event : void 0; + if (this.#transportAdapter.openEventStream != null) return this.#subscribeViaSharedStream(params, transform); + return this.#subscribeViaCommand(params, transform); + } + /** + * Subscribe via the single shared SSE connection. + * + * The subscription is registered immediately in `#subscriptions` so + * fan-out can reach it the moment events begin flowing. The returned + * promise resolves after a stream rotation completes whose union + * filter covers this subscription's channels — mirroring the per-sub + * `await streamHandle.ready` semantics callers depended on. + * + * Every subscribe schedules a stream rotation, even when the current + * stream's filter already covers `params`. Rotating opens a fresh + * server-side session that replays the run's full history from + * `seq=0`; without it a late-joining sub would only see events that + * arrive after it registered, because the shared pump's dedup drops + * events the existing sub already consumed. Per-sub dedup + * (`seenEventIds`) protects existing subs from receiving the + * replay as duplicates. Rapid subscribes in the same microtask are + * coalesced by `#scheduleReconcile` into a single rotation. + */ + async #subscribeViaSharedStream(params, transform) { + const subscriptionId = `sse-${this.#nextCommandId++}`; + const handle = new SubscriptionHandle(subscriptionId, params, async (id) => { + this.#subscriptions.delete(id); + this.#scheduleReconcile(); + }, transform); + const subscription = Object.assign(handle, { + filter: params, + registeredAfterSeq: this.ordering.lastSeenSeq, + seenEventIds: /* @__PURE__ */ new Set() + }); + this.#subscriptions.set(subscriptionId, subscription); + const covered = new Promise((resolve, reject) => { + this.#pendingSubResolves.push({ + filter: params, + resolve, + reject + }); + }); + this.#scheduleReconcile(); + try { + await covered; + } catch (err) { + this.#subscriptions.delete(subscriptionId); + throw err; + } + return handle; + } + /** + * Progressive-expansion union of every currently-registered + * subscription's filter. The server receives the narrowest filter + * that still covers every active sub so deeply-namespaced or + * selectively-opened projections don't pull down the entire thread's + * event firehose. + * + * Unioning rules (matching the server's matching semantics in + * `matchesSinkFilter`): + * - Channels: set union. + * - Namespaces: if any subscription requests a wildcard + * (`namespaces === undefined`) the union is wildcard; otherwise + * the union is the deduplicated list of every explicit prefix. + * - Depth: if any subscription is unbounded (`depth === undefined`) + * the union is unbounded; otherwise the union is the maximum + * depth across all subscriptions (matching the per-sub "max + * reach below the prefix" semantics). + * + * Returns `null` when there are no subscriptions. + */ + #computeUnionFilter() { + if (this.#subscriptions.size === 0) return null; + const channels = /* @__PURE__ */ new Set(); + let wildcardNamespaces = false; + const namespaceMap = /* @__PURE__ */ new Map(); + let unboundedDepth = false; + let maxDepth = 0; + for (const sub of this.#subscriptions.values()) { + for (const ch of sub.filter.channels) channels.add(ch); + if (sub.filter.namespaces == null) wildcardNamespaces = true; + else if (!wildcardNamespaces) for (const ns of sub.filter.namespaces) namespaceMap.set(namespaceKey(ns), ns); + if (sub.filter.depth == null) unboundedDepth = true; + else if (!unboundedDepth && sub.filter.depth > maxDepth) maxDepth = sub.filter.depth; + } + const result = { channels: [...channels] }; + if (!wildcardNamespaces) result.namespaces = [...namespaceMap.values()]; + if (!unboundedDepth) result.depth = maxDepth; + return result; + } + /** + * Schedule a stream reconciliation for the next microtask. + * + * Coalesces multiple subscribe/unsubscribe calls in the same tick + * into a single rotation, and serializes across ticks (no two + * rotations ever run concurrently). + */ + #scheduleReconcile() { + if (this.#closed) return; + if (this.#rotationState !== "idle") return; + this.#rotationState = "scheduled"; + queueMicrotask(() => { + if (this.#closed) { + this.#rotationState = "idle"; + return; + } + this.#rotationState = "idle"; + this.#reconcileStream().catch(() => { + this.#rotationState = "idle"; + }); + }); + } + /** + * Reconcile the shared SSE stream to match the desired union filter. + * + * Rotation strategy: open the new stream first, await its `ready`, + * then close the old one. Overlap is absorbed by `#seenEventIds` + * dedup in `#handleIncoming`. + * + * Error handling: + * - Failure before `ready` resolves: reject all pending `subscribe` + * promises whose filter isn't covered by the existing stream, + * and keep the existing stream running for other subscriptions. + * - Failure mid-pump on the active stream: close the thread via + * {@link #failThreadWithError} so higher layers can rebind. + */ + async #reconcileStream() { + if (this.#closed) return; + if (this.#rotationState === "rotating") return; + const desired = this.#computeUnionFilter(); + if (desired == null) return; + if (this.#runStartReady != null) { + try { + await this.#runStartReady; + } catch (err) { + const normalized = err instanceof Error ? err : /* @__PURE__ */ new Error("run.start failed"); + this.#rejectUncoveredPending(normalized); + return; + } + if (this.#closed) return; + if (this.#rotationState === "rotating") return; + } + if (this.#sharedStreamFilter != null && filterEqual(desired, this.#sharedStreamFilter) && this.#pendingSubResolves.length === 0) { + this.#resolvePending(); + return; + } + this.#rotationState = "rotating"; + let newHandle; + try { + newHandle = this.#transportAdapter.openEventStream(desired); + } catch (err) { + this.#rotationState = "idle"; + this.#rejectUncoveredPending(err); + return; + } + try { + await newHandle.ready; + } catch (err) { + this.#rotationState = "idle"; + try { + newHandle.close(); + } catch {} + this.#rejectUncoveredPending(err); + return; + } + if (this.#closed) { + try { + newHandle.close(); + } catch {} + this.#rotationState = "idle"; + return; + } + this.#pumpStream(newHandle); + const oldHandle = this.#sharedStream; + this.#sharedStream = newHandle; + this.#sharedStreamFilter = desired; + if (oldHandle != null) try { + oldHandle.close(); + } catch {} + this.#rotationState = "idle"; + this.#resolvePending(); + const next = this.#computeUnionFilter(); + if (next != null && !filterEqual(next, this.#sharedStreamFilter)) this.#scheduleReconcile(); + } + /** + * Pump events from a shared-stream handle into `#handleIncoming`. + * One pump task runs per open stream; during rotation overlap two + * pumps may be active briefly, with `#seenEventIds` deduping. + */ + async #pumpStream(handle) { + try { + for await (const message of handle.events) { + if (this.#closed) break; + this.#handleIncoming(message); + } + } catch (err) { + if (handle === this.#sharedStream && !this.#closed) this.#failThreadWithError(err); + } + } + /** + * Resolve any pending `subscribe()` promises whose filter is now + * covered by the active shared stream. Called after every successful + * rotation (and after no-op reconciliations). + */ + #resolvePending() { + if (this.#sharedStreamFilter == null) return; + const current = this.#sharedStreamFilter; + if (this.#pendingSubResolves.length === 0) return; + const stillPending = []; + for (const pending of this.#pendingSubResolves) if (filterCovers(current, pending.filter)) pending.resolve(); + else stillPending.push(pending); + this.#pendingSubResolves.length = 0; + this.#pendingSubResolves.push(...stillPending); + } + /** + * Reject pending `subscribe()` promises whose filter isn't covered + * by the existing stream (they're the ones that triggered the + * failed rotation). Covered pending subs are resolved normally — + * they didn't need the new stream. + */ + #rejectUncoveredPending(err) { + if (this.#pendingSubResolves.length === 0) return; + const current = this.#sharedStreamFilter; + const stillPending = []; + for (const pending of this.#pendingSubResolves) if (current != null && filterCovers(current, pending.filter)) pending.resolve(); + else stillPending.push(pending); + this.#pendingSubResolves.length = 0; + for (const pending of stillPending) pending.reject(err); + } + /** + * Terminate the thread due to an unrecoverable shared-stream error. + * Rejects pending commands, closes subscriptions, and marks the + * thread closed so no further rotations occur. + */ + #failThreadWithError(err) { + const normalized = err instanceof Error ? err : new Error(String(err)); + for (const pending of this.#pending.values()) pending.reject(normalized); + this.#pending.clear(); + for (const pending of this.#pendingSubResolves) pending.reject(normalized); + this.#pendingSubResolves.length = 0; + for (const subscription of this.#subscriptions.values()) subscription.close(); + } + /** + * Command-based subscription (WebSocket fallback). The server replays + * matching buffered events on subscribe via the same WebSocket stream. + */ + async #subscribeViaCommand(params, transform) { + const placeholderId = `pending:${this.#nextCommandId}:${Math.random().toString(36).slice(2, 10)}`; + let resolvedId = placeholderId; + const handle = new SubscriptionHandle(placeholderId, params, async () => { + this.#subscriptions.delete(resolvedId); + if (!this.#closed && resolvedId !== placeholderId) await this.#send("subscription.unsubscribe", { subscription_id: resolvedId }).catch((err) => { + if (err instanceof ProtocolError && err.code === "no_such_subscription") return; + throw err; + }); + }, transform); + const subscription = Object.assign(handle, { + filter: params, + registeredAfterSeq: this.ordering.lastSeenSeq, + seenEventIds: /* @__PURE__ */ new Set() + }); + this.#subscriptions.set(placeholderId, subscription); + if (this.#runStartReady != null) try { + await this.#runStartReady; + } catch (err) { + this.#subscriptions.delete(placeholderId); + throw err; + } + let result; + try { + result = await this.#send("subscription.subscribe", params); + } catch (err) { + this.#subscriptions.delete(placeholderId); + throw err; + } + this.#subscriptions.delete(placeholderId); + resolvedId = result.subscription_id; + handle.subscriptionId = resolvedId; + this.#subscriptions.set(resolvedId, subscription); + return handle; + } + /** + * Re-issue `subscription.subscribe` for every active WS subscription + * after the transport reconnects. The server replays buffered events on + * the new socket; client-side `event_id` dedup suppresses duplicates. + */ + async #resubscribeWebSocketSubscriptions() { + if (this.#transportAdapter.openEventStream != null || this.#closed) return; + const entries = [...this.#subscriptions.entries()]; + await Promise.all(entries.map(async ([id, subscription]) => { + if (id.startsWith("pending:")) return; + try { + const nextId = (await this.#send("subscription.subscribe", subscription.filter)).subscription_id; + if (nextId === id) return; + this.#subscriptions.delete(id); + subscription.subscriptionId = nextId; + this.#subscriptions.set(nextId, subscription); + if (this.#lifecycleSubId === id) this.#lifecycleSubId = nextId; + } catch {} + })); + } + async #consumeEvents() { + try { + for await (const message of this.#transportAdapter.events()) this.#handleIncoming(message); + for (const subscription of this.#subscriptions.values()) subscription.close(); + } catch (error) { + const normalized = error instanceof Error ? error : new Error(String(error)); + for (const pending of this.#pending.values()) pending.reject(normalized); + for (const subscription of this.#subscriptions.values()) subscription.close(); + this.#pending.clear(); + } + } + /** + * Pause non-lifecycle subscriptions after a root terminal lifecycle. + * + * The pause is deferred one macrotask so same-run trailing events + * emitted immediately after terminal (for example final `values`) + * can still drain. `terminalSeq` lets replay attachers skip terminals + * that happened before they registered, so late subscribers can keep + * consuming the replayed history they joined for. + */ + #scheduleTerminalPause(terminalSeq) { + if (this.#terminalPauseTimer != null) clearTimeout(this.#terminalPauseTimer); + this.#terminalPauseSeq = terminalSeq ?? null; + this.#terminalPauseTimer = setTimeout(() => { + this.#terminalPauseTimer = void 0; + if (this.#closed) return; + for (const [id, subscription] of this.#subscriptions) { + if (id === this.#lifecycleSubId) continue; + if (terminalSeq != null && subscription.registeredAfterSeq != null && subscription.registeredAfterSeq >= terminalSeq) continue; + subscription.pause(); + } + }, 0); + } + #handleIncoming(message) { + if (message.type === "event") { + if (typeof message.seq === "number") this.ordering.lastSeenSeq = maxSeq(this.ordering.lastSeenSeq, message.seq); + if (message.event_id) this.ordering.lastEventId = message.event_id; + const eventId = message.event_id ?? void 0; + const globallyProcessed = eventId != null && this.#seenEventIds.has(eventId); + if (eventId != null) this.#seenEventIds.add(eventId); + const TERMINAL_LIFECYCLE_EVENTS = /* @__PURE__ */ new Set([ + "interrupted", + "completed", + "failed" + ]); + if (!globallyProcessed) { + this.#applyThreadLevelEffects(message); + this.#fireOnEvent(message); + } + let fannedToAny = false; + for (const subscription of this.#subscriptions.values()) { + if (!matchesSubscription(message, subscription.filter)) continue; + if (eventId != null) { + if (subscription.seenEventIds.has(eventId)) continue; + subscription.seenEventIds.add(eventId); + } + subscription.push(message); + fannedToAny = true; + } + if (fannedToAny && this.#terminalPauseSeq !== void 0 && !(message.method === "lifecycle" && message.params.namespace.length === 0)) { + const eventSeq = typeof message.seq === "number" ? message.seq : void 0; + const terminalSeq = this.#terminalPauseSeq; + if (terminalSeq === null || eventSeq == null || eventSeq > terminalSeq) { + if (this.#terminalPauseTimer != null) { + clearTimeout(this.#terminalPauseTimer); + this.#terminalPauseTimer = void 0; + } + for (const [id, subscription] of this.#subscriptions) if (id !== this.#lifecycleSubId) subscription.resume(); + this.#scheduleTerminalPause(terminalSeq === null ? void 0 : terminalSeq); + } + } + if (fannedToAny && message.method === "lifecycle" && message.params.namespace.length === 0 && TERMINAL_LIFECYCLE_EVENTS.has(message.params.data.event)) { + if (message.params.data.event === "interrupted" && this.#headlessInterruptsAwaitingTerminal.size > 0) { + this.#headlessInterruptsAwaitingTerminal.clear(); + return; + } + this.#scheduleTerminalPause(typeof message.seq === "number" ? message.seq : void 0); + } + return; + } + const messageId = typeof message.id === "number" ? message.id : void 0; + const pending = messageId === void 0 ? void 0 : this.#pending.get(messageId); + if (!pending) return; + if (messageId !== void 0) this.#pending.delete(messageId); + if (message.type === "error") { + pending.reject(new ProtocolError(message)); + return; + } + if (typeof message.meta?.applied_through_seq === "number") this.ordering.lastAppliedThroughSeq = message.meta.applied_through_seq; + pending.resolve(message); + } + async #send(method, params) { + await this.#ensureOpen(); + const id = this.#nextCommandId++; + const command = { + id, + method, + params + }; + const responsePromise = new Promise((resolve, reject) => { + this.#pending.set(id, { + resolve, + reject + }); + }); + const immediate = await this.#transportAdapter.send(command); + if (immediate) { + this.#pending.delete(id); + if (immediate.type === "error") throw new ProtocolError(immediate); + if (typeof immediate.meta?.applied_through_seq === "number") this.ordering.lastAppliedThroughSeq = immediate.meta.applied_through_seq; + return immediate.result; + } + return (await responsePromise).result; + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/queue.js +var AsyncQueue = class { + values = []; + waiters = []; + rejecters = []; + closed = false; + error = null; + push(value) { + if (this.closed) return; + const waiter = this.waiters.shift(); + this.rejecters.shift(); + if (waiter) { + waiter({ + done: false, + value + }); + return; + } + this.values.push(value); + } + close(error) { + if (this.closed) return; + this.closed = true; + this.error = error == null ? null : error instanceof Error ? error : new Error(String(error)); + if (this.error) { + for (const rejecter of this.rejecters.splice(0)) rejecter(this.error); + this.waiters.length = 0; + return; + } + for (const waiter of this.waiters.splice(0)) waiter({ + done: true, + value: void 0 + }); + this.rejecters.length = 0; + } + async shift() { + if (this.values.length > 0) return { + done: false, + value: this.values.shift() + }; + if (this.error) throw this.error; + if (this.closed) return { + done: true, + value: void 0 + }; + return await new Promise((resolve, reject) => { + this.waiters.push(resolve); + this.rejecters.push(reject); + }); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/utils.js +var isRecord = (value) => typeof value === "object" && value !== null; +/** +* Resolve a {@link ProtocolPath} against the transport's currently-bound +* thread. +* +* - a fixed `string` is used verbatim (back-compat: a baked path is +* independent of the bound thread); +* - a function path and the default fallback are evaluated against +* `threadId`, so late-bound / re-bound adapters target the right thread. +* +* Throws when neither a fixed path nor a bound thread is available — i.e. +* a request was attempted before `client.threads.stream(threadId, …)` / +* {@link TransportAdapter.setThreadId} bound a thread. +*/ +function resolveProtocolPath(path, threadId, fallback) { + if (typeof path === "string") return path; + if (!threadId) throw new Error("Protocol transport has no bound threadId. Bind one — the framework calls client.threads.stream(threadId, { transport }) / transport.setThreadId(threadId) — before issuing requests."); + return path ? path(threadId) : fallback(threadId); +} +/** Match {@link BaseClient.prepareFetchOptions}: preserve any apiUrl path prefix. */ +var toAbsoluteUrl = (apiUrl, path) => new URL(`${apiUrl.replace(/\/$/, "")}${path}`); +var toError = (error) => error instanceof Error ? error : new Error(String(error)); +var toWebSocketUrl = (apiUrl) => { + const url = new URL(apiUrl); + url.protocol = url.protocol === "https:" ? "wss:" : "ws:"; + url.search = ""; + url.hash = ""; + return url.toString(); +}; +var hasHeaders = (headers) => Object.values(headers ?? {}).some((value) => value != null); +function mergeHeaders(...headerGroups) { + const merged = new Headers(); + for (const group of headerGroups) { + if (!group) continue; + if (group instanceof Headers) { + group.forEach((value, key) => { + merged.set(key, value); + }); + continue; + } + if (Array.isArray(group)) { + for (const [key, value] of group) if (value == null) merged.delete(key); + else merged.set(key, value); + continue; + } + for (const [key, value] of Object.entries(group)) if (value == null) merged.delete(key); + else merged.set(key, value); + } + return merged; +} +function isProtocolResponse(value) { + return isRecord(value) && typeof value.type === "string" && (value.type === "success" || value.type === "error"); +} +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/http.js +/** +* Transport adapter that speaks the thread-centric protocol over HTTP +* commands plus SSE event streams. Bound to a `threadId` at construction +* or later via {@link setThreadId}; request URLs derive from the +* currently-bound thread. Each {@link openEventStream} call opens an +* independent filtered SSE connection via +* `POST /threads/:thread_id/stream/events`. +*/ +var ProtocolSseTransportAdapter = class { + threadId; + apiUrl; + queue = new AsyncQueue(); + fetchImpl; + defaultHeaders; + onRequest; + fetchFactory; + asyncCaller; + maxReconnectAttempts; + idleReconnect; + onReconnect; + reconnectDelayMs; + paths; + sessionAbortController = new AbortController(); + eventStreams = /* @__PURE__ */ new Set(); + closed = false; + constructor(options) { + this.fetchImpl = options.fetch ?? fetch; + this.apiUrl = options.apiUrl; + this.defaultHeaders = options.defaultHeaders ?? {}; + this.onRequest = options.onRequest; + this.fetchFactory = options.fetchFactory; + this.asyncCaller = options.asyncCaller; + this.maxReconnectAttempts = options.maxReconnectAttempts ?? 5; + this.idleReconnect = options.idleReconnect ?? "auto"; + this.onReconnect = options.onReconnect; + this.reconnectDelayMs = options.reconnectDelayMs ?? reconnectDelayMs; + this.threadId = options.threadId ?? ""; + this.paths = options.paths; + } + /** {@inheritDoc TransportAdapter.setThreadId} */ + setThreadId(threadId) { + this.threadId = threadId; + } + /** + * Command/stream/state URLs derive from the currently-bound thread so a + * single adapter can follow {@link setThreadId} re-binds. A fixed + * `paths.*` string overrides the default and is used as-is. + */ + get commandsUrl() { + return resolveProtocolPath(this.paths?.commands, this.threadId, (id) => `/threads/${id}/commands`); + } + get streamUrl() { + return resolveProtocolPath(this.paths?.stream, this.threadId, (id) => `/threads/${id}/stream/events`); + } + get stateUrl() { + return resolveProtocolPath(this.paths?.state, this.threadId, (id) => `/threads/${id}/state`); + } + /** + * Fetch checkpointed thread state for hydration. + * + * Uses `GET`, matching `client.threads.getState()` and both LangGraph + * Platform and Agent Protocol custom backends (`POST` is reserved for + * `updateState`). + */ + async getState() { + const url = toAbsoluteUrl(this.apiUrl, this.stateUrl); + let requestInit = { + method: "GET", + headers: mergeHeaders(this.defaultHeaders, {}) + }; + if (this.onRequest) requestInit = await this.onRequest(url, requestInit); + const response = await (await this.resolveFetch())(url.toString(), requestInit); + if (response.status === 404) return null; + if (!response.ok) { + const error = toError(/* @__PURE__ */ new Error(`Thread state request failed: ${response.status} ${response.statusText}`)); + error.status = response.status; + throw error; + } + return await response.json(); + } + async resolveFetch() { + if (this.fetchFactory) return await this.fetchFactory(); + return this.fetchImpl; + } + /** + * HTTP/SSE transports have no handshake — connections are made + * per-command and per-subscription. + */ + async open() {} + async send(command) { + const response = await this.request(this.commandsUrl, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(command), + signal: this.sessionAbortController.signal + }); + if (response.status === 202 || response.status === 204) return; + const payload = await response.json(); + if (!isProtocolResponse(payload)) throw new Error("Protocol command did not return a valid response."); + return payload; + } + /** + * WebSocket-style single event stream. + * For the SSE transport this returns a dummy iterable; real event + * delivery happens via {@link openEventStream}. + */ + events() { + const queue = this.queue; + return { [Symbol.asyncIterator]: () => ({ + next: async () => await queue.shift(), + return: async () => { + queue.close(); + return { + done: true, + value: void 0 + }; + } + }) }; + } + openEventStream(params) { + if (this.closed) throw new Error("Protocol transport is closed."); + const ac = new AbortController(); + this.eventStreams.add(ac); + const streamQueue = new AsyncQueue(); + const streamUrl = this.streamUrl; + let resolveReady; + let rejectReady; + const ready = new Promise((resolve, reject) => { + resolveReady = resolve; + rejectReady = reject; + }); + const initialSince = typeof params.since === "number" ? params.since : void 0; + let readySettled = false; + const startStream = async () => { + let attempt = 0; + while (!ac.signal.aborted && !this.closed) try { + const response = await this.request(streamUrl, { + method: "POST", + headers: { + "content-type": "application/json", + accept: "text/event-stream" + }, + body: JSON.stringify({ + channels: params.channels, + ...params.namespaces ? { namespaces: params.namespaces } : {}, + ...params.depth != null ? { depth: params.depth } : {}, + ...!readySettled && initialSince != null ? { since: initialSince } : {} + }), + signal: ac.signal + }, { stream: true }); + if (!readySettled) { + readySettled = true; + resolveReady(); + } + const readable = response.body ?? new ReadableStream({ start(controller) { + controller.close(); + } }); + const enableIdle = this.idleReconnect === "auto" || typeof this.idleReconnect === "number" && this.idleReconnect > 0; + const lines = readable.pipeThrough(BytesLineDecoder()); + const stream = (enableIdle ? lines.pipeThrough(idleReconnectStream({ mode: this.idleReconnect })) : lines).pipeThrough(SSEDecoder()); + const iterable = IterableReadableStream.fromReadableStream(stream); + for await (const event of iterable) { + if (ac.signal.aborted || this.closed) break; + if (isRecord(event.data)) streamQueue.push(event.data); + } + streamQueue.close(); + return; + } catch (error) { + if (ac.signal.aborted || this.closed) { + if (!readySettled) rejectReady(error); + streamQueue.close(); + return; + } + if (this.maxReconnectAttempts <= 0) { + if (!readySettled) rejectReady(error); + streamQueue.close(toError(error)); + return; + } + attempt += 1; + if (attempt > this.maxReconnectAttempts) { + if (!readySettled) rejectReady(error); + streamQueue.close(toError(error)); + return; + } + this.onReconnect?.({ + attempt, + cause: error + }); + const delay = this.reconnectDelayMs(attempt); + if (delay > 0) await new Promise((resolve) => { + setTimeout(resolve, delay); + }); + } + }; + startStream(); + const cleanup = () => { + this.eventStreams.delete(ac); + ac.abort(); + streamQueue.close(); + }; + return { + events: { [Symbol.asyncIterator]: () => ({ + next: async () => await streamQueue.shift(), + return: async () => { + cleanup(); + return { + done: true, + value: void 0 + }; + } + }) }, + ready, + close: cleanup + }; + } + async close() { + if (this.closed) return; + this.closed = true; + this.sessionAbortController.abort(); + for (const ac of this.eventStreams) ac.abort(); + this.eventStreams.clear(); + this.queue.close(); + } + async request(path, init, options) { + const url = toAbsoluteUrl(this.apiUrl, path); + let requestInit = { + ...init, + headers: mergeHeaders(this.defaultHeaders, init.headers) + }; + if (this.onRequest) requestInit = await this.onRequest(url, requestInit); + const useAsyncCaller = this.asyncCaller != null && !options?.stream; + const execute = async () => { + const response = await (await this.resolveFetch())(url.toString(), requestInit); + if (!response.ok) { + if (useAsyncCaller) throw response; + let detail = ""; + try { + const body = await response.text(); + const parsed = JSON.parse(body); + if (typeof parsed === "object" && parsed != null) detail = parsed.message ?? parsed.error ?? ""; + if (!detail) detail = body; + } catch {} + const message = detail ? `Protocol request failed: ${response.status} ${response.statusText} — ${detail}` : `Protocol request failed: ${response.status} ${response.statusText}`; + throw new Error(message); + } + return response; + }; + try { + return useAsyncCaller ? await this.asyncCaller.call(execute) : await execute(); + } catch (error) { + throw toError(error); + } + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/websocket.js +var WEB_SOCKET_CONNECTING = 0; +var WEB_SOCKET_OPEN = 1; +var WEB_SOCKET_CLOSED = 3; +/** +* Transport adapter that speaks the thread-centric protocol over a +* bidirectional WebSocket. Bound to a `threadId` at construction or later +* via {@link setThreadId} — the socket connects to +* `ws://.../threads/:thread_id/stream/events`. +* +* On unexpected disconnect the adapter reconnects with exponential +* backoff (see {@link ProtocolWebSocketTransportOptions.maxReconnectAttempts}). +* The server replays buffered events on the new socket; the SDK +* deduplicates by `event_id`. {@link ProtocolWebSocketTransportOptions.onReconnected} +* runs after each successful reconnect so `ThreadStream` can re-issue +* `subscription.subscribe` commands. +*/ +var ProtocolWebSocketTransportAdapter = class { + threadId; + queue = new AsyncQueue(); + apiUrl; + defaultHeaders; + onRequest; + webSocketFactory; + paths; + maxReconnectAttempts; + onReconnect; + reconnectDelayMs; + onReconnected; + pending = /* @__PURE__ */ new Map(); + socket = null; + closed = false; + intentionalClose = false; + reconnectInFlight = null; + constructor(options) { + this.apiUrl = options.apiUrl; + this.threadId = options.threadId ?? ""; + this.defaultHeaders = options.defaultHeaders; + this.onRequest = options.onRequest; + this.webSocketFactory = options.webSocketFactory ?? ((url) => new WebSocket(url)); + this.paths = options.paths; + this.maxReconnectAttempts = options.maxReconnectAttempts ?? 5; + this.onReconnect = options.onReconnect; + this.onReconnected = options.onReconnected; + this.reconnectDelayMs = options.reconnectDelayMs ?? reconnectDelayMs; + } + /** {@inheritDoc TransportAdapter.setThreadId} */ + setThreadId(threadId) { + if (threadId === this.threadId) return; + if (this.reconnectInFlight != null || this.socket != null && this.socket.readyState !== WEB_SOCKET_CLOSED) throw new Error("Protocol WebSocket transport cannot be rebound to a different thread while the socket is open. Close the current stream and create a new WebSocket transport for the new thread."); + this.threadId = threadId; + } + /** + * Socket URL derives from the currently-bound thread so a single adapter + * can follow {@link setThreadId} re-binds; the next {@link open} connects + * to the new thread. A fixed `paths.stream` string overrides the default. + */ + get streamUrl() { + return resolveProtocolPath(this.paths?.stream, this.threadId, (id) => `/threads/${id}/stream/events`); + } + /** + * Register a callback invoked after each successful reconnect. Used + * by {@link ThreadStream} to re-send active `subscription.subscribe` + * commands. + */ + setOnReconnected(handler) { + this.onReconnected = handler; + } + async open() { + if (this.closed) throw new Error("Protocol WebSocket transport is closed."); + if (this.socket?.readyState === WEB_SOCKET_OPEN) return; + if (this.socket != null) { + this.#detachSocket(this.socket); + this.socket = null; + } + this.assertBrowserSafeTransportConfig(); + const wsUrl = toWebSocketUrl(toAbsoluteUrl(this.apiUrl, this.streamUrl).toString()); + const socket = this.webSocketFactory(wsUrl); + this.socket = socket; + this.intentionalClose = false; + this.#attachSocket(socket); + await new Promise((resolve, reject) => { + const onOpen = () => { + cleanup(); + resolve(); + }; + const onError = () => { + cleanup(); + reject(/* @__PURE__ */ new Error("Failed to open protocol WebSocket.")); + }; + const cleanup = () => { + socket.removeEventListener("open", onOpen); + socket.removeEventListener("error", onError); + }; + socket.addEventListener("open", onOpen, { once: true }); + socket.addEventListener("error", onError, { once: true }); + }); + } + async send(command) { + return await this.sendCommand(command); + } + events() { + const queue = this.queue; + return { [Symbol.asyncIterator]: () => ({ + next: async () => await queue.shift(), + return: async () => { + queue.close(); + return { + done: true, + value: void 0 + }; + } + }) }; + } + async close() { + if (this.closed) return; + this.closed = true; + this.intentionalClose = true; + for (const { reject } of this.pending.values()) reject(/* @__PURE__ */ new Error("Protocol WebSocket connection closed.")); + this.pending.clear(); + this.queue.close(); + const socket = this.socket; + this.socket = null; + if (!socket) return; + this.#detachSocket(socket); + await new Promise((resolve) => { + if (socket.readyState === WEB_SOCKET_CLOSED) { + resolve(); + return; + } + const onClose = () => { + socket.removeEventListener("close", onClose); + resolve(); + }; + socket.addEventListener("close", onClose, { once: true }); + if (socket.readyState === WEB_SOCKET_OPEN || socket.readyState === WEB_SOCKET_CONNECTING) socket.close(); + else resolve(); + }); + } + assertBrowserSafeTransportConfig() { + if (hasHeaders(this.defaultHeaders) || this.onRequest != null) throw new Error("Browser WebSocket protocol transport does not support defaultHeaders or onRequest hooks. Supply a custom protocolWebSocketFactory if you need custom WebSocket setup."); + } + async sendCommand(command) { + let socket = this.socket; + if (this.reconnectInFlight != null && (socket == null || socket.readyState !== WEB_SOCKET_OPEN)) { + await this.reconnectInFlight.catch(() => void 0); + socket = this.socket; + } + if (socket == null || socket.readyState !== WEB_SOCKET_OPEN) throw new Error("Protocol WebSocket is not open."); + return await new Promise((resolve, reject) => { + this.pending.set(command.id, { + resolve, + reject + }); + try { + socket.send(JSON.stringify(command)); + } catch (error) { + this.pending.delete(command.id); + reject(toError(error)); + } + }); + } + #attachSocket(socket) { + socket.addEventListener("message", this.handleMessage); + socket.addEventListener("close", this.handleClose); + socket.addEventListener("error", this.handleSocketError); + } + #detachSocket(socket) { + socket.removeEventListener("message", this.handleMessage); + socket.removeEventListener("close", this.handleClose); + socket.removeEventListener("error", this.handleSocketError); + } + handleMessage = (event) => { + let payload; + try { + payload = JSON.parse(String(event.data)); + } catch { + return; + } + if (isRecord(payload) && typeof payload.id === "number" && (payload.type === "success" || payload.type === "error")) { + const pending = this.pending.get(payload.id); + if (pending) { + this.pending.delete(payload.id); + pending.resolve(payload); + } + return; + } + if (isRecord(payload) && payload.type === "event") this.queue.push(payload); + }; + handleClose = () => { + const socket = this.socket; + if (socket != null) this.#detachSocket(socket); + this.socket = null; + if (this.intentionalClose || this.closed) { + this.queue.close(); + return; + } + this.#handleUnexpectedDisconnect(/* @__PURE__ */ new Error("Protocol WebSocket closed unexpectedly.")); + }; + handleSocketError = () => { + if (this.closed || this.intentionalClose) return; + this.#handleUnexpectedDisconnect(/* @__PURE__ */ new Error("Protocol WebSocket encountered an error.")); + }; + #handleUnexpectedDisconnect(cause) { + const error = toError(cause); + for (const { reject } of this.pending.values()) reject(error); + this.pending.clear(); + if (this.maxReconnectAttempts <= 0) { + this.queue.close(error); + return; + } + this.#scheduleReconnect(cause); + } + #scheduleReconnect(cause) { + if (this.closed || this.intentionalClose) return; + if (this.reconnectInFlight != null) return; + this.reconnectInFlight = this.#runReconnectLoop(cause).finally(() => { + this.reconnectInFlight = null; + }); + } + async #runReconnectLoop(initialCause) { + let lastError = initialCause; + for (let attempt = 1; attempt <= this.maxReconnectAttempts; attempt += 1) { + if (this.closed || this.intentionalClose) return; + this.onReconnect?.({ + attempt, + cause: lastError + }); + const delay = this.reconnectDelayMs(attempt); + if (delay > 0) await new Promise((resolve) => { + setTimeout(resolve, delay); + }); + if (this.closed || this.intentionalClose) return; + try { + await this.open(); + if (this.onReconnected) await this.onReconnected(); + return; + } catch (error) { + lastError = error; + } + } + this.queue.close(new MaxWebSocketReconnectAttemptsError(this.maxReconnectAttempts, lastError)); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/assistants/index.js +var AssistantsClient = class extends BaseClient { + /** + * Get an assistant by ID. + * + * @param assistantId The ID of the assistant. + * @returns Assistant + */ + async get(assistantId, options) { + return this.fetch(`/assistants/${assistantId}`, { signal: options?.signal }); + } + /** + * Get the JSON representation of the graph assigned to a runnable + * @param assistantId The ID of the assistant. + * @param options.xray Whether to include subgraphs in the serialized graph representation. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included. + * @returns Serialized graph + */ + async getGraph(assistantId, options) { + return this.fetch(`/assistants/${assistantId}/graph`, { + params: { xray: options?.xray }, + signal: options?.signal + }); + } + /** + * Get the state and config schema of the graph assigned to a runnable + * @param assistantId The ID of the assistant. + * @returns Graph schema + */ + async getSchemas(assistantId, options) { + return this.fetch(`/assistants/${assistantId}/schemas`, { signal: options?.signal }); + } + /** + * Get the schemas of an assistant by ID. + * + * @param assistantId The ID of the assistant to get the schema of. + * @param options Additional options for getting subgraphs, such as namespace or recursion extraction. + * @returns The subgraphs of the assistant. + */ + async getSubgraphs(assistantId, options) { + if (options?.namespace) return this.fetch(`/assistants/${assistantId}/subgraphs/${options.namespace}`, { + params: { recurse: options?.recurse }, + signal: options?.signal + }); + return this.fetch(`/assistants/${assistantId}/subgraphs`, { + params: { recurse: options?.recurse }, + signal: options?.signal + }); + } + /** + * Create a new assistant. + * @param payload Payload for creating an assistant. + * @returns The created assistant. + */ + async create(payload) { + return this.fetch("/assistants", { + method: "POST", + json: { + graph_id: payload.graphId, + config: payload.config, + context: payload.context, + metadata: payload.metadata, + assistant_id: payload.assistantId, + if_exists: payload.ifExists, + name: payload.name, + description: payload.description + }, + signal: payload.signal + }); + } + /** + * Update an assistant. + * @param assistantId ID of the assistant. + * @param payload Payload for updating the assistant. + * @returns The updated assistant. + */ + async update(assistantId, payload) { + return this.fetch(`/assistants/${assistantId}`, { + method: "PATCH", + json: { + graph_id: payload.graphId, + config: payload.config, + context: payload.context, + metadata: payload.metadata, + name: payload.name, + description: payload.description + }, + signal: payload.signal + }); + } + /** + * Delete an assistant. + * + * @param assistantId ID of the assistant. + * @param deleteThreads If true, delete all threads with `metadata.assistant_id` equal to `assistantId`. Defaults to false. + */ + async delete(assistantId, options) { + return this.fetch(`/assistants/${assistantId}?delete_threads=${options?.deleteThreads ?? false}`, { + method: "DELETE", + signal: options?.signal + }); + } + async search(query) { + const json = { + graph_id: query?.graphId ?? void 0, + name: query?.name ?? void 0, + metadata: query?.metadata ?? void 0, + limit: query?.limit ?? 10, + offset: query?.offset ?? 0, + sort_by: query?.sortBy ?? void 0, + sort_order: query?.sortOrder ?? void 0, + select: query?.select ?? void 0 + }; + const [assistants, response] = await this.fetch("/assistants/search", { + method: "POST", + json, + withResponse: true, + signal: query?.signal + }); + if (query?.includePagination) return { + assistants, + next: response.headers.get("X-Pagination-Next") + }; + return assistants; + } + /** + * Count assistants matching filters. + * + * @param query.metadata Metadata to filter by. Exact match for each key/value. + * @param query.graphId Optional graph id to filter by. + * @param query.name Optional name to filter by. + * @returns Number of assistants matching the criteria. + */ + async count(query) { + return this.fetch(`/assistants/count`, { + method: "POST", + json: { + metadata: query?.metadata ?? void 0, + graph_id: query?.graphId ?? void 0, + name: query?.name ?? void 0 + }, + signal: query?.signal + }); + } + /** + * List all versions of an assistant. + * + * @param assistantId ID of the assistant. + * @returns List of assistant versions. + */ + async getVersions(assistantId, payload) { + return this.fetch(`/assistants/${assistantId}/versions`, { + method: "POST", + json: { + metadata: payload?.metadata ?? void 0, + limit: payload?.limit ?? 10, + offset: payload?.offset ?? 0 + }, + signal: payload?.signal + }); + } + /** + * Change the version of an assistant. + * + * @param assistantId ID of the assistant. + * @param version The version to change to. + * @returns The updated assistant. + */ + async setLatest(assistantId, version, options) { + return this.fetch(`/assistants/${assistantId}/latest`, { + method: "POST", + json: { version }, + signal: options?.signal + }); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/threads/index.js +var ThreadsClient = class extends BaseClient { + /** + * Get a thread by ID. + * + * @param threadId ID of the thread. + * @returns The thread. + */ + async get(threadId, options) { + return this.fetch(`/threads/${threadId}`, { + params: { include: options?.include ?? void 0 }, + signal: options?.signal + }); + } + /** + * Create a new thread. + * + * @param payload Payload for creating a thread. + * @returns The created thread. + */ + async create(payload) { + const ttlPayload = typeof payload?.ttl === "number" ? { + ttl: payload.ttl, + strategy: "delete" + } : payload?.ttl; + return this.fetch(`/threads`, { + method: "POST", + json: { + metadata: { + ...payload?.metadata, + graph_id: payload?.graphId + }, + thread_id: payload?.threadId, + if_exists: payload?.ifExists, + supersteps: payload?.supersteps?.map((s) => ({ updates: s.updates.map((u) => ({ + values: u.values, + command: u.command, + as_node: u.asNode + })) })), + ttl: ttlPayload + }, + signal: payload?.signal + }); + } + /** + * Copy an existing thread + * @param threadId ID of the thread to be copied + * @returns Newly copied thread + */ + async copy(threadId, options) { + return this.fetch(`/threads/${threadId}/copy`, { + method: "POST", + signal: options?.signal + }); + } + async update(threadId, payload) { + const ttlPayload = typeof payload?.ttl === "number" ? { + ttl: payload.ttl, + strategy: "delete" + } : payload?.ttl; + return this.fetch(`/threads/${threadId}`, { + method: "PATCH", + headers: payload?.returnMinimal ? { Prefer: "return=minimal" } : void 0, + json: { + metadata: payload?.metadata, + ttl: ttlPayload + }, + signal: payload?.signal + }); + } + /** + * Delete a thread. + * + * @param threadId ID of the thread. + */ + async delete(threadId, options) { + return this.fetch(`/threads/${threadId}`, { + method: "DELETE", + signal: options?.signal + }); + } + /** + * Prune threads by ID. The 'delete' strategy removes threads entirely. + * The 'keep_latest' strategy prunes old checkpoints but keeps threads + * and their latest state. + * + * @param threadIds List of thread IDs to prune. + * @param options Additional options for pruning. + * @param options.strategy The prune strategy. Defaults to 'delete'. + * @param options.signal Signal to abort the request. + * @returns An object containing `pruned_count`. + */ + async prune(threadIds, options) { + return this.fetch("/threads/prune", { + method: "POST", + json: { + thread_ids: threadIds, + strategy: options?.strategy ?? "delete" + }, + signal: options?.signal + }); + } + /** + * List threads + * + * @param query Query options + * @returns List of threads + */ + async search(query) { + return this.fetch("/threads/search", { + method: "POST", + json: { + metadata: query?.metadata ?? void 0, + ids: query?.ids ?? void 0, + limit: query?.limit ?? 10, + offset: query?.offset ?? 0, + status: query?.status, + sort_by: query?.sortBy, + sort_order: query?.sortOrder, + select: query?.select ?? void 0, + values: query?.values ?? void 0, + extract: query?.extract ?? void 0 + }, + signal: query?.signal + }); + } + /** + * Count threads matching filters. + * + * @param query.metadata Thread metadata to filter on. + * @param query.values State values to filter on. + * @param query.status Thread status to filter on. + * @returns Number of threads matching the criteria. + */ + async count(query) { + return this.fetch(`/threads/count`, { + method: "POST", + json: { + metadata: query?.metadata ?? void 0, + values: query?.values ?? void 0, + status: query?.status ?? void 0 + }, + signal: query?.signal + }); + } + /** + * Get state for a thread. + * + * @param threadId ID of the thread. + * @returns Thread state. + */ + async getState(threadId, checkpoint, options) { + if (checkpoint != null) { + if (typeof checkpoint !== "string") return this.fetch(`/threads/${threadId}/state/checkpoint`, { + method: "POST", + json: { + checkpoint, + subgraphs: options?.subgraphs + }, + signal: options?.signal + }); + return this.fetch(`/threads/${threadId}/state/${checkpoint}`, { + params: { subgraphs: options?.subgraphs }, + signal: options?.signal + }); + } + return this.fetch(`/threads/${threadId}/state`, { + params: { subgraphs: options?.subgraphs }, + signal: options?.signal, + dedupe: true + }); + } + /** + * Add state to a thread. + * + * @param threadId The ID of the thread. + * @returns + */ + async updateState(threadId, options) { + return this.fetch(`/threads/${threadId}/state`, { + method: "POST", + json: { + values: options.values, + checkpoint: options.checkpoint, + checkpoint_id: options.checkpointId, + as_node: options?.asNode + }, + signal: options?.signal + }); + } + /** + * Patch the metadata of a thread. + * + * @param threadIdOrConfig Thread ID or config to patch the state of. + * @param metadata Metadata to patch the state with. + */ + async patchState(threadIdOrConfig, metadata, options) { + let threadId; + if (typeof threadIdOrConfig !== "string") { + if (typeof threadIdOrConfig.configurable?.thread_id !== "string") throw new Error("Thread ID is required when updating state with a config."); + threadId = threadIdOrConfig.configurable.thread_id; + } else threadId = threadIdOrConfig; + return this.fetch(`/threads/${threadId}/state`, { + method: "PATCH", + json: { metadata }, + signal: options?.signal + }); + } + /** + * Get all past states for a thread. + * + * @param threadId ID of the thread. + * @param options Additional options. + * @returns List of thread states. + */ + async getHistory(threadId, options) { + return this.fetch(`/threads/${threadId}/history`, { + method: "POST", + json: { + limit: options?.limit ?? 10, + before: options?.before, + metadata: options?.metadata, + checkpoint: options?.checkpoint + }, + signal: options?.signal, + dedupe: true + }); + } + async *joinStream(threadId, options) { + yield* this.streamWithRetry({ + endpoint: `/threads/${threadId}/stream`, + method: "GET", + signal: options?.signal, + headers: options?.lastEventId ? { "Last-Event-ID": options.lastEventId } : void 0, + params: options?.streamMode ? { stream_mode: options.streamMode } : void 0 + }); + } + stream(threadIdOrOptions, maybeOptions) { + const { threadId, options } = typeof threadIdOrOptions === "string" ? { + threadId: threadIdOrOptions, + options: maybeOptions + } : threadIdOrOptions == null ? { + threadId: v7(), + options: maybeOptions + } : { + threadId: v7(), + options: threadIdOrOptions + }; + const userFetch = options.fetch; + const protocolFetch = userFetch ?? this.asyncCaller.fetch.bind(this.asyncCaller); + let transport; + if (options.transport != null && typeof options.transport !== "string") { + transport = options.transport; + transport.setThreadId?.(threadId); + } else { + const transportKind = options.transport ?? (this.streamProtocol === "v2-websocket" ? "websocket" : "sse"); + const maxReconnectAttempts = options.maxReconnectAttempts ?? 5; + /** + * Common options for both transports. + */ + const commonOpts = { + apiUrl: this.apiUrl, + threadId, + defaultHeaders: this.defaultHeaders, + onRequest: this.onRequest, + maxReconnectAttempts, + reconnectDelayMs: options.reconnectDelayMs, + onReconnect: options.onReconnect + }; + transport = transportKind === "websocket" ? new ProtocolWebSocketTransportAdapter({ + ...commonOpts, + webSocketFactory: options.webSocketFactory + }) : new ProtocolSseTransportAdapter({ + ...commonOpts, + idleReconnect: options.streamIdleReconnect, + fetch: userFetch, + asyncCaller: userFetch ? void 0 : this.asyncCaller + }); + } + return new ThreadStream(transport, { + ...options, + fetch: protocolFetch + }); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/runs/index.js +var RunsClient = class extends BaseClient { + /** + * Create a run and stream the results. + * + * @param threadId The ID of the thread. + * @param assistantId Assistant ID to use for this run. + * @param payload Payload for creating a run. + */ + async *stream(threadId, assistantId, payload) { + const json = { + input: payload?.input, + command: payload?.command, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + stream_mode: payload?.streamMode, + stream_subgraphs: payload?.streamSubgraphs, + stream_resumable: payload?.streamResumable, + feedback_keys: payload?.feedbackKeys, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + checkpoint: payload?.checkpoint, + webhook: payload?.webhook, + multitask_strategy: payload?.multitaskStrategy, + on_completion: payload?.onCompletion, + on_disconnect: payload?.onDisconnect, + after_seconds: payload?.afterSeconds, + if_not_exists: payload?.ifNotExists, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability + }; + yield* this.streamWithRetry({ + endpoint: threadId == null ? `/runs/stream` : `/threads/${threadId}/runs/stream`, + method: "POST", + json, + signal: payload?.signal, + idleReconnect: payload?.streamIdleReconnect, + onInitialResponse: (response) => { + const runMetadata = getRunMetadataFromResponse(response); + if (runMetadata) payload?.onRunCreated?.(runMetadata); + } + }); + } + /** + * Create a run. + * + * @param threadId The ID of the thread. + * @param assistantId Assistant ID to use for this run. + * @param payload Payload for creating a run. + * @returns The created run. + */ + async create(threadId, assistantId, payload) { + const json = { + input: payload?.input, + command: payload?.command, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + stream_mode: payload?.streamMode, + stream_subgraphs: payload?.streamSubgraphs, + stream_resumable: payload?.streamResumable, + feedback_keys: payload?.feedbackKeys, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + webhook: payload?.webhook, + checkpoint: payload?.checkpoint, + checkpoint_id: payload?.checkpointId, + multitask_strategy: payload?.multitaskStrategy, + after_seconds: payload?.afterSeconds, + if_not_exists: payload?.ifNotExists, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability, + on_completion: payload?.onCompletion, + langsmith_tracer: payload?._langsmithTracer ? { + project_name: payload?._langsmithTracer?.projectName, + example_id: payload?._langsmithTracer?.exampleId + } : void 0 + }; + const endpoint = threadId === null ? "/runs" : `/threads/${threadId}/runs`; + const [run, response] = await this.fetch(endpoint, { + method: "POST", + json, + signal: payload?.signal, + withResponse: true + }); + const runMetadata = getRunMetadataFromResponse(response); + if (runMetadata) payload?.onRunCreated?.(runMetadata); + return run; + } + /** + * Create a batch of stateless background runs. + * + * @param payloads An array of payloads for creating runs. + * @returns An array of created runs. + */ + async createBatch(payloads, options) { + const filteredPayloads = payloads.map((payload) => ({ + ...payload, + assistant_id: payload.assistantId + })).map((payload) => { + return Object.fromEntries(Object.entries(payload).filter(([_, v]) => v !== void 0)); + }); + return this.fetch("/runs/batch", { + method: "POST", + json: filteredPayloads, + signal: options?.signal + }); + } + /** + * Create a run and wait for it to complete. + * + * @param threadId The ID of the thread. + * @param assistantId Assistant ID to use for this run. + * @param payload Payload for creating a run. + * @returns The last values chunk of the thread. + */ + async wait(threadId, assistantId, payload) { + const json = { + input: payload?.input, + command: payload?.command, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + checkpoint: payload?.checkpoint, + checkpoint_id: payload?.checkpointId, + webhook: payload?.webhook, + multitask_strategy: payload?.multitaskStrategy, + on_completion: payload?.onCompletion, + on_disconnect: payload?.onDisconnect, + after_seconds: payload?.afterSeconds, + if_not_exists: payload?.ifNotExists, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability, + langsmith_tracer: payload?._langsmithTracer ? { + project_name: payload?._langsmithTracer?.projectName, + example_id: payload?._langsmithTracer?.exampleId + } : void 0 + }; + const endpoint = threadId == null ? `/runs/wait` : `/threads/${threadId}/runs/wait`; + const [run, response] = await this.fetch(endpoint, { + method: "POST", + json, + timeoutMs: null, + signal: payload?.signal, + withResponse: true + }); + const runMetadata = getRunMetadataFromResponse(response); + if (runMetadata) payload?.onRunCreated?.(runMetadata); + if ((payload?.raiseError !== void 0 ? payload.raiseError : true) && "__error__" in run && typeof run.__error__ === "object" && run.__error__ && "error" in run.__error__ && "message" in run.__error__) throw new Error(`${run.__error__?.error}: ${run.__error__?.message}`); + return run; + } + /** + * List all runs for a thread. + * + * @param threadId The ID of the thread. + * @param options Filtering and pagination options. + * @returns List of runs. + */ + async list(threadId, options) { + return this.fetch(`/threads/${threadId}/runs`, { + params: { + limit: options?.limit ?? 10, + offset: options?.offset ?? 0, + status: options?.status ?? void 0, + select: options?.select ?? void 0 + }, + signal: options?.signal + }); + } + /** + * Get a run by ID. + * + * @param threadId The ID of the thread. + * @param runId The ID of the run. + * @returns The run. + */ + async get(threadId, runId, options) { + return this.fetch(`/threads/${threadId}/runs/${runId}`, { signal: options?.signal }); + } + /** + * Cancel a run. + * + * @param threadId The ID of the thread. + * @param runId The ID of the run. + * @param wait Whether to block when canceling + * @param action Action to take when cancelling the run. Possible values are `interrupt` or `rollback`. Default is `interrupt`. + * @returns + */ + async cancel(threadId, runId, wait = false, action = "interrupt", options = {}) { + return this.fetch(`/threads/${threadId}/runs/${runId}/cancel`, { + method: "POST", + params: { + wait: wait ? "1" : "0", + action + }, + signal: options?.signal + }); + } + /** + * Cancel one or more runs. + * + * @param options Options for cancelling runs. + * @returns + */ + async cancelMany(options) { + return this.fetch(`/runs/cancel`, { + method: "POST", + json: { + thread_id: options.threadId, + run_ids: options.runIds, + status: options.status + }, + params: { action: options.action }, + signal: options.signal + }); + } + /** + * Block until a run is done. + * + * @param threadId The ID of the thread. + * @param runId The ID of the run. + * @returns + */ + async join(threadId, runId, options) { + return this.fetch(`/threads/${threadId}/runs/${runId}/join`, { + timeoutMs: null, + params: { cancel_on_disconnect: options?.cancelOnDisconnect ? "1" : "0" }, + signal: options?.signal + }); + } + /** + * Stream output from a run in real-time, until the run is done. + * + * @param threadId The ID of the thread. + * @param runId The ID of the run. + * @param options Additional options for controlling the stream behavior. + * @returns An async generator yielding stream parts. + */ + async *joinStream(threadId, runId, options) { + const opts = typeof options === "object" && options != null && options instanceof AbortSignal ? { signal: options } : options; + yield* this.streamWithRetry({ + endpoint: threadId != null ? `/threads/${threadId}/runs/${runId}/stream` : `/runs/${runId}/stream`, + method: "GET", + signal: opts?.signal, + idleReconnect: opts?.streamIdleReconnect, + headers: opts?.lastEventId ? { "Last-Event-ID": opts.lastEventId } : void 0, + params: { + cancel_on_disconnect: opts?.cancelOnDisconnect ? "1" : "0", + stream_mode: opts?.streamMode + } + }); + } + /** + * Delete a run. + * + * @param threadId The ID of the thread. + * @param runId The ID of the run. + * @returns + */ + async delete(threadId, runId, options) { + return this.fetch(`/threads/${threadId}/runs/${runId}`, { + method: "DELETE", + signal: options?.signal + }); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/crons/index.js +var CronsClient = class extends BaseClient { + /** + * + * @param threadId The ID of the thread. + * @param assistantId Assistant ID to use for this cron job. + * @param payload Payload for creating a cron job. + * @returns The created background run. + */ + async createForThread(threadId, assistantId, payload) { + const json = { + schedule: payload?.schedule, + input: payload?.input, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + webhook: payload?.webhook, + multitask_strategy: payload?.multitaskStrategy, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability, + enabled: payload?.enabled, + timezone: payload?.timezone, + stream_mode: payload?.streamMode, + stream_subgraphs: payload?.streamSubgraphs, + stream_resumable: payload?.streamResumable, + end_time: payload?.endTime, + on_run_completed: payload?.onRunCompleted + }; + return this.fetch(`/threads/${threadId}/runs/crons`, { + method: "POST", + json, + signal: payload?.signal + }); + } + /** + * + * @param assistantId Assistant ID to use for this cron job. + * @param payload Payload for creating a cron job. + * @returns + */ + async create(assistantId, payload) { + const json = { + schedule: payload?.schedule, + input: payload?.input, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + webhook: payload?.webhook, + on_run_completed: payload?.onRunCompleted, + multitask_strategy: payload?.multitaskStrategy, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability, + enabled: payload?.enabled, + timezone: payload?.timezone, + stream_mode: payload?.streamMode, + stream_subgraphs: payload?.streamSubgraphs, + stream_resumable: payload?.streamResumable, + end_time: payload?.endTime + }; + return this.fetch(`/runs/crons`, { + method: "POST", + json, + signal: payload?.signal + }); + } + /** + * Update a cron job by ID. + * + * @param cronId The cron ID to update. + * @param payload Payload for updating a cron job. + * @returns The updated cron job. + * ``` + */ + async update(cronId, payload) { + const json = { + schedule: payload?.schedule, + timezone: payload?.timezone, + end_time: payload?.endTime, + input: payload?.input, + metadata: payload?.metadata, + config: payload?.config, + context: payload?.context, + webhook: payload?.webhook, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + on_run_completed: payload?.onRunCompleted, + enabled: payload?.enabled, + stream_mode: payload?.streamMode, + stream_subgraphs: payload?.streamSubgraphs, + stream_resumable: payload?.streamResumable, + durability: payload?.durability + }; + return this.fetch(`/runs/crons/${cronId}`, { + method: "PATCH", + json, + signal: payload?.signal + }); + } + /** + * Delete a cron job by ID. + * + * @param cronId Cron ID of Cron job to delete. + * @param options Optional parameters for the request. + */ + async delete(cronId, options) { + await this.fetch(`/runs/crons/${cronId}`, { + method: "DELETE", + signal: options?.signal + }); + } + /** + * + * @param query Query options. + * @param query.metadata Metadata to filter by. Exact match filter for each KV pair. + * Available in Agent Server version 0.9.0 and later. + * @returns List of crons. + */ + async search(query) { + return this.fetch("/runs/crons/search", { + method: "POST", + json: { + assistant_id: query?.assistantId ?? void 0, + thread_id: query?.threadId ?? void 0, + enabled: query?.enabled ?? void 0, + limit: query?.limit ?? 10, + offset: query?.offset ?? 0, + sort_by: query?.sortBy ?? void 0, + sort_order: query?.sortOrder ?? void 0, + select: query?.select ?? void 0, + metadata: query?.metadata ?? void 0 + }, + signal: query?.signal + }); + } + /** + * Count cron jobs matching filters. + * + * @param query.assistantId Assistant ID to filter by. + * @param query.threadId Thread ID to filter by. + * @param query.metadata Metadata to filter by. Exact match filter for each KV pair. + * Available in Agent Server version 0.9.0 and later. + * @returns Number of cron jobs matching the criteria. + */ + async count(query) { + return this.fetch(`/runs/crons/count`, { + method: "POST", + json: { + assistant_id: query?.assistantId ?? void 0, + thread_id: query?.threadId ?? void 0, + metadata: query?.metadata ?? void 0 + }, + signal: query?.signal + }); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/store/index.js +var StoreClient = class extends BaseClient { + /** + * Store or update an item. + * + * @param namespace A list of strings representing the namespace path. + * @param key The unique identifier for the item within the namespace. + * @param value A dictionary containing the item's data. + * @param options.index Controls search indexing - null (use defaults), false (disable), or list of field paths to index. + * @param options.ttl Optional time-to-live in minutes for the item, or null for no expiration. + * @returns Promise + */ + async putItem(namespace, key, value, options) { + namespace.forEach((label) => { + if (label.includes(".")) throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`); + }); + const payload = { + namespace, + key, + value, + index: options?.index, + ttl: options?.ttl + }; + return this.fetch("/store/items", { + method: "PUT", + json: payload, + signal: options?.signal + }); + } + /** + * Retrieve a single item. + * + * @param namespace A list of strings representing the namespace path. + * @param key The unique identifier for the item. + * @param options.refreshTtl Whether to refresh the TTL on this read operation. + * @returns Promise + */ + async getItem(namespace, key, options) { + namespace.forEach((label) => { + if (label.includes(".")) throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`); + }); + const params = { + namespace: namespace.join("."), + key + }; + if (options?.refreshTtl !== void 0) params.refresh_ttl = options.refreshTtl; + const response = await this.fetch("/store/items", { + params, + signal: options?.signal + }); + return response ? { + ...response, + createdAt: response.created_at, + updatedAt: response.updated_at + } : null; + } + /** + * Delete an item. + * + * @param namespace A list of strings representing the namespace path. + * @param key The unique identifier for the item. + * @returns Promise + */ + async deleteItem(namespace, key, options) { + namespace.forEach((label) => { + if (label.includes(".")) throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`); + }); + return this.fetch("/store/items", { + method: "DELETE", + json: { + namespace, + key + }, + signal: options?.signal + }); + } + /** + * Search for items within a namespace prefix. + * + * @param namespacePrefix List of strings representing the namespace prefix. + * @param options Search options including filter, pagination, and query. + * @returns Promise + */ + async searchItems(namespacePrefix, options) { + const payload = { + namespace_prefix: namespacePrefix, + filter: options?.filter, + limit: options?.limit ?? 10, + offset: options?.offset ?? 0, + query: options?.query, + refresh_ttl: options?.refreshTtl + }; + return { items: (await this.fetch("/store/items/search", { + method: "POST", + json: payload, + signal: options?.signal + })).items.map((item) => ({ + ...item, + createdAt: item.created_at, + updatedAt: item.updated_at + })) }; + } + /** + * List namespaces with optional match conditions. + * + * @param options Filtering and pagination options for namespaces. + * @returns Promise + */ + async listNamespaces(options) { + const payload = { + prefix: options?.prefix, + suffix: options?.suffix, + max_depth: options?.maxDepth, + limit: options?.limit ?? 100, + offset: options?.offset ?? 0 + }; + return this.fetch("/store/namespaces", { + method: "POST", + json: payload, + signal: options?.signal + }); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/ui-internal/index.js +var UiClient = class UiClient extends BaseClient { + static promiseCache = {}; + static getOrCached(key, fn) { + if (UiClient.promiseCache[key] != null) return UiClient.promiseCache[key]; + const promise = fn(); + UiClient.promiseCache[key] = promise; + return promise; + } + async getComponent(assistantId, agentName) { + return UiClient.getOrCached(`${this.apiUrl}-${assistantId}-${agentName}`, async () => { + let [url, init] = this.prepareFetchOptions(`/ui/${assistantId}`, { + headers: { + Accept: "text/html", + "Content-Type": "application/json" + }, + method: "POST", + json: { name: agentName } + }); + if (this.onRequest != null) init = await this.onRequest(url, init); + return (await this.asyncCaller.fetch(url.toString(), init)).text(); + }); + } +}; +//#endregion +//#region node_modules/@langchain/langgraph-sdk/dist/client/index.js +var Client = class { + /** + * The client for interacting with assistants. + */ + assistants; + /** + * The client for interacting with threads. + */ + threads; + /** + * The client for interacting with runs. + */ + runs; + /** + * The client for interacting with cron runs. + */ + crons; + /** + * The client for interacting with the KV store. + */ + store; + /** + * The client for interacting with the UI. + * @internal Used by LoadExternalComponent and the API might change in the future. + */ + "~ui"; + /** + * @internal Used to obtain a stable key representing the client. + */ + "~configHash"; + constructor(config) { + this["~configHash"] = JSON.stringify({ + apiUrl: config?.apiUrl, + apiKey: config?.apiKey, + timeoutMs: config?.timeoutMs, + defaultHeaders: config?.defaultHeaders, + streamProtocol: config?.streamProtocol, + maxConcurrency: config?.callerOptions?.maxConcurrency, + maxRetries: config?.callerOptions?.maxRetries, + callbacks: { + onFailedResponseHook: config?.callerOptions?.onFailedResponseHook != null, + onRequest: config?.onRequest != null, + fetch: config?.callerOptions?.fetch != null + } + }); + this.assistants = new AssistantsClient(config); + this.threads = new ThreadsClient(config); + this.runs = new RunsClient(config); + this.crons = new CronsClient(config); + this.store = new StoreClient(config); + this["~ui"] = new UiClient(config); + } +}; +Object.freeze([]); +//#endregion +export { Client as t }; diff --git a/.vercel/output/functions/__server.func/_libs/@langchain/mcp-adapters+[...].mjs b/.vercel/output/functions/__server.func/_libs/@langchain/mcp-adapters+[...].mjs new file mode 100644 index 0000000..13cca01 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/@langchain/mcp-adapters+[...].mjs @@ -0,0 +1,20117 @@ +import { a as __toCommonJS, i as __require, n as __esmMin, o as __toESM, r as __exportAll, t as __commonJSMin } from "../../_runtime.mjs"; +import { $t as string$1, Bt as array, En as NEVER, Gt as intersection, Ht as custom, It as _enum, Jt as number$1, Kt as literal, Mt as ZodBoolean, Nt as ZodNumber, Pt as ZodString, Qt as record, Rt as _null, Sn as prettifyError, Ut as discriminatedUnion, Vt as boolean$1, Xt as optional, Yt as object, Zt as preprocess, an as ZodError, cn as _coercedBoolean, ln as _coercedNumber, nn as unknown, on as datetime, qt as looseObject, rn as url, tn as union, un as _coercedString, xn as safeParse$1, zt as any } from "../@better-auth/core+[...].mjs"; +import { Ct as voidType, Ln as ToolMessage, St as unknownType, _t as promiseType, bt as tupleType, ct as booleanType, dt as functionType, gt as optionalType, ht as objectType, i as DynamicStructuredTool, lt as custom$1, mt as numberType, pt as literalType, st as arrayType, ut as enumType, vt as recordType, wt as ZodError$1, xt as unionType, yt as stringType } from "./anthropic+[...].mjs"; +import { g as Command, p as getCurrentTaskInput } from "./langgraph+[...].mjs"; +import { PassThrough } from "node:stream"; +import process$1 from "node:process"; +//#region node_modules/zod/v4/classic/compat.js +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +var ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom" +}; +/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ +var ZodFirstPartyTypeKind; +ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}); +//#endregion +//#region node_modules/zod/v4/classic/coerce.js +function string(params) { + return _coercedString(ZodString, params); +} +function number(params) { + return _coercedNumber(ZodNumber, params); +} +function boolean(params) { + return _coercedBoolean(ZodBoolean, params); +} +//#endregion +//#region node_modules/@langchain/mcp-adapters/dist/hooks.js +var toolCallRequestSchema = objectType({ + serverName: stringType(), + name: stringType(), + args: unknownType() +}); +var toolResultBeforeSchema = tupleType([custom$1(), arrayType(unionType([custom$1(), custom$1()]))]); +/** +* Tool result schema that users can return within the `afterToolCall` callback +*/ +var toolResultSchema = unionType([ + stringType(), + custom$1(), + toolResultBeforeSchema, + custom$1() +]); +var toolCallResultSchema = objectType({ + ...toolCallRequestSchema.shape, + result: toolResultBeforeSchema +}); +var modifiedToolCallResultSchema = objectType({ + ...toolCallRequestSchema.shape, + result: toolResultSchema +}); +var toolCallModificationSchema = objectType({ + headers: recordType(stringType()), + args: unknownType() +}).partial(); +var toolHooksSchema = objectType({ + beforeToolCall: functionType().args(toolCallRequestSchema, custom$1(), custom$1()).returns(unionType([ + promiseType(toolCallModificationSchema), + toolCallModificationSchema, + voidType(), + promiseType(voidType()) + ])).optional(), + afterToolCall: functionType().args(toolCallResultSchema, custom$1(), custom$1()).returns(unionType([ + promiseType(modifiedToolCallResultSchema.pick({ result: true })), + modifiedToolCallResultSchema.pick({ result: true }), + voidType(), + promiseType(voidType()) + ])).optional() +}); +//#endregion +//#region node_modules/@langchain/mcp-adapters/dist/types.js +var callToolResultContentTypes = [ + "audio", + "image", + "resource", + "resource_link", + "text" +]; +/** +* The severity of a log message. +* @see {@link https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/types.ts#L1067} +*/ +var LoggingLevelSchema$1 = enumType([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" +]); +/** +* A uniquely identifying ID for a request in JSON-RPC. +* @see {@link https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/types.ts#L71C1-L74C72} +*/ +var RequestIdSchema$1 = unionType([stringType(), numberType().int()]); +var outputHandlingSchema = unionType([unionType([literalType("content").describe("Put tool output into the ToolMessage.content array"), literalType("artifact").describe("Put tool output into the ToolMessage.artifact array")]), objectType(Object.fromEntries(callToolResultContentTypes.map((contentType) => [contentType, unionType([literalType("content").describe(`Put all ${contentType} tool output into the ToolMessage.content array`), literalType("artifact").describe(`Put all ${contentType} tool output into the ToolMessage.artifact array`)]).describe(`Where to place ${contentType} tool output in the LangChain ToolMessage`).optional()])))]).describe("Defines where to place each tool output type in the LangChain ToolMessage.\n\nItems in the `content` field will be used as input context for the LLM, while the artifact field is\nused for capturing tool output that won't be shown to the model, to be used in some later workflow\nstep.\n\nFor example, imagine that you have a SQL query tool that can return huge result sets. Rather than\nsending these large outputs directly to the model, perhaps you want the model to be able to inspect\nthe output in a code execution environment. In this case, you would set the output handling for the\n`resource` type to `artifact` (it's default value), and then upon initialization of your code\nexecution environment, you would look through your message history for `ToolMessage`s with the\n`artifact` field set to `resource`, and use the `content` field during initialization of the\nenvironment."); +/** +* Zod schema for validating OAuthClientProvider interface +* Since OAuthClientProvider has methods, we create a custom validator +*/ +var oAuthClientProviderSchema = custom$1((val) => { + if (!val || typeof val !== "object") return false; + const requiredMethods = [ + "redirectUrl", + "clientMetadata", + "clientInformation", + "tokens", + "saveTokens" + ]; + if (!("redirectUrl" in val)) return false; + if (!("clientMetadata" in val)) return false; + for (const method of requiredMethods) if (!(method in val)) return false; + return true; +}, { message: "Must be a valid OAuthClientProvider implementation with required properties: redirectUrl, clientMetadata, clientInformation, tokens, saveTokens" }); +var baseConfigSchema = objectType({ + outputHandling: outputHandlingSchema.optional(), + defaultToolTimeout: numberType().min(1).optional() +}); +/** +* Stdio transport restart configuration +*/ +var stdioRestartSchema = objectType({ + enabled: booleanType().describe("Whether to automatically restart the process if it exits").optional(), + maxAttempts: numberType().describe("The maximum number of restart attempts").optional(), + delayMs: numberType().describe("The delay in milliseconds between restart attempts").optional() +}).describe("Configuration for stdio transport restart"); +/** +* Stdio transport connection +*/ +var stdioConnectionSchema = objectType({ + transport: literalType("stdio").optional(), + type: literalType("stdio").optional(), + command: stringType().describe("The executable to run the server"), + args: arrayType(stringType()).describe("Command line arguments to pass to the executable"), + env: recordType(stringType()).describe("The environment to use when spawning the process").optional(), + encoding: stringType().describe("The encoding to use when reading from the process").optional(), + stderr: unionType([ + literalType("overlapped"), + literalType("pipe"), + literalType("ignore"), + literalType("inherit") + ]).describe("How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`").optional().default("inherit"), + cwd: stringType().describe("The working directory to use when spawning the process").optional(), + restart: stdioRestartSchema.optional() +}).and(baseConfigSchema).describe("Configuration for stdio transport connection"); +/** +* Streamable HTTP transport reconnection configuration +*/ +var streamableHttpReconnectSchema = objectType({ + enabled: booleanType().describe("Whether to automatically reconnect if the connection is lost").optional(), + maxAttempts: numberType().describe("The maximum number of reconnection attempts").optional(), + delayMs: numberType().describe("The delay in milliseconds between reconnection attempts").optional() +}).describe("Configuration for streamable HTTP transport reconnection"); +/** +* Create combined schema for all transport connection types +*/ +var connectionSchema = unionType([stdioConnectionSchema, objectType({ + transport: unionType([literalType("http"), literalType("sse")]).optional(), + type: unionType([literalType("http"), literalType("sse")]).optional(), + url: stringType().url(), + headers: recordType(stringType()).optional(), + authProvider: oAuthClientProviderSchema.optional(), + reconnect: streamableHttpReconnectSchema.optional(), + automaticSSEFallback: booleanType().optional().default(true) +}).and(baseConfigSchema).describe("Configuration for streamable HTTP transport connection")]).describe("Configuration for a single MCP server"); +var eventContextSchema = unionType([objectType({ + type: literalType("tool"), + name: stringType(), + args: unknownType(), + server: stringType() +}), objectType({ type: literalType("unknown") })]); +var serverMessageSourceSchema = objectType({ + server: stringType(), + options: connectionSchema +}); +var notifications = objectType({ + onMessage: functionType().args(objectType({ + level: LoggingLevelSchema$1, + logger: optionalType(stringType()), + data: unknownType() + }), serverMessageSourceSchema).returns(unionType([voidType(), promiseType(voidType())])).optional(), + onProgress: functionType().args(objectType({ + progress: numberType(), + total: optionalType(numberType()), + message: optionalType(stringType()) + }), eventContextSchema).returns(unionType([voidType(), promiseType(voidType())])).optional(), + onCancelled: functionType().args(objectType({ + requestId: RequestIdSchema$1, + reason: stringType().optional() + }), serverMessageSourceSchema).returns(unionType([voidType(), promiseType(voidType())])).optional(), + onInitialized: functionType().args(serverMessageSourceSchema).returns(unionType([voidType(), promiseType(voidType())])).optional(), + onPromptsListChanged: functionType().args(serverMessageSourceSchema).returns(unionType([voidType(), promiseType(voidType())])).optional(), + onResourcesListChanged: functionType().args(serverMessageSourceSchema).returns(unionType([voidType(), promiseType(voidType())])).optional(), + onResourcesUpdated: functionType().args(objectType({ uri: stringType() }), serverMessageSourceSchema).returns(unionType([voidType(), promiseType(voidType())])).optional(), + onRootsListChanged: functionType().args(serverMessageSourceSchema).returns(unionType([voidType(), promiseType(voidType())])).optional(), + onToolsListChanged: functionType().args(serverMessageSourceSchema).returns(unionType([voidType(), promiseType(voidType())])).optional() +}); +/** +* {@link MultiServerMCPClient} configuration +*/ +var clientConfigSchema = objectType({ + mcpServers: recordType(connectionSchema).describe("A map of server names to their configuration"), + throwOnLoadError: booleanType().describe("Whether to throw an error if a tool fails to load").optional().default(true), + prefixToolNameWithServerName: booleanType().describe("Whether to prefix tool names with the server name").optional().default(false), + additionalToolNamePrefix: stringType().describe("An additional prefix to add to the tool name").optional().default(""), + useStandardContentBlocks: booleanType().describe("If true, the tool will use LangChain's standard multimodal content blocks for tools that output\nimage or audio content. When true, embedded resources will be converted to `StandardFileBlock`\nobjects. When `false`, all artifacts are left in their MCP format, but embedded resources will\nbe converted to `StandardFileBlock` objects if `outputHandling` causes embedded resources to be\ntreated as content, as otherwise ChatModel providers will not be able to interpret them.").optional().default(false), + onConnectionError: unionType([enumType(["throw", "ignore"]), functionType().args(objectType({ + serverName: stringType(), + error: unknownType() + })).returns(voidType())]).describe("Behavior when a server fails to connect: 'throw' to error immediately, 'ignore' to skip failed servers, or a function for custom error handling").optional().default("throw") +}).and(baseConfigSchema).and(toolHooksSchema).and(notifications).describe("Configuration for the MCP client"); +/** +* Helper function that expands a string literal OutputHandling to an object with all content types. +* Used when applying server-level overrides to the top-level config. +* +* @internal +*/ +function _resolveDetailedOutputHandling(outputHandling, applyDefaults = false) { + if (outputHandling == null) return {}; + if (typeof outputHandling === "string") return Object.fromEntries(callToolResultContentTypes.map((contentType) => [contentType, outputHandling])); + const resolved = {}; + for (const contentType of callToolResultContentTypes) if (outputHandling[contentType] || applyDefaults) resolved[contentType] = outputHandling[contentType] ?? (contentType === "resource" ? "artifact" : "content"); + return resolved; +} +/** +* Given a base {@link OutputHandling}, apply any overrides from the override {@link OutputHandling}. +* +* @internal +*/ +function _resolveAndApplyOverrideHandlingOverrides(base, override) { + const expandedBase = _resolveDetailedOutputHandling(base); + const expandedOverride = _resolveDetailedOutputHandling(override); + return { + ...expandedBase, + ...expandedOverride + }; +} +//#endregion +//#region node_modules/ms/index.js +var require_ms = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** + * Helpers. + */ + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) return parse(val); + else if (type === "number" && isFinite(val)) 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)); + }; + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + function parse(str) { + str = String(str); + if (str.length > 100) return; + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + switch ((match[2] || "ms").toLowerCase()) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": return n * y; + case "weeks": + case "week": + case "w": return n * w; + case "days": + case "day": + case "d": return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": return n; + default: return; + } + } + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) return Math.round(ms / d) + "d"; + if (msAbs >= h) return Math.round(ms / h) + "h"; + if (msAbs >= m) return Math.round(ms / m) + "m"; + if (msAbs >= s) return Math.round(ms / s) + "s"; + return ms + "ms"; + } + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) return plural(ms, msAbs, d, "day"); + if (msAbs >= h) return plural(ms, msAbs, h, "hour"); + if (msAbs >= m) return plural(ms, msAbs, m, "minute"); + if (msAbs >= s) return plural(ms, msAbs, s, "second"); + return ms + " ms"; + } + /** + * Pluralization helper. + */ + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } +})); +//#endregion +//#region node_modules/debug/src/common.js +var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + /** + * The currently active debug mode names, and names to skip. + */ + createDebug.names = []; + createDebug.skips = []; + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; + } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug(...args) { + if (!debug.enabled) return; + const self = debug; + const curr = Number(/* @__PURE__ */ new Date()); + self.diff = curr - (prevTime || curr); + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") args.unshift("%O"); + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") return "%"; + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index]; + match = formatter.call(self, val); + args.splice(index, 1); + index--; + } + return match; + }); + createDebug.formatArgs.call(self, args); + (self.log || createDebug.log).apply(self, args); + } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; + Object.defineProperty(debug, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) return enableOverride; + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") createDebug.init(debug); + return debug; + } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) if (ns[0] === "-") createDebug.skips.push(ns.slice(1)); + else createDebug.names.push(ns); + } + /** + * Checks if the given string matches a namespace template, honoring + * asterisks as wildcards. + * + * @param {String} search + * @param {String} template + * @return {Boolean} + */ + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else return false; + while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++; + return templateIndex === template.length; + } + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [...createDebug.names, ...createDebug.skips.map((namespace) => "-" + namespace)].join(","); + createDebug.enable(""); + return namespaces; + } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + for (const skip of createDebug.skips) if (matchesTemplate(name, skip)) return false; + for (const ns of createDebug.names) if (matchesTemplate(name, ns)) return true; + return false; + } + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; + } + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + module.exports = setup; +})); +//#endregion +//#region node_modules/debug/src/browser.js +var require_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** + * This is the web browser implementation of `debug()`. + */ + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + /** + * Colors. + */ + exports.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + /** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) return true; + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) return false; + let m; + 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 && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + /** + * Colorize log arguments if enabled. + * + * @api public + */ + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); + if (!this.useColors) return; + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") return; + index++; + if (match === "%c") lastC = index; + }); + args.splice(lastC, 0, c); + } + /** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ + exports.log = console.debug || console.log || (() => {}); + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + try { + if (namespaces) exports.storage.setItem("debug", namespaces); + else exports.storage.removeItem("debug"); + } catch (error) {} + } + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + let r; + try { + r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); + } catch (error) {} + if (!r && typeof process !== "undefined" && "env" in process) r = process.env.DEBUG; + return r; + } + /** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + function localstorage() { + try { + return localStorage; + } catch (error) {} + } + module.exports = require_common()(exports); + var { formatters } = module.exports; + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error) { + return "[UnexpectedJSONParseError]: " + error.message; + } + }; +})); +//#endregion +//#region node_modules/has-flag/index.js +var require_has_flag = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; +})); +//#endregion +//#region node_modules/supports-color/index.js +var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var os = __require("os"); + var tty$1 = __require("tty"); + var hasFlag = require_has_flag(); + var { env } = process; + var forceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) forceColor = 0; + else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) forceColor = 1; + if ("FORCE_COLOR" in env) if (env.FORCE_COLOR === "true") forceColor = 1; + else if (env.FORCE_COLOR === "false") forceColor = 0; + else forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + function translateLevel(level) { + if (level === 0) return false; + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) return 0; + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3; + if (hasFlag("color=256")) return 2; + if (haveStream && !streamIsTTY && forceColor === void 0) return 0; + const min = forceColor || 0; + if (env.TERM === "dumb") return min; + if (process.platform === "win32") { + const osRelease = os.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2; + return 1; + } + if ("CI" in env) { + if ([ + "TRAVIS", + "CIRCLECI", + "APPVEYOR", + "GITLAB_CI", + "GITHUB_ACTIONS", + "BUILDKITE" + ].some((sign) => sign in env) || env.CI_NAME === "codeship") return 1; + return min; + } + if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + if (env.COLORTERM === "truecolor") return 3; + if ("TERM_PROGRAM" in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": return version >= 3 ? 3 : 2; + case "Apple_Terminal": return 2; + } + } + if (/-256(color)?$/i.test(env.TERM)) return 2; + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1; + if ("COLORTERM" in env) return 1; + return min; + } + function getSupportLevel(stream) { + return translateLevel(supportsColor(stream, stream && stream.isTTY)); + } + module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty$1.isatty(1))), + stderr: translateLevel(supportsColor(true, tty$1.isatty(2))) + }; +})); +//#endregion +//#region node_modules/debug/src/node.js +var require_node = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** + * Module dependencies. + */ + var tty = __require("tty"); + var util = __require("util"); + /** + * This is the Node.js implementation of `debug()`. + */ + exports.init = init; + exports.log = log; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + /** + * Colors. + */ + exports.colors = [ + 6, + 2, + 3, + 4, + 5, + 1 + ]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } catch (error) {} + /** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + exports.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === "null") val = null; + else val = Number(val); + obj[prop] = val; + return obj; + }, {}); + /** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + function useColors() { + return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + /** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + function formatArgs(args) { + const { namespace: name, useColors } = this; + if (useColors) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); + } else args[0] = getDate() + name + " " + args[0]; + } + function getDate() { + if (exports.inspectOpts.hideDate) return ""; + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + /** + * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. + */ + function log(...args) { + return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + "\n"); + } + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + if (namespaces) process.env.DEBUG = namespaces; + else delete process.env.DEBUG; + } + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + return process.env.DEBUG; + } + /** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + function init(debug) { + debug.inspectOpts = {}; + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } + module.exports = require_common()(exports); + var { formatters } = module.exports; + /** + * Map %o to `util.inspect()`, all on a single line. + */ + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + }; + /** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; +})); +//#endregion +//#region node_modules/@langchain/mcp-adapters/dist/logging.js +var import_src = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => { + /** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) module.exports = require_browser(); + else module.exports = require_node(); +})))(), 1); +var packageName = "@langchain/mcp-adapters"; +var debugLog$3 = {}; +function getDebugLog(instanceName = "client") { + const key = `${packageName}:${instanceName}`; + if (!debugLog$3[key]) debugLog$3[key] = (0, import_src.default)(key); + return debugLog$3[key]; +} +//#endregion +//#region node_modules/@langchain/mcp-adapters/dist/tools.js +var debugLog$2 = getDebugLog("tools"); +/** +* Dereferences $ref pointers in a JSON Schema by inlining the definitions from $defs. +* This is necessary because some JSON Schema validators (like @cfworker/json-schema) +* don't automatically resolve $ref references to $defs. +* +* @param schema - The JSON Schema to dereference +* @returns A new schema with all $ref pointers resolved +*/ +function dereferenceJsonSchema(schema) { + const definitions = schema.$defs ?? schema.definitions ?? {}; + /** + * Recursively resolve $ref pointers in the schema. + * Tracks visited refs to prevent infinite recursion with circular references. + */ + function resolveRefs(obj, visitedRefs = /* @__PURE__ */ new Set()) { + if (typeof obj !== "object" || obj === null) return obj; + if (obj.$ref && typeof obj.$ref === "string") { + const refPath = obj.$ref; + const defsMatch = refPath.match(/^#\/\$defs\/(.+)$/); + const definitionsMatch = refPath.match(/^#\/definitions\/(.+)$/); + const match = defsMatch || definitionsMatch; + if (match) { + const defName = match[1]; + const definition = definitions[defName]; + if (definition) { + if (visitedRefs.has(refPath)) { + debugLog$2(`WARNING: Circular reference detected for ${refPath}, using empty object`); + return { type: "object" }; + } + const newVisitedRefs = new Set(visitedRefs); + newVisitedRefs.add(refPath); + const { $ref: _, ...restOfObj } = obj; + return { + ...resolveRefs(definition, newVisitedRefs), + ...restOfObj + }; + } else debugLog$2(`WARNING: Could not resolve $ref: ${refPath}`); + } + return obj; + } + const result = {}; + for (const [key, value] of Object.entries(obj)) { + if (key === "$defs" || key === "definitions") continue; + if (Array.isArray(value)) result[key] = value.map((item) => typeof item === "object" && item !== null ? resolveRefs(item, visitedRefs) : item); + else if (typeof value === "object" && value !== null) result[key] = resolveRefs(value, visitedRefs); + else result[key] = value; + } + return result; + } + return resolveRefs(schema); +} +/** +* Deep merges two JSON Schema objects. +* Arrays are concatenated (with special handling for enum), objects are recursively merged, +* primitives are overwritten. +* +* @param target - The target schema to merge into +* @param source - The source schema to merge from +* @returns A new merged schema +*/ +function deepMergeSchemas(target, source) { + const result = { ...target }; + for (const [key, sourceValue] of Object.entries(source)) { + const targetValue = result[key]; + if (key === "required" && Array.isArray(targetValue)) result[key] = [.../* @__PURE__ */ new Set([...targetValue, ...sourceValue])]; + else if (key === "const") { + const existingConst = result.const; + const existingEnum = result.enum; + const values = /* @__PURE__ */ new Set(); + if (existingEnum) for (const v of existingEnum) values.add(v); + if (existingConst !== void 0) values.add(existingConst); + values.add(sourceValue); + delete result.const; + result.enum = [...values]; + } else if (key === "enum" && Array.isArray(sourceValue)) { + const values = /* @__PURE__ */ new Set(); + if (Array.isArray(targetValue)) for (const v of targetValue) values.add(v); + if (result.const !== void 0) { + values.add(result.const); + delete result.const; + } + for (const v of sourceValue) values.add(v); + result[key] = [...values]; + } else if (key === "properties" && typeof targetValue === "object" && targetValue !== null) { + const mergedProps = { ...targetValue }; + for (const [propKey, propValue] of Object.entries(sourceValue)) if (mergedProps[propKey] && typeof mergedProps[propKey] === "object" && typeof propValue === "object") mergedProps[propKey] = deepMergeSchemas(mergedProps[propKey], propValue); + else mergedProps[propKey] = propValue; + result[key] = mergedProps; + } else if (Array.isArray(sourceValue) && Array.isArray(targetValue)) result[key] = [...targetValue, ...sourceValue]; + else if (typeof sourceValue === "object" && sourceValue !== null && !Array.isArray(sourceValue) && typeof targetValue === "object" && targetValue !== null && !Array.isArray(targetValue)) result[key] = deepMergeSchemas(targetValue, sourceValue); + else result[key] = sourceValue; + } + return result; +} +/** +* Extracts and merges properties from if/then/else conditional schemas. +* This is used when processing allOf items that contain conditionals. +* +* @param schema - A schema that may contain if/then/else +* @returns Properties extracted from both then and else branches +*/ +function extractPropertiesFromConditional(schema) { + let result = {}; + if (schema.then && typeof schema.then === "object") { + const thenSchema = schema.then; + if (thenSchema.properties) result = deepMergeSchemas(result, { properties: thenSchema.properties }); + if (thenSchema.required) result.required = [.../* @__PURE__ */ new Set([...result.required || [], ...thenSchema.required])]; + } + if (schema.else && typeof schema.else === "object") { + const elseSchema = schema.else; + if (elseSchema.properties) result = deepMergeSchemas(result, { properties: elseSchema.properties }); + if (elseSchema.required) result.required = [.../* @__PURE__ */ new Set([...result.required || [], ...elseSchema.required])]; + } + return result; +} +/** +* Simplifies a JSON Schema for LLM compatibility by removing patterns that +* OpenAI and other LLM providers don't support at the top level: +* - allOf: merged into the main schema +* - anyOf/oneOf: flattened to the first object variant or merged if all are objects +* - if/then/else: conditional schemas are removed, but properties are extracted +* - not: negation constraints are removed +* - $schema: meta schema reference is removed +* - unevaluatedProperties: not supported by OpenAI +* +* This transformation is applied recursively to nested schemas as well. +* +* @param schema - The JSON Schema to simplify +* @returns A new simplified schema compatible with LLM tool calling APIs +*/ +function simplifyJsonSchemaForLLM(schema) { + if (typeof schema !== "object" || schema === null) return schema; + const { allOf, anyOf, oneOf, not: _not, if: schemaIf, then: schemaThen, else: schemaElse, $schema: _$schema, unevaluatedProperties: _unevaluatedProperties, ...baseSchema } = schema; + let result = { ...baseSchema }; + if (schemaIf || schemaThen || schemaElse) { + const conditionalProps = extractPropertiesFromConditional({ + if: schemaIf, + then: schemaThen, + else: schemaElse + }); + result = deepMergeSchemas(result, conditionalProps); + debugLog$2(`INFO: Extracted properties from if/then/else conditional`); + } + if (Array.isArray(allOf)) { + for (const subSchema of allOf) { + if (subSchema.if || subSchema.then || subSchema.else) { + const conditionalProps = extractPropertiesFromConditional(subSchema); + result = deepMergeSchemas(result, conditionalProps); + } + const simplified = simplifyJsonSchemaForLLM(subSchema); + result = deepMergeSchemas(result, simplified); + } + debugLog$2(`INFO: Flattened allOf with ${allOf.length} schemas into base schema`); + } + const unionSchemas = anyOf || oneOf; + if (Array.isArray(unionSchemas) && unionSchemas.length > 0) { + const allAreObjects = unionSchemas.every((s) => typeof s === "object" && s !== null && (s.type === "object" || s.properties)); + const mergedProperties = {}; + const requiredSets = []; + const schemasToMerge = allAreObjects ? unionSchemas : unionSchemas.filter((s) => typeof s === "object" && s !== null && (s.type === "object" || s.properties)); + for (const subSchema of schemasToMerge) { + const simplified = simplifyJsonSchemaForLLM(subSchema); + if (simplified.properties) Object.assign(mergedProperties, simplified.properties); + if (simplified.required && Array.isArray(simplified.required)) requiredSets.push(new Set(simplified.required)); + if (simplified.type && !result.type) result.type = simplified.type; + } + if (Object.keys(mergedProperties).length > 0) result.properties = { + ...result.properties, + ...mergedProperties + }; + if (requiredSets.length > 0) { + const commonRequired = requiredSets.reduce((acc, set) => { + return new Set([...acc].filter((x) => set.has(x))); + }); + if (commonRequired.size > 0) result.required = [.../* @__PURE__ */ new Set([...result.required || [], ...commonRequired])]; + } + debugLog$2(`INFO: Merged ${schemasToMerge.length} object schemas from ${anyOf ? "anyOf" : "oneOf"}`); + } + if (result.properties && !result.type) result.type = "object"; + if (result.properties) { + const simplifiedProperties = {}; + for (const [propName, propSchema] of Object.entries(result.properties)) if (typeof propSchema === "object" && propSchema !== null) simplifiedProperties[propName] = simplifyJsonSchemaForLLM(propSchema); + else simplifiedProperties[propName] = propSchema; + result.properties = simplifiedProperties; + } + if (result.items) { + if (Array.isArray(result.items)) result.items = result.items.map((item) => typeof item === "object" && item !== null ? simplifyJsonSchemaForLLM(item) : item); + else if (typeof result.items === "object") result.items = simplifyJsonSchemaForLLM(result.items); + } + if (typeof result.additionalProperties === "object" && result.additionalProperties !== null) result.additionalProperties = simplifyJsonSchemaForLLM(result.additionalProperties); + return result; +} +/** +* Custom error class for tool exceptions +*/ +var ToolException = class extends Error { + constructor(message, cause) { + super(message); + this.name = "ToolException"; + /** + * don't display the large ZodError stack trace + */ + if (cause && (cause instanceof ZodError || cause instanceof ZodError$1)) { + const minifiedZodError = new Error(prettifyError(cause)); + const stackByLine = cause.stack?.split("\n") || []; + minifiedZodError.stack = cause.stack?.split("\n").slice(stackByLine.findIndex((l) => l.includes(" at"))).join("\n"); + this.cause = minifiedZodError; + } else if (cause) this.cause = cause; + } +}; +function isToolException(error) { + return typeof error === "object" && error !== null && "name" in error && error.name === "ToolException"; +} +function isResourceReference(resource) { + return typeof resource === "object" && resource !== null && "uri" in resource && typeof resource.uri === "string" && (!("blob" in resource) || resource.blob == null) && (!("text" in resource) || resource.text == null); +} +async function* _embeddedResourceToStandardFileBlocks(resource, client) { + if (isResourceReference(resource)) { + const response = await client.readResource({ uri: resource.uri }); + for (const content of response.contents) yield* _embeddedResourceToStandardFileBlocks(content, client); + return; + } + if ("blob" in resource && resource.blob != null) yield { + type: "file", + source_type: "base64", + data: resource.blob, + mime_type: resource.mimeType, + ...resource.uri != null ? { metadata: { uri: resource.uri } } : {} + }; + if ("text" in resource && resource.text != null) yield { + type: "file", + source_type: "text", + mime_type: resource.mimeType, + text: resource.text, + ...resource.uri != null ? { metadata: { uri: resource.uri } } : {} + }; +} +async function _toolOutputToContentBlocks(content, useStandardContentBlocks, client, toolName, serverName) { + const blocks = []; + switch (content.type) { + case "text": return [{ + type: "text", + ...useStandardContentBlocks ? { source_type: "text" } : {}, + text: content.text + }]; + case "image": + if (useStandardContentBlocks) return [{ + type: "image", + source_type: "base64", + data: content.data, + mime_type: content.mimeType + }]; + return [{ + type: "image_url", + image_url: { url: `data:${content.mimeType};base64,${content.data}` } + }]; + case "audio": return [{ + type: "audio", + source_type: "base64", + data: content.data, + mime_type: content.mimeType + }]; + case "resource": + for await (const block of _embeddedResourceToStandardFileBlocks(content.resource, client)) blocks.push(block); + return blocks; + case "resource_link": return [{ + type: "file", + source_type: "url", + url: content.uri, + mime_type: content.mimeType + }]; + default: throw new ToolException(`MCP tool '${toolName}' on server '${serverName}' returned a content block with unexpected type "${content.type}." Expected one of ${callToolResultContentTypes.map((t) => `"${t}"`).join(", ")}.`); + } +} +async function _embeddedResourceToArtifact(resource, useStandardContentBlocks, client, toolName, serverName) { + if (useStandardContentBlocks) return _toolOutputToContentBlocks(resource, useStandardContentBlocks, client, toolName, serverName); + if ((!("blob" in resource) || resource.blob == null) && (!("text" in resource) || resource.text == null) && "uri" in resource && typeof resource.uri === "string") return (await client.readResource({ uri: resource.uri })).contents.map((content) => ({ + type: "resource", + resource: { ...content } + })); + return [resource]; +} +function _getOutputTypeForContentType(contentType, outputHandling) { + if (outputHandling === "content" || outputHandling === "artifact") return outputHandling; + return _resolveDetailedOutputHandling(outputHandling)[contentType] ?? (contentType === "resource" ? "artifact" : "content"); +} +/** +* Process the result from calling an MCP tool. +* Extracts text content and non-text content for better agent compatibility. +* +* @internal +* +* @param args - The arguments to pass to the tool +* @returns A tuple of [textContent, nonTextContent] +*/ +async function _convertCallToolResult({ serverName, toolName, result, client, useStandardContentBlocks, outputHandling }) { + if (!result) throw new ToolException(`MCP tool '${toolName}' on server '${serverName}' returned an invalid result - tool call response was undefined`); + if (!Array.isArray(result.content)) throw new ToolException(`MCP tool '${toolName}' on server '${serverName}' returned an invalid result - expected an array of content, but was ${typeof result.content}`); + if (result.isError) throw new ToolException(`MCP tool '${toolName}' on server '${serverName}' returned an error: ${result.content.map((content) => content.type === "text" ? content.text : "").join("\n")}`); + const convertedContent = (await Promise.all(result.content.filter((content) => _getOutputTypeForContentType(content.type, outputHandling) === "content").map((content) => _toolOutputToContentBlocks(content, useStandardContentBlocks, client, toolName, serverName)))).flat(); + const artifacts = (await Promise.all(result.content.filter((content) => _getOutputTypeForContentType(content.type, outputHandling) === "artifact").map((content) => { + return _embeddedResourceToArtifact(content, useStandardContentBlocks, client, toolName, serverName); + }))).flat(); + const structuredContent = result.structuredContent; + const meta = result._meta; + const enhancedArtifacts = [...artifacts]; + if (structuredContent) enhancedArtifacts.push({ + type: "mcp_structured_content", + data: structuredContent + }); + if (meta) enhancedArtifacts.push({ + type: "mcp_meta", + data: meta + }); + if (convertedContent.length === 1 && convertedContent[0].type === "text") { + const textBlock = convertedContent[0]; + const textContent = textBlock.text; + if (structuredContent || meta) return [{ + ...textBlock, + ...structuredContent ? { structuredContent } : {}, + ...meta ? { meta } : {} + }, enhancedArtifacts]; + return [textContent, enhancedArtifacts]; + } + return [convertedContent, enhancedArtifacts]; +} +/** +* Call an MCP tool. +* +* Use this with `.bind` to capture the fist three arguments, then pass to the constructor of DynamicStructuredTool. +* +* @internal +* @param args - The arguments to pass to the tool +* @returns A tuple of [textContent, nonTextContent] +*/ +async function _callTool({ serverName, toolName, client, args, config, useStandardContentBlocks, outputHandling, onProgress, beforeToolCall, afterToolCall }) { + try { + debugLog$2(`INFO: Calling tool ${toolName}(${JSON.stringify(args)})`); + const numericTimeout = config?.metadata?.timeoutMs ?? config?.timeout; + const requestOptions = { + ...numericTimeout ? { timeout: numericTimeout } : {}, + ...config?.signal ? { signal: config.signal } : {}, + ...onProgress ? { onprogress: (progress) => { + onProgress?.(progress, { + type: "tool", + name: toolName, + args, + server: serverName + }); + } } : {} + }; + let state = {}; + try { + state = getCurrentTaskInput(config); + } catch (error) { + debugLog$2(`State can't be derrived as LangGraph is not used: ${String(error)}`); + } + const beforeToolCallInterception = await beforeToolCall?.({ + name: toolName, + args, + serverName + }, state, config ?? {}); + const finalArgs = Object.assign(args, beforeToolCallInterception?.args || {}); + const headers = beforeToolCallInterception?.headers || {}; + const hasHeaderChanges = Object.entries(headers).length > 0; + if (hasHeaderChanges && typeof client.fork !== "function") throw new ToolException(`MCP client for server "${serverName}" does not support header changes`); + const finalClient = hasHeaderChanges && typeof client.fork === "function" ? await client.fork(headers) : client; + const callToolArgs = [{ + name: toolName, + arguments: finalArgs + }]; + if (Object.keys(requestOptions).length > 0) { + callToolArgs.push(void 0); + callToolArgs.push(requestOptions); + } + const [content, artifacts] = await _convertCallToolResult({ + serverName, + toolName, + result: await finalClient.callTool(...callToolArgs), + client: finalClient, + useStandardContentBlocks, + outputHandling + }); + const normalizedContent = typeof content === "string" ? content : Array.isArray(content) ? content : [content]; + const normalizedArtifacts = artifacts.filter((artifact) => artifact.type === "resource" || artifact.type !== "mcp_structured_content" && artifact.type !== "mcp_meta" && typeof artifact === "object" && artifact !== null && "source_type" in artifact); + const interceptedResult = await afterToolCall?.({ + name: toolName, + args: finalArgs, + result: [normalizedContent, normalizedArtifacts], + serverName + }, state, config ?? {}); + if (!interceptedResult) return [content, artifacts]; + if (typeof interceptedResult.result === "string") return [interceptedResult.result, []]; + if (Array.isArray(interceptedResult.result)) return interceptedResult.result; + if (ToolMessage.isInstance(interceptedResult.result)) return [interceptedResult.result.contentBlocks, []]; + if (interceptedResult?.result instanceof Command) return interceptedResult.result; + throw new Error(`Unexpected result value type from afterToolCall: expected either a Command, a ToolMessage or a tuple of ContentBlock and Artifact, but got ${interceptedResult.result}`); + } catch (error) { + if (error instanceof ZodError || error instanceof ZodError$1) throw new ToolException(prettifyError(error), error); + debugLog$2(`Error calling tool ${toolName}: ${String(error)}`); + if (isToolException(error)) throw error; + throw new ToolException(`Error calling tool ${toolName}: ${String(error)}`); + } +} +var defaultLoadMcpToolsOptions = { + throwOnLoadError: true, + prefixToolNameWithServerName: false, + additionalToolNamePrefix: "", + useStandardContentBlocks: false +}; +/** +* Load all tools from an MCP client. +* +* @param serverName - The name of the server to load tools from +* @param client - The MCP client +* @returns A list of LangChain tools +*/ +async function loadMcpTools(serverName, client, options) { + const { throwOnLoadError, prefixToolNameWithServerName, additionalToolNamePrefix, useStandardContentBlocks, outputHandling, defaultToolTimeout } = { + ...defaultLoadMcpToolsOptions, + ...options ?? {} + }; + const mcpTools = []; + let toolsResponse; + do { + toolsResponse = await client.listTools({ ...toolsResponse?.nextCursor ? { cursor: toolsResponse.nextCursor } : {} }); + mcpTools.push(...toolsResponse.tools || []); + } while (toolsResponse.nextCursor); + debugLog$2(`INFO: Found ${mcpTools.length} MCP tools`); + const toolNamePrefix = `${additionalToolNamePrefix ? `${additionalToolNamePrefix}__` : ""}${prefixToolNameWithServerName ? `${serverName}__` : ""}`; + return (await Promise.all(mcpTools.filter((tool) => !!tool.name).map(async (tool) => { + try { + if (!tool.inputSchema.properties) tool.inputSchema.properties = {}; + const simplifiedSchema = simplifyJsonSchemaForLLM(dereferenceJsonSchema(tool.inputSchema)); + const dst = new DynamicStructuredTool({ + name: `${toolNamePrefix}${tool.name}`, + description: tool.description || "", + schema: simplifiedSchema, + responseFormat: "content_and_artifact", + metadata: { annotations: tool.annotations }, + defaultConfig: defaultToolTimeout ? { timeout: defaultToolTimeout } : void 0, + func: async (args, _runManager, config) => { + return _callTool({ + serverName, + toolName: tool.name, + client, + args, + config, + useStandardContentBlocks, + outputHandling, + onProgress: options?.onProgress, + beforeToolCall: options?.beforeToolCall, + afterToolCall: options?.afterToolCall + }); + } + }); + debugLog$2(`INFO: Successfully loaded tool: ${dst.name}`); + return dst; + } catch (error) { + debugLog$2(`ERROR: Failed to load tool "${tool.name}":`, error); + if (throwOnLoadError) throw error; + return null; + } + }))).filter(Boolean); +} +//#endregion +//#region node_modules/@langchain/mcp-adapters/dist/package.js +var package_default = { + name: "@langchain/mcp-adapters", + version: "1.1.3", + description: "LangChain.js adapters for Model Context Protocol (MCP)", + author: "LangChain", + license: "MIT", + type: "module", + packageManager: "pnpm@10.14.0", + repository: { + "type": "git", + "url": "git@github.com:langchain-ai/langchainjs.git" + }, + homepage: "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-mcp-adapters/", + bugs: { "url": "https://github.com/langchain-ai/langchainjs/issues" }, + scripts: { + "build": "turbo build:compile build:examples --filter @langchain/core --output-logs new-only", + "build:compile": "tsdown", + "build:examples": "tsc -p ./examples/tsconfig.json", + "clean": "rm -rf dist/ dist-cjs/ .turbo/", + "format": "prettier --write \"src/**/*.ts\" \"examples/**/*.ts\"", + "format:check": "prettier --check \"src\" \"examples/**/*.ts\"", + "lint": "run-s lint:eslint lint:dpdm", + "lint:dpdm": "dpdm --skip-dynamic-imports circular --exit-code circular:1 --no-warning --no-tree src/**/*.ts examples/**/*.ts", + "lint:eslint": "eslint --cache src/ examples/", + "lint:fix": "pnpm lint:eslint --fix && pnpm lint:dpdm", + "test": "vitest run", + "test:coverage": "vitest run --coverage", + "test:watch": "vitest" + }, + keywords: [ + "langchain", + "mcp", + "model-context-protocol", + "ai", + "tools" + ], + dependencies: { + "@modelcontextprotocol/sdk": "^1.26.0", + "debug": "^4.4.3", + "zod": "^3.25.76 || ^4" + }, + peerDependencies: { + "@langchain/core": "^1.0.0", + "@langchain/langgraph": "^1.0.0" + }, + peerDependenciesMeta: { + "@langchain/core": { "optional": false }, + "@langchain/langgraph": { "optional": false } + }, + optionalDependencies: { "extended-eventsource": "^1.7.0" }, + devDependencies: { + "@eslint/js": "^9.36.0", + "@langchain/core": "workspace:^", + "@langchain/eslint": "workspace:*", + "@langchain/langgraph": "^1.0.0", + "@langchain/openai": "workspace:*", + "@langchain/tsconfig": "workspace:*", + "@tsconfig/recommended": "^1.0.10", + "@types/debug": "^4.1.12", + "@types/express": "^5.0.6", + "@types/node": "^22.18.8", + "@vitest/coverage-v8": "^3.2.4", + "dotenv": "^16.6.1", + "dpdm": "^3.14.0", + "eslint": "^9.36.0", + "eventsource": "^4.1.0", + "express": "^5.2.1", + "langchain": "workspace:*", + "npm-run-all2": "^8.0.4", + "prettier": "^3.6.2", + "ts-node": "^10.9.2", + "typescript": "~5.8.3", + "typescript-eslint": "^8.45.0", + "vitest": "^3.2.4" + }, + engines: { "node": ">=20.10.0" }, + directories: { "example": "examples" }, + main: "./dist/index.cjs", + types: "./dist/index.d.cts", + exports: { + ".": { + "input": "./src/index.ts", + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + }, + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "./package.json": "./package.json" + }, + files: [ + "dist/", + "CHANGELOG.md", + "README.md", + "LICENSE" + ], + module: "./dist/index.js" +}; +//#endregion +//#region node_modules/eventsource-parser/dist/index.js +var ParseError = class extends Error { + constructor(message, options) { + super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; + } +}; +var LF = 10; +var CR = 13; +var SPACE = 32; +function noop(_arg) {} +function createParser(config) { + if (typeof config == "function") throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"); + const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = []; + let pendingFragmentsLength = 0, isFirstChunk = !0, id, data = "", dataLines = 0, eventType, terminated = !1; + function feed(chunk) { + if (terminated) throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."); + if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) { + const trailing2 = processLines(chunk); + trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize(); + return; + } + if (chunk.indexOf(` +`) === -1 && chunk.indexOf("\r") === -1) { + pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize(); + return; + } + pendingFragments.push(chunk); + const input = pendingFragments.join(""); + pendingFragments.length = 0, pendingFragmentsLength = 0; + const trailing = processLines(input); + trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize(); + } + function checkBufferSize() { + maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, { type: "max-buffer-size-exceeded" })))); + } + function processLines(chunk) { + let searchIndex = 0; + if (chunk.indexOf("\r") === -1) { + let lfIndex = chunk.indexOf(` +`, searchIndex); + for (; lfIndex !== -1;) { + if (searchIndex === lfIndex) { + dataLines > 0 && onEvent({ + id, + event: eventType, + data + }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` +`, searchIndex); + continue; + } + const firstCharCode = chunk.charCodeAt(searchIndex); + if (isDataPrefix(chunk, searchIndex, firstCharCode)) { + const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex); + if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) { + onEvent({ + id, + event: eventType, + data: value + }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(` +`, searchIndex); + continue; + } + data = dataLines === 0 ? value : `${data} +${value}`, dataLines++; + } else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || void 0 : parseLine(chunk, searchIndex, lfIndex); + searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(` +`, searchIndex); + } + return chunk.slice(searchIndex); + } + for (; searchIndex < chunk.length;) { + const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` +`, searchIndex); + let lineEnd = -1; + if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break; + parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++; + } + return chunk.slice(searchIndex); + } + function parseLine(chunk, start, end) { + if (start === end) { + dispatchEvent(); + return; + } + const firstCharCode = chunk.charCodeAt(start); + if (isDataPrefix(chunk, start, firstCharCode)) { + const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end); + data = dataLines === 0 ? value2 : `${data} +${value2}`, dataLines++; + return; + } + if (isEventPrefix(chunk, start, firstCharCode)) { + eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0; + return; + } + if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) { + const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end); + id = value2.includes("\0") ? void 0 : value2; + return; + } + if (firstCharCode === 58) { + if (onComment) { + const line2 = chunk.slice(start, end); + onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1)); + } + return; + } + const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":"); + if (fieldSeparatorIndex === -1) { + processField(line, "", line); + return; + } + const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1; + processField(field, line.slice(fieldSeparatorIndex + offset), line); + } + function processField(field, value, line) { + switch (field) { + case "event": + eventType = value || void 0; + break; + case "data": + data = dataLines === 0 ? value : `${data} +${value}`, dataLines++; + break; + case "id": + id = value.includes("\0") ? void 0 : value; + break; + case "retry": + /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, { + type: "invalid-retry", + value, + line + })); + break; + default: + onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { + type: "unknown-field", + field, + value, + line + })); + break; + } + } + function dispatchEvent() { + dataLines > 0 && onEvent({ + id, + event: eventType, + data + }), id = void 0, data = "", dataLines = 0, eventType = void 0; + } + function reset(options = {}) { + if (options.consume && pendingFragments.length > 0) { + const incompleteLine = pendingFragments.join(""); + parseLine(incompleteLine, 0, incompleteLine.length); + } + isFirstChunk = !0, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1; + } + return { + feed, + reset + }; +} +function isDataPrefix(chunk, i, firstCharCode) { + return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58; +} +function isEventPrefix(chunk, i, firstCharCode) { + return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58; +} +//#endregion +//#region node_modules/eventsource/dist/index.js +var ErrorEvent = class extends Event { + /** + * Constructs a new `ErrorEvent` instance. This is typically not called directly, + * but rather emitted by the `EventSource` object when an error occurs. + * + * @param type - The type of the event (should be "error") + * @param errorEventInitDict - Optional properties to include in the error event + */ + constructor(type, errorEventInitDict) { + var _a, _b; + super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0; + } + /** + * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance, + * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, + * we explicitly include the properties in the `inspect` method. + * + * This is automatically called by Node.js when you `console.log` an instance of this class. + * + * @param _depth - The current depth + * @param options - The options passed to `util.inspect` + * @param inspect - The inspect function to use (prevents having to import it from `util`) + * @returns A string representation of the error + */ + [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) { + return inspect(inspectableError(this), options); + } + /** + * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance, + * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, + * we explicitly include the properties in the `inspect` method. + * + * This is automatically called by Deno when you `console.log` an instance of this class. + * + * @param inspect - The inspect function to use (prevents having to import it from `util`) + * @param options - The options passed to `Deno.inspect` + * @returns A string representation of the error + */ + [Symbol.for("Deno.customInspect")](inspect, options) { + return inspect(inspectableError(this), options); + } +}; +function syntaxError(message) { + const DomException = globalThis.DOMException; + return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message); +} +function flattenError(err) { + return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`; +} +function inspectableError(err) { + return { + type: err.type, + message: err.message, + code: err.code, + defaultPrevented: err.defaultPrevented, + cancelable: err.cancelable, + timeStamp: err.timeStamp + }; +} +var __typeError = (msg) => { + throw TypeError(msg); +}; +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); +var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value); +var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); +var _readyState; +var _url; +var _redirectUrl; +var _withCredentials; +var _fetch; +var _reconnectInterval; +var _reconnectTimer; +var _lastEventId; +var _controller; +var _parser; +var _onError; +var _onMessage; +var _onOpen; +var _EventSource_instances; +var connect_fn; +var _onFetchResponse; +var _onFetchError; +var getRequestOptions_fn; +var _onEvent; +var _onRetryChange; +var failConnection_fn; +var scheduleReconnect_fn; +var _reconnect; +var EventSource = class extends EventTarget { + constructor(url, eventSourceInitDict) { + var _a, _b; + super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => { + var _a2; + __privateGet(this, _parser).reset(); + const { body, redirected, status, headers } = response; + if (status === 204) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close(); + return; + } + if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status); + return; + } + if (!(headers.get("content-type") || "").startsWith("text/event-stream")) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid content type, expected \"text/event-stream\"", status); + return; + } + if (__privateGet(this, _readyState) === this.CLOSED) return; + __privateSet(this, _readyState, this.OPEN); + const openEvent = new Event("open"); + if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close(); + return; + } + const decoder = new TextDecoder(), reader = body.getReader(); + let open = !0; + do { + const { done, value } = await reader.read(); + value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = !1, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this)); + } while (open); + }), __privateAdd(this, _onFetchError, (err) => { + __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err)); + }), __privateAdd(this, _onEvent, (event) => { + typeof event.id == "string" && __privateSet(this, _lastEventId, event.id); + const messageEvent = new MessageEvent(event.event || "message", { + data: event.data, + origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin, + lastEventId: event.id || "" + }); + __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent); + }), __privateAdd(this, _onRetryChange, (value) => { + __privateSet(this, _reconnectInterval, value); + }), __privateAdd(this, _reconnect, () => { + __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this); + }); + try { + if (url instanceof URL) __privateSet(this, _url, url); + else if (typeof url == "string") __privateSet(this, _url, new URL(url, getBaseURL())); + else throw new Error("Invalid URL"); + } catch { + throw syntaxError("An invalid or illegal string was specified"); + } + __privateSet(this, _parser, createParser({ + onEvent: __privateGet(this, _onEvent), + onRetry: __privateGet(this, _onRetryChange) + })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : !1), __privateMethod(this, _EventSource_instances, connect_fn).call(this); + } + /** + * Returns the state of this EventSource object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + * + * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface, + * defined in the TypeScript `dom` library. + * + * @public + */ + get readyState() { + return __privateGet(this, _readyState); + } + /** + * Returns the URL providing the event stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + * + * @public + */ + get url() { + return __privateGet(this, _url).href; + } + /** + * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials() { + return __privateGet(this, _withCredentials); + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror() { + return __privateGet(this, _onError); + } + set onerror(value) { + __privateSet(this, _onError, value); + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage() { + return __privateGet(this, _onMessage); + } + set onmessage(value) { + __privateSet(this, _onMessage, value); + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen() { + return __privateGet(this, _onOpen); + } + set onopen(value) { + __privateSet(this, _onOpen, value); + } + addEventListener(type, listener, options) { + const listen = listener; + super.addEventListener(type, listen, options); + } + removeEventListener(type, listener, options) { + const listen = listener; + super.removeEventListener(type, listen, options); + } + /** + * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + * + * @public + */ + close() { + __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0)); + } +}; +_readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), connect_fn = function() { + __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError)); +}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), getRequestOptions_fn = function() { + var _a; + const init = { + mode: "cors", + redirect: "follow", + headers: { + Accept: "text/event-stream", + ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 + }, + cache: "no-store", + signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal + }; + return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init; +}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), failConnection_fn = function(message, code) { + var _a; + __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED); + const errorEvent = new ErrorEvent("error", { + code, + message + }); + (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent); +}, scheduleReconnect_fn = function(message, code) { + var _a; + if (__privateGet(this, _readyState) === this.CLOSED) return; + __privateSet(this, _readyState, this.CONNECTING); + const errorEvent = new ErrorEvent("error", { + code, + message + }); + (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval))); +}, _reconnect = /* @__PURE__ */ new WeakMap(), EventSource.CONNECTING = 0, EventSource.OPEN = 1, EventSource.CLOSED = 2; +function getBaseURL() { + const doc = "document" in globalThis ? globalThis.document : void 0; + return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0; +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js +/** +* Normalizes HeadersInit to a plain Record for manipulation. +* Handles Headers objects, arrays of tuples, and plain objects. +*/ +function normalizeHeaders(headers) { + if (!headers) return {}; + if (headers instanceof Headers) return Object.fromEntries(headers.entries()); + if (Array.isArray(headers)) return Object.fromEntries(headers); + return { ...headers }; +} +/** +* Creates a fetch function that includes base RequestInit options. +* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. +* +* @param baseFetch - The base fetch function to wrap (defaults to global fetch) +* @param baseInit - The base RequestInit to merge with each request +* @returns A wrapped fetch function that merges base options with call-specific options +*/ +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) return baseFetch; + return async (url, init) => { + return baseFetch(url, { + ...baseInit, + ...init, + headers: init?.headers ? { + ...normalizeHeaders(baseInit.headers), + ...normalizeHeaders(init.headers) + } : baseInit.headers + }); + }; +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/types.js +var LATEST_PROTOCOL_VERSION = "2025-11-25"; +var SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-06-18", + "2025-03-26", + "2024-11-05", + "2024-10-07" +]; +var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +/** +* Assert 'object' type schema. +* +* @internal +*/ +var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function")); +/** +* A progress token, used to associate progress notifications with the original request. +*/ +var ProgressTokenSchema = union([string$1(), number$1().int()]); +/** +* An opaque token used to represent a cursor for pagination. +*/ +var CursorSchema = string$1(); +looseObject({ + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl: number$1().optional(), + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: number$1().optional() +}); +var TaskMetadataSchema = object({ ttl: number$1().optional() }); +/** +* Metadata for associating messages with a task. +* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. +*/ +var RelatedTaskMetadataSchema = object({ taskId: string$1() }); +var RequestMetaSchema = looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: ProgressTokenSchema.optional(), + /** + * If specified, this request is related to the provided task. + */ + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +/** +* Common params for any request. +*/ +var BaseRequestParamsSchema = object({ +/** +* See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. +*/ +_meta: RequestMetaSchema.optional() }); +/** +* Common params for any task-augmented request. +*/ +var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ +/** +* If specified, the caller is requesting task-augmented execution for this request. +* The request will return a CreateTaskResult immediately, and the actual result can be +* retrieved later via tasks/result. +* +* Task augmentation is subject to capability negotiation - receivers MUST declare support +* for task augmentation of specific request types in their capabilities. +*/ +task: TaskMetadataSchema.optional() }); +/** +* Checks if a value is a valid TaskAugmentedRequestParams. +* @param value - The value to check. +* +* @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. +*/ +var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +var RequestSchema = object({ + method: string$1(), + params: BaseRequestParamsSchema.loose().optional() +}); +var NotificationsParamsSchema = object({ +/** +* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) +* for notes on _meta usage. +*/ +_meta: RequestMetaSchema.optional() }); +var NotificationSchema = object({ + method: string$1(), + params: NotificationsParamsSchema.loose().optional() +}); +var ResultSchema = looseObject({ +/** +* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) +* for notes on _meta usage. +*/ +_meta: RequestMetaSchema.optional() }); +/** +* A uniquely identifying ID for a request in JSON-RPC. +*/ +var RequestIdSchema = union([string$1(), number$1().int()]); +/** +* A request that expects a response. +*/ +var JSONRPCRequestSchema = object({ + jsonrpc: literal("2.0"), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +/** +* A notification which does not expect a response. +*/ +var JSONRPCNotificationSchema = object({ + jsonrpc: literal("2.0"), + ...NotificationSchema.shape +}).strict(); +var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** +* A successful (non-error) response to a request. +*/ +var JSONRPCResultResponseSchema = object({ + jsonrpc: literal("2.0"), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +/** +* Checks if a value is a valid JSONRPCResultResponse. +* @param value - The value to check. +* +* @returns True if the value is a valid JSONRPCResultResponse, false otherwise. +*/ +var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +/** +* Error codes defined by the JSON-RPC specification. +*/ +var ErrorCode; +(function(ErrorCode) { + ErrorCode[ErrorCode["ConnectionClosed"] = -32e3] = "ConnectionClosed"; + ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; + ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; + ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; + ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; + ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; + ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; + ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; +})(ErrorCode || (ErrorCode = {})); +/** +* A response to a request that indicates an error occurred. +*/ +var JSONRPCErrorResponseSchema = object({ + jsonrpc: literal("2.0"), + id: RequestIdSchema.optional(), + error: object({ + /** + * The error type that occurred. + */ + code: number$1().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string$1(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: unknown().optional() + }) +}).strict(); +/** +* Checks if a value is a valid JSONRPCErrorResponse. +* @param value - The value to check. +* +* @returns True if the value is a valid JSONRPCErrorResponse, false otherwise. +*/ +var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +var JSONRPCMessageSchema = union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +/** +* A response that indicates success but carries no data. +*/ +var EmptyResultSchema = ResultSchema.strict(); +var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema.optional(), + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: string$1().optional() +}); +/** +* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. +* +* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. +* +* This notification indicates that the result will be unused, so any associated processing SHOULD cease. +* +* A client MUST NOT attempt to cancel its `initialize` request. +*/ +var CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +/** +* Base schema to add `icons` property. +* +*/ +var IconsSchema = object({ +/** +* Optional set of sized icons that the client can display in a user interface. +* +* Clients that support rendering icons MUST support at least the following MIME types: +* - `image/png` - PNG images (safe, universal compatibility) +* - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) +* +* Clients that support rendering icons SHOULD also support: +* - `image/svg+xml` - SVG images (scalable but requires security precautions) +* - `image/webp` - WebP images (modern, efficient format) +*/ +icons: array(object({ + /** + * URL or data URI for the icon. + */ + src: string$1(), + /** + * Optional MIME type for the icon. + */ + mimeType: string$1().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: array(string$1()).optional(), + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme: _enum(["light", "dark"]).optional() +})).optional() }); +/** +* Base metadata interface for common properties across resources, tools, prompts, and implementations. +*/ +var BaseMetadataSchema = object({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: string$1(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: string$1().optional() +}); +/** +* Describes the name and version of an MCP implementation. +*/ +var ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: string$1(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: string$1().optional(), + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description: string$1().optional() +}); +var ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value)) { + if (Object.keys(value).length === 0) return { form: {} }; + } + return value; +}, intersection(object({ + form: intersection(object({ applyDefaults: boolean$1().optional() }), record(string$1(), unknown())).optional(), + url: AssertObjectSchema.optional() +}), record(string$1(), unknown()).optional())); +/** +* Task capabilities for clients, indicating which request types support task creation. +*/ +var ClientTasksCapabilitySchema = looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for sampling requests. + */ + sampling: looseObject({ createMessage: AssertObjectSchema.optional() }).optional(), + /** + * Task support for elicitation requests. + */ + elicitation: looseObject({ create: AssertObjectSchema.optional() }).optional() + }).optional() +}); +/** +* Task capabilities for servers, indicating which request types support task creation. +*/ +var ServerTasksCapabilitySchema = looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for tool requests. + */ +tools: looseObject({ call: AssertObjectSchema.optional() }).optional() }).optional() +}); +/** +* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. +*/ +var ClientCapabilitiesSchema = object({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: record(string$1(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: object({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ + tools: AssertObjectSchema.optional() + }).optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ + roots: object({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ +listChanged: boolean$1().optional() }).optional(), + /** + * Present if the client supports task creation. + */ + tasks: ClientTasksCapabilitySchema.optional(), + /** + * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: record(string$1(), AssertObjectSchema).optional() +}); +var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string$1(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** +* This request is sent from the client to the server when it first connects, asking it to begin initialization. +*/ +var InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +/** +* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. +*/ +var ServerCapabilitiesSchema = object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: record(string$1(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ +listChanged: boolean$1().optional() }).optional(), + /** + * Present if the server offers any resources to read. + */ + resources: object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: boolean$1().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: boolean$1().optional() + }).optional(), + /** + * Present if the server offers any tools to call. + */ + tools: object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ +listChanged: boolean$1().optional() }).optional(), + /** + * Present if the server supports task creation. + */ + tasks: ServerTasksCapabilitySchema.optional(), + /** + * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: record(string$1(), AssertObjectSchema).optional() +}); +/** +* After receiving an initialize request from the client, the server sends this response. +*/ +var InitializeResultSchema = ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string$1(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: string$1().optional() +}); +/** +* This notification is sent from the client to the server after initialization has finished. +*/ +var InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +var isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +/** +* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. +*/ +var PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +var ProgressSchema = object({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: number$1(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: optional(number$1()), + /** + * An optional message describing the current progress. + */ + message: optional(string$1()) +}); +var ProgressNotificationParamsSchema = object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema +}); +/** +* An out-of-band notification used to inform the receiver of a progress update for a long-running request. +* +* @category notifications/progress +*/ +var ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ +/** +* An opaque token representing the current pagination position. +* If provided, the server should return results starting after this cursor. +*/ +cursor: CursorSchema.optional() }); +var PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); +var PaginatedResultSchema = ResultSchema.extend({ +/** +* An opaque token representing the pagination position after the last returned result. +* If present, there may be more results available. +*/ +nextCursor: CursorSchema.optional() }); +/** +* The status of a task. +* */ +var TaskStatusSchema = _enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" +]); +/** +* A pollable state object associated with a request. +*/ +var TaskSchema = object({ + taskId: string$1(), + status: TaskStatusSchema, + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: union([number$1(), _null()]), + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string$1(), + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string$1(), + pollInterval: optional(number$1()), + /** + * Optional diagnostic message for failed tasks or other status information. + */ + statusMessage: optional(string$1()) +}); +/** +* Result returned when a task is created, containing the task data wrapped in a task field. +*/ +var CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); +/** +* Parameters for task status notification. +*/ +var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +/** +* A notification sent when a task's status changes. +*/ +var TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +/** +* A request to get the state of a specific task. +*/ +var GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ taskId: string$1() }) +}); +/** +* The response to a tasks/get request. +*/ +var GetTaskResultSchema = ResultSchema.merge(TaskSchema); +/** +* A request to get the result of a specific task. +*/ +var GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ taskId: string$1() }) +}); +ResultSchema.loose(); +/** +* A request to list tasks. +*/ +var ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); +/** +* The response to a tasks/list request. +*/ +var ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) }); +/** +* A request to cancel a specific task. +*/ +var CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ taskId: string$1() }) +}); +/** +* The response to a tasks/cancel request. +*/ +var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +/** +* The contents of a specific resource or sub-resource. +*/ +var ResourceContentsSchema = object({ + /** + * The URI of this resource. + */ + uri: string$1(), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string$1()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +var TextResourceContentsSchema = ResourceContentsSchema.extend({ +/** +* The text of the item. This must only be set if the item can actually be represented as text (not binary data). +*/ +text: string$1() }); +/** +* A Zod schema for validating Base64 strings that is more performant and +* robust for very large inputs than the default regex-based check. It avoids +* stack overflows by using the native `atob` function for validation. +*/ +var Base64Schema = string$1().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +var BlobResourceContentsSchema = ResourceContentsSchema.extend({ +/** +* A base64-encoded string representing the binary data of the item. +*/ +blob: Base64Schema }); +/** +* The sender or recipient of messages and data in a conversation. +*/ +var RoleSchema = _enum(["user", "assistant"]); +/** +* Optional annotations providing clients additional context about a resource. +*/ +var AnnotationsSchema = object({ + /** + * Intended audience(s) for the resource. + */ + audience: array(RoleSchema).optional(), + /** + * Importance hint for the resource, from 0 (least) to 1 (most). + */ + priority: number$1().min(0).max(1).optional(), + /** + * ISO 8601 timestamp for the most recent modification. + */ + lastModified: datetime({ offset: true }).optional() +}); +/** +* A known resource that the server is capable of reading. +*/ +var ResourceSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: string$1(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string$1()), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string$1()), + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size: optional(number$1()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) +}); +/** +* A template description for resources available on the server. +*/ +var ResourceTemplateSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: string$1(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string$1()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: optional(string$1()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) +}); +/** +* Sent from the client to request a list of resources the server has. +*/ +var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); +/** +* The server's response to a resources/list request from the client. +*/ +var ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) }); +/** +* Sent from the client to request a list of resource templates the server has. +*/ +var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); +/** +* The server's response to a resources/templates/list request from the client. +*/ +var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) }); +var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ +/** +* The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. +* +* @format uri +*/ +uri: string$1() }); +/** +* Parameters for a `resources/read` request. +*/ +var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to the server, to read a specific resource URI. +*/ +var ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +/** +* The server's response to a resources/read request from the client. +*/ +var ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); +/** +* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. +*/ +var ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. +*/ +var SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. +*/ +var UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +/** +* Parameters for a `notifications/resources/updated` notification. +*/ +var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ +/** +* The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. +*/ +uri: string$1() }); +/** +* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. +*/ +var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +/** +* Describes an argument that a prompt can accept. +*/ +var PromptArgumentSchema = object({ + /** + * The name of the argument. + */ + name: string$1(), + /** + * A human-readable description of the argument. + */ + description: optional(string$1()), + /** + * Whether this argument must be provided. + */ + required: optional(boolean$1()) +}); +/** +* A prompt or prompt template that the server offers. +*/ +var PromptSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: optional(string$1()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: optional(array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) +}); +/** +* Sent from the client to request a list of prompts and prompt templates the server has. +*/ +var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); +/** +* The server's response to a prompts/list request from the client. +*/ +var ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) }); +/** +* Parameters for a `prompts/get` request. +*/ +var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: string$1(), + /** + * Arguments to use for templating the prompt. + */ + arguments: record(string$1(), string$1()).optional() +}); +/** +* Used by the client to get a prompt provided by the server. +*/ +var GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +/** +* Text provided to or from an LLM. +*/ +var TextContentSchema = object({ + type: literal("text"), + /** + * The text content of the message. + */ + text: string$1(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +/** +* An image provided to or from an LLM. +*/ +var ImageContentSchema = object({ + type: literal("image"), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string$1(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +/** +* An Audio provided to or from an LLM. +*/ +var AudioContentSchema = object({ + type: literal("audio"), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string$1(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +/** +* A tool call request from an assistant (LLM). +* Represents the assistant's request to use a tool. +*/ +var ToolUseContentSchema = object({ + type: literal("tool_use"), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: string$1(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: string$1(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: record(string$1(), unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +/** +* The contents of a resource, embedded into a prompt or tool call result. +*/ +var EmbeddedResourceSchema = object({ + type: literal("resource"), + resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +/** +* A content block that can be used in prompts and tool results. +*/ +var ContentBlockSchema = union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceSchema.extend({ type: literal("resource_link") }), + EmbeddedResourceSchema +]); +/** +* Describes a message returned as part of a prompt. +*/ +var PromptMessageSchema = object({ + role: RoleSchema, + content: ContentBlockSchema +}); +/** +* The server's response to a prompts/get request from the client. +*/ +var GetPromptResultSchema = ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: string$1().optional(), + messages: array(PromptMessageSchema) +}); +/** +* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +var PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Additional properties describing a Tool to clients. +* +* NOTE: all properties in ToolAnnotations are **hints**. +* They are not guaranteed to provide a faithful description of +* tool behavior (including descriptive properties like `title`). +* +* Clients should never make tool use decisions based on ToolAnnotations +* received from untrusted servers. +*/ +var ToolAnnotationsSchema = object({ + /** + * A human-readable title for the tool. + */ + title: string$1().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: boolean$1().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: boolean$1().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: boolean$1().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: boolean$1().optional() +}); +/** +* Execution-related properties for a tool. +*/ +var ToolExecutionSchema = object({ +/** +* Indicates the tool's preference for task-augmented execution. +* - "required": Clients MUST invoke the tool as a task +* - "optional": Clients MAY invoke the tool as a task or normal request +* - "forbidden": Clients MUST NOT attempt to invoke the tool as a task +* +* If not present, defaults to "forbidden". +*/ +taskSupport: _enum([ + "required", + "optional", + "forbidden" +]).optional() }); +/** +* Definition for a tool the client can call. +*/ +var ToolSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: string$1().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ + inputSchema: object({ + type: literal("object"), + properties: record(string$1(), AssertObjectSchema).optional(), + required: array(string$1()).optional() + }).catchall(unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ + outputSchema: object({ + type: literal("object"), + properties: record(string$1(), AssertObjectSchema).optional(), + required: array(string$1()).optional() + }).catchall(unknown()).optional(), + /** + * Optional additional tool information. + */ + annotations: ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: ToolExecutionSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +/** +* Sent from the client to request a list of tools the server has. +*/ +var ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); +/** +* The server's response to a tools/list request from the client. +*/ +var ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) }); +/** +* The server's response to a tool call. +*/ +var CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: array(ContentBlockSchema).default([]), + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: record(string$1(), unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: boolean$1().optional() +}); +CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); +/** +* Parameters for a `tools/call` request. +*/ +var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: string$1(), + /** + * Arguments to pass to the tool. + */ + arguments: record(string$1(), unknown()).optional() +}); +/** +* Used by the client to invoke a tool provided by the server. +*/ +var CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +/** +* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +var ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Base schema for list changed subscription options (without callback). +* Used internally for Zod validation of autoRefresh and debounceMs. +*/ +var ListChangedOptionsBaseSchema = object({ + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * The callback will be called with the updated list. + * + * If false, the callback will be called with null items, allowing manual refresh. + * + * @default true + */ + autoRefresh: boolean$1().default(true), + /** + * Debounce time in milliseconds for list changed notification processing. + * + * Multiple notifications received within this timeframe will only trigger one refresh. + * Set to 0 to disable debouncing. + * + * @default 300 + */ + debounceMs: number$1().int().nonnegative().default(300) +}); +/** +* The severity of a log message. +*/ +var LoggingLevelSchema = _enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" +]); +/** +* Parameters for a `logging/setLevel` request. +*/ +var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ +/** +* The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. +*/ +level: LoggingLevelSchema }); +/** +* A request from the client to the server, to enable or adjust logging. +*/ +var SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +/** +* Parameters for a `notifications/message` notification. +*/ +var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: string$1().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown() +}); +/** +* Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. +*/ +var LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +/** +* The server's preferences for model selection, requested of the client during sampling. +*/ +var ModelPreferencesSchema = object({ + /** + * Optional hints to use for model selection. + */ + hints: array(object({ + /** + * A hint for a model name. + */ +name: string$1().optional() })).optional(), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: number$1().min(0).max(1).optional(), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: number$1().min(0).max(1).optional(), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: number$1().min(0).max(1).optional() +}); +/** +* Controls tool usage behavior in sampling requests. +*/ +var ToolChoiceSchema = object({ +/** +* Controls when tools are used: +* - "auto": Model decides whether to use tools (default) +* - "required": Model MUST use at least one tool before completing +* - "none": Model MUST NOT use any tools +*/ +mode: _enum([ + "auto", + "required", + "none" +]).optional() }); +/** +* The result of a tool execution, provided by the user (server). +* Represents the outcome of invoking a tool requested via ToolUseContent. +*/ +var ToolResultContentSchema = object({ + type: literal("tool_result"), + toolUseId: string$1().describe("The unique identifier for the corresponding tool call."), + content: array(ContentBlockSchema).default([]), + structuredContent: object({}).loose().optional(), + isError: boolean$1().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +/** +* Basic content types for sampling responses (without tool use). +* Used for backwards-compatible CreateMessageResult when tools are not used. +*/ +var SamplingContentSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema +]); +/** +* Content block types allowed in sampling messages. +* This includes text, image, audio, tool use requests, and tool results. +*/ +var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** +* Describes a message issued to or received from an LLM API. +*/ +var SamplingMessageSchema = object({ + role: RoleSchema, + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +/** +* Parameters for a `sampling/createMessage` request. +*/ +var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + messages: array(SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: string$1().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: _enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: number$1().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number$1().int(), + stopSequences: array(string$1()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: AssertObjectSchema.optional(), + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: array(ToolSchema).optional(), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: ToolChoiceSchema.optional() +}); +/** +* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. +*/ +var CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +/** +* The client's response to a sampling/create_message request from the server. +* This is the backwards-compatible version that returns single content (no arrays). +* Used when the request does not include tools. +*/ +var CreateMessageResultSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: string$1(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(string$1())), + role: RoleSchema, + /** + * Response content. Single content block (text, image, or audio). + */ + content: SamplingContentSchema +}); +/** +* The client's response to a sampling/create_message request when tools were provided. +* This version supports array content for tool use flows. +*/ +var CreateMessageResultWithToolsSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: string$1(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(string$1())), + role: RoleSchema, + /** + * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". + */ + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) +}); +/** +* Primitive schema definition for boolean fields. +*/ +var BooleanSchemaSchema = object({ + type: literal("boolean"), + title: string$1().optional(), + description: string$1().optional(), + default: boolean$1().optional() +}); +/** +* Primitive schema definition for string fields. +*/ +var StringSchemaSchema = object({ + type: literal("string"), + title: string$1().optional(), + description: string$1().optional(), + minLength: number$1().optional(), + maxLength: number$1().optional(), + format: _enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: string$1().optional() +}); +/** +* Primitive schema definition for number fields. +*/ +var NumberSchemaSchema = object({ + type: _enum(["number", "integer"]), + title: string$1().optional(), + description: string$1().optional(), + minimum: number$1().optional(), + maximum: number$1().optional(), + default: number$1().optional() +}); +/** +* Schema for single-selection enumeration without display titles for options. +*/ +var UntitledSingleSelectEnumSchemaSchema = object({ + type: literal("string"), + title: string$1().optional(), + description: string$1().optional(), + enum: array(string$1()), + default: string$1().optional() +}); +/** +* Schema for single-selection enumeration with display titles for each option. +*/ +var TitledSingleSelectEnumSchemaSchema = object({ + type: literal("string"), + title: string$1().optional(), + description: string$1().optional(), + oneOf: array(object({ + const: string$1(), + title: string$1() + })), + default: string$1().optional() +}); +/** +* Union of all primitive schema definitions. +*/ +var PrimitiveSchemaDefinitionSchema = union([ + union([ + object({ + type: literal("string"), + title: string$1().optional(), + description: string$1().optional(), + enum: array(string$1()), + enumNames: array(string$1()).optional(), + default: string$1().optional() + }), + union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]), + union([object({ + type: literal("array"), + title: string$1().optional(), + description: string$1().optional(), + minItems: number$1().optional(), + maxItems: number$1().optional(), + items: object({ + type: literal("string"), + enum: array(string$1()) + }), + default: array(string$1()).optional() + }), object({ + type: literal("array"), + title: string$1().optional(), + description: string$1().optional(), + minItems: number$1().optional(), + maxItems: number$1().optional(), + items: object({ anyOf: array(object({ + const: string$1(), + title: string$1() + })) }), + default: array(string$1()).optional() + })]) + ]), + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema +]); +/** +* The parameters for a request to elicit additional information from the user via the client. +*/ +var ElicitRequestParamsSchema = union([TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + * + * Optional for backward compatibility. Clients MUST treat missing mode as "form". + */ + mode: literal("form").optional(), + /** + * The message to present to the user describing what information is being requested. + */ + message: string$1(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: object({ + type: literal("object"), + properties: record(string$1(), PrimitiveSchemaDefinitionSchema), + required: array(string$1()).optional() + }) +}), TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: literal("url"), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string$1(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string$1(), + /** + * The URL that the user should navigate to. + */ + url: string$1().url() +})]); +/** +* A request from the server to elicit user input via the client. +* The client should present the message and form fields to the user (form mode) +* or navigate to a URL (URL mode). +*/ +var ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +/** +* Parameters for a `notifications/elicitation/complete` notification. +* +* @category notifications/elicitation/complete +*/ +var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ +/** +* The ID of the elicitation that completed. +*/ +elicitationId: string$1() }); +/** +* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. +* +* @category notifications/elicitation/complete +*/ +var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +/** +* The client's response to an elicitation/create request from the server. +*/ +var ElicitResultSchema = ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: _enum([ + "accept", + "decline", + "cancel" + ]), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize null to undefined for leniency while maintaining type compatibility. + */ + content: preprocess((val) => val === null ? void 0 : val, record(string$1(), union([ + string$1(), + number$1(), + boolean$1(), + array(string$1()) + ])).optional()) +}); +/** +* A reference to a resource or resource template definition. +*/ +var ResourceTemplateReferenceSchema = object({ + type: literal("ref/resource"), + /** + * The URI or URI template of the resource. + */ + uri: string$1() +}); +/** +* Identifies a prompt. +*/ +var PromptReferenceSchema = object({ + type: literal("ref/prompt"), + /** + * The name of the prompt or prompt template + */ + name: string$1() +}); +/** +* Parameters for a `completion/complete` request. +*/ +var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: object({ + /** + * The name of the argument + */ + name: string$1(), + /** + * The value of the argument to use for completion matching. + */ + value: string$1() + }), + context: object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ +arguments: record(string$1(), string$1()).optional() }).optional() +}); +/** +* A request from the client to the server, to ask for completion options. +*/ +var CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +/** +* The server's response to a completion/complete request +*/ +var CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: array(string$1()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: optional(number$1().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: optional(boolean$1()) +}) }); +/** +* Represents a root directory or file that the server can operate on. +*/ +var RootSchema = object({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: string$1().startsWith("file://"), + /** + * An optional name for the root. + */ + name: string$1().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string$1(), unknown()).optional() +}); +/** +* Sent from the server to request a list of root URIs from the client. +*/ +var ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The client's response to a roots/list request from the server. +*/ +var ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) }); +/** +* A notification from the client to the server, informing it that the list of roots has changed. +*/ +var RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema, + TaskStatusNotificationSchema +]); +union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + TaskStatusNotificationSchema, + ElicitationCompleteNotificationSchema +]); +union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +var McpError = class McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = "McpError"; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); + } + return new McpError(code, message, data); + } +}; +/** +* Specialized error type when a tool requires a URL mode elicitation. +* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. +*/ +var UrlElicitationRequiredError = class extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(ErrorCode.UrlElicitationRequired, message, { elicitations }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; +//#endregion +//#region node_modules/pkce-challenge/dist/index.node.js +var crypto = globalThis.crypto?.webcrypto ?? globalThis.crypto ?? import("node:crypto").then((m) => m.webcrypto); +/** +* Creates an array of length `size` of random bytes +* @param size +* @returns Array of random ints (0 to 255) +*/ +async function getRandomValues(size) { + return (await crypto).getRandomValues(new Uint8Array(size)); +} +/** Generate cryptographically strong random string +* @param size The desired length of the string +* @returns The random string +*/ +async function random(size) { + const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"; + const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % 66; + let result = ""; + while (result.length < size) { + const randomBytes = await getRandomValues(size - result.length); + for (const randomByte of randomBytes) if (randomByte < evenDistCutoff) result += mask[randomByte % 66]; + } + return result; +} +/** Generate a PKCE challenge verifier +* @param length Length of the verifier +* @returns A random verifier `length` characters long +*/ +async function generateVerifier(length) { + return await random(length); +} +/** Generate a PKCE code challenge from a code verifier +* @param code_verifier +* @returns The base64 url encoded code challenge +*/ +async function generateChallenge(code_verifier) { + const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier)); + return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, ""); +} +/** Generate a PKCE challenge pair +* @param length Length of the verifer (between 43-128). Defaults to 43. +* @returns PKCE challenge pair +*/ +async function pkceChallenge(length) { + if (!length) length = 43; + if (length < 43 || length > 128) throw `Expected a length between 43 and 128. Received ${length}.`; + const verifier = await generateVerifier(length); + return { + code_verifier: verifier, + code_challenge: await generateChallenge(verifier) + }; +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js +/** +* Reusable URL validation that disallows javascript: scheme +*/ +var SafeUrlSchema = url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } +}).refine((url) => { + const u = new URL(url); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; +}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); +/** +* RFC 9728 OAuth Protected Resource Metadata +*/ +var OAuthProtectedResourceMetadataSchema = looseObject({ + resource: string$1().url(), + authorization_servers: array(SafeUrlSchema).optional(), + jwks_uri: string$1().url().optional(), + scopes_supported: array(string$1()).optional(), + bearer_methods_supported: array(string$1()).optional(), + resource_signing_alg_values_supported: array(string$1()).optional(), + resource_name: string$1().optional(), + resource_documentation: string$1().optional(), + resource_policy_uri: string$1().url().optional(), + resource_tos_uri: string$1().url().optional(), + tls_client_certificate_bound_access_tokens: boolean$1().optional(), + authorization_details_types_supported: array(string$1()).optional(), + dpop_signing_alg_values_supported: array(string$1()).optional(), + dpop_bound_access_tokens_required: boolean$1().optional() +}); +/** +* RFC 8414 OAuth 2.0 Authorization Server Metadata +*/ +var OAuthMetadataSchema = looseObject({ + issuer: string$1(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: array(string$1()).optional(), + response_types_supported: array(string$1()), + response_modes_supported: array(string$1()).optional(), + grant_types_supported: array(string$1()).optional(), + token_endpoint_auth_methods_supported: array(string$1()).optional(), + token_endpoint_auth_signing_alg_values_supported: array(string$1()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: array(string$1()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: array(string$1()).optional(), + introspection_endpoint: string$1().optional(), + introspection_endpoint_auth_methods_supported: array(string$1()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: array(string$1()).optional(), + code_challenge_methods_supported: array(string$1()).optional(), + client_id_metadata_document_supported: boolean$1().optional() +}); +/** +* OpenID Connect Discovery metadata that may include OAuth 2.0 fields +* This schema represents the real-world scenario where OIDC providers +* return a mix of OpenID Connect and OAuth 2.0 metadata fields +*/ +var OpenIdProviderDiscoveryMetadataSchema = object({ + ...looseObject({ + issuer: string$1(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: array(string$1()).optional(), + response_types_supported: array(string$1()), + response_modes_supported: array(string$1()).optional(), + grant_types_supported: array(string$1()).optional(), + acr_values_supported: array(string$1()).optional(), + subject_types_supported: array(string$1()), + id_token_signing_alg_values_supported: array(string$1()), + id_token_encryption_alg_values_supported: array(string$1()).optional(), + id_token_encryption_enc_values_supported: array(string$1()).optional(), + userinfo_signing_alg_values_supported: array(string$1()).optional(), + userinfo_encryption_alg_values_supported: array(string$1()).optional(), + userinfo_encryption_enc_values_supported: array(string$1()).optional(), + request_object_signing_alg_values_supported: array(string$1()).optional(), + request_object_encryption_alg_values_supported: array(string$1()).optional(), + request_object_encryption_enc_values_supported: array(string$1()).optional(), + token_endpoint_auth_methods_supported: array(string$1()).optional(), + token_endpoint_auth_signing_alg_values_supported: array(string$1()).optional(), + display_values_supported: array(string$1()).optional(), + claim_types_supported: array(string$1()).optional(), + claims_supported: array(string$1()).optional(), + service_documentation: string$1().optional(), + claims_locales_supported: array(string$1()).optional(), + ui_locales_supported: array(string$1()).optional(), + claims_parameter_supported: boolean$1().optional(), + request_parameter_supported: boolean$1().optional(), + request_uri_parameter_supported: boolean$1().optional(), + require_request_uri_registration: boolean$1().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: boolean$1().optional() + }).shape, + ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape +}); +/** +* OAuth 2.1 token response +*/ +var OAuthTokensSchema = object({ + access_token: string$1(), + id_token: string$1().optional(), + token_type: string$1(), + expires_in: number().optional(), + scope: string$1().optional(), + refresh_token: string$1().optional() +}).strip(); +/** +* OAuth 2.1 error response +*/ +var OAuthErrorResponseSchema = object({ + error: string$1(), + error_description: string$1().optional(), + error_uri: string$1().optional() +}); +/** +* Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri +*/ +var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata +*/ +var OAuthClientMetadataSchema = object({ + redirect_uris: array(SafeUrlSchema), + token_endpoint_auth_method: string$1().optional(), + grant_types: array(string$1()).optional(), + response_types: array(string$1()).optional(), + client_name: string$1().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: string$1().optional(), + contacts: array(string$1()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: string$1().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: string$1().optional(), + software_version: string$1().optional(), + software_statement: string$1().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration client information +*/ +var OAuthClientInformationSchema = object({ + client_id: string$1(), + client_secret: string$1().optional(), + client_id_issued_at: number$1().optional(), + client_secret_expires_at: number$1().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) +*/ +var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +object({ + error: string$1(), + error_description: string$1().optional() +}).strip(); +object({ + token: string$1(), + token_type_hint: string$1().optional() +}).strip(); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js +/** +* Utilities for handling OAuth resource URIs. +*/ +/** +* Converts a server URL to a resource URL by removing the fragment. +* RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". +* Keeps everything else unchanged (scheme, domain, port, path, query). +*/ +function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); + resourceURL.hash = ""; + return resourceURL; +} +/** +* Checks if a requested resource URL matches a configured resource URL. +* A requested resource matches if it has the same scheme, domain, port, +* and its path starts with the configured resource's path. +* +* @param requestedResource The resource URL being requested +* @param configuredResource The resource URL that has been configured +* @returns true if the requested resource matches the configured resource, false otherwise +*/ +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); + if (requested.origin !== configured.origin) return false; + if (requested.pathname.length < configured.pathname.length) return false; + const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; + const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; + return requestedPath.startsWith(configuredPath); +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js +/** +* Base class for all OAuth errors +*/ +var OAuthError = class extends Error { + constructor(message, errorUri) { + super(message); + this.errorUri = errorUri; + this.name = this.constructor.name; + } + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject() { + const response = { + error: this.errorCode, + error_description: this.message + }; + if (this.errorUri) response.error_uri = this.errorUri; + return response; + } + get errorCode() { + return this.constructor.errorCode; + } +}; +/** +* Invalid request error - The request is missing a required parameter, +* includes an invalid parameter value, includes a parameter more than once, +* or is otherwise malformed. +*/ +var InvalidRequestError = class extends OAuthError {}; +InvalidRequestError.errorCode = "invalid_request"; +/** +* Invalid client error - Client authentication failed (e.g., unknown client, no client +* authentication included, or unsupported authentication method). +*/ +var InvalidClientError = class extends OAuthError {}; +InvalidClientError.errorCode = "invalid_client"; +/** +* Invalid grant error - The provided authorization grant or refresh token is +* invalid, expired, revoked, does not match the redirection URI used in the +* authorization request, or was issued to another client. +*/ +var InvalidGrantError = class extends OAuthError {}; +InvalidGrantError.errorCode = "invalid_grant"; +/** +* Unauthorized client error - The authenticated client is not authorized to use +* this authorization grant type. +*/ +var UnauthorizedClientError = class extends OAuthError {}; +UnauthorizedClientError.errorCode = "unauthorized_client"; +/** +* Unsupported grant type error - The authorization grant type is not supported +* by the authorization server. +*/ +var UnsupportedGrantTypeError = class extends OAuthError {}; +UnsupportedGrantTypeError.errorCode = "unsupported_grant_type"; +/** +* Invalid scope error - The requested scope is invalid, unknown, malformed, or +* exceeds the scope granted by the resource owner. +*/ +var InvalidScopeError = class extends OAuthError {}; +InvalidScopeError.errorCode = "invalid_scope"; +/** +* Access denied error - The resource owner or authorization server denied the request. +*/ +var AccessDeniedError = class extends OAuthError {}; +AccessDeniedError.errorCode = "access_denied"; +/** +* Server error - The authorization server encountered an unexpected condition +* that prevented it from fulfilling the request. +*/ +var ServerError = class extends OAuthError {}; +ServerError.errorCode = "server_error"; +/** +* Temporarily unavailable error - The authorization server is currently unable to +* handle the request due to a temporary overloading or maintenance of the server. +*/ +var TemporarilyUnavailableError = class extends OAuthError {}; +TemporarilyUnavailableError.errorCode = "temporarily_unavailable"; +/** +* Unsupported response type error - The authorization server does not support +* obtaining an authorization code using this method. +*/ +var UnsupportedResponseTypeError = class extends OAuthError {}; +UnsupportedResponseTypeError.errorCode = "unsupported_response_type"; +/** +* Unsupported token type error - The authorization server does not support +* the requested token type. +*/ +var UnsupportedTokenTypeError = class extends OAuthError {}; +UnsupportedTokenTypeError.errorCode = "unsupported_token_type"; +/** +* Invalid token error - The access token provided is expired, revoked, malformed, +* or invalid for other reasons. +*/ +var InvalidTokenError = class extends OAuthError {}; +InvalidTokenError.errorCode = "invalid_token"; +/** +* Method not allowed error - The HTTP method used is not allowed for this endpoint. +* (Custom, non-standard error) +*/ +var MethodNotAllowedError = class extends OAuthError {}; +MethodNotAllowedError.errorCode = "method_not_allowed"; +/** +* Too many requests error - Rate limit exceeded. +* (Custom, non-standard error based on RFC 6585) +*/ +var TooManyRequestsError = class extends OAuthError {}; +TooManyRequestsError.errorCode = "too_many_requests"; +/** +* Invalid client metadata error - The client metadata is invalid. +* (Custom error for dynamic client registration - RFC 7591) +*/ +var InvalidClientMetadataError = class extends OAuthError {}; +InvalidClientMetadataError.errorCode = "invalid_client_metadata"; +/** +* Insufficient scope error - The request requires higher privileges than provided by the access token. +*/ +var InsufficientScopeError = class extends OAuthError {}; +InsufficientScopeError.errorCode = "insufficient_scope"; +/** +* Invalid target error - The requested resource is invalid, missing, unknown, or malformed. +* (Custom error for resource indicators - RFC 8707) +*/ +var InvalidTargetError = class extends OAuthError {}; +InvalidTargetError.errorCode = "invalid_target"; +/** +* A full list of all OAuthErrors, enabling parsing from error responses +*/ +var OAUTH_ERRORS = { + [InvalidRequestError.errorCode]: InvalidRequestError, + [InvalidClientError.errorCode]: InvalidClientError, + [InvalidGrantError.errorCode]: InvalidGrantError, + [UnauthorizedClientError.errorCode]: UnauthorizedClientError, + [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, + [InvalidScopeError.errorCode]: InvalidScopeError, + [AccessDeniedError.errorCode]: AccessDeniedError, + [ServerError.errorCode]: ServerError, + [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, + [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, + [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, + [InvalidTokenError.errorCode]: InvalidTokenError, + [MethodNotAllowedError.errorCode]: MethodNotAllowedError, + [TooManyRequestsError.errorCode]: TooManyRequestsError, + [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, + [InsufficientScopeError.errorCode]: InsufficientScopeError, + [InvalidTargetError.errorCode]: InvalidTargetError +}; +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js +var UnauthorizedError = class extends Error { + constructor(message) { + super(message ?? "Unauthorized"); + } +}; +function isClientAuthMethod(method) { + return [ + "client_secret_basic", + "client_secret_post", + "none" + ].includes(method); +} +var AUTHORIZATION_CODE_RESPONSE_TYPE = "code"; +var AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256"; +/** +* Determines the best client authentication method to use based on server support and client configuration. +* +* Priority order (highest to lowest): +* 1. client_secret_basic (if client secret is available) +* 2. client_secret_post (if client secret is available) +* 3. none (for public clients) +* +* @param clientInformation - OAuth client information containing credentials +* @param supportedMethods - Authentication methods supported by the authorization server +* @returns The selected authentication method +*/ +function selectClientAuthMethod(clientInformation, supportedMethods) { + const hasClientSecret = clientInformation.client_secret !== void 0; + if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) return clientInformation.token_endpoint_auth_method; + if (supportedMethods.length === 0) return hasClientSecret ? "client_secret_basic" : "none"; + if (hasClientSecret && supportedMethods.includes("client_secret_basic")) return "client_secret_basic"; + if (hasClientSecret && supportedMethods.includes("client_secret_post")) return "client_secret_post"; + if (supportedMethods.includes("none")) return "none"; + return hasClientSecret ? "client_secret_post" : "none"; +} +/** +* Applies client authentication to the request based on the specified method. +* +* Implements OAuth 2.1 client authentication methods: +* - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1) +* - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1) +* - none: Public client authentication (RFC 6749 Section 2.1) +* +* @param method - The authentication method to use +* @param clientInformation - OAuth client information containing credentials +* @param headers - HTTP headers object to modify +* @param params - URL search parameters to modify +* @throws {Error} When required credentials are missing +*/ +function applyClientAuthentication(method, clientInformation, headers, params) { + const { client_id, client_secret } = clientInformation; + switch (method) { + case "client_secret_basic": + applyBasicAuth(client_id, client_secret, headers); + return; + case "client_secret_post": + applyPostAuth(client_id, client_secret, params); + return; + case "none": + applyPublicAuth(client_id, params); + return; + default: throw new Error(`Unsupported client authentication method: ${method}`); + } +} +/** +* Applies HTTP Basic authentication (RFC 6749 Section 2.3.1) +*/ +function applyBasicAuth(clientId, clientSecret, headers) { + if (!clientSecret) throw new Error("client_secret_basic authentication requires a client_secret"); + const credentials = btoa(`${clientId}:${clientSecret}`); + headers.set("Authorization", `Basic ${credentials}`); +} +/** +* Applies POST body authentication (RFC 6749 Section 2.3.1) +*/ +function applyPostAuth(clientId, clientSecret, params) { + params.set("client_id", clientId); + if (clientSecret) params.set("client_secret", clientSecret); +} +/** +* Applies public client authentication (RFC 6749 Section 2.1) +*/ +function applyPublicAuth(clientId, params) { + params.set("client_id", clientId); +} +/** +* Parses an OAuth error response from a string or Response object. +* +* If the input is a standard OAuth2.0 error response, it will be parsed according to the spec +* and an instance of the appropriate OAuthError subclass will be returned. +* If parsing fails, it falls back to a generic ServerError that includes +* the response status (if available) and original content. +* +* @param input - A Response object or string containing the error response +* @returns A Promise that resolves to an OAuthError instance +*/ +async function parseErrorResponse(input) { + const statusCode = input instanceof Response ? input.status : void 0; + const body = input instanceof Response ? await input.text() : input; + try { + const { error, error_description, error_uri } = OAuthErrorResponseSchema.parse(JSON.parse(body)); + return new (OAUTH_ERRORS[error] || ServerError)(error_description || "", error_uri); + } catch (error) { + return new ServerError(`${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`); + } +} +/** +* Orchestrates the full auth flow with a server. +* +* This can be used as a single entry point for all authorization functionality, +* instead of linking together the other lower-level functions in this module. +*/ +async function auth(provider, options) { + try { + return await authInternal(provider, options); + } catch (error) { + if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) { + await provider.invalidateCredentials?.("all"); + return await authInternal(provider, options); + } else if (error instanceof InvalidGrantError) { + await provider.invalidateCredentials?.("tokens"); + return await authInternal(provider, options); + } + throw error; + } +} +async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { + const cachedState = await provider.discoveryState?.(); + let resourceMetadata; + let authorizationServerUrl; + let metadata; + let effectiveResourceMetadataUrl = resourceMetadataUrl; + if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl); + if (cachedState?.authorizationServerUrl) { + authorizationServerUrl = cachedState.authorizationServerUrl; + resourceMetadata = cachedState.resourceMetadata; + metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn }); + if (!resourceMetadata) try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn); + } catch {} + if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) await provider.saveDiscoveryState?.({ + authorizationServerUrl: String(authorizationServerUrl), + resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), + resourceMetadata, + authorizationServerMetadata: metadata + }); + } else { + const serverInfo = await discoverOAuthServerInfo(serverUrl, { + resourceMetadataUrl: effectiveResourceMetadataUrl, + fetchFn + }); + authorizationServerUrl = serverInfo.authorizationServerUrl; + metadata = serverInfo.authorizationServerMetadata; + resourceMetadata = serverInfo.resourceMetadata; + await provider.saveDiscoveryState?.({ + authorizationServerUrl: String(authorizationServerUrl), + resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(), + resourceMetadata, + authorizationServerMetadata: metadata + }); + } + const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); + const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope; + let clientInformation = await Promise.resolve(provider.clientInformation()); + if (!clientInformation) { + if (authorizationCode !== void 0) throw new Error("Existing OAuth client information is required when exchanging an authorization code"); + const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true; + const clientMetadataUrl = provider.clientMetadataUrl; + if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); + if (supportsUrlBasedClientId && clientMetadataUrl) { + clientInformation = { client_id: clientMetadataUrl }; + await provider.saveClientInformation?.(clientInformation); + } else { + if (!provider.saveClientInformation) throw new Error("OAuth client information must be saveable for dynamic registration"); + const fullInformation = await registerClient(authorizationServerUrl, { + metadata, + clientMetadata: provider.clientMetadata, + scope: resolvedScope, + fetchFn + }); + await provider.saveClientInformation(fullInformation); + clientInformation = fullInformation; + } + } + const nonInteractiveFlow = !provider.redirectUrl; + if (authorizationCode !== void 0 || nonInteractiveFlow) { + const tokens = await fetchToken(provider, authorizationServerUrl, { + metadata, + resource, + authorizationCode, + fetchFn + }); + await provider.saveTokens(tokens); + return "AUTHORIZED"; + } + const tokens = await provider.tokens(); + if (tokens?.refresh_token) try { + const newTokens = await refreshAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + refreshToken: tokens.refresh_token, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn + }); + await provider.saveTokens(newTokens); + return "AUTHORIZED"; + } catch (error) { + if (!(error instanceof OAuthError) || error instanceof ServerError) {} else throw error; + } + const state = provider.state ? await provider.state() : void 0; + const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + state, + redirectUrl: provider.redirectUrl, + scope: resolvedScope, + resource + }); + await provider.saveCodeVerifier(codeVerifier); + await provider.redirectToAuthorization(authorizationUrl); + return "REDIRECT"; +} +/** +* SEP-991: URL-based Client IDs +* Validate that the client_id is a valid URL with https scheme +*/ +function isHttpsUrl(value) { + if (!value) return false; + try { + const url = new URL(value); + return url.protocol === "https:" && url.pathname !== "/"; + } catch { + return false; + } +} +async function selectResourceURL(serverUrl, provider, resourceMetadata) { + const defaultResource = resourceUrlFromServerUrl(serverUrl); + if (provider.validateResourceURL) return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource); + if (!resourceMetadata) return; + if (!checkResourceAllowed({ + requestedResource: defaultResource, + configuredResource: resourceMetadata.resource + })) throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); + return new URL(resourceMetadata.resource); +} +/** +* Extract resource_metadata, scope, and error from WWW-Authenticate header. +*/ +function extractWWWAuthenticateParams(res) { + const authenticateHeader = res.headers.get("WWW-Authenticate"); + if (!authenticateHeader) return {}; + const [type, scheme] = authenticateHeader.split(" "); + if (type.toLowerCase() !== "bearer" || !scheme) return {}; + const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0; + let resourceMetadataUrl; + if (resourceMetadataMatch) try { + resourceMetadataUrl = new URL(resourceMetadataMatch); + } catch {} + const scope = extractFieldFromWwwAuth(res, "scope") || void 0; + const error = extractFieldFromWwwAuth(res, "error") || void 0; + return { + resourceMetadataUrl, + scope, + error + }; +} +/** +* Extracts a specific field's value from the WWW-Authenticate header string. +* +* @param response The HTTP response object containing the headers. +* @param fieldName The name of the field to extract (e.g., "realm", "nonce"). +* @returns The field value +*/ +function extractFieldFromWwwAuth(response, fieldName) { + const wwwAuthHeader = response.headers.get("WWW-Authenticate"); + if (!wwwAuthHeader) return null; + const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); + const match = wwwAuthHeader.match(pattern); + if (match) return match[1] || match[2]; + return null; +} +/** +* Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. +* +* If the server returns a 404 for the well-known endpoint, this function will +* return `undefined`. Any other errors will be thrown as exceptions. +*/ +async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { + const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, { + protocolVersion: opts?.protocolVersion, + metadataUrl: opts?.resourceMetadataUrl + }); + if (!response || response.status === 404) { + await response?.body?.cancel(); + throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); + } + if (!response.ok) { + await response.body?.cancel(); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); + } + return OAuthProtectedResourceMetadataSchema.parse(await response.json()); +} +/** +* Helper function to handle fetch with CORS retry logic +*/ +async function fetchWithCorsRetry(url, headers, fetchFn = fetch) { + try { + return await fetchFn(url, { headers }); + } catch (error) { + if (error instanceof TypeError) if (headers) return fetchWithCorsRetry(url, void 0, fetchFn); + else return; + throw error; + } +} +/** +* Constructs the well-known path for auth-related metadata discovery +*/ +function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) { + if (pathname.endsWith("/")) pathname = pathname.slice(0, -1); + return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; +} +/** +* Tries to discover OAuth metadata at a specific URL +*/ +async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) { + return await fetchWithCorsRetry(url, { "MCP-Protocol-Version": protocolVersion }, fetchFn); +} +/** +* Determines if fallback to root discovery should be attempted +*/ +function shouldAttemptFallback(response, pathname) { + return !response || response.status >= 400 && response.status < 500 && pathname !== "/"; +} +/** +* Generic function for discovering OAuth metadata with fallback support +*/ +async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { + const issuer = new URL(serverUrl); + const protocolVersion = opts?.protocolVersion ?? "2025-11-25"; + let url; + if (opts?.metadataUrl) url = new URL(opts.metadataUrl); + else { + const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); + url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer); + url.search = issuer.search; + } + let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn); + if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) response = await tryMetadataDiscovery(new URL(`/.well-known/${wellKnownType}`, issuer), protocolVersion, fetchFn); + return response; +} +/** +* Builds a list of discovery URLs to try for authorization server metadata. +* URLs are returned in priority order: +* 1. OAuth metadata at the given URL +* 2. OIDC metadata endpoints at the given URL +*/ +function buildDiscoveryUrls(authorizationServerUrl) { + const url = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl; + const hasPath = url.pathname !== "/"; + const urlsToTry = []; + if (!hasPath) { + urlsToTry.push({ + url: new URL("/.well-known/oauth-authorization-server", url.origin), + type: "oauth" + }); + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration`, url.origin), + type: "oidc" + }); + return urlsToTry; + } + let pathname = url.pathname; + if (pathname.endsWith("/")) pathname = pathname.slice(0, -1); + urlsToTry.push({ + url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin), + type: "oauth" + }); + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin), + type: "oidc" + }); + urlsToTry.push({ + url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin), + type: "oidc" + }); + return urlsToTry; +} +/** +* Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata +* and OpenID Connect Discovery 1.0 specifications. +* +* This function implements a fallback strategy for authorization server discovery: +* 1. Attempts RFC 8414 OAuth metadata discovery first +* 2. If OAuth discovery fails, falls back to OpenID Connect Discovery +* +* @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's +* protected resource metadata, or the MCP server's URL if the +* metadata was not found. +* @param options - Configuration options +* @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch +* @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION +* @returns Promise resolving to authorization server metadata, or undefined if discovery fails +*/ +async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) { + const headers = { + "MCP-Protocol-Version": protocolVersion, + Accept: "application/json" + }; + const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); + for (const { url: endpointUrl, type } of urlsToTry) { + const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); + if (!response) + /** + * CORS error occurred - don't throw as the endpoint may not allow CORS, + * continue trying other possible endpoints + */ + continue; + if (!response.ok) { + await response.body?.cancel(); + if (response.status >= 400 && response.status < 500) continue; + throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`); + } + if (type === "oauth") return OAuthMetadataSchema.parse(await response.json()); + else return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); + } +} +/** +* Discovers the authorization server for an MCP server following +* {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected +* Resource Metadata), with fallback to treating the server URL as the +* authorization server. +* +* This function combines two discovery steps into one call: +* 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the +* authorization server URL (RFC 9728). +* 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery). +* +* Use this when you need the authorization server metadata for operations outside the +* {@linkcode auth} orchestrator, such as token refresh or token revocation. +* +* @param serverUrl - The MCP resource server URL +* @param opts - Optional configuration +* @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint +* @param opts.fetchFn - Custom fetch function for HTTP requests +* @returns Authorization server URL, metadata, and resource metadata (if available) +*/ +async function discoverOAuthServerInfo(serverUrl, opts) { + let resourceMetadata; + let authorizationServerUrl; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn); + if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) authorizationServerUrl = resourceMetadata.authorization_servers[0]; + } catch {} + if (!authorizationServerUrl) authorizationServerUrl = String(new URL("/", serverUrl)); + const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn }); + return { + authorizationServerUrl, + authorizationServerMetadata, + resourceMetadata + }; +} +/** +* Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. +*/ +async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { + let authorizationUrl; + if (metadata) { + authorizationUrl = new URL(metadata.authorization_endpoint); + if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); + if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); + } else authorizationUrl = new URL("/authorize", authorizationServerUrl); + const challenge = await pkceChallenge(); + const codeVerifier = challenge.code_verifier; + const codeChallenge = challenge.code_challenge; + authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE); + authorizationUrl.searchParams.set("client_id", clientInformation.client_id); + authorizationUrl.searchParams.set("code_challenge", codeChallenge); + authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD); + authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl)); + if (state) authorizationUrl.searchParams.set("state", state); + if (scope) authorizationUrl.searchParams.set("scope", scope); + if (scope?.includes("offline_access")) authorizationUrl.searchParams.append("prompt", "consent"); + if (resource) authorizationUrl.searchParams.set("resource", resource.href); + return { + authorizationUrl, + codeVerifier + }; +} +/** +* Prepares token request parameters for an authorization code exchange. +* +* This is the default implementation used by fetchToken when the provider +* doesn't implement prepareTokenRequest. +* +* @param authorizationCode - The authorization code received from the authorization endpoint +* @param codeVerifier - The PKCE code verifier +* @param redirectUri - The redirect URI used in the authorization request +* @returns URLSearchParams for the authorization_code grant +*/ +function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) { + return new URLSearchParams({ + grant_type: "authorization_code", + code: authorizationCode, + code_verifier: codeVerifier, + redirect_uri: String(redirectUri) + }); +} +/** +* Internal helper to execute a token request with the given parameters. +* Used by exchangeAuthorization, refreshAuthorization, and fetchToken. +*/ +async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) { + const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl); + const headers = new Headers({ + "Content-Type": "application/x-www-form-urlencoded", + Accept: "application/json" + }); + if (resource) tokenRequestParams.set("resource", resource.href); + if (addClientAuthentication) await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata); + else if (clientInformation) applyClientAuthentication(selectClientAuthMethod(clientInformation, metadata?.token_endpoint_auth_methods_supported ?? []), clientInformation, headers, tokenRequestParams); + const response = await (fetchFn ?? fetch)(tokenUrl, { + method: "POST", + headers, + body: tokenRequestParams + }); + if (!response.ok) throw await parseErrorResponse(response); + return OAuthTokensSchema.parse(await response.json()); +} +/** +* Exchange a refresh token for an updated access token. +* +* Supports multiple client authentication methods as specified in OAuth 2.1: +* - Automatically selects the best authentication method based on server support +* - Preserves the original refresh token if a new one is not returned +* +* @param authorizationServerUrl - The authorization server's base URL +* @param options - Configuration object containing client info, refresh token, etc. +* @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) +* @throws {Error} When token refresh fails or authentication is invalid +*/ +async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { + return { + refresh_token: refreshToken, + ...await executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams: new URLSearchParams({ + grant_type: "refresh_token", + refresh_token: refreshToken + }), + clientInformation, + addClientAuthentication, + resource, + fetchFn + }) + }; +} +/** +* Unified token fetching that works with any grant type via provider.prepareTokenRequest(). +* +* This function provides a single entry point for obtaining tokens regardless of the +* OAuth grant type. The provider's prepareTokenRequest() method determines which grant +* to use and supplies the grant-specific parameters. +* +* @param provider - OAuth client provider that implements prepareTokenRequest() +* @param authorizationServerUrl - The authorization server's base URL +* @param options - Configuration for the token request +* @returns Promise resolving to OAuth tokens +* @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails +* +* @example +* // Provider for client_credentials: +* class MyProvider implements OAuthClientProvider { +* prepareTokenRequest(scope) { +* const params = new URLSearchParams({ grant_type: 'client_credentials' }); +* if (scope) params.set('scope', scope); +* return params; +* } +* // ... other methods +* } +* +* const tokens = await fetchToken(provider, authServerUrl, { metadata }); +*/ +async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) { + const scope = provider.clientMetadata.scope; + let tokenRequestParams; + if (provider.prepareTokenRequest) tokenRequestParams = await provider.prepareTokenRequest(scope); + if (!tokenRequestParams) { + if (!authorizationCode) throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required"); + if (!provider.redirectUrl) throw new Error("redirectUrl is required for authorization_code flow"); + tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, await provider.codeVerifier(), provider.redirectUrl); + } + const clientInformation = await provider.clientInformation(); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation: clientInformation ?? void 0, + addClientAuthentication: provider.addClientAuthentication, + resource, + fetchFn + }); +} +/** +* Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. +* +* If `scope` is provided, it overrides `clientMetadata.scope` in the registration +* request body. This allows callers to apply the Scope Selection Strategy (SEP-835) +* consistently across both DCR and the subsequent authorization request. +*/ +async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) { + let registrationUrl; + if (metadata) { + if (!metadata.registration_endpoint) throw new Error("Incompatible auth server: does not support dynamic client registration"); + registrationUrl = new URL(metadata.registration_endpoint); + } else registrationUrl = new URL("/register", authorizationServerUrl); + const response = await (fetchFn ?? fetch)(registrationUrl, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + ...clientMetadata, + ...scope !== void 0 ? { scope } : {} + }) + }); + if (!response.ok) throw await parseErrorResponse(response); + return OAuthClientInformationFullSchema.parse(await response.json()); +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js +var SseError = class extends Error { + constructor(code, message, event) { + super(`SSE error: ${message}`); + this.code = code; + this.event = event; + } +}; +/** +* Client transport for SSE: this will connect to a server using Server-Sent Events for receiving +* messages and make separate POST requests for sending messages. +* @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. +*/ +var SSEClientTransport = class { + constructor(url, opts) { + this._url = url; + this._resourceMetadataUrl = void 0; + this._scope = void 0; + this._eventSourceInit = opts?.eventSourceInit; + this._requestInit = opts?.requestInit; + this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); + } + async _authThenStart() { + if (!this._authProvider) throw new UnauthorizedError("No auth provider"); + let result; + try { + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } catch (error) { + this.onerror?.(error); + throw error; + } + if (result !== "AUTHORIZED") throw new UnauthorizedError(); + return await this._startOrAuth(); + } + async _commonHeaders() { + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) headers["Authorization"] = `Bearer ${tokens.access_token}`; + } + if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion; + const extraHeaders = normalizeHeaders(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + _startOrAuth() { + const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch; + return new Promise((resolve, reject) => { + this._eventSource = new EventSource(this._url.href, { + ...this._eventSourceInit, + fetch: async (url, init) => { + const headers = await this._commonHeaders(); + headers.set("Accept", "text/event-stream"); + const response = await fetchImpl(url, { + ...init, + headers + }); + if (response.status === 401 && response.headers.has("www-authenticate")) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + } + return response; + } + }); + this._abortController = new AbortController(); + this._eventSource.onerror = (event) => { + if (event.code === 401 && this._authProvider) { + this._authThenStart().then(resolve, reject); + return; + } + const error = new SseError(event.code, event.message, event); + reject(error); + this.onerror?.(error); + }; + this._eventSource.onopen = () => {}; + this._eventSource.addEventListener("endpoint", (event) => { + const messageEvent = event; + try { + this._endpoint = new URL(messageEvent.data, this._url); + if (this._endpoint.origin !== this._url.origin) throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); + } catch (error) { + reject(error); + this.onerror?.(error); + this.close(); + return; + } + resolve(); + }); + this._eventSource.onmessage = (event) => { + const messageEvent = event; + let message; + try { + message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); + } catch (error) { + this.onerror?.(error); + return; + } + this.onmessage?.(message); + }; + }); + } + async start() { + if (this._eventSource) throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically."); + return await this._startOrAuth(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) throw new UnauthorizedError("No auth provider"); + if (await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize"); + } + async close() { + this._abortController?.abort(); + this._eventSource?.close(); + this.onclose?.(); + } + async send(message) { + if (!this._endpoint) throw new Error("Not connected"); + try { + const headers = await this._commonHeaders(); + headers.set("content-type", "application/json"); + const init = { + ...this._requestInit, + method: "POST", + headers, + body: JSON.stringify(message), + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._endpoint, init); + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + if (await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }) !== "AUTHORIZED") throw new UnauthorizedError(); + return this.send(message); + } + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + await response.body?.cancel(); + } catch (error) { + this.onerror?.(error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } +}; +/*! +* content-type +* Copyright(c) 2015 Douglas Christopher Wilson +* MIT Licensed +*/ +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js +var import_content_type = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => { + /** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + /** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + /** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.parse = parse; + /** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + function parse(string) { + if (!string) throw new TypeError("argument string is required"); + var header = typeof string === "object" ? getcontenttype(string) : string; + if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); + var index = header.indexOf(";"); + var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); + var obj = new ContentType(type.toLowerCase()); + if (index !== -1) { + var key; + var match; + var value; + PARAM_REGEXP.lastIndex = index; + while (match = PARAM_REGEXP.exec(header)) { + if (match.index !== index) throw new TypeError("invalid parameter format"); + index += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); + } + obj.parameters[key] = value; + } + if (index !== header.length) throw new TypeError("invalid parameter format"); + } + return obj; + } + /** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + function getcontenttype(obj) { + var header; + if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); + else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; + if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); + return header; + } + /** + * Class to represent a content type. + * @private + */ + function ContentType(type) { + this.parameters = Object.create(null); + this.type = type; + } +})))(), 1); +/** +* Extracts the media type (the lowercased `type/subtype` pair, without +* parameters) from a raw `Content-Type` header value, or `undefined` when the +* header is missing or empty. +* +* Content-Type comparisons must use the parsed media type, never a substring +* search of the raw header: a value like `text/plain; a=application/json` +* contains the substring `application/json` but its media type is +* `text/plain`, and case variants or parameters make naive string comparison +* wrong in both directions. +* +* "Essence" is the WHATWG MIME Sniffing standard's term for the bare +* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); +* the Fetch standard's request classification is defined against it +* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). +* +* Parsing is RFC 9110 (`content-type` package) first. When the parameter +* section is malformed (`application/json;`, `application/json; charset=`), +* browsers and most HTTP stacks still derive the media type from the segment +* before the first `;` — the fallback matches that widely-implemented +* behavior, so a header whose media type is unambiguous is not rejected for +* a sloppy parameter section. +*/ +function mediaTypeEssence(header) { + if (!header) return; + try { + return import_content_type.parse(header).type; + } catch { + const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); + if (essence === "" || header.slice(essence.length).includes(",")) return; + return essence; + } +} +//#endregion +//#region node_modules/eventsource-parser/dist/stream.js +var EventSourceParserStream = class extends TransformStream { + constructor({ onError, onRetry, onComment, maxBufferSize } = {}) { + let parser; + super({ + start(controller) { + parser = createParser({ + onEvent: (event) => { + controller.enqueue(event); + }, + onError(error) { + typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error); + }, + onRetry, + onComment, + maxBufferSize + }); + }, + transform(chunk) { + parser.feed(chunk); + } + }); + } +}; +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js +var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { + initialReconnectionDelay: 1e3, + maxReconnectionDelay: 3e4, + reconnectionDelayGrowFactor: 1.5, + maxRetries: 2 +}; +var StreamableHTTPError = class extends Error { + constructor(code, message) { + super(`Streamable HTTP error: ${message}`); + this.code = code; + } +}; +/** +* Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. +* It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events +* for receiving messages. +*/ +var StreamableHTTPClientTransport = class { + constructor(url, opts) { + this._hasCompletedAuthFlow = false; + this._url = url; + this._resourceMetadataUrl = void 0; + this._scope = void 0; + this._requestInit = opts?.requestInit; + this._authProvider = opts?.authProvider; + this._fetch = opts?.fetch; + this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit); + this._sessionId = opts?.sessionId; + this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; + } + async _authThenStart() { + if (!this._authProvider) throw new UnauthorizedError("No auth provider"); + let result; + try { + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } catch (error) { + this.onerror?.(error); + throw error; + } + if (result !== "AUTHORIZED") throw new UnauthorizedError(); + return await this._startOrAuthSse({ resumptionToken: void 0 }); + } + async _commonHeaders() { + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) headers["Authorization"] = `Bearer ${tokens.access_token}`; + } + if (this._sessionId) headers["mcp-session-id"] = this._sessionId; + if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion; + const extraHeaders = normalizeHeaders(this._requestInit?.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + async _startOrAuthSse(options) { + const { resumptionToken } = options; + try { + const headers = await this._commonHeaders(); + headers.set("Accept", "text/event-stream"); + if (resumptionToken) headers.set("last-event-id", resumptionToken); + const response = await (this._fetch ?? fetch)(this._url, { + method: "GET", + headers, + signal: this._abortController?.signal + }); + if (!response.ok) { + await response.body?.cancel(); + if (response.status === 401 && this._authProvider) return await this._authThenStart(); + if (response.status === 405) return; + throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); + } + this._handleSseStream(response.body, options, true); + } catch (error) { + this.onerror?.(error); + throw error; + } + } + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + _getNextReconnectionDelay(attempt) { + if (this._serverRetryMs !== void 0) return this._serverRetryMs; + const initialDelay = this._reconnectionOptions.initialReconnectionDelay; + const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; + const maxDelay = this._reconnectionOptions.maxReconnectionDelay; + return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); + } + /** + * Schedule a reconnection attempt using server-provided retry interval or backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + _scheduleReconnection(options, attemptCount = 0) { + const maxRetries = this._reconnectionOptions.maxRetries; + if (attemptCount >= maxRetries) { + this.onerror?.(/* @__PURE__ */ new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); + return; + } + const delay = this._getNextReconnectionDelay(attemptCount); + this._reconnectionTimeout = setTimeout(() => { + this._startOrAuthSse(options).catch((error) => { + this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)); + this._scheduleReconnection(options, attemptCount + 1); + }); + }, delay); + } + _handleSseStream(stream, options, isReconnectable) { + if (!stream) return; + const { onresumptiontoken, replayMessageId } = options; + let lastEventId; + let hasPrimingEvent = false; + let receivedResponse = false; + const processStream = async () => { + try { + const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({ onRetry: (retryMs) => { + this._serverRetryMs = retryMs; + } })).getReader(); + while (true) { + const { value: event, done } = await reader.read(); + if (done) break; + if (event.id) { + lastEventId = event.id; + hasPrimingEvent = true; + onresumptiontoken?.(event.id); + } + if (!event.data) continue; + if (!event.event || event.event === "message") try { + const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); + if (isJSONRPCResultResponse(message)) { + receivedResponse = true; + if (replayMessageId !== void 0) message.id = replayMessageId; + } + this.onmessage?.(message); + } catch (error) { + this.onerror?.(error); + } + } + if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !this._abortController.signal.aborted) this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`SSE stream disconnected: ${error}`)); + if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !this._abortController.signal.aborted) try { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`)); + } + } + }; + processStream(); + } + async start() { + if (this._abortController) throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically."); + this._abortController = new AbortController(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) throw new UnauthorizedError("No auth provider"); + if (await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize"); + } + async close() { + if (this._reconnectionTimeout) { + clearTimeout(this._reconnectionTimeout); + this._reconnectionTimeout = void 0; + } + this._abortController?.abort(); + this.onclose?.(); + } + async send(message, options) { + try { + const { resumptionToken, onresumptiontoken } = options || {}; + if (resumptionToken) { + this._startOrAuthSse({ + resumptionToken, + replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 + }).catch((err) => this.onerror?.(err)); + return; + } + const headers = await this._commonHeaders(); + headers.set("content-type", "application/json"); + headers.set("accept", "application/json, text/event-stream"); + const init = { + ...this._requestInit, + method: "POST", + headers, + body: JSON.stringify(message), + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + const sessionId = response.headers.get("mcp-session-id"); + if (sessionId) this._sessionId = sessionId; + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + if (this._hasCompletedAuthFlow) throw new StreamableHTTPError(401, "Server returned 401 after successful authentication"); + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + if (await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }) !== "AUTHORIZED") throw new UnauthorizedError(); + this._hasCompletedAuthFlow = true; + return this.send(message); + } + if (response.status === 403 && this._authProvider) { + const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response); + if (error === "insufficient_scope") { + const wwwAuthHeader = response.headers.get("WWW-Authenticate"); + if (this._lastUpscopingHeader === wwwAuthHeader) throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping"); + if (scope) this._scope = scope; + if (resourceMetadataUrl) this._resourceMetadataUrl = resourceMetadataUrl; + this._lastUpscopingHeader = wwwAuthHeader ?? void 0; + if (await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetch + }) !== "AUTHORIZED") throw new UnauthorizedError(); + return this.send(message); + } + } + throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`); + } + this._hasCompletedAuthFlow = false; + this._lastUpscopingHeader = void 0; + if (response.status === 202) { + await response.body?.cancel(); + if (isInitializedNotification(message)) this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err)); + return; + } + const hasRequests = (Array.isArray(message) ? message : [message]).filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0; + const contentType = response.headers.get("content-type"); + const responseMediaType = mediaTypeEssence(contentType); + if (hasRequests) if (responseMediaType === "text/event-stream") this._handleSseStream(response.body, { onresumptiontoken }, false); + else if (responseMediaType === "application/json") { + const data = await response.json(); + const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)]; + for (const msg of responseMessages) this.onmessage?.(msg); + } else { + await response.body?.cancel(); + throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); + } + else await response.body?.cancel(); + } catch (error) { + this.onerror?.(error); + throw error; + } + } + get sessionId() { + return this._sessionId; + } + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + async terminateSession() { + if (!this._sessionId) return; + try { + const headers = await this._commonHeaders(); + const init = { + ...this._requestInit, + method: "DELETE", + headers, + signal: this._abortController?.signal + }; + const response = await (this._fetch ?? fetch)(this._url, init); + await response.body?.cancel(); + if (!response.ok && response.status !== 405) throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); + this._sessionId = void 0; + } catch (error) { + this.onerror?.(error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } + get protocolVersion() { + return this._protocolVersion; + } + /** + * Resume an SSE stream from a previous event ID. + * Opens a GET SSE connection with Last-Event-ID header to replay missed events. + * + * @param lastEventId The event ID to resume from + * @param options Optional callback to receive new resumption tokens + */ + async resumeStream(lastEventId, options) { + await this._startOrAuthSse({ + resumptionToken: lastEventId, + onresumptiontoken: options?.onresumptiontoken + }); + } +}; +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js +function isZ4Schema(s) { + return !!s._zod; +} +function safeParse(schema, data) { + if (isZ4Schema(schema)) return safeParse$1(schema, data); + return schema.safeParse(data); +} +function getObjectShape(schema) { + if (!schema) return void 0; + let rawShape; + if (isZ4Schema(schema)) rawShape = schema._zod?.def?.shape; + else rawShape = schema.shape; + if (!rawShape) return void 0; + if (typeof rawShape === "function") try { + return rawShape(); + } catch { + return; + } + return rawShape; +} +/** +* Gets the literal value from a schema, if it's a literal schema. +* Works with both Zod v3 and v4. +* Returns undefined if the schema is not a literal or the value cannot be determined. +*/ +function getLiteralValue(schema) { + if (isZ4Schema(schema)) { + const def = schema._zod?.def; + if (def) { + if (def.value !== void 0) return def.value; + if (Array.isArray(def.values) && def.values.length > 0) return def.values[0]; + } + } + const def = schema._def; + if (def) { + if (def.value !== void 0) return def.value; + if (Array.isArray(def.values) && def.values.length > 0) return def.values[0]; + } + const directValue = schema.value; + if (directValue !== void 0) return directValue; +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js +/** +* Experimental task interfaces for MCP SDK. +* WARNING: These APIs are experimental and may change without notice. +*/ +/** +* Checks if a task status represents a terminal state. +* Terminal states are those where the task has finished and will not change. +* +* @param status - The task status to check +* @returns True if the status is terminal (completed, failed, or cancelled) +* @experimental +*/ +function isTerminal(status) { + return status === "completed" || status === "failed" || status === "cancelled"; +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js +function getMethodLiteral(schema) { + const methodSchema = getObjectShape(schema)?.method; + if (!methodSchema) throw new Error("Schema is missing a method literal"); + const value = getLiteralValue(methodSchema); + if (typeof value !== "string") throw new Error("Schema method literal must be a string"); + return value; +} +function parseWithCompat(schema, data) { + const result = safeParse(schema, data); + if (!result.success) throw result.error; + return result.data; +} +/** +* Implements MCP protocol framing on top of a pluggable transport, including +* features like request/response linking, notifications, and progress. +*/ +var Protocol = class { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = /* @__PURE__ */ new Map(); + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + this._notificationHandlers = /* @__PURE__ */ new Map(); + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers = /* @__PURE__ */ new Map(); + this._timeoutInfo = /* @__PURE__ */ new Map(); + this._pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + this._taskProgressTokens = /* @__PURE__ */ new Map(); + this._requestResolvers = /* @__PURE__ */ new Map(); + this.setNotificationHandler(CancelledNotificationSchema, (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler(ProgressNotificationSchema, (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler(PingRequestSchema, (_request) => ({})); + this._taskStore = _options?.taskStore; + this._taskMessageQueue = _options?.taskMessageQueue; + if (this._taskStore) { + this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + return { ...task }; + }); + this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { + const handleTaskResult = async () => { + const taskId = request.params.taskId; + if (this._taskMessageQueue) { + let queuedMessage; + while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) { + if (queuedMessage.type === "response" || queuedMessage.type === "error") { + const message = queuedMessage.message; + const requestId = message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + this._requestResolvers.delete(requestId); + if (queuedMessage.type === "response") resolver(message); + else { + const errorMessage = message; + resolver(new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data)); + } + } else { + const messageType = queuedMessage.type === "response" ? "Response" : "Error"; + this._onerror(/* @__PURE__ */ new Error(`${messageType} handler missing for request ${requestId}`)); + } + continue; + } + await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); + } + } + const task = await this._taskStore.getTask(taskId, extra.sessionId); + if (!task) throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); + if (!isTerminal(task.status)) { + await this._waitForTaskUpdate(taskId, extra.signal); + return await handleTaskResult(); + } + if (isTerminal(task.status)) { + const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); + this._clearTaskQueue(taskId); + return { + ...result, + _meta: { + ...result._meta, + [RELATED_TASK_META_KEY]: { taskId } + } + }; + } + return await handleTaskResult(); + }; + return await handleTaskResult(); + }); + this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { + try { + const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); + return { + tasks, + nextCursor, + _meta: {} + }; + } catch (error) { + throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`); + } + }); + this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { + try { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); + if (isTerminal(task.status)) throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); + await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId); + this._clearTaskQueue(request.params.taskId); + const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!cancelledTask) throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); + return { + _meta: {}, + ...cancelledTask + }; + } catch (error) { + if (error instanceof McpError) throw error; + throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`); + } + }); + } + } + async _oncancel(notification) { + if (!notification.params.requestId) return; + this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + if (this._transport) throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection."); + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + _onclose?.(); + this._onclose(); + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) this._onresponse(message); + else if (isJSONRPCRequest(message)) this._onrequest(message, extra); + else if (isJSONRPCNotification(message)) this._onnotification(message); + else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); + }; + await this._transport.start(); + } + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._taskProgressTokens.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); + this._timeoutInfo.clear(); + for (const controller of this._requestHandlerAbortControllers.values()) controller.abort(); + this._requestHandlerAbortControllers.clear(); + const error = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + this.onclose?.(); + for (const handler of responseHandlers.values()) handler(error); + } + _onerror(error) { + this.onerror?.(error); + } + _onnotification(notification) { + const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; + if (handler === void 0) return; + Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(request, extra) { + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + const capturedTransport = this._transport; + const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; + if (handler === void 0) { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: ErrorCode.MethodNotFound, + message: "Method not found" + } + }; + if (relatedTaskId && this._taskMessageQueue) this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to enqueue error response: ${error}`))); + else capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0; + const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0; + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport?.sessionId, + _meta: request.params?._meta, + sendNotification: async (notification) => { + if (abortController.signal.aborted) return; + const notificationOptions = { relatedRequestId: request.id }; + if (relatedTaskId) notificationOptions.relatedTask = { taskId: relatedTaskId }; + await this.notification(notification, notificationOptions); + }, + sendRequest: async (r, resultSchema, options) => { + if (abortController.signal.aborted) throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled"); + const requestOptions = { + ...options, + relatedRequestId: request.id + }; + if (relatedTaskId && !requestOptions.relatedTask) requestOptions.relatedTask = { taskId: relatedTaskId }; + const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; + if (effectiveTaskId && taskStore) await taskStore.updateTaskStatus(effectiveTaskId, "input_required"); + return await this.request(r, resultSchema, requestOptions); + }, + authInfo: extra?.authInfo, + requestId: request.id, + requestInfo: extra?.requestInfo, + taskId: relatedTaskId, + taskStore, + taskRequestedTtl: taskCreationParams?.ttl, + closeSSEStream: extra?.closeSSEStream, + closeStandaloneSSEStream: extra?.closeStandaloneSSEStream + }; + Promise.resolve().then(() => { + if (taskCreationParams) this.assertTaskHandlerCapability(request.method); + }).then(() => handler(request, fullExtra)).then(async (result) => { + if (abortController.signal.aborted) return; + const response = { + result, + jsonrpc: "2.0", + id: request.id + }; + if (relatedTaskId && this._taskMessageQueue) await this._enqueueTaskMessage(relatedTaskId, { + type: "response", + message: response, + timestamp: Date.now() + }, capturedTransport?.sessionId); + else await capturedTransport?.send(response); + }, async (error) => { + if (abortController.signal.aborted) return; + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError, + message: error.message ?? "Internal error", + ...error["data"] !== void 0 && { data: error["data"] } + } + }; + if (relatedTaskId && this._taskMessageQueue) await this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId); + else await capturedTransport?.send(errorResponse); + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { + this._resetTimeout(messageId); + } catch (error) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + handler(params); + } + _onresponse(response) { + const messageId = Number(response.id); + const resolver = this._requestResolvers.get(messageId); + if (resolver) { + this._requestResolvers.delete(messageId); + if (isJSONRPCResultResponse(response)) resolver(response); + else resolver(new McpError(response.error.code, response.error.message, response.error.data)); + return; + } + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + let isTaskResponse = false; + if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") { + const result = response.result; + if (result.task && typeof result.task === "object") { + const task = result.task; + if (typeof task.taskId === "string") { + isTaskResponse = true; + this._taskProgressTokens.set(task.taskId, messageId); + } + } + } + if (!isTaskResponse) this._progressHandlers.delete(messageId); + if (isJSONRPCResultResponse(response)) handler(response); + else handler(McpError.fromError(response.error.code, response.error.message, response.error.data)); + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. + */ + async *requestStream(request, resultSchema, options) { + const { task } = options ?? {}; + if (!task) { + try { + yield { + type: "result", + result: await this.request(request, resultSchema, options) + }; + } catch (error) { + yield { + type: "error", + error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) + }; + } + return; + } + let taskId; + try { + const createResult = await this.request(request, CreateTaskResultSchema, options); + if (createResult.task) { + taskId = createResult.task.taskId; + yield { + type: "taskCreated", + task: createResult.task + }; + } else throw new McpError(ErrorCode.InternalError, "Task creation did not return a task"); + while (true) { + const task = await this.getTask({ taskId }, options); + yield { + type: "taskStatus", + task + }; + if (isTerminal(task.status)) { + if (task.status === "completed") yield { + type: "result", + result: await this.getTaskResult({ taskId }, resultSchema, options) + }; + else if (task.status === "failed") yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) + }; + else if (task.status === "cancelled") yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) + }; + return; + } + if (task.status === "input_required") { + yield { + type: "result", + result: await this.getTaskResult({ taskId }, resultSchema, options) + }; + return; + } + const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3; + await new Promise((resolve) => setTimeout(resolve, pollInterval)); + options?.signal?.throwIfAborted(); + } + } catch (error) { + yield { + type: "error", + error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) + }; + } + } + /** + * Sends a request and waits for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(/* @__PURE__ */ new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) try { + this.assertCapabilityForMethod(request.method); + if (task) this.assertTaskCapability(request.method); + } catch (e) { + earlyReject(e); + return; + } + options?.signal?.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta || {}, + progressToken: messageId + } + }; + } + if (task) jsonrpcRequest.params = { + ...jsonrpcRequest.params, + task + }; + if (relatedTask) jsonrpcRequest.params = { + ...jsonrpcRequest.params, + _meta: { + ...jsonrpcRequest.params?._meta || {}, + [RELATED_TASK_META_KEY]: relatedTask + } + }; + const cancel = (reason) => { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._transport?.send({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }, { + relatedRequestId, + resumptionToken, + onresumptiontoken + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); + reject(reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason))); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) return; + if (response instanceof Error) return reject(response); + try { + const parseResult = safeParse(resultSchema, response.result); + if (!parseResult.success) reject(parseResult.error); + else resolve(parseResult.data); + } catch (error) { + reject(error); + } + }); + options?.signal?.addEventListener("abort", () => { + cancel(options?.signal?.reason); + }); + const timeout = options?.timeout ?? 6e4; + const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + const relatedTaskId = relatedTask?.taskId; + if (relatedTaskId) { + const responseResolver = (response) => { + const handler = this._responseHandlers.get(messageId); + if (handler) handler(response); + else this._onerror(/* @__PURE__ */ new Error(`Response handler missing for side-channeled request ${messageId}`)); + }; + this._requestResolvers.set(messageId, responseResolver); + this._enqueueTaskMessage(relatedTaskId, { + type: "request", + message: jsonrpcRequest, + timestamp: Date.now() + }).catch((error) => { + this._cleanupTimeout(messageId); + reject(error); + }); + } else this._transport.send(jsonrpcRequest, { + relatedRequestId, + resumptionToken, + onresumptiontoken + }).catch((error) => { + this._cleanupTimeout(messageId); + reject(error); + }); + }); + } + /** + * Gets the current status of a task. + * + * @experimental Use `client.experimental.tasks.getTask()` to access this method. + */ + async getTask(params, options) { + return this.request({ + method: "tasks/get", + params + }, GetTaskResultSchema, options); + } + /** + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. + */ + async getTaskResult(params, resultSchema, options) { + return this.request({ + method: "tasks/result", + params + }, resultSchema, options); + } + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. + */ + async listTasks(params, options) { + return this.request({ + method: "tasks/list", + params + }, ListTasksResultSchema, options); + } + /** + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. + */ + async cancelTask(params, options) { + return this.request({ + method: "tasks/cancel", + params + }, CancelTaskResultSchema, options); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + if (!this._transport) throw new Error("Not connected"); + this.assertNotificationCapability(notification.method); + const relatedTaskId = options?.relatedTask?.taskId; + if (relatedTaskId) { + const jsonrpcNotification = { + ...notification, + jsonrpc: "2.0", + params: { + ...notification.params, + _meta: { + ...notification.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + await this._enqueueTaskMessage(relatedTaskId, { + type: "notification", + message: jsonrpcNotification, + timestamp: Date.now() + }); + return; + } + if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask) { + if (this._pendingDebouncedNotifications.has(notification.method)) return; + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) return; + let jsonrpcNotification = { + ...notification, + jsonrpc: "2.0" + }; + if (options?.relatedTask) jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...jsonrpcNotification.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); + }); + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: "2.0" + }; + if (options?.relatedTask) jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...jsonrpcNotification.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + await this._transport.send(jsonrpcNotification, options); + } + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema, handler) { + const method = getMethodLiteral(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = parseWithCompat(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema, handler) { + const method = getMethodLiteral(notificationSchema); + this._notificationHandlers.set(method, (notification) => { + const parsed = parseWithCompat(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } + /** + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. + */ + _cleanupTaskProgressHandler(taskId) { + const progressToken = this._taskProgressTokens.get(taskId); + if (progressToken !== void 0) { + this._progressHandlers.delete(progressToken); + this._taskProgressTokens.delete(taskId); + } + } + /** + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. + */ + async _enqueueTaskMessage(taskId, message, sessionId) { + if (!this._taskStore || !this._taskMessageQueue) throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured"); + const maxQueueSize = this._options?.maxTaskQueueSize; + await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); + } + /** + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session + */ + async _clearTaskQueue(taskId, sessionId) { + if (this._taskMessageQueue) { + const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); + for (const message of messages) if (message.type === "request" && isJSONRPCRequest(message.message)) { + const requestId = message.message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed")); + this._requestResolvers.delete(requestId); + } else this._onerror(/* @__PURE__ */ new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); + } + } + } + /** + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @returns Promise that resolves when an update occurs or rejects if aborted + */ + async _waitForTaskUpdate(taskId, signal) { + let interval = this._options?.defaultTaskPollInterval ?? 1e3; + try { + const task = await this._taskStore?.getTask(taskId); + if (task?.pollInterval) interval = task.pollInterval; + } catch {} + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + return; + } + const timeoutId = setTimeout(resolve, interval); + signal.addEventListener("abort", () => { + clearTimeout(timeoutId); + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + }, { once: true }); + }); + } + requestTaskStore(request, sessionId) { + const taskStore = this._taskStore; + if (!taskStore) throw new Error("No task store configured"); + return { + createTask: async (taskParams) => { + if (!request) throw new Error("No request provided"); + return await taskStore.createTask(taskParams, request.id, { + method: request.method, + params: request.params + }, sessionId); + }, + getTask: async (taskId) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + return task; + }, + storeTaskResult: async (taskId, status, result) => { + await taskStore.storeTaskResult(taskId, status, result, sessionId); + const task = await taskStore.getTask(taskId, sessionId); + if (task) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: task + }); + await this.notification(notification); + if (isTerminal(task.status)) this._cleanupTaskProgressHandler(taskId); + } + }, + getTaskResult: (taskId) => { + return taskStore.getTaskResult(taskId, sessionId); + }, + updateTaskStatus: async (taskId, status, statusMessage) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); + if (isTerminal(task.status)) throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); + await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); + const updatedTask = await taskStore.getTask(taskId, sessionId); + if (updatedTask) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: updatedTask + }); + await this.notification(notification); + if (isTerminal(updatedTask.status)) this._cleanupTaskProgressHandler(taskId); + } + }, + listTasks: (cursor) => { + return taskStore.listTasks(cursor, sessionId); + } + }; + } +}; +function isPlainObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) continue; + const baseValue = result[k]; + if (isPlainObject(baseValue) && isPlainObject(addValue)) result[k] = { + ...baseValue, + ...addValue + }; + else result[k] = addValue; + } + return result; +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/code.js +var require_code$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class {}; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + const item = this._items[0]; + return item === "" || item === "\"\""; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + var plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) code.push(...arg._items); + else if (arg instanceof Name) code.push(arg); + else code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === "\"\"") return a; + if (a === "\"\"") return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== "\"") return; + if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; + if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code$3(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + return this._names[prefix] = { + prefix, + index: 0 + }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + var line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { + ...opts, + _n: opts.lines ? line : code_1.nil + }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) return _name; + } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { + property: prefix, + itemIndex + }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; + else throw new ValueError(name); + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code$3(); + var scope_1 = require_scope$1(); + var code_2 = require_code$3(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return code_2._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return code_2.str; + } + }); + Object.defineProperty(exports, "strConcat", { + enumerable: true, + get: function() { + return code_2.strConcat; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return code_2.nil; + } + }); + Object.defineProperty(exports, "getProperty", { + enumerable: true, + get: function() { + return code_2.getProperty; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return code_2.stringify; + } + }); + Object.defineProperty(exports, "regexpCode", { + enumerable: true, + get: function() { + return code_2.regexpCode; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return code_2.Name; + } + }); + var scope_2 = require_scope$1(); + Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function() { + return scope_2.Scope; + } + }); + Object.defineProperty(exports, "ValueScope", { + enumerable: true, + get: function() { + return scope_2.ValueScope; + } + }); + Object.defineProperty(exports, "ValueScopeName", { + enumerable: true, + get: function() { + return scope_2.ValueScopeName; + } + }); + Object.defineProperty(exports, "varKinds", { + enumerable: true, + get: function() { + return scope_2.varKinds; + } + }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) return; + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `break${this.label ? ` ${this.label}` : ""};` + _n; + } + }; + var Throw = class extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) nodes.splice(i, 1, ...n); + else if (n) nodes[i] = n; + else nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode {}; + var Else = class extends BlockNode {}; + Else.kind = "else"; + var If = class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes; + if (this.nodes.length) return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode {}; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + return addExprNames(addExprNames(super.names, this.from), this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) code += this.catch.render(opts); + if (this.finally) code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) addNames(names, this.catch.names); + if (this.finally) addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { + ...opts, + _n: opts.lines ? "\n" : "" + }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + name(prefix) { + return this._scope.name(prefix); + } + scopeName(prefix) { + return this._extScope.name(prefix); + } + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + code(c) { + if (typeof c == "function") c(); + else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); + return this; + } + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); + else if (thenBody) this.code(thenBody).endIf(); + else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); + return this; + } + elseIf(condition) { + return this._elseNode(new If(condition)); + } + else() { + return this._elseNode(new Else()); + } + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) this.code(forBody).endFor(); + return this; + } + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + endFor() { + return this._endBlockNode(For); + } + label(label) { + return this._leafNode(new Label(label)); + } + break(label) { + return this._leafNode(new Break(label)); + } + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); + return this._endBlockNode(Return); + } + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error) { + return this._leafNode(new Throw(error)); + } + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) this.code(body).endBlock(nodeCount); + return this; + } + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + this._nodes.length = len; + return this; + } + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) this.code(funcBody).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) return replaceName(expr); + if (!canOptimize(expr)) return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) c = replaceName(c); + if (c instanceof code_1._Code) items.push(...c._items); + else items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + var andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + var orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/util.js +var require_util$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen$1(); + var code_1 = require_code$3(); + function toHash(arr) { + const hash = {}; + for (const item of arr) hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") return schema; + if (Object.keys(schema).length === 0) return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) return; + if (typeof schema === "boolean") return; + const rules = self.RULES.keywords; + for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (rules[key]) return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema; + if (typeof schema == "string") return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) for (const x of xs) f(x); + else f(xs); + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) gen.assign(to, true); + else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { + ...from, + ...to + }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) return; + msg = `strict mode: ${msg}`; + if (mode === true) throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/names.js +var require_names$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + exports.default = { + data: new codegen_1.Name("data"), + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/errors.js +var require_errors$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var names_1 = require_names$1(); + exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; + exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); + else returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error, errorPaths)); + if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + /* istanbul ignore if */ + if (errsCount === void 0) throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + var E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + if (propertyName) keyValues.push([E.propertyName, propertyName]); + } +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors$1(); + var codegen_1 = require_codegen$1(); + var names_1 = require_names$1(); + var boolError = { message: "boolean schema is false" }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) falseSchemaError(it, false); + else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else gen.var(valid, true); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/rules.js +var require_rules$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var jsonTypes = /* @__PURE__ */ new Set([ + "string", + "number", + "integer", + "boolean", + "null", + "object", + "array" + ]); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { + type: "number", + rules: [] + }, + string: { + type: "string", + rules: [] + }, + array: { + type: "array", + rules: [] + }, + object: { + type: "object", + rules: [] + } + }; + return { + types: { + ...groups, + integer: true, + boolean: true, + null: true + }, + rules: [ + { rules: [] }, + groups.number, + groups.string, + groups.array, + groups.object + ], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules$1(); + var applicability_1 = require_applicability$1(); + var errors_1 = require_errors$1(); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var DataType; + (function(DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + if (types.includes("null")) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); + if (schema.nullable === true) types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo); + else reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set([ + "string", + "number", + "integer", + "boolean", + "null" + ]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else cond = codegen_1.nil; + if (types.number) delete types.integer; + for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); + else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/code.js +var require_code$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var names_1 = require_names$1(); + var util_2 = require_util$1(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen$1(); + var names_1 = require_names$1(); + var code_1 = require_code$2(); + var errors_1 = require_errors$1(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a; + gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { + ref: result, + code: (0, codegen_1.stringify)(result) + }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + if (def.validateSchema) { + if (!def.validateSchema(schema[keyword])) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") self.logger.error(msg); + else throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error("either \"keyword\" or \"schema\" must be passed"); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); + if (propertyName !== void 0) subschema.propertyName = propertyName; + } + if (dataTypes) subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) subschema.compositeRule = compositeRule; + if (createErrors !== void 0) subschema.createErrors = createErrors; + if (allErrors !== void 0) subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; +})); +//#endregion +//#region node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0;) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: 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 + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/resolve.js +var require_resolve$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util$1(); + var equal = require_fast_deep_equal(); + var traverse = require_json_schema_traverse$1(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") return true; + if (limit === true) return !hasRef(schema); + if (!limit) return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) return true; + if (typeof sch == "object" && hasRef(sch)) return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) continue; + if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + if (count === Infinity) return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) id = normalizeId(id); + return _getFullPath(resolver, resolver.parse(id)); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + return resolver.serialize(p).split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); + else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else this.refs[ref] = fullPath; + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); + } + function ambiguos(ref) { + return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/index.js +var require_validate$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema$1(); + var dataType_1 = require_dataType$1(); + var applicability_1 = require_applicability$1(); + var dataType_2 = require_dataType$1(); + var defaults_1 = require_defaults$1(); + var keyword_1 = require_keyword$1(); + var subschema_1 = require_subschema$1(); + var codegen_1 = require_codegen$1(); + var names_1 = require_names$1(); + var resolve_1 = require_resolve$1(); + var util_1 = require_util$1(); + var errors_1 = require_errors$1(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (self.RULES.all[key]) return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else iterateKeywords(it, group); + if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); + else if (withTypes.includes("integer") && t === "number") ts.push("integer"); + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) failAction(); + else this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(condition) { + if (!this.$data) return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) Object.assign(this.params, obj); + else this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { + ...this.it, + ...subschema, + items: void 0, + props: void 0 + }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; + if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) def.code(cxt, ruleType); + else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); + else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve$1(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/index.js +var require_compile$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen$1(); + var validation_error_1 = require_validation_error$1(); + var names_1 = require_names$1(); + var resolve_1 = require_resolve$1(); + var util_1 = require_util$1(); + var validate_1 = require_validate$1(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { + es5, + lines, + ownProperties + }); + let _ValidationError; + if (sch.$async) _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { + ref: sch.schema, + code: (0, codegen_1.stringify)(sch.schema) + } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); + const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) validate.$async = true; + if (this.opts.code.source === true) validate.source = { + validateName, + validateCode, + scopeValues: gen._values + }; + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema) _sch = new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + if (_sch === void 0) return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; + if (!schOrRef.validate) compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + if (env.schema !== env.root.schema) return env; + } +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/data.json +var data_exports$1 = /* @__PURE__ */ __exportAll({ + $id: () => $id$3, + additionalProperties: () => false, + default: () => data_default$1, + description: () => description$1, + properties: () => properties$3, + required: () => required$1, + type: () => type$3 +}), $id$3, description$1, type$3, required$1, properties$3, data_default$1; +var init_data$1 = __esmMin((() => { + $id$3 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"; + description$1 = "Meta-schema for $data reference (JSON AnySchema extension proposal)"; + type$3 = "object"; + required$1 = ["$data"]; + properties$3 = { "$data": { + "type": "string", + "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] + } }; + data_default$1 = { + $id: $id$3, + description: description$1, + type: type$3, + required: required$1, + properties: properties$3, + additionalProperties: false + }; +})); +//#endregion +//#region node_modules/fast-uri/lib/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** @type {(value: string) => boolean} */ + var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + /** @type {(value: string) => boolean} */ + var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + /** @type {(value: string) => boolean} */ + var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu); + /** @type {(value: string) => boolean} */ + var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu); + /** @type {(value: string) => boolean} */ + var isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu); + /** + * @param {Array} input + * @returns {string} + */ + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) continue; + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + } + return acc; + } + /** + * @typedef {Object} GetIPV6Result + * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. + * @property {string} address - The parsed IPv6 address. + * @property {string} [zone] - The zone identifier, if present. + */ + /** + * @param {string} value + * @returns {boolean} + */ + var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + /** + * @param {Array} buffer + * @returns {boolean} + */ + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + /** + * @param {Array} buffer + * @param {Array} address + * @param {GetIPV6Result} output + * @returns {boolean} + */ + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex = stringArrayToHexStripped(buffer); + if (hex !== "") address.push(hex); + else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + /** + * @param {string} input + * @returns {GetIPV6Result} + */ + function getIPV6(input) { + let tokenCount = 0; + const output = { + error: false, + address: "", + zone: "" + }; + /** @type {Array} */ + const address = []; + /** @type {Array} */ + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i = 0; i < input.length; i++) { + const cursor = input[i]; + if (cursor === "[" || cursor === "]") continue; + if (cursor === ":") { + if (endipv6Encountered === true) endIpv6 = true; + if (!consume(buffer, address, output)) break; + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) break; + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); + else if (endIpv6) address.push(buffer.join("")); + else address.push(stringArrayToHexStripped(buffer)); + output.address = address.join(""); + return output; + } + /** + * @typedef {Object} NormalizeIPv6Result + * @property {string} host - The normalized host. + * @property {string} [escapedHost] - The escaped host. + * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. + */ + /** + * @param {string} host + * @returns {NormalizeIPv6Result} + */ + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) return { + host, + isIPV6: false + }; + const ipv6 = getIPV6(host); + if (!ipv6.error) { + let newHost = ipv6.address; + let escapedHost = ipv6.address; + if (ipv6.zone) { + newHost += "%" + ipv6.zone; + escapedHost += "%25" + ipv6.zone; + } + return { + host: newHost, + isIPV6: true, + escapedHost + }; + } else return { + host, + isIPV6: false + }; + } + /** + * @param {string} str + * @param {string} token + * @returns {number} + */ + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; + return ind; + } + /** + * @param {string} path + * @returns {string} + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) if (input === ".") break; + else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") break; + else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) output.pop(); + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) output.pop(); + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + /** + * Re-escape RFC 3986 gen-delims that must not appear literally in the host. + * After the URI regex parses, these characters cannot be literal in the host + * field, so any that appear after decoding came from percent-encoding and + * must be restored to prevent authority structure changes. + * + * @param {string} host + * @param {boolean} isIP - true for IPv4/IPv6 hosts (skip colon re-escaping) + * @returns {string} + */ + var HOST_DELIMS = { + "@": "%40", + "/": "%2F", + "?": "%3F", + "#": "%23", + ":": "%3A" + }; + var HOST_DELIM_RE = /[@/?#:]/g; + var HOST_DELIM_NO_COLON_RE = /[@/?#]/g; + function reescapeHostDelimiters(host, isIP) { + const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE; + re.lastIndex = 0; + return host.replace(re, (ch) => HOST_DELIMS[ch]); + } + /** + * Normalizes percent escapes and optionally decodes only unreserved ASCII bytes. + * Reserved delimiters such as `%2F` and `%2E` stay escaped. + * + * @param {string} input + * @param {boolean} [decodeUnreserved=false] + * @returns {string} + */ + function normalizePercentEncoding(input, decodeUnreserved = false) { + if (input.indexOf("%") === -1) return input; + let output = ""; + for (let i = 0; i < input.length; i++) { + if (input[i] === "%" && i + 2 < input.length) { + const hex = input.slice(i + 1, i + 3); + if (isHexPair(hex)) { + const normalizedHex = hex.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (decodeUnreserved && isUnreserved(decoded)) output += decoded; + else output += "%" + normalizedHex; + i += 2; + continue; + } + } + output += input[i]; + } + return output; + } + /** + * Normalizes path data without turning reserved escapes into live path syntax. + * Valid escapes are uppercased, raw unsafe characters are escaped, and only + * unreserved bytes that are not `.` are decoded. + * + * @param {string} input + * @returns {string} + */ + function normalizePathEncoding(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + if (input[i] === "%" && i + 2 < input.length) { + const hex = input.slice(i + 1, i + 3); + if (isHexPair(hex)) { + const normalizedHex = hex.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (decoded !== "." && isUnreserved(decoded)) output += decoded; + else output += "%" + normalizedHex; + i += 2; + continue; + } + } + if (isPathCharacter(input[i])) output += input[i]; + else output += escape(input[i]); + } + return output; + } + /** + * Escapes a component while preserving existing valid percent escapes. + * + * @param {string} input + * @returns {string} + */ + function escapePreservingEscapes(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + if (input[i] === "%" && i + 2 < input.length) { + const hex = input.slice(i + 1, i + 3); + if (isHexPair(hex)) { + output += "%" + hex.toUpperCase(); + i += 2; + continue; + } + } + output += escape(input[i]); + } + return output; + } + /** + * @param {import('../types/index').URIComponent} component + * @returns {string|undefined} + */ + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; + else host = reescapeHostDelimiters(host, false); + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + reescapeHostDelimiters, + normalizePercentEncoding, + normalizePathEncoding, + escapePreservingEscapes, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; +})); +//#endregion +//#region node_modules/fast-uri/lib/schemes.js +var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var { isUUID } = require_utils(); + var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + var supportedSchemeNames = [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ]; + /** @typedef {supportedSchemeNames[number]} SchemeName */ + /** + * @param {string} name + * @returns {name is SchemeName} + */ + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf(name) !== -1; + } + /** + * @callback SchemeFn + * @param {import('../types/index').URIComponent} component + * @param {import('../types/index').Options} options + * @returns {import('../types/index').URIComponent} + */ + /** + * @typedef {Object} SchemeHandler + * @property {SchemeName} scheme - The scheme name. + * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. + * @property {SchemeFn} parse - Function to parse the URI component for this scheme. + * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. + * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. + * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. + * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. + */ + /** + * @param {import('../types/index').URIComponent} wsComponent + * @returns {boolean} + */ + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) return true; + else if (wsComponent.secure === false) return false; + else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + else return false; + } + /** @type {SchemeFn} */ + function httpParse(component) { + if (!component.host) component.error = component.error || "HTTP URIs must have a host."; + return component; + } + /** @type {SchemeFn} */ + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; + if (!component.path) component.path = "/"; + return component; + } + /** @type {SchemeFn} */ + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); + urnComponent.path = void 0; + if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); + } else urnComponent.error = urnComponent.error || "URN can not be parsed."; + return urnComponent; + } + /** @type {SchemeFn} */ + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); + if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + /** @type {SchemeFn} */ + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; + return uuidComponent; + } + /** @type {SchemeFn} */ + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + var http = { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + }; + var https = { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + }; + var ws = { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + }; + var SCHEMES = { + http, + https, + ws, + wss: { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + }, + urn: { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + }, + "urn:uuid": { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + } + }; + Object.setPrototypeOf(SCHEMES, null); + /** + * @param {string|undefined} scheme + * @returns {SchemeHandler|undefined} + */ + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; +})); +//#endregion +//#region node_modules/fast-uri/index.js +var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils(); + var { SCHEMES, getSchemeHandler } = require_schemes(); + /** + * @template {import('./types/index').URIComponent|string} T + * @param {T} uri + * @param {import('./types/index').Options} [options] + * @returns {T} + */ + function normalize(uri, options) { + if (typeof uri === "string") uri = normalizeString(uri, options); + else if (typeof uri === "object") uri = parse(serialize(uri, options), options); + return uri; + } + /** + * @param {string} baseURI + * @param {string} relativeURI + * @param {import('./types/index').Options} [options] + * @returns {string} + */ + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed } = parseWithStatus(baseURI, schemelessOptions); + const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed } = parseWithStatus(relativeURI, schemelessOptions); + if (baseMalformed || relativeMalformed) throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed."); + const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + /** + * @param {import ('./types/index').URIComponent} base + * @param {import ('./types/index').URIComponent} relative + * @param {import('./types/index').Options} [options] + * @param {boolean} [skipNormalization=false] + * @returns {import ('./types/index').URIComponent} + */ + function resolveComponent(base, relative, options, skipNormalization) { + /** @type {import('./types/index').URIComponent} */ + const target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); + relative = parse(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) target.query = relative.query; + else target.query = base.query; + } else { + if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); + else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; + else if (!base.path) target.path = relative.path; + else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + /** + * @param {import ('./types/index').URIComponent|string} uriA + * @param {import ('./types/index').URIComponent|string} uriB + * @param {import ('./types/index').Options} options + * @returns {boolean} + */ + function equal(uriA, uriB, options) { + const normalizedA = normalizeComparableURI(uriA, options); + const normalizedB = normalizeComparableURI(uriB, options); + return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA.toLowerCase() === normalizedB.toLowerCase(); + } + /** + * @param {Readonly} cmpts + * @param {import('./types/index').Options} [opts] + * @returns {string} + */ + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) if (!options.skipEscape) { + component.path = escapePreservingEscapes(component.path); + if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); + } else component.path = normalizePercentEncoding(component.path); + if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") uriTokens.push("//"); + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") uriTokens.push("/"); + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); + if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); + uriTokens.push(s); + } + if (component.query !== void 0) uriTokens.push("?", component.query); + if (component.fragment !== void 0) uriTokens.push("#", component.fragment); + return uriTokens.join(""); + } + var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/; + var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/; + /** + * @param {import('./types/index').URIComponent} parsed + * @param {RegExpMatchArray} matches + * @returns {string|undefined} + */ + function getParseError(parsed, matches) { + if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") return "URI path must start with \"/\" when authority is present."; + if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) return "URI port is malformed."; + } + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns {{ parsed: import('./types/index').URIComponent, malformedAuthorityOrPort: boolean }} + */ + function parseWithStatus(uri, opts) { + const options = Object.assign({}, opts); + /** @type {import('./types/index').URIComponent} */ + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let malformedAuthorityOrPort = false; + let isIP = false; + if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; + else uri = "//" + uri; + const authorityMatch = uri.match(AUTHORITY_PREFIX); + if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) { + parsed.error = "URI authority must not contain a literal backslash."; + malformedAuthorityOrPort = true; + } + const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION); + if (introducerMatch !== null) { + const region = introducerMatch[1]; + const normalizedRegion = region.replace(/[\t\n\r]/g, ""); + if (normalizedRegion.length >= 2) { + if (normalizedRegion.slice(0, 2) !== "//") { + parsed.error = parsed.error || "URI authority must not contain a literal backslash."; + malformedAuthorityOrPort = true; + } else if (region.length !== normalizedRegion.length) { + parsed.error = parsed.error || "URI authority introducer must not contain whitespace."; + malformedAuthorityOrPort = true; + } + } + } + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) parsed.port = matches[5]; + const parseError = getParseError(parsed, matches); + if (parseError !== void 0) { + parsed.error = parsed.error || parseError; + malformedAuthorityOrPort = true; + } + if (parsed.host) if (isIPv4(parsed.host) === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else isIP = true; + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; + else if (parsed.scheme === void 0) parsed.reference = "relative"; + else if (parsed.fragment === void 0) parsed.reference = "absolute"; + else parsed.reference = "uri"; + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { + parsed.host = new URL("http://" + parsed.host).hostname; + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); + if (parsed.host !== void 0) parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP); + } + if (parsed.path) parsed.path = normalizePathEncoding(parsed.path); + if (parsed.fragment) try { + parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } catch { + parsed.error = parsed.error || "URI malformed"; + } + } + if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); + } else parsed.error = parsed.error || "URI can not be parsed."; + return { + parsed, + malformedAuthorityOrPort + }; + } + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns + */ + function parse(uri, opts) { + return parseWithStatus(uri, opts).parsed; + } + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns {string} + */ + function normalizeString(uri, opts) { + return normalizeStringWithStatus(uri, opts).normalized; + } + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns {{ normalized: string, malformedAuthorityOrPort: boolean }} + */ + function normalizeStringWithStatus(uri, opts) { + const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts); + return { + normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts), + malformedAuthorityOrPort + }; + } + /** + * @param {import ('./types/index').URIComponent|string} uri + * @param {import('./types/index').Options} [opts] + * @returns {string|undefined} + */ + function normalizeComparableURI(uri, opts) { + if (typeof uri === "string") { + const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts); + return malformedAuthorityOrPort ? void 0 : normalized; + } + if (typeof uri === "object") return serialize(uri, opts); + } + var fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/uri.js +var require_uri$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var uri = require_fast_uri(); + uri.code = "require(\"ajv/dist/runtime/uri\").default"; + exports.default = uri; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/core.js +var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate$1(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error$1(); + var ref_error_1 = require_ref_error$1(); + var rules_1 = require_rules$1(); + var compile_1 = require_compile$1(); + var codegen_2 = require_codegen$1(); + var resolve_1 = require_resolve$1(); + var dataType_1 = require_dataType$1(); + var util_1 = require_util$1(); + var $dataRefSchema = (init_data$1(), __toCommonJS(data_exports$1).default); + var uri_1 = require_uri$1(); + var defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = [ + "removeAdditional", + "useDefaults", + "coerceTypes" + ]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: "\"nullable\" keyword is supported by default.", + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: "\"uniqueItems\" keyword is always validated.", + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." + }; + var MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { + ...o.code, + optimize, + regExp + } : { + optimize, + regExp + }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = Object.create(null); + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { + ...opts, + ...requiredOptions(opts) + }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ + scope: {}, + prefixes: EXT_SCOPE_NAMES, + es5, + lines + }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else v = this.compile(schemaKeyRef); + const valid = v(data); + if (!("$async" in v)) this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message); + else throw new Error(message); + } + return valid; + } + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ + schema: {}, + schemaId + }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: throw new Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(definitions) { + for (const def of definitions) this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); + } else throw new Error("invalid addKeywords parameters"); + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) group.rules.splice(i, 1); + } + return this; + } + addFormat(name, format) { + if (typeof format == "string") format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") delete schemas[keyRef]; + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") id = schema[schemaId]; + else if (this.opts.jtd) throw new Error("schema must be object"); + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); + let sch = this._cache.get(schema); + if (sch !== void 0) return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ + schema, + schemaId, + meta, + baseId, + localRefs + }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); + } + _compileSchemaEnv(sch) { + if (sch.meta) this._compileMetaSchema(sch); + else compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + exports.default = Ajv; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); + else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { + log() {}, + warn() {}, + error() {} + }; + function getLogger(logger) { + if (logger === false) return noLogs; + if (logger === void 0) return console; + if (logger.log && logger.warn && logger.error) return logger; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) return; + if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); + else ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) ruleGroup.rules.splice(i, 0, rule); + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) return; + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/id.js +var require_id$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = { + keyword: "id", + code() { + throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error$1(); + var code_1 = require_code$2(); + var codegen_1 = require_codegen$1(); + var names_1 = require_names$1(); + var compile_1 = require_compile$1(); + var util_1 = require_util$1(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + callRef(cxt, getValidate(cxt, sch), sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { + ref: sch, + code: (0, codegen_1.stringify)(sch) + } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) callAsyncRef(); + else callSyncRef(); + function callAsyncRef() { + if (!env.$async) throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + exports.callRef = callRef; + exports.default = def; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/index.js +var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var id_1 = require_id$1(); + var ref_1 = require_ref$1(); + exports.default = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + minimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + exclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + exclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + exports.default = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + exports.default = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var ucs2length_1 = require_ucs2length$1(); + exports.default = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code$2(); + var util_1 = require_util$1(); + var codegen_1 = require_codegen$1(); + exports.default = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + exports.default = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code$2(); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + exports.default = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) allErrorsMode(); + else exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + function allErrorsMode() { + if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); + else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + exports.default = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/equal.js +var require_equal$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = "require(\"ajv/dist/runtime/equal\").default"; + exports.default = equal; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType$1(); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var equal_1 = require_equal$1(); + exports.default = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ + i, + j + }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var equal_1 = require_equal$1(); + exports.default = { + keyword: "const", + $data: true, + error: { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var equal_1 = require_equal$1(); + exports.default = { + keyword: "enum", + schemaType: "array", + $data: true, + error: { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber$1(); + var multipleOf_1 = require_multipleOf$1(); + var limitLength_1 = require_limitLength$1(); + var pattern_1 = require_pattern$1(); + var limitProperties_1 = require_limitProperties$1(); + var required_1 = require_required$1(); + var limitItems_1 = require_limitItems$1(); + var uniqueItems_1 = require_uniqueItems$1(); + var const_1 = require_const$1(); + var enum_1 = require_enum$1(); + exports.default = [ + limitNumber_1.default, + multipleOf_1.default, + limitLength_1.default, + pattern_1.default, + limitProperties_1.default, + required_1.default, + limitItems_1.default, + uniqueItems_1.default, + { + keyword: "type", + schemaType: ["string", "array"] + }, + { + keyword: "nullable", + schemaType: "boolean" + }, + const_1.default, + enum_1.default + ]; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var code_1 = require_code$2(); + var def = { + keyword: "items", + type: "array", + schemaType: [ + "object", + "array", + "boolean" + ], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var items_1 = require_items$1(); + exports.default = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var code_1 = require_code$2(); + var additionalItems_1 = require_additionalItems$1(); + exports.default = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else cxt.ok((0, code_1.validateArray)(cxt)); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + exports.default = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else min = 1; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ + min, + max + }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); + else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) gen.assign(valid, true); + else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var code_1 = require_code$2(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) gen.if(hasProperty, () => { + for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); + }); + else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: prop + }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true)); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + exports.default = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) gen.break(); + }); + }); + cxt.ok(valid); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code$2(); + var codegen_1 = require_codegen$1(); + var names_1 = require_names$1(); + var util_1 = require_util$1(); + exports.default = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) additionalPropertyCode(key); + else gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + else definedProp = codegen_1.nil; + if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + cxt.subschema(subschema, valid); + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate$1(); + var code_1 = require_code$2(); + var util_1 = require_util$1(); + var additionalProperties_1 = require_additionalProperties$1(); + exports.default = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) it.definedProperties.add(prop); + if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) applyPropertySchema(prop); + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code$2(); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var util_2 = require_util$1(); + exports.default = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat); + if (it.allErrors) validateProperties(pat); + else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); + else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + }); + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util$1(); + exports.default = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: require_code$2().validateUnion, + error: { message: "must match a schema in anyOf" } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + exports.default = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); + else schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util$1(); + exports.default = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + const schCxt = cxt.subschema({ + keyword: "allOf", + schemaProp: i + }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var util_1 = require_util$1(); + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) gen.if(schValid, validateClause("then")); + else gen.if((0, codegen_1.not)(schValid), validateClause("else")); + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util$1(); + exports.default = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems$1(); + var prefixItems_1 = require_prefixItems$1(); + var items_1 = require_items$1(); + var items2020_1 = require_items2020$1(); + var contains_1 = require_contains$1(); + var dependencies_1 = require_dependencies$1(); + var propertyNames_1 = require_propertyNames$1(); + var additionalProperties_1 = require_additionalProperties$1(); + var properties_1 = require_properties$1(); + var patternProperties_1 = require_patternProperties$1(); + var not_1 = require_not$1(); + var anyOf_1 = require_anyOf$1(); + var oneOf_1 = require_oneOf$1(); + var allOf_1 = require_allOf$1(); + var if_1 = require_if$1(); + var thenElse_1 = require_thenElse$1(); + function getApplicator(draft2020 = false) { + const applicator = [ + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); + else applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/format.js +var require_format$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + exports.default = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) return; + if ($data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { + key: schema, + ref: fmtDef, + code + }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ + fmtDef.type || "string", + fmtDef.validate, + (0, codegen_1._)`${fmt}.validate` + ]; + return [ + "string", + fmtDef, + fmt + ]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/index.js +var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = [require_format$3().default]; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core$2(); + var validation_1 = require_validation$1(); + var applicator_1 = require_applicator$1(); + var format_1 = require_format$2(); + var metadata_1 = require_metadata$1(); + exports.default = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen$1(); + var types_1 = require_types$1(); + var compile_1 = require_compile$1(); + var ref_error_1 = require_ref_error$1(); + var util_1 = require_util$1(); + exports.default = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); + const tagName = schema.propertyName; + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); + if (schema.mapping) throw new Error("discriminator: mapping is not supported"); + if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag, + tagName + }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp + }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) addMapping(sch.const, i); + else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); + else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); + oneOfMapping[tagValue] = i; + } + } + } + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/json-schema-draft-07.json +var json_schema_draft_07_exports$1 = /* @__PURE__ */ __exportAll({ + $id: () => $id$2, + $schema: () => $schema$1, + default: () => json_schema_draft_07_default$1, + definitions: () => definitions$1, + properties: () => properties$2, + title: () => title$1, + type: () => type$2 +}); +var $schema$1, $id$2, title$1, definitions$1, type$2, properties$2, json_schema_draft_07_default$1; +var init_json_schema_draft_07$1 = __esmMin((() => { + $schema$1 = "http://json-schema.org/draft-07/schema#"; + $id$2 = "http://json-schema.org/draft-07/schema#"; + title$1 = "Core schema meta-schema"; + definitions$1 = { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }; + type$2 = ["object", "boolean"]; + properties$2 = { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { "type": "string" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": { "$ref": "#" }, + "then": { "$ref": "#" }, + "else": { "$ref": "#" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }; + json_schema_draft_07_default$1 = { + $schema: $schema$1, + $id: $id$2, + title: title$1, + definitions: definitions$1, + type: type$2, + properties: properties$2, + "default": true + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/ajv.js +var require_ajv$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core$3(); + var draft7_1 = require_draft7$1(); + var discriminator_1 = require_discriminator$1(); + var draft7MetaSchema = (init_json_schema_draft_07$1(), __toCommonJS(json_schema_draft_07_exports$1).default); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate$1(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error$1(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error$1(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); +//#endregion +//#region node_modules/ajv-formats/dist/formats.js +var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { + validate, + compare + }; + } + exports.fullFormats = { + date: fmtDef(date, compareDate), + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[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, + "uri-template": /^(?:(?:[^\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|127)(?:\.\d{1,3}){3})(?!(?:169\.254|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-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/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, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\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, + regex, + 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)*)*)$/, + byte, + int32: { + type: "number", + validate: validateInt32 + }, + int64: { + type: "number", + validate: validateInt64 + }, + float: { + type: "number", + validate: validateNumber + }, + double: { + type: "number", + validate: validateNumber + }, + password: true, + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\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, compareIsoDateTime), + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var DAYS = [ + 0, + 31, + 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + ]; + function date(str) { + const matches = DATE.exec(str); + 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 compareDate(d1, d2) { + if (!(d1 && d2)) return void 0; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + return 0; + } + var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time(str) { + const matches = TIME.exec(str); + if (!matches) return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; + if (hr <= 23 && min <= 59 && sec < 60) return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) return 1; + if (t1 < t2) return -1; + return 0; + } + var DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) return void 0; + return res || compareTime(t1, t2); + } + var NOT_URI_FRAGMENT = /\/|:/; + var URI = /^(?:[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; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + var MIN_INT32 = -(2 ** 31); + var MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + var Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/code.js +var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class {}; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + const item = this._items[0]; + return item === "" || item === "\"\""; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + var plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) code.push(...arg._items); + else if (arg instanceof Name) code.push(arg); + else code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === "\"\"") return a; + if (a === "\"\"") return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== "\"") return; + if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; + if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code$1(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + return this._names[prefix] = { + prefix, + index: 0 + }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + var line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { + ...opts, + _n: opts.lines ? line : code_1.nil + }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) return _name; + } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { + property: prefix, + itemIndex + }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; + else throw new ValueError(name); + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code$1(); + var scope_1 = require_scope(); + var code_2 = require_code$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return code_2._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return code_2.str; + } + }); + Object.defineProperty(exports, "strConcat", { + enumerable: true, + get: function() { + return code_2.strConcat; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return code_2.nil; + } + }); + Object.defineProperty(exports, "getProperty", { + enumerable: true, + get: function() { + return code_2.getProperty; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return code_2.stringify; + } + }); + Object.defineProperty(exports, "regexpCode", { + enumerable: true, + get: function() { + return code_2.regexpCode; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return code_2.Name; + } + }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function() { + return scope_2.Scope; + } + }); + Object.defineProperty(exports, "ValueScope", { + enumerable: true, + get: function() { + return scope_2.ValueScope; + } + }); + Object.defineProperty(exports, "ValueScopeName", { + enumerable: true, + get: function() { + return scope_2.ValueScopeName; + } + }); + Object.defineProperty(exports, "varKinds", { + enumerable: true, + get: function() { + return scope_2.varKinds; + } + }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) return; + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `break${this.label ? ` ${this.label}` : ""};` + _n; + } + }; + var Throw = class extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) nodes.splice(i, 1, ...n); + else if (n) nodes[i] = n; + else nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode {}; + var Else = class extends BlockNode {}; + Else.kind = "else"; + var If = class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes; + if (this.nodes.length) return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode {}; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + return addExprNames(addExprNames(super.names, this.from), this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) code += this.catch.render(opts); + if (this.finally) code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) addNames(names, this.catch.names); + if (this.finally) addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { + ...opts, + _n: opts.lines ? "\n" : "" + }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + name(prefix) { + return this._scope.name(prefix); + } + scopeName(prefix) { + return this._extScope.name(prefix); + } + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + code(c) { + if (typeof c == "function") c(); + else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); + return this; + } + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); + else if (thenBody) this.code(thenBody).endIf(); + else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); + return this; + } + elseIf(condition) { + return this._elseNode(new If(condition)); + } + else() { + return this._elseNode(new Else()); + } + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) this.code(forBody).endFor(); + return this; + } + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + endFor() { + return this._endBlockNode(For); + } + label(label) { + return this._leafNode(new Label(label)); + } + break(label) { + return this._leafNode(new Break(label)); + } + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); + return this._endBlockNode(Return); + } + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error) { + return this._leafNode(new Throw(error)); + } + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) this.code(body).endBlock(nodeCount); + return this; + } + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + this._nodes.length = len; + return this; + } + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) this.code(funcBody).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) return replaceName(expr); + if (!canOptimize(expr)) return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) c = replaceName(c); + if (c instanceof code_1._Code) items.push(...c._items); + else items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + var andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + var orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen(); + var code_1 = require_code$1(); + function toHash(arr) { + const hash = {}; + for (const item of arr) hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") return schema; + if (Object.keys(schema).length === 0) return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) return; + if (typeof schema === "boolean") return; + const rules = self.RULES.keywords; + for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (rules[key]) return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema; + if (typeof schema == "string") return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) for (const x of xs) f(x); + else f(xs); + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) gen.assign(to, true); + else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { + ...from, + ...to + }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) return; + msg = `strict mode: ${msg}`; + if (mode === true) throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js +var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + exports.default = { + data: new codegen_1.Name("data"), + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; + exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); + else returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error, errorPaths)); + if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + /* istanbul ignore if */ + if (errsCount === void 0) throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + var E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + if (propertyName) keyValues.push([E.propertyName, propertyName]); + } +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var boolError = { message: "boolean schema is false" }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) falseSchemaError(it, false); + else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else gen.var(valid, true); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/rules.js +var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var jsonTypes = /* @__PURE__ */ new Set([ + "string", + "number", + "integer", + "boolean", + "null", + "object", + "array" + ]); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { + type: "number", + rules: [] + }, + string: { + type: "string", + rules: [] + }, + array: { + type: "array", + rules: [] + }, + object: { + type: "object", + rules: [] + } + }; + return { + types: { + ...groups, + integer: true, + boolean: true, + null: true + }, + rules: [ + { rules: [] }, + groups.number, + groups.string, + groups.array, + groups.object + ], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules(); + var applicability_1 = require_applicability(); + var errors_1 = require_errors(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var DataType; + (function(DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + if (types.includes("null")) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); + if (schema.nullable === true) types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo); + else reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set([ + "string", + "number", + "integer", + "boolean", + "null" + ]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else cond = codegen_1.nil; + if (types.number) delete types.integer; + for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); + else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js +var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + var util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var code_1 = require_code(); + var errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a; + gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { + ref: result, + code: (0, codegen_1.stringify)(result) + }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + if (def.validateSchema) { + if (!def.validateSchema(schema[keyword])) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") self.logger.error(msg); + else throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error("either \"keyword\" or \"schema\" must be passed"); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); + if (propertyName !== void 0) subschema.propertyName = propertyName; + } + if (dataTypes) subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) subschema.compositeRule = compositeRule; + if (createErrors !== void 0) subschema.createErrors = createErrors; + if (allErrors !== void 0) subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: 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 + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js +var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util(); + var equal = require_fast_deep_equal(); + var traverse = require_json_schema_traverse(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") return true; + if (limit === true) return !hasRef(schema); + if (!limit) return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) return true; + if (typeof sch == "object" && hasRef(sch)) return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) continue; + if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + if (count === Infinity) return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) id = normalizeId(id); + return _getFullPath(resolver, resolver.parse(id)); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + return resolver.serialize(p).split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); + else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else this.refs[ref] = fullPath; + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); + } + function ambiguos(ref) { + return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/index.js +var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema(); + var dataType_1 = require_dataType(); + var applicability_1 = require_applicability(); + var dataType_2 = require_dataType(); + var defaults_1 = require_defaults(); + var keyword_1 = require_keyword(); + var subschema_1 = require_subschema(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (self.RULES.all[key]) return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else iterateKeywords(it, group); + if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); + else if (withTypes.includes("integer") && t === "number") ts.push("integer"); + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) failAction(); + else this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(condition) { + if (!this.$data) return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) Object.assign(this.params, obj); + else this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { + ...this.it, + ...subschema, + items: void 0, + props: void 0 + }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; + if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) def.code(cxt, ruleType); + else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); + else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js +var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen(); + var validation_error_1 = require_validation_error(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { + es5, + lines, + ownProperties + }); + let _ValidationError; + if (sch.$async) _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { + ref: sch.schema, + code: (0, codegen_1.stringify)(sch.schema) + } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); + const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) validate.$async = true; + if (this.opts.code.source === true) validate.source = { + validateName, + validateCode, + scopeValues: gen._values + }; + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema) _sch = new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + if (_sch === void 0) return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; + if (!schOrRef.validate) compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + if (env.schema !== env.root.schema) return env; + } +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/refs/data.json +var data_exports = /* @__PURE__ */ __exportAll({ + $id: () => $id$1, + additionalProperties: () => false, + default: () => data_default, + description: () => description, + properties: () => properties$1, + required: () => required, + type: () => type$1 +}), $id$1, description, type$1, required, properties$1, data_default; +var init_data = __esmMin((() => { + $id$1 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"; + description = "Meta-schema for $data reference (JSON AnySchema extension proposal)"; + type$1 = "object"; + required = ["$data"]; + properties$1 = { "$data": { + "type": "string", + "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] + } }; + data_default = { + $id: $id$1, + description, + type: type$1, + required, + properties: properties$1, + additionalProperties: false + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/runtime/uri.js +var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var uri = require_fast_uri(); + uri.code = "require(\"ajv/dist/runtime/uri\").default"; + exports.default = uri; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/core.js +var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + var ref_error_1 = require_ref_error(); + var rules_1 = require_rules(); + var compile_1 = require_compile(); + var codegen_2 = require_codegen(); + var resolve_1 = require_resolve(); + var dataType_1 = require_dataType(); + var util_1 = require_util(); + var $dataRefSchema = (init_data(), __toCommonJS(data_exports).default); + var uri_1 = require_uri(); + var defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = [ + "removeAdditional", + "useDefaults", + "coerceTypes" + ]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: "\"nullable\" keyword is supported by default.", + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: "\"uniqueItems\" keyword is always validated.", + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." + }; + var MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { + ...o.code, + optimize, + regExp + } : { + optimize, + regExp + }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = Object.create(null); + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { + ...opts, + ...requiredOptions(opts) + }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ + scope: {}, + prefixes: EXT_SCOPE_NAMES, + es5, + lines + }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else v = this.compile(schemaKeyRef); + const valid = v(data); + if (!("$async" in v)) this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message); + else throw new Error(message); + } + return valid; + } + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ + schema: {}, + schemaId + }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: throw new Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(definitions) { + for (const def of definitions) this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); + } else throw new Error("invalid addKeywords parameters"); + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) group.rules.splice(i, 1); + } + return this; + } + addFormat(name, format) { + if (typeof format == "string") format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") delete schemas[keyRef]; + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") id = schema[schemaId]; + else if (this.opts.jtd) throw new Error("schema must be object"); + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); + let sch = this._cache.get(schema); + if (sch !== void 0) return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ + schema, + schemaId, + meta, + baseId, + localRefs + }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); + } + _compileSchemaEnv(sch) { + if (sch.meta) this._compileMetaSchema(sch); + else compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + exports.default = Ajv; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); + else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { + log() {}, + warn() {}, + error() {} + }; + function getLogger(logger) { + if (logger === false) return noLogs; + if (logger === void 0) return console; + if (logger.log && logger.warn && logger.error) return logger; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) return; + if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); + else ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) ruleGroup.rules.splice(i, 0, rule); + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) return; + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = { + keyword: "id", + code() { + throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error(); + var code_1 = require_code(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var compile_1 = require_compile(); + var util_1 = require_util(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + callRef(cxt, getValidate(cxt, sch), sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { + ref: sch, + code: (0, codegen_1.stringify)(sch) + } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) callAsyncRef(); + else callSyncRef(); + function callAsyncRef() { + if (!env.$async) throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + exports.callRef = callRef; + exports.default = def; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/index.js +var require_core = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var id_1 = require_id(); + var ref_1 = require_ref(); + exports.default = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + minimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + exclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + exclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + exports.default = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + exports.default = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var ucs2length_1 = require_ucs2length(); + exports.default = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code(); + var util_1 = require_util(); + var codegen_1 = require_codegen(); + exports.default = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + exports.default = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + exports.default = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) allErrorsMode(); + else exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + function allErrorsMode() { + if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); + else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + exports.default = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/runtime/equal.js +var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = "require(\"ajv/dist/runtime/equal\").default"; + exports.default = equal; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + exports.default = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ + i, + j + }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + exports.default = { + keyword: "const", + $data: true, + error: { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + exports.default = { + keyword: "enum", + schemaType: "array", + $data: true, + error: { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber(); + var multipleOf_1 = require_multipleOf(); + var limitLength_1 = require_limitLength(); + var pattern_1 = require_pattern(); + var limitProperties_1 = require_limitProperties(); + var required_1 = require_required(); + var limitItems_1 = require_limitItems(); + var uniqueItems_1 = require_uniqueItems(); + var const_1 = require_const(); + var enum_1 = require_enum(); + exports.default = [ + limitNumber_1.default, + multipleOf_1.default, + limitLength_1.default, + pattern_1.default, + limitProperties_1.default, + required_1.default, + limitItems_1.default, + uniqueItems_1.default, + { + keyword: "type", + schemaType: ["string", "array"] + }, + { + keyword: "nullable", + schemaType: "boolean" + }, + const_1.default, + enum_1.default + ]; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code(); + var def = { + keyword: "items", + type: "array", + schemaType: [ + "object", + "array", + "boolean" + ], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var items_1 = require_items(); + exports.default = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code(); + var additionalItems_1 = require_additionalItems(); + exports.default = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else cxt.ok((0, code_1.validateArray)(cxt)); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + exports.default = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else min = 1; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ + min, + max + }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); + else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) gen.assign(valid, true); + else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) gen.if(hasProperty, () => { + for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); + }); + else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: prop + }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true)); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + exports.default = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) gen.break(); + }); + }); + cxt.ok(valid); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var util_1 = require_util(); + exports.default = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) additionalPropertyCode(key); + else gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + else definedProp = codegen_1.nil; + if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + cxt.subschema(subschema, valid); + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate(); + var code_1 = require_code(); + var util_1 = require_util(); + var additionalProperties_1 = require_additionalProperties(); + exports.default = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) it.definedProperties.add(prop); + if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) applyPropertySchema(prop); + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var util_2 = require_util(); + exports.default = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat); + if (it.allErrors) validateProperties(pat); + else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); + else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + }); + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + exports.default = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: require_code().validateUnion, + error: { message: "must match a schema in anyOf" } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + exports.default = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); + else schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + exports.default = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + const schCxt = cxt.subschema({ + keyword: "allOf", + schemaProp: i + }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) gen.if(schValid, validateClause("then")); + else gen.if((0, codegen_1.not)(schValid), validateClause("else")); + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + exports.default = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems(); + var prefixItems_1 = require_prefixItems(); + var items_1 = require_items(); + var items2020_1 = require_items2020(); + var contains_1 = require_contains(); + var dependencies_1 = require_dependencies(); + var propertyNames_1 = require_propertyNames(); + var additionalProperties_1 = require_additionalProperties(); + var properties_1 = require_properties(); + var patternProperties_1 = require_patternProperties(); + var not_1 = require_not(); + var anyOf_1 = require_anyOf(); + var oneOf_1 = require_oneOf(); + var allOf_1 = require_allOf(); + var if_1 = require_if(); + var thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); + else applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/format.js +var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + exports.default = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) return; + if ($data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { + key: schema, + ref: fmtDef, + code + }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ + fmtDef.type || "string", + fmtDef.validate, + (0, codegen_1._)`${fmt}.validate` + ]; + return [ + "string", + fmtDef, + fmt + ]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/index.js +var require_format = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = [require_format$1().default]; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core(); + var validation_1 = require_validation(); + var applicator_1 = require_applicator(); + var format_1 = require_format(); + var metadata_1 = require_metadata(); + exports.default = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var types_1 = require_types(); + var compile_1 = require_compile(); + var ref_error_1 = require_ref_error(); + var util_1 = require_util(); + exports.default = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); + const tagName = schema.propertyName; + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); + if (schema.mapping) throw new Error("discriminator: mapping is not supported"); + if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag, + tagName + }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp + }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) addMapping(sch.const, i); + else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); + else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); + oneOfMapping[tagValue] = i; + } + } + } + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/refs/json-schema-draft-07.json +var json_schema_draft_07_exports = /* @__PURE__ */ __exportAll({ + $id: () => $id, + $schema: () => $schema, + default: () => json_schema_draft_07_default, + definitions: () => definitions, + properties: () => properties, + title: () => title, + type: () => type +}); +var $schema, $id, title, definitions, type, properties, json_schema_draft_07_default; +var init_json_schema_draft_07 = __esmMin((() => { + $schema = "http://json-schema.org/draft-07/schema#"; + $id = "http://json-schema.org/draft-07/schema#"; + title = "Core schema meta-schema"; + definitions = { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }; + type = ["object", "boolean"]; + properties = { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { "type": "string" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": { "$ref": "#" }, + "then": { "$ref": "#" }, + "else": { "$ref": "#" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }; + json_schema_draft_07_default = { + $schema, + $id, + title, + definitions, + type, + properties, + "default": true + }; +})); +//#endregion +//#region node_modules/ajv-formats/node_modules/ajv/dist/ajv.js +var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core$1(); + var draft7_1 = require_draft7(); + var discriminator_1 = require_discriminator(); + var draft7MetaSchema = (init_json_schema_draft_07(), __toCommonJS(json_schema_draft_07_exports).default); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); +//#endregion +//#region node_modules/ajv-formats/dist/limit.js +var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + var ajv_1 = require_ajv(); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + formatMaximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + formatMinimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + formatExclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + formatExclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + var formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; +})); +//#endregion +//#region node_modules/ajv-formats/dist/index.js +var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var formats_1 = require_formats(); + var limit_1 = require_limit(); + var codegen_1 = require_codegen(); + var fullName = new codegen_1.Name("fullFormats"); + var fastName = new codegen_1.Name("fastFormats"); + var formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); + if (opts.keywords) (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; + if (!f) throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats(ajv, list, fs, exportName) { + var _a; + var _b; + (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); + for (const f of list) ajv.addFormat(f, fs[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js +var import_ajv = /* @__PURE__ */ __toESM(require_ajv$1(), 1); +var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); +function createDefaultAjvInstance() { + const ajv = new import_ajv.default({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + (0, import_dist.default)(ajv); + return ajv; +} +/** +* @example +* ```typescript +* // Use with default AJV instance (recommended) +* import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; +* const validator = new AjvJsonSchemaValidator(); +* +* // Use with custom AJV instance +* import { Ajv } from 'ajv'; +* const ajv = new Ajv({ strict: true, allErrors: true }); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +*/ +var AjvJsonSchemaValidator = class { + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv) { + this._ajv = ajv ?? createDefaultAjvInstance(); + } + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema); + return (input) => { + if (ajvValidator(input)) return { + valid: true, + data: input, + errorMessage: void 0 + }; + else return { + valid: false, + data: void 0, + errorMessage: this._ajv.errorsText(ajvValidator.errors) + }; + }; + } +}; +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js +/** +* Experimental client task features for MCP SDK. +* WARNING: These APIs are experimental and may change without notice. +* +* @experimental +*/ +/** +* Experimental task features for MCP clients. +* +* Access via `client.experimental.tasks`: +* ```typescript +* const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} }); +* const task = await client.experimental.tasks.getTask(taskId); +* ``` +* +* @experimental +*/ +var ExperimentalClientTasks = class { + constructor(_client) { + this._client = _client; + } + /** + * Calls a tool and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to tool execution, allowing you to + * observe intermediate task status updates for long-running tool calls. + * Automatically validates structured output if the tool has an outputSchema. + * + * @example + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} }); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Tool execution started:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Tool status:', message.task.status); + * break; + * case 'result': + * console.log('Tool result:', message.result); + * break; + * case 'error': + * console.error('Tool error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - Tool call parameters (name and arguments) + * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema) + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + async *callToolStream(params, resultSchema = CallToolResultSchema, options) { + const clientInternal = this._client; + const optionsWithTask = { + ...options, + task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0) + }; + const stream = clientInternal.requestStream({ + method: "tools/call", + params + }, resultSchema, optionsWithTask); + const validator = clientInternal.getToolOutputValidator(params.name); + for await (const message of stream) { + if (message.type === "result" && validator) { + const result = message.result; + if (!result.structuredContent && !result.isError) { + yield { + type: "error", + error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`) + }; + return; + } + if (result.structuredContent) try { + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + yield { + type: "error", + error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`) + }; + return; + } + } catch (error) { + if (error instanceof McpError) { + yield { + type: "error", + error + }; + return; + } + yield { + type: "error", + error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`) + }; + return; + } + } + yield message; + } + } + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + async getTask(taskId, options) { + return this._client.getTask({ taskId }, options); + } + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + async getTaskResult(taskId, resultSchema, options) { + return this._client.getTaskResult({ taskId }, resultSchema, options); + } + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + async listTasks(cursor, options) { + return this._client.listTasks(cursor ? { cursor } : void 0, options); + } + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + async cancelTask(taskId, options) { + return this._client.cancelTask({ taskId }, options); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request, resultSchema, options) { + return this._client.requestStream(request, resultSchema, options); + } +}; +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js +/** +* Experimental task capability assertion helpers. +* WARNING: These APIs are experimental and may change without notice. +* +* @experimental +*/ +/** +* Asserts that task creation is supported for tools/call. +* Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability. +* +* @param requests - The task requests capability object +* @param method - The method being checked +* @param entityName - 'Server' or 'Client' for error messages +* @throws Error if the capability is not supported +* +* @experimental +*/ +function assertToolsCallTaskCapability(requests, method, entityName) { + if (!requests) throw new Error(`${entityName} does not support task creation (required for ${method})`); + switch (method) { + case "tools/call": + if (!requests.tools?.call) throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); + break; + default: break; + } +} +/** +* Asserts that task creation is supported for sampling/createMessage or elicitation/create. +* Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability. +* +* @param requests - The task requests capability object +* @param method - The method being checked +* @param entityName - 'Server' or 'Client' for error messages +* @throws Error if the capability is not supported +* +* @experimental +*/ +function assertClientRequestTaskCapability(requests, method, entityName) { + if (!requests) throw new Error(`${entityName} does not support task creation (required for ${method})`); + switch (method) { + case "sampling/createMessage": + if (!requests.sampling?.createMessage) throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); + break; + case "elicitation/create": + if (!requests.elicitation?.create) throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); + break; + default: break; + } +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js +/** +* Elicitation default application helper. Applies defaults to the data based on the schema. +* +* @param schema - The schema to apply defaults to. +* @param data - The data to apply defaults to. +*/ +function applyElicitationDefaults(schema, data) { + if (!schema || data === null || typeof data !== "object") return; + if (schema.type === "object" && schema.properties && typeof schema.properties === "object") { + const obj = data; + const props = schema.properties; + for (const key of Object.keys(props)) { + const propSchema = props[key]; + if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) obj[key] = propSchema.default; + if (obj[key] !== void 0) applyElicitationDefaults(propSchema, obj[key]); + } + } + if (Array.isArray(schema.anyOf)) { + for (const sub of schema.anyOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data); + } + if (Array.isArray(schema.oneOf)) { + for (const sub of schema.oneOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data); + } +} +/** +* Determines which elicitation modes are supported based on declared client capabilities. +* +* According to the spec: +* - An empty elicitation capability object defaults to form mode support (backwards compatibility) +* - URL mode is only supported if explicitly declared +* +* @param capabilities - The client's elicitation capabilities +* @returns An object indicating which modes are supported +*/ +function getSupportedElicitationModes(capabilities) { + if (!capabilities) return { + supportsFormMode: false, + supportsUrlMode: false + }; + const hasFormCapability = capabilities.form !== void 0; + const hasUrlCapability = capabilities.url !== void 0; + return { + supportsFormMode: hasFormCapability || !hasFormCapability && !hasUrlCapability, + supportsUrlMode: hasUrlCapability + }; +} +/** +* An MCP client on top of a pluggable transport. +* +* The client will automatically begin the initialization flow with the server when connect() is called. +* +* To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: +* +* ```typescript +* // Custom schemas +* const CustomRequestSchema = RequestSchema.extend({...}) +* const CustomNotificationSchema = NotificationSchema.extend({...}) +* const CustomResultSchema = ResultSchema.extend({...}) +* +* // Type aliases +* type CustomRequest = z.infer +* type CustomNotification = z.infer +* type CustomResult = z.infer +* +* // Create typed client +* const client = new Client({ +* name: "CustomClient", +* version: "1.0.0" +* }) +* ``` +*/ +var Client = class extends Protocol { + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo, options) { + super(options); + this._clientInfo = _clientInfo; + this._cachedToolOutputValidators = /* @__PURE__ */ new Map(); + this._cachedKnownTaskTools = /* @__PURE__ */ new Set(); + this._cachedRequiredTaskTools = /* @__PURE__ */ new Set(); + this._listChangedDebounceTimers = /* @__PURE__ */ new Map(); + this._capabilities = options?.capabilities ?? {}; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + if (options?.listChanged) this._pendingListChangedConfig = options.listChanged; + } + /** + * Set up handlers for list changed notifications based on config and server capabilities. + * This should only be called after initialization when server capabilities are known. + * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. + * @internal + */ + _setupListChangedHandlers(config) { + if (config.tools && this._serverCapabilities?.tools?.listChanged) this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config.tools, async () => { + return (await this.listTools()).tools; + }); + if (config.prompts && this._serverCapabilities?.prompts?.listChanged) this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config.prompts, async () => { + return (await this.listPrompts()).prompts; + }); + if (config.resources && this._serverCapabilities?.resources?.listChanged) this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config.resources, async () => { + return (await this.listResources()).resources; + }); + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) this._experimental = { tasks: new ExperimentalClientTasks(this) }; + return this._experimental; + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) throw new Error("Cannot register capabilities after connecting to transport"); + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema, handler) { + const methodSchema = getObjectShape(requestSchema)?.method; + if (!methodSchema) throw new Error("Schema is missing a method literal"); + const methodValue = getLiteralValue(methodSchema); + if (typeof methodValue !== "string") throw new Error("Schema method literal must be a string"); + const method = methodValue; + if (method === "elicitation/create") { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse(ElicitRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + params.mode = params.mode ?? "form"; + const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); + if (params.mode === "form" && !supportsFormMode) throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests"); + if (params.mode === "url" && !supportsUrlMode) throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests"); + const result = await Promise.resolve(handler(request, extra)); + if (params.task) { + const taskValidationResult = safeParse(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + const validationResult = safeParse(ElicitResultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); + } + const validatedResult = validationResult.data; + const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0; + if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) { + if (this._capabilities.elicitation?.form?.applyDefaults) try { + applyElicitationDefaults(requestedSchema, validatedResult.content); + } catch {} + } + return validatedResult; + }; + return super.setRequestHandler(requestSchema, wrappedHandler); + } + if (method === "sampling/createMessage") { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse(CreateMessageRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + if (params.task) { + const taskValidationResult = safeParse(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + const validationResult = safeParse(params.tools || params.toolChoice ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`); + } + return validationResult.data; + }; + return super.setRequestHandler(requestSchema, wrappedHandler); + } + return super.setRequestHandler(requestSchema, handler); + } + assertCapability(capability, method) { + if (!this._serverCapabilities?.[capability]) throw new Error(`Server does not support ${capability} (required for ${method})`); + } + async connect(transport, options) { + await super.connect(transport); + if (transport.sessionId !== void 0) return; + try { + const result = await this.request({ + method: "initialize", + params: { + protocolVersion: LATEST_PROTOCOL_VERSION, + capabilities: this._capabilities, + clientInfo: this._clientInfo + } + }, InitializeResultSchema, options); + if (result === void 0) throw new Error(`Server sent invalid initialize result: ${result}`); + if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); + this._serverCapabilities = result.capabilities; + this._serverVersion = result.serverInfo; + if (transport.setProtocolVersion) transport.setProtocolVersion(result.protocolVersion); + this._instructions = result.instructions; + await this.notification({ method: "notifications/initialized" }); + if (this._pendingListChangedConfig) { + this._setupListChangedHandlers(this._pendingListChangedConfig); + this._pendingListChangedConfig = void 0; + } + } catch (error) { + this.close(); + throw error; + } + } + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities() { + return this._serverCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion() { + return this._serverVersion; + } + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions() { + return this._instructions; + } + assertCapabilityForMethod(method) { + switch (method) { + case "logging/setLevel": + if (!this._serverCapabilities?.logging) throw new Error(`Server does not support logging (required for ${method})`); + break; + case "prompts/get": + case "prompts/list": + if (!this._serverCapabilities?.prompts) throw new Error(`Server does not support prompts (required for ${method})`); + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + case "resources/subscribe": + case "resources/unsubscribe": + if (!this._serverCapabilities?.resources) throw new Error(`Server does not support resources (required for ${method})`); + if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) throw new Error(`Server does not support resource subscriptions (required for ${method})`); + break; + case "tools/call": + case "tools/list": + if (!this._serverCapabilities?.tools) throw new Error(`Server does not support tools (required for ${method})`); + break; + case "completion/complete": + if (!this._serverCapabilities?.completions) throw new Error(`Server does not support completions (required for ${method})`); + break; + case "initialize": break; + case "ping": break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/roots/list_changed": + if (!this._capabilities.roots?.listChanged) throw new Error(`Client does not support roots list changed notifications (required for ${method})`); + break; + case "notifications/initialized": break; + case "notifications/cancelled": break; + case "notifications/progress": break; + } + } + assertRequestHandlerCapability(method) { + if (!this._capabilities) return; + switch (method) { + case "sampling/createMessage": + if (!this._capabilities.sampling) throw new Error(`Client does not support sampling capability (required for ${method})`); + break; + case "elicitation/create": + if (!this._capabilities.elicitation) throw new Error(`Client does not support elicitation capability (required for ${method})`); + break; + case "roots/list": + if (!this._capabilities.roots) throw new Error(`Client does not support roots capability (required for ${method})`); + break; + case "tasks/get": + case "tasks/list": + case "tasks/result": + case "tasks/cancel": + if (!this._capabilities.tasks) throw new Error(`Client does not support tasks capability (required for ${method})`); + break; + case "ping": break; + } + } + assertTaskCapability(method) { + assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server"); + } + assertTaskHandlerCapability(method) { + if (!this._capabilities) return; + assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client"); + } + async ping(options) { + return this.request({ method: "ping" }, EmptyResultSchema, options); + } + async complete(params, options) { + return this.request({ + method: "completion/complete", + params + }, CompleteResultSchema, options); + } + async setLoggingLevel(level, options) { + return this.request({ + method: "logging/setLevel", + params: { level } + }, EmptyResultSchema, options); + } + async getPrompt(params, options) { + return this.request({ + method: "prompts/get", + params + }, GetPromptResultSchema, options); + } + async listPrompts(params, options) { + return this.request({ + method: "prompts/list", + params + }, ListPromptsResultSchema, options); + } + async listResources(params, options) { + return this.request({ + method: "resources/list", + params + }, ListResourcesResultSchema, options); + } + async listResourceTemplates(params, options) { + return this.request({ + method: "resources/templates/list", + params + }, ListResourceTemplatesResultSchema, options); + } + async readResource(params, options) { + return this.request({ + method: "resources/read", + params + }, ReadResourceResultSchema, options); + } + async subscribeResource(params, options) { + return this.request({ + method: "resources/subscribe", + params + }, EmptyResultSchema, options); + } + async unsubscribeResource(params, options) { + return this.request({ + method: "resources/unsubscribe", + params + }, EmptyResultSchema, options); + } + /** + * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema. + * + * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead. + */ + async callTool(params, resultSchema = CallToolResultSchema, options) { + if (this.isToolTaskRequired(params.name)) throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`); + const result = await this.request({ + method: "tools/call", + params + }, resultSchema, options); + const validator = this.getToolOutputValidator(params.name); + if (validator) { + if (!result.structuredContent && !result.isError) throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); + if (result.structuredContent) try { + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); + } catch (error) { + if (error instanceof McpError) throw error; + throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`); + } + } + return result; + } + isToolTask(toolName) { + if (!this._serverCapabilities?.tasks?.requests?.tools?.call) return false; + return this._cachedKnownTaskTools.has(toolName); + } + /** + * Check if a tool requires task-based execution. + * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'. + */ + isToolTaskRequired(toolName) { + return this._cachedRequiredTaskTools.has(toolName); + } + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + cacheToolMetadata(tools) { + this._cachedToolOutputValidators.clear(); + this._cachedKnownTaskTools.clear(); + this._cachedRequiredTaskTools.clear(); + for (const tool of tools) { + if (tool.outputSchema) { + const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); + this._cachedToolOutputValidators.set(tool.name, toolValidator); + } + const taskSupport = tool.execution?.taskSupport; + if (taskSupport === "required" || taskSupport === "optional") this._cachedKnownTaskTools.add(tool.name); + if (taskSupport === "required") this._cachedRequiredTaskTools.add(tool.name); + } + } + /** + * Get cached validator for a tool + */ + getToolOutputValidator(toolName) { + return this._cachedToolOutputValidators.get(toolName); + } + async listTools(params, options) { + const result = await this.request({ + method: "tools/list", + params + }, ListToolsResultSchema, options); + this.cacheToolMetadata(result.tools); + return result; + } + /** + * Set up a single list changed handler. + * @internal + */ + _setupListChangedHandler(listType, notificationSchema, options, fetcher) { + const parseResult = ListChangedOptionsBaseSchema.safeParse(options); + if (!parseResult.success) throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`); + if (typeof options.onChanged !== "function") throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`); + const { autoRefresh, debounceMs } = parseResult.data; + const { onChanged } = options; + const refresh = async () => { + if (!autoRefresh) { + onChanged(null, null); + return; + } + try { + const items = await fetcher(); + onChanged(null, items); + } catch (e) { + const error = e instanceof Error ? e : new Error(String(e)); + onChanged(error, null); + } + }; + const handler = () => { + if (debounceMs) { + const existingTimer = this._listChangedDebounceTimers.get(listType); + if (existingTimer) clearTimeout(existingTimer); + const timer = setTimeout(refresh, debounceMs); + this._listChangedDebounceTimers.set(listType, timer); + } else refresh(); + }; + this.setNotificationHandler(notificationSchema, handler); + } + async sendRootsListChanged() { + return this.notification({ method: "notifications/roots/list_changed" }); + } +}; +//#endregion +//#region node_modules/isexe/windows.js +var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = isexe; + isexe.sync = sync; + var fs$2 = __require("fs"); + function checkPathExt(path, options) { + var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT; + if (!pathext) return true; + pathext = pathext.split(";"); + if (pathext.indexOf("") !== -1) return true; + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase(); + if (p && path.substr(-p.length).toLowerCase() === p) return true; + } + return false; + } + function checkStat(stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) return false; + return checkPathExt(path, options); + } + function isexe(path, options, cb) { + fs$2.stat(path, function(er, stat) { + cb(er, er ? false : checkStat(stat, path, options)); + }); + } + function sync(path, options) { + return checkStat(fs$2.statSync(path), path, options); + } +})); +//#endregion +//#region node_modules/isexe/mode.js +var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = isexe; + isexe.sync = sync; + var fs$1 = __require("fs"); + function isexe(path, options, cb) { + fs$1.stat(path, function(er, stat) { + cb(er, er ? false : checkStat(stat, options)); + }); + } + function sync(path, options) { + return checkStat(fs$1.statSync(path), options); + } + function checkStat(stat, options) { + return stat.isFile() && checkMode(stat, options); + } + function checkMode(stat, options) { + var mod = stat.mode; + var uid = stat.uid; + var gid = stat.gid; + var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid(); + var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid(); + var u = parseInt("100", 8); + var g = parseInt("010", 8); + var o = parseInt("001", 8); + var ug = u | g; + return mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0; + } +})); +//#endregion +//#region node_modules/isexe/index.js +var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => { + __require("fs"); + var core; + if (process.platform === "win32" || global.TESTING_WINDOWS) core = require_windows(); + else core = require_mode(); + module.exports = isexe; + isexe.sync = sync; + function isexe(path, options, cb) { + if (typeof options === "function") { + cb = options; + options = {}; + } + if (!cb) { + if (typeof Promise !== "function") throw new TypeError("callback not provided"); + return new Promise(function(resolve, reject) { + isexe(path, options || {}, function(er, is) { + if (er) reject(er); + else resolve(is); + }); + }); + } + core(path, options || {}, function(er, is) { + if (er) { + if (er.code === "EACCES" || options && options.ignoreErrors) { + er = null; + is = false; + } + } + cb(er, is); + }); + } + function sync(path, options) { + try { + return core.sync(path, options || {}); + } catch (er) { + if (options && options.ignoreErrors || er.code === "EACCES") return false; + else throw er; + } + } +})); +//#endregion +//#region node_modules/which/which.js +var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys"; + var path$2 = __require("path"); + var COLON = isWindows ? ";" : ":"; + var isexe = require_isexe(); + var getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" }); + var getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON; + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH || "").split(colon)]; + const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : ""; + const pathExt = isWindows ? pathExtExe.split(colon) : [""]; + if (isWindows) { + if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") pathExt.unshift(""); + } + return { + pathEnv, + pathExt, + pathExtExe + }; + }; + var which = (cmd, opt, cb) => { + if (typeof opt === "function") { + cb = opt; + opt = {}; + } + if (!opt) opt = {}; + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + const step = (i) => new Promise((resolve, reject) => { + if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)); + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + const pCmd = path$2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; + resolve(subStep(p, i, 0)); + }); + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) return resolve(step(i + 1)); + const ext = pathExt[ii]; + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) if (opt.all) found.push(p + ext); + else return resolve(p + ext); + return resolve(subStep(p, i, ii + 1)); + }); + }); + return cb ? step(0).then((res) => cb(null, res), cb) : step(0); + }; + var whichSync = (cmd, opt) => { + opt = opt || {}; + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + for (let i = 0; i < pathEnv.length; i++) { + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + const pCmd = path$2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; + for (let j = 0; j < pathExt.length; j++) { + const cur = p + pathExt[j]; + try { + if (isexe.sync(cur, { pathExt: pathExtExe })) if (opt.all) found.push(cur); + else return cur; + } catch (ex) {} + } + } + if (opt.all && found.length) return found; + if (opt.nothrow) return null; + throw getNotFoundError(cmd); + }; + module.exports = which; + which.sync = whichSync; +})); +//#endregion +//#region node_modules/path-key/index.js +var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var pathKey = (options = {}) => { + const environment = options.env || process.env; + if ((options.platform || process.platform) !== "win32") return "PATH"; + return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path"; + }; + module.exports = pathKey; + module.exports.default = pathKey; +})); +//#endregion +//#region node_modules/cross-spawn/lib/util/resolveCommand.js +var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var path$1 = __require("path"); + var which = require_which(); + var getPathKey = require_path_key(); + function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled; + if (shouldSwitchCwd) try { + process.chdir(parsed.options.cwd); + } catch (err) {} + let resolved; + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path$1.delimiter : void 0 + }); + } catch (e) {} finally { + if (shouldSwitchCwd) process.chdir(cwd); + } + if (resolved) resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved); + return resolved; + } + function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); + } + module.exports = resolveCommand; +})); +//#endregion +//#region node_modules/cross-spawn/lib/util/escape.js +var require_escape = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + function escapeCommand(arg) { + arg = arg.replace(metaCharsRegExp, "^$1"); + return arg; + } + function escapeArgument(arg, doubleEscapeMetaChars) { + arg = `${arg}`; + arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\""); + arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1"); + arg = `"${arg}"`; + arg = arg.replace(metaCharsRegExp, "^$1"); + if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1"); + return arg; + } + module.exports.command = escapeCommand; + module.exports.argument = escapeArgument; +})); +//#endregion +//#region node_modules/shebang-regex/index.js +var require_shebang_regex = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = /^#!(.*)/; +})); +//#endregion +//#region node_modules/shebang-command/index.js +var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var shebangRegex = require_shebang_regex(); + module.exports = (string = "") => { + const match = string.match(shebangRegex); + if (!match) return null; + const [path, argument] = match[0].replace(/#! ?/, "").split(" "); + const binary = path.split("/").pop(); + if (binary === "env") return argument; + return argument ? `${binary} ${argument}` : binary; + }; +})); +//#endregion +//#region node_modules/cross-spawn/lib/util/readShebang.js +var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var fs = __require("fs"); + var shebangCommand = require_shebang_command(); + function readShebang(command) { + const size = 150; + const buffer = Buffer.alloc(size); + let fd; + try { + fd = fs.openSync(command, "r"); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) {} + return shebangCommand(buffer.toString()); + } + module.exports = readShebang; +})); +//#endregion +//#region node_modules/cross-spawn/lib/parse.js +var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var path = __require("path"); + var resolveCommand = require_resolveCommand(); + var escape = require_escape(); + var readShebang = require_readShebang(); + var isWin = process.platform === "win32"; + var isExecutableRegExp = /\.(?:com|exe)$/i; + var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + const shebang = parsed.file && readShebang(parsed.file); + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + return resolveCommand(parsed); + } + return parsed.file; + } + function parseNonShell(parsed) { + if (!isWin) return parsed; + const commandFile = detectShebang(parsed); + const needsShell = !isExecutableRegExp.test(commandFile); + if (parsed.options.forceShell || needsShell) { + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + parsed.command = path.normalize(parsed.command); + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + parsed.args = [ + "/d", + "/s", + "/c", + `"${[parsed.command].concat(parsed.args).join(" ")}"` + ]; + parsed.command = process.env.comspec || "cmd.exe"; + parsed.options.windowsVerbatimArguments = true; + } + return parsed; + } + function parse(command, args, options) { + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + args = args ? args.slice(0) : []; + options = Object.assign({}, options); + const parsed = { + command, + args, + options, + file: void 0, + original: { + command, + args + } + }; + return options.shell ? parsed : parseNonShell(parsed); + } + module.exports = parse; +})); +//#endregion +//#region node_modules/cross-spawn/lib/enoent.js +var require_enoent = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var isWin = process.platform === "win32"; + function notFoundError(original, syscall) { + return Object.assign(/* @__PURE__ */ new Error(`${syscall} ${original.command} ENOENT`), { + code: "ENOENT", + errno: "ENOENT", + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args + }); + } + function hookChildProcess(cp, parsed) { + if (!isWin) return; + const originalEmit = cp.emit; + cp.emit = function(name, arg1) { + if (name === "exit") { + const err = verifyENOENT(arg1, parsed); + if (err) return originalEmit.call(cp, "error", err); + } + return originalEmit.apply(cp, arguments); + }; + } + function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawn"); + return null; + } + function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawnSync"); + return null; + } + module.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError + }; +})); +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js +var import_cross_spawn = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => { + var cp = __require("child_process"); + var parse = require_parse(); + var enoent = require_enoent(); + function spawn(command, args, options) { + const parsed = parse(command, args, options); + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + enoent.hookChildProcess(spawned, parsed); + return spawned; + } + function spawnSync(command, args, options) { + const parsed = parse(command, args, options); + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + return result; + } + module.exports = spawn; + module.exports.spawn = spawn; + module.exports.sync = spawnSync; + module.exports._parse = parse; + module.exports._enoent = enoent; +})))(), 1); +/** +* Buffers a continuous stdio stream into discrete JSON-RPC messages. +*/ +var ReadBuffer = class { + constructor(options) { + this._maxBufferSize = options?.maxBufferSize ?? 10485760; + } + append(chunk) { + if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { + this.clear(); + throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); + } + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + if (!this._buffer) return null; + const index = this._buffer.indexOf("\n"); + if (index === -1) return null; + const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index + 1); + return deserializeMessage(line); + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} +//#endregion +//#region node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js +/** +* Environment variables to inherit by default, if an environment is not explicitly given. +*/ +var DEFAULT_INHERITED_ENV_VARS = process$1.platform === "win32" ? [ + "APPDATA", + "HOMEDRIVE", + "HOMEPATH", + "LOCALAPPDATA", + "PATH", + "PROCESSOR_ARCHITECTURE", + "SYSTEMDRIVE", + "SYSTEMROOT", + "TEMP", + "USERNAME", + "USERPROFILE", + "PROGRAMFILES" +] : [ + "HOME", + "LOGNAME", + "PATH", + "SHELL", + "TERM", + "USER" +]; +/** +* Returns a default environment object including only environment variables deemed safe to inherit. +*/ +function getDefaultEnvironment() { + const env = {}; + for (const key of DEFAULT_INHERITED_ENV_VARS) { + const value = process$1.env[key]; + if (value === void 0) continue; + if (value.startsWith("()")) continue; + env[key] = value; + } + return env; +} +/** +* Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. +* +* This transport is only available in Node.js environments. +*/ +var StdioClientTransport = class { + constructor(server) { + this._stderrStream = null; + this._serverParams = server; + this._readBuffer = new ReadBuffer({ maxBufferSize: server.maxBufferSize }); + if (server.stderr === "pipe" || server.stderr === "overlapped") this._stderrStream = new PassThrough(); + } + /** + * Starts the server process and prepares to communicate with it. + */ + async start() { + if (this._process) throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically."); + return new Promise((resolve, reject) => { + this._process = (0, import_cross_spawn.default)(this._serverParams.command, this._serverParams.args ?? [], { + env: { + ...getDefaultEnvironment(), + ...this._serverParams.env + }, + stdio: [ + "pipe", + "pipe", + this._serverParams.stderr ?? "inherit" + ], + shell: false, + windowsHide: process$1.platform === "win32", + cwd: this._serverParams.cwd + }); + this._process.on("error", (error) => { + reject(error); + this.onerror?.(error); + }); + this._process.on("spawn", () => { + resolve(); + }); + this._process.on("close", (_code) => { + this._process = void 0; + this.onclose?.(); + }); + this._process.stdin?.on("error", (error) => { + this.onerror?.(error); + }); + this._process.stdout?.on("data", (chunk) => { + try { + this._readBuffer.append(chunk); + this.processReadBuffer(); + } catch (error) { + this.onerror?.(error); + this.close().catch(() => {}); + } + }); + this._process.stdout?.on("error", (error) => { + this.onerror?.(error); + }); + if (this._stderrStream && this._process.stderr) this._process.stderr.pipe(this._stderrStream); + }); + } + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr() { + if (this._stderrStream) return this._stderrStream; + return this._process?.stderr ?? null; + } + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid() { + return this._process?.pid ?? null; + } + processReadBuffer() { + while (true) try { + const message = this._readBuffer.readMessage(); + if (message === null) break; + this.onmessage?.(message); + } catch (error) { + this.onerror?.(error); + } + } + async close() { + if (this._process) { + const processToClose = this._process; + this._process = void 0; + const closePromise = new Promise((resolve) => { + processToClose.once("close", () => { + resolve(); + }); + }); + try { + processToClose.stdin?.end(); + } catch {} + await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]); + if (processToClose.exitCode === null) { + try { + processToClose.kill("SIGTERM"); + } catch {} + await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]); + } + if (processToClose.exitCode === null) try { + processToClose.kill("SIGKILL"); + } catch {} + } + this._readBuffer.clear(); + } + send(message) { + return new Promise((resolve) => { + if (!this._process?.stdin) throw new Error("Not connected"); + const json = serializeMessage(message); + if (this._process.stdin.write(json)) resolve(); + else this._process.stdin.once("drain", resolve); + }); + } +}; +//#endregion +//#region node_modules/@langchain/mcp-adapters/dist/connection.js +var debugLog$1 = getDebugLog("connection"); +var transportTypes = [ + "http", + "sse", + "stdio" +]; +/** +* Manages a pool of MCP clients with different transport, server name and connection configurations. +* This ensures we don't create multiple connections for the same server with the same configuration. +*/ +var ConnectionManager = class { + #connections = /* @__PURE__ */ new Map(); + #hooks; + constructor(hooks = {}) { + this.#hooks = hooks; + } + async createClient(...args) { + const [type, serverName, options] = args; + if (!transportTypes.includes(type)) throw new Error(`Invalid transport type: ${type}`); + const transport = type === "http" ? await this.#createStreamableHTTPTransport(serverName, options) : type === "sse" ? await this.#createSSETransport(serverName, options) : await this.#createStdioTransport(options); + const mcpClient = new Client({ + name: package_default.name, + version: package_default.version + }); + await mcpClient.connect(transport); + if (this.#hooks.onMessage) mcpClient.setNotificationHandler(LoggingMessageNotificationSchema, (notification) => this.#hooks.onMessage?.(notification.params, { + server: serverName, + options + })); + if (this.#hooks.onInitialized) mcpClient.setNotificationHandler(InitializedNotificationSchema, () => this.#hooks.onInitialized?.({ + server: serverName, + options + })); + if (this.#hooks.onCancelled) mcpClient.setNotificationHandler(CancelledNotificationSchema, (notification) => { + const { requestId, reason } = notification.params; + if (requestId == null) return; + const result = this.#hooks.onCancelled?.({ + requestId, + reason + }, { + server: serverName, + options + }); + if (result && typeof result.catch === "function") result.catch(() => {}); + }); + if (this.#hooks.onPromptsListChanged) mcpClient.setNotificationHandler(PromptListChangedNotificationSchema, () => this.#hooks.onPromptsListChanged?.({ + server: serverName, + options + })); + if (this.#hooks.onResourcesListChanged) mcpClient.setNotificationHandler(ResourceListChangedNotificationSchema, () => this.#hooks.onResourcesListChanged?.({ + server: serverName, + options + })); + if (this.#hooks.onResourcesUpdated) mcpClient.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => this.#hooks.onResourcesUpdated?.(notification.params, { + server: serverName, + options + })); + if (this.#hooks.onRootsListChanged) mcpClient.setNotificationHandler(RootsListChangedNotificationSchema, () => this.#hooks.onRootsListChanged?.({ + server: serverName, + options + })); + if (this.#hooks.onToolsListChanged) mcpClient.setNotificationHandler(ToolListChangedNotificationSchema, () => this.#hooks.onToolsListChanged?.({ + server: serverName, + options + })); + const key = type === "stdio" ? { serverName } : { + serverName, + headers: serializeHeaders(options.headers), + authProvider: options.authProvider + }; + const forkClient = (headers) => { + return this.#forkClient(key, headers); + }; + const client = new Proxy(mcpClient, { get(target, prop) { + if (prop === "fork") return forkClient.bind(this); + return target[prop]; + } }); + this.#connections.set(key, { + transport, + client, + transportOptions: options, + closeCallback: async () => client.close() + }); + return client; + } + /** + * Allows to fork a client with a new set of headers + */ + #forkClient(key, headers) { + const [, connection] = [...this.#connections.entries()].find(([k]) => key === k) ?? []; + if (!connection) throw new Error("Transport not found"); + const type = connection.transportOptions.type ?? connection.transportOptions.transport; + if (type === "stdio") throw new Error("Forking stdio transport is not supported"); + return this.createClient(type, key.serverName, { + ...connection.transportOptions, + headers + }); + } + get(options) { + if (typeof options === "string") return this.#queryConnection({ serverName: options })?.connection.client; + return this.#queryConnection(options)?.connection.client; + } + /** + * Get all clients + * @returns All clients + */ + getAllClients() { + return Array.from(this.#connections.values()).map((connection) => connection.client); + } + /** + * Find the connection based on the parameter provided. This approach makes sure + * that `this.get({ serverName })` and `this.get({ serverName, headers: undefined, authProvider: undefined })` + * will return the same connection. + * + * @param options - The options for the transport + * @returns The connection and the key + */ + #queryConnection(options) { + const headers = serializeHeaders(options.headers); + const [key, connection] = [...this.#connections.entries()].find(([key$1]) => { + if (options.headers && options.authProvider) return key$1.serverName === options.serverName && key$1.headers === headers && key$1.authProvider === options.authProvider; + if (options.headers && !options.authProvider) return key$1.serverName === options.serverName && key$1.headers === headers; + if (options.authProvider && !options.headers) return key$1.serverName === options.serverName && key$1.authProvider === options.authProvider; + return key$1.serverName === options.serverName; + }) ?? []; + if (key && connection) return { + key, + connection + }; + } + has(options) { + return Boolean(typeof options === "string" ? this.get(options) : this.get(options)); + } + /** + * Delete the transport based on server name and connection configuration. + * @param options - The options for the transport, if not provided, all transports are deleted + */ + async delete(options) { + if (!options) { + await Promise.all(Array.from(this.#connections.values()).map((connection) => connection.closeCallback())); + this.#connections.clear(); + return; + } + const result = this.#queryConnection(options); + if (result) { + await result.connection.closeCallback(); + this.#connections.delete(result.key); + } + } + getTransport(opts) { + /** + * if a client instance is passed in + */ + if ("listTools" in opts) return [...this.#connections.values()].find((connection$1) => connection$1.client === opts)?.transport; + const result = this.#queryConnection(opts); + if (result) return result.connection.transport; + } + async #createStreamableHTTPTransport(serverName, args) { + const { url, headers, reconnect, authProvider } = args; + const options = { + ...authProvider ? { authProvider } : {}, + ...headers ? { requestInit: { headers } } : {} + }; + if (reconnect != null) { + const reconnectionOptions = { + initialReconnectionDelay: reconnect?.delayMs ?? 1e3, + maxReconnectionDelay: reconnect?.delayMs ?? 3e4, + maxRetries: reconnect?.maxAttempts ?? 2, + reconnectionDelayGrowFactor: 1.5 + }; + if (reconnect.enabled === false) reconnectionOptions.maxRetries = 0; + options.reconnectionOptions = reconnectionOptions; + } + if (options.requestInit?.headers) debugLog$1(`DEBUG: Using custom headers for SSE transport to server "${serverName}"`); + if (options.authProvider) debugLog$1(`DEBUG: Using OAuth authentication for Streamable HTTP transport to server "${serverName}"`); + if (options.reconnectionOptions) if (options.reconnectionOptions.maxRetries === 0) debugLog$1(`DEBUG: Disabling reconnection for Streamable HTTP transport to server "${serverName}"`); + else debugLog$1(`DEBUG: Using custom reconnection options for Streamable HTTP transport to server "${serverName}"`); + return Object.keys(options).length > 0 ? new StreamableHTTPClientTransport(new URL(url), options) : new StreamableHTTPClientTransport(new URL(url)); + } + /** + * Create an SSE transport with appropriate EventSource implementation + * + * @param serverName - The name of the server + * @param url - The URL of the server + * @param headers - The headers to send with the request + * @param authProvider - The OAuth client provider to use for authentication + * @returns The SSE transport + */ + async #createSSETransport(serverName, args) { + const { url, headers, authProvider } = args; + const options = {}; + if (authProvider) { + options.authProvider = authProvider; + debugLog$1(`DEBUG: Using OAuth authentication for SSE transport to server "${serverName}"`); + } + if (headers) { + options.eventSourceInit = { fetch: async (url$1, init) => { + const requestHeaders = new Headers(init?.headers); + if (authProvider) { + const tokens = await authProvider.tokens(); + if (tokens) requestHeaders.set("Authorization", `Bearer ${tokens.access_token}`); + } + Object.entries(headers).forEach(([key, value]) => { + requestHeaders.set(key, value); + }); + requestHeaders.set("Accept", "text/event-stream"); + return fetch(url$1, { + ...init, + headers: requestHeaders + }); + } }; + options.requestInit = { headers }; + debugLog$1(`DEBUG: Using custom headers for SSE transport to server "${serverName}"`); + } + return new SSEClientTransport(new URL(url), options); + } + #createStdioTransport(options) { + const { command, args, env, stderr, cwd } = options; + return new StdioClientTransport({ + command, + args, + stderr, + cwd, + ...env ? { env: { + PATH: process.env.PATH, + ...env + } } : {} + }); + } +}; +/** +* A utility function that serializes the headers object to a string +* and orders the keys alphabetically so that the same headers object +* will always produce the same string. +* @param headers - The headers object to serialize +* @returns The serialized headers object +*/ +function serializeHeaders(headers) { + if (!headers) return; + return Object.entries(headers).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}: ${value}`).join("\n"); +} +//#endregion +//#region node_modules/@langchain/mcp-adapters/dist/client.js +var debugLog = getDebugLog(); +/** +* Error class for MCP client operations +*/ +var MCPClientError = class extends Error { + constructor(message, serverName) { + super(message); + this.serverName = serverName; + this.name = "MCPClientError"; + } +}; +/** +* Checks if the connection configuration is for a stdio transport +* @param connection - The connection configuration +* @returns True if the connection configuration is for a stdio transport +*/ +function isResolvedStdioConnection(connection) { + if (typeof connection !== "object" || connection === null || Array.isArray(connection)) return false; + if ("transport" in connection && connection.transport === "stdio") return true; + if ("type" in connection && connection.type === "stdio") return true; + if ("command" in connection && typeof connection.command === "string") return true; + return false; +} +/** +* Checks if the connection configuration is for a streamable HTTP transport +* @param connection - The connection configuration +* @returns True if the connection configuration is for a streamable HTTP transport +*/ +function isResolvedStreamableHTTPConnection(connection) { + if (typeof connection !== "object" || connection === null || Array.isArray(connection)) return false; + if ("transport" in connection && typeof connection.transport === "string" && ["http", "sse"].includes(connection.transport) || "type" in connection && typeof connection.type === "string" && ["http", "sse"].includes(connection.type)) return true; + if ("url" in connection && typeof connection.url === "string") try { + new URL(connection.url); + return true; + } catch { + return false; + } + return false; +} +/** +* Client for connecting to multiple MCP servers and loading LangChain-compatible tools. +*/ +var MultiServerMCPClient = class { + /** + * Cached map of server names to tools + */ + #serverNameToTools = {}; + /** + * Configured MCP servers + */ + #mcpServers; + /** + * Cached map of server names to load tools options + */ + #loadToolsOptions = {}; + /** + * Connection manager + */ + #clientConnections; + /** + * Resolved client config + */ + #config; + /** + * Behavior when a server fails to connect + */ + #onConnectionError; + /** + * Set of server names that have failed to connect (when onConnectionError is "ignore") + */ + #failedServers = /* @__PURE__ */ new Set(); + /** + * Returns clone of server config for inspection purposes. + * + * Client does not support config modifications. + */ + get config() { + return JSON.parse(JSON.stringify(this.#config)); + } + /** + * Create a new MultiServerMCPClient. + * + * @param config - Configuration object + */ + constructor(config) { + let parsedServerConfig; + const configSchema = clientConfigSchema; + if ("mcpServers" in config) parsedServerConfig = configSchema.parse(config); + else { + const parsedMcpServers = recordType(connectionSchema).parse(config); + parsedServerConfig = configSchema.parse({ mcpServers: parsedMcpServers }); + } + if (Object.keys(parsedServerConfig.mcpServers).length === 0) throw new MCPClientError("No MCP servers provided"); + for (const [serverName, serverConfig] of Object.entries(parsedServerConfig.mcpServers)) { + const outputHandling = _resolveAndApplyOverrideHandlingOverrides(parsedServerConfig.outputHandling, serverConfig.outputHandling); + const defaultToolTimeout = parsedServerConfig.defaultToolTimeout ?? serverConfig.defaultToolTimeout; + this.#loadToolsOptions[serverName] = { + throwOnLoadError: parsedServerConfig.throwOnLoadError, + prefixToolNameWithServerName: parsedServerConfig.prefixToolNameWithServerName, + additionalToolNamePrefix: parsedServerConfig.additionalToolNamePrefix, + useStandardContentBlocks: parsedServerConfig.useStandardContentBlocks, + ...Object.keys(outputHandling).length > 0 ? { outputHandling } : {}, + ...defaultToolTimeout ? { defaultToolTimeout } : {}, + onProgress: parsedServerConfig.onProgress, + beforeToolCall: parsedServerConfig.beforeToolCall, + afterToolCall: parsedServerConfig.afterToolCall + }; + } + this.#config = parsedServerConfig; + this.#mcpServers = parsedServerConfig.mcpServers; + this.#clientConnections = new ConnectionManager(parsedServerConfig); + this.#onConnectionError = parsedServerConfig.onConnectionError; + } + /** + * Proactively initialize connections to all servers. This will be called automatically when + * methods requiring an active connection (like {@link getTools} or {@link getClient}) are called, + * but you can call it directly to ensure all connections are established before using the tools. + * + * When a server fails to connect, the client will throw an error if `onConnectionError` is "throw", + * otherwise it will skip the server and continue with the remaining servers. + * + * @returns A map of server names to arrays of tools + * @throws {MCPClientError} If initialization fails and `onConnectionError` is "throw" (default) + */ + async initializeConnections(customTransportOptions) { + if (!this.#mcpServers || Object.keys(this.#mcpServers).length === 0) throw new MCPClientError("No connections to initialize"); + for (const [serverName, connection] of Object.entries(this.#mcpServers)) { + if ((this.#onConnectionError === "ignore" || typeof this.#onConnectionError === "function") && this.#failedServers.has(serverName)) continue; + try { + await this._initializeConnection(serverName, connection, customTransportOptions); + this.#failedServers.delete(serverName); + } catch (error) { + if (this.#onConnectionError === "throw") throw error; + if (typeof this.#onConnectionError === "function") { + this.#onConnectionError({ + serverName, + error + }); + this.#failedServers.add(serverName); + debugLog(`WARN: Failed to initialize connection to server "${serverName}": ${String(error)}`); + continue; + } + this.#failedServers.add(serverName); + debugLog(`WARN: Failed to initialize connection to server "${serverName}": ${String(error)}`); + continue; + } + } + if (this.#onConnectionError === "ignore" && Object.keys(this.#serverNameToTools).length === 0) debugLog(`WARN: No servers successfully connected. All connection attempts failed.`); + return this.#serverNameToTools; + } + async getTools(...args) { + if (args.length === 0 || args.every((arg) => typeof arg === "string")) { + await this.initializeConnections(); + const servers$1 = args; + return servers$1.length === 0 ? this._getAllToolsAsFlatArray() : this._getToolsFromServers(servers$1); + } + const [servers, options] = args; + await this.initializeConnections(options); + return servers.length === 0 ? this._getAllToolsAsFlatArray() : this._getToolsFromServers(servers); + } + async setLoggingLevel(...args) { + if (args.length === 1 && typeof args[0] === "string") { + const level$1 = args[0]; + await Promise.all(this.#clientConnections.getAllClients().map((client) => client.setLoggingLevel(level$1))); + return; + } + const [serverName, level] = args; + await this.#clientConnections.get(serverName)?.setLoggingLevel(level); + } + /** + * Get a the MCP client for a specific server. Useful for fetching prompts or resources from that server. + * + * @param serverName - The name of the server + * @returns The client for the server, or undefined if the server is not connected + */ + async getClient(serverName, options) { + await this.initializeConnections(options); + return this.#clientConnections.get({ + serverName, + headers: options?.headers, + authProvider: options?.authProvider + }); + } + async listResources(...args) { + let servers; + let options; + if (args.length === 0 || args.every((arg) => typeof arg === "string")) { + servers = args; + await this.initializeConnections(); + } else { + [servers, options] = args; + await this.initializeConnections(options); + } + const targetServers = servers.length > 0 ? servers : Object.keys(this.#config.mcpServers); + const result = {}; + for (const serverName of targetServers) { + const client = await this.getClient(serverName, options); + if (!client) { + debugLog(`WARN: Server "${serverName}" not found or not connected`); + continue; + } + try { + result[serverName] = (await client.listResources()).resources.map((resource) => ({ + uri: resource.uri, + name: resource.title ?? resource.name, + description: resource.description, + mimeType: resource.mimeType + })); + debugLog(`INFO: Listed ${result[serverName].length} resources from server "${serverName}"`); + } catch (error) { + debugLog(`ERROR: Failed to list resources from server "${serverName}": ${error}`); + result[serverName] = []; + } + } + return result; + } + async listResourceTemplates(...args) { + let servers; + let options; + if (args.length === 0 || args.every((arg) => typeof arg === "string")) { + servers = args; + await this.initializeConnections(); + } else { + [servers, options] = args; + await this.initializeConnections(options); + } + const targetServers = servers.length > 0 ? servers : Object.keys(this.#config.mcpServers); + const result = {}; + for (const serverName of targetServers) { + const client = await this.getClient(serverName, options); + if (!client) { + debugLog(`WARN: Server "${serverName}" not found or not connected`); + continue; + } + try { + result[serverName] = (await client.listResourceTemplates()).resourceTemplates.map((template) => ({ + uriTemplate: template.uriTemplate, + name: template.title ?? template.name, + description: template.description, + mimeType: template.mimeType + })); + debugLog(`INFO: Listed ${result[serverName].length} resource templates from server "${serverName}"`); + } catch (error) { + debugLog(`ERROR: Failed to list resource templates from server "${serverName}": ${error}`); + result[serverName] = []; + } + } + return result; + } + /** + * Read a resource from a specific server. + * + * @param serverName - The name of the server to read the resource from + * @param uri - The URI of the resource to read + * @param options - Optional connection options for reading the resource, e.g. custom auth provider or headers. + * @returns The resource contents + * + * @example + * ```ts + * const content = await client.readResource("server1", "file://path/to/resource"); + * ``` + */ + async readResource(serverName, uri, options) { + await this.initializeConnections(options); + const client = await this.getClient(serverName, options); + if (!client) throw new MCPClientError(`Server "${serverName}" not found or not connected`, serverName); + try { + debugLog(`INFO: Reading resource "${uri}" from server "${serverName}"`); + return (await client.readResource({ uri })).contents.map((content) => ({ + uri: content.uri, + mimeType: content.mimeType, + text: "text" in content ? content.text : void 0, + blob: "blob" in content ? content.blob : void 0 + })); + } catch (error) { + throw new MCPClientError(`Failed to read resource "${uri}" from server "${serverName}": ${error}`, serverName); + } + } + /** + * Close all connections. + */ + async close() { + debugLog(`INFO: Closing all MCP connections...`); + this.#serverNameToTools = {}; + this.#failedServers.clear(); + await this.#clientConnections.delete(); + debugLog(`INFO: All MCP connections closed`); + } + /** + * Initialize a connection to a specific server + */ + async _initializeConnection(serverName, connection, customTransportOptions) { + if (isResolvedStdioConnection(connection)) { + debugLog(`INFO: Initializing stdio connection to server "${serverName}"...`); + /** + * check if we already initialized this stdio connection + */ + if (this.#clientConnections.has(serverName)) return; + await this._initializeStdioConnection(serverName, connection); + } else if (isResolvedStreamableHTTPConnection(connection)) { + /** + * Users may want to use different connection options for tool calls or tool discovery. + */ + const { authProvider, headers } = customTransportOptions ?? {}; + const updatedConnection = { + ...connection, + authProvider: authProvider ?? connection.authProvider, + headers: { + ...headers, + ...connection.headers + } + }; + /** + * check if we already initialized this streamable HTTP connection + */ + const key = { + serverName, + headers: updatedConnection.headers, + authProvider: updatedConnection.authProvider + }; + if (this.#clientConnections.has(key)) return; + if (connection.type === "sse" || connection.transport === "sse") await this._initializeSSEConnection(serverName, updatedConnection); + else await this._initializeStreamableHTTPConnection(serverName, updatedConnection); + } else throw new MCPClientError(`Unsupported transport type for server "${serverName}"`, serverName); + } + /** + * Initialize a stdio connection + */ + async _initializeStdioConnection(serverName, connection) { + const { command, args, restart } = connection; + debugLog(`DEBUG: Creating stdio transport for server "${serverName}" with command: ${command} ${args.join(" ")}`); + try { + const client = await this.#clientConnections.createClient("stdio", serverName, connection); + const transport = this.#clientConnections.getTransport({ serverName }); + if (restart?.enabled) this._setupStdioRestart(serverName, transport, connection, restart); + await this._loadToolsForServer(serverName, client); + } catch (error) { + throw new MCPClientError(`Failed to connect to stdio server "${serverName}": ${error}`, serverName); + } + } + /** + * Set up stdio restart handling + */ + _setupStdioRestart(serverName, transport, connection, restart) { + const originalOnClose = transport.onclose; + transport.onclose = async () => { + if (originalOnClose) await originalOnClose(); + if (this.#clientConnections.get(serverName)) { + debugLog(`INFO: Process for server "${serverName}" exited, attempting to restart...`); + await this._attemptReconnect(serverName, connection, restart.maxAttempts, restart.delayMs); + } + }; + } + _getHttpErrorCode(error) { + const streamableError = error; + let { code } = streamableError; + if (code == null) { + const m = streamableError.message.match(/\(HTTP (\d\d\d)\)/); + if (m && m.length > 1) code = parseInt(m[1], 10); + } + return code; + } + _createAuthenticationErrorMessage(serverName, url, transport, originalError) { + return `Authentication failed for ${transport} server "${serverName}" at ${url}. Please check your credentials, authorization headers, or OAuth configuration. Original error: ${originalError}`; + } + _toSSEConnectionURL(url) { + const urlObj = new URL(url); + const pathnameParts = urlObj.pathname.split("/"); + const lastPart = pathnameParts.at(-1); + if (lastPart && lastPart === "mcp") pathnameParts[pathnameParts.length - 1] = "sse"; + urlObj.pathname = pathnameParts.join("/"); + return urlObj.toString(); + } + /** + * Initialize a streamable HTTP connection + */ + async _initializeStreamableHTTPConnection(serverName, connection) { + const { url, type: typeField, transport: transportField } = connection; + const automaticSSEFallback = connection.automaticSSEFallback ?? true; + const transportType = typeField || transportField; + debugLog(`DEBUG: Creating Streamable HTTP transport for server "${serverName}" with URL: ${url}`); + if (transportType === "http" || transportType == null) try { + const client = await this.#clientConnections.createClient("http", serverName, connection); + await this._loadToolsForServer(serverName, client); + } catch (error) { + const code = this._getHttpErrorCode(error); + if (automaticSSEFallback && code != null && code >= 400 && code < 500) try { + await this._initializeSSEConnection(serverName, connection); + } catch (firstSSEError) { + const sseUrl = this._toSSEConnectionURL(url); + if (sseUrl !== url) try { + await this._initializeSSEConnection(serverName, { + ...connection, + url: sseUrl + }); + } catch (secondSSEError) { + if (code === 401) throw new MCPClientError(this._createAuthenticationErrorMessage(serverName, url, "HTTP", `${error}. Also tried SSE fallback at ${url} and ${sseUrl}, but both failed with authentication errors.`), serverName); + throw new MCPClientError(`Failed to connect to streamable HTTP server "${serverName}, url: ${url}": ${error}. Additionally, tried falling back to SSE at ${url} and ${sseUrl}, but this also failed: ${secondSSEError}`, serverName); + } + else { + if (code === 401) throw new MCPClientError(this._createAuthenticationErrorMessage(serverName, url, "HTTP", `${error}. Also tried SSE fallback at ${url}, but it failed with authentication error: ${firstSSEError}`), serverName); + throw new MCPClientError(`Failed to connect to streamable HTTP server after trying to fall back to SSE: "${serverName}, url: ${url}": ${error} (SSE fallback failed with error ${firstSSEError})`, serverName); + } + } + else { + if (code === 401) throw new MCPClientError(this._createAuthenticationErrorMessage(serverName, url, "HTTP", `${error}`), serverName); + throw new MCPClientError(`Failed to connect to streamable HTTP server "${serverName}, url: ${url}": ${error}`, serverName); + } + } + } + /** + * Initialize an SSE connection + * + * Don't call this directly unless SSE transport is explicitly requested. Otherwise, + * use _initializeStreamableHTTPConnection and it'll fall back to SSE if needed for + * backwards compatibility. + * + * @param serverName - The name of the server + * @param connection - The connection configuration + */ + async _initializeSSEConnection(serverName, connection) { + const { url, headers, reconnect, authProvider } = connection; + try { + const client = await this.#clientConnections.createClient("sse", serverName, connection); + const transport = this.#clientConnections.getTransport({ + serverName, + headers, + authProvider + }); + if (reconnect?.enabled) this._setupSSEReconnect(serverName, transport, connection, reconnect); + await this._loadToolsForServer(serverName, client); + } catch (error) { + if (error && error.name === "MCPClientError") throw error; + if (error && this._getHttpErrorCode(error) === 401) throw new MCPClientError(this._createAuthenticationErrorMessage(serverName, url, "SSE", `${error}`), serverName); + throw new MCPClientError(`Failed to create SSE transport for server "${serverName}, url: ${url}": ${error}`, serverName); + } + } + /** + * Set up reconnect handling for SSE (Streamable HTTP reconnects are more complex and are handled internally by the SDK) + */ + _setupSSEReconnect(serverName, transport, connection, reconnect) { + const originalOnClose = transport.onclose; + transport.onclose = async () => { + if (originalOnClose) await originalOnClose(); + if (this.#clientConnections.get({ + serverName, + headers: connection.headers, + authProvider: connection.authProvider + })) { + debugLog(`INFO: HTTP connection for server "${serverName}" closed, attempting to reconnect...`); + await this._attemptReconnect(serverName, connection, reconnect.maxAttempts, reconnect.delayMs); + } + }; + } + /** + * Load tools for a specific server + */ + async _loadToolsForServer(serverName, client) { + try { + debugLog(`DEBUG: Loading tools for server "${serverName}"...`); + const tools = await loadMcpTools(serverName, client, this.#loadToolsOptions[serverName]); + this.#serverNameToTools[serverName] = tools; + debugLog(`INFO: Successfully loaded ${tools.length} tools from server "${serverName}"`); + } catch (error) { + throw new MCPClientError(`Failed to load tools from server "${serverName}": ${error}`); + } + } + /** + * Attempt to reconnect to a server after a connection failure. + * + * @param serverName - The name of the server to reconnect to + * @param connection - The connection configuration + * @param maxAttempts - Maximum number of reconnection attempts + * @param delayMs - Delay in milliseconds between reconnection attempts + * @private + */ + async _attemptReconnect(serverName, connection, maxAttempts = 3, delayMs = 1e3) { + let connected = false; + let attempts = 0; + if ("headers" in connection || "authProvider" in connection) { + const { headers, authProvider } = connection; + await this.#cleanupServerResources({ + serverName, + authProvider, + headers + }); + } else await this.#cleanupServerResources({ serverName }); + while (!connected && (maxAttempts === void 0 || attempts < maxAttempts)) { + attempts += 1; + debugLog(`INFO: Reconnection attempt ${attempts}${maxAttempts ? `/${maxAttempts}` : ""} for server "${serverName}"`); + try { + if (delayMs) await new Promise((resolve) => { + setTimeout(resolve, delayMs); + }); + if (isResolvedStdioConnection(connection)) await this._initializeStdioConnection(serverName, connection); + else if (isResolvedStreamableHTTPConnection(connection)) if (connection.type === "sse" || connection.transport === "sse") await this._initializeSSEConnection(serverName, connection); + else await this._initializeStreamableHTTPConnection(serverName, connection); + const key = "headers" in connection ? { + serverName, + headers: connection.headers, + authProvider: connection.authProvider + } : { serverName }; + if (this.#clientConnections.has(key)) { + connected = true; + debugLog(`INFO: Successfully reconnected to server "${serverName}"`); + } + } catch (error) { + debugLog(`ERROR: Failed to reconnect to server "${serverName}" (attempt ${attempts}): ${error}`); + } + } + if (!connected) debugLog(`ERROR: Failed to reconnect to server "${serverName}" after ${attempts} attempts`); + } + /** + * Clean up resources for a specific server + */ + async #cleanupServerResources(transportOptions) { + const { serverName, authProvider, headers } = transportOptions; + delete this.#serverNameToTools[serverName]; + await this.#clientConnections.delete({ + serverName, + authProvider, + headers + }); + } + /** + * Get all tools from all servers as a flat array. + * + * @returns A flattened array of all tools + */ + _getAllToolsAsFlatArray() { + const allTools = []; + for (const tools of Object.values(this.#serverNameToTools)) allTools.push(...tools); + return allTools; + } + /** + * Get tools from specific servers as a flat array. + * + * @param serverNames - Names of servers to get tools from + * @returns A flattened array of tools from the specified servers + */ + _getToolsFromServers(serverNames) { + const allTools = []; + for (const serverName of serverNames) { + const tools = this.#serverNameToTools[serverName]; + if (tools) allTools.push(...tools); + } + return allTools; + } +}; +//#endregion +//#region node_modules/@langchain/mcp-adapters/dist/index.js +var dist_exports = /* @__PURE__ */ __exportAll({ MultiServerMCPClient: () => MultiServerMCPClient }); +//#endregion +export { string as i, boolean as n, number as r, dist_exports as t }; diff --git a/.vercel/output/functions/__server.func/_libs/@langchain/ollama+[...].mjs b/.vercel/output/functions/__server.func/_libs/@langchain/ollama+[...].mjs new file mode 100644 index 0000000..71f260e --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/@langchain/ollama+[...].mjs @@ -0,0 +1,1748 @@ +import { r as __exportAll } from "../../_runtime.mjs"; +import { Gt as concat, It as isInteropZodSchema, Sn as AIMessageChunk, Tt as isSerializableSchema, _ as createFunctionCallingParser, bn as getEnvironmentVariable, f as finalizeContentBlock, g as createContentParser, h as assembleStructuredOutputPipeline, l as BaseChatModel, n as convertToOpenAITool, pn as v4, rt as toJsonSchema, xn as AIMessage, zt as ChatGenerationChunk } from "./anthropic+[...].mjs"; +import "../langchain__core+mustache.mjs"; +//#region node_modules/@langchain/ollama/dist/utils/stream_events.js +/** +* Converts Ollama chat stream chunks into LangChain ChatModelStreamEvents. +* +* @module +*/ +async function* convertOllamaStream(source, options = {}) { + const shouldStreamUsage = options.streamUsage ?? true; + const preferThinking = options.think ?? false; + const blockAccumulators = /* @__PURE__ */ new Map(); + const blockKeyToIndex = /* @__PURE__ */ new Map(); + let nextBlockIndex = 0; + let messageStarted = false; + let usageSnapshot; + let finishReason; + const getOrCreateBlockIndex = (key, initial) => { + const existing = blockKeyToIndex.get(key); + if (existing !== void 0) return { + index: existing, + isNew: false + }; + const index = nextBlockIndex++; + blockKeyToIndex.set(key, index); + blockAccumulators.set(index, { ...initial }); + return { + index, + isNew: true + }; + }; + for await (const chunk of source) { + if (!messageStarted) { + messageStarted = true; + yield { event: "message-start" }; + } + if (shouldStreamUsage) { + const input = chunk.prompt_eval_count ?? 0; + const output = chunk.eval_count ?? 0; + if (input > 0 || output > 0) { + usageSnapshot = { + input_tokens: input, + output_tokens: output, + total_tokens: input + output + }; + yield { + event: "usage", + usage: usageSnapshot + }; + } + } + if (chunk.done_reason) finishReason = mapOllamaDoneReason(chunk.done_reason); + const { message } = chunk; + if (preferThinking && message.thinking) { + const { index, isNew } = getOrCreateBlockIndex("reasoning", { + type: "reasoning", + reasoning: "" + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "reasoning", + reasoning: "" + } + }; + const acc = blockAccumulators.get(index); + acc.reasoning = (acc.reasoning ?? "") + message.thinking; + yield { + event: "content-block-delta", + index, + delta: { + type: "reasoning-delta", + reasoning: message.thinking + } + }; + } + if (message.content) { + const { index, isNew } = getOrCreateBlockIndex("text", { + type: "text", + text: "" + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "text", + text: "" + } + }; + const acc = blockAccumulators.get(index); + acc.text = (acc.text ?? "") + message.content; + yield { + event: "content-block-delta", + index, + delta: { + type: "text-delta", + text: message.content + } + }; + } + if (message.tool_calls?.length) for (let i = 0; i < message.tool_calls.length; i++) { + const tc = message.tool_calls[i]; + const key = `tool:${i}`; + const args = typeof tc.function.arguments === "string" ? tc.function.arguments : JSON.stringify(tc.function.arguments); + const { index, isNew } = getOrCreateBlockIndex(key, { + type: "tool_call_chunk", + name: tc.function.name, + args: "", + index: i + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "tool_call_chunk", + name: tc.function.name, + args: "", + index: i + } + }; + const acc = blockAccumulators.get(index); + acc.name = tc.function.name; + acc.args = args; + yield { + event: "content-block-delta", + index, + delta: { + type: "block-delta", + fields: { + type: "tool_call_chunk", + name: acc.name, + args: acc.args + } + } + }; + } + } + for (const [index, acc] of blockAccumulators) yield { + event: "content-block-finish", + index, + content: finalizeContentBlock(acc) + }; + yield { + event: "message-finish", + reason: finishReason, + ...usageSnapshot ? { usage: usageSnapshot } : {}, + responseMetadata: { model_provider: "ollama" } + }; +} +function mapOllamaDoneReason(reason) { + switch (reason) { + case "stop": return "stop"; + case "length": return "length"; + default: return "stop"; + } +} +//#endregion +//#region node_modules/@langchain/ollama/dist/utils.js +function convertOllamaMessagesToLangChain(messages, extra) { + return new AIMessageChunk({ + content: messages.content ?? "", + additional_kwargs: messages.thinking && messages.thinking !== "" ? { reasoning_content: messages.thinking } : {}, + tool_call_chunks: messages.tool_calls?.map((tc) => ({ + name: tc.function.name, + args: JSON.stringify(tc.function.arguments), + type: "tool_call_chunk", + index: 0, + id: v4() + })), + response_metadata: { + ...extra?.responseMetadata, + model_provider: "ollama" + }, + usage_metadata: extra?.usageMetadata + }); +} +function extractBase64FromDataUrl(dataUrl) { + const match = dataUrl.match(/^data:.*?;base64,(.*)$/); + return match ? match[1] : ""; +} +function convertAMessagesToOllama(messages) { + if (typeof messages.content === "string") { + if (messages.tool_calls?.length) { + const toolCalls = messages.tool_calls.map((tc) => ({ + id: tc.id, + type: "function", + function: { + name: tc.name, + arguments: tc.args + } + })); + return [{ + role: "assistant", + content: messages.content, + tool_calls: toolCalls + }]; + } + return [{ + role: "assistant", + content: messages.content + }]; + } + const textMessages = messages.content.filter((c) => c.type === "text" && typeof c.text === "string").map((c) => ({ + role: "assistant", + content: c.text + })); + let toolCallMsgs; + if (messages.content.find((c) => c.type === "tool_use") && messages.tool_calls?.length) { + const toolCalls = messages.tool_calls?.map((tc) => ({ + id: tc.id, + type: "function", + function: { + name: tc.name, + arguments: tc.args + } + })); + if (toolCalls) toolCallMsgs = { + role: "assistant", + tool_calls: toolCalls, + content: "" + }; + } else if (messages.content.find((c) => c.type === "tool_use") && !messages.tool_calls?.length) throw new Error("'tool_use' content type is not supported without tool calls."); + return [...textMessages, ...toolCallMsgs ? [toolCallMsgs] : []]; +} +function convertHumanGenericMessagesToOllama(message) { + if (typeof message.content === "string") return [{ + role: "user", + content: message.content + }]; + return message.content.map((c) => { + if (c.type === "text") return { + role: "user", + content: c.text + }; + else if (c.type === "image_url") { + if (typeof c.image_url === "string") return { + role: "user", + content: "", + images: [extractBase64FromDataUrl(c.image_url)] + }; + else if (c.image_url.url && typeof c.image_url.url === "string") return { + role: "user", + content: "", + images: [extractBase64FromDataUrl(c.image_url.url)] + }; + } + throw new Error(`Unsupported content type: ${c.type}`); + }); +} +function convertSystemMessageToOllama(message) { + if (typeof message.content === "string") return [{ + role: "system", + content: message.content + }]; + else if (message.content.every((c) => c.type === "text" && typeof c.text === "string")) return message.content.map((c) => ({ + role: "system", + content: c.text + })); + else throw new Error(`Unsupported content type(s): ${message.content.map((c) => c.type).join(", ")}`); +} +function convertToolMessageToOllama(message) { + if (typeof message.content !== "string") throw new Error("Non string tool message content is not supported"); + return [{ + role: "tool", + content: message.content + }]; +} +function convertToOllamaMessages(messages) { + return messages.flatMap((msg) => { + if (["human", "generic"].includes(msg._getType())) return convertHumanGenericMessagesToOllama(msg); + else if (msg._getType() === "ai") return convertAMessagesToOllama(msg); + else if (msg._getType() === "system") return convertSystemMessageToOllama(msg); + else if (msg._getType() === "tool") return convertToolMessageToOllama(msg); + else throw new Error(`Unsupported message type: ${msg._getType()}`); + }); +} +//#endregion +//#region node_modules/whatwg-fetch/fetch.js +var g = typeof globalThis !== "undefined" && globalThis || typeof self !== "undefined" && self || typeof global !== "undefined" && global || {}; +var support = { + searchParams: "URLSearchParams" in g, + iterable: "Symbol" in g && "iterator" in Symbol, + blob: "FileReader" in g && "Blob" in g && (function() { + try { + new Blob(); + return true; + } catch (e) { + return false; + } + })(), + formData: "FormData" in g, + arrayBuffer: "ArrayBuffer" in g +}; +function isDataView(obj) { + return obj && DataView.prototype.isPrototypeOf(obj); +} +if (support.arrayBuffer) { + var viewClasses = [ + "[object Int8Array]", + "[object Uint8Array]", + "[object Uint8ClampedArray]", + "[object Int16Array]", + "[object Uint16Array]", + "[object Int32Array]", + "[object Uint32Array]", + "[object Float32Array]", + "[object Float64Array]" + ]; + var isArrayBufferView = ArrayBuffer.isView || function(obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1; + }; +} +function normalizeName(name) { + if (typeof name !== "string") name = String(name); + if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === "") throw new TypeError("Invalid character in header field name: \"" + name + "\""); + return name.toLowerCase(); +} +function normalizeValue(value) { + if (typeof value !== "string") value = String(value); + return value; +} +function iteratorFor(items) { + var iterator = { next: function() { + var value = items.shift(); + return { + done: value === void 0, + value + }; + } }; + if (support.iterable) iterator[Symbol.iterator] = function() { + return iterator; + }; + return iterator; +} +function Headers$1(headers) { + this.map = {}; + if (headers instanceof Headers$1) headers.forEach(function(value, name) { + this.append(name, value); + }, this); + else if (Array.isArray(headers)) headers.forEach(function(header) { + if (header.length != 2) throw new TypeError("Headers constructor: expected name/value pair to be length 2, found" + header.length); + this.append(header[0], header[1]); + }, this); + else if (headers) Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]); + }, this); +} +Headers$1.prototype.append = function(name, value) { + name = normalizeName(name); + value = normalizeValue(value); + var oldValue = this.map[name]; + this.map[name] = oldValue ? oldValue + ", " + value : value; +}; +Headers$1.prototype["delete"] = function(name) { + delete this.map[normalizeName(name)]; +}; +Headers$1.prototype.get = function(name) { + name = normalizeName(name); + return this.has(name) ? this.map[name] : null; +}; +Headers$1.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)); +}; +Headers$1.prototype.set = function(name, value) { + this.map[normalizeName(name)] = normalizeValue(value); +}; +Headers$1.prototype.forEach = function(callback, thisArg) { + for (var name in this.map) if (this.map.hasOwnProperty(name)) callback.call(thisArg, this.map[name], name, this); +}; +Headers$1.prototype.keys = function() { + var items = []; + this.forEach(function(value, name) { + items.push(name); + }); + return iteratorFor(items); +}; +Headers$1.prototype.values = function() { + var items = []; + this.forEach(function(value) { + items.push(value); + }); + return iteratorFor(items); +}; +Headers$1.prototype.entries = function() { + var items = []; + this.forEach(function(value, name) { + items.push([name, value]); + }); + return iteratorFor(items); +}; +if (support.iterable) Headers$1.prototype[Symbol.iterator] = Headers$1.prototype.entries; +function consumed(body) { + if (body._noBody) return; + if (body.bodyUsed) return Promise.reject(/* @__PURE__ */ new TypeError("Already read")); + body.bodyUsed = true; +} +function fileReaderReady(reader) { + return new Promise(function(resolve, reject) { + reader.onload = function() { + resolve(reader.result); + }; + reader.onerror = function() { + reject(reader.error); + }; + }); +} +function readBlobAsArrayBuffer(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsArrayBuffer(blob); + return promise; +} +function readBlobAsText(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + var match = /charset=([A-Za-z0-9_-]+)/.exec(blob.type); + var encoding = match ? match[1] : "utf-8"; + reader.readAsText(blob, encoding); + return promise; +} +function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf); + var chars = new Array(view.length); + for (var i = 0; i < view.length; i++) chars[i] = String.fromCharCode(view[i]); + return chars.join(""); +} +function bufferClone(buf) { + if (buf.slice) return buf.slice(0); + else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer; + } +} +function Body() { + this.bodyUsed = false; + this._initBody = function(body) { + this.bodyUsed = this.bodyUsed; + this._bodyInit = body; + if (!body) { + this._noBody = true; + this._bodyText = ""; + } else if (typeof body === "string") this._bodyText = body; + else if (support.blob && Blob.prototype.isPrototypeOf(body)) this._bodyBlob = body; + else if (support.formData && FormData.prototype.isPrototypeOf(body)) this._bodyFormData = body; + else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) this._bodyText = body.toString(); + else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) this._bodyArrayBuffer = bufferClone(body); + else this._bodyText = body = Object.prototype.toString.call(body); + if (!this.headers.get("content-type")) { + if (typeof body === "string") this.headers.set("content-type", "text/plain;charset=UTF-8"); + else if (this._bodyBlob && this._bodyBlob.type) this.headers.set("content-type", this._bodyBlob.type); + else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8"); + } + }; + if (support.blob) this.blob = function() { + var rejected = consumed(this); + if (rejected) return rejected; + if (this._bodyBlob) return Promise.resolve(this._bodyBlob); + else if (this._bodyArrayBuffer) return Promise.resolve(new Blob([this._bodyArrayBuffer])); + else if (this._bodyFormData) throw new Error("could not read FormData body as blob"); + else return Promise.resolve(new Blob([this._bodyText])); + }; + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + var isConsumed = consumed(this); + if (isConsumed) return isConsumed; + else if (ArrayBuffer.isView(this._bodyArrayBuffer)) return Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset, this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength)); + else return Promise.resolve(this._bodyArrayBuffer); + } else if (support.blob) return this.blob().then(readBlobAsArrayBuffer); + else throw new Error("could not read as ArrayBuffer"); + }; + this.text = function() { + var rejected = consumed(this); + if (rejected) return rejected; + if (this._bodyBlob) return readBlobAsText(this._bodyBlob); + else if (this._bodyArrayBuffer) return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)); + else if (this._bodyFormData) throw new Error("could not read FormData body as text"); + else return Promise.resolve(this._bodyText); + }; + if (support.formData) this.formData = function() { + return this.text().then(decode); + }; + this.json = function() { + return this.text().then(JSON.parse); + }; + return this; +} +var methods = [ + "CONNECT", + "DELETE", + "GET", + "HEAD", + "OPTIONS", + "PATCH", + "POST", + "PUT", + "TRACE" +]; +function normalizeMethod(method) { + var upcased = method.toUpperCase(); + return methods.indexOf(upcased) > -1 ? upcased : method; +} +function Request(input, options) { + if (!(this instanceof Request)) throw new TypeError("Please use the \"new\" operator, this DOM object constructor cannot be called as a function."); + options = options || {}; + var body = options.body; + if (input instanceof Request) { + if (input.bodyUsed) throw new TypeError("Already read"); + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) this.headers = new Headers$1(input.headers); + this.method = input.method; + this.mode = input.mode; + this.signal = input.signal; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else this.url = String(input); + this.credentials = options.credentials || this.credentials || "same-origin"; + if (options.headers || !this.headers) this.headers = new Headers$1(options.headers); + this.method = normalizeMethod(options.method || this.method || "GET"); + this.mode = options.mode || this.mode || null; + this.signal = options.signal || this.signal || function() { + if ("AbortController" in g) return new AbortController().signal; + }(); + this.referrer = null; + if ((this.method === "GET" || this.method === "HEAD") && body) throw new TypeError("Body not allowed for GET or HEAD requests"); + this._initBody(body); + if (this.method === "GET" || this.method === "HEAD") { + if (options.cache === "no-store" || options.cache === "no-cache") { + var reParamSearch = /([?&])_=[^&]*/; + if (reParamSearch.test(this.url)) this.url = this.url.replace(reParamSearch, "$1_=" + (/* @__PURE__ */ new Date()).getTime()); + else { + var reQueryString = /\?/; + this.url += (reQueryString.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime(); + } + } + } +} +Request.prototype.clone = function() { + return new Request(this, { body: this._bodyInit }); +}; +function decode(body) { + var form = new FormData(); + body.trim().split("&").forEach(function(bytes) { + if (bytes) { + var split = bytes.split("="); + var name = split.shift().replace(/\+/g, " "); + var value = split.join("=").replace(/\+/g, " "); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + return form; +} +function parseHeaders(rawHeaders) { + var headers = new Headers$1(); + rawHeaders.replace(/\r?\n[\t ]+/g, " ").split("\r").map(function(header) { + return header.indexOf("\n") === 0 ? header.substr(1, header.length) : header; + }).forEach(function(line) { + var parts = line.split(":"); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(":").trim(); + try { + headers.append(key, value); + } catch (error) { + console.warn("Response " + error.message); + } + } + }); + return headers; +} +Body.call(Request.prototype); +function Response(bodyInit, options) { + if (!(this instanceof Response)) throw new TypeError("Please use the \"new\" operator, this DOM object constructor cannot be called as a function."); + if (!options) options = {}; + this.type = "default"; + this.status = options.status === void 0 ? 200 : options.status; + if (this.status < 200 || this.status > 599) throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599]."); + this.ok = this.status >= 200 && this.status < 300; + this.statusText = options.statusText === void 0 ? "" : "" + options.statusText; + this.headers = new Headers$1(options.headers); + this.url = options.url || ""; + this._initBody(bodyInit); +} +Body.call(Response.prototype); +Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers$1(this.headers), + url: this.url + }); +}; +Response.error = function() { + var response = new Response(null, { + status: 200, + statusText: "" + }); + response.ok = false; + response.status = 0; + response.type = "error"; + return response; +}; +var redirectStatuses = [ + 301, + 302, + 303, + 307, + 308 +]; +Response.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) throw new RangeError("Invalid status code"); + return new Response(null, { + status, + headers: { location: url } + }); +}; +var DOMException = g.DOMException; +try { + new DOMException(); +} catch (err) { + DOMException = function(message, name) { + this.message = message; + this.name = name; + var error = Error(message); + this.stack = error.stack; + }; + DOMException.prototype = Object.create(Error.prototype); + DOMException.prototype.constructor = DOMException; +} +function fetch$1(input, init) { + return new Promise(function(resolve, reject) { + var request = new Request(input, init); + if (request.signal && request.signal.aborted) return reject(new DOMException("Aborted", "AbortError")); + var xhr = new XMLHttpRequest(); + function abortXhr() { + xhr.abort(); + } + xhr.onload = function() { + var options = { + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || "") + }; + if (request.url.indexOf("file://") === 0 && (xhr.status < 200 || xhr.status > 599)) options.status = 200; + else options.status = xhr.status; + options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL"); + var body = "response" in xhr ? xhr.response : xhr.responseText; + setTimeout(function() { + resolve(new Response(body, options)); + }, 0); + }; + xhr.onerror = function() { + setTimeout(function() { + reject(/* @__PURE__ */ new TypeError("Network request failed")); + }, 0); + }; + xhr.ontimeout = function() { + setTimeout(function() { + reject(/* @__PURE__ */ new TypeError("Network request timed out")); + }, 0); + }; + xhr.onabort = function() { + setTimeout(function() { + reject(new DOMException("Aborted", "AbortError")); + }, 0); + }; + function fixUrl(url) { + try { + return url === "" && g.location.href ? g.location.href : url; + } catch (e) { + return url; + } + } + xhr.open(request.method, fixUrl(request.url), true); + if (request.credentials === "include") xhr.withCredentials = true; + else if (request.credentials === "omit") xhr.withCredentials = false; + if ("responseType" in xhr) { + if (support.blob) xhr.responseType = "blob"; + else if (support.arrayBuffer) xhr.responseType = "arraybuffer"; + } + if (init && typeof init.headers === "object" && !(init.headers instanceof Headers$1 || g.Headers && init.headers instanceof g.Headers)) { + var names = []; + Object.getOwnPropertyNames(init.headers).forEach(function(name) { + names.push(normalizeName(name)); + xhr.setRequestHeader(name, normalizeValue(init.headers[name])); + }); + request.headers.forEach(function(value, name) { + if (names.indexOf(name) === -1) xhr.setRequestHeader(name, value); + }); + } else request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value); + }); + if (request.signal) { + request.signal.addEventListener("abort", abortXhr); + xhr.onreadystatechange = function() { + if (xhr.readyState === 4) request.signal.removeEventListener("abort", abortXhr); + }; + } + xhr.send(typeof request._bodyInit === "undefined" ? null : request._bodyInit); + }); +} +fetch$1.polyfill = true; +if (!g.fetch) { + g.fetch = fetch$1; + g.Headers = Headers$1; + g.Request = Request; + g.Response = Response; +} +//#endregion +//#region node_modules/ollama/dist/browser.mjs +var defaultPort = "11434"; +var defaultHost = `http://127.0.0.1:${defaultPort}`; +var version = "0.6.3"; +var __defProp$1 = Object.defineProperty; +var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { + enumerable: true, + configurable: true, + writable: true, + value +}) : obj[key] = value; +var __publicField$1 = (obj, key, value) => { + __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +var ResponseError = class ResponseError extends Error { + constructor(error, status_code) { + super(error); + this.error = error; + this.status_code = status_code; + this.name = "ResponseError"; + if (Error.captureStackTrace) Error.captureStackTrace(this, ResponseError); + } +}; +var AbortableAsyncIterator = class { + constructor(abortController, itr, doneCallback) { + __publicField$1(this, "abortController"); + __publicField$1(this, "itr"); + __publicField$1(this, "doneCallback"); + this.abortController = abortController; + this.itr = itr; + this.doneCallback = doneCallback; + } + abort() { + this.abortController.abort(); + } + async *[Symbol.asyncIterator]() { + for await (const message of this.itr) { + if ("error" in message) throw new Error(message.error); + yield message; + if (message.done || message.status === "success") { + this.doneCallback(); + return; + } + } + throw new Error("Did not receive done or success response in stream."); + } +}; +var checkOk = async (response) => { + if (response.ok) return; + let message = `Error ${response.status}: ${response.statusText}`; + let errorData = null; + if (response.headers.get("content-type")?.includes("application/json")) try { + errorData = await response.json(); + message = errorData.error || message; + } catch (error) { + console.log("Failed to parse error response as JSON"); + } + else try { + console.log("Getting text from response"); + message = await response.text() || message; + } catch (error) { + console.log("Failed to get text from error response"); + } + throw new ResponseError(message, response.status); +}; +function getPlatform() { + if (typeof window !== "undefined" && window.navigator) { + const nav = navigator; + if ("userAgentData" in nav && nav.userAgentData?.platform) return `${nav.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`; + if (navigator.platform) return `${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`; + return `unknown Browser/${navigator.userAgent};`; + } else if (typeof process !== "undefined") return `${process.arch} ${process.platform} Node.js/${process.version}`; + return ""; +} +function normalizeHeaders(headers) { + if (headers instanceof Headers) { + const obj = {}; + headers.forEach((value, key) => { + obj[key] = value; + }); + return obj; + } else if (Array.isArray(headers)) return Object.fromEntries(headers); + else return headers || {}; +} +var readEnvVar = (obj, key) => { + return obj[key]; +}; +var fetchWithHeaders = async (fetch, url, options = {}) => { + const defaultHeaders = { + "Content-Type": "application/json", + Accept: "application/json", + "User-Agent": `ollama-js/${version} (${getPlatform()})` + }; + options.headers = normalizeHeaders(options.headers); + try { + const parsed = new URL(url); + if (parsed.protocol === "https:" && parsed.hostname === "ollama.com") { + const apiKey = typeof process === "object" && process !== null && typeof process.env === "object" && process.env !== null ? readEnvVar(process.env, "OLLAMA_API_KEY") : void 0; + if (!(options.headers["authorization"] || options.headers["Authorization"]) && apiKey) options.headers["Authorization"] = `Bearer ${apiKey}`; + } + } catch (error) { + console.error("error parsing url", error); + } + const customHeaders = Object.fromEntries(Object.entries(options.headers).filter(([key]) => !Object.keys(defaultHeaders).some((defaultKey) => defaultKey.toLowerCase() === key.toLowerCase()))); + options.headers = { + ...defaultHeaders, + ...customHeaders + }; + return fetch(url, options); +}; +var get = async (fetch, host, options) => { + const response = await fetchWithHeaders(fetch, host, { headers: options?.headers }); + await checkOk(response); + return response; +}; +var post = async (fetch, host, data, options) => { + const isRecord = (input) => { + return input !== null && typeof input === "object" && !Array.isArray(input); + }; + const response = await fetchWithHeaders(fetch, host, { + method: "POST", + body: isRecord(data) ? JSON.stringify(data) : data, + signal: options?.signal, + headers: options?.headers + }); + await checkOk(response); + return response; +}; +var del = async (fetch, host, data, options) => { + const response = await fetchWithHeaders(fetch, host, { + method: "DELETE", + body: JSON.stringify(data), + headers: options?.headers + }); + await checkOk(response); + return response; +}; +var parseJSON = async function* (itr) { + const decoder = new TextDecoder("utf-8"); + let buffer = ""; + const reader = itr.getReader(); + while (true) { + const { done, value: chunk } = await reader.read(); + if (done) break; + buffer += decoder.decode(chunk, { stream: true }); + const parts = buffer.split("\n"); + buffer = parts.pop() ?? ""; + for (const part of parts) try { + yield JSON.parse(part); + } catch (error) { + console.warn("invalid json: ", part); + } + } + buffer += decoder.decode(); + for (const part of buffer.split("\n").filter((p) => p !== "")) try { + yield JSON.parse(part); + } catch (error) { + console.warn("invalid json: ", part); + } +}; +var formatHost = (host) => { + if (!host) return defaultHost; + let isExplicitProtocol = host.includes("://"); + if (host.startsWith(":")) { + host = `http://127.0.0.1${host}`; + isExplicitProtocol = true; + } + if (!isExplicitProtocol) host = `http://${host}`; + const url = new URL(host); + let port = url.port; + if (!port) if (!isExplicitProtocol) port = defaultPort; + else port = url.protocol === "https:" ? "443" : "80"; + let auth = ""; + if (url.username) { + auth = url.username; + if (url.password) auth += `:${url.password}`; + auth += "@"; + } + let formattedHost = `${url.protocol}//${auth}${url.hostname}:${port}${url.pathname}`; + if (formattedHost.endsWith("/")) formattedHost = formattedHost.slice(0, -1); + return formattedHost; +}; +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { + enumerable: true, + configurable: true, + writable: true, + value +}) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +var Ollama$1 = class Ollama { + constructor(config) { + __publicField(this, "config"); + __publicField(this, "fetch"); + __publicField(this, "ongoingStreamedRequests", []); + this.config = { + host: "", + headers: config?.headers + }; + if (!config?.proxy) this.config.host = formatHost(config?.host ?? defaultHost); + this.fetch = config?.fetch ?? fetch; + } + abort() { + for (const request of this.ongoingStreamedRequests) request.abort(); + this.ongoingStreamedRequests.length = 0; + } + /** + * Processes a request to the Ollama server. If the request is streamable, it will return a + * AbortableAsyncIterator that yields the response messages. Otherwise, it will return the response + * object. + * @param endpoint {string} - The endpoint to send the request to. + * @param request {object} - The request object to send to the endpoint. + * @protected {T | AbortableAsyncIterator} - The response object or a AbortableAsyncIterator that yields + * response messages. + * @throws {Error} - If the response body is missing or if the response is an error. + * @returns {Promise>} - The response object or a AbortableAsyncIterator that yields the streamed response. + */ + async processStreamableRequest(endpoint, request) { + request.stream = request.stream ?? false; + const host = `${this.config.host}/api/${endpoint}`; + if (request.stream) { + const abortController = new AbortController(); + const response2 = await post(this.fetch, host, request, { + signal: abortController.signal, + headers: this.config.headers + }); + if (!response2.body) throw new Error("Missing body"); + const abortableAsyncIterator = new AbortableAsyncIterator(abortController, parseJSON(response2.body), () => { + const i = this.ongoingStreamedRequests.indexOf(abortableAsyncIterator); + if (i > -1) this.ongoingStreamedRequests.splice(i, 1); + }); + this.ongoingStreamedRequests.push(abortableAsyncIterator); + return abortableAsyncIterator; + } + return await (await post(this.fetch, host, request, { headers: this.config.headers })).json(); + } + /** + * Encodes an image to base64 if it is a Uint8Array. + * @param image {Uint8Array | string} - The image to encode. + * @returns {Promise} - The base64 encoded image. + */ + async encodeImage(image) { + if (typeof image !== "string") { + const uint8Array = new Uint8Array(image); + let byteString = ""; + const len = uint8Array.byteLength; + for (let i = 0; i < len; i++) byteString += String.fromCharCode(uint8Array[i]); + return btoa(byteString); + } + return image; + } + /** + * Generates a response from a text prompt. + * @param request {GenerateRequest} - The request object. + * @returns {Promise>} - The response object or + * an AbortableAsyncIterator that yields response messages. + */ + async generate(request) { + if (request.images) request.images = await Promise.all(request.images.map(this.encodeImage.bind(this))); + return this.processStreamableRequest("generate", request); + } + /** + * Chats with the model. The request object can contain messages with images that are either + * Uint8Arrays or base64 encoded strings. The images will be base64 encoded before sending the + * request. + * @param request {ChatRequest} - The request object. + * @returns {Promise>} - The response object or an + * AbortableAsyncIterator that yields response messages. + */ + async chat(request) { + if (request.messages) { + for (const message of request.messages) if (message.images) message.images = await Promise.all(message.images.map(this.encodeImage.bind(this))); + } + return this.processStreamableRequest("chat", request); + } + /** + * Creates a new model from a stream of data. + * @param request {CreateRequest} - The request object. + * @returns {Promise>} - The response object or a stream of progress responses. + */ + async create(request) { + return this.processStreamableRequest("create", { ...request }); + } + /** + * Pulls a model from the Ollama registry. The request object can contain a stream flag to indicate if the + * response should be streamed. + * @param request {PullRequest} - The request object. + * @returns {Promise>} - The response object or + * an AbortableAsyncIterator that yields response messages. + */ + async pull(request) { + return this.processStreamableRequest("pull", { + name: request.model, + stream: request.stream, + insecure: request.insecure + }); + } + /** + * Pushes a model to the Ollama registry. The request object can contain a stream flag to indicate if the + * response should be streamed. + * @param request {PushRequest} - The request object. + * @returns {Promise>} - The response object or + * an AbortableAsyncIterator that yields response messages. + */ + async push(request) { + return this.processStreamableRequest("push", { + name: request.model, + stream: request.stream, + insecure: request.insecure + }); + } + /** + * Deletes a model from the server. The request object should contain the name of the model to + * delete. + * @param request {DeleteRequest} - The request object. + * @returns {Promise} - The response object. + */ + async delete(request) { + await del(this.fetch, `${this.config.host}/api/delete`, { name: request.model }, { headers: this.config.headers }); + return { status: "success" }; + } + /** + * Copies a model from one name to another. The request object should contain the name of the + * model to copy and the new name. + * @param request {CopyRequest} - The request object. + * @returns {Promise} - The response object. + */ + async copy(request) { + await post(this.fetch, `${this.config.host}/api/copy`, { ...request }, { headers: this.config.headers }); + return { status: "success" }; + } + /** + * Lists the models on the server. + * @returns {Promise} - The response object. + * @throws {Error} - If the response body is missing. + */ + async list() { + return await (await get(this.fetch, `${this.config.host}/api/tags`, { headers: this.config.headers })).json(); + } + /** + * Shows the metadata of a model. The request object should contain the name of the model. + * @param request {ShowRequest} - The request object. + * @returns {Promise} - The response object. + */ + async show(request) { + return await (await post(this.fetch, `${this.config.host}/api/show`, { ...request }, { headers: this.config.headers })).json(); + } + /** + * Embeds text input into vectors. + * @param request {EmbedRequest} - The request object. + * @returns {Promise} - The response object. + */ + async embed(request) { + return await (await post(this.fetch, `${this.config.host}/api/embed`, { ...request }, { headers: this.config.headers })).json(); + } + /** + * Embeds a text prompt into a vector. + * @param request {EmbeddingsRequest} - The request object. + * @returns {Promise} - The response object. + */ + async embeddings(request) { + return await (await post(this.fetch, `${this.config.host}/api/embeddings`, { ...request }, { headers: this.config.headers })).json(); + } + /** + * Lists the running models on the server + * @returns {Promise} - The response object. + * @throws {Error} - If the response body is missing. + */ + async ps() { + return await (await get(this.fetch, `${this.config.host}/api/ps`, { headers: this.config.headers })).json(); + } + /** + * Returns the Ollama server version. + * @returns {Promise} - The server version object. + */ + async version() { + return await (await get(this.fetch, `${this.config.host}/api/version`, { headers: this.config.headers })).json(); + } + /** + * Performs web search using the Ollama web search API + * @param request {WebSearchRequest} - The search request containing query and options + * @returns {Promise} - The search results + * @throws {Error} - If the request is invalid or the server returns an error + */ + async webSearch(request) { + if (!request.query || request.query.length === 0) throw new Error("Query is required"); + return await (await post(this.fetch, `https://ollama.com/api/web_search`, { ...request }, { headers: this.config.headers })).json(); + } + /** + * Fetches a single page using the Ollama web fetch API + * @param request {WebFetchRequest} - The fetch request containing a URL + * @returns {Promise} - The fetch result + * @throws {Error} - If the request is invalid or the server returns an error + */ + async webFetch(request) { + if (!request.url || request.url.length === 0) throw new Error("URL is required"); + return await (await post(this.fetch, `https://ollama.com/api/web_fetch`, { ...request }, { headers: this.config.headers })).json(); + } +}; +new Ollama$1(); +//#endregion +//#region node_modules/@langchain/ollama/dist/chat_models.js +/** +* Ollama chat model integration. +* +* Setup: +* Install `@langchain/ollama` and the Ollama app. +* +* ```bash +* npm install @langchain/ollama +* export OLLAMA_BASE_URL="http://127.0.0.1:11434" # Optional; defaults to http://127.0.0.1:11434 if not set +* ``` +* +* ## [Constructor args](https://api.js.langchain.com/classes/_langchain_ollama.ChatOllama.html#constructor) +* +* ## [Runtime args](https://api.js.langchain.com/interfaces/_langchain_ollama.ChatOllamaCallOptions.html) +* +* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. +* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: +* +* ```typescript +* // When calling `.withConfig`, call options should be passed via the first argument +* const llmWithArgsBound = llm.withConfig({ +* stop: ["\n"], +* }); +* +* // When calling `.bindTools`, call options should be passed via the second argument +* const llmWithTools = llm.bindTools( +* [...], +* { +* stop: ["\n"], +* } +* ); +* ``` +* +* ## Examples +* +*
+* Instantiate +* +* ```typescript +* import { ChatOllama } from '@langchain/ollama'; +* +* const llm = new ChatOllama({ +* model: "llama-3.1:8b", +* temperature: 0, +* // other params... +* }); +* ``` +*
+* +*
+* +*
+* Invoking +* +* ```typescript +* const input = `Translate "I love programming" into French.`; +* +* // Models also accept a list of chat messages or a formatted prompt +* const result = await llm.invoke(input); +* console.log(result); +* ``` +* +* ```txt +* AIMessage { +* "content": "The translation of \"I love programming\" into French is:\n\n\"J'adore programmer.\"", +* "additional_kwargs": {}, +* "response_metadata": { +* "model": "llama3.1:8b", +* "created_at": "2024-08-12T22:12:23.09468Z", +* "done_reason": "stop", +* "done": true, +* "total_duration": 3715571291, +* "load_duration": 35244375, +* "prompt_eval_count": 19, +* "prompt_eval_duration": 3092116000, +* "eval_count": 20, +* "eval_duration": 585789000 +* }, +* "tool_calls": [], +* "invalid_tool_calls": [], +* "usage_metadata": { +* "input_tokens": 19, +* "output_tokens": 20, +* "total_tokens": 39 +* } +* } +* ``` +*
+* +*
+* +*
+* Streaming Chunks +* +* ```typescript +* for await (const chunk of await llm.stream(input)) { +* console.log(chunk); +* } +* ``` +* +* ```txt +* AIMessageChunk { +* "content": "The", +* "additional_kwargs": {}, +* "response_metadata": {}, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": " translation", +* "additional_kwargs": {}, +* "response_metadata": {}, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": " of", +* "additional_kwargs": {}, +* "response_metadata": {}, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": " \"", +* "additional_kwargs": {}, +* "response_metadata": {}, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": "I", +* "additional_kwargs": {}, +* "response_metadata": {}, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* ... +* AIMessageChunk { +* "content": "", +* "additional_kwargs": {}, +* "response_metadata": {}, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": "", +* "additional_kwargs": {}, +* "response_metadata": { +* "model": "llama3.1:8b", +* "created_at": "2024-08-12T22:13:22.22423Z", +* "done_reason": "stop", +* "done": true, +* "total_duration": 8599883208, +* "load_duration": 35975875, +* "prompt_eval_count": 19, +* "prompt_eval_duration": 7918195000, +* "eval_count": 20, +* "eval_duration": 643569000 +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [], +* "usage_metadata": { +* "input_tokens": 19, +* "output_tokens": 20, +* "total_tokens": 39 +* } +* } +* ``` +*
+* +*
+* +*
+* Bind tools +* +* ```typescript +* import { z } from 'zod'; +* +* const GetWeather = { +* name: "GetWeather", +* description: "Get the current weather in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const GetPopulation = { +* name: "GetPopulation", +* description: "Get the current population in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); +* const aiMsg = await llmWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?" +* ); +* console.log(aiMsg.tool_calls); +* ``` +* +* ```txt +* [ +* { +* name: 'GetWeather', +* args: { location: 'Los Angeles, CA' }, +* id: '49410cad-2163-415e-bdcd-d26938a9c8c5', +* type: 'tool_call' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'New York, NY' }, +* id: '39e230e4-63ec-4fae-9df0-21c3abe735ad', +* type: 'tool_call' +* } +* ] +* ``` +*
+* +*
+* +*
+* Structured Output +* +* ```typescript +* import { z } from 'zod'; +* +* const Joke = z.object({ +* setup: z.string().describe("The setup of the joke"), +* punchline: z.string().describe("The punchline to the joke"), +* rating: z.number().optional().describe("How funny the joke is, from 1 to 10") +* }).describe('Joke to tell user.'); +* +* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); +* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); +* console.log(jokeResult); +* ``` +* +* ```txt +* { +* punchline: 'Why did the cat join a band? Because it wanted to be the purr-cussionist!', +* rating: 8, +* setup: 'A cat walks into a music store and asks the owner...' +* } +* ``` +*
+* +*
+* +*
+* Usage Metadata +* +* ```typescript +* const aiMsgForMetadata = await llm.invoke(input); +* console.log(aiMsgForMetadata.usage_metadata); +* ``` +* +* ```txt +* { input_tokens: 19, output_tokens: 20, total_tokens: 39 } +* ``` +*
+* +*
+* +*
+* Response Metadata +* +* ```typescript +* const aiMsgForResponseMetadata = await llm.invoke(input); +* console.log(aiMsgForResponseMetadata.response_metadata); +* ``` +* +* ```txt +* { +* model: 'llama3.1:8b', +* created_at: '2024-08-12T22:17:42.274795Z', +* done_reason: 'stop', +* done: true, +* total_duration: 6767071209, +* load_duration: 31628209, +* prompt_eval_count: 19, +* prompt_eval_duration: 6124504000, +* eval_count: 20, +* eval_duration: 608785000 +* } +* ``` +*
+* +*
+*/ +var ChatOllama = class extends BaseChatModel { + static lc_name() { + return "ChatOllama"; + } + model = "llama3"; + numa; + numCtx; + numBatch; + numGpu; + mainGpu; + lowVram; + f16Kv; + logitsAll; + vocabOnly; + useMmap; + useMlock; + embeddingOnly; + numThread; + numKeep; + seed; + numPredict; + topK; + topP; + tfsZ; + typicalP; + repeatLastN; + temperature; + repeatPenalty; + presencePenalty; + frequencyPenalty; + mirostat; + mirostatTau; + mirostatEta; + penalizeNewline; + streaming; + format; + keepAlive; + client; + checkOrPullModel = false; + baseUrl = "http://127.0.0.1:11434"; + think; + constructor(modelOrFields, fieldsArg) { + const fields = typeof modelOrFields === "string" ? { + ...fieldsArg ?? {}, + model: modelOrFields + } : modelOrFields ?? {}; + super(fields); + this._addVersion("@langchain/ollama", "1.3.0"); + this.baseUrl = fields.baseUrl ?? getEnvironmentVariable("OLLAMA_BASE_URL") ?? this.baseUrl; + this.client = new Ollama$1({ + fetch: fields.fetch, + host: this.baseUrl, + headers: fields.headers + }); + this.model = fields.model ?? this.model; + this.numa = fields.numa; + this.numCtx = fields.numCtx; + this.numBatch = fields.numBatch; + this.numGpu = fields.numGpu; + this.mainGpu = fields.mainGpu; + this.lowVram = fields.lowVram; + this.f16Kv = fields.f16Kv; + this.logitsAll = fields.logitsAll; + this.vocabOnly = fields.vocabOnly; + this.useMmap = fields.useMmap; + this.useMlock = fields.useMlock; + this.embeddingOnly = fields.embeddingOnly; + this.numThread = fields.numThread; + this.numKeep = fields.numKeep; + this.seed = fields.seed; + this.numPredict = fields.numPredict; + this.topK = fields.topK; + this.topP = fields.topP; + this.tfsZ = fields.tfsZ; + this.typicalP = fields.typicalP; + this.repeatLastN = fields.repeatLastN; + this.temperature = fields.temperature; + this.repeatPenalty = fields.repeatPenalty; + this.presencePenalty = fields.presencePenalty; + this.frequencyPenalty = fields.frequencyPenalty; + this.mirostat = fields.mirostat; + this.mirostatTau = fields.mirostatTau; + this.mirostatEta = fields.mirostatEta; + this.penalizeNewline = fields.penalizeNewline; + this.streaming = fields.streaming; + this.format = fields.format; + this.keepAlive = fields.keepAlive; + this.think = fields.think; + this.checkOrPullModel = fields.checkOrPullModel ?? this.checkOrPullModel; + } + _llmType() { + return "ollama"; + } + /** + * Download a model onto the local machine. + * + * @param {string} model The name of the model to download. + * @param {PullModelOptions | undefined} options Options for pulling the model. + * @returns {Promise} + */ + async pull(model, options) { + const { stream, insecure, logProgress } = { + stream: true, + ...options + }; + if (stream) { + for await (const chunk of await this.client.pull({ + model, + insecure, + stream + })) if (logProgress) console.log(chunk); + } else { + const response = await this.client.pull({ + model, + insecure + }); + if (logProgress) console.log(response); + } + } + bindTools(tools, kwargs) { + return this.withConfig({ + tools: tools.map((tool) => convertToOpenAITool(tool)), + ...kwargs + }); + } + getLsParams(options) { + const params = this.invocationParams(options); + return { + ls_provider: "ollama", + ls_model_name: this.model, + ls_model_type: "chat", + ls_temperature: params.options?.temperature ?? void 0, + ls_max_tokens: params.options?.num_predict ?? void 0, + ls_stop: options.stop + }; + } + invocationParams(options) { + return { + model: this.model, + format: options?.format ?? this.format, + keep_alive: this.keepAlive, + think: this.think, + options: { + numa: this.numa, + num_ctx: this.numCtx, + num_batch: this.numBatch, + num_gpu: this.numGpu, + main_gpu: this.mainGpu, + low_vram: this.lowVram, + f16_kv: this.f16Kv, + logits_all: this.logitsAll, + vocab_only: this.vocabOnly, + use_mmap: this.useMmap, + use_mlock: this.useMlock, + embedding_only: this.embeddingOnly, + num_thread: this.numThread, + num_keep: this.numKeep, + seed: this.seed, + num_predict: this.numPredict, + top_k: this.topK, + top_p: this.topP, + tfs_z: this.tfsZ, + typical_p: this.typicalP, + repeat_last_n: this.repeatLastN, + temperature: this.temperature, + repeat_penalty: this.repeatPenalty, + presence_penalty: this.presencePenalty, + frequency_penalty: this.frequencyPenalty, + mirostat: this.mirostat, + mirostat_tau: this.mirostatTau, + mirostat_eta: this.mirostatEta, + penalize_newline: this.penalizeNewline, + stop: options?.stop + }, + tools: options?.tools?.length ? options.tools.map((tool) => convertToOpenAITool(tool)) : void 0 + }; + } + /** + * Check if a model exists on the local machine. + * + * @param {string} model The name of the model to check. + * @returns {Promise} Whether or not the model exists. + */ + async checkModelExistsOnMachine(model) { + const { models } = await this.client.list(); + return !!models.find((m) => m.name === model || m.name === `${model}:latest`); + } + async ensureModelAvailable() { + if (this.checkOrPullModel) { + if (!await this.checkModelExistsOnMachine(this.model)) await this.pull(this.model, { logProgress: true }); + } + } + async _generate(messages, options, runManager) { + options.signal?.throwIfAborted(); + await this.ensureModelAvailable(); + let finalChunk; + for await (const chunk of this._streamResponseChunks(messages, options, runManager)) if (!finalChunk) finalChunk = chunk.message; + else finalChunk = concat(finalChunk, chunk.message); + const nonChunkMessage = new AIMessage({ + id: finalChunk?.id, + content: finalChunk?.content ?? "", + additional_kwargs: finalChunk?.additional_kwargs, + tool_calls: finalChunk?.tool_calls, + response_metadata: finalChunk?.response_metadata, + usage_metadata: finalChunk?.usage_metadata + }); + return { generations: [{ + text: typeof nonChunkMessage.content === "string" ? nonChunkMessage.content : "", + message: nonChunkMessage + }] }; + } + async *_streamChatModelEvents(messages, options, _runManager) { + await this.ensureModelAvailable(); + const params = this.invocationParams(options); + const ollamaMessages = convertToOllamaMessages(messages); + const stream = await this.client.chat({ + ...params, + messages: ollamaMessages, + stream: true + }); + const shouldStreamUsage = options.streamUsage ?? true; + const abortableStream = async function* (source, signal) { + for await (const chunk of source) { + if (signal?.aborted) return; + yield chunk; + } + }; + yield* convertOllamaStream(abortableStream(stream, options.signal), { + streamUsage: shouldStreamUsage, + think: this.think + }); + } + async *_streamResponseChunks(messages, options, runManager) { + await this.ensureModelAvailable(); + const params = this.invocationParams(options); + const ollamaMessages = convertToOllamaMessages(messages); + const usageMetadata = { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0 + }; + const stream = await this.client.chat({ + ...params, + messages: ollamaMessages, + stream: true + }); + let lastMetadata; + for await (const streamChunk of stream) { + if (options.signal?.aborted) { + this.client.abort(); + return; + } + const { message: responseMessage, ...rest } = streamChunk; + usageMetadata.input_tokens += rest.prompt_eval_count ?? 0; + usageMetadata.output_tokens += rest.eval_count ?? 0; + usageMetadata.total_tokens = usageMetadata.input_tokens + usageMetadata.output_tokens; + lastMetadata = rest; + const token = this.think ? responseMessage.thinking ?? responseMessage.content ?? "" : responseMessage.content ?? ""; + const chunk = new ChatGenerationChunk({ + text: token, + message: convertOllamaMessagesToLangChain(responseMessage) + }); + yield chunk; + await runManager?.handleLLMNewToken(token, void 0, void 0, void 0, void 0, { chunk }); + } + yield new ChatGenerationChunk({ + text: "", + message: new AIMessageChunk({ + content: "", + response_metadata: { + ...lastMetadata, + model_provider: "ollama" + }, + usage_metadata: usageMetadata + }) + }); + } + withStructuredOutput(outputSchema, config) { + let llm; + let outputParser; + const { schema, name, includeRaw } = { + ...config, + schema: outputSchema + }; + const method = config?.method ?? "jsonSchema"; + if (method === "functionCalling") { + let functionName = name ?? "extract"; + let toolFunction; + const jsonSchema = toJsonSchema(schema); + if (isInteropZodSchema(schema) || isSerializableSchema(schema)) toolFunction = { + name: functionName, + description: jsonSchema.description, + parameters: jsonSchema + }; + else if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) { + toolFunction = schema; + functionName = schema.name; + } else toolFunction = { + name: functionName, + description: schema.description ?? "", + parameters: schema + }; + llm = this.bindTools([{ + type: "function", + function: toolFunction + }]).withConfig({ ls_structured_output_format: { + kwargs: { method }, + schema: isInteropZodSchema(schema) || isSerializableSchema(schema) ? jsonSchema : schema + } }); + outputParser = createFunctionCallingParser(schema, functionName); + } else if (method === "jsonMode" || method === "jsonSchema") { + outputParser = createContentParser(schema); + const jsonSchema = toJsonSchema(schema); + llm = this.withConfig({ + format: method === "jsonMode" ? "json" : jsonSchema, + ls_structured_output_format: { + kwargs: { method }, + schema: jsonSchema + } + }); + } else throw new TypeError(`Unrecognized structured output method '${method}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`); + return assembleStructuredOutputPipeline(llm, outputParser, includeRaw, includeRaw ? "StructuredOutputRunnable" : "ChatOllamaStructuredOutput"); + } +}; +//#endregion +//#region node_modules/@langchain/ollama/dist/index.js +var dist_exports = /* @__PURE__ */ __exportAll({ ChatOllama: () => ChatOllama }); +//#endregion +export { dist_exports as t }; diff --git a/.vercel/output/functions/__server.func/_libs/@nodelib/fs.scandir+[...].mjs b/.vercel/output/functions/__server.func/_libs/@nodelib/fs.scandir+[...].mjs new file mode 100644 index 0000000..f283b29 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/@nodelib/fs.scandir+[...].mjs @@ -0,0 +1,455 @@ +import { i as __require, t as __commonJSMin } from "../../_runtime.mjs"; +//#region node_modules/@nodelib/fs.stat/out/providers/async.js +var require_async$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.read = void 0; + function read(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + callFailureCallback(callback, lstatError); + return; + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + callSuccessCallback(callback, lstat); + return; + } + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + callFailureCallback(callback, statError); + return; + } + callSuccessCallback(callback, lstat); + return; + } + if (settings.markSymbolicLink) stat.isSymbolicLink = () => true; + callSuccessCallback(callback, stat); + }); + }); + } + exports.read = read; + function callFailureCallback(callback, error) { + callback(error); + } + function callSuccessCallback(callback, result) { + callback(null, result); + } +})); +//#endregion +//#region node_modules/@nodelib/fs.stat/out/providers/sync.js +var require_sync$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.read = void 0; + function read(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) return lstat; + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) stat.isSymbolicLink = () => true; + return stat; + } catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) return lstat; + throw error; + } + } + exports.read = read; +})); +//#endregion +//#region node_modules/@nodelib/fs.stat/out/adapters/fs.js +var require_fs$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; + var fs$1 = __require("fs"); + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs$1.lstat, + stat: fs$1.stat, + lstatSync: fs$1.lstatSync, + statSync: fs$1.statSync + }; + function createFileSystemAdapter(fsMethods) { + if (fsMethods === void 0) return exports.FILE_SYSTEM_ADAPTER; + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + exports.createFileSystemAdapter = createFileSystemAdapter; +})); +//#endregion +//#region node_modules/@nodelib/fs.stat/out/settings.js +var require_settings$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var fs = require_fs$2(); + var Settings = class { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } + }; + exports.default = Settings; +})); +//#endregion +//#region node_modules/@nodelib/fs.stat/out/index.js +var require_out$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.statSync = exports.stat = exports.Settings = void 0; + var async = require_async$1(); + var sync = require_sync$1(); + var settings_1 = require_settings$1(); + exports.Settings = settings_1.default; + function stat(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === "function") { + async.read(path, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); + } + exports.stat = stat; + function statSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); + } + exports.statSync = statSync; + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) return settingsOrOptions; + return new settings_1.default(settingsOrOptions); + } +})); +//#endregion +//#region node_modules/queue-microtask/index.js +var require_queue_microtask = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /*! queue-microtask. MIT License. Feross Aboukhadijeh */ + var promise; + module.exports = typeof queueMicrotask === "function" ? queueMicrotask.bind(typeof window !== "undefined" ? window : global) : (cb) => (promise || (promise = Promise.resolve())).then(cb).catch((err) => setTimeout(() => { + throw err; + }, 0)); +})); +//#endregion +//#region node_modules/run-parallel/index.js +var require_run_parallel = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /*! run-parallel. MIT License. Feross Aboukhadijeh */ + module.exports = runParallel; + var queueMicrotask = require_queue_microtask(); + function runParallel(tasks, cb) { + let results, pending, keys; + let isSync = true; + if (Array.isArray(tasks)) { + results = []; + pending = tasks.length; + } else { + keys = Object.keys(tasks); + results = {}; + pending = keys.length; + } + function done(err) { + function end() { + if (cb) cb(err, results); + cb = null; + } + if (isSync) queueMicrotask(end); + else end(); + } + function each(i, err, result) { + results[i] = result; + if (--pending === 0 || err) done(err); + } + if (!pending) done(null); + else if (keys) keys.forEach(function(key) { + tasks[key](function(err, result) { + each(key, err, result); + }); + }); + else tasks.forEach(function(task, i) { + task(function(err, result) { + each(i, err, result); + }); + }); + isSync = false; + } +})); +//#endregion +//#region node_modules/@nodelib/fs.scandir/out/constants.js +var require_constants = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; + var NODE_PROCESS_VERSION_PARTS = process.versions.node.split("."); + if (NODE_PROCESS_VERSION_PARTS[0] === void 0 || NODE_PROCESS_VERSION_PARTS[1] === void 0) throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); + var MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); + var MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); + var SUPPORTED_MAJOR_VERSION = 10; + /** + * IS `true` for Node.js 10.10 and greater. + */ + exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION || MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= 10; +})); +//#endregion +//#region node_modules/@nodelib/fs.scandir/out/utils/fs.js +var require_fs$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createDirentFromStats = void 0; + var DirentFromStats = class { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } + }; + function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); + } + exports.createDirentFromStats = createDirentFromStats; +})); +//#endregion +//#region node_modules/@nodelib/fs.scandir/out/utils/index.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fs = void 0; + exports.fs = require_fs$1(); +})); +//#endregion +//#region node_modules/@nodelib/fs.scandir/out/providers/common.js +var require_common = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.joinPathSegments = void 0; + function joinPathSegments(a, b, separator) { + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) return a + b; + return a + separator + b; + } + exports.joinPathSegments = joinPathSegments; +})); +//#endregion +//#region node_modules/@nodelib/fs.scandir/out/providers/async.js +var require_async = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; + var fsStat = require_out$1(); + var rpl = require_run_parallel(); + var constants_1 = require_constants(); + var utils = require_utils(); + var common = require_common(); + function read(directory, settings, callback) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes(directory, settings, callback); + return; + } + readdir(directory, settings, callback); + } + exports.read = read; + function readdirWithFileTypes(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback(callback, entries); + return; + } + rpl(entries.map((entry) => makeRplTaskEntry(entry, settings)), (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, rplEntries); + }); + }); + } + exports.readdirWithFileTypes = readdirWithFileTypes; + function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + done(null, entry); + return; + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + done(statError); + return; + } + done(null, entry); + return; + } + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; + } + function readdir(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + rpl(names.map((name) => { + const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat.stat(path, settings.fsStatSettings, (error, stats) => { + if (error !== null) { + done(error); + return; + } + const entry = { + name, + path, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) entry.stats = stats; + done(null, entry); + }); + }; + }), (rplError, entries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, entries); + }); + }); + } + exports.readdir = readdir; + function callFailureCallback(callback, error) { + callback(error); + } + function callSuccessCallback(callback, result) { + callback(null, result); + } +})); +//#endregion +//#region node_modules/@nodelib/fs.scandir/out/providers/sync.js +var require_sync = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; + var fsStat = require_out$1(); + var constants_1 = require_constants(); + var utils = require_utils(); + var common = require_common(); + function read(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) return readdirWithFileTypes(directory, settings); + return readdir(directory, settings); + } + exports.read = read; + function readdirWithFileTypes(directory, settings) { + return settings.fs.readdirSync(directory, { withFileTypes: true }).map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + } catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) throw error; + } + return entry; + }); + } + exports.readdirWithFileTypes = readdirWithFileTypes; + function readdir(directory, settings) { + return settings.fs.readdirSync(directory).map((name) => { + const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) entry.stats = stats; + return entry; + }); + } + exports.readdir = readdir; +})); +//#endregion +//#region node_modules/@nodelib/fs.scandir/out/adapters/fs.js +var require_fs = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; + var fs = __require("fs"); + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync + }; + function createFileSystemAdapter(fsMethods) { + if (fsMethods === void 0) return exports.FILE_SYSTEM_ADAPTER; + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + exports.createFileSystemAdapter = createFileSystemAdapter; +})); +//#endregion +//#region node_modules/@nodelib/fs.scandir/out/settings.js +var require_settings = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var path = __require("path"); + var fsStat = require_out$1(); + var fs = require_fs(); + var Settings = class { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } + }; + exports.default = Settings; +})); +//#endregion +//#region node_modules/@nodelib/fs.scandir/out/index.js +var require_out = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Settings = exports.scandirSync = exports.scandir = void 0; + var async = require_async(); + var sync = require_sync(); + var settings_1 = require_settings(); + exports.Settings = settings_1.default; + function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === "function") { + async.read(path, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); + } + exports.scandir = scandir; + function scandirSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); + } + exports.scandirSync = scandirSync; + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) return settingsOrOptions; + return new settings_1.default(settingsOrOptions); + } +})); +//#endregion +export { require_out$1 as n, require_out as t }; diff --git a/.vercel/output/functions/__server.func/_libs/better-auth__memory-adapter.mjs b/.vercel/output/functions/__server.func/_libs/better-auth__memory-adapter.mjs index 6fbdd78..c3bbbd6 100644 --- a/.vercel/output/functions/__server.func/_libs/better-auth__memory-adapter.mjs +++ b/.vercel/output/functions/__server.func/_libs/better-auth__memory-adapter.mjs @@ -1,5 +1,5 @@ import { r as __exportAll } from "../_runtime.mjs"; -import { $t as logger, kt as createAdapterFactory } from "./@better-auth/core+[...].mjs"; +import { Pn as logger, ht as createAdapterFactory } from "./@better-auth/core+[...].mjs"; //#region node_modules/@better-auth/memory-adapter/dist/index.mjs var dist_exports = /* @__PURE__ */ __exportAll({ memoryAdapter: () => memoryAdapter }); /** diff --git a/.vercel/output/functions/__server.func/_libs/better-auth__utils.mjs b/.vercel/output/functions/__server.func/_libs/better-auth__utils.mjs index 8fe591a..6a3d9fa 100644 --- a/.vercel/output/functions/__server.func/_libs/better-auth__utils.mjs +++ b/.vercel/output/functions/__server.func/_libs/better-auth__utils.mjs @@ -1,4 +1,4 @@ -import { B as base64Url, V as getWebcryptoSubtle, z as base64 } from "./@better-auth/core+[...].mjs"; +import { D as getWebcryptoSubtle, E as base64Url, T as base64 } from "./@better-auth/core+[...].mjs"; import { randomBytes, scrypt } from "node:crypto"; //#region node_modules/@better-auth/utils/dist/password.node.mjs var config = { diff --git a/.vercel/output/functions/__server.func/_libs/braces+[...].mjs b/.vercel/output/functions/__server.func/_libs/braces+[...].mjs new file mode 100644 index 0000000..a0cf16c --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/braces+[...].mjs @@ -0,0 +1,1078 @@ +import { i as __require, t as __commonJSMin } from "../_runtime.mjs"; +//#region node_modules/braces/lib/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => { + exports.isInteger = (num) => { + if (typeof num === "number") return Number.isInteger(num); + if (typeof num === "string" && num.trim() !== "") return Number.isInteger(Number(num)); + return false; + }; + /** + * Find a node of the given type + */ + exports.find = (node, type) => node.nodes.find((node) => node.type === type); + /** + * Find a node of the given type + */ + exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return (Number(max) - Number(min)) / Number(step) >= limit; + }; + /** + * Escape the given node with '\\' before node.value + */ + exports.escapeNode = (block, n = 0, type) => { + const node = block.nodes[n]; + if (!node) return; + if (type && node.type === type || node.type === "open" || node.type === "close") { + if (node.escaped !== true) { + node.value = "\\" + node.value; + node.escaped = true; + } + } + }; + /** + * Returns true if the given brace node should be enclosed in literal braces + */ + exports.encloseBrace = (node) => { + if (node.type !== "brace") return false; + if (node.commas >> 0 + node.ranges >> 0 === 0) { + node.invalid = true; + return true; + } + return false; + }; + /** + * Returns true if a brace node is invalid. + */ + exports.isInvalidBrace = (block) => { + if (block.type !== "brace") return false; + if (block.invalid === true || block.dollar) return true; + if (block.commas >> 0 + block.ranges >> 0 === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; + }; + /** + * Returns true if a node is an open or close node + */ + exports.isOpenOrClose = (node) => { + if (node.type === "open" || node.type === "close") return true; + return node.open === true || node.close === true; + }; + /** + * Reduce an array of text nodes. + */ + exports.reduce = (nodes) => nodes.reduce((acc, node) => { + if (node.type === "text") acc.push(node.value); + if (node.type === "range") node.type = "text"; + return acc; + }, []); + /** + * Flatten an array + */ + exports.flatten = (...args) => { + const result = []; + const flat = (arr) => { + for (let i = 0; i < arr.length; i++) { + const ele = arr[i]; + if (Array.isArray(ele)) { + flat(ele); + continue; + } + if (ele !== void 0) result.push(ele); + } + return result; + }; + flat(args); + return result; + }; +})); +//#endregion +//#region node_modules/braces/lib/stringify.js +var require_stringify = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + module.exports = (ast, options = {}) => { + const stringify = (node, parent = {}) => { + const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ""; + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) return "\\" + node.value; + return node.value; + } + if (node.value) return node.value; + if (node.nodes) for (const child of node.nodes) output += stringify(child); + return output; + }; + return stringify(ast); + }; +})); +//#endregion +//#region node_modules/is-number/index.js +/*! +* is-number +* +* Copyright (c) 2014-present, Jon Schlinkert. +* Released under the MIT License. +*/ +var require_is_number = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = function(num) { + if (typeof num === "number") return num - num === 0; + if (typeof num === "string" && num.trim() !== "") return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + return false; + }; +})); +//#endregion +//#region node_modules/to-regex-range/index.js +/*! +* to-regex-range +* +* Copyright (c) 2015-present, Jon Schlinkert. +* Released under the MIT License. +*/ +var require_to_regex_range = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var isNumber = require_is_number(); + var toRegexRange = (min, max, options) => { + if (isNumber(min) === false) throw new TypeError("toRegexRange: expected the first argument to be a number"); + if (max === void 0 || min === max) return String(min); + if (isNumber(max) === false) throw new TypeError("toRegexRange: expected the second argument to be a number."); + let opts = { + relaxZeros: true, + ...options + }; + if (typeof opts.strictZeros === "boolean") opts.relaxZeros = opts.strictZeros === false; + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ":" + max + "=" + relax + shorthand + capture + wrap; + if (toRegexRange.cache.hasOwnProperty(cacheKey)) return toRegexRange.cache[cacheKey].result; + let a = Math.min(min, max); + let b = Math.max(min, max); + if (Math.abs(a - b) === 1) { + let result = min + "|" + max; + if (opts.capture) return `(${result})`; + if (opts.wrap === false) return result; + return `(?:${result})`; + } + let isPadded = hasPadding(min) || hasPadding(max); + let state = { + min, + max, + a, + b + }; + let positives = []; + let negatives = []; + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + if (a < 0) { + negatives = splitToPatterns(b < 0 ? Math.abs(b) : 1, Math.abs(a), state, opts); + a = state.a = 0; + } + if (b >= 0) positives = splitToPatterns(a, b, state, opts); + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives, opts); + if (opts.capture === true) state.result = `(${state.result})`; + else if (opts.wrap !== false && positives.length + negatives.length > 1) state.result = `(?:${state.result})`; + toRegexRange.cache[cacheKey] = state; + return state.result; + }; + function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, "-", false, options) || []; + let onlyPositive = filterPatterns(pos, neg, "", false, options) || []; + let intersected = filterPatterns(neg, pos, "-?", true, options) || []; + return onlyNegative.concat(intersected).concat(onlyPositive).join("|"); + } + function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + let stop = countNines(min, nines); + let stops = /* @__PURE__ */ new Set([max]); + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + stop = countZeros(max + 1, zeros) - 1; + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + stops = [...stops]; + stops.sort(compare); + return stops; + } + /** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + function rangeToPattern(start, stop, options) { + if (start === stop) return { + pattern: start, + count: [], + digits: 0 + }; + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ""; + let count = 0; + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + if (startDigit === stopDigit) pattern += startDigit; + else if (startDigit !== "0" || stopDigit !== "9") pattern += toCharacterClass(startDigit, stopDigit, options); + else count++; + } + if (count) pattern += options.shorthand === true ? "\\d" : "[0-9]"; + return { + pattern, + count: [count], + digits + }; + } + function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ""; + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) prev.count.pop(); + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + if (tok.isPadded) zeros = padZeros(max, tok, options); + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + return tokens; + } + function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + for (let ele of arr) { + let { string } = ele; + if (!intersection && !contains(comparison, "string", string)) result.push(prefix + string); + if (intersection && contains(comparison, "string", string)) result.push(prefix + string); + } + return result; + } + /** + * Zip strings + */ + function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; + } + function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; + } + function contains(arr, key, val) { + return arr.some((ele) => ele[key] === val); + } + function countNines(min, len) { + return Number(String(min).slice(0, -len) + "9".repeat(len)); + } + function countZeros(integer, zeros) { + return integer - integer % Math.pow(10, zeros); + } + function toQuantifier(digits) { + let [start = 0, stop = ""] = digits; + if (stop || start > 1) return `{${start + (stop ? "," + stop : "")}}`; + return ""; + } + function toCharacterClass(a, b, options) { + return `[${a}${b - a === 1 ? "" : "-"}${b}]`; + } + function hasPadding(str) { + return /^-?(0+)\d/.test(str); + } + function padZeros(value, tok, options) { + if (!tok.isPadded) return value; + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + switch (diff) { + case 0: return ""; + case 1: return relax ? "0?" : "0"; + case 2: return relax ? "0{0,2}" : "00"; + default: return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } + /** + * Cache + */ + toRegexRange.cache = {}; + toRegexRange.clearCache = () => toRegexRange.cache = {}; + /** + * Expose `toRegexRange` + */ + module.exports = toRegexRange; +})); +//#endregion +//#region node_modules/fill-range/index.js +/*! +* fill-range +* +* Copyright (c) 2014-present, Jon Schlinkert. +* Licensed under the MIT License. +*/ +var require_fill_range = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var util = __require("util"); + var toRegexRange = require_to_regex_range(); + var isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); + var transform = (toNumber) => { + return (value) => toNumber === true ? Number(value) : String(value); + }; + var isValidValue = (value) => { + return typeof value === "number" || typeof value === "string" && value !== ""; + }; + var isNumber = (num) => Number.isInteger(+num); + var zeros = (input) => { + let value = `${input}`; + let index = -1; + if (value[0] === "-") value = value.slice(1); + if (value === "0") return false; + while (value[++index] === "0"); + return index > 0; + }; + var stringify = (start, end, options) => { + if (typeof start === "string" || typeof end === "string") return true; + return options.stringify === true; + }; + var pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === "-" ? "-" : ""; + if (dash) input = input.slice(1); + input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0"); + } + if (toNumber === false) return String(input); + return input; + }; + var toMaxLen = (input, maxLength) => { + let negative = input[0] === "-" ? "-" : ""; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = "0" + input; + return negative ? "-" + input : input; + }; + var toSequence = (parts, options, maxLen) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + let prefix = options.capture ? "" : "?:"; + let positives = ""; + let negatives = ""; + let result; + if (parts.positives.length) positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|"); + if (parts.negatives.length) negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`; + if (positives && negatives) result = `${positives}|${negatives}`; + else result = positives || negatives; + if (options.wrap) return `(${prefix}${result})`; + return result; + }; + var toRange = (a, b, isNumbers, options) => { + if (isNumbers) return toRegexRange(a, b, { + wrap: false, + ...options + }); + let start = String.fromCharCode(a); + if (a === b) return start; + return `[${start}-${String.fromCharCode(b)}]`; + }; + var toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? "" : "?:"; + return wrap ? `(${prefix}${start.join("|")})` : start.join("|"); + } + return toRegexRange(start, end, options); + }; + var rangeError = (...args) => { + return /* @__PURE__ */ new RangeError("Invalid range arguments: " + util.inspect(...args)); + }; + var invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + }; + var invalidStep = (step, options) => { + if (options.strictRanges === true) throw new TypeError(`Expected step "${step}" to be a number`); + return []; + }; + var fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + if (a === 0) a = 0; + if (b === 0) b = 0; + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify(start, end, options) === false; + let format = options.transform || transform(toNumber); + if (options.toRegex && step === 1) return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + let parts = { + negatives: [], + positives: [] + }; + let push = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num)); + let range = []; + let index = 0; + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) push(a); + else range.push(pad(format(a, index), maxLen, toNumber)); + a = descending ? a - step : a + step; + index++; + } + if (options.toRegex === true) return step > 1 ? toSequence(parts, options, maxLen) : toRegex(range, null, { + wrap: false, + ...options + }); + return range; + }; + var fillLetters = (start, end, step = 1, options = {}) => { + if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) return invalidRange(start, end, options); + let format = options.transform || ((val) => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + if (options.toRegex && step === 1) return toRange(min, max, false, options); + let range = []; + let index = 0; + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + if (options.toRegex === true) return toRegex(range, null, { + wrap: false, + options + }); + return range; + }; + var fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) return [start]; + if (!isValidValue(start) || !isValidValue(end)) return invalidRange(start, end, options); + if (typeof step === "function") return fill(start, end, 1, { transform: step }); + if (isObject(step)) return fill(start, end, 0, step); + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + if (!isNumber(step)) { + if (step != null && !isObject(step)) return invalidStep(step, opts); + return fill(start, end, 1, step); + } + if (isNumber(start) && isNumber(end)) return fillNumbers(start, end, step, opts); + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); + }; + module.exports = fill; +})); +//#endregion +//#region node_modules/braces/lib/compile.js +var require_compile = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var fill = require_fill_range(); + var utils = require_utils(); + var compile = (ast, options = {}) => { + const walk = (node, parent = {}) => { + const invalidBlock = utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + const invalid = invalidBlock === true || invalidNode === true; + const prefix = options.escapeInvalid === true ? "\\" : ""; + let output = ""; + if (node.isOpen === true) return prefix + node.value; + if (node.isClose === true) { + console.log("node.isClose", prefix, node.value); + return prefix + node.value; + } + if (node.type === "open") return invalid ? prefix + node.value : "("; + if (node.type === "close") return invalid ? prefix + node.value : ")"; + if (node.type === "comma") return node.prev.type === "comma" ? "" : invalid ? node.value : "|"; + if (node.value) return node.value; + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + const range = fill(...args, { + ...options, + wrap: false, + toRegex: true, + strictZeros: true + }); + if (range.length !== 0) return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + if (node.nodes) for (const child of node.nodes) output += walk(child, node); + return output; + }; + return walk(ast); + }; + module.exports = compile; +})); +//#endregion +//#region node_modules/braces/lib/expand.js +var require_expand = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var fill = require_fill_range(); + var stringify = require_stringify(); + var utils = require_utils(); + var append = (queue = "", stash = "", enclose = false) => { + const result = []; + queue = [].concat(queue); + stash = [].concat(stash); + if (!stash.length) return queue; + if (!queue.length) return enclose ? utils.flatten(stash).map((ele) => `{${ele}}`) : stash; + for (const item of queue) if (Array.isArray(item)) for (const value of item) result.push(append(value, stash, enclose)); + else for (let ele of stash) { + if (enclose === true && typeof ele === "string") ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); + } + return utils.flatten(result); + }; + var expand = (ast, options = {}) => { + const rangeLimit = options.rangeLimit === void 0 ? 1e3 : options.rangeLimit; + const walk = (node, parent = {}) => { + node.queue = []; + let p = parent; + let q = parent.queue; + while (p.type !== "brace" && p.type !== "root" && p.parent) { + p = p.parent; + q = p.queue; + } + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify(node, options))); + return; + } + if (node.type === "brace" && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ["{}"])); + return; + } + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + if (utils.exceedsLimit(...args, options.step, rangeLimit)) throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit."); + let range = fill(...args, options); + if (range.length === 0) range = stringify(node, options); + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + const enclose = utils.encloseBrace(node); + let queue = node.queue; + let block = node; + while (block.type !== "brace" && block.type !== "root" && block.parent) { + block = block.parent; + queue = block.queue; + } + for (let i = 0; i < node.nodes.length; i++) { + const child = node.nodes[i]; + if (child.type === "comma" && node.type === "brace") { + if (i === 1) queue.push(""); + queue.push(""); + continue; + } + if (child.type === "close") { + q.push(append(q.pop(), queue, enclose)); + continue; + } + if (child.value && child.type !== "open") { + queue.push(append(queue.pop(), child.value)); + continue; + } + if (child.nodes) walk(child, node); + } + return queue; + }; + return utils.flatten(walk(ast)); + }; + module.exports = expand; +})); +//#endregion +//#region node_modules/braces/lib/constants.js +var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + MAX_LENGTH: 1e4, + CHAR_0: "0", + CHAR_9: "9", + CHAR_UPPERCASE_A: "A", + CHAR_LOWERCASE_A: "a", + CHAR_UPPERCASE_Z: "Z", + CHAR_LOWERCASE_Z: "z", + CHAR_LEFT_PARENTHESES: "(", + CHAR_RIGHT_PARENTHESES: ")", + CHAR_ASTERISK: "*", + CHAR_AMPERSAND: "&", + CHAR_AT: "@", + CHAR_BACKSLASH: "\\", + CHAR_BACKTICK: "`", + CHAR_CARRIAGE_RETURN: "\r", + CHAR_CIRCUMFLEX_ACCENT: "^", + CHAR_COLON: ":", + CHAR_COMMA: ",", + CHAR_DOLLAR: "$", + CHAR_DOT: ".", + CHAR_DOUBLE_QUOTE: "\"", + CHAR_EQUAL: "=", + CHAR_EXCLAMATION_MARK: "!", + CHAR_FORM_FEED: "\f", + CHAR_FORWARD_SLASH: "/", + CHAR_HASH: "#", + CHAR_HYPHEN_MINUS: "-", + CHAR_LEFT_ANGLE_BRACKET: "<", + CHAR_LEFT_CURLY_BRACE: "{", + CHAR_LEFT_SQUARE_BRACKET: "[", + CHAR_LINE_FEED: "\n", + CHAR_NO_BREAK_SPACE: "\xA0", + CHAR_PERCENT: "%", + CHAR_PLUS: "+", + CHAR_QUESTION_MARK: "?", + CHAR_RIGHT_ANGLE_BRACKET: ">", + CHAR_RIGHT_CURLY_BRACE: "}", + CHAR_RIGHT_SQUARE_BRACKET: "]", + CHAR_SEMICOLON: ";", + CHAR_SINGLE_QUOTE: "'", + CHAR_SPACE: " ", + CHAR_TAB: " ", + CHAR_UNDERSCORE: "_", + CHAR_VERTICAL_LINE: "|", + CHAR_ZERO_WIDTH_NOBREAK_SPACE: "" + }; +})); +//#endregion +//#region node_modules/braces/lib/parse.js +var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var stringify = require_stringify(); + /** + * Constants + */ + var { MAX_LENGTH, CHAR_BACKSLASH, CHAR_BACKTICK, CHAR_COMMA, CHAR_DOT, CHAR_LEFT_PARENTHESES, CHAR_RIGHT_PARENTHESES, CHAR_LEFT_CURLY_BRACE, CHAR_RIGHT_CURLY_BRACE, CHAR_LEFT_SQUARE_BRACKET, CHAR_RIGHT_SQUARE_BRACKET, CHAR_DOUBLE_QUOTE, CHAR_SINGLE_QUOTE, CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = require_constants(); + /** + * parse + */ + var parse = (input, options = {}) => { + if (typeof input !== "string") throw new TypeError("Expected a string"); + const opts = options || {}; + const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + const ast = { + type: "root", + input, + nodes: [] + }; + const stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + const length = input.length; + let index = 0; + let depth = 0; + let value; + /** + * Helpers + */ + const advance = () => input[index++]; + const push = (node) => { + if (node.type === "text" && prev.type === "dot") prev.type = "text"; + if (prev && prev.type === "text" && node.type === "text") { + prev.value += node.value; + return; + } + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + push({ type: "bos" }); + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + /** + * Invalid chars + */ + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) continue; + /** + * Escaped chars + */ + if (value === CHAR_BACKSLASH) { + push({ + type: "text", + value: (options.keepEscaping ? value : "") + advance() + }); + continue; + } + /** + * Right square bracket (literal): ']' + */ + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ + type: "text", + value: "\\" + value + }); + continue; + } + /** + * Left square bracket: '[' + */ + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + let next; + while (index < length && (next = advance())) { + value += next; + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + if (brackets === 0) break; + } + } + push({ + type: "text", + value + }); + continue; + } + /** + * Parentheses + */ + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ + type: "paren", + nodes: [] + }); + stack.push(block); + push({ + type: "text", + value + }); + continue; + } + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== "paren") { + push({ + type: "text", + value + }); + continue; + } + block = stack.pop(); + push({ + type: "text", + value + }); + block = stack[stack.length - 1]; + continue; + } + /** + * Quotes: '|"|` + */ + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + const open = value; + let next; + if (options.keepQuotes !== true) value = ""; + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + value += next; + } + push({ + type: "text", + value + }); + continue; + } + /** + * Left curly brace: '{' + */ + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + block = push({ + type: "brace", + open: true, + close: false, + dollar: prev.value && prev.value.slice(-1) === "$" || block.dollar === true, + depth, + commas: 0, + ranges: 0, + nodes: [] + }); + stack.push(block); + push({ + type: "open", + value + }); + continue; + } + /** + * Right curly brace: '}' + */ + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== "brace") { + push({ + type: "text", + value + }); + continue; + } + const type = "close"; + block = stack.pop(); + block.close = true; + push({ + type, + value + }); + depth--; + block = stack[stack.length - 1]; + continue; + } + /** + * Comma: ',' + */ + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + const open = block.nodes.shift(); + block.nodes = [open, { + type: "text", + value: stringify(block) + }]; + } + push({ + type: "comma", + value + }); + block.commas++; + continue; + } + /** + * Dot: '.' + */ + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + const siblings = block.nodes; + if (depth === 0 || siblings.length === 0) { + push({ + type: "text", + value + }); + continue; + } + if (prev.type === "dot") { + block.range = []; + prev.value += value; + prev.type = "range"; + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = "text"; + continue; + } + block.ranges++; + block.args = []; + continue; + } + if (prev.type === "range") { + siblings.pop(); + const before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + push({ + type: "dot", + value + }); + continue; + } + /** + * Text + */ + push({ + type: "text", + value + }); + } + do { + block = stack.pop(); + if (block.type !== "root") { + block.nodes.forEach((node) => { + if (!node.nodes) { + if (node.type === "open") node.isOpen = true; + if (node.type === "close") node.isClose = true; + if (!node.nodes) node.type = "text"; + node.invalid = true; + } + }); + const parent = stack[stack.length - 1]; + const index = parent.nodes.indexOf(block); + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + push({ type: "eos" }); + return ast; + }; + module.exports = parse; +})); +//#endregion +//#region node_modules/braces/index.js +var require_braces = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var stringify = require_stringify(); + var compile = require_compile(); + var expand = require_expand(); + var parse = require_parse(); + /** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + var braces = (input, options = {}) => { + let output = []; + if (Array.isArray(input)) for (const pattern of input) { + const result = braces.create(pattern, options); + if (Array.isArray(result)) output.push(...result); + else output.push(result); + } + else output = [].concat(braces.create(input, options)); + if (options && options.expand === true && options.nodupes === true) output = [...new Set(output)]; + return output; + }; + /** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + braces.parse = (input, options = {}) => parse(input, options); + /** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + braces.stringify = (input, options = {}) => { + if (typeof input === "string") return stringify(braces.parse(input, options), options); + return stringify(input, options); + }; + /** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + braces.compile = (input, options = {}) => { + if (typeof input === "string") input = braces.parse(input, options); + return compile(input, options); + }; + /** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + braces.expand = (input, options = {}) => { + if (typeof input === "string") input = braces.parse(input, options); + let result = expand(input, options); + if (options.noempty === true) result = result.filter(Boolean); + if (options.nodupes === true) result = [...new Set(result)]; + return result; + }; + /** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + braces.create = (input, options = {}) => { + if (input === "" || input.length < 3) return [input]; + return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); + }; + /** + * Expose "braces" + */ + module.exports = braces; +})); +//#endregion +export { require_braces as t }; diff --git a/.vercel/output/functions/__server.func/_libs/cfworker__json-schema.mjs b/.vercel/output/functions/__server.func/_libs/cfworker__json-schema.mjs new file mode 100644 index 0000000..b6a377d --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/cfworker__json-schema.mjs @@ -0,0 +1,879 @@ +//#region node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js +function deepCompareStrict(a, b) { + const typeofa = typeof a; + if (typeofa !== typeof b) return false; + if (Array.isArray(a)) { + if (!Array.isArray(b)) return false; + const length = a.length; + if (length !== b.length) return false; + for (let i = 0; i < length; i++) if (!deepCompareStrict(a[i], b[i])) return false; + return true; + } + if (typeofa === "object") { + if (!a || !b) return a === b; + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + if (aKeys.length !== bKeys.length) return false; + for (const k of aKeys) if (!deepCompareStrict(a[k], b[k])) return false; + return true; + } + return a === b; +} +//#endregion +//#region node_modules/@cfworker/json-schema/dist/esm/pointer.js +function encodePointer(p) { + return encodeURI(escapePointer(p)); +} +function escapePointer(p) { + return p.replace(/~/g, "~0").replace(/\//g, "~1"); +} +//#endregion +//#region node_modules/@cfworker/json-schema/dist/esm/dereference.js +var schemaArrayKeyword = { + prefixItems: true, + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; +var schemaMapKeyword = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependentSchemas: true +}; +var 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 +}; +var initialBaseURI = typeof self !== "undefined" && self.location && self.location.origin !== "null" ? new URL(self.location.origin + self.location.pathname + location.search) : new URL("https://github.com/cfworker"); +function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = "") { + if (schema && typeof schema === "object" && !Array.isArray(schema)) { + const id = schema.$id || schema.id; + if (id) { + const url = new URL(id, baseURI.href); + if (url.hash.length > 1) lookup[url.href] = schema; + else { + url.hash = ""; + if (basePointer === "") baseURI = url; + else dereference(schema, lookup, baseURI); + } + } + } else if (schema !== true && schema !== false) return lookup; + const schemaURI = baseURI.href + (basePointer ? "#" + basePointer : ""); + if (lookup[schemaURI] !== void 0) throw new Error(`Duplicate schema URI "${schemaURI}".`); + lookup[schemaURI] = schema; + if (schema === true || schema === false) return lookup; + if (schema.__absolute_uri__ === void 0) Object.defineProperty(schema, "__absolute_uri__", { + enumerable: false, + value: schemaURI + }); + if (schema.$ref && schema.__absolute_ref__ === void 0) { + const url = new URL(schema.$ref, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, "__absolute_ref__", { + enumerable: false, + value: url.href + }); + } + if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === void 0) { + const url = new URL(schema.$recursiveRef, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, "__absolute_recursive_ref__", { + enumerable: false, + value: url.href + }); + } + if (schema.$anchor) { + const url = new URL("#" + schema.$anchor, baseURI.href); + lookup[url.href] = schema; + } + for (let key in schema) { + if (ignoredKeyword[key]) continue; + const keyBase = `${basePointer}/${encodePointer(key)}`; + const subSchema = schema[key]; + if (Array.isArray(subSchema)) { + if (schemaArrayKeyword[key]) { + const length = subSchema.length; + for (let i = 0; i < length; i++) dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); + } + } 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; +} +//#endregion +//#region node_modules/@cfworker/json-schema/dist/esm/format.js +var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +var DAYS = [ + 0, + 31, + 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 +]; +var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; +var 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; +var 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; +var 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; +var 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; +var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; +var EMAIL = (input) => { + if (input[0] === "\"") return false; + const [name, host, ...rest] = input.split("@"); + if (!name || !host || rest.length !== 0 || name.length > 64 || host.length > 253) return false; + if (name[0] === "." || name.endsWith(".") || name.includes("..")) return false; + if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) return false; + return host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); +}; +var IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; +var 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; +var 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)); +function bind(r) { + return r.test.bind(r); +} +var format = { + date, + time: time.bind(void 0, false), + "date-time": date_time, + duration: DURATION, + uri, + "uri-reference": bind(URIREF), + "uri-template": bind(URITEMPLATE), + url: bind(URL_), + email: EMAIL, + hostname: bind(HOSTNAME), + ipv4: bind(IPV4), + ipv6: bind(IPV6), + regex, + uuid: bind(UUID), + "json-pointer": bind(JSON_POINTER), + "json-pointer-uri-fragment": bind(JSON_POINTER_URI_FRAGMENT), + "relative-json-pointer": bind(RELATIVE_JSON_POINTER) +}; +function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} +function date(str) { + const matches = str.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, str) { + const matches = str.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); +} +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]); +} +var NOT_URI_FRAGMENT = /\/|:/; +var 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; +function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); +} +var Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str, "u"); + return true; + } catch (e) { + return false; + } +} +//#endregion +//#region node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js +function ucs2length(s) { + let result = 0; + let length = s.length; + let index = 0; + let charCode; + while (index < length) { + result++; + charCode = s.charCodeAt(index++); + if (charCode >= 55296 && charCode <= 56319 && index < length) { + charCode = s.charCodeAt(index); + if ((charCode & 64512) == 56320) index++; + } + } + return result; +} +//#endregion +//#region node_modules/@cfworker/json-schema/dist/esm/validate.js +function validate(instance, schema, draft = "2019-09", lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = "#", schemaLocation = "#", evaluated = Object.create(null)) { + if (schema === true) return { + valid: true, + errors: [] + }; + if (schema === 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__ } = schema; + const errors = []; + if ($recursiveAnchor === true && recursiveAnchor === null) recursiveAnchor = schema; + if ($recursiveRef === "#") { + const refSchema = recursiveAnchor === null ? lookup[__absolute_recursive_ref__] : recursiveAnchor; + const keywordLocation = `${schemaLocation}/$recursiveRef`; + const result = validate(instance, recursiveAnchor === null ? schema : 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 refSchema = lookup[__absolute_ref__ || $ref]; + if (refSchema === void 0) { + let message = `Unresolved $ref "${$ref}".`; + if (__absolute_ref__ && __absolute_ref__ !== $ref) message += ` Absolute URI "${__absolute_ref__}".`; + message += `\nKnown schemas:\n- ${Object.keys(lookup).join("\n- ")}`; + throw new Error(message); + } + const keywordLocation = `${schemaLocation}/$ref`; + const result = validate(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 i = 0; i < length; i++) if (instanceType === $type[i] || $type[i] === "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`; + if (validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation).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 i = 0; i < $anyOf.length; i++) { + const subSchema = $anyOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, 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 i = 0; i < $allOf.length; i++) { + const subSchema = $allOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, 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, i) => { + const subEvaluated = Object.create(evaluated); + const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, 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`; + if (validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid) { + if ($then !== void 0) { + const thenResult = validate(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 = validate(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 = validate(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 = validate(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 = validate(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 = validate(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 regex = new RegExp(pattern, "u"); + const subSchema = $patternProperties[pattern]; + for (const key in instance) { + if (!regex.test(key)) continue; + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate(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 = validate(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 = validate(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 i = 0; + let stop = false; + if ($prefixItems !== void 0) { + const keywordLocation = `${schemaLocation}/prefixItems`; + const length2 = Math.min($prefixItems.length, length); + for (; i < length2; i++) { + const result = validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = 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 (; i < length2; i++) { + const result = validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = 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 (; i < length; i++) { + const result = validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = 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 keywordLocation = `${schemaLocation}/additionalItems`; + for (; i < length; i++) { + const result = validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: "additionalItems", + keywordLocation, + 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 j = 0; j < length; j++) { + const result = validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); + if (result.valid) { + evaluated[j] = 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 (; i < length; i++) { + if (evaluated[i]) continue; + const result = validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) errors.push({ + instanceLocation, + keyword: "unevaluatedItems", + keywordLocation, + error: `Items did not match unevaluated items schema.` + }, ...result.errors); + } + } + if ($uniqueItems) for (let j = 0; j < length; j++) { + const a = instance[j]; + const ao = typeof a === "object" && a !== null; + for (let k = 0; k < length; k++) { + if (j === k) continue; + const b = instance[k]; + if (a === b || ao && typeof b === "object" && b !== null && deepCompareStrict(a, b)) { + errors.push({ + instanceLocation, + keyword: "uniqueItems", + keywordLocation: `${schemaLocation}/uniqueItems`, + error: `Duplicate items at indexes ${j} and ${k}.` + }); + j = Number.MAX_SAFE_INTEGER; + k = 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) >= 1.1920929e-7 && Math.abs($multipleOf - remainder) >= 1.1920929e-7) 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, "u").test(instance)) errors.push({ + instanceLocation, + keyword: "pattern", + keywordLocation: `${schemaLocation}/pattern`, + error: `String does not match pattern.` + }); + if ($format !== void 0 && format[$format] && !format[$format](instance)) errors.push({ + instanceLocation, + keyword: "format", + keywordLocation: `${schemaLocation}/format`, + error: `String does not match format "${$format}".` + }); + } + return { + valid: errors.length === 0, + errors + }; +} +//#endregion +//#region node_modules/@cfworker/json-schema/dist/esm/validator.js +var Validator = class { + schema; + draft; + shortCircuit; + lookup; + constructor(schema, draft = "2019-09", shortCircuit = true) { + this.schema = schema; + this.draft = draft; + this.shortCircuit = shortCircuit; + this.lookup = dereference(schema); + } + validate(instance) { + return validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit); + } + addSchema(schema, id) { + if (id) schema = { + ...schema, + $id: id + }; + dereference(schema, this.lookup); + } +}; +//#endregion +export { deepCompareStrict as i, validate as n, dereference as r, Validator as t }; diff --git a/.vercel/output/functions/__server.func/_libs/core-util-is.mjs b/.vercel/output/functions/__server.func/_libs/core-util-is.mjs new file mode 100644 index 0000000..57b943f --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/core-util-is.mjs @@ -0,0 +1,67 @@ +import { i as __require, t as __commonJSMin } from "../_runtime.mjs"; +//#region node_modules/core-util-is/lib/util.js +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + function isArray(arg) { + if (Array.isArray) return Array.isArray(arg); + return objectToString(arg) === "[object Array]"; + } + exports.isArray = isArray; + function isBoolean(arg) { + return typeof arg === "boolean"; + } + exports.isBoolean = isBoolean; + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + function isNumber(arg) { + return typeof arg === "number"; + } + exports.isNumber = isNumber; + function isString(arg) { + return typeof arg === "string"; + } + exports.isString = isString; + function isSymbol(arg) { + return typeof arg === "symbol"; + } + exports.isSymbol = isSymbol; + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + function isRegExp(re) { + return objectToString(re) === "[object RegExp]"; + } + exports.isRegExp = isRegExp; + function isObject(arg) { + return typeof arg === "object" && arg !== null; + } + exports.isObject = isObject; + function isDate(d) { + return objectToString(d) === "[object Date]"; + } + exports.isDate = isDate; + function isError(e) { + return objectToString(e) === "[object Error]" || e instanceof Error; + } + exports.isError = isError; + function isFunction(arg) { + return typeof arg === "function"; + } + exports.isFunction = isFunction; + function isPrimitive(arg) { + return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || typeof arg === "undefined"; + } + exports.isPrimitive = isPrimitive; + exports.isBuffer = __require("buffer").Buffer.isBuffer; + function objectToString(o) { + return Object.prototype.toString.call(o); + } +})); +//#endregion +export { require_util as t }; diff --git a/.vercel/output/functions/__server.func/_libs/deepagents+[...].mjs b/.vercel/output/functions/__server.func/_libs/deepagents+[...].mjs new file mode 100644 index 0000000..636b97e --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/deepagents+[...].mjs @@ -0,0 +1,22194 @@ +import { i as __require, o as __toESM, t as __commonJSMin } from "../_runtime.mjs"; +import { $t as string, Bt as array, Ht as custom, Jt as number, Lt as _instanceof, Qt as record, Vt as boolean, Yt as object, Zt as preprocess, tn as union, zt as any } from "./@better-auth/core+[...].mjs"; +import { r as number$1 } from "./@langchain/mcp-adapters+[...].mjs"; +import { An as HumanMessage, At as getSchemaDescription, Dn as SystemMessage, Ft as isInteropZodObject, G as Runnable, In as ToolInputParsingException, It as isInteropZodSchema, J as RunnableSequence, Jt as ensureConfig, K as RunnableBinding, Ln as ToolMessage, Mt as interopSafeParseAsync, N as BaseLanguageModel, Nt as interopZodObjectMakeFieldsOptional, Pt as interopZodObjectPartial, Qt as AsyncLocalStorageProviderSingleton, Rt as isZodSchemaV4, Sn as AIMessageChunk, Tn as getBufferString, Tt as isSerializableSchema, Ut as AsyncGeneratorWithSetup, Vn as BaseMessage, Wt as IterableReadableStream, Yt as mergeConfigs, _t as promiseType, c as isLangChainTool, ct as booleanType, dt as functionType, ft as instanceOfType, ht as objectType, jt as interopParse, kn as RemoveMessage, kt as getInteropZodObjectShape, l as BaseChatModel, lt as custom$1, mt as numberType, n as convertToOpenAITool, nr as ContextOverflowError, o as tool, ot as anyType, p as ChatModelStream, pt as literalType, q as RunnableLambda, qt as raceWithSignal, rt as toJsonSchema, st as arrayType, ut as enumType, vt as recordType, xn as AIMessage, xt as unionType, yt as stringType } from "./@langchain/anthropic+[...].mjs"; +import { t as Validator } from "./cfworker__json-schema.mjs"; +import { _ as END, a as REMOVE_ALL_MESSAGES, b as isCommand, c as ReducedValue, d as StreamChannel, f as getConfig, g as Command, h as isGraphInterrupt, i as MessagesValue, l as interrupt, m as isGraphBubbleUp, n as StateGraph, o as StateSchema, p as getCurrentTaskInput, r as schemaMetaRegistry, s as UntrackedValue, u as createMessagesTransformer, v as START, y as Send } from "./@langchain/langgraph+[...].mjs"; +import { n as context } from "./langchain__core+mustache.mjs"; +import { t as require_braces } from "./braces+[...].mjs"; +import { t as Client } from "./@langchain/langgraph-sdk+[...].mjs"; +import { n as require_out$1 } from "./@nodelib/fs.scandir+[...].mjs"; +import { t as require_out$2 } from "./fastq+nodelib__fs.walk+reusify.mjs"; +import { spawn } from "node:child_process"; +import fs$1 from "node:fs/promises"; +import fs from "node:fs"; +import path from "node:path"; +import "node:os"; +//#region node_modules/langchain/dist/chat_models/universal.js +var MODEL_PROVIDER_CONFIG = { + openai: { + package: "@langchain/openai", + className: "ChatOpenAI" + }, + anthropic: { + package: "@langchain/anthropic", + className: "ChatAnthropic" + }, + azure_openai: { + package: "@langchain/openai", + className: "AzureChatOpenAI" + }, + cohere: { + package: "@langchain/cohere", + className: "ChatCohere" + }, + google: { + package: "@langchain/google", + className: "ChatGoogle" + }, + "google-vertexai": { + package: "@langchain/google-vertexai", + className: "ChatVertexAI" + }, + "google-vertexai-web": { + package: "@langchain/google-vertexai-web", + className: "ChatVertexAI" + }, + "google-genai": { + package: "@langchain/google-genai", + className: "ChatGoogleGenerativeAI" + }, + ollama: { + package: "@langchain/ollama", + className: "ChatOllama" + }, + mistralai: { + package: "@langchain/mistralai", + className: "ChatMistralAI" + }, + mistral: { + package: "@langchain/mistralai", + className: "ChatMistralAI" + }, + groq: { + package: "@langchain/groq", + className: "ChatGroq" + }, + bedrock: { + package: "@langchain/aws", + className: "ChatBedrockConverse" + }, + aws: { + package: "@langchain/aws", + className: "ChatBedrockConverse" + }, + deepseek: { + package: "@langchain/deepseek", + className: "ChatDeepSeek" + }, + xai: { + package: "@langchain/xai", + className: "ChatXAI" + }, + cerebras: { + package: "@langchain/cerebras", + className: "ChatCerebras" + }, + fireworks: { + package: "@langchain/fireworks", + className: "ChatFireworks" + }, + together: { + package: "@langchain/together-ai", + className: "ChatTogetherAI", + hasCircularDependency: true + }, + perplexity: { + package: "@langchain/perplexity", + className: "ChatPerplexity" + } +}; +var SUPPORTED_PROVIDERS = Object.keys(MODEL_PROVIDER_CONFIG); +/** +* Helper function to get a chat model class by its class name or model provider. +* @param className The class name (e.g., "ChatOpenAI", "ChatAnthropic") +* @param modelProvider Optional model provider key for direct lookup (e.g., "google-vertexai-web"). +* When provided, uses direct lookup to avoid className collision issues. +* @returns The imported model class or undefined if not found +*/ +async function getChatModelByClassName(className, modelProvider) { + let config; + if (modelProvider) config = MODEL_PROVIDER_CONFIG[modelProvider]; + else { + const providerEntry = Object.entries(MODEL_PROVIDER_CONFIG).find(([, c]) => c.className === className); + config = providerEntry ? providerEntry[1] : void 0; + } + if (!config) return; + try { + return (await import(config.package))[config.className]; + } catch (e) { + const err = e; + if ("code" in err && err.code?.toString().includes("ERR_MODULE_NOT_FOUND") && "message" in err && typeof err.message === "string") { + const attemptedPackage = (err.message.startsWith("Error: ") ? err.message.slice(7) : err.message).split("Cannot find package '")[1].split("'")[0]; + throw new Error(`Unable to import ${attemptedPackage}. Please install with \`npm install ${attemptedPackage}\` or \`pnpm install ${attemptedPackage}\``); + } + throw e; + } +} +async function _initChatModelHelper(model, modelProvider, params = {}) { + const modelProviderCopy = modelProvider || _inferModelProvider(model); + if (!modelProviderCopy) throw new Error(`Unable to infer model provider for { model: ${model} }, please specify modelProvider directly.`); + const config = MODEL_PROVIDER_CONFIG[modelProviderCopy]; + if (!config) { + const supported = SUPPORTED_PROVIDERS.join(", "); + throw new Error(`Unsupported { modelProvider: ${modelProviderCopy} }.\n\nSupported model providers are: ${supported}`); + } + const { modelProvider: _unused, ...passedParams } = params; + return new (await (getChatModelByClassName(config.className, modelProviderCopy)))({ + model, + ...passedParams + }); +} +/** +* Attempts to infer the model provider based on the given model name. +* +* @param {string} modelName - The name of the model to infer the provider for. +* @returns {string | undefined} The inferred model provider name, or undefined if unable to infer. +* +* @example +* _inferModelProvider("gpt-4"); // returns "openai" +* _inferModelProvider("claude-2"); // returns "anthropic" +* _inferModelProvider("unknown-model"); // returns undefined +*/ +function _inferModelProvider(modelName) { + if (modelName.startsWith("gpt-3") || modelName.startsWith("gpt-4") || modelName.startsWith("gpt-5") || modelName.startsWith("o1") || modelName.startsWith("o3") || modelName.startsWith("o4")) return "openai"; + else if (modelName.startsWith("claude")) return "anthropic"; + else if (modelName.startsWith("command")) return "cohere"; + else if (modelName.startsWith("accounts/fireworks")) return "fireworks"; + else if (modelName.startsWith("gemini")) return "google-vertexai"; + else if (modelName.startsWith("amazon.")) return "bedrock"; + else if (modelName.startsWith("mistral")) return "mistralai"; + else if (modelName.startsWith("sonar") || modelName.startsWith("pplx")) return "perplexity"; + else return; +} +/** +* Internal class used to create chat models. +* +* @internal +*/ +var ConfigurableModel = class ConfigurableModel extends BaseChatModel { + _llmType() { + return "chat_model"; + } + lc_namespace = ["langchain", "chat_models"]; + _defaultConfig = {}; + /** + * @default "any" + */ + _configurableFields = "any"; + /** + * @default "" + */ + _configPrefix; + /** + * Methods which should be called after the model is initialized. + * The key will be the method name, and the value will be the arguments. + */ + _queuedMethodOperations = {}; + /** @internal */ + _modelInstanceCache = /* @__PURE__ */ new Map(); + /** @internal */ + _profile; + constructor(fields) { + super(fields); + this._defaultConfig = fields.defaultConfig ?? {}; + if (fields.configurableFields === "any") this._configurableFields = "any"; + else this._configurableFields = fields.configurableFields ?? ["model", "modelProvider"]; + if (fields.configPrefix) this._configPrefix = fields.configPrefix.endsWith("_") ? fields.configPrefix : `${fields.configPrefix}_`; + else this._configPrefix = ""; + this._queuedMethodOperations = fields.queuedMethodOperations ?? this._queuedMethodOperations; + this._profile = fields.profile ?? void 0; + this.metadata = { + ...this.metadata, + ls_integration: "langchain_init_chat_model" + }; + } + async _getModelInstance(config) { + const cacheKey = this._getCacheKey(config); + const cachedModel = this._modelInstanceCache.get(cacheKey); + if (cachedModel) return cachedModel; + const params = { + ...this._defaultConfig, + ...this._modelParams(config) + }; + let initializedModel = await _initChatModelHelper(params.model, params.modelProvider, params); + for (const [method, args] of Object.entries(this._queuedMethodOperations)) if (method in initializedModel && typeof initializedModel[method] === "function") initializedModel = await initializedModel[method](...args); + this._modelInstanceCache.set(cacheKey, initializedModel); + return initializedModel; + } + async _generate(messages, options, runManager) { + return (await this._getModelInstance(options))._generate(messages, options ?? {}, runManager); + } + bindTools(tools, params) { + const newQueuedOperations = { ...this._queuedMethodOperations }; + newQueuedOperations.bindTools = [tools, params]; + return new ConfigurableModel({ + defaultConfig: this._defaultConfig, + configurableFields: this._configurableFields, + configPrefix: this._configPrefix, + queuedMethodOperations: newQueuedOperations + }); + } + withStructuredOutput = (schema, ...args) => { + const newQueuedOperations = { ...this._queuedMethodOperations }; + newQueuedOperations.withStructuredOutput = [schema, ...args]; + return new ConfigurableModel({ + defaultConfig: this._defaultConfig, + configurableFields: this._configurableFields, + configPrefix: this._configPrefix, + queuedMethodOperations: newQueuedOperations + }); + }; + _modelParams(config) { + const configurable = config?.configurable ?? {}; + let modelParams = {}; + for (const [key, value] of Object.entries(configurable)) if (key.startsWith(this._configPrefix)) { + const strippedKey = this._removePrefix(key, this._configPrefix); + modelParams[strippedKey] = value; + } + if (this._configurableFields !== "any") modelParams = Object.fromEntries(Object.entries(modelParams).filter(([key]) => this._configurableFields.includes(key))); + return modelParams; + } + _removePrefix(str, prefix) { + return str.startsWith(prefix) ? str.slice(prefix.length) : str; + } + /** + * Bind config to a Runnable, returning a new Runnable. + * @param {RunnableConfig | undefined} [config] - The config to bind. + * @returns {RunnableBinding} A new RunnableBinding with the bound config. + */ + withConfig(config) { + const mergedConfig = { ...config || {} }; + const modelParams = this._modelParams(mergedConfig); + const remainingConfig = Object.fromEntries(Object.entries(mergedConfig).filter(([k]) => k !== "configurable")); + remainingConfig.configurable = Object.fromEntries(Object.entries(mergedConfig.configurable || {}).filter(([k]) => this._configPrefix && !Object.keys(modelParams).includes(this._removePrefix(k, this._configPrefix)))); + return new RunnableBinding({ + config: mergedConfig, + bound: new ConfigurableModel({ + defaultConfig: { + ...this._defaultConfig, + ...modelParams + }, + configurableFields: Array.isArray(this._configurableFields) ? [...this._configurableFields] : this._configurableFields, + configPrefix: this._configPrefix, + queuedMethodOperations: this._queuedMethodOperations + }) + }); + } + async invoke(input, options) { + const model = await this._getModelInstance(options); + const config = ensureConfig(options); + return model.invoke(input, config); + } + async stream(input, options) { + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: await (await this._getModelInstance(options)).stream(input, options), + config: options + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + async batch(inputs, options, batchOptions) { + return super.batch(inputs, options, batchOptions); + } + async *transform(generator, options) { + const model = await this._getModelInstance(options); + const config = ensureConfig(options); + yield* model.transform(generator, config); + } + async *streamLog(input, options, streamOptions) { + const model = await this._getModelInstance(options); + const config = ensureConfig(options); + yield* model.streamLog(input, config, { + ...streamOptions, + _schemaFormat: "original", + includeNames: streamOptions?.includeNames, + includeTypes: streamOptions?.includeTypes, + includeTags: streamOptions?.includeTags, + excludeNames: streamOptions?.excludeNames, + excludeTypes: streamOptions?.excludeTypes, + excludeTags: streamOptions?.excludeTags + }); + } + streamEvents(input, options, streamOptions) { + if (options?.version === "v1" || options?.version === "v2") { + const outerThis = this; + const tracingCallOptions = options; + async function* wrappedGenerator() { + const model = await outerThis._getModelInstance(tracingCallOptions); + const tracingOptions = { + ...ensureConfig(tracingCallOptions), + version: tracingCallOptions.version, + ...tracingCallOptions.encoding !== void 0 ? { encoding: tracingCallOptions.encoding } : {} + }; + let eventStream; + if (tracingCallOptions.version === "v1" && tracingCallOptions.encoding === "text/event-stream") eventStream = model.streamEvents(input, tracingOptions, streamOptions); + else if (tracingCallOptions.version === "v1") eventStream = model.streamEvents(input, tracingOptions, streamOptions); + else if (tracingCallOptions.version === "v2" && tracingCallOptions.encoding === "text/event-stream") eventStream = model.streamEvents(input, tracingOptions, streamOptions); + else eventStream = model.streamEvents(input, tracingOptions, streamOptions); + for await (const chunk of eventStream) yield chunk; + } + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator()); + } + const outerThis = this; + async function* deferredEvents() { + const model = await outerThis._getModelInstance(options); + const config = ensureConfig(options); + yield* model.streamEvents(input, config); + } + return new ChatModelStream(deferredEvents()); + } + /** + * Return profiling information for the model. + * + * @returns {ModelProfile} An object describing the model's capabilities and constraints + */ + get profile() { + if (this._profile) return this._profile; + const cacheKey = this._getCacheKey({}); + return this._modelInstanceCache.get(cacheKey)?.profile ?? {}; + } + /** @internal */ + _getCacheKey(config) { + let toStringify = config ?? {}; + if (toStringify.configurable) { + const { configurable } = toStringify; + const filtered = {}; + for (const [k, v] of Object.entries(configurable)) if (!k.startsWith("__pregel_")) filtered[k] = v; + toStringify = { + ...toStringify, + configurable: filtered + }; + } + return JSON.stringify(toStringify); + } +}; +/** +* Initialize a ChatModel from the model name and provider. +* Must have the integration package corresponding to the model provider installed. +* +* @template {extends BaseLanguageModelInput = BaseLanguageModelInput} RunInput - The input type for the model. +* @template {extends ConfigurableChatModelCallOptions = ConfigurableChatModelCallOptions} CallOptions - Call options for the model. +* +* @param {string | ChatModelProvider} [model] - The name of the model, e.g. "gpt-4", "claude-3-opus-20240229". +* Can be prefixed with the model provider, e.g. "openai:gpt-4", "anthropic:claude-3-opus-20240229". +* @param {Object} [fields] - Additional configuration options. +* @param {string} [fields.modelProvider] - The model provider. Supported values include: +* - openai (@langchain/openai) +* - anthropic (@langchain/anthropic) +* - azure_openai (@langchain/openai) +* - google-vertexai (@langchain/google-vertexai) +* - google-vertexai-web (@langchain/google-vertexai-web) +* - google-genai (@langchain/google-genai) +* - bedrock (@langchain/aws) +* - cohere (@langchain/cohere) +* - fireworks (@langchain/fireworks) +* - together (@langchain/together-ai) +* - mistralai (@langchain/mistralai) +* - groq (@langchain/groq) +* - ollama (@langchain/ollama) +* - perplexity (@langchain/perplexity) +* - cerebras (@langchain/cerebras) +* - deepseek (@langchain/deepseek) +* - xai (@langchain/xai) +* @param {string[] | "any"} [fields.configurableFields] - Which model parameters are configurable: +* - undefined: No configurable fields. +* - "any": All fields are configurable. (See Security Note in description) +* - string[]: Specified fields are configurable. +* @param {string} [fields.configPrefix] - Prefix for configurable fields at runtime. +* @param {ModelProfile} [fields.profile] - Overrides the profiling information for the model. If not provided, +* the profile will be inferred from the inner model instance. +* @param {Record} [fields.params] - Additional keyword args to pass to the ChatModel constructor. +* @returns {Promise>} A class which extends BaseChatModel. +* @throws {Error} If modelProvider cannot be inferred or isn't supported. +* @throws {Error} If the model provider integration package is not installed. +* +* @example Initialize non-configurable models +* ```typescript +* import { initChatModel } from "langchain/chat_models/universal"; +* +* const gpt4 = await initChatModel("openai:gpt-4", { +* temperature: 0.25, +* }); +* const gpt4Result = await gpt4.invoke("what's your name"); +* +* const claude = await initChatModel("anthropic:claude-3-opus-20240229", { +* temperature: 0.25, +* }); +* const claudeResult = await claude.invoke("what's your name"); +* +* const gemini = await initChatModel("gemini-1.5-pro", { +* modelProvider: "google-vertexai", +* temperature: 0.25, +* }); +* const geminiResult = await gemini.invoke("what's your name"); +* ``` +* +* @example Create a partially configurable model with no default model +* ```typescript +* import { initChatModel } from "langchain/chat_models/universal"; +* +* const configurableModel = await initChatModel(undefined, { +* temperature: 0, +* configurableFields: ["model", "apiKey"], +* }); +* +* const gpt4Result = await configurableModel.invoke("what's your name", { +* configurable: { +* model: "gpt-4", +* }, +* }); +* +* const claudeResult = await configurableModel.invoke("what's your name", { +* configurable: { +* model: "claude-sonnet-4-5-20250929", +* }, +* }); +* ``` +* +* @example Create a fully configurable model with a default model and a config prefix +* ```typescript +* import { initChatModel } from "langchain/chat_models/universal"; +* +* const configurableModelWithDefault = await initChatModel("gpt-4", { +* modelProvider: "openai", +* configurableFields: "any", +* configPrefix: "foo", +* temperature: 0, +* }); +* +* const openaiResult = await configurableModelWithDefault.invoke( +* "what's your name", +* { +* configurable: { +* foo_apiKey: process.env.OPENAI_API_KEY, +* }, +* } +* ); +* +* const claudeResult = await configurableModelWithDefault.invoke( +* "what's your name", +* { +* configurable: { +* foo_model: "claude-sonnet-4-5-20250929", +* foo_modelProvider: "anthropic", +* foo_temperature: 0.6, +* foo_apiKey: process.env.ANTHROPIC_API_KEY, +* }, +* } +* ); +* ``` +* +* @example Bind tools to a configurable model: +* ```typescript +* import { initChatModel } from "langchain/chat_models/universal"; +* import { z } from "zod/v3"; +* import { tool } from "@langchain/core/tools"; +* +* const getWeatherTool = tool( +* (input) => { +* // Do something with the input +* return JSON.stringify(input); +* }, +* { +* schema: z +* .object({ +* location: z +* .string() +* .describe("The city and state, e.g. San Francisco, CA"), +* }) +* .describe("Get the current weather in a given location"), +* name: "GetWeather", +* description: "Get the current weather in a given location", +* } +* ); +* +* const getPopulationTool = tool( +* (input) => { +* // Do something with the input +* return JSON.stringify(input); +* }, +* { +* schema: z +* .object({ +* location: z +* .string() +* .describe("The city and state, e.g. San Francisco, CA"), +* }) +* .describe("Get the current population in a given location"), +* name: "GetPopulation", +* description: "Get the current population in a given location", +* } +* ); +* +* const configurableModel = await initChatModel("gpt-4", { +* configurableFields: ["model", "modelProvider", "apiKey"], +* temperature: 0, +* }); +* +* const configurableModelWithTools = configurableModel.bindTools([ +* getWeatherTool, +* getPopulationTool, +* ]); +* +* const configurableToolResult = await configurableModelWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?", +* { +* configurable: { +* apiKey: process.env.OPENAI_API_KEY, +* }, +* } +* ); +* +* const configurableToolResult2 = await configurableModelWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?", +* { +* configurable: { +* model: "claude-sonnet-4-5-20250929", +* apiKey: process.env.ANTHROPIC_API_KEY, +* }, +* } +* ); +* ``` +* +* @example Initialize a model with a custom profile +* ```typescript +* import { initChatModel } from "langchain/chat_models/universal"; +* +* const model = await initChatModel("gpt-4o-mini", { +* profile: { +* maxInputTokens: 100000, +* }, +* }); +* +* @description +* This function initializes a ChatModel based on the provided model name and provider. +* It supports various model providers and allows for runtime configuration of model parameters. +* +* Security Note: Setting `configurableFields` to "any" means fields like apiKey, baseUrl, etc. +* can be altered at runtime, potentially redirecting model requests to a different service/user. +* Make sure that if you're accepting untrusted configurations, you enumerate the +* `configurableFields` explicitly. +* +* The function will attempt to infer the model provider from the model name if not specified. +* Certain model name prefixes are associated with specific providers: +* - gpt-3... or gpt-4... -> openai +* - claude... -> anthropic +* - amazon.... -> bedrock +* - gemini... -> google-vertexai +* - command... -> cohere +* - accounts/fireworks... -> fireworks +* +* @since 0.2.11 +* @version 0.2.11 +*/ +async function initChatModel(model, fields) { + let { configurableFields, configPrefix, modelProvider, profile, ...params } = { + configPrefix: "", + ...fields ?? {} + }; + if (modelProvider === void 0 && model?.includes(":")) { + const [provider, ...remainingParts] = model.split(":"); + const modelComponents = remainingParts.length === 0 ? [provider] : [provider, remainingParts.join(":")]; + if (SUPPORTED_PROVIDERS.includes(modelComponents[0])) [modelProvider, model] = modelComponents; + } + let configurableFieldsCopy = Array.isArray(configurableFields) ? [...configurableFields] : configurableFields; + if (!model && configurableFieldsCopy === void 0) configurableFieldsCopy = ["model", "modelProvider"]; + if (configPrefix && configurableFieldsCopy === void 0) console.warn(`{ configPrefix: ${configPrefix} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`); + const paramsCopy = { ...params }; + let configurableModel; + if (configurableFieldsCopy === void 0) configurableModel = new ConfigurableModel({ + defaultConfig: { + ...paramsCopy, + model, + modelProvider + }, + configPrefix, + profile + }); + else { + if (model) paramsCopy.model = model; + if (modelProvider) paramsCopy.modelProvider = modelProvider; + configurableModel = new ConfigurableModel({ + defaultConfig: paramsCopy, + configPrefix, + configurableFields: configurableFieldsCopy, + profile + }); + } + await configurableModel._getModelInstance(); + return configurableModel; +} +//#endregion +//#region node_modules/langchain/dist/tools/headless.js +/** +* Unified Tool Primitive for LangChain Agents +* +* This module re-exports the `tool` primitive from `@langchain/core/tools` with +* an additional overload: when called without an implementation function, it +* creates a **headless tool** that interrupts agent execution and delegates the +* implementation to the client (e.g. via `useStream({ tools: [...] })`). +* +* @module +*/ +function createHeadlessTool(fields) { + const { name, description, schema } = fields; + const wrappedTool = tool(async (args, config) => { + const { interrupt } = await import("./@langchain/langgraph+[...].mjs").then((n) => n.t); + return interrupt({ + type: "tool", + toolCall: { + id: config?.toolCall?.id, + name, + args + } + }); + }, { + name, + description, + schema, + metadata: { headlessTool: true } + }); + const headlessTool = Object.assign(wrappedTool, { implement: (execute) => ({ + tool: headlessTool, + execute + }) }); + return headlessTool; +} +/** +* Unified tool primitive for LangChain agents. +* +* Enhances the `tool` function from `@langchain/core/tools` with a headless +* overload: when called **without** an implementation function, the tool +* interrupts agent execution and lets the client supply the implementation. +* +* --- +* +* **Normal tool** — pass an implementation function as the first argument: +* +* ```typescript +* import { tool } from "langchain/tools"; +* import { z } from "zod"; +* +* const getWeather = tool( +* async ({ city }) => `The weather in ${city} is sunny.`, +* { +* name: "get_weather", +* description: "Get the weather for a city", +* schema: z.object({ city: z.string() }), +* } +* ); +* ``` +* +* --- +* +* **Headless tool** — omit the implementation; the client provides it later: +* +* ```typescript +* import { tool } from "langchain/tools"; +* import { z } from "zod"; +* +* // Server: define the tool shape — no implementation needed +* export const getLocation = tool({ +* name: "get_location", +* description: "Get the user's current GPS location", +* schema: z.object({ +* highAccuracy: z.boolean().optional().describe("Request high accuracy GPS"), +* }), +* }); +* +* // Server: register with the agent +* const agent = createAgent({ +* model: "openai:gpt-4o", +* tools: [getLocation], +* }); +* +* // Client: provide the implementation in useStream +* const stream = useStream({ +* assistantId: "agent", +* tools: [ +* getLocation.implement(async ({ highAccuracy }) => { +* return new Promise((resolve, reject) => { +* navigator.geolocation.getCurrentPosition( +* (pos) => resolve({ +* latitude: pos.coords.latitude, +* longitude: pos.coords.longitude, +* }), +* (err) => reject(new Error(err.message)), +* { enableHighAccuracy: highAccuracy } +* ); +* }); +* }), +* ], +* }); +* ``` +*/ +var tool$1 = ((funcOrFields, fields) => { + if (typeof funcOrFields !== "function") return createHeadlessTool(funcOrFields); + return tool(funcOrFields, fields); +}); +//#endregion +//#region node_modules/langchain/dist/agents/errors.js +var MultipleToolsBoundError = class extends Error { + constructor() { + super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter."); + } +}; +/** +* Raised when model returns multiple structured output tool calls when only one is expected. +*/ +var MultipleStructuredOutputsError = class extends Error { + toolNames; + constructor(toolNames) { + super(`The model has called multiple tools: ${toolNames.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`); + this.toolNames = toolNames; + } +}; +/** +* Raised when structured output tool call arguments fail to parse according to the schema. +*/ +var StructuredOutputParsingError = class extends Error { + toolName; + errors; + constructor(toolName, errors) { + super(`Failed to parse structured output for tool '${toolName}':${errors.map((e) => `\n - ${e}`).join("")}.`); + this.toolName = toolName; + this.errors = errors; + } +}; +/** +* Raised when a tool call is throwing an error. +*/ +var ToolInvocationError = class extends Error { + "~brand" = "ToolInvocationError"; + toolCall; + toolError; + constructor(toolError, toolCall) { + const error = toolError instanceof Error ? toolError : new Error(String(toolError)); + const toolArgs = JSON.stringify(toolCall.args); + super(`Error invoking tool '${toolCall.name}' with kwargs ${toolArgs} with error: ${error.stack}\n Please fix the error and try again.`); + this.toolCall = toolCall; + this.toolError = error; + } + /** + * Check if the error is a ToolInvocationError. + * @param error - The error to check + * @returns Whether the error is a ToolInvocationError + */ + static isInstance(error) { + return error instanceof Error && "~brand" in error && error["~brand"] === "ToolInvocationError"; + } +}; +/** +* Error thrown when a middleware fails. +* +* Use `MiddlewareError.wrap()` to create instances. The constructor is private +* to ensure that GraphBubbleUp errors (like GraphInterrupt) are never wrapped. +*/ +var MiddlewareError = class MiddlewareError extends Error { + "~brand" = "MiddlewareError"; + constructor(error, middlewareName) { + const errorMessage = error instanceof Error ? error.message : String(error); + super(errorMessage); + this.name = error instanceof Error ? error.name : `${middlewareName[0].toUpperCase() + middlewareName.slice(1)}Error`; + if (error instanceof Error) this.cause = error; + } + /** + * Wrap an error in a MiddlewareError, unless it's a GraphBubbleUp error + * (like GraphInterrupt) which should propagate unchanged. + * + * @param error - The error to wrap + * @param middlewareName - The name of the middleware that threw the error + * @returns The original error if it's a GraphBubbleUp, otherwise a new MiddlewareError + */ + static wrap(error, middlewareName) { + if (isGraphBubbleUp(error)) return error; + return new MiddlewareError(error, middlewareName); + } + /** + * Check if the error is a MiddlewareError. + * @param error - The error to check + * @returns Whether the error is a MiddlewareError + */ + static isInstance(error) { + return error instanceof Error && "~brand" in error && error["~brand"] === "MiddlewareError"; + } +}; +//#endregion +//#region node_modules/langchain/dist/agents/model.js +function isBaseChatModel(model) { + return "invoke" in model && typeof model.invoke === "function" && "_streamResponseChunks" in model; +} +function isConfigurableModel(model) { + return typeof model === "object" && model != null && "_queuedMethodOperations" in model && "_getModelInstance" in model && typeof model._getModelInstance === "function"; +} +//#endregion +//#region node_modules/langchain/dist/agents/responses.js +/** +* Default value for strict mode in providerStrategy. +* +* When using providerStrategy with json_schema response format, OpenAI's parse() method +* requires all function tools to have strict: true. This ensures the model's output +* exactly matches the provided JSON schema. +* +* @see https://platform.openai.com/docs/guides/structured-outputs +*/ +var PROVIDER_STRATEGY_DEFAULT_STRICT = true; +/** +* This is a global counter for generating unique names for tools. +*/ +var bindingIdentifier = 0; +/** +* Information for tracking structured output tool metadata. +* This contains all necessary information to handle structured responses generated +* via tool calls, including the original schema, its type classification, and the +* corresponding tool implementation used by the tools strategy. +*/ +var ToolStrategy = class ToolStrategy { + constructor(schema, tool, options) { + this.schema = schema; + this.tool = tool; + this.options = options; + } + get name() { + return this.tool.function.name; + } + static fromSchema(schema, outputOptions) { + /** + * It is required for tools to have a name so we can map the tool call to the correct tool + * when parsing the response. + */ + function getFunctionName(name) { + return name ?? `extract-${++bindingIdentifier}`; + } + if (isSerializableSchema(schema) || isInteropZodSchema(schema)) { + const asJsonSchema = toJsonSchema(schema); + return new ToolStrategy(asJsonSchema, { + type: "function", + function: { + name: getFunctionName(asJsonSchema.title), + strict: false, + description: asJsonSchema.description ?? "Tool for extracting structured output from the model's response.", + parameters: asJsonSchema + } + }, outputOptions); + } + let functionDefinition; + if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) functionDefinition = schema; + else functionDefinition = { + name: getFunctionName(schema.title), + description: schema.description ?? "", + parameters: schema.schema || schema + }; + return new ToolStrategy(toJsonSchema(schema), { + type: "function", + function: functionDefinition + }, outputOptions); + } + /** + * Parse tool arguments according to the schema. + * + * @throws {StructuredOutputParsingError} if the response is not valid + * @param toolArgs - The arguments from the tool call + * @returns The parsed response according to the schema type + */ + parse(toolArgs) { + const result = new Validator(this.schema).validate(toolArgs); + if (!result.valid) throw new StructuredOutputParsingError(this.name, result.errors.map((e) => e.error)); + return toolArgs; + } +}; +var ProviderStrategy = class ProviderStrategy { + _schemaType; + /** + * The schema to use for the provider strategy + */ + schema; + /** + * Whether to use strict mode for the provider strategy + */ + strict; + constructor(schemaOrOptions, strict) { + if ("schema" in schemaOrOptions && typeof schemaOrOptions.schema === "object" && schemaOrOptions.schema !== null && !("type" in schemaOrOptions)) { + const options = schemaOrOptions; + this.schema = options.schema; + this.strict = options.strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT; + } else { + this.schema = schemaOrOptions; + this.strict = strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT; + } + } + static fromSchema(schema, strict) { + return new ProviderStrategy(toJsonSchema(schema), strict); + } + /** + * Parse tool arguments according to the schema. If the response is not valid, return undefined. + * + * @param response - The AI message response to parse + * @returns The parsed response according to the schema type + */ + parse(response) { + /** + * Extract text content from the response. + * Handles both string content and array content (e.g., from thinking models). + */ + let textContent; + if (typeof response.content === "string") textContent = response.content; + else if (Array.isArray(response.content)) { + /** + * For thinking models, content is an array with thinking blocks and text blocks. + * Extract the text from text blocks. + */ + for (const block of response.content) if (typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") { + textContent = block.text; + break; + } + } + if (!textContent || textContent === "") return; + try { + const content = JSON.parse(textContent); + if (!new Validator(this.schema).validate(content).valid) return; + return content; + } catch {} + } +}; +/** +* Handle user input for `responseFormat` parameter of `CreateAgentParams`. +* This function defines the default behavior for the `responseFormat` parameter, which is: +* +* - if value is a Zod schema, default to structured output via tool calling +* - if value is a JSON schema, default to structured output via tool calling +* - if value is a custom response format, return it as is +* - if value is an array, ensure all array elements are instance of `ToolStrategy` +* @param responseFormat - The response format to transform, provided by the user +* @param options - The response format options for tool strategy +* @param model - The model to check if it supports JSON schema output +* @returns +*/ +function transformResponseFormat(responseFormat, options, model) { + if (!responseFormat) return []; + if (typeof responseFormat === "object" && responseFormat !== null && "__responseFormatUndefined" in responseFormat) return []; + /** + * If users provide an array, it should only contain raw schemas (Zod, Standard Schema or JSON schema), + * not ToolStrategy or ProviderStrategy instances. + */ + if (Array.isArray(responseFormat)) { + /** + * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is + */ + if (responseFormat.every((item) => item instanceof ToolStrategy || item instanceof ProviderStrategy)) return responseFormat; + /** + * Check if all items are Standard Schema + */ + if (responseFormat.every((item) => isSerializableSchema(item))) return responseFormat.map((item) => ToolStrategy.fromSchema(item, options)); + /** + * Check if all items are Zod schemas + */ + if (responseFormat.every((item) => isInteropZodObject(item))) return responseFormat.map((item) => ToolStrategy.fromSchema(item, options)); + /** + * Check if all items are plain objects (JSON schema) + */ + if (responseFormat.every((item) => typeof item === "object" && item !== null && !isInteropZodObject(item) && !isSerializableSchema(item))) return responseFormat.map((item) => ToolStrategy.fromSchema(item, options)); + throw new Error("Invalid response format: list contains mixed types.\nAll items must be either InteropZodObject, Standard Schema, or plain JSON schema objects."); + } + if (responseFormat instanceof ToolStrategy || responseFormat instanceof ProviderStrategy) return [responseFormat]; + const useProviderStrategy = hasSupportForJsonSchemaOutput(model); + /** + * `responseFormat` is a Standard Schema + */ + if (isSerializableSchema(responseFormat)) return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)]; + /** + * `responseFormat` is a Zod schema + */ + if (isInteropZodObject(responseFormat)) return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)]; + /** + * Handle plain object (JSON schema) + */ + if (typeof responseFormat === "object" && responseFormat !== null && "properties" in responseFormat) return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)]; + throw new Error(`Invalid response format: ${String(responseFormat)}`); +} +/** +* Creates a tool strategy for structured output using function calling. +* +* This function configures structured output by converting schemas into function tools that +* the model calls. Unlike `providerStrategy`, which uses native JSON schema support, +* `toolStrategy` works with any model that supports function calling, making it more +* widely compatible across providers and model versions. +* +* The model will call a function with arguments matching your schema, and the agent will +* extract and validate the structured output from the tool call. This approach is automatically +* used when your model doesn't support native JSON schema output. +* +* @param responseFormat - The schema(s) to enforce. Can be a single Zod schema, a Standard Schema +* (e.g., Valibot, ArkType, TypeBox), a JSON schema object, or arrays of any of these. +* @param options - Optional configuration for the tool strategy +* @param options.handleError - How to handle errors when the model calls multiple structured output tools +* or when the output doesn't match the schema. Defaults to `true` (auto-retry). Can be `false` (throw), +* a `string` (retry with message), or a `function` (custom handler). +* @param options.toolMessageContent - Custom message content to include in conversation history +* when structured output is generated via tool call +* @returns A `TypedToolStrategy` instance that can be used as the `responseFormat` in `createAgent` +* +* @example +* ```ts +* import { toolStrategy, createAgent } from "langchain"; +* import { z } from "zod"; +* +* const agent = createAgent({ +* model: "claude-haiku-4-5", +* responseFormat: toolStrategy( +* z.object({ +* answer: z.string(), +* confidence: z.number().min(0).max(1), +* }) +* ), +* }); +* ``` +* +* @example +* ```ts +* // Multiple schemas - model can choose which one to use +* const agent = createAgent({ +* model: "claude-haiku-4-5", +* responseFormat: toolStrategy([ +* z.object({ name: z.string(), age: z.number() }), +* z.object({ email: z.string(), phone: z.string() }), +* ]), +* }); +* ``` +*/ +function toolStrategy(responseFormat, options) { + return transformResponseFormat(responseFormat, options); +} +/** +* Identifies the models that support JSON schema output by reading +* the model's profile metadata. +* +* @param model - A resolved model instance to check. Callers should resolve +* string model names and ConfigurableModel wrappers before calling this. +* @returns True if the model supports JSON schema output, false otherwise +*/ +function hasSupportForJsonSchemaOutput(model) { + if (!model || !isBaseChatModel(model) || !("profile" in model) || typeof model.profile !== "object" || !model.profile) return false; + return "structuredOutput" in model.profile && model.profile.structuredOutput === true; +} +//#endregion +//#region node_modules/langchain/dist/agents/middleware/utils.js +/** +* Default token counter that approximates based on character count. +* +* If tools are provided, the token count also includes stringified tool schemas. +* +* @param messages Messages to count tokens for +* @param tools Optional list of tools to include in the token count. Each tool +* can be either a LangChain tool instance or a dict representing a tool schema. +* LangChain tool instances are converted to OpenAI tool format before counting. +* @returns Approximate token count +*/ +function countTokensApproximately(messages, tools) { + const charsPerToken = 4; + let totalChars = 0; + if (tools && tools.length > 0) { + let toolsChars = 0; + for (const tool of tools) { + const toolDict = isLangChainTool(tool) ? convertToOpenAITool(tool) : tool; + toolsChars += JSON.stringify(toolDict).length; + } + totalChars += toolsChars; + } + for (const msg of messages) { + let textContent; + if (typeof msg.content === "string") textContent = msg.content; + else if (Array.isArray(msg.content)) textContent = msg.content.map((item) => { + if (typeof item === "string") return item; + if (item.type === "text" && "text" in item) return item.text; + return ""; + }).join(""); + else textContent = ""; + if (AIMessage.isInstance(msg) && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) textContent += JSON.stringify(msg.tool_calls); + if (ToolMessage.isInstance(msg)) textContent += msg.tool_call_id ?? ""; + totalChars += textContent.length; + } + return Math.ceil(totalChars / charsPerToken); +} +function getHookConstraint(hook) { + if (!hook || typeof hook === "function") return; + return hook.canJumpTo; +} +function getHookFunction(arg) { + if (typeof arg === "function") return arg; + return arg.hook; +} +//#endregion +//#region node_modules/langchain/dist/agents/transformers/tool-call.js +/** +* Returns true when `ns` belongs to the agent's own graph — i.e. it +* starts with `path` and is at most one level deeper (the agent's +* internal nodes like `tools`, `model_request`, etc.). +* +* Events from subagent subgraphs (two or more levels deeper) are +* excluded, so `run.toolCalls` / `run.middleware` only show events +* from the agent itself, not from its subagents. +*/ +function isOwnEvent(ns, path) { + if (ns.length < path.length || ns.length > path.length + 1) return false; + for (let i = 0; i < path.length; i += 1) if (ns[i] !== path[i]) return false; + return true; +} +/** +* Detects when a `tool-error` payload is actually a graph interrupt rather +* than a genuine tool failure. +* +* A tool that calls `interrupt()` throws a `GraphInterrupt`, whose message is +* the JSON-serialized `Interrupt[]` array. Each entry has the LangGraph +* `Interrupt` shape `{ id, value }`: a stable `id` (a hash of the checkpoint +* namespace, generated by `interrupt()` and always present during graph +* execution) plus the `value` passed to `interrupt(...)`. We require BOTH a +* string `id` and a `value` on every entry — a bare `value` is not a reliable +* discriminator, since a genuine tool error message can also be a JSON array +* of `{ value }` records (e.g. a validator emitting +* `[{ "value": "bad input", "message": "invalid" }]`). Keying off the +* interrupt `id` keeps real tool failures on the error path. +* +* An interrupt is control flow that *suspends* the run (the tool re-runs on +* resume); it is not an error, so the tool call must stay pending rather than +* have its `output` promise rejected. Any interrupt qualifies regardless of +* its `value` shape: HITL middleware interrupts (`value.type === "tool"`) and +* raw `interrupt(...)` calls from inside a tool are treated identically — +* raising an interrupt in a tool must work whether or not +* `humanInTheLoopMiddleware` is involved. +*/ +function isToolInterrupt(message) { + let parsed; + try { + parsed = JSON.parse(message); + } catch { + return false; + } + if (!Array.isArray(parsed) || parsed.length === 0) return false; + return parsed.every((entry) => { + if (entry == null || typeof entry !== "object") return false; + const record = entry; + return typeof record.id === "string" && "value" in record; + }); +} +/** +* Detects serialized LangChain `ToolMessage` values that can appear on +* `tool-finished.output` after crossing a protocol or serialization boundary. +* +* @example +* ```ts +* { +* lc: 1, +* type: "constructor", +* id: ["langchain_core", "messages", "ToolMessage"], +* kwargs: { content: "raw tool result", tool_call_id: "call_1" } +* } +* ``` +*/ +function isSerializedToolMessage(value) { + if (value == null || typeof value !== "object") return false; + const record = value; + if (record.type !== "constructor" || !Array.isArray(record.id)) return false; + return record.id[record.id.length - 1] === "ToolMessage"; +} +function normalizeToolOutput(output) { + if (ToolMessage.isInstance(output)) return output.content; + if (isSerializedToolMessage(output)) return output.kwargs?.content; + return output; +} +/** +* Creates a native transformer that correlates `tools` channel events +* into per-call {@link ToolCallStream} objects. +* +* Marked `__native: true` — projection keys land directly on the +* `GraphRunStream` instance as `run.toolCalls`. +*/ +function createToolCallTransformer(path) { + return () => { + const toolCallsLog = StreamChannel.local(); + const pendingCalls = /* @__PURE__ */ new Map(); + function createToolCallEntry(callId, name, rawInput) { + if (pendingCalls.has(callId)) return; + const input = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput; + let resolveOutput; + let rejectOutput; + let resolveStatus; + let resolveError; + const output = new Promise((res, rej) => { + resolveOutput = res; + rejectOutput = rej; + }); + const status = new Promise((res) => { + resolveStatus = res; + }); + const error = new Promise((res) => { + resolveError = res; + }); + pendingCalls.set(callId, { + resolveOutput, + rejectOutput, + resolveStatus, + resolveError + }); + toolCallsLog.push({ + name, + callId, + input, + output, + status, + error + }); + } + return { + __native: true, + init: () => ({ toolCalls: toolCallsLog }), + process(event) { + /** + * Only process events that are at the same depth as the agent's graph. + */ + if (!isOwnEvent(event.params.namespace, path)) return true; + if (event.method === "messages") { + const data = event.params.data; + if (data.event === "content-block-finish") { + const cb = data.contentBlock ?? data.content_block; + if (cb?.type === "tool_call") createToolCallEntry(String(cb.id ?? ""), String(cb.name ?? ""), cb.args ?? cb.input); + } + } + if (event.method === "tools") { + const data = event.params.data; + const toolCallId = data.tool_call_id; + if (data.event === "tool-started") createToolCallEntry(toolCallId, data.tool_name ?? "unknown", data.input); + const pending = toolCallId ? pendingCalls.get(toolCallId) : void 0; + if (pending) { + if (data.event === "tool-finished") { + pending.resolveOutput(normalizeToolOutput(data.output)); + pending.resolveStatus("finished"); + pending.resolveError(void 0); + pendingCalls.delete(toolCallId); + } else if (data.event === "tool-error") { + const message = data.message ?? "unknown error"; + if (isToolInterrupt(message)) return true; + pending.rejectOutput(new Error(message)); + pending.resolveStatus("error"); + pending.resolveError(message); + pendingCalls.delete(toolCallId); + } + } + } + return true; + }, + finalize() { + for (const pending of pendingCalls.values()) { + pending.resolveStatus("finished"); + pending.resolveError(void 0); + pending.resolveOutput(void 0); + } + pendingCalls.clear(); + toolCallsLog.close(); + }, + fail(err) { + for (const pending of pendingCalls.values()) { + pending.resolveStatus("error"); + pending.resolveError(err instanceof Error ? err.message : String(err)); + pending.rejectOutput(err); + } + pendingCalls.clear(); + toolCallsLog.fail(err); + } + }; + }; +} +//#endregion +//#region node_modules/langchain/dist/agents/transformers/subagent.js +function isRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +/** Stable string key for a namespace. */ +function nsKey(ns) { + return ns.join("\0"); +} +/** Tests whether `ns` starts with every segment in `prefix`. */ +function hasPrefix(ns, prefix) { + if (prefix.length > ns.length) return false; + for (let i = 0; i < prefix.length; i += 1) if (ns[i] !== prefix[i]) return false; + return true; +} +/** +* Creates a native transformer that surfaces nested named agents on +* `run.subagents`. +* +* It watches `tasks` events to record each namespace's `lc_agent_name` (set by +* `createAgent({ name })`) and the triggering tool call, then — for any nested +* run one level below {@link scope} that carries an `lc_agent_name` — emits a +* typed {@link SubagentRunStream} handle. +* +* Each handle is backed by its own per-subagent transformer instances +* ({@link createMessagesTransformer}, {@link createToolCallTransformer}, and a +* nested {@link createSubagentTransformer}) scoped to the subagent's namespace. +* Every event in the subtree is fed straight into those transformers, which +* self-filter by namespace; the subagent's final `output` is resolved from its +* last `values` snapshot when its `lifecycle` completes. +* +* Marked `__native: true` — the `subagents` projection lands directly on the +* `GraphRunStream` instance as `run.subagents`. +* +* @param scope - Namespace prefix this transformer is scoped to. The root agent +* uses `[]`; nested handles use their subagent's namespace, so grandchild +* subagents are discovered recursively. +*/ +function createSubagentTransformer(scope = []) { + return () => { + const subagentsLog = StreamChannel.local(); + /** `lc_agent_name` observed per namespace (first task event wins). */ + const lcByNs = /* @__PURE__ */ new Map(); + /** Triggering task id -> originating LLM `tool_call_id`. */ + const pendingToolCalls = /* @__PURE__ */ new Map(); + /** + * Namespace key -> the `tool_call_id` of the most recent tool to start + * executing there. A tool that invokes a subagent emits its `tool-started` + * at the tools-node namespace (`tools:`) where the subagent then + * roots, so this is the tool call that caused the subagent. + */ + const activeToolCallByNs = /* @__PURE__ */ new Map(); + const handles = /* @__PURE__ */ new Map(); + const depth = scope.length; + function recordIdentity(ns, data) { + const key = nsKey(ns); + if (lcByNs.has(key)) return; + const lc = (isRecord(data) && isRecord(data.metadata) ? data.metadata : void 0)?.lc_agent_name; + lcByNs.set(key, typeof lc === "string" ? lc : void 0); + } + function recordPendingToolCalls(data) { + if (!isRecord(data)) return; + const taskId = data.id; + if (typeof taskId !== "string") return; + const input = data.input; + let toolCallId; + if (isRecord(input) && isRecord(input.tool_call)) { + const candidate = input.tool_call.id; + if (typeof candidate === "string") toolCallId = candidate; + } else if (Array.isArray(input)) { + for (const toolCall of input) if (isRecord(toolCall) && typeof toolCall.id === "string") { + toolCallId = toolCall.id; + break; + } + } + if (toolCallId != null) pendingToolCalls.set(taskId, toolCallId); + } + /** + * Derive the `toolCall` cause for a named-subagent namespace. + * + * Primary signal: the tool whose `tool-started` event fired at the + * subagent's own namespace (the tools node it roots under). Fallback: the + * namespace segment's task id (`node:`) joined to a tool call + * harvested from a `tool_call_with_context`-shaped task input, so the + * derivation stays correct if that shape reaches the stream in the future. + */ + function deriveCause(ns) { + const active = activeToolCallByNs.get(nsKey(ns)); + if (typeof active === "string" && active.length > 0) return { + type: "toolCall", + tool_call_id: active + }; + const segment = ns[ns.length - 1]; + const colon = segment.indexOf(":"); + if (colon === -1) return void 0; + const triggerCallId = segment.slice(colon + 1); + if (triggerCallId.length === 0) return void 0; + const toolCallId = pendingToolCalls.get(triggerCallId); + if (typeof toolCallId !== "string" || toolCallId.length === 0) return; + return { + type: "toolCall", + tool_call_id: toolCallId + }; + } + function maybeStartSubagent(ns) { + if (ns.length !== depth + 1 || !hasPrefix(ns, scope)) return; + const key = nsKey(ns); + if (handles.has(key)) return; + const lc = lcByNs.get(key); + if (typeof lc !== "string" || lc.length === 0) return; + const messages = createMessagesTransformer(ns); + const messagesProjection = messages.init(); + const toolCall = createToolCallTransformer(ns)(); + const toolCallProjection = toolCall.init(); + const nested = createSubagentTransformer(ns)(); + const nestedProjection = nested.init(); + let resolveOutput; + let rejectOutput; + const output = new Promise((resolve, reject) => { + resolveOutput = resolve; + rejectOutput = reject; + }); + handles.set(key, { + key, + path: ns, + name: lc, + messages, + toolCall, + nested, + resolveOutput, + rejectOutput, + latestValues: void 0, + done: false + }); + subagentsLog.push({ + name: lc, + cause: deriveCause(ns), + output, + messages: messagesProjection.messages, + toolCalls: toolCallProjection.toolCalls, + subagents: nestedProjection.subagents + }); + } + function finishHandle(handle, outcome) { + if (handle.done) return; + handle.done = true; + if (outcome.type === "resolve") handle.resolveOutput(handle.latestValues); + else handle.rejectOutput(outcome.error); + handle.messages.finalize?.(); + handle.toolCall.finalize?.(); + handle.nested.finalize?.(); + } + return { + __native: true, + init: () => ({ subagents: subagentsLog }), + process(event) { + const ns = event.params.namespace; + const data = event.params.data; + const isTaskResult = event.method === "tasks" && isRecord(data) && "result" in data; + if (event.method === "tools" && isRecord(data) && data.event === "tool-started" && typeof data.tool_call_id === "string" && data.tool_call_id.length > 0) activeToolCallByNs.set(nsKey(ns), data.tool_call_id); + if (event.method === "tasks" && !isTaskResult) { + recordIdentity(ns, data); + recordPendingToolCalls(data); + maybeStartSubagent(ns); + } + for (const handle of handles.values()) { + if (handle.done) continue; + if (!hasPrefix(ns, handle.path)) continue; + handle.messages.process(event); + handle.toolCall.process(event); + handle.nested.process(event); + if (nsKey(ns) === handle.key) { + if (event.method === "values" && isRecord(data)) handle.latestValues = data; + else if (event.method === "lifecycle" && isRecord(data)) { + const status = data.event; + if (status === "completed" || status === "interrupted") finishHandle(handle, { type: "resolve" }); + else if (status === "failed") finishHandle(handle, { + type: "reject", + error: /* @__PURE__ */ new Error(`Subagent ${handle.name} failed`) + }); + } + } + } + return true; + }, + finalize() { + for (const handle of handles.values()) finishHandle(handle, { type: "resolve" }); + subagentsLog.close(); + }, + fail(err) { + for (const handle of handles.values()) finishHandle(handle, { + type: "reject", + error: err + }); + subagentsLog.fail(err); + } + }; + }; +} +//#endregion +//#region node_modules/langchain/dist/agents/middleware/types.js +/** +* Unique symbol used to brand middleware instances. +* This prevents functions from being accidentally assignable to AgentMiddleware +* since functions have a 'name' property that would otherwise make them structurally compatible. +*/ +var MIDDLEWARE_BRAND = Symbol.for("AgentMiddleware"); +//#endregion +//#region node_modules/langchain/dist/agents/middleware.js +/** +* Creates a middleware instance with automatic schema inference. +* +* @param config - Middleware configuration +* @param config.name - The name of the middleware +* @param config.stateSchema - The schema of the middleware state +* @param config.contextSchema - The schema of the middleware context +* @param config.wrapModelCall - The function to wrap model invocation +* @param config.wrapToolCall - The function to wrap tool invocation +* @param config.beforeModel - The function to run before the model call +* @param config.afterModel - The function to run after the model call +* @param config.beforeAgent - The function to run before the agent execution starts +* @param config.afterAgent - The function to run after the agent execution completes +* @param config.tools - Additional tools registered by the middleware +* @param config.streamTransformers - Stream transformer factories registered by the middleware +* @returns A middleware instance +* +* @example Using Zod schema +* ```ts +* const authMiddleware = createMiddleware({ +* name: "AuthMiddleware", +* stateSchema: z.object({ +* isAuthenticated: z.boolean().default(false), +* }), +* contextSchema: z.object({ +* userId: z.string(), +* }), +* beforeModel: async (state, runtime) => { +* if (!state.isAuthenticated) { +* throw new Error("Not authenticated"); +* } +* }, +* }); +* ``` +* +* @example Using StateSchema +* ```ts +* import { StateSchema, ReducedValue } from "@langchain/langgraph"; +* +* const historyMiddleware = createMiddleware({ +* name: "HistoryMiddleware", +* stateSchema: new StateSchema({ +* count: z.number().default(0), +* history: new ReducedValue( +* z.array(z.string()).default(() => []), +* { inputSchema: z.string(), reducer: (current, next) => [...current, next] } +* ), +* }), +* beforeModel: async (state, runtime) => { +* return { count: state.count + 1 }; +* }, +* }); +* ``` +*/ +function createMiddleware(config) { + return { + [MIDDLEWARE_BRAND]: true, + name: config.name, + stateSchema: config.stateSchema, + contextSchema: config.contextSchema, + wrapToolCall: config.wrapToolCall, + wrapModelCall: config.wrapModelCall, + beforeAgent: config.beforeAgent, + beforeModel: config.beforeModel, + afterModel: config.afterModel, + afterAgent: config.afterAgent, + tools: config.tools, + streamTransformers: config.streamTransformers + }; +} +//#endregion +//#region node_modules/langchain/dist/agents/annotation.js +function createAgentState(hasStructuredResponse = true, stateSchema, middlewareList = []) { + /** + * Collect fields from state schemas + */ + const stateFields = { jumpTo: new UntrackedValue() }; + const inputFields = {}; + const outputFields = {}; + const applySchema = (schema) => { + if (StateSchema.isInstance(schema)) { + for (const [key, field] of Object.entries(schema.fields)) if (!(key in stateFields)) { + stateFields[key] = field; + if (key.startsWith("_")) continue; + if (ReducedValue.isInstance(field)) { + inputFields[key] = field.inputSchema || field.valueSchema; + outputFields[key] = field.valueSchema; + } else { + inputFields[key] = field; + outputFields[key] = field; + } + } + return; + } + const shape = getInteropZodObjectShape(schema); + for (const [key, fieldSchema] of Object.entries(shape)) { + const isPrivate = key.startsWith("_"); + if (!(key in stateFields)) { + if (isZodSchemaV4(fieldSchema)) { + const meta = schemaMetaRegistry.get(fieldSchema); + if (meta?.reducer) { + if (meta.reducer.schema) { + stateFields[key] = new ReducedValue(fieldSchema, { + inputSchema: meta.reducer.schema, + reducer: meta.reducer.fn + }); + if (!isPrivate) { + inputFields[key] = meta.reducer.schema; + outputFields[key] = fieldSchema; + } + } else { + stateFields[key] = new ReducedValue(fieldSchema, { reducer: meta.reducer.fn }); + if (!isPrivate) { + inputFields[key] = fieldSchema; + outputFields[key] = fieldSchema; + } + } + continue; + } + } + stateFields[key] = fieldSchema; + if (!isPrivate) { + inputFields[key] = fieldSchema; + outputFields[key] = fieldSchema; + } + } + } + }; + /** + * Add state schema properties from user-provided schema. + * Supports both StateSchema and Zod v3/v4 objects. + */ + if (stateSchema && (StateSchema.isInstance(stateSchema) || isInteropZodObject(stateSchema))) applySchema(stateSchema); + /** + * Add state schema properties from middleware. + * Supports both StateSchema and Zod v3/v4 objects. + */ + for (const middleware of middlewareList) if (middleware.stateSchema && (StateSchema.isInstance(middleware.stateSchema) || isInteropZodObject(middleware.stateSchema))) applySchema(middleware.stateSchema); + if (hasStructuredResponse) outputFields.structuredResponse = new UntrackedValue(); + /** + * Create StateSchema instances for state, input, and output. + * Using MessagesValue provides the proper message reducer behavior. + */ + return { + state: new StateSchema({ + messages: MessagesValue, + ...stateFields + }), + input: new StateSchema({ + messages: MessagesValue, + ...inputFields + }), + output: new StateSchema({ + messages: MessagesValue, + ...outputFields + }) + }; +} +//#endregion +//#region node_modules/langchain/dist/agents/utils.js +var NAME_PATTERN = /(.*?)<\/name>/s; +var CONTENT_PATTERN = /(.*?)<\/content>/s; +/** +* Parse middleware state from the full agent state based on the middleware's stateSchema. +* +* Handles two types of state schemas: +* 1. Zod schemas (v3 or v4) - parsed using interopParse +* 2. LangGraph StateSchema - extracts only the keys defined in `fields` +* +* @param stateSchema - The middleware's state schema (Zod or LangGraph StateSchema) +* @param state - The full agent state to parse from +* @returns Parsed state containing only the keys defined in the schema +*/ +function parseMiddlewareState(stateSchema, state) { + if (StateSchema.isInstance(stateSchema)) { + const result = {}; + for (const key of Object.keys(stateSchema.fields)) if (key in state) result[key] = state[key]; + return result; + } + if (isInteropZodSchema(stateSchema)) return interopParse(stateSchema, state); + throw new Error(`Invalid state schema type: ${typeof stateSchema}`); +} +/** +* Attach formatted agent names to the messages passed to and from a language model. +* +* This is useful for making a message history with multiple agents more coherent. +* +* NOTE: agent name is consumed from the message.name field. +* If you're using an agent built with createAgent, name is automatically set. +* If you're building a custom agent, make sure to set the name on the AI message returned by the LLM. +* +* @param message - Message to add agent name formatting to +* @returns Message with agent name formatting +* +* @internal +*/ +function _addInlineAgentName(message) { + if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) return message; + if (!message.name) return message; + const { name } = message; + if (typeof message.content === "string") return new AIMessage({ + ...message.lc_kwargs, + content: `${name}${message.content}`, + name: void 0 + }); + const updatedContent = []; + let textBlockCount = 0; + for (const contentBlock of message.content) if (typeof contentBlock === "string") { + textBlockCount += 1; + updatedContent.push(`${name}${contentBlock}`); + } else if (typeof contentBlock === "object" && "type" in contentBlock && contentBlock.type === "text") { + textBlockCount += 1; + updatedContent.push({ + ...contentBlock, + text: `${name}${contentBlock.text}` + }); + } else updatedContent.push(contentBlock); + if (!textBlockCount) updatedContent.unshift({ + type: "text", + text: `${name}` + }); + return new AIMessage({ + ...message.lc_kwargs, + content: updatedContent, + name: void 0 + }); +} +/** +* Remove explicit name and content XML tags from the AI message content. +* +* Examples: +* +* @example +* ```typescript +* removeInlineAgentName(new AIMessage({ content: "assistantHello", name: "assistant" })) +* // AIMessage with content: "Hello" +* +* removeInlineAgentName(new AIMessage({ content: [{type: "text", text: "assistantHello"}], name: "assistant" })) +* // AIMessage with content: [{type: "text", text: "Hello"}] +* ``` +* +* @internal +*/ +function _removeInlineAgentName(message) { + if (!AIMessage.isInstance(message) || !message.content) return message; + let updatedContent = []; + let updatedName; + if (Array.isArray(message.content)) updatedContent = message.content.filter((block) => { + if (block.type === "text" && typeof block.text === "string") { + const nameMatch = block.text.match(NAME_PATTERN); + const contentMatch = block.text.match(CONTENT_PATTERN); + if (nameMatch && (!contentMatch || contentMatch[1] === "")) { + updatedName = nameMatch[1]; + return false; + } + return true; + } + return true; + }).map((block) => { + if (block.type === "text" && typeof block.text === "string") { + const nameMatch = block.text.match(NAME_PATTERN); + const contentMatch = block.text.match(CONTENT_PATTERN); + if (!nameMatch || !contentMatch) return block; + updatedName = nameMatch[1]; + return { + ...block, + text: contentMatch[1] + }; + } + return block; + }); + else { + const content = message.content; + const nameMatch = content.match(NAME_PATTERN); + const contentMatch = content.match(CONTENT_PATTERN); + if (!nameMatch || !contentMatch) return message; + updatedName = nameMatch[1]; + updatedContent = contentMatch[1]; + } + return new AIMessage({ + ...Object.keys(message.lc_kwargs ?? {}).length > 0 ? message.lc_kwargs : message, + content: updatedContent, + name: updatedName + }); +} +function isClientTool(tool) { + return Runnable.isRunnable(tool); +} +/** +* Helper function to check if a language model has a bindTools method. +* @param llm - The language model to check if it has a bindTools method. +* @returns True if the language model has a bindTools method, false otherwise. +*/ +function _isChatModelWithBindTools(llm) { + if (!isBaseChatModel(llm)) return false; + return "bindTools" in llm && typeof llm.bindTools === "function"; +} +/** +* Helper function to bind tools to a language model. +* @param llm - The language model to bind tools to. +* @param toolClasses - The tools to bind to the language model. +* @param options - The options to pass to the language model. +* @returns The language model with the tools bound to it. +*/ +var _simpleBindTools = (llm, toolClasses, options = {}) => { + if (_isChatModelWithBindTools(llm)) return llm.bindTools(toolClasses, options); + if (RunnableBinding.isRunnableBinding(llm) && _isChatModelWithBindTools(llm.bound)) { + const newBound = llm.bound.bindTools(toolClasses, options); + if (RunnableBinding.isRunnableBinding(newBound)) return new RunnableBinding({ + bound: newBound.bound, + config: { + ...llm.config, + ...newBound.config + }, + kwargs: { + ...llm.kwargs, + ...newBound.kwargs + }, + configFactories: newBound.configFactories ?? llm.configFactories + }); + return new RunnableBinding({ + bound: newBound, + config: llm.config, + kwargs: llm.kwargs, + configFactories: llm.configFactories + }); + } + return null; +}; +/** +* Check if the LLM already has bound tools and throw if it does. +* +* @param llm - The LLM to check. +* @returns void +*/ +function validateLLMHasNoBoundTools(llm) { + /** + * If llm is a function, we can't validate until runtime, so skip + */ + if (typeof llm === "function") return; + let model = llm; + /** + * If model is a RunnableSequence, find a RunnableBinding in its steps + */ + if (RunnableSequence.isRunnableSequence(model)) model = model.steps.find((step) => RunnableBinding.isRunnableBinding(step)) || model; + /** + * If model is configurable, get the underlying model + */ + if (isConfigurableModel(model)) + /** + * Can't validate async model retrieval in constructor + */ + return; + /** + * Check if model is a RunnableBinding with bound tools + */ + if (RunnableBinding.isRunnableBinding(model)) { + const hasToolsInKwargs = model.kwargs != null && typeof model.kwargs === "object" && "tools" in model.kwargs && Array.isArray(model.kwargs.tools) && model.kwargs.tools.length > 0; + const hasToolsInConfig = model.config != null && typeof model.config === "object" && "tools" in model.config && Array.isArray(model.config.tools) && model.config.tools.length > 0; + if (hasToolsInKwargs || hasToolsInConfig) throw new MultipleToolsBoundError(); + } + /** + * Also check if model has tools property directly (e.g., FakeToolCallingModel) + */ + if ("tools" in model && model.tools !== void 0 && Array.isArray(model.tools) && model.tools.length > 0) throw new MultipleToolsBoundError(); +} +/** +* Check if the last message in the messages array has tool calls. +* +* @param messages - The messages to check. +* @returns True if the last message has tool calls, false otherwise. +*/ +function hasToolCalls(message) { + return Boolean(AIMessage.isInstance(message) && message.tool_calls && message.tool_calls.length > 0); +} +/** +* Normalizes a system prompt to a SystemMessage object. +* If it's already a SystemMessage, returns it as-is. +* If it's a string, converts it to a SystemMessage. +* If it's undefined, creates an empty system message so it is easier to append to it later. +*/ +function normalizeSystemPrompt$1(systemPrompt) { + if (systemPrompt == null) return new SystemMessage(""); + if (SystemMessage.isInstance(systemPrompt)) return systemPrompt; + if (typeof systemPrompt === "string") return new SystemMessage({ content: [{ + type: "text", + text: systemPrompt + }] }); + throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`); +} +/** +* Helper function to bind tools to a language model. +* @param llm - The language model to bind tools to. +* @param toolClasses - The tools to bind to the language model. +* @param options - The options to pass to the language model. +* @returns The language model with the tools bound to it. +*/ +async function bindTools(llm, toolClasses, options = {}) { + const model = _simpleBindTools(llm, toolClasses, options); + if (model) return model; + if (isConfigurableModel(llm)) { + const model = _simpleBindTools(await llm._getModelInstance(), toolClasses, options); + if (model) return model; + } + if (RunnableSequence.isRunnableSequence(llm)) { + const modelStep = llm.steps.findIndex((step) => RunnableBinding.isRunnableBinding(step) || isBaseChatModel(step) || isConfigurableModel(step)); + if (modelStep >= 0) { + const model = _simpleBindTools(llm.steps[modelStep], toolClasses, options); + if (model) { + const nextSteps = llm.steps.slice(); + nextSteps.splice(modelStep, 1, model); + return RunnableSequence.from(nextSteps); + } + } + } + throw new Error(`llm ${llm} must define bindTools method.`); +} +/** +* Compose multiple wrapToolCall handlers into a single middleware stack. +* +* Composes handlers so the first in the list becomes the outermost layer. +* Each handler receives a handler callback to execute inner layers. +* +* @param handlers - List of handlers. First handler wraps all others. +* @returns Composed handler, or undefined if handlers array is empty. +* +* @example +* ```typescript +* // handlers=[auth, retry] means: auth wraps retry +* // Flow: auth calls retry, retry calls base handler +* const auth: ToolCallWrapper = async (request, handler) => { +* try { +* return await handler(request); +* } catch (error) { +* if (error.message === "Unauthorized") { +* await refreshToken(); +* return await handler(request); +* } +* throw error; +* } +* }; +* +* const retry: ToolCallWrapper = async (request, handler) => { +* for (let attempt = 0; attempt < 3; attempt++) { +* try { +* return await handler(request); +* } catch (error) { +* if (attempt === 2) throw error; +* } +* } +* throw new Error("Unreachable"); +* }; +* +* const composedHandler = chainToolCallHandlers([auth, retry]); +* ``` +*/ +function chainToolCallHandlers(handlers) { + if (handlers.length === 0) return; + if (handlers.length === 1) return handlers[0]; + function composeTwo(outer, inner) { + return async (request, handler) => { + const innerHandler = async (passedRequest) => { + return inner(passedRequest, handler); + }; + return outer(request, innerHandler); + }; + } + let result = handlers[handlers.length - 1]; + for (let i = handlers.length - 2; i >= 0; i--) result = composeTwo(handlers[i], result); + return result; +} +/** +* Wrapping `wrapToolCall` invocation so we can inject middleware name into +* the error message. +* +* @param middleware list of middleware passed to the agent +* @param state state of the agent +* @returns single wrap function +*/ +function wrapToolCall(middleware) { + const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall); + if (middlewareWithWrapToolCall.length === 0) return; + return chainToolCallHandlers(middlewareWithWrapToolCall.map((m) => { + const originalHandler = m.wrapToolCall; + /** + * Wrap with error handling and validation + */ + const wrappedHandler = async (request, handler) => { + /** + * Capture the original state for this middleware's schema parsing. + * This is important because the request may be modified (via override) + * as it passes through the middleware chain, but each middleware + * should always see the full original state for its schema parsing. + */ + const originalState = request.state; + /** + * Create a handler that preserves state parsing for this middleware + * while allowing tool/toolCall/state modifications from inner middleware + */ + const downstreamErrors = /* @__PURE__ */ new Set(); + const wrappedInnerHandler = async (passedRequest) => { + /** + * Merge the passed request with the original state for parsing. + * This ensures middleware can override tool/toolCall while + * maintaining proper state parsing for each middleware in the chain. + */ + const mergedState = { + ...originalState, + ...passedRequest.state + }; + try { + return await handler({ + ...passedRequest, + state: mergedState + }); + } catch (error) { + downstreamErrors.add(error); + throw error; + } + }; + try { + const result = await originalHandler({ + ...request, + /** + * override state with the state from the specific middleware + */ + state: { + messages: originalState.messages, + ...m.stateSchema ? parseMiddlewareState(m.stateSchema, { ...originalState }) : {} + } + }, wrappedInnerHandler); + /** + * Validate return type + */ + if (!ToolMessage.isInstance(result) && !isCommand(result)) throw new Error(`Invalid response from "wrapToolCall" in middleware "${m.name}": expected ToolMessage or Command, got ${typeof result}`); + return result; + } catch (error) { + if (downstreamErrors.has(error)) throw error; + throw MiddlewareError.wrap(error, m.name); + } + }; + return wrappedHandler; + })); +} +/** +* Static LangGraph config keys propagated from ReactAgent defaults onto the +* compiled inner graph. This ensures values set via `withConfig()` survive +* LangGraph API loading, which unwraps ReactAgent to `.graph` before execution. +*/ +var GRAPH_DEFAULT_CONFIG_KEYS = [ + "tags", + "metadata", + "runName", + "maxConcurrency", + "recursionLimit", + "configurable" +]; +function toGraphDefaultConfig(config) { + const result = {}; + for (const key of GRAPH_DEFAULT_CONFIG_KEYS) { + const value = config[key]; + if (value !== void 0) result[key] = value; + } + return result; +} +//#endregion +//#region node_modules/langchain/dist/agents/nodes/utils.js +/** +* Helper function to initialize middleware state defaults. +* This is used to ensure all middleware state properties are initialized. +* +* Private properties (starting with _) are automatically made optional since +* users cannot provide them when invoking the agent. +*/ +async function initializeMiddlewareStates(middlewareList, state) { + const middlewareStates = {}; + for (const middleware of middlewareList) { + /** + * skip middleware if it doesn't have a state schema + */ + if (!middleware.stateSchema) continue; + let zodSchema; + if (StateSchema.isInstance(middleware.stateSchema)) { + const zodShape = {}; + for (const [key, field] of Object.entries(middleware.stateSchema.fields)) if (ReducedValue.isInstance(field)) zodShape[key] = field.inputSchema || field.valueSchema; + else zodShape[key] = field; + zodSchema = object(zodShape); + } else if (isInteropZodObject(middleware.stateSchema)) zodSchema = middleware.stateSchema; + else continue; + const parseResult = await interopSafeParseAsync(interopZodObjectMakeFieldsOptional(zodSchema, (key) => key.startsWith("_")), state); + if (parseResult.success) { + Object.assign(middlewareStates, parseResult.data); + continue; + } + /** + * If safeParse fails, there are required public fields missing. + * Note: Zod v3 uses message "Required", Zod v4 uses "Invalid input: expected X, received undefined" + */ + const requiredFields = parseResult.error.issues.filter((issue) => issue.code === "invalid_type").map((issue) => ` - ${issue.path.join(".")}: Required`).join("\n"); + throw new Error(`Middleware "${middleware.name}" has required state fields that must be initialized:\n${requiredFields}\n\nTo fix this, either:\n1. Provide default values in your middleware's state schema using .default():\n stateSchema: z.object({\n myField: z.string().default("default value")\n })\n\n2. Or make the fields optional using .optional():\n stateSchema: z.object({\n myField: z.string().optional()\n })\n\n3. Or ensure you pass these values when invoking the agent:\n agent.invoke({\n messages: [...],\n ${parseResult.error.issues[0]?.path.join(".")}: "value"\n })`); + } + return middlewareStates; +} +/** +* Users can define private and public state for a middleware. Private state properties start with an underscore. +* This function will return the private state properties from the state schema, making all of them optional. +* @param stateSchema - The middleware state schema +* @returns A new schema containing only the private properties (underscore-prefixed), all made optional +*/ +function derivePrivateState(stateSchema) { + const builtInStateSchema = { + messages: custom(() => []), + structuredResponse: any().optional() + }; + if (!stateSchema) return object(builtInStateSchema); + let shape; + if (StateSchema.isInstance(stateSchema)) { + shape = {}; + for (const [key, field] of Object.entries(stateSchema.fields)) if (ReducedValue.isInstance(field)) shape[key] = field.inputSchema || field.valueSchema; + else shape[key] = field; + } else if (isInteropZodObject(stateSchema)) shape = getInteropZodObjectShape(stateSchema); + else return object(builtInStateSchema); + const privateShape = { ...builtInStateSchema }; + for (const [key, value] of Object.entries(shape)) if (key.startsWith("_")) privateShape[key] = value.optional(); + else privateShape[key] = value; + return object(privateShape); +} +/** +* Converts any supported schema type (ZodObject, StateSchema, AnnotationRoot) to a partial Zod object. +* This is useful for parsing state loosely where all fields are optional. +* +* @param schema - The schema to convert (InteropZodObject, StateSchema, or AnnotationRoot) +* @returns A partial Zod object schema where all fields are optional +*/ +function toPartialZodObject(schema) { + if (isInteropZodObject(schema)) return interopZodObjectPartial(schema); + if (StateSchema.isInstance(schema)) { + const partialShape = {}; + for (const [key, field] of Object.entries(schema.fields)) { + let fieldSchema; + if (ReducedValue.isInstance(field)) fieldSchema = field.inputSchema || field.valueSchema; + else fieldSchema = field; + partialShape[key] = isZodSchemaV4(fieldSchema) ? fieldSchema.optional() : any().optional(); + } + return object(partialShape); + } + return object({}); +} +function parseJumpToTarget(target) { + if (!target) return; + /** + * if target is already a valid jump target, return it + */ + if ([ + "model_request", + "tools", + "__end__" + ].includes(target)) return target; + if (target === "model") return "model_request"; + if (target === "tools") return "tools"; + if (target === "end") return END; + throw new Error(`Invalid jump target: ${target}, must be "model", "tools" or "end".`); +} +/** +* `config` always contains a signal from LangGraphs Pregel class. +* To ensure we acknowledge the abort signal from the user, we merge it +* with the signal from the ToolNode. +* +* @param signals - The signals to merge. +* @returns The merged signal. +*/ +function mergeAbortSignals(...signals) { + return AbortSignal.any(signals.filter((maybeSignal) => maybeSignal !== null && maybeSignal !== void 0 && typeof maybeSignal === "object" && "aborted" in maybeSignal && typeof maybeSignal.aborted === "boolean")); +} +//#endregion +//#region node_modules/langchain/dist/agents/RunnableCallable.js +var RunnableCallable = class extends Runnable { + lc_namespace = ["langgraph"]; + func; + tags; + config; + trace = true; + recurse = true; + #state; + constructor(fields) { + super(); + this.name = fields.name ?? fields.func.name; + this.func = fields.func; + this.config = fields.tags ? { tags: fields.tags } : void 0; + this.recurse = fields.recurse ?? this.recurse; + } + getState() { + return this.#state; + } + /** + * This allows us to set the state of the runnable, e.g. for model and middleware nodes. + * @internal + */ + setState(state) { + this.#state = { + ...this.#state, + ...state + }; + } + async invoke(input, options) { + const mergedConfig = mergeConfigs(this.config, options); + const returnValue = await AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); + if (Runnable.isRunnable(returnValue) && this.recurse) return await AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); + this.#state = returnValue; + return returnValue; + } +}; +//#endregion +//#region node_modules/langchain/dist/agents/withAgentName.js +/** +* Attach formatted agent names to the messages passed to and from a language model. +* +* This is useful for making a message history with multiple agents more coherent. +* +* NOTE: agent name is consumed from the message.name field. +* If you're using an agent built with createAgent, name is automatically set. +* If you're building a custom agent, make sure to set the name on the AI message returned by the LLM. +* +* @param model - Language model to add agent name formatting to +* @param agentNameMode - How to expose the agent name to the LLM +* - "inline": Add the agent name directly into the content field of the AI message using XML-style tags. +* Example: "How can I help you" -> "agent_nameHow can I help you?". +*/ +function withAgentName(model, agentNameMode) { + let processInputMessage; + let processOutputMessage; + if (agentNameMode === "inline") { + processInputMessage = _addInlineAgentName; + processOutputMessage = _removeInlineAgentName; + } else throw new Error(`Invalid agent name mode: ${agentNameMode}. Needs to be one of: "inline"`); + function processInputMessages(messages) { + return messages.map(processInputMessage); + } + return RunnableSequence.from([ + RunnableLambda.from(processInputMessages), + model, + RunnableLambda.from(processOutputMessage) + ]); +} +//#endregion +//#region node_modules/langchain/dist/agents/nodes/AgentNode.js +/** +* Check if the response is an internal model response. +* @param response - The response to check. +* @returns True if the response is an internal model response, false otherwise. +*/ +function isInternalModelResponse(response) { + return AIMessage.isInstance(response) || isCommand(response) || typeof response === "object" && response !== null && "structuredResponse" in response && "messages" in response; +} +/** +* The name of the agent node in the state graph. +*/ +var AGENT_NODE_NAME = "model_request"; +var AgentNode = class extends RunnableCallable { + #options; + #systemMessage; + constructor(options) { + super({ + name: options.name ?? "model", + func: (input, config) => this.#run(input, config) + }); + this.#options = options; + this.#systemMessage = options.systemMessage; + } + /** + * Returns response format primtivies based on given model and response format provided by the user. + * + * If the user selects a tool output: + * - return a record of tools to extract structured output from the model's response + * + * if the user selects a native schema output or if the model supports JSON schema output: + * - return a provider strategy to extract structured output from the model's response + * + * @param model - The model to get the response format for. + * @returns The response format. + */ + async #getResponseFormat(model, responseFormat = this.#options.responseFormat) { + if (!responseFormat) return; + let resolvedModel; + if (isConfigurableModel(model)) resolvedModel = await model._getModelInstance(); + else if (typeof model !== "string") resolvedModel = model; + const strategies = transformResponseFormat(responseFormat, void 0, resolvedModel); + if (strategies.length === 0) return; + /** + * Populate a list of structured tool info. + */ + if (!strategies.every((format) => format instanceof ProviderStrategy)) return { + type: "tool", + tools: strategies.filter((format) => format instanceof ToolStrategy).reduce((acc, format) => { + acc[format.name] = format; + return acc; + }, {}) + }; + return { + type: "native", + /** + * there can only be one provider strategy + */ + strategy: strategies[0] + }; + } + async #run(state, config) { + /** + * Check if we just executed a returnDirect tool + * If so, we should generate structured response (if needed) and stop + */ + const lastMessage = state.messages.at(-1); + if (lastMessage && ToolMessage.isInstance(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name)) return [new Command({ update: { messages: [] } })]; + const { response, lastAiMessage, collectedCommands } = await this.#invokeModel(state, config); + /** + * structuredResponse — return as a plain state update dict (not a Command) + * because the structuredResponse channel uses UntrackedValue(guard=true) + * which only allows a single write per step. + */ + if (typeof response === "object" && response !== null && "structuredResponse" in response && "messages" in response) { + const { structuredResponse, messages } = response; + return { + messages: [...state.messages, ...messages], + structuredResponse + }; + } + const commands = []; + const aiMessage = AIMessage.isInstance(response) ? response : lastAiMessage; + if (aiMessage) { + aiMessage.name = this.name; + aiMessage.lc_kwargs.name = this.name; + if (this.#areMoreStepsNeeded(state, aiMessage)) commands.push(new Command({ update: { messages: [new AIMessage({ + content: "Sorry, need more steps to process this request.", + name: this.name, + id: aiMessage.id + })] } })); + else commands.push(new Command({ update: { messages: [aiMessage] } })); + } + if (isCommand(response) && !collectedCommands.includes(response)) commands.push(response); + commands.push(...collectedCommands); + return commands; + } + /** + * Derive the model from the options. + * @param state - The state of the agent. + * @param config - The config of the agent. + * @returns The model. + */ + #deriveModel() { + if (typeof this.#options.model === "string") return initChatModel(this.#options.model); + if (this.#options.model) return this.#options.model; + throw new Error("No model option was provided, either via `model` option."); + } + async #invokeModel(state, config, options = {}) { + const model = await this.#deriveModel(); + const lgConfig = config; + /** + * Create a local variable for current system message to avoid concurrency issues + * Each invocation gets its own copy + */ + let currentSystemMessage = this.#systemMessage; + /** + * Shared tracking state for AIMessage and Command collection. + * lastAiMessage tracks the effective AIMessage through the middleware chain. + * collectedCommands accumulates Commands returned by middleware (not base handler). + */ + let lastAiMessage = null; + const collectedCommands = []; + /** + * Create the base handler that performs the actual model invocation + */ + const baseHandler = async (request) => { + /** + * Check if the LLM already has bound tools and throw if it does. + */ + validateLLMHasNoBoundTools(request.model); + const structuredResponseFormat = await this.#getResponseFormat(request.model, request.responseFormat); + const modelWithTools = await this.#bindTools(request.model, request, structuredResponseFormat); + /** + * prepend the system message to the messages if it is not empty + */ + const messages = [...currentSystemMessage.text === "" ? [] : [currentSystemMessage], ...request.messages]; + const signal = mergeAbortSignals(this.#options.signal, config.signal); + const response = await raceWithSignal(modelWithTools.invoke(messages, { + ...config, + signal + }), signal); + lastAiMessage = response; + /** + * if the user requests a native schema output, try to parse the response + * and return the structured response if it is valid + */ + if (structuredResponseFormat?.type === "native") { + const structuredResponse = structuredResponseFormat.strategy.parse(response); + if (structuredResponse) return { + structuredResponse, + messages: [response] + }; + /** + * If the model produced a terminal response (no tool calls) but the + * output failed to satisfy the provider strategy's schema, throw an + * informative error instead of silently exiting with + * `structuredResponse: undefined`. If tool calls are present, the + * agent loop continues and a subsequent terminal step will get + * another chance to produce a valid structured response. + */ + if (!response.tool_calls || response.tool_calls.length === 0) throw new StructuredOutputParsingError(typeof structuredResponseFormat.strategy.schema?.title === "string" ? structuredResponseFormat.strategy.schema.title : "providerStrategy", ["Model output did not satisfy the provided response schema."]); + return response; + } + if (!structuredResponseFormat || !response.tool_calls) return response; + const toolCalls = response.tool_calls.filter((call) => call.name in structuredResponseFormat.tools); + /** + * if there were not structured tool calls, we can return the response + */ + if (toolCalls.length === 0) return response; + /** + * if there were multiple structured tool calls, we should throw an error as this + * scenario is not defined/supported. + */ + if (toolCalls.length > 1) return this.#handleMultipleStructuredOutputs(response, toolCalls, structuredResponseFormat); + const toolMessageContent = structuredResponseFormat.tools[toolCalls[0].name]?.options?.toolMessageContent; + return this.#handleSingleStructuredOutput(response, toolCalls[0], structuredResponseFormat, toolMessageContent ?? options.lastMessage); + }; + const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? []; + let wrappedHandler = baseHandler; + /** + * Build composed handler from last to first so first middleware becomes outermost + */ + for (let i = wrapperMiddleware.length - 1; i >= 0; i--) { + const middlewareEntry = wrapperMiddleware[i]; + const middleware = Array.isArray(middlewareEntry) ? middlewareEntry[0] : middlewareEntry; + if (middleware.wrapModelCall) { + const innerHandler = wrappedHandler; + const currentMiddleware = middleware; + wrappedHandler = async (request) => { + const baselineSystemMessage = currentSystemMessage; + /** + * Merge context with default context of middleware + */ + const context = currentMiddleware.contextSchema ? interopParse(currentMiddleware.contextSchema, lgConfig?.context || {}) : lgConfig?.context; + /** + * Create runtime + */ + const runtime = Object.freeze({ + context, + store: lgConfig.store, + configurable: lgConfig.configurable, + writer: lgConfig.writer, + interrupt: lgConfig.interrupt, + signal: lgConfig.signal + }); + /** + * Create the request with state and runtime + */ + const requestWithStateAndRuntime = { + ...request, + state: { + ...middleware.stateSchema ? interopParse(toPartialZodObject(middleware.stateSchema), state) : {}, + messages: state.messages + }, + runtime + }; + /** + * Create handler that validates tools and calls the inner handler + */ + const handlerWithValidation = async (req) => { + currentSystemMessage = baselineSystemMessage; + /** + * Validate tool modifications in wrapModelCall. + * + * Classify each client tool as either: + * - "added": a genuinely new tool name not in the static toolClasses + * - "replaced": same name as a registered tool but different instance + * + * Added tools are allowed when a wrapToolCall middleware exists to + * handle their execution. Replaced tools are always rejected to + * preserve ToolNode execution identity. + */ + const modifiedTools = req.tools ?? []; + const registeredToolsByName = new Map(this.#options.toolClasses.filter(isClientTool).map((t) => [t.name, t])); + const addedClientTools = modifiedTools.filter((tool) => isClientTool(tool) && !registeredToolsByName.has(tool.name)); + const replacedClientTools = modifiedTools.filter((tool) => { + if (!isClientTool(tool)) return false; + const original = registeredToolsByName.get(tool.name); + return original != null && original !== tool; + }); + if (addedClientTools.length > 0) { + if (!this.#options.middleware?.some((m) => m.wrapToolCall != null)) throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${currentMiddleware.name}": ${addedClientTools.map((tool) => tool.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`); + } + if (replacedClientTools.length > 0) throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${currentMiddleware.name}": ${replacedClientTools.map((tool) => tool.name).join(", ")}. This is not supported.`); + let normalizedReq = req; + const hasSystemPromptChanged = req.systemPrompt !== currentSystemMessage.text; + const hasSystemMessageChanged = req.systemMessage !== currentSystemMessage; + if (hasSystemPromptChanged && hasSystemMessageChanged) throw new Error("Cannot change both systemPrompt and systemMessage in the same request."); + /** + * Check if systemPrompt is a string was changed, if so create a new SystemMessage + */ + if (hasSystemPromptChanged) { + currentSystemMessage = new SystemMessage({ content: [{ + type: "text", + text: req.systemPrompt + }] }); + normalizedReq = { + ...req, + systemPrompt: currentSystemMessage.text, + systemMessage: currentSystemMessage + }; + } + /** + * If the systemMessage was changed, update the current system message + */ + if (hasSystemMessageChanged) { + currentSystemMessage = new SystemMessage({ ...req.systemMessage }); + normalizedReq = { + ...req, + systemPrompt: currentSystemMessage.text, + systemMessage: currentSystemMessage + }; + } + const innerHandlerResult = await innerHandler(normalizedReq); + /** + * Normalize Commands so middleware always sees AIMessage from handler(). + * When an inner handler (base handler or nested middleware) returns a + * Command (e.g. structured-output retry), substitute the tracked + * lastAiMessage so the middleware sees an AIMessage, and collect the + * raw Command so the framework can still propagate it (e.g. for retries). + * + * Only collect if not already present: Commands from inner middleware + * are already tracked via the middleware validation layer (line ~627). + */ + if (isCommand(innerHandlerResult) && lastAiMessage) { + if (!collectedCommands.includes(innerHandlerResult)) collectedCommands.push(innerHandlerResult); + return lastAiMessage; + } + return innerHandlerResult; + }; + if (!currentMiddleware.wrapModelCall) return handlerWithValidation(requestWithStateAndRuntime); + try { + const middlewareResponse = await currentMiddleware.wrapModelCall(requestWithStateAndRuntime, handlerWithValidation); + /** + * Validate that this specific middleware returned a valid response + */ + if (!isInternalModelResponse(middlewareResponse)) throw new Error(`Invalid response from "wrapModelCall" in middleware "${currentMiddleware.name}": expected AIMessage or Command, got ${typeof middlewareResponse}`); + if (AIMessage.isInstance(middlewareResponse)) lastAiMessage = middlewareResponse; + else if (isCommand(middlewareResponse)) collectedCommands.push(middlewareResponse); + return middlewareResponse; + } catch (error) { + throw MiddlewareError.wrap(error, currentMiddleware.name); + } + }; + } + } + /** + * Execute the wrapped handler with the initial request + * Reset current system prompt to initial state and convert to string using .text getter + * for backwards compatibility with ModelRequest + */ + currentSystemMessage = this.#systemMessage; + const initialRequest = { + model, + responseFormat: this.#options.responseFormat, + systemPrompt: currentSystemMessage?.text, + systemMessage: currentSystemMessage, + messages: state.messages, + tools: this.#options.toolClasses, + state, + runtime: Object.freeze({ + context: lgConfig?.context, + store: lgConfig.store, + configurable: lgConfig.configurable, + writer: lgConfig.writer, + interrupt: lgConfig.interrupt, + signal: lgConfig.signal + }) + }; + return { + response: await wrappedHandler(initialRequest), + lastAiMessage, + collectedCommands + }; + } + /** + * If the model returns multiple structured outputs, we need to handle it. + * @param response - The response from the model + * @param toolCalls - The tool calls that were made + * @returns The response from the model + */ + #handleMultipleStructuredOutputs(response, toolCalls, responseFormat) { + const multipleStructuredOutputsError = new MultipleStructuredOutputsError(toolCalls.map((call) => call.name)); + return this.#handleToolStrategyError(multipleStructuredOutputsError, response, toolCalls[0], responseFormat); + } + /** + * If the model returns a single structured output, we need to handle it. + * @param toolCall - The tool call that was made + * @returns The structured response and a message to the LLM if needed + */ + #handleSingleStructuredOutput(response, toolCall, responseFormat, lastMessage) { + const tool = responseFormat.tools[toolCall.name]; + try { + const structuredResponse = tool.parse(toolCall.args); + return { + structuredResponse, + messages: [ + response, + new ToolMessage({ + tool_call_id: toolCall.id ?? "", + content: JSON.stringify(structuredResponse), + name: toolCall.name + }), + new AIMessage(lastMessage ?? `Returning structured response: ${JSON.stringify(structuredResponse)}`) + ] + }; + } catch (error) { + return this.#handleToolStrategyError(error, response, toolCall, responseFormat); + } + } + async #handleToolStrategyError(error, response, toolCall, responseFormat) { + /** + * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here. + * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user + * uses `toolStrategy` to define the response format. If the user applies a list of json + * schema objects, these will be transformed into multiple `ToolStrategy` entries but all + * with the same `handleError` option. + */ + const errorHandler = Object.values(responseFormat.tools).at(0)?.options?.handleError; + const toolCallId = toolCall.id; + if (!toolCallId) throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID."); + /** + * Default behavior: retry if `errorHandler` is undefined or truthy. + * Only throw if explicitly set to `false`. + */ + if (errorHandler === false) throw error; + /** + * retry if: + */ + if (errorHandler === void 0 || typeof errorHandler === "boolean" && errorHandler || Array.isArray(errorHandler) && errorHandler.some((h) => h instanceof MultipleStructuredOutputsError)) return new Command({ + update: { messages: [response, new ToolMessage({ + content: error.message, + tool_call_id: toolCallId + })] }, + goto: AGENT_NODE_NAME + }); + /** + * if `errorHandler` is a string, retry the tool call with given string + */ + if (typeof errorHandler === "string") return new Command({ + update: { messages: [response, new ToolMessage({ + content: errorHandler, + tool_call_id: toolCallId + })] }, + goto: AGENT_NODE_NAME + }); + /** + * if `errorHandler` is a function, retry the tool call with the function + */ + if (typeof errorHandler === "function") { + const content = await errorHandler(error); + if (typeof content !== "string") throw new Error("Error handler must return a string."); + return new Command({ + update: { messages: [response, new ToolMessage({ + content, + tool_call_id: toolCallId + })] }, + goto: AGENT_NODE_NAME + }); + } + /** + * Default: retry if we reach here + */ + return new Command({ + update: { messages: [response, new ToolMessage({ + content: error.message, + tool_call_id: toolCallId + })] }, + goto: AGENT_NODE_NAME + }); + } + #areMoreStepsNeeded(state, response) { + const allToolsReturnDirect = AIMessage.isInstance(response) && response.tool_calls?.every((call) => this.#options.shouldReturnDirect.has(call.name)); + const remainingSteps = "remainingSteps" in state ? state.remainingSteps : void 0; + return Boolean(remainingSteps && (remainingSteps < 1 && allToolsReturnDirect || remainingSteps < 2 && hasToolCalls(state.messages.at(-1)))); + } + async #bindTools(model, preparedOptions, structuredResponseFormat) { + const options = {}; + const structuredTools = Object.values(structuredResponseFormat && "tools" in structuredResponseFormat ? structuredResponseFormat.tools : {}); + /** + * Use tools from preparedOptions if provided, otherwise use default tools + */ + const allTools = [...preparedOptions?.tools ?? this.#options.toolClasses, ...structuredTools.map((toolStrategy) => toolStrategy.tool)]; + /** + * If there are structured tools, we need to set the tool choice to "any" + * so that the model can choose to use a structured tool or not. + */ + const toolChoice = preparedOptions?.toolChoice || (structuredTools.length > 0 ? "any" : void 0); + /** + * check if the user requests a native schema output + */ + if (structuredResponseFormat?.type === "native") { + const resolvedStrict = preparedOptions?.modelSettings?.strict ?? structuredResponseFormat?.strategy?.strict ?? true; + const jsonSchemaParams = { + name: structuredResponseFormat.strategy.schema?.name ?? "extract", + description: getSchemaDescription(structuredResponseFormat.strategy.schema), + schema: structuredResponseFormat.strategy.schema, + strict: resolvedStrict + }; + Object.assign(options, { + /** + * OpenAI-style options + * Used by ChatOpenAI, ChatXAI, and other OpenAI-compatible providers. + */ + response_format: { + type: "json_schema", + json_schema: jsonSchemaParams + }, + /** + * Anthropic-style options + */ + outputConfig: { format: { + type: "json_schema", + schema: structuredResponseFormat.strategy.schema + } }, + /** + * Google-style options + * Used by ChatGoogle and other Gemini-based providers. + */ + responseSchema: structuredResponseFormat.strategy.schema, + /** + * for LangSmith structured output tracing + */ + ls_structured_output_format: { + kwargs: { method: "json_schema" }, + schema: structuredResponseFormat.strategy.schema + }, + /** + * Don't force strict on tools: it makes Anthropic's combined grammar + * "too complex for compilation", and only OpenAI Chat Completions needs + * it (re-applied there). Honor an explicit override; else leave unset. + */ + strict: preparedOptions?.modelSettings?.strict + }); + } + /** + * Bind tools to the model if they are not already bound. + */ + const modelWithTools = await bindTools(model, allTools, { + ...options, + ...preparedOptions?.modelSettings, + tool_choice: toolChoice + }); + return this.#options.includeAgentName === "inline" ? withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools; + } + /** + * Returns internal bookkeeping state for StateManager, not graph output. + * The return shape differs from the node's output type (Command). + */ + getState() { + const state = super.getState(); + return { + messages: [], + ...state && !isCommand(state) ? state : {} + }; + } +}; +//#endregion +//#region node_modules/langchain/dist/agents/nodes/ToolNode.js +/** +* Error message template for when middleware adds tools that can't be executed. +* This happens when middleware modifies tools in wrapModelCall but doesn't provide +* a wrapToolCall handler to execute them. +*/ +var getInvalidToolError = (toolName, availableTools) => `Error: ${toolName} is not a valid tool, try one of [${availableTools.join(", ")}].`; +/** +* The name of the tool node in the state graph. +*/ +var TOOLS_NODE_NAME = "tools"; +var isBaseMessageArray = (input) => Array.isArray(input) && input.every(BaseMessage.isInstance); +var isMessagesState = (input) => typeof input === "object" && input != null && "messages" in input && isBaseMessageArray(input.messages); +var isSendInput = (input) => typeof input === "object" && input != null && "lg_tool_call" in input; +/** +* Default error handler for tool errors. +* +* This is applied to errors from baseHandler (tool execution). +* For errors from wrapToolCall middleware, those are handled separately +* and will bubble up by default. +* +* Catches all tool execution errors and converts them to ToolMessage. +* This allows the LLM to see the error and potentially retry with different arguments. +*/ +function defaultHandleToolErrors(error, toolCall) { + if (ToolInvocationError.isInstance(error)) return new ToolMessage({ + content: error.message, + tool_call_id: toolCall.id, + name: toolCall.name + }); + /** + * Catch all other tool errors and convert to ToolMessage + */ + return new ToolMessage({ + content: `${error}\n Please fix your mistakes.`, + tool_call_id: toolCall.id, + name: toolCall.name + }); +} +/** +* `ToolNode` is a built-in LangGraph component that handles tool calls within an agent's workflow. +* It works seamlessly with `createAgent`, offering advanced tool execution control, built +* in parallelism, and error handling. +* +* @example +* ```ts +* import { ToolNode, tool, AIMessage } from "langchain"; +* import { z } from "zod/v3"; +* +* const getWeather = tool((input) => { +* if (["sf", "san francisco"].includes(input.location.toLowerCase())) { +* return "It's 60 degrees and foggy."; +* } else { +* return "It's 90 degrees and sunny."; +* } +* }, { +* name: "get_weather", +* description: "Call to get the current weather.", +* schema: z.object({ +* location: z.string().describe("Location to get the weather for."), +* }), +* }); +* +* const tools = [getWeather]; +* const toolNode = new ToolNode(tools); +* +* const messageWithSingleToolCall = new AIMessage({ +* content: "", +* tool_calls: [ +* { +* name: "get_weather", +* args: { location: "sf" }, +* id: "tool_call_id", +* type: "tool_call", +* } +* ] +* }) +* +* await toolNode.invoke({ messages: [messageWithSingleToolCall] }); +* // Returns tool invocation responses as: +* // { messages: ToolMessage[] } +* ``` +*/ +var ToolNode = class extends RunnableCallable { + tools; + trace = false; + signal; + handleToolErrors = defaultHandleToolErrors; + wrapToolCall; + constructor(tools, options) { + const { name, tags, handleToolErrors, signal, wrapToolCall } = options ?? {}; + super({ + name, + tags, + func: (state, config) => this.run(state, config) + }); + this.options = options; + this.tools = tools; + this.handleToolErrors = handleToolErrors ?? this.handleToolErrors; + this.signal = signal; + this.wrapToolCall = wrapToolCall; + } + /** + * Handle errors from tool execution or middleware. + * @param error - The error to handle + * @param call - The tool call that caused the error + * @param isMiddlewareError - Whether the error came from wrapToolCall middleware + * @returns ToolMessage if error is handled, otherwise re-throws + */ + #handleError(error, call, isMiddlewareError) { + /** + * {@link NodeInterrupt} errors are a breakpoint to bring a human into the loop. + * As such, they are not recoverable by the agent and shouldn't be fed + * back. Instead, re-throw these errors even when `handleToolErrors = true`. + */ + if (isGraphInterrupt(error)) throw error; + /** + * If the signal is aborted, we want to bubble up the error to the invoke caller. + */ + if (this.signal?.aborted) throw error; + /** + * A recoverable tool error (e.g. tool-input schema validation) can be + * rewrapped as a {@link MiddlewareError} with the original error on `.cause` + * — once per `wrapToolCall` middleware, so it may be nested several layers + * deep. Walk the cause chain to the root; if it's a {@link ToolInvocationError}, + * unwrap it so the intended `handleToolErrors` self-correction path still + * applies. Genuine middleware errors stay fatal by default. + */ + let effectiveError = error; + let errorFromMiddleware = isMiddlewareError; + if (isMiddlewareError) { + let unwrapped = error; + while (MiddlewareError.isInstance(unwrapped)) unwrapped = unwrapped.cause; + if (ToolInvocationError.isInstance(unwrapped)) { + effectiveError = unwrapped; + errorFromMiddleware = false; + } + } + /** + * If error is from middleware and handleToolErrors is not true, bubble up + * (default handler and false both re-raise middleware errors) + */ + if (errorFromMiddleware && this.handleToolErrors !== true) throw effectiveError; + /** + * If handleToolErrors is false, throw all errors + */ + if (!this.handleToolErrors) throw effectiveError; + /** + * Apply handleToolErrors to the error + */ + if (typeof this.handleToolErrors === "function") { + const result = this.handleToolErrors(effectiveError, call); + if (result && ToolMessage.isInstance(result)) return result; + /** + * `handleToolErrors` returned undefined - re-raise + */ + throw effectiveError; + } else if (this.handleToolErrors) return new ToolMessage({ + name: call.name, + content: `${effectiveError}\n Please fix your mistakes.`, + tool_call_id: call.id + }); + /** + * Shouldn't reach here, but throw as fallback + */ + throw effectiveError; + } + async runTool(call, config, state) { + /** + * Build runtime from LangGraph config + */ + const lgConfig = config; + const runtime = { + context: lgConfig?.context, + store: lgConfig?.store, + configurable: lgConfig?.configurable, + writer: lgConfig?.writer, + interrupt: lgConfig?.interrupt, + signal: lgConfig?.signal + }; + /** + * Find the tool instance to include in the request. + * For dynamically registered tools, this may be undefined. + */ + const registeredTool = this.tools.find((t) => t.name === call.name); + /** + * Define the base handler that executes the tool. + * When wrapToolCall middleware is present, this handler does NOT catch errors + * so the middleware can handle them. + * When no middleware, errors are caught and handled here. + * + * The handler now accepts an overridden tool from the request, allowing + * middleware to provide tool implementations for dynamically registered tools. + */ + const baseHandler = async (request) => { + const { toolCall, tool: requestTool } = request; + /** + * Use the tool from the request (which may be overridden via spread syntax) + * or fall back to finding it in registered tools. + * This allows middleware to provide dynamic tool implementations. + */ + const tool = requestTool ?? this.tools.find((t) => t.name === toolCall.name); + if (tool === void 0) { + /** + * Tool not found - return a graceful error message rather than throwing. + * This allows the LLM to see the error and potentially retry. + */ + const availableTools = this.tools.map((t) => t.name); + return new ToolMessage({ + content: getInvalidToolError(toolCall.name, availableTools), + tool_call_id: toolCall.id, + name: toolCall.name, + status: "error" + }); + } + /** + * Cast tool to a common invokable type. + * The tool can be from registered tools (StructuredToolInterface | DynamicTool | RunnableToolLike) + * or from middleware override (ClientTool | ServerTool). + */ + const invokableTool = tool; + try { + const output = await invokableTool.invoke({ + ...toolCall, + type: "tool_call" + }, { + ...config, + /** + * extend to match ToolRuntime + */ + config, + toolCallId: toolCall.id, + state: config.configurable?.__pregel_scratchpad?.currentTaskInput, + signal: mergeAbortSignals(this.signal, config.signal) + }); + if (ToolMessage.isInstance(output) || isCommand(output)) return output; + return new ToolMessage({ + name: invokableTool.name, + content: typeof output === "string" ? output : JSON.stringify(output), + tool_call_id: toolCall.id + }); + } catch (e) { + /** + * Handle errors from tool execution (not from wrapToolCall) + * If tool invocation fails due to input parsing error, throw a {@link ToolInvocationError} + */ + if (e instanceof ToolInputParsingException) throw new ToolInvocationError(e, toolCall); + /** + * Re-throw to be handled by caller + */ + throw e; + } + }; + /** + * Create request object for middleware + * Cast to ToolCallRequest to satisfy type constraints + * of wrapToolCall which expects AgentBuiltInState + */ + const request = { + toolCall: call, + tool: registeredTool, + state, + runtime + }; + /** + * If wrapToolCall is provided, use it to wrap the tool execution + */ + if (this.wrapToolCall) try { + return await this.wrapToolCall(request, baseHandler); + } catch (e) { + /** + * Handle middleware errors + */ + return this.#handleError(e, call, true); + } + /** + * No wrapToolCall - if tool wasn't found, return graceful error + */ + if (!registeredTool) { + const availableTools = this.tools.map((t) => t.name); + return new ToolMessage({ + content: getInvalidToolError(call.name, availableTools), + tool_call_id: call.id, + name: call.name, + status: "error" + }); + } + /** + * No wrapToolCall - execute tool directly and handle errors here + */ + try { + return await baseHandler(request); + } catch (e) { + /** + * Handle tool errors when no middleware provided + */ + return this.#handleError(e, call, false); + } + } + async run(state, config) { + let outputs; + if (isSendInput(state)) { + const { lg_tool_call: _, jumpTo: __, ...newState } = state; + outputs = [await this.runTool(state.lg_tool_call, config, newState)]; + } else { + let messages; + if (isBaseMessageArray(state)) messages = state; + else if (isMessagesState(state)) messages = state.messages; + else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input."); + const toolMessageIds = new Set(messages.filter((msg) => msg.getType() === "tool").map((msg) => msg.tool_call_id)); + let aiMessage; + for (let i = messages.length - 1; i >= 0; i -= 1) { + const message = messages[i]; + if (AIMessage.isInstance(message)) { + aiMessage = message; + break; + } + } + if (!AIMessage.isInstance(aiMessage)) throw new Error("ToolNode only accepts AIMessages as input."); + outputs = await Promise.all(aiMessage.tool_calls?.filter((call) => call.id == null || !toolMessageIds.has(call.id)).map((call) => this.runTool(call, config, state)) ?? []); + } + if (!outputs.some(isCommand)) return Array.isArray(state) ? outputs : { messages: outputs }; + const combinedOutputs = []; + let parentCommand = null; + for (const output of outputs) if (isCommand(output)) if (output.graph === Command.PARENT && Array.isArray(output.goto) && output.goto.every((send) => isSend(send))) if (parentCommand) parentCommand.goto.push(...output.goto); + else parentCommand = new Command({ + graph: Command.PARENT, + goto: output.goto + }); + else combinedOutputs.push(output); + else combinedOutputs.push(Array.isArray(state) ? [output] : { messages: [output] }); + if (parentCommand) combinedOutputs.push(parentCommand); + return combinedOutputs; + } +}; +function isSend(x) { + return x instanceof Send; +} +//#endregion +//#region node_modules/langchain/dist/agents/nodes/middleware.js +/** +* Named class for context objects to provide better error messages +*/ +var AgentContext = class {}; +var AgentRuntime = class {}; +var MiddlewareNode = class extends RunnableCallable { + constructor(fields) { + super(fields); + } + async invokeMiddleware(invokeState, config) { + /** + * Filter context based on middleware's contextSchema + */ + let filteredContext = {}; + /** + * Parse context using middleware's contextSchema to apply defaults and validation + */ + if (this.middleware.contextSchema && isInteropZodObject(this.middleware.contextSchema)) { + /** + * Extract only the fields relevant to this middleware's schema + */ + const schemaShape = getInteropZodObjectShape(this.middleware.contextSchema); + if (schemaShape) { + const relevantContext = {}; + const invokeContext = config?.context || {}; + for (const key of Object.keys(schemaShape)) if (key in invokeContext) relevantContext[key] = invokeContext[key]; + /** + * Parse to apply defaults and validation, even if relevantContext is empty + * This will throw if required fields are missing and no defaults exist + */ + filteredContext = interopParse(this.middleware.contextSchema, relevantContext); + } + } + const state = { + ...invokeState, + /** + * don't overwrite possible outdated messages from other middleware nodes + */ + messages: invokeState.messages + }; + const runtime = { + context: filteredContext, + store: config?.store, + configurable: config?.configurable, + writer: config?.writer, + interrupt: config?.interrupt, + signal: config?.signal + }; + const result = await this.runHook( + state, + /** + * assign runtime and context values into empty named class + * instances to create a better error message. + */ + Object.freeze(Object.assign(new AgentRuntime(), { + ...runtime, + context: Object.freeze(Object.assign(new AgentContext(), filteredContext)) + })) + ); + /** + * If result is undefined, the hook made no state changes — return + * only the jumpTo sentinel so we don't re-emit every input key as + * a state update. + */ + if (!result) return { jumpTo: void 0 }; + /** + * Verify that the jump target is allowed for the middleware + */ + let jumpToConstraint; + let constraint; + if (this.name?.startsWith("BeforeAgentNode_")) { + jumpToConstraint = getHookConstraint(this.middleware.beforeAgent); + constraint = "beforeAgent.canJumpTo"; + } else if (this.name?.startsWith("BeforeModelNode_")) { + jumpToConstraint = getHookConstraint(this.middleware.beforeModel); + constraint = "beforeModel.canJumpTo"; + } else if (this.name?.startsWith("AfterAgentNode_")) { + jumpToConstraint = getHookConstraint(this.middleware.afterAgent); + constraint = "afterAgent.canJumpTo"; + } else if (this.name?.startsWith("AfterModelNode_")) { + jumpToConstraint = getHookConstraint(this.middleware.afterModel); + constraint = "afterModel.canJumpTo"; + } + if (typeof result.jumpTo === "string" && !jumpToConstraint?.includes(result.jumpTo)) { + const suggestion = jumpToConstraint && jumpToConstraint.length > 0 ? `must be one of: ${jumpToConstraint?.join(", ")}.` : constraint ? `no ${constraint} defined in middleware ${this.middleware.name}` : ""; + throw new Error(`Invalid jump target: ${result.jumpTo}, ${suggestion}.`); + } + /** + * If result is a control action, handle it + */ + if (typeof result === "object" && "type" in result) { + if (result.type === "terminate") { + if (result.error) throw result.error; + return { + ...state, + ...result.result || {}, + jumpTo: result.jumpTo + }; + } + throw new Error(`Invalid control action: ${JSON.stringify(result)}`); + } + /** + * If result is a state update, merge it with current state + */ + return { + ...state, + ...result, + jumpTo: result.jumpTo + }; + } + get nodeOptions() { + return { input: derivePrivateState(this.middleware.stateSchema) }; + } +}; +//#endregion +//#region node_modules/langchain/dist/agents/nodes/BeforeAgentNode.js +/** +* Node for executing a single middleware's beforeAgent hook. +*/ +var BeforeAgentNode = class extends MiddlewareNode { + lc_namespace = [ + "langchain", + "agents", + "beforeAgentNodes" + ]; + constructor(middleware) { + super({ + name: `BeforeAgentNode_${middleware.name}`, + func: async (state, config) => this.invokeMiddleware(state, config) + }); + this.middleware = middleware; + } + runHook(state, runtime) { + return getHookFunction(this.middleware.beforeAgent)(state, runtime); + } +}; +//#endregion +//#region node_modules/langchain/dist/agents/nodes/BeforeModelNode.js +/** +* Node for executing a single middleware's beforeModel hook. +*/ +var BeforeModelNode = class extends MiddlewareNode { + lc_namespace = [ + "langchain", + "agents", + "beforeModelNodes" + ]; + constructor(middleware) { + super({ + name: `BeforeModelNode_${middleware.name}`, + func: async (state, config) => this.invokeMiddleware(state, config) + }); + this.middleware = middleware; + } + runHook(state, runtime) { + return getHookFunction(this.middleware.beforeModel)(state, runtime); + } +}; +//#endregion +//#region node_modules/langchain/dist/agents/nodes/AfterModelNode.js +/** +* Node for executing a single middleware's afterModel hook. +*/ +var AfterModelNode = class extends MiddlewareNode { + lc_namespace = [ + "langchain", + "agents", + "afterModelNodes" + ]; + constructor(middleware) { + super({ + name: `AfterModelNode_${middleware.name}`, + func: async (state, config) => this.invokeMiddleware(state, config) + }); + this.middleware = middleware; + } + runHook(state, runtime) { + return getHookFunction(this.middleware.afterModel)(state, runtime); + } +}; +//#endregion +//#region node_modules/langchain/dist/agents/nodes/AfterAgentNode.js +/** +* Node for executing a single middleware's afterAgent hook. +*/ +var AfterAgentNode = class extends MiddlewareNode { + lc_namespace = [ + "langchain", + "agents", + "afterAgentNodes" + ]; + constructor(middleware) { + super({ + name: `AfterAgentNode_${middleware.name}`, + func: async (state, config) => this.invokeMiddleware(state, config) + }); + this.middleware = middleware; + } + runHook(state, runtime) { + return getHookFunction(this.middleware.afterAgent)(state, runtime); + } +}; +//#endregion +//#region node_modules/langchain/dist/agents/ReactAgent.js +/** +* ReactAgent is a production-ready ReAct (Reasoning + Acting) agent that combines +* language models with tools and middleware. +* +* The agent is parameterized by a single type bag `Types` that encapsulates all +* type information: +* +* @typeParam Types - An {@link AgentTypeConfig} that bundles: +* - `Response`: The structured response type +* - `State`: The custom state schema type +* - `Context`: The context schema type +* - `Middleware`: The middleware array type +* - `Tools`: The combined tools type from agent and middleware +* +* @example +* ```typescript +* // Using the type bag pattern +* type MyTypes = AgentTypeConfig< +* { name: string }, // Response +* typeof myState, // State +* typeof myContext, // Context +* typeof middleware, // Middleware +* typeof tools // Tools +* >; +* +* const agent: ReactAgent = createAgent({ ... }); +* ``` +*/ +var ReactAgent = class ReactAgent { + #graph; + #toolBehaviorVersion = "v2"; + #agentNode; + #defaultConfig; + constructor(options, defaultConfig) { + this.options = options; + this.#defaultConfig = mergeConfigs(defaultConfig ?? {}, { + metadata: { ls_integration: "langchain_create_agent" }, + configurable: { ls_agent_type: "root" } + }); + if (options.name) this.#defaultConfig = mergeConfigs(this.#defaultConfig, { metadata: { lc_agent_name: options.name } }); + this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion; + /** + * validate that model option is provided + */ + if (!options.model) throw new Error("`model` option is required to create an agent."); + /** + * Check if the LLM already has bound tools and throw if it does. + */ + if (typeof options.model !== "string") validateLLMHasNoBoundTools(options.model); + /** + * define complete list of tools based on options and middleware + */ + const middlewareTools = this.options.middleware?.filter((m) => m.tools).flatMap((m) => m.tools) ?? []; + const toolClasses = [...options.tools ?? [], ...middlewareTools]; + /** + * If any of the tools are configured to return_directly after running, + * our graph needs to check if these were called + */ + const shouldReturnDirect = new Set(toolClasses.filter(isClientTool).filter((tool) => "returnDirect" in tool && tool.returnDirect).map((tool) => tool.name)); + /** + * Create a schema that merges agent base schema with middleware state schemas + * Using Zod with withLangGraph ensures LangGraph Studio gets proper metadata + */ + const hasDynamicStructuredResponse = Boolean(this.options.middleware?.some((middleware) => middleware.wrapModelCall)); + const { state, input, output } = createAgentState(this.options.responseFormat !== void 0 || hasDynamicStructuredResponse, this.options.stateSchema, this.options.middleware); + const allNodeWorkflows = new StateGraph(state, { + input, + output, + context: this.options.contextSchema + }); + const beforeAgentNodes = []; + const beforeModelNodes = []; + const afterModelNodes = []; + const afterAgentNodes = []; + const wrapModelCallHookMiddleware = []; + this.#agentNode = new AgentNode({ + model: this.options.model, + systemMessage: normalizeSystemPrompt$1(this.options.systemPrompt), + includeAgentName: this.options.includeAgentName, + name: this.options.name, + responseFormat: this.options.responseFormat, + middleware: this.options.middleware, + toolClasses, + shouldReturnDirect, + signal: this.options.signal, + wrapModelCallHookMiddleware + }); + const middlewareNames = /* @__PURE__ */ new Set(); + const middleware = this.options.middleware ?? []; + for (let i = 0; i < middleware.length; i++) { + let beforeAgentNode; + let beforeModelNode; + let afterModelNode; + let afterAgentNode; + const m = middleware[i]; + if (middlewareNames.has(m.name)) throw new Error(`Middleware ${m.name} is defined multiple times`); + middlewareNames.add(m.name); + if (m.beforeAgent) { + beforeAgentNode = new BeforeAgentNode(m); + const name = `${m.name}.before_agent`; + beforeAgentNodes.push({ + index: i, + name, + allowed: getHookConstraint(m.beforeAgent) + }); + allNodeWorkflows.addNode(name, beforeAgentNode, beforeAgentNode.nodeOptions); + } + if (m.beforeModel) { + beforeModelNode = new BeforeModelNode(m); + const name = `${m.name}.before_model`; + beforeModelNodes.push({ + index: i, + name, + allowed: getHookConstraint(m.beforeModel) + }); + allNodeWorkflows.addNode(name, beforeModelNode, beforeModelNode.nodeOptions); + } + if (m.afterModel) { + afterModelNode = new AfterModelNode(m); + const name = `${m.name}.after_model`; + afterModelNodes.push({ + index: i, + name, + allowed: getHookConstraint(m.afterModel) + }); + allNodeWorkflows.addNode(name, afterModelNode, afterModelNode.nodeOptions); + } + if (m.afterAgent) { + afterAgentNode = new AfterAgentNode(m); + const name = `${m.name}.after_agent`; + afterAgentNodes.push({ + index: i, + name, + allowed: getHookConstraint(m.afterAgent) + }); + allNodeWorkflows.addNode(name, afterAgentNode, afterAgentNode.nodeOptions); + } + if (m.wrapModelCall) wrapModelCallHookMiddleware.push(m); + } + /** + * Add Nodes + */ + allNodeWorkflows.addNode(AGENT_NODE_NAME, this.#agentNode); + /** + * Check if any middleware has wrapToolCall defined. + * If so, we need to create a ToolNode even without pre-registered tools + * to allow middleware to handle dynamically registered tools. + */ + const hasWrapToolCallMiddleware = middleware.some((m) => m.wrapToolCall); + const clientTools = toolClasses.filter(isClientTool); + /** + * Create ToolNode if we have client-side tools OR if middleware defines wrapToolCall + * (which may handle dynamically registered tools) + */ + if (clientTools.length > 0 || hasWrapToolCallMiddleware) { + const toolNode = new ToolNode(clientTools, { + signal: this.options.signal, + wrapToolCall: wrapToolCall(middleware) + }); + allNodeWorkflows.addNode(TOOLS_NODE_NAME, toolNode); + } + /** + * Add Edges + */ + let entryNode; + if (beforeAgentNodes.length > 0) entryNode = beforeAgentNodes[0].name; + else if (beforeModelNodes.length > 0) entryNode = beforeModelNodes[0].name; + else entryNode = AGENT_NODE_NAME; + const loopEntryNode = beforeModelNodes.length > 0 ? beforeModelNodes[0].name : AGENT_NODE_NAME; + const exitNode = afterAgentNodes.length > 0 ? afterAgentNodes[afterAgentNodes.length - 1].name : END; + allNodeWorkflows.addEdge(START, entryNode); + /** + * Determine if we have tools available for routing. + * This includes both registered client tools AND dynamic tools via middleware. + */ + const hasToolsAvailable = clientTools.length > 0 || hasWrapToolCallMiddleware; + for (let i = 0; i < beforeAgentNodes.length; i++) { + const node = beforeAgentNodes[i]; + const current = node.name; + const nextDefault = i === beforeAgentNodes.length - 1 ? loopEntryNode : beforeAgentNodes[i + 1].name; + if (node.allowed && node.allowed.length > 0) { + const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + const destinations = Array.from(/* @__PURE__ */ new Set([nextDefault, ...allowedMapped.map((dest) => dest === "__end__" ? exitNode : dest)])); + allNodeWorkflows.addConditionalEdges(current, this.#createBeforeAgentRouter(clientTools, nextDefault, exitNode, hasToolsAvailable), destinations); + } else allNodeWorkflows.addEdge(current, nextDefault); + } + for (let i = 0; i < beforeModelNodes.length; i++) { + const node = beforeModelNodes[i]; + const current = node.name; + const nextDefault = i === beforeModelNodes.length - 1 ? AGENT_NODE_NAME : beforeModelNodes[i + 1].name; + if (node.allowed && node.allowed.length > 0) { + const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + const destinations = Array.from(/* @__PURE__ */ new Set([nextDefault, ...allowedMapped])); + allNodeWorkflows.addConditionalEdges(current, this.#createBeforeModelRouter(clientTools, nextDefault, hasToolsAvailable), destinations); + } else allNodeWorkflows.addEdge(current, nextDefault); + } + const lastAfterModelNode = afterModelNodes.at(-1); + if (afterModelNodes.length > 0 && lastAfterModelNode) allNodeWorkflows.addEdge(AGENT_NODE_NAME, lastAfterModelNode.name); + else { + const destinations = this.#getModelPaths(clientTools, false, hasToolsAvailable).map((p) => p === "__end__" ? exitNode : p); + if (destinations.length === 1) allNodeWorkflows.addEdge(AGENT_NODE_NAME, destinations[0]); + else allNodeWorkflows.addConditionalEdges(AGENT_NODE_NAME, this.#createModelRouter(exitNode), destinations); + } + for (let i = afterModelNodes.length - 1; i > 0; i--) { + const node = afterModelNodes[i]; + const current = node.name; + const nextDefault = afterModelNodes[i - 1].name; + if (node.allowed && node.allowed.length > 0) { + const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + const destinations = Array.from(/* @__PURE__ */ new Set([nextDefault, ...allowedMapped])); + allNodeWorkflows.addConditionalEdges(current, this.#createAfterModelSequenceRouter(clientTools, node.allowed, nextDefault, hasToolsAvailable), destinations); + } else allNodeWorkflows.addEdge(current, nextDefault); + } + if (afterModelNodes.length > 0) { + const firstAfterModel = afterModelNodes[0]; + const firstAfterModelNode = firstAfterModel.name; + const modelPaths = this.#getModelPaths(clientTools, true, hasToolsAvailable).filter((p) => p !== "tools" || hasToolsAvailable); + const allowJump = Boolean(firstAfterModel.allowed && firstAfterModel.allowed.length > 0); + const destinations = modelPaths.map((p) => p === "__end__" ? exitNode : p); + allNodeWorkflows.addConditionalEdges(firstAfterModelNode, this.#createAfterModelRouter(clientTools, allowJump, exitNode, hasToolsAvailable), destinations); + } + for (let i = afterAgentNodes.length - 1; i > 0; i--) { + const node = afterAgentNodes[i]; + const current = node.name; + const nextDefault = afterAgentNodes[i - 1].name; + if (node.allowed && node.allowed.length > 0) { + const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + const destinations = Array.from(/* @__PURE__ */ new Set([nextDefault, ...allowedMapped])); + allNodeWorkflows.addConditionalEdges(current, this.#createAfterModelSequenceRouter(clientTools, node.allowed, nextDefault, hasToolsAvailable), destinations); + } else allNodeWorkflows.addEdge(current, nextDefault); + } + if (afterAgentNodes.length > 0) { + const firstAfterAgent = afterAgentNodes[0]; + const firstAfterAgentNode = firstAfterAgent.name; + if (firstAfterAgent.allowed && firstAfterAgent.allowed.length > 0) { + const allowedMapped = firstAfterAgent.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + /** + * For after_agent, only use explicitly allowed destinations (don't add loopEntryNode) + * The default destination (when no jump occurs) should be END + */ + const destinations = Array.from(/* @__PURE__ */ new Set([END, ...allowedMapped])); + allNodeWorkflows.addConditionalEdges(firstAfterAgentNode, this.#createAfterModelSequenceRouter(clientTools, firstAfterAgent.allowed, END, hasToolsAvailable), destinations); + } else allNodeWorkflows.addEdge(firstAfterAgentNode, END); + } + /** + * add edges for tools node (includes both registered tools and dynamic tools via middleware) + */ + if (hasToolsAvailable) { + const toolReturnTarget = loopEntryNode; + if (shouldReturnDirect.size > 0) allNodeWorkflows.addConditionalEdges(TOOLS_NODE_NAME, this.#createToolsRouter(shouldReturnDirect, exitNode, toolReturnTarget), [toolReturnTarget, exitNode]); + else allNodeWorkflows.addEdge(TOOLS_NODE_NAME, toolReturnTarget); + } + /** + * compile the graph with native + user-defined stream transformers + */ + const middlewareStreamTransformers = (this.options.middleware ?? []).flatMap((m) => m.streamTransformers ?? []); + const compileTransformers = [ + createToolCallTransformer([]), + createSubagentTransformer([]), + ...middlewareStreamTransformers, + ...this.options.streamTransformers ?? [] + ]; + this.#graph = allNodeWorkflows.compile({ + checkpointer: this.options.checkpointer, + store: this.options.store, + name: this.options.name, + description: this.options.description, + transformers: compileTransformers + }); + /** + * LangGraph API resolves exported agents by unwrapping ReactAgent to the + * inner compiled graph (see langgraph-api load.utils `afterResolve`) and + * calls streamEvents on that pregel directly. That path only sees config + * baked into the graph via `.withConfig()`, not ReactAgent's #defaultConfig + * merged at invoke/stream time — so propagate static defaults here. + */ + const graphDefaultConfig = toGraphDefaultConfig(this.#defaultConfig); + if (Object.keys(graphDefaultConfig).length > 0) this.#graph = this.#graph.withConfig(graphDefaultConfig); + } + /** + * Get the compiled {@link https://docs.langchain.com/oss/javascript/langgraph/use-graph-api | StateGraph}. + */ + get graph() { + return this.#graph; + } + get checkpointer() { + return this.#graph.checkpointer; + } + set checkpointer(value) { + this.#graph.checkpointer = value; + } + get store() { + return this.#graph.store; + } + set store(value) { + this.#graph.store = value; + } + /** + * Creates a new ReactAgent with the given config merged into the existing config. + * Follows the same pattern as LangGraph's Pregel.withConfig(). + * + * The merged config is applied as a default that gets merged with any config + * passed at invocation time (invoke/stream). Invocation-time config takes precedence. + * + * @param config - Configuration to merge with existing config + * @returns A new ReactAgent instance with the merged configuration + * + * @example + * ```typescript + * const agent = createAgent({ model: "gpt-4o", tools: [...] }); + * + * // Set a default recursion limit + * const configuredAgent = agent.withConfig({ recursionLimit: 1000 }); + * + * // Chain multiple configs + * const debugAgent = agent + * .withConfig({ recursionLimit: 1000 }) + * .withConfig({ tags: ["debug"] }); + * ``` + */ + withConfig(config) { + return new ReactAgent(this.options, mergeConfigs(this.#defaultConfig, config)); + } + /** + * Get possible edge destinations from model node. + * @param toolClasses names of tools to call + * @param includeModelRequest whether to include "model_request" as a valid path (for jumpTo routing) + * @param hasToolsAvailable whether tools are available (includes dynamic tools via middleware) + * @returns list of possible edge destinations + */ + #getModelPaths(toolClasses, includeModelRequest = false, hasToolsAvailable = toolClasses.length > 0) { + const paths = []; + if (hasToolsAvailable) paths.push(TOOLS_NODE_NAME); + if (includeModelRequest) paths.push(AGENT_NODE_NAME); + paths.push(END); + return paths; + } + /** + * Create routing function for tools node conditional edges. + */ + #createToolsRouter(shouldReturnDirect, exitNode, toolReturnTarget) { + return (state) => { + const messages = state.messages; + const lastMessage = messages[messages.length - 1]; + if (ToolMessage.isInstance(lastMessage) && lastMessage.name && shouldReturnDirect.has(lastMessage.name)) return this.options.responseFormat ? toolReturnTarget : exitNode; + return toolReturnTarget; + }; + } + /** + * Create routing function for model node conditional edges. + * @param exitNode - The exit node to route to (could be after_agent or END) + */ + #createModelRouter(exitNode = END) { + /** + * determine if the agent should continue or not + */ + return (state) => { + const lastMessage = state.messages.at(-1); + if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) return exitNode; + if (lastMessage.tool_calls.every((toolCall) => toolCall.name.startsWith("extract-"))) return exitNode; + /** + * The tool node processes a single message. + */ + if (this.#toolBehaviorVersion === "v1") return TOOLS_NODE_NAME; + /** + * Route to tools node (filter out any structured response tool calls) + */ + const regularToolCalls = lastMessage.tool_calls.filter((toolCall) => !toolCall.name.startsWith("extract-")); + if (regularToolCalls.length === 0) return exitNode; + return regularToolCalls.map((toolCall) => new Send(TOOLS_NODE_NAME, { + ...state, + lg_tool_call: toolCall + })); + }; + } + /** + * Create routing function for jumpTo functionality after afterModel hooks. + * + * This router checks if the `jumpTo` property is set in the state after afterModel middleware + * execution. If set, it routes to the specified target ("model_request" or "tools"). + * If not set, it falls back to the normal model routing logic for afterModel context. + * + * The jumpTo property is automatically cleared after use to prevent infinite loops. + * + * @param toolClasses - Available tool classes for validation + * @param allowJump - Whether jumping is allowed + * @param exitNode - The exit node to route to (could be after_agent or END) + * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware) + * @returns Router function that handles jumpTo logic and normal routing + */ + #createAfterModelRouter(toolClasses, allowJump, exitNode, hasToolsAvailable = toolClasses.length > 0) { + const hasStructuredResponse = Boolean(this.options.responseFormat); + return (state) => { + const builtInState = state; + const messages = builtInState.messages; + const lastMessage = messages.at(-1); + if (AIMessage.isInstance(lastMessage) && (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)) return exitNode; + if (allowJump && builtInState.jumpTo) { + const destination = parseJumpToTarget(builtInState.jumpTo); + if (destination === "__end__") return exitNode; + if (destination === "tools") { + if (!hasToolsAvailable) return exitNode; + return new Send(TOOLS_NODE_NAME, { + ...state, + jumpTo: void 0 + }); + } + return new Send(AGENT_NODE_NAME, { + ...state, + jumpTo: void 0 + }); + } + const toolMessages = messages.filter(ToolMessage.isInstance); + const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1); + const pendingToolCalls = lastAiMessage?.tool_calls?.filter((call) => !toolMessages.some((m) => m.tool_call_id === call.id)); + if (pendingToolCalls && pendingToolCalls.length > 0) { + /** + * v1: route the full message to the ToolNode; it filters already-processed + * calls internally and runs the remaining ones via Promise.all. + * v2: dispatch each pending call as a separate Send task. + */ + if (this.#toolBehaviorVersion === "v1") return TOOLS_NODE_NAME; + return pendingToolCalls.map((toolCall) => new Send(TOOLS_NODE_NAME, { + ...state, + lg_tool_call: toolCall + })); + } + const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some((toolCall) => toolCall.name.startsWith("extract-")); + if (pendingToolCalls && pendingToolCalls.length === 0 && !hasStructuredResponseCalls && hasStructuredResponse) return AGENT_NODE_NAME; + if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) return exitNode; + const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every((toolCall) => toolCall.name.startsWith("extract-")); + const hasRegularToolCalls = lastMessage.tool_calls.some((toolCall) => !toolCall.name.startsWith("extract-")); + if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) return exitNode; + /** + * v1: route the full AIMessage to a single ToolNode invocation so all + * tool calls run concurrently via Promise.all. + * + * v2: dispatch each regular tool call as a separate Send task, matching + * the behaviour of #createModelRouter when no afterModel middleware is + * present. + */ + if (this.#toolBehaviorVersion === "v1") return TOOLS_NODE_NAME; + const regularToolCalls = lastMessage.tool_calls.filter((toolCall) => !toolCall.name.startsWith("extract-")); + if (regularToolCalls.length === 0) return exitNode; + return regularToolCalls.map((toolCall) => new Send(TOOLS_NODE_NAME, { + ...state, + lg_tool_call: toolCall + })); + }; + } + /** + * Router for afterModel sequence nodes (connecting later middlewares to earlier ones), + * honoring allowed jump targets and defaulting to the next node. + * @param toolClasses - Available tool classes for validation + * @param allowed - List of allowed jump targets + * @param nextDefault - Default node to route to + * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware) + */ + #createAfterModelSequenceRouter(toolClasses, allowed, nextDefault, hasToolsAvailable = toolClasses.length > 0) { + const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t))); + return (state) => { + const builtInState = state; + if (builtInState.jumpTo) { + const dest = parseJumpToTarget(builtInState.jumpTo); + if (dest === "__end__" && allowedSet.has("__end__")) return END; + if (dest === "tools" && allowedSet.has("tools")) { + if (!hasToolsAvailable) return END; + return new Send(TOOLS_NODE_NAME, { + ...state, + jumpTo: void 0 + }); + } + if (dest === "model_request" && allowedSet.has("model_request")) return new Send(AGENT_NODE_NAME, { + ...state, + jumpTo: void 0 + }); + } + return nextDefault; + }; + } + /** + * Create routing function for jumpTo functionality after beforeAgent hooks. + * Falls back to the default next node if no jumpTo is present. + * When jumping to END, routes to exitNode (which could be an afterAgent node). + * @param toolClasses - Available tool classes for validation + * @param nextDefault - Default node to route to + * @param exitNode - Exit node to route to (could be after_agent or END) + * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware) + */ + #createBeforeAgentRouter(toolClasses, nextDefault, exitNode, hasToolsAvailable = toolClasses.length > 0) { + return (state) => { + const builtInState = state; + if (!builtInState.jumpTo) return nextDefault; + const destination = parseJumpToTarget(builtInState.jumpTo); + if (destination === "__end__") + /** + * When beforeAgent jumps to END, route to exitNode (first afterAgent node) + */ + return exitNode; + if (destination === "tools") { + if (!hasToolsAvailable) return exitNode; + return new Send(TOOLS_NODE_NAME, { + ...state, + jumpTo: void 0 + }); + } + return new Send(AGENT_NODE_NAME, { + ...state, + jumpTo: void 0 + }); + }; + } + /** + * Create routing function for jumpTo functionality after beforeModel hooks. + * Falls back to the default next node if no jumpTo is present. + * @param toolClasses - Available tool classes for validation + * @param nextDefault - Default node to route to + * @param hasToolsAvailable - Whether tools are available (includes dynamic tools via middleware) + */ + #createBeforeModelRouter(toolClasses, nextDefault, hasToolsAvailable = toolClasses.length > 0) { + return (state) => { + const builtInState = state; + if (!builtInState.jumpTo) return nextDefault; + const destination = parseJumpToTarget(builtInState.jumpTo); + if (destination === "__end__") return END; + if (destination === "tools") { + if (!hasToolsAvailable) return END; + return new Send(TOOLS_NODE_NAME, { + ...state, + jumpTo: void 0 + }); + } + return new Send(AGENT_NODE_NAME, { + ...state, + jumpTo: void 0 + }); + }; + } + /** + * Initialize middleware states if not already present in the input state. + */ + async #initializeMiddlewareStates(state, config) { + if (!this.options.middleware || this.options.middleware.length === 0 || state instanceof Command || !state) return state; + const defaultStates = await initializeMiddlewareStates(this.options.middleware, state); + const updatedState = { + ...(await this.#graph.getState(config).catch(() => ({ values: {} }))).values, + ...state + }; + if (!updatedState) return updatedState; + for (const [key, value] of Object.entries(defaultStates)) if (!(key in updatedState)) updatedState[key] = value; + return updatedState; + } + /** + * Executes the agent with the given state and returns the final state after all processing. + * + * This method runs the agent's entire workflow synchronously, including: + * - Processing the input messages through any configured middleware + * - Calling the language model to generate responses + * - Executing any tool calls made by the model + * - Running all middleware hooks (beforeModel, afterModel, etc.) + * + * @param state - The initial state for the agent execution. Can be: + * - An object containing `messages` array and any middleware-specific state properties + * - A Command object for more advanced control flow + * + * @param config - Optional runtime configuration including: + * @param config.context - The context for the agent execution. + * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc. + * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}. + * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution. + * @param config.recursionLimit - The recursion limit for the agent execution. + * + * @returns A Promise that resolves to the final agent state after execution completes. + * The returned state includes: + * - a `messages` property containing an array with all messages (input, AI responses, tool calls/results) + * - a `structuredResponse` property containing the structured response (if configured) + * - all state values defined in the middleware + * + * @example + * ```typescript + * const agent = new ReactAgent({ + * llm: myModel, + * tools: [calculator, webSearch], + * responseFormat: z.object({ + * weather: z.string(), + * }), + * }); + * + * const result = await agent.invoke({ + * messages: [{ role: "human", content: "What's the weather in Paris?" }] + * }); + * + * console.log(result.structuredResponse.weather); // outputs: "It's sunny and 75°F." + * ``` + */ + async invoke(state, config) { + const mergedConfig = mergeConfigs(this.#defaultConfig, config); + const initializedState = await this.#initializeMiddlewareStates(state, mergedConfig); + return this.#graph.invoke(initializedState, mergedConfig); + } + /** + * Executes the agent with streaming, returning an async iterable of state updates as they occur. + * + * This method runs the agent's workflow similar to `invoke`, but instead of waiting for + * completion, it streams high-level state updates in real-time. This allows you to: + * - Display intermediate results to users as they're generated + * - Monitor the agent's progress through each step + * - React to state changes as nodes complete + * + * For more granular event-level streaming (like individual LLM tokens), use `streamEvents` instead. + * + * @param state - The initial state for the agent execution. Can be: + * - An object containing `messages` array and any middleware-specific state properties + * - A Command object for more advanced control flow + * + * @param config - Optional runtime configuration including: + * @param config.context - The context for the agent execution. + * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc. + * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}. + * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution. + * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}. + * @param config.recursionLimit - The recursion limit for the agent execution. + * + * @returns A Promise that resolves to an IterableReadableStream of state updates. + * Each update contains the current state after a node completes. + * + * @example + * ```typescript + * const agent = new ReactAgent({ + * llm: myModel, + * tools: [calculator, webSearch] + * }); + * + * const stream = await agent.stream({ + * messages: [{ role: "human", content: "What's 2+2 and the weather in NYC?" }] + * }); + * + * for await (const chunk of stream) { + * console.log(chunk); // State update from each node + * } + * ``` + */ + async stream(state, config) { + const mergedConfig = mergeConfigs(this.#defaultConfig, config); + const initializedState = await this.#initializeMiddlewareStates(state, mergedConfig); + return this.#graph.stream(initializedState, mergedConfig); + } + streamEvents(state, config, streamOptions) { + if (config?.version !== "v3" || streamOptions != null) { + const mergedConfig = mergeConfigs(this.#defaultConfig, config); + const version = config?.version === "v1" || config?.version === "v2" ? config.version : "v2"; + return this.#graph.streamEvents(state, { + ...mergedConfig, + version + }, streamOptions); + } + return (async () => { + const { transformers: callSiteTransformers, version: _version, ...restConfig } = config ?? {}; + const mergedConfig = mergeConfigs(this.#defaultConfig, restConfig); + const initializedState = await this.#initializeMiddlewareStates(state, mergedConfig); + return await this.#graph.streamEvents(initializedState, { + ...mergedConfig, + version: "v3", + transformers: callSiteTransformers + }); + })(); + } + /** + * Visualize the graph as a PNG image. + * @param params - Parameters for the drawMermaidPng method. + * @param params.withStyles - Whether to include styles in the graph. + * @param params.curveStyle - The style of the graph's curves. + * @param params.nodeColors - The colors of the graph's nodes. + * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label. + * @param params.backgroundColor - The background color of the graph. + * @returns PNG image as a buffer + */ + async drawMermaidPng(params) { + const arrayBuffer = await (await (await this.#graph.getGraphAsync()).drawMermaidPng(params)).arrayBuffer(); + return new Uint8Array(arrayBuffer); + } + /** + * Draw the graph as a Mermaid string. + * @param params - Parameters for the drawMermaid method. + * @param params.withStyles - Whether to include styles in the graph. + * @param params.curveStyle - The style of the graph's curves. + * @param params.nodeColors - The colors of the graph's nodes. + * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label. + * @param params.backgroundColor - The background color of the graph. + * @returns Mermaid string + */ + async drawMermaid(params) { + return (await this.#graph.getGraphAsync()).drawMermaid(params); + } + /** + * The following are internal methods to enable support for LangGraph Platform. + * They are not part of the createAgent public API. + * + * Note: we intentionally return as `never` to avoid type errors due to type inference. + */ + /** + * @internal + */ + getGraphAsync(config) { + return this.#graph.getGraphAsync(config); + } + /** + * @internal + */ + getState(config, options) { + return this.#graph.getState(config, options); + } + /** + * @internal + */ + getStateHistory(config, options) { + return this.#graph.getStateHistory(config, options); + } + /** + * @internal + */ + getSubgraphs(namespace, recurse) { + return this.#graph.getSubgraphs(namespace, recurse); + } + /** + * @internal + */ + getSubgraphsAsync(namespace, recurse) { + return this.#graph.getSubgraphsAsync(namespace, recurse); + } + /** + * @internal + */ + updateState(inputConfig, values, asNode) { + return this.#graph.updateState(inputConfig, values, asNode); + } + /** + * @internal + */ + get builder() { + return this.#graph.builder; + } +}; +//#endregion +//#region node_modules/langchain/dist/agents/index.js +function createAgent(params) { + return new ReactAgent(params); +} +//#endregion +//#region node_modules/langchain/dist/agents/middleware/hitl.js +var WhenFunctionSchema = functionType().args(custom$1()).returns(unionType([booleanType(), promiseType(booleanType())])); +var DescriptionFunctionSchema = functionType().args(custom$1(), custom$1(), custom$1()).returns(unionType([stringType(), promiseType(stringType())])); +/** +* The type of decision a human can make. +*/ +var ALLOWED_DECISIONS = [ + "approve", + "edit", + "reject" +]; +var InterruptOnConfigSchema = objectType({ + /** + * The decisions that are allowed for this action. + */ + allowedDecisions: arrayType(enumType(ALLOWED_DECISIONS)), + /** + * The description attached to the request for human input. + * Can be either: + * - A static string describing the approval request + * - A callable that dynamically generates the description based on agent state, + * runtime, and tool call information + * + * @example + * Static string description + * ```typescript + * import type { InterruptOnConfig } from "langchain"; + * + * const config: InterruptOnConfig = { + * allowedDecisions: ["approve", "reject"], + * description: "Please review this tool execution" + * }; + * ``` + * + * @example + * Dynamic callable description + * ```typescript + * import type { + * AgentBuiltInState, + * Runtime, + * DescriptionFactory, + * ToolCall, + * InterruptOnConfig + * } from "langchain"; + * + * const formatToolDescription: DescriptionFactory = ( + * toolCall: ToolCall, + * state: AgentBuiltInState, + * runtime: Runtime + * ) => { + * return `Tool: ${toolCall.name}\nArguments:\n${JSON.stringify(toolCall.args, null, 2)}`; + * }; + * + * const config: InterruptOnConfig = { + * allowedDecisions: ["approve", "edit"], + * description: formatToolDescription + * }; + * ``` + */ + description: unionType([stringType(), DescriptionFunctionSchema]).optional(), + /** + * JSON schema for the arguments associated with the action, if edits are allowed. + */ + argsSchema: recordType(anyType()).optional(), + /** + * Optional predicate controlling whether to interrupt for a given tool call. + * + * Receives a {@link ToolCallRequest} and returns `true` to interrupt or + * `false` to auto-approve the tool call. + * + * The request is constructed with `tool` set to `undefined` and `runtime` set + * to the node-level {@link Runtime}, so `request.tool` is not available. + * + * @example + * ```typescript + * import type { InterruptOnConfig } from "langchain"; + * + * // Only interrupt delete_file calls targeting /etc + * const config: InterruptOnConfig = { + * allowedDecisions: ["approve", "reject"], + * when: (request) => + * String(request.toolCall.args.path ?? "").startsWith("/etc"), + * }; + * ``` + */ + when: WhenFunctionSchema.optional() +}); +var contextSchema$6 = objectType({ + /** + * Mapping of tool name to allowed reviewer responses. + * If a tool doesn't have an entry, it's auto-approved by default. + * + * - `true` -> pause for approval and allow approve/edit/reject decisions + * - `false` -> auto-approve (no human review) + * - `InterruptOnConfig` -> explicitly specify which decisions are allowed for this tool + */ + interruptOn: recordType(unionType([booleanType(), InterruptOnConfigSchema])).optional(), + /** + * Prefix used when constructing human-facing approval messages. + * Provides context about the tool call being reviewed; does not change the underlying action. + * + * Note: This prefix is only applied for tools that do not provide a custom + * `description` via their {@link InterruptOnConfig}. If a tool specifies a custom + * `description`, that per-tool text is used and this prefix is ignored. + */ + descriptionPrefix: stringType().default("Tool execution requires approval") +}); +/** +* Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight. +* +* This middleware intercepts tool calls made by an AI agent and provides human oversight +* capabilities before execution. It enables selective approval workflows where certain tools +* require human intervention while others can execute automatically. +* +* A invocation result that has been interrupted by the middleware will have a `__interrupt__` +* property that contains the interrupt request. +* +* ```ts +* import { type HITLRequest, type HITLResponse } from "langchain"; +* import { type Interrupt } from "langchain"; +* +* const result = await agent.invoke(request); +* const interruptRequest = result.__interrupt__?.[0] as Interrupt; +* +* // Examine the action requests and review configs +* const actionRequests = interruptRequest.value.actionRequests; +* const reviewConfigs = interruptRequest.value.reviewConfigs; +* +* // Create decisions for each action +* const resume: HITLResponse = { +* decisions: actionRequests.map((action, i) => { +* if (action.name === "calculator") { +* return { type: "approve" }; +* } else if (action.name === "write_file") { +* return { +* type: "edit", +* editedAction: { name: "write_file", args: { filename: "safe.txt", content: "Safe content" } } +* }; +* } +* return { type: "reject", message: "Action not allowed" }; +* }) +* }; +* +* // Resume with decisions +* await agent.invoke(new Command({ resume }), config); +* ``` +* +* ## Features +* +* - **Selective Tool Approval**: Configure which tools require human approval +* - **Multiple Decision Types**: Approve, edit, or reject tool calls +* - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval +* - **Custom Approval Messages**: Provide context-specific descriptions for approval requests +* +* ## Decision Types +* +* When a tool requires approval, the human operator can respond with: +* - `approve`: Execute the tool with original arguments +* - `edit`: Modify the tool name and/or arguments before execution +* - `reject`: Provide a manual response instead of executing the tool +* +* @param options - Configuration options for the middleware +* @param options.interruptOn - Per-tool configuration mapping tool names to their settings +* @param options.interruptOn[toolName].allowedDecisions - Array of decision types allowed for this tool (e.g., ["approve", "edit", "reject"]) +* @param options.interruptOn[toolName].description - Custom approval message for the tool. Can be either a static string or a callable that dynamically generates the description based on agent state, runtime, and tool call information +* @param options.interruptOn[toolName].argsSchema - JSON schema for the arguments associated with the action, if edits are allowed +* @param options.interruptOn[toolName].when - Optional predicate that dynamically controls whether a tool call triggers an interrupt. Returns `true` to interrupt or `false` to auto-approve the tool call. +* @param options.descriptionPrefix - Default prefix for approval messages (default: "Tool execution requires approval"). Only used for tools that do not define a custom `description` in their InterruptOnConfig. +* +* @returns A middleware instance that can be passed to `createAgent` +* +* @example +* Basic usage with selective tool approval +* ```typescript +* import { humanInTheLoopMiddleware } from "langchain"; +* import { createAgent } from "langchain"; +* +* const hitlMiddleware = humanInTheLoopMiddleware({ +* interruptOn: { +* // Interrupt write_file tool and allow edits or approvals +* "write_file": { +* allowedDecisions: ["approve", "edit"], +* description: "⚠️ File write operation requires approval" +* }, +* // Auto-approve read_file tool +* "read_file": false +* } +* }); +* +* const agent = createAgent({ +* model: "openai:gpt-4", +* tools: [writeFileTool, readFileTool], +* middleware: [hitlMiddleware] +* }); +* ``` +* +* @example +* Handling approval requests +* ```typescript +* import { type HITLRequest, type HITLResponse, type Interrupt } from "langchain"; +* import { Command } from "@langchain/langgraph"; +* +* // Initial agent invocation +* const result = await agent.invoke({ +* messages: [new HumanMessage("Write 'Hello' to output.txt")] +* }, config); +* +* // Check if agent is paused for approval +* if (result.__interrupt__) { +* const interruptRequest = result.__interrupt__?.[0] as Interrupt; +* +* // Show tool call details to user +* console.log("Actions:", interruptRequest.value.actionRequests); +* console.log("Review configs:", interruptRequest.value.reviewConfigs); +* +* // Resume with approval +* const resume: HITLResponse = { +* decisions: [{ type: "approve" }] +* }; +* await agent.invoke( +* new Command({ resume }), +* config +* ); +* } +* ``` +* +* @example +* Different decision types +* ```typescript +* import { type HITLResponse } from "langchain"; +* +* // Approve the tool call as-is +* const resume: HITLResponse = { +* decisions: [{ type: "approve" }] +* }; +* +* // Edit the tool arguments +* const resume: HITLResponse = { +* decisions: [{ +* type: "edit", +* editedAction: { name: "write_file", args: { filename: "safe.txt", content: "Modified" } } +* }] +* }; +* +* // Reject with feedback +* const resume: HITLResponse = { +* decisions: [{ +* type: "reject", +* message: "File operation not allowed in demo mode" +* }] +* }; +* ``` +* +* @example +* Production use case with database operations +* ```typescript +* const hitlMiddleware = humanInTheLoopMiddleware({ +* interruptOn: { +* "execute_sql": { +* allowedDecisions: ["approve", "edit", "reject"], +* description: "🚨 SQL query requires DBA approval\nPlease review for safety and performance" +* }, +* "read_schema": false, // Reading metadata is safe +* "delete_records": { +* allowedDecisions: ["approve", "reject"], +* description: "⛔ DESTRUCTIVE OPERATION - Requires manager approval" +* } +* }, +* descriptionPrefix: "Database operation pending approval" +* }); +* ``` +* +* @example +* Using dynamic callable descriptions +* ```typescript +* import { type DescriptionFactory, type ToolCall } from "langchain"; +* import type { AgentBuiltInState, Runtime } from "langchain/agents"; +* +* // Define a dynamic description factory +* const formatToolDescription: DescriptionFactory = ( +* toolCall: ToolCall, +* state: AgentBuiltInState, +* runtime: Runtime +* ) => { +* return `Tool: ${toolCall.name}\nArguments:\n${JSON.stringify(toolCall.args, null, 2)}`; +* }; +* +* const hitlMiddleware = humanInTheLoopMiddleware({ +* interruptOn: { +* "write_file": { +* allowedDecisions: ["approve", "edit"], +* // Use dynamic description that can access tool call, state, and runtime +* description: formatToolDescription +* }, +* // Or use an inline function +* "send_email": { +* allowedDecisions: ["approve", "reject"], +* description: (toolCall, state, runtime) => { +* const { to, subject } = toolCall.args; +* return `Email to ${to}\nSubject: ${subject}\n\nRequires approval before sending`; +* } +* } +* } +* }); +* ``` +* +* @remarks +* - Tool calls are processed in the order they appear in the AI message +* - Auto-approved tools execute immediately without interruption +* - Multiple tools requiring approval are bundled into a single interrupt request +* - The middleware operates in the `afterModel` phase, intercepting before tool execution +* - Requires a checkpointer to maintain state across interruptions +* +* @see {@link createAgent} for agent creation +* @see {@link Command} for resuming interrupted execution +* @public +*/ +function humanInTheLoopMiddleware(options) { + const createActionAndConfig = async (toolCall, config, state, runtime) => { + const toolName = toolCall.name; + const toolArgs = toolCall.args; + const descriptionValue = config.description; + let description; + if (typeof descriptionValue === "function") description = await descriptionValue(toolCall, state, runtime); + else if (descriptionValue !== void 0) description = descriptionValue; + else description = `${options.descriptionPrefix ?? "Tool execution requires approval"}\n\nTool: ${toolName}\nArgs: ${JSON.stringify(toolArgs, null, 2)}`; + /** + * Create ActionRequest with description + */ + const actionRequest = { + name: toolName, + args: toolArgs, + description + }; + /** + * Create ReviewConfig + */ + const reviewConfig = { + actionName: toolName, + allowedDecisions: config.allowedDecisions + }; + if (config.argsSchema) reviewConfig.argsSchema = config.argsSchema; + return { + actionRequest, + reviewConfig + }; + }; + /** + * Return `false` if the `when` predicate rejects this tool call, `true` otherwise. + * + * When no `when` predicate is configured the tool call always interrupts. + */ + const shouldInterrupt = async (toolCall, config, state, runtime) => { + const { when } = config; + if (when == null) return true; + return when({ + toolCall, + tool: void 0, + state, + runtime + }); + }; + const processDecision = (decision, toolCall, config) => { + const allowedDecisions = config.allowedDecisions; + if (decision.type === "approve" && allowedDecisions.includes("approve")) return { + revisedToolCall: toolCall, + toolMessage: null + }; + if (decision.type === "edit" && allowedDecisions.includes("edit")) { + const editedAction = decision.editedAction; + /** + * Validate edited action structure + */ + if (!editedAction || typeof editedAction.name !== "string") throw new Error(`Invalid edited action for tool "${toolCall.name}": name must be a string`); + if (!editedAction.args || typeof editedAction.args !== "object") throw new Error(`Invalid edited action for tool "${toolCall.name}": args must be an object`); + return { + revisedToolCall: { + type: "tool_call", + name: editedAction.name, + args: editedAction.args, + id: toolCall.id + }, + toolMessage: null + }; + } + if (decision.type === "reject" && allowedDecisions.includes("reject")) { + /** + * Validate that message is a string if provided + */ + if (decision.message !== void 0 && typeof decision.message !== "string") throw new Error(`Tool call response for "${toolCall.name}" must be a string, got ${typeof decision.message}`); + return { + revisedToolCall: toolCall, + toolMessage: new ToolMessage({ + content: decision.message ?? `User rejected the tool call for \`${toolCall.name}\` with id ${toolCall.id}`, + name: toolCall.name, + tool_call_id: toolCall.id, + status: "error" + }) + }; + } + const msg = `Unexpected human decision: ${JSON.stringify(decision)}. Decision type '${decision.type}' is not allowed for tool '${toolCall.name}'. Expected one of ${JSON.stringify(allowedDecisions)} based on the tool's configuration.`; + throw new Error(msg); + }; + return createMiddleware({ + name: "HumanInTheLoopMiddleware", + contextSchema: contextSchema$6, + afterModel: { + canJumpTo: ["model"], + hook: async (state, runtime) => { + const config = interopParse(contextSchema$6, { + ...options, + ...runtime.context || {} + }); + if (!config) return; + const { messages } = state; + if (!messages.length) return; + /** + * Don't do anything if the last message isn't an AI message with tool calls. + */ + const lastMessage = [...messages].reverse().find((msg) => AIMessage.isInstance(msg)); + if (!lastMessage || !lastMessage.tool_calls?.length) return; + /** + * If the user omits the interruptOn config, we don't do anything. + */ + if (!config.interruptOn) return; + /** + * Resolve per-tool configs (boolean true -> all decisions allowed; false -> auto-approve) + */ + const resolvedConfigs = {}; + for (const [toolName, toolConfig] of Object.entries(config.interruptOn)) if (typeof toolConfig === "boolean") { + if (toolConfig === true) resolvedConfigs[toolName] = { allowedDecisions: [...ALLOWED_DECISIONS] }; + } else if (toolConfig.allowedDecisions) resolvedConfigs[toolName] = toolConfig; + const interruptToolCalls = []; + const autoApprovedToolCalls = []; + for (const toolCall of lastMessage.tool_calls) { + const interruptConfig = resolvedConfigs[toolCall.name]; + /** + * A tool call is interrupted only when it has a resolved config and its + * optional `when` predicate doesn't opt it out. Otherwise it is + * auto-approved. + */ + if (interruptConfig && await shouldInterrupt(toolCall, interruptConfig, state, runtime)) interruptToolCalls.push(toolCall); + else autoApprovedToolCalls.push(toolCall); + } + /** + * No interrupt tool calls, so we can just return. + */ + if (!interruptToolCalls.length) return; + /** + * Create action requests and review configs for all tools that need approval + */ + const actionRequests = []; + const reviewConfigs = []; + for (const toolCall of interruptToolCalls) { + const interruptConfig = resolvedConfigs[toolCall.name]; + /** + * Create ActionRequest and ReviewConfig using helper method + */ + const { actionRequest, reviewConfig } = await createActionAndConfig(toolCall, interruptConfig, state, runtime); + actionRequests.push(actionRequest); + reviewConfigs.push(reviewConfig); + } + const decisions = (await interrupt({ + actionRequests, + reviewConfigs + })).decisions; + /** + * Validate that decisions is a valid array before checking length + */ + if (!decisions || !Array.isArray(decisions)) throw new Error("Invalid HITLResponse: decisions must be a non-empty array"); + /** + * Validate that the number of decisions matches the number of interrupt tool calls + */ + if (decisions.length !== interruptToolCalls.length) throw new Error(`Number of human decisions (${decisions.length}) does not match number of hanging tool calls (${interruptToolCalls.length}).`); + const revisedToolCalls = [...autoApprovedToolCalls]; + const artificialToolMessages = []; + const hasRejectedToolCalls = decisions.some((decision) => decision.type === "reject"); + /** + * Process each decision using helper method + */ + for (let i = 0; i < decisions.length; i++) { + const decision = decisions[i]; + const toolCall = interruptToolCalls[i]; + const interruptConfig = resolvedConfigs[toolCall.name]; + const { revisedToolCall, toolMessage } = processDecision(decision, toolCall, interruptConfig); + if (revisedToolCall && (!hasRejectedToolCalls || decision.type === "reject")) revisedToolCalls.push(revisedToolCall); + if (toolMessage) artificialToolMessages.push(toolMessage); + } + /** + * Update the AI message to only include approved tool calls + */ + if (AIMessage.isInstance(lastMessage)) lastMessage.tool_calls = revisedToolCalls; + const jumpTo = hasRejectedToolCalls ? "model" : void 0; + return { + messages: [lastMessage, ...artificialToolMessages], + jumpTo + }; + } + } + }); +} +//#endregion +//#region node_modules/langchain/dist/agents/middleware/summarization.js +var DEFAULT_SUMMARY_PROMPT$1 = ` +Context Extraction Assistant + + + +Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below. + + + +You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history. +This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal. + + + +The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history. +You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal. + + +The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved: + +With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history. +Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context. + + +Messages to summarize: +{messages} +`; +var tokenCounterSchema = functionType().args(arrayType(custom$1())).returns(unionType([numberType(), promiseType(numberType())])); +var contextSizeSchema = objectType({ + /** + * Fraction of the model's context size to use as the trigger + */ + fraction: numberType().gt(0, "Fraction must be greater than 0").max(1, "Fraction must be less than or equal to 1").optional(), + /** + * Number of tokens to use as the trigger + */ + tokens: numberType().positive("Tokens must be greater than 0").optional(), + /** + * Number of messages to use as the trigger + */ + messages: numberType().int("Messages must be an integer").positive("Messages must be greater than 0").optional() +}).refine((data) => { + return [ + data.fraction, + data.tokens, + data.messages + ].filter((v) => v !== void 0).length >= 1; +}, { message: "At least one of fraction, tokens, or messages must be provided" }); +var keepSchema = objectType({ + /** + * Fraction of the model's context size to keep + */ + fraction: numberType().min(0, "Messages must be non-negative").max(1, "Fraction must be less than or equal to 1").optional(), + /** + * Number of tokens to keep + */ + tokens: numberType().min(0, "Tokens must be greater than or equal to 0").optional(), + messages: numberType().int("Messages must be an integer").min(0, "Messages must be non-negative").optional() +}).refine((data) => { + return [ + data.fraction, + data.tokens, + data.messages + ].filter((v) => v !== void 0).length === 1; +}, { message: "Exactly one of fraction, tokens, or messages must be provided" }); +objectType({ + /** + * Model to use for summarization + */ + model: custom$1(), + /** + * Trigger conditions for summarization. + * Can be a single condition object (all properties must be met) or an array of conditions (any condition must be met). + * + * @example + * ```ts + * // Single condition: trigger if tokens >= 5000 AND messages >= 3 + * trigger: { tokens: 5000, messages: 3 } + * + * // Multiple conditions: trigger if (tokens >= 5000 AND messages >= 3) OR (tokens >= 3000 AND messages >= 6) + * trigger: [ + * { tokens: 5000, messages: 3 }, + * { tokens: 3000, messages: 6 } + * ] + * ``` + */ + trigger: unionType([contextSizeSchema, arrayType(contextSizeSchema)]).optional(), + /** + * Keep conditions for summarization + */ + keep: keepSchema.optional(), + /** + * Token counter function to use for summarization + */ + tokenCounter: tokenCounterSchema.optional(), + /** + * Summary prompt to use for summarization + * @default {@link DEFAULT_SUMMARY_PROMPT} + */ + summaryPrompt: stringType().default(DEFAULT_SUMMARY_PROMPT$1), + /** + * Number of tokens to trim to before summarizing + */ + trimTokensToSummarize: numberType().optional(), + /** + * Prefix to add to the summary + */ + summaryPrefix: stringType().optional(), + /** + * @deprecated Use `trigger: { tokens: value }` instead. + */ + maxTokensBeforeSummary: numberType().optional(), + /** + * @deprecated Use `keep: { messages: value }` instead. + */ + messagesToKeep: numberType().optional() +}); +objectType({ + /** + * The language model to use for tool selection (default: the provided model from the agent options). + */ + model: stringType().or(instanceOfType(BaseLanguageModel)).optional(), + /** + * System prompt for the tool selection model. + */ + systemPrompt: stringType().optional(), + /** + * Maximum number of tools to select. If the model selects more, + * only the first maxTools will be used. No limit if not specified. + */ + maxTools: numberType().optional(), + /** + * Tool names to always include regardless of selection. + * These do not count against the maxTools limit. + */ + alwaysInclude: arrayType(stringType()).optional() +}); +objectType({ + /** + * Whether to check user messages before model call + */ + applyToInput: booleanType().optional(), + /** + * Whether to check AI messages after model call + */ + applyToOutput: booleanType().optional(), + /** + * Whether to check tool result messages after tool execution + */ + applyToToolResults: booleanType().optional() +}); +objectType({ +/** +* A record of PII detection rules to apply +* @default DEFAULT_PII_RULES (with enabled rules only) +*/ +rules: recordType(stringType(), instanceOfType(RegExp).describe("Regular expression pattern to match PII")).optional() }); +/** +* Schema for the exit behavior. +*/ +var exitBehaviorSchema = enumType([ + "continue", + "error", + "end" +]).default("continue"); +objectType({ + /** + * Name of the specific tool to limit. If undefined, limits apply to all tools. + */ + toolName: stringType().optional(), + /** + * Maximum number of tool calls allowed per thread. + * undefined means no limit. + */ + threadLimit: numberType().optional(), + /** + * Maximum number of tool calls allowed per run. + * undefined means no limit. + */ + runLimit: numberType().optional(), + /** + * What to do when limits are exceeded. + * - "continue": Block exceeded tools with error messages, let other tools continue (default) + * - "error": Raise a ToolCallLimitExceededError exception + * - "end": Stop execution immediately, injecting a ToolMessage and an AI message + * for the single tool call that exceeded the limit. Raises NotImplementedError + * if there are multiple tool calls. + * + * @default "continue" + */ + exitBehavior: exitBehaviorSchema +}); +objectType({ + threadToolCallCount: recordType(stringType(), numberType()).default({}), + runToolCallCount: recordType(stringType(), numberType()).default({}) +}); +//#endregion +//#region node_modules/langchain/dist/agents/middleware/todoListMiddleware.js +/** +* Description for the write_todos tool +* Ported exactly from Python WRITE_TODOS_DESCRIPTION +*/ +var WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user. +It also helps the user understand the progress of the task and overall progress of their requests. +Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the task directly. + +## When to Use This Tool +Use this tool in these scenarios: + +1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions +2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations +3. User explicitly requests todo list - When the user directly asks you to use the todo list +4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated) +5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful. + +## How to Use This Tool +1. When you start working on a task - Mark it as in_progress BEFORE beginning work. +2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation. +3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks. +4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress. + +## When NOT to Use This Tool +It is important to skip using this tool when: +1. There is only a single, straightforward task +2. The task is trivial and tracking it provides no benefit +3. The task can be completed in less than 3 trivial steps +4. The task is purely conversational or informational + +## Examples of When to Use the Todo List + + +User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done! +Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation. +*Creates todo list with the following items:* +1. Create dark mode toggle component in Settings page +2. Add dark mode state management (context/store) +3. Implement CSS-in-JS styles for dark theme +4. Update existing components to support theme switching +5. Run tests and build process, addressing any failures or errors that occur +*Begins working on the first task* + + +The assistant used the todo list because: +1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes +2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task +3. Both of the user's requests are complex and require multiple steps to complete. + + + + +User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases. +Assistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components. +*Creates todo list with the following items:* +1. Define target audience and key messaging +2. Create social media content calendar and posting schedule +3. Design email marketing sequence and automation flows +4. Draft press release and identify media contacts +5. Set up tracking and analytics for campaign performance +6. Create visual assets and brand materials +7. Coordinate launch timeline and deliverables +*Begins working on the first task* + + +The assistant used the todo list because: +1. Marketing campaign planning involves multiple distinct channels and activities +2. Each component requires careful coordination and planning +3. The systematic approach ensures all aspects of the launch are covered + + + + +User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project +Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'. +*Uses search tools to locate all instances of getCwd in the codebase* +Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes. +*Creates todo list with specific items for each file that needs updating* + + +The assistant used the todo list because: +1. The assistant searched to understand the scope of the task +2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3) +3. The todo list helps ensure every instance is tracked and updated systematically +4. This approach prevents missing any occurrences and maintains consistency. + + + + +User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow. +Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization. +*Creates todo list with items like: 1) Sort and declutter desk items, 2) Set up physical filing system for documents, 3) Organize digital files and folders, 4) Create daily workflow and productivity systems, 5) Establish maintenance routines* +Let's start with decluttering your desk space to create a clean foundation for the other organizational systems. + + +The assistant used the todo list because: +1. The user provided multiple distinct organizational tasks +2. Each area requires different approaches and careful planning +3. Home organization benefits from systematic, step-by-step completion +4. Progress tracking ensures all areas are addressed thoroughly + + + +## Examples of When NOT to Use the Todo List + + +User: How do I print 'Hello World' in Python? +Assistant: In Python, you can print "Hello World" with this simple code: + +\`\`\`python +print("Hello World") +\`\`\` + +This will output the text "Hello World" to the console when executed. + + +The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request. + + + + +User: What's the best way to water houseplants? +Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines: + +- Check soil moisture by inserting your finger about 1-2 inches into the soil +- Water thoroughly when the top inch feels dry, allowing water to drain from the bottom +- Use room temperature water and water in the morning when possible +- Avoid overwatering, which is more harmful than underwatering for most plants + +Different plants have different needs, so it's important to research your specific varieties for optimal care. + + +The assistant did not use the todo list because this is an informational request with no actual tasks to complete. The user is simply asking for advice and explanation, not for the assistant to perform multiple steps or activities. + + + + +User: Can you add a comment to the calculateTotal function to explain what it does? +Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does. +* Uses the Edit tool to add a comment to the calculateTotal function * + + +The assistant did not use the todo list because this is a single, straightforward task confined to one location. Adding a comment doesn't require tracking multiple steps or systematic organization. + + + + +User: What time is it in Tokyo right now? +Assistant: I'll check the current time in Tokyo for you. + +*Searches for current time in Tokyo* + +The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9. + + +The assistant did not use the todo list because this is a single information lookup with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward request. + + + + +User: I need to write a function that checks if a number is prime and then test it out. +Assistant: I'll help you write a function that checks if a number is prime and then test it out. +*Writes function that checks if a number is prime* +*Tests the function* + + +Even though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens. + + + + +User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway. +Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway. +*Orders a pizza from Dominos* +*Orders a burger from McDonald's* +*Orders a salad from Subway* + + +Even though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls. +Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact. + + + + +## Task States and Management + +1. **Task States**: Use these states to track progress: + - pending: Task not yet started + - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel) + - completed: Task finished successfully + +2. **Task Management**: + - Update task status in real-time as you work + - Mark tasks complete IMMEDIATELY after finishing (don't batch completions) + - Complete current tasks before starting new ones + - Remove tasks that are no longer relevant from the list entirely + - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!. + - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something. + +3. **Task Completion Requirements**: + - ONLY mark a task as completed when you have FULLY accomplished it + - If you encounter errors, blockers, or cannot finish, keep the task as in_progress + - When blocked, create a new task describing what needs to be resolved + - Never mark a task as completed if: + - There are unresolved issues or errors + - Work is partial or incomplete + - You encountered blockers that prevent completion + - You couldn't find necessary resources or dependencies + - Quality standards haven't been met + +4. **Task Breakdown**: + - Create specific, actionable items + - Break complex tasks into smaller, manageable steps + - Use clear, descriptive task names + +Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully +Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`; +var TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = `## \`write_todos\` + +You have access to the \`write_todos\` tool to help you manage and plan complex objectives. +Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress. +This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps. + +It is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed. +For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool. +Writing todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests. + +## Important To-Do List Usage Notes to Remember +- The \`write_todos\` tool should never be called multiple times in parallel. +- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`; +var TodoStatus = enumType([ + "pending", + "in_progress", + "completed" +]).describe("Status of the todo"); +var TodoSchema = objectType({ + content: stringType().describe("Content of the todo item"), + status: TodoStatus +}); +var stateSchema$1 = objectType({ todos: arrayType(TodoSchema).default([]) }); +/** +* Creates a middleware that provides todo list management capabilities to agents. +* +* This middleware adds a `write_todos` tool that allows agents to create and manage +* structured task lists for complex multi-step operations. It's designed to help +* agents track progress, organize complex tasks, and provide users with visibility +* into task completion status. +* +* The middleware automatically injects system prompts that guide the agent on when +* and how to use the todo functionality effectively. It also enforces that the +* `write_todos` tool is called at most once per model turn, since the tool replaces +* the entire todo list and parallel calls would create ambiguity about precedence. +* +* @example +* ```typescript +* import { todoListMiddleware, createAgent } from 'langchain'; +* +* const agent = createAgent({ +* model: "openai:gpt-4o", +* middleware: [todoListMiddleware()], +* }); +* +* // Agent now has access to write_todos tool and todo state tracking +* const result = await agent.invoke({ +* messages: [new HumanMessage("Help me refactor my codebase")] +* }); +* +* console.log(result.todos); // Array of todo items with status tracking +* ``` +* +* @returns A configured middleware instance that provides todo management capabilities +* +* @see {@link TodoMiddlewareState} for the state schema +* @see {@link writeTodos} for the tool implementation +*/ +function todoListMiddleware(options) { + /** + * Write todos tool - manages todo list with Command return + */ + const writeTodos = tool(({ todos }, config) => { + return new Command({ update: { + todos, + messages: [new ToolMessage({ + content: `Updated todo list to ${JSON.stringify(todos)}`, + tool_call_id: config.toolCall?.id, + name: "write_todos" + })] + } }); + }, { + name: "write_todos", + description: options?.toolDescription ?? WRITE_TODOS_DESCRIPTION, + schema: objectType({ todos: arrayType(TodoSchema).describe("List of todo items to update") }) + }); + return createMiddleware({ + name: "todoListMiddleware", + stateSchema: stateSchema$1, + tools: [writeTodos], + wrapModelCall: (request, handler) => handler({ + ...request, + systemMessage: request.systemMessage.concat(`\n\n${options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT}`) + }), + afterModel: (state) => { + /** + * Check for parallel write_todos tool calls and return errors if detected. + * + * The todo list is designed to be updated at most once per model turn. Since + * the `write_todos` tool replaces the entire todo list with each call, making + * multiple parallel calls would create ambiguity about which update should take + * precedence. This method prevents such conflicts by rejecting any response that + * contains multiple write_todos tool calls. + */ + const messages = state.messages; + if (!messages || messages.length === 0) return; + /** + * Find the last AI message + */ + const lastAiMsg = [...messages].reverse().find((msg) => AIMessage.isInstance(msg)); + if (!lastAiMsg || !lastAiMsg.tool_calls || lastAiMsg.tool_calls.length === 0) return; + /** + * Count write_todos tool calls + */ + const writeTodosCalls = lastAiMsg.tool_calls.filter((tc) => tc.name === writeTodos.name); + if (writeTodosCalls.length > 1) + /** + * Keep the tool calls in the AI message but return error messages + * This follows the same pattern as HumanInTheLoopMiddleware + */ + return { messages: writeTodosCalls.map((tc) => new ToolMessage({ + content: "Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.", + tool_call_id: tc.id, + name: "write_todos", + status: "error" + })) }; + } + }); +} +objectType({ + /** + * The maximum number of model calls allowed per thread. + */ + threadLimit: numberType().optional(), + /** + * The maximum number of model calls allowed per run. + */ + runLimit: numberType().optional(), + /** + * The behavior to take when the limit is exceeded. + * - "error" will throw an error and stop the agent. + * - "end" will end the agent. + * @default "end" + */ + exitBehavior: enumType(["error", "end"]).optional() +}); +objectType({ + threadModelCallCount: numberType().default(0), + runModelCallCount: numberType().default(0) +}); +//#endregion +//#region node_modules/langchain/dist/agents/middleware/constants.js +var RetrySchema = objectType({ + /** + * Maximum number of retry attempts after the initial call. + * Default is 2 retries (3 total attempts). Must be >= 0. + */ + maxRetries: numberType().min(0).default(2), + /** + * Either an array of error constructors to retry on, or a function + * that takes an error and returns `true` if it should be retried. + * Default is to retry on all errors. + */ + retryOn: unionType([functionType().args(instanceOfType(Error)).returns(booleanType()), arrayType(custom$1())]).default(() => () => true), + /** + * Multiplier for exponential backoff. Each retry waits + * `initialDelayMs * (backoffFactor ** retryNumber)` milliseconds. + * Set to 0.0 for constant delay. Default is 2.0. + */ + backoffFactor: numberType().min(0).default(2), + /** + * Initial delay in milliseconds before first retry. Default is 1000 (1 second). + */ + initialDelayMs: numberType().min(0).default(1e3), + /** + * Maximum delay in milliseconds between retries. Caps exponential + * backoff growth. Default is 60000 (60 seconds). + */ + maxDelayMs: numberType().min(0).default(6e4), + /** + * Whether to add random jitter (±25%) to delay to avoid thundering herd. + * Default is `true`. + */ + jitter: booleanType().default(true) +}); +objectType({ +/** +* Behavior when all retries are exhausted. Options: +* - `"continue"` (default): Return an AIMessage with error details, allowing +* the agent to potentially handle the failure gracefully. +* - `"error"`: Re-raise the exception, stopping agent execution. +* - Custom function: Function that takes the exception and returns a string +* for the AIMessage content, allowing custom error formatting. +*/ +onFailure: unionType([ + literalType("error"), + literalType("continue"), + functionType().args(instanceOfType(Error)).returns(stringType()) +]).default("continue") }).merge(RetrySchema); +objectType({ + /** + * Optional list of tools or tool names to apply retry logic to. + * Can be a list of `BaseTool` instances or tool name strings. + * If `undefined`, applies to all tools. Default is `undefined`. + */ + tools: arrayType(unionType([ + custom$1(), + custom$1(), + stringType() + ])).optional(), + /** + * Behavior when all retries are exhausted. Options: + * - `"continue"` (default): Return an AIMessage with error details, allowing + * the agent to potentially handle the failure gracefully. + * - `"error"`: Re-raise the exception, stopping agent execution. + * - Custom function: Function that takes the exception and returns a string + * for the AIMessage content, allowing custom error formatting. + * + * Deprecated values: + * - `"raise"`: use `"error"` instead. + * - `"return_message"`: use `"continue"` instead. + */ + onFailure: unionType([ + literalType("error"), + literalType("continue"), + literalType("raise"), + literalType("return_message"), + functionType().args(instanceOfType(Error)).returns(stringType()) + ]).default("continue") +}).merge(RetrySchema); +//#endregion +//#region node_modules/langchain/dist/agents/middleware/provider/anthropic/promptCaching.js +var DEFAULT_ENABLE_CACHING$1 = true; +var DEFAULT_TTL$1 = "5m"; +var DEFAULT_MIN_MESSAGES_TO_CACHE$1 = 3; +var DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR$1 = "warn"; +var contextSchema$1 = objectType({ + /** + * Whether to enable prompt caching. + * @default true + */ + enableCaching: booleanType().optional(), + /** + * The time-to-live for the cached prompt. + * @default "5m" + */ + ttl: enumType(["5m", "1h"]).optional(), + /** + * The minimum number of messages required before caching is applied. + * @default 3 + */ + minMessagesToCache: numberType().optional(), + /** + * The behavior to take when an unsupported model is used. + * - "ignore" will ignore the unsupported model and continue without caching. + * - "warn" will warn the user and continue without caching. + * - "raise" will raise an error and stop the agent. + * @default "warn" + */ + unsupportedModelBehavior: enumType([ + "ignore", + "warn", + "raise" + ]).optional() +}); +var PromptCachingMiddlewareError = class extends Error { + constructor(message) { + super(message); + this.name = "PromptCachingMiddlewareError"; + } +}; +/** +* Creates a prompt caching middleware for Anthropic models to optimize API usage. +* +* This middleware automatically adds cache control headers to the last messages when using Anthropic models, +* enabling their prompt caching feature. This can significantly reduce costs for applications with repetitive +* prompts, long system messages, or extensive conversation histories. +* +* ## How It Works +* +* The middleware intercepts model requests and adds cache control metadata that tells Anthropic's +* API to cache processed prompt prefixes. On subsequent requests with matching prefixes, the +* cached representations are reused, skipping redundant token processing. +* +* ## Benefits +* +* - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly (up to 90% savings on cached portions) +* - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed +* - **Better Scalability**: Reduced computational load enables handling more requests +* - **Consistent Performance**: Stable response times for repetitive queries +* +* @param middlewareOptions - Configuration options for the caching behavior +* @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`) +* @param middlewareOptions.ttl - Cache time-to-live: `"5m"` for 5 minutes or `"1h"` for 1 hour (default: `"5m"`) +* @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`) +* @param middlewareOptions.unsupportedModelBehavior - The behavior to take when an unsupported model is used (default: `"warn"`) +* +* @returns A middleware instance that can be passed to `createAgent` +* +* @throws {Error} If used with non-Anthropic models +* +* @example +* Basic usage with default settings +* ```typescript +* import { createAgent } from "langchain"; +* import { anthropicPromptCachingMiddleware } from "langchain"; +* +* const agent = createAgent({ +* model: "anthropic:claude-sonnet-4-5", +* middleware: [ +* anthropicPromptCachingMiddleware() +* ] +* }); +* ``` +* +* @example +* Custom configuration for longer conversations +* ```typescript +* const cachingMiddleware = anthropicPromptCachingMiddleware({ +* ttl: "1h", // Cache for 1 hour instead of default 5 minutes +* minMessagesToCache: 5 // Only cache after 5 messages +* }); +* +* const agent = createAgent({ +* model: "anthropic:claude-sonnet-4-5", +* systemPrompt: "You are a helpful assistant with deep knowledge of...", // Long system prompt +* middleware: [cachingMiddleware] +* }); +* ``` +* +* @example +* Conditional caching based on runtime context +* ```typescript +* const agent = createAgent({ +* model: "anthropic:claude-sonnet-4-5", +* middleware: [ +* anthropicPromptCachingMiddleware({ +* enableCaching: true, +* ttl: "5m" +* }) +* ] +* }); +* +* // Disable caching for specific requests +* await agent.invoke( +* { messages: [new HumanMessage("Process this without caching")] }, +* { +* configurable: { +* middleware_context: { enableCaching: false } +* } +* } +* ); +* ``` +* +* @example +* Optimal setup for customer support chatbot +* ```typescript +* const supportAgent = createAgent({ +* model: "anthropic:claude-sonnet-4-5", +* systemPrompt: `You are a customer support agent for ACME Corp. +* +* Company policies: +* - Always be polite and professional +* - Refer to knowledge base for product information +* - Escalate billing issues to human agents +* ... (extensive policies and guidelines) +* `, +* tools: [searchKnowledgeBase, createTicket, checkOrderStatus], +* middleware: [ +* anthropicPromptCachingMiddleware({ +* ttl: "1h", // Long TTL for stable system prompt +* minMessagesToCache: 1 // Cache immediately due to large system prompt +* }) +* ] +* }); +* ``` +* +* @remarks +* - **Anthropic Only**: This middleware only works with Anthropic models and will throw an error if used with other providers +* - **Automatic Application**: Caching is applied automatically when message count exceeds `minMessagesToCache` +* - **Cache Scope**: Caches are isolated per API key and cannot be shared across different keys +* - **TTL Options**: Only supports "5m" (5 minutes) and "1h" (1 hour) as TTL values per Anthropic's API +* - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications +* - **Cost Impact**: Cached tokens are billed at 10% of the base input token price, cache writes are billed at 25% of the base +* +* @see {@link createAgent} for agent creation +* @see {@link https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching} Anthropic's prompt caching documentation +* @public +*/ +function anthropicPromptCachingMiddleware(middlewareOptions) { + return createMiddleware({ + name: "PromptCachingMiddleware", + contextSchema: contextSchema$1, + wrapModelCall: (request, handler) => { + /** + * Prefer runtime context values over middleware options values over defaults + */ + const enableCaching = request.runtime.context.enableCaching ?? middlewareOptions?.enableCaching ?? DEFAULT_ENABLE_CACHING$1; + const ttl = request.runtime.context.ttl ?? middlewareOptions?.ttl ?? DEFAULT_TTL$1; + const minMessagesToCache = request.runtime.context.minMessagesToCache ?? middlewareOptions?.minMessagesToCache ?? DEFAULT_MIN_MESSAGES_TO_CACHE$1; + const unsupportedModelBehavior = request.runtime.context.unsupportedModelBehavior ?? middlewareOptions?.unsupportedModelBehavior ?? DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR$1; + if (!enableCaching || !request.model) return handler(request); + if (!(request.model.getName() === "ChatAnthropic" || request.model.getName() === "ConfigurableModel" && request.model._defaultConfig?.modelProvider === "anthropic")) { + const modelName = request.model.getName(); + const baseMessage = `Unsupported model '${request.model.getName() === "ConfigurableModel" ? `${modelName} (${request.model._defaultConfig?.modelProvider})` : modelName}'. Prompt caching requires an Anthropic model`; + if (unsupportedModelBehavior === "raise") throw new PromptCachingMiddlewareError(`${baseMessage} (e.g., 'anthropic:claude-4-0-sonnet').`); + else if (unsupportedModelBehavior === "warn") console.warn(`PromptCachingMiddleware: Skipping caching for ${modelName}. Consider switching to an Anthropic model for caching benefits.`); + return handler(request); + } + if (request.state.messages.length + (request.systemPrompt ? 1 : 0) < minMessagesToCache) return handler(request); + /** + * The cache_control is applied at the final message formatting layer in ChatAnthropic, + * which avoids issues with message content block manipulation during earlier + * processing stages (e.g., streaming response reassembly). + * + * @see https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching + */ + return handler({ + ...request, + modelSettings: { + ...request.modelSettings, + cache_control: { + type: "ephemeral", + ttl + } + } + }); + } + }); +} +//#endregion +//#region node_modules/langchain/dist/agents/middleware/provider/aws/promptCaching.js +var DEFAULT_ENABLE_CACHING = true; +var DEFAULT_TTL = "5m"; +var DEFAULT_MIN_MESSAGES_TO_CACHE = 1; +var DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR = "warn"; +var contextSchema = objectType({ + /** + * Whether to enable prompt caching. + * @default true + */ + enableCaching: booleanType().optional(), + /** + * The time-to-live for the cached prompt. + * @default "5m" + */ + ttl: enumType(["5m", "1h"]).optional(), + /** + * The minimum number of messages required before caching is applied. + * @default 1 + */ + minMessagesToCache: numberType().optional(), + /** + * The behavior to take when an unsupported model is used. + * - "ignore" will ignore the unsupported model and continue without caching. + * - "warn" will warn the user and continue without caching. + * - "raise" will raise an error and stop the agent. + * @default "warn" + */ + unsupportedModelBehavior: enumType([ + "ignore", + "warn", + "raise" + ]).optional() +}); +var BedrockPromptCachingMiddlewareError = class extends Error { + constructor(message) { + super(message); + this.name = "BedrockPromptCachingMiddlewareError"; + } +}; +/** +* Creates a prompt caching middleware for AWS Bedrock Converse models to optimize API usage. +* +* This middleware automatically enables Bedrock's prompt caching when using AWS Bedrock Converse +* models. This can significantly reduce costs for applications with repetitive prompts, long +* system messages, or extensive conversation histories. +* +* ## How It Works +* +* The middleware intercepts model requests and sets a cache control signal that +* `ChatBedrockConverse` translates into Bedrock `cachePoint` breakpoints. Cache points are +* inserted after the system prompt, after the tool definitions, and after the final message, so +* the stable prefix of each request is cached. On subsequent requests with a matching prefix, the +* cached representations are reused, skipping redundant token processing. Exact placement varies +* by model (e.g. Amazon Nova models cache fewer breakpoints and ignore the `"1h"` TTL). +* +* ## Benefits +* +* - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly +* - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed +* - **Better Scalability**: Reduced computational load enables handling more requests +* - **Consistent Performance**: Stable response times for repetitive queries +* +* @param middlewareOptions - Configuration options for the caching behavior +* @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`) +* @param middlewareOptions.ttl - Cache time-to-live: `"5m"` for 5 minutes or `"1h"` for 1 hour (default: `"5m"`) +* @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `1`) +* @param middlewareOptions.unsupportedModelBehavior - The behavior to take when an unsupported model is used (default: `"warn"`) +* +* @returns A middleware instance that can be passed to `createAgent` +* +* @throws {Error} When `unsupportedModelBehavior` is `"raise"` and the model is not a +* cache-capable Bedrock Converse model — either a non-Bedrock provider, or a Bedrock +* Converse model outside the Anthropic Claude / Amazon Nova families. +* +* @example +* Basic usage with default settings +* ```typescript +* import { createAgent } from "langchain"; +* import { bedrockPromptCachingMiddleware } from "langchain"; +* +* const agent = createAgent({ +* model: "bedrock:anthropic.claude-haiku-4-5-20251001-v1:0", +* middleware: [ +* bedrockPromptCachingMiddleware() +* ] +* }); +* ``` +* +* @example +* Custom configuration for longer conversations +* ```typescript +* const cachingMiddleware = bedrockPromptCachingMiddleware({ +* ttl: "1h", // Cache for 1 hour instead of default 5 minutes +* minMessagesToCache: 5 // Only cache after 5 messages +* }); +* +* const agent = createAgent({ +* model: "bedrock:anthropic.claude-haiku-4-5-20251001-v1:0", +* systemPrompt: "You are a helpful assistant with deep knowledge of...", // Long system prompt +* middleware: [cachingMiddleware] +* }); +* ``` +* +* @example +* Conditional caching based on runtime context +* ```typescript +* const agent = createAgent({ +* model: "bedrock:anthropic.claude-haiku-4-5-20251001-v1:0", +* middleware: [ +* bedrockPromptCachingMiddleware({ +* enableCaching: true, +* ttl: "5m" +* }) +* ] +* }); +* +* // Disable caching for specific requests +* await agent.invoke( +* { messages: [new HumanMessage("Process this without caching")] }, +* { +* configurable: { +* middleware_context: { enableCaching: false } +* } +* } +* ); +* ``` +* +* @example +* Optimal setup for customer support chatbot +* ```typescript +* const supportAgent = createAgent({ +* model: "bedrock:anthropic.claude-haiku-4-5-20251001-v1:0", +* systemPrompt: `You are a customer support agent for ACME Corp. +* +* Company policies: +* - Always be polite and professional +* - Refer to knowledge base for product information +* - Escalate billing issues to human agents +* ... (extensive policies and guidelines) +* `, +* tools: [searchKnowledgeBase, createTicket, checkOrderStatus], +* middleware: [ +* bedrockPromptCachingMiddleware({ +* ttl: "1h", // Long TTL for stable system prompt +* minMessagesToCache: 1 // Cache immediately due to large system prompt +* }) +* ] +* }); +* ``` +* +* @remarks +* - **Bedrock Converse Only**: This middleware only applies caching to AWS Bedrock Converse models. Other providers are handled per `unsupportedModelBehavior` +* - **Supported Families**: Bedrock prompt caching is only available on the **Anthropic Claude** and **Amazon Nova** model families. Other Bedrock Converse models (e.g. Mistral, Cohere, Meta) reject cache points at request time, so they are treated as unsupported and routed through `unsupportedModelBehavior` +* - **Automatic Application**: Caching is applied automatically when the message count reaches `minMessagesToCache` +* - **TTL Options**: Only supports "5m" (5 minutes) and "1h" (1 hour) as TTL values; actual support varies by model +* - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications +* +* @see {@link createAgent} for agent creation +* @see {@link https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html} AWS Bedrock prompt caching documentation +* @public +*/ +function bedrockPromptCachingMiddleware(middlewareOptions) { + return createMiddleware({ + name: "BedrockPromptCachingMiddleware", + contextSchema, + wrapModelCall: (request, handler) => { + const enableCaching = request.runtime.context.enableCaching ?? middlewareOptions?.enableCaching ?? DEFAULT_ENABLE_CACHING; + const ttl = request.runtime.context.ttl ?? middlewareOptions?.ttl ?? DEFAULT_TTL; + const minMessagesToCache = request.runtime.context.minMessagesToCache ?? middlewareOptions?.minMessagesToCache ?? DEFAULT_MIN_MESSAGES_TO_CACHE; + const unsupportedModelBehavior = request.runtime.context.unsupportedModelBehavior ?? middlewareOptions?.unsupportedModelBehavior ?? DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR; + if (!enableCaching || !request.model) return handler(request); + const modelName = request.model.getName(); + const isBedrockConverseModel = modelName === "ChatBedrockConverse" || modelName === "ConfigurableModel" && (request.model._defaultConfig?.modelProvider === "bedrock" || request.model._defaultConfig?.modelProvider === "aws"); + const modelId = modelName === "ConfigurableModel" ? request.model._defaultConfig?.model : request.model.model; + if (!(isBedrockConverseModel && typeof modelId === "string" && (modelId.toLowerCase().includes("anthropic.claude") || modelId.toLowerCase().includes("amazon.nova")))) { + const modelInfo = modelName === "ConfigurableModel" ? `${modelName} (${request.model._defaultConfig?.modelProvider})` : modelName; + const baseMessage = isBedrockConverseModel ? `Unsupported model '${modelInfo}'. Bedrock prompt caching is only supported on Anthropic Claude and Amazon Nova models` : `Unsupported model '${modelInfo}'. Prompt caching requires an AWS Bedrock Converse model`; + if (unsupportedModelBehavior === "raise") throw new BedrockPromptCachingMiddlewareError(`${baseMessage} (e.g., 'bedrock:anthropic.claude-haiku-4-5-20251001-v1:0').`); + else if (unsupportedModelBehavior === "warn") console.warn(`BedrockPromptCachingMiddleware: Skipping caching for ${modelName}. Consider switching to an Anthropic Claude or Amazon Nova model for caching benefits.`); + return handler(request); + } + if (request.state.messages.length + (request.systemPrompt ? 1 : 0) < minMessagesToCache) return handler(request); + /** + * The cache_control is applied at the final message formatting layer in + * ChatBedrockConverse (translated into Converse `cachePoint` blocks). + * + * @see https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html + */ + return handler({ + ...request, + modelSettings: { + ...request.modelSettings, + cache_control: { + type: "ephemeral", + ttl + } + } + }); + } + }); +} +//#endregion +//#region node_modules/micromatch/node_modules/picomatch/lib/constants.js +var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var path$7 = __require("path"); + var WIN_SLASH = "\\\\/"; + var WIN_NO_SLASH = `[^${WIN_SLASH}]`; + var DEFAULT_MAX_EXTGLOB_RECURSION = 0; + /** + * Posix glob regex + */ + var DOT_LITERAL = "\\."; + var PLUS_LITERAL = "\\+"; + var QMARK_LITERAL = "\\?"; + var SLASH_LITERAL = "\\/"; + var ONE_CHAR = "(?=.)"; + var QMARK = "[^/]"; + var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; + var START_ANCHOR = `(?:^|${SLASH_LITERAL})`; + var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; + var POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!${START_ANCHOR}${DOTS_SLASH})`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`, + NO_DOTS_SLASH: `(?!${DOTS_SLASH})`, + QMARK_NO_DOT: `[^.${SLASH_LITERAL}]`, + STAR: `${QMARK}*?`, + START_ANCHOR + }; + /** + * Windows glob regex + */ + var WINDOWS_CHARS = { + ...POSIX_CHARS, + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` + }; + module.exports = { + DEFAULT_MAX_EXTGLOB_RECURSION, + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE: { + __proto__: null, + alnum: "a-zA-Z0-9", + alpha: "a-zA-Z", + ascii: "\\x00-\\x7F", + blank: " \\t", + cntrl: "\\x00-\\x1F\\x7F", + digit: "0-9", + graph: "\\x21-\\x7E", + lower: "a-z", + print: "\\x20-\\x7E ", + punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~", + space: " \\t\\r\\n\\v\\f", + upper: "A-Z", + word: "A-Za-z0-9_", + xdigit: "A-Fa-f0-9" + }, + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + REPLACEMENTS: { + __proto__: null, + "***": "*", + "**/**": "**", + "**/**/**": "**" + }, + CHAR_0: 48, + CHAR_9: 57, + CHAR_UPPERCASE_A: 65, + CHAR_LOWERCASE_A: 97, + CHAR_UPPERCASE_Z: 90, + CHAR_LOWERCASE_Z: 122, + CHAR_LEFT_PARENTHESES: 40, + CHAR_RIGHT_PARENTHESES: 41, + CHAR_ASTERISK: 42, + CHAR_AMPERSAND: 38, + CHAR_AT: 64, + CHAR_BACKWARD_SLASH: 92, + CHAR_CARRIAGE_RETURN: 13, + CHAR_CIRCUMFLEX_ACCENT: 94, + CHAR_COLON: 58, + CHAR_COMMA: 44, + CHAR_DOT: 46, + CHAR_DOUBLE_QUOTE: 34, + CHAR_EQUAL: 61, + CHAR_EXCLAMATION_MARK: 33, + CHAR_FORM_FEED: 12, + CHAR_FORWARD_SLASH: 47, + CHAR_GRAVE_ACCENT: 96, + CHAR_HASH: 35, + CHAR_HYPHEN_MINUS: 45, + CHAR_LEFT_ANGLE_BRACKET: 60, + CHAR_LEFT_CURLY_BRACE: 123, + CHAR_LEFT_SQUARE_BRACKET: 91, + CHAR_LINE_FEED: 10, + CHAR_NO_BREAK_SPACE: 160, + CHAR_PERCENT: 37, + CHAR_PLUS: 43, + CHAR_QUESTION_MARK: 63, + CHAR_RIGHT_ANGLE_BRACKET: 62, + CHAR_RIGHT_CURLY_BRACE: 125, + CHAR_RIGHT_SQUARE_BRACKET: 93, + CHAR_SEMICOLON: 59, + CHAR_SINGLE_QUOTE: 39, + CHAR_SPACE: 32, + CHAR_TAB: 9, + CHAR_UNDERSCORE: 95, + CHAR_VERTICAL_LINE: 124, + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, + SEP: path$7.sep, + /** + * Create EXTGLOB_CHARS + */ + extglobChars(chars) { + return { + "!": { + type: "negate", + open: "(?:(?!(?:", + close: `))${chars.STAR})` + }, + "?": { + type: "qmark", + open: "(?:", + close: ")?" + }, + "+": { + type: "plus", + open: "(?:", + close: ")+" + }, + "*": { + type: "star", + open: "(?:", + close: ")*" + }, + "@": { + type: "at", + open: "(?:", + close: ")" + } + }; + }, + /** + * Create GLOB_CHARS + */ + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } + }; +})); +//#endregion +//#region node_modules/micromatch/node_modules/picomatch/lib/utils.js +var require_utils$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var path$6 = __require("path"); + var win32 = process.platform === "win32"; + var { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants(); + exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); + exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str); + exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str); + exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1"); + exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/"); + exports.removeBackslashes = (str) => { + return str.replace(REGEX_REMOVE_BACKSLASH, (match) => { + return match === "\\" ? "" : match; + }); + }; + exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split(".").map(Number); + if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) return true; + return false; + }; + exports.isWindows = (options) => { + if (options && typeof options.windows === "boolean") return options.windows; + return win32 === true || path$6.sep === "\\"; + }; + exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; + }; + exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith("./")) { + output = output.slice(2); + state.prefix = "./"; + } + return output; + }; + exports.wrapOutput = (input, state = {}, options = {}) => { + let output = `${options.contains ? "" : "^"}(?:${input})${options.contains ? "" : "$"}`; + if (state.negated === true) output = `(?:^(?!${output}).*$)`; + return output; + }; +})); +//#endregion +//#region node_modules/micromatch/node_modules/picomatch/lib/scan.js +var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils$1(); + var { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants(); + var isPathSeparator = (code) => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; + }; + var depth = (token) => { + if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1; + }; + /** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + var scan = (input, options) => { + const opts = options || {}; + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { + value: "", + depth: 0, + isGlob: false + }; + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + while (index < length) { + code = advance(); + let next; + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + if (code === CHAR_LEFT_CURLY_BRACE) braceEscaped = true; + continue; + } + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) continue; + break; + } + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) continue; + break; + } + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + if (scanToEnd === true) continue; + break; + } + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { + value: "", + depth: 0, + isGlob: false + }; + if (finished === true) continue; + if (prev === CHAR_DOT && index === start + 1) { + start += 2; + continue; + } + lastIndex = index + 1; + continue; + } + if (opts.noext !== true) { + if ((code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK) === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true; + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) continue; + break; + } + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) continue; + break; + } + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + if (scanToEnd === true) continue; + break; + } + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + if (isGlob === true) { + finished = true; + if (scanToEnd === true) continue; + break; + } + } + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + let base = str; + let prefix = ""; + let glob = ""; + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ""; + glob = str; + } else base = str; + if (base && base !== "" && base !== "/" && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) base = base.slice(0, -1); + } + if (opts.unescape === true) { + if (glob) glob = utils.removeBackslashes(glob); + if (base && backslashes === true) base = utils.removeBackslashes(base); + } + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) tokens.push(token); + state.tokens = tokens; + } + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else tokens[idx].value = value; + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== "") parts.push(value); + prevIndex = i; + } + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + state.slashes = slashes; + state.parts = parts; + } + return state; + }; + module.exports = scan; +})); +//#endregion +//#region node_modules/micromatch/node_modules/picomatch/lib/parse.js +var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var constants = require_constants(); + var utils = require_utils$1(); + /** + * Constants + */ + var { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants; + /** + * Helpers + */ + var expandRange = (args, options) => { + if (typeof options.expandRange === "function") return options.expandRange(...args, options); + args.sort(); + const value = `[${args.join("-")}]`; + try { + new RegExp(value); + } catch (ex) { + return args.map((v) => utils.escapeRegex(v)).join(".."); + } + return value; + }; + /** + * Create the message for a syntax error + */ + var syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; + }; + var splitTopLevel = (input) => { + const parts = []; + let bracket = 0; + let paren = 0; + let quote = 0; + let value = ""; + let escaped = false; + for (const ch of input) { + if (escaped === true) { + value += ch; + escaped = false; + continue; + } + if (ch === "\\") { + value += ch; + escaped = true; + continue; + } + if (ch === "\"") { + quote = quote === 1 ? 0 : 1; + value += ch; + continue; + } + if (quote === 0) { + if (ch === "[") bracket++; + else if (ch === "]" && bracket > 0) bracket--; + else if (bracket === 0) { + if (ch === "(") paren++; + else if (ch === ")" && paren > 0) paren--; + else if (ch === "|" && paren === 0) { + parts.push(value); + value = ""; + continue; + } + } + } + value += ch; + } + parts.push(value); + return parts; + }; + var isPlainBranch = (branch) => { + let escaped = false; + for (const ch of branch) { + if (escaped === true) { + escaped = false; + continue; + } + if (ch === "\\") { + escaped = true; + continue; + } + if (/[?*+@!()[\]{}]/.test(ch)) return false; + } + return true; + }; + var normalizeSimpleBranch = (branch) => { + let value = branch.trim(); + let changed = true; + while (changed === true) { + changed = false; + if (/^@\([^\\()[\]{}|]+\)$/.test(value)) { + value = value.slice(2, -1); + changed = true; + } + } + if (!isPlainBranch(value)) return; + return value.replace(/\\(.)/g, "$1"); + }; + var hasRepeatedCharPrefixOverlap = (branches) => { + const values = branches.map(normalizeSimpleBranch).filter(Boolean); + for (let i = 0; i < values.length; i++) for (let j = i + 1; j < values.length; j++) { + const a = values[i]; + const b = values[j]; + const char = a[0]; + if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) continue; + if (a === b || a.startsWith(b) || b.startsWith(a)) return true; + } + return false; + }; + var parseRepeatedExtglob = (pattern, requireEnd = true) => { + if (pattern[0] !== "+" && pattern[0] !== "*" || pattern[1] !== "(") return; + let bracket = 0; + let paren = 0; + let quote = 0; + let escaped = false; + for (let i = 1; i < pattern.length; i++) { + const ch = pattern[i]; + if (escaped === true) { + escaped = false; + continue; + } + if (ch === "\\") { + escaped = true; + continue; + } + if (ch === "\"") { + quote = quote === 1 ? 0 : 1; + continue; + } + if (quote === 1) continue; + if (ch === "[") { + bracket++; + continue; + } + if (ch === "]" && bracket > 0) { + bracket--; + continue; + } + if (bracket > 0) continue; + if (ch === "(") { + paren++; + continue; + } + if (ch === ")") { + paren--; + if (paren === 0) { + if (requireEnd === true && i !== pattern.length - 1) return; + return { + type: pattern[0], + body: pattern.slice(2, i), + end: i + }; + } + } + } + }; + var getStarExtglobSequenceOutput = (pattern) => { + let index = 0; + const chars = []; + while (index < pattern.length) { + const match = parseRepeatedExtglob(pattern.slice(index), false); + if (!match || match.type !== "*") return; + const branches = splitTopLevel(match.body).map((branch) => branch.trim()); + if (branches.length !== 1) return; + const branch = normalizeSimpleBranch(branches[0]); + if (!branch || branch.length !== 1) return; + chars.push(branch); + index += match.end + 1; + } + if (chars.length < 1) return; + return `${chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch) => utils.escapeRegex(ch)).join("")}]`}*`; + }; + var repeatedExtglobRecursion = (pattern) => { + let depth = 0; + let value = pattern.trim(); + let match = parseRepeatedExtglob(value); + while (match) { + depth++; + value = match.body.trim(); + match = parseRepeatedExtglob(value); + } + return depth; + }; + var analyzeRepeatedExtglob = (body, options) => { + if (options.maxExtglobRecursion === false) return { risky: false }; + const max = typeof options.maxExtglobRecursion === "number" ? options.maxExtglobRecursion : constants.DEFAULT_MAX_EXTGLOB_RECURSION; + const branches = splitTopLevel(body).map((branch) => branch.trim()); + if (branches.length > 1) { + if (branches.some((branch) => branch === "") || branches.some((branch) => /^[*?]+$/.test(branch)) || hasRepeatedCharPrefixOverlap(branches)) return { risky: true }; + } + for (const branch of branches) { + const safeOutput = getStarExtglobSequenceOutput(branch); + if (safeOutput) return { + risky: true, + safeOutput + }; + if (repeatedExtglobRecursion(branch) > max) return { risky: true }; + } + return { risky: false }; + }; + /** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + var parse = (input, options) => { + if (typeof input !== "string") throw new TypeError("Expected a string"); + input = REPLACEMENTS[input] || input; + const opts = { ...options }; + const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + let len = input.length; + if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + const bos = { + type: "bos", + value: "", + output: opts.prepend || "" + }; + const tokens = [bos]; + const capture = opts.capture ? "" : "?:"; + const win32 = utils.isWindows(options); + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; + const globstar = (opts) => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + const nodot = opts.dot ? "" : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + if (opts.capture) star = `(${star})`; + if (typeof opts.noext === "boolean") opts.noextglob = opts.noext; + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: "", + output: "", + prefix: "", + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + input = utils.removePrefix(input, state); + len = input.length; + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + /** + * Tokenizing helpers + */ + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ""; + const remaining = () => input.slice(state.index + 1); + const consume = (value = "", num = 0) => { + state.consumed += value; + state.index += num; + }; + const append = (token) => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + const negate = () => { + let count = 1; + while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) { + advance(); + state.start++; + count++; + } + if (count % 2 === 0) return false; + state.negated = true; + state.start++; + return true; + }; + const increment = (type) => { + state[type]++; + stack.push(type); + }; + const decrement = (type) => { + state[type]--; + stack.pop(); + }; + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + const push = (tok) => { + if (prev.type === "globstar") { + const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"); + const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren"); + if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = "star"; + prev.value = "*"; + prev.output = star; + state.output += prev.output; + } + } + if (extglobs.length && tok.type !== "paren") extglobs[extglobs.length - 1].inner += tok.value; + if (tok.value || tok.output) append(tok); + if (prev && prev.type === "text" && tok.type === "text") { + prev.value += tok.value; + prev.output = (prev.output || "") + tok.value; + return; + } + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + const extglobOpen = (type, value) => { + const token = { + ...EXTGLOB_CHARS[value], + conditions: 1, + inner: "" + }; + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + token.startIndex = state.index; + token.tokensIndex = tokens.length; + const output = (opts.capture ? "(" : "") + token.open; + increment("parens"); + push({ + type, + value, + output: state.output ? "" : ONE_CHAR + }); + push({ + type: "paren", + extglob: true, + value: advance(), + output + }); + extglobs.push(token); + }; + const extglobClose = (token) => { + const literal = input.slice(token.startIndex, state.index + 1); + const analysis = analyzeRepeatedExtglob(input.slice(token.startIndex + 2, state.index), opts); + if ((token.type === "plus" || token.type === "star") && analysis.risky) { + const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0; + const open = tokens[token.tokensIndex]; + open.type = "text"; + open.value = literal; + open.output = safeOutput || utils.escapeRegex(literal); + for (let i = token.tokensIndex + 1; i < tokens.length; i++) { + tokens[i].value = ""; + tokens[i].output = ""; + delete tokens[i].suffix; + } + state.output = token.output + open.output; + state.backtrack = true; + push({ + type: "paren", + extglob: true, + value, + output: "" + }); + decrement("parens"); + return; + } + let output = token.close + (opts.capture ? ")" : ""); + let rest; + if (token.type === "negate") { + let extglobStar = star; + if (token.inner && token.inner.length > 1 && token.inner.includes("/")) extglobStar = globstar(opts); + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) output = token.close = `)$))${extglobStar}`; + if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) output = token.close = `)${parse(rest, { + ...options, + fastpaths: false + }).output})${extglobStar})`; + if (token.prev.type === "bos") state.negatedExtglob = true; + } + push({ + type: "paren", + extglob: true, + value, + output + }); + decrement("parens"); + }; + /** + * Fast paths + */ + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === "\\") { + backslashes = true; + return m; + } + if (first === "?") { + if (esc) return esc + first + (rest ? QMARK.repeat(rest.length) : ""); + if (index === 0) return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ""); + return QMARK.repeat(chars.length); + } + if (first === ".") return DOT_LITERAL.repeat(chars.length); + if (first === "*") { + if (esc) return esc + first + (rest ? star : ""); + return star; + } + return esc ? m : `\\${m}`; + }); + if (backslashes === true) if (opts.unescape === true) output = output.replace(/\\/g, ""); + else output = output.replace(/\\+/g, (m) => { + return m.length % 2 === 0 ? "\\\\" : m ? "\\" : ""; + }); + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + state.output = utils.wrapOutput(output, state, options); + return state; + } + /** + * Tokenize input until we reach end-of-string + */ + while (!eos()) { + value = advance(); + if (value === "\0") continue; + /** + * Escaped characters + */ + if (value === "\\") { + const next = peek(); + if (next === "/" && opts.bash !== true) continue; + if (next === "." || next === ";") continue; + if (!next) { + value += "\\"; + push({ + type: "text", + value + }); + continue; + } + const match = /^\\+/.exec(remaining()); + let slashes = 0; + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) value += "\\"; + } + if (opts.unescape === true) value = advance(); + else value += advance(); + if (state.brackets === 0) { + push({ + type: "text", + value + }); + continue; + } + } + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) { + if (opts.posix !== false && value === ":") { + const inner = prev.value.slice(1); + if (inner.includes("[")) { + prev.posix = true; + if (inner.includes(":")) { + const idx = prev.value.lastIndexOf("["); + const pre = prev.value.slice(0, idx); + const posix = POSIX_REGEX_SOURCE[prev.value.slice(idx + 2)]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + if (!bos.output && tokens.indexOf(prev) === 1) bos.output = ONE_CHAR; + continue; + } + } + } + } + if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") value = `\\${value}`; + if (value === "]" && (prev.value === "[" || prev.value === "[^")) value = `\\${value}`; + if (opts.posix === true && value === "!" && prev.value === "[") value = "^"; + prev.value += value; + append({ value }); + continue; + } + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + if (state.quotes === 1 && value !== "\"") { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + /** + * Double quotes + */ + if (value === "\"") { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) push({ + type: "text", + value + }); + continue; + } + /** + * Parentheses + */ + if (value === "(") { + increment("parens"); + push({ + type: "paren", + value + }); + continue; + } + if (value === ")") { + if (state.parens === 0 && opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "(")); + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + push({ + type: "paren", + value, + output: state.parens ? ")" : "\\)" + }); + decrement("parens"); + continue; + } + /** + * Square brackets + */ + if (value === "[") { + if (opts.nobracket === true || !remaining().includes("]")) { + if (opts.nobracket !== true && opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]")); + value = `\\${value}`; + } else increment("brackets"); + push({ + type: "bracket", + value + }); + continue; + } + if (value === "]") { + if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) { + push({ + type: "text", + value, + output: `\\${value}` + }); + continue; + } + if (state.brackets === 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "[")); + push({ + type: "text", + value, + output: `\\${value}` + }); + continue; + } + decrement("brackets"); + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) value = `/${value}`; + prev.value += value; + append({ value }); + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) continue; + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + /** + * Braces + */ + if (value === "{" && opts.nobrace !== true) { + increment("braces"); + const open = { + type: "brace", + value, + output: "(", + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + braces.push(open); + push(open); + continue; + } + if (value === "}") { + const brace = braces[braces.length - 1]; + if (opts.nobrace === true || !brace) { + push({ + type: "text", + value, + output: value + }); + continue; + } + let output = ")"; + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === "brace") break; + if (arr[i].type !== "dots") range.unshift(arr[i].value); + } + output = expandRange(range, opts); + state.backtrack = true; + } + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = "\\{"; + value = output = "\\}"; + state.output = out; + for (const t of toks) state.output += t.output || t.value; + } + push({ + type: "brace", + value, + output + }); + decrement("braces"); + braces.pop(); + continue; + } + /** + * Pipes + */ + if (value === "|") { + if (extglobs.length > 0) extglobs[extglobs.length - 1].conditions++; + push({ + type: "text", + value + }); + continue; + } + /** + * Commas + */ + if (value === ",") { + let output = value; + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === "braces") { + brace.comma = true; + output = "|"; + } + push({ + type: "comma", + value, + output + }); + continue; + } + /** + * Slashes + */ + if (value === "/") { + if (prev.type === "dot" && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ""; + state.output = ""; + tokens.pop(); + prev = bos; + continue; + } + push({ + type: "slash", + value, + output: SLASH_LITERAL + }); + continue; + } + /** + * Dots + */ + if (value === ".") { + if (state.braces > 0 && prev.type === "dot") { + if (prev.value === ".") prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = "dots"; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") { + push({ + type: "text", + value, + output: DOT_LITERAL + }); + continue; + } + push({ + type: "dot", + value, + output: DOT_LITERAL + }); + continue; + } + /** + * Question marks + */ + if (value === "?") { + if (!(prev && prev.value === "(") && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { + extglobOpen("qmark", value); + continue; + } + if (prev && prev.type === "paren") { + const next = peek(); + let output = value; + if (next === "<" && !utils.supportsLookbehinds()) throw new Error("Node.js v10 or higher is required for regex lookbehinds"); + if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) output = `\\${value}`; + push({ + type: "text", + value, + output + }); + continue; + } + if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) { + push({ + type: "qmark", + value, + output: QMARK_NO_DOT + }); + continue; + } + push({ + type: "qmark", + value, + output: QMARK + }); + continue; + } + /** + * Exclamation + */ + if (value === "!") { + if (opts.noextglob !== true && peek() === "(") { + if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) { + extglobOpen("negate", value); + continue; + } + } + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + /** + * Plus + */ + if (value === "+") { + if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { + extglobOpen("plus", value); + continue; + } + if (prev && prev.value === "(" || opts.regex === false) { + push({ + type: "plus", + value, + output: PLUS_LITERAL + }); + continue; + } + if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) { + push({ + type: "plus", + value + }); + continue; + } + push({ + type: "plus", + value: PLUS_LITERAL + }); + continue; + } + /** + * Plain text + */ + if (value === "@") { + if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { + push({ + type: "at", + extglob: true, + value, + output: "" + }); + continue; + } + push({ + type: "text", + value + }); + continue; + } + /** + * Plain text + */ + if (value !== "*") { + if (value === "$" || value === "^") value = `\\${value}`; + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + push({ + type: "text", + value + }); + continue; + } + /** + * Stars + */ + if (prev && (prev.type === "globstar" || prev.star === true)) { + prev.type = "star"; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen("star", value); + continue; + } + if (prev.type === "star") { + if (opts.noglobstar === true) { + consume(value); + continue; + } + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === "slash" || prior.type === "bos"; + const afterStar = before && (before.type === "star" || before.type === "globstar"); + if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) { + push({ + type: "star", + value, + output: "" + }); + continue; + } + const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"); + const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren"); + if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) { + push({ + type: "star", + value, + output: "" + }); + continue; + } + while (rest.slice(0, 3) === "/**") { + const after = input[state.index + 4]; + if (after && after !== "/") break; + rest = rest.slice(3); + consume("/**", 3); + } + if (prior.type === "bos" && eos()) { + prev.type = "globstar"; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = "globstar"; + prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") { + const end = rest[1] !== void 0 ? "|$" : ""; + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = "globstar"; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + state.output += prior.output + prev.output; + state.globstar = true; + consume(value + advance()); + push({ + type: "slash", + value: "/", + output: "" + }); + continue; + } + if (prior.type === "bos" && rest[0] === "/") { + prev.type = "globstar"; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ + type: "slash", + value: "/", + output: "" + }); + continue; + } + state.output = state.output.slice(0, -prev.output.length); + prev.type = "globstar"; + prev.output = globstar(opts); + prev.value += value; + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + const token = { + type: "star", + value, + output: star + }; + if (opts.bash === true) { + token.output = ".*?"; + if (prev.type === "bos" || prev.type === "slash") token.output = nodot + token.output; + push(token); + continue; + } + if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) { + token.output = value; + push(token); + continue; + } + if (state.index === state.start || prev.type === "slash" || prev.type === "dot") { + if (prev.type === "dot") { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + } else { + state.output += nodot; + prev.output += nodot; + } + if (peek() !== "*") { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + push(token); + } + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]")); + state.output = utils.escapeLast(state.output, "["); + decrement("brackets"); + } + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")")); + state.output = utils.escapeLast(state.output, "("); + decrement("parens"); + } + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}")); + state.output = utils.escapeLast(state.output, "{"); + decrement("braces"); + } + if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) push({ + type: "maybe_slash", + value: "", + output: `${SLASH_LITERAL}?` + }); + if (state.backtrack === true) { + state.output = ""; + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + if (token.suffix) state.output += token.suffix; + } + } + return state; + }; + /** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + parse.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + input = REPLACEMENTS[input] || input; + const win32 = utils.isWindows(options); + const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants.globChars(win32); + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? "" : "?:"; + const state = { + negated: false, + prefix: "" + }; + let star = opts.bash === true ? ".*?" : STAR; + if (opts.capture) star = `(${star})`; + const globstar = (opts) => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + const create = (str) => { + switch (str) { + case "*": return `${nodot}${ONE_CHAR}${star}`; + case ".*": return `${DOT_LITERAL}${ONE_CHAR}${star}`; + case "*.*": return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + case "*/*": return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + case "**": return nodot + globstar(opts); + case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + const source = create(match[1]); + if (!source) return; + return source + DOT_LITERAL + match[2]; + } + } + }; + let source = create(utils.removePrefix(input, state)); + if (source && opts.strictSlashes !== true) source += `${SLASH_LITERAL}?`; + return source; + }; + module.exports = parse; +})); +//#endregion +//#region node_modules/micromatch/node_modules/picomatch/lib/picomatch.js +var require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var path$5 = __require("path"); + var scan = require_scan(); + var parse = require_parse(); + var utils = require_utils$1(); + var constants = require_constants(); + var isObject = (val) => val && typeof val === "object" && !Array.isArray(val); + /** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + var picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map((input) => picomatch(input, options, returnState)); + const arrayMatcher = (str) => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + const isState = isObject(glob) && glob.tokens && glob.input; + if (glob === "" || typeof glob !== "string" && !isState) throw new TypeError("Expected pattern to be a non-empty string"); + const opts = options || {}; + const posix = utils.isWindows(options); + const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); + const state = regex.state; + delete regex.state; + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { + ...options, + ignore: null, + onMatch: null, + onResult: null + }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { + glob, + posix + }); + const result = { + glob, + state, + regex, + posix, + input, + output, + match, + isMatch + }; + if (typeof opts.onResult === "function") opts.onResult(result); + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + if (isIgnored(input)) { + if (typeof opts.onIgnore === "function") opts.onIgnore(result); + result.isMatch = false; + return returnObject ? result : false; + } + if (typeof opts.onMatch === "function") opts.onMatch(result); + return returnObject ? result : true; + }; + if (returnState) matcher.state = state; + return matcher; + }; + /** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + picomatch.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== "string") throw new TypeError("Expected input to be a string"); + if (input === "") return { + isMatch: false, + output: "" + }; + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = match && format ? format(input) : input; + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch.matchBase(input, regex, options, posix); + else match = regex.exec(output); + return { + isMatch: Boolean(match), + match, + output + }; + }; + /** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + return (glob instanceof RegExp ? glob : picomatch.makeRe(glob, options)).test(path$5.basename(input)); + }; + /** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + /** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map((p) => picomatch.parse(p, options)); + return parse(pattern, { + ...options, + fastpaths: false + }); + }; + /** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + picomatch.scan = (input, options) => scan(input, options); + /** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ + picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) return state.output; + const opts = options || {}; + const prepend = opts.contains ? "" : "^"; + const append = opts.contains ? "" : "$"; + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) source = `^(?!${source}).*$`; + const regex = picomatch.toRegex(source, options); + if (returnState === true) regex.state = state; + return regex; + }; + /** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== "string") throw new TypeError("Expected a non-empty string"); + let parsed = { + negated: false, + fastpaths: true + }; + if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) parsed.output = parse.fastpaths(input, options); + if (!parsed.output) parsed = parse(input, options); + return picomatch.compileRe(parsed, options, returnOutput, returnState); + }; + /** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? "i" : "")); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } + }; + /** + * Picomatch constants. + * @return {Object} + */ + picomatch.constants = constants; + /** + * Expose "picomatch" + */ + module.exports = picomatch; +})); +//#endregion +//#region node_modules/micromatch/node_modules/picomatch/index.js +var require_picomatch = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = require_picomatch$1(); +})); +//#endregion +//#region node_modules/micromatch/index.js +var require_micromatch = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var util = __require("util"); + var braces = require_braces(); + var picomatch = require_picomatch(); + var utils = require_utils$1(); + var isEmptyString = (v) => v === "" || v === "./"; + var hasBraces = (v) => { + const index = v.indexOf("{"); + return index > -1 && v.indexOf("}", index) > -1; + }; + /** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} `list` List of strings to match. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + var micromatch = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); + let omit = /* @__PURE__ */ new Set(); + let keep = /* @__PURE__ */ new Set(); + let items = /* @__PURE__ */ new Set(); + let negatives = 0; + let onResult = (state) => { + items.add(state.output); + if (options && options.onResult) options.onResult(state); + }; + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch(String(patterns[i]), { + ...options, + onResult + }, true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; + for (let item of list) { + let matched = isMatch(item, true); + if (!(negated ? !matched.isMatch : matched.isMatch)) continue; + if (negated) omit.add(matched.output); + else { + omit.delete(matched.output); + keep.add(matched.output); + } + } + } + let matches = (negatives === patterns.length ? [...items] : [...keep]).filter((item) => !omit.has(item)); + if (options && matches.length === 0) { + if (options.failglob === true) throw new Error(`No matches found for "${patterns.join(", ")}"`); + if (options.nonull === true || options.nullglob === true) return options.unescape ? patterns.map((p) => p.replace(/\\/g, "")) : patterns; + } + return matches; + }; + /** + * Backwards compatibility + */ + micromatch.match = micromatch; + /** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ + micromatch.matcher = (pattern, options) => picomatch(pattern, options); + /** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `[options]` See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + /** + * Backwards compatibility + */ + micromatch.any = micromatch.isMatch; + /** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + micromatch.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = /* @__PURE__ */ new Set(); + let items = []; + let onResult = (state) => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; + let matches = new Set(micromatch(list, patterns, { + ...options, + onResult + })); + for (let item of items) if (!matches.has(item)) result.add(item); + return [...result]; + }; + /** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any of the patterns matches any part of `str`. + * @api public + */ + micromatch.contains = (str, pattern, options) => { + if (typeof str !== "string") throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + if (Array.isArray(pattern)) return pattern.some((p) => micromatch.contains(str, p, options)); + if (typeof pattern === "string") { + if (isEmptyString(str) || isEmptyString(pattern)) return false; + if (str.includes(pattern) || str.startsWith("./") && str.slice(2).includes(pattern)) return true; + } + return micromatch.isMatch(str, pattern, { + ...options, + contains: true + }); + }; + /** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + micromatch.matchKeys = (obj, patterns, options) => { + if (!utils.isObject(obj)) throw new TypeError("Expected the first argument to be an object"); + let keys = micromatch(Object.keys(obj), patterns, options); + let res = {}; + for (let key of keys) res[key] = obj[key]; + return res; + }; + /** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` + * @api public + */ + micromatch.some = (list, patterns, options) => { + let items = [].concat(list); + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (items.some((item) => isMatch(item))) return true; + } + return false; + }; + /** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` + * @api public + */ + micromatch.every = (list, patterns, options) => { + let items = [].concat(list); + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (!items.every((item) => isMatch(item))) return false; + } + return true; + }; + /** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + micromatch.all = (str, patterns, options) => { + if (typeof str !== "string") throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + return [].concat(patterns).every((p) => picomatch(p, options)(str)); + }; + /** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ + micromatch.capture = (glob, input, options) => { + let posix = utils.isWindows(options); + let match = picomatch.makeRe(String(glob), { + ...options, + capture: true + }).exec(posix ? utils.toPosixSlashes(input) : input); + if (match) return match.slice(1).map((v) => v === void 0 ? "" : v); + }; + /** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + micromatch.makeRe = (...args) => picomatch.makeRe(...args); + /** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + micromatch.scan = (...args) => picomatch.scan(...args); + /** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.parse(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ + micromatch.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) for (let str of braces(String(pattern), options)) res.push(picomatch.parse(str, options)); + return res; + }; + /** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + micromatch.braces = (pattern, options) => { + if (typeof pattern !== "string") throw new TypeError("Expected a string"); + if (options && options.nobrace === true || !hasBraces(pattern)) return [pattern]; + return braces(pattern, options); + }; + /** + * Expand braces + */ + micromatch.braceExpand = (pattern, options) => { + if (typeof pattern !== "string") throw new TypeError("Expected a string"); + return micromatch.braces(pattern, { + ...options, + expand: true + }); + }; + /** + * Expose micromatch + */ + micromatch.hasBraces = hasBraces; + module.exports = micromatch; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/identity.js +var require_identity = /* @__PURE__ */ __commonJSMin(((exports) => { + var ALIAS = Symbol.for("yaml.alias"); + var DOC = Symbol.for("yaml.document"); + var MAP = Symbol.for("yaml.map"); + var PAIR = Symbol.for("yaml.pair"); + var SCALAR = Symbol.for("yaml.scalar"); + var SEQ = Symbol.for("yaml.seq"); + var NODE_TYPE = Symbol.for("yaml.node.type"); + var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; + var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; + var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; + var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; + var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; + var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; + function isCollection(node) { + if (node && typeof node === "object") switch (node[NODE_TYPE]) { + case MAP: + case SEQ: return true; + } + return false; + } + function isNode(node) { + if (node && typeof node === "object") switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: return true; + } + return false; + } + var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + exports.ALIAS = ALIAS; + exports.DOC = DOC; + exports.MAP = MAP; + exports.NODE_TYPE = NODE_TYPE; + exports.PAIR = PAIR; + exports.SCALAR = SCALAR; + exports.SEQ = SEQ; + exports.hasAnchor = hasAnchor; + exports.isAlias = isAlias; + exports.isCollection = isCollection; + exports.isDocument = isDocument; + exports.isMap = isMap; + exports.isNode = isNode; + exports.isPair = isPair; + exports.isScalar = isScalar; + exports.isSeq = isSeq; +})); +//#endregion +//#region node_modules/yaml/dist/visit.js +var require_visit = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var BREAK = Symbol("break visit"); + var SKIP = Symbol("skip children"); + var REMOVE = Symbol("remove node"); + /** + * Apply a visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ + function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + if (visit_(null, node.contents, visitor_, Object.freeze([node])) === REMOVE) node.contents = null; + } else visit_(null, node, visitor_, Object.freeze([])); + } + /** Terminate visit traversal completely */ + visit.BREAK = BREAK; + /** Do not visit the children of the current node */ + visit.SKIP = SKIP; + /** Remove the current node */ + visit.REMOVE = REMOVE; + function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (identity.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") i = ci - 1; + else if (ci === BREAK) return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) return BREAK; + else if (ck === REMOVE) node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) return BREAK; + else if (cv === REMOVE) node.value = null; + } + } + return ctrl; + } + /** + * Apply an async visitor to an AST node or document. + * + * Walks through the tree (depth-first) starting from `node`, calling a + * `visitor` function with three arguments: + * - `key`: For sequence values and map `Pair`, the node's index in the + * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly. + * `null` for the root node. + * - `node`: The current node. + * - `path`: The ancestry of the current node. + * + * The return value of the visitor may be used to control the traversal: + * - `Promise`: Must resolve to one of the following values + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this node, continue with next + * sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current node, then continue with the next one + * - `Node`: Replace the current node, then continue by visiting it + * - `number`: While iterating the items of a sequence or map, set the index + * of the next step. This is useful especially if the index of the current + * node has changed. + * + * If `visitor` is a single function, it will be called with all values + * encountered in the tree, including e.g. `null` values. Alternatively, + * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`, + * `Alias` and `Scalar` node. To define the same visitor function for more than + * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar) + * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most + * specific defined one will be used for each node. + */ + async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + if (await visitAsync_(null, node.contents, visitor_, Object.freeze([node])) === REMOVE) node.contents = null; + } else await visitAsync_(null, node, visitor_, Object.freeze([])); + } + /** Terminate visit traversal completely */ + visitAsync.BREAK = BREAK; + /** Do not visit the children of the current node */ + visitAsync.SKIP = SKIP; + /** Remove the current node */ + visitAsync.REMOVE = REMOVE; + async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (identity.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") i = ci - 1; + else if (ci === BREAK) return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) return BREAK; + else if (ck === REMOVE) node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) return BREAK; + else if (cv === REMOVE) node.value = null; + } + } + return ctrl; + } + function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + return visitor; + } + function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") return visitor(key, node, path); + if (identity.isMap(node)) return visitor.Map?.(key, node, path); + if (identity.isSeq(node)) return visitor.Seq?.(key, node, path); + if (identity.isPair(node)) return visitor.Pair?.(key, node, path); + if (identity.isScalar(node)) return visitor.Scalar?.(key, node, path); + if (identity.isAlias(node)) return visitor.Alias?.(key, node, path); + } + function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (identity.isCollection(parent)) parent.items[key] = node; + else if (identity.isPair(parent)) if (key === "key") parent.key = node; + else parent.value = node; + else if (identity.isDocument(parent)) parent.contents = node; + else { + const pt = identity.isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } + } + exports.visit = visit; + exports.visitAsync = visitAsync; +})); +//#endregion +//#region node_modules/yaml/dist/doc/directives.js +var require_directives = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var visit = require_visit(); + var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" + }; + var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); + var Directives = class Directives { + constructor(yaml, tags) { + /** + * The directives-end/doc-start marker `---`. If `null`, a marker may still be + * included in the document's stringified representation. + */ + this.docStart = null; + /** The doc-end marker `...`. */ + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml); + this.tags = Object.assign({}, Directives.defaultTags, tags); + } + clone() { + const copy = new Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: "1.1" + }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + if (handle === "!") return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) if (tag.startsWith(prefix)) return handle + escapeTagName(tag.substring(prefix.length)); + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) { + const tags = {}; + visit.visit(doc.contents, (_key, node) => { + if (identity.isNode(node) && node.tag) tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join("\n"); + } + }; + Directives.defaultYaml = { + explicit: false, + version: "1.2" + }; + Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + exports.Directives = Directives; +})); +//#endregion +//#region node_modules/yaml/dist/doc/anchors.js +var require_anchors = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var visit = require_visit(); + /** + * Verify that the input string is a valid anchor. + * + * Will throw on errors. + */ + function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const msg = `Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`; + throw new Error(msg); + } + return true; + } + function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit.visit(root, { Value(_key, node) { + if (node.anchor) anchors.add(node.anchor); + } }); + return anchors; + } + /** Find a new anchor name with the given `prefix` and a one-indexed suffix. */ + function findNewAnchor(prefix, exclude) { + for (let i = 1;; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) return name; + } + } + function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) ref.node.anchor = ref.anchor; + else { + const error = /* @__PURE__ */ new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; + } + exports.anchorIsValid = anchorIsValid; + exports.anchorNames = anchorNames; + exports.createNodeAnchors = createNodeAnchors; + exports.findNewAnchor = findNewAnchor; +})); +//#endregion +//#region node_modules/yaml/dist/doc/applyReviver.js +var require_applyReviver = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec, + * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the + * 2021 edition: https://tc39.es/ecma262/#sec-json.parse + * + * Includes extensions for handling Map and Set objects. + */ + function applyReviver(reviver, obj, key, val) { + if (val && typeof val === "object") if (Array.isArray(val)) for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === void 0) delete val[i]; + else if (v1 !== v0) val[i] = v1; + } + else if (val instanceof Map) for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) val.delete(k); + else if (v1 !== v0) val.set(k, v1); + } + else if (val instanceof Set) for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + else for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === void 0) delete val[k]; + else if (v1 !== v0) val[k] = v1; + } + return reviver.call(obj, key, val); + } + exports.applyReviver = applyReviver; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/toJS.js +var require_toJS = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + /** + * Recursively convert any node or its contents to native JavaScript + * + * @param value - The input value + * @param arg - If `value` defines a `toJSON()` method, use this + * as its first argument + * @param ctx - Conversion context, originally set in Document#toJS(). If + * `{ keep: true }` is not set, output should be suitable for JSON + * stringification. + */ + function toJS(value, arg, ctx) { + if (Array.isArray(value)) return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === "function") { + if (!ctx || !identity.hasAnchor(value)) return value.toJSON(arg, ctx); + const data = { + aliasCount: 0, + count: 1, + res: void 0 + }; + ctx.anchors.set(value, data); + ctx.onCreate = (res) => { + data.res = res; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) ctx.onCreate(res); + return res; + } + if (typeof value === "bigint" && !ctx?.keep) return Number(value); + return value; + } + exports.toJS = toJS; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/Node.js +var require_Node = /* @__PURE__ */ __commonJSMin(((exports) => { + var applyReviver = require_applyReviver(); + var identity = require_identity(); + var toJS = require_toJS(); + var NodeBase = class { + constructor(type) { + Object.defineProperty(this, identity.NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) copy.range = this.range.slice(); + return copy; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!identity.isDocument(doc)) throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS.toJS(this, "", ctx); + if (typeof onAnchor === "function") for (const { count, res } of ctx.anchors.values()) onAnchor(res, count); + return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; + } + }; + exports.NodeBase = NodeBase; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/Alias.js +var require_Alias = /* @__PURE__ */ __commonJSMin(((exports) => { + var anchors = require_anchors(); + var visit = require_visit(); + var identity = require_identity(); + var Node = require_Node(); + var toJS = require_toJS(); + var Alias = class extends Node.NodeBase { + constructor(source) { + super(identity.ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { set() { + throw new Error("Alias nodes cannot have tags"); + } }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) nodes = ctx.aliasResolveCache; + else { + nodes = []; + visit.visit(doc, { Node: (_key, node) => { + if (identity.isAlias(node) || identity.hasAnchor(node)) nodes.push(node); + } }); + if (ctx) ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) break; + if (node.anchor === this.source) found = node; + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) return { source: this.source }; + const { anchors, doc, maxAliasCount } = ctx; + const source = this.resolve(doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data = anchors.get(source); + if (!data) { + toJS.toJS(source, null, ctx); + data = anchors.get(source); + } + /* istanbul ignore if */ + if (data?.res === void 0) throw new ReferenceError("This should not happen: Alias anchor was not resolved?"); + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) data.aliasCount = getAliasCount(doc, source, anchors); + if (data.count * data.aliasCount > maxAliasCount) throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack"); + } + return data.res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchors.anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) return `${src} `; + } + return src; + } + }; + function getAliasCount(doc, node, anchors) { + if (identity.isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (identity.isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors); + if (c > count) count = c; + } + return count; + } else if (identity.isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; + } + exports.Alias = Alias; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/Scalar.js +var require_Scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Node = require_Node(); + var toJS = require_toJS(); + var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; + var Scalar = class extends Node.NodeBase { + constructor(value) { + super(identity.SCALAR); + this.value = value; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } + }; + Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; + Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; + Scalar.PLAIN = "PLAIN"; + Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; + Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + exports.Scalar = Scalar; + exports.isScalarValue = isScalarValue; +})); +//#endregion +//#region node_modules/yaml/dist/doc/createNode.js +var require_createNode = /* @__PURE__ */ __commonJSMin(((exports) => { + var Alias = require_Alias(); + var identity = require_identity(); + var Scalar = require_Scalar(); + var defaultTagPrefix = "tag:yaml.org,2002:"; + function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value) && !t.format); + } + function createNode(value, tagName, ctx) { + if (identity.isDocument(value)) value = value.contents; + if (identity.isNode(value)) return value; + if (identity.isPair(value)) { + const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx); + map.items.push(value); + return map; + } + if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) value = value.valueOf(); + const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value && typeof value === "object") { + ref = sourceObjects.get(value); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value)); + return new Alias.Alias(ref.anchor); + } else { + ref = { + anchor: null, + node: null + }; + sourceObjects.set(value, ref); + } + } + if (tagName?.startsWith("!!")) tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + if (!tagObj) { + if (value && typeof value.toJSON === "function") value = value.toJSON(); + if (!value || typeof value !== "object") { + const node = new Scalar.Scalar(value); + if (ref) ref.node = node; + return node; + } + tagObj = value instanceof Map ? schema[identity.MAP] : Symbol.iterator in Object(value) ? schema[identity.SEQ] : schema[identity.MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value); + if (tagName) node.tag = tagName; + else if (!tagObj.default) node.tag = tagObj.tag; + if (ref) ref.node = node; + return node; + } + exports.createNode = createNode; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/Collection.js +var require_Collection = /* @__PURE__ */ __commonJSMin(((exports) => { + var createNode = require_createNode(); + var identity = require_identity(); + var Node = require_Node(); + function collectionFromPath(schema, path, value) { + let v = value; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else v = /* @__PURE__ */ new Map([[k, v]]); + } + return createNode.createNode(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema, + sourceObjects: /* @__PURE__ */ new Map() + }); + } + var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; + var Collection = class extends Node.NodeBase { + constructor(type, schema) { + super(type); + Object.defineProperty(this, "schema", { + value: schema, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema) copy.schema = schema; + copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it); + if (this.range) copy.range = this.range.slice(); + return copy; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value) { + if (isEmptyPath(path)) this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (identity.isCollection(node)) node.addIn(rest, value); + else if (node === void 0 && this.schema) this.set(key, collectionFromPath(this.schema, rest, value)); + else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) return this.delete(key); + const node = this.get(key, true); + if (identity.isCollection(node)) return node.deleteIn(rest); + else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) return !keepScalar && identity.isScalar(node) ? node.value : node; + else return identity.isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!identity.isPair(node)) return false; + const n = node.value; + return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) return this.has(key); + const node = this.get(key, true); + return identity.isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + const [key, ...rest] = path; + if (rest.length === 0) this.set(key, value); + else { + const node = this.get(key, true); + if (identity.isCollection(node)) node.setIn(rest, value); + else if (node === void 0 && this.schema) this.set(key, collectionFromPath(this.schema, rest, value)); + else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + }; + exports.Collection = Collection; + exports.collectionFromPath = collectionFromPath; + exports.isEmptyPath = isEmptyPath; +})); +//#endregion +//#region node_modules/yaml/dist/stringify/stringifyComment.js +var require_stringifyComment = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * Stringifies a comment. + * + * Empty comment lines are left empty, + * lines consisting of a single space are replaced by `#`, + * and all other lines are prefixed with a `#`. + */ + var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); + function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; + } + var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; + exports.indentComment = indentComment; + exports.lineComment = lineComment; + exports.stringifyComment = stringifyComment; +})); +//#endregion +//#region node_modules/yaml/dist/stringify/foldFlowLines.js +var require_foldFlowLines = /* @__PURE__ */ __commonJSMin(((exports) => { + var FOLD_FLOW = "flow"; + var FOLD_BLOCK = "block"; + var FOLD_QUOTED = "quoted"; + /** + * Tries to keep input at up to `lineWidth` characters, splitting only on spaces + * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are + * terminated with `\n` and started with `indent`. + */ + function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) return text; + if (lineWidth < minContentWidth) minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0); + else end = lineWidth - indentAtStart; + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) end = i + endStep; + } + for (let ch; ch = text[i += 1];) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") split = i; + } + if (i >= end) if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else overflow = true; + } + prev = ch; + } + if (overflow && onOverflow) onOverflow(); + if (folds.length === 0) return text; + if (onFold) onFold(); + let res = text.slice(0, folds[0]); + for (let i = 0; i < folds.length; ++i) { + const fold = folds[i]; + const end = folds[i + 1] || text.length; + if (fold === 0) res = `\n${indent}${text.slice(0, end)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; + res += `\n${indent}${text.slice(fold + 1, end)}`; + } + } + return res; + } + /** + * Presumes `i + 1` is at the start of a line + * @returns index of last newline in more-indented block + */ + function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") if (i < start + indent) ch = text[++i]; + else { + do + ch = text[++i]; + while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + return end; + } + exports.FOLD_BLOCK = FOLD_BLOCK; + exports.FOLD_FLOW = FOLD_FLOW; + exports.FOLD_QUOTED = FOLD_QUOTED; + exports.foldFlowLines = foldFlowLines; +})); +//#endregion +//#region node_modules/yaml/dist/stringify/stringifyString.js +var require_stringifyString = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var foldFlowLines = require_foldFlowLines(); + var getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth + }); + var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); + function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) return false; + for (let i = 0, start = 0; i < strLen; ++i) if (str[i] === "\n") { + if (i - start > limit) return true; + start = i + 1; + if (strLen - start <= limit) return false; + } + return true; + } + function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") switch (json[i + 1]) { + case "u": + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str += "\\0"; + break; + case "0007": + str += "\\a"; + break; + case "000b": + str += "\\v"; + break; + case "001b": + str += "\\e"; + break; + case "0085": + str += "\\N"; + break; + case "00a0": + str += "\\_"; + break; + case "2028": + str += "\\L"; + break; + case "2029": + str += "\\P"; + break; + default: if (code.substr(0, 2) === "00") str += "\\x" + code.substr(2); + else str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === "\"" || json.length < minMultiLineLength) i += 1; + else { + str += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== "\"") { + str += "\n"; + i += 2; + } + str += indent; + if (json[i + 2] === " ") str += "\\"; + i += 1; + start = i + 1; + } + break; + default: i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false)); + } + function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); + } + function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) qs = doubleQuotedString; + else { + const hasDouble = value.includes("\""); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) qs = singleQuotedString; + else if (hasSingle && !hasDouble) qs = doubleQuotedString; + else qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); + } + var blockEndNewlines; + try { + blockEndNewlines = /* @__PURE__ */ new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) chomp = "-"; + else if (value === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) onChompKeep(); + } else chomp = ""; + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === "\n") end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === " ") startWithSpace = true; + else if (ch === "\n") startNlPos = startEnd; + else break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + let header = (startWithSpace ? indent ? "2" : "1" : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) onComment(); + } + if (!literal) { + const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) foldOptions.onOverflow = () => { + literalFallback = true; + }; + const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions); + if (!literalFallback) return `>${header}\n${indent}${body}`; + } + value = value.replace(/\n+/g, `$&${indent}`); + return `|${header}\n${indent}${start}${value}${end}`; + } + function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) return quotedString(value, ctx); + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes("\n")) return blockString(item, ctx, onComment, onChompKeep); + if (containsDocumentMarker(value)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) return quotedString(value, ctx); + } + const str = value.replace(/\n+/g, `$&\n${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) return quotedString(value, ctx); + } + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); + } + function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) type = Scalar.Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.Scalar.BLOCK_FOLDED: + case Scalar.Scalar.BLOCK_LITERAL: return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.Scalar.QUOTE_DOUBLE: return doubleQuotedString(ss.value, ctx); + case Scalar.Scalar.QUOTE_SINGLE: return singleQuotedString(ss.value, ctx); + case Scalar.Scalar.PLAIN: return plainString(ss, ctx, onComment, onChompKeep); + default: return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) throw new Error(`Unsupported default string type ${t}`); + } + return res; + } + exports.stringifyString = stringifyString; +})); +//#endregion +//#region node_modules/yaml/dist/stringify/stringify.js +var require_stringify = /* @__PURE__ */ __commonJSMin(((exports) => { + var anchors = require_anchors(); + var identity = require_identity(); + var stringifyComment = require_stringifyComment(); + var stringifyString = require_stringifyString(); + function createStringifyContext(doc, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment.stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", + inFlow, + options: opt + }; + } + function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj; + if (identity.isScalar(item)) { + obj = item.value; + let match = tags.filter((t) => t.identify?.(obj)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj = item; + tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; + } + function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) { + if (!doc.directives) return ""; + const props = []; + const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor; + if (anchor && anchors.anchorIsValid(anchor)) { + anchors$1.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) props.push(doc.directives.tagString(tag)); + return props.join(" "); + } + function stringify(item, ctx, onComment, onChompKeep) { + if (identity.isPair(item)) return item.toString(ctx, onComment, onChompKeep); + if (identity.isAlias(item)) { + if (ctx.doc.directives) return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) throw new TypeError(`Cannot stringify circular structure without alias nodes`); + else { + if (ctx.resolvedAliases) ctx.resolvedAliases.add(item); + else ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) return str; + return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`; + } + exports.createStringifyContext = createStringifyContext; + exports.stringify = stringify; +})); +//#endregion +//#region node_modules/yaml/dist/stringify/stringifyPair.js +var require_stringifyPair = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var stringify = require_stringify(); + var stringifyComment = require_stringifyComment(); + function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = identity.isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) throw new Error("With simple keys, key nodes cannot have comments"); + if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") throw new Error("With simple keys, collection cannot be used as a key value"); + } + let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) onComment(); + return str === "" ? "?" : explicitKey ? `? ${str}` : str; + } + } else if (allNullValues && !simpleKeys || value == null && explicitKey) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + else if (chompKeep && onChompKeep) onChompKeep(); + return str; + } + if (keyCommentDone) keyComment = null; + if (explicitKey) { + if (keyComment) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str}\n${indent}:`; + } else { + str = `${str}:`; + if (keyComment) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (identity.isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === "object") value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && identity.isScalar(value)) ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) ctx.indent = ctx.indent.substring(2); + let valueCommentDone = false; + const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += `\n${stringifyComment.indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) ws = "\n\n"; + } else ws += `\n${ctx.indent}`; + } else if (!explicitKey && identity.isCollection(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") sp0 = valueStr.indexOf(" ", sp0 + 1); + if (sp0 === -1 || nl0 < sp0) hasPropsLine = true; + } + if (!hasPropsLine) ws = `\n${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") ws = ""; + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) onComment(); + } else if (valueComment && !valueCommentDone) str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment)); + else if (chompKeep && onChompKeep) onChompKeep(); + return str; + } + exports.stringifyPair = stringifyPair; +})); +//#endregion +//#region node_modules/yaml/dist/log.js +var require_log = /* @__PURE__ */ __commonJSMin(((exports) => { + var node_process$2 = __require("process"); + function debug(logLevel, ...messages) { + if (logLevel === "debug") console.log(...messages); + } + function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") if (typeof node_process$2.emitWarning === "function") node_process$2.emitWarning(warning); + else console.warn(warning); + } + exports.debug = debug; + exports.warn = warn; +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/merge.js +var require_merge = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var MERGE_KEY = "<<"; + var merge = { + identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), { addToJSMap: addMergeToJSMap }), + stringify: () => MERGE_KEY + }; + var isMergeKey = (ctx, key) => (merge.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default); + function addMergeToJSMap(ctx, map, value) { + const source = resolveAliasValue(ctx, value); + if (identity.isSeq(source)) for (const it of source.items) mergeValue(ctx, map, it); + else if (Array.isArray(source)) for (const it of source) mergeValue(ctx, map, it); + else mergeValue(ctx, map, source); + } + function mergeValue(ctx, map, value) { + const source = resolveAliasValue(ctx, value); + if (!identity.isMap(source)) throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value] of srcMap) if (map instanceof Map) { + if (!map.has(key)) map.set(key, value); + } else if (map instanceof Set) map.add(key); + else if (!Object.prototype.hasOwnProperty.call(map, key)) Object.defineProperty(map, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + return map; + } + function resolveAliasValue(ctx, value) { + return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value; + } + exports.addMergeToJSMap = addMergeToJSMap; + exports.isMergeKey = isMergeKey; + exports.merge = merge; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/addPairToJSMap.js +var require_addPairToJSMap = /* @__PURE__ */ __commonJSMin(((exports) => { + var log = require_log(); + var merge = require_merge(); + var stringify = require_stringify(); + var identity = require_identity(); + var toJS = require_toJS(); + function addPairToJSMap(ctx, map, { key, value }) { + if (identity.isNode(key) && key.addToJSMap) key.addToJSMap(ctx, map, value); + else if (merge.isMergeKey(ctx, key)) merge.addMergeToJSMap(ctx, map, value); + else { + const jsKey = toJS.toJS(key, "", ctx); + if (map instanceof Map) map.set(jsKey, toJS.toJS(value, jsKey, ctx)); + else if (map instanceof Set) map.add(jsKey); + else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS.toJS(value, stringKey, ctx); + if (stringKey in map) Object.defineProperty(map, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else map[stringKey] = jsValue; + } + } + return map; + } + function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) return ""; + if (typeof jsKey !== "object") return String(jsKey); + if (identity.isNode(key) && ctx?.doc) { + const strCtx = stringify.createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) jsonStr = jsonStr.substring(0, 36) + "...\""; + log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); + } + exports.addPairToJSMap = addPairToJSMap; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/Pair.js +var require_Pair = /* @__PURE__ */ __commonJSMin(((exports) => { + var createNode = require_createNode(); + var stringifyPair = require_stringifyPair(); + var addPairToJSMap = require_addPairToJSMap(); + var identity = require_identity(); + function createPair(key, value, ctx) { + return new Pair(createNode.createNode(key, void 0, ctx), createNode.createNode(value, void 0, ctx)); + } + var Pair = class Pair { + constructor(key, value = null) { + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR }); + this.key = key; + this.value = value; + } + clone(schema) { + let { key, value } = this; + if (identity.isNode(key)) key = key.clone(schema); + if (identity.isNode(value)) value = value.clone(schema); + return new Pair(key, value); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap.addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } + }; + exports.Pair = Pair; + exports.createPair = createPair; +})); +//#endregion +//#region node_modules/yaml/dist/stringify/stringifyCollection.js +var require_stringifyCollection = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var stringify = require_stringify(); + var stringifyComment = require_stringifyComment(); + function stringifyCollection(collection, ctx, options) { + return (ctx.inFlow ?? collection.flow ? stringifyFlowCollection : stringifyBlockCollection)(collection, ctx, options); + } + function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + type: null + }); + let chompKeep = false; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (identity.isNode(item)) { + if (!chompKeep && item.spaceBefore) lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) comment = item.comment; + } else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str = stringify.stringify(item, itemCtx, () => comment = null, () => chompKeep = true); + if (comment) str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); + if (chompKeep && comment) chompKeep = false; + lines.push(blockItemPrefix + str); + } + let str; + if (lines.length === 0) str = flowChars.start + flowChars.end; + else { + str = lines[0]; + for (let i = 1; i < lines.length; ++i) { + const line = lines[i]; + str += line ? `\n${indent}${line}` : "\n"; + } + } + if (comment) { + str += "\n" + stringifyComment.indentComment(commentString(comment), indent); + if (onComment) onComment(); + } else if (chompKeep && onChompKeep) onChompKeep(); + return str; + } + function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (identity.isNode(item)) { + if (item.spaceBefore) lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) comment = item.comment; + } else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) reqNewline = true; + } + const iv = identity.isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) comment = iv.comment; + if (iv.commentBefore) reqNewline = true; + } else if (item.value == null && ik?.comment) comment = ik.comment; + } + if (comment) reqNewline = true; + let str = stringify.stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines.length > linesAtValue || str.includes("\n")); + if (i < items.length - 1) str += ","; + else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth); + if (reqNewline) str += ","; + } + if (comment) str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) return start + end; + else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) str += line ? `\n${indentStep}${indent}${line}` : "\n"; + return `${str}\n${indent}${end}`; + } else return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; + } + } + function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = stringifyComment.indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); + } + } + exports.stringifyCollection = stringifyCollection; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/YAMLMap.js +var require_YAMLMap = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyCollection = require_stringifyCollection(); + var addPairToJSMap = require_addPairToJSMap(); + var Collection = require_Collection(); + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + function findPair(items, key) { + const k = identity.isScalar(key) ? key.value : key; + for (const it of items) if (identity.isPair(it)) { + if (it.key === key || it.key === k) return it; + if (identity.isScalar(it.key) && it.key.value === k) return it; + } + } + var YAMLMap = class extends Collection.Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema) { + super(identity.MAP, schema); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map = new this(schema); + const add = (key, value) => { + if (typeof replacer === "function") value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) return; + if (value !== void 0 || keepUndefined) map.items.push(Pair.createPair(key, value, ctx)); + }; + if (obj instanceof Map) for (const [key, value] of obj) add(key, value); + else if (obj && typeof obj === "object") for (const key of Object.keys(obj)) add(key, obj[key]); + if (typeof schema.sortMapEntries === "function") map.items.sort(schema.sortMapEntries); + return map; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (identity.isPair(pair)) _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) _pair = new Pair.Pair(pair, pair?.value); + else _pair = new Pair.Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) throw new Error(`Key ${_pair.key} already set`); + if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value)) prev.value.value = _pair.value; + else prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) this.items.push(_pair); + else this.items.splice(i, 0, _pair); + } else this.items.push(_pair); + } + delete(key) { + const it = findPair(this.items, key); + if (!it) return false; + return this.items.splice(this.items.indexOf(it), 1).length > 0; + } + get(key, keepScalar) { + const node = findPair(this.items, key)?.value; + return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair.Pair(key, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) ctx.onCreate(map); + for (const item of this.items) addPairToJSMap.addPairToJSMap(ctx, map, item); + return map; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + for (const item of this.items) if (!identity.isPair(item)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + if (!ctx.allNullValues && this.hasAllNullValues(false)) ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { + start: "{", + end: "}" + }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } + }; + exports.YAMLMap = YAMLMap; + exports.findPair = findPair; +})); +//#endregion +//#region node_modules/yaml/dist/schema/common/map.js +var require_map = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var YAMLMap = require_YAMLMap(); + exports.map = { + collection: "map", + default: true, + nodeClass: YAMLMap.YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map, onError) { + if (!identity.isMap(map)) onError("Expected a mapping for this tag"); + return map; + }, + createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx) + }; +})); +//#endregion +//#region node_modules/yaml/dist/nodes/YAMLSeq.js +var require_YAMLSeq = /* @__PURE__ */ __commonJSMin(((exports) => { + var createNode = require_createNode(); + var stringifyCollection = require_stringifyCollection(); + var Collection = require_Collection(); + var identity = require_identity(); + var Scalar = require_Scalar(); + var toJS = require_toJS(); + var YAMLSeq = class extends Collection.Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema) { + super(identity.SEQ, schema); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") return false; + return this.items.splice(idx, 1).length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") return void 0; + const it = this.items[idx]; + return !keepScalar && identity.isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== "number") throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (identity.isScalar(prev) && Scalar.isScalarValue(value)) prev.value = value; + else this.items[idx] = value; + } + toJSON(_, ctx) { + const seq = []; + if (ctx?.onCreate) ctx.onCreate(seq); + let i = 0; + for (const item of this.items) seq.push(toJS.toJS(item, String(i++), ctx)); + return seq; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { + start: "[", + end: "]" + }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema, obj, ctx) { + const { replacer } = ctx; + const seq = new this(schema); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === "function") { + const key = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key, it); + } + seq.items.push(createNode.createNode(it, void 0, ctx)); + } + } + return seq; + } + }; + function asItemIndex(key) { + let idx = identity.isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; + } + exports.YAMLSeq = YAMLSeq; +})); +//#endregion +//#region node_modules/yaml/dist/schema/common/seq.js +var require_seq = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var YAMLSeq = require_YAMLSeq(); + exports.seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq.YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq, onError) { + if (!identity.isSeq(seq)) onError("Expected a sequence for this tag"); + return seq; + }, + createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx) + }; +})); +//#endregion +//#region node_modules/yaml/dist/schema/common/string.js +var require_string$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyString = require_stringifyString(); + exports.string = { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString.stringifyString(item, ctx, onComment, onChompKeep); + } + }; +})); +//#endregion +//#region node_modules/yaml/dist/schema/common/null.js +var require_null = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var nullTag = { + identify: (value) => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar.Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr + }; + exports.nullTag = nullTag; +})); +//#endregion +//#region node_modules/yaml/dist/schema/core/bool.js +var require_bool$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var boolTag = { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + if (value === (source[0] === "t" || source[0] === "T")) return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } + }; + exports.boolTag = boolTag; +})); +//#endregion +//#region node_modules/yaml/dist/stringify/stringifyNumber.js +var require_stringifyNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + function stringifyNumber({ format, minFractionDigits, tag, value }) { + if (typeof value === "bigint") return String(value); + const num = typeof value === "number" ? value : Number(value); + if (!isFinite(num)) return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; + let n = Object.is(value, -0) ? "-0" : JSON.stringify(value); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) n += "0"; + } + return n; + } + exports.stringifyNumber = stringifyNumber; +})); +//#endregion +//#region node_modules/yaml/dist/schema/core/float.js +var require_float$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var stringifyNumber = require_stringifyNumber(); + var floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber + }; + var floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); + } + }; + exports.float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str)); + const dot = str.indexOf("."); + if (dot !== -1 && str[str.length - 1] === "0") node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber.stringifyNumber + }; + exports.floatExp = floatExp; + exports.floatNaN = floatNaN; +})); +//#endregion +//#region node_modules/yaml/dist/schema/core/int.js +var require_int$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyNumber = require_stringifyNumber(); + var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); + function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value) && value >= 0) return prefix + value.toString(radix); + return stringifyNumber.stringifyNumber(node); + } + var intOct = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt), + stringify: (node) => intStringify(node, 8, "0o") + }; + var int = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber + }; + var intHex = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") + }; + exports.int = int; + exports.intHex = intHex; + exports.intOct = intOct; +})); +//#endregion +//#region node_modules/yaml/dist/schema/core/schema.js +var require_schema$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + var map = require_map(); + var _null = require_null(); + var seq = require_seq(); + var string = require_string$1(); + var bool = require_bool$1(); + var float = require_float$1(); + var int = require_int$1(); + exports.schema = [ + map.map, + seq.seq, + string.string, + _null.nullTag, + bool.boolTag, + int.intOct, + int.int, + int.intHex, + float.floatNaN, + float.floatExp, + float.float + ]; +})); +//#endregion +//#region node_modules/yaml/dist/schema/json/schema.js +var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var map = require_map(); + var seq = require_seq(); + function intIdentify(value) { + return typeof value === "bigint" || Number.isInteger(value); + } + var stringifyJSON = ({ value }) => JSON.stringify(value); + var jsonScalars = [ + { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify: stringifyJSON + }, + { + identify: (value) => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str) => str === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str) => parseFloat(str), + stringify: stringifyJSON + } + ]; + exports.schema = [map.map, seq.seq].concat(jsonScalars, { + default: true, + tag: "", + test: /^/, + resolve(str, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } + }); +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/binary.js +var require_binary = /* @__PURE__ */ __commonJSMin(((exports) => { + var node_buffer = __require("buffer"); + var Scalar = require_Scalar(); + var stringifyString = require_stringifyString(); + exports.binary = { + identify: (value) => value instanceof Uint8Array, + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof node_buffer.Buffer === "function") return node_buffer.Buffer.from(src, "base64"); + else if (typeof atob === "function") { + const str = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + if (!value) return ""; + const buf = value; + let str; + if (typeof node_buffer.Buffer === "function") str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64"); + else if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) s += String.fromCharCode(buf[i]); + str = btoa(s); + } else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + type ?? (type = Scalar.Scalar.BLOCK_LITERAL); + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) lines[i] = str.substr(o, lineWidth); + str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString.stringifyString({ + comment, + type, + value: str + }, ctx, onComment, onChompKeep); + } + }; +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/pairs.js +var require_pairs = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + var YAMLSeq = require_YAMLSeq(); + function resolvePairs(seq, onError) { + if (identity.isSeq(seq)) for (let i = 0; i < seq.items.length; ++i) { + let item = seq.items[i]; + if (identity.isPair(item)) continue; + else if (identity.isMap(item)) { + if (item.items.length > 1) onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null)); + if (item.commentBefore) pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}\n${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment}\n${cn.comment}` : item.comment; + } + item = pair; + } + seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item); + } + else onError("Expected a sequence for this tag"); + return seq; + } + function createPairs(schema, iterable, ctx) { + const { replacer } = ctx; + const pairs = new YAMLSeq.YAMLSeq(schema); + pairs.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) for (let it of iterable) { + if (typeof replacer === "function") it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) if (it.length === 2) { + key = it[0]; + value = it[1]; + } else throw new TypeError(`Expected [key, value] tuple: ${it}`); + else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } else key = it; + pairs.items.push(Pair.createPair(key, value, ctx)); + } + return pairs; + } + var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs + }; + exports.createPairs = createPairs; + exports.pairs = pairs; + exports.resolvePairs = resolvePairs; +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/omap.js +var require_omap = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var toJS = require_toJS(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var pairs = require_pairs(); + var YAMLOMap = class YAMLOMap extends YAMLSeq.YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) return super.toJSON(_); + const map = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) ctx.onCreate(map); + for (const pair of this.items) { + let key, value; + if (identity.isPair(pair)) { + key = toJS.toJS(pair.key, "", ctx); + value = toJS.toJS(pair.value, key, ctx); + } else key = toJS.toJS(pair, "", ctx); + if (map.has(key)) throw new Error("Ordered maps must not include duplicate keys"); + map.set(key, value); + } + return map; + } + static from(schema, iterable, ctx) { + const pairs$1 = pairs.createPairs(schema, iterable, ctx); + const omap = new this(); + omap.items = pairs$1.items; + return omap; + } + }; + YAMLOMap.tag = "tag:yaml.org,2002:omap"; + var omap = { + collection: "seq", + identify: (value) => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq, onError) { + const pairs$1 = pairs.resolvePairs(seq, onError); + const seenKeys = []; + for (const { key } of pairs$1.items) if (identity.isScalar(key)) if (seenKeys.includes(key.value)) onError(`Ordered maps must not include duplicate keys: ${key.value}`); + else seenKeys.push(key.value); + return Object.assign(new YAMLOMap(), pairs$1); + }, + createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) + }; + exports.YAMLOMap = YAMLOMap; + exports.omap = omap; +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/bool.js +var require_bool = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + function boolStringify({ value, source }, ctx) { + if (source && (value ? trueTag : falseTag).test.test(source)) return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; + } + var trueTag = { + identify: (value) => value === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar.Scalar(true), + stringify: boolStringify + }; + var falseTag = { + identify: (value) => value === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar.Scalar(false), + stringify: boolStringify + }; + exports.falseTag = falseTag; + exports.trueTag = trueTag; +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/float.js +var require_float = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var stringifyNumber = require_stringifyNumber(); + var floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber + }; + var floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, "")), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); + } + }; + exports.float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, ""))); + const dot = str.indexOf("."); + if (dot !== -1) { + const f = str.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber.stringifyNumber + }; + exports.floatExp = floatExp; + exports.floatNaN = floatNaN; +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/int.js +var require_int = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyNumber = require_stringifyNumber(); + var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + function intResolve(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === "-" || sign === "+") offset += 1; + str = str.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n = BigInt(str); + return sign === "-" ? BigInt(-1) * n : n; + } + const n = parseInt(str, radix); + return sign === "-" ? -1 * n : n; + } + function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber.stringifyNumber(node); + } + var intBin = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: (node) => intStringify(node, 2, "0b") + }; + var intOct = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: (node) => intStringify(node, 8, "0") + }; + var int = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber + }; + var intHex = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") + }; + exports.int = int; + exports.intBin = intBin; + exports.intHex = intHex; + exports.intOct = intOct; +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/set.js +var require_set = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var YAMLSet = class YAMLSet extends YAMLMap.YAMLMap { + constructor(schema) { + super(schema); + this.tag = YAMLSet.tag; + } + add(key) { + let pair; + if (identity.isPair(key)) pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) pair = new Pair.Pair(key.key, null); + else pair = new Pair.Pair(key, null); + if (!YAMLMap.findPair(this.items, pair.key)) this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = YAMLMap.findPair(this.items, key); + return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value) { + if (typeof value !== "boolean") throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = YAMLMap.findPair(this.items, key); + if (prev && !value) this.items.splice(this.items.indexOf(prev), 1); + else if (!prev && value) this.items.push(new Pair.Pair(key)); + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) return JSON.stringify(this); + if (this.hasAllNullValues(true)) return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else throw new Error("Set items must all have null values"); + } + static from(schema, iterable, ctx) { + const { replacer } = ctx; + const set = new this(schema); + if (iterable && Symbol.iterator in Object(iterable)) for (let value of iterable) { + if (typeof replacer === "function") value = replacer.call(iterable, value, value); + set.items.push(Pair.createPair(value, null, ctx)); + } + return set; + } + }; + YAMLSet.tag = "tag:yaml.org,2002:set"; + var set = { + collection: "map", + identify: (value) => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), + resolve(map, onError) { + if (identity.isMap(map)) if (map.hasAllNullValues(true)) return Object.assign(new YAMLSet(), map); + else onError("Set items must all have null values"); + else onError("Expected a mapping for this tag"); + return map; + } + }; + exports.YAMLSet = YAMLSet; + exports.set = set; +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/timestamp.js +var require_timestamp = /* @__PURE__ */ __commonJSMin(((exports) => { + var stringifyNumber = require_stringifyNumber(); + /** Internal types handle bigint as number, because TS can't figure it out. */ + function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === "-" || sign === "+" ? str.substring(1) : str; + const num = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res, p) => res * num(60) + num(p), num(0)); + return sign === "-" ? num(-1) * res : res; + } + /** + * hhhh:mm:ss.sss + * + * Internal types handle bigint as number, because TS can't figure it out. + */ + function stringifySexagesimal(node) { + let { value } = node; + let num = (n) => n; + if (typeof value === "bigint") num = (n) => BigInt(n); + else if (isNaN(value) || !isFinite(value)) return stringifyNumber.stringifyNumber(node); + let sign = ""; + if (value < 0) { + sign = "-"; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; + if (value < 60) parts.unshift(0); + else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); + } + var intTime = { + identify: (value) => typeof value === "bigint" || Number.isInteger(value), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal + }; + var floatTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str) => parseSexagesimal(str, false), + stringify: stringifySexagesimal + }; + var timestamp = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str) { + const match = str.match(timestamp.test); + if (!match) throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" + }; + exports.floatTime = floatTime; + exports.intTime = intTime; + exports.timestamp = timestamp; +})); +//#endregion +//#region node_modules/yaml/dist/schema/yaml-1.1/schema.js +var require_schema = /* @__PURE__ */ __commonJSMin(((exports) => { + var map = require_map(); + var _null = require_null(); + var seq = require_seq(); + var string = require_string$1(); + var binary = require_binary(); + var bool = require_bool(); + var float = require_float(); + var int = require_int(); + var merge = require_merge(); + var omap = require_omap(); + var pairs = require_pairs(); + var set = require_set(); + var timestamp = require_timestamp(); + exports.schema = [ + map.map, + seq.seq, + string.string, + _null.nullTag, + bool.trueTag, + bool.falseTag, + int.intBin, + int.intOct, + int.int, + int.intHex, + float.floatNaN, + float.floatExp, + float.float, + binary.binary, + merge.merge, + omap.omap, + pairs.pairs, + set.set, + timestamp.intTime, + timestamp.floatTime, + timestamp.timestamp + ]; +})); +//#endregion +//#region node_modules/yaml/dist/schema/tags.js +var require_tags = /* @__PURE__ */ __commonJSMin(((exports) => { + var map = require_map(); + var _null = require_null(); + var seq = require_seq(); + var string = require_string$1(); + var bool = require_bool$1(); + var float = require_float$1(); + var int = require_int$1(); + var schema = require_schema$2(); + var schema$1 = require_schema$1(); + var binary = require_binary(); + var merge = require_merge(); + var omap = require_omap(); + var pairs = require_pairs(); + var schema$2 = require_schema(); + var set = require_set(); + var timestamp = require_timestamp(); + var schemas = /* @__PURE__ */ new Map([ + ["core", schema.schema], + ["failsafe", [ + map.map, + seq.seq, + string.string + ]], + ["json", schema$1.schema], + ["yaml11", schema$2.schema], + ["yaml-1.1", schema$2.schema] + ]); + var tagsByName = { + binary: binary.binary, + bool: bool.boolTag, + float: float.float, + floatExp: float.floatExp, + floatNaN: float.floatNaN, + floatTime: timestamp.floatTime, + int: int.int, + intHex: int.intHex, + intOct: int.intOct, + intTime: timestamp.intTime, + map: map.map, + merge: merge.merge, + null: _null.nullTag, + omap: omap.omap, + pairs: pairs.pairs, + seq: seq.seq, + set: set.set, + timestamp: timestamp.timestamp + }; + var coreKnownTags = { + "tag:yaml.org,2002:binary": binary.binary, + "tag:yaml.org,2002:merge": merge.merge, + "tag:yaml.org,2002:omap": omap.omap, + "tag:yaml.org,2002:pairs": pairs.pairs, + "tag:yaml.org,2002:set": set.set, + "tag:yaml.org,2002:timestamp": timestamp.timestamp + }; + function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) return addMergeTag && !schemaTags.includes(merge.merge) ? schemaTags.concat(merge.merge) : schemaTags.slice(); + let tags = schemaTags; + if (!tags) if (Array.isArray(customTags)) tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + if (Array.isArray(customTags)) for (const tag of customTags) tags = tags.concat(tag); + else if (typeof customTags === "function") tags = customTags(tags.slice()); + if (addMergeTag) tags = tags.concat(merge.merge); + return tags.reduce((tags, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags.includes(tagObj)) tags.push(tagObj); + return tags; + }, []); + } + exports.coreKnownTags = coreKnownTags; + exports.getTags = getTags; +})); +//#endregion +//#region node_modules/yaml/dist/schema/Schema.js +var require_Schema = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var map = require_map(); + var seq = require_seq(); + var string = require_string$1(); + var tags = require_tags(); + var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; + exports.Schema = class Schema { + constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null; + this.name = typeof schema === "string" && schema || "core"; + this.knownTags = resolveKnownTags ? tags.coreKnownTags : {}; + this.tags = tags.getTags(customTags, this.name, merge); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, identity.MAP, { value: map.map }); + Object.defineProperty(this, identity.SCALAR, { value: string.string }); + Object.defineProperty(this, identity.SEQ, { value: seq.seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; + } + }; +})); +//#endregion +//#region node_modules/yaml/dist/stringify/stringifyDocument.js +var require_stringifyDocument = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var stringify = require_stringify(); + var stringifyComment = require_stringifyComment(); + function stringifyDocument(doc, options) { + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) hasDirectives = true; + } + if (hasDirectives) lines.push("---"); + const ctx = stringify.createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) lines.unshift(""); + const cs = commentString(doc.commentBefore); + lines.unshift(stringifyComment.indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (identity.isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) lines.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(stringifyComment.indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) body += stringifyComment.lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") lines[lines.length - 1] = `--- ${body}`; + else lines.push(body); + } else lines.push(stringify.stringify(doc.contents, ctx)); + if (doc.directives?.docEnd) if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines.push("..."); + lines.push(stringifyComment.indentComment(cs, "")); + } else lines.push(`... ${cs}`); + } else lines.push("..."); + else { + let dc = doc.comment; + if (dc && chompKeep) dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") lines.push(""); + lines.push(stringifyComment.indentComment(commentString(dc), "")); + } + } + return lines.join("\n") + "\n"; + } + exports.stringifyDocument = stringifyDocument; +})); +//#endregion +//#region node_modules/yaml/dist/doc/Document.js +var require_Document = /* @__PURE__ */ __commonJSMin(((exports) => { + var Alias = require_Alias(); + var Collection = require_Collection(); + var identity = require_identity(); + var Pair = require_Pair(); + var toJS = require_toJS(); + var Schema = require_Schema(); + var stringifyDocument = require_stringifyDocument(); + var anchors = require_anchors(); + var applyReviver = require_applyReviver(); + var createNode = require_createNode(); + var directives = require_directives(); + var Document = class Document { + constructor(value, replacer, options) { + /** A comment before this Document */ + this.commentBefore = null; + /** A comment immediately after this Document */ + this.comment = null; + /** Errors encountered during parsing. */ + this.errors = []; + /** Warnings encountered during parsing. */ + this.warnings = []; + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) _replacer = replacer; + else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt; + let { version } = opt; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) version = this.directives.yaml.version; + } else this.directives = new directives.Directives({ version }); + this.setSchema(version, options); + this.contents = value === void 0 ? null : this.createNode(value, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy = Object.create(Document.prototype, { [identity.NODE_TYPE]: { value: identity.DOC } }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents; + if (this.range) copy.range = this.range.slice(); + return copy; + } + /** Adds a value to the document. */ + add(value) { + if (assertCollection(this.contents)) this.contents.add(value); + } + /** Adds a value to the document. */ + addIn(path, value) { + if (assertCollection(this.contents)) this.contents.addIn(path, value); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchors.anchorNames(this); + node.anchor = !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name; + } + return new Alias.Alias(node.anchor); + } + createNode(value, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value = replacer.call({ "": value }, "", value); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, anchorPrefix || "a"); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode.createNode(value, tag, ctx); + if (flow && identity.isCollection(node)) node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value, null, options); + return new Pair.Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (Collection.isEmptyPath(path)) { + if (this.contents == null) return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (Collection.isEmptyPath(path)) return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; + return identity.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return identity.isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (Collection.isEmptyPath(path)) return this.contents !== void 0; + return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value) { + if (this.contents == null) this.contents = Collection.collectionFromPath(this.schema, [key], value); + else if (assertCollection(this.contents)) this.contents.set(key, value); + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + if (Collection.isEmptyPath(path)) this.contents = value; + else if (this.contents == null) this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value); + else if (assertCollection(this.contents)) this.contents.setIn(path, value); + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") version = String(version); + let opt; + switch (version) { + case "1.1": + if (this.directives) this.directives.yaml.version = "1.1"; + else this.directives = new directives.Directives({ version: "1.1" }); + opt = { + resolveKnownTags: false, + schema: "yaml-1.1" + }; + break; + case "1.2": + case "next": + if (this.directives) this.directives.yaml.version = version; + else this.directives = new directives.Directives({ version }); + opt = { + resolveKnownTags: true, + schema: "core" + }; + break; + case null: + if (this.directives) delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) this.schema = options.schema; + else if (opt) this.schema = new Schema.Schema(Object.assign(opt, options)); + else throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS.toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") for (const { count, res } of ctx.anchors.values()) onAnchor(res, count); + return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ + json: true, + jsonArg, + mapAsMap: false, + onAnchor + }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument.stringifyDocument(this, options); + } + }; + function assertCollection(contents) { + if (identity.isCollection(contents)) return true; + throw new Error("Expected a YAML collection as document contents"); + } + exports.Document = Document; +})); +//#endregion +//#region node_modules/yaml/dist/errors.js +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } + }; + var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } + }; + var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } + }; + var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "…" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) lineStr = lineStr.substring(0, 79) + "…"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) prev = prev.substring(0, 79) + "…\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) count = Math.max(1, Math.min(end.col - col, 80 - ci)); + const pointer = " ".repeat(ci) + "^".repeat(count); + error.message += `:\n\n${lineStr}\n${pointer}\n`; + } + }; + exports.YAMLError = YAMLError; + exports.YAMLParseError = YAMLParseError; + exports.YAMLWarning = YAMLWarning; + exports.prettifyError = prettifyError; +})); +//#endregion +//#region node_modules/yaml/dist/compose/resolve-props.js +var require_resolve_props = /* @__PURE__ */ __commonJSMin(((exports) => { + function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) tab = token; + hasSpace = true; + break; + case "comment": { + if (!hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) comment = cb; + else comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) comment += token.source; + else if (!found || indicator !== "seq-item-ind") spaceBefore = true; + } else commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": + if (tag) onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case indicator: + if (anchor || tag) onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": if (flow) { + if (comma) onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; + } + exports.resolveProps = resolveProps; +})); +//#endregion +//#region node_modules/yaml/dist/compose/util-contains-newline.js +var require_util_contains_newline = /* @__PURE__ */ __commonJSMin(((exports) => { + function containsNewline(key) { + if (!key) return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) return true; + if (key.end) { + for (const st of key.end) if (st.type === "newline") return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) if (st.type === "newline") return true; + if (it.sep) { + for (const st of it.sep) if (st.type === "newline") return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) return true; + } + return false; + default: return true; + } + } + exports.containsNewline = containsNewline; +})); +//#endregion +//#region node_modules/yaml/dist/compose/util-flow-indent-check.js +var require_util_flow_indent_check = /* @__PURE__ */ __commonJSMin(((exports) => { + var utilContainsNewline = require_util_contains_newline(); + function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) onError(end, "BAD_INDENT", "Flow end indicator should be more indented than parent", true); + } + } + exports.flowIndentCheck = flowIndentCheck; +})); +//#endregion +//#region node_modules/yaml/dist/compose/util-map-includes.js +var require_util_map_includes = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); + } + exports.mapIncludes = mapIncludes; +})); +//#endregion +//#region node_modules/yaml/dist/compose/resolve-block-map.js +var require_resolve_block_map = /* @__PURE__ */ __commonJSMin(((exports) => { + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var resolveProps = require_resolve_props(); + var utilContainsNewline = require_util_contains_newline(); + var utilFlowIndentCheck = require_util_flow_indent_check(); + var utilMapIncludes = require_util_map_includes(); + var startColMsg = "All mapping items must start at the same column"; + function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) { + const map = new ((tag?.nodeClass) ?? YAMLMap.YAMLMap)(ctx.schema); + if (ctx.atRoot) ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value } = collItem; + const keyProps = resolveProps.resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) if (map.comment) map.comment += "\n" + keyProps.comment; + else map.comment = keyProps.comment; + continue; + } + if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } else if (keyProps.found?.indent !== bm.indent) onError(offset, "BAD_INDENT", startColMsg); + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps.resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value?.type === "block-map" && !valueProps.hasNewline) onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError); + offset = valueNode.range[2]; + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) pair.srcToken = collItem; + map.items.push(pair); + } else { + if (implicitKey) onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) if (keyNode.comment) keyNode.comment += "\n" + valueProps.comment; + else keyNode.comment = valueProps.comment; + const pair = new Pair.Pair(keyNode); + if (ctx.options.keepSourceTokens) pair.srcToken = collItem; + map.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map.range = [ + bm.offset, + offset, + commentEnd ?? offset + ]; + return map; + } + exports.resolveBlockMap = resolveBlockMap; +})); +//#endregion +//#region node_modules/yaml/dist/compose/resolve-block-seq.js +var require_resolve_block_seq = /* @__PURE__ */ __commonJSMin(((exports) => { + var YAMLSeq = require_YAMLSeq(); + var resolveProps = require_resolve_props(); + var utilFlowIndentCheck = require_util_flow_indent_check(); + function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) { + const seq = new ((tag?.nodeClass) ?? YAMLSeq.YAMLSeq)(ctx.schema); + if (ctx.atRoot) ctx.atRoot = false; + if (ctx.atKey) ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps.resolveProps(start, { + indicator: "seq-item-ind", + next: value, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) if (props.anchor || props.tag || value) if (value?.type === "block-seq") onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + else { + commentEnd = props.end; + if (props.comment) seq.comment = props.comment; + continue; + } + const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError); + offset = node.range[2]; + seq.items.push(node); + } + seq.range = [ + bs.offset, + offset, + commentEnd ?? offset + ]; + return seq; + } + exports.resolveBlockSeq = resolveBlockSeq; +})); +//#endregion +//#region node_modules/yaml/dist/compose/resolve-end.js +var require_resolve_end = /* @__PURE__ */ __commonJSMin(((exports) => { + function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) comment = cb; + else comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) sep += source; + hasSpace = true; + break; + default: onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { + comment, + offset + }; + } + exports.resolveEnd = resolveEnd; +})); +//#endregion +//#region node_modules/yaml/dist/compose/resolve-flow-collection.js +var require_resolve_flow_collection = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var resolveEnd = require_resolve_end(); + var resolveProps = require_resolve_props(); + var utilContainsNewline = require_util_contains_newline(); + var utilMapIncludes = require_util_map_includes(); + var blockMsg = "Block collections are not allowed within flow collections"; + var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); + function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) { + const isMap = fc.start.source === "{"; + const fcName = isMap ? "flow map" : "flow sequence"; + const coll = new ((tag?.nodeClass) ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq))(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) ctx.atRoot = false; + if (ctx.atKey) ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value } = collItem; + const props = resolveProps.resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i === 0 && props.comma) onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) if (coll.comment) coll.comment += "\n" + props.comment; + else coll.comment = props.comment; + offset = props.end; + continue; + } + if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key)) onError(key, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + } + if (i === 0) { + if (props.comma) onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) switch (st.type) { + case "comma": + case "space": break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: break loop; + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (identity.isPair(prev)) prev = prev.value ?? prev.key; + if (prev.comment) prev.comment += "\n" + prevItemComment; + else prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap && !sep && !props.found) { + const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value)) onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps.resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap && !props.found && ctx.options.strict) { + if (sep) for (const st of sep) { + if (st === valueProps.found) break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value) if ("source" in value && value.source?.[0] === ":") onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value)) onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) if (keyNode.comment) keyNode.comment += "\n" + valueProps.comment; + else keyNode.comment = valueProps.comment; + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) pair.srcToken = collItem; + if (isMap) { + const map = coll; + if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map.items.push(pair); + } else { + const map = new YAMLMap.YAMLMap(ctx.schema); + map.flow = true; + map.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map.range = [ + keyNode.range[0], + endRange[1], + endRange[2] + ]; + coll.items.push(map); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) if (coll.comment) coll.comment += "\n" + end.comment; + else coll.comment = end.comment; + coll.range = [ + fc.offset, + cePos, + end.offset + ]; + } else coll.range = [ + fc.offset, + cePos, + cePos + ]; + return coll; + } + exports.resolveFlowCollection = resolveFlowCollection; +})); +//#endregion +//#region node_modules/yaml/dist/compose/compose-collection.js +var require_compose_collection = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var resolveBlockMap = require_resolve_block_map(); + var resolveBlockSeq = require_resolve_block_seq(); + var resolveFlowCollection = require_resolve_flow_collection(); + function resolveCollection(CN, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) coll.tag = tagName; + return coll; + } + function composeCollection(CN, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) onError(lastProp, "MISSING_CHAR", "Missing newline after block sequence props"); + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") return resolveCollection(CN, ctx, token, onError, tagName); + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + else onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + return resolveCollection(CN, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = identity.isNode(res) ? res : new Scalar.Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) node.format = tag.format; + return node; + } + exports.composeCollection = composeCollection; +})); +//#endregion +//#region node_modules/yaml/dist/compose/resolve-block-scalar.js +var require_resolve_block_scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) return { + value: "", + type: null, + comment: "", + range: [ + start, + start, + start + ] + }; + const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines.length; + for (let i = lines.length - 1; i >= 0; --i) { + const content = lines[i][1]; + if (content === "" || content === "\r") chompStart = i; + else break; + } + if (chompStart === 0) { + const value = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : ""; + let end = start + header.length; + if (scalar.source) end += scalar.source.length; + return { + value, + type, + comment: header.comment, + range: [ + start, + end, + end + ] + }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) trimIndent = indent.length; + } else { + if (indent.length < trimIndent) onError(offset + indent.length, "MISSING_CHAR", "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"); + if (header.indent === 0) trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) onError(offset, "BAD_INDENT", "Block scalar values in collections must be indented"); + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines.length - 1; i >= chompStart; --i) if (lines[i][0].length > trimIndent) chompStart = i + 1; + let value = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) value += lines[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) content = content.slice(0, -1); + /* istanbul ignore if already caught in lexer */ + if (content && indent.length < trimIndent) { + const message = `Block scalar lines must not be less indented than their ${header.indent ? "explicit indentation indicator" : "first line"}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") sep = "\n"; + else if (!prevMoreIndented && sep === "\n") sep = "\n\n"; + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") if (sep === "\n") value += "\n"; + else sep = "\n"; + else { + value += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": break; + case "+": + for (let i = chompStart; i < lines.length; ++i) value += "\n" + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== "\n") value += "\n"; + break; + default: value += "\n"; + } + const end = start + header.length + scalar.source.length; + return { + value, + type, + comment: header.comment, + range: [ + start, + end, + end + ] + }; + } + function parseBlockScalarHeader({ offset, props }, strict, onError) { + /* istanbul ignore if should not happen */ + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) chomp = ch; + else { + const n = Number(ch); + if (!indent && n) indent = n; + else if (error === -1) error = offset + i; + } + } + if (error !== -1) onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": hasSpace = true; + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + onError(token, "UNEXPECTED_TOKEN", `Unexpected token in block scalar header: ${token.type}`); + const ts = token.source; + if (ts && typeof ts === "string") length += ts.length; + } + } + } + return { + mode, + indent, + chomp, + comment, + length + }; + } + /** @returns Array of lines split up as `[indent, content]` */ + function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const lines = [m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]]; + for (let i = 1; i < split.length; i += 2) lines.push([split[i], split[i + 1]]); + return lines; + } + exports.resolveBlockScalar = resolveBlockScalar; +})); +//#endregion +//#region node_modules/yaml/dist/compose/resolve-flow-scalar.js +var require_resolve_flow_scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var Scalar = require_Scalar(); + var resolveEnd = require_resolve_end(); + function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [ + offset, + offset + source.length, + offset + source.length + ] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError); + return { + value, + type: _type, + comment: re.comment, + range: [ + offset, + valueEnd, + re.offset + ] + }; + } + function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": + badChar = `block scalar indicator ${source[0]}`; + break; + case "@": + case "`": + badChar = `reserved character ${source[0]}`; + break; + } + if (badChar) onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return foldLines(source); + } + function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return foldLines(source.slice(1, -1)).replace(/''/g, "'"); + } + function foldLines(source) { + /** + * The negative lookbehind here and in the `re` RegExp is to + * prevent causing a polynomial search time in certain cases. + * + * The try-catch is for Safari, which doesn't support this yet: + * https://caniuse.com/js-regexp-lookbehind + */ + let first, line; + try { + first = /* @__PURE__ */ new RegExp("(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else res += ch; + } + if (source[source.length - 1] !== "\"" || source.length === 1) onError(source.length, "MISSING_CHAR", "Missing closing \"quote"); + return res; + } + /** + * Fold a single newline into a space, multiple newlines to N - 1 newlines. + * Presumes `source[offset] === '\n'` + */ + function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") break; + if (ch === "\n") fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) fold = " "; + return { + fold, + offset + }; + } + var escapeCodes = { + "0": "\0", + a: "\x07", + b: "\b", + e: "\x1B", + f: "\f", + n: "\n", + r: "\r", + t: " ", + v: "\v", + N: "…", + _: "\xA0", + L: "\u2028", + P: "\u2029", + " ": " ", + "\"": "\"", + "/": "/", + "\\": "\\", + " ": " " + }; + function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const code = cc.length === length && /^[0-9a-fA-F]+$/.test(cc) ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } + } + exports.resolveFlowScalar = resolveFlowScalar; +})); +//#endregion +//#region node_modules/yaml/dist/compose/compose-scalar.js +var require_compose_scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var resolveBlockScalar = require_resolve_block_scalar(); + var resolveFlowScalar = require_resolve_flow_scalar(); + function composeScalar(ctx, token, tagToken, onError) { + const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) tag = ctx.schema[identity.SCALAR]; + else if (tagName) tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); + else if (token.type === "scalar") tag = findScalarTagByTest(ctx, value, token, onError); + else tag = ctx.schema[identity.SCALAR]; + let scalar; + try { + const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar.Scalar(value); + } + scalar.range = range; + scalar.source = value; + if (type) scalar.type = type; + if (tagName) scalar.tag = tagName; + if (tag.format) scalar.format = tag.format; + if (comment) scalar.comment = comment; + return scalar; + } + function findScalarTagByName(schema, value, tagName, tagToken, onError) { + if (tagName === "!") return schema[identity.SCALAR]; + const matchWithTest = []; + for (const tag of schema.tags) if (!tag.collection && tag.tag === tagName) if (tag.default && tag.test) matchWithTest.push(tag); + else return tag; + for (const tag of matchWithTest) if (tag.test?.test(value)) return tag; + const kt = schema.knownTags[tagName]; + if (kt && !kt.collection) { + schema.tags.push(Object.assign({}, kt, { + default: false, + test: void 0 + })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema[identity.SCALAR]; + } + function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) { + const tag = schema.tags.find((tag) => (tag.default === true || atKey && tag.default === "key") && tag.test?.test(value)) || schema[identity.SCALAR]; + if (schema.compat) { + const compat = schema.compat.find((tag) => tag.default && tag.test?.test(value)) ?? schema[identity.SCALAR]; + if (tag.tag !== compat.tag) onError(token, "TAG_RESOLVE_FAILED", `Value may be parsed as either ${directives.tagString(tag.tag)} or ${directives.tagString(compat.tag)}`, true); + } + return tag; + } + exports.composeScalar = composeScalar; +})); +//#endregion +//#region node_modules/yaml/dist/compose/util-empty-scalar-position.js +var require_util_empty_scalar_position = /* @__PURE__ */ __commonJSMin(((exports) => { + function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; + } + exports.emptyScalarPosition = emptyScalarPosition; +})); +//#endregion +//#region node_modules/yaml/dist/compose/compose-node.js +var require_compose_node = /* @__PURE__ */ __commonJSMin(((exports) => { + var Alias = require_Alias(); + var identity = require_identity(); + var composeCollection = require_compose_collection(); + var composeScalar = require_compose_scalar(); + var resolveEnd = require_resolve_end(); + var utilEmptyScalarPosition = require_util_empty_scalar_position(); + var CN = { + composeNode, + composeEmptyNode + }; + function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar.composeScalar(ctx, token, tag, onError); + if (anchor) node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection.composeCollection(CN, ctx, token, props, onError); + if (anchor) node.anchor = anchor.source.substring(1); + } catch (error) { + onError(token, "RESOURCE_EXHAUSTION", error instanceof Error ? error.message : String(error)); + } + break; + default: + onError(token, "UNEXPECTED_TOKEN", token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`); + isSrcToken = false; + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) onError(tag ?? token, "NON_STRING_KEY", "With stringKeys, all keys must be strings"); + if (spaceBefore) node.spaceBefore = true; + if (comment) if (token.type === "scalar" && token.source === "") node.comment = comment; + else node.commentBefore = comment; + if (ctx.options.keepSourceTokens && isSrcToken) node.srcToken = token; + return node; + } + function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar.composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; + } + function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias.Alias(source.substring(1)); + if (alias.source === "") onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [ + offset, + valueEnd, + re.offset + ]; + if (re.comment) alias.comment = re.comment; + return alias; + } + exports.composeEmptyNode = composeEmptyNode; + exports.composeNode = composeNode; +})); +//#endregion +//#region node_modules/yaml/dist/compose/compose-doc.js +var require_compose_doc = /* @__PURE__ */ __commonJSMin(((exports) => { + var Document = require_Document(); + var composeNode = require_compose_node(); + var resolveEnd = require_resolve_end(); + var resolveProps = require_resolve_props(); + function composeDoc(options, directives, { offset, start, value, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document.Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps.resolveProps(start, { + indicator: "doc-start", + next: value ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd.resolveEnd(end, contentEnd, false, onError); + if (re.comment) doc.comment = re.comment; + doc.range = [ + offset, + contentEnd, + re.offset + ]; + return doc; + } + exports.composeDoc = composeDoc; +})); +//#endregion +//#region node_modules/yaml/dist/compose/composer.js +var require_composer = /* @__PURE__ */ __commonJSMin(((exports) => { + var node_process$1 = __require("process"); + var directives = require_directives(); + var Document = require_Document(); + var errors = require_errors(); + var identity = require_identity(); + var composeDoc = require_compose_doc(); + var resolveEnd = require_resolve_end(); + function getErrorPos(src) { + if (typeof src === "number") return [src, src + 1]; + if (Array.isArray(src)) return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; + } + function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") i += 1; + atComment = false; + break; + default: + if (!atComment) afterEmptyLine = true; + atComment = false; + } + } + return { + comment, + afterEmptyLine + }; + } + /** + * Compose a stream of CST nodes into a stream of YAML Documents. + * + * ```ts + * import { Composer, Parser } from 'yaml' + * + * const src: string = ... + * const tokens = new Parser().parse(src) + * const docs = new Composer().compose(tokens) + * ``` + */ + var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) this.warnings.push(new errors.YAMLWarning(pos, code, message)); + else this.errors.push(new errors.YAMLParseError(pos, code, message)); + }; + this.directives = new directives.Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment; + else if (afterEmptyLine || doc.directives.docStart || !dc) doc.commentBefore = comment; + else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (identity.isPair(it)) it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment}\n${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment}\n${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + if (node_process$1.env.LOG_STREAM) console.dir(token, { depth: null }); + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) this.errors.push(error); + else this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", "Unexpected doc-end without preceding document")); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document.Document(void 0, opts); + if (this.atDirectives) this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [ + 0, + endOffset, + endOffset + ]; + this.decorate(doc, false); + yield doc; + } + } + }; + exports.Composer = Composer; +})); +//#endregion +//#region node_modules/yaml/dist/parse/cst-scalar.js +var require_cst_scalar = /* @__PURE__ */ __commonJSMin(((exports) => { + var resolveBlockScalar = require_resolve_block_scalar(); + var resolveFlowScalar = require_resolve_flow_scalar(); + var errors = require_errors(); + var stringifyString = require_stringifyString(); + function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) onError(offset, code, message); + else throw new errors.YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": return resolveFlowScalar.resolveFlowScalar(token, strict, _onError); + case "block-scalar": return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; + } + /** + * Create a new scalar token with `value` + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param value The string representation of the value, which will have its content properly indented. + * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.indent The indent level of the token. + * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value. + * @param context.offset The offset position of the token. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ + function createScalarToken(value, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString.stringifyString({ + type, + value + }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { + blockQuote: true, + lineWidth: -1 + } + }); + const end = context.end ?? [{ + type: "newline", + offset: -1, + indent, + source: "\n" + }]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + const props = [{ + type: "block-scalar-header", + offset, + indent, + source: head + }]; + if (!addEndtoBlockProps(props, end)) props.push({ + type: "newline", + offset: -1, + indent, + source: "\n" + }); + return { + type: "block-scalar", + offset, + indent, + props, + source: body + }; + } + case "\"": return { + type: "double-quoted-scalar", + offset, + indent, + source, + end + }; + case "'": return { + type: "single-quoted-scalar", + offset, + indent, + source, + end + }; + default: return { + type: "scalar", + offset, + indent, + source, + end + }; + } + } + /** + * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have. + * + * Best efforts are made to retain any comments previously associated with the `token`, + * though all contents within a collection's `items` will be overwritten. + * + * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`, + * as this function does not support any schema operations and won't check for such conflicts. + * + * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key. + * @param value The string representation of the value, which will have its content properly indented. + * @param context.afterKey In most cases, values after a key should have an additional level of indentation. + * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value. + * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value. + * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`. + */ + function setScalarValue(token, value, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") indent += 2; + if (!type) switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: type = "PLAIN"; + } + const source = stringifyString.stringifyString({ + type, + value + }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { + blockQuote: true, + lineWidth: -1 + } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case "\"": + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: setFlowScalarValue(token, source, "scalar"); + } + } + function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [{ + type: "block-scalar-header", + offset, + indent, + source: head + }]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) props.push({ + type: "newline", + offset: -1, + indent, + source: "\n" + }); + for (const key of Object.keys(token)) if (key !== "type" && key !== "offset") delete token[key]; + Object.assign(token, { + type: "block-scalar", + indent, + props, + source: body + }); + } + } + /** @returns `true` if last token is a newline */ + function addEndtoBlockProps(props, end) { + if (end) for (const st of end) switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; + } + function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") oa -= token.props[0].source.length; + for (const tok of end) tok.offset += oa; + delete token.props; + Object.assign(token, { + type, + source, + end + }); + break; + } + case "block-map": + case "block-seq": { + const nl = { + type: "newline", + offset: token.offset + source.length, + indent: token.indent, + source: "\n" + }; + delete token.items; + Object.assign(token, { + type, + source, + end: [nl] + }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) if (key !== "type" && key !== "offset") delete token[key]; + Object.assign(token, { + type, + indent, + source, + end + }); + } + } + } + exports.createScalarToken = createScalarToken; + exports.resolveAsScalar = resolveAsScalar; + exports.setScalarValue = setScalarValue; +})); +//#endregion +//#region node_modules/yaml/dist/parse/cst-stringify.js +var require_cst_stringify = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * Stringify a CST document, token, or collection item + * + * Fair warning: This applies no validation whatsoever, and + * simply concatenates the sources in their logical order. + */ + var stringify = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); + function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) res += stringifyItem(item); + for (const st of token.end) res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) for (const st of token.end) res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) for (const st of token.end) res += st.source; + return res; + } + } + } + function stringifyItem({ start, key, sep, value }) { + let res = ""; + for (const st of start) res += st.source; + if (key) res += stringifyToken(key); + if (sep) for (const st of sep) res += st.source; + if (value) res += stringifyToken(value); + return res; + } + exports.stringify = stringify; +})); +//#endregion +//#region node_modules/yaml/dist/parse/cst-visit.js +var require_cst_visit = /* @__PURE__ */ __commonJSMin(((exports) => { + var BREAK = Symbol("break visit"); + var SKIP = Symbol("skip children"); + var REMOVE = Symbol("remove item"); + /** + * Apply a visitor to a CST document or item. + * + * Walks through the tree (depth-first) starting from the root, calling a + * `visitor` function with two arguments when entering each item: + * - `item`: The current item, which included the following members: + * - `start: SourceToken[]` – Source tokens before the key or value, + * possibly including its anchor or tag. + * - `key?: Token | null` – Set for pair values. May then be `null`, if + * the key before the `:` separator is empty. + * - `sep?: SourceToken[]` – Source tokens between the key and the value, + * which should include the `:` map value indicator if `value` is set. + * - `value?: Token` – The value of a sequence item, or of a map pair. + * - `path`: The steps from the root to the current node, as an array of + * `['key' | 'value', number]` tuples. + * + * The return value of the visitor may be used to control the traversal: + * - `undefined` (default): Do nothing and continue + * - `visit.SKIP`: Do not visit the children of this token, continue with + * next sibling + * - `visit.BREAK`: Terminate traversal completely + * - `visit.REMOVE`: Remove the current item, then continue with the next one + * - `number`: Set the index of the next step. This is useful especially if + * the index of the current token has changed. + * - `function`: Define the next visitor for this item. After the original + * visitor is called on item entry, next visitors are called after handling + * a non-empty `key` and when exiting the item. + */ + function visit(cst, visitor) { + if ("type" in cst && cst.type === "document") cst = { + start: cst.start, + value: cst.value + }; + _visit(Object.freeze([]), cst, visitor); + } + /** Terminate visit traversal completely */ + visit.BREAK = BREAK; + /** Do not visit the children of the current item */ + visit.SKIP = SKIP; + /** Remove the current item */ + visit.REMOVE = REMOVE; + /** Find the item at `path` from `cst` as the root */ + visit.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) item = tok.items[index]; + else return void 0; + } + return item; + }; + /** + * Get the immediate parent collection of the item at `path` from `cst` as the root. + * + * Throws an error if the collection is not found, which should never happen if the item itself exists. + */ + visit.parentCollection = (cst, path) => { + const parent = visit.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) return coll; + throw new Error("Parent collection not found"); + }; + function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") i = ci - 1; + else if (ci === BREAK) return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; + } + exports.visit = visit; +})); +//#endregion +//#region node_modules/yaml/dist/parse/cst.js +var require_cst = /* @__PURE__ */ __commonJSMin(((exports) => { + var cstScalar = require_cst_scalar(); + var cstStringify = require_cst_stringify(); + var cstVisit = require_cst_visit(); + /** The byte order mark */ + var BOM = ""; + /** Start of doc-mode */ + var DOCUMENT = ""; + /** Unexpected end of flow-mode */ + var FLOW_END = ""; + /** Next token is a scalar value */ + var SCALAR = ""; + /** @returns `true` if `token` is a flow or block collection */ + var isCollection = (token) => !!token && "items" in token; + /** @returns `true` if `token` is a flow or block scalar; not an alias */ + var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); + /* istanbul ignore next */ + /** Get a printable representation of a lexer token */ + function prettyToken(token) { + switch (token) { + case BOM: return ""; + case DOCUMENT: return ""; + case FLOW_END: return ""; + case SCALAR: return ""; + default: return JSON.stringify(token); + } + } + /** Identify the type of a lexer token. May return `null` for unknown tokens. */ + function tokenType(source) { + switch (source) { + case BOM: return "byte-order-mark"; + case DOCUMENT: return "doc-mode"; + case FLOW_END: return "flow-error-end"; + case SCALAR: return "scalar"; + case "---": return "doc-start"; + case "...": return "doc-end"; + case "": + case "\n": + case "\r\n": return "newline"; + case "-": return "seq-item-ind"; + case "?": return "explicit-key-ind"; + case ":": return "map-value-ind"; + case "{": return "flow-map-start"; + case "}": return "flow-map-end"; + case "[": return "flow-seq-start"; + case "]": return "flow-seq-end"; + case ",": return "comma"; + } + switch (source[0]) { + case " ": + case " ": return "space"; + case "#": return "comment"; + case "%": return "directive-line"; + case "*": return "alias"; + case "&": return "anchor"; + case "!": return "tag"; + case "'": return "single-quoted-scalar"; + case "\"": return "double-quoted-scalar"; + case "|": + case ">": return "block-scalar-header"; + } + return null; + } + exports.createScalarToken = cstScalar.createScalarToken; + exports.resolveAsScalar = cstScalar.resolveAsScalar; + exports.setScalarValue = cstScalar.setScalarValue; + exports.stringify = cstStringify.stringify; + exports.visit = cstVisit.visit; + exports.BOM = BOM; + exports.DOCUMENT = DOCUMENT; + exports.FLOW_END = FLOW_END; + exports.SCALAR = SCALAR; + exports.isCollection = isCollection; + exports.isScalar = isScalar; + exports.prettyToken = prettyToken; + exports.tokenType = tokenType; +})); +//#endregion +//#region node_modules/yaml/dist/parse/lexer.js +var require_lexer = /* @__PURE__ */ __commonJSMin(((exports) => { + var cst = require_cst(); + function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": return true; + default: return false; + } + } + var hexDigits = /* @__PURE__ */ new Set("0123456789ABCDEFabcdef"); + var tagChars = /* @__PURE__ */ new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); + var flowIndicatorChars = /* @__PURE__ */ new Set(",[]{}"); + var invalidAnchorChars = /* @__PURE__ */ new Set(" ,[]{}\n\r "); + var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); + /** + * Splits an input string into lexical tokens, i.e. smaller strings that are + * easily identifiable by `tokens.tokenType()`. + * + * Lexing starts always in a "stream" context. Incomplete input may be buffered + * until a complete token can be emitted. + * + * In addition to slices of the original input, the following control characters + * may also be emitted: + * + * - `\x02` (Start of Text): A document starts with the next token + * - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error) + * - `\x1f` (Unit Separator): Next token is a scalar value + * - `\u{FEFF}` (Byte order mark): Emitted separately outside documents + */ + var Lexer = class { + constructor() { + /** + * Flag indicating whether the end of the current buffer marks the end of + * all input + */ + this.atEnd = false; + /** + * Explicit indent set in block scalar header, as an offset from the current + * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not + * explicitly set. + */ + this.blockScalarIndent = -1; + /** + * Block scalars that include a + (keep) chomping indicator in their header + * include trailing empty lines, which are otherwise excluded from the + * scalar's contents. + */ + this.blockScalarKeep = false; + /** Current input */ + this.buffer = ""; + /** + * Flag noting whether the map value indicator : can immediately follow this + * node within a flow context. + */ + this.flowKey = false; + /** Count of surrounding flow collection levels. */ + this.flowLevel = 0; + /** + * Minimum level of indentation required for next lines to be parsed as a + * part of the current scalar value. + */ + this.indentNext = 0; + /** Indentation level of the current line. */ + this.indentValue = 0; + /** Position of the next \n character. */ + this.lineEndPos = null; + /** Stores the state of the lexer if reaching the end of incpomplete input */ + this.next = null; + /** A pointer to `buffer`; the current position of the lexer. */ + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") return true; + if (ch === "\r") return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": return yield* this.parseStream(); + case "line-start": return yield* this.parseLineStart(); + case "block-start": return yield* this.parseBlockStart(); + case "doc": return yield* this.parseDocument(); + case "flow": return yield* this.parseFlowCollection(); + case "quoted-scalar": return yield* this.parseQuotedScalar(); + case "block-scalar": return yield* this.parseBlockScalar(); + case "plain-scalar": return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) return this.setNext("stream"); + if (line[0] === cst.BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else cs = line.indexOf("#", cs + 1); + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") dirEnd -= 1; + else break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield cst.DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": yield* this.pushCount(line.length - n); + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case "\"": + case "'": return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else sp = 0; + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + if (!(indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"))) { + this.flowLevel = 0; + yield cst.FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case "\"": + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") while (end !== -1 && this.buffer[end + 1] === "'") end = this.buffer.indexOf("'", end + 2); + else while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") n += 1; + if (n % 2 === 0) break; + end = this.buffer.indexOf("\"", end + 1); + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + if (end === -1) { + if (!this.atEnd) return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i = this.pos; ch = this.buffer[i]; ++i) switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i; + indent = 0; + break; + case "\r": { + const next = this.buffer[i + 1]; + if (!next && !this.atEnd) return this.setNext("block-scalar"); + if (next === "\n") break; + } + default: break loop; + } + if (!ch && !this.atEnd) return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) this.indentNext = indent; + else this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) do { + let i = nl - 1; + let ch = this.buffer[i]; + if (ch === "\r") ch = this.buffer[--i]; + const lastChar = i; + while (ch === " ") ch = this.buffer[--i]; + if (ch === "\n" && i >= this.pos && i + 1 + indent > lastChar) nl = i; + else break; + } while (true); + yield cst.SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else end = i; + if (next === "#" || inFlow && flowIndicatorChars.has(next)) break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) break; + end = i; + } + if (!ch && !this.atEnd) return this.setNext("plain-scalar"); + yield cst.SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + case "?": + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) this.indentNext = this.indentValue + 1; + else if (this.flowKey) this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) if (tagChars.has(ch)) ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) ch = this.buffer[i += 3]; + else break; + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") return yield* this.pushCount(2); + else return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do + ch = this.buffer[++i]; + while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } + }; + exports.Lexer = Lexer; +})); +//#endregion +//#region node_modules/yaml/dist/parse/line-counter.js +var require_line_counter = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * Tracks newlines during parsing in order to provide an efficient API for + * determining the one-indexed `{ line, col }` position for any offset + * within the input. + */ + var LineCounter = class { + constructor() { + this.lineStarts = []; + /** + * Should be called in ascending order. Otherwise, call + * `lineCounter.lineStarts.sort()` before calling `linePos()`. + */ + this.addNewLine = (offset) => this.lineStarts.push(offset); + /** + * Performs a binary search and returns the 1-indexed { line, col } + * position of `offset`. If `line === 0`, `addNewLine` has never been + * called or `offset` is before the first known newline. + */ + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) low = mid + 1; + else high = mid; + } + if (this.lineStarts[low] === offset) return { + line: low + 1, + col: 1 + }; + if (low === 0) return { + line: 0, + col: offset + }; + const start = this.lineStarts[low - 1]; + return { + line: low, + col: offset - start + 1 + }; + }; + } + }; + exports.LineCounter = LineCounter; +})); +//#endregion +//#region node_modules/yaml/dist/parse/parser.js +var require_parser = /* @__PURE__ */ __commonJSMin(((exports) => { + var node_process = __require("process"); + var cst = require_cst(); + var lexer = require_lexer(); + function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) if (list[i].type === type) return true; + return false; + } + function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) switch (list[i].type) { + case "space": + case "comment": + case "newline": break; + default: return i; + } + return -1; + } + function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": return true; + default: return false; + } + } + function getPrevProps(parent) { + switch (parent.type) { + case "document": return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: return []; + } + } + /** Note: May modify input array */ + function getFirstKeyStartProps(prev) { + if (prev.length === 0) return []; + let i = prev.length; + loop: while (--i >= 0) switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": break loop; + } + while (prev[++i]?.type === "space"); + return prev.splice(i, prev.length); + } + function arrayPushArray(target, source) { + if (source.length < 1e5) Array.prototype.push.apply(target, source); + else for (let i = 0; i < source.length; ++i) target.push(source[i]); + } + function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) if (it.value.end) arrayPushArray(it.value.end, it.sep); + else it.value.end = it.sep; + else arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } + /** + * A YAML concrete syntax tree (CST) parser + * + * ```ts + * const src: string = ... + * for (const token of new Parser().parse(src)) { + * // token: Token + * } + * ``` + * + * To use the parser with a user-provided lexer: + * + * ```ts + * function* parse(source: string, lexer: Lexer) { + * const parser = new Parser() + * for (const lexeme of lexer.lex(source)) + * yield* parser.next(lexeme) + * yield* parser.end() + * } + * + * const src: string = ... + * const lexer = new Lexer() + * for (const token of parse(src, lexer)) { + * // token: Token + * } + * ``` + */ + var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + /** If true, space and sequence indicators count as indentation */ + this.atNewLine = true; + /** If true, next token is a scalar value */ + this.atScalar = false; + /** Current indentation level */ + this.indent = 0; + /** Current offset since the start of parsing */ + this.offset = 0; + /** On the same line with a block map key */ + this.onKeyLine = false; + /** Top indicates the node that's currently being built */ + this.stack = []; + /** The source of the current token, set in parse() */ + this.source = ""; + /** The type of the current token, set in parse() */ + this.type = ""; + this.lexer = new lexer.Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) yield* this.next(lexeme); + if (!incomplete) yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (node_process.env.LOG_TOKENS) console.log("|", cst.prettyToken(source)); + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = cst.tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ + type: "error", + offset: this.offset, + message, + source + }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": return; + default: this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) yield* this.pop(); + } + get sourceToken() { + return { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) return yield* this.stream(); + switch (top.type) { + case "document": return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": return yield* this.scalar(top); + case "block-scalar": return yield* this.blockScalar(top); + case "block-map": return yield* this.blockMap(top); + case "block-seq": return yield* this.blockSequence(top); + case "flow-collection": return yield* this.flowCollection(top); + case "doc-end": return yield* this.documentEnd(top); + } + /* istanbul ignore next should not happen */ + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + /* istanbul ignore if should not happen */ + if (!token) yield { + type: "error", + offset: this.offset, + source: "", + message: "Tried to pop an empty stack" + }; + else if (this.stack.length === 0) yield token; + else { + const top = this.peek(1); + if (token.type === "block-scalar") token.indent = "indent" in top ? top.indent : 0; + else if (token.type === "flow-collection" && top.type === "document") token.indent = 0; + if (token.type === "flow-collection") fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ + start: [], + key: token, + sep: [] + }); + this.onKeyLine = true; + return; + } else if (it.sep) it.value = token; + else { + Object.assign(it, { + key: token, + sep: [] + }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) top.items.push({ + start: [], + value: token + }); + else it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) top.items.push({ + start: [], + key: token, + sep: [] + }); + else if (it.sep) it.value = token; + else Object.assign(it, { + key: token, + sep: [] + }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") top.end = last.start; + else top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { + type: "directive", + offset: this.offset, + source: this.source + }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else doc.start.push(this.sourceToken); + return; + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) this.stack.push(bv); + else yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const start = getFirstKeyStartProps(getPrevProps(this.peek(2))); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else sep = [this.sourceToken]; + const map = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ + start, + key: scalar, + sep + }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } else yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map) { + const it = map.items[map.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + if ((Array.isArray(end) ? end[end.length - 1] : void 0)?.type === "comment") end?.push(this.sourceToken); + else map.items.push({ start: [this.sourceToken] }); + } else if (it.sep) it.sep.push(this.sourceToken); + else it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) map.items.push({ start: [this.sourceToken] }); + else if (it.sep) it.sep.push(this.sourceToken); + else { + if (this.atIndentedComment(it.start, map.indent)) { + const end = map.items[map.items.length - 2]?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": break; + case "comment": + if (st.indent > map.indent) nl.length = 0; + break; + default: nl.length = 0; + } + } + if (nl.length >= 2) start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) it.sep.push(this.sourceToken); + else it.start.push(this.sourceToken); + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ + start, + explicitKey: true + }); + } else this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start: [this.sourceToken], + explicitKey: true + }] + }); + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) if (!it.sep) if (includesToken(it.start, "newline")) Object.assign(it, { + key: null, + sep: [this.sourceToken] + }); + else { + const start = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + key: null, + sep: [this.sourceToken] + }] + }); + } + else if (it.value) map.items.push({ + start: [], + key: null, + sep: [this.sourceToken] + }); + else if (includesToken(it.sep, "map-value-ind")) this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + key: null, + sep: [this.sourceToken] + }] + }); + else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + key, + sep + }] + }); + } else if (start.length > 0) it.sep = it.sep.concat(start, this.sourceToken); + else it.sep.push(this.sourceToken); + else if (!it.sep) Object.assign(it, { + key: null, + sep: [this.sourceToken] + }); + else if (it.value || atNextItem) map.items.push({ + start, + key: null, + sep: [this.sourceToken] + }); + else if (includesToken(it.sep, "map-value-ind")) this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start: [], + key: null, + sep: [this.sourceToken] + }] + }); + else it.sep.push(this.sourceToken); + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (atNextItem || it.value) { + map.items.push({ + start, + key: fs, + sep: [] + }); + this.onKeyLine = true; + } else if (it.sep) this.stack.push(fs); + else { + Object.assign(it, { + key: fs, + sep: [] + }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) map.items.push({ start }); + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq) { + const it = seq.items[seq.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + if ((Array.isArray(end) ? end[end.length - 1] : void 0)?.type === "comment") end?.push(this.sourceToken); + else seq.items.push({ start: [this.sourceToken] }); + } else it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) seq.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq.indent)) { + const end = seq.items[seq.items.length - 2]?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq.indent) break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq.indent) break; + if (it.value || includesToken(it.start, "seq-item-ind")) seq.items.push({ start: [this.sourceToken] }); + else it.start.push(this.sourceToken); + return; + } + if (this.indent > seq.indent) { + const bv = this.startBlockValue(seq); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) fc.items.push({ start: [this.sourceToken] }); + else it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) fc.items.push({ + start: [], + key: null, + sep: [this.sourceToken] + }); + else if (it.sep) it.sep.push(this.sourceToken); + else Object.assign(it, { + key: null, + sep: [this.sourceToken] + }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) it.sep.push(this.sourceToken); + else it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (!it || it.value) fc.items.push({ + start: [], + key: fs, + sep: [] + }); + else if (it.sep) this.stack.push(fs); + else Object.assign(it, { + key: fs, + sep: [] + }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + /* istanbul ignore else should not happen */ + if (bv) this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const start = getFirstKeyStartProps(getPrevProps(parent)); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ + start, + key: fc, + sep + }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } else yield* this.lineEnd(fc); + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": return this.flowScalar(this.type); + case "block-scalar-header": return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const start = getFirstKeyStartProps(getPrevProps(parent)); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + explicitKey: true + }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const start = getFirstKeyStartProps(getPrevProps(parent)); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ + start, + key: null, + sep: [this.sourceToken] + }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") return false; + if (this.indent <= indent) return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) docEnd.end.push(this.sourceToken); + else docEnd.end = [this.sourceToken]; + if (this.type === "newline") yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": this.onKeyLine = false; + default: + if (token.end) token.end.push(this.sourceToken); + else token.end = [this.sourceToken]; + if (this.type === "newline") yield* this.pop(); + } + } + }; + exports.Parser = Parser; +})); +//#endregion +//#region node_modules/yaml/dist/public-api.js +var require_public_api = /* @__PURE__ */ __commonJSMin(((exports) => { + var composer = require_composer(); + var Document = require_Document(); + var errors = require_errors(); + var log = require_log(); + var identity = require_identity(); + var lineCounter = require_line_counter(); + var parser = require_parser(); + function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + return { + lineCounter: options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null, + prettyErrors + }; + } + /** + * Parse the input as a stream of YAML documents. + * + * Documents should be separated from each other by `...` or `---` marker lines. + * + * @returns If an empty `docs` array is returned, it will be of type + * EmptyStream and contain additional stream information. In + * TypeScript, you should use `'empty' in docs` as a type guard for it. + */ + function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter?.addNewLine); + const composer$1 = new composer.Composer(options); + const docs = Array.from(composer$1.compose(parser$1.parse(source))); + if (prettyErrors && lineCounter) for (const doc of docs) { + doc.errors.forEach(errors.prettifyError(source, lineCounter)); + doc.warnings.forEach(errors.prettifyError(source, lineCounter)); + } + if (docs.length > 0) return docs; + return Object.assign([], { empty: true }, composer$1.streamInfo()); + } + /** Parse an input string into a single YAML.Document */ + function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter?.addNewLine); + const composer$1 = new composer.Composer(options); + let doc = null; + for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) if (!doc) doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(errors.prettifyError(source, lineCounter)); + doc.warnings.forEach(errors.prettifyError(source, lineCounter)); + } + return doc; + } + function parse(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") _reviver = reviver; + else if (options === void 0 && reviver && typeof reviver === "object") options = reviver; + const doc = parseDocument(src, options); + if (!doc) return null; + doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) if (doc.options.logLevel !== "silent") throw doc.errors[0]; + else doc.errors = []; + return doc.toJS(Object.assign({ reviver: _reviver }, options)); + } + function stringify(value, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) _replacer = replacer; + else if (options === void 0 && replacer) options = replacer; + if (typeof options === "string") options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) return void 0; + } + if (identity.isDocument(value) && !_replacer) return value.toString(options); + return new Document.Document(value, _replacer, options).toString(options); + } + exports.parse = parse; + exports.parseAllDocuments = parseAllDocuments; + exports.parseDocument = parseDocument; + exports.stringify = stringify; +})); +//#endregion +//#region node_modules/yaml/dist/index.js +var require_dist = /* @__PURE__ */ __commonJSMin(((exports) => { + var composer = require_composer(); + var Document = require_Document(); + var Schema = require_Schema(); + var errors = require_errors(); + var Alias = require_Alias(); + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + require_cst(); + var lexer = require_lexer(); + var lineCounter = require_line_counter(); + var parser = require_parser(); + var publicApi = require_public_api(); + var visit = require_visit(); + exports.Composer = composer.Composer; + exports.Document = Document.Document; + exports.Schema = Schema.Schema; + exports.YAMLError = errors.YAMLError; + exports.YAMLParseError = errors.YAMLParseError; + exports.YAMLWarning = errors.YAMLWarning; + exports.Alias = Alias.Alias; + exports.isAlias = identity.isAlias; + exports.isCollection = identity.isCollection; + exports.isDocument = identity.isDocument; + exports.isMap = identity.isMap; + exports.isNode = identity.isNode; + exports.isPair = identity.isPair; + exports.isScalar = identity.isScalar; + exports.isSeq = identity.isSeq; + exports.Pair = Pair.Pair; + exports.Scalar = Scalar.Scalar; + exports.YAMLMap = YAMLMap.YAMLMap; + exports.YAMLSeq = YAMLSeq.YAMLSeq; + exports.Lexer = lexer.Lexer; + exports.LineCounter = lineCounter.LineCounter; + exports.Parser = parser.Parser; + exports.parse = publicApi.parse; + exports.parseAllDocuments = publicApi.parseAllDocuments; + exports.parseDocument = publicApi.parseDocument; + exports.stringify = publicApi.stringify; + exports.visit = visit.visit; + exports.visitAsync = visit.visitAsync; +})); +//#endregion +//#region node_modules/langsmith/dist/sandbox/errors.js +var import_micromatch = /* @__PURE__ */ __toESM(require_micromatch(), 1); +var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); +/** +* Custom error classes for the sandbox module. +* +* All sandbox errors extend LangSmithSandboxError for unified error handling. +* The errors are organized by type rather than resource type, with additional +* properties for specific handling when needed. +*/ +/** +* Base exception for sandbox client errors. +*/ +var LangSmithSandboxError = class extends Error { + constructor(message) { + super(message); + this.name = "LangSmithSandboxError"; + } +}; +/** +* Raised when connection to the sandbox server fails. +*/ +var LangSmithSandboxConnectionError = class extends LangSmithSandboxError { + constructor(message) { + super(message); + this.name = "LangSmithSandboxConnectionError"; + } +}; +/** +* Raised when a sandbox operation fails (run, read, write). +*/ +var LangSmithSandboxOperationError = class extends LangSmithSandboxError { + constructor(message, operation, errorType) { + super(message); + /** + * The operation that failed (command, read, write). + */ + Object.defineProperty(this, "operation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Machine-readable error type from the API. + */ + Object.defineProperty(this, "errorType", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = "LangSmithSandboxOperationError"; + this.operation = operation; + this.errorType = errorType; + } + toString() { + if (this.errorType) return `${super.toString()} [${this.errorType}]`; + return super.toString(); + } +}; +//#endregion +//#region node_modules/langsmith/dist/sandbox/command_handle.js +/** +* CommandHandle - async handle to a running command with streaming output +* and auto-reconnect. +* +* Port of Python's AsyncCommandHandle to TypeScript. +*/ +/** +* Async handle to a running command with streaming output and auto-reconnect. +* +* Async iterable, yielding OutputChunk objects (stdout and stderr interleaved +* in arrival order). Access .result after iteration to get the full +* ExecutionResult. +* +* Auto-reconnect behavior: +* - Server hot-reload (1001 Going Away): reconnect immediately +* - Network error / unexpected close: reconnect with exponential backoff +* - User called kill(): do NOT reconnect (propagate error) +* +* @example +* ```typescript +* const handle = await sandbox.run("make build", { timeout: 600, wait: false }); +* +* for await (const chunk of handle) { // auto-reconnects on transient errors +* process.stdout.write(chunk.data); +* } +* +* const result = await handle.result; +* console.log(`Exit code: ${result.exit_code}`); +* ``` +*/ +var CommandHandle = class CommandHandle { + /** @internal */ + constructor(messageStream, control, sandbox, options) { + Object.defineProperty(this, "_stream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_control", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_sandbox", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_commandId", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "_pid", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "_result", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "_stdoutParts", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "_stderrParts", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "_exhausted", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "_lastStdoutOffset", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_lastStderrOffset", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_started", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_onStdout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_onStderr", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this._stream = messageStream; + this._control = control; + this._sandbox = sandbox; + this._lastStdoutOffset = options?.stdoutOffset ?? 0; + this._lastStderrOffset = options?.stderrOffset ?? 0; + this._onStdout = options?.onStdout; + this._onStderr = options?.onStderr; + if (options?.commandId) { + this._commandId = options.commandId; + this._started = true; + } else this._started = false; + } + /** + * Read the 'started' message to populate commandId and pid. + * + * Must be called (and awaited) before iterating for new executions. + */ + async _ensureStarted() { + if (this._started) return; + const firstResult = await this._stream.next(); + if (firstResult.done) throw new LangSmithSandboxOperationError("Command stream ended before 'started' message", "command"); + const firstMsg = firstResult.value; + if (firstMsg.type !== "started") throw new LangSmithSandboxOperationError(`Expected 'started' message, got '${firstMsg.type}'`, "command"); + this._commandId = firstMsg.command_id ?? null; + this._pid = firstMsg.pid ?? null; + this._started = true; + } + /** The server-assigned command ID. Available after _ensureStarted(). */ + get commandId() { + return this._commandId; + } + /** The process ID on the sandbox. Available after _ensureStarted(). */ + get pid() { + return this._pid; + } + /** + * The final execution result. Drains the stream if not already exhausted. + */ + get result() { + return this._getResult(); + } + async _getResult() { + if (this._result === null) for await (const _ of this); + if (this._result === null) throw new LangSmithSandboxOperationError("Command stream ended without exit message", "command"); + return this._result; + } + /** + * Iterate over output chunks from the current stream (no reconnect). + */ + async *_iterStream() { + await this._ensureStarted(); + if (this._exhausted) return; + for await (const msg of this._stream) { + const msgType = msg.type; + if (msgType === "stdout" || msgType === "stderr") { + const chunk = { + stream: msgType, + data: msg.data, + offset: msg.offset ?? 0 + }; + if (msgType === "stdout") this._stdoutParts.push(msg.data); + else this._stderrParts.push(msg.data); + yield chunk; + } else if (msgType === "exit") { + this._result = { + stdout: this._stdoutParts.join(""), + stderr: this._stderrParts.join(""), + exit_code: msg.exit_code ?? -1 + }; + this._exhausted = true; + return; + } + } + throw new LangSmithSandboxConnectionError("Command stream ended without exit message"); + } + /** + * Async iterate over output chunks with auto-reconnect on transient errors. + * + * Reconnect strategy: + * - 1001 Going Away (hot-reload): immediate reconnect, no delay + * - Other SandboxConnectionError: exponential backoff (0.5s, 1s, 2s...) + * - After kill(): no reconnect, error propagates + */ + async *[Symbol.asyncIterator]() { + let reconnectAttempts = 0; + while (true) try { + for await (const chunk of this._iterStream()) { + reconnectAttempts = 0; + if (chunk.stream === "stdout") { + this._lastStdoutOffset = chunk.offset + new TextEncoder().encode(chunk.data).length; + this._onStdout?.(chunk.data); + } else { + this._lastStderrOffset = chunk.offset + new TextEncoder().encode(chunk.data).length; + this._onStderr?.(chunk.data); + } + yield chunk; + } + return; + } catch (e) { + const eName = e != null && typeof e === "object" ? e.name : ""; + if (eName !== "LangSmithSandboxConnectionError" && eName !== "LangSmithSandboxServerReloadError") throw e; + if (this._control && this._control.killed) throw e; + reconnectAttempts++; + if (reconnectAttempts > CommandHandle.MAX_AUTO_RECONNECTS) throw new LangSmithSandboxConnectionError(`Lost connection ${reconnectAttempts} times in succession, giving up`); + if (!(eName === "LangSmithSandboxServerReloadError")) { + const delay = Math.min(CommandHandle.BACKOFF_BASE * 2 ** (reconnectAttempts - 1), CommandHandle.BACKOFF_MAX); + await new Promise((r) => setTimeout(r, delay * 1e3)); + } + if (this._commandId === null) throw e; + const newHandle = await this._sandbox.reconnect(this._commandId, { + stdoutOffset: this._lastStdoutOffset, + stderrOffset: this._lastStderrOffset + }); + this._stream = newHandle._stream; + this._control = newHandle._control; + this._exhausted = false; + } + } + /** + * Send a kill signal to the running command (SIGKILL). + * + * The server kills the entire process group. The stream will + * subsequently yield an exit message with a non-zero exit code. + */ + kill() { + if (this._control) this._control.sendKill(); + } + /** + * Write data to the command's stdin. + */ + sendInput(data) { + if (this._control) this._control.sendInput(data); + } + /** Last known stdout byte offset (for manual reconnection). */ + get lastStdoutOffset() { + return this._lastStdoutOffset; + } + /** Last known stderr byte offset (for manual reconnection). */ + get lastStderrOffset() { + return this._lastStderrOffset; + } + /** + * Reconnect to this command from the last known offsets. + * + * Returns a new CommandHandle that resumes output from where this one + * left off. + */ + async reconnect() { + if (this._commandId === null) throw new LangSmithSandboxOperationError("Cannot reconnect: command ID not available", "reconnect"); + return this._sandbox.reconnect(this._commandId, { + stdoutOffset: this._lastStdoutOffset, + stderrOffset: this._lastStderrOffset + }); + } +}; +Object.defineProperty(CommandHandle, "MAX_AUTO_RECONNECTS", { + enumerable: true, + configurable: true, + writable: true, + value: 5 +}); +Object.defineProperty(CommandHandle, "BACKOFF_BASE", { + enumerable: true, + configurable: true, + writable: true, + value: .5 +}); +Object.defineProperty(CommandHandle, "BACKOFF_MAX", { + enumerable: true, + configurable: true, + writable: true, + value: 8 +}); +//#endregion +//#region node_modules/deepagents/dist/langsmith-DgbmWtWj.js +/** +* Shared utility functions for memory backend implementations. +* +* This module contains both user-facing string formatters and structured +* helpers used by backends and the composite router. Structured helpers +* enable composition without fragile string parsing. +*/ +var EMPTY_CONTENT_WARNING = "System reminder: File exists but has empty contents"; +var MAX_LINE_LENGTH = 5e3; +var TOOL_RESULT_TOKEN_LIMIT = 2e4; +var TRUNCATION_GUIDANCE = "... [results truncated, try being more specific with your parameters]"; +var MIME_TYPES = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", + ".svg": "image/svg+xml", + ".heic": "image/heic", + ".heif": "image/heif", + ".mp3": "audio/mpeg", + ".wav": "audio/wav", + ".aiff": "audio/aiff", + ".aac": "audio/aac", + ".ogg": "audio/ogg", + ".flac": "audio/flac", + ".mp4": "video/mp4", + ".webm": "video/webm", + ".mpeg": "video/mpeg", + ".mov": "video/quicktime", + ".avi": "video/x-msvideo", + ".flv": "video/x-flv", + ".mpg": "video/mpeg", + ".wmv": "video/x-ms-wmv", + ".3gpp": "video/3gpp", + ".pdf": "application/pdf", + ".ppt": "application/vnd.ms-powerpoint", + ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + ".txt": "text/plain", + ".md": "text/markdown", + ".markdown": "text/markdown", + ".html": "text/html", + ".htm": "text/html", + ".css": "text/css", + ".csv": "text/csv", + ".xml": "text/xml", + ".json": "application/json", + ".js": "application/javascript", + ".mjs": "application/javascript", + ".cjs": "application/javascript", + ".ts": "text/plain", + ".tsx": "text/plain", + ".jsx": "text/plain", + ".py": "text/plain", + ".rb": "text/plain", + ".java": "text/plain", + ".c": "text/plain", + ".cpp": "text/plain", + ".h": "text/plain", + ".hpp": "text/plain", + ".go": "text/plain", + ".rs": "text/plain", + ".sh": "text/plain", + ".bash": "text/plain", + ".zsh": "text/plain", + ".yaml": "text/plain", + ".yml": "text/plain", + ".toml": "text/plain", + ".ini": "text/plain", + ".cfg": "text/plain", + ".conf": "text/plain", + ".env": "text/plain", + ".log": "text/plain", + ".sql": "text/plain", + ".graphql": "text/plain", + ".proto": "text/plain", + ".r": "text/plain", + ".swift": "text/plain", + ".kt": "text/plain", + ".kts": "text/plain", + ".scala": "text/plain", + ".dart": "text/plain", + ".lua": "text/plain", + ".pl": "text/plain", + ".pm": "text/plain", + ".php": "text/plain", + ".ex": "text/plain", + ".exs": "text/plain", + ".erl": "text/plain", + ".hs": "text/plain", + ".ml": "text/plain", + ".mli": "text/plain", + ".vue": "text/plain", + ".svelte": "text/plain", + ".astro": "text/plain", + ".tf": "text/plain", + ".cmake": "text/plain", + ".makefile": "text/plain", + ".dockerfile": "text/plain", + ".gitignore": "text/plain", + ".dockerignore": "text/plain", + ".editorconfig": "text/plain" +}; +function basename(filePath) { + const normalized = filePath.replace(/\\/g, "/"); + const slashIdx = normalized.lastIndexOf("/"); + return slashIdx === -1 ? normalized : normalized.slice(slashIdx + 1); +} +function extname(filePath) { + const name = basename(filePath); + const dotIdx = name.lastIndexOf("."); + return dotIdx <= 0 ? "" : name.slice(dotIdx); +} +/** +* Sanitize tool_call_id to prevent path traversal and separator issues. +* +* Replaces dangerous characters (., /, \) with underscores. +*/ +function sanitizeToolCallId(toolCallId) { + return toolCallId.replace(/\./g, "_").replace(/\//g, "_").replace(/\\/g, "_"); +} +/** +* Format file content with line numbers (cat -n style). +* +* Chunks lines longer than MAX_LINE_LENGTH with continuation markers (e.g., 5.1, 5.2). +* +* @param content - File content as string or list of lines +* @param startLine - Starting line number (default: 1) +* @returns Formatted content with line numbers and continuation markers +*/ +function formatContentWithLineNumbers(content, startLine = 1) { + let lines; + if (typeof content === "string") { + lines = content.split("\n"); + if (lines.length > 0 && lines[lines.length - 1] === "") lines = lines.slice(0, -1); + } else lines = content; + const resultLines = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const lineNum = i + startLine; + if (line.length <= 5e3) resultLines.push(`${lineNum.toString().padStart(6)}\t${line}`); + else { + const numChunks = Math.ceil(line.length / MAX_LINE_LENGTH); + for (let chunkIdx = 0; chunkIdx < numChunks; chunkIdx++) { + const start = chunkIdx * MAX_LINE_LENGTH; + const end = Math.min(start + MAX_LINE_LENGTH, line.length); + const chunk = line.substring(start, end); + if (chunkIdx === 0) resultLines.push(`${lineNum.toString().padStart(6)}\t${chunk}`); + else { + const continuationMarker = `${lineNum}.${chunkIdx}`; + resultLines.push(`${continuationMarker.padStart(6)}\t${chunk}`); + } + } + } + } + return resultLines.join("\n"); +} +/** +* Check if content is empty and return warning message. +* +* @param content - Content to check +* @returns Warning message if empty, null otherwise +*/ +function checkEmptyContent(content) { + if (!content || content.trim() === "") return EMPTY_CONTENT_WARNING; + return null; +} +/** +* Convert FileData to plain string content. +* +* @param fileData - FileData object with 'content' key +* @returns Content as string with lines joined by newlines +*/ +function fileDataToString(fileData) { + if (Array.isArray(fileData.content)) return fileData.content.join("\n"); + if (typeof fileData.content === "string") return fileData.content; + throw new Error("Cannot convert binary FileData to string"); +} +/** +* Type guard to check if FileData contains binary content (Uint8Array). +* +* @param data - FileData to check +* @returns True if the content is a Uint8Array (binary) +*/ +function isFileDataBinary(data) { + return ArrayBuffer.isView(data.content); +} +/** +* Create a FileData object. +* +* Defaults to v2 format (content as single string). Pass `fileFormat: "v1"` for +* backward compatibility with older readers during a rolling deployment. +* Binary content (Uint8Array) is only supported with v2. +* +* @param content - File content as a string or binary Uint8Array (v2 only) +* @param createdAt - Optional creation timestamp (ISO format), defaults to now +* @param fileFormat - Storage format: "v2" (default) or "v1" (legacy line array) +* @returns FileData in the requested format +*/ +function createFileData(content, createdAt, fileFormat = "v2", mimeType) { + const now = (/* @__PURE__ */ new Date()).toISOString(); + if (fileFormat === "v1" && ArrayBuffer.isView(content)) throw new Error("Binary data is not supported with v1 file formats. Please use v2 file format"); + if (fileFormat === "v2") { + if (ArrayBuffer.isView(content)) return { + content: new Uint8Array(content.buffer, content.byteOffset, content.byteLength), + mimeType: mimeType ?? "application/octet-stream", + created_at: createdAt || now, + modified_at: now + }; + return { + content, + mimeType: mimeType ?? "text/plain", + created_at: createdAt || now, + modified_at: now + }; + } + return { + content: typeof content === "string" ? content.split("\n") : content, + created_at: createdAt || now, + modified_at: now + }; +} +/** +* Update FileData with new content, preserving creation timestamp. +* +* @param fileData - Existing FileData object +* @param content - New content as string +* @returns Updated FileData object +*/ +function updateFileData(fileData, content) { + const now = (/* @__PURE__ */ new Date()).toISOString(); + if (isFileDataV1(fileData)) return { + content: typeof content === "string" ? content.split("\n") : content, + created_at: fileData.created_at, + modified_at: now + }; + return { + content, + mimeType: fileData.mimeType, + created_at: fileData.created_at, + modified_at: now + }; +} +/** +* Build FileData for write semantics. +* +* Text writes preserve an existing file's creation timestamp. Binary writes +* accept base64 text input and store decoded bytes with the path's MIME type. +*/ +function decodeBase64ToBytes(base64) { + const trimmed = base64.trim(); + const payload = trimmed.startsWith("data:") ? trimmed.slice(trimmed.indexOf(",") + 1) : trimmed; + const binary = atob(payload.replace(/\s/g, "")); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} +function createWriteFileData(filePath, content, fileFormat = "v2", existing) { + const mimeType = getMimeType(filePath); + const createdAt = existing?.created_at; + if (!isTextMimeType(mimeType)) return fileFormat === "v1" ? createFileData(content, createdAt, "v1", mimeType) : createFileData(decodeBase64ToBytes(content), createdAt, "v2", mimeType); + return existing ? updateFileData(existing, content) : createFileData(content, void 0, fileFormat, mimeType); +} +/** +* Perform string replacement with occurrence validation. +* +* @param content - Original content +* @param oldString - String to replace +* @param newString - Replacement string +* @param replaceAll - Whether to replace all occurrences +* @returns Tuple of [new_content, occurrences] on success, or error message string +* +* Special case: When both content and oldString are empty, this sets the initial +* content to newString. This allows editing empty files by treating empty oldString +* as "set initial content" rather than "replace nothing". +*/ +function performStringReplacement(content, oldString, newString, replaceAll) { + if (content === "" && oldString === "") return [newString, 0]; + if (oldString === "") return "Error: oldString cannot be empty when file has content"; + const occurrences = content.split(oldString).length - 1; + if (occurrences === 0) return `Error: String not found in file: '${oldString}'`; + if (occurrences > 1 && !replaceAll) return `Error: String '${oldString}' has multiple occurrences (appears ${occurrences} times) in file. Use replace_all=True to replace all instances, or provide a more specific string with surrounding context.`; + return [content.split(oldString).join(newString), occurrences]; +} +/** +* Truncate list or string result if it exceeds token limit (rough estimate: 4 chars/token). +*/ +function truncateIfTooLong(result) { + if (Array.isArray(result)) { + const totalChars = result.reduce((sum, item) => sum + item.length, 0); + if (totalChars > 2e4 * 4) { + const truncateAt = Math.floor(result.length * TOOL_RESULT_TOKEN_LIMIT * 4 / totalChars); + return [...result.slice(0, truncateAt), TRUNCATION_GUIDANCE]; + } + return result; + } + if (result.length > 2e4 * 4) return result.substring(0, TOOL_RESULT_TOKEN_LIMIT * 4) + "\n... [results truncated, try being more specific with your parameters]"; + return result; +} +/** +* Validate and normalize a directory path. +* +* Ensures paths are safe to use by preventing directory traversal attacks +* and enforcing consistent formatting. All paths are normalized to use +* forward slashes and start with a leading slash. +* +* This function is designed for virtual filesystem paths and rejects +* Windows absolute paths (e.g., C:/..., F:/...) to maintain consistency +* and prevent path format ambiguity. +* +* @param path - Path to validate +* @returns Normalized path starting with / and ending with / +* @throws Error if path is invalid +* +* @example +* ```typescript +* validatePath("foo/bar") // Returns: "/foo/bar/" +* validatePath("/./foo//bar") // Returns: "/foo/bar/" +* validatePath("../etc/passwd") // Throws: Path traversal not allowed +* validatePath("C:\\Users\\file") // Throws: Windows absolute paths not supported +* ``` +*/ +function validatePath$1(path) { + const pathStr = path || "/"; + if (!pathStr || pathStr.trim() === "") throw new Error("Path cannot be empty"); + let normalized = pathStr.startsWith("/") ? pathStr : "/" + pathStr; + if (!normalized.endsWith("/")) normalized += "/"; + return normalized; +} +/** +* Resolve the files under `path` for grep/glob search. +* +* If `path` exactly names a file that exists in `files`, only that file is +* returned (exact match) — this lets grep/glob target a specific file +* directly instead of only matching directories. Otherwise `path` is treated +* as a directory and files are filtered by the normalized directory prefix. +* +* @returns Filtered files map, or null if `path` is invalid (e.g. whitespace-only). +*/ +function filterFilesByPath(files, path) { + const exactPath = path ? path.startsWith("/") ? path : "/" + path : "/"; + if (Object.prototype.hasOwnProperty.call(files, exactPath)) return { [exactPath]: files[exactPath] }; + try { + const normalizedPath = validatePath$1(path); + return Object.fromEntries(Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath))); + } catch { + return null; + } +} +/** +* Search files dict for paths matching glob pattern. +* +* @param files - Dictionary of file paths to FileData +* @param pattern - Glob pattern (e.g., `*.py`, `**\/*.ts`) +* @param path - Base path to search from. If `path` names an exact file, only +* that file is considered. +* @returns Newline-separated file paths, sorted by modification time (most recent first). +* Returns "No files found" if no matches. +* +* @example +* ```typescript +* const files = {"/src/main.py": FileData(...), "/test.py": FileData(...)}; +* globSearchFiles(files, "*.py", "/"); +* // Returns: "/test.py\n/src/main.py" (sorted by modified_at) +* ``` +*/ +function globSearchFiles(files, pattern, path = "/") { + const filtered = filterFilesByPath(files, path); + if (filtered === null) return "No files found"; + const normalizedPath = validatePath$1(path); + const effectivePattern = pattern; + const matches = []; + for (const [filePath, fileData] of Object.entries(filtered)) { + let relative = filePath.substring(normalizedPath.length); + if (relative.startsWith("/")) relative = relative.substring(1); + if (!relative) { + const parts = filePath.split("/"); + relative = parts[parts.length - 1] || ""; + } + if (import_micromatch.default.isMatch(relative, effectivePattern, { + dot: true, + nobrace: false + })) matches.push([filePath, fileData.modified_at]); + } + matches.sort((a, b) => b[1].localeCompare(a[1])); + if (matches.length === 0) return "No files found"; + return matches.map(([fp]) => fp).join("\n"); +} +/** +* Return structured grep matches from an in-memory files mapping. +* +* Performs literal text search (not regex). Binary files are skipped. +* If `path` names an exact file, only that file is considered. +* Returns an empty array when no matches are found or on invalid input. +*/ +function grepMatchesFromFiles(files, pattern, path = null, glob = null) { + let filtered = filterFilesByPath(files, path); + if (filtered === null) return []; + if (glob) filtered = Object.fromEntries(Object.entries(filtered).filter(([fp]) => import_micromatch.default.isMatch(basename(fp), glob, { + dot: true, + nobrace: false + }))); + const matches = []; + for (const [filePath, fileData] of Object.entries(filtered)) { + if (!isTextMimeType(migrateToFileDataV2(fileData, filePath).mimeType)) continue; + const lines = fileDataToString(fileData).split("\n"); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const lineNum = i + 1; + if (line.includes(pattern)) matches.push({ + path: filePath, + line: lineNum, + text: line + }); + } + } + return matches; +} +/** +* Determine MIME type from a file path's extension. +* +* Defaults to "text/plain" for unknown extensions. Only the known non-text +* formats above (images, audio, video, PDF/PPT) are treated as binary by +* {@link isTextMimeType}; everything else reads as text, including source files +* with uncommon extensions (.properties, .scss, .tf) and extension-less files +* (Dockerfile, mvnw). This avoids base64-encoding text into document blocks, +* which the model can't read and which the Anthropic provider rejects with a +* 400. +* +* @param filePath - File path to inspect +* @returns MIME type string (e.g., "image/png", "text/plain") +*/ +function getMimeType(filePath) { + return MIME_TYPES[extname(filePath).toLocaleLowerCase()] || "text/plain"; +} +/** +* Check whether a MIME type represents text content. +* +* @param mimeType - MIME type string to check +* @returns True if the MIME type is text-based +*/ +function isTextMimeType(mimeType) { + return mimeType.startsWith("text/") || mimeType === "application/json" || mimeType === "application/javascript" || mimeType === "image/svg+xml"; +} +/** +* Type guard to check if FileData is v1 format (content as line array). +* +* @param data - FileData to check +* @returns True if data is FileDataV1 +*/ +function isFileDataV1(data) { + return Array.isArray(data.content); +} +/** +* Convert FileData to v2 format, joining v1 line arrays into a single string. +* +* If the data is already v2, returns it unchanged. +* +* @param data - FileData in either format +* @returns FileDataV2 with content as string (text) or Uint8Array (binary) +*/ +function migrateToFileDataV2(data, filePath) { + if (isFileDataV1(data)) return { + content: data.content.join("\n"), + mimeType: getMimeType(filePath), + created_at: data.created_at, + modified_at: data.modified_at + }; + if (!("mimeType" in data) || !data.mimeType) return { + ...data, + mimeType: getMimeType(filePath) + }; + return data; +} +/** +* Adapt a v1 {@link BackendProtocol} to {@link BackendProtocolV2}. +* +* If the backend already implements v2, it is returned as-is. +* For v1 backends, wraps returns in Result types: +* - `read()` string returns wrapped in {@link ReadResult} +* - `readRaw()` FileData returns wrapped in {@link ReadRawResult} +* - `grep()` returns wrapped in {@link GrepResult} +* - `ls()` FileInfo[] returns wrapped in {@link LsResult} +* - `glob()` FileInfo[] returns wrapped in {@link GlobResult} +* +* Note: For sandbox instances, use {@link adaptSandboxProtocol} instead. +* +* @param backend - Backend instance (v1 or v2) +* @returns BackendProtocolV2-compatible backend +*/ +function adaptBackendProtocol(backend) { + const adapted = { + async ls(path) { + const result = await ("ls" in backend ? backend.ls(path) : backend.lsInfo(path)); + if (Array.isArray(result)) return { files: result }; + return result; + }, + async readRaw(filePath) { + const result = await backend.readRaw(filePath); + if ("data" in result || "error" in result) return result; + return { data: migrateToFileDataV2(result, filePath) }; + }, + async glob(pattern, path) { + const result = await ("glob" in backend ? backend.glob(pattern, path) : backend.globInfo(pattern, path)); + if (Array.isArray(result)) return { files: result }; + return result; + }, + write: (filePath, content) => backend.write(filePath, content), + edit: (filePath, oldString, newString, replaceAll) => backend.edit(filePath, oldString, newString, replaceAll), + delete: backend.delete?.bind(backend), + uploadFiles: backend.uploadFiles ? (files) => backend.uploadFiles(files) : void 0, + downloadFiles: backend.downloadFiles ? (paths) => backend.downloadFiles(paths) : void 0, + async read(filePath, offset, limit) { + const result = await backend.read(filePath, offset, limit); + if (typeof result === "string") return { content: result }; + return result; + }, + async grep(pattern, path, glob) { + const result = await ("grep" in backend ? backend.grep(pattern, path, glob) : backend.grepRaw(pattern, path, glob)); + if (Array.isArray(result)) return { matches: result }; + if (typeof result === "string") return { error: result }; + return result; + } + }; + const routePrefixes = backend.routePrefixes; + if (Array.isArray(routePrefixes)) Object.defineProperty(adapted, "routePrefixes", { + value: routePrefixes, + enumerable: true, + configurable: true + }); + return adapted; +} +/** +* Adapt a sandbox backend from v1 to v2 interface. +* +* This extends {@link adaptBackendProtocol} to also preserve sandbox-specific +* properties from {@link SandboxBackendProtocol}: `execute` and `id`. +* +* @param sandbox - Sandbox backend (v1 or v2) +* @returns SandboxBackendProtocolV2-compatible sandbox +*/ +function adaptSandboxProtocol(sandbox) { + const adapted = adaptBackendProtocol(sandbox); + adapted.execute = (cmd) => sandbox.execute(cmd); + Object.defineProperty(adapted, "id", { + value: sandbox.id, + enumerable: true, + configurable: true + }); + return adapted; +} +/** +* Type guard to check if a backend supports execution. +* +* @param backend - Backend instance to check +* @returns True if the backend implements SandboxBackendProtocolV2 +*/ +function isSandboxBackend(backend) { + return backend != null && typeof backend === "object" && typeof backend.execute === "function" && typeof backend.id === "string" && backend.id !== ""; +} +/** +* Type guard to check if a backend is a sandbox protocol (v1 or v2). +* +* Checks for the presence of `execute` function and `id` string, +* which are the defining features of sandbox protocols. +* +* @param backend - Backend instance to check +* @returns True if the backend implements sandbox protocol (v1 or v2) +*/ +function isSandboxProtocol(backend) { + return backend != null && typeof backend === "object" && typeof backend.execute === "function" && typeof backend.id === "string" && backend.id !== ""; +} +/** +* Resolve a backend instance or await a {@link BackendFactory}. +* +* Accepts {@link BackendRuntime} or {@link ToolRuntime} — store typing differs +* between LangGraph checkpoint stores and core `ToolRuntime`; factories receive +* a value that is structurally compatible at runtime. +* +* @internal +*/ +async function resolveBackend(backend, runtime) { + if (typeof backend === "function") { + const resolved = await backend(runtime); + return isSandboxProtocol(resolved) ? adaptSandboxProtocol(resolved) : adaptBackendProtocol(resolved); + } + return isSandboxProtocol(backend) ? adaptSandboxProtocol(backend) : adaptBackendProtocol(backend); +} +var PREGEL_SEND_KEY = "__pregel_send"; +var PREGEL_READ_KEY = "__pregel_read"; +/** +* Backend that stores files in agent state (ephemeral). +* +* Uses LangGraph's state management and checkpointing. Files persist within +* a conversation thread but not across threads. State is automatically +* checkpointed after each agent step. +* +* Special handling: Since LangGraph state must be updated via Command objects +* (not direct mutation), operations return filesUpdate in WriteResult/EditResult +* for the middleware to apply via Command. +*/ +var StateBackend = class { + runtime; + fileFormat; + constructor(runtimeOrOptions, options) { + if (runtimeOrOptions != null && typeof runtimeOrOptions === "object" && "state" in runtimeOrOptions) { + this.runtime = runtimeOrOptions; + this.fileFormat = options?.fileFormat ?? "v2"; + } else { + this.runtime = void 0; + this.fileFormat = runtimeOrOptions?.fileFormat ?? "v2"; + } + } + /** + * Whether this instance was constructed with the legacy factory pattern. + * + * When true, state is read from the injected `runtime` and `filesUpdate` + * is returned to the caller. When false, state is read from LangGraph's + * execution context and updates are sent via `__pregel_send`. + */ + get isLegacy() { + return this.runtime !== void 0; + } + /** + * Get files from current state. + * + * In legacy mode, reads from the injected {@link BackendRuntime}. + * In zero-arg mode, reads via {@link PREGEL_READ_KEY} with fresh=true, + * which applies any pending task writes through the reducer before returning. + */ + get files() { + if (this.runtime) return this.runtime.state.files ?? {}; + const read = getConfig().configurable?.[PREGEL_READ_KEY]; + return read?.("files", true) ?? {}; + } + /** + * Push a files state update through LangGraph's internal send channel. + * + * In zero-arg mode, sends the update via the `__pregel_send` function + * from {@link getConfig}, mirroring Python's `CONFIG_KEY_SEND`. + * In legacy mode, this is a no-op — the caller uses `filesUpdate` + * from the return value instead. + * + * @param update - Map of file paths to their updated {@link FileData}, + * or null deletion markers. + */ + sendFilesUpdate(update) { + if (this.isLegacy) return; + const send = getConfig().configurable?.[PREGEL_SEND_KEY]; + if (typeof send === "function") send([["files", update]]); + } + /** + * List files and directories in the specified directory (non-recursive). + * + * @param path - Absolute path to directory + * @returns LsResult with list of FileInfo objects on success or error on failure. + * Directories have a trailing / in their path and is_dir=true. + */ + ls(path) { + const files = this.files; + const infos = []; + const subdirs = /* @__PURE__ */ new Set(); + const normalizedPath = path.endsWith("/") ? path : path + "/"; + for (const [k, fd] of Object.entries(files)) { + if (!k.startsWith(normalizedPath)) continue; + const relative = k.substring(normalizedPath.length); + if (relative.includes("/")) { + const subdirName = relative.split("/")[0]; + subdirs.add(normalizedPath + subdirName + "/"); + continue; + } + const size = isFileDataV1(fd) ? fd.content.join("\n").length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length; + infos.push({ + path: k, + is_dir: false, + size, + modified_at: fd.modified_at + }); + } + for (const subdir of Array.from(subdirs).sort()) infos.push({ + path: subdir, + is_dir: true, + size: 0, + modified_at: "" + }); + infos.sort((a, b) => a.path.localeCompare(b.path)); + return { files: infos }; + } + /** + * Read file content. + * + * Text files are paginated by line offset/limit. + * Binary files return full Uint8Array content (offset/limit ignored). + * + * @param filePath - Absolute file path + * @param offset - Line offset to start reading from (0-indexed) + * @param limit - Maximum number of lines to read + * @returns ReadResult with content on success or error on failure + */ + read(filePath, offset = 0, limit = 500) { + const fileData = this.files[filePath]; + if (!fileData) return { error: `File '${filePath}' not found` }; + const fileDataV2 = migrateToFileDataV2(fileData, filePath); + if (!isTextMimeType(fileDataV2.mimeType)) return { + content: fileDataV2.content, + mimeType: fileDataV2.mimeType + }; + if (typeof fileDataV2.content !== "string") return { error: `File '${filePath}' has binary content but text MIME type` }; + return { + content: fileDataV2.content.split("\n").slice(offset, offset + limit).join("\n"), + mimeType: fileDataV2.mimeType + }; + } + /** + * Read file content as raw FileData. + * + * @param filePath - Absolute file path + * @returns ReadRawResult with raw file data on success or error on failure + */ + readRaw(filePath) { + const fileData = this.files[filePath]; + if (!fileData) return { error: `File '${filePath}' not found` }; + return { data: fileData }; + } + /** + * Write content to a file, creating it or overwriting it if it already exists. + * Returns WriteResult with filesUpdate to update LangGraph state. + */ + write(filePath, content) { + const existing = this.files[filePath]; + const newFileData = createWriteFileData(filePath, content, this.fileFormat, existing); + const update = { [filePath]: newFileData }; + if (!this.isLegacy) { + this.sendFilesUpdate(update); + return { path: filePath }; + } + return { + path: filePath, + filesUpdate: { [filePath]: newFileData } + }; + } + /** + * Edit a file by replacing string occurrences. + * Returns EditResult with filesUpdate and occurrences. + */ + edit(filePath, oldString, newString, replaceAll = false) { + const fileData = this.files[filePath]; + if (!fileData) return { error: `Error: File '${filePath}' not found` }; + const result = performStringReplacement(fileDataToString(fileData), oldString, newString, replaceAll); + if (typeof result === "string") return { error: result }; + const [newContent, occurrences] = result; + const newFileData = updateFileData(fileData, newContent); + const update = { [filePath]: newFileData }; + if (!this.isLegacy) { + this.sendFilesUpdate(update); + return { + path: filePath, + occurrences + }; + } + return { + path: filePath, + filesUpdate: { [filePath]: newFileData }, + occurrences + }; + } + /** + * Delete a file from state by sending a null deletion marker through Pregel. + */ + delete(filePath) { + if (!(filePath in this.files)) return { error: `Error: File '${filePath}' not found` }; + if (this.isLegacy) return { error: "StateBackend.delete requires a zero-argument StateBackend in a LangGraph execution context." }; + this.sendFilesUpdate({ [filePath]: null }); + return { path: filePath }; + } + /** + * Search file contents for a literal text pattern. + * Binary files are skipped. + */ + grep(pattern, path = "/", glob = null) { + const files = this.files; + return { matches: grepMatchesFromFiles(files, pattern, path, glob) }; + } + /** + * Structured glob matching returning FileInfo objects. + */ + glob(pattern, path = "/") { + const files = this.files; + const result = globSearchFiles(files, pattern, path); + if (result === "No files found") return { files: [] }; + const paths = result.split("\n"); + const infos = []; + for (const p of paths) { + const fd = files[p]; + const size = fd ? isFileDataV1(fd) ? fd.content.join("\n").length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length : 0; + infos.push({ + path: p, + is_dir: false, + size, + modified_at: fd?.modified_at || "" + }); + } + return { files: infos }; + } + /** + * Upload multiple files. + * + * Note: Since LangGraph state must be updated via Command objects, + * the caller must apply filesUpdate via Command after calling this method. + * + * @param files - List of [path, content] tuples to upload + * @returns List of FileUploadResponse objects, one per input file + */ + uploadFiles(files) { + const responses = []; + const updates = {}; + for (const [path, content] of files) try { + const mimeType = getMimeType(path); + if (this.fileFormat === "v2" && !isTextMimeType(mimeType)) updates[path] = createFileData(content, void 0, "v2", mimeType); + else updates[path] = createFileData(new TextDecoder().decode(content), void 0, this.fileFormat, mimeType); + responses.push({ + path, + error: null + }); + } catch { + responses.push({ + path, + error: "invalid_path" + }); + } + if (!this.isLegacy) { + if (Object.keys(updates).length > 0) this.sendFilesUpdate(updates); + return responses; + } + const result = responses; + result.filesUpdate = updates; + return result; + } + /** + * Download multiple files. + * + * @param paths - List of file paths to download + * @returns List of FileDownloadResponse objects, one per input path + */ + downloadFiles(paths) { + const files = this.files; + const responses = []; + for (const path of paths) { + const fileData = files[path]; + if (!fileData) { + responses.push({ + path, + content: null, + error: "file_not_found" + }); + continue; + } + const fileDataV2 = migrateToFileDataV2(fileData, path); + if (typeof fileDataV2.content === "string") { + const content = new TextEncoder().encode(fileDataV2.content); + responses.push({ + path, + content, + error: null + }); + } else responses.push({ + path, + content: fileDataV2.content, + error: null + }); + } + return responses; + } +}; +/** +* Validate permission rule paths at setup time. Throws if any path is +* relative, contains `..`, or contains `~`. +*/ +function validatePermissionPaths(permissions) { + for (const permission of permissions) for (const path of permission.paths) validatePath(path); +} +/** +* Canonicalize and validate an absolute path before permission checking. +* +* Throws for: +* - Empty or non-string input +* - Non-absolute paths (must start with `/`) +* - Paths containing `..` +* - Paths containing `~` +*/ +function validatePath(raw) { + if (typeof raw !== "string" || raw.length === 0) throw new Error("path must be a non-empty string"); + if (!raw.startsWith("/")) throw new Error(`path must be absolute: ${JSON.stringify(raw)}`); + const segments = raw.split("/").filter((s) => s.length > 0); + if (segments.includes("..")) throw new Error(`path must not contain "..": ${JSON.stringify(raw)}`); + if (segments.includes("~")) throw new Error(`path must not contain "~": ${JSON.stringify(raw)}`); + return `/${segments.join("/")}`; +} +/** +* Test whether `path` matches a glob `pattern`. +* +* Supports: +* - `**` — any number of directory levels +* - `*` — within a single path segment +* - `{a,b}` — brace expansion +* +* Uses `micromatch` with `dot: true` so dotfiles are matched by default. +*/ +function globMatch(path, pattern) { + return import_micromatch.default.isMatch(path, pattern, { dot: true }); +} +/** +* Evaluate permission rules against an operation + path and return the +* access decision. +* +* First-match-wins; permissive default. +* +* @returns `"allow"` if the operation is permitted, `"deny"` otherwise. +*/ +function decidePathAccess(rules, operation, path) { + for (const rule of rules) { + if (!rule.operations.includes(operation)) continue; + if (rule.paths.some((pattern) => globMatch(path, pattern))) return rule.mode ?? "allow"; + } + return "allow"; +} +/** +* Backend that routes file operations to different backends based on path prefix. +* +* This enables hybrid storage strategies like: +* - `/memories/` → StoreBackend (persistent, cross-thread) +* - Everything else → StateBackend (ephemeral, per-thread) +* +* The CompositeBackend handles path prefix stripping/re-adding transparently. +*/ +var CompositeBackend = class { + default; + routes; + sortedRoutes; + constructor(defaultBackend, routes) { + this.default = isSandboxProtocol(defaultBackend) ? adaptSandboxProtocol(defaultBackend) : adaptBackendProtocol(defaultBackend); + this.routes = Object.fromEntries(Object.entries(routes).map(([k, v]) => [k, isSandboxProtocol(v) ? adaptSandboxProtocol(v) : adaptBackendProtocol(v)])); + this.sortedRoutes = Object.entries(this.routes).sort((a, b) => b[0].length - a[0].length); + } + /** Delegates to default backend's id if it is a sandbox, otherwise empty string. */ + get id() { + return isSandboxBackend(this.default) ? this.default.id : ""; + } + /** Route prefixes registered on this backend (e.g. `["/workspace"]`). */ + get routePrefixes() { + return Object.keys(this.routes); + } + /** + * Type guard — returns true if `backend` is a {@link CompositeBackend}. + * + * Uses duck-typing on `routePrefixes` so it works across module boundaries + * where `instanceof` may fail. + */ + static isInstance(backend) { + return typeof backend === "object" && backend !== null && Array.isArray(backend.routePrefixes); + } + /** + * Determine which backend handles this key and strip prefix. + * + * @param key - Original file path + * @returns Tuple of [backend, stripped_key] where stripped_key has the route + * prefix removed (but keeps leading slash). + */ + getBackendAndKey(key) { + for (const [prefix, backend] of this.sortedRoutes) if (key.startsWith(prefix)) { + const suffix = key.substring(prefix.length); + return [backend, suffix ? "/" + suffix : "/"]; + } + return [this.default, key]; + } + /** + * Returns true when `path` points at `routePrefix` or its descendants. + */ + isPathWithinRoute(path, routePrefix) { + const normalizedRoute = routePrefix.endsWith("/") ? routePrefix : `${routePrefix}/`; + return path === normalizedRoute.slice(0, -1) || path.startsWith(normalizedRoute); + } + /** + * Returns true when `routePrefix` is inside `path` (or equal to it). + * + * Examples: + * - path `/` includes all routes + * - path `/workspace` includes route `/workspace/memories/` + * - path `/workspace` excludes route `/skills/` + */ + isRouteUnderPath(routePrefix, path) { + if (path === "/") return true; + const normalizedPath = path.endsWith("/") ? path : `${path}/`; + return (routePrefix.endsWith("/") ? routePrefix : `${routePrefix}/`).startsWith(normalizedPath); + } + /** + * List files and directories in the specified directory (non-recursive). + * + * @param path - Absolute path to directory + * @returns LsResult with list of FileInfo objects (with route prefixes added) on success or error on failure. + * Directories have a trailing / in their path and is_dir=true. + */ + async ls(path) { + for (const [routePrefix, backend] of this.sortedRoutes) if (this.isPathWithinRoute(path, routePrefix)) { + const suffix = path.substring(routePrefix.length); + const searchPath = suffix ? "/" + suffix : "/"; + const result = await backend.ls(searchPath); + if (result.error) return result; + const prefixed = []; + for (const fi of result.files || []) prefixed.push({ + ...fi, + path: routePrefix.slice(0, -1) + fi.path + }); + return { files: prefixed }; + } + if (path === "/") { + const results = []; + const defaultResult = await this.default.ls(path); + if (defaultResult.error) return defaultResult; + results.push(...defaultResult.files || []); + for (const [routePrefix] of this.sortedRoutes) results.push({ + path: routePrefix, + is_dir: true, + size: 0, + modified_at: "" + }); + results.sort((a, b) => a.path.localeCompare(b.path)); + return { files: results }; + } + return await this.default.ls(path); + } + /** + * Read file content, routing to appropriate backend. + * + * @param filePath - Absolute file path + * @param offset - Line offset to start reading from (0-indexed) + * @param limit - Maximum number of lines to read + * @returns Formatted file content with line numbers, or error message + */ + async read(filePath, offset = 0, limit = 500) { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.read(strippedKey, offset, limit); + } + /** + * Read file content as raw FileData. + * + * @param filePath - Absolute file path + * @returns ReadRawResult with raw file data on success or error on failure + */ + async readRaw(filePath) { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.readRaw(strippedKey); + } + /** + * Structured search results or error string for invalid input. + */ + async grep(pattern, path = "/", glob = null) { + const searchPath = path || "/"; + for (const [routePrefix, backend] of this.sortedRoutes) if (this.isPathWithinRoute(searchPath, routePrefix)) { + const routeSearchPath = searchPath.substring(routePrefix.length - 1); + const raw = await backend.grep(pattern, routeSearchPath || "/", glob); + if (raw.error) return raw; + return { matches: (raw.matches || []).map((m) => ({ + ...m, + path: routePrefix.slice(0, -1) + m.path + })) }; + } + const allMatches = []; + const rawDefault = await this.default.grep(pattern, searchPath, glob); + if (rawDefault.error) return rawDefault; + allMatches.push(...rawDefault.matches || []); + for (const [routePrefix, backend] of Object.entries(this.routes)) { + if (!this.isRouteUnderPath(routePrefix, searchPath)) continue; + const raw = await backend.grep(pattern, "/", glob); + if (raw.error) return raw; + const matches = (raw.matches || []).map((m) => ({ + ...m, + path: routePrefix.slice(0, -1) + m.path + })); + allMatches.push(...matches); + } + return { matches: allMatches }; + } + /** + * Structured glob matching returning FileInfo objects. + */ + async glob(pattern, path = "/") { + const results = []; + for (const [routePrefix, backend] of this.sortedRoutes) if (this.isPathWithinRoute(path, routePrefix)) { + const searchPath = path.substring(routePrefix.length - 1); + const result = await backend.glob(pattern, searchPath || "/"); + if (result.error) return result; + return { files: (result.files || []).map((fi) => ({ + ...fi, + path: routePrefix.slice(0, -1) + fi.path + })) }; + } + const defaultResult = await this.default.glob(pattern, path); + if (defaultResult.error) return defaultResult; + results.push(...defaultResult.files || []); + for (const [routePrefix, backend] of Object.entries(this.routes)) { + if (!this.isRouteUnderPath(routePrefix, path)) continue; + const result = await backend.glob(pattern, "/"); + if (result.error) continue; + const files = (result.files || []).map((fi) => ({ + ...fi, + path: routePrefix.slice(0, -1) + fi.path + })); + results.push(...files); + } + results.sort((a, b) => a.path.localeCompare(b.path)); + return { files: results }; + } + /** + * Write content to a file, routing to appropriate backend. + * + * @param filePath - Absolute file path + * @param content - File content as string + * @returns WriteResult with path or error + */ + async write(filePath, content) { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.write(strippedKey, content); + } + /** + * Edit a file, routing to appropriate backend. + * + * @param filePath - Absolute file path + * @param oldString - String to find and replace + * @param newString - Replacement string + * @param replaceAll - If true, replace all occurrences + * @returns EditResult with path, occurrences, or error + */ + async edit(filePath, oldString, newString, replaceAll = false) { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.edit(strippedKey, oldString, newString, replaceAll); + } + /** + * Delete a file, routing to the appropriate backend. + */ + async delete(filePath) { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + if (!backend.delete) return { error: "Backend does not support delete" }; + const result = await backend.delete(strippedKey); + if (result.path !== void 0) return { + ...result, + path: filePath + }; + return result; + } + /** + * Execute a command via the default backend. + * Execution is not path-specific, so it always delegates to the default backend. + * + * @param command - Full shell command string to execute + * @returns ExecuteResponse with combined output, exit code, and truncation flag + * @throws Error if the default backend doesn't support command execution + */ + execute(command) { + if (!isSandboxBackend(this.default)) throw new Error("Default backend doesn't support command execution (SandboxBackendProtocol). To enable execution, provide a default backend that implements SandboxBackendProtocol."); + return Promise.resolve(this.default.execute(command)); + } + /** + * Upload multiple files, batching by backend for efficiency. + * + * @param files - List of [path, content] tuples to upload + * @returns List of FileUploadResponse objects, one per input file + */ + async uploadFiles(files) { + const results = Array.from({ length: files.length }, () => null); + const batchesByBackend = /* @__PURE__ */ new Map(); + for (let idx = 0; idx < files.length; idx++) { + const [path, content] = files[idx]; + const [backend, strippedPath] = this.getBackendAndKey(path); + if (!batchesByBackend.has(backend)) batchesByBackend.set(backend, []); + batchesByBackend.get(backend).push({ + idx, + path: strippedPath, + content + }); + } + for (const [backend, batch] of batchesByBackend) { + if (!backend.uploadFiles) throw new Error("Backend does not support uploadFiles"); + const batchFiles = batch.map((b) => [b.path, b.content]); + const batchResponses = await backend.uploadFiles(batchFiles); + for (let i = 0; i < batch.length; i++) { + const originalIdx = batch[i].idx; + results[originalIdx] = { + path: files[originalIdx][0], + error: batchResponses[i]?.error ?? null + }; + } + } + return results; + } + /** + * Download multiple files, batching by backend for efficiency. + * + * @param paths - List of file paths to download + * @returns List of FileDownloadResponse objects, one per input path + */ + async downloadFiles(paths) { + const results = Array.from({ length: paths.length }, () => null); + const batchesByBackend = /* @__PURE__ */ new Map(); + for (let idx = 0; idx < paths.length; idx++) { + const path = paths[idx]; + const [backend, strippedPath] = this.getBackendAndKey(path); + if (!batchesByBackend.has(backend)) batchesByBackend.set(backend, []); + batchesByBackend.get(backend).push({ + idx, + path: strippedPath + }); + } + for (const [backend, batch] of batchesByBackend) { + if (!backend.downloadFiles) throw new Error("Backend does not support downloadFiles"); + const batchPaths = batch.map((b) => b.path); + const batchResponses = await backend.downloadFiles(batchPaths); + for (let i = 0; i < batch.length; i++) { + const originalIdx = batch[i].idx; + results[originalIdx] = { + path: paths[originalIdx], + content: batchResponses[i]?.content ?? null, + error: batchResponses[i]?.error ?? null + }; + } + } + return results; + } +}; +/** +* Middleware for providing filesystem tools to an agent. +* +* Provides ls, read_file, write_file, edit_file, glob, and grep tools with support for: +* - Pluggable backends (StateBackend, StoreBackend, FilesystemBackend, CompositeBackend) +* - Tool result eviction for large outputs +*/ +var INT_FORMATTER = new Intl.NumberFormat("en-US"); +/** +* Normalizes tool input so that models sending `path` instead of `file_path` +* still work. If the input has `path` but not `file_path`, copies `path` into +* `file_path`. This makes the filesystem tools resilient to parameter-name +* variations across models of different capability levels. +*/ +function normalizeFilePathInput(input) { + if (typeof input === "object" && input !== null && "path" in input && !("file_path" in input)) { + const { path, ...rest } = input; + return { + ...rest, + file_path: path + }; + } + return input; +} +/** +* Tools that should be excluded from the large result eviction logic. +* +* This array contains tools that should NOT have their results evicted to the filesystem +* when they exceed token limits. Tools are excluded for different reasons: +* +* 1. Tools with built-in truncation (ls, glob, grep): +* These tools truncate their own output when it becomes too large. When these tools +* produce truncated output due to many matches, it typically indicates the query +* needs refinement rather than full result preservation. In such cases, the truncated +* matches are potentially more like noise and the LLM should be prompted to narrow +* its search criteria instead. +* +* 2. Tools with problematic truncation behavior (read_file): +* read_file is tricky to handle as the failure mode here is single long lines +* (e.g., imagine a jsonl file with very long payloads on each line). If we try to +* truncate the result of read_file, the agent may then attempt to re-read the +* truncated file using read_file again, which won't help. +* +* 3. Tools that never exceed limits (edit_file, write_file): +* These tools return minimal confirmation messages and are never expected to produce +* output large enough to exceed token limits, so checking them would be unnecessary. +*/ +/** +* All tool names registered by FilesystemMiddleware. +* This is the single source of truth — used by createDeepAgent to detect +* collisions with user-supplied tools at construction time. +*/ +var FILESYSTEM_TOOL_NAMES = [ + "ls", + "read_file", + "write_file", + "edit_file", + "glob", + "grep", + "execute" +]; +var TOOLS_EXCLUDED_FROM_EVICTION = FILESYSTEM_TOOL_NAMES.filter((name) => name !== "execute"); +/** +* Maximum size for binary (non-text) files read via read_file, in bytes. +* Base64-encoded content is ~33% larger, so 10MB raw ≈ 13.3MB in context. +* This keeps inline multimodal payloads within all major provider limits. +*/ +var MAX_BINARY_READ_SIZE_BYTES = 10 * 1024 * 1024; +/** +* Template for truncation message in read_file. +* {file_path} will be filled in at runtime. +*/ +var READ_FILE_TRUNCATION_MSG = ` + +[Output was truncated due to size limits. The file content is very large. Consider reformatting the file to make it easier to navigate. For example, if this is JSON, use execute(command='jq . {file_path}') to pretty-print it with line breaks. For other formats, you can use appropriate formatting tools to split long lines.]`; +/** +* Message template for evicted tool results. +*/ +var TOO_LARGE_TOOL_MSG = context` + Tool result too large, the result of this tool call {tool_call_id} was saved in the filesystem at this path: {file_path} + You can read the result from the filesystem by using the read_file tool, but make sure to only read part of the result at a time. + You can do this by specifying an offset and limit in the read_file tool call. + For example, to read the first ${100} lines, you can use the read_file tool with offset=0 and limit=${100}. + + Here is a preview showing the head and tail of the result (lines of the form + ... [N lines truncated] ... + indicate omitted lines in the middle of the content): + + {content_sample} +`; +/** +* Message template for evicted HumanMessages. +*/ +var TOO_LARGE_HUMAN_MSG = `Message content too large and was saved to the filesystem at: {file_path} + +You can read the full content using the read_file tool with pagination (offset and limit parameters). + +Here is a preview showing the head and tail of the content: + +{content_sample}`; +/** +* Extract text content from a message. +* +* For string content, returns it directly. For array content (mixed block types +* like text + image), joins all text blocks. Returns empty string if no text found. +*/ +function extractTextFromMessage(message) { + if (typeof message.content === "string") return message.content; + if (Array.isArray(message.content)) return message.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n"); + return String(message.content); +} +function stringifyToolContent(content) { + if (typeof content === "string") return content; + if (Array.isArray(content)) return content.map((block) => { + if (typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") return block.text; + return JSON.stringify(block); + }).join("\n"); + return String(content); +} +/** +* Build replacement content for an evicted HumanMessage, preserving non-text blocks. +* +* For plain string content, returns the replacement text directly. For list content +* with mixed block types (e.g., text + image), replaces all text blocks with a single +* text block containing the replacement text while keeping non-text blocks intact. +*/ +function buildEvictedHumanContent(message, replacementText) { + if (typeof message.content === "string") return replacementText; + if (Array.isArray(message.content)) { + const mediaBlocks = message.content.filter((block) => typeof block === "object" && block !== null && block.type !== "text"); + if (mediaBlocks.length === 0) return replacementText; + return [{ + type: "text", + text: replacementText + }, ...mediaBlocks]; + } + return replacementText; +} +/** +* Build a truncated HumanMessage for the model request. +* +* Computes a preview from the full content still in state and returns a +* lightweight replacement the model will see. Pure string computation — no +* backend I/O. +*/ +function buildTruncatedHumanMessage(message, filePath) { + const contentSample = createContentPreview(extractTextFromMessage(message)); + return new HumanMessage({ + content: buildEvictedHumanContent(message, TOO_LARGE_HUMAN_MSG.replace("{file_path}", filePath).replace("{content_sample}", contentSample)), + id: message.id, + additional_kwargs: { ...message.additional_kwargs }, + response_metadata: { ...message.response_metadata } + }); +} +/** +* Create a preview of content showing head and tail with truncation marker. +* +* @param contentStr - The full content string to preview. +* @param headLines - Number of lines to show from the start (default: 5). +* @param tailLines - Number of lines to show from the end (default: 5). +* @returns Formatted preview string with line numbers. +*/ +function createContentPreview(contentStr, headLines = 5, tailLines = 5) { + const lines = contentStr.split("\n"); + if (lines.length <= headLines + tailLines) return formatContentWithLineNumbers(lines.map((line) => line.substring(0, 1e3)), 1); + const head = lines.slice(0, headLines).map((line) => line.substring(0, 1e3)); + const tail = lines.slice(-tailLines).map((line) => line.substring(0, 1e3)); + const headSample = formatContentWithLineNumbers(head, 1); + const truncationNotice = `\n... [${lines.length - headLines - tailLines} lines truncated] ...\n`; + const tailSample = formatContentWithLineNumbers(tail, lines.length - tailLines + 1); + return headSample + truncationNotice + tailSample; +} +/** +* Zod v3 schema for FileData (re-export from backends) +*/ +var FileDataSchema = union([object({ + content: array(string()), + created_at: string(), + modified_at: string() +}), object({ + content: union([string(), _instanceof(Uint8Array)]), + mimeType: string(), + created_at: string(), + modified_at: string() +})]); +/** +* Reducer for files state that merges file updates with support for deletions. +* When a file value is null, the file is deleted from state. +* When a file value is non-null, it is added or updated in state. +* +* This reducer enables concurrent updates from parallel subagents by properly +* merging their file changes instead of requiring LastValue semantics. +* +* @param current - The current files record (from state) +* @param update - The new files record (from a subagent update), with null values for deletions +* @returns Merged files record with deletions applied +*/ +function fileDataReducer(current, update) { + if (update === void 0) return current || {}; + if (current === void 0) { + const result = {}; + for (const [key, value] of Object.entries(update)) if (value !== null) result[key] = value; + return result; + } + const result = { ...current }; + for (const [key, value] of Object.entries(update)) if (value === null) delete result[key]; + else result[key] = value; + return result; +} +/** +* Shared filesystem state schema. +* Defined at module level to ensure the same object identity is used across all agents, +* preventing "Channel already exists with different type" errors when multiple agents +* use createFilesystemMiddleware. +* +* Uses ReducedValue for files to allow concurrent updates from parallel subagents. +*/ +var FilesystemStateSchema = new StateSchema({ files: new ReducedValue(record(string(), FileDataSchema).default(() => ({})), { + inputSchema: record(string(), FileDataSchema.nullable()).optional(), + reducer: fileDataReducer +}) }); +/** Extract a message string from an unknown thrown value without `instanceof`. */ +function getErrorMessage$1(error) { + if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message; + return String(error); +} +/** +* Check whether `path` is permitted under `rules` for `operation`, returning an +* error string to surface to the model (or `undefined` when allowed). +* +* Never throws: an invalid path (non-absolute, or containing `..` or `~`) or a +* denied path is a recoverable tool error, not a fatal run-ending one. Such +* paths are rejected, never normalized, so they cannot bypass a deny rule or +* reach the backend. +* +* @internal +*/ +function checkPermission(rules, operation, path) { + if (rules.length === 0) return; + let canonical; + try { + canonical = validatePath(path); + } catch (error) { + return `Error: ${getErrorMessage$1(error)}`; + } + if (decidePathAccess(rules, operation, canonical) === "deny") return `Error: permission denied for ${operation} on ${canonical}`; +} +/** +* Build an error {@link ToolMessage} for a rejected or denied path. Returning a +* bare string would be wrapped as a `status: "success"` message whose content +* merely starts with "Error:"; marking `status: "error"` reports the failure +* accurately so callers and the model can distinguish a real failure from a +* successful result. +*/ +function toolError(runtime, toolName, message) { + return new ToolMessage({ + content: message, + name: toolName, + tool_call_id: runtime.toolCall?.id, + status: "error" + }); +} +/** +* Filter a list of filesystem entries to those the rules permit. +* +* `getPath` extracts the absolute path from each entry. Entries with +* unparsable paths are included (not silently dropped). Returns the +* original array unchanged when `rules` is empty. +* +* @internal +*/ +function filterByPermissions(entries, rules, operation, getPath) { + if (rules.length === 0) return entries; + return entries.filter((entry) => { + try { + return decidePathAccess(rules, operation, validatePath(getPath(entry))) !== "deny"; + } catch { + return true; + } + }); +} +var LS_TOOL_DESCRIPTION = context` + Lists all files in a directory. + + This is useful for exploring the filesystem and finding the right file to read or edit. + You should almost ALWAYS use this tool before using the read_file or edit_file tools. +`; +var READ_FILE_TOOL_DESCRIPTION = context` + Reads a file from the filesystem. Assume any path the user provides is valid; reading a missing file returns an error. + + Usage: + - By default, it reads up to ${100} lines starting from the beginning of the file. Use \`offset\`/\`limit\` to page through large files instead of reading them whole. + - Results are returned with line numbers starting at \`offset\` + 1 (1 by default), then two spaces, then the source line. Never include these line-number prefixes when editing. + - Lines over ${INT_FORMATTER.format(MAX_LINE_LENGTH)} characters are split with continuation markers (e.g. 5.1, 5.2); \`limit\` counts source lines, so continuation rows do not consume the budget. + - Speculatively batch multiple \`read_file\` calls in one response when several files may be useful. + - An empty file returns a system-reminder warning in place of contents. + - Large tool results may be offloaded to a file; the tool message gives the path. Read that path here, paging with \`offset\`/\`limit\`. + - Images (\`.png\`, \`.jpg\`, etc.), audio, video, and PDFs return multimodal content blocks (https://docs.langchain.com/javascript/python/langchain/messages#multimodal). + - For images and PDFs, pagination via \`offset\`/\`limit\` is text-only - supply \`file_path\` only. + - Always read a file before editing it. +`; +var WRITE_FILE_TOOL_DESCRIPTION = context` + Writes content to a file. Creates the file if it does not exist; replaces it entirely if it does. + + Usage: + - Use this tool when you intend to create a new file or replace the whole file. You do not need to read the file first. + - Prefer to edit existing files (with the edit_file tool) over creating new ones when possible. +`; +var EDIT_FILE_TOOL_DESCRIPTION = context` + Performs exact string replacements in files. + + Usage: + - You must read the file before editing; this tool errors otherwise. + - Preserve the exact indentation from the read output, and never include line-number prefixes in old_string or new_string. + - Prefer editing an existing file over creating a new one. + - Only use emojis if the user explicitly requests it. +`; +var GLOB_TOOL_DESCRIPTION = context` + Find files matching a glob pattern, returning absolute paths. + + Supports \`*\` (any characters), \`**\` (any directories), \`?\` (single character), e.g. \`**/*.py\`, \`*.txt\`, \`/subdir/**/*.md\`. +`; +var GREP_REGEX_EXECUTE_FALLBACK = "\n- If you genuinely need regex, use the execute tool with `rg ''` instead."; +function getGrepToolDescription(includeExecution) { + return context` + Search for a LITERAL text pattern across files (NOT regex). + + The pattern is matched verbatim: regex metacharacters are ordinary characters, not operators. To match any of several strings, run a separate grep for each; \`grep(pattern="foo|bar")\` searches for the literal text "foo|bar", and \`.*\` or \`\\.\` match those characters literally.${includeExecution ? GREP_REGEX_EXECUTE_FALLBACK : ""} + + Returns matching files or content per \`output_mode\`. Offloaded large tool results live under the artifacts root (\`/large_tool_results/\` by default); grep that directory to search them when you do not know the exact path. + `; +} +var EXECUTE_SEARCH_GUIDANCE = { + both: "You MUST avoid using search commands like find and grep. Instead use the grep, glob tools to search. ", + grep: "You MUST avoid using shell grep for searches. Instead use the grep tool to search text. ", + glob: "You MUST avoid using shell find for searches. Instead use the glob tool to find files. ", + none: "" +}; +function getExecuteToolDescription(hasGrep, hasGlob) { + const searchGuidance = hasGrep ? hasGlob ? EXECUTE_SEARCH_GUIDANCE.both : EXECUTE_SEARCH_GUIDANCE.grep : hasGlob ? EXECUTE_SEARCH_GUIDANCE.glob : EXECUTE_SEARCH_GUIDANCE.none; + const examples = [hasGlob ? "- execute(command=\"find . -name '*.py'\") # Use glob tool instead" : "", hasGrep ? "- execute(command=\"grep -r 'pattern' .\") # Use grep tool instead" : ""].filter(Boolean); + return context` + Executes a shell command in an isolated sandbox and returns combined stdout/stderr with the exit code (truncated if very large). + + Usage: + - Quote paths containing spaces (e.g. cd "/path/with spaces"). + - Chain commands with ';' or '&&' (use '&&' when a command depends on the previous); do not use newlines except inside quoted strings. + - Use absolute paths and avoid \`cd\` so the working directory stays stable. + - ${searchGuidance}Use read_file rather than cat/head/tail.${examples.length ? `\n${examples.join("\n")}` : ""} + + Only available on backends implementing SandboxBackendProtocol; otherwise it returns an error. + `; +} +/** +* Create ls tool using backend. +*/ +function createLsTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + const permissionError = checkPermission(permissions, "read", input.path ?? "/"); + if (permissionError !== void 0) return toolError(runtime, "ls", permissionError); + const resolvedBackend = await resolveBackend(backend, runtime); + const path = input.path || "/"; + const lsResult = await resolvedBackend.ls(path); + if (lsResult.error) return `Error listing files: ${lsResult.error}`; + const infos = filterByPermissions(lsResult.files ?? [], permissions, "read", (info) => info.path); + if (infos.length === 0) return `No files found in ${path}`; + const lines = []; + for (const info of infos) if (info.is_dir) lines.push(`${info.path} (directory)`); + else { + const size = info.size ? ` (${info.size} bytes)` : ""; + lines.push(`${info.path}${size}`); + } + const result = truncateIfTooLong(lines); + if (Array.isArray(result)) return result.join("\n"); + return result; + }, { + name: "ls", + description: customDescription || LS_TOOL_DESCRIPTION, + schema: object({ path: string().optional().default("/").describe("Directory path to list (default: /)") }) + }); +} +/** +* Create read_file tool using backend. +*/ +function createReadFileTool(backend, options) { + const { customDescription, toolTokenLimitBeforeEvict, permissions } = options; + return tool$1(async (input, runtime) => { + const permissionError = checkPermission(permissions, "read", input.file_path); + if (permissionError !== void 0) return toolError(runtime, "read_file", permissionError); + const resolvedBackend = await resolveBackend(backend, runtime); + const { file_path, offset = 0, limit = 100 } = input; + const readResult = await resolvedBackend.read(file_path, offset, limit); + if (readResult.error) return [{ + type: "text", + text: `Error: ${readResult.error}` + }]; + const mimeType = readResult.mimeType ?? getMimeType(file_path); + if (!isTextMimeType(mimeType)) { + const binaryContent = readResult.content; + if (!binaryContent) return [{ + type: "text", + text: `Error: expected binary content for '${file_path}'` + }]; + let base64Data; + if (typeof binaryContent === "string") base64Data = binaryContent; + else if (ArrayBuffer.isView(binaryContent)) base64Data = Buffer.from(binaryContent).toString("base64"); + else { + const values = Object.values(binaryContent); + base64Data = Buffer.from(new Uint8Array(values)).toString("base64"); + } + const sizeBytes = Math.ceil(base64Data.length * 3 / 4); + if (sizeBytes > 10485760) return [{ + type: "text", + text: `Error: file too large to read (${Math.round(sizeBytes / (1024 * 1024))}MB exceeds ${MAX_BINARY_READ_SIZE_BYTES / (1024 * 1024)}MB limit for binary files)` + }]; + if (mimeType.startsWith("image/")) return [{ + type: "image", + mimeType, + data: base64Data + }]; + if (mimeType.startsWith("audio/")) return [{ + type: "audio", + mimeType, + data: base64Data + }]; + if (mimeType.startsWith("video/")) return [{ + type: "video", + mimeType, + data: base64Data + }]; + return [{ + type: "file", + mimeType, + data: base64Data + }]; + } + let content = typeof readResult.content === "string" ? readResult.content : ""; + const lines = content.split("\n"); + if (lines.length > limit) content = lines.slice(0, limit).join("\n"); + let formatted = formatContentWithLineNumbers(content, offset + 1); + if (toolTokenLimitBeforeEvict && formatted.length >= 4 * toolTokenLimitBeforeEvict) { + const truncationMsg = READ_FILE_TRUNCATION_MSG.replace("{file_path}", file_path); + const maxContentLength = 4 * toolTokenLimitBeforeEvict - truncationMsg.length; + formatted = formatted.substring(0, maxContentLength) + truncationMsg; + } + return [{ + type: "text", + text: formatted + }]; + }, { + name: "read_file", + description: customDescription || READ_FILE_TOOL_DESCRIPTION, + schema: preprocess(normalizeFilePathInput, object({ + file_path: string().describe("Absolute path to the file to read"), + offset: number$1().optional().default(0).describe("Line offset to start reading from (0-indexed)"), + limit: number$1().optional().default(100).describe("Maximum number of lines to read") + })) + }); +} +/** +* Create write_file tool using backend. +*/ +function createWriteFileTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + const permissionError = checkPermission(permissions, "write", input.file_path); + if (permissionError !== void 0) return toolError(runtime, "write_file", permissionError); + const resolvedBackend = await resolveBackend(backend, runtime); + const { file_path, content } = input; + const result = await resolvedBackend.write(file_path, content); + if (result.error) return result.error; + const message = new ToolMessage({ + content: `Successfully wrote to '${file_path}'`, + tool_call_id: runtime.toolCall?.id, + name: "write_file", + metadata: result.metadata + }); + if (result.filesUpdate) return new Command({ update: { + files: result.filesUpdate, + messages: [message] + } }); + return message; + }, { + name: "write_file", + description: customDescription || WRITE_FILE_TOOL_DESCRIPTION, + schema: preprocess(normalizeFilePathInput, object({ + file_path: string().describe("Absolute path where the file should be written. Must be absolute, not relative."), + content: string().default("").describe("The text content to write to the file. Defaults to empty.") + })) + }); +} +/** +* Create edit_file tool using backend. +*/ +function createEditFileTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + const permissionError = checkPermission(permissions, "write", input.file_path); + if (permissionError !== void 0) return toolError(runtime, "edit_file", permissionError); + const resolvedBackend = await resolveBackend(backend, runtime); + const { file_path, old_string, new_string, replace_all = false } = input; + const result = await resolvedBackend.edit(file_path, old_string, new_string, replace_all); + if (result.error) return result.error; + const message = new ToolMessage({ + content: `Successfully replaced ${result.occurrences} occurrence(s) in '${file_path}'`, + tool_call_id: runtime.toolCall?.id, + name: "edit_file", + metadata: result.metadata + }); + if (result.filesUpdate) return new Command({ update: { + files: result.filesUpdate, + messages: [message] + } }); + return message; + }, { + name: "edit_file", + description: customDescription || EDIT_FILE_TOOL_DESCRIPTION, + schema: preprocess(normalizeFilePathInput, object({ + file_path: string().describe("Absolute path to the file to edit"), + old_string: string().describe("String to be replaced (must match exactly)"), + new_string: string().describe("String to replace with"), + replace_all: boolean().optional().default(false).describe("Whether to replace all occurrences") + })) + }); +} +/** +* Create glob tool using backend. +*/ +function createGlobTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + const permissionError = checkPermission(permissions, "read", input.path ?? "/"); + if (permissionError !== void 0) return toolError(runtime, "glob", permissionError); + const resolvedBackend = await resolveBackend(backend, runtime); + const { pattern, path } = input; + const globResult = await resolvedBackend.glob(pattern, path); + if (globResult.error) return `Error finding files: ${globResult.error}`; + const infos = filterByPermissions(globResult.files ?? [], permissions, "read", (info) => info.path); + if (infos.length === 0) return `No files found matching pattern '${pattern}'`; + const result = truncateIfTooLong(infos.map((info) => info.path)); + if (Array.isArray(result)) return result.join("\n"); + return result; + }, { + name: "glob", + description: customDescription || GLOB_TOOL_DESCRIPTION, + schema: object({ + pattern: string().describe("Glob pattern to match files (e.g., '**/*.py', '*.txt', '/subdir/**/*.md')"), + path: string().optional().describe("Base directory to search from. Defaults to the backend's default root.") + }) + }); +} +/** +* Create grep tool using backend. +*/ +function createGrepTool(backend, options) { + const { customDescription, permissions, includeExecution } = options; + return tool$1(async (input, runtime) => { + const permissionError = checkPermission(permissions, "read", input.path ?? "/"); + if (permissionError !== void 0) return toolError(runtime, "grep", permissionError); + const resolvedBackend = await resolveBackend(backend, runtime); + const { pattern, path = "/", glob = null } = input; + const result = await resolvedBackend.grep(pattern, path, glob); + if (result.error) return result.error; + const matches = filterByPermissions(result.matches ?? [], permissions, "read", (m) => m.path); + if (matches.length === 0) return `No matches found for pattern '${pattern}'`; + const lines = []; + let currentFile = null; + for (const match of matches) { + if (match.path !== currentFile) { + currentFile = match.path; + lines.push(`\n${currentFile}:`); + } + lines.push(` ${match.line}: ${match.text}`); + } + const truncated = truncateIfTooLong(lines); + if (Array.isArray(truncated)) return truncated.join("\n"); + return truncated; + }, { + name: "grep", + description: customDescription || getGrepToolDescription(includeExecution), + schema: object({ + pattern: string().describe("Literal text pattern to search for (not regex)"), + path: string().optional().default("/").describe("Base path to search from (default: /)"), + glob: string().optional().nullable().default(null).describe("Optional glob pattern to filter files (e.g., '*.py')") + }) + }); +} +/** +* Create execute tool using backend. +*/ +function createExecuteTool(backend, options) { + const { customDescription, permissions, hasGrep, hasGlob } = options; + return tool$1(async (input, runtime) => { + const resolvedBackend = await resolveBackend(backend, runtime); + if (!isSandboxBackend(resolvedBackend)) return "Error: Execution not available. This agent's backend does not support command execution (SandboxBackendProtocol). To use the execute tool, provide a backend that implements SandboxBackendProtocol."; + if (permissions.length > 0 && !allPathsScopedToRoutes(permissions, resolvedBackend)) return "Error: Execution not available. Filesystem permissions cannot be used with a backend that supports command execution because shell commands can access any path, making path-based rules ineffective."; + const result = await resolvedBackend.execute(input.command); + const parts = [result.output]; + if (result.exitCode !== null) { + const status = result.exitCode === 0 ? "succeeded" : "failed"; + parts.push(`\n[Command ${status} with exit code ${result.exitCode}]`); + } + if (result.truncated) parts.push("\n[Output was truncated due to size limits]"); + return parts.join(""); + }, { + name: "execute", + description: customDescription || getExecuteToolDescription(hasGrep, hasGlob), + schema: object({ command: string().describe("The shell command to execute") }) + }); +} +/** +* Returns true only when backend exposes route prefixes (CompositeBackend) and +* every permission path is scoped under one of them. +*/ +function normalizeFilesystemTools(tools) { + if (tools == null || tools === "all") return null; + const enabledTools = new Set(tools); + if (!enabledTools.has("read_file")) throw new Error("read_file must be included in tools; it is required by FilesystemMiddleware"); + return enabledTools; +} +function allPathsScopedToRoutes(permissions, backend) { + if (!CompositeBackend.isInstance(backend)) return false; + const prefixes = backend.routePrefixes; + if (prefixes.length === 0) return false; + return permissions.every((rule) => rule.paths.every((path) => prefixes.some((prefix) => path.startsWith(prefix.endsWith("/") ? prefix : `${prefix}/`)))); +} +/** +* Create middleware that provides built-in filesystem tools and optional custom +* prompt guidance. +* +* By default, the middleware registers every built-in filesystem tool listed in +* {@link FILESYSTEM_TOOL_NAMES}. Use {@link FilesystemMiddlewareOptions.tools} +* to narrow that set for read-only, search-only, or otherwise restricted +* agents. The allowlist only controls built-in filesystem tools; custom tools +* from the agent or other middleware are left untouched. +* +* The middleware also filters tools whose backend capabilities are unavailable +* at request time. In particular, `execute` is only visible when the resolved +* backend supports command execution. +* +* @param options Filesystem middleware configuration. +* @returns Agent middleware that contributes filesystem state, tools, prompt +* guidance, permission checks, and large-result eviction. +* +* @example Read-only filesystem middleware +* ```ts +* const middleware = createFilesystemMiddleware({ +* tools: ["read_file", "ls", "glob", "grep"], +* }); +* ``` +*/ +function createFilesystemMiddleware(options = {}) { + const { backend = (runtime) => new StateBackend(runtime), systemPrompt: customSystemPrompt = null, customToolDescriptions = null, toolTokenLimitBeforeEvict = 2e4, humanMessageTokenLimitBeforeEvict = 5e4, permissions = [], tools: filesystemTools = null } = options; + const enabledFilesystemTools = normalizeFilesystemTools(filesystemTools); + const executeToolEnabled = enabledFilesystemTools == null || enabledFilesystemTools.has("execute"); + if (permissions.length > 0) validatePermissionPaths(permissions); + if (permissions.length > 0 && executeToolEnabled && typeof backend !== "function" && isSandboxBackend(backend) && !allPathsScopedToRoutes(permissions, backend)) throw new Error("Filesystem permissions cannot be used with a backend that supports command execution. Shell commands can access any path, making path-based rules ineffective. Either remove permissions, use a backend without execution support, or use a CompositeBackend with all permission paths scoped to a route prefix."); + const baseSystemPrompt = customSystemPrompt ?? null; + const configuredToolNames = enabledFilesystemTools ?? new Set(FILESYSTEM_TOOL_NAMES); + /** + * All tools including execute + * (execute will be filtered at runtime if backend doesn't support it) + */ + const allToolsByName = { + ls: createLsTool(backend, { + customDescription: customToolDescriptions?.ls, + permissions + }), + read_file: createReadFileTool(backend, { + customDescription: customToolDescriptions?.read_file, + toolTokenLimitBeforeEvict, + permissions + }), + write_file: createWriteFileTool(backend, { + customDescription: customToolDescriptions?.write_file, + permissions + }), + edit_file: createEditFileTool(backend, { + customDescription: customToolDescriptions?.edit_file, + permissions + }), + glob: createGlobTool(backend, { + customDescription: customToolDescriptions?.glob, + permissions + }), + grep: createGrepTool(backend, { + customDescription: customToolDescriptions?.grep, + permissions, + includeExecution: configuredToolNames.has("execute") && typeof backend !== "function" && isSandboxBackend(backend) + }), + execute: createExecuteTool(backend, { + customDescription: customToolDescriptions?.execute, + permissions, + hasGrep: configuredToolNames.has("grep"), + hasGlob: configuredToolNames.has("glob") + }) + }; + const allTools = FILESYSTEM_TOOL_NAMES.filter((name) => enabledFilesystemTools == null || enabledFilesystemTools.has(name)).map((name) => allToolsByName[name]); + async function processToolMessage(msg, runtime, state, fallbackToolCallId) { + if (!toolTokenLimitBeforeEvict) return { + message: msg, + filesUpdate: null + }; + if (msg.name && TOOLS_EXCLUDED_FROM_EVICTION.includes(msg.name)) return { + message: msg, + filesUpdate: null + }; + const textContent = stringifyToolContent(msg.content); + if (textContent.length <= toolTokenLimitBeforeEvict * 4) return { + message: msg, + filesUpdate: null + }; + const resolvedBackend = await resolveBackend(backend, { + ...runtime, + state + }); + const evictPath = `/large_tool_results/${sanitizeToolCallId(fallbackToolCallId || msg.tool_call_id)}.txt`; + const writeResult = await resolvedBackend.write(evictPath, textContent); + const contentSample = createContentPreview(textContent); + return { + message: new ToolMessage({ + content: writeResult.error ? `Tool result too large, but the result could not be saved to the filesystem: ${writeResult.error}` : TOO_LARGE_TOOL_MSG.replace("{tool_call_id}", msg.tool_call_id).replace("{file_path}", evictPath).replace("{content_sample}", contentSample), + tool_call_id: msg.tool_call_id, + name: msg.name, + id: msg.id, + artifact: msg.artifact, + status: msg.status, + metadata: msg.metadata, + additional_kwargs: msg.additional_kwargs, + response_metadata: msg.response_metadata + }), + filesUpdate: writeResult.error ? null : writeResult.filesUpdate + }; + } + return createMiddleware({ + name: "FilesystemMiddleware", + stateSchema: FilesystemStateSchema, + tools: allTools, + async beforeAgent(state) { + if (!humanMessageTokenLimitBeforeEvict) return; + const messages = state.messages; + if (!messages || messages.length === 0) return; + const last = messages[messages.length - 1]; + if (!HumanMessage.isInstance(last)) return; + if (last.additional_kwargs?.lc_evicted_to) return; + const contentStr = extractTextFromMessage(last); + const threshold = 4 * humanMessageTokenLimitBeforeEvict; + if (contentStr.length <= threshold) return; + const resolvedBackend = await resolveBackend(backend, { state: state || {} }); + const filePath = `/conversation_history/${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`; + const writeResult = await resolvedBackend.write(filePath, contentStr); + if (writeResult.error) return; + const result = { messages: [new HumanMessage({ + content: last.content, + id: last.id, + additional_kwargs: { + ...last.additional_kwargs, + lc_evicted_to: filePath + }, + response_metadata: { ...last.response_metadata } + })] }; + if (writeResult.filesUpdate) result.files = writeResult.filesUpdate; + return result; + }, + wrapModelCall: async (request, handler) => { + const supportsExecution = isSandboxBackend(await resolveBackend(backend, { + ...request.runtime, + state: request.state + })); + let tools = request.tools; + if (!supportsExecution) tools = tools.filter((t) => t.name !== "execute"); + const newSystemMessage = baseSystemPrompt ? request.systemMessage.concat(baseSystemPrompt) : request.systemMessage; + let messages = request.messages; + if (humanMessageTokenLimitBeforeEvict && messages) { + if (messages.some((msg) => HumanMessage.isInstance(msg) && msg.additional_kwargs?.lc_evicted_to)) messages = messages.map((msg) => { + if (HumanMessage.isInstance(msg) && msg.additional_kwargs?.lc_evicted_to) return buildTruncatedHumanMessage(msg, msg.additional_kwargs.lc_evicted_to); + return msg; + }); + } + return handler({ + ...request, + tools, + messages, + systemMessage: newSystemMessage + }); + }, + wrapToolCall: async (request, handler) => { + if (!toolTokenLimitBeforeEvict) return handler(request); + const toolName = request.toolCall?.name; + if (toolName && TOOLS_EXCLUDED_FROM_EVICTION.includes(toolName)) return handler(request); + const result = await handler(request); + if (ToolMessage.isInstance(result)) { + const processed = await processToolMessage(result, request.runtime, request.state, request.toolCall?.id); + if (processed.filesUpdate) return new Command({ update: { + files: processed.filesUpdate, + messages: [processed.message] + } }); + return processed.message; + } + if (isCommand(result)) { + const update = result.update; + if (!update?.messages) return result; + let hasLargeResults = false; + const accumulatedFiles = update.files ? { ...update.files } : {}; + const processedMessages = []; + for (const msg of update.messages) if (ToolMessage.isInstance(msg)) { + const processed = await processToolMessage(msg, request.runtime, request.state, request.toolCall?.id); + processedMessages.push(processed.message); + if (processed.filesUpdate) { + hasLargeResults = true; + Object.assign(accumulatedFiles, processed.filesUpdate); + } + } else processedMessages.push(msg); + if (hasLargeResults) return new Command({ update: { + ...update, + messages: processedMessages, + files: accumulatedFiles + } }); + } + return result; + } + }); +} +/** +* Config key used by task-tool callers to request dynamic response format. +* +* When set in `config.configurable`, the task tool recompiles the target +* subagent with this response format instead of using the pre-compiled graph. +*/ +var SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY = "__deepagents_subagent_response_format"; +/** +* Default system prompt for subagents. +* Provides a minimal base prompt that can be extended by specific subagent configurations. +*/ +var DEFAULT_SUBAGENT_PROMPT = "In order to complete the objective that the user asks of you, you have access to a number of standard tools."; +/** +* State keys that are excluded when passing state to subagents and when returning +* updates from subagents. +* +* When returning updates: +* 1. The messages key is handled explicitly to ensure only the final message is included +* 2. The todos and structuredResponse keys are excluded as they do not have a defined reducer +* and no clear meaning for returning them from a subagent to the main agent. +* 3. The skillsMetadata and memoryContents keys are automatically excluded from subagent output +* to prevent parent state from leaking to child agents. Each agent loads its own skills/memory +* independently based on its middleware configuration. +*/ +var EXCLUDED_STATE_KEYS = [ + "messages", + "todos", + "structuredResponse", + "skillsMetadata", + "memoryContents" +]; +/** +* Default description for the general-purpose subagent. +* This description is shown to the model when selecting which subagent to use. +*/ +var DEFAULT_GENERAL_PURPOSE_DESCRIPTION = "General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. This agent has access to all tools as the main agent."; +function getTaskToolDescription(subagentDescriptions) { + return context` + Launch an ephemeral subagent to handle a complex, multi-step task in an isolated context window. + + Available agent types and the tools they have access to: + ${subagentDescriptions.join("\n")} + + Specify subagent_type to select the agent. Usage notes: + - Launch multiple agents concurrently when their tasks are independent, using a single message with multiple tool calls. + - Each invocation is stateless: the agent sees only the prompt you give it and returns a single final report. Put full detail in the prompt and state exactly what it should return. + - The agent's report is not shown to the user; relay a summary yourself. + - Tell the agent whether to create content, analyze, or only research, since it cannot see the user's intent. + - If an agent's description says to use it proactively, do so without waiting to be asked. + - When only general-purpose is available, use it for any complex, context-heavy task; it has the same capabilities as the main agent. + `; +} +/** +* Base specification for the general-purpose subagent. +* +* This constant provides the default configuration for the general-purpose subagent +* that is automatically included when `generalPurposeAgent: true` (the default). +* +* The general-purpose subagent: +* - Has access to all tools from the main agent +* - Inherits skills from the main agent (when skills are configured) +* - Uses the same model as the main agent (by default) +* - Is ideal for delegating complex, multi-step tasks +* +* You can spread this constant and override specific properties when creating +* custom subagents that should behave similarly to the general-purpose agent: +* +* @example +* ```typescript +* import { GENERAL_PURPOSE_SUBAGENT, createDeepAgent } from "@anthropic/deepagents"; +* +* // Use as-is (automatically included with generalPurposeAgent: true) +* const agent = createDeepAgent({ model: "claude-sonnet-4-5-20250929" }); +* +* // Or create a custom variant with different tools +* const customGP: SubAgent = { +* ...GENERAL_PURPOSE_SUBAGENT, +* name: "research-gp", +* tools: [webSearchTool, readFileTool], +* }; +* +* const agent = createDeepAgent({ +* model: "claude-sonnet-4-5-20250929", +* subagents: [customGP], +* // Disable the default general-purpose agent since we're providing our own +* // (handled automatically when using createSubAgentMiddleware directly) +* }); +* ``` +*/ +var GENERAL_PURPOSE_SUBAGENT = { + name: "general-purpose", + description: DEFAULT_GENERAL_PURPOSE_DESCRIPTION, + systemPrompt: DEFAULT_SUBAGENT_PROMPT +}; +/** +* Filter state to exclude certain keys when passing to subagents +*/ +function filterStateForSubagent(state) { + const filtered = {}; + for (const [key, value] of Object.entries(state)) if (!EXCLUDED_STATE_KEYS.includes(key)) filtered[key] = value; + return filtered; +} +/** +* Invalid tool message block types +*/ +var INVALID_TOOL_MESSAGE_BLOCK_TYPES = [ + "tool_use", + "thinking", + "redacted_thinking" +]; +/** +* Create Command with filtered state update from subagent result +*/ +function returnCommandWithStateUpdate(result, toolCallId) { + const stateUpdate = filterStateForSubagent(result); + let content; + if (result.structuredResponse != null) content = JSON.stringify(result.structuredResponse); + else { + const messages = result.messages ?? []; + content = "Task completed"; + for (let i = messages.length - 1; i >= 0; i -= 1) { + const message = messages[i]; + if (!message || !AIMessage.isInstance(message)) continue; + const text = typeof message.content === "string" ? message.content.trim() : message.text?.trim() ?? ""; + if (text) { + content = text; + break; + } + } + } + return new Command({ update: { + ...stateUpdate, + messages: [new ToolMessage({ + content, + tool_call_id: toolCallId, + name: "task" + })] + } }); +} +/** +* Create a runnable agent from a declarative `SubAgent` spec. +* +* This is the shared entrypoint for compiling a `SubAgent` into a +* `ReactAgent`. Pre-compiled `CompiledSubAgent` runnables bypass this +* function entirely. +* +* The spec must have `model` and `tools` set — the caller is responsible +* for coalescing any defaults before calling this function. +* +* @param spec - Declarative subagent specification. Must specify `model` and `tools`. +* @returns A compiled `ReactAgent` ready for task-tool invocation. +*/ +function createSubAgent(spec, options) { + if (!spec.model) throw new Error(`SubAgent '${spec.name}' must specify 'model'`); + if (!spec.tools) throw new Error(`SubAgent '${spec.name}' must specify 'tools'`); + const middleware = [...spec.middleware ?? []]; + if (spec.interruptOn) middleware.push(humanInTheLoopMiddleware({ interruptOn: spec.interruptOn })); + const selectedResponseFormat = options?.responseFormat ?? spec.responseFormat; + return createAgent({ + model: spec.model, + systemPrompt: spec.systemPrompt, + tools: spec.tools, + middleware, + name: spec.name, + ...selectedResponseFormat != null && { responseFormat: selectedResponseFormat } + }); +} +/** +* Create subagent instances from specifications. +* +* Returns compiled agents, raw specs keyed by name (for on-demand +* recompilation with dynamic response formats), and descriptions. +*/ +function getSubagents(options) { + const { defaultModel, defaultTools, defaultMiddleware, generalPurposeMiddleware: gpMiddleware, defaultInterruptOn, subagents, generalPurposeAgent } = options; + const defaultSubagentMiddleware = defaultMiddleware || []; + const generalPurposeMiddlewareBase = gpMiddleware || defaultSubagentMiddleware; + const agents = {}; + const specsByName = {}; + const subagentDescriptions = []; + if (generalPurposeAgent) { + const generalPurposeMiddleware = [...generalPurposeMiddlewareBase]; + if (defaultInterruptOn) generalPurposeMiddleware.push(humanInTheLoopMiddleware({ interruptOn: defaultInterruptOn })); + const gpSpec = { + name: "general-purpose", + description: DEFAULT_GENERAL_PURPOSE_DESCRIPTION, + model: defaultModel, + systemPrompt: DEFAULT_SUBAGENT_PROMPT, + tools: defaultTools, + middleware: generalPurposeMiddleware + }; + agents["general-purpose"] = createSubAgent(gpSpec); + specsByName["general-purpose"] = gpSpec; + subagentDescriptions.push(`- general-purpose: ${DEFAULT_GENERAL_PURPOSE_DESCRIPTION}`); + } + for (const agentParams of subagents) { + subagentDescriptions.push(`- ${agentParams.name}: ${agentParams.description}`); + if ("runnable" in agentParams) { + agents[agentParams.name] = agentParams.runnable; + specsByName[agentParams.name] = agentParams; + } else { + const resolvedSpec = { + ...agentParams, + model: agentParams.model ?? defaultModel, + tools: agentParams.tools ?? defaultTools, + middleware: [...defaultSubagentMiddleware, ...agentParams.middleware ?? []], + interruptOn: agentParams.interruptOn ?? defaultInterruptOn ?? void 0 + }; + agents[agentParams.name] = createSubAgent(resolvedSpec); + specsByName[agentParams.name] = resolvedSpec; + } + } + return { + agents, + specsByName, + descriptions: subagentDescriptions + }; +} +/** +* Create the task tool for invoking subagents +*/ +function createTaskTool(options) { + const { defaultModel, defaultTools, defaultMiddleware, generalPurposeMiddleware, defaultInterruptOn, subagents, generalPurposeAgent, taskDescription } = options; + const { agents: subagentGraphs, specsByName, descriptions: subagentDescriptions } = getSubagents({ + defaultModel, + defaultTools, + defaultMiddleware, + generalPurposeMiddleware, + defaultInterruptOn, + subagents, + generalPurposeAgent + }); + function selectSubagent(subagentType, config) { + const responseFormat = config.configurable?.[SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY]; + if (responseFormat != null) { + const spec = specsByName[subagentType]; + if ("runnable" in spec) throw new Error(`responseSchema cannot be used with compiled subagent "${spec.name}"; dynamic schemas require a declarative SubAgent spec.`); + return createSubAgent(spec, { responseFormat }); + } + return subagentGraphs[subagentType]; + } + return tool$1(async (input, config) => { + const { description, subagent_type } = input; + if (!(subagent_type in subagentGraphs)) { + const allowedTypes = Object.keys(subagentGraphs).map((k) => `\`${k}\``).join(", "); + throw new Error(`Error: invoked agent of type ${subagent_type}, the only allowed types are ${allowedTypes}`); + } + const subagent = selectSubagent(subagent_type, config); + const subagentState = filterStateForSubagent(getCurrentTaskInput()); + subagentState.messages = [new HumanMessage({ content: description })]; + const subagentConfig = { + ...config, + metadata: { + ...config.metadata, + lc_agent_name: subagent_type + }, + configurable: { + ...config.configurable, + ls_agent_type: "subagent" + } + }; + const result = await subagent.invoke(subagentState, subagentConfig); + if (!config.toolCall?.id) { + if (result.structuredResponse != null) return JSON.stringify(result.structuredResponse); + const messages = result.messages; + let content = (messages?.[messages.length - 1])?.content || "Task completed"; + if (Array.isArray(content)) { + content = content.filter((block) => !INVALID_TOOL_MESSAGE_BLOCK_TYPES.includes(block.type)); + if (content.length === 0) return "Task completed"; + return content.map((block) => "text" in block ? block.text : JSON.stringify(block)).join("\n"); + } + return content; + } + return returnCommandWithStateUpdate(result, config.toolCall.id); + }, { + name: "task", + description: taskDescription ? taskDescription : getTaskToolDescription(subagentDescriptions), + schema: object({ + description: string().describe("The task to execute with the selected agent"), + subagent_type: string().describe(`Name of the agent to use. Available: ${Object.keys(subagentGraphs).join(", ")}`) + }) + }); +} +/** +* Create subagent middleware with task tool +*/ +function createSubAgentMiddleware(options) { + const { defaultModel, defaultTools = [], defaultMiddleware = null, generalPurposeMiddleware = null, defaultInterruptOn = null, subagents = [], systemPrompt = null, generalPurposeAgent = true, taskDescription = null } = options; + return createMiddleware({ + name: "subAgentMiddleware", + tools: [createTaskTool({ + defaultModel, + defaultTools, + defaultMiddleware, + generalPurposeMiddleware, + defaultInterruptOn, + subagents, + generalPurposeAgent, + taskDescription + })], + wrapModelCall: async (request, handler) => { + if (systemPrompt !== null) return handler({ + ...request, + systemMessage: request.systemMessage.concat(new SystemMessage({ content: systemPrompt })) + }); + return handler(request); + } + }); +} +/** +* Patch tool call / tool response parity in a messages array. +* +* Ensures strict 1:1 correspondence between AIMessage tool_calls and +* ToolMessage responses: +* +* 1. **Dangling tool_calls** — an AIMessage contains a tool_call with no +* matching ToolMessage anywhere after it. A synthetic cancellation +* ToolMessage is inserted immediately after the AIMessage. +* +* 2. **Orphaned ToolMessages** — a ToolMessage whose `tool_call_id` does not +* match any tool_call in a preceding AIMessage. The ToolMessage is removed. +* +* Both directions are required for providers that enforce strict parity +* (e.g. Google Gemini returns 400 INVALID_ARGUMENT otherwise). +* +* @param messages - The messages array to patch +* @returns Object with patched messages and needsPatch flag +*/ +function patchDanglingToolCalls(messages) { + if (!messages || messages.length === 0) return { + patchedMessages: [], + needsPatch: false + }; + const allToolCallIds = /* @__PURE__ */ new Set(); + for (const msg of messages) if (AIMessage.isInstance(msg) && msg.tool_calls != null) { + for (const tc of msg.tool_calls) if (tc.id) allToolCallIds.add(tc.id); + } + const patchedMessages = []; + let needsPatch = false; + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; + if (ToolMessage.isInstance(msg)) { + if (!allToolCallIds.has(msg.tool_call_id)) { + needsPatch = true; + continue; + } + } + patchedMessages.push(msg); + if (AIMessage.isInstance(msg) && msg.tool_calls != null) { + for (const toolCall of msg.tool_calls) if (!messages.slice(i + 1).find((m) => ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id)) { + needsPatch = true; + const toolMsg = `Tool call ${toolCall.name} with id ${toolCall.id} was cancelled - another message came in before it could be completed.`; + patchedMessages.push(new ToolMessage({ + content: toolMsg, + name: toolCall.name, + tool_call_id: toolCall.id + })); + } + } + } + return { + patchedMessages, + needsPatch + }; +} +/** +* Create middleware that enforces strict tool call / tool response parity in +* the messages history. +* +* Two kinds of violations are repaired: +* 1. **Dangling tool_calls** — an AIMessage contains tool_calls with no +* matching ToolMessage responses. Synthetic cancellation ToolMessages are +* injected so every tool_call has a response. +* 2. **Orphaned ToolMessages** — a ToolMessage exists whose `tool_call_id` +* does not match any tool_call in a preceding AIMessage. These are removed. +* +* This is critical for providers like Google Gemini that reject requests with +* mismatched function call / function response counts (400 INVALID_ARGUMENT). +* +* This middleware patches in two places: +* 1. `beforeAgent`: Patches state at the start of the agent loop (handles most cases) +* 2. `wrapModelCall`: Patches the request right before model invocation (handles +* edge cases like HITL rejection during graph resume where state updates from +* beforeAgent may not be applied in time) +* +* @returns AgentMiddleware that enforces tool call / response parity +* +* @example +* ```typescript +* import { createAgent } from "langchain"; +* import { createPatchToolCallsMiddleware } from "./middleware/patch_tool_calls"; +* +* const agent = createAgent({ +* model: "claude-sonnet-4-5-20250929", +* middleware: [createPatchToolCallsMiddleware()], +* }); +* ``` +*/ +function createPatchToolCallsMiddleware() { + return createMiddleware({ + name: "patchToolCallsMiddleware", + beforeAgent: async (state) => { + const messages = state.messages; + if (!messages || messages.length === 0) return; + const { patchedMessages, needsPatch } = patchDanglingToolCalls(messages); + /** + * Only trigger REMOVE_ALL_MESSAGES if patching is actually needed + */ + if (!needsPatch) return; + return { messages: [new RemoveMessage({ id: REMOVE_ALL_MESSAGES }), ...patchedMessages] }; + }, + /** + * Also patch in wrapModelCall as a safety net. + * This handles edge cases where: + * - HITL rejects a tool call during graph resume + * - The state update from beforeAgent might not be applied in time + * - The model would otherwise receive dangling tool_call_ids + */ + wrapModelCall: async (request, handler) => { + const messages = request.messages; + if (!messages || messages.length === 0) return handler(request); + const { patchedMessages, needsPatch } = patchDanglingToolCalls(messages); + if (!needsPatch) return handler(request); + return handler({ + ...request, + messages: patchedMessages + }); + } + }); +} +/** +* Shared state values for use in StateSchema definitions. +* +* This module provides pre-configured ReducedValue instances that can be +* reused across different state schemas, similar to LangGraph's messagesValue. +*/ +/** +* Shared ReducedValue for file data state management. +* +* This provides a reusable pattern for managing file state with automatic +* merging of concurrent updates from parallel subagents. Files can be updated +* or deleted (using null values) and the reducer handles the merge logic. +* +* Similar to LangGraph's messagesValue, this encapsulates the common pattern +* of managing files in agent state so you don't have to manually configure +* the ReducedValue each time. +* +* @example +* ```typescript +* import { filesValue } from "@anthropic/deepagents"; +* import { StateSchema } from "@langchain/langgraph"; +* +* const MyStateSchema = new StateSchema({ +* files: filesValue, +* // ... other state fields +* }); +* ``` +*/ +var filesValue = new ReducedValue(record(string(), FileDataSchema).default(() => ({})), { + inputSchema: record(string(), FileDataSchema.nullable()).optional(), + reducer: fileDataReducer +}); +/** +* Detect whether a model is an Anthropic model. +* +* Used to gate Anthropic-specific prompt caching optimizations +* (cache_control breakpoints). +* +* Accepts the wider `RunnableInterface` shape (the type of `request.model` +* inside `wrapModelCall`, aliased as `AgentLanguageModelLike` in langchain) +* because the function only depends on `.getName()`, which is part of the +* Runnable contract. `BaseLanguageModel` extends `Runnable`, so existing +* call sites still type-check. +*/ +function isAnthropicModel(model) { + if (typeof model === "string") { + if (model.includes(":")) return model.split(":")[0] === "anthropic"; + return model.startsWith("claude"); + } + if (model.getName() === "ConfigurableModel") return model._defaultConfig?.modelProvider === "anthropic"; + return model.getName() === "ChatAnthropic"; +} +/** +* Detect whether a model is an AWS Bedrock Converse model. +* +* Accepts the wider `RunnableInterface` shape (the type of `request.model` +* inside `wrapModelCall`, aliased as `AgentLanguageModelLike` in langchain) +* because the function only depends on `.getName()`, which is part of the +* Runnable contract. `BaseLanguageModel` extends `Runnable`, so existing +* call sites still type-check. +*/ +function isBedrockConverseModel(model) { + if (typeof model === "string") { + const colonIdx = model.indexOf(":"); + if (colonIdx !== -1) { + const prefix = model.slice(0, colonIdx); + if (prefix === "bedrock" || prefix === "aws") return true; + } + return model.startsWith("amazon."); + } + if (model.getName() === "ConfigurableModel") { + const provider = model._defaultConfig?.modelProvider; + return provider === "bedrock" || provider === "aws"; + } + return model.getName() === "ChatBedrockConverse"; +} +/** +* Extract the provider name from a model instance for profile lookup. +* +* Checks `_defaultConfig.modelProvider` (ConfigurableModel) and falls +* back to known model class name → provider mappings. +* +* @internal +*/ +function getModelProvider(model) { + if (model.getName() === "ConfigurableModel") return model._defaultConfig?.modelProvider; + return { + ChatAnthropic: "anthropic", + ChatOpenAI: "openai", + ChatGoogleGenerativeAI: "google" + }[model.getName()]; +} +/** +* Extract the model identifier from a model instance for profile +* lookup. +* +* Checks `_defaultConfig.model`, `model_name`, and `modelName` in +* that order. +* +* @internal +*/ +function getModelIdentifier(model) { + return (model.getName() === "ConfigurableModel" ? model._defaultConfig : void 0)?.model ?? model.model_name ?? model.modelName ?? void 0; +} +/** +* Middleware for loading agent memory/context from AGENTS.md files. +* +* This module implements support for the AGENTS.md specification (https://agents.md/), +* loading memory/context from configurable sources and injecting into the system prompt. +* +* ## Overview +* +* AGENTS.md files provide project-specific context and instructions to help AI agents +* work effectively. Unlike skills (which are on-demand workflows), memory is always +* loaded and provides persistent context. +* +* ## Usage +* +* ```typescript +* import { createMemoryMiddleware } from "@anthropic/deepagents"; +* import { FilesystemBackend } from "@anthropic/deepagents"; +* +* // Security: FilesystemBackend allows reading/writing from the entire filesystem. +* // Either ensure the agent is running within a sandbox OR add human-in-the-loop (HIL) +* // approval to file operations. +* const backend = new FilesystemBackend({ rootDir: "/" }); +* +* const middleware = createMemoryMiddleware({ +* backend, +* sources: [ +* "~/.deepagents/AGENTS.md", +* "./.deepagents/AGENTS.md", +* ], +* }); +* +* const agent = createDeepAgent({ middleware: [middleware] }); +* ``` +* +* ## Memory Sources +* +* Sources are simply paths to AGENTS.md files that are loaded in order and combined. +* Multiple sources are concatenated in order, with all content included. +* Later sources appear after earlier ones in the combined prompt. +* +* ## File Format +* +* AGENTS.md files are standard Markdown with no required structure. +* Common sections include: +* - Project overview +* - Build/test commands +* - Code style guidelines +* - Architecture notes +*/ +/** +* State schema for memory middleware. +*/ +var MemoryStateSchema = new StateSchema({ + /** + * Dict mapping source paths to their loaded content. + * Marked as private so it's not included in the final agent state. + */ + memoryContents: record(string(), string()).optional(), + files: filesValue +}); +/** +* Default system prompt template for memory. +* Ported from Python's comprehensive memory guidelines. +*/ +var MEMORY_SYSTEM_PROMPT = context` + + {memory_contents} + + + + The above was loaded in from files in your filesystem. As you learn from your interactions with the user, you can save new knowledge by calling the \`edit_file\` tool. + + **Learning from feedback:** + - One of your MAIN PRIORITIES is to learn from your interactions with the user. These learnings can be implicit or explicit. This means that in the future, you will remember this important information. + - When you need to remember something, updating memory must be your FIRST, IMMEDIATE action - before responding to the user, before calling other tools, before doing anything else. Just update memory immediately. + - When user says something is better/worse, capture WHY and encode it as a pattern. + - Each correction is a chance to improve permanently - don't just fix the immediate issue, update your instructions. + - A great opportunity to update your memories is when the user interrupts a tool call and provides feedback. You should update your memories immediately before revising the tool call. + - Look for the underlying principle behind corrections, not just the specific mistake. + - The user might not explicitly ask you to remember something, but if they provide information that is useful for future use, you should update your memories immediately. + + **Asking for information:** + - If you lack context to perform an action (e.g. send a Slack DM, requires a user ID/email) you should explicitly ask the user for this information. + - It is preferred for you to ask for information, don't assume anything that you do not know! + - When the user provides information that is useful for future use, you should update your memories immediately. + + **When to update memories:** + - When the user explicitly asks you to remember something (e.g., "remember my email", "save this preference") + - When the user describes your role or how you should behave (e.g., "you are a web researcher", "always do X") + - When the user gives feedback on your work - capture what was wrong and how to improve + - When the user provides information required for tool use (e.g., slack channel ID, email addresses) + - When the user provides context useful for future tasks, such as how to use tools, or which actions to take in a particular situation + - When you discover new patterns or preferences (coding styles, conventions, workflows) + + **When to NOT update memories:** + - When the information is temporary or transient (e.g., "I'm running late", "I'm on my phone right now") + - When the information is a one-time task request (e.g., "Find me a recipe", "What's 25 * 4?") + - When the information is a simple question that doesn't reveal lasting preferences (e.g., "What day is it?", "Can you explain X?") + - When the information is an acknowledgment or small talk (e.g., "Sounds good!", "Hello", "Thanks for that") + - When the information is stale or irrelevant in future conversations + - Never store API keys, access tokens, passwords, or any other credentials in any file, memory, or system prompt. + - If the user asks where to put API keys or provides an API key, do NOT echo or save it. + + **Examples:** + Example 1 (remembering user information): + User: Can you connect to my google account? + Agent: Sure, I'll connect to your google account, what's your google account email? + User: john@example.com + Agent: Let me save this to my memory. + Tool Call: edit_file(...) -> remembers that the user's google account email is john@example.com + + Example 2 (remembering implicit user preferences): + User: Can you write me an example for creating a deep agent in LangChain? + Agent: Sure, I'll write you an example for creating a deep agent in LangChain + User: Can you do this in JavaScript + Agent: Let me save this to my memory. + Tool Call: edit_file(...) -> remembers that the user prefers to get LangChain code examples in JavaScript + Agent: Sure, here is the JavaScript example + + Example 3 (do not remember transient information): + User: I'm going to play basketball tonight so I will be offline for a few hours. + Agent: Okay I'll add a block to your calendar. + Tool Call: create_calendar_event(...) -> just calls a tool, does not commit anything to memory, as it is transient information + +`; +/** +* Format loaded memory contents for injection into prompt. +* Pairs memory locations with their contents for clarity. +*/ +function formatMemoryContents(contents, sources) { + if (Object.keys(contents).length === 0) return "(No memory loaded)"; + const sections = []; + for (const path of sources) if (contents[path]) sections.push(`${path}\n${contents[path]}`); + if (sections.length === 0) return "(No memory loaded)"; + return sections.join("\n\n"); +} +/** +* Load memory content from a backend path. +* +* @param backend - Backend to load from. +* @param path - Path to the AGENTS.md file. +* @returns File content if found, null otherwise. +*/ +async function loadMemoryFromBackend(backend, path) { + const adaptedBackend = adaptBackendProtocol(backend); + if (!adaptedBackend.downloadFiles) { + const content = await adaptedBackend.read(path); + if (content.error) return null; + if (typeof content.content !== "string") return null; + return content.content; + } + const results = await adaptedBackend.downloadFiles([path]); + if (results.length !== 1) throw new Error(`Expected 1 response for path ${path}, got ${results.length}`); + const response = results[0]; + if (response.error != null) { + if (response.error === "file_not_found") return null; + throw new Error(`Failed to download ${path}: ${response.error}`); + } + if (response.content != null) return new TextDecoder().decode(response.content); + return null; +} +/** +* Create middleware for loading agent memory from AGENTS.md files. +* +* Loads memory content from configured sources and injects into the system prompt. +* Supports multiple sources that are combined together. +* +* @param options - Configuration options +* @returns AgentMiddleware for memory loading and injection +* +* @example +* ```typescript +* const middleware = createMemoryMiddleware({ +* backend: new FilesystemBackend({ rootDir: "/" }), +* sources: [ +* "~/.deepagents/AGENTS.md", +* "./.deepagents/AGENTS.md", +* ], +* }); +* ``` +*/ +function createMemoryMiddleware(options) { + const { backend, sources, addCacheControl = false } = options; + return createMiddleware({ + name: "MemoryMiddleware", + stateSchema: MemoryStateSchema, + async beforeAgent(state) { + if ("memoryContents" in state && state.memoryContents != null) return; + const resolvedBackend = await resolveBackend(backend, { state }); + const contents = {}; + for (const path of sources) try { + const content = await loadMemoryFromBackend(resolvedBackend, path); + if (content) contents[path] = content; + } catch (error) { + console.debug(`Failed to load memory from ${path}:`, error); + } + return { memoryContents: contents }; + }, + wrapModelCall(request, handler) { + const formattedContents = formatMemoryContents(request.state?.memoryContents || {}, sources); + const memorySection = MEMORY_SYSTEM_PROMPT.replace("{memory_contents}", formattedContents); + const existingContent = request.systemMessage.content; + const existingBlocks = typeof existingContent === "string" ? [{ + type: "text", + text: existingContent + }] : Array.isArray(existingContent) ? existingContent : []; + const writeCacheControl = addCacheControl && isAnthropicModel(request.model); + const newSystemMessage = new SystemMessage({ content: [...existingBlocks, { + type: "text", + text: memorySection, + ...writeCacheControl && { cache_control: { type: "ephemeral" } } + }] }); + return handler({ + ...request, + systemMessage: newSystemMessage + }); + } + }); +} +var DEFAULT_SKILL_READ_LINE_LIMIT = 1e3; +var MAX_SKILL_DESCRIPTION_LENGTH = 1024; +/** +* File extensions a skill module entrypoint may use. +*/ +var SKILL_MODULE_EXTENSIONS = [ + ".js", + ".mjs", + ".cjs", + ".ts", + ".mts", + ".cts", + ".jsx", + ".tsx" +]; +/** +* Zod schema for a single skill metadata entry. +*/ +var SkillMetadataEntrySchema = object({ + name: string(), + description: string(), + path: string(), + license: string().nullable().optional(), + compatibility: string().nullable().optional(), + metadata: record(string(), string()).optional(), + allowedTools: array(string()).optional(), + module: string().optional() +}); +/** +* Reducer for skillsMetadata that merges arrays from parallel subagents. +* Skills are deduplicated by name, with later values overriding earlier ones. +* +* @param current - The current skillsMetadata array (from state) +* @param update - The new skillsMetadata array (from a subagent update) +* @returns Merged array with duplicates resolved by name (later values win) +*/ +function skillsMetadataReducer(current, update) { + if (!update || update.length === 0) return current || []; + if (!current || current.length === 0) return update; + const merged = /* @__PURE__ */ new Map(); + for (const skill of current) merged.set(skill.name, skill); + for (const skill of update) merged.set(skill.name, skill); + return Array.from(merged.values()); +} +/** +* State schema for skills middleware. +* Uses ReducedValue for skillsMetadata to allow concurrent updates from parallel subagents. +*/ +var SkillsStateSchema = new StateSchema({ + skillsMetadata: new ReducedValue(array(SkillMetadataEntrySchema).default(() => []), { + inputSchema: array(SkillMetadataEntrySchema).optional(), + reducer: skillsMetadataReducer + }), + files: filesValue +}); +/** +* Skills System Documentation prompt template. +*/ +var SKILLS_SYSTEM_PROMPT = context` + ## Skills System + + You have access to a skills library that provides specialized capabilities and domain knowledge. + + {skills_locations} + + **Available Skills:** + + {skills_list} + + **How to Use Skills (Progressive Disclosure):** + + Skills follow a **progressive disclosure** pattern - you know they exist (name + description above), but you only read the full instructions when needed: + + 1. **Recognize when a skill applies**: Check if the user's task matches any skill's description + 2. **Read the skill's full instructions**: Use \`read_file\` on the path shown in the skill list above. + Pass \`limit=${DEFAULT_SKILL_READ_LINE_LIMIT}\` since the default of ${100} lines is too small for most skill files. + 3. **Follow the skill's instructions**: SKILL.md contains step-by-step workflows, best practices, and examples + 4. **Access supporting files**: Skills may include scripts, configs, or reference docs - use absolute paths + + **When to Use Skills:** + - When the user's request matches a skill's domain (e.g., "research X" → web-research skill) + - When you need specialized knowledge or structured workflows + - When a skill provides proven patterns for complex tasks + **Skills are Self-Documenting:** + - Each SKILL.md tells you exactly what the skill does and how to use it + - The skill list above shows the full path for each skill's SKILL.md file + + **Executing Skill Scripts:** + Skills may contain scripts or other executable files. Always use absolute paths from the skill list. + + **Example Workflow:** + + User: "Can you research the latest developments in quantum computing?" + + 1. Check available skills above → See "web-research" skill with its full path + 2. Read the full skill file: \`read_file(file_path, limit=${DEFAULT_SKILL_READ_LINE_LIMIT})\` + 3. Follow the skill's research workflow (search → organize → synthesize) + 4. Use any helper scripts with absolute paths + + Remember: Skills are tools to make you more capable and consistent. When in doubt, check if a skill exists for the task! +`; +/** +* Validate skill name per Agent Skills specification. +* +* Constraints per Agent Skills specification: +* +* - 1-64 characters +* - Unicode lowercase alphanumeric and hyphens only (`a-z` and `-`). +* - Must not start or end with `-` +* - Must not contain consecutive `--` +* - Must match the parent directory name containing the `SKILL.md` file +* +* Unicode lowercase alphanumeric means any lowercase or decimal digit, which +* covers accented Latin characters (e.g., `'café'`, `'über-tool'`) and other +* scripts. +* +* @param name - The skill name from YAML frontmatter +* @param directoryName - The parent directory name +* @returns `{ valid, error }` tuple. Error is empty string if valid. +*/ +function validateSkillName(name, directoryName) { + if (!name) return { + valid: false, + error: "name is required" + }; + if (name.length > 64) return { + valid: false, + error: "name exceeds 64 characters" + }; + if (name.startsWith("-") || name.endsWith("-") || name.includes("--")) return { + valid: false, + error: "name must be lowercase alphanumeric with single hyphens only" + }; + for (const c of name) { + if (c === "-") continue; + if (/\p{Ll}/u.test(c) || /\p{Nd}/u.test(c)) continue; + return { + valid: false, + error: "name must be lowercase alphanumeric with single hyphens only" + }; + } + if (name !== directoryName) return { + valid: false, + error: `name '${name}' must match directory name '${directoryName}'` + }; + return { + valid: true, + error: "" + }; +} +/** +* Validate and normalize the metadata field from YAML frontmatter. +* +* YAML parsing can return any type for the `metadata` key. This ensures the +* value in {@link SkillMetadata} is always a `Record` by +* coercing via `String()` and rejecting non-object inputs. +* +* @param raw - Raw value from `frontmatterData.metadata`. +* @param skillPath - Path to the `SKILL.md` file (for warning messages). +* @returns A validated `Record`. +*/ +function validateMetadata(raw, skillPath) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + if (raw) console.warn(`Ignoring non-object metadata in ${skillPath} (got ${typeof raw})`); + return {}; + } + const result = {}; + for (const [k, v] of Object.entries(raw)) result[String(k)] = String(v); + return result; +} +/** +* Build a parenthetical annotation string from optional skill fields. +* +* Combines license and compatibility into a comma-separated string for +* display in the system prompt skill listing. +* +* @param skill - Skill metadata to extract annotations from. +* @returns Annotation string like `'License: MIT, Compatibility: Python 3.10+'`, +* or empty string if neither field is set. +*/ +function formatSkillAnnotations(skill) { + const parts = []; + if (skill.license) parts.push(`License: ${skill.license}`); + if (skill.compatibility) parts.push(`Compatibility: ${skill.compatibility}`); + return parts.join(", "); +} +/** +* Parse YAML frontmatter from `SKILL.md` content. +* +* Extracts metadata per Agent Skills specification from YAML frontmatter +* delimited by `---` markers at the start of the content. +* +* @param content - Content of the `SKILL.md` file +* @param skillPath - Path to the `SKILL.md` file (for error messages and metadata) +* @param directoryName - Name of the parent directory containing the skill +* @returns `SkillMetadata` if parsing succeeds, `null` if parsing fails or +* validation errors occur +*/ +function parseSkillMetadataFromContent(content, skillPath, directoryName) { + if (content.length > 10485760) { + console.warn(`Skipping ${skillPath}: content too large (${content.length} bytes)`); + return null; + } + const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/); + if (!match) { + console.warn(`Skipping ${skillPath}: no valid YAML frontmatter found`); + return null; + } + const frontmatterStr = match[1]; + let frontmatterData; + try { + frontmatterData = import_dist.parse(frontmatterStr); + } catch (e) { + console.warn(`Invalid YAML in ${skillPath}:`, e); + return null; + } + if (!frontmatterData || typeof frontmatterData !== "object") { + console.warn(`Skipping ${skillPath}: frontmatter is not a mapping`); + return null; + } + const name = String(frontmatterData.name ?? "").trim(); + const description = String(frontmatterData.description ?? "").trim(); + if (!name || !description) { + console.warn(`Skipping ${skillPath}: missing required 'name' or 'description'`); + return null; + } + const validation = validateSkillName(name, directoryName); + if (!validation.valid) console.warn(`Skill '${name}' in ${skillPath} does not follow Agent Skills specification: ${validation.error}. Consider renaming for spec compliance.`); + let descriptionStr = description; + if (descriptionStr.length > 1024) { + console.warn(`Description exceeds ${MAX_SKILL_DESCRIPTION_LENGTH} characters in ${skillPath}, truncating`); + descriptionStr = descriptionStr.slice(0, MAX_SKILL_DESCRIPTION_LENGTH); + } + const rawTools = frontmatterData["allowed-tools"]; + let allowedTools; + if (rawTools) if (Array.isArray(rawTools)) allowedTools = rawTools.map((t) => String(t).trim()).filter(Boolean); + else allowedTools = String(rawTools).split(/\s+/).filter(Boolean); + else allowedTools = []; + let compatibilityStr = String(frontmatterData.compatibility ?? "").trim() || null; + if (compatibilityStr && compatibilityStr.length > 500) { + console.warn(`Compatibility exceeds 500 characters in ${skillPath}, truncating`); + compatibilityStr = compatibilityStr.slice(0, 500); + } + return { + name, + description: descriptionStr, + path: skillPath, + metadata: validateMetadata(frontmatterData.metadata ?? {}, skillPath), + license: String(frontmatterData.license ?? "").trim() || null, + compatibility: compatibilityStr, + allowedTools, + module: validateModulePath(frontmatterData.module) + }; +} +/** +* Read a single file from the backend, returning its content as a string or +* null if the file does not exist or cannot be read. +*/ +async function readFileFromBackend(backend, filePath) { + if (backend.downloadFiles) { + const results = await backend.downloadFiles([filePath]); + if (results.length !== 1) return null; + const response = results[0]; + if (response.error != null || response.content == null) return null; + return new TextDecoder().decode(response.content); + } + const readResult = await backend.read(filePath); + if (readResult.error) return null; + if (typeof readResult.content !== "string") return null; + return readResult.content; +} +/** +* List all skills from a backend source. +* +* Supports two source formats: +* +* - **Parent directory** (e.g. `"/skills/"`): the directory is scanned for +* subdirectories, each of which must contain a `SKILL.md` file. This is the +* standard pattern for hosting a collection of skills in one place. +* +* - **Direct skill path** (e.g. `"/skills/my-skill/"`): the path points to a +* single skill directory that contains `SKILL.md` directly. Detected +* automatically when the directory listing includes a `SKILL.md` file entry. +*/ +async function listSkillsFromBackend(backend, sourcePath) { + const adaptedBackend = adaptBackendProtocol(backend); + const skills = []; + const pathSep = sourcePath.includes("\\") ? "\\" : "/"; + const normalizedPath = sourcePath.endsWith("/") || sourcePath.endsWith("\\") ? sourcePath : `${sourcePath}${pathSep}`; + let fileInfos; + try { + const lsResult = await adaptedBackend.ls(normalizedPath); + if (lsResult.error || !lsResult.files) return []; + fileInfos = lsResult.files; + } catch { + return []; + } + const entries = fileInfos.map((info) => ({ + name: info.path.replace(/[/\\]$/, "").split(/[/\\]/).pop() || "", + type: info.is_dir ? "directory" : "file" + })); + if (entries.some((e) => e.type === "file" && e.name === "SKILL.md")) { + const directoryName = normalizedPath.replace(/[/\\]$/, "").split(/[/\\]/).pop() || ""; + const skillMdPath = `${normalizedPath}SKILL.md`; + const content = await readFileFromBackend(adaptedBackend, skillMdPath); + if (content !== null) { + const metadata = parseSkillMetadataFromContent(content, skillMdPath, directoryName); + if (metadata) skills.push(metadata); + } + return skills; + } + for (const entry of entries) { + if (entry.type !== "directory") continue; + const skillMdPath = `${normalizedPath}${entry.name}${pathSep}SKILL.md`; + const content = await readFileFromBackend(adaptedBackend, skillMdPath); + if (content === null) continue; + const metadata = parseSkillMetadataFromContent(content, skillMdPath, entry.name); + if (metadata) skills.push(metadata); + } + return skills; +} +/** +* Format skills locations for display in system prompt. +* Shows priority indicator for the last source (highest priority). +*/ +function formatSkillsLocations(sources) { + if (sources.length === 0) return "**Skills Sources:** None configured"; + const lines = []; + for (let i = 0; i < sources.length; i++) { + const sourcePath = sources[i]; + const name = sourcePath.replace(/[/\\]$/, "").split(/[/\\]/).filter(Boolean).pop()?.replace(/^./, (c) => c.toUpperCase()) || "Skills"; + const suffix = i === sources.length - 1 ? " (higher priority)" : ""; + lines.push(`**${name} Skills**: \`${sourcePath}\`${suffix}`); + } + return lines.join("\n"); +} +/** +* Format skills metadata for display in system prompt. +* Shows allowed tools for each skill if specified. +*/ +function formatSkillsList(skills, sources) { + if (skills.length === 0) return `(No skills available yet. You can create skills in ${sources.map((s) => `\`${s}\``).join(" or ")})`; + const lines = []; + for (const skill of skills) { + const annotations = formatSkillAnnotations(skill); + let descLine = `- **${skill.name}**: ${skill.description}`; + if (annotations) descLine += ` (${annotations})`; + lines.push(descLine); + if (skill.allowedTools && skill.allowedTools.length > 0) lines.push(` → Allowed tools: ${skill.allowedTools.join(", ")}`); + lines.push(` → Read \`${skill.path}\` for full instructions`); + if (skill.module !== void 0) lines.push(` → Import: \`await import("@/skills/${skill.name}")\``); + } + return lines.join("\n"); +} +/** +* Returns true when `value` ends with a recognized skill module extension. +*/ +function endsWithModuleExtension(value) { + for (const ext of SKILL_MODULE_EXTENSIONS) if (value.endsWith(ext)) return true; + return false; +} +/** +* Validate and normalize the `module` frontmatter key from a `SKILL.md`. +* +* Returns the normalized path (e.g. `"index.ts"`, `"lib/entry.js"`) or +* `undefined` when the key is absent, empty, non-string, absolute, contains +* path traversal, or uses an unsupported extension. Invalid values silently +* degrade the skill to prose-only. +*/ +function validateModulePath(raw) { + if (raw === null || raw === void 0) return; + if (typeof raw !== "string") return; + const stripped = raw.trim(); + if (stripped === "") return; + const normalized = stripped.startsWith("./") ? stripped.slice(2) : stripped; + if (normalized.startsWith("/")) return; + if (normalized === ".." || normalized.startsWith("../") || normalized.includes("/../") || normalized.endsWith("/..")) return; + if (normalized.endsWith(".d.ts") || normalized.endsWith(".d.mts") || normalized.endsWith(".d.cts")) return; + if (!endsWithModuleExtension(normalized)) return; + return normalized; +} +/** +* Create backend-agnostic middleware for loading and exposing agent skills. +* +* This middleware loads skills from configurable backend sources and injects +* skill metadata into the system prompt. It implements the progressive disclosure +* pattern: skill names and descriptions are shown in the prompt, but the agent +* reads full SKILL.md content only when needed. +* +* @param options - Configuration options +* @returns AgentMiddleware for skills loading and injection +* +* @example +* ```typescript +* const middleware = createSkillsMiddleware({ +* backend: new FilesystemBackend({ rootDir: "/" }), +* sources: ["/skills/user/", "/skills/project/"], +* }); +* ``` +*/ +function createSkillsMiddleware(options) { + const { backend, sources } = options; + let loadedSkills = []; + return createMiddleware({ + name: "SkillsMiddleware", + stateSchema: SkillsStateSchema, + async beforeAgent(state) { + const stateHasSkills = "skillsMetadata" in state && Array.isArray(state.skillsMetadata) && state.skillsMetadata.length > 0; + if (loadedSkills.length > 0) return stateHasSkills ? void 0 : { skillsMetadata: loadedSkills }; + if (stateHasSkills) { + loadedSkills = state.skillsMetadata; + return; + } + const resolvedBackend = await resolveBackend(backend, { state }); + const allSkills = /* @__PURE__ */ new Map(); + for (const sourcePath of sources) try { + const skills = await listSkillsFromBackend(resolvedBackend, sourcePath); + for (const skill of skills) allSkills.set(skill.name, skill); + } catch (error) { + console.debug(`[BackendSkillsMiddleware] Failed to load skills from ${sourcePath}:`, error); + } + loadedSkills = Array.from(allSkills.values()); + return { skillsMetadata: loadedSkills }; + }, + wrapModelCall(request, handler) { + const skillsMetadata = loadedSkills.length > 0 ? loadedSkills : request.state?.skillsMetadata || []; + const skillsLocations = formatSkillsLocations(sources); + const skillsList = formatSkillsList(skillsMetadata, sources); + const skillsSection = SKILLS_SYSTEM_PROMPT.replace("{skills_locations}", skillsLocations).replace("{skills_list}", skillsList); + const newSystemMessage = request.systemMessage.concat(skillsSection); + return handler({ + ...request, + systemMessage: newSystemMessage + }); + } + }); +} +/** +* Merge custom middleware into an assembled stack by `.name`. +* +* Matching custom middleware replaces the existing entry in place. New +* middleware is appended after the base stack in caller-provided order. +*/ +function mergeMiddleware$1(base, custom) { + const merged = new Map(base.map((middleware) => [middleware.name, middleware])); + for (const middleware of custom) merged.set(middleware.name, middleware); + return [...merged.values()]; +} +function middlewareNames(middleware) { + return new Set(middleware.map((entry) => entry.name)); +} +function matchingMiddleware(middleware, names) { + return middleware.filter((entry) => names.has(entry.name)); +} +/** +* Merge custom middleware into default and tail middleware segments. +* +* Same-name custom entries replace matching defaults in either segment. Novel +* custom entries are inserted between the default and tail segments unless +* `appendNew` is false. +*/ +function mergeMiddlewareStack(defaultMiddleware, customMiddleware, tailMiddleware = [], options = {}) { + const defaultMiddlewareNames = middlewareNames(defaultMiddleware); + const tailMiddlewareNames = middlewareNames(tailMiddleware); + const knownMiddlewareNames = /* @__PURE__ */ new Set([...defaultMiddlewareNames, ...tailMiddlewareNames]); + const novelMiddleware = options.appendNew === false ? [] : customMiddleware.filter((entry) => !knownMiddlewareNames.has(entry.name)); + return [ + ...mergeMiddleware$1(defaultMiddleware, matchingMiddleware(customMiddleware, defaultMiddlewareNames)), + ...novelMiddleware, + ...mergeMiddleware$1(tailMiddleware, matchingMiddleware(customMiddleware, tailMiddlewareNames)) + ]; +} +object({ +/** The callback thread ID. Used to address the notification. */ +["callbackThreadId"]: string().optional() }); +/** +* Summarization middleware with backend support for conversation history offloading. +* +* This module extends the base LangChain summarization middleware with additional +* backend-based features for persisting conversation history before summarization. +* +* ## Usage +* +* ```typescript +* import { createSummarizationMiddleware } from "@anthropic/deepagents"; +* import { FilesystemBackend } from "@anthropic/deepagents"; +* +* const backend = new FilesystemBackend({ rootDir: "/data" }); +* +* const middleware = createSummarizationMiddleware({ +* model: "gpt-4o-mini", +* backend, +* trigger: { type: "fraction", value: 0.85 }, +* keep: { type: "fraction", value: 0.10 }, +* }); +* +* const agent = createDeepAgent({ middleware: [middleware] }); +* ``` +* +* ## Storage +* +* Offloaded messages are stored as markdown at `/conversation_history/{thread_id}.md`. +* +* Each summarization event appends a new section to this file, creating a running log +* of all evicted messages. +* +* ## Relationship to LangChain Summarization Middleware +* +* The base `summarizationMiddleware` from `langchain` provides core summarization +* functionality. This middleware adds: +* - Backend-based conversation history offloading +* - Tool argument truncation for old messages +* +* For simple use cases without backend offloading, use `summarizationMiddleware` +* from `langchain` directly. +*/ +var DEFAULT_MESSAGES_TO_KEEP = 20; +var DEFAULT_TRIM_TOKEN_LIMIT = 4e3; +var FALLBACK_TRIGGER = { + type: "tokens", + value: 17e4 +}; +var FALLBACK_KEEP = { + type: "messages", + value: 6 +}; +var FALLBACK_TRUNCATE_ARGS = { + trigger: { + type: "messages", + value: 20 + }, + keep: { + type: "messages", + value: 20 + } +}; +var PROFILE_TRIGGER = { + type: "fraction", + value: .85 +}; +var PROFILE_KEEP = { + type: "fraction", + value: .1 +}; +var PROFILE_TRUNCATE_ARGS = { + trigger: { + type: "fraction", + value: .85 + }, + keep: { + type: "fraction", + value: .1 + } +}; +/** +* Compute summarization defaults based on model profile. +* Mirrors Python's `_compute_summarization_defaults`. +* +* If the model has a profile with `maxInputTokens`, uses fraction-based +* settings. Otherwise, uses fixed token/message counts. +* +* @param resolvedModel - The resolved chat model instance. +*/ +function computeSummarizationDefaults(resolvedModel) { + if (resolvedModel.profile && typeof resolvedModel.profile === "object" && "maxInputTokens" in resolvedModel.profile && typeof resolvedModel.profile.maxInputTokens === "number") return { + trigger: PROFILE_TRIGGER, + keep: PROFILE_KEEP, + truncateArgsSettings: PROFILE_TRUNCATE_ARGS + }; + return { + trigger: FALLBACK_TRIGGER, + keep: FALLBACK_KEEP, + truncateArgsSettings: FALLBACK_TRUNCATE_ARGS + }; +} +var DEFAULT_SUMMARY_PROMPT = `You are a conversation summarizer. Your task is to create a concise summary of the conversation that captures: +1. The main topics discussed +2. Key decisions or conclusions reached +3. Any important context that would be needed for continuing the conversation + +Keep the summary focused and informative. Do not include unnecessary details. + +Conversation to summarize: +{conversation} + +Summary:`; +/** +* Zod schema for a summarization event that tracks what was summarized and +* where the cutoff is. +* +* Instead of rewriting LangGraph state with `RemoveMessage(REMOVE_ALL_MESSAGES)`, +* the middleware stores this event and uses it to reconstruct the effective message +* list on subsequent calls. +*/ +var SummarizationEventSchema = object({ + /** + * The index in the state messages list where summarization occurred. + * Messages before this index have been summarized. */ + cutoffIndex: number(), + /** The HumanMessage containing the summary. */ + summaryMessage: _instanceof(HumanMessage), + /** Path where the conversation history was offloaded, or null if offload failed. */ + filePath: string().nullable() +}); +/** +* State schema for summarization middleware. +*/ +var SummarizationStateSchema = object({ + /** Session ID for history file naming */ + _summarizationSessionId: string().optional(), + /** Most recent summarization event (private state, not visible to agent) */ + _summarizationEvent: SummarizationEventSchema.optional() +}); +/** +* Check if a message is a previous summarization message. +* Summary messages are HumanMessage objects with lc_source='summarization' in additional_kwargs. +*/ +function isSummaryMessage(msg) { + if (!HumanMessage.isInstance(msg)) return false; + return msg.additional_kwargs?.lc_source === "summarization"; +} +/** +* Create summarization middleware with backend support for conversation history offloading. +* +* This middleware: +* 1. Monitors conversation length against configured thresholds +* 2. When triggered, offloads old messages to backend storage +* 3. Generates a summary of offloaded messages +* 4. Replaces old messages with the summary, preserving recent context +* +* @param options - Configuration options +* @returns AgentMiddleware for summarization and history offloading +*/ +function createSummarizationMiddleware(options) { + const { model, backend, summaryPrompt = DEFAULT_SUMMARY_PROMPT, trimTokensToSummarize = DEFAULT_TRIM_TOKEN_LIMIT, historyPathPrefix = "/conversation_history" } = options; + let trigger = options.trigger; + let keep = options.keep ?? { + type: "messages", + value: DEFAULT_MESSAGES_TO_KEEP + }; + let truncateArgsSettings = options.truncateArgsSettings; + let defaultsComputed = trigger != null; + let truncateTrigger = truncateArgsSettings?.trigger; + let truncateKeep = truncateArgsSettings?.keep ?? { + type: "messages", + value: 20 + }; + let maxArgLength = truncateArgsSettings?.maxLength ?? 2e3; + let truncationText = truncateArgsSettings?.truncationText ?? "...(argument truncated)"; + /** + * Lazily compute defaults from model profile when trigger was not provided. + * Called once when the model is first resolved. + */ + function applyModelDefaults(resolvedModel) { + if (defaultsComputed) return; + defaultsComputed = true; + const defaults = computeSummarizationDefaults(resolvedModel); + trigger = defaults.trigger; + keep = options.keep ?? defaults.keep; + if (!options.truncateArgsSettings) { + truncateArgsSettings = defaults.truncateArgsSettings; + truncateTrigger = defaults.truncateArgsSettings.trigger; + truncateKeep = defaults.truncateArgsSettings.keep ?? { + type: "messages", + value: 20 + }; + maxArgLength = defaults.truncateArgsSettings.maxLength ?? 2e3; + truncationText = defaults.truncateArgsSettings.truncationText ?? "...(argument truncated)"; + } + } + let sessionId = null; + let tokenEstimationMultiplier = 1; + /** + * Get or create session ID for history file naming. + */ + function getSessionId(state) { + if (state._summarizationSessionId) return state._summarizationSessionId; + if (!sessionId) sessionId = `session_${crypto.randomUUID().substring(0, 8)}`; + return sessionId; + } + /** + * Get the history file path. + */ + function getHistoryPath(state) { + const id = getSessionId(state); + return `${historyPathPrefix}/${id}.md`; + } + /** + * Cached resolved model to avoid repeated initChatModel calls + */ + let cachedModel = void 0; + /** + * Resolve the chat model. + * Uses initChatModel to support any model provider from a string name. + * The resolved model is cached for subsequent calls. + */ + async function getChatModel() { + if (cachedModel) return cachedModel; + if (!model) throw new Error("Summarization middleware could not resolve a model. Provide `options.model` or ensure `request.model` is present."); + if (typeof model === "string") cachedModel = await initChatModel(model); + else cachedModel = model; + return cachedModel; + } + /** + * Get the max input tokens from the model's profile. + * Similar to Python's _get_profile_limits. + * + * When the profile is unavailable, returns undefined. In that case the + * middleware uses fixed token/message-count fallback defaults for + * trigger/keep, and relies on the ContextOverflowError catch as a + * safety net if the prompt still exceeds the model's actual limit. + */ + function getMaxInputTokens(resolvedModel) { + const profile = resolvedModel.profile; + if (profile && typeof profile === "object" && "maxInputTokens" in profile && typeof profile.maxInputTokens === "number") return profile.maxInputTokens; + } + /** + * Check if summarization should be triggered. + */ + function shouldSummarize(messages, totalTokens, maxInputTokens) { + if (!trigger) return false; + const adjustedTokens = totalTokens * tokenEstimationMultiplier; + const triggers = Array.isArray(trigger) ? trigger : [trigger]; + for (const t of triggers) { + if (t.type === "messages" && messages.length >= t.value) return true; + if (t.type === "tokens" && adjustedTokens >= t.value) return true; + if (t.type === "fraction" && maxInputTokens) { + if (adjustedTokens >= Math.floor(maxInputTokens * t.value)) return true; + } + } + return false; + } + /** + * Find a safe cutoff point that doesn't split AI/Tool message pairs. + * + * If the message at `cutoffIndex` is a ToolMessage, this adjusts the boundary + * so that related AI and Tool messages stay together. Two strategies are used: + * + * 1. **Move backward** to include the AIMessage that produced the tool calls, + * keeping the pair in the preserved set. Preferred when it doesn't move + * the cutoff too far back. + * + * 2. **Advance forward** past all consecutive ToolMessages, putting the entire + * pair into the summarized set. Used when moving backward would preserve + * too many messages (e.g., a single AIMessage made 20+ tool calls). + */ + function findSafeCutoffPoint(messages, cutoffIndex) { + if (cutoffIndex >= messages.length || !ToolMessage.isInstance(messages[cutoffIndex])) return cutoffIndex; + let forwardIdx = cutoffIndex; + while (forwardIdx < messages.length && ToolMessage.isInstance(messages[forwardIdx])) forwardIdx++; + const toolCallIds = /* @__PURE__ */ new Set(); + for (let i = cutoffIndex; i < forwardIdx; i++) { + const toolMsg = messages[i]; + if (toolMsg.tool_call_id) toolCallIds.add(toolMsg.tool_call_id); + } + let backwardIdx = null; + for (let i = cutoffIndex - 1; i >= 0; i--) { + const msg = messages[i]; + if (AIMessage.isInstance(msg) && msg.tool_calls) { + const aiToolCallIds = new Set(msg.tool_calls.map((tc) => tc.id).filter((id) => id != null)); + for (const id of toolCallIds) if (aiToolCallIds.has(id)) { + backwardIdx = i; + break; + } + if (backwardIdx !== null) break; + } + } + if (backwardIdx === null) return forwardIdx; + if (cutoffIndex - backwardIdx > cutoffIndex / 2 && cutoffIndex > 2) return forwardIdx; + return backwardIdx; + } + /** + * Determine cutoff index for messages to summarize. + * Messages at index < cutoff will be summarized. + * Messages at index >= cutoff will be preserved. + * + * Uses findSafeCutoffPoint to ensure tool call/result pairs stay together. + */ + function determineCutoffIndex(messages, maxInputTokens) { + let rawCutoff; + if (keep.type === "messages") { + if (messages.length <= keep.value) return 0; + rawCutoff = messages.length - keep.value; + } else if (keep.type === "tokens" || keep.type === "fraction") { + const targetTokenCount = keep.type === "fraction" && maxInputTokens ? Math.floor(maxInputTokens * keep.value) : keep.value; + let tokensKept = 0; + rawCutoff = 0; + for (let i = messages.length - 1; i >= 0; i--) { + const msgTokens = countTokensApproximately([messages[i]]); + if (tokensKept + msgTokens > targetTokenCount) { + rawCutoff = i + 1; + break; + } + tokensKept += msgTokens; + } + } else return 0; + return findSafeCutoffPoint(messages, rawCutoff); + } + /** + * Check if argument truncation should be triggered. + */ + function shouldTruncateArgs(messages, totalTokens, maxInputTokens) { + if (!truncateTrigger) return false; + const adjustedTokens = totalTokens * tokenEstimationMultiplier; + if (truncateTrigger.type === "messages") return messages.length >= truncateTrigger.value; + if (truncateTrigger.type === "tokens") return adjustedTokens >= truncateTrigger.value; + if (truncateTrigger.type === "fraction" && maxInputTokens) return adjustedTokens >= Math.floor(maxInputTokens * truncateTrigger.value); + return false; + } + /** + * Determine cutoff index for argument truncation. + * Uses findSafeCutoffPoint to ensure tool call/result pairs stay together. + */ + function determineTruncateCutoffIndex(messages, maxInputTokens) { + let rawCutoff; + if (truncateKeep.type === "messages") { + if (messages.length <= truncateKeep.value) return messages.length; + rawCutoff = messages.length - truncateKeep.value; + } else if (truncateKeep.type === "tokens" || truncateKeep.type === "fraction") { + const targetTokenCount = truncateKeep.type === "fraction" && maxInputTokens ? Math.floor(maxInputTokens * truncateKeep.value) : truncateKeep.value; + let tokensKept = 0; + rawCutoff = 0; + for (let i = messages.length - 1; i >= 0; i--) { + const msgTokens = countTokensApproximately([messages[i]]); + if (tokensKept + msgTokens > targetTokenCount) { + rawCutoff = i + 1; + break; + } + tokensKept += msgTokens; + } + } else return messages.length; + return findSafeCutoffPoint(messages, rawCutoff); + } + /** + * Count tokens including system message and tools, matching Python's approach. + * This gives a more accurate picture of what actually gets sent to the model. + */ + function countTotalTokens(messages, systemMessage, tools) { + return countTokensApproximately(systemMessage && SystemMessage.isInstance(systemMessage) ? [systemMessage, ...messages] : [...messages], tools && Array.isArray(tools) && tools.length > 0 ? tools : null); + } + /** + * Truncate ToolMessage content so that the total payload fits within the + * model's context window. Each ToolMessage gets an equal share of the + * remaining token budget after accounting for non-tool messages, system + * message, and tool schemas. + * + * This is critical for conversations where a single AIMessage triggers + * many tool calls whose results collectively exceed the context window. + * Without this, findSafeCutoffPoint cannot split the AI/Tool group and + * summarization would discard everything, causing the model to re-call + * the same tools in an infinite loop. + */ + function compactToolResults(messages, maxInputTokens, systemMessage, tools) { + const toolMessageIndices = []; + for (let i = 0; i < messages.length; i++) if (ToolMessage.isInstance(messages[i])) toolMessageIndices.push(i); + if (toolMessageIndices.length === 0) return { + messages, + modified: false + }; + const overheadTokens = countTotalTokens(messages.filter((m) => !ToolMessage.isInstance(m)), systemMessage, tools); + const adjustedMax = maxInputTokens / tokenEstimationMultiplier; + const budgetForTools = Math.max(adjustedMax * .7 - overheadTokens, 1e3); + const perToolBudgetChars = Math.floor(budgetForTools / toolMessageIndices.length) * 4; + let modified = false; + const result = [...messages]; + for (const idx of toolMessageIndices) { + const msg = messages[idx]; + const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content); + if (content.length > perToolBudgetChars) { + result[idx] = new ToolMessage({ + content: content.substring(0, perToolBudgetChars) + "\n...(result truncated)", + tool_call_id: msg.tool_call_id, + name: msg.name + }); + modified = true; + } + } + return { + messages: result, + modified + }; + } + /** + * Truncate large tool arguments in old messages. + */ + function truncateArgs(messages, maxInputTokens, systemMessage, tools, options) { + if (!shouldTruncateArgs(messages, options?.totalTokens ?? countTotalTokens(messages, systemMessage, tools), maxInputTokens)) return { + messages, + modified: false + }; + const cutoffIndex = determineTruncateCutoffIndex(messages, maxInputTokens); + if (cutoffIndex >= messages.length) return { + messages, + modified: false + }; + const truncatedMessages = []; + let modified = false; + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; + if (i < cutoffIndex && AIMessage.isInstance(msg) && msg.tool_calls) { + const truncatedToolCalls = msg.tool_calls.map((toolCall) => { + const args = toolCall.args || {}; + const truncatedArgs = {}; + let toolModified = false; + for (const [key, value] of Object.entries(args)) if (typeof value === "string" && value.length > maxArgLength && (toolCall.name === "write_file" || toolCall.name === "edit_file")) { + truncatedArgs[key] = value.substring(0, 20) + truncationText; + toolModified = true; + } else truncatedArgs[key] = value; + if (toolModified) { + modified = true; + return { + ...toolCall, + args: truncatedArgs + }; + } + return toolCall; + }); + if (modified) { + const truncatedMsg = new AIMessage({ + content: msg.content, + tool_calls: truncatedToolCalls, + additional_kwargs: msg.additional_kwargs + }); + truncatedMessages.push(truncatedMsg); + } else truncatedMessages.push(msg); + } else truncatedMessages.push(msg); + } + return { + messages: truncatedMessages, + modified + }; + } + /** + * Filter out previous summary messages. + */ + function filterSummaryMessages(messages) { + return messages.filter((msg) => !isSummaryMessage(msg)); + } + /** + * Offload messages to backend by appending to the history file. + * + * Uses uploadFiles() directly with raw byte concatenation instead of + * edit() to avoid downloading the file twice and performing a full + * string search-and-replace. This keeps peak memory at ~2x file size + * (existing bytes + combined bytes) instead of ~6x with the old + * download → edit(oldContent, newContent) approach. + */ + async function offloadToBackend(resolvedBackend, messages, state) { + const filePath = getHistoryPath(state); + const filteredMessages = filterSummaryMessages(messages); + const newSection = `## Summarized at ${(/* @__PURE__ */ new Date()).toISOString()}\n\n${getBufferString(filteredMessages)}\n\n`; + const sectionBytes = new TextEncoder().encode(newSection); + try { + let existingBytes = null; + if (resolvedBackend.downloadFiles) try { + const responses = await resolvedBackend.downloadFiles([filePath]); + if (responses.length > 0 && responses[0].content && !responses[0].error) existingBytes = responses[0].content; + } catch {} + let result; + if (existingBytes && resolvedBackend.uploadFiles) { + const combined = new Uint8Array(existingBytes.byteLength + sectionBytes.byteLength); + combined.set(existingBytes, 0); + combined.set(sectionBytes, existingBytes.byteLength); + const uploadResults = await resolvedBackend.uploadFiles([[filePath, combined]]); + result = uploadResults[0].error ? { error: uploadResults[0].error } : { path: filePath }; + } else if (!existingBytes) result = await resolvedBackend.write(filePath, newSection); + else { + const existingContent = new TextDecoder().decode(existingBytes); + result = await resolvedBackend.edit(filePath, existingContent, existingContent + newSection); + } + if (result.error) { + console.warn(`Failed to offload conversation history to ${filePath}: ${result.error}`); + return null; + } + return filePath; + } catch (e) { + console.warn(`Exception offloading conversation history to ${filePath}:`, e); + return null; + } + } + /** + * Create summary of messages. + */ + async function createSummary(messages, chatModel) { + let messagesToSummarize = messages; + if (countTokensApproximately(messages) > trimTokensToSummarize) { + let kept = 0; + const trimmedMessages = []; + for (let i = messages.length - 1; i >= 0; i--) { + const msgTokens = countTokensApproximately([messages[i]]); + if (kept + msgTokens > trimTokensToSummarize) break; + trimmedMessages.unshift(messages[i]); + kept += msgTokens; + } + messagesToSummarize = trimmedMessages; + } + const conversation = getBufferString(messagesToSummarize); + const prompt = summaryPrompt.replace("{conversation}", conversation); + const response = await chatModel.invoke([new HumanMessage({ content: prompt })]); + return typeof response.content === "string" ? response.content : JSON.stringify(response.content); + } + /** + * Build the summary message with file path reference. + */ + function buildSummaryMessage(summary, filePath) { + let content; + if (filePath) content = context` + You are in the middle of a conversation that has been summarized. + + The full conversation history has been saved to ${filePath} should you need to refer back to it for details. + + A condensed summary follows: + + + ${summary} + + `; + else content = `Here is a summary of the conversation to date:\n\n${summary}`; + return new HumanMessage({ + content, + additional_kwargs: { lc_source: "summarization" } + }); + } + /** + * Reconstruct the effective message list based on any previous summarization event. + * + * After summarization, instead of using all messages from state, we use the summary + * message plus messages after the cutoff index. This avoids full state rewrites. + */ + function getEffectiveMessages(messages, state) { + const event = state._summarizationEvent; + if (!event) return messages; + const result = [event.summaryMessage]; + result.push(...messages.slice(event.cutoffIndex)); + return result; + } + /** + * Summarize a set of messages using the given model and build the + * summary message + backend offload. Returns the summary message, + * the file path, and the state cutoff index. + */ + async function summarizeMessages(messagesToSummarize, resolvedModel, state, previousCutoffIndex, cutoffIndex) { + const filePath = await offloadToBackend(await resolveBackend(backend, { state }), messagesToSummarize, state); + if (filePath === null) console.warn(`[SummarizationMiddleware] Backend offload failed during summarization. Proceeding with summary generation.`); + return { + summaryMessage: buildSummaryMessage(await createSummary(messagesToSummarize, resolvedModel), filePath), + filePath, + stateCutoffIndex: previousCutoffIndex != null ? previousCutoffIndex + cutoffIndex - 1 : cutoffIndex + }; + } + /** + * Check if an error (possibly wrapped in MiddlewareError layers) is a + * ContextOverflowError by walking the `cause` chain. + */ + function isContextOverflow(err) { + let cause = err; + for (;;) { + if (!cause) break; + if (ContextOverflowError.isInstance(cause)) return true; + cause = typeof cause === "object" && "cause" in cause ? cause.cause : void 0; + } + return false; + } + async function performSummarization(request, handler, truncatedMessages, resolvedModel, maxInputTokens) { + const cutoffIndex = determineCutoffIndex(truncatedMessages, maxInputTokens); + if (cutoffIndex <= 0) return handler({ + ...request, + messages: truncatedMessages + }); + const messagesToSummarize = truncatedMessages.slice(0, cutoffIndex); + const preservedMessages = truncatedMessages.slice(cutoffIndex); + if (preservedMessages.length === 0 && maxInputTokens) { + const compact = compactToolResults(truncatedMessages, maxInputTokens, request.systemMessage, request.tools); + if (compact.modified) try { + return await handler({ + ...request, + messages: compact.messages + }); + } catch (err) { + if (!isContextOverflow(err)) throw err; + } + } + const previousEvent = request.state._summarizationEvent; + const previousCutoffIndex = previousEvent != null ? previousEvent.cutoffIndex : void 0; + const { summaryMessage, filePath, stateCutoffIndex } = await summarizeMessages(messagesToSummarize, resolvedModel, request.state, previousCutoffIndex, cutoffIndex); + let modifiedMessages = [summaryMessage, ...preservedMessages]; + const modifiedTokens = countTotalTokens(modifiedMessages, request.systemMessage, request.tools); + let finalStateCutoffIndex = stateCutoffIndex; + let finalSummaryMessage = summaryMessage; + let finalFilePath = filePath; + try { + await handler({ + ...request, + messages: modifiedMessages + }); + } catch (err) { + if (!isContextOverflow(err)) throw err; + if (maxInputTokens && modifiedTokens > 0) { + const observedRatio = maxInputTokens / modifiedTokens; + if (observedRatio > tokenEstimationMultiplier) tokenEstimationMultiplier = observedRatio * 1.1; + } + const reSumResult = await summarizeMessages([...messagesToSummarize, ...preservedMessages], resolvedModel, request.state, previousCutoffIndex, truncatedMessages.length); + finalSummaryMessage = reSumResult.summaryMessage; + finalFilePath = reSumResult.filePath; + finalStateCutoffIndex = reSumResult.stateCutoffIndex; + modifiedMessages = [reSumResult.summaryMessage]; + await handler({ + ...request, + messages: modifiedMessages + }); + } + return new Command({ update: { + _summarizationEvent: { + cutoffIndex: finalStateCutoffIndex, + summaryMessage: finalSummaryMessage, + filePath: finalFilePath + }, + _summarizationSessionId: getSessionId(request.state) + } }); + } + return createMiddleware({ + name: "SummarizationMiddleware", + stateSchema: SummarizationStateSchema, + async wrapModelCall(request, handler) { + const effectiveMessages = getEffectiveMessages(request.messages ?? [], request.state); + if (effectiveMessages.length === 0) return handler(request); + /** + * Resolve the chat model and get max input tokens from its profile. + */ + const resolvedModel = request.model ?? await getChatModel(); + const maxInputTokens = getMaxInputTokens(resolvedModel); + applyModelDefaults(resolvedModel); + const totalTokens = countTotalTokens(effectiveMessages, request.systemMessage, request.tools); + /** + * Step 1: Truncate args if configured + */ + const { messages: truncatedMessages, modified: truncateModified } = truncateArgs(effectiveMessages, maxInputTokens, request.systemMessage, request.tools, { totalTokens }); + /** + * Step 2: Check if summarization should happen. + * Recount only if truncation changed messages. + */ + const tokensForSummary = truncateModified ? countTotalTokens(truncatedMessages, request.systemMessage, request.tools) : totalTokens; + /** + * If no summarization needed, try passing through. + * If the handler throws a ContextOverflowError, fall back to + * emergency summarization (matching Python's behavior). + */ + if (!shouldSummarize(truncatedMessages, tokensForSummary, maxInputTokens)) try { + return await handler({ + ...request, + messages: truncatedMessages + }); + } catch (err) { + if (!isContextOverflow(err)) throw err; + if (maxInputTokens && tokensForSummary > 0) { + const observedRatio = maxInputTokens / tokensForSummary; + if (observedRatio > tokenEstimationMultiplier) tokenEstimationMultiplier = observedRatio * 1.1; + } + } + /** + * Step 3: Perform summarization + */ + return performSummarization(request, handler, truncatedMessages, resolvedModel, maxInputTokens); + } + }); +} +function toolCallIdFromRuntime(runtime) { + return runtime.toolCall?.id ?? runtime.toolCallId ?? ""; +} +/** +* Zod schema for {@link AsyncTask}. +* +* Used by the {@link ReducedValue} in the state schema so that LangGraph +* can validate and serialize task records stored in `asyncTasks`. +*/ +var AsyncTaskSchema = object({ + taskId: string(), + agentName: string(), + threadId: string(), + runId: string(), + status: string(), + createdAt: string(), + description: string().optional(), + updatedAt: string().optional(), + checkedAt: string().optional() +}); +/** +* State schema for the async subagent middleware. +* +* Declares `asyncTasks` as a reduced state channel so that individual +* tool updates (launch, check, update, cancel, list) merge into the existing +* tasks dict rather than replacing it wholesale. +*/ +var AsyncTaskStateSchema = new StateSchema({ asyncTasks: new ReducedValue(record(string(), AsyncTaskSchema).default(() => ({})), { + inputSchema: record(string(), AsyncTaskSchema).optional(), + reducer: asyncTasksReducer +}) }); +/** +* Reducer for the `asyncTasks` state channel. +* +* Merges task updates into the existing tasks dict using shallow spread. +* This allows individual tools to update a single task without overwriting +* the full map — only the keys present in `update` are replaced. +* +* @param existing - The current tasks dict from state (may be undefined on first write). +* @param update - New or updated task entries to merge in. +* @returns Merged tasks dict. +*/ +function asyncTasksReducer(existing, update) { + return { + ...existing || {}, + ...update || {} + }; +} +/** +* Description template for the `start_async_task` tool. +* +* The `{available_agents}` placeholder is replaced at middleware creation +* time with a formatted list of configured async subagent names and descriptions. +*/ +var ASYNC_TASK_TOOL_DESCRIPTION = `Launch an async subagent on a remote server. The subagent runs in the background and returns a task ID immediately. + +Available async agent types: +{available_agents} + +## Usage notes: +1. This tool launches a background task and returns immediately with a task ID. Report the task ID to the user and stop — do NOT immediately check status. +2. Use \`check_async_task\` only when the user asks for a status update or result. +3. Use \`update_async_task\` to send new instructions to a running task. +4. Multiple async subagents can run concurrently — launch several and let them run in the background. +5. The subagent runs on a remote server, so it has its own tools and capabilities.`; +/** +* Task statuses that will never change. +* +* When listing tasks, live-status fetches are skipped for tasks whose +* cached status is in this set, since they are guaranteed to be final. +*/ +/** +* Names of the tools added by the async subagent middleware. +* +* Exported so `agent.ts` can include them in `BUILTIN_TOOL_NAMES` and +* surface a `ConfigurationError` if a user-provided tool collides. +*/ +var ASYNC_TASK_TOOL_NAMES = [ + "start_async_task", + "check_async_task", + "update_async_task", + "cancel_async_task", + "list_async_tasks" +]; +var TERMINAL_STATUSES = /* @__PURE__ */ new Set([ + "cancelled", + "success", + "error", + "timeout", + "interrupted" +]); +/** +* Look up a tracked task from state by its `taskId`. +* +* @param taskId - The task ID to look up (will be trimmed). +* @param state - The current agent state containing `asyncTasks`. +* @returns The tracked task on success, or an error string. +*/ +function resolveTrackedTask(taskId, state) { + const tracked = (state.asyncTasks ?? {})[taskId.trim()]; + if (!tracked) return `No tracked task found for taskId: '${taskId}'`; + return tracked; +} +/** +* Build a check result from a run's current status and thread state values. +* +* For successful runs, extracts the last message's content from the remote +* thread's state values. For errored runs, includes a generic error message. +* +* @param run - The run object from the SDK. +* @param threadId - The thread ID for the run. +* @param threadValues - The `values` from `ThreadState` (the remote subagent's state). +*/ +function buildCheckResult(run, threadId, threadValues) { + const checkResult = { + status: run.status, + threadId + }; + if (run.status === "success") { + const messages = (Array.isArray(threadValues) ? {} : threadValues)?.messages ?? []; + if (messages.length > 0) { + const last = messages[messages.length - 1]; + const rawContent = typeof last === "object" && last !== null && "content" in last ? last.content : last; + checkResult.result = typeof rawContent === "string" ? rawContent : JSON.stringify(rawContent); + } else checkResult.result = "Completed with no output messages."; + } else if (run.status === "error") checkResult.error = "The async subagent encountered an error."; + return checkResult; +} +/** +* Filter tasks by cached status from agent state. +* +* Filtering uses the cached status, not live server status. Live statuses +* are fetched after filtering by the calling tool. +* +* @param tasks - All tracked tasks from state. +* @param statusFilter - If nullish or `'all'`, return all tasks. +* Otherwise return only tasks whose cached status matches. +*/ +function filterTasks(tasks, statusFilter) { + if (!statusFilter || statusFilter === "all") return Object.values(tasks); + return Object.values(tasks).filter((task) => task.status === statusFilter); +} +/** +* Fetch the current run status from the server. +* +* Returns the cached status immediately for terminal tasks (avoiding +* unnecessary API calls). Falls back to the cached status on SDK errors. +*/ +async function fetchLiveTaskStatus(clients, task) { + if (TERMINAL_STATUSES.has(task.status)) return task.status; + try { + return (await clients.getClient(task.agentName).runs.get(task.threadId, task.runId)).status; + } catch { + return task.status; + } +} +/** +* Format a single task as a display string for list output. +*/ +function formatTaskEntry(task, status) { + return `- taskId: ${task.taskId} agent: ${task.agentName} status: ${status}`; +} +/** +* Lazily-created, cached LangGraph SDK clients keyed by (url, headers). +* +* Agents that share the same URL and headers will reuse a single `Client` +* instance, avoiding unnecessary connections. +*/ +var ClientCache = class { + agents; + clients = /* @__PURE__ */ new Map(); + constructor(agents) { + this.agents = agents; + } + /** + * Build headers for a remote Agent Protocol server. + * + * Adds `x-auth-scheme: langsmith` by default unless already provided. + * For self-hosted servers that don't require this header, it is typically + * ignored. Override via the `headers` field on the AsyncSubAgent config. + */ + resolveHeaders(spec) { + const headers = { ...spec.headers || {} }; + if (!("x-auth-scheme" in headers)) headers["x-auth-scheme"] = "langsmith"; + return headers; + } + /** + * Build a stable cache key from a spec's url and resolved headers. + */ + cacheKey(spec) { + const headers = this.resolveHeaders(spec); + const headerStr = Object.entries(headers).sort().flat().join(":"); + return `${spec.url ?? ""}|${headerStr}`; + } + /** + * Get or create a `Client` for the named agent. + */ + getClient(name) { + const spec = this.agents[name]; + const key = this.cacheKey(spec); + const existing = this.clients.get(key); + if (existing) return existing; + const headers = this.resolveHeaders(spec); + const client = new Client({ + apiUrl: spec.url, + defaultHeaders: headers + }); + this.clients.set(key, client); + return client; + } +}; +/** +* Extract the callback thread ID from the tool runtime. +* +* The thread ID is included in the subagent's input state so the subagent +* can notify the parent when it completes (via +* `CompletionCallbackMiddleware`). +* +* @returns Object with `callbackThreadId` if available. Empty object otherwise. +*/ +function extractCallbackContext(runtime) { + const threadId = (runtime.config?.configurable)?.thread_id; + if (typeof threadId === "string" && threadId) return { callbackThreadId: threadId }; + return {}; +} +/** +* Build the `start_async_task` tool. +* +* Creates a thread on the remote server, starts a run, and returns a +* `Command` that persists the new task in state. +*/ +function buildStartTool(agentMap, clients, toolDescription) { + return tool$1(async (input, runtime) => { + if (!(input.agentName in agentMap)) { + const allowed = Object.keys(agentMap).map((k) => `\`${k}\``).join(", "); + return `Unknown async subagent type \`${input.agentName}\`. Available types: ${allowed}`; + } + const spec = agentMap[input.agentName]; + const callbackContext = extractCallbackContext(runtime); + try { + const client = clients.getClient(input.agentName); + const thread = await client.threads.create(); + const run = await client.runs.create(thread.thread_id, spec.graphId, { input: { + messages: [{ + role: "user", + content: input.description + }], + ...callbackContext + } }); + const taskId = thread.thread_id; + const task = { + taskId, + agentName: input.agentName, + threadId: taskId, + runId: run.run_id, + status: "running", + createdAt: (/* @__PURE__ */ new Date()).toISOString(), + description: input.description + }; + return new Command({ update: { + messages: [new ToolMessage({ + content: `Launched async subagent. taskId: ${taskId}`, + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: { [taskId]: task } + } }); + } catch (e) { + return `Failed to launch async subagent '${input.agentName}': ${e}`; + } + }, { + name: "start_async_task", + description: toolDescription, + schema: object({ + description: string().describe("A detailed description of the task for the async subagent to perform."), + agentName: string().describe("The type of async subagent to use. Must be one of the available types listed in the tool description.") + }) + }); +} +/** +* Build the `check_async_task` tool. +* +* Fetches the current run status from the remote server and, if the run +* succeeded, retrieves the thread state to extract the result. +*/ +function buildCheckTool(clients) { + return tool$1(async (input, runtime) => { + const task = resolveTrackedTask(input.taskId, runtime.state); + if (typeof task === "string") return task; + const client = clients.getClient(task.agentName); + let run; + try { + run = await client.runs.get(task.threadId, task.runId); + } catch (e) { + return `Failed to get run status: ${e}`; + } + let threadValues = {}; + if (run.status === "success") try { + threadValues = (await client.threads.getState(task.threadId)).values || {}; + } catch {} + const result = buildCheckResult(run, task.threadId, threadValues); + const updatedTask = { + taskId: task.taskId, + agentName: task.agentName, + threadId: task.threadId, + runId: task.runId, + status: result.status, + createdAt: task.createdAt, + updatedAt: result.status !== task.status ? (/* @__PURE__ */ new Date()).toISOString() : task.updatedAt, + checkedAt: (/* @__PURE__ */ new Date()).toISOString() + }; + return new Command({ update: { + messages: [new ToolMessage({ + content: JSON.stringify(result), + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: { [task.taskId]: updatedTask } + } }); + }, { + name: "check_async_task", + description: "Check the status of an async subagent task. Returns the current status and, if complete, the result. Statuses shown earlier in the conversation are always stale, so call this to get the current status rather than reporting a status from a previous tool result.", + schema: object({ taskId: string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") }) + }); +} +/** +* Build the `update_async_task` tool. +* +* Sends a follow-up message to a running async subagent by creating a new +* run on the same thread with `multitaskStrategy: "interrupt"`. The subagent +* sees the full conversation history plus the new message. The `taskId` +* remains the same; only the internal `runId` is updated. +*/ +function buildUpdateTool(agentMap, clients) { + return tool$1(async (input, runtime) => { + const tracked = resolveTrackedTask(input.taskId, runtime.state); + if (typeof tracked === "string") return tracked; + const spec = agentMap[tracked.agentName]; + try { + const run = await clients.getClient(tracked.agentName).runs.create(tracked.threadId, spec.graphId, { + input: { messages: [{ + role: "user", + content: input.message + }] }, + multitaskStrategy: "interrupt" + }); + const task = { + taskId: tracked.taskId, + agentName: tracked.agentName, + threadId: tracked.threadId, + runId: run.run_id, + status: "running", + createdAt: tracked.createdAt, + description: input.message, + updatedAt: (/* @__PURE__ */ new Date()).toISOString(), + checkedAt: tracked.checkedAt + }; + return new Command({ update: { + messages: [new ToolMessage({ + content: `Updated async subagent. taskId: ${tracked.taskId}`, + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: { [tracked.taskId]: task } + } }); + } catch (e) { + return `Failed to update async subagent: ${e}`; + } + }, { + name: "update_async_task", + description: "send updated instructions to an async subagent. Interrupts the current run and starts a new one on the same thread so the subagent sees the full conversation history plus your new message. The taskId remains the same.", + schema: object({ + taskId: string().describe("The exact taskId string returned by start_async_task. Pass it verbatim."), + message: string().describe("Follow-up instructions or context to send to the subagent") + }) + }); +} +/** +* Build the `cancel_async_task` tool. +* +* Cancels the current run on the remote server and updates the task's +* cached status to `"cancelled"`. +*/ +function buildCancelTool(clients) { + return tool$1(async (input, runtime) => { + const tracked = resolveTrackedTask(input.taskId, runtime.state); + if (typeof tracked === "string") return tracked; + const client = clients.getClient(tracked.agentName); + try { + await client.runs.cancel(tracked.threadId, tracked.runId); + } catch (e) { + return `Failed to cancel run: ${e}`; + } + const updated = { + taskId: tracked.taskId, + agentName: tracked.agentName, + threadId: tracked.threadId, + runId: tracked.runId, + status: "cancelled", + createdAt: tracked.createdAt, + updatedAt: (/* @__PURE__ */ new Date()).toISOString(), + checkedAt: tracked.checkedAt + }; + return new Command({ update: { + messages: [new ToolMessage({ + content: `Cancelled async subagent task: ${tracked.taskId}`, + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: { [tracked.taskId]: updated } + } }); + }, { + name: "cancel_async_task", + description: "Cancel a running async subagent task. Use this to stop a task that is no longer needed.", + schema: object({ taskId: string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") }) + }); +} +/** +* Build the `list_async_tasks` tool. +* +* Lists all tracked tasks with their live statuses fetched in parallel. +* Supports optional filtering by cached status. +*/ +function buildListTool(clients) { + return tool$1(async (input, runtime) => { + const filtered = filterTasks(runtime.state.asyncTasks ?? {}, input.statusFilter ?? void 0); + if (filtered.length === 0) return "No async subagent tasks tracked"; + const statuses = await Promise.all(filtered.map((task) => fetchLiveTaskStatus(clients, task))); + const updatedTasks = {}; + const entries = []; + for (let idx = 0; idx < filtered.length; idx++) { + const task = filtered[idx]; + const status = statuses[idx]; + const taskEntry = formatTaskEntry(task, status); + entries.push(taskEntry); + updatedTasks[task.taskId] = { + taskId: task.taskId, + agentName: task.agentName, + threadId: task.threadId, + runId: task.runId, + status, + createdAt: task.createdAt, + updatedAt: status !== task.status ? (/* @__PURE__ */ new Date()).toISOString() : task.updatedAt, + checkedAt: task.checkedAt + }; + } + return new Command({ update: { + messages: [new ToolMessage({ + content: `${entries.length} tracked task(s):\n${entries.join("\n")}`, + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: updatedTasks + } }); + }, { + name: "list_async_tasks", + description: "List tracked async subagent tasks with their current live statuses. By default shows all tasks. Use `statusFilter` to narrow by status (e.g., 'running', 'success', 'error', 'cancelled'). Use `check_async_task` to get the full result of a specific completed task. Statuses shown earlier in the conversation are always stale, so call this to read current statuses rather than reporting one from a previous tool result.", + schema: object({ statusFilter: string().nullish().describe("Filter tasks by status. One of: 'running', 'success', 'error', 'cancelled', 'all'. Defaults to 'all'.") }) + }); +} +/** +* Create middleware that adds async subagent tools to an agent. +* +* Provides five tools for launching, checking, updating, cancelling, and +* listing background tasks on remote Agent Protocol servers. Task state is +* persisted in the `asyncTasks` state channel so it survives +* context compaction. +* +* Works with any Agent Protocol-compliant server — LangGraph Platform (managed) +* or self-hosted (e.g. a Hono/Express server implementing the Agent Protocol spec). +* +* @throws {Error} If no async subagents are provided or names are duplicated. +* +* @example +* ```ts +* const middleware = createAsyncSubAgentMiddleware({ +* asyncSubAgents: [{ +* name: "researcher", +* description: "Research agent for deep analysis", +* url: "https://my-agent-protocol-server.example.com", +* graphId: "research_agent", +* }], +* }); +* ``` +*/ +/** +* Type guard to distinguish async SubAgents from sync SubAgents/CompiledSubAgents. +* +* Uses the presence of the `graphId` field as the runtime discriminant — +* `AsyncSubAgent` requires it, while `SubAgent` and `CompiledSubAgent` do not have it. +*/ +function isAsyncSubAgent(subAgent) { + return "graphId" in subAgent; +} +function createAsyncSubAgentMiddleware(options) { + const { asyncSubAgents, systemPrompt = null } = options; + if (!asyncSubAgents || asyncSubAgents.length === 0) throw new Error("At least one async subagent must be specified"); + const names = asyncSubAgents.map((a) => a.name); + const duplicates = names.filter((n, i) => names.indexOf(n) !== i); + if (duplicates.length > 0) throw new Error(`Duplicate async subagent names: ${[...new Set(duplicates)].join(", ")}`); + const agentMap = Object.fromEntries(asyncSubAgents.map((a) => [a.name, a])); + const clients = new ClientCache(agentMap); + const agentsDescription = asyncSubAgents.map((a) => `- ${a.name}: ${a.description}`).join("\n"); + const tools = [ + buildStartTool(agentMap, clients, ASYNC_TASK_TOOL_DESCRIPTION.replace("{available_agents}", agentsDescription)), + buildCheckTool(clients), + buildUpdateTool(agentMap, clients), + buildCancelTool(clients), + buildListTool(clients) + ]; + const fullSystemPrompt = systemPrompt ? `${systemPrompt}\n\nAvailable async subagent types:\n${agentsDescription}` : null; + return createMiddleware({ + name: "asyncSubAgentMiddleware", + stateSchema: AsyncTaskStateSchema, + tools, + wrapModelCall: async (request, handler) => { + if (fullSystemPrompt !== null) return handler({ + ...request, + systemMessage: request.systemMessage.concat(new SystemMessage({ content: fullSystemPrompt })) + }); + return handler(request); + } + }); +} +var CONFIGURATION_ERROR_SYMBOL = Symbol.for("deepagents.configuration_error"); +/** +* Thrown when `createDeepAgent` receives invalid configuration. +* +* Follows the same pattern as {@link SandboxError}: a human-readable +* `message`, a structured `code` for programmatic handling, and a +* static `isInstance` guard that works across realms. +* +* @example +* ```typescript +* try { +* createDeepAgent({ tools: [myTool] }); +* } catch (error) { +* if (ConfigurationError.isInstance(error)) { +* switch (error.code) { +* case "TOOL_NAME_COLLISION": +* console.error("Rename your tool:", error.message); +* break; +* } +* } +* } +* ``` +*/ +var ConfigurationError = class ConfigurationError extends Error { + code; + cause; + [CONFIGURATION_ERROR_SYMBOL] = true; + name = "ConfigurationError"; + constructor(message, code, cause) { + super(message); + this.code = code; + this.cause = cause; + Object.setPrototypeOf(this, ConfigurationError.prototype); + } + static isInstance(error) { + return typeof error === "object" && error !== null && error[CONFIGURATION_ERROR_SYMBOL] === true; + } +}; +/** +* Creates a middleware that places a cache breakpoint at the end of the static +* system prompt content. +* +* This middleware tags the last block of the system message with +* `cache_control: { type: "ephemeral" }` at the time it runs, capturing all +* static content injected by preceding middleware (e.g. todo list instructions, +* filesystem tools, subagent instructions) in a single cache breakpoint. +* +* This should run after all static system prompt middleware and before any +* dynamic middleware (e.g. memory) so the breakpoint sits at the boundary +* between stable and changing content. +* +* When used alongside memory middleware (which adds its own breakpoint on the +* memory block), the result is two separate cache breakpoints: +* - One covering all static content +* - One covering the memory block +* +* The `cache_control` marker is Anthropic-specific. The middleware is gated +* per-call on `request.model` so it is a no-op when `modelFallbackMiddleware` +* (or any other middleware) has swapped the request to a non-Anthropic +* provider. Without this gate, the marker leaks to providers that reject it +* (e.g. OpenAI returns `400 Unknown parameter: 'cache_control'`). +* +* This is a no-op when the system message has no content blocks. +*/ +function createCacheBreakpointMiddleware() { + return createMiddleware({ + name: "CacheBreakpointMiddleware", + wrapModelCall(request, handler) { + if (!isAnthropicModel(request.model)) return handler(request); + const existingContent = request.systemMessage.content; + const existingBlocks = typeof existingContent === "string" ? [{ + type: "text", + text: existingContent + }] : Array.isArray(existingContent) ? [...existingContent] : []; + if (existingBlocks.length === 0) return handler(request); + existingBlocks[existingBlocks.length - 1] = { + ...existingBlocks[existingBlocks.length - 1], + cache_control: { type: "ephemeral" } + }; + return handler({ + ...request, + systemMessage: new SystemMessage({ content: existingBlocks }) + }); + } + }); +} +function hasToolName(tool) { + return tool !== null && typeof tool === "object" && "name" in tool && typeof tool.name === "string"; +} +/** +* Create middleware that removes excluded tools after all tool-injecting +* middleware has had a chance to add tools to the request. +* +* @internal +*/ +function createToolExclusionMiddleware(excludedTools) { + return createMiddleware({ + name: "_ToolExclusionMiddleware", + wrapModelCall(request, handler) { + return handler({ + ...request, + tools: request.tools?.filter((tool) => !hasToolName(tool) || !excludedTools.has(tool.name)) + }); + } + }); +} +/** +* Normalize and validate a profile registry key. +* +* Trims leading/trailing whitespace, then enforces the `"provider"` or +* `"provider:model"` shape. Rejects empty strings, multiple colons, and +* empty halves. +* +* @param key - The registry key to validate. +* @returns The trimmed, validated key. +* @throws {Error} When the key is malformed. +* +* @example +* ```typescript +* validateProfileKey("anthropic:claude-opus-4-7"); // "anthropic:claude-opus-4-7" +* validateProfileKey(" openai "); // "openai" +* validateProfileKey("openai:"); // throws +* validateProfileKey(""); // throws +* ``` +*/ +function validateProfileKey(key) { + const trimmed = key.trim(); + if (!trimmed) throw new Error("Profile key must be a non-empty string"); + if (trimmed.split(":").length > 2) throw new Error(`Profile key "${trimmed}" has more than one ":"; expected "provider" or "provider:model"`); + if (trimmed.includes(":")) { + const [provider, model] = trimmed.split(":"); + if (!provider.trim() || !model.trim()) throw new Error(`Profile key "${trimmed}" has an empty provider or model half; expected "provider:model"`); + } + return trimmed; +} +/** +* Middleware names that provide essential agent capabilities and cannot +* be excluded via `excludedMiddleware`. +* +* - `FilesystemMiddleware` backs all built-in file tools and enforces +* filesystem permissions. +* - `SubAgentMiddleware` backs the `task` tool for subagent delegation. +*/ +var REQUIRED_MIDDLEWARE_NAMES = /* @__PURE__ */ new Set(["FilesystemMiddleware", "SubAgentMiddleware"]); +/** +* Resolve middleware to a concrete array, invoking the factory if +* needed. +* +* @internal +*/ +function resolveMiddleware(middleware) { + if (typeof middleware === "function") return middleware(); + return middleware; +} +/** +* Validate the grammar of an `excludedMiddleware` entry. +* +* Runs at profile construction time so malformed entries fail +* immediately. Checks: +* +* 1. Non-empty, non-whitespace string. +* 2. No colons (class-path `module:Class` syntax is reserved). +* 3. No underscore prefix (private middleware is not part of the +* exclusion surface). +* 4. Not a required scaffolding name. +* +* @param name - The middleware name to validate. +* @throws {Error} When the name violates any rule. +*/ +function validateExcludedMiddlewareName(name) { + if (!name || !name.trim()) throw new Error("excludedMiddleware entries must be non-empty, non-whitespace strings."); + if (name.includes(":")) throw new Error(`excludedMiddleware entries must be plain middleware names; class-path syntax is not supported, got "${name}".`); + if (name.startsWith("_")) throw new Error(`excludedMiddleware entry "${name}" cannot start with "_" (underscore-prefixed names refer to private middleware not part of the public exclusion surface).`); + if (REQUIRED_MIDDLEWARE_NAMES.has(name)) throw new Error(`Cannot exclude required middleware "${name}" — it provides essential agent capabilities that the runtime depends on.`); +} +/** +* Create a frozen {@link HarnessProfile} from user-provided options. +* +* Validates all fields, converts mutable collections to their +* frozen counterparts, and returns a frozen object. +* Empty options produce a no-op profile (all defaults). +* +* @param options - Partial profile configuration. +* @returns A frozen, validated `HarnessProfile`. +* @throws {Error} When any field violates validation rules (invalid +* middleware names, scaffolding exclusion attempts). +* +* @example +* ```typescript +* const profile = createHarnessProfile({ +* systemPromptSuffix: "Think step by step.", +* excludedTools: ["execute"], +* }); +* ``` +*/ +function createHarnessProfile(options = {}) { + for (const name of options.excludedMiddleware ?? []) validateExcludedMiddlewareName(name); + const toolDescriptionOverrides = Object.freeze(Object.assign(Object.create(null), options.toolDescriptionOverrides)); + const generalPurposeSubagent = options.generalPurposeSubagent ? Object.freeze({ ...options.generalPurposeSubagent }) : void 0; + const profile = { + baseSystemPrompt: options.baseSystemPrompt, + systemPromptSuffix: options.systemPromptSuffix, + toolDescriptionOverrides, + excludedTools: new Set(options.excludedTools), + excludedMiddleware: new Set(options.excludedMiddleware), + extraMiddleware: options.extraMiddleware ?? [], + generalPurposeSubagent + }; + return Object.freeze(profile); +} +/** +* An empty no-op profile used as the default when no registered +* profile matches. Avoids creating a new object on every miss. +*/ +var EMPTY_HARNESS_PROFILE = createHarnessProfile(); +/** +* Zod schema for the general-purpose subagent config section of an +* external harness profile config file. +*/ +var generalPurposeSubagentConfigSchema = object({ + enabled: boolean().optional(), + description: string().optional(), + systemPrompt: string().optional() +}).strict(); +object({ + baseSystemPrompt: string().optional(), + systemPromptSuffix: string().optional(), + toolDescriptionOverrides: record(string(), string()).optional(), + excludedTools: array(string()).optional(), + excludedMiddleware: array(string()).optional(), + generalPurposeSubagent: generalPurposeSubagentConfigSchema.optional() +}).strict(); +/** +* Merge two middleware sequences by `.name`. +* +* When the override has a middleware whose `.name` already appears in +* the base, the override instance replaces the base instance at the +* same position. Novel names from the override are appended. If the +* base has duplicates of the same name, only the first is replaced; +* later duplicates are dropped. +* +* Returns a factory to ensure fresh resolution on each call. +*/ +function mergeMiddleware(base, override) { + const baseArr = resolveMiddleware(base); + const overrideArr = resolveMiddleware(override); + if (baseArr.length === 0) return override; + if (overrideArr.length === 0) return base; + return () => { + const baseSeq = resolveMiddleware(base); + const overrideSeq = resolveMiddleware(override); + const overrideByName = new Map(overrideSeq.map((m) => [m.name, m])); + const merged = []; + const replaced = /* @__PURE__ */ new Set(); + for (const entry of baseSeq) { + const replacement = overrideByName.get(entry.name); + if (replacement) { + if (!replaced.has(entry.name)) { + merged.push(replacement); + replaced.add(entry.name); + } + } else merged.push(entry); + } + for (const entry of overrideSeq) if (!replaced.has(entry.name)) merged.push(entry); + return merged; + }; +} +/** +* Merge two GP subagent configs field-wise. +* +* Override wins per sub-field when not `undefined`; unset fields +* inherit from base. Returns `undefined` only when both inputs are +* `undefined`. +*/ +function mergeGeneralPurposeSubagentConfigs(base, override) { + if (base === void 0) return override; + if (override === void 0) return base; + return { + enabled: override.enabled ?? base.enabled, + description: override.description ?? base.description, + systemPrompt: override.systemPrompt ?? base.systemPrompt + }; +} +/** +* Merge two harness profiles, layering `override` on top of `base`. +* +* Merge semantics per field: +* +* | Field | Strategy | +* |-------|----------| +* | `baseSystemPrompt` | Override wins if not `undefined` | +* | `systemPromptSuffix` | Override wins if not `undefined` | +* | `toolDescriptionOverrides` | Object spread merge; override wins per key | +* | `excludedTools` | Set union | +* | `excludedMiddleware` | Set union | +* | `extraMiddleware` | Merge by `.name`; override instance replaces base at same position; novel names appended | +* | `generalPurposeSubagent` | Field-wise merge; override wins per sub-field | +* +* @param base - Lower-priority profile (e.g., provider-wide). +* @param override - Higher-priority profile (e.g., exact model). +* @returns A new merged profile. +*/ +function mergeProfiles(base, override) { + return createHarnessProfile({ + baseSystemPrompt: override.baseSystemPrompt ?? base.baseSystemPrompt, + systemPromptSuffix: override.systemPromptSuffix ?? base.systemPromptSuffix, + toolDescriptionOverrides: { + ...base.toolDescriptionOverrides, + ...override.toolDescriptionOverrides + }, + excludedTools: [...base.excludedTools, ...override.excludedTools], + excludedMiddleware: [...base.excludedMiddleware, ...override.excludedMiddleware], + extraMiddleware: mergeMiddleware(base.extraMiddleware, override.extraMiddleware), + generalPurposeSubagent: mergeGeneralPurposeSubagentConfigs(base.generalPurposeSubagent, override.generalPurposeSubagent) + }); +} +var SYSTEM_PROMPT_SUFFIX$3 = `\ + +If you intend to call multiple tools and there are no dependencies between the tool calls, make all of the independent tool calls in parallel. Prioritize calling tools simultaneously whenever the actions can be done in parallel rather than sequentially. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. Maximize use of parallel tool calls where possible to increase speed and efficiency. However, if some tool calls depend on previous calls to inform dependent values like the parameters, do NOT call these tools in parallel and instead call them sequentially. Never use placeholders or guess missing parameters in tool calls. + + + +Never speculate about code you have not opened. If the user references a specific file, you MUST read the file before answering. Make sure to investigate and read relevant files BEFORE answering questions about the codebase. Never make any claims about code before investigating unless you are certain of the correct answer - give grounded and hallucination-free answers. + + + +After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. + + + +When a task depends on the state of files, tests, or system output, use tools to observe that state directly rather than reasoning from memory about what it probably contains. Read files before describing them. Run tests before claiming they pass. Search the codebase before asserting a symbol does or does not exist. Active investigation with tools is the default mode of working, not a fallback. + + + +Do not spawn a subagent for work you can complete directly in a single response (e.g. refactoring a function you can already see). + +Spawn multiple subagents in the same turn when fanning out across items or reading multiple files. +`; +/** +* Register the built-in Claude Opus 4.7 harness profile. +* +* Layers a system-prompt suffix onto `anthropic:claude-opus-4-7` +* tuned to the model's documented behaviors: parallel tool calls, +* grounded answers, post-tool reflection, active investigation, and +* subagent spawning guidance. +* +* @internal +*/ +function register$3() { + registerHarnessProfileImpl("anthropic:claude-opus-4-7", createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX$3 })); +} +var SYSTEM_PROMPT_SUFFIX$2 = `\ + +If you intend to call multiple tools and there are no dependencies between the tool calls, make all of the independent tool calls in parallel. Prioritize calling tools simultaneously whenever the actions can be done in parallel rather than sequentially. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. Maximize use of parallel tool calls where possible to increase speed and efficiency. However, if some tool calls depend on previous calls to inform dependent values like the parameters, do NOT call these tools in parallel and instead call them sequentially. Never use placeholders or guess missing parameters in tool calls. + + + +Never speculate about code you have not opened. If the user references a specific file, you MUST read the file before answering. Make sure to investigate and read relevant files BEFORE answering questions about the codebase. Never make any claims about code before investigating unless you are certain of the correct answer - give grounded and hallucination-free answers. + + + +After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. +`; +/** +* Register the built-in Claude Sonnet 4.6 harness profile. +* +* Layers universal Claude guidance (parallel tool calls, grounded +* answers, post-tool reflection) onto `anthropic:claude-sonnet-4-6`. +* +* No Sonnet-specific overlays — Anthropic's guidance for Sonnet 4.6 +* centers on API-level configuration rather than system-prompt +* adjustments. This module exists as the audit anchor: its presence +* documents the review and justifies the absence of model-specific +* content. +* +* @internal +*/ +function register$2() { + registerHarnessProfileImpl("anthropic:claude-sonnet-4-6", createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX$2 })); +} +var SYSTEM_PROMPT_SUFFIX$1 = `\ + +If you intend to call multiple tools and there are no dependencies between the tool calls, make all of the independent tool calls in parallel. Prioritize calling tools simultaneously whenever the actions can be done in parallel rather than sequentially. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. Maximize use of parallel tool calls where possible to increase speed and efficiency. However, if some tool calls depend on previous calls to inform dependent values like the parameters, do NOT call these tools in parallel and instead call them sequentially. Never use placeholders or guess missing parameters in tool calls. + + + +Never speculate about code you have not opened. If the user references a specific file, you MUST read the file before answering. Make sure to investigate and read relevant files BEFORE answering questions about the codebase. Never make any claims about code before investigating unless you are certain of the correct answer - give grounded and hallucination-free answers. + + + +After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. +`; +/** +* Register the built-in Claude Haiku 4.5 harness profile. +* +* Same universal Claude guidance as Sonnet 4.6. No Haiku-specific +* overlays. +* +* @internal +*/ +function register$1() { + registerHarnessProfileImpl("anthropic:claude-haiku-4-5", createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX$1 })); +} +/** +* Model specs that receive the Codex harness profile. +* +* All variants share the same trained response style, so a single +* suffix works across the family. +*/ +var CODEX_MODEL_SPECS = [ + "openai:gpt-5.1-codex", + "openai:gpt-5.2-codex", + "openai:gpt-5.3-codex" +]; +var SYSTEM_PROMPT_SUFFIX = `\ +## Codex-Specific Behavior + +- You are an autonomous senior engineer. Once given a direction, proactively \ +gather context, plan, implement, and verify without waiting for additional \ +prompts at each step. +- Persist until the task is fully handled end-to-end within the current turn \ +whenever feasible. Do not stop at analysis or partial fixes; carry changes \ +through implementation, verification, and a clear explanation of outcomes. +- Bias to action: default to implementing with reasonable assumptions. Do not \ +end your turn with clarifications unless truly blocked. +- Do not communicate an upfront plan or status preamble before acting. Just act. + +## Parallel Tool Use + +- Before any tool call, decide ALL files and resources you will need. +- Batch reads, searches, and other independent operations into parallel tool \ +calls instead of issuing them one at a time. +- Only make sequential calls when you truly cannot determine the next step \ +without seeing a prior result. + +## Plan Hygiene + +- Before finishing, reconcile every TODO or plan item created via write_todos. \ +Mark each as done, blocked (with a one-sentence reason), or cancelled. Do not \ +finish with pending items.`; +function createExtraMiddleware() { + return [todoListMiddleware()]; +} +/** +* Register the built-in Codex harness profiles. +* +* Registers the same profile under each Codex model spec. Per-model +* keys (not the bare `"openai"` prefix) keep the default behavior of +* non-Codex OpenAI models unchanged. +* +* @internal +*/ +function register() { + const profile = createHarnessProfile({ + systemPromptSuffix: SYSTEM_PROMPT_SUFFIX, + extraMiddleware: createExtraMiddleware + }); + for (const spec of CODEX_MODEL_SPECS) registerHarnessProfileImpl(spec, profile); +} +/** +* Register all built-in harness profiles and snapshot the resulting +* registry keys as the builtin baseline. +* +* Called once during lazy bootstrap by `ensureBuiltinsLoaded()`. +* Uses `registerHarnessProfileImpl` internally (not the public +* `registerHarnessProfile`) to avoid triggering re-entrant bootstrap. +* +* @internal +*/ +function loadBuiltinProfiles() { + register$3(); + register$2(); + register$1(); + register(); + snapshotBuiltinKeys(); +} +/** +* Process-global symbol key for the harness profile registry. The `.v1` +* suffix is a version gate — bump it when the {@link HarnessProfileRegistry} +* shape changes in a breaking way so that incompatible versions coexist +* on `globalThis` without corrupting each other. +*/ +var PROFILE_REGISTRY_KEY = Symbol.for("deepagents.harness-profiles.v1"); +/** +* Returns the process-global registry, creating it on first access. +*/ +function getHarnessProfileRegistry() { + const global = globalThis; + if (global[PROFILE_REGISTRY_KEY] == null) global[PROFILE_REGISTRY_KEY] = { + profiles: /* @__PURE__ */ new Map(), + builtinKeys: /* @__PURE__ */ new Set(), + builtinsLoaded: false + }; + return global[PROFILE_REGISTRY_KEY]; +} +/** +* Ensure lazy-loaded builtin profiles have been registered. +* +* Called by the public `registerHarnessProfile` and lookup functions. +* Built-in registration modules call `registerHarnessProfileImpl` +* directly to avoid re-entrant bootstrap. +* +* @internal +*/ +function ensureBuiltinsLoaded() { + const registry = getHarnessProfileRegistry(); + if (registry.builtinsLoaded) return; + registry.builtinsLoaded = true; + loadBuiltinProfiles(); +} +/** +* Snapshot the current registry keys as the builtin baseline. +* +* Called by the builtin loader after all built-in profiles are +* registered. This allows {@link hasUserRegisteredProfiles} to +* distinguish user registrations from built-ins. +* +* @internal +*/ +function snapshotBuiltinKeys() { + const registry = getHarnessProfileRegistry(); + registry.builtinKeys = new Set(registry.profiles.keys()); +} +/** +* Core registration implementation. Does not trigger lazy bootstrap. +* +* Used by built-in profile modules during bootstrap. External callers +* should use {@link registerHarnessProfile} instead. +* +* @internal +*/ +function registerHarnessProfileImpl(key, profile) { + key = validateProfileKey(key); + const { profiles } = getHarnessProfileRegistry(); + const existing = profiles.get(key); + if (existing !== void 0) profiles.set(key, mergeProfiles(existing, profile)); + else profiles.set(key, profile); +} +/** +* Look up the {@link HarnessProfile} for a model spec string. +* +* Resolution order: +* +* 1. **Exact match** on `spec` (e.g., `"openai:gpt-5.4"`). +* 2. **Provider prefix** (everything before `:`) when `spec` contains +* a colon and both halves are non-empty. +* 3. When both exist, they are **merged** (provider as base, exact as +* override). +* 4. `undefined` when nothing matches. +* +* Malformed specs (empty, multiple colons, empty halves) return +* `undefined` without consulting the registry. +* +* @param spec - Model spec in `"provider:model"` format, or a bare +* provider/model identifier. +* @returns The matching profile, or `undefined`. +*/ +function getHarnessProfile(spec) { + if (spec.split(":").length > 2) return; + const colonIdx = spec.indexOf(":"); + const hasColon = colonIdx !== -1; + const provider = hasColon ? spec.slice(0, colonIdx) : void 0; + const model = hasColon ? spec.slice(colonIdx + 1) : void 0; + if (hasColon && (!provider || !model)) return; + ensureBuiltinsLoaded(); + const { profiles } = getHarnessProfileRegistry(); + const exact = profiles.get(spec); + const base = provider ? profiles.get(provider) : void 0; + if (exact !== void 0 && base !== void 0) return mergeProfiles(base, exact); + return exact ?? base; +} +/** +* Resolve the harness profile for a model, falling back to the +* empty default when nothing matches. +* +* When `spec` is set (the original model parameter), it drives the +* lookup directly. When absent (pre-built model instance), +* `providerHint` and `identifierHint` are used to construct lookup +* keys. +* +* @param opts - Model metadata used to resolve the profile. +* @returns The resolved profile (never `undefined`). +* +* @internal +*/ +function resolveHarnessProfile(opts = {}) { + const { spec, providerHint, identifierHint } = opts; + if (spec !== void 0) return getHarnessProfile(spec) ?? EMPTY_HARNESS_PROFILE; + if (providerHint && identifierHint && !identifierHint.includes(":")) { + const profile = getHarnessProfile(`${providerHint}:${identifierHint}`); + if (profile) return profile; + } + if (identifierHint && identifierHint.includes(":")) { + const profile = getHarnessProfile(identifierHint); + if (profile) return profile; + } + if (providerHint) { + const profile = getHarnessProfile(providerHint); + if (profile) return profile; + } + return EMPTY_HARNESS_PROFILE; +} +/** +* Apply a profile's prompt overlay to a base prompt string. +* +* - `baseSystemPrompt` (when set) replaces `basePrompt` entirely. +* - `systemPromptSuffix` (when set) is appended with `\n\n`. +* +* Both are independently optional. A profile that sets only the suffix +* layers it on top of whatever base the caller passes in. +* +* Used uniformly for the main agent, declarative subagents, and the +* auto-added general-purpose subagent. +* +* @param profile - The harness profile to apply. +* @param basePrompt - The active base prompt (empty by default). +* @returns The assembled prompt string. +*/ +function applyProfilePrompt(profile, basePrompt) { + const prompt = profile.baseSystemPrompt !== void 0 ? profile.baseSystemPrompt : basePrompt; + if (profile.systemPromptSuffix !== void 0) return prompt ? `${prompt}\n\n${profile.systemPromptSuffix}` : profile.systemPromptSuffix; + return prompt; +} +function normalizeSystemPrompt(systemPrompt) { + if (systemPrompt === void 0) return {}; + if (typeof systemPrompt === "string" || SystemMessage.isInstance(systemPrompt)) return { prefix: systemPrompt }; + return systemPrompt; +} +function assemblePromptParts(parts) { + const nonEmptyParts = parts.filter((part) => part != null && (typeof part !== "string" || part.length > 0)); + if (nonEmptyParts.length === 0) return ""; + if (nonEmptyParts.every((part) => typeof part === "string")) return nonEmptyParts.join("\n\n"); + const contentBlocks = []; + for (const [index, part] of nonEmptyParts.entries()) { + if (index > 0) contentBlocks.push({ + type: "text", + text: "\n\n" + }); + if (SystemMessage.isInstance(part)) contentBlocks.push(...part.contentBlocks); + else contentBlocks.push({ + type: "text", + text: part + }); + } + return new SystemMessage({ contentBlocks }); +} +var BUILTIN_TOOL_NAMES = /* @__PURE__ */ new Set([ + ...FILESYSTEM_TOOL_NAMES, + ...ASYNC_TASK_TOOL_NAMES, + "task" +]); +/** +* Create a Deep Agent. +* +* This is the main entry point for building a production-style agent with +* deepagents. It gives you a strong default runtime (filesystem, tasks, +* subagents, summarization) and lets you opt into skills, memory, +* human-in-the-loop interrupts, async subagents, and custom middleware. +* +* The runtime is intentionally opinionated: defaults work out of the box, and +* when you customize behavior, the middleware ordering stays deterministic. +* +* @param params Configuration parameters for the agent +* @returns Deep Agent instance with inferred state/response types +* +* @example +* ```typescript +* // Custom state from middleware and/or the agent stateSchema param — both are merged +* const ResearchMiddleware = createMiddleware({ +* name: "ResearchMiddleware", +* stateSchema: z.object({ research: z.string().default("") }), +* }); +* +* const agent = createDeepAgent({ +* middleware: [ResearchMiddleware], +* stateSchema: z.object({ author: z.string().default("Me") }), +* }); +* +* const result = await agent.invoke({ messages: [...] }); +* // result.research and result.author are properly typed as strings +* ``` +*/ +function createDeepAgent(params = {}) { + const { model = "anthropic:claude-sonnet-4-6", tools = [], systemPrompt, stateSchema, middleware: customMiddleware = [], subagents = [], responseFormat, contextSchema, checkpointer, store, backend = (config) => new StateBackend(config), interruptOn, name, memory, skills, permissions = [], streamTransformers = [] } = params; + const collidingTools = tools.map((t) => t.name).filter((n) => typeof n === "string" && BUILTIN_TOOL_NAMES.has(n)); + if (collidingTools.length > 0) throw new ConfigurationError(`Tool name(s) [${collidingTools.join(", ")}] conflict with built-in tools. Rename your custom tools to avoid this.`, "TOOL_NAME_COLLISION"); + const harnessProfile = typeof model === "string" ? resolveHarnessProfile({ spec: model }) : resolveHarnessProfile({ + providerHint: getModelProvider(model), + identifierHint: getModelIdentifier(model) + }); + const filesystemTools = FILESYSTEM_TOOL_NAMES.filter((toolName) => !harnessProfile.excludedTools.has(toolName)); + const profileFilesystemTools = filesystemTools.length === FILESYSTEM_TOOL_NAMES.length || !filesystemTools.includes("read_file") ? void 0 : filesystemTools; + const toolOverrides = harnessProfile.toolDescriptionOverrides; + const effectiveTools = Object.keys(toolOverrides).length > 0 ? tools.map((t) => t.name in toolOverrides ? Object.assign(Object.create(Object.getPrototypeOf(t)), t, { description: toolOverrides[t.name] }) : t) : tools; + const anthropicModel = isAnthropicModel(model); + const bedrockModel = isBedrockConverseModel(model); + let cacheMiddleware = []; + if (anthropicModel) cacheMiddleware = [ + ...cacheMiddleware, + anthropicPromptCachingMiddleware({ + unsupportedModelBehavior: "ignore", + minMessagesToCache: 1 + }), + createCacheBreakpointMiddleware() + ]; + if (bedrockModel) cacheMiddleware = [...cacheMiddleware, bedrockPromptCachingMiddleware({ unsupportedModelBehavior: "ignore" })]; + /** + * Process subagents to add SkillsMiddleware for those with their own skills. + * + * Custom subagents do NOT inherit skills from the main agent by default. + * Only the general-purpose subagent inherits the main agent's skills. + * If a custom subagent needs skills, it must specify its own `skills` array. + */ + const createSubagentDefaultMiddleware = (input) => { + const effectivePermissions = input.permissions ?? permissions; + return [ + createFilesystemMiddleware({ + backend, + permissions: effectivePermissions, + tools: profileFilesystemTools + }), + createSummarizationMiddleware({ backend }), + createPatchToolCallsMiddleware(), + ...input.skills != null && input.skills.length > 0 ? [createSkillsMiddleware({ + backend, + sources: input.skills + })] : [] + ]; + }; + const normalizeSubagentSpec = (input) => { + let subagentMiddleware = mergeMiddlewareStack(createSubagentDefaultMiddleware(input), input.middleware ?? [], [...resolveMiddleware(harnessProfile.extraMiddleware), ...cacheMiddleware]); + if (harnessProfile.excludedMiddleware.size > 0) subagentMiddleware = subagentMiddleware.filter((middleware) => !harnessProfile.excludedMiddleware.has(middleware.name)); + return { + ...input, + tools: input.tools ?? [], + middleware: subagentMiddleware + }; + }; + const allSubagents = subagents; + const asyncSubAgents = allSubagents.filter((item) => isAsyncSubAgent(item)); + const inlineSubagents = allSubagents.filter((item) => !isAsyncSubAgent(item)).map((item) => "runnable" in item ? item : normalizeSubagentSpec(item)); + const gpConfig = harnessProfile.generalPurposeSubagent; + if (!(gpConfig?.enabled === false) && !inlineSubagents.some((item) => item.name === GENERAL_PURPOSE_SUBAGENT["name"])) { + const gpSystemPrompt = gpConfig?.systemPrompt ?? applyProfilePrompt(harnessProfile, GENERAL_PURPOSE_SUBAGENT.systemPrompt); + const generalPurposeSpec = normalizeSubagentSpec({ + ...GENERAL_PURPOSE_SUBAGENT, + description: gpConfig?.description ?? GENERAL_PURPOSE_SUBAGENT.description, + systemPrompt: gpSystemPrompt, + model, + skills, + tools: effectiveTools + }); + generalPurposeSpec.middleware = mergeMiddlewareStack(generalPurposeSpec.middleware ?? [], customMiddleware, [], { appendNew: false }); + inlineSubagents.unshift(generalPurposeSpec); + } + const skillsMiddleware = skills != null && skills.length > 0 ? [createSkillsMiddleware({ + backend, + sources: skills + })] : []; + const [fsMiddleware, subagentMiddleware, summarizationMiddleware, patchToolCallsMiddleware] = [ + createFilesystemMiddleware({ + backend, + permissions, + tools: profileFilesystemTools + }), + createSubAgentMiddleware({ + defaultModel: model, + defaultTools: effectiveTools, + defaultInterruptOn: interruptOn, + subagents: inlineSubagents, + generalPurposeAgent: false + }), + createSummarizationMiddleware({ backend }), + createPatchToolCallsMiddleware() + ]; + let middleware = mergeMiddlewareStack([ + ...skillsMiddleware, + fsMiddleware, + subagentMiddleware, + summarizationMiddleware, + patchToolCallsMiddleware, + ...asyncSubAgents.length > 0 ? [createAsyncSubAgentMiddleware({ asyncSubAgents })] : [] + ], customMiddleware, [ + ...resolveMiddleware(harnessProfile.extraMiddleware), + ...cacheMiddleware, + ...memory && memory.length > 0 ? [createMemoryMiddleware({ + backend, + sources: memory, + addCacheControl: anthropicModel + })] : [], + ...interruptOn ? [humanInTheLoopMiddleware({ interruptOn })] : [] + ]); + if (harnessProfile.excludedMiddleware.size > 0) { + const excluded = harnessProfile.excludedMiddleware; + middleware = middleware.filter((entry) => !excluded.has(entry.name)); + } + if (harnessProfile.excludedTools.size > 0) middleware.push(createToolExclusionMiddleware(harnessProfile.excludedTools)); + const promptConfig = normalizeSystemPrompt(systemPrompt); + const activeBasePrompt = promptConfig.base !== void 0 ? promptConfig.base : harnessProfile.baseSystemPrompt; + const finalSystemPrompt = assemblePromptParts([ + promptConfig.prefix, + activeBasePrompt, + promptConfig.suffix, + harnessProfile.systemPromptSuffix + ]); + /** + * Return as DeepAgent with proper DeepAgentTypeConfig + * - Response: InferStructuredResponse (unwraps ToolStrategy/ProviderStrategy → T) + * - State: User-provided stateSchema, merged with middleware-derived state downstream + * - Context: ContextSchema + * - Middleware: AllMiddleware (built-in + custom + subagent middleware for state inference) + * - Tools: TTools + * - Subagents: TSubagents (for type-safe streaming) + * - StreamTransformers: TStreamTransformers + */ + return createAgent({ + model, + ...finalSystemPrompt !== "" && { systemPrompt: finalSystemPrompt }, + stateSchema, + tools: effectiveTools, + middleware, + ...responseFormat !== null && { responseFormat }, + contextSchema, + checkpointer, + store, + name, + streamTransformers + }).withConfig({ + recursionLimit: 1e4, + metadata: { + ls_integration: "deepagents", + lc_agent_name: name + } + }); +} +context` + You are a Deep Agent, an AI assistant that helps users accomplish tasks using tools. You respond with text and tool calls. The user can see your responses and tool outputs in real time. + + ## Core Behavior + + - Be concise and direct. Don't over-explain unless asked. + - NEVER add unnecessary preamble (\"Sure!\", \"Great question!\", \"I'll now...\"). + - Don't say \"I'll now do X\" — just do it. + - If the request is ambiguous, ask questions before acting. + - If asked how to approach something, explain first, then act. + + ## Professional Objectivity + + - Prioritize accuracy over validating the user's beliefs + - Disagree respectfully when the user is incorrect + - Avoid unnecessary superlatives, praise, or emotional validation + + ## Doing Tasks + + When the user asks you to do something: + + 1. **Understand first** — read relevant files, check existing patterns. Quick but thorough — gather enough evidence to start, then iterate. + 2. **Act** — implement the solution. Work quickly but accurately. + 3. **Verify** — check your work against what was asked, not against your own output. Your first attempt is rarely correct — iterate. + + Keep working until the task is fully complete. Don't stop partway and explain what you would do — just do it. Only yield back to the user when the task is done or you're genuinely blocked. + + **When things go wrong:** + - If something fails repeatedly, stop and analyze *why* — don't keep retrying the same approach. + - If you're blocked, tell the user what's wrong and ask for guidance. + + ## Progress Updates + + For longer tasks, provide brief progress updates at reasonable intervals — a concise sentence recapping what you've done and what's next. +`; +context` + ## \`task\` (subagent spawner) + + You have access to a \`task\` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result. + + When to use the task tool: + - When a task is complex and multi-step, and can be fully delegated in isolation + - When a task is independent of other tasks and can run in parallel + - When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread + - When sandboxing improves reliability (e.g. code execution, structured searches, data formatting) + - When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.) + + Subagent lifecycle: + 1. **Spawn** → Provide clear role, instructions, and expected output + 2. **Run** → The subagent completes the task autonomously + 3. **Return** → The subagent provides a single structured result + 4. **Reconcile** → Incorporate or synthesize the result into the main thread + + When NOT to use the task tool: + - If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them) + - If the task is trivial (a few tool calls or simple lookup) + - If delegating does not reduce token usage, complexity, or context switching + - If splitting would add latency without benefit + + ## Important Task Tool Usage Notes to Remember + - Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important. + - Remember to use the \`task\` tool to silo independent tasks within a multi-part objective. + - You should use the \`task\` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient. +`; +context` + ## Execute Tool \`execute\` + + You have access to an \`execute\` tool for running shell commands in a sandboxed environment. + Use this tool to run commands, scripts, tests, builds, and other shell operations. + + - execute: run a shell command in the sandbox (returns output and exit code) +`; +//#endregion +//#region node_modules/fast-glob/out/utils/array.js +var require_array = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.splitWhen = exports.flatten = void 0; + function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); + } + exports.flatten = flatten; + function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } else result[groupIndex].push(item); + return result; + } + exports.splitWhen = splitWhen; +})); +//#endregion +//#region node_modules/fast-glob/out/utils/errno.js +var require_errno = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isEnoentCodeError = void 0; + function isEnoentCodeError(error) { + return error.code === "ENOENT"; + } + exports.isEnoentCodeError = isEnoentCodeError; +})); +//#endregion +//#region node_modules/fast-glob/out/utils/fs.js +var require_fs = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createDirentFromStats = void 0; + var DirentFromStats = class { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } + }; + function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); + } + exports.createDirentFromStats = createDirentFromStats; +})); +//#endregion +//#region node_modules/fast-glob/out/utils/path.js +var require_path = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0; + var os$2 = __require("os"); + var path$4 = __require("path"); + var IS_WINDOWS_PLATFORM = os$2.platform() === "win32"; + var LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; + /** + * All non-escaped special characters. + * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. + * Windows: (){}[], !+@ before (, ! at the beginning. + */ + var POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; + var WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; + /** + * The device path (\\.\ or \\?\). + * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths + */ + var DOS_DEVICE_PATH_RE = /^\\\\([.?])/; + /** + * All backslashes except those escaping special characters. + * Windows: !()+@{} + * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions + */ + var WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; + /** + * Designed to work only with simple paths: `dir\\file`. + */ + function unixify(filepath) { + return filepath.replace(/\\/g, "/"); + } + exports.unixify = unixify; + function makeAbsolute(cwd, filepath) { + return path$4.resolve(cwd, filepath); + } + exports.makeAbsolute = makeAbsolute; + function removeLeadingDotSegment(entry) { + if (entry.charAt(0) === ".") { + const secondCharactery = entry.charAt(1); + if (secondCharactery === "/" || secondCharactery === "\\") return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + return entry; + } + exports.removeLeadingDotSegment = removeLeadingDotSegment; + exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; + function escapeWindowsPath(pattern) { + return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2"); + } + exports.escapeWindowsPath = escapeWindowsPath; + function escapePosixPath(pattern) { + return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2"); + } + exports.escapePosixPath = escapePosixPath; + exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; + function convertWindowsPathToPattern(filepath) { + return escapeWindowsPath(filepath).replace(DOS_DEVICE_PATH_RE, "//$1").replace(WINDOWS_BACKSLASHES_RE, "/"); + } + exports.convertWindowsPathToPattern = convertWindowsPathToPattern; + function convertPosixPathToPattern(filepath) { + return escapePosixPath(filepath); + } + exports.convertPosixPathToPattern = convertPosixPathToPattern; +})); +//#endregion +//#region node_modules/is-extglob/index.js +var require_is_extglob = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + module.exports = function isExtglob(str) { + if (typeof str !== "string" || str === "") return false; + var match; + while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + return false; + }; +})); +//#endregion +//#region node_modules/is-glob/index.js +var require_is_glob = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + var isExtglob = require_is_extglob(); + var chars = { + "{": "}", + "(": ")", + "[": "]" + }; + var strictCheck = function(str) { + if (str[0] === "!") return true; + var index = 0; + var pipeIndex = -2; + var closeSquareIndex = -2; + var closeCurlyIndex = -2; + var closeParenIndex = -2; + var backSlashIndex = -2; + while (index < str.length) { + if (str[index] === "*") return true; + if (str[index + 1] === "?" && /[\].+)]/.test(str[index])) return true; + if (closeSquareIndex !== -1 && str[index] === "[" && str[index + 1] !== "]") { + if (closeSquareIndex < index) closeSquareIndex = str.indexOf("]", index); + if (closeSquareIndex > index) { + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true; + backSlashIndex = str.indexOf("\\", index); + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true; + } + } + if (closeCurlyIndex !== -1 && str[index] === "{" && str[index + 1] !== "}") { + closeCurlyIndex = str.indexOf("}", index); + if (closeCurlyIndex > index) { + backSlashIndex = str.indexOf("\\", index); + if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) return true; + } + } + if (closeParenIndex !== -1 && str[index] === "(" && str[index + 1] === "?" && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ")") { + closeParenIndex = str.indexOf(")", index); + if (closeParenIndex > index) { + backSlashIndex = str.indexOf("\\", index); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true; + } + } + if (pipeIndex !== -1 && str[index] === "(" && str[index + 1] !== "|") { + if (pipeIndex < index) pipeIndex = str.indexOf("|", index); + if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") { + closeParenIndex = str.indexOf(")", pipeIndex); + if (closeParenIndex > pipeIndex) { + backSlashIndex = str.indexOf("\\", pipeIndex); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true; + } + } + } + if (str[index] === "\\") { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) index = n + 1; + } + if (str[index] === "!") return true; + } else index++; + } + return false; + }; + var relaxedCheck = function(str) { + if (str[0] === "!") return true; + var index = 0; + while (index < str.length) { + if (/[*?{}()[\]]/.test(str[index])) return true; + if (str[index] === "\\") { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) index = n + 1; + } + if (str[index] === "!") return true; + } else index++; + } + return false; + }; + module.exports = function isGlob(str, options) { + if (typeof str !== "string" || str === "") return false; + if (isExtglob(str)) return true; + var check = strictCheck; + if (options && options.strict === false) check = relaxedCheck; + return check(str); + }; +})); +//#endregion +//#region node_modules/fast-glob/node_modules/glob-parent/index.js +var require_glob_parent = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var isGlob = require_is_glob(); + var pathPosixDirname = __require("path").posix.dirname; + var isWin32 = __require("os").platform() === "win32"; + var slash = "/"; + var backslash = /\\/g; + var enclosure = /[\{\[].*[\}\]]$/; + var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; + var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + /** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + * @returns {string} + */ + module.exports = function globParent(str, opts) { + if (Object.assign({ flipBackslashes: true }, opts).flipBackslashes && isWin32 && str.indexOf(slash) < 0) str = str.replace(backslash, slash); + if (enclosure.test(str)) str += slash; + str += "a"; + do + str = pathPosixDirname(str); + while (isGlob(str) || globby.test(str)); + return str.replace(escaped, "$1"); + }; +})); +//#endregion +//#region node_modules/fast-glob/out/utils/pattern.js +var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; + var path$3 = __require("path"); + var globParent = require_glob_parent(); + var micromatch = require_micromatch(); + var GLOBSTAR = "**"; + var ESCAPE_SYMBOL = "\\"; + var COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; + var REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; + var REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; + var GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; + var BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; + /** + * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. + * The latter is due to the presence of the device path at the beginning of the UNC path. + */ + var DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; + function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); + } + exports.isStaticPattern = isStaticPattern; + function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === "") return false; + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) return true; + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) return true; + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) return true; + if (options.braceExpansion !== false && hasBraceExpansion(pattern)) return true; + return false; + } + exports.isDynamicPattern = isDynamicPattern; + function hasBraceExpansion(pattern) { + const openingBraceIndex = pattern.indexOf("{"); + if (openingBraceIndex === -1) return false; + const closingBraceIndex = pattern.indexOf("}", openingBraceIndex + 1); + if (closingBraceIndex === -1) return false; + const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); + return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); + } + function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; + } + exports.convertToPositivePattern = convertToPositivePattern; + function convertToNegativePattern(pattern) { + return "!" + pattern; + } + exports.convertToNegativePattern = convertToNegativePattern; + function isNegativePattern(pattern) { + return pattern.startsWith("!") && pattern[1] !== "("; + } + exports.isNegativePattern = isNegativePattern; + function isPositivePattern(pattern) { + return !isNegativePattern(pattern); + } + exports.isPositivePattern = isPositivePattern; + function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); + } + exports.getNegativePatterns = getNegativePatterns; + function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); + } + exports.getPositivePatterns = getPositivePatterns; + /** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ + function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); + } + exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; + /** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ + function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); + } + exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; + function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith("..") || pattern.startsWith("./.."); + } + exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; + function getBaseDirectory(pattern) { + return globParent(pattern, { flipBackslashes: false }); + } + exports.getBaseDirectory = getBaseDirectory; + function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); + } + exports.hasGlobStar = hasGlobStar; + function endsWithSlashGlobStar(pattern) { + return pattern.endsWith("/**"); + } + exports.endsWithSlashGlobStar = endsWithSlashGlobStar; + function isAffectDepthOfReadingPattern(pattern) { + const basename = path$3.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); + } + exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; + function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); + } + exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; + function expandBraceExpansion(pattern) { + const patterns = micromatch.braces(pattern, { + expand: true, + nodupes: true, + keepEscaping: true + }); + /** + * Sort the patterns by length so that the same depth patterns are processed side by side. + * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` + */ + patterns.sort((a, b) => a.length - b.length); + /** + * Micromatch can return an empty string in the case of patterns like `{a,}`. + */ + return patterns.filter((pattern) => pattern !== ""); + } + exports.expandBraceExpansion = expandBraceExpansion; + function getPatternParts(pattern, options) { + let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + if (parts.length === 0) parts = [pattern]; + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + if (parts[0].startsWith("/")) { + parts[0] = parts[0].slice(1); + parts.unshift(""); + } + return parts; + } + exports.getPatternParts = getPatternParts; + function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); + } + exports.makeRe = makeRe; + function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); + } + exports.convertPatternsToRe = convertPatternsToRe; + function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); + } + exports.matchAny = matchAny; + /** + * This package only works with forward slashes as a path separator. + * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + */ + function removeDuplicateSlashes(pattern) { + return pattern.replace(DOUBLE_SLASH_RE, "/"); + } + exports.removeDuplicateSlashes = removeDuplicateSlashes; + function partitionAbsoluteAndRelative(patterns) { + const absolute = []; + const relative = []; + for (const pattern of patterns) if (isAbsolute(pattern)) absolute.push(pattern); + else relative.push(pattern); + return [absolute, relative]; + } + exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative; + function isAbsolute(pattern) { + return path$3.isAbsolute(pattern); + } + exports.isAbsolute = isAbsolute; +})); +//#endregion +//#region node_modules/merge2/index.js +var require_merge2 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var PassThrough = __require("stream").PassThrough; + var slice = Array.prototype.slice; + module.exports = merge2; + function merge2() { + const streamsQueue = []; + const args = slice.call(arguments); + let merging = false; + let options = args[args.length - 1]; + if (options && !Array.isArray(options) && options.pipe == null) args.pop(); + else options = {}; + const doEnd = options.end !== false; + const doPipeError = options.pipeError === true; + if (options.objectMode == null) options.objectMode = true; + if (options.highWaterMark == null) options.highWaterMark = 64 * 1024; + const mergedStream = PassThrough(options); + function addStream() { + for (let i = 0, len = arguments.length; i < len; i++) streamsQueue.push(pauseStreams(arguments[i], options)); + mergeStream(); + return this; + } + function mergeStream() { + if (merging) return; + merging = true; + let streams = streamsQueue.shift(); + if (!streams) { + process.nextTick(endStream); + return; + } + if (!Array.isArray(streams)) streams = [streams]; + let pipesCount = streams.length + 1; + function next() { + if (--pipesCount > 0) return; + merging = false; + mergeStream(); + } + function pipe(stream) { + function onend() { + stream.removeListener("merge2UnpipeEnd", onend); + stream.removeListener("end", onend); + if (doPipeError) stream.removeListener("error", onerror); + next(); + } + function onerror(err) { + mergedStream.emit("error", err); + } + if (stream._readableState.endEmitted) return next(); + stream.on("merge2UnpipeEnd", onend); + stream.on("end", onend); + if (doPipeError) stream.on("error", onerror); + stream.pipe(mergedStream, { end: false }); + stream.resume(); + } + for (let i = 0; i < streams.length; i++) pipe(streams[i]); + next(); + } + function endStream() { + merging = false; + mergedStream.emit("queueDrain"); + if (doEnd) mergedStream.end(); + } + mergedStream.setMaxListeners(0); + mergedStream.add = addStream; + mergedStream.on("unpipe", function(stream) { + stream.emit("merge2UnpipeEnd"); + }); + if (args.length) addStream.apply(null, args); + return mergedStream; + } + function pauseStreams(streams, options) { + if (!Array.isArray(streams)) { + if (!streams._readableState && streams.pipe) streams = streams.pipe(PassThrough(options)); + if (!streams._readableState || !streams.pause || !streams.pipe) throw new Error("Only readable stream can be merged."); + streams.pause(); + } else for (let i = 0, len = streams.length; i < len; i++) streams[i] = pauseStreams(streams[i], options); + return streams; + } +})); +//#endregion +//#region node_modules/fast-glob/out/utils/stream.js +var require_stream$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.merge = void 0; + var merge2 = require_merge2(); + function merge(streams) { + const mergedStream = merge2(streams); + streams.forEach((stream) => { + stream.once("error", (error) => mergedStream.emit("error", error)); + }); + mergedStream.once("close", () => propagateCloseEventToSources(streams)); + mergedStream.once("end", () => propagateCloseEventToSources(streams)); + return mergedStream; + } + exports.merge = merge; + function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit("close")); + } +})); +//#endregion +//#region node_modules/fast-glob/out/utils/string.js +var require_string = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isEmpty = exports.isString = void 0; + function isString(input) { + return typeof input === "string"; + } + exports.isString = isString; + function isEmpty(input) { + return input === ""; + } + exports.isEmpty = isEmpty; +})); +//#endregion +//#region node_modules/fast-glob/out/utils/index.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; + exports.array = require_array(); + exports.errno = require_errno(); + exports.fs = require_fs(); + exports.path = require_path(); + exports.pattern = require_pattern(); + exports.stream = require_stream$2(); + exports.string = require_string(); +})); +//#endregion +//#region node_modules/fast-glob/out/managers/tasks.js +var require_tasks = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; + var utils = require_utils(); + function generate(input, settings) { + const patterns = processPatterns(input, settings); + const ignore = processPatterns(settings.ignore, settings); + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, true); + return staticTasks.concat(dynamicTasks); + } + exports.generate = generate; + function processPatterns(input, settings) { + let patterns = input; + /** + * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry + * and some problems with the micromatch package (see fast-glob issues: #365, #394). + * + * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown + * in matching in the case of a large set of patterns after expansion. + */ + if (settings.braceExpansion) patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns); + /** + * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used + * at any nesting level. + * + * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change + * the pattern in the filter before creating a regular expression. There is no need to change the patterns + * in the application. Only on the input. + */ + if (settings.baseNameMatch) patterns = patterns.map((pattern) => pattern.includes("/") ? pattern : `**/${pattern}`); + /** + * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. + */ + return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern)); + } + /** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ + function convertPatternsToTasks(positive, negative, dynamic) { + const tasks = []; + const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); + const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); + const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); + tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); + if ("." in insideCurrentDirectoryGroup) tasks.push(convertPatternGroupToTask(".", patternsInsideCurrentDirectory, negative, dynamic)); + else tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + return tasks; + } + exports.convertPatternsToTasks = convertPatternsToTasks; + function getPositivePatterns(patterns) { + return utils.pattern.getPositivePatterns(patterns); + } + exports.getPositivePatterns = getPositivePatterns; + function getNegativePatternsAsPositive(patterns, ignore) { + return utils.pattern.getNegativePatterns(patterns).concat(ignore).map(utils.pattern.convertToPositivePattern); + } + exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; + function groupPatternsByBaseDirectory(patterns) { + return patterns.reduce((collection, pattern) => { + const base = utils.pattern.getBaseDirectory(pattern); + if (base in collection) collection[base].push(pattern); + else collection[base] = [pattern]; + return collection; + }, {}); + } + exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; + function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); + } + exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; + function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) + }; + } + exports.convertPatternGroupToTask = convertPatternGroupToTask; +})); +//#endregion +//#region node_modules/fast-glob/out/readers/reader.js +var require_reader = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var path$2 = __require("path"); + var fsStat = require_out$1(); + var utils = require_utils(); + var Reader = class { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path$2.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) entry.stats = stats; + return entry; + } + _isFatalError(error) { + return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } + }; + exports.default = Reader; +})); +//#endregion +//#region node_modules/fast-glob/out/readers/stream.js +var require_stream$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var stream_1$1 = __require("stream"); + var fsStat = require_out$1(); + var fsWalk = require_out$2(); + var reader_1 = require_reader(); + var ReaderStream = class extends reader_1.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk.walkStream; + this._stat = fsStat.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream_1$1.PassThrough({ objectMode: true }); + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options).then((entry) => { + if (entry !== null && options.entryFilter(entry)) stream.push(entry); + if (index === filepaths.length - 1) stream.end(); + done(); + }).catch(done); + }; + for (let i = 0; i < filepaths.length; i++) stream.write(i); + return stream; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath).then((stats) => this._makeEntry(stats, pattern)).catch((error) => { + if (options.errorFilter(error)) return null; + throw error; + }); + } + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } + }; + exports.default = ReaderStream; +})); +//#endregion +//#region node_modules/fast-glob/out/readers/async.js +var require_async$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var fsWalk = require_out$2(); + var reader_1 = require_reader(); + var stream_1 = require_stream$1(); + var ReaderAsync = class extends reader_1.default { + constructor() { + super(...arguments); + this._walkAsync = fsWalk.walk; + this._readerStream = new stream_1.default(this._settings); + } + dynamic(root, options) { + return new Promise((resolve, reject) => { + this._walkAsync(root, options, (error, entries) => { + if (error === null) resolve(entries); + else reject(error); + }); + }); + } + async static(patterns, options) { + const entries = []; + const stream = this._readerStream.static(patterns, options); + return new Promise((resolve, reject) => { + stream.once("error", reject); + stream.on("data", (entry) => entries.push(entry)); + stream.once("end", () => resolve(entries)); + }); + } + }; + exports.default = ReaderAsync; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/matchers/matcher.js +var require_matcher = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils(); + var Matcher = class { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + for (const pattern of this._patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + _getPatternSegments(pattern) { + return utils.pattern.getPatternParts(pattern, this._micromatchOptions).map((part) => { + if (!utils.pattern.isDynamicPattern(part, this._settings)) return { + dynamic: false, + pattern: part + }; + return { + dynamic: true, + pattern: part, + patternRe: utils.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); + } + }; + exports.default = Matcher; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/matchers/partial.js +var require_partial = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var matcher_1 = require_matcher(); + var PartialMatcher = class extends matcher_1.default { + match(filepath) { + const parts = filepath.split("/"); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + if (!pattern.complete && levels > section.length) return true; + if (parts.every((part, index) => { + const segment = pattern.segments[index]; + if (segment.dynamic && segment.patternRe.test(part)) return true; + if (!segment.dynamic && segment.pattern === part) return true; + return false; + })) return true; + } + return false; + } + }; + exports.default = PartialMatcher; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/filters/deep.js +var require_deep = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils(); + var partial_1 = require_partial(); + var DeepFilter = class { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); + } + _getMatcher(patterns) { + return new partial_1.default(patterns, this._settings, this._micromatchOptions); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); + return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) return false; + if (this._isSkippedSymbolicLink(entry)) return false; + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) return false; + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) return false; + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split("/").length; + if (basePath === "") return entryPathDepth; + return entryPathDepth - basePath.split("/").length; + } + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils.pattern.matchAny(entryPath, patternsRe); + } + }; + exports.default = DeepFilter; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/filters/entry.js +var require_entry$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils(); + var EntryFilter = class { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = /* @__PURE__ */ new Map(); + } + getFilter(positive, negative) { + const [absoluteNegative, relativeNegative] = utils.pattern.partitionAbsoluteAndRelative(negative); + const patterns = { + positive: { all: utils.pattern.convertPatternsToRe(positive, this._micromatchOptions) }, + negative: { + absolute: utils.pattern.convertPatternsToRe(absoluteNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })), + relative: utils.pattern.convertPatternsToRe(relativeNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })) + } + }; + return (entry) => this._filter(entry, patterns); + } + _filter(entry, patterns) { + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._settings.unique && this._isDuplicateEntry(filepath)) return false; + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) return false; + const isMatched = this._isMatchToPatternsSet(filepath, patterns, entry.dirent.isDirectory()); + if (this._settings.unique && isMatched) this._createIndexRecord(filepath); + return isMatched; + } + _isDuplicateEntry(filepath) { + return this.index.has(filepath); + } + _createIndexRecord(filepath) { + this.index.set(filepath, void 0); + } + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isMatchToPatternsSet(filepath, patterns, isDirectory) { + if (!this._isMatchToPatterns(filepath, patterns.positive.all, isDirectory)) return false; + if (this._isMatchToPatterns(filepath, patterns.negative.relative, isDirectory)) return false; + if (this._isMatchToAbsoluteNegative(filepath, patterns.negative.absolute, isDirectory)) return false; + return true; + } + _isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) return false; + const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath); + return this._isMatchToPatterns(fullpath, patternsRe, isDirectory); + } + _isMatchToPatterns(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) return false; + const isMatched = utils.pattern.matchAny(filepath, patternsRe); + if (!isMatched && isDirectory) return utils.pattern.matchAny(filepath + "/", patternsRe); + return isMatched; + } + }; + exports.default = EntryFilter; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/filters/error.js +var require_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils(); + var ErrorFilter = class { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } + }; + exports.default = ErrorFilter; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/transformers/entry.js +var require_entry = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils(); + var EntryTransformer = class { + constructor(_settings) { + this._settings = _settings; + } + getTransformer() { + return (entry) => this._transform(entry); + } + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils.path.unixify(filepath); + } + if (this._settings.markDirectories && entry.dirent.isDirectory()) filepath += "/"; + if (!this._settings.objectMode) return filepath; + return Object.assign(Object.assign({}, entry), { path: filepath }); + } + }; + exports.default = EntryTransformer; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/provider.js +var require_provider = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var path$1 = __require("path"); + var deep_1 = require_deep(); + var entry_1 = require_entry$1(); + var error_1 = require_error(); + var entry_2 = require_entry(); + var Provider = class { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error_1.default(this._settings); + this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry_2.default(this._settings); + } + _getRootDirectory(task) { + return path$1.resolve(this._settings.cwd, task.base); + } + _getReaderOptions(task) { + const basePath = task.base === "." ? "" : task.base; + return { + basePath, + pathSegmentSeparator: "/", + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } + }; + exports.default = Provider; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/async.js +var require_async = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var async_1 = require_async$1(); + var provider_1 = require_provider(); + var ProviderAsync = class extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new async_1.default(this._settings); + } + async read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + return (await this.api(root, task, options)).map((entry) => options.transform(entry)); + } + api(root, task, options) { + if (task.dynamic) return this._reader.dynamic(root, options); + return this._reader.static(task.patterns, options); + } + }; + exports.default = ProviderAsync; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/stream.js +var require_stream = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var stream_1 = __require("stream"); + var stream_2 = require_stream$1(); + var provider_1 = require_provider(); + var ProviderStream = class extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const destination = new stream_1.Readable({ + objectMode: true, + read: () => {} + }); + source.once("error", (error) => destination.emit("error", error)).on("data", (entry) => destination.emit("data", options.transform(entry))).once("end", () => destination.emit("end")); + destination.once("close", () => source.destroy()); + return destination; + } + api(root, task, options) { + if (task.dynamic) return this._reader.dynamic(root, options); + return this._reader.static(task.patterns, options); + } + }; + exports.default = ProviderStream; +})); +//#endregion +//#region node_modules/fast-glob/out/readers/sync.js +var require_sync$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var fsStat = require_out$1(); + var fsWalk = require_out$2(); + var reader_1 = require_reader(); + var ReaderSync = class extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) continue; + entries.push(entry); + } + return entries; + } + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } catch (error) { + if (options.errorFilter(error)) return null; + throw error; + } + } + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } + }; + exports.default = ReaderSync; +})); +//#endregion +//#region node_modules/fast-glob/out/providers/sync.js +var require_sync = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var sync_1 = require_sync$1(); + var provider_1 = require_provider(); + var ProviderSync = class extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + return this.api(root, task, options).map(options.transform); + } + api(root, task, options) { + if (task.dynamic) return this._reader.dynamic(root, options); + return this._reader.static(task.patterns, options); + } + }; + exports.default = ProviderSync; +})); +//#endregion +//#region node_modules/fast-glob/out/settings.js +var require_settings = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; + var fs$2 = __require("fs"); + var os$1 = __require("os"); + /** + * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. + * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 + */ + var CPU_COUNT = Math.max(os$1.cpus().length, 1); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs$2.lstat, + lstatSync: fs$2.lstatSync, + stat: fs$2.stat, + statSync: fs$2.statSync, + readdir: fs$2.readdir, + readdirSync: fs$2.readdirSync + }; + var Settings = class { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) this.onlyFiles = false; + if (this.stats) this.objectMode = true; + this.ignore = [].concat(this.ignore); + } + _getValue(option, value) { + return option === void 0 ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } + }; + exports.default = Settings; +})); +//#endregion +//#region node_modules/deepagents/dist/src-DeCEf6Ie.js +var import_out = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => { + var taskManager = require_tasks(); + var async_1 = require_async(); + var stream_1 = require_stream(); + var sync_1 = require_sync(); + var settings_1 = require_settings(); + var utils = require_utils(); + async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async_1.default, options); + const result = await Promise.all(works); + return utils.array.flatten(result); + } + (function(FastGlob) { + FastGlob.glob = FastGlob; + FastGlob.globSync = sync; + FastGlob.globStream = stream; + FastGlob.async = FastGlob; + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync_1.default, options); + return utils.array.flatten(works); + } + FastGlob.sync = sync; + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream_1.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + return utils.stream.merge(works); + } + FastGlob.stream = stream; + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings_1.default(options); + return taskManager.generate(patterns, settings); + } + FastGlob.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings_1.default(options); + return utils.pattern.isDynamicPattern(source, settings); + } + FastGlob.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escape(source); + } + FastGlob.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPathToPattern(source); + } + FastGlob.convertPathToPattern = convertPathToPattern; + (function(posix) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapePosixPath(source); + } + posix.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPosixPathToPattern(source); + } + posix.convertPathToPattern = convertPathToPattern; + })(FastGlob.posix || (FastGlob.posix = {})); + (function(win32) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapeWindowsPath(source); + } + win32.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertWindowsPathToPattern(source); + } + win32.convertPathToPattern = convertPathToPattern; + })(FastGlob.win32 || (FastGlob.win32 = {})); + })(FastGlob || (FastGlob = {})); + function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings_1.default(options); + const tasks = taskManager.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks.map(provider.read, provider); + } + function assertPatternsInput(input) { + if (![].concat(input).every((item) => utils.string.isString(item) && !utils.string.isEmpty(item))) throw new TypeError("Patterns must be a string (non empty) or an array of strings"); + } + module.exports = FastGlob; +})))(), 1); +object({ + /** Personal preferences from ~/.deepagents/{agent}/ (applies everywhere) */ + userMemory: string().optional(), + /** Project-specific context (loaded from project root) */ + projectMemory: string().optional() +}); +/** +* FilesystemBackend: Read and write files directly from the filesystem. +* +* Security and search upgrades: +* - Secure path resolution with root containment when in virtual_mode (sandboxed to cwd) +* - Prevent symlink-following on file I/O using O_NOFOLLOW when available +* - Ripgrep-powered grep with literal (fixed-string) search, plus substring fallback +* and optional glob include filtering, while preserving virtual path behavior +*/ +var SUPPORTS_NOFOLLOW = fs.constants.O_NOFOLLOW !== void 0; +function getErrorMessage(error) { + if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message; + return String(error); +} +function hasErrorCode(error, code) { + return typeof error === "object" && error !== null && "code" in error && error.code === code; +} +/** +* Backend that reads and writes files directly from the filesystem. +* +* Files are accessed using their actual filesystem paths. Relative paths are +* resolved relative to the current working directory. Content is read/written +* as plain text, and metadata (timestamps) are derived from filesystem stats. +*/ +var FilesystemBackend = class { + cwd; + virtualMode; + maxFileSizeBytes; + constructor(options = {}) { + const { rootDir, virtualMode = false, maxFileSizeMb = 10 } = options; + this.cwd = rootDir ? path.resolve(rootDir) : process.cwd(); + this.virtualMode = virtualMode; + this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024; + } + /** + * Resolve a file path with security checks. + * + * When virtualMode=true, treat incoming paths as virtual absolute paths under + * this.cwd, disallow traversal (.., ~) and ensure resolved path stays within root. + * When virtualMode=false, preserve legacy behavior: absolute paths are allowed + * as-is; relative paths resolve under cwd. + * + * @param key - File path (absolute, relative, or virtual when virtualMode=true) + * @returns Resolved absolute path string + * @throws Error if path traversal detected or path outside root + */ + resolvePath(key) { + if (this.virtualMode) { + const vpath = key.startsWith("/") ? key : "/" + key; + if (vpath.includes("..") || vpath.startsWith("~")) throw new Error("Path traversal not allowed"); + const full = path.resolve(this.cwd, vpath.substring(1)); + const relative = path.relative(this.cwd, full); + if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error(`Path: ${full} outside root directory: ${this.cwd}`); + return full; + } + if (path.isAbsolute(key)) return key; + return path.resolve(this.cwd, key); + } + /** + * Resolve the concrete path to unlink for a virtual delete operation. + * + * Virtual-mode path containment is lexical in resolvePath(), so deleting via + * that path could follow a symlinked parent outside the virtual root. Resolve + * and validate the real parent, then unlink through that real parent path so a + * replacement of the original lexical parent cannot redirect the unlink. + */ + async resolveDeletePath(resolvedPath, filePath) { + if (!this.virtualMode) return resolvedPath; + const segments = path.relative(this.cwd, resolvedPath).split(path.sep).filter(Boolean); + let current = this.cwd; + for (const segment of segments.slice(0, -1)) { + current = path.join(current, segment); + if ((await fs$1.lstat(current)).isSymbolicLink()) throw new Error(`Symlink parent not allowed: ${filePath}`); + } + const realRoot = await fs$1.realpath(this.cwd); + const realParent = await fs$1.realpath(path.dirname(resolvedPath)); + const realRelative = path.relative(realRoot, realParent); + if (realRelative.startsWith("..") || path.isAbsolute(realRelative)) throw new Error(`Path '${filePath}' resolves outside root directory`); + return path.join(realParent, path.basename(resolvedPath)); + } + /** + * List files and directories in the specified directory (non-recursive). + * + * @param dirPath - Absolute directory path to list files from + * @returns List of FileInfo objects for files and directories directly in the directory. + * Directories have a trailing / in their path and is_dir=true. + */ + async ls(dirPath) { + try { + const resolvedPath = this.resolvePath(dirPath); + if (!(await fs$1.stat(resolvedPath)).isDirectory()) return { files: [] }; + const entries = await fs$1.readdir(resolvedPath, { withFileTypes: true }); + const results = []; + const cwdStr = this.cwd.endsWith(path.sep) ? this.cwd : this.cwd + path.sep; + for (const entry of entries) { + const fullPath = path.join(resolvedPath, entry.name); + try { + const entryStat = await fs$1.stat(fullPath); + const isFile = entryStat.isFile(); + const isDir = entryStat.isDirectory(); + if (!this.virtualMode) { + if (isFile) results.push({ + path: fullPath, + is_dir: false, + size: entryStat.size, + modified_at: entryStat.mtime.toISOString() + }); + else if (isDir) results.push({ + path: fullPath + path.sep, + is_dir: true, + size: 0, + modified_at: entryStat.mtime.toISOString() + }); + } else { + let relativePath; + if (fullPath.startsWith(cwdStr)) relativePath = fullPath.substring(cwdStr.length); + else if (fullPath.startsWith(this.cwd)) relativePath = fullPath.substring(this.cwd.length).replace(/^[/\\]/, ""); + else relativePath = fullPath; + relativePath = relativePath.split(path.sep).join("/"); + const virtPath = "/" + relativePath; + if (isFile) results.push({ + path: virtPath, + is_dir: false, + size: entryStat.size, + modified_at: entryStat.mtime.toISOString() + }); + else if (isDir) results.push({ + path: virtPath + "/", + is_dir: true, + size: 0, + modified_at: entryStat.mtime.toISOString() + }); + } + } catch { + continue; + } + } + results.sort((a, b) => a.path.localeCompare(b.path)); + return { files: results }; + } catch { + return { files: [] }; + } + } + /** + * Read file content with line numbers. + * + * @param filePath - Absolute or relative file path + * @param offset - Line offset to start reading from (0-indexed) + * @param limit - Maximum number of lines to read + * @returns Formatted file content with line numbers, or error message + */ + async read(filePath, offset = 0, limit = 500) { + try { + const resolvedPath = this.resolvePath(filePath); + const mimeType = getMimeType(filePath); + const isBinary = !isTextMimeType(mimeType); + let content; + if (SUPPORTS_NOFOLLOW) { + if (!(await fs$1.stat(resolvedPath)).isFile()) return { error: `File '${filePath}' not found` }; + const fd = await fs$1.open(resolvedPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + try { + if (isBinary) { + const buffer = await fd.readFile(); + return { + content: new Uint8Array(buffer), + mimeType + }; + } + content = await fd.readFile({ encoding: "utf-8" }); + } finally { + await fd.close(); + } + } else { + const stat = await fs$1.lstat(resolvedPath); + if (stat.isSymbolicLink()) return { error: `Symlinks are not allowed: ${filePath}` }; + if (!stat.isFile()) return { error: `File '${filePath}' not found` }; + if (isBinary) { + const buffer = await fs$1.readFile(resolvedPath); + return { + content: new Uint8Array(buffer), + mimeType + }; + } + content = await fs$1.readFile(resolvedPath, "utf-8"); + } + const emptyMsg = checkEmptyContent(content); + if (emptyMsg) return { + content: emptyMsg, + mimeType + }; + const lines = content.split("\n"); + const startIdx = offset; + const endIdx = Math.min(startIdx + limit, lines.length); + if (startIdx >= lines.length) return { error: `Line offset ${offset} exceeds file length (${lines.length} lines)` }; + return { + content: lines.slice(startIdx, endIdx).join("\n"), + mimeType + }; + } catch (e) { + return { error: `Error reading file '${filePath}': ${e.message}` }; + } + } + /** + * Read file content as raw FileData. + * + * @param filePath - Absolute file path + * @returns ReadRawResult with raw file data on success or error on failure + */ + async readRaw(filePath) { + const resolvedPath = this.resolvePath(filePath); + const mimeType = getMimeType(filePath); + const isBinary = !isTextMimeType(mimeType); + let content; + let stat; + if (SUPPORTS_NOFOLLOW) { + stat = await fs$1.stat(resolvedPath); + if (!stat.isFile()) return { error: `File '${filePath}' not found` }; + const fd = await fs$1.open(resolvedPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + try { + if (isBinary) { + const buffer = await fd.readFile(); + return { data: { + content: new Uint8Array(buffer), + mimeType, + created_at: stat.ctime.toISOString(), + modified_at: stat.mtime.toISOString() + } }; + } + content = await fd.readFile({ encoding: "utf-8" }); + } finally { + await fd.close(); + } + } else { + stat = await fs$1.lstat(resolvedPath); + if (stat.isSymbolicLink()) return { error: `Symlinks are not allowed: ${filePath}` }; + if (!stat.isFile()) return { error: `File '${filePath}' not found` }; + if (isBinary) { + const buffer = await fs$1.readFile(resolvedPath); + return { data: { + content: new Uint8Array(buffer), + mimeType, + created_at: stat.ctime.toISOString(), + modified_at: stat.mtime.toISOString() + } }; + } + content = await fs$1.readFile(resolvedPath, "utf-8"); + } + return { data: { + content, + mimeType, + created_at: stat.ctime.toISOString(), + modified_at: stat.mtime.toISOString() + } }; + } + /** + * Write content to a file, creating it or overwriting it if it already exists. + * Returns WriteResult. External storage sets filesUpdate=null. + */ + async write(filePath, content) { + try { + const resolvedPath = this.resolvePath(filePath); + const isBinary = !isTextMimeType(getMimeType(filePath)); + try { + if ((await fs$1.lstat(resolvedPath)).isSymbolicLink()) return { error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.` }; + } catch {} + await fs$1.mkdir(path.dirname(resolvedPath), { recursive: true }); + if (SUPPORTS_NOFOLLOW) { + const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC | fs.constants.O_NOFOLLOW; + const fd = await fs$1.open(resolvedPath, flags, 420); + try { + if (isBinary) { + const buffer = Buffer.from(content, "base64"); + await fd.writeFile(buffer); + } else await fd.writeFile(content, "utf-8"); + } finally { + await fd.close(); + } + } else if (isBinary) { + const buffer = Buffer.from(content, "base64"); + await fs$1.writeFile(resolvedPath, buffer); + } else await fs$1.writeFile(resolvedPath, content, "utf-8"); + return { + path: filePath, + filesUpdate: null + }; + } catch (e) { + return { error: `Error writing file '${filePath}': ${e.message}` }; + } + } + /** + * Edit a file by replacing string occurrences. + * Returns EditResult. External storage sets filesUpdate=null. + */ + async edit(filePath, oldString, newString, replaceAll = false) { + try { + const resolvedPath = this.resolvePath(filePath); + let content; + if (SUPPORTS_NOFOLLOW) { + if (!(await fs$1.stat(resolvedPath)).isFile()) return { error: `Error: File '${filePath}' not found` }; + const fd = await fs$1.open(resolvedPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + try { + content = await fd.readFile({ encoding: "utf-8" }); + } finally { + await fd.close(); + } + } else { + const stat = await fs$1.lstat(resolvedPath); + if (stat.isSymbolicLink()) return { error: `Error: Symlinks are not allowed: ${filePath}` }; + if (!stat.isFile()) return { error: `Error: File '${filePath}' not found` }; + content = await fs$1.readFile(resolvedPath, "utf-8"); + } + const result = performStringReplacement(content, oldString, newString, replaceAll); + if (typeof result === "string") return { error: result }; + const [newContent, occurrences] = result; + if (SUPPORTS_NOFOLLOW) { + const flags = fs.constants.O_WRONLY | fs.constants.O_TRUNC | fs.constants.O_NOFOLLOW; + const fd = await fs$1.open(resolvedPath, flags); + try { + await fd.writeFile(newContent, "utf-8"); + } finally { + await fd.close(); + } + } else await fs$1.writeFile(resolvedPath, newContent, "utf-8"); + return { + path: filePath, + filesUpdate: null, + occurrences + }; + } catch (e) { + return { error: `Error editing file '${filePath}': ${e.message}` }; + } + } + /** + * Delete a file from the filesystem. + */ + async delete(filePath) { + let resolvedPath; + try { + resolvedPath = this.resolvePath(filePath); + } catch (error) { + return { error: `Error deleting file '${filePath}': ${getErrorMessage(error)}` }; + } + try { + const deletePath = await this.resolveDeletePath(resolvedPath, filePath); + if ((await fs$1.lstat(deletePath)).isDirectory()) return { error: `Error: '${filePath}' is a directory, not a file` }; + await fs$1.unlink(deletePath); + return { path: filePath }; + } catch (error) { + if (hasErrorCode(error, "ENOENT")) return { error: `Error: File '${filePath}' not found` }; + return { error: `Error deleting file '${filePath}': ${getErrorMessage(error)}` }; + } + } + /** + * Search for a literal text pattern in files. + * + * Uses ripgrep if available, falling back to substring search. + * + * @param pattern - Literal string to search for (NOT regex). + * @param dirPath - Directory or file path to search in. Defaults to current directory. + * @param glob - Optional glob pattern to filter which files to search. + * @returns List of GrepMatch dicts containing path, line number, and matched text. + */ + async grep(pattern, dirPath = "/", glob = null) { + let baseFull; + try { + baseFull = this.resolvePath(dirPath || "."); + } catch { + return { matches: [] }; + } + try { + await fs$1.stat(baseFull); + } catch { + return { matches: [] }; + } + let results = await this.ripgrepSearch(pattern, baseFull, glob); + if (results === null) results = await this.literalSearch(pattern, baseFull, glob); + const matches = []; + for (const [fpath, items] of Object.entries(results)) for (const [lineNum, lineText] of items) matches.push({ + path: fpath, + line: lineNum, + text: lineText + }); + return { matches }; + } + /** + * Search using ripgrep with fixed-string (literal) mode. + * + * @param pattern - Literal string to search for (unescaped). + * @param baseFull - Resolved base path to search in. + * @param includeGlob - Optional glob pattern to filter files. + * @returns Dict mapping file paths to list of (line_number, line_text) tuples. + * Returns null if ripgrep is unavailable or times out. + */ + async ripgrepSearch(pattern, baseFull, includeGlob) { + return new Promise((resolve) => { + const args = ["--json", "-F"]; + if (includeGlob) args.push("--glob", includeGlob); + args.push("--", pattern, baseFull); + const proc = spawn("rg", args, { timeout: 3e4 }); + const results = {}; + let output = ""; + proc.stdout.on("data", (data) => { + output += data.toString(); + }); + proc.on("close", (code) => { + if (code !== 0 && code !== 1) { + resolve(null); + return; + } + for (const line of output.split("\n")) { + if (!line.trim()) continue; + try { + const data = JSON.parse(line); + if (data.type !== "match") continue; + const pdata = data.data || {}; + const ftext = pdata.path?.text; + if (!ftext) continue; + let virtPath; + if (this.virtualMode) try { + const resolved = path.resolve(ftext); + const relative = path.relative(this.cwd, resolved); + if (relative.startsWith("..")) continue; + virtPath = "/" + relative.split(path.sep).join("/"); + } catch { + continue; + } + else virtPath = ftext; + const ln = pdata.line_number; + const lt = pdata.lines?.text?.replace(/\n$/, "") || ""; + if (ln === void 0) continue; + if (!results[virtPath]) results[virtPath] = []; + results[virtPath].push([ln, lt]); + } catch { + continue; + } + } + resolve(results); + }); + proc.on("error", () => { + resolve(null); + }); + }); + } + /** + * Fallback search using literal substring matching when ripgrep is unavailable. + * + * Recursively searches files, respecting maxFileSizeBytes limit. + * + * @param pattern - Literal string to search for. + * @param baseFull - Resolved base path to search in. + * @param includeGlob - Optional glob pattern to filter files by name. + * @returns Dict mapping file paths to list of (line_number, line_text) tuples. + */ + async literalSearch(pattern, baseFull, includeGlob) { + const results = {}; + const files = await (0, import_out.default)("**/*", { + cwd: (await fs$1.stat(baseFull)).isDirectory() ? baseFull : path.dirname(baseFull), + absolute: true, + onlyFiles: true, + dot: true, + followSymbolicLinks: false + }); + for (const fp of files) try { + if (!isTextMimeType(getMimeType(fp))) continue; + if (includeGlob && !import_micromatch.default.isMatch(path.basename(fp), includeGlob)) continue; + if ((await fs$1.stat(fp)).size > this.maxFileSizeBytes) continue; + const lines = (await fs$1.readFile(fp, "utf-8")).split("\n"); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (line.includes(pattern)) { + let virtPath; + if (this.virtualMode) try { + const relative = path.relative(this.cwd, fp); + if (relative.startsWith("..")) continue; + virtPath = "/" + relative.split(path.sep).join("/"); + } catch { + continue; + } + else virtPath = fp; + if (!results[virtPath]) results[virtPath] = []; + results[virtPath].push([i + 1, line]); + } + } + } catch { + continue; + } + return results; + } + /** + * Structured glob matching returning FileInfo objects. + */ + async glob(pattern, searchPath = "/") { + if (pattern.startsWith("/")) pattern = pattern.substring(1); + const resolvedSearchPath = searchPath === "/" ? this.cwd : this.resolvePath(searchPath); + try { + if (!(await fs$1.stat(resolvedSearchPath)).isDirectory()) return { files: [] }; + } catch { + return { files: [] }; + } + const results = []; + try { + const matches = await (0, import_out.default)(pattern, { + cwd: resolvedSearchPath, + absolute: true, + onlyFiles: false, + dot: true, + followSymbolicLinks: false + }); + for (const matchedPath of matches) try { + const stat = await fs$1.stat(matchedPath); + if (!stat.isFile()) continue; + const normalizedPath = matchedPath.split("/").join(path.sep); + if (!this.virtualMode) results.push({ + path: normalizedPath, + is_dir: false, + size: stat.size, + modified_at: stat.mtime.toISOString() + }); + else { + const cwdStr = this.cwd.endsWith(path.sep) ? this.cwd : this.cwd + path.sep; + let relativePath; + if (normalizedPath.startsWith(cwdStr)) relativePath = normalizedPath.substring(cwdStr.length); + else if (normalizedPath.startsWith(this.cwd)) relativePath = normalizedPath.substring(this.cwd.length).replace(/^[/\\]/, ""); + else relativePath = normalizedPath; + relativePath = relativePath.split(path.sep).join("/"); + const virt = "/" + relativePath; + results.push({ + path: virt, + is_dir: false, + size: stat.size, + modified_at: stat.mtime.toISOString() + }); + } + } catch { + continue; + } + } catch {} + results.sort((a, b) => a.path.localeCompare(b.path)); + return { files: results }; + } + /** + * Upload multiple files to the filesystem. + * + * @param files - List of [path, content] tuples to upload + * @returns List of FileUploadResponse objects, one per input file + */ + async uploadFiles(files) { + const responses = []; + for (const [filePath, content] of files) try { + const resolvedPath = this.resolvePath(filePath); + await fs$1.mkdir(path.dirname(resolvedPath), { recursive: true }); + await fs$1.writeFile(resolvedPath, content); + responses.push({ + path: filePath, + error: null + }); + } catch (e) { + if (e.code === "ENOENT") responses.push({ + path: filePath, + error: "file_not_found" + }); + else if (e.code === "EACCES") responses.push({ + path: filePath, + error: "permission_denied" + }); + else if (e.code === "EISDIR") responses.push({ + path: filePath, + error: "is_directory" + }); + else responses.push({ + path: filePath, + error: "invalid_path" + }); + } + return responses; + } + /** + * Download multiple files from the filesystem. + * + * @param paths - List of file paths to download + * @returns List of FileDownloadResponse objects, one per input path + */ + async downloadFiles(paths) { + const responses = []; + for (const filePath of paths) try { + const resolvedPath = this.resolvePath(filePath); + const content = await fs$1.readFile(resolvedPath); + responses.push({ + path: filePath, + content, + error: null + }); + } catch (e) { + if (e.code === "ENOENT") responses.push({ + path: filePath, + content: null, + error: "file_not_found" + }); + else if (e.code === "EACCES") responses.push({ + path: filePath, + content: null, + error: "permission_denied" + }); + else if (e.code === "EISDIR") responses.push({ + path: filePath, + content: null, + error: "is_directory" + }); + else responses.push({ + path: filePath, + content: null, + error: "invalid_path" + }); + } + return responses; + } +}; +//#endregion +export { createDeepAgent as n, toolStrategy as r, FilesystemBackend as t }; diff --git a/.vercel/output/functions/__server.func/_libs/electric-sql__pglite.mjs b/.vercel/output/functions/__server.func/_libs/electric-sql__pglite.mjs index 1210432..5f73a02 100644 --- a/.vercel/output/functions/__server.func/_libs/electric-sql__pglite.mjs +++ b/.vercel/output/functions/__server.func/_libs/electric-sql__pglite.mjs @@ -1,6 +1,6 @@ import { r as __exportAll } from "../_runtime.mjs"; -import * as s$1 from "fs"; import * as o$2 from "path"; +import * as s$1 from "fs"; //#region node_modules/@electric-sql/pglite/dist/chunk-QY3QWFKW.js var p$3 = Object.create; var i = Object.defineProperty; diff --git a/.vercel/output/functions/__server.func/_libs/fastq+nodelib__fs.walk+reusify.mjs b/.vercel/output/functions/__server.func/_libs/fastq+nodelib__fs.walk+reusify.mjs new file mode 100644 index 0000000..0c07d81 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/fastq+nodelib__fs.walk+reusify.mjs @@ -0,0 +1,613 @@ +import { i as __require, t as __commonJSMin } from "../_runtime.mjs"; +import { t as require_out$1 } from "./@nodelib/fs.scandir+[...].mjs"; +//#region node_modules/reusify/reusify.js +var require_reusify = /* @__PURE__ */ __commonJSMin(((exports, module) => { + function reusify(Constructor) { + var head = new Constructor(); + var tail = head; + function get() { + var current = head; + if (current.next) head = current.next; + else { + head = new Constructor(); + tail = head; + } + current.next = null; + return current; + } + function release(obj) { + tail.next = obj; + tail = obj; + } + return { + get, + release + }; + } + module.exports = reusify; +})); +//#endregion +//#region node_modules/fastq/queue.js +var require_queue = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var reusify = require_reusify(); + function fastqueue(context, worker, _concurrency) { + if (typeof context === "function") { + _concurrency = worker; + worker = context; + context = null; + } + if (!(_concurrency >= 1)) throw new Error("fastqueue concurrency must be equal to or greater than 1"); + var cache = reusify(Task); + var queueHead = null; + var queueTail = null; + var _running = 0; + var errorHandler = null; + var self = { + push, + drain: noop, + saturated: noop, + pause, + paused: false, + get concurrency() { + return _concurrency; + }, + set concurrency(value) { + if (!(value >= 1)) throw new Error("fastqueue concurrency must be equal to or greater than 1"); + _concurrency = value; + if (self.paused) return; + for (; queueHead && _running < _concurrency;) { + _running++; + release(); + } + }, + running, + resume, + idle, + length, + getQueue, + unshift, + empty: noop, + kill, + killAndDrain, + error, + abort + }; + return self; + function running() { + return _running; + } + function pause() { + self.paused = true; + } + function length() { + var current = queueHead; + var counter = 0; + while (current) { + current = current.next; + counter++; + } + return counter; + } + function getQueue() { + var current = queueHead; + var tasks = []; + while (current) { + tasks.push(current.value); + current = current.next; + } + return tasks; + } + function resume() { + if (!self.paused) return; + self.paused = false; + if (queueHead === null) { + _running++; + release(); + return; + } + for (; queueHead && _running < _concurrency;) { + _running++; + release(); + } + } + function idle() { + return _running === 0 && self.length() === 0; + } + function push(value, done) { + var current = cache.get(); + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop; + current.errorHandler = errorHandler; + if (_running >= _concurrency || self.paused) if (queueTail) { + queueTail.next = current; + queueTail = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + else { + _running++; + worker.call(context, current.value, current.worked); + } + } + function unshift(value, done) { + var current = cache.get(); + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop; + current.errorHandler = errorHandler; + if (_running >= _concurrency || self.paused) if (queueHead) { + current.next = queueHead; + queueHead = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + else { + _running++; + worker.call(context, current.value, current.worked); + } + } + function release(holder) { + if (holder) cache.release(holder); + var next = queueHead; + if (next && _running <= _concurrency) if (!self.paused) { + if (queueTail === queueHead) queueTail = null; + queueHead = next.next; + next.next = null; + worker.call(context, next.value, next.worked); + if (queueTail === null) self.empty(); + } else _running--; + else if (--_running === 0) self.drain(); + } + function kill() { + queueHead = null; + queueTail = null; + self.drain = noop; + } + function killAndDrain() { + queueHead = null; + queueTail = null; + self.drain(); + self.drain = noop; + } + function abort() { + var current = queueHead; + queueHead = null; + queueTail = null; + while (current) { + var next = current.next; + var callback = current.callback; + var errorHandler = current.errorHandler; + var val = current.value; + var context = current.context; + current.value = null; + current.callback = noop; + current.errorHandler = null; + if (errorHandler) errorHandler(/* @__PURE__ */ new Error("abort"), val); + callback.call(context, /* @__PURE__ */ new Error("abort")); + current.release(current); + current = next; + } + self.drain = noop; + } + function error(handler) { + errorHandler = handler; + } + } + function noop() {} + function Task() { + this.value = null; + this.callback = noop; + this.next = null; + this.release = noop; + this.context = null; + this.errorHandler = null; + var self = this; + this.worked = function worked(err, result) { + var callback = self.callback; + var errorHandler = self.errorHandler; + var val = self.value; + self.value = null; + self.callback = noop; + if (self.errorHandler) errorHandler(err, val); + callback.call(self.context, err, result); + self.release(self); + }; + } + function queueAsPromised(context, worker, _concurrency) { + if (typeof context === "function") { + _concurrency = worker; + worker = context; + context = null; + } + function asyncWrapper(arg, cb) { + worker.call(this, arg).then(function(res) { + cb(null, res); + }, cb); + } + var queue = fastqueue(context, asyncWrapper, _concurrency); + var pushCb = queue.push; + var unshiftCb = queue.unshift; + queue.push = push; + queue.unshift = unshift; + queue.drained = drained; + return queue; + function push(value) { + var p = new Promise(function(resolve, reject) { + pushCb(value, function(err, result) { + if (err) { + reject(err); + return; + } + resolve(result); + }); + }); + p.catch(noop); + return p; + } + function unshift(value) { + var p = new Promise(function(resolve, reject) { + unshiftCb(value, function(err, result) { + if (err) { + reject(err); + return; + } + resolve(result); + }); + }); + p.catch(noop); + return p; + } + function drained() { + return new Promise(function(resolve) { + process.nextTick(function() { + if (queue.idle()) resolve(); + else { + var previousDrain = queue.drain; + queue.drain = function() { + if (typeof previousDrain === "function") previousDrain(); + resolve(); + queue.drain = previousDrain; + }; + } + }); + }); + } + } + module.exports = fastqueue; + module.exports.promise = queueAsPromised; +})); +//#endregion +//#region node_modules/@nodelib/fs.walk/out/readers/common.js +var require_common = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0; + function isFatalError(settings, error) { + if (settings.errorFilter === null) return true; + return !settings.errorFilter(error); + } + exports.isFatalError = isFatalError; + function isAppliedFilter(filter, value) { + return filter === null || filter(value); + } + exports.isAppliedFilter = isAppliedFilter; + function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[/\\]/).join(separator); + } + exports.replacePathSegmentSeparator = replacePathSegmentSeparator; + function joinPathSegments(a, b, separator) { + if (a === "") return b; + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) return a + b; + return a + separator + b; + } + exports.joinPathSegments = joinPathSegments; +})); +//#endregion +//#region node_modules/@nodelib/fs.walk/out/readers/reader.js +var require_reader = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var common = require_common(); + var Reader = class { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } + }; + exports.default = Reader; +})); +//#endregion +//#region node_modules/@nodelib/fs.walk/out/readers/async.js +var require_async$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var events_1 = __require("events"); + var fsScandir = require_out$1(); + var fastq = require_queue(); + var common = require_common(); + var reader_1 = require_reader(); + var AsyncReader = class extends reader_1.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir.scandir; + this._emitter = new events_1.EventEmitter(); + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) this._emitter.emit("end"); + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + get isDestroyed() { + return this._isDestroyed; + } + destroy() { + if (this._isDestroyed) throw new Error("The reader is already destroyed"); + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on("entry", callback); + } + onError(callback) { + this._emitter.once("error", callback); + } + onEnd(callback) { + this._emitter.once("end", callback); + } + _pushToQueue(directory, base) { + const queueItem = { + directory, + base + }; + this._queue.push(queueItem, (error) => { + if (error !== null) this._handleError(error); + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + done(error, void 0); + return; + } + for (const entry of entries) this._handleEntry(entry, item.base); + done(null, void 0); + }); + } + _handleError(error) { + if (this._isDestroyed || !common.isFatalError(this._settings, error)) return; + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit("error", error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) return; + const fullpath = entry.path; + if (base !== void 0) entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + if (common.isAppliedFilter(this._settings.entryFilter, entry)) this._emitEntry(entry); + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) this._pushToQueue(fullpath, base === void 0 ? void 0 : entry.path); + } + _emitEntry(entry) { + this._emitter.emit("entry", entry); + } + }; + exports.default = AsyncReader; +})); +//#endregion +//#region node_modules/@nodelib/fs.walk/out/providers/async.js +var require_async = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var async_1 = require_async$1(); + var AsyncProvider = class { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._storage = []; + } + read(callback) { + this._reader.onError((error) => { + callFailureCallback(callback, error); + }); + this._reader.onEntry((entry) => { + this._storage.push(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, this._storage); + }); + this._reader.read(); + } + }; + exports.default = AsyncProvider; + function callFailureCallback(callback, error) { + callback(error); + } + function callSuccessCallback(callback, entries) { + callback(null, entries); + } +})); +//#endregion +//#region node_modules/@nodelib/fs.walk/out/providers/stream.js +var require_stream = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var stream_1 = __require("stream"); + var async_1 = require_async$1(); + var StreamProvider = class { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._stream = new stream_1.Readable({ + objectMode: true, + read: () => {}, + destroy: () => { + if (!this._reader.isDestroyed) this._reader.destroy(); + } + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit("error", error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } + }; + exports.default = StreamProvider; +})); +//#endregion +//#region node_modules/@nodelib/fs.walk/out/readers/sync.js +var require_sync$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var fsScandir = require_out$1(); + var common = require_common(); + var reader_1 = require_reader(); + var SyncReader = class extends reader_1.default { + constructor() { + super(...arguments); + this._scandir = fsScandir.scandirSync; + this._storage = []; + this._queue = /* @__PURE__ */ new Set(); + } + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return this._storage; + } + _pushToQueue(directory, base) { + this._queue.add({ + directory, + base + }); + } + _handleQueue() { + for (const item of this._queue.values()) this._handleDirectory(item.directory, item.base); + } + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + for (const entry of entries) this._handleEntry(entry, base); + } catch (error) { + this._handleError(error); + } + } + _handleError(error) { + if (!common.isFatalError(this._settings, error)) return; + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== void 0) entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + if (common.isAppliedFilter(this._settings.entryFilter, entry)) this._pushToStorage(entry); + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) this._pushToQueue(fullpath, base === void 0 ? void 0 : entry.path); + } + _pushToStorage(entry) { + this._storage.push(entry); + } + }; + exports.default = SyncReader; +})); +//#endregion +//#region node_modules/@nodelib/fs.walk/out/providers/sync.js +var require_sync = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var sync_1 = require_sync$1(); + var SyncProvider = class { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } + }; + exports.default = SyncProvider; +})); +//#endregion +//#region node_modules/@nodelib/fs.walk/out/settings.js +var require_settings = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var path = __require("path"); + var fsScandir = require_out$1(); + var Settings = class { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, void 0); + this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } + }; + exports.default = Settings; +})); +//#endregion +//#region node_modules/@nodelib/fs.walk/out/index.js +var require_out = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0; + var async_1 = require_async(); + var stream_1 = require_stream(); + var sync_1 = require_sync(); + var settings_1 = require_settings(); + exports.Settings = settings_1.default; + function walk(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === "function") { + new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + return; + } + new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); + } + exports.walk = walk; + function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return new sync_1.default(directory, settings).read(); + } + exports.walkSync = walkSync; + function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return new stream_1.default(directory, settings).read(); + } + exports.walkStream = walkStream; + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) return settingsOrOptions; + return new settings_1.default(settingsOrOptions); + } +})); +//#endregion +export { require_out as t }; diff --git a/.vercel/output/functions/__server.func/_libs/h3+rou3+srvx.mjs b/.vercel/output/functions/__server.func/_libs/h3+rou3+srvx.mjs index ed192ec..277cbaf 100644 --- a/.vercel/output/functions/__server.func/_libs/h3+rou3+srvx.mjs +++ b/.vercel/output/functions/__server.func/_libs/h3+rou3+srvx.mjs @@ -1,4 +1,5 @@ import { PassThrough, Readable } from "node:stream"; +import "node:stream/promises"; //#region node_modules/h3/node_modules/rou3/dist/index.mjs var NullProtoObj = /* @__PURE__ */ (() => { const e = function() {}; diff --git a/.vercel/output/functions/__server.func/_libs/immediate.mjs b/.vercel/output/functions/__server.func/_libs/immediate.mjs new file mode 100644 index 0000000..54a89c9 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/immediate.mjs @@ -0,0 +1,57 @@ +import { t as __commonJSMin } from "../_runtime.mjs"; +//#region node_modules/immediate/lib/index.js +var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var Mutation = global.MutationObserver || global.WebKitMutationObserver; + var scheduleDrain; + if (process.browser) if (Mutation) { + var called = 0; + var observer = new Mutation(nextTick); + var element = global.document.createTextNode(""); + observer.observe(element, { characterData: true }); + scheduleDrain = function() { + element.data = called = ++called % 2; + }; + } else if (!global.setImmediate && typeof global.MessageChannel !== "undefined") { + var channel = new global.MessageChannel(); + channel.port1.onmessage = nextTick; + scheduleDrain = function() { + channel.port2.postMessage(0); + }; + } else if ("document" in global && "onreadystatechange" in global.document.createElement("script")) scheduleDrain = function() { + var scriptEl = global.document.createElement("script"); + scriptEl.onreadystatechange = function() { + nextTick(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global.document.documentElement.appendChild(scriptEl); + }; + else scheduleDrain = function() { + setTimeout(nextTick, 0); + }; + else scheduleDrain = function() { + process.nextTick(nextTick); + }; + var draining; + var queue = []; + function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) oldQueue[i](); + len = queue.length; + } + draining = false; + } + module.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) scheduleDrain(); + } +})); +//#endregion +export { require_lib as t }; diff --git a/.vercel/output/functions/__server.func/_libs/inherits.mjs b/.vercel/output/functions/__server.func/_libs/inherits.mjs new file mode 100644 index 0000000..ada4490 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/inherits.mjs @@ -0,0 +1,39 @@ +import { i as __require, t as __commonJSMin } from "../_runtime.mjs"; +//#region node_modules/inherits/inherits_browser.js +var require_inherits_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => { + if (typeof Object.create === "function") module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } }); + } + }; + else module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; +})); +//#endregion +//#region node_modules/inherits/inherits.js +var require_inherits = /* @__PURE__ */ __commonJSMin(((exports, module) => { + try { + var util = __require("util"); + /* istanbul ignore next */ + if (typeof util.inherits !== "function") throw ""; + module.exports = util.inherits; + } catch (e) { + /* istanbul ignore next */ + module.exports = require_inherits_browser(); + } +})); +//#endregion +export { require_inherits as t }; diff --git a/.vercel/output/functions/__server.func/_libs/isarray.mjs b/.vercel/output/functions/__server.func/_libs/isarray.mjs new file mode 100644 index 0000000..e12f1b8 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/isarray.mjs @@ -0,0 +1,10 @@ +import { t as __commonJSMin } from "../_runtime.mjs"; +//#region node_modules/isarray/index.js +var require_isarray = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var toString = {}.toString; + module.exports = Array.isArray || function(arr) { + return toString.call(arr) == "[object Array]"; + }; +})); +//#endregion +export { require_isarray as t }; diff --git a/.vercel/output/functions/__server.func/_libs/jose.mjs b/.vercel/output/functions/__server.func/_libs/jose.mjs index ff4e76d..c3e5af5 100644 --- a/.vercel/output/functions/__server.func/_libs/jose.mjs +++ b/.vercel/output/functions/__server.func/_libs/jose.mjs @@ -1,4 +1,4 @@ -import { $ as sign, Ct as encode$1, Dt as uint32be, Et as encode, G as JWTClaimsBuilder, J as validateAlgorithms, K as validateClaimsSet, Ot as uint64be, Q as checkKeyLength, St as decode, Tt as decoder, X as importJWK, Y as validateCrit, Z as normalizeKey, _t as JWTClaimValidationFailed, at as digest, bt as invalidKeyInput, ct as isCryptoKey, dt as JOSEAlgNotAllowed, et as isDisjoint, ft as JOSENotSupported, gt as JWSInvalid, ht as JWKInvalid, it as decodeBase64url, lt as isKeyLike, mt as JWEInvalid, nt as isObject, ot as unprotected, pt as JWEDecryptionFailed, q as checkKeyType, rt as assertNotSet, st as assertCryptoKey, tt as isJWK, ut as isKeyObject, wt as concat, xt as checkEncCryptoKey, yt as JWTInvalid } from "./@better-auth/core+[...].mjs"; +import { $ as JWEDecryptionFailed, B as isDisjoint, F as validateCrit, G as digest, H as isObject, I as importJWK, J as isCryptoKey, K as unprotected, L as normalizeKey, M as validateClaimsSet, N as checkKeyType, P as validateAlgorithms, Q as JOSENotSupported, R as checkKeyLength, U as assertNotSet, V as isJWK, W as decodeBase64url, X as isKeyObject, Y as isKeyLike, Z as JOSEAlgNotAllowed, at as JWTInvalid, ct as decode, dt as decoder, et as JWEInvalid, ft as encode, j as JWTClaimsBuilder, lt as encode$1, mt as uint64be, nt as JWSInvalid, ot as invalidKeyInput, pt as uint32be, q as assertCryptoKey, rt as JWTClaimValidationFailed, st as checkEncCryptoKey, tt as JWKInvalid, ut as concat, z as sign } from "./@better-auth/core+[...].mjs"; //#region node_modules/jose/dist/webapi/lib/content_encryption.js function cekLength(alg) { switch (alg) { diff --git a/.vercel/output/functions/__server.func/_libs/js-yaml.mjs b/.vercel/output/functions/__server.func/_libs/js-yaml.mjs new file mode 100644 index 0000000..59d7638 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/js-yaml.mjs @@ -0,0 +1,2193 @@ +//#region node_modules/js-yaml/dist/js-yaml.mjs +/*! js-yaml 5.2.2 https://github.com/nodeca/js-yaml @license MIT */ +var NOT_RESOLVED = Symbol("NOT_RESOLVED"); +var MERGE_KEY = Symbol("MERGE_KEY"); +function defineScalarTag(tagName, options) { + return { + tagName, + nodeKind: "scalar", + implicit: options.implicit ?? false, + matchByTagPrefix: options.matchByTagPrefix ?? false, + implicitFirstChars: options.implicitFirstChars ?? null, + resolve: options.resolve, + identify: options.identify ?? null, + represent: options.represent ?? ((data) => String(data)), + representTagName: options.representTagName ?? null + }; +} +function defineSequenceTag(tagName, options) { + const carrierIsResult = options.finalize === void 0; + return { + tagName, + nodeKind: "sequence", + implicit: false, + matchByTagPrefix: options.matchByTagPrefix ?? false, + create: options.create, + addItem: options.addItem, + finalize: options.finalize ?? ((carrier) => carrier), + carrierIsResult, + identify: options.identify ?? null, + represent: options.represent ?? ((data) => data), + representTagName: options.representTagName ?? null + }; +} +function defineMappingTag(tagName, options) { + const carrierIsResult = options.finalize === void 0; + return { + tagName, + nodeKind: "mapping", + implicit: false, + matchByTagPrefix: options.matchByTagPrefix ?? false, + create: options.create, + addPair: options.addPair, + has: options.has, + keys: options.keys, + get: options.get, + finalize: options.finalize ?? ((carrier) => carrier), + carrierIsResult, + identify: options.identify ?? null, + represent: options.represent ?? ((data) => data), + representTagName: options.representTagName ?? null + }; +} +var strTag = defineScalarTag("tag:yaml.org,2002:str", { + resolve: (source) => source, + identify: (data) => typeof data === "string" +}); +var NULL_VALUES$1 = [ + "", + "~", + "null", + "Null", + "NULL" +]; +var nullCoreTag = defineScalarTag("tag:yaml.org,2002:null", { + implicit: true, + implicitFirstChars: [ + "", + "~", + "n", + "N" + ], + resolve: (source) => { + if (NULL_VALUES$1.indexOf(source) !== -1) return null; + return NOT_RESOLVED; + }, + identify: (object) => object === null, + represent: () => "null" +}); +var nullJsonTag = defineScalarTag("tag:yaml.org,2002:null", { + implicit: true, + implicitFirstChars: ["n"], + resolve: (source, isExplicit) => { + if (source === "null" || isExplicit && source === "") return null; + return NOT_RESOLVED; + }, + identify: (object) => object === null, + represent: () => "null" +}); +var NULL_VALUES = [ + "", + "~", + "null", + "Null", + "NULL" +]; +var nullYaml11Tag = defineScalarTag("tag:yaml.org,2002:null", { + implicit: true, + implicitFirstChars: [ + "", + "~", + "n", + "N" + ], + resolve: (source) => { + if (NULL_VALUES.indexOf(source) !== -1) return null; + return NOT_RESOLVED; + }, + identify: (object) => object === null, + represent: () => "null" +}); +var TRUE_VALUES$2 = [ + "true", + "True", + "TRUE" +]; +var FALSE_VALUES$2 = [ + "false", + "False", + "FALSE" +]; +var boolCoreTag = defineScalarTag("tag:yaml.org,2002:bool", { + implicit: true, + implicitFirstChars: [ + "t", + "T", + "f", + "F" + ], + resolve: (source) => { + if (TRUE_VALUES$2.indexOf(source) !== -1) return true; + if (FALSE_VALUES$2.indexOf(source) !== -1) return false; + return NOT_RESOLVED; + }, + identify: (object) => Object.prototype.toString.call(object) === "[object Boolean]", + represent: (object) => object ? "true" : "false" +}); +var TRUE_VALUES$1 = ["true"]; +var FALSE_VALUES$1 = ["false"]; +var boolJsonTag = defineScalarTag("tag:yaml.org,2002:bool", { + implicit: true, + implicitFirstChars: ["t", "f"], + resolve: (source) => { + if (TRUE_VALUES$1.indexOf(source) !== -1) return true; + if (FALSE_VALUES$1.indexOf(source) !== -1) return false; + return NOT_RESOLVED; + }, + identify: (object) => Object.prototype.toString.call(object) === "[object Boolean]", + represent: (object) => object ? "true" : "false" +}); +var TRUE_VALUES = [ + "true", + "True", + "TRUE", + "y", + "Y", + "yes", + "Yes", + "YES", + "on", + "On", + "ON" +]; +var FALSE_VALUES = [ + "false", + "False", + "FALSE", + "n", + "N", + "no", + "No", + "NO", + "off", + "Off", + "OFF" +]; +var boolYaml11Tag = defineScalarTag("tag:yaml.org,2002:bool", { + implicit: true, + implicitFirstChars: [ + "y", + "Y", + "n", + "N", + "t", + "T", + "f", + "F", + "o", + "O" + ], + resolve: (source) => { + if (TRUE_VALUES.indexOf(source) !== -1) return true; + if (FALSE_VALUES.indexOf(source) !== -1) return false; + return NOT_RESOLVED; + }, + identify: (object) => Object.prototype.toString.call(object) === "[object Boolean]", + represent: (object) => object ? "true" : "false" +}); +var YAML_INTEGER_IMPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:0o[0-7]+|0x[0-9a-fA-F]+|[-+]?[0-9]+)$"); +var YAML_INTEGER_EXPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$"); +function parseYamlInteger$2(source) { + let value = source; + let sign = 1; + if (value[0] === "-" || value[0] === "+") { + if (value[0] === "-") sign = -1; + value = value.slice(1); + } + if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2); + if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8); + if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16); + return sign * parseInt(value, 10); +} +function resolveYamlInteger$2(source, isExplicit) { + if (isExplicit) { + if (!YAML_INTEGER_EXPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED; + } else if (!YAML_INTEGER_IMPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED; + const result = parseYamlInteger$2(source); + return Number.isFinite(result) ? result : NOT_RESOLVED; +} +var intCoreTag = defineScalarTag("tag:yaml.org,2002:int", { + implicit: true, + implicitFirstChars: [ + "-", + "+", + ..."0123456789" + ], + resolve: resolveYamlInteger$2, + identify: (object) => Number.isInteger(object) && !Object.is(object, -0) && object.toString(10).indexOf("e") < 0, + represent: (object) => object.toString(10) +}); +var YAML_INTEGER_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)$"); +var YAML_INTEGER_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$"); +function parseYamlInteger$1(source) { + let value = source; + let sign = 1; + if (value[0] === "-" || value[0] === "+") { + if (value[0] === "-") sign = -1; + value = value.slice(1); + } + if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2); + if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8); + if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16); + return sign * parseInt(value, 10); +} +function resolveYamlInteger$1(source, isExplicit) { + if (isExplicit) { + if (!YAML_INTEGER_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED; + } else if (!YAML_INTEGER_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED; + const result = parseYamlInteger$1(source); + return Number.isFinite(result) ? result : NOT_RESOLVED; +} +var intJsonTag = defineScalarTag("tag:yaml.org,2002:int", { + implicit: true, + implicitFirstChars: ["-", ..."0123456789"], + resolve: resolveYamlInteger$1, + identify: (object) => Number.isInteger(object) && !Object.is(object, -0) && object.toString(10).indexOf("e") < 0, + represent: (object) => object.toString(10) +}); +var YAML_INTEGER_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?0x[0-9a-fA-F_]+|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+|[-+]?(?:0|[1-9][0-9_]*))$"); +function parseYamlInteger(source) { + let value = source.replace(/_/g, ""); + let sign = 1; + if (value[0] === "-" || value[0] === "+") { + if (value[0] === "-") sign = -1; + value = value.slice(1); + } + if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2); + if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16); + if (value.includes(":")) { + let result = 0; + for (const part of value.split(":")) result = result * 60 + Number(part); + return sign * result; + } + if (value !== "0" && value[0] === "0") return sign * parseInt(value, 8); + return sign * parseInt(value, 10); +} +function resolveYamlInteger(source) { + if (!YAML_INTEGER_PATTERN.test(source)) return NOT_RESOLVED; + const result = parseYamlInteger(source); + return Number.isFinite(result) ? result : NOT_RESOLVED; +} +var intYaml11Tag = defineScalarTag("tag:yaml.org,2002:int", { + implicit: true, + implicitFirstChars: [ + "-", + "+", + ..."0123456789" + ], + resolve: resolveYamlInteger, + identify: (object) => Number.isInteger(object) && !Object.is(object, -0) && object.toString(10).indexOf("e") < 0, + represent: (object) => object.toString(10) +}); +var YAML_FLOAT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); +var YAML_FLOAT_SPECIAL_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); +function resolveYamlFloat$2(source) { + if (!YAML_FLOAT_PATTERN$1.test(source)) return NOT_RESOLVED; + let value = source.toLowerCase(); + const sign = value[0] === "-" ? -1 : 1; + if ("+-".includes(value[0])) value = value.slice(1); + if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + if (value === ".nan") return NaN; + const result = sign * parseFloat(value); + if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN$1.test(source)) return result; + return NOT_RESOLVED; +} +function representYamlFloat$2(object) { + if (isNaN(object)) return ".nan"; + if (object === Number.POSITIVE_INFINITY) return ".inf"; + if (object === Number.NEGATIVE_INFINITY) return "-.inf"; + if (Object.is(object, -0)) return "-0.0"; + const result = object.toString(10); + return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result; +} +var floatCoreTag = defineScalarTag("tag:yaml.org,2002:float", { + implicit: true, + implicitFirstChars: [ + "-", + "+", + ".", + ..."0123456789" + ], + resolve: resolveYamlFloat$2, + identify: (object) => typeof object === "number" && (!Number.isInteger(object) || Object.is(object, -0) || object.toString(10).indexOf("e") >= 0), + represent: representYamlFloat$2 +}); +var YAML_FLOAT_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$"); +var YAML_FLOAT_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); +function resolveYamlFloat$1(source, isExplicit) { + if (isExplicit) { + if (!YAML_FLOAT_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED; + let value = source.toLowerCase(); + const sign = value[0] === "-" ? -1 : 1; + if ("+-".includes(value[0])) value = value.slice(1); + if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + if (value === ".nan") return NaN; + const result = sign * parseFloat(value); + return Number.isFinite(result) ? result : NOT_RESOLVED; + } + if (!YAML_FLOAT_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED; + const result = Number(source); + if (Number.isFinite(result)) return result; + return NOT_RESOLVED; +} +function representYamlFloat$1(object) { + if (isNaN(object)) return ".nan"; + if (object === Number.POSITIVE_INFINITY) return ".inf"; + if (object === Number.NEGATIVE_INFINITY) return "-.inf"; + if (Object.is(object, -0)) return "-0.0"; + const result = object.toString(10); + return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result; +} +var floatJsonTag = defineScalarTag("tag:yaml.org,2002:float", { + implicit: true, + implicitFirstChars: ["-", ..."0123456789"], + resolve: resolveYamlFloat$1, + identify: (object) => typeof object === "number" && (!Number.isInteger(object) || Object.is(object, -0) || object.toString(10).indexOf("e") >= 0), + represent: representYamlFloat$1 +}); +var YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\.[0-9_]*)(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); +var YAML_FLOAT_SPECIAL_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"); +function resolveYamlFloat(source) { + if (!YAML_FLOAT_PATTERN.test(source)) return NOT_RESOLVED; + let value = source.toLowerCase().replace(/_/g, ""); + const sign = value[0] === "-" ? -1 : 1; + if ("+-".includes(value[0])) value = value.slice(1); + if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + if (value === ".nan") return NaN; + let result = 0; + if (value.includes(":")) { + for (const part of value.split(":")) result = result * 60 + Number(part); + result *= sign; + } else result = sign * parseFloat(value); + if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN.test(source)) return result; + return NOT_RESOLVED; +} +function representYamlFloat(object) { + if (isNaN(object)) return ".nan"; + if (object === Number.POSITIVE_INFINITY) return ".inf"; + if (object === Number.NEGATIVE_INFINITY) return "-.inf"; + if (Object.is(object, -0)) return "-0.0"; + const result = object.toString(10); + return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result; +} +var floatYaml11Tag = defineScalarTag("tag:yaml.org,2002:float", { + implicit: true, + implicitFirstChars: [ + "-", + "+", + ".", + ..."0123456789" + ], + resolve: resolveYamlFloat, + identify: (object) => typeof object === "number" && (!Number.isInteger(object) || Object.is(object, -0) || object.toString(10).indexOf("e") >= 0), + represent: representYamlFloat +}); +var mergeTag = defineScalarTag("tag:yaml.org,2002:merge", { + implicit: true, + implicitFirstChars: ["<"], + resolve: (source, isExplicit) => { + if (source === "<<" || isExplicit && source === "") return MERGE_KEY; + return NOT_RESOLVED; + } +}); +var BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/; +function resolveYamlBinary(source) { + const input = source.replace(/\s/g, ""); + if (input.length % 4 !== 0 || !BASE64_PATTERN.test(input)) return NOT_RESOLVED; + const binary = atob(input); + const result = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) result[index] = binary.charCodeAt(index); + return result; +} +function representYamlBinary(object) { + let binary = ""; + for (let index = 0; index < object.length; index++) binary += String.fromCharCode(object[index]); + return btoa(binary); +} +var binaryTag = defineScalarTag("tag:yaml.org,2002:binary", { + resolve: resolveYamlBinary, + identify: (object) => Object.prototype.toString.call(object) === "[object Uint8Array]", + represent: representYamlBinary +}); +var YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"); +var YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"); +function resolveYamlTimestamp(source) { + let match = YAML_DATE_REGEXP.exec(source); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(source); + if (match === null) return NOT_RESOLVED; + const year = +match[1]; + const month = +match[2] - 1; + const day = +match[3]; + if (!match[4]) { + const date = new Date(Date.UTC(year, month, day)); + if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day) return NOT_RESOLVED; + return date; + } + const hour = +match[4]; + const minute = +match[5]; + const second = +match[6]; + let fraction = 0; + if (hour > 23 || minute > 59 || second > 59) return NOT_RESOLVED; + if (match[7]) { + let value = match[7].slice(0, 3); + while (value.length < 3) value += "0"; + fraction = +value; + } + const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day) return NOT_RESOLVED; + if (match[9]) { + const offsetHour = +match[10]; + const offsetMinute = +(match[11] || 0); + if (offsetHour > 23 || offsetMinute > 59) return NOT_RESOLVED; + const offset = (offsetHour * 60 + offsetMinute) * 6e4; + date.setTime(date.getTime() - (match[9] === "-" ? -offset : offset)); + } + return date; +} +var timestampTag = defineScalarTag("tag:yaml.org,2002:timestamp", { + implicit: true, + implicitFirstChars: [..."0123456789"], + resolve: resolveYamlTimestamp, + identify: (object) => object instanceof Date, + represent: (object) => object.toISOString() +}); +var seqTag = defineSequenceTag("tag:yaml.org,2002:seq", { + create: () => [], + addItem: (container, item) => { + container.push(item); + }, + identify: Array.isArray +}); +function isPlainObject(data) { + if (data === null || typeof data !== "object" || Array.isArray(data)) return false; + const prototype = Object.getPrototypeOf(data); + return prototype === null || prototype === Object.prototype; +} +function pick(object, keys) { + const result = {}; + for (const key of keys) if (object[key] !== void 0) result[key] = object[key]; + return result; +} +var omapTag = defineSequenceTag("tag:yaml.org,2002:omap", { + create: () => ({ + list: [], + seen: /* @__PURE__ */ new Set() + }), + addItem: (carrier, item) => { + let key; + if (item instanceof Map) { + if (item.size !== 1) return "cannot resolve an ordered map item"; + key = item.keys().next().value; + } else if (isPlainObject(item)) { + const itemKeys = Object.keys(item); + if (itemKeys.length !== 1) return "cannot resolve an ordered map item"; + key = itemKeys[0]; + } else return "cannot resolve an ordered map item"; + if (carrier.seen.has(key)) return "duplicate key in ordered map"; + carrier.seen.add(key); + carrier.list.push(item); + return ""; + }, + finalize: (carrier) => carrier.list +}); +var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", { + create: () => [], + addItem: (container, item) => { + if (item instanceof Map) { + if (item.size !== 1) return "cannot resolve a pairs item"; + container.push(item.entries().next().value); + return ""; + } + if (Object.prototype.toString.call(item) !== "[object Object]") return "cannot resolve a pairs item"; + const object = item; + const keys = Object.keys(object); + if (keys.length !== 1) return "cannot resolve a pairs item"; + container.push([keys[0], object[keys[0]]]); + return ""; + } +}); +var mapTag = defineMappingTag("tag:yaml.org,2002:map", { + create: () => ({}), + identify: isPlainObject, + represent: (o) => { + const map = /* @__PURE__ */ new Map(); + for (const key of Object.keys(o)) map.set(key, o[key]); + return map; + }, + addPair: (container, key, value) => { + if (key !== null && typeof key === "object") return "object-based map does not support complex keys"; + const normalizedKey = String(key); + if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, { + value, + enumerable: true, + configurable: true, + writable: true + }); + else container[normalizedKey] = value; + return ""; + }, + has: (container, key) => { + if (key !== null && typeof key === "object") return false; + return Object.prototype.hasOwnProperty.call(container, String(key)); + }, + keys: (container) => Object.keys(container), + get: (container, key) => container[String(key)] +}); +var setTag = defineMappingTag("tag:yaml.org,2002:set", { + create: () => /* @__PURE__ */ new Set(), + identify: (data) => data instanceof Set, + represent: (data) => { + const map = /* @__PURE__ */ new Map(); + for (const key of data) map.set(key, null); + return map; + }, + addPair: (container, key, value) => { + if (value !== null) return "cannot resolve a set item"; + container.add(key); + return ""; + }, + has: (container, key) => container.has(key), + keys: (container) => container.keys(), + get: () => null +}); +function createTagDefinitionMap() { + return { + scalar: {}, + sequence: {}, + mapping: {} + }; +} +function createTagDefinitionListMap() { + return { + scalar: [], + sequence: [], + mapping: [] + }; +} +function compileTags(tags) { + const result = []; + for (const tag of tags) { + let index = result.length; + for (let previousIndex = 0; previousIndex < result.length; previousIndex++) { + const previous = result[previousIndex]; + if (previous.nodeKind === tag.nodeKind && previous.tagName === tag.tagName && previous.matchByTagPrefix === tag.matchByTagPrefix) { + index = previousIndex; + break; + } + } + result[index] = tag; + } + return result; +} +var Schema = class Schema { + tags; + implicitScalarTags; + implicitScalarByFirstChar; + implicitScalarAnyFirstChar; + defaultScalarTag; + defaultSequenceTag; + defaultMappingTag; + exact; + prefix; + constructor(tags) { + const compiledTags = compileTags(tags); + const implicitScalarTags = []; + const exact = createTagDefinitionMap(); + const prefix = createTagDefinitionListMap(); + for (const tag of compiledTags) { + if (tag.nodeKind === "scalar" && tag.implicit) { + if (tag.matchByTagPrefix) throw new Error("Implicit scalar tags cannot match by tag prefix"); + implicitScalarTags.push(tag); + } + switch (tag.nodeKind) { + case "scalar": + if (tag.matchByTagPrefix) prefix.scalar.push(tag); + else exact.scalar[tag.tagName] = tag; + break; + case "sequence": + if (tag.matchByTagPrefix) prefix.sequence.push(tag); + else exact.sequence[tag.tagName] = tag; + break; + case "mapping": + if (tag.matchByTagPrefix) prefix.mapping.push(tag); + else exact.mapping[tag.tagName] = tag; + break; + } + } + const implicitScalarAnyFirstChar = implicitScalarTags.filter((tag) => tag.implicitFirstChars === null); + const keys = /* @__PURE__ */ new Set(); + for (const tag of implicitScalarTags) if (tag.implicitFirstChars !== null) for (const key of tag.implicitFirstChars) keys.add(key); + const implicitScalarByFirstChar = /* @__PURE__ */ new Map(); + for (const key of keys) implicitScalarByFirstChar.set(key, implicitScalarTags.filter((tag) => tag.implicitFirstChars === null || tag.implicitFirstChars.indexOf(key) !== -1)); + const defaultScalarTag = exact.scalar["tag:yaml.org,2002:str"]; + if (!defaultScalarTag) throw new Error("schema does not define the default scalar tag (tag:yaml.org,2002:str)"); + this.tags = compiledTags; + this.implicitScalarTags = implicitScalarTags; + this.implicitScalarByFirstChar = implicitScalarByFirstChar; + this.implicitScalarAnyFirstChar = implicitScalarAnyFirstChar; + this.defaultScalarTag = defaultScalarTag; + this.defaultSequenceTag = exact.sequence["tag:yaml.org,2002:seq"]; + this.defaultMappingTag = exact.mapping["tag:yaml.org,2002:map"]; + this.exact = exact; + this.prefix = prefix; + } + withTags(...tags) { + let flatTags = []; + for (const tag of tags) flatTags = flatTags.concat(tag); + return new Schema([...this.tags, ...flatTags]); + } +}; +var FAILSAFE_SCHEMA = new Schema([ + strTag, + seqTag, + mapTag +]); +new Schema([ + ...FAILSAFE_SCHEMA.tags, + nullJsonTag, + boolJsonTag, + intJsonTag, + floatJsonTag +]); +var CORE_SCHEMA = new Schema([ + ...FAILSAFE_SCHEMA.tags, + nullCoreTag, + boolCoreTag, + intCoreTag, + floatCoreTag +]); +var YAML11_SCHEMA = new Schema([ + ...FAILSAFE_SCHEMA.tags, + nullYaml11Tag, + boolYaml11Tag, + intYaml11Tag, + floatYaml11Tag, + timestampTag, + mergeTag, + binaryTag, + omapTag, + pairsTag, + setTag +]); +defineMappingTag("tag:yaml.org,2002:map", { + create: () => /* @__PURE__ */ new Map(), + addPair: (container, key, value) => { + container.set(key, value); + return ""; + }, + has: (container, key) => container.has(key), + keys: (container) => container.keys(), + get: (container, key) => container.get(key), + identify: (data) => data instanceof Map || isPlainObject(data), + represent: (data) => { + if (data instanceof Map) return data; + const map = /* @__PURE__ */ new Map(); + const obj = data; + for (const key of Object.keys(obj)) map.set(key, obj[key]); + return map; + } +}); +function normalizeKey(key) { + if (Array.isArray(key)) { + const array = Array.prototype.slice.call(key); + for (let index = 0; index < array.length; index++) { + if (Array.isArray(array[index])) return null; + if (typeof array[index] === "object" && Object.prototype.toString.call(array[index]) === "[object Object]") array[index] = "[object Object]"; + } + return String(array); + } + if (typeof key === "object" && Object.prototype.toString.call(key) === "[object Object]") return "[object Object]"; + return String(key); +} +defineMappingTag("tag:yaml.org,2002:map", { + create: () => ({}), + identify: isPlainObject, + represent: (o) => { + const map = /* @__PURE__ */ new Map(); + for (const key of Object.keys(o)) map.set(key, o[key]); + return map; + }, + addPair: (container, key, value) => { + const normalizedKey = normalizeKey(key); + if (normalizedKey === null) return "nested arrays are not supported inside keys"; + if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, { + value, + enumerable: true, + configurable: true, + writable: true + }); + else container[normalizedKey] = value; + return ""; + }, + has: (container, key) => { + const normalizedKey = normalizeKey(key); + return normalizedKey !== null && Object.prototype.hasOwnProperty.call(container, normalizedKey); + }, + keys: (container) => Object.keys(container), + get: (container, key) => container[String(key)] +}); +var DEFAULT_SNIPPET_OPTIONS = { + maxLength: 79, + indent: 1, + linesBefore: 3, + linesAfter: 2 +}; +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + let head = ""; + let tail = ""; + const maxHalfLength = Math.floor(maxLineLength / 2) - 1; + if (position - lineStart > maxHalfLength) { + head = " ... "; + lineStart = position - maxHalfLength + head.length; + } + if (lineEnd - position > maxHalfLength) { + tail = " ..."; + lineEnd = position + maxHalfLength - tail.length; + } + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "→") + tail, + pos: position - lineStart + head.length + }; +} +function padStart(string, max) { + return " ".repeat(Math.max(max - string.length, 0)) + string; +} +function makeSnippet(mark, options) { + if (!mark.buffer) return null; + const opts = { + ...DEFAULT_SNIPPET_OPTIONS, + ...options + }; + const re = /\r?\n|\r|\0/g; + const lineStarts = [0]; + const lineEnds = []; + let match; + let foundLineNo = -1; + while (match = re.exec(mark.buffer)) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + if (mark.position <= match.index && foundLineNo < 0) foundLineNo = lineStarts.length - 2; + } + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + let result = ""; + const lineNoLength = Math.min(mark.line + opts.linesAfter, lineEnds.length).toString().length; + const maxLineLength = opts.maxLength - (opts.indent + lineNoLength + 3); + for (let i = 1; i <= opts.linesBefore; i++) { + if (foundLineNo - i < 0) break; + const line = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength); + result = `${" ".repeat(opts.indent)}${padStart((mark.line - i + 1).toString(), lineNoLength)} | ${line.str}\n${result}`; + } + const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += `${" ".repeat(opts.indent)}${padStart((mark.line + 1).toString(), lineNoLength)} | ${line.str}\n`; + result += `${"-".repeat(opts.indent + lineNoLength + 3 + line.pos)}^\n`; + for (let i = 1; i <= opts.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + const line = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength); + result += `${" ".repeat(opts.indent)}${padStart((mark.line + i + 1).toString(), lineNoLength)} | ${line.str}\n`; + } + return result.replace(/\n$/, ""); +} +function formatError(exception, compact) { + let where = ""; + if (!exception.mark) return exception.reason; + if (exception.mark.name) where += `in "${exception.mark.name}" `; + where += `(${exception.mark.line + 1}:${exception.mark.column + 1})`; + if (!compact && exception.mark.snippet) where += `\n\n${exception.mark.snippet}`; + return `${exception.reason} ${where}`; +} +var YAMLException = class extends Error { + reason; + mark; + constructor(reason, mark) { + super(); + this.name = "YAMLException"; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); + if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); + } + toString(compact) { + return `${this.name}: ${formatError(this, compact)}`; + } +}; +function throwErrorAt(source, position, message, filename = "") { + let line = 0; + let lineStart = 0; + for (let index = 0; index < position; index++) { + const ch = source.charCodeAt(index); + if (ch === 10) { + line++; + lineStart = index + 1; + } else if (ch === 13) { + line++; + if (source.charCodeAt(index + 1) === 10) index++; + lineStart = index + 1; + } + } + const mark = { + name: filename, + buffer: source, + position, + line, + column: position - lineStart + }; + mark.snippet = makeSnippet(mark); + throw new YAMLException(message, mark); +} +var NO_RANGE$3 = -1; +function simpleEscapeSequence(c) { + switch (c) { + case 48: return "\0"; + case 97: return "\x07"; + case 98: return "\b"; + case 116: return " "; + case 9: return " "; + case 110: return "\n"; + case 118: return "\v"; + case 102: return "\f"; + case 114: return "\r"; + case 101: return "\x1B"; + case 32: return " "; + case 34: return "\""; + case 47: return "/"; + case 92: return "\\"; + case 78: return "…"; + case 95: return "\xA0"; + case 76: return "\u2028"; + case 80: return "\u2029"; + default: return ""; + } +} +var simpleEscapeCheck = new Array(256); +var simpleEscapeMap = new Array(256); +for (let i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} +function charFromCodepoint(c) { + if (c <= 65535) return String.fromCharCode(c); + return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320); +} +function fromHexCode$1(c) { + if (c >= 48 && c <= 57) return c - 48; + return (c | 32) - 97 + 10; +} +function escapedHexLen$1(c) { + if (c === 120) return 2; + if (c === 117) return 4; + return 8; +} +function skipFoldedBreaks(input, position, end) { + let breaks = 0; + while (position < end) { + const ch = input.charCodeAt(position); + if (ch === 10) { + breaks++; + position++; + } else if (ch === 13) { + breaks++; + position++; + if (input.charCodeAt(position) === 10) position++; + } else if (ch === 32 || ch === 9) position++; + else break; + } + return { + position, + breaks + }; +} +function foldedBreaks(count) { + if (count === 1) return " "; + return "\n".repeat(count - 1); +} +function getPlainValue(input, start, end) { + let result = ""; + let position = start; + let captureStart = start; + let captureEnd = start; + while (position < end) { + const ch = input.charCodeAt(position); + if (ch === 10 || ch === 13) { + result += input.slice(captureStart, captureEnd); + const fold = skipFoldedBreaks(input, position, end); + result += foldedBreaks(fold.breaks); + position = captureStart = captureEnd = fold.position; + } else { + position++; + if (ch !== 32 && ch !== 9) captureEnd = position; + } + } + return result + input.slice(captureStart, captureEnd); +} +function getSingleQuotedValue(input, start, end) { + let result = ""; + let position = start; + let captureStart = start; + let captureEnd = start; + while (position < end) { + const ch = input.charCodeAt(position); + if (ch === 39) { + result += input.slice(captureStart, position) + "'"; + position += 2; + captureStart = captureEnd = position; + } else if (ch === 10 || ch === 13) { + result += input.slice(captureStart, captureEnd); + const fold = skipFoldedBreaks(input, position, end); + result += foldedBreaks(fold.breaks); + position = captureStart = captureEnd = fold.position; + } else { + position++; + if (ch !== 32 && ch !== 9) captureEnd = position; + } + } + return result + input.slice(captureStart, end); +} +function getDoubleQuotedValue(input, start, end) { + let result = ""; + let position = start; + let captureStart = start; + let captureEnd = start; + while (position < end) { + const ch = input.charCodeAt(position); + if (ch === 92) { + result += input.slice(captureStart, position); + position++; + const escaped = input.charCodeAt(position); + if (escaped === 10 || escaped === 13) position = skipFoldedBreaks(input, position, end).position; + else if (escaped < 256 && simpleEscapeCheck[escaped]) { + result += simpleEscapeMap[escaped]; + position++; + } else { + let hexLength = escapedHexLen$1(escaped); + let hexResult = 0; + for (; hexLength > 0; hexLength--) { + position++; + const digit = fromHexCode$1(input.charCodeAt(position)); + hexResult = (hexResult << 4) + digit; + } + result += charFromCodepoint(hexResult); + position++; + } + captureStart = captureEnd = position; + } else if (ch === 10 || ch === 13) { + result += input.slice(captureStart, captureEnd); + const fold = skipFoldedBreaks(input, position, end); + result += foldedBreaks(fold.breaks); + position = captureStart = captureEnd = fold.position; + } else { + position++; + if (ch !== 32 && ch !== 9) captureEnd = position; + } + } + return result + input.slice(captureStart, end); +} +function getBlockValue(input, start, end, indent, chomping, folded) { + const textIndent = indent < 0 ? 0 : indent; + const region = input.slice(start, end).replace(/\r\n?/g, "\n"); + const lines = region === "" ? [] : (region.endsWith("\n") ? region.slice(0, -1) : region).split("\n"); + let result = ""; + let didReadContent = false; + let emptyLines = 0; + let atMoreIndented = false; + for (const line of lines) { + let column = 0; + while (column < textIndent && line.charCodeAt(column) === 32) column++; + if (indent < 0 || column >= line.length) { + emptyLines++; + continue; + } + const content = line.slice(textIndent); + const first = content.charCodeAt(0); + if (folded) if (first === 32 || first === 9) { + atMoreIndented = true; + result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); + } else if (atMoreIndented) { + atMoreIndented = false; + result += "\n".repeat(emptyLines + 1); + } else if (emptyLines === 0) { + if (didReadContent) result += " "; + } else result += "\n".repeat(emptyLines); + else result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); + result += content; + didReadContent = true; + emptyLines = 0; + } + if (chomping === 3) result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines); + else if (chomping !== 2) { + if (didReadContent) result += "\n"; + } + return result; +} +function getScalarValue(input, scalar) { + if (scalar.valueStart === NO_RANGE$3) return ""; + const { valueStart, valueEnd } = scalar; + if (scalar.fast) return input.slice(valueStart, valueEnd); + switch (scalar.style) { + case 2: return getSingleQuotedValue(input, valueStart, valueEnd); + case 3: return getDoubleQuotedValue(input, valueStart, valueEnd); + case 4: return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, false); + case 5: return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, true); + default: return getPlainValue(input, valueStart, valueEnd); + } +} +var DEFAULT_TAG_HANDLERS = { + "!": "!", + "!!": "tag:yaml.org,2002:" +}; +function tagNameFull(rawTag, tagHandlers) { + if (rawTag.startsWith("!<") && rawTag.endsWith(">")) return decodeURIComponent(rawTag.slice(2, -1)); + const handleEnd = rawTag.indexOf("!", 1); + const handle = handleEnd === -1 ? "!" : rawTag.slice(0, handleEnd + 1); + const prefix = tagHandlers?.[handle] ?? DEFAULT_TAG_HANDLERS[handle] ?? handle; + return decodeURIComponent(prefix) + decodeURIComponent(rawTag.slice(handle.length)); +} +var NO_RANGE$2 = -1; +var DEFAULT_CONSTRUCTOR_OPTIONS = { + filename: "", + schema: CORE_SCHEMA, + json: false, + maxTotalMergeKeys: 1e4, + maxAliases: -1 +}; +function eventPosition$1(event) { + if ("tagStart" in event && event.tagStart !== NO_RANGE$2) return event.tagStart; + if ("anchorStart" in event && event.anchorStart !== NO_RANGE$2) return event.anchorStart; + if ("valueStart" in event && event.valueStart !== NO_RANGE$2) return event.valueStart; + if ("start" in event) return event.start; + return 0; +} +function throwError$1(state, message) { + throwErrorAt(state.source, state.position, message, state.filename); +} +function finalizeCollection(state, position, tag, carrier) { + try { + return tag.finalize(carrier); + } catch (error) { + if (error instanceof YAMLException) throw error; + throwErrorAt(state.source, position, error instanceof Error ? error.message : String(error), state.filename); + } +} +function lookupTag(exact, prefix, tagName) { + const exactTag = exact[tagName]; + if (exactTag) return exactTag; + for (const tag of prefix) if (tagName.startsWith(tag.tagName)) return tag; +} +function findExplicitTag(state, exact, prefix, tagName, nodeKind) { + const tag = lookupTag(exact, prefix, tagName); + if (tag) return tag; + throwError$1(state, `unknown ${nodeKind} tag !<${tagName}>`); +} +function constructScalar(state, event) { + const source = getScalarValue(state.source, event); + const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd); + const strTag = state.schema.defaultScalarTag; + if (rawTag !== "") { + if (rawTag === "!") return { + value: source, + tag: strTag + }; + const tagName = tagNameFull(rawTag, state.tagHandlers); + const scalarTag = lookupTag(state.schema.exact.scalar, state.schema.prefix.scalar, tagName); + if (scalarTag) { + const result = scalarTag.resolve(source, true, tagName); + if (result === NOT_RESOLVED) throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`); + return { + value: result, + tag: scalarTag + }; + } + const collectionTagDef = lookupTag(state.schema.exact.mapping, state.schema.prefix.mapping, tagName) ?? lookupTag(state.schema.exact.sequence, state.schema.prefix.sequence, tagName); + if (collectionTagDef) { + if (source !== "") throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`); + const carrier = collectionTagDef.create(tagName); + return { + value: collectionTagDef.carrierIsResult ? carrier : finalizeCollection(state, state.position, collectionTagDef, carrier), + tag: collectionTagDef + }; + } + throwError$1(state, `unknown scalar tag !<${tagName}>`); + } + if (event.style === 1) { + const candidates = state.schema.implicitScalarByFirstChar.get(source.charAt(0)) ?? state.schema.implicitScalarAnyFirstChar; + for (const tag of candidates) { + const result = tag.resolve(source, false, tag.tagName); + if (result !== NOT_RESOLVED) return { + value: result, + tag + }; + } + } + return { + value: strTag.resolve(source, false, strTag.tagName), + tag: strTag + }; +} +function collectionTag(state, event, exact, prefix, defaultTagName, nodeKind) { + const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd); + const tagName = rawTag === "" || rawTag === "!" ? defaultTagName : tagNameFull(rawTag, state.tagHandlers); + return { + tagName, + tag: findExplicitTag(state, exact, prefix, tagName, nodeKind) + }; +} +function isMappingTag(tag) { + return tag.nodeKind === "mapping"; +} +function mergeKeys(state, frame, source, sourceTag) { + for (const sourceKey of sourceTag.keys(source)) { + if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`); + if (frame.tag.has(frame.value, sourceKey)) continue; + const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey)); + if (err) throwError$1(state, err); + (frame.overridable ??= /* @__PURE__ */ new Set()).add(sourceKey); + } +} +function mergeSource(state, frame, source, sourceTag) { + state.position = frame.keyPosition; + if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag); + else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) for (const element of source) mergeKeys(state, frame, element, frame.tag); + else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable"); +} +function addMappingValue(state, frame, key, value, tag) { + state.position = frame.keyPosition; + if (key === MERGE_KEY) { + mergeSource(state, frame, value, tag); + return; + } + if (!state.json && frame.tag.has(frame.value, key) && !frame.overridable?.has(key)) throwError$1(state, "duplicated mapping key"); + const err = frame.tag.addPair(frame.value, key, value); + if (err) throwError$1(state, err); + frame.overridable?.delete(key); +} +function addValue(state, value, tag) { + const frame = state.frames[state.frames.length - 1]; + if (frame.kind === "document") { + frame.value = value; + frame.hasValue = true; + } else if (frame.kind === "sequence") { + if (frame.merge) { + if (!isMappingTag(tag)) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable"); + } + const err = frame.tag.addItem(frame.value, value, frame.index++); + if (err) throwError$1(state, err); + } else if (frame.hasKey) { + const key = frame.key; + frame.key = void 0; + frame.hasKey = false; + addMappingValue(state, frame, key, value, tag); + } else { + frame.key = value; + frame.keyPosition = state.position; + frame.hasKey = true; + } +} +function storeAnchor(state, event, value, tag, isValueFinal) { + if (event.anchorStart !== NO_RANGE$2) { + const anchor = { + value, + tag, + isValueFinal + }; + state.anchors.set(state.source.slice(event.anchorStart, event.anchorEnd), anchor); + return anchor; + } + return null; +} +function constructFromEvents(events, options) { + const state = { + ...DEFAULT_CONSTRUCTOR_OPTIONS, + ...options, + events, + documents: [], + eventIndex: 0, + position: 0, + frames: [], + anchors: /* @__PURE__ */ new Map(), + tagHandlers: Object.create(null), + totalMergeKeys: 0, + aliasCount: 0 + }; + while (state.eventIndex < state.events.length) { + const event = state.events[state.eventIndex++]; + state.position = eventPosition$1(event); + switch (event.type) { + case 1: + state.anchors = /* @__PURE__ */ new Map(); + state.aliasCount = 0; + state.tagHandlers = Object.create(null); + for (const directive of event.directives) if (directive.kind === "tag") state.tagHandlers[directive.handle] = directive.prefix; + state.frames.push({ + kind: "document", + position: state.position, + value: void 0, + hasValue: false + }); + break; + case 4: { + const { value, tag } = constructScalar(state, event); + storeAnchor(state, event, value, tag, true); + addValue(state, value, tag); + break; + } + case 2: { + const definition = collectionTag(state, event, state.schema.exact.sequence, state.schema.prefix.sequence, "tag:yaml.org,2002:seq", "sequence"); + const value = definition.tag.create(definition.tagName); + const anchor = storeAnchor(state, event, value, definition.tag, definition.tag.carrierIsResult); + const parent = state.frames[state.frames.length - 1]; + const merge = parent !== void 0 && parent.kind === "mapping" && parent.hasKey && parent.key === MERGE_KEY; + state.frames.push({ + kind: "sequence", + position: state.position, + value, + tag: definition.tag, + anchor, + index: 0, + merge + }); + break; + } + case 3: { + const definition = collectionTag(state, event, state.schema.exact.mapping, state.schema.prefix.mapping, "tag:yaml.org,2002:map", "mapping"); + const value = definition.tag.create(definition.tagName); + const anchor = storeAnchor(state, event, value, definition.tag, definition.tag.carrierIsResult); + state.frames.push({ + kind: "mapping", + position: state.position, + value, + tag: definition.tag, + anchor, + key: void 0, + keyPosition: state.position, + hasKey: false, + overridable: null + }); + break; + } + case 5: { + if (state.maxAliases !== -1 && ++state.aliasCount > state.maxAliases) throwError$1(state, `aliases exceeded maxAliases (${state.maxAliases})`); + const name = state.source.slice(event.anchorStart, event.anchorEnd); + const anchor = state.anchors.get(name); + if (!anchor) throwError$1(state, `unidentified alias "${name}"`); + if (!anchor.isValueFinal) throwError$1(state, `recursive alias "${name}" is not supported for tag ${anchor.tag.tagName} because it uses finalize()`); + addValue(state, anchor.value, anchor.tag); + break; + } + case 6: { + const frame = state.frames.pop(); + if (frame.kind === "document") state.documents.push(frame.value); + else { + const value = frame.tag.carrierIsResult ? frame.value : finalizeCollection(state, frame.position, frame.tag, frame.value); + if (frame.anchor) { + frame.anchor.value = value; + frame.anchor.isValueFinal = true; + } + addValue(state, value, frame.tag); + } + break; + } + } + } + return state.documents; +} +var NO_RANGE$1 = -1; +var HAS_OWN = Object.prototype.hasOwnProperty; +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]{}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/; +var NS_URI_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$,_.!~*'()\[\]])`; +var NS_TAG_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$.~*'()_])`; +var PATTERN_TAG_URI = new RegExp(`^(?:${NS_URI_CHAR})*$`); +var PATTERN_TAG_SUFFIX = new RegExp(`^(?:${NS_TAG_CHAR})+$`); +var PATTERN_TAG_PREFIX = new RegExp(`^(?:!(?:${NS_URI_CHAR})*|${NS_TAG_CHAR}(?:${NS_URI_CHAR})*)$`); +var DEFAULT_PARSER_OPTIONS = { + filename: "", + maxDepth: 100 +}; +function addDocumentEvent(state, explicitStart, explicitEnd) { + state.events.push({ + type: 1, + explicitStart, + explicitEnd, + directives: state.directives + }); +} +function addSequenceEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) { + state.events.push({ + type: 2, + start, + anchorStart, + anchorEnd, + tagStart, + tagEnd, + style + }); +} +function addMappingEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) { + state.events.push({ + type: 3, + start, + anchorStart, + anchorEnd, + tagStart, + tagEnd, + style + }); +} +function insertFlowPairMappingEvent(state, snapshot) { + state.events.splice(snapshot.eventsLength, 0, { + type: 3, + start: snapshot.position, + anchorStart: NO_RANGE$1, + anchorEnd: NO_RANGE$1, + tagStart: NO_RANGE$1, + tagEnd: NO_RANGE$1, + style: 2 + }); +} +function addScalarEvent(state, valueStart, valueEnd, anchorStart, anchorEnd, tagStart, tagEnd, style, chomping = 1, indent = -1, fast = false) { + state.events.push({ + type: 4, + valueStart, + valueEnd, + anchorStart, + anchorEnd, + tagStart, + tagEnd, + style, + chomping, + indent, + fast + }); +} +function addAliasEvent(state, anchorStart, anchorEnd) { + state.events.push({ + type: 5, + anchorStart, + anchorEnd + }); +} +function addPopEvent(state) { + state.events.push({ type: 6 }); +} +function addEmptyScalarEvent(state) { + addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, 1); +} +function emptyProperties() { + return { + anchorStart: NO_RANGE$1, + anchorEnd: NO_RANGE$1, + tagStart: NO_RANGE$1, + tagEnd: NO_RANGE$1 + }; +} +function snapshotState(state) { + return { + position: state.position, + line: state.line, + lineStart: state.lineStart, + lineIndent: state.lineIndent, + firstTabInLine: state.firstTabInLine, + eventsLength: state.events.length + }; +} +function restoreState(state, snapshot) { + state.position = snapshot.position; + state.line = snapshot.line; + state.lineStart = snapshot.lineStart; + state.lineIndent = snapshot.lineIndent; + state.firstTabInLine = snapshot.firstTabInLine; + state.events.length = snapshot.eventsLength; +} +function throwError(state, message) { + throwErrorAt(state.input.slice(0, state.length), state.position, message, state.filename); +} +function isEol(c) { + return c === 10 || c === 13; +} +function isWhiteSpace(c) { + return c === 9 || c === 32; +} +function isWsOrEol(c) { + return isWhiteSpace(c) || isEol(c); +} +function isWsOrEolOrEnd(c) { + return c === 0 || isWsOrEol(c); +} +function isFlowIndicator(c) { + return c === 44 || c === 91 || c === 93 || c === 123 || c === 125; +} +function fromDecimalCode(c) { + return c >= 48 && c <= 57 ? c - 48 : -1; +} +function fromHexCode(c) { + if (c >= 48 && c <= 57) return c - 48; + const lc = c | 32; + if (lc >= 97 && lc <= 102) return lc - 97 + 10; + return -1; +} +function escapedHexLen(c) { + if (c === 120) return 2; + if (c === 117) return 4; + if (c === 85) return 8; + return 0; +} +function isSimpleEscape(c) { + return c === 48 || c === 97 || c === 98 || c === 116 || c === 9 || c === 110 || c === 118 || c === 102 || c === 114 || c === 101 || c === 32 || c === 34 || c === 47 || c === 92 || c === 78 || c === 95 || c === 76 || c === 80; +} +function consumeLineBreak(state) { + if (state.input.charCodeAt(state.position) === 10) state.position++; + else { + state.position++; + if (state.input.charCodeAt(state.position) === 10) state.position++; + } + state.line++; + state.lineStart = state.position; + state.lineIndent = 0; + state.firstTabInLine = -1; +} +function skipSeparationSpace(state, allowComments) { + let lineBreaks = 0; + let ch = state.input.charCodeAt(state.position); + let hasSeparation = state.position === state.lineStart || isWsOrEol(state.input.charCodeAt(state.position - 1)); + while (ch !== 0) { + while (isWhiteSpace(ch)) { + hasSeparation = true; + if (ch === 9 && state.firstTabInLine === -1) state.firstTabInLine = state.position; + ch = state.input.charCodeAt(++state.position); + } + if (allowComments && hasSeparation && ch === 35) do + ch = state.input.charCodeAt(++state.position); + while (!isEol(ch) && ch !== 0); + if (!isEol(ch)) break; + consumeLineBreak(state); + lineBreaks++; + hasSeparation = true; + ch = state.input.charCodeAt(state.position); + while (ch === 32) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } + return lineBreaks; +} +function testDocumentSeparator(state, position = state.position) { + const ch = state.input.charCodeAt(position); + if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(position + 1) && ch === state.input.charCodeAt(position + 2)) { + const following = state.input.charCodeAt(position + 3); + return following === 0 || isWsOrEol(following); + } + return false; +} +function skipUntilLineEnd(state) { + let ch = state.input.charCodeAt(state.position); + while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position); +} +function checkPrintable(state, start, end) { + if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) throwError(state, "the stream contains non-printable characters"); +} +function readTagProperty(state, props, inFlow) { + if (state.input.charCodeAt(state.position) !== 33) return false; + if (props.tagStart !== NO_RANGE$1) throwError(state, "duplication of a tag property"); + const start = state.position; + let isVerbatim = false; + let isNamed = false; + let tagHandle = "!"; + let ch = state.input.charCodeAt(++state.position); + if (ch === 60) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + } else if (ch === 33) { + isNamed = true; + tagHandle = "!!"; + ch = state.input.charCodeAt(++state.position); + } + let suffixStart = state.position; + let tagName; + if (isVerbatim) { + while (ch !== 0 && ch !== 62) ch = state.input.charCodeAt(++state.position); + if (ch !== 62) throwError(state, "unexpected end of the stream within a verbatim tag"); + tagName = state.input.slice(suffixStart, state.position); + state.position++; + } else { + while (ch !== 0 && !isWsOrEol(ch) && !(inFlow && isFlowIndicator(ch))) { + if (ch === 33) if (!isNamed) { + tagHandle = state.input.slice(suffixStart - 1, state.position + 1); + if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, "named tag handle cannot contain such characters"); + isNamed = true; + suffixStart = state.position + 1; + } else throwError(state, "tag suffix cannot contain exclamation marks"); + ch = state.input.charCodeAt(++state.position); + } + tagName = state.input.slice(suffixStart, state.position); + if (PATTERN_FLOW_INDICATORS.test(tagName)) throwError(state, "tag suffix cannot contain flow indicator characters"); + } + if (tagName && !(isVerbatim ? PATTERN_TAG_URI.test(tagName) : PATTERN_TAG_SUFFIX.test(tagName))) throwError(state, `tag name cannot contain such characters: ${tagName}`); + if (!isVerbatim && tagHandle !== "!" && tagHandle !== "!!" && !HAS_OWN.call(state.tagHandlers, tagHandle)) throwError(state, `undeclared tag handle "${tagHandle}"`); + props.tagStart = start; + props.tagEnd = state.position; + return true; +} +function readAnchorProperty(state, props) { + if (state.input.charCodeAt(state.position) !== 38) return false; + if (props.anchorStart !== NO_RANGE$1) throwError(state, "duplication of an anchor property"); + state.position++; + const start = state.position; + while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++; + if (state.position === start) throwError(state, "name of an anchor node must contain at least one character"); + props.anchorStart = start; + props.anchorEnd = state.position; + return true; +} +function readAlias(state, props) { + if (state.input.charCodeAt(state.position) !== 42) return false; + if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) throwError(state, "alias node should not have any properties"); + state.position++; + const start = state.position; + while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++; + if (state.position === start) throwError(state, "name of an alias node must contain at least one character"); + addAliasEvent(state, start, state.position); + return true; +} +function readFlowScalarBreak(state, nodeIndent) { + skipSeparationSpace(state, false); + if (state.lineIndent < nodeIndent) throwError(state, "deficient indentation"); +} +function readSingleQuotedScalar(state, nodeIndent, props) { + if (state.input.charCodeAt(state.position) !== 39) return false; + state.position++; + const start = state.position; + let simple = true; + while (state.input.charCodeAt(state.position) !== 0) { + const ch = state.input.charCodeAt(state.position); + if (ch === 39) { + if (state.input.charCodeAt(state.position + 1) === 39) { + simple = false; + state.position += 2; + continue; + } + const end = state.position; + state.position++; + addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 2, 1, -1, simple); + return true; + } + if (isEol(ch)) { + simple = false; + readFlowScalarBreak(state, nodeIndent); + } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a single quoted scalar"); + else if (ch !== 9 && ch < 32) throwError(state, "expected valid JSON character"); + else state.position++; + } + throwError(state, "unexpected end of the stream within a single quoted scalar"); +} +function readDoubleQuotedScalar(state, nodeIndent, props) { + if (state.input.charCodeAt(state.position) !== 34) return false; + state.position++; + const start = state.position; + let simple = true; + while (state.input.charCodeAt(state.position) !== 0) { + const ch = state.input.charCodeAt(state.position); + if (ch === 34) { + const end = state.position; + state.position++; + addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 3, 1, -1, simple); + return true; + } + if (ch === 92) { + simple = false; + const escaped = state.input.charCodeAt(++state.position); + if (isEol(escaped)) readFlowScalarBreak(state, nodeIndent); + else if (isSimpleEscape(escaped)) state.position++; + else { + let hexLength = escapedHexLen(escaped); + if (hexLength === 0) throwError(state, "unknown escape sequence"); + while (hexLength-- > 0) { + state.position++; + if (fromHexCode(state.input.charCodeAt(state.position)) < 0) throwError(state, "expected hexadecimal character"); + } + state.position++; + } + } else if (isEol(ch)) { + simple = false; + readFlowScalarBreak(state, nodeIndent); + } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a double quoted scalar"); + else if (ch !== 9 && ch < 32) throwError(state, "expected valid JSON character"); + else state.position++; + } + throwError(state, "unexpected end of the stream within a double quoted scalar"); +} +function readBlockScalar(state, parentIndent, props) { + const ch = state.input.charCodeAt(state.position); + let chomping = 1; + let indent = -1; + let detectedIndent = false; + if (ch !== 124 && ch !== 62) return false; + const style = ch === 124 ? 4 : 5; + state.position++; + while (state.input.charCodeAt(state.position) !== 0) { + const current = state.input.charCodeAt(state.position); + const digit = fromDecimalCode(current); + if (current === 43 || current === 45) { + if (chomping !== 1) throwError(state, "repeat of a chomping mode identifier"); + chomping = current === 43 ? 3 : 2; + state.position++; + } else if (digit >= 0) { + if (digit === 0) throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one"); + if (detectedIndent) throwError(state, "repeat of an indentation width identifier"); + indent = parentIndent + digit - 1; + detectedIndent = true; + state.position++; + } else break; + } + let hadWhitespace = false; + while (isWhiteSpace(state.input.charCodeAt(state.position))) { + hadWhitespace = true; + state.position++; + } + if (hadWhitespace && state.input.charCodeAt(state.position) === 35) skipUntilLineEnd(state); + if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state); + else if (state.input.charCodeAt(state.position) !== 0) throwError(state, "a line break is expected"); + let contentIndent = detectedIndent ? indent : -1; + let maxLeadingIndent = 0; + const valueStart = state.position; + let valueEnd = state.position; + while (state.input.charCodeAt(state.position) !== 0) { + const linePosition = state.position; + let column = 0; + while (state.input.charCodeAt(linePosition + column) === 32) column++; + const first = state.input.charCodeAt(linePosition + column); + if (first === 0) { + if (contentIndent >= 0) { + if (column > contentIndent) valueEnd = linePosition + column; + } else if (column > 0) valueEnd = linePosition + column; + break; + } + if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition)) break; + if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column); + if (!detectedIndent && contentIndent === -1 && !isEol(first)) { + if (first === 9 && column < parentIndent) { + state.position = linePosition + column; + throwError(state, "tab characters must not be used in indentation"); + } + if (column < maxLeadingIndent) { + state.position = linePosition + column; + throwError(state, "bad indentation of a mapping entry"); + } + } + if (contentIndent === -1 && first !== 0 && !isEol(first) && column < parentIndent) { + state.lineIndent = column; + state.position = linePosition + column; + break; + } + if (!detectedIndent && first !== 0 && !isEol(first) && contentIndent === -1) contentIndent = column; + const requiredIndent = contentIndent === -1 ? parentIndent + 1 : contentIndent; + if (first !== 0 && !isEol(first) && column < requiredIndent) { + state.lineIndent = column; + state.position = linePosition + column; + break; + } + skipUntilLineEnd(state); + valueEnd = state.position; + if (isEol(state.input.charCodeAt(state.position))) { + consumeLineBreak(state); + valueEnd = state.position; + } + } + checkPrintable(state, valueStart, valueEnd); + addScalarEvent(state, valueStart, valueEnd, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, style, chomping, contentIndent); + return true; +} +function canStartPlainScalar(state, nodeContext) { + const ch = state.input.charCodeAt(state.position); + const inFlow = nodeContext === CONTEXT_FLOW_IN; + if (ch === 0 || isWsOrEol(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96 || inFlow && isFlowIndicator(ch)) return false; + if (ch === 63 || ch === 45) { + const following = state.input.charCodeAt(state.position + 1); + if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) return false; + } + return true; +} +function readPlainScalar(state, nodeIndent, nodeContext, props) { + if (!canStartPlainScalar(state, nodeContext)) return false; + const start = state.position; + let end = state.position; + let ch = state.input.charCodeAt(state.position); + const inFlow = nodeContext === CONTEXT_FLOW_IN; + let multiline = false; + while (ch !== 0) { + if (state.position === state.lineStart && testDocumentSeparator(state)) break; + if (ch === 58) { + const following = state.input.charCodeAt(state.position + 1); + if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break; + } else if (ch === 35) { + if (isWsOrEol(state.input.charCodeAt(state.position - 1))) break; + } else if (inFlow && isFlowIndicator(ch)) break; + else if (isEol(ch)) { + const savedPosition = state.position; + const savedLine = state.line; + const savedLineStart = state.lineStart; + const savedLineIndent = state.lineIndent; + skipSeparationSpace(state, false); + if (state.lineIndent >= nodeIndent) { + multiline = true; + ch = state.input.charCodeAt(state.position); + continue; + } + state.position = savedPosition; + state.line = savedLine; + state.lineStart = savedLineStart; + state.lineIndent = savedLineIndent; + break; + } + if (!isWhiteSpace(ch)) end = state.position + 1; + ch = state.input.charCodeAt(++state.position); + } + if (end === start) return false; + checkPrintable(state, start, end); + addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1, 1, -1, !multiline); + return true; +} +function skipFlowSeparationSpace(state, nodeIndent) { + const startLine = state.line; + skipSeparationSpace(state, true); + if (state.line > startLine && state.lineIndent < nodeIndent || state.firstTabInLine !== -1 && state.lineIndent < nodeIndent) throwError(state, "deficient indentation"); +} +function readFlowCollection(state, nodeIndent, props) { + const ch = state.input.charCodeAt(state.position); + const isMapping = ch === 123; + const start = state.position; + let readNext = true; + if (ch !== 91 && ch !== 123) return false; + const terminator = isMapping ? 125 : 93; + if (isMapping) addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 2); + else addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 2); + state.position++; + while (state.input.charCodeAt(state.position) !== 0) { + skipFlowSeparationSpace(state, nodeIndent); + let ch = state.input.charCodeAt(state.position); + if (ch === terminator) { + state.position++; + addPopEvent(state); + return true; + } else if (!readNext) throwError(state, "missed comma between flow collection entries"); + else if (ch === 44) throwError(state, "expected the node content, but found ','"); + let isPair = false; + let isExplicitPair = false; + if (ch === 63 && isWsOrEol(state.input.charCodeAt(state.position + 1))) { + isPair = isExplicitPair = true; + state.position += 1; + skipFlowSeparationSpace(state, nodeIndent); + } + const entryLine = state.line; + const entryStart = snapshotState(state); + const keyWasRead = parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + skipFlowSeparationSpace(state, nodeIndent); + ch = state.input.charCodeAt(state.position); + if ((isMapping || isExplicitPair || state.line === entryLine) && ch === 58) { + isPair = true; + state.position++; + skipFlowSeparationSpace(state, nodeIndent); + if (!isMapping) { + insertFlowPairMappingEvent(state, entryStart); + if (!keyWasRead) addEmptyScalarEvent(state); + } else if (!keyWasRead) addEmptyScalarEvent(state); + if (!parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)) addEmptyScalarEvent(state); + skipFlowSeparationSpace(state, nodeIndent); + if (!isMapping) addPopEvent(state); + } else if (isMapping && isPair) { + if (!keyWasRead) addEmptyScalarEvent(state); + addEmptyScalarEvent(state); + } else if (isMapping) addEmptyScalarEvent(state); + else if (isPair) { + insertFlowPairMappingEvent(state, entryStart); + if (!keyWasRead) addEmptyScalarEvent(state); + addEmptyScalarEvent(state); + addPopEvent(state); + } + ch = state.input.charCodeAt(state.position); + if (ch === 44) { + readNext = true; + state.position++; + } else readNext = false; + } + throwError(state, "unexpected end of the stream within a flow collection"); +} +function readBlockSequence(state, nodeIndent, props) { + if (state.firstTabInLine !== -1 || state.input.charCodeAt(state.position) !== 45 || !isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) return false; + addSequenceEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); + while (state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, "tab characters must not be used in indentation"); + } + const entryLine = state.line; + state.position++; + const hadBreak = skipSeparationSpace(state, true) > 0; + if (state.firstTabInLine !== -1 && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry"); + if (hadBreak && state.lineIndent <= nodeIndent) addEmptyScalarEvent(state); + else parseNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + skipSeparationSpace(state, true); + if (state.lineIndent < nodeIndent || state.position >= state.length) break; + if (state.lineIndent > nodeIndent) throwError(state, "bad indentation of a sequence entry"); + if (state.line === entryLine && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry"); + } + addPopEvent(state); + return true; +} +function readBlockMapping(state, nodeIndent, flowIndent, props) { + let atExplicitKey = false; + let detected = false; + let mappingOpened = false; + let pendingExplicitKey = false; + if (state.firstTabInLine !== -1) return false; + let ch = state.input.charCodeAt(state.position); + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, "tab characters must not be used in indentation"); + } + const following = state.input.charCodeAt(state.position + 1); + const entryLine = state.line; + if ((ch === 63 || ch === 58) && isWsOrEolOrEnd(following)) { + if (!mappingOpened) { + addMappingEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); + mappingOpened = true; + } + if (ch === 63) { + if (atExplicitKey) addEmptyScalarEvent(state); + detected = true; + atExplicitKey = true; + } else if (atExplicitKey) atExplicitKey = false; + else { + addEmptyScalarEvent(state); + detected = true; + atExplicitKey = false; + } + state.position += 1; + pendingExplicitKey = true; + } else { + if (atExplicitKey) { + addEmptyScalarEvent(state); + atExplicitKey = false; + } + const beforeKey = snapshotState(state); + if (!parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) break; + if (state.line === entryLine) { + ch = state.input.charCodeAt(state.position); + while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position); + if (ch === 58) { + ch = state.input.charCodeAt(++state.position); + if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping"); + if (!mappingOpened) { + restoreState(state, beforeKey); + addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); + mappingOpened = true; + parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true); + ch = state.input.charCodeAt(state.position); + while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position); + state.position++; + } + detected = true; + atExplicitKey = false; + pendingExplicitKey = false; + } else if (detected) throwError(state, "expected ':' after a mapping key"); + else { + if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) { + restoreState(state, beforeKey); + return false; + } + return true; + } + } else if (detected) throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key"); + else { + if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) { + restoreState(state, beforeKey); + return false; + } + return true; + } + } + if (parseNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, pendingExplicitKey)) pendingExplicitKey = false; + if (!atExplicitKey) { + if (pendingExplicitKey) { + addEmptyScalarEvent(state); + pendingExplicitKey = false; + } + } + skipSeparationSpace(state, true); + ch = state.input.charCodeAt(state.position); + if ((state.line === entryLine || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, "bad indentation of a mapping entry"); + else if (state.lineIndent < nodeIndent) break; + } + if (!detected) return false; + if (atExplicitKey) addEmptyScalarEvent(state); + if (mappingOpened) addPopEvent(state); + return true; +} +function parseNode(state, parentIndent, nodeContext, allowToSeek, allowCompact, allowPropertyMapping = true) { + if (state.depth >= state.maxDepth) throwError(state, `nesting exceeded maxDepth (${state.maxDepth})`); + state.depth++; + let indentStatus = 1; + let atNewLine = false; + let hasContent = false; + let propertyStart = null; + const props = emptyProperties(); + let allowBlockScalars = nodeContext === CONTEXT_BLOCK_OUT || nodeContext === CONTEXT_BLOCK_IN; + let allowBlockCollections = allowBlockScalars; + const allowBlockStyles = allowBlockScalars; + if (allowToSeek && skipSeparationSpace(state, true)) { + atNewLine = true; + if (state.lineIndent > parentIndent) indentStatus = 1; + else if (state.lineIndent === parentIndent) indentStatus = 0; + else indentStatus = -1; + } + if (state.position === state.lineStart && testDocumentSeparator(state)) { + state.depth--; + return false; + } + if (indentStatus === 1) while (true) { + const ch = state.input.charCodeAt(state.position); + const propertyState = snapshotState(state); + if (atNewLine && indentStatus !== 1 && (ch === 33 || ch === 38)) break; + if (atNewLine && allowBlockStyles && (props.tagStart !== NO_RANGE$1 || props.anchorStart !== NO_RANGE$1) && (ch === 33 || ch === 38)) { + const fallbackState = snapshotState(state); + const flowIndent = parentIndent + 1; + if (readBlockMapping(state, state.position - state.lineStart, flowIndent, props) && state.events[fallbackState.eventsLength]?.type === 3) { + state.depth--; + return true; + } + restoreState(state, fallbackState); + } + if (atNewLine && (ch === 33 && props.tagStart !== NO_RANGE$1 || ch === 38 && props.anchorStart !== NO_RANGE$1)) break; + if (!readTagProperty(state, props, nodeContext === CONTEXT_FLOW_IN) && !readAnchorProperty(state, props)) break; + if (propertyStart === null) propertyStart = propertyState; + if (skipSeparationSpace(state, true)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + if (state.lineIndent > parentIndent) indentStatus = 1; + else if (state.lineIndent === parentIndent) indentStatus = 0; + else indentStatus = -1; + } else allowBlockCollections = false; + } + if (allowBlockCollections) allowBlockCollections = atNewLine || allowCompact; + if (indentStatus === 1 || nodeContext === CONTEXT_BLOCK_OUT) { + const flowIndent = nodeContext === CONTEXT_FLOW_IN || nodeContext === CONTEXT_FLOW_OUT ? parentIndent : parentIndent + 1; + const blockIndent = state.position - state.lineStart; + if (indentStatus === 1) if (allowBlockCollections && (readBlockSequence(state, blockIndent, props) || readBlockMapping(state, blockIndent, flowIndent, props)) || readFlowCollection(state, flowIndent, props)) hasContent = true; + else { + const ch = state.input.charCodeAt(state.position); + if (propertyStart !== null && allowPropertyMapping && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62) { + const fallbackState = snapshotState(state); + const propertyIndent = propertyStart.position - propertyStart.lineStart; + restoreState(state, propertyStart); + if (readBlockMapping(state, propertyIndent, flowIndent, emptyProperties()) && state.events[fallbackState.eventsLength]?.type === 3) hasContent = true; + else restoreState(state, fallbackState); + } + if (!hasContent && (allowBlockScalars && readBlockScalar(state, flowIndent, props) || readSingleQuotedScalar(state, flowIndent, props) || readDoubleQuotedScalar(state, flowIndent, props) || readAlias(state, props) || readPlainScalar(state, flowIndent, nodeContext, props))) hasContent = true; + } + else if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent, props); + } + allowBlockScalars = allowBlockScalars && !hasContent; + if (!hasContent && (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1 || allowBlockScalars)) { + addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, 1); + hasContent = true; + } + state.depth--; + return hasContent || props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1; +} +function readDirective(state) { + if (state.lineIndent > 0 || state.input.charCodeAt(state.position) !== 37) return false; + state.position++; + const nameStart = state.position; + while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++; + const name = state.input.slice(nameStart, state.position); + const args = []; + if (name.length === 0) throwError(state, "directive name must not be less than one character in length"); + while (state.input.charCodeAt(state.position) !== 0 && !isEol(state.input.charCodeAt(state.position))) { + while (isWhiteSpace(state.input.charCodeAt(state.position))) state.position++; + if (state.input.charCodeAt(state.position) === 35 || isEol(state.input.charCodeAt(state.position)) || state.input.charCodeAt(state.position) === 0) break; + const start = state.position; + while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++; + args.push(state.input.slice(start, state.position)); + } + if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state); + if (name === "YAML") { + if (state.directives.some((directive) => directive.kind === "yaml")) throwError(state, "duplication of %YAML directive"); + if (args.length !== 1) throwError(state, "YAML directive accepts exactly one argument"); + const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + if (match === null) throwError(state, "ill-formed argument of the YAML directive"); + if (parseInt(match[1], 10) !== 1) throwError(state, "unacceptable YAML version of the document"); + state.directives.push({ + kind: "yaml", + version: args[0] + }); + } else if (name === "TAG") { + if (args.length !== 2) throwError(state, "TAG directive accepts exactly two arguments"); + const [handle, prefix] = args; + if (!PATTERN_TAG_HANDLE.test(handle)) throwError(state, "ill-formed tag handle (first argument) of the TAG directive"); + if (HAS_OWN.call(state.tagHandlers, handle)) throwError(state, `there is a previously declared suffix for "${handle}" tag handle`); + if (!PATTERN_TAG_PREFIX.test(prefix)) throwError(state, "ill-formed tag prefix (second argument) of the TAG directive"); + state.tagHandlers[handle] = prefix; + state.directives.push({ + kind: "tag", + handle, + prefix + }); + } + return true; +} +function readDocument(state) { + state.directives = []; + state.tagHandlers = Object.create(null); + let hasDirectives = false; + skipSeparationSpace(state, true); + while (readDirective(state)) { + hasDirectives = true; + skipSeparationSpace(state, true); + } + let explicitStart = false; + let explicitEnd = false; + let allowCompact = true; + if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 3))) { + explicitStart = true; + const markerLine = state.line; + state.position += 3; + skipSeparationSpace(state, true); + allowCompact = state.line > markerLine; + } else if (hasDirectives) throwError(state, "directives end mark is expected"); + const documentEventIndex = state.events.length; + if (!explicitStart && state.position === state.lineStart && state.input.charCodeAt(state.position) === 46 && testDocumentSeparator(state)) { + state.position += 3; + skipSeparationSpace(state, true); + return; + } + addDocumentEvent(state, explicitStart, false); + if (!parseNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, allowCompact, allowCompact)) addEmptyScalarEvent(state); + skipSeparationSpace(state, true); + if (state.position === state.lineStart && testDocumentSeparator(state)) { + explicitEnd = state.input.charCodeAt(state.position) === 46; + if (explicitEnd) { + const markerLine = state.line; + state.position += 3; + skipSeparationSpace(state, true); + if (state.line === markerLine && state.position < state.length) throwError(state, "end of the stream or a document separator is expected"); + } + } + const documentEvent = state.events[documentEventIndex]; + if (documentEvent?.type === 1) documentEvent.explicitEnd = explicitEnd; + addPopEvent(state); + if (!explicitEnd && state.position < state.length && !(state.position === state.lineStart && testDocumentSeparator(state))) throwError(state, "end of the stream or a document separator is expected"); +} +function parseEvents(input, options) { + const length = input.length; + const state = { + ...DEFAULT_PARSER_OPTIONS, + ...options, + input: `${input}\0`, + length, + position: 0, + line: 0, + lineStart: 0, + lineIndent: 0, + firstTabInLine: -1, + depth: 0, + directives: [], + tagHandlers: Object.create(null), + events: [] + }; + const nullpos = input.indexOf("\0"); + if (nullpos !== -1) throwErrorAt(input, nullpos, "null byte is not allowed in input", state.filename); + if (state.input.charCodeAt(state.position) === 65279) state.position++; + while (state.position < state.length) { + skipSeparationSpace(state, true); + if (state.position >= state.length) break; + const documentStart = state.position; + readDocument(state); + if (state.position === documentStart) + /* c8 ignore next */ + throwError(state, "can not read a document"); + } + return state.events; +} +var DEFAULT_LOAD_OPTIONS = { + ...DEFAULT_PARSER_OPTIONS, + ...DEFAULT_CONSTRUCTOR_OPTIONS +}; +function loadDocuments(input, options = {}) { + const opts = { + ...DEFAULT_LOAD_OPTIONS, + ...options + }; + const source = String(input); + const PARSER_OPT_KEYS = Object.keys(DEFAULT_PARSER_OPTIONS); + const CONSTRUCTOR_OPT_KEYS = Object.keys(DEFAULT_CONSTRUCTOR_OPTIONS); + return constructFromEvents(parseEvents(source, pick(opts, PARSER_OPT_KEYS)), { + ...pick(opts, CONSTRUCTOR_OPT_KEYS), + source + }); +} +function load(input, options) { + const documents = loadDocuments(input, options); + if (documents.length === 0) throw new YAMLException("expected a document, but the input is empty"); + if (documents.length === 1) return documents[0]; + throw new YAMLException("expected a single document in the stream, but found more"); +} +var ESCAPE_SEQUENCES = {}; +ESCAPE_SEQUENCES[0] = "\\0"; +ESCAPE_SEQUENCES[7] = "\\a"; +ESCAPE_SEQUENCES[8] = "\\b"; +ESCAPE_SEQUENCES[9] = "\\t"; +ESCAPE_SEQUENCES[10] = "\\n"; +ESCAPE_SEQUENCES[11] = "\\v"; +ESCAPE_SEQUENCES[12] = "\\f"; +ESCAPE_SEQUENCES[13] = "\\r"; +ESCAPE_SEQUENCES[27] = "\\e"; +ESCAPE_SEQUENCES[34] = "\\\""; +ESCAPE_SEQUENCES[92] = "\\\\"; +ESCAPE_SEQUENCES[133] = "\\N"; +ESCAPE_SEQUENCES[160] = "\\_"; +ESCAPE_SEQUENCES[8232] = "\\L"; +ESCAPE_SEQUENCES[8233] = "\\P"; +var DEFAULT_PRESENTER_OPTIONS = { + indent: 2, + seqNoIndent: false, + seqInlineFirst: true, + sortKeys: false, + lineWidth: 80, + flowBracketPadding: false, + flowSkipCommaSpace: false, + flowSkipColonSpace: false, + quoteFlowKeys: false, + quoteStyle: "single", + forceQuotes: false, + tagBeforeAnchor: false +}; +YAML11_SCHEMA.withTags({ + ...intYaml11Tag, + resolve: (source, isExplicit, tagName) => { + const result = intYaml11Tag.resolve(source, isExplicit, tagName); + return result === NOT_RESOLVED ? intCoreTag.resolve(source, isExplicit, tagName) : result; + } +}, { + ...floatYaml11Tag, + resolve: (source, isExplicit, tagName) => { + const result = floatYaml11Tag.resolve(source, isExplicit, tagName); + return result === NOT_RESOLVED ? floatCoreTag.resolve(source, isExplicit, tagName) : result; + } +}); +({ ...DEFAULT_PRESENTER_OPTIONS }); +//#endregion +export { load as t }; diff --git a/.vercel/output/functions/__server.func/_libs/jszip+[...].mjs b/.vercel/output/functions/__server.func/_libs/jszip+[...].mjs new file mode 100644 index 0000000..959d838 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/jszip+[...].mjs @@ -0,0 +1,8671 @@ +import { i as __require, t as __commonJSMin } from "../_runtime.mjs"; +import { t as require_isarray } from "./isarray.mjs"; +import { t as require_util } from "./core-util-is.mjs"; +import { t as require_inherits } from "./inherits.mjs"; +import { t as require_lib$2 } from "./immediate.mjs"; +//#region node_modules/process-nextick-args/index.js +var require_process_nextick_args = /* @__PURE__ */ __commonJSMin(((exports, module) => { + if (typeof process === "undefined" || !process.version || process.version.indexOf("v0.") === 0 || process.version.indexOf("v1.") === 0 && process.version.indexOf("v1.8.") !== 0) module.exports = { nextTick }; + else module.exports = process; + function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== "function") throw new TypeError("\"callback\" argument must be a function"); + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: return process.nextTick(fn); + case 2: return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) args[i++] = arguments[i]; + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } + } +})); +//#endregion +//#region node_modules/readable-stream/lib/internal/streams/stream.js +var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = __require("stream"); +})); +//#endregion +//#region node_modules/safe-buffer/index.js +var require_safe_buffer = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var buffer = __require("buffer"); + var Buffer = buffer.Buffer; + function copyProps(src, dst) { + for (var key in src) dst[key] = src[key]; + } + if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) module.exports = buffer; + else { + copyProps(buffer, exports); + exports.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length); + } + copyProps(Buffer, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length) { + if (typeof arg === "number") throw new TypeError("Argument must not be a number"); + return Buffer(arg, encodingOrOffset, length); + }; + SafeBuffer.alloc = function(size, fill, encoding) { + if (typeof size !== "number") throw new TypeError("Argument must be a number"); + var buf = Buffer(size); + if (fill !== void 0) if (typeof encoding === "string") buf.fill(fill, encoding); + else buf.fill(fill); + else buf.fill(0); + return buf; + }; + SafeBuffer.allocUnsafe = function(size) { + if (typeof size !== "number") throw new TypeError("Argument must be a number"); + return Buffer(size); + }; + SafeBuffer.allocUnsafeSlow = function(size) { + if (typeof size !== "number") throw new TypeError("Argument must be a number"); + return buffer.SlowBuffer(size); + }; +})); +//#endregion +//#region node_modules/readable-stream/lib/internal/streams/BufferList.js +var require_BufferList = /* @__PURE__ */ __commonJSMin(((exports, module) => { + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); + } + var Buffer = require_safe_buffer().Buffer; + var util = __require("util"); + function copyBuffer(src, target, offset) { + src.copy(target, offset); + } + module.exports = function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + BufferList.prototype.push = function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + }; + BufferList.prototype.unshift = function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + }; + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ""; + var p = this.head; + var ret = "" + p.data; + while (p = p.next) ret += s + p.data; + return ret; + }; + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + return BufferList; + }(); + if (util && util.inspect && util.inspect.custom) module.exports.prototype[util.inspect.custom] = function() { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + " " + obj; + }; +})); +//#endregion +//#region node_modules/readable-stream/lib/internal/streams/destroy.js +var require_destroy = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var pna = require_process_nextick_args(); + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) cb(err); + else if (err) { + if (!this._writableState) pna.nextTick(emitErrorNT, this, err); + else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, this, err); + } + } + return this; + } + if (this._readableState) this._readableState.destroyed = true; + if (this._writableState) this._writableState.destroyed = true; + this._destroy(err || null, function(err) { + if (!cb && err) { + if (!_this._writableState) pna.nextTick(emitErrorNT, _this, err); + else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, _this, err); + } + } else if (cb) cb(err); + }); + return this; + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self, err) { + self.emit("error", err); + } + module.exports = { + destroy, + undestroy + }; +})); +//#endregion +//#region node_modules/util-deprecate/node.js +var require_node = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + module.exports = __require("util").deprecate; +})); +//#endregion +//#region node_modules/readable-stream/lib/_stream_writable.js +var require__stream_writable = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var pna = require_process_nextick_args(); + module.exports = Writable; + function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state); + }; + } + var asyncWrite = !process.browser && ["v0.10", "v0.9."].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; + var Duplex; + Writable.WritableState = WritableState; + var util = Object.create(require_util()); + util.inherits = require_inherits(); + var internalUtil = { deprecate: require_node() }; + var Stream = require_stream(); + var Buffer = require_safe_buffer().Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() {}; + function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); + } + function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = require_destroy(); + util.inherits(Writable, Stream); + function nop() {} + function WritableState(options, stream) { + Duplex = Duplex || require__stream_duplex(); + options = options || {}; + var isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + if (hwm || hwm === 0) this.highWaterMark = hwm; + else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm; + else this.highWaterMark = defaultHwm; + this.highWaterMark = Math.floor(this.highWaterMark); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er) { + onwrite(stream, er); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { get: internalUtil.deprecate(function() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") }); + } catch (_) {} + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { value: function(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } }); + } else realHasInstance = function(object) { + return object instanceof this; + }; + function Writable(options) { + Duplex = Duplex || require__stream_duplex(); + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) return new Writable(options); + this._writableState = new WritableState(options, this); + this.writable = true; + if (options) { + if (typeof options.write === "function") this._write = options.write; + if (typeof options.writev === "function") this._writev = options.writev; + if (typeof options.destroy === "function") this._destroy = options.destroy; + if (typeof options.final === "function") this._final = options.final; + } + Stream.call(this); + } + Writable.prototype.pipe = function() { + this.emit("error", /* @__PURE__ */ new Error("Cannot pipe, not readable")); + }; + function writeAfterEnd(stream, cb) { + var er = /* @__PURE__ */ new Error("write after end"); + stream.emit("error", er); + pna.nextTick(cb, er); + } + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + if (chunk === null) er = /* @__PURE__ */ new TypeError("May not write null values to stream"); + else if (typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) er = /* @__PURE__ */ new TypeError("Invalid non-string/buffer chunk"); + if (er) { + stream.emit("error", er); + pna.nextTick(cb, er); + valid = false; + } + return valid; + } + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) chunk = _uint8ArrayToBuffer(chunk); + if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = "buffer"; + else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== "function") cb = nop; + if (state.ended) writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; + }; + Writable.prototype.cork = function() { + var state = this._writableState; + state.corked++; + }; + Writable.prototype.uncork = function() { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + if (typeof encoding === "string") encoding = encoding.toLowerCase(); + if (!([ + "hex", + "utf8", + "utf-8", + "ascii", + "binary", + "base64", + "ucs2", + "ucs-2", + "utf16le", + "utf-16le", + "raw" + ].indexOf((encoding + "").toLowerCase()) > -1)) throw new TypeError("Unknown encoding: " + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") chunk = Buffer.from(chunk, encoding); + return chunk; + } + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + enumerable: false, + get: function() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = "buffer"; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk, + encoding, + isBuf, + callback: cb, + next: null + }; + if (last) last.next = state.lastBufferedRequest; + else state.bufferedRequest = state.lastBufferedRequest; + state.bufferedRequestCount += 1; + } else doWrite(stream, state, false, len, chunk, encoding, cb); + return ret; + } + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite); + else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + pna.nextTick(cb, er); + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit("error", er); + } else { + cb(er); + stream._writableState.errorEmitted = true; + stream.emit("error", er); + finishMaybe(stream, state); + } + } + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb); + else { + var finished = needFinish(state); + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(stream, state); + if (sync) asyncWrite(afterWrite, stream, state, finished, cb); + else afterWrite(stream, state, finished, cb); + } + } + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit("drain"); + } + } + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, "", holder.finish); + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else state.corkedRequestsFree = new CorkedRequest(state); + state.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + doWrite(stream, state, false, state.objectMode ? 1 : chunk.length, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + if (state.writing) break; + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding, cb) { + cb(/* @__PURE__ */ new Error("_write() is not implemented")); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== void 0) this.write(chunk, encoding); + if (state.corked) { + state.corked = 1; + this.uncork(); + } + if (!state.ending) endWritable(this, state, cb); + }; + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + function callFinal(stream, state) { + stream._final(function(err) { + state.pendingcb--; + if (err) stream.emit("error", err); + state.prefinished = true; + stream.emit("prefinish"); + finishMaybe(stream, state); + }); + } + function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) if (typeof stream._final === "function") { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit("prefinish"); + } + } + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit("finish"); + } + } + return need; + } + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) if (state.finished) pna.nextTick(cb); + else stream.once("finish", cb); + state.ended = true; + stream.writable = false; + } + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + state.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + get: function() { + if (this._writableState === void 0) return false; + return this._writableState.destroyed; + }, + set: function(value) { + if (!this._writableState) return; + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + this.end(); + cb(err); + }; +})); +//#endregion +//#region node_modules/readable-stream/lib/_stream_duplex.js +var require__stream_duplex = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var pna = require_process_nextick_args(); + var objectKeys = Object.keys || function(obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; + }; + module.exports = Duplex; + var util = Object.create(require_util()); + util.inherits = require_inherits(); + var Readable = require__stream_readable(); + var Writable = require__stream_writable(); + util.inherits(Duplex, Readable); + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + if (options && options.readable === false) this.readable = false; + if (options && options.writable === false) this.writable = false; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + this.once("end", onend); + } + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + enumerable: false, + get: function() { + return this._writableState.highWaterMark; + } + }); + function onend() { + if (this.allowHalfOpen || this._writableState.ended) return; + pna.nextTick(onEndNT, this); + } + function onEndNT(self) { + self.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + get: function() { + if (this._readableState === void 0 || this._writableState === void 0) return false; + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function(value) { + if (this._readableState === void 0 || this._writableState === void 0) return; + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + Duplex.prototype._destroy = function(err, cb) { + this.push(null); + this.end(); + pna.nextTick(cb, err); + }; +})); +//#endregion +//#region node_modules/readable-stream/lib/_stream_readable.js +var require__stream_readable = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var pna = require_process_nextick_args(); + module.exports = Readable; + var isArray = require_isarray(); + var Duplex; + Readable.ReadableState = ReadableState; + __require("events").EventEmitter; + var EElistenerCount = function(emitter, type) { + return emitter.listeners(type).length; + }; + var Stream = require_stream(); + var Buffer = require_safe_buffer().Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() {}; + function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); + } + function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + } + var util = Object.create(require_util()); + util.inherits = require_inherits(); + var debugUtil = __require("util"); + var debug = void 0; + if (debugUtil && debugUtil.debuglog) debug = debugUtil.debuglog("stream"); + else debug = function() {}; + var BufferList = require_BufferList(); + var destroyImpl = require_destroy(); + var StringDecoder; + util.inherits(Readable, Stream); + var kProxyEvents = [ + "error", + "close", + "destroy", + "pause", + "resume" + ]; + function prependListener(emitter, event, fn) { + if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn); + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); + else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; + } + function ReadableState(options, stream) { + Duplex = Duplex || require__stream_duplex(); + options = options || {}; + var isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + if (hwm || hwm === 0) this.highWaterMark = hwm; + else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm; + else this.highWaterMark = defaultHwm; + this.highWaterMark = Math.floor(this.highWaterMark); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.destroyed = false; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __require("node:string_decoder").StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + Duplex = Duplex || require__stream_duplex(); + if (!(this instanceof Readable)) return new Readable(options); + this._readableState = new ReadableState(options, this); + this.readable = true; + if (options) { + if (typeof options.read === "function") this._read = options.read; + if (typeof options.destroy === "function") this._destroy = options.destroy; + } + Stream.call(this); + } + Object.defineProperty(Readable.prototype, "destroyed", { + get: function() { + if (this._readableState === void 0) return false; + return this._readableState.destroyed; + }, + set: function(value) { + if (!this._readableState) return; + this._readableState.destroyed = value; + } + }); + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function(err, cb) { + this.push(null); + cb(err); + }; + Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === "string") { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ""; + } + skipChunkCheck = true; + } + } else skipChunkCheck = true; + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; + Readable.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) stream.emit("error", er); + else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) chunk = _uint8ArrayToBuffer(chunk); + if (addToFront) if (state.endEmitted) stream.emit("error", /* @__PURE__ */ new Error("stream.unshift() after end event")); + else addChunk(stream, state, chunk, true); + else if (state.ended) stream.emit("error", /* @__PURE__ */ new Error("stream.push() after EOF")); + else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false); + else maybeReadMore(stream, state); + } else addChunk(stream, state, chunk, false); + } + } else if (!addToFront) state.reading = false; + } + return needMoreData(state); + } + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit("data", chunk); + stream.read(0); + } else { + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk); + else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); + } + function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) er = /* @__PURE__ */ new TypeError("Invalid non-string/buffer chunk"); + return er; + } + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + Readable.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) StringDecoder = __require("node:string_decoder").StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + var MAX_HWM = 8388608; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) n = MAX_HWM; + else { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) if (state.flowing && state.length) return state.buffer.head.data.length; + else return state.length; + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + Readable.prototype.read = function(n) { + debug("read", n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug("read: emitReadable", state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this); + else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + var doRead = state.needReadable; + debug("need readable", doRead); + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug("length less than watermark", doRead); + } + if (state.ended || state.reading) { + doRead = false; + debug("reading or ended", doRead); + } else if (doRead) { + debug("do read"); + state.reading = true; + state.sync = true; + if (state.length === 0) state.needReadable = true; + this._read(state.highWaterMark); + state.sync = false; + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state); + else ret = null; + if (ret === null) { + state.needReadable = true; + n = 0; + } else state.length -= n; + if (state.length === 0) { + if (!state.ended) state.needReadable = true; + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit("data", ret); + return ret; + }; + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + emitReadable(stream); + } + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug("emitReadable", state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream); + else emitReadable_(stream); + } + } + function emitReadable_(stream) { + debug("emit readable"); + stream.emit("readable"); + flow(stream); + } + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } + } + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug("maybeReadMore read 0"); + stream.read(0); + if (len === state.length) break; + else len = state.length; + } + state.readingMore = false; + } + Readable.prototype._read = function(n) { + this.emit("error", /* @__PURE__ */ new Error("_read() is not implemented")); + }; + Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts); + var endFn = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn); + else src.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable, unpipeInfo) { + debug("onunpipe"); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src.removeListener("end", onend); + src.removeListener("end", unpipe); + src.removeListener("data", ondata); + cleanedUp = true; + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + var increasedAwaitDrain = false; + src.on("data", ondata); + function ondata(chunk) { + debug("ondata"); + increasedAwaitDrain = false; + if (false === dest.write(chunk) && !increasedAwaitDrain) { + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug("false write response, pause", state.awaitDrain); + state.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + function onerror(er) { + debug("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) dest.emit("error", er); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug("unpipe"); + src.unpipe(dest); + } + dest.emit("pipe", src); + if (!state.flowing) { + debug("pipe resume"); + src.resume(); + } + return dest; + }; + function pipeOnDrain(src) { + return function() { + var state = src._readableState; + debug("pipeOnDrain", state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, "data")) { + state.flowing = true; + flow(src); + } + }; + } + Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + if (state.pipesCount === 0) return this; + if (state.pipesCount === 1) { + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit("unpipe", this, unpipeInfo); + return this; + } + if (!dest) { + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit("unpipe", this, { hasUnpiped: false }); + return this; + } + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + if (ev === "data") { + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === "readable") { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) pna.nextTick(nReadingNextTick, this); + else if (state.length) emitReadable(this); + } + } + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + function nReadingNextTick(self) { + debug("readable nexttick read 0"); + self.read(0); + } + Readable.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug("resume"); + state.flowing = true; + resume(this, state); + } + return this; + }; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } + } + function resume_(stream, state) { + if (!state.reading) { + debug("resume read 0"); + stream.read(0); + } + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit("resume"); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + Readable.prototype.pause = function() { + debug("call pause flowing=%j", this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + return this; + }; + function flow(stream) { + var state = stream._readableState; + debug("flow", state.flowing); + while (state.flowing && stream.read() !== null); + } + Readable.prototype.wrap = function(stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on("end", function() { + debug("wrapped end"); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on("data", function(chunk) { + debug("wrapped data"); + if (state.decoder) chunk = state.decoder.write(chunk); + if (state.objectMode && (chunk === null || chunk === void 0)) return; + else if (!state.objectMode && (!chunk || !chunk.length)) return; + if (!_this.push(chunk)) { + paused = true; + stream.pause(); + } + }); + for (var i in stream) if (this[i] === void 0 && typeof stream[i] === "function") this[i] = function(method) { + return function() { + return stream[method].apply(stream, arguments); + }; + }(i); + for (var n = 0; n < kProxyEvents.length; n++) stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + this._read = function(n) { + debug("wrapped _read", n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; + }; + Object.defineProperty(Readable.prototype, "readableHighWaterMark", { + enumerable: false, + get: function() { + return this._readableState.highWaterMark; + } + }); + Readable._fromList = fromList; + function fromList(n, state) { + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift(); + else if (!n || n >= state.length) { + if (state.decoder) ret = state.buffer.join(""); + else if (state.buffer.length === 1) ret = state.buffer.head.data; + else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else ret = fromListPartial(n, state.buffer, state.decoder); + return ret; + } + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) ret = list.shift(); + else ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + return ret; + } + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str; + else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next; + else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next; + else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + function endReadable(stream) { + var state = stream._readableState; + if (state.length > 0) throw new Error("\"endReadable()\" called on non-empty stream"); + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } + } + function endReadableNT(state, stream) { + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit("end"); + } + } + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) if (xs[i] === x) return i; + return -1; + } +})); +//#endregion +//#region node_modules/readable-stream/lib/_stream_transform.js +var require__stream_transform = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = Transform; + var Duplex = require__stream_duplex(); + var util = Object.create(require_util()); + util.inherits = require_inherits(); + util.inherits(Transform, Duplex); + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (!cb) return this.emit("error", /* @__PURE__ */ new Error("write callback called multiple times")); + ts.writechunk = null; + ts.writecb = null; + if (data != null) this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options) { + if (typeof options.transform === "function") this._transform = options.transform; + if (typeof options.flush === "function") this._flush = options.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function") this._flush(function(er, data) { + done(_this, er, data); + }); + else done(this, null, null); + } + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error("_transform() is not implemented"); + }; + Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + Transform.prototype._read = function(n) { + var ts = this._transformState; + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else ts.needTransform = true; + }; + Transform.prototype._destroy = function(err, cb) { + var _this2 = this; + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + _this2.emit("close"); + }); + }; + function done(stream, er, data) { + if (er) return stream.emit("error", er); + if (data != null) stream.push(data); + if (stream._writableState.length) throw new Error("Calling transform done when ws.length != 0"); + if (stream._transformState.transforming) throw new Error("Calling transform done when still transforming"); + return stream.push(null); + } +})); +//#endregion +//#region node_modules/readable-stream/lib/_stream_passthrough.js +var require__stream_passthrough = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = PassThrough; + var Transform = require__stream_transform(); + var util = Object.create(require_util()); + util.inherits = require_inherits(); + util.inherits(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); + } + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; +})); +//#endregion +//#region node_modules/readable-stream/readable.js +var require_readable = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var Stream = __require("stream"); + if (process.env.READABLE_STREAM === "disable" && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; + } else { + exports = module.exports = require__stream_readable(); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require__stream_writable(); + exports.Duplex = require__stream_duplex(); + exports.Transform = require__stream_transform(); + exports.PassThrough = require__stream_passthrough(); + } +})); +//#endregion +//#region node_modules/jszip/lib/support.js +var require_support = /* @__PURE__ */ __commonJSMin(((exports) => { + exports.base64 = true; + exports.array = true; + exports.string = true; + exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; + exports.nodebuffer = typeof Buffer !== "undefined"; + exports.uint8array = typeof Uint8Array !== "undefined"; + if (typeof ArrayBuffer === "undefined") exports.blob = false; + else { + var buffer = /* @__PURE__ */ new ArrayBuffer(0); + try { + exports.blob = new Blob([buffer], { type: "application/zip" }).size === 0; + } catch (e) { + try { + var builder = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)(); + builder.append(buffer); + exports.blob = builder.getBlob("application/zip").size === 0; + } catch (e) { + exports.blob = false; + } + } + } + try { + exports.nodestream = !!require_readable().Readable; + } catch (e) { + exports.nodestream = false; + } +})); +//#endregion +//#region node_modules/jszip/lib/base64.js +var require_base64 = /* @__PURE__ */ __commonJSMin(((exports) => { + var utils = require_utils(); + var support = require_support(); + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + exports.encode = function(input) { + var output = []; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0, len = input.length, remainingBytes = len; + var isArray = utils.getTypeOf(input) !== "string"; + while (i < input.length) { + remainingBytes = len - i; + if (!isArray) { + chr1 = input.charCodeAt(i++); + chr2 = i < len ? input.charCodeAt(i++) : 0; + chr3 = i < len ? input.charCodeAt(i++) : 0; + } else { + chr1 = input[i++]; + chr2 = i < len ? input[i++] : 0; + chr3 = i < len ? input[i++] : 0; + } + enc1 = chr1 >> 2; + enc2 = (chr1 & 3) << 4 | chr2 >> 4; + enc3 = remainingBytes > 1 ? (chr2 & 15) << 2 | chr3 >> 6 : 64; + enc4 = remainingBytes > 2 ? chr3 & 63 : 64; + output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); + } + return output.join(""); + }; + exports.decode = function(input) { + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0, resultIndex = 0; + var dataUrlPrefix = "data:"; + if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) throw new Error("Invalid base64 input, it looks like a data url."); + input = input.replace(/[^A-Za-z0-9+/=]/g, ""); + var totalLength = input.length * 3 / 4; + if (input.charAt(input.length - 1) === _keyStr.charAt(64)) totalLength--; + if (input.charAt(input.length - 2) === _keyStr.charAt(64)) totalLength--; + if (totalLength % 1 !== 0) throw new Error("Invalid base64 input, bad content length."); + var output; + if (support.uint8array) output = new Uint8Array(totalLength | 0); + else output = new Array(totalLength | 0); + while (i < input.length) { + enc1 = _keyStr.indexOf(input.charAt(i++)); + enc2 = _keyStr.indexOf(input.charAt(i++)); + enc3 = _keyStr.indexOf(input.charAt(i++)); + enc4 = _keyStr.indexOf(input.charAt(i++)); + chr1 = enc1 << 2 | enc2 >> 4; + chr2 = (enc2 & 15) << 4 | enc3 >> 2; + chr3 = (enc3 & 3) << 6 | enc4; + output[resultIndex++] = chr1; + if (enc3 !== 64) output[resultIndex++] = chr2; + if (enc4 !== 64) output[resultIndex++] = chr3; + } + return output; + }; +})); +//#endregion +//#region node_modules/jszip/lib/nodejsUtils.js +var require_nodejsUtils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + /** + * True if this is running in Nodejs, will be undefined in a browser. + * In a browser, browserify won't include this file and the whole module + * will be resolved an empty object. + */ + isNode: typeof Buffer !== "undefined", + /** + * Create a new nodejs Buffer from an existing content. + * @param {Object} data the data to pass to the constructor. + * @param {String} encoding the encoding to use. + * @return {Buffer} a new Buffer. + */ + newBufferFrom: function(data, encoding) { + if (Buffer.from && Buffer.from !== Uint8Array.from) return Buffer.from(data, encoding); + else { + if (typeof data === "number") throw new Error("The \"data\" argument must not be a number"); + return new Buffer(data, encoding); + } + }, + /** + * Create a new nodejs Buffer with the specified size. + * @param {Integer} size the size of the buffer. + * @return {Buffer} a new Buffer. + */ + allocBuffer: function(size) { + if (Buffer.alloc) return Buffer.alloc(size); + else { + var buf = new Buffer(size); + buf.fill(0); + return buf; + } + }, + /** + * Find out if an object is a Buffer. + * @param {Object} b the object to test. + * @return {Boolean} true if the object is a Buffer, false otherwise. + */ + isBuffer: function(b) { + return Buffer.isBuffer(b); + }, + isStream: function(obj) { + return obj && typeof obj.on === "function" && typeof obj.pause === "function" && typeof obj.resume === "function"; + } + }; +})); +//#endregion +//#region node_modules/lie/lib/index.js +var require_lib$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var immediate = require_lib$2(); + /* istanbul ignore next */ + function INTERNAL() {} + var handlers = {}; + var REJECTED = ["REJECTED"]; + var FULFILLED = ["FULFILLED"]; + var PENDING = ["PENDING"]; + /* istanbul ignore else */ + if (!process.browser) var UNHANDLED = ["UNHANDLED"]; + module.exports = Promise; + function Promise(resolver) { + if (typeof resolver !== "function") throw new TypeError("resolver must be a function"); + this.state = PENDING; + this.queue = []; + this.outcome = void 0; + /* istanbul ignore else */ + if (!process.browser) this.handled = UNHANDLED; + if (resolver !== INTERNAL) safelyResolveThenable(this, resolver); + } + Promise.prototype.finally = function(callback) { + if (typeof callback !== "function") return this; + var p = this.constructor; + return this.then(resolve, reject); + function resolve(value) { + function yes() { + return value; + } + return p.resolve(callback()).then(yes); + } + function reject(reason) { + function no() { + throw reason; + } + return p.resolve(callback()).then(no); + } + }; + Promise.prototype.catch = function(onRejected) { + return this.then(null, onRejected); + }; + Promise.prototype.then = function(onFulfilled, onRejected) { + if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) return this; + var promise = new this.constructor(INTERNAL); + /* istanbul ignore else */ + if (!process.browser) { + if (this.handled === UNHANDLED) this.handled = null; + } + if (this.state !== PENDING) unwrap(promise, this.state === FULFILLED ? onFulfilled : onRejected, this.outcome); + else this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + return promise; + }; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === "function") { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === "function") { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } + } + QueueItem.prototype.callFulfilled = function(value) { + handlers.resolve(this.promise, value); + }; + QueueItem.prototype.otherCallFulfilled = function(value) { + unwrap(this.promise, this.onFulfilled, value); + }; + QueueItem.prototype.callRejected = function(value) { + handlers.reject(this.promise, value); + }; + QueueItem.prototype.otherCallRejected = function(value) { + unwrap(this.promise, this.onRejected, value); + }; + function unwrap(promise, func, value) { + immediate(function() { + var returnValue; + try { + returnValue = func(value); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) handlers.reject(promise, /* @__PURE__ */ new TypeError("Cannot resolve promise with itself")); + else handlers.resolve(promise, returnValue); + }); + } + handlers.resolve = function(self, value) { + var result = tryCatch(getThen, value); + if (result.status === "error") return handlers.reject(self, result.value); + var thenable = result.value; + if (thenable) safelyResolveThenable(self, thenable); + else { + self.state = FULFILLED; + self.outcome = value; + var i = -1; + var len = self.queue.length; + while (++i < len) self.queue[i].callFulfilled(value); + } + return self; + }; + handlers.reject = function(self, error) { + self.state = REJECTED; + self.outcome = error; + /* istanbul ignore else */ + if (!process.browser) { + if (self.handled === UNHANDLED) immediate(function() { + if (self.handled === UNHANDLED) process.emit("unhandledRejection", error, self); + }); + } + var i = -1; + var len = self.queue.length; + while (++i < len) self.queue[i].callRejected(error); + return self; + }; + function getThen(obj) { + var then = obj && obj.then; + if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") return function appyThen() { + then.apply(obj, arguments); + }; + } + function safelyResolveThenable(self, thenable) { + var called = false; + function onError(value) { + if (called) return; + called = true; + handlers.reject(self, value); + } + function onSuccess(value) { + if (called) return; + called = true; + handlers.resolve(self, value); + } + function tryToUnwrap() { + thenable(onSuccess, onError); + } + var result = tryCatch(tryToUnwrap); + if (result.status === "error") onError(result.value); + } + function tryCatch(func, value) { + var out = {}; + try { + out.value = func(value); + out.status = "success"; + } catch (e) { + out.status = "error"; + out.value = e; + } + return out; + } + Promise.resolve = resolve; + function resolve(value) { + if (value instanceof this) return value; + return handlers.resolve(new this(INTERNAL), value); + } + Promise.reject = reject; + function reject(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + Promise.all = all; + function all(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") return this.reject(/* @__PURE__ */ new TypeError("must be an array")); + var len = iterable.length; + var called = false; + if (!len) return this.resolve([]); + var values = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) allResolver(iterable[i], i); + return promise; + function allResolver(value, i) { + self.resolve(value).then(resolveFromAll, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values[i] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values); + } + } + } + } + Promise.race = race; + function race(iterable) { + var self = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") return this.reject(/* @__PURE__ */ new TypeError("must be an array")); + var len = iterable.length; + var called = false; + if (!len) return this.resolve([]); + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) resolver(iterable[i]); + return promise; + function resolver(value) { + self.resolve(value).then(function(response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } + } +})); +//#endregion +//#region node_modules/jszip/lib/external.js +var require_external = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var ES6Promise = null; + if (typeof Promise !== "undefined") ES6Promise = Promise; + else ES6Promise = require_lib$1(); + /** + * Let the user use/change some implementations. + */ + module.exports = { Promise: ES6Promise }; +})); +//#endregion +//#region node_modules/setimmediate/setImmediate.js +var require_setImmediate = /* @__PURE__ */ __commonJSMin((() => { + (function(global, undefined) { + "use strict"; + if (global.setImmediate) return; + var nextHandle = 1; + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global.document; + var registerImmediate; + function setImmediate(callback) { + if (typeof callback !== "function") callback = new Function("" + callback); + var args = new Array(arguments.length - 1); + for (var i = 0; i < args.length; i++) args[i] = arguments[i + 1]; + tasksByHandle[nextHandle] = { + callback, + args + }; + registerImmediate(nextHandle); + return nextHandle++; + } + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined, args); + break; + } + } + function runIfPresent(handle) { + if (currentlyRunningATask) setTimeout(runIfPresent, 0, handle); + else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function() { + runIfPresent(handle); + }); + }; + } + function canUsePostMessage() { + if (global.postMessage && !global.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global.onmessage; + global.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global.postMessage("", "*"); + global.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + function installPostMessageImplementation() { + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) runIfPresent(+event.data.slice(messagePrefix.length)); + }; + if (global.addEventListener) global.addEventListener("message", onGlobalMessage, false); + else global.attachEvent("onmessage", onGlobalMessage); + registerImmediate = function(handle) { + global.postMessage(messagePrefix + handle, "*"); + }; + } + function installMessageChannelImplementation() { + var channel = new MessageChannel(); + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + var script = doc.createElement("script"); + script.onreadystatechange = function() { + runIfPresent(handle); + script.onreadystatechange = null; + html.removeChild(script); + script = null; + }; + html.appendChild(script); + }; + } + function installSetTimeoutImplementation() { + registerImmediate = function(handle) { + setTimeout(runIfPresent, 0, handle); + }; + } + var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); + attachTo = attachTo && attachTo.setTimeout ? attachTo : global; + if ({}.toString.call(global.process) === "[object process]") installNextTickImplementation(); + else if (canUsePostMessage()) installPostMessageImplementation(); + else if (global.MessageChannel) installMessageChannelImplementation(); + else if (doc && "onreadystatechange" in doc.createElement("script")) installReadyStateChangeImplementation(); + else installSetTimeoutImplementation(); + attachTo.setImmediate = setImmediate; + attachTo.clearImmediate = clearImmediate; + })(typeof self === "undefined" ? typeof global === "undefined" ? void 0 : global : self); +})); +//#endregion +//#region node_modules/jszip/lib/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => { + var support = require_support(); + var base64 = require_base64(); + var nodejsUtils = require_nodejsUtils(); + var external = require_external(); + require_setImmediate(); + /** + * Convert a string that pass as a "binary string": it should represent a byte + * array but may have > 255 char codes. Be sure to take only the first byte + * and returns the byte array. + * @param {String} str the string to transform. + * @return {Array|Uint8Array} the string in a binary format. + */ + function string2binary(str) { + var result = null; + if (support.uint8array) result = new Uint8Array(str.length); + else result = new Array(str.length); + return stringToArrayLike(str, result); + } + /** + * Create a new blob with the given content and the given type. + * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use + * an Uint8Array because the stock browser of android 4 won't accept it (it + * will be silently converted to a string, "[object Uint8Array]"). + * + * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge: + * when a large amount of Array is used to create the Blob, the amount of + * memory consumed is nearly 100 times the original data amount. + * + * @param {String} type the mime type of the blob. + * @return {Blob} the created blob. + */ + exports.newBlob = function(part, type) { + exports.checkSupport("blob"); + try { + return new Blob([part], { type }); + } catch (e) { + try { + var builder = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)(); + builder.append(part); + return builder.getBlob(type); + } catch (e) { + throw new Error("Bug : can't construct the Blob."); + } + } + }; + /** + * The identity function. + * @param {Object} input the input. + * @return {Object} the same input. + */ + function identity(input) { + return input; + } + /** + * Fill in an array with a string. + * @param {String} str the string to use. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). + * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. + */ + function stringToArrayLike(str, array) { + for (var i = 0; i < str.length; ++i) array[i] = str.charCodeAt(i) & 255; + return array; + } + /** + * An helper for the function arrayLikeToString. + * This contains static information and functions that + * can be optimized by the browser JIT compiler. + */ + var arrayToStringHelper = { + /** + * Transform an array of int into a string, chunk by chunk. + * See the performances notes on arrayLikeToString. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. + * @param {String} type the type of the array. + * @param {Integer} chunk the chunk size. + * @return {String} the resulting string. + * @throws Error if the chunk is too big for the stack. + */ + stringifyByChunk: function(array, type, chunk) { + var result = [], k = 0, len = array.length; + if (len <= chunk) return String.fromCharCode.apply(null, array); + while (k < len) { + if (type === "array" || type === "nodebuffer") result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); + else result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); + k += chunk; + } + return result.join(""); + }, + /** + * Call String.fromCharCode on every item in the array. + * This is the naive implementation, which generate A LOT of intermediate string. + * This should be used when everything else fail. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. + * @return {String} the result. + */ + stringifyByChar: function(array) { + var resultStr = ""; + for (var i = 0; i < array.length; i++) resultStr += String.fromCharCode(array[i]); + return resultStr; + }, + applyCanBeUsed: { + /** + * true if the browser accepts to use String.fromCharCode on Uint8Array + */ + uint8array: (function() { + try { + return support.uint8array && String.fromCharCode.apply(null, /* @__PURE__ */ new Uint8Array(1)).length === 1; + } catch (e) { + return false; + } + })(), + /** + * true if the browser accepts to use String.fromCharCode on nodejs Buffer. + */ + nodebuffer: (function() { + try { + return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1; + } catch (e) { + return false; + } + })() + } + }; + /** + * Transform an array-like object to a string. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. + * @return {String} the result. + */ + function arrayLikeToString(array) { + var chunk = 65536, type = exports.getTypeOf(array), canUseApply = true; + if (type === "uint8array") canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array; + else if (type === "nodebuffer") canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer; + if (canUseApply) while (chunk > 1) try { + return arrayToStringHelper.stringifyByChunk(array, type, chunk); + } catch (e) { + chunk = Math.floor(chunk / 2); + } + return arrayToStringHelper.stringifyByChar(array); + } + exports.applyFromCharCode = arrayLikeToString; + /** + * Copy the data from an array-like to an other array-like. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. + * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. + */ + function arrayLikeToArrayLike(arrayFrom, arrayTo) { + for (var i = 0; i < arrayFrom.length; i++) arrayTo[i] = arrayFrom[i]; + return arrayTo; + } + var transform = {}; + transform["string"] = { + "string": identity, + "array": function(input) { + return stringToArrayLike(input, new Array(input.length)); + }, + "arraybuffer": function(input) { + return transform["string"]["uint8array"](input).buffer; + }, + "uint8array": function(input) { + return stringToArrayLike(input, new Uint8Array(input.length)); + }, + "nodebuffer": function(input) { + return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); + } + }; + transform["array"] = { + "string": arrayLikeToString, + "array": identity, + "arraybuffer": function(input) { + return new Uint8Array(input).buffer; + }, + "uint8array": function(input) { + return new Uint8Array(input); + }, + "nodebuffer": function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform["arraybuffer"] = { + "string": function(input) { + return arrayLikeToString(new Uint8Array(input)); + }, + "array": function(input) { + return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); + }, + "arraybuffer": identity, + "uint8array": function(input) { + return new Uint8Array(input); + }, + "nodebuffer": function(input) { + return nodejsUtils.newBufferFrom(new Uint8Array(input)); + } + }; + transform["uint8array"] = { + "string": arrayLikeToString, + "array": function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + "arraybuffer": function(input) { + return input.buffer; + }, + "uint8array": identity, + "nodebuffer": function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform["nodebuffer"] = { + "string": arrayLikeToString, + "array": function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + "arraybuffer": function(input) { + return transform["nodebuffer"]["uint8array"](input).buffer; + }, + "uint8array": function(input) { + return arrayLikeToArrayLike(input, new Uint8Array(input.length)); + }, + "nodebuffer": identity + }; + /** + * Transform an input into any type. + * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. + * If no output type is specified, the unmodified input will be returned. + * @param {String} outputType the output type. + * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. + * @throws {Error} an Error if the browser doesn't support the requested output type. + */ + exports.transformTo = function(outputType, input) { + if (!input) input = ""; + if (!outputType) return input; + exports.checkSupport(outputType); + return transform[exports.getTypeOf(input)][outputType](input); + }; + /** + * Resolve all relative path components, "." and "..", in a path. If these relative components + * traverse above the root then the resulting path will only contain the final path component. + * + * All empty components, e.g. "//", are removed. + * @param {string} path A path with / or \ separators + * @returns {string} The path with all relative path components resolved. + */ + exports.resolve = function(path) { + var parts = path.split("/"); + var result = []; + for (var index = 0; index < parts.length; index++) { + var part = parts[index]; + if (part === "." || part === "" && index !== 0 && index !== parts.length - 1) continue; + else if (part === "..") result.pop(); + else result.push(part); + } + return result.join("/"); + }; + /** + * Return the type of the input. + * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. + * @param {Object} input the input to identify. + * @return {String} the (lowercase) type of the input. + */ + exports.getTypeOf = function(input) { + if (typeof input === "string") return "string"; + if (Object.prototype.toString.call(input) === "[object Array]") return "array"; + if (support.nodebuffer && nodejsUtils.isBuffer(input)) return "nodebuffer"; + if (support.uint8array && input instanceof Uint8Array) return "uint8array"; + if (support.arraybuffer && input instanceof ArrayBuffer) return "arraybuffer"; + }; + /** + * Throw an exception if the type is not supported. + * @param {String} type the type to check. + * @throws {Error} an Error if the browser doesn't support the requested type. + */ + exports.checkSupport = function(type) { + if (!support[type.toLowerCase()]) throw new Error(type + " is not supported by this platform"); + }; + exports.MAX_VALUE_16BITS = 65535; + exports.MAX_VALUE_32BITS = -1; + /** + * Prettify a string read as binary. + * @param {string} str the string to prettify. + * @return {string} a pretty string. + */ + exports.pretty = function(str) { + var res = "", code, i; + for (i = 0; i < (str || "").length; i++) { + code = str.charCodeAt(i); + res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); + } + return res; + }; + /** + * Defer the call of a function. + * @param {Function} callback the function to call asynchronously. + * @param {Array} args the arguments to give to the callback. + */ + exports.delay = function(callback, args, self) { + setImmediate(function() { + callback.apply(self || null, args || []); + }); + }; + /** + * Extends a prototype with an other, without calling a constructor with + * side effects. Inspired by nodejs' `utils.inherits` + * @param {Function} ctor the constructor to augment + * @param {Function} superCtor the parent constructor to use + */ + exports.inherits = function(ctor, superCtor) { + var Obj = function() {}; + Obj.prototype = superCtor.prototype; + ctor.prototype = new Obj(); + }; + /** + * Merge the objects passed as parameters into a new one. + * @private + * @param {...Object} var_args All objects to merge. + * @return {Object} a new object with the data of the others. + */ + exports.extend = function() { + var result = {}, i, attr; + for (i = 0; i < arguments.length; i++) for (attr in arguments[i]) if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") result[attr] = arguments[i][attr]; + return result; + }; + /** + * Transform arbitrary content into a Promise. + * @param {String} name a name for the content being processed. + * @param {Object} inputData the content to process. + * @param {Boolean} isBinary true if the content is not an unicode string + * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character. + * @param {Boolean} isBase64 true if the string content is encoded with base64. + * @return {Promise} a promise in a format usable by JSZip. + */ + exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) { + return external.Promise.resolve(inputData).then(function(data) { + if (support.blob && (data instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data)) !== -1) && typeof FileReader !== "undefined") return new external.Promise(function(resolve, reject) { + var reader = new FileReader(); + reader.onload = function(e) { + resolve(e.target.result); + }; + reader.onerror = function(e) { + reject(e.target.error); + }; + reader.readAsArrayBuffer(data); + }); + else return data; + }).then(function(data) { + var dataType = exports.getTypeOf(data); + if (!dataType) return external.Promise.reject(/* @__PURE__ */ new Error("Can't read the data of '" + name + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")); + if (dataType === "arraybuffer") data = exports.transformTo("uint8array", data); + else if (dataType === "string") { + if (isBase64) data = base64.decode(data); + else if (isBinary) { + if (isOptimizedBinaryString !== true) data = string2binary(data); + } + } + return data; + }); + }; +})); +//#endregion +//#region node_modules/jszip/lib/stream/GenericWorker.js +var require_GenericWorker = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** + * A worker that does nothing but passing chunks to the next one. This is like + * a nodejs stream but with some differences. On the good side : + * - it works on IE 6-9 without any issue / polyfill + * - it weights less than the full dependencies bundled with browserify + * - it forwards errors (no need to declare an error handler EVERYWHERE) + * + * A chunk is an object with 2 attributes : `meta` and `data`. The former is an + * object containing anything (`percent` for example), see each worker for more + * details. The latter is the real data (String, Uint8Array, etc). + * + * @constructor + * @param {String} name the name of the stream (mainly used for debugging purposes) + */ + function GenericWorker(name) { + this.name = name || "default"; + this.streamInfo = {}; + this.generatedError = null; + this.extraStreamInfo = {}; + this.isPaused = true; + this.isFinished = false; + this.isLocked = false; + this._listeners = { + "data": [], + "end": [], + "error": [] + }; + this.previous = null; + } + GenericWorker.prototype = { + /** + * Push a chunk to the next workers. + * @param {Object} chunk the chunk to push + */ + push: function(chunk) { + this.emit("data", chunk); + }, + /** + * End the stream. + * @return {Boolean} true if this call ended the worker, false otherwise. + */ + end: function() { + if (this.isFinished) return false; + this.flush(); + try { + this.emit("end"); + this.cleanUp(); + this.isFinished = true; + } catch (e) { + this.emit("error", e); + } + return true; + }, + /** + * End the stream with an error. + * @param {Error} e the error which caused the premature end. + * @return {Boolean} true if this call ended the worker with an error, false otherwise. + */ + error: function(e) { + if (this.isFinished) return false; + if (this.isPaused) this.generatedError = e; + else { + this.isFinished = true; + this.emit("error", e); + if (this.previous) this.previous.error(e); + this.cleanUp(); + } + return true; + }, + /** + * Add a callback on an event. + * @param {String} name the name of the event (data, end, error) + * @param {Function} listener the function to call when the event is triggered + * @return {GenericWorker} the current object for chainability + */ + on: function(name, listener) { + this._listeners[name].push(listener); + return this; + }, + /** + * Clean any references when a worker is ending. + */ + cleanUp: function() { + this.streamInfo = this.generatedError = this.extraStreamInfo = null; + this._listeners = []; + }, + /** + * Trigger an event. This will call registered callback with the provided arg. + * @param {String} name the name of the event (data, end, error) + * @param {Object} arg the argument to call the callback with. + */ + emit: function(name, arg) { + if (this._listeners[name]) for (var i = 0; i < this._listeners[name].length; i++) this._listeners[name][i].call(this, arg); + }, + /** + * Chain a worker with an other. + * @param {Worker} next the worker receiving events from the current one. + * @return {worker} the next worker for chainability + */ + pipe: function(next) { + return next.registerPrevious(this); + }, + /** + * Same as `pipe` in the other direction. + * Using an API with `pipe(next)` is very easy. + * Implementing the API with the point of view of the next one registering + * a source is easier, see the ZipFileWorker. + * @param {Worker} previous the previous worker, sending events to this one + * @return {Worker} the current worker for chainability + */ + registerPrevious: function(previous) { + if (this.isLocked) throw new Error("The stream '" + this + "' has already been used."); + this.streamInfo = previous.streamInfo; + this.mergeStreamInfo(); + this.previous = previous; + var self = this; + previous.on("data", function(chunk) { + self.processChunk(chunk); + }); + previous.on("end", function() { + self.end(); + }); + previous.on("error", function(e) { + self.error(e); + }); + return this; + }, + /** + * Pause the stream so it doesn't send events anymore. + * @return {Boolean} true if this call paused the worker, false otherwise. + */ + pause: function() { + if (this.isPaused || this.isFinished) return false; + this.isPaused = true; + if (this.previous) this.previous.pause(); + return true; + }, + /** + * Resume a paused stream. + * @return {Boolean} true if this call resumed the worker, false otherwise. + */ + resume: function() { + if (!this.isPaused || this.isFinished) return false; + this.isPaused = false; + var withError = false; + if (this.generatedError) { + this.error(this.generatedError); + withError = true; + } + if (this.previous) this.previous.resume(); + return !withError; + }, + /** + * Flush any remaining bytes as the stream is ending. + */ + flush: function() {}, + /** + * Process a chunk. This is usually the method overridden. + * @param {Object} chunk the chunk to process. + */ + processChunk: function(chunk) { + this.push(chunk); + }, + /** + * Add a key/value to be added in the workers chain streamInfo once activated. + * @param {String} key the key to use + * @param {Object} value the associated value + * @return {Worker} the current worker for chainability + */ + withStreamInfo: function(key, value) { + this.extraStreamInfo[key] = value; + this.mergeStreamInfo(); + return this; + }, + /** + * Merge this worker's streamInfo into the chain's streamInfo. + */ + mergeStreamInfo: function() { + for (var key in this.extraStreamInfo) { + if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key)) continue; + this.streamInfo[key] = this.extraStreamInfo[key]; + } + }, + /** + * Lock the stream to prevent further updates on the workers chain. + * After calling this method, all calls to pipe will fail. + */ + lock: function() { + if (this.isLocked) throw new Error("The stream '" + this + "' has already been used."); + this.isLocked = true; + if (this.previous) this.previous.lock(); + }, + /** + * + * Pretty print the workers chain. + */ + toString: function() { + var me = "Worker " + this.name; + if (this.previous) return this.previous + " -> " + me; + else return me; + } + }; + module.exports = GenericWorker; +})); +//#endregion +//#region node_modules/jszip/lib/utf8.js +var require_utf8 = /* @__PURE__ */ __commonJSMin(((exports) => { + var utils = require_utils(); + var support = require_support(); + var nodejsUtils = require_nodejsUtils(); + var GenericWorker = require_GenericWorker(); + /** + * The following functions come from pako, from pako/lib/utils/strings + * released under the MIT license, see pako https://github.com/nodeca/pako/ + */ + var _utf8len = new Array(256); + for (var i = 0; i < 256; i++) _utf8len[i] = i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1; + _utf8len[254] = _utf8len[254] = 1; + var string2buf = function(str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + if (support.uint8array) buf = new Uint8Array(buf_len); + else buf = new Array(buf_len); + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) buf[i++] = c; + else if (c < 2048) { + buf[i++] = 192 | c >>> 6; + buf[i++] = 128 | c & 63; + } else if (c < 65536) { + buf[i++] = 224 | c >>> 12; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } else { + buf[i++] = 240 | c >>> 18; + buf[i++] = 128 | c >>> 12 & 63; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } + } + return buf; + }; + var utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) max = buf.length; + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) pos--; + if (pos < 0) return max; + if (pos === 0) return max; + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; + var buf2string = function(buf) { + var i, out, c, c_len; + var len = buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i < len) { + c = c << 6 | buf[i++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) utf16buf[out++] = c; + else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + if (utf16buf.length !== out) if (utf16buf.subarray) utf16buf = utf16buf.subarray(0, out); + else utf16buf.length = out; + return utils.applyFromCharCode(utf16buf); + }; + /** + * Transform a javascript string into an array (typed if possible) of bytes, + * UTF-8 encoded. + * @param {String} str the string to encode + * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string. + */ + exports.utf8encode = function utf8encode(str) { + if (support.nodebuffer) return nodejsUtils.newBufferFrom(str, "utf-8"); + return string2buf(str); + }; + /** + * Transform a bytes array (or a representation) representing an UTF-8 encoded + * string into a javascript string. + * @param {Array|Uint8Array|Buffer} buf the data de decode + * @return {String} the decoded string. + */ + exports.utf8decode = function utf8decode(buf) { + if (support.nodebuffer) return utils.transformTo("nodebuffer", buf).toString("utf-8"); + buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); + return buf2string(buf); + }; + /** + * A worker to decode utf8 encoded binary chunks into string chunks. + * @constructor + */ + function Utf8DecodeWorker() { + GenericWorker.call(this, "utf-8 decode"); + this.leftOver = null; + } + utils.inherits(Utf8DecodeWorker, GenericWorker); + /** + * @see GenericWorker.processChunk + */ + Utf8DecodeWorker.prototype.processChunk = function(chunk) { + var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data); + if (this.leftOver && this.leftOver.length) { + if (support.uint8array) { + var previousData = data; + data = new Uint8Array(previousData.length + this.leftOver.length); + data.set(this.leftOver, 0); + data.set(previousData, this.leftOver.length); + } else data = this.leftOver.concat(data); + this.leftOver = null; + } + var nextBoundary = utf8border(data); + var usableData = data; + if (nextBoundary !== data.length) if (support.uint8array) { + usableData = data.subarray(0, nextBoundary); + this.leftOver = data.subarray(nextBoundary, data.length); + } else { + usableData = data.slice(0, nextBoundary); + this.leftOver = data.slice(nextBoundary, data.length); + } + this.push({ + data: exports.utf8decode(usableData), + meta: chunk.meta + }); + }; + /** + * @see GenericWorker.flush + */ + Utf8DecodeWorker.prototype.flush = function() { + if (this.leftOver && this.leftOver.length) { + this.push({ + data: exports.utf8decode(this.leftOver), + meta: {} + }); + this.leftOver = null; + } + }; + exports.Utf8DecodeWorker = Utf8DecodeWorker; + /** + * A worker to endcode string chunks into utf8 encoded binary chunks. + * @constructor + */ + function Utf8EncodeWorker() { + GenericWorker.call(this, "utf-8 encode"); + } + utils.inherits(Utf8EncodeWorker, GenericWorker); + /** + * @see GenericWorker.processChunk + */ + Utf8EncodeWorker.prototype.processChunk = function(chunk) { + this.push({ + data: exports.utf8encode(chunk.data), + meta: chunk.meta + }); + }; + exports.Utf8EncodeWorker = Utf8EncodeWorker; +})); +//#endregion +//#region node_modules/jszip/lib/stream/ConvertWorker.js +var require_ConvertWorker = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var GenericWorker = require_GenericWorker(); + var utils = require_utils(); + /** + * A worker which convert chunks to a specified type. + * @constructor + * @param {String} destType the destination type. + */ + function ConvertWorker(destType) { + GenericWorker.call(this, "ConvertWorker to " + destType); + this.destType = destType; + } + utils.inherits(ConvertWorker, GenericWorker); + /** + * @see GenericWorker.processChunk + */ + ConvertWorker.prototype.processChunk = function(chunk) { + this.push({ + data: utils.transformTo(this.destType, chunk.data), + meta: chunk.meta + }); + }; + module.exports = ConvertWorker; +})); +//#endregion +//#region node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js +var require_NodejsStreamOutputAdapter = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var Readable = require_readable().Readable; + require_utils().inherits(NodejsStreamOutputAdapter, Readable); + /** + * A nodejs stream using a worker as source. + * @see the SourceWrapper in http://nodejs.org/api/stream.html + * @constructor + * @param {StreamHelper} helper the helper wrapping the worker + * @param {Object} options the nodejs stream options + * @param {Function} updateCb the update callback. + */ + function NodejsStreamOutputAdapter(helper, options, updateCb) { + Readable.call(this, options); + this._helper = helper; + var self = this; + helper.on("data", function(data, meta) { + if (!self.push(data)) self._helper.pause(); + if (updateCb) updateCb(meta); + }).on("error", function(e) { + self.emit("error", e); + }).on("end", function() { + self.push(null); + }); + } + NodejsStreamOutputAdapter.prototype._read = function() { + this._helper.resume(); + }; + module.exports = NodejsStreamOutputAdapter; +})); +//#endregion +//#region node_modules/jszip/lib/stream/StreamHelper.js +var require_StreamHelper = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + var ConvertWorker = require_ConvertWorker(); + var GenericWorker = require_GenericWorker(); + var base64 = require_base64(); + var support = require_support(); + var external = require_external(); + var NodejsStreamOutputAdapter = null; + if (support.nodestream) try { + NodejsStreamOutputAdapter = require_NodejsStreamOutputAdapter(); + } catch (e) {} + /** + * Apply the final transformation of the data. If the user wants a Blob for + * example, it's easier to work with an U8intArray and finally do the + * ArrayBuffer/Blob conversion. + * @param {String} type the name of the final type + * @param {String|Uint8Array|Buffer} content the content to transform + * @param {String} mimeType the mime type of the content, if applicable. + * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format. + */ + function transformZipOutput(type, content, mimeType) { + switch (type) { + case "blob": return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType); + case "base64": return base64.encode(content); + default: return utils.transformTo(type, content); + } + } + /** + * Concatenate an array of data of the given type. + * @param {String} type the type of the data in the given array. + * @param {Array} dataArray the array containing the data chunks to concatenate + * @return {String|Uint8Array|Buffer} the concatenated data + * @throws Error if the asked type is unsupported + */ + function concat(type, dataArray) { + var i, index = 0, res = null, totalLength = 0; + for (i = 0; i < dataArray.length; i++) totalLength += dataArray[i].length; + switch (type) { + case "string": return dataArray.join(""); + case "array": return Array.prototype.concat.apply([], dataArray); + case "uint8array": + res = new Uint8Array(totalLength); + for (i = 0; i < dataArray.length; i++) { + res.set(dataArray[i], index); + index += dataArray[i].length; + } + return res; + case "nodebuffer": return Buffer.concat(dataArray); + default: throw new Error("concat : unsupported type '" + type + "'"); + } + } + /** + * Listen a StreamHelper, accumulate its content and concatenate it into a + * complete block. + * @param {StreamHelper} helper the helper to use. + * @param {Function} updateCallback a callback called on each update. Called + * with one arg : + * - the metadata linked to the update received. + * @return Promise the promise for the accumulation. + */ + function accumulate(helper, updateCallback) { + return new external.Promise(function(resolve, reject) { + var dataArray = []; + var chunkType = helper._internalType, resultType = helper._outputType, mimeType = helper._mimeType; + helper.on("data", function(data, meta) { + dataArray.push(data); + if (updateCallback) updateCallback(meta); + }).on("error", function(err) { + dataArray = []; + reject(err); + }).on("end", function() { + try { + resolve(transformZipOutput(resultType, concat(chunkType, dataArray), mimeType)); + } catch (e) { + reject(e); + } + dataArray = []; + }).resume(); + }); + } + /** + * An helper to easily use workers outside of JSZip. + * @constructor + * @param {Worker} worker the worker to wrap + * @param {String} outputType the type of data expected by the use + * @param {String} mimeType the mime type of the content, if applicable. + */ + function StreamHelper(worker, outputType, mimeType) { + var internalType = outputType; + switch (outputType) { + case "blob": + case "arraybuffer": + internalType = "uint8array"; + break; + case "base64": + internalType = "string"; + break; + } + try { + this._internalType = internalType; + this._outputType = outputType; + this._mimeType = mimeType; + utils.checkSupport(internalType); + this._worker = worker.pipe(new ConvertWorker(internalType)); + worker.lock(); + } catch (e) { + this._worker = new GenericWorker("error"); + this._worker.error(e); + } + } + StreamHelper.prototype = { + /** + * Listen a StreamHelper, accumulate its content and concatenate it into a + * complete block. + * @param {Function} updateCb the update callback. + * @return Promise the promise for the accumulation. + */ + accumulate: function(updateCb) { + return accumulate(this, updateCb); + }, + /** + * Add a listener on an event triggered on a stream. + * @param {String} evt the name of the event + * @param {Function} fn the listener + * @return {StreamHelper} the current helper. + */ + on: function(evt, fn) { + var self = this; + if (evt === "data") this._worker.on(evt, function(chunk) { + fn.call(self, chunk.data, chunk.meta); + }); + else this._worker.on(evt, function() { + utils.delay(fn, arguments, self); + }); + return this; + }, + /** + * Resume the flow of chunks. + * @return {StreamHelper} the current helper. + */ + resume: function() { + utils.delay(this._worker.resume, [], this._worker); + return this; + }, + /** + * Pause the flow of chunks. + * @return {StreamHelper} the current helper. + */ + pause: function() { + this._worker.pause(); + return this; + }, + /** + * Return a nodejs stream for this helper. + * @param {Function} updateCb the update callback. + * @return {NodejsStreamOutputAdapter} the nodejs stream. + */ + toNodejsStream: function(updateCb) { + utils.checkSupport("nodestream"); + if (this._outputType !== "nodebuffer") throw new Error(this._outputType + " is not supported by this method"); + return new NodejsStreamOutputAdapter(this, { objectMode: this._outputType !== "nodebuffer" }, updateCb); + } + }; + module.exports = StreamHelper; +})); +//#endregion +//#region node_modules/jszip/lib/defaults.js +var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { + exports.base64 = false; + exports.binary = false; + exports.dir = false; + exports.createFolders = true; + exports.date = null; + exports.compression = null; + exports.compressionOptions = null; + exports.comment = null; + exports.unixPermissions = null; + exports.dosPermissions = null; +})); +//#endregion +//#region node_modules/jszip/lib/stream/DataWorker.js +var require_DataWorker = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var DEFAULT_BLOCK_SIZE = 16 * 1024; + /** + * A worker that reads a content and emits chunks. + * @constructor + * @param {Promise} dataP the promise of the data to split + */ + function DataWorker(dataP) { + GenericWorker.call(this, "DataWorker"); + var self = this; + this.dataIsReady = false; + this.index = 0; + this.max = 0; + this.data = null; + this.type = ""; + this._tickScheduled = false; + dataP.then(function(data) { + self.dataIsReady = true; + self.data = data; + self.max = data && data.length || 0; + self.type = utils.getTypeOf(data); + if (!self.isPaused) self._tickAndRepeat(); + }, function(e) { + self.error(e); + }); + } + utils.inherits(DataWorker, GenericWorker); + /** + * @see GenericWorker.cleanUp + */ + DataWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this.data = null; + }; + /** + * @see GenericWorker.resume + */ + DataWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) return false; + if (!this._tickScheduled && this.dataIsReady) { + this._tickScheduled = true; + utils.delay(this._tickAndRepeat, [], this); + } + return true; + }; + /** + * Trigger a tick a schedule an other call to this function. + */ + DataWorker.prototype._tickAndRepeat = function() { + this._tickScheduled = false; + if (this.isPaused || this.isFinished) return; + this._tick(); + if (!this.isFinished) { + utils.delay(this._tickAndRepeat, [], this); + this._tickScheduled = true; + } + }; + /** + * Read and push a chunk. + */ + DataWorker.prototype._tick = function() { + if (this.isPaused || this.isFinished) return false; + var size = DEFAULT_BLOCK_SIZE; + var data = null, nextIndex = Math.min(this.max, this.index + size); + if (this.index >= this.max) return this.end(); + else { + switch (this.type) { + case "string": + data = this.data.substring(this.index, nextIndex); + break; + case "uint8array": + data = this.data.subarray(this.index, nextIndex); + break; + case "array": + case "nodebuffer": + data = this.data.slice(this.index, nextIndex); + break; + } + this.index = nextIndex; + return this.push({ + data, + meta: { percent: this.max ? this.index / this.max * 100 : 0 } + }); + } + }; + module.exports = DataWorker; +})); +//#endregion +//#region node_modules/jszip/lib/crc32.js +var require_crc32$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + /** + * The following functions come from pako, from pako/lib/zlib/crc32.js + * released under the MIT license, see pako https://github.com/nodeca/pako/ + */ + function makeTable() { + var c, table = []; + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos; i < end; i++) crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + return crc ^ -1; + } + /** + * Compute the crc32 of a string. + * This is almost the same as the function crc32, but for strings. Using the + * same function for the two use cases leads to horrible performances. + * @param {Number} crc the starting value of the crc. + * @param {String} str the string to use. + * @param {Number} len the length of the string. + * @param {Number} pos the starting position for the crc32 computation. + * @return {Number} the computed crc32. + */ + function crc32str(crc, str, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos; i < end; i++) crc = crc >>> 8 ^ t[(crc ^ str.charCodeAt(i)) & 255]; + return crc ^ -1; + } + module.exports = function crc32wrapper(input, crc) { + if (typeof input === "undefined" || !input.length) return 0; + if (utils.getTypeOf(input) !== "string") return crc32(crc | 0, input, input.length, 0); + else return crc32str(crc | 0, input, input.length, 0); + }; +})); +//#endregion +//#region node_modules/jszip/lib/stream/Crc32Probe.js +var require_Crc32Probe = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var GenericWorker = require_GenericWorker(); + var crc32 = require_crc32$1(); + var utils = require_utils(); + /** + * A worker which calculate the crc32 of the data flowing through. + * @constructor + */ + function Crc32Probe() { + GenericWorker.call(this, "Crc32Probe"); + this.withStreamInfo("crc32", 0); + } + utils.inherits(Crc32Probe, GenericWorker); + /** + * @see GenericWorker.processChunk + */ + Crc32Probe.prototype.processChunk = function(chunk) { + this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0); + this.push(chunk); + }; + module.exports = Crc32Probe; +})); +//#endregion +//#region node_modules/jszip/lib/stream/DataLengthProbe.js +var require_DataLengthProbe = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + /** + * A worker which calculate the total length of the data flowing through. + * @constructor + * @param {String} propName the name used to expose the length + */ + function DataLengthProbe(propName) { + GenericWorker.call(this, "DataLengthProbe for " + propName); + this.propName = propName; + this.withStreamInfo(propName, 0); + } + utils.inherits(DataLengthProbe, GenericWorker); + /** + * @see GenericWorker.processChunk + */ + DataLengthProbe.prototype.processChunk = function(chunk) { + if (chunk) { + var length = this.streamInfo[this.propName] || 0; + this.streamInfo[this.propName] = length + chunk.data.length; + } + GenericWorker.prototype.processChunk.call(this, chunk); + }; + module.exports = DataLengthProbe; +})); +//#endregion +//#region node_modules/jszip/lib/compressedObject.js +var require_compressedObject = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var external = require_external(); + var DataWorker = require_DataWorker(); + var Crc32Probe = require_Crc32Probe(); + var DataLengthProbe = require_DataLengthProbe(); + /** + * Represent a compressed object, with everything needed to decompress it. + * @constructor + * @param {number} compressedSize the size of the data compressed. + * @param {number} uncompressedSize the size of the data after decompression. + * @param {number} crc32 the crc32 of the decompressed file. + * @param {object} compression the type of compression, see lib/compressions.js. + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data. + */ + function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) { + this.compressedSize = compressedSize; + this.uncompressedSize = uncompressedSize; + this.crc32 = crc32; + this.compression = compression; + this.compressedContent = data; + } + CompressedObject.prototype = { + /** + * Create a worker to get the uncompressed content. + * @return {GenericWorker} the worker. + */ + getContentWorker: function() { + var worker = new DataWorker(external.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new DataLengthProbe("data_length")); + var that = this; + worker.on("end", function() { + if (this.streamInfo["data_length"] !== that.uncompressedSize) throw new Error("Bug : uncompressed data size mismatch"); + }); + return worker; + }, + /** + * Create a worker to get the compressed content. + * @return {GenericWorker} the worker. + */ + getCompressedWorker: function() { + return new DataWorker(external.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression); + } + }; + /** + * Chain the given worker with other workers to compress the content with the + * given compression. + * @param {GenericWorker} uncompressedWorker the worker to pipe. + * @param {Object} compression the compression object. + * @param {Object} compressionOptions the options to use when compressing. + * @return {GenericWorker} the new worker compressing the content. + */ + CompressedObject.createWorkerFrom = function(uncompressedWorker, compression, compressionOptions) { + return uncompressedWorker.pipe(new Crc32Probe()).pipe(new DataLengthProbe("uncompressedSize")).pipe(compression.compressWorker(compressionOptions)).pipe(new DataLengthProbe("compressedSize")).withStreamInfo("compression", compression); + }; + module.exports = CompressedObject; +})); +//#endregion +//#region node_modules/jszip/lib/zipObject.js +var require_zipObject = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var StreamHelper = require_StreamHelper(); + var DataWorker = require_DataWorker(); + var utf8 = require_utf8(); + var CompressedObject = require_compressedObject(); + var GenericWorker = require_GenericWorker(); + /** + * A simple object representing a file in the zip file. + * @constructor + * @param {string} name the name of the file + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data + * @param {Object} options the options of the file + */ + var ZipObject = function(name, data, options) { + this.name = name; + this.dir = options.dir; + this.date = options.date; + this.comment = options.comment; + this.unixPermissions = options.unixPermissions; + this.dosPermissions = options.dosPermissions; + this._data = data; + this._dataBinary = options.binary; + this.options = { + compression: options.compression, + compressionOptions: options.compressionOptions + }; + }; + ZipObject.prototype = { + /** + * Create an internal stream for the content of this object. + * @param {String} type the type of each chunk. + * @return StreamHelper the stream. + */ + internalStream: function(type) { + var result = null, outputType = "string"; + try { + if (!type) throw new Error("No output type specified."); + outputType = type.toLowerCase(); + var askUnicodeString = outputType === "string" || outputType === "text"; + if (outputType === "binarystring" || outputType === "text") outputType = "string"; + result = this._decompressWorker(); + var isUnicodeString = !this._dataBinary; + if (isUnicodeString && !askUnicodeString) result = result.pipe(new utf8.Utf8EncodeWorker()); + if (!isUnicodeString && askUnicodeString) result = result.pipe(new utf8.Utf8DecodeWorker()); + } catch (e) { + result = new GenericWorker("error"); + result.error(e); + } + return new StreamHelper(result, outputType, ""); + }, + /** + * Prepare the content in the asked type. + * @param {String} type the type of the result. + * @param {Function} onUpdate a function to call on each internal update. + * @return Promise the promise of the result. + */ + async: function(type, onUpdate) { + return this.internalStream(type).accumulate(onUpdate); + }, + /** + * Prepare the content as a nodejs stream. + * @param {String} type the type of each chunk. + * @param {Function} onUpdate a function to call on each internal update. + * @return Stream the stream. + */ + nodeStream: function(type, onUpdate) { + return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate); + }, + /** + * Return a worker for the compressed content. + * @private + * @param {Object} compression the compression object to use. + * @param {Object} compressionOptions the options to use when compressing. + * @return Worker the worker. + */ + _compressWorker: function(compression, compressionOptions) { + if (this._data instanceof CompressedObject && this._data.compression.magic === compression.magic) return this._data.getCompressedWorker(); + else { + var result = this._decompressWorker(); + if (!this._dataBinary) result = result.pipe(new utf8.Utf8EncodeWorker()); + return CompressedObject.createWorkerFrom(result, compression, compressionOptions); + } + }, + /** + * Return a worker for the decompressed content. + * @private + * @return Worker the worker. + */ + _decompressWorker: function() { + if (this._data instanceof CompressedObject) return this._data.getContentWorker(); + else if (this._data instanceof GenericWorker) return this._data; + else return new DataWorker(this._data); + } + }; + var removedMethods = [ + "asText", + "asBinary", + "asNodeBuffer", + "asUint8Array", + "asArrayBuffer" + ]; + var removedFn = function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }; + for (var i = 0; i < removedMethods.length; i++) ZipObject.prototype[removedMethods[i]] = removedFn; + module.exports = ZipObject; +})); +//#endregion +//#region node_modules/pako/lib/utils/common.js +var require_common = /* @__PURE__ */ __commonJSMin(((exports) => { + var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined"; + function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + } + exports.assign = function(obj) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) continue; + if (typeof source !== "object") throw new TypeError(source + "must be non-object"); + for (var p in source) if (_has(source, p)) obj[p] = source[p]; + } + return obj; + }; + exports.shrinkBuf = function(buf, size) { + if (buf.length === size) return buf; + if (buf.subarray) return buf.subarray(0, size); + buf.length = size; + return buf; + }; + var fnTyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + for (var i = 0; i < len; i++) dest[dest_offs + i] = src[src_offs + i]; + }, + flattenChunks: function(chunks) { + var i, l, len = 0, pos, chunk, result; + for (i = 0, l = chunks.length; i < l; i++) len += chunks[i].length; + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + return result; + } + }; + var fnUntyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) dest[dest_offs + i] = src[src_offs + i]; + }, + flattenChunks: function(chunks) { + return [].concat.apply([], chunks); + } + }; + exports.setTyped = function(on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } + }; + exports.setTyped(TYPED_OK); +})); +//#endregion +//#region node_modules/pako/lib/zlib/trees.js +var require_trees = /* @__PURE__ */ __commonJSMin(((exports) => { + var utils = require_common(); + var Z_FIXED = 4; + var Z_BINARY = 0; + var Z_TEXT = 1; + var Z_UNKNOWN = 2; + function zero(buf) { + var len = buf.length; + while (--len >= 0) buf[len] = 0; + } + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var Buf_size = 16; + var MAX_BL_BITS = 7; + var END_BLOCK = 256; + var REP_3_6 = 16; + var REPZ_3_10 = 17; + var REPZ_11_138 = 18; + var extra_lbits = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 5, + 0 + ]; + var extra_dbits = [ + 0, + 0, + 0, + 0, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 7, + 8, + 8, + 9, + 9, + 10, + 10, + 11, + 11, + 12, + 12, + 13, + 13 + ]; + var extra_blbits = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 3, + 7 + ]; + var bl_order = [ + 16, + 17, + 18, + 0, + 8, + 7, + 9, + 6, + 10, + 5, + 11, + 4, + 12, + 3, + 13, + 2, + 14, + 1, + 15 + ]; + var DIST_CODE_LEN = 512; + var static_ltree = new Array((L_CODES + 2) * 2); + zero(static_ltree); + var static_dtree = new Array(D_CODES * 2); + zero(static_dtree); + var _dist_code = new Array(DIST_CODE_LEN); + zero(_dist_code); + var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); + zero(_length_code); + var base_length = new Array(LENGTH_CODES); + zero(base_length); + var base_dist = new Array(D_CODES); + zero(base_dist); + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + this.static_tree = static_tree; + this.extra_bits = extra_bits; + this.extra_base = extra_base; + this.elems = elems; + this.max_length = max_length; + this.has_stree = static_tree && static_tree.length; + } + var static_l_desc; + var static_d_desc; + var static_bl_desc; + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; + this.max_code = 0; + this.stat_desc = stat_desc; + } + function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; + } + function put_short(s, w) { + s.pending_buf[s.pending++] = w & 255; + s.pending_buf[s.pending++] = w >>> 8 & 255; + } + function send_bits(s, value, length) { + if (s.bi_valid > Buf_size - length) { + s.bi_buf |= value << s.bi_valid & 65535; + put_short(s, s.bi_buf); + s.bi_buf = value >> Buf_size - s.bi_valid; + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= value << s.bi_valid & 65535; + s.bi_valid += length; + } + } + function send_code(s, c, tree) { + send_bits(s, tree[c * 2], tree[c * 2 + 1]); + } + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 255; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + function gen_bitlen(s, desc) { + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; + var n, m; + var bits; + var xbits; + var f; + var overflow = 0; + for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0; + tree[s.heap[s.heap_max] * 2 + 1] = 0; + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] = bits; + if (n > max_code) continue; + s.bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n - base]; + f = tree[n * 2]; + s.opt_len += f * (bits + xbits); + if (has_stree) s.static_len += f * (stree[n * 2 + 1] + xbits); + } + if (overflow === 0) return; + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) bits--; + s.bl_count[bits]--; + s.bl_count[bits + 1] += 2; + s.bl_count[max_length]--; + overflow -= 2; + } while (overflow > 0); + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) continue; + if (tree[m * 2 + 1] !== bits) { + s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2]; + tree[m * 2 + 1] = bits; + } + n--; + } + } + } + function gen_codes(tree, max_code, bl_count) { + var next_code = new Array(MAX_BITS + 1); + var code = 0; + var bits; + var n; + for (bits = 1; bits <= MAX_BITS; bits++) next_code[bits] = code = code + bl_count[bits - 1] << 1; + for (n = 0; n <= max_code; n++) { + var len = tree[n * 2 + 1]; + if (len === 0) continue; + tree[n * 2] = bi_reverse(next_code[len]++, len); + } + } + function tr_static_init() { + var n; + var bits; + var length; + var code; + var dist; + var bl_count = new Array(MAX_BITS + 1); + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < 1 << extra_lbits[code]; n++) _length_code[length++] = code; + } + _length_code[length - 1] = code; + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < 1 << extra_dbits[code]; n++) _dist_code[dist++] = code; + } + dist >>= 7; + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < 1 << extra_dbits[code] - 7; n++) _dist_code[256 + dist++] = code; + } + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1] = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1] = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + gen_codes(static_ltree, L_CODES + 1, bl_count); + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1] = 5; + static_dtree[n * 2] = bi_reverse(n, 5); + } + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + } + function init_block(s) { + var n; + for (n = 0; n < L_CODES; n++) s.dyn_ltree[n * 2] = 0; + for (n = 0; n < D_CODES; n++) s.dyn_dtree[n * 2] = 0; + for (n = 0; n < BL_CODES; n++) s.bl_tree[n * 2] = 0; + s.dyn_ltree[END_BLOCK * 2] = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + function bi_windup(s) { + if (s.bi_valid > 8) put_short(s, s.bi_buf); + else if (s.bi_valid > 0) s.pending_buf[s.pending++] = s.bi_buf; + s.bi_buf = 0; + s.bi_valid = 0; + } + function copy_block(s, buf, len, header) { + bi_windup(s); + if (header) { + put_short(s, len); + put_short(s, ~len); + } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m]; + } + function pqdownheap(s, tree, k) { + var v = s.heap[k]; + var j = k << 1; + while (j <= s.heap_len) { + if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) j++; + if (smaller(tree, v, s.heap[j], s.depth)) break; + s.heap[k] = s.heap[j]; + k = j; + j <<= 1; + } + s.heap[k] = v; + } + function compress_block(s, ltree, dtree) { + var dist; + var lc; + var lx = 0; + var code; + var extra; + if (s.last_lit !== 0) do { + dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; + lc = s.pending_buf[s.l_buf + lx]; + lx++; + if (dist === 0) send_code(s, lc, ltree); + else { + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); + } + dist--; + code = d_code(dist); + send_code(s, code, dtree); + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); + } + } + } while (lx < s.last_lit); + send_code(s, END_BLOCK, ltree); + } + function build_tree(s, desc) { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; + var max_code = -1; + var node; + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + for (n = 0; n < elems; n++) if (tree[n * 2] !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + } else tree[n * 2 + 1] = 0; + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; + tree[node * 2] = 1; + s.depth[node] = 0; + s.opt_len--; + if (has_stree) s.static_len -= stree[node * 2 + 1]; + } + desc.max_code = max_code; + for (n = s.heap_len >> 1; n >= 1; n--) pqdownheap(s, tree, n); + node = elems; + do { + /*** pqremove ***/ + n = s.heap[1]; + s.heap[1] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1); + m = s.heap[1]; + s.heap[--s.heap_max] = n; + s.heap[--s.heap_max] = m; + tree[node * 2] = tree[n * 2] + tree[m * 2]; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] = tree[m * 2 + 1] = node; + s.heap[1] = node++; + pqdownheap(s, tree, 1); + } while (s.heap_len >= 2); + s.heap[--s.heap_max] = s.heap[1]; + gen_bitlen(s, desc); + gen_codes(tree, max_code, s.bl_count); + } + function scan_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] = 65535; + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) continue; + else if (count < min_count) s.bl_tree[curlen * 2] += count; + else if (curlen !== 0) { + if (curlen !== prevlen) s.bl_tree[curlen * 2]++; + s.bl_tree[REP_3_6 * 2]++; + } else if (count <= 10) s.bl_tree[REPZ_3_10 * 2]++; + else s.bl_tree[REPZ_11_138 * 2]++; + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function send_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) continue; + else if (count < min_count) do + send_code(s, curlen, s.bl_tree); + while (--count !== 0); + else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function build_bl_tree(s) { + var max_blindex; + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + build_tree(s, s.bl_desc); + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) break; + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + return max_blindex; + } + function send_all_trees(s, lcodes, dcodes, blcodes) { + var rank; + send_bits(s, lcodes - 257, 5); + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); + for (rank = 0; rank < blcodes; rank++) send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3); + send_tree(s, s.dyn_ltree, lcodes - 1); + send_tree(s, s.dyn_dtree, dcodes - 1); + } + function detect_data_type(s) { + var black_mask = 4093624447; + var n; + for (n = 0; n <= 31; n++, black_mask >>>= 1) if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) return Z_BINARY; + if (s.dyn_ltree[18] !== 0 || s.dyn_ltree[20] !== 0 || s.dyn_ltree[26] !== 0) return Z_TEXT; + for (n = 32; n < LITERALS; n++) if (s.dyn_ltree[n * 2] !== 0) return Z_TEXT; + return Z_BINARY; + } + var static_init_done = false; + function _tr_init(s) { + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + s.bi_buf = 0; + s.bi_valid = 0; + init_block(s); + } + function _tr_stored_block(s, buf, stored_len, last) { + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); + copy_block(s, buf, stored_len, true); + } + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + } + function _tr_flush_block(s, buf, stored_len, last) { + var opt_lenb, static_lenb; + var max_blindex = 0; + if (s.level > 0) { + if (s.strm.data_type === Z_UNKNOWN) s.strm.data_type = detect_data_type(s); + build_tree(s, s.l_desc); + build_tree(s, s.d_desc); + max_blindex = build_bl_tree(s); + opt_lenb = s.opt_len + 3 + 7 >>> 3; + static_lenb = s.static_len + 3 + 7 >>> 3; + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + } else opt_lenb = static_lenb = stored_len + 5; + if (stored_len + 4 <= opt_lenb && buf !== -1) _tr_stored_block(s, buf, stored_len, last); + else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + init_block(s); + if (last) bi_windup(s); + } + function _tr_tally(s, dist, lc) { + s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 255; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 255; + s.pending_buf[s.l_buf + s.last_lit] = lc & 255; + s.last_lit++; + if (dist === 0) s.dyn_ltree[lc * 2]++; + else { + s.matches++; + dist--; + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++; + s.dyn_dtree[d_code(dist) * 2]++; + } + return s.last_lit === s.lit_bufsize - 1; + } + exports._tr_init = _tr_init; + exports._tr_stored_block = _tr_stored_block; + exports._tr_flush_block = _tr_flush_block; + exports._tr_tally = _tr_tally; + exports._tr_align = _tr_align; +})); +//#endregion +//#region node_modules/pako/lib/zlib/adler32.js +var require_adler32 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + function adler32(adler, buf, len, pos) { + var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0; + while (len !== 0) { + n = len > 2e3 ? 2e3 : len; + len -= n; + do { + s1 = s1 + buf[pos++] | 0; + s2 = s2 + s1 | 0; + } while (--n); + s1 %= 65521; + s2 %= 65521; + } + return s1 | s2 << 16 | 0; + } + module.exports = adler32; +})); +//#endregion +//#region node_modules/pako/lib/zlib/crc32.js +var require_crc32 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + function makeTable() { + var c, table = []; + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc ^= -1; + for (var i = pos; i < end; i++) crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + return crc ^ -1; + } + module.exports = crc32; +})); +//#endregion +//#region node_modules/pako/lib/zlib/messages.js +var require_messages = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + 2: "need dictionary", + 1: "stream end", + 0: "", + "-1": "file error", + "-2": "stream error", + "-3": "data error", + "-4": "insufficient memory", + "-5": "buffer error", + "-6": "incompatible version" + }; +})); +//#endregion +//#region node_modules/pako/lib/zlib/deflate.js +var require_deflate$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var utils = require_common(); + var trees = require_trees(); + var adler32 = require_adler32(); + var crc32 = require_crc32(); + var msg = require_messages(); + var Z_NO_FLUSH = 0; + var Z_PARTIAL_FLUSH = 1; + var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_BUF_ERROR = -5; + var Z_DEFAULT_COMPRESSION = -1; + var Z_FILTERED = 1; + var Z_HUFFMAN_ONLY = 2; + var Z_RLE = 3; + var Z_FIXED = 4; + var Z_DEFAULT_STRATEGY = 0; + var Z_UNKNOWN = 2; + var Z_DEFLATED = 8; + var MAX_MEM_LEVEL = 9; + var MAX_WBITS = 15; + var DEF_MEM_LEVEL = 8; + var L_CODES = 286; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; + var PRESET_DICT = 32; + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; + var BS_NEED_MORE = 1; + var BS_BLOCK_DONE = 2; + var BS_FINISH_STARTED = 3; + var BS_FINISH_DONE = 4; + var OS_CODE = 3; + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } + function rank(f) { + return (f << 1) - (f > 4 ? 9 : 0); + } + function zero(buf) { + var len = buf.length; + while (--len >= 0) buf[len] = 0; + } + function flush_pending(strm) { + var s = strm.state; + var len = s.pending; + if (len > strm.avail_out) len = strm.avail_out; + if (len === 0) return; + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) s.pending_out = 0; + } + function flush_block_only(s, last) { + trees._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); + } + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } + function putShortMSB(s, b) { + s.pending_buf[s.pending++] = b >>> 8 & 255; + s.pending_buf[s.pending++] = b & 255; + } + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + if (len > size) len = size; + if (len === 0) return 0; + strm.avail_in -= len; + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) strm.adler = adler32(strm.adler, buf, len, start); + else if (strm.state.wrap === 2) strm.adler = crc32(strm.adler, buf, len, start); + strm.next_in += len; + strm.total_in += len; + return len; + } + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; + var scan = s.strstart; + var match; + var len; + var best_len = s.prev_length; + var nice_match = s.nice_match; + var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0; + var _win = s.window; + var wmask = s.w_mask; + var prev = s.prev; + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + if (s.prev_length >= s.good_match) chain_length >>= 2; + if (nice_match > s.lookahead) nice_match = s.lookahead; + do { + match = cur_match; + if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) continue; + scan += 2; + match++; + do ; +while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) break; + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + if (best_len <= s.lookahead) return best_len; + return s.lookahead; + } + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + do { + more = s.window_size - s.lookahead - s.strstart; + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + s.block_start -= _w_size; + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + more += _w_size; + } + if (s.strm.avail_in === 0) break; + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask; + while (s.insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) break; + } + } + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + } + function deflate_stored(s, flush) { + var max_block_size = 65535; + if (max_block_size > s.pending_buf_size - 5) max_block_size = s.pending_buf_size - 5; + for (;;) { + if (s.lookahead <= 1) { + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) return BS_NEED_MORE; + if (s.lookahead === 0) break; + } + s.strstart += s.lookahead; + s.lookahead = 0; + var max_start = s.block_start + max_block_size; + if (s.strstart === 0 || s.strstart >= max_start) { + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) return BS_FINISH_STARTED; + return BS_FINISH_DONE; + } + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + return BS_NEED_MORE; + } + function deflate_fast(s, flush) { + var hash_head; + var bflush; + for (;;) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) return BS_NEED_MORE; + if (s.lookahead === 0) break; + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) s.match_length = longest_match(s, hash_head); + if (s.match_length >= MIN_MATCH) { + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) { + s.match_length--; + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask; + } + } else { + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) return BS_FINISH_STARTED; + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + return BS_BLOCK_DONE; + } + function deflate_slow(s, flush) { + var hash_head; + var bflush; + var max_insert; + for (;;) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) return BS_NEED_MORE; + if (s.lookahead === 0) break; + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) s.match_length = MIN_MATCH - 1; + } + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + } else if (s.match_available) { + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + if (bflush) + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } else { + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + if (s.match_available) { + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) return BS_FINISH_STARTED; + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + return BS_BLOCK_DONE; + } + function deflate_rle(s, flush) { + var bflush; + var prev; + var scan, strend; + var _win = s.window; + for (;;) { + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) return BS_NEED_MORE; + if (s.lookahead === 0) break; + } + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do ; +while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) s.match_length = s.lookahead; + } + } + if (s.match_length >= MIN_MATCH) { + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) return BS_FINISH_STARTED; + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + return BS_BLOCK_DONE; + } + function deflate_huff(s, flush) { + var bflush; + for (;;) { + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) return BS_NEED_MORE; + break; + } + } + s.match_length = 0; + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) return BS_FINISH_STARTED; + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) return BS_NEED_MORE; + } + return BS_BLOCK_DONE; + } + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + var configuration_table = [ + new Config(0, 0, 0, 0, deflate_stored), + new Config(4, 4, 8, 4, deflate_fast), + new Config(4, 5, 16, 8, deflate_fast), + new Config(4, 6, 32, 32, deflate_fast), + new Config(4, 4, 16, 16, deflate_slow), + new Config(8, 16, 32, 32, deflate_slow), + new Config(8, 16, 128, 128, deflate_slow), + new Config(8, 32, 128, 256, deflate_slow), + new Config(32, 128, 258, 1024, deflate_slow), + new Config(32, 258, 258, 4096, deflate_slow) + ]; + function lm_init(s) { + s.window_size = 2 * s.w_size; + /*** CLEAR_HASH(s); ***/ + zero(s.head); + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } + function DeflateState() { + this.strm = null; + this.status = 0; + this.pending_buf = null; + this.pending_buf_size = 0; + this.pending_out = 0; + this.pending = 0; + this.wrap = 0; + this.gzhead = null; + this.gzindex = 0; + this.method = Z_DEFLATED; + this.last_flush = -1; + this.w_size = 0; + this.w_bits = 0; + this.w_mask = 0; + this.window = null; + this.window_size = 0; + this.prev = null; + this.head = null; + this.ins_h = 0; + this.hash_size = 0; + this.hash_bits = 0; + this.hash_mask = 0; + this.hash_shift = 0; + this.block_start = 0; + this.match_length = 0; + this.prev_match = 0; + this.match_available = 0; + this.strstart = 0; + this.match_start = 0; + this.lookahead = 0; + this.prev_length = 0; + this.max_chain_length = 0; + this.max_lazy_match = 0; + this.level = 0; + this.strategy = 0; + this.good_match = 0; + this.nice_match = 0; + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + this.l_desc = null; + this.d_desc = null; + this.bl_desc = null; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + this.heap = new utils.Buf16(2 * L_CODES + 1); + zero(this.heap); + this.heap_len = 0; + this.heap_max = 0; + this.depth = new utils.Buf16(2 * L_CODES + 1); + zero(this.depth); + this.l_buf = 0; + this.lit_bufsize = 0; + this.last_lit = 0; + this.d_buf = 0; + this.opt_len = 0; + this.static_len = 0; + this.matches = 0; + this.insert = 0; + this.bi_buf = 0; + this.bi_valid = 0; + } + function deflateResetKeep(strm) { + var s; + if (!strm || !strm.state) return err(strm, Z_STREAM_ERROR); + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + s = strm.state; + s.pending = 0; + s.pending_out = 0; + if (s.wrap < 0) s.wrap = -s.wrap; + s.status = s.wrap ? INIT_STATE : BUSY_STATE; + strm.adler = s.wrap === 2 ? 0 : 1; + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; + } + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) lm_init(strm.state); + return ret; + } + function deflateSetHeader(strm, head) { + if (!strm || !strm.state) return Z_STREAM_ERROR; + if (strm.state.wrap !== 2) return Z_STREAM_ERROR; + strm.state.gzhead = head; + return Z_OK; + } + function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) return Z_STREAM_ERROR; + var wrap = 1; + if (level === Z_DEFAULT_COMPRESSION) level = 6; + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else if (windowBits > 15) { + wrap = 2; + windowBits -= 16; + } + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) return err(strm, Z_STREAM_ERROR); + if (windowBits === 8) windowBits = 9; + var s = new DeflateState(); + strm.state = s; + s.strm = strm; + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + s.lit_bufsize = 1 << memLevel + 6; + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + s.d_buf = 1 * s.lit_bufsize; + s.l_buf = 3 * s.lit_bufsize; + s.level = level; + s.strategy = strategy; + s.method = method; + return deflateReset(strm); + } + function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + function deflate(strm, flush) { + var old_flush, s; + var beg, val; + if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + s = strm.state; + if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR); + s.strm = strm; + old_flush = s.last_flush; + s.last_flush = flush; + if (s.status === INIT_STATE) if (s.wrap === 2) { + strm.adler = 0; + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } else { + put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16)); + put_byte(s, s.gzhead.time & 255); + put_byte(s, s.gzhead.time >> 8 & 255); + put_byte(s, s.gzhead.time >> 16 & 255); + put_byte(s, s.gzhead.time >> 24 & 255); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, s.gzhead.os & 255); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 255); + put_byte(s, s.gzhead.extra.length >> 8 & 255); + } + if (s.gzhead.hcrc) strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } else { + var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8; + var level_flags = -1; + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) level_flags = 0; + else if (s.level < 6) level_flags = 1; + else if (s.level === 6) level_flags = 2; + else level_flags = 3; + header |= level_flags << 6; + if (s.strstart !== 0) header |= PRESET_DICT; + header += 31 - header % 31; + s.status = BUSY_STATE; + putShortMSB(s, header); + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + strm.adler = 1; + } + if (s.status === EXTRA_STATE) if (s.gzhead.extra) { + beg = s.pending; + while (s.gzindex < (s.gzhead.extra.length & 65535)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) break; + } + put_byte(s, s.gzhead.extra[s.gzindex] & 255); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } else s.status = NAME_STATE; + if (s.status === NAME_STATE) if (s.gzhead.name) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + if (s.gzindex < s.gzhead.name.length) val = s.gzhead.name.charCodeAt(s.gzindex++) & 255; + else val = 0; + put_byte(s, val); + } while (val !== 0); + if (s.gzhead.hcrc && s.pending > beg) strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } else s.status = COMMENT_STATE; + if (s.status === COMMENT_STATE) if (s.gzhead.comment) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + if (s.gzindex < s.gzhead.comment.length) val = s.gzhead.comment.charCodeAt(s.gzindex++) & 255; + else val = 0; + put_byte(s, val); + } while (val !== 0); + if (s.gzhead.hcrc && s.pending > beg) strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + if (val === 0) s.status = HCRC_STATE; + } else s.status = HCRC_STATE; + if (s.status === HCRC_STATE) if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) flush_pending(strm); + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + strm.adler = 0; + s.status = BUSY_STATE; + } + } else s.status = BUSY_STATE; + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) return err(strm, Z_BUF_ERROR); + if (s.status === FINISH_STATE && strm.avail_in !== 0) return err(strm, Z_BUF_ERROR); + if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) { + var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush); + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) s.status = FINISH_STATE; + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) s.last_flush = -1; + return Z_OK; + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) trees._tr_align(s); + else if (flush !== Z_BLOCK) { + trees._tr_stored_block(s, 0, 0, false); + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ zero(s.head); + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } + } + if (flush !== Z_FINISH) return Z_OK; + if (s.wrap <= 0) return Z_STREAM_END; + if (s.wrap === 2) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + put_byte(s, strm.adler >> 16 & 255); + put_byte(s, strm.adler >> 24 & 255); + put_byte(s, strm.total_in & 255); + put_byte(s, strm.total_in >> 8 & 255); + put_byte(s, strm.total_in >> 16 & 255); + put_byte(s, strm.total_in >> 24 & 255); + } else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + flush_pending(strm); + if (s.wrap > 0) s.wrap = -s.wrap; + return s.pending !== 0 ? Z_OK : Z_STREAM_END; + } + function deflateEnd(strm) { + var status; + if (!strm || !strm.state) return Z_STREAM_ERROR; + status = strm.state.status; + if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) return err(strm, Z_STREAM_ERROR); + strm.state = null; + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; + } + function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + if (!strm || !strm.state) return Z_STREAM_ERROR; + s = strm.state; + wrap = s.wrap; + if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) return Z_STREAM_ERROR; + if (wrap === 1) strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + s.wrap = 0; + if (dictLength >= s.w_size) { + if (wrap === 0) { + /*** CLEAR_HASH(s); ***/ + zero(s.head); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; + } + exports.deflateInit = deflateInit; + exports.deflateInit2 = deflateInit2; + exports.deflateReset = deflateReset; + exports.deflateResetKeep = deflateResetKeep; + exports.deflateSetHeader = deflateSetHeader; + exports.deflate = deflate; + exports.deflateEnd = deflateEnd; + exports.deflateSetDictionary = deflateSetDictionary; + exports.deflateInfo = "pako deflate (from Nodeca project)"; +})); +//#endregion +//#region node_modules/pako/lib/utils/strings.js +var require_strings = /* @__PURE__ */ __commonJSMin(((exports) => { + var utils = require_common(); + var STR_APPLY_OK = true; + var STR_APPLY_UIA_OK = true; + try { + String.fromCharCode.apply(null, [0]); + } catch (__) { + STR_APPLY_OK = false; + } + try { + String.fromCharCode.apply(null, /* @__PURE__ */ new Uint8Array(1)); + } catch (__) { + STR_APPLY_UIA_OK = false; + } + var _utf8len = new utils.Buf8(256); + for (var q = 0; q < 256; q++) _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; + _utf8len[254] = _utf8len[254] = 1; + exports.string2buf = function(str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + buf = new utils.Buf8(buf_len); + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) buf[i++] = c; + else if (c < 2048) { + buf[i++] = 192 | c >>> 6; + buf[i++] = 128 | c & 63; + } else if (c < 65536) { + buf[i++] = 224 | c >>> 12; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } else { + buf[i++] = 240 | c >>> 18; + buf[i++] = 128 | c >>> 12 & 63; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } + } + return buf; + }; + function buf2binstring(buf, len) { + if (len < 65534) { + if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + var result = ""; + for (var i = 0; i < len; i++) result += String.fromCharCode(buf[i]); + return result; + } + exports.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); + }; + exports.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) buf[i] = str.charCodeAt(i); + return buf; + }; + exports.buf2string = function(buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i < len) { + c = c << 6 | buf[i++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) utf16buf[out++] = c; + else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + return buf2binstring(utf16buf, out); + }; + exports.utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) max = buf.length; + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) pos--; + if (pos < 0) return max; + if (pos === 0) return max; + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; +})); +//#endregion +//#region node_modules/pako/lib/zlib/zstream.js +var require_zstream = /* @__PURE__ */ __commonJSMin(((exports, module) => { + function ZStream() { + this.input = null; + this.next_in = 0; + this.avail_in = 0; + this.total_in = 0; + this.output = null; + this.next_out = 0; + this.avail_out = 0; + this.total_out = 0; + this.msg = ""; + this.state = null; + this.data_type = 2; + this.adler = 0; + } + module.exports = ZStream; +})); +//#endregion +//#region node_modules/pako/lib/deflate.js +var require_deflate = /* @__PURE__ */ __commonJSMin(((exports) => { + var zlib_deflate = require_deflate$1(); + var utils = require_common(); + var strings = require_strings(); + var msg = require_messages(); + var ZStream = require_zstream(); + var toString = Object.prototype.toString; + var Z_NO_FLUSH = 0; + var Z_FINISH = 4; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_SYNC_FLUSH = 2; + var Z_DEFAULT_COMPRESSION = -1; + var Z_DEFAULT_STRATEGY = 0; + var Z_DEFLATED = 8; + /** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + /** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + /** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + /** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + /** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ + function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits > 0) opt.windowBits = -opt.windowBits; + else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) opt.windowBits += 16; + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream(); + this.strm.avail_out = 0; + var status = zlib_deflate.deflateInit2(this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy); + if (status !== Z_OK) throw new Error(msg[status]); + if (opt.header) zlib_deflate.deflateSetHeader(this.strm, opt.header); + if (opt.dictionary) { + var dict; + if (typeof opt.dictionary === "string") dict = strings.string2buf(opt.dictionary); + else if (toString.call(opt.dictionary) === "[object ArrayBuffer]") dict = new Uint8Array(opt.dictionary); + else dict = opt.dictionary; + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + if (status !== Z_OK) throw new Error(msg[status]); + this._dict_set = true; + } + } + /** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ + Deflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + if (this.ended) return false; + _mode = mode === ~~mode ? mode : mode === true ? Z_FINISH : Z_NO_FLUSH; + if (typeof data === "string") strm.input = strings.string2buf(data); + else if (toString.call(data) === "[object ArrayBuffer]") strm.input = new Uint8Array(data); + else strm.input = data; + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) if (this.options.to === "string") this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + else this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + /** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ + Deflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + /** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ + Deflate.prototype.onEnd = function(status) { + if (status === Z_OK) if (this.options.to === "string") this.result = this.chunks.join(""); + else this.result = utils.flattenChunks(this.chunks); + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + /** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ + function deflate(input, options) { + var deflator = new Deflate(options); + deflator.push(input, true); + if (deflator.err) throw deflator.msg || msg[deflator.err]; + return deflator.result; + } + /** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ + function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); + } + /** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ + function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); + } + exports.Deflate = Deflate; + exports.deflate = deflate; + exports.deflateRaw = deflateRaw; + exports.gzip = gzip; +})); +//#endregion +//#region node_modules/pako/lib/zlib/inffast.js +var require_inffast = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var BAD = 30; + var TYPE = 12; + module.exports = function inflate_fast(strm, start) { + var state; + var _in; + var last; + var _out; + var beg; + var end; + var dmax; + var wsize; + var whave; + var wnext; + var s_window; + var hold; + var bits; + var lcode; + var dcode; + var lmask; + var dmask; + var here; + var op; + var len; + var dist; + var from; + var from_source; + var input, output; + state = strm.state; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + dmax = state.dmax; + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + top: do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: for (;;) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op === 0) output[_out++] = here & 65535; + else if (op & 16) { + len = here & 65535; + op &= 15; + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & (1 << op) - 1; + hold >>>= op; + bits -= op; + } + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: for (;;) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op & 16) { + dist = here & 65535; + op &= 15; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & (1 << op) - 1; + if (dist > dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + hold >>>= op; + bits -= op; + op = _out - beg; + if (dist > op) { + op = dist - op; + if (op > whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + } + from = 0; + from_source = s_window; + if (wnext === 0) { + from += wsize - op; + if (op < len) { + len -= op; + do + output[_out++] = s_window[from++]; + while (--op); + from = _out - dist; + from_source = output; + } + } else if (wnext < op) { + from += wsize + wnext - op; + op -= wnext; + if (op < len) { + len -= op; + do + output[_out++] = s_window[from++]; + while (--op); + from = 0; + if (wnext < len) { + op = wnext; + len -= op; + do + output[_out++] = s_window[from++]; + while (--op); + from = _out - dist; + from_source = output; + } + } + } else { + from += wnext - op; + if (op < len) { + len -= op; + do + output[_out++] = s_window[from++]; + while (--op); + from = _out - dist; + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) output[_out++] = from_source[from++]; + } + } else { + from = _out - dist; + do { + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) output[_out++] = output[from++]; + } + } + } else if ((op & 64) === 0) { + here = dcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dodist; + } else { + strm.msg = "invalid distance code"; + state.mode = BAD; + break top; + } + break; + } + } else if ((op & 64) === 0) { + here = lcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dolen; + } else if (op & 32) { + state.mode = TYPE; + break top; + } else { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break top; + } + break; + } + } while (_in < last && _out < end); + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last); + strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); + state.hold = hold; + state.bits = bits; + }; +})); +//#endregion +//#region node_modules/pako/lib/zlib/inftrees.js +var require_inftrees = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_common(); + var MAXBITS = 15; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var lbase = [ + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 13, + 15, + 17, + 19, + 23, + 27, + 31, + 35, + 43, + 51, + 59, + 67, + 83, + 99, + 115, + 131, + 163, + 195, + 227, + 258, + 0, + 0 + ]; + var lext = [ + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 17, + 17, + 17, + 17, + 18, + 18, + 18, + 18, + 19, + 19, + 19, + 19, + 20, + 20, + 20, + 20, + 21, + 21, + 21, + 21, + 16, + 72, + 78 + ]; + var dbase = [ + 1, + 2, + 3, + 4, + 5, + 7, + 9, + 13, + 17, + 25, + 33, + 49, + 65, + 97, + 129, + 193, + 257, + 385, + 513, + 769, + 1025, + 1537, + 2049, + 3073, + 4097, + 6145, + 8193, + 12289, + 16385, + 24577, + 0, + 0 + ]; + var dext = [ + 16, + 16, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 20, + 20, + 21, + 21, + 22, + 22, + 23, + 23, + 24, + 24, + 25, + 25, + 26, + 26, + 27, + 27, + 28, + 28, + 29, + 29, + 64, + 64 + ]; + module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + var len = 0; + var sym = 0; + var min = 0, max = 0; + var root = 0; + var curr = 0; + var drop = 0; + var left = 0; + var used = 0; + var huff = 0; + var incr; + var fill; + var low; + var mask; + var next; + var base = null; + var base_index = 0; + var end; + var count = new utils.Buf16(MAXBITS + 1); + var offs = new utils.Buf16(MAXBITS + 1); + var extra = null; + var extra_index = 0; + var here_bits, here_op, here_val; + for (len = 0; len <= MAXBITS; len++) count[len] = 0; + for (sym = 0; sym < codes; sym++) count[lens[lens_index + sym]]++; + root = bits; + for (max = MAXBITS; max >= 1; max--) if (count[max] !== 0) break; + if (root > max) root = max; + if (max === 0) { + table[table_index++] = 20971520; + table[table_index++] = 20971520; + opts.bits = 1; + return 0; + } + for (min = 1; min < max; min++) if (count[min] !== 0) break; + if (root < min) root = min; + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; + } + if (left > 0 && (type === CODES || max !== 1)) return -1; + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) offs[len + 1] = offs[len] + count[len]; + for (sym = 0; sym < codes; sym++) if (lens[lens_index + sym] !== 0) work[offs[lens[lens_index + sym]]++] = sym; + if (type === CODES) { + base = extra = work; + end = 19; + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + } else { + base = dbase; + extra = dext; + end = -1; + } + huff = 0; + sym = 0; + len = min; + next = table_index; + curr = root; + drop = 0; + low = -1; + used = 1 << root; + mask = used - 1; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) return 1; + for (;;) { + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } else { + here_op = 96; + here_val = 0; + } + incr = 1 << len - drop; + fill = 1 << curr; + min = fill; + do { + fill -= incr; + table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0; + } while (fill !== 0); + incr = 1 << len - 1; + while (huff & incr) incr >>= 1; + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else huff = 0; + sym++; + if (--count[len] === 0) { + if (len === max) break; + len = lens[lens_index + work[sym]]; + } + if (len > root && (huff & mask) !== low) { + if (drop === 0) drop = root; + next += min; + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + used += 1 << curr; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) return 1; + low = huff & mask; + table[low] = root << 24 | curr << 16 | next - table_index | 0; + } + } + if (huff !== 0) table[next + huff] = len - drop << 24 | 4194304; + opts.bits = root; + return 0; + }; +})); +//#endregion +//#region node_modules/pako/lib/zlib/inflate.js +var require_inflate$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + var utils = require_common(); + var adler32 = require_adler32(); + var crc32 = require_crc32(); + var inflate_fast = require_inffast(); + var inflate_table = require_inftrees(); + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_TREES = 6; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_NEED_DICT = 2; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + var Z_DEFLATED = 8; + var HEAD = 1; + var FLAGS = 2; + var TIME = 3; + var OS = 4; + var EXLEN = 5; + var EXTRA = 6; + var NAME = 7; + var COMMENT = 8; + var HCRC = 9; + var DICTID = 10; + var DICT = 11; + var TYPE = 12; + var TYPEDO = 13; + var STORED = 14; + var COPY_ = 15; + var COPY = 16; + var TABLE = 17; + var LENLENS = 18; + var CODELENS = 19; + var LEN_ = 20; + var LEN = 21; + var LENEXT = 22; + var DIST = 23; + var DISTEXT = 24; + var MATCH = 25; + var LIT = 26; + var CHECK = 27; + var LENGTH = 28; + var DONE = 29; + var BAD = 30; + var MEM = 31; + var SYNC = 32; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var DEF_WBITS = 15; + function zswap32(q) { + return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24); + } + function InflateState() { + this.mode = 0; + this.last = false; + this.wrap = 0; + this.havedict = false; + this.flags = 0; + this.dmax = 0; + this.check = 0; + this.total = 0; + this.head = null; + this.wbits = 0; + this.wsize = 0; + this.whave = 0; + this.wnext = 0; + this.window = null; + this.hold = 0; + this.bits = 0; + this.length = 0; + this.offset = 0; + this.extra = 0; + this.lencode = null; + this.distcode = null; + this.lenbits = 0; + this.distbits = 0; + this.ncode = 0; + this.nlen = 0; + this.ndist = 0; + this.have = 0; + this.next = null; + this.lens = new utils.Buf16(320); + this.work = new utils.Buf16(288); + this.lendyn = null; + this.distdyn = null; + this.sane = 0; + this.back = 0; + this.was = 0; + } + function inflateResetKeep(strm) { + var state; + if (!strm || !strm.state) return Z_STREAM_ERROR; + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ""; + if (state.wrap) strm.adler = state.wrap & 1; + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null; + state.hold = 0; + state.bits = 0; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + state.sane = 1; + state.back = -1; + return Z_OK; + } + function inflateReset(strm) { + var state; + if (!strm || !strm.state) return Z_STREAM_ERROR; + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + } + function inflateReset2(strm, windowBits) { + var wrap; + var state; + if (!strm || !strm.state) return Z_STREAM_ERROR; + state = strm.state; + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) windowBits &= 15; + } + if (windowBits && (windowBits < 8 || windowBits > 15)) return Z_STREAM_ERROR; + if (state.window !== null && state.wbits !== windowBits) state.window = null; + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); + } + function inflateInit2(strm, windowBits) { + var ret; + var state; + if (!strm) return Z_STREAM_ERROR; + state = new InflateState(); + strm.state = state; + state.window = null; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) strm.state = null; + return ret; + } + function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); + } + var virgin = true; + var lenfix; + var distfix; + function fixedtables(state) { + if (virgin) { + var sym; + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + sym = 0; + while (sym < 144) state.lens[sym++] = 8; + while (sym < 256) state.lens[sym++] = 9; + while (sym < 280) state.lens[sym++] = 7; + while (sym < 288) state.lens[sym++] = 8; + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + sym = 0; + while (sym < 32) state.lens[sym++] = 5; + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + virgin = false; + } + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; + } + function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + state.window = new utils.Buf8(state.wsize); + } + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } else { + dist = state.wsize - state.wnext; + if (dist > copy) dist = copy; + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } else { + state.wnext += dist; + if (state.wnext === state.wsize) state.wnext = 0; + if (state.whave < state.wsize) state.whave += dist; + } + } + return 0; + } + function inflate(strm, flush) { + var state; + var input, output; + var next; + var put; + var have, left; + var hold; + var bits; + var _in, _out; + var copy; + var from; + var from_source; + var here = 0; + var here_bits, here_op, here_val; + var last_bits, last_op, last_val; + var len; + var ret; + var hbuf = new utils.Buf8(4); + var opts; + var n; + var order = [ + 16, + 17, + 18, + 0, + 8, + 7, + 9, + 6, + 10, + 5, + 11, + 4, + 12, + 3, + 13, + 2, + 14, + 1, + 15 + ]; + if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) return Z_STREAM_ERROR; + state = strm.state; + if (state.mode === TYPE) state.mode = TYPEDO; + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + _in = have; + _out = left; + ret = Z_OK; + inf_leave: for (;;) switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + while (bits < 16) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.wrap & 2 && hold === 35615) { + state.check = 0; + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + hold = 0; + bits = 0; + state.mode = FLAGS; + break; + } + state.flags = 0; + if (state.head) state.head.done = false; + if (!(state.wrap & 1) || (((hold & 255) << 8) + (hold >> 8)) % 31) { + strm.msg = "incorrect header check"; + state.mode = BAD; + break; + } + if ((hold & 15) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + hold >>>= 4; + bits -= 4; + len = (hold & 15) + 8; + if (state.wbits === 0) state.wbits = len; + else if (len > state.wbits) { + strm.msg = "invalid window size"; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + strm.adler = state.check = 1; + state.mode = hold & 512 ? DICTID : TYPE; + hold = 0; + bits = 0; + break; + case FLAGS: + while (bits < 16) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + state.flags = hold; + if ((state.flags & 255) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + if (state.flags & 57344) { + strm.msg = "unknown header flags set"; + state.mode = BAD; + break; + } + if (state.head) state.head.text = hold >> 8 & 1; + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = TIME; + case TIME: + while (bits < 32) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) state.head.time = hold; + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + hbuf[2] = hold >>> 16 & 255; + hbuf[3] = hold >>> 24 & 255; + state.check = crc32(state.check, hbuf, 4, 0); + } + hold = 0; + bits = 0; + state.mode = OS; + case OS: + while (bits < 16) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.xflags = hold & 255; + state.head.os = hold >> 8; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = EXLEN; + case EXLEN: + if (state.flags & 1024) { + while (bits < 16) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length = hold; + if (state.head) state.head.extra_len = hold; + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + } else if (state.head) state.head.extra = null; + state.mode = EXTRA; + case EXTRA: + if (state.flags & 1024) { + copy = state.length; + if (copy > have) copy = have; + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) state.head.extra = new Array(state.head.extra_len); + utils.arraySet(state.head.extra, input, next, copy, len); + } + if (state.flags & 512) state.check = crc32(state.check, input, copy, next); + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) break inf_leave; + } + state.length = 0; + state.mode = NAME; + case NAME: + if (state.flags & 2048) { + if (have === 0) break inf_leave; + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) state.head.name += String.fromCharCode(len); + } while (len && copy < have); + if (state.flags & 512) state.check = crc32(state.check, input, copy, next); + have -= copy; + next += copy; + if (len) break inf_leave; + } else if (state.head) state.head.name = null; + state.length = 0; + state.mode = COMMENT; + case COMMENT: + if (state.flags & 4096) { + if (have === 0) break inf_leave; + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) state.head.comment += String.fromCharCode(len); + } while (len && copy < have); + if (state.flags & 512) state.check = crc32(state.check, input, copy, next); + have -= copy; + next += copy; + if (len) break inf_leave; + } else if (state.head) state.head.comment = null; + state.mode = HCRC; + case HCRC: + if (state.flags & 512) { + while (bits < 16) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.check & 65535)) { + strm.msg = "header crc mismatch"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + if (state.head) { + state.head.hcrc = state.flags >> 9 & 1; + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + while (bits < 32) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + strm.adler = state.check = zswap32(hold); + hold = 0; + bits = 0; + state.mode = DICT; + case DICT: + if (state.havedict === 0) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + return Z_NEED_DICT; + } + strm.adler = state.check = 1; + state.mode = TYPE; + case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) break inf_leave; + case TYPEDO: + if (state.last) { + hold >>>= bits & 7; + bits -= bits & 7; + state.mode = CHECK; + break; + } + while (bits < 3) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + state.last = hold & 1; + hold >>>= 1; + bits -= 1; + switch (hold & 3) { + case 0: + state.mode = STORED; + break; + case 1: + fixedtables(state); + state.mode = LEN_; + if (flush === Z_TREES) { + hold >>>= 2; + bits -= 2; + break inf_leave; + } + break; + case 2: + state.mode = TABLE; + break; + case 3: + strm.msg = "invalid block type"; + state.mode = BAD; + } + hold >>>= 2; + bits -= 2; + break; + case STORED: + hold >>>= bits & 7; + bits -= bits & 7; + while (bits < 32) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((hold & 65535) !== (hold >>> 16 ^ 65535)) { + strm.msg = "invalid stored block lengths"; + state.mode = BAD; + break; + } + state.length = hold & 65535; + hold = 0; + bits = 0; + state.mode = COPY_; + if (flush === Z_TREES) break inf_leave; + case COPY_: state.mode = COPY; + case COPY: + copy = state.length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy === 0) break inf_leave; + utils.arraySet(output, input, next, copy, put); + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + state.mode = TYPE; + break; + case TABLE: + while (bits < 14) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + state.nlen = (hold & 31) + 257; + hold >>>= 5; + bits -= 5; + state.ndist = (hold & 31) + 1; + hold >>>= 5; + bits -= 5; + state.ncode = (hold & 15) + 4; + hold >>>= 4; + bits -= 4; + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = "too many length or distance symbols"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = LENLENS; + case LENLENS: + while (state.have < state.ncode) { + while (bits < 3) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + state.lens[order[state.have++]] = hold & 7; + hold >>>= 3; + bits -= 3; + } + while (state.have < 19) state.lens[order[state.have++]] = 0; + state.lencode = state.lendyn; + state.lenbits = 7; + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid code lengths set"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = CODELENS; + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) break; + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_val < 16) { + hold >>>= here_bits; + bits -= here_bits; + state.lens[state.have++] = here_val; + } else { + if (here_val === 16) { + n = here_bits + 2; + while (bits < n) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + if (state.have === 0) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 3); + hold >>>= 2; + bits -= 2; + } else if (here_val === 17) { + n = here_bits + 3; + while (bits < n) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 3 + (hold & 7); + hold >>>= 3; + bits -= 3; + } else { + n = here_bits + 7; + while (bits < n) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 11 + (hold & 127); + hold >>>= 7; + bits -= 7; + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + while (copy--) state.lens[state.have++] = len; + } + } + if (state.mode === BAD) break; + if (state.lens[256] === 0) { + strm.msg = "invalid code -- missing end-of-block"; + state.mode = BAD; + break; + } + state.lenbits = 9; + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid literal/lengths set"; + state.mode = BAD; + break; + } + state.distbits = 6; + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + state.distbits = opts.bits; + if (ret) { + strm.msg = "invalid distances set"; + state.mode = BAD; + break; + } + state.mode = LEN_; + if (flush === Z_TREES) break inf_leave; + case LEN_: state.mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + inflate_fast(strm, _out); + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + if (state.mode === TYPE) state.back = -1; + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) break; + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_op && (here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) break; + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + state.mode = LIT; + break; + } + if (here_op & 32) { + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + case LENEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + state.was = state.length; + state.mode = DIST; + case DIST: + for (;;) { + here = state.distcode[hold & (1 << state.distbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) break; + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) break; + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + if (here_op & 64) { + strm.msg = "invalid distance code"; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = here_op & 15; + state.mode = DISTEXT; + case DISTEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + state.offset += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + if (state.offset > state.dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + state.mode = MATCH; + case MATCH: + if (left === 0) break inf_leave; + copy = _out - left; + if (state.offset > copy) { + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } else from = state.wnext - copy; + if (copy > state.length) copy = state.length; + from_source = state.window; + } else { + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) copy = left; + left -= copy; + state.length -= copy; + do + output[put++] = from_source[from++]; + while (--copy); + if (state.length === 0) state.mode = LEN; + break; + case LIT: + if (left === 0) break inf_leave; + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + while (bits < 32) { + if (have === 0) break inf_leave; + have--; + hold |= input[next++] << bits; + bits += 8; + } + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) strm.adler = state.check = state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out); + _out = left; + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = "incorrect data check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = LENGTH; + case LENGTH: + if (state.wrap && state.flags) { + while (bits < 32) { + if (have === 0) break inf_leave; + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.total & 4294967295)) { + strm.msg = "incorrect length check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = DONE; + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: return Z_MEM_ERROR; + case SYNC: + default: return Z_STREAM_ERROR; + } + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH)) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) strm.adler = state.check = state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out); + strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) ret = Z_BUF_ERROR; + return ret; + } + function inflateEnd(strm) { + if (!strm || !strm.state) return Z_STREAM_ERROR; + var state = strm.state; + if (state.window) state.window = null; + strm.state = null; + return Z_OK; + } + function inflateGetHeader(strm, head) { + var state; + if (!strm || !strm.state) return Z_STREAM_ERROR; + state = strm.state; + if ((state.wrap & 2) === 0) return Z_STREAM_ERROR; + state.head = head; + head.done = false; + return Z_OK; + } + function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var state; + var dictid; + var ret; + if (!strm || !strm.state) return Z_STREAM_ERROR; + state = strm.state; + if (state.wrap !== 0 && state.mode !== DICT) return Z_STREAM_ERROR; + if (state.mode === DICT) { + dictid = 1; + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) return Z_DATA_ERROR; + } + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + return Z_OK; + } + exports.inflateReset = inflateReset; + exports.inflateReset2 = inflateReset2; + exports.inflateResetKeep = inflateResetKeep; + exports.inflateInit = inflateInit; + exports.inflateInit2 = inflateInit2; + exports.inflate = inflate; + exports.inflateEnd = inflateEnd; + exports.inflateGetHeader = inflateGetHeader; + exports.inflateSetDictionary = inflateSetDictionary; + exports.inflateInfo = "pako inflate (from Nodeca project)"; +})); +//#endregion +//#region node_modules/pako/lib/zlib/constants.js +var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_BUF_ERROR: -5, + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + Z_BINARY: 0, + Z_TEXT: 1, + Z_UNKNOWN: 2, + Z_DEFLATED: 8 + }; +})); +//#endregion +//#region node_modules/pako/lib/zlib/gzheader.js +var require_gzheader = /* @__PURE__ */ __commonJSMin(((exports, module) => { + function GZheader() { + this.text = 0; + this.time = 0; + this.xflags = 0; + this.os = 0; + this.extra = null; + this.extra_len = 0; + this.name = ""; + this.comment = ""; + this.hcrc = 0; + this.done = false; + } + module.exports = GZheader; +})); +//#endregion +//#region node_modules/pako/lib/inflate.js +var require_inflate = /* @__PURE__ */ __commonJSMin(((exports) => { + var zlib_inflate = require_inflate$1(); + var utils = require_common(); + var strings = require_strings(); + var c = require_constants(); + var msg = require_messages(); + var ZStream = require_zstream(); + var GZheader = require_gzheader(); + var toString = Object.prototype.toString; + /** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + /** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + /** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + /** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + /** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ + function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) opt.windowBits = -15; + } + if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) opt.windowBits += 32; + if (opt.windowBits > 15 && opt.windowBits < 48) { + if ((opt.windowBits & 15) === 0) opt.windowBits |= 15; + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream(); + this.strm.avail_out = 0; + var status = zlib_inflate.inflateInit2(this.strm, opt.windowBits); + if (status !== c.Z_OK) throw new Error(msg[status]); + this.header = new GZheader(); + zlib_inflate.inflateGetHeader(this.strm, this.header); + if (opt.dictionary) { + if (typeof opt.dictionary === "string") opt.dictionary = strings.string2buf(opt.dictionary); + else if (toString.call(opt.dictionary) === "[object ArrayBuffer]") opt.dictionary = new Uint8Array(opt.dictionary); + if (opt.raw) { + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) throw new Error(msg[status]); + } + } + } + /** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ + Inflate.prototype.push = function(data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + var allowBufError = false; + if (this.ended) return false; + _mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH; + if (typeof data === "string") strm.input = strings.binstring2buf(data); + else if (toString.call(data) === "[object ArrayBuffer]") strm.input = new Uint8Array(data); + else strm.input = data; + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); + if (status === c.Z_NEED_DICT && dictionary) status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) if (this.options.to === "string") { + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); + this.onData(utf8str); + } else this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + if (strm.avail_in === 0 && strm.avail_out === 0) allowBufError = true; + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + if (status === c.Z_STREAM_END) _mode = c.Z_FINISH; + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + /** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ + Inflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + /** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ + Inflate.prototype.onEnd = function(status) { + if (status === c.Z_OK) if (this.options.to === "string") this.result = this.chunks.join(""); + else this.result = utils.flattenChunks(this.chunks); + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + /** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ + function inflate(input, options) { + var inflator = new Inflate(options); + inflator.push(input, true); + if (inflator.err) throw inflator.msg || msg[inflator.err]; + return inflator.result; + } + /** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ + function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); + } + /** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + exports.Inflate = Inflate; + exports.inflate = inflate; + exports.inflateRaw = inflateRaw; + exports.ungzip = inflate; +})); +//#endregion +//#region node_modules/pako/index.js +var require_pako = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var assign = require_common().assign; + var deflate = require_deflate(); + var inflate = require_inflate(); + var constants = require_constants(); + var pako = {}; + assign(pako, deflate, inflate, constants); + module.exports = pako; +})); +//#endregion +//#region node_modules/jszip/lib/flate.js +var require_flate = /* @__PURE__ */ __commonJSMin(((exports) => { + var USE_TYPEDARRAY = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Uint32Array !== "undefined"; + var pako = require_pako(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array"; + exports.magic = "\b\0"; + /** + * Create a worker that uses pako to inflate/deflate. + * @constructor + * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate". + * @param {Object} options the options to use when (de)compressing. + */ + function FlateWorker(action, options) { + GenericWorker.call(this, "FlateWorker/" + action); + this._pako = null; + this._pakoAction = action; + this._pakoOptions = options; + this.meta = {}; + } + utils.inherits(FlateWorker, GenericWorker); + /** + * @see GenericWorker.processChunk + */ + FlateWorker.prototype.processChunk = function(chunk) { + this.meta = chunk.meta; + if (this._pako === null) this._createPako(); + this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false); + }; + /** + * @see GenericWorker.flush + */ + FlateWorker.prototype.flush = function() { + GenericWorker.prototype.flush.call(this); + if (this._pako === null) this._createPako(); + this._pako.push([], true); + }; + /** + * @see GenericWorker.cleanUp + */ + FlateWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this._pako = null; + }; + /** + * Create the _pako object. + * TODO: lazy-loading this object isn't the best solution but it's the + * quickest. The best solution is to lazy-load the worker list. See also the + * issue #446. + */ + FlateWorker.prototype._createPako = function() { + this._pako = new pako[this._pakoAction]({ + raw: true, + level: this._pakoOptions.level || -1 + }); + var self = this; + this._pako.onData = function(data) { + self.push({ + data, + meta: self.meta + }); + }; + }; + exports.compressWorker = function(compressionOptions) { + return new FlateWorker("Deflate", compressionOptions); + }; + exports.uncompressWorker = function() { + return new FlateWorker("Inflate", {}); + }; +})); +//#endregion +//#region node_modules/jszip/lib/compressions.js +var require_compressions = /* @__PURE__ */ __commonJSMin(((exports) => { + var GenericWorker = require_GenericWorker(); + exports.STORE = { + magic: "\0\0", + compressWorker: function() { + return new GenericWorker("STORE compression"); + }, + uncompressWorker: function() { + return new GenericWorker("STORE decompression"); + } + }; + exports.DEFLATE = require_flate(); +})); +//#endregion +//#region node_modules/jszip/lib/signature.js +var require_signature = /* @__PURE__ */ __commonJSMin(((exports) => { + exports.LOCAL_FILE_HEADER = "PK"; + exports.CENTRAL_FILE_HEADER = "PK"; + exports.CENTRAL_DIRECTORY_END = "PK"; + exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07"; + exports.ZIP64_CENTRAL_DIRECTORY_END = "PK"; + exports.DATA_DESCRIPTOR = "PK\x07\b"; +})); +//#endregion +//#region node_modules/jszip/lib/generate/ZipFileWorker.js +var require_ZipFileWorker = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var utf8 = require_utf8(); + var crc32 = require_crc32$1(); + var signature = require_signature(); + /** + * Transform an integer into a string in hexadecimal. + * @private + * @param {number} dec the number to convert. + * @param {number} bytes the number of bytes to generate. + * @returns {string} the result. + */ + var decToHex = function(dec, bytes) { + var hex = "", i; + for (i = 0; i < bytes; i++) { + hex += String.fromCharCode(dec & 255); + dec = dec >>> 8; + } + return hex; + }; + /** + * Generate the UNIX part of the external file attributes. + * @param {Object} unixPermissions the unix permissions or null. + * @param {Boolean} isDir true if the entry is a directory, false otherwise. + * @return {Number} a 32 bit integer. + * + * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute : + * + * TTTTsstrwxrwxrwx0000000000ADVSHR + * ^^^^____________________________ file type, see zipinfo.c (UNX_*) + * ^^^_________________________ setuid, setgid, sticky + * ^^^^^^^^^________________ permissions + * ^^^^^^^^^^______ not used ? + * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only + */ + var generateUnixExternalFileAttr = function(unixPermissions, isDir) { + var result = unixPermissions; + if (!unixPermissions) result = isDir ? 16893 : 33204; + return (result & 65535) << 16; + }; + /** + * Generate the DOS part of the external file attributes. + * @param {Object} dosPermissions the dos permissions or null. + * @param {Boolean} isDir true if the entry is a directory, false otherwise. + * @return {Number} a 32 bit integer. + * + * Bit 0 Read-Only + * Bit 1 Hidden + * Bit 2 System + * Bit 3 Volume Label + * Bit 4 Directory + * Bit 5 Archive + */ + var generateDosExternalFileAttr = function(dosPermissions) { + return (dosPermissions || 0) & 63; + }; + /** + * Generate the various parts used in the construction of the final zip file. + * @param {Object} streamInfo the hash with information about the compressed file. + * @param {Boolean} streamedContent is the content streamed ? + * @param {Boolean} streamingEnded is the stream finished ? + * @param {number} offset the current offset from the start of the zip file. + * @param {String} platform let's pretend we are this platform (change platform dependents fields) + * @param {Function} encodeFileName the function to encode the file name / comment. + * @return {Object} the zip parts. + */ + var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) { + var file = streamInfo["file"], compression = streamInfo["compression"], useCustomEncoding = encodeFileName !== utf8.utf8encode, encodedFileName = utils.transformTo("string", encodeFileName(file.name)), utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), comment = file.comment, encodedComment = utils.transformTo("string", encodeFileName(comment)), utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, useUTF8ForComment = utfEncodedComment.length !== comment.length, dosTime, dosDate, extraFields = "", unicodePathExtraField = "", unicodeCommentExtraField = "", dir = file.dir, date = file.date; + var dataInfo = { + crc32: 0, + compressedSize: 0, + uncompressedSize: 0 + }; + if (!streamedContent || streamingEnded) { + dataInfo.crc32 = streamInfo["crc32"]; + dataInfo.compressedSize = streamInfo["compressedSize"]; + dataInfo.uncompressedSize = streamInfo["uncompressedSize"]; + } + var bitflag = 0; + if (streamedContent) bitflag |= 8; + if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) bitflag |= 2048; + var extFileAttr = 0; + var versionMadeBy = 0; + if (dir) extFileAttr |= 16; + if (platform === "UNIX") { + versionMadeBy = 798; + extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); + } else { + versionMadeBy = 20; + extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); + } + dosTime = date.getUTCHours(); + dosTime = dosTime << 6; + dosTime = dosTime | date.getUTCMinutes(); + dosTime = dosTime << 5; + dosTime = dosTime | date.getUTCSeconds() / 2; + dosDate = date.getUTCFullYear() - 1980; + dosDate = dosDate << 4; + dosDate = dosDate | date.getUTCMonth() + 1; + dosDate = dosDate << 5; + dosDate = dosDate | date.getUTCDate(); + if (useUTF8ForFileName) { + unicodePathExtraField = decToHex(1, 1) + decToHex(crc32(encodedFileName), 4) + utfEncodedFileName; + extraFields += "up" + decToHex(unicodePathExtraField.length, 2) + unicodePathExtraField; + } + if (useUTF8ForComment) { + unicodeCommentExtraField = decToHex(1, 1) + decToHex(crc32(encodedComment), 4) + utfEncodedComment; + extraFields += "uc" + decToHex(unicodeCommentExtraField.length, 2) + unicodeCommentExtraField; + } + var header = ""; + header += "\n\0"; + header += decToHex(bitflag, 2); + header += compression.magic; + header += decToHex(dosTime, 2); + header += decToHex(dosDate, 2); + header += decToHex(dataInfo.crc32, 4); + header += decToHex(dataInfo.compressedSize, 4); + header += decToHex(dataInfo.uncompressedSize, 4); + header += decToHex(encodedFileName.length, 2); + header += decToHex(extraFields.length, 2); + return { + fileRecord: signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields, + dirRecord: signature.CENTRAL_FILE_HEADER + decToHex(versionMadeBy, 2) + header + decToHex(encodedComment.length, 2) + "\0\0\0\0" + decToHex(extFileAttr, 4) + decToHex(offset, 4) + encodedFileName + extraFields + encodedComment + }; + }; + /** + * Generate the EOCD record. + * @param {Number} entriesCount the number of entries in the zip file. + * @param {Number} centralDirLength the length (in bytes) of the central dir. + * @param {Number} localDirLength the length (in bytes) of the local dir. + * @param {String} comment the zip file comment as a binary string. + * @param {Function} encodeFileName the function to encode the comment. + * @return {String} the EOCD record. + */ + var generateCentralDirectoryEnd = function(entriesCount, centralDirLength, localDirLength, comment, encodeFileName) { + var dirEnd = ""; + var encodedComment = utils.transformTo("string", encodeFileName(comment)); + dirEnd = signature.CENTRAL_DIRECTORY_END + "\0\0\0\0" + decToHex(entriesCount, 2) + decToHex(entriesCount, 2) + decToHex(centralDirLength, 4) + decToHex(localDirLength, 4) + decToHex(encodedComment.length, 2) + encodedComment; + return dirEnd; + }; + /** + * Generate data descriptors for a file entry. + * @param {Object} streamInfo the hash generated by a worker, containing information + * on the file entry. + * @return {String} the data descriptors. + */ + var generateDataDescriptors = function(streamInfo) { + var descriptor = ""; + descriptor = signature.DATA_DESCRIPTOR + decToHex(streamInfo["crc32"], 4) + decToHex(streamInfo["compressedSize"], 4) + decToHex(streamInfo["uncompressedSize"], 4); + return descriptor; + }; + /** + * A worker to concatenate other workers to create a zip file. + * @param {Boolean} streamFiles `true` to stream the content of the files, + * `false` to accumulate it. + * @param {String} comment the comment to use. + * @param {String} platform the platform to use, "UNIX" or "DOS". + * @param {Function} encodeFileName the function to encode file names and comments. + */ + function ZipFileWorker(streamFiles, comment, platform, encodeFileName) { + GenericWorker.call(this, "ZipFileWorker"); + this.bytesWritten = 0; + this.zipComment = comment; + this.zipPlatform = platform; + this.encodeFileName = encodeFileName; + this.streamFiles = streamFiles; + this.accumulate = false; + this.contentBuffer = []; + this.dirRecords = []; + this.currentSourceOffset = 0; + this.entriesCount = 0; + this.currentFile = null; + this._sources = []; + } + utils.inherits(ZipFileWorker, GenericWorker); + /** + * @see GenericWorker.push + */ + ZipFileWorker.prototype.push = function(chunk) { + var currentFilePercent = chunk.meta.percent || 0; + var entriesCount = this.entriesCount; + var remainingFiles = this._sources.length; + if (this.accumulate) this.contentBuffer.push(chunk); + else { + this.bytesWritten += chunk.data.length; + GenericWorker.prototype.push.call(this, { + data: chunk.data, + meta: { + currentFile: this.currentFile, + percent: entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100 + } + }); + } + }; + /** + * The worker started a new source (an other worker). + * @param {Object} streamInfo the streamInfo object from the new source. + */ + ZipFileWorker.prototype.openedSource = function(streamInfo) { + this.currentSourceOffset = this.bytesWritten; + this.currentFile = streamInfo["file"].name; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + if (streamedContent) { + var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + } else this.accumulate = true; + }; + /** + * The worker finished a source (an other worker). + * @param {Object} streamInfo the streamInfo object from the finished source. + */ + ZipFileWorker.prototype.closedSource = function(streamInfo) { + this.accumulate = false; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.dirRecords.push(record.dirRecord); + if (streamedContent) this.push({ + data: generateDataDescriptors(streamInfo), + meta: { percent: 100 } + }); + else { + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + while (this.contentBuffer.length) this.push(this.contentBuffer.shift()); + } + this.currentFile = null; + }; + /** + * @see GenericWorker.flush + */ + ZipFileWorker.prototype.flush = function() { + var localDirLength = this.bytesWritten; + for (var i = 0; i < this.dirRecords.length; i++) this.push({ + data: this.dirRecords[i], + meta: { percent: 100 } + }); + var centralDirLength = this.bytesWritten - localDirLength; + var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName); + this.push({ + data: dirEnd, + meta: { percent: 100 } + }); + }; + /** + * Prepare the next source to be read. + */ + ZipFileWorker.prototype.prepareNextSource = function() { + this.previous = this._sources.shift(); + this.openedSource(this.previous.streamInfo); + if (this.isPaused) this.previous.pause(); + else this.previous.resume(); + }; + /** + * @see GenericWorker.registerPrevious + */ + ZipFileWorker.prototype.registerPrevious = function(previous) { + this._sources.push(previous); + var self = this; + previous.on("data", function(chunk) { + self.processChunk(chunk); + }); + previous.on("end", function() { + self.closedSource(self.previous.streamInfo); + if (self._sources.length) self.prepareNextSource(); + else self.end(); + }); + previous.on("error", function(e) { + self.error(e); + }); + return this; + }; + /** + * @see GenericWorker.resume + */ + ZipFileWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) return false; + if (!this.previous && this._sources.length) { + this.prepareNextSource(); + return true; + } + if (!this.previous && !this._sources.length && !this.generatedError) { + this.end(); + return true; + } + }; + /** + * @see GenericWorker.error + */ + ZipFileWorker.prototype.error = function(e) { + var sources = this._sources; + if (!GenericWorker.prototype.error.call(this, e)) return false; + for (var i = 0; i < sources.length; i++) try { + sources[i].error(e); + } catch (e) {} + return true; + }; + /** + * @see GenericWorker.lock + */ + ZipFileWorker.prototype.lock = function() { + GenericWorker.prototype.lock.call(this); + var sources = this._sources; + for (var i = 0; i < sources.length; i++) sources[i].lock(); + }; + module.exports = ZipFileWorker; +})); +//#endregion +//#region node_modules/jszip/lib/generate/index.js +var require_generate = /* @__PURE__ */ __commonJSMin(((exports) => { + var compressions = require_compressions(); + var ZipFileWorker = require_ZipFileWorker(); + /** + * Find the compression to use. + * @param {String} fileCompression the compression defined at the file level, if any. + * @param {String} zipCompression the compression defined at the load() level. + * @return {Object} the compression object to use. + */ + var getCompression = function(fileCompression, zipCompression) { + var compressionName = fileCompression || zipCompression; + var compression = compressions[compressionName]; + if (!compression) throw new Error(compressionName + " is not a valid compression method !"); + return compression; + }; + /** + * Create a worker to generate a zip file. + * @param {JSZip} zip the JSZip instance at the right root level. + * @param {Object} options to generate the zip file. + * @param {String} comment the comment to use. + */ + exports.generateWorker = function(zip, options, comment) { + var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName); + var entriesCount = 0; + try { + zip.forEach(function(relativePath, file) { + entriesCount++; + var compression = getCompression(file.options.compression, options.compression); + var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; + var dir = file.dir, date = file.date; + file._compressWorker(compression, compressionOptions).withStreamInfo("file", { + name: relativePath, + dir, + date, + comment: file.comment || "", + unixPermissions: file.unixPermissions, + dosPermissions: file.dosPermissions + }).pipe(zipFileWorker); + }); + zipFileWorker.entriesCount = entriesCount; + } catch (e) { + zipFileWorker.error(e); + } + return zipFileWorker; + }; +})); +//#endregion +//#region node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js +var require_NodejsStreamInputAdapter = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + /** + * A worker that use a nodejs stream as source. + * @constructor + * @param {String} filename the name of the file entry for this stream. + * @param {Readable} stream the nodejs stream. + */ + function NodejsStreamInputAdapter(filename, stream) { + GenericWorker.call(this, "Nodejs stream input adapter for " + filename); + this._upstreamEnded = false; + this._bindStream(stream); + } + utils.inherits(NodejsStreamInputAdapter, GenericWorker); + /** + * Prepare the stream and bind the callbacks on it. + * Do this ASAP on node 0.10 ! A lazy binding doesn't always work. + * @param {Stream} stream the nodejs stream to use. + */ + NodejsStreamInputAdapter.prototype._bindStream = function(stream) { + var self = this; + this._stream = stream; + stream.pause(); + stream.on("data", function(chunk) { + self.push({ + data: chunk, + meta: { percent: 0 } + }); + }).on("error", function(e) { + if (self.isPaused) this.generatedError = e; + else self.error(e); + }).on("end", function() { + if (self.isPaused) self._upstreamEnded = true; + else self.end(); + }); + }; + NodejsStreamInputAdapter.prototype.pause = function() { + if (!GenericWorker.prototype.pause.call(this)) return false; + this._stream.pause(); + return true; + }; + NodejsStreamInputAdapter.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) return false; + if (this._upstreamEnded) this.end(); + else this._stream.resume(); + return true; + }; + module.exports = NodejsStreamInputAdapter; +})); +//#endregion +//#region node_modules/jszip/lib/object.js +var require_object = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utf8 = require_utf8(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var StreamHelper = require_StreamHelper(); + var defaults = require_defaults(); + var CompressedObject = require_compressedObject(); + var ZipObject = require_zipObject(); + var generate = require_generate(); + var nodejsUtils = require_nodejsUtils(); + var NodejsStreamInputAdapter = require_NodejsStreamInputAdapter(); + /** + * Add a file in the current folder. + * @private + * @param {string} name the name of the file + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file + * @param {Object} originalOptions the options of the file + * @return {Object} the new file. + */ + var fileAdd = function(name, data, originalOptions) { + var dataType = utils.getTypeOf(data), parent; + var o = utils.extend(originalOptions || {}, defaults); + o.date = o.date || /* @__PURE__ */ new Date(); + if (o.compression !== null) o.compression = o.compression.toUpperCase(); + if (typeof o.unixPermissions === "string") o.unixPermissions = parseInt(o.unixPermissions, 8); + if (o.unixPermissions && o.unixPermissions & 16384) o.dir = true; + if (o.dosPermissions && o.dosPermissions & 16) o.dir = true; + if (o.dir) name = forceTrailingSlash(name); + if (o.createFolders && (parent = parentFolder(name))) folderAdd.call(this, parent, true); + var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false; + if (!originalOptions || typeof originalOptions.binary === "undefined") o.binary = !isUnicodeString; + if (data instanceof CompressedObject && data.uncompressedSize === 0 || o.dir || !data || data.length === 0) { + o.base64 = false; + o.binary = true; + data = ""; + o.compression = "STORE"; + dataType = "string"; + } + var zipObjectContent = null; + if (data instanceof CompressedObject || data instanceof GenericWorker) zipObjectContent = data; + else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) zipObjectContent = new NodejsStreamInputAdapter(name, data); + else zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64); + var object = new ZipObject(name, zipObjectContent, o); + this.files[name] = object; + }; + /** + * Find the parent folder of the path. + * @private + * @param {string} path the path to use + * @return {string} the parent folder, or "" + */ + var parentFolder = function(path) { + if (path.slice(-1) === "/") path = path.substring(0, path.length - 1); + var lastSlash = path.lastIndexOf("/"); + return lastSlash > 0 ? path.substring(0, lastSlash) : ""; + }; + /** + * Returns the path with a slash at the end. + * @private + * @param {String} path the path to check. + * @return {String} the path with a trailing slash. + */ + var forceTrailingSlash = function(path) { + if (path.slice(-1) !== "/") path += "/"; + return path; + }; + /** + * Add a (sub) folder in the current folder. + * @private + * @param {string} name the folder's name + * @param {boolean=} [createFolders] If true, automatically create sub + * folders. Defaults to false. + * @return {Object} the new folder. + */ + var folderAdd = function(name, createFolders) { + createFolders = typeof createFolders !== "undefined" ? createFolders : defaults.createFolders; + name = forceTrailingSlash(name); + if (!this.files[name]) fileAdd.call(this, name, null, { + dir: true, + createFolders + }); + return this.files[name]; + }; + /** + * Cross-window, cross-Node-context regular expression detection + * @param {Object} object Anything + * @return {Boolean} true if the object is a regular expression, + * false otherwise + */ + function isRegExp(object) { + return Object.prototype.toString.call(object) === "[object RegExp]"; + } + module.exports = { + /** + * @see loadAsync + */ + load: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + /** + * Call a callback function for each entry at this folder level. + * @param {Function} cb the callback function: + * function (relativePath, file) {...} + * It takes 2 arguments : the relative path and the file. + */ + forEach: function(cb) { + var filename, relativePath, file; + for (filename in this.files) { + file = this.files[filename]; + relativePath = filename.slice(this.root.length, filename.length); + if (relativePath && filename.slice(0, this.root.length) === this.root) cb(relativePath, file); + } + }, + /** + * Filter nested files/folders with the specified function. + * @param {Function} search the predicate to use : + * function (relativePath, file) {...} + * It takes 2 arguments : the relative path and the file. + * @return {Array} An array of matching elements. + */ + filter: function(search) { + var result = []; + this.forEach(function(relativePath, entry) { + if (search(relativePath, entry)) result.push(entry); + }); + return result; + }, + /** + * Add a file to the zip file, or search a file. + * @param {string|RegExp} name The name of the file to add (if data is defined), + * the name of the file to find (if no data) or a regex to match files. + * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded + * @param {Object} o File options + * @return {JSZip|Object|Array} this JSZip object (when adding a file), + * a file (when searching by string) or an array of files (when searching by regex). + */ + file: function(name, data, o) { + if (arguments.length === 1) if (isRegExp(name)) { + var regexp = name; + return this.filter(function(relativePath, file) { + return !file.dir && regexp.test(relativePath); + }); + } else { + var obj = this.files[this.root + name]; + if (obj && !obj.dir) return obj; + else return null; + } + else { + name = this.root + name; + fileAdd.call(this, name, data, o); + } + return this; + }, + /** + * Add a directory to the zip file, or search. + * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders. + * @return {JSZip} an object with the new directory as the root, or an array containing matching folders. + */ + folder: function(arg) { + if (!arg) return this; + if (isRegExp(arg)) return this.filter(function(relativePath, file) { + return file.dir && arg.test(relativePath); + }); + var name = this.root + arg; + var newFolder = folderAdd.call(this, name); + var ret = this.clone(); + ret.root = newFolder.name; + return ret; + }, + /** + * Delete a file, or a directory and all sub-files, from the zip + * @param {string} name the name of the file to delete + * @return {JSZip} this JSZip object + */ + remove: function(name) { + name = this.root + name; + var file = this.files[name]; + if (!file) { + if (name.slice(-1) !== "/") name += "/"; + file = this.files[name]; + } + if (file && !file.dir) delete this.files[name]; + else { + var kids = this.filter(function(relativePath, file) { + return file.name.slice(0, name.length) === name; + }); + for (var i = 0; i < kids.length; i++) delete this.files[kids[i].name]; + } + return this; + }, + /** + * @deprecated This method has been removed in JSZip 3.0, please check the upgrade guide. + */ + generate: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + /** + * Generate the complete zip file as an internal stream. + * @param {Object} options the options to generate the zip file : + * - compression, "STORE" by default. + * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob. + * @return {StreamHelper} the streamed zip file. + */ + generateInternalStream: function(options) { + var worker, opts = {}; + try { + opts = utils.extend(options || {}, { + streamFiles: false, + compression: "STORE", + compressionOptions: null, + type: "", + platform: "DOS", + comment: null, + mimeType: "application/zip", + encodeFileName: utf8.utf8encode + }); + opts.type = opts.type.toLowerCase(); + opts.compression = opts.compression.toUpperCase(); + if (opts.type === "binarystring") opts.type = "string"; + if (!opts.type) throw new Error("No output type specified."); + utils.checkSupport(opts.type); + if (opts.platform === "darwin" || opts.platform === "freebsd" || opts.platform === "linux" || opts.platform === "sunos") opts.platform = "UNIX"; + if (opts.platform === "win32") opts.platform = "DOS"; + var comment = opts.comment || this.comment || ""; + worker = generate.generateWorker(this, opts, comment); + } catch (e) { + worker = new GenericWorker("error"); + worker.error(e); + } + return new StreamHelper(worker, opts.type || "string", opts.mimeType); + }, + /** + * Generate the complete zip file asynchronously. + * @see generateInternalStream + */ + generateAsync: function(options, onUpdate) { + return this.generateInternalStream(options).accumulate(onUpdate); + }, + /** + * Generate the complete zip file asynchronously. + * @see generateInternalStream + */ + generateNodeStream: function(options, onUpdate) { + options = options || {}; + if (!options.type) options.type = "nodebuffer"; + return this.generateInternalStream(options).toNodejsStream(onUpdate); + } + }; +})); +//#endregion +//#region node_modules/jszip/lib/reader/DataReader.js +var require_DataReader = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + function DataReader(data) { + this.data = data; + this.length = data.length; + this.index = 0; + this.zero = 0; + } + DataReader.prototype = { + /** + * Check that the offset will not go too far. + * @param {string} offset the additional offset to check. + * @throws {Error} an Error if the offset is out of bounds. + */ + checkOffset: function(offset) { + this.checkIndex(this.index + offset); + }, + /** + * Check that the specified index will not be too far. + * @param {string} newIndex the index to check. + * @throws {Error} an Error if the index is out of bounds. + */ + checkIndex: function(newIndex) { + if (this.length < this.zero + newIndex || newIndex < 0) throw new Error("End of data reached (data length = " + this.length + ", asked index = " + newIndex + "). Corrupted zip ?"); + }, + /** + * Change the index. + * @param {number} newIndex The new index. + * @throws {Error} if the new index is out of the data. + */ + setIndex: function(newIndex) { + this.checkIndex(newIndex); + this.index = newIndex; + }, + /** + * Skip the next n bytes. + * @param {number} n the number of bytes to skip. + * @throws {Error} if the new index is out of the data. + */ + skip: function(n) { + this.setIndex(this.index + n); + }, + /** + * Get the byte at the specified index. + * @param {number} i the index to use. + * @return {number} a byte. + */ + byteAt: function() {}, + /** + * Get the next number with a given byte size. + * @param {number} size the number of bytes to read. + * @return {number} the corresponding number. + */ + readInt: function(size) { + var result = 0, i; + this.checkOffset(size); + for (i = this.index + size - 1; i >= this.index; i--) result = (result << 8) + this.byteAt(i); + this.index += size; + return result; + }, + /** + * Get the next string with a given byte size. + * @param {number} size the number of bytes to read. + * @return {string} the corresponding string. + */ + readString: function(size) { + return utils.transformTo("string", this.readData(size)); + }, + /** + * Get raw data without conversion, bytes. + * @param {number} size the number of bytes to read. + * @return {Object} the raw data, implementation specific. + */ + readData: function() {}, + /** + * Find the last occurrence of a zip signature (4 bytes). + * @param {string} sig the signature to find. + * @return {number} the index of the last occurrence, -1 if not found. + */ + lastIndexOfSignature: function() {}, + /** + * Read the signature (4 bytes) at the current position and compare it with sig. + * @param {string} sig the expected signature + * @return {boolean} true if the signature matches, false otherwise. + */ + readAndCheckSignature: function() {}, + /** + * Get the next date. + * @return {Date} the date. + */ + readDate: function() { + var dostime = this.readInt(4); + return new Date(Date.UTC((dostime >> 25 & 127) + 1980, (dostime >> 21 & 15) - 1, dostime >> 16 & 31, dostime >> 11 & 31, dostime >> 5 & 63, (dostime & 31) << 1)); + } + }; + module.exports = DataReader; +})); +//#endregion +//#region node_modules/jszip/lib/reader/ArrayReader.js +var require_ArrayReader = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var DataReader = require_DataReader(); + var utils = require_utils(); + function ArrayReader(data) { + DataReader.call(this, data); + for (var i = 0; i < this.data.length; i++) data[i] = data[i] & 255; + } + utils.inherits(ArrayReader, DataReader); + /** + * @see DataReader.byteAt + */ + ArrayReader.prototype.byteAt = function(i) { + return this.data[this.zero + i]; + }; + /** + * @see DataReader.lastIndexOfSignature + */ + ArrayReader.prototype.lastIndexOfSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3); + for (var i = this.length - 4; i >= 0; --i) if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) return i - this.zero; + return -1; + }; + /** + * @see DataReader.readAndCheckSignature + */ + ArrayReader.prototype.readAndCheckSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3), data = this.readData(4); + return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3]; + }; + /** + * @see DataReader.readData + */ + ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) return []; + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = ArrayReader; +})); +//#endregion +//#region node_modules/jszip/lib/reader/StringReader.js +var require_StringReader = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var DataReader = require_DataReader(); + var utils = require_utils(); + function StringReader(data) { + DataReader.call(this, data); + } + utils.inherits(StringReader, DataReader); + /** + * @see DataReader.byteAt + */ + StringReader.prototype.byteAt = function(i) { + return this.data.charCodeAt(this.zero + i); + }; + /** + * @see DataReader.lastIndexOfSignature + */ + StringReader.prototype.lastIndexOfSignature = function(sig) { + return this.data.lastIndexOf(sig) - this.zero; + }; + /** + * @see DataReader.readAndCheckSignature + */ + StringReader.prototype.readAndCheckSignature = function(sig) { + return sig === this.readData(4); + }; + /** + * @see DataReader.readData + */ + StringReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = StringReader; +})); +//#endregion +//#region node_modules/jszip/lib/reader/Uint8ArrayReader.js +var require_Uint8ArrayReader = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var ArrayReader = require_ArrayReader(); + var utils = require_utils(); + function Uint8ArrayReader(data) { + ArrayReader.call(this, data); + } + utils.inherits(Uint8ArrayReader, ArrayReader); + /** + * @see DataReader.readData + */ + Uint8ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) return /* @__PURE__ */ new Uint8Array(0); + var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = Uint8ArrayReader; +})); +//#endregion +//#region node_modules/jszip/lib/reader/NodeBufferReader.js +var require_NodeBufferReader = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var Uint8ArrayReader = require_Uint8ArrayReader(); + var utils = require_utils(); + function NodeBufferReader(data) { + Uint8ArrayReader.call(this, data); + } + utils.inherits(NodeBufferReader, Uint8ArrayReader); + /** + * @see DataReader.readData + */ + NodeBufferReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = NodeBufferReader; +})); +//#endregion +//#region node_modules/jszip/lib/reader/readerFor.js +var require_readerFor = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + var support = require_support(); + var ArrayReader = require_ArrayReader(); + var StringReader = require_StringReader(); + var NodeBufferReader = require_NodeBufferReader(); + var Uint8ArrayReader = require_Uint8ArrayReader(); + /** + * Create a reader adapted to the data. + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read. + * @return {DataReader} the data reader. + */ + module.exports = function(data) { + var type = utils.getTypeOf(data); + utils.checkSupport(type); + if (type === "string" && !support.uint8array) return new StringReader(data); + if (type === "nodebuffer") return new NodeBufferReader(data); + if (support.uint8array) return new Uint8ArrayReader(utils.transformTo("uint8array", data)); + return new ArrayReader(utils.transformTo("array", data)); + }; +})); +//#endregion +//#region node_modules/jszip/lib/zipEntry.js +var require_zipEntry = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var readerFor = require_readerFor(); + var utils = require_utils(); + var CompressedObject = require_compressedObject(); + var crc32fn = require_crc32$1(); + var utf8 = require_utf8(); + var compressions = require_compressions(); + var support = require_support(); + var MADE_BY_DOS = 0; + var MADE_BY_UNIX = 3; + /** + * Find a compression registered in JSZip. + * @param {string} compressionMethod the method magic to find. + * @return {Object|null} the JSZip compression object, null if none found. + */ + var findCompression = function(compressionMethod) { + for (var method in compressions) { + if (!Object.prototype.hasOwnProperty.call(compressions, method)) continue; + if (compressions[method].magic === compressionMethod) return compressions[method]; + } + return null; + }; + /** + * An entry in the zip file. + * @constructor + * @param {Object} options Options of the current file. + * @param {Object} loadOptions Options for loading the stream. + */ + function ZipEntry(options, loadOptions) { + this.options = options; + this.loadOptions = loadOptions; + } + ZipEntry.prototype = { + /** + * say if the file is encrypted. + * @return {boolean} true if the file is encrypted, false otherwise. + */ + isEncrypted: function() { + return (this.bitFlag & 1) === 1; + }, + /** + * say if the file has utf-8 filename/comment. + * @return {boolean} true if the filename/comment is in utf-8, false otherwise. + */ + useUTF8: function() { + return (this.bitFlag & 2048) === 2048; + }, + /** + * Read the local part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readLocalPart: function(reader) { + var compression, localExtraFieldsLength; + reader.skip(22); + this.fileNameLength = reader.readInt(2); + localExtraFieldsLength = reader.readInt(2); + this.fileName = reader.readData(this.fileNameLength); + reader.skip(localExtraFieldsLength); + if (this.compressedSize === -1 || this.uncompressedSize === -1) throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)"); + compression = findCompression(this.compressionMethod); + if (compression === null) throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); + this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); + }, + /** + * Read the central part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readCentralPart: function(reader) { + this.versionMadeBy = reader.readInt(2); + reader.skip(2); + this.bitFlag = reader.readInt(2); + this.compressionMethod = reader.readString(2); + this.date = reader.readDate(); + this.crc32 = reader.readInt(4); + this.compressedSize = reader.readInt(4); + this.uncompressedSize = reader.readInt(4); + var fileNameLength = reader.readInt(2); + this.extraFieldsLength = reader.readInt(2); + this.fileCommentLength = reader.readInt(2); + this.diskNumberStart = reader.readInt(2); + this.internalFileAttributes = reader.readInt(2); + this.externalFileAttributes = reader.readInt(4); + this.localHeaderOffset = reader.readInt(4); + if (this.isEncrypted()) throw new Error("Encrypted zip are not supported"); + reader.skip(fileNameLength); + this.readExtraFields(reader); + this.parseZIP64ExtraField(reader); + this.fileComment = reader.readData(this.fileCommentLength); + }, + /** + * Parse the external file attributes and get the unix/dos permissions. + */ + processAttributes: function() { + this.unixPermissions = null; + this.dosPermissions = null; + var madeBy = this.versionMadeBy >> 8; + this.dir = this.externalFileAttributes & 16 ? true : false; + if (madeBy === MADE_BY_DOS) this.dosPermissions = this.externalFileAttributes & 63; + if (madeBy === MADE_BY_UNIX) this.unixPermissions = this.externalFileAttributes >> 16 & 65535; + if (!this.dir && this.fileNameStr.slice(-1) === "/") this.dir = true; + }, + /** + * Parse the ZIP64 extra field and merge the info in the current ZipEntry. + * @param {DataReader} reader the reader to use. + */ + parseZIP64ExtraField: function() { + if (!this.extraFields[1]) return; + var extraReader = readerFor(this.extraFields[1].value); + if (this.uncompressedSize === utils.MAX_VALUE_32BITS) this.uncompressedSize = extraReader.readInt(8); + if (this.compressedSize === utils.MAX_VALUE_32BITS) this.compressedSize = extraReader.readInt(8); + if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) this.localHeaderOffset = extraReader.readInt(8); + if (this.diskNumberStart === utils.MAX_VALUE_32BITS) this.diskNumberStart = extraReader.readInt(4); + }, + /** + * Read the central part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readExtraFields: function(reader) { + var end = reader.index + this.extraFieldsLength, extraFieldId, extraFieldLength, extraFieldValue; + if (!this.extraFields) this.extraFields = {}; + while (reader.index + 4 < end) { + extraFieldId = reader.readInt(2); + extraFieldLength = reader.readInt(2); + extraFieldValue = reader.readData(extraFieldLength); + this.extraFields[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + reader.setIndex(end); + }, + /** + * Apply an UTF8 transformation if needed. + */ + handleUTF8: function() { + var decodeParamType = support.uint8array ? "uint8array" : "array"; + if (this.useUTF8()) { + this.fileNameStr = utf8.utf8decode(this.fileName); + this.fileCommentStr = utf8.utf8decode(this.fileComment); + } else { + var upath = this.findExtraFieldUnicodePath(); + if (upath !== null) this.fileNameStr = upath; + else { + var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); + this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); + } + var ucomment = this.findExtraFieldUnicodeComment(); + if (ucomment !== null) this.fileCommentStr = ucomment; + else { + var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); + this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); + } + } + }, + /** + * Find the unicode path declared in the extra field, if any. + * @return {String} the unicode path, null otherwise. + */ + findExtraFieldUnicodePath: function() { + var upathField = this.extraFields[28789]; + if (upathField) { + var extraReader = readerFor(upathField.value); + if (extraReader.readInt(1) !== 1) return null; + if (crc32fn(this.fileName) !== extraReader.readInt(4)) return null; + return utf8.utf8decode(extraReader.readData(upathField.length - 5)); + } + return null; + }, + /** + * Find the unicode comment declared in the extra field, if any. + * @return {String} the unicode comment, null otherwise. + */ + findExtraFieldUnicodeComment: function() { + var ucommentField = this.extraFields[25461]; + if (ucommentField) { + var extraReader = readerFor(ucommentField.value); + if (extraReader.readInt(1) !== 1) return null; + if (crc32fn(this.fileComment) !== extraReader.readInt(4)) return null; + return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); + } + return null; + } + }; + module.exports = ZipEntry; +})); +//#endregion +//#region node_modules/jszip/lib/zipEntries.js +var require_zipEntries = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var readerFor = require_readerFor(); + var utils = require_utils(); + var sig = require_signature(); + var ZipEntry = require_zipEntry(); + var support = require_support(); + /** + * All the entries in the zip file. + * @constructor + * @param {Object} loadOptions Options for loading the stream. + */ + function ZipEntries(loadOptions) { + this.files = []; + this.loadOptions = loadOptions; + } + ZipEntries.prototype = { + /** + * Check that the reader is on the specified signature. + * @param {string} expectedSignature the expected signature. + * @throws {Error} if it is an other signature. + */ + checkSignature: function(expectedSignature) { + if (!this.reader.readAndCheckSignature(expectedSignature)) { + this.reader.index -= 4; + var signature = this.reader.readString(4); + throw new Error("Corrupted zip or bug: unexpected signature (" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); + } + }, + /** + * Check if the given signature is at the given index. + * @param {number} askedIndex the index to check. + * @param {string} expectedSignature the signature to expect. + * @return {boolean} true if the signature is here, false otherwise. + */ + isSignature: function(askedIndex, expectedSignature) { + var currentIndex = this.reader.index; + this.reader.setIndex(askedIndex); + var result = this.reader.readString(4) === expectedSignature; + this.reader.setIndex(currentIndex); + return result; + }, + /** + * Read the end of the central directory. + */ + readBlockEndOfCentral: function() { + this.diskNumber = this.reader.readInt(2); + this.diskWithCentralDirStart = this.reader.readInt(2); + this.centralDirRecordsOnThisDisk = this.reader.readInt(2); + this.centralDirRecords = this.reader.readInt(2); + this.centralDirSize = this.reader.readInt(4); + this.centralDirOffset = this.reader.readInt(4); + this.zipCommentLength = this.reader.readInt(2); + var zipComment = this.reader.readData(this.zipCommentLength); + var decodeParamType = support.uint8array ? "uint8array" : "array"; + var decodeContent = utils.transformTo(decodeParamType, zipComment); + this.zipComment = this.loadOptions.decodeFileName(decodeContent); + }, + /** + * Read the end of the Zip 64 central directory. + * Not merged with the method readEndOfCentral : + * The end of central can coexist with its Zip64 brother, + * I don't want to read the wrong number of bytes ! + */ + readBlockZip64EndOfCentral: function() { + this.zip64EndOfCentralSize = this.reader.readInt(8); + this.reader.skip(4); + this.diskNumber = this.reader.readInt(4); + this.diskWithCentralDirStart = this.reader.readInt(4); + this.centralDirRecordsOnThisDisk = this.reader.readInt(8); + this.centralDirRecords = this.reader.readInt(8); + this.centralDirSize = this.reader.readInt(8); + this.centralDirOffset = this.reader.readInt(8); + this.zip64ExtensibleData = {}; + var extraDataSize = this.zip64EndOfCentralSize - 44, index = 0, extraFieldId, extraFieldLength, extraFieldValue; + while (index < extraDataSize) { + extraFieldId = this.reader.readInt(2); + extraFieldLength = this.reader.readInt(4); + extraFieldValue = this.reader.readData(extraFieldLength); + this.zip64ExtensibleData[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + }, + /** + * Read the end of the Zip 64 central directory locator. + */ + readBlockZip64EndOfCentralLocator: function() { + this.diskWithZip64CentralDirStart = this.reader.readInt(4); + this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); + this.disksCount = this.reader.readInt(4); + if (this.disksCount > 1) throw new Error("Multi-volumes zip are not supported"); + }, + /** + * Read the local files, based on the offset read in the central part. + */ + readLocalFiles: function() { + var i, file; + for (i = 0; i < this.files.length; i++) { + file = this.files[i]; + this.reader.setIndex(file.localHeaderOffset); + this.checkSignature(sig.LOCAL_FILE_HEADER); + file.readLocalPart(this.reader); + file.handleUTF8(); + file.processAttributes(); + } + }, + /** + * Read the central directory. + */ + readCentralDir: function() { + var file; + this.reader.setIndex(this.centralDirOffset); + while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { + file = new ZipEntry({ zip64: this.zip64 }, this.loadOptions); + file.readCentralPart(this.reader); + this.files.push(file); + } + if (this.centralDirRecords !== this.files.length) { + if (this.centralDirRecords !== 0 && this.files.length === 0) throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); + } + }, + /** + * Read the end of central directory. + */ + readEndOfCentral: function() { + var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); + if (offset < 0) if (!this.isSignature(0, sig.LOCAL_FILE_HEADER)) throw new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); + else throw new Error("Corrupted zip: can't find end of central directory"); + this.reader.setIndex(offset); + var endOfCentralDirOffset = offset; + this.checkSignature(sig.CENTRAL_DIRECTORY_END); + this.readBlockEndOfCentral(); + if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { + this.zip64 = true; + offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + if (offset < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); + this.reader.setIndex(offset); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + this.readBlockZip64EndOfCentralLocator(); + if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { + this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + if (this.relativeOffsetEndOfZip64CentralDir < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); + } + this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + this.readBlockZip64EndOfCentral(); + } + var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; + if (this.zip64) { + expectedEndOfCentralDirOffset += 20; + expectedEndOfCentralDirOffset += 12 + this.zip64EndOfCentralSize; + } + var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; + if (extraBytes > 0) if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {} else this.reader.zero = extraBytes; + else if (extraBytes < 0) throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); + }, + prepareReader: function(data) { + this.reader = readerFor(data); + }, + /** + * Read a zip file and create ZipEntries. + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. + */ + load: function(data) { + this.prepareReader(data); + this.readEndOfCentral(); + this.readCentralDir(); + this.readLocalFiles(); + } + }; + module.exports = ZipEntries; +})); +//#endregion +//#region node_modules/jszip/lib/load.js +var require_load = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var utils = require_utils(); + var external = require_external(); + var utf8 = require_utf8(); + var ZipEntries = require_zipEntries(); + var Crc32Probe = require_Crc32Probe(); + var nodejsUtils = require_nodejsUtils(); + /** + * Check the CRC32 of an entry. + * @param {ZipEntry} zipEntry the zip entry to check. + * @return {Promise} the result. + */ + function checkEntryCRC32(zipEntry) { + return new external.Promise(function(resolve, reject) { + var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe()); + worker.on("error", function(e) { + reject(e); + }).on("end", function() { + if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) reject(/* @__PURE__ */ new Error("Corrupted zip : CRC32 mismatch")); + else resolve(); + }).resume(); + }); + } + module.exports = function(data, options) { + var zip = this; + options = utils.extend(options || {}, { + base64: false, + checkCRC32: false, + optimizedBinaryString: false, + createFolders: false, + decodeFileName: utf8.utf8decode + }); + if (nodejsUtils.isNode && nodejsUtils.isStream(data)) return external.Promise.reject(/* @__PURE__ */ new Error("JSZip can't accept a stream when loading a zip file.")); + return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64).then(function(data) { + var zipEntries = new ZipEntries(options); + zipEntries.load(data); + return zipEntries; + }).then(function checkCRC32(zipEntries) { + var promises = [external.Promise.resolve(zipEntries)]; + var files = zipEntries.files; + if (options.checkCRC32) for (var i = 0; i < files.length; i++) promises.push(checkEntryCRC32(files[i])); + return external.Promise.all(promises); + }).then(function addFiles(results) { + var zipEntries = results.shift(); + var files = zipEntries.files; + for (var i = 0; i < files.length; i++) { + var input = files[i]; + var unsafeName = input.fileNameStr; + var safeName = utils.resolve(input.fileNameStr); + zip.file(safeName, input.decompressed, { + binary: true, + optimizedBinaryString: true, + date: input.date, + dir: input.dir, + comment: input.fileCommentStr.length ? input.fileCommentStr : null, + unixPermissions: input.unixPermissions, + dosPermissions: input.dosPermissions, + createFolders: options.createFolders + }); + if (!input.dir) zip.file(safeName).unsafeOriginalName = unsafeName; + } + if (zipEntries.zipComment.length) zip.comment = zipEntries.zipComment; + return zip; + }); + }; +})); +//#endregion +//#region node_modules/jszip/lib/index.js +var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** + * Representation a of zip file in js + * @constructor + */ + function JSZip() { + if (!(this instanceof JSZip)) return new JSZip(); + if (arguments.length) throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); + this.files = Object.create(null); + this.comment = null; + this.root = ""; + this.clone = function() { + var newObj = new JSZip(); + for (var i in this) if (typeof this[i] !== "function") newObj[i] = this[i]; + return newObj; + }; + } + JSZip.prototype = require_object(); + JSZip.prototype.loadAsync = require_load(); + JSZip.support = require_support(); + JSZip.defaults = require_defaults(); + JSZip.version = "3.10.1"; + JSZip.loadAsync = function(content, options) { + return new JSZip().loadAsync(content, options); + }; + JSZip.external = require_external(); + module.exports = JSZip; +})); +//#endregion +export { require_lib as t }; diff --git a/.vercel/output/functions/__server.func/_libs/langchain__core+mustache.mjs b/.vercel/output/functions/__server.func/_libs/langchain__core+mustache.mjs new file mode 100644 index 0000000..207cdb7 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/langchain__core+mustache.mjs @@ -0,0 +1,6996 @@ +import { $ as async_caller_exports, $t as CallbackManager, A as BaseOutputParser, An as HumanMessage, B as prompt_values_exports, Bn as tool_exports, Bt as GenerationChunk, C as makeInvalidToolCall, D as json_patch_exports, Dn as SystemMessage, Et as standard_schema_exports, Fn as parsePartialJson, G as Runnable, Gn as Serializable, Gt as concat$1, H as hash_exports, Ht as outputs_exports, I as tiktoken_exports, Jn as isEscapedObject, Jt as ensureConfig, K as RunnableBinding, Kn as get_lc_unique_name, Kt as stream_exports$2, L as ChatPromptValue, Ln as ToolMessage, N as BaseLanguageModel, Nn as ChatMessage, O as BaseCumulativeTransformOutputParser, P as base_exports$2, Q as AsyncCaller, R as ImagePromptValue, S as convertLangChainToolCallToOpenAI, Sn as AIMessageChunk, T as output_parsers_exports, U as sha256, Un as isBaseMessage, V as caches_exports, Vn as BaseMessage, Vt as RUN_KEY, W as messages_exports, Wt as IterableReadableStream, Xn as keyFromJson, Yn as unescapeValue, Z as graph_exports, Zn as mapKeys, Zt as singletons_exports, a as StructuredTool, an as console_exports, ar as __exportAll, b as JsonOutputKeyToolsParser, bn as getEnvironmentVariable, cn as Client, d as compat_exports, dn as callbackHandlerPrefersStreaming, et as log_stream_exports, f as finalizeContentBlock, fn as uuid_exports, in as tracer_langchain_exports, ir as errors_exports, j as runnables_exports, k as BaseLLMOutputParser, l as BaseChatModel, m as stream_exports$1, mn as v5, nn as parseCallbackConfigArg, nt as json_schema_exports, on as BaseTracer, q as RunnableLambda, qn as serializable_exports, r as function_calling_exports, rn as promises_exports, rr as addLangChainErrorFields, rt as toJsonSchema, s as tools_exports, sn as base_exports$3, tn as manager_exports, tt as compare, u as chat_models_exports, un as base_exports$1, v as structured_output_exports, vn as env_exports, w as parseToolCall, wn as coerceMessageLikeToMessage, x as JsonOutputToolsParser, xn as AIMessage, y as types_exports, z as StringPromptValue, zt as ChatGenerationChunk } from "./@langchain/anthropic+[...].mjs"; +//#region node_modules/@langchain/core/dist/load/import_constants.js +/** Auto-generated by import-constants plugin. Do not edit manually */ +var optionalImportEntrypoints = []; +//#endregion +//#region node_modules/@langchain/core/dist/index.js +var src_exports = /* @__PURE__ */ __exportAll({}); +//#endregion +//#region node_modules/@langchain/core/dist/agents.js +var agents_exports = /* @__PURE__ */ __exportAll({}); +//#endregion +//#region node_modules/@langchain/core/dist/chat_history.js +var chat_history_exports = /* @__PURE__ */ __exportAll({ + BaseChatMessageHistory: () => BaseChatMessageHistory, + BaseListChatMessageHistory: () => BaseListChatMessageHistory, + InMemoryChatMessageHistory: () => InMemoryChatMessageHistory +}); +/** +* Base class for all chat message histories. All chat message histories +* should extend this class. +*/ +var BaseChatMessageHistory = class extends Serializable { + /** + * Add a list of messages. + * + * Implementations should override this method to handle bulk addition of messages + * in an efficient manner to avoid unnecessary round-trips to the underlying store. + * + * @param messages - A list of BaseMessage objects to store. + */ + async addMessages(messages) { + for (const message of messages) await this.addMessage(message); + } +}; +/** +* Base class for all list chat message histories. All list chat message +* histories should extend this class. +*/ +var BaseListChatMessageHistory = class extends Serializable { + /** + * This is a convenience method for adding a human message string to the store. + * Please note that this is a convenience method. Code should favor the + * bulk addMessages interface instead to save on round-trips to the underlying + * persistence layer. + * This method may be deprecated in a future release. + */ + addUserMessage(message) { + return this.addMessage(new HumanMessage(message)); + } + /** + * This is a convenience method for adding an AI message string to the store. + * Please note that this is a convenience method. Code should favor the bulk + * addMessages interface instead to save on round-trips to the underlying + * persistence layer. + * This method may be deprecated in a future release. + */ + addAIMessage(message) { + return this.addMessage(new AIMessage(message)); + } + /** + * Add a list of messages. + * + * Implementations should override this method to handle bulk addition of messages + * in an efficient manner to avoid unnecessary round-trips to the underlying store. + * + * @param messages - A list of BaseMessage objects to store. + */ + async addMessages(messages) { + for (const message of messages) await this.addMessage(message); + } + /** + * Remove all messages from the store. + */ + clear() { + throw new Error("Not implemented."); + } +}; +/** +* Class for storing chat message history in-memory. It extends the +* BaseListChatMessageHistory class and provides methods to get, add, and +* clear messages. +*/ +var InMemoryChatMessageHistory = class extends BaseListChatMessageHistory { + lc_namespace = [ + "langchain", + "stores", + "message", + "in_memory" + ]; + messages = []; + constructor(messages) { + super(...arguments); + this.messages = messages ?? []; + } + /** + * Method to get all the messages stored in the ChatMessageHistory + * instance. + * @returns Array of stored BaseMessage instances. + */ + async getMessages() { + return this.messages; + } + /** + * Method to add a new message to the ChatMessageHistory instance. + * @param message The BaseMessage instance to add. + * @returns A promise that resolves when the message has been added. + */ + async addMessage(message) { + this.messages.push(message); + } + /** + * Method to clear all the messages from the ChatMessageHistory instance. + * @returns A promise that resolves when all messages have been cleared. + */ + async clear() { + this.messages = []; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/documents/document.js +/** +* Interface for interacting with a document. +*/ +var Document = class { + pageContent; + metadata; + /** + * An optional identifier for the document. + * + * Ideally this should be unique across the document collection and formatted + * as a UUID, but this will not be enforced. + */ + id; + constructor(fields) { + this.pageContent = fields.pageContent !== void 0 ? fields.pageContent.toString() : ""; + this.metadata = fields.metadata ?? {}; + this.id = fields.id; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/documents/transformers.js +/** +* Abstract base class for document transformation systems. +* +* A document transformation system takes an array of Documents and returns an +* array of transformed Documents. These arrays do not necessarily have to have +* the same length. +* +* One example of this is a text splitter that splits a large document into +* many smaller documents. +*/ +var BaseDocumentTransformer = class extends Runnable { + lc_namespace = [ + "langchain_core", + "documents", + "transformers" + ]; + /** + * Method to invoke the document transformation. This method calls the + * transformDocuments method with the provided input. + * @param input The input documents to be transformed. + * @param _options Optional configuration object to customize the behavior of callbacks. + * @returns A Promise that resolves to the transformed documents. + */ + invoke(input, _options) { + return this.transformDocuments(input); + } +}; +/** +* Class for document transformers that return exactly one transformed document +* for each input document. +*/ +var MappingDocumentTransformer = class extends BaseDocumentTransformer { + async transformDocuments(documents) { + const newDocuments = []; + for (const document of documents) { + const transformedDocument = await this._transformDocument(document); + newDocuments.push(transformedDocument); + } + return newDocuments; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/documents/index.js +var documents_exports = /* @__PURE__ */ __exportAll({ + BaseDocumentTransformer: () => BaseDocumentTransformer, + Document: () => Document, + MappingDocumentTransformer: () => MappingDocumentTransformer +}); +//#endregion +//#region node_modules/@langchain/core/dist/document_loaders/base.js +var base_exports = /* @__PURE__ */ __exportAll({ BaseDocumentLoader: () => BaseDocumentLoader }); +/** +* Abstract class that provides a default implementation for the +* loadAndSplit() method from the DocumentLoader interface. The load() +* method is left abstract and needs to be implemented by subclasses. +*/ +var BaseDocumentLoader = class {}; +//#endregion +//#region node_modules/@langchain/core/dist/document_loaders/langsmith.js +var langsmith_exports = /* @__PURE__ */ __exportAll({ LangSmithLoader: () => LangSmithLoader }); +/** +* Document loader integration with LangSmith. +* +* ## [Constructor args](https://api.js.langchain.com/interfaces/_langchain_core.document_loaders_langsmith.LangSmithLoaderFields.html) +* +*
+* Load +* +* ```typescript +* import { LangSmithLoader } from '@langchain/core/document_loaders/langsmith'; +* import { Client } from 'langsmith'; +* +* const langSmithClient = new Client({ +* apiKey: process.env.LANGSMITH_API_KEY, +* }) +* +* const loader = new LangSmithLoader({ +* datasetId: "9a3b36f7-b308-40a5-9b46-6613853b6330", +* limit: 1, +* }); +* +* const docs = await loader.load(); +* ``` +* +* ```txt +* [ +* { +* pageContent: '{\n "input_key_str": "string",\n "input_key_bool": true\n}', +* metadata: { +* id: '8523d9e9-c123-4b23-9b46-21021nds289e', +* created_at: '2024-08-19T17:09:14.806441+00:00', +* modified_at: '2024-08-19T17:09:14.806441+00:00', +* name: '#8517 @ brace-test-dataset', +* dataset_id: '9a3b36f7-b308-40a5-9b46-6613853b6330', +* source_run_id: null, +* metadata: [Object], +* inputs: [Object], +* outputs: [Object] +* } +* } +* ] +* ``` +*
+*/ +var LangSmithLoader = class extends BaseDocumentLoader { + datasetId; + datasetName; + exampleIds; + asOf; + splits; + inlineS3Urls; + offset; + limit; + metadata; + filter; + contentKey; + formatContent; + client; + constructor(fields) { + super(); + if (fields.client && fields.clientConfig) throw new Error("client and clientConfig cannot both be provided."); + this.client = fields.client ?? new Client(fields?.clientConfig); + this.contentKey = fields.contentKey ? fields.contentKey.split(".") : []; + this.formatContent = fields.formatContent ?? _stringify; + this.datasetId = fields.datasetId; + this.datasetName = fields.datasetName; + this.exampleIds = fields.exampleIds; + this.asOf = fields.asOf; + this.splits = fields.splits; + this.inlineS3Urls = fields.inlineS3Urls; + this.offset = fields.offset; + this.limit = fields.limit; + this.metadata = fields.metadata; + this.filter = fields.filter; + } + async load() { + const documents = []; + for await (const example of this.client.listExamples({ + datasetId: this.datasetId, + datasetName: this.datasetName, + exampleIds: this.exampleIds, + asOf: this.asOf, + splits: this.splits, + inlineS3Urls: this.inlineS3Urls, + offset: this.offset, + limit: this.limit, + metadata: this.metadata, + filter: this.filter + })) { + let content = example.inputs; + for (const key of this.contentKey) content = content[key]; + const contentStr = this.formatContent(content); + const metadata = example; + ["created_at", "modified_at"].forEach((k) => { + if (k in metadata) { + if (typeof metadata[k] === "object") metadata[k] = metadata[k].toString(); + } + }); + documents.push({ + pageContent: contentStr, + metadata + }); + } + return documents; + } +}; +function _stringify(x) { + if (typeof x === "string") return x; + else try { + return JSON.stringify(x, null, 2); + } catch { + return String(x); + } +} +//#endregion +//#region node_modules/@langchain/core/dist/embeddings.js +var embeddings_exports = /* @__PURE__ */ __exportAll({ Embeddings: () => Embeddings }); +/** +* An abstract class that provides methods for embedding documents and +* queries using LangChain. +*/ +var Embeddings = class { + /** + * The async caller should be used by subclasses to make any async calls, + * which will thus benefit from the concurrency and retry logic. + */ + caller; + constructor(params) { + this.caller = new AsyncCaller(params ?? {}); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/example_selectors/base.js +/** +* Base class for example selectors. +*/ +var BaseExampleSelector = class extends Serializable { + lc_namespace = [ + "langchain_core", + "example_selectors", + "base" + ]; +}; +//#endregion +//#region node_modules/@langchain/core/dist/example_selectors/conditional.js +/** +* Abstract class that defines the interface for selecting a prompt for a +* given language model. +*/ +var BasePromptSelector = class { + /** + * Asynchronous version of `getPrompt` that also accepts an options object + * for partial variables. + * @param llm The language model for which to get a prompt. + * @param options Optional object for partial variables. + * @returns A Promise that resolves to a prompt template. + */ + async getPromptAsync(llm, options) { + return this.getPrompt(llm).partial(options?.partialVariables ?? {}); + } +}; +/** +* Concrete implementation of `BasePromptSelector` that selects a prompt +* based on a set of conditions. It has a default prompt that it returns +* if none of the conditions are met. +*/ +var ConditionalPromptSelector = class extends BasePromptSelector { + defaultPrompt; + conditionals; + constructor(default_prompt, conditionals = []) { + super(); + this.defaultPrompt = default_prompt; + this.conditionals = conditionals; + } + /** + * Method that selects a prompt based on a set of conditions. If none of + * the conditions are met, it returns the default prompt. + * @param llm The language model for which to get a prompt. + * @returns A prompt template. + */ + getPrompt(llm) { + for (const [condition, prompt] of this.conditionals) if (condition(llm)) return prompt; + return this.defaultPrompt; + } +}; +/** +* Type guard function that checks if a given language model is of type +* `BaseLLM`. +*/ +function isLLM(llm) { + return llm._modelType() === "base_llm"; +} +/** +* Type guard function that checks if a given language model is of type +* `BaseChatModel`. +*/ +function isChatModel(llm) { + return llm._modelType() === "base_chat_model"; +} +//#endregion +//#region node_modules/@langchain/core/dist/example_selectors/length_based.js +/** +* Calculates the length of a text based on the number of words and lines. +*/ +function getLengthBased(text) { + return text.split(/\n| /).length; +} +/** +* A specialized example selector that selects examples based on their +* length, ensuring that the total length of the selected examples does +* not exceed a specified maximum length. +* @example +* ```typescript +* const exampleSelector = new LengthBasedExampleSelector( +* [ +* { input: "happy", output: "sad" }, +* { input: "tall", output: "short" }, +* { input: "energetic", output: "lethargic" }, +* { input: "sunny", output: "gloomy" }, +* { input: "windy", output: "calm" }, +* ], +* { +* examplePrompt: new PromptTemplate({ +* inputVariables: ["input", "output"], +* template: "Input: {input}\nOutput: {output}", +* }), +* maxLength: 25, +* }, +* ); +* const dynamicPrompt = new FewShotPromptTemplate({ +* exampleSelector, +* examplePrompt: new PromptTemplate({ +* inputVariables: ["input", "output"], +* template: "Input: {input}\nOutput: {output}", +* }), +* prefix: "Give the antonym of every input", +* suffix: "Input: {adjective}\nOutput:", +* inputVariables: ["adjective"], +* }); +* console.log(dynamicPrompt.format({ adjective: "big" })); +* console.log( +* dynamicPrompt.format({ +* adjective: +* "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else", +* }), +* ); +* ``` +*/ +var LengthBasedExampleSelector = class LengthBasedExampleSelector extends BaseExampleSelector { + examples = []; + examplePrompt; + getTextLength = getLengthBased; + maxLength = 2048; + exampleTextLengths = []; + constructor(data) { + super(data); + this.examplePrompt = data.examplePrompt; + this.maxLength = data.maxLength ?? 2048; + this.getTextLength = data.getTextLength ?? getLengthBased; + } + /** + * Adds an example to the list of examples and calculates its length. + * @param example The example to be added. + * @returns Promise that resolves when the example has been added and its length calculated. + */ + async addExample(example) { + this.examples.push(example); + const stringExample = await this.examplePrompt.format(example); + this.exampleTextLengths.push(this.getTextLength(stringExample)); + } + /** + * Calculates the lengths of the examples. + * @param v Array of lengths of the examples. + * @param values Instance of LengthBasedExampleSelector. + * @returns Promise that resolves with an array of lengths of the examples. + */ + async calculateExampleTextLengths(v, values) { + if (v.length > 0) return v; + const { examples, examplePrompt } = values; + return (await Promise.all(examples.map((eg) => examplePrompt.format(eg)))).map((eg) => this.getTextLength(eg)); + } + /** + * Selects examples until the total length of the selected examples + * reaches the maxLength. + * @param inputVariables The input variables for the examples. + * @returns Promise that resolves with an array of selected examples. + */ + async selectExamples(inputVariables) { + const inputs = Object.values(inputVariables).join(" "); + let remainingLength = this.maxLength - this.getTextLength(inputs); + let i = 0; + const examples = []; + while (remainingLength > 0 && i < this.examples.length) { + const newLength = remainingLength - this.exampleTextLengths[i]; + if (newLength < 0) break; + else { + examples.push(this.examples[i]); + remainingLength = newLength; + } + i += 1; + } + return examples; + } + /** + * Creates a new instance of LengthBasedExampleSelector and adds a list of + * examples to it. + * @param examples Array of examples to be added. + * @param args Input parameters for the LengthBasedExampleSelector. + * @returns Promise that resolves with a new instance of LengthBasedExampleSelector with the examples added. + */ + static async fromExamples(examples, args) { + const selector = new LengthBasedExampleSelector(args); + await Promise.all(examples.map((eg) => selector.addExample(eg))); + return selector; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js +function sortedValues(values) { + return Object.keys(values).sort().map((key) => values[key]); +} +/** +* Class that selects examples based on semantic similarity. It extends +* the BaseExampleSelector class. +* @example +* ```typescript +* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( +* [ +* { input: "happy", output: "sad" }, +* { input: "tall", output: "short" }, +* { input: "energetic", output: "lethargic" }, +* { input: "sunny", output: "gloomy" }, +* { input: "windy", output: "calm" }, +* ], +* new OpenAIEmbeddings(), +* HNSWLib, +* { k: 1 }, +* ); +* const dynamicPrompt = new FewShotPromptTemplate({ +* exampleSelector, +* examplePrompt: PromptTemplate.fromTemplate( +* "Input: {input}\nOutput: {output}", +* ), +* prefix: "Give the antonym of every input", +* suffix: "Input: {adjective}\nOutput:", +* inputVariables: ["adjective"], +* }); +* console.log(await dynamicPrompt.format({ adjective: "rainy" })); +* ``` +*/ +var SemanticSimilarityExampleSelector = class SemanticSimilarityExampleSelector extends BaseExampleSelector { + vectorStoreRetriever; + exampleKeys; + inputKeys; + constructor(data) { + super(data); + 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".`); + } + /** + * Method that adds a new example to the vectorStore. The example is + * converted to a string and added to the vectorStore as a document. + * @param example The example to be added to the vectorStore. + * @returns Promise that resolves when the example has been added to the vectorStore. + */ + async addExample(example) { + const stringExample = sortedValues((this.inputKeys ?? Object.keys(example)).reduce((acc, key) => ({ + ...acc, + [key]: example[key] + }), {})).join(" "); + await this.vectorStoreRetriever.addDocuments([new Document({ + pageContent: stringExample, + metadata: example + })]); + } + /** + * Method that selects which examples to use based on semantic similarity. + * It performs a similarity search in the vectorStore using the input + * variables and returns the examples with the highest similarity. + * @param inputVariables The input variables used for the similarity search. + * @returns Promise that resolves with an array of the selected examples. + */ + async selectExamples(inputVariables) { + const query = sortedValues((this.inputKeys ?? Object.keys(inputVariables)).reduce((acc, key) => ({ + ...acc, + [key]: inputVariables[key] + }), {})).join(" "); + const examples = (await this.vectorStoreRetriever.invoke(query)).map((doc) => doc.metadata); + if (this.exampleKeys) return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ + ...acc, + [key]: example[key] + }), {})); + return examples; + } + /** + * Static method that creates a new instance of + * SemanticSimilarityExampleSelector. It takes a list of examples, an + * instance of Embeddings, a VectorStore class, and an options object as + * parameters. It converts the examples to strings, creates a VectorStore + * from the strings and the embeddings, and returns a new + * SemanticSimilarityExampleSelector with the created VectorStore and the + * options provided. + * @param examples The list of examples to be used. + * @param embeddings The instance of Embeddings to be used. + * @param vectorStoreCls The VectorStore class to be used. + * @param options The options object for the SemanticSimilarityExampleSelector. + * @returns Promise that resolves with a new instance of SemanticSimilarityExampleSelector. + */ + static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { + const inputKeys = options.inputKeys ?? null; + const stringExamples = examples.map((example) => sortedValues(inputKeys ? inputKeys.reduce((acc, key) => ({ + ...acc, + [key]: example[key] + }), {}) : example).join(" ")); + return new SemanticSimilarityExampleSelector({ + vectorStore: await vectorStoreCls.fromTexts(stringExamples, examples, embeddings, options), + k: options.k ?? 4, + exampleKeys: options.exampleKeys, + inputKeys: options.inputKeys + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/example_selectors/index.js +var example_selectors_exports = /* @__PURE__ */ __exportAll({ + BaseExampleSelector: () => BaseExampleSelector, + BasePromptSelector: () => BasePromptSelector, + ConditionalPromptSelector: () => ConditionalPromptSelector, + LengthBasedExampleSelector: () => LengthBasedExampleSelector, + SemanticSimilarityExampleSelector: () => SemanticSimilarityExampleSelector, + isChatModel: () => isChatModel, + isLLM: () => isLLM +}); +//#endregion +//#region node_modules/@langchain/core/dist/indexing/record_manager.js +var UUIDV5_NAMESPACE = "10f90ea3-90a4-4962-bf75-83a0f3c1c62a"; +var RecordManager = class extends Serializable { + lc_namespace = ["langchain", "recordmanagers"]; +}; +//#endregion +//#region node_modules/@langchain/core/dist/indexing/base.js +/** +* HashedDocument is a Document with hashes calculated. +* Hashes are calculated based on page content and metadata. +* It is used for indexing. +*/ +var _HashedDocument = class { + uid; + hash_; + contentHash; + metadataHash; + pageContent; + metadata; + keyEncoder = sha256; + constructor(fields) { + this.uid = fields.uid; + this.pageContent = fields.pageContent; + this.metadata = fields.metadata; + } + makeDefaultKeyEncoder(keyEncoderFn) { + this.keyEncoder = keyEncoderFn; + } + calculateHashes() { + const forbiddenKeys = [ + "hash_", + "content_hash", + "metadata_hash" + ]; + for (const key of forbiddenKeys) if (key in this.metadata) throw new Error(`Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(", ")}]`); + const contentHash = this._hashStringToUUID(this.pageContent); + try { + const metadataHash = this._hashNestedDictToUUID(this.metadata); + this.contentHash = contentHash; + this.metadataHash = metadataHash; + } catch (e) { + throw new Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`); + } + this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash); + if (!this.uid) this.uid = this.hash_; + } + toDocument() { + return new Document({ + pageContent: this.pageContent, + metadata: this.metadata + }); + } + static fromDocument(document, uid) { + const doc = new this({ + pageContent: document.pageContent, + metadata: document.metadata, + uid: uid || document.uid + }); + doc.calculateHashes(); + return doc; + } + _hashStringToUUID(inputString) { + return v5(this.keyEncoder(inputString), UUIDV5_NAMESPACE); + } + _hashNestedDictToUUID(data) { + const serialized_data = JSON.stringify(data, Object.keys(data).sort()); + return v5(this.keyEncoder(serialized_data), UUIDV5_NAMESPACE); + } +}; +function _batch(size, iterable) { + const batches = []; + let currentBatch = []; + iterable.forEach((item) => { + currentBatch.push(item); + if (currentBatch.length >= size) { + batches.push(currentBatch); + currentBatch = []; + } + }); + if (currentBatch.length > 0) batches.push(currentBatch); + return batches; +} +function _deduplicateInOrder(hashedDocuments) { + const seen = /* @__PURE__ */ new Set(); + const deduplicated = []; + for (const hashedDoc of hashedDocuments) { + if (!hashedDoc.hash_) throw new Error("Hashed document does not have a hash"); + if (!seen.has(hashedDoc.hash_)) { + seen.add(hashedDoc.hash_); + deduplicated.push(hashedDoc); + } + } + return deduplicated; +} +function _getSourceIdAssigner(sourceIdKey) { + if (sourceIdKey === null) return (_doc) => null; + else if (typeof sourceIdKey === "string") return (doc) => doc.metadata[sourceIdKey]; + else if (typeof sourceIdKey === "function") return sourceIdKey; + else throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`); +} +var _isBaseDocumentLoader = (arg) => { + if ("load" in arg && typeof arg.load === "function" && "loadAndSplit" in arg && typeof arg.loadAndSplit === "function") return true; + return false; +}; +/** +* Index data from the doc source into the vector store. +* +* Indexing functionality uses a manager to keep track of which documents +* are in the vector store. +* +* This allows us to keep track of which documents were updated, and which +* documents were deleted, which documents should be skipped. +* +* For the time being, documents are indexed using their hashes, and users +* are not able to specify the uid of the document. +* +* @param {IndexArgs} args +* @param {BaseDocumentLoader | DocumentInterface[]} args.docsSource The source of documents to index. Can be a DocumentLoader or a list of Documents. +* @param {RecordManagerInterface} args.recordManager The record manager to use for keeping track of indexed documents. +* @param {VectorStore} args.vectorStore The vector store to use for storing the documents. +* @param {IndexOptions | undefined} args.options Options for indexing. +* @returns {Promise} +*/ +async function index(args) { + const { docsSource, recordManager, vectorStore, options } = args; + const { batchSize = 100, cleanup, sourceIdKey, cleanupBatchSize = 1e3, forceUpdate = false } = options ?? {}; + if (cleanup === "incremental" && !sourceIdKey) throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'."); + const docs = _isBaseDocumentLoader(docsSource) ? await docsSource.load() : docsSource; + const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null); + const indexStartDt = await recordManager.getTime(); + let numAdded = 0; + let numDeleted = 0; + let numUpdated = 0; + let numSkipped = 0; + const batches = _batch(batchSize ?? 100, docs); + for (const batch of batches) { + const hashedDocs = _deduplicateInOrder(batch.map((doc) => _HashedDocument.fromDocument(doc))); + const sourceIds = hashedDocs.map((doc) => sourceIdAssigner(doc)); + if (cleanup === "incremental") hashedDocs.forEach((_hashedDoc, index) => { + if (sourceIds[index] === null) throw new Error("sourceIdKey must be provided when cleanup is incremental"); + }); + const batchExists = await recordManager.exists(hashedDocs.map((doc) => doc.uid)); + const uids = []; + const docsToIndex = []; + const docsToUpdate = []; + const seenDocs = /* @__PURE__ */ new Set(); + hashedDocs.forEach((hashedDoc, i) => { + if (batchExists[i]) if (forceUpdate) seenDocs.add(hashedDoc.uid); + else { + docsToUpdate.push(hashedDoc.uid); + return; + } + uids.push(hashedDoc.uid); + docsToIndex.push(hashedDoc.toDocument()); + }); + if (docsToUpdate.length > 0) { + await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt }); + numSkipped += docsToUpdate.length; + } + if (docsToIndex.length > 0) { + await vectorStore.addDocuments(docsToIndex, { ids: uids }); + numAdded += docsToIndex.length - seenDocs.size; + numUpdated += seenDocs.size; + } + await recordManager.update(hashedDocs.map((doc) => doc.uid), { + timeAtLeast: indexStartDt, + groupIds: sourceIds + }); + if (cleanup === "incremental") { + sourceIds.forEach((sourceId) => { + if (!sourceId) throw new Error("Source id cannot be null"); + }); + const uidsToDelete = await recordManager.listKeys({ + before: indexStartDt, + groupIds: sourceIds + }); + if (uidsToDelete.length > 0) { + await vectorStore.delete({ ids: uidsToDelete }); + await recordManager.deleteKeys(uidsToDelete); + numDeleted += uidsToDelete.length; + } + } + } + if (cleanup === "full") { + let uidsToDelete = await recordManager.listKeys({ + before: indexStartDt, + limit: cleanupBatchSize + }); + while (uidsToDelete.length > 0) { + await vectorStore.delete({ ids: uidsToDelete }); + await recordManager.deleteKeys(uidsToDelete); + numDeleted += uidsToDelete.length; + uidsToDelete = await recordManager.listKeys({ + before: indexStartDt, + limit: cleanupBatchSize + }); + } + } + return { + numAdded, + numDeleted, + numUpdated, + numSkipped + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/indexing/index.js +var indexing_exports = /* @__PURE__ */ __exportAll({ + RecordManager: () => RecordManager, + UUIDV5_NAMESPACE: () => UUIDV5_NAMESPACE, + _HashedDocument: () => _HashedDocument, + _batch: () => _batch, + _deduplicateInOrder: () => _deduplicateInOrder, + _getSourceIdAssigner: () => _getSourceIdAssigner, + _isBaseDocumentLoader: () => _isBaseDocumentLoader, + index: () => index +}); +//#endregion +//#region node_modules/@langchain/core/dist/language_models/openai_completions_stream.js +/** +* Converts OpenAI Chat Completions-shaped stream chunks into +* {@link ChatModelStreamEvent}s. +* +* Used by `@langchain/openai` and OpenAI-compatible providers (Groq, Mistral, +* OpenRouter, IBM watsonx, etc.) without requiring a dependency on +* `@langchain/openai`. +* +* @module +*/ +var openai_completions_stream_exports = /* @__PURE__ */ __exportAll({ convertOpenAICompletionsStream: () => convertOpenAICompletionsStream }); +/** +* Convert an async iterable of OpenAI Chat Completions-shaped stream chunks into +* LangChain `ChatModelStreamEvent`s with typed deltas. +*/ +async function* convertOpenAICompletionsStream(source, options = {}) { + const shouldStreamUsage = options.streamUsage ?? true; + const provider = options.provider ?? "openai"; + const mapChunk = options.mapChunk; + const blockAccumulators = /* @__PURE__ */ new Map(); + const blockKeyToIndex = /* @__PURE__ */ new Map(); + let nextBlockIndex = 0; + let messageStarted = false; + let usageSnapshot; + let finishReason; + let responseMetadata; + let emittedProviderMetadata = false; + const getOrCreateBlockIndex = (key, initial) => { + const existing = blockKeyToIndex.get(key); + if (existing !== void 0) return { + index: existing, + isNew: false + }; + const index = nextBlockIndex++; + blockKeyToIndex.set(key, index); + blockAccumulators.set(index, { ...initial }); + return { + index, + isNew: true + }; + }; + for await (let data of source) { + if (mapChunk) data = mapChunk(data); + if (!messageStarted) { + messageStarted = true; + yield { + event: "message-start", + id: data.id + }; + } + if (!emittedProviderMetadata && (data.model || data.service_tier)) { + emittedProviderMetadata = true; + yield { + event: "provider", + provider, + name: "stream_metadata", + payload: { + model: data.model, + service_tier: data.service_tier + } + }; + } + if (data.usage && shouldStreamUsage) { + usageSnapshot = buildUsageSnapshot(data.usage); + yield { + event: "usage", + usage: usageSnapshot + }; + } + const groqUsage = data.x_groq?.usage; + if (groqUsage && shouldStreamUsage) { + usageSnapshot = buildGroqUsageSnapshot(groqUsage); + yield { + event: "usage", + usage: usageSnapshot + }; + } + const choice = data.choices?.[0]; + if (!choice) continue; + if (choice.finish_reason != null) { + finishReason = mapFinishReason(choice.finish_reason); + responseMetadata = buildResponseMetadata(data, choice); + } + const { delta } = choice; + if (!delta) continue; + const reasoningText = getReasoningDeltaText(delta); + if (reasoningText) { + const { index, isNew } = getOrCreateBlockIndex("reasoning", { + type: "reasoning", + reasoning: "" + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "reasoning", + reasoning: "" + } + }; + const acc = blockAccumulators.get(index); + acc.reasoning = (acc.reasoning ?? "") + reasoningText; + yield { + event: "content-block-delta", + index, + delta: { + type: "reasoning-delta", + reasoning: reasoningText + } + }; + } + if (delta.content) { + const { index, isNew } = getOrCreateBlockIndex("text", { + type: "text", + text: "" + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "text", + text: "" + } + }; + const acc = blockAccumulators.get(index); + acc.text = (acc.text ?? "") + delta.content; + yield { + event: "content-block-delta", + index, + delta: { + type: "text-delta", + text: delta.content + } + }; + } + if (Array.isArray(delta.tool_calls)) for (const rawToolCall of delta.tool_calls) { + const toolIndex = rawToolCall.index ?? 0; + const { index, isNew } = getOrCreateBlockIndex(`tool:${toolIndex}`, { + type: "tool_call_chunk", + id: rawToolCall.id, + name: rawToolCall.function?.name, + args: "", + index: toolIndex + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "tool_call_chunk", + id: rawToolCall.id, + name: rawToolCall.function?.name, + args: "", + index: toolIndex + } + }; + const acc = blockAccumulators.get(index); + if (rawToolCall.id != null) acc.id = rawToolCall.id; + if (rawToolCall.function?.name != null) acc.name = rawToolCall.function.name; + const argDelta = rawToolCall.function?.arguments ?? ""; + acc.args = (acc.args ?? "") + argDelta; + yield { + event: "content-block-delta", + index, + delta: { + type: "block-delta", + fields: { + type: "tool_call_chunk", + ...acc.id != null ? { id: acc.id } : {}, + ...acc.name != null ? { name: acc.name } : {}, + args: acc.args + } + } + }; + } + if (delta.audio) { + const { index, isNew } = getOrCreateBlockIndex("audio", { + type: "audio", + id: delta.audio.id, + data: "", + mimeType: "audio/pcm", + transcript: delta.audio.transcript ?? "" + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "audio", + id: delta.audio.id, + data: "", + mimeType: "audio/pcm", + transcript: delta.audio.transcript ?? "" + } + }; + const acc = blockAccumulators.get(index); + if (delta.audio.transcript) { + acc.transcript = (acc.transcript ?? "") + delta.audio.transcript; + yield { + event: "content-block-delta", + index, + delta: { + type: "block-delta", + fields: { + type: "audio", + transcript: acc.transcript + } + } + }; + } + if (delta.audio.data) { + acc.data = (acc.data ?? "") + delta.audio.data; + yield { + event: "content-block-delta", + index, + delta: { + type: "data-delta", + data: delta.audio.data, + encoding: "base64" + } + }; + } + } + if (delta.function_call) yield { + event: "provider", + provider, + name: "function_call", + payload: delta.function_call + }; + if (choice.logprobs) yield { + event: "provider", + provider, + name: "logprobs", + payload: choice.logprobs + }; + } + for (const [index, acc] of blockAccumulators) yield { + event: "content-block-finish", + index, + content: finalizeContentBlock(acc) + }; + yield { + event: "message-finish", + reason: finishReason, + ...usageSnapshot ? { usage: usageSnapshot } : {}, + ...responseMetadata ? { responseMetadata } : {} + }; +} +function getReasoningDeltaText(delta) { + const reasoning = delta.reasoning_content ?? delta.reasoning; + return typeof reasoning === "string" && reasoning.length > 0 ? reasoning : void 0; +} +function buildGroqUsageSnapshot(usage) { + return { + input_tokens: usage.prompt_tokens ?? 0, + output_tokens: usage.completion_tokens ?? 0, + total_tokens: usage.total_tokens ?? 0 + }; +} +function mapFinishReason(reason) { + switch (reason) { + case "stop": return "stop"; + case "length": + case "max_tokens": return "length"; + case "tool_calls": + case "function_call": return "tool_use"; + case "content_filter": return "content_filter"; + default: return "stop"; + } +} +function buildUsageSnapshot(usage) { + const inputTokenDetails = { + ...usage.prompt_tokens_details?.audio_tokens != null && { audio: usage.prompt_tokens_details.audio_tokens }, + ...usage.prompt_tokens_details?.cached_tokens != null && { cache_read: usage.prompt_tokens_details.cached_tokens } + }; + const outputTokenDetails = { + ...usage.completion_tokens_details?.audio_tokens != null && { audio: usage.completion_tokens_details.audio_tokens }, + ...usage.completion_tokens_details?.reasoning_tokens != null && { reasoning: usage.completion_tokens_details.reasoning_tokens } + }; + return { + input_tokens: usage.prompt_tokens ?? 0, + output_tokens: usage.completion_tokens ?? 0, + total_tokens: usage.total_tokens ?? 0, + ...Object.keys(inputTokenDetails).length > 0 && { input_token_details: inputTokenDetails }, + ...Object.keys(outputTokenDetails).length > 0 && { output_token_details: outputTokenDetails } + }; +} +function buildResponseMetadata(data, choice) { + return { + model_provider: "openai", + model_name: data.model, + system_fingerprint: data.system_fingerprint, + service_tier: data.service_tier, + finish_reason: choice.finish_reason, + ...data.usage ? { usage: data.usage } : {} + }; +} +//#endregion +//#region node_modules/@langchain/core/dist/language_models/event.js +var event_exports = /* @__PURE__ */ __exportAll({}); +//#endregion +//#region node_modules/@langchain/core/dist/language_models/llms.js +var llms_exports = /* @__PURE__ */ __exportAll({ + BaseLLM: () => BaseLLM, + LLM: () => LLM +}); +/** +* LLM Wrapper. Takes in a prompt (or prompts) and returns a string. +*/ +var BaseLLM = class BaseLLM extends BaseLanguageModel { + lc_namespace = [ + "langchain", + "llms", + this._llmType() + ]; + /** + * This method takes an input and options, and returns a string. It + * converts the input to a prompt value and generates a result based on + * the prompt. + * @param input Input for the LLM. + * @param options Options for the LLM call. + * @returns A string result based on the prompt. + */ + async invoke(input, options) { + const promptValue = BaseLLM._convertInputToPromptValue(input); + return (await this.generatePrompt([promptValue], options, options?.callbacks)).generations[0][0].text; + } + async *_streamResponseChunks(_input, _options, _runManager) { + throw new Error("Not implemented."); + } + _separateRunnableConfigFromCallOptionsCompat(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + 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._separateRunnableConfigFromCallOptionsCompat(options); + const invocationParams = this.invocationParams(callOptions); + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: callOptions, + invocation_params: invocationParams, + batch_size: 1 + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); + let generation = new GenerationChunk({ text: "" }); + try { + for await (const chunk of this._streamResponseChunks(prompt.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]] }))); + } + } + /** + * This method takes prompt values, options, and callbacks, and generates + * a result based on the prompts. + * @param promptValues Prompt values for the LLM. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns An LLMResult based on the prompts. + */ + async generatePrompt(promptValues, options, callbacks) { + const prompts = promptValues.map((promptValue) => promptValue.toString()); + return this.generate(prompts, options, callbacks); + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(_options) { + return {}; + } + _flattenLLMResult(llmResult) { + const llmResults = []; + for (let i = 0; i < llmResult.generations.length; i += 1) { + const genList = llmResult.generations[i]; + if (i === 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; + } + /** @ignore */ + async _generateUncached(prompts, parsedOptions, handledOptions, startedRunManagers) { + let runManagers; + if (startedRunManagers !== void 0 && startedRunManagers.length === prompts.length) runManagers = startedRunManagers; + else { + const invocationParams = this.invocationParams(parsedOptions); + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: parsedOptions, + invocation_params: invocationParams, + batch_size: prompts.length + }; + runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, handledOptions.runId, void 0, extra, void 0, void 0, handledOptions?.runName); + } + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + let output; + if (hasStreamingHandler && prompts.length === 1 && this._streamResponseChunks !== BaseLLM.prototype._streamResponseChunks) try { + const stream = await this._streamResponseChunks(prompts[0], parsedOptions, runManagers?.[0]); + let aggregated; + for await (const chunk of stream) if (aggregated === void 0) aggregated = chunk; + else aggregated = concat$1(aggregated, chunk); + if (aggregated === void 0) throw new Error("Received empty response from chat model call."); + output = { + generations: [[aggregated]], + llmOutput: {} + }; + await runManagers?.[0].handleLLMEnd(output); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + else { + 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, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); + } + 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, llmStringKey, parsedOptions, handledOptions, runId }) { + const invocationParams = this.invocationParams(parsedOptions); + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: parsedOptions, + invocation_params: invocationParams, + batch_size: prompts.length + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, runId, void 0, extra, void 0, void 0, handledOptions?.runName); + const missingPromptIndices = []; + const cachedResults = (await Promise.allSettled(prompts.map(async (prompt, index) => { + const result = await cache.lookup(prompt, llmStringKey); + if (result == null) missingPromptIndices.push(index); + return result; + }))).map((result, index) => ({ + result, + runManager: runManagers?.[index] + })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result) => { + result.generationInfo = { + ...result.generationInfo, + tokenUsage: {} + }; + return result; + }); + if (result.length) await runManager?.handleLLMNewToken(result[0].text); + return runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true }); + } else { + await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true }); + return Promise.reject(promiseResult.reason); + } + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, + configurable: true + }); + return output; + } + /** + * Run the LLM on the given prompts and input, handling caching. + */ + 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._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) return this._generateUncached(prompts, callOptions, runnableConfig); + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + prompts, + cache, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig, + runId: runnableConfig.runId + }); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + return cache.update(prompts[promptIndex], llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { + generations, + llmOutput + }; + } + /** + * Get the identifying parameters of the LLM. + */ + _identifyingParams() { + return {}; + } + _modelType() { + return "base_llm"; + } +}; +/** +* LLM class that provides a simpler interface to subclass than {@link BaseLLM}. +* +* Requires only implementing a simpler {@link _call} method instead of {@link _generate}. +* +* @augments BaseLLM +*/ +var LLM = class extends BaseLLM { + async _generate(prompts, options, runManager) { + return { generations: await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { + ...options, + promptIndex + }, runManager).then((text) => [{ text }]))) }; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/language_models/profile.js +var profile_exports = /* @__PURE__ */ __exportAll({}); +//#endregion +//#region node_modules/@langchain/core/dist/memory.js +var memory_exports = /* @__PURE__ */ __exportAll({ + BaseMemory: () => BaseMemory, + getInputValue: () => getInputValue, + getOutputValue: () => getOutputValue, + getPromptInputKey: () => getPromptInputKey +}); +/** +* Abstract base class for memory in LangChain's Chains. Memory refers to +* the state in Chains. It can be used to store information about past +* executions of a Chain and inject that information into the inputs of +* future executions of the Chain. +*/ +var BaseMemory = class {}; +var getValue = (values, key) => { + if (key !== void 0) return values[key]; + const keys = Object.keys(values); + if (keys.length === 1) return values[keys[0]]; +}; +/** +* This function is used by memory classes to select the input value +* to use for the memory. If there is only one input value, it is used. +* If there are multiple input values, the inputKey must be specified. +*/ +var getInputValue = (inputValues, inputKey) => { + const value = getValue(inputValues, inputKey); + if (!value) throw new Error(`input values have ${Object.keys(inputValues).length} keys, you must specify an input key or pass only 1 key as input`); + return value; +}; +/** +* This function is used by memory classes to select the output value +* to use for the memory. If there is only one output value, it is used. +* If there are multiple output values, the outputKey must be specified. +* If no outputKey is specified, an error is thrown. +*/ +var getOutputValue = (outputValues, outputKey) => { + const value = getValue(outputValues, outputKey); + if (!value && value !== "") throw new Error(`output values have ${Object.keys(outputValues).length} keys, you must specify an output key or pass only 1 key as output`); + return value; +}; +/** +* Function used by memory classes to get the key of the prompt input, +* excluding any keys that are memory variables or the "stop" key. If +* there is not exactly one prompt input key, an error is thrown. +*/ +function getPromptInputKey(inputs, memoryVariables) { + const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); + if (promptInputKeys.length !== 1) throw new Error(`One input key expected, but got ${promptInputKeys.length}`); + return promptInputKeys[0]; +} +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/openai_functions/json_output_functions_parsers.js +/** +* Class for parsing the output of an LLM. Can be configured to return +* only the arguments of the function call in the output. +*/ +var OutputFunctionsParser = class extends BaseLLMOutputParser { + static lc_name() { + return "OutputFunctionsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_functions" + ]; + lc_serializable = true; + argsOnly = true; + constructor(config) { + super(); + this.argsOnly = config?.argsOnly ?? this.argsOnly; + } + /** + * Parses the output and returns a string representation of the function + * call or its arguments. + * @param generations The output of the LLM to parse. + * @returns A string representation of the function call or its arguments. + */ + async parseResult(generations) { + if ("message" in generations[0]) { + const functionCall = generations[0].message.additional_kwargs.function_call; + if (!functionCall) throw new Error(`No function_call in message ${JSON.stringify(generations)}`); + if (!functionCall.arguments) throw new Error(`No arguments in function_call ${JSON.stringify(generations)}`); + if (this.argsOnly) return functionCall.arguments; + return JSON.stringify(functionCall); + } else throw new Error(`No message in generations ${JSON.stringify(generations)}`); + } +}; +/** +* Class for parsing the output of an LLM into a JSON object. Uses an +* instance of `OutputFunctionsParser` to parse the output. +*/ +var JsonOutputFunctionsParser = class extends BaseCumulativeTransformOutputParser { + static lc_name() { + return "JsonOutputFunctionsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_functions" + ]; + lc_serializable = true; + outputParser; + argsOnly = true; + constructor(config) { + super(config); + this.argsOnly = config?.argsOnly ?? this.argsOnly; + this.outputParser = new OutputFunctionsParser(config); + } + _diff(prev, next) { + if (!next) return; + return compare(prev ?? {}, next); + } + async parsePartialResult(generations) { + const generation = generations[0]; + if (!generation.message) return; + const { message } = generation; + const functionCall = message.additional_kwargs.function_call; + if (!functionCall) return; + if (this.argsOnly) return parsePartialJson(functionCall.arguments); + return { + ...functionCall, + arguments: parsePartialJson(functionCall.arguments) + }; + } + /** + * Parses the output and returns a JSON object. If `argsOnly` is true, + * only the arguments of the function call are returned. + * @param generations The output of the LLM to parse. + * @returns A JSON object representation of the function call or its arguments. + */ + async parseResult(generations) { + const result = await this.outputParser.parseResult(generations); + if (!result) throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(generations)}`); + return this.parse(result); + } + async parse(text) { + const parsedResult = JSON.parse(text); + if (this.argsOnly) return parsedResult; + parsedResult.arguments = JSON.parse(parsedResult.arguments); + return parsedResult; + } + getFormatInstructions() { + return ""; + } +}; +/** +* Class for parsing the output of an LLM into a JSON object and returning +* a specific attribute. Uses an instance of `JsonOutputFunctionsParser` +* to parse the output. +*/ +var JsonKeyOutputFunctionsParser = class extends BaseLLMOutputParser { + static lc_name() { + return "JsonKeyOutputFunctionsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_functions" + ]; + lc_serializable = true; + outputParser = new JsonOutputFunctionsParser(); + attrName; + get lc_aliases() { + return { attrName: "key_name" }; + } + constructor(fields) { + super(fields); + this.attrName = fields.attrName; + } + /** + * Parses the output and returns a specific attribute of the parsed JSON + * object. + * @param generations The output of the LLM to parse. + * @returns The value of a specific attribute of the parsed JSON object. + */ + async parseResult(generations) { + return (await this.outputParser.parseResult(generations))[this.attrName]; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/openai_functions/index.js +var openai_functions_exports = /* @__PURE__ */ __exportAll({ + JsonKeyOutputFunctionsParser: () => JsonKeyOutputFunctionsParser, + JsonOutputFunctionsParser: () => JsonOutputFunctionsParser, + OutputFunctionsParser: () => OutputFunctionsParser +}); +//#endregion +//#region node_modules/@langchain/core/dist/output_parsers/openai_tools/index.js +var openai_tools_exports = /* @__PURE__ */ __exportAll({ + JsonOutputKeyToolsParser: () => JsonOutputKeyToolsParser, + JsonOutputToolsParser: () => JsonOutputToolsParser, + convertLangChainToolCallToOpenAI: () => convertLangChainToolCallToOpenAI, + makeInvalidToolCall: () => makeInvalidToolCall, + parseToolCall: () => parseToolCall +}); +//#endregion +//#region node_modules/@langchain/core/dist/prompts/base.js +/** +* Base class for prompt templates. Exposes a format method that returns a +* string prompt given a set of input values. +*/ +var BasePromptTemplate = class extends Runnable { + lc_serializable = true; + lc_namespace = [ + "langchain_core", + "prompts", + this._getPromptType() + ]; + get lc_attributes() { + return { partialVariables: void 0 }; + } + inputVariables; + outputParser; + partialVariables; + /** + * Metadata to be used for tracing. + */ + metadata; + /** Tags to be used for tracing. */ + tags; + constructor(input) { + super(input); + 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); + } + /** + * Merges partial variables and user variables. + * @param userVariables The user variables to merge with the partial variables. + * @returns A Promise that resolves to an object containing the merged variables. + */ + 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(); + return { + ...partialValues, + ...userVariables + }; + } + /** + * Invokes the prompt template with the given input and options. + * @param input The input to invoke the prompt template with. + * @param options Optional configuration for the callback. + * @returns A Promise that resolves to the output of the prompt template. + */ + async invoke(input, options) { + const metadata = { + ...this.metadata, + ...options?.metadata + }; + const tags = [...this.tags ?? [], ...options?.tags ?? []]; + return this._callWithConfig((input) => this.formatPromptValue(input), input, { + ...options, + tags, + metadata, + runType: "prompt" + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/prompts/string.js +/** +* Base class for string prompt templates. It extends the +* BasePromptTemplate class and overrides the formatPromptValue method to +* return a StringPromptValue. +*/ +var BaseStringPromptTemplate = class extends BasePromptTemplate { + /** + * Formats the prompt given the input values and returns a formatted + * prompt value. + * @param values The input values to format the prompt. + * @returns A Promise that resolves to a formatted prompt value. + */ + async formatPromptValue(values) { + return new StringPromptValue(await this.format(values)); + } +}; +//#endregion +//#region node_modules/mustache/mustache.mjs +/*! +* mustache.js - Logic-less {{mustache}} templates with JavaScript +* http://github.com/janl/mustache.js +*/ +var objectToString = Object.prototype.toString; +var isArray = Array.isArray || function isArrayPolyfill(object) { + return objectToString.call(object) === "[object Array]"; +}; +function isFunction(object) { + return typeof object === "function"; +} +/** +* More correct typeof string handling array +* which normally returns typeof 'object' +*/ +function typeStr(obj) { + return isArray(obj) ? "array" : typeof obj; +} +function escapeRegExp(string) { + return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); +} +/** +* Null safe way of checking whether or not an object, +* including its prototype, has a given property +*/ +function hasProperty(obj, propName) { + return obj != null && typeof obj === "object" && propName in obj; +} +/** +* Safe way of detecting whether or not the given thing is a primitive and +* whether it has the given property +*/ +function primitiveHasOwnProperty(primitive, propName) { + return primitive != null && typeof primitive !== "object" && primitive.hasOwnProperty && primitive.hasOwnProperty(propName); +} +var regExpTest = RegExp.prototype.test; +function testRegExp(re, string) { + return regExpTest.call(re, string); +} +var nonSpaceRe = /\S/; +function isWhitespace(string) { + return !testRegExp(nonSpaceRe, string); +} +var entityMap = { + "&": "&", + "<": "<", + ">": ">", + "\"": """, + "'": "'", + "/": "/", + "`": "`", + "=": "=" +}; +function escapeHtml(string) { + return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap(s) { + return entityMap[s]; + }); +} +var whiteRe = /\s*/; +var spaceRe = /\s+/; +var equalsRe = /\s*=/; +var curlyRe = /\s*\}/; +var tagRe = /#|\^|\/|>|\{|&|=|!/; +/** +* Breaks up the given `template` string into a tree of tokens. If the `tags` +* argument is given here it must be an array with two string values: the +* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of +* course, the default is to use mustaches (i.e. mustache.tags). +* +* A token is an array with at least 4 elements. The first element is the +* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag +* did not contain a symbol (i.e. {{myValue}}) this element is "name". For +* all text that appears outside a symbol this element is "text". +* +* The second element of a token is its "value". For mustache tags this is +* whatever else was inside the tag besides the opening symbol. For text tokens +* this is the text itself. +* +* The third and fourth elements of the token are the start and end indices, +* respectively, of the token in the original template. +* +* Tokens that are the root node of a subtree contain two more elements: 1) an +* array of tokens in the subtree and 2) the index in the original template at +* which the closing tag for that section begins. +* +* Tokens for partials also contain two more elements: 1) a string value of +* indendation prior to that tag and 2) the index of that tag on that line - +* eg a value of 2 indicates the partial is the third tag on this line. +*/ +function parseTemplate$1(template, tags) { + if (!template) return []; + var lineHasNonSpace = false; + var sections = []; + var tokens = []; + var spaces = []; + var hasTag = false; + var nonSpace = false; + var indentation = ""; + var tagIndex = 0; + function stripSpace() { + if (hasTag && !nonSpace) while (spaces.length) delete tokens[spaces.pop()]; + else spaces = []; + hasTag = false; + nonSpace = false; + } + var openingTagRe, closingTagRe, closingCurlyRe; + function compileTags(tagsToCompile) { + if (typeof tagsToCompile === "string") tagsToCompile = tagsToCompile.split(spaceRe, 2); + if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) throw new Error("Invalid tags: " + tagsToCompile); + openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + "\\s*"); + closingTagRe = new RegExp("\\s*" + escapeRegExp(tagsToCompile[1])); + closingCurlyRe = new RegExp("\\s*" + escapeRegExp("}" + tagsToCompile[1])); + } + compileTags(tags || mustache.tags); + var scanner = new Scanner(template); + var start, type, value, chr, token, openSection; + while (!scanner.eos()) { + start = scanner.pos; + value = scanner.scanUntil(openingTagRe); + if (value) for (var i = 0, valueLength = value.length; i < valueLength; ++i) { + chr = value.charAt(i); + if (isWhitespace(chr)) { + spaces.push(tokens.length); + indentation += chr; + } else { + nonSpace = true; + lineHasNonSpace = true; + indentation += " "; + } + tokens.push([ + "text", + chr, + start, + start + 1 + ]); + start += 1; + if (chr === "\n") { + stripSpace(); + indentation = ""; + tagIndex = 0; + lineHasNonSpace = false; + } + } + if (!scanner.scan(openingTagRe)) break; + hasTag = true; + type = scanner.scan(tagRe) || "name"; + scanner.scan(whiteRe); + if (type === "=") { + value = scanner.scanUntil(equalsRe); + scanner.scan(equalsRe); + scanner.scanUntil(closingTagRe); + } else if (type === "{") { + value = scanner.scanUntil(closingCurlyRe); + scanner.scan(curlyRe); + scanner.scanUntil(closingTagRe); + type = "&"; + } else value = scanner.scanUntil(closingTagRe); + if (!scanner.scan(closingTagRe)) throw new Error("Unclosed tag at " + scanner.pos); + if (type == ">") token = [ + type, + value, + start, + scanner.pos, + indentation, + tagIndex, + lineHasNonSpace + ]; + else token = [ + type, + value, + start, + scanner.pos + ]; + tagIndex++; + tokens.push(token); + if (type === "#" || type === "^") sections.push(token); + else if (type === "/") { + openSection = sections.pop(); + if (!openSection) throw new Error("Unopened section \"" + value + "\" at " + start); + if (openSection[1] !== value) throw new Error("Unclosed section \"" + openSection[1] + "\" at " + start); + } else if (type === "name" || type === "{" || type === "&") nonSpace = true; + else if (type === "=") compileTags(value); + } + stripSpace(); + openSection = sections.pop(); + if (openSection) throw new Error("Unclosed section \"" + openSection[1] + "\" at " + scanner.pos); + return nestTokens(squashTokens(tokens)); +} +/** +* Combines the values of consecutive text tokens in the given `tokens` array +* to a single token. +*/ +function squashTokens(tokens) { + var squashedTokens = []; + var token, lastToken; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + token = tokens[i]; + if (token) if (token[0] === "text" && lastToken && lastToken[0] === "text") { + lastToken[1] += token[1]; + lastToken[3] = token[3]; + } else { + squashedTokens.push(token); + lastToken = token; + } + } + return squashedTokens; +} +/** +* Forms the given array of `tokens` into a nested tree structure where +* tokens that represent a section have two additional items: 1) an array of +* all tokens that appear in that section and 2) the index in the original +* template that represents the end of that section. +*/ +function nestTokens(tokens) { + var nestedTokens = []; + var collector = nestedTokens; + var sections = []; + var token, section; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + token = tokens[i]; + switch (token[0]) { + case "#": + case "^": + collector.push(token); + sections.push(token); + collector = token[4] = []; + break; + case "/": + section = sections.pop(); + section[5] = token[2]; + collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; + break; + default: collector.push(token); + } + } + return nestedTokens; +} +/** +* A simple string scanner that is used by the template parser to find +* tokens in template strings. +*/ +function Scanner(string) { + this.string = string; + this.tail = string; + this.pos = 0; +} +/** +* Returns `true` if the tail is empty (end of string). +*/ +Scanner.prototype.eos = function eos() { + return this.tail === ""; +}; +/** +* Tries to match the given regular expression at the current position. +* Returns the matched text if it can match, the empty string otherwise. +*/ +Scanner.prototype.scan = function scan(re) { + var match = this.tail.match(re); + if (!match || match.index !== 0) return ""; + var string = match[0]; + this.tail = this.tail.substring(string.length); + this.pos += string.length; + return string; +}; +/** +* Skips all text until the given regular expression can be matched. Returns +* the skipped string, which is the entire tail if no match can be made. +*/ +Scanner.prototype.scanUntil = function scanUntil(re) { + var index = this.tail.search(re), match; + switch (index) { + case -1: + match = this.tail; + this.tail = ""; + break; + case 0: + match = ""; + break; + default: + match = this.tail.substring(0, index); + this.tail = this.tail.substring(index); + } + this.pos += match.length; + return match; +}; +/** +* Represents a rendering context by wrapping a view object and +* maintaining a reference to the parent context. +*/ +function Context(view, parentContext) { + this.view = view; + this.cache = { ".": this.view }; + this.parent = parentContext; +} +/** +* Creates a new context using the given view with this context +* as the parent. +*/ +Context.prototype.push = function push(view) { + return new Context(view, this); +}; +/** +* Returns the value of the given name in this context, traversing +* up the context hierarchy if the value is absent in this context's view. +*/ +Context.prototype.lookup = function lookup(name) { + var cache = this.cache; + var value; + if (cache.hasOwnProperty(name)) value = cache[name]; + else { + var context = this, intermediateValue, names, index, lookupHit = false; + while (context) { + if (name.indexOf(".") > 0) { + intermediateValue = context.view; + names = name.split("."); + index = 0; + /** + * Using the dot notion path in `name`, we descend through the + * nested objects. + * + * To be certain that the lookup has been successful, we have to + * check if the last object in the path actually has the property + * we are looking for. We store the result in `lookupHit`. + * + * This is specially necessary for when the value has been set to + * `undefined` and we want to avoid looking up parent contexts. + * + * In the case where dot notation is used, we consider the lookup + * to be successful even if the last "object" in the path is + * not actually an object but a primitive (e.g., a string, or an + * integer), because it is sometimes useful to access a property + * of an autoboxed primitive, such as the length of a string. + **/ + while (intermediateValue != null && index < names.length) { + if (index === names.length - 1) lookupHit = hasProperty(intermediateValue, names[index]) || primitiveHasOwnProperty(intermediateValue, names[index]); + intermediateValue = intermediateValue[names[index++]]; + } + } else { + intermediateValue = context.view[name]; + /** + * Only checking against `hasProperty`, which always returns `false` if + * `context.view` is not an object. Deliberately omitting the check + * against `primitiveHasOwnProperty` if dot notation is not used. + * + * Consider this example: + * ``` + * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"}) + * ``` + * + * If we were to check also against `primitiveHasOwnProperty`, as we do + * in the dot notation case, then render call would return: + * + * "The length of a football field is 9." + * + * rather than the expected: + * + * "The length of a football field is 100 yards." + **/ + lookupHit = hasProperty(context.view, name); + } + if (lookupHit) { + value = intermediateValue; + break; + } + context = context.parent; + } + cache[name] = value; + } + if (isFunction(value)) value = value.call(this.view); + return value; +}; +/** +* A Writer knows how to take a stream of tokens and render them to a +* string, given a context. It also maintains a cache of templates to +* avoid the need to parse the same template twice. +*/ +function Writer() { + this.templateCache = { + _cache: {}, + set: function set(key, value) { + this._cache[key] = value; + }, + get: function get(key) { + return this._cache[key]; + }, + clear: function clear() { + this._cache = {}; + } + }; +} +/** +* Clears all cached templates in this writer. +*/ +Writer.prototype.clearCache = function clearCache() { + if (typeof this.templateCache !== "undefined") this.templateCache.clear(); +}; +/** +* Parses and caches the given `template` according to the given `tags` or +* `mustache.tags` if `tags` is omitted, and returns the array of tokens +* that is generated from the parse. +*/ +Writer.prototype.parse = function parse(template, tags) { + var cache = this.templateCache; + var cacheKey = template + ":" + (tags || mustache.tags).join(":"); + var isCacheEnabled = typeof cache !== "undefined"; + var tokens = isCacheEnabled ? cache.get(cacheKey) : void 0; + if (tokens == void 0) { + tokens = parseTemplate$1(template, tags); + isCacheEnabled && cache.set(cacheKey, tokens); + } + return tokens; +}; +/** +* High-level method that is used to render the given `template` with +* the given `view`. +* +* The optional `partials` argument may be an object that contains the +* names and templates of partials that are used in the template. It may +* also be a function that is used to load partial templates on the fly +* that takes a single argument: the name of the partial. +* +* If the optional `config` argument is given here, then it should be an +* object with a `tags` attribute or an `escape` attribute or both. +* If an array is passed, then it will be interpreted the same way as +* a `tags` attribute on a `config` object. +* +* The `tags` attribute of a `config` object must be an array with two +* string values: the opening and closing tags used in the template (e.g. +* [ "<%", "%>" ]). The default is to mustache.tags. +* +* The `escape` attribute of a `config` object must be a function which +* accepts a string as input and outputs a safely escaped string. +* If an `escape` function is not provided, then an HTML-safe string +* escaping function is used as the default. +*/ +Writer.prototype.render = function render(template, view, partials, config) { + var tags = this.getConfigTags(config); + var tokens = this.parse(template, tags); + var context = view instanceof Context ? view : new Context(view, void 0); + return this.renderTokens(tokens, context, partials, template, config); +}; +/** +* Low-level method that renders the given array of `tokens` using +* the given `context` and `partials`. +* +* Note: The `originalTemplate` is only ever used to extract the portion +* of the original template that was contained in a higher-order section. +* If the template doesn't use higher-order sections, this argument may +* be omitted. +*/ +Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate, config) { + var buffer = ""; + var token, symbol, value; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + value = void 0; + token = tokens[i]; + symbol = token[0]; + if (symbol === "#") value = this.renderSection(token, context, partials, originalTemplate, config); + else if (symbol === "^") value = this.renderInverted(token, context, partials, originalTemplate, config); + else if (symbol === ">") value = this.renderPartial(token, context, partials, config); + else if (symbol === "&") value = this.unescapedValue(token, context); + else if (symbol === "name") value = this.escapedValue(token, context, config); + else if (symbol === "text") value = this.rawValue(token); + if (value !== void 0) buffer += value; + } + return buffer; +}; +Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate, config) { + var self = this; + var buffer = ""; + var value = context.lookup(token[1]); + function subRender(template) { + return self.render(template, context, partials, config); + } + if (!value) return; + if (isArray(value)) for (var j = 0, valueLength = value.length; j < valueLength; ++j) buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config); + else if (typeof value === "object" || typeof value === "string" || typeof value === "number") buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config); + else if (isFunction(value)) { + if (typeof originalTemplate !== "string") throw new Error("Cannot use higher-order sections without the original template"); + value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); + if (value != null) buffer += value; + } else buffer += this.renderTokens(token[4], context, partials, originalTemplate, config); + return buffer; +}; +Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate, config) { + var value = context.lookup(token[1]); + if (!value || isArray(value) && value.length === 0) return this.renderTokens(token[4], context, partials, originalTemplate, config); +}; +Writer.prototype.indentPartial = function indentPartial(partial, indentation, lineHasNonSpace) { + var filteredIndentation = indentation.replace(/[^ \t]/g, ""); + var partialByNl = partial.split("\n"); + for (var i = 0; i < partialByNl.length; i++) if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) partialByNl[i] = filteredIndentation + partialByNl[i]; + return partialByNl.join("\n"); +}; +Writer.prototype.renderPartial = function renderPartial(token, context, partials, config) { + if (!partials) return; + var tags = this.getConfigTags(config); + var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; + if (value != null) { + var lineHasNonSpace = token[6]; + var tagIndex = token[5]; + var indentation = token[4]; + var indentedValue = value; + if (tagIndex == 0 && indentation) indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); + var tokens = this.parse(indentedValue, tags); + return this.renderTokens(tokens, context, partials, indentedValue, config); + } +}; +Writer.prototype.unescapedValue = function unescapedValue(token, context) { + var value = context.lookup(token[1]); + if (value != null) return value; +}; +Writer.prototype.escapedValue = function escapedValue(token, context, config) { + var escape = this.getConfigEscape(config) || mustache.escape; + var value = context.lookup(token[1]); + if (value != null) return typeof value === "number" && escape === mustache.escape ? String(value) : escape(value); +}; +Writer.prototype.rawValue = function rawValue(token) { + return token[1]; +}; +Writer.prototype.getConfigTags = function getConfigTags(config) { + if (isArray(config)) return config; + else if (config && typeof config === "object") return config.tags; + else return; +}; +Writer.prototype.getConfigEscape = function getConfigEscape(config) { + if (config && typeof config === "object" && !isArray(config)) return config.escape; + else return; +}; +var mustache = { + name: "mustache.js", + version: "4.2.0", + tags: ["{{", "}}"], + clearCache: void 0, + escape: void 0, + parse: void 0, + render: void 0, + Scanner: void 0, + Context: void 0, + Writer: void 0, + /** + * Allows a user to override the default caching strategy, by providing an + * object with set, get and clear methods. This can also be used to disable + * the cache by setting it to the literal `undefined`. + */ + set templateCache(cache) { + defaultWriter.templateCache = cache; + }, + /** + * Gets the default or overridden caching object from the default writer. + */ + get templateCache() { + return defaultWriter.templateCache; + } +}; +var defaultWriter = new Writer(); +/** +* Clears all cached templates in the default writer. +*/ +mustache.clearCache = function clearCache() { + return defaultWriter.clearCache(); +}; +/** +* Parses and caches the given template in the default writer and returns the +* array of tokens it contains. Doing this ahead of time avoids the need to +* parse templates on the fly as they are rendered. +*/ +mustache.parse = function parse(template, tags) { + return defaultWriter.parse(template, tags); +}; +/** +* Renders the `template` with the given `view`, `partials`, and `config` +* using the default writer. +*/ +mustache.render = function render(template, view, partials, config) { + if (typeof template !== "string") throw new TypeError("Invalid template! Template should be a \"string\" but \"" + typeStr(template) + "\" was given as the first argument for mustache#render(template, view, partials)"); + return defaultWriter.render(template, view, partials, config); +}; +mustache.escape = escapeHtml; +mustache.Scanner = Scanner; +mustache.Context = Context; +mustache.Writer = Writer; +//#endregion +//#region node_modules/@langchain/core/dist/prompts/template.js +function configureMustache() { + mustache.escape = (text) => text; +} +var parseFString = (template) => { + const chars = template.split(""); + const nodes = []; + const nextBracket = (bracket, start) => { + for (let i = start; i < chars.length; i += 1) if (bracket.includes(chars[i])) return i; + return -1; + }; + let i = 0; + while (i < chars.length) if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { + nodes.push({ + type: "literal", + text: "{" + }); + i += 2; + } else if (chars[i] === "}" && i + 1 < chars.length && chars[i + 1] === "}") { + nodes.push({ + type: "literal", + text: "}" + }); + i += 2; + } else if (chars[i] === "{") { + const j = nextBracket("}", i); + if (j < 0) throw new Error("Unclosed '{' in template."); + nodes.push({ + type: "variable", + name: chars.slice(i + 1, j).join("") + }); + i = j + 1; + } else if (chars[i] === "}") throw new Error("Single '}' in template."); + else { + const next = nextBracket("{}", i); + const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); + nodes.push({ + type: "literal", + text + }); + i = next < 0 ? chars.length : next; + } + return nodes; +}; +/** +* Convert the result of mustache.parse into an array of ParsedTemplateNode, +* to make it compatible with other LangChain string parsing template formats. +* +* @param {mustache.TemplateSpans} template The result of parsing a mustache template with the mustache.js library. +* @param {string[]} context Array of section variable names for nested context +* @returns {ParsedTemplateNode[]} +*/ +var mustacheTemplateToNodes = (template, context = []) => { + const nodes = []; + for (const temp of template) if (temp[0] === "name") { + const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1]; + nodes.push({ + type: "variable", + name + }); + } else if ([ + "#", + "&", + "^", + ">" + ].includes(temp[0])) { + nodes.push({ + type: "variable", + name: temp[1] + }); + if (temp[0] === "#" && temp.length > 4 && Array.isArray(temp[4])) { + const newContext = [...context, temp[1]]; + const nestedNodes = mustacheTemplateToNodes(temp[4], newContext); + nodes.push(...nestedNodes); + } + } else nodes.push({ + type: "literal", + text: temp[1] + }); + return nodes; +}; +var parseMustache = (template) => { + configureMustache(); + return mustacheTemplateToNodes(mustache.parse(template)); +}; +var interpolateFString = (template, values) => { + return parseFString(template).reduce((res, node) => { + if (node.type === "variable") { + if (node.name in values) return res + (typeof values[node.name] === "string" ? values[node.name] : JSON.stringify(values[node.name])); + throw new Error(`(f-string) Missing value for input ${node.name}`); + } + return res + node.text; + }, ""); +}; +var interpolateMustache = (template, values) => { + configureMustache(); + return mustache.render(template, values); +}; +var DEFAULT_FORMATTER_MAPPING = { + "f-string": interpolateFString, + mustache: interpolateMustache +}; +var DEFAULT_PARSER_MAPPING = { + "f-string": parseFString, + mustache: parseMustache +}; +var renderTemplate = (template, templateFormat, inputValues) => { + try { + return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); + } catch (e) { + throw addLangChainErrorFields(e, "INVALID_PROMPT_INPUT"); + } +}; +var parseTemplate = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template); +var checkValidTemplate = (template, templateFormat, inputVariables) => { + if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) throw new Error(`Invalid template format. Got \`${templateFormat}\`; + should be one of ${Object.keys(DEFAULT_FORMATTER_MAPPING)}`); + try { + const dummyInputs = Object.fromEntries(inputVariables.map((v) => [v, "foo"])); + if (Array.isArray(template)) template.forEach((message) => { + if (message.type === "text" && "text" in message && typeof message.text === "string") renderTemplate(message.text, templateFormat, dummyInputs); + else if (message.type === "image_url") { + if (typeof message.image_url === "string") renderTemplate(message.image_url, templateFormat, dummyInputs); + else if (typeof message.image_url === "object" && message.image_url !== null && "url" in message.image_url && typeof message.image_url.url === "string") { + 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(template, templateFormat, dummyInputs); + } catch (e) { + throw new Error(`Invalid prompt schema: ${e.message}`); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/prompts/prompt.js +/** +* Schema to represent a basic prompt for an LLM. +* @augments BasePromptTemplate +* @augments PromptTemplateInput +* +* @example +* ```ts +* import { PromptTemplate } from "langchain/prompts"; +* +* const prompt = new PromptTemplate({ +* inputVariables: ["foo"], +* template: "Say {foo}", +* }); +* ``` +*/ +var PromptTemplate = class PromptTemplate extends BaseStringPromptTemplate { + static lc_name() { + return "PromptTemplate"; + } + template; + templateFormat = "f-string"; + validateTemplate = true; + /** + * Additional fields which should be included inside + * the message content array if using a complex message + * content. + */ + additionalContentFields; + constructor(input) { + super(input); + if (input.templateFormat === "mustache" && input.validateTemplate === void 0) this.validateTemplate = false; + Object.assign(this, input); + if (this.validateTemplate) { + if (this.templateFormat === "mustache") throw new Error("Mustache templates cannot be validated."); + let totalInputVariables = this.inputVariables; + if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + checkValidTemplate(this.template, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "prompt"; + } + /** + * Formats the prompt template with the provided values. + * @param values The values to be used to format the prompt template. + * @returns A promise that resolves to a string which is the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + return renderTemplate(this.template, this.templateFormat, allValues); + } + /** + * Take examples in list format with prefix and suffix to create a prompt. + * + * Intended to be used as a way to dynamically create a prompt from examples. + * + * @param examples - List of examples to use in the prompt. + * @param suffix - String to go after the list of examples. Should generally set up the user's input. + * @param inputVariables - A list of variable names the final prompt template will expect + * @param exampleSeparator - The separator to use in between examples + * @param prefix - String that should go before any examples. Generally includes examples. + * + * @returns The final prompt template generated. + */ + static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { + return new PromptTemplate({ + inputVariables, + template: [ + prefix, + ...examples, + suffix + ].join(exampleSeparator) + }); + } + static fromTemplate(template, options) { + const { templateFormat = "f-string", ...rest } = options ?? {}; + const names = /* @__PURE__ */ new Set(); + parseTemplate(template, templateFormat).forEach((node) => { + if (node.type === "variable") names.add(node.name); + }); + return new PromptTemplate({ + inputVariables: [...names], + templateFormat, + template, + ...rest + }); + } + /** + * Partially applies values to the prompt template. + * @param values The values to be partially applied to the prompt template. + * @returns A new instance of PromptTemplate with the partially applied values. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new PromptTemplate({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }); + } + 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"); + return new PromptTemplate({ + inputVariables: data.input_variables, + template: data.template, + templateFormat: data.template_format + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/prompts/image.js +/** +* An image prompt template for a multimodal model. +*/ +var ImagePromptTemplate = class ImagePromptTemplate extends BasePromptTemplate { + static lc_name() { + return "ImagePromptTemplate"; + } + lc_namespace = [ + "langchain_core", + "prompts", + "image" + ]; + template; + templateFormat = "f-string"; + validateTemplate = true; + /** + * Additional fields which should be included inside + * the message content array if using a complex message + * content. + */ + additionalContentFields; + constructor(input) { + super(input); + this.template = input.template; + this.templateFormat = input.templateFormat ?? this.templateFormat; + this.validateTemplate = input.validateTemplate ?? this.validateTemplate; + this.additionalContentFields = input.additionalContentFields; + 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"; + } + /** + * Partially applies values to the prompt template. + * @param values The values to be partially applied to the prompt template. + * @returns A new instance of ImagePromptTemplate with the partially applied values. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new ImagePromptTemplate({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }); + } + /** + * Formats the prompt template with the provided values. + * @param values The values to be used to format the prompt template. + * @returns A promise that resolves to a string which is the formatted prompt. + */ + async format(values) { + const formatted = {}; + for (const [key, value] of Object.entries(this.template)) if (typeof value === "string") formatted[key] = renderTemplate(value, this.templateFormat, values); + 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; + } + /** + * Formats the prompt given the input values and returns a formatted + * prompt value. + * @param values The input values to format the prompt. + * @returns A Promise that resolves to a formatted prompt value. + */ + async formatPromptValue(values) { + return new ImagePromptValue(await this.format(values)); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/prompts/dict.js +var DictPromptTemplate = class extends Runnable { + lc_namespace = [ + "langchain_core", + "prompts", + "dict" + ]; + lc_serializable = true; + template; + templateFormat; + inputVariables; + static lc_name() { + return "DictPromptTemplate"; + } + constructor(fields) { + const templateFormat = fields.templateFormat ?? "f-string"; + const inputVariables = _getInputVariables(fields.template, templateFormat); + super({ + inputVariables, + ...fields + }); + this.template = fields.template; + this.templateFormat = templateFormat; + this.inputVariables = inputVariables; + } + async format(values) { + return _insertInputVariables(this.template, values, this.templateFormat); + } + async invoke(values) { + return await this._callWithConfig(this.format.bind(this), values, { runType: "prompt" }); + } +}; +function _getInputVariables(template, templateFormat) { + const inputVariables = []; + for (const v of Object.values(template)) if (typeof v === "string") parseTemplate(v, templateFormat).forEach((t) => { + if (t.type === "variable") inputVariables.push(t.name); + }); + else if (Array.isArray(v)) { + for (const x of v) if (typeof x === "string") parseTemplate(x, templateFormat).forEach((t) => { + if (t.type === "variable") inputVariables.push(t.name); + }); + else if (typeof x === "object") inputVariables.push(..._getInputVariables(x, templateFormat)); + } else if (typeof v === "object" && v !== null) inputVariables.push(..._getInputVariables(v, templateFormat)); + return Array.from(new Set(inputVariables)); +} +function _insertInputVariables(template, inputs, templateFormat) { + const formatted = {}; + for (const [k, v] of Object.entries(template)) if (typeof v === "string") formatted[k] = renderTemplate(v, templateFormat, inputs); + else if (Array.isArray(v)) { + const formattedV = []; + for (const x of v) if (typeof x === "string") formattedV.push(renderTemplate(x, templateFormat, inputs)); + else if (typeof x === "object") formattedV.push(_insertInputVariables(x, inputs, templateFormat)); + formatted[k] = formattedV; + } else if (typeof v === "object" && v !== null) formatted[k] = _insertInputVariables(v, inputs, templateFormat); + else formatted[k] = v; + return formatted; +} +//#endregion +//#region node_modules/@langchain/core/dist/prompts/chat.js +/** +* Abstract class that serves as a base for creating message prompt +* templates. It defines how to format messages for different roles in a +* conversation. +*/ +var BaseMessagePromptTemplate = class extends Runnable { + lc_namespace = [ + "langchain_core", + "prompts", + "chat" + ]; + lc_serializable = true; + /** + * Calls the formatMessages method with the provided input and options. + * @param input Input for the formatMessages method + * @param options Optional BaseCallbackConfig + * @returns Formatted output messages + */ + async invoke(input, options) { + return this._callWithConfig((input) => this.formatMessages(input), input, { + ...options, + runType: "prompt" + }); + } +}; +/** +* Class that represents a placeholder for messages in a chat prompt. It +* extends the BaseMessagePromptTemplate. +*/ +var MessagesPlaceholder = class extends BaseMessagePromptTemplate { + static lc_name() { + return "MessagesPlaceholder"; + } + variableName; + optional; + constructor(fields) { + if (typeof fields === "string") fields = { variableName: fields }; + super(fields); + this.variableName = fields.variableName; + this.optional = fields.optional ?? false; + } + get inputVariables() { + return [this.variableName]; + } + async formatMessages(values) { + const input = values[this.variableName]; + if (this.optional && !input) return []; + else if (!input) { + const error = /* @__PURE__ */ new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`); + error.name = "InputFormatError"; + throw error; + } + let formattedMessages; + try { + if (Array.isArray(input)) formattedMessages = input.map(coerceMessageLikeToMessage); + else formattedMessages = [coerceMessageLikeToMessage(input)]; + } catch (e) { + const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2); + const error = new Error([ + `Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`, + `Received value: ${readableInput}`, + `Additional message: ${e.message}` + ].join("\n\n")); + error.name = "InputFormatError"; + error.lc_error_code = e.lc_error_code; + throw error; + } + return formattedMessages; + } +}; +/** +* Abstract class that serves as a base for creating message string prompt +* templates. It extends the BaseMessagePromptTemplate. +*/ +var BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { + prompt; + constructor(fields) { + if (!("prompt" in fields)) fields = { prompt: fields }; + super(fields); + this.prompt = fields.prompt; + } + get inputVariables() { + return this.prompt.inputVariables; + } + async formatMessages(values) { + return [await this.format(values)]; + } +}; +/** +* Abstract class that serves as a base for creating chat prompt +* templates. It extends the BasePromptTemplate. +*/ +var BaseChatPromptTemplate = class extends BasePromptTemplate { + constructor(input) { + super(input); + } + async format(values) { + return (await this.formatPromptValue(values)).toString(); + } + async formatPromptValue(values) { + return new ChatPromptValue(await this.formatMessages(values)); + } +}; +/** +* Class that represents a chat message prompt template. It extends the +* BaseMessageStringPromptTemplate. +*/ +var ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { + static lc_name() { + return "ChatMessagePromptTemplate"; + } + role; + constructor(fields, role) { + if (!("prompt" in fields)) fields = { + prompt: fields, + role + }; + super(fields); + this.role = fields.role; + } + async format(values) { + return new ChatMessage(await this.prompt.format(values), this.role); + } + static fromTemplate(template, role, options) { + return new this(PromptTemplate.fromTemplate(template, { templateFormat: options?.templateFormat }), role); + } +}; +function isTextTemplateParam(param) { + if (param === null || typeof param !== "object" || Array.isArray(param)) return false; + return Object.keys(param).length === 1 && "text" in param && typeof param.text === "string"; +} +function isImageTemplateParam(param) { + if (param === null || typeof param !== "object" || Array.isArray(param)) return false; + return "image_url" in param && (typeof param.image_url === "string" || typeof param.image_url === "object" && param.image_url !== null && "url" in param.image_url && typeof param.image_url.url === "string"); +} +var _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate { + lc_namespace = [ + "langchain_core", + "prompts", + "chat" + ]; + lc_serializable = true; + inputVariables = []; + additionalOptions = {}; + prompt; + messageClass; + static _messageClass() { + throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate"); + } + chatMessageClass; + constructor(fields, additionalOptions) { + if (!("prompt" in fields)) fields = { prompt: fields }; + super(fields); + this.prompt = fields.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()) return new (constructor._messageClass())({ 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(name) { + switch (name) { + 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(template, additionalOptions) { + if (typeof template === "string") return new this(PromptTemplate.fromTemplate(template, additionalOptions)); + const prompt = []; + for (const item of template) if (typeof item === "string") prompt.push(PromptTemplate.fromTemplate(item, additionalOptions)); + else if (item === null) {} else if (isTextTemplateParam(item)) { + let text = ""; + if (typeof item.text === "string") text = item.text ?? ""; + const options = { + ...additionalOptions, + additionalContentFields: item + }; + prompt.push(PromptTemplate.fromTemplate(text, options)); + } else if (isImageTemplateParam(item)) { + let imgTemplate = item.image_url ?? ""; + let imgTemplateObject; + let inputVariables = []; + if (typeof imgTemplate === "string") { + let parsedTemplate; + if (additionalOptions?.templateFormat === "mustache") parsedTemplate = parseMustache(imgTemplate); + else parsedTemplate = parseFString(imgTemplate); + const variables = parsedTemplate.flatMap((item) => item.type === "variable" ? [item.name] : []); + if ((variables?.length ?? 0) > 0) { + if (variables.length > 1) throw new Error(`Only one format variable allowed per image template.\nGot: ${variables}\nFrom: ${imgTemplate}`); + inputVariables = [variables[0]]; + } else inputVariables = []; + imgTemplate = { url: imgTemplate }; + imgTemplateObject = new ImagePromptTemplate({ + template: imgTemplate, + inputVariables, + templateFormat: additionalOptions?.templateFormat, + additionalContentFields: item + }); + } else if (typeof imgTemplate === "object") { + if ("url" in imgTemplate) { + let parsedTemplate; + if (additionalOptions?.templateFormat === "mustache") parsedTemplate = parseMustache(imgTemplate.url); + else parsedTemplate = parseFString(imgTemplate.url); + inputVariables = parsedTemplate.flatMap((item) => item.type === "variable" ? [item.name] : []); + } else inputVariables = []; + imgTemplateObject = new ImagePromptTemplate({ + template: imgTemplate, + inputVariables, + templateFormat: additionalOptions?.templateFormat, + additionalContentFields: item + }); + } else throw new Error("Invalid image template"); + prompt.push(imgTemplateObject); + } else if (typeof item === "object") prompt.push(new DictPromptTemplate({ + template: item, + templateFormat: additionalOptions?.templateFormat + })); + 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); + let additionalContentFields; + if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; + if (formatted !== "") content.push({ + ...additionalContentFields, + type: "text", + text: formatted + }); + } else if (prompt instanceof ImagePromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; + content.push({ + ...additionalContentFields, + type: "image_url", + image_url: formatted + }); + } else if (prompt instanceof DictPromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; + content.push({ + ...additionalContentFields, + ...formatted + }); + } + } + return this.createMessage(content); + } + } + async formatMessages(values) { + return [await this.format(values)]; + } +}; +/** +* Class that represents a human message prompt template. It extends the +* BaseMessageStringPromptTemplate. +* @example +* ```typescript +* const message = HumanMessagePromptTemplate.fromTemplate("{text}"); +* const formatted = await message.format({ text: "Hello world!" }); +* +* const chatPrompt = ChatPromptTemplate.fromMessages([message]); +* const formattedChatPrompt = await chatPrompt.invoke({ +* text: "Hello world!", +* }); +* ``` +*/ +var HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return HumanMessage; + } + static lc_name() { + return "HumanMessagePromptTemplate"; + } +}; +/** +* Class that represents an AI message prompt template. It extends the +* BaseMessageStringPromptTemplate. +*/ +var AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return AIMessage; + } + static lc_name() { + return "AIMessagePromptTemplate"; + } +}; +/** +* Class that represents a system message prompt template. It extends the +* BaseMessageStringPromptTemplate. +* @example +* ```typescript +* const message = SystemMessagePromptTemplate.fromTemplate("{text}"); +* const formatted = await message.format({ text: "Hello world!" }); +* +* const chatPrompt = ChatPromptTemplate.fromMessages([message]); +* const formattedChatPrompt = await chatPrompt.invoke({ +* text: "Hello world!", +* }); +* ``` +*/ +var SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return SystemMessage; + } + static lc_name() { + return "SystemMessagePromptTemplate"; + } +}; +function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { + return typeof baseMessagePromptTemplateLike.formatMessages === "function"; +} +function _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) { + if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) return messagePromptTemplateLike; + if (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === "placeholder") { + const messageContent = messagePromptTemplateLike[1]; + if (extra?.templateFormat === "mustache" && typeof messageContent === "string" && messageContent.slice(0, 2) === "{{" && messageContent.slice(-2) === "}}") return new MessagesPlaceholder({ + variableName: messageContent.slice(2, -2), + optional: true + }); + else if (typeof messageContent === "string" && messageContent[0] === "{" && messageContent[messageContent.length - 1] === "}") return new MessagesPlaceholder({ + variableName: messageContent.slice(1, -1), + optional: true + }); + throw new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `"f-string"`}: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by ${extra?.templateFormat === "mustache" ? "double" : "single"} curly braces.`); + } + const message = coerceMessageLikeToMessage(messagePromptTemplateLike); + let templateData; + if (typeof message.content === "string") templateData = message.content; + else templateData = message.content.map((item) => { + if ("text" in item) return { + ...item, + text: item.text + }; + else if ("image_url" in item) return { + ...item, + image_url: item.image_url + }; + else return item; + }); + if (message._getType() === "human") return HumanMessagePromptTemplate.fromTemplate(templateData, extra); + else if (message._getType() === "ai") return AIMessagePromptTemplate.fromTemplate(templateData, extra); + else if (message._getType() === "system") return SystemMessagePromptTemplate.fromTemplate(templateData, extra); + else if (ChatMessage.isInstance(message)) return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra); + else throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); +} +function isMessagesPlaceholder(x) { + return x.constructor.lc_name() === "MessagesPlaceholder"; +} +/** +* Class that represents a chat prompt. It extends the +* BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate +* instances to format a series of messages for a conversation. +* @example +* ```typescript +* const message = SystemMessagePromptTemplate.fromTemplate("{text}"); +* const chatPrompt = ChatPromptTemplate.fromMessages([ +* ["ai", "You are a helpful assistant."], +* message, +* ]); +* const formattedChatPrompt = await chatPrompt.invoke({ +* text: "Hello world!", +* }); +* ``` +*/ +var ChatPromptTemplate = class ChatPromptTemplate extends BaseChatPromptTemplate { + static lc_name() { + return "ChatPromptTemplate"; + } + get lc_aliases() { + return { promptMessages: "messages" }; + } + promptMessages; + validateTemplate = true; + templateFormat = "f-string"; + constructor(input) { + super(input); + if (input.templateFormat === "mustache" && input.validateTemplate === void 0) this.validateTemplate = false; + Object.assign(this, input); + if (this.validateTemplate) { + const inputVariablesMessages = /* @__PURE__ */ 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 difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); + if (difference.size > 0) throw new Error(`Input variables \`${[...difference]}\` are not used in any of the prompt messages.`); + const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); + 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; + message.content = 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 if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url && typeof item.image_url.url === "string") imageUrl = item.image_url.url; + const formattedUrl = await PromptTemplate.fromTemplate(imageUrl, { templateFormat: this.templateFormat }).format(inputValues); + if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) item.image_url.url = formattedUrl; + else item.image_url = formattedUrl; + return item; + })); + 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 { + let inputValues; + if (this.templateFormat === "mustache") inputValues = { ...allValues }; + else inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { + if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) throw addLangChainErrorFields(/* @__PURE__ */ new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT"); + 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 + }; + return new ChatPromptTemplate({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }); + } + static fromTemplate(template, options) { + const humanTemplate = new HumanMessagePromptTemplate({ prompt: PromptTemplate.fromTemplate(template, options) }); + return this.fromMessages([humanTemplate]); + } + /** + * Create a chat model-specific prompt from individual chat messages + * or message-like tuples. + * @param promptMessages Messages to be passed to the chat model + * @returns A new ChatPromptTemplate + */ + static fromMessages(promptMessages, extra) { + const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(promptMessage instanceof ChatPromptTemplate ? promptMessage.promptMessages : [_coerceMessagePromptTemplateLike(promptMessage, extra)]), []); + const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => promptMessage instanceof ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc, Object.create(null)); + const inputVariables = /* @__PURE__ */ 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, + templateFormat: extra?.templateFormat + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/prompts/few_shot.js +/** +* Prompt template that contains few-shot examples. +* @augments BasePromptTemplate +* @augments FewShotPromptTemplateInput +* @example +* ```typescript +* const examplePrompt = PromptTemplate.fromTemplate( +* "Input: {input}\nOutput: {output}", +* ); +* +* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( +* [ +* { input: "happy", output: "sad" }, +* { input: "tall", output: "short" }, +* { input: "energetic", output: "lethargic" }, +* { input: "sunny", output: "gloomy" }, +* { input: "windy", output: "calm" }, +* ], +* new OpenAIEmbeddings(), +* HNSWLib, +* { k: 1 }, +* ); +* +* const dynamicPrompt = new FewShotPromptTemplate({ +* exampleSelector, +* examplePrompt, +* prefix: "Give the antonym of every input", +* suffix: "Input: {adjective}\nOutput:", +* inputVariables: ["adjective"], +* }); +* +* // Format the dynamic prompt with the input 'rainy' +* console.log(await dynamicPrompt.format({ adjective: "rainy" })); +* +* ``` +*/ +var FewShotPromptTemplate = class FewShotPromptTemplate extends BaseStringPromptTemplate { + lc_serializable = false; + examples; + exampleSelector; + examplePrompt; + suffix = ""; + exampleSeparator = "\n\n"; + prefix = ""; + templateFormat = "f-string"; + validateTemplate = true; + constructor(input) { + super(input); + 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 + }; + return new FewShotPromptTemplate({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }); + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); + return renderTemplate([ + this.prefix, + ...exampleStrings, + this.suffix + ].join(this.exampleSeparator), 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 examples; + if (Array.isArray(data.examples)) examples = data.examples; + else throw new Error("Invalid examples format. Only list or string are supported."); + return new FewShotPromptTemplate({ + inputVariables: data.input_variables, + examplePrompt, + examples, + exampleSeparator: data.example_separator, + prefix: data.prefix, + suffix: data.suffix, + templateFormat: data.template_format + }); + } +}; +/** +* Chat prompt template that contains few-shot examples. +* @augments BasePromptTemplateInput +* @augments FewShotChatMessagePromptTemplateInput +*/ +var FewShotChatMessagePromptTemplate = class FewShotChatMessagePromptTemplate extends BaseChatPromptTemplate { + lc_serializable = true; + examples; + exampleSelector; + examplePrompt; + suffix = ""; + exampleSeparator = "\n\n"; + prefix = ""; + templateFormat = "f-string"; + validateTemplate = true; + _getPromptType() { + return "few_shot_chat"; + } + static lc_name() { + return "FewShotChatMessagePromptTemplate"; + } + constructor(fields) { + super(fields); + this.examples = fields.examples; + this.examplePrompt = fields.examplePrompt; + this.exampleSeparator = fields.exampleSeparator ?? "\n\n"; + this.exampleSelector = fields.exampleSelector; + this.prefix = fields.prefix ?? ""; + this.suffix = fields.suffix ?? ""; + this.templateFormat = fields.templateFormat ?? "f-string"; + this.validateTemplate = fields.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"); + } + /** + * Formats the list of values and returns a list of formatted messages. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async formatMessages(values) { + const allValues = await this.mergePartialAndUserVariables(values); + let examples = await this.getExamples(allValues); + examples = examples.map((example) => { + const result = {}; + this.examplePrompt.inputVariables.forEach((inputVariable) => { + result[inputVariable] = example[inputVariable]; + }); + return result; + }); + const messages = []; + for (const example of examples) { + const exampleMessages = await this.examplePrompt.formatMessages(example); + messages.push(...exampleMessages); + } + return messages; + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = (await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example)))).flat().map((message) => message.content); + return renderTemplate([ + this.prefix, + ...exampleStrings, + this.suffix + ].join(this.exampleSeparator), this.templateFormat, allValues); + } + /** + * Partially formats the prompt with the given values. + * @param values The values to partially format the prompt with. + * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((variable) => !(variable in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new FewShotChatMessagePromptTemplate({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/prompts/pipeline.js +/** +* Class that handles a sequence of prompts, each of which may require +* different input variables. Includes methods for formatting these +* prompts, extracting required input values, and handling partial +* prompts. +* @example +* ```typescript +* const composedPrompt = new PipelinePromptTemplate({ +* pipelinePrompts: [ +* { +* name: "introduction", +* prompt: PromptTemplate.fromTemplate(`You are impersonating {person}.`), +* }, +* { +* name: "example", +* prompt: PromptTemplate.fromTemplate( +* `Here's an example of an interaction: +* Q: {example_q} +* A: {example_a}`, +* ), +* }, +* { +* name: "start", +* prompt: PromptTemplate.fromTemplate( +* `Now, do this for real! +* Q: {input} +* A:`, +* ), +* }, +* ], +* finalPrompt: PromptTemplate.fromTemplate( +* `{introduction} +* {example} +* {start}`, +* ), +* }); +* +* const formattedPrompt = await composedPrompt.format({ +* person: "Elon Musk", +* example_q: `What's your favorite car?`, +* example_a: "Tesla", +* input: `What's your favorite social media site?`, +* }); +* ``` +*/ +var PipelinePromptTemplate = class PipelinePromptTemplate extends BasePromptTemplate { + static lc_name() { + return "PipelinePromptTemplate"; + } + pipelinePrompts; + finalPrompt; + constructor(input) { + super({ + ...input, + inputVariables: [] + }); + this.pipelinePrompts = input.pipelinePrompts; + this.finalPrompt = input.finalPrompt; + this.inputVariables = this.computeInputValues(); + } + /** + * Computes the input values required by the pipeline prompts. + * @returns Array of input values required by the pipeline prompts. + */ + 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; + }, {}); + } + /** + * Formats the pipeline prompts based on the provided input values. + * @param values Input values to format the pipeline prompts. + * @returns Promise that resolves with the formatted input values. + */ + 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); + } + /** + * Formats the final prompt value based on the provided input values. + * @param values Input values to format the final prompt value. + * @returns Promise that resolves with the formatted final prompt value. + */ + async formatPromptValue(values) { + return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); + } + async format(values) { + return this.finalPrompt.format(await this.formatPipelinePrompts(values)); + } + /** + * Handles partial prompts, which are prompts that have been partially + * filled with input values. + * @param values Partial input values. + * @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables. + */ + 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"; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/prompts/structured.js +function isWithStructuredOutput(x) { + return typeof x === "object" && x != null && "withStructuredOutput" in x && typeof x.withStructuredOutput === "function"; +} +function isRunnableBinding(x) { + return typeof x === "object" && x != null && "lc_id" in x && Array.isArray(x.lc_id) && x.lc_id.join("/") === "langchain_core/runnables/RunnableBinding"; +} +var StructuredPrompt = class StructuredPrompt extends ChatPromptTemplate { + schema; + method; + lc_namespace = [ + "langchain_core", + "prompts", + "structured" + ]; + get lc_aliases() { + return { + ...super.lc_aliases, + schema: "schema_" + }; + } + constructor(input) { + super(input); + this.schema = input.schema; + this.method = input.method; + } + pipe(coerceable) { + if (isWithStructuredOutput(coerceable)) return super.pipe(coerceable.withStructuredOutput(this.schema)); + if (isRunnableBinding(coerceable) && isWithStructuredOutput(coerceable.bound)) return super.pipe(new RunnableBinding({ + bound: coerceable.bound.withStructuredOutput(this.schema, ...this.method ? [{ method: this.method }] : []), + kwargs: coerceable.kwargs ?? {}, + config: coerceable.config, + configFactories: coerceable.configFactories + })); + throw new Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`); + } + static fromMessagesAndSchema(promptMessages, schema, method) { + return StructuredPrompt.fromMessages(promptMessages, { + schema, + method + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/prompts/index.js +var prompts_exports = /* @__PURE__ */ __exportAll({ + 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, + DictPromptTemplate: () => DictPromptTemplate, + FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, + FewShotPromptTemplate: () => FewShotPromptTemplate, + HumanMessagePromptTemplate: () => HumanMessagePromptTemplate, + ImagePromptTemplate: () => ImagePromptTemplate, + MessagesPlaceholder: () => MessagesPlaceholder, + PipelinePromptTemplate: () => PipelinePromptTemplate, + PromptTemplate: () => PromptTemplate, + StructuredPrompt: () => StructuredPrompt, + SystemMessagePromptTemplate: () => SystemMessagePromptTemplate, + checkValidTemplate: () => checkValidTemplate, + interpolateFString: () => interpolateFString, + interpolateMustache: () => interpolateMustache, + parseFString: () => parseFString, + parseMustache: () => parseMustache, + parseTemplate: () => parseTemplate, + renderTemplate: () => renderTemplate +}); +//#endregion +//#region node_modules/@langchain/core/dist/retrievers/document_compressors/index.js +var document_compressors_exports = /* @__PURE__ */ __exportAll({ BaseDocumentCompressor: () => BaseDocumentCompressor }); +/** +* Base Document Compression class. All compressors should extend this class. +*/ +var BaseDocumentCompressor = class { + static isBaseDocumentCompressor(x) { + return x?.compressDocuments !== void 0; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/retrievers/index.js +var retrievers_exports = /* @__PURE__ */ __exportAll({ BaseRetriever: () => BaseRetriever }); +/** +* Abstract base class for a document retrieval system, designed to +* process string queries and return the most relevant documents from a source. +* +* `BaseRetriever` provides common properties and methods for derived retrievers, +* such as callbacks, tagging, and verbose logging. Custom retrieval systems +* should extend this class and implement `_getRelevantDocuments` to define +* the specific retrieval logic. +* +* @template Metadata - The type of metadata associated with each document, +* defaulting to `Record`. +*/ +var BaseRetriever = class extends Runnable { + /** + * Optional callbacks to handle various events in the retrieval process. + */ + callbacks; + /** + * Tags to label or categorize the retrieval operation. + */ + tags; + /** + * Metadata to provide additional context or information about the retrieval + * operation. + */ + metadata; + /** + * If set to `true`, enables verbose logging for the retrieval process. + */ + verbose; + /** + * Constructs a new `BaseRetriever` instance with optional configuration fields. + * + * @param fields - Optional input configuration that can include `callbacks`, + * `tags`, `metadata`, and `verbose` settings for custom retriever behavior. + */ + constructor(fields) { + super(fields); + this.callbacks = fields?.callbacks; + this.tags = fields?.tags ?? []; + this.metadata = fields?.metadata ?? {}; + this.verbose = fields?.verbose ?? false; + } + /** + * TODO: This should be an abstract method, but we'd like to avoid breaking + * changes to people currently using subclassed custom retrievers. + * Change it on next major release. + */ + /** + * Placeholder method for retrieving relevant documents based on a query. + * + * This method is intended to be implemented by subclasses and will be + * converted to an abstract method in the next major release. Currently, it + * throws an error if not implemented, ensuring that custom retrievers define + * the specific retrieval logic. + * + * @param _query - The query string used to search for relevant documents. + * @param _callbacks - (optional) Callback manager for managing callbacks + * during retrieval. + * @returns A promise resolving to an array of `DocumentInterface` instances relevant to the query. + * @throws {Error} Throws an error indicating the method is not implemented. + */ + _getRelevantDocuments(_query, _callbacks) { + throw new Error("Not implemented!"); + } + /** + * Executes a retrieval operation. + * + * @param input - The query string used to search for relevant documents. + * @param options - (optional) Configuration options for the retrieval run, + * which may include callbacks, tags, and metadata. + * @returns A promise that resolves to an array of `DocumentInterface` instances + * representing the most relevant documents to the query. + */ + async invoke(input, options) { + const parsedConfig = ensureConfig(parseCallbackConfigArg(options)); + const runManager = await (await CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }))?.handleRetrieverStart(this.toJSON(), input, parsedConfig.runId, void 0, void 0, void 0, parsedConfig.runName); + try { + const results = await this._getRelevantDocuments(input, runManager); + await runManager?.handleRetrieverEnd(results); + return results; + } catch (error) { + await runManager?.handleRetrieverError(error); + throw error; + } + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/stores.js +var stores_exports = /* @__PURE__ */ __exportAll({ + BaseStore: () => BaseStore, + InMemoryStore: () => InMemoryStore +}); +/** +* Abstract interface for a key-value store. +*/ +var BaseStore = class extends Serializable {}; +/** +* In-memory implementation of the BaseStore using a dictionary. Used for +* storing key-value pairs in memory. +* @example +* ```typescript +* const store = new InMemoryStore(); +* await store.mset( +* Array.from({ length: 5 }).map((_, index) => [ +* `message:id:${index}`, +* index % 2 === 0 +* ? new AIMessage("ai stuff...") +* : new HumanMessage("human stuff..."), +* ]), +* ); +* +* const retrievedMessages = await store.mget(["message:id:0", "message:id:1"]); +* await store.mdelete(await store.yieldKeys("message:id:").toArray()); +* ``` +*/ +var InMemoryStore = class extends BaseStore { + lc_namespace = ["langchain", "storage"]; + store = {}; + /** + * Retrieves the values associated with the given keys from the store. + * @param keys Keys to retrieve values for. + * @returns Array of values associated with the given keys. + */ + async mget(keys) { + return keys.map((key) => this.store[key]); + } + /** + * Sets the values for the given keys in the store. + * @param keyValuePairs Array of key-value pairs to set in the store. + * @returns Promise that resolves when all key-value pairs have been set. + */ + async mset(keyValuePairs) { + for (const [key, value] of keyValuePairs) this.store[key] = value; + } + /** + * Deletes the given keys and their associated values from the store. + * @param keys Keys to delete from the store. + * @returns Promise that resolves when all keys have been deleted. + */ + async mdelete(keys) { + for (const key of keys) delete this.store[key]; + } + /** + * Asynchronous generator that yields keys from the store. If a prefix is + * provided, it only yields keys that start with the prefix. + * @param prefix Optional prefix to filter keys. + * @returns AsyncGenerator that yields keys from the store. + */ + async *yieldKeys(prefix) { + const keys = Object.keys(this.store); + for (const key of keys) if (prefix === void 0 || key.startsWith(prefix)) yield key; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/structured_query/ir.js +var Operators = { + and: "and", + or: "or", + not: "not" +}; +var Comparators = { + eq: "eq", + ne: "ne", + lt: "lt", + gt: "gt", + lte: "lte", + gte: "gte" +}; +/** +* Abstract class for visiting expressions. Subclasses must implement +* visitOperation, visitComparison, and visitStructuredQuery methods. +*/ +var Visitor = class {}; +/** +* Abstract class representing an expression. Subclasses must implement +* the exprName property and the accept method. +*/ +var Expression = class { + accept(visitor) { + if (this.exprName === "Operation") return visitor.visitOperation(this); + else if (this.exprName === "Comparison") return visitor.visitComparison(this); + else if (this.exprName === "StructuredQuery") return visitor.visitStructuredQuery(this); + else throw new Error("Unknown Expression type"); + } +}; +/** +* Abstract class representing a filter directive. It extends the +* Expression class. +*/ +var FilterDirective = class extends Expression {}; +/** +* Class representing a comparison filter directive. It extends the +* FilterDirective class. +*/ +var Comparison = class extends FilterDirective { + exprName = "Comparison"; + constructor(comparator, attribute, value) { + super(); + this.comparator = comparator; + this.attribute = attribute; + this.value = value; + } +}; +/** +* Class representing an operation filter directive. It extends the +* FilterDirective class. +*/ +var Operation = class extends FilterDirective { + exprName = "Operation"; + constructor(operator, args) { + super(); + this.operator = operator; + this.args = args; + } +}; +/** +* Class representing a structured query expression. It extends the +* Expression class. +*/ +var StructuredQuery = class extends Expression { + exprName = "StructuredQuery"; + constructor(query, filter) { + super(); + this.query = query; + this.filter = filter; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/structured_query/utils.js +/** +* Checks if the provided argument is an object and not an array. +*/ +function isObject(obj) { + return obj && typeof obj === "object" && !Array.isArray(obj); +} +/** +* Checks if a provided filter is empty. The filter can be a function, an +* object, a string, or undefined. +*/ +function isFilterEmpty(filter) { + if (!filter) return true; + if (typeof filter === "string" && filter.length > 0) return false; + if (typeof filter === "function") return false; + return isObject(filter) && Object.keys(filter).length === 0; +} +/** +* Checks if the provided value is an integer. +*/ +function isInt(value) { + if (typeof value === "number") return value % 1 === 0; + else if (typeof value === "string") { + const numberValue = parseInt(value, 10); + return !Number.isNaN(numberValue) && numberValue % 1 === 0 && numberValue.toString() === value; + } + return false; +} +/** +* Checks if the provided value is a floating-point number. +*/ +function isFloat(value) { + if (typeof value === "number") return value % 1 !== 0; + else if (typeof value === "string") { + const numberValue = parseFloat(value); + return !Number.isNaN(numberValue) && numberValue % 1 !== 0 && numberValue.toString() === value; + } + return false; +} +/** +* Checks if the provided value is a string that cannot be parsed into a +* number. +*/ +function isString(value) { + return typeof value === "string" && (Number.isNaN(parseFloat(value)) || parseFloat(value).toString() !== value); +} +/** +* Checks if the provided value is a boolean. +*/ +function isBoolean(value) { + return typeof value === "boolean"; +} +/** +* Casts a value that might be string or number to actual string or number. +* Since LLM might return back an integer/float as a string, we need to cast +* it back to a number, as many vector databases can't handle number as string +* values as a comparator. +*/ +function castValue(input) { + let value; + if (isString(input)) value = input; + else if (isInt(input)) value = parseInt(input, 10); + else if (isFloat(input)) value = parseFloat(input); + else if (isBoolean(input)) value = Boolean(input); + else throw new Error("Unsupported value type"); + return value; +} +//#endregion +//#region node_modules/@langchain/core/dist/structured_query/base.js +/** +* Abstract class that provides a blueprint for creating specific +* translator classes. Defines two abstract methods: formatFunction and +* mergeFilters. +*/ +var BaseTranslator = class extends Visitor {}; +/** +* Class that extends the BaseTranslator class and provides concrete +* implementations for the abstract methods. Also declares three types: +* VisitOperationOutput, VisitComparisonOutput, and +* VisitStructuredQueryOutput, which are used as the return types for the +* visitOperation, visitComparison, and visitStructuredQuery methods +* respectively. +*/ +var BasicTranslator = class extends BaseTranslator { + allowedOperators; + allowedComparators; + constructor(opts) { + super(); + this.allowedOperators = opts?.allowedOperators ?? [Operators.and, Operators.or]; + this.allowedComparators = opts?.allowedComparators ?? [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + } + formatFunction(func) { + if (func in Comparators) { + if (this.allowedComparators.length > 0 && this.allowedComparators.indexOf(func) === -1) throw new Error(`Comparator ${func} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`); + } else if (func in Operators) { + if (this.allowedOperators.length > 0 && this.allowedOperators.indexOf(func) === -1) throw new Error(`Operator ${func} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`); + } else throw new Error("Unknown comparator or operator"); + return `$${func}`; + } + /** + * Visits an operation and returns a result. + * @param operation The operation to visit. + * @returns The result of visiting the operation. + */ + visitOperation(operation) { + const args = operation.args?.map((arg) => arg.accept(this)); + return { [this.formatFunction(operation.operator)]: args }; + } + /** + * Visits a comparison and returns a result. + * @param comparison The comparison to visit. + * @returns The result of visiting the comparison. + */ + visitComparison(comparison) { + return { [comparison.attribute]: { [this.formatFunction(comparison.comparator)]: castValue(comparison.value) } }; + } + /** + * Visits a structured query and returns a result. + * @param query The structured query to visit. + * @returns The result of visiting the structured query. + */ + visitStructuredQuery(query) { + let nextArg = {}; + if (query.filter) nextArg = { filter: query.filter.accept(this) }; + return nextArg; + } + mergeFilters(defaultFilter, generatedFilter, mergeType = "and", forceDefaultFilter = false) { + if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return; + if (isFilterEmpty(defaultFilter) || mergeType === "replace") { + if (isFilterEmpty(generatedFilter)) return; + return generatedFilter; + } + if (isFilterEmpty(generatedFilter)) { + if (forceDefaultFilter) return defaultFilter; + if (mergeType === "and") return; + return defaultFilter; + } + if (mergeType === "and") return { $and: [defaultFilter, generatedFilter] }; + else if (mergeType === "or") return { $or: [defaultFilter, generatedFilter] }; + else throw new Error("Unknown merge type"); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/structured_query/functional.js +/** +* A class that extends `BaseTranslator` to translate structured queries +* into functional filters. +* @example +* ```typescript +* const functionalTranslator = new FunctionalTranslator(); +* const relevantDocuments = await functionalTranslator.getRelevantDocuments( +* "Which movies are rated higher than 8.5?", +* ); +* ``` +*/ +var FunctionalTranslator = class extends BaseTranslator { + allowedOperators = [Operators.and, Operators.or]; + allowedComparators = [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + formatFunction() { + throw new Error("Not implemented"); + } + /** + * Returns the allowed comparators for a given data type. + * @param input The input value to get the allowed comparators for. + * @returns An array of allowed comparators for the input data type. + */ + getAllowedComparatorsForType(inputType) { + switch (inputType) { + case "string": return [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + case "number": return [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + case "boolean": return [Comparators.eq, Comparators.ne]; + default: throw new Error(`Unsupported data type: ${inputType}`); + } + } + /** + * Returns a function that performs a comparison based on the provided + * comparator. + * @param comparator The comparator to base the comparison function on. + * @returns A function that takes two arguments and returns a boolean based on the comparison. + */ + getComparatorFunction(comparator) { + switch (comparator) { + case Comparators.eq: return (a, b) => a === b; + case Comparators.ne: return (a, b) => a !== b; + case Comparators.gt: return (a, b) => a > b; + case Comparators.gte: return (a, b) => a >= b; + case Comparators.lt: return (a, b) => a < b; + case Comparators.lte: return (a, b) => a <= b; + default: throw new Error("Unknown comparator"); + } + } + /** + * Returns a function that performs an operation based on the provided + * operator. + * @param operator The operator to base the operation function on. + * @returns A function that takes two boolean arguments and returns a boolean based on the operation. + */ + getOperatorFunction(operator) { + switch (operator) { + case Operators.and: return (a, b) => a && b; + case Operators.or: return (a, b) => a || b; + default: throw new Error("Unknown operator"); + } + } + /** + * Visits the operation part of a structured query and translates it into + * a functional filter. + * @param operation The operation part of a structured query. + * @returns A function that takes a `Document` as an argument and returns a boolean based on the operation. + */ + visitOperation(operation) { + const { operator, args } = operation; + if (this.allowedOperators.includes(operator)) { + const operatorFunction = this.getOperatorFunction(operator); + return (document) => { + if (!args) return true; + return args.reduce((acc, arg) => { + const result = arg.accept(this); + if (typeof result === "function") return operatorFunction(acc, result(document)); + else throw new Error("Filter is not a function"); + }, true); + }; + } else throw new Error("Operator not allowed"); + } + /** + * Visits the comparison part of a structured query and translates it into + * a functional filter. + * @param comparison The comparison part of a structured query. + * @returns A function that takes a `Document` as an argument and returns a boolean based on the comparison. + */ + visitComparison(comparison) { + const { comparator, attribute, value } = comparison; + const undefinedTrue = [Comparators.ne]; + if (this.allowedComparators.includes(comparator)) { + if (!this.getAllowedComparatorsForType(typeof value).includes(comparator)) throw new Error(`'${comparator}' comparator not allowed to be used with ${typeof value}`); + const comparatorFunction = this.getComparatorFunction(comparator); + return (document) => { + const documentValue = document.metadata[attribute]; + if (documentValue === void 0) { + if (undefinedTrue.includes(comparator)) return true; + return false; + } + return comparatorFunction(documentValue, castValue(value)); + }; + } else throw new Error("Comparator not allowed"); + } + /** + * Visits a structured query and translates it into a functional filter. + * @param query The structured query to translate. + * @returns An object containing a `filter` property, which is a function that takes a `Document` as an argument and returns a boolean based on the structured query. + */ + visitStructuredQuery(query) { + if (!query.filter) return {}; + const filterFunction = query.filter?.accept(this); + if (typeof filterFunction !== "function") throw new Error("Structured query filter is not a function"); + return { filter: filterFunction }; + } + /** + * Merges two filters into one, based on the specified merge type. + * @param defaultFilter The default filter function. + * @param generatedFilter The generated filter function. + * @param mergeType The type of merge to perform. Can be 'and', 'or', or 'replace'. Default is 'and'. + * @returns A function that takes a `Document` as an argument and returns a boolean based on the merged filters, or `undefined` if both filters are empty. + */ + mergeFilters(defaultFilter, generatedFilter, mergeType = "and") { + if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return; + if (isFilterEmpty(defaultFilter) || mergeType === "replace") { + if (isFilterEmpty(generatedFilter)) return; + return generatedFilter; + } + if (isFilterEmpty(generatedFilter)) { + if (mergeType === "and") return; + return defaultFilter; + } + if (mergeType === "and") return (document) => defaultFilter(document) && generatedFilter(document); + else if (mergeType === "or") return (document) => defaultFilter(document) || generatedFilter(document); + else throw new Error("Unknown merge type"); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/structured_query/index.js +var structured_query_exports = /* @__PURE__ */ __exportAll({ + BaseTranslator: () => BaseTranslator, + BasicTranslator: () => BasicTranslator, + Comparators: () => Comparators, + Comparison: () => Comparison, + Expression: () => Expression, + FilterDirective: () => FilterDirective, + FunctionalTranslator: () => FunctionalTranslator, + Operation: () => Operation, + Operators: () => Operators, + StructuredQuery: () => StructuredQuery, + Visitor: () => Visitor, + castValue: () => castValue, + isBoolean: () => isBoolean, + isFilterEmpty: () => isFilterEmpty, + isFloat: () => isFloat, + isInt: () => isInt, + isObject: () => isObject, + isString: () => isString +}); +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/stream.js +function isChatModelStream(received) { + if (received == null || typeof received !== "object") return false; + const stream = received; + return typeof stream.text !== "undefined" && typeof stream.toolCalls !== "undefined" && typeof stream.reasoning !== "undefined" && typeof stream.usage !== "undefined" && typeof stream.output !== "undefined" && typeof stream[Symbol.asyncIterator] === "function"; +} +function matchesPartialObject(actual, expected, equals) { + if (actual == null) return false; + return Object.entries(expected).every(([key, value]) => equals(actual[key], value)); +} +function matchesStreamUsage(actual, expected, equals) { + if (actual == null) return false; + return matchesPartialObject(actual, expected, equals); +} +function getOutputText(message) { + return message.content.find((block) => block.type === "text")?.text; +} +function matchesStreamOutput(message, expected, equals) { + if (expected.id !== void 0 && message.id !== expected.id) return false; + if (expected.text !== void 0 && getOutputText(message) !== expected.text) return false; + if (expected.toolCalls !== void 0) { + const calls = message.tool_calls ?? []; + if (calls.length !== expected.toolCalls.length) return false; + for (let i = 0; i < expected.toolCalls.length; i++) { + const call = calls[i]; + const exp = expected.toolCalls[i]; + if (call?.name !== exp.name || !equals(call.args, exp.args)) return false; + } + } + if (expected.usage !== void 0 && !matchesStreamUsage(message.usage_metadata, expected.usage, equals)) return false; + if (expected.responseMetadata !== void 0 && !matchesPartialObject(message.response_metadata, expected.responseMetadata, equals)) return false; + return true; +} +function invalidStreamResult(received, matcherName, utils) { + return { + pass: false, + message: () => `${utils.matcherHint(matcherName)}\n\nExpected: ChatModelStream (return value of model.streamEvents("Hello"))\nReceived: ${utils.printReceived(received)}`, + actual: received, + expected: "ChatModelStream" + }; +} +function applyNot(pass, isNot) { + return isNot ? !pass : pass; +} +async function toHaveStreamText(received, expected) { + const { isNot, utils } = this; + const matcherName = "toHaveStreamText"; + if (!isChatModelStream(received)) return invalidStreamResult(received, matcherName, utils); + const actual = await received.text; + return { + pass: applyNot(actual === expected, isNot), + message: () => `${utils.matcherHint(matcherName, void 0, void 0, { isNot })}\n\nExpected stream text: ${isNot ? "not " : ""}${utils.printExpected(expected)}\nReceived stream text: ${utils.printReceived(actual)}`, + actual, + expected + }; +} +async function toHaveStreamReasoning(received, expected) { + const { isNot, utils } = this; + const matcherName = "toHaveStreamReasoning"; + if (!isChatModelStream(received)) return invalidStreamResult(received, matcherName, utils); + const actual = await received.reasoning; + return { + pass: applyNot(actual === expected, isNot), + message: () => `${utils.matcherHint(matcherName, void 0, void 0, { isNot })}\n\nExpected stream reasoning: ${isNot ? "not " : ""}${utils.printExpected(expected)}\nReceived stream reasoning: ${utils.printReceived(actual)}`, + actual, + expected + }; +} +async function toHaveStreamToolCalls(received, expected) { + const { isNot, utils } = this; + const matcherName = "toHaveStreamToolCalls"; + if (!isChatModelStream(received)) return invalidStreamResult(received, matcherName, utils); + const actual = await received.toolCalls; + let pass = actual.length === expected.length && expected.every((exp, i) => { + const call = actual[i]; + return call?.name === exp.name && this.equals(call.args, exp.args); + }); + pass = applyNot(pass, isNot); + return { + pass, + message: () => `${utils.matcherHint(matcherName, void 0, void 0, { isNot })}\n\nExpected stream tool calls: ${utils.printExpected(expected)}\nReceived stream tool calls: ${utils.printReceived(actual.map((tc) => ({ + name: tc.name, + args: tc.args + })))}`, + actual: actual.map((tc) => ({ + name: tc.name, + args: tc.args + })), + expected + }; +} +async function toHaveStreamUsage(received, expected) { + const { isNot, utils } = this; + const matcherName = "toHaveStreamUsage"; + if (!isChatModelStream(received)) return invalidStreamResult(received, matcherName, utils); + const actual = await received.usage; + return { + pass: applyNot(matchesStreamUsage(actual, expected, this.equals), isNot), + message: () => `${utils.matcherHint(matcherName, void 0, void 0, { isNot })}\n\nExpected stream usage: ${utils.printExpected(expected)}\nReceived stream usage: ${utils.printReceived(actual)}`, + actual, + expected + }; +} +async function toHaveStreamOutput(received, expected) { + const { isNot, utils } = this; + const matcherName = "toHaveStreamOutput"; + if (!isChatModelStream(received)) return invalidStreamResult(received, matcherName, utils); + const message = await received.output; + return { + pass: applyNot(matchesStreamOutput(message, expected, this.equals), isNot), + message: () => `${utils.matcherHint(matcherName, void 0, void 0, { isNot })}\n\nExpected stream output: ${utils.printExpected(expected)}\nReceived stream output: ${utils.printReceived({ + id: message.id, + text: getOutputText(message), + tool_calls: message.tool_calls?.map((tc) => ({ + name: tc.name, + args: tc.args + })), + usage_metadata: message.usage_metadata, + response_metadata: message.response_metadata + })}`, + actual: message, + expected + }; +} +/** Stream matchers for `expect.extend()`. */ +var streamMatchers = { + toHaveStreamText, + toHaveStreamReasoning, + toHaveStreamToolCalls, + toHaveStreamUsage, + toHaveStreamOutput +}; +//#endregion +//#region node_modules/@langchain/core/dist/testing/matchers.js +function getMessageTypeName(msg) { + if (!BaseMessage.isInstance(msg)) return typeof msg; + return msg.constructor.name || msg.type; +} +function makeMessageTypeMatcher(typeName, isInstance) { + return function(received, expected) { + const { isNot, utils } = this; + if (!isInstance(received)) return { + pass: false, + message: () => `${utils.matcherHint(`toBe${typeName}`, void 0, void 0)}\n\nExpected: ${isNot ? "not " : ""}${typeName}\nReceived: ${getMessageTypeName(received)}`, + actual: getMessageTypeName(received), + expected: typeName + }; + if (expected === void 0) return { + pass: true, + message: () => `${utils.matcherHint(`toBe${typeName}`, void 0, void 0)}\n\nExpected: not ${typeName}\nReceived: ${typeName}` + }; + const msg = received; + if (typeof expected === "string") return { + pass: msg.content === expected, + message: () => `${utils.matcherHint(`toBe${typeName}`, void 0, void 0)}\n\nExpected: ${typeName} with content ${utils.printExpected(expected)}\nReceived: ${typeName} with content ${utils.printReceived(msg.content)}`, + actual: msg.content, + expected + }; + return { + pass: Object.entries(expected).every(([key, value]) => this.equals(msg[key], value)), + message: () => { + const receivedFields = {}; + for (const key of Object.keys(expected)) receivedFields[key] = msg[key]; + return `${utils.matcherHint(`toBe${typeName}`, void 0, void 0)}\n\nExpected: ${typeName} matching ${utils.printExpected(expected)}\nReceived: ${typeName} with ${utils.printReceived(receivedFields)}`; + }, + actual: (() => { + const receivedFields = {}; + for (const key of Object.keys(expected)) receivedFields[key] = msg[key]; + return receivedFields; + })(), + expected + }; + }; +} +var toBeHumanMessage = makeMessageTypeMatcher("HumanMessage", HumanMessage.isInstance); +var toBeAIMessage = makeMessageTypeMatcher("AIMessage", AIMessage.isInstance); +var toBeSystemMessage = makeMessageTypeMatcher("SystemMessage", SystemMessage.isInstance); +var toBeToolMessage = makeMessageTypeMatcher("ToolMessage", ToolMessage.isInstance); +function toHaveToolCalls(received, expected) { + const { isNot, utils } = this; + if (!AIMessage.isInstance(received)) return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolCalls")}\n\nExpected: AIMessage\nReceived: ${getMessageTypeName(received)}` + }; + const actual = received.tool_calls ?? []; + if (actual.length !== expected.length) return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolCalls")}\n\nExpected ${isNot ? "not " : ""}${expected.length} tool call(s), received ${actual.length}`, + actual: actual.length, + expected: expected.length + }; + const unmatched = expected.filter((exp) => !actual.some((tc) => Object.entries(exp).every(([key, value]) => this.equals(tc[key], value)))); + if (unmatched.length > 0) return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolCalls")}\n\nCould not find matching tool call(s) for:\n${utils.printExpected(unmatched)}\nReceived tool calls: ${utils.printReceived(actual.map((tc) => ({ + name: tc.name, + id: tc.id, + args: tc.args + })))}`, + actual: actual.map((tc) => ({ + name: tc.name, + id: tc.id, + args: tc.args + })), + expected + }; + return { + pass: true, + message: () => `${utils.matcherHint("toHaveToolCalls")}\n\nExpected AIMessage not to have matching tool calls` + }; +} +function toHaveToolCallCount(received, expected) { + const { isNot, utils } = this; + if (!AIMessage.isInstance(received)) return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolCallCount")}\n\nExpected: AIMessage\nReceived: ${getMessageTypeName(received)}` + }; + const actual = received.tool_calls?.length ?? 0; + return { + pass: actual === expected, + message: () => `${utils.matcherHint("toHaveToolCallCount")}\n\nExpected ${isNot ? "not " : ""}${expected} tool call(s)\nReceived: ${actual}`, + actual, + expected + }; +} +function toContainToolCall(received, expected) { + const { isNot, utils } = this; + if (!AIMessage.isInstance(received)) return { + pass: false, + message: () => `${utils.matcherHint("toContainToolCall")}\n\nExpected: AIMessage\nReceived: ${getMessageTypeName(received)}` + }; + const actual = received.tool_calls ?? []; + return { + pass: actual.some((tc) => Object.entries(expected).every(([key, value]) => this.equals(tc[key], value))), + message: () => `${utils.matcherHint("toContainToolCall")}\n\nExpected AIMessage ${isNot ? "not " : ""}to contain a tool call matching ${utils.printExpected(expected)}\nReceived tool calls: ${utils.printReceived(actual.map((tc) => ({ + name: tc.name, + id: tc.id + })))}`, + actual: actual.map((tc) => ({ + name: tc.name, + id: tc.id + })), + expected + }; +} +function toHaveToolMessages(received, expected) { + const { isNot, utils } = this; + if (!Array.isArray(received)) return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolMessages")}\n\nExpected an array of messages\nReceived: ${typeof received}` + }; + const toolMessages = received.filter(ToolMessage.isInstance); + if (toolMessages.length !== expected.length) return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolMessages")}\n\nExpected ${isNot ? "not " : ""}${expected.length} tool message(s), found ${toolMessages.length}`, + actual: toolMessages.length, + expected: expected.length + }; + for (let i = 0; i < expected.length; i++) if (!Object.entries(expected[i]).every(([key, value]) => this.equals(toolMessages[i][key], value))) return { + pass: false, + message: () => { + const receivedFields = {}; + for (const key of Object.keys(expected[i])) receivedFields[key] = toolMessages[i][key]; + return `${utils.matcherHint("toHaveToolMessages")}\n\nTool message at index ${i} did not match:\nExpected: ${utils.printExpected(expected[i])}\nReceived: ${utils.printReceived(receivedFields)}`; + }, + actual: toolMessages[i], + expected: expected[i] + }; + return { + pass: true, + message: () => `${utils.matcherHint("toHaveToolMessages")}\n\nExpected messages not to contain matching tool messages` + }; +} +function toHaveBeenInterrupted(received, expectedValue) { + const { isNot, utils } = this; + const interrupts = received?.__interrupt__; + if (!(Array.isArray(interrupts) && interrupts.length > 0)) return { + pass: false, + message: () => `${utils.matcherHint("toHaveBeenInterrupted")}\n\nExpected result ${isNot ? "not " : ""}to have been interrupted\nReceived __interrupt__: ${utils.printReceived(interrupts)}` + }; + if (expectedValue === void 0) return { + pass: true, + message: () => `${utils.matcherHint("toHaveBeenInterrupted")}\n\nExpected result not to have been interrupted\nReceived ${interrupts.length} interrupt(s)` + }; + const actualValue = interrupts[0]?.value; + return { + pass: this.equals(actualValue, expectedValue), + message: () => `${utils.matcherHint("toHaveBeenInterrupted")}\n\nExpected interrupt value: ${utils.printExpected(expectedValue)}\nReceived interrupt value: ${utils.printReceived(actualValue)}`, + actual: actualValue, + expected: expectedValue + }; +} +function toHaveStructuredResponse(received, expected) { + const { isNot, utils } = this; + const structuredResponse = received?.structuredResponse; + if (!(structuredResponse !== void 0)) return { + pass: false, + message: () => `${utils.matcherHint("toHaveStructuredResponse")}\n\nExpected result ${isNot ? "not " : ""}to have a structured response\nReceived structuredResponse: undefined` + }; + if (expected === void 0) return { + pass: true, + message: () => `${utils.matcherHint("toHaveStructuredResponse")}\n\nExpected result not to have a structured response` + }; + return { + pass: Object.entries(expected).every(([key, value]) => this.equals(structuredResponse[key], value)), + message: () => `${utils.matcherHint("toHaveStructuredResponse")}\n\nExpected structured response: ${utils.printExpected(expected)}\nReceived structured response: ${utils.printReceived(structuredResponse)}`, + actual: structuredResponse, + expected + }; +} +/** +* All matcher functions bundled for convenient use with `expect.extend()`. +*/ +var langchainMatchers = { + toBeHumanMessage, + toBeAIMessage, + toBeSystemMessage, + toBeToolMessage, + toHaveToolCalls, + toHaveToolCallCount, + toContainToolCall, + toHaveToolMessages, + toHaveBeenInterrupted, + toHaveStructuredResponse, + ...streamMatchers +}; +//#endregion +//#region node_modules/@langchain/core/dist/testing/fake_model_builder.js +function deriveContent(messages) { + return messages.map((m) => m.text).filter(Boolean).join("-"); +} +var idCounter = 0; +function nextToolCallId() { + idCounter += 1; + return `fake_tc_${idCounter}`; +} +/** +* A fake chat model for testing, created via {@link fakeModel}. +* +* Queue responses with `.respond()` and `.respondWithTools()`, then +* pass the instance directly wherever a chat model is expected. +* Responses are consumed in first-in-first-out order — one per `invoke()` call. +* When all queued responses are consumed, further invocations throw. +*/ +var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel { + queue = []; + _alwaysThrowError; + _structuredResponseValue; + _tools = []; + _state = { + callIndex: 0, + calls: [] + }; + /** + * All invocations recorded by this model, in order. + * Each entry contains the `messages` array and `options` that were + * passed to `invoke()`. + */ + get calls() { + return this._state.calls; + } + /** + * The number of times this model has been invoked. + */ + get callCount() { + return this._state.calls.length; + } + constructor() { + super({}); + } + _llmType() { + return "fake-model-builder"; + } + _combineLLMOutput() { + return []; + } + /** + * Enqueue a response that the model will return on its next invocation. + * @param entry A {@link BaseMessage} to return, an `Error` to throw, or + * a factory `(messages) => BaseMessage | Error` for dynamic responses. + * @returns `this`, for chaining. + */ + respond(entry) { + if (typeof entry === "function") this.queue.push({ + kind: "factory", + factory: entry + }); + else if (BaseMessage.isInstance(entry)) this.queue.push({ + kind: "message", + message: entry + }); + else this.queue.push({ + kind: "error", + error: entry + }); + return this; + } + /** + * Enqueue an {@link AIMessage} that carries the given tool calls. + * Content is derived from the input messages at invocation time. + * @param toolCalls Array of tool calls. Each entry needs `name` and + * `args`; `id` is optional and auto-generated when omitted. + * @returns `this`, for chaining. + */ + respondWithTools(toolCalls) { + this.queue.push({ + kind: "toolCalls", + toolCalls: toolCalls.map((tc) => ({ + name: tc.name, + args: tc.args, + id: tc.id ?? nextToolCallId(), + type: "tool_call" + })) + }); + return this; + } + /** + * Make every invocation throw the given error, regardless of the queue. + * @param error The error to throw. + * @returns `this`, for chaining. + */ + alwaysThrow(error) { + this._alwaysThrowError = error; + return this; + } + /** + * Set the value that {@link withStructuredOutput} will resolve to. + * @param value The structured object to return. + * @returns `this`, for chaining. + */ + structuredResponse(value) { + this._structuredResponseValue = value; + return this; + } + /** + * Bind tools to the model. Returns a new model that shares the same + * response queue and call history. + * @param tools The tools to bind, as {@link StructuredTool} instances or + * plain {@link ToolSpec} objects. + * @returns A new RunnableBinding with the tools bound. + */ + bindTools(tools) { + const merged = [...this._tools, ...tools]; + const next = new FakeBuiltModel(); + next.queue = this.queue; + next._alwaysThrowError = this._alwaysThrowError; + next._structuredResponseValue = this._structuredResponseValue; + next._tools = merged; + next._state = this._state; + return next.withConfig({}); + } + /** + * Returns a {@link Runnable} that produces the {@link structuredResponse} + * value. The schema argument is accepted for compatibility but ignored. + * @param _params Schema or params (ignored). + * @param _config Options (ignored). + * @returns A Runnable that resolves to the structured response value. + */ + withStructuredOutput(_params, _config) { + const { _structuredResponseValue } = this; + return RunnableLambda.from(async () => { + return _structuredResponseValue; + }); + } + async _generate(messages, options, _runManager) { + this._state.calls.push({ + messages: [...messages], + options + }); + const currentCallIndex = this._state.callIndex; + this._state.callIndex += 1; + if (this._alwaysThrowError) throw this._alwaysThrowError; + const entry = this.queue[currentCallIndex]; + if (!entry) throw new Error(`FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`); + if (entry.kind === "error") throw entry.error; + if (entry.kind === "factory") { + const result = entry.factory(messages); + if (!BaseMessage.isInstance(result)) throw result; + return { generations: [{ + text: "", + message: result + }] }; + } + if (entry.kind === "message") return { generations: [{ + text: "", + message: entry.message + }] }; + const content = deriveContent(messages); + return { + generations: [{ + text: content, + message: new AIMessage({ + content, + id: currentCallIndex.toString(), + tool_calls: entry.toolCalls.length > 0 ? entry.toolCalls.map((tc) => ({ + ...tc, + type: "tool_call" + })) : void 0 + }) + }], + llmOutput: {} + }; + } +}; +/** +* Creates a new {@link FakeBuiltModel} for testing. +* +* Returns a chainable builder — queue responses, then pass the model +* anywhere a chat model is expected. Responses are consumed in FIFO +* order, one per `invoke()` call. +* +* ## API summary +* +* | Method | Description | +* | --- | --- | +* | `fakeModel()` | Creates a new fake chat model. Returns a chainable builder. | +* | `.respond(message)` | Queue an `AIMessage` (or any `BaseMessage`) to return on the next invocation. | +* | `.respond(error)` | Queue an `Error` to throw on the next invocation. | +* | `.respond(factory)` | Queue a function `(messages) => BaseMessage \| Error` for dynamic responses. | +* | `.respondWithTools(toolCalls)` | Shorthand for `.respond()` with tool calls. Each entry needs `name` and `args`; `id` is optional. | +* | `.alwaysThrow(error)` | Make every invocation throw this error, regardless of the queue. | +* | `.structuredResponse(value)` | Set the value returned by `.withStructuredOutput()`. | +* | `.bindTools(tools)` | Bind tools to the model. Returns a `RunnableBinding` that shares the response queue and call recording. | +* | `.withStructuredOutput(schema)` | Returns a runnable that produces the `.structuredResponse()` value. | +* | `.calls` | Array of `{ messages, options }` for every invocation (read-only). | +* | `.callCount` | Number of times the model has been invoked. | +* +* @example +* ```typescript +* const model = fakeModel() +* .respondWithTools([{ name: "search", args: { query: "weather" } }]) +* .respond(new AIMessage("Sunny and warm.")); +* +* const r1 = await model.invoke([new HumanMessage("What's the weather?")]); +* // r1.tool_calls[0].name === "search" +* +* const r2 = await model.invoke([new HumanMessage("Thanks")]); +* // r2.content === "Sunny and warm." +* ``` +*/ +function fakeModel() { + return new FakeBuiltModel(); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/openai_stream_fixtures.js +function asAsyncIterable(items) { + return { async *[Symbol.asyncIterator]() { + for (const item of items) yield item; + } }; +} +function openAITextOnlyChunksWithUsage(model = "test-model") { + const chunks = openAITextOnlyChunks(model); + const last = chunks[chunks.length - 1]; + chunks[chunks.length - 1] = { + ...last, + usage: { + prompt_tokens: 10, + completion_tokens: 2, + total_tokens: 12 + } + }; + return chunks; +} +function openAITextOnlyChunks(model = "test-model") { + return [ + { + id: "chatcmpl-text", + model, + choices: [{ + index: 0, + delta: { + role: "assistant", + content: "Hello" + }, + finish_reason: null + }] + }, + { + id: "chatcmpl-text", + model, + choices: [{ + index: 0, + delta: { content: " world" }, + finish_reason: null + }] + }, + { + id: "chatcmpl-text", + model, + choices: [{ + index: 0, + delta: {}, + finish_reason: "stop" + }] + } + ]; +} +function openAIReasoningTextChunks(model = "test-model") { + return [ + { + id: "chatcmpl-reason", + model, + choices: [{ + index: 0, + delta: { + role: "assistant", + reasoning_content: "Let me reason..." + }, + finish_reason: null + }] + }, + { + id: "chatcmpl-reason", + model, + choices: [{ + index: 0, + delta: { content: "Answer." }, + finish_reason: null + }] + }, + { + id: "chatcmpl-reason", + model, + choices: [{ + index: 0, + delta: {}, + finish_reason: "stop" + }] + } + ]; +} +function openAIToolCallChunks(model = "test-model") { + return [ + { + id: "chatcmpl-tools", + model, + choices: [{ + index: 0, + delta: { + role: "assistant", + content: "Let me search." + }, + finish_reason: null + }] + }, + { + id: "chatcmpl-tools", + model, + choices: [{ + index: 0, + delta: { tool_calls: [{ + index: 0, + id: "call_abc", + type: "function", + function: { + name: "web_search", + arguments: "{\"query\"" + } + }] }, + finish_reason: null + }] + }, + { + id: "chatcmpl-tools", + model, + choices: [{ + index: 0, + delta: { tool_calls: [{ + index: 0, + function: { arguments: ":\"weather\"}" } + }] }, + finish_reason: null + }] + }, + { + id: "chatcmpl-tools", + model, + choices: [{ + index: 0, + delta: {}, + finish_reason: "tool_calls" + }] + } + ]; +} +function sseResponseFromOpenAIChunks(chunks) { + const encoder = new TextEncoder(); + return new Response(new ReadableStream({ start(controller) { + for (const chunk of chunks) controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`)); + controller.close(); + } }), { + status: 200, + headers: { "Content-Type": "text/event-stream" } + }); +} +//#endregion +//#region node_modules/@langchain/core/dist/testing/index.js +var testing_exports$1 = /* @__PURE__ */ __exportAll({ + FakeBuiltModel: () => FakeBuiltModel, + asAsyncIterable: () => asAsyncIterable, + fakeModel: () => fakeModel, + langchainMatchers: () => langchainMatchers, + openAIReasoningTextChunks: () => openAIReasoningTextChunks, + openAITextOnlyChunks: () => openAITextOnlyChunks, + openAITextOnlyChunksWithUsage: () => openAITextOnlyChunksWithUsage, + openAIToolCallChunks: () => openAIToolCallChunks, + sseResponseFromOpenAIChunks: () => sseResponseFromOpenAIChunks, + streamMatchers: () => streamMatchers, + toBeAIMessage: () => toBeAIMessage, + toBeHumanMessage: () => toBeHumanMessage, + toBeSystemMessage: () => toBeSystemMessage, + toBeToolMessage: () => toBeToolMessage, + toContainToolCall: () => toContainToolCall, + toHaveBeenInterrupted: () => toHaveBeenInterrupted, + toHaveStructuredResponse: () => toHaveStructuredResponse, + toHaveToolCallCount: () => toHaveToolCallCount, + toHaveToolCalls: () => toHaveToolCalls, + toHaveToolMessages: () => toHaveToolMessages +}); +//#endregion +//#region node_modules/@langchain/core/dist/tracers/run_collector.js +var run_collector_exports = /* @__PURE__ */ __exportAll({ RunCollectorCallbackHandler: () => RunCollectorCallbackHandler }); +/** +* A callback handler that collects traced runs and makes it easy to fetch the traced run object from calls through any langchain object. +* For instance, it makes it easy to fetch the run ID and then do things with that, such as log feedback. +*/ +var RunCollectorCallbackHandler = class extends BaseTracer { + /** The name of the callback handler. */ + name = "run_collector"; + /** The ID of the example. */ + exampleId; + /** An array of traced runs. */ + tracedRuns; + /** + * Creates a new instance of the RunCollectorCallbackHandler class. + * @param exampleId The ID of the example. + */ + constructor({ exampleId } = {}) { + super({ _awaitHandler: true }); + this.exampleId = exampleId; + this.tracedRuns = []; + } + /** + * Persists the given run object. + * @param run The run object to persist. + */ + async persistRun(run) { + const run_ = { ...run }; + run_.reference_example_id = this.exampleId; + this.tracedRuns.push(run_); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/types/stream.js +var stream_exports = /* @__PURE__ */ __exportAll({}); +//#endregion +//#region node_modules/@langchain/core/dist/utils/chunk_array.js +var chunk_array_exports = /* @__PURE__ */ __exportAll({ chunkArray: () => chunkArray }); +var chunkArray = (arr, chunkSize) => arr.reduce((chunks, elem, index) => { + const chunkIndex = Math.floor(index / chunkSize); + chunks[chunkIndex] = (chunks[chunkIndex] || []).concat([elem]); + return chunks; +}, []); +//#endregion +//#region node_modules/@langchain/core/dist/utils/context.js +var context_exports = /* @__PURE__ */ __exportAll({ context: () => context }); +/** +* A tagged template function for creating formatted strings. +* +* This utility provides a clean, template literal-based API for string formatting +* that can be used for prompts, descriptions, and other text formatting needs. +* +* It automatically handles whitespace normalization and indentation, making it +* ideal for multi-line strings in code. +* +* When using this utility, it will: +* - Strip common leading indentation from all lines +* - Trim leading/trailing whitespace +* - Align multi-line interpolated values to match indentation +* - Support escape sequences: `\\n` (newline), `\\`` (backtick), `\\$` (dollar), `\\{` (brace) +* +* @example +* ```typescript +* import { context } from "@langchain/core/utils/context"; +* +* const role = "agent"; +* const prompt = context` +* You are an ${role}. +* Your task is to help users. +* `; +* // Returns: "You are an agent.\nYour task is to help users." +* ``` +* +* @example +* ```typescript +* // Multi-line interpolated values are aligned +* const items = "- Item 1\n- Item 2\n- Item 3"; +* const message = context` +* Shopping list: +* ${items} +* End of list. +* `; +* // The items will be indented to match " " (4 spaces) +* ``` +*/ +function context(strings, ...values) { + const raw = strings.raw; + let result = ""; + for (let i = 0; i < raw.length; i++) { + const next = raw[i].replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{"); + result += next; + if (i < values.length) { + const value = alignValue(values[i], result); + result += typeof value === "string" ? value : JSON.stringify(value); + } + } + result = stripIndent(result); + result = result.trim(); + result = result.replace(/\\n/g, "\n"); + return result; +} +/** +* Adjusts the indentation of a multi-line interpolated value to match the current line. +* +* @param value - The interpolated value +* @param precedingText - The text that comes before this value +* @returns The value with adjusted indentation +*/ +function alignValue(value, precedingText) { + if (typeof value !== "string" || !value.includes("\n")) return value; + const indentMatch = precedingText.slice(precedingText.lastIndexOf("\n") + 1).match(/^(\s+)/); + if (indentMatch) { + const indent = indentMatch[1]; + return value.replace(/\n/g, `\n${indent}`); + } + return value; +} +/** +* Strips common leading indentation from all lines. +* +* @param text - The text to process +* @returns The text with common indentation removed +*/ +function stripIndent(text) { + const lines = text.split("\n"); + let minIndent = null; + for (const line of lines) { + const match = line.match(/^(\s+)\S+/); + if (match) { + const indent = match[1].length; + if (minIndent === null) minIndent = indent; + else minIndent = Math.min(minIndent, indent); + } + } + if (minIndent === null) return text; + return lines.map((line) => line[0] === " " || line[0] === " " ? line.slice(minIndent) : line).join("\n"); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/event_source_parse.js +var event_source_parse_exports = /* @__PURE__ */ __exportAll({ + EventStreamContentType: () => EventStreamContentType, + convertEventStreamToIterableReadableDataStream: () => convertEventStreamToIterableReadableDataStream, + getBytes: () => getBytes, + getLines: () => getLines, + getMessages: () => getMessages +}); +var EventStreamContentType = "text/event-stream"; +/** +* Converts a ReadableStream into a callback pattern. +* @param stream The input ReadableStream. +* @param onChunk A function that will be called on each new byte chunk in the stream. +* @returns {Promise} A promise that will be resolved when the stream closes. +*/ +async function getBytes(stream, onChunk) { + if (stream instanceof ReadableStream) { + const reader = stream.getReader(); + while (true) { + const result = await reader.read(); + if (result.done) { + onChunk(/* @__PURE__ */ new Uint8Array(), true); + break; + } + onChunk(result.value); + } + } else try { + for await (const chunk of stream) onChunk(new Uint8Array(chunk)); + onChunk(/* @__PURE__ */ new Uint8Array(), true); + } catch (e) { + throw new Error([ + "Parsing event source stream failed.", + "Ensure your implementation of fetch returns a web or Node readable stream.", + `Error: ${e.message}` + ].join("\n")); + } +} +/** +* Parses arbitary byte chunks into EventSource line buffers. +* Each line should be of the format "field: value" and ends with \r, \n, or \r\n. +* @param onLine A function that will be called on each new EventSource line. +* @returns A function that should be called for each incoming byte chunk. +*/ +function getLines(onLine) { + let buffer; + let position; + let fieldLength; + let discardTrailingNewline = false; + return function onChunk(arr, flush) { + if (flush) { + onLine(arr, 0, true); + return; + } + if (buffer === void 0) { + buffer = arr; + position = 0; + fieldLength = -1; + } else buffer = concat(buffer, arr); + const bufLength = buffer.length; + let lineStart = 0; + while (position < bufLength) { + if (discardTrailingNewline) { + if (buffer[position] === 10) lineStart = ++position; + discardTrailingNewline = false; + } + let lineEnd = -1; + for (; position < bufLength && lineEnd === -1; ++position) switch (buffer[position]) { + case 58: + if (fieldLength === -1) fieldLength = position - lineStart; + break; + case 13: discardTrailingNewline = true; + case 10: + lineEnd = position; + break; + } + if (lineEnd === -1) break; + onLine(buffer.subarray(lineStart, lineEnd), fieldLength); + lineStart = position; + fieldLength = -1; + } + if (lineStart === bufLength) buffer = void 0; + else if (lineStart !== 0) { + buffer = buffer.subarray(lineStart); + position -= lineStart; + } + }; +} +/** +* Parses line buffers into EventSourceMessages. +* @param onId A function that will be called on each `id` field. +* @param onRetry A function that will be called on each `retry` field. +* @param onMessage A function that will be called on each message. +* @returns A function that should be called for each incoming line buffer. +*/ +function getMessages(onMessage, onId, onRetry) { + let message = newMessage(); + const decoder = new TextDecoder(); + return function onLine(line, fieldLength, flush) { + if (flush) { + if (!isEmpty(message)) { + onMessage?.(message); + message = newMessage(); + } + return; + } + if (line.length === 0) { + onMessage?.(message); + message = newMessage(); + } else if (fieldLength > 0) { + const field = decoder.decode(line.subarray(0, fieldLength)); + const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1); + const value = decoder.decode(line.subarray(valueOffset)); + switch (field) { + case "data": + message.data = message.data ? message.data + "\n" + value : value; + break; + case "event": + message.event = value; + break; + case "id": + onId?.(message.id = value); + break; + case "retry": { + const retry = parseInt(value, 10); + if (!Number.isNaN(retry)) onRetry?.(message.retry = retry); + break; + } + } + } + }; +} +function concat(a, b) { + const res = new Uint8Array(a.length + b.length); + res.set(a); + res.set(b, a.length); + return res; +} +function newMessage() { + return { + data: "", + event: "", + id: "", + retry: void 0 + }; +} +function convertEventStreamToIterableReadableDataStream(stream, onMetadataEvent) { + const dataStream = new ReadableStream({ async start(controller) { + const enqueueLine = getMessages((msg) => { + if (msg.event === "error") throw new Error(msg.data ?? "Unspecified event streaming error."); + else if (msg.event === "metadata") onMetadataEvent?.(msg); + else if (msg.data) controller.enqueue(msg.data); + }); + const onLine = (line, fieldLength, flush) => { + enqueueLine(line, fieldLength, flush); + if (flush) controller.close(); + }; + await getBytes(stream, getLines(onLine)); + } }); + return IterableReadableStream.fromReadableStream(dataStream); +} +function isEmpty(message) { + return message.data === "" && message.event === "" && message.id === "" && message.retry === void 0; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/format.js +var format_exports = /* @__PURE__ */ __exportAll({}); +//#endregion +//#region node_modules/@langchain/core/dist/utils/ml-distance/similarities.js +/** +* Returns the average of cosine distances between vectors a and b +* @param a - first vector +* @param b - second vector +* +*/ +function cosine(a, b) { + let p = 0; + let p2 = 0; + let q2 = 0; + for (let i = 0; i < a.length; i++) { + p += a[i] * b[i]; + p2 += a[i] * a[i]; + q2 += b[i] * b[i]; + } + return p / (Math.sqrt(p2) * Math.sqrt(q2)); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/ml-distance/distances.js +/** +*Returns the Inner Product similarity between vectors a and b +* @link [Inner Product Similarity algorithm](https://www.naun.org/main/NAUN/ijmmas/mmmas-49.pdf) +* @param a - first vector +* @param b - second vector +* +*/ +function innerProduct$1(a, b) { + let ans = 0; + for (let i = 0; i < a.length; i++) ans += a[i] * b[i]; + return ans; +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/ml-distance-euclidean/euclidean.js +function squaredEuclidean(p, q) { + let d = 0; + for (let i = 0; i < p.length; i++) d += (p[i] - q[i]) * (p[i] - q[i]); + return d; +} +function euclidean(p, q) { + return Math.sqrt(squaredEuclidean(p, q)); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/math.js +var math_exports = /* @__PURE__ */ __exportAll({ + cosineSimilarity: () => cosineSimilarity, + euclideanDistance: () => euclideanDistance, + innerProduct: () => innerProduct, + matrixFunc: () => matrixFunc, + maximalMarginalRelevance: () => maximalMarginalRelevance, + normalize: () => normalize +}); +/** +* Apply a row-wise function between two matrices with the same number of columns. +* +* @param {number[][]} X - The first matrix. +* @param {number[][]} Y - The second matrix. +* @param {VectorFunction} func - The function to apply. +* +* @throws {Error} If the number of columns in X and Y are not the same. +* +* @returns {number[][] | [[]]} A matrix where each row represents the result of applying the function between the corresponding rows of X and Y. +*/ +function matrixFunc(X, Y, func) { + if (X.length === 0 || X[0].length === 0 || Y.length === 0 || Y[0].length === 0) return [[]]; + if (X[0].length !== Y[0].length) throw new Error(`Number of columns in X and Y must be the same. X has shape ${[X.length, X[0].length]} and Y has shape ${[Y.length, Y[0].length]}.`); + return X.map((xVector) => Y.map((yVector) => func(xVector, yVector)).map((similarity) => Number.isNaN(similarity) ? 0 : similarity)); +} +function normalize(M, similarity = false) { + const max = matrixMaxVal(M); + return M.map((row) => row.map((val) => similarity ? 1 - val / max : val / max)); +} +/** +* This function calculates the row-wise cosine similarity between two matrices with the same number of columns. +* +* @param {number[][]} X - The first matrix. +* @param {number[][]} Y - The second matrix. +* +* @throws {Error} If the number of columns in X and Y are not the same. +* +* @returns {number[][] | [[]]} A matrix where each row represents the cosine similarity values between the corresponding rows of X and Y. +*/ +function cosineSimilarity(X, Y) { + return matrixFunc(X, Y, cosine); +} +function innerProduct(X, Y) { + return matrixFunc(X, Y, innerProduct$1); +} +function euclideanDistance(X, Y) { + return matrixFunc(X, Y, euclidean); +} +/** +* This function implements the Maximal Marginal Relevance algorithm +* to select a set of embeddings that maximizes the diversity and relevance to a query embedding. +* +* @param {number[]|number[][]} queryEmbedding - The query embedding. +* @param {number[][]} embeddingList - The list of embeddings to select from. +* @param {number} [lambda=0.5] - The trade-off parameter between relevance and diversity. +* @param {number} [k=4] - The maximum number of embeddings to select. +* +* @returns {number[]} The indexes of the selected embeddings in the embeddingList. +*/ +function maximalMarginalRelevance(queryEmbedding, embeddingList, lambda = .5, k = 4) { + if (Math.min(k, embeddingList.length) <= 0) return []; + const similarityToQuery = cosineSimilarity(Array.isArray(queryEmbedding[0]) ? queryEmbedding : [queryEmbedding], embeddingList)[0]; + const mostSimilarEmbeddingIndex = argMax(similarityToQuery).maxIndex; + const selectedEmbeddings = [embeddingList[mostSimilarEmbeddingIndex]]; + const selectedEmbeddingsIndexes = [mostSimilarEmbeddingIndex]; + while (selectedEmbeddingsIndexes.length < Math.min(k, embeddingList.length)) { + let bestScore = -Infinity; + let bestIndex = -1; + const similarityToSelected = cosineSimilarity(embeddingList, selectedEmbeddings); + similarityToQuery.forEach((queryScore, queryScoreIndex) => { + if (selectedEmbeddingsIndexes.includes(queryScoreIndex)) return; + const maxSimilarityToSelected = Math.max(...similarityToSelected[queryScoreIndex]); + const score = lambda * queryScore - (1 - lambda) * maxSimilarityToSelected; + if (score > bestScore) { + bestScore = score; + bestIndex = queryScoreIndex; + } + }); + selectedEmbeddings.push(embeddingList[bestIndex]); + selectedEmbeddingsIndexes.push(bestIndex); + } + return selectedEmbeddingsIndexes; +} +/** +* Finds the index of the maximum value in the given array. +* @param {number[]} array - The input array. +* +* @returns {number} The index of the maximum value in the array. If the array is empty, returns -1. +*/ +function argMax(array) { + if (array.length === 0) return { + maxIndex: -1, + maxValue: NaN + }; + let maxValue = array[0]; + let maxIndex = 0; + for (let i = 1; i < array.length; i += 1) if (array[i] > maxValue) { + maxIndex = i; + maxValue = array[i]; + } + return { + maxIndex, + maxValue + }; +} +function matrixMaxVal(arrays) { + return arrays.reduce((acc, array) => Math.max(acc, argMax(array).maxValue), 0); +} +//#endregion +//#region node_modules/@langchain/core/dist/utils/ssrf.js +var ssrf_exports = /* @__PURE__ */ __exportAll({ + isCloudMetadata: () => isCloudMetadata, + isLocalhost: () => isLocalhost, + isPrivateIp: () => isPrivateIp, + isSafeUrl: () => isSafeUrl, + isSameOrigin: () => isSameOrigin, + validateSafeUrl: () => validateSafeUrl +}); +var PRIVATE_IP_RANGES = [ + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + "127.0.0.0/8", + "169.254.0.0/16", + "0.0.0.0/8", + "::1/128", + "fc00::/7", + "fe80::/10", + "ff00::/8" +]; +var CLOUD_METADATA_IPS = [ + "169.254.169.254", + "169.254.170.2", + "100.100.100.200" +]; +var CLOUD_METADATA_HOSTNAMES = [ + "metadata.google.internal", + "metadata", + "instance-data" +]; +var LOCALHOST_NAMES = ["localhost", "localhost.localdomain"]; +/** +* IPv4 regex: four octets 0-255 +*/ +var IPV4_REGEX = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/; +/** +* Check if a string is a valid IPv4 address. +*/ +function isIPv4(ip) { + return IPV4_REGEX.test(ip); +} +/** +* Check if a string is a valid IPv6 address. +* Uses expandIpv6 for validation. +*/ +function isIPv6(ip) { + return expandIpv6(ip) !== null; +} +/** +* Check if a string is a valid IP address (IPv4 or IPv6). +*/ +function isIP(ip) { + return isIPv4(ip) || isIPv6(ip); +} +/** +* Parse an IP address string to an array of integers (for IPv4) or an array of 16-bit values (for IPv6) +* Returns null if the IP is invalid. +*/ +function parseIp(ip) { + if (isIPv4(ip)) return ip.split(".").map((octet) => parseInt(octet, 10)); + else if (isIPv6(ip)) { + const expanded = expandIpv6(ip); + if (!expanded) return null; + const parts = expanded.split(":"); + const result = []; + for (const part of parts) result.push(parseInt(part, 16)); + return result; + } + return null; +} +/** +* Expand compressed IPv6 address to full form. +*/ +function expandIpv6(ip) { + if (!ip || typeof ip !== "string") return null; + if (!ip.includes(":")) return null; + if (!/^[0-9a-fA-F:]+$/.test(ip)) return null; + let normalized = ip; + if (normalized.includes("::")) { + const parts = normalized.split("::"); + if (parts.length > 2) return null; + const [left, right] = parts; + const leftParts = left ? left.split(":") : []; + const rightParts = right ? right.split(":") : []; + const missing = 8 - (leftParts.length + rightParts.length); + if (missing < 0) return null; + const zeros = Array(missing).fill("0"); + normalized = [ + ...leftParts, + ...zeros, + ...rightParts + ].filter((p) => p !== "").join(":"); + } + const parts = normalized.split(":"); + if (parts.length !== 8) return null; + for (const part of parts) { + if (part.length === 0 || part.length > 4) return null; + if (!/^[0-9a-fA-F]+$/.test(part)) return null; + } + return parts.map((p) => p.padStart(4, "0").toLowerCase()).join(":"); +} +/** +* Parse CIDR notation (e.g., "192.168.0.0/24") into network address and prefix length. +*/ +function parseCidr(cidr) { + const [addrStr, prefixStr] = cidr.split("/"); + if (!addrStr || !prefixStr) return null; + const addr = parseIp(addrStr); + if (!addr) return null; + const prefixLen = parseInt(prefixStr, 10); + if (isNaN(prefixLen)) return null; + const isIpv6 = isIPv6(addrStr); + if (isIpv6 && prefixLen > 128) return null; + if (!isIpv6 && prefixLen > 32) return null; + return { + addr, + prefixLen, + isIpv6 + }; +} +/** +* Check if an IP address is in a given CIDR range. +*/ +function isIpInCidr(ip, cidr) { + const ipParsed = parseIp(ip); + if (!ipParsed) return false; + const cidrParsed = parseCidr(cidr); + if (!cidrParsed) return false; + const isIpv6 = isIPv6(ip); + if (isIpv6 !== cidrParsed.isIpv6) return false; + const { addr: cidrAddr, prefixLen } = cidrParsed; + if (isIpv6) for (let i = 0; i < Math.ceil(prefixLen / 16); i++) { + const mask = 65535 << 16 - Math.min(16, prefixLen - i * 16) & 65535; + if ((ipParsed[i] & mask) !== (cidrAddr[i] & mask)) return false; + } + else for (let i = 0; i < Math.ceil(prefixLen / 8); i++) { + const mask = 255 << 8 - Math.min(8, prefixLen - i * 8) & 255; + if ((ipParsed[i] & mask) !== (cidrAddr[i] & mask)) return false; + } + return true; +} +/** +* Check if an IP address is private (RFC 1918, loopback, link-local, etc.) +*/ +function isPrivateIp(ip) { + if (!isIP(ip)) return false; + for (const range of PRIVATE_IP_RANGES) if (isIpInCidr(ip, range)) return true; + return false; +} +/** +* Check if a hostname or IP is a known cloud metadata endpoint. +*/ +function isCloudMetadata(hostname, ip) { + if (CLOUD_METADATA_IPS.includes(ip || "")) return true; + const lowerHostname = hostname.toLowerCase(); + if (CLOUD_METADATA_HOSTNAMES.includes(lowerHostname)) return true; + return false; +} +/** +* Check if a hostname or IP is localhost. +*/ +function isLocalhost(hostname, ip) { + if (ip) { + if (ip === "127.0.0.1" || ip === "::1" || ip === "0.0.0.0") return true; + if (ip.startsWith("127.")) return true; + } + const lowerHostname = hostname.toLowerCase(); + if (LOCALHOST_NAMES.includes(lowerHostname)) return true; + return false; +} +/** +* Validate that a URL is safe to connect to. +* Performs static validation checks against hostnames and direct IP addresses. +* Does not perform DNS resolution. +* +* @param url URL to validate +* @param options.allowPrivate Allow private IPs (default: false) +* @param options.allowHttp Allow http:// scheme (default: false) +* @returns The validated URL +* @throws Error if URL is not safe +*/ +function validateSafeUrl(url, options) { + const allowPrivate = options?.allowPrivate ?? false; + const allowHttp = options?.allowHttp ?? false; + try { + let parsedUrl; + try { + parsedUrl = new URL(url); + } catch { + throw new Error(`Invalid URL: ${url}`); + } + const hostname = parsedUrl.hostname; + if (!hostname) throw new Error("URL missing hostname."); + if (isCloudMetadata(hostname)) throw new Error(`URL points to cloud metadata endpoint: ${hostname}`); + if (isLocalhost(hostname)) { + if (!allowPrivate) throw new Error(`URL points to localhost: ${hostname}`); + return url; + } + const scheme = parsedUrl.protocol; + if (scheme !== "http:" && scheme !== "https:") throw new Error(`Invalid URL scheme: ${scheme}. Only http and https are allowed.`); + if (scheme === "http:" && !allowHttp) throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true."); + if (isIP(hostname)) { + const ip = hostname; + if (isLocalhost(hostname, ip)) { + if (!allowPrivate) throw new Error(`URL points to localhost: ${hostname}`); + return url; + } + if (isCloudMetadata(hostname, ip)) throw new Error(`URL resolves to cloud metadata IP: ${ip} (${hostname})`); + if (isPrivateIp(ip)) { + if (!allowPrivate) throw new Error(`URL resolves to private IP: ${ip} (${hostname}). Set allowPrivate: true to allow.`); + } + return url; + } + return url; + } catch (error) { + if (error && typeof error === "object" && "message" in error) throw error; + throw new Error(`URL validation failed: ${error}`); + } +} +/** +* Check if a URL is safe to connect to (non-throwing version). +* +* @param url URL to check +* @param options.allowPrivate Allow private IPs (default: false) +* @param options.allowHttp Allow http:// scheme (default: false) +* @returns true if URL is safe, false otherwise +*/ +function isSafeUrl(url, options) { + try { + validateSafeUrl(url, options); + return true; + } catch { + return false; + } +} +/** +* Check if two URLs have the same origin (scheme, host, port). +* Uses semantic URL parsing to prevent SSRF bypasses via URL variations. +* +* @param url1 First URL +* @param url2 Second URL +* @returns true if both URLs have the same origin, false otherwise +*/ +function isSameOrigin(url1, url2) { + try { + return new URL(url1).origin === new URL(url2).origin; + } catch { + return false; + } +} +//#endregion +//#region node_modules/@langchain/core/dist/vectorstores.js +var vectorstores_exports = /* @__PURE__ */ __exportAll({ + SaveableVectorStore: () => SaveableVectorStore, + VectorStore: () => VectorStore, + VectorStoreRetriever: () => VectorStoreRetriever +}); +/** +* Class for retrieving documents from a `VectorStore` based on vector similarity +* or maximal marginal relevance (MMR). +* +* `VectorStoreRetriever` extends `BaseRetriever`, implementing methods for +* adding documents to the underlying vector store and performing document +* retrieval with optional configurations. +* +* @class VectorStoreRetriever +* @extends BaseRetriever +* @implements VectorStoreRetrieverInterface +* @template V - Type of vector store implementing `VectorStoreInterface`. +*/ +var VectorStoreRetriever = class extends BaseRetriever { + static lc_name() { + return "VectorStoreRetriever"; + } + get lc_namespace() { + return ["langchain_core", "vectorstores"]; + } + /** + * The instance of `VectorStore` used for storing and retrieving document embeddings. + * This vector store must implement the `VectorStoreInterface` to be compatible + * with the retriever’s operations. + */ + vectorStore; + /** + * Specifies the number of documents to retrieve for each search query. + * Defaults to 4 if not specified, providing a basic result count for similarity or MMR searches. + */ + k = 4; + /** + * Determines the type of search operation to perform on the vector store. + * + * - `"similarity"` (default): Conducts a similarity search based purely on vector similarity + * to the query. + * - `"mmr"`: Executes a maximal marginal relevance (MMR) search, balancing relevance and + * diversity in the retrieved results. + */ + searchType = "similarity"; + /** + * Additional options specific to maximal marginal relevance (MMR) search, applicable + * only if `searchType` is set to `"mmr"`. + * + * Includes: + * - `fetchK`: The initial number of documents fetched before applying the MMR algorithm, + * allowing for a larger selection from which to choose the most diverse results. + * - `lambda`: A parameter between 0 and 1 to adjust the relevance-diversity balance, + * where 0 prioritizes diversity and 1 prioritizes relevance. + */ + searchKwargs; + /** + * Optional filter applied to search results, defined by the `FilterType` of the vector store. + * Allows for refined, targeted results by restricting the returned documents based + * on specified filter criteria. + */ + filter; + /** + * Returns the type of vector store, as defined by the `vectorStore` instance. + * + * @returns {string} The vector store type. + */ + _vectorstoreType() { + return this.vectorStore._vectorstoreType(); + } + /** + * Initializes a new instance of `VectorStoreRetriever` with the specified configuration. + * + * This constructor configures the retriever to interact with a given `VectorStore` + * and supports different retrieval strategies, including similarity search and maximal + * marginal relevance (MMR) search. Various options allow customization of the number + * of documents retrieved per query, filtering based on conditions, and fine-tuning + * MMR-specific parameters. + * + * @param fields - Configuration options for setting up the retriever: + * + * - `vectorStore` (required): The `VectorStore` instance implementing `VectorStoreInterface` + * that will be used to store and retrieve document embeddings. This is the core component + * of the retriever, enabling vector-based similarity and MMR searches. + * + * - `k` (optional): Specifies the number of documents to retrieve per search query. If not + * provided, defaults to 4. This count determines the number of most relevant documents returned + * for each search operation, balancing performance with comprehensiveness. + * + * - `searchType` (optional): Defines the search approach used by the retriever, allowing for + * flexibility between two methods: + * - `"similarity"` (default): A similarity-based search, retrieving documents with high vector + * similarity to the query. This type prioritizes relevance and is often used when diversity + * among results is less critical. + * - `"mmr"`: Maximal Marginal Relevance search, which combines relevance with diversity. MMR + * is useful for scenarios where varied content is essential, as it selects results that + * both match the query and introduce content diversity. + * + * - `filter` (optional): A filter of type `FilterType`, defined by the vector store, that allows + * for refined and targeted search results. This filter applies specified conditions to limit + * which documents are eligible for retrieval, offering control over the scope of results. + * + * - `searchKwargs` (optional, applicable only if `searchType` is `"mmr"`): Additional settings + * for configuring MMR-specific behavior. These parameters allow further tuning of the MMR + * search process: + * - `fetchK`: The initial number of documents fetched from the vector store before the MMR + * algorithm is applied. Fetching a larger set enables the algorithm to select a more + * diverse subset of documents. + * - `lambda`: A parameter controlling the relevance-diversity balance, where 0 emphasizes + * diversity and 1 prioritizes relevance. Intermediate values provide a blend of the two, + * allowing customization based on the importance of content variety relative to query relevance. + */ + constructor(fields) { + super(fields); + this.vectorStore = fields.vectorStore; + this.k = fields.k ?? this.k; + this.searchType = fields.searchType ?? this.searchType; + this.filter = fields.filter; + if (fields.searchType === "mmr") this.searchKwargs = fields.searchKwargs; + } + /** + * Retrieves relevant documents based on the specified query, using either + * similarity or maximal marginal relevance (MMR) search. + * + * If `searchType` is set to `"mmr"`, performs an MMR search to balance + * similarity and diversity among results. If `searchType` is `"similarity"`, + * retrieves results purely based on similarity to the query. + * + * @param query - The query string used to find relevant documents. + * @param runManager - Optional callback manager for tracking retrieval progress. + * @returns A promise that resolves to an array of `DocumentInterface` instances + * representing the most relevant documents to the query. + * @throws {Error} Throws an error if MMR search is requested but not supported + * by the vector store. + * @protected + */ + async _getRelevantDocuments(query, runManager) { + if (this.searchType === "mmr") { + if (typeof this.vectorStore.maxMarginalRelevanceSearch !== "function") throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`); + return this.vectorStore.maxMarginalRelevanceSearch(query, { + k: this.k, + filter: this.filter, + ...this.searchKwargs + }, runManager?.getChild("vectorstore")); + } + return this.vectorStore.similaritySearch(query, this.k, this.filter, runManager?.getChild("vectorstore")); + } + /** + * Adds an array of documents to the vector store, embedding them as part of + * the storage process. + * + * This method delegates document embedding and storage to the `addDocuments` + * method of the underlying vector store. + * + * @param documents - An array of documents to embed and add to the vector store. + * @param options - Optional settings to customize document addition. + * @returns A promise that resolves to an array of document IDs or `void`, + * depending on the vector store's implementation. + */ + async addDocuments(documents, options) { + return this.vectorStore.addDocuments(documents, options); + } +}; +/** +* Abstract class representing a vector storage system for performing +* similarity searches on embedded documents. +* +* `VectorStore` provides methods for adding precomputed vectors or documents, +* removing documents based on criteria, and performing similarity searches +* with optional scoring. Subclasses are responsible for implementing specific +* storage mechanisms and the exact behavior of certain abstract methods. +* +* @abstract +* @extends Serializable +* @implements VectorStoreInterface +*/ +var VectorStore = class extends Serializable { + /** + * Namespace within LangChain to uniquely identify this vector store's + * location, based on the vector store type. + * + * @internal + */ + lc_namespace = [ + "langchain", + "vectorstores", + this._vectorstoreType() + ]; + /** + * Embeddings interface for generating vector embeddings from text queries, + * enabling vector-based similarity searches. + */ + embeddings; + /** + * Initializes a new vector store with embeddings and database configuration. + * + * @param embeddings - Instance of `EmbeddingsInterface` used to embed queries. + * @param dbConfig - Configuration settings for the database or storage system. + */ + constructor(embeddings, dbConfig) { + super(dbConfig); + this.embeddings = embeddings; + } + /** + * Deletes documents from the vector store based on the specified parameters. + * + * @param _params - Flexible key-value pairs defining conditions for document deletion. + * @returns A promise that resolves once the deletion is complete. + */ + async delete(_params) { + throw new Error("Not implemented."); + } + /** + * Searches for documents similar to a text query by embedding the query and + * performing a similarity search on the resulting vector. + * + * @param query - Text query for finding similar documents. + * @param k - Number of similar results to return. Defaults to 4. + * @param filter - Optional filter based on `FilterType`. + * @param _callbacks - Optional callbacks for monitoring search progress + * @returns A promise resolving to an array of `DocumentInterface` instances representing similar documents. + */ + async similaritySearch(query, k = 4, filter = void 0, _callbacks = void 0) { + return (await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter)).map((result) => result[0]); + } + /** + * Searches for documents similar to a text query by embedding the query, + * and returns results with similarity scores. + * + * @param query - Text query for finding similar documents. + * @param k - Number of similar results to return. Defaults to 4. + * @param filter - Optional filter based on `FilterType`. + * @param _callbacks - Optional callbacks for monitoring search progress + * @returns A promise resolving to an array of tuples, each containing a + * document and its similarity score. + */ + async similaritySearchWithScore(query, k = 4, filter = void 0, _callbacks = void 0) { + return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter); + } + /** + * Creates a `VectorStore` instance from an array of text strings and optional + * metadata, using the specified embeddings and database configuration. + * + * Subclasses must implement this method to define how text and metadata + * are embedded and stored in the vector store. Throws an error if not overridden. + * + * @param _texts - Array of strings representing the text documents to be stored. + * @param _metadatas - Metadata for the texts, either as an array (one for each text) + * or a single object (applied to all texts). + * @param _embeddings - Instance of `EmbeddingsInterface` to embed the texts. + * @param _dbConfig - Database configuration settings. + * @returns A promise that resolves to a new `VectorStore` instance. + * @throws {Error} Throws an error if this method is not overridden by a subclass. + */ + static fromTexts(_texts, _metadatas, _embeddings, _dbConfig) { + throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); + } + /** + * Creates a `VectorStore` instance from an array of documents, using the specified + * embeddings and database configuration. + * + * Subclasses must implement this method to define how documents are embedded + * and stored. Throws an error if not overridden. + * + * @param _docs - Array of `DocumentInterface` instances representing the documents to be stored. + * @param _embeddings - Instance of `EmbeddingsInterface` to embed the documents. + * @param _dbConfig - Database configuration settings. + * @returns A promise that resolves to a new `VectorStore` instance. + * @throws {Error} Throws an error if this method is not overridden by a subclass. + */ + static fromDocuments(_docs, _embeddings, _dbConfig) { + throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); + } + /** + * Creates a `VectorStoreRetriever` instance with flexible configuration options. + * + * @param kOrFields + * - If a number is provided, it sets the `k` parameter (number of items to retrieve). + * - If an object is provided, it should contain various configuration options. + * @param filter + * - Optional filter criteria to limit the items retrieved based on the specified filter type. + * @param callbacks + * - Optional callbacks that may be triggered at specific stages of the retrieval process. + * @param tags + * - Tags to categorize or label the `VectorStoreRetriever`. Defaults to an empty array if not provided. + * @param metadata + * - Additional metadata as key-value pairs to add contextual information for the retrieval process. + * @param verbose + * - If `true`, enables detailed logging for the retrieval process. Defaults to `false`. + * + * @returns + * - A configured `VectorStoreRetriever` instance based on the provided parameters. + * + * @example + * Basic usage with a `k` value: + * ```typescript + * const retriever = myVectorStore.asRetriever(5); + * ``` + * + * Usage with a configuration object: + * ```typescript + * const retriever = myVectorStore.asRetriever({ + * k: 10, + * filter: myFilter, + * tags: ['example', 'test'], + * verbose: true, + * searchType: 'mmr', + * searchKwargs: { alpha: 0.5 }, + * }); + * ``` + */ + asRetriever(kOrFields, filter, callbacks, tags, metadata, verbose) { + if (typeof kOrFields === "number") return new VectorStoreRetriever({ + vectorStore: this, + k: kOrFields, + filter, + tags: [...tags ?? [], this._vectorstoreType()], + metadata, + verbose, + callbacks + }); + else { + const params = { + vectorStore: this, + k: kOrFields?.k, + filter: kOrFields?.filter, + tags: [...kOrFields?.tags ?? [], this._vectorstoreType()], + metadata: kOrFields?.metadata, + verbose: kOrFields?.verbose, + callbacks: kOrFields?.callbacks, + searchType: kOrFields?.searchType + }; + if (kOrFields?.searchType === "mmr") return new VectorStoreRetriever({ + ...params, + searchKwargs: kOrFields.searchKwargs + }); + return new VectorStoreRetriever({ ...params }); + } + } +}; +/** +* Abstract class extending `VectorStore` that defines a contract for saving +* and loading vector store instances. +* +* The `SaveableVectorStore` class allows vector store implementations to +* persist their data and retrieve it when needed.The format for saving and +* loading data is left to the implementing subclass. +* +* Subclasses must implement the `save` method to handle their custom +* serialization logic, while the `load` method enables reconstruction of a +* vector store from saved data, requiring compatible embeddings through the +* `EmbeddingsInterface`. +* +* @abstract +* @extends VectorStore +*/ +var SaveableVectorStore = class extends VectorStore { + /** + * Loads a vector store instance from the specified directory, using the + * provided embeddings to ensure compatibility. + * + * This static method reconstructs a `SaveableVectorStore` from previously + * saved data. Implementations should interpret the saved data format to + * recreate the vector store instance. + * + * @param _directory - The directory path from which the vector store + * data will be loaded. + * @param _embeddings - An instance of `EmbeddingsInterface` to align + * the embeddings with the loaded vector data. + * @returns A promise that resolves to a `SaveableVectorStore` instance + * constructed from the saved data. + */ + static load(_directory, _embeddings) { + throw new Error("Not implemented"); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/chat_models.js +var FakeChatModel = class extends BaseChatModel { + _combineLLMOutput() { + return []; + } + _llmType() { + return "fake"; + } + async _generate(messages, options, runManager) { + if (options?.stop?.length) return { generations: [{ + message: new AIMessage(options.stop[0]), + text: options.stop[0] + }] }; + const text = messages.map((m) => { + if (typeof m.content === "string") return m.content; + return JSON.stringify(m.content, null, 2); + }).join("\n"); + await runManager?.handleLLMNewToken(text); + return { + generations: [{ + message: new AIMessage(text), + text + }], + llmOutput: {} + }; + } +}; +var FakeStreamingChatModel = class FakeStreamingChatModel extends BaseChatModel { + sleep = 50; + responses = []; + chunks = []; + toolStyle = "openai"; + thrownErrorString; + tools = []; + constructor({ sleep = 50, responses = [], chunks = [], toolStyle = "openai", thrownErrorString, ...rest }) { + super(rest); + this.sleep = sleep; + this.responses = responses; + this.chunks = chunks; + this.toolStyle = toolStyle; + this.thrownErrorString = thrownErrorString; + } + _llmType() { + return "fake"; + } + bindTools(tools) { + const merged = [...this.tools, ...tools]; + const toolDicts = merged.map((t) => { + switch (this.toolStyle) { + case "openai": return { + type: "function", + function: { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + } + }; + case "anthropic": return { + name: t.name, + description: t.description, + input_schema: toJsonSchema(t.schema) + }; + case "bedrock": return { toolSpec: { + name: t.name, + description: t.description, + inputSchema: toJsonSchema(t.schema) + } }; + case "google": return { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + }; + default: throw new Error(`Unsupported tool style: ${this.toolStyle}`); + } + }); + const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; + const next = new FakeStreamingChatModel({ + sleep: this.sleep, + responses: this.responses, + chunks: this.chunks, + toolStyle: this.toolStyle, + thrownErrorString: this.thrownErrorString + }); + next.tools = merged; + return next.withConfig({ tools: wrapped }); + } + async _generate(messages, _options, _runManager) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + return { generations: [{ + text: "", + message: new AIMessage({ + content: this.responses?.[0]?.content ?? messages[0].content ?? "", + tool_calls: this.chunks?.[0]?.tool_calls + }) + }] }; + } + async *_streamResponseChunks(_messages, options, runManager) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + if (this.chunks?.length) { + for (const msgChunk of this.chunks) { + const cg = new ChatGenerationChunk({ + message: new AIMessageChunk({ + content: msgChunk.content, + tool_calls: msgChunk.tool_calls, + additional_kwargs: msgChunk.additional_kwargs ?? {} + }), + text: msgChunk.content?.toString() ?? "" + }); + if (options.signal?.aborted) break; + yield cg; + await runManager?.handleLLMNewToken(msgChunk.content, void 0, void 0, void 0, void 0, { chunk: cg }); + } + return; + } + const fallback = this.responses?.[0] ?? new AIMessage(typeof _messages[0].content === "string" ? _messages[0].content : ""); + const text = typeof fallback.content === "string" ? fallback.content : ""; + for (const ch of text) { + await new Promise((r) => setTimeout(r, this.sleep)); + const cg = new ChatGenerationChunk({ + message: new AIMessageChunk({ content: ch }), + text: ch + }); + if (options.signal?.aborted) break; + yield cg; + await runManager?.handleLLMNewToken(ch, void 0, void 0, void 0, void 0, { chunk: cg }); + } + } +}; +/** +* A fake Chat Model that returns a predefined list of responses. It can be used +* for testing purposes. +* @example +* ```typescript +* const chat = new FakeListChatModel({ +* responses: ["I'll callback later.", "You 'console' them!"] +* }); +* +* const firstMessage = new HumanMessage("You want to hear a JavaScript joke?"); +* const secondMessage = new HumanMessage("How do you cheer up a JavaScript developer?"); +* +* // Call the chat model with a message and log the response +* const firstResponse = await chat.call([firstMessage]); +* console.log({ firstResponse }); +* +* const secondResponse = await chat.call([secondMessage]); +* console.log({ secondResponse }); +* ``` +*/ +var FakeListChatModel = class FakeListChatModel extends BaseChatModel { + static lc_name() { + return "FakeListChatModel"; + } + lc_serializable = true; + responses; + i = 0; + sleep; + emitCustomEvent = false; + generationInfo; + tools = []; + toolStyle = "openai"; + constructor(params) { + super(params); + const { responses, sleep, emitCustomEvent, generationInfo } = params; + this.responses = responses; + this.sleep = sleep; + this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent; + this.generationInfo = generationInfo; + } + _combineLLMOutput() { + return []; + } + _llmType() { + return "fake-list"; + } + async _generate(_messages, options, runManager) { + await this._sleepIfRequested(); + if (options?.thrownErrorString) throw new Error(options.thrownErrorString); + if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true }); + if (options?.stop?.length) return { generations: [this._formatGeneration(options.stop[0])] }; + else { + const response = this._currentResponse(); + this._incrementResponse(); + return { + generations: [this._formatGeneration(response)], + llmOutput: {} + }; + } + } + _formatGeneration(text) { + return { + message: new AIMessage(text), + text + }; + } + async *_streamResponseChunks(_messages, options, runManager) { + const response = this._currentResponse(); + this._incrementResponse(); + if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true }); + const responseChars = [...response]; + for (let i = 0; i < responseChars.length; i++) { + const text = responseChars[i]; + const isLastChunk = i === responseChars.length - 1; + await this._sleepIfRequested(); + if (options?.thrownErrorString) throw new Error(options.thrownErrorString); + const chunk = this._createResponseChunk(text, isLastChunk ? this.generationInfo : void 0); + if (options.signal?.aborted) break; + yield chunk; + runManager?.handleLLMNewToken(text); + } + } + async _sleepIfRequested() { + if (this.sleep !== void 0) await this._sleep(); + } + async _sleep() { + return new Promise((resolve) => { + setTimeout(() => resolve(), this.sleep); + }); + } + _createResponseChunk(text, generationInfo) { + return new ChatGenerationChunk({ + message: new AIMessageChunk({ content: text }), + text, + generationInfo + }); + } + _currentResponse() { + return this.responses[this.i]; + } + _incrementResponse() { + if (this.i < this.responses.length - 1) this.i += 1; + else this.i = 0; + } + bindTools(tools) { + const merged = [...this.tools, ...tools]; + const toolDicts = merged.map((t) => { + switch (this.toolStyle) { + case "openai": return { + type: "function", + function: { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + } + }; + case "anthropic": return { + name: t.name, + description: t.description, + input_schema: toJsonSchema(t.schema) + }; + case "bedrock": return { toolSpec: { + name: t.name, + description: t.description, + inputSchema: toJsonSchema(t.schema) + } }; + case "google": return { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + }; + default: throw new Error(`Unsupported tool style: ${this.toolStyle}`); + } + }); + const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; + const next = new FakeListChatModel({ + responses: this.responses, + sleep: this.sleep, + emitCustomEvent: this.emitCustomEvent, + generationInfo: this.generationInfo + }); + next.tools = merged; + next.toolStyle = this.toolStyle; + next.i = this.i; + return next.withConfig({ tools: wrapped }); + } + withStructuredOutput(_params, _config) { + return RunnableLambda.from(async (input) => { + const message = await this.invoke(input); + if (message.tool_calls?.[0]?.args) return message.tool_calls[0].args; + if (typeof message.content === "string") return JSON.parse(message.content); + throw new Error("No structured output found"); + }); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/embeddings.js +/** +* A class that provides synthetic embeddings by overriding the +* embedDocuments and embedQuery methods to generate embeddings based on +* the input documents. The embeddings are generated by converting each +* document into chunks, calculating a numerical value for each chunk, and +* returning an array of these values as the embedding. +*/ +var SyntheticEmbeddings = class extends Embeddings { + vectorSize; + constructor(params) { + super(params ?? {}); + this.vectorSize = params?.vectorSize ?? 4; + } + /** + * Generates synthetic embeddings for a list of documents. + * @param documents List of documents to generate embeddings for. + * @returns A promise that resolves with a list of synthetic embeddings for each document. + */ + async embedDocuments(documents) { + return Promise.all(documents.map((doc) => this.embedQuery(doc))); + } + /** + * Generates a synthetic embedding for a document. The document is + * converted into chunks, a numerical value is calculated for each chunk, + * and an array of these values is returned as the embedding. + * @param document The document to generate an embedding for. + * @returns A promise that resolves with a synthetic embedding for the document. + */ + async embedQuery(document) { + let doc = document; + doc = doc.toLowerCase().replaceAll(/[^a-z ]/g, ""); + const padMod = doc.length % this.vectorSize; + const padGapSize = padMod === 0 ? 0 : this.vectorSize - padMod; + const padSize = doc.length + padGapSize; + doc = doc.padEnd(padSize, " "); + const chunkSize = doc.length / this.vectorSize; + const docChunk = []; + for (let co = 0; co < doc.length; co += chunkSize) docChunk.push(doc.slice(co, co + chunkSize)); + return docChunk.map((s) => { + let sum = 0; + for (let co = 0; co < s.length; co += 1) sum += s === " " ? 0 : s.charCodeAt(co); + return sum % 26 / 26; + }); + } +}; +/** +* A class that provides fake embeddings by overriding the embedDocuments +* and embedQuery methods to return fixed values. +*/ +var FakeEmbeddings = class extends Embeddings { + constructor(params) { + super(params ?? {}); + } + /** + * Generates fixed embeddings for a list of documents. + * @param documents List of documents to generate embeddings for. + * @returns A promise that resolves with a list of fixed embeddings for each document. + */ + embedDocuments(documents) { + return Promise.resolve(documents.map(() => [ + .1, + .2, + .3, + .4 + ])); + } + /** + * Generates a fixed embedding for a query. + * @param _ The query to generate an embedding for. + * @returns A promise that resolves with a fixed embedding for the query. + */ + embedQuery(_) { + return Promise.resolve([ + .1, + .2, + .3, + .4 + ]); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/llms.js +var FakeLLM = class extends LLM { + response; + thrownErrorString; + constructor(fields) { + super(fields); + this.response = fields.response; + this.thrownErrorString = fields.thrownErrorString; + } + _llmType() { + return "fake"; + } + async _call(prompt, _options, runManager) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + const response = this.response ?? prompt; + await runManager?.handleLLMNewToken(response); + return response; + } +}; +var FakeStreamingLLM = class extends LLM { + sleep = 50; + responses; + thrownErrorString; + constructor(fields) { + super(fields); + this.sleep = fields.sleep ?? this.sleep; + this.responses = fields.responses; + this.thrownErrorString = fields.thrownErrorString; + } + _llmType() { + return "fake"; + } + async _call(prompt) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + const response = this.responses?.[0]; + this.responses = this.responses?.slice(1); + return response ?? prompt; + } + async *_streamResponseChunks(input, _options, runManager) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + const response = this.responses?.[0]; + this.responses = this.responses?.slice(1); + for (const c of response ?? input) { + await new Promise((resolve) => setTimeout(resolve, this.sleep)); + yield { + text: c, + generationInfo: {} + }; + await runManager?.handleLLMNewToken(c); + } + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/message_history.js +var FakeChatMessageHistory = class extends BaseChatMessageHistory { + lc_namespace = [ + "langchain_core", + "message", + "fake" + ]; + messages = []; + constructor() { + super(); + } + async getMessages() { + return this.messages; + } + async addMessage(message) { + this.messages.push(message); + } + async addUserMessage(message) { + this.messages.push(new HumanMessage(message)); + } + async addAIMessage(message) { + this.messages.push(new AIMessage(message)); + } + async clear() { + this.messages = []; + } +}; +var FakeListChatMessageHistory = class extends BaseListChatMessageHistory { + lc_namespace = [ + "langchain_core", + "message", + "fake" + ]; + messages = []; + constructor() { + super(); + } + async addMessage(message) { + this.messages.push(message); + } + async getMessages() { + return this.messages; + } +}; +var FakeTracer = class extends BaseTracer { + name = "fake_tracer"; + runs = []; + constructor() { + super(); + } + persistRun(run) { + this.runs.push(run); + return Promise.resolve(); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/output_parsers.js +/** +* Parser for comma-separated values. It splits the input text by commas +* and trims the resulting values. +*/ +var FakeSplitIntoListParser = class extends BaseOutputParser { + lc_namespace = ["tests", "fake"]; + getFormatInstructions() { + return ""; + } + async parse(text) { + return text.split(",").map((value) => value.trim()); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/retrievers.js +var FakeRetriever = class extends BaseRetriever { + lc_namespace = ["test", "fake"]; + output = [new Document({ pageContent: "foo" }), new Document({ pageContent: "bar" })]; + constructor(fields) { + super(); + this.output = fields?.output ?? this.output; + } + async _getRelevantDocuments(_query) { + return this.output; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/runnables.js +var FakeRunnable = class extends Runnable { + lc_namespace = ["tests", "fake"]; + returnOptions; + constructor(fields) { + super(fields); + this.returnOptions = fields.returnOptions; + } + async invoke(input, options) { + if (this.returnOptions) return options ?? {}; + return { input }; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/tools.js +var FakeTool = class extends StructuredTool { + name; + description; + schema; + constructor(fields) { + super(fields); + this.name = fields.name; + this.description = fields.description; + this.schema = fields.schema; + } + async _call(arg, _runManager) { + return JSON.stringify(arg); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/tracers.js +var SingleRunExtractor = class extends BaseTracer { + runPromiseResolver; + runPromise; + /** The name of the callback handler. */ + name = "single_run_extractor"; + constructor() { + super(); + this.runPromise = new Promise((extract) => { + this.runPromiseResolver = extract; + }); + } + async persistRun(run) { + this.runPromiseResolver(run); + } + async extract() { + return this.runPromise; + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/vectorstores.js +/** +* Class that extends `VectorStore` to store vectors in memory. Provides +* methods for adding documents, performing similarity searches, and +* creating instances from texts, documents, or an existing index. +*/ +var FakeVectorStore = class FakeVectorStore extends VectorStore { + memoryVectors = []; + similarity; + _vectorstoreType() { + return "memory"; + } + constructor(embeddings, { similarity, ...rest } = {}) { + super(embeddings, rest); + this.similarity = similarity ?? cosine; + } + /** + * Method to add documents to the memory vector store. It extracts the + * text from each document, generates embeddings for them, and adds the + * resulting vectors to the store. + * @param documents Array of `Document` instances to be added to the store. + * @returns Promise that resolves when all documents have been added. + */ + async addDocuments(documents) { + const texts = documents.map(({ pageContent }) => pageContent); + return this.addVectors(await this.embeddings.embedDocuments(texts), documents); + } + /** + * Method to add vectors to the memory vector store. It creates + * `MemoryVector` instances for each vector and document pair and adds + * them to the store. + * @param vectors Array of vectors to be added to the store. + * @param documents Array of `Document` instances corresponding to the vectors. + * @returns Promise that resolves when all vectors have been added. + */ + async addVectors(vectors, documents) { + const memoryVectors = vectors.map((embedding, idx) => ({ + content: documents[idx].pageContent, + embedding, + metadata: documents[idx].metadata + })); + this.memoryVectors = this.memoryVectors.concat(memoryVectors); + } + /** + * Method to perform a similarity search in the memory vector store. It + * calculates the similarity between the query vector and each vector in + * the store, sorts the results by similarity, and returns the top `k` + * results along with their scores. + * @param query Query vector to compare against the vectors in the store. + * @param k Number of top results to return. + * @param filter Optional filter function to apply to the vectors before performing the search. + * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score. + */ + async similaritySearchVectorWithScore(query, k, filter) { + const filterFunction = (memoryVector) => { + if (!filter) return true; + return filter(new Document({ + metadata: memoryVector.metadata, + pageContent: memoryVector.content + })); + }; + const filteredMemoryVectors = this.memoryVectors.filter(filterFunction); + return filteredMemoryVectors.map((vector, index) => ({ + similarity: this.similarity(query, vector.embedding), + index + })).sort((a, b) => a.similarity > b.similarity ? -1 : 0).slice(0, k).map((search) => [new Document({ + metadata: filteredMemoryVectors[search.index].metadata, + pageContent: filteredMemoryVectors[search.index].content + }), search.similarity]); + } + /** + * Static method to create a `FakeVectorStore` instance from an array of + * texts. It creates a `Document` for each text and metadata pair, and + * adds them to the store. + * @param texts Array of texts to be added to the store. + * @param metadatas Array or single object of metadata corresponding to the texts. + * @param embeddings `Embeddings` instance used to generate embeddings for the texts. + * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. + * @returns Promise that resolves with a new `FakeVectorStore` instance. + */ + static async fromTexts(texts, metadatas, embeddings, dbConfig) { + const docs = []; + for (let i = 0; i < texts.length; i += 1) { + const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas; + const newDoc = new Document({ + pageContent: texts[i], + metadata + }); + docs.push(newDoc); + } + return FakeVectorStore.fromDocuments(docs, embeddings, dbConfig); + } + /** + * Static method to create a `FakeVectorStore` instance from an array of + * `Document` instances. It adds the documents to the store. + * @param docs Array of `Document` instances to be added to the store. + * @param embeddings `Embeddings` instance used to generate embeddings for the documents. + * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. + * @returns Promise that resolves with a new `FakeVectorStore` instance. + */ + static async fromDocuments(docs, embeddings, dbConfig) { + const instance = new this(embeddings, dbConfig); + await instance.addDocuments(docs); + return instance; + } + /** + * Static method to create a `FakeVectorStore` instance from an existing + * index. It creates a new `FakeVectorStore` instance without adding any + * documents or vectors. + * @param embeddings `Embeddings` instance used to generate embeddings for the documents. + * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. + * @returns Promise that resolves with a new `FakeVectorStore` instance. + */ + static async fromExistingIndex(embeddings, dbConfig) { + return new this(embeddings, dbConfig); + } +}; +//#endregion +//#region node_modules/@langchain/core/dist/utils/testing/index.js +var testing_exports = /* @__PURE__ */ __exportAll({ + FakeChatMessageHistory: () => FakeChatMessageHistory, + FakeChatModel: () => FakeChatModel, + FakeEmbeddings: () => FakeEmbeddings, + FakeLLM: () => FakeLLM, + FakeListChatMessageHistory: () => FakeListChatMessageHistory, + FakeListChatModel: () => FakeListChatModel, + FakeRetriever: () => FakeRetriever, + FakeRunnable: () => FakeRunnable, + FakeSplitIntoListParser: () => FakeSplitIntoListParser, + FakeStreamingChatModel: () => FakeStreamingChatModel, + FakeStreamingLLM: () => FakeStreamingLLM, + FakeTool: () => FakeTool, + FakeTracer: () => FakeTracer, + FakeVectorStore: () => FakeVectorStore, + SingleRunExtractor: () => SingleRunExtractor, + SyntheticEmbeddings: () => SyntheticEmbeddings, + asAsyncIterable: () => asAsyncIterable, + openAIReasoningTextChunks: () => openAIReasoningTextChunks, + openAITextOnlyChunks: () => openAITextOnlyChunks, + openAITextOnlyChunksWithUsage: () => openAITextOnlyChunksWithUsage, + openAIToolCallChunks: () => openAIToolCallChunks, + sseResponseFromOpenAIChunks: () => sseResponseFromOpenAIChunks, + streamMatchers: () => streamMatchers +}); +//#endregion +//#region node_modules/@langchain/core/dist/load/import_map.js +var import_map_exports = /* @__PURE__ */ __exportAll({ + agents: () => agents_exports, + caches: () => caches_exports, + callbacks__base: () => base_exports$1, + callbacks__manager: () => manager_exports, + callbacks__promises: () => promises_exports, + chat_history: () => chat_history_exports, + document_loaders__base: () => base_exports, + document_loaders__langsmith: () => langsmith_exports, + documents: () => documents_exports, + embeddings: () => embeddings_exports, + errors: () => errors_exports, + example_selectors: () => example_selectors_exports, + index: () => src_exports, + indexing: () => indexing_exports, + language_models__base: () => base_exports$2, + language_models__chat_models: () => chat_models_exports, + language_models__compat: () => compat_exports, + language_models__event: () => event_exports, + language_models__llms: () => llms_exports, + language_models__openai_completions_stream: () => openai_completions_stream_exports, + language_models__profile: () => profile_exports, + language_models__stream: () => stream_exports$1, + language_models__structured_output: () => structured_output_exports, + load__serializable: () => serializable_exports, + memory: () => memory_exports, + messages: () => messages_exports, + messages__tool: () => tool_exports, + output_parsers: () => output_parsers_exports, + output_parsers__openai_functions: () => openai_functions_exports, + output_parsers__openai_tools: () => openai_tools_exports, + outputs: () => outputs_exports, + prompt_values: () => prompt_values_exports, + prompts: () => prompts_exports, + retrievers: () => retrievers_exports, + retrievers__document_compressors: () => document_compressors_exports, + runnables: () => runnables_exports, + runnables__graph: () => graph_exports, + singletons: () => singletons_exports, + stores: () => stores_exports, + structured_query: () => structured_query_exports, + testing: () => testing_exports$1, + tools: () => tools_exports, + tracers__base: () => base_exports$3, + tracers__console: () => console_exports, + tracers__log_stream: () => log_stream_exports, + tracers__run_collector: () => run_collector_exports, + tracers__tracer_langchain: () => tracer_langchain_exports, + types__stream: () => stream_exports, + utils__async_caller: () => async_caller_exports, + utils__chunk_array: () => chunk_array_exports, + utils__context: () => context_exports, + utils__env: () => env_exports, + utils__event_source_parse: () => event_source_parse_exports, + utils__format: () => format_exports, + utils__function_calling: () => function_calling_exports, + utils__hash: () => hash_exports, + utils__json_patch: () => json_patch_exports, + utils__json_schema: () => json_schema_exports, + utils__math: () => math_exports, + utils__ssrf: () => ssrf_exports, + utils__standard_schema: () => standard_schema_exports, + utils__stream: () => stream_exports$2, + utils__testing: () => testing_exports, + utils__tiktoken: () => tiktoken_exports, + utils__types: () => types_exports, + utils__uuid: () => uuid_exports, + vectorstores: () => vectorstores_exports +}); +//#endregion +//#region node_modules/@langchain/core/dist/load/index.js +/** +* Load LangChain objects from JSON strings or objects. +* +* **WARNING: `load()` deserializes data by instantiating classes and invoking +* constructors. Never call `load()` on untrusted or user-supplied input.** +* Doing so can lead to insecure deserialization — including arbitrary class +* instantiation, secret exfiltration, and server-side request forgery (SSRF). +* Only deserialize data that originates from a trusted source you control. +* +* ## How it works +* +* Each `Serializable` LangChain object has a unique identifier (its "class path"), +* which is a list of strings representing the module path and class name. For example: +* +* - `AIMessage` -> `["langchain_core", "messages", "ai", "AIMessage"]` +* - `ChatPromptTemplate` -> `["langchain_core", "prompts", "chat", "ChatPromptTemplate"]` +* +* When deserializing, the class path is validated against supported namespaces. +* +* ## Threat model +* +* A serialized LangChain payload crosses a trust boundary because the manifest +* may contain serialized objects and configuration that affect runtime behavior. +* For example, a payload can configure a chat model with a custom `base_url`, +* custom headers, a different model name, or other constructor arguments. These +* are supported features, but they also mean the payload contents should be +* treated as executable configuration rather than plain text. +* +* Concretely, deserialization instantiates classes, so any constructor on an +* allowed class will run during `load()`. A crafted payload that is allowed to +* reach an unintended class — or an intended class with attacker-controlled +* kwargs — could cause network calls, file operations, or environment-variable +* access while the object is being built. +* +* ## Security model +* +* The `secretsFromEnv` parameter controls whether secrets can be loaded from environment +* variables: +* +* - `false` (default): Secrets must be provided in `secretsMap`. If a secret is not +* found, `null` is returned instead of loading from environment variables. +* - `true`: If a secret is not found in `secretsMap`, it will be loaded from +* environment variables. Use this only in trusted environments. +* +* ### Hardening recommendations +* +* - **Never enable `secretsFromEnv`** unless the serialized data is fully trusted. +* A crafted payload can reference arbitrary environment variable names, leaking +* secrets to an attacker-controlled class constructor. +* - **Keep `secretsMap` minimal.** Only include the specific secrets the serialized +* object actually needs. +* - **Keep `importMap` / `optionalImportsMap` as small and static as possible.** +* Each entry widens the set of classes an attacker can instantiate. Never +* populate these maps from user input. +* +* ### Injection protection (escape-based) +* +* During serialization, plain objects that contain an `'lc'` key are escaped by wrapping +* them: `{"__lc_escaped__": {...}}`. During deserialization, escaped objects are unwrapped +* and returned as plain objects, NOT instantiated as LC objects. +* +* This is an allowlist approach: only objects explicitly produced by +* `Serializable.toJSON()` (which are NOT escaped) are treated as LC objects; +* everything else is user data. +* +* @module +*/ +/** +* Default maximum recursion depth for deserialization. +* This provides protection against DoS attacks via deeply nested structures. +*/ +var DEFAULT_MAX_DEPTH = 50; +function combineAliasesAndInvert(constructor) { + const aliases = {}; + for (let current = constructor; current && current.prototype; current = Object.getPrototypeOf(current)) Object.assign(aliases, Reflect.get(current.prototype, "lc_aliases")); + return Object.entries(aliases).reduce((acc, [key, value]) => { + acc[value] = key; + return acc; + }, {}); +} +/** +* Recursively revive a value, handling escape markers and LC objects. +* +* This function handles: +* 1. Escaped dicts - unwrapped and returned as plain objects +* 2. LC secret objects - resolved from secretsMap or env +* 3. LC constructor objects - instantiated +* 4. Regular objects/arrays - recursed into +*/ +async function reviver(value) { + const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path, depth, maxDepth } = this; + const pathStr = path.join("."); + if (depth > maxDepth) throw new Error(`Maximum recursion depth (${maxDepth}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`); + if (typeof value !== "object" || value == null) return value; + if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({ + ...this, + path: [...path, `${i}`], + depth: depth + 1 + }, v))); + const record = value; + if (isEscapedObject(record)) return unescapeValue(record); + if ("lc" in record && "type" in record && "id" in record && record.lc === 1 && record.type === "secret") { + const [key] = record.id; + if (key in secretsMap) return secretsMap[key]; + else if (secretsFromEnv) { + const secretValueInEnv = getEnvironmentVariable(key); + if (secretValueInEnv) return secretValueInEnv; + } + throw new Error(`Missing secret "${key}" at ${pathStr}`); + } + if ("lc" in record && "type" in record && "id" in record && record.lc === 1 && record.type === "not_implemented") { + const str = JSON.stringify(record); + throw new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`); + } + if ("lc" in record && "type" in record && "id" in record && "kwargs" in record && record.lc === 1 && record.type === "constructor") { + const serialized = record; + const str = JSON.stringify(serialized); + const [name, ...namespaceReverse] = serialized.id.slice().reverse(); + const namespace = namespaceReverse.reverse(); + const importMaps = { + langchain_core: import_map_exports, + langchain: importMap + }; + let module = null; + const optionalImportNamespaceAliases = [namespace.join("/")]; + if (namespace[0] === "langchain_community") optionalImportNamespaceAliases.push(["langchain", ...namespace.slice(1)].join("/")); + const matchingNamespaceAlias = optionalImportNamespaceAliases.find((alias) => alias in optionalImportsMap); + if (optionalImportEntrypoints.concat(optionalImportEntrypoints$1).includes(namespace.join("/")) || matchingNamespaceAlias) if (matchingNamespaceAlias !== void 0) module = await optionalImportsMap[matchingNamespaceAlias]; + else throw new Error(`Missing key "${namespace.join("/")}" for ${pathStr} in load(optionalImportsMap={})`); + else { + let finalImportMap; + if (namespace[0] === "langchain" || namespace[0] === "langchain_core") { + finalImportMap = importMaps[namespace[0]]; + namespace.shift(); + } else throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); + if (namespace.length === 0) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); + let importMapKey; + do { + importMapKey = namespace.join("__"); + if (importMapKey in finalImportMap) break; + else namespace.pop(); + } while (namespace.length > 0); + if (importMapKey in finalImportMap) module = finalImportMap[importMapKey]; + } + if (typeof module !== "object" || module === null) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); + const builder = module[name] ?? Object.values(module).find((v) => typeof v === "function" && get_lc_unique_name(v) === name); + if (typeof builder !== "function") throw new Error(`Invalid identifer: ${pathStr} -> ${str}`); + const instance = new builder(mapKeys(await reviver.call({ + ...this, + path: [...path, "kwargs"], + depth: depth + 1 + }, serialized.kwargs), keyFromJson, combineAliasesAndInvert(builder))); + Object.defineProperty(instance.constructor, "name", { value: name }); + return instance; + } + const result = {}; + for (const [key, val] of Object.entries(record)) result[key] = await reviver.call({ + ...this, + path: [...path, key], + depth: depth + 1 + }, val); + return result; +} +/** +* Load a LangChain object from a JSON string. +* +* **WARNING — insecure deserialization risk.** This function instantiates +* classes and invokes constructors based on the contents of `text`. If `text` +* originates from an untrusted source, an attacker can craft a payload that +* instantiates arbitrary allowed classes with attacker-controlled arguments, +* potentially causing secret exfiltration, SSRF, or other side effects. +* +* A serialized payload should be treated as executable configuration — it can +* configure models with custom endpoints, headers, or other constructor kwargs +* that execute during instantiation. +* +* Only call `load()` on data you have produced yourself or received from a +* fully trusted origin (e.g., your own database). **Never deserialize +* user-supplied or network-received JSON without independent validation.** +* +* @param text - The JSON string to parse and load. +* @param options - Options for loading. See {@link LoadOptions} for security guidance. +* @returns The loaded LangChain object. +* +* @example +* ```typescript +* import { load } from "@langchain/core/load"; +* import { AIMessage } from "@langchain/core/messages"; +* +* // Basic usage - secrets must be provided explicitly +* const msg = await load(jsonString); +* +* // With secrets from a map (preferred over secretsFromEnv) +* const msg = await load(jsonString, { +* secretsMap: { OPENAI_API_KEY: "sk-..." } +* }); +* +* // Allow loading secrets from environment — ONLY for fully trusted data +* const msg = await load(jsonString, { +* secretsFromEnv: true +* }); +* ``` +*/ +async function load(text, options) { + const json = JSON.parse(text); + const context = { + optionalImportsMap: options?.optionalImportsMap ?? {}, + optionalImportEntrypoints: options?.optionalImportEntrypoints ?? [], + secretsMap: options?.secretsMap ?? {}, + secretsFromEnv: options?.secretsFromEnv ?? false, + importMap: options?.importMap ?? {}, + path: ["$"], + depth: 0, + maxDepth: options?.maxDepth ?? DEFAULT_MAX_DEPTH + }; + return reviver.call(context, json); +} +//#endregion +export { context as n, convertOpenAICompletionsStream as r, load as t }; diff --git a/.vercel/output/functions/__server.func/_libs/langchain__openai+openai.mjs b/.vercel/output/functions/__server.func/_libs/langchain__openai+openai.mjs new file mode 100644 index 0000000..bc66c6c --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/langchain__openai+openai.mjs @@ -0,0 +1,17744 @@ +import { r as __exportAll } from "../_runtime.mjs"; +import { $t as string, Bt as array, It as _enum, Jt as number, Kt as literal, Qt as record, Yt as object, hn as registry, in as parse, sn as toJSONSchema, tn as union, yn as parse$1 } from "./@better-auth/core+[...].mjs"; +import { $n as isDataContentBlock, At as getSchemaDescription, C as makeInvalidToolCall, Cn as isAIMessage, E as JsonOutputParser, En as iife, F as isOpenAITool, It as isInteropZodSchema, Ln as ToolMessage, Lt as isZodSchemaV3, Mn as FunctionMessageChunk, Nn as ChatMessage, On as SystemMessageChunk, Pn as ChatMessageChunk, Qn as convertToProviderContentBlock, Rn as ToolMessageChunk, Rt as isZodSchemaV4, S as convertLangChainToolCallToOpenAI, Sn as AIMessageChunk, Tt as isSerializableSchema, _ as createFunctionCallingParser, bn as getEnvironmentVariable, c as isLangChainTool, er as parseBase64DataUrl, f as finalizeContentBlock, g as createContentParser, h as assembleStructuredOutputPipeline, it as ZodFirstPartyTypeKind, jn as HumanMessageChunk, l as BaseChatModel, n as convertToOpenAITool, nr as ContextOverflowError, q as RunnableLambda, rt as toJsonSchema, tr as parseMimeType, w as parseToolCall$2, xn as AIMessage, yn as getEnv, zt as ChatGenerationChunk } from "./@langchain/anthropic+[...].mjs"; +import { r as convertOpenAICompletionsStream } from "./langchain__core+mustache.mjs"; +//#region node_modules/@langchain/openai/dist/utils/errors.js +function addLangChainErrorFields(error, lc_error_code) { + error.lc_error_code = lc_error_code; + error.message = `${error.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\n`; + return error; +} +//#endregion +//#region node_modules/openai/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +//#endregion +//#region node_modules/openai/internal/utils/uuid.mjs +/** +* https://stackoverflow.com/a/2117523 +*/ +var uuid4 = function() { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); + } + const u8 = /* @__PURE__ */ new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; +//#endregion +//#region node_modules/openai/internal/errors.mjs +function isAbortError(err) { + return typeof err === "object" && err !== null && ("name" in err && err.name === "AbortError" || "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError = (err) => { + if (err instanceof Error) return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) error.stack = err.stack; + if (err.cause && !error.cause) error.cause = err.cause; + if (err.name) error.name = err.name; + return error; + } + } catch {} + try { + return new Error(JSON.stringify(err)); + } catch {} + } + return new Error(err); +}; +//#endregion +//#region node_modules/openai/core/error.mjs +var OpenAIError = class extends Error {}; +var APIError = class APIError extends OpenAIError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get("x-request-id"); + this.error = error; + const data = error; + 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 || !headers) return new APIConnectionError({ + message, + 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); + } +}; +var APIUserAbortError = class extends APIError { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } +}; +var APIConnectionError = class extends APIError { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) this.cause = cause; + } +}; +var APIConnectionTimeoutError = class extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } +}; +var BadRequestError = class extends APIError {}; +var AuthenticationError = class extends APIError {}; +var PermissionDeniedError = class extends APIError {}; +var NotFoundError = class extends APIError {}; +var ConflictError = class extends APIError {}; +var UnprocessableEntityError = class extends APIError {}; +var RateLimitError = class extends APIError {}; +var InternalServerError = class extends APIError {}; +var LengthFinishReasonError = class extends OpenAIError { + constructor() { + super(`Could not parse response content as the length limit was reached`); + } +}; +var ContentFilterFinishReasonError = class extends OpenAIError { + constructor() { + super(`Could not parse response content as the request was rejected by the content filter`); + } +}; +var InvalidWebhookSignatureError = class extends Error { + constructor(message) { + super(message); + } +}; +/** +* Error thrown by the API server during OAuth token exchange. +* Can have status codes 400, 401, or 403. +* Other status codes from OAuth endpoints are raised as normal APIError types. +*/ +var OAuthError = class extends APIError { + constructor(status, error, headers) { + let finalMessage = "OAuth2 authentication error"; + let error_code = void 0; + if (error && typeof error === "object") { + const errorData = error; + error_code = errorData["error"]; + const description = errorData["error_description"]; + if (description && typeof description === "string") finalMessage = description; + else if (error_code) finalMessage = error_code; + } + super(status, error, finalMessage, headers); + this.error_code = error_code; + } +}; +var SubjectTokenProviderError = class extends OpenAIError { + constructor(message, provider, cause) { + super(message); + this.provider = provider; + this.cause = cause; + } +}; +//#endregion +//#region node_modules/openai/internal/utils/values.mjs +var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +var isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +var isArray = (val) => (isArray = Array.isArray, isArray(val)); +var isReadonlyArray = isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +function maybeObj(x) { + if (typeof x !== "object") return {}; + return x ?? {}; +} +function isEmptyObj$1(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 isObj(obj) { + return obj != null && typeof obj === "object" && !Array.isArray(obj); +} +var validatePositiveInteger = (name, n) => { + if (typeof n !== "number" || !Number.isInteger(n)) throw new OpenAIError(`${name} must be an integer`); + if (n < 0) throw new OpenAIError(`${name} must be a positive integer`); + return n; +}; +var safeJSON = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return; + } +}; +//#endregion +//#region node_modules/openai/internal/utils/sleep.mjs +var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +//#endregion +//#region node_modules/openai/version.mjs +var VERSION = "6.49.0"; +//#endregion +//#region node_modules/openai/internal/detect-platform.mjs +var isRunningInBrowser = () => { + return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined"; +}; +/** +* Note this does not detect 'browser'; for that, use getBrowserInfo(). +*/ +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) return "deno"; + if (typeof EdgeRuntime !== "undefined") return "edge"; + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") return "node"; + return "unknown"; +} +var getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") 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": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + 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": globalThis.process.version + }; + if (detectedPlatform === "node") return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + 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" + }; +}; +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) return null; + for (const { key, pattern } of [ + { + 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/ + } + ]) { + const match = pattern.exec(navigator.userAgent); + if (match) return { + browser: key, + version: `${match[1] || 0}.${match[2] || 0}.${match[3] || 0}` + }; + } + return null; +} +var 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"; +}; +var 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"; +}; +var _platformHeaders; +var getPlatformHeaders = () => { + return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); +}; +//#endregion +//#region node_modules/openai/internal/shims.mjs +function getDefaultFetch() { + if (typeof fetch !== "undefined") return fetch; + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === "undefined") throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() {}, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) controller.close(); + else controller.enqueue(value); + }, + async cancel() { + await iter.return?.(); + } + }); +} +/** +* Most browsers don't yet have async iterable support for ReadableStream, +* and Node has a very different way of reading bytes from its "ReadableStream". +* +* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 +*/ +function ReadableStreamToAsyncIterable(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 (e) { + reader.releaseLock(); + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { + done: true, + value: void 0 + }; + }, + [Symbol.asyncIterator]() { + return this; + } + }; +} +/** +* Cancels a ReadableStream we don't need to consume. +* See https://undici.nodejs.org/#/?id=garbage-collection +*/ +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== "object") return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +//#endregion +//#region node_modules/openai/internal/request-options.mjs +var FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { "content-type": "application/json" }, + body: JSON.stringify(body) + }; +}; +//#endregion +//#region node_modules/openai/internal/qs/formats.mjs +var default_format = "RFC3986"; +var default_formatter = (v) => String(v); +var formatters = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter +}; +//#endregion +//#region node_modules/openai/internal/qs/utils.mjs +var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); +var hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + return array; +})(); +var limit = 1024; +var encode = (str, _defaultEncoder, charset, _kind, format) => { + if (str.length === 0) return str; + let string = str; + if (typeof str === "symbol") string = Symbol.prototype.toString.call(str); + else if (typeof str !== "string") string = String(str); + if (charset === "iso-8859-1") return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + let out = ""; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === "RFC1738" && (c === 40 || c === 41)) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr[arr.length] = hex_table[c]; + continue; + } + if (c < 2048) { + arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + } + out += arr.join(""); + } + return out; +}; +function is_buffer(obj) { + if (!obj || typeof obj !== "object") return false; + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val, fn) { + if (isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) mapped.push(fn(val[i])); + return mapped; + } + return fn(val); +} +//#endregion +//#region node_modules/openai/internal/qs/stringify.mjs +var array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } +}; +var push_to_array = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); +}; +var toISOString; +var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false +}; +function is_non_nullish_primitive(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +var sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") if (pos === step) throw new RangeError("Cyclic object value"); + else find_flag = true; + if (typeof tmp_sc.get(sentinel) === "undefined") step = 0; + } + if (typeof filter === "function") obj = filter(prefix, obj); + else if (obj instanceof Date) obj = serializeDate?.(obj); + else if (generateArrayPrefix === "comma" && isArray(obj)) obj = maybe_map(obj, function(value) { + if (value instanceof Date) return serializeDate?.(value); + return value; + }); + if (obj === null) { + if (strictNullHandling) return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix; + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); + return [formatter?.(key_value) + "=" + formatter?.(encoder(obj, defaults.encoder, charset, "value", format))]; + } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") return values; + let obj_keys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + if (encodeValuesOnly && encoder) obj = maybe_map(obj, encoder); + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) obj_keys = filter; + else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray(obj) && obj.length === 0) return adjusted_prefix + "[]"; + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]; + if (skipNulls && value === null) continue; + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); + } + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") throw new TypeError("Encoder has to be a function."); + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + let format = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) throw new TypeError("Unknown format option provided."); + format = opts.format; + } + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) filter = opts.filter; + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) arrayFormat = opts.arrayFormat; + else if ("indices" in opts) arrayFormat = opts.indices ? "indices" : "repeat"; + else arrayFormat = defaults.arrayFormat; + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; +} +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) return ""; + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) obj_keys = Object.keys(obj); + if (options.sort) obj_keys.sort(options.sort); + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) continue; + push_to_array(keys, inner_stringify(obj[key], key, generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) if (options.charset === "iso-8859-1") prefix += "utf8=%26%2310003%3B&"; + else prefix += "utf8=%E2%9C%93&"; + return joined.length > 0 ? prefix + joined : ""; +} +//#endregion +//#region node_modules/openai/internal/utils/query.mjs +function stringifyQuery(query) { + return stringify(query, { arrayFormat: "brackets" }); +} +//#endregion +//#region node_modules/openai/internal/utils/bytes.mjs +function concatBytes(buffers) { + let length = 0; + for (const buffer of buffers) length += buffer.length; + const output = new Uint8Array(length); + let index = 0; + for (const buffer of buffers) { + output.set(buffer, index); + index += buffer.length; + } + return output; +} +var encodeUTF8_; +function encodeUTF8(str) { + let encoder; + return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str); +} +var decodeUTF8_; +function decodeUTF8(bytes) { + let decoder; + return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes); +} +//#endregion +//#region node_modules/openai/internal/decoders/line.mjs +var _LineDecoder_buffer; +var _LineDecoder_carriageReturnIndex; +/** +* A re-implementation of httpx's `LineDecoder` in Python that handles incrementally +* reading lines from text. +* +* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 +*/ +var LineDecoder = class { + constructor() { + _LineDecoder_buffer.set(this, void 0); + _LineDecoder_carriageReturnIndex.set(this, void 0); + __classPrivateFieldSet(this, _LineDecoder_buffer, /* @__PURE__ */ new Uint8Array(), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + decode(chunk) { + if (chunk == null) return []; + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; + __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + continue; + } + if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + continue; + } + const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); + lines.push(line); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + return lines; + } + flush() { + if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) return []; + return this.decode("\n"); + } +}; +_LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex = /* @__PURE__ */ new WeakMap(); +LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]); +LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +/** +* This function searches the buffer for the end patterns, (\r or \n) +* and returns an object with the index preceding the matched newline and the +* index after the newline char. `null` is returned if no new line is found. +* +* ```ts +* findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } +* ``` +*/ +function findNewlineIndex(buffer, startIndex) { + const newline = 10; + const carriage = 13; + for (let i = startIndex ?? 0; i < buffer.length; i++) { + if (buffer[i] === newline) return { + preceding: i, + index: i + 1, + carriage: false + }; + if (buffer[i] === carriage) return { + preceding: i, + index: i + 1, + carriage: true + }; + } + return null; +} +function findDoubleNewlineIndex(buffer) { + const newline = 10; + const carriage = 13; + for (let i = 0; i < buffer.length - 1; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) return i + 2; + if (buffer[i] === carriage && buffer[i + 1] === carriage) return i + 2; + if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) return i + 4; + } + return -1; +} +//#endregion +//#region node_modules/openai/internal/utils/log.mjs +var levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 +}; +var parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) return; + if (hasOwn(levelNumbers, maybeLevel)) return maybeLevel; + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); +}; +function noop() {} +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) return noop; + else return logger[fnLevel].bind(logger); +} +var noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop +}; +var cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger) return noopLogger; + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) return cachedLogger[1]; + const levelLogger = { + error: makeLogFn("error", logger, logLevel), + warn: makeLogFn("warn", logger, logLevel), + info: makeLogFn("info", logger, logLevel), + debug: makeLogFn("debug", logger, logLevel) + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +var formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "x-amz-security-token" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value])); + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) details.retryOf = details.retryOfRequestLogID; + delete details.retryOfRequestLogID; + } + return details; +}; +//#endregion +//#region node_modules/openai/core/streaming.mjs +var _Stream_client; +var Stream = class Stream { + constructor(iterator, controller, client) { + this.iterator = iterator; + _Stream_client.set(this, void 0); + this.controller = controller; + __classPrivateFieldSet(this, _Stream_client, client, "f"); + } + static fromSSEResponse(response, controller, client, synthesizeEventData) { + let consumed = false; + const logger = client ? loggerFor(client) : console; + async function* iterator() { + if (consumed) throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (done) continue; + if (sse.data.startsWith("[DONE]")) { + done = true; + continue; + } + if (sse.event === null || !sse.event.startsWith("thread.")) { + let data; + try { + data = JSON.parse(sse.data); + } catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + if (data && data.error) throw new APIError(void 0, data.error, void 0, response.headers); + yield synthesizeEventData ? { + event: sse.event, + data + } : data; + } else { + let data; + try { + data = JSON.parse(sse.data); + } catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + if (sse.event == "error") throw new APIError(void 0, data.error, data.message, void 0); + yield { + event: sse.event, + data + }; + } + } + done = true; + } catch (e) { + if (isAbortError(e)) return; + throw e; + } finally { + if (!done) controller.abort(); + } + } + return new Stream(iterator, controller, client); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller, client) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new LineDecoder(); + const reader = readableStream.getReader(); + let closed = false; + let cancelPromise; + const cancel = () => { + cancelPromise ?? (cancelPromise = reader.cancel()); + cancelPromise.catch(() => {}); + }; + controller.signal.addEventListener("abort", cancel, { once: true }); + try { + if (controller.signal.aborted) { + cancel(); + return; + } + while (true) { + const { value: chunk, done } = await reader.read(); + if (done) { + closed = true; + break; + } + if (controller.signal.aborted) return; + for (const line of lineDecoder.decode(chunk)) { + if (controller.signal.aborted) return; + yield line; + } + } + if (controller.signal.aborted) return; + for (const line of lineDecoder.flush()) { + if (controller.signal.aborted) return; + yield line; + } + } finally { + controller.signal.removeEventListener("abort", cancel); + if (!closed) cancel(); + reader.releaseLock(); + } + } + async function* iterator() { + if (consumed) throw new OpenAIError("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 (e) { + if (controller.signal.aborted || isAbortError(e)) return; + throw e; + } finally { + if (!done) controller.abort(); + } + } + return new Stream(iterator, controller, client); + } + [(_Stream_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + } }; + }; + return [new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f"))]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self = this; + let iter; + return makeReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) return ctrl.close(); + const bytes = encodeUTF8(JSON.stringify(value) + "\n"); + ctrl.enqueue(bytes); + } catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + } + }); + } +}; +async function* _iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") throw new OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + throw new OpenAIError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) yield sse; + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) yield sse; + } +} +/** +* Given an async iterable iterator, iterates over it and yields full +* SSE chunks, i.e. yields when a double new-line is encountered. +*/ +async function* iterSSEChunks(iterator) { + let data = /* @__PURE__ */ new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) continue; + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) yield data; +} +var 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, _, 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; + } +}; +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) return [ + str.substring(0, index), + delimiter, + str.substring(index + delimiter.length) + ]; + return [ + str, + "", + "" + ]; +} +//#endregion +//#region node_modules/openai/internal/parse.mjs +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + loggerFor(client).debug("response", response.status, response.url, response.headers, response.body); + if (props.options.__streamClass) return props.options.__streamClass.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData); + return Stream.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData); + } + if (response.status === 204) return null; + if (props.options.__binaryResponse) return response; + const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim(); + if (mediaType?.includes("application/json") || mediaType?.endsWith("+json")) { + if (response.headers.get("content-length") === "0") return; + return addRequestID(await response.json(), response); + } + return await response.text(); + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} +function addRequestID(value, response) { + if (!value || typeof value !== "object" || Array.isArray(value)) return value; + return Object.defineProperty(value, "_request_id", { + value: response.headers.get("x-request-id"), + enumerable: false + }); +} +//#endregion +//#region node_modules/openai/core/api-promise.mjs +var _APIPromise_client; +/** +* A subclass of `Promise` providing additional helper methods +* for interacting with the SDK. +*/ +var APIPromise = class APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the X-Request-ID header which is useful for debugging requests and reporting + * issues to OpenAI. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { + data, + response, + request_id: response.headers.get("x-request-id") + }; + } + parse() { + if (!this.parsedPromise) this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + 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); + } +}; +_APIPromise_client = /* @__PURE__ */ new WeakMap(); +//#endregion +//#region node_modules/openai/core/pagination.mjs +var _AbstractPage_client; +var 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() { + if (!this.getPaginatedItems().length) return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + 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 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) for (const item of page.getPaginatedItems()) yield item; + } +}; +/** +* This subclass of Promise will resolve to an instantiated Page once the request completes. +* +* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: +* +* for await (const item of client.items.list()) { +* console.log(item) +* } +*/ +var PagePromise = class extends APIPromise { + constructor(client, request, Page) { + super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) yield item; + } +}; +/** +* Note: no pagination actually occurs yet, this is for forwards-compatibility. +*/ +var 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 ?? []; + } + nextPageRequestOptions() { + return null; + } +}; +var CursorPage = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) return false; + return super.hasNextPage(); + } + nextPageRequestOptions() { + const data = this.getPaginatedItems(); + const id = data[data.length - 1]?.id; + if (!id) return null; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after: id + } + }; + } +}; +var ConversationCursorPage = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.last_id = body.last_id || ""; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) return false; + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.last_id; + if (!cursor) return null; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after: cursor + } + }; + } +}; +var NextCursorPage = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.next = body.next || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) return false; + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.next; + if (!cursor) return null; + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after: cursor + } + }; + } +}; +//#endregion +//#region node_modules/openai/auth/workload-identity-auth.mjs +var SUBJECT_TOKEN_TYPES = { + jwt: "urn:ietf:params:oauth:token-type:jwt", + id: "urn:ietf:params:oauth:token-type:id_token" +}; +var TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; +var WorkloadIdentityAuth = class { + constructor(config, fetch) { + this.cachedToken = null; + this.refreshPromise = null; + this.tokenExchangeUrl = "https://auth.openai.com/oauth/token"; + this.config = config; + this.fetch = fetch ?? getDefaultFetch(); + } + async getToken() { + if (!this.cachedToken || this.isTokenExpired(this.cachedToken)) { + if (this.refreshPromise) return await this.refreshPromise; + this.refreshPromise = this.refreshToken(); + try { + return await this.refreshPromise; + } finally { + this.refreshPromise = null; + } + } + if (this.needsRefresh(this.cachedToken) && !this.refreshPromise) this.refreshPromise = this.refreshToken().finally(() => { + this.refreshPromise = null; + }); + return this.cachedToken.token; + } + async refreshToken() { + const body = { + grant_type: TOKEN_EXCHANGE_GRANT_TYPE, + subject_token: await this.config.provider.getToken(), + subject_token_type: SUBJECT_TOKEN_TYPES[this.config.provider.tokenType], + identity_provider_id: this.config.identityProviderId, + service_account_id: this.config.serviceAccountId + }; + if (this.config.clientId) body["client_id"] = this.config.clientId; + const response = await this.fetch(this.tokenExchangeUrl, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body) + }); + if (!response.ok) { + const errorText = await response.text(); + let body = void 0; + try { + body = JSON.parse(errorText); + } catch {} + if (response.status === 400 || response.status === 401 || response.status === 403) throw new OAuthError(response.status, body, response.headers); + throw APIError.generate(response.status, body, `Token exchange failed with status ${response.status}`, response.headers); + } + const tokenResponse = await response.json(); + if (typeof tokenResponse !== "object" || tokenResponse === null || !("access_token" in tokenResponse) || typeof tokenResponse.access_token !== "string" || tokenResponse.access_token.trim().length === 0) throw new OpenAIError("Token exchange response missing 'access_token' field"); + const accessToken = tokenResponse.access_token; + const expiresIn = tokenResponse.expires_in ?? 3600; + const expiresAt = Date.now() + expiresIn * 1e3; + this.cachedToken = { + token: accessToken, + expiresAt + }; + return accessToken; + } + isTokenExpired(cachedToken) { + return Date.now() >= cachedToken.expiresAt; + } + needsRefresh(cachedToken) { + const bufferMs = (this.config.refreshBufferSeconds ?? 1200) * 1e3; + return Date.now() >= cachedToken.expiresAt - bufferMs; + } + invalidateToken() { + this.cachedToken = null; + this.refreshPromise = null; + } +}; +//#endregion +//#region node_modules/openai/internal/headers.mjs +var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); +var httpTokenHeaderName = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; +function* iterateHeaders(headers) { + if (!headers) return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) yield [name, null]; + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) iter = headers.entries(); + else if (isReadonlyArray(headers)) iter = headers; + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") throw new TypeError("expected header name to be a string"); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === void 0) continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +var buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders(headers)) { + if (!httpTokenHeaderName.test(name)) throw new TypeError(`Header name must be a valid HTTP token ["${name}"]`); + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(lowerName); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(lowerName); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(lowerName, value); + nullHeaders.delete(lowerName); + } + } + } + return { + [brand_privateNullableHeaders]: true, + values: targetHeaders, + nulls: nullHeaders + }; +}; +//#endregion +//#region node_modules/openai/internal/uploads.mjs +var brand_privateStreamingFile = /* @__PURE__ */ Symbol("brand.privateStreamingFile"); +/** +* Wrap a stream as an uploadable file without reading it into memory. +* +* Unlike {@link toFile}, this helper does not create a web `File`, because the `File` constructor +* must consume all of its contents up front. The stream is instead encoded lazily as multipart +* form data when the request is sent. +*/ +function toStreamingFile(data, name, options) { + if (!name) throw new TypeError("toStreamingFile requires a non-empty file name"); + return { + [brand_privateStreamingFile]: true, + data, + name, + ...options?.type ? { type: options.type } : {} + }; +} +var checkFileSupport = () => { + if (typeof File === "undefined") { + const { process } = globalThis; + const isOldNode = typeof process?.versions?.node === "string" && parseInt(process.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}; +/** +* Construct a `File` instance. This is used to ensure a helpful error is thrown +* for environments that don't define a global `File` yet. +*/ +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; +} +var isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; +/** +* Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. +* Otherwise returns the request as is. +*/ +var maybeMultipartFormRequestOptions = async (opts, fetch) => { + if (!hasUploadableValue(opts.body)) return opts; + if (hasStreamingUploadableValue(opts.body)) return createStreamingFormRequestOptions(opts); + return { + ...opts, + body: await createForm(opts.body, fetch) + }; +}; +var multipartFormRequestOptions = async (opts, fetch) => { + if (hasStreamingUploadableValue(opts.body)) return createStreamingFormRequestOptions(opts); + return { + ...opts, + body: await createForm(opts.body, fetch) + }; +}; +var supportsFormDataMap = /* @__PURE__ */ new WeakMap(); +/** +* node-fetch doesn't support the global FormData object in recent node versions. Instead of sending +* properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". +* This function detects if the fetch function provided supports the global FormData object to avoid +* confusing error messages later on. +*/ +function supportsFormData(fetchObject) { + const fetch = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap.get(fetch); + if (cached) return cached; + const promise = (async () => { + try { + const FetchResponse = "Response" in fetch ? fetch.Response : (await fetch("data:,")).constructor; + const data = new FormData(); + if (data.toString() === await new FetchResponse(data).text()) return false; + return true; + } catch { + return true; + } + })(); + supportsFormDataMap.set(fetch, promise); + return promise; +} +var createForm = async (body, fetch) => { + if (!await supportsFormData(fetch)) throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; +var isNamedBlob = (value) => value instanceof Blob && "name" in value; +var isReadableStream = (value) => typeof value === "object" && value !== null && "getReader" in value && typeof value.getReader === "function"; +var isStreamingFile = (value) => typeof value === "object" && value !== null && brand_privateStreamingFile in value; +var isUploadable = (value) => typeof value === "object" && value !== null && (value instanceof Response || isAsyncIterable(value) || isReadableStream(value) || isStreamingFile(value) || isNamedBlob(value)); +var hasStreamingUploadableValue = (value) => { + if (isStreamingFile(value) || isAsyncIterable(value) || isReadableStream(value)) return true; + if (Array.isArray(value)) return value.some(hasStreamingUploadableValue); + if (value && typeof value === "object" && !isNamedBlob(value) && !(value instanceof Response)) { + for (const k in value) if (hasStreamingUploadableValue(value[k])) return true; + } + return false; +}; +var hasUploadableValue = (value) => { + if (isUploadable(value)) return true; + if (Array.isArray(value)) return value.some(hasUploadableValue); + if (value && typeof value === "object") { + for (const k in value) if (hasUploadableValue(value[k])) return true; + } + return false; +}; +var createStreamingFormRequestOptions = (opts) => { + const boundary = `openai-${Math.random().toString(36).slice(2)}`; + const body = ReadableStreamFrom(iterateMultipartBody(opts.body, boundary)); + return { + ...opts, + body, + headers: buildHeaders([{ "content-type": `multipart/form-data; boundary=${boundary}` }, opts.headers]) + }; +}; +async function* iterateMultipartBody(body, boundary) { + for await (const { key, value } of iterateFormEntries(body)) { + yield encodeUTF8(`--${boundary}\r\n`); + if (isUploadable(value)) { + const filename = getStreamingFileName(value); + const type = getStreamingFileType(value); + yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"; filename="${escapeHeaderValue(filename)}"\r\nContent-Type: ${type}\r\n\r\n`); + yield* iterateBytes(getStreamingFileData(value)); + } else yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"\r\n\r\n${String(value)}`); + yield encodeUTF8("\r\n"); + } + yield encodeUTF8(`--${boundary}--\r\n`); +} +async function* iterateFormEntries(body) { + if (!body || typeof body !== "object") return; + for (const [key, value] of Object.entries(body)) yield* iterateFormValue(key, value); +} +async function* iterateFormValue(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" || isUploadable(value)) yield { + key, + value + }; + else if (Array.isArray(value)) for (const entry of value) yield* iterateFormValue(key + "[]", entry); + else if (typeof value === "object") for (const [name, prop] of Object.entries(value)) yield* iterateFormValue(`${key}[${name}]`, prop); + else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); +} +function getStreamingFileName(value) { + return isStreamingFile(value) ? value.name : getName(value) ?? "unknown_file"; +} +function getStreamingFileType(value) { + if (isStreamingFile(value)) return value.type || "application/octet-stream"; + if (isNamedBlob(value) && value.type) return value.type; + if (value instanceof Response) return value.headers.get("content-type") || "application/octet-stream"; + return "application/octet-stream"; +} +function getStreamingFileData(value) { + if (isStreamingFile(value)) return value.data; + return value; +} +async function* iterateBytes(value) { + if (typeof value === "string") yield encodeUTF8(value); + else if (ArrayBuffer.isView(value)) yield new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + else if (value instanceof ArrayBuffer) yield new Uint8Array(value); + else if (value instanceof Response) if (value.body) yield* iterateBytes(value.body); + else yield* iterateBytes(await value.blob()); + else if (value instanceof Blob) if (typeof value.stream === "function") yield* iterateBytes(value.stream()); + else yield new Uint8Array(await value.arrayBuffer()); + else if (isReadableStream(value)) for await (const chunk of ReadableStreamToAsyncIterable(value)) yield* iterateBytes(chunk); + else if (isAsyncIterable(value)) for await (const chunk of value) yield* iterateBytes(chunk); + else throw new TypeError(`Invalid streaming file chunk: ${String(value)}`); +} +function escapeHeaderValue(value) { + return value.replace(/["\\\r\n]/g, (character) => encodeURIComponent(character)); +} +var 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 (value instanceof Response) form.append(key, makeFile([await value.blob()], getName(value))); + else if (isAsyncIterable(value)) form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value))); + else if (isNamedBlob(value)) form.append(key, value, getName(value)); + 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(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); + else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); +}; +//#endregion +//#region node_modules/openai/internal/to-file.mjs +/** +* This check adds the arrayBuffer() method type because it is available and used at runtime +*/ +var 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"; +/** +* This check adds the arrayBuffer() method type because it is available and used at runtime +*/ +var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); +var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; +/** +* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats +* @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts +* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible +* @param {Object=} options additional properties +* @param {string=} options.type the MIME type of the content +* @param {number=} options.lastModified the last modified timestamp +* @returns a {@link File} with the given properties +*/ +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + if (isFileLike(value)) { + if (value instanceof File) return value; + return makeFile([await value.arrayBuffer()], value.name); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + name || (name = getName(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") options = { + ...options, + type + }; + } + return makeFile(parts, name, 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(value instanceof Blob ? value : await value.arrayBuffer()); + else if (isAsyncIterable(value)) for await (const chunk of value) parts.push(...await getBytes(chunk)); + else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) return ""; + return `; props: [${Object.getOwnPropertyNames(value).map((p) => `"${p}"`).join(", ")}]`; +} +//#endregion +//#region node_modules/openai/core/resource.mjs +var APIResource = class { + constructor(client) { + this._client = client; + } +}; +//#endregion +//#region node_modules/openai/internal/utils/path.mjs +/** +* Percent-encode everything that isn't safe to have in a path without encoding safe chars. +* +* Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: +* > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" +* > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" +* > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" +*/ +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +var createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { + if (statics.length === 1) return statics[0]; + let postPath = false; + const invalidSegments = []; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) postPath = true; + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index === params.length ? "" : encoded); + }, ""); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter` + }); + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new OpenAIError(`Path parameters result in path with invalid segments:\n${invalidSegments.map((e) => e.error).join("\n")}\n${path}\n${underline}`); + } + return path; +}; +/** +* URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. +*/ +var path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); +//#endregion +//#region node_modules/openai/resources/chat/completions/messages.mjs +/** +* Given a list of messages comprising a conversation, the model will return a response. +*/ +var Messages$1 = class extends APIResource { + /** + * Get the messages in a stored chat completion. Only Chat Completions that have + * been created with the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list( + * 'completion_id', + * )) { + * // ... + * } + * ``` + */ + list(completionID, query = {}, options) { + return this._client.getAPIList(path`/chat/completions/${completionID}/messages`, CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/lib/parser.mjs +function isChatCompletionFunctionTool(tool) { + return tool !== void 0 && "function" in tool && tool.function !== void 0; +} +function makeParseableResponseFormat$1(response_format, parser) { + const obj = { ...response_format }; + Object.defineProperties(obj, { + $brand: { + value: "auto-parseable-response-format", + enumerable: false + }, + $parseRaw: { + value: parser, + enumerable: false + } + }); + return obj; +} +function isAutoParsableResponseFormat(response_format) { + return response_format?.["$brand"] === "auto-parseable-response-format"; +} +function isAutoParsableTool$1(tool) { + return tool?.["$brand"] === "auto-parseable-tool"; +} +function maybeParseChatCompletion(completion, params) { + if (!params || !hasAutoParseableInput$1(params)) return { + ...completion, + choices: completion.choices.map((choice) => { + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + parsed: null, + ...choice.message.tool_calls ? { tool_calls: choice.message.tool_calls } : void 0 + } + }; + }) + }; + return parseChatCompletion(completion, params); +} +function parseChatCompletion(completion, params) { + const choices = completion.choices.map((choice) => { + if (choice.finish_reason === "length") throw new LengthFinishReasonError(); + if (choice.finish_reason === "content_filter") throw new ContentFilterFinishReasonError(); + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + ...choice.message.tool_calls ? { tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall$1(params, toolCall)) ?? void 0 } : void 0, + parsed: choice.message.content && !choice.message.refusal ? parseResponseFormat(params, choice.message.content) : null + } + }; + }); + return { + ...completion, + choices + }; +} +function parseResponseFormat(params, content) { + if (params.response_format?.type !== "json_schema") return null; + if (params.response_format?.type === "json_schema") { + if ("$parseRaw" in params.response_format) return params.response_format.$parseRaw(content); + return JSON.parse(content); + } + return null; +} +function parseToolCall$1(params, toolCall) { + const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); + return { + ...toolCall, + function: { + ...toolCall.function, + parsed_arguments: isAutoParsableTool$1(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) : null + } + }; +} +function shouldParseToolCall(params, toolCall) { + if (!params || !("tools" in params) || !params.tools) return false; + const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); + return isChatCompletionFunctionTool(inputTool) && (isAutoParsableTool$1(inputTool) || inputTool?.function.strict || false); +} +function hasAutoParseableInput$1(params) { + if (isAutoParsableResponseFormat(params.response_format)) return true; + return params.tools?.some((t) => isAutoParsableTool$1(t) || t.type === "function" && t.function.strict === true) ?? false; +} +function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) { + for (const toolCall of toolCalls || []) if (toolCall.type !== "function") throw new OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``); +} +function validateInputTools(tools) { + for (const tool of tools ?? []) { + if (tool.type !== "function") throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); + if (tool.function.strict !== true) throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); + } +} +//#endregion +//#region node_modules/openai/lib/chatCompletionUtils.mjs +var isAssistantMessage = (message) => { + return message?.role === "assistant"; +}; +var isToolMessage = (message) => { + return message?.role === "tool"; +}; +//#endregion +//#region node_modules/openai/lib/EventStream.mjs +var _EventStream_instances; +var _EventStream_connectedPromise; +var _EventStream_resolveConnectedPromise; +var _EventStream_rejectConnectedPromise; +var _EventStream_endPromise; +var _EventStream_resolveEndPromise; +var _EventStream_rejectEndPromise; +var _EventStream_listeners; +var _EventStream_abortListeners; +var _EventStream_ended; +var _EventStream_errored; +var _EventStream_aborted; +var _EventStream_catchingPromiseCreated; +var _EventStream_removeAbortListeners; +var _EventStream_handleError; +var EventStream = class { + constructor() { + _EventStream_instances.add(this); + this.controller = new AbortController(); + _EventStream_connectedPromise.set(this, void 0); + _EventStream_resolveConnectedPromise.set(this, () => {}); + _EventStream_rejectConnectedPromise.set(this, () => {}); + _EventStream_endPromise.set(this, void 0); + _EventStream_resolveEndPromise.set(this, () => {}); + _EventStream_rejectEndPromise.set(this, () => {}); + _EventStream_listeners.set(this, {}); + _EventStream_abortListeners.set(this, []); + _EventStream_ended.set(this, false); + _EventStream_errored.set(this, false); + _EventStream_aborted.set(this, false); + _EventStream_catchingPromiseCreated.set(this, false); + __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f"); + }), "f"); + __classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => {}); + __classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => {}); + } + _run(executor) { + setTimeout(() => { + Promise.resolve().then(executor).then(() => { + try { + this._emitFinal(); + } catch (error) { + __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).call(this, error); + return; + } + this._emit("end"); + }, __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); + }, 0); + } + _connected() { + if (this.ended) return; + __classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this); + this._emit("connect"); + } + get ended() { + return __classPrivateFieldGet(this, _EventStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _EventStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _EventStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + _listenForAbort(signal) { + if (!signal || this.ended) return; + if (signal.aborted) { + this.controller.abort(); + return; + } + const listener = () => this.controller.abort(); + signal.addEventListener("abort", listener, { once: true }); + __classPrivateFieldGet(this, _EventStream_abortListeners, "f").push({ + signal, + listener + }); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event, listener) { + (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = [])).push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; + if (!listeners) return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event, listener) { + (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = [])).push({ + listener, + once: true + }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); + if (event !== "error") this.once("error", reject); + this.once(event, resolve); + }); + } + /** + * Returns an async iterator that yields every time the event is triggered. + * The iterator ends when the stream ends and rejects if the stream errors + * or is aborted. If you request the 'error' or 'abort' event, the iterator + * yields that event instead of rejecting. + * + * Example: + * + * for await (const [message] of stream.events('message')) { + * await processMessage(message); + * } + */ + events(event) { + const pushQueue = []; + const readQueue = []; + let ended = this.ended; + let failure; + let failureDelivered = false; + const doneResult = () => ({ + value: void 0, + done: true + }); + const finishReaders = () => { + while (readQueue.length) readQueue.shift().resolve(doneResult()); + }; + const rejectReader = () => { + if (!failure || failureDelivered || !readQueue.length) return; + failureDelivered = true; + readQueue.shift().reject(failure); + }; + const cleanup = () => { + this.off(event, onEvent); + this.off("end", onEnd); + if (event !== "error") this.off("error", onFailure); + if (event !== "abort") this.off("abort", onFailure); + }; + const onEvent = (...args) => { + if (ended) return; + const reader = readQueue.shift(); + if (reader) reader.resolve({ + value: args, + done: false + }); + else pushQueue.push(args); + }; + const onFailure = (error) => { + failure = error; + if (!pushQueue.length) rejectReader(); + }; + const onEnd = () => { + ended = true; + cleanup(); + if (!pushQueue.length) { + rejectReader(); + finishReaders(); + } + }; + if (!ended) { + this.on(event, onEvent); + this.on("end", onEnd); + if (event !== "error") this.on("error", onFailure); + if (event !== "abort") this.on("abort", onFailure); + } + return { + next: () => { + const value = pushQueue.shift(); + if (value) return Promise.resolve({ + value, + done: false + }); + if (failure && !failureDelivered) { + failureDelivered = true; + return Promise.reject(failure); + } + if (ended) return Promise.resolve(doneResult()); + return new Promise((resolve, reject) => { + readQueue.push({ + resolve, + reject + }); + }); + }, + return: () => { + ended = true; + pushQueue.length = 0; + cleanup(); + finishReaders(); + return Promise.resolve(doneResult()); + }, + [Symbol.asyncIterator]() { + return this; + } + }; + } + async done() { + __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _EventStream_endPromise, "f"); + } + _emit(event, ...args) { + if (__classPrivateFieldGet(this, _EventStream_ended, "f")) return; + if (event === "end") { + __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_removeAbortListeners).call(this); + __classPrivateFieldSet(this, _EventStream_ended, true, "f"); + __classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === "abort") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); + __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + return; + } + if (event === "error") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) Promise.reject(error); + __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + } + } + _emitFinal() {} +}; +_EventStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_endPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_listeners = /* @__PURE__ */ new WeakMap(), _EventStream_abortListeners = /* @__PURE__ */ new WeakMap(), _EventStream_ended = /* @__PURE__ */ new WeakMap(), _EventStream_errored = /* @__PURE__ */ new WeakMap(), _EventStream_aborted = /* @__PURE__ */ new WeakMap(), _EventStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _EventStream_instances = /* @__PURE__ */ new WeakSet(), _EventStream_removeAbortListeners = function _EventStream_removeAbortListeners() { + for (const { signal, listener } of __classPrivateFieldGet(this, _EventStream_abortListeners, "f").splice(0)) signal.removeEventListener("abort", listener); +}, _EventStream_handleError = function _EventStream_handleError(error) { + __classPrivateFieldSet(this, _EventStream_errored, true, "f"); + if (error instanceof Error && error.name === "AbortError") error = new APIUserAbortError(); + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _EventStream_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))); +}; +//#endregion +//#region node_modules/openai/lib/RunnableFunction.mjs +function isRunnableFunctionWithParse(fn) { + return typeof fn.parse === "function"; +} +//#endregion +//#region node_modules/openai/lib/AbstractChatCompletionRunner.mjs +var _AbstractChatCompletionRunner_instances; +var _AbstractChatCompletionRunner_getFinalContent; +var _AbstractChatCompletionRunner_getFinalMessage; +var _AbstractChatCompletionRunner_getFinalFunctionToolCall; +var _AbstractChatCompletionRunner_getFinalFunctionToolCallResult; +var _AbstractChatCompletionRunner_calculateTotalUsage; +var _AbstractChatCompletionRunner_validateParams; +var _AbstractChatCompletionRunner_stringifyFunctionCallResult; +var DEFAULT_MAX_CHAT_COMPLETIONS = 10; +function normalizeToolCallIds(chatCompletion) { + for (const choice of chatCompletion.choices) for (const toolCall of choice.message.tool_calls ?? []) if (!toolCall.id) toolCall.id = `call_${uuid4()}`; +} +/** +* Parsed completions contain response-only and helper-only fields. Keep those +* on runner.messages for callers, but only replay valid request fields. +*/ +function toRequestMessage(message) { + if (!isAssistantMessage(message)) return message; + const requestMessage = { role: "assistant" }; + if (message.audio != null) requestMessage.audio = { id: message.audio.id }; + if (message.content !== void 0) requestMessage.content = message.content; + if (message.function_call != null) requestMessage.function_call = message.function_call; + if (message.name !== void 0) requestMessage.name = message.name; + if (message.refusal != null) requestMessage.refusal = message.refusal; + if (message.tool_calls !== void 0) requestMessage.tool_calls = message.tool_calls.map((toolCall) => { + if (toolCall.type === "custom") return { + id: toolCall.id, + type: toolCall.type, + custom: { + input: toolCall.custom.input, + name: toolCall.custom.name + } + }; + return { + id: toolCall.id, + type: toolCall.type, + function: { + arguments: toolCall.function.arguments, + name: toolCall.function.name + } + }; + }); + return requestMessage; +} +var AbstractChatCompletionRunner = class extends EventStream { + constructor() { + super(...arguments); + _AbstractChatCompletionRunner_instances.add(this); + this._chatCompletions = []; + this.messages = []; + } + _addChatCompletion(chatCompletion) { + normalizeToolCallIds(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 (isToolMessage(message) && message.content) this._emit("functionToolCallResult", message.content); + else if (isAssistantMessage(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) if (tool_call.type === "function") this._emit("functionToolCall", tool_call.function); + } + } + } + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + 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; + } + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalContent() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + } + /** + * @returns a promise that resolves with the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalFunctionToolCall() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); + } + async finalFunctionToolCallResult() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); + } + async totalUsage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); + } + allChatCompletions() { + return [...this._chatCompletions]; + } + _emitFinal() { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) this._emit("finalChatCompletion", completion); + const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + if (finalMessage) this._emit("finalMessage", finalMessage); + const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + if (finalContent) this._emit("finalContent", finalContent); + const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); + if (finalFunctionCall) this._emit("finalFunctionToolCall", finalFunctionCall); + const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); + if (finalFunctionCallResult != null) this._emit("finalFunctionToolCallResult", finalFunctionCallResult); + if (this._chatCompletions.some((c) => c.usage)) this._emit("totalUsage", __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); + } + async _createChatCompletion(client, params, options) { + this._listenForAbort(options?.signal); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); + const chatCompletion = await client.chat.completions.create({ + ...params, + stream: false + }, { + ...options, + signal: this.controller.signal + }); + this._connected(); + return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); + } + async _runChatCompletion(client, params, options) { + for (const message of params.messages) this._addMessage(message, false); + return await this._createChatCompletion(client, params, options); + } + async _runTools(client, params, runner, options) { + const role = "tool"; + const { tool_choice = "auto", stream, toolContext: inputToolContext, ...restParams } = params; + const toolContext = inputToolContext; + const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice.type === "function" && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS, afterCompletion } = options || {}; + const inputTools = params.tools.map((tool) => { + if (isAutoParsableTool$1(tool)) { + if (!tool.$callback) throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function"); + return { + type: "function", + function: { + function: tool.$callback, + name: tool.function.name, + description: tool.function.description || "", + parameters: tool.function.parameters, + parse: tool.$parseRaw, + strict: true + } + }; + } + return tool; + }); + const functionsByName = {}; + for (const f of inputTools) if (f.type === "function") functionsByName[f.function.name || f.function.function.name] = f.function; + const tools = "tools" in params ? inputTools.map((t) => t.type === "function" ? { + type: "function", + function: { + name: t.function.name || t.function.function.name, + parameters: t.function.parameters, + description: t.function.description, + strict: t.function.strict + } + } : t) : void 0; + for (const message of params.messages) this._addMessage(message, false); + const runToolCall = async (toolCall) => { + if (toolCall.type !== "function") return { + message: void 0, + functionCalled: false + }; + const tool_call_id = toolCall.id; + const { name, arguments: args } = toolCall.function; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name) => JSON.stringify(name)).join(", ")}. Please try again`; + return { + message: { + role, + tool_call_id, + content + }, + functionCalled: false + }; + } + if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + return { + message: { + role, + tool_call_id, + content + }, + functionCalled: false + }; + } + let rawContent; + if (isRunnableFunctionWithParse(fn)) { + let parsed; + try { + parsed = await fn.parse(args); + } catch (error) { + const content = error instanceof Error ? error.message : String(error); + return { + message: { + role, + tool_call_id, + content + }, + functionCalled: false + }; + } + rawContent = await fn.function(parsed, runner, toolContext); + } else rawContent = await fn.function(args, runner, toolContext); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + return { + message: { + role, + tool_call_id, + content + }, + functionCalled: true + }; + }; + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(client, { + ...restParams, + tool_choice, + tools, + messages: this.messages.map(toRequestMessage) + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) throw new OpenAIError(`missing message in ChatCompletion response`); + if (!message.tool_calls?.length) { + await afterCompletion?.(chatCompletion, runner); + return; + } + if (singleFunctionToCall || params.parallel_tool_calls === false) for (const toolCall of message.tool_calls) { + const result = await runToolCall(toolCall); + if (result.message) this._addMessage(result.message); + if (singleFunctionToCall && result.functionCalled) { + await afterCompletion?.(chatCompletion, runner); + return; + } + } + else { + const results = await Promise.allSettled(message.tool_calls.map(runToolCall)); + for (const result of results) if (result.status === "rejected") throw result.reason; + for (const result of results) if (result.status === "fulfilled" && result.value.message) this._addMessage(result.value.message); + } + await afterCompletion?.(chatCompletion, runner); + } + } +}; +_AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; +}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { + let i = this.messages.length; + while (i-- > 0) { + const message = this.messages[i]; + if (isAssistantMessage(message)) return { + ...message, + content: message.content ?? null, + refusal: message.refusal ?? null + }; + } + throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant"); +}, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isAssistantMessage(message) && message?.tool_calls?.length) for (let j = message.tool_calls.length - 1; j >= 0; j--) { + const toolCall = message.tool_calls[j]; + if (toolCall?.type === "function") return toolCall.function; + } + } +}, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isToolMessage(message) && message.content != null && typeof message.content === "string" && this.messages.some((x) => x.role === "assistant" && x.tool_calls?.some((y) => y.type === "function" && y.id === message.tool_call_id))) return message.content; + } +}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { + 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_validateParams(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_stringifyFunctionCallResult(rawContent) { + return typeof rawContent === "string" ? rawContent : rawContent === void 0 ? "undefined" : JSON.stringify(rawContent); +}; +//#endregion +//#region node_modules/openai/lib/ChatCompletionRunner.mjs +var ChatCompletionRunner = class ChatCompletionRunner extends AbstractChatCompletionRunner { + static runTools(client, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { + ...options?.headers, + "X-Stainless-Helper-Method": "runTools" + } + }; + runner._run(() => runner._runTools(client, params, runner, opts)); + return runner; + } + _addMessage(message, emit = true) { + super._addMessage(message, emit); + if (isAssistantMessage(message) && message.content) this._emit("content", message.content); + } +}; +//#endregion +//#region node_modules/openai/_vendor/partial-json-parser/parser.mjs +var Allow = { + STR: 1, + NUM: 2, + ARR: 4, + OBJ: 8, + NULL: 16, + BOOL: 32, + NAN: 64, + INFINITY: 128, + MINUS_INFINITY: 256, + INF: 384, + SPECIAL: 496, + ATOM: 499, + COLLECTION: 12, + ALL: 511 +}; +var PartialJSON = class extends Error {}; +var MalformedJSON = class extends Error {}; +/** +* Parse incomplete JSON +* @param {string} jsonString Partial JSON to be parsed +* @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details +* @returns The parsed JSON +* @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) +* @throws {MalformedJSON} If the JSON is malformed +*/ +function parseJSON(jsonString, allowPartial = Allow.ALL) { + if (typeof jsonString !== "string") throw new TypeError(`expecting str, got ${typeof jsonString}`); + if (!jsonString.trim()) throw new Error(`${jsonString} is empty`); + return _parseJSON(jsonString.trim(), allowPartial); +} +var _parseJSON = (jsonString, allow) => { + const length = jsonString.length; + let index = 0; + const markPartialJSON = (msg) => { + throw new PartialJSON(`${msg} at position ${index}`); + }; + const throwMalformedError = (msg) => { + throw new MalformedJSON(`${msg} at position ${index}`); + }; + const parseAny = () => { + skipBlank(); + if (index >= length) markPartialJSON("Unexpected end of input"); + if (jsonString[index] === "\"") return parseStr(); + if (jsonString[index] === "{") return parseObj(); + if (jsonString[index] === "[") return parseArr(); + if (jsonString.substring(index, index + 4) === "null" || Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) { + index += 4; + return null; + } + if (jsonString.substring(index, index + 4) === "true" || Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) { + index += 4; + return true; + } + if (jsonString.substring(index, index + 5) === "false" || Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) { + index += 5; + return false; + } + if (jsonString.substring(index, index + 8) === "Infinity" || Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) { + index += 8; + return Infinity; + } + if (jsonString.substring(index, index + 9) === "-Infinity" || Allow.MINUS_INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) { + index += 9; + return -Infinity; + } + if (jsonString.substring(index, index + 3) === "NaN" || Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) { + index += 3; + return NaN; + } + return parseNum(); + }; + const parseStr = () => { + const start = index; + let escape = false; + index++; + while (index < length && (jsonString[index] !== "\"" || escape && jsonString[index - 1] === "\\")) { + escape = jsonString[index] === "\\" ? !escape : false; + index++; + } + if (jsonString.charAt(index) == "\"") try { + return JSON.parse(jsonString.substring(start, ++index - Number(escape))); + } catch (e) { + throwMalformedError(String(e)); + } + else if (Allow.STR & allow) try { + return JSON.parse(jsonString.substring(start, index - Number(escape)) + "\""); + } catch (e) { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + "\""); + } + markPartialJSON("Unterminated string literal"); + }; + const parseObj = () => { + index++; + skipBlank(); + const obj = {}; + try { + while (jsonString[index] !== "}") { + skipBlank(); + if (index >= length && Allow.OBJ & allow) return obj; + const key = parseStr(); + skipBlank(); + index++; + try { + const value = parseAny(); + Object.defineProperty(obj, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } catch (e) { + if (Allow.OBJ & allow) return obj; + else throw e; + } + skipBlank(); + if (jsonString[index] === ",") index++; + } + } catch (e) { + if (Allow.OBJ & allow) return obj; + else markPartialJSON("Expected '}' at end of object"); + } + index++; + return obj; + }; + const parseArr = () => { + index++; + const arr = []; + try { + while (jsonString[index] !== "]") { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index] === ",") index++; + } + } catch (e) { + if (Allow.ARR & allow) return arr; + markPartialJSON("Expected ']' at end of array"); + } + index++; + return arr; + }; + const parseNum = () => { + if (index === 0) { + if (jsonString === "-" && Allow.NUM & allow) markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } catch (e) { + if (Allow.NUM & allow) try { + if ("." === jsonString[jsonString.length - 1]) return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("."))); + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e"))); + } catch (e) {} + throwMalformedError(String(e)); + } + } + const start = index; + if (jsonString[index] === "-") index++; + while (jsonString[index] && !",]}".includes(jsonString[index])) index++; + if (index == length && !(Allow.NUM & allow)) markPartialJSON("Unterminated number literal"); + try { + return JSON.parse(jsonString.substring(start, index)); + } catch (e) { + if (jsonString.substring(start, index) === "-" && Allow.NUM & allow) markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e"))); + } catch (e) { + throwMalformedError(String(e)); + } + } + }; + const skipBlank = () => { + while (index < length && " \n\r ".includes(jsonString[index])) index++; + }; + return parseAny(); +}; +var partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); +//#endregion +//#region node_modules/openai/lib/ChatCompletionStream.mjs +var _ChatCompletionStream_instances; +var _ChatCompletionStream_params; +var _ChatCompletionStream_audioDoneChoiceIndexes; +var _ChatCompletionStream_choiceEventStates; +var _ChatCompletionStream_currentChatCompletionSnapshot; +var _ChatCompletionStream_beginRequest; +var _ChatCompletionStream_getChoiceEventState; +var _ChatCompletionStream_addChunk; +var _ChatCompletionStream_emitToolCallDoneEvent; +var _ChatCompletionStream_emitContentDoneEvents; +var _ChatCompletionStream_endRequest; +var _ChatCompletionStream_getAutoParseableResponseFormat; +var _ChatCompletionStream_accumulateChatCompletion; +var CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX = "chat.completion.chunk.message:"; +function makeChatCompletionReadableStreamMessageChunk(chunk, message, toolCallIds) { + const payload = { + type: "message", + message, + ...toolCallIds ? { tool_call_ids: toolCallIds } : {} + }; + return { + id: chunk.id, + choices: [], + created: chunk.created, + model: chunk.model, + object: `${CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX}${JSON.stringify(payload)}` + }; +} +function isChatCompletionReadableStreamMessage(item) { + return "type" in item && item.type === "message" && "message" in item || "object" in item && typeof item.object === "string" && item.object.startsWith(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX); +} +function getChatCompletionReadableStreamMessage(item) { + if ("type" in item) return item; + return JSON.parse(item.object.slice(30)); +} +var ChatCompletionStream = class ChatCompletionStream extends AbstractChatCompletionRunner { + constructor(params) { + super(); + _ChatCompletionStream_instances.add(this); + _ChatCompletionStream_params.set(this, void 0); + _ChatCompletionStream_audioDoneChoiceIndexes.set(this, void 0); + _ChatCompletionStream_choiceEventStates.set(this, void 0); + _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); + __classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, /* @__PURE__ */ new Set(), "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); + } + get currentChatCompletionSnapshot() { + return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new ChatCompletionStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createChatCompletion(client, params, options) { + const runner = new ChatCompletionStream(params); + runner._run(() => runner._runChatCompletion(client, { + ...params, + stream: true + }, { + ...options, + headers: { + ...options?.headers, + "X-Stainless-Helper-Method": "stream" + } + })); + return runner; + } + async _createChatCompletion(client, params, options) { + super._createChatCompletion; + this._listenForAbort(options?.signal); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + const stream = await client.chat.completions.create({ + ...params, + stream: true + }, { + ...options, + signal: this.controller.signal + }); + this._connected(); + for await (const chunk of stream) __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + async _fromReadableStream(readableStream, options) { + this._listenForAbort(options?.signal); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const item of stream) { + if (isChatCompletionReadableStreamMessage(item)) { + const message = getChatCompletionReadableStreamMessage(item); + if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) { + const toolCalls = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f").choices[0]?.message.tool_calls; + for (const [index, id] of message.tool_call_ids?.entries() ?? []) { + const toolCall = toolCalls?.[index]; + if (toolCall && id) toolCall.id = id; + } + this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + chatId = void 0; + } + this._addMessage(message.message); + continue; + } + const chunk = item; + if (chatId && chunk.id && chatId !== chunk.id) this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + if (chunk.id) chatId = chunk.id; + } + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + const lastChatCompletion = this._chatCompletions[this._chatCompletions.length - 1]; + if (lastChatCompletion) return lastChatCompletion; + throw new OpenAIError(`request ended without sending any chunks`); + } + [(_ChatCompletionStream_params = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_audioDoneChoiceIndexes = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_choiceEventStates = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { + if (this.ended) return; + __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, /* @__PURE__ */ new Set(), "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f"); + }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) { + let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; + if (state) return state; + state = { + content_done: false, + refusal_done: false, + logprobs_content_done: false, + logprobs_refusal_done: false, + done_tool_calls: /* @__PURE__ */ new Set(), + current_tool_call_index: null + }; + __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; + return state; + }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { + if (this.ended) return; + const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); + this._emit("chunk", chunk, completion); + for (const choice of chunk.choices) { + const choiceSnapshot = completion.choices[choice.index]; + const { delta } = choice; + if (delta?.content != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.content) { + this._emit("content", delta.content, choiceSnapshot.message.content); + this._emit("content.delta", { + delta: delta.content, + snapshot: choiceSnapshot.message.content, + parsed: choiceSnapshot.message.parsed + }); + } + if (delta?.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) this._emit("refusal.delta", { + delta: delta.refusal, + snapshot: choiceSnapshot.message.refusal + }); + if (choice.logprobs?.content != null && choiceSnapshot.message?.role === "assistant") this._emit("logprobs.content.delta", { + content: choice.logprobs?.content, + snapshot: choiceSnapshot.logprobs?.content ?? [] + }); + if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === "assistant") this._emit("logprobs.refusal.delta", { + refusal: choice.logprobs?.refusal, + snapshot: choiceSnapshot.logprobs?.refusal ?? [] + }); + const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (choiceSnapshot.finish_reason) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + if (state.current_tool_call_index != null) __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + } + for (const toolCall of delta?.tool_calls ?? []) { + if (state.current_tool_call_index !== toolCall.index) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + if (state.current_tool_call_index != null) __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + } + state.current_tool_call_index = toolCall.index; + } + for (const toolCallDelta of delta?.tool_calls ?? []) { + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index]; + if (!toolCallSnapshot?.type) continue; + if (toolCallSnapshot?.type === "function") this._emit("tool_calls.function.arguments.delta", { + name: toolCallSnapshot.function?.name, + index: toolCallDelta.index, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: toolCallSnapshot.function.parsed_arguments, + arguments_delta: toolCallDelta.function?.arguments ?? "" + }); + else toolCallSnapshot?.type; + } + } + }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) { + if (__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot).done_tool_calls.has(toolCallIndex)) return; + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex]; + if (!toolCallSnapshot) throw new Error("no tool call snapshot"); + if (!toolCallSnapshot.type) throw new Error("tool call snapshot missing `type`"); + if (toolCallSnapshot.type === "function") { + const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name); + this._emit("tool_calls.function.arguments.done", { + name: toolCallSnapshot.function.name, + index: toolCallIndex, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: isAutoParsableTool$1(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) : null + }); + } else toolCallSnapshot.type; + }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) { + const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (choiceSnapshot.message.content && !state.content_done) { + state.content_done = true; + const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); + this._emit("content.done", { + content: choiceSnapshot.message.content, + parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null + }); + } + if (choiceSnapshot.message.refusal && !state.refusal_done) { + state.refusal_done = true; + this._emit("refusal.done", { refusal: choiceSnapshot.message.refusal }); + } + if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) { + state.logprobs_content_done = true; + this._emit("logprobs.content.done", { content: choiceSnapshot.logprobs.content }); + } + if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) { + state.logprobs_refusal_done = true; + this._emit("logprobs.refusal.done", { refusal: choiceSnapshot.logprobs.refusal }); + } + }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { + if (this.ended) throw new OpenAIError(`stream has ended, this shouldn't happen`); + const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + if (!snapshot) throw new OpenAIError(`request ended without sending any chunks`); + const audioDoneChoiceIndexes = __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, /* @__PURE__ */ new Set(), "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); + return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), audioDoneChoiceIndexes); + }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() { + const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format; + if (isAutoParsableResponseFormat(responseFormat)) return responseFormat; + return null; + }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { + var _a, _b, _c, _d, _e; + let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + const { choices, ...rest } = chunk; + if (!snapshot) snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { + ...rest, + choices: [] + }, "f"); + else if (chunk.id) Object.assign(snapshot, rest); + for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index]; + if (!choice) choice = snapshot.choices[index] = { + finish_reason, + index, + message: {}, + logprobs, + ...other + }; + if (logprobs) if (!choice.logprobs) choice.logprobs = Object.assign({}, logprobs); + else { + const { content, refusal, ...rest } = logprobs; + Object.assign(choice.logprobs, rest); + if (content) { + (_a = choice.logprobs).content ?? (_a.content = []); + choice.logprobs.content.push(...content); + } + if (refusal) { + (_b = choice.logprobs).refusal ?? (_b.refusal = []); + choice.logprobs.refusal.push(...refusal); + } + } + if (finish_reason) { + choice.finish_reason = finish_reason; + if (__classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput$1(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) { + if (finish_reason === "length") throw new LengthFinishReasonError(); + if (finish_reason === "content_filter") throw new ContentFilterFinishReasonError(); + } + } + Object.assign(choice, other); + if (!delta) continue; + __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").delete(index); + const { audio, content, refusal, function_call, role, tool_calls, ...rest } = delta; + Object.assign(choice.message, rest); + if (audio?.expires_at != null && audio.id == null && audio.data == null && audio.transcript == null && content == null && refusal == null && function_call == null && role == null && tool_calls == null && Object.keys(rest).length === 0) __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").add(index); + if (refusal) choice.message.refusal = (choice.message.refusal || "") + refusal; + if (role) choice.message.role = role; + if (audio) { + const audioSnapshot = (_c = choice.message).audio ?? (_c.audio = {}); + if (audio.id != null) audioSnapshot.id = audio.id; + if (audio.data != null) audioSnapshot.data = (audioSnapshot.data ?? "") + audio.data; + if (audio.transcript != null) audioSnapshot.transcript = (audioSnapshot.transcript ?? "") + audio.transcript; + if (audio.expires_at != null) audioSnapshot.expires_at = audio.expires_at; + } + 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) { + (_d = choice.message.function_call).arguments ?? (_d.arguments = ""); + choice.message.function_call.arguments += function_call.arguments; + } + } + if (content) { + choice.message.content = (choice.message.content || "") + content; + if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) choice.message.parsed = choice.message.content.trim() ? partialParse(choice.message.content) : null; + } + if (tool_calls) { + if (!choice.message.tool_calls) choice.message.tool_calls = []; + for (const { index, id, type, function: fn, ...rest } of tool_calls) { + const tool_call = (_e = choice.message.tool_calls)[index] ?? (_e[index] = {}); + Object.assign(tool_call, rest); + if (id) tool_call.id = id; + if (type) tool_call.type = type; + if (fn) tool_call.function ?? (tool_call.function = { + name: fn.name ?? "", + arguments: "" + }); + if (fn?.name) tool_call.function.name = fn.name; + if (fn?.arguments) { + tool_call.function.arguments += fn.arguments; + if (shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) tool_call.function.parsed_arguments = partialParse(tool_call.function.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((chunk) => chunk ? { + value: chunk, + done: false + } : { + value: void 0, + done: true + }); + } + return { + value: pushQueue.shift(), + done: false + }; + }, + return: async () => { + this.abort(); + return { + value: void 0, + done: true + }; + } + }; + } + toReadableStream() { + return new Stream(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream(); + } +}; +function finalizeChatCompletion(snapshot, params, audioDoneChoiceIndexes) { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + return maybeParseChatCompletion({ + ...rest, + id, + choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { + const { content = null, function_call, tool_calls, audio, ...messageRest } = message; + const finishReason = finish_reason ?? (audioDoneChoiceIndexes.has(index) && isCompleteAudio(audio) ? "stop" : null); + if (!finishReason) throw new OpenAIError(`missing finish_reason for choice ${index}`); + const audioResponse = audio ? { audio } : {}; + const role = message.role; + if (!role) throw new OpenAIError(`missing role for choice ${index}`); + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) throw new OpenAIError(`missing function_call.arguments for choice ${index}`); + if (!name) throw new OpenAIError(`missing function_call.name for choice ${index}`); + return { + ...choiceRest, + message: { + ...audioResponse, + content, + function_call: { + arguments: args, + name + }, + role, + refusal: message.refusal ?? null + }, + finish_reason: finishReason, + index, + logprobs + }; + } + if (tool_calls) return { + ...choiceRest, + index, + finish_reason: finishReason, + logprobs, + message: { + ...messageRest, + ...audioResponse, + role, + content, + refusal: message.refusal ?? null, + tool_calls: tool_calls.map((tool_call, i) => { + const { function: fn, type, id, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (type == null) throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); + if (name == null) throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); + if (args == null) throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); + return { + ...toolRest, + id: id || `call_${uuid4()}`, + type, + function: { + ...fnRest, + name, + arguments: args + } + }; + }) + } + }; + return { + ...choiceRest, + message: { + ...messageRest, + ...audioResponse, + content, + role, + refusal: message.refusal ?? null + }, + finish_reason: finishReason, + index, + logprobs + }; + }), + created, + model, + object: "chat.completion", + ...system_fingerprint ? { system_fingerprint } : {} + }, params); +} +function isCompleteAudio(audio) { + return audio?.id != null && audio.data != null && audio.transcript != null && audio.expires_at != null; +} +function str(x) { + return JSON.stringify(x); +} +//#endregion +//#region node_modules/openai/lib/ChatCompletionStreamingRunner.mjs +var ChatCompletionStreamingRunner = class ChatCompletionStreamingRunner extends ChatCompletionStream { + static fromReadableStream(stream) { + const runner = new ChatCompletionStreamingRunner(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + toReadableStream() { + const pushQueue = []; + const readQueue = []; + let done = false; + let lastChunk; + let toolCallIds; + const pushEvent = (event) => { + const reader = readQueue.shift(); + if (reader) reader.resolve(event); + else pushQueue.push(event); + }; + this.on("chunk", (chunk) => { + lastChunk = chunk; + pushEvent(chunk); + }); + this.on("message", (message) => { + if (isAssistantMessage(message)) { + toolCallIds = message.tool_calls?.map((toolCall) => toolCall.id); + return; + } + if (isToolMessage(message)) { + if (!lastChunk) throw new OpenAIError("cannot serialize a tool message before receiving any chunks"); + pushEvent(makeChatCompletionReadableStreamMessageChunk(lastChunk, message, toolCallIds)); + } + }); + 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; + }); + const iterator = () => ({ + next: async () => { + if (!pushQueue.length) { + if (done) return { + value: void 0, + done: true + }; + return new Promise((resolve, reject) => readQueue.push({ + resolve, + reject + })).then((event) => event ? { + value: event, + done: false + } : { + value: void 0, + done: true + }); + } + const event = pushQueue.shift(); + if (!event) return { + value: void 0, + done: true + }; + return { + value: event, + done: false + }; + }, + return: async () => { + this.abort(); + return { + value: void 0, + done: true + }; + } + }); + return new Stream(iterator, this.controller).toReadableStream(); + } + static runTools(client, params, options) { + const runner = new ChatCompletionStreamingRunner(params); + const opts = { + ...options, + headers: { + ...options?.headers, + "X-Stainless-Helper-Method": "runTools" + } + }; + runner._run(() => runner._runTools(client, params, runner, opts)); + return runner; + } +}; +//#endregion +//#region node_modules/openai/resources/chat/completions/completions.mjs +/** +* Given a list of messages comprising a conversation, the model will return a response. +*/ +var Completions$1 = class extends APIResource { + constructor() { + super(...arguments); + this.messages = new Messages$1(this._client); + } + create(body, options) { + return this._client.post("/chat/completions", { + body, + ...options, + stream: body.stream ?? false, + __security: { bearerAuth: true } + }); + } + /** + * Get a stored chat completion. Only Chat Completions that have been created with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * const chatCompletion = + * await client.chat.completions.retrieve('completion_id'); + * ``` + */ + retrieve(completionID, options) { + return this._client.get(path`/chat/completions/${completionID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Modify a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be modified. Currently, the only + * supported modification is to update the `metadata` field. + * + * @example + * ```ts + * const chatCompletion = await client.chat.completions.update( + * 'completion_id', + * { metadata: { foo: 'string' } }, + * ); + * ``` + */ + update(completionID, body, options) { + return this._client.post(path`/chat/completions/${completionID}`, { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List stored Chat Completions. Only Chat Completions that have been stored with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletion of client.chat.completions.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/chat/completions", CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be deleted. + * + * @example + * ```ts + * const chatCompletionDeleted = + * await client.chat.completions.delete('completion_id'); + * ``` + */ + delete(completionID, options) { + return this._client.delete(path`/chat/completions/${completionID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + parse(body, options) { + validateInputTools(body.tools); + return this._client.chat.completions.create(body, { + ...options, + headers: { + ...options?.headers, + "X-Stainless-Helper-Method": "chat.completions.parse" + } + })._thenUnwrap((completion) => parseChatCompletion(completion, body)); + } + runTools(body, options) { + if (body.stream) return ChatCompletionStreamingRunner.runTools(this._client, body, options); + return ChatCompletionRunner.runTools(this._client, body, options); + } + /** + * Creates a chat completion stream + */ + stream(body, options) { + return ChatCompletionStream.createChatCompletion(this._client, body, options); + } +}; +Completions$1.Messages = Messages$1; +//#endregion +//#region node_modules/openai/resources/chat/chat.mjs +var Chat = class extends APIResource { + constructor() { + super(...arguments); + this.completions = new Completions$1(this._client); + } +}; +Chat.Completions = Completions$1; +//#endregion +//#region node_modules/openai/resources/admin/organization/admin-api-keys.mjs +var AdminAPIKeys = class extends APIResource { + /** + * Create an organization admin API key + * + * @example + * ```ts + * const adminAPIKey = + * await client.admin.organization.adminAPIKeys.create({ + * name: 'New Admin Key', + * }); + * ``` + */ + create(body, options) { + return this._client.post("/organization/admin_api_keys", { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieve a single organization API key + * + * @example + * ```ts + * const adminAPIKey = + * await client.admin.organization.adminAPIKeys.retrieve( + * 'key_id', + * ); + * ``` + */ + retrieve(keyID, options) { + return this._client.get(path`/organization/admin_api_keys/${keyID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * List organization API keys + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const adminAPIKey of client.admin.organization.adminAPIKeys.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/organization/admin_api_keys", CursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Delete an organization admin API key + * + * @example + * ```ts + * const adminAPIKey = + * await client.admin.organization.adminAPIKeys.delete( + * 'key_id', + * ); + * ``` + */ + delete(keyID, options) { + return this._client.delete(path`/organization/admin_api_keys/${keyID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/audit-logs.mjs +/** +* List user actions and configuration changes within this organization. +*/ +var AuditLogs = class extends APIResource { + /** + * List user actions and configuration changes within this organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const auditLogListResponse of client.admin.organization.auditLogs.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/organization/audit_logs", ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/certificates.mjs +var Certificates$1 = class extends APIResource { + /** + * Upload a certificate to the organization. This does **not** automatically + * activate the certificate. + * + * Organizations can upload up to 50 certificates. + * + * @example + * ```ts + * const certificate = + * await client.admin.organization.certificates.create({ + * certificate: 'certificate', + * }); + * ``` + */ + create(body, options) { + return this._client.post("/organization/certificates", { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get a certificate that has been uploaded to the organization. + * + * You can get a certificate regardless of whether it is active or not. + * + * @example + * ```ts + * const certificate = + * await client.admin.organization.certificates.retrieve( + * 'certificate_id', + * ); + * ``` + */ + retrieve(certificateID, query = {}, options) { + return this._client.get(path`/organization/certificates/${certificateID}`, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Modify a certificate. Note that only the name can be modified. + * + * @example + * ```ts + * const certificate = + * await client.admin.organization.certificates.update( + * 'certificate_id', + * ); + * ``` + */ + update(certificateID, body, options) { + return this._client.post(path`/organization/certificates/${certificateID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * List uploaded certificates for this organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const certificateListResponse of client.admin.organization.certificates.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/organization/certificates", ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Delete a certificate from the organization. + * + * The certificate must be inactive for the organization and all projects. + * + * @example + * ```ts + * const certificate = + * await client.admin.organization.certificates.delete( + * 'certificate_id', + * ); + * ``` + */ + delete(certificateID, options) { + return this._client.delete(path`/organization/certificates/${certificateID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Activate certificates at the organization level. + * + * You can atomically and idempotently activate up to 10 certificates at a time. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const certificateActivateResponse of client.admin.organization.certificates.activate( + * { certificate_ids: ['cert_abc'] }, + * )) { + * // ... + * } + * ``` + */ + activate(body, options) { + return this._client.getAPIList("/organization/certificates/activate", Page, { + body, + method: "post", + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deactivate certificates at the organization level. + * + * You can atomically and idempotently deactivate up to 10 certificates at a time. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const certificateDeactivateResponse of client.admin.organization.certificates.deactivate( + * { certificate_ids: ['cert_abc'] }, + * )) { + * // ... + * } + * ``` + */ + deactivate(body, options) { + return this._client.getAPIList("/organization/certificates/deactivate", Page, { + body, + method: "post", + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/data-retention.mjs +var DataRetention$1 = class extends APIResource { + /** + * Retrieves organization data retention controls. + * + * @example + * ```ts + * const organizationDataRetention = + * await client.admin.organization.dataRetention.retrieve(); + * ``` + */ + retrieve(options) { + return this._client.get("/organization/data_retention", { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates organization data retention controls. + * + * @example + * ```ts + * const organizationDataRetention = + * await client.admin.organization.dataRetention.update({ + * retention_type: 'zero_data_retention', + * }); + * ``` + */ + update(body, options) { + return this._client.post("/organization/data_retention", { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/invites.mjs +var Invites = class extends APIResource { + /** + * Create an invite for a user to the organization. The invite must be accepted by + * the user before they have access to the organization. + * + * @example + * ```ts + * const invite = + * await client.admin.organization.invites.create({ + * email: 'email', + * role: 'reader', + * }); + * ``` + */ + create(body, options) { + return this._client.post("/organization/invites", { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves an invite. + * + * @example + * ```ts + * const invite = + * await client.admin.organization.invites.retrieve( + * 'invite_id', + * ); + * ``` + */ + retrieve(inviteID, options) { + return this._client.get(path`/organization/invites/${inviteID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Returns a list of invites in the organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const invite of client.admin.organization.invites.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/organization/invites", ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Delete an invite. If the invite has already been accepted, it cannot be deleted. + * + * @example + * ```ts + * const invite = + * await client.admin.organization.invites.delete( + * 'invite_id', + * ); + * ``` + */ + delete(inviteID, options) { + return this._client.delete(path`/organization/invites/${inviteID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/roles.mjs +var Roles$5 = class extends APIResource { + /** + * Creates a custom role for the organization. + * + * @example + * ```ts + * const role = await client.admin.organization.roles.create({ + * permissions: ['string'], + * role_name: 'role_name', + * }); + * ``` + */ + create(body, options) { + return this._client.post("/organization/roles", { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves an organization role. + * + * @example + * ```ts + * const role = await client.admin.organization.roles.retrieve( + * 'role_id', + * ); + * ``` + */ + retrieve(roleID, options) { + return this._client.get(path`/organization/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates an existing organization role. + * + * @example + * ```ts + * const role = await client.admin.organization.roles.update( + * 'role_id', + * ); + * ``` + */ + update(roleID, body, options) { + return this._client.post(path`/organization/roles/${roleID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists the roles configured for the organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const role of client.admin.organization.roles.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/organization/roles", NextCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes a custom role from the organization. + * + * @example + * ```ts + * const role = await client.admin.organization.roles.delete( + * 'role_id', + * ); + * ``` + */ + delete(roleID, options) { + return this._client.delete(path`/organization/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/spend-alerts.mjs +var SpendAlerts$1 = class extends APIResource { + /** + * Creates an organization spend alert. + * + * @example + * ```ts + * const organizationSpendAlert = + * await client.admin.organization.spendAlerts.create({ + * currency: 'USD', + * interval: 'month', + * notification_channel: { + * recipients: ['string'], + * type: 'email', + * }, + * threshold_amount: 0, + * }); + * ``` + */ + create(body, options) { + return this._client.post("/organization/spend_alerts", { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves an organization spend alert. + * + * @example + * ```ts + * const organizationSpendAlert = + * await client.admin.organization.spendAlerts.retrieve( + * 'alert_id', + * ); + * ``` + */ + retrieve(alertID, options) { + return this._client.get(path`/organization/spend_alerts/${alertID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates an organization spend alert. + * + * @example + * ```ts + * const organizationSpendAlert = + * await client.admin.organization.spendAlerts.update( + * 'alert_id', + * { + * currency: 'USD', + * interval: 'month', + * notification_channel: { + * recipients: ['string'], + * type: 'email', + * }, + * threshold_amount: 0, + * }, + * ); + * ``` + */ + update(alertID, body, options) { + return this._client.post(path`/organization/spend_alerts/${alertID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists organization spend alerts. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const organizationSpendAlert of client.admin.organization.spendAlerts.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/organization/spend_alerts", ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes an organization spend alert. + * + * @example + * ```ts + * const organizationSpendAlertDeleted = + * await client.admin.organization.spendAlerts.delete( + * 'alert_id', + * ); + * ``` + */ + delete(alertID, options) { + return this._client.delete(path`/organization/spend_alerts/${alertID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/spend-limit.mjs +var SpendLimit$1 = class extends APIResource { + /** + * Get the organization's hard spend limit. + * + * @example + * ```ts + * const organizationSpendLimit = + * await client.admin.organization.spendLimit.retrieve(); + * ``` + */ + retrieve(options) { + return this._client.get("/organization/spend_limit", { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Create or replace the organization's hard spend limit. + * + * @example + * ```ts + * const organizationSpendLimit = + * await client.admin.organization.spendLimit.update({ + * currency: 'USD', + * interval: 'month', + * threshold_amount: 1, + * }); + * ``` + */ + update(body, options) { + return this._client.post("/organization/spend_limit", { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Delete the organization's hard spend limit. + * + * @example + * ```ts + * const organizationSpendLimitDeleted = + * await client.admin.organization.spendLimit.delete(); + * ``` + */ + delete(options) { + return this._client.delete("/organization/spend_limit", { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/usage.mjs +var Usage = class extends APIResource { + /** + * Get audio speeches usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.audioSpeeches({ + * start_time: 0, + * }); + * ``` + */ + audioSpeeches(query, options) { + return this._client.get("/organization/usage/audio_speeches", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get audio transcriptions usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.audioTranscriptions( + * { start_time: 0 }, + * ); + * ``` + */ + audioTranscriptions(query, options) { + return this._client.get("/organization/usage/audio_transcriptions", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get code interpreter sessions usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.codeInterpreterSessions( + * { start_time: 0 }, + * ); + * ``` + */ + codeInterpreterSessions(query, options) { + return this._client.get("/organization/usage/code_interpreter_sessions", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get completions usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.completions({ + * start_time: 0, + * }); + * ``` + */ + completions(query, options) { + return this._client.get("/organization/usage/completions", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get costs details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.costs({ + * start_time: 0, + * }); + * ``` + */ + costs(query, options) { + return this._client.get("/organization/costs", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get embeddings usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.embeddings({ + * start_time: 0, + * }); + * ``` + */ + embeddings(query, options) { + return this._client.get("/organization/usage/embeddings", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get file search calls usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.fileSearchCalls({ + * start_time: 0, + * }); + * ``` + */ + fileSearchCalls(query, options) { + return this._client.get("/organization/usage/file_search_calls", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get images usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.images({ + * start_time: 0, + * }); + * ``` + */ + images(query, options) { + return this._client.get("/organization/usage/images", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get moderations usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.moderations({ + * start_time: 0, + * }); + * ``` + */ + moderations(query, options) { + return this._client.get("/organization/usage/moderations", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get vector stores usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.vectorStores({ + * start_time: 0, + * }); + * ``` + */ + vectorStores(query, options) { + return this._client.get("/organization/usage/vector_stores", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Get web search calls usage details for the organization. + * + * @example + * ```ts + * const response = + * await client.admin.organization.usage.webSearchCalls({ + * start_time: 0, + * }); + * ``` + */ + webSearchCalls(query, options) { + return this._client.get("/organization/usage/web_search_calls", { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/groups/roles.mjs +var Roles$4 = class extends APIResource { + /** + * Assigns an organization role to a group within the organization. + * + * @example + * ```ts + * const role = + * await client.admin.organization.groups.roles.create( + * 'group_id', + * { role_id: 'role_id' }, + * ); + * ``` + */ + create(groupID, body, options) { + return this._client.post(path`/organization/groups/${groupID}/roles`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves an organization role assigned to a group. + * + * @example + * ```ts + * const role = + * await client.admin.organization.groups.roles.retrieve( + * 'role_id', + * { group_id: 'group_id' }, + * ); + * ``` + */ + retrieve(roleID, params, options) { + const { group_id } = params; + return this._client.get(path`/organization/groups/${group_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists the organization roles assigned to a group within the organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const roleListResponse of client.admin.organization.groups.roles.list( + * 'group_id', + * )) { + * // ... + * } + * ``` + */ + list(groupID, query = {}, options) { + return this._client.getAPIList(path`/organization/groups/${groupID}/roles`, NextCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Unassigns an organization role from a group within the organization. + * + * @example + * ```ts + * const role = + * await client.admin.organization.groups.roles.delete( + * 'role_id', + * { group_id: 'group_id' }, + * ); + * ``` + */ + delete(roleID, params, options) { + const { group_id } = params; + return this._client.delete(path`/organization/groups/${group_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/groups/users.mjs +var Users$2 = class extends APIResource { + /** + * Adds a user to a group. + * + * @example + * ```ts + * const user = + * await client.admin.organization.groups.users.create( + * 'group_id', + * { user_id: 'user_id' }, + * ); + * ``` + */ + create(groupID, body, options) { + return this._client.post(path`/organization/groups/${groupID}/users`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a user in a group. + * + * @example + * ```ts + * const user = + * await client.admin.organization.groups.users.retrieve( + * 'user_id', + * { group_id: 'group_id' }, + * ); + * ``` + */ + retrieve(userID, params, options) { + const { group_id } = params; + return this._client.get(path`/organization/groups/${group_id}/users/${userID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists the users assigned to a group. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const organizationGroupUser of client.admin.organization.groups.users.list( + * 'group_id', + * )) { + * // ... + * } + * ``` + */ + list(groupID, query = {}, options) { + return this._client.getAPIList(path`/organization/groups/${groupID}/users`, NextCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Removes a user from a group. + * + * @example + * ```ts + * const user = + * await client.admin.organization.groups.users.delete( + * 'user_id', + * { group_id: 'group_id' }, + * ); + * ``` + */ + delete(userID, params, options) { + const { group_id } = params; + return this._client.delete(path`/organization/groups/${group_id}/users/${userID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/groups/groups.mjs +var Groups$1 = class extends APIResource { + constructor() { + super(...arguments); + this.users = new Users$2(this._client); + this.roles = new Roles$4(this._client); + } + /** + * Creates a new group in the organization. + * + * @example + * ```ts + * const group = await client.admin.organization.groups.create( + * { name: 'x' }, + * ); + * ``` + */ + create(body, options) { + return this._client.post("/organization/groups", { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a group. + * + * @example + * ```ts + * const group = + * await client.admin.organization.groups.retrieve( + * 'group_id', + * ); + * ``` + */ + retrieve(groupID, options) { + return this._client.get(path`/organization/groups/${groupID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates a group's information. + * + * @example + * ```ts + * const group = await client.admin.organization.groups.update( + * 'group_id', + * { name: 'x' }, + * ); + * ``` + */ + update(groupID, body, options) { + return this._client.post(path`/organization/groups/${groupID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists all groups in the organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const group of client.admin.organization.groups.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/organization/groups", NextCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes a group from the organization. + * + * @example + * ```ts + * const group = await client.admin.organization.groups.delete( + * 'group_id', + * ); + * ``` + */ + delete(groupID, options) { + return this._client.delete(path`/organization/groups/${groupID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +Groups$1.Users = Users$2; +Groups$1.Roles = Roles$4; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/api-keys.mjs +var APIKeys$1 = class extends APIResource { + /** + * Retrieves an API key in the project. + * + * @example + * ```ts + * const projectAPIKey = + * await client.admin.organization.projects.apiKeys.retrieve( + * 'api_key_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + retrieve(apiKeyID, params, options) { + const { project_id } = params; + return this._client.get(path`/organization/projects/${project_id}/api_keys/${apiKeyID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Returns a list of API keys in the project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const projectAPIKey of client.admin.organization.projects.apiKeys.list( + * 'project_id', + * )) { + * // ... + * } + * ``` + */ + list(projectID, query = {}, options) { + return this._client.getAPIList(path`/organization/projects/${projectID}/api_keys`, ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes an API key from the project. + * + * Returns confirmation of the key deletion, or an error if the key belonged to a + * service account. + * + * @example + * ```ts + * const apiKey = + * await client.admin.organization.projects.apiKeys.delete( + * 'api_key_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + delete(apiKeyID, params, options) { + const { project_id } = params; + return this._client.delete(path`/organization/projects/${project_id}/api_keys/${apiKeyID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/certificates.mjs +var Certificates = class extends APIResource { + /** + * List certificates for this project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const certificateListResponse of client.admin.organization.projects.certificates.list( + * 'project_id', + * )) { + * // ... + * } + * ``` + */ + list(projectID, query = {}, options) { + return this._client.getAPIList(path`/organization/projects/${projectID}/certificates`, ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Activate certificates at the project level. + * + * You can atomically and idempotently activate up to 10 certificates at a time. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const certificateActivateResponse of client.admin.organization.projects.certificates.activate( + * 'project_id', + * { certificate_ids: ['cert_abc'] }, + * )) { + * // ... + * } + * ``` + */ + activate(projectID, body, options) { + return this._client.getAPIList(path`/organization/projects/${projectID}/certificates/activate`, Page, { + body, + method: "post", + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deactivate certificates at the project level. You can atomically and + * idempotently deactivate up to 10 certificates at a time. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const certificateDeactivateResponse of client.admin.organization.projects.certificates.deactivate( + * 'project_id', + * { certificate_ids: ['cert_abc'] }, + * )) { + * // ... + * } + * ``` + */ + deactivate(projectID, body, options) { + return this._client.getAPIList(path`/organization/projects/${projectID}/certificates/deactivate`, Page, { + body, + method: "post", + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/data-retention.mjs +var DataRetention = class extends APIResource { + /** + * Retrieves project data retention controls. + * + * @example + * ```ts + * const projectDataRetention = + * await client.admin.organization.projects.dataRetention.retrieve( + * 'project_id', + * ); + * ``` + */ + retrieve(projectID, options) { + return this._client.get(path`/organization/projects/${projectID}/data_retention`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates project data retention controls. + * + * @example + * ```ts + * const projectDataRetention = + * await client.admin.organization.projects.dataRetention.update( + * 'project_id', + * { retention_type: 'organization_default' }, + * ); + * ``` + */ + update(projectID, body, options) { + return this._client.post(path`/organization/projects/${projectID}/data_retention`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs +var HostedToolPermissions = class extends APIResource { + /** + * Returns hosted tool permissions for a project. + * + * @example + * ```ts + * const projectHostedToolPermissions = + * await client.admin.organization.projects.hostedToolPermissions.retrieve( + * 'project_id', + * ); + * ``` + */ + retrieve(projectID, options) { + return this._client.get(path`/organization/projects/${projectID}/hosted_tool_permissions`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates hosted tool permissions for a project. + * + * @example + * ```ts + * const projectHostedToolPermissions = + * await client.admin.organization.projects.hostedToolPermissions.update( + * 'project_id', + * ); + * ``` + */ + update(projectID, body, options) { + return this._client.post(path`/organization/projects/${projectID}/hosted_tool_permissions`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/model-permissions.mjs +var ModelPermissions = class extends APIResource { + /** + * Returns model permissions for a project. + * + * @example + * ```ts + * const projectModelPermissions = + * await client.admin.organization.projects.modelPermissions.retrieve( + * 'project_id', + * ); + * ``` + */ + retrieve(projectID, options) { + return this._client.get(path`/organization/projects/${projectID}/model_permissions`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates model permissions for a project. + * + * @example + * ```ts + * const projectModelPermissions = + * await client.admin.organization.projects.modelPermissions.update( + * 'project_id', + * { mode: 'allow_list', model_ids: ['string'] }, + * ); + * ``` + */ + update(projectID, body, options) { + return this._client.post(path`/organization/projects/${projectID}/model_permissions`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes model permissions for a project. + * + * @example + * ```ts + * const projectModelPermissionsDeleted = + * await client.admin.organization.projects.modelPermissions.delete( + * 'project_id', + * ); + * ``` + */ + delete(projectID, options) { + return this._client.delete(path`/organization/projects/${projectID}/model_permissions`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/rate-limits.mjs +var RateLimits = class extends APIResource { + /** + * Returns the rate limits per model for a project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const projectRateLimit of client.admin.organization.projects.rateLimits.listRateLimits( + * 'project_id', + * )) { + * // ... + * } + * ``` + */ + listRateLimits(projectID, query = {}, options) { + return this._client.getAPIList(path`/organization/projects/${projectID}/rate_limits`, ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates a project rate limit. + * + * @example + * ```ts + * const projectRateLimit = + * await client.admin.organization.projects.rateLimits.updateRateLimit( + * 'rate_limit_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + updateRateLimit(rateLimitID, params, options) { + const { project_id, ...body } = params; + return this._client.post(path`/organization/projects/${project_id}/rate_limits/${rateLimitID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/roles.mjs +var Roles$3 = class extends APIResource { + /** + * Creates a custom role for a project. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.roles.create( + * 'project_id', + * { permissions: ['string'], role_name: 'role_name' }, + * ); + * ``` + */ + create(projectID, body, options) { + return this._client.post(path`/projects/${projectID}/roles`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a project role. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.roles.retrieve( + * 'role_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + retrieve(roleID, params, options) { + const { project_id } = params; + return this._client.get(path`/projects/${project_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates an existing project role. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.roles.update( + * 'role_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + update(roleID, params, options) { + const { project_id, ...body } = params; + return this._client.post(path`/projects/${project_id}/roles/${roleID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists the roles configured for a project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const role of client.admin.organization.projects.roles.list( + * 'project_id', + * )) { + * // ... + * } + * ``` + */ + list(projectID, query = {}, options) { + return this._client.getAPIList(path`/projects/${projectID}/roles`, NextCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes a custom role from a project. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.roles.delete( + * 'role_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + delete(roleID, params, options) { + const { project_id } = params; + return this._client.delete(path`/projects/${project_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs +var SpendAlerts = class extends APIResource { + /** + * Creates a project spend alert. + * + * @example + * ```ts + * const projectSpendAlert = + * await client.admin.organization.projects.spendAlerts.create( + * 'project_id', + * { + * currency: 'USD', + * interval: 'month', + * notification_channel: { + * recipients: ['string'], + * type: 'email', + * }, + * threshold_amount: 0, + * }, + * ); + * ``` + */ + create(projectID, body, options) { + return this._client.post(path`/organization/projects/${projectID}/spend_alerts`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a project spend alert. + * + * @example + * ```ts + * const projectSpendAlert = + * await client.admin.organization.projects.spendAlerts.retrieve( + * 'alert_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + retrieve(alertID, params, options) { + const { project_id } = params; + return this._client.get(path`/organization/projects/${project_id}/spend_alerts/${alertID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates a project spend alert. + * + * @example + * ```ts + * const projectSpendAlert = + * await client.admin.organization.projects.spendAlerts.update( + * 'alert_id', + * { + * project_id: 'project_id', + * currency: 'USD', + * interval: 'month', + * notification_channel: { + * recipients: ['string'], + * type: 'email', + * }, + * threshold_amount: 0, + * }, + * ); + * ``` + */ + update(alertID, params, options) { + const { project_id, ...body } = params; + return this._client.post(path`/organization/projects/${project_id}/spend_alerts/${alertID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists project spend alerts. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const projectSpendAlert of client.admin.organization.projects.spendAlerts.list( + * 'project_id', + * )) { + * // ... + * } + * ``` + */ + list(projectID, query = {}, options) { + return this._client.getAPIList(path`/organization/projects/${projectID}/spend_alerts`, ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes a project spend alert. + * + * @example + * ```ts + * const projectSpendAlertDeleted = + * await client.admin.organization.projects.spendAlerts.delete( + * 'alert_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + delete(alertID, params, options) { + const { project_id } = params; + return this._client.delete(path`/organization/projects/${project_id}/spend_alerts/${alertID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/spend-limit.mjs +var SpendLimit = class extends APIResource { + /** + * Get a project's hard spend limit. + * + * @example + * ```ts + * const projectSpendLimit = + * await client.admin.organization.projects.spendLimit.retrieve( + * 'proj_123', + * ); + * ``` + */ + retrieve(projectID, options) { + return this._client.get(path`/organization/projects/${projectID}/spend_limit`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Create or replace a project's hard spend limit. + * + * @example + * ```ts + * const projectSpendLimit = + * await client.admin.organization.projects.spendLimit.update( + * 'proj_123', + * { + * currency: 'USD', + * interval: 'month', + * threshold_amount: 1, + * }, + * ); + * ``` + */ + update(projectID, body, options) { + return this._client.post(path`/organization/projects/${projectID}/spend_limit`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Delete a project's hard spend limit. + * + * @example + * ```ts + * const projectSpendLimitDeleted = + * await client.admin.organization.projects.spendLimit.delete( + * 'proj_123', + * ); + * ``` + */ + delete(projectID, options) { + return this._client.delete(path`/organization/projects/${projectID}/spend_limit`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/groups/roles.mjs +var Roles$2 = class extends APIResource { + /** + * Assigns a project role to a group within a project. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.groups.roles.create( + * 'group_id', + * { project_id: 'project_id', role_id: 'role_id' }, + * ); + * ``` + */ + create(groupID, params, options) { + const { project_id, ...body } = params; + return this._client.post(path`/projects/${project_id}/groups/${groupID}/roles`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a project role assigned to a group. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.groups.roles.retrieve( + * 'role_id', + * { project_id: 'project_id', group_id: 'group_id' }, + * ); + * ``` + */ + retrieve(roleID, params, options) { + const { project_id, group_id } = params; + return this._client.get(path`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists the project roles assigned to a group within a project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const roleListResponse of client.admin.organization.projects.groups.roles.list( + * 'group_id', + * { project_id: 'project_id' }, + * )) { + * // ... + * } + * ``` + */ + list(groupID, params, options) { + const { project_id, ...query } = params; + return this._client.getAPIList(path`/projects/${project_id}/groups/${groupID}/roles`, NextCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Unassigns a project role from a group within a project. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.groups.roles.delete( + * 'role_id', + * { project_id: 'project_id', group_id: 'group_id' }, + * ); + * ``` + */ + delete(roleID, params, options) { + const { project_id, group_id } = params; + return this._client.delete(path`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/groups/groups.mjs +var Groups = class extends APIResource { + constructor() { + super(...arguments); + this.roles = new Roles$2(this._client); + } + /** + * Grants a group access to a project. + * + * @example + * ```ts + * const projectGroup = + * await client.admin.organization.projects.groups.create( + * 'project_id', + * { group_id: 'group_id', role: 'role' }, + * ); + * ``` + */ + create(projectID, body, options) { + return this._client.post(path`/organization/projects/${projectID}/groups`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a project's group. + * + * @example + * ```ts + * const projectGroup = + * await client.admin.organization.projects.groups.retrieve( + * 'group_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + retrieve(groupID, params, options) { + const { project_id, ...query } = params; + return this._client.get(path`/organization/projects/${project_id}/groups/${groupID}`, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists the groups that have access to a project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const projectGroup of client.admin.organization.projects.groups.list( + * 'project_id', + * )) { + * // ... + * } + * ``` + */ + list(projectID, query = {}, options) { + return this._client.getAPIList(path`/organization/projects/${projectID}/groups`, NextCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Revokes a group's access to a project. + * + * @example + * ```ts + * const group = + * await client.admin.organization.projects.groups.delete( + * 'group_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + delete(groupID, params, options) { + const { project_id } = params; + return this._client.delete(path`/organization/projects/${project_id}/groups/${groupID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +Groups.Roles = Roles$2; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/service-accounts/api-keys.mjs +var APIKeys = class extends APIResource { + /** + * Creates an API key for a service account in the project. + * + * @example + * ```ts + * const apiKey = + * await client.admin.organization.projects.serviceAccounts.apiKeys.create( + * 'service_account_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + create(serviceAccountID, params, options) { + const { project_id, ...body } = params; + return this._client.post(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}/api_keys`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/service-accounts/service-accounts.mjs +var ServiceAccounts = class extends APIResource { + constructor() { + super(...arguments); + this.apiKeys = new APIKeys(this._client); + } + /** + * Creates a new service account in the project. By default, this also returns an + * unredacted API key for the service account. + * + * @example + * ```ts + * const serviceAccount = + * await client.admin.organization.projects.serviceAccounts.create( + * 'project_id', + * { name: 'name' }, + * ); + * ``` + */ + create(projectID, body, options) { + return this._client.post(path`/organization/projects/${projectID}/service_accounts`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a service account in the project. + * + * @example + * ```ts + * const projectServiceAccount = + * await client.admin.organization.projects.serviceAccounts.retrieve( + * 'service_account_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + retrieve(serviceAccountID, params, options) { + const { project_id } = params; + return this._client.get(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Updates a service account in the project. + * + * @example + * ```ts + * const projectServiceAccount = + * await client.admin.organization.projects.serviceAccounts.update( + * 'service_account_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + update(serviceAccountID, params, options) { + const { project_id, ...body } = params; + return this._client.post(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Returns a list of service accounts in the project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const projectServiceAccount of client.admin.organization.projects.serviceAccounts.list( + * 'project_id', + * )) { + * // ... + * } + * ``` + */ + list(projectID, query = {}, options) { + return this._client.getAPIList(path`/organization/projects/${projectID}/service_accounts`, ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes a service account from the project. + * + * Returns confirmation of service account deletion, or an error if the project is + * archived (archived projects have no service accounts). + * + * @example + * ```ts + * const serviceAccount = + * await client.admin.organization.projects.serviceAccounts.delete( + * 'service_account_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + delete(serviceAccountID, params, options) { + const { project_id } = params; + return this._client.delete(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +ServiceAccounts.APIKeys = APIKeys; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/users/roles.mjs +var Roles$1 = class extends APIResource { + /** + * Assigns a project role to a user within a project. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.users.roles.create( + * 'user_id', + * { project_id: 'project_id', role_id: 'role_id' }, + * ); + * ``` + */ + create(userID, params, options) { + const { project_id, ...body } = params; + return this._client.post(path`/projects/${project_id}/users/${userID}/roles`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a project role assigned to a user. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.users.roles.retrieve( + * 'role_id', + * { project_id: 'project_id', user_id: 'user_id' }, + * ); + * ``` + */ + retrieve(roleID, params, options) { + const { project_id, user_id } = params; + return this._client.get(path`/projects/${project_id}/users/${user_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists the project roles assigned to a user within a project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const roleListResponse of client.admin.organization.projects.users.roles.list( + * 'user_id', + * { project_id: 'project_id' }, + * )) { + * // ... + * } + * ``` + */ + list(userID, params, options) { + const { project_id, ...query } = params; + return this._client.getAPIList(path`/projects/${project_id}/users/${userID}/roles`, NextCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Unassigns a project role from a user within a project. + * + * @example + * ```ts + * const role = + * await client.admin.organization.projects.users.roles.delete( + * 'role_id', + * { project_id: 'project_id', user_id: 'user_id' }, + * ); + * ``` + */ + delete(roleID, params, options) { + const { project_id, user_id } = params; + return this._client.delete(path`/projects/${project_id}/users/${user_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/users/users.mjs +var Users$1 = class extends APIResource { + constructor() { + super(...arguments); + this.roles = new Roles$1(this._client); + } + /** + * Adds a user to the project. Users must already be members of the organization to + * be added to a project. + * + * @example + * ```ts + * const projectUser = + * await client.admin.organization.projects.users.create( + * 'project_id', + * { role: 'role' }, + * ); + * ``` + */ + create(projectID, body, options) { + return this._client.post(path`/organization/projects/${projectID}/users`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a user in the project. + * + * @example + * ```ts + * const projectUser = + * await client.admin.organization.projects.users.retrieve( + * 'user_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + retrieve(userID, params, options) { + const { project_id } = params; + return this._client.get(path`/organization/projects/${project_id}/users/${userID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Modifies a user's role in the project. + * + * @example + * ```ts + * const projectUser = + * await client.admin.organization.projects.users.update( + * 'user_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + update(userID, params, options) { + const { project_id, ...body } = params; + return this._client.post(path`/organization/projects/${project_id}/users/${userID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Returns a list of users in the project. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const projectUser of client.admin.organization.projects.users.list( + * 'project_id', + * )) { + * // ... + * } + * ``` + */ + list(projectID, query = {}, options) { + return this._client.getAPIList(path`/organization/projects/${projectID}/users`, ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes a user from the project. + * + * Returns confirmation of project user deletion, or an error if the project is + * archived (archived projects have no users). + * + * @example + * ```ts + * const user = + * await client.admin.organization.projects.users.delete( + * 'user_id', + * { project_id: 'project_id' }, + * ); + * ``` + */ + delete(userID, params, options) { + const { project_id } = params; + return this._client.delete(path`/organization/projects/${project_id}/users/${userID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +Users$1.Roles = Roles$1; +//#endregion +//#region node_modules/openai/resources/admin/organization/projects/projects.mjs +var Projects = class extends APIResource { + constructor() { + super(...arguments); + this.users = new Users$1(this._client); + this.serviceAccounts = new ServiceAccounts(this._client); + this.apiKeys = new APIKeys$1(this._client); + this.rateLimits = new RateLimits(this._client); + this.modelPermissions = new ModelPermissions(this._client); + this.hostedToolPermissions = new HostedToolPermissions(this._client); + this.groups = new Groups(this._client); + this.roles = new Roles$3(this._client); + this.dataRetention = new DataRetention(this._client); + this.spendLimit = new SpendLimit(this._client); + this.spendAlerts = new SpendAlerts(this._client); + this.certificates = new Certificates(this._client); + } + /** + * Create a new project in the organization. Projects can be created and archived, + * but cannot be deleted. + * + * @example + * ```ts + * const project = + * await client.admin.organization.projects.create({ + * name: 'name', + * }); + * ``` + */ + create(body, options) { + return this._client.post("/organization/projects", { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves a project. + * + * @example + * ```ts + * const project = + * await client.admin.organization.projects.retrieve( + * 'project_id', + * ); + * ``` + */ + retrieve(projectID, options) { + return this._client.get(path`/organization/projects/${projectID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Modifies a project in the organization. + * + * @example + * ```ts + * const project = + * await client.admin.organization.projects.update( + * 'project_id', + * ); + * ``` + */ + update(projectID, body, options) { + return this._client.post(path`/organization/projects/${projectID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Returns a list of projects. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const project of client.admin.organization.projects.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/organization/projects", ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Archives a project in the organization. Archived projects cannot be used or + * updated. + * + * @example + * ```ts + * const project = + * await client.admin.organization.projects.archive( + * 'project_id', + * ); + * ``` + */ + archive(projectID, options) { + return this._client.post(path`/organization/projects/${projectID}/archive`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +Projects.Users = Users$1; +Projects.ServiceAccounts = ServiceAccounts; +Projects.APIKeys = APIKeys$1; +Projects.RateLimits = RateLimits; +Projects.ModelPermissions = ModelPermissions; +Projects.HostedToolPermissions = HostedToolPermissions; +Projects.Groups = Groups; +Projects.Roles = Roles$3; +Projects.DataRetention = DataRetention; +Projects.SpendLimit = SpendLimit; +Projects.SpendAlerts = SpendAlerts; +Projects.Certificates = Certificates; +//#endregion +//#region node_modules/openai/resources/admin/organization/users/roles.mjs +var Roles = class extends APIResource { + /** + * Assigns an organization role to a user within the organization. + * + * @example + * ```ts + * const role = + * await client.admin.organization.users.roles.create( + * 'user_id', + * { role_id: 'role_id' }, + * ); + * ``` + */ + create(userID, body, options) { + return this._client.post(path`/organization/users/${userID}/roles`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Retrieves an organization role assigned to a user. + * + * @example + * ```ts + * const role = + * await client.admin.organization.users.roles.retrieve( + * 'role_id', + * { user_id: 'user_id' }, + * ); + * ``` + */ + retrieve(roleID, params, options) { + const { user_id } = params; + return this._client.get(path`/organization/users/${user_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists the organization roles assigned to a user within the organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const roleListResponse of client.admin.organization.users.roles.list( + * 'user_id', + * )) { + * // ... + * } + * ``` + */ + list(userID, query = {}, options) { + return this._client.getAPIList(path`/organization/users/${userID}/roles`, NextCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Unassigns an organization role from a user within the organization. + * + * @example + * ```ts + * const role = + * await client.admin.organization.users.roles.delete( + * 'role_id', + * { user_id: 'user_id' }, + * ); + * ``` + */ + delete(roleID, params, options) { + const { user_id } = params; + return this._client.delete(path`/organization/users/${user_id}/roles/${roleID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/admin/organization/users/users.mjs +var Users = class extends APIResource { + constructor() { + super(...arguments); + this.roles = new Roles(this._client); + } + /** + * Retrieves a user by their identifier. + * + * @example + * ```ts + * const organizationUser = + * await client.admin.organization.users.retrieve('user_id'); + * ``` + */ + retrieve(userID, options) { + return this._client.get(path`/organization/users/${userID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Modifies a user's role in the organization. + * + * @example + * ```ts + * const organizationUser = + * await client.admin.organization.users.update('user_id'); + * ``` + */ + update(userID, body, options) { + return this._client.post(path`/organization/users/${userID}`, { + body, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Lists all of the users in the organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const organizationUser of client.admin.organization.users.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/organization/users", ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * Deletes a user from the organization. + * + * @example + * ```ts + * const user = await client.admin.organization.users.delete( + * 'user_id', + * ); + * ``` + */ + delete(userID, options) { + return this._client.delete(path`/organization/users/${userID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +Users.Roles = Roles; +//#endregion +//#region node_modules/openai/resources/admin/organization/organization.mjs +var Organization = class extends APIResource { + constructor() { + super(...arguments); + this.auditLogs = new AuditLogs(this._client); + this.adminAPIKeys = new AdminAPIKeys(this._client); + this.usage = new Usage(this._client); + this.invites = new Invites(this._client); + this.users = new Users(this._client); + this.groups = new Groups$1(this._client); + this.roles = new Roles$5(this._client); + this.dataRetention = new DataRetention$1(this._client); + this.spendLimit = new SpendLimit$1(this._client); + this.spendAlerts = new SpendAlerts$1(this._client); + this.certificates = new Certificates$1(this._client); + this.projects = new Projects(this._client); + } +}; +Organization.AuditLogs = AuditLogs; +Organization.AdminAPIKeys = AdminAPIKeys; +Organization.Usage = Usage; +Organization.Invites = Invites; +Organization.Users = Users; +Organization.Groups = Groups$1; +Organization.Roles = Roles$5; +Organization.DataRetention = DataRetention$1; +Organization.SpendLimit = SpendLimit$1; +Organization.SpendAlerts = SpendAlerts$1; +Organization.Certificates = Certificates$1; +Organization.Projects = Projects; +//#endregion +//#region node_modules/openai/resources/admin/admin.mjs +var Admin = class extends APIResource { + constructor() { + super(...arguments); + this.organization = new Organization(this._client); + } +}; +Admin.Organization = Organization; +//#endregion +//#region node_modules/openai/resources/audio/speech.mjs +/** +* Turn audio into text or text into audio. +*/ +var Speech = class extends APIResource { + /** + * Generates audio from the input text. + * + * Returns the audio file content, or a stream of audio events. + * + * @example + * ```ts + * const speech = await client.audio.speech.create({ + * input: 'input', + * model: 'tts-1', + * voice: 'alloy', + * }); + * + * const content = await speech.blob(); + * console.log(content); + * ``` + */ + create(body, options) { + return this._client.post("/audio/speech", { + body, + ...options, + headers: buildHeaders([{ Accept: "application/octet-stream" }, options?.headers]), + __security: { bearerAuth: true }, + __binaryResponse: true + }); + } +}; +//#endregion +//#region node_modules/openai/resources/audio/transcriptions.mjs +/** +* Turn audio into text or text into audio. +*/ +var Transcriptions = class extends APIResource { + create(body, options) { + return this._client.post("/audio/transcriptions", multipartFormRequestOptions({ + body, + ...options, + stream: body.stream ?? false, + __metadata: { model: body.model }, + __security: { bearerAuth: true } + }, this._client)); + } +}; +//#endregion +//#region node_modules/openai/resources/audio/translations.mjs +/** +* Turn audio into text or text into audio. +*/ +var Translations = class extends APIResource { + create(body, options) { + return this._client.post("/audio/translations", multipartFormRequestOptions({ + body, + ...options, + __metadata: { model: body.model }, + __security: { bearerAuth: true } + }, this._client)); + } +}; +//#endregion +//#region node_modules/openai/resources/audio/audio.mjs +var 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); + } +}; +Audio.Transcriptions = Transcriptions; +Audio.Translations = Translations; +Audio.Speech = Speech; +//#endregion +//#region node_modules/openai/resources/batches.mjs +/** +* Create large batches of API requests to run asynchronously. +*/ +var Batches = class extends APIResource { + /** + * Creates and executes a batch from an uploaded file of requests + */ + create(body, options) { + return this._client.post("/batches", { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Retrieves a batch. + */ + retrieve(batchID, options) { + return this._client.get(path`/batches/${batchID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List your organization's batches. + */ + list(query = {}, options) { + return this._client.getAPIList("/batches", CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to + * 10 minutes, before changing to `cancelled`, where it will have partial results + * (if any) available in the output file. + */ + cancel(batchID, options) { + return this._client.post(path`/batches/${batchID}/cancel`, { + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/beta/assistants.mjs +/** +* Build Assistants that can call models and use tools. +*/ +var Assistants = class extends APIResource { + /** + * Create an assistant with a model and instructions. + * + * @deprecated + */ + create(body, options) { + return this._client.post("/assistants", { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Retrieves an assistant. + * + * @deprecated + */ + retrieve(assistantID, options) { + return this._client.get(path`/assistants/${assistantID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Modifies an assistant. + * + * @deprecated + */ + update(assistantID, body, options) { + return this._client.post(path`/assistants/${assistantID}`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Returns a list of assistants. + * + * @deprecated + */ + list(query = {}, options) { + return this._client.getAPIList("/assistants", CursorPage, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Delete an assistant. + * + * @deprecated + */ + delete(assistantID, options) { + return this._client.delete(path`/assistants/${assistantID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/beta/realtime/sessions.mjs +var Sessions$1 = class extends APIResource { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API. Can be configured with the same session parameters as the + * `session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const session = + * await client.beta.realtime.sessions.create(); + * ``` + */ + create(body, options) { + return this._client.post("/realtime/sessions", { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +var TranscriptionSessions = class extends APIResource { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API specifically for realtime transcriptions. Can be configured with + * the same session parameters as the `transcription_session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const transcriptionSession = + * await client.beta.realtime.transcriptionSessions.create(); + * ``` + */ + create(body, options) { + return this._client.post("/realtime/transcription_sessions", { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/beta/realtime/realtime.mjs +/** +* @deprecated Realtime has now launched and is generally available. The old beta API is now deprecated. +*/ +var Realtime$1 = class extends APIResource { + constructor() { + super(...arguments); + this.sessions = new Sessions$1(this._client); + this.transcriptionSessions = new TranscriptionSessions(this._client); + } +}; +Realtime$1.Sessions = Sessions$1; +Realtime$1.TranscriptionSessions = TranscriptionSessions; +//#endregion +//#region node_modules/openai/resources/beta/chatkit/sessions.mjs +var Sessions = class extends APIResource { + /** + * Create a ChatKit session. + * + * @example + * ```ts + * const chatSession = + * await client.beta.chatkit.sessions.create({ + * user: 'x', + * workflow: { id: 'id' }, + * }); + * ``` + */ + create(body, options) { + return this._client.post("/chatkit/sessions", { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Cancel an active ChatKit session and return its most recent metadata. + * + * Cancelling prevents new requests from using the issued client secret. + * + * @example + * ```ts + * const chatSession = + * await client.beta.chatkit.sessions.cancel('cksess_123'); + * ``` + */ + cancel(sessionID, options) { + return this._client.post(path`/chatkit/sessions/${sessionID}/cancel`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/beta/chatkit/threads.mjs +var Threads$1 = class extends APIResource { + /** + * Retrieve a ChatKit thread by its identifier. + * + * @example + * ```ts + * const chatkitThread = + * await client.beta.chatkit.threads.retrieve('cthr_123'); + * ``` + */ + retrieve(threadID, options) { + return this._client.get(path`/chatkit/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * List ChatKit threads with optional pagination and user filters. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatkitThread of client.beta.chatkit.threads.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/chatkit/threads", ConversationCursorPage, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Delete a ChatKit thread along with its items and stored attachments. + * + * @example + * ```ts + * const thread = await client.beta.chatkit.threads.delete( + * 'cthr_123', + * ); + * ``` + */ + delete(threadID, options) { + return this._client.delete(path`/chatkit/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * List items that belong to a ChatKit thread. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const thread of client.beta.chatkit.threads.listItems( + * 'cthr_123', + * )) { + * // ... + * } + * ``` + */ + listItems(threadID, query = {}, options) { + return this._client.getAPIList(path`/chatkit/threads/${threadID}/items`, ConversationCursorPage, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/beta/chatkit/chatkit.mjs +var ChatKit = class extends APIResource { + constructor() { + super(...arguments); + this.sessions = new Sessions(this._client); + this.threads = new Threads$1(this._client); + } +}; +ChatKit.Sessions = Sessions; +ChatKit.Threads = Threads$1; +//#endregion +//#region node_modules/openai/resources/beta/responses/input-items.mjs +var InputItems$1 = class extends APIResource { + /** + * Returns a list of input items for a given response. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaResponseItem of client.beta.responses.inputItems.list( + * 'response_id', + * )) { + * // ... + * } + * ``` + */ + list(responseID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path`/responses/${responseID}/input_items?beta=true`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/beta/responses/input-tokens.mjs +var InputTokens$1 = class extends APIResource { + /** + * Returns input token counts of the request. + * + * Returns an object with `object` set to `response.input_tokens` and an + * `input_tokens` count. + * + * @example + * ```ts + * const response = + * await client.beta.responses.inputTokens.count(); + * ``` + */ + count(params = {}, options) { + const { betas, ...body } = params ?? {}; + return this._client.post("/responses/input_tokens?beta=true", { + body, + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/beta/responses/responses.mjs +var Responses$1 = class extends APIResource { + constructor() { + super(...arguments); + this.inputItems = new InputItems$1(this._client); + this.inputTokens = new InputTokens$1(this._client); + } + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/responses?beta=true", { + body, + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 }, options?.headers]), + stream: params.stream ?? false, + __security: { bearerAuth: true } + }); + } + retrieve(responseID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.get(path`/responses/${responseID}?beta=true`, { + query, + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 }, options?.headers]), + stream: params?.stream ?? false, + __security: { bearerAuth: true } + }); + } + /** + * Deletes a model response with the given ID. + * + * @example + * ```ts + * await client.beta.responses.delete( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + delete(responseID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path`/responses/${responseID}?beta=true`, { + ...options, + headers: buildHeaders([{ + Accept: "*/*", + ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 + }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Cancels a model response with the given ID. Only responses created with the + * `background` parameter set to `true` can be cancelled. + * [Learn more](https://platform.openai.com/docs/guides/background). + * + * @example + * ```ts + * const betaResponse = await client.beta.responses.cancel( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + cancel(responseID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path`/responses/${responseID}/cancel?beta=true`, { + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Compact a conversation. Returns a compacted response object. + * + * Learn when and how to compact long-running conversations in the + * [conversation state guide](https://platform.openai.com/docs/guides/conversation-state#managing-the-context-window). + * For ZDR-compatible compaction details, see + * [Compaction (advanced)](https://platform.openai.com/docs/guides/conversation-state#compaction-advanced). + * + * @example + * ```ts + * const betaCompactedResponse = + * await client.beta.responses.compact({ + * model: 'gpt-5.6-sol', + * }); + * ``` + */ + compact(params, options) { + const { betas, ...body } = params; + return this._client.post("/responses/compact?beta=true", { + body, + ...options, + headers: buildHeaders([{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +Responses$1.InputItems = InputItems$1; +Responses$1.InputTokens = InputTokens$1; +//#endregion +//#region node_modules/openai/resources/beta/threads/messages.mjs +/** +* Build Assistants that can call models and use tools. +* +* @deprecated The Assistants API is deprecated in favor of the Responses API +*/ +var Messages = class extends APIResource { + /** + * Create a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(threadID, body, options) { + return this._client.post(path`/threads/${threadID}/messages`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Retrieve a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(messageID, params, options) { + const { thread_id } = params; + return this._client.get(path`/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Modifies a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(messageID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path`/threads/${thread_id}/messages/${messageID}`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Returns a list of messages for a given thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path`/threads/${threadID}/messages`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Deletes a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(messageID, params, options) { + const { thread_id } = params; + return this._client.delete(path`/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/beta/threads/runs/steps.mjs +/** +* Build Assistants that can call models and use tools. +* +* @deprecated The Assistants API is deprecated in favor of the Responses API +*/ +var Steps = class extends APIResource { + /** + * Retrieves a run step. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(stepID, params, options) { + const { thread_id, run_id, ...query } = params; + return this._client.get(path`/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Returns a list of run steps belonging to a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(runID, params, options) { + const { thread_id, ...query } = params; + return this._client.getAPIList(path`/threads/${thread_id}/runs/${runID}/steps`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/internal/utils/base64.mjs +/** +* Converts a Base64 encoded string to a Float32Array. +* @param base64Str - The Base64 encoded string. +* @returns An Array of numbers interpreted as Float32 values. +*/ +var toFloat32Array = (base64Str) => { + if (typeof Buffer !== "undefined") { + const buf = Buffer.from(base64Str, "base64"); + return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT)); + } else { + const binaryStr = atob(base64Str); + const len = binaryStr.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) bytes[i] = binaryStr.charCodeAt(i); + return Array.from(new Float32Array(bytes.buffer)); + } +}; +//#endregion +//#region node_modules/openai/internal/utils/env.mjs +/** +* Read an environment variable. +* +* Trims beginning and trailing whitespace. +* +* Will return undefined if the environment variable doesn't exist or cannot be accessed. +*/ +var readEnv = (env) => { + if (typeof globalThis.process !== "undefined") return globalThis.process.env?.[env]?.trim() || void 0; + if (typeof globalThis.Deno !== "undefined") return globalThis.Deno.env?.get?.(env)?.trim() || void 0; +}; +//#endregion +//#region node_modules/openai/lib/AssistantStream.mjs +var _AssistantStream_instances; +var _a$1; +var _AssistantStream_events; +var _AssistantStream_runStepSnapshots; +var _AssistantStream_messageSnapshots; +var _AssistantStream_messageSnapshot; +var _AssistantStream_finalRun; +var _AssistantStream_currentContentIndex; +var _AssistantStream_currentContent; +var _AssistantStream_currentToolCallIndex; +var _AssistantStream_currentToolCall; +var _AssistantStream_currentEvent; +var _AssistantStream_currentRunSnapshot; +var _AssistantStream_currentRunStepSnapshot; +var _AssistantStream_addEvent; +var _AssistantStream_endRequest; +var _AssistantStream_handleMessage; +var _AssistantStream_handleRunStep; +var _AssistantStream_handleEvent; +var _AssistantStream_accumulateRunStep; +var _AssistantStream_accumulateMessage; +var _AssistantStream_accumulateContent; +var _AssistantStream_handleRun; +var AssistantStream = class extends EventStream { + 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 = /* @__PURE__ */ new WeakMap(), _AssistantStream_runStepSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_finalRun = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContentIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCallIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCall = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentEvent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunStepSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("event", (event) => { + const eventCopy = structuredClone(event); + const reader = readQueue.shift(); + if (reader) reader.resolve(eventCopy); + else pushQueue.push(eventCopy); + }); + 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((chunk) => chunk ? { + value: chunk, + done: false + } : { + value: void 0, + done: true + }); + } + return { + value: pushQueue.shift(), + done: false + }; + }, + return: async () => { + this.abort(); + return { + value: void 0, + done: true + }; + } + }; + } + static fromReadableStream(stream) { + const runner = new _a$1(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + async _fromReadableStream(readableStream, options) { + this._listenForAbort(options?.signal); + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + toReadableStream() { + return new Stream(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream(); + } + static createToolAssistantStream(runId, runs, params, options) { + const runner = new _a$1(); + runner._run(() => runner._runToolAssistantStream(runId, runs, params, { + ...options, + headers: { + ...options?.headers, + "X-Stainless-Helper-Method": "stream" + } + })); + return runner; + } + async _createToolAssistantStream(run, runId, params, options) { + this._listenForAbort(options?.signal); + const body = { + ...params, + stream: true + }; + const stream = await run.submitToolOutputs(runId, body, { + ...options, + signal: this.controller.signal + }); + this._connected(); + for await (const event of stream) __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static createThreadAssistantStream(params, thread, options) { + const runner = new _a$1(); + runner._run(() => runner._threadAssistantStream(params, thread, { + ...options, + headers: { + ...options?.headers, + "X-Stainless-Helper-Method": "stream" + } + })); + return runner; + } + static createAssistantStream(threadId, runs, params, options) { + const runner = new _a$1(); + runner._run(() => runner._runAssistantStream(threadId, runs, params, { + ...options, + headers: { + ...options?.headers, + "X-Stainless-Helper-Method": "stream" + } + })); + return runner; + } + currentEvent() { + return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); + } + currentRun() { + return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); + } + currentMessageSnapshot() { + return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); + } + currentRunStepSnapshot() { + return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); + } + async finalRunSteps() { + await this.done(); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); + } + async finalMessages() { + await this.done(); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); + } + async finalRun() { + await this.done(); + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) throw Error("Final run was not received."); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); + } + async _createThreadAssistantStream(thread, params, options) { + this._listenForAbort(options?.signal); + const body = { + ...params, + stream: true + }; + const stream = await thread.createAndRun(body, { + ...options, + signal: this.controller.signal + }); + this._connected(); + for await (const event of stream) __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + async _createAssistantStream(run, threadId, params, options) { + this._listenForAbort(options?.signal); + const body = { + ...params, + stream: true + }; + const stream = await run.create(threadId, body, { + ...options, + signal: this.controller.signal + }); + this._connected(); + for await (const event of stream) __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + return this._addRun(__classPrivateFieldGet(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((x) => typeof x === "string" || typeof x === "number")) { + accValue.push(...deltaValue); + continue; + } + for (const deltaEntry of deltaValue) { + if (!isObj(deltaEntry)) throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`); + const index = deltaEntry["index"]; + if (index == null) { + console.error(deltaEntry); + throw new Error("Expected array delta entry to have an `index` property"); + } + if (typeof index !== "number") throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`); + const accEntry = accValue[index]; + if (accEntry == null) accValue[index] = deltaEntry; + else accValue[index] = this.accumulateDelta(accEntry, deltaEntry); + } + continue; + } else throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); + acc[key] = accValue; + } + return acc; + } + _addRun(run) { + return run; + } + async _threadAssistantStream(params, thread, options) { + return await this._createThreadAssistantStream(thread, params, options); + } + async _runAssistantStream(threadId, runs, params, options) { + return await this._createAssistantStream(runs, threadId, params, options); + } + async _runToolAssistantStream(runId, runs, params, options) { + return await this._createToolAssistantStream(runs, runId, params, options); + } +}; +_a$1 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { + if (this.ended) return; + __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); + switch (event.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.incomplete": + case "thread.run.failed": + case "thread.run.cancelling": + case "thread.run.cancelled": + case "thread.run.expired": + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); + 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": + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); + break; + case "thread.message.created": + case "thread.message.in_progress": + case "thread.message.delta": + case "thread.message.completed": + case "thread.message.incomplete": + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); + break; + case "error": throw new Error("Encountered an error event in event processing - errors should be processed earlier"); + default: + } +}, _AssistantStream_endRequest = function _AssistantStream_endRequest() { + if (this.ended) throw new OpenAIError(`stream has ended, this shouldn't happen`); + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) throw Error("Final run has not been received"); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); +}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { + const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); + __classPrivateFieldGet(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 (event.event) { + case "thread.message.created": + this._emit("messageCreated", event.data); + break; + case "thread.message.in_progress": break; + case "thread.message.delta": + this._emit("messageDelta", event.data.delta, accumulatedMessage); + if (event.data.delta.content) for (const content of event.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 != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { + if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { + case "text": + this._emit("textDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case "image_file": + this._emit("imageFileDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); + } + __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); + } + break; + case "thread.message.completed": + case "thread.message.incomplete": + if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== void 0) { + const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; + if (currentContent) switch (currentContent.type) { + case "image_file": + this._emit("imageFileDone", currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case "text": + this._emit("textDone", currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) this._emit("messageDone", event.data); + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, void 0, "f"); + } +}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { + const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); + switch (event.event) { + case "thread.run.step.created": + this._emit("runStepCreated", event.data); + break; + case "thread.run.step.delta": + const delta = event.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 == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) this._emit("toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); + else { + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) this._emit("toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) this._emit("toolCallCreated", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + } + this._emit("runStepDelta", event.data.delta, accumulatedRunStep); + break; + case "thread.run.step.completed": + case "thread.run.step.failed": + case "thread.run.step.cancelled": + case "thread.run.step.expired": + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, void 0, "f"); + if (event.data.step_details.type == "tool_calls") { + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit("toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f"); + } + } + this._emit("runStepDone", event.data, accumulatedRunStep); + break; + case "thread.run.step.in_progress": break; + } +}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { + __classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); + this._emit("event", event); +}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { + switch (event.event) { + case "thread.run.step.created": + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + return event.data; + case "thread.run.step.delta": + let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + if (!snapshot) throw Error("Received a RunStepDelta before creation of a snapshot"); + let data = event.data; + if (data.delta) { + const accumulated = _a$1.accumulateDelta(snapshot, data.delta); + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; + } + return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.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": + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + break; + } + if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + throw new Error("No snapshot available"); +}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { + let newContent = []; + switch (event.event) { + case "thread.message.created": return [event.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 = event.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] = __classPrivateFieldGet(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_accumulateContent(contentElement, currentContent) { + return _a$1.accumulateDelta(currentContent, contentElement); +}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { + __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); + switch (event.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": + case "thread.run.incomplete": + __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit("toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f"); + } + break; + case "thread.run.cancelling": break; + } +}; +//#endregion +//#region node_modules/openai/resources/beta/threads/runs/runs.mjs +/** +* Build Assistants that can call models and use tools. +* +* @deprecated The Assistants API is deprecated in favor of the Responses API +*/ +var Runs$1 = class extends APIResource { + constructor() { + super(...arguments); + this.steps = new Steps(this._client); + } + create(threadID, params, options) { + const { include, ...body } = params; + return this._client.post(path`/threads/${threadID}/runs`, { + query: { include }, + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + stream: params.stream ?? false, + __synthesizeEventData: true, + __security: { bearerAuth: true } + }); + } + /** + * Retrieves a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(runID, params, options) { + const { thread_id } = params; + return this._client.get(path`/threads/${thread_id}/runs/${runID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Modifies a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path`/threads/${thread_id}/runs/${runID}`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Returns a list of runs belonging to a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path`/threads/${threadID}/runs`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Cancels a run that is `in_progress`. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + cancel(runID, params, options) { + const { thread_id } = params; + return this._client.post(path`/threads/${thread_id}/runs/${runID}/cancel`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndPoll(threadId, body, options) { + const run = await this.create(threadId, body, options); + return await this.poll(run.id, { thread_id: threadId }, options); + } + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async poll(runId, params, options) { + const headers = buildHeaders([options?.headers, { + "X-Stainless-Poll-Helper": "true", + "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0 + }]); + while (true) { + const { data: run, response } = await this.retrieve(runId, params, { + ...options, + headers: { + ...options?.headers, + ...headers + } + }).withResponse(); + switch (run.status) { + case "queued": + case "in_progress": + case "cancelling": + let sleepInterval = 5e3; + if (options?.pollIntervalMs) sleepInterval = options.pollIntervalMs; + else { + const headerInterval = response.headers.get("openai-poll-after-ms"); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) sleepInterval = headerIntervalMs; + } + } + await sleep(sleepInterval); + break; + case "requires_action": + case "incomplete": + case "cancelled": + case "completed": + case "failed": + case "expired": return run; + } + } + } + /** + * Create a Run stream + */ + stream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + submitToolOutputs(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + stream: params.stream ?? false, + __synthesizeEventData: true, + __security: { bearerAuth: true } + }); + } + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async submitToolOutputsAndPoll(runId, params, options) { + const run = await this.submitToolOutputs(runId, params, options); + return await this.poll(run.id, params, options); + } + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream(runId, params, options) { + return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options); + } +}; +Runs$1.Steps = Steps; +//#endregion +//#region node_modules/openai/resources/beta/threads/threads.mjs +/** +* Build Assistants that can call models and use tools. +* +* @deprecated The Assistants API is deprecated in favor of the Responses API +*/ +var Threads = class extends APIResource { + constructor() { + super(...arguments); + this.runs = new Runs$1(this._client); + this.messages = new Messages(this._client); + } + /** + * Create a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(body = {}, options) { + return this._client.post("/threads", { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Retrieves a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(threadID, options) { + return this._client.get(path`/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Modifies a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(threadID, body, options) { + return this._client.post(path`/threads/${threadID}`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Delete a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(threadID, options) { + return this._client.delete(path`/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + createAndRun(body, options) { + return this._client.post("/threads/runs", { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + stream: body.stream ?? false, + __synthesizeEventData: true, + __security: { bearerAuth: true } + }); + } + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndRunPoll(body, options) { + const run = await this.createAndRun(body, options); + return await this.runs.poll(run.id, { thread_id: run.thread_id }, options); + } + /** + * Create a thread and stream the run back + */ + createAndRunStream(body, options) { + return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + } +}; +Threads.Runs = Runs$1; +Threads.Messages = Messages; +//#endregion +//#region node_modules/openai/resources/beta/beta.mjs +var Beta = class extends APIResource { + constructor() { + super(...arguments); + this.realtime = new Realtime$1(this._client); + this.responses = new Responses$1(this._client); + this.chatkit = new ChatKit(this._client); + this.assistants = new Assistants(this._client); + this.threads = new Threads(this._client); + } +}; +Beta.Realtime = Realtime$1; +Beta.Responses = Responses$1; +Beta.ChatKit = ChatKit; +Beta.Assistants = Assistants; +Beta.Threads = Threads; +//#endregion +//#region node_modules/openai/resources/completions.mjs +/** +* Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position. +*/ +var Completions = class extends APIResource { + create(body, options) { + return this._client.post("/completions", { + body, + ...options, + stream: body.stream ?? false, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/containers/files/content.mjs +var Content$2 = class extends APIResource { + /** + * Retrieve Container File Content + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path`/containers/${container_id}/files/${fileID}/content`, { + ...options, + headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), + __security: { bearerAuth: true }, + __binaryResponse: true + }); + } +}; +//#endregion +//#region node_modules/openai/resources/containers/files/files.mjs +var Files$2 = class extends APIResource { + constructor() { + super(...arguments); + this.content = new Content$2(this._client); + } + /** + * Create a Container File + * + * You can send either a multipart/form-data request with the raw file content, or + * a JSON request with a file ID. + */ + create(containerID, body, options) { + return this._client.post(path`/containers/${containerID}/files`, maybeMultipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } + /** + * Retrieve Container File + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path`/containers/${container_id}/files/${fileID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List Container files + */ + list(containerID, query = {}, options) { + return this._client.getAPIList(path`/containers/${containerID}/files`, CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete Container File + */ + delete(fileID, params, options) { + const { container_id } = params; + return this._client.delete(path`/containers/${container_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +Files$2.Content = Content$2; +//#endregion +//#region node_modules/openai/resources/containers/containers.mjs +var Containers = class extends APIResource { + constructor() { + super(...arguments); + this.files = new Files$2(this._client); + } + /** + * Create Container + */ + create(body, options) { + return this._client.post("/containers", { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Retrieve Container + */ + retrieve(containerID, options) { + return this._client.get(path`/containers/${containerID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List Containers + */ + list(query = {}, options) { + return this._client.getAPIList("/containers", CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete Container + */ + delete(containerID, options) { + return this._client.delete(path`/containers/${containerID}`, { + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +Containers.Files = Files$2; +//#endregion +//#region node_modules/openai/resources/conversations/items.mjs +/** +* Manage conversations and conversation items. +*/ +var Items = class extends APIResource { + /** + * Create items in a conversation with the given ID. + */ + create(conversationID, params, options) { + const { include, ...body } = params; + return this._client.post(path`/conversations/${conversationID}/items`, { + query: { include }, + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Get a single item from a conversation with the given IDs. + */ + retrieve(itemID, params, options) { + const { conversation_id, ...query } = params; + return this._client.get(path`/conversations/${conversation_id}/items/${itemID}`, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List all items for a conversation with the given ID. + */ + list(conversationID, query = {}, options) { + return this._client.getAPIList(path`/conversations/${conversationID}/items`, ConversationCursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete an item from a conversation with the given IDs. + */ + delete(itemID, params, options) { + const { conversation_id } = params; + return this._client.delete(path`/conversations/${conversation_id}/items/${itemID}`, { + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/conversations/conversations.mjs +/** +* Manage conversations and conversation items. +*/ +var Conversations = class extends APIResource { + constructor() { + super(...arguments); + this.items = new Items(this._client); + } + /** + * Create a conversation. + */ + create(body = {}, options) { + return this._client.post("/conversations", { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Get a conversation + */ + retrieve(conversationID, options) { + return this._client.get(path`/conversations/${conversationID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Update a conversation + */ + update(conversationID, body, options) { + return this._client.post(path`/conversations/${conversationID}`, { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete a conversation. Items in the conversation will not be deleted. + */ + delete(conversationID, options) { + return this._client.delete(path`/conversations/${conversationID}`, { + ...options, + __security: { bearerAuth: true } + }); + } +}; +Conversations.Items = Items; +//#endregion +//#region node_modules/openai/resources/embeddings.mjs +/** +* Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. +*/ +var Embeddings = class extends APIResource { + /** + * Creates an embedding vector representing the input text. + * + * @example + * ```ts + * const createEmbeddingResponse = + * await client.embeddings.create({ + * input: 'The quick brown fox jumped over the lazy dog', + * model: 'text-embedding-3-small', + * }); + * ``` + */ + create(body, options) { + const hasUserProvidedEncodingFormat = !!body.encoding_format; + let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : "base64"; + if (hasUserProvidedEncodingFormat) loggerFor(this._client).debug("embeddings/user defined encoding_format:", body.encoding_format); + const response = this._client.post("/embeddings", { + body: { + ...body, + encoding_format + }, + ...options, + __security: { bearerAuth: true } + }); + if (hasUserProvidedEncodingFormat) return response; + loggerFor(this._client).debug("embeddings/decoding base64 embeddings from base64"); + return response._thenUnwrap((response) => { + if (response && response.data) response.data.forEach((embeddingBase64Obj) => { + const embeddingBase64Str = embeddingBase64Obj.embedding; + embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); + }); + return response; + }); + } +}; +//#endregion +//#region node_modules/openai/resources/evals/runs/output-items.mjs +/** +* Manage and run evals in the OpenAI platform. +*/ +var OutputItems = class extends APIResource { + /** + * Get an evaluation run output item by ID. + */ + retrieve(outputItemID, params, options) { + const { eval_id, run_id } = params; + return this._client.get(path`/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Get a list of output items for an evaluation run. + */ + list(runID, params, options) { + const { eval_id, ...query } = params; + return this._client.getAPIList(path`/evals/${eval_id}/runs/${runID}/output_items`, CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/evals/runs/runs.mjs +/** +* Manage and run evals in the OpenAI platform. +*/ +var Runs = class extends APIResource { + constructor() { + super(...arguments); + this.outputItems = new OutputItems(this._client); + } + /** + * Kicks off a new run for a given evaluation, specifying the data source, and what + * model configuration to use to test. The datasource will be validated against the + * schema specified in the config of the evaluation. + */ + create(evalID, body, options) { + return this._client.post(path`/evals/${evalID}/runs`, { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Get an evaluation run by ID. + */ + retrieve(runID, params, options) { + const { eval_id } = params; + return this._client.get(path`/evals/${eval_id}/runs/${runID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Get a list of runs for an evaluation. + */ + list(evalID, query = {}, options) { + return this._client.getAPIList(path`/evals/${evalID}/runs`, CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete an eval run. + */ + delete(runID, params, options) { + const { eval_id } = params; + return this._client.delete(path`/evals/${eval_id}/runs/${runID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Cancel an ongoing evaluation run. + */ + cancel(runID, params, options) { + const { eval_id } = params; + return this._client.post(path`/evals/${eval_id}/runs/${runID}`, { + ...options, + __security: { bearerAuth: true } + }); + } +}; +Runs.OutputItems = OutputItems; +//#endregion +//#region node_modules/openai/resources/evals/evals.mjs +/** +* Manage and run evals in the OpenAI platform. +*/ +var Evals = class extends APIResource { + constructor() { + super(...arguments); + this.runs = new Runs(this._client); + } + /** + * Create the structure of an evaluation that can be used to test a model's + * performance. An evaluation is a set of testing criteria and the config for a + * data source, which dictates the schema of the data used in the evaluation. After + * creating an evaluation, you can run it on different models and model parameters. + * We support several types of graders and datasources. For more information, see + * the [Evals guide](https://platform.openai.com/docs/guides/evals). + */ + create(body, options) { + return this._client.post("/evals", { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Get an evaluation by ID. + */ + retrieve(evalID, options) { + return this._client.get(path`/evals/${evalID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Update certain properties of an evaluation. + */ + update(evalID, body, options) { + return this._client.post(path`/evals/${evalID}`, { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List evaluations for a project. + */ + list(query = {}, options) { + return this._client.getAPIList("/evals", CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete an evaluation. + */ + delete(evalID, options) { + return this._client.delete(path`/evals/${evalID}`, { + ...options, + __security: { bearerAuth: true } + }); + } +}; +Evals.Runs = Runs; +//#endregion +//#region node_modules/openai/resources/files.mjs +/** +* Files are used to upload documents that can be used with features like Assistants and Fine-tuning. +*/ +var Files$1 = class extends APIResource { + /** + * Upload a file that can be used across various endpoints. Individual files can be + * up to 512 MB, and each project can store up to 2.5 TB of files in total. There + * is no organization-wide storage limit. Uploads to this endpoint are rate-limited + * to 1,000 requests per minute per authenticated user. + * + * - The Assistants API supports files up to 2 million tokens and of specific file + * types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) + * for details. + * - The Fine-tuning API only supports `.jsonl` files. The input also has certain + * required formats for fine-tuning + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) + * or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input + * also has a specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * - For Retrieval or `file_search` ingestion, upload files here first. If you need + * to attach multiple uploaded files to the same vector store, use + * [`/vector_stores/{vector_store_id}/file_batches`](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/createBatch) + * instead of attaching them one by one. Vector store attachment has separate + * limits from file upload, including 2,000 attached files per minute per + * organization. + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + create(body, options) { + return this._client.post("/files", multipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } + /** + * Returns information about a specific file. + */ + retrieve(fileID, options) { + return this._client.get(path`/files/${fileID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Returns a list of files. + */ + list(query = {}, options) { + return this._client.getAPIList("/files", CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete a file and remove it from all vector stores. + */ + delete(fileID, options) { + return this._client.delete(path`/files/${fileID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Returns the contents of the specified file. + */ + content(fileID, options) { + return this._client.get(path`/files/${fileID}/content`, { + ...options, + headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), + __security: { bearerAuth: true }, + __binaryResponse: true + }); + } + /** + * Waits for the given file to be processed, default timeout is 30 mins. + */ + async waitForProcessing(id, { pollInterval = 5e3, maxWait = 1800 * 1e3 } = {}) { + const TERMINAL_STATES = /* @__PURE__ */ new Set([ + "processed", + "error", + "deleted" + ]); + const start = Date.now(); + let file = await this.retrieve(id); + while (!file.status || !TERMINAL_STATES.has(file.status)) { + await sleep(pollInterval); + file = await this.retrieve(id); + if (Date.now() - start > maxWait) throw new APIConnectionTimeoutError({ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.` }); + } + return file; + } +}; +//#endregion +//#region node_modules/openai/resources/fine-tuning/methods.mjs +var Methods = class extends APIResource {}; +//#endregion +//#region node_modules/openai/resources/fine-tuning/alpha/graders.mjs +/** +* Manage fine-tuning jobs to tailor a model to your specific training data. +*/ +var Graders$1 = class extends APIResource { + /** + * Run a grader. + * + * @example + * ```ts + * const response = await client.fineTuning.alpha.graders.run({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * model_sample: 'model_sample', + * }); + * ``` + */ + run(body, options) { + return this._client.post("/fine_tuning/alpha/graders/run", { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Validate a grader. + * + * @example + * ```ts + * const response = + * await client.fineTuning.alpha.graders.validate({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * }); + * ``` + */ + validate(body, options) { + return this._client.post("/fine_tuning/alpha/graders/validate", { + body, + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +var Alpha = class extends APIResource { + constructor() { + super(...arguments); + this.graders = new Graders$1(this._client); + } +}; +Alpha.Graders = Graders$1; +//#endregion +//#region node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +/** +* Manage fine-tuning jobs to tailor a model to your specific training data. +*/ +var Permissions = class extends APIResource { + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } + * ``` + */ + create(fineTunedModelCheckpoint, body, options) { + return this._client.getAPIList(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, Page, { + body, + method: "post", + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @deprecated Retrieve is deprecated. Please swap to the paginated list method instead. + */ + retrieve(fineTunedModelCheckpoint, query = {}, options) { + return this._client.get(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionListResponse of client.fineTuning.checkpoints.permissions.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTunedModelCheckpoint, query = {}, options) { + return this._client.getAPIList(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, ConversationCursorPage, { + query, + ...options, + __security: { adminAPIKeyAuth: true } + }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); + * ``` + */ + delete(permissionID, params, options) { + const { fine_tuned_model_checkpoint } = params; + return this._client.delete(path`/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, { + ...options, + __security: { adminAPIKeyAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +var Checkpoints$1 = class extends APIResource { + constructor() { + super(...arguments); + this.permissions = new Permissions(this._client); + } +}; +Checkpoints$1.Permissions = Permissions; +//#endregion +//#region node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +/** +* Manage fine-tuning jobs to tailor a model to your specific training data. +*/ +var Checkpoints = class extends APIResource { + /** + * List checkpoints for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path`/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +/** +* Manage fine-tuning jobs to tailor a model to your specific training data. +*/ +var Jobs = class extends APIResource { + constructor() { + super(...arguments); + this.checkpoints = new Checkpoints(this._client); + } + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body, options) { + return this._client.post("/fine_tuning/jobs", { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTuningJobID, options) { + return this._client.get(path`/fine_tuning/jobs/${fineTuningJobID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List your organization's fine-tuning jobs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/fine_tuning/jobs", CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Immediately cancel a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + cancel(fineTuningJobID, options) { + return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/cancel`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path`/fine_tuning/jobs/${fineTuningJobID}/events`, CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + pause(fineTuningJobID, options) { + return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/pause`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + resume(fineTuningJobID, options) { + return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/resume`, { + ...options, + __security: { bearerAuth: true } + }); + } +}; +Jobs.Checkpoints = Checkpoints; +//#endregion +//#region node_modules/openai/resources/fine-tuning/fine-tuning.mjs +var FineTuning = class extends APIResource { + constructor() { + super(...arguments); + this.methods = new Methods(this._client); + this.jobs = new Jobs(this._client); + this.checkpoints = new Checkpoints$1(this._client); + this.alpha = new Alpha(this._client); + } +}; +FineTuning.Methods = Methods; +FineTuning.Jobs = Jobs; +FineTuning.Checkpoints = Checkpoints$1; +FineTuning.Alpha = Alpha; +//#endregion +//#region node_modules/openai/resources/graders/grader-models.mjs +var GraderModels = class extends APIResource {}; +//#endregion +//#region node_modules/openai/resources/graders/graders.mjs +var Graders = class extends APIResource { + constructor() { + super(...arguments); + this.graderModels = new GraderModels(this._client); + } +}; +Graders.GraderModels = GraderModels; +//#endregion +//#region node_modules/openai/resources/images.mjs +/** +* Given a prompt and/or an input image, the model will generate a new image. +*/ +var Images = class extends APIResource { + /** + * Creates a variation of a given image. This endpoint only supports `dall-e-2`. + * + * @example + * ```ts + * const imagesResponse = await client.images.createVariation({ + * image: fs.createReadStream('otter.png'), + * }); + * ``` + */ + createVariation(body, options) { + return this._client.post("/images/variations", multipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } + edit(body, options) { + return this._client.post("/images/edits", multipartFormRequestOptions({ + body, + ...options, + stream: body.stream ?? false, + __security: { bearerAuth: true } + }, this._client)); + } + generate(body, options) { + return this._client.post("/images/generations", { + body, + ...options, + stream: body.stream ?? false, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/models.mjs +/** +* List and describe the various models available in the API. +*/ +var Models = class extends APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model, options) { + return this._client.get(path`/models/${model}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options) { + return this._client.getAPIList("/models", Page, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. + */ + delete(model, options) { + return this._client.delete(path`/models/${model}`, { + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/moderations.mjs +/** +* Given text and/or image inputs, classifies if those inputs are potentially harmful. +*/ +var Moderations = class extends APIResource { + /** + * Classifies if text and/or image inputs are potentially harmful. Learn more in + * the [moderation guide](https://platform.openai.com/docs/guides/moderation). + */ + create(body, options) { + return this._client.post("/moderations", { + body, + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/realtime/calls.mjs +var Calls = class extends APIResource { + /** + * Accept an incoming SIP call and configure the realtime session that will handle + * it. + * + * @example + * ```ts + * await client.realtime.calls.accept('call_id', { + * type: 'realtime', + * }); + * ``` + */ + accept(callID, body, options) { + return this._client.post(path`/realtime/calls/${callID}/accept`, { + body, + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * End an active Realtime API call, whether it was initiated over SIP or WebRTC. + * + * @example + * ```ts + * await client.realtime.calls.hangup('call_id'); + * ``` + */ + hangup(callID, options) { + return this._client.post(path`/realtime/calls/${callID}/hangup`, { + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Transfer an active SIP call to a new destination using the SIP REFER verb. + * + * @example + * ```ts + * await client.realtime.calls.refer('call_id', { + * target_uri: 'tel:+14155550123', + * }); + * ``` + */ + refer(callID, body, options) { + return this._client.post(path`/realtime/calls/${callID}/refer`, { + body, + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Decline an incoming SIP call by returning a SIP status code to the caller. + * + * @example + * ```ts + * await client.realtime.calls.reject('call_id'); + * ``` + */ + reject(callID, body = {}, options) { + return this._client.post(path`/realtime/calls/${callID}/reject`, { + body, + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/realtime/client-secrets.mjs +var ClientSecrets = class extends APIResource { + /** + * Create a Realtime client secret with an associated session configuration. + * + * Client secrets are short-lived tokens that can be passed to a client app, such + * as a web frontend or mobile client, which grants access to the Realtime API + * without leaking your main API key. You can configure a custom TTL for each + * client secret. + * + * You can also attach session configuration options to the client secret, which + * will be applied to any sessions created using that client secret, but these can + * also be overridden by the client connection. + * + * [Learn more about authentication with client secrets over WebRTC](https://platform.openai.com/docs/guides/realtime-webrtc). + * + * Returns the created client secret and the effective session object. The client + * secret is a string that looks like `ek_1234`. + * + * @example + * ```ts + * const clientSecret = + * await client.realtime.clientSecrets.create(); + * ``` + */ + create(body, options) { + return this._client.post("/realtime/client_secrets", { + body, + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/realtime/realtime.mjs +var Realtime = class extends APIResource { + constructor() { + super(...arguments); + this.clientSecrets = new ClientSecrets(this._client); + this.calls = new Calls(this._client); + } +}; +Realtime.ClientSecrets = ClientSecrets; +Realtime.Calls = Calls; +//#endregion +//#region node_modules/openai/lib/ResponsesParser.mjs +function maybeParseResponse(response, params) { + if (!params || !hasAutoParseableInput(params)) { + const parsed = { + ...response, + output_parsed: null, + output: response.output.map((item) => { + if (item.type === "function_call") return { + ...item, + parsed_arguments: null + }; + if (item.type === "message") return { + ...item, + content: item.content.map((content) => ({ + ...content, + parsed: null + })) + }; + else return item; + }) + }; + if (needsOutputText(response, parsed)) addOutputText(parsed); + return parsed; + } + return parseResponse(response, params); +} +function parseResponse(response, params) { + const shouldParse = !response.status || response.status === "completed"; + const output = response.output.map((item) => { + if (item.type === "function_call") return shouldParse ? parseToolCall(params, item) : { + ...item, + parsed_arguments: null + }; + if (item.type === "message") { + const content = item.content.map((content) => { + if (content.type === "output_text") return { + ...content, + parsed: shouldParse ? parseTextFormat(params, content.text) : null + }; + return content; + }); + return { + ...item, + content + }; + } + return item; + }); + const parsed = Object.assign({}, response, { output }); + if (needsOutputText(response, parsed)) addOutputText(parsed); + Object.defineProperty(parsed, "output_parsed", { + enumerable: true, + get() { + for (const output of parsed.output) { + if (output.type !== "message") continue; + for (const content of output.content) if (content.type === "output_text" && content.parsed !== null) return content.parsed; + } + return null; + } + }); + return parsed; +} +function parseTextFormat(params, content) { + if (params.text?.format?.type !== "json_schema") return null; + if ("$parseRaw" in params.text?.format) return (params.text?.format).$parseRaw(content); + return JSON.parse(content); +} +function hasAutoParseableInput(params) { + if (isAutoParsableResponseFormat(params.text?.format)) return true; + return Array.isArray(params.tools) && params.tools.some((tool) => isAutoParsableTool(tool) || tool.type === "function" && tool.strict === true); +} +function isAutoParsableTool(tool) { + return tool?.["$brand"] === "auto-parseable-tool"; +} +function getInputToolByName(input_tools, name) { + return input_tools.find((tool) => tool.type === "function" && tool.name === name); +} +function parseToolCall(params, toolCall) { + const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); + return { + ...toolCall, + ...toolCall, + parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments) : inputTool?.strict ? JSON.parse(toolCall.arguments) : null + }; +} +function needsOutputText(response, target) { + return !Object.getOwnPropertyDescriptor(response, "output_text") || target.output_text == null; +} +function addOutputText(rsp) { + const texts = []; + for (const output of rsp.output) { + if (output.type !== "message") continue; + for (const content of output.content) if (content.type === "output_text") texts.push(content.text); + } + rsp.output_text = texts.join(""); +} +//#endregion +//#region node_modules/openai/lib/responses/ResponseAccumulator.mjs +/** +* Applies a streaming event to a response snapshot. +* +* Always use the returned snapshot. Incremental events update the supplied snapshot +* in place, while response lifecycle events return a detached replacement. Event +* payloads are cloned, so retaining or replaying the raw events is safe. +*/ +function accumulateResponse(event, snapshot) { + if (!snapshot) { + if (event.type !== "response.created") throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`); + return cloneResponse(event.response); + } + switch (event.type) { + case "response.output_item.added": + snapshot.output.push(structuredClone(event.item)); + if (event.item.type === "message") addOutputText(snapshot); + break; + case "response.output_item.done": + getOutput(snapshot, event.output_index); + snapshot.output[event.output_index] = structuredClone(event.item); + if (event.item.type === "message") addOutputText(snapshot); + break; + case "response.content_part.added": { + const output = getOutput(snapshot, event.output_index); + const type = output.type; + const part = event.part; + if (type === "message" && part.type !== "reasoning_text") { + output.content.push(structuredClone(part)); + if (part.type === "output_text") addOutputText(snapshot); + } else if (type === "reasoning" && part.type === "reasoning_text") { + if (!output.content) output.content = []; + output.content.push(structuredClone(part)); + } + break; + } + case "response.content_part.done": { + const output = getOutput(snapshot, event.output_index); + const part = event.part; + if (output.type === "message" && part.type !== "reasoning_text") { + getContent(output.content, event.content_index); + output.content[event.content_index] = structuredClone(part); + if (part.type === "output_text") addOutputText(snapshot); + } else if (output.type === "reasoning" && part.type === "reasoning_text") { + const content = output.content; + if (!content) throw new OpenAIError(`missing content at index ${event.content_index}`); + getContent(content, event.content_index); + content[event.content_index] = structuredClone(part); + } + break; + } + case "response.output_text.delta": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "message") { + const content = getContent(output.content, event.content_index); + if (content.type !== "output_text") throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`); + content.text += event.delta; + snapshot.output_text += event.delta; + } + break; + } + case "response.output_text.done": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "message") { + const content = getContent(output.content, event.content_index); + if (content.type !== "output_text") throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`); + content.text = event.text; + addOutputText(snapshot); + } + break; + } + case "response.output_text.annotation.added": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "message") { + const content = getContent(output.content, event.content_index); + if (content.type !== "output_text") throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`); + content.annotations[event.annotation_index] = structuredClone(event.annotation); + } + break; + } + case "response.refusal.delta": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "message") { + const content = getContent(output.content, event.content_index); + if (content.type !== "refusal") throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`); + content.refusal += event.delta; + } + break; + } + case "response.refusal.done": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "message") { + const content = getContent(output.content, event.content_index); + if (content.type !== "refusal") throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`); + content.refusal = event.refusal; + } + break; + } + case "response.function_call_arguments.delta": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "function_call") output.arguments += event.delta; + break; + } + case "response.function_call_arguments.done": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "function_call") output.arguments = event.arguments; + break; + } + case "response.reasoning_text.delta": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "reasoning") { + if (!output.content) throw new OpenAIError(`missing content at index ${event.content_index}`); + const content = getContent(output.content, event.content_index); + if (content.type !== "reasoning_text") throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`); + content.text += event.delta; + } + break; + } + case "response.reasoning_text.done": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "reasoning") { + if (!output.content) throw new OpenAIError(`missing content at index ${event.content_index}`); + const content = getContent(output.content, event.content_index); + if (content.type !== "reasoning_text") throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`); + content.text = event.text; + } + break; + } + case "response.reasoning_summary_part.added": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "reasoning") output.summary.push(structuredClone(event.part)); + break; + } + case "response.reasoning_summary_part.done": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "reasoning") { + getContent(output.summary, event.summary_index); + output.summary[event.summary_index] = structuredClone(event.part); + } + break; + } + case "response.reasoning_summary_text.delta": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "reasoning") { + const part = getContent(output.summary, event.summary_index); + part.text += event.delta; + } + break; + } + case "response.reasoning_summary_text.done": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "reasoning") { + const part = getContent(output.summary, event.summary_index); + part.text = event.text; + } + break; + } + case "response.custom_tool_call_input.delta": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "custom_tool_call") output.input += event.delta; + break; + } + case "response.custom_tool_call_input.done": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "custom_tool_call") output.input = event.input; + break; + } + case "response.mcp_call_arguments.delta": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "mcp_call") output.arguments += event.delta; + break; + } + case "response.mcp_call_arguments.done": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "mcp_call") output.arguments = event.arguments; + break; + } + case "response.code_interpreter_call_code.delta": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "code_interpreter_call") output.code = (output.code ?? "") + event.delta; + break; + } + case "response.code_interpreter_call_code.done": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "code_interpreter_call") output.code = event.code; + break; + } + case "response.code_interpreter_call.in_progress": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "code_interpreter_call") output.status = "in_progress"; + break; + } + case "response.code_interpreter_call.interpreting": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "code_interpreter_call") output.status = "interpreting"; + break; + } + case "response.code_interpreter_call.completed": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "code_interpreter_call") output.status = "completed"; + break; + } + case "response.file_search_call.in_progress": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "file_search_call") output.status = "in_progress"; + break; + } + case "response.file_search_call.searching": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "file_search_call") output.status = "searching"; + break; + } + case "response.file_search_call.completed": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "file_search_call") output.status = "completed"; + break; + } + case "response.web_search_call.in_progress": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "web_search_call") output.status = "in_progress"; + break; + } + case "response.web_search_call.searching": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "web_search_call") output.status = "searching"; + break; + } + case "response.web_search_call.completed": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "web_search_call") output.status = "completed"; + break; + } + case "response.image_generation_call.in_progress": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "image_generation_call") output.status = "in_progress"; + break; + } + case "response.image_generation_call.generating": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "image_generation_call") output.status = "generating"; + break; + } + case "response.image_generation_call.completed": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "image_generation_call") output.status = "completed"; + break; + } + case "response.mcp_call.in_progress": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "mcp_call") output.status = "in_progress"; + break; + } + case "response.mcp_call.completed": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "mcp_call") output.status = "completed"; + break; + } + case "response.mcp_call.failed": { + const output = getOutput(snapshot, event.output_index); + if (output.type === "mcp_call") output.status = "failed"; + break; + } + case "response.created": + case "response.queued": + case "response.in_progress": + case "response.completed": + case "response.failed": + case "response.incomplete": + snapshot = cloneResponse(event.response); + break; + case "response.audio.delta": + case "response.audio.done": + case "response.audio.transcript.delta": + case "response.audio.transcript.done": + case "response.image_generation_call.partial_image": + case "response.mcp_list_tools.in_progress": + case "response.mcp_list_tools.completed": + case "response.mcp_list_tools.failed": + case "keepalive": + case "error": break; + default: assertNever(event); + } + return snapshot; +} +function cloneResponse(response) { + const snapshot = structuredClone(response); + if (!Object.getOwnPropertyDescriptor(snapshot, "output_text") || snapshot.output_text == null) addOutputText(snapshot); + return snapshot; +} +function getOutput(snapshot, outputIndex) { + const output = snapshot.output[outputIndex]; + if (!output) throw new OpenAIError(`missing output at index ${outputIndex}`); + return output; +} +function getContent(content, contentIndex) { + const part = content[contentIndex]; + if (!part) throw new OpenAIError(`missing content at index ${contentIndex}`); + return part; +} +function assertNever(value) { + throw new OpenAIError(`Unhandled response stream event: ${JSON.stringify(value)}`); +} +//#endregion +//#region node_modules/openai/lib/responses/ResponseStream.mjs +var _ResponseStream_instances; +var _ResponseStream_params; +var _ResponseStream_currentResponseSnapshot; +var _ResponseStream_finalResponse; +var _ResponseStream_beginRequest; +var _ResponseStream_addEvent; +var _ResponseStream_endRequest; +var ResponseStream = class ResponseStream extends EventStream { + constructor(params) { + super(); + _ResponseStream_instances.add(this); + _ResponseStream_params.set(this, void 0); + _ResponseStream_currentResponseSnapshot.set(this, void 0); + _ResponseStream_finalResponse.set(this, void 0); + __classPrivateFieldSet(this, _ResponseStream_params, params, "f"); + } + static createResponse(client, params, options) { + const runner = new ResponseStream(params); + runner._run(() => runner._createOrRetrieveResponse(client, params, { + ...options, + headers: { + ...options?.headers, + "X-Stainless-Helper-Method": "stream" + } + })); + return runner; + } + static fromReadableStream(stream) { + const runner = new ResponseStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + async _createOrRetrieveResponse(client, params, options) { + this._listenForAbort(options?.signal); + __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); + let stream; + let starting_after = null; + if ("response_id" in params) { + stream = await client.responses.retrieve(params.response_id, { stream: true }, { + ...options, + signal: this.controller.signal, + stream: true + }); + starting_after = params.starting_after ?? null; + } else stream = await client.responses.create({ + ...params, + stream: true + }, { + ...options, + signal: this.controller.signal + }); + this._connected(); + for await (const event of stream) __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); + } + async _fromReadableStream(readableStream, options) { + this._listenForAbort(options?.signal); + __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, null); + if (stream.controller.signal?.aborted) throw new APIUserAbortError(); + return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); + } + [(_ResponseStream_params = /* @__PURE__ */ new WeakMap(), _ResponseStream_currentResponseSnapshot = /* @__PURE__ */ new WeakMap(), _ResponseStream_finalResponse = /* @__PURE__ */ new WeakMap(), _ResponseStream_instances = /* @__PURE__ */ new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() { + if (this.ended) return; + __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f"); + }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event, starting_after) { + if (this.ended) return; + const maybeEmit = (name, event) => { + if (starting_after == null || event.sequence_number > starting_after) this._emit(name, event); + }; + const response = accumulateResponse(event, __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f")); + __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, response, "f"); + maybeEmit("event", event); + switch (event.type) { + case "response.output_text.delta": { + const output = response.output[event.output_index]; + if (!output) throw new OpenAIError(`missing output at index ${event.output_index}`); + if (output.type === "message") { + const content = output.content[event.content_index]; + if (!content) throw new OpenAIError(`missing content at index ${event.content_index}`); + if (content.type !== "output_text") throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`); + maybeEmit("response.output_text.delta", { + ...event, + snapshot: content.text + }); + } + break; + } + case "response.function_call_arguments.delta": { + const output = response.output[event.output_index]; + if (!output) throw new OpenAIError(`missing output at index ${event.output_index}`); + if (output.type === "function_call") maybeEmit("response.function_call_arguments.delta", { + ...event, + snapshot: output.arguments + }); + break; + } + default: + maybeEmit(event.type, event); + break; + } + }, _ResponseStream_endRequest = function _ResponseStream_endRequest() { + if (this.ended) throw new OpenAIError(`stream has ended, this shouldn't happen`); + const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); + if (!snapshot) throw new OpenAIError(`request ended without sending any events`); + __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f"); + const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f")); + __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f"); + return parsedResponse; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("event", (event) => { + const reader = readQueue.shift(); + if (reader) reader.resolve(event); + else pushQueue.push(event); + }); + 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((event) => event ? { + value: event, + done: false + } : { + value: void 0, + done: true + }); + } + return { + value: pushQueue.shift(), + done: false + }; + }, + return: async () => { + this.abort(); + return { + value: void 0, + done: true + }; + } + }; + } + /** + * @returns a promise that resolves with the final Response, or rejects + * if an error occurred or the stream ended prematurely without producing a REsponse. + */ + async finalResponse() { + await this.done(); + const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, "f"); + if (!response) throw new OpenAIError("stream ended without producing a ChatCompletion"); + return response; + } +}; +function finalizeResponse(snapshot, params) { + return maybeParseResponse(snapshot, params); +} +//#endregion +//#region node_modules/openai/resources/responses/input-items.mjs +var InputItems = class extends APIResource { + /** + * Returns a list of input items for a given response. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const responseItem of client.responses.inputItems.list( + * 'response_id', + * )) { + * // ... + * } + * ``` + */ + list(responseID, query = {}, options) { + return this._client.getAPIList(path`/responses/${responseID}/input_items`, CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/responses/input-tokens.mjs +var InputTokens = class extends APIResource { + /** + * Returns input token counts of the request. + * + * Returns an object with `object` set to `response.input_tokens` and an + * `input_tokens` count. + * + * @example + * ```ts + * const response = await client.responses.inputTokens.count(); + * ``` + */ + count(body = {}, options) { + return this._client.post("/responses/input_tokens", { + body, + ...options, + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/responses/responses.mjs +var Responses = class extends APIResource { + constructor() { + super(...arguments); + this.inputItems = new InputItems(this._client); + this.inputTokens = new InputTokens(this._client); + } + create(body, options) { + return this._client.post("/responses", { + body, + ...options, + stream: body.stream ?? false, + __security: { bearerAuth: true } + })._thenUnwrap((rsp) => { + if ("object" in rsp && rsp.object === "response") addOutputText(rsp); + return rsp; + }); + } + retrieve(responseID, query = {}, options) { + return this._client.get(path`/responses/${responseID}`, { + query, + ...options, + stream: query?.stream ?? false, + __security: { bearerAuth: true } + })._thenUnwrap((rsp) => { + if ("object" in rsp && rsp.object === "response") addOutputText(rsp); + return rsp; + }); + } + /** + * Deletes a model response with the given ID. + * + * @example + * ```ts + * await client.responses.delete( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + delete(responseID, options) { + return this._client.delete(path`/responses/${responseID}`, { + ...options, + headers: buildHeaders([{ Accept: "*/*" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + parse(body, options) { + return this._client.responses.create(body, options)._thenUnwrap((response) => parseResponse(response, body)); + } + /** + * Creates a model response stream + */ + stream(body, options) { + return ResponseStream.createResponse(this._client, body, options); + } + /** + * Cancels a model response with the given ID. Only responses created with the + * `background` parameter set to `true` can be cancelled. + * [Learn more](https://platform.openai.com/docs/guides/background). + * + * @example + * ```ts + * const response = await client.responses.cancel( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + cancel(responseID, options) { + return this._client.post(path`/responses/${responseID}/cancel`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Compact a conversation. Returns a compacted response object. + * + * Learn when and how to compact long-running conversations in the + * [conversation state guide](https://platform.openai.com/docs/guides/conversation-state#managing-the-context-window). + * For ZDR-compatible compaction details, see + * [Compaction (advanced)](https://platform.openai.com/docs/guides/conversation-state#compaction-advanced). + * + * @example + * ```ts + * const compactedResponse = await client.responses.compact({ + * model: 'gpt-5.6-sol', + * }); + * ``` + */ + compact(body, options) { + return this._client.post("/responses/compact", { + body, + ...options, + __security: { bearerAuth: true } + }); + } +}; +Responses.InputItems = InputItems; +Responses.InputTokens = InputTokens; +//#endregion +//#region node_modules/openai/resources/skills/content.mjs +var Content$1 = class extends APIResource { + /** + * Download a skill zip bundle by its ID. + */ + retrieve(skillID, options) { + return this._client.get(path`/skills/${skillID}/content`, { + ...options, + headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), + __security: { bearerAuth: true }, + __binaryResponse: true + }); + } +}; +//#endregion +//#region node_modules/openai/resources/skills/versions/content.mjs +var Content = class extends APIResource { + /** + * Download a skill version zip bundle. + */ + retrieve(version, params, options) { + const { skill_id } = params; + return this._client.get(path`/skills/${skill_id}/versions/${version}/content`, { + ...options, + headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), + __security: { bearerAuth: true }, + __binaryResponse: true + }); + } +}; +//#endregion +//#region node_modules/openai/resources/skills/versions/versions.mjs +var Versions = class extends APIResource { + constructor() { + super(...arguments); + this.content = new Content(this._client); + } + /** + * Create a new immutable skill version. + */ + create(skillID, body = {}, options) { + return this._client.post(path`/skills/${skillID}/versions`, maybeMultipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } + /** + * Get a specific skill version. + */ + retrieve(version, params, options) { + const { skill_id } = params; + return this._client.get(path`/skills/${skill_id}/versions/${version}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List skill versions for a skill. + */ + list(skillID, query = {}, options) { + return this._client.getAPIList(path`/skills/${skillID}/versions`, CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete a skill version. + */ + delete(version, params, options) { + const { skill_id } = params; + return this._client.delete(path`/skills/${skill_id}/versions/${version}`, { + ...options, + __security: { bearerAuth: true } + }); + } +}; +Versions.Content = Content; +//#endregion +//#region node_modules/openai/resources/skills/skills.mjs +var Skills = class extends APIResource { + constructor() { + super(...arguments); + this.content = new Content$1(this._client); + this.versions = new Versions(this._client); + } + /** + * Create a new skill. + */ + create(body = {}, options) { + return this._client.post("/skills", maybeMultipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } + /** + * Get a skill by its ID. + */ + retrieve(skillID, options) { + return this._client.get(path`/skills/${skillID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Update the default version pointer for a skill. + */ + update(skillID, body, options) { + return this._client.post(path`/skills/${skillID}`, { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List all skills for the current project. + */ + list(query = {}, options) { + return this._client.getAPIList("/skills", CursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Delete a skill by its ID. + */ + delete(skillID, options) { + return this._client.delete(path`/skills/${skillID}`, { + ...options, + __security: { bearerAuth: true } + }); + } +}; +Skills.Content = Content$1; +Skills.Versions = Versions; +//#endregion +//#region node_modules/openai/resources/uploads/parts.mjs +/** +* Use Uploads to upload large files in multiple parts. +*/ +var Parts = class extends APIResource { + /** + * Adds a + * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. + * A Part represents a chunk of bytes from the file you are trying to upload. + * + * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload + * maximum of 8 GB. + * + * It is possible to add multiple Parts in parallel. You can decide the intended + * order of the Parts when you + * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). + */ + create(uploadID, body, options) { + return this._client.post(path`/uploads/${uploadID}/parts`, multipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } +}; +//#endregion +//#region node_modules/openai/resources/uploads/uploads.mjs +/** +* Use Uploads to upload large files in multiple parts. +*/ +var Uploads = class extends APIResource { + constructor() { + super(...arguments); + this.parts = new Parts(this._client); + } + /** + * Creates an intermediate + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object + * that you can add + * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. + * Currently, an Upload can accept at most 8 GB in total and expires after an hour + * after you create it. + * + * Once you complete the Upload, we will create a + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * contains all the parts you uploaded. This File is usable in the rest of our + * platform as a regular File object. + * + * For certain `purpose` values, the correct `mime_type` must be specified. Please + * refer to documentation for the + * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). + * + * For guidance on the proper filename extensions for each purpose, please follow + * the documentation on + * [creating a File](https://platform.openai.com/docs/api-reference/files/create). + * + * Returns the Upload object with status `pending`. + */ + create(body, options) { + return this._client.post("/uploads", { + body, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Cancels the Upload. No Parts may be added after an Upload is cancelled. + * + * Returns the Upload object with status `cancelled`. + */ + cancel(uploadID, options) { + return this._client.post(path`/uploads/${uploadID}/cancel`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Completes the + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). + * + * Within the returned Upload object, there is a nested + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * is ready to use in the rest of the platform. + * + * You can specify the order of the Parts by passing in an ordered list of the Part + * IDs. + * + * The number of bytes uploaded upon completion must match the number of bytes + * initially specified when creating the Upload object. No Parts may be added after + * an Upload is completed. Returns the Upload object with status `completed`, + * including an additional `file` property containing the created usable File + * object. + */ + complete(uploadID, body, options) { + return this._client.post(path`/uploads/${uploadID}/complete`, { + body, + ...options, + __security: { bearerAuth: true } + }); + } +}; +Uploads.Parts = Parts; +//#endregion +//#region node_modules/openai/lib/Util.mjs +/** +* Like `Promise.allSettled()` but throws an error if any promises are rejected. +*/ +var allSettledWithThrow = async (promises) => { + const results = await Promise.allSettled(promises); + const rejected = results.filter((result) => result.status === "rejected"); + if (rejected.length) { + for (const result of rejected) console.error(result.reason); + throw new Error(`${rejected.length} promise(s) failed - see the above errors`); + } + const values = []; + for (const result of results) if (result.status === "fulfilled") values.push(result.value); + return values; +}; +//#endregion +//#region node_modules/openai/resources/vector-stores/file-batches.mjs +var FileBatches = class extends APIResource { + /** + * Create a vector store file batch. + */ + create(vectorStoreID, body, options) { + return this._client.post(path`/vector_stores/${vectorStoreID}/file_batches`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Retrieves a vector store file batch. + */ + retrieve(batchID, params, options) { + const { vector_store_id } = params; + return this._client.get(path`/vector_stores/${vector_store_id}/file_batches/${batchID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Cancel a vector store file batch. This attempts to cancel the processing of + * files in this batch as soon as possible. + */ + cancel(batchID, params, options) { + const { vector_store_id } = params; + return this._client.post(path`/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Create a vector store batch and poll until all files have been processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const batch = await this.create(vectorStoreId, body); + return await this.poll(vectorStoreId, batch.id, options); + } + /** + * Returns a list of vector store files in a batch. + */ + listFiles(batchID, params, options) { + const { vector_store_id, ...query } = params; + return this._client.getAPIList(path`/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Wait for the given file batch to be processed. + * + * Note: this will return even if one of the files failed to process, you need to + * check batch.file_counts.failed_count to handle this case. + */ + async poll(vectorStoreID, batchID, options) { + const headers = buildHeaders([options?.headers, { + "X-Stainless-Poll-Helper": "true", + "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0 + }]); + while (true) { + const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, { + ...options, + headers + }).withResponse(); + switch (batch.status) { + case "in_progress": + let sleepInterval = 5e3; + if (options?.pollIntervalMs) sleepInterval = options.pollIntervalMs; + else { + const headerInterval = response.headers.get("openai-poll-after-ms"); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) sleepInterval = headerIntervalMs; + } + } + await sleep(sleepInterval); + break; + case "failed": + case "cancelled": + case "completed": return batch; + } + } + } + /** + * Uploads the given files concurrently and then creates a vector store file batch. + * + * The concurrency limit is configurable using the `maxConcurrency` parameter. + */ + async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { + if (files == null || files.length == 0) throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); + const configuredConcurrency = options?.maxConcurrency ?? 5; + const concurrencyLimit = Math.min(configuredConcurrency, files.length); + const client = this._client; + const fileIterator = files.values(); + const allFileIds = [...fileIds]; + async function processFiles(iterator) { + for (let item of iterator) { + const fileObj = await client.files.create({ + file: item, + purpose: "assistants" + }, options); + allFileIds.push(fileObj.id); + } + } + await allSettledWithThrow(Array(concurrencyLimit).fill(fileIterator).map(processFiles)); + return await this.createAndPoll(vectorStoreId, { file_ids: allFileIds }); + } +}; +//#endregion +//#region node_modules/openai/resources/vector-stores/files.mjs +var Files = class extends APIResource { + /** + * Create a vector store file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). + */ + create(vectorStoreID, body, options) { + return this._client.post(path`/vector_stores/${vectorStoreID}/files`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Retrieves a vector store file. + */ + retrieve(fileID, params, options) { + const { vector_store_id } = params; + return this._client.get(path`/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Update attributes on a vector store file. + */ + update(fileID, params, options) { + const { vector_store_id, ...body } = params; + return this._client.post(path`/vector_stores/${vector_store_id}/files/${fileID}`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Returns a list of vector store files. + */ + list(vectorStoreID, query = {}, options) { + return this._client.getAPIList(path`/vector_stores/${vectorStoreID}/files`, CursorPage, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Delete a vector store file. This will remove the file from the vector store but + * the file itself will not be deleted. To delete the file, use the + * [delete file](https://platform.openai.com/docs/api-reference/files/delete) + * endpoint. + */ + delete(fileID, params, options) { + const { vector_store_id } = params; + return this._client.delete(path`/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Attach a file to the given vector store and wait for it to be processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const file = await this.create(vectorStoreId, body, options); + return await this.poll(vectorStoreId, file.id, options); + } + /** + * Wait for the vector store file to finish processing. + * + * Note: this will return even if the file failed to process, you need to check + * file.last_error and file.status to handle these cases + */ + async poll(vectorStoreID, fileID, options) { + const headers = buildHeaders([options?.headers, { + "X-Stainless-Poll-Helper": "true", + "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0 + }]); + while (true) { + const fileResponse = await this.retrieve(fileID, { vector_store_id: vectorStoreID }, { + ...options, + headers + }).withResponse(); + const file = fileResponse.data; + switch (file.status) { + case "in_progress": + let sleepInterval = 5e3; + if (options?.pollIntervalMs) sleepInterval = options.pollIntervalMs; + else { + const headerInterval = fileResponse.response.headers.get("openai-poll-after-ms"); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) sleepInterval = headerIntervalMs; + } + } + await sleep(sleepInterval); + break; + case "failed": + case "completed": return file; + } + } + } + /** + * Upload a file to the `files` API and then attach it to the given vector store. + * + * Note the file will be asynchronously processed (you can use the alternative + * polling helper method to wait for processing to complete). + */ + async upload(vectorStoreId, file, options) { + const fileInfo = await this._client.files.create({ + file, + purpose: "assistants" + }, options); + return this.create(vectorStoreId, { file_id: fileInfo.id }, options); + } + /** + * Add a file to a vector store and poll until processing is complete. + */ + async uploadAndPoll(vectorStoreId, file, options) { + const fileInfo = await this.upload(vectorStoreId, file, options); + return await this.poll(vectorStoreId, fileInfo.id, options); + } + /** + * Retrieve the parsed contents of a vector store file. + */ + content(fileID, params, options) { + const { vector_store_id } = params; + return this._client.getAPIList(path`/vector_stores/${vector_store_id}/files/${fileID}/content`, Page, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +//#endregion +//#region node_modules/openai/resources/vector-stores/vector-stores.mjs +var VectorStores = class extends APIResource { + constructor() { + super(...arguments); + this.files = new Files(this._client); + this.fileBatches = new FileBatches(this._client); + } + /** + * Create a vector store. + */ + create(body, options) { + return this._client.post("/vector_stores", { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Retrieves a vector store. + */ + retrieve(vectorStoreID, options) { + return this._client.get(path`/vector_stores/${vectorStoreID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Modifies a vector store. + */ + update(vectorStoreID, body, options) { + return this._client.post(path`/vector_stores/${vectorStoreID}`, { + body, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Returns a list of vector stores. + */ + list(query = {}, options) { + return this._client.getAPIList("/vector_stores", CursorPage, { + query, + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Delete a vector store. + */ + delete(vectorStoreID, options) { + return this._client.delete(path`/vector_stores/${vectorStoreID}`, { + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } + /** + * Search a vector store for relevant chunks based on a query and file attributes + * filter. + */ + search(vectorStoreID, body, options) { + return this._client.getAPIList(path`/vector_stores/${vectorStoreID}/search`, Page, { + body, + method: "post", + ...options, + headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + __security: { bearerAuth: true } + }); + } +}; +VectorStores.Files = Files; +VectorStores.FileBatches = FileBatches; +//#endregion +//#region node_modules/openai/resources/videos.mjs +var Videos = class extends APIResource { + /** + * Create a new video generation job from a prompt and optional reference assets. + */ + create(body, options) { + return this._client.post("/videos", multipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } + /** + * Fetch the latest metadata for a generated video. + */ + retrieve(videoID, options) { + return this._client.get(path`/videos/${videoID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * List recently generated videos for the current project. + */ + list(query = {}, options) { + return this._client.getAPIList("/videos", ConversationCursorPage, { + query, + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Permanently delete a completed or failed video and its stored assets. + */ + delete(videoID, options) { + return this._client.delete(path`/videos/${videoID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Create a character from an uploaded video. + */ + createCharacter(body, options) { + return this._client.post("/videos/characters", multipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } + /** + * Download the generated video bytes or a derived preview asset. + * + * Streams the rendered video content for the specified video job. + */ + downloadContent(videoID, query = {}, options) { + return this._client.get(path`/videos/${videoID}/content`, { + query, + ...options, + headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), + __security: { bearerAuth: true }, + __binaryResponse: true + }); + } + /** + * Create a new video generation job by editing a source video or existing + * generated video. + */ + edit(body, options) { + return this._client.post("/videos/edits", multipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } + /** + * Create an extension of a completed video. + */ + extend(body, options) { + return this._client.post("/videos/extensions", multipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } + /** + * Fetch a character. + */ + getCharacter(characterID, options) { + return this._client.get(path`/videos/characters/${characterID}`, { + ...options, + __security: { bearerAuth: true } + }); + } + /** + * Create a remix of a completed video using a refreshed prompt. + */ + remix(videoID, body, options) { + return this._client.post(path`/videos/${videoID}/remix`, maybeMultipartFormRequestOptions({ + body, + ...options, + __security: { bearerAuth: true } + }, this._client)); + } +}; +//#endregion +//#region node_modules/openai/resources/webhooks/webhooks.mjs +var _Webhooks_instances; +var _Webhooks_validateSecret; +var _Webhooks_getRequiredHeader; +var Webhooks = class extends APIResource { + constructor() { + super(...arguments); + _Webhooks_instances.add(this); + } + /** + * Validates that the given payload was sent by OpenAI and parses the payload. + */ + async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + await this.verifySignature(payload, headers, secret, tolerance); + return JSON.parse(payload); + } + /** + * Validates whether or not the webhook payload was sent by OpenAI. + * + * An error will be raised if the webhook payload was not sent by OpenAI. + * + * @param payload - The webhook payload + * @param headers - The webhook headers + * @param secret - The webhook secret (optional, will use client secret if not provided) + * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes) + */ + async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + if (typeof crypto === "undefined" || typeof crypto.subtle.importKey !== "function" || typeof crypto.subtle.verify !== "function") throw new Error("Webhook signature verification is only supported when the `crypto` global is defined"); + __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret); + const headersObj = buildHeaders([headers]).values; + const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature"); + const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp"); + const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id"); + const timestampSeconds = parseInt(timestamp, 10); + if (isNaN(timestampSeconds)) throw new InvalidWebhookSignatureError("Invalid webhook timestamp format"); + const nowSeconds = Math.floor(Date.now() / 1e3); + if (nowSeconds - timestampSeconds > tolerance) throw new InvalidWebhookSignatureError("Webhook timestamp is too old"); + if (timestampSeconds > nowSeconds + tolerance) throw new InvalidWebhookSignatureError("Webhook timestamp is too new"); + const signatures = signatureHeader.split(" ").map((part) => part.startsWith("v1,") ? part.substring(3) : part); + const decodedSecret = secret.startsWith("whsec_") ? Buffer.from(secret.replace("whsec_", ""), "base64") : Buffer.from(secret, "utf-8"); + const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; + const key = await crypto.subtle.importKey("raw", decodedSecret, { + name: "HMAC", + hash: "SHA-256" + }, false, ["verify"]); + for (const signature of signatures) try { + const signatureBytes = Buffer.from(signature, "base64"); + if (await crypto.subtle.verify("HMAC", key, signatureBytes, new TextEncoder().encode(signedPayload))) return; + } catch { + continue; + } + throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature"); + } +}; +_Webhooks_instances = /* @__PURE__ */ new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret(secret) { + if (typeof secret !== "string" || secret.length === 0) throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`); +}, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader(headers, name) { + if (!headers) throw new Error(`Headers are required`); + const value = headers.get(name); + if (value === null || value === void 0) throw new Error(`Missing required header: ${name}`); + return value; +}; +//#endregion +//#region node_modules/openai/internal/provider.mjs +/** +* A provider factory such as `bedrock(options)` captures configuration in a +* definition, while every OpenAI client receives a fresh runtime from +* `definition.configure()`. Keeping definitions out of the provider object +* makes providers opaque and prevents arbitrary objects from imitating one. +* It also leaves provider-specific dependencies outside the core SDK. +* +* The registry lives on `globalThis` under a global symbol so a provider made +* by one copy of the package still works with another copy, including mixed +* CommonJS and ESM installations. The WeakMap avoids retaining discarded +* provider configurations. +*/ +var providerDefinitionsKey = Symbol.for("openai.node.providerDefinitions.v1"); +var providerGlobal = globalThis; +var existingProviderDefinitions = providerGlobal[providerDefinitionsKey]; +var providerDefinitions = existingProviderDefinitions ?? /* @__PURE__ */ new WeakMap(); +if (!existingProviderDefinitions) Object.defineProperty(providerGlobal, providerDefinitionsKey, { value: providerDefinitions }); +function configureProvider(provider) { + const definition = providerDefinitions.get(provider); + if (!definition) throw new Error("Invalid provider. Providers must be created with createProvider()."); + return definition.configure(); +} +//#endregion +//#region node_modules/openai/client.mjs +var _OpenAI_instances; +var _a; +var _OpenAI_encoder; +var _OpenAI_baseURLOverridden; +var WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER = "workload-identity-auth"; +/** +* API Client for interfacing with the OpenAI API. +*/ +var OpenAI = class { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.adminAPIKey=process.env['OPENAI_ADMIN_KEY'] ?? null] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] + * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {Provider} [opts.provider] - Configure a third-party API provider. Mutually exclusive with top-level authentication and base URL options. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor(clientOptions = {}) { + _OpenAI_instances.add(this); + _OpenAI_encoder.set(this, void 0); + /** + * Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position. + */ + this.completions = new Completions(this); + this.chat = new Chat(this); + /** + * Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. + */ + this.embeddings = new Embeddings(this); + /** + * Files are used to upload documents that can be used with features like Assistants and Fine-tuning. + */ + this.files = new Files$1(this); + /** + * Given a prompt and/or an input image, the model will generate a new image. + */ + this.images = new Images(this); + this.audio = new Audio(this); + /** + * Given text and/or image inputs, classifies if those inputs are potentially harmful. + */ + this.moderations = new Moderations(this); + /** + * List and describe the various models available in the API. + */ + this.models = new Models(this); + this.fineTuning = new FineTuning(this); + this.graders = new Graders(this); + this.vectorStores = new VectorStores(this); + this.webhooks = new Webhooks(this); + this.beta = new Beta(this); + /** + * Create large batches of API requests to run asynchronously. + */ + this.batches = new Batches(this); + /** + * Use Uploads to upload large files in multiple parts. + */ + this.uploads = new Uploads(this); + this.admin = new Admin(this); + this.responses = new Responses(this); + this.realtime = new Realtime(this); + /** + * Manage conversations and conversation items. + */ + this.conversations = new Conversations(this); + /** + * Manage and run evals in the OpenAI platform. + */ + this.evals = new Evals(this); + this.containers = new Containers(this); + this.skills = new Skills(this); + this.videos = new Videos(this); + const provider = clientOptions.provider; + if (provider) { + const conflictingOptions = [ + "apiKey", + "adminAPIKey", + "workloadIdentity", + "baseURL" + ].filter((key) => clientOptions[key] != null); + if (conflictingOptions.length) throw new OpenAIError(`The \`provider\` option cannot be used with ${conflictingOptions.map((key) => `\`${key}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`); + } + const { baseURL = provider ? null : readEnv("OPENAI_BASE_URL"), apiKey = provider ? null : readEnv("OPENAI_API_KEY") ?? null, adminAPIKey = provider ? null : readEnv("OPENAI_ADMIN_KEY") ?? null, organization = provider ? null : readEnv("OPENAI_ORG_ID") ?? null, project = provider ? null : readEnv("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv("OPENAI_WEBHOOK_SECRET") ?? null, workloadIdentity, ...opts } = clientOptions; + const providerRuntime = provider ? configureProvider(provider) : void 0; + const options = { + apiKey, + adminAPIKey, + organization, + project, + webhookSecret, + workloadIdentity, + provider, + ...opts, + baseURL: providerRuntime?.baseURL ?? (baseURL || `https://api.openai.com/v1`) + }; + if (apiKey && workloadIdentity) throw new OpenAIError("The `apiKey` and `workloadIdentity` options are mutually exclusive"); + if (!providerRuntime && !apiKey && !adminAPIKey && !workloadIdentity) throw new OpenAIError("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable."); + 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"); + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("OPENAI_LOG"), "process.env['OPENAI_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f"); + const customHeadersEnv = provider ? void 0 : readEnv("OPENAI_CUSTOM_HEADERS"); + if (customHeadersEnv) { + const parsed = {}; + for (const line of customHeadersEnv.split("\n")) { + const colon = line.indexOf(":"); + if (colon >= 0) parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim(); + } + options.defaultHeaders = buildHeaders([parsed, options.defaultHeaders]); + } + this._options = options; + this._provider = providerRuntime; + if (workloadIdentity) this._workloadIdentityAuth = new WorkloadIdentityAuth(workloadIdentity, this.fetch); + this.apiKey = typeof apiKey === "string" ? apiKey : null; + this.adminAPIKey = adminAPIKey; + this.organization = organization; + this.project = project; + this.webhookSecret = webhookSecret; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const inheritedProvider = this._options.provider; + const provider = options.provider ?? inheritedProvider; + const inheritedOptions = { + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this._options.apiKey, + adminAPIKey: this.adminAPIKey, + workloadIdentity: this._options.workloadIdentity, + organization: this.organization, + project: this.project, + webhookSecret: this.webhookSecret + }; + if (provider) { + delete inheritedOptions.apiKey; + delete inheritedOptions.adminAPIKey; + delete inheritedOptions.workloadIdentity; + delete inheritedOptions.baseURL; + if (provider !== inheritedProvider) { + delete inheritedOptions.organization; + delete inheritedOptions.project; + delete inheritedOptions.defaultHeaders; + } + } + return new this.constructor({ + ...inheritedOptions, + ...options, + provider + }); + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }, schemes = { + bearerAuth: true, + adminAPIKeyAuth: true + }) { + if (values.get("authorization") || values.get("api-key")) return; + if (nulls.has("authorization") || nulls.has("api-key")) return; + if (this._workloadIdentityAuth && schemes.bearerAuth) return; + throw new Error("Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the \"Authorization\" or \"api-key\" headers to be explicitly omitted"); + } + async authHeaders(opts, schemes = { + bearerAuth: true, + adminAPIKeyAuth: true + }) { + return buildHeaders([schemes.bearerAuth ? await this.bearerAuth(opts) : null, schemes.adminAPIKeyAuth ? await this.adminAPIKeyAuth(opts) : null]); + } + async bearerAuth(opts) { + if (this._workloadIdentityAuth) return buildHeaders([{ Authorization: `Bearer ${await this._workloadIdentityAuth.getToken()}` }]); + if (this.apiKey == null) return; + return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); + } + async adminAPIKeyAuth(opts) { + if (this.adminAPIKey == null) return; + return buildHeaders([{ Authorization: `Bearer ${this.adminAPIKey}` }]); + } + stringifyQuery(query) { + return stringifyQuery(query); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + async _callApiKey() { + if (this._provider) return false; + const apiKey = this._options.apiKey; + if (typeof apiKey !== "function") return false; + let token; + try { + token = await apiKey(); + } catch (err) { + if (err instanceof OpenAIError) throw err; + throw new OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`, { cause: err }); + } + if (typeof token !== "string" || !token) throw new OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`); + this.apiKey = token; + return true; + } + buildURL(path, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL(path) ? new URL(path) : new URL(baseURL + (baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + const pathQuery = Object.fromEntries(url.searchParams); + if (!isEmptyObj$1(defaultQuery) || !isEmptyObj$1(pathQuery)) query = { + ...pathQuery, + ...defaultQuery, + ...query + }; + if (typeof query === "object" && query && !Array.isArray(query)) url.search = this.stringifyQuery(query); + return url.toString(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { + if (this._provider) return; + if ((options.__security ?? { bearerAuth: true }).bearerAuth) await this._callApiKey(); + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) {} + 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((opts) => { + return { + method, + path, + ...opts + }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) retriesRemaining = maxRetries; + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); + const hasStreamingBody = options.__metadata?.["hasStreamingBody"] === true; + await this.prepareRequest(req, { + url, + options + }); + await this._provider?.prepareRequest?.(req, { + url, + options + }); + /** Not an API request ID, just for correlating local log entries. */ + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) throw new APIUserAbortError(); + const security = options.__security ?? { bearerAuth: true }; + const controller = new AbortController(); + const response = await this.fetchWithAuth(url, req, timeout, controller, security).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) throw new APIUserAbortError(); + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining && !hasStreamingBody) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + const terminalMessage = hasStreamingBody ? "error; streaming body cannot be retried" : "error; no more retries left"; + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${terminalMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${terminalMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (response instanceof OAuthError || response instanceof SubjectTokenProviderError) throw response; + if (isTimeout) throw new APIConnectionTimeoutError(); + throw new APIConnectionError({ + message: getConnectionErrorMessage(response), + cause: response + }); + } + const responseInfo = `[${requestLogID}${retryLogStr}${[...response.headers.entries()].filter(([name]) => name === "x-request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("")}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + if (response.status === 401 && this._workloadIdentityAuth && security.bearerAuth && !options.__metadata?.["hasStreamingBody"] && !options.__metadata?.["workloadIdentityTokenRefreshed"]) { + await CancelReadableStream(response.body); + this._workloadIdentityAuth.invalidateToken(); + return this.makeRequest({ + ...options, + __metadata: { + ...options.__metadata, + workloadIdentityTokenRefreshed: true + } + }, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry && !hasStreamingBody) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? hasStreamingBody ? `error; streaming body cannot be retried` : `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err) => castToError(err).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + throw this.makeStatusError(response.status, errJSON, errMessage, response.headers); + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { + response, + options, + controller, + requestLogID, + retryOfRequestLogID, + startTime + }; + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, opts && "then" in opts ? opts.then((opts) => ({ + method: "get", + path, + ...opts + })) : { + method: "get", + path, + ...opts + }); + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise(this, request, Page); + } + async fetchWithAuth(url, init, timeout, controller, schemes = { + bearerAuth: true, + adminAPIKeyAuth: true + }) { + if (this._workloadIdentityAuth && schemes.bearerAuth) { + const headers = init.headers; + const authHeader = headers.get("Authorization"); + if (!authHeader || authHeader === `Bearer ${WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER}`) { + const token = await this._workloadIdentityAuth.getToken(); + headers.set("Authorization", `Bearer ${token}`); + } + } + return await this.fetchWithTimeout(url, init, timeout, controller); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) fetchOptions.method = method.toUpperCase(); + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async 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, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) timeoutMillis = timeoutMs; + } + const retryAfterHeader = responseHeaders?.get("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 === void 0) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = .5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + return Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay) * (1 - Math.random() * .25) * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path, query, defaultBaseURL } = options; + const url = this.buildURL(path, query, defaultBaseURL); + if ("timeout" in options) validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body, isStreamingBody } = this.buildBody({ options }); + if (isStreamingBody) inputOptions.__metadata = { + ...inputOptions.__metadata, + hasStreamingBody: true + }; + return { + req: { + method, + headers: await this.buildHeaders({ + options: inputOptions, + method, + bodyHeaders, + retryCount + }), + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }, + url, + timeout: options.timeout + }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders(), + "OpenAI-Organization": this.organization, + "OpenAI-Project": this.project + }, + this._provider ? void 0 : await this.authHeaders(options, options.__security ?? { bearerAuth: true }), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + if (!this._provider) this.validateHeaders(headers, options.__security ?? { bearerAuth: true }); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options }) { + const { body, headers: rawHeaders } = options; + if (!body) { + if (body === void 0 && "body" in options) return { + ...__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { + body, + headers: buildHeaders([rawHeaders]) + }), + isStreamingBody: false + }; + return { + bodyHeaders: void 0, + body: void 0, + isStreamingBody: false + }; + } + const headers = buildHeaders([rawHeaders]); + const isReadableStream = typeof globalThis.ReadableStream !== "undefined" && body instanceof globalThis.ReadableStream; + const isRetryableBody = !isReadableStream && (typeof body === "string" || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof globalThis.Blob !== "undefined" && body instanceof globalThis.Blob || body instanceof URLSearchParams || body instanceof FormData); + if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || isReadableStream) return { + bodyHeaders: void 0, + body, + isStreamingBody: !isRetryableBody + }; + else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) return { + bodyHeaders: void 0, + body: ReadableStreamFrom(body), + isStreamingBody: true + }; + else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body), + isStreamingBody: false + }; + else return { + ...__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { + body, + headers + }), + isStreamingBody: false + }; + } +}; +_a = OpenAI, _OpenAI_encoder = /* @__PURE__ */ new WeakMap(), _OpenAI_instances = /* @__PURE__ */ new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() { + return this._provider !== void 0 || this.baseURL !== "https://api.openai.com/v1"; +}; +OpenAI.OpenAI = _a; +OpenAI.DEFAULT_TIMEOUT = 6e5; +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; +OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError; +OpenAI.toFile = toFile; +OpenAI.toStreamingFile = toStreamingFile; +OpenAI.Completions = Completions; +OpenAI.Chat = Chat; +OpenAI.Embeddings = Embeddings; +OpenAI.Files = Files$1; +OpenAI.Images = Images; +OpenAI.Audio = Audio; +OpenAI.Moderations = Moderations; +OpenAI.Models = Models; +OpenAI.FineTuning = FineTuning; +OpenAI.Graders = Graders; +OpenAI.VectorStores = VectorStores; +OpenAI.Webhooks = Webhooks; +OpenAI.Beta = Beta; +OpenAI.Batches = Batches; +OpenAI.Uploads = Uploads; +OpenAI.Admin = Admin; +OpenAI.Responses = Responses; +OpenAI.Realtime = Realtime; +OpenAI.Conversations = Conversations; +OpenAI.Evals = Evals; +OpenAI.Containers = Containers; +OpenAI.Skills = Skills; +OpenAI.Videos = Videos; +function getConnectionErrorMessage(error) { + if (isUndiciDispatcherVersionMismatchError(error)) return `Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`; +} +function isUndiciDispatcherVersionMismatchError(error) { + let current = error; + for (let i = 0; i < 8 && current && typeof current === "object"; i++) { + const err = current; + if (err.code === "UND_ERR_INVALID_ARG" && typeof err.message === "string" && err.message.includes("invalid onRequestStart method")) return true; + current = err.cause; + } + return false; +} +//#endregion +//#region node_modules/@langchain/openai/dist/utils/client.js +function _isOpenAIContextOverflowError(e) { + if (String(e).includes("context_length_exceeded")) return true; + if ("message" in e && typeof e.message === "string" && (e.message.includes("Input tokens exceed the configured limit") || e.message.includes("exceeds the context window") || e.message.includes("maximum context length"))) return true; + return false; +} +function wrapOpenAIClientError(e) { + if (!e || typeof e !== "object") return e; + let error; + if (e.constructor.name === APIConnectionTimeoutError.name && "message" in e && typeof e.message === "string") { + error = new Error(e.message); + error.name = "TimeoutError"; + } else if (e.constructor.name === APIUserAbortError.name && "message" in e && typeof e.message === "string") { + error = new Error(e.message); + error.name = "AbortError"; + } else if (_isOpenAIContextOverflowError(e)) error = ContextOverflowError.fromError(e); + else if ("status" in e && e.status === 400 && "message" in e && typeof e.message === "string" && e.message.includes("tool_calls")) error = addLangChainErrorFields(e, "INVALID_TOOL_RESULTS"); + else if ("status" in e && e.status === 401) error = addLangChainErrorFields(e, "MODEL_AUTHENTICATION"); + else if ("status" in e && e.status === 429) error = addLangChainErrorFields(e, "MODEL_RATE_LIMIT"); + else if ("status" in e && e.status === 404) error = addLangChainErrorFields(e, "MODEL_NOT_FOUND"); + else error = e; + return error; +} +//#endregion +//#region node_modules/@langchain/openai/dist/utils/misc.js +var iife$1 = (fn) => fn(); +function isReasoningModel(model) { + if (!model) return false; + if (/^o\d/.test(model ?? "")) return true; + if (model.startsWith("gpt-5") && !model.startsWith("gpt-5-chat")) return true; + return false; +} +function extractGenericMessageCustomRole(message) { + if (message.role !== "system" && message.role !== "developer" && message.role !== "assistant" && message.role !== "user" && message.role !== "function" && message.role !== "tool") console.warn(`Unknown message role: ${message.role}`); + return message.role; +} +function getFilenameFromMetadata(block) { + return block.metadata?.filename ?? block.metadata?.name ?? block.metadata?.title; +} +var LC_AUTOGENERATED_FILENAME = "LC_AUTOGENERATED"; +function getRequiredFilenameFromMetadata(block) { + const filename = block.metadata?.filename ?? block.metadata?.name ?? block.metadata?.title; + if (!filename) { + console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."); + return LC_AUTOGENERATED_FILENAME; + } + return filename; +} +function messageToOpenAIRole(message) { + const type = message._getType(); + switch (type) { + 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: ${type}`); + } +} +function _modelPrefersResponsesAPI(model) { + if (model.includes("gpt-5.2-pro")) return true; + if (model.includes("gpt-5.4-pro")) return true; + if (model.includes("gpt-5.5-pro")) return true; + if (model.includes("codex")) return true; + return false; +} +//#endregion +//#region node_modules/@langchain/openai/dist/utils/azure.js +/** +* This function generates an endpoint URL for (Azure) OpenAI +* based on the configuration parameters provided. +* +* @param {OpenAIEndpointConfig} config - The configuration object for the (Azure) endpoint. +* +* @property {string} config.azureOpenAIApiDeploymentName - The deployment name of Azure OpenAI. +* @property {string} config.azureOpenAIApiInstanceName - The instance name of Azure OpenAI, e.g. `example-resource`. +* @property {string} config.azureOpenAIApiKey - The API Key for Azure OpenAI. +* @property {string} config.azureOpenAIBasePath - The base path for Azure OpenAI, e.g. `https://example-resource.azure.openai.com/openai/deployments/`. +* @property {string} config.baseURL - Some other custom base path URL. +* @property {string} config.azureOpenAIEndpoint - The endpoint for the Azure OpenAI instance, e.g. `https://example-resource.azure.openai.com/`. +* +* The function operates as follows: +* - If both `azureOpenAIBasePath` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`). +* - If both `azureOpenAIEndpoint` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`). +* - If `azureOpenAIApiKey` is provided, it checks for `azureOpenAIApiInstanceName` and `azureOpenAIApiDeploymentName` and throws an error if any of these is missing. If both are provided, it generates an URL incorporating these parameters. +* - If none of the above conditions are met, return any custom `baseURL`. +* - The function returns the generated URL as a string, or undefined if no custom paths are specified. +* +* @throws Will throw an error if the necessary parameters for generating the URL are missing. +* +* @returns {string | undefined} The generated (Azure) OpenAI endpoint URL. +*/ +function getEndpoint(config) { + const { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, baseURL, azureADTokenProvider, azureOpenAIEndpoint } = config; + if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIBasePath && azureOpenAIApiDeploymentName) return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`; + if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIEndpoint && azureOpenAIApiDeploymentName) return `${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`; + if (azureOpenAIApiKey || azureADTokenProvider) { + 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; +} +function isHeaders(headers) { + return typeof Headers !== "undefined" && headers !== null && typeof headers === "object" && Object.prototype.toString.call(headers) === "[object Headers]"; +} +/** +* Normalizes various header formats into a consistent Record format. +* +* This function accepts headers in multiple formats and converts them to a +* Record for consistent handling. +* +* @param headers - The headers to normalize. Can be: +* - A Headers instance +* - An array of [key, value] pairs +* - A plain object with string keys +* - A NullableHeaders-like object with a 'values' property containing Headers +* - null or undefined +* @returns A normalized Record containing the header key-value pairs +* +* @example +* ```ts +* // With Headers instance +* const headers1 = new Headers([['content-type', 'application/json']]); +* const normalized1 = normalizeHeaders(headers1); +* +* // With plain object +* const headers2 = { 'content-type': 'application/json' }; +* const normalized2 = normalizeHeaders(headers2); +* +* // With array of pairs +* const headers3 = [['content-type', 'application/json']]; +* const normalized3 = normalizeHeaders(headers3); +* ``` +*/ +function normalizeHeaders(headers) { + const output = iife$1(() => { + if (isHeaders(headers)) return headers; + else if (Array.isArray(headers)) return new Headers(headers); + else if (typeof headers === "object" && headers !== null && "values" in headers && isHeaders(headers.values)) return headers.values; + else if (typeof headers === "object" && headers !== null) { + const entries = Object.entries(headers).filter(([, v]) => typeof v === "string").map(([k, v]) => [k, v]); + return new Headers(entries); + } + return new Headers(); + }); + return Object.fromEntries(output.entries()); +} +function getFormattedEnv() { + let env = getEnv(); + if (env === "node" || env === "deno") env = `(${env}/${process.version}; ${process.platform}; ${process.arch})`; + return env; +} +function getHeadersWithUserAgent(headers, isAzure = false, version = "1.0.0") { + const normalizedHeaders = normalizeHeaders(headers); + const env = getFormattedEnv(); + const library = `langchainjs${isAzure ? "-azure" : ""}-openai`; + return { + ...normalizedHeaders, + "User-Agent": normalizedHeaders["User-Agent"] ? `${library}/${version} (${env})${normalizedHeaders["User-Agent"]}` : `${library}/${version} (${env})` + }; +} +//#endregion +//#region node_modules/@langchain/openai/dist/utils/tools.js +/** +* Formats a tool in either OpenAI format, or LangChain structured tool format +* into an OpenAI tool format. If the tool is already in OpenAI format, return without +* any changes. If it is in LangChain structured tool format, convert it to OpenAI tool format +* using OpenAI's `zodFunction` util, falling back to `convertToOpenAIFunction` if the parameters +* returned from the `zodFunction` util are not defined. +* +* @param {BindToolsInput} tool The tool to convert to an OpenAI tool. +* @param {Object} [fields] Additional fields to add to the OpenAI tool. +* @returns {ToolDefinition} The inputted tool in OpenAI tool format. +*/ +function _convertToOpenAITool(tool, fields) { + let toolDef; + if (isLangChainTool(tool)) toolDef = convertToOpenAITool(tool); + else toolDef = tool; + if (fields?.strict !== void 0) toolDef.function.strict = fields.strict; + return toolDef; +} +function isAnyOfProp(prop) { + return prop.anyOf !== void 0 && Array.isArray(prop.anyOf); +} +function formatFunctionDefinitions(functions) { + const lines = ["namespace functions {", ""]; + for (const f of functions) { + if (f.description) lines.push(`// ${f.description}`); + if (Object.keys(f.parameters.properties ?? {}).length > 0) { + lines.push(`type ${f.name} = (_: {`); + lines.push(formatObjectProperties(f.parameters, 0)); + lines.push("}) => any;"); + } else lines.push(`type ${f.name} = () => any;`); + lines.push(""); + } + lines.push("} // namespace functions"); + return lines.join("\n"); +} +function formatObjectProperties(obj, indent) { + const lines = []; + for (const [name, param] of Object.entries(obj.properties ?? {})) { + if (param.description && indent < 2) lines.push(`// ${param.description}`); + if (obj.required?.includes(name)) lines.push(`${name}: ${formatType(param, indent)},`); + else lines.push(`${name}?: ${formatType(param, indent)},`); + } + return lines.map((line) => " ".repeat(indent) + line).join("\n"); +} +function formatType(param, indent) { + if (isAnyOfProp(param)) return param.anyOf.map((v) => formatType(v, indent)).join(" | "); + switch (param.type) { + case "string": + if (param.enum) return param.enum.map((v) => `"${v}"`).join(" | "); + return "string"; + case "number": + if (param.enum) return param.enum.map((v) => `${v}`).join(" | "); + return "number"; + case "integer": + if (param.enum) return param.enum.map((v) => `${v}`).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 ""; + } +} +function formatToOpenAIToolChoice(toolChoice) { + if (!toolChoice) return; + else if (toolChoice === "any" || toolChoice === "required") return "required"; + else if (toolChoice === "auto") return "auto"; + else if (toolChoice === "none") return "none"; + else if (typeof toolChoice === "string") return { + type: "function", + function: { name: toolChoice } + }; + else return toolChoice; +} +function isBuiltInTool(tool) { + return "type" in tool && tool.type !== "function"; +} +/** +* Checks if a tool has a provider-specific tool definition in extras.providerToolDefinition. +* This is used for tools like localShell, shell, computerUse, and applyPatch +* that need to be sent as built-in tool types to the OpenAI API. +*/ +function hasProviderToolDefinition(tool) { + return typeof tool === "object" && tool !== null && "extras" in tool && typeof tool.extras === "object" && tool.extras !== null && "providerToolDefinition" in tool.extras && typeof tool.extras.providerToolDefinition === "object" && tool.extras.providerToolDefinition !== null; +} +function isBuiltInToolChoice(tool_choice) { + return tool_choice != null && typeof tool_choice === "object" && "type" in tool_choice && tool_choice.type !== "function"; +} +function isCustomTool(tool) { + return typeof tool === "object" && tool !== null && "metadata" in tool && typeof tool.metadata === "object" && tool.metadata !== null && "customTool" in tool.metadata && typeof tool.metadata.customTool === "object" && tool.metadata.customTool !== null; +} +function isOpenAICustomTool(tool) { + return "type" in tool && tool.type === "custom" && "custom" in tool && typeof tool.custom === "object" && tool.custom !== null; +} +function parseCustomToolCall(rawToolCall) { + if (rawToolCall.type !== "custom_tool_call") return; + return { + ...rawToolCall, + type: "tool_call", + call_id: rawToolCall.id, + id: rawToolCall.call_id, + name: rawToolCall.name, + isCustomTool: true, + args: { input: rawToolCall.input } + }; +} +/** +* Parses a computer_call output item from the OpenAI Responses API +* into a ToolCall format that can be processed by the ToolNode. +* +* @param rawToolCall - The raw computer_call output item from the API +* @returns A ComputerToolCall object if valid, undefined otherwise +*/ +function parseComputerCall(rawToolCall) { + if (rawToolCall.type !== "computer_call") return; + return { + ...rawToolCall, + type: "tool_call", + call_id: rawToolCall.id, + id: rawToolCall.call_id, + name: "computer_use", + isComputerTool: true, + args: { action: rawToolCall.action } + }; +} +/** +* Checks if a tool call is a computer tool call. +* @param toolCall - The tool call to check. +* @returns True if the tool call is a computer tool call, false otherwise. +*/ +function isComputerToolCall(toolCall) { + return typeof toolCall === "object" && toolCall !== null && "type" in toolCall && toolCall.type === "tool_call" && "isComputerTool" in toolCall && toolCall.isComputerTool === true; +} +function isCustomToolCall(toolCall, customToolCallIds) { + if (typeof toolCall !== "object" || toolCall === null || !("type" in toolCall) || toolCall.type !== "tool_call") return false; + if ("isCustomTool" in toolCall && toolCall.isCustomTool === true) return true; + if (customToolCallIds && "id" in toolCall && typeof toolCall.id === "string" && toolCall.id in customToolCallIds) return true; + return false; +} +function convertCompletionsCustomTool(tool) { + const getFormat = () => { + if (!tool.custom.format) return; + if (tool.custom.format.type === "grammar") return { + type: "grammar", + definition: tool.custom.format.grammar.definition, + syntax: tool.custom.format.grammar.syntax + }; + if (tool.custom.format.type === "text") return { type: "text" }; + }; + return { + type: "custom", + name: tool.custom.name, + description: tool.custom.description, + format: getFormat() + }; +} +function convertResponsesCustomTool(tool) { + const getFormat = () => { + if (!tool.format) return; + if (tool.format.type === "grammar") return { + type: "grammar", + grammar: { + definition: tool.format.definition, + syntax: tool.format.syntax + } + }; + if (tool.format.type === "text") return { type: "text" }; + }; + return { + type: "custom", + custom: { + name: tool.name, + description: tool.description, + format: getFormat() + } + }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/Options.mjs +var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); +var defaultOptions = { + name: void 0, + $refStrategy: "root", + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + nullableStrategy: "from-target", + removeAdditionalStrategy: "passthrough", + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref" +}; +var getDefaultOptions = (options) => { + return typeof options === "string" ? { + ...defaultOptions, + basePath: ["#"], + definitions: {}, + name: options + } : { + ...defaultOptions, + basePath: ["#"], + definitions: {}, + ...options + }; +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/util.mjs +var zodDef = (zodSchema) => { + return "_def" in zodSchema ? zodSchema._def : zodSchema; +}; +function isEmptyObj(obj) { + if (!obj) return true; + for (const _k in obj) return false; + return true; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs +var 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, + seenRefs: /* @__PURE__ */ new Set(), + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [zodDef(def), { + def: zodDef(def), + path: [ + ..._options.basePath, + _options.definitionPath, + name + ], + jsonSchema: void 0 + }])) + }; +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs +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); +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs +function parseAnyDef() { + return {}; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs +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; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs +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; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs +function parseBooleanDef() { + return { type: "boolean" }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs +function parseBrandedDef(_def, refs, forceResolution) { + return parseDef(_def.type._def, refs, forceResolution); +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs +var parseCatchDef = (def, refs, forceResolution) => { + return parseDef(def.innerType._def, refs, forceResolution); +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) }; + switch (strategy) { + case "string": + case "format:date-time": return { + type: "string", + format: "date-time" + }; + case "format:date": return { + type: "string", + format: "date" + }; + case "integer": return integerDateParser(def, refs); + } +} +var integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time" + }; + if (refs.target === "openApi3") return res; + for (const check of def.checks) switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + break; + } + return res; +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs +function parseDefaultDef(_def, refs, forceResolution) { + return { + ...parseDef(_def.innerType._def, refs, forceResolution), + default: _def.defaultValue() + }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs +function parseEffectsDef(_def, refs, forceResolution) { + return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs, forceResolution) : {}; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs +function parseEnumDef(def) { + return { + type: "string", + enum: [...def.values] + }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs +var isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") return false; + return "allOf" in type; +}; +function parseIntersectionDef(def, refs) { + const allOf = [parseDef(def.left._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "0" + ] + }), parseDef(def.right._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "1" + ] + })].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; + const mergedAllOf = []; + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === void 0) unevaluatedProperties = void 0; + } else { + let nestedSchema = schema; + if ("additionalProperties" in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } else unevaluatedProperties = void 0; + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? { + allOf: mergedAllOf, + ...unevaluatedProperties + } : void 0; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs +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 + }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs +var emojiRegex; +/** +* Generated from the regular expressions found here as of 2024-05-22: +* https://github.com/colinhacks/zod/blob/master/src/types.ts. +* +* Expressions with /i flag have been changed accordingly. +*/ +var zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex === void 0) emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + return emojiRegex; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/ +}; +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, check.message, refs); + break; + case "cuid": + addPattern(res, zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern(res, zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check.message, refs); + break; + case "date": + addFormat(res, "date", check.message, refs); + break; + case "time": + addFormat(res, "time", check.message, refs); + break; + case "duration": + addFormat(res, "duration", check.message, refs); + break; + case "length": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "includes": + addPattern(res, RegExp(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 "base64": + switch (refs.base64Strategy) { + case "format:binary": + addFormat(res, "binary", check.message, refs); + break; + case "contentEncoding:base64": + setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + break; + case "nanoid": addPattern(res, zodPatterns.nanoid, check.message, refs); + case "toLowerCase": + case "toUpperCase": + case "trim": break; + default: + } + return res; +} +var escapeNonAlphaNumeric = (value) => Array.from(value).map((c) => /[a-zA-Z0-9]/.test(c) ? c : `\\${c}`).join(""); +var addFormat = (schema, value, message, refs) => { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) schema.anyOf = []; + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; + } + } + schema.anyOf.push({ + format: value, + ...message && refs.errorMessages && { errorMessage: { format: message } } + }); + } else setResponseValueAndErrors(schema, "format", value, message, refs); +}; +var addPattern = (schema, regex, message, refs) => { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) schema.allOf = []; + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; + } + } + schema.allOf.push({ + pattern: processRegExp(regex, refs), + ...message && refs.errorMessages && { errorMessage: { pattern: message } } + }); + } else setResponseValueAndErrors(schema, "pattern", processRegExp(regex, refs), message, refs); +}; +var processRegExp = (regexOrFunction, refs) => { + const regex = typeof regexOrFunction === "function" ? regexOrFunction() : regexOrFunction; + if (!refs.applyRegexFlags || !regex.flags) return regex.source; + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s") + }; + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } else pattern += `${source[i]}${source[i].toUpperCase()}`; + continue; + } + } else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === "^") { + pattern += `(^|(?<=[\r\n]))`; + continue; + } else if (source[i] === "$") { + pattern += `($|(?=[\r\n]))`; + continue; + } + } + if (flags.s && source[i] === ".") { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; + } + pattern += source[i]; + if (source[i] === "\\") isEscaped = true; + else if (inCharGroup && source[i] === "]") inCharGroup = false; + else if (!inCharGroup && source[i] === "[") inCharGroup = true; + } + try { + new RegExp(pattern); + } catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs +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 schema = { + type: "object", + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? {} + }; + if (refs.target === "openApi3") return schema; + 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 { + ...schema, + propertyNames: keyType + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return { + ...schema, + propertyNames: { enum: def.keyType._def.values } + }; + return schema; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs +function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") return parseRecordDef(def, refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [parseDef(def.keyType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + "items", + "0" + ] + }) || {}, parseDef(def.valueType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + "items", + "1" + ] + }) || {}], + minItems: 2, + maxItems: 2 + } + }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs +function parseNativeEnumDef(def) { + const object = def.values; + const actualValues = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }).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 + }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs +function parseNeverDef() { + return { not: {} }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs +function parseNullDef(refs) { + return refs.target === "openApi3" ? { + enum: ["null"], + nullable: true + } : { type: "null" }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs +var primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null" +}; +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { + const types = options.reduce((types, x) => { + const type = primitiveMappings[x._def.typeName]; + return type && !types.includes(type) ? [...types, type] : types; + }, []); + return { type: types.length > 1 ? types : types[0] }; + } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case "string": + case "number": + case "boolean": return [...acc, type]; + case "bigint": return [...acc, "integer"]; + case "object": if (x._def.value === null) return [...acc, "null"]; + default: return acc; + } + }, []); + if (types.length === options.length) { + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []) + }; + } + } else if (options.every((x) => x._def.typeName === "ZodEnum")) return { + type: "string", + enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []) + }; + return asAnyOf(def, refs); +} +var asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + `${i}` + ] + })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); + return anyOf.length ? { anyOf } : void 0; +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs +function parseNullableDef(def, refs, forceResolution) { + if ([ + "ZodString", + "ZodNumber", + "ZodBigInt", + "ZodBoolean", + "ZodNull" + ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3" || refs.nullableStrategy === "property") return { + type: primitiveMappings[def.innerType._def.typeName], + nullable: true + }; + return { type: [primitiveMappings[def.innerType._def.typeName], "null"] }; + } + if (refs.target === "openApi3") { + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath] + }, forceResolution); + if (base && "$ref" in base) return { + allOf: [base], + nullable: true + }; + return base && { + ...base, + nullable: true + }; + } + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + "0" + ] + }); + return base && { anyOf: [base, { type: "null" }] }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs +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; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs +function decideAdditionalProperties(def, refs) { + if (refs.removeAdditionalStrategy === "strict") return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys !== "strict" : parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? true; + else return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? true; +} +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 propertyPath = [ + ...refs.currentPath, + "properties", + propName + ]; + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: propertyPath, + propertyPath + }); + if (parsedDef === void 0) return acc; + if (refs.openaiStrictMode && propDef.isOptional() && !propDef.isNullable() && typeof propDef._def?.defaultValue === "undefined") throw new Error(`Zod field at \`${propertyPath.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); + return { + properties: { + ...acc.properties, + [propName]: parsedDef + }, + required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName] + }; + }, { + properties: {}, + required: [] + }), + additionalProperties: decideAdditionalProperties(def, refs) + }; + if (!result.required.length) delete result.required; + return result; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs +var parseOptionalDef = (def, refs, forceResolution) => { + if (refs.propertyPath && refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString()) return parseDef(def.innerType._def, { + ...refs, + currentPath: refs.currentPath + }, forceResolution); + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + "1" + ] + }, forceResolution); + return innerSchema ? { anyOf: [{ not: {} }, innerSchema] } : {}; +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs +var parsePipelineDef = (def, refs, forceResolution) => { + if (refs.pipeStrategy === "input") return parseDef(def.in._def, refs, forceResolution); + else if (refs.pipeStrategy === "output") return parseDef(def.out._def, refs, forceResolution); + const a = parseDef(def.in._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "0" + ] + }); + return { allOf: [a, parseDef(def.out._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + a ? "1" : "0" + ] + })].filter((x) => x !== void 0) }; +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs +function parsePromiseDef(def, refs, forceResolution) { + return parseDef(def.type._def, refs, forceResolution); +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs +function parseSetDef(def, refs) { + const schema = { + type: "array", + uniqueItems: true, + items: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }) + }; + if (def.minSize) setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); + if (def.maxSize) setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + return schema; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs +function parseTupleDef(def, refs) { + if (def.rest) return { + type: "array", + minItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + `${i}` + ] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"] + }) + }; + else return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + `${i}` + ] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) + }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs +function parseUndefinedDef() { + return { not: {} }; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs +function parseUnknownDef() { + return {}; +} +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs +var parseReadonlyDef = (def, refs, forceResolution) => { + return parseDef(def.innerType._def, refs, forceResolution); +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) return overrideResult; + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== void 0) { + if ("$ref" in seenSchema) refs.seenRefs.add(seenSchema.$ref); + return seenSchema; + } + } + const newItem = { + def, + path: refs.currentPath, + jsonSchema: void 0 + }; + refs.seen.set(def, newItem); + try { + const jsonSchema = selectParser(def, def.typeName, refs, forceResolution); + if (jsonSchema) addMeta(def, refs, jsonSchema); + newItem.jsonSchema = jsonSchema; + return jsonSchema; + } finally { + if (forceResolution && seenItem) refs.seen.set(def, seenItem); + } +} +var get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": return { $ref: item.path.join("/") }; + case "extract-to-root": + const name = item.path.slice(refs.basePath.length + 1).map((part, index) => index === 0 ? part : encodeDefinitionPathPart(part)).join("_"); + if (name !== refs.name && refs.nameStrategy === "duplicate-ref") refs.definitions[name] = item.def; + return { $ref: [ + ...refs.basePath, + refs.definitionPath, + name + ].join("/") }; + case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": + if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return {}; + } + return refs.$refStrategy === "seen" ? {} : void 0; + } +}; +var encodedDefinitionPathPartPrefix = "_x_"; +var encodeDefinitionPathPart = (part) => { + if (/^[A-Za-z0-9_-]*$/.test(part) && !part.startsWith(encodedDefinitionPathPartPrefix)) return part; + let encoded = encodedDefinitionPathPartPrefix; + for (let i = 0; i < part.length; i++) encoded += part.charCodeAt(i).toString(16).padStart(4, "0"); + return encoded; +}; +var getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break; + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; +var selectParser = (def, typeName, refs, forceResolution) => { + 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, forceResolution); + case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: return parseDef(def.getter()._def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(); + case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(); + case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(); + case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: return; + default: return ((_) => void 0)(typeName); + } +}; +var addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) jsonSchema.markdownDescription = def.description; + } + return jsonSchema; +}; +//#endregion +//#region node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs +var zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; + const main = parseDef(schema._def, name === void 0 ? refs : { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + name + ] + }, false) ?? {}; + const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; + if (title !== void 0) main.title = title; + const definitions = (() => { + if (isEmptyObj(refs.definitions)) return; + const definitions = {}; + const processedDefinitions = /* @__PURE__ */ new Set(); + for (let i = 0; i < 500; i++) { + const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key)); + if (newDefinitions.length === 0) break; + for (const [key, schema] of newDefinitions) { + definitions[key] = parseDef(zodDef(schema), { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + key + ] + }, true) ?? {}; + processedDefinitions.add(key); + } + } + return definitions; + })(); + const combined = name === void 0 ? definitions ? { + ...main, + [refs.definitionPath]: definitions + } : main : refs.nameStrategy === "duplicate-ref" ? { + ...main, + ...definitions || refs.seenRefs.size ? { [refs.definitionPath]: { + ...definitions, + ...refs.seenRefs.size ? { [name]: main } : void 0 + } } : void 0 + } : { + $ref: [ + ...refs.$refStrategy === "relative" ? [] : refs.basePath, + refs.definitionPath, + name + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main + } + }; + if (refs.target === "jsonSchema7") combined.$schema = "http://json-schema.org/draft-07/schema#"; + else if (refs.target === "jsonSchema2019-09") combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + return combined; +}; +//#endregion +//#region node_modules/openai/lib/transform.mjs +var JSON_SCHEMA_ANNOTATION_KEYWORDS = /* @__PURE__ */ new Set([ + "$comment", + "default", + "description", + "examples", + "readOnly", + "title", + "writeOnly" +]); +var JSON_SCHEMA_ROOT_METADATA_KEYWORDS = /* @__PURE__ */ new Set(["$id", "$schema"]); +var JSON_SCHEMA_OBJECT_KEYWORDS = /* @__PURE__ */ new Set([ + "additionalProperties", + "dependencies", + "maxProperties", + "minProperties", + "patternProperties", + "properties", + "propertyNames", + "required" +]); +var JSON_SCHEMA_SINGLE_SCHEMA_KEYWORDS = [ + "additionalItems", + "additionalProperties", + "contains", + "contentSchema", + "else", + "if", + "not", + "propertyNames", + "then", + "unevaluatedItems", + "unevaluatedProperties" +]; +var JSON_SCHEMA_ARRAY_SCHEMA_KEYWORDS = [ + "allOf", + "anyOf", + "items", + "oneOf", + "prefixItems" +]; +var JSON_SCHEMA_MAP_SCHEMA_KEYWORDS = [ + "$defs", + "definitions", + "dependentSchemas", + "dependencies", + "patternProperties", + "properties" +]; +var JSON_SCHEMA_UNSUPPORTED_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "$anchor", + "$dynamicAnchor", + "$dynamicRef", + "$recursiveAnchor", + "$recursiveRef", + "allOf", + "contains", + "contentEncoding", + "contentMediaType", + "contentSchema", + "dependentRequired", + "dependentSchemas", + "dependencies", + "else", + "if", + "maxContains", + "maxProperties", + "minContains", + "minProperties", + "not", + "patternProperties", + "prefixItems", + "propertyNames", + "then", + "unevaluatedItems", + "unevaluatedProperties", + "uniqueItems" +]); +var MERGEABLE_OBJECT_ALL_OF_KEYWORDS = /* @__PURE__ */ new Set([ + ...JSON_SCHEMA_ANNOTATION_KEYWORDS, + "additionalProperties", + "properties", + "required", + "type" +]); +/** +* Visits only values carried by JSON Schema keywords that contain schemas. +* Literal payloads such as enum, const, and default deliberately do not +* participate. +*/ +function forEachJSONSchemaChild(schema, path, visit) { + const record = schema; + for (const keyword of JSON_SCHEMA_SINGLE_SCHEMA_KEYWORDS) if (keyword in record) visit(record[keyword], [...path, keyword], keyword); + for (const keyword of JSON_SCHEMA_ARRAY_SCHEMA_KEYWORDS) { + const children = record[keyword]; + if (Array.isArray(children)) for (const [index, child] of children.entries()) visit(child, [ + ...path, + keyword, + String(index) + ], keyword); + else if (children !== void 0) visit(children, [...path, keyword], keyword); + } + for (const keyword of JSON_SCHEMA_MAP_SCHEMA_KEYWORDS) { + const children = record[keyword]; + if (!isObject(children)) continue; + for (const [key, child] of Object.entries(children)) { + if (keyword === "dependencies" && !isSchemaDefinition(child)) continue; + visit(child, [ + ...path, + keyword, + key + ], keyword); + } + } +} +function toStrictJsonSchema(schema) { + const schemaCopy = structuredClone(schema); + stripUndefinedSchemaKeywords(schemaCopy); + normalizeSingletonTypeArrays(schemaCopy); + assertNoNestedSchemaIds(schemaCopy); + normalizeRootRefAndAllOf(schemaCopy); + if (schemaCopy.type !== "object") throw new Error(`Root schema must have type: 'object' but got type: ${schemaCopy.type ? `'${schemaCopy.type}'` : "undefined"}`); + if (schemaCopy.anyOf !== void 0) throw new Error("Root schema must not use `anyOf` because strict Structured Outputs requires a root object without a union."); + validateRefSchemas(schemaCopy, [], schemaCopy); + preserveAllOfRefTargets(schemaCopy); + validateRefSchemas(schemaCopy, [], schemaCopy); + rewriteLocalRefsIntoFilteredAnyOfBranches(schemaCopy); + normalizeObjectAllOfBranches(schemaCopy, [], schemaCopy); + const strictSchema = ensureStrictJsonSchema(schemaCopy, [], schemaCopy); + validateRefSchemas(strictSchema, [], strictSchema); + return strictSchema; +} +function stripUndefinedSchemaKeywords(schema, visited = /* @__PURE__ */ new Set()) { + if (typeof schema === "boolean" || !isObject(schema) || visited.has(schema)) return; + visited.add(schema); + const schemaRecord = schema; + for (const keyword of Object.keys(schemaRecord)) if (schemaRecord[keyword] === void 0) delete schemaRecord[keyword]; + forEachJSONSchemaChild(schema, [], (child) => { + stripUndefinedSchemaKeywords(child, visited); + }); +} +/** +* Root ref inlining and singleton allOf flattening can expose each other. +* Iterate until flattening no longer produces another root ref so every +* exactly representable chain reaches its final object form before the root +* type check runs. +*/ +function normalizeRootRefAndAllOf(schema) { + const seenRefs = /* @__PURE__ */ new Set(); + while (true) { + if (typeof schema.$ref === "string") { + if (seenRefs.has(schema.$ref)) throw new Error("Cyclic local $ref at `` is not supported: " + JSON.stringify(schema.$ref)); + seenRefs.add(schema.$ref); + } + inlineRootRefObject(schema); + preserveAllOfRefTargets(schema, true); + normalizeRootAllOf(schema); + const normalizedAnyOf = normalizeRootAnyOf(schema); + if (schema.$ref === void 0 && !normalizedAnyOf) return; + } +} +/** +* Some Standard Schema converters emit the root object through a local ref, +* with the referenced schema stored in a root definition map. Structured +* Outputs requires the root itself to be an object, so inline that safe, +* definition-only form while keeping the root maps available for every local +* pointer in the schema. +*/ +function inlineRootRefObject(schema) { + let ref = schema.$ref; + if (ref === void 0) return; + assertLocalRootRef(ref); + if (!hasOnlyRootRefAndDefinitions(schema)) throw new Error("Schema $ref at `` has non-metadata siblings that Draft 7 ignores and cannot be represented in strict Structured Outputs."); + const seenRefs = /* @__PURE__ */ new Set(); + const inheritedAnnotations = Object.fromEntries(Object.entries(schema).filter(([keyword]) => JSON_SCHEMA_ANNOTATION_KEYWORDS.has(keyword))); + let resolved; + while (true) { + if (seenRefs.has(ref)) throw new Error("Cyclic local $ref at `` is not supported: " + JSON.stringify(ref)); + seenRefs.add(ref); + const target = resolveLocalRef(schema, ref); + if (target === void 0) throw new Error("Local $ref at `` does not resolve to an object or boolean schema: " + JSON.stringify(ref)); + if (typeof target === "boolean") throw new TypeError("Expected object schema but got boolean; path="); + const nextRef = target.$ref; + if (nextRef === void 0) { + resolved = target; + break; + } + assertLocalRootRef(nextRef); + if (seenRefs.has(nextRef)) throw new Error("Cyclic local $ref at `` is not supported: " + JSON.stringify(nextRef)); + if (!hasOnlyRefAndAnnotations(target)) throw new Error("Schema $ref in root chain has non-annotation siblings that Draft 7 ignores and cannot be represented in strict Structured Outputs."); + for (const keyword of JSON_SCHEMA_ANNOTATION_KEYWORDS) if (!(keyword in inheritedAnnotations) && keyword in target) inheritedAnnotations[keyword] = target[keyword]; + ref = nextRef; + } + const rootDefinitions = schema.$defs; + const legacyDefinitions = schema.definitions; + const rootMetadata = Object.fromEntries(Object.entries(schema).filter(([keyword]) => JSON_SCHEMA_ANNOTATION_KEYWORDS.has(keyword) || JSON_SCHEMA_ROOT_METADATA_KEYWORDS.has(keyword))); + const inlined = structuredClone(resolved); + for (const keyword of ["$defs", "definitions"]) if (schema[keyword] !== void 0 && inlined[keyword] !== void 0) delete inlined[keyword]; + const schemaRecord = schema; + for (const keyword of Object.keys(schema)) delete schemaRecord[keyword]; + Object.assign(schema, inlined, inheritedAnnotations, rootMetadata); + if (rootDefinitions !== void 0) schema.$defs = rootDefinitions; + if (legacyDefinitions !== void 0) schema.definitions = legacyDefinitions; +} +/** +* Root object validation runs before recursive strictification, so normalize +* the same exactly representable allOf forms here that the recursive pass +* handles for nested schemas. +*/ +function normalizeRootAllOf(schema) { + while (schema.allOf !== void 0) { + if (Array.isArray(schema.allOf)) for (const [index, branch] of schema.allOf.entries()) normalizeObjectAllOfBranches(branch, ["allOf", String(index)], schema); + if (mergeObjectAllOf(schema, [], schema)) continue; + const allOf = schema.allOf; + if (!Array.isArray(allOf) || allOf.length !== 1 || !hasOnlyRootAllOfMetadataSiblings(schema)) return; + const branch = allOf[0]; + if (typeof branch === "boolean" || !isObject(branch)) return; + const rootMetadata = { ...schema }; + delete rootMetadata.allOf; + const normalized = structuredClone(branch); + const schemaRecord = schema; + for (const keyword of Object.keys(schema)) delete schemaRecord[keyword]; + Object.assign(schema, normalized, rootMetadata); + } +} +/** +* A singleton root anyOf with no validating siblings is equivalent to its +* only branch. Flatten it before the root-union check so converters that +* retain a redundant object wrapper can still produce a strict root object. +*/ +function normalizeRootAnyOf(schema) { + const anyOf = schema.anyOf; + if (!Array.isArray(anyOf) || !hasOnlyRootAnyOfMetadataSiblings(schema)) return false; + const realBranches = anyOf.map((branch, index) => ({ + branch, + index + })).filter(({ branch }) => branch !== false); + if (realBranches.length !== 1) return false; + const { branch, index: branchIndex } = realBranches[0]; + if (typeof branch === "boolean" || !isObject(branch) || !isObjectOnlySchema(branch, schema)) return false; + const definitionRenames = planPromotedRootAnyOfDefinitionRenames(schema, branch); + rewriteLocalRefsIntoPromotedRootAnyOfBranch(schema, branchIndex, definitionRenames); + const rootMetadata = { ...schema }; + delete rootMetadata.anyOf; + const normalized = structuredClone(branch); + for (const keyword of ["$defs", "definitions"]) { + const rootDefinitions = schema[keyword]; + const branchDefinitions = normalized[keyword]; + if (!isObject(rootDefinitions) || !isObject(branchDefinitions)) continue; + const renames = definitionRenames.get(keyword); + const mergedDefinitions = { ...rootDefinitions }; + for (const [name, definition] of Object.entries(branchDefinitions)) mergedDefinitions[renames?.get(name) ?? name] = definition; + normalized[keyword] = mergedDefinitions; + delete rootMetadata[keyword]; + } + const schemaRecord = schema; + for (const keyword of Object.keys(schema)) delete schemaRecord[keyword]; + Object.assign(schema, normalized, rootMetadata); + return true; +} +/** +* Root and promoted branch definition maps occupy the same pointer after +* promotion. Give conflicting branch definitions stable aliases before refs +* are rewritten so neither original target is rebound. +*/ +function planPromotedRootAnyOfDefinitionRenames(root, branch) { + const renames = /* @__PURE__ */ new Map(); + for (const keyword of ["$defs", "definitions"]) { + const rootDefinitions = root[keyword]; + const branchDefinitions = branch[keyword]; + if (!isObject(rootDefinitions) || !isObject(branchDefinitions)) continue; + const usedNames = /* @__PURE__ */ new Set([...Object.keys(rootDefinitions), ...Object.keys(branchDefinitions)]); + const keywordRenames = /* @__PURE__ */ new Map(); + let aliasIndex = 0; + for (const [name, definition] of Object.entries(branchDefinitions)) { + if (!Object.prototype.hasOwnProperty.call(rootDefinitions, name) || schemasEqual(rootDefinitions[name], definition)) continue; + let alias = "__openai_strict_anyOf_definition_" + aliasIndex++; + while (usedNames.has(alias)) alias = "__openai_strict_anyOf_definition_" + aliasIndex++; + usedNames.add(alias); + keywordRenames.set(name, alias); + } + if (keywordRenames.size > 0) renames.set(keyword, keywordRenames); + } + return renames; +} +/** +* Promoting a singleton root anyOf branch removes the original anyOf/index +* pointer prefix. Rewrite refs through that prefix while the old tree still +* exists so the promoted schema keeps naming the same targets. +*/ +function rewriteLocalRefsIntoPromotedRootAnyOfBranch(root, branchIndex, definitionRenames) { + const rewriteRef = (ref) => { + const parts = parseLocalRef(ref); + if (parts === void 0 || parts[0] !== "anyOf" || parts[1] !== String(branchIndex)) return ref; + const promotedParts = parts.slice(2); + const definitionKeyword = promotedParts[0]; + if (promotedParts.length > 1 && (definitionKeyword === "$defs" || definitionKeyword === "definitions")) { + const renamed = definitionRenames.get(definitionKeyword)?.get(promotedParts[1]); + if (renamed !== void 0) promotedParts[1] = renamed; + } + return promotedParts.length === 0 ? "#" : "#/" + promotedParts.map(encodeJSONPointerTokenForURIFragment).join("/"); + }; + const rewriteRefs = (value) => { + if (typeof value === "boolean" || !isObject(value)) return; + if (typeof value.$ref === "string") value.$ref = rewriteRef(value.$ref); + forEachJSONSchemaChild(value, [], (child) => { + rewriteRefs(child); + }); + }; + rewriteRefs(root); +} +function assertLocalRootRef(ref) { + if (typeof ref !== "string") throw new TypeError("Received non-string $ref - " + String(ref) + "; path="); + if (!ref.startsWith("#")) throw new Error("External $ref at `` is not supported in strict Structured Outputs: " + JSON.stringify(ref)); +} +function hasOnlyRootRefAndDefinitions(schema) { + return Object.keys(schema).every((keyword) => keyword === "$ref" || keyword === "$defs" || keyword === "definitions" || JSON_SCHEMA_ROOT_METADATA_KEYWORDS.has(keyword) || JSON_SCHEMA_ANNOTATION_KEYWORDS.has(keyword)); +} +/** +* Draft 7 permits `type` to be either a string or an array of strings. A +* singleton array has exactly the same validation semantics as its scalar +* form, so canonicalize it before root validation and recursive strictifying. +* Multi-type arrays carry real union semantics and must remain unchanged. +*/ +function normalizeSingletonTypeArrays(schema) { + if (typeof schema === "boolean" || !isObject(schema)) return; + if (Array.isArray(schema.type) && schema.type.length === 1) schema.type = schema.type[0]; + forEachJSONSchemaChild(schema, [], (child) => { + normalizeSingletonTypeArrays(child); + }); +} +function isNullable(schema, root, seenRefs = /* @__PURE__ */ new Set()) { + if (typeof schema === "boolean") return schema; + const ref = schema.$ref; + if (ref !== void 0) { + if (typeof ref !== "string" || !hasOnlyRefAndAnnotations(schema) || seenRefs.has(ref)) return false; + const resolved = resolveLocalRef(root, ref); + if (resolved === void 0) return false; + return isNullable(resolved, root, /* @__PURE__ */ new Set([...seenRefs, ref])); + } + if (schema.type !== void 0 && schema.type !== "null" && !(Array.isArray(schema.type) && schema.type.includes("null"))) return false; + if ("const" in schema && schema.const !== null) return false; + if (schema.enum !== void 0 && (!Array.isArray(schema.enum) || !schema.enum.includes(null))) return false; + if (schema.allOf !== void 0) { + if (!Array.isArray(schema.allOf) || !schema.allOf.every((variant) => isNullable(variant, root))) return false; + } + if (schema.anyOf !== void 0) { + if (!Array.isArray(schema.anyOf) || !schema.anyOf.some((variant) => isNullable(variant, root))) return false; + } + if (schema.oneOf !== void 0) { + if (!Array.isArray(schema.oneOf) || schema.oneOf.filter((variant) => isNullable(variant, root)).length !== 1) return false; + } + if (schema.not !== void 0 || schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) return false; + return true; +} +/** +* Mutates the given JSON schema to ensure it conforms to the `strict` standard +* that the API expects. +*/ +function ensureStrictJsonSchema(jsonSchema, path, root) { + if (typeof jsonSchema === "boolean") throw new TypeError(`Expected object schema but got boolean; path=${path.join("/")}`); + if (!isObject(jsonSchema)) throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path.join("/")}`); + if (mergeObjectAllOf(jsonSchema, path, root)) return ensureStrictJsonSchema(jsonSchema, path, root); + normalizeAnyOfFalseBranches(jsonSchema); + normalizeObjectUnionWrapper(jsonSchema, path, root); + if (hasObjectShape(jsonSchema)) { + if (!("additionalProperties" in jsonSchema)) jsonSchema.additionalProperties = false; + else if (jsonSchema.additionalProperties !== false) throw new Error(`Object schema at \`${path.join("/") || ""}\` must set \`additionalProperties: false\` to be compatible with strict Structured Outputs.`); + } + const required = jsonSchema.required ?? []; + if (!Array.isArray(required) || required.some((key) => typeof key !== "string")) throw new TypeError(`Expected \`required\` to be an array of strings; path=${path.join("/") || ""}`); + const properties = jsonSchema.properties; + if (hasObjectShape(jsonSchema)) { + for (const key of required) if (!isObject(properties) || !Object.prototype.hasOwnProperty.call(properties, key)) throw new Error(`Object schema at \`${path.join("/") || ""}\` requires property \`${key}\` but does not declare it in \`properties\`.`); + } + if (isObject(properties)) { + for (const [key, value] of Object.entries(properties)) if (!isNullable(value, root) && !required.includes(key)) throw new Error(`Schema field at \`${[ + ...path, + "properties", + key + ].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); + jsonSchema.required = Object.keys(properties); + } + const items = jsonSchema.items; + const additionalItems = jsonSchema.additionalItems; + if (Array.isArray(items)) throw new Error(`Schema at \`${path.join("/") || ""}\` uses tuple-form \`items\`, which cannot be represented in strict Structured Outputs.`); + if (additionalItems !== void 0) throw new Error(`Schema at \`${path.join("/") || ""}\` uses unsupported keyword \`additionalItems\` and cannot be represented in strict Structured Outputs.`); + const allOf = jsonSchema.allOf; + if (Array.isArray(allOf)) { + if (allOf.length === 1 && hasOnlyAnnotationSiblings(jsonSchema, "allOf")) { + const branch = allOf[0]; + if (branch === false) throw new Error(`Schema at \`${path.join("/") || ""}\` uses \`allOf: [false]\`, which cannot be represented in strict Structured Outputs.`); + if (branch === true) delete jsonSchema.allOf; + else { + const resolved = ensureStrictJsonSchema(branch, [ + ...path, + "allOf", + "0" + ], root); + const annotations = { ...jsonSchema }; + delete annotations.allOf; + Object.assign(jsonSchema, resolved, annotations); + delete jsonSchema.allOf; + } + } + } + normalizeArrayUnionWrapper(jsonSchema, root); + const schemaRecord = jsonSchema; + for (const keyword of JSON_SCHEMA_UNSUPPORTED_SCHEMA_KEYWORDS) { + if (schemaRecord[keyword] !== void 0) throw new Error(`Schema at \`${path.join("/") || ""}\` uses unsupported keyword \`${keyword}\` and cannot be represented in strict Structured Outputs.`); + delete schemaRecord[keyword]; + } + const type = jsonSchema.type; + const currentItems = jsonSchema.items; + if ((type === "array" || Array.isArray(type) && type.includes("array")) && currentItems === void 0) throw new Error(`Schema at \`${path.join("/") || ""}\` declares an array without \`items\`, which cannot be represented in strict Structured Outputs.`); + forEachJSONSchemaChild(jsonSchema, path, (child, childPath, keyword) => { + if (typeof child === "boolean" && (keyword === "additionalProperties" || keyword === "additionalItems")) return; + ensureStrictJsonSchema(child, childPath, root); + }); + if (jsonSchema.default === null) delete jsonSchema.default; + return jsonSchema; +} +function parseLocalRef(ref) { + if (!ref.startsWith("#")) return; + let pointer; + try { + pointer = decodeURIComponent(ref.slice(1)); + } catch { + return; + } + if (pointer === "") return []; + if (!pointer.startsWith("/")) return; + const parts = []; + for (const encodedPart of pointer.slice(1).split("/")) { + if (/~(?:[^01]|$)/.test(encodedPart)) return; + parts.push(encodedPart.replace(/~1/g, "/").replace(/~0/g, "~")); + } + return parts; +} +function resolvePointerPart(resolved, part) { + if (Array.isArray(resolved)) { + if (!/^(?:0|[1-9]\d*)$/.test(part)) return; + const index = Number(part); + if (!Object.prototype.hasOwnProperty.call(resolved, index)) return; + return resolved[index]; + } + if (!isObject(resolved) || !Object.prototype.hasOwnProperty.call(resolved, part)) return; + return resolved[part]; +} +function resolveLocalRef(root, ref) { + const parts = parseLocalRef(ref); + if (parts === void 0) return; + let resolved = root; + for (let index = 0; index < parts.length;) { + if (!isObject(resolved)) return; + const keyword = parts[index]; + if (JSON_SCHEMA_SINGLE_SCHEMA_KEYWORDS.includes(keyword)) { + resolved = resolvePointerPart(resolved, keyword); + index += 1; + continue; + } + if (JSON_SCHEMA_ARRAY_SCHEMA_KEYWORDS.includes(keyword)) { + resolved = resolvePointerPart(resolved, keyword); + index += 1; + if (Array.isArray(resolved)) { + if (index >= parts.length) return; + resolved = resolvePointerPart(resolved, parts[index]); + index += 1; + } + continue; + } + if (JSON_SCHEMA_MAP_SCHEMA_KEYWORDS.includes(keyword)) { + const children = resolvePointerPart(resolved, keyword); + index += 1; + if (!isObject(children) || index >= parts.length) return; + resolved = resolvePointerPart(children, parts[index]); + if (keyword === "dependencies" && !isSchemaDefinition(resolved)) return; + index += 1; + continue; + } + return; + } + return isSchemaDefinition(resolved) ? resolved : void 0; +} +function isObject(obj) { + return typeof obj === "object" && obj !== null && !Array.isArray(obj); +} +function isSchemaDefinition(value) { + return typeof value === "boolean" || isObject(value); +} +function isObjectOnlySchema(schema, root, seenRefs = /* @__PURE__ */ new Set()) { + if (typeof schema === "boolean" || !isObject(schema)) return false; + if (schema.$ref !== void 0) { + if (typeof schema.$ref !== "string" || !hasOnlyRefAndAnnotations(schema) || seenRefs.has(schema.$ref)) return false; + const resolved = resolveLocalRef(root, schema.$ref); + if (resolved === void 0) return false; + return isObjectOnlySchema(resolved, root, /* @__PURE__ */ new Set([...seenRefs, schema.$ref])); + } + if (schema.allOf !== void 0) { + if (!Array.isArray(schema.allOf) || schema.allOf.length !== 1 || !hasOnlyAnnotationSiblings(schema, "allOf")) return false; + const branch = schema.allOf[0]; + return branch !== void 0 && branch !== true && branch !== false ? isObjectOnlySchema(branch, root, seenRefs) : false; + } + return schema.type === "object" || Array.isArray(schema.type) && schema.type.length === 1 && schema.type[0] === "object"; +} +function isArrayOnlySchema(schema, root, seenRefs = /* @__PURE__ */ new Set()) { + if (typeof schema === "boolean" || !isObject(schema)) return false; + if (schema.$ref !== void 0) { + if (typeof schema.$ref !== "string" || !hasOnlyRefAndAnnotations(schema) || seenRefs.has(schema.$ref)) return false; + const resolved = resolveLocalRef(root, schema.$ref); + if (resolved === void 0) return false; + return isArrayOnlySchema(resolved, root, /* @__PURE__ */ new Set([...seenRefs, schema.$ref])); + } + if (schema.allOf !== void 0) { + if (!Array.isArray(schema.allOf) || schema.allOf.length !== 1 || !hasOnlyAnnotationSiblings(schema, "allOf")) return false; + const branch = schema.allOf[0]; + return branch !== void 0 && branch !== true && branch !== false ? isArrayOnlySchema(branch, root, seenRefs) : false; + } + return schema.type === "array" || Array.isArray(schema.type) && schema.type.length === 1 && schema.type[0] === "array"; +} +function hasOnlyRefAndAnnotations(schema) { + return Object.keys(schema).every((keyword) => keyword === "$ref" || keyword === "$defs" || keyword === "definitions" || JSON_SCHEMA_ANNOTATION_KEYWORDS.has(keyword)); +} +function hasOnlyAnnotationSiblings(schema, keyword) { + const schemaRecord = schema; + return Object.keys(schema).every((schemaKeyword) => schemaKeyword === keyword || (schemaKeyword === "$defs" || schemaKeyword === "definitions") && isObject(schemaRecord[schemaKeyword]) || JSON_SCHEMA_ANNOTATION_KEYWORDS.has(schemaKeyword)); +} +function hasOnlyRootAllOfMetadataSiblings(schema) { + return Object.keys(schema).every((keyword) => keyword === "allOf" || keyword === "$defs" || keyword === "definitions" || JSON_SCHEMA_ROOT_METADATA_KEYWORDS.has(keyword) || JSON_SCHEMA_ANNOTATION_KEYWORDS.has(keyword)); +} +function hasOnlyRootAnyOfMetadataSiblings(schema) { + return Object.keys(schema).every((keyword) => keyword === "anyOf" || keyword === "$defs" || keyword === "definitions" || keyword === "type" && schema.type === "object" || JSON_SCHEMA_ROOT_METADATA_KEYWORDS.has(keyword) || JSON_SCHEMA_ANNOTATION_KEYWORDS.has(keyword)); +} +function hasObjectKeywords(schema) { + return Object.keys(schema).some((keyword) => JSON_SCHEMA_OBJECT_KEYWORDS.has(keyword)); +} +function hasObjectShape(schema) { + const typ = schema.type; + return typ === "object" || Array.isArray(typ) && typ.includes("object") || typ === void 0 && hasObjectKeywords(schema); +} +function isRedundantUnionWrapperType(type, branchType) { + return type === branchType || Array.isArray(type) && type.length === 2 && type.includes(branchType) && type.includes("null"); +} +function normalizeObjectUnionWrapper(jsonSchema, path, root) { + if (jsonSchema.anyOf === void 0) return; + const hasEmptyProperties = isObject(jsonSchema.properties) && Object.keys(jsonSchema.properties).length === 0; + const hasEmptyRequired = Array.isArray(jsonSchema.required) && jsonSchema.required.length === 0; + if (hasEmptyProperties) delete jsonSchema.properties; + if (hasEmptyRequired) delete jsonSchema.required; + if (!hasObjectShape(jsonSchema)) return; + const hasOwnObjectConstraints = Object.keys(jsonSchema).some((keyword) => JSON_SCHEMA_OBJECT_KEYWORDS.has(keyword)); + if (isRedundantUnionWrapperType(jsonSchema.type, "object") && !hasOwnObjectConstraints && Array.isArray(jsonSchema.anyOf) && jsonSchema.anyOf.every((branch) => isObjectOnlySchema(branch, root))) { + delete jsonSchema.type; + return; + } + throw new Error("Object anyOf schema at `" + (path.join("/") || "") + "` cannot be represented in strict Structured Outputs without changing Draft 7 validation."); +} +function normalizeArrayUnionWrapper(jsonSchema, root) { + if (isRedundantUnionWrapperType(jsonSchema.type, "array") && jsonSchema.items === void 0 && Array.isArray(jsonSchema.anyOf) && jsonSchema.anyOf.every((branch) => isArrayOnlySchema(branch, root))) delete jsonSchema.type; +} +function normalizeAnyOfFalseBranches(jsonSchema) { + if (!Array.isArray(jsonSchema.anyOf)) return; + const realBranches = jsonSchema.anyOf.filter((branch) => branch !== false); + if (realBranches.length > 0 && realBranches.length !== jsonSchema.anyOf.length) jsonSchema.anyOf = realBranches; +} +function assertNoNestedSchemaIds(schema) { + const visit = (value, path) => { + if (typeof value === "boolean" || !isObject(value)) return; + if (path.length > 0 && value.$id !== void 0) throw new Error("Nested $id at " + JSON.stringify(path.join("/")) + " establishes a separate JSON Schema resource scope and cannot be represented in strict Structured Outputs."); + forEachJSONSchemaChild(value, path, (child, childPath) => { + visit(child, childPath); + }); + }; + visit(schema, []); +} +function refTargetsAllOfBranch(root, ref) { + const parts = parseLocalRef(ref); + if (parts === void 0) return false; + let resolved = root; + for (const [index, part] of parts.entries()) { + if (part === "allOf" && isObject(resolved) && Array.isArray(resolved["allOf"]) && index < parts.length - 1) return true; + resolved = resolvePointerPart(resolved, part); + if (resolved === void 0) return false; + } + return false; +} +function escapeJSONPointerToken(token) { + return token.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function encodeJSONPointerTokenForURIFragment(token) { + return encodeURIComponent(escapeJSONPointerToken(token)).replace(/%24/g, "$"); +} +/** +* Strictification removes false anyOf alternatives. Rewrite pointers into +* surviving alternatives before that filtering happens so each local ref +* still names the same schema after earlier indices disappear. +*/ +function rewriteLocalRefsIntoFilteredAnyOfBranches(root) { + const rewriteRef = (ref) => { + const originalParts = parseLocalRef(ref); + if (originalParts === void 0 || originalParts.length === 0) return ref; + const rewrittenParts = [...originalParts]; + let resolved = root; + let changed = false; + for (const [index, part] of originalParts.entries()) { + const resolvedRecord = typeof resolved === "object" && resolved !== null && !Array.isArray(resolved) ? resolved : void 0; + if (part === "anyOf" && index < originalParts.length - 1 && resolvedRecord !== void 0 && Array.isArray(resolvedRecord["anyOf"])) { + const branches = resolvedRecord["anyOf"]; + const branchIndexPart = originalParts[index + 1]; + if (!/^(?:0|[1-9]\d*)$/.test(branchIndexPart)) return ref; + const branchIndex = Number(branchIndexPart); + if (!Object.prototype.hasOwnProperty.call(branches, branchIndex)) return ref; + const realBranches = branches.filter((branch) => branch !== false); + if (realBranches.length > 0 && realBranches.length !== branches.length) { + if (branches[branchIndex] === false) return ref; + const rewrittenIndex = branches.slice(0, branchIndex).filter((branch) => branch !== false).length; + if (rewrittenIndex !== branchIndex) { + rewrittenParts[index + 1] = String(rewrittenIndex); + changed = true; + } + } + } + resolved = resolvePointerPart(resolved, part); + if (resolved === void 0) return ref; + } + return changed ? "#/" + rewrittenParts.map(encodeJSONPointerTokenForURIFragment).join("/") : ref; + }; + const rewriteRefs = (value) => { + if (typeof value === "boolean" || !isObject(value)) return; + if (typeof value.$ref === "string") value.$ref = rewriteRef(value.$ref); + forEachJSONSchemaChild(value, [], (child) => { + rewriteRefs(child); + }); + }; + rewriteRefs(root); +} +/** +* Strictification removes every representable allOf. Preserve any schema +* referenced through an allOf branch under a stable root definition first so +* structural flattening cannot leave a dangling local pointer behind. +*/ +function preserveAllOfRefTargets(root, rootOnly = false) { + const refsToPreserve = /* @__PURE__ */ new Set(); + const collectRefs = (value) => { + if (typeof value === "boolean" || !isObject(value)) return; + if (typeof value.$ref === "string" && refTargetsAllOfBranch(root, value.$ref)) { + const pointerParts = parseLocalRef(value.$ref); + if (!rootOnly || pointerParts?.[0] === "allOf") refsToPreserve.add(value.$ref); + } + forEachJSONSchemaChild(value, [], (child) => { + collectRefs(child); + }); + }; + collectRefs(root); + if (refsToPreserve.size === 0) return; + if (root.$defs !== void 0 && !isObject(root.$defs)) throw new Error("Root schema has invalid $defs and cannot preserve local allOf references."); + const definitions = root.$defs ?? (root.$defs = {}); + const rewrittenRefs = /* @__PURE__ */ new Map(); + let aliasIndex = 0; + for (const ref of refsToPreserve) { + const target = resolveLocalRef(root, ref); + if (!isSchemaDefinition(target)) { + if (rootOnly) continue; + throw new Error("Local $ref cannot be preserved before allOf flattening: " + JSON.stringify(ref)); + } + let alias = "__openai_strict_allOf_ref_" + aliasIndex++; + while (Object.prototype.hasOwnProperty.call(definitions, alias)) alias = "__openai_strict_allOf_ref_" + aliasIndex++; + definitions[alias] = structuredClone(target); + rewrittenRefs.set(ref, "#/$defs/" + escapeJSONPointerToken(alias)); + } + const rewriteRefs = (value) => { + if (typeof value === "boolean" || !isObject(value)) return; + if (typeof value.$ref === "string") value.$ref = rewrittenRefs.get(value.$ref) ?? value.$ref; + forEachJSONSchemaChild(value, [], (child) => { + rewriteRefs(child); + }); + }; + rewriteRefs(root); +} +/** +* Closed allOf merges can discard optional property declarations. Preserve +* only local refs into declarations that are about to disappear, then rewrite +* those refs to stable root definitions before the merge removes their paths. +*/ +function preserveDiscardedAllOfPropertyRefTargets(root, discardedPaths) { + if (discardedPaths.length === 0) return; + const refsToPreserve = /* @__PURE__ */ new Set(); + const collectRefs = (value) => { + if (typeof value === "boolean" || !isObject(value)) return; + if (typeof value.$ref === "string") { + const parts = parseLocalRef(value.$ref); + if (parts !== void 0 && discardedPaths.some((discardedPath) => parts.length >= discardedPath.length && discardedPath.every((part, index) => parts[index] === part))) refsToPreserve.add(value.$ref); + } + forEachJSONSchemaChild(value, [], (child) => { + collectRefs(child); + }); + }; + collectRefs(root); + if (refsToPreserve.size === 0) return; + if (root.$defs !== void 0 && !isObject(root.$defs)) throw new Error("Root schema has invalid $defs and cannot preserve discarded allOf properties."); + const definitions = root.$defs ?? (root.$defs = {}); + const rewrittenRefs = /* @__PURE__ */ new Map(); + let aliasIndex = 0; + for (const ref of refsToPreserve) { + const target = resolveLocalRef(root, ref); + if (!isSchemaDefinition(target)) throw new Error("Local $ref cannot be preserved before allOf property removal: " + JSON.stringify(ref)); + let alias = "__openai_strict_allOf_property_ref_" + aliasIndex++; + while (Object.prototype.hasOwnProperty.call(definitions, alias)) alias = "__openai_strict_allOf_property_ref_" + aliasIndex++; + definitions[alias] = structuredClone(target); + rewrittenRefs.set(ref, "#/$defs/" + escapeJSONPointerToken(alias)); + } + const rewriteRefs = (value) => { + if (typeof value === "boolean" || !isObject(value)) return; + if (typeof value.$ref === "string") value.$ref = rewrittenRefs.get(value.$ref) ?? value.$ref; + forEachJSONSchemaChild(value, [], (child) => { + rewriteRefs(child); + }); + }; + rewriteRefs(root); +} +function validateRefSchemas(schema, path, root) { + if (typeof schema === "boolean" || !isObject(schema)) return; + const ref = schema.$ref; + if (ref !== void 0) { + if (typeof ref !== "string") throw new TypeError(`Received non-string $ref - ${ref}; path=${path.join("/")}`); + if (!ref.startsWith("#")) throw new Error(`External $ref at \`${path.join("/") || ""}\` is not supported in strict Structured Outputs: ${JSON.stringify(ref)}`); + const resolved = resolveLocalRef(root, ref); + if (resolved === void 0 || !isSchemaDefinition(resolved)) throw new Error(`Local $ref at \`${path.join("/") || ""}\` does not resolve to an object or boolean schema: ${JSON.stringify(ref)}`); + if (typeof resolved === "boolean") throw new TypeError(`Expected object schema but got boolean; path=${path.join("/")}`); + if (!hasOnlyRefAndAnnotations(schema)) throw new Error(`Schema $ref at \`${path.join("/") || ""}\` has non-annotation siblings that Draft 7 ignores and cannot be represented in strict Structured Outputs.`); + } + forEachJSONSchemaChild(schema, path, (child, childPath) => { + validateRefSchemas(child, childPath, root); + }); +} +/** +* Resolve only local aliases whose siblings carry no validation semantics. +* Keeping this separate from general ref validation lets allOf merging inspect +* the effective object shape without broadening which refs or sibling +* constraints are accepted. +*/ +function resolveObjectAllOfBranch(schema, root, normalizing) { + const refChain = [schema]; + const seenRefs = /* @__PURE__ */ new Set(); + let resolved = schema; + let resolvedPath = []; + while (true) { + while (resolved.$ref !== void 0) { + const ref = resolved.$ref; + if (typeof ref !== "string" || !hasOnlyRefAndAnnotations(resolved) || seenRefs.has(ref)) return; + seenRefs.add(ref); + const target = resolveLocalRef(root, ref); + if (typeof target === "boolean" || !isObject(target)) return; + const targetPath = parseLocalRef(ref); + if (targetPath === void 0) return; + resolved = target; + resolvedPath = targetPath; + refChain.push(resolved); + } + if (resolved.allOf !== void 0 && !normalizing.has(resolved)) { + const previousAllOf = resolved.allOf; + normalizeObjectAllOfBranches(resolved, resolvedPath, root, normalizing); + if (resolved.$ref !== void 0 || resolved.allOf !== previousAllOf) continue; + } + return { + schema: resolved, + refChain + }; + } +} +function normalizeObjectAllOfBranches(schema, path, root, normalizing = /* @__PURE__ */ new Set()) { + if (typeof schema === "boolean" || !isObject(schema)) return; + if (normalizing.has(schema)) return; + normalizing.add(schema); + try { + while (true) { + forEachJSONSchemaChild(schema, path, (child, childPath) => { + normalizeObjectAllOfBranches(child, childPath, root, normalizing); + }); + if (!mergeObjectAllOf(schema, path, root, normalizing)) return; + } + } finally { + normalizing.delete(schema); + } +} +function mergeObjectAllOf(jsonSchema, path, root, normalizing = /* @__PURE__ */ new Set()) { + const allOf = jsonSchema.allOf; + if (!Array.isArray(allOf) || allOf.length === 0) return false; + const uniqueBranches = allOf.filter((branch, index) => !allOf.slice(0, index).some((candidate) => schemasEqual(candidate, branch))); + if (uniqueBranches.length !== allOf.length) { + jsonSchema.allOf = uniqueBranches; + return true; + } + const nonNeutralBranches = allOf.filter((entry) => entry !== true); + if (nonNeutralBranches.length !== allOf.length) { + if (nonNeutralBranches.length === 0) delete jsonSchema.allOf; + else jsonSchema.allOf = nonNeutralBranches; + return true; + } + const parentHasObjectShape = hasObjectShapeWithoutAllOf(jsonSchema); + const resolvedEntries = allOf.map((entry) => isObject(entry) ? resolveObjectAllOfBranch(entry, root, normalizing) : void 0); + const objectBranches = resolvedEntries.map((entry) => entry?.schema).filter((entry) => entry !== void 0 && hasObjectShapeWithoutAllOf(entry)); + if (!parentHasObjectShape && objectBranches.length === 0) return false; + if (!parentHasObjectShape && allOf.length === 1) return false; + const fail = () => { + throw new Error(`Object allOf at \`${path.join("/") || ""}\` cannot be merged without changing Draft 7 validation.`); + }; + if (!parentHasObjectShape && [ + "additionalProperties", + "properties", + "required", + "type" + ].some((keyword) => keyword in jsonSchema)) fail(); + for (const keyword of Object.keys(jsonSchema)) if (keyword !== "allOf" && keyword !== "$defs" && keyword !== "definitions" && !(path.length === 0 && JSON_SCHEMA_ROOT_METADATA_KEYWORDS.has(keyword)) && !MERGEABLE_OBJECT_ALL_OF_KEYWORDS.has(keyword)) fail(); + const branches = []; + if (parentHasObjectShape) branches.push({ + schema: jsonSchema, + sourcePath: path + }); + for (const [index, entry] of allOf.entries()) { + if (!isObject(entry)) fail(); + const resolvedEntry = resolvedEntries[index]; + if (resolvedEntry === void 0) return fail(); + const branch = resolvedEntry.schema; + if (hasObjectShapeWithoutAllOf(branch)) branches.push({ + schema: branch, + sourcePath: branch === entry ? [ + ...path, + "allOf", + String(index) + ] : void 0 + }); + else if (!hasOnlyNeutralAllOfBranchKeywords(branch)) fail(); + } + const merged = {}; + for (const keyword of ["$defs", "definitions"]) if (jsonSchema[keyword] !== void 0) merged[keyword] = jsonSchema[keyword]; + if (path.length === 0) { + for (const keyword of JSON_SCHEMA_ROOT_METADATA_KEYWORDS) if (keyword in jsonSchema) merged[keyword] = jsonSchema[keyword]; + } + const mergedProperties = Object.create(null); + const mergedRequired = /* @__PURE__ */ new Set(); + const closedPropertySets = []; + const propertyEntries = []; + let sawProperties = false; + let sawRequired = false; + let hasExplicitObjectType = false; + let hasExplicitNullableObjectType = false; + const mergeAnnotations = (schema) => { + for (const keyword of JSON_SCHEMA_ANNOTATION_KEYWORDS) { + if (!(keyword in schema)) continue; + if (!(keyword in merged)) merged[keyword] = schema[keyword]; + } + }; + mergeAnnotations(jsonSchema); + for (const resolvedEntry of resolvedEntries) { + if (resolvedEntry === void 0) continue; + for (const entry of resolvedEntry.refChain) mergeAnnotations(entry); + } + for (const { schema: branch, sourcePath } of branches) { + for (const keyword of Object.keys(branch)) { + if (keyword === "allOf" && branch === jsonSchema) continue; + if ((keyword === "$defs" || keyword === "definitions") && isObject(branch[keyword])) continue; + if (branch === jsonSchema && path.length === 0 && JSON_SCHEMA_ROOT_METADATA_KEYWORDS.has(keyword)) continue; + if (!MERGEABLE_OBJECT_ALL_OF_KEYWORDS.has(keyword)) fail(); + } + if (branch.type !== void 0) { + if (!isMergeableObjectType(branch.type)) fail(); + if (branch.type === "object") hasExplicitObjectType = true; + else hasExplicitNullableObjectType = true; + } + if (branch.properties !== void 0) { + if (!isObject(branch.properties)) fail(); + sawProperties = true; + for (const [key, propertySchema] of Object.entries(branch.properties)) propertyEntries.push({ + key, + propertySchema, + sourcePath: sourcePath === void 0 ? void 0 : [ + ...sourcePath, + "properties", + key + ] + }); + } + if (branch.required !== void 0) { + if (!Array.isArray(branch.required) || branch.required.some((key) => typeof key !== "string")) fail(); + sawRequired = true; + for (const key of branch.required) mergedRequired.add(key); + } + if ("additionalProperties" in branch) { + if (branch.additionalProperties !== false) fail(); + closedPropertySets.push(new Set(Object.keys(branch.properties ?? {}))); + } + } + const allowedClosedProperties = closedPropertySets.length === 0 ? void 0 : closedPropertySets.slice(1).reduce((allowed, keys) => new Set([...allowed].filter((key) => keys.has(key))), new Set(closedPropertySets[0])); + const excludesRequiredProperty = allowedClosedProperties !== void 0 && [...mergedRequired].some((key) => !allowedClosedProperties.has(key)); + const collapsesToNull = excludesRequiredProperty && !hasExplicitObjectType && hasExplicitNullableObjectType; + preserveDiscardedAllOfPropertyRefTargets(root, propertyEntries.filter(({ key, sourcePath }) => sourcePath !== void 0 && (collapsesToNull || allowedClosedProperties !== void 0 && !allowedClosedProperties.has(key))).map(({ sourcePath }) => sourcePath)); + if (jsonSchema === root && root.$defs !== void 0) merged.$defs = root.$defs; + if (excludesRequiredProperty) { + if (collapsesToNull) { + merged.type = "null"; + for (const keyword of Object.keys(jsonSchema)) delete jsonSchema[keyword]; + Object.assign(jsonSchema, merged); + return true; + } + fail(); + } + for (const { key, propertySchema } of propertyEntries) { + if (allowedClosedProperties !== void 0 && !allowedClosedProperties.has(key)) continue; + if (Object.prototype.hasOwnProperty.call(mergedProperties, key) && !schemasEqual(mergedProperties[key], propertySchema)) fail(); + mergedProperties[key] = propertySchema; + } + if (hasExplicitObjectType || hasExplicitNullableObjectType) merged.type = hasExplicitObjectType ? "object" : ["object", "null"]; + if (sawProperties) merged.properties = Object.fromEntries(Object.entries(mergedProperties)); + if (sawRequired) merged.required = [...mergedRequired]; + if (closedPropertySets.length > 0) merged.additionalProperties = false; + for (const keyword of Object.keys(jsonSchema)) delete jsonSchema[keyword]; + Object.assign(jsonSchema, merged); + return true; +} +function hasObjectShapeWithoutAllOf(schema) { + if (schema.type !== void 0) return isMergeableObjectType(schema.type); + return Object.keys(schema).some((keyword) => JSON_SCHEMA_OBJECT_KEYWORDS.has(keyword)); +} +function hasOnlyNeutralAllOfBranchKeywords(schema) { + const schemaRecord = schema; + return Object.keys(schema).every((keyword) => JSON_SCHEMA_ANNOTATION_KEYWORDS.has(keyword) || (keyword === "$defs" || keyword === "definitions") && isObject(schemaRecord[keyword])); +} +function isMergeableObjectType(type) { + return type === "object" || Array.isArray(type) && type.length === 2 && type.includes("object") && type.includes("null"); +} +function schemasEqual(left, right) { + if (left === right) return true; + if (Array.isArray(left) || Array.isArray(right)) { + if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false; + return left.every((value, index) => schemasEqual(value, right[index])); + } + if (typeof left !== "object" || left === null || typeof right !== "object" || right === null) return false; + const leftRecord = left; + const rightRecord = right; + const leftKeys = Object.keys(leftRecord).sort(); + const rightKeys = Object.keys(rightRecord).sort(); + if (leftKeys.length !== rightKeys.length) return false; + return leftKeys.every((key, index) => key === rightKeys[index] && schemasEqual(leftRecord[key], rightRecord[key])); +} +//#endregion +//#region node_modules/openai/helpers/zod.mjs +function encodeSchemaDefinitionRefToken(token) { + return encodeURIComponent(token.replace(/~/g, "~0").replace(/\//g, "~1")); +} +function validateSchemaDefinitions(schemaDefinitions) { + if (schemaDefinitions && Object.prototype.hasOwnProperty.call(schemaDefinitions, "__proto__")) throw new Error("schemaDefinitions cannot include \"__proto__\" as a definition name"); +} +function escapeSchemaDefinitionRefs(schema, schemaDefinitions) { + const refReplacements = new Map(Object.keys(schemaDefinitions ?? {}).map((name) => [`#/definitions/${name}`, `#/definitions/${encodeSchemaDefinitionRefToken(name)}`])); + const visit = (value) => { + if (!value || typeof value !== "object") return; + if (Array.isArray(value)) { + for (const child of value) visit(child); + return; + } + const record = value; + const ref = record["$ref"]; + if (typeof ref === "string") record["$ref"] = refReplacements.get(ref) ?? ref; + for (const child of Object.values(record)) visit(child); + }; + visit(schema); + return schema; +} +function getZodV3RootName(name, schemaDefinitions) { + let rootName = name; + while (schemaDefinitions && Object.prototype.hasOwnProperty.call(schemaDefinitions, rootName)) rootName = `${rootName}_root`; + return rootName; +} +function zodV3ToJsonSchema(schema, options) { + return escapeSchemaDefinitionRefs(zodToJsonSchema(schema, { + openaiStrictMode: true, + name: getZodV3RootName(options.name, options.schemaDefinitions), + nameStrategy: "duplicate-ref", + $refStrategy: "extract-to-root", + nullableStrategy: "property", + ...options.schemaDefinitions ? { definitions: options.schemaDefinitions } : void 0 + }), options.schemaDefinitions); +} +function zodV4ToJsonSchema(schema, options = {}) { + const metadata = options.schemaDefinitions ? registry() : void 0; + for (const [name, definition] of Object.entries(options.schemaDefinitions ?? {})) metadata?.add(definition, { id: name }); + return toStrictJsonSchema(escapeSchemaDefinitionRefs(toJSONSchema(schema, { + target: "draft-7", + ...metadata ? { metadata } : void 0, + override: ({ zodSchema, jsonSchema }) => { + const def = zodSchema._zod.def; + if (def.type === "union" && "discriminator" in def && Array.isArray(jsonSchema.oneOf)) { + if (jsonSchema.anyOf !== void 0) throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema"); + jsonSchema.anyOf = jsonSchema.oneOf; + delete jsonSchema.oneOf; + } + } + }), options.schemaDefinitions)); +} +function isZodV4(zodObject) { + return "_zod" in zodObject; +} +function parseZodObject(zodObject, content) { + const parsed = JSON.parse(content); + const parser = zodObject.parse; + if (typeof parser === "function") return parser.call(zodObject, parsed); + return parse(zodObject, parsed); +} +/** +* Creates a chat completion `JSONSchema` response format object from +* the given Zod schema. +* +* If this is passed to the `.parse()`, `.stream()` or `.runTools()` +* chat completion methods then the response message will contain a +* `.parsed` property that is the result of parsing the content with +* the given Zod object. +* +* ```ts +* const completion = await client.chat.completions.parse({ +* model: 'gpt-4o-2024-08-06', +* messages: [ +* { role: 'system', content: 'You are a helpful math tutor.' }, +* { role: 'user', content: 'solve 8x + 31 = 2' }, +* ], +* response_format: zodResponseFormat( +* z.object({ +* steps: z.array(z.object({ +* explanation: z.string(), +* answer: z.string(), +* })), +* final_answer: z.string(), +* }), +* 'math_answer', +* ), +* }); +* const message = completion.choices[0]?.message; +* if (message?.parsed) { +* console.log(message.parsed); +* console.log(message.parsed.final_answer); +* } +* ``` +* +* This can be passed directly to the `.create()` method but will not +* result in any automatic parsing, you'll have to parse the response yourself. +*/ +function zodResponseFormat(zodObject, name, props) { + const zodSchema = zodObject; + const { schemaDefinitions, ...responseFormatProps } = props ?? {}; + validateSchemaDefinitions(schemaDefinitions); + return makeParseableResponseFormat$1({ + type: "json_schema", + json_schema: { + ...responseFormatProps, + name, + strict: true, + schema: isZodV4(zodSchema) ? zodV4ToJsonSchema(zodSchema, { schemaDefinitions }) : zodV3ToJsonSchema(zodSchema, { + name, + schemaDefinitions + }) + } + }, (content) => parseZodObject(zodObject, content)); +} +//#endregion +//#region node_modules/@langchain/openai/dist/utils/output.js +var SUPPORTED_METHODS = [ + "jsonSchema", + "functionCalling", + "jsonMode" +]; +/** +* Get the structured output method for a given model. By default, it uses +* `jsonSchema` if the model supports it, otherwise it uses `functionCalling`. +* +* @throws if the method is invalid, e.g. is not a string or invalid method is provided. +* @param model - The model name. +* @param config - The structured output method options. +* @returns The structured output method. +*/ +function getStructuredOutputMethod(model, method) { + /** + * If a method is provided, validate it. + */ + if (typeof method !== "undefined" && !SUPPORTED_METHODS.includes(method)) throw new Error(`Invalid method: ${method}. Supported methods are: ${SUPPORTED_METHODS.join(", ")}`); + const hasSupportForJsonSchema = !model.startsWith("gpt-3") && !model.startsWith("gpt-4-") && model !== "gpt-4"; + /** + * If the model supports JSON Schema, use it by default. + */ + if (hasSupportForJsonSchema && !method) return "jsonSchema"; + if (!hasSupportForJsonSchema && method === "jsonSchema") throw new Error(`JSON Schema is not supported for model "${model}". Please use a different method, e.g. "functionCalling" or "jsonMode".`); + /** + * If the model does not support JSON Schema, use function calling by default. + */ + return method ?? "functionCalling"; +} +function makeParseableResponseFormat(response_format, parser) { + const obj = { ...response_format }; + Object.defineProperties(obj, { + $brand: { + value: "auto-parseable-response-format", + enumerable: false + }, + $parseRaw: { + value: parser, + enumerable: false + } + }); + return obj; +} +function interopZodResponseFormat(zodSchema, name, props) { + if (isZodSchemaV3(zodSchema)) return zodResponseFormat(zodSchema, name, props); + if (isZodSchemaV4(zodSchema)) return makeParseableResponseFormat({ + type: "json_schema", + json_schema: { + ...props, + name, + strict: true, + schema: toJsonSchema(zodSchema, { + cycles: "ref", + reused: "ref", + override(ctx) { + ctx.jsonSchema.title = name; + } + }) + } + }, (content) => parse$1(zodSchema, JSON.parse(content))); + throw new Error("Unsupported schema response format"); +} +/** +* Handle multi modal response content. +* +* @param content The content of the message. +* @param messages The messages of the response. +* @returns The new content of the message. +*/ +function handleMultiModalOutput(content, messages) { + /** + * Handle OpenRouter image responses + * @see https://openrouter.ai/docs/features/multimodal/image-generation#api-usage + */ + if (messages && typeof messages === "object" && "images" in messages && Array.isArray(messages.images)) { + const images = messages.images.filter((image) => typeof image?.image_url?.url === "string").map((image) => ({ + type: "image", + url: image.image_url.url + })); + return [{ + type: "text", + text: content + }, ...images]; + } + return content; +} +//#endregion +//#region node_modules/@langchain/openai/dist/chat_models/profiles.js +var PROFILES = { + "gpt-4o-2024-11-20": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.3-codex": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-codex": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-pro": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 272e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4o-mini": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "text-embedding-ada-002": { + maxInputTokens: 8192, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1536, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-chat-latest": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "codex-mini-latest": { + maxInputTokens: 2e5, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.1-codex-max": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4o-2024-05-13": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.2-chat-latest": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.2-codex": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o3-deep-research": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + o1: { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.1": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o4-mini-deep-research": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.3-codex-spark": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + o3: { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "text-embedding-3-small": { + maxInputTokens: 8191, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1536, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4.1-nano": { + maxInputTokens: 1047576, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "text-embedding-3-large": { + maxInputTokens: 8191, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 3072, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-3.5-turbo": { + maxInputTokens: 16385, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: false, + imageUrlInputs: false, + pdfToolMessage: false, + imageToolMessage: false, + toolChoice: true + }, + "gpt-5.1-codex-mini": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.2": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4.1": { + maxInputTokens: 1047576, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o3-pro": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4-turbo": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o4-mini": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4.1-mini": { + maxInputTokens: 1047576, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.4": { + maxInputTokens: 105e4, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o1-preview": { + maxInputTokens: 128e3, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.4-pro": { + maxInputTokens: 105e4, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.5": { + maxInputTokens: 105e4, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 13e4, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.5-pro": { + maxInputTokens: 105e4, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o1-pro": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.1-codex": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.2-pro": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o3-mini": { + maxInputTokens: 2e5, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4o-2024-08-06": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-mini": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5.1-chat-latest": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4": { + maxInputTokens: 8192, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-nano": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o1-mini": { + maxInputTokens: 128e3, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4o": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + } +}; +//#endregion +//#region node_modules/@langchain/openai/dist/chat_models/base.js +function getChatOpenAIModelParams(modelOrParams, paramsArg) { + if (typeof modelOrParams === "string") return { + model: modelOrParams, + ...paramsArg ?? {} + }; + if (modelOrParams == null) return paramsArg; + return modelOrParams; +} +/** @internal */ +var BaseChatOpenAI = class extends BaseChatModel { + temperature; + topP; + frequencyPenalty; + presencePenalty; + n; + logitBias; + model = "gpt-3.5-turbo"; + modelKwargs; + stop; + stopSequences; + user; + timeout; + streaming = false; + streamUsage = true; + maxTokens; + logprobs; + topLogprobs; + apiKey; + organization; + __includeRawResponse; + /** @internal */ + client; + /** @internal */ + clientConfig; + /** + * Whether the model supports the `strict` argument when passing in tools. + * If `undefined` the `strict` argument will not be passed to OpenAI. + */ + supportsStrictToolCalling; + audio; + modalities; + reasoning; + /** + * Must be set to `true` in tenancies with Zero Data Retention. Setting to `true` will disable + * output storage in the Responses API, but this DOES NOT enable Zero Data Retention in your + * OpenAI organization or project. This must be configured directly with OpenAI. + * + * See: + * https://platform.openai.com/docs/guides/your-data + * https://platform.openai.com/docs/api-reference/responses/create#responses-create-store + * + * @default false + */ + zdrEnabled; + /** + * Service tier to use for this request. Can be "auto", "default", or "flex" or "priority". + * Specifies the service tier for prioritization and latency optimization. + */ + service_tier; + /** + * Used by OpenAI to cache responses for similar requests to optimize your cache + * hit rates. + * [Learn more](https://platform.openai.com/docs/guides/prompt-caching). + */ + promptCacheKey; + /** + * Used by OpenAI to set cache retention time + */ + promptCacheRetention; + /** + * The verbosity of the model's response. + */ + verbosity; + defaultOptions; + _llmType() { + return "openai"; + } + static lc_name() { + return "ChatOpenAI"; + } + get callKeys() { + return [ + ...super.callKeys, + "options", + "function_call", + "functions", + "tools", + "tool_choice", + "promptIndex", + "response_format", + "seed", + "reasoning", + "reasoning_effort", + "service_tier" + ]; + } + lc_serializable = true; + get lc_secrets() { + return { + apiKey: "OPENAI_API_KEY", + organization: "OPENAI_ORGANIZATION" + }; + } + get lc_aliases() { + return { + apiKey: "openai_api_key", + modelName: "model" + }; + } + get lc_serializable_keys() { + return [ + "configuration", + "logprobs", + "topLogprobs", + "prefixMessages", + "supportsStrictToolCalling", + "modalities", + "audio", + "temperature", + "maxTokens", + "topP", + "frequencyPenalty", + "presencePenalty", + "n", + "logitBias", + "user", + "streaming", + "streamUsage", + "model", + "modelName", + "modelKwargs", + "stop", + "stopSequences", + "timeout", + "apiKey", + "cache", + "maxConcurrency", + "maxRetries", + "verbose", + "callbacks", + "tags", + "metadata", + "disableStreaming", + "zdrEnabled", + "reasoning", + "promptCacheKey", + "promptCacheRetention", + "verbosity" + ]; + } + getLsParams(options) { + const params = this.invocationParams(options); + return { + ls_provider: "openai", + ls_model_name: this.model, + ls_model_type: "chat", + ls_temperature: params.temperature ?? void 0, + ls_max_tokens: params.max_tokens ?? void 0, + ls_stop: options.stop + }; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.model, + ...this.invocationParams(), + ...this.clientConfig + }; + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return this._identifyingParams(); + } + constructor(fields) { + super(fields ?? {}); + const configApiKey = typeof fields?.configuration?.apiKey === "string" || typeof fields?.configuration?.apiKey === "function" ? fields?.configuration?.apiKey : void 0; + this.apiKey = fields?.apiKey ?? configApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); + this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); + this.model = fields?.model ?? fields?.modelName ?? this.model; + this.modelKwargs = fields?.modelKwargs ?? {}; + this.timeout = fields?.timeout; + this.temperature = fields?.temperature ?? this.temperature; + this.topP = fields?.topP ?? this.topP; + this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; + this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; + this.logprobs = fields?.logprobs; + this.topLogprobs = fields?.topLogprobs; + this.n = fields?.n ?? this.n; + this.logitBias = fields?.logitBias; + this.stop = fields?.stopSequences ?? fields?.stop; + this.stopSequences = this.stop; + this.user = fields?.user; + this.__includeRawResponse = fields?.__includeRawResponse; + this.audio = fields?.audio; + this.modalities = fields?.modalities; + this.reasoning = fields?.reasoning; + this.maxTokens = fields?.maxCompletionTokens ?? fields?.maxTokens; + this.promptCacheKey = fields?.promptCacheKey ?? this.promptCacheKey; + this.promptCacheRetention = fields?.promptCacheRetention ?? this.promptCacheRetention; + this.verbosity = fields?.verbosity ?? this.verbosity; + this.disableStreaming = fields?.disableStreaming === true; + this.streaming = fields?.streaming === true; + if (this.disableStreaming) this.streaming = false; + if (fields?.streaming === false) this.disableStreaming = true; + this.streamUsage = fields?.streamUsage ?? this.streamUsage; + if (this.disableStreaming) this.streamUsage = false; + this.clientConfig = { + apiKey: this.apiKey, + organization: this.organization, + dangerouslyAllowBrowser: true, + ...fields?.configuration + }; + if (fields?.supportsStrictToolCalling !== void 0) this.supportsStrictToolCalling = fields.supportsStrictToolCalling; + if (fields?.service_tier !== void 0) this.service_tier = fields.service_tier; + this.zdrEnabled = fields?.zdrEnabled ?? false; + this._addVersion("@langchain/openai", "1.5.5"); + } + /** + * Returns backwards compatible reasoning parameters from constructor params and call options + * @internal + */ + _getReasoningParams(options) { + if (!isReasoningModel(this.model)) return; + let reasoning; + if (this.reasoning !== void 0) reasoning = { + ...reasoning, + ...this.reasoning + }; + if (options?.reasoning !== void 0) reasoning = { + ...reasoning, + ...options.reasoning + }; + if (options?.reasoningEffort !== void 0 && reasoning?.effort === void 0) reasoning = { + ...reasoning, + effort: options.reasoningEffort + }; + return reasoning; + } + /** + * Returns an openai compatible response format from a set of options + * @internal + */ + _getResponseFormat(resFormat) { + if (resFormat && resFormat.type === "json_schema" && resFormat.json_schema.schema && isInteropZodSchema(resFormat.json_schema.schema)) return interopZodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, { description: resFormat.json_schema.description }); + return resFormat; + } + _combineCallOptions(additionalOptions) { + return { + ...this.defaultOptions, + ...additionalOptions ?? {} + }; + } + /** @internal */ + _getClientOptions(options) { + if (!this.client) { + const endpoint = getEndpoint({ baseURL: this.clientConfig.baseURL }); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0 + }; + if (!params.baseURL) delete params.baseURL; + params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders); + this.client = new OpenAI(params); + } + return { + ...this.clientConfig, + ...options + }; + } + _convertChatOpenAIToolToCompletionsTool(tool, fields) { + if (isCustomTool(tool)) return convertResponsesCustomTool(tool.metadata.customTool); + if (isOpenAITool(tool)) { + if (fields?.strict !== void 0) return { + ...tool, + function: { + ...tool.function, + strict: fields.strict + } + }; + return tool; + } + return _convertToOpenAITool(tool, fields); + } + bindTools(tools, kwargs) { + let strict; + if (kwargs?.strict !== void 0) strict = kwargs.strict; + else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; + return this.withConfig({ + tools: tools.map((tool) => { + if (isBuiltInTool(tool) || isCustomTool(tool)) return tool; + if (hasProviderToolDefinition(tool)) return tool.extras.providerToolDefinition; + const converted = this._convertChatOpenAIToolToCompletionsTool(tool, { strict }); + if (isLangChainTool(tool) && tool.extras?.defer_loading === true) return { + ...converted, + defer_loading: true + }; + return converted; + }), + ...kwargs + }); + } + async stream(input, options) { + return super.stream(input, this._combineCallOptions(options)); + } + async invoke(input, options) { + return super.invoke(input, this._combineCallOptions(options)); + } + /** @ignore */ + _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 + } }); + } + async getNumTokensFromMessages(messages) { + let totalCount = 0; + let tokensPerMessage = 0; + let tokensPerName = 0; + if (this.model === "gpt-3.5-turbo-0301") { + tokensPerMessage = 4; + tokensPerName = -1; + } else { + tokensPerMessage = 3; + tokensPerName = 1; + } + const countPerMessage = await Promise.all(messages.map(async (message) => { + const [textCount, roleCount] = await Promise.all([this.getNumTokens(message.content), 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) try { + count += await this.getNumTokens(JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments))); + } catch (error) { + console.error("Error parsing function arguments", error, JSON.stringify(openAIMessage.additional_kwargs.function_call)); + count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments); + } + totalCount += count; + return count; + })); + totalCount += 3; + return { + totalCount, + countPerMessage + }; + } + /** @internal */ + async _getNumTokensFromGenerations(generations) { + return (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); + }))).reduce((a, b) => a + b, 0); + } + /** @internal */ + async _getEstimatedTokenCountFromPrompt(messages, functions, function_call) { + let tokens = (await this.getNumTokensFromMessages(messages)).totalCount; + if (functions && function_call !== "auto") { + const promptDefinitions = formatFunctionDefinitions(functions); + tokens += await this.getNumTokens(promptDefinitions); + tokens += 9; + } + if (functions && messages.find((m) => m._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; + } + /** + * Moderate content using OpenAI's Moderation API. + * + * This method checks whether content violates OpenAI's content policy by + * analyzing text for categories such as hate, harassment, self-harm, + * sexual content, violence, and more. + * + * @param input - The text or array of texts to moderate + * @param params - Optional parameters for the moderation request + * @param params.model - The moderation model to use. Defaults to "omni-moderation-latest". + * @param params.options - Additional options to pass to the underlying request + * @returns A promise that resolves to the moderation response containing results for each input + * + * @example + * ```typescript + * const model = new ChatOpenAI({ model: "gpt-4o-mini" }); + * + * // Moderate a single text + * const result = await model.moderateContent("This is a test message"); + * console.log(result.results[0].flagged); // false + * console.log(result.results[0].categories); // { hate: false, harassment: false, ... } + * + * // Moderate multiple texts + * const results = await model.moderateContent([ + * "Hello, how are you?", + * "This is inappropriate content" + * ]); + * results.results.forEach((result, index) => { + * console.log(`Text ${index + 1} flagged:`, result.flagged); + * }); + * + * // Use a specific moderation model + * const stableResult = await model.moderateContent( + * "Test content", + * { model: "omni-moderation-latest" } + * ); + * ``` + */ + async moderateContent(input, params) { + const clientOptions = this._getClientOptions(params?.options); + const moderationRequest = { + input, + model: params?.model ?? "omni-moderation-latest" + }; + return this.caller.call(async () => { + try { + return await this.client.moderations.create(moderationRequest, clientOptions); + } catch (e) { + throw wrapOpenAIClientError(e); + } + }); + } + /** + * Return profiling information for the model. + * + * Provides information about the model's capabilities and constraints, + * including token limits, multimodal support, and advanced features like + * tool calling and structured output. + * + * @returns {ModelProfile} An object describing the model's capabilities and constraints + * + * @example + * ```typescript + * const model = new ChatOpenAI({ model: "gpt-4o" }); + * const profile = model.profile; + * console.log(profile.maxInputTokens); // 128000 + * console.log(profile.imageInputs); // true + * ``` + */ + get profile() { + return PROFILES[this.model] ?? {}; + } + /** @internal */ + _getStructuredOutputMethod(config) { + const ensuredConfig = { ...config }; + if (!this.model.startsWith("gpt-3") && !this.model.startsWith("gpt-4-") && this.model !== "gpt-4") { + if (ensuredConfig?.method === void 0) return "jsonSchema"; + } else if (ensuredConfig.method === "jsonSchema") console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`); + return ensuredConfig.method; + } + /** + * Add structured output to the model. + * + * The OpenAI model family supports the following structured output methods: + * - `jsonSchema`: Use the `response_format` field in the response to return a JSON schema. Only supported with the `gpt-4o-mini`, + * `gpt-4o-mini-2024-07-18`, and `gpt-4o-2024-08-06` model snapshots and later. + * - `functionCalling`: Function calling is useful when you are building an application that bridges the models and functionality + * of your application. + * - `jsonMode`: JSON mode is a more basic version of the Structured Outputs feature. While JSON mode ensures that model + * output is valid JSON, Structured Outputs reliably matches the model's output to the schema you specify. + * We recommend you use `functionCalling` or `jsonSchema` if it is supported for your use case. + * + * The default method is `functionCalling`. + * + * @see https://platform.openai.com/docs/guides/structured-outputs + * @param outputSchema - The schema to use for structured output. + * @param config - The structured output method options. + * @returns The model with structured output. + */ + withStructuredOutput(outputSchema, config) { + let llm; + let outputParser; + const { schema, name, includeRaw } = { + ...config, + schema: outputSchema + }; + if (config?.strict !== void 0 && config.method === "jsonMode") throw new Error("Argument `strict` is only supported for `method` = 'function_calling'"); + const method = getStructuredOutputMethod(this.model, config?.method); + if (method === "jsonMode") { + outputParser = createContentParser(schema); + const asJsonSchema = toJsonSchema(schema); + llm = this.withConfig({ + outputVersion: "v0", + response_format: { type: "json_object" }, + ls_structured_output_format: { + kwargs: { method: "json_mode" }, + schema: { + title: name ?? "extract", + ...asJsonSchema + } + } + }); + } else if (method === "jsonSchema") { + const asJsonSchema = toJsonSchema(schema); + const openaiJsonSchemaParams = { + name: name ?? "extract", + description: getSchemaDescription(asJsonSchema), + schema: isInteropZodSchema(schema) ? schema : asJsonSchema, + strict: config?.strict + }; + llm = this.withConfig({ + outputVersion: "v0", + response_format: { + type: "json_schema", + json_schema: openaiJsonSchemaParams + }, + ls_structured_output_format: { + kwargs: { method: "json_schema" }, + schema: { + title: openaiJsonSchemaParams.name, + description: openaiJsonSchemaParams.description, + ...asJsonSchema + } + } + }); + if (isInteropZodSchema(schema) || isSerializableSchema(schema)) { + const altParser = createContentParser(schema); + outputParser = RunnableLambda.from(async (aiMessage) => { + if ("parsed" in aiMessage.additional_kwargs) return aiMessage.additional_kwargs.parsed; + return altParser.invoke(aiMessage.content); + }); + } else outputParser = new JsonOutputParser(); + } else { + let functionName = name ?? "extract"; + const asJsonSchema = toJsonSchema(schema); + let toolFunction; + if (isInteropZodSchema(schema) || isSerializableSchema(schema)) toolFunction = { + name: functionName, + description: asJsonSchema.description, + parameters: asJsonSchema + }; + else if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) { + toolFunction = schema; + functionName = schema.name; + } else { + functionName = schema.title ?? functionName; + toolFunction = { + name: functionName, + description: schema.description ?? "", + parameters: schema + }; + } + llm = this.withConfig({ + outputVersion: "v0", + tools: [{ + type: "function", + function: toolFunction + }], + tool_choice: { + type: "function", + function: { name: functionName } + }, + ls_structured_output_format: { + kwargs: { method: "function_calling" }, + schema: { + title: functionName, + ...asJsonSchema + } + }, + ...config?.strict !== void 0 ? { strict: config.strict } : {} + }); + outputParser = createFunctionCallingParser(schema, functionName); + } + return assembleStructuredOutputPipeline(llm, outputParser, includeRaw); + } +}; +//#endregion +//#region node_modules/@langchain/openai/dist/converters/completions.js +/** +* @deprecated This converter is an internal detail of the OpenAI provider. Do not use it directly. This will be revisited in a future release. +*/ +var completionsApiContentBlockConverter = { + providerName: "ChatOpenAI", + fromStandardTextBlock(block) { + return { + type: "text", + text: block.text + }; + }, + fromStandardImageBlock(block) { + if (block.source_type === "url") return { + type: "image_url", + image_url: { + url: block.url, + ...block.metadata?.detail ? { detail: block.metadata.detail } : {} + } + }; + if (block.source_type === "base64") return { + type: "image_url", + image_url: { + url: `data:${block.mime_type ?? ""};base64,${block.data}`, + ...block.metadata?.detail ? { detail: block.metadata.detail } : {} + } + }; + throw new Error(`Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); + }, + fromStandardAudioBlock(block) { + if (block.source_type === "url") { + const data = parseBase64DataUrl({ dataUrl: block.url }); + if (!data) throw new Error(`URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`); + const rawMimeType = data.mime_type || block.mime_type || ""; + let mimeType; + try { + mimeType = parseMimeType(rawMimeType); + } catch { + throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); + } + if (mimeType.type !== "audio" || mimeType.subtype !== "wav" && mimeType.subtype !== "mp3") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); + return { + type: "input_audio", + input_audio: { + format: mimeType.subtype, + data: data.data + } + }; + } + if (block.source_type === "base64") { + let mimeType; + try { + mimeType = parseMimeType(block.mime_type ?? ""); + } catch { + throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); + } + if (mimeType.type !== "audio" || mimeType.subtype !== "wav" && mimeType.subtype !== "mp3") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); + return { + type: "input_audio", + input_audio: { + format: mimeType.subtype, + data: block.data + } + }; + } + throw new Error(`Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); + }, + fromStandardFileBlock(block) { + if (block.source_type === "url") { + const data = parseBase64DataUrl({ dataUrl: block.url }); + const filename = getRequiredFilenameFromMetadata(block); + if (!data) throw new Error(`URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`); + return { + type: "file", + file: { + file_data: block.url, + filename + } + }; + } + if (block.source_type === "base64") { + const filename = getRequiredFilenameFromMetadata(block); + return { + type: "file", + file: { + file_data: `data:${block.mime_type ?? ""};base64,${block.data}`, + filename + } + }; + } + if (block.source_type === "id") return { + type: "file", + file: { file_id: block.id } + }; + throw new Error(`File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); + } +}; +/** +* Converts an OpenAI Chat Completions API message to a LangChain BaseMessage. +* +* This converter transforms messages from OpenAI's Chat Completions API format into +* LangChain's internal message representation, handling various message types and +* preserving metadata, tool calls, and other relevant information. +* +* @remarks +* The converter handles the following message roles: +* - `assistant`: Converted to {@link AIMessage} with support for tool calls, function calls, +* audio content, and multi-modal outputs +* - Other roles: Converted to generic {@link ChatMessage} +* +* For assistant messages, the converter: +* - Parses and validates tool calls, separating valid and invalid calls +* - Preserves function call information in additional_kwargs +* - Includes usage statistics and system fingerprint in response_metadata +* - Handles multi-modal content (text, images, audio) +* - Optionally includes the raw API response for debugging +* +* @param params - Conversion parameters +* @param params.message - The OpenAI chat completion message to convert +* @param params.rawResponse - The complete raw response from OpenAI's API, used to extract +* metadata like model name, usage statistics, and system fingerprint +* @param params.includeRawResponse - If true, includes the raw OpenAI response in the +* message's additional_kwargs under the `__raw_response` key. Useful for debugging +* or accessing provider-specific fields. Defaults to false. +* +* @returns A LangChain BaseMessage instance: +* - {@link AIMessage} for assistant messages with tool calls, metadata, and content +* - {@link ChatMessage} for all other message types +* +* @example +* ```typescript +* const baseMessage = convertCompletionsMessageToBaseMessage({ +* message: { +* role: "assistant", +* content: "Hello! How can I help you?", +* tool_calls: [ +* { +* id: "call_123", +* type: "function", +* function: { name: "get_weather", arguments: '{"location":"NYC"}' } +* } +* ] +* }, +* rawResponse: completionResponse, +* includeRawResponse: true +* }); +* // Returns an AIMessage with parsed tool calls and metadata +* ``` +* +* @throws {Error} If tool call parsing fails, the invalid tool call is captured in +* the `invalid_tool_calls` array rather than throwing an error +* +*/ +var convertCompletionsMessageToBaseMessage = ({ message, rawResponse, includeRawResponse }) => { + const rawToolCalls = message.tool_calls; + const providerReasoningContent = message.reasoning_content; + switch (message.role) { + case "assistant": { + const toolCalls = []; + const invalidToolCalls = []; + for (const rawToolCall of rawToolCalls ?? []) try { + toolCalls.push(parseToolCall$2(rawToolCall, { returnId: true })); + } catch (e) { + invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message)); + } + const additional_kwargs = { + function_call: message.function_call, + tool_calls: rawToolCalls + }; + if (includeRawResponse !== void 0) additional_kwargs.__raw_response = rawResponse; + if (providerReasoningContent !== void 0) additional_kwargs.reasoning_content = providerReasoningContent; + const response_metadata = { + model_provider: "openai", + model_name: rawResponse.model, + ...rawResponse.system_fingerprint ? { + usage: { ...rawResponse.usage }, + system_fingerprint: rawResponse.system_fingerprint + } : {} + }; + if (message.audio) additional_kwargs.audio = message.audio; + return new AIMessage({ + content: handleMultiModalOutput(message.content || "", rawResponse.choices?.[0]?.message), + tool_calls: toolCalls, + invalid_tool_calls: invalidToolCalls, + additional_kwargs, + response_metadata, + id: rawResponse.id + }); + } + default: return new ChatMessage(message.content || "", message.role ?? "unknown"); + } +}; +/** +* Converts an OpenAI Chat Completions API delta (streaming chunk) to a LangChain BaseMessageChunk. +* +* This converter is used during streaming responses to transform incremental updates from OpenAI's +* Chat Completions API into LangChain message chunks. It handles various message types, tool calls, +* function calls, audio content, and role-specific message chunk creation. +* +* @param params - Conversion parameters +* @param params.delta - The delta object from an OpenAI streaming chunk containing incremental +* message updates. May include content, role, tool_calls, function_call, audio, etc. +* @param params.rawResponse - The complete raw ChatCompletionChunk response from OpenAI, +* containing metadata like model info, usage stats, and the delta +* @param params.includeRawResponse - Optional flag to include the raw OpenAI response in the +* message chunk's additional_kwargs. Useful for debugging or accessing provider-specific data +* @param params.defaultRole - Optional default role to use if the delta doesn't specify one. +* Typically used to maintain role consistency across chunks in a streaming response +* +* @returns A BaseMessageChunk subclass appropriate for the message role: +* - HumanMessageChunk for "user" role +* - AIMessageChunk for "assistant" role (includes tool call chunks) +* - SystemMessageChunk for "system" or "developer" roles +* - FunctionMessageChunk for "function" role +* - ToolMessageChunk for "tool" role +* - ChatMessageChunk for any other role +* +* @example +* Basic streaming text chunk: +* ```typescript +* const chunk = convertCompletionsDeltaToBaseMessageChunk({ +* delta: { role: "assistant", content: "Hello" }, +* rawResponse: { id: "chatcmpl-123", model: "gpt-4", ... } +* }); +* // Returns: AIMessageChunk with content "Hello" +* ``` +* +* @example +* Streaming chunk with tool call: +* ```typescript +* const chunk = convertCompletionsDeltaToBaseMessageChunk({ +* delta: { +* role: "assistant", +* tool_calls: [{ +* index: 0, +* id: "call_123", +* function: { name: "get_weather", arguments: '{"location":' } +* }] +* }, +* rawResponse: { id: "chatcmpl-123", ... } +* }); +* // Returns: AIMessageChunk with tool_call_chunks containing partial tool call data +* ``` +* +* @remarks +* - Tool calls are converted to ToolCallChunk objects with incremental data +* - Audio content includes the chunk index from the raw response +* - The "developer" role is mapped to SystemMessageChunk with a special marker +* - Response metadata includes model provider info and usage statistics +* - Function calls and tool calls are stored in additional_kwargs for compatibility +*/ +var convertCompletionsDeltaToBaseMessageChunk = ({ delta, rawResponse, includeRawResponse, 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 (includeRawResponse) additional_kwargs.__raw_response = rawResponse; + if (delta.reasoning_content !== void 0) additional_kwargs.reasoning_content = delta.reasoning_content; + if (delta.audio) additional_kwargs.audio = { + ...delta.audio, + index: rawResponse.choices[0].index + }; + const response_metadata = { + model_provider: "openai", + usage: { ...rawResponse.usage } + }; + if (role === "user") return new HumanMessageChunk({ + content, + response_metadata + }); + else if (role === "assistant") { + const toolCallChunks = []; + if (Array.isArray(delta.tool_calls)) for (const rawToolCall of delta.tool_calls) toolCallChunks.push({ + name: rawToolCall.function?.name, + args: rawToolCall.function?.arguments, + id: rawToolCall.id, + index: rawToolCall.index, + type: "tool_call_chunk" + }); + return new AIMessageChunk({ + content, + tool_call_chunks: toolCallChunks, + additional_kwargs, + id: rawResponse.id, + response_metadata + }); + } else if (role === "system") return new SystemMessageChunk({ + content, + response_metadata + }); + else if (role === "developer") return new SystemMessageChunk({ + content, + response_metadata, + additional_kwargs: { __openai_role__: "developer" } + }); + else if (role === "function") return new FunctionMessageChunk({ + content, + additional_kwargs, + name: delta.name, + response_metadata + }); + else if (role === "tool") return new ToolMessageChunk({ + content, + additional_kwargs, + tool_call_id: delta.tool_call_id, + response_metadata + }); + else return new ChatMessageChunk({ + content, + role, + response_metadata + }); +}; +/** +* Converts a standard LangChain content block to an OpenAI Completions API content part. +* +* This converter transforms LangChain's standardized content blocks (image, audio, file) +* into the format expected by OpenAI's Chat Completions API. It handles various content +* types including images (URL or base64), audio (base64), and files (data or file ID). +* +* @param block - The standard content block to convert. Can be an image, audio, or file block. +* +* @returns An OpenAI Chat Completions content part object, or undefined if the block +* cannot be converted (e.g., missing required data). +* +* @example +* Image with URL: +* ```typescript +* const block = { type: "image", url: "https://example.com/image.jpg" }; +* const part = convertStandardContentBlockToCompletionsContentPart(block); +* // Returns: { type: "image_url", image_url: { url: "https://example.com/image.jpg" } } +* ``` +* +* @example +* Image with base64 data: +* ```typescript +* const block = { type: "image", data: "iVBORw0KGgo...", mimeType: "image/png" }; +* const part = convertStandardContentBlockToCompletionsContentPart(block); +* // Returns: { type: "image_url", image_url: { url: "data:image/png;base64,iVBORw0KGgo..." } } +* ``` +*/ +var convertStandardContentBlockToCompletionsContentPart = (block) => { + if (block.type === "image") { + if (block.url) return { + type: "image_url", + image_url: { url: block.url } + }; + else if (block.data) return { + type: "image_url", + image_url: { url: `data:${block.mimeType};base64,${block.data}` } + }; + } + if (block.type === "audio") { + if (block.data) { + const format = iife(() => { + const [, format] = block.mimeType.split("/"); + if (format === "wav" || format === "mp3") return format; + return "wav"; + }); + return { + type: "input_audio", + input_audio: { + data: block.data.toString(), + format + } + }; + } + } + if (block.type === "file") { + if (block.data) { + const filename = getRequiredFilenameFromMetadata(block); + return { + type: "file", + file: { + file_data: `data:${block.mimeType};base64,${block.data}`, + filename + } + }; + } + if (block.fileId) return { + type: "file", + file: { file_id: block.fileId } + }; + } +}; +/** +* Converts a LangChain BaseMessage with standard content blocks to an OpenAI Chat Completions API message parameter. +* +* This converter transforms LangChain's standardized message format (using contentBlocks) into the format +* expected by OpenAI's Chat Completions API. It handles role mapping, content filtering, and multi-modal +* content conversion for various message types. +* +* @remarks +* The converter performs the following transformations: +* - Maps LangChain message roles to OpenAI API roles (user, assistant, system, developer, tool, function) +* - For reasoning models, automatically converts "system" role to "developer" role +* - Filters content blocks based on message role (most roles only include text blocks) +* - For user messages, converts multi-modal content blocks (images, audio, files) to OpenAI format +* - Preserves tool call IDs for tool messages and function names for function messages +* +* Role-specific behavior: +* - **developer**: Returns only text content blocks (used for reasoning models) +* - **system**: Returns only text content blocks +* - **assistant**: Returns only text content blocks +* - **tool**: Returns only text content blocks with tool_call_id preserved +* - **function**: Returns text content blocks joined as a single string with function name +* - **user** (default): Returns multi-modal content including text, images, audio, and files +* +* @param params - Conversion parameters +* @param params.message - The LangChain BaseMessage to convert. Must have contentBlocks property +* containing an array of standard content blocks (text, image, audio, file, etc.) +* @param params.model - Optional model name. Used to determine if special role mapping is needed +* (e.g., "system" -> "developer" for reasoning models like o1) +* +* @returns An OpenAI ChatCompletionMessageParam object formatted for the Chat Completions API. +* The structure varies by role: +* - Developer/System/Assistant: `{ role, content: TextBlock[] }` +* - Tool: `{ role: "tool", tool_call_id, content: TextBlock[] }` +* - Function: `{ role: "function", name, content: string }` +* - User: `{ role: "user", content: Array }` +* +* @example +* Simple text message: +* ```typescript +* const message = new HumanMessage({ +* content: [{ type: "text", text: "Hello!" }] +* }); +* const param = convertStandardContentMessageToCompletionsMessage({ message }); +* // Returns: { role: "user", content: [{ type: "text", text: "Hello!" }] } +* ``` +* +* @example +* Multi-modal user message with image: +* ```typescript +* const message = new HumanMessage({ +* content: [ +* { type: "text", text: "What's in this image?" }, +* { type: "image", url: "https://example.com/image.jpg" } +* ] +* }); +* const param = convertStandardContentMessageToCompletionsMessage({ message }); +* // Returns: { +* // role: "user", +* // content: [ +* // { type: "text", text: "What's in this image?" }, +* // { type: "image_url", image_url: { url: "https://example.com/image.jpg" } } +* // ] +* // } +* ``` +*/ +var convertStandardContentMessageToCompletionsMessage = ({ message, model }) => { + let role = messageToOpenAIRole(message); + if (role === "system" && isReasoningModel(model)) role = "developer"; + if (role === "developer") return { + role: "developer", + content: message.contentBlocks.filter((block) => block.type === "text") + }; + else if (role === "system") return { + role: "system", + content: message.contentBlocks.filter((block) => block.type === "text") + }; + else if (role === "assistant") { + const completionParam = { + role: "assistant", + content: message.contentBlocks.filter((block) => block.type === "text") + }; + if (AIMessage.isInstance(message) && !!message.tool_calls?.length) completionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI); + else if (message.additional_kwargs.tool_calls != null) completionParam.tool_calls = message.additional_kwargs.tool_calls; + return completionParam; + } else if (role === "tool" && ToolMessage.isInstance(message)) return { + role: "tool", + tool_call_id: message.tool_call_id, + content: message.contentBlocks.filter((block) => block.type === "text") + }; + else if (role === "function") return { + role: "function", + name: message.name ?? "", + content: message.contentBlocks.filter((block) => block.type === "text").join("") + }; + function* iterateUserContent(blocks) { + for (const block of blocks) { + if (block.type === "text") yield { + type: "text", + text: block.text + }; + const data = convertStandardContentBlockToCompletionsContentPart(block); + if (data) yield data; + } + } + return { + role: "user", + content: Array.from(iterateUserContent(message.contentBlocks)) + }; +}; +/** +* Converts an array of LangChain BaseMessages to OpenAI Chat Completions API message parameters. +* +* This converter transforms LangChain's internal message representation into the format required +* by OpenAI's Chat Completions API. It handles various message types, roles, content formats, +* tool calls, function calls, audio messages, and special model-specific requirements. +* +* @remarks +* The converter performs several key transformations: +* - Maps LangChain message types to OpenAI roles (user, assistant, system, tool, function, developer) +* - Converts standard content blocks (v1 format) using a specialized converter +* - Handles multimodal content including text, images, audio, and data blocks +* - Preserves tool calls and function calls with proper formatting +* - Applies model-specific role mappings (e.g., "system" → "developer" for reasoning models) +* - Splits audio messages into separate message parameters when needed +* +* @param params - Conversion parameters +* @param params.messages - Array of LangChain BaseMessages to convert. Can include any message +* type: HumanMessage, AIMessage, SystemMessage, ToolMessage, FunctionMessage, etc. +* @param params.model - Optional model name used to determine if special role mapping is needed. +* For reasoning models (o1, o3, etc.), "system" role is converted to "developer" role. +* +* @returns Array of ChatCompletionMessageParam objects formatted for OpenAI's Chat Completions API. +* Some messages may be split into multiple parameters (e.g., audio messages). +* +* @example +* Basic message conversion: +* ```typescript +* const messages = [ +* new HumanMessage("What's the weather like?"), +* new AIMessage("Let me check that for you.") +* ]; +* +* const params = convertMessagesToCompletionsMessageParams({ +* messages, +* model: "gpt-4" +* }); +* // Returns: +* // [ +* // { role: "user", content: "What's the weather like?" }, +* // { role: "assistant", content: "Let me check that for you." } +* // ] +* ``` +* +* @example +* Message with tool calls: +* ```typescript +* const messages = [ +* new AIMessage({ +* content: "", +* tool_calls: [{ +* id: "call_123", +* name: "get_weather", +* args: { location: "San Francisco" } +* }] +* }) +* ]; +* +* const params = convertMessagesToCompletionsMessageParams({ messages }); +* // Returns: +* // [{ +* // role: "assistant", +* // content: "", +* // tool_calls: [{ +* // id: "call_123", +* // type: "function", +* // function: { name: "get_weather", arguments: '{"location":"San Francisco"}' } +* // }] +* // }] +* ``` +*/ +var convertMessagesToCompletionsMessageParams = ({ messages, model }) => { + return messages.flatMap((message) => { + if ("output_version" in message.response_metadata && message.response_metadata?.output_version === "v1") return convertStandardContentMessageToCompletionsMessage({ message }); + let role = messageToOpenAIRole(message); + if (role === "system" && isReasoningModel(model)) role = "developer"; + const content = typeof message.content === "string" ? message.content : message.content.flatMap((m) => { + if (isDataContentBlock(m)) return convertToProviderContentBlock(m, completionsApiContentBlockConverter); + if (typeof m === "object" && m !== null && "type" in m && (m.type === "tool_use" || m.type === "tool_call" || m.type === "reasoning" || m.type === "reasoning_content" || m.type === "thinking")) return []; + return m; + }); + const completionParam = { + role, + content + }; + if (message.name != null) completionParam.name = message.name; + if (message.additional_kwargs.function_call != null) completionParam.function_call = message.additional_kwargs.function_call; + if (AIMessage.isInstance(message) && !!message.tool_calls?.length) completionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI); + else { + if (message.additional_kwargs.tool_calls != null) completionParam.tool_calls = message.additional_kwargs.tool_calls; + if (ToolMessage.isInstance(message) && message.tool_call_id != null) completionParam.tool_call_id = message.tool_call_id; + } + if (message.additional_kwargs.audio && typeof message.additional_kwargs.audio === "object" && "id" in message.additional_kwargs.audio) return [completionParam, { + role: "assistant", + audio: { id: message.additional_kwargs.audio.id } + }]; + return completionParam; + }); +}; +//#endregion +//#region node_modules/@langchain/openai/dist/chat_models/completions.js +/** +* OpenAI Completions API implementation. +* @internal +*/ +var ChatOpenAICompletions = class extends BaseChatOpenAI { + constructor(modelOrFields, fieldsArg) { + super(getChatOpenAIModelParams(modelOrFields, fieldsArg)); + } + /** @internal */ + invocationParams(options, extra) { + let strict; + if (options?.strict !== void 0) strict = options.strict; + else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; + if (!(this.streaming || extra?.streaming) && options?.response_format?.type === "json_schema" && strict !== false) strict = true; + let streamOptionsConfig = {}; + if (options?.stream_options !== void 0) streamOptionsConfig = { stream_options: options.stream_options }; + else if (this.streamUsage && (this.streaming || extra?.streaming)) streamOptionsConfig = { stream_options: { include_usage: true } }; + const params = { + model: this.model, + temperature: this.temperature, + top_p: this.topP, + frequency_penalty: this.frequencyPenalty, + presence_penalty: this.presencePenalty, + logprobs: this.logprobs, + top_logprobs: this.topLogprobs, + n: this.n, + logit_bias: this.logitBias, + stop: options?.stop ?? this.stopSequences, + user: this.user, + stream: this.streaming, + functions: options?.functions, + function_call: options?.function_call, + tools: options?.tools?.length ? options.tools.map((tool) => this._convertChatOpenAIToolToCompletionsTool(tool, { strict })) : void 0, + tool_choice: formatToOpenAIToolChoice(options?.tool_choice), + response_format: this._getResponseFormat(options?.response_format), + seed: options?.seed, + ...streamOptionsConfig, + parallel_tool_calls: options?.parallel_tool_calls, + ...this.audio || options?.audio ? { audio: this.audio || options?.audio } : {}, + ...this.modalities || options?.modalities ? { modalities: this.modalities || options?.modalities } : {}, + ...this.modelKwargs, + prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey, + prompt_cache_retention: options?.promptCacheRetention ?? this.promptCacheRetention, + verbosity: options?.verbosity ?? this.verbosity + }; + if (options?.prediction !== void 0) params.prediction = options.prediction; + if (this.service_tier !== void 0) params.service_tier = this.service_tier; + if (options?.service_tier !== void 0) params.service_tier = options.service_tier; + const reasoning = this._getReasoningParams(options); + if (reasoning !== void 0 && reasoning.effort !== void 0) params.reasoning_effort = reasoning.effort; + if (isReasoningModel(params.model)) params.max_completion_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens; + else params.max_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens; + return params; + } + async _generate(messages, options, runManager) { + options.signal?.throwIfAborted(); + const usageMetadata = {}; + const params = this.invocationParams(options); + const messagesMapped = convertMessagesToCompletionsMessageParams({ + messages, + model: this.model + }); + if (params.stream) { + const stream = this._streamResponseChunks(messages, options, runManager); + const finalChunks = {}; + for await (const chunk of stream) { + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata + }; + const index = chunk.generationInfo?.completion ?? 0; + if (finalChunks[index] === void 0) finalChunks[index] = chunk; + else finalChunks[index] = finalChunks[index].concat(chunk); + } + const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value); + const { functions, function_call } = this.invocationParams(options); + const promptTokenUsage = await this._getEstimatedTokenCountFromPrompt(messages, functions, function_call); + const completionTokenUsage = await this._getNumTokensFromGenerations(generations); + usageMetadata.input_tokens = promptTokenUsage; + usageMetadata.output_tokens = completionTokenUsage; + usageMetadata.total_tokens = promptTokenUsage + completionTokenUsage; + return { + generations, + llmOutput: { estimatedTokenUsage: { + promptTokens: usageMetadata.input_tokens, + completionTokens: usageMetadata.output_tokens, + totalTokens: usageMetadata.total_tokens + } } + }; + } 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, prompt_tokens_details: promptTokensDetails, completion_tokens_details: completionTokensDetails } = data?.usage ?? {}; + if (completionTokens) usageMetadata.output_tokens = (usageMetadata.output_tokens ?? 0) + completionTokens; + if (promptTokens) usageMetadata.input_tokens = (usageMetadata.input_tokens ?? 0) + promptTokens; + if (totalTokens) usageMetadata.total_tokens = (usageMetadata.total_tokens ?? 0) + totalTokens; + if (promptTokensDetails?.audio_tokens !== null || promptTokensDetails?.cached_tokens !== null) usageMetadata.input_token_details = { + ...promptTokensDetails?.audio_tokens !== null && { audio: promptTokensDetails?.audio_tokens }, + ...promptTokensDetails?.cached_tokens !== null && { cache_read: promptTokensDetails?.cached_tokens } + }; + if (completionTokensDetails?.audio_tokens !== null || completionTokensDetails?.reasoning_tokens !== null) usageMetadata.output_token_details = { + ...completionTokensDetails?.audio_tokens !== null && { audio: completionTokensDetails?.audio_tokens }, + ...completionTokensDetails?.reasoning_tokens !== null && { reasoning: completionTokensDetails?.reasoning_tokens } + }; + const generations = []; + for (const part of data?.choices ?? []) { + const generation = { + text: part.message?.content ?? "", + message: this._convertCompletionsMessageToBaseMessage(part.message ?? { role: "assistant" }, data) + }; + generation.generationInfo = { + ...part.finish_reason ? { finish_reason: part.finish_reason } : {}, + ...part.logprobs ? { logprobs: part.logprobs } : {} + }; + if (isAIMessage(generation.message)) generation.message.usage_metadata = usageMetadata; + generation.message = new AIMessage(Object.fromEntries(Object.entries(generation.message).filter(([key]) => !key.startsWith("lc_")))); + generations.push(generation); + } + return { + generations, + llmOutput: { tokenUsage: { + promptTokens: usageMetadata.input_tokens, + completionTokens: usageMetadata.output_tokens, + totalTokens: usageMetadata.total_tokens + } } + }; + } + } + /** + * Native implementation of the content-block-centric streaming protocol + * for OpenAI Chat Completions. + */ + async *_streamChatModelEvents(messages, options, _runManager) { + const messagesMapped = convertMessagesToCompletionsMessageParams({ + messages, + model: this.model + }); + const params = { + ...this.invocationParams(options, { streaming: true }), + messages: messagesMapped, + stream: true + }; + const streamIterable = await this.completionWithRetry(params, options); + const shouldStreamUsage = this.streamUsage ?? options.streamUsage; + const abortableStream = async function* (source, signal) { + for await (const data of source) { + if (signal?.aborted) return; + yield data; + } + }; + yield* convertOpenAICompletionsStream(abortableStream(streamIterable, options.signal), { + streamUsage: shouldStreamUsage ?? true, + provider: this.streamEventProvider + }); + } + /** Provider id used in native stream protocol passthrough events. */ + get streamEventProvider() { + return "openai"; + } + async *_streamResponseChunks(messages, options, runManager) { + const messagesMapped = convertMessagesToCompletionsMessageParams({ + messages, + model: this.model + }); + const params = { + ...this.invocationParams(options, { streaming: true }), + messages: messagesMapped, + stream: true + }; + let defaultRole; + const streamIterable = await this.completionWithRetry(params, options); + let usage; + for await (const data of streamIterable) { + if (options.signal?.aborted) return; + const choice = data?.choices?.[0]; + if (data.usage) usage = data.usage; + if (!choice) continue; + const { delta } = choice; + if (!delta) continue; + const chunk = this._convertCompletionsDeltaToBaseMessageChunk(delta, data, 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 != null) { + generationInfo.finish_reason = choice.finish_reason; + generationInfo.system_fingerprint = data.system_fingerprint; + generationInfo.model_name = data.model; + generationInfo.service_tier = data.service_tier; + } + if (this.logprobs) generationInfo.logprobs = choice.logprobs; + const generationChunk = new ChatGenerationChunk({ + message: chunk, + text: chunk.content, + generationInfo + }); + yield generationChunk; + await runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk }); + } + if (usage) { + const inputTokenDetails = { + ...usage.prompt_tokens_details?.audio_tokens !== null && { audio: usage.prompt_tokens_details?.audio_tokens }, + ...usage.prompt_tokens_details?.cached_tokens !== null && { cache_read: usage.prompt_tokens_details?.cached_tokens } + }; + const outputTokenDetails = { + ...usage.completion_tokens_details?.audio_tokens !== null && { audio: usage.completion_tokens_details?.audio_tokens }, + ...usage.completion_tokens_details?.reasoning_tokens !== null && { reasoning: usage.completion_tokens_details?.reasoning_tokens } + }; + const generationChunk = new ChatGenerationChunk({ + message: new AIMessageChunk({ + content: "", + response_metadata: { usage: { ...usage } }, + usage_metadata: { + input_tokens: usage.prompt_tokens, + output_tokens: usage.completion_tokens, + total_tokens: usage.total_tokens, + ...Object.keys(inputTokenDetails).length > 0 && { input_token_details: inputTokenDetails }, + ...Object.keys(outputTokenDetails).length > 0 && { output_token_details: outputTokenDetails } + } + }), + text: "" + }); + yield generationChunk; + await runManager?.handleLLMNewToken(generationChunk.text ?? "", { + prompt: 0, + completion: 0 + }, void 0, void 0, void 0, { chunk: generationChunk }); + } + if (options.signal?.aborted) throw new Error("AbortError"); + } + async completionWithRetry(request, requestOptions) { + const clientOptions = this._getClientOptions(requestOptions); + const isParseableFormat = request.response_format && request.response_format.type === "json_schema"; + return this.caller.call(async () => { + try { + if (isParseableFormat && !request.stream) return await this.client.chat.completions.parse(request, clientOptions); + else return await this.client.chat.completions.create(request, clientOptions); + } catch (e) { + throw wrapOpenAIClientError(e); + } + }); + } + /** + * @deprecated + * This function was hoisted into a publicly accessible function from a + * different export, but to maintain backwards compatibility with chat models + * that depend on ChatOpenAICompletions, we'll keep it here as an overridable + * method. This will be removed in a future release + */ + _convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) { + return convertCompletionsDeltaToBaseMessageChunk({ + delta, + rawResponse, + includeRawResponse: this.__includeRawResponse, + defaultRole + }); + } + /** + * @deprecated + * This function was hoisted into a publicly accessible function from a + * different export, but to maintain backwards compatibility with chat models + * that depend on ChatOpenAICompletions, we'll keep it here as an overridable + * method. This will be removed in a future release + */ + _convertCompletionsMessageToBaseMessage(message, rawResponse) { + return convertCompletionsMessageToBaseMessage({ + message, + rawResponse, + includeRawResponse: this.__includeRawResponse + }); + } +}; +//#endregion +//#region node_modules/@langchain/openai/dist/converters/responses.js +var _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__"; +var _CUSTOM_TOOL_CALL_IDS_MAP_KEY = "__openai_custom_tool_call_ids__"; +/** +* Converts an OpenAI annotation to a LangChain Citation or BaseContentBlock. +* +* OpenAI has several annotation types: +* - `url_citation`: Web citations with url, title, start_index, end_index +* - `file_citation`: File citations with file_id, filename, index +* - `container_file_citation`: Container file citations with container_id, file_id, filename, start_index, end_index +* - `file_path`: File paths with file_id, index +* +* This function maps them to LangChain's Citation format or preserves them as non-standard blocks. +*/ +function convertOpenAIAnnotationToLangChain(annotation) { + if (annotation.type === "url_citation") return { + type: "citation", + source: "url_citation", + url: annotation.url, + title: annotation.title, + startIndex: annotation.start_index, + endIndex: annotation.end_index + }; + if (annotation.type === "file_citation") return { + type: "citation", + source: "file_citation", + title: annotation.filename, + startIndex: annotation.index, + file_id: annotation.file_id + }; + if (annotation.type === "container_file_citation") return { + type: "citation", + source: "container_file_citation", + title: annotation.filename, + startIndex: annotation.start_index, + endIndex: annotation.end_index, + file_id: annotation.file_id, + container_id: annotation.container_id + }; + if (annotation.type === "file_path") return { + type: "citation", + source: "file_path", + startIndex: annotation.index, + file_id: annotation.file_id + }; + return { + type: "non_standard", + value: annotation + }; +} +/** +* Converts a LangChain Citation or BaseContentBlock back to an OpenAI annotation. +* +* This is the inverse of `convertOpenAIAnnotationToLangChain`. It handles all four +* annotation types (url_citation, file_citation, container_file_citation, file_path) +* and also passes through annotations that are already in OpenAI format. +*/ +function convertLangChainAnnotationToOpenAI(annotation) { + if (annotation.type === "url_citation" || annotation.type === "file_citation" || annotation.type === "container_file_citation" || annotation.type === "file_path") return annotation; + if (annotation.type === "citation") { + const citation = annotation; + if (citation.source === "url_citation") return { + type: "url_citation", + url: citation.url ?? "", + title: citation.title ?? "", + start_index: citation.startIndex ?? 0, + end_index: citation.endIndex ?? 0 + }; + if (citation.source === "file_citation") return { + type: "file_citation", + file_id: citation.file_id ?? "", + filename: citation.title ?? "", + index: citation.startIndex ?? 0 + }; + if (citation.source === "container_file_citation") return { + type: "container_file_citation", + file_id: citation.file_id ?? "", + filename: citation.title ?? "", + container_id: citation.container_id ?? "", + start_index: citation.startIndex ?? 0, + end_index: citation.endIndex ?? 0 + }; + if (citation.source === "file_path") return { + type: "file_path", + file_id: citation.file_id ?? "", + index: citation.startIndex ?? 0 + }; + } + if (annotation.type === "non_standard") return annotation.value; + return annotation; +} +/** +* Converts OpenAI Responses API usage statistics to LangChain's UsageMetadata format. +* +* This converter transforms token usage information from OpenAI's Responses API into +* the standardized UsageMetadata format used throughout LangChain. It handles both +* basic token counts and detailed token breakdowns including cached tokens and +* reasoning tokens. +* +* @param usage - The usage statistics object from OpenAI's Responses API containing +* token counts and optional detailed breakdowns. +* +* @returns A UsageMetadata object containing: +* - `input_tokens`: Total number of tokens in the input/prompt (defaults to 0 if not provided) +* - `output_tokens`: Total number of tokens in the model's output (defaults to 0 if not provided) +* - `total_tokens`: Combined total of input and output tokens (defaults to 0 if not provided) +* - `input_token_details`: Object containing detailed input token information: +* - `cache_read`: Number of tokens read from cache (only included if available) +* - `output_token_details`: Object containing detailed output token information: +* - `reasoning`: Number of tokens used for reasoning (only included if available) +* +* @example +* ```typescript +* const usage = { +* input_tokens: 100, +* output_tokens: 50, +* total_tokens: 150, +* input_tokens_details: { cached_tokens: 20 }, +* output_tokens_details: { reasoning_tokens: 10 } +* }; +* +* const metadata = convertResponsesUsageToUsageMetadata(usage); +* // Returns: +* // { +* // input_tokens: 100, +* // output_tokens: 50, +* // total_tokens: 150, +* // input_token_details: { cache_read: 20 }, +* // output_token_details: { reasoning: 10 } +* // } +* ``` +* +* @remarks +* - The function safely handles undefined or null values by using optional chaining +* and nullish coalescing operators +* - Detailed token information (cache_read, reasoning) is only included in the result +* if the corresponding values are present in the input +* - Token counts default to 0 if not provided in the usage object +* - This converter is specifically designed for OpenAI's Responses API format and +* may differ from other OpenAI API endpoints +*/ +var convertResponsesUsageToUsageMetadata = (usage) => { + const inputTokenDetails = { ...usage?.input_tokens_details?.cached_tokens != null && { cache_read: usage?.input_tokens_details?.cached_tokens } }; + const outputTokenDetails = { ...usage?.output_tokens_details?.reasoning_tokens != null && { reasoning: usage?.output_tokens_details?.reasoning_tokens } }; + return { + input_tokens: usage?.input_tokens ?? 0, + output_tokens: usage?.output_tokens ?? 0, + total_tokens: usage?.total_tokens ?? 0, + input_token_details: inputTokenDetails, + output_token_details: outputTokenDetails + }; +}; +/** +* Converts an OpenAI Responses API response to a LangChain AIMessage. +* +* This converter processes the output from OpenAI's Responses API (both `create` and `parse` methods) +* and transforms it into a LangChain AIMessage object with all relevant metadata, tool calls, and content. +* +* @param response - The response object from OpenAI's Responses API. Can be either: +* - ResponsesCreateInvoke: Result from `responses.create()` +* - ResponsesParseInvoke: Result from `responses.parse()` +* +* @returns An AIMessage containing: +* - `id`: The message ID from the response output +* - `content`: Array of message content blocks (text, images, etc.) +* - `tool_calls`: Array of successfully parsed tool calls +* - `invalid_tool_calls`: Array of tool calls that failed to parse +* - `usage_metadata`: Token usage information converted to LangChain format +* - `additional_kwargs`: Extra data including: +* - `refusal`: Refusal text if the model refused to respond +* - `reasoning`: Reasoning output for reasoning models +* - `tool_outputs`: Results from built-in tools (web search, file search, etc.) +* - `parsed`: Parsed structured output when using json_schema format +* - Function call ID mappings for tracking +* - `response_metadata`: Metadata about the response including model, timestamps, status, etc. +* +* @throws Error if the response contains an error object. The error message and code are extracted +* from the response.error field. +* +* @example +* ```typescript +* const response = await client.responses.create({ +* model: "gpt-4", +* input: [{ type: "message", content: "Hello" }] +* }); +* const message = convertResponsesMessageToAIMessage(response); +* console.log(message.content); // Message content +* console.log(message.tool_calls); // Any tool calls made +* ``` +* +* @remarks +* The converter handles multiple output item types: +* - `message`: Text and structured content from the model +* - `function_call`: Tool/function calls that need to be executed +* - `reasoning`: Reasoning traces from reasoning models (o1, o3, etc.) +* - `custom_tool_call`: Custom tool invocations +* - Built-in tool outputs: web_search, file_search, code_interpreter, etc. +* +* Tool calls are parsed and validated. Invalid tool calls (malformed JSON, etc.) are captured +* in the `invalid_tool_calls` array rather than throwing errors. +*/ +var convertResponsesMessageToAIMessage = (response) => { + if (response.error) { + const error = new Error(response.error.message); + error.name = response.error.code; + throw error; + } + const content = []; + const tool_calls = []; + const invalid_tool_calls = []; + const cleanedOutput = response.output.map((item) => { + if (item.type === "function_call" && "parsed_arguments" in item) { + const cleaned = { ...item }; + delete cleaned.parsed_arguments; + return cleaned; + } + return item; + }); + const response_metadata = { + model_provider: "openai", + model: response.model, + created_at: response.created_at, + id: response.id, + incomplete_details: response.incomplete_details, + metadata: response.metadata, + object: response.object, + output: cleanedOutput, + status: response.status, + user: response.user, + service_tier: response.service_tier, + model_name: response.model + }; + const additional_kwargs = {}; + for (const item of response.output) if (item.type === "message") content.push(...item.content.flatMap((part) => { + if (part.type === "output_text") { + if ("parsed" in part && part.parsed != null) additional_kwargs.parsed = part.parsed; + return { + type: "text", + text: part.text, + annotations: part.annotations.map(convertOpenAIAnnotationToLangChain), + ...item.phase !== null ? { phase: item.phase } : {} + }; + } + if (part.type === "refusal") { + additional_kwargs.refusal = part.refusal; + return []; + } + return part; + })); + else if (item.type === "function_call") { + const fnAdapter = { + function: { + name: item.name, + arguments: item.arguments + }, + id: item.call_id + }; + try { + tool_calls.push(parseToolCall$2(fnAdapter, { returnId: true })); + } catch (e) { + let errMessage; + if (typeof e === "object" && e != null && "message" in e && typeof e.message === "string") errMessage = e.message; + invalid_tool_calls.push(makeInvalidToolCall(fnAdapter, errMessage)); + } + additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {}; + if (item.id) additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id; + } else if (item.type === "reasoning") { + additional_kwargs.reasoning = item; + const reasoningText = item.summary?.map((s) => s.text).filter(Boolean).join(""); + if (reasoningText) content.push({ + type: "reasoning", + reasoning: reasoningText + }); + } else if (item.type === "custom_tool_call") { + const parsed = parseCustomToolCall(item); + if (parsed) { + tool_calls.push(parsed); + additional_kwargs[_CUSTOM_TOOL_CALL_IDS_MAP_KEY] ??= {}; + if (item.id && item.call_id) additional_kwargs[_CUSTOM_TOOL_CALL_IDS_MAP_KEY][item.call_id] = item.id; + } else invalid_tool_calls.push(makeInvalidToolCall(item, "Malformed custom tool call")); + } else if (item.type === "computer_call") { + const parsed = parseComputerCall(item); + if (parsed) tool_calls.push(parsed); + else invalid_tool_calls.push(makeInvalidToolCall(item, "Malformed computer call")); + } else if (item.type === "image_generation_call") { + if (item.result) content.push({ + type: "image", + mimeType: "image/png", + data: item.result, + id: item.id, + metadata: { status: item.status } + }); + additional_kwargs.tool_outputs ??= []; + additional_kwargs.tool_outputs.push(item); + } else { + additional_kwargs.tool_outputs ??= []; + additional_kwargs.tool_outputs.push(item); + } + return new AIMessage({ + id: response.id, + content, + tool_calls, + invalid_tool_calls, + usage_metadata: convertResponsesUsageToUsageMetadata(response.usage), + additional_kwargs, + response_metadata + }); +}; +/** +* Converts a LangChain ChatOpenAI reasoning summary to an OpenAI Responses API reasoning item. +* +* This converter transforms reasoning summaries that have been accumulated during streaming +* (where summary parts may arrive in multiple chunks with the same index) into the final +* consolidated format expected by OpenAI's Responses API. It combines summary parts that +* share the same index and removes the index field from the final output. +* +* @param reasoning - A ChatOpenAI reasoning summary object containing: +* - `id`: The reasoning item ID +* - `type`: The type of reasoning (typically "reasoning") +* - `summary`: Array of summary parts, each with: +* - `text`: The summary text content +* - `type`: The summary type (e.g., "summary_text") +* - `index`: The index used to group related summary parts during streaming +* +* @returns An OpenAI Responses API ResponseReasoningItem with: +* - All properties from the input reasoning object +* - `summary`: Consolidated array of summary objects with: +* - `text`: Combined text from all parts with the same index +* - `type`: The summary type +* - No `index` field (removed after consolidation) +* +* @example +* ```typescript +* // Input: Reasoning summary with multiple parts at the same index +* const reasoning = { +* id: "reasoning_123", +* type: "reasoning", +* summary: [ +* { text: "First ", type: "summary_text", index: 0 }, +* { text: "part", type: "summary_text", index: 0 }, +* { text: "Second part", type: "summary_text", index: 1 } +* ] +* }; +* +* const result = convertReasoningSummaryToResponsesReasoningItem(reasoning); +* // Returns: +* // { +* // id: "reasoning_123", +* // type: "reasoning", +* // summary: [ +* // { text: "First part", type: "summary_text" }, +* // { text: "Second part", type: "summary_text" } +* // ] +* // } +* ``` +* +* @remarks +* - This converter is primarily used when reconstructing complete reasoning items from +* streaming chunks, where summary parts may arrive incrementally with index markers +* - Summary parts with the same index are concatenated in the order they appear +* - If the reasoning summary contains only one part, no reduction is performed +* - The index field is used internally during streaming to track which summary parts +* belong together, but is removed from the final output as it's not part of the +* OpenAI Responses API schema +* - This is the inverse operation of the streaming accumulation that happens in +* `convertResponsesDeltaToChatGenerationChunk` +*/ +var convertReasoningSummaryToResponsesReasoningItem = (reasoning) => { + const summary = (reasoning.summary.length > 1 ? reasoning.summary.reduce((acc, curr) => { + const last = acc[acc.length - 1]; + if (last.index === curr.index) last.text += curr.text; + else acc.push(curr); + return acc; + }, [{ ...reasoning.summary[0] }]) : reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== "index"))); + return { + ...reasoning, + summary + }; +}; +/** +* Converts OpenAI Responses API stream events to LangChain ChatGenerationChunk objects. +* +* This converter processes streaming events from OpenAI's Responses API and transforms them +* into LangChain ChatGenerationChunk objects that can be used in streaming chat applications. +* It handles various event types including text deltas, tool calls, reasoning, and metadata updates. +* +* @param event - A streaming event from OpenAI's Responses API +* +* @returns A ChatGenerationChunk containing: +* - `text`: Concatenated text content from all text parts in the event +* - `message`: An AIMessageChunk with: +* - `id`: Response ID (set on `response.created` / `response.completed`) +* - `content`: Array of content blocks (text with optional annotations) +* - `tool_call_chunks`: Incremental tool call data (name, args, id) +* - `usage_metadata`: Token usage information (only in completion events) +* - `additional_kwargs`: Extra data including: +* - `refusal`: Refusal text if the model refused to respond +* - `reasoning`: Reasoning output for reasoning models (id, type, summary) +* - `tool_outputs`: Results from built-in tools (web search, file search, etc.) +* - `parsed`: Parsed structured output when using json_schema format +* - Function call ID mappings for tracking +* - `response_metadata`: Metadata about the response (model, id, etc.) +* - `generationInfo`: Additional generation information (e.g., tool output status) +* +* Returns `null` for events that don't produce meaningful chunks: +* - Partial image generation events (to avoid storing all partial images in history) +* - Unrecognized event types +* +* @example +* ```typescript +* const stream = await client.responses.create({ +* model: "gpt-4", +* input: [{ type: "message", content: "Hello" }], +* stream: true +* }); +* +* for await (const event of stream) { +* const chunk = convertResponsesDeltaToChatGenerationChunk(event); +* if (chunk) { +* console.log(chunk.text); // Incremental text +* console.log(chunk.message.tool_call_chunks); // Tool call updates +* } +* } +* ``` +* +* @remarks +* - Text content is accumulated in an array with index tracking for proper ordering +* - Tool call chunks include incremental arguments that need to be concatenated by the consumer +* - Reasoning summaries are built incrementally across multiple events +* - Function call IDs are tracked in `additional_kwargs` to map call_id to item id +* - The `text` field is provided for legacy compatibility with `onLLMNewToken` callbacks +* - Usage metadata is only available in `response.completed` events +* - Partial images are intentionally ignored to prevent memory bloat in conversation history +*/ +var convertResponsesDeltaToChatGenerationChunk = (event) => { + const content = []; + let generationInfo = {}; + let usage_metadata; + const tool_call_chunks = []; + const response_metadata = { model_provider: "openai" }; + const additional_kwargs = {}; + let id; + if (event.type === "response.output_text.delta") content.push({ + type: "text", + text: event.delta, + index: event.content_index + }); + else if (event.type === "response.output_text.annotation.added") content.push({ + type: "text", + text: "", + annotations: [convertOpenAIAnnotationToLangChain(event.annotation)], + index: event.content_index + }); + else if (event.type === "response.output_item.added" && event.item.type === "message") { + const phase = "phase" in event.item ? event.item.phase : void 0; + if (phase) content.push({ + type: "text", + text: "", + phase, + index: 0 + }); + } else if (event.type === "response.output_item.added" && event.item.type === "function_call") { + tool_call_chunks.push({ + type: "tool_call_chunk", + name: event.item.name, + args: event.item.arguments, + id: event.item.call_id, + index: event.output_index + }); + additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = { [event.item.call_id]: event.item.id }; + } else if (event.type === "response.output_item.added" && event.item.type === "custom_tool_call") { + tool_call_chunks.push({ + type: "tool_call_chunk", + isCustomTool: true, + name: event.item.name, + args: event.item.input, + id: event.item.call_id, + index: event.output_index + }); + additional_kwargs[_CUSTOM_TOOL_CALL_IDS_MAP_KEY] = { [event.item.call_id]: event.item.id }; + } else if (event.type === "response.output_item.done" && event.item.type === "computer_call") { + tool_call_chunks.push({ + type: "tool_call_chunk", + name: "computer_use", + args: JSON.stringify({ action: event.item.action }), + id: event.item.call_id, + index: event.output_index + }); + additional_kwargs.tool_outputs = [event.item]; + } else if (event.type === "response.output_item.done" && event.item.type === "image_generation_call") { + if (event.item.result) content.push({ + type: "image", + mimeType: "image/png", + data: event.item.result, + id: event.item.id, + metadata: { status: event.item.status } + }); + additional_kwargs.tool_outputs = [event.item]; + } else if (event.type === "response.output_item.done" && [ + "web_search_call", + "file_search_call", + "code_interpreter_call", + "shell_call", + "local_shell_call", + "mcp_call", + "mcp_list_tools", + "mcp_approval_request", + "custom_tool_call", + "tool_search_call", + "tool_search_output" + ].includes(event.item.type)) additional_kwargs.tool_outputs = [event.item]; + else if (event.type === "response.created") { + id = event.response.id; + response_metadata.id = event.response.id; + response_metadata.model_name = event.response.model; + response_metadata.model = event.response.model; + } else if (event.type === "response.completed" || event.type === "response.incomplete") { + id = event.response.id; + const msg = convertResponsesMessageToAIMessage(event.response); + usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage); + if (event.response.text?.format?.type === "json_schema" && msg.text) try { + additional_kwargs.parsed ??= JSON.parse(msg.text); + } catch {} + for (const [key, value] of Object.entries(event.response)) { + if (key === "id") continue; + if (key === "output") response_metadata[key] = msg.response_metadata.output; + else response_metadata[key] = value; + } + } else if (event.type === "response.function_call_arguments.delta" || event.type === "response.custom_tool_call_input.delta") tool_call_chunks.push({ + type: "tool_call_chunk", + args: event.delta, + index: event.output_index, + ...event.type === "response.custom_tool_call_input.delta" ? { isCustomTool: true } : {} + }); + else if (event.type === "response.web_search_call.in_progress" || event.type === "response.web_search_call.searching" || event.type === "response.web_search_call.completed" || event.type === "response.file_search_call.in_progress" || event.type === "response.file_search_call.searching" || event.type === "response.file_search_call.completed" || event.type === "response.image_generation_call.in_progress" || event.type === "response.image_generation_call.generating" || event.type === "response.image_generation_call.completed") { + const [, type, status] = event.type.match(/^response\.(.*)\.([^.]+)$/) ?? [ + "", + "", + "" + ]; + generationInfo = { tool_outputs: { + id: event.item_id, + type, + status + } }; + } else if (event.type === "response.refusal.done") additional_kwargs.refusal = event.refusal; + else if (event.type === "response.output_item.added" && "item" in event && event.item.type === "reasoning") { + const summary = event.item.summary ? event.item.summary.map((s, index) => ({ + ...s, + index + })) : void 0; + additional_kwargs.reasoning = { + id: event.item.id, + type: event.item.type, + ...summary ? { summary } : {} + }; + const reasoningText = event.item.summary?.map((s) => s.text).filter(Boolean).join(""); + if (reasoningText) content.push({ + type: "reasoning", + reasoning: reasoningText + }); + } else if (event.type === "response.reasoning_summary_part.added") { + additional_kwargs.reasoning = { + type: "reasoning", + summary: [{ + ...event.part, + index: event.summary_index + }] + }; + if (event.part.text) content.push({ + type: "reasoning", + reasoning: event.part.text, + index: event.summary_index + }); + } else if (event.type === "response.reasoning_summary_text.delta") { + additional_kwargs.reasoning = { + type: "reasoning", + summary: [{ + text: event.delta, + type: "summary_text", + index: event.summary_index + }] + }; + if (event.delta) content.push({ + type: "reasoning", + reasoning: event.delta, + index: event.summary_index + }); + } else if (event.type === "response.image_generation_call.partial_image") return null; + else return null; + return new ChatGenerationChunk({ + text: content.map((part) => part.text).join(""), + message: new AIMessageChunk({ + id, + content, + tool_call_chunks, + usage_metadata, + additional_kwargs, + response_metadata + }), + generationInfo + }); +}; +/** +* Converts a single LangChain BaseMessage to OpenAI Responses API input format. +* +* This converter transforms a LangChain message into one or more ResponseInputItem objects +* that can be used with OpenAI's Responses API. It handles complex message structures including +* tool calls, reasoning blocks, multimodal content, and various content block types. +* +* @param message - The LangChain BaseMessage to convert. Can be any message type including +* HumanMessage, AIMessage, SystemMessage, ToolMessage, etc. +* +* @returns An array of ResponseInputItem objects. +* +* @example +* Basic text message conversion: +* ```typescript +* const message = new HumanMessage("Hello, how are you?"); +* const items = convertStandardContentMessageToResponsesInput(message); +* // Returns: [{ type: "message", role: "user", content: [{ type: "input_text", text: "Hello, how are you?" }] }] +* ``` +* +* @example +* AI message with tool calls: +* ```typescript +* const message = new AIMessage({ +* content: "I'll check the weather for you.", +* tool_calls: [{ +* id: "call_123", +* name: "get_weather", +* args: { location: "San Francisco" } +* }] +* }); +* const items = convertStandardContentMessageToResponsesInput(message); +* // Returns: +* // [ +* // { type: "message", role: "assistant", content: [{ type: "input_text", text: "I'll check the weather for you." }] }, +* // { type: "function_call", call_id: "call_123", name: "get_weather", arguments: '{"location":"San Francisco"}' } +* // ] +* ``` +*/ +var convertStandardContentMessageToResponsesInput = (message) => { + const isResponsesMessage = AIMessage.isInstance(message) && message.response_metadata?.model_provider === "openai"; + function* iterateItems() { + const messageRole = iife$1(() => { + try { + const role = messageToOpenAIRole(message); + if (role === "system" || role === "developer" || role === "assistant" || role === "user") return role; + return "assistant"; + } catch { + return "assistant"; + } + }); + const makeTextPart = (text) => messageRole === "assistant" ? { + type: "output_text", + text, + annotations: [] + } : { + type: "input_text", + text + }; + let currentMessage = void 0; + const functionCallIdsWithBlocks = /* @__PURE__ */ new Set(); + const serverFunctionCallIdsWithBlocks = /* @__PURE__ */ new Set(); + const pendingFunctionChunks = /* @__PURE__ */ new Map(); + const pendingServerFunctionChunks = /* @__PURE__ */ new Map(); + function* flushMessage() { + if (!currentMessage) return; + const content = currentMessage.content; + if (typeof content === "string" && content.length > 0 || Array.isArray(content) && content.length > 0) yield currentMessage; + currentMessage = void 0; + } + const pushMessageContent = (content, phase) => { + if (!currentMessage) currentMessage = { + type: "message", + role: messageRole, + content: [], + ...phase ? { phase } : {} + }; + if (typeof currentMessage.content === "string") currentMessage.content = currentMessage.content.length > 0 ? [makeTextPart(currentMessage.content), ...content] : [...content]; + else currentMessage.content.push(...content); + }; + const toJsonString = (value) => { + if (typeof value === "string") return value; + try { + return JSON.stringify(value ?? {}); + } catch { + return "{}"; + } + }; + const resolveImageItem = (block) => { + const detail = iife$1(() => { + const raw = block.metadata?.detail; + if (raw === "low" || raw === "high" || raw === "auto") return raw; + return "auto"; + }); + if (block.fileId) return { + type: "input_image", + detail, + file_id: block.fileId + }; + if (block.url) return { + type: "input_image", + detail, + image_url: block.url + }; + if (block.data) { + const base64Data = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64"); + return { + type: "input_image", + detail, + image_url: `data:${block.mimeType ?? "image/png"};base64,${base64Data}` + }; + } + }; + const resolveFileItem = (block) => { + if (block.fileId) { + const filename = getFilenameFromMetadata(block); + return { + type: "input_file", + file_id: block.fileId, + ...filename ? { filename } : {} + }; + } + if (block.url) { + const filename = getFilenameFromMetadata(block); + return { + ...filename ? { filename } : {}, + type: "input_file", + file_url: block.url + }; + } + if (block.data) { + const filename = getRequiredFilenameFromMetadata(block); + const encoded = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64"); + return { + type: "input_file", + file_data: `data:${block.mimeType ?? "application/octet-stream"};base64,${encoded}`, + filename + }; + } + }; + const convertReasoningBlock = (block) => { + const summaryEntries = iife$1(() => { + if (Array.isArray(block.summary)) { + const mapped = block.summary?.map((item) => item?.text).filter((text) => typeof text === "string") ?? []; + if (mapped.length > 0) return mapped; + } + return block.reasoning ? [block.reasoning] : []; + }); + const summary = summaryEntries.length > 0 ? summaryEntries.map((text) => ({ + type: "summary_text", + text + })) : [{ + type: "summary_text", + text: "" + }]; + return { + type: "reasoning", + ...block.id ? { id: block.id } : {}, + summary + }; + }; + const convertFunctionCall = (block) => ({ + type: "function_call", + name: block.name ?? "", + call_id: block.id ?? "", + arguments: toJsonString(block.args) + }); + const convertFunctionCallOutput = (block) => { + const output = toJsonString(block.output); + const status = block.status === "success" ? "completed" : block.status === "error" ? "incomplete" : void 0; + return { + type: "function_call_output", + call_id: block.toolCallId ?? "", + output, + ...status ? { status } : {} + }; + }; + for (const block of message.contentBlocks) if (block.type === "text") { + const phase = iife$1(() => { + if (!("extras" in block && typeof block.extras === "object" && block.extras !== null && "phase" in block.extras)) return void 0; + return block.extras.phase; + }); + pushMessageContent([makeTextPart(block.text)], phase); + } else if (block.type === "invalid_tool_call") {} else if (block.type === "reasoning") { + yield* flushMessage(); + yield convertReasoningBlock(block); + } else if (block.type === "tool_call") { + yield* flushMessage(); + const id = block.id ?? ""; + if (id) { + functionCallIdsWithBlocks.add(id); + pendingFunctionChunks.delete(id); + } + yield convertFunctionCall(block); + } else if (block.type === "tool_call_chunk") { + if (block.id) { + const existing = pendingFunctionChunks.get(block.id) ?? { + name: block.name, + args: [] + }; + if (block.name) existing.name = block.name; + if (block.args) existing.args.push(block.args); + pendingFunctionChunks.set(block.id, existing); + } + } else if (block.type === "server_tool_call") { + yield* flushMessage(); + const id = block.id ?? ""; + if (id) { + serverFunctionCallIdsWithBlocks.add(id); + pendingServerFunctionChunks.delete(id); + } + yield convertFunctionCall(block); + } else if (block.type === "server_tool_call_chunk") { + if (block.id) { + const existing = pendingServerFunctionChunks.get(block.id) ?? { + name: block.name, + args: [] + }; + if (block.name) existing.name = block.name; + if (block.args) existing.args.push(block.args); + pendingServerFunctionChunks.set(block.id, existing); + } + } else if (block.type === "server_tool_call_result") { + yield* flushMessage(); + yield convertFunctionCallOutput(block); + } else if (block.type === "audio") {} else if (block.type === "file") { + const fileItem = resolveFileItem(block); + if (fileItem) pushMessageContent([fileItem]); + } else if (block.type === "image") { + const imageItem = resolveImageItem(block); + if (imageItem) pushMessageContent([imageItem]); + } else if (block.type === "video") { + const videoItem = resolveFileItem(block); + if (videoItem) pushMessageContent([videoItem]); + } else if (block.type === "text-plain") { + if (block.text) pushMessageContent([makeTextPart(block.text)]); + } else if (block.type === "non_standard" && isResponsesMessage) { + yield* flushMessage(); + yield block.value; + } + yield* flushMessage(); + for (const [id, chunk] of pendingFunctionChunks) { + if (!id || functionCallIdsWithBlocks.has(id)) continue; + const args = chunk.args.join(""); + if (!chunk.name && !args) continue; + yield { + type: "function_call", + call_id: id, + name: chunk.name ?? "", + arguments: args + }; + } + for (const [id, chunk] of pendingServerFunctionChunks) { + if (!id || serverFunctionCallIdsWithBlocks.has(id)) continue; + const args = chunk.args.join(""); + if (!chunk.name && !args) continue; + yield { + type: "function_call", + call_id: id, + name: chunk.name ?? "", + arguments: args + }; + } + } + return Array.from(iterateItems()); +}; +/** +* - MCP (Model Context Protocol) approval responses +* - Zero Data Retention (ZDR) mode handling +* +* @param params - Conversion parameters +* @param params.messages - Array of LangChain BaseMessages to convert +* @param params.zdrEnabled - Whether Zero Data Retention mode is enabled. When true, certain +* metadata like message IDs and function call IDs are omitted from the output +* @param params.model - The model name being used. Used to determine if special role mapping +* is needed (e.g., "system" -> "developer" for reasoning models) +* +* @returns Array of ResponsesInputItem objects formatted for the OpenAI Responses API +* +* @throws {Error} When a function message is encountered (not supported) +* @throws {Error} When computer call output format is invalid +* +* @example +* ```typescript +* const messages = [ +* new HumanMessage("Hello"), +* new AIMessage({ content: "Hi there!", tool_calls: [...] }) +* ]; +* +* const input = convertMessagesToResponsesInput({ +* messages, +* zdrEnabled: false, +* model: "gpt-4" +* }); +* ``` +*/ +var convertMessagesToResponsesInput = ({ messages, zdrEnabled, model }) => { + return messages.flatMap((lcMsg) => { + const responseMetadata = lcMsg.response_metadata; + if (responseMetadata?.output_version === "v1") return convertStandardContentMessageToResponsesInput(lcMsg); + const additional_kwargs = lcMsg.additional_kwargs; + let role = messageToOpenAIRole(lcMsg); + if (role === "system" && isReasoningModel(model)) role = "developer"; + if (role === "function") throw new Error("Function messages are not supported in Responses API"); + if (role === "tool") { + const toolMessage = lcMsg; + if (additional_kwargs?.type === "computer_call_output") + /** + * Cast needed because OpenAI SDK types don't yet include input_image + * for computer-use-preview model output format + */ + return { + type: "computer_call_output", + output: (() => { + if (typeof toolMessage.content === "string") return { + type: "input_image", + image_url: toolMessage.content + }; + if (Array.isArray(toolMessage.content)) { + /** + * Check for input_image type first (computer-use-preview format) + */ + const inputImage = toolMessage.content.find((i) => i.type === "input_image"); + if (inputImage) return inputImage; + /** + * Check for computer_screenshot type (legacy format) + */ + const oaiScreenshot = toolMessage.content.find((i) => i.type === "computer_screenshot"); + if (oaiScreenshot) return oaiScreenshot; + /** + * Convert image_url content block to input_image format + */ + const lcImage = toolMessage.content.find((i) => i.type === "image_url"); + if (lcImage) return { + type: "input_image", + image_url: typeof lcImage.image_url === "string" ? lcImage.image_url : lcImage.image_url.url + }; + } + throw new Error("Invalid computer call output"); + })(), + call_id: toolMessage.tool_call_id + }; + if (toolMessage.additional_kwargs?.customTool) return { + type: "custom_tool_call_output", + call_id: toolMessage.tool_call_id, + output: toolMessage.content + }; + const isProviderNativeContent = Array.isArray(toolMessage.content) && toolMessage.content.every((item) => typeof item === "object" && item !== null && "type" in item && (item.type === "input_file" || item.type === "input_image" || item.type === "input_text")); + return { + type: "function_call_output", + call_id: toolMessage.tool_call_id, + id: toolMessage.id?.startsWith("fc_") ? toolMessage.id : void 0, + output: isProviderNativeContent ? toolMessage.content : typeof toolMessage.content !== "string" ? JSON.stringify(toolMessage.content) : toolMessage.content + }; + } + if (role === "assistant") { + if (!zdrEnabled && responseMetadata?.output != null && Array.isArray(responseMetadata?.output) && responseMetadata?.output.length > 0 && responseMetadata?.output.every((item) => "type" in item)) return responseMetadata?.output; + const input = []; + const reasoning = additional_kwargs?.reasoning; + const hasEncryptedContent = !!reasoning?.encrypted_content; + /** + * With ZDR enabled, OpenAI does not retain reasoning items, so we only send + * them when encrypted content is available (via include: ["reasoning.encrypted_content"]). + * With ZDR disabled, we include reasoning item ids so OpenAI can reference them, as it's storing them. + */ + if (reasoning && (!zdrEnabled || hasEncryptedContent)) { + const reasoningItem = convertReasoningSummaryToResponsesReasoningItem(reasoning); + input.push(reasoningItem); + } + let { content } = lcMsg; + if (additional_kwargs?.refusal) { + if (typeof content === "string") content = [{ + type: "output_text", + text: content, + annotations: [] + }]; + content = [...content, { + type: "refusal", + refusal: additional_kwargs.refusal + }]; + } + if (typeof content === "string" || content.length > 0) { + const messageItem = { + type: "message", + role: "assistant", + ...lcMsg.id && !zdrEnabled && lcMsg.id.startsWith("msg_") ? { id: lcMsg.id } : {}, + content: iife$1(() => { + if (typeof content === "string") return content; + return content.flatMap((item) => { + if (item.type === "text") { + const textItem = item; + return { + type: "output_text", + text: textItem.text, + annotations: (textItem.annotations ?? []).map(convertLangChainAnnotationToOpenAI) + }; + } + if (item.type === "output_text" || item.type === "refusal") return item; + return []; + }); + }), + phase: iife$1(() => { + if (!Array.isArray(content)) return; + return content.find((item) => "phase" in item && typeof item.phase === "string")?.phase; + }) + }; + input.push(messageItem); + } + const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY]; + const customToolCallIds = additional_kwargs?.[_CUSTOM_TOOL_CALL_IDS_MAP_KEY]; + if (AIMessage.isInstance(lcMsg) && !!lcMsg.tool_calls?.length) input.push(...lcMsg.tool_calls.map((toolCall) => { + if (isCustomToolCall(toolCall, customToolCallIds)) return { + type: "custom_tool_call", + id: "call_id" in toolCall && typeof toolCall.call_id === "string" ? toolCall.call_id : customToolCallIds?.[toolCall.id ?? ""] ?? "", + call_id: toolCall.id ?? "", + input: toolCall.args.input, + name: toolCall.name + }; + if (isComputerToolCall(toolCall)) return { + type: "computer_call", + id: toolCall.call_id, + call_id: toolCall.id ?? "", + action: toolCall.args.action + }; + return { + type: "function_call", + name: toolCall.name, + arguments: JSON.stringify(toolCall.args), + call_id: toolCall.id, + ...!zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {} + }; + })); + else if (additional_kwargs?.tool_calls) input.push(...additional_kwargs.tool_calls.map((toolCall) => ({ + type: "function_call", + name: toolCall.function.name, + call_id: toolCall.id, + arguments: toolCall.function.arguments, + ...!zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {} + }))); + const toolOutputs = (responseMetadata?.output)?.length ? responseMetadata?.output : additional_kwargs.tool_outputs; + const fallthroughCallTypes = [ + "computer_call", + "mcp_call", + "code_interpreter_call", + "image_generation_call", + "shell_call", + "local_shell_call" + ]; + if (toolOutputs != null) { + const fallthroughCalls = toolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type)); + if (fallthroughCalls.length > 0) input.push(...fallthroughCalls); + } + return input; + } + if (role === "user" || role === "system" || role === "developer") { + if (typeof lcMsg.content === "string") return { + type: "message", + role, + content: lcMsg.content + }; + const messages = []; + const content = lcMsg.content.flatMap((item) => { + if (item.type === "mcp_approval_response") messages.push({ + type: "mcp_approval_response", + approval_request_id: item.approval_request_id, + approve: item.approve + }); + if (isDataContentBlock(item)) { + if (item.type === "file") { + const filename = getFilenameFromMetadata(item); + if (item.source_type === "url") return { + type: "input_file", + file_url: item.url, + ...filename ? { filename } : {} + }; + if (item.source_type === "id") return { + type: "input_file", + file_id: item.id, + ...filename ? { filename } : {} + }; + if (item.source_type === "base64") return { + type: "input_file", + file_data: `data:${item.mime_type ?? ""};base64,${item.data}`, + filename: getRequiredFilenameFromMetadata(item) + }; + } + return convertToProviderContentBlock(item, completionsApiContentBlockConverter); + } + if (item.type === "text") return { + type: "input_text", + text: item.text + }; + if (item.type === "image_url") return { + type: "input_image", + image_url: iife$1(() => { + if (typeof item.image_url === "string") return item.image_url; + else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) return item.image_url.url; + }), + detail: iife$1(() => { + if (typeof item.image_url === "string") return "auto"; + else if (typeof item.image_url === "object" && item.image_url !== null && "detail" in item.image_url) return item.image_url.detail; + }) + }; + if (item.type === "input_text" || item.type === "input_image" || item.type === "input_file") return item; + return []; + }); + if (content.length > 0) messages.push({ + type: "message", + role, + content + }); + return messages; + } + console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`); + return []; + }); +}; +//#endregion +//#region node_modules/@langchain/openai/dist/utils/responses_stream_events.js +async function* convertOpenAIResponsesStream(source, options = {}) { + const shouldStreamUsage = options.streamUsage ?? true; + const provider = options.provider ?? "openai"; + const blockAccumulators = /* @__PURE__ */ new Map(); + const blockKeyToIndex = /* @__PURE__ */ new Map(); + let nextBlockIndex = 0; + let messageStarted = false; + let messageId; + let usageSnapshot; + let finishReason; + let responseMetadata; + const finalizedBlockIndices = /* @__PURE__ */ new Set(); + const getOrCreateBlockIndex = (key, initial) => { + const existing = blockKeyToIndex.get(key); + if (existing !== void 0) return { + index: existing, + isNew: false + }; + const index = nextBlockIndex++; + blockKeyToIndex.set(key, index); + blockAccumulators.set(index, { ...initial }); + return { + index, + isNew: true + }; + }; + const ensureMessageStart = function* () { + if (!messageStarted) { + messageStarted = true; + yield { + event: "message-start", + id: messageId + }; + } + }; + const finalizeBlock = function* (index) { + if (finalizedBlockIndices.has(index)) return; + const acc = blockAccumulators.get(index); + if (!acc) return; + finalizedBlockIndices.add(index); + yield { + event: "content-block-finish", + index, + content: finalizeContentBlock(acc) + }; + }; + for await (const event of source) { + if (event.type === "response.created") { + messageId = event.response.id; + yield* ensureMessageStart(); + yield { + event: "provider", + provider, + name: "response.created", + payload: { + model: event.response.model, + id: event.response.id + } + }; + continue; + } + if (event.type === "response.output_text.delta") { + yield* ensureMessageStart(); + const { index, isNew } = getOrCreateBlockIndex(`text:${event.output_index}:${event.content_index}`, { + type: "text", + text: "" + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "text", + text: "" + } + }; + const acc = blockAccumulators.get(index); + acc.text = (acc.text ?? "") + event.delta; + yield { + event: "content-block-delta", + index, + delta: { + type: "text-delta", + text: event.delta + } + }; + continue; + } + if (event.type === "response.reasoning_summary_text.delta") { + yield* ensureMessageStart(); + const { index, isNew } = getOrCreateBlockIndex(`reasoning:${event.output_index}:${event.summary_index}`, { + type: "reasoning", + reasoning: "" + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "reasoning", + reasoning: "" + } + }; + const acc = blockAccumulators.get(index); + acc.reasoning = (acc.reasoning ?? "") + event.delta; + yield { + event: "content-block-delta", + index, + delta: { + type: "reasoning-delta", + reasoning: event.delta + } + }; + continue; + } + if (event.type === "response.output_item.added" && (event.item.type === "function_call" || event.item.type === "custom_tool_call")) { + yield* ensureMessageStart(); + const key = `tool:${event.output_index}`; + const isCustom = event.item.type === "custom_tool_call"; + const initialArgs = event.item.type === "function_call" ? event.item.arguments ?? "" : event.item.input ?? ""; + const { index, isNew } = getOrCreateBlockIndex(key, { + type: "tool_call_chunk", + id: event.item.call_id, + name: event.item.name, + args: initialArgs, + index: event.output_index, + ...isCustom ? { isCustomTool: true } : {} + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "tool_call_chunk", + id: event.item.call_id, + name: event.item.name, + args: initialArgs, + index: event.output_index + } + }; + if (initialArgs) { + const acc = blockAccumulators.get(index); + yield { + event: "content-block-delta", + index, + delta: { + type: "block-delta", + fields: { + type: "tool_call_chunk", + ...acc.id != null ? { id: acc.id } : {}, + ...acc.name != null ? { name: acc.name } : {}, + args: acc.args + } + } + }; + } + continue; + } + if (event.type === "response.function_call_arguments.delta" || event.type === "response.custom_tool_call_input.delta") { + yield* ensureMessageStart(); + const { index, isNew } = getOrCreateBlockIndex(`tool:${event.output_index}`, { + type: "tool_call_chunk", + args: "", + index: event.output_index, + ...event.type === "response.custom_tool_call_input.delta" ? { isCustomTool: true } : {} + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "tool_call_chunk", + args: "", + index: event.output_index + } + }; + const acc = blockAccumulators.get(index); + acc.args = (acc.args ?? "") + event.delta; + yield { + event: "content-block-delta", + index, + delta: { + type: "block-delta", + fields: { + type: "tool_call_chunk", + ...acc.id != null ? { id: acc.id } : {}, + ...acc.name != null ? { name: acc.name } : {}, + args: acc.args + } + } + }; + continue; + } + if (event.type === "response.output_item.done" && (event.item.type === "function_call" || event.item.type === "custom_tool_call")) { + yield* ensureMessageStart(); + const key = `tool:${event.output_index}`; + const args = event.item.type === "function_call" ? event.item.arguments ?? "" : event.item.input ?? ""; + const { index, isNew } = getOrCreateBlockIndex(key, { + type: "tool_call_chunk", + id: event.item.call_id, + name: event.item.name, + args, + index: event.output_index + }); + if (isNew) yield { + event: "content-block-start", + index, + content: { + type: "tool_call_chunk", + id: event.item.call_id, + name: event.item.name, + args, + index: event.output_index + } + }; + else { + const acc = blockAccumulators.get(index); + acc.args = args; + acc.id = event.item.call_id; + acc.name = event.item.name; + } + yield* finalizeBlock(index); + continue; + } + if (event.type === "response.completed" || event.type === "response.incomplete") { + yield* ensureMessageStart(); + messageId = event.response.id; + finishReason = mapResponseStatusToFinishReason(event.response.status, event.type); + responseMetadata = { + model_provider: provider, + id: event.response.id, + model: event.response.model, + status: event.response.status + }; + if (shouldStreamUsage && event.response.usage) { + usageSnapshot = convertResponsesUsageToUsageMetadata(event.response.usage); + yield { + event: "usage", + usage: usageSnapshot + }; + } + continue; + } + if (event.type === "response.image_generation_call.partial_image") continue; + yield* ensureMessageStart(); + yield { + event: "provider", + provider, + name: event.type, + payload: event + }; + } + if (!messageStarted) yield { event: "message-start" }; + for (const [index] of blockAccumulators) if (!finalizedBlockIndices.has(index)) yield* finalizeBlock(index); + yield { + event: "message-finish", + reason: finishReason, + ...usageSnapshot ? { usage: usageSnapshot } : {}, + ...responseMetadata ? { responseMetadata } : {} + }; +} +function mapResponseStatusToFinishReason(status, eventType) { + if (eventType === "response.incomplete") return "length"; + if (status === "completed") return "stop"; + if (status === "incomplete") return "length"; + return "stop"; +} +//#endregion +//#region node_modules/@langchain/openai/dist/chat_models/responses.js +/** +* OpenAI Responses API implementation. +* +* Will be exported in a later version of @langchain/openai. +* +* @internal +*/ +var ChatOpenAIResponses = class extends BaseChatOpenAI { + constructor(modelOrFields, fieldsArg) { + super(getChatOpenAIModelParams(modelOrFields, fieldsArg)); + } + invocationParams(options) { + let strict; + if (options?.strict !== void 0) strict = options.strict; + if (strict === void 0 && this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; + const params = { + model: this.model, + temperature: this.temperature, + top_p: this.topP, + user: this.user, + service_tier: this.service_tier, + stream: this.streaming, + previous_response_id: options?.previous_response_id, + truncation: options?.truncation, + include: options?.include, + tools: options?.tools?.length ? this._reduceChatOpenAITools(options.tools, { + stream: this.streaming, + strict + }) : void 0, + tool_choice: isBuiltInToolChoice(options?.tool_choice) ? options?.tool_choice : (() => { + const formatted = formatToOpenAIToolChoice(options?.tool_choice); + if (typeof formatted === "object" && "type" in formatted) { + if (formatted.type === "function") return { + type: "function", + name: formatted.function.name + }; + else if (formatted.type === "allowed_tools") return { + type: "allowed_tools", + mode: formatted.allowed_tools.mode, + tools: formatted.allowed_tools.tools + }; + else if (formatted.type === "custom") return { + type: "custom", + name: formatted.custom.name + }; + } + })(), + text: (() => { + if (options?.text) return options.text; + const format = this._getResponseFormat(options?.response_format); + if (format?.type === "json_schema") { + if (format.json_schema.schema != null) return { + format: { + type: "json_schema", + schema: format.json_schema.schema, + description: format.json_schema.description, + name: format.json_schema.name, + strict: format.json_schema.strict + }, + verbosity: options?.verbosity + }; + return; + } + return { + format, + verbosity: options?.verbosity + }; + })(), + parallel_tool_calls: options?.parallel_tool_calls, + max_output_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens, + prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey, + prompt_cache_retention: options?.promptCacheRetention ?? this.promptCacheRetention, + ...this.zdrEnabled ? { store: false } : {}, + ...this.modelKwargs + }; + const reasoning = this._getReasoningParams(options); + if (reasoning !== void 0) params.reasoning = reasoning; + return params; + } + async _generate(messages, options, runManager) { + options.signal?.throwIfAborted(); + const invocationParams = this.invocationParams(options); + if (invocationParams.stream) { + const stream = this._streamResponseChunks(messages, options, runManager); + let finalChunk; + for await (const chunk of stream) { + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata + }; + finalChunk = finalChunk?.concat(chunk) ?? chunk; + } + return { + generations: finalChunk ? [finalChunk] : [], + llmOutput: { estimatedTokenUsage: (finalChunk?.message)?.usage_metadata } + }; + } else { + const data = await this.completionWithRetry({ + input: convertMessagesToResponsesInput({ + messages, + zdrEnabled: this.zdrEnabled ?? false, + model: this.model + }), + ...invocationParams, + stream: false + }, { + signal: options?.signal, + ...options?.options + }); + return { + generations: [{ + text: data.output_text, + message: convertResponsesMessageToAIMessage(data) + }], + llmOutput: { + id: data.id, + estimatedTokenUsage: data.usage ? { + promptTokens: data.usage.input_tokens, + completionTokens: data.usage.output_tokens, + totalTokens: data.usage.total_tokens + } : void 0 + } + }; + } + } + async *_streamChatModelEvents(messages, options, _runManager) { + const streamIterable = await this.completionWithRetry({ + ...this.invocationParams(options), + input: convertMessagesToResponsesInput({ + messages, + zdrEnabled: this.zdrEnabled ?? false, + model: this.model + }), + stream: true + }, options); + const shouldStreamUsage = this.streamUsage ?? options.streamUsage; + const abortableStream = async function* (source, signal) { + for await (const data of source) { + if (signal?.aborted) return; + yield data; + } + }; + yield* convertOpenAIResponsesStream(abortableStream(streamIterable, options.signal), { + streamUsage: shouldStreamUsage ?? true, + provider: this.streamEventProvider + }); + } + /** Provider id used in native stream protocol passthrough events. */ + get streamEventProvider() { + return "openai"; + } + async *_streamResponseChunks(messages, options, runManager) { + const streamIterable = await this.completionWithRetry({ + ...this.invocationParams(options), + input: convertMessagesToResponsesInput({ + messages, + zdrEnabled: this.zdrEnabled ?? false, + model: this.model + }), + stream: true + }, options); + try { + for await (const data of streamIterable) { + if (options.signal?.aborted) return; + const chunk = convertResponsesDeltaToChatGenerationChunk(data); + if (chunk == null) continue; + yield chunk; + await runManager?.handleLLMNewToken(chunk.text || "", { + prompt: options.promptIndex ?? 0, + completion: 0 + }, void 0, void 0, void 0, { chunk }); + } + } catch (e) { + throw wrapOpenAIClientError(e); + } + } + async completionWithRetry(request, requestOptions) { + return this.caller.call(async () => { + const clientOptions = this._getClientOptions(requestOptions); + try { + if (request.text?.format?.type === "json_schema" && !request.stream) return await this.client.responses.parse(request, clientOptions); + return await this.client.responses.create(request, clientOptions); + } catch (e) { + throw wrapOpenAIClientError(e); + } + }); + } + /** @internal */ + _reduceChatOpenAITools(tools, fields) { + const reducedTools = []; + for (const tool of tools) if (isBuiltInTool(tool)) { + if (tool.type === "image_generation" && fields?.stream) tool.partial_images = 1; + reducedTools.push(tool); + } else if (isCustomTool(tool)) { + const customToolData = tool.metadata.customTool; + reducedTools.push({ + type: "custom", + name: customToolData.name, + description: customToolData.description, + format: customToolData.format + }); + } else if (isOpenAITool(tool)) { + const extra = {}; + for (const [k, v] of Object.entries(tool)) if (k !== "type" && k !== "function") extra[k] = v; + reducedTools.push({ + type: "function", + name: tool.function.name, + parameters: tool.function.parameters, + description: tool.function.description, + strict: fields?.strict ?? null, + ...extra + }); + } else if (isOpenAICustomTool(tool)) reducedTools.push(convertCompletionsCustomTool(tool)); + return reducedTools; + } +}; +//#endregion +//#region node_modules/@langchain/openai/dist/chat_models/index.js +/** +* OpenAI chat model integration. +* +* To use with Azure, import the `AzureChatOpenAI` class. +* +* Setup: +* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`. +* +* ```bash +* npm install @langchain/openai +* export OPENAI_API_KEY="your-api-key" +* ``` +* +* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor) +* +* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html) +* +* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. +* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: +* +* ```typescript +* // When calling `.withConfig`, call options should be passed via the first argument +* const llmWithArgsBound = llm.withConfig({ +* stop: ["\n"], +* tools: [...], +* }); +* +* // When calling `.bindTools`, call options should be passed via the second argument +* const llmWithTools = llm.bindTools( +* [...], +* { +* tool_choice: "auto", +* } +* ); +* ``` +* +* ## Examples +* +*
+* Instantiate +* +* ```typescript +* import { ChatOpenAI } from '@langchain/openai'; +* +* const llm = new ChatOpenAI({ +* model: "gpt-4o-mini", +* temperature: 0, +* maxTokens: undefined, +* timeout: undefined, +* maxRetries: 2, +* // apiKey: "...", +* // configuration: { +* // baseURL: "...", +* // } +* // organization: "...", +* // other params... +* }); +* ``` +*
+* +*
+* +*
+* Invoking +* +* ```typescript +* const input = `Translate "I love programming" into French.`; +* +* // Models also accept a list of chat messages or a formatted prompt +* const result = await llm.invoke(input); +* console.log(result); +* ``` +* +* ```txt +* AIMessage { +* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz", +* "content": "J'adore la programmation.", +* "response_metadata": { +* "tokenUsage": { +* "completionTokens": 5, +* "promptTokens": 28, +* "totalTokens": 33 +* }, +* "finish_reason": "stop", +* "system_fingerprint": "fp_3aa7262c27" +* }, +* "usage_metadata": { +* "input_tokens": 28, +* "output_tokens": 5, +* "total_tokens": 33 +* } +* } +* ``` +*
+* +*
+* +*
+* Streaming Chunks +* +* ```typescript +* for await (const chunk of await llm.stream(input)) { +* console.log(chunk); +* } +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs", +* "content": "" +* } +* AIMessageChunk { +* "content": "J" +* } +* AIMessageChunk { +* "content": "'adore" +* } +* AIMessageChunk { +* "content": " la" +* } +* AIMessageChunk { +* "content": " programmation",, +* } +* AIMessageChunk { +* "content": ".",, +* } +* AIMessageChunk { +* "content": "", +* "response_metadata": { +* "finish_reason": "stop", +* "system_fingerprint": "fp_c9aa9c0491" +* }, +* } +* AIMessageChunk { +* "content": "", +* "usage_metadata": { +* "input_tokens": 28, +* "output_tokens": 5, +* "total_tokens": 33 +* } +* } +* ``` +*
+* +*
+* +*
+* Aggregate Streamed Chunks +* +* ```typescript +* import { AIMessageChunk } from '@langchain/core/messages'; +* import { concat } from '@langchain/core/utils/stream'; +* +* const stream = await llm.stream(input); +* let full: AIMessageChunk | undefined; +* for await (const chunk of stream) { +* full = !full ? chunk : concat(full, chunk); +* } +* console.log(full); +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu", +* "content": "J'adore la programmation.", +* "response_metadata": { +* "prompt": 0, +* "completion": 0, +* "finish_reason": "stop", +* }, +* "usage_metadata": { +* "input_tokens": 28, +* "output_tokens": 5, +* "total_tokens": 33 +* } +* } +* ``` +*
+* +*
+* +*
+* Bind tools +* +* ```typescript +* import { z } from 'zod'; +* +* const GetWeather = { +* name: "GetWeather", +* description: "Get the current weather in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const GetPopulation = { +* name: "GetPopulation", +* description: "Get the current population in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const llmWithTools = llm.bindTools( +* [GetWeather, GetPopulation], +* { +* // strict: true // enforce tool args schema is respected +* } +* ); +* const aiMsg = await llmWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?" +* ); +* console.log(aiMsg.tool_calls); +* ``` +* +* ```txt +* [ +* { +* name: 'GetWeather', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call', +* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK' +* }, +* { +* name: 'GetWeather', +* args: { location: 'New York, NY' }, +* type: 'tool_call', +* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call', +* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'New York, NY' }, +* type: 'tool_call', +* id: 'call_s9KQB1UWj45LLGaEnjz0179q' +* } +* ] +* ``` +*
+* +*
+* +*
+* Structured Output +* +* ```typescript +* import { z } from 'zod'; +* +* const Joke = z.object({ +* setup: z.string().describe("The setup of the joke"), +* punchline: z.string().describe("The punchline to the joke"), +* rating: z.number().nullable().describe("How funny the joke is, from 1 to 10") +* }).describe('Joke to tell user.'); +* +* const structuredLlm = llm.withStructuredOutput(Joke, { +* name: "Joke", +* strict: true, // Optionally enable OpenAI structured outputs +* }); +* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); +* console.log(jokeResult); +* ``` +* +* ```txt +* { +* setup: 'Why was the cat sitting on the computer?', +* punchline: 'Because it wanted to keep an eye on the mouse!', +* rating: 7 +* } +* ``` +*
+* +*
+* +*
+* JSON Object Response Format +* +* ```typescript +* const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } }); +* const jsonLlmAiMsg = await jsonLlm.invoke( +* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]" +* ); +* console.log(jsonLlmAiMsg.content); +* ``` +* +* ```txt +* { +* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67] +* } +* ``` +*
+* +*
+* +*
+* Multimodal +* +* ```typescript +* import { HumanMessage } from '@langchain/core/messages'; +* +* const imageUrl = "https://example.com/image.jpg"; +* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); +* const base64Image = Buffer.from(imageData).toString('base64'); +* +* const message = new HumanMessage({ +* content: [ +* { type: "text", text: "describe the weather in this image" }, +* { +* type: "image_url", +* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, +* }, +* ] +* }); +* +* const imageDescriptionAiMsg = await llm.invoke([message]); +* console.log(imageDescriptionAiMsg.content); +* ``` +* +* ```txt +* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. +* ``` +*
+* +*
+* +*
+* Usage Metadata +* +* ```typescript +* const aiMsgForMetadata = await llm.invoke(input); +* console.log(aiMsgForMetadata.usage_metadata); +* ``` +* +* ```txt +* { input_tokens: 28, output_tokens: 5, total_tokens: 33 } +* ``` +*
+* +*
+* +*
+* Logprobs +* +* ```typescript +* const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true }); +* const aiMsgForLogprobs = await logprobsLlm.invoke(input); +* console.log(aiMsgForLogprobs.response_metadata.logprobs); +* ``` +* +* ```txt +* { +* content: [ +* { +* token: 'J', +* logprob: -0.000050616763, +* bytes: [Array], +* top_logprobs: [] +* }, +* { +* token: "'", +* logprob: -0.01868736, +* bytes: [Array], +* top_logprobs: [] +* }, +* { +* token: 'ad', +* logprob: -0.0000030545007, +* bytes: [Array], +* top_logprobs: [] +* }, +* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] }, +* { +* token: ' la', +* logprob: -0.515404, +* bytes: [Array], +* top_logprobs: [] +* }, +* { +* token: ' programm', +* logprob: -0.0000118755715, +* bytes: [Array], +* top_logprobs: [] +* }, +* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] }, +* { +* token: '.', +* logprob: -0.0000037697225, +* bytes: [Array], +* top_logprobs: [] +* } +* ], +* refusal: null +* } +* ``` +*
+* +*
+* +*
+* Response Metadata +* +* ```typescript +* const aiMsgForResponseMetadata = await llm.invoke(input); +* console.log(aiMsgForResponseMetadata.response_metadata); +* ``` +* +* ```txt +* { +* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 }, +* finish_reason: 'stop', +* system_fingerprint: 'fp_3aa7262c27' +* } +* ``` +*
+* +*
+* +*
+* JSON Schema Structured Output +* +* ```typescript +* const llmForJsonSchema = new ChatOpenAI({ +* model: "gpt-4o-2024-08-06", +* }).withStructuredOutput( +* z.object({ +* command: z.string().describe("The command to execute"), +* expectedOutput: z.string().describe("The expected output of the command"), +* options: z +* .array(z.string()) +* .describe("The options you can pass to the command"), +* }), +* { +* method: "jsonSchema", +* strict: true, // Optional when using the `jsonSchema` method +* } +* ); +* +* const jsonSchemaRes = await llmForJsonSchema.invoke( +* "What is the command to list files in a directory?" +* ); +* console.log(jsonSchemaRes); +* ``` +* +* ```txt +* { +* command: 'ls', +* expectedOutput: 'A list of files and subdirectories within the specified directory.', +* options: [ +* '-a: include directory entries whose names begin with a dot (.).', +* '-l: use a long listing format.', +* '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).', +* '-t: sort by time, newest first.', +* '-r: reverse order while sorting.', +* '-S: sort by file size, largest first.', +* '-R: list subdirectories recursively.' +* ] +* } +* ``` +*
+* +*
+* +*
+* Audio Outputs +* +* ```typescript +* import { ChatOpenAI } from "@langchain/openai"; +* +* const modelWithAudioOutput = new ChatOpenAI({ +* model: "gpt-4o-audio-preview", +* // You may also pass these fields to `.withConfig` as a call argument. +* modalities: ["text", "audio"], // Specifies that the model should output audio. +* audio: { +* voice: "alloy", +* format: "wav", +* }, +* }); +* +* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats."); +* const castMessageContent = audioOutputResult.content[0] as Record; +* +* console.log({ +* ...castMessageContent, +* data: castMessageContent.data.slice(0, 100) // Sliced for brevity +* }) +* ``` +* +* ```txt +* { +* id: 'audio_67117718c6008190a3afad3e3054b9b6', +* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg', +* expires_at: 1729201448, +* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!' +* } +* ``` +*
+* +*
+* +*
+* Audio Outputs +* +* ```typescript +* import { ChatOpenAI } from "@langchain/openai"; +* +* const modelWithAudioOutput = new ChatOpenAI({ +* model: "gpt-4o-audio-preview", +* // You may also pass these fields to `.withConfig` as a call argument. +* modalities: ["text", "audio"], // Specifies that the model should output audio. +* audio: { +* voice: "alloy", +* format: "wav", +* }, +* }); +* +* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats."); +* const castAudioContent = audioOutputResult.additional_kwargs.audio as Record; +* +* console.log({ +* ...castAudioContent, +* data: castAudioContent.data.slice(0, 100) // Sliced for brevity +* }) +* ``` +* +* ```txt +* { +* id: 'audio_67117718c6008190a3afad3e3054b9b6', +* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg', +* expires_at: 1729201448, +* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!' +* } +* ``` +*
+* +*
+*/ +var ChatOpenAI = class ChatOpenAI extends BaseChatOpenAI { + /** + * Whether to use the responses API for all requests. If `false` the responses API will be used + * only when required in order to fulfill the request. + */ + useResponsesApi = false; + responses; + completions; + get lc_serializable_keys() { + return [...super.lc_serializable_keys, "useResponsesApi"]; + } + get callKeys() { + return [...super.callKeys, "useResponsesApi"]; + } + fields; + constructor(modelOrFields, fieldsArg) { + const fields = getChatOpenAIModelParams(modelOrFields, fieldsArg); + super(fields); + this.fields = fields; + this.useResponsesApi = fields?.useResponsesApi ?? false; + this.responses = fields?.responses ?? new ChatOpenAIResponses(fields); + this.completions = fields?.completions ?? new ChatOpenAICompletions(fields); + } + _useResponsesApi(options) { + const usesBuiltInTools = options?.tools?.some(isBuiltInTool); + const hasResponsesOnlyKwargs = options?.previous_response_id != null || options?.text != null || options?.truncation != null || options?.include != null || options?.reasoning?.summary != null || this.reasoning?.summary != null; + const hasCustomTools = options?.tools?.some(isOpenAICustomTool) || options?.tools?.some(isCustomTool); + return this.useResponsesApi || usesBuiltInTools || hasResponsesOnlyKwargs || hasCustomTools || _modelPrefersResponsesAPI(this.model); + } + getLsParams(options) { + const optionsWithDefaults = this._combineCallOptions(options); + if (this._useResponsesApi(options)) return this.responses.getLsParams(optionsWithDefaults); + return this.completions.getLsParams(optionsWithDefaults); + } + invocationParams(options) { + const optionsWithDefaults = this._combineCallOptions(options); + if (this._useResponsesApi(options)) return this.responses.invocationParams(optionsWithDefaults); + return this.completions.invocationParams(optionsWithDefaults); + } + /** @ignore */ + async _generate(messages, options, runManager) { + if (this._useResponsesApi(options)) return this.responses._generate(messages, options, runManager); + return this.completions._generate(messages, options, runManager); + } + async *_streamChatModelEvents(messages, options, runManager) { + if (this._useResponsesApi(options)) { + yield* this.responses._streamChatModelEvents(messages, this._combineCallOptions(options), runManager); + return; + } + yield* this.completions._streamChatModelEvents(messages, this._combineCallOptions(options), runManager); + } + async *_streamResponseChunks(messages, options, runManager) { + if (this._useResponsesApi(options)) { + yield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager); + return; + } + yield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager); + } + withConfig(config) { + const newModel = new ChatOpenAI(this.fields); + newModel.defaultOptions = { + ...this.defaultOptions, + ...config + }; + return newModel; + } +}; +object({ action: union([ + object({ type: literal("screenshot") }), + object({ + type: literal("click"), + x: number(), + y: number(), + button: _enum([ + "left", + "right", + "wheel", + "back", + "forward" + ]).default("left") + }), + object({ + type: literal("double_click"), + x: number(), + y: number(), + button: _enum([ + "left", + "right", + "wheel", + "back", + "forward" + ]).default("left") + }), + object({ + type: literal("drag"), + path: array(object({ + x: number(), + y: number() + })) + }), + object({ + type: literal("keypress"), + keys: array(string()) + }), + object({ + type: literal("move"), + x: number(), + y: number() + }), + object({ + type: literal("scroll"), + x: number(), + y: number(), + scroll_x: number(), + scroll_y: number() + }), + object({ + type: literal("type"), + text: string() + }), + object({ + type: literal("wait"), + duration: number().optional() + }) +]) }); +union([object({ + type: literal("exec"), + command: array(string()), + env: record(string(), string()).optional(), + working_directory: string().optional(), + timeout_ms: number().optional(), + user: string().optional() +})]); +object({ + commands: array(string()).describe("Array of shell commands to execute"), + timeout_ms: number().optional().describe("Optional timeout in milliseconds for the commands"), + max_output_length: number().optional().describe("Optional maximum number of characters to return from each command") +}); +union([ + object({ + type: literal("create_file"), + path: string(), + diff: string() + }), + object({ + type: literal("update_file"), + path: string(), + diff: string() + }), + object({ + type: literal("delete_file"), + path: string() + }) +]); +//#endregion +//#region node_modules/@langchain/openai/dist/index.js +var dist_exports = /* @__PURE__ */ __exportAll({ ChatOpenAI: () => ChatOpenAI }); +//#endregion +export { ChatOpenAICompletions as n, dist_exports as t }; diff --git a/.vercel/output/functions/__server.func/_libs/langchain__xai.mjs b/.vercel/output/functions/__server.func/_libs/langchain__xai.mjs new file mode 100644 index 0000000..6a52e76 --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/langchain__xai.mjs @@ -0,0 +1,883 @@ +import { r as __exportAll } from "../_runtime.mjs"; +import { bn as getEnvironmentVariable, c as isLangChainTool, n as convertToOpenAITool } from "./@langchain/anthropic+[...].mjs"; +import { n as ChatOpenAICompletions } from "./langchain__openai+openai.mjs"; +//#region node_modules/@langchain/xai/dist/live_search.js +/** +* Merge search parameters from instance defaults, tool definition +* and per-call overrides. +* +* Precedence (lowest → highest): +* 1. tool-level configuration (e.g. from xaiLiveSearch) +* 2. instance-level defaults +* 3. per-call overrides passed via `searchParameters` +*/ +function mergeSearchParams(instanceParams, callParams, toolParams) { + if (!instanceParams && !callParams && !toolParams) return; + return { + ...toolParams ?? {}, + ...instanceParams ?? {}, + ...callParams ?? {} + }; +} +/** +* Build the `search_parameters` payload to send to the xAI API +* from high-level `XAISearchParameters`. +*/ +function buildSearchParametersPayload(params) { + if (!params) return; + const payload = { mode: params.mode ?? "auto" }; + if (params.max_search_results !== void 0) payload.max_search_results = params.max_search_results; + if (params.from_date !== void 0) payload.from_date = params.from_date; + if (params.to_date !== void 0) payload.to_date = params.to_date; + if (params.return_citations !== void 0) payload.return_citations = params.return_citations; + if (params.sources && params.sources.length > 0) payload.sources = params.sources; + return payload; +} +/** +* Filter out xAI built-in tools (like `live_search`) from a tools array. +* Used before sending the request to the xAI API, since built-in tools +* are controlled via `search_parameters` instead. +*/ +function filterXAIBuiltInTools(payload) { + if (!payload?.tools) return; + const filtered = payload.tools.filter((tool) => { + if (tool == null || typeof tool !== "object") return true; + if (!("type" in tool)) return true; + if (!payload?.excludedTypes?.length) return true; + return !payload.excludedTypes.includes(tool.type); + }); + return filtered.length > 0 ? filtered : void 0; +} +//#endregion +//#region node_modules/@langchain/xai/dist/profiles.js +var PROFILES = { + "grok-3-fast-latest": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-2-vision": { + maxInputTokens: 8192, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-3": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-code-fast-1": { + maxInputTokens: 256e3, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 1e4, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-2-vision-1212": { + maxInputTokens: 8192, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-4-1-fast-non-reasoning": { + maxInputTokens: 2e6, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 3e4, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-3-mini-fast": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-4-fast": { + maxInputTokens: 2e6, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 3e4, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-4": { + maxInputTokens: 256e3, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-3-latest": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-4-1-fast": { + maxInputTokens: 2e6, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 3e4, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-2-vision-latest": { + maxInputTokens: 8192, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-3-mini-latest": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-3-mini": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-3-mini-fast-latest": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-2-latest": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-4-fast-non-reasoning": { + maxInputTokens: 2e6, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 3e4, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-vision-beta": { + maxInputTokens: 8192, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "grok-3-fast": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + } +}; +//#endregion +//#region node_modules/@langchain/xai/dist/tools/live_search.js +/** +* xAI's deprecated live_search tool type. +*/ +var XAI_LIVE_SEARCH_TOOL_TYPE = "live_search_deprecated_20251215"; +//#endregion +//#region node_modules/@langchain/xai/dist/chat_models/completions.js +/** +* Set of all supported xAI built-in server-side tool types. +* This allows us to easily extend support for future built-in tools +* without changing the core detection logic. +*/ +var XAI_BUILT_IN_TOOL_TYPES = /* @__PURE__ */ new Set([XAI_LIVE_SEARCH_TOOL_TYPE]); +/** +* Checks if a tool is an xAI built-in tool (like live_search). +* Built-in tools are executed server-side by the xAI API. +* +* @param tool - The tool to check +* @returns true if the tool is an xAI built-in tool +*/ +function isXAIBuiltInTool(tool) { + return typeof tool === "object" && tool !== null && "type" in tool && typeof tool.type === "string" && XAI_BUILT_IN_TOOL_TYPES.has(tool.type); +} +/** +* xAI chat model integration. +* +* The xAI API is compatible to the OpenAI API with some limitations. +* +* Setup: +* Install `@langchain/xai` and set an environment variable named `XAI_API_KEY`. +* +* ```bash +* npm install @langchain/xai +* export XAI_API_KEY="your-api-key" +* ``` +* +* ## [Constructor args](https://api.js.langchain.com/classes/_langchain_xai.ChatXAI.html#constructor) +* +* ## [Runtime args](https://api.js.langchain.com/interfaces/_langchain_xai.ChatXAICallOptions.html) +* +* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. +* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: +* +* ```typescript +* // When calling `.withConfig`, call options should be passed via the first argument +* const llmWithArgsBound = llm.withConfig({ +* stop: ["\n"], +* tools: [...], +* }); +* +* // When calling `.bindTools`, call options should be passed via the second argument +* const llmWithTools = llm.bindTools( +* [...], +* { +* tool_choice: "auto", +* } +* ); +* ``` +* +* ## Examples +* +*
+* Instantiate +* +* ```typescript +* import { ChatXAI } from '@langchain/xai'; +* +* const llm = new ChatXAI({ +* model: "grok-3-fast", +* temperature: 0, +* // other params... +* }); +* ``` +*
+* +*
+* +*
+* Invoking +* +* ```typescript +* const input = `Translate "I love programming" into French.`; +* +* // Models also accept a list of chat messages or a formatted prompt +* const result = await llm.invoke(input); +* console.log(result); +* ``` +* +* ```txt +* AIMessage { +* "content": "The French translation of \"I love programming\" is \"J'aime programmer\". In this sentence, \"J'aime\" is the first person singular conjugation of the French verb \"aimer\" which means \"to love\", and \"programmer\" is the French infinitive for \"to program\". I hope this helps! Let me know if you have any other questions.", +* "additional_kwargs": {}, +* "response_metadata": { +* "tokenUsage": { +* "completionTokens": 82, +* "promptTokens": 20, +* "totalTokens": 102 +* }, +* "finish_reason": "stop" +* }, +* "tool_calls": [], +* "invalid_tool_calls": [] +* } +* ``` +*
+* +*
+* +*
+* Streaming Chunks +* +* ```typescript +* for await (const chunk of await llm.stream(input)) { +* console.log(chunk); +* } +* ``` +* +* ```txt +* AIMessageChunk { +* "content": "", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": null +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": "The", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": null +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": " French", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": null +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": " translation", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": null +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": " of", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": null +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": " \"", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": null +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": "I", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": null +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": " love", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": null +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* ... +* AIMessageChunk { +* "content": ".", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": null +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* AIMessageChunk { +* "content": "", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": "stop" +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* ``` +*
+* +*
+* +*
+* Aggregate Streamed Chunks +* +* ```typescript +* import { AIMessageChunk } from '@langchain/core/messages'; +* import { concat } from '@langchain/core/utils/stream'; +* +* const stream = await llm.stream(input); +* let full: AIMessageChunk | undefined; +* for await (const chunk of stream) { +* full = !full ? chunk : concat(full, chunk); +* } +* console.log(full); +* ``` +* +* ```txt +* AIMessageChunk { +* "content": "The French translation of \"I love programming\" is \"J'aime programmer\". In this sentence, \"J'aime\" is the first person singular conjugation of the French verb \"aimer\" which means \"to love\", and \"programmer\" is the French infinitive for \"to program\". I hope this helps! Let me know if you have any other questions.", +* "additional_kwargs": {}, +* "response_metadata": { +* "finishReason": "stop" +* }, +* "tool_calls": [], +* "tool_call_chunks": [], +* "invalid_tool_calls": [] +* } +* ``` +*
+* +*
+* +*
+* Bind tools +* +* ```typescript +* import { z } from 'zod'; +* +* const llmForToolCalling = new ChatXAI({ +* model: "grok-3-fast", +* temperature: 0, +* // other params... +* }); +* +* const GetWeather = { +* name: "GetWeather", +* description: "Get the current weather in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const GetPopulation = { +* name: "GetPopulation", +* description: "Get the current population in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const llmWithTools = llmForToolCalling.bindTools([GetWeather, GetPopulation]); +* const aiMsg = await llmWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?" +* ); +* console.log(aiMsg.tool_calls); +* ``` +* +* ```txt +* [ +* { +* name: 'GetWeather', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call', +* id: 'call_cd34' +* }, +* { +* name: 'GetWeather', +* args: { location: 'New York, NY' }, +* type: 'tool_call', +* id: 'call_68rf' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call', +* id: 'call_f81z' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'New York, NY' }, +* type: 'tool_call', +* id: 'call_8byt' +* } +* ] +* ``` +*
+* +*
+* +*
+* Structured Output +* +* ```typescript +* import { z } from 'zod'; +* +* const Joke = z.object({ +* setup: z.string().describe("The setup of the joke"), +* punchline: z.string().describe("The punchline to the joke"), +* rating: z.number().optional().describe("How funny the joke is, from 1 to 10") +* }).describe('Joke to tell user.'); +* +* const structuredLlm = llmForToolCalling.withStructuredOutput(Joke, { name: "Joke" }); +* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); +* console.log(jokeResult); +* ``` +* +* ```txt +* { +* setup: "Why don't cats play poker in the wild?", +* punchline: 'Because there are too many cheetahs.' +* } +* ``` +*
+* +*
+* +*
+* Server Tool Calling (Live Search) +* +* xAI supports server-side tools that are executed by the API rather than +* requiring client-side execution. The `live_search` tool enables the model +* to search the web for real-time information. +* +* ```typescript +* // Method 1: Using the built-in live_search tool +* const llm = new ChatXAI({ +* model: "grok-3-fast", +* temperature: 0, +* }); +* +* const llmWithSearch = llm.bindTools([{ type: "live_search" }]); +* const result = await llmWithSearch.invoke("What happened in tech news today?"); +* console.log(result.content); +* // The model will search the web and include real-time information in its response +* ``` +* +* ```typescript +* // Method 2: Using searchParameters for more control +* const llm = new ChatXAI({ +* model: "grok-3-fast", +* searchParameters: { +* mode: "auto", // "auto" | "on" | "off" +* max_search_results: 5, +* from_date: "2024-01-01", // ISO date string +* return_citations: true, +* } +* }); +* +* const result = await llm.invoke("What are the latest AI developments?"); +* ``` +* +* ```typescript +* // Method 3: Override search parameters per request +* const result = await llm.invoke("Find recent news about SpaceX", { +* searchParameters: { +* mode: "on", +* max_search_results: 10, +* sources: [ +* { type: "web", allowed_websites: ["spacex.com", "nasa.gov"] }, +* ], +* } +* }); +* ``` +*
+* +*
+*/ +var ChatXAI = class extends ChatOpenAICompletions { + static lc_name() { + return "ChatXAI"; + } + _llmType() { + return "xai"; + } + get lc_secrets() { + return { apiKey: "XAI_API_KEY" }; + } + lc_serializable = true; + lc_namespace = [ + "langchain", + "chat_models", + "xai" + ]; + /** + * Default search parameters for the Live Search API. + */ + searchParameters; + constructor(modelOrFields, fieldsArg) { + const fields = typeof modelOrFields === "string" ? { + ...fieldsArg ?? {}, + model: modelOrFields + } : modelOrFields ?? {}; + const apiKey = fields?.apiKey || getEnvironmentVariable("XAI_API_KEY"); + if (!apiKey) throw new Error(`xAI API key not found. Please set the XAI_API_KEY environment variable or provide the key into "apiKey" field.`); + super({ + ...fields, + model: fields?.model || "grok-3-fast", + apiKey, + configuration: { baseURL: fields?.baseURL ?? "https://api.x.ai/v1" } + }); + this._addVersion("@langchain/xai", "1.4.5"); + this.searchParameters = fields?.searchParameters; + } + toJSON() { + const result = super.toJSON(); + if ("kwargs" in result && typeof result.kwargs === "object" && result.kwargs != null) { + delete result.kwargs.openai_api_key; + delete result.kwargs.configuration; + } + return result; + } + getLsParams(options) { + const params = super.getLsParams(options); + params.ls_provider = "xai"; + return params; + } + /** + * Get the effective search parameters, merging defaults with call options. + * @param options Call options that may contain search parameters + * @returns Merged search parameters or undefined if none are configured + */ + _getEffectiveSearchParameters(options) { + return mergeSearchParams(this.searchParameters, options?.searchParameters); + } + /** + * Check if any built-in tools (like live_search) are in the tools list. + * @param tools List of tools to check + * @returns true if any built-in tools are present + */ + _hasBuiltInTools(tools) { + return tools?.some(isXAIBuiltInTool) ?? false; + } + /** + * Formats tools to xAI/OpenAI format, preserving provider-specific definitions. + * + * @param tools The tools to format + * @returns The formatted tools + */ + formatStructuredToolToXAI(tools) { + if (!tools || !tools.length) return; + return tools.map((tool) => { + if (isLangChainTool(tool) && tool.extras?.providerToolDefinition) return tool.extras.providerToolDefinition; + if (isXAIBuiltInTool(tool)) return tool; + return convertToOpenAITool(tool); + }); + } + bindTools(tools, kwargs) { + return this.withConfig({ + tools: this.formatStructuredToolToXAI(tools), + ...kwargs + }); + } + /** @internal */ + invocationParams(options, extra) { + const params = { ...super.invocationParams(options, extra) }; + const liveSearchTool = options?.tools?.find(isXAIBuiltInTool); + const mergedSearchParams = mergeSearchParams(this.searchParameters, options?.searchParameters, liveSearchTool); + if (mergedSearchParams) params.search_parameters = buildSearchParametersPayload(mergedSearchParams); + return params; + } + /** + * Calls the xAI API with retry logic in case of failures. + * @param request The request to send to the xAI API. + * @param options Optional configuration for the API call. + * @returns The response from the xAI API. + */ + async completionWithRetry(request, options) { + delete request.frequency_penalty; + delete request.presence_penalty; + delete request.logit_bias; + delete request.functions; + const newRequestMessages = request.messages.map((msg) => { + if (!msg.content) return { + ...msg, + content: "" + }; + return msg; + }); + let filteredTools; + if (request.tools) filteredTools = filterXAIBuiltInTools({ + tools: request.tools, + excludedTypes: [XAI_LIVE_SEARCH_TOOL_TYPE] + }); + const newRequest = { + ...request, + messages: newRequestMessages, + tools: filteredTools + }; + if (newRequest.stream === true) return super.completionWithRetry(newRequest, options); + return super.completionWithRetry(newRequest, options); + } + _convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) { + const messageChunk = super._convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole); + const responseMetadata = messageChunk.response_metadata; + if (!rawResponse.choices[0]?.finish_reason) { + delete responseMetadata.usage; + delete messageChunk.usage_metadata; + } else messageChunk.usage_metadata = responseMetadata.usage; + return messageChunk; + } + /** + * Return profiling information for the model. + * + * Provides information about the model's capabilities and constraints, + * including token limits, multimodal support, and advanced features like + * tool calling and structured output. + * + * @returns {ModelProfile} An object describing the model's capabilities and constraints + * + * @example + * ```typescript + * const model = new ChatXAI({ model: "grok-3-fast" }); + * const profile = model.profile; + * console.log(profile.maxInputTokens); // 128000 + * console.log(profile.imageInputs); // true + * ``` + */ + get profile() { + return PROFILES[this.model] ?? {}; + } + get streamEventProvider() { + return "xai"; + } +}; +//#endregion +//#region node_modules/@langchain/xai/dist/index.js +var dist_exports = /* @__PURE__ */ __exportAll({ ChatXAI: () => ChatXAI }); +//#endregion +export { dist_exports as t }; diff --git a/.vercel/output/functions/__server.func/_libs/lucide-react.mjs b/.vercel/output/functions/__server.func/_libs/lucide-react.mjs index de14f5c..297791a 100644 --- a/.vercel/output/functions/__server.func/_libs/lucide-react.mjs +++ b/.vercel/output/functions/__server.func/_libs/lucide-react.mjs @@ -95,6 +95,32 @@ var ArrowDown = createLucideIcon("arrow-down", [["path", { * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var ArrowLeft = createLucideIcon("arrow-left", [["path", { + d: "m12 19-7-7 7-7", + key: "1l729n" +}], ["path", { + d: "M19 12H5", + key: "x3x0zl" +}]]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ +var ArrowRight = createLucideIcon("arrow-right", [["path", { + d: "M5 12h14", + key: "1ays0h" +}], ["path", { + d: "m12 5 7 7-7 7", + key: "xquz4c" +}]]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var ArrowUp = createLucideIcon("arrow-up", [["path", { d: "m5 12 7-7 7 7", key: "hav0vg" @@ -108,6 +134,42 @@ var ArrowUp = createLucideIcon("arrow-up", [["path", { * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Bot = createLucideIcon("bot", [ + ["path", { + d: "M12 8V4H8", + key: "hb8ula" + }], + ["rect", { + width: "16", + height: "12", + x: "4", + y: "8", + rx: "2", + key: "enze0r" + }], + ["path", { + d: "M2 14h2", + key: "vft8re" + }], + ["path", { + d: "M20 14h2", + key: "4cs60a" + }], + ["path", { + d: "M15 13v2", + key: "1xurst" + }], + ["path", { + d: "M9 13v2", + key: "rq6x2g" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var Check = createLucideIcon("check", [["path", { d: "M20 6 9 17l-5-5", key: "1gmf2c" @@ -206,6 +268,29 @@ var Copy = createLucideIcon("copy", [["rect", { * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Download = createLucideIcon("download", [ + ["path", { + d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4", + key: "ih7n3h" + }], + ["polyline", { + points: "7 10 12 15 17 10", + key: "2ggqvy" + }], + ["line", { + x1: "12", + x2: "12", + y1: "15", + y2: "3", + key: "1vk2je" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var Ellipsis = createLucideIcon("ellipsis", [ ["circle", { cx: "12", @@ -247,7 +332,7 @@ var Eye = createLucideIcon("eye", [["path", { * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ -var FilePlus = createLucideIcon("file-plus", [ +var FileDown = createLucideIcon("file-down", [ ["path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z", key: "1rqfz7" @@ -256,13 +341,13 @@ var FilePlus = createLucideIcon("file-plus", [ d: "M14 2v4a2 2 0 0 0 2 2h4", key: "tnqrlb" }], - ["path", { - d: "M9 15h6", - key: "cctwl0" - }], ["path", { d: "M12 18v-6", key: "17g6i2" + }], + ["path", { + d: "m9 15 3 3 3-3", + key: "1npd3o" }] ]); /** @@ -299,6 +384,76 @@ var FileText = createLucideIcon("file-text", [ * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var FolderInput = createLucideIcon("folder-input", [ + ["path", { + d: "M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1", + key: "fm4g5t" + }], + ["path", { + d: "M2 13h10", + key: "pgb2dq" + }], + ["path", { + d: "m9 16 3-3-3-3", + key: "6m91ic" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ +var FolderOpen = createLucideIcon("folder-open", [["path", { + d: "m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2", + key: "usdka0" +}]]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ +var FolderOutput = createLucideIcon("folder-output", [ + ["path", { + d: "M2 7.5V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-1.5", + key: "1yk7aj" + }], + ["path", { + d: "M2 13h10", + key: "pgb2dq" + }], + ["path", { + d: "m5 10-3 3 3 3", + key: "1r8ie0" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ +var FolderPlus = createLucideIcon("folder-plus", [ + ["path", { + d: "M12 10v6", + key: "1bos4e" + }], + ["path", { + d: "M9 13h6", + key: "1uhe8q" + }], + ["path", { + d: "M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z", + key: "1kt360" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var GripVertical = createLucideIcon("grip-vertical", [ ["circle", { cx: "9", @@ -343,6 +498,39 @@ var GripVertical = createLucideIcon("grip-vertical", [ * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var HardDrive = createLucideIcon("hard-drive", [ + ["line", { + x1: "22", + x2: "2", + y1: "12", + y2: "12", + key: "1y58io" + }], + ["path", { + d: "M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z", + key: "oot6mr" + }], + ["line", { + x1: "6", + x2: "6.01", + y1: "16", + y2: "16", + key: "sgf278" + }], + ["line", { + x1: "10", + x2: "10.01", + y1: "16", + y2: "16", + key: "1l4acy" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var Heading1 = createLucideIcon("heading-1", [ ["path", { d: "M4 12h8", @@ -446,6 +634,29 @@ var Image = createLucideIcon("image", [ * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Link2 = createLucideIcon("link-2", [ + ["path", { + d: "M9 17H7A5 5 0 0 1 7 7h2", + key: "8i5ue5" + }], + ["path", { + d: "M15 7h2a5 5 0 1 1 0 10h-2", + key: "1b9ql8" + }], + ["line", { + x1: "8", + x2: "16", + y1: "12", + y2: "12", + key: "1jonct" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var ListOrdered = createLucideIcon("list-ordered", [ ["path", { d: "M10 12h11", @@ -643,6 +854,36 @@ var Minus = createLucideIcon("minus", [["path", { * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Monitor = createLucideIcon("monitor", [ + ["rect", { + width: "20", + height: "14", + x: "2", + y: "3", + rx: "2", + key: "48i651" + }], + ["line", { + x1: "8", + x2: "16", + y1: "21", + y2: "21", + key: "1svkeh" + }], + ["line", { + x1: "12", + x2: "12", + y1: "17", + y2: "21", + key: "vw1qmm" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var Moon = createLucideIcon("moon", [["path", { d: "M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z", key: "a7tn18" @@ -717,6 +958,30 @@ var Plus = createLucideIcon("plus", [["path", { * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Plug = createLucideIcon("plug", [ + ["path", { + d: "M12 22v-5", + key: "1ega77" + }], + ["path", { + d: "M9 8V2", + key: "14iosj" + }], + ["path", { + d: "M15 8V2", + key: "18g5xt" + }], + ["path", { + d: "M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z", + key: "osxo6l" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var Quote = createLucideIcon("quote", [["path", { d: "M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z", key: "rib7q0" @@ -743,6 +1008,26 @@ var RotateCcw = createLucideIcon("rotate-ccw", [["path", { * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Save = createLucideIcon("save", [ + ["path", { + d: "M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z", + key: "1c8476" + }], + ["path", { + d: "M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7", + key: "1ydtos" + }], + ["path", { + d: "M7 3v4a1 1 0 0 0 1 1h7", + key: "t51u73" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var Search = createLucideIcon("search", [["path", { d: "m21 21-4.34-4.34", key: "14j7rj" @@ -814,6 +1099,20 @@ var SquareCheckBig = createLucideIcon("square-check-big", [["path", { * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Square = createLucideIcon("square", [["rect", { + width: "18", + height: "18", + x: "3", + y: "3", + rx: "2", + key: "afitv7" +}]]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var Star = createLucideIcon("star", [["path", { d: "M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z", key: "r04s7s" @@ -880,6 +1179,22 @@ var Table2 = createLucideIcon("table-2", [["path", { * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Terminal = createLucideIcon("terminal", [["polyline", { + points: "4 17 10 11 4 5", + key: "akl6gq" +}], ["line", { + x1: "12", + x2: "20", + y1: "19", + y2: "19", + key: "q2wloq" +}]]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var Trash2 = createLucideIcon("trash-2", [ ["path", { d: "M3 6h18", @@ -940,6 +1255,73 @@ var Type = createLucideIcon("type", [ * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Unlink = createLucideIcon("unlink", [ + ["path", { + d: "m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71", + key: "yqzxt4" + }], + ["path", { + d: "m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71", + key: "4qinb0" + }], + ["line", { + x1: "8", + x2: "8", + y1: "2", + y2: "5", + key: "1041cp" + }], + ["line", { + x1: "2", + x2: "5", + y1: "8", + y2: "8", + key: "14m1p5" + }], + ["line", { + x1: "16", + x2: "16", + y1: "19", + y2: "22", + key: "rzdirn" + }], + ["line", { + x1: "19", + x2: "22", + y1: "16", + y2: "16", + key: "ox905f" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ +var Upload = createLucideIcon("upload", [ + ["path", { + d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4", + key: "ih7n3h" + }], + ["polyline", { + points: "17 8 12 3 7 8", + key: "t8dd8p" + }], + ["line", { + x1: "12", + x2: "12", + y1: "3", + y2: "15", + key: "widbto" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var WandSparkles = createLucideIcon("wand-sparkles", [ ["path", { d: "m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72", @@ -980,6 +1362,30 @@ var WandSparkles = createLucideIcon("wand-sparkles", [ * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */ +var Wifi = createLucideIcon("wifi", [ + ["path", { + d: "M12 20h.01", + key: "zekei9" + }], + ["path", { + d: "M2 8.82a15 15 0 0 1 20 0", + key: "dnpr2z" + }], + ["path", { + d: "M5 12.859a10 10 0 0 1 14 0", + key: "1x1e6c" + }], + ["path", { + d: "M8.5 16.429a5 5 0 0 1 7 0", + key: "1bycff" + }] +]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ var Workflow = createLucideIcon("workflow", [ ["rect", { width: "8", @@ -1015,5 +1421,15 @@ var X = createLucideIcon("x", [["path", { d: "m6 6 12 12", key: "d8bk6v" }]]); +/** +* @license lucide-react v0.510.0 - ISC +* +* This source code is licensed under the ISC license. +* See the LICENSE file in the root directory of this source tree. +*/ +var Zap = createLucideIcon("zap", [["path", { + d: "M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z", + key: "1xq2db" +}]]); //#endregion -export { Heading3 as A, Cloud as B, LogIn as C, ListTodo as D, ListTree as E, FilePlus as F, ArrowUp as G, ChevronRight as H, Eye as I, ArrowDown as K, Ellipsis as L, Heading1 as M, GripVertical as N, ListOrdered as O, FileText as P, Copy as R, Menu as S, List as T, ChevronDown as U, CloudOff as V, Check as W, PanelLeft as _, Trash2 as a, Minus as b, Star as c, Settings as d, Search as f, Play as g, Plus as h, Type as i, Heading2 as j, Image as k, SquareCheckBig as l, Quote as m, Workflow as n, Table2 as o, RotateCcw as p, WandSparkles as r, Sun as s, X as t, Sparkles as u, PanelLeftClose as v, LoaderCircle as w, MessageSquare as x, Moon as y, CodeXml as z }; +export { Download as $, MessageSquare as A, Heading3 as B, Plus as C, Moon as D, PanelLeftClose as E, ListTree as F, FolderPlus as G, Heading1 as H, ListTodo as I, FolderInput as J, FolderOutput as K, ListOrdered as L, LogIn as M, LoaderCircle as N, Monitor as O, List as P, Ellipsis as Q, Link2 as R, Plug as S, PanelLeft as T, HardDrive as U, Heading2 as V, GripVertical as W, FileDown as X, FileText as Y, Eye as Z, Settings as _, WandSparkles as a, ChevronDown as at, RotateCcw as b, Type as c, ArrowUp as ct, Table2 as d, ArrowDown as dt, Copy as et, Sun as f, Sparkles as g, SquareCheckBig as h, Wifi as i, ChevronRight as it, Menu as j, Minus as k, Trash2 as l, ArrowRight as lt, Square as m, X as n, Cloud as nt, Upload as o, Check as ot, Star as p, FolderOpen as q, Workflow as r, CloudOff as rt, Unlink as s, Bot as st, Zap as t, CodeXml as tt, Terminal as u, ArrowLeft as ut, Search as v, Play as w, Quote as x, Save as y, Image as z }; diff --git a/.vercel/output/functions/__server.func/_libs/sonner.mjs b/.vercel/output/functions/__server.func/_libs/sonner.mjs index f76d03c..922e2a9 100644 --- a/.vercel/output/functions/__server.func/_libs/sonner.mjs +++ b/.vercel/output/functions/__server.func/_libs/sonner.mjs @@ -328,7 +328,7 @@ var isHttpResponse = (data) => { var basicToast = toastFunction; var getHistory = () => ToastState.toasts; var getToasts = () => ToastState.getActiveToasts(); -Object.assign(basicToast, { +var toast = Object.assign(basicToast, { success: ToastState.success, info: ToastState.info, warning: ToastState.warning, @@ -905,4 +905,4 @@ var Toaster = /*#__PURE__*/ import_react.forwardRef(function Toaster(props, ref) })); }); //#endregion -export { Toaster as t }; +export { toast as n, Toaster as t }; diff --git a/.vercel/output/functions/__server.func/_libs/tauri-apps__api.mjs b/.vercel/output/functions/__server.func/_libs/tauri-apps__api.mjs new file mode 100644 index 0000000..bb5421b --- /dev/null +++ b/.vercel/output/functions/__server.func/_libs/tauri-apps__api.mjs @@ -0,0 +1,90 @@ +import { r as __exportAll } from "../_runtime.mjs"; +//#endregion +//#region node_modules/@tauri-apps/api/core.js +var core_exports = /* @__PURE__ */ __exportAll({ + SERIALIZE_TO_IPC_FN: () => SERIALIZE_TO_IPC_FN, + invoke: () => invoke, + transformCallback: () => transformCallback +}); +/** +* Invoke your custom commands. +* +* This package is also accessible with `window.__TAURI__.core` when [`app.withGlobalTauri`](https://v2.tauri.app/reference/config/#withglobaltauri) in `tauri.conf.json` is set to `true`. +* @module +*/ +/** +* A key to be used to implement a special function +* on your types that define how your type should be serialized +* when passing across the IPC. +* @example +* Given a type in Rust that looks like this +* ```rs +* #[derive(serde::Serialize, serde::Deserialize) +* enum UserId { +* String(String), +* Number(u32), +* } +* ``` +* `UserId::String("id")` would be serialized into `{ String: "id" }` +* and so we need to pass the same structure back to Rust +* ```ts +* import { SERIALIZE_TO_IPC_FN } from "@tauri-apps/api/core" +* +* class UserIdString { +* id +* constructor(id) { +* this.id = id +* } +* +* [SERIALIZE_TO_IPC_FN]() { +* return { String: this.id } +* } +* } +* +* class UserIdNumber { +* id +* constructor(id) { +* this.id = id +* } +* +* [SERIALIZE_TO_IPC_FN]() { +* return { Number: this.id } +* } +* } +* +* type UserId = UserIdString | UserIdNumber +* ``` +* +*/ +var SERIALIZE_TO_IPC_FN = "__TAURI_TO_IPC_KEY__"; +/** +* Stores the callback in a known location, and returns an identifier that can be passed to the backend. +* The backend uses the identifier to `eval()` the callback. +* +* @return An unique identifier associated with the callback function. +* +* @since 1.0.0 +*/ +function transformCallback(callback, once = false) { + return window.__TAURI_INTERNALS__.transformCallback(callback, once); +} +/** +* Sends a message to the backend. +* @example +* ```typescript +* import { invoke } from '@tauri-apps/api/core'; +* await invoke('login', { user: 'tauri', password: 'poiwe3h4r5ip3yrhtew9ty' }); +* ``` +* +* @param cmd The command name. +* @param args The optional arguments to pass to the command. +* @param options The request options. +* @return A promise resolving or rejecting to the backend response. +* +* @since 1.0.0 +*/ +async function invoke(cmd, args = {}, options) { + return window.__TAURI_INTERNALS__.invoke(cmd, args, options); +} +//#endregion +export { core_exports as t }; diff --git a/.vercel/output/functions/__server.func/_libs/zod.mjs b/.vercel/output/functions/__server.func/_libs/zod.mjs deleted file mode 100644 index 8a9eb02..0000000 --- a/.vercel/output/functions/__server.func/_libs/zod.mjs +++ /dev/null @@ -1,10 +0,0 @@ -import { E as ZodString, L as _coercedBoolean, R as _coercedString, T as ZodBoolean } from "./@better-auth/core+[...].mjs"; -//#region node_modules/zod/v4/classic/coerce.js -function string(params) { - return _coercedString(ZodString, params); -} -function boolean(params) { - return _coercedBoolean(ZodBoolean, params); -} -//#endregion -export { string as n, boolean as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/ai-server-BfsU_lCo.mjs b/.vercel/output/functions/__server.func/_ssr/ai-server-BfsU_lCo.mjs new file mode 100644 index 0000000..abc30f1 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/ai-server-BfsU_lCo.mjs @@ -0,0 +1,455 @@ +import { r as createServerFn } from "./ssr.mjs"; +import { t as createServerRpc } from "./createServerRpc-CcvdN_gc.mjs"; +import { i as resolveChatModel, n as getAiConfig, r as hasLiveCredentials, t as WORKSPACE_SKILLS } from "./resolve-model-CV2sMs92.mjs"; +import { a as publicAiSettings } from "./settings-types-CI9vU3Ws.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/ai-server-BfsU_lCo.js +function validateMcpServer(m) { + return { + id: String(m.id || "mcp").slice(0, 64), + name: String(m.name || "mcp").slice(0, 80), + enabled: m.enabled !== false, + transport: m.transport === "sse" || m.transport === "stdio" || m.transport === "http" ? m.transport : "http", + url: typeof m.url === "string" ? m.url.slice(0, 500) : "", + authToken: typeof m.authToken === "string" ? m.authToken.slice(0, 500) : "", + headersText: typeof m.headersText === "string" ? m.headersText.slice(0, 2e3) : "", + command: typeof m.command === "string" ? m.command.slice(0, 200) : "", + argsText: typeof m.argsText === "string" ? m.argsText.slice(0, 1e3) : "", + envText: typeof m.envText === "string" ? m.envText.slice(0, 2e3) : "" + }; +} +function validateSettings(input) { + if (!input || typeof input !== "object") return null; + const s = input; + return { + setupComplete: Boolean(s.setupComplete), + enabled: s.enabled !== false, + backend: s.backend === "direct" || s.backend === "local" || s.backend === "deepagents" || s.backend === "claude-cli" || s.backend === "codex-cli" || s.backend === "grok-cli" ? s.backend : "deepagents", + preferStreaming: s.preferStreaming !== false, + provider: s.provider === "anthropic" || s.provider === "openai" || s.provider === "ollama" || s.provider === "openai_compatible" || s.provider === "xai" ? s.provider : "xai", + model: typeof s.model === "string" ? s.model.slice(0, 120) : "grok-4.5", + apiKey: typeof s.apiKey === "string" ? s.apiKey.slice(0, 500) : "", + baseUrl: typeof s.baseUrl === "string" ? s.baseUrl.slice(0, 500) : "", + temperature: Math.min(1.5, Math.max(0, Number(s.temperature) || .35)), + recursionLimit: Math.min(80, Math.max(8, Number(s.recursionLimit) || 40)), + mcpServers: Array.isArray(s.mcpServers) ? s.mcpServers.slice(0, 20).map((m) => validateMcpServer(m)) : [], + enabledSkills: Array.isArray(s.enabledSkills) ? s.enabledSkills.map(String).slice(0, 50) : [...WORKSPACE_SKILLS] + }; +} +function validateRequest(input) { + const data = input; + if (!data || typeof data !== "object") throw new Error("Invalid AI request"); + const action = data.action; + if (![ + "edit_block", + "summarize", + "action_items", + "table", + "outline", + "mermaid", + "custom" + ].includes(action)) throw new Error("Invalid AI action"); + return { + action, + instruction: typeof data.instruction === "string" ? data.instruction.slice(0, 4e3) : "", + blockText: typeof data.blockText === "string" ? data.blockText.slice(0, 8e3) : "", + blockType: data.blockType, + pageTitle: typeof data.pageTitle === "string" ? data.pageTitle.slice(0, 500) : "", + pageText: typeof data.pageText === "string" ? data.pageText.slice(0, 2e4) : "", + clientSettings: validateSettings(data.clientSettings) + }; +} +function buildSystemPrompt(action) { + const base = "You help edit a Notion-style notes workspace. Be concise, high-signal, and practical. Never use emoji unless the user asks. Return only the content requested — no preamble."; + switch (action) { + case "edit_block": return `${base} Rewrite the given block text per the instruction. Return plain text only (no quotes around the whole answer).`; + case "summarize": return `${base} Summarize the page. Return JSON: {"blocks":[{"type":"heading2","content":"..."},{"type":"paragraph","content":"..."},{"type":"bullet","content":"..."}]} using types paragraph|heading1|heading2|heading3|bullet|numbered|todo|quote|callout|code|mermaid.`; + case "action_items": return `${base} Extract action items as todos. Return JSON: {"blocks":[{"type":"heading2","content":"Action items"},{"type":"todo","content":"..."}]} only.`; + case "table": return `${base} Create a markdown table from the page. Return JSON: {"blocks":[{"type":"heading2","content":"..."},{"type":"code","content":"| Col | ... |\\n|---|---|\\n| ... |"}]} — put the table in a code block.`; + case "outline": return `${base} Create a hierarchical outline. Return JSON: {"blocks":[{"type":"heading2","content":"Outline"},{"type":"bullet","content":"..."},{"type":"bullet","content":"..."}]} .`; + case "mermaid": return `${base} Create a Mermaid diagram for the page. Return JSON: {"blocks":[{"type":"heading2","content":"Diagram"},{"type":"mermaid","content":"flowchart TD\\n A-->B"}]} . Valid mermaid only in content.`; + case "custom": return `${base} Follow the user instruction using the page context. Prefer JSON {"blocks":[...]} when creating multiple blocks; otherwise plain text in {"text":"..."}. Allowed block types: paragraph,heading1,heading2,heading3,bullet,numbered,todo,quote,callout,code,mermaid.`; + default: return base; + } +} +function buildUserPrompt(req) { + const parts = []; + if (req.pageTitle) parts.push(`Page title: ${req.pageTitle}`); + if (req.pageText) parts.push(`Page content:\n${req.pageText}`); + if (req.blockText) parts.push(`Block (${req.blockType ?? "text"}):\n${req.blockText}`); + if (req.instruction) parts.push(`Instruction:\n${req.instruction}`); + if (req.action === "edit_block" && !req.instruction) parts.push("Instruction: Improve clarity and fix grammar while preserving meaning."); + return parts.join("\n\n") || "Empty page."; +} +async function callDirect(settings, system, user) { + const { model, provider, modelName } = await resolveChatModel(settings); + const res = await model.invoke([{ + role: "system", + content: system + }, { + role: "user", + content: user + }]); + const text = typeof res.content === "string" ? res.content.trim() : Array.isArray(res.content) ? res.content.map((c) => typeof c === "string" ? c : c.text ?? "").join("").trim() : String(res.content ?? "").trim(); + if (!text) throw new Error("Empty model response"); + return { + text, + model: modelName, + provider + }; +} +function parseModelPayload(raw, action) { + const candidate = (raw.match(/```(?:json)?\s*([\s\S]*?)```/)?.[1] ?? raw).trim(); + try { + const parsed = JSON.parse(candidate); + if (parsed.blocks && Array.isArray(parsed.blocks)) return { + text: parsed.text ?? "", + blocks: parsed.blocks.filter((b) => b && typeof b.content === "string").map((b) => ({ + type: b.type || "paragraph", + content: String(b.content) + })), + provider: "xai" + }; + if (typeof parsed.text === "string") return { + text: parsed.text, + provider: "xai" + }; + } catch {} + if (action === "edit_block" || action === "custom") return { + text: raw.replace(/^["']|["']$/g, "").trim(), + provider: "xai" + }; + return { + text: raw, + blocks: [{ + type: "paragraph", + content: raw + }], + provider: "xai" + }; +} +function localAi(req) { + const page = (req.pageText || "").trim(); + const title = req.pageTitle || "Untitled"; + const lines = page.split("\n").map((l) => l.replace(/^#+\s*/, "").replace(/^[-*•]\s*/, "").replace(/^\d+\.\s*/, "").trim()).filter(Boolean); + const unique = [...new Set(lines)].slice(0, 24); + if (req.action === "edit_block") { + let text = (req.blockText || "").trim(); + const instruction = (req.instruction || "").toLowerCase(); + if (!text) text = "Add a clear note here."; + if (instruction.includes("short") || instruction.includes("concise")) { + text = text.split(/[.!?]/).slice(0, 2).join(". ").trim(); + if (text && !/[.!?]$/.test(text)) text += "."; + } else if (instruction.includes("long") || instruction.includes("expand")) text = `${text} In practice, this means spelling out the goal, the constraints, and the next concrete step so anyone can pick it up cold.`; + else if (instruction.includes("professional") || instruction.includes("formal")) { + text = text.replace(/\b(gonna|wanna|kinda|gotta)\b/gi, (m) => { + return { + gonna: "going to", + wanna: "want to", + kinda: "somewhat", + gotta: "need to" + }[m.toLowerCase()] ?? m; + }); + text = text.charAt(0).toUpperCase() + text.slice(1); + } else if (instruction.includes("fix") || instruction.includes("grammar")) { + text = text.replace(/\s+/g, " ").replace(/\si\s/g, " I ").replace(/(^\w)/, (c) => c.toUpperCase()); + if (text && !/[.!?]$/.test(text)) text += "."; + } else if (instruction) text = `${text}\n\n(${instruction.replace(/\.$/, "")} — local demo. Open AI setup to connect Grok, Claude, Ollama, etc.)`; + else { + text = text.replace(/\s+/g, " ").trim(); + if (text && !/[.!?]$/.test(text)) text += "."; + } + return { + text, + provider: "local" + }; + } + if (req.action === "summarize") { + const bullets = unique.slice(0, 5); + return { + text: "", + provider: "local", + blocks: [ + { + type: "heading2", + content: `Summary — ${title}` + }, + { + type: "paragraph", + content: bullets.length > 0 ? `This page covers ${bullets.length} main points: ${bullets.slice(0, 3).map((b) => b.replace(/\.$/, "")).join("; ")}.` : "This page is still light — add notes, then run AI summary again." + }, + ...bullets.map((b) => ({ + type: "bullet", + content: b.slice(0, 200) + })) + ] + }; + } + if (req.action === "action_items") { + const todos = unique.filter((l) => /todo|need|should|must|fix|add|ship|write|create|update|check/i.test(l) || l.length < 80).slice(0, 6); + const items = todos.length ? todos : unique.slice(0, 4); + return { + text: "", + provider: "local", + blocks: [{ + type: "heading2", + content: "Action items" + }, ...items.length ? items.map((c) => ({ + type: "todo", + content: c.slice(0, 160) + })) : [{ + type: "todo", + content: "Capture next steps on this page" + }]] + }; + } + if (req.action === "table") return { + text: "", + provider: "local", + blocks: [{ + type: "heading2", + content: "Table" + }, { + type: "code", + content: [ + "| Topic | Note |", + "| --- | --- |", + ...unique.slice(0, 6).map((r, i) => `| ${i + 1}. ${r.slice(0, 40).replace(/\|/g, "/")} | From page |`) + ].join("\n") + }] + }; + if (req.action === "outline") return { + text: "", + provider: "local", + blocks: [ + { + type: "heading2", + content: "Outline" + }, + { + type: "bullet", + content: title + }, + ...unique.slice(0, 8).map((c) => ({ + type: "bullet", + content: c.slice(0, 120) + })) + ] + }; + if (req.action === "mermaid") { + const nodes = unique.slice(0, 5).map((l, i) => { + return { + id: String.fromCharCode(65 + i), + label: l.slice(0, 28).replace(/"/g, "'") + }; + }); + return { + text: "", + provider: "local", + blocks: [{ + type: "heading2", + content: "Diagram" + }, { + type: "mermaid", + content: (nodes.length >= 2 ? [ + "flowchart TD", + ...nodes.map((n) => ` ${n.id}["${n.label}"]`), + ...nodes.slice(0, -1).map((n, i) => ` ${n.id} --> ${nodes[i + 1].id}`) + ] : [ + "flowchart TD", + ` A["${title.slice(0, 28)}"]`, + " B[\"Add more notes\"]", + " A --> B" + ]).join("\n") + }] + }; + } + return { + text: "", + provider: "local", + blocks: [ + { + type: "heading2", + content: "AI response" + }, + { + type: "paragraph", + content: `Request: ${(req.instruction || "Help with this page").trim()}` + }, + { + type: "callout", + content: "Local demo mode. Open Settings → Configure AI to connect Grok, Claude, OpenAI, Ollama, and MCP servers." + }, + ...unique.slice(0, 4).map((c) => ({ + type: "bullet", + content: c.slice(0, 160) + })) + ] + }; +} +function effectiveBackend(settings) { + if (!settings) return getAiConfig().effective; + if (!settings.enabled || settings.backend === "local") return "local"; + if (settings.backend === "claude-cli" || settings.backend === "codex-cli" || settings.backend === "grok-cli") return settings.backend; + if (hasLiveCredentials(settings)) return settings.backend; + if (settings.provider === "xai" && process.env.XAI_API_KEY?.trim()) return settings.backend; + if (settings.provider === "anthropic" && process.env.ANTHROPIC_API_KEY?.trim()) return settings.backend; + if (settings.provider === "openai" && process.env.OPENAI_API_KEY?.trim()) return settings.backend; + if (settings.provider === "ollama") return settings.backend; + return "local"; +} +var runAi_createServerFn_handler = createServerRpc({ + id: "76d08ea8f0b0103fcaf7055c8b138a9579e4124d0d2f62a0686a1011273cd47a", + name: "runAi", + filename: "src/lib/ai-server.ts" +}, (opts) => runAi.__executeServer(opts)); +var runAi = createServerFn({ method: "POST" }).validator((input) => validateRequest(input)).handler(runAi_createServerFn_handler, async ({ data }) => { + const settings = data.clientSettings ?? null; + const backend = effectiveBackend(settings); + const req = { + action: data.action, + instruction: data.instruction, + blockText: data.blockText, + blockType: data.blockType, + pageTitle: data.pageTitle, + pageText: data.pageText + }; + if (backend === "local") return localAi(req); + if (backend === "claude-cli" || backend === "codex-cli" || backend === "grok-cli") try { + const { runCliAgent } = await import("./cli-backends-BkZaX-Hk.mjs").then((n) => n.t); + return await runCliAgent(backend, req); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + console.error("[ai] cli backend failed:", message); + throw new Error(message); + } + if (backend === "deepagents") try { + const { runDeepAgent } = await import("./deep-agent-CPCjT_2e.mjs"); + return await runDeepAgent(req, settings); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + if (message !== "NO_KEY") console.error("[ai] deepagents failed:", message); + } + try { + const { text, model, provider } = await callDirect(settings, buildSystemPrompt(req.action), buildUserPrompt(req)); + return { + ...parseModelPayload(text, req.action), + model: `${provider}:${model}` + }; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + if (message !== "NO_KEY") console.error("[ai] direct failed:", message); + } + return localAi(req); +}); +var testAiConnection_createServerFn_handler = createServerRpc({ + id: "5e6a13ce7e871cac8b1efc1cf5ccb213d79a60710661cd7012f69f2c7ccb6982", + name: "testAiConnection", + filename: "src/lib/ai-server.ts" +}, (opts) => testAiConnection.__executeServer(opts)); +var testAiConnection = createServerFn({ method: "POST" }).validator((input) => ({ clientSettings: validateSettings(input?.clientSettings) })).handler(testAiConnection_createServerFn_handler, async ({ data }) => { + const settings = data.clientSettings; + if (!settings) return { + ok: false, + message: "No settings provided" + }; + if (settings.backend === "local" || !settings.enabled) return { + ok: true, + message: "Local demo mode (no remote model)", + mode: "local" + }; + if (settings.backend === "claude-cli" || settings.backend === "codex-cli" || settings.backend === "grok-cli") { + const { listCliBackends } = await import("./cli-backends-BkZaX-Hk.mjs").then((n) => n.t); + const hit = (await listCliBackends()).find((b) => b.id === settings.backend); + if (hit?.available) return { + ok: true, + message: `${hit.label} found on PATH (${hit.binary})`, + mode: settings.backend + }; + return { + ok: false, + message: `${settings.backend} not found on PATH. Install and authenticate the CLI.`, + mode: settings.backend + }; + } + try { + if (settings.backend === "deepagents") { + const { probeDeepAgent } = await import("./deep-agent-CPCjT_2e.mjs"); + return { + ...await probeDeepAgent(settings), + mode: "deepagents" + }; + } + const { model, provider, modelName } = await resolveChatModel(settings); + await model.invoke([{ + role: "user", + content: "Say ok" + }]); + return { + ok: true, + message: `Connected to ${provider} · ${modelName}`, + model: `${provider}:${modelName}`, + mode: "direct" + }; + } catch (err) { + return { + ok: false, + message: err instanceof Error ? err.message : String(err), + mode: settings.backend + }; + } +}); +var testMcpConnection_createServerFn_handler = createServerRpc({ + id: "1e62b13d94b613cf423e7774bb51046a7dfc3005d0164d46cbd5f39fd41e65ae", + name: "testMcpConnection", + filename: "src/lib/ai-server.ts" +}, (opts) => testMcpConnection.__executeServer(opts)); +var testMcpConnection = createServerFn({ method: "POST" }).validator((input) => { + const server = input?.server; + if (!server || typeof server !== "object") throw new Error("Missing server"); + return { server: validateMcpServer(server) }; +}).handler(testMcpConnection_createServerFn_handler, async ({ data }) => { + const { testMcpServer } = await import("./mcp-PdRpzr2V.mjs"); + return testMcpServer(data.server); +}); +var getAiStatus_createServerFn_handler = createServerRpc({ + id: "5252add61246cf72a4fa382b4734734c4e8ea74302302ba378f1ecb54d53868d", + name: "getAiStatus", + filename: "src/lib/ai-server.ts" +}, (opts) => getAiStatus.__executeServer(opts)); +var getAiStatus = createServerFn({ method: "GET" }).handler(getAiStatus_createServerFn_handler, async () => { + const cfg = getAiConfig(); + const { listCliBackends } = await import("./cli-backends-BkZaX-Hk.mjs").then((n) => n.t); + const clis = await listCliBackends(); + return { + configured: cfg.configured, + backend: cfg.backend, + effective: cfg.effective, + model: cfg.model, + skills: [...WORKSPACE_SKILLS], + recursionLimit: cfg.recursionLimit, + envHasXai: Boolean(process.env.XAI_API_KEY?.trim()), + envHasAnthropic: Boolean(process.env.ANTHROPIC_API_KEY?.trim()), + envHasOpenai: Boolean(process.env.OPENAI_API_KEY?.trim()), + clis + }; +}); +var listAiCliBackends_createServerFn_handler = createServerRpc({ + id: "9bf431d4df4d57d04f011720753080a98c88face5f4f24058da2b17f8da151b8", + name: "listAiCliBackends", + filename: "src/lib/ai-server.ts" +}, (opts) => listAiCliBackends.__executeServer(opts)); +var listAiCliBackends = createServerFn({ method: "GET" }).handler(listAiCliBackends_createServerFn_handler, async () => { + const { listCliBackends } = await import("./cli-backends-BkZaX-Hk.mjs").then((n) => n.t); + return listCliBackends(); +}); +var describeAiSettings_createServerFn_handler = createServerRpc({ + id: "12c220cad66e7d4a3abab6da0b2bab6053a48aee4b6a0cde9d321705b501bd69", + name: "describeAiSettings", + filename: "src/lib/ai-server.ts" +}, (opts) => describeAiSettings.__executeServer(opts)); +var describeAiSettings = createServerFn({ method: "POST" }).validator((input) => ({ clientSettings: validateSettings(input?.clientSettings) })).handler(describeAiSettings_createServerFn_handler, async ({ data }) => { + if (!data.clientSettings) return null; + return publicAiSettings(data.clientSettings); +}); +//#endregion +export { describeAiSettings_createServerFn_handler, getAiStatus_createServerFn_handler, listAiCliBackends_createServerFn_handler, runAi_createServerFn_handler, testAiConnection_createServerFn_handler, testMcpConnection_createServerFn_handler }; diff --git a/.vercel/output/functions/__server.func/_ssr/ai-server-BiqlgRjO.mjs b/.vercel/output/functions/__server.func/_ssr/ai-server-BiqlgRjO.mjs deleted file mode 100644 index b51b58f..0000000 --- a/.vercel/output/functions/__server.func/_ssr/ai-server-BiqlgRjO.mjs +++ /dev/null @@ -1,313 +0,0 @@ -import { i as createServerFn } from "./ssr.mjs"; -import { t as createServerRpc } from "./createServerRpc-CcvdN_gc.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/ai-server-BiqlgRjO.js -function validateRequest(input) { - const data = input; - if (!data || typeof data !== "object") throw new Error("Invalid AI request"); - const action = data.action; - if (![ - "edit_block", - "summarize", - "action_items", - "table", - "outline", - "mermaid", - "custom" - ].includes(action)) throw new Error("Invalid AI action"); - return { - action, - instruction: typeof data.instruction === "string" ? data.instruction.slice(0, 4e3) : "", - blockText: typeof data.blockText === "string" ? data.blockText.slice(0, 8e3) : "", - blockType: data.blockType, - pageTitle: typeof data.pageTitle === "string" ? data.pageTitle.slice(0, 500) : "", - pageText: typeof data.pageText === "string" ? data.pageText.slice(0, 2e4) : "" - }; -} -function buildSystemPrompt(action) { - const base = "You help edit a Notion-style notes workspace. Be concise, high-signal, and practical. Never use emoji unless the user asks. Return only the content requested — no preamble."; - switch (action) { - case "edit_block": return `${base} Rewrite the given block text per the instruction. Return plain text only (no quotes around the whole answer).`; - case "summarize": return `${base} Summarize the page. Return JSON: {"blocks":[{"type":"heading2","content":"..."},{"type":"paragraph","content":"..."},{"type":"bullet","content":"..."}]} using types paragraph|heading1|heading2|heading3|bullet|numbered|todo|quote|callout|code|mermaid.`; - case "action_items": return `${base} Extract action items as todos. Return JSON: {"blocks":[{"type":"heading2","content":"Action items"},{"type":"todo","content":"..."}]} only.`; - case "table": return `${base} Create a markdown table from the page. Return JSON: {"blocks":[{"type":"heading2","content":"..."},{"type":"code","content":"| Col | ... |\\n|---|---|\\n| ... |"}]} — put the table in a code block.`; - case "outline": return `${base} Create a hierarchical outline. Return JSON: {"blocks":[{"type":"heading2","content":"Outline"},{"type":"bullet","content":"..."},{"type":"bullet","content":"..."}]} .`; - case "mermaid": return `${base} Create a Mermaid diagram for the page. Return JSON: {"blocks":[{"type":"heading2","content":"Diagram"},{"type":"mermaid","content":"flowchart TD\\n A-->B"}]} . Valid mermaid only in content.`; - case "custom": return `${base} Follow the user instruction using the page context. Prefer JSON {"blocks":[...]} when creating multiple blocks; otherwise plain text in {"text":"..."}. Allowed block types: paragraph,heading1,heading2,heading3,bullet,numbered,todo,quote,callout,code,mermaid.`; - default: return base; - } -} -function buildUserPrompt(req) { - const parts = []; - if (req.pageTitle) parts.push(`Page title: ${req.pageTitle}`); - if (req.pageText) parts.push(`Page content:\n${req.pageText}`); - if (req.blockText) parts.push(`Block (${req.blockType ?? "text"}):\n${req.blockText}`); - if (req.instruction) parts.push(`Instruction:\n${req.instruction}`); - if (req.action === "edit_block" && !req.instruction) parts.push("Instruction: Improve clarity and fix grammar while preserving meaning."); - return parts.join("\n\n") || "Empty page."; -} -async function callXai(system, user) { - const apiKey = process.env.XAI_API_KEY?.trim(); - if (!apiKey) throw new Error("NO_KEY"); - const model = process.env.XAI_MODEL?.trim() || "grok-4.5"; - const res = await fetch("https://api.x.ai/v1/chat/completions", { - method: "POST", - headers: { - "content-type": "application/json", - authorization: `Bearer ${apiKey}` - }, - body: JSON.stringify({ - model, - temperature: .4, - messages: [{ - role: "system", - content: system - }, { - role: "user", - content: user - }] - }) - }); - if (!res.ok) { - const errText = await res.text().catch(() => ""); - throw new Error(`xAI error ${res.status}: ${errText.slice(0, 200)}`); - } - const text = (await res.json()).choices?.[0]?.message?.content?.trim() ?? ""; - if (!text) throw new Error("Empty model response"); - return { - text, - model - }; -} -function parseModelPayload(raw, action) { - const candidate = (raw.match(/```(?:json)?\s*([\s\S]*?)```/)?.[1] ?? raw).trim(); - try { - const parsed = JSON.parse(candidate); - if (parsed.blocks && Array.isArray(parsed.blocks)) return { - text: parsed.text ?? "", - blocks: parsed.blocks.filter((b) => b && typeof b.content === "string").map((b) => ({ - type: b.type || "paragraph", - content: String(b.content) - })), - provider: "xai" - }; - if (typeof parsed.text === "string") return { - text: parsed.text, - provider: "xai" - }; - } catch {} - if (action === "edit_block" || action === "custom") return { - text: raw.replace(/^["']|["']$/g, "").trim(), - provider: "xai" - }; - return { - text: raw, - blocks: [{ - type: "paragraph", - content: raw - }], - provider: "xai" - }; -} -/** Local heuristic fallback so the preview is demoable without XAI_API_KEY. */ -function localAi(req) { - const page = (req.pageText || "").trim(); - const title = req.pageTitle || "Untitled"; - const lines = page.split("\n").map((l) => l.replace(/^#+\s*/, "").replace(/^[-*•]\s*/, "").replace(/^\d+\.\s*/, "").trim()).filter(Boolean); - const unique = [...new Set(lines)].slice(0, 24); - if (req.action === "edit_block") { - let text = (req.blockText || "").trim(); - const instruction = (req.instruction || "").toLowerCase(); - if (!text) text = "Add a clear note here."; - if (instruction.includes("short") || instruction.includes("concise")) { - text = text.split(/[.!?]/).slice(0, 2).join(". ").trim(); - if (text && !/[.!?]$/.test(text)) text += "."; - } else if (instruction.includes("long") || instruction.includes("expand")) text = `${text} In practice, this means spelling out the goal, the constraints, and the next concrete step so anyone can pick it up cold.`; - else if (instruction.includes("professional") || instruction.includes("formal")) { - text = text.replace(/\b(gonna|wanna|kinda|gotta)\b/gi, (m) => { - return { - gonna: "going to", - wanna: "want to", - kinda: "somewhat", - gotta: "need to" - }[m.toLowerCase()] ?? m; - }); - text = text.charAt(0).toUpperCase() + text.slice(1); - } else if (instruction.includes("fix") || instruction.includes("grammar")) { - text = text.replace(/\s+/g, " ").replace(/\si\s/g, " I ").replace(/(^\w)/, (c) => c.toUpperCase()); - if (text && !/[.!?]$/.test(text)) text += "."; - } else if (instruction) text = `${text}\n\n(${instruction.replace(/\.$/, "")} — applied locally; connect XAI_API_KEY for full model rewrites.)`; - else { - text = text.replace(/\s+/g, " ").trim(); - if (text && !/[.!?]$/.test(text)) text += "."; - } - return { - text, - provider: "local" - }; - } - if (req.action === "summarize") { - const bullets = unique.slice(0, 5); - return { - text: "", - provider: "local", - blocks: [ - { - type: "heading2", - content: `Summary — ${title}` - }, - { - type: "paragraph", - content: bullets.length > 0 ? `This page covers ${bullets.length} main points: ${bullets.slice(0, 3).map((b) => b.replace(/\.$/, "")).join("; ")}.` : "This page is still light — add notes, then run AI summary again." - }, - ...bullets.map((b) => ({ - type: "bullet", - content: b.slice(0, 200) - })) - ] - }; - } - if (req.action === "action_items") { - const todos = unique.filter((l) => /todo|need|should|must|fix|add|ship|write|create|update|check/i.test(l) || l.length < 80).slice(0, 6); - const items = todos.length ? todos : unique.slice(0, 4); - return { - text: "", - provider: "local", - blocks: [{ - type: "heading2", - content: "Action items" - }, ...items.length ? items.map((c) => ({ - type: "todo", - content: c.slice(0, 160) - })) : [{ - type: "todo", - content: "Capture next steps on this page" - }]] - }; - } - if (req.action === "table") return { - text: "", - provider: "local", - blocks: [{ - type: "heading2", - content: "Table" - }, { - type: "code", - content: [ - "| Topic | Note |", - "| --- | --- |", - ...unique.slice(0, 6).map((r, i) => `| ${i + 1}. ${r.slice(0, 40).replace(/\|/g, "/")} | From page |`) - ].join("\n") - }] - }; - if (req.action === "outline") return { - text: "", - provider: "local", - blocks: [ - { - type: "heading2", - content: "Outline" - }, - { - type: "bullet", - content: title - }, - ...unique.slice(0, 8).map((c) => ({ - type: "bullet", - content: c.slice(0, 120) - })) - ] - }; - if (req.action === "mermaid") { - const nodes = unique.slice(0, 5).map((l, i) => { - return { - id: String.fromCharCode(65 + i), - label: l.slice(0, 28).replace(/"/g, "'") - }; - }); - return { - text: "", - provider: "local", - blocks: [{ - type: "heading2", - content: "Diagram" - }, { - type: "mermaid", - content: (nodes.length >= 2 ? [ - "flowchart TD", - ...nodes.map((n) => ` ${n.id}["${n.label}"]`), - ...nodes.slice(0, -1).map((n, i) => ` ${n.id} --> ${nodes[i + 1].id}`) - ] : [ - "flowchart TD", - ` A["${title.slice(0, 28)}"]`, - " B[\"Add more notes\"]", - " A --> B" - ]).join("\n") - }] - }; - } - return { - text: "", - provider: "local", - blocks: [ - { - type: "heading2", - content: "AI response" - }, - { - type: "paragraph", - content: `Request: ${(req.instruction || "Help with this page").trim()}` - }, - { - type: "callout", - content: unique.length > 0 ? `Based on this page (${unique.length} lines). Connect an XAI_API_KEY for full Grok responses; local mode drafted this structure from your notes.` : "Add page content, then run again — or connect XAI_API_KEY for full Grok responses." - }, - ...unique.slice(0, 4).map((c) => ({ - type: "bullet", - content: c.slice(0, 160) - })) - ] - }; -} -var runAi_createServerFn_handler = createServerRpc({ - id: "76d08ea8f0b0103fcaf7055c8b138a9579e4124d0d2f62a0686a1011273cd47a", - name: "runAi", - filename: "src/lib/ai-server.ts" -}, (opts) => runAi.__executeServer(opts)); -var runAi = createServerFn({ method: "POST" }).validator((input) => validateRequest(input)).handler(runAi_createServerFn_handler, async ({ data }) => { - const system = buildSystemPrompt(data.action); - const user = buildUserPrompt(data); - try { - const { text, model } = await callXai(system, user); - return { - ...parseModelPayload(text, data.action), - provider: "xai", - model - }; - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - if (message === "NO_KEY" || message.startsWith("xAI error") || message.includes("fetch")) { - const local = localAi(data); - if (message !== "NO_KEY") { - if (local.blocks?.[0]) local.blocks = [{ - type: "callout", - content: `Used local AI fallback (${message.slice(0, 80)}). Set XAI_API_KEY for Grok.` - }, ...local.blocks]; - } - return local; - } - throw err; - } -}); -var getAiStatus_createServerFn_handler = createServerRpc({ - id: "5252add61246cf72a4fa382b4734734c4e8ea74302302ba378f1ecb54d53868d", - name: "getAiStatus", - filename: "src/lib/ai-server.ts" -}, (opts) => getAiStatus.__executeServer(opts)); -var getAiStatus = createServerFn({ method: "GET" }).handler(getAiStatus_createServerFn_handler, async () => { - return { - configured: Boolean(process.env.XAI_API_KEY?.trim()), - model: process.env.XAI_MODEL?.trim() || "grok-4.5" - }; -}); -//#endregion -export { getAiStatus_createServerFn_handler, runAi_createServerFn_handler }; diff --git a/.vercel/output/functions/__server.func/_ssr/cli-backends-BkZaX-Hk.mjs b/.vercel/output/functions/__server.func/_ssr/cli-backends-BkZaX-Hk.mjs new file mode 100644 index 0000000..3a98c8a --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/cli-backends-BkZaX-Hk.mjs @@ -0,0 +1,419 @@ +import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs"; +import { spawn } from "node:child_process"; +import { access } from "node:fs/promises"; +import { constants } from "node:fs"; +//#region node_modules/.nitro/vite/services/ssr/assets/cli-backends-BkZaX-Hk.js +function buildSystemPrompt(action) { + const base = "You help edit a Notion-style notes workspace. Be concise, high-signal, and practical. Never use emoji unless the user asks. Return only the content requested — no preamble."; + switch (action) { + case "edit_block": return `${base} Rewrite the given block text per the instruction. Return plain text only (no quotes around the whole answer).`; + case "summarize": return `${base} Summarize the page. Return JSON: {"blocks":[{"type":"heading2","content":"..."},{"type":"paragraph","content":"..."},{"type":"bullet","content":"..."}]} using types paragraph|heading1|heading2|heading3|bullet|numbered|todo|quote|callout|code|mermaid.`; + case "action_items": return `${base} Extract action items as todos. Return JSON: {"blocks":[{"type":"heading2","content":"Action items"},{"type":"todo","content":"..."}]} only.`; + case "table": return `${base} Create a markdown table from the page. Return JSON: {"blocks":[{"type":"heading2","content":"..."},{"type":"code","content":"| Col | ... |\\n|---|---|\\n| ... |"}]} — put the table in a code block.`; + case "outline": return `${base} Create a hierarchical outline. Return JSON: {"blocks":[{"type":"heading2","content":"Outline"},{"type":"bullet","content":"..."},{"type":"bullet","content":"..."}]} .`; + case "mermaid": return `${base} Create a Mermaid diagram for the page. Return JSON: {"blocks":[{"type":"heading2","content":"Diagram"},{"type":"mermaid","content":"flowchart TD\\n A-->B"}]} . Valid mermaid only in content.`; + case "custom": return `${base} Follow the user instruction using the page context. Prefer JSON {"blocks":[...]} when creating multiple blocks; otherwise plain text in {"text":"..."}. Allowed block types: paragraph,heading1,heading2,heading3,bullet,numbered,todo,quote,callout,code,mermaid.`; + default: return base; + } +} +function buildUserPrompt(req) { + const parts = []; + if (req.pageTitle) parts.push(`Page title: ${req.pageTitle}`); + if (req.pageText) parts.push(`Page content:\n${req.pageText}`); + if (req.blockText) parts.push(`Block (${req.blockType ?? "text"}):\n${req.blockText}`); + if (req.instruction) parts.push(`Instruction:\n${req.instruction}`); + if (req.action === "edit_block" && !req.instruction) parts.push("Instruction: Improve clarity and fix grammar while preserving meaning."); + return parts.join("\n\n") || "Empty page."; +} +function parseModelPayload(raw, action, provider = "local") { + const candidate = (raw.match(/```(?:json)?\s*([\s\S]*?)```/)?.[1] ?? raw).trim(); + try { + const parsed = JSON.parse(candidate); + if (parsed.blocks && Array.isArray(parsed.blocks)) return { + text: parsed.text ?? "", + blocks: parsed.blocks.filter((b) => b && typeof b.content === "string").map((b) => ({ + type: b.type || "paragraph", + content: String(b.content) + })), + provider + }; + if (typeof parsed.text === "string") return { + text: parsed.text, + provider + }; + } catch {} + if (action === "edit_block" || action === "custom") return { + text: raw.replace(/^["']|["']$/g, "").trim(), + provider + }; + return { + text: raw, + blocks: [{ + type: "paragraph", + content: raw + }], + provider + }; +} +function composeCliPrompt(system, user) { + return `${system}\n\n---\n\n${user}`; +} +/** +* Coding-agent CLI backends for workspace AI generation. +* Claude Code · Codex · Grok Build — with streaming stdout when available. +*/ +var cli_backends_exports = /* @__PURE__ */ __exportAll({ + isCliBackend: () => isCliBackend, + listCliBackends: () => listCliBackends, + runCliAgent: () => runCliAgent, + streamCliAgent: () => streamCliAgent +}); +var BIN = { + "claude-cli": "claude", + "codex-cli": "codex", + "grok-cli": "grok" +}; +async function which(bin) { + if (bin.includes("/")) try { + await access(bin, constants.X_OK); + return true; + } catch { + return false; + } + return new Promise((resolve) => { + const child = spawn("which", [bin], { stdio: "ignore" }); + child.on("close", (code) => resolve(code === 0)); + child.on("error", () => resolve(false)); + }); +} +async function listCliBackends() { + const defs = [ + { + id: "claude-cli", + label: "Claude Code CLI", + binary: "claude", + supportsStream: true, + notes: "Uses `claude -p` with stream-json when available.", + example: "claude -p \"…\" --output-format stream-json" + }, + { + id: "codex-cli", + label: "Codex CLI", + binary: "codex", + supportsStream: true, + notes: "Uses `codex exec` (streams stdout).", + example: "codex exec \"…\"" + }, + { + id: "grok-cli", + label: "Grok CLI / Grok Build", + binary: "grok", + supportsStream: true, + notes: "Prefers `grok chat --stream`; falls back to plain prompt flags.", + example: "grok chat --stream \"…\"" + } + ]; + const out = []; + for (const d of defs) out.push({ + ...d, + available: await which(d.binary) + }); + return out; +} +function isCliBackend(id) { + return id === "claude-cli" || id === "codex-cli" || id === "grok-cli"; +} +function buildArgs(backend, prompt, stream) { + const bin = BIN[backend]; + if (backend === "claude-cli") { + if (stream) return { + bin, + args: [ + "-p", + prompt, + "--output-format", + "stream-json", + "--verbose" + ], + mode: "stream-json" + }; + return { + bin, + args: [ + "-p", + prompt, + "--output-format", + "text" + ], + mode: "text" + }; + } + if (backend === "codex-cli") return { + bin, + args: [ + "exec", + "--skip-git-repo-check", + prompt + ], + mode: "text" + }; + if (stream) return { + bin, + args: [ + "chat", + "--stream", + prompt + ], + mode: "text" + }; + return { + bin, + args: ["chat", prompt], + mode: "text" + }; +} +function fallbackArgs(backend, prompt) { + const bin = BIN[backend]; + if (backend === "claude-cli") return { + bin, + args: ["-p", prompt], + mode: "text" + }; + if (backend === "codex-cli") return { + bin, + args: ["exec", prompt], + mode: "text" + }; + if (backend === "grok-cli") return { + bin, + args: ["-p", prompt], + mode: "text" + }; + return null; +} +function extractStreamJsonToken(line) { + const trimmed = line.trim(); + if (!trimmed.startsWith("{")) return ""; + try { + const obj = JSON.parse(trimmed); + if (obj.type === "content_block_delta") { + const delta = obj.delta; + if (delta?.text) return delta.text; + } + if (obj.type === "assistant" && typeof obj.message === "object" && obj.message) { + const msg = obj.message; + if (Array.isArray(msg.content)) return msg.content.map((c) => c.text ?? "").join(""); + } + if (typeof obj.text === "string") return obj.text; + if (typeof obj.content === "string") return obj.content; + if (typeof obj.delta === "string") return obj.delta; + if (obj.type === "item.completed" || obj.type === "message") { + const item = obj.item; + if (item?.text) return item.text; + if (item?.content) return item.content; + } + } catch { + return ""; + } + return ""; +} +function runProcessToQueue(bin, args, mode, push, timeoutMs = 18e4) { + let child; + try { + child = spawn(bin, args, { + env: { + ...process.env, + FORCE_COLOR: "0", + NO_COLOR: "1" + }, + stdio: [ + "ignore", + "pipe", + "pipe" + ] + }); + } catch (err) { + push({ + type: "__err__", + error: err instanceof Error ? err : new Error(String(err)) + }); + push({ type: "__end__" }); + return; + } + let stdout = ""; + let stderr = ""; + let lineBuf = ""; + let assembled = ""; + let sawStreamTokens = false; + let settled = false; + const settle = (item) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (item) push(item); + push({ type: "__end__" }); + }; + const timer = setTimeout(() => { + child.kill("SIGTERM"); + settle({ + type: "__err__", + error: /* @__PURE__ */ new Error(`${bin} timed out after ${timeoutMs}ms`) + }); + }, timeoutMs); + child.stdout?.on("data", (chunk) => { + const s = String(chunk); + stdout += s; + if (mode === "stream-json") { + lineBuf += s; + const parts = lineBuf.split("\n"); + lineBuf = parts.pop() ?? ""; + for (const line of parts) { + const token = extractStreamJsonToken(line); + if (token) { + sawStreamTokens = true; + assembled += token; + push({ + type: "token", + text: token + }); + } + } + } else push({ + type: "token", + text: s + }); + }); + child.stderr?.on("data", (chunk) => { + stderr += String(chunk); + }); + child.on("error", (err) => { + settle({ + type: "__err__", + error: err + }); + }); + child.on("close", (code) => { + if (mode === "stream-json" && lineBuf.trim()) { + const token = extractStreamJsonToken(lineBuf); + if (token) { + sawStreamTokens = true; + assembled += token; + push({ + type: "token", + text: token + }); + } + } + const finalText = (sawStreamTokens ? assembled : stdout).trim(); + if (code !== 0 && !finalText) { + settle({ + type: "__err__", + error: new Error(stderr.trim() || `${bin} exited ${code}`) + }); + return; + } + push({ + type: "done", + text: finalText || stdout.trim() + }); + settle(); + }); +} +async function* drainQueue(start) { + const queue = []; + let wake = null; + const push = (item) => { + queue.push(item); + wake?.(); + }; + start(push); + let finished = false; + while (!finished) { + if (queue.length === 0) { + await new Promise((r) => { + wake = r; + }); + wake = null; + } + while (queue.length) { + const item = queue.shift(); + if (item.type === "__end__") { + finished = true; + break; + } + if (item.type === "__err__") { + yield { + type: "error", + message: item.error.message + }; + finished = true; + break; + } + yield item; + } + } +} +async function* streamCliAgent(backend, req) { + if (!await which(BIN[backend])) { + yield { + type: "error", + message: `${BIN[backend]} not found on PATH. Install the CLI and authenticate (claude login / codex login / grok login).` + }; + return; + } + const prompt = composeCliPrompt(buildSystemPrompt(req.action), buildUserPrompt(req)); + const primary = buildArgs(backend, prompt, true); + yield { + type: "status", + message: `Starting ${backend}…` + }; + yield { + type: "status", + message: `$ ${primary.bin} ${primary.args[0] ?? ""} …` + }; + let hadError = false; + let hadDone = false; + for await (const chunk of drainQueue((push) => runProcessToQueue(primary.bin, primary.args, primary.mode, push))) { + if (chunk.type === "error") { + hadError = true; + const fb = fallbackArgs(backend, prompt); + if (!fb) { + yield chunk; + return; + } + yield { + type: "status", + message: `Primary failed (${chunk.message}). Retrying fallback…` + }; + for await (const c2 of drainQueue((push) => runProcessToQueue(fb.bin, fb.args, fb.mode, push))) { + if (c2.type === "done") hadDone = true; + yield c2; + } + return; + } + if (chunk.type === "done") hadDone = true; + yield chunk; + } + if (!hadDone && !hadError) yield { + type: "error", + message: "CLI produced no output" + }; +} +async function runCliAgent(backend, req) { + let full = ""; + let error = null; + for await (const chunk of streamCliAgent(backend, req)) { + if (chunk.type === "token" && chunk.text) full += chunk.text; + if (chunk.type === "done" && chunk.text) full = chunk.text; + if (chunk.type === "error") error = chunk.message ?? "CLI error"; + } + if (error && !full.trim()) throw new Error(error); + const provider = backend; + return { + ...parseModelPayload(full, req.action, provider), + model: backend, + provider + }; +} +//#endregion +export { buildUserPrompt as a, buildSystemPrompt as i, isCliBackend as n, parseModelPayload as o, streamCliAgent as r, cli_backends_exports as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/client-C9atugA7.mjs b/.vercel/output/functions/__server.func/_ssr/client-Bm2YFrbd.mjs similarity index 99% rename from .vercel/output/functions/__server.func/_ssr/client-C9atugA7.mjs rename to .vercel/output/functions/__server.func/_ssr/client-Bm2YFrbd.mjs index 5395856..0079f5a 100644 --- a/.vercel/output/functions/__server.func/_ssr/client-C9atugA7.mjs +++ b/.vercel/output/functions/__server.func/_ssr/client-Bm2YFrbd.mjs @@ -1,11 +1,11 @@ import { o as __toESM } from "../_runtime.mjs"; +import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs"; import { u as require_react } from "../_libs/@floating-ui/react-dom+[...].mjs"; -import { n as __exportAll } from "./ssr.mjs"; -import { Kt as capitalizeFirstLetter, Xt as isSafeUrlScheme, Yt as createFetch, qt as toKebabCase } from "../_libs/@better-auth/core+[...].mjs"; +import { An as createFetch, Dn as capitalizeFirstLetter, On as toKebabCase, jn as isSafeUrlScheme } from "../_libs/@better-auth/core+[...].mjs"; import { n as PACKAGE_VERSION, r as getBaseURL, t as GENERIC_OAUTH_ERROR_CODES } from "./url-CBX8wGYU.mjs"; import { i as atom, n as onMount, r as onSet, t as listenKeys } from "../_libs/nanostores.mjs"; import { n as defu } from "../_libs/defu.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/client-C9atugA7.js +//#region node_modules/.nitro/vite/services/ssr/assets/client-Bm2YFrbd.js var import_react = /* @__PURE__ */ __toESM(require_react()); var genericOAuthClient = () => { return { diff --git a/.vercel/output/functions/__server.func/_ssr/createServerRpc-CcvdN_gc.mjs b/.vercel/output/functions/__server.func/_ssr/createServerRpc-CcvdN_gc.mjs index b6921f6..4897c29 100644 --- a/.vercel/output/functions/__server.func/_ssr/createServerRpc-CcvdN_gc.mjs +++ b/.vercel/output/functions/__server.func/_ssr/createServerRpc-CcvdN_gc.mjs @@ -1,4 +1,4 @@ -import { t as TSS_SERVER_FUNCTION } from "./ssr.mjs"; +import { i as TSS_SERVER_FUNCTION } from "./ssr.mjs"; //#region node_modules/.nitro/vite/services/ssr/assets/createServerRpc-CcvdN_gc.js var createServerRpc = (serverFnMeta, splitImportFn) => { const url = "/_serverFn/" + serverFnMeta.id; diff --git a/.vercel/output/functions/__server.func/_ssr/db-BCrmCYup.mjs b/.vercel/output/functions/__server.func/_ssr/db-BLv9nwdP.mjs similarity index 86% rename from .vercel/output/functions/__server.func/_ssr/db-BCrmCYup.mjs rename to .vercel/output/functions/__server.func/_ssr/db-BLv9nwdP.mjs index a9de39c..c2cd2cb 100644 --- a/.vercel/output/functions/__server.func/_ssr/db-BCrmCYup.mjs +++ b/.vercel/output/functions/__server.func/_ssr/db-BLv9nwdP.mjs @@ -1,6 +1,7 @@ -//#region node_modules/.nitro/vite/services/ssr/assets/db-BCrmCYup.js +//#region node_modules/.nitro/vite/services/ssr/assets/db-BLv9nwdP.js var _0001_auth_default = "-- Better Auth schema (identity + sessions for \"Sign in with Grok\").\n--\n-- Generated by the Better Auth CLI for its Postgres adapter — DO NOT EDIT by\n-- hand. `@/lib/auth/server` runs Better Auth against these tables when\n-- DATABASE_URL is set. The columns are camelCase and MUST stay double-quoted so\n-- Postgres preserves the case Better Auth queries by.\n--\n-- Migrations in this folder are the single source of truth for your schema. They\n-- apply to Neon during the Vercel build (`npm run build`) and to the local\n-- PGLite fallback automatically on startup, so dev matches production. Applied\n-- files are recorded by name in `_migrations` and NEVER run again.\n--\n-- Put YOUR app's schema in NEW ordered files (0002_*.sql, 0003_*.sql, …), never\n-- in this one. For app tables, prefer snake_case and give per-user tables a\n-- `user_id TEXT NOT NULL` column (TEXT, not UUID — the preview dev user id is\n-- the string 'dev-user'), then scope every query to the authenticated user\n-- server-side (see the `neon` + `auth` skills and src/lib/auth/verify.server.ts).\n\ncreate table if not exists \"user\" (\n \"id\" text not null primary key,\n \"name\" text not null,\n \"email\" text not null unique,\n \"emailVerified\" boolean not null,\n \"image\" text,\n \"createdAt\" timestamptz default CURRENT_TIMESTAMP not null,\n \"updatedAt\" timestamptz default CURRENT_TIMESTAMP not null\n);\n\ncreate table if not exists \"session\" (\n \"id\" text not null primary key,\n \"expiresAt\" timestamptz not null,\n \"token\" text not null unique,\n \"createdAt\" timestamptz default CURRENT_TIMESTAMP not null,\n \"updatedAt\" timestamptz not null,\n \"ipAddress\" text,\n \"userAgent\" text,\n \"userId\" text not null references \"user\" (\"id\") on delete cascade\n);\n\ncreate table if not exists \"account\" (\n \"id\" text not null primary key,\n \"accountId\" text not null,\n \"providerId\" text not null,\n \"userId\" text not null references \"user\" (\"id\") on delete cascade,\n \"accessToken\" text,\n \"refreshToken\" text,\n \"idToken\" text,\n \"accessTokenExpiresAt\" timestamptz,\n \"refreshTokenExpiresAt\" timestamptz,\n \"scope\" text,\n \"password\" text,\n \"createdAt\" timestamptz default CURRENT_TIMESTAMP not null,\n \"updatedAt\" timestamptz not null\n);\n\ncreate table if not exists \"verification\" (\n \"id\" text not null primary key,\n \"identifier\" text not null,\n \"value\" text not null,\n \"expiresAt\" timestamptz not null,\n \"createdAt\" timestamptz default CURRENT_TIMESTAMP not null,\n \"updatedAt\" timestamptz default CURRENT_TIMESTAMP not null\n);\n\ncreate index if not exists \"session_userId_idx\" on \"session\" (\"userId\");\ncreate index if not exists \"account_userId_idx\" on \"account\" (\"userId\");\ncreate index if not exists \"verification_identifier_idx\" on \"verification\" (\"identifier\");\n"; var _0002_workspace_default = "-- Notion-clone workspace schema (per-user pages + settings).\n-- Scoped by user_id TEXT (Better Auth ids / preview 'dev-user').\n\ncreate table if not exists workspaces (\n user_id text primary key,\n name text not null default 'Workspace',\n theme text not null default 'light',\n active_page_id text,\n sidebar_open boolean not null default true,\n updated_at timestamptz not null default now()\n);\n\ncreate table if not exists pages (\n id text not null,\n user_id text not null,\n title text not null default '',\n icon text not null default '📄',\n cover text,\n parent_id text,\n favorite boolean not null default false,\n archived boolean not null default false,\n blocks jsonb not null default '[]'::jsonb,\n created_at timestamptz not null default now(),\n updated_at timestamptz not null default now(),\n primary key (user_id, id)\n);\n\ncreate index if not exists pages_user_id_idx on pages (user_id);\ncreate index if not exists pages_user_parent_idx on pages (user_id, parent_id);\n"; +var _0003_search_default = "-- Full-text search index for workspace pages.\n-- Keyword: to_tsvector / plainto_tsquery\n-- Similarity: pg_trgm when available (Neon); otherwise ts_rank + ILIKE fallback.\n\ncreate table if not exists page_search (\n user_id text not null,\n page_id text not null,\n title text not null default '',\n icon text not null default '📄',\n parent_id text,\n favorite boolean not null default false,\n archived boolean not null default false,\n content_text text not null default '',\n tsv tsvector,\n updated_at timestamptz not null default now(),\n primary key (user_id, page_id)\n);\n\ncreate index if not exists page_search_user_idx on page_search (user_id);\ncreate index if not exists page_search_tsv_idx on page_search using gin (tsv);\n\n-- Optional trigram indexes (Neon / full Postgres). Safe to skip on PGLite.\ndo $$\nbegin\n create extension if not exists pg_trgm;\nexception\n when others then\n raise notice 'pg_trgm not available — similarity falls back to rank + ILIKE';\nend $$;\n\ndo $$\nbegin\n create index if not exists page_search_title_trgm_idx\n on page_search using gin (title gin_trgm_ops);\n create index if not exists page_search_content_trgm_idx\n on page_search using gin (content_text gin_trgm_ops);\nexception\n when others then\n raise notice 'trigram indexes skipped';\nend $$;\n"; var rawDatabaseUrl = typeof process !== "undefined" ? process.env.DATABASE_URL : void 0; var databaseUrl = rawDatabaseUrl && rawDatabaseUrl.trim() ? rawDatabaseUrl : void 0; /** @@ -79,7 +80,8 @@ async function createPgliteSql() { const migrate = async () => { const migrations = /* #__PURE__ */ Object.assign({ "/migrations/0001_auth.sql": _0001_auth_default, - "/migrations/0002_workspace.sql": _0002_workspace_default + "/migrations/0002_workspace.sql": _0002_workspace_default, + "/migrations/0003_search.sql": _0003_search_default }); const doneRows = await pg.query("select name from _migrations"); const done = new Set(doneRows.rows.map((r) => r.name)); diff --git a/.vercel/output/functions/__server.func/_ssr/deep-agent-CPCjT_2e.mjs b/.vercel/output/functions/__server.func/_ssr/deep-agent-CPCjT_2e.mjs new file mode 100644 index 0000000..39165d7 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/deep-agent-CPCjT_2e.mjs @@ -0,0 +1,199 @@ +import { i as resolveChatModel, n as getAiConfig } from "./resolve-model-CV2sMs92.mjs"; +import { $t as string, Bt as array, It as _enum, Yt as object } from "../_libs/@better-auth/core+[...].mjs"; +import { loadMcpTools } from "./mcp-PdRpzr2V.mjs"; +import { n as createDeepAgent, r as toolStrategy, t as FilesystemBackend } from "../_libs/deepagents+[...].mjs"; +import path from "node:path"; +//#region node_modules/.nitro/vite/services/ssr/assets/deep-agent-CPCjT_2e.js +var blockTypeEnum = _enum([ + "paragraph", + "heading1", + "heading2", + "heading3", + "bullet", + "numbered", + "todo", + "quote", + "callout", + "code", + "mermaid" +]); +var agentResponseSchema = object({ + text: string().default("").describe("Plain replacement text for single-block edits; empty when only inserting blocks"), + blocks: array(object({ + type: blockTypeEnum, + content: string() + })).optional().describe("Blocks to insert under the AI block") +}); +function skillForAction(action) { + switch (action) { + case "summarize": return "summarize-page"; + case "edit_block": return "edit-block"; + case "action_items": return "action-items"; + case "table": return "table-from-notes"; + case "mermaid": return "mermaid-diagram"; + case "outline": return "custom-page-task"; + default: return "custom-page-task"; + } +} +function buildUserMessage(req, settings) { + const skill = skillForAction(req.action); + const parts = [!settings?.enabledSkills?.length || settings.enabledSkills.includes(skill) ? `Load and follow the skill: ${skill}` : `Skill ${skill} is disabled — still complete the action using general workspace rules.`, `Action: ${req.action}`]; + if (req.pageTitle) parts.push(`Page title: ${req.pageTitle}`); + if (req.pageText) parts.push(`Page content:\n${req.pageText}`); + if (req.blockText) { + parts.push(`Target block type: ${req.blockType ?? "paragraph"}`); + parts.push(`Target block text:\n${req.blockText}`); + } + if (req.instruction) parts.push(`Instruction:\n${req.instruction}`); + if (req.action === "outline") parts.push("Produce a hierarchical outline using heading2 + bullet blocks."); + parts.push("Return structured output with `text` and optional `blocks` per the schema."); + return parts.join("\n\n"); +} +function extractStructured(result) { + if (!result || typeof result !== "object") return null; + const r = result; + for (const key of ["structuredResponse", "structured_response"]) if (r[key] && typeof r[key] === "object") { + const parsed = agentResponseSchema.safeParse(r[key]); + if (parsed.success) return parsed.data; + } + const messages = r.messages; + if (Array.isArray(messages) && messages.length > 0) { + const last = messages[messages.length - 1]; + const content = last?.content ?? last?.kwargs?.content; + let text = ""; + if (typeof content === "string") text = content; + else if (Array.isArray(content)) text = content.map((c) => typeof c === "string" ? c : c && typeof c === "object" && "text" in c ? String(c.text) : "").join("\n"); + if (text) { + const candidate = (text.match(/```(?:json)?\s*([\s\S]*?)```/)?.[1] ?? text).trim(); + try { + const parsed = agentResponseSchema.safeParse(JSON.parse(candidate)); + if (parsed.success) return parsed.data; + } catch { + return { + text: candidate, + blocks: void 0 + }; + } + } + } + return null; +} +function fingerprint(settings, modelName, provider) { + return JSON.stringify({ + provider, + modelName, + baseUrl: settings?.baseUrl ?? "", + recursionLimit: settings?.recursionLimit, + temperature: settings?.temperature, + skills: settings?.enabledSkills ?? [], + mcp: (settings?.mcpServers ?? []).filter((m) => m.enabled).map((m) => ({ + n: m.name, + t: m.transport, + u: m.url, + c: m.command, + a: m.argsText + })) + }); +} +var cached = null; +async function getAgent(settings) { + const { model, provider, modelName } = await resolveChatModel(settings); + const key = fingerprint(settings, modelName, provider); + if (cached?.key === key) return { + agent: cached.agent, + provider, + modelName + }; + const cfg = getAiConfig(); + const rootDir = path.join(process.cwd(), cfg.deepAgentsRoot); + const { tools: mcpTools, errors: mcpErrors } = settings ? await loadMcpTools(settings) : { + tools: [], + errors: [] + }; + if (mcpErrors.length) console.warn("[ai] MCP load warnings:", mcpErrors.join("; ")); + const agent = createDeepAgent({ + model, + name: "workspace-deep-agent", + systemPrompt: "You are the workspace Deep Agent (LangChain). Use skills for specialized page tasks. You may call MCP tools when helpful for research or external context. Prefer structured output. Be concise.", + backend: new FilesystemBackend({ + rootDir, + virtualMode: true + }), + skills: [cfg.skillsPath], + memory: ["/AGENTS.md"], + tools: mcpTools, + responseFormat: toolStrategy(agentResponseSchema), + permissions: [{ + operations: ["read"], + paths: ["/skills/**", "/AGENTS.md"] + }, { + operations: ["write"], + paths: ["/**"], + mode: "deny" + }] + }); + cached = { + key, + agent + }; + return { + agent, + provider, + modelName + }; +} +async function runDeepAgent(req, settings) { + const { agent, provider, modelName } = await getAgent(settings); + const userMessage = buildUserMessage(req, settings); + const recursionLimit = Math.min(80, Math.max(8, settings?.recursionLimit || getAiConfig().recursionLimit || 40)); + const structured = extractStructured(await agent.invoke({ messages: [{ + role: "user", + content: userMessage + }] }, { recursionLimit })); + if (!structured) throw new Error("Deep Agent returned no structured output"); + const blocks = structured.blocks?.map((b) => ({ + type: b.type, + content: b.content + })); + return { + text: structured.text ?? "", + blocks, + provider: "deepagents", + model: `${provider}:${modelName}` + }; +} +/** Lightweight connectivity check */ +async function probeDeepAgent(settings) { + try { + const { model, provider, modelName } = await resolveChatModel(settings); + const res = await model.invoke([{ + role: "user", + content: "Reply with exactly: {\"ok\":true}" + }]); + typeof res.content === "string" ? res.content : Array.isArray(res.content) ? res.content.map((c) => typeof c === "string" ? c : "").join("") : String(res.content ?? ""); + let mcpTools = []; + if (settings) mcpTools = (await loadMcpTools(settings)).toolNames; + return { + ok: true, + message: `Connected to ${provider} · ${modelName}`, + model: `${provider}:${modelName}`, + mcpTools + }; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + if (message === "NO_KEY") return { + ok: false, + message: "Missing API key for this provider" + }; + if (message === "BASE_URL_REQUIRED") return { + ok: false, + message: "Base URL is required for this provider" + }; + return { + ok: false, + message + }; + } +} +//#endregion +export { probeDeepAgent, runDeepAgent }; diff --git a/.vercel/output/functions/__server.func/_ssr/use-current-user-Ct6wm9as.mjs b/.vercel/output/functions/__server.func/_ssr/input-CLjwzknR.mjs similarity index 82% rename from .vercel/output/functions/__server.func/_ssr/use-current-user-Ct6wm9as.mjs rename to .vercel/output/functions/__server.func/_ssr/input-CLjwzknR.mjs index f4115c0..86cfda0 100644 --- a/.vercel/output/functions/__server.func/_ssr/use-current-user-Ct6wm9as.mjs +++ b/.vercel/output/functions/__server.func/_ssr/input-CLjwzknR.mjs @@ -1,10 +1,10 @@ import { o as __toESM } from "../_runtime.mjs"; import { u as require_react } from "../_libs/@floating-ui/react-dom+[...].mjs"; import { c as require_jsx_runtime, r as Slot } from "../_libs/@radix-ui/react-collection+[...].mjs"; -import { t as authClient } from "./client-C9atugA7.mjs"; +import { t as authClient } from "./client-Bm2YFrbd.mjs"; import { t as cva } from "../_libs/class-variance-authority+clsx.mjs"; -import { t as cn } from "./utils-DkRSI2_g.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/use-current-user-Ct6wm9as.js +import { r as cn } from "./seed-CQXoc2iK.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/input-CLjwzknR.js var import_react = /* @__PURE__ */ __toESM(require_react()); var import_jsx_runtime = require_jsx_runtime(); var buttonVariants = cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[background-color,color,opacity,box-shadow,transform] duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:pointer-events-none disabled:opacity-50 active:scale-[0.98] [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", { @@ -85,5 +85,12 @@ function useCurrentUserState() { function useCurrentUser() { return useCurrentUserState().user; } +var Input = import_react.forwardRef(({ className, type, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + type, + className: cn("flex h-9 w-full rounded-md border border-border bg-background px-3 py-1 text-sm text-foreground shadow-none transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50", className), + ref, + ...props +})); +Input.displayName = "Input"; //#endregion -export { useCurrentUser as n, useCurrentUserState as r, Button as t }; +export { useCurrentUserState as i, Input as n, useCurrentUser as r, Button as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/isolation.server-CGNg1r0B.mjs b/.vercel/output/functions/__server.func/_ssr/isolation.server-CGNg1r0B.mjs index 6b55f54..85fbc67 100644 --- a/.vercel/output/functions/__server.func/_ssr/isolation.server-CGNg1r0B.mjs +++ b/.vercel/output/functions/__server.func/_ssr/isolation.server-CGNg1r0B.mjs @@ -1,4 +1,4 @@ -import { a as getRequest } from "./ssr.mjs"; +import { o as getRequest } from "./ssr.mjs"; //#region node_modules/.nitro/vite/services/ssr/assets/isolation.server-CGNg1r0B.js /** * Fetch-Metadata sibling isolation — **server-only** (`.server.ts` suffix). diff --git a/.vercel/output/functions/__server.func/_ssr/local-model-DJKwz5o1.mjs b/.vercel/output/functions/__server.func/_ssr/local-model-DJKwz5o1.mjs new file mode 100644 index 0000000..3a9b0d7 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/local-model-DJKwz5o1.mjs @@ -0,0 +1,59 @@ +//#region node_modules/.nitro/vite/services/ssr/assets/local-model-DJKwz5o1.js +/** +* Lightweight model call for harness roles using env keys. +* Avoids @/ path alias so CLI (tsx) and Vite both work. +*/ +async function runHarnessModel(opts) { + const xaiKey = process.env.XAI_API_KEY?.trim() || ""; + const anthropicKey = process.env.ANTHROPIC_API_KEY?.trim() || ""; + const openaiKey = process.env.OPENAI_API_KEY?.trim() || ""; + const xaiModel = process.env.XAI_MODEL?.trim() || "grok-4.5"; + if (!xaiKey && !anthropicKey && !openaiKey) throw new Error("NO_KEY"); + if (xaiKey) { + const { ChatXAI } = await import("../_libs/langchain__xai.mjs").then((n) => n.t); + return contentToText((await new ChatXAI({ + apiKey: xaiKey, + model: opts.model || xaiModel, + temperature: .3 + }).invoke([{ + role: "system", + content: opts.system + }, { + role: "user", + content: opts.user + }])).content); + } + if (anthropicKey) { + const { ChatAnthropic } = await import("../_libs/@langchain/anthropic+[...].mjs").then((n) => n.t); + return contentToText((await new ChatAnthropic({ + apiKey: anthropicKey, + model: opts.model || "claude-sonnet-4-6", + temperature: .3 + }).invoke([{ + role: "system", + content: opts.system + }, { + role: "user", + content: opts.user + }])).content); + } + const { ChatOpenAI } = await import("../_libs/langchain__openai+openai.mjs").then((n) => n.t); + return contentToText((await new ChatOpenAI({ + apiKey: openaiKey, + model: opts.model || "gpt-4.1", + temperature: .3 + }).invoke([{ + role: "system", + content: opts.system + }, { + role: "user", + content: opts.user + }])).content); +} +function contentToText(content) { + if (typeof content === "string") return content.trim(); + if (Array.isArray(content)) return content.map((c) => typeof c === "string" ? c : c.text ?? "").join("").trim(); + return String(content ?? "").trim(); +} +//#endregion +export { runHarnessModel }; diff --git a/.vercel/output/functions/__server.func/_ssr/login-Bi7a5wKY.mjs b/.vercel/output/functions/__server.func/_ssr/login-Bi7a5wKY.mjs deleted file mode 100644 index 5bc91d3..0000000 --- a/.vercel/output/functions/__server.func/_ssr/login-Bi7a5wKY.mjs +++ /dev/null @@ -1,56 +0,0 @@ -import { g as Navigate, h as Link } from "../_libs/@tanstack/react-router+[...].mjs"; -import { c as require_jsx_runtime } from "../_libs/@radix-ui/react-collection+[...].mjs"; -import { r as signIn } from "./client-C9atugA7.mjs"; -import { t as GROK_PROVIDERS } from "./server-B2xtU6TT.mjs"; -import { r as useCurrentUserState, t as Button } from "./use-current-user-Ct6wm9as.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/login-Bi7a5wKY.js -var import_jsx_runtime = require_jsx_runtime(); -function LoginPage() { - const { user, isPending } = useCurrentUserState(); - if (!isPending && user) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Navigate, { to: "/" }); - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("main", { - className: "grid min-h-dvh place-items-center bg-background px-6 text-foreground", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "w-full max-w-sm space-y-6", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "space-y-2 text-center", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "mx-auto flex size-12 items-center justify-center rounded-xl bg-foreground text-lg font-semibold text-background", - children: "W" - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h1", { - className: "text-2xl font-semibold tracking-tight", - children: "Sign in to Workspace" - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "text-sm text-muted-foreground", - children: "Your pages save to the cloud database when you're signed in. Guests keep a local copy in this browser only." - }) - ] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "space-y-2", - children: GROK_PROVIDERS.map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - variant: "outline", - className: "h-11 w-full justify-center", - onClick: () => void signIn(p.providerId, { callbackURL: "/" }), - children: ["Continue with ", p.label] - }, p.providerId)) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "text-center text-sm text-muted-foreground", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, { - to: "/", - className: "underline-offset-4 hover:underline", - children: "Continue as guest" - }) - }) - ] - }) - }); -} -//#endregion -export { LoginPage as component }; diff --git a/.vercel/output/functions/__server.func/_ssr/login-DaJJyGy-.mjs b/.vercel/output/functions/__server.func/_ssr/login-DaJJyGy-.mjs new file mode 100644 index 0000000..2bee4bf --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/login-DaJJyGy-.mjs @@ -0,0 +1,225 @@ +import { o as __toESM } from "../_runtime.mjs"; +import { u as require_react } from "../_libs/@floating-ui/react-dom+[...].mjs"; +import { g as Navigate, h as Link } from "../_libs/@tanstack/react-router+[...].mjs"; +import { c as require_jsx_runtime } from "../_libs/@radix-ui/react-collection+[...].mjs"; +import { r as signIn, t as authClient } from "./client-Bm2YFrbd.mjs"; +import { t as GROK_PROVIDERS } from "./server-A0BVD3fT.mjs"; +import { i as useCurrentUserState, n as Input, t as Button } from "./input-CLjwzknR.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/login-DaJJyGy-.js +var import_react = /* @__PURE__ */ __toESM(require_react()); +var import_jsx_runtime = require_jsx_runtime(); +/** True on loopback / desktop-local origins where the Grok preview OAuth client rejects callbacks. */ +function isLocalAuthOrigin() { + if (typeof window === "undefined") return false; + const host = window.location.hostname; + return host === "localhost" || host === "127.0.0.1" || host === "[::1]"; +} +function LoginPage() { + const { user, isPending } = useCurrentUserState(); + const [email, setEmail] = (0, import_react.useState)(""); + const [password, setPassword] = (0, import_react.useState)(""); + const [name, setName] = (0, import_react.useState)(""); + const [mode, setMode] = (0, import_react.useState)("signin"); + const [busy, setBusy] = (0, import_react.useState)(false); + const [error, setError] = (0, import_react.useState)(null); + const [localOrigin, setLocalOrigin] = (0, import_react.useState)(false); + (0, import_react.useEffect)(() => setLocalOrigin(isLocalAuthOrigin()), []); + if (!isPending && user) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Navigate, { to: "/" }); + async function onEmailSubmit(e) { + e.preventDefault(); + setError(null); + setBusy(true); + try { + if (mode === "signup") { + const { error: err } = await authClient.signUp.email({ + email: email.trim(), + password, + name: name.trim() || email.trim().split("@")[0] || "User" + }); + if (err) throw new Error(err.message ?? "Sign-up failed"); + } else { + const { error: err } = await authClient.signIn.email({ + email: email.trim(), + password + }); + if (err) throw new Error(err.message ?? "Sign-in failed"); + } + window.location.href = "/"; + } catch (err) { + setError(err instanceof Error ? err.message : "Authentication failed"); + } finally { + setBusy(false); + } + } + async function onSocial(providerId) { + setError(null); + setBusy(true); + try { + await signIn(providerId, { callbackURL: "/" }); + } catch (err) { + const raw = err instanceof Error ? err.message : "Sign-in failed"; + if (/invalid redirect/i.test(raw) || localOrigin) setError("Google / X sign-in needs a public app URL registered with the Grok auth broker. On this machine use email & password, or open the app in a Grok live preview / deployed host."); + else setError(raw); + setBusy(false); + } + } + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("main", { + className: "grid min-h-dvh place-items-center bg-background px-6 text-foreground", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "w-full max-w-sm space-y-6", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-2 text-center", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "mx-auto flex size-12 items-center justify-center rounded-xl bg-foreground text-lg font-semibold text-background", + children: "F" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("h1", { + className: "text-2xl font-semibold tracking-tight", + children: "Sign in to ForgeNotes" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-sm text-muted-foreground", + children: "Signed-in pages sync to the database. Guests keep a local copy only." + }) + ] + }), + localOrigin && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-left text-xs leading-relaxed text-amber-950 dark:text-amber-100", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { + className: "font-medium", + children: "Desktop / local note:" + }), + " Continue with Google or X uses the shared Grok auth broker, which only accepts callbacks from", + " ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { + className: "rounded bg-black/5 px-1 dark:bg-white/10", + children: "*.grok-sandbox.com" + }), + " ", + "(or a deployed app with its own broker credentials). For this Tauri / localhost window, use ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "email & password" }), + " below." + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-4", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("form", { + onSubmit: onEmailSubmit, + className: "space-y-3", + children: [ + mode === "signup" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { + htmlFor: "name", + className: "text-xs font-medium text-muted-foreground", + children: "Name" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + id: "name", + autoComplete: "name", + value: name, + onChange: (e) => setName(e.target.value), + placeholder: "Your name", + disabled: busy + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { + htmlFor: "email", + className: "text-xs font-medium text-muted-foreground", + children: "Email" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + id: "email", + type: "email", + autoComplete: "email", + required: true, + value: email, + onChange: (e) => setEmail(e.target.value), + placeholder: "you@example.com", + disabled: busy + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { + htmlFor: "password", + className: "text-xs font-medium text-muted-foreground", + children: "Password" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + id: "password", + type: "password", + autoComplete: mode === "signup" ? "new-password" : "current-password", + required: true, + minLength: 8, + value: password, + onChange: (e) => setPassword(e.target.value), + placeholder: "At least 8 characters", + disabled: busy + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "submit", + className: "h-11 w-full", + disabled: busy, + children: busy ? "Working…" : mode === "signup" ? "Create account" : "Sign in with email" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "w-full text-center text-xs text-muted-foreground underline-offset-4 hover:underline", + disabled: busy, + onClick: () => { + setMode((m) => m === "signin" ? "signup" : "signin"); + setError(null); + }, + children: mode === "signup" ? "Already have an account? Sign in" : "Need an account? Sign up" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "relative py-1", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "absolute inset-0 flex items-center", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "w-full border-t border-border" }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "relative flex justify-center text-xs uppercase", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "bg-background px-2 text-muted-foreground", + children: "or" + }) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "space-y-2", + children: GROK_PROVIDERS.map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + variant: "outline", + className: "h-11 w-full justify-center", + disabled: busy, + onClick: () => void onSocial(p.providerId), + children: ["Continue with ", p.label] + }, p.providerId)) + }) + ] + }), + error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive", + children: error + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-center text-sm text-muted-foreground", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, { + to: "/", + className: "underline-offset-4 hover:underline", + children: "Continue as guest" + }) + }) + ] + }) + }); +} +//#endregion +export { LoginPage as component }; diff --git a/.vercel/output/functions/__server.func/_ssr/mcp-PdRpzr2V.mjs b/.vercel/output/functions/__server.func/_ssr/mcp-PdRpzr2V.mjs new file mode 100644 index 0000000..04563b1 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/mcp-PdRpzr2V.mjs @@ -0,0 +1,119 @@ +//#region node_modules/.nitro/vite/services/ssr/assets/mcp-PdRpzr2V.js +function parseHeaders(server) { + const headers = {}; + if (server.authToken?.trim()) headers.Authorization = `Bearer ${server.authToken.trim()}`; + const raw = server.headersText?.trim() ?? ""; + for (const line of raw.split("\n")) { + const idx = line.indexOf(":"); + if (idx <= 0) continue; + const key = line.slice(0, idx).trim(); + const value = line.slice(idx + 1).trim(); + if (key) headers[key] = value; + } + return headers; +} +function parseEnv(text) { + const env = {}; + if (!text?.trim()) return env; + for (const line of text.split("\n")) { + const idx = line.indexOf("="); + if (idx <= 0) continue; + const key = line.slice(0, idx).trim(); + const value = line.slice(idx + 1).trim(); + if (key) env[key] = value; + } + return env; +} +function parseArgs(text) { + if (!text?.trim()) return []; + return text.trim().split(/\s+/).filter(Boolean); +} +function buildMcpConnections(servers) { + const connections = {}; + for (const s of servers) { + if (!s.enabled) continue; + const name = s.name || s.id; + if (s.transport === "stdio") { + if (!s.command?.trim()) continue; + connections[name] = { + transport: "stdio", + command: s.command.trim(), + args: parseArgs(s.argsText), + env: parseEnv(s.envText) + }; + } else { + if (!s.url?.trim()) continue; + connections[name] = { + transport: s.transport === "sse" ? "sse" : "http", + url: s.url.trim(), + headers: parseHeaders(s) + }; + } + } + return connections; +} +async function loadMcpTools(settings) { + const connections = buildMcpConnections(settings.mcpServers); + if (Object.keys(connections).length === 0) return { + tools: [], + errors: [], + toolNames: [] + }; + try { + const { MultiServerMCPClient } = await import("../_libs/@langchain/mcp-adapters+[...].mjs").then((n) => n.t); + const tools = await new MultiServerMCPClient({ mcpServers: connections }).getTools(); + return { + tools, + errors: [], + toolNames: tools.map((t) => t.name) + }; + } catch (err) { + return { + tools: [], + errors: [err instanceof Error ? err.message : String(err)], + toolNames: [] + }; + } +} +async function testMcpServer(server) { + const fake = { + setupComplete: true, + enabled: true, + backend: "deepagents", + provider: "xai", + model: "test", + apiKey: "", + baseUrl: "", + temperature: 0, + recursionLimit: 10, + mcpServers: [{ + ...server, + enabled: true + }], + enabledSkills: [], + preferStreaming: true + }; + try { + const connections = buildMcpConnections(fake.mcpServers); + if (Object.keys(connections).length === 0) return { + ok: false, + message: "Incomplete MCP config (URL or command required)", + toolNames: [] + }; + const { MultiServerMCPClient } = await import("../_libs/@langchain/mcp-adapters+[...].mjs").then((n) => n.t); + const names = (await new MultiServerMCPClient({ mcpServers: connections }).getTools()).map((t) => t.name); + return { + ok: true, + message: `OK · ${names.length} tool${names.length === 1 ? "" : "s"}`, + toolNames: names + }; + } catch (err) { + return { + ok: false, + message: err instanceof Error ? err.message : String(err), + toolNames: [] + }; + } +} +//#endregion +export { loadMcpTools, testMcpServer }; diff --git a/.vercel/output/functions/__server.func/_ssr/middleware-DoQ2eaJS.mjs b/.vercel/output/functions/__server.func/_ssr/middleware-DoQ2eaJS.mjs new file mode 100644 index 0000000..e5f0d4f --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/middleware-DoQ2eaJS.mjs @@ -0,0 +1,37 @@ +import { n as createMiddleware } from "./ssr.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/middleware-DoQ2eaJS.js +/** +* Auth middleware for server functions — the standard way to get the caller's +* verified user id. When deployed the session cookie is same-origin and rides +* along automatically. In the live preview the client also forwards the bearer +* token (partitioned cookies) via the `.client` hook below — call sites do not +* thread it themselves. +* +* import { createServerFn } from "@tanstack/react-start"; +* import { getSql } from "@/lib/db"; +* import { authMiddleware } from "@/lib/auth/middleware"; +* +* export const listTodos = createServerFn({ method: "GET" }) +* .middleware([authMiddleware]) +* .handler(async ({ context }) => { +* const sql = await getSql(); +* return sql`select * from todos where user_id = ${context.userId}`; +* }); +* +* Signed out (auth on — the default, including live preview) -> throws +* `UnauthorizedError` (see `verify.server.ts`). Only when auth is explicitly +* disabled (`VITE_AUTH_ENABLED=false`) does it resolve the shared dev user and +* never throw. Use it on every server function that touches per-user data, and +* scope every query by `context.userId`. +*/ +var authMiddleware = createMiddleware({ type: "function" }).client(async ({ next }) => { + const { getBearerToken } = await import("./client-Bm2YFrbd.mjs").then((n) => n.n); + return next({ sendContext: { bearerToken: getBearerToken() ?? void 0 } }); +}).server(async ({ next, context }) => { + const { assertSameSiteRequest } = await import("./isolation.server-CGNg1r0B.mjs"); + const { requireUserId } = await import("./verify.server-4Dqp9B_I.mjs"); + assertSameSiteRequest(); + return next({ context: { userId: await requireUserId(context.bearerToken) } }); +}); +//#endregion +export { authMiddleware as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/resolve-model-CV2sMs92.mjs b/.vercel/output/functions/__server.func/_ssr/resolve-model-CV2sMs92.mjs new file mode 100644 index 0000000..6ee45af --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/resolve-model-CV2sMs92.mjs @@ -0,0 +1,125 @@ +//#region node_modules/.nitro/vite/services/ssr/assets/resolve-model-CV2sMs92.js +function getAiConfig() { + const apiKey = process.env.XAI_API_KEY?.trim() || ""; + const model = process.env.XAI_MODEL?.trim() || "grok-4.5"; + const rawBackend = process.env.AI_BACKEND?.trim().toLowerCase() || "deepagents"; + const backend = rawBackend === "direct" || rawBackend === "local" || rawBackend === "deepagents" ? rawBackend : "deepagents"; + const recursionLimit = Math.min(80, Math.max(8, Number(process.env.AI_RECURSION_LIMIT || 40) || 40)); + const configured = Boolean(apiKey); + return { + apiKey, + model, + backend, + effective: !configured ? "local" : backend === "local" ? "local" : backend, + configured, + recursionLimit, + deepAgentsRoot: "deepagents-root", + skillsPath: "/skills/" + }; +} +var WORKSPACE_SKILLS = [ + "summarize-page", + "edit-block", + "action-items", + "table-from-notes", + "mermaid-diagram", + "custom-page-task" +]; +/** +* Build a LangChain chat model from user settings, falling back to process env. +*/ +async function resolveChatModel(settings) { + const env = getAiConfig(); + const provider = settings?.provider ?? "xai"; + const modelName = settings?.model?.trim() || env.model || "grok-4.5"; + const temperature = settings?.temperature ?? .35; + const userKey = settings?.apiKey?.trim() || ""; + const envXai = env.apiKey; + const baseUrl = settings?.baseUrl?.trim() || ""; + if (provider === "xai") { + const apiKey = userKey || envXai; + if (!apiKey) throw new Error("NO_KEY"); + const { ChatXAI } = await import("../_libs/langchain__xai.mjs").then((n) => n.t); + return { + model: new ChatXAI({ + apiKey, + model: modelName, + temperature + }), + provider: "xai", + modelName, + source: userKey ? "user" : "env" + }; + } + if (provider === "anthropic") { + const apiKey = userKey || process.env.ANTHROPIC_API_KEY?.trim() || ""; + if (!apiKey) throw new Error("NO_KEY"); + const { ChatAnthropic } = await import("../_libs/@langchain/anthropic+[...].mjs").then((n) => n.t); + return { + model: new ChatAnthropic({ + apiKey, + model: modelName, + temperature + }), + provider: "anthropic", + modelName, + source: userKey ? "user" : "env" + }; + } + if (provider === "openai") { + const apiKey = userKey || process.env.OPENAI_API_KEY?.trim() || ""; + if (!apiKey) throw new Error("NO_KEY"); + const { ChatOpenAI } = await import("../_libs/langchain__openai+openai.mjs").then((n) => n.t); + return { + model: new ChatOpenAI({ + apiKey, + model: modelName, + temperature + }), + provider: "openai", + modelName, + source: userKey ? "user" : "env" + }; + } + if (provider === "ollama") { + const { ChatOllama } = await import("../_libs/@langchain/ollama+[...].mjs").then((n) => n.t); + return { + model: new ChatOllama({ + baseUrl: baseUrl || "http://127.0.0.1:11434", + model: modelName, + temperature + }), + provider: "ollama", + modelName, + source: "user" + }; + } + const apiKey = userKey || process.env.OPENAI_API_KEY?.trim() || "not-needed"; + if (!baseUrl) throw new Error("BASE_URL_REQUIRED"); + const { ChatOpenAI } = await import("../_libs/langchain__openai+openai.mjs").then((n) => n.t); + return { + model: new ChatOpenAI({ + apiKey, + model: modelName, + temperature, + configuration: { baseURL: baseUrl } + }), + provider: "openai_compatible", + modelName, + source: "user" + }; +} +function hasLiveCredentials(settings) { + if (!settings?.enabled) return false; + if (settings.backend === "local") return false; + const provider = settings.provider; + if (provider === "ollama") return true; + if (provider === "openai_compatible") return Boolean(settings.baseUrl?.trim()); + if (settings.apiKey?.trim()) return true; + if (provider === "xai" && process.env.XAI_API_KEY?.trim()) return true; + if (provider === "anthropic" && process.env.ANTHROPIC_API_KEY?.trim()) return true; + if (provider === "openai" && process.env.OPENAI_API_KEY?.trim()) return true; + return false; +} +//#endregion +export { resolveChatModel as i, getAiConfig as n, hasLiveCredentials as r, WORKSPACE_SKILLS as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/rolldown-runtime-D7D4PA-g.mjs b/.vercel/output/functions/__server.func/_ssr/rolldown-runtime-D7D4PA-g.mjs new file mode 100644 index 0000000..8564842 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/rolldown-runtime-D7D4PA-g.mjs @@ -0,0 +1,13 @@ +//#region node_modules/.nitro/vite/services/ssr/assets/rolldown-runtime-D7D4PA-g.js +var __defProp = Object.defineProperty; +var __exportAll = (all, no_symbols) => { + let target = {}; + for (var name in all) __defProp(target, name, { + get: all[name], + enumerable: true + }); + if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" }); + return target; +}; +//#endregion +export { __exportAll as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/router-DFPfY5Jx.mjs b/.vercel/output/functions/__server.func/_ssr/router-DFPfY5Jx.mjs new file mode 100644 index 0000000..950fad0 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/router-DFPfY5Jx.mjs @@ -0,0 +1,386 @@ +import { o as __toESM } from "../_runtime.mjs"; +import { u as require_react } from "../_libs/@floating-ui/react-dom+[...].mjs"; +import { c as HeadContent, d as Outlet, f as lazyRouteComponent, m as createRootRoute, p as createFileRoute, s as Scripts, u as createRouter } from "../_libs/@tanstack/react-router+[...].mjs"; +import { c as require_jsx_runtime } from "../_libs/@radix-ui/react-collection+[...].mjs"; +import { i as resolveChatModel, r as hasLiveCredentials } from "./resolve-model-CV2sMs92.mjs"; +import { a as buildUserPrompt, i as buildSystemPrompt, n as isCliBackend, o as parseModelPayload, r as streamCliAgent } from "./cli-backends-BkZaX-Hk.mjs"; +import { n as auth } from "./server-A0BVD3fT.mjs"; +import { t as useWorkspace } from "./store-DoRtk2cu.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/router-DFPfY5Jx.js +var import_react = /* @__PURE__ */ __toESM(require_react()); +var import_jsx_runtime = require_jsx_runtime(); +/** +* App-wide client provider mounted once near the root (in `src/routes/__root.tsx`): +* +* +* +* Better Auth's React client (`@/lib/auth/client`) needs NO context provider — +* its `useSession()` works standalone — so this is a passthrough today. It's +* kept as the single, stable mount point for any future client-side providers +* (e.g. a toast or theme provider) without churning the root shell. +*/ +function AuthProvider({ children }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children }); +} +/** +* Applies the persisted theme to . +* +* Lives at the root, not inside AppShell. It used to be an effect in AppShell, +* which meant `/login` never got the `.dark` class on a cold load — the login +* page uses theme-aware tokens, so its dark rendering was simply unreachable +* unless you navigated there from `/` in the same document. +*/ +function useTheme() { + const theme = useWorkspace((s) => s.theme); + (0, import_react.useEffect)(() => { + const root = document.documentElement; + if (theme === "dark") root.classList.add("dark"); + else root.classList.remove("dark"); + }, [theme]); +} +/** +* App-level zoom: ⌘+ / ⌘- scale every rem in the app, remembered per device. +* +* Implemented as a root font size rather than a CSS `zoom` or `transform`, +* because Tailwind v4 sizes everything here in rem — so one property scales +* type, padding, gaps and radii together, and nothing needs to know it happened. +* `transform: scale()` would blur text and break `position: fixed` children +* (the command palette, every dialog); `zoom` is still inconsistent across +* engines, and this app ships on WebKit. +* +* Deliberately NOT in the workspace store. `workspace-v1` is partialized into +* the remote workspace and comes back through `loadFromRemote`, so a zoom level +* set on a 4K desktop would follow you to a laptop and overwrite what that +* screen needs. Zoom is a property of the display you are sitting at, so it +* gets its own machine-local key. +*/ +var KEY = "forgenotes-zoom"; +/** +* A fixed ladder rather than repeated multiplication. `scale *= 1.1` accumulates +* float error and lands on values like 1.3310000000000004, which then round-trip +* through localStorage and never compare equal to anything. +*/ +var ZOOM_STEPS = [ + .75, + .85, + 1, + 1.15, + 1.3, + 1.5, + 1.75, + 2 +]; +/** Index of the ladder entry closest to `scale`. Never returns -1. */ +function nearestStep(scale) { + let best = 0; + for (let i = 1; i < ZOOM_STEPS.length; i++) if (Math.abs(ZOOM_STEPS[i] - scale) < Math.abs(ZOOM_STEPS[best] - scale)) best = i; + return best; +} +/** +* The next zoom level in `direction` (+1 in, -1 out, 0 reset). +* +* Snapping to the nearest step first means a value hand-edited in localStorage, +* or left behind by an older ladder, still steps sensibly instead of jumping. +*/ +function stepZoom(current, direction) { + if (direction === 0) return 1; + const i = nearestStep(current) + direction; + return ZOOM_STEPS[Math.min(ZOOM_STEPS.length - 1, Math.max(0, i))]; +} +function readZoom() { + if (typeof window === "undefined") return 1; + const raw = Number.parseFloat(window.localStorage.getItem(KEY) ?? ""); + if (!Number.isFinite(raw) || raw <= 0) return 1; + return Math.min(ZOOM_STEPS.at(-1), Math.max(ZOOM_STEPS[0], raw)); +} +function applyZoom(scale) { + document.documentElement.style.fontSize = scale === 1 ? "" : `${scale * 100}%`; +} +/** +* Binds the zoom shortcuts and applies the remembered level. Root-level, like +* `useTheme` — `/login` needs it too, and it renders outside `AppShell`. +*/ +function useZoom() { + (0, import_react.useEffect)(() => { + let scale = readZoom(); + applyZoom(scale); + const onKey = (e) => { + if (!(e.metaKey || e.ctrlKey) || e.altKey) return; + const direction = e.key === "=" || e.key === "+" ? 1 : e.key === "-" || e.key === "_" ? -1 : e.key === "0" ? 0 : null; + if (direction === null) return; + const next = stepZoom(scale, direction); + e.preventDefault(); + if (next === scale) return; + scale = next; + applyZoom(scale); + window.localStorage.setItem(KEY, String(scale)); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); +} +function useCaptureMode() { + (0, import_react.useEffect)(() => {}, []); +} +var styles_default = "/assets/styles-Peq6Rcdg.css"; +var Route$4 = createRootRoute({ + head: () => ({ + meta: [ + { charSet: "utf-8" }, + { + name: "viewport", + content: "width=device-width, initial-scale=1" + }, + { title: "ForgeNotes — notes, AI & harness" }, + { + name: "description", + content: "ForgeNotes is a Notion-style workspace for notes, AI (Deep Agents & coding CLIs), markdown, and agent workflows." + } + ], + links: [{ + rel: "stylesheet", + href: styles_default + }] + }), + component: RootDocument +}); +function RootDocument() { + useTheme(); + useZoom(); + useCaptureMode(); + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("html", { + lang: "en", + suppressHydrationWarning: true, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("head", { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HeadContent, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("body", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(AuthProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Outlet, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Scripts, {})] })] + }); +} +var $$splitComponentImporter$1 = () => import("./routes-B0km-ETS.mjs"); +var Route$3 = createFileRoute("/")({ component: lazyRouteComponent($$splitComponentImporter$1, "component") }); +var $$splitComponentImporter = () => import("./login-DaJJyGy-.mjs"); +var Route$2 = createFileRoute("/login")({ component: lazyRouteComponent($$splitComponentImporter, "component") }); +/** True on loopback / desktop-local origins where the Grok preview OAuth client rejects callbacks. */ +function sse(event) { + return `data: ${JSON.stringify(event)}\n\n`; +} +function validateBody(raw) { + const data = raw; + if (!data?.action || ![ + "edit_block", + "summarize", + "action_items", + "table", + "outline", + "mermaid", + "custom" + ].includes(data.action)) throw new Error("Invalid action"); + return { + req: { + action: data.action, + instruction: typeof data.instruction === "string" ? data.instruction.slice(0, 4e3) : "", + blockText: typeof data.blockText === "string" ? data.blockText.slice(0, 8e3) : "", + blockType: data.blockType, + pageTitle: typeof data.pageTitle === "string" ? data.pageTitle.slice(0, 500) : "", + pageText: typeof data.pageText === "string" ? data.pageText.slice(0, 2e4) : "" + }, + clientSettings: data.clientSettings ?? null, + backendOverride: typeof data.backend === "string" ? data.backend : void 0 + }; +} +function resolveBackend(settings, override) { + if (override) return override; + if (!settings) return "local"; + if (!settings.enabled) return "local"; + return settings.backend; +} +async function* streamDirect(settings, req) { + if (!hasLiveCredentials(settings) && settings?.provider !== "ollama") { + if (!process.env.XAI_API_KEY && !process.env.ANTHROPIC_API_KEY && !process.env.OPENAI_API_KEY) { + yield { + type: "error", + message: "No API credentials for direct streaming" + }; + return; + } + } + yield { + type: "status", + message: "Streaming from model…" + }; + const { model, provider, modelName } = await resolveChatModel(settings); + const system = buildSystemPrompt(req.action); + const user = buildUserPrompt(req); + const m = model; + let full = ""; + if (typeof m.stream === "function") { + const stream = await m.stream([{ + role: "system", + content: system + }, { + role: "user", + content: user + }]); + for await (const chunk of stream) { + const content = chunk?.content; + let piece = ""; + if (typeof content === "string") piece = content; + else if (Array.isArray(content)) piece = content.map((c) => typeof c === "string" ? c : c.text ?? "").join(""); + if (piece) { + full += piece; + yield { + type: "token", + text: piece + }; + } + } + } else { + const res = await model.invoke([{ + role: "system", + content: system + }, { + role: "user", + content: user + }]); + full = typeof res.content === "string" ? res.content : Array.isArray(res.content) ? res.content.map((c) => typeof c === "string" ? c : c.text ?? "").join("") : String(res.content ?? ""); + yield { + type: "token", + text: full + }; + } + const result = { + ...parseModelPayload(full, req.action, "direct"), + model: `${provider}:${modelName}`, + provider: "direct" + }; + yield { + type: "done", + text: full, + result + }; +} +var Route$1 = createFileRoute("/api/ai/stream")({ server: { handlers: { POST: async ({ request }) => { + let body; + try { + body = await request.json(); + } catch { + return new Response(JSON.stringify({ error: "Invalid JSON" }), { status: 400 }); + } + let parsed; + try { + parsed = validateBody(body); + } catch (e) { + return new Response(JSON.stringify({ error: e instanceof Error ? e.message : "Bad request" }), { status: 400 }); + } + const backend = resolveBackend(parsed.clientSettings, parsed.backendOverride); + const encoder = new TextEncoder(); + const stream = new ReadableStream({ async start(controller) { + const send = (ev) => { + controller.enqueue(encoder.encode(sse(ev))); + }; + try { + if (isCliBackend(backend)) { + let full = ""; + for await (const chunk of streamCliAgent(backend, parsed.req)) if (chunk.type === "token" && chunk.text) { + full += chunk.text; + send({ + type: "token", + text: chunk.text + }); + } else if (chunk.type === "status") send({ + type: "status", + message: chunk.message + }); + else if (chunk.type === "done") { + full = chunk.text || full; + const result = { + ...parseModelPayload(full, parsed.req.action, backend), + model: backend, + provider: backend + }; + send({ + type: "done", + text: full, + result + }); + } else if (chunk.type === "error") send({ + type: "error", + message: chunk.message + }); + } else if (backend === "direct" || backend === "deepagents") try { + for await (const ev of streamDirect(parsed.clientSettings, parsed.req)) send(ev); + } catch (err) { + send({ + type: "error", + message: err instanceof Error ? err.message : String(err) + }); + } + else { + send({ + type: "status", + message: "Local demo (no live stream)" + }); + const demo = "Local demo mode. Choose Claude Code, Codex, Grok CLI, or configure an API key for live generation."; + send({ + type: "token", + text: demo + }); + send({ + type: "done", + text: demo, + result: { + text: demo, + provider: "local", + blocks: [{ + type: "paragraph", + content: demo + }] + } + }); + } + } catch (err) { + send({ + type: "error", + message: err instanceof Error ? err.message : String(err) + }); + } finally { + controller.close(); + } + } }); + return new Response(stream, { headers: { + "Content-Type": "text/event-stream; charset=utf-8", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } }); +} } } }); +var Route = createFileRoute("/api/auth/$")({ server: { handlers: { + GET: ({ request }) => auth.handler(request), + POST: ({ request }) => auth.handler(request) +} } }); +var rootRouteChildren = { + IndexRoute: Route$3.update({ + id: "/", + path: "/", + getParentRoute: () => Route$4 + }), + LoginRoute: Route$2.update({ + id: "/login", + path: "/login", + getParentRoute: () => Route$4 + }), + ApiAiStreamRoute: Route$1.update({ + id: "/api/ai/stream", + path: "/api/ai/stream", + getParentRoute: () => Route$4 + }), + ApiAuthSplatRoute: Route.update({ + id: "/api/auth/$", + path: "/api/auth/$", + getParentRoute: () => Route$4 + }) +}; +var routeTree = Route$4._addFileChildren(rootRouteChildren)._addFileTypes(); +function getRouter() { + return createRouter({ routeTree }); +} +//#endregion +export { getRouter }; diff --git a/.vercel/output/functions/__server.func/_ssr/router-Yvf9JIm-.mjs b/.vercel/output/functions/__server.func/_ssr/router-Yvf9JIm-.mjs deleted file mode 100644 index a1ccef1..0000000 --- a/.vercel/output/functions/__server.func/_ssr/router-Yvf9JIm-.mjs +++ /dev/null @@ -1,78 +0,0 @@ -import { c as HeadContent, d as Outlet, f as lazyRouteComponent, m as createRootRoute, p as createFileRoute, s as Scripts, u as createRouter } from "../_libs/@tanstack/react-router+[...].mjs"; -import { c as require_jsx_runtime } from "../_libs/@radix-ui/react-collection+[...].mjs"; -import { n as auth } from "./server-B2xtU6TT.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/router-Yvf9JIm-.js -var import_jsx_runtime = require_jsx_runtime(); -/** -* App-wide client provider mounted once near the root (in `src/routes/__root.tsx`): -* -* -* -* Better Auth's React client (`@/lib/auth/client`) needs NO context provider — -* its `useSession()` works standalone — so this is a passthrough today. It's -* kept as the single, stable mount point for any future client-side providers -* (e.g. a toast or theme provider) without churning the root shell. -*/ -function AuthProvider({ children }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children }); -} -var styles_default = "/assets/styles-Dja5CCtV.css"; -var Route$3 = createRootRoute({ - head: () => ({ - meta: [ - { charSet: "utf-8" }, - { - name: "viewport", - content: "width=device-width, initial-scale=1" - }, - { title: "Workspace — notes & docs" }, - { - name: "description", - content: "A calm Notion-style workspace for notes, pages, and plans." - } - ], - links: [{ - rel: "stylesheet", - href: styles_default - }] - }), - component: RootDocument -}); -function RootDocument() { - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("html", { - lang: "en", - suppressHydrationWarning: true, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("head", { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HeadContent, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("body", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(AuthProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Outlet, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Scripts, {})] })] - }); -} -var $$splitComponentImporter$1 = () => import("./routes-Cr5s3SSS.mjs"); -var Route$2 = createFileRoute("/")({ component: lazyRouteComponent($$splitComponentImporter$1, "component") }); -var $$splitComponentImporter = () => import("./login-Bi7a5wKY.mjs"); -var Route$1 = createFileRoute("/login")({ component: lazyRouteComponent($$splitComponentImporter, "component") }); -var Route = createFileRoute("/api/auth/$")({ server: { handlers: { - GET: ({ request }) => auth.handler(request), - POST: ({ request }) => auth.handler(request) -} } }); -var rootRouteChildren = { - IndexRoute: Route$2.update({ - id: "/", - path: "/", - getParentRoute: () => Route$3 - }), - LoginRoute: Route$1.update({ - id: "/login", - path: "/login", - getParentRoute: () => Route$3 - }), - ApiAuthSplatRoute: Route.update({ - id: "/api/auth/$", - path: "/api/auth/$", - getParentRoute: () => Route$3 - }) -}; -var routeTree = Route$3._addFileChildren(rootRouteChildren)._addFileTypes(); -function getRouter() { - return createRouter({ routeTree }); -} -//#endregion -export { getRouter }; diff --git a/.vercel/output/functions/__server.func/_ssr/routes-B0km-ETS.mjs b/.vercel/output/functions/__server.func/_ssr/routes-B0km-ETS.mjs new file mode 100644 index 0000000..5268595 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/routes-B0km-ETS.mjs @@ -0,0 +1,4983 @@ +import { o as __toESM } from "../_runtime.mjs"; +import { u as require_react } from "../_libs/@floating-ui/react-dom+[...].mjs"; +import { h as Link } from "../_libs/@tanstack/react-router+[...].mjs"; +import { c as require_jsx_runtime } from "../_libs/@radix-ui/react-collection+[...].mjs"; +import { r as createServerFn } from "./ssr.mjs"; +import { t as WORKSPACE_SKILLS } from "./resolve-model-CV2sMs92.mjs"; +import { i as defaultUserAiSettings, n as DEFAULT_MODELS, r as PROVIDER_META, t as BACKEND_META } from "./settings-types-CI9vU3Ws.mjs"; +import { i as signOut } from "./client-Bm2YFrbd.mjs"; +import { i as createEmptyPage, n as PAGE_ICONS, o as uid, r as cn, t as COVER_PRESETS } from "./seed-CQXoc2iK.mjs"; +import { i as useCurrentUserState, n as Input, r as useCurrentUser, t as Button } from "./input-CLjwzknR.mjs"; +import { n as create, t as persist } from "../_libs/zustand.mjs"; +import { t as useWorkspace } from "./store-DoRtk2cu.mjs"; +import { t as authMiddleware } from "./middleware-DoQ2eaJS.mjs"; +import { c as titleFromMarkdown, i as pageToMarkdownFile, n as localSearchPages, o as searchPages, r as markdownToBlocks, s as slugifyFilename, t as createSsrRpc } from "./search-server-B-Vicnmt.mjs"; +import { $ as Download, A as MessageSquare, B as Heading3, C as Plus, D as Moon, E as PanelLeftClose, F as ListTree, G as FolderPlus, H as Heading1, I as ListTodo, J as FolderInput, K as FolderOutput, L as ListOrdered, M as LogIn, N as LoaderCircle, O as Monitor, P as List, Q as Ellipsis, R as Link2, S as Plug, T as PanelLeft, U as HardDrive, V as Heading2, W as GripVertical, X as FileDown, Y as FileText, Z as Eye, _ as Settings, a as WandSparkles, at as ChevronDown, b as RotateCcw, c as Type, ct as ArrowUp, d as Table2, dt as ArrowDown, et as Copy, f as Sun, g as Sparkles, h as SquareCheckBig, i as Wifi, it as ChevronRight, j as Menu, k as Minus, l as Trash2, lt as ArrowRight, m as Square, n as X, nt as Cloud, o as Upload, ot as Check, p as Star, q as FolderOpen, r as Workflow, rt as CloudOff, s as Unlink, st as Bot, t as Zap, tt as CodeXml, u as Terminal, ut as ArrowLeft, v as Search, w as Play, x as Quote, y as Save, z as Image } from "../_libs/lucide-react.mjs"; +import { a as DialogOverlay$1, i as DialogDescription$1, n as DialogClose, o as DialogPortal$1, r as DialogContent$1, s as DialogTitle$1, t as Dialog$1 } from "../_libs/@radix-ui/react-dialog+[...].mjs"; +import { a as DropdownMenuPortal, c as DropdownMenuSubContent$1, i as DropdownMenuLabel$1, l as DropdownMenuSubTrigger$1, n as DropdownMenuContent$1, o as DropdownMenuSeparator$1, r as DropdownMenuItem$1, s as DropdownMenuSub$1, t as DropdownMenu$1, u as DropdownMenuTrigger$1 } from "../_libs/@radix-ui/react-dropdown-menu+[...].mjs"; +import { t as TooltipProvider$1 } from "../_libs/radix-ui__react-tooltip.mjs"; +import { a as ScrollAreaViewport, i as ScrollAreaThumb, n as ScrollAreaCorner, r as ScrollAreaScrollbar, t as ScrollArea$1 } from "../_libs/radix-ui__react-scroll-area.mjs"; +import { n as toast, t as Toaster } from "../_libs/sonner.mjs"; +import { t as require_lib } from "../_libs/jszip+[...].mjs"; +import { i as PopoverTrigger$1, n as PopoverContent$1, r as PopoverPortal, t as Popover$1 } from "../_libs/radix-ui__react-popover.mjs"; +import { t as _e } from "../_libs/cmdk.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/routes-B0km-ETS.js +var import_react = /* @__PURE__ */ __toESM(require_react()); +var import_jsx_runtime = require_jsx_runtime(); +var import_lib = /* @__PURE__ */ __toESM(require_lib()); +var TooltipProvider = TooltipProvider$1; +function ScrollArea({ className, children, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(ScrollArea$1, { + className: cn("relative overflow-hidden", className), + ...props, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollAreaViewport, { + className: "h-full w-full rounded-[inherit]", + children + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollBar, {}), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollAreaCorner, {}) + ] + }); +} +function ScrollBar({ className, orientation = "vertical", ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollAreaScrollbar, { + orientation, + className: cn("flex touch-none select-none transition-colors", orientation === "vertical" && "h-full w-2 border-l border-l-transparent p-px", orientation === "horizontal" && "h-2 flex-col border-t border-t-transparent p-px", className), + ...props, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollAreaThumb, { className: "relative flex-1 rounded-full bg-border" }) + }); +} +var DropdownMenu = DropdownMenu$1; +var DropdownMenuTrigger = DropdownMenuTrigger$1; +var DropdownMenuSub = DropdownMenuSub$1; +function DropdownMenuSubTrigger({ className, inset, children, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuSubTrigger$1, { + className: cn("flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-muted data-[state=open]:bg-muted", inset && "pl-8", className), + ...props, + children: [children, /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: "ml-auto size-4 opacity-60" })] + }); +} +function DropdownMenuSubContent({ className, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSubContent$1, { + className: cn("z-50 min-w-40 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg", className), + ...props + }); +} +function DropdownMenuContent({ className, sideOffset = 4, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuPortal, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuContent$1, { + sideOffset, + className: cn("z-50 min-w-44 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95", className), + ...props + }) }); +} +function DropdownMenuItem({ className, inset, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuItem$1, { + className: cn("relative flex cursor-default select-none items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50", inset && "pl-8", className), + ...props + }); +} +function DropdownMenuLabel({ className, inset, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuLabel$1, { + className: cn("px-2 py-1.5 text-xs font-medium text-muted-foreground", inset && "pl-8", className), + ...props + }); +} +function DropdownMenuSeparator({ className, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator$1, { + className: cn("-mx-1 my-1 h-px bg-border", className), + ...props + }); +} +var Dialog = Dialog$1; +var DialogPortal = DialogPortal$1; +function DialogOverlay({ className, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogOverlay$1, { + className: cn("fixed inset-0 z-50 bg-black/40 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className), + ...props + }); +} +function DialogContent({ className, children, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogPortal, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogOverlay, {}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent$1, { + className: cn("fixed left-1/2 top-1/2 z-50 grid w-[calc(100%-2rem)] max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border border-border bg-background p-6 shadow-xl duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95", className), + ...props, + children: [children, /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogClose, { + className: "absolute right-3 top-3 rounded-md p-1.5 text-muted-foreground opacity-70 transition-opacity hover:bg-muted hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring/40", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(X, { className: "size-4" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "sr-only", + children: "Close" + })] + })] + })] }); +} +function DialogHeader({ className, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: cn("flex flex-col gap-1.5 text-left", className), + ...props + }); +} +function DialogTitle({ className, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogTitle$1, { + className: cn("text-lg font-semibold leading-none tracking-tight", className), + ...props + }); +} +function DialogDescription({ className, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogDescription$1, { + className: cn("text-sm text-muted-foreground", className), + ...props + }); +} +/** +* Minimal signed-in identity chip + sign-out. Restyle freely (see the +* `design-ui` skill). Sign-out is only shown when auth is enabled (the +* disabled-auth dev user has nothing to sign out of). +*/ +function UserButton() { + const user = useCurrentUser(); + if (!user) return null; + const label = user.displayName ?? user.primaryEmail ?? "Account"; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2", + children: [ + user.profileImageUrl ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("img", { + src: user.profileImageUrl, + alt: "", + className: "h-8 w-8 rounded-full object-cover" + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "grid h-8 w-8 place-items-center rounded-full bg-black/10 text-sm font-medium dark:bg-white/20", + children: label.charAt(0).toUpperCase() + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-sm font-medium", + children: label + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + onClick: () => void signOut(), + className: "cursor-pointer text-sm underline-offset-4 opacity-70 hover:underline", + children: "Sign out" + }) + ] + }); +} +function validateMcpServer(m) { + return { + id: String(m.id || "mcp").slice(0, 64), + name: String(m.name || "mcp").slice(0, 80), + enabled: m.enabled !== false, + transport: m.transport === "sse" || m.transport === "stdio" || m.transport === "http" ? m.transport : "http", + url: typeof m.url === "string" ? m.url.slice(0, 500) : "", + authToken: typeof m.authToken === "string" ? m.authToken.slice(0, 500) : "", + headersText: typeof m.headersText === "string" ? m.headersText.slice(0, 2e3) : "", + command: typeof m.command === "string" ? m.command.slice(0, 200) : "", + argsText: typeof m.argsText === "string" ? m.argsText.slice(0, 1e3) : "", + envText: typeof m.envText === "string" ? m.envText.slice(0, 2e3) : "" + }; +} +function validateSettings(input) { + if (!input || typeof input !== "object") return null; + const s = input; + return { + setupComplete: Boolean(s.setupComplete), + enabled: s.enabled !== false, + backend: s.backend === "direct" || s.backend === "local" || s.backend === "deepagents" || s.backend === "claude-cli" || s.backend === "codex-cli" || s.backend === "grok-cli" ? s.backend : "deepagents", + preferStreaming: s.preferStreaming !== false, + provider: s.provider === "anthropic" || s.provider === "openai" || s.provider === "ollama" || s.provider === "openai_compatible" || s.provider === "xai" ? s.provider : "xai", + model: typeof s.model === "string" ? s.model.slice(0, 120) : "grok-4.5", + apiKey: typeof s.apiKey === "string" ? s.apiKey.slice(0, 500) : "", + baseUrl: typeof s.baseUrl === "string" ? s.baseUrl.slice(0, 500) : "", + temperature: Math.min(1.5, Math.max(0, Number(s.temperature) || .35)), + recursionLimit: Math.min(80, Math.max(8, Number(s.recursionLimit) || 40)), + mcpServers: Array.isArray(s.mcpServers) ? s.mcpServers.slice(0, 20).map((m) => validateMcpServer(m)) : [], + enabledSkills: Array.isArray(s.enabledSkills) ? s.enabledSkills.map(String).slice(0, 50) : [...WORKSPACE_SKILLS] + }; +} +function validateRequest(input) { + const data = input; + if (!data || typeof data !== "object") throw new Error("Invalid AI request"); + const action = data.action; + if (![ + "edit_block", + "summarize", + "action_items", + "table", + "outline", + "mermaid", + "custom" + ].includes(action)) throw new Error("Invalid AI action"); + return { + action, + instruction: typeof data.instruction === "string" ? data.instruction.slice(0, 4e3) : "", + blockText: typeof data.blockText === "string" ? data.blockText.slice(0, 8e3) : "", + blockType: data.blockType, + pageTitle: typeof data.pageTitle === "string" ? data.pageTitle.slice(0, 500) : "", + pageText: typeof data.pageText === "string" ? data.pageText.slice(0, 2e4) : "", + clientSettings: validateSettings(data.clientSettings) + }; +} +var runAi = createServerFn({ method: "POST" }).validator((input) => validateRequest(input)).handler(createSsrRpc("76d08ea8f0b0103fcaf7055c8b138a9579e4124d0d2f62a0686a1011273cd47a")); +var testAiConnection = createServerFn({ method: "POST" }).validator((input) => ({ clientSettings: validateSettings(input?.clientSettings) })).handler(createSsrRpc("5e6a13ce7e871cac8b1efc1cf5ccb213d79a60710661cd7012f69f2c7ccb6982")); +var testMcpConnection = createServerFn({ method: "POST" }).validator((input) => { + const server = input?.server; + if (!server || typeof server !== "object") throw new Error("Missing server"); + return { server: validateMcpServer(server) }; +}).handler(createSsrRpc("1e62b13d94b613cf423e7774bb51046a7dfc3005d0164d46cbd5f39fd41e65ae")); +var getAiStatus = createServerFn({ method: "GET" }).handler(createSsrRpc("5252add61246cf72a4fa382b4734734c4e8ea74302302ba378f1ecb54d53868d")); +var listAiCliBackends = createServerFn({ method: "GET" }).handler(createSsrRpc("9bf431d4df4d57d04f011720753080a98c88face5f4f24058da2b17f8da151b8")); +createServerFn({ method: "POST" }).validator((input) => ({ clientSettings: validateSettings(input?.clientSettings) })).handler(createSsrRpc("12c220cad66e7d4a3abab6da0b2bab6053a48aee4b6a0cde9d321705b501bd69")); +var useAiSettings = create()(persist((set, get) => ({ + ...defaultUserAiSettings(), + hydrated: false, + setHydrated: (v) => set({ hydrated: v }), + patch: (partial) => set((s) => ({ + ...s, + ...partial + })), + reset: () => set({ + ...defaultUserAiSettings(), + hydrated: true + }), + setProviderDefaults: (provider) => set((s) => { + const models = { + xai: "grok-4.5", + anthropic: "claude-sonnet-4-6", + openai: "gpt-4.1", + ollama: "llama3.2", + openai_compatible: "gpt-4o" + }; + const base = provider === "ollama" ? s.baseUrl || "http://127.0.0.1:11434" : provider === "openai_compatible" ? s.baseUrl || "https://api.example.com/v1" : ""; + return { + provider, + model: models[provider], + baseUrl: base + }; + }), + addMcpServer: (partial) => { + const id = uid("mcp"); + const server = { + id, + name: partial?.name ?? "New MCP server", + enabled: partial?.enabled ?? true, + transport: partial?.transport ?? "http", + url: partial?.url ?? "https://", + authToken: partial?.authToken ?? "", + headersText: partial?.headersText ?? "", + command: partial?.command ?? "npx", + argsText: partial?.argsText ?? "-y @modelcontextprotocol/server-everything", + envText: partial?.envText ?? "" + }; + set((s) => ({ mcpServers: [...s.mcpServers, server] })); + return id; + }, + updateMcpServer: (id, patch) => set((s) => ({ mcpServers: s.mcpServers.map((m) => m.id === id ? { + ...m, + ...patch + } : m) })), + removeMcpServer: (id) => set((s) => ({ mcpServers: s.mcpServers.filter((m) => m.id !== id) })), + getSettings: () => { + const s = get(); + return { + setupComplete: s.setupComplete, + enabled: s.enabled, + backend: s.backend, + provider: s.provider, + model: s.model, + apiKey: s.apiKey, + baseUrl: s.baseUrl, + temperature: s.temperature, + recursionLimit: s.recursionLimit, + mcpServers: s.mcpServers, + enabledSkills: s.enabledSkills, + preferStreaming: s.preferStreaming !== false + }; + } +}), { + name: "workspace-ai-settings-v1", + partialize: (s) => ({ + setupComplete: s.setupComplete, + enabled: s.enabled, + backend: s.backend, + provider: s.provider, + model: s.model, + apiKey: s.apiKey, + baseUrl: s.baseUrl, + temperature: s.temperature, + recursionLimit: s.recursionLimit, + mcpServers: s.mcpServers, + enabledSkills: s.enabledSkills, + preferStreaming: s.preferStreaming !== false + }), + onRehydrateStorage: () => (state) => { + state?.setHydrated(true); + } +})); +function snapshotAiSettings() { + return useAiSettings.getState().getSettings(); +} +var STEPS = [ + { + id: "welcome", + title: "Welcome" + }, + { + id: "provider", + title: "Provider" + }, + { + id: "credentials", + title: "Credentials" + }, + { + id: "mcp", + title: "MCP tools" + }, + { + id: "skills", + title: "Skills" + }, + { + id: "review", + title: "Test & finish" + } +]; +function AiSetupWizard({ open, onOpenChange, initialStep = "welcome" }) { + const settings = useAiSettings(); + const [stepIndex, setStepIndex] = (0, import_react.useState)(0); + const [testing, setTesting] = (0, import_react.useState)(false); + const [testResult, setTestResult] = (0, import_react.useState)(null); + const [mcpTestingId, setMcpTestingId] = (0, import_react.useState)(null); + const [cliStatus, setCliStatus] = (0, import_react.useState)([]); + (0, import_react.useEffect)(() => { + if (!open) return; + const idx = STEPS.findIndex((s) => s.id === initialStep); + setStepIndex(idx >= 0 ? idx : 0); + setTestResult(null); + listAiCliBackends().then((list) => setCliStatus(list.map((c) => ({ + id: c.id, + label: c.label, + available: c.available + })))).catch(() => setCliStatus([])); + }, [open, initialStep]); + const step = STEPS[stepIndex]; + const isCliBackend = settings.backend === "claude-cli" || settings.backend === "codex-cli" || settings.backend === "grok-cli"; + const snapshot = () => settings.getSettings(); + const canNext = (0, import_react.useMemo)(() => { + if (step.id === "provider") return Boolean(settings.backend); + if (step.id === "credentials") { + if (isCliBackend) return true; + if (settings.provider === "openai_compatible" && !settings.baseUrl.trim()) return false; + return Boolean(settings.model.trim()); + } + return true; + }, [ + step.id, + settings.backend, + settings.provider, + settings.baseUrl, + settings.model, + isCliBackend + ]); + const go = (delta) => { + setTestResult(null); + setStepIndex((i) => Math.min(STEPS.length - 1, Math.max(0, i + delta))); + }; + const finish = () => { + settings.patch({ + setupComplete: true, + enabled: true + }); + onOpenChange(false); + }; + const runConnectionTest = async () => { + setTesting(true); + setTestResult(null); + try { + const res = await testAiConnection({ data: { clientSettings: snapshot() } }); + setTestResult({ + ok: res.ok, + message: res.message + }); + } catch (e) { + setTestResult({ + ok: false, + message: e instanceof Error ? e.message : "Test failed" + }); + } finally { + setTesting(false); + } + }; + const runMcpTest = async (server) => { + setMcpTestingId(server.id); + try { + const res = await testMcpConnection({ data: { server } }); + settings.updateMcpServer(server.id, { + lastTestOk: res.ok, + lastTestMessage: res.message, + lastToolCount: res.toolNames?.length ?? 0 + }); + } catch (e) { + settings.updateMcpServer(server.id, { + lastTestOk: false, + lastTestMessage: e instanceof Error ? e.message : "Test failed" + }); + } finally { + setMcpTestingId(null); + } + }; + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, { + open, + onOpenChange, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, { + className: "flex max-h-[90vh] max-w-2xl flex-col gap-0 overflow-hidden p-0", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "border-b border-border px-6 py-4", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogTitle, { + className: "flex items-center gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-4" }), "AI setup · Deep Agents & coding CLIs"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogDescription, { children: "Connect an API model, or shell out to Claude Code / Codex / Grok CLIs with streaming." })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ol", { + className: "mt-4 flex flex-wrap gap-1.5", + children: STEPS.map((s, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + "data-testid": `wizard-step-${s.id}`, + "aria-current": i === stepIndex ? "step" : void 0, + onClick: () => setStepIndex(i), + className: cn("rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors", i === stepIndex ? "bg-foreground text-background" : i < stepIndex ? "bg-muted text-foreground" : "bg-muted/50 text-muted-foreground"), + children: [ + i + 1, + ". ", + s.title + ] + }) }, s.id)) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + "data-wizard-step": step.id, + className: "min-h-0 flex-1 overflow-y-auto px-6 py-5", + children: [ + step.id === "welcome" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WelcomeStep, {}), + step.id === "provider" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ProviderStep, { + provider: settings.provider, + backend: settings.backend, + preferStreaming: settings.preferStreaming !== false, + cliStatus, + onProvider: (p) => settings.setProviderDefaults(p), + onBackend: (backend) => settings.patch({ backend }), + onPreferStreaming: (preferStreaming) => settings.patch({ preferStreaming }) + }), + step.id === "credentials" && (isCliBackend ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CliCredentialsStep, { + backend: settings.backend, + cliStatus + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CredentialsStep, { + provider: settings.provider, + model: settings.model, + apiKey: settings.apiKey, + baseUrl: settings.baseUrl, + temperature: settings.temperature, + recursionLimit: settings.recursionLimit, + onChange: (p) => settings.patch(p) + })), + step.id === "mcp" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(McpStep, { + servers: settings.mcpServers, + testingId: mcpTestingId, + onAdd: () => settings.addMcpServer(), + onUpdate: (id, patch) => settings.updateMcpServer(id, patch), + onRemove: (id) => settings.removeMcpServer(id), + onTest: (s) => void runMcpTest(s) + }), + step.id === "skills" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SkillsStep, { + enabled: settings.enabledSkills, + onToggle: (name) => { + const set = new Set(settings.enabledSkills); + if (set.has(name)) set.delete(name); + else set.add(name); + settings.patch({ enabledSkills: [...set] }); + }, + onAll: () => settings.patch({ enabledSkills: [...WORKSPACE_SKILLS] }) + }), + step.id === "review" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ReviewStep, { + settings: snapshot(), + testing, + testResult, + onTest: () => void runConnectionTest() + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center justify-between gap-2 border-t border-border px-6 py-4", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + variant: "ghost", + disabled: stepIndex === 0, + onClick: () => go(-1), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ArrowLeft, { className: "size-4" }), " Back"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "flex gap-2", + children: step.id !== "review" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + disabled: !canNext, + onClick: () => go(1), + children: ["Continue ", /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ArrowRight, { className: "size-4" })] + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + onClick: finish, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Check, { className: "size-4" }), " Save & finish"] + }) + })] + }) + ] + }) + }); +} +function WelcomeStep() { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-4 text-sm leading-relaxed text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "text-base text-foreground", + children: [ + "Generate and edit content with ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "Deep Agents" }), + ", provider APIs, or", + " ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "coding CLIs" }), + " (Claude Code, Codex, Grok) — with streaming when available." + ] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("ul", { + className: "list-inside list-disc space-y-1.5", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: "API path: Grok / Claude / OpenAI / Ollama keys (browser-stored)" }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { children: [ + "CLI path: ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { + className: "text-xs", + children: "claude" + }), + ", ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { + className: "text-xs", + children: "codex" + }), + ",", + " ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { + className: "text-xs", + children: "grok" + }), + " already logged in on the host" + ] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: "Streaming tokens over SSE for live previews in AI blocks and edit dialogs" }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: "Optional MCP servers + workspace skills for Deep Agents mode" }) + ] + })] + }); +} +function ProviderStep({ provider, backend, preferStreaming, cliStatus, onProvider, onBackend, onPreferStreaming }) { + const providers = Object.keys(PROVIDER_META); + const backends = Object.keys(BACKEND_META); + const isCli = BACKEND_META[backend]?.isCli; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-5", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("h3", { + className: "mb-2 flex items-center gap-2 text-sm font-medium text-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Terminal, { className: "size-4" }), " Generation backend"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "grid gap-2 sm:grid-cols-2", + children: backends.map((id) => { + const meta = BACKEND_META[id]; + const cli = cliStatus.find((c) => c.id === id); + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + onClick: () => onBackend(id), + className: cn("rounded-xl border px-3 py-3 text-left transition-colors", backend === id ? "border-foreground bg-muted/60" : "border-border hover:bg-muted/40"), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 text-sm font-semibold text-foreground", + children: [meta.label, meta.isCli && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: cn("rounded-full px-1.5 py-0.5 text-[10px] font-medium", cli?.available ? "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300" : "bg-muted text-muted-foreground"), + children: cli ? cli.available ? "on PATH" : "not found" : "CLI" + })] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "mt-1 text-xs text-muted-foreground", + children: meta.description + })] + }, id); + }) + })] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "flex items-center gap-2 text-sm", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + type: "checkbox", + checked: preferStreaming, + onChange: (e) => onPreferStreaming(e.target.checked) + }), "Prefer streaming output (SSE) when the backend supports it"] + }), + !isCli && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h3", { + className: "mb-2 text-sm font-medium text-foreground", + children: "Model provider (API)" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "grid gap-2 sm:grid-cols-2", + children: providers.map((id) => { + const meta = PROVIDER_META[id]; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + onClick: () => onProvider(id), + className: cn("rounded-xl border px-3 py-3 text-left transition-colors", provider === id ? "border-foreground bg-muted/60" : "border-border hover:bg-muted/40"), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "text-sm font-semibold text-foreground", + children: meta.label + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "mt-1 text-xs text-muted-foreground", + children: meta.description + })] + }, id); + }) + })] }) + ] + }); +} +function CliCredentialsStep({ backend, cliStatus }) { + const hit = cliStatus.find((c) => c.id === backend); + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-4 text-sm", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: cn("rounded-lg border px-3 py-2 text-xs", hit?.available ? "border-emerald-500/40 bg-emerald-500/10 text-emerald-900 dark:text-emerald-200" : "border-border bg-muted/40 text-muted-foreground"), + children: hit?.available ? `${BACKEND_META[backend]?.label ?? backend} is available on PATH.` : `${BACKEND_META[backend]?.label ?? backend} was not found on PATH in this environment. Install it on the machine running the app server.` + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("ul", { + className: "list-inside list-disc space-y-1.5 text-muted-foreground", + children: ({ + "claude-cli": [ + "Install Claude Code CLI and run `claude login`", + "Streaming uses `claude -p … --output-format stream-json`", + "Falls back to plain `-p` if stream-json is unavailable" + ], + "codex-cli": [ + "Install Codex CLI and authenticate", + "Streaming uses `codex exec` stdout", + "Workspace AI never stores your Codex credentials" + ], + "grok-cli": [ + "Install Grok CLI / Grok Build (`grok login` or XAI_API_KEY)", + "Streaming prefers `grok chat --stream`", + "Falls back to `grok -p` / chat without stream flags" + ] + }[backend] ?? ["Authenticate the CLI on the host machine."]).map((t) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: t }, t)) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-xs text-muted-foreground", + children: "No API key is stored in the workspace for CLI backends — auth is handled by the CLI itself." + }) + ] + }); +} +function CredentialsStep({ provider, model, apiKey, baseUrl, temperature, recursionLimit, onChange }) { + const meta = PROVIDER_META[provider]; + const models = DEFAULT_MODELS[provider]; + const showBase = provider === "ollama" || provider === "openai_compatible"; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-4", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "rounded-lg border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground", + children: ["Provider: ", /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "font-medium text-foreground", + children: meta.label + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-sm font-medium", + children: meta.keyLabel + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + type: "password", + autoComplete: "off", + placeholder: meta.keyPlaceholder, + value: apiKey, + onChange: (e) => onChange({ apiKey: e.target.value }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-[11px] text-muted-foreground", + children: "Stored in this browser’s local storage. Not written to the project repo." + }) + ] + }), + showBase && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-sm font-medium", + children: "Base URL" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + placeholder: meta.baseUrlDefault, + value: baseUrl, + onChange: (e) => onChange({ baseUrl: e.target.value }) + }), + meta.baseUrlHint && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-[11px] text-muted-foreground", + children: meta.baseUrlHint + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-sm font-medium", + children: "Model" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", { + className: "h-9 w-full rounded-md border border-border bg-background px-2 text-sm", + value: model, + onChange: (e) => onChange({ model: e.target.value }), + children: models.map((m) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { + value: m, + children: m + }, m)) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + className: "mt-1", + placeholder: "Or type a custom model id", + value: model, + onChange: (e) => onChange({ model: e.target.value }) + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "grid gap-3 sm:grid-cols-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "text-sm font-medium", + children: [ + "Temperature (", + temperature.toFixed(2), + ")" + ] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + type: "range", + min: 0, + max: 1.2, + step: .05, + value: temperature, + onChange: (e) => onChange({ temperature: Number(e.target.value) }), + className: "w-full" + })] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-sm font-medium", + children: "Agent recursion limit" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + type: "number", + min: 8, + max: 80, + value: recursionLimit, + onChange: (e) => onChange({ recursionLimit: Number(e.target.value) || 40 }) + })] + })] + }) + ] + }); +} +function McpStep({ servers, testingId, onAdd, onUpdate, onRemove, onTest }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center justify-between", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "text-sm text-muted-foreground", + children: [ + "MCP tools are used when backend is ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "Deep Agents" }), + "." + ] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "outline", + onClick: onAdd, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-3.5" }), " Add server"] + })] + }), + servers.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-xs text-muted-foreground", + children: "No MCP servers yet." + }), + servers.map((s) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-2 rounded-xl border border-border p-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plug, { className: "size-4 text-muted-foreground" }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + value: s.name, + onChange: (e) => onUpdate(s.id, { name: e.target.value }), + className: "h-8" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "flex items-center gap-1 text-xs", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + type: "checkbox", + checked: s.enabled, + onChange: (e) => onUpdate(s.id, { enabled: e.target.checked }) + }), "On"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + size: "icon-sm", + variant: "ghost", + onClick: () => onRemove(s.id), + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trash2, { className: "size-3.5" }) + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("select", { + className: "h-8 w-full rounded-md border border-border bg-background px-2 text-xs", + value: s.transport, + onChange: (e) => onUpdate(s.id, { transport: e.target.value }), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { + value: "http", + children: "HTTP" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { + value: "sse", + children: "SSE" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { + value: "stdio", + children: "stdio" + }) + ] + }), + s.transport === "stdio" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + placeholder: "command", + value: s.command ?? "", + onChange: (e) => onUpdate(s.id, { command: e.target.value }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + placeholder: "args (space-separated)", + value: s.argsText ?? "", + onChange: (e) => onUpdate(s.id, { argsText: e.target.value }) + })] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + placeholder: "https://…", + value: s.url ?? "", + onChange: (e) => onUpdate(s.id, { url: e.target.value }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "secondary", + disabled: testingId === s.id, + onClick: () => onTest(s), + children: [testingId === s.id ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-3.5 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Wifi, { className: "size-3.5" }), "Test"] + }), s.lastTestMessage && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: cn("text-[11px]", s.lastTestOk ? "text-emerald-600" : "text-destructive"), + children: s.lastTestMessage + })] + }) + ] + }, s.id)) + ] + }); +} +function SkillsStep({ enabled, onToggle, onAll }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-3", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center justify-between", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-sm text-muted-foreground", + children: "Skills for Deep Agents mode." + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + size: "sm", + variant: "ghost", + onClick: onAll, + children: "Enable all" + })] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "grid gap-2 sm:grid-cols-2", + children: WORKSPACE_SKILLS.map((name) => { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + onClick: () => onToggle(name), + className: cn("rounded-lg border px-3 py-2 text-left text-sm", enabled.includes(name) ? "border-foreground bg-muted/50" : "border-border text-muted-foreground"), + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "font-medium", + children: name + }) + }, name); + }) + })] + }); +} +function ReviewStep({ settings, testing, testResult, onTest }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-4 text-sm", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("dl", { + className: "grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-xs", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", { + className: "text-muted-foreground", + children: "Backend" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dd", { + className: "font-medium", + children: BACKEND_META[settings.backend]?.label ?? settings.backend + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", { + className: "text-muted-foreground", + children: "Streaming" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dd", { children: settings.preferStreaming !== false ? "Preferred" : "Off" }), + !BACKEND_META[settings.backend]?.isCli && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", { + className: "text-muted-foreground", + children: "Provider" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("dd", { children: [ + PROVIDER_META[settings.provider]?.label, + " · ", + settings.model + ] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", { + className: "text-muted-foreground", + children: "API key" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dd", { children: settings.apiKey ? "Set" : "Not set" }) + ] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", { + className: "text-muted-foreground", + children: "MCP servers" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("dd", { children: [settings.mcpServers.filter((m) => m.enabled).length, " enabled"] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dt", { + className: "text-muted-foreground", + children: "Skills" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("dd", { children: settings.enabledSkills.length }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + variant: "secondary", + disabled: testing, + onClick: onTest, + children: [testing ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Wifi, { className: "size-4" }), "Test connection"] + }), + testResult && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: cn("text-xs", testResult.ok ? "text-emerald-600" : "text-destructive"), + children: testResult.message + }) + ] + }); +} +function AiSetupBanner({ onOpen }) { + const setupComplete = useAiSettings((s) => s.setupComplete); + const backend = useAiSettings((s) => s.backend); + if (setupComplete) return null; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + onClick: onOpen, + className: "flex w-full items-center gap-2 rounded-lg border border-dashed border-border bg-background px-3 py-2 text-left text-xs text-muted-foreground hover:bg-muted/40", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-3.5 shrink-0" }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [ + "Set up AI — Grok, Claude, Codex CLI, MCP…", + " ", + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "text-foreground", + children: [ + "(", + BACKEND_META[backend]?.label ?? backend, + ")" + ] + }) + ] })] + }); +} +var SAMPLE_MOUNT = { + id: "mount_sample", + name: "Sample notes (linked)", + kind: "server", + serverPath: "/workspace/markdown-samples", + createdAt: Date.now() +}; +var useMarkdownMounts = create()(persist((set, get) => ({ + mounts: [SAMPLE_MOUNT], + selection: null, + hydrated: false, + setHydrated: (v) => set({ hydrated: v }), + setSelection: (sel) => set({ selection: sel }), + addServerMount: (name, serverPath) => { + const id = uid("mount"); + set((s) => ({ mounts: [...s.mounts, { + id, + name: name || "Linked folder", + kind: "server", + serverPath, + createdAt: Date.now() + }] })); + return id; + }, + addBrowserMount: (name) => { + const id = uid("mount"); + set((s) => ({ mounts: [...s.mounts, { + id, + name: name || "Local folder", + kind: "browser", + createdAt: Date.now() + }] })); + return id; + }, + removeMount: (id) => set((s) => ({ + mounts: s.mounts.filter((m) => m.id !== id), + selection: s.selection?.mountId === id ? null : s.selection + })), + renameMount: (id, name) => set((s) => ({ mounts: s.mounts.map((m) => m.id === id ? { + ...m, + name + } : m) })), + ...(function ensure() { + return {}; + })() +}), { + name: "workspace-md-mounts-v1", + partialize: (s) => ({ mounts: s.mounts }), + onRehydrateStorage: () => (state) => { + state?.setHydrated(true); + if (state && !state.mounts.some((m) => m.id === "mount_sample")) state.mounts = [SAMPLE_MOUNT, ...state.mounts]; + } +})); +var IDB_NAME = "workspace-md-handles"; +var IDB_STORE = "handles"; +function openIdb() { + return new Promise((resolve, reject) => { + const req = indexedDB.open(IDB_NAME, 1); + req.onupgradeneeded = () => { + const db = req.result; + if (!db.objectStoreNames.contains(IDB_STORE)) db.createObjectStore(IDB_STORE); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); +} +async function saveDirectoryHandle(mountId, handle) { + const db = await openIdb(); + await new Promise((resolve, reject) => { + const tx = db.transaction(IDB_STORE, "readwrite"); + tx.objectStore(IDB_STORE).put(handle, mountId); + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error); + }); + db.close(); +} +async function loadDirectoryHandle(mountId) { + const db = await openIdb(); + const handle = await new Promise((resolve, reject) => { + const req = db.transaction(IDB_STORE, "readonly").objectStore(IDB_STORE).get(mountId); + req.onsuccess = () => resolve(req.result ?? null); + req.onerror = () => reject(req.error); + }); + db.close(); + return handle; +} +async function listBrowserDir(handle, relPath = "") { + const entries = []; + for await (const [name, entry] of handle.entries()) { + if (name.startsWith(".")) continue; + const path = relPath ? `${relPath}/${name}` : name; + if (entry.kind === "directory") entries.push({ + name, + relPath: path, + kind: "dir" + }); + else if (name.toLowerCase().endsWith(".md")) entries.push({ + name, + relPath: path, + kind: "file" + }); + } + return entries.sort((a, b) => { + if (a.kind !== b.kind) return a.kind === "dir" ? -1 : 1; + return a.name.localeCompare(b.name); + }); +} +async function readBrowserFile(root, relPath) { + const parts = relPath.split("/").filter(Boolean); + let dir = root; + for (let i = 0; i < parts.length - 1; i++) dir = await dir.getDirectoryHandle(parts[i]); + return (await (await dir.getFileHandle(parts[parts.length - 1])).getFile()).text(); +} +async function writeBrowserFile(root, relPath, content) { + const parts = relPath.split("/").filter(Boolean); + let dir = root; + for (let i = 0; i < parts.length - 1; i++) dir = await dir.getDirectoryHandle(parts[i], { create: true }); + const writable = await (await dir.getFileHandle(parts[parts.length - 1], { create: true })).createWritable(); + await writable.write(content); + await writable.close(); +} +/** Only allow reading/writing under these roots (safety). */ +var listServerMount = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.root || typeof d.root !== "string") throw new Error("root required"); + return { + root: d.root.slice(0, 500), + relPath: typeof d.relPath === "string" ? d.relPath.slice(0, 500) : "" + }; +}).handler(createSsrRpc("e157ab9abea20eda7cb1dfe0993f10e014c05e1948b91dad507e96d5387ed401")); +var readServerMountFile = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.root || !d?.relPath) throw new Error("root and relPath required"); + return { + root: d.root.slice(0, 500), + relPath: d.relPath.slice(0, 500) + }; +}).handler(createSsrRpc("c3a114c6a1c5b50dbdfd57a20fe11e1478b2807ee716176eb560a65a27d27cdc")); +var writeServerMountFile = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.root || !d?.relPath || typeof d.content !== "string") throw new Error("root, relPath, content required"); + return { + root: d.root.slice(0, 500), + relPath: d.relPath.slice(0, 500), + content: d.content.slice(0, 2e6) + }; +}).handler(createSsrRpc("0cc4b6b2ef3fcd2c2324866a03056ffdffdb4bfdfdb4862fc42fd41f6339f896")); +var exportPagesToServerDir = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.targetDir || !Array.isArray(d.files)) throw new Error("Invalid export"); + return { + targetDir: d.targetDir.slice(0, 500), + files: d.files.slice(0, 500).map((f) => ({ + relPath: String(f.relPath).slice(0, 400), + content: String(f.content).slice(0, 2e6) + })) + }; +}).handler(createSsrRpc("b62660f341ad0ae3ab4593f5ba2b4559082a2961290a3f1c4443f4cff98a92c1")); +function LinkFolderDialog({ open, onOpenChange }) { + const addServerMount = useMarkdownMounts((s) => s.addServerMount); + const addBrowserMount = useMarkdownMounts((s) => s.addBrowserMount); + const setSelection = useMarkdownMounts((s) => s.setSelection); + const [name, setName] = (0, import_react.useState)("Linked notes"); + const [serverPath, setServerPath] = (0, import_react.useState)("/workspace/markdown-samples"); + const [busy, setBusy] = (0, import_react.useState)(false); + const linkServer = async () => { + setBusy(true); + try { + await listServerMount({ data: { + root: serverPath, + relPath: "" + } }); + const id = addServerMount(name || "Linked folder", serverPath); + setSelection({ + mountId: id, + relPath: "" + }); + toast.success("Folder linked (view only until you open a file)"); + onOpenChange(false); + } catch (e) { + toast.error(e instanceof Error ? e.message : "Could not open path"); + } finally { + setBusy(false); + } + }; + const linkBrowser = async () => { + const w = window; + if (typeof w.showDirectoryPicker !== "function") { + toast.error("Your browser doesn’t support folder access. Use a server path instead."); + return; + } + setBusy(true); + try { + const handle = await w.showDirectoryPicker({ mode: "readwrite" }); + const id = addBrowserMount(name || handle.name || "Local folder"); + await saveDirectoryHandle(id, handle); + setSelection({ + mountId: id, + relPath: "" + }); + toast.success("Local folder linked without importing"); + onOpenChange(false); + } catch (e) { + if (e instanceof Error && e.name === "AbortError") return; + toast.error(e instanceof Error ? e.message : "Could not link folder"); + } finally { + setBusy(false); + } + }; + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, { + open, + onOpenChange, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, { + className: "max-w-md", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogTitle, { + className: "flex items-center gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link2, { className: "size-4" }), "Link markdown folder"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogDescription, { children: [ + "Browse ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { + className: "text-xs", + children: ".md" + }), + " files in the same UI", + " ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "without importing" }), + " them into the workspace." + ] })] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5 text-sm", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "font-medium", + children: "Display name" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + value: name, + onChange: (e) => setName(e.target.value) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-2 rounded-xl border border-border p-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "flex items-center gap-2 text-sm font-medium", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(HardDrive, { className: "size-4" }), " This computer"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-xs text-muted-foreground", + children: "Uses the browser’s folder picker. Files stay on disk; we only read/write when you open or save." + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + disabled: busy, + onClick: () => void linkBrowser(), + children: [busy ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FolderPlus, { className: "size-4" }), "Choose local folder"] + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-2 rounded-xl border border-border p-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-sm font-medium", + children: "Server path (sandbox / deploy host)" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + value: serverPath, + onChange: (e) => setServerPath(e.target.value), + placeholder: "/workspace/markdown-samples" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "text-[11px] text-muted-foreground", + children: [ + "Allowed under ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "/workspace" }), + ". Sample:", + " ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "/workspace/markdown-samples" }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "secondary", + disabled: busy, + onClick: () => void linkServer(), + children: "Link server folder" + }) + ] + }) + ] + }) + }); +} +function collectSubtree(pages, rootId) { + const byParent = /* @__PURE__ */ new Map(); + for (const p of pages) { + if (p.archived) continue; + const list = byParent.get(p.parentId) ?? []; + list.push(p); + byParent.set(p.parentId, list); + } + const out = []; + const walk = (id) => { + const page = pages.find((p) => p.id === id); + if (!page || page.archived) return; + out.push(page); + for (const child of byParent.get(id) ?? []) walk(child.id); + }; + walk(rootId); + return out; +} +function uniquePath(used, base) { + if (!used.has(base)) { + used.add(base); + return base; + } + let i = 2; + while (used.has(`${base}-${i}`)) i += 1; + const p = `${base}-${i}`; + used.add(p); + return p; +} +/** +* Build a zip of markdown files for one page or a full hierarchy. +* Folders mirror the page tree; each page is `slug.md` and children live in `slug/`. +*/ +async function exportPagesToZip(pages, opts) { + const zip = new import_lib.default(); + const roots = opts.hierarchy ? collectSubtree(pages, opts.rootId) : pages.filter((p) => p.id === opts.rootId); + if (roots.length === 0) throw new Error("Page not found"); + const root = pages.find((p) => p.id === opts.rootId); + const used = /* @__PURE__ */ new Set(); + const dirOf = /* @__PURE__ */ new Map(); + const rootSlug = uniquePath(used, slugifyFilename(root.title || "page")); + zip.file(`${rootSlug}.md`, pageToMarkdownFile(root)); + dirOf.set(root.id, rootSlug); + if (opts.hierarchy) for (const page of roots) { + if (page.id === root.id) continue; + const parentDir = page.parentId ? dirOf.get(page.parentId) : rootSlug; + if (!parentDir) continue; + const slug = uniquePath(used, `${parentDir}/${slugifyFilename(page.title || "page")}`); + zip.file(`${slug}.md`, pageToMarkdownFile(page)); + dirOf.set(page.id, slug); + } + return { + blob: await zip.generateAsync({ type: "blob" }), + filename: `${slugifyFilename(root.title || "export")}${opts.hierarchy ? "-tree" : ""}.zip` + }; +} +/** Import a single .md file into a page draft. */ +function importMarkdownFile(filename, content, parentTempId = null) { + const title = titleFromMarkdown(content, filename.split(/[/\\]/).pop() || "page.md"); + let body = content; + body = body.replace(new RegExp(`^#\\s+${escapeReg(title)}\\s*\\n+`), ""); + return { + tempId: uid("imp"), + title, + icon: "📝", + parentTempId, + blocks: markdownToBlocks(body), + relPath: filename + }; +} +function escapeReg(s) { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +/** +* Import a tree of relative paths → content (e.g. from zip or directory picker). +* Nested folders become parent pages. +*/ +function importMarkdownTree(files) { + const mdFiles = files.map((f) => ({ + path: f.path.replace(/\\/g, "/").replace(/^\.\//, ""), + content: f.content + })).filter((f) => f.path.toLowerCase().endsWith(".md")); + const folderIds = /* @__PURE__ */ new Map(); + const drafts = []; + const ensureFolder = (folderPath) => { + if (!folderPath || folderPath === ".") return null; + if (folderIds.has(folderPath)) return folderIds.get(folderPath); + const parts = folderPath.split("/"); + const name = parts[parts.length - 1]; + const parentPath = parts.slice(0, -1).join("/"); + const parentTempId = parentPath ? ensureFolder(parentPath) : null; + const tempId = uid("imp"); + folderIds.set(folderPath, tempId); + drafts.push({ + tempId, + title: name, + icon: "📁", + parentTempId, + blocks: [{ + id: uid("b"), + type: "paragraph", + content: `Folder: ${name}`, + indent: 0 + }], + relPath: folderPath + "/" + }); + return tempId; + }; + mdFiles.sort((a, b) => a.path.localeCompare(b.path)); + for (const f of mdFiles) { + const parts = f.path.split("/"); + const fileName = parts.pop(); + const folder = parts.join("/"); + const parentTempId = folder ? ensureFolder(folder) : null; + drafts.push(importMarkdownFile(fileName, f.content, parentTempId)); + drafts[drafts.length - 1].relPath = f.path; + } + return drafts; +} +/** Materialize drafts into real Page objects and return pages + root ids. */ +function materializeImports(drafts, parentPageId) { + const idMap = /* @__PURE__ */ new Map(); + const pages = []; + const rootIds = []; + for (const d of drafts) idMap.set(d.tempId, uid("page")); + for (const d of drafts) { + const realId = idMap.get(d.tempId); + const realParent = d.parentTempId ? idMap.get(d.parentTempId) ?? parentPageId : parentPageId; + const page = createEmptyPage({ + id: realId, + title: d.title, + icon: d.icon, + parentId: realParent, + blocks: d.blocks + }); + pages.push(page); + if (!d.parentTempId) rootIds.push(realId); + } + return { + pages, + rootIds + }; +} +function downloadBlob(blob, filename) { + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = filename; + a.click(); + URL.revokeObjectURL(url); +} +function MarkdownIODialog({ open, onOpenChange, initialTab = "export", pageId }) { + const pages = useWorkspace((s) => s.pages); + const activePageId = useWorkspace((s) => s.activePageId); + const importPages = useWorkspace((s) => s.importPages); + const setActivePage = useWorkspace((s) => s.setActivePage); + const targetId = pageId ?? activePageId; + const page = pages.find((p) => p.id === targetId); + const [tab, setTab] = (0, import_react.useState)(initialTab); + const [hierarchy, setHierarchy] = (0, import_react.useState)(true); + const [busy, setBusy] = (0, import_react.useState)(false); + const [serverDir, setServerDir] = (0, import_react.useState)("/workspace/markdown-mounts/export"); + const [importParent, setImportParent] = (0, import_react.useState)(true); + const fileRef = (0, import_react.useRef)(null); + const dirRef = (0, import_react.useRef)(null); + const doExportZip = async () => { + if (!targetId) return; + setBusy(true); + try { + const { blob, filename } = await exportPagesToZip(pages, { + rootId: targetId, + hierarchy + }); + downloadBlob(blob, filename); + toast.success("Markdown zip downloaded"); + } catch (e) { + toast.error(e instanceof Error ? e.message : "Export failed"); + } finally { + setBusy(false); + } + }; + const doExportSingleMd = () => { + if (!page) return; + const md = pageToMarkdownFile(page); + downloadBlob(new Blob([md], { type: "text/markdown" }), `${slugifyFilename(page.title || "page")}.md`); + toast.success("Markdown file downloaded"); + }; + const doExportServer = async () => { + if (!targetId) return; + setBusy(true); + try { + const { blob } = await exportPagesToZip(pages, { + rootId: targetId, + hierarchy + }); + const zip = await import_lib.default.loadAsync(blob); + const files = []; + const names = Object.keys(zip.files); + for (const name of names) { + const f = zip.files[name]; + if (f.dir) continue; + files.push({ + relPath: name, + content: await f.async("string") + }); + } + const res = await exportPagesToServerDir({ data: { + targetDir: serverDir, + files + } }); + toast.success(`Wrote ${res.count} files to ${res.dir}`); + } catch (e) { + toast.error(e instanceof Error ? e.message : "Server export failed"); + } finally { + setBusy(false); + } + }; + const applyImports = (files) => { + const { pages: created, rootIds } = materializeImports(files.length === 1 ? [importMarkdownFile(files[0].path, files[0].content)] : importMarkdownTree(files), importParent ? targetId ?? null : null); + importPages(created, rootIds[0] ?? created[0]?.id ?? null); + if (rootIds[0]) setActivePage(rootIds[0]); + toast.success(`Imported ${created.length} page${created.length === 1 ? "" : "s"}`); + onOpenChange(false); + }; + const onPickFiles = async (fileList) => { + if (!fileList?.length) return; + setBusy(true); + try { + const files = []; + for (const file of Array.from(fileList)) { + if (!file.name.toLowerCase().endsWith(".md") && !file.name.toLowerCase().endsWith(".zip")) continue; + if (file.name.toLowerCase().endsWith(".zip")) { + const zip = await import_lib.default.loadAsync(await file.arrayBuffer()); + for (const name of Object.keys(zip.files)) { + const entry = zip.files[name]; + if (entry.dir || !name.toLowerCase().endsWith(".md")) continue; + files.push({ + path: name, + content: await entry.async("string") + }); + } + } else { + const path = file.webkitRelativePath || file.name; + files.push({ + path, + content: await file.text() + }); + } + } + if (!files.length) { + toast.error("No markdown files found"); + return; + } + applyImports(files); + } catch (e) { + toast.error(e instanceof Error ? e.message : "Import failed"); + } finally { + setBusy(false); + } + }; + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, { + open, + onOpenChange, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, { + className: "max-w-lg", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogTitle, { + className: "flex items-center gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(FolderOutput, { className: "size-4" }), "Markdown import / export"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogDescription, { children: [ + "Move pages as folders of ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { + className: "text-xs", + children: ".md" + }), + " files — or export a hierarchy." + ] })] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "flex gap-1 rounded-lg border border-border p-1", + children: ["export", "import"].map((t) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + onClick: () => setTab(t), + className: tab === t ? "flex-1 rounded-md bg-foreground px-3 py-1.5 text-sm font-medium text-background" : "flex-1 rounded-md px-3 py-1.5 text-sm text-muted-foreground hover:bg-muted", + children: t === "export" ? "Export" : "Import" + }, t)) + }), + tab === "export" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-4 text-sm", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "text-muted-foreground", + children: [ + "Current page:", + " ", + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "font-medium text-foreground", + children: [ + page?.icon, + " ", + page?.title || "Untitled" + ] + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "flex items-center gap-2 text-sm", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + type: "checkbox", + checked: hierarchy, + onChange: (e) => setHierarchy(e.target.checked) + }), "Include child pages (folder hierarchy)"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex flex-col gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + disabled: busy || !page, + onClick: () => void doExportZip(), + children: [busy ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Download, { className: "size-4" }), "Download as .zip"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "outline", + disabled: !page || hierarchy, + onClick: doExportSingleMd, + children: "Download single .md" + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-2 rounded-lg border border-border p-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-xs font-medium text-foreground", + children: "Write to server folder" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + value: serverDir, + onChange: (e) => setServerDir(e.target.value) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "text-[11px] text-muted-foreground", + children: [ + "Allowed under ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "/workspace" }), + " (e.g.", + " ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "/workspace/markdown-mounts/export" }), + ")" + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "secondary", + disabled: busy || !page, + onClick: () => void doExportServer(), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(FolderOutput, { className: "size-3.5" }), " Write markdown dir"] + }) + ] + }) + ] + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-4 text-sm", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "flex items-center gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + type: "checkbox", + checked: importParent, + onChange: (e) => setImportParent(e.target.checked) + }), "Nest under current page"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + ref: fileRef, + type: "file", + accept: ".md,.zip,text/markdown,application/zip", + multiple: true, + className: "hidden", + onChange: (e) => void onPickFiles(e.target.files) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + ref: dirRef, + type: "file", + webkitdirectory: "", + directory: "", + multiple: true, + className: "hidden", + onChange: (e) => void onPickFiles(e.target.files) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex flex-col gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + disabled: busy, + onClick: () => fileRef.current?.click(), + children: [busy ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Upload, { className: "size-4" }), "Import .md or .zip"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + variant: "outline", + disabled: busy, + onClick: () => dirRef.current?.click(), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(FolderInput, { className: "size-4" }), " Import folder of markdown"] + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "text-xs text-muted-foreground", + children: [ + "Folders become parent pages; each ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: ".md" }), + " becomes a page. Content is copied into the workspace (unlike linked mounts)." + ] + }) + ] + }) + ] + }) + }); +} +/** Flatten to plain JSON-safe DTO for TanStack server fns */ +var harnessStatus = createServerFn({ method: "GET" }).handler(createSsrRpc("19e00543f0313fe7905c045b33772265c61fa51d18574d69244c3f084698fddb")); +createServerFn({ method: "GET" }).handler(createSsrRpc("9869410eeb67daab81f5d2ed574198eae379b3efb7eb41fe5a887f5ee51051d9")); +var harnessRunAgent = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.agent) throw new Error("agent required"); + return { + agent: String(d.agent).slice(0, 120), + message: String(d.message || "Hello").slice(0, 8e3), + backend: d.backend ? String(d.backend).slice(0, 64) : "" + }; +}).handler(createSsrRpc("3a3b06354c92fa523d323b08f8cb2c04194a6d325c5629dfe4c092272682e98a")); +var harnessRunWorkflow = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.workflow) throw new Error("workflow required"); + return { + workflow: String(d.workflow).slice(0, 120), + feature: String(d.feature || "feature").slice(0, 200), + backend: d.backend ? String(d.backend).slice(0, 64) : "" + }; +}).handler(createSsrRpc("64ebef571e60681eaece2b296de9be5f6f33209c413aad1e4ff65d57e56c9c83")); +function HarnessPanel({ open, onOpenChange }) { + const [backends, setBackends] = (0, import_react.useState)([]); + const [agents, setAgents] = (0, import_react.useState)([]); + const [workflows, setWorkflows] = (0, import_react.useState)([]); + const [loading, setLoading] = (0, import_react.useState)(false); + const [running, setRunning] = (0, import_react.useState)(false); + const [backend, setBackend] = (0, import_react.useState)("mock"); + const [feature, setFeature] = (0, import_react.useState)("JWT authentication"); + const [agentName, setAgentName] = (0, import_react.useState)("hello"); + const [message, setMessage] = (0, import_react.useState)("What is a meta-harness?"); + const [workflow, setWorkflow] = (0, import_react.useState)("jwt-auth.yaml"); + const [result, setResult] = (0, import_react.useState)(null); + const [tab, setTab] = (0, import_react.useState)("workflow"); + const [error, setError] = (0, import_react.useState)(null); + (0, import_react.useEffect)(() => { + if (!open) return; + setLoading(true); + setError(null); + harnessStatus().then((s) => { + setBackends(s.backends); + setAgents(s.agents); + setWorkflows(s.workflows); + if (s.agents[0]) setAgentName(s.agents[0].replace(/\.ya?ml$/, "")); + const jwt = s.workflows.find((w) => w.includes("jwt")); + if (jwt) setWorkflow(jwt); + else if (s.workflows[0]) setWorkflow(s.workflows[0]); + }).catch((e) => setError(e instanceof Error ? e.message : "Failed to load harness")).finally(() => setLoading(false)); + }, [open]); + if (!open) return null; + const runWf = async () => { + setRunning(true); + setResult(null); + setError(null); + try { + const res = await harnessRunWorkflow({ data: { + workflow, + feature: feature || "feature", + backend: backend || "mock" + } }); + setResult(res); + toast.success(`Workflow done · ${res.runId}`); + } catch (e) { + const msg = e instanceof Error ? e.message : "Run failed"; + setError(msg); + toast.error(msg); + } finally { + setRunning(false); + } + }; + const runAg = async () => { + setRunning(true); + setResult(null); + setError(null); + try { + const res = await harnessRunAgent({ data: { + agent: agentName, + message, + backend: backend || "mock" + } }); + setResult(res); + toast.success(`Agent done · ${res.runId}`); + } catch (e) { + const msg = e instanceof Error ? e.message : "Run failed"; + setError(msg); + toast.error(msg); + } finally { + setRunning(false); + } + }; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "fixed inset-0 z-[120] flex items-center justify-center p-4", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "absolute inset-0 z-0 bg-black/40", + "aria-label": "Dismiss", + onClick: () => { + if (!running) onOpenChange(false); + } + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + role: "dialog", + "aria-modal": "true", + "aria-labelledby": "harness-title", + className: "relative z-10 flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-border bg-background shadow-2xl", + onClick: (e) => e.stopPropagation(), + onMouseDown: (e) => e.stopPropagation(), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "border-b border-border px-6 py-4", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-start justify-between gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("h2", { + id: "harness-title", + className: "flex items-center gap-2 text-lg font-semibold", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Terminal, { className: "size-4" }), "Meta-harness · CLI agents"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "mt-1 text-sm text-muted-foreground", + children: "Plan → Implement → Review → Validate. Swap backends without rewriting the workflow." + })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "rounded-md p-1.5 text-muted-foreground hover:bg-muted", + onClick: () => onOpenChange(false), + "aria-label": "Close", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(X, { className: "size-4" }) + })] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "mt-3 flex flex-wrap gap-1.5", + children: [ + [ + "workflow", + "Workflow", + Workflow + ], + [ + "agent", + "Single agent", + Bot + ], + [ + "backends", + "Backends", + Zap + ] + ].map(([id, label, Icon]) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + onClick: () => setTab(id), + className: cn("inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium", tab === id ? "bg-foreground text-background" : "bg-muted text-muted-foreground"), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { className: "size-3" }), label] + }, id)) + })] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "min-h-0 flex-1 space-y-4 overflow-y-auto px-6 py-5 text-sm", + children: loading ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin" }), " Loading harness…"] + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [ + error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive", + children: error + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-xs font-medium text-muted-foreground", + children: "Backend slot (executor.harness)" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", { + className: "h-9 w-full rounded-md border border-border bg-background px-2 text-sm", + value: backend, + onChange: (e) => setBackend(e.target.value), + children: backends.map((b) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("option", { + value: b.id, + children: [ + b.available ? "●" : "○", + " ", + b.label, + " (", + b.id, + ")" + ] + }, b.id)) + })] + }), + tab === "workflow" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-xs font-medium text-muted-foreground", + children: "Workflow" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", { + className: "h-9 w-full rounded-md border border-border bg-background px-2 text-sm", + value: workflow, + onChange: (e) => setWorkflow(e.target.value), + children: workflows.map((w) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { + value: w, + children: w + }, w)) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-xs font-medium text-muted-foreground", + children: "Feature" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + value: feature, + onChange: (e) => setFeature(e.target.value) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + disabled: running || !workflow, + onClick: () => void runWf(), + children: [running ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Play, { className: "size-4" }), "Run workflow"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { + className: "overflow-x-auto rounded-lg border border-border bg-muted/40 p-3 text-[11px] leading-relaxed text-muted-foreground", + children: `wks harness workflow ${workflow.replace(/\.ya?ml$/, "")} \\\n --feature "${feature}" --backend ${backend}` + }) + ] + }), + tab === "agent" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-xs font-medium text-muted-foreground", + children: "Agent YAML" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", { + className: "h-9 w-full rounded-md border border-border bg-background px-2 text-sm", + value: agentName, + onChange: (e) => setAgentName(e.target.value), + children: agents.map((a) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { + value: a.replace(/\.ya?ml$/, ""), + children: a + }, a)) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-xs font-medium text-muted-foreground", + children: "Message" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, { + value: message, + onChange: (e) => setMessage(e.target.value) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + disabled: running, + onClick: () => void runAg(), + children: [running ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Play, { className: "size-4" }), "Run agent"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { + className: "overflow-x-auto rounded-lg border border-border bg-muted/40 p-3 text-[11px] text-muted-foreground", + children: `wks harness run ${agentName} --message "${message}" --backend ${backend}` + }) + ] + }), + tab === "backends" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "text-xs text-muted-foreground", + children: [ + "Install CLIs locally for live runs; ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "mock" }), + " always works in preview. Grok Build via ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "grok agent stdio" }), + " (ACP)." + ] + }), backends.map((b) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-start gap-2 rounded-lg border border-border px-3 py-2", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: cn("mt-0.5 size-2 shrink-0 rounded-full", b.available ? "bg-emerald-500" : "bg-muted-foreground/40") }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "min-w-0 flex-1", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "font-medium", + children: b.label + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "text-[11px] text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: b.id }), b.command ? ` · ${b.command}` : ""] + }), + b.notes && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "mt-0.5 text-[11px] text-muted-foreground", + children: b.notes + }) + ] + }), + b.available && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Check, { className: "size-3.5 text-emerald-600" }) + ] + }, b.id))] + }), + result && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-2 rounded-xl border border-border p-3", + "data-testid": "harness-result", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex flex-wrap items-center gap-2 text-xs", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: cn("rounded-full px-2 py-0.5 font-medium", result.ok ? "bg-emerald-500/15 text-emerald-800 dark:text-emerald-300" : "bg-destructive/10 text-destructive"), + children: result.ok ? "ok" : "failed" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + "data-volatile": true, + className: "text-muted-foreground", + children: [ + result.runId, + " · ", + result.backend, + " · ", + result.durationMs, + "ms" + ] + }), + result.planPath && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "text-muted-foreground", + children: ["plan: ", result.planPath] + }) + ] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { + className: "max-h-48 overflow-auto whitespace-pre-wrap rounded-md bg-muted/50 p-2 text-[11px] leading-relaxed", + children: result.summary + })] + }) + ] }) + })] + })] + }); +} +/** +* Desktop (Tauri) helpers — safe to import from web; no-ops when not in Tauri. +*/ +function isTauri() { + if (typeof window === "undefined") return false; + const w = window; + return Boolean(w.__TAURI_INTERNALS__ || w.__TAURI__ || w.__WORKSPACE_DESKTOP__); +} +async function getDesktopInfo() { + if (!isTauri()) return null; + try { + const { invoke } = await import("../_libs/tauri-apps__api.mjs").then((n) => n.t); + return await invoke("desktop_info"); + } catch { + return { isDesktop: true }; + } +} +function SidebarAction({ icon, label, onClick }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + onClick, + className: "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-sidebar-fg transition-colors hover:bg-sidebar-hover", + children: [icon, /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "truncate", + children: label + })] + }); +} +function Sidebar({ onOpenSearch, mobile, onNavigate }) { + const name = useWorkspace((s) => s.name); + const pages = useWorkspace((s) => s.pages); + const activePageId = useWorkspace((s) => s.activePageId); + const theme = useWorkspace((s) => s.theme); + const storageMode = useWorkspace((s) => s.storageMode); + const syncStatus = useWorkspace((s) => s.syncStatus); + const setActivePage = useWorkspace((s) => s.setActivePage); + const createPage = useWorkspace((s) => s.createPage); + const deletePage = useWorkspace((s) => s.deletePage); + const restorePage = useWorkspace((s) => s.restorePage); + const permanentlyDeletePage = useWorkspace((s) => s.permanentlyDeletePage); + const duplicatePage = useWorkspace((s) => s.duplicatePage); + const updatePage = useWorkspace((s) => s.updatePage); + const toggleSidebar = useWorkspace((s) => s.toggleSidebar); + const setTheme = useWorkspace((s) => s.setTheme); + const setName = useWorkspace((s) => s.setName); + const resetWorkspace = useWorkspace((s) => s.resetWorkspace); + const { user } = useCurrentUserState(); + const [expanded, setExpanded] = (0, import_react.useState)({}); + const [trashOpen, setTrashOpen] = (0, import_react.useState)(false); + const [settingsOpen, setSettingsOpen] = (0, import_react.useState)(false); + const [aiWizardOpen, setAiWizardOpen] = (0, import_react.useState)(false); + const [aiWizardStep, setAiWizardStep] = (0, import_react.useState)("welcome"); + const aiSetup = useAiSettings(); + const [linkFolderOpen, setLinkFolderOpen] = (0, import_react.useState)(false); + const [ioOpen, setIoOpen] = (0, import_react.useState)(false); + const [harnessOpen, setHarnessOpen] = (0, import_react.useState)(false); + const mounts = useMarkdownMounts((s) => s.mounts); + const mountSelection = useMarkdownMounts((s) => s.selection); + const setMountSelection = useMarkdownMounts((s) => s.setSelection); + const removeMount = useMarkdownMounts((s) => s.removeMount); + const [mountExpanded, setMountExpanded] = (0, import_react.useState)({ mount_sample: true }); + const [mountChildren, setMountChildren] = (0, import_react.useState)({}); + const [desktopLabel, setDesktopLabel] = (0, import_react.useState)(null); + const [cliSummary, setCliSummary] = (0, import_react.useState)(null); + (0, import_react.useEffect)(() => { + if (!isTauri()) return; + getDesktopInfo().then((info) => { + if (info?.isDesktop) setDesktopLabel(info.platform ? `Desktop · ${info.platform}` : "Desktop app"); + }); + }, []); + (0, import_react.useEffect)(() => { + getAiStatus().then((s) => { + const clis = s.clis; + if (clis?.length) setCliSummary(clis.map((c) => `${c.label.split(" ")[0]} ${c.available ? "✓" : "·"}`).join(" · ")); + }).catch(() => setCliSummary(null)); + }, []); + const goPage = (0, import_react.useCallback)((id) => { + setActivePage(id); + setMountSelection(null); + onNavigate?.(); + }, [ + setActivePage, + setMountSelection, + onNavigate + ]); + const favorites = (0, import_react.useMemo)(() => pages.filter((p) => !p.archived && p.favorite), [pages]); + const trash = (0, import_react.useMemo)(() => pages.filter((p) => p.archived), [pages]); + const roots = (0, import_react.useMemo)(() => pages.filter((p) => !p.archived && !p.parentId).sort((a, b) => a.createdAt - b.createdAt), [pages]); + const childrenOf = (0, import_react.useCallback)((parentId) => pages.filter((p) => !p.archived && p.parentId === parentId).sort((a, b) => a.createdAt - b.createdAt), [pages]); + const loadMountKids = async (mountId) => { + const m = mounts.find((x) => x.id === mountId); + if (!m) return; + try { + if (m.kind === "server" && m.serverPath) { + const res = await listServerMount({ data: { + root: m.serverPath, + relPath: "" + } }); + const entries = Array.isArray(res) ? res : []; + setMountChildren((c) => ({ + ...c, + [mountId]: entries.map((e) => ({ + name: e.name, + relPath: e.relPath, + kind: e.kind + })) + })); + } else if (m.kind === "browser") { + const handle = await loadDirectoryHandle(mountId); + if (!handle) { + setMountChildren((c) => ({ + ...c, + [mountId]: [] + })); + return; + } + const entries = await listBrowserDir(handle, ""); + setMountChildren((c) => ({ + ...c, + [mountId]: entries + })); + } + } catch { + setMountChildren((c) => ({ + ...c, + [mountId]: [] + })); + } + }; + const openMount = (mountId, relPath) => { + setMountSelection({ + mountId, + relPath + }); + setActivePage(null); + onNavigate?.(); + }; + const renderTree = (parentId, depth) => { + return (parentId === null ? roots : childrenOf(parentId)).map((page) => { + const hasKids = childrenOf(page.id).length > 0; + const isOpen = expanded[page.id] ?? depth < 1; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: cn("group flex items-center gap-0.5 rounded-md pr-1", activePageId === page.id && !mountSelection ? "bg-sidebar-active text-foreground" : "hover:bg-sidebar-hover"), + style: { paddingLeft: 8 + depth * 12 }, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground", + onClick: () => setExpanded((e) => ({ + ...e, + [page.id]: !isOpen + })), + "aria-label": isOpen ? "Collapse" : "Expand", + children: hasKids ? isOpen ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronDown, { className: "size-3.5" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: "size-3.5" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "size-3.5" }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + className: "flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm", + onClick: () => goPage(page.id), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "shrink-0 text-sm", + children: page.icon || "📄" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "truncate", + children: page.title || "Untitled" + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + "data-hover-reveal": true, + className: "flex items-center opacity-0 group-hover:opacity-100", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenu, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuTrigger, { + asChild: true, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10", + "aria-label": "Page menu", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Ellipsis, { className: "size-3.5 text-muted-foreground" }) + }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuContent, { + align: "start", + className: "w-48", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: () => updatePage(page.id, { favorite: !page.favorite }), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Star, { className: "size-4" }), page.favorite ? "Unfavorite" : "Favorite"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: () => { + createPage({ parentId: page.id }); + setExpanded((e) => ({ + ...e, + [page.id]: true + })); + }, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-4" }), " Add sub-page"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: () => duplicatePage(page.id), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Copy, { className: "size-4" }), " Duplicate"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator, {}), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + className: "text-destructive focus:text-destructive", + onClick: () => deletePage(page.id), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trash2, { className: "size-4" }), " Delete"] + }) + ] + })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10", + "aria-label": "New sub-page", + onClick: () => { + createPage({ parentId: page.id }); + setExpanded((e) => ({ + ...e, + [page.id]: true + })); + }, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-3.5 text-muted-foreground" }) + })] + }) + ] + }), hasKids && isOpen && renderTree(page.id, depth + 1)] }, page.id); + }); + }; + const syncIcon = storageMode === "database" ? syncStatus === "saving" || syncStatus === "pending" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Cloud, { className: "size-3.5 animate-pulse text-muted-foreground" }) : syncStatus === "error" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CloudOff, { className: "size-3.5 text-destructive" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Cloud, { className: "size-3.5 text-emerald-600" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CloudOff, { className: "size-3.5 text-muted-foreground" }); + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("aside", { + className: cn("flex h-full flex-col border-r border-sidebar-border bg-sidebar text-sidebar-fg", mobile ? "w-full" : "w-[260px] min-w-[260px]"), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 px-3 pb-1 pt-3", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + className: "flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-sidebar-hover", + onClick: () => setSettingsOpen(true), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "flex size-6 shrink-0 items-center justify-center rounded-md bg-foreground text-[11px] font-semibold text-background", + children: name.slice(0, 1).toUpperCase() || "W" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "truncate text-sm font-semibold text-foreground", + children: name + }), + syncIcon + ] + }), !mobile && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-sidebar-hover", + onClick: () => toggleSidebar(), + "aria-label": "Collapse sidebar", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PanelLeftClose, { className: "size-4" }) + })] + }), + desktopLabel && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mx-3 mb-1 flex items-center gap-1.5 rounded-md bg-muted/50 px-2 py-1 text-[10px] font-medium text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Monitor, { className: "size-3" }), desktopLabel] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-0.5 px-2 py-1", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { + icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Search, { className: "size-4" }), + label: "Search", + onClick: onOpenSearch + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { + icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-4" }), + label: "New page", + onClick: () => { + const id = createPage(); + goPage(id); + } + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { + icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FileDown, { className: "size-4" }), + label: "Import / export", + onClick: () => setIoOpen(true) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { + icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link2, { className: "size-4" }), + label: "Link markdown", + onClick: () => setLinkFolderOpen(true) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { + icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Terminal, { className: "size-4" }), + label: "Agent harness", + onClick: () => setHarnessOpen(true) + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(ScrollArea, { + className: "min-h-0 flex-1 px-2", + children: [ + favorites.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mb-3", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground", + children: "Favorites" + }), favorites.map((page) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + className: cn("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm", activePageId === page.id && !mountSelection ? "bg-sidebar-active text-foreground" : "hover:bg-sidebar-hover"), + onClick: () => goPage(page.id), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: page.icon || "📄" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "truncate", + children: page.title || "Untitled" + })] + }, page.id))] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mb-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground", + children: "Private" + }), + renderTree(null, 0), + roots.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "px-2 py-2 text-xs text-muted-foreground", + children: "No pages yet" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mb-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground", + children: "Linked markdown" + }), + mounts.map((m) => { + const open = mountExpanded[m.id] ?? false; + const kids = mountChildren[m.id] ?? []; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mb-0.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "group flex items-center gap-0.5 rounded-md pr-1 hover:bg-sidebar-hover", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground", + onClick: () => { + setMountExpanded((e) => ({ + ...e, + [m.id]: !open + })); + if (!open) loadMountKids(m.id); + }, + children: open ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronDown, { className: "size-3.5" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: "size-3.5" }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + className: "flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm", + onClick: () => { + setMountExpanded((e) => ({ + ...e, + [m.id]: true + })); + loadMountKids(m.id); + openMount(m.id, ""); + }, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link2, { className: "size-3.5 shrink-0 text-muted-foreground" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "truncate font-medium", + children: m.name + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + "data-hover-reveal": true, + className: "flex size-6 items-center justify-center rounded opacity-0 group-hover:opacity-100 hover:bg-black/5", + title: "Unlink", + onClick: () => removeMount(m.id), + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Unlink, { className: "size-3 text-muted-foreground" }) + }) + ] + }), open && kids.map((k) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + className: cn("flex w-full items-center gap-2 rounded-md py-1.5 pl-8 pr-2 text-left text-sm", mountSelection?.mountId === m.id && mountSelection.relPath === k.relPath ? "bg-sidebar-active text-foreground" : "text-sidebar-fg hover:bg-sidebar-hover"), + onClick: () => void openMount(m.id, k.relPath), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-xs", + children: k.kind === "dir" ? "📁" : "📝" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "truncate", + children: k.name + })] + }, k.relPath))] + }, m.id); + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "px-2 py-1 text-[11px] text-muted-foreground", + children: "Link folder (no import)" + }) + ] + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-0.5 border-t border-sidebar-border px-2 py-2", + children: [ + !user && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Link, { + to: "/login", + className: "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-sidebar-hover", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(LogIn, { className: "size-4" }), "Sign in to sync"] + }), + user && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "px-1 py-1", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(UserButton, {}) + }), + !user && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "px-2 py-0.5 text-[11px] text-muted-foreground", + children: "Local only · Sign in to sync" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { + icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trash2, { className: "size-4" }), + label: "Trash", + onClick: () => setTrashOpen(true) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { + icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Settings, { className: "size-4" }), + label: "Settings", + onClick: () => setSettingsOpen(true) + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, { + open: trashOpen, + onOpenChange: setTrashOpen, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, { + className: "max-w-md", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogTitle, { children: "Trash" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogDescription, { children: "Restored pages return to the top level of your workspace." })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "max-h-72 space-y-1 overflow-y-auto", + children: [trash.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-sm text-muted-foreground", + children: "Trash is empty" + }), trash.map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 rounded-md border border-border px-2 py-1.5", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: p.icon || "📄" }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "min-w-0 flex-1 truncate text-sm", + children: p.title || "Untitled" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + size: "sm", + variant: "outline", + onClick: () => restorePage(p.id), + children: "Restore" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + size: "sm", + variant: "ghost", + className: "text-destructive", + onClick: () => permanentlyDeletePage(p.id), + children: "Delete" + }) + ] + }, p.id))] + })] + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, { + open: settingsOpen, + onOpenChange: setSettingsOpen, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, { + className: "max-w-md", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogTitle, { children: "Settings" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogDescription, { children: "Workspace preferences and AI" })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-4 text-sm", + children: [ + desktopLabel && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Monitor, { className: "size-3.5" }), + "Running as ", + desktopLabel, + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-muted-foreground", + children: "· Tauri standalone" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { + className: "block space-y-1.5", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-xs font-medium text-muted-foreground", + children: "Workspace name" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + className: "h-9 w-full rounded-md border border-border bg-background px-3 text-sm", + value: name, + onChange: (e) => setName(e.target.value) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center justify-between", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-sm", + children: "Theme" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex gap-1", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: theme === "light" ? "default" : "outline", + onClick: () => setTheme("light"), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sun, { className: "size-3.5" }), " Light"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: theme === "dark" ? "default" : "outline", + onClick: () => setTheme("dark"), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Moon, { className: "size-3.5" }), " Dark"] + })] + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "rounded-lg border border-border p-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 font-medium", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-4" }), " AI"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "mt-1 text-xs text-muted-foreground", + children: [ + "Backend: ", + BACKEND_META[aiSetup.backend]?.label ?? aiSetup.backend, + !BACKEND_META[aiSetup.backend]?.isCli && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [ + " ", + "· ", + PROVIDER_META[aiSetup.provider]?.label, + " · ", + aiSetup.model + ] }) + ] + }), + cliSummary && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "mt-1 text-[11px] text-muted-foreground", + children: ["CLIs: ", cliSummary] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + size: "sm", + className: "mt-2", + variant: "secondary", + onClick: () => { + setAiWizardStep("provider"); + setAiWizardOpen(true); + }, + children: "Configure AI" + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "rounded-lg border border-border p-3 text-xs text-muted-foreground", + children: [ + "Storage: ", + storageMode === "database" ? "Database (synced)" : "Local only", + storageMode === "database" && ` · ${syncStatus}` + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + variant: "outline", + className: "w-full text-destructive", + onClick: () => { + if (confirm("Reset workspace to seed pages? This cannot be undone.")) { + resetWorkspace(); + setSettingsOpen(false); + } + }, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(RotateCcw, { className: "size-4" }), " Reset workspace"] + }) + ] + })] + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MarkdownIODialog, { + open: ioOpen, + onOpenChange: setIoOpen + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LinkFolderDialog, { + open: linkFolderOpen, + onOpenChange: setLinkFolderOpen + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HarnessPanel, { + open: harnessOpen, + onOpenChange: setHarnessOpen + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AiSetupWizard, { + open: aiWizardOpen, + onOpenChange: setAiWizardOpen, + initialStep: aiWizardStep + }) + ] + }); +} +var Popover = Popover$1; +var PopoverTrigger = PopoverTrigger$1; +function PopoverContent({ className, align = "center", sideOffset = 6, ...props }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PopoverPortal, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PopoverContent$1, { + align, + sideOffset, + className: cn("z-50 w-72 rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-lg outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95", className), + ...props + }) }); +} +var BLOCK_TYPES = [ + { + type: "paragraph", + label: "Text", + description: "Just start writing with plain text.", + icon: Type, + keywords: [ + "text", + "paragraph", + "plain" + ], + placeholder: "Type '/' for commands" + }, + { + type: "heading1", + label: "Heading 1", + description: "Big section heading.", + icon: Heading1, + keywords: [ + "h1", + "title", + "heading" + ], + placeholder: "Heading 1" + }, + { + type: "heading2", + label: "Heading 2", + description: "Medium section heading.", + icon: Heading2, + keywords: [ + "h2", + "heading", + "subtitle" + ], + placeholder: "Heading 2" + }, + { + type: "heading3", + label: "Heading 3", + description: "Small section heading.", + icon: Heading3, + keywords: ["h3", "heading"], + placeholder: "Heading 3" + }, + { + type: "bullet", + label: "Bulleted list", + description: "Create a simple bulleted list.", + icon: List, + keywords: [ + "ul", + "list", + "bullet", + "unordered" + ], + placeholder: "List item" + }, + { + type: "numbered", + label: "Numbered list", + description: "Create a list with numbering.", + icon: ListOrdered, + keywords: [ + "ol", + "list", + "number", + "ordered" + ], + placeholder: "List item" + }, + { + type: "todo", + label: "To-do list", + description: "Track tasks with a to-do checkbox.", + icon: SquareCheckBig, + keywords: [ + "todo", + "task", + "checkbox", + "check" + ], + placeholder: "To-do" + }, + { + type: "toggle", + label: "Toggle", + description: "Hide and show content inside.", + icon: ChevronRight, + keywords: [ + "toggle", + "collapse", + "details" + ], + placeholder: "Toggle heading" + }, + { + type: "quote", + label: "Quote", + description: "Capture a quote.", + icon: Quote, + keywords: [ + "quote", + "blockquote", + "cite" + ], + placeholder: "Empty quote" + }, + { + type: "callout", + label: "Callout", + description: "Make writing stand out.", + icon: MessageSquare, + keywords: [ + "callout", + "note", + "info", + "tip" + ], + placeholder: "Callout" + }, + { + type: "code", + label: "Code", + description: "Capture a code snippet.", + icon: CodeXml, + keywords: [ + "code", + "snippet", + "pre" + ], + placeholder: "Code" + }, + { + type: "mermaid", + label: "Mermaid", + description: "Diagram with Mermaid syntax.", + icon: Workflow, + keywords: [ + "mermaid", + "diagram", + "flowchart", + "sequence", + "graph" + ], + placeholder: "flowchart TD\n A[Start] --> B[End]" + }, + { + type: "ai", + label: "AI", + description: "Generate from the rest of this page.", + icon: Sparkles, + keywords: [ + "ai", + "gpt", + "grok", + "summary", + "assistant", + "llm" + ], + placeholder: "Summarize this page as a launch checklist…" + }, + { + type: "divider", + label: "Divider", + description: "Visually divide blocks.", + icon: Minus, + keywords: [ + "divider", + "line", + "hr", + "separator" + ], + placeholder: "" + } +]; +function getBlockMeta(type) { + return BLOCK_TYPES.find((b) => b.type === type) ?? BLOCK_TYPES[0]; +} +function filterBlockTypes(query) { + const q = query.trim().toLowerCase(); + if (!q) return BLOCK_TYPES; + return BLOCK_TYPES.filter((b) => b.label.toLowerCase().includes(q) || b.description.toLowerCase().includes(q) || b.keywords.some((k) => k.includes(q))); +} +function SlashMenu({ query, selectedIndex, onSelect, onHover, position }) { + const items = (0, import_react.useMemo)(() => filterBlockTypes(query), [query]); + const listRef = (0, import_react.useRef)(null); + (0, import_react.useEffect)(() => { + (listRef.current?.querySelector(`[data-index="${selectedIndex}"]`))?.scrollIntoView({ block: "nearest" }); + }, [selectedIndex]); + if (items.length === 0) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "fixed z-50 w-72 overflow-hidden rounded-xl border border-border bg-popover p-3 text-sm text-muted-foreground shadow-xl", + style: { + top: position.top, + left: position.left + }, + children: "No matching blocks" + }); + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + ref: listRef, + className: "fixed z-50 max-h-72 w-72 overflow-y-auto rounded-xl border border-border bg-popover p-1.5 shadow-xl", + style: { + top: position.top, + left: Math.min(position.left, window.innerWidth - 300) + }, + role: "listbox", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "px-2 py-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground", + children: "Basic blocks" + }), items.map((item, index) => { + const Icon = item.icon; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + "data-index": index, + role: "option", + "aria-selected": index === selectedIndex, + className: cn("flex w-full items-start gap-2.5 rounded-lg px-2 py-2 text-left transition-colors", index === selectedIndex ? "bg-muted" : "hover:bg-muted/70"), + onMouseEnter: () => onHover(index), + onMouseDown: (e) => { + e.preventDefault(); + onSelect(item.type); + }, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { className: "size-4" }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "min-w-0", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "block text-sm font-medium text-foreground", + children: item.label + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "block truncate text-xs text-muted-foreground", + children: item.description + })] + })] + }, item.type); + })] + }); +} +var mermaidReady = null; +function loadMermaid() { + if (!mermaidReady) mermaidReady = import("../_libs/mermaid+[...].mjs").then((n) => n.t).then((mod) => { + const mermaid = mod.default; + mermaid.initialize({ + startOnLoad: false, + securityLevel: "strict", + theme: document.documentElement.classList.contains("dark") ? "dark" : "neutral", + fontFamily: "inherit" + }); + return mermaid; + }); + return mermaidReady; +} +function MermaidDiagram({ source, className }) { + const reactId = (0, import_react.useId)().replace(/:/g, ""); + const containerRef = (0, import_react.useRef)(null); + const [error, setError] = (0, import_react.useState)(null); + const [svg, setSvg] = (0, import_react.useState)(""); + (0, import_react.useEffect)(() => { + let cancelled = false; + const code = source.trim(); + if (!code) { + setSvg(""); + setError(null); + return; + } + (async () => { + try { + const mermaid = await loadMermaid(); + mermaid.initialize({ + startOnLoad: false, + securityLevel: "strict", + theme: document.documentElement.classList.contains("dark") ? "dark" : "neutral", + fontFamily: "inherit" + }); + const id = `mmd_${reactId}_${Math.random().toString(36).slice(2, 8)}`; + const { svg: rendered } = await mermaid.render(id, code); + if (!cancelled) { + setSvg(rendered); + setError(null); + } + } catch (e) { + if (!cancelled) { + setSvg(""); + setError(e instanceof Error ? e.message : "Invalid Mermaid diagram"); + } + } + })(); + return () => { + cancelled = true; + }; + }, [source, reactId]); + if (!source.trim()) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-sm text-muted-foreground", + children: "Write Mermaid syntax (e.g. flowchart TD) — diagram previews here." + }); + if (error) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive", + children: error + }); + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + ref: containerRef, + className: cn("overflow-x-auto rounded-md border border-border bg-background px-3 py-4 [&_svg]:mx-auto [&_svg]:max-w-full", className), + dangerouslySetInnerHTML: svg ? { __html: svg } : void 0 + }); +} +/** +* Stream AI generation via SSE (`POST /api/ai/stream`). +* Prefers coding-agent CLIs when selected in settings (claude / codex / grok). +*/ +async function streamAi(opts) { + const res = await fetch("/api/ai/stream", { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "text/event-stream" + }, + body: JSON.stringify({ + ...opts.request, + clientSettings: opts.clientSettings, + backend: opts.backend + }), + signal: opts.signal + }); + if (!res.ok) { + const msg = await res.text().catch(() => res.statusText); + throw new Error(msg || `Stream failed (${res.status})`); + } + if (!res.body) throw new Error("No response body for stream"); + const reader = res.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + let full = ""; + let final = null; + let streamError = null; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + const parts = buffer.split("\n\n"); + buffer = parts.pop() ?? ""; + for (const part of parts) { + const line = part.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).join(""); + if (!line) continue; + let ev; + try { + ev = JSON.parse(line); + } catch { + continue; + } + if (ev.type === "token" && ev.text) { + full += ev.text; + opts.onToken?.(ev.text, full); + } else if (ev.type === "status" && ev.message) opts.onStatus?.(ev.message); + else if (ev.type === "done") { + if (ev.text) full = ev.text; + if (ev.result) final = ev.result; + else final = { + text: full, + provider: "local" + }; + opts.onDone?.(final, full); + } else if (ev.type === "error") { + streamError = ev.message || "Stream error"; + opts.onError?.(streamError); + } + } + } + if (streamError && !final && !full.trim()) throw new Error(streamError); + return final ?? { + text: full, + provider: "local" + }; +} +var PRESETS$1 = [ + { + action: "summarize", + label: "Summary", + icon: FileText, + hint: "Condense the page" + }, + { + action: "action_items", + label: "Todos", + icon: ListTodo, + hint: "Extract action items" + }, + { + action: "table", + label: "Table", + icon: Table2, + hint: "Markdown table" + }, + { + action: "outline", + label: "Outline", + icon: ListTree, + hint: "Hierarchical outline" + }, + { + action: "mermaid", + label: "Diagram", + icon: Workflow, + hint: "Mermaid flowchart" + } +]; +function providerLabel$1(provider, model) { + if (provider === "claude-cli") return "Claude Code CLI"; + if (provider === "codex-cli") return "Codex CLI"; + if (provider === "grok-cli") return "Grok CLI"; + if (provider === "deepagents") return `Deep Agents · ${model ?? "model"}`; + if (provider === "direct") return model ?? "Direct API"; + if (provider === "xai") return model ?? "Grok"; + return "Local demo AI"; +} +function AiBlockPanel({ content, aiOutput, aiError, pageTitle, pageText, onChangePrompt, onResult }) { + const [loading, setLoading] = (0, import_react.useState)(false); + const [provider, setProvider] = (0, import_react.useState)(null); + const [wizardOpen, setWizardOpen] = (0, import_react.useState)(false); + const [streamPreview, setStreamPreview] = (0, import_react.useState)(""); + const [status, setStatus] = (0, import_react.useState)(null); + const abortRef = (0, import_react.useRef)(null); + const stop = () => { + abortRef.current?.abort(); + abortRef.current = null; + setLoading(false); + setStatus("Stopped"); + }; + const execute = async (action, instruction) => { + setLoading(true); + setStreamPreview(""); + setStatus(null); + const settings = snapshotAiSettings(); + const preferStream = settings.preferStreaming !== false; + const isCli = settings.backend === "claude-cli" || settings.backend === "codex-cli" || settings.backend === "grok-cli"; + const useStream = preferStream && (isCli || settings.backend === "direct" || settings.backend === "deepagents"); + try { + if (useStream) { + const ac = new AbortController(); + abortRef.current = ac; + const res = await streamAi({ + request: { + action, + instruction: instruction ?? content, + pageTitle, + pageText + }, + clientSettings: settings, + backend: settings.backend, + signal: ac.signal, + onToken: (_t, full) => setStreamPreview(full), + onStatus: (m) => setStatus(m) + }); + setProvider(providerLabel$1(res.provider, res.model)); + onResult({ + output: res.text || (res.blocks ? res.blocks.map((b) => `${b.type}: ${b.content}`).join("\n") : ""), + blocks: res.blocks + }); + setStreamPreview(""); + } else { + const res = await runAi({ data: { + action, + instruction: instruction ?? content, + pageTitle, + pageText, + clientSettings: settings + } }); + setProvider(providerLabel$1(res.provider, res.model)); + onResult({ + output: res.text || (res.blocks ? res.blocks.map((b) => `${b.type}: ${b.content}`).join("\n") : ""), + blocks: res.blocks + }); + } + } catch (e) { + if (e?.name === "AbortError") onResult({ + output: streamPreview, + error: "Generation stopped" + }); + else onResult({ + output: "", + error: e instanceof Error ? e.message : "AI request failed" + }); + } finally { + abortRef.current = null; + setLoading(false); + setStatus(null); + } + }; + const settingsSnap = snapshotAiSettings(); + const backendHint = BACKEND_META[settingsSnap.backend]?.label ?? settingsSnap.backend; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "w-full space-y-3 rounded-xl border border-border bg-muted/30 p-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 text-sm font-medium text-foreground", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "flex size-7 items-center justify-center rounded-md bg-foreground text-background", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-3.5" }) + }), + "AI block", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "ml-auto text-[11px] font-normal text-muted-foreground", + children: provider ?? backendHint + }) + ] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AiSetupBanner, { onOpen: () => setWizardOpen(true) }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-xs text-muted-foreground", + children: "Uses page context. Backends: Deep Agents, API keys, or coding CLIs (Claude Code / Codex / Grok) with live streaming when available." + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "flex flex-wrap gap-1.5", + children: PRESETS$1.map((p) => { + const Icon = p.icon; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "outline", + className: "bg-background", + disabled: loading, + title: p.hint, + onClick: () => void execute(p.action), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { className: "size-3.5" }), p.label] + }, p.action); + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { + className: "min-h-[64px] flex-1 resize-y rounded-md border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring/30", + placeholder: "Custom instruction…", + value: content, + onChange: (e) => onChangePrompt(e.target.value), + disabled: loading + }), loading ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "destructive", + onClick: stop, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Square, { className: "size-3.5" }), "Stop"] + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + disabled: !content.trim(), + onClick: () => void execute("custom", content), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Play, { className: "size-3.5" }), "Run"] + })] + }), + (loading || streamPreview) && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "rounded-lg border border-border bg-background p-3", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mb-1 flex items-center gap-2 text-[11px] text-muted-foreground", + children: [loading && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-3 animate-spin" }), status ?? (loading ? "Streaming…" : "Preview")] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { + className: "max-h-40 overflow-auto whitespace-pre-wrap text-xs leading-relaxed", + children: streamPreview || "…" + })] + }), + aiError && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-xs text-destructive", + children: aiError + }), + aiOutput && !streamPreview && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { + className: "max-h-48 overflow-auto rounded-lg border border-border bg-background p-3 text-xs", + children: aiOutput + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AiSetupWizard, { + open: wizardOpen, + onOpenChange: setWizardOpen + }) + ] + }); +} +var PRESETS = [ + { + id: "improve", + label: "Improve", + instruction: "Improve clarity and flow while preserving meaning." + }, + { + id: "shorter", + label: "Shorter", + instruction: "Make this shorter and more concise." + }, + { + id: "longer", + label: "Expand", + instruction: "Expand this with one more sentence of useful detail." + }, + { + id: "fix", + label: "Fix grammar", + instruction: "Fix grammar and spelling only." + }, + { + id: "pro", + label: "Professional", + instruction: "Rewrite in a clear, professional tone." + } +]; +function providerLabel(provider, model) { + if (provider === "claude-cli") return "Claude Code CLI"; + if (provider === "codex-cli") return "Codex CLI"; + if (provider === "grok-cli") return "Grok CLI"; + if (provider === "deepagents") return `Deep Agents · ${model ?? "model"}`; + if (provider === "direct") return model ?? "Direct API"; + if (provider === "xai") return model ?? "Grok"; + return "Local demo AI"; +} +function AiEditDialog({ open, onOpenChange, blockText, blockType, pageTitle, pageText, onApply }) { + const [instruction, setInstruction] = (0, import_react.useState)(""); + const [preview, setPreview] = (0, import_react.useState)(null); + const [loading, setLoading] = (0, import_react.useState)(false); + const [error, setError] = (0, import_react.useState)(null); + const [provider, setProvider] = (0, import_react.useState)(null); + const [status, setStatus] = (0, import_react.useState)(null); + const [wizardOpen, setWizardOpen] = (0, import_react.useState)(false); + const abortRef = (0, import_react.useRef)(null); + const stop = () => { + abortRef.current?.abort(); + abortRef.current = null; + setLoading(false); + }; + const run = async (instr) => { + setLoading(true); + setError(null); + setPreview(""); + setStatus(null); + const settings = snapshotAiSettings(); + const preferStream = settings.preferStreaming !== false; + const isCli = settings.backend === "claude-cli" || settings.backend === "codex-cli" || settings.backend === "grok-cli"; + const useStream = preferStream && (isCli || settings.backend === "direct" || settings.backend === "deepagents"); + try { + if (useStream) { + const ac = new AbortController(); + abortRef.current = ac; + const res = await streamAi({ + request: { + action: "edit_block", + instruction: instr, + blockText, + blockType, + pageTitle, + pageText + }, + clientSettings: settings, + backend: settings.backend, + signal: ac.signal, + onToken: (_t, full) => setPreview(full), + onStatus: (m) => setStatus(m) + }); + setPreview(res.text); + setProvider(providerLabel(res.provider, res.model)); + } else { + const res = await runAi({ data: { + action: "edit_block", + instruction: instr, + blockText, + blockType, + pageTitle, + pageText, + clientSettings: settings + } }); + setPreview(res.text); + setProvider(providerLabel(res.provider, res.model)); + } + } catch (e) { + if (e?.name !== "AbortError") setError(e instanceof Error ? e.message : "AI request failed"); + } finally { + abortRef.current = null; + setLoading(false); + setStatus(null); + } + }; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, { + open, + onOpenChange: (v) => { + if (!v) { + stop(); + setPreview(null); + setError(null); + setInstruction(""); + } + onOpenChange(v); + }, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, { + className: "max-w-lg", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogTitle, { + className: "flex items-center gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-4" }), "Edit block with AI"] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogDescription, { children: ["Rewrite this block. Uses your configured backend (API or Claude / Codex / Grok CLI) with streaming when available.", provider && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "mt-1 block text-xs text-muted-foreground", + children: provider + })] })] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AiSetupBanner, { onOpen: () => setWizardOpen(true) }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "rounded-md border border-border bg-muted/40 p-2 text-xs text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "font-medium text-foreground", + children: "Original" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "mt-1 line-clamp-4 whitespace-pre-wrap", + children: blockText || "(empty)" + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "flex flex-wrap gap-1.5", + children: PRESETS.map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "outline", + disabled: loading, + onClick: () => void run(p.instruction), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(WandSparkles, { className: "size-3.5" }), p.label] + }, p.id)) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + className: "h-9 flex-1 rounded-md border border-border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring/30", + placeholder: "Custom instruction…", + value: instruction, + onChange: (e) => setInstruction(e.target.value), + disabled: loading, + onKeyDown: (e) => { + if (e.key === "Enter" && instruction.trim()) run(instruction.trim()); + } + }), loading ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "destructive", + onClick: stop, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Square, { className: "size-3.5" }), "Stop"] + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + size: "sm", + disabled: !instruction.trim(), + onClick: () => void run(instruction.trim()), + children: "Run" + })] + }), + loading && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 text-xs text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-3.5 animate-spin" }), status ?? "Generating…"] + }), + error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-xs text-destructive", + children: error + }), + preview != null && preview !== "" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-2", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "text-xs font-medium text-muted-foreground", + children: "Preview" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { + className: cn("max-h-48 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-background p-3 text-sm", loading && "opacity-80"), + children: preview + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + className: "w-full", + disabled: loading, + onClick: () => { + onApply(preview); + onOpenChange(false); + }, + children: "Apply to block" + }) + ] + }) + ] + }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AiSetupWizard, { + open: wizardOpen, + onOpenChange: setWizardOpen + })] }); +} +function BlockRow({ block, index, isFocused, listNumber, pageTitle, pageText, onFocus, onChange, onTypeChange, onToggleCheck, onToggleCollapse, onEnter, onBackspaceEmpty, onMove, onDelete, onIndent, onPatch, onAiInsert, focusRequest, onFocusHandled, inputRefs }) { + const meta = getBlockMeta(block.type); + const areaRef = (0, import_react.useRef)(null); + const rowRef = (0, import_react.useRef)(null); + const [slashOpen, setSlashOpen] = (0, import_react.useState)(false); + const [slashQuery, setSlashQuery] = (0, import_react.useState)(""); + const [slashIndex, setSlashIndex] = (0, import_react.useState)(0); + const [slashPos, setSlashPos] = (0, import_react.useState)({ + top: 0, + left: 0 + }); + const [hovered, setHovered] = (0, import_react.useState)(false); + const [aiOpen, setAiOpen] = (0, import_react.useState)(false); + const setRef = (0, import_react.useCallback)((el) => { + areaRef.current = el; + if (el) inputRefs.current.set(block.id, el); + else inputRefs.current.delete(block.id); + }, [block.id, inputRefs]); + const autosize = (0, import_react.useCallback)(() => { + const el = areaRef.current; + if (!el) return; + el.style.height = "0px"; + el.style.height = `${Math.max(el.scrollHeight, 28)}px`; + }, []); + (0, import_react.useEffect)(() => { + autosize(); + }, [ + block.content, + block.type, + autosize + ]); + (0, import_react.useEffect)(() => { + if (focusRequest !== block.id) return; + const el = areaRef.current; + if (el) { + el.focus(); + const len = el.value.length; + el.setSelectionRange(len, len); + } + onFocusHandled(); + }, [ + focusRequest, + block.id, + onFocusHandled + ]); + const openSlash = (query) => { + const el = rowRef.current; + if (!el) return; + const rect = el.getBoundingClientRect(); + const left = Math.min(rect.left + 48, window.innerWidth - 300); + const top = rect.bottom + 280 > window.innerHeight ? Math.max(8, rect.top - 280) : rect.bottom + 4; + setSlashPos({ + top, + left + }); + setSlashQuery(query); + setSlashIndex(0); + setSlashOpen(true); + }; + const closeSlash = () => { + setSlashOpen(false); + setSlashQuery(""); + setSlashIndex(0); + }; + const applySlash = (type) => { + const content = block.content; + const slashIdx = content.lastIndexOf("/"); + const cleaned = slashIdx >= 0 ? content.slice(0, slashIdx) : content; + onChange(block.id, cleaned); + onTypeChange(block.id, type); + closeSlash(); + requestAnimationFrame(() => { + inputRefs.current.get(block.id)?.focus(); + }); + }; + const handleChange = (value) => { + onChange(block.id, value); + requestAnimationFrame(autosize); + const slashIdx = value.lastIndexOf("/"); + if (slashIdx >= 0) { + const after = value.slice(slashIdx + 1); + const before = value[slashIdx - 1]; + if ((slashIdx === 0 || before === " " || before === "\n") && !after.includes("\n")) { + openSlash(after); + return; + } + } + if (slashOpen) closeSlash(); + }; + const handleKeyDown = (e) => { + if (slashOpen) { + const items = filterBlockTypes(slashQuery); + if (e.key === "ArrowDown") { + e.preventDefault(); + setSlashIndex((i) => (i + 1) % Math.max(items.length, 1)); + return; + } + if (e.key === "ArrowUp") { + e.preventDefault(); + setSlashIndex((i) => (i - 1 + Math.max(items.length, 1)) % Math.max(items.length, 1)); + return; + } + if (e.key === "Enter" || e.key === "Tab") { + e.preventDefault(); + const pick = items[slashIndex]; + if (pick) applySlash(pick.type); + return; + } + if (e.key === "Escape") { + e.preventDefault(); + closeSlash(); + return; + } + } + if (e.key === "Enter" && !e.shiftKey && block.type !== "code" && block.type !== "mermaid") { + e.preventDefault(); + onEnter(block.id); + return; + } + if (e.key === "Backspace") { + const el = e.currentTarget; + if (!el.value && el.selectionStart === 0) { + e.preventDefault(); + onBackspaceEmpty(block.id); + return; + } + } + if (e.key === "Tab") { + e.preventDefault(); + onIndent(block.id, e.shiftKey ? -1 : 1); + } + if (e.key === "ArrowUp" && (e.metaKey || e.ctrlKey)) { + e.preventDefault(); + onMove(block.id, "up"); + } + if (e.key === "ArrowDown" && (e.metaKey || e.ctrlKey)) { + e.preventDefault(); + onMove(block.id, "down"); + } + }; + const indentStyle = { paddingLeft: `${(block.indent ?? 0) * 1.5}rem` }; + const canAiEdit = block.type !== "divider" && block.type !== "ai" && block.type !== "mermaid"; + if (block.type === "divider") return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + ref: rowRef, + "data-block-id": block.id, + "data-block-type": block.type, + className: "group relative flex items-center gap-1 py-2", + style: indentStyle, + onMouseEnter: () => setHovered(true), + onMouseLeave: () => setHovered(false), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockHandles, { + visible: hovered || isFocused, + canAiEdit: false, + onAdd: () => onEnter(block.id), + onMoveUp: () => onMove(block.id, "up"), + onMoveDown: () => onMove(block.id, "down"), + onDelete: () => onDelete(block.id), + onTypeChange: (t) => onTypeChange(block.id, t), + onAiEdit: () => setAiOpen(true) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("hr", { className: "w-full border-0 border-t border-border" })] + }); + if (block.type === "ai") return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + ref: rowRef, + "data-block-id": block.id, + "data-block-type": block.type, + className: "group relative py-1", + style: indentStyle, + onMouseEnter: () => setHovered(true), + onMouseLeave: () => setHovered(false), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockHandles, { + visible: hovered || isFocused, + canAiEdit: false, + onAdd: () => onEnter(block.id), + onMoveUp: () => onMove(block.id, "up"), + onMoveDown: () => onMove(block.id, "down"), + onDelete: () => onDelete(block.id), + onTypeChange: (t) => onTypeChange(block.id, t), + onAiEdit: () => void 0 + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "pl-1", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AiBlockPanel, { + content: block.content, + aiOutput: block.aiOutput, + aiError: block.aiError, + pageTitle, + pageText, + onChangePrompt: (v) => onChange(block.id, v), + onResult: ({ output, blocks, error }) => { + onPatch(block.id, { + aiOutput: output, + aiError: error + }); + if (blocks?.length) onAiInsert(block.id, blocks); + } + }) + })] + }); + if (block.type === "mermaid") { + const showSource = block.showSource ?? !block.content.trim(); + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + ref: rowRef, + "data-block-id": block.id, + "data-block-type": block.type, + className: "group relative py-1", + style: indentStyle, + onMouseEnter: () => setHovered(true), + onMouseLeave: () => setHovered(false), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockHandles, { + visible: hovered || isFocused, + canAiEdit: false, + onAdd: () => onEnter(block.id), + onMoveUp: () => onMove(block.id, "up"), + onMoveDown: () => onMove(block.id, "down"), + onDelete: () => onDelete(block.id), + onTypeChange: (t) => onTypeChange(block.id, t), + onAiEdit: () => void 0 + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-2 rounded-xl border border-border bg-muted/20 p-3", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center justify-between gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", + children: "Mermaid" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + size: "sm", + variant: "ghost", + className: "h-7 text-muted-foreground", + onClick: () => onPatch(block.id, { showSource: !showSource }), + children: showSource ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Eye, { className: "size-3.5" }), " Preview"] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CodeXml, { className: "size-3.5" }), " Edit source"] }) + })] + }), showSource ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { + ref: setRef, + value: block.content, + onChange: (e) => handleChange(e.target.value), + onFocus: () => onFocus(block.id), + onKeyDown: handleKeyDown, + placeholder: meta.placeholder, + rows: Math.max(4, block.content.split("\n").length), + spellCheck: false, + className: "w-full resize-y rounded-md border border-border bg-background px-3 py-2 font-mono text-sm leading-relaxed text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/40" + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MermaidDiagram, { source: block.content })] + }), + slashOpen && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SlashMenu, { + query: slashQuery, + selectedIndex: slashIndex, + onSelect: applySlash, + onHover: setSlashIndex, + position: slashPos + }) + ] + }); + } + const fieldClass = cn("block w-full resize-none overflow-hidden border-0 bg-background p-0 text-foreground shadow-none outline-none ring-0 focus:outline-none focus:ring-0", "placeholder:text-muted-foreground/60", block.type === "paragraph" && "text-base leading-relaxed", block.type === "heading1" && "text-3xl font-semibold leading-tight tracking-tight", block.type === "heading2" && "text-2xl font-semibold leading-tight tracking-tight", block.type === "heading3" && "text-xl font-semibold leading-snug tracking-tight", (block.type === "bullet" || block.type === "numbered") && "text-base leading-relaxed", block.type === "todo" && cn("text-base leading-relaxed", block.checked && "text-muted-foreground line-through"), block.type === "toggle" && "text-base font-medium leading-relaxed", block.type === "quote" && "text-base leading-relaxed text-muted-foreground", block.type === "callout" && "text-base leading-relaxed", block.type === "code" && "min-h-16 font-mono text-sm leading-relaxed"); + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + ref: rowRef, + "data-block-id": block.id, + "data-block-type": block.type, + className: cn("group relative flex items-start gap-1 rounded-md py-0.5", isFocused && "bg-muted/40"), + style: indentStyle, + onMouseEnter: () => setHovered(true), + onMouseLeave: () => setHovered(false), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockHandles, { + visible: hovered || isFocused, + canAiEdit, + onAdd: () => onEnter(block.id), + onMoveUp: () => onMove(block.id, "up"), + onMoveDown: () => onMove(block.id, "down"), + onDelete: () => onDelete(block.id), + onTypeChange: (t) => onTypeChange(block.id, t), + onAiEdit: () => setAiOpen(true) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: cn("flex min-w-0 flex-1 items-start gap-2 rounded-md px-1 py-1", block.type === "callout" && "border border-border bg-muted/50 px-3 py-2.5", block.type === "quote" && "border-l-2 border-foreground/25 pl-3", block.type === "code" && "border border-border bg-muted/60 px-3 py-2.5"), + children: [ + block.type === "bullet" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "mt-2.5 size-1.5 shrink-0 rounded-full bg-foreground/80" }), + block.type === "numbered" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "mt-1 w-5 shrink-0 text-right text-sm tabular-nums text-muted-foreground", + children: [listNumber ?? index + 1, "."] + }), + block.type === "todo" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: cn("mt-1.5 flex size-4 shrink-0 items-center justify-center rounded border transition-colors", block.checked ? "border-primary bg-primary text-primary-foreground" : "border-border bg-background hover:border-foreground/40"), + onClick: () => onToggleCheck(block.id), + "aria-label": block.checked ? "Mark incomplete" : "Mark complete", + children: block.checked && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Check, { + className: "size-3", + strokeWidth: 3 + }) + }), + block.type === "toggle" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "mt-1 flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted", + onClick: () => onToggleCollapse(block.id), + "aria-label": block.collapsed ? "Expand" : "Collapse", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: cn("size-4 text-muted-foreground transition-transform duration-150", !block.collapsed && "rotate-90") }) + }), + block.type === "callout" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "mt-1 shrink-0 text-base leading-none", + "aria-hidden": true, + children: "💡" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { + ref: setRef, + value: block.content, + onChange: (e) => handleChange(e.target.value), + onFocus: () => onFocus(block.id), + onKeyDown: handleKeyDown, + placeholder: meta.placeholder, + rows: 1, + spellCheck: block.type !== "code", + className: fieldClass + }) + ] + }), + slashOpen && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SlashMenu, { + query: slashQuery, + selectedIndex: slashIndex, + onSelect: applySlash, + onHover: setSlashIndex, + position: slashPos + }), + canAiEdit && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AiEditDialog, { + open: aiOpen, + onOpenChange: setAiOpen, + blockText: block.content, + blockType: block.type, + pageTitle, + pageText, + onApply: (text) => onChange(block.id, text) + }) + ] + }); +} +function BlockHandles({ visible, canAiEdit, onAdd, onMoveUp, onMoveDown, onDelete, onTypeChange, onAiEdit }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + "data-hover-reveal": true, + className: cn("absolute -left-12 top-1 flex items-center gap-0.5 opacity-0 transition-opacity max-sm:-left-10", visible && "opacity-100"), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "ghost", + size: "icon-sm", + className: "text-muted-foreground", + onClick: onAdd, + "aria-label": "Add block below", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-3.5" }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenu, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuTrigger, { + asChild: true, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "ghost", + size: "icon-sm", + className: "text-muted-foreground", + "aria-label": "Block menu", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(GripVertical, { className: "size-3.5" }) + }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuContent, { + align: "start", + className: "w-48", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuLabel, { children: "Block" }), + canAiEdit && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: onAiEdit, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-4" }), " Edit with AI"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: onMoveUp, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ArrowUp, { className: "size-4" }), " Move up"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: onMoveDown, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ArrowDown, { className: "size-4" }), " Move down"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuSub, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuSubTrigger, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Ellipsis, { className: "size-4" }), " Turn into"] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSubContent, { + className: "max-h-64 overflow-y-auto", + children: BLOCK_TYPES.map((t) => { + const Icon = t.icon; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: () => onTypeChange(t.type), + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { className: "size-4" }), + " ", + t.label + ] + }, t.type); + }) + })] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator, {}), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + className: "text-destructive focus:text-destructive", + onClick: onDelete, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trash2, { className: "size-4" }), " Delete"] + }) + ] + })] })] + }); +} +function blocksToPlainText(page) { + return page.blocks.filter((b) => b.type !== "ai" && b.type !== "divider").map((b) => { + return `${b.type === "heading1" ? "# " : b.type === "heading2" ? "## " : b.type === "heading3" ? "### " : b.type === "bullet" ? "- " : b.type === "numbered" ? "1. " : b.type === "todo" ? b.checked ? "[x] " : "[ ] " : b.type === "quote" ? "> " : b.type === "code" || b.type === "mermaid" ? "" : ""}${b.content}`.trim(); + }).filter(Boolean).join("\n"); +} +function PageEditor({ page }) { + const updatePage = useWorkspace((s) => s.updatePage); + const updateBlock = useWorkspace((s) => s.updateBlock); + const insertBlock = useWorkspace((s) => s.insertBlock); + const deleteBlock = useWorkspace((s) => s.deleteBlock); + const changeBlockType = useWorkspace((s) => s.changeBlockType); + const moveBlock = useWorkspace((s) => s.moveBlock); + const deletePage = useWorkspace((s) => s.deletePage); + const duplicatePage = useWorkspace((s) => s.duplicatePage); + const createPage = useWorkspace((s) => s.createPage); + const setBlocks = useWorkspace((s) => s.setBlocks); + const [focusedId, setFocusedId] = (0, import_react.useState)(null); + const [focusRequest, setFocusRequest] = (0, import_react.useState)(null); + const inputRefs = (0, import_react.useRef)(/* @__PURE__ */ new Map()); + const titleRef = (0, import_react.useRef)(null); + const pageText = (0, import_react.useMemo)(() => blocksToPlainText(page), [page]); + const listNumbers = (0, import_react.useMemo)(() => { + const map = /* @__PURE__ */ new Map(); + let n = 0; + for (const b of page.blocks) if (b.type === "numbered") { + n += 1; + map.set(b.id, n); + } else n = 0; + return map; + }, [page.blocks]); + (0, import_react.useEffect)(() => { + const el = titleRef.current; + if (!el) return; + el.style.height = "auto"; + el.style.height = `${el.scrollHeight}px`; + }, [page.title]); + const handleEnter = (0, import_react.useCallback)((blockId) => { + const newId = insertBlock(page.id, blockId, "paragraph", ""); + setFocusRequest(newId); + setFocusedId(newId); + }, [insertBlock, page.id]); + const handleBackspaceEmpty = (0, import_react.useCallback)((blockId) => { + const idx = page.blocks.findIndex((b) => b.id === blockId); + if (idx < 0) return; + const prev = page.blocks[idx - 1]; + deleteBlock(page.id, blockId); + if (prev) { + setFocusRequest(prev.id); + setFocusedId(prev.id); + } + }, [ + deleteBlock, + page.blocks, + page.id + ]); + const handleIndent = (0, import_react.useCallback)((blockId, delta) => { + const block = page.blocks.find((b) => b.id === blockId); + if (!block) return; + const next = Math.max(0, Math.min(4, (block.indent ?? 0) + delta)); + updateBlock(page.id, blockId, { indent: next }); + }, [ + page.blocks, + page.id, + updateBlock + ]); + const handleAiInsert = (0, import_react.useCallback)((afterId, generated) => { + const idx = page.blocks.findIndex((b) => b.id === afterId); + if (idx < 0 || generated.length === 0) return; + const newBlocks = generated.map((g) => ({ + id: uid("b"), + type: g.type, + content: g.content, + indent: 0, + checked: g.type === "todo" ? false : void 0, + showSource: g.type === "mermaid" ? false : void 0 + })); + const next = [...page.blocks]; + next.splice(idx + 1, 0, ...newBlocks); + setBlocks(page.id, next); + setFocusRequest(newBlocks[0].id); + }, [ + page.blocks, + page.id, + setBlocks + ]); + const cover = page.cover ? COVER_PRESETS[page.cover] : null; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mx-auto w-full max-w-3xl px-4 pb-32 pt-4 sm:px-12 sm:pt-8", + children: [ + cover ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "group/cover relative -mx-4 mb-2 h-36 overflow-hidden rounded-xl sm:-mx-6 sm:h-44", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: cn("absolute inset-0", cover.className) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + "data-hover-reveal": true, + className: "absolute bottom-3 right-3 opacity-0 transition-opacity group-hover/cover:opacity-100", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + size: "sm", + variant: "secondary", + className: "bg-background/90 shadow-sm backdrop-blur-sm", + onClick: () => updatePage(page.id, { cover: null }), + children: "Remove cover" + }) + })] + }) : null, + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mb-1 flex flex-wrap items-end gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Popover, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PopoverTrigger, { + asChild: true, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "flex size-16 items-center justify-center rounded-xl text-4xl transition-colors hover:bg-muted", + "aria-label": "Change page icon", + children: page.icon + }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(PopoverContent, { + align: "start", + className: "w-72", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "mb-2 text-xs font-medium text-muted-foreground", + children: "Page icon" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "grid grid-cols-8 gap-1", + children: PAGE_ICONS.map((icon) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: cn("flex size-8 items-center justify-center rounded-md text-lg transition-colors hover:bg-muted", page.icon === icon && "bg-muted ring-1 ring-border"), + onClick: () => updatePage(page.id, { icon }), + children: icon + }, icon)) + })] + })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mb-2 flex flex-1 flex-wrap items-center gap-1", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "ghost", + className: "text-muted-foreground", + onClick: () => updatePage(page.id, { favorite: !page.favorite }), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Star, { className: cn("size-3.5", page.favorite && "fill-amber-400 text-amber-500") }), page.favorite ? "Unfavorite" : "Favorite"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "ghost", + className: "text-muted-foreground", + onClick: () => { + const last = page.blocks[page.blocks.length - 1]; + const id = insertBlock(page.id, last?.id ?? null, "ai", ""); + setFocusRequest(id); + }, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-3.5" }), "AI block"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenu, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuTrigger, { + asChild: true, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + variant: "ghost", + className: "text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Image, { className: "size-3.5" }), "Cover"] + }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuContent, { + align: "start", + children: [Object.entries(COVER_PRESETS).map(([key, preset]) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: () => updatePage(page.id, { cover: key }), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: cn("mr-2 size-4 rounded", preset.className) }), preset.label] + }, key)), page.cover && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator, {}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuItem, { + onClick: () => updatePage(page.id, { cover: null }), + children: "Remove cover" + })] })] + })] }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenu, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuTrigger, { + asChild: true, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + size: "sm", + variant: "ghost", + "aria-label": "Page actions", + className: "text-muted-foreground", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Ellipsis, { className: "size-3.5" }) + }) + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuContent, { + align: "start", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: () => createPage({ parentId: page.id }), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-4" }), " Add sub-page"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + onClick: () => duplicatePage(page.id), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Copy, { className: "size-4" }), " Duplicate"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator, {}), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { + className: "text-destructive focus:text-destructive", + onClick: () => deletePage(page.id), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trash2, { className: "size-4" }), " Move to trash"] + }) + ] + })] }) + ] + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { + ref: titleRef, + value: page.title, + onChange: (e) => updatePage(page.id, { title: e.target.value }), + placeholder: "Untitled", + rows: 1, + className: "mb-4 w-full resize-none overflow-hidden bg-transparent text-4xl font-bold tracking-tight text-foreground outline-none placeholder:text-muted-foreground/50", + onKeyDown: (e) => { + if (e.key === "Enter") { + e.preventDefault(); + const first = page.blocks[0]; + if (first) { + setFocusRequest(first.id); + setFocusedId(first.id); + } + } + } + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "relative space-y-0.5 pl-10 sm:pl-12", + children: page.blocks.map((block, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockRow, { + pageId: page.id, + block, + index, + isFocused: focusedId === block.id, + listNumber: listNumbers.get(block.id), + pageTitle: page.title, + pageText, + onFocus: setFocusedId, + onChange: (id, content) => updateBlock(page.id, id, { content }), + onTypeChange: (id, type) => changeBlockType(page.id, id, type), + onToggleCheck: (id) => { + const b = page.blocks.find((x) => x.id === id); + if (b) updateBlock(page.id, id, { checked: !b.checked }); + }, + onToggleCollapse: (id) => { + const b = page.blocks.find((x) => x.id === id); + if (b) updateBlock(page.id, id, { collapsed: !b.collapsed }); + }, + onEnter: handleEnter, + onBackspaceEmpty: handleBackspaceEmpty, + onMove: (id, dir) => moveBlock(page.id, id, dir), + onDelete: (id) => deleteBlock(page.id, id), + onIndent: handleIndent, + onPatch: (id, patch) => updateBlock(page.id, id, patch), + onAiInsert: handleAiInsert, + focusRequest, + onFocusHandled: () => setFocusRequest(null), + inputRefs + }, block.id)) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "mt-2 ml-10 min-h-16 w-[calc(100%-2.5rem)] cursor-text rounded-md sm:ml-12 sm:w-[calc(100%-3rem)]", + "aria-label": "Add block at end", + onClick: () => { + const last = page.blocks[page.blocks.length - 1]; + if (last && last.type === "paragraph" && !last.content) { + setFocusRequest(last.id); + setFocusedId(last.id); + } else { + const id = insertBlock(page.id, last?.id ?? null, "paragraph", ""); + setFocusRequest(id); + setFocusedId(id); + } + } + }) + ] + }); +} +function CommandPalette({ open, onOpenChange }) { + const pages = useWorkspace((s) => s.pages); + const storageMode = useWorkspace((s) => s.storageMode); + const setActivePage = useWorkspace((s) => s.setActivePage); + const createPage = useWorkspace((s) => s.createPage); + const [query, setQuery] = (0, import_react.useState)(""); + const [hits, setHits] = (0, import_react.useState)([]); + const [searching, setSearching] = (0, import_react.useState)(false); + const [trgm, setTrgm] = (0, import_react.useState)(false); + const [mode, setMode] = (0, import_react.useState)("local"); + (0, import_react.useEffect)(() => { + if (!open) { + setQuery(""); + setHits([]); + } + }, [open]); + (0, import_react.useEffect)(() => { + const onKey = (e) => { + if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { + e.preventDefault(); + onOpenChange(!open); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [open, onOpenChange]); + (0, import_react.useEffect)(() => { + if (!open) return; + const q = query.trim(); + if (!q) { + setHits([]); + setSearching(false); + return; + } + let cancelled = false; + setSearching(true); + const t = setTimeout(() => { + (async () => { + try { + if (storageMode === "database") { + const res = await searchPages({ data: { + query: q, + limit: 24 + } }); + if (cancelled) return; + setHits(res.hits); + setTrgm(res.trgm); + setMode("postgres"); + } else { + const res = localSearchPages(pages, q, 24); + if (cancelled) return; + setHits(res); + setTrgm(false); + setMode("local"); + } + } catch { + if (cancelled) return; + setHits(localSearchPages(pages, q, 24)); + setMode("local"); + } finally { + if (!cancelled) setSearching(false); + } + })(); + }, 180); + return () => { + cancelled = true; + clearTimeout(t); + }; + }, [ + query, + open, + storageMode, + pages + ]); + const fallbackPages = (0, import_react.useMemo)(() => pages.filter((p) => !p.archived).slice(0, 30), [pages]); + if (!open) return null; + const showHits = query.trim().length > 0; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "fixed inset-0 z-[100]", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "absolute inset-0 bg-black/40", + onClick: () => onOpenChange(false), + "aria-hidden": true + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + role: "dialog", + "aria-modal": "true", + "aria-label": "Command palette", + "data-testid": "command-palette", + className: "absolute left-1/2 top-[18%] w-[min(560px,calc(100%-2rem))] -translate-x-1/2 overflow-hidden rounded-xl border border-border bg-popover shadow-2xl", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(_e, { + className: "flex flex-col", + label: "Search pages", + shouldFilter: false, + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 border-b border-border px-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Search, { className: "size-4 shrink-0 text-muted-foreground" }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(_e.Input, { + value: query, + onValueChange: setQuery, + placeholder: storageMode === "database" ? "Search pages (Postgres keyword + similarity)…" : "Search pages…", + className: "h-12 w-full bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground", + autoFocus: true + }), + searching ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin text-muted-foreground" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("kbd", { + className: "hidden rounded border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground sm:inline", + children: "ESC" + }) + ] + }), + showHits && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "border-b border-border px-3 py-1.5 text-[11px] text-muted-foreground", + children: mode === "postgres" ? `Postgres full-text${trgm ? " + pg_trgm similarity" : " + ILIKE fallback"}` : "Local search (sign in to sync for Postgres search)" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(_e.List, { + className: "max-h-80 overflow-y-auto p-2", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(_e.Group, { + heading: "Actions", + className: "[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(_e.Item, { + value: "new page create", + onSelect: () => { + createPage(); + onOpenChange(false); + }, + className: cn("flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-sm aria-selected:bg-muted"), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-4 text-muted-foreground" }), "New page"] + }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(_e.Group, { + heading: showHits ? "Results" : "Pages", + className: "mt-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground", + children: (showHits ? hits : fallbackPages.map(pageToHit)).map((hit) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(_e.Item, { + value: `${hit.title} ${hit.pageId}`, + onSelect: () => { + setActivePage(hit.pageId); + window.dispatchEvent(new CustomEvent("workspace:clear-mount")); + onOpenChange(false); + }, + className: "flex cursor-pointer flex-col gap-0.5 rounded-md px-2 py-2 text-sm aria-selected:bg-muted", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-base leading-none", + children: hit.icon + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "min-w-0 flex-1 truncate font-medium", + children: hit.title || "Untitled" + }), + hit.favorite && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Star, { className: "size-3.5 fill-amber-400 text-amber-500" }), + showHits && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-[10px] uppercase text-muted-foreground", + children: hit.mode + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FileText, { className: "size-3.5 text-muted-foreground" }) + ] + }), showHits && hit.snippet && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "line-clamp-2 pl-7 text-xs text-muted-foreground", + children: hit.snippet + })] + }, hit.pageId)) + }), + showHits && hits.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "py-8 text-center text-sm text-muted-foreground", + children: searching ? "Searching…" : "No pages found" + }) + ] + }) + ] + }) + })] + }); +} +function pageToHit(page) { + return { + pageId: page.id, + title: page.title, + icon: page.icon, + parentId: page.parentId, + favorite: page.favorite, + snippet: "", + score: 0, + mode: "keyword" + }; +} +/** +* Browse + view/edit a linked markdown file without importing into the workspace. +*/ +function MountedMarkdownView() { + const mounts = useMarkdownMounts((s) => s.mounts); + const selection = useMarkdownMounts((s) => s.selection); + const setSelection = useMarkdownMounts((s) => s.setSelection); + const mount = mounts.find((m) => m.id === selection?.mountId); + const [entries, setEntries] = (0, import_react.useState)([]); + const [dirPath, setDirPath] = (0, import_react.useState)(""); + const [content, setContent] = (0, import_react.useState)(""); + const [blocks, setBlocks] = (0, import_react.useState)([]); + const [title, setTitle] = (0, import_react.useState)(""); + const [loading, setLoading] = (0, import_react.useState)(false); + const [saving, setSaving] = (0, import_react.useState)(false); + const [dirty, setDirty] = (0, import_react.useState)(false); + const [error, setError] = (0, import_react.useState)(null); + const [mode, setMode] = (0, import_react.useState)("browse"); + const loadDir = (0, import_react.useCallback)(async (rel = "") => { + if (!mount) return; + setLoading(true); + setError(null); + try { + if (mount.kind === "server" && mount.serverPath) { + const list = await listServerMount({ data: { + root: mount.serverPath, + relPath: rel + } }); + setEntries(list); + } else { + const handle = await loadDirectoryHandle(mount.id); + if (!handle) throw new Error("Local folder permission lost — re-link the folder."); + let dir = handle; + if (rel) for (const part of rel.split("/").filter(Boolean)) dir = await dir.getDirectoryHandle(part); + const list = await listBrowserDir(dir, rel); + setEntries(list.map((e) => ({ + ...e, + relPath: rel ? `${rel}/${e.name}` : e.name + }))); + } + setDirPath(rel); + setMode("browse"); + } catch (e) { + setError(e instanceof Error ? e.message : "Failed to list folder"); + } finally { + setLoading(false); + } + }, [mount]); + const loadFile = (0, import_react.useCallback)(async (relPath) => { + if (!mount) return; + setLoading(true); + setError(null); + try { + let text = ""; + if (mount.kind === "server" && mount.serverPath) text = (await readServerMountFile({ data: { + root: mount.serverPath, + relPath + } })).content; + else { + const handle = await loadDirectoryHandle(mount.id); + if (!handle) throw new Error("Local folder permission lost — re-link the folder."); + text = await readBrowserFile(handle, relPath); + } + setContent(text); + const t = titleFromMarkdown(text, relPath.split("/").pop() || "note"); + setTitle(t); + setBlocks(markdownToBlocks(text.replace(new RegExp(`^#\\s+${t}\\s*\\n+`), ""))); + setDirty(false); + setMode("file"); + setSelection({ + mountId: mount.id, + relPath + }); + } catch (e) { + setError(e instanceof Error ? e.message : "Failed to read file"); + } finally { + setLoading(false); + } + }, [mount, setSelection]); + (0, import_react.useEffect)(() => { + if (!mount) return; + if (selection?.relPath && selection.relPath.toLowerCase().endsWith(".md")) loadFile(selection.relPath); + else loadDir(selection?.relPath && !selection.relPath.endsWith(".md") ? selection.relPath : ""); + }, [mount?.id]); + const save = async () => { + if (!mount || !selection?.relPath) return; + setSaving(true); + setError(null); + try { + const md = pageToMarkdownFile({ + id: "x", + title, + icon: "📝", + cover: null, + parentId: null, + favorite: false, + createdAt: 0, + updatedAt: 0, + blocks + }); + if (mount.kind === "server" && mount.serverPath) await writeServerMountFile({ data: { + root: mount.serverPath, + relPath: selection.relPath, + content: md + } }); + else { + const handle = await loadDirectoryHandle(mount.id); + if (!handle) throw new Error("Local folder permission lost"); + await writeBrowserFile(handle, selection.relPath, md); + } + setContent(md); + setDirty(false); + } catch (e) { + setError(e instanceof Error ? e.message : "Save failed"); + } finally { + setSaving(false); + } + }; + if (!mount || !selection) return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex h-full flex-col items-center justify-center gap-2 p-8 text-center text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link2, { className: "size-8 opacity-40" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-sm", + children: "Select a linked markdown file from the sidebar." + })] + }); + const crumbs = (mode === "file" ? selection.relPath : dirPath).split("/").filter(Boolean); + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mx-auto w-full max-w-3xl px-4 pb-32 pt-6 sm:px-12", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mb-4 flex flex-wrap items-center gap-2 text-xs text-muted-foreground", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 font-medium text-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link2, { className: "size-3" }), " Linked · not imported"] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "hover:text-foreground", + onClick: () => void loadDir(""), + children: mount.name + }), + crumbs.map((c, i) => { + const path = crumbs.slice(0, i + 1).join("/"); + const isLast = i === crumbs.length - 1 && mode === "file"; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "flex items-center gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "/" }), isLast ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "text-foreground", + children: c + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { + type: "button", + className: "hover:text-foreground", + onClick: () => { + if (c.toLowerCase().endsWith(".md")) loadFile(path); + else loadDir(path); + }, + children: c + })] + }, path); + }) + ] + }), + error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "mb-4 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive", + children: error + }), + loading ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex items-center gap-2 py-12 text-sm text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin" }), " Loading…"] + }) : mode === "browse" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "space-y-1", + children: [ + dirPath && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + className: "flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted", + onClick: () => { + const parent = dirPath.split("/").slice(0, -1).join("/"); + loadDir(parent); + }, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(FolderOpen, { className: "size-4 text-muted-foreground" }), ".."] + }), + entries.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "py-8 text-center text-sm text-muted-foreground", + children: "No markdown files here" + }), + entries.map((e) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + className: "flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted", + onClick: () => { + if (e.kind === "dir") loadDir(e.relPath); + else loadFile(e.relPath); + }, + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: e.kind === "dir" ? "📁" : "📝" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "font-medium", + children: e.name + })] + }, e.relPath)) + ] + }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "mb-4 flex flex-wrap items-center gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { + className: "min-w-0 flex-1 bg-transparent text-3xl font-bold tracking-tight outline-none", + value: title, + onChange: (e) => { + setTitle(e.target.value); + setDirty(true); + } + }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { + type: "button", + size: "sm", + disabled: !dirty || saving, + onClick: () => void save(), + children: [saving ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-3.5 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Save, { className: "size-3.5" }), "Save to disk"] + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "relative space-y-0.5 pl-2", + children: [blocks.map((block, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "rounded-md py-1", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { + className: "w-full resize-y rounded-md border border-transparent bg-transparent px-1 py-1 text-base leading-relaxed outline-none hover:border-border focus:border-border focus:bg-background", + rows: Math.max(1, block.content.split("\n").length), + value: block.content, + onChange: (e) => { + const next = blocks.map((b) => b.id === block.id ? { + ...b, + content: e.target.value + } : b); + setBlocks(next); + setDirty(true); + }, + placeholder: block.type + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "px-1 text-[10px] uppercase tracking-wide text-muted-foreground", + children: block.type + })] + }, block.id)), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + size: "sm", + variant: "ghost", + className: "mt-2", + onClick: () => { + setBlocks([...blocks, { + id: uid("b"), + type: "paragraph", + content: "", + indent: 0 + }]); + setDirty(true); + }, + children: "Add block" + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { + className: "mt-8 text-xs text-muted-foreground", + children: [ + "Edits write back to the linked file. This page is ", + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "not" }), + " stored in your workspace until you Import." + ] + }) + ] }) + ] + }); +} +function validateSnapshot(input) { + const data = input; + if (!data || typeof data !== "object") throw new Error("Invalid workspace snapshot"); + if (typeof data.name !== "string") throw new Error("Invalid name"); + if (data.theme !== "light" && data.theme !== "dark") throw new Error("Invalid theme"); + if (!Array.isArray(data.pages)) throw new Error("Invalid pages"); + return { + name: data.name.slice(0, 120), + theme: data.theme, + activePageId: data.activePageId ?? null, + sidebarOpen: Boolean(data.sidebarOpen), + pages: data.pages.map((p) => ({ + id: String(p.id), + title: String(p.title ?? "").slice(0, 500), + icon: String(p.icon ?? "📄").slice(0, 16), + cover: p.cover ?? null, + parentId: p.parentId ?? null, + favorite: Boolean(p.favorite), + archived: Boolean(p.archived), + createdAt: Number(p.createdAt) || Date.now(), + updatedAt: Number(p.updatedAt) || Date.now(), + blocks: Array.isArray(p.blocks) ? p.blocks : [] + })) + }; +} +var loadWorkspace = createServerFn({ method: "GET" }).middleware([authMiddleware]).handler(createSsrRpc("e3fb77d67dfdadad5d019581d79338a7f7cf2e42797c44110574e289b39fd293")); +var saveWorkspace = createServerFn({ method: "POST" }).middleware([authMiddleware]).validator((input) => validateSnapshot(input)).handler(createSsrRpc("7bd9976b9723bbefb2399d41723684e8ed7d3bfcf4f814066bb422e47b4bb658")); +var saveTimer = null; +var saving = false; +var pending = false; +var remoteMode = false; +var bootstrapped = false; +var unsub = null; +function snapshotFromStore() { + const s = useWorkspace.getState(); + return { + name: s.name, + theme: s.theme, + activePageId: s.activePageId, + sidebarOpen: s.sidebarOpen, + pages: s.pages + }; +} +function attachAutosave() { + unsub?.(); + unsub = useWorkspace.subscribe((state, prev) => { + if (!remoteMode || !bootstrapped) return; + if (state.name === prev.name && state.theme === prev.theme && state.activePageId === prev.activePageId && state.sidebarOpen === prev.sidebarOpen && state.pages === prev.pages) return; + scheduleRemoteSave(); + }); +} +/** Load workspace from Postgres for the signed-in user (or seed on first visit). */ +async function bootstrapRemoteWorkspace() { + try { + const data = await loadWorkspace(); + bootstrapped = false; + useWorkspace.setState({ + name: data.name, + theme: data.theme, + activePageId: data.activePageId, + sidebarOpen: data.sidebarOpen, + pages: data.pages, + hydrated: true, + syncStatus: "saved", + storageMode: "database" + }); + remoteMode = true; + bootstrapped = true; + attachAutosave(); + return data.source; + } catch { + remoteMode = false; + bootstrapped = false; + unsub?.(); + unsub = null; + useWorkspace.setState({ + storageMode: "local", + syncStatus: "local", + hydrated: true + }); + return "error"; + } +} +function scheduleRemoteSave() { + if (!remoteMode || !bootstrapped) return; + useWorkspace.setState({ syncStatus: "pending" }); + if (saveTimer) clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + flushRemoteSave(); + }, 600); +} +async function flushRemoteSave() { + if (!remoteMode) return; + if (saving) { + pending = true; + return; + } + saving = true; + useWorkspace.setState({ syncStatus: "saving" }); + try { + await saveWorkspace({ data: snapshotFromStore() }); + useWorkspace.setState({ syncStatus: "saved" }); + } catch { + useWorkspace.setState({ syncStatus: "error" }); + } finally { + saving = false; + if (pending) { + pending = false; + scheduleRemoteSave(); + } + } +} +/** Immediate save (e.g. before unload). */ +async function flushRemoteSaveNow() { + if (saveTimer) { + clearTimeout(saveTimer); + saveTimer = null; + } + if (!remoteMode) return; + try { + await saveWorkspace({ data: snapshotFromStore() }); + useWorkspace.setState({ syncStatus: "saved" }); + } catch { + useWorkspace.setState({ syncStatus: "error" }); + } +} +function useLocalOnlyMode() { + remoteMode = false; + bootstrapped = false; + unsub?.(); + unsub = null; + useWorkspace.setState({ + storageMode: "local", + syncStatus: "local", + hydrated: true + }); +} +function AppShell() { + const pages = useWorkspace((s) => s.pages); + const activePageId = useWorkspace((s) => s.activePageId); + const sidebarOpen = useWorkspace((s) => s.sidebarOpen); + const theme = useWorkspace((s) => s.theme); + const hydrated = useWorkspace((s) => s.hydrated); + const storageMode = useWorkspace((s) => s.storageMode); + const syncStatus = useWorkspace((s) => s.syncStatus); + const setSidebarOpen = useWorkspace((s) => s.setSidebarOpen); + const toggleSidebar = useWorkspace((s) => s.toggleSidebar); + const setActivePage = useWorkspace((s) => s.setActivePage); + const setTheme = useWorkspace((s) => s.setTheme); + const updatePage = useWorkspace((s) => s.updatePage); + const createPage = useWorkspace((s) => s.createPage); + const setHydrated = useWorkspace((s) => s.setHydrated); + const mountSelection = useMarkdownMounts((s) => s.selection); + const mounts = useMarkdownMounts((s) => s.mounts); + const setMountSelection = useMarkdownMounts((s) => s.setSelection); + const mount = mounts.find((m) => m.id === mountSelection?.mountId); + const { user, isPending: authPending } = useCurrentUserState(); + const [searchOpen, setSearchOpen] = (0, import_react.useState)(false); + const [mobileSidebar, setMobileSidebar] = (0, import_react.useState)(false); + const [remoteLoading, setRemoteLoading] = (0, import_react.useState)(false); + const [ioOpen, setIoOpen] = (0, import_react.useState)(false); + (0, import_react.useEffect)(() => { + const unsub = useWorkspace.persist.onFinishHydration(() => { + if (!user) setHydrated(true); + }); + if (useWorkspace.persist.hasHydrated() && !user) setHydrated(true); + return unsub; + }, [setHydrated, user]); + (0, import_react.useEffect)(() => { + if (authPending) return; + let cancelled = false; + async function run() { + if (user) { + setRemoteLoading(true); + await bootstrapRemoteWorkspace(); + if (!cancelled) setRemoteLoading(false); + } else { + useLocalOnlyMode(); + if (useWorkspace.persist.hasHydrated()) setHydrated(true); + } + } + run(); + return () => { + cancelled = true; + }; + }, [ + user, + authPending, + setHydrated + ]); + (0, import_react.useEffect)(() => { + const onHide = () => { + if (storageMode === "database") flushRemoteSaveNow(); + }; + window.addEventListener("pagehide", onHide); + return () => window.removeEventListener("pagehide", onHide); + }, [storageMode]); + (0, import_react.useEffect)(() => { + const clear = () => setMountSelection(null); + window.addEventListener("workspace:clear-mount", clear); + return () => window.removeEventListener("workspace:clear-mount", clear); + }, [setMountSelection]); + const showMount = Boolean(mountSelection && mount); + const page = !showMount ? pages.find((p) => p.id === activePageId && !p.archived) : void 0; + const breadcrumbs = (() => { + if (!page) return []; + const chain = []; + let cur = page; + const byId = new Map(pages.map((p) => [p.id, p])); + while (cur) { + chain.unshift(cur); + cur = cur.parentId ? byId.get(cur.parentId) : void 0; + } + return chain; + })(); + if (!hydrated || authPending || remoteLoading) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "flex h-dvh items-center justify-center bg-background text-muted-foreground", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex flex-col items-center gap-3", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "size-8 animate-pulse rounded-lg bg-muted" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-sm", + children: remoteLoading ? "Loading workspace from database…" : "Loading workspace…" + })] + }) + }); + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TooltipProvider, { + delayDuration: 300, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex h-dvh overflow-hidden bg-background text-foreground", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: cn("hidden h-full shrink-0 transition-[width,opacity] duration-200 md:block", sidebarOpen ? "w-[260px] opacity-100" : "w-0 overflow-hidden opacity-0"), + children: sidebarOpen && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sidebar, { onOpenSearch: () => setSearchOpen(true) }) + }), + mobileSidebar && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "fixed inset-0 z-50 md:hidden", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "absolute inset-0 bg-black/40", + onClick: () => setMobileSidebar(false), + "aria-hidden": true + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "absolute inset-y-0 left-0 w-[min(280px,88vw)] shadow-xl", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sidebar, { + mobile: true, + onOpenSearch: () => { + setMobileSidebar(false); + setSearchOpen(true); + }, + onNavigate: () => setMobileSidebar(false) + }) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex min-w-0 flex-1 flex-col", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("header", { + className: "flex h-11 shrink-0 items-center gap-1 border-b border-border px-2 sm:px-3", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "ghost", + size: "icon-sm", + className: "md:hidden", + onClick: () => setMobileSidebar(true), + "aria-label": "Open sidebar", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Menu, { className: "size-4" }) + }), + !sidebarOpen && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "ghost", + size: "icon-sm", + className: "hidden md:inline-flex", + onClick: toggleSidebar, + "aria-label": "Open sidebar", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PanelLeft, { className: "size-4" }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("nav", { + className: "flex min-w-0 flex-1 items-center gap-0.5 overflow-hidden text-sm", + children: [showMount ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "flex items-center gap-1.5 px-1.5 text-muted-foreground", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link2, { className: "size-3.5" }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "truncate font-medium text-foreground", + children: [mount?.name, mountSelection?.relPath ? ` / ${mountSelection.relPath}` : ""] + })] + }) : breadcrumbs.map((crumb, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "flex min-w-0 items-center gap-0.5", + children: [i > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: "size-3.5 shrink-0 text-muted-foreground" }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { + type: "button", + className: cn("max-w-[140px] truncate rounded px-1.5 py-0.5 transition-colors hover:bg-muted sm:max-w-[200px]", i === breadcrumbs.length - 1 ? "font-medium text-foreground" : "text-muted-foreground"), + onClick: () => setActivePage(crumb.id), + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "mr-1", + children: crumb.icon + }), crumb.title || "Untitled"] + })] + }, crumb.id)), !page && !showMount && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { + className: "px-1.5 text-muted-foreground", + children: "No page selected" + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SyncChip, { + mode: storageMode, + status: syncStatus + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "ghost", + size: "icon-sm", + onClick: () => setTheme(theme === "dark" ? "light" : "dark"), + "aria-label": theme === "dark" ? "Switch to light theme" : "Switch to dark theme", + children: theme === "dark" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sun, { className: "size-4 text-muted-foreground" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Moon, { className: "size-4 text-muted-foreground" }) + }), + (page || showMount) && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "ghost", + size: "icon-sm", + title: "Import / export markdown", + onClick: () => setIoOpen(true), + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FileDown, { className: "size-4 text-muted-foreground" }) + }), + page && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "ghost", + size: "icon-sm", + onClick: () => updatePage(page.id, { favorite: !page.favorite }), + "aria-label": page.favorite ? "Unfavorite" : "Favorite", + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Star, { className: cn("size-4", page.favorite ? "fill-amber-400 text-amber-500" : "text-muted-foreground") }) + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { + className: "ml-1 hidden items-center gap-2 sm:flex", + children: user ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(UserButton, {}) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + size: "sm", + variant: "outline", + asChild: true, + children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, { + to: "/login", + children: "Sign in to sync" + }) + }) + }) + ] + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("main", { + className: "min-h-0 flex-1 overflow-y-auto", + children: showMount ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MountedMarkdownView, {}, `${mountSelection.mountId}:${mountSelection.relPath}`) : page ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PageEditor, { page }, page.id) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EmptyWorkspace, { + onCreate: () => createPage(), + onOpenSidebar: () => { + setSidebarOpen(true); + setMobileSidebar(true); + } + }) + })] + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CommandPalette, { + open: searchOpen, + onOpenChange: setSearchOpen + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MarkdownIODialog, { + open: ioOpen, + onOpenChange: setIoOpen + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Toaster, { + position: "bottom-right", + theme, + toastOptions: { className: "border border-border bg-background text-foreground" } + }) + ] + }) + }); +} +function SyncChip({ mode, status }) { + if (mode === "local") return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: "hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground sm:inline-flex", + title: "Guest mode — data stays in this browser", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CloudOff, { className: "size-3" }), "Local only"] + }); + const label = status === "saving" || status === "pending" ? "Saving…" : status === "error" ? "Sync error" : "Saved to DB"; + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { + className: cn("hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] sm:inline-flex", status === "error" ? "text-destructive" : "text-muted-foreground"), + title: "Signed in — workspace syncs to Postgres", + children: [status === "saving" || status === "pending" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-3 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Cloud, { className: "size-3" }), label] + }); +} +function EmptyWorkspace({ onCreate, onOpenSidebar }) { + return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex h-full flex-col items-center justify-center gap-4 p-8 text-center", + children: [ + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "text-lg font-medium", + children: "No page open" + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { + className: "max-w-sm text-sm text-muted-foreground", + children: "Create a page, open one from the sidebar, or link a markdown folder without importing." + }), + /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { + className: "flex flex-wrap justify-center gap-2", + children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + onClick: onCreate, + children: "New page" + }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { + type: "button", + variant: "outline", + onClick: onOpenSidebar, + children: "Open sidebar" + })] + }) + ] + }); +} +function Home() { + return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AppShell, {}); +} +//#endregion +export { Home as component }; diff --git a/.vercel/output/functions/__server.func/_ssr/routes-Cr5s3SSS.mjs b/.vercel/output/functions/__server.func/_ssr/routes-Cr5s3SSS.mjs deleted file mode 100644 index 35154d1..0000000 --- a/.vercel/output/functions/__server.func/_ssr/routes-Cr5s3SSS.mjs +++ /dev/null @@ -1,2533 +0,0 @@ -import { o as __toESM } from "../_runtime.mjs"; -import { u as require_react } from "../_libs/@floating-ui/react-dom+[...].mjs"; -import { h as Link } from "../_libs/@tanstack/react-router+[...].mjs"; -import { c as require_jsx_runtime } from "../_libs/@radix-ui/react-collection+[...].mjs"; -import { i as createServerFn, o as getServerFnById, t as TSS_SERVER_FUNCTION } from "./ssr.mjs"; -import { i as signOut } from "./client-C9atugA7.mjs"; -import { n as uid, t as cn } from "./utils-DkRSI2_g.mjs"; -import { n as useCurrentUser, r as useCurrentUserState, t as Button } from "./use-current-user-Ct6wm9as.mjs"; -import { a as seedWorkspace, i as createEmptyPage, n as PAGE_ICONS, r as authMiddleware, t as COVER_PRESETS } from "./seed-D7faJ9JV.mjs"; -import { A as Heading3, B as Cloud, C as LogIn, D as ListTodo, E as ListTree, F as FilePlus, G as ArrowUp, H as ChevronRight, I as Eye, K as ArrowDown, L as Ellipsis, M as Heading1, N as GripVertical, O as ListOrdered, P as FileText, R as Copy, S as Menu, T as List, U as ChevronDown, V as CloudOff, W as Check, _ as PanelLeft, a as Trash2, b as Minus, c as Star, d as Settings, f as Search, g as Play, h as Plus, i as Type, j as Heading2, k as Image, l as SquareCheckBig, m as Quote, n as Workflow, o as Table2, p as RotateCcw, r as WandSparkles, s as Sun, t as X, u as Sparkles, v as PanelLeftClose, w as LoaderCircle, x as MessageSquare, y as Moon, z as CodeXml } from "../_libs/lucide-react.mjs"; -import { n as create, t as persist } from "../_libs/zustand.mjs"; -import { a as DialogOverlay$1, i as DialogDescription$1, n as DialogClose, o as DialogPortal$1, r as DialogContent$1, s as DialogTitle$1, t as Dialog$1 } from "../_libs/@radix-ui/react-dialog+[...].mjs"; -import { a as DropdownMenuPortal, c as DropdownMenuSubContent$1, i as DropdownMenuLabel$1, l as DropdownMenuSubTrigger$1, n as DropdownMenuContent$1, o as DropdownMenuSeparator$1, r as DropdownMenuItem$1, s as DropdownMenuSub$1, t as DropdownMenu$1, u as DropdownMenuTrigger$1 } from "../_libs/@radix-ui/react-dropdown-menu+[...].mjs"; -import { t as TooltipProvider$1 } from "../_libs/radix-ui__react-tooltip.mjs"; -import { a as ScrollAreaViewport, i as ScrollAreaThumb, n as ScrollAreaCorner, r as ScrollAreaScrollbar, t as ScrollArea$1 } from "../_libs/radix-ui__react-scroll-area.mjs"; -import { i as PopoverTrigger$1, n as PopoverContent$1, r as PopoverPortal, t as Popover$1 } from "../_libs/radix-ui__react-popover.mjs"; -import { t as _e } from "../_libs/cmdk.mjs"; -import { t as Toaster } from "../_libs/sonner.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/routes-Cr5s3SSS.js -var import_react = /* @__PURE__ */ __toESM(require_react()); -var import_jsx_runtime = require_jsx_runtime(); -function touch(page) { - return { - ...page, - updatedAt: Date.now() - }; -} -function collectDescendants(pages, rootId) { - const ids = /* @__PURE__ */ new Set([rootId]); - let changed = true; - while (changed) { - changed = false; - for (const p of pages) if (p.parentId && ids.has(p.parentId) && !ids.has(p.id)) { - ids.add(p.id); - changed = true; - } - } - return ids; -} -var seeded = seedWorkspace(); -var useWorkspace = create()(persist((set, get) => ({ - name: "Rick's Workspace", - pages: seeded.pages, - activePageId: seeded.activePageId, - sidebarOpen: true, - theme: "light", - hydrated: false, - storageMode: "local", - syncStatus: "local", - setHydrated: (v) => set({ hydrated: v }), - setName: (name) => set({ name }), - setSidebarOpen: (open) => set({ sidebarOpen: open }), - toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })), - setTheme: (theme) => set({ theme }), - setActivePage: (id) => set({ activePageId: id }), - getPage: (id) => get().pages.find((p) => p.id === id), - getChildren: (parentId) => get().pages.filter((p) => !p.archived && p.parentId === parentId).sort((a, b) => a.createdAt - b.createdAt), - createPage: (opts = {}) => { - const page = createEmptyPage({ - parentId: opts.parentId ?? null, - title: opts.title ?? "", - icon: opts.icon ?? "📄" - }); - set((s) => ({ - pages: [...s.pages, page], - activePageId: page.id - })); - return page.id; - }, - updatePage: (id, patch) => set((s) => ({ pages: s.pages.map((p) => p.id === id ? touch({ - ...p, - ...patch - }) : p) })), - deletePage: (id) => { - const ids = collectDescendants(get().pages, id); - set((s) => { - const pages = s.pages.map((p) => ids.has(p.id) ? touch({ - ...p, - archived: true - }) : p); - let activePageId = s.activePageId; - if (activePageId && ids.has(activePageId)) activePageId = pages.find((p) => !p.archived)?.id ?? null; - return { - pages, - activePageId - }; - }); - }, - restorePage: (id) => set((s) => ({ pages: s.pages.map((p) => p.id === id ? touch({ - ...p, - archived: false - }) : p) })), - permanentlyDeletePage: (id) => { - const ids = collectDescendants(get().pages, id); - set((s) => { - const pages = s.pages.filter((p) => !ids.has(p.id)); - let activePageId = s.activePageId; - if (activePageId && ids.has(activePageId)) activePageId = pages.find((p) => !p.archived)?.id ?? null; - return { - pages, - activePageId - }; - }); - }, - duplicatePage: (id) => { - const src = get().getPage(id); - if (!src) return null; - const copy = { - ...src, - id: uid("page"), - title: src.title ? `${src.title} (copy)` : "Untitled (copy)", - createdAt: Date.now(), - updatedAt: Date.now(), - favorite: false, - archived: false, - blocks: src.blocks.map((b) => ({ - ...b, - id: uid("b") - })) - }; - set((s) => ({ - pages: [...s.pages, copy], - activePageId: copy.id - })); - return copy.id; - }, - movePage: (id, parentId) => { - if (parentId === id) return; - if (parentId) { - if (collectDescendants(get().pages, id).has(parentId)) return; - } - set((s) => ({ pages: s.pages.map((p) => p.id === id ? touch({ - ...p, - parentId - }) : p) })); - }, - setBlocks: (pageId, blocks) => set((s) => ({ pages: s.pages.map((p) => p.id === pageId ? touch({ - ...p, - blocks - }) : p) })), - updateBlock: (pageId, blockId, patch) => set((s) => ({ pages: s.pages.map((p) => { - if (p.id !== pageId) return p; - return touch({ - ...p, - blocks: p.blocks.map((b) => b.id === blockId ? { - ...b, - ...patch - } : b) - }); - }) })), - insertBlock: (pageId, afterId, type = "paragraph", content = "") => { - const block = { - id: uid("b"), - type, - content, - indent: 0, - checked: type === "todo" ? false : void 0 - }; - set((s) => ({ pages: s.pages.map((p) => { - if (p.id !== pageId) return p; - const blocks = [...p.blocks]; - if (!afterId) blocks.unshift(block); - else { - const idx = blocks.findIndex((b) => b.id === afterId); - if (idx === -1) blocks.push(block); - else blocks.splice(idx + 1, 0, block); - } - return touch({ - ...p, - blocks - }); - }) })); - return block.id; - }, - deleteBlock: (pageId, blockId) => set((s) => ({ pages: s.pages.map((p) => { - if (p.id !== pageId) return p; - if (p.blocks.length <= 1) return touch({ - ...p, - blocks: [{ - id: uid("b"), - type: "paragraph", - content: "", - indent: 0 - }] - }); - return touch({ - ...p, - blocks: p.blocks.filter((b) => b.id !== blockId) - }); - }) })), - changeBlockType: (pageId, blockId, type) => set((s) => ({ pages: s.pages.map((p) => { - if (p.id !== pageId) return p; - return touch({ - ...p, - blocks: p.blocks.map((b) => b.id === blockId ? { - ...b, - type, - checked: type === "todo" ? b.checked ?? false : void 0, - collapsed: type === "toggle" ? b.collapsed ?? false : void 0 - } : b) - }); - }) })), - moveBlock: (pageId, blockId, direction) => set((s) => ({ pages: s.pages.map((p) => { - if (p.id !== pageId) return p; - const blocks = [...p.blocks]; - const idx = blocks.findIndex((b) => b.id === blockId); - if (idx < 0) return p; - const target = direction === "up" ? idx - 1 : idx + 1; - if (target < 0 || target >= blocks.length) return p; - [blocks[idx], blocks[target]] = [blocks[target], blocks[idx]]; - return touch({ - ...p, - blocks - }); - }) })), - resetWorkspace: () => { - const fresh = seedWorkspace(); - set({ - name: "Rick's Workspace", - pages: fresh.pages, - activePageId: fresh.activePageId, - sidebarOpen: true, - theme: "light" - }); - } -}), { - name: "notion-clone-workspace-v1", - partialize: (s) => ({ - name: s.name, - pages: s.pages, - activePageId: s.activePageId, - sidebarOpen: s.sidebarOpen, - theme: s.theme - }), - onRehydrateStorage: () => (state) => { - state?.setHydrated(true); - } -})); -var TooltipProvider = TooltipProvider$1; -function ScrollArea({ className, children, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(ScrollArea$1, { - className: cn("relative overflow-hidden", className), - ...props, - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollAreaViewport, { - className: "h-full w-full rounded-[inherit]", - children - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollBar, {}), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollAreaCorner, {}) - ] - }); -} -function ScrollBar({ className, orientation = "vertical", ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollAreaScrollbar, { - orientation, - className: cn("flex touch-none select-none transition-colors", orientation === "vertical" && "h-full w-2 border-l border-l-transparent p-px", orientation === "horizontal" && "h-2 flex-col border-t border-t-transparent p-px", className), - ...props, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScrollAreaThumb, { className: "relative flex-1 rounded-full bg-border" }) - }); -} -var DropdownMenu = DropdownMenu$1; -var DropdownMenuTrigger = DropdownMenuTrigger$1; -var DropdownMenuSub = DropdownMenuSub$1; -function DropdownMenuSubTrigger({ className, inset, children, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuSubTrigger$1, { - className: cn("flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-muted data-[state=open]:bg-muted", inset && "pl-8", className), - ...props, - children: [children, /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: "ml-auto size-4 opacity-60" })] - }); -} -function DropdownMenuSubContent({ className, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSubContent$1, { - className: cn("z-50 min-w-40 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg", className), - ...props - }); -} -function DropdownMenuContent({ className, sideOffset = 4, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuPortal, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuContent$1, { - sideOffset, - className: cn("z-50 min-w-44 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95", className), - ...props - }) }); -} -function DropdownMenuItem({ className, inset, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuItem$1, { - className: cn("relative flex cursor-default select-none items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50", inset && "pl-8", className), - ...props - }); -} -function DropdownMenuLabel({ className, inset, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuLabel$1, { - className: cn("px-2 py-1.5 text-xs font-medium text-muted-foreground", inset && "pl-8", className), - ...props - }); -} -function DropdownMenuSeparator({ className, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator$1, { - className: cn("-mx-1 my-1 h-px bg-border", className), - ...props - }); -} -var Dialog = Dialog$1; -var DialogPortal = DialogPortal$1; -function DialogOverlay({ className, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogOverlay$1, { - className: cn("fixed inset-0 z-50 bg-black/40 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className), - ...props - }); -} -function DialogContent({ className, children, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogPortal, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogOverlay, {}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent$1, { - className: cn("fixed left-1/2 top-1/2 z-50 grid w-[calc(100%-2rem)] max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border border-border bg-background p-6 shadow-xl duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95", className), - ...props, - children: [children, /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogClose, { - className: "absolute right-3 top-3 rounded-md p-1.5 text-muted-foreground opacity-70 transition-opacity hover:bg-muted hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring/40", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(X, { className: "size-4" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "sr-only", - children: "Close" - })] - })] - })] }); -} -function DialogHeader({ className, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: cn("flex flex-col gap-1.5 text-left", className), - ...props - }); -} -function DialogTitle({ className, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogTitle$1, { - className: cn("text-lg font-semibold leading-none tracking-tight", className), - ...props - }); -} -function DialogDescription({ className, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogDescription$1, { - className: cn("text-sm text-muted-foreground", className), - ...props - }); -} -/** -* Minimal signed-in identity chip + sign-out. Restyle freely (see the -* `design-ui` skill). Sign-out is only shown when auth is enabled (the -* disabled-auth dev user has nothing to sign out of). -*/ -function UserButton() { - const user = useCurrentUser(); - if (!user) return null; - const label = user.displayName ?? user.primaryEmail ?? "Account"; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex items-center gap-2", - children: [ - user.profileImageUrl ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("img", { - src: user.profileImageUrl, - alt: "", - className: "h-8 w-8 rounded-full object-cover" - }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "grid h-8 w-8 place-items-center rounded-full bg-black/10 text-sm font-medium dark:bg-white/20", - children: label.charAt(0).toUpperCase() - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-sm font-medium", - children: label - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - onClick: () => void signOut(), - className: "cursor-pointer text-sm underline-offset-4 opacity-70 hover:underline", - children: "Sign out" - }) - ] - }); -} -function Sidebar({ onOpenSearch, mobile, onNavigate }) { - const name = useWorkspace((s) => s.name); - const pages = useWorkspace((s) => s.pages); - const activePageId = useWorkspace((s) => s.activePageId); - const theme = useWorkspace((s) => s.theme); - const storageMode = useWorkspace((s) => s.storageMode); - const syncStatus = useWorkspace((s) => s.syncStatus); - const setActivePage = useWorkspace((s) => s.setActivePage); - const createPage = useWorkspace((s) => s.createPage); - const deletePage = useWorkspace((s) => s.deletePage); - const restorePage = useWorkspace((s) => s.restorePage); - const permanentlyDeletePage = useWorkspace((s) => s.permanentlyDeletePage); - const duplicatePage = useWorkspace((s) => s.duplicatePage); - const updatePage = useWorkspace((s) => s.updatePage); - const toggleSidebar = useWorkspace((s) => s.toggleSidebar); - const setTheme = useWorkspace((s) => s.setTheme); - const setName = useWorkspace((s) => s.setName); - const resetWorkspace = useWorkspace((s) => s.resetWorkspace); - const { user } = useCurrentUserState(); - const [expanded, setExpanded] = (0, import_react.useState)({}); - const [trashOpen, setTrashOpen] = (0, import_react.useState)(false); - const [settingsOpen, setSettingsOpen] = (0, import_react.useState)(false); - const active = pages.filter((p) => !p.archived); - const archived = pages.filter((p) => p.archived); - const favorites = active.filter((p) => p.favorite); - const childrenOf = (0, import_react.useMemo)(() => { - const map = /* @__PURE__ */ new Map(); - for (const p of active) { - const key = p.parentId; - const list = map.get(key) ?? []; - list.push(p); - map.set(key, list); - } - for (const [, list] of map) list.sort((a, b) => a.createdAt - b.createdAt); - return map; - }, [active]); - const select = (id) => { - setActivePage(id); - onNavigate?.(); - }; - const toggleExpand = (id) => { - setExpanded((e) => ({ - ...e, - [id]: !e[id] - })); - }; - const renderTree = (parentId, depth = 0) => { - return (childrenOf.get(parentId) ?? []).map((page) => { - const hasKids = (childrenOf.get(page.id) ?? []).length > 0; - const isOpen = expanded[page.id] ?? depth < 1; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: cn("group flex items-center gap-0.5 rounded-md pr-1 text-sm transition-colors", activePageId === page.id ? "bg-sidebar-active text-foreground" : "text-sidebar-fg hover:bg-sidebar-hover"), - style: { paddingLeft: `${8 + depth * 12}px` }, - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - className: cn("flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-black/5 dark:hover:bg-white/10", !hasKids && "opacity-0"), - onClick: () => toggleExpand(page.id), - "aria-label": isOpen ? "Collapse" : "Expand", - tabIndex: hasKids ? 0 : -1, - children: isOpen ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronDown, { className: "size-3.5" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: "size-3.5" }) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { - type: "button", - className: "flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left", - onClick: () => select(page.id), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "shrink-0 text-sm leading-none", - children: page.icon - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "truncate font-medium", - children: page.title || "Untitled" - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex shrink-0 items-center opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenu, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuTrigger, { - asChild: true, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - className: "flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10", - "aria-label": "Page options", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Ellipsis, { className: "size-3.5 text-muted-foreground" }) - }) - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuContent, { - align: "start", - className: "w-48", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: () => updatePage(page.id, { favorite: !page.favorite }), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Star, { className: "size-4" }), page.favorite ? "Remove favorite" : "Add to favorites"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: () => createPage({ parentId: page.id }), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-4" }), " Add sub-page"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: () => duplicatePage(page.id), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Copy, { className: "size-4" }), " Duplicate"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator, {}), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - className: "text-destructive focus:text-destructive", - onClick: () => deletePage(page.id), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trash2, { className: "size-4" }), " Delete"] - }) - ] - })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - className: "flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10", - "aria-label": "New sub-page", - onClick: () => { - createPage({ parentId: page.id }); - setExpanded((e) => ({ - ...e, - [page.id]: true - })); - }, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-3.5 text-muted-foreground" }) - })] - }) - ] - }), hasKids && isOpen && renderTree(page.id, depth + 1)] }, page.id); - }); - }; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("aside", { - className: cn("flex h-full flex-col border-r border-sidebar-border bg-sidebar text-sidebar-fg", mobile ? "w-full" : "w-[260px] min-w-[260px]"), - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex items-center gap-2 px-3 pb-1 pt-3", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { - type: "button", - className: "flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-sidebar-hover", - onClick: () => setSettingsOpen(true), - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "flex size-6 shrink-0 items-center justify-center rounded-md bg-foreground text-[11px] font-semibold text-background", - children: name.slice(0, 1).toUpperCase() || "W" - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "truncate text-sm font-semibold text-foreground", - children: name - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronDown, { className: "size-3.5 shrink-0 text-muted-foreground" }) - ] - }), !mobile && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - variant: "ghost", - size: "icon-sm", - className: "shrink-0 text-muted-foreground", - onClick: toggleSidebar, - "aria-label": "Close sidebar", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PanelLeftClose, { className: "size-4" }) - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "space-y-0.5 px-2 py-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { - icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Search, { className: "size-4" }), - label: "Search", - shortcut: "⌘K", - onClick: onOpenSearch - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { - icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FilePlus, { className: "size-4" }), - label: "New page", - onClick: () => createPage() - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(ScrollArea, { - className: "flex-1 px-2", - children: [favorites.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "mb-3", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "px-2 py-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground", - children: "Favorites" - }), favorites.map((page) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { - type: "button", - onClick: () => select(page.id), - className: cn("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors", activePageId === page.id ? "bg-sidebar-active text-foreground" : "text-sidebar-fg hover:bg-sidebar-hover"), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-sm leading-none", - children: page.icon - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "truncate font-medium", - children: page.title || "Untitled" - })] - }, `fav-${page.id}`))] - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "mb-3", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex items-center justify-between px-2 py-1", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-[11px] font-medium uppercase tracking-wide text-muted-foreground", - children: "Private" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - className: "flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-sidebar-hover", - onClick: () => createPage(), - "aria-label": "New page", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-3.5" }) - })] - }), - renderTree(null), - active.filter((p) => !p.parentId).length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "px-2 py-2 text-xs text-muted-foreground", - children: "No pages yet" - }) - ] - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "space-y-0.5 border-t border-sidebar-border p-2", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "flex items-center gap-2 rounded-md px-2 py-1.5 text-xs text-muted-foreground", - children: storageMode === "database" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Cloud, { className: "size-3.5 shrink-0" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "truncate", - children: syncStatus === "error" ? "Database sync error" : syncStatus === "saving" || syncStatus === "pending" ? "Saving to database…" : "Synced to database" - })] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CloudOff, { className: "size-3.5 shrink-0" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "truncate", - children: "Local browser only" - })] }) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "px-1 py-1", - children: user ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(UserButton, {}) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Link, { - to: "/login", - className: "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-fg transition-colors hover:bg-sidebar-hover", - onClick: onNavigate, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(LogIn, { className: "size-4 text-muted-foreground" }), "Sign in to sync"] - }) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { - icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trash2, { className: "size-4" }), - label: "Trash", - onClick: () => setTrashOpen(true) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SidebarAction, { - icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Settings, { className: "size-4" }), - label: "Settings", - onClick: () => setSettingsOpen(true) - }) - ] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, { - open: trashOpen, - onOpenChange: setTrashOpen, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, { - className: "max-w-md", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogTitle, { children: "Trash" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogDescription, { children: "Restored pages return to the top level of your workspace." })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "max-h-72 space-y-1 overflow-y-auto", - children: [archived.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "py-8 text-center text-sm text-muted-foreground", - children: "Trash is empty" - }), archived.map((page) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex items-center gap-2 rounded-lg border border-border px-3 py-2", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: page.icon }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "min-w-0 flex-1 truncate text-sm font-medium", - children: page.title || "Untitled" - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - size: "sm", - variant: "ghost", - onClick: () => restorePage(page.id), - children: "Restore" - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - size: "sm", - variant: "ghost", - className: "text-destructive", - onClick: () => permanentlyDeletePage(page.id), - children: "Delete" - }) - ] - }, page.id))] - })] - }) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, { - open: settingsOpen, - onOpenChange: setSettingsOpen, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, { - className: "max-w-md", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogTitle, { children: "Workspace settings" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogDescription, { children: storageMode === "database" ? "Changes save to your database automatically." : "Guest data stays in this browser. Sign in to sync to the database." })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "space-y-4", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { - className: "block space-y-1.5", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-sm font-medium", - children: "Workspace name" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { - className: "flex h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/40", - value: name, - onChange: (e) => setName(e.target.value) - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "space-y-1.5", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-sm font-medium", - children: "Appearance" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex gap-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - variant: theme === "light" ? "secondary" : "outline", - className: "flex-1", - onClick: () => setTheme("light"), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sun, { className: "size-4" }), " Light"] - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - variant: theme === "dark" ? "secondary" : "outline", - className: "flex-1", - onClick: () => setTheme("dark"), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Moon, { className: "size-4" }), " Dark"] - })] - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "rounded-lg border border-border bg-muted/40 p-3 text-xs leading-relaxed text-muted-foreground", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "font-medium text-foreground", - children: "Storage" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "mt-1", - children: storageMode === "database" ? "Postgres (Neon when deployed, embedded PGLite in this preview)." : "Browser localStorage only. Sign in to use the database." - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - variant: "outline", - className: "w-full", - onClick: () => { - resetWorkspace(); - setSettingsOpen(false); - }, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(RotateCcw, { className: "size-4" }), " Reset demo content"] - }) - ] - })] - }) - }) - ] - }); -} -function SidebarAction({ icon, label, shortcut, onClick }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { - type: "button", - onClick, - className: "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm text-sidebar-fg transition-colors hover:bg-sidebar-hover", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-muted-foreground", - children: icon - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "flex-1 text-left font-medium", - children: label - }), - shortcut && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-[11px] text-muted-foreground", - children: shortcut - }) - ] - }); -} -var Popover = Popover$1; -var PopoverTrigger = PopoverTrigger$1; -function PopoverContent({ className, align = "center", sideOffset = 6, ...props }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PopoverPortal, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PopoverContent$1, { - align, - sideOffset, - className: cn("z-50 w-72 rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-lg outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95", className), - ...props - }) }); -} -var BLOCK_TYPES = [ - { - type: "paragraph", - label: "Text", - description: "Just start writing with plain text.", - icon: Type, - keywords: [ - "text", - "paragraph", - "plain" - ], - placeholder: "Type '/' for commands" - }, - { - type: "heading1", - label: "Heading 1", - description: "Big section heading.", - icon: Heading1, - keywords: [ - "h1", - "title", - "heading" - ], - placeholder: "Heading 1" - }, - { - type: "heading2", - label: "Heading 2", - description: "Medium section heading.", - icon: Heading2, - keywords: [ - "h2", - "heading", - "subtitle" - ], - placeholder: "Heading 2" - }, - { - type: "heading3", - label: "Heading 3", - description: "Small section heading.", - icon: Heading3, - keywords: ["h3", "heading"], - placeholder: "Heading 3" - }, - { - type: "bullet", - label: "Bulleted list", - description: "Create a simple bulleted list.", - icon: List, - keywords: [ - "ul", - "list", - "bullet", - "unordered" - ], - placeholder: "List item" - }, - { - type: "numbered", - label: "Numbered list", - description: "Create a list with numbering.", - icon: ListOrdered, - keywords: [ - "ol", - "list", - "number", - "ordered" - ], - placeholder: "List item" - }, - { - type: "todo", - label: "To-do list", - description: "Track tasks with a to-do checkbox.", - icon: SquareCheckBig, - keywords: [ - "todo", - "task", - "checkbox", - "check" - ], - placeholder: "To-do" - }, - { - type: "toggle", - label: "Toggle", - description: "Hide and show content inside.", - icon: ChevronRight, - keywords: [ - "toggle", - "collapse", - "details" - ], - placeholder: "Toggle heading" - }, - { - type: "quote", - label: "Quote", - description: "Capture a quote.", - icon: Quote, - keywords: [ - "quote", - "blockquote", - "cite" - ], - placeholder: "Empty quote" - }, - { - type: "callout", - label: "Callout", - description: "Make writing stand out.", - icon: MessageSquare, - keywords: [ - "callout", - "note", - "info", - "tip" - ], - placeholder: "Callout" - }, - { - type: "code", - label: "Code", - description: "Capture a code snippet.", - icon: CodeXml, - keywords: [ - "code", - "snippet", - "pre" - ], - placeholder: "Code" - }, - { - type: "mermaid", - label: "Mermaid", - description: "Diagram with Mermaid syntax.", - icon: Workflow, - keywords: [ - "mermaid", - "diagram", - "flowchart", - "sequence", - "graph" - ], - placeholder: "flowchart TD\n A[Start] --> B[End]" - }, - { - type: "ai", - label: "AI", - description: "Generate from the rest of this page.", - icon: Sparkles, - keywords: [ - "ai", - "gpt", - "grok", - "summary", - "assistant", - "llm" - ], - placeholder: "Summarize this page as a launch checklist…" - }, - { - type: "divider", - label: "Divider", - description: "Visually divide blocks.", - icon: Minus, - keywords: [ - "divider", - "line", - "hr", - "separator" - ], - placeholder: "" - } -]; -function getBlockMeta(type) { - return BLOCK_TYPES.find((b) => b.type === type) ?? BLOCK_TYPES[0]; -} -function filterBlockTypes(query) { - const q = query.trim().toLowerCase(); - if (!q) return BLOCK_TYPES; - return BLOCK_TYPES.filter((b) => b.label.toLowerCase().includes(q) || b.description.toLowerCase().includes(q) || b.keywords.some((k) => k.includes(q))); -} -function SlashMenu({ query, selectedIndex, onSelect, onHover, position }) { - const items = (0, import_react.useMemo)(() => filterBlockTypes(query), [query]); - const listRef = (0, import_react.useRef)(null); - (0, import_react.useEffect)(() => { - (listRef.current?.querySelector(`[data-index="${selectedIndex}"]`))?.scrollIntoView({ block: "nearest" }); - }, [selectedIndex]); - if (items.length === 0) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "fixed z-50 w-72 overflow-hidden rounded-xl border border-border bg-popover p-3 text-sm text-muted-foreground shadow-xl", - style: { - top: position.top, - left: position.left - }, - children: "No matching blocks" - }); - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - ref: listRef, - className: "fixed z-50 max-h-72 w-72 overflow-y-auto rounded-xl border border-border bg-popover p-1.5 shadow-xl", - style: { - top: position.top, - left: Math.min(position.left, window.innerWidth - 300) - }, - role: "listbox", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "px-2 py-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground", - children: "Basic blocks" - }), items.map((item, index) => { - const Icon = item.icon; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { - type: "button", - "data-index": index, - role: "option", - "aria-selected": index === selectedIndex, - className: cn("flex w-full items-start gap-2.5 rounded-lg px-2 py-2 text-left transition-colors", index === selectedIndex ? "bg-muted" : "hover:bg-muted/70"), - onMouseEnter: () => onHover(index), - onMouseDown: (e) => { - e.preventDefault(); - onSelect(item.type); - }, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { className: "size-4" }) - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { - className: "min-w-0", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "block text-sm font-medium text-foreground", - children: item.label - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "block truncate text-xs text-muted-foreground", - children: item.description - })] - })] - }, item.type); - })] - }); -} -var mermaidReady = null; -function loadMermaid() { - if (!mermaidReady) mermaidReady = import("../_libs/mermaid+[...].mjs").then((n) => n.t).then((mod) => { - const mermaid = mod.default; - mermaid.initialize({ - startOnLoad: false, - securityLevel: "strict", - theme: document.documentElement.classList.contains("dark") ? "dark" : "neutral", - fontFamily: "inherit" - }); - return mermaid; - }); - return mermaidReady; -} -function MermaidDiagram({ source, className }) { - const reactId = (0, import_react.useId)().replace(/:/g, ""); - const containerRef = (0, import_react.useRef)(null); - const [error, setError] = (0, import_react.useState)(null); - const [svg, setSvg] = (0, import_react.useState)(""); - (0, import_react.useEffect)(() => { - let cancelled = false; - const code = source.trim(); - if (!code) { - setSvg(""); - setError(null); - return; - } - (async () => { - try { - const mermaid = await loadMermaid(); - mermaid.initialize({ - startOnLoad: false, - securityLevel: "strict", - theme: document.documentElement.classList.contains("dark") ? "dark" : "neutral", - fontFamily: "inherit" - }); - const id = `mmd_${reactId}_${Math.random().toString(36).slice(2, 8)}`; - const { svg: rendered } = await mermaid.render(id, code); - if (!cancelled) { - setSvg(rendered); - setError(null); - } - } catch (e) { - if (!cancelled) { - setSvg(""); - setError(e instanceof Error ? e.message : "Invalid Mermaid diagram"); - } - } - })(); - return () => { - cancelled = true; - }; - }, [source, reactId]); - if (!source.trim()) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "text-sm text-muted-foreground", - children: "Write Mermaid syntax (e.g. flowchart TD) — diagram previews here." - }); - if (error) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive", - children: error - }); - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - ref: containerRef, - className: cn("overflow-x-auto rounded-md border border-border bg-background px-3 py-4 [&_svg]:mx-auto [&_svg]:max-w-full", className), - dangerouslySetInnerHTML: svg ? { __html: svg } : void 0 - }); -} -var createSsrRpc = (functionId) => { - const url = "/_serverFn/" + functionId; - const serverFnMeta = { id: functionId }; - const fn = async (...args) => { - return (await getServerFnById(functionId, { origin: "server" }))(...args); - }; - return Object.assign(fn, { - url, - serverFnMeta, - [TSS_SERVER_FUNCTION]: true - }); -}; -function validateRequest(input) { - const data = input; - if (!data || typeof data !== "object") throw new Error("Invalid AI request"); - const action = data.action; - if (![ - "edit_block", - "summarize", - "action_items", - "table", - "outline", - "mermaid", - "custom" - ].includes(action)) throw new Error("Invalid AI action"); - return { - action, - instruction: typeof data.instruction === "string" ? data.instruction.slice(0, 4e3) : "", - blockText: typeof data.blockText === "string" ? data.blockText.slice(0, 8e3) : "", - blockType: data.blockType, - pageTitle: typeof data.pageTitle === "string" ? data.pageTitle.slice(0, 500) : "", - pageText: typeof data.pageText === "string" ? data.pageText.slice(0, 2e4) : "" - }; -} -/** Local heuristic fallback so the preview is demoable without XAI_API_KEY. */ -var runAi = createServerFn({ method: "POST" }).validator((input) => validateRequest(input)).handler(createSsrRpc("76d08ea8f0b0103fcaf7055c8b138a9579e4124d0d2f62a0686a1011273cd47a")); -createServerFn({ method: "GET" }).handler(createSsrRpc("5252add61246cf72a4fa382b4734734c4e8ea74302302ba378f1ecb54d53868d")); -var PRESETS$1 = [ - { - action: "summarize", - label: "Summary", - icon: FileText, - hint: "Condense the page" - }, - { - action: "action_items", - label: "Todos", - icon: ListTodo, - hint: "Extract action items" - }, - { - action: "table", - label: "Table", - icon: Table2, - hint: "Markdown table" - }, - { - action: "outline", - label: "Outline", - icon: ListTree, - hint: "Hierarchical outline" - }, - { - action: "mermaid", - label: "Diagram", - icon: Workflow, - hint: "Mermaid flowchart" - } -]; -function AiBlockPanel({ content, aiOutput, aiError, pageTitle, pageText, onChangePrompt, onResult }) { - const [loading, setLoading] = (0, import_react.useState)(false); - const [provider, setProvider] = (0, import_react.useState)(null); - const execute = async (action, instruction) => { - setLoading(true); - try { - const res = await runAi({ data: { - action, - instruction: instruction ?? content, - pageTitle, - pageText - } }); - setProvider(res.provider === "xai" ? res.model ?? "Grok" : "Local demo AI"); - onResult({ - output: res.text || (res.blocks ? res.blocks.map((b) => `${b.type}: ${b.content}`).join("\n") : ""), - blocks: res.blocks - }); - } catch (e) { - onResult({ - output: "", - error: e instanceof Error ? e.message : "AI request failed" - }); - } finally { - setLoading(false); - } - }; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "w-full space-y-3 rounded-xl border border-border bg-muted/30 p-3", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex items-center gap-2 text-sm font-medium text-foreground", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "flex size-7 items-center justify-center rounded-md bg-foreground text-background", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-3.5" }) - }), - "AI block", - provider && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "ml-auto text-[11px] font-normal text-muted-foreground", - children: provider - }) - ] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "text-xs text-muted-foreground", - children: "Uses the rest of this page as context. Inserts results below this block." - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "flex flex-wrap gap-1.5", - children: PRESETS$1.map((p) => { - const Icon = p.icon; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - size: "sm", - variant: "outline", - className: "bg-background", - disabled: loading, - title: p.hint, - onClick: () => void execute(p.action), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { className: "size-3.5" }), p.label] - }, p.action); - }) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { - value: content, - onChange: (e) => onChangePrompt(e.target.value), - placeholder: "Custom instruction — e.g. Turn this into a launch checklist…", - rows: 2, - className: "w-full resize-y rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/40" - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex items-center gap-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - size: "sm", - disabled: loading || !content.trim(), - onClick: () => void execute("custom", content.trim()), - children: [loading ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-3.5 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Play, { className: "size-3.5" }), "Run custom"] - }), loading && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-xs text-muted-foreground", - children: "Thinking…" - })] - }), - aiError && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "text-sm text-destructive", - children: aiError - }), - aiOutput && !aiError && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: cn("rounded-md border border-border bg-background px-3 py-2 text-xs text-muted-foreground"), - children: "Last run applied below this block." - }) - ] - }); -} -var PRESETS = [ - { - id: "improve", - label: "Improve", - instruction: "Improve clarity and flow while preserving meaning." - }, - { - id: "shorter", - label: "Shorter", - instruction: "Make this shorter and more concise." - }, - { - id: "longer", - label: "Expand", - instruction: "Expand this with one more sentence of useful detail." - }, - { - id: "fix", - label: "Fix grammar", - instruction: "Fix grammar and spelling only." - }, - { - id: "pro", - label: "Professional", - instruction: "Rewrite in a clear, professional tone." - } -]; -function AiEditDialog({ open, onOpenChange, blockText, blockType, pageTitle, pageText, onApply }) { - const [instruction, setInstruction] = (0, import_react.useState)(""); - const [preview, setPreview] = (0, import_react.useState)(null); - const [loading, setLoading] = (0, import_react.useState)(false); - const [error, setError] = (0, import_react.useState)(null); - const [provider, setProvider] = (0, import_react.useState)(null); - const run = async (instr) => { - setLoading(true); - setError(null); - try { - const res = await runAi({ data: { - action: "edit_block", - instruction: instr, - blockText, - blockType, - pageTitle, - pageText - } }); - setPreview(res.text); - setProvider(res.provider === "xai" ? res.model ?? "Grok" : "Local demo AI"); - } catch (e) { - setError(e instanceof Error ? e.message : "AI request failed"); - } finally { - setLoading(false); - } - }; - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, { - open, - onOpenChange: (v) => { - if (!v) { - setPreview(null); - setError(null); - setInstruction(""); - } - onOpenChange(v); - }, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, { - className: "max-w-lg", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogTitle, { - className: "flex items-center gap-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-4" }), "Edit block with AI"] - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogDescription, { children: [ - "Rewrite this block. Uses Grok when ", - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { - className: "text-xs", - children: "XAI_API_KEY" - }), - " is set; otherwise a local demo fallback." - ] })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "space-y-3", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "rounded-lg border border-border bg-muted/40 px-3 py-2 text-sm text-muted-foreground", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "mb-1 text-[11px] font-medium uppercase tracking-wide", - children: "Original" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "whitespace-pre-wrap text-foreground", - children: blockText || "(empty)" - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "flex flex-wrap gap-1.5", - children: PRESETS.map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - size: "sm", - variant: "outline", - disabled: loading, - onClick: () => void run(p.instruction), - children: p.label - }, p.id)) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex gap-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { - className: "flex h-9 min-w-0 flex-1 rounded-md border border-border bg-background px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/40", - placeholder: "Custom instruction…", - value: instruction, - onChange: (e) => setInstruction(e.target.value), - onKeyDown: (e) => { - if (e.key === "Enter" && instruction.trim()) run(instruction.trim()); - } - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - disabled: loading || !instruction.trim(), - onClick: () => void run(instruction.trim()), - children: [loading ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-4 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WandSparkles, { className: "size-4" }), "Run"] - })] - }), - error && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "text-sm text-destructive", - children: error - }), - preview != null && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "space-y-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "rounded-lg border border-border bg-background px-3 py-2 text-sm", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "mb-1 flex items-center justify-between text-[11px] font-medium uppercase tracking-wide text-muted-foreground", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "Suggestion" }), provider && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "normal-case", - children: provider - })] - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: cn("whitespace-pre-wrap text-foreground"), - children: preview - })] - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex justify-end gap-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - variant: "ghost", - onClick: () => setPreview(null), - children: "Discard" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - onClick: () => { - onApply(preview); - onOpenChange(false); - setPreview(null); - setInstruction(""); - }, - children: "Replace block" - })] - })] - }) - ] - })] - }) - }); -} -function BlockRow({ block, index, isFocused, listNumber, pageTitle, pageText, onFocus, onChange, onTypeChange, onToggleCheck, onToggleCollapse, onEnter, onBackspaceEmpty, onMove, onDelete, onIndent, onPatch, onAiInsert, focusRequest, onFocusHandled, inputRefs }) { - const meta = getBlockMeta(block.type); - const areaRef = (0, import_react.useRef)(null); - const rowRef = (0, import_react.useRef)(null); - const [slashOpen, setSlashOpen] = (0, import_react.useState)(false); - const [slashQuery, setSlashQuery] = (0, import_react.useState)(""); - const [slashIndex, setSlashIndex] = (0, import_react.useState)(0); - const [slashPos, setSlashPos] = (0, import_react.useState)({ - top: 0, - left: 0 - }); - const [hovered, setHovered] = (0, import_react.useState)(false); - const [aiOpen, setAiOpen] = (0, import_react.useState)(false); - const setRef = (0, import_react.useCallback)((el) => { - areaRef.current = el; - if (el) inputRefs.current.set(block.id, el); - else inputRefs.current.delete(block.id); - }, [block.id, inputRefs]); - const autosize = (0, import_react.useCallback)(() => { - const el = areaRef.current; - if (!el) return; - el.style.height = "0px"; - el.style.height = `${Math.max(el.scrollHeight, 28)}px`; - }, []); - (0, import_react.useEffect)(() => { - autosize(); - }, [ - block.content, - block.type, - autosize - ]); - (0, import_react.useEffect)(() => { - if (focusRequest !== block.id) return; - const el = areaRef.current; - if (el) { - el.focus(); - const len = el.value.length; - el.setSelectionRange(len, len); - } - onFocusHandled(); - }, [ - focusRequest, - block.id, - onFocusHandled - ]); - const openSlash = (query) => { - const el = rowRef.current; - if (!el) return; - const rect = el.getBoundingClientRect(); - const left = Math.min(rect.left + 48, window.innerWidth - 300); - const top = rect.bottom + 280 > window.innerHeight ? Math.max(8, rect.top - 280) : rect.bottom + 4; - setSlashPos({ - top, - left - }); - setSlashQuery(query); - setSlashIndex(0); - setSlashOpen(true); - }; - const closeSlash = () => { - setSlashOpen(false); - setSlashQuery(""); - setSlashIndex(0); - }; - const applySlash = (type) => { - const content = block.content; - const slashIdx = content.lastIndexOf("/"); - const cleaned = slashIdx >= 0 ? content.slice(0, slashIdx) : content; - onChange(block.id, cleaned); - onTypeChange(block.id, type); - closeSlash(); - requestAnimationFrame(() => { - inputRefs.current.get(block.id)?.focus(); - }); - }; - const handleChange = (value) => { - onChange(block.id, value); - requestAnimationFrame(autosize); - const slashIdx = value.lastIndexOf("/"); - if (slashIdx >= 0) { - const after = value.slice(slashIdx + 1); - const before = value[slashIdx - 1]; - if ((slashIdx === 0 || before === " " || before === "\n") && !after.includes("\n")) { - openSlash(after); - return; - } - } - if (slashOpen) closeSlash(); - }; - const handleKeyDown = (e) => { - if (slashOpen) { - const items = filterBlockTypes(slashQuery); - if (e.key === "ArrowDown") { - e.preventDefault(); - setSlashIndex((i) => (i + 1) % Math.max(items.length, 1)); - return; - } - if (e.key === "ArrowUp") { - e.preventDefault(); - setSlashIndex((i) => (i - 1 + Math.max(items.length, 1)) % Math.max(items.length, 1)); - return; - } - if (e.key === "Enter" || e.key === "Tab") { - e.preventDefault(); - const pick = items[slashIndex]; - if (pick) applySlash(pick.type); - return; - } - if (e.key === "Escape") { - e.preventDefault(); - closeSlash(); - return; - } - } - if (e.key === "Enter" && !e.shiftKey && block.type !== "code" && block.type !== "mermaid") { - e.preventDefault(); - onEnter(block.id); - return; - } - if (e.key === "Backspace") { - const el = e.currentTarget; - if (!el.value && el.selectionStart === 0) { - e.preventDefault(); - onBackspaceEmpty(block.id); - return; - } - } - if (e.key === "Tab") { - e.preventDefault(); - onIndent(block.id, e.shiftKey ? -1 : 1); - } - if (e.key === "ArrowUp" && (e.metaKey || e.ctrlKey)) { - e.preventDefault(); - onMove(block.id, "up"); - } - if (e.key === "ArrowDown" && (e.metaKey || e.ctrlKey)) { - e.preventDefault(); - onMove(block.id, "down"); - } - }; - const indentStyle = { paddingLeft: `${(block.indent ?? 0) * 1.5}rem` }; - const canAiEdit = block.type !== "divider" && block.type !== "ai" && block.type !== "mermaid"; - if (block.type === "divider") return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - ref: rowRef, - className: "group relative flex items-center gap-1 py-2", - style: indentStyle, - onMouseEnter: () => setHovered(true), - onMouseLeave: () => setHovered(false), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockHandles, { - visible: hovered || isFocused, - canAiEdit: false, - onAdd: () => onEnter(block.id), - onMoveUp: () => onMove(block.id, "up"), - onMoveDown: () => onMove(block.id, "down"), - onDelete: () => onDelete(block.id), - onTypeChange: (t) => onTypeChange(block.id, t), - onAiEdit: () => setAiOpen(true) - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("hr", { className: "w-full border-0 border-t border-border" })] - }); - if (block.type === "ai") return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - ref: rowRef, - className: "group relative py-1", - style: indentStyle, - onMouseEnter: () => setHovered(true), - onMouseLeave: () => setHovered(false), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockHandles, { - visible: hovered || isFocused, - canAiEdit: false, - onAdd: () => onEnter(block.id), - onMoveUp: () => onMove(block.id, "up"), - onMoveDown: () => onMove(block.id, "down"), - onDelete: () => onDelete(block.id), - onTypeChange: (t) => onTypeChange(block.id, t), - onAiEdit: () => void 0 - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "pl-1", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AiBlockPanel, { - content: block.content, - aiOutput: block.aiOutput, - aiError: block.aiError, - pageTitle, - pageText, - onChangePrompt: (v) => onChange(block.id, v), - onResult: ({ output, blocks, error }) => { - onPatch(block.id, { - aiOutput: output, - aiError: error - }); - if (blocks?.length) onAiInsert(block.id, blocks); - } - }) - })] - }); - if (block.type === "mermaid") { - const showSource = block.showSource ?? !block.content.trim(); - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - ref: rowRef, - className: "group relative py-1", - style: indentStyle, - onMouseEnter: () => setHovered(true), - onMouseLeave: () => setHovered(false), - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockHandles, { - visible: hovered || isFocused, - canAiEdit: false, - onAdd: () => onEnter(block.id), - onMoveUp: () => onMove(block.id, "up"), - onMoveDown: () => onMove(block.id, "down"), - onDelete: () => onDelete(block.id), - onTypeChange: (t) => onTypeChange(block.id, t), - onAiEdit: () => void 0 - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "space-y-2 rounded-xl border border-border bg-muted/20 p-3", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex items-center justify-between gap-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", - children: "Mermaid" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - size: "sm", - variant: "ghost", - className: "h-7 text-muted-foreground", - onClick: () => onPatch(block.id, { showSource: !showSource }), - children: showSource ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Eye, { className: "size-3.5" }), " Preview"] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CodeXml, { className: "size-3.5" }), " Edit source"] }) - })] - }), showSource ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { - ref: setRef, - value: block.content, - onChange: (e) => handleChange(e.target.value), - onFocus: () => onFocus(block.id), - onKeyDown: handleKeyDown, - placeholder: meta.placeholder, - rows: Math.max(4, block.content.split("\n").length), - spellCheck: false, - className: "w-full resize-y rounded-md border border-border bg-background px-3 py-2 font-mono text-sm leading-relaxed text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/40" - }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(MermaidDiagram, { source: block.content })] - }), - slashOpen && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SlashMenu, { - query: slashQuery, - selectedIndex: slashIndex, - onSelect: applySlash, - onHover: setSlashIndex, - position: slashPos - }) - ] - }); - } - const fieldClass = cn("block w-full resize-none overflow-hidden border-0 bg-background p-0 text-foreground shadow-none outline-none ring-0 focus:outline-none focus:ring-0", "placeholder:text-muted-foreground/60", block.type === "paragraph" && "text-base leading-relaxed", block.type === "heading1" && "text-3xl font-semibold leading-tight tracking-tight", block.type === "heading2" && "text-2xl font-semibold leading-tight tracking-tight", block.type === "heading3" && "text-xl font-semibold leading-snug tracking-tight", (block.type === "bullet" || block.type === "numbered") && "text-base leading-relaxed", block.type === "todo" && cn("text-base leading-relaxed", block.checked && "text-muted-foreground line-through"), block.type === "toggle" && "text-base font-medium leading-relaxed", block.type === "quote" && "text-base leading-relaxed text-muted-foreground", block.type === "callout" && "text-base leading-relaxed", block.type === "code" && "min-h-16 font-mono text-sm leading-relaxed"); - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - ref: rowRef, - className: cn("group relative flex items-start gap-1 rounded-md py-0.5", isFocused && "bg-muted/40"), - style: indentStyle, - onMouseEnter: () => setHovered(true), - onMouseLeave: () => setHovered(false), - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockHandles, { - visible: hovered || isFocused, - canAiEdit, - onAdd: () => onEnter(block.id), - onMoveUp: () => onMove(block.id, "up"), - onMoveDown: () => onMove(block.id, "down"), - onDelete: () => onDelete(block.id), - onTypeChange: (t) => onTypeChange(block.id, t), - onAiEdit: () => setAiOpen(true) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: cn("flex min-w-0 flex-1 items-start gap-2 rounded-md px-1 py-1", block.type === "callout" && "border border-border bg-muted/50 px-3 py-2.5", block.type === "quote" && "border-l-2 border-foreground/25 pl-3", block.type === "code" && "border border-border bg-muted/60 px-3 py-2.5"), - children: [ - block.type === "bullet" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "mt-2.5 size-1.5 shrink-0 rounded-full bg-foreground/80" }), - block.type === "numbered" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { - className: "mt-1 w-5 shrink-0 text-right text-sm tabular-nums text-muted-foreground", - children: [listNumber ?? index + 1, "."] - }), - block.type === "todo" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - className: cn("mt-1.5 flex size-4 shrink-0 items-center justify-center rounded border transition-colors", block.checked ? "border-primary bg-primary text-primary-foreground" : "border-border bg-background hover:border-foreground/40"), - onClick: () => onToggleCheck(block.id), - "aria-label": block.checked ? "Mark incomplete" : "Mark complete", - children: block.checked && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Check, { - className: "size-3", - strokeWidth: 3 - }) - }), - block.type === "toggle" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - className: "mt-1 flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted", - onClick: () => onToggleCollapse(block.id), - "aria-label": block.collapsed ? "Expand" : "Collapse", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: cn("size-4 text-muted-foreground transition-transform duration-150", !block.collapsed && "rotate-90") }) - }), - block.type === "callout" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "mt-1 shrink-0 text-base leading-none", - "aria-hidden": true, - children: "💡" - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { - ref: setRef, - value: block.content, - onChange: (e) => handleChange(e.target.value), - onFocus: () => onFocus(block.id), - onKeyDown: handleKeyDown, - placeholder: meta.placeholder, - rows: 1, - spellCheck: block.type !== "code", - className: fieldClass - }) - ] - }), - slashOpen && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SlashMenu, { - query: slashQuery, - selectedIndex: slashIndex, - onSelect: applySlash, - onHover: setSlashIndex, - position: slashPos - }), - canAiEdit && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AiEditDialog, { - open: aiOpen, - onOpenChange: setAiOpen, - blockText: block.content, - blockType: block.type, - pageTitle, - pageText, - onApply: (text) => onChange(block.id, text) - }) - ] - }); -} -function BlockHandles({ visible, canAiEdit, onAdd, onMoveUp, onMoveDown, onDelete, onTypeChange, onAiEdit }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: cn("absolute -left-12 top-1 flex items-center gap-0.5 opacity-0 transition-opacity max-sm:-left-10", visible && "opacity-100"), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - variant: "ghost", - size: "icon-sm", - className: "text-muted-foreground", - onClick: onAdd, - "aria-label": "Add block below", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-3.5" }) - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenu, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuTrigger, { - asChild: true, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - variant: "ghost", - size: "icon-sm", - className: "text-muted-foreground", - "aria-label": "Block menu", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(GripVertical, { className: "size-3.5" }) - }) - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuContent, { - align: "start", - className: "w-48", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuLabel, { children: "Block" }), - canAiEdit && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: onAiEdit, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-4" }), " Edit with AI"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: onMoveUp, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ArrowUp, { className: "size-4" }), " Move up"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: onMoveDown, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ArrowDown, { className: "size-4" }), " Move down"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuSub, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuSubTrigger, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Ellipsis, { className: "size-4" }), " Turn into"] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSubContent, { - className: "max-h-64 overflow-y-auto", - children: BLOCK_TYPES.map((t) => { - const Icon = t.icon; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: () => onTypeChange(t.type), - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { className: "size-4" }), - " ", - t.label - ] - }, t.type); - }) - })] }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator, {}), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - className: "text-destructive focus:text-destructive", - onClick: onDelete, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trash2, { className: "size-4" }), " Delete"] - }) - ] - })] })] - }); -} -function blocksToPlainText(page) { - return page.blocks.filter((b) => b.type !== "ai" && b.type !== "divider").map((b) => { - return `${b.type === "heading1" ? "# " : b.type === "heading2" ? "## " : b.type === "heading3" ? "### " : b.type === "bullet" ? "- " : b.type === "numbered" ? "1. " : b.type === "todo" ? b.checked ? "[x] " : "[ ] " : b.type === "quote" ? "> " : b.type === "code" || b.type === "mermaid" ? "" : ""}${b.content}`.trim(); - }).filter(Boolean).join("\n"); -} -function PageEditor({ page }) { - const updatePage = useWorkspace((s) => s.updatePage); - const updateBlock = useWorkspace((s) => s.updateBlock); - const insertBlock = useWorkspace((s) => s.insertBlock); - const deleteBlock = useWorkspace((s) => s.deleteBlock); - const changeBlockType = useWorkspace((s) => s.changeBlockType); - const moveBlock = useWorkspace((s) => s.moveBlock); - const deletePage = useWorkspace((s) => s.deletePage); - const duplicatePage = useWorkspace((s) => s.duplicatePage); - const createPage = useWorkspace((s) => s.createPage); - const setBlocks = useWorkspace((s) => s.setBlocks); - const [focusedId, setFocusedId] = (0, import_react.useState)(null); - const [focusRequest, setFocusRequest] = (0, import_react.useState)(null); - const inputRefs = (0, import_react.useRef)(/* @__PURE__ */ new Map()); - const titleRef = (0, import_react.useRef)(null); - const pageText = (0, import_react.useMemo)(() => blocksToPlainText(page), [page]); - const listNumbers = (0, import_react.useMemo)(() => { - const map = /* @__PURE__ */ new Map(); - let n = 0; - for (const b of page.blocks) if (b.type === "numbered") { - n += 1; - map.set(b.id, n); - } else n = 0; - return map; - }, [page.blocks]); - (0, import_react.useEffect)(() => { - const el = titleRef.current; - if (!el) return; - el.style.height = "auto"; - el.style.height = `${el.scrollHeight}px`; - }, [page.title]); - const handleEnter = (0, import_react.useCallback)((blockId) => { - const newId = insertBlock(page.id, blockId, "paragraph", ""); - setFocusRequest(newId); - setFocusedId(newId); - }, [insertBlock, page.id]); - const handleBackspaceEmpty = (0, import_react.useCallback)((blockId) => { - const idx = page.blocks.findIndex((b) => b.id === blockId); - if (idx < 0) return; - const prev = page.blocks[idx - 1]; - deleteBlock(page.id, blockId); - if (prev) { - setFocusRequest(prev.id); - setFocusedId(prev.id); - } - }, [ - deleteBlock, - page.blocks, - page.id - ]); - const handleIndent = (0, import_react.useCallback)((blockId, delta) => { - const block = page.blocks.find((b) => b.id === blockId); - if (!block) return; - const next = Math.max(0, Math.min(4, (block.indent ?? 0) + delta)); - updateBlock(page.id, blockId, { indent: next }); - }, [ - page.blocks, - page.id, - updateBlock - ]); - const handleAiInsert = (0, import_react.useCallback)((afterId, generated) => { - const idx = page.blocks.findIndex((b) => b.id === afterId); - if (idx < 0 || generated.length === 0) return; - const newBlocks = generated.map((g) => ({ - id: uid("b"), - type: g.type, - content: g.content, - indent: 0, - checked: g.type === "todo" ? false : void 0, - showSource: g.type === "mermaid" ? false : void 0 - })); - const next = [...page.blocks]; - next.splice(idx + 1, 0, ...newBlocks); - setBlocks(page.id, next); - setFocusRequest(newBlocks[0].id); - }, [ - page.blocks, - page.id, - setBlocks - ]); - const cover = page.cover ? COVER_PRESETS[page.cover] : null; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "mx-auto w-full max-w-3xl px-4 pb-32 pt-4 sm:px-12 sm:pt-8", - children: [ - cover ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "group/cover relative -mx-4 mb-2 h-36 overflow-hidden rounded-xl sm:-mx-6 sm:h-44", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: cn("absolute inset-0", cover.className) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "absolute bottom-3 right-3 opacity-0 transition-opacity group-hover/cover:opacity-100", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - size: "sm", - variant: "secondary", - className: "bg-background/90 shadow-sm backdrop-blur-sm", - onClick: () => updatePage(page.id, { cover: null }), - children: "Remove cover" - }) - })] - }) : null, - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "mb-1 flex flex-wrap items-end gap-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Popover, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PopoverTrigger, { - asChild: true, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - className: "flex size-16 items-center justify-center rounded-xl text-4xl transition-colors hover:bg-muted", - "aria-label": "Change page icon", - children: page.icon - }) - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(PopoverContent, { - align: "start", - className: "w-72", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "mb-2 text-xs font-medium text-muted-foreground", - children: "Page icon" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "grid grid-cols-8 gap-1", - children: PAGE_ICONS.map((icon) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - className: cn("flex size-8 items-center justify-center rounded-md text-lg transition-colors hover:bg-muted", page.icon === icon && "bg-muted ring-1 ring-border"), - onClick: () => updatePage(page.id, { icon }), - children: icon - }, icon)) - })] - })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "mb-2 flex flex-1 flex-wrap items-center gap-1", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - size: "sm", - variant: "ghost", - className: "text-muted-foreground", - onClick: () => updatePage(page.id, { favorite: !page.favorite }), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Star, { className: cn("size-3.5", page.favorite && "fill-amber-400 text-amber-500") }), page.favorite ? "Unfavorite" : "Favorite"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - size: "sm", - variant: "ghost", - className: "text-muted-foreground", - onClick: () => { - const last = page.blocks[page.blocks.length - 1]; - const id = insertBlock(page.id, last?.id ?? null, "ai", ""); - setFocusRequest(id); - }, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sparkles, { className: "size-3.5" }), "AI block"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenu, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuTrigger, { - asChild: true, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, { - type: "button", - size: "sm", - variant: "ghost", - className: "text-muted-foreground", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Image, { className: "size-3.5" }), "Cover"] - }) - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuContent, { - align: "start", - children: [Object.entries(COVER_PRESETS).map(([key, preset]) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: () => updatePage(page.id, { cover: key }), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: cn("mr-2 size-4 rounded", preset.className) }), preset.label] - }, key)), page.cover && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator, {}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuItem, { - onClick: () => updatePage(page.id, { cover: null }), - children: "Remove cover" - })] })] - })] }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenu, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuTrigger, { - asChild: true, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - size: "sm", - variant: "ghost", - className: "text-muted-foreground", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Ellipsis, { className: "size-3.5" }) - }) - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuContent, { - align: "start", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: () => createPage({ parentId: page.id }), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-4" }), " Add sub-page"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - onClick: () => duplicatePage(page.id), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Copy, { className: "size-4" }), " Duplicate"] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DropdownMenuSeparator, {}), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownMenuItem, { - className: "text-destructive focus:text-destructive", - onClick: () => deletePage(page.id), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trash2, { className: "size-4" }), " Move to trash"] - }) - ] - })] }) - ] - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("textarea", { - ref: titleRef, - value: page.title, - onChange: (e) => updatePage(page.id, { title: e.target.value }), - placeholder: "Untitled", - rows: 1, - className: "mb-4 w-full resize-none overflow-hidden bg-transparent text-4xl font-bold tracking-tight text-foreground outline-none placeholder:text-muted-foreground/50", - onKeyDown: (e) => { - if (e.key === "Enter") { - e.preventDefault(); - const first = page.blocks[0]; - if (first) { - setFocusRequest(first.id); - setFocusedId(first.id); - } - } - } - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "relative space-y-0.5 pl-10 sm:pl-12", - children: page.blocks.map((block, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlockRow, { - pageId: page.id, - block, - index, - isFocused: focusedId === block.id, - listNumber: listNumbers.get(block.id), - pageTitle: page.title, - pageText, - onFocus: setFocusedId, - onChange: (id, content) => updateBlock(page.id, id, { content }), - onTypeChange: (id, type) => changeBlockType(page.id, id, type), - onToggleCheck: (id) => { - const b = page.blocks.find((x) => x.id === id); - if (b) updateBlock(page.id, id, { checked: !b.checked }); - }, - onToggleCollapse: (id) => { - const b = page.blocks.find((x) => x.id === id); - if (b) updateBlock(page.id, id, { collapsed: !b.collapsed }); - }, - onEnter: handleEnter, - onBackspaceEmpty: handleBackspaceEmpty, - onMove: (id, dir) => moveBlock(page.id, id, dir), - onDelete: (id) => deleteBlock(page.id, id), - onIndent: handleIndent, - onPatch: (id, patch) => updateBlock(page.id, id, patch), - onAiInsert: handleAiInsert, - focusRequest, - onFocusHandled: () => setFocusRequest(null), - inputRefs - }, block.id)) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { - type: "button", - className: "mt-2 ml-10 min-h-16 w-[calc(100%-2.5rem)] cursor-text rounded-md sm:ml-12 sm:w-[calc(100%-3rem)]", - "aria-label": "Add block at end", - onClick: () => { - const last = page.blocks[page.blocks.length - 1]; - if (last && last.type === "paragraph" && !last.content) { - setFocusRequest(last.id); - setFocusedId(last.id); - } else { - const id = insertBlock(page.id, last?.id ?? null, "paragraph", ""); - setFocusRequest(id); - setFocusedId(id); - } - } - }) - ] - }); -} -function CommandPalette({ open, onOpenChange }) { - const pages = useWorkspace((s) => s.pages); - const setActivePage = useWorkspace((s) => s.setActivePage); - const createPage = useWorkspace((s) => s.createPage); - const [query, setQuery] = (0, import_react.useState)(""); - (0, import_react.useEffect)(() => { - if (!open) setQuery(""); - }, [open]); - (0, import_react.useEffect)(() => { - const onKey = (e) => { - if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { - e.preventDefault(); - onOpenChange(!open); - } - }; - window.addEventListener("keydown", onKey); - return () => window.removeEventListener("keydown", onKey); - }, [open, onOpenChange]); - const activePages = (0, import_react.useMemo)(() => pages.filter((p) => !p.archived), [pages]); - if (!open) return null; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "fixed inset-0 z-[100]", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "absolute inset-0 bg-black/40", - onClick: () => onOpenChange(false), - "aria-hidden": true - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "absolute left-1/2 top-[18%] w-[min(560px,calc(100%-2rem))] -translate-x-1/2 overflow-hidden rounded-xl border border-border bg-popover shadow-2xl", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(_e, { - className: "flex flex-col", - label: "Search pages", - shouldFilter: true, - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex items-center gap-2 border-b border-border px-3", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Search, { className: "size-4 shrink-0 text-muted-foreground" }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(_e.Input, { - value: query, - onValueChange: setQuery, - placeholder: "Search pages…", - className: "h-12 w-full bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground", - autoFocus: true - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("kbd", { - className: "hidden rounded border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground sm:inline", - children: "ESC" - }) - ] - }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(_e.List, { - className: "max-h-80 overflow-y-auto p-2", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(_e.Empty, { - className: "py-8 text-center text-sm text-muted-foreground", - children: "No pages found" - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(_e.Group, { - heading: "Actions", - className: "[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(_e.Item, { - value: "new page create", - onSelect: () => { - createPage(); - onOpenChange(false); - }, - className: cn("flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-sm aria-selected:bg-muted"), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Plus, { className: "size-4 text-muted-foreground" }), "New page"] - }) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(_e.Group, { - heading: "Pages", - className: "mt-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground", - children: activePages.map((page) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(_e.Item, { - value: `${page.title} ${page.icon} untitled`, - onSelect: () => { - setActivePage(page.id); - onOpenChange(false); - }, - className: "flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-sm aria-selected:bg-muted", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "text-base leading-none", - children: page.icon - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "min-w-0 flex-1 truncate font-medium", - children: page.title || "Untitled" - }), - page.favorite && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Star, { className: "size-3.5 fill-amber-400 text-amber-500" }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FileText, { className: "size-3.5 text-muted-foreground" }) - ] - }, page.id)) - }) - ] - })] - }) - })] - }); -} -function validateSnapshot(input) { - const data = input; - if (!data || typeof data !== "object") throw new Error("Invalid workspace snapshot"); - if (typeof data.name !== "string") throw new Error("Invalid name"); - if (data.theme !== "light" && data.theme !== "dark") throw new Error("Invalid theme"); - if (!Array.isArray(data.pages)) throw new Error("Invalid pages"); - return { - name: data.name.slice(0, 120), - theme: data.theme, - activePageId: data.activePageId ?? null, - sidebarOpen: Boolean(data.sidebarOpen), - pages: data.pages.map((p) => ({ - id: String(p.id), - title: String(p.title ?? "").slice(0, 500), - icon: String(p.icon ?? "📄").slice(0, 16), - cover: p.cover ?? null, - parentId: p.parentId ?? null, - favorite: Boolean(p.favorite), - archived: Boolean(p.archived), - createdAt: Number(p.createdAt) || Date.now(), - updatedAt: Number(p.updatedAt) || Date.now(), - blocks: Array.isArray(p.blocks) ? p.blocks : [] - })) - }; -} -/** Load the signed-in user's workspace. Seeds demo content on first visit. */ -var loadWorkspace = createServerFn({ method: "GET" }).middleware([authMiddleware]).handler(createSsrRpc("e3fb77d67dfdadad5d019581d79338a7f7cf2e42797c44110574e289b39fd293")); -/** Replace the signed-in user's full workspace snapshot (debounced from the client). */ -var saveWorkspace = createServerFn({ method: "POST" }).middleware([authMiddleware]).validator((input) => validateSnapshot(input)).handler(createSsrRpc("7bd9976b9723bbefb2399d41723684e8ed7d3bfcf4f814066bb422e47b4bb658")); -var saveTimer = null; -var saving = false; -var pending = false; -var remoteMode = false; -var bootstrapped = false; -var unsub = null; -function snapshotFromStore() { - const s = useWorkspace.getState(); - return { - name: s.name, - theme: s.theme, - activePageId: s.activePageId, - sidebarOpen: s.sidebarOpen, - pages: s.pages - }; -} -function attachAutosave() { - unsub?.(); - unsub = useWorkspace.subscribe((state, prev) => { - if (!remoteMode || !bootstrapped) return; - if (state.name === prev.name && state.theme === prev.theme && state.activePageId === prev.activePageId && state.sidebarOpen === prev.sidebarOpen && state.pages === prev.pages) return; - scheduleRemoteSave(); - }); -} -/** Load workspace from Postgres for the signed-in user (or seed on first visit). */ -async function bootstrapRemoteWorkspace() { - try { - const data = await loadWorkspace(); - bootstrapped = false; - useWorkspace.setState({ - name: data.name, - theme: data.theme, - activePageId: data.activePageId, - sidebarOpen: data.sidebarOpen, - pages: data.pages, - hydrated: true, - syncStatus: "saved", - storageMode: "database" - }); - remoteMode = true; - bootstrapped = true; - attachAutosave(); - return data.source; - } catch { - remoteMode = false; - bootstrapped = false; - unsub?.(); - unsub = null; - useWorkspace.setState({ - storageMode: "local", - syncStatus: "local", - hydrated: true - }); - return "error"; - } -} -function scheduleRemoteSave() { - if (!remoteMode || !bootstrapped) return; - useWorkspace.setState({ syncStatus: "pending" }); - if (saveTimer) clearTimeout(saveTimer); - saveTimer = setTimeout(() => { - flushRemoteSave(); - }, 600); -} -async function flushRemoteSave() { - if (!remoteMode) return; - if (saving) { - pending = true; - return; - } - saving = true; - useWorkspace.setState({ syncStatus: "saving" }); - try { - await saveWorkspace({ data: snapshotFromStore() }); - useWorkspace.setState({ syncStatus: "saved" }); - } catch { - useWorkspace.setState({ syncStatus: "error" }); - } finally { - saving = false; - if (pending) { - pending = false; - scheduleRemoteSave(); - } - } -} -/** Immediate save (e.g. before unload). */ -async function flushRemoteSaveNow() { - if (saveTimer) { - clearTimeout(saveTimer); - saveTimer = null; - } - if (!remoteMode) return; - try { - await saveWorkspace({ data: snapshotFromStore() }); - useWorkspace.setState({ syncStatus: "saved" }); - } catch { - useWorkspace.setState({ syncStatus: "error" }); - } -} -function useLocalOnlyMode() { - remoteMode = false; - bootstrapped = false; - unsub?.(); - unsub = null; - useWorkspace.setState({ - storageMode: "local", - syncStatus: "local", - hydrated: true - }); -} -function AppShell() { - const pages = useWorkspace((s) => s.pages); - const activePageId = useWorkspace((s) => s.activePageId); - const sidebarOpen = useWorkspace((s) => s.sidebarOpen); - const theme = useWorkspace((s) => s.theme); - const hydrated = useWorkspace((s) => s.hydrated); - const storageMode = useWorkspace((s) => s.storageMode); - const syncStatus = useWorkspace((s) => s.syncStatus); - const setSidebarOpen = useWorkspace((s) => s.setSidebarOpen); - const toggleSidebar = useWorkspace((s) => s.toggleSidebar); - const setActivePage = useWorkspace((s) => s.setActivePage); - const updatePage = useWorkspace((s) => s.updatePage); - const createPage = useWorkspace((s) => s.createPage); - const setHydrated = useWorkspace((s) => s.setHydrated); - const { user, isPending: authPending } = useCurrentUserState(); - const [searchOpen, setSearchOpen] = (0, import_react.useState)(false); - const [mobileSidebar, setMobileSidebar] = (0, import_react.useState)(false); - const [remoteLoading, setRemoteLoading] = (0, import_react.useState)(false); - (0, import_react.useEffect)(() => { - const unsub = useWorkspace.persist.onFinishHydration(() => { - if (!user) setHydrated(true); - }); - if (useWorkspace.persist.hasHydrated() && !user) setHydrated(true); - return unsub; - }, [setHydrated, user]); - (0, import_react.useEffect)(() => { - if (authPending) return; - let cancelled = false; - async function run() { - if (user) { - setRemoteLoading(true); - await bootstrapRemoteWorkspace(); - if (!cancelled) setRemoteLoading(false); - } else { - useLocalOnlyMode(); - if (useWorkspace.persist.hasHydrated()) setHydrated(true); - } - } - run(); - return () => { - cancelled = true; - }; - }, [ - user, - authPending, - setHydrated - ]); - (0, import_react.useEffect)(() => { - const onHide = () => { - if (storageMode === "database") flushRemoteSaveNow(); - }; - window.addEventListener("pagehide", onHide); - return () => window.removeEventListener("pagehide", onHide); - }, [storageMode]); - (0, import_react.useEffect)(() => { - const root = document.documentElement; - if (theme === "dark") root.classList.add("dark"); - else root.classList.remove("dark"); - }, [theme]); - const page = pages.find((p) => p.id === activePageId && !p.archived); - const breadcrumbs = (() => { - if (!page) return []; - const chain = []; - let cur = page; - const byId = new Map(pages.map((p) => [p.id, p])); - while (cur) { - chain.unshift(cur); - cur = cur.parentId ? byId.get(cur.parentId) : void 0; - } - return chain; - })(); - if (!hydrated || authPending || remoteLoading) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "flex h-dvh items-center justify-center bg-background text-muted-foreground", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex flex-col items-center gap-3", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "size-8 animate-pulse rounded-lg bg-muted" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "text-sm", - children: remoteLoading ? "Loading workspace from database…" : "Loading workspace…" - })] - }) - }); - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TooltipProvider, { - delayDuration: 300, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex h-dvh overflow-hidden bg-background text-foreground", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: cn("hidden h-full shrink-0 transition-[width,opacity] duration-200 md:block", sidebarOpen ? "w-[260px] opacity-100" : "w-0 opacity-0 overflow-hidden"), - children: sidebarOpen && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sidebar, { onOpenSearch: () => setSearchOpen(true) }) - }), - mobileSidebar && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "fixed inset-0 z-50 md:hidden", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "absolute inset-0 bg-black/40", - onClick: () => setMobileSidebar(false), - "aria-hidden": true - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "absolute inset-y-0 left-0 w-[min(280px,88vw)] shadow-xl", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sidebar, { - mobile: true, - onOpenSearch: () => { - setMobileSidebar(false); - setSearchOpen(true); - }, - onNavigate: () => setMobileSidebar(false) - }) - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex min-w-0 flex-1 flex-col", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("header", { - className: "flex h-11 shrink-0 items-center gap-1 border-b border-border px-2 sm:px-3", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - variant: "ghost", - size: "icon-sm", - className: "md:hidden", - onClick: () => setMobileSidebar(true), - "aria-label": "Open sidebar", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Menu, { className: "size-4" }) - }), - !sidebarOpen && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - variant: "ghost", - size: "icon-sm", - className: "hidden md:inline-flex", - onClick: toggleSidebar, - "aria-label": "Open sidebar", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PanelLeft, { className: "size-4" }) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("nav", { - className: "flex min-w-0 flex-1 items-center gap-0.5 overflow-hidden text-sm", - children: [breadcrumbs.map((crumb, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { - className: "flex min-w-0 items-center gap-0.5", - children: [i > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: "size-3.5 shrink-0 text-muted-foreground" }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("button", { - type: "button", - className: cn("max-w-[140px] truncate rounded px-1.5 py-0.5 transition-colors hover:bg-muted sm:max-w-[200px]", i === breadcrumbs.length - 1 ? "font-medium text-foreground" : "text-muted-foreground"), - onClick: () => setActivePage(crumb.id), - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "mr-1", - children: crumb.icon - }), crumb.title || "Untitled"] - })] - }, crumb.id)), !page && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { - className: "px-1.5 text-muted-foreground", - children: "No page selected" - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SyncChip, { - mode: storageMode, - status: syncStatus - }), - page && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - variant: "ghost", - size: "icon-sm", - onClick: () => updatePage(page.id, { favorite: !page.favorite }), - "aria-label": page.favorite ? "Unfavorite" : "Favorite", - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Star, { className: cn("size-4", page.favorite ? "fill-amber-400 text-amber-500" : "text-muted-foreground") }) - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "ml-1 hidden items-center gap-2 sm:flex", - children: user ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(UserButton, {}) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - size: "sm", - variant: "outline", - asChild: true, - children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, { - to: "/login", - children: "Sign in to sync" - }) - }) - }) - ] - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("main", { - className: "min-h-0 flex-1 overflow-y-auto", - children: page ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PageEditor, { page }, page.id) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EmptyWorkspace, { - onCreate: () => createPage(), - onOpenSidebar: () => { - setSidebarOpen(true); - setMobileSidebar(true); - } - }) - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CommandPalette, { - open: searchOpen, - onOpenChange: setSearchOpen - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Toaster, { - position: "bottom-right", - theme, - toastOptions: { className: "border border-border bg-background text-foreground" } - }) - ] - }) - }); -} -function SyncChip({ mode, status }) { - if (mode === "local") return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { - className: "hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground sm:inline-flex", - title: "Guest mode — data stays in this browser", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CloudOff, { className: "size-3" }), "Local only"] - }); - const label = status === "saving" || status === "pending" ? "Saving…" : status === "error" ? "Sync error" : "Saved to DB"; - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { - className: cn("hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] sm:inline-flex", status === "error" ? "text-destructive" : "text-muted-foreground"), - title: "Signed in — workspace syncs to Postgres", - children: [status === "saving" || status === "pending" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "size-3 animate-spin" }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Cloud, { className: "size-3" }), label] - }); -} -function EmptyWorkspace({ onCreate, onOpenSidebar }) { - return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex h-full flex-col items-center justify-center gap-4 px-6 text-center", - children: [ - /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { - className: "flex size-14 items-center justify-center rounded-2xl border border-border bg-muted text-2xl", - children: "📄" - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "space-y-1", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h1", { - className: "text-xl font-semibold tracking-tight", - children: "No pages yet" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { - className: "max-w-sm text-sm text-muted-foreground", - children: "Create a page to start writing, or restore one from trash." - })] - }), - /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { - className: "flex flex-wrap items-center justify-center gap-2", - children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - onClick: onCreate, - children: "New page" - }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { - type: "button", - variant: "outline", - onClick: onOpenSidebar, - children: "Open sidebar" - })] - }) - ] - }); -} -function Home() { - return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AppShell, {}); -} -//#endregion -export { Home as component }; diff --git a/.vercel/output/functions/__server.func/_ssr/search-server-B-Vicnmt.mjs b/.vercel/output/functions/__server.func/_ssr/search-server-B-Vicnmt.mjs new file mode 100644 index 0000000..07c7a50 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/search-server-B-Vicnmt.mjs @@ -0,0 +1,292 @@ +import { a as getServerFnById, i as TSS_SERVER_FUNCTION, r as createServerFn } from "./ssr.mjs"; +import { o as uid } from "./seed-CQXoc2iK.mjs"; +import { t as authMiddleware } from "./middleware-DoQ2eaJS.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/search-server-B-Vicnmt.js +var createSsrRpc = (functionId) => { + const url = "/_serverFn/" + functionId; + const serverFnMeta = { id: functionId }; + const fn = async (...args) => { + return (await getServerFnById(functionId, { origin: "server" }))(...args); + }; + return Object.assign(fn, { + url, + serverFnMeta, + [TSS_SERVER_FUNCTION]: true + }); +}; +/** Flatten page blocks to plain text (for search index). */ +function blocksToSearchText(page) { + const parts = [page.title || ""]; + for (const b of page.blocks) { + if (b.type === "divider" || b.type === "ai") continue; + if (b.content?.trim()) parts.push(b.content.trim()); + } + return parts.join("\n"); +} +/** Serialize a page to markdown body (no frontmatter). */ +function blocksToMarkdown(blocks) { + const lines = []; + let numbered = 0; + for (const b of blocks) { + const c = b.content ?? ""; + switch (b.type) { + case "heading1": + lines.push(`# ${c}`); + numbered = 0; + break; + case "heading2": + lines.push(`## ${c}`); + numbered = 0; + break; + case "heading3": + lines.push(`### ${c}`); + numbered = 0; + break; + case "bullet": + lines.push(`${" ".repeat(b.indent ?? 0)}- ${c}`); + numbered = 0; + break; + case "numbered": + numbered += 1; + lines.push(`${" ".repeat(b.indent ?? 0)}${numbered}. ${c}`); + break; + case "todo": + lines.push(`${" ".repeat(b.indent ?? 0)}- [${b.checked ? "x" : " "}] ${c}`); + numbered = 0; + break; + case "quote": + lines.push(c.split("\n").map((l) => `> ${l}`).join("\n")); + numbered = 0; + break; + case "callout": + lines.push(`> 💡 ${c}`); + numbered = 0; + break; + case "code": + lines.push("```"); + lines.push(c); + lines.push("```"); + numbered = 0; + break; + case "mermaid": + lines.push("```mermaid"); + lines.push(c); + lines.push("```"); + numbered = 0; + break; + case "divider": + lines.push("---"); + numbered = 0; + break; + case "toggle": + lines.push(`
${c || "Toggle"}`); + lines.push(""); + lines.push(`
`); + numbered = 0; + break; + case "ai": break; + default: + lines.push(c); + numbered = 0; + } + lines.push(""); + } + return lines.join("\n").replace(/\n{3,}/g, "\n\n").trim() + "\n"; +} +function pageToMarkdownFile(page) { + const title = page.title || "Untitled"; + const body = blocksToMarkdown(page.blocks); + if (body.startsWith(`# ${title}`)) return body; + return `# ${title}\n\n${body}`; +} +function makeBlock(type, content, extra) { + return { + id: uid("b"), + type, + content, + indent: 0, + ...extra + }; +} +/** Parse markdown into workspace blocks (best-effort). */ +function markdownToBlocks(md) { + const text = md.replace(/\r\n/g, "\n"); + const blocks = []; + const lines = text.split("\n"); + let i = 0; + while (i < lines.length) { + const line = lines[i]; + const fence = line.match(/^```(\w+)?\s*$/); + if (fence) { + const lang = fence[1] || ""; + const body = []; + i += 1; + while (i < lines.length && !lines[i].match(/^```\s*$/)) { + body.push(lines[i]); + i += 1; + } + i += 1; + if (lang === "mermaid") blocks.push(makeBlock("mermaid", body.join("\n"), { showSource: false })); + else blocks.push(makeBlock("code", body.join("\n"))); + continue; + } + if (/^---+\s*$/.test(line)) { + blocks.push(makeBlock("divider", "")); + i += 1; + continue; + } + const h = line.match(/^(#{1,3})\s+(.*)$/); + if (h) { + const level = h[1].length; + const type = level === 1 ? "heading1" : level === 2 ? "heading2" : "heading3"; + blocks.push(makeBlock(type, h[2] ?? "")); + i += 1; + continue; + } + const todo = line.match(/^(\s*)[-*+]\s+\[([ xX])\]\s+(.*)$/); + if (todo) { + const indent = Math.min(4, Math.floor((todo[1]?.length ?? 0) / 2)); + blocks.push(makeBlock("todo", todo[3] ?? "", { + checked: todo[2].toLowerCase() === "x", + indent + })); + i += 1; + continue; + } + const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/); + if (bullet) { + const indent = Math.min(4, Math.floor((bullet[1]?.length ?? 0) / 2)); + blocks.push(makeBlock("bullet", bullet[2] ?? "", { indent })); + i += 1; + continue; + } + const num = line.match(/^(\s*)\d+\.\s+(.*)$/); + if (num) { + const indent = Math.min(4, Math.floor((num[1]?.length ?? 0) / 2)); + blocks.push(makeBlock("numbered", num[2] ?? "", { indent })); + i += 1; + continue; + } + if (line.startsWith(">")) { + const quoteLines = []; + while (i < lines.length && lines[i].startsWith(">")) { + quoteLines.push(lines[i].replace(/^>\s?/, "")); + i += 1; + } + const joined = quoteLines.join("\n"); + if (joined.startsWith("💡") || joined.startsWith(":bulb:")) blocks.push(makeBlock("callout", joined.replace(/^💡\s*|^:bulb:\s*/, ""))); + else blocks.push(makeBlock("quote", joined)); + continue; + } + if (!line.trim()) { + i += 1; + continue; + } + const para = [line]; + i += 1; + while (i < lines.length) { + const n = lines[i]; + if (!n.trim() || n.startsWith("#") || n.startsWith(">") || n.startsWith("```") || /^[-*+]\s/.test(n) || /^\d+\.\s/.test(n) || /^---+\s*$/.test(n)) break; + para.push(n); + i += 1; + } + blocks.push(makeBlock("paragraph", para.join("\n"))); + } + if (blocks.length === 0) blocks.push(makeBlock("paragraph", "")); + return blocks; +} +function titleFromMarkdown(md, fallback) { + const m = md.match(/^#\s+(.+)$/m); + if (m?.[1]?.trim()) return m[1].trim().slice(0, 200); + return fallback.replace(/\.md$/i, "") || "Untitled"; +} +function slugifyFilename(title) { + return (title || "untitled").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "untitled"; +} +/** Client-side keyword-ish search when not signed in to Postgres. */ +function localSearchPages(pages, query, limit = 20) { + const q = query.trim().toLowerCase(); + if (!q) return []; + const terms = q.split(/\s+/).filter(Boolean); + const hits = []; + for (const page of pages) { + if (page.archived) continue; + const text = blocksToSearchText(page); + const hay = `${page.title}\n${text}`.toLowerCase(); + let score = 0; + if (page.title.toLowerCase().includes(q)) score += 2; + for (const t of terms) if (hay.includes(t)) score += 1; + const title = page.title.toLowerCase(); + let common = 0; + for (let i = 0; i < Math.min(title.length, q.length); i++) if (title[i] === q[i]) common += 1; + else break; + score += common * .1; + if (score <= 0) continue; + const flat = text.replace(/\s+/g, " ").trim(); + const idx = flat.toLowerCase().indexOf(q); + let snippet = flat.slice(0, 120) + (flat.length > 120 ? "…" : ""); + if (idx >= 0) { + const start = Math.max(0, idx - 40); + const end = Math.min(flat.length, idx + q.length + 80); + snippet = (start > 0 ? "…" : "") + flat.slice(start, end) + (end < flat.length ? "…" : ""); + } + hits.push({ + pageId: page.id, + title: page.title || "Untitled", + icon: page.icon, + parentId: page.parentId, + favorite: page.favorite, + snippet, + score, + mode: score >= 2 ? "keyword" : "similarity" + }); + } + return hits.sort((a, b) => b.score - a.score).slice(0, limit); +} +function pageToIndexRow(userId, page) { + const contentText = blocksToSearchText(page); + return { + userId, + pageId: page.id, + title: page.title || "Untitled", + icon: page.icon || "📄", + parentId: page.parentId, + favorite: Boolean(page.favorite), + archived: Boolean(page.archived), + contentText + }; +} +/** Rebuild the search index for a user from page list. */ +async function reindexUserPages(sql, userId, pages) { + await sql`delete from page_search where user_id = ${userId}`; + for (const page of pages) { + const row = pageToIndexRow(userId, page); + await sql` + insert into page_search ( + user_id, page_id, title, icon, parent_id, favorite, archived, + content_text, tsv, updated_at + ) values ( + ${row.userId}, + ${row.pageId}, + ${row.title}, + ${row.icon}, + ${row.parentId}, + ${row.favorite}, + ${row.archived}, + ${row.contentText}, + setweight(to_tsvector('english', coalesce(${row.title}, '')), 'A') || + setweight(to_tsvector('english', coalesce(${row.contentText}, '')), 'B'), + now() + ) + `; + } +} +var searchPages = createServerFn({ method: "POST" }).middleware([authMiddleware]).validator((input) => { + const d = input; + return { + query: typeof d?.query === "string" ? d.query.slice(0, 200).trim() : "", + limit: Math.min(40, Math.max(1, Number(d?.limit) || 20)) + }; +}).handler(createSsrRpc("a98064319e8852a83544a57d2b08358536b8e71b7accdbbc3c7a0bc01b34e11a")); +//#endregion +export { reindexUserPages as a, titleFromMarkdown as c, pageToMarkdownFile as i, localSearchPages as n, searchPages as o, markdownToBlocks as r, slugifyFilename as s, createSsrRpc as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/search-server-D9tG3kEu.mjs b/.vercel/output/functions/__server.func/_ssr/search-server-D9tG3kEu.mjs new file mode 100644 index 0000000..fc6c18d --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/search-server-D9tG3kEu.mjs @@ -0,0 +1,143 @@ +import { r as createServerFn } from "./ssr.mjs"; +import { t as createServerRpc } from "./createServerRpc-CcvdN_gc.mjs"; +import { r as getSql } from "./db-BLv9nwdP.mjs"; +import { t as authMiddleware } from "./middleware-DoQ2eaJS.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/search-server-D9tG3kEu.js +/** Rebuild the search index for a user from page list. */ +var trgmAvailable = null; +async function hasTrgm(sql) { + if (trgmAvailable != null) return trgmAvailable; + try { + await sql.query(`select similarity('a','a') as s`); + trgmAvailable = true; + } catch { + trgmAvailable = false; + } + return trgmAvailable; +} +var searchPages_createServerFn_handler = createServerRpc({ + id: "a98064319e8852a83544a57d2b08358536b8e71b7accdbbc3c7a0bc01b34e11a", + name: "searchPages", + filename: "src/lib/search-server.ts" +}, (opts) => searchPages.__executeServer(opts)); +var searchPages = createServerFn({ method: "POST" }).middleware([authMiddleware]).validator((input) => { + const d = input; + return { + query: typeof d?.query === "string" ? d.query.slice(0, 200).trim() : "", + limit: Math.min(40, Math.max(1, Number(d?.limit) || 20)) + }; +}).handler(searchPages_createServerFn_handler, async ({ context, data }) => { + const q = data.query; + if (!q) return { + hits: [], + trgm: false + }; + const sql = await getSql(); + const userId = context.userId; + const trgm = await hasTrgm(sql); + const keywordRows = await sql.query(` + select page_id, title, icon, parent_id, favorite, content_text, + ts_rank(tsv, plainto_tsquery('english', $2))::float8 as rank + from page_search + where user_id = $1 + and archived = false + and tsv @@ plainto_tsquery('english', $2) + order by rank desc + limit $3 + `, [ + userId, + q, + data.limit + ]); + let simRows = []; + if (trgm) try { + simRows = await sql.query(` + select page_id, title, icon, parent_id, favorite, content_text, + greatest( + similarity(title, $2), + similarity(left(content_text, 2000), $2) + )::float8 as rank + from page_search + where user_id = $1 + and archived = false + and ( + title % $2 + or content_text % $2 + or title ilike '%' || $2 || '%' + or content_text ilike '%' || $2 || '%' + ) + order by rank desc + limit $3 + `, [ + userId, + q, + data.limit + ]); + } catch { + simRows = []; + } + else simRows = await sql.query(` + select page_id, title, icon, parent_id, favorite, content_text, + case + when title ilike $2 then 0.9 + when title ilike $3 then 0.7 + when content_text ilike $3 then 0.5 + else 0.3 + end::float8 as rank + from page_search + where user_id = $1 + and archived = false + and (title ilike $3 or content_text ilike $3) + order by rank desc + limit $4 + `, [ + userId, + q, + `%${q}%`, + data.limit + ]); + const map = /* @__PURE__ */ new Map(); + for (const r of keywordRows) map.set(r.page_id, { + pageId: r.page_id, + title: r.title, + icon: r.icon, + parentId: r.parent_id, + favorite: Boolean(r.favorite), + snippet: makeSnippet(r.content_text, q), + score: Number(r.rank) || 0, + mode: "keyword" + }); + for (const r of simRows) { + const existing = map.get(r.page_id); + const score = Number(r.rank) || 0; + if (!existing) map.set(r.page_id, { + pageId: r.page_id, + title: r.title, + icon: r.icon, + parentId: r.parent_id, + favorite: Boolean(r.favorite), + snippet: makeSnippet(r.content_text, q), + score, + mode: "similarity" + }); + else { + existing.score = existing.score + score; + existing.mode = "hybrid"; + } + } + return { + hits: [...map.values()].sort((a, b) => b.score - a.score).slice(0, data.limit), + trgm + }; +}); +function makeSnippet(text, q) { + const flat = text.replace(/\s+/g, " ").trim(); + if (!flat) return ""; + const idx = flat.toLowerCase().indexOf(q.toLowerCase()); + if (idx < 0) return flat.slice(0, 120) + (flat.length > 120 ? "…" : ""); + const start = Math.max(0, idx - 40); + const end = Math.min(flat.length, idx + q.length + 80); + return (start > 0 ? "…" : "") + flat.slice(start, end) + (end < flat.length ? "…" : ""); +} +//#endregion +export { searchPages_createServerFn_handler }; diff --git a/.vercel/output/functions/__server.func/_ssr/seed-D7faJ9JV.mjs b/.vercel/output/functions/__server.func/_ssr/seed-CQXoc2iK.mjs similarity index 76% rename from .vercel/output/functions/__server.func/_ssr/seed-D7faJ9JV.mjs rename to .vercel/output/functions/__server.func/_ssr/seed-CQXoc2iK.mjs index aafa8f9..8f14ff2 100644 --- a/.vercel/output/functions/__server.func/_ssr/seed-D7faJ9JV.mjs +++ b/.vercel/output/functions/__server.func/_ssr/seed-CQXoc2iK.mjs @@ -1,39 +1,12 @@ -import { r as createMiddleware } from "./ssr.mjs"; -import { n as uid } from "./utils-DkRSI2_g.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/seed-D7faJ9JV.js -/** -* Auth middleware for server functions — the standard way to get the caller's -* verified user id. When deployed the session cookie is same-origin and rides -* along automatically. In the live preview the client also forwards the bearer -* token (partitioned cookies) via the `.client` hook below — call sites do not -* thread it themselves. -* -* import { createServerFn } from "@tanstack/react-start"; -* import { getSql } from "@/lib/db"; -* import { authMiddleware } from "@/lib/auth/middleware"; -* -* export const listTodos = createServerFn({ method: "GET" }) -* .middleware([authMiddleware]) -* .handler(async ({ context }) => { -* const sql = await getSql(); -* return sql`select * from todos where user_id = ${context.userId}`; -* }); -* -* Signed out (auth on — the default, including live preview) -> throws -* `UnauthorizedError` (see `verify.server.ts`). Only when auth is explicitly -* disabled (`VITE_AUTH_ENABLED=false`) does it resolve the shared dev user and -* never throw. Use it on every server function that touches per-user data, and -* scope every query by `context.userId`. -*/ -var authMiddleware = createMiddleware({ type: "function" }).client(async ({ next }) => { - const { getBearerToken } = await import("./client-C9atugA7.mjs").then((n) => n.n); - return next({ sendContext: { bearerToken: getBearerToken() ?? void 0 } }); -}).server(async ({ next, context }) => { - const { assertSameSiteRequest } = await import("./isolation.server-CGNg1r0B.mjs"); - const { requireUserId } = await import("./verify.server-2LHiOIs-.mjs"); - assertSameSiteRequest(); - return next({ context: { userId: await requireUserId(context.bearerToken) } }); -}); +import { n as clsx } from "../_libs/class-variance-authority+clsx.mjs"; +import { t as twMerge } from "../_libs/tailwind-merge.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/seed-CQXoc2iK.js +function cn(...inputs) { + return twMerge(clsx(inputs)); +} +function uid(prefix = "id") { + return `${prefix}_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36).slice(-4)}`; +} function blocks(...items) { return items.map((item) => ({ id: uid("b"), @@ -73,7 +46,7 @@ function seedWorkspace() { favorite: true, blocks: blocks({ type: "paragraph", - content: "Welcome to your workspace — notes, AI assist, Mermaid diagrams, and optional database sync." + content: "Welcome to ForgeNotes — notes, AI assist, Mermaid diagrams, and optional database sync." }, { type: "heading1", content: "What you can do" @@ -341,4 +314,4 @@ var COVER_PRESETS = { } }; //#endregion -export { seedWorkspace as a, createEmptyPage as i, PAGE_ICONS as n, authMiddleware as r, COVER_PRESETS as t }; +export { seedWorkspace as a, createEmptyPage as i, PAGE_ICONS as n, uid as o, cn as r, COVER_PRESETS as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/server-B2xtU6TT.mjs b/.vercel/output/functions/__server.func/_ssr/server-A0BVD3fT.mjs similarity index 99% rename from .vercel/output/functions/__server.func/_ssr/server-B2xtU6TT.mjs rename to .vercel/output/functions/__server.func/_ssr/server-A0BVD3fT.mjs index 6e4f96e..07d6379 100644 --- a/.vercel/output/functions/__server.func/_ssr/server-B2xtU6TT.mjs +++ b/.vercel/output/functions/__server.func/_ssr/server-A0BVD3fT.mjs @@ -1,17 +1,17 @@ -import { $t as logger, A as email, At as withSpan, B as base64Url, Bt as runWithTransaction, C as toResponse, Ct as encode, D as any, F as record, Ft as safeJSONParse, Gt as createRandomStringGenerator, H as decodeJwt, Ht as initGetModelName, I as string, It as getAuthTables, Jt as betterFetch, Lt as getCurrentAdapter, M as number, Mt as ATTR_HOOK_TYPE, N as object, Nt as ATTR_OPERATION_ID, O as array, P as optional, Pt as import_src, Qt as createLogger, Rt as queueAfterTransactionHook, S as serializeSignedCookie, U as decodeProtectedHeader, Ut as initGetFieldName, Vt as getBetterAuthVersion, W as jwtVerify, Wt as generateId, Zt as normalizePathname, _ as runWithRequestState, a as createAuthorizationURL, an as isDevelopment, b as createRouter$1, c as createRateLimitKey, cn as APIError, d as deprecate, dn as BASE_ERROR_CODES, en as shouldPublishLog, f as createAuthEndpoint, g as hasRequestState, h as defineRequestState, i as refreshAccessToken, j as looseObject, jt as ATTR_CONTEXT, k as boolean, l as findInvalidTrustedProxies, ln as BetterAuthError, m as isAPIError, n as socialProviders, nn as env, o as applyDefaultAccessTokenExpiry, on as isProduction, p as createAuthMiddleware, r as validateAuthorizationCode, s as isLoopbackHost, sn as isTest, t as SocialProviderListEnum, u as getIp, un as kAPIErrorHeaderSymbol, v as getCurrentAuthContext, vt as JWTExpired, w as filterOutputFields, x as serializeCookie, y as runWithEndpointContext, zt as runWithAdapter } from "../_libs/@better-auth/core+[...].mjs"; +import { $t as string, A as jwtVerify, At as generateId, Bn as isDevelopment, Bt as array, C as toResponse, Ct as getCurrentAdapter, Dt as getBetterAuthVersion, E as base64Url, Et as runWithTransaction, Fn as shouldPublishLog, Gn as kAPIErrorHeaderSymbol, Hn as isTest, Jt as number, Kn as BASE_ERROR_CODES, Ln as env, Mn as normalizePathname, Nn as createLogger, O as decodeJwt, Ot as initGetModelName, Pn as logger, Qt as record, S as serializeSignedCookie, St as getAuthTables, Tt as runWithAdapter, Un as APIError, Vn as isProduction, Vt as boolean, Wn as BetterAuthError, Wt as email, Xt as optional, Yt as object, _ as runWithRequestState, _t as ATTR_CONTEXT, a as createAuthorizationURL, b as createRouter$1, bt as import_src, c as createRateLimitKey, d as deprecate, f as createAuthEndpoint, g as hasRequestState, gt as withSpan, h as defineRequestState, i as refreshAccessToken, it as JWTExpired, jt as createRandomStringGenerator, k as decodeProtectedHeader, kn as betterFetch, kt as initGetFieldName, l as findInvalidTrustedProxies, lt as encode, m as isAPIError, n as socialProviders, o as applyDefaultAccessTokenExpiry, p as createAuthMiddleware, qt as looseObject, r as validateAuthorizationCode, s as isLoopbackHost, t as SocialProviderListEnum, u as getIp, v as getCurrentAuthContext, vt as ATTR_HOOK_TYPE, w as filterOutputFields, wt as queueAfterTransactionHook, x as serializeCookie, xt as safeJSONParse, y as runWithEndpointContext, yt as ATTR_OPERATION_ID, zt as any } from "../_libs/@better-auth/core+[...].mjs"; import { a as getOrigin, c as isRequestLike, i as getHost, l as resolveBaseURL, n as PACKAGE_VERSION, o as getProtocol, r as getBaseURL, s as isDynamicBaseURLConfig, t as GENERIC_OAUTH_ERROR_CODES, u as wildcardMatch } from "./url-CBX8wGYU.mjs"; import { n as defu, t as createDefu } from "../_libs/defu.mjs"; +import { i as string$1, n as boolean$1 } from "../_libs/@langchain/mcp-adapters+[...].mjs"; import { a as PostgresIntrospector, c as sql, i as PostgresAdapter, n as getKyselyDatabaseType, o as PostgresQueryCompiler, s as CompiledQuery, t as createKyselyAdapter } from "../_libs/@better-auth/kysely-adapter+[...].mjs"; -import { n as getPglite, t as ensureDbReady } from "./db-BCrmCYup.mjs"; +import { n as getPglite, t as ensureDbReady } from "./db-BLv9nwdP.mjs"; import { n as hkdf, t as sha256 } from "../_libs/noble__hashes.mjs"; import { i as jwtDecrypt, n as EncryptJWT, r as SignJWT, t as calculateJwkThumbprint } from "../_libs/jose.mjs"; import { i as verifyPassword, n as binary, r as hashPassword, t as createHMAC } from "../_libs/better-auth__utils.mjs"; import { n as createHash, t as createTelemetry } from "../_libs/@better-auth/telemetry+[...].mjs"; import { a as utf8ToBytes, i as managedNonce, n as bytesToHex, r as hexToBytes, t as xchacha20poly1305 } from "../_libs/noble__ciphers.mjs"; -import { n as string$1, t as boolean$1 } from "../_libs/zod.mjs"; import { t as Pool } from "../_libs/pg.mjs"; import { randomBytes } from "node:crypto"; -//#region node_modules/.nitro/vite/services/ssr/assets/server-B2xtU6TT.js +//#region node_modules/.nitro/vite/services/ssr/assets/server-A0BVD3fT.js function tryDecode$1(str) { if (str.indexOf("%") === -1) return str; try { @@ -8382,7 +8382,7 @@ var tanstackStartCookies = () => { const setCookies = returned?.get("set-cookie"); if (!setCookies) return; const parsed = parseSetCookieHeader(setCookies); - const { setCookie } = await import("./ssr.mjs").then((n) => n.s).then((n) => n.t); + const { setCookie } = await import("./ssr.mjs").then((n) => n.t); parsed.forEach((value, key) => { if (!key) return; try { @@ -8595,6 +8595,7 @@ var auth = betterAuth({ enabled: true, maxAge: 300 } }, + emailAndPassword: { enabled: true }, advanced: { useSecureCookies: false, defaultCookieAttributes: { diff --git a/.vercel/output/functions/__server.func/_ssr/server-Bvhad4nz.mjs b/.vercel/output/functions/__server.func/_ssr/server-Bvhad4nz.mjs new file mode 100644 index 0000000..f65a450 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/server-Bvhad4nz.mjs @@ -0,0 +1,744 @@ +import { r as createServerFn } from "./ssr.mjs"; +import { t as createServerRpc } from "./createServerRpc-CcvdN_gc.mjs"; +import { t as load } from "../_libs/js-yaml.mjs"; +import { spawn } from "node:child_process"; +import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { constants } from "node:fs"; +import path from "node:path"; +//#region node_modules/.nitro/vite/services/ssr/assets/server-Bvhad4nz.js +function parseAgentYaml(text) { + const doc = load(text); + if (!doc || typeof doc !== "object") throw new Error("Invalid agent YAML"); + if (typeof doc.name !== "string" || !doc.name.trim()) throw new Error("Agent YAML requires `name`"); + if (typeof doc.prompt !== "string") throw new Error("Agent YAML requires `prompt`"); + const exec = doc.executor ?? {}; + if (typeof exec.harness !== "string") throw new Error("Agent YAML requires `executor.harness`"); + return { + name: doc.name.trim(), + description: typeof doc.description === "string" ? doc.description : void 0, + prompt: doc.prompt, + executor: { + harness: exec.harness, + model: typeof exec.model === "string" ? exec.model : void 0, + command: typeof exec.command === "string" ? exec.command : void 0, + args: Array.isArray(exec.args) ? exec.args.map(String) : void 0, + cwd: typeof exec.cwd === "string" ? exec.cwd : void 0, + timeoutMs: typeof exec.timeoutMs === "number" ? exec.timeoutMs : void 0, + auth: exec.auth + }, + tools: Array.isArray(doc.tools) ? doc.tools : void 0, + policies: doc.policies, + os_env: doc.os_env + }; +} +function parseWorkflowYaml(text) { + const doc = load(text); + if (!doc || typeof doc !== "object") throw new Error("Invalid workflow YAML"); + if (typeof doc.name !== "string") throw new Error("Workflow requires `name`"); + if (!Array.isArray(doc.phases)) throw new Error("Workflow requires `phases`"); + const artifacts = doc.artifacts ?? {}; + return { + name: doc.name, + description: typeof doc.description === "string" ? doc.description : void 0, + feature: typeof doc.feature === "string" ? doc.feature : void 0, + phases: doc.phases, + artifacts: { + planPath: artifacts.planPath || "harness/plans/{feature}-plan.md", + runDir: artifacts.runDir || "harness/artifacts/{runId}" + }, + policies: doc.policies + }; +} +async function commandExists(cmd) { + const bin = cmd.split(/\s+/)[0]; + if (bin.includes("/")) try { + await access(bin, constants.X_OK); + return true; + } catch { + return false; + } + return new Promise((resolve) => { + const child = spawn("which", [bin], { stdio: "ignore" }); + child.on("close", (code) => resolve(code === 0)); + child.on("error", () => resolve(false)); + }); +} +async function listBackends() { + const candidates = [ + { + id: "local-deepagents", + label: "Workspace Deep Agents (LangChain)", + kind: "builtin", + notes: "In-process via workspace AI settings / XAI_API_KEY" + }, + { + id: "local-direct", + label: "Workspace direct chat", + kind: "builtin", + notes: "Single-shot model call without agent loop" + }, + { + id: "mock", + label: "Mock (deterministic demo)", + kind: "mock", + notes: "No external deps — always available for dry-runs" + }, + { + id: "claude-cli", + label: "Claude Code CLI", + kind: "cli", + command: "claude", + check: "claude", + notes: "Anthropic Claude Code" + }, + { + id: "codex-cli", + label: "Codex CLI", + kind: "cli", + command: "codex", + check: "codex", + notes: "OpenAI Codex" + }, + { + id: "cursor-cli", + label: "Cursor agent CLI", + kind: "cli", + command: "cursor-agent", + check: "cursor-agent" + }, + { + id: "grok-build", + label: "Grok Build (ACP)", + kind: "acp", + command: "grok agent --always-approve stdio", + check: "grok", + notes: "Register as acp:grok-build in Omnigent; auth via grok login" + }, + { + id: "opencode", + label: "OpenCode", + kind: "cli", + command: "opencode", + check: "opencode" + }, + { + id: "hermes", + label: "Hermes", + kind: "cli", + command: "hermes", + check: "hermes" + }, + { + id: "pi", + label: "Pi", + kind: "cli", + command: "pi", + check: "pi" + }, + { + id: "shell", + label: "Generic shell command", + kind: "cli", + notes: "executor.command required in agent YAML" + }, + { + id: "acp", + label: "Generic ACP agent", + kind: "acp", + notes: "executor.command must speak Agent Client Protocol on stdio" + } + ]; + const out = []; + for (const c of candidates) { + let available = c.kind === "builtin" || c.kind === "mock"; + if (c.check) available = await commandExists(c.check); + if (c.id === "shell" || c.id === "acp") available = true; + out.push({ + id: c.id, + label: c.label, + kind: c.kind, + available, + command: c.command, + notes: c.notes + }); + } + return out; +} +function emit(onEvent, partial) { + onEvent?.(partial); +} +async function executeAgent(input) { + const harness = String(input.agent.executor.harness); + const fullPrompt = [ + input.agent.prompt.trim(), + input.context ? `\n\n## Context\n${input.context}` : "", + `\n\n## Task\n${input.userMessage}` + ].join(""); + emit(input.onEvent, { + phase: "execute", + roleId: input.agent.name, + level: "info", + message: `Running via backend \`${harness}\`` + }); + if (harness === "mock") { + const text = mockRespond(input.agent.name, input.userMessage); + emit(input.onEvent, { + phase: "execute", + roleId: input.agent.name, + level: "result", + message: text.slice(0, 200) + }); + return { + text, + backend: "mock", + ok: true + }; + } + if (harness === "local-deepagents" || harness === "local-direct") try { + const { runHarnessModel } = await import("./local-model-DJKwz5o1.mjs"); + const text = await runHarnessModel({ + system: input.agent.prompt, + user: `${input.context ? input.context + "\n\n" : ""}${input.userMessage}`, + model: input.agent.executor.model, + mode: harness === "local-direct" ? "direct" : "deepagents" + }); + emit(input.onEvent, { + phase: "execute", + roleId: input.agent.name, + level: "result", + message: text.slice(0, 240) + }); + return { + text, + backend: harness, + ok: true + }; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + emit(input.onEvent, { + phase: "execute", + roleId: input.agent.name, + level: "warn", + message: `Live model unavailable (${message}); using mock fallback` + }); + return { + text: mockRespond(input.agent.name, input.userMessage), + backend: "mock", + ok: true, + error: message + }; + } + if (harness === "shell" || harness === "acp" || harness === "claude-cli" || harness === "codex-cli" || harness === "cursor-cli" || harness === "grok-build" || harness === "opencode" || harness === "hermes" || harness === "pi" || harness.startsWith("acp:")) { + const cmd = resolveCliCommand(harness, input.agent); + if (!cmd) return { + text: "", + backend: harness, + ok: false, + error: `No command configured for harness ${harness}` + }; + try { + const text = await runShellAgent(cmd, fullPrompt, input.agent.executor.timeoutMs ?? 12e4); + emit(input.onEvent, { + phase: "execute", + roleId: input.agent.name, + level: "result", + message: text.slice(0, 240) + }); + return { + text, + backend: harness, + ok: true + }; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + emit(input.onEvent, { + phase: "execute", + roleId: input.agent.name, + level: "error", + message + }); + return { + text: `${mockRespond(input.agent.name, input.userMessage)}\n\n_Note: CLI backend \`${harness}\` failed: ${message}_`, + backend: harness, + ok: false, + error: message + }; + } + } + return { + text: "", + backend: harness, + ok: false, + error: `Unknown harness: ${harness}` + }; +} +function resolveCliCommand(harness, agent) { + if (agent.executor.command) { + const parts = agent.executor.command.split(/\s+/).filter(Boolean); + return { + bin: parts[0], + args: [...parts.slice(1), ...agent.executor.args ?? []] + }; + } + const map = { + "claude-cli": { + bin: "claude", + args: ["-p"] + }, + "codex-cli": { + bin: "codex", + args: ["exec"] + }, + "cursor-cli": { + bin: "cursor-agent", + args: [] + }, + "grok-build": { + bin: "grok", + args: [ + "agent", + "--always-approve", + "stdio" + ] + }, + opencode: { + bin: "opencode", + args: ["run"] + }, + hermes: { + bin: "hermes", + args: [] + }, + pi: { + bin: "pi", + args: [] + } + }; + if (harness.startsWith("acp:")) return map["grok-build"] ?? null; + return map[harness] ?? null; +} +function runShellAgent(cmd, prompt, timeoutMs) { + return new Promise((resolve, reject) => { + const child = spawn(cmd.bin, cmd.args, { + stdio: [ + "pipe", + "pipe", + "pipe" + ], + env: process.env + }); + let stdout = ""; + let stderr = ""; + const timer = setTimeout(() => { + child.kill("SIGTERM"); + reject(/* @__PURE__ */ new Error(`Timeout after ${timeoutMs}ms`)); + }, timeoutMs); + child.stdout.on("data", (d) => { + stdout += String(d); + }); + child.stderr.on("data", (d) => { + stderr += String(d); + }); + child.on("error", (err) => { + clearTimeout(timer); + reject(err); + }); + child.on("close", (code) => { + clearTimeout(timer); + if (code !== 0 && !stdout.trim()) { + reject(new Error(stderr.trim() || `Exit ${code}`)); + return; + } + resolve(stdout.trim() || stderr.trim()); + }); + child.stdin.write(prompt); + child.stdin.end(); + }); +} +function mockRespond(agentName, task) { + const short = task.slice(0, 160).replace(/\n/g, " "); + const name = agentName.toLowerCase(); + if (name.includes("review")) return [ + `# Review (read-only)`, + ``, + `## Blocking`, + `- None identified in mock mode`, + ``, + `## Non-blocking`, + `- Add edge-case tests for error paths`, + `- Document public API surface`, + ``, + `_Reviewer agent: ${agentName}_`, + `_Scope: ${short}_` + ].join("\n"); + if (name.includes("validat")) return [ + `# Validation`, + ``, + `- Tests: simulated green (mock backend)`, + `- Blocking review items: none or addressed`, + `- Remaining risks: mock run — re-run with a live CLI for real signal`, + ``, + `## Summary`, + `Feature task completed under meta-harness workflow.`, + ``, + `_Validator: ${agentName}_` + ].join("\n"); + if (name.includes("orchestr") || name.includes("plan") || /create a plan|decompos/i.test(task)) return [ + `# Plan`, + ``, + `## Package A — Core utilities`, + `- Acceptance: pure functions covered by unit tests`, + ``, + `## Package B — API / integration surface`, + `- Acceptance: endpoints return expected contracts`, + ``, + `## Package C — Tests & docs`, + `- Acceptance: suite green; README updated`, + ``, + `_Generated by mock harness for: ${short}_` + ].join("\n"); + if (name.includes("hello") || /\?/.test(task)) return [ + `A **meta-harness** is a thin compatibility layer above coding agents.`, + ``, + `You define workflow once (policies, plan → implement → review → validate, durable artifacts)`, + `and treat Claude Code, Codex, Grok Build, etc. as pluggable backends via \`executor.harness\`.`, + ``, + `The lock-in you avoid is not the model — it is the automation wired to one vendor CLI.`, + ``, + `_Mock agent: ${agentName}_` + ].join("\n"); + return [ + `# Implementation notes (${agentName})`, + ``, + `Scope: ${short}`, + ``, + `- Stayed within package boundary`, + `- Left local tests green (simulated)`, + `- Ready for independent review` + ].join("\n"); +} +function uid(prefix = "id") { + return `${prefix}_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36).slice(-4)}`; +} +var ROOT = process.cwd(); +var HARNESS_DIR = path.join(ROOT, "harness"); +function slug(s) { + return (s || "feature").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 48) || "feature"; +} +function resolveTemplate(tpl, vars) { + return tpl.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? ""); +} +async function listAgentFiles() { + const dir = path.join(HARNESS_DIR, "agents"); + try { + return (await readdir(dir)).filter((f) => f.endsWith(".yaml") || f.endsWith(".yml")).sort(); + } catch { + return []; + } +} +async function listWorkflowFiles() { + const dir = path.join(HARNESS_DIR, "workflows"); + try { + return (await readdir(dir)).filter((f) => f.endsWith(".yaml") || f.endsWith(".yml")).sort(); + } catch { + return []; + } +} +async function loadAgentFile(relOrName) { + const candidates = [ + path.resolve(ROOT, relOrName), + path.join(HARNESS_DIR, "agents", relOrName), + path.join(HARNESS_DIR, "agents", `${relOrName}.yaml`), + path.join(HARNESS_DIR, "agents", `${relOrName}.yml`) + ]; + for (const p of candidates) try { + return parseAgentYaml(await readFile(p, "utf8")); + } catch {} + throw new Error(`Agent not found: ${relOrName}`); +} +async function loadWorkflowFile(relOrName) { + const candidates = [ + path.resolve(ROOT, relOrName), + path.join(HARNESS_DIR, "workflows", relOrName), + path.join(HARNESS_DIR, "workflows", `${relOrName}.yaml`) + ]; + for (const p of candidates) try { + return parseWorkflowYaml(await readFile(p, "utf8")); + } catch {} + throw new Error(`Workflow not found: ${relOrName}`); +} +async function runAgentFile(opts) { + const started = Date.now(); + const runId = uid("run"); + const events = []; + const agent = await loadAgentFile(opts.agentPath); + if (opts.backendOverride) agent.executor.harness = opts.backendOverride; + const result = await executeAgent({ + agent, + userMessage: opts.message, + onEvent: (e) => events.push({ + ...e, + ts: Date.now() + }) + }); + const runDir = path.join(HARNESS_DIR, "artifacts", runId); + await mkdir(runDir, { recursive: true }); + await writeFile(path.join(runDir, "output.md"), result.text, "utf8"); + await writeFile(path.join(runDir, "meta.json"), JSON.stringify({ + agent: agent.name, + backend: result.backend, + ok: result.ok + }, null, 2), "utf8"); + return { + ok: result.ok, + runId, + agent: agent.name, + backend: result.backend, + events, + outputs: { output: result.text }, + summary: result.ok ? `Agent \`${agent.name}\` finished via \`${result.backend}\`` : `Agent failed: ${result.error}`, + durationMs: Date.now() - started + }; +} +async function runWorkflow(opts) { + const started = Date.now(); + const runId = uid("run"); + const feature = opts.feature.trim() || "feature"; + const featureSlug = slug(feature); + const events = []; + const outputs = {}; + const wf = await loadWorkflowFile(opts.workflowPath); + const vars = { + feature: featureSlug, + runId, + FEATURE: feature + }; + const planPath = path.resolve(ROOT, resolveTemplate(wf.artifacts.planPath, vars)); + const runDir = path.resolve(ROOT, resolveTemplate(wf.artifacts.runDir, vars)); + await mkdir(runDir, { recursive: true }); + await mkdir(path.dirname(planPath), { recursive: true }); + const push = (e) => { + events.push({ + ...e, + ts: Date.now() + }); + }; + push({ + phase: "start", + roleId: "orchestrator", + level: "info", + message: `Workflow \`${wf.name}\` · feature: ${feature}` + }); + let planText = ""; + let lastBackend = "mock"; + for (const phase of wf.phases) { + push({ + phase: String(phase.id), + roleId: "orchestrator", + level: "info", + message: `Phase: ${phase.title}${phase.parallel ? " (parallel)" : ""}` + }); + const roles = phase.roles; + const runRole = async (role) => { + let agent; + try { + agent = await loadAgentFile(role.agent); + } catch { + agent = { + name: role.id, + prompt: defaultPromptForRole(role.role, role.readOnly), + executor: { harness: opts.backendOverride || "mock" } + }; + } + if (opts.backendOverride) agent.executor.harness = opts.backendOverride; + if (wf.policies?.crossVendorReview && role.role === "reviewer" && !opts.backendOverride) agent.executor.harness = pickReviewBackend(String(agent.executor.harness)); + const userMessage = buildRoleMessage({ + role, + feature, + phase: phase.id, + planPath + }); + const res = await executeAgent({ + agent, + userMessage, + context: planText ? `## Existing plan\n${planText}` : void 0, + onEvent: (e) => push({ + ...e, + phase: String(phase.id), + roleId: role.id + }) + }); + lastBackend = res.backend; + outputs[role.id] = res.text; + await writeFile(path.join(runDir, `${phase.id}-${role.id}.md`), res.text, "utf8"); + if (role.role === "orchestrator" || phase.id === "plan" || role.id.includes("plan")) { + planText = res.text; + await writeFile(planPath, res.text, "utf8"); + push({ + phase: String(phase.id), + roleId: role.id, + level: "info", + message: `Wrote plan → ${path.relative(ROOT, planPath)}` + }); + } + return res; + }; + if (phase.parallel) await Promise.all(roles.map((r) => runRole(r))); + else for (const r of roles) await runRole(r); + } + const summary = [ + `# Harness run ${runId}`, + ``, + `- Workflow: ${wf.name}`, + `- Feature: ${feature}`, + `- Plan: ${path.relative(ROOT, planPath)}`, + `- Backend (last): ${lastBackend}`, + `- Duration: ${Date.now() - started}ms`, + ``, + `## Artifacts`, + ...Object.keys(outputs).map((k) => `- ${k}`), + ``, + `## Events`, + ...events.map((e) => `- [${e.level}] ${e.phase}/${e.roleId}: ${e.message.replace(/\n/g, " ").slice(0, 160)}`) + ].join("\n"); + await writeFile(path.join(runDir, "SUMMARY.md"), summary, "utf8"); + await writeFile(path.join(runDir, "events.json"), JSON.stringify(events, null, 2), "utf8"); + return { + ok: true, + runId, + workflow: wf.name, + backend: lastBackend, + feature, + planPath: path.relative(ROOT, planPath), + events, + outputs, + summary, + durationMs: Date.now() - started + }; +} +function defaultPromptForRole(role, readOnly) { + if (role === "reviewer" || readOnly) return "You are an independent reviewer. Judge only against the acceptance contract. Do not edit code. Report blocking vs non-blocking issues."; + if (role === "orchestrator") return "You are the orchestrator. Decompose work into independent packages with clear acceptance criteria. Never write product code yourself."; + if (role === "validator") return "You validate that blocking review items are addressed and tests are green. Produce a final summary of changes and remaining risks."; + return "You are an implementer. Stay within your package scope. Leave tests green for your scope."; +} +function buildRoleMessage(opts) { + if (opts.role.role === "orchestrator" || opts.phase === "plan") return [ + `Create a plan for: ${opts.feature}`, + `Break into 3 independent packages with clear acceptance criteria.`, + `Write the plan as markdown (this will be saved to ${opts.planPath}).` + ].join("\n"); + if (opts.role.role === "implementer") return [ + `Implement package for feature: ${opts.feature}`, + opts.role.package ? `Package focus: ${opts.role.package}` : `Role id: ${opts.role.id}`, + `Stay in scope. Leave tests green for this package.`, + `Summarize files you would change and tests you would add.` + ].join("\n"); + if (opts.role.role === "reviewer" || opts.role.readOnly) return [ + `Review the implementation plan/output for: ${opts.feature}`, + `Focus: ${opts.role.package || opts.role.id}`, + `Read-only: do not edit code.`, + `Report blocking vs non-blocking issues.` + ].join("\n"); + if (opts.role.role === "validator") return [ + `Validate feature: ${opts.feature}`, + `Synthesize reviews, apply only blocking fixes (describe them),`, + `run the full test suite (or describe commands), and produce a final summary.` + ].join("\n"); + return `Work on feature: ${opts.feature} (${opts.role.id})`; +} +function pickReviewBackend(implHarness) { + return [ + "mock", + "local-direct", + "local-deepagents" + ].find((h) => h !== implHarness) || "mock"; +} +async function getHarnessStatus() { + return { + backends: await listBackends(), + agents: await listAgentFiles(), + workflows: await listWorkflowFiles(), + harnessDir: "harness/" + }; +} +/** Flatten to plain JSON-safe DTO for TanStack server fns */ +function toDto(r) { + return { + ok: Boolean(r.ok), + runId: String(r.runId), + workflow: r.workflow ? String(r.workflow) : void 0, + agent: r.agent ? String(r.agent) : void 0, + backend: String(r.backend), + feature: r.feature ? String(r.feature) : void 0, + planPath: r.planPath ? String(r.planPath) : void 0, + events: (r.events || []).map((e) => ({ + ts: Number(e.ts) || 0, + phase: String(e.phase), + roleId: String(e.roleId), + level: e.level, + message: String(e.message).slice(0, 500) + })), + outputs: Object.fromEntries(Object.entries(r.outputs || {}).map(([k, v]) => [k, String(v).slice(0, 8e3)])), + summary: String(r.summary || "").slice(0, 2e4), + durationMs: Number(r.durationMs) || 0 + }; +} +var harnessStatus_createServerFn_handler = createServerRpc({ + id: "19e00543f0313fe7905c045b33772265c61fa51d18574d69244c3f084698fddb", + name: "harnessStatus", + filename: "src/lib/harness/server.ts" +}, (opts) => harnessStatus.__executeServer(opts)); +var harnessStatus = createServerFn({ method: "GET" }).handler(harnessStatus_createServerFn_handler, async () => { + return getHarnessStatus(); +}); +var harnessListBackends_createServerFn_handler = createServerRpc({ + id: "9869410eeb67daab81f5d2ed574198eae379b3efb7eb41fe5a887f5ee51051d9", + name: "harnessListBackends", + filename: "src/lib/harness/server.ts" +}, (opts) => harnessListBackends.__executeServer(opts)); +var harnessListBackends = createServerFn({ method: "GET" }).handler(harnessListBackends_createServerFn_handler, async () => { + return listBackends(); +}); +var harnessRunAgent_createServerFn_handler = createServerRpc({ + id: "3a3b06354c92fa523d323b08f8cb2c04194a6d325c5629dfe4c092272682e98a", + name: "harnessRunAgent", + filename: "src/lib/harness/server.ts" +}, (opts) => harnessRunAgent.__executeServer(opts)); +var harnessRunAgent = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.agent) throw new Error("agent required"); + return { + agent: String(d.agent).slice(0, 120), + message: String(d.message || "Hello").slice(0, 8e3), + backend: d.backend ? String(d.backend).slice(0, 64) : "" + }; +}).handler(harnessRunAgent_createServerFn_handler, async ({ data }) => { + return toDto(await runAgentFile({ + agentPath: data.agent, + message: data.message, + backendOverride: data.backend || void 0 + })); +}); +var harnessRunWorkflow_createServerFn_handler = createServerRpc({ + id: "64ebef571e60681eaece2b296de9be5f6f33209c413aad1e4ff65d57e56c9c83", + name: "harnessRunWorkflow", + filename: "src/lib/harness/server.ts" +}, (opts) => harnessRunWorkflow.__executeServer(opts)); +var harnessRunWorkflow = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.workflow) throw new Error("workflow required"); + return { + workflow: String(d.workflow).slice(0, 120), + feature: String(d.feature || "feature").slice(0, 200), + backend: d.backend ? String(d.backend).slice(0, 64) : "" + }; +}).handler(harnessRunWorkflow_createServerFn_handler, async ({ data }) => { + return toDto(await runWorkflow({ + workflowPath: data.workflow, + feature: data.feature, + backendOverride: data.backend || void 0 + })); +}); +//#endregion +export { harnessListBackends_createServerFn_handler, harnessRunAgent_createServerFn_handler, harnessRunWorkflow_createServerFn_handler, harnessStatus_createServerFn_handler }; diff --git a/.vercel/output/functions/__server.func/_ssr/server-mounts-CskpCUay.mjs b/.vercel/output/functions/__server.func/_ssr/server-mounts-CskpCUay.mjs new file mode 100644 index 0000000..5c73e8a --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/server-mounts-CskpCUay.mjs @@ -0,0 +1,127 @@ +import { r as createServerFn } from "./ssr.mjs"; +import { t as createServerRpc } from "./createServerRpc-CcvdN_gc.mjs"; +import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +//#region node_modules/.nitro/vite/services/ssr/assets/server-mounts-CskpCUay.js +/** Only allow reading/writing under these roots (safety). */ +var ALLOWED_ROOTS = [ + path.resolve("/workspace/markdown-samples"), + path.resolve("/workspace/markdown-mounts"), + path.resolve("/workspace") +]; +function resolveSafe(userPath) { + const resolved = path.resolve(userPath); + if (!ALLOWED_ROOTS.some((root) => resolved === root || resolved.startsWith(root + path.sep))) throw new Error("Path not allowed. Use a folder under /workspace (e.g. /workspace/markdown-samples)."); + return resolved; +} +var listServerMount_createServerFn_handler = createServerRpc({ + id: "e157ab9abea20eda7cb1dfe0993f10e014c05e1948b91dad507e96d5387ed401", + name: "listServerMount", + filename: "src/lib/markdown/server-mounts.ts" +}, (opts) => listServerMount.__executeServer(opts)); +var listServerMount = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.root || typeof d.root !== "string") throw new Error("root required"); + return { + root: d.root.slice(0, 500), + relPath: typeof d.relPath === "string" ? d.relPath.slice(0, 500) : "" + }; +}).handler(listServerMount_createServerFn_handler, async ({ data }) => { + const root = resolveSafe(data.root); + const resolvedDir = resolveSafe(data.relPath ? path.join(root, data.relPath) : root); + if (!(await stat(resolvedDir)).isDirectory()) throw new Error("Not a directory"); + const names = await readdir(resolvedDir); + const entries = []; + for (const name of names) { + if (name.startsWith(".")) continue; + const s = await stat(path.join(resolvedDir, name)); + const relPath = data.relPath ? `${data.relPath}/${name}` : name; + if (s.isDirectory()) entries.push({ + name, + relPath, + kind: "dir" + }); + else if (name.toLowerCase().endsWith(".md")) entries.push({ + name, + relPath, + kind: "file" + }); + } + return entries.sort((a, b) => { + if (a.kind !== b.kind) return a.kind === "dir" ? -1 : 1; + return a.name.localeCompare(b.name); + }); +}); +var readServerMountFile_createServerFn_handler = createServerRpc({ + id: "c3a114c6a1c5b50dbdfd57a20fe11e1478b2807ee716176eb560a65a27d27cdc", + name: "readServerMountFile", + filename: "src/lib/markdown/server-mounts.ts" +}, (opts) => readServerMountFile.__executeServer(opts)); +var readServerMountFile = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.root || !d?.relPath) throw new Error("root and relPath required"); + return { + root: d.root.slice(0, 500), + relPath: d.relPath.slice(0, 500) + }; +}).handler(readServerMountFile_createServerFn_handler, async ({ data }) => { + const root = resolveSafe(data.root); + const full = resolveSafe(path.join(root, data.relPath)); + if (!full.toLowerCase().endsWith(".md")) throw new Error("Only .md files"); + return { + content: await readFile(full, "utf8"), + absPath: full + }; +}); +var writeServerMountFile_createServerFn_handler = createServerRpc({ + id: "0cc4b6b2ef3fcd2c2324866a03056ffdffdb4bfdfdb4862fc42fd41f6339f896", + name: "writeServerMountFile", + filename: "src/lib/markdown/server-mounts.ts" +}, (opts) => writeServerMountFile.__executeServer(opts)); +var writeServerMountFile = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.root || !d?.relPath || typeof d.content !== "string") throw new Error("root, relPath, content required"); + return { + root: d.root.slice(0, 500), + relPath: d.relPath.slice(0, 500), + content: d.content.slice(0, 2e6) + }; +}).handler(writeServerMountFile_createServerFn_handler, async ({ data }) => { + const root = resolveSafe(data.root); + const full = resolveSafe(path.join(root, data.relPath)); + if (!full.toLowerCase().endsWith(".md")) throw new Error("Only .md files"); + await mkdir(path.dirname(full), { recursive: true }); + await writeFile(full, data.content, "utf8"); + return { ok: true }; +}); +var exportPagesToServerDir_createServerFn_handler = createServerRpc({ + id: "b62660f341ad0ae3ab4593f5ba2b4559082a2961290a3f1c4443f4cff98a92c1", + name: "exportPagesToServerDir", + filename: "src/lib/markdown/server-mounts.ts" +}, (opts) => exportPagesToServerDir.__executeServer(opts)); +var exportPagesToServerDir = createServerFn({ method: "POST" }).validator((input) => { + const d = input; + if (!d?.targetDir || !Array.isArray(d.files)) throw new Error("Invalid export"); + return { + targetDir: d.targetDir.slice(0, 500), + files: d.files.slice(0, 500).map((f) => ({ + relPath: String(f.relPath).slice(0, 400), + content: String(f.content).slice(0, 2e6) + })) + }; +}).handler(exportPagesToServerDir_createServerFn_handler, async ({ data }) => { + const base = resolveSafe(data.targetDir); + await mkdir(base, { recursive: true }); + for (const f of data.files) { + const full = resolveSafe(path.join(base, f.relPath)); + await mkdir(path.dirname(full), { recursive: true }); + await writeFile(full, f.content, "utf8"); + } + return { + ok: true, + dir: base, + count: data.files.length + }; +}); +//#endregion +export { exportPagesToServerDir_createServerFn_handler, listServerMount_createServerFn_handler, readServerMountFile_createServerFn_handler, writeServerMountFile_createServerFn_handler }; diff --git a/.vercel/output/functions/__server.func/_ssr/settings-types-CI9vU3Ws.mjs b/.vercel/output/functions/__server.func/_ssr/settings-types-CI9vU3Ws.mjs new file mode 100644 index 0000000..ac78bd3 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/settings-types-CI9vU3Ws.mjs @@ -0,0 +1,159 @@ +import { t as WORKSPACE_SKILLS } from "./resolve-model-CV2sMs92.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/settings-types-CI9vU3Ws.js +var DEFAULT_MODELS = { + xai: [ + "grok-4.5", + "grok-4", + "grok-3", + "grok-3-mini", + "grok-2" + ], + anthropic: [ + "claude-sonnet-4-6", + "claude-opus-4-6", + "claude-haiku-4-5-20251001", + "claude-3-5-sonnet-latest" + ], + openai: [ + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4o", + "o4-mini", + "gpt-4o-mini" + ], + ollama: [ + "llama3.2", + "llama3.1", + "mistral", + "qwen2.5", + "gemma3", + "deepseek-r1" + ], + openai_compatible: [ + "gpt-4o", + "llama3.1", + "custom-model" + ] +}; +var BACKEND_META = { + deepagents: { + label: "LangChain Deep Agents", + description: "In-process agent with skills + MCP tools.", + needsApiKey: true, + isCli: false + }, + direct: { + label: "Direct model API", + description: "Single-shot chat via provider API (streamable).", + needsApiKey: true, + isCli: false + }, + "claude-cli": { + label: "Claude Code CLI", + description: "Shell out to `claude` with stream-json when available.", + needsApiKey: false, + isCli: true + }, + "codex-cli": { + label: "Codex CLI", + description: "Shell out to `codex exec` (streams stdout).", + needsApiKey: false, + isCli: true + }, + "grok-cli": { + label: "Grok CLI", + description: "Shell out to `grok chat --stream` / Grok Build.", + needsApiKey: false, + isCli: true + }, + local: { + label: "Local demo", + description: "No remote model — offline placeholders.", + needsApiKey: false, + isCli: false + } +}; +var PROVIDER_META = { + xai: { + label: "xAI · Grok", + description: "Grok models via the xAI API (OpenAI-compatible).", + keyLabel: "xAI API key", + keyPlaceholder: "xai-…", + needsKey: true + }, + anthropic: { + label: "Anthropic · Claude", + description: "Claude models (Sonnet, Opus, Haiku).", + keyLabel: "Anthropic API key", + keyPlaceholder: "sk-ant-…", + needsKey: true + }, + openai: { + label: "OpenAI", + description: "GPT and o-series models from OpenAI.", + keyLabel: "OpenAI API key", + keyPlaceholder: "sk-…", + needsKey: true + }, + ollama: { + label: "Ollama (local)", + description: "Run open models on your machine or LAN.", + keyLabel: "API key (optional)", + keyPlaceholder: "Usually blank", + needsKey: false, + baseUrlDefault: "http://127.0.0.1:11434", + baseUrlHint: "Ollama OpenAI-compatible base (no /v1 suffix needed)." + }, + openai_compatible: { + label: "OpenAI-compatible", + description: "Any OpenAI-style endpoint (Groq, Together, Azure proxy, etc.).", + keyLabel: "API key", + keyPlaceholder: "Optional / required by host", + needsKey: false, + baseUrlDefault: "https://api.example.com/v1", + baseUrlHint: "Must include /v1 if the host expects it." + } +}; +function defaultUserAiSettings() { + return { + setupComplete: false, + enabled: true, + backend: "deepagents", + provider: "xai", + model: DEFAULT_MODELS.xai[0], + apiKey: "", + baseUrl: "", + temperature: .35, + recursionLimit: 40, + mcpServers: [], + enabledSkills: [...WORKSPACE_SKILLS], + preferStreaming: true + }; +} +function publicAiSettings(s) { + return { + setupComplete: s.setupComplete, + enabled: s.enabled, + backend: s.backend, + provider: s.provider, + model: s.model, + hasApiKey: Boolean(s.apiKey?.trim()), + baseUrl: s.baseUrl, + temperature: s.temperature, + recursionLimit: s.recursionLimit, + preferStreaming: s.preferStreaming !== false, + mcpCount: s.mcpServers.filter((m) => m.enabled).length, + mcpServers: s.mcpServers.map((m) => ({ + id: m.id, + name: m.name, + enabled: m.enabled, + transport: m.transport, + url: m.url, + hasAuth: Boolean(m.authToken?.trim()), + command: m.command + })), + enabledSkills: s.enabledSkills + }; +} +//#endregion +export { publicAiSettings as a, defaultUserAiSettings as i, DEFAULT_MODELS as n, PROVIDER_META as r, BACKEND_META as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/ssr.mjs b/.vercel/output/functions/__server.func/_ssr/ssr.mjs index b639471..765a603 100644 --- a/.vercel/output/functions/__server.func/_ssr/ssr.mjs +++ b/.vercel/output/functions/__server.func/_ssr/ssr.mjs @@ -1,4 +1,5 @@ -import { r as __exportAll$1 } from "../_runtime.mjs"; +import "../_runtime.mjs"; +import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs"; import { u as require_react } from "../_libs/@floating-ui/react-dom+[...].mjs"; import { A as isNotFound, C as resolveManifestAssetLink, D as isResolvedRedirect, E as isRedirect, M as invariant, O as parseRedirect, S as getStylesheetHref, T as executeRewriteInput, a as replaceSsrResponse, i as normalizeSsrResponse, k as rootRouteId, l as RouterProvider, n as defineHandlerCallback, o as stripSsrResponseBody, r as isSsrResponse, t as renderRouterToStream, w as resolveManifestCssLink, x as getScriptPreloadAttrs } from "../_libs/@tanstack/react-router+[...].mjs"; import { n as createMemoryHistory } from "../_libs/tanstack__history.mjs"; @@ -6,30 +7,8 @@ import { a as defaultSerovalPlugins, c as makeSerovalPlugin, d as lu, i as getOr import { c as require_jsx_runtime } from "../_libs/@radix-ui/react-collection+[...].mjs"; import { n as setCookie, r as toResponse, t as H3Event } from "../_libs/h3-v2+rou3.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; -//#region node_modules/.nitro/vite/services/ssr/index.js -var ssr_exports = /* @__PURE__ */ __exportAll$1({ - a: () => getServerFnById, - createServerEntry: () => createServerEntry, - default: () => server_default, - i: () => TSS_SERVER_FUNCTION, - n: () => createMiddleware, - o: () => getRequest, - r: () => createServerFn, - s: () => __exportAll, - t: () => server_exports -}); require_react(); var import_jsx_runtime = require_jsx_runtime(); -var __defProp = Object.defineProperty; -var __exportAll = (all, no_symbols) => { - let target = {}; - for (var name in all) __defProp(target, name, { - get: all[name], - enumerable: true - }); - if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" }); - return target; -}; function StartServer(props) { return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RouterProvider, { router: props.router }); } @@ -118,7 +97,7 @@ var HEADERS = { TSS_SHELL: "X-TSS_SHELL" }; * the dev styles URL for route-scoped CSS collection. */ async function getStartManifest(matchedRoutes) { - const { tsrStartManifest } = await import("../_tanstack-start-manifest_v-DvlhOH0j.mjs"); + const { tsrStartManifest } = await import("../_tanstack-start-manifest_v-IfG0faZn.mjs"); const startManifest = tsrStartManifest(); let routes = startManifest.routes; routes[rootRouteId]; @@ -138,21 +117,73 @@ async function getStartManifest(matchedRoutes) { }; } var manifest = { + "0cc4b6b2ef3fcd2c2324866a03056ffdffdb4bfdfdb4862fc42fd41f6339f896": { + functionName: "writeServerMountFile_createServerFn_handler", + importer: () => import("./server-mounts-CskpCUay.mjs") + }, + "12c220cad66e7d4a3abab6da0b2bab6053a48aee4b6a0cde9d321705b501bd69": { + functionName: "describeAiSettings_createServerFn_handler", + importer: () => import("./ai-server-BfsU_lCo.mjs") + }, + "19e00543f0313fe7905c045b33772265c61fa51d18574d69244c3f084698fddb": { + functionName: "harnessStatus_createServerFn_handler", + importer: () => import("./server-Bvhad4nz.mjs") + }, + "1e62b13d94b613cf423e7774bb51046a7dfc3005d0164d46cbd5f39fd41e65ae": { + functionName: "testMcpConnection_createServerFn_handler", + importer: () => import("./ai-server-BfsU_lCo.mjs") + }, + "3a3b06354c92fa523d323b08f8cb2c04194a6d325c5629dfe4c092272682e98a": { + functionName: "harnessRunAgent_createServerFn_handler", + importer: () => import("./server-Bvhad4nz.mjs") + }, "5252add61246cf72a4fa382b4734734c4e8ea74302302ba378f1ecb54d53868d": { functionName: "getAiStatus_createServerFn_handler", - importer: () => import("./ai-server-BiqlgRjO.mjs") + importer: () => import("./ai-server-BfsU_lCo.mjs") + }, + "5e6a13ce7e871cac8b1efc1cf5ccb213d79a60710661cd7012f69f2c7ccb6982": { + functionName: "testAiConnection_createServerFn_handler", + importer: () => import("./ai-server-BfsU_lCo.mjs") + }, + "64ebef571e60681eaece2b296de9be5f6f33209c413aad1e4ff65d57e56c9c83": { + functionName: "harnessRunWorkflow_createServerFn_handler", + importer: () => import("./server-Bvhad4nz.mjs") }, "76d08ea8f0b0103fcaf7055c8b138a9579e4124d0d2f62a0686a1011273cd47a": { functionName: "runAi_createServerFn_handler", - importer: () => import("./ai-server-BiqlgRjO.mjs") + importer: () => import("./ai-server-BfsU_lCo.mjs") }, "7bd9976b9723bbefb2399d41723684e8ed7d3bfcf4f814066bb422e47b4bb658": { functionName: "saveWorkspace_createServerFn_handler", - importer: () => import("./workspace-server-D1_Qdv8y.mjs") + importer: () => import("./workspace-server-B5lvCDPy.mjs") + }, + "9869410eeb67daab81f5d2ed574198eae379b3efb7eb41fe5a887f5ee51051d9": { + functionName: "harnessListBackends_createServerFn_handler", + importer: () => import("./server-Bvhad4nz.mjs") + }, + "9bf431d4df4d57d04f011720753080a98c88face5f4f24058da2b17f8da151b8": { + functionName: "listAiCliBackends_createServerFn_handler", + importer: () => import("./ai-server-BfsU_lCo.mjs") + }, + "a98064319e8852a83544a57d2b08358536b8e71b7accdbbc3c7a0bc01b34e11a": { + functionName: "searchPages_createServerFn_handler", + importer: () => import("./search-server-D9tG3kEu.mjs") + }, + "b62660f341ad0ae3ab4593f5ba2b4559082a2961290a3f1c4443f4cff98a92c1": { + functionName: "exportPagesToServerDir_createServerFn_handler", + importer: () => import("./server-mounts-CskpCUay.mjs") + }, + "c3a114c6a1c5b50dbdfd57a20fe11e1478b2807ee716176eb560a65a27d27cdc": { + functionName: "readServerMountFile_createServerFn_handler", + importer: () => import("./server-mounts-CskpCUay.mjs") + }, + "e157ab9abea20eda7cb1dfe0993f10e014c05e1948b91dad507e96d5387ed401": { + functionName: "listServerMount_createServerFn_handler", + importer: () => import("./server-mounts-CskpCUay.mjs") }, "e3fb77d67dfdadad5d019581d79338a7f7cf2e42797c44110574e289b39fd293": { functionName: "loadWorkspace_createServerFn_handler", - importer: () => import("./workspace-server-D1_Qdv8y.mjs") + importer: () => import("./workspace-server-B5lvCDPy.mjs") } }; async function getServerFnById(id, access) { @@ -1422,7 +1453,7 @@ var getBaseManifest = getProdBaseManifest; var createEarlyHintsForRequest = createEarlyHintsCollector; async function loadEntries() { const [routerEntry, startEntry, pluginAdapters] = await Promise.all([ - import("./router-Yvf9JIm-.mjs"), + import("./router-DFPfY5Jx.mjs"), import("./start-5Z2QO8AU.mjs"), import("./empty-plugin-adapters-D9UWiqvJ.mjs") ]); @@ -1808,4 +1839,4 @@ function createServerEntry(entry) { } var server_default = createServerEntry({ fetch }); //#endregion -export { getRequest as a, createServerFn as i, __exportAll as n, getServerFnById as o, createMiddleware as r, ssr_exports as s, TSS_SERVER_FUNCTION as t }; +export { getServerFnById as a, createServerEntry, server_default as default, TSS_SERVER_FUNCTION as i, createMiddleware as n, getRequest as o, createServerFn as r, server_exports as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/store-DoRtk2cu.mjs b/.vercel/output/functions/__server.func/_ssr/store-DoRtk2cu.mjs new file mode 100644 index 0000000..fd4bdc0 --- /dev/null +++ b/.vercel/output/functions/__server.func/_ssr/store-DoRtk2cu.mjs @@ -0,0 +1,241 @@ +import { a as seedWorkspace, i as createEmptyPage, o as uid } from "./seed-CQXoc2iK.mjs"; +import { n as create, t as persist } from "../_libs/zustand.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/store-DoRtk2cu.js +function touch(page) { + return { + ...page, + updatedAt: Date.now() + }; +} +function collectDescendants(pages, rootId) { + const ids = /* @__PURE__ */ new Set([rootId]); + let changed = true; + while (changed) { + changed = false; + for (const p of pages) if (p.parentId && ids.has(p.parentId) && !ids.has(p.id)) { + ids.add(p.id); + changed = true; + } + } + return ids; +} +function cloneBlocks(blocks) { + return blocks.map((b) => ({ + ...b, + id: uid("b") + })); +} +var seeded = seedWorkspace(); +var useWorkspace = create()(persist((set, get) => ({ + name: "ForgeNotes", + pages: seeded.pages, + activePageId: seeded.activePageId, + sidebarOpen: true, + theme: "light", + hydrated: false, + storageMode: "local", + syncStatus: "local", + setHydrated: (v) => set({ hydrated: v }), + setName: (name) => set({ name }), + setSidebarOpen: (open) => set({ sidebarOpen: open }), + toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })), + setTheme: (theme) => set({ theme }), + setActivePage: (id) => set({ activePageId: id }), + setStorageMode: (mode) => set({ storageMode: mode }), + setSyncStatus: (status) => set({ syncStatus: status }), + loadFromRemote: (data) => set({ + name: data.name, + pages: data.pages, + activePageId: data.activePageId, + sidebarOpen: data.sidebarOpen, + theme: data.theme, + storageMode: "database", + syncStatus: "saved", + hydrated: true + }), + getPage: (id) => get().pages.find((p) => p.id === id), + getChildren: (parentId) => get().pages.filter((p) => !p.archived && p.parentId === parentId).sort((a, b) => a.createdAt - b.createdAt), + createPage: (opts) => { + const page = createEmptyPage({ + parentId: opts?.parentId ?? null, + title: opts?.title ?? "", + icon: opts?.icon + }); + set((s) => ({ + pages: [...s.pages, page], + activePageId: page.id + })); + return page.id; + }, + updatePage: (id, patch) => set((s) => ({ pages: s.pages.map((p) => p.id === id ? touch({ + ...p, + ...patch + }) : p) })), + deletePage: (id) => { + const ids = collectDescendants(get().pages, id); + set((s) => { + const pages = s.pages.map((p) => ids.has(p.id) ? touch({ + ...p, + archived: true, + favorite: false + }) : p); + let activePageId = s.activePageId; + if (activePageId && ids.has(activePageId)) activePageId = pages.find((p) => !p.archived && !ids.has(p.id))?.id ?? null; + return { + pages, + activePageId + }; + }); + }, + restorePage: (id) => set((s) => ({ pages: s.pages.map((p) => p.id === id ? touch({ + ...p, + archived: false, + parentId: null + }) : p) })), + permanentlyDeletePage: (id) => { + const ids = collectDescendants(get().pages, id); + set((s) => { + const pages = s.pages.filter((p) => !ids.has(p.id)); + let activePageId = s.activePageId; + if (activePageId && ids.has(activePageId)) activePageId = pages.find((p) => !p.archived)?.id ?? null; + return { + pages, + activePageId + }; + }); + }, + duplicatePage: (id) => { + const src = get().pages.find((p) => p.id === id); + if (!src) return null; + const copy = createEmptyPage({ + title: src.title ? `${src.title} (copy)` : "Untitled (copy)", + icon: src.icon, + cover: src.cover, + parentId: src.parentId, + favorite: false, + blocks: cloneBlocks(src.blocks) + }); + set((s) => ({ + pages: [...s.pages, copy], + activePageId: copy.id + })); + return copy.id; + }, + movePage: (id, parentId) => { + if (id === parentId) return; + if (parentId) { + if (collectDescendants(get().pages, id).has(parentId)) return; + } + set((s) => ({ pages: s.pages.map((p) => p.id === id ? touch({ + ...p, + parentId + }) : p) })); + }, + setBlocks: (pageId, blocks) => set((s) => ({ pages: s.pages.map((p) => p.id === pageId ? touch({ + ...p, + blocks + }) : p) })), + updateBlock: (pageId, blockId, patch) => set((s) => ({ pages: s.pages.map((p) => { + if (p.id !== pageId) return p; + return touch({ + ...p, + blocks: p.blocks.map((b) => b.id === blockId ? { + ...b, + ...patch + } : b) + }); + }) })), + insertBlock: (pageId, afterId, type = "paragraph", content = "") => { + const block = { + id: uid("b"), + type, + content, + indent: 0 + }; + set((s) => ({ pages: s.pages.map((p) => { + if (p.id !== pageId) return p; + const blocks = [...p.blocks]; + if (!afterId) blocks.unshift(block); + else { + const idx = blocks.findIndex((b) => b.id === afterId); + if (idx >= 0) blocks.splice(idx + 1, 0, block); + else blocks.push(block); + } + return touch({ + ...p, + blocks + }); + }) })); + return block.id; + }, + deleteBlock: (pageId, blockId) => set((s) => ({ pages: s.pages.map((p) => { + if (p.id !== pageId) return p; + let blocks = p.blocks.filter((b) => b.id !== blockId); + if (blocks.length === 0) blocks = [{ + id: uid("b"), + type: "paragraph", + content: "", + indent: 0 + }]; + return touch({ + ...p, + blocks + }); + }) })), + changeBlockType: (pageId, blockId, type) => set((s) => ({ pages: s.pages.map((p) => { + if (p.id !== pageId) return p; + return touch({ + ...p, + blocks: p.blocks.map((b) => b.id === blockId ? { + ...b, + type, + checked: type === "todo" ? b.checked ?? false : void 0 + } : b) + }); + }) })), + moveBlock: (pageId, blockId, direction) => set((s) => ({ pages: s.pages.map((p) => { + if (p.id !== pageId) return p; + const blocks = [...p.blocks]; + const idx = blocks.findIndex((b) => b.id === blockId); + if (idx < 0) return p; + const swap = direction === "up" ? idx - 1 : idx + 1; + if (swap < 0 || swap >= blocks.length) return p; + const tmp = blocks[idx]; + blocks[idx] = blocks[swap]; + blocks[swap] = tmp; + return touch({ + ...p, + blocks + }); + }) })), + importPages: (pages, activateId) => set((s) => ({ + pages: [...s.pages, ...pages], + activePageId: activateId ?? pages[0]?.id ?? s.activePageId + })), + resetWorkspace: () => { + const next = seedWorkspace(); + set({ + name: "ForgeNotes", + pages: next.pages, + activePageId: next.activePageId, + sidebarOpen: true, + theme: "light", + storageMode: "local", + syncStatus: "local" + }); + } +}), { + name: "workspace-v1", + partialize: (s) => ({ + name: s.name, + pages: s.pages, + activePageId: s.activePageId, + sidebarOpen: s.sidebarOpen, + theme: s.theme + }), + onRehydrateStorage: () => (state) => { + state?.setHydrated(true); + } +})); +//#endregion +export { useWorkspace as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/url-CBX8wGYU.mjs b/.vercel/output/functions/__server.func/_ssr/url-CBX8wGYU.mjs index d5d9db4..b4088e6 100644 --- a/.vercel/output/functions/__server.func/_ssr/url-CBX8wGYU.mjs +++ b/.vercel/output/functions/__server.func/_ssr/url-CBX8wGYU.mjs @@ -1,4 +1,4 @@ -import { fn as defineErrorCodes, ln as BetterAuthError, nn as env } from "../_libs/@better-auth/core+[...].mjs"; +import { Ln as env, Wn as BetterAuthError, qn as defineErrorCodes } from "../_libs/@better-auth/core+[...].mjs"; //#region node_modules/.nitro/vite/services/ssr/assets/url-CBX8wGYU.js var PACKAGE_VERSION = "1.6.25"; var GENERIC_OAUTH_ERROR_CODES = defineErrorCodes({ diff --git a/.vercel/output/functions/__server.func/_ssr/utils-DkRSI2_g.mjs b/.vercel/output/functions/__server.func/_ssr/utils-DkRSI2_g.mjs deleted file mode 100644 index 274c9d3..0000000 --- a/.vercel/output/functions/__server.func/_ssr/utils-DkRSI2_g.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import { n as clsx } from "../_libs/class-variance-authority+clsx.mjs"; -import { t as twMerge } from "../_libs/tailwind-merge.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/utils-DkRSI2_g.js -function cn(...inputs) { - return twMerge(clsx(inputs)); -} -function uid(prefix = "id") { - return `${prefix}_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36).slice(-4)}`; -} -//#endregion -export { uid as n, cn as t }; diff --git a/.vercel/output/functions/__server.func/_ssr/verify.server-2LHiOIs-.mjs b/.vercel/output/functions/__server.func/_ssr/verify.server-4Dqp9B_I.mjs similarity index 96% rename from .vercel/output/functions/__server.func/_ssr/verify.server-2LHiOIs-.mjs rename to .vercel/output/functions/__server.func/_ssr/verify.server-4Dqp9B_I.mjs index c2ebe84..f72b408 100644 --- a/.vercel/output/functions/__server.func/_ssr/verify.server-2LHiOIs-.mjs +++ b/.vercel/output/functions/__server.func/_ssr/verify.server-4Dqp9B_I.mjs @@ -1,6 +1,6 @@ -import { a as getRequest } from "./ssr.mjs"; -import { n as auth, r as authConfigured } from "./server-B2xtU6TT.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/verify.server-2LHiOIs-.js +import { o as getRequest } from "./ssr.mjs"; +import { n as auth, r as authConfigured } from "./server-A0BVD3fT.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/verify.server-4Dqp9B_I.js /** * Server-side session resolution (server-only). * diff --git a/.vercel/output/functions/__server.func/_ssr/workspace-server-D1_Qdv8y.mjs b/.vercel/output/functions/__server.func/_ssr/workspace-server-B5lvCDPy.mjs similarity index 92% rename from .vercel/output/functions/__server.func/_ssr/workspace-server-D1_Qdv8y.mjs rename to .vercel/output/functions/__server.func/_ssr/workspace-server-B5lvCDPy.mjs index e3b04c1..6e77d63 100644 --- a/.vercel/output/functions/__server.func/_ssr/workspace-server-D1_Qdv8y.mjs +++ b/.vercel/output/functions/__server.func/_ssr/workspace-server-B5lvCDPy.mjs @@ -1,8 +1,10 @@ -import { i as createServerFn } from "./ssr.mjs"; +import { r as createServerFn } from "./ssr.mjs"; import { t as createServerRpc } from "./createServerRpc-CcvdN_gc.mjs"; -import { r as getSql } from "./db-BCrmCYup.mjs"; -import { a as seedWorkspace, r as authMiddleware } from "./seed-D7faJ9JV.mjs"; -//#region node_modules/.nitro/vite/services/ssr/assets/workspace-server-D1_Qdv8y.js +import { r as getSql } from "./db-BLv9nwdP.mjs"; +import { a as seedWorkspace } from "./seed-CQXoc2iK.mjs"; +import { t as authMiddleware } from "./middleware-DoQ2eaJS.mjs"; +import { a as reindexUserPages } from "./search-server-B-Vicnmt.mjs"; +//#region node_modules/.nitro/vite/services/ssr/assets/workspace-server-B5lvCDPy.js function parseBlocks(raw) { if (Array.isArray(raw)) return raw; if (typeof raw === "string") try { @@ -59,7 +61,6 @@ function validateSnapshot(input) { })) }; } -/** Load the signed-in user's workspace. Seeds demo content on first visit. */ var loadWorkspace_createServerFn_handler = createServerRpc({ id: "e3fb77d67dfdadad5d019581d79338a7f7cf2e42797c44110574e289b39fd293", name: "loadWorkspace", @@ -156,6 +157,11 @@ async function writeSnapshot(sql, userId, snapshot) { ) `; } + try { + await reindexUserPages(sql, userId, snapshot.pages); + } catch (err) { + console.error("[search] reindex failed:", err); + } } //#endregion export { loadWorkspace_createServerFn_handler, saveWorkspace_createServerFn_handler }; diff --git a/.vercel/output/functions/__server.func/_tanstack-start-manifest_v-DvlhOH0j.mjs b/.vercel/output/functions/__server.func/_tanstack-start-manifest_v-DvlhOH0j.mjs deleted file mode 100644 index 91e43d9..0000000 --- a/.vercel/output/functions/__server.func/_tanstack-start-manifest_v-DvlhOH0j.mjs +++ /dev/null @@ -1,42 +0,0 @@ -//#region node_modules/.nitro/vite/services/ssr/assets/_tanstack-start-manifest_v-DvlhOH0j.js -var tsrStartManifest = () => ({ routes: { - __root__: { - filePath: "/workspace/src/routes/__root.tsx", - children: [ - "/", - "/login", - "/api/auth/$" - ], - preloads: [ - "/assets/index-DU4A6Ttf.js", - "/assets/rolldown-runtime-QTnfLwEv.js", - "/assets/react-Biaal4sZ.js", - "/assets/link-DYUXAN0T.js" - ], - scripts: [{ attrs: { - type: "module", - async: !0, - src: "/assets/index-DU4A6Ttf.js" - } }] - }, - "/": { - filePath: "/workspace/src/routes/index.tsx", - children: void 0, - preloads: [ - "/assets/routes-C6kpKjAV.js", - "/assets/client-8boibB1R.js", - "/assets/use-current-user-BkYwj4ZJ.js" - ] - }, - "/login": { - filePath: "/workspace/src/routes/login.tsx", - children: void 0, - preloads: [ - "/assets/login-C3NWOInE.js", - "/assets/client-8boibB1R.js", - "/assets/use-current-user-BkYwj4ZJ.js" - ] - } -} }); -//#endregion -export { tsrStartManifest }; diff --git a/.vercel/output/functions/__server.func/_tanstack-start-manifest_v-IfG0faZn.mjs b/.vercel/output/functions/__server.func/_tanstack-start-manifest_v-IfG0faZn.mjs new file mode 100644 index 0000000..d56bc4b --- /dev/null +++ b/.vercel/output/functions/__server.func/_tanstack-start-manifest_v-IfG0faZn.mjs @@ -0,0 +1,43 @@ +//#region node_modules/.nitro/vite/services/ssr/assets/_tanstack-start-manifest_v-IfG0faZn.js +var tsrStartManifest = () => ({ routes: { + __root__: { + filePath: "/Users/richardhightower/clients/spillwave/src/forge-notes/src/routes/__root.tsx", + children: [ + "/", + "/login", + "/api/ai/stream", + "/api/auth/$" + ], + preloads: [ + "/assets/index-CXgd9jpl.js", + "/assets/rolldown-runtime-aKtaBQYM.js", + "/assets/react-BLJmJXjR.js", + "/assets/utils-BTuSbA5p.js" + ], + scripts: [{ attrs: { + type: "module", + async: !0, + src: "/assets/index-CXgd9jpl.js" + } }] + }, + "/": { + filePath: "/Users/richardhightower/clients/spillwave/src/forge-notes/src/routes/index.tsx", + children: void 0, + preloads: [ + "/assets/routes-BDn33g5C.js", + "/assets/client-CwgDvMJw.js", + "/assets/input-mze7gZ5r.js" + ] + }, + "/login": { + filePath: "/Users/richardhightower/clients/spillwave/src/forge-notes/src/routes/login.tsx", + children: void 0, + preloads: [ + "/assets/login-xkhUej_P.js", + "/assets/client-CwgDvMJw.js", + "/assets/input-mze7gZ5r.js" + ] + } +} }); +//#endregion +export { tsrStartManifest }; diff --git a/.vercel/output/functions/__server.func/index.mjs b/.vercel/output/functions/__server.func/index.mjs index d2775c5..cb0a2ce 100644 --- a/.vercel/output/functions/__server.func/index.mjs +++ b/.vercel/output/functions/__server.func/index.mjs @@ -9,7 +9,7 @@ function lazyService(loader) { return promise.then((mod) => mod.fetch(req)); } }; } -var services = { ["ssr"]: lazyService(() => import("./_ssr/ssr.mjs").then((n) => n.s)) }; +var services = { ["ssr"]: lazyService(() => import("./_ssr/ssr.mjs")) }; globalThis.__nitro_vite_envs__ = services; //#endregion //#region node_modules/nitro/dist/runtime/internal/route-rules.mjs @@ -38,11 +38,11 @@ var findRouteRules = /* @__PURE__ */ (() => { return r; }; })(); -var _lazy_IO091Z = defineLazyEventHandler(() => import("./_chunks/ssr-renderer.mjs")); +var _lazy_CQqvAI = defineLazyEventHandler(() => import("./_chunks/ssr-renderer.mjs")); var findRoute = /* @__PURE__ */ (() => { const data = { route: "/**", - handler: _lazy_IO091Z + handler: _lazy_CQqvAI }; return ((_m, p) => { return { diff --git a/.vercel/output/nitro.json b/.vercel/output/nitro.json index 947983f..eef5867 100644 --- a/.vercel/output/nitro.json +++ b/.vercel/output/nitro.json @@ -1,5 +1,5 @@ { - "date": "2026-07-31T15:31:36.156Z", + "date": "2026-08-03T14:06:10.520Z", "preset": "vercel", "framework": { "name": "nitro", diff --git a/.vercel/output/static/assets/abnfDiagram-VRR7QNED-CXuHdQsQ.js b/.vercel/output/static/assets/abnfDiagram-VRR7QNED-DLdRCqX4.js similarity index 83% rename from .vercel/output/static/assets/abnfDiagram-VRR7QNED-CXuHdQsQ.js rename to .vercel/output/static/assets/abnfDiagram-VRR7QNED-DLdRCqX4.js index 6925439..3198c78 100644 --- a/.vercel/output/static/assets/abnfDiagram-VRR7QNED-CXuHdQsQ.js +++ b/.vercel/output/static/assets/abnfDiagram-VRR7QNED-DLdRCqX4.js @@ -1 +1 @@ -import{n as e}from"./chunk-5HE753X5-o8-OCfIL.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-_wZywoZs.js";import"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-VAUOI2AC-CLN1Ga8_.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-DR1aBwdH.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-AdnthA1k.js";var c=e().RailroadAbnf.parser.LangiumParser,l=t(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformAlternation`),u=t(e=>{let t=e.elements.map(f);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformConcatenation`),d=t(e=>{if(e.includes(`*`)){let[t,n]=e.split(`*`);return{min:t?parseInt(t,10):0,max:n?parseInt(n,10):1/0}}let t=parseInt(e,10);return{min:t,max:t}},`parseRepeat`),f=t(e=>{let t=p(e.primary);if(!e.repeat)return t;let{min:n,max:r}=d(e.repeat);return n===0&&r===1?{type:`optional`,element:t}:{type:`repetition`,element:t,min:n,max:r}},`transformElement`),p=t(e=>{switch(e.$type){case`AbnfStringLiteral`:return{type:`terminal`,value:e.value};case`AbnfNumVal`:return{type:`terminal`,value:e.value};case`AbnfRuleName`:return{type:`nonterminal`,name:e.name};case`AbnfGroup`:return l(e.element);case`AbnfOptionalGroup`:return{type:`optional`,element:l(e.element)};default:throw Error(`Unsupported ABNF primary node: ${e.$type}`)}},`transformPrimary`),m=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),h=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(m(e)))},`populateDb`),g={parser:{parse:t(e=>{a.clear(),n.debug(`[ABNF Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[ABNF Parser] Parsed rules:`,r.rules.length),h(r),n.debug(`[ABNF Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{g as diagram}; \ No newline at end of file +import{n as e}from"./chunk-5HE753X5-o8-OCfIL.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-Bju_yCKi.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-Z7xZAZRH.js";var c=e().RailroadAbnf.parser.LangiumParser,l=t(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformAlternation`),u=t(e=>{let t=e.elements.map(f);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformConcatenation`),d=t(e=>{if(e.includes(`*`)){let[t,n]=e.split(`*`);return{min:t?parseInt(t,10):0,max:n?parseInt(n,10):1/0}}let t=parseInt(e,10);return{min:t,max:t}},`parseRepeat`),f=t(e=>{let t=p(e.primary);if(!e.repeat)return t;let{min:n,max:r}=d(e.repeat);return n===0&&r===1?{type:`optional`,element:t}:{type:`repetition`,element:t,min:n,max:r}},`transformElement`),p=t(e=>{switch(e.$type){case`AbnfStringLiteral`:return{type:`terminal`,value:e.value};case`AbnfNumVal`:return{type:`terminal`,value:e.value};case`AbnfRuleName`:return{type:`nonterminal`,name:e.name};case`AbnfGroup`:return l(e.element);case`AbnfOptionalGroup`:return{type:`optional`,element:l(e.element)};default:throw Error(`Unsupported ABNF primary node: ${e.$type}`)}},`transformPrimary`),m=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),h=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(m(e)))},`populateDb`),g={parser:{parse:t(e=>{a.clear(),n.debug(`[ABNF Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[ABNF Parser] Parsed rules:`,r.rules.length),h(r),n.debug(`[ABNF Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{g as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/arc-BjSQqbzd.js b/.vercel/output/static/assets/arc-DqK6O3qL.js similarity index 98% rename from .vercel/output/static/assets/arc-BjSQqbzd.js rename to .vercel/output/static/assets/arc-DqK6O3qL.js index d1ee7a3..5046079 100644 --- a/.vercel/output/static/assets/arc-BjSQqbzd.js +++ b/.vercel/output/static/assets/arc-DqK6O3qL.js @@ -1 +1 @@ -import{n as e,t}from"./path-BWPyau1x.js";import{a as n,c as r,d as i,f as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,u as p}from"./dist-D9sYb5Oa.js";function m(e){return e.innerRadius}function h(e){return e.outerRadius}function g(e){return e.startAngle}function _(e){return e.endAngle}function v(e){return e&&e.padAngle}function y(e,t,n,r,i,a,o,s){var c=n-e,l=r-t,u=o-i,d=s-a,f=d*c-u*l;if(!(f*f<1e-12))return f=(u*(t-a)-d*(e-i))/f,[e+f*c,t+f*l]}function b(e,t,n,r,i,a,o){var c=e-n,l=t-r,u=(o?a:-a)/d(c*c+l*l),f=u*l,p=-u*c,m=e+f,h=t+p,g=n+f,_=r+p,v=(m+g)/2,y=(h+_)/2,b=g-m,x=_-h,S=b*b+x*x,C=i-a,w=m*_-g*h,T=(x<0?-1:1)*d(s(0,C*C*S-w*w)),E=(w*x-b*T)/S,D=(-w*b-x*T)/S,O=(w*x+b*T)/S,k=(-w*b+x*T)/S,A=E-v,j=D-y,M=O-v,N=k-y;return A*A+j*j>M*M+N*N&&(E=O,D=k),{cx:E,cy:D,x01:-f,y01:-p,x11:E*(i/C-1),y11:D*(i/C-1)}}function x(){var s=m,x=h,S=e(0),C=null,w=g,T=_,E=v,D=null,O=t(k);function k(){var e,t,m=+s.apply(this,arguments),h=+x.apply(this,arguments),g=w.apply(this,arguments)-r,_=T.apply(this,arguments)-r,v=l(_-g),k=_>g;if(D||=e=O(),h1e-12))D.moveTo(0,0);else if(v>c-1e-12)D.moveTo(h*u(g),h*a(g)),D.arc(0,0,h,g,_,!k),m>1e-12&&(D.moveTo(m*u(_),m*a(_)),D.arc(0,0,m,_,g,k));else{var A=g,j=_,M=g,N=_,P=v,F=v,I=E.apply(this,arguments)/2,L=I>1e-12&&(C?+C.apply(this,arguments):d(m*m+h*h)),R=p(l(h-m)/2,+S.apply(this,arguments)),z=R,B=R,V,H;if(L>1e-12){var U=o(L/m*a(I)),W=o(L/h*a(I));(P-=U*2)>1e-12?(U*=k?1:-1,M+=U,N-=U):(P=0,M=N=(g+_)/2),(F-=W*2)>1e-12?(W*=k?1:-1,A+=W,j-=W):(F=0,A=j=(g+_)/2)}var G=h*u(A),K=h*a(A),q=m*u(N),J=m*a(N);if(R>1e-12){var Y=h*u(j),X=h*a(j),Z=m*u(M),Q=m*a(M),$;if(v1e-12?B>1e-12?(V=b(Z,Q,G,K,h,B,k),H=b(Y,X,q,J,h,B,k),D.moveTo(V.cx+V.x01,V.cy+V.y01),B1e-12)||!(P>1e-12)?D.lineTo(q,J):z>1e-12?(V=b(q,J,Y,X,m,-z,k),H=b(G,K,Z,Q,m,-z,k),D.lineTo(V.cx+V.x01,V.cy+V.y01),zM*M+N*N&&(E=O,D=k),{cx:E,cy:D,x01:-f,y01:-p,x11:E*(i/C-1),y11:D*(i/C-1)}}function x(){var s=m,x=h,S=e(0),C=null,w=g,T=_,E=v,D=null,O=t(k);function k(){var e,t,m=+s.apply(this,arguments),h=+x.apply(this,arguments),g=w.apply(this,arguments)-r,_=T.apply(this,arguments)-r,v=l(_-g),k=_>g;if(D||=e=O(),h1e-12))D.moveTo(0,0);else if(v>c-1e-12)D.moveTo(h*u(g),h*a(g)),D.arc(0,0,h,g,_,!k),m>1e-12&&(D.moveTo(m*u(_),m*a(_)),D.arc(0,0,m,_,g,k));else{var A=g,j=_,M=g,N=_,P=v,F=v,I=E.apply(this,arguments)/2,L=I>1e-12&&(C?+C.apply(this,arguments):d(m*m+h*h)),R=p(l(h-m)/2,+S.apply(this,arguments)),z=R,B=R,V,H;if(L>1e-12){var U=o(L/m*a(I)),W=o(L/h*a(I));(P-=U*2)>1e-12?(U*=k?1:-1,M+=U,N-=U):(P=0,M=N=(g+_)/2),(F-=W*2)>1e-12?(W*=k?1:-1,A+=W,j-=W):(F=0,A=j=(g+_)/2)}var G=h*u(A),K=h*a(A),q=m*u(N),J=m*a(N);if(R>1e-12){var Y=h*u(j),X=h*a(j),Z=m*u(M),Q=m*a(M),$;if(v1e-12?B>1e-12?(V=b(Z,Q,G,K,h,B,k),H=b(Y,X,q,J,h,B,k),D.moveTo(V.cx+V.x01,V.cy+V.y01),B1e-12)||!(P>1e-12)?D.lineTo(q,J):z>1e-12?(V=b(q,J,Y,X,m,-z,k),H=b(G,K,Z,Q,m,-z,k),D.lineTo(V.cx+V.x01,V.cy+V.y01),z{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.layoutBase=r():n.layoutBase=r()})(e,function(){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=28)})([(function(e,t,n){function r(){}r.QUALITY=1,r.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,r.DEFAULT_INCREMENTAL=!1,r.DEFAULT_ANIMATION_ON_LAYOUT=!0,r.DEFAULT_ANIMATION_DURING_LAYOUT=!1,r.DEFAULT_ANIMATION_PERIOD=50,r.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,r.DEFAULT_GRAPH_MARGIN=15,r.NODE_DIMENSIONS_INCLUDE_LABELS=!1,r.SIMPLE_NODE_SIZE=40,r.SIMPLE_NODE_HALF_SIZE=r.SIMPLE_NODE_SIZE/2,r.EMPTY_COMPOUND_NODE_SIZE=40,r.MIN_EDGE_LENGTH=1,r.WORLD_BOUNDARY=1e6,r.INITIAL_WORLD_BOUNDARY=r.WORLD_BOUNDARY/1e3,r.WORLD_CENTER_X=1200,r.WORLD_CENTER_Y=900,e.exports=r}),(function(e,t,n){var r=n(2),i=n(8),a=n(9);function o(e,t,n){r.call(this,n),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=n,this.bendpoints=[],this.source=e,this.target=t}for(var s in o.prototype=Object.create(r.prototype),r)o[s]=r[s];o.prototype.getSource=function(){return this.source},o.prototype.getTarget=function(){return this.target},o.prototype.isInterGraph=function(){return this.isInterGraph},o.prototype.getLength=function(){return this.length},o.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},o.prototype.getBendpoints=function(){return this.bendpoints},o.prototype.getLca=function(){return this.lca},o.prototype.getSourceInLca=function(){return this.sourceInLca},o.prototype.getTargetInLca=function(){return this.targetInLca},o.prototype.getOtherEnd=function(e){if(this.source===e)return this.target;if(this.target===e)return this.source;throw`Node is not incident with this edge`},o.prototype.getOtherEndInGraph=function(e,t){for(var n=this.getOtherEnd(e),r=t.getGraphManager().getRoot();;){if(n.getOwner()==t)return n;if(n.getOwner()==r)break;n=n.getOwner().getParent()}return null},o.prototype.updateLength=function(){var e=[,,,,];this.isOverlapingSourceAndTarget=i.getIntersection(this.target.getRect(),this.source.getRect(),e),this.isOverlapingSourceAndTarget||(this.lengthX=e[0]-e[2],this.lengthY=e[1]-e[3],Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},o.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},e.exports=o}),(function(e,t,n){function r(e){this.vGraphObject=e}e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(13),o=n(0),s=n(16),c=n(5);function l(e,t,n,o){n==null&&o==null&&(o=t),r.call(this,o),e.graphManager!=null&&(e=e.graphManager),this.estimatedSize=i.MIN_VALUE,this.inclusionTreeDepth=i.MAX_VALUE,this.vGraphObject=o,this.edges=[],this.graphManager=e,n!=null&&t!=null?this.rect=new a(t.x,t.y,n.width,n.height):this.rect=new a}for(var u in l.prototype=Object.create(r.prototype),r)l[u]=r[u];l.prototype.getEdges=function(){return this.edges},l.prototype.getChild=function(){return this.child},l.prototype.getOwner=function(){return this.owner},l.prototype.getWidth=function(){return this.rect.width},l.prototype.setWidth=function(e){this.rect.width=e},l.prototype.getHeight=function(){return this.rect.height},l.prototype.setHeight=function(e){this.rect.height=e},l.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},l.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},l.prototype.getCenter=function(){return new c(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},l.prototype.getLocation=function(){return new c(this.rect.x,this.rect.y)},l.prototype.getRect=function(){return this.rect},l.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},l.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},l.prototype.setRect=function(e,t){this.rect.x=e.x,this.rect.y=e.y,this.rect.width=t.width,this.rect.height=t.height},l.prototype.setCenter=function(e,t){this.rect.x=e-this.rect.width/2,this.rect.y=t-this.rect.height/2},l.prototype.setLocation=function(e,t){this.rect.x=e,this.rect.y=t},l.prototype.moveBy=function(e,t){this.rect.x+=e,this.rect.y+=t},l.prototype.getEdgeListToNode=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(r.target==e){if(r.source!=n)throw`Incorrect edge source!`;t.push(r)}}),t},l.prototype.getEdgesBetween=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(!(r.source==n||r.target==n))throw`Incorrect edge source and/or target`;(r.target==e||r.source==e)&&t.push(r)}),t},l.prototype.getNeighborsList=function(){var e=new Set,t=this;return t.edges.forEach(function(n){if(n.source==t)e.add(n.target);else{if(n.target!=t)throw`Incorrect incidency!`;e.add(n.source)}}),e},l.prototype.withChildren=function(){var e=new Set,t,n;if(e.add(this),this.child!=null)for(var r=this.child.getNodes(),i=0;it?(this.rect.x-=(this.labelWidth-t)/2,this.setWidth(this.labelWidth)):this.labelPosHorizontal==`right`&&this.setWidth(t+this.labelWidth)),this.labelHeight&&(this.labelPosVertical==`top`?(this.rect.y-=this.labelHeight,this.setHeight(n+this.labelHeight)):this.labelPosVertical==`center`&&this.labelHeight>n?(this.rect.y-=(this.labelHeight-n)/2,this.setHeight(this.labelHeight)):this.labelPosVertical==`bottom`&&this.setHeight(n+this.labelHeight))}}},l.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==i.MAX_VALUE)throw`assert failed`;return this.inclusionTreeDepth},l.prototype.transform=function(e){var t=this.rect.x;t>o.WORLD_BOUNDARY?t=o.WORLD_BOUNDARY:t<-o.WORLD_BOUNDARY&&(t=-o.WORLD_BOUNDARY);var n=this.rect.y;n>o.WORLD_BOUNDARY?n=o.WORLD_BOUNDARY:n<-o.WORLD_BOUNDARY&&(n=-o.WORLD_BOUNDARY);var r=new c(t,n),i=e.inverseTransformPoint(r);this.setLocation(i.x,i.y)},l.prototype.getLeft=function(){return this.rect.x},l.prototype.getRight=function(){return this.rect.x+this.rect.width},l.prototype.getTop=function(){return this.rect.y},l.prototype.getBottom=function(){return this.rect.y+this.rect.height},l.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},e.exports=l}),(function(e,t,n){var r=n(0);function i(){}for(var a in r)i[a]=r[a];i.MAX_ITERATIONS=2500,i.DEFAULT_EDGE_LENGTH=50,i.DEFAULT_SPRING_STRENGTH=.45,i.DEFAULT_REPULSION_STRENGTH=4500,i.DEFAULT_GRAVITY_STRENGTH=.4,i.DEFAULT_COMPOUND_GRAVITY_STRENGTH=1,i.DEFAULT_GRAVITY_RANGE_FACTOR=3.8,i.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=1.5,i.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION=!0,i.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION=!0,i.DEFAULT_COOLING_FACTOR_INCREMENTAL=.3,i.COOLING_ADAPTATION_FACTOR=.33,i.ADAPTATION_LOWER_NODE_LIMIT=1e3,i.ADAPTATION_UPPER_NODE_LIMIT=5e3,i.MAX_NODE_DISPLACEMENT_INCREMENTAL=100,i.MAX_NODE_DISPLACEMENT=i.MAX_NODE_DISPLACEMENT_INCREMENTAL*3,i.MIN_REPULSION_DIST=i.DEFAULT_EDGE_LENGTH/10,i.CONVERGENCE_CHECK_PERIOD=100,i.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=.1,i.MIN_EDGE_LENGTH=1,i.GRID_CALCULATION_CHECK_PERIOD=10,e.exports=i}),(function(e,t,n){function r(e,t){e==null&&t==null?(this.x=0,this.y=0):(this.x=e,this.y=t)}r.prototype.getX=function(){return this.x},r.prototype.getY=function(){return this.y},r.prototype.setX=function(e){this.x=e},r.prototype.setY=function(e){this.y=e},r.prototype.getDifference=function(e){return new DimensionD(this.x-e.x,this.y-e.y)},r.prototype.getCopy=function(){return new r(this.x,this.y)},r.prototype.translate=function(e){return this.x+=e.width,this.y+=e.height,this},e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(0),o=n(7),s=n(3),c=n(1),l=n(13),u=n(12),d=n(11);function f(e,t,n){r.call(this,n),this.estimatedSize=i.MIN_VALUE,this.margin=a.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=e,t!=null&&t instanceof o?this.graphManager=t:t!=null&&t instanceof Layout&&(this.graphManager=t.graphManager)}for(var p in f.prototype=Object.create(r.prototype),r)f[p]=r[p];f.prototype.getNodes=function(){return this.nodes},f.prototype.getEdges=function(){return this.edges},f.prototype.getGraphManager=function(){return this.graphManager},f.prototype.getParent=function(){return this.parent},f.prototype.getLeft=function(){return this.left},f.prototype.getRight=function(){return this.right},f.prototype.getTop=function(){return this.top},f.prototype.getBottom=function(){return this.bottom},f.prototype.isConnected=function(){return this.isConnected},f.prototype.add=function(e,t,n){if(t==null&&n==null){var r=e;if(this.graphManager==null)throw`Graph has no graph mgr!`;if(this.getNodes().indexOf(r)>-1)throw`Node already in graph!`;return r.owner=this,this.getNodes().push(r),r}else{var i=e;if(!(this.getNodes().indexOf(t)>-1&&this.getNodes().indexOf(n)>-1))throw`Source or target not in graph!`;if(!(t.owner==n.owner&&t.owner==this))throw`Both owners must be this graph!`;return t.owner==n.owner?(i.source=t,i.target=n,i.isInterGraph=!1,this.getEdges().push(i),t.edges.push(i),n!=t&&n.edges.push(i),i):null}},f.prototype.remove=function(e){var t=e;if(e instanceof s){if(t==null)throw`Node is null!`;if(!(t.owner!=null&&t.owner==this))throw`Owner graph is invalid!`;if(this.graphManager==null)throw`Owner graph manager is invalid!`;for(var n=t.edges.slice(),r,i=n.length,a=0;a-1&&u>-1))throw`Source and/or target doesn't know this edge!`;r.source.edges.splice(l,1),r.target!=r.source&&r.target.edges.splice(u,1);var o=r.source.owner.getEdges().indexOf(r);if(o==-1)throw`Not in owner's edge list!`;r.source.owner.getEdges().splice(o,1)}},f.prototype.updateLeftTop=function(){for(var e=i.MAX_VALUE,t=i.MAX_VALUE,n,r,a,o=this.getNodes(),s=o.length,c=0;cn&&(e=n),t>r&&(t=r)}return e==i.MAX_VALUE?null:(a=o[0].getParent().paddingLeft==null?this.margin:o[0].getParent().paddingLeft,this.left=t-a,this.top=e-a,new u(this.left,this.top))},f.prototype.updateBounds=function(e){for(var t=i.MAX_VALUE,n=-i.MAX_VALUE,r=i.MAX_VALUE,a=-i.MAX_VALUE,o,s,c,u,d,f=this.nodes,p=f.length,m=0;mo&&(t=o),nc&&(r=c),ao&&(t=o),nc&&(r=c),a=this.nodes.length){var c=0;n.forEach(function(t){t.owner==e&&c++}),c==this.nodes.length&&(this.isConnected=!0)}},e.exports=f}),(function(e,t,n){var r,i=n(1);function a(e){r=n(6),this.layout=e,this.graphs=[],this.edges=[]}a.prototype.addRoot=function(){var e=this.layout.newGraph(),t=this.layout.newNode(null),n=this.add(e,t);return this.setRootGraph(n),this.rootGraph},a.prototype.add=function(e,t,n,r,i){if(n==null&&r==null&&i==null){if(e==null)throw`Graph is null!`;if(t==null)throw`Parent node is null!`;if(this.graphs.indexOf(e)>-1)throw`Graph already in this graph mgr!`;if(this.graphs.push(e),e.parent!=null)throw`Already has a parent!`;if(t.child!=null)throw`Already has a child!`;return e.parent=t,t.child=e,e}else{i=n,r=t,n=e;var a=r.getOwner(),o=i.getOwner();if(!(a!=null&&a.getGraphManager()==this))throw`Source not in this graph mgr!`;if(!(o!=null&&o.getGraphManager()==this))throw`Target not in this graph mgr!`;if(a==o)return n.isInterGraph=!1,a.add(n,r,i);if(n.isInterGraph=!0,n.source=r,n.target=i,this.edges.indexOf(n)>-1)throw`Edge already in inter-graph edge list!`;if(this.edges.push(n),!(n.source!=null&&n.target!=null))throw`Edge source and/or target is null!`;if(!(n.source.edges.indexOf(n)==-1&&n.target.edges.indexOf(n)==-1))throw`Edge already in source and/or target incidency list!`;return n.source.edges.push(n),n.target.edges.push(n),n}},a.prototype.remove=function(e){if(e instanceof r){var t=e;if(t.getGraphManager()!=this)throw`Graph not in this graph mgr`;if(!(t==this.rootGraph||t.parent!=null&&t.parent.graphManager==this))throw`Invalid parent node!`;var n=[];n=n.concat(t.getEdges());for(var a,o=n.length,s=0;s=t.getRight()?n[0]+=Math.min(t.getX()-e.getX(),e.getRight()-t.getRight()):t.getX()<=e.getX()&&t.getRight()>=e.getRight()&&(n[0]+=Math.min(e.getX()-t.getX(),t.getRight()-e.getRight())),e.getY()<=t.getY()&&e.getBottom()>=t.getBottom()?n[1]+=Math.min(t.getY()-e.getY(),e.getBottom()-t.getBottom()):t.getY()<=e.getY()&&t.getBottom()>=e.getBottom()&&(n[1]+=Math.min(e.getY()-t.getY(),t.getBottom()-e.getBottom()));var a=Math.abs((t.getCenterY()-e.getCenterY())/(t.getCenterX()-e.getCenterX()));t.getCenterY()===e.getCenterY()&&t.getCenterX()===e.getCenterX()&&(a=1);var o=a*n[0],s=n[1]/a;n[0]o)return n[0]=r,n[1]=c,n[2]=a,n[3]=y,!1;if(ia)return n[0]=s,n[1]=i,n[2]=_,n[3]=o,!1;if(ra?(n[0]=u,n[1]=d,C=!0):(n[0]=l,n[1]=c,C=!0):T===D&&(r>a?(n[0]=s,n[1]=c,C=!0):(n[0]=f,n[1]=d,C=!0)),-E===D?a>r?(n[2]=v,n[3]=y,w=!0):(n[2]=_,n[3]=g,w=!0):E===D&&(a>r?(n[2]=h,n[3]=g,w=!0):(n[2]=b,n[3]=y,w=!0)),C&&w)return!1;if(r>a?i>o?(O=this.getCardinalDirection(T,D,4),k=this.getCardinalDirection(E,D,2)):(O=this.getCardinalDirection(-T,D,3),k=this.getCardinalDirection(-E,D,1)):i>o?(O=this.getCardinalDirection(-T,D,1),k=this.getCardinalDirection(-E,D,3)):(O=this.getCardinalDirection(T,D,2),k=this.getCardinalDirection(E,D,4)),!C)switch(O){case 1:j=c,A=r+-m/D,n[0]=A,n[1]=j;break;case 2:A=f,j=i+p*D,n[0]=A,n[1]=j;break;case 3:j=d,A=r+m/D,n[0]=A,n[1]=j;break;case 4:A=u,j=i+-p*D,n[0]=A,n[1]=j;break}if(!w)switch(k){case 1:N=g,M=a+-S/D,n[2]=M,n[3]=N;break;case 2:M=b,N=o+x*D,n[2]=M,n[3]=N;break;case 3:N=y,M=a+S/D,n[2]=M,n[3]=N;break;case 4:M=v,N=o+-x*D,n[2]=M,n[3]=N;break}}return!1},i.getCardinalDirection=function(e,t,n){return e>t?n:1+n%4},i.getIntersection=function(e,t,n,i){if(i==null)return this.getIntersection2(e,t,n);var a=e.x,o=e.y,s=t.x,c=t.y,l=n.x,u=n.y,d=i.x,f=i.y,p=void 0,m=void 0,h=void 0,g=void 0,_=void 0,v=void 0,y=void 0,b=void 0,x=void 0;return h=c-o,_=a-s,y=s*o-a*c,g=f-u,v=l-d,b=d*u-l*f,x=h*v-g*_,x===0?null:(p=(_*b-v*y)/x,m=(g*y-h*b)/x,new r(p,m))},i.angleOfVector=function(e,t,n,r){var i=void 0;return e===n?i=r=0){var u=(-c+Math.sqrt(c*c-4*s*l))/(2*s),d=(-c-Math.sqrt(c*c-4*s*l))/(2*s);return u>=0&&u<=1?[u]:d>=0&&d<=1?[d]:null}else return null},i.HALF_PI=.5*Math.PI,i.ONE_AND_HALF_PI=1.5*Math.PI,i.TWO_PI=2*Math.PI,i.THREE_PI=3*Math.PI,e.exports=i}),(function(e,t,n){function r(){}r.sign=function(e){return e>0?1:e<0?-1:0},r.floor=function(e){return e<0?Math.ceil(e):Math.floor(e)},r.ceil=function(e){return e<0?Math.floor(e):Math.ceil(e)},e.exports=r}),(function(e,t,n){function r(){}r.MAX_VALUE=2147483647,r.MIN_VALUE=-2147483648,e.exports=r}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n0&&t;){for(s.push(l[0]);s.length>0&&t;){var u=s[0];s.splice(0,1),o.add(u);for(var d=u.getEdges(),a=0;a-1&&l.splice(h,1)}o=new Set,c=new Map}}return e},f.prototype.createDummyNodesForBendpoints=function(e){for(var t=[],n=e.source,r=this.graphManager.calcLowestCommonAncestor(e.source,e.target),i=0;i0){for(var i=this.edgeToDummyNodes.get(n),a=0;a=0&&t.splice(d,1),s.getNeighborsList().forEach(function(e){if(n.indexOf(e)<0){var t=r.get(e)-1;t==1&&l.push(e),r.set(e,t)}})}n=n.concat(l),(t.length==1||t.length==2)&&(i=!0,a=t[0])}return a},f.prototype.setGraphManager=function(e){this.graphManager=e},e.exports=f}),(function(e,t,n){function r(){}r.seed=1,r.x=0,r.nextDouble=function(){return r.x=Math.sin(r.seed++)*1e4,r.x-Math.floor(r.x)},e.exports=r}),(function(e,t,n){var r=n(5);function i(e,t){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}i.prototype.getWorldOrgX=function(){return this.lworldOrgX},i.prototype.setWorldOrgX=function(e){this.lworldOrgX=e},i.prototype.getWorldOrgY=function(){return this.lworldOrgY},i.prototype.setWorldOrgY=function(e){this.lworldOrgY=e},i.prototype.getWorldExtX=function(){return this.lworldExtX},i.prototype.setWorldExtX=function(e){this.lworldExtX=e},i.prototype.getWorldExtY=function(){return this.lworldExtY},i.prototype.setWorldExtY=function(e){this.lworldExtY=e},i.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},i.prototype.setDeviceOrgX=function(e){this.ldeviceOrgX=e},i.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},i.prototype.setDeviceOrgY=function(e){this.ldeviceOrgY=e},i.prototype.getDeviceExtX=function(){return this.ldeviceExtX},i.prototype.setDeviceExtX=function(e){this.ldeviceExtX=e},i.prototype.getDeviceExtY=function(){return this.ldeviceExtY},i.prototype.setDeviceExtY=function(e){this.ldeviceExtY=e},i.prototype.transformX=function(e){var t=0,n=this.lworldExtX;return n!=0&&(t=this.ldeviceOrgX+(e-this.lworldOrgX)*this.ldeviceExtX/n),t},i.prototype.transformY=function(e){var t=0,n=this.lworldExtY;return n!=0&&(t=this.ldeviceOrgY+(e-this.lworldOrgY)*this.ldeviceExtY/n),t},i.prototype.inverseTransformX=function(e){var t=0,n=this.ldeviceExtX;return n!=0&&(t=this.lworldOrgX+(e-this.ldeviceOrgX)*this.lworldExtX/n),t},i.prototype.inverseTransformY=function(e){var t=0,n=this.ldeviceExtY;return n!=0&&(t=this.lworldOrgY+(e-this.ldeviceOrgY)*this.lworldExtY/n),t},i.prototype.inverseTransformPoint=function(e){return new r(this.inverseTransformX(e.x),this.inverseTransformY(e.y))},e.exports=i}),(function(e,t,n){function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);ta.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*a.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-a.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT_INCREMENTAL):(e>a.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(a.COOLING_ADAPTATION_FACTOR,1-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*(1-a.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.displacementThresholdPerNode=3*a.DEFAULT_EDGE_LENGTH/100,this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},l.prototype.calcSpringForces=function(){for(var e=this.getAllEdges(),t,n=0;n0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n,r,i,o,s=this.getAllNodes(),c;if(this.useFRGridVariant)for(this.totalIterations%a.GRID_CALCULATION_CHECK_PERIOD==1&&e&&this.updateGrid(),c=new Set,n=0;nc||s>c)&&(e.gravitationForceX=-this.gravityConstant*i,e.gravitationForceY=-this.gravityConstant*a)):(c=t.getEstimatedSize()*this.compoundGravityRangeFactor,(o>c||s>c)&&(e.gravitationForceX=-this.gravityConstant*i*this.compoundGravityConstant,e.gravitationForceY=-this.gravityConstant*a*this.compoundGravityConstant))},l.prototype.isConverged=function(){var e,t=!1;return this.totalIterations>this.maxIterations/3&&(t=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),e=this.totalDisplacement=c.length||u>=c[0].length)){for(var d=0;de}}]),e}()}),(function(e,t,n){function r(){}r.svd=function(e){this.U=null,this.V=null,this.s=null,this.m=0,this.n=0,this.m=e.length,this.n=e[0].length;var t=Math.min(this.m,this.n);this.s=function(e){for(var t=[];e-->0;)t.push(0);return t}(Math.min(this.m+1,this.n)),this.U=function(e){return function e(t){if(t.length==0)return 0;for(var n=[],r=0;r0;)t.push(0);return t}(this.n),i=function(e){for(var t=[];e-->0;)t.push(0);return t}(this.m),a=!0,o=!0,s=Math.min(this.m-1,this.n),c=Math.max(0,Math.min(this.n-2,this.m)),l=0;l=0;k--)if(this.s[k]!==0){for(var A=k+1;A=0;L--){if(function(e,t){return e&&t}(L0;){var U=void 0,W=void 0;for(U=E-2;U>=-1&&U!==-1;U--)if(Math.abs(n[U])<=re+ne*(Math.abs(this.s[U])+Math.abs(this.s[U+1]))){n[U]=0;break}if(U===E-2)W=4;else{var G=void 0;for(G=E-1;G>=U&&G!==U;G--){var ie=(G===E?0:Math.abs(n[G]))+(G===U+1?0:Math.abs(n[G-1]));if(Math.abs(this.s[G])<=re+ne*ie){this.s[G]=0;break}}G===U?W=3:G===E-1?W=1:(W=2,U=G)}switch(U++,W){case 1:var K=n[E-2];n[E-2]=0;for(var q=E-2;q>=U;q--){var J=r.hypot(this.s[q],K),Y=this.s[q]/J,X=K/J;if(this.s[q]=J,q!==U&&(K=-X*n[q-1],n[q-1]=Y*n[q-1]),o)for(var Z=0;Z=this.s[U+1]);){var De=this.s[U];if(this.s[U]=this.s[U+1],this.s[U+1]=De,o&&UMath.abs(t)?(n=t/e,n=Math.abs(e)*Math.sqrt(1+n*n)):t==0?n=0:(n=e/t,n=Math.abs(t)*Math.sqrt(1+n*n)),n},e.exports=r}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;i(this,e),this.sequence1=t,this.sequence2=n,this.match_score=r,this.mismatch_penalty=a,this.gap_penalty=o,this.iMax=t.length+1,this.jMax=n.length+1,this.grid=Array(this.iMax);for(var s=0;s=0;n--){var r=this.listeners[n];r.event===e&&r.callback===t&&this.listeners.splice(n,1)}},i.emit=function(e,t){for(var n=0;n{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(D()):typeof define==`function`&&define.amd?define([`layout-base`],r):typeof e==`object`?e.coseBase=r(D()):n.coseBase=r(n.layoutBase)})(e,function(e){return(()=>{var t={45:((e,t,n)=>{var r={};r.layoutBase=n(551),r.CoSEConstants=n(806),r.CoSEEdge=n(767),r.CoSEGraph=n(880),r.CoSEGraphManager=n(578),r.CoSELayout=n(765),r.CoSENode=n(991),r.ConstraintHandler=n(902),e.exports=r}),806:((e,t,n)=>{var r=n(551).FDLayoutConstants;function i(){}for(var a in r)i[a]=r[a];i.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,i.DEFAULT_RADIAL_SEPARATION=r.DEFAULT_EDGE_LENGTH,i.DEFAULT_COMPONENT_SEPERATION=60,i.TILE=!0,i.TILING_PADDING_VERTICAL=10,i.TILING_PADDING_HORIZONTAL=10,i.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,i.ENFORCE_CONSTRAINTS=!0,i.APPLY_LAYOUT=!0,i.RELAX_MOVEMENT_ON_CONSTRAINTS=!0,i.TREE_REDUCTION_ON_INCREMENTAL=!0,i.PURE_INCREMENTAL=i.DEFAULT_INCREMENTAL,e.exports=i}),767:((e,t,n)=>{var r=n(551).FDLayoutEdge;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),880:((e,t,n)=>{var r=n(551).LGraph;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),578:((e,t,n)=>{var r=n(551).LGraphManager;function i(e){r.call(this,e)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),765:((e,t,n)=>{var r=n(551).FDLayout,i=n(578),a=n(880),o=n(991),s=n(767),c=n(806),l=n(902),u=n(551).FDLayoutConstants,d=n(551).LayoutConstants,f=n(551).Point,p=n(551).PointD,m=n(551).DimensionD,h=n(551).Layout,g=n(551).Integer,_=n(551).IGeometry,v=n(551).LGraph,y=n(551).Transform,b=n(551).LinkedList;function x(){r.call(this),this.toBeTiled={},this.constraints={}}for(var S in x.prototype=Object.create(r.prototype),r)x[S]=r[S];x.prototype.newGraphManager=function(){var e=new i(this);return this.graphManager=e,e},x.prototype.newGraph=function(e){return new a(null,this.graphManager,e)},x.prototype.newNode=function(e){return new o(this.graphManager,e)},x.prototype.newEdge=function(e){return new s(null,null,e)},x.prototype.initParameters=function(){r.prototype.initParameters.call(this,arguments),this.isSubLayout||(c.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=c.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=c.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.gravityConstant=u.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=u.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=u.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=u.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1)},x.prototype.initSpringEmbedder=function(){r.prototype.initSpringEmbedder.call(this),this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/u.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=.04,this.coolingAdjuster=1},x.prototype.layout=function(){return d.DEFAULT_CREATE_BENDS_AS_NEEDED&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},x.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),!this.incremental){var e=this.getFlatForest();if(e.length>0)this.positionNodesRadially(e);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n),this.positionNodesRandomly()}}else if(c.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n)}return Object.keys(this.constraints).length>0&&(l.handleConstraints(this),this.initConstraintVariables()),this.initSpringEmbedder(),c.APPLY_LAYOUT&&this.runSpringEmbedder(),!0},x.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%u.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-this.coolingCycle**+(Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),t=this.nodesWithGravity.filter(function(t){return e.has(t)});this.graphManager.setAllNodesToApplyGravitation(t),this.graphManager.updateBounds(),this.updateGrid(),c.PURE_INCREMENTAL?this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL/2:this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),c.PURE_INCREMENTAL?this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL/2*((100-this.afterGrowthIterations)/100):this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var n=!this.isTreeGrowing&&!this.isGrowthFinished,r=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(n,r),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},x.prototype.getPositionsData=function(){for(var e=this.graphManager.getAllNodes(),t={},n=0;n0&&this.updateDisplacements();for(var n=0;n0&&(r.fixedNodeWeight=a)}}if(this.constraints.relativePlacementConstraint){var o=new Map,s=new Map;if(this.dummyToNodeForVerticalAlignment=new Map,this.dummyToNodeForHorizontalAlignment=new Map,this.fixedNodesOnHorizontal=new Set,this.fixedNodesOnVertical=new Set,this.fixedNodeSet.forEach(function(t){e.fixedNodesOnHorizontal.add(t),e.fixedNodesOnVertical.add(t)}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var l=this.constraints.alignmentConstraint.vertical,n=0;n=2*e.length/3;r--)t=Math.floor(Math.random()*(r+1)),n=e[r],e[r]=e[t],e[t]=n;return e},this.nodesInRelativeHorizontal=[],this.nodesInRelativeVertical=[],this.nodeToRelativeConstraintMapHorizontal=new Map,this.nodeToRelativeConstraintMapVertical=new Map,this.nodeToTempPositionMapHorizontal=new Map,this.nodeToTempPositionMapVertical=new Map,this.constraints.relativePlacementConstraint.forEach(function(t){if(t.left){var n=o.has(t.left)?o.get(t.left):t.left,r=o.has(t.right)?o.get(t.right):t.right;e.nodesInRelativeHorizontal.includes(n)||(e.nodesInRelativeHorizontal.push(n),e.nodeToRelativeConstraintMapHorizontal.set(n,[]),e.dummyToNodeForVerticalAlignment.has(n)?e.nodeToTempPositionMapHorizontal.set(n,e.idToNodeMap.get(e.dummyToNodeForVerticalAlignment.get(n)[0]).getCenterX()):e.nodeToTempPositionMapHorizontal.set(n,e.idToNodeMap.get(n).getCenterX())),e.nodesInRelativeHorizontal.includes(r)||(e.nodesInRelativeHorizontal.push(r),e.nodeToRelativeConstraintMapHorizontal.set(r,[]),e.dummyToNodeForVerticalAlignment.has(r)?e.nodeToTempPositionMapHorizontal.set(r,e.idToNodeMap.get(e.dummyToNodeForVerticalAlignment.get(r)[0]).getCenterX()):e.nodeToTempPositionMapHorizontal.set(r,e.idToNodeMap.get(r).getCenterX())),e.nodeToRelativeConstraintMapHorizontal.get(n).push({right:r,gap:t.gap}),e.nodeToRelativeConstraintMapHorizontal.get(r).push({left:n,gap:t.gap})}else{var i=s.has(t.top)?s.get(t.top):t.top,a=s.has(t.bottom)?s.get(t.bottom):t.bottom;e.nodesInRelativeVertical.includes(i)||(e.nodesInRelativeVertical.push(i),e.nodeToRelativeConstraintMapVertical.set(i,[]),e.dummyToNodeForHorizontalAlignment.has(i)?e.nodeToTempPositionMapVertical.set(i,e.idToNodeMap.get(e.dummyToNodeForHorizontalAlignment.get(i)[0]).getCenterY()):e.nodeToTempPositionMapVertical.set(i,e.idToNodeMap.get(i).getCenterY())),e.nodesInRelativeVertical.includes(a)||(e.nodesInRelativeVertical.push(a),e.nodeToRelativeConstraintMapVertical.set(a,[]),e.dummyToNodeForHorizontalAlignment.has(a)?e.nodeToTempPositionMapVertical.set(a,e.idToNodeMap.get(e.dummyToNodeForHorizontalAlignment.get(a)[0]).getCenterY()):e.nodeToTempPositionMapVertical.set(a,e.idToNodeMap.get(a).getCenterY())),e.nodeToRelativeConstraintMapVertical.get(i).push({bottom:a,gap:t.gap}),e.nodeToRelativeConstraintMapVertical.get(a).push({top:i,gap:t.gap})}});else{var d=new Map,f=new Map;this.constraints.relativePlacementConstraint.forEach(function(e){if(e.left){var t=o.has(e.left)?o.get(e.left):e.left,n=o.has(e.right)?o.get(e.right):e.right;d.has(t)?d.get(t).push(n):d.set(t,[n]),d.has(n)?d.get(n).push(t):d.set(n,[t])}else{var r=s.has(e.top)?s.get(e.top):e.top,i=s.has(e.bottom)?s.get(e.bottom):e.bottom;f.has(r)?f.get(r).push(i):f.set(r,[i]),f.has(i)?f.get(i).push(r):f.set(i,[r])}});var p=function(e,t){var n=[],r=[],i=new b,a=new Set,o=0;return e.forEach(function(s,c){if(!a.has(c)){n[o]=[],r[o]=!1;var l=c;for(i.push(l),a.add(l),n[o].push(l);i.length!=0;)l=i.shift(),t.has(l)&&(r[o]=!0),e.get(l).forEach(function(e){a.has(e)||(i.push(e),a.add(e),n[o].push(e))});o++}}),{components:n,isFixed:r}},m=p(d,e.fixedNodesOnHorizontal);this.componentsOnHorizontal=m.components,this.fixedComponentsOnHorizontal=m.isFixed;var h=p(f,e.fixedNodesOnVertical);this.componentsOnVertical=h.components,this.fixedComponentsOnVertical=h.isFixed}}},x.prototype.updateDisplacements=function(){var e=this;if(this.constraints.fixedNodeConstraint&&this.constraints.fixedNodeConstraint.forEach(function(t){var n=e.idToNodeMap.get(t.nodeId);n.displacementX=0,n.displacementY=0}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var t=this.constraints.alignmentConstraint.vertical,n=0;n1){var s;for(s=0;sr&&(r=Math.floor(o.y)),a=Math.floor(o.x+c.DEFAULT_COMPONENT_SEPERATION)}this.transform(new p(d.WORLD_CENTER_X-o.x/2,d.WORLD_CENTER_Y-o.y/2))},x.radialLayout=function(e,t,n){var r=Math.max(this.maxDiagonalInTree(e),c.DEFAULT_RADIAL_SEPARATION);x.branchRadialLayout(t,null,0,359,0,r);var i=v.calculateBounds(e),a=new y;a.setDeviceOrgX(i.getMinX()),a.setDeviceOrgY(i.getMinY()),a.setWorldOrgX(n.x),a.setWorldOrgY(n.y);for(var o=0;o1;){var g=h[0];h.splice(0,1);var v=u.indexOf(g);v>=0&&u.splice(v,1),p--,d--}m=t==null?0:(u.indexOf(h[0])+1)%p;for(var y=Math.abs(r-n)/d,b=m;f!=d;b=++b%p){var S=u[b].getOtherEnd(e);if(S!=t){var C=(n+f*y)%360,w=(C+y)%360;x.branchRadialLayout(S,e,C,w,i+a,a),f++}}},x.maxDiagonalInTree=function(e){for(var t=g.MIN_VALUE,n=0;nt&&(t=r)}return t},x.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},x.prototype.groupZeroDegreeMembers=function(){var e=this,t={};this.memberGroups={},this.idToDummyNode={};for(var n=[],r=this.graphManager.getAllNodes(),i=0;i1){var r=`DummyCompound_`+n;e.memberGroups[r]=t[n];var i=t[n][0].getParent(),a=new o(e.graphManager);a.id=r,a.paddingLeft=i.paddingLeft||0,a.paddingRight=i.paddingRight||0,a.paddingBottom=i.paddingBottom||0,a.paddingTop=i.paddingTop||0,e.idToDummyNode[r]=a;var s=e.getGraphManager().add(e.newGraph(),a),c=i.getChild();c.add(a);for(var l=0;li?(r.rect.x-=(r.labelWidth-i)/2,r.setWidth(r.labelWidth),r.labelMarginLeft=(r.labelWidth-i)/2):r.labelPosHorizontal==`right`&&r.setWidth(i+r.labelWidth)),r.labelHeight&&(r.labelPosVertical==`top`?(r.rect.y-=r.labelHeight,r.setHeight(a+r.labelHeight),r.labelMarginTop=r.labelHeight):r.labelPosVertical==`center`&&r.labelHeight>a?(r.rect.y-=(r.labelHeight-a)/2,r.setHeight(r.labelHeight),r.labelMarginTop=(r.labelHeight-a)/2):r.labelPosVertical==`bottom`&&r.setHeight(a+r.labelHeight))}})},x.prototype.repopulateCompounds=function(){for(var e=this.compoundOrder.length-1;e>=0;e--){var t=this.compoundOrder[e],n=t.id,r=t.paddingLeft,i=t.paddingTop,a=t.labelMarginLeft,o=t.labelMarginTop;this.adjustLocations(this.tiledMemberPack[n],t.rect.x,t.rect.y,r,i,a,o)}},x.prototype.repopulateZeroDegreeMembers=function(){var e=this,t=this.tiledZeroDegreePack;Object.keys(t).forEach(function(n){var r=e.idToDummyNode[n],i=r.paddingLeft,a=r.paddingTop,o=r.labelMarginLeft,s=r.labelMarginTop;e.adjustLocations(t[n],r.rect.x,r.rect.y,i,a,o,s)})},x.prototype.getToBeTiled=function(e){var t=e.id;if(this.toBeTiled[t]!=null)return this.toBeTiled[t];var n=e.getChild();if(n==null)return this.toBeTiled[t]=!1,!1;for(var r=n.getNodes(),i=0;i0)return this.toBeTiled[t]=!1,!1;if(a.getChild()==null){this.toBeTiled[a.id]=!1;continue}if(!this.getToBeTiled(a))return this.toBeTiled[t]=!1,!1}return this.toBeTiled[t]=!0,!0},x.prototype.getNodeDegree=function(e){e.id;for(var t=e.getEdges(),n=0,r=0;ru&&(u=f.rect.height)}n+=u+e.verticalPadding}},x.prototype.tileCompoundMembers=function(e,t){var n=this;this.tiledMemberPack=[],Object.keys(e).forEach(function(r){var i=t[r];if(n.tiledMemberPack[r]=n.tileNodes(e[r],i.paddingLeft+i.paddingRight),i.rect.width=n.tiledMemberPack[r].width,i.rect.height=n.tiledMemberPack[r].height,i.setCenter(n.tiledMemberPack[r].centerX,n.tiledMemberPack[r].centerY),i.labelMarginLeft=0,i.labelMarginTop=0,c.NODE_DIMENSIONS_INCLUDE_LABELS){var a=i.rect.width,o=i.rect.height;i.labelWidth&&(i.labelPosHorizontal==`left`?(i.rect.x-=i.labelWidth,i.setWidth(a+i.labelWidth),i.labelMarginLeft=i.labelWidth):i.labelPosHorizontal==`center`&&i.labelWidth>a?(i.rect.x-=(i.labelWidth-a)/2,i.setWidth(i.labelWidth),i.labelMarginLeft=(i.labelWidth-a)/2):i.labelPosHorizontal==`right`&&i.setWidth(a+i.labelWidth)),i.labelHeight&&(i.labelPosVertical==`top`?(i.rect.y-=i.labelHeight,i.setHeight(o+i.labelHeight),i.labelMarginTop=i.labelHeight):i.labelPosVertical==`center`&&i.labelHeight>o?(i.rect.y-=(i.labelHeight-o)/2,i.setHeight(i.labelHeight),i.labelMarginTop=(i.labelHeight-o)/2):i.labelPosVertical==`bottom`&&i.setHeight(o+i.labelHeight))}})},x.prototype.tileNodes=function(e,t){var n=this.tileNodesByFavoringDim(e,t,!0),r=this.tileNodesByFavoringDim(e,t,!1),i=this.getOrgRatio(n);return this.getOrgRatio(r)s&&(s=e.getWidth())});var l=a/i,u=o/i,d=(n-r)**2+4*(l+r)*(u+n)*i,f=(r-n+Math.sqrt(d))/(2*(l+r)),p;t?(p=Math.ceil(f),p==f&&p++):p=Math.floor(f);var m=p*(l+r)-r;return s>m&&(m=s),m+=r*2,m},x.prototype.tileNodesByFavoringDim=function(e,t,n){var r=c.TILING_PADDING_VERTICAL,i=c.TILING_PADDING_HORIZONTAL,a=c.TILING_COMPARE_BY,o={rows:[],rowWidth:[],rowHeight:[],width:0,height:t,verticalPadding:r,horizontalPadding:i,centerX:0,centerY:0};a&&(o.idealRowWidth=this.calcIdealRowWidth(e,n));var s=function(e){return e.rect.width*e.rect.height},l=function(e,t){return s(t)-s(e)};e.sort(function(e,t){var n=l;return o.idealRowWidth?(n=a,n(e.id,t.id)):n(e,t)});for(var u=0,d=0,f=0;f0&&(a+=e.horizontalPadding),e.rowWidth[n]=a,e.width0&&(o+=e.verticalPadding);var s=0;o>e.rowHeight[n]&&(s=e.rowHeight[n],e.rowHeight[n]=o,s=e.rowHeight[n]-s),e.height+=s,e.rows[n].push(t)},x.prototype.getShortestRowIndex=function(e){for(var t=-1,n=Number.MAX_VALUE,r=0;rn&&(t=r,n=e.rowWidth[r]);return t},x.prototype.canAddHorizontal=function(e,t,n){if(e.idealRowWidth){var r=e.rows.length-1;return e.rowWidth[r]+t+e.horizontalPadding<=e.idealRowWidth}var i=this.getShortestRowIndex(e);if(i<0)return!0;var a=e.rowWidth[i];if(a+e.horizontalPadding+t<=e.width)return!0;var o=0;e.rowHeight[i]0&&(o=n+e.verticalPadding-e.rowHeight[i]);var s=e.width-a>=t+e.horizontalPadding?(e.height+o)/(a+t+e.horizontalPadding):(e.height+o)/e.width;o=n+e.verticalPadding;var c=e.widtha&&t!=n){r.splice(-1,1),e.rows[n].push(i),e.rowWidth[t]=e.rowWidth[t]-a,e.rowWidth[n]=e.rowWidth[n]+a,e.width=e.rowWidth[instance.getLongestRowIndex(e)];for(var o=Number.MIN_VALUE,s=0;so&&(o=r[s].height);t>0&&(o+=e.verticalPadding);var c=e.rowHeight[t]+e.rowHeight[n];e.rowHeight[t]=o,e.rowHeight[n]0)for(var d=i;d<=a;d++)l[0]+=this.grid[d][o-1].length+this.grid[d][o].length-1;if(a0)for(var d=o;d<=s;d++)l[3]+=this.grid[i-1][d].length+this.grid[i][d].length-1;for(var f=g.MAX_VALUE,p,m,h=0;h{var r=n(551).FDLayoutNode,i=n(551).IMath;function a(e,t,n,i){r.call(this,e,t,n,i)}for(var o in a.prototype=Object.create(r.prototype),r)a[o]=r[o];a.prototype.calculateDisplacement=function(){var e=this.graphManager.getLayout();this.getChild()!=null&&this.fixedNodeWeight?(this.displacementX+=e.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.fixedNodeWeight,this.displacementY+=e.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.fixedNodeWeight):(this.displacementX+=e.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY+=e.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren),Math.abs(this.displacementX)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementX=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementX)),Math.abs(this.displacementY)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementY=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementY)),this.child&&this.child.getNodes().length>0&&this.propogateDisplacementToChildren(this.displacementX,this.displacementY)},a.prototype.propogateDisplacementToChildren=function(e,t){for(var n=this.getChild().getNodes(),r,i=0;i{function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t0){var a=0;r.forEach(function(e){t==`horizontal`?(f.set(e,c.has(e)?l[c.get(e)]:i.get(e)),a+=f.get(e)):(f.set(e,c.has(e)?u[c.get(e)]:i.get(e)),a+=f.get(e))}),a/=r.length,e.forEach(function(e){n.has(e)||f.set(e,a)})}else{var o=0;e.forEach(function(e){t==`horizontal`?o+=c.has(e)?l[c.get(e)]:i.get(e):o+=c.has(e)?u[c.get(e)]:i.get(e)}),o/=e.length,e.forEach(function(e){f.set(e,o)})}});for(var h=function(){var r=m.shift();e.get(r).forEach(function(e){if(f.get(e.id)o&&(o=v),ys&&(s=y)}}catch(e){p=!0,m=e}finally{try{!d&&h.return&&h.return()}finally{if(p)throw m}}var b=(r+o)/2-(a+s)/2,x=!0,S=!1,C=void 0;try{for(var w=e[Symbol.iterator](),T;!(x=(T=w.next()).done);x=!0){var E=T.value;f.set(E,f.get(E)+b)}}catch(e){S=!0,C=e}finally{try{!x&&w.return&&w.return()}finally{if(S)throw C}}})}return f},v=function(e){var t=0,n=0,r=0,i=0;if(e.forEach(function(e){e.left?l[c.get(e.left)]-l[c.get(e.right)]>=0?t++:n++:u[c.get(e.top)]-u[c.get(e.bottom)]>=0?r++:i++}),t>n&&r>i)for(var a=0;an)for(var o=0;oi)for(var s=0;s1)t.fixedNodeConstraint.forEach(function(e,t){S[t]=[e.position.x,e.position.y],C[t]=[l[c.get(e.nodeId)],u[c.get(e.nodeId)]]}),w=!0;else if(t.alignmentConstraint)(function(){var e=0;if(t.alignmentConstraint.vertical){for(var n=t.alignmentConstraint.vertical,i=function(t){var i=new Set;n[t].forEach(function(e){i.add(e)});var a=new Set([].concat(r(i)).filter(function(e){return E.has(e)})),o=void 0;o=a.size>0?l[c.get(a.values().next().value)]:g(i).x,n[t].forEach(function(t){S[e]=[o,u[c.get(t)]],C[e]=[l[c.get(t)],u[c.get(t)]],e++})},a=0;a0?l[c.get(i.values().next().value)]:g(n).y,o[t].forEach(function(t){S[e]=[l[c.get(t)],a],C[e]=[l[c.get(t)],u[c.get(t)]],e++})},d=0;dA&&(A=k[M].length,j=M);if(A0){var W={x:0,y:0};t.fixedNodeConstraint.forEach(function(e,t){var n={x:l[c.get(e.nodeId)],y:u[c.get(e.nodeId)]},r=e.position,i=h(r,n);W.x+=i.x,W.y+=i.y}),W.x/=t.fixedNodeConstraint.length,W.y/=t.fixedNodeConstraint.length,l.forEach(function(e,t){l[t]+=W.x}),u.forEach(function(e,t){u[t]+=W.y}),t.fixedNodeConstraint.forEach(function(e){l[c.get(e.nodeId)]=e.position.x,u[c.get(e.nodeId)]=e.position.y})}if(t.alignmentConstraint){if(t.alignmentConstraint.vertical)for(var G=t.alignmentConstraint.vertical,ie=function(e){var t=new Set;G[e].forEach(function(e){t.add(e)});var n=new Set([].concat(r(t)).filter(function(e){return E.has(e)})),i=void 0;i=n.size>0?l[c.get(n.values().next().value)]:g(t).x,t.forEach(function(e){E.has(e)||(l[c.get(e)]=i)})},K=0;K0?u[c.get(n.values().next().value)]:g(t).y,t.forEach(function(e){E.has(e)||(u[c.get(e)]=i)})},Y=0;Y{t.exports=e})},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}return r(45)})()})})),k=e(t(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(O()):typeof define==`function`&&define.amd?define([`cose-base`],r):typeof e==`object`?e.cytoscapeFcose=r(O()):n.cytoscapeFcose=r(n.coseBase)})(e,function(e){return(()=>{var t={658:(e=>{e.exports=Object.assign==null?function(e){return[...arguments].slice(1).forEach(function(t){Object.keys(t).forEach(function(n){return e[n]=t[n]})}),e}:Object.assign.bind(Object)}),548:((e,t,n)=>{var r=function(){function e(e,t){var n=[],r=!0,i=!1,a=void 0;try{for(var o=e[Symbol.iterator](),s;!(r=(s=o.next()).done)&&(n.push(s.value),!(t&&n.length===t));r=!0);}catch(e){i=!0,a=e}finally{try{!r&&o.return&&o.return()}finally{if(i)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw TypeError(`Invalid attempt to destructure non-iterable instance`)}}(),i=n(140).layoutBase.LinkedList,a={};a.getTopMostNodes=function(e){for(var t={},n=0;n0&&l.merge(e)});for(var u=0;u1){l=s[0],u=l.connectedEdges().length,s.forEach(function(e){e.connectedEdges().length0&&r.set(`dummy`+(r.size+1),p),m},a.relocateComponent=function(e,t,n){if(!n.fixedNodeConstraint){var i=1/0,a=-1/0,o=1/0,s=-1/0;if(n.quality==`draft`){var c=!0,l=!1,u=void 0;try{for(var d=t.nodeIndexes[Symbol.iterator](),f;!(c=(f=d.next()).done);c=!0){var p=f.value,m=r(p,2),h=m[0],g=m[1],_=n.cy.getElementById(h);if(_){var v=_.boundingBox(),y=t.xCoords[g]-v.w/2,b=t.xCoords[g]+v.w/2,x=t.yCoords[g]-v.h/2,S=t.yCoords[g]+v.h/2;ya&&(a=b),xs&&(s=S)}}}catch(e){l=!0,u=e}finally{try{!c&&d.return&&d.return()}finally{if(l)throw u}}var C=e.x-(a+i)/2,w=e.y-(s+o)/2;t.xCoords=t.xCoords.map(function(e){return e+C}),t.yCoords=t.yCoords.map(function(e){return e+w})}else{Object.keys(t).forEach(function(e){var n=t[e],r=n.getRect().x,c=n.getRect().x+n.getRect().width,l=n.getRect().y,u=n.getRect().y+n.getRect().height;ra&&(a=c),ls&&(s=u)});var T=e.x-(a+i)/2,E=e.y-(s+o)/2;Object.keys(t).forEach(function(e){var n=t[e];n.setCenter(n.getCenterX()+T,n.getCenterY()+E)})}}},a.calcBoundingBox=function(e,t,n,r){for(var i=2**53-1,a=-(2**53-1),o=2**53-1,s=-(2**53-1),c=void 0,l=void 0,u=void 0,d=void 0,f=e.descendants().not(`:parent`),p=f.length,m=0;mc&&(i=c),au&&(o=u),s{var r=n(548),i=n(140).CoSELayout,a=n(140).CoSENode,o=n(140).layoutBase.PointD,s=n(140).layoutBase.DimensionD,c=n(140).layoutBase.LayoutConstants,l=n(140).layoutBase.FDLayoutConstants,u=n(140).CoSEConstants;e.exports={coseLayout:function(e,t){var n=e.cy,d=e.eles,f=d.nodes(),p=d.edges(),m=void 0,h=void 0,g=void 0,_={};e.randomize&&(m=t.nodeIndexes,h=t.xCoords,g=t.yCoords);var v=function(e){return typeof e==`function`},y=function(e,t){return v(e)?e(t):e},b=r.calcParentsWithoutChildren(n,d),x=function e(t,n,i,c){for(var l=n.length,u=0;u0){var S=void 0;S=i.getGraphManager().add(i.newGraph(),p),e(S,f,i,c)}}},S=function(t,n,r){for(var i=0,a=0,o=0;o0?u.DEFAULT_EDGE_LENGTH=l.DEFAULT_EDGE_LENGTH=i/a:v(e.idealEdgeLength)?u.DEFAULT_EDGE_LENGTH=l.DEFAULT_EDGE_LENGTH=50:u.DEFAULT_EDGE_LENGTH=l.DEFAULT_EDGE_LENGTH=e.idealEdgeLength,u.MIN_REPULSION_DIST=l.MIN_REPULSION_DIST=l.DEFAULT_EDGE_LENGTH/10,u.DEFAULT_RADIAL_SEPARATION=l.DEFAULT_EDGE_LENGTH)},C=function(e,t){t.fixedNodeConstraint&&(e.constraints.fixedNodeConstraint=t.fixedNodeConstraint),t.alignmentConstraint&&(e.constraints.alignmentConstraint=t.alignmentConstraint),t.relativePlacementConstraint&&(e.constraints.relativePlacementConstraint=t.relativePlacementConstraint)};e.nestingFactor!=null&&(u.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=l.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=e.nestingFactor),e.gravity!=null&&(u.DEFAULT_GRAVITY_STRENGTH=l.DEFAULT_GRAVITY_STRENGTH=e.gravity),e.numIter!=null&&(u.MAX_ITERATIONS=l.MAX_ITERATIONS=e.numIter),e.gravityRange!=null&&(u.DEFAULT_GRAVITY_RANGE_FACTOR=l.DEFAULT_GRAVITY_RANGE_FACTOR=e.gravityRange),e.gravityCompound!=null&&(u.DEFAULT_COMPOUND_GRAVITY_STRENGTH=l.DEFAULT_COMPOUND_GRAVITY_STRENGTH=e.gravityCompound),e.gravityRangeCompound!=null&&(u.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=l.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=e.gravityRangeCompound),e.initialEnergyOnIncremental!=null&&(u.DEFAULT_COOLING_FACTOR_INCREMENTAL=l.DEFAULT_COOLING_FACTOR_INCREMENTAL=e.initialEnergyOnIncremental),e.tilingCompareBy!=null&&(u.TILING_COMPARE_BY=e.tilingCompareBy),e.quality==`proof`?c.QUALITY=2:c.QUALITY=0,u.NODE_DIMENSIONS_INCLUDE_LABELS=l.NODE_DIMENSIONS_INCLUDE_LABELS=c.NODE_DIMENSIONS_INCLUDE_LABELS=e.nodeDimensionsIncludeLabels,u.DEFAULT_INCREMENTAL=l.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=!e.randomize,u.ANIMATE=l.ANIMATE=c.ANIMATE=e.animate,u.TILE=e.tile,u.TILING_PADDING_VERTICAL=typeof e.tilingPaddingVertical==`function`?e.tilingPaddingVertical.call():e.tilingPaddingVertical,u.TILING_PADDING_HORIZONTAL=typeof e.tilingPaddingHorizontal==`function`?e.tilingPaddingHorizontal.call():e.tilingPaddingHorizontal,u.DEFAULT_INCREMENTAL=l.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=!0,u.PURE_INCREMENTAL=!e.randomize,c.DEFAULT_UNIFORM_LEAF_NODE_SIZES=e.uniformNodeDimensions,e.step==`transformed`&&(u.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,u.ENFORCE_CONSTRAINTS=!1,u.APPLY_LAYOUT=!1),e.step==`enforced`&&(u.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,u.ENFORCE_CONSTRAINTS=!0,u.APPLY_LAYOUT=!1),e.step==`cose`&&(u.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,u.ENFORCE_CONSTRAINTS=!1,u.APPLY_LAYOUT=!0),e.step==`all`&&(e.randomize?u.TRANSFORM_ON_CONSTRAINT_HANDLING=!0:u.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,u.ENFORCE_CONSTRAINTS=!0,u.APPLY_LAYOUT=!0),e.fixedNodeConstraint||e.alignmentConstraint||e.relativePlacementConstraint?u.TREE_REDUCTION_ON_INCREMENTAL=!1:u.TREE_REDUCTION_ON_INCREMENTAL=!0;var w=new i,T=w.newGraphManager();return x(T.addRoot(),r.getTopMostNodes(f),w,e),S(w,T,p),C(w,e),w.runLayout(),_}}}),212:((e,t,n)=>{var r=function(){function e(e,t){for(var n=0;n0)if(f){var p=o.getTopMostNodes(t.eles.nodes());if(l=o.connectComponents(n,t.eles,p),l.forEach(function(e){var t=e.boundingBox();u.push({x:t.x1+t.w/2,y:t.y1+t.h/2})}),t.randomize&&l.forEach(function(e){t.eles=e,i.push(s(t))}),t.quality=="default"||t.quality==`proof`){var m=n.collection();if(t.tile){var h=new Map,g=[],_=[],v=0,y={nodeIndexes:h,xCoords:g,yCoords:_},b=[];if(l.forEach(function(e,t){e.edges().length==0&&(e.nodes().forEach(function(t,n){m.merge(e.nodes()[n]),t.isParent()||(y.nodeIndexes.set(e.nodes()[n].id(),v++),y.xCoords.push(e.nodes()[0].position().x),y.yCoords.push(e.nodes()[0].position().y))}),b.push(t))}),m.length>1){var x=m.boundingBox();u.push({x:x.x1+x.w/2,y:x.y1+x.h/2}),l.push(m),i.push(y);for(var S=b.length-1;S>=0;S--)l.splice(b[S],1),i.splice(b[S],1),u.splice(b[S],1)}}l.forEach(function(e,n){t.eles=e,a.push(c(t,i[n])),o.relocateComponent(u[n],a[n],t)})}else l.forEach(function(e,n){o.relocateComponent(u[n],i[n],t)});var C=new Set;if(l.length>1){var w=[],T=r.filter(function(e){return e.css(`display`)==`none`});l.forEach(function(e,n){var r=void 0;if(t.quality==`draft`&&(r=i[n].nodeIndexes),e.nodes().not(T).length>0){var s={};s.edges=[],s.nodes=[];var c=void 0;e.nodes().not(T).forEach(function(e){if(t.quality==`draft`)if(!e.isParent())c=r.get(e.id()),s.nodes.push({x:i[n].xCoords[c]-e.boundingbox().w/2,y:i[n].yCoords[c]-e.boundingbox().h/2,width:e.boundingbox().w,height:e.boundingbox().h});else{var l=o.calcBoundingBox(e,i[n].xCoords,i[n].yCoords,r);s.nodes.push({x:l.topLeftX,y:l.topLeftY,width:l.width,height:l.height})}else a[n][e.id()]&&s.nodes.push({x:a[n][e.id()].getLeft(),y:a[n][e.id()].getTop(),width:a[n][e.id()].getWidth(),height:a[n][e.id()].getHeight()})}),e.edges().forEach(function(e){var c=e.source(),l=e.target();if(c.css(`display`)!=`none`&&l.css(`display`)!=`none`)if(t.quality==`draft`){var u=r.get(c.id()),d=r.get(l.id()),f=[],p=[];if(c.isParent()){var m=o.calcBoundingBox(c,i[n].xCoords,i[n].yCoords,r);f.push(m.topLeftX+m.width/2),f.push(m.topLeftY+m.height/2)}else f.push(i[n].xCoords[u]),f.push(i[n].yCoords[u]);if(l.isParent()){var h=o.calcBoundingBox(l,i[n].xCoords,i[n].yCoords,r);p.push(h.topLeftX+h.width/2),p.push(h.topLeftY+h.height/2)}else p.push(i[n].xCoords[d]),p.push(i[n].yCoords[d]);s.edges.push({startX:f[0],startY:f[1],endX:p[0],endY:p[1]})}else a[n][c.id()]&&a[n][l.id()]&&s.edges.push({startX:a[n][c.id()].getCenterX(),startY:a[n][c.id()].getCenterY(),endX:a[n][l.id()].getCenterX(),endY:a[n][l.id()].getCenterY()})}),s.nodes.length>0&&(w.push(s),C.add(n))}});var E=d.packComponents(w,t.randomize).shifts;if(t.quality==`draft`)i.forEach(function(e,t){var n=e.xCoords.map(function(e){return e+E[t].dx}),r=e.yCoords.map(function(e){return e+E[t].dy});e.xCoords=n,e.yCoords=r});else{var D=0;C.forEach(function(e){Object.keys(a[e]).forEach(function(t){var n=a[e][t];n.setCenter(n.getCenterX()+E[D].dx,n.getCenterY()+E[D].dy)}),D++})}}}else{var O=t.eles.boundingBox();if(u.push({x:O.x1+O.w/2,y:O.y1+O.h/2}),t.randomize){var k=s(t);i.push(k)}t.quality=="default"||t.quality==`proof`?(a.push(c(t,i[0])),o.relocateComponent(u[0],a[0],t)):o.relocateComponent(u[0],i[0],t)}var A=function(e,n){if(t.quality=="default"||t.quality==`proof`){typeof e==`number`&&(e=n);var r=void 0,o=void 0,s=e.data(`id`);return a.forEach(function(e){s in e&&(r={x:e[s].getRect().getCenterX(),y:e[s].getRect().getCenterY()},o=e[s])}),t.nodeDimensionsIncludeLabels&&(o.labelWidth&&(o.labelPosHorizontal==`left`?r.x+=o.labelWidth/2:o.labelPosHorizontal==`right`&&(r.x-=o.labelWidth/2)),o.labelHeight&&(o.labelPosVertical==`top`?r.y+=o.labelHeight/2:o.labelPosVertical==`bottom`&&(r.y-=o.labelHeight/2))),r??={x:e.position(`x`),y:e.position(`y`)},{x:r.x,y:r.y}}else{var c=void 0;return i.forEach(function(t){var n=t.nodeIndexes.get(e.id());n!=null&&(c={x:t.xCoords[n],y:t.yCoords[n]})}),c??={x:e.position(`x`),y:e.position(`y`)},{x:c.x,y:c.y}}};if(t.quality=="default"||t.quality==`proof`||t.randomize){var j=o.calcParentsWithoutChildren(n,r),M=r.filter(function(e){return e.css(`display`)==`none`});t.eles=r.not(M),r.nodes().not(`:parent`).not(M).layoutPositions(e,t,A),j.length>0&&j.forEach(function(e){e.position(A(e))})}else console.log(`If randomize option is set to false, then quality option must be 'default' or 'proof'.`)}}]),e}()}),657:((e,t,n)=>{var r=n(548),i=n(140).layoutBase.Matrix,a=n(140).layoutBase.SVD;e.exports={spectralLayout:function(e){var t=e.cy,n=e.eles,o=n.nodes(),s=n.nodes(`:parent`),c=new Map,l=new Map,u=new Map,d=[],f=[],p=[],m=[],h=[],g=[],_=[],v=[],y=void 0,b=1e8,x=1e-9,S=e.piTol,C=e.samplingType,w=e.nodeSeparation,T=void 0,E=function(){for(var e=0,t=0,n=!1;t=i;){o=r[i++];for(var m=d[o],_=0;_u&&(u=h[x],f=x)}return f},O=function(e){var t=void 0;if(e){t=Math.floor(Math.random()*y);for(var n=0;n=1)break;u=l}for(var h=0;h=1)break;u=l}for(var b=0;b0&&(r.isParent()?d[t].push(u.get(r.id())):d[t].push(r.id()))})});var B=function(e){var n=l.get(e),r=void 0;c.get(e).forEach(function(i){r=t.getElementById(i).isParent()?u.get(i):i,d[n].push(r),d[l.get(r)].push(e)})},V=!0,ee=!1,te=void 0;try{for(var H=c.keys()[Symbol.iterator](),ne;!(V=(ne=H.next()).done);V=!0){var re=ne.value;B(re)}}catch(e){ee=!0,te=e}finally{try{!V&&H.return&&H.return()}finally{if(ee)throw te}}y=l.size;var U=void 0;if(y>2){T=y{var r=n(212),i=function(e){e&&e(`layout`,`fcose`,r)};typeof cytoscape<`u`&&i(cytoscape),e.exports=i}),140:(t=>{t.exports=e})},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}return r(579)})()})}))(),1),A={L:`left`,R:`right`,T:`top`,B:`bottom`},j={L:n(e=>`${e},${e/2} 0,${e} 0,0`,`L`),R:n(e=>`0,${e/2} ${e},0 ${e},${e}`,`R`),T:n(e=>`0,0 ${e},0 ${e/2},${e}`,`T`),B:n(e=>`${e/2},0 ${e},${e} 0,${e}`,`B`)},M={L:n((e,t)=>e-t+2,`L`),R:n((e,t)=>e-2,`R`),T:n((e,t)=>e-t+2,`T`),B:n((e,t)=>e-2,`B`)},N=n(function(e){return F(e)?e===`L`?`R`:`L`:e===`T`?`B`:`T`},`getOppositeArchitectureDirection`),P=n(function(e){let t=e;return t===`L`||t===`R`||t===`T`||t===`B`},`isArchitectureDirection`),F=n(function(e){let t=e;return t===`L`||t===`R`},`isArchitectureDirectionX`),I=n(function(e){let t=e;return t===`T`||t===`B`},`isArchitectureDirectionY`),L=n(function(e,t){let n=F(e)&&I(t),r=I(e)&&F(t);return n||r},`isArchitectureDirectionXY`),R=n(function(e){let t=e[0],n=e[1],r=F(t)&&I(n),i=I(t)&&F(n);return r||i},`isArchitecturePairXY`),z=n(function(e){return e!==`LL`&&e!==`RR`&&e!==`TT`&&e!==`BB`},`isValidArchitectureDirectionPair`),B=n(function(e,t){let n=`${e}${t}`;return z(n)?n:void 0},`getArchitectureDirectionPair`),V=n(function([e,t],n){let r=n[0],i=n[1];return F(r)?I(i)?[e+(r===`L`?-1:1),t+(i===`T`?1:-1)]:[e+(r===`L`?-1:1),t]:F(i)?[e+(i===`L`?1:-1),t+(r===`T`?1:-1)]:[e,t+(r===`T`?1:-1)]},`shiftPositionByArchitectureDirectionPair`),ee=n(function(e){return e===`LT`||e===`TL`?[1,1]:e===`BL`||e===`LB`?[1,-1]:e===`BR`||e===`RB`?[-1,-1]:[-1,1]},`getArchitectureDirectionXYFactors`),te=n(function(e,t){return L(e,t)?`bend`:F(e)?`horizontal`:`vertical`},`getArchitectureDirectionAlignment`),H=n(function(e){return e.type===`service`},`isArchitectureService`),ne=n(function(e){return e.type===`junction`},`isArchitectureJunction`),re=n(e=>e.data(),`edgeData`),U=n(e=>e.data(),`nodeData`),W=d.architecture,G=class{constructor(){this.nodes={},this.groups={},this.edges=[],this.layoutHints=[],this.registeredIds={},this.elements={},this.diagramId=``,this.setAccTitle=c,this.getAccTitle=h,this.setDiagramTitle=s,this.getDiagramTitle=p,this.getAccDescription=f,this.setAccDescription=a,this.clear()}static{n(this,`ArchitectureDB`)}setDiagramId(e){this.diagramId=e}getDiagramId(){return this.diagramId}clear(){this.nodes={},this.groups={},this.edges=[],this.layoutHints=[],this.registeredIds={},this.dataStructures=void 0,this.elements={},this.diagramId=``,l()}addService({id:e,icon:t,in:n,title:r,iconText:i}){if(this.registeredIds[e]!==void 0)throw Error(`The service id [${e}] is already in use by another ${this.registeredIds[e]}`);if(n!==void 0){if(e===n)throw Error(`The service [${e}] cannot be placed within itself`);if(this.registeredIds[n]===void 0)throw Error(`The service [${e}]'s parent does not exist. Please make sure the parent is created before this service`);if(this.registeredIds[n]===`node`)throw Error(`The service [${e}]'s parent is not a group`)}this.registeredIds[e]=`node`,this.nodes[e]={id:e,type:`service`,icon:t,iconText:i,title:r,edges:[],in:n}}getServices(){return Object.values(this.nodes).filter(H)}addJunction({id:e,in:t}){if(this.registeredIds[e]!==void 0)throw Error(`The junction id [${e}] is already in use by another ${this.registeredIds[e]}`);if(t!==void 0){if(e===t)throw Error(`The junction [${e}] cannot be placed within itself`);if(this.registeredIds[t]===void 0)throw Error(`The junction [${e}]'s parent does not exist. Please make sure the parent is created before this junction`);if(this.registeredIds[t]===`node`)throw Error(`The junction [${e}]'s parent is not a group`)}this.registeredIds[e]=`node`,this.nodes[e]={id:e,type:`junction`,edges:[],in:t}}getJunctions(){return Object.values(this.nodes).filter(ne)}getNodes(){return Object.values(this.nodes)}getNode(e){return this.nodes[e]??null}addGroup({id:e,icon:t,in:n,title:r}){if(this.registeredIds?.[e]!==void 0)throw Error(`The group id [${e}] is already in use by another ${this.registeredIds[e]}`);if(n!==void 0){if(e===n)throw Error(`The group [${e}] cannot be placed within itself`);if(this.registeredIds?.[n]===void 0)throw Error(`The group [${e}]'s parent does not exist. Please make sure the parent is created before this group`);if(this.registeredIds?.[n]===`node`)throw Error(`The group [${e}]'s parent is not a group`)}this.registeredIds[e]=`group`,this.groups[e]={id:e,icon:t,title:r,in:n}}getGroups(){return Object.values(this.groups)}addEdge({lhsId:e,rhsId:t,lhsDir:n,rhsDir:r,lhsInto:i,rhsInto:a,lhsGroup:o,rhsGroup:s,title:c}){if(!P(n))throw Error(`Invalid direction given for left hand side of edge ${e}--${t}. Expected (L,R,T,B) got ${String(n)}`);if(!P(r))throw Error(`Invalid direction given for right hand side of edge ${e}--${t}. Expected (L,R,T,B) got ${String(r)}`);if(this.nodes[e]===void 0&&this.groups[e]===void 0)throw Error(`The left-hand id [${e}] does not yet exist. Please create the service/group before declaring an edge to it.`);if(this.nodes[t]===void 0&&this.groups[t]===void 0)throw Error(`The right-hand id [${t}] does not yet exist. Please create the service/group before declaring an edge to it.`);let l=this.nodes[e].in,u=this.nodes[t].in;if(o&&l&&u&&l==u)throw Error(`The left-hand id [${e}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);if(s&&l&&u&&l==u)throw Error(`The right-hand id [${t}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);let d={lhsId:e,lhsDir:n,lhsInto:i,lhsGroup:o,rhsId:t,rhsDir:r,rhsInto:a,rhsGroup:s,title:c};this.edges.push(d),this.nodes[e]&&this.nodes[t]&&(this.nodes[e].edges.push(this.edges[this.edges.length-1]),this.nodes[t].edges.push(this.edges[this.edges.length-1]))}getEdges(){return this.edges}addLayoutHint(e){if(e.members.length<2)throw Error(`An align directive requires at least two members; got ${e.members.length}`);let t=new Set;e.members.forEach(n=>{if(this.registeredIds[n]!==`node`)throw Error(`align ${e.direction} references [${n}], which is not a service or junction`);if(t.has(n))throw Error(`align ${e.direction} lists [${n}] more than once`);t.add(n)}),this.layoutHints.push(e)}getLayoutHints(){return this.layoutHints}getDataStructures(){if(this.dataStructures===void 0){let e={},t=Object.entries(this.nodes).reduce((t,[n,r])=>(t[n]=r.edges.reduce((t,r)=>{let i=this.getNode(r.lhsId)?.in,a=this.getNode(r.rhsId)?.in;if(i&&a&&i!==a){let t=te(r.lhsDir,r.rhsDir);t!==`bend`&&(e[i]??={},e[i][a]=t,e[a]??={},e[a][i]=t)}if(r.lhsId===n){let e=B(r.lhsDir,r.rhsDir);e&&(t[e]=r.rhsId)}else{let e=B(r.rhsDir,r.lhsDir);e&&(t[e]=r.lhsId)}return t},{}),t),{}),r=Object.keys(t)[0],i={[r]:1},a=Object.keys(t).reduce((e,t)=>t===r?e:{...e,[t]:1},{}),o=n(e=>{let n={[e]:[0,0]},r=[e];for(;r.length>0;){let e=r.shift();if(e){i[e]=1,delete a[e];let o=t[e],[s,c]=n[e];Object.entries(o).forEach(([e,t])=>{i[t]||(n[t]=V([s,c],e),r.push(t))})}}return n},`BFS`),s=[o(r)];for(;Object.keys(a).length>0;)s.push(o(Object.keys(a)[0]));this.dataStructures={adjList:t,spatialMaps:s,groupAlignments:e}}return this.dataStructures}setElementForId(e,t){this.elements[e]=t}getElementById(e){return this.elements[e]}getConfig(){return v({...W,...u().architecture})}getConfigField(e){return this.getConfig()[e]}},ie=n((e,t)=>{b(e,t),e.groups.map(e=>t.addGroup(e)),e.services.map(e=>t.addService({...e,type:`service`})),e.junctions.map(e=>t.addJunction({...e,type:`junction`})),e.edges.map(e=>t.addEdge(e)),e.alignments?.map(e=>t.addLayoutHint({direction:e.direction,members:[...e.members]}))},`populateDb`),K={parser:{yy:void 0},parse:n(async e=>{let t=await x(`architecture`,e);r.debug(t);let n=K.parser?.yy;if(!(n instanceof G))throw Error(`parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);ie(t,n)},`parse`)},q=n(e=>` +import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as r,p as i}from"./src-UMNXGZaF.js";import{H as a,J as o,K as s,U as c,a as l,b as u,f as d,v as f,w as p,x as m,y as h,z as g}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{c as _,i as v}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as y}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as b}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as x}from"./mermaid-parser.core-Z7xZAZRH.js";import{i as S,r as C,t as w}from"./chunk-HOUHSVGY-iJuv90UH.js";import{n as T}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{t as E}from"./cytoscape.esm-CQFVGiJu.js";var D=t(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.layoutBase=r():n.layoutBase=r()})(e,function(){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=28)})([(function(e,t,n){function r(){}r.QUALITY=1,r.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,r.DEFAULT_INCREMENTAL=!1,r.DEFAULT_ANIMATION_ON_LAYOUT=!0,r.DEFAULT_ANIMATION_DURING_LAYOUT=!1,r.DEFAULT_ANIMATION_PERIOD=50,r.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,r.DEFAULT_GRAPH_MARGIN=15,r.NODE_DIMENSIONS_INCLUDE_LABELS=!1,r.SIMPLE_NODE_SIZE=40,r.SIMPLE_NODE_HALF_SIZE=r.SIMPLE_NODE_SIZE/2,r.EMPTY_COMPOUND_NODE_SIZE=40,r.MIN_EDGE_LENGTH=1,r.WORLD_BOUNDARY=1e6,r.INITIAL_WORLD_BOUNDARY=r.WORLD_BOUNDARY/1e3,r.WORLD_CENTER_X=1200,r.WORLD_CENTER_Y=900,e.exports=r}),(function(e,t,n){var r=n(2),i=n(8),a=n(9);function o(e,t,n){r.call(this,n),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=n,this.bendpoints=[],this.source=e,this.target=t}for(var s in o.prototype=Object.create(r.prototype),r)o[s]=r[s];o.prototype.getSource=function(){return this.source},o.prototype.getTarget=function(){return this.target},o.prototype.isInterGraph=function(){return this.isInterGraph},o.prototype.getLength=function(){return this.length},o.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},o.prototype.getBendpoints=function(){return this.bendpoints},o.prototype.getLca=function(){return this.lca},o.prototype.getSourceInLca=function(){return this.sourceInLca},o.prototype.getTargetInLca=function(){return this.targetInLca},o.prototype.getOtherEnd=function(e){if(this.source===e)return this.target;if(this.target===e)return this.source;throw`Node is not incident with this edge`},o.prototype.getOtherEndInGraph=function(e,t){for(var n=this.getOtherEnd(e),r=t.getGraphManager().getRoot();;){if(n.getOwner()==t)return n;if(n.getOwner()==r)break;n=n.getOwner().getParent()}return null},o.prototype.updateLength=function(){var e=[,,,,];this.isOverlapingSourceAndTarget=i.getIntersection(this.target.getRect(),this.source.getRect(),e),this.isOverlapingSourceAndTarget||(this.lengthX=e[0]-e[2],this.lengthY=e[1]-e[3],Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},o.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},e.exports=o}),(function(e,t,n){function r(e){this.vGraphObject=e}e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(13),o=n(0),s=n(16),c=n(5);function l(e,t,n,o){n==null&&o==null&&(o=t),r.call(this,o),e.graphManager!=null&&(e=e.graphManager),this.estimatedSize=i.MIN_VALUE,this.inclusionTreeDepth=i.MAX_VALUE,this.vGraphObject=o,this.edges=[],this.graphManager=e,n!=null&&t!=null?this.rect=new a(t.x,t.y,n.width,n.height):this.rect=new a}for(var u in l.prototype=Object.create(r.prototype),r)l[u]=r[u];l.prototype.getEdges=function(){return this.edges},l.prototype.getChild=function(){return this.child},l.prototype.getOwner=function(){return this.owner},l.prototype.getWidth=function(){return this.rect.width},l.prototype.setWidth=function(e){this.rect.width=e},l.prototype.getHeight=function(){return this.rect.height},l.prototype.setHeight=function(e){this.rect.height=e},l.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},l.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},l.prototype.getCenter=function(){return new c(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},l.prototype.getLocation=function(){return new c(this.rect.x,this.rect.y)},l.prototype.getRect=function(){return this.rect},l.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},l.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},l.prototype.setRect=function(e,t){this.rect.x=e.x,this.rect.y=e.y,this.rect.width=t.width,this.rect.height=t.height},l.prototype.setCenter=function(e,t){this.rect.x=e-this.rect.width/2,this.rect.y=t-this.rect.height/2},l.prototype.setLocation=function(e,t){this.rect.x=e,this.rect.y=t},l.prototype.moveBy=function(e,t){this.rect.x+=e,this.rect.y+=t},l.prototype.getEdgeListToNode=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(r.target==e){if(r.source!=n)throw`Incorrect edge source!`;t.push(r)}}),t},l.prototype.getEdgesBetween=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(!(r.source==n||r.target==n))throw`Incorrect edge source and/or target`;(r.target==e||r.source==e)&&t.push(r)}),t},l.prototype.getNeighborsList=function(){var e=new Set,t=this;return t.edges.forEach(function(n){if(n.source==t)e.add(n.target);else{if(n.target!=t)throw`Incorrect incidency!`;e.add(n.source)}}),e},l.prototype.withChildren=function(){var e=new Set,t,n;if(e.add(this),this.child!=null)for(var r=this.child.getNodes(),i=0;it?(this.rect.x-=(this.labelWidth-t)/2,this.setWidth(this.labelWidth)):this.labelPosHorizontal==`right`&&this.setWidth(t+this.labelWidth)),this.labelHeight&&(this.labelPosVertical==`top`?(this.rect.y-=this.labelHeight,this.setHeight(n+this.labelHeight)):this.labelPosVertical==`center`&&this.labelHeight>n?(this.rect.y-=(this.labelHeight-n)/2,this.setHeight(this.labelHeight)):this.labelPosVertical==`bottom`&&this.setHeight(n+this.labelHeight))}}},l.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==i.MAX_VALUE)throw`assert failed`;return this.inclusionTreeDepth},l.prototype.transform=function(e){var t=this.rect.x;t>o.WORLD_BOUNDARY?t=o.WORLD_BOUNDARY:t<-o.WORLD_BOUNDARY&&(t=-o.WORLD_BOUNDARY);var n=this.rect.y;n>o.WORLD_BOUNDARY?n=o.WORLD_BOUNDARY:n<-o.WORLD_BOUNDARY&&(n=-o.WORLD_BOUNDARY);var r=new c(t,n),i=e.inverseTransformPoint(r);this.setLocation(i.x,i.y)},l.prototype.getLeft=function(){return this.rect.x},l.prototype.getRight=function(){return this.rect.x+this.rect.width},l.prototype.getTop=function(){return this.rect.y},l.prototype.getBottom=function(){return this.rect.y+this.rect.height},l.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},e.exports=l}),(function(e,t,n){var r=n(0);function i(){}for(var a in r)i[a]=r[a];i.MAX_ITERATIONS=2500,i.DEFAULT_EDGE_LENGTH=50,i.DEFAULT_SPRING_STRENGTH=.45,i.DEFAULT_REPULSION_STRENGTH=4500,i.DEFAULT_GRAVITY_STRENGTH=.4,i.DEFAULT_COMPOUND_GRAVITY_STRENGTH=1,i.DEFAULT_GRAVITY_RANGE_FACTOR=3.8,i.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=1.5,i.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION=!0,i.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION=!0,i.DEFAULT_COOLING_FACTOR_INCREMENTAL=.3,i.COOLING_ADAPTATION_FACTOR=.33,i.ADAPTATION_LOWER_NODE_LIMIT=1e3,i.ADAPTATION_UPPER_NODE_LIMIT=5e3,i.MAX_NODE_DISPLACEMENT_INCREMENTAL=100,i.MAX_NODE_DISPLACEMENT=i.MAX_NODE_DISPLACEMENT_INCREMENTAL*3,i.MIN_REPULSION_DIST=i.DEFAULT_EDGE_LENGTH/10,i.CONVERGENCE_CHECK_PERIOD=100,i.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=.1,i.MIN_EDGE_LENGTH=1,i.GRID_CALCULATION_CHECK_PERIOD=10,e.exports=i}),(function(e,t,n){function r(e,t){e==null&&t==null?(this.x=0,this.y=0):(this.x=e,this.y=t)}r.prototype.getX=function(){return this.x},r.prototype.getY=function(){return this.y},r.prototype.setX=function(e){this.x=e},r.prototype.setY=function(e){this.y=e},r.prototype.getDifference=function(e){return new DimensionD(this.x-e.x,this.y-e.y)},r.prototype.getCopy=function(){return new r(this.x,this.y)},r.prototype.translate=function(e){return this.x+=e.width,this.y+=e.height,this},e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(0),o=n(7),s=n(3),c=n(1),l=n(13),u=n(12),d=n(11);function f(e,t,n){r.call(this,n),this.estimatedSize=i.MIN_VALUE,this.margin=a.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=e,t!=null&&t instanceof o?this.graphManager=t:t!=null&&t instanceof Layout&&(this.graphManager=t.graphManager)}for(var p in f.prototype=Object.create(r.prototype),r)f[p]=r[p];f.prototype.getNodes=function(){return this.nodes},f.prototype.getEdges=function(){return this.edges},f.prototype.getGraphManager=function(){return this.graphManager},f.prototype.getParent=function(){return this.parent},f.prototype.getLeft=function(){return this.left},f.prototype.getRight=function(){return this.right},f.prototype.getTop=function(){return this.top},f.prototype.getBottom=function(){return this.bottom},f.prototype.isConnected=function(){return this.isConnected},f.prototype.add=function(e,t,n){if(t==null&&n==null){var r=e;if(this.graphManager==null)throw`Graph has no graph mgr!`;if(this.getNodes().indexOf(r)>-1)throw`Node already in graph!`;return r.owner=this,this.getNodes().push(r),r}else{var i=e;if(!(this.getNodes().indexOf(t)>-1&&this.getNodes().indexOf(n)>-1))throw`Source or target not in graph!`;if(!(t.owner==n.owner&&t.owner==this))throw`Both owners must be this graph!`;return t.owner==n.owner?(i.source=t,i.target=n,i.isInterGraph=!1,this.getEdges().push(i),t.edges.push(i),n!=t&&n.edges.push(i),i):null}},f.prototype.remove=function(e){var t=e;if(e instanceof s){if(t==null)throw`Node is null!`;if(!(t.owner!=null&&t.owner==this))throw`Owner graph is invalid!`;if(this.graphManager==null)throw`Owner graph manager is invalid!`;for(var n=t.edges.slice(),r,i=n.length,a=0;a-1&&u>-1))throw`Source and/or target doesn't know this edge!`;r.source.edges.splice(l,1),r.target!=r.source&&r.target.edges.splice(u,1);var o=r.source.owner.getEdges().indexOf(r);if(o==-1)throw`Not in owner's edge list!`;r.source.owner.getEdges().splice(o,1)}},f.prototype.updateLeftTop=function(){for(var e=i.MAX_VALUE,t=i.MAX_VALUE,n,r,a,o=this.getNodes(),s=o.length,c=0;cn&&(e=n),t>r&&(t=r)}return e==i.MAX_VALUE?null:(a=o[0].getParent().paddingLeft==null?this.margin:o[0].getParent().paddingLeft,this.left=t-a,this.top=e-a,new u(this.left,this.top))},f.prototype.updateBounds=function(e){for(var t=i.MAX_VALUE,n=-i.MAX_VALUE,r=i.MAX_VALUE,a=-i.MAX_VALUE,o,s,c,u,d,f=this.nodes,p=f.length,m=0;mo&&(t=o),nc&&(r=c),ao&&(t=o),nc&&(r=c),a=this.nodes.length){var c=0;n.forEach(function(t){t.owner==e&&c++}),c==this.nodes.length&&(this.isConnected=!0)}},e.exports=f}),(function(e,t,n){var r,i=n(1);function a(e){r=n(6),this.layout=e,this.graphs=[],this.edges=[]}a.prototype.addRoot=function(){var e=this.layout.newGraph(),t=this.layout.newNode(null),n=this.add(e,t);return this.setRootGraph(n),this.rootGraph},a.prototype.add=function(e,t,n,r,i){if(n==null&&r==null&&i==null){if(e==null)throw`Graph is null!`;if(t==null)throw`Parent node is null!`;if(this.graphs.indexOf(e)>-1)throw`Graph already in this graph mgr!`;if(this.graphs.push(e),e.parent!=null)throw`Already has a parent!`;if(t.child!=null)throw`Already has a child!`;return e.parent=t,t.child=e,e}else{i=n,r=t,n=e;var a=r.getOwner(),o=i.getOwner();if(!(a!=null&&a.getGraphManager()==this))throw`Source not in this graph mgr!`;if(!(o!=null&&o.getGraphManager()==this))throw`Target not in this graph mgr!`;if(a==o)return n.isInterGraph=!1,a.add(n,r,i);if(n.isInterGraph=!0,n.source=r,n.target=i,this.edges.indexOf(n)>-1)throw`Edge already in inter-graph edge list!`;if(this.edges.push(n),!(n.source!=null&&n.target!=null))throw`Edge source and/or target is null!`;if(!(n.source.edges.indexOf(n)==-1&&n.target.edges.indexOf(n)==-1))throw`Edge already in source and/or target incidency list!`;return n.source.edges.push(n),n.target.edges.push(n),n}},a.prototype.remove=function(e){if(e instanceof r){var t=e;if(t.getGraphManager()!=this)throw`Graph not in this graph mgr`;if(!(t==this.rootGraph||t.parent!=null&&t.parent.graphManager==this))throw`Invalid parent node!`;var n=[];n=n.concat(t.getEdges());for(var a,o=n.length,s=0;s=t.getRight()?n[0]+=Math.min(t.getX()-e.getX(),e.getRight()-t.getRight()):t.getX()<=e.getX()&&t.getRight()>=e.getRight()&&(n[0]+=Math.min(e.getX()-t.getX(),t.getRight()-e.getRight())),e.getY()<=t.getY()&&e.getBottom()>=t.getBottom()?n[1]+=Math.min(t.getY()-e.getY(),e.getBottom()-t.getBottom()):t.getY()<=e.getY()&&t.getBottom()>=e.getBottom()&&(n[1]+=Math.min(e.getY()-t.getY(),t.getBottom()-e.getBottom()));var a=Math.abs((t.getCenterY()-e.getCenterY())/(t.getCenterX()-e.getCenterX()));t.getCenterY()===e.getCenterY()&&t.getCenterX()===e.getCenterX()&&(a=1);var o=a*n[0],s=n[1]/a;n[0]o)return n[0]=r,n[1]=c,n[2]=a,n[3]=y,!1;if(ia)return n[0]=s,n[1]=i,n[2]=_,n[3]=o,!1;if(ra?(n[0]=u,n[1]=d,C=!0):(n[0]=l,n[1]=c,C=!0):T===D&&(r>a?(n[0]=s,n[1]=c,C=!0):(n[0]=f,n[1]=d,C=!0)),-E===D?a>r?(n[2]=v,n[3]=y,w=!0):(n[2]=_,n[3]=g,w=!0):E===D&&(a>r?(n[2]=h,n[3]=g,w=!0):(n[2]=b,n[3]=y,w=!0)),C&&w)return!1;if(r>a?i>o?(O=this.getCardinalDirection(T,D,4),k=this.getCardinalDirection(E,D,2)):(O=this.getCardinalDirection(-T,D,3),k=this.getCardinalDirection(-E,D,1)):i>o?(O=this.getCardinalDirection(-T,D,1),k=this.getCardinalDirection(-E,D,3)):(O=this.getCardinalDirection(T,D,2),k=this.getCardinalDirection(E,D,4)),!C)switch(O){case 1:j=c,A=r+-m/D,n[0]=A,n[1]=j;break;case 2:A=f,j=i+p*D,n[0]=A,n[1]=j;break;case 3:j=d,A=r+m/D,n[0]=A,n[1]=j;break;case 4:A=u,j=i+-p*D,n[0]=A,n[1]=j;break}if(!w)switch(k){case 1:N=g,M=a+-S/D,n[2]=M,n[3]=N;break;case 2:M=b,N=o+x*D,n[2]=M,n[3]=N;break;case 3:N=y,M=a+S/D,n[2]=M,n[3]=N;break;case 4:M=v,N=o+-x*D,n[2]=M,n[3]=N;break}}return!1},i.getCardinalDirection=function(e,t,n){return e>t?n:1+n%4},i.getIntersection=function(e,t,n,i){if(i==null)return this.getIntersection2(e,t,n);var a=e.x,o=e.y,s=t.x,c=t.y,l=n.x,u=n.y,d=i.x,f=i.y,p=void 0,m=void 0,h=void 0,g=void 0,_=void 0,v=void 0,y=void 0,b=void 0,x=void 0;return h=c-o,_=a-s,y=s*o-a*c,g=f-u,v=l-d,b=d*u-l*f,x=h*v-g*_,x===0?null:(p=(_*b-v*y)/x,m=(g*y-h*b)/x,new r(p,m))},i.angleOfVector=function(e,t,n,r){var i=void 0;return e===n?i=r=0){var u=(-c+Math.sqrt(c*c-4*s*l))/(2*s),d=(-c-Math.sqrt(c*c-4*s*l))/(2*s);return u>=0&&u<=1?[u]:d>=0&&d<=1?[d]:null}else return null},i.HALF_PI=.5*Math.PI,i.ONE_AND_HALF_PI=1.5*Math.PI,i.TWO_PI=2*Math.PI,i.THREE_PI=3*Math.PI,e.exports=i}),(function(e,t,n){function r(){}r.sign=function(e){return e>0?1:e<0?-1:0},r.floor=function(e){return e<0?Math.ceil(e):Math.floor(e)},r.ceil=function(e){return e<0?Math.floor(e):Math.ceil(e)},e.exports=r}),(function(e,t,n){function r(){}r.MAX_VALUE=2147483647,r.MIN_VALUE=-2147483648,e.exports=r}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n0&&t;){for(s.push(l[0]);s.length>0&&t;){var u=s[0];s.splice(0,1),o.add(u);for(var d=u.getEdges(),a=0;a-1&&l.splice(h,1)}o=new Set,c=new Map}}return e},f.prototype.createDummyNodesForBendpoints=function(e){for(var t=[],n=e.source,r=this.graphManager.calcLowestCommonAncestor(e.source,e.target),i=0;i0){for(var i=this.edgeToDummyNodes.get(n),a=0;a=0&&t.splice(d,1),s.getNeighborsList().forEach(function(e){if(n.indexOf(e)<0){var t=r.get(e)-1;t==1&&l.push(e),r.set(e,t)}})}n=n.concat(l),(t.length==1||t.length==2)&&(i=!0,a=t[0])}return a},f.prototype.setGraphManager=function(e){this.graphManager=e},e.exports=f}),(function(e,t,n){function r(){}r.seed=1,r.x=0,r.nextDouble=function(){return r.x=Math.sin(r.seed++)*1e4,r.x-Math.floor(r.x)},e.exports=r}),(function(e,t,n){var r=n(5);function i(e,t){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}i.prototype.getWorldOrgX=function(){return this.lworldOrgX},i.prototype.setWorldOrgX=function(e){this.lworldOrgX=e},i.prototype.getWorldOrgY=function(){return this.lworldOrgY},i.prototype.setWorldOrgY=function(e){this.lworldOrgY=e},i.prototype.getWorldExtX=function(){return this.lworldExtX},i.prototype.setWorldExtX=function(e){this.lworldExtX=e},i.prototype.getWorldExtY=function(){return this.lworldExtY},i.prototype.setWorldExtY=function(e){this.lworldExtY=e},i.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},i.prototype.setDeviceOrgX=function(e){this.ldeviceOrgX=e},i.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},i.prototype.setDeviceOrgY=function(e){this.ldeviceOrgY=e},i.prototype.getDeviceExtX=function(){return this.ldeviceExtX},i.prototype.setDeviceExtX=function(e){this.ldeviceExtX=e},i.prototype.getDeviceExtY=function(){return this.ldeviceExtY},i.prototype.setDeviceExtY=function(e){this.ldeviceExtY=e},i.prototype.transformX=function(e){var t=0,n=this.lworldExtX;return n!=0&&(t=this.ldeviceOrgX+(e-this.lworldOrgX)*this.ldeviceExtX/n),t},i.prototype.transformY=function(e){var t=0,n=this.lworldExtY;return n!=0&&(t=this.ldeviceOrgY+(e-this.lworldOrgY)*this.ldeviceExtY/n),t},i.prototype.inverseTransformX=function(e){var t=0,n=this.ldeviceExtX;return n!=0&&(t=this.lworldOrgX+(e-this.ldeviceOrgX)*this.lworldExtX/n),t},i.prototype.inverseTransformY=function(e){var t=0,n=this.ldeviceExtY;return n!=0&&(t=this.lworldOrgY+(e-this.ldeviceOrgY)*this.lworldExtY/n),t},i.prototype.inverseTransformPoint=function(e){return new r(this.inverseTransformX(e.x),this.inverseTransformY(e.y))},e.exports=i}),(function(e,t,n){function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);ta.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*a.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-a.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT_INCREMENTAL):(e>a.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(a.COOLING_ADAPTATION_FACTOR,1-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*(1-a.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.displacementThresholdPerNode=3*a.DEFAULT_EDGE_LENGTH/100,this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},l.prototype.calcSpringForces=function(){for(var e=this.getAllEdges(),t,n=0;n0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n,r,i,o,s=this.getAllNodes(),c;if(this.useFRGridVariant)for(this.totalIterations%a.GRID_CALCULATION_CHECK_PERIOD==1&&e&&this.updateGrid(),c=new Set,n=0;nc||s>c)&&(e.gravitationForceX=-this.gravityConstant*i,e.gravitationForceY=-this.gravityConstant*a)):(c=t.getEstimatedSize()*this.compoundGravityRangeFactor,(o>c||s>c)&&(e.gravitationForceX=-this.gravityConstant*i*this.compoundGravityConstant,e.gravitationForceY=-this.gravityConstant*a*this.compoundGravityConstant))},l.prototype.isConverged=function(){var e,t=!1;return this.totalIterations>this.maxIterations/3&&(t=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),e=this.totalDisplacement=c.length||u>=c[0].length)){for(var d=0;de}}]),e}()}),(function(e,t,n){function r(){}r.svd=function(e){this.U=null,this.V=null,this.s=null,this.m=0,this.n=0,this.m=e.length,this.n=e[0].length;var t=Math.min(this.m,this.n);this.s=function(e){for(var t=[];e-->0;)t.push(0);return t}(Math.min(this.m+1,this.n)),this.U=function(e){return function e(t){if(t.length==0)return 0;for(var n=[],r=0;r0;)t.push(0);return t}(this.n),i=function(e){for(var t=[];e-->0;)t.push(0);return t}(this.m),a=!0,o=!0,s=Math.min(this.m-1,this.n),c=Math.max(0,Math.min(this.n-2,this.m)),l=0;l=0;k--)if(this.s[k]!==0){for(var A=k+1;A=0;L--){if(function(e,t){return e&&t}(L0;){var U=void 0,W=void 0;for(U=E-2;U>=-1&&U!==-1;U--)if(Math.abs(n[U])<=re+ne*(Math.abs(this.s[U])+Math.abs(this.s[U+1]))){n[U]=0;break}if(U===E-2)W=4;else{var G=void 0;for(G=E-1;G>=U&&G!==U;G--){var ie=(G===E?0:Math.abs(n[G]))+(G===U+1?0:Math.abs(n[G-1]));if(Math.abs(this.s[G])<=re+ne*ie){this.s[G]=0;break}}G===U?W=3:G===E-1?W=1:(W=2,U=G)}switch(U++,W){case 1:var K=n[E-2];n[E-2]=0;for(var q=E-2;q>=U;q--){var J=r.hypot(this.s[q],K),Y=this.s[q]/J,X=K/J;if(this.s[q]=J,q!==U&&(K=-X*n[q-1],n[q-1]=Y*n[q-1]),o)for(var Z=0;Z=this.s[U+1]);){var De=this.s[U];if(this.s[U]=this.s[U+1],this.s[U+1]=De,o&&UMath.abs(t)?(n=t/e,n=Math.abs(e)*Math.sqrt(1+n*n)):t==0?n=0:(n=e/t,n=Math.abs(t)*Math.sqrt(1+n*n)),n},e.exports=r}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;i(this,e),this.sequence1=t,this.sequence2=n,this.match_score=r,this.mismatch_penalty=a,this.gap_penalty=o,this.iMax=t.length+1,this.jMax=n.length+1,this.grid=Array(this.iMax);for(var s=0;s=0;n--){var r=this.listeners[n];r.event===e&&r.callback===t&&this.listeners.splice(n,1)}},i.emit=function(e,t){for(var n=0;n{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(D()):typeof define==`function`&&define.amd?define([`layout-base`],r):typeof e==`object`?e.coseBase=r(D()):n.coseBase=r(n.layoutBase)})(e,function(e){return(()=>{var t={45:((e,t,n)=>{var r={};r.layoutBase=n(551),r.CoSEConstants=n(806),r.CoSEEdge=n(767),r.CoSEGraph=n(880),r.CoSEGraphManager=n(578),r.CoSELayout=n(765),r.CoSENode=n(991),r.ConstraintHandler=n(902),e.exports=r}),806:((e,t,n)=>{var r=n(551).FDLayoutConstants;function i(){}for(var a in r)i[a]=r[a];i.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,i.DEFAULT_RADIAL_SEPARATION=r.DEFAULT_EDGE_LENGTH,i.DEFAULT_COMPONENT_SEPERATION=60,i.TILE=!0,i.TILING_PADDING_VERTICAL=10,i.TILING_PADDING_HORIZONTAL=10,i.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,i.ENFORCE_CONSTRAINTS=!0,i.APPLY_LAYOUT=!0,i.RELAX_MOVEMENT_ON_CONSTRAINTS=!0,i.TREE_REDUCTION_ON_INCREMENTAL=!0,i.PURE_INCREMENTAL=i.DEFAULT_INCREMENTAL,e.exports=i}),767:((e,t,n)=>{var r=n(551).FDLayoutEdge;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),880:((e,t,n)=>{var r=n(551).LGraph;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),578:((e,t,n)=>{var r=n(551).LGraphManager;function i(e){r.call(this,e)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),765:((e,t,n)=>{var r=n(551).FDLayout,i=n(578),a=n(880),o=n(991),s=n(767),c=n(806),l=n(902),u=n(551).FDLayoutConstants,d=n(551).LayoutConstants,f=n(551).Point,p=n(551).PointD,m=n(551).DimensionD,h=n(551).Layout,g=n(551).Integer,_=n(551).IGeometry,v=n(551).LGraph,y=n(551).Transform,b=n(551).LinkedList;function x(){r.call(this),this.toBeTiled={},this.constraints={}}for(var S in x.prototype=Object.create(r.prototype),r)x[S]=r[S];x.prototype.newGraphManager=function(){var e=new i(this);return this.graphManager=e,e},x.prototype.newGraph=function(e){return new a(null,this.graphManager,e)},x.prototype.newNode=function(e){return new o(this.graphManager,e)},x.prototype.newEdge=function(e){return new s(null,null,e)},x.prototype.initParameters=function(){r.prototype.initParameters.call(this,arguments),this.isSubLayout||(c.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=c.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=c.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.gravityConstant=u.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=u.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=u.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=u.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1)},x.prototype.initSpringEmbedder=function(){r.prototype.initSpringEmbedder.call(this),this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/u.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=.04,this.coolingAdjuster=1},x.prototype.layout=function(){return d.DEFAULT_CREATE_BENDS_AS_NEEDED&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},x.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),!this.incremental){var e=this.getFlatForest();if(e.length>0)this.positionNodesRadially(e);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n),this.positionNodesRandomly()}}else if(c.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n)}return Object.keys(this.constraints).length>0&&(l.handleConstraints(this),this.initConstraintVariables()),this.initSpringEmbedder(),c.APPLY_LAYOUT&&this.runSpringEmbedder(),!0},x.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%u.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-this.coolingCycle**+(Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),t=this.nodesWithGravity.filter(function(t){return e.has(t)});this.graphManager.setAllNodesToApplyGravitation(t),this.graphManager.updateBounds(),this.updateGrid(),c.PURE_INCREMENTAL?this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL/2:this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),c.PURE_INCREMENTAL?this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL/2*((100-this.afterGrowthIterations)/100):this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var n=!this.isTreeGrowing&&!this.isGrowthFinished,r=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(n,r),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},x.prototype.getPositionsData=function(){for(var e=this.graphManager.getAllNodes(),t={},n=0;n0&&this.updateDisplacements();for(var n=0;n0&&(r.fixedNodeWeight=a)}}if(this.constraints.relativePlacementConstraint){var o=new Map,s=new Map;if(this.dummyToNodeForVerticalAlignment=new Map,this.dummyToNodeForHorizontalAlignment=new Map,this.fixedNodesOnHorizontal=new Set,this.fixedNodesOnVertical=new Set,this.fixedNodeSet.forEach(function(t){e.fixedNodesOnHorizontal.add(t),e.fixedNodesOnVertical.add(t)}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var l=this.constraints.alignmentConstraint.vertical,n=0;n=2*e.length/3;r--)t=Math.floor(Math.random()*(r+1)),n=e[r],e[r]=e[t],e[t]=n;return e},this.nodesInRelativeHorizontal=[],this.nodesInRelativeVertical=[],this.nodeToRelativeConstraintMapHorizontal=new Map,this.nodeToRelativeConstraintMapVertical=new Map,this.nodeToTempPositionMapHorizontal=new Map,this.nodeToTempPositionMapVertical=new Map,this.constraints.relativePlacementConstraint.forEach(function(t){if(t.left){var n=o.has(t.left)?o.get(t.left):t.left,r=o.has(t.right)?o.get(t.right):t.right;e.nodesInRelativeHorizontal.includes(n)||(e.nodesInRelativeHorizontal.push(n),e.nodeToRelativeConstraintMapHorizontal.set(n,[]),e.dummyToNodeForVerticalAlignment.has(n)?e.nodeToTempPositionMapHorizontal.set(n,e.idToNodeMap.get(e.dummyToNodeForVerticalAlignment.get(n)[0]).getCenterX()):e.nodeToTempPositionMapHorizontal.set(n,e.idToNodeMap.get(n).getCenterX())),e.nodesInRelativeHorizontal.includes(r)||(e.nodesInRelativeHorizontal.push(r),e.nodeToRelativeConstraintMapHorizontal.set(r,[]),e.dummyToNodeForVerticalAlignment.has(r)?e.nodeToTempPositionMapHorizontal.set(r,e.idToNodeMap.get(e.dummyToNodeForVerticalAlignment.get(r)[0]).getCenterX()):e.nodeToTempPositionMapHorizontal.set(r,e.idToNodeMap.get(r).getCenterX())),e.nodeToRelativeConstraintMapHorizontal.get(n).push({right:r,gap:t.gap}),e.nodeToRelativeConstraintMapHorizontal.get(r).push({left:n,gap:t.gap})}else{var i=s.has(t.top)?s.get(t.top):t.top,a=s.has(t.bottom)?s.get(t.bottom):t.bottom;e.nodesInRelativeVertical.includes(i)||(e.nodesInRelativeVertical.push(i),e.nodeToRelativeConstraintMapVertical.set(i,[]),e.dummyToNodeForHorizontalAlignment.has(i)?e.nodeToTempPositionMapVertical.set(i,e.idToNodeMap.get(e.dummyToNodeForHorizontalAlignment.get(i)[0]).getCenterY()):e.nodeToTempPositionMapVertical.set(i,e.idToNodeMap.get(i).getCenterY())),e.nodesInRelativeVertical.includes(a)||(e.nodesInRelativeVertical.push(a),e.nodeToRelativeConstraintMapVertical.set(a,[]),e.dummyToNodeForHorizontalAlignment.has(a)?e.nodeToTempPositionMapVertical.set(a,e.idToNodeMap.get(e.dummyToNodeForHorizontalAlignment.get(a)[0]).getCenterY()):e.nodeToTempPositionMapVertical.set(a,e.idToNodeMap.get(a).getCenterY())),e.nodeToRelativeConstraintMapVertical.get(i).push({bottom:a,gap:t.gap}),e.nodeToRelativeConstraintMapVertical.get(a).push({top:i,gap:t.gap})}});else{var d=new Map,f=new Map;this.constraints.relativePlacementConstraint.forEach(function(e){if(e.left){var t=o.has(e.left)?o.get(e.left):e.left,n=o.has(e.right)?o.get(e.right):e.right;d.has(t)?d.get(t).push(n):d.set(t,[n]),d.has(n)?d.get(n).push(t):d.set(n,[t])}else{var r=s.has(e.top)?s.get(e.top):e.top,i=s.has(e.bottom)?s.get(e.bottom):e.bottom;f.has(r)?f.get(r).push(i):f.set(r,[i]),f.has(i)?f.get(i).push(r):f.set(i,[r])}});var p=function(e,t){var n=[],r=[],i=new b,a=new Set,o=0;return e.forEach(function(s,c){if(!a.has(c)){n[o]=[],r[o]=!1;var l=c;for(i.push(l),a.add(l),n[o].push(l);i.length!=0;)l=i.shift(),t.has(l)&&(r[o]=!0),e.get(l).forEach(function(e){a.has(e)||(i.push(e),a.add(e),n[o].push(e))});o++}}),{components:n,isFixed:r}},m=p(d,e.fixedNodesOnHorizontal);this.componentsOnHorizontal=m.components,this.fixedComponentsOnHorizontal=m.isFixed;var h=p(f,e.fixedNodesOnVertical);this.componentsOnVertical=h.components,this.fixedComponentsOnVertical=h.isFixed}}},x.prototype.updateDisplacements=function(){var e=this;if(this.constraints.fixedNodeConstraint&&this.constraints.fixedNodeConstraint.forEach(function(t){var n=e.idToNodeMap.get(t.nodeId);n.displacementX=0,n.displacementY=0}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var t=this.constraints.alignmentConstraint.vertical,n=0;n1){var s;for(s=0;sr&&(r=Math.floor(o.y)),a=Math.floor(o.x+c.DEFAULT_COMPONENT_SEPERATION)}this.transform(new p(d.WORLD_CENTER_X-o.x/2,d.WORLD_CENTER_Y-o.y/2))},x.radialLayout=function(e,t,n){var r=Math.max(this.maxDiagonalInTree(e),c.DEFAULT_RADIAL_SEPARATION);x.branchRadialLayout(t,null,0,359,0,r);var i=v.calculateBounds(e),a=new y;a.setDeviceOrgX(i.getMinX()),a.setDeviceOrgY(i.getMinY()),a.setWorldOrgX(n.x),a.setWorldOrgY(n.y);for(var o=0;o1;){var g=h[0];h.splice(0,1);var v=u.indexOf(g);v>=0&&u.splice(v,1),p--,d--}m=t==null?0:(u.indexOf(h[0])+1)%p;for(var y=Math.abs(r-n)/d,b=m;f!=d;b=++b%p){var S=u[b].getOtherEnd(e);if(S!=t){var C=(n+f*y)%360,w=(C+y)%360;x.branchRadialLayout(S,e,C,w,i+a,a),f++}}},x.maxDiagonalInTree=function(e){for(var t=g.MIN_VALUE,n=0;nt&&(t=r)}return t},x.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},x.prototype.groupZeroDegreeMembers=function(){var e=this,t={};this.memberGroups={},this.idToDummyNode={};for(var n=[],r=this.graphManager.getAllNodes(),i=0;i1){var r=`DummyCompound_`+n;e.memberGroups[r]=t[n];var i=t[n][0].getParent(),a=new o(e.graphManager);a.id=r,a.paddingLeft=i.paddingLeft||0,a.paddingRight=i.paddingRight||0,a.paddingBottom=i.paddingBottom||0,a.paddingTop=i.paddingTop||0,e.idToDummyNode[r]=a;var s=e.getGraphManager().add(e.newGraph(),a),c=i.getChild();c.add(a);for(var l=0;li?(r.rect.x-=(r.labelWidth-i)/2,r.setWidth(r.labelWidth),r.labelMarginLeft=(r.labelWidth-i)/2):r.labelPosHorizontal==`right`&&r.setWidth(i+r.labelWidth)),r.labelHeight&&(r.labelPosVertical==`top`?(r.rect.y-=r.labelHeight,r.setHeight(a+r.labelHeight),r.labelMarginTop=r.labelHeight):r.labelPosVertical==`center`&&r.labelHeight>a?(r.rect.y-=(r.labelHeight-a)/2,r.setHeight(r.labelHeight),r.labelMarginTop=(r.labelHeight-a)/2):r.labelPosVertical==`bottom`&&r.setHeight(a+r.labelHeight))}})},x.prototype.repopulateCompounds=function(){for(var e=this.compoundOrder.length-1;e>=0;e--){var t=this.compoundOrder[e],n=t.id,r=t.paddingLeft,i=t.paddingTop,a=t.labelMarginLeft,o=t.labelMarginTop;this.adjustLocations(this.tiledMemberPack[n],t.rect.x,t.rect.y,r,i,a,o)}},x.prototype.repopulateZeroDegreeMembers=function(){var e=this,t=this.tiledZeroDegreePack;Object.keys(t).forEach(function(n){var r=e.idToDummyNode[n],i=r.paddingLeft,a=r.paddingTop,o=r.labelMarginLeft,s=r.labelMarginTop;e.adjustLocations(t[n],r.rect.x,r.rect.y,i,a,o,s)})},x.prototype.getToBeTiled=function(e){var t=e.id;if(this.toBeTiled[t]!=null)return this.toBeTiled[t];var n=e.getChild();if(n==null)return this.toBeTiled[t]=!1,!1;for(var r=n.getNodes(),i=0;i0)return this.toBeTiled[t]=!1,!1;if(a.getChild()==null){this.toBeTiled[a.id]=!1;continue}if(!this.getToBeTiled(a))return this.toBeTiled[t]=!1,!1}return this.toBeTiled[t]=!0,!0},x.prototype.getNodeDegree=function(e){e.id;for(var t=e.getEdges(),n=0,r=0;ru&&(u=f.rect.height)}n+=u+e.verticalPadding}},x.prototype.tileCompoundMembers=function(e,t){var n=this;this.tiledMemberPack=[],Object.keys(e).forEach(function(r){var i=t[r];if(n.tiledMemberPack[r]=n.tileNodes(e[r],i.paddingLeft+i.paddingRight),i.rect.width=n.tiledMemberPack[r].width,i.rect.height=n.tiledMemberPack[r].height,i.setCenter(n.tiledMemberPack[r].centerX,n.tiledMemberPack[r].centerY),i.labelMarginLeft=0,i.labelMarginTop=0,c.NODE_DIMENSIONS_INCLUDE_LABELS){var a=i.rect.width,o=i.rect.height;i.labelWidth&&(i.labelPosHorizontal==`left`?(i.rect.x-=i.labelWidth,i.setWidth(a+i.labelWidth),i.labelMarginLeft=i.labelWidth):i.labelPosHorizontal==`center`&&i.labelWidth>a?(i.rect.x-=(i.labelWidth-a)/2,i.setWidth(i.labelWidth),i.labelMarginLeft=(i.labelWidth-a)/2):i.labelPosHorizontal==`right`&&i.setWidth(a+i.labelWidth)),i.labelHeight&&(i.labelPosVertical==`top`?(i.rect.y-=i.labelHeight,i.setHeight(o+i.labelHeight),i.labelMarginTop=i.labelHeight):i.labelPosVertical==`center`&&i.labelHeight>o?(i.rect.y-=(i.labelHeight-o)/2,i.setHeight(i.labelHeight),i.labelMarginTop=(i.labelHeight-o)/2):i.labelPosVertical==`bottom`&&i.setHeight(o+i.labelHeight))}})},x.prototype.tileNodes=function(e,t){var n=this.tileNodesByFavoringDim(e,t,!0),r=this.tileNodesByFavoringDim(e,t,!1),i=this.getOrgRatio(n);return this.getOrgRatio(r)s&&(s=e.getWidth())});var l=a/i,u=o/i,d=(n-r)**2+4*(l+r)*(u+n)*i,f=(r-n+Math.sqrt(d))/(2*(l+r)),p;t?(p=Math.ceil(f),p==f&&p++):p=Math.floor(f);var m=p*(l+r)-r;return s>m&&(m=s),m+=r*2,m},x.prototype.tileNodesByFavoringDim=function(e,t,n){var r=c.TILING_PADDING_VERTICAL,i=c.TILING_PADDING_HORIZONTAL,a=c.TILING_COMPARE_BY,o={rows:[],rowWidth:[],rowHeight:[],width:0,height:t,verticalPadding:r,horizontalPadding:i,centerX:0,centerY:0};a&&(o.idealRowWidth=this.calcIdealRowWidth(e,n));var s=function(e){return e.rect.width*e.rect.height},l=function(e,t){return s(t)-s(e)};e.sort(function(e,t){var n=l;return o.idealRowWidth?(n=a,n(e.id,t.id)):n(e,t)});for(var u=0,d=0,f=0;f0&&(a+=e.horizontalPadding),e.rowWidth[n]=a,e.width0&&(o+=e.verticalPadding);var s=0;o>e.rowHeight[n]&&(s=e.rowHeight[n],e.rowHeight[n]=o,s=e.rowHeight[n]-s),e.height+=s,e.rows[n].push(t)},x.prototype.getShortestRowIndex=function(e){for(var t=-1,n=Number.MAX_VALUE,r=0;rn&&(t=r,n=e.rowWidth[r]);return t},x.prototype.canAddHorizontal=function(e,t,n){if(e.idealRowWidth){var r=e.rows.length-1;return e.rowWidth[r]+t+e.horizontalPadding<=e.idealRowWidth}var i=this.getShortestRowIndex(e);if(i<0)return!0;var a=e.rowWidth[i];if(a+e.horizontalPadding+t<=e.width)return!0;var o=0;e.rowHeight[i]0&&(o=n+e.verticalPadding-e.rowHeight[i]);var s=e.width-a>=t+e.horizontalPadding?(e.height+o)/(a+t+e.horizontalPadding):(e.height+o)/e.width;o=n+e.verticalPadding;var c=e.widtha&&t!=n){r.splice(-1,1),e.rows[n].push(i),e.rowWidth[t]=e.rowWidth[t]-a,e.rowWidth[n]=e.rowWidth[n]+a,e.width=e.rowWidth[instance.getLongestRowIndex(e)];for(var o=Number.MIN_VALUE,s=0;so&&(o=r[s].height);t>0&&(o+=e.verticalPadding);var c=e.rowHeight[t]+e.rowHeight[n];e.rowHeight[t]=o,e.rowHeight[n]0)for(var d=i;d<=a;d++)l[0]+=this.grid[d][o-1].length+this.grid[d][o].length-1;if(a0)for(var d=o;d<=s;d++)l[3]+=this.grid[i-1][d].length+this.grid[i][d].length-1;for(var f=g.MAX_VALUE,p,m,h=0;h{var r=n(551).FDLayoutNode,i=n(551).IMath;function a(e,t,n,i){r.call(this,e,t,n,i)}for(var o in a.prototype=Object.create(r.prototype),r)a[o]=r[o];a.prototype.calculateDisplacement=function(){var e=this.graphManager.getLayout();this.getChild()!=null&&this.fixedNodeWeight?(this.displacementX+=e.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.fixedNodeWeight,this.displacementY+=e.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.fixedNodeWeight):(this.displacementX+=e.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY+=e.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren),Math.abs(this.displacementX)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementX=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementX)),Math.abs(this.displacementY)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementY=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementY)),this.child&&this.child.getNodes().length>0&&this.propogateDisplacementToChildren(this.displacementX,this.displacementY)},a.prototype.propogateDisplacementToChildren=function(e,t){for(var n=this.getChild().getNodes(),r,i=0;i{function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t0){var a=0;r.forEach(function(e){t==`horizontal`?(f.set(e,c.has(e)?l[c.get(e)]:i.get(e)),a+=f.get(e)):(f.set(e,c.has(e)?u[c.get(e)]:i.get(e)),a+=f.get(e))}),a/=r.length,e.forEach(function(e){n.has(e)||f.set(e,a)})}else{var o=0;e.forEach(function(e){t==`horizontal`?o+=c.has(e)?l[c.get(e)]:i.get(e):o+=c.has(e)?u[c.get(e)]:i.get(e)}),o/=e.length,e.forEach(function(e){f.set(e,o)})}});for(var h=function(){var r=m.shift();e.get(r).forEach(function(e){if(f.get(e.id)o&&(o=v),ys&&(s=y)}}catch(e){p=!0,m=e}finally{try{!d&&h.return&&h.return()}finally{if(p)throw m}}var b=(r+o)/2-(a+s)/2,x=!0,S=!1,C=void 0;try{for(var w=e[Symbol.iterator](),T;!(x=(T=w.next()).done);x=!0){var E=T.value;f.set(E,f.get(E)+b)}}catch(e){S=!0,C=e}finally{try{!x&&w.return&&w.return()}finally{if(S)throw C}}})}return f},v=function(e){var t=0,n=0,r=0,i=0;if(e.forEach(function(e){e.left?l[c.get(e.left)]-l[c.get(e.right)]>=0?t++:n++:u[c.get(e.top)]-u[c.get(e.bottom)]>=0?r++:i++}),t>n&&r>i)for(var a=0;an)for(var o=0;oi)for(var s=0;s1)t.fixedNodeConstraint.forEach(function(e,t){S[t]=[e.position.x,e.position.y],C[t]=[l[c.get(e.nodeId)],u[c.get(e.nodeId)]]}),w=!0;else if(t.alignmentConstraint)(function(){var e=0;if(t.alignmentConstraint.vertical){for(var n=t.alignmentConstraint.vertical,i=function(t){var i=new Set;n[t].forEach(function(e){i.add(e)});var a=new Set([].concat(r(i)).filter(function(e){return E.has(e)})),o=void 0;o=a.size>0?l[c.get(a.values().next().value)]:g(i).x,n[t].forEach(function(t){S[e]=[o,u[c.get(t)]],C[e]=[l[c.get(t)],u[c.get(t)]],e++})},a=0;a0?l[c.get(i.values().next().value)]:g(n).y,o[t].forEach(function(t){S[e]=[l[c.get(t)],a],C[e]=[l[c.get(t)],u[c.get(t)]],e++})},d=0;dA&&(A=k[M].length,j=M);if(A0){var W={x:0,y:0};t.fixedNodeConstraint.forEach(function(e,t){var n={x:l[c.get(e.nodeId)],y:u[c.get(e.nodeId)]},r=e.position,i=h(r,n);W.x+=i.x,W.y+=i.y}),W.x/=t.fixedNodeConstraint.length,W.y/=t.fixedNodeConstraint.length,l.forEach(function(e,t){l[t]+=W.x}),u.forEach(function(e,t){u[t]+=W.y}),t.fixedNodeConstraint.forEach(function(e){l[c.get(e.nodeId)]=e.position.x,u[c.get(e.nodeId)]=e.position.y})}if(t.alignmentConstraint){if(t.alignmentConstraint.vertical)for(var G=t.alignmentConstraint.vertical,ie=function(e){var t=new Set;G[e].forEach(function(e){t.add(e)});var n=new Set([].concat(r(t)).filter(function(e){return E.has(e)})),i=void 0;i=n.size>0?l[c.get(n.values().next().value)]:g(t).x,t.forEach(function(e){E.has(e)||(l[c.get(e)]=i)})},K=0;K0?u[c.get(n.values().next().value)]:g(t).y,t.forEach(function(e){E.has(e)||(u[c.get(e)]=i)})},Y=0;Y{t.exports=e})},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}return r(45)})()})})),k=e(t(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(O()):typeof define==`function`&&define.amd?define([`cose-base`],r):typeof e==`object`?e.cytoscapeFcose=r(O()):n.cytoscapeFcose=r(n.coseBase)})(e,function(e){return(()=>{var t={658:(e=>{e.exports=Object.assign==null?function(e){return[...arguments].slice(1).forEach(function(t){Object.keys(t).forEach(function(n){return e[n]=t[n]})}),e}:Object.assign.bind(Object)}),548:((e,t,n)=>{var r=function(){function e(e,t){var n=[],r=!0,i=!1,a=void 0;try{for(var o=e[Symbol.iterator](),s;!(r=(s=o.next()).done)&&(n.push(s.value),!(t&&n.length===t));r=!0);}catch(e){i=!0,a=e}finally{try{!r&&o.return&&o.return()}finally{if(i)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw TypeError(`Invalid attempt to destructure non-iterable instance`)}}(),i=n(140).layoutBase.LinkedList,a={};a.getTopMostNodes=function(e){for(var t={},n=0;n0&&l.merge(e)});for(var u=0;u1){l=s[0],u=l.connectedEdges().length,s.forEach(function(e){e.connectedEdges().length0&&r.set(`dummy`+(r.size+1),p),m},a.relocateComponent=function(e,t,n){if(!n.fixedNodeConstraint){var i=1/0,a=-1/0,o=1/0,s=-1/0;if(n.quality==`draft`){var c=!0,l=!1,u=void 0;try{for(var d=t.nodeIndexes[Symbol.iterator](),f;!(c=(f=d.next()).done);c=!0){var p=f.value,m=r(p,2),h=m[0],g=m[1],_=n.cy.getElementById(h);if(_){var v=_.boundingBox(),y=t.xCoords[g]-v.w/2,b=t.xCoords[g]+v.w/2,x=t.yCoords[g]-v.h/2,S=t.yCoords[g]+v.h/2;ya&&(a=b),xs&&(s=S)}}}catch(e){l=!0,u=e}finally{try{!c&&d.return&&d.return()}finally{if(l)throw u}}var C=e.x-(a+i)/2,w=e.y-(s+o)/2;t.xCoords=t.xCoords.map(function(e){return e+C}),t.yCoords=t.yCoords.map(function(e){return e+w})}else{Object.keys(t).forEach(function(e){var n=t[e],r=n.getRect().x,c=n.getRect().x+n.getRect().width,l=n.getRect().y,u=n.getRect().y+n.getRect().height;ra&&(a=c),ls&&(s=u)});var T=e.x-(a+i)/2,E=e.y-(s+o)/2;Object.keys(t).forEach(function(e){var n=t[e];n.setCenter(n.getCenterX()+T,n.getCenterY()+E)})}}},a.calcBoundingBox=function(e,t,n,r){for(var i=2**53-1,a=-(2**53-1),o=2**53-1,s=-(2**53-1),c=void 0,l=void 0,u=void 0,d=void 0,f=e.descendants().not(`:parent`),p=f.length,m=0;mc&&(i=c),au&&(o=u),s{var r=n(548),i=n(140).CoSELayout,a=n(140).CoSENode,o=n(140).layoutBase.PointD,s=n(140).layoutBase.DimensionD,c=n(140).layoutBase.LayoutConstants,l=n(140).layoutBase.FDLayoutConstants,u=n(140).CoSEConstants;e.exports={coseLayout:function(e,t){var n=e.cy,d=e.eles,f=d.nodes(),p=d.edges(),m=void 0,h=void 0,g=void 0,_={};e.randomize&&(m=t.nodeIndexes,h=t.xCoords,g=t.yCoords);var v=function(e){return typeof e==`function`},y=function(e,t){return v(e)?e(t):e},b=r.calcParentsWithoutChildren(n,d),x=function e(t,n,i,c){for(var l=n.length,u=0;u0){var S=void 0;S=i.getGraphManager().add(i.newGraph(),p),e(S,f,i,c)}}},S=function(t,n,r){for(var i=0,a=0,o=0;o0?u.DEFAULT_EDGE_LENGTH=l.DEFAULT_EDGE_LENGTH=i/a:v(e.idealEdgeLength)?u.DEFAULT_EDGE_LENGTH=l.DEFAULT_EDGE_LENGTH=50:u.DEFAULT_EDGE_LENGTH=l.DEFAULT_EDGE_LENGTH=e.idealEdgeLength,u.MIN_REPULSION_DIST=l.MIN_REPULSION_DIST=l.DEFAULT_EDGE_LENGTH/10,u.DEFAULT_RADIAL_SEPARATION=l.DEFAULT_EDGE_LENGTH)},C=function(e,t){t.fixedNodeConstraint&&(e.constraints.fixedNodeConstraint=t.fixedNodeConstraint),t.alignmentConstraint&&(e.constraints.alignmentConstraint=t.alignmentConstraint),t.relativePlacementConstraint&&(e.constraints.relativePlacementConstraint=t.relativePlacementConstraint)};e.nestingFactor!=null&&(u.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=l.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=e.nestingFactor),e.gravity!=null&&(u.DEFAULT_GRAVITY_STRENGTH=l.DEFAULT_GRAVITY_STRENGTH=e.gravity),e.numIter!=null&&(u.MAX_ITERATIONS=l.MAX_ITERATIONS=e.numIter),e.gravityRange!=null&&(u.DEFAULT_GRAVITY_RANGE_FACTOR=l.DEFAULT_GRAVITY_RANGE_FACTOR=e.gravityRange),e.gravityCompound!=null&&(u.DEFAULT_COMPOUND_GRAVITY_STRENGTH=l.DEFAULT_COMPOUND_GRAVITY_STRENGTH=e.gravityCompound),e.gravityRangeCompound!=null&&(u.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=l.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=e.gravityRangeCompound),e.initialEnergyOnIncremental!=null&&(u.DEFAULT_COOLING_FACTOR_INCREMENTAL=l.DEFAULT_COOLING_FACTOR_INCREMENTAL=e.initialEnergyOnIncremental),e.tilingCompareBy!=null&&(u.TILING_COMPARE_BY=e.tilingCompareBy),e.quality==`proof`?c.QUALITY=2:c.QUALITY=0,u.NODE_DIMENSIONS_INCLUDE_LABELS=l.NODE_DIMENSIONS_INCLUDE_LABELS=c.NODE_DIMENSIONS_INCLUDE_LABELS=e.nodeDimensionsIncludeLabels,u.DEFAULT_INCREMENTAL=l.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=!e.randomize,u.ANIMATE=l.ANIMATE=c.ANIMATE=e.animate,u.TILE=e.tile,u.TILING_PADDING_VERTICAL=typeof e.tilingPaddingVertical==`function`?e.tilingPaddingVertical.call():e.tilingPaddingVertical,u.TILING_PADDING_HORIZONTAL=typeof e.tilingPaddingHorizontal==`function`?e.tilingPaddingHorizontal.call():e.tilingPaddingHorizontal,u.DEFAULT_INCREMENTAL=l.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=!0,u.PURE_INCREMENTAL=!e.randomize,c.DEFAULT_UNIFORM_LEAF_NODE_SIZES=e.uniformNodeDimensions,e.step==`transformed`&&(u.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,u.ENFORCE_CONSTRAINTS=!1,u.APPLY_LAYOUT=!1),e.step==`enforced`&&(u.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,u.ENFORCE_CONSTRAINTS=!0,u.APPLY_LAYOUT=!1),e.step==`cose`&&(u.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,u.ENFORCE_CONSTRAINTS=!1,u.APPLY_LAYOUT=!0),e.step==`all`&&(e.randomize?u.TRANSFORM_ON_CONSTRAINT_HANDLING=!0:u.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,u.ENFORCE_CONSTRAINTS=!0,u.APPLY_LAYOUT=!0),e.fixedNodeConstraint||e.alignmentConstraint||e.relativePlacementConstraint?u.TREE_REDUCTION_ON_INCREMENTAL=!1:u.TREE_REDUCTION_ON_INCREMENTAL=!0;var w=new i,T=w.newGraphManager();return x(T.addRoot(),r.getTopMostNodes(f),w,e),S(w,T,p),C(w,e),w.runLayout(),_}}}),212:((e,t,n)=>{var r=function(){function e(e,t){for(var n=0;n0)if(f){var p=o.getTopMostNodes(t.eles.nodes());if(l=o.connectComponents(n,t.eles,p),l.forEach(function(e){var t=e.boundingBox();u.push({x:t.x1+t.w/2,y:t.y1+t.h/2})}),t.randomize&&l.forEach(function(e){t.eles=e,i.push(s(t))}),t.quality=="default"||t.quality==`proof`){var m=n.collection();if(t.tile){var h=new Map,g=[],_=[],v=0,y={nodeIndexes:h,xCoords:g,yCoords:_},b=[];if(l.forEach(function(e,t){e.edges().length==0&&(e.nodes().forEach(function(t,n){m.merge(e.nodes()[n]),t.isParent()||(y.nodeIndexes.set(e.nodes()[n].id(),v++),y.xCoords.push(e.nodes()[0].position().x),y.yCoords.push(e.nodes()[0].position().y))}),b.push(t))}),m.length>1){var x=m.boundingBox();u.push({x:x.x1+x.w/2,y:x.y1+x.h/2}),l.push(m),i.push(y);for(var S=b.length-1;S>=0;S--)l.splice(b[S],1),i.splice(b[S],1),u.splice(b[S],1)}}l.forEach(function(e,n){t.eles=e,a.push(c(t,i[n])),o.relocateComponent(u[n],a[n],t)})}else l.forEach(function(e,n){o.relocateComponent(u[n],i[n],t)});var C=new Set;if(l.length>1){var w=[],T=r.filter(function(e){return e.css(`display`)==`none`});l.forEach(function(e,n){var r=void 0;if(t.quality==`draft`&&(r=i[n].nodeIndexes),e.nodes().not(T).length>0){var s={};s.edges=[],s.nodes=[];var c=void 0;e.nodes().not(T).forEach(function(e){if(t.quality==`draft`)if(!e.isParent())c=r.get(e.id()),s.nodes.push({x:i[n].xCoords[c]-e.boundingbox().w/2,y:i[n].yCoords[c]-e.boundingbox().h/2,width:e.boundingbox().w,height:e.boundingbox().h});else{var l=o.calcBoundingBox(e,i[n].xCoords,i[n].yCoords,r);s.nodes.push({x:l.topLeftX,y:l.topLeftY,width:l.width,height:l.height})}else a[n][e.id()]&&s.nodes.push({x:a[n][e.id()].getLeft(),y:a[n][e.id()].getTop(),width:a[n][e.id()].getWidth(),height:a[n][e.id()].getHeight()})}),e.edges().forEach(function(e){var c=e.source(),l=e.target();if(c.css(`display`)!=`none`&&l.css(`display`)!=`none`)if(t.quality==`draft`){var u=r.get(c.id()),d=r.get(l.id()),f=[],p=[];if(c.isParent()){var m=o.calcBoundingBox(c,i[n].xCoords,i[n].yCoords,r);f.push(m.topLeftX+m.width/2),f.push(m.topLeftY+m.height/2)}else f.push(i[n].xCoords[u]),f.push(i[n].yCoords[u]);if(l.isParent()){var h=o.calcBoundingBox(l,i[n].xCoords,i[n].yCoords,r);p.push(h.topLeftX+h.width/2),p.push(h.topLeftY+h.height/2)}else p.push(i[n].xCoords[d]),p.push(i[n].yCoords[d]);s.edges.push({startX:f[0],startY:f[1],endX:p[0],endY:p[1]})}else a[n][c.id()]&&a[n][l.id()]&&s.edges.push({startX:a[n][c.id()].getCenterX(),startY:a[n][c.id()].getCenterY(),endX:a[n][l.id()].getCenterX(),endY:a[n][l.id()].getCenterY()})}),s.nodes.length>0&&(w.push(s),C.add(n))}});var E=d.packComponents(w,t.randomize).shifts;if(t.quality==`draft`)i.forEach(function(e,t){var n=e.xCoords.map(function(e){return e+E[t].dx}),r=e.yCoords.map(function(e){return e+E[t].dy});e.xCoords=n,e.yCoords=r});else{var D=0;C.forEach(function(e){Object.keys(a[e]).forEach(function(t){var n=a[e][t];n.setCenter(n.getCenterX()+E[D].dx,n.getCenterY()+E[D].dy)}),D++})}}}else{var O=t.eles.boundingBox();if(u.push({x:O.x1+O.w/2,y:O.y1+O.h/2}),t.randomize){var k=s(t);i.push(k)}t.quality=="default"||t.quality==`proof`?(a.push(c(t,i[0])),o.relocateComponent(u[0],a[0],t)):o.relocateComponent(u[0],i[0],t)}var A=function(e,n){if(t.quality=="default"||t.quality==`proof`){typeof e==`number`&&(e=n);var r=void 0,o=void 0,s=e.data(`id`);return a.forEach(function(e){s in e&&(r={x:e[s].getRect().getCenterX(),y:e[s].getRect().getCenterY()},o=e[s])}),t.nodeDimensionsIncludeLabels&&(o.labelWidth&&(o.labelPosHorizontal==`left`?r.x+=o.labelWidth/2:o.labelPosHorizontal==`right`&&(r.x-=o.labelWidth/2)),o.labelHeight&&(o.labelPosVertical==`top`?r.y+=o.labelHeight/2:o.labelPosVertical==`bottom`&&(r.y-=o.labelHeight/2))),r??={x:e.position(`x`),y:e.position(`y`)},{x:r.x,y:r.y}}else{var c=void 0;return i.forEach(function(t){var n=t.nodeIndexes.get(e.id());n!=null&&(c={x:t.xCoords[n],y:t.yCoords[n]})}),c??={x:e.position(`x`),y:e.position(`y`)},{x:c.x,y:c.y}}};if(t.quality=="default"||t.quality==`proof`||t.randomize){var j=o.calcParentsWithoutChildren(n,r),M=r.filter(function(e){return e.css(`display`)==`none`});t.eles=r.not(M),r.nodes().not(`:parent`).not(M).layoutPositions(e,t,A),j.length>0&&j.forEach(function(e){e.position(A(e))})}else console.log(`If randomize option is set to false, then quality option must be 'default' or 'proof'.`)}}]),e}()}),657:((e,t,n)=>{var r=n(548),i=n(140).layoutBase.Matrix,a=n(140).layoutBase.SVD;e.exports={spectralLayout:function(e){var t=e.cy,n=e.eles,o=n.nodes(),s=n.nodes(`:parent`),c=new Map,l=new Map,u=new Map,d=[],f=[],p=[],m=[],h=[],g=[],_=[],v=[],y=void 0,b=1e8,x=1e-9,S=e.piTol,C=e.samplingType,w=e.nodeSeparation,T=void 0,E=function(){for(var e=0,t=0,n=!1;t=i;){o=r[i++];for(var m=d[o],_=0;_u&&(u=h[x],f=x)}return f},O=function(e){var t=void 0;if(e){t=Math.floor(Math.random()*y);for(var n=0;n=1)break;u=l}for(var h=0;h=1)break;u=l}for(var b=0;b0&&(r.isParent()?d[t].push(u.get(r.id())):d[t].push(r.id()))})});var B=function(e){var n=l.get(e),r=void 0;c.get(e).forEach(function(i){r=t.getElementById(i).isParent()?u.get(i):i,d[n].push(r),d[l.get(r)].push(e)})},V=!0,ee=!1,te=void 0;try{for(var H=c.keys()[Symbol.iterator](),ne;!(V=(ne=H.next()).done);V=!0){var re=ne.value;B(re)}}catch(e){ee=!0,te=e}finally{try{!V&&H.return&&H.return()}finally{if(ee)throw te}}y=l.size;var U=void 0;if(y>2){T=y{var r=n(212),i=function(e){e&&e(`layout`,`fcose`,r)};typeof cytoscape<`u`&&i(cytoscape),e.exports=i}),140:(t=>{t.exports=e})},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}return r(579)})()})}))(),1),A={L:`left`,R:`right`,T:`top`,B:`bottom`},j={L:n(e=>`${e},${e/2} 0,${e} 0,0`,`L`),R:n(e=>`0,${e/2} ${e},0 ${e},${e}`,`R`),T:n(e=>`0,0 ${e},0 ${e/2},${e}`,`T`),B:n(e=>`${e/2},0 ${e},${e} 0,${e}`,`B`)},M={L:n((e,t)=>e-t+2,`L`),R:n((e,t)=>e-2,`R`),T:n((e,t)=>e-t+2,`T`),B:n((e,t)=>e-2,`B`)},N=n(function(e){return F(e)?e===`L`?`R`:`L`:e===`T`?`B`:`T`},`getOppositeArchitectureDirection`),P=n(function(e){let t=e;return t===`L`||t===`R`||t===`T`||t===`B`},`isArchitectureDirection`),F=n(function(e){let t=e;return t===`L`||t===`R`},`isArchitectureDirectionX`),I=n(function(e){let t=e;return t===`T`||t===`B`},`isArchitectureDirectionY`),L=n(function(e,t){let n=F(e)&&I(t),r=I(e)&&F(t);return n||r},`isArchitectureDirectionXY`),R=n(function(e){let t=e[0],n=e[1],r=F(t)&&I(n),i=I(t)&&F(n);return r||i},`isArchitecturePairXY`),z=n(function(e){return e!==`LL`&&e!==`RR`&&e!==`TT`&&e!==`BB`},`isValidArchitectureDirectionPair`),B=n(function(e,t){let n=`${e}${t}`;return z(n)?n:void 0},`getArchitectureDirectionPair`),V=n(function([e,t],n){let r=n[0],i=n[1];return F(r)?I(i)?[e+(r===`L`?-1:1),t+(i===`T`?1:-1)]:[e+(r===`L`?-1:1),t]:F(i)?[e+(i===`L`?1:-1),t+(r===`T`?1:-1)]:[e,t+(r===`T`?1:-1)]},`shiftPositionByArchitectureDirectionPair`),ee=n(function(e){return e===`LT`||e===`TL`?[1,1]:e===`BL`||e===`LB`?[1,-1]:e===`BR`||e===`RB`?[-1,-1]:[-1,1]},`getArchitectureDirectionXYFactors`),te=n(function(e,t){return L(e,t)?`bend`:F(e)?`horizontal`:`vertical`},`getArchitectureDirectionAlignment`),H=n(function(e){return e.type===`service`},`isArchitectureService`),ne=n(function(e){return e.type===`junction`},`isArchitectureJunction`),re=n(e=>e.data(),`edgeData`),U=n(e=>e.data(),`nodeData`),W=d.architecture,G=class{constructor(){this.nodes={},this.groups={},this.edges=[],this.layoutHints=[],this.registeredIds={},this.elements={},this.diagramId=``,this.setAccTitle=c,this.getAccTitle=h,this.setDiagramTitle=s,this.getDiagramTitle=p,this.getAccDescription=f,this.setAccDescription=a,this.clear()}static{n(this,`ArchitectureDB`)}setDiagramId(e){this.diagramId=e}getDiagramId(){return this.diagramId}clear(){this.nodes={},this.groups={},this.edges=[],this.layoutHints=[],this.registeredIds={},this.dataStructures=void 0,this.elements={},this.diagramId=``,l()}addService({id:e,icon:t,in:n,title:r,iconText:i}){if(this.registeredIds[e]!==void 0)throw Error(`The service id [${e}] is already in use by another ${this.registeredIds[e]}`);if(n!==void 0){if(e===n)throw Error(`The service [${e}] cannot be placed within itself`);if(this.registeredIds[n]===void 0)throw Error(`The service [${e}]'s parent does not exist. Please make sure the parent is created before this service`);if(this.registeredIds[n]===`node`)throw Error(`The service [${e}]'s parent is not a group`)}this.registeredIds[e]=`node`,this.nodes[e]={id:e,type:`service`,icon:t,iconText:i,title:r,edges:[],in:n}}getServices(){return Object.values(this.nodes).filter(H)}addJunction({id:e,in:t}){if(this.registeredIds[e]!==void 0)throw Error(`The junction id [${e}] is already in use by another ${this.registeredIds[e]}`);if(t!==void 0){if(e===t)throw Error(`The junction [${e}] cannot be placed within itself`);if(this.registeredIds[t]===void 0)throw Error(`The junction [${e}]'s parent does not exist. Please make sure the parent is created before this junction`);if(this.registeredIds[t]===`node`)throw Error(`The junction [${e}]'s parent is not a group`)}this.registeredIds[e]=`node`,this.nodes[e]={id:e,type:`junction`,edges:[],in:t}}getJunctions(){return Object.values(this.nodes).filter(ne)}getNodes(){return Object.values(this.nodes)}getNode(e){return this.nodes[e]??null}addGroup({id:e,icon:t,in:n,title:r}){if(this.registeredIds?.[e]!==void 0)throw Error(`The group id [${e}] is already in use by another ${this.registeredIds[e]}`);if(n!==void 0){if(e===n)throw Error(`The group [${e}] cannot be placed within itself`);if(this.registeredIds?.[n]===void 0)throw Error(`The group [${e}]'s parent does not exist. Please make sure the parent is created before this group`);if(this.registeredIds?.[n]===`node`)throw Error(`The group [${e}]'s parent is not a group`)}this.registeredIds[e]=`group`,this.groups[e]={id:e,icon:t,title:r,in:n}}getGroups(){return Object.values(this.groups)}addEdge({lhsId:e,rhsId:t,lhsDir:n,rhsDir:r,lhsInto:i,rhsInto:a,lhsGroup:o,rhsGroup:s,title:c}){if(!P(n))throw Error(`Invalid direction given for left hand side of edge ${e}--${t}. Expected (L,R,T,B) got ${String(n)}`);if(!P(r))throw Error(`Invalid direction given for right hand side of edge ${e}--${t}. Expected (L,R,T,B) got ${String(r)}`);if(this.nodes[e]===void 0&&this.groups[e]===void 0)throw Error(`The left-hand id [${e}] does not yet exist. Please create the service/group before declaring an edge to it.`);if(this.nodes[t]===void 0&&this.groups[t]===void 0)throw Error(`The right-hand id [${t}] does not yet exist. Please create the service/group before declaring an edge to it.`);let l=this.nodes[e].in,u=this.nodes[t].in;if(o&&l&&u&&l==u)throw Error(`The left-hand id [${e}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);if(s&&l&&u&&l==u)throw Error(`The right-hand id [${t}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);let d={lhsId:e,lhsDir:n,lhsInto:i,lhsGroup:o,rhsId:t,rhsDir:r,rhsInto:a,rhsGroup:s,title:c};this.edges.push(d),this.nodes[e]&&this.nodes[t]&&(this.nodes[e].edges.push(this.edges[this.edges.length-1]),this.nodes[t].edges.push(this.edges[this.edges.length-1]))}getEdges(){return this.edges}addLayoutHint(e){if(e.members.length<2)throw Error(`An align directive requires at least two members; got ${e.members.length}`);let t=new Set;e.members.forEach(n=>{if(this.registeredIds[n]!==`node`)throw Error(`align ${e.direction} references [${n}], which is not a service or junction`);if(t.has(n))throw Error(`align ${e.direction} lists [${n}] more than once`);t.add(n)}),this.layoutHints.push(e)}getLayoutHints(){return this.layoutHints}getDataStructures(){if(this.dataStructures===void 0){let e={},t=Object.entries(this.nodes).reduce((t,[n,r])=>(t[n]=r.edges.reduce((t,r)=>{let i=this.getNode(r.lhsId)?.in,a=this.getNode(r.rhsId)?.in;if(i&&a&&i!==a){let t=te(r.lhsDir,r.rhsDir);t!==`bend`&&(e[i]??={},e[i][a]=t,e[a]??={},e[a][i]=t)}if(r.lhsId===n){let e=B(r.lhsDir,r.rhsDir);e&&(t[e]=r.rhsId)}else{let e=B(r.rhsDir,r.lhsDir);e&&(t[e]=r.lhsId)}return t},{}),t),{}),r=Object.keys(t)[0],i={[r]:1},a=Object.keys(t).reduce((e,t)=>t===r?e:{...e,[t]:1},{}),o=n(e=>{let n={[e]:[0,0]},r=[e];for(;r.length>0;){let e=r.shift();if(e){i[e]=1,delete a[e];let o=t[e],[s,c]=n[e];Object.entries(o).forEach(([e,t])=>{i[t]||(n[t]=V([s,c],e),r.push(t))})}}return n},`BFS`),s=[o(r)];for(;Object.keys(a).length>0;)s.push(o(Object.keys(a)[0]));this.dataStructures={adjList:t,spatialMaps:s,groupAlignments:e}}return this.dataStructures}setElementForId(e,t){this.elements[e]=t}getElementById(e){return this.elements[e]}getConfig(){return v({...W,...u().architecture})}getConfigField(e){return this.getConfig()[e]}},ie=n((e,t)=>{b(e,t),e.groups.map(e=>t.addGroup(e)),e.services.map(e=>t.addService({...e,type:`service`})),e.junctions.map(e=>t.addJunction({...e,type:`junction`})),e.edges.map(e=>t.addEdge(e)),e.alignments?.map(e=>t.addLayoutHint({direction:e.direction,members:[...e.members]}))},`populateDb`),K={parser:{yy:void 0},parse:n(async e=>{let t=await x(`architecture`,e);r.debug(t);let n=K.parser?.yy;if(!(n instanceof G))throw Error(`parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);ie(t,n)},`parse`)},q=n(e=>` .edge { stroke-width: ${e.archEdgeWidth}; stroke: ${e.archEdgeColor}; diff --git a/.vercel/output/static/assets/blockDiagram-677ZJIJ3-DNbsA_px.js b/.vercel/output/static/assets/blockDiagram-677ZJIJ3-Dn3HALPW.js similarity index 99% rename from .vercel/output/static/assets/blockDiagram-677ZJIJ3-DNbsA_px.js rename to .vercel/output/static/assets/blockDiagram-677ZJIJ3-Dn3HALPW.js index 7f1e2dd..537ca0a 100644 --- a/.vercel/output/static/assets/blockDiagram-677ZJIJ3-DNbsA_px.js +++ b/.vercel/output/static/assets/blockDiagram-677ZJIJ3-Dn3HALPW.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{O as r,T as i,a,b as o,c as s,it as c,s as l,x as u,z as d}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as f}from"./channel-DA-EZjf8.js";import{A as p,B as m,C as h,D as g,E as _,F as v,G as y,H as b,I as x,L as S,M as C,N as w,O as T,P as E,R as D,T as O,U as k,V as A,W as j,a as M,b as ee,et as te,g as N,j as ne,k as re,l as ie,v as ae,w as oe,z as se}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as ce}from"./line-CDW8hdKE.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import{n as P}from"./chunk-Q4XR5HBZ-5srkZ5CC.js";import{t as le}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{n as ue,t as F}from"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as de,t as fe}from"./chunk-OGEWGWER-Dr-qyYzn.js";import{t as pe}from"./graphlib-DS17s2tU.js";function me(e){return Array.isArray(e)}function he(e){if(ee(e))return e;let t=y(e);if(!ge(e))return{};if(me(e)){let t=Array.from(e);return e.length>0&&typeof e[0]==`string`&&Object.hasOwn(e,`index`)&&(t.index=e.index,t.input=e.input),t}if(ae(e)){let t=e,n=t.constructor;return new n(t.buffer,t.byteOffset,t.length)}if(t===`[object ArrayBuffer]`)return new ArrayBuffer(e.byteLength);if(t===`[object DataView]`){let t=e,n=t.buffer,r=t.byteOffset,i=t.byteLength,a=new ArrayBuffer(i),o=new Uint8Array(n,r,i);return new Uint8Array(a).set(o),new DataView(a)}if(t===`[object Boolean]`||t===`[object Number]`||t===`[object String]`){let n=e.constructor,r=new n(e.valueOf());return t===`[object String]`?ye(r,e):_e(r,e),r}if(t===`[object Date]`)return new Date(Number(e));if(t===`[object RegExp]`){let t=e,n=new RegExp(t.source,t.flags);return n.lastIndex=t.lastIndex,n}if(t===`[object Symbol]`)return Object(Symbol.prototype.valueOf.call(e));if(t===`[object Map]`){let t=e,n=new Map;return t.forEach((e,t)=>{n.set(t,e)}),n}if(t===`[object Set]`){let t=e,n=new Set;return t.forEach(e=>{n.add(e)}),n}if(t===`[object Arguments]`){let t=e,n={};return _e(n,t),n.length=t.length,n[Symbol.iterator]=t[Symbol.iterator],n}let n={};return be(n,e),_e(n,e),ve(n,e),n}function ge(e){switch(y(e)){case h:case O:case oe:case g:case _:case T:case re:case p:case w:case ne:case C:case E:case v:case x:case S:case D:case se:case m:case k:case j:case A:case b:return!0;default:return!1}}function _e(e,t){for(let n in t)Object.hasOwn(t,n)&&(e[n]=t[n])}function ve(e,t){let n=Object.getOwnPropertySymbols(t);for(let r=0;r=n)&&(e[r]=t[r])}function be(e,t){let n=Object.getPrototypeOf(t);n!==null&&typeof t.constructor==`function`&&Object.setPrototypeOf(e,n)}var xe=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,15],r=[1,7],i=[1,13],a=[1,14],o=[1,19],s=[1,16],c=[1,17],l=[1,18],u=[8,30],d=[8,10,21,28,29,30,31,39,43,46],f=[1,23],p=[1,24],m=[8,10,15,16,21,28,29,30,31,39,43,46],h=[8,10,15,16,21,27,28,29,30,31,39,43,46],g=[1,49],_={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,spaceLines:3,SPACELINE:4,NL:5,separator:6,SPACE:7,EOF:8,start:9,BLOCK_DIAGRAM_KEY:10,document:11,stop:12,statement:13,link:14,LINK:15,START_LINK:16,LINK_LABEL:17,STR:18,nodeStatement:19,columnsStatement:20,SPACE_BLOCK:21,blockStatement:22,classDefStatement:23,cssClassStatement:24,styleStatement:25,node:26,SIZE:27,COLUMNS:28,"id-block":29,end:30,NODE_ID:31,nodeShapeNLabel:32,dirList:33,DIR:34,NODE_DSTART:35,NODE_DEND:36,BLOCK_ARROW_START:37,BLOCK_ARROW_END:38,classDef:39,CLASSDEF_ID:40,CLASSDEF_STYLEOPTS:41,DEFAULT:42,class:43,CLASSENTITY_IDS:44,STYLECLASS:45,style:46,STYLE_ENTITY_IDS:47,STYLE_DEFINITION_DATA:48,$accept:0,$end:1},terminals_:{2:`error`,4:`SPACELINE`,5:`NL`,7:`SPACE`,8:`EOF`,10:`BLOCK_DIAGRAM_KEY`,15:`LINK`,16:`START_LINK`,17:`LINK_LABEL`,18:`STR`,21:`SPACE_BLOCK`,27:`SIZE`,28:`COLUMNS`,29:`id-block`,30:`end`,31:`NODE_ID`,34:`DIR`,35:`NODE_DSTART`,36:`NODE_DEND`,37:`BLOCK_ARROW_START`,38:`BLOCK_ARROW_END`,39:`classDef`,40:`CLASSDEF_ID`,41:`CLASSDEF_STYLEOPTS`,42:`DEFAULT`,43:`class`,44:`CLASSENTITY_IDS`,45:`STYLECLASS`,46:`style`,47:`STYLE_ENTITY_IDS`,48:`STYLE_DEFINITION_DATA`},productions_:[0,[3,1],[3,2],[3,2],[6,1],[6,1],[6,1],[9,3],[12,1],[12,1],[12,2],[12,2],[11,1],[11,2],[14,1],[14,4],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[19,3],[19,2],[19,1],[20,1],[22,4],[22,3],[26,1],[26,2],[33,1],[33,2],[32,3],[32,4],[23,3],[23,3],[24,3],[25,3]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 4:r.getLogger().debug(`Rule: separator (NL) `);break;case 5:r.getLogger().debug(`Rule: separator (Space) `);break;case 6:r.getLogger().debug(`Rule: separator (EOF) `);break;case 7:r.getLogger().debug(`Rule: hierarchy: `,a[s-1]),r.setHierarchy(a[s-1]);break;case 8:r.getLogger().debug(`Stop NL `);break;case 9:r.getLogger().debug(`Stop EOF `);break;case 10:r.getLogger().debug(`Stop NL2 `);break;case 11:r.getLogger().debug(`Stop EOF2 `);break;case 12:r.getLogger().debug(`Rule: statement: `,a[s]),typeof a[s].length==`number`?this.$=a[s]:this.$=[a[s]];break;case 13:r.getLogger().debug(`Rule: statement #2: `,a[s-1]),this.$=[a[s-1]].concat(a[s]);break;case 14:r.getLogger().debug(`Rule: link: `,a[s],e),this.$={edgeTypeStr:a[s],label:``};break;case 15:r.getLogger().debug(`Rule: LABEL link: `,a[s-3],a[s-1],a[s]),this.$={edgeTypeStr:a[s],label:a[s-1]};break;case 18:let t=parseInt(a[s]),n=r.generateId();this.$={id:n,type:`space`,label:``,width:t,children:[]};break;case 23:r.getLogger().debug(`Rule: (nodeStatement link node) `,a[s-2],a[s-1],a[s],` typestr: `,a[s-1].edgeTypeStr);let i=r.edgeStrToEdgeData(a[s-1].edgeTypeStr),o=r.edgeStrToEdgeStartData(a[s-1].edgeTypeStr),c=r.edgeStrToThickness(a[s-1].edgeTypeStr),l=r.edgeStrToPattern(a[s-1].edgeTypeStr);this.$=[{id:a[s-2].id,label:a[s-2].label,type:a[s-2].type,directions:a[s-2].directions},{id:a[s-2].id+`-`+a[s].id,start:a[s-2].id,end:a[s].id,label:a[s-1].label,type:`edge`,thickness:c,pattern:l,directions:a[s].directions,arrowTypeEnd:i,arrowTypeStart:o},{id:a[s].id,label:a[s].label,type:r.typeStr2Type(a[s].typeStr),directions:a[s].directions}];break;case 24:r.getLogger().debug(`Rule: nodeStatement (abc88 node size) `,a[s-1],a[s]),this.$={id:a[s-1].id,label:a[s-1].label,type:r.typeStr2Type(a[s-1].typeStr),directions:a[s-1].directions,widthInColumns:parseInt(a[s],10)};break;case 25:r.getLogger().debug(`Rule: nodeStatement (node) `,a[s]),this.$={id:a[s].id,label:a[s].label,type:r.typeStr2Type(a[s].typeStr),directions:a[s].directions,widthInColumns:1};break;case 26:r.getLogger().debug(`APA123`,this?this:`na`),r.getLogger().debug(`COLUMNS: `,a[s]),this.$={type:`column-setting`,columns:a[s]===`auto`?-1:parseInt(a[s])};break;case 27:r.getLogger().debug(`Rule: id-block statement : `,a[s-2],a[s-1]),r.generateId(),this.$={...a[s-2],type:`composite`,children:a[s-1]};break;case 28:r.getLogger().debug(`Rule: blockStatement : `,a[s-2],a[s-1],a[s]);let u=r.generateId();this.$={id:u,type:`composite`,label:``,children:a[s-1]};break;case 29:r.getLogger().debug(`Rule: node (NODE_ID separator): `,a[s]),this.$={id:a[s]};break;case 30:r.getLogger().debug(`Rule: node (NODE_ID nodeShapeNLabel separator): `,a[s-1],a[s]),this.$={id:a[s-1],label:a[s].label,typeStr:a[s].typeStr,directions:a[s].directions};break;case 31:r.getLogger().debug(`Rule: dirList: `,a[s]),this.$=[a[s]];break;case 32:r.getLogger().debug(`Rule: dirList: `,a[s-1],a[s]),this.$=[a[s-1]].concat(a[s]);break;case 33:r.getLogger().debug(`Rule: nodeShapeNLabel: `,a[s-2],a[s-1],a[s]),this.$={typeStr:a[s-2]+a[s],label:a[s-1]};break;case 34:r.getLogger().debug(`Rule: BLOCK_ARROW nodeShapeNLabel: `,a[s-3],a[s-2],` #3:`,a[s-1],a[s]),this.$={typeStr:a[s-3]+a[s],label:a[s-2],directions:a[s-1]};break;case 35:case 36:this.$={type:`classDef`,id:a[s-1].trim(),css:a[s].trim()};break;case 37:this.$={type:`applyClass`,id:a[s-1].trim(),styleClass:a[s].trim()};break;case 38:this.$={type:`applyStyles`,id:a[s-1].trim(),stylesStr:a[s].trim()};break}},`anonymous`),table:[{9:1,10:[1,2]},{1:[3]},{10:n,11:3,13:4,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:a,31:o,39:s,43:c,46:l},{8:[1,20]},t(u,[2,12],{13:4,19:5,20:6,22:8,23:9,24:10,25:11,26:12,11:21,10:n,21:r,28:i,29:a,31:o,39:s,43:c,46:l}),t(d,[2,16],{14:22,15:f,16:p}),t(d,[2,17]),t(d,[2,18]),t(d,[2,19]),t(d,[2,20]),t(d,[2,21]),t(d,[2,22]),t(m,[2,25],{27:[1,25]}),t(d,[2,26]),{19:26,26:12,31:o},{10:n,11:27,13:4,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:a,31:o,39:s,43:c,46:l},{40:[1,28],42:[1,29]},{44:[1,30]},{47:[1,31]},t(h,[2,29],{32:32,35:[1,33],37:[1,34]}),{1:[2,7]},t(u,[2,13]),{26:35,31:o},{31:[2,14]},{17:[1,36]},t(m,[2,24]),{10:n,11:37,13:4,14:22,15:f,16:p,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:a,31:o,39:s,43:c,46:l},{30:[1,38]},{41:[1,39]},{41:[1,40]},{45:[1,41]},{48:[1,42]},t(h,[2,30]),{18:[1,43]},{18:[1,44]},t(m,[2,23]),{18:[1,45]},{30:[1,46]},t(d,[2,28]),t(d,[2,35]),t(d,[2,36]),t(d,[2,37]),t(d,[2,38]),{36:[1,47]},{33:48,34:g},{15:[1,50]},t(d,[2,27]),t(h,[2,33]),{38:[1,51]},{33:52,34:g,38:[2,31]},{31:[2,15]},t(h,[2,34]),{38:[2,32]}],defaultActions:{20:[2,7],23:[2,14],50:[2,15],52:[2,32]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{O as r,T as i,a,b as o,c as s,it as c,s as l,x as u,z as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as f}from"./channel-C4fgBBJ4.js";import{A as p,B as m,C as h,D as g,E as _,F as v,G as y,H as b,I as x,L as S,M as C,N as w,O as T,P as E,R as D,T as O,U as k,V as A,W as j,a as M,b as ee,et as te,g as N,j as ne,k as re,l as ie,v as ae,w as oe,z as se}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as ce}from"./line-b9Ala942.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import{n as P}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{t as le}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{n as ue,t as F}from"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as de,t as fe}from"./chunk-OGEWGWER-D-nWYRNR.js";import{t as pe}from"./graphlib-DS17s2tU.js";function me(e){return Array.isArray(e)}function he(e){if(ee(e))return e;let t=y(e);if(!ge(e))return{};if(me(e)){let t=Array.from(e);return e.length>0&&typeof e[0]==`string`&&Object.hasOwn(e,`index`)&&(t.index=e.index,t.input=e.input),t}if(ae(e)){let t=e,n=t.constructor;return new n(t.buffer,t.byteOffset,t.length)}if(t===`[object ArrayBuffer]`)return new ArrayBuffer(e.byteLength);if(t===`[object DataView]`){let t=e,n=t.buffer,r=t.byteOffset,i=t.byteLength,a=new ArrayBuffer(i),o=new Uint8Array(n,r,i);return new Uint8Array(a).set(o),new DataView(a)}if(t===`[object Boolean]`||t===`[object Number]`||t===`[object String]`){let n=e.constructor,r=new n(e.valueOf());return t===`[object String]`?ye(r,e):_e(r,e),r}if(t===`[object Date]`)return new Date(Number(e));if(t===`[object RegExp]`){let t=e,n=new RegExp(t.source,t.flags);return n.lastIndex=t.lastIndex,n}if(t===`[object Symbol]`)return Object(Symbol.prototype.valueOf.call(e));if(t===`[object Map]`){let t=e,n=new Map;return t.forEach((e,t)=>{n.set(t,e)}),n}if(t===`[object Set]`){let t=e,n=new Set;return t.forEach(e=>{n.add(e)}),n}if(t===`[object Arguments]`){let t=e,n={};return _e(n,t),n.length=t.length,n[Symbol.iterator]=t[Symbol.iterator],n}let n={};return be(n,e),_e(n,e),ve(n,e),n}function ge(e){switch(y(e)){case h:case O:case oe:case g:case _:case T:case re:case p:case w:case ne:case C:case E:case v:case x:case S:case D:case se:case m:case k:case j:case A:case b:return!0;default:return!1}}function _e(e,t){for(let n in t)Object.hasOwn(t,n)&&(e[n]=t[n])}function ve(e,t){let n=Object.getOwnPropertySymbols(t);for(let r=0;r=n)&&(e[r]=t[r])}function be(e,t){let n=Object.getPrototypeOf(t);n!==null&&typeof t.constructor==`function`&&Object.setPrototypeOf(e,n)}var xe=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,15],r=[1,7],i=[1,13],a=[1,14],o=[1,19],s=[1,16],c=[1,17],l=[1,18],u=[8,30],d=[8,10,21,28,29,30,31,39,43,46],f=[1,23],p=[1,24],m=[8,10,15,16,21,28,29,30,31,39,43,46],h=[8,10,15,16,21,27,28,29,30,31,39,43,46],g=[1,49],_={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,spaceLines:3,SPACELINE:4,NL:5,separator:6,SPACE:7,EOF:8,start:9,BLOCK_DIAGRAM_KEY:10,document:11,stop:12,statement:13,link:14,LINK:15,START_LINK:16,LINK_LABEL:17,STR:18,nodeStatement:19,columnsStatement:20,SPACE_BLOCK:21,blockStatement:22,classDefStatement:23,cssClassStatement:24,styleStatement:25,node:26,SIZE:27,COLUMNS:28,"id-block":29,end:30,NODE_ID:31,nodeShapeNLabel:32,dirList:33,DIR:34,NODE_DSTART:35,NODE_DEND:36,BLOCK_ARROW_START:37,BLOCK_ARROW_END:38,classDef:39,CLASSDEF_ID:40,CLASSDEF_STYLEOPTS:41,DEFAULT:42,class:43,CLASSENTITY_IDS:44,STYLECLASS:45,style:46,STYLE_ENTITY_IDS:47,STYLE_DEFINITION_DATA:48,$accept:0,$end:1},terminals_:{2:`error`,4:`SPACELINE`,5:`NL`,7:`SPACE`,8:`EOF`,10:`BLOCK_DIAGRAM_KEY`,15:`LINK`,16:`START_LINK`,17:`LINK_LABEL`,18:`STR`,21:`SPACE_BLOCK`,27:`SIZE`,28:`COLUMNS`,29:`id-block`,30:`end`,31:`NODE_ID`,34:`DIR`,35:`NODE_DSTART`,36:`NODE_DEND`,37:`BLOCK_ARROW_START`,38:`BLOCK_ARROW_END`,39:`classDef`,40:`CLASSDEF_ID`,41:`CLASSDEF_STYLEOPTS`,42:`DEFAULT`,43:`class`,44:`CLASSENTITY_IDS`,45:`STYLECLASS`,46:`style`,47:`STYLE_ENTITY_IDS`,48:`STYLE_DEFINITION_DATA`},productions_:[0,[3,1],[3,2],[3,2],[6,1],[6,1],[6,1],[9,3],[12,1],[12,1],[12,2],[12,2],[11,1],[11,2],[14,1],[14,4],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[19,3],[19,2],[19,1],[20,1],[22,4],[22,3],[26,1],[26,2],[33,1],[33,2],[32,3],[32,4],[23,3],[23,3],[24,3],[25,3]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 4:r.getLogger().debug(`Rule: separator (NL) `);break;case 5:r.getLogger().debug(`Rule: separator (Space) `);break;case 6:r.getLogger().debug(`Rule: separator (EOF) `);break;case 7:r.getLogger().debug(`Rule: hierarchy: `,a[s-1]),r.setHierarchy(a[s-1]);break;case 8:r.getLogger().debug(`Stop NL `);break;case 9:r.getLogger().debug(`Stop EOF `);break;case 10:r.getLogger().debug(`Stop NL2 `);break;case 11:r.getLogger().debug(`Stop EOF2 `);break;case 12:r.getLogger().debug(`Rule: statement: `,a[s]),typeof a[s].length==`number`?this.$=a[s]:this.$=[a[s]];break;case 13:r.getLogger().debug(`Rule: statement #2: `,a[s-1]),this.$=[a[s-1]].concat(a[s]);break;case 14:r.getLogger().debug(`Rule: link: `,a[s],e),this.$={edgeTypeStr:a[s],label:``};break;case 15:r.getLogger().debug(`Rule: LABEL link: `,a[s-3],a[s-1],a[s]),this.$={edgeTypeStr:a[s],label:a[s-1]};break;case 18:let t=parseInt(a[s]),n=r.generateId();this.$={id:n,type:`space`,label:``,width:t,children:[]};break;case 23:r.getLogger().debug(`Rule: (nodeStatement link node) `,a[s-2],a[s-1],a[s],` typestr: `,a[s-1].edgeTypeStr);let i=r.edgeStrToEdgeData(a[s-1].edgeTypeStr),o=r.edgeStrToEdgeStartData(a[s-1].edgeTypeStr),c=r.edgeStrToThickness(a[s-1].edgeTypeStr),l=r.edgeStrToPattern(a[s-1].edgeTypeStr);this.$=[{id:a[s-2].id,label:a[s-2].label,type:a[s-2].type,directions:a[s-2].directions},{id:a[s-2].id+`-`+a[s].id,start:a[s-2].id,end:a[s].id,label:a[s-1].label,type:`edge`,thickness:c,pattern:l,directions:a[s].directions,arrowTypeEnd:i,arrowTypeStart:o},{id:a[s].id,label:a[s].label,type:r.typeStr2Type(a[s].typeStr),directions:a[s].directions}];break;case 24:r.getLogger().debug(`Rule: nodeStatement (abc88 node size) `,a[s-1],a[s]),this.$={id:a[s-1].id,label:a[s-1].label,type:r.typeStr2Type(a[s-1].typeStr),directions:a[s-1].directions,widthInColumns:parseInt(a[s],10)};break;case 25:r.getLogger().debug(`Rule: nodeStatement (node) `,a[s]),this.$={id:a[s].id,label:a[s].label,type:r.typeStr2Type(a[s].typeStr),directions:a[s].directions,widthInColumns:1};break;case 26:r.getLogger().debug(`APA123`,this?this:`na`),r.getLogger().debug(`COLUMNS: `,a[s]),this.$={type:`column-setting`,columns:a[s]===`auto`?-1:parseInt(a[s])};break;case 27:r.getLogger().debug(`Rule: id-block statement : `,a[s-2],a[s-1]),r.generateId(),this.$={...a[s-2],type:`composite`,children:a[s-1]};break;case 28:r.getLogger().debug(`Rule: blockStatement : `,a[s-2],a[s-1],a[s]);let u=r.generateId();this.$={id:u,type:`composite`,label:``,children:a[s-1]};break;case 29:r.getLogger().debug(`Rule: node (NODE_ID separator): `,a[s]),this.$={id:a[s]};break;case 30:r.getLogger().debug(`Rule: node (NODE_ID nodeShapeNLabel separator): `,a[s-1],a[s]),this.$={id:a[s-1],label:a[s].label,typeStr:a[s].typeStr,directions:a[s].directions};break;case 31:r.getLogger().debug(`Rule: dirList: `,a[s]),this.$=[a[s]];break;case 32:r.getLogger().debug(`Rule: dirList: `,a[s-1],a[s]),this.$=[a[s-1]].concat(a[s]);break;case 33:r.getLogger().debug(`Rule: nodeShapeNLabel: `,a[s-2],a[s-1],a[s]),this.$={typeStr:a[s-2]+a[s],label:a[s-1]};break;case 34:r.getLogger().debug(`Rule: BLOCK_ARROW nodeShapeNLabel: `,a[s-3],a[s-2],` #3:`,a[s-1],a[s]),this.$={typeStr:a[s-3]+a[s],label:a[s-2],directions:a[s-1]};break;case 35:case 36:this.$={type:`classDef`,id:a[s-1].trim(),css:a[s].trim()};break;case 37:this.$={type:`applyClass`,id:a[s-1].trim(),styleClass:a[s].trim()};break;case 38:this.$={type:`applyStyles`,id:a[s-1].trim(),stylesStr:a[s].trim()};break}},`anonymous`),table:[{9:1,10:[1,2]},{1:[3]},{10:n,11:3,13:4,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:a,31:o,39:s,43:c,46:l},{8:[1,20]},t(u,[2,12],{13:4,19:5,20:6,22:8,23:9,24:10,25:11,26:12,11:21,10:n,21:r,28:i,29:a,31:o,39:s,43:c,46:l}),t(d,[2,16],{14:22,15:f,16:p}),t(d,[2,17]),t(d,[2,18]),t(d,[2,19]),t(d,[2,20]),t(d,[2,21]),t(d,[2,22]),t(m,[2,25],{27:[1,25]}),t(d,[2,26]),{19:26,26:12,31:o},{10:n,11:27,13:4,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:a,31:o,39:s,43:c,46:l},{40:[1,28],42:[1,29]},{44:[1,30]},{47:[1,31]},t(h,[2,29],{32:32,35:[1,33],37:[1,34]}),{1:[2,7]},t(u,[2,13]),{26:35,31:o},{31:[2,14]},{17:[1,36]},t(m,[2,24]),{10:n,11:37,13:4,14:22,15:f,16:p,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:a,31:o,39:s,43:c,46:l},{30:[1,38]},{41:[1,39]},{41:[1,40]},{45:[1,41]},{48:[1,42]},t(h,[2,30]),{18:[1,43]},{18:[1,44]},t(m,[2,23]),{18:[1,45]},{30:[1,46]},t(d,[2,28]),t(d,[2,35]),t(d,[2,36]),t(d,[2,37]),t(d,[2,38]),{36:[1,47]},{33:48,34:g},{15:[1,50]},t(d,[2,27]),t(h,[2,33]),{38:[1,51]},{33:52,34:g,38:[2,31]},{31:[2,15]},t(h,[2,34]),{38:[2,32]}],defaultActions:{20:[2,7],23:[2,14],50:[2,15],52:[2,32]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};_.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/c4Diagram-LMCZKHZV-DwxrqiYd.js b/.vercel/output/static/assets/c4Diagram-LMCZKHZV-B2PQ0JjZ.js similarity index 99% rename from .vercel/output/static/assets/c4Diagram-LMCZKHZV-DwxrqiYd.js rename to .vercel/output/static/assets/c4Diagram-LMCZKHZV-B2PQ0JjZ.js index 33ff5be..9beb0a0 100644 --- a/.vercel/output/static/assets/c4Diagram-LMCZKHZV-DwxrqiYd.js +++ b/.vercel/output/static/assets/c4Diagram-LMCZKHZV-B2PQ0JjZ.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{H as r,U as i,c as a,r as o,s,v as l,x as u,y as d,z as f}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as p}from"./dist-D9sYb5Oa.js";import{_ as m,n as h,r as g}from"./chunk-ICXQ74PX-fa5hHXws.js";import{a as _,s as v}from"./chunk-32BRIVSS-BtH22FN8.js";var y=p(),b=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,24],r=[1,25],i=[1,26],a=[1,27],o=[1,28],s=[1,63],l=[1,64],u=[1,65],d=[1,66],f=[1,67],p=[1,68],m=[1,69],h=[1,29],g=[1,30],_=[1,31],v=[1,32],y=[1,33],b=[1,34],x=[1,35],S=[1,36],C=[1,37],w=[1,38],T=[1,39],E=[1,40],D=[1,41],O=[1,42],k=[1,43],A=[1,44],j=[1,45],M=[1,46],N=[1,47],P=[1,48],F=[1,50],I=[1,51],L=[1,52],R=[1,53],z=[1,54],B=[1,55],V=[1,56],H=[1,57],ee=[1,58],te=[1,59],ne=[1,60],re=[14,42],ie=[14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],ae=[12,14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],U=[1,82],W=[1,83],G=[1,84],K=[1,85],q=[12,14,42],oe=[12,14,33,42],se=[12,14,33,42,76,77,79,80],ce=[12,33],le=[34,36,37,38,39,40,41,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],J={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,direction:5,direction_tb:6,direction_bt:7,direction_rl:8,direction_lr:9,graphConfig:10,C4_CONTEXT:11,NEWLINE:12,statements:13,EOF:14,C4_CONTAINER:15,C4_COMPONENT:16,C4_DYNAMIC:17,C4_DEPLOYMENT:18,otherStatements:19,diagramStatements:20,otherStatement:21,title:22,accDescription:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,boundaryStatement:29,boundaryStartStatement:30,boundaryStopStatement:31,boundaryStart:32,LBRACE:33,ENTERPRISE_BOUNDARY:34,attributes:35,SYSTEM_BOUNDARY:36,BOUNDARY:37,CONTAINER_BOUNDARY:38,NODE:39,NODE_L:40,NODE_R:41,RBRACE:42,diagramStatement:43,PERSON:44,PERSON_EXT:45,SYSTEM:46,SYSTEM_DB:47,SYSTEM_QUEUE:48,SYSTEM_EXT:49,SYSTEM_EXT_DB:50,SYSTEM_EXT_QUEUE:51,CONTAINER:52,CONTAINER_DB:53,CONTAINER_QUEUE:54,CONTAINER_EXT:55,CONTAINER_EXT_DB:56,CONTAINER_EXT_QUEUE:57,COMPONENT:58,COMPONENT_DB:59,COMPONENT_QUEUE:60,COMPONENT_EXT:61,COMPONENT_EXT_DB:62,COMPONENT_EXT_QUEUE:63,REL:64,BIREL:65,REL_U:66,REL_D:67,REL_L:68,REL_R:69,REL_B:70,REL_INDEX:71,UPDATE_EL_STYLE:72,UPDATE_REL_STYLE:73,UPDATE_LAYOUT_CONFIG:74,attribute:75,STR:76,STR_KEY:77,STR_VALUE:78,ATTRIBUTE:79,ATTRIBUTE_EMPTY:80,$accept:0,$end:1},terminals_:{2:`error`,6:`direction_tb`,7:`direction_bt`,8:`direction_rl`,9:`direction_lr`,11:`C4_CONTEXT`,12:`NEWLINE`,14:`EOF`,15:`C4_CONTAINER`,16:`C4_COMPONENT`,17:`C4_DYNAMIC`,18:`C4_DEPLOYMENT`,22:`title`,23:`accDescription`,24:`acc_title`,25:`acc_title_value`,26:`acc_descr`,27:`acc_descr_value`,28:`acc_descr_multiline_value`,33:`LBRACE`,34:`ENTERPRISE_BOUNDARY`,36:`SYSTEM_BOUNDARY`,37:`BOUNDARY`,38:`CONTAINER_BOUNDARY`,39:`NODE`,40:`NODE_L`,41:`NODE_R`,42:`RBRACE`,44:`PERSON`,45:`PERSON_EXT`,46:`SYSTEM`,47:`SYSTEM_DB`,48:`SYSTEM_QUEUE`,49:`SYSTEM_EXT`,50:`SYSTEM_EXT_DB`,51:`SYSTEM_EXT_QUEUE`,52:`CONTAINER`,53:`CONTAINER_DB`,54:`CONTAINER_QUEUE`,55:`CONTAINER_EXT`,56:`CONTAINER_EXT_DB`,57:`CONTAINER_EXT_QUEUE`,58:`COMPONENT`,59:`COMPONENT_DB`,60:`COMPONENT_QUEUE`,61:`COMPONENT_EXT`,62:`COMPONENT_EXT_DB`,63:`COMPONENT_EXT_QUEUE`,64:`REL`,65:`BIREL`,66:`REL_U`,67:`REL_D`,68:`REL_L`,69:`REL_R`,70:`REL_B`,71:`REL_INDEX`,72:`UPDATE_EL_STYLE`,73:`UPDATE_REL_STYLE`,74:`UPDATE_LAYOUT_CONFIG`,76:`STR`,77:`STR_KEY`,78:`STR_VALUE`,79:`ATTRIBUTE`,80:`ATTRIBUTE_EMPTY`},productions_:[0,[3,1],[3,1],[5,1],[5,1],[5,1],[5,1],[4,1],[10,4],[10,4],[10,4],[10,4],[10,4],[13,1],[13,1],[13,2],[19,1],[19,2],[19,3],[21,1],[21,1],[21,2],[21,2],[21,1],[29,3],[30,3],[30,3],[30,4],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[31,1],[20,1],[20,2],[20,3],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,1],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[35,1],[35,2],[75,1],[75,2],[75,1],[75,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 3:r.setDirection(`TB`);break;case 4:r.setDirection(`BT`);break;case 5:r.setDirection(`RL`);break;case 6:r.setDirection(`LR`);break;case 8:case 9:case 10:case 11:case 12:r.setC4Type(a[s-3]);break;case 19:r.setTitle(a[s].substring(6)),this.$=a[s].substring(6);break;case 20:r.setAccDescription(a[s].substring(15)),this.$=a[s].substring(15);break;case 21:this.$=a[s].trim(),r.setTitle(this.$);break;case 22:case 23:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 28:a[s].splice(2,0,`ENTERPRISE`),r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 29:a[s].splice(2,0,`SYSTEM`),r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 30:r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 31:a[s].splice(2,0,`CONTAINER`),r.addContainerBoundary(...a[s]),this.$=a[s];break;case 32:r.addDeploymentNode(`node`,...a[s]),this.$=a[s];break;case 33:r.addDeploymentNode(`nodeL`,...a[s]),this.$=a[s];break;case 34:r.addDeploymentNode(`nodeR`,...a[s]),this.$=a[s];break;case 35:r.popBoundaryParseStack();break;case 39:r.addPersonOrSystem(`person`,...a[s]),this.$=a[s];break;case 40:r.addPersonOrSystem(`external_person`,...a[s]),this.$=a[s];break;case 41:r.addPersonOrSystem(`system`,...a[s]),this.$=a[s];break;case 42:r.addPersonOrSystem(`system_db`,...a[s]),this.$=a[s];break;case 43:r.addPersonOrSystem(`system_queue`,...a[s]),this.$=a[s];break;case 44:r.addPersonOrSystem(`external_system`,...a[s]),this.$=a[s];break;case 45:r.addPersonOrSystem(`external_system_db`,...a[s]),this.$=a[s];break;case 46:r.addPersonOrSystem(`external_system_queue`,...a[s]),this.$=a[s];break;case 47:r.addContainer(`container`,...a[s]),this.$=a[s];break;case 48:r.addContainer(`container_db`,...a[s]),this.$=a[s];break;case 49:r.addContainer(`container_queue`,...a[s]),this.$=a[s];break;case 50:r.addContainer(`external_container`,...a[s]),this.$=a[s];break;case 51:r.addContainer(`external_container_db`,...a[s]),this.$=a[s];break;case 52:r.addContainer(`external_container_queue`,...a[s]),this.$=a[s];break;case 53:r.addComponent(`component`,...a[s]),this.$=a[s];break;case 54:r.addComponent(`component_db`,...a[s]),this.$=a[s];break;case 55:r.addComponent(`component_queue`,...a[s]),this.$=a[s];break;case 56:r.addComponent(`external_component`,...a[s]),this.$=a[s];break;case 57:r.addComponent(`external_component_db`,...a[s]),this.$=a[s];break;case 58:r.addComponent(`external_component_queue`,...a[s]),this.$=a[s];break;case 60:r.addRel(`rel`,...a[s]),this.$=a[s];break;case 61:r.addRel(`birel`,...a[s]),this.$=a[s];break;case 62:r.addRel(`rel_u`,...a[s]),this.$=a[s];break;case 63:r.addRel(`rel_d`,...a[s]),this.$=a[s];break;case 64:r.addRel(`rel_l`,...a[s]),this.$=a[s];break;case 65:r.addRel(`rel_r`,...a[s]),this.$=a[s];break;case 66:r.addRel(`rel_b`,...a[s]),this.$=a[s];break;case 67:a[s].splice(0,1),r.addRel(`rel`,...a[s]),this.$=a[s];break;case 68:r.updateElStyle(`update_el_style`,...a[s]),this.$=a[s];break;case 69:r.updateRelStyle(`update_rel_style`,...a[s]),this.$=a[s];break;case 70:r.updateLayoutConfig(`update_layout_config`,...a[s]),this.$=a[s];break;case 71:this.$=[a[s]];break;case 72:a[s].unshift(a[s-1]),this.$=a[s];break;case 73:case 75:this.$=a[s].trim();break;case 74:let e={};e[a[s-1].trim()]=a[s].trim(),this.$=e;break;case 76:this.$=``;break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],7:[1,6],8:[1,7],9:[1,8],10:4,11:[1,9],15:[1,10],16:[1,11],17:[1,12],18:[1,13]},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,7]},{1:[2,3]},{1:[2,4]},{1:[2,5]},{1:[2,6]},{12:[1,14]},{12:[1,15]},{12:[1,16]},{12:[1,17]},{12:[1,18]},{13:19,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:70,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:71,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:72,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:73,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{14:[1,74]},t(re,[2,13],{43:23,29:49,30:61,32:62,20:75,34:s,36:l,37:u,38:d,39:f,40:p,41:m,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne}),t(re,[2,14]),t(ie,[2,16],{12:[1,76]}),t(re,[2,36],{12:[1,77]}),t(ae,[2,19]),t(ae,[2,20]),{25:[1,78]},{27:[1,79]},t(ae,[2,23]),{35:80,75:81,76:U,77:W,79:G,80:K},{35:86,75:81,76:U,77:W,79:G,80:K},{35:87,75:81,76:U,77:W,79:G,80:K},{35:88,75:81,76:U,77:W,79:G,80:K},{35:89,75:81,76:U,77:W,79:G,80:K},{35:90,75:81,76:U,77:W,79:G,80:K},{35:91,75:81,76:U,77:W,79:G,80:K},{35:92,75:81,76:U,77:W,79:G,80:K},{35:93,75:81,76:U,77:W,79:G,80:K},{35:94,75:81,76:U,77:W,79:G,80:K},{35:95,75:81,76:U,77:W,79:G,80:K},{35:96,75:81,76:U,77:W,79:G,80:K},{35:97,75:81,76:U,77:W,79:G,80:K},{35:98,75:81,76:U,77:W,79:G,80:K},{35:99,75:81,76:U,77:W,79:G,80:K},{35:100,75:81,76:U,77:W,79:G,80:K},{35:101,75:81,76:U,77:W,79:G,80:K},{35:102,75:81,76:U,77:W,79:G,80:K},{35:103,75:81,76:U,77:W,79:G,80:K},{35:104,75:81,76:U,77:W,79:G,80:K},t(q,[2,59]),{35:105,75:81,76:U,77:W,79:G,80:K},{35:106,75:81,76:U,77:W,79:G,80:K},{35:107,75:81,76:U,77:W,79:G,80:K},{35:108,75:81,76:U,77:W,79:G,80:K},{35:109,75:81,76:U,77:W,79:G,80:K},{35:110,75:81,76:U,77:W,79:G,80:K},{35:111,75:81,76:U,77:W,79:G,80:K},{35:112,75:81,76:U,77:W,79:G,80:K},{35:113,75:81,76:U,77:W,79:G,80:K},{35:114,75:81,76:U,77:W,79:G,80:K},{35:115,75:81,76:U,77:W,79:G,80:K},{20:116,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{12:[1,118],33:[1,117]},{35:119,75:81,76:U,77:W,79:G,80:K},{35:120,75:81,76:U,77:W,79:G,80:K},{35:121,75:81,76:U,77:W,79:G,80:K},{35:122,75:81,76:U,77:W,79:G,80:K},{35:123,75:81,76:U,77:W,79:G,80:K},{35:124,75:81,76:U,77:W,79:G,80:K},{35:125,75:81,76:U,77:W,79:G,80:K},{14:[1,126]},{14:[1,127]},{14:[1,128]},{14:[1,129]},{1:[2,8]},t(re,[2,15]),t(ie,[2,17],{21:22,19:130,22:n,23:r,24:i,26:a,28:o}),t(re,[2,37],{19:20,20:21,21:22,43:23,29:49,30:61,32:62,13:131,22:n,23:r,24:i,26:a,28:o,34:s,36:l,37:u,38:d,39:f,40:p,41:m,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne}),t(ae,[2,21]),t(ae,[2,22]),t(q,[2,39]),t(oe,[2,71],{75:81,35:132,76:U,77:W,79:G,80:K}),t(se,[2,73]),{78:[1,133]},t(se,[2,75]),t(se,[2,76]),t(q,[2,40]),t(q,[2,41]),t(q,[2,42]),t(q,[2,43]),t(q,[2,44]),t(q,[2,45]),t(q,[2,46]),t(q,[2,47]),t(q,[2,48]),t(q,[2,49]),t(q,[2,50]),t(q,[2,51]),t(q,[2,52]),t(q,[2,53]),t(q,[2,54]),t(q,[2,55]),t(q,[2,56]),t(q,[2,57]),t(q,[2,58]),t(q,[2,60]),t(q,[2,61]),t(q,[2,62]),t(q,[2,63]),t(q,[2,64]),t(q,[2,65]),t(q,[2,66]),t(q,[2,67]),t(q,[2,68]),t(q,[2,69]),t(q,[2,70]),{31:134,42:[1,135]},{12:[1,136]},{33:[1,137]},t(ce,[2,28]),t(ce,[2,29]),t(ce,[2,30]),t(ce,[2,31]),t(ce,[2,32]),t(ce,[2,33]),t(ce,[2,34]),{1:[2,9]},{1:[2,10]},{1:[2,11]},{1:[2,12]},t(ie,[2,18]),t(re,[2,38]),t(oe,[2,72]),t(se,[2,74]),t(q,[2,24]),t(q,[2,35]),t(le,[2,25]),t(le,[2,26],{12:[1,138]}),t(le,[2,27])],defaultActions:{2:[2,1],3:[2,2],4:[2,7],5:[2,3],6:[2,4],7:[2,5],8:[2,6],74:[2,8],126:[2,9],127:[2,10],128:[2,11],129:[2,12]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,l=``,u=0,d=0,f=0,p=2,m=1,h=o.slice.call(arguments,1),g=Object.create(this.lexer),_={yy:{}};for(var v in this.yy)Object.prototype.hasOwnProperty.call(this.yy,v)&&(_.yy[v]=this.yy[v]);g.setInput(t,_.yy),_.yy.lexer=g,_.yy.parser=this,g.yylloc===void 0&&(g.yylloc={});var y=g.yylloc;o.push(y);var b=g.options&&g.options.ranges;typeof _.yy.parseError==`function`?this.parseError=_.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function x(e){r.length-=2*e,a.length-=e,o.length-=e}e(x,`popStack`);function S(){var e=i.pop()||g.lex()||m;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(S,`lex`);for(var C,w,T,E,D,O={},k,A,j,M;;){if(T=r[r.length-1],this.defaultActions[T]?E=this.defaultActions[T]:(C??=S(),E=s[T]&&s[T][C]),E===void 0||!E.length||!E[0]){var N=``;for(k in M=[],s[T])this.terminals_[k]&&k>p&&M.push(`'`+this.terminals_[k]+`'`);N=g.showPosition?`Parse error on line `+(u+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{H as r,U as i,c as a,r as o,s,v as l,x as u,y as d,z as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as p}from"./dist-qx0Iv9vM.js";import{_ as m,n as h,r as g}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{a as _,s as v}from"./chunk-32BRIVSS-DWU3ezKg.js";var y=p(),b=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,24],r=[1,25],i=[1,26],a=[1,27],o=[1,28],s=[1,63],l=[1,64],u=[1,65],d=[1,66],f=[1,67],p=[1,68],m=[1,69],h=[1,29],g=[1,30],_=[1,31],v=[1,32],y=[1,33],b=[1,34],x=[1,35],S=[1,36],C=[1,37],w=[1,38],T=[1,39],E=[1,40],D=[1,41],O=[1,42],k=[1,43],A=[1,44],j=[1,45],M=[1,46],N=[1,47],P=[1,48],F=[1,50],I=[1,51],L=[1,52],R=[1,53],z=[1,54],B=[1,55],V=[1,56],H=[1,57],ee=[1,58],te=[1,59],ne=[1,60],re=[14,42],ie=[14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],ae=[12,14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],U=[1,82],W=[1,83],G=[1,84],K=[1,85],q=[12,14,42],oe=[12,14,33,42],se=[12,14,33,42,76,77,79,80],ce=[12,33],le=[34,36,37,38,39,40,41,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],J={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,direction:5,direction_tb:6,direction_bt:7,direction_rl:8,direction_lr:9,graphConfig:10,C4_CONTEXT:11,NEWLINE:12,statements:13,EOF:14,C4_CONTAINER:15,C4_COMPONENT:16,C4_DYNAMIC:17,C4_DEPLOYMENT:18,otherStatements:19,diagramStatements:20,otherStatement:21,title:22,accDescription:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,boundaryStatement:29,boundaryStartStatement:30,boundaryStopStatement:31,boundaryStart:32,LBRACE:33,ENTERPRISE_BOUNDARY:34,attributes:35,SYSTEM_BOUNDARY:36,BOUNDARY:37,CONTAINER_BOUNDARY:38,NODE:39,NODE_L:40,NODE_R:41,RBRACE:42,diagramStatement:43,PERSON:44,PERSON_EXT:45,SYSTEM:46,SYSTEM_DB:47,SYSTEM_QUEUE:48,SYSTEM_EXT:49,SYSTEM_EXT_DB:50,SYSTEM_EXT_QUEUE:51,CONTAINER:52,CONTAINER_DB:53,CONTAINER_QUEUE:54,CONTAINER_EXT:55,CONTAINER_EXT_DB:56,CONTAINER_EXT_QUEUE:57,COMPONENT:58,COMPONENT_DB:59,COMPONENT_QUEUE:60,COMPONENT_EXT:61,COMPONENT_EXT_DB:62,COMPONENT_EXT_QUEUE:63,REL:64,BIREL:65,REL_U:66,REL_D:67,REL_L:68,REL_R:69,REL_B:70,REL_INDEX:71,UPDATE_EL_STYLE:72,UPDATE_REL_STYLE:73,UPDATE_LAYOUT_CONFIG:74,attribute:75,STR:76,STR_KEY:77,STR_VALUE:78,ATTRIBUTE:79,ATTRIBUTE_EMPTY:80,$accept:0,$end:1},terminals_:{2:`error`,6:`direction_tb`,7:`direction_bt`,8:`direction_rl`,9:`direction_lr`,11:`C4_CONTEXT`,12:`NEWLINE`,14:`EOF`,15:`C4_CONTAINER`,16:`C4_COMPONENT`,17:`C4_DYNAMIC`,18:`C4_DEPLOYMENT`,22:`title`,23:`accDescription`,24:`acc_title`,25:`acc_title_value`,26:`acc_descr`,27:`acc_descr_value`,28:`acc_descr_multiline_value`,33:`LBRACE`,34:`ENTERPRISE_BOUNDARY`,36:`SYSTEM_BOUNDARY`,37:`BOUNDARY`,38:`CONTAINER_BOUNDARY`,39:`NODE`,40:`NODE_L`,41:`NODE_R`,42:`RBRACE`,44:`PERSON`,45:`PERSON_EXT`,46:`SYSTEM`,47:`SYSTEM_DB`,48:`SYSTEM_QUEUE`,49:`SYSTEM_EXT`,50:`SYSTEM_EXT_DB`,51:`SYSTEM_EXT_QUEUE`,52:`CONTAINER`,53:`CONTAINER_DB`,54:`CONTAINER_QUEUE`,55:`CONTAINER_EXT`,56:`CONTAINER_EXT_DB`,57:`CONTAINER_EXT_QUEUE`,58:`COMPONENT`,59:`COMPONENT_DB`,60:`COMPONENT_QUEUE`,61:`COMPONENT_EXT`,62:`COMPONENT_EXT_DB`,63:`COMPONENT_EXT_QUEUE`,64:`REL`,65:`BIREL`,66:`REL_U`,67:`REL_D`,68:`REL_L`,69:`REL_R`,70:`REL_B`,71:`REL_INDEX`,72:`UPDATE_EL_STYLE`,73:`UPDATE_REL_STYLE`,74:`UPDATE_LAYOUT_CONFIG`,76:`STR`,77:`STR_KEY`,78:`STR_VALUE`,79:`ATTRIBUTE`,80:`ATTRIBUTE_EMPTY`},productions_:[0,[3,1],[3,1],[5,1],[5,1],[5,1],[5,1],[4,1],[10,4],[10,4],[10,4],[10,4],[10,4],[13,1],[13,1],[13,2],[19,1],[19,2],[19,3],[21,1],[21,1],[21,2],[21,2],[21,1],[29,3],[30,3],[30,3],[30,4],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[31,1],[20,1],[20,2],[20,3],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,1],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[35,1],[35,2],[75,1],[75,2],[75,1],[75,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 3:r.setDirection(`TB`);break;case 4:r.setDirection(`BT`);break;case 5:r.setDirection(`RL`);break;case 6:r.setDirection(`LR`);break;case 8:case 9:case 10:case 11:case 12:r.setC4Type(a[s-3]);break;case 19:r.setTitle(a[s].substring(6)),this.$=a[s].substring(6);break;case 20:r.setAccDescription(a[s].substring(15)),this.$=a[s].substring(15);break;case 21:this.$=a[s].trim(),r.setTitle(this.$);break;case 22:case 23:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 28:a[s].splice(2,0,`ENTERPRISE`),r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 29:a[s].splice(2,0,`SYSTEM`),r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 30:r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 31:a[s].splice(2,0,`CONTAINER`),r.addContainerBoundary(...a[s]),this.$=a[s];break;case 32:r.addDeploymentNode(`node`,...a[s]),this.$=a[s];break;case 33:r.addDeploymentNode(`nodeL`,...a[s]),this.$=a[s];break;case 34:r.addDeploymentNode(`nodeR`,...a[s]),this.$=a[s];break;case 35:r.popBoundaryParseStack();break;case 39:r.addPersonOrSystem(`person`,...a[s]),this.$=a[s];break;case 40:r.addPersonOrSystem(`external_person`,...a[s]),this.$=a[s];break;case 41:r.addPersonOrSystem(`system`,...a[s]),this.$=a[s];break;case 42:r.addPersonOrSystem(`system_db`,...a[s]),this.$=a[s];break;case 43:r.addPersonOrSystem(`system_queue`,...a[s]),this.$=a[s];break;case 44:r.addPersonOrSystem(`external_system`,...a[s]),this.$=a[s];break;case 45:r.addPersonOrSystem(`external_system_db`,...a[s]),this.$=a[s];break;case 46:r.addPersonOrSystem(`external_system_queue`,...a[s]),this.$=a[s];break;case 47:r.addContainer(`container`,...a[s]),this.$=a[s];break;case 48:r.addContainer(`container_db`,...a[s]),this.$=a[s];break;case 49:r.addContainer(`container_queue`,...a[s]),this.$=a[s];break;case 50:r.addContainer(`external_container`,...a[s]),this.$=a[s];break;case 51:r.addContainer(`external_container_db`,...a[s]),this.$=a[s];break;case 52:r.addContainer(`external_container_queue`,...a[s]),this.$=a[s];break;case 53:r.addComponent(`component`,...a[s]),this.$=a[s];break;case 54:r.addComponent(`component_db`,...a[s]),this.$=a[s];break;case 55:r.addComponent(`component_queue`,...a[s]),this.$=a[s];break;case 56:r.addComponent(`external_component`,...a[s]),this.$=a[s];break;case 57:r.addComponent(`external_component_db`,...a[s]),this.$=a[s];break;case 58:r.addComponent(`external_component_queue`,...a[s]),this.$=a[s];break;case 60:r.addRel(`rel`,...a[s]),this.$=a[s];break;case 61:r.addRel(`birel`,...a[s]),this.$=a[s];break;case 62:r.addRel(`rel_u`,...a[s]),this.$=a[s];break;case 63:r.addRel(`rel_d`,...a[s]),this.$=a[s];break;case 64:r.addRel(`rel_l`,...a[s]),this.$=a[s];break;case 65:r.addRel(`rel_r`,...a[s]),this.$=a[s];break;case 66:r.addRel(`rel_b`,...a[s]),this.$=a[s];break;case 67:a[s].splice(0,1),r.addRel(`rel`,...a[s]),this.$=a[s];break;case 68:r.updateElStyle(`update_el_style`,...a[s]),this.$=a[s];break;case 69:r.updateRelStyle(`update_rel_style`,...a[s]),this.$=a[s];break;case 70:r.updateLayoutConfig(`update_layout_config`,...a[s]),this.$=a[s];break;case 71:this.$=[a[s]];break;case 72:a[s].unshift(a[s-1]),this.$=a[s];break;case 73:case 75:this.$=a[s].trim();break;case 74:let e={};e[a[s-1].trim()]=a[s].trim(),this.$=e;break;case 76:this.$=``;break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],7:[1,6],8:[1,7],9:[1,8],10:4,11:[1,9],15:[1,10],16:[1,11],17:[1,12],18:[1,13]},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,7]},{1:[2,3]},{1:[2,4]},{1:[2,5]},{1:[2,6]},{12:[1,14]},{12:[1,15]},{12:[1,16]},{12:[1,17]},{12:[1,18]},{13:19,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:70,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:71,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:72,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:73,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{14:[1,74]},t(re,[2,13],{43:23,29:49,30:61,32:62,20:75,34:s,36:l,37:u,38:d,39:f,40:p,41:m,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne}),t(re,[2,14]),t(ie,[2,16],{12:[1,76]}),t(re,[2,36],{12:[1,77]}),t(ae,[2,19]),t(ae,[2,20]),{25:[1,78]},{27:[1,79]},t(ae,[2,23]),{35:80,75:81,76:U,77:W,79:G,80:K},{35:86,75:81,76:U,77:W,79:G,80:K},{35:87,75:81,76:U,77:W,79:G,80:K},{35:88,75:81,76:U,77:W,79:G,80:K},{35:89,75:81,76:U,77:W,79:G,80:K},{35:90,75:81,76:U,77:W,79:G,80:K},{35:91,75:81,76:U,77:W,79:G,80:K},{35:92,75:81,76:U,77:W,79:G,80:K},{35:93,75:81,76:U,77:W,79:G,80:K},{35:94,75:81,76:U,77:W,79:G,80:K},{35:95,75:81,76:U,77:W,79:G,80:K},{35:96,75:81,76:U,77:W,79:G,80:K},{35:97,75:81,76:U,77:W,79:G,80:K},{35:98,75:81,76:U,77:W,79:G,80:K},{35:99,75:81,76:U,77:W,79:G,80:K},{35:100,75:81,76:U,77:W,79:G,80:K},{35:101,75:81,76:U,77:W,79:G,80:K},{35:102,75:81,76:U,77:W,79:G,80:K},{35:103,75:81,76:U,77:W,79:G,80:K},{35:104,75:81,76:U,77:W,79:G,80:K},t(q,[2,59]),{35:105,75:81,76:U,77:W,79:G,80:K},{35:106,75:81,76:U,77:W,79:G,80:K},{35:107,75:81,76:U,77:W,79:G,80:K},{35:108,75:81,76:U,77:W,79:G,80:K},{35:109,75:81,76:U,77:W,79:G,80:K},{35:110,75:81,76:U,77:W,79:G,80:K},{35:111,75:81,76:U,77:W,79:G,80:K},{35:112,75:81,76:U,77:W,79:G,80:K},{35:113,75:81,76:U,77:W,79:G,80:K},{35:114,75:81,76:U,77:W,79:G,80:K},{35:115,75:81,76:U,77:W,79:G,80:K},{20:116,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{12:[1,118],33:[1,117]},{35:119,75:81,76:U,77:W,79:G,80:K},{35:120,75:81,76:U,77:W,79:G,80:K},{35:121,75:81,76:U,77:W,79:G,80:K},{35:122,75:81,76:U,77:W,79:G,80:K},{35:123,75:81,76:U,77:W,79:G,80:K},{35:124,75:81,76:U,77:W,79:G,80:K},{35:125,75:81,76:U,77:W,79:G,80:K},{14:[1,126]},{14:[1,127]},{14:[1,128]},{14:[1,129]},{1:[2,8]},t(re,[2,15]),t(ie,[2,17],{21:22,19:130,22:n,23:r,24:i,26:a,28:o}),t(re,[2,37],{19:20,20:21,21:22,43:23,29:49,30:61,32:62,13:131,22:n,23:r,24:i,26:a,28:o,34:s,36:l,37:u,38:d,39:f,40:p,41:m,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne}),t(ae,[2,21]),t(ae,[2,22]),t(q,[2,39]),t(oe,[2,71],{75:81,35:132,76:U,77:W,79:G,80:K}),t(se,[2,73]),{78:[1,133]},t(se,[2,75]),t(se,[2,76]),t(q,[2,40]),t(q,[2,41]),t(q,[2,42]),t(q,[2,43]),t(q,[2,44]),t(q,[2,45]),t(q,[2,46]),t(q,[2,47]),t(q,[2,48]),t(q,[2,49]),t(q,[2,50]),t(q,[2,51]),t(q,[2,52]),t(q,[2,53]),t(q,[2,54]),t(q,[2,55]),t(q,[2,56]),t(q,[2,57]),t(q,[2,58]),t(q,[2,60]),t(q,[2,61]),t(q,[2,62]),t(q,[2,63]),t(q,[2,64]),t(q,[2,65]),t(q,[2,66]),t(q,[2,67]),t(q,[2,68]),t(q,[2,69]),t(q,[2,70]),{31:134,42:[1,135]},{12:[1,136]},{33:[1,137]},t(ce,[2,28]),t(ce,[2,29]),t(ce,[2,30]),t(ce,[2,31]),t(ce,[2,32]),t(ce,[2,33]),t(ce,[2,34]),{1:[2,9]},{1:[2,10]},{1:[2,11]},{1:[2,12]},t(ie,[2,18]),t(re,[2,38]),t(oe,[2,72]),t(se,[2,74]),t(q,[2,24]),t(q,[2,35]),t(le,[2,25]),t(le,[2,26],{12:[1,138]}),t(le,[2,27])],defaultActions:{2:[2,1],3:[2,2],4:[2,7],5:[2,3],6:[2,4],7:[2,5],8:[2,6],74:[2,8],126:[2,9],127:[2,10],128:[2,11],129:[2,12]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,l=``,u=0,d=0,f=0,p=2,m=1,h=o.slice.call(arguments,1),g=Object.create(this.lexer),_={yy:{}};for(var v in this.yy)Object.prototype.hasOwnProperty.call(this.yy,v)&&(_.yy[v]=this.yy[v]);g.setInput(t,_.yy),_.yy.lexer=g,_.yy.parser=this,g.yylloc===void 0&&(g.yylloc={});var y=g.yylloc;o.push(y);var b=g.options&&g.options.ranges;typeof _.yy.parseError==`function`?this.parseError=_.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function x(e){r.length-=2*e,a.length-=e,o.length-=e}e(x,`popStack`);function S(){var e=i.pop()||g.lex()||m;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(S,`lex`);for(var C,w,T,E,D,O={},k,A,j,M;;){if(T=r[r.length-1],this.defaultActions[T]?E=this.defaultActions[T]:(C??=S(),E=s[T]&&s[T][C]),E===void 0||!E.length||!E[0]){var N=``;for(k in M=[],s[T])this.terminals_[k]&&k>p&&M.push(`'`+this.terminals_[k]+`'`);N=g.showPosition?`Parse error on line `+(u+1)+`: `+g.showPosition()+` Expecting `+M.join(`, `)+`, got '`+(this.terminals_[C]||C)+`'`:`Parse error on line `+(u+1)+`: Unexpected `+(C==m?`end of input`:`'`+(this.terminals_[C]||C)+`'`),this.parseError(N,{text:g.match,token:this.terminals_[C]||C,line:g.yylineno,loc:y,expected:M})}if(E[0]instanceof Array&&E.length>1)throw Error(`Parse Error: multiple actions possible at state: `+T+`, token: `+C);switch(E[0]){case 1:r.push(C),a.push(g.yytext),o.push(g.yylloc),r.push(E[1]),C=null,w?(C=w,w=null):(d=g.yyleng,l=g.yytext,u=g.yylineno,y=g.yylloc,f>0&&f--);break;case 2:if(A=this.productions_[E[1]][1],O.$=a[a.length-A],O._$={first_line:o[o.length-(A||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(A||1)].first_column,last_column:o[o.length-1].last_column},b&&(O._$.range=[o[o.length-(A||1)].range[0],o[o.length-1].range[1]]),D=this.performAction.apply(O,[l,d,u,_.yy,E[1],a,o].concat(h)),D!==void 0)return D;A&&(r=r.slice(0,-1*A*2),a=a.slice(0,-1*A),o=o.slice(0,-1*A)),r.push(this.productions_[E[1]][0]),a.push(O.$),o.push(O._$),j=s[r[r.length-2]][r[r.length-1]],r.push(j);break;case 3:return!0}}return!0},`parse`)};J.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/channel-C4fgBBJ4.js b/.vercel/output/static/assets/channel-C4fgBBJ4.js new file mode 100644 index 0000000..8e63e6e --- /dev/null +++ b/.vercel/output/static/assets/channel-C4fgBBJ4.js @@ -0,0 +1 @@ +import{at as e,ot as t}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var n=(n,r)=>t.lang.round(e.parse(n)[r]);export{n as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/channel-DA-EZjf8.js b/.vercel/output/static/assets/channel-DA-EZjf8.js deleted file mode 100644 index 728209c..0000000 --- a/.vercel/output/static/assets/channel-DA-EZjf8.js +++ /dev/null @@ -1 +0,0 @@ -import{at as e,ot as t}from"./chunk-WYO6CB5R-ajGU-pWR.js";var n=(n,r)=>t.lang.round(e.parse(n)[r]);export{n as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-32BRIVSS-BtH22FN8.js b/.vercel/output/static/assets/chunk-32BRIVSS-DWU3ezKg.js similarity index 93% rename from .vercel/output/static/assets/chunk-32BRIVSS-BtH22FN8.js rename to .vercel/output/static/assets/chunk-32BRIVSS-DWU3ezKg.js index 5c894ed..4680930 100644 --- a/.vercel/output/static/assets/chunk-32BRIVSS-BtH22FN8.js +++ b/.vercel/output/static/assets/chunk-32BRIVSS-DWU3ezKg.js @@ -1 +1 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-_wZywoZs.js";import{j as n}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as r}from"./dist-D9sYb5Oa.js";var i=r(),a=e((e,t)=>{let n=e.append(`rect`);if(n.attr(`x`,t.x),n.attr(`y`,t.y),n.attr(`fill`,t.fill),n.attr(`stroke`,t.stroke),n.attr(`width`,t.width),n.attr(`height`,t.height),t.name&&n.attr(`name`,t.name),t.rx&&n.attr(`rx`,t.rx),t.ry&&n.attr(`ry`,t.ry),t.attrs!==void 0)for(let e in t.attrs)n.attr(e,t.attrs[e]);return t.class&&n.attr(`class`,t.class),n},`drawRect`),o=e((e,t)=>{a(e,{x:t.startx,y:t.starty,width:t.stopx-t.startx,height:t.stopy-t.starty,fill:t.fill,stroke:t.stroke,class:`rect`}).lower()},`drawBackgroundRect`),s=e((e,t)=>{let r=t.text.replace(n,` `),i=e.append(`text`);i.attr(`x`,t.x),i.attr(`y`,t.y),i.attr(`class`,`legend`),i.style(`text-anchor`,t.anchor),t.class&&i.attr(`class`,t.class);let a=i.append(`tspan`);return a.attr(`x`,t.x+t.textMargin*2),a.text(r),i},`drawText`),c=e((e,t,n,r)=>{let a=e.append(`image`);a.attr(`x`,t),a.attr(`y`,n);let o=(0,i.sanitizeUrl)(r);a.attr(`xlink:href`,o)},`drawImage`),l=e((e,t,n,r)=>{let a=e.append(`use`);a.attr(`x`,t),a.attr(`y`,n);let o=(0,i.sanitizeUrl)(r);a.attr(`xlink:href`,`#${o}`)},`drawEmbeddedImage`),u=e(()=>({x:0,y:0,width:100,height:100,fill:`#EDF2AE`,stroke:`#666`,anchor:`start`,rx:0,ry:0}),`getNoteRect`),d=e(()=>({x:0,y:0,width:100,height:100,"text-anchor":`start`,style:`#666`,textMargin:0,rx:0,ry:0,tspan:!0}),`getTextObj`),f=e(()=>{let e=t(`.mermaidTooltip`);return e.empty()&&(e=t(`body`).append(`div`).attr(`class`,`mermaidTooltip`).style(`opacity`,0).style(`position`,`absolute`).style(`text-align`,`center`).style(`max-width`,`200px`).style(`padding`,`2px`).style(`font-size`,`12px`).style(`background`,`#ffffde`).style(`border`,`1px solid #333`).style(`border-radius`,`2px`).style(`pointer-events`,`none`).style(`z-index`,`100`)),e},`createTooltip`);export{a,d as c,c as i,o as n,s as o,l as r,u as s,f as t}; \ No newline at end of file +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{j as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as r}from"./dist-qx0Iv9vM.js";var i=r(),a=e((e,t)=>{let n=e.append(`rect`);if(n.attr(`x`,t.x),n.attr(`y`,t.y),n.attr(`fill`,t.fill),n.attr(`stroke`,t.stroke),n.attr(`width`,t.width),n.attr(`height`,t.height),t.name&&n.attr(`name`,t.name),t.rx&&n.attr(`rx`,t.rx),t.ry&&n.attr(`ry`,t.ry),t.attrs!==void 0)for(let e in t.attrs)n.attr(e,t.attrs[e]);return t.class&&n.attr(`class`,t.class),n},`drawRect`),o=e((e,t)=>{a(e,{x:t.startx,y:t.starty,width:t.stopx-t.startx,height:t.stopy-t.starty,fill:t.fill,stroke:t.stroke,class:`rect`}).lower()},`drawBackgroundRect`),s=e((e,t)=>{let r=t.text.replace(n,` `),i=e.append(`text`);i.attr(`x`,t.x),i.attr(`y`,t.y),i.attr(`class`,`legend`),i.style(`text-anchor`,t.anchor),t.class&&i.attr(`class`,t.class);let a=i.append(`tspan`);return a.attr(`x`,t.x+t.textMargin*2),a.text(r),i},`drawText`),c=e((e,t,n,r)=>{let a=e.append(`image`);a.attr(`x`,t),a.attr(`y`,n);let o=(0,i.sanitizeUrl)(r);a.attr(`xlink:href`,o)},`drawImage`),l=e((e,t,n,r)=>{let a=e.append(`use`);a.attr(`x`,t),a.attr(`y`,n);let o=(0,i.sanitizeUrl)(r);a.attr(`xlink:href`,`#${o}`)},`drawEmbeddedImage`),u=e(()=>({x:0,y:0,width:100,height:100,fill:`#EDF2AE`,stroke:`#666`,anchor:`start`,rx:0,ry:0}),`getNoteRect`),d=e(()=>({x:0,y:0,width:100,height:100,"text-anchor":`start`,style:`#666`,textMargin:0,rx:0,ry:0,tspan:!0}),`getTextObj`),f=e(()=>{let e=t(`.mermaidTooltip`);return e.empty()&&(e=t(`body`).append(`div`).attr(`class`,`mermaidTooltip`).style(`opacity`,0).style(`position`,`absolute`).style(`text-align`,`center`).style(`max-width`,`200px`).style(`padding`,`2px`).style(`font-size`,`12px`).style(`background`,`#ffffde`).style(`border`,`1px solid #333`).style(`border-radius`,`2px`).style(`pointer-events`,`none`).style(`z-index`,`100`)),e},`createTooltip`);export{a,d as c,c as i,o as n,s as o,l as r,u as s,f as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-52WLFC77-BBAyrLn9.js b/.vercel/output/static/assets/chunk-52WLFC77-BOCvVCX1.js similarity index 98% rename from .vercel/output/static/assets/chunk-52WLFC77-BBAyrLn9.js rename to .vercel/output/static/assets/chunk-52WLFC77-BOCvVCX1.js index 7c0f041..04c43e2 100644 --- a/.vercel/output/static/assets/chunk-52WLFC77-BBAyrLn9.js +++ b/.vercel/output/static/assets/chunk-52WLFC77-BOCvVCX1.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{T as r,b as i,x as a}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{$ as o,J as s,K as c,Q as l,X as u,Y as d,Z as f,et as p,g as m,nt as h,q as g,rt as _,tt as v,u as y}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as b}from"./line-CDW8hdKE.js";import{n as x}from"./chunk-Q4XR5HBZ-5srkZ5CC.js";import{i as S,n as ee,r as C,t as w}from"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as T}from"./chunk-OGEWGWER-Dr-qyYzn.js";import{i as E,n as D}from"./chunk-C7G6YPKG-DJfjwbsZ.js";import{t as te}from"./rough.esm-CSKSodPl.js";import{r as O}from"./chunk-ZGVPDNZ5-zo3h_nOA.js";var ne=e((e,t,n,r,i,a=!1,o)=>{t.arrowTypeStart&&j(e,`start`,t.arrowTypeStart,n,r,i,a,o),t.arrowTypeEnd&&j(e,`end`,t.arrowTypeEnd,n,r,i,a,o)},`addEdgeMarkers`),k={arrow_cross:{type:`cross`,fill:!1},arrow_point:{type:`point`,fill:!0},arrow_barb:{type:`barb`,fill:!0},arrow_barb_neo:{type:`barb`,fill:!0},arrow_circle:{type:`circle`,fill:!1},aggregation:{type:`aggregation`,fill:!1},extension:{type:`extension`,fill:!1},composition:{type:`composition`,fill:!0},dependency:{type:`dependency`,fill:!0},lollipop:{type:`lollipop`,fill:!1},only_one:{type:`onlyOne`,fill:!1},zero_or_one:{type:`zeroOrOne`,fill:!1},one_or_more:{type:`oneOrMore`,fill:!1},zero_or_more:{type:`zeroOrMore`,fill:!1},requirement_arrow:{type:`requirement_arrow`,fill:!1},requirement_contains:{type:`requirement_contains`,fill:!1}},A=[`cross`,`point`,`circle`,`lollipop`,`aggregation`,`extension`,`composition`,`dependency`,`barb`],j=e((e,n,r,i,a,o,s=!1,c)=>{let l=k[r],u=l&&A.includes(l.type);if(!l){t.warn(`Unknown arrow type: ${r}`);return}let d=`${a}_${o}-${l.type}${n===`start`?`Start`:`End`}${s&&u?`-margin`:``}`;if(c&&c.trim()!==``){let t=`${d}_${c.replace(/[^\dA-Za-z]/g,`_`)}`;if(!document.getElementById(t)){let e=document.getElementById(d);if(e){let n=e.cloneNode(!0);n.id=t,n.querySelectorAll(`path, circle, line`).forEach(e=>{e.setAttribute(`stroke`,c),l.fill&&e.setAttribute(`fill`,c)}),e.parentNode?.appendChild(n)}}e.attr(`marker-${n}`,`url(${i}#${t})`)}else e.attr(`marker-${n}`,`url(${i}#${d})`)},`addEdgeMarker`),re=e(e=>typeof e==`string`?e:a()?.flowchart?.curve,`resolveEdgeCurveType`),M=new Map,N=new Map,P=e(()=>{M.clear(),N.clear()},`clear`),F=e(e=>e?typeof e==`string`?e:e.reduce((e,t)=>e+`;`+t,``):``,`getLabelStyles`),I=e(async(e,i)=>{let o=a(),s=r(o),{labelStyles:c}=E(i);i.labelStyle=c;let l=e.insert(`g`).attr(`class`,`edgeLabel`),u=l.insert(`g`).attr(`class`,`label`).attr(`data-id`,i.id),d=i.labelType===`markdown`,f=await x(e,i.label,{style:F(i.labelStyle),useHtmlLabels:s,addSvgBackground:!0,isNode:!1,markdown:d,width:void 0},o);u.node().appendChild(f),t.info(`abc82`,i,i.labelType);let p=f.getBBox(),m=p;if(s){let e=f.children[0],t=n(f);p=e.getBoundingClientRect(),m=p,t.attr(`width`,p.width),t.attr(`height`,p.height)}else{let e=n(f).select(`text`).node();e&&typeof e.getBBox==`function`&&(m=e.getBBox())}u.attr(`transform`,w(m,s)),M.set(i.id,l),i.width=p.width,i.height=p.height;let h;if(i.startLabelLeft){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(r,i.startLabelLeft,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).startLeft=t,L(h,i.startLabelLeft)}if(i.startLabelRight){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(r,i.startLabelRight,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).startRight=t,L(h,i.startLabelRight)}if(i.endLabelLeft){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(t,i.endLabelLeft,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).endLeft=t,L(h,i.endLabelLeft)}if(i.endLabelRight){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(t,i.endLabelRight,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).endRight=t,L(h,i.endLabelRight)}return f},`insertEdgeLabel`);function L(e,t){r(a())&&e&&(e.style.width=t.length*9+`px`,e.style.height=`12px`)}e(L,`setTerminalWidth`);var R=e((e,n)=>{t.debug(`Moving label abc88 `,e.id,e.label,M.get(e.id),n);let r=n.updatedPath?n.updatedPath:n.originalPath,{subGraphTitleTotalMargin:i}=T(a());if(e.label){let a=M.get(e.id),o=e.x,s=e.y;if(r){let i=m.calcLabelPosition(r);t.debug(`Moving label `+e.label+` from (`,o,`,`,s,`) to (`,i.x,`,`,i.y,`) abc88`),n.updatedPath&&(o=i.x,s=i.y)}a.attr(`transform`,`translate(${o}, ${s+i/2})`)}if(e.startLabelLeft){let t=N.get(e.id).startLeft,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_left`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.startLabelRight){let t=N.get(e.id).startRight,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_right`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.endLabelLeft){let t=N.get(e.id).endLeft,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_left`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.endLabelRight){let t=N.get(e.id).endRight,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_right`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}},`positionEdgeLabel`),ie=e((e,t)=>{if(!e?.isLabelEdge||!e?.id?.endsWith(`-to-label`)||!Array.isArray(t)||t.length!==2)return t;let[n,r]=t,i=Math.abs(r.x-n.x),a=Math.abs(r.y-n.y);return i<.001||a<.001?t:a>=i?[n,{x:n.x,y:r.y},r]:[n,{x:r.x,y:n.y},r]},`orthogonalizeToLabelClippedPoints`),z=e((e,t)=>{let n=e.x,r=e.y,i=Math.abs(t.x-n),a=Math.abs(t.y-r),o=e.width/2,s=e.height/2;return i>=o||a>=s},`outsideNode`),B=e((e,n,r)=>{t.debug(`intersection calc abc89: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{T as r,b as i,x as a}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{$ as o,J as s,K as c,Q as l,X as u,Y as d,Z as f,et as p,g as m,nt as h,q as g,rt as _,tt as v,u as y}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as b}from"./line-b9Ala942.js";import{n as x}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{i as S,n as ee,r as C,t as w}from"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as T}from"./chunk-OGEWGWER-D-nWYRNR.js";import{i as E,n as D}from"./chunk-C7G6YPKG-DW-1jWUA.js";import{t as te}from"./rough.esm-CSKSodPl.js";import{r as O}from"./chunk-ZGVPDNZ5-DGInJAPD.js";var ne=e((e,t,n,r,i,a=!1,o)=>{t.arrowTypeStart&&j(e,`start`,t.arrowTypeStart,n,r,i,a,o),t.arrowTypeEnd&&j(e,`end`,t.arrowTypeEnd,n,r,i,a,o)},`addEdgeMarkers`),k={arrow_cross:{type:`cross`,fill:!1},arrow_point:{type:`point`,fill:!0},arrow_barb:{type:`barb`,fill:!0},arrow_barb_neo:{type:`barb`,fill:!0},arrow_circle:{type:`circle`,fill:!1},aggregation:{type:`aggregation`,fill:!1},extension:{type:`extension`,fill:!1},composition:{type:`composition`,fill:!0},dependency:{type:`dependency`,fill:!0},lollipop:{type:`lollipop`,fill:!1},only_one:{type:`onlyOne`,fill:!1},zero_or_one:{type:`zeroOrOne`,fill:!1},one_or_more:{type:`oneOrMore`,fill:!1},zero_or_more:{type:`zeroOrMore`,fill:!1},requirement_arrow:{type:`requirement_arrow`,fill:!1},requirement_contains:{type:`requirement_contains`,fill:!1}},A=[`cross`,`point`,`circle`,`lollipop`,`aggregation`,`extension`,`composition`,`dependency`,`barb`],j=e((e,n,r,i,a,o,s=!1,c)=>{let l=k[r],u=l&&A.includes(l.type);if(!l){t.warn(`Unknown arrow type: ${r}`);return}let d=`${a}_${o}-${l.type}${n===`start`?`Start`:`End`}${s&&u?`-margin`:``}`;if(c&&c.trim()!==``){let t=`${d}_${c.replace(/[^\dA-Za-z]/g,`_`)}`;if(!document.getElementById(t)){let e=document.getElementById(d);if(e){let n=e.cloneNode(!0);n.id=t,n.querySelectorAll(`path, circle, line`).forEach(e=>{e.setAttribute(`stroke`,c),l.fill&&e.setAttribute(`fill`,c)}),e.parentNode?.appendChild(n)}}e.attr(`marker-${n}`,`url(${i}#${t})`)}else e.attr(`marker-${n}`,`url(${i}#${d})`)},`addEdgeMarker`),re=e(e=>typeof e==`string`?e:a()?.flowchart?.curve,`resolveEdgeCurveType`),M=new Map,N=new Map,P=e(()=>{M.clear(),N.clear()},`clear`),F=e(e=>e?typeof e==`string`?e:e.reduce((e,t)=>e+`;`+t,``):``,`getLabelStyles`),I=e(async(e,i)=>{let o=a(),s=r(o),{labelStyles:c}=E(i);i.labelStyle=c;let l=e.insert(`g`).attr(`class`,`edgeLabel`),u=l.insert(`g`).attr(`class`,`label`).attr(`data-id`,i.id),d=i.labelType===`markdown`,f=await x(e,i.label,{style:F(i.labelStyle),useHtmlLabels:s,addSvgBackground:!0,isNode:!1,markdown:d,width:void 0},o);u.node().appendChild(f),t.info(`abc82`,i,i.labelType);let p=f.getBBox(),m=p;if(s){let e=f.children[0],t=n(f);p=e.getBoundingClientRect(),m=p,t.attr(`width`,p.width),t.attr(`height`,p.height)}else{let e=n(f).select(`text`).node();e&&typeof e.getBBox==`function`&&(m=e.getBBox())}u.attr(`transform`,w(m,s)),M.set(i.id,l),i.width=p.width,i.height=p.height;let h;if(i.startLabelLeft){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(r,i.startLabelLeft,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).startLeft=t,L(h,i.startLabelLeft)}if(i.startLabelRight){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(r,i.startLabelRight,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).startRight=t,L(h,i.startLabelRight)}if(i.endLabelLeft){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(t,i.endLabelLeft,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).endLeft=t,L(h,i.endLabelLeft)}if(i.endLabelRight){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(t,i.endLabelRight,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).endRight=t,L(h,i.endLabelRight)}return f},`insertEdgeLabel`);function L(e,t){r(a())&&e&&(e.style.width=t.length*9+`px`,e.style.height=`12px`)}e(L,`setTerminalWidth`);var R=e((e,n)=>{t.debug(`Moving label abc88 `,e.id,e.label,M.get(e.id),n);let r=n.updatedPath?n.updatedPath:n.originalPath,{subGraphTitleTotalMargin:i}=T(a());if(e.label){let a=M.get(e.id),o=e.x,s=e.y;if(r){let i=m.calcLabelPosition(r);t.debug(`Moving label `+e.label+` from (`,o,`,`,s,`) to (`,i.x,`,`,i.y,`) abc88`),n.updatedPath&&(o=i.x,s=i.y)}a.attr(`transform`,`translate(${o}, ${s+i/2})`)}if(e.startLabelLeft){let t=N.get(e.id).startLeft,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_left`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.startLabelRight){let t=N.get(e.id).startRight,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_right`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.endLabelLeft){let t=N.get(e.id).endLeft,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_left`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.endLabelRight){let t=N.get(e.id).endRight,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_right`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}},`positionEdgeLabel`),ie=e((e,t)=>{if(!e?.isLabelEdge||!e?.id?.endsWith(`-to-label`)||!Array.isArray(t)||t.length!==2)return t;let[n,r]=t,i=Math.abs(r.x-n.x),a=Math.abs(r.y-n.y);return i<.001||a<.001?t:a>=i?[n,{x:n.x,y:r.y},r]:[n,{x:r.x,y:n.y},r]},`orthogonalizeToLabelClippedPoints`),z=e((e,t)=>{let n=e.x,r=e.y,i=Math.abs(t.x-n),a=Math.abs(t.y-r),o=e.width/2,s=e.height/2;return i>=o||a>=s},`outsideNode`),B=e((e,n,r)=>{t.debug(`intersection calc abc89: outsidePoint: ${JSON.stringify(n)} insidePoint : ${JSON.stringify(r)} node : x:${e.x} y:${e.y} w:${e.width} h:${e.height}`);let i=e.x,a=e.y,o=Math.abs(i-r.x),s=e.width/2,c=r.xMath.abs(i-n.x)*l){let e=r.y{t.warn(`abc88 cutPathAtIntersect`,e,n);let r=[],i=e[0],a=!1;return e.forEach(e=>{if(t.info(`abc88 checking point`,e,n),!z(n,e)&&!a){let o=B(n,i,e);t.debug(`abc88 inside`,e,i,o),t.debug(`abc88 intersection`,o,n);let s=!1;r.forEach(e=>{s||=e.x===o.x&&e.y===o.y}),r.some(e=>e.x===o.x&&e.y===o.y)?t.warn(`abc88 no intersect`,o,r):r.push(o),a=!0}else t.warn(`abc88 outside`,e,i),i=e,a||r.push(e)}),t.debug(`returning points`,r),r},`cutPathAtIntersect`);function H(e){let t=[],n=[];for(let r=1;r5&&Math.abs(a.y-i.y)>5||i.y===a.y&&a.x===o.x&&Math.abs(a.x-i.x)>5&&Math.abs(a.y-o.y)>5)&&(t.push(a),n.push(r))}return{cornerPoints:t,cornerPointPositions:n}}e(H,`extractCornerPoints`);var U=e(function(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=n/Math.sqrt(r*r+i*i);return{x:t.x-a*r,y:t.y-a*i}},`findAdjacentPoint`),ae=e(function(e){let{cornerPointPositions:n}=H(e),r=[];for(let i=0;i10&&Math.abs(a.y-n.y)>=10?(t.debug(`Corner point fixing`,Math.abs(a.x-n.x),Math.abs(a.y-n.y)),f=o.x===s.x?{x:l<0?s.x-5+d:s.x+5-d,y:u<0?s.y-d:s.y+d}:{x:l<0?s.x-d:s.x+d,y:u<0?s.y-5+d:s.y+5-d}):t.debug(`Corner point skipping fixing`,Math.abs(a.x-n.x),Math.abs(a.y-n.y)),r.push(f,c)}else r.push(e[i]);return r},`fixCorners`),oe=e((e,t,n)=>{let r=e-t-n,i=Math.floor(r/4);return`0 ${t} ${Array(i).fill(`2 2`).join(` `)} ${n}`},`generateDashArray`),W=e(function(e,r,i,x,C,w,T,E=!1){if(!T)throw Error(`insertEdge: missing diagramId for edge "${r.id}" \u2014 edge IDs require a diagram prefix for uniqueness`);let{handDrawnSeed:O,layout:k}=a(),A=r.points,j=!1,M=C;var N=w;let P=[];for(let e in r.cssCompiledStyles)D(e)||P.push(r.cssCompiledStyles[e]);if(k===`swimlane`){if(N.intersect&&M.intersect&&Array.isArray(A)&&A.length>=2)if(A.length===2)A=[M.intersect(A[0]),N.intersect(A[1])];else{let e=A.slice(1,-1),t=e[0],n=e[e.length-1],r=.5,i=Math.abs(A[A.length-1].x-n.x)!Number.isNaN(e.y)),L=re(r.curve);L!==`rounded`&&(I=ae(I));let R=_;switch(L){case`linear`:R=_;break;case`basis`:R=p;break;case`cardinal`:R=o;break;case`bumpX`:R=v;break;case`bumpY`:R=h;break;case`catmullRom`:R=l;break;case`monotoneX`:R=u;break;case`monotoneY`:R=f;break;case`natural`:R=d;break;case`step`:R=s;break;case`stepAfter`:R=c;break;case`stepBefore`:R=g;break;case`rounded`:R=_;break;default:R=p}let{x:z,y:B}=ee(r),H=b().x(z).y(B).curve(R),U;switch(r.thickness){case`normal`:U=`edge-thickness-normal`;break;case`thick`:U=`edge-thickness-thick`;break;case`invisible`:U=`edge-thickness-invisible`;break;default:U=`edge-thickness-normal`}switch(r.pattern){case`solid`:U+=` edge-pattern-solid`;break;case`dotted`:U+=` edge-pattern-dotted`;break;case`dashed`:U+=` edge-pattern-dashed`;break;default:U+=` edge-pattern-solid`}let W,K=L===`rounded`?G(q(I,r),5):H(I),J=Array.isArray(r.style)?r.style:[r.style],Y=J.find(e=>e?.startsWith(`stroke:`)),X=``;r.animate&&(X=`edge-animation-fast`),r.animation&&(X=`edge-animation-`+r.animation);let Z=!1;if(r.look===`handDrawn`){let t=te.svg(e);Object.assign([],I);let i=t.path(K,{roughness:.3,seed:O});U+=` transition`,W=n(i).select(`path`).attr(`id`,`${T}-${r.id}`).attr(`class`,` `+U+(r.classes?` `+r.classes:``)+(X?` `+X:``)).attr(`style`,J?J.reduce((e,t)=>e+`;`+t,``):``);let a=W.attr(`d`);W.attr(`d`,a),e.node().appendChild(W.node())}else{let t=P.join(`;`),n=J?J.reduce((e,t)=>e+t+`;`,``):``,i=(t?t+`;`+n+`;`:n)+`;`+(J?J.reduce((e,t)=>e+`;`+t,``):``);W=e.append(`path`).attr(`d`,K).attr(`id`,`${T}-${r.id}`).attr(`class`,` `+U+(r.classes?` `+r.classes:``)+(X?` `+X:``)).attr(`style`,i),Y=i.match(/stroke:([^;]+)/)?.[1],Z=r.animate===!0||!!r.animation||t.includes(`animation`);let a=W.node(),o=typeof a.getTotalLength==`function`?a.getTotalLength():0,s=S[r.arrowTypeStart]||0,c=S[r.arrowTypeEnd]||0;if(r.look===`neo`&&!Z){let e=`stroke-dasharray: ${r.pattern===`dotted`||r.pattern===`dashed`?oe(o,s,c):`0 ${s} ${o-s-c} ${c}`}; stroke-dashoffset: 0;`;W.attr(`style`,e+W.attr(`style`))}}W.attr(`data-edge`,!0),W.attr(`data-et`,`edge`),W.attr(`data-id`,r.id),W.attr(`data-points`,F),W.attr(`data-look`,y(r.look)),r.showPoints&&I.forEach(t=>{e.append(`circle`).style(`stroke`,`red`).style(`fill`,`red`).attr(`r`,1).attr(`cx`,t.x).attr(`cy`,t.y)});let Q=``;(a().flowchart.arrowMarkerAbsolute||a().state.arrowMarkerAbsolute)&&(Q=window.location.protocol+`//`+window.location.host+window.location.pathname+window.location.search,Q=Q.replace(/\(/g,`\\(`).replace(/\)/g,`\\)`)),t.info(`arrowTypeStart`,r.arrowTypeStart),t.info(`arrowTypeEnd`,r.arrowTypeEnd);let se=!Z&&r?.look===`neo`;ne(W,r,Q,T,x,se,Y);let ce=Math.floor(A.length/2),le=A[ce];m.isLabelCoordinateInPath(le,W.attr(`d`))||(j=!0);let $={};return j&&($.updatedPath=A),$.originalPath=r.points,$},`insertEdge`);function G(e,t){if(e.length<2)return``;let n=``,r=e.length,i=1e-5;for(let a=0;a({...e}));if(e.length>=2&&C[t.arrowTypeStart]){let r=C[t.arrowTypeStart],i=e[0],a=e[1],{angle:o}=K(i,a),s=r*Math.cos(o),c=r*Math.sin(o);n[0].x=i.x+s,n[0].y=i.y+c}let r=e.length;if(r>=2&&C[t.arrowTypeEnd]){let i=C[t.arrowTypeEnd],a=e[r-1],o=e[r-2],{angle:s}=K(o,a),c=i*Math.cos(s),l=i*Math.sin(s);n[r-1].x=a.x-c,n[r-1].y=a.y-l}return n}e(q,`applyMarkerOffsetsToPoints`);var J=e((e,t,n,r)=>{t.forEach(t=>{Y[t](e,n,r)})},`insertMarkers`),Y={extension:e((e,n,r)=>{t.trace(`Making markers for `,r),e.append(`defs`).append(`marker`).attr(`id`,r+`_`+n+`-extensionStart`).attr(`class`,`marker extension `+n).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).attr(`d`,`M 1,7 L18,13 V 1 Z`),e.append(`defs`).append(`marker`).attr(`id`,r+`_`+n+`-extensionEnd`).attr(`class`,`marker extension `+n).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 V 13 L18,7 Z`),e.append(`marker`).attr(`id`,r+`_`+n+`-extensionStart-margin`).attr(`class`,`marker extension `+n).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).attr(`viewBox`,`0 0 20 14`).append(`polygon`).attr(`points`,`10,7 18,13 18,1`).style(`stroke-width`,2).style(`stroke-dasharray`,`0`),e.append(`defs`).append(`marker`).attr(`id`,r+`_`+n+`-extensionEnd-margin`).attr(`class`,`marker extension `+n).attr(`refX`,9).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).attr(`viewBox`,`0 0 20 14`).append(`polygon`).attr(`points`,`10,1 10,13 18,7`).style(`stroke-width`,2).style(`stroke-dasharray`,`0`)},`extension`),composition:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionStart`).attr(`class`,`marker composition `+t).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionEnd`).attr(`class`,`marker composition `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionStart-margin`).attr(`class`,`marker composition `+t).attr(`refX`,15).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,0).attr(`viewBox`,`0 0 15 15`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionEnd-margin`).attr(`class`,`marker composition `+t).attr(`refX`,3.5).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,0).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`)},`composition`),aggregation:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationStart`).attr(`class`,`marker aggregation `+t).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationEnd`).attr(`class`,`marker aggregation `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationStart-margin`).attr(`class`,`marker aggregation `+t).attr(`refX`,15).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,2).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationEnd-margin`).attr(`class`,`marker aggregation `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,2).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`)},`aggregation`),dependency:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyStart`).attr(`class`,`marker dependency `+t).attr(`refX`,6).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 5,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyEnd`).attr(`class`,`marker dependency `+t).attr(`refX`,13).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L14,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyStart-margin`).attr(`class`,`marker dependency `+t).attr(`refX`,4).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,0).attr(`d`,`M 5,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyEnd-margin`).attr(`class`,`marker dependency `+t).attr(`refX`,16).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,0).attr(`d`,`M 18,7 L9,13 L14,7 L9,1 Z`)},`dependency`),lollipop:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopStart`).attr(`class`,`marker lollipop `+t).attr(`refX`,13).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`circle`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopEnd`).attr(`class`,`marker lollipop `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`circle`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopStart-margin`).attr(`class`,`marker lollipop `+t).attr(`refX`,13).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`circle`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6).attr(`stroke-width`,2),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopEnd-margin`).attr(`class`,`marker lollipop `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`circle`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6).attr(`stroke-width`,2)},`lollipop`),point:e((e,t,n)=>{e.append(`marker`).attr(`id`,n+`_`+t+`-pointEnd`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,5).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,8).attr(`markerHeight`,8).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-pointStart`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,4.5).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,8).attr(`markerHeight`,8).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 5 L 10 10 L 10 0 z`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-pointEnd-margin`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 11.5 14`).attr(`refX`,11.5).attr(`refY`,7).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,10.5).attr(`markerHeight`,14).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 0 L 11.5 7 L 0 14 z`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,0).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-pointStart-margin`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 11.5 14`).attr(`refX`,1).attr(`refY`,7).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11.5).attr(`markerHeight`,14).attr(`orient`,`auto`).append(`polygon`).attr(`points`,`0,7 11.5,14 11.5,0`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,0).style(`stroke-dasharray`,`1,0`)},`point`),circle:e((e,t,n)=>{e.append(`marker`).attr(`id`,n+`_`+t+`-circleEnd`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,11).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-circleStart`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,-1).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-circleEnd-margin`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refY`,5).attr(`refX`,12.25).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,14).attr(`markerHeight`,14).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,0).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-circleStart-margin`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,-2).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,14).attr(`markerHeight`,14).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,0).style(`stroke-dasharray`,`1,0`)},`circle`),cross:e((e,t,n)=>{e.append(`marker`).attr(`id`,n+`_`+t+`-crossEnd`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 11 11`).attr(`refX`,12).attr(`refY`,5.2).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 l 9,9 M 10,1 l -9,9`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-crossStart`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 11 11`).attr(`refX`,-1).attr(`refY`,5.2).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 l 9,9 M 10,1 l -9,9`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-crossEnd-margin`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 15 15`).attr(`refX`,17.7).attr(`refY`,7.5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,12).attr(`markerHeight`,12).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 L 14,14 M 1,14 L 14,1`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2.5),e.append(`marker`).attr(`id`,n+`_`+t+`-crossStart-margin`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 15 15`).attr(`refX`,-3.5).attr(`refY`,7.5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,12).attr(`markerHeight`,12).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 L 14,14 M 1,14 L 14,1`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2.5).style(`stroke-dasharray`,`1,0`)},`cross`),barb:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-barbEnd`).attr(`refX`,19).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,14).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L9,13 L14,7 L9,1 Z`)},`barb`),barbNeo:e((e,t,n)=>{let{themeVariables:r}=i(),{transitionColor:a}=r;e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-barbEnd`).attr(`refX`,19).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,14).attr(`markerUnits`,`strokeWidth`).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L11,14 L13,7 L11,0 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-barbEnd-margin`).attr(`refX`,17).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,14).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L11,14 L13,7 L11,0 Z`).attr(`fill`,`${a}`)},`barbNeo`),only_one:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-onlyOneStart`).attr(`class`,`marker onlyOne `+t).attr(`refX`,0).attr(`refY`,9).attr(`markerWidth`,18).attr(`markerHeight`,18).attr(`orient`,`auto`).append(`path`).attr(`d`,`M9,0 L9,18 M15,0 L15,18`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-onlyOneEnd`).attr(`class`,`marker onlyOne `+t).attr(`refX`,18).attr(`refY`,9).attr(`markerWidth`,18).attr(`markerHeight`,18).attr(`orient`,`auto`).append(`path`).attr(`d`,`M3,0 L3,18 M9,0 L9,18`)},`only_one`),zero_or_one:e((e,t,n)=>{let r=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrOneStart`).attr(`class`,`marker zeroOrOne `+t).attr(`refX`,0).attr(`refY`,9).attr(`markerWidth`,30).attr(`markerHeight`,18).attr(`orient`,`auto`);r.append(`circle`).attr(`fill`,`white`).attr(`cx`,21).attr(`cy`,9).attr(`r`,6),r.append(`path`).attr(`d`,`M9,0 L9,18`);let i=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrOneEnd`).attr(`class`,`marker zeroOrOne `+t).attr(`refX`,30).attr(`refY`,9).attr(`markerWidth`,30).attr(`markerHeight`,18).attr(`orient`,`auto`);i.append(`circle`).attr(`fill`,`white`).attr(`cx`,9).attr(`cy`,9).attr(`r`,6),i.append(`path`).attr(`d`,`M21,0 L21,18`)},`zero_or_one`),one_or_more:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-oneOrMoreStart`).attr(`class`,`marker oneOrMore `+t).attr(`refX`,18).attr(`refY`,18).attr(`markerWidth`,45).attr(`markerHeight`,36).attr(`orient`,`auto`).append(`path`).attr(`d`,`M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-oneOrMoreEnd`).attr(`class`,`marker oneOrMore `+t).attr(`refX`,27).attr(`refY`,18).attr(`markerWidth`,45).attr(`markerHeight`,36).attr(`orient`,`auto`).append(`path`).attr(`d`,`M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18`)},`one_or_more`),zero_or_more:e((e,t,n)=>{let r=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrMoreStart`).attr(`class`,`marker zeroOrMore `+t).attr(`refX`,18).attr(`refY`,18).attr(`markerWidth`,57).attr(`markerHeight`,36).attr(`orient`,`auto`);r.append(`circle`).attr(`fill`,`white`).attr(`cx`,48).attr(`cy`,18).attr(`r`,6),r.append(`path`).attr(`d`,`M0,18 Q18,0 36,18 Q18,36 0,18`);let i=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrMoreEnd`).attr(`class`,`marker zeroOrMore `+t).attr(`refX`,39).attr(`refY`,18).attr(`markerWidth`,57).attr(`markerHeight`,36).attr(`orient`,`auto`);i.append(`circle`).attr(`fill`,`white`).attr(`cx`,9).attr(`cy`,18).attr(`r`,6),i.append(`path`).attr(`d`,`M21,18 Q39,0 57,18 Q39,36 21,18`)},`zero_or_more`),only_one_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a}=r;e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-onlyOneStart`).attr(`class`,`marker onlyOne `+t).attr(`refX`,0).attr(`refY`,9).attr(`markerWidth`,18).attr(`markerHeight`,18).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).attr(`d`,`M9,0 L9,18 M15,0 L15,18`).attr(`stroke-width`,`${a}`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-onlyOneEnd`).attr(`class`,`marker onlyOne `+t).attr(`refX`,18).attr(`refY`,9).attr(`markerWidth`,18).attr(`markerHeight`,18).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).attr(`d`,`M3,0 L3,18 M9,0 L9,18`).attr(`stroke-width`,`${a}`)},`only_one_neo`),zero_or_one_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a,mainBkg:o}=r,s=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrOneStart`).attr(`class`,`marker zeroOrOne `+t).attr(`refX`,0).attr(`refY`,9).attr(`markerWidth`,30).attr(`markerHeight`,18).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`);s.append(`circle`).attr(`fill`,o??`white`).attr(`cx`,21).attr(`cy`,9).attr(`stroke-width`,`${a}`).attr(`r`,6),s.append(`path`).attr(`d`,`M9,0 L9,18`).attr(`stroke-width`,`${a}`);let c=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrOneEnd`).attr(`class`,`marker zeroOrOne `+t).attr(`refX`,30).attr(`refY`,9).attr(`markerWidth`,30).attr(`markerHeight`,18).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`);c.append(`circle`).attr(`fill`,o??`white`).attr(`cx`,9).attr(`cy`,9).attr(`stroke-width`,`${a}`).attr(`r`,6),c.append(`path`).attr(`d`,`M21,0 L21,18`).attr(`stroke-width`,`${a}`)},`zero_or_one_neo`),one_or_more_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a}=r;e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-oneOrMoreStart`).attr(`class`,`marker oneOrMore `+t).attr(`refX`,18).attr(`refY`,18).attr(`markerWidth`,45).attr(`markerHeight`,36).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).attr(`d`,`M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27`).attr(`stroke-width`,`${a}`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-oneOrMoreEnd`).attr(`class`,`marker oneOrMore `+t).attr(`refX`,27).attr(`refY`,18).attr(`markerWidth`,45).attr(`markerHeight`,36).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`).append(`path`).attr(`d`,`M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18`).attr(`stroke-width`,`${a}`)},`one_or_more_neo`),zero_or_more_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a,mainBkg:o}=r,s=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrMoreStart`).attr(`class`,`marker zeroOrMore `+t).attr(`refX`,18).attr(`refY`,18).attr(`markerWidth`,57).attr(`markerHeight`,36).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`);s.append(`circle`).attr(`fill`,o??`white`).attr(`cx`,45.5).attr(`cy`,18).attr(`r`,6).attr(`stroke-width`,`${a}`),s.append(`path`).attr(`d`,`M0,18 Q18,0 36,18 Q18,36 0,18`).attr(`stroke-width`,`${a}`);let c=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrMoreEnd`).attr(`class`,`marker zeroOrMore `+t).attr(`refX`,39).attr(`refY`,18).attr(`markerWidth`,57).attr(`markerHeight`,36).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`);c.append(`circle`).attr(`fill`,o??`white`).attr(`cx`,11).attr(`cy`,18).attr(`r`,6).attr(`stroke-width`,`${a}`),c.append(`path`).attr(`d`,`M21,18 Q39,0 57,18 Q39,36 21,18`).attr(`stroke-width`,`${a}`)},`zero_or_more_neo`),requirement_arrow:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-requirement_arrowEnd`).attr(`refX`,20).attr(`refY`,10).attr(`markerWidth`,20).attr(`markerHeight`,20).attr(`orient`,`auto`).append(`path`).attr(`d`,`M0,0 diff --git a/.vercel/output/static/assets/chunk-C7G6YPKG-DJfjwbsZ.js b/.vercel/output/static/assets/chunk-C7G6YPKG-DW-1jWUA.js similarity index 96% rename from .vercel/output/static/assets/chunk-C7G6YPKG-DJfjwbsZ.js rename to .vercel/output/static/assets/chunk-C7G6YPKG-DW-1jWUA.js index 80a0f73..fb9dee2 100644 --- a/.vercel/output/static/assets/chunk-C7G6YPKG-DJfjwbsZ.js +++ b/.vercel/output/static/assets/chunk-C7G6YPKG-DW-1jWUA.js @@ -1 +1 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{x as t}from"./chunk-WYO6CB5R-ajGU-pWR.js";var n=e(e=>{let{handDrawnSeed:n}=t();return{fill:e,hachureAngle:120,hachureGap:4,fillWeight:2,roughness:.7,stroke:e,seed:n}},`solidStateFill`),r=e(e=>{let t=i([...e.cssCompiledStyles||[],...e.cssStyles||[],...e.labelStyle||[]]);return{stylesMap:t,stylesArray:[...t]}},`compileStyles`),i=e(e=>{let t=new Map;return e.forEach(e=>{let[n,r]=e.split(`:`);t.set(n.trim(),r?.trim())}),t},`styles2Map`),a=e(e=>e===`color`||e===`font-size`||e===`font-family`||e===`font-weight`||e===`font-style`||e===`text-decoration`||e===`text-align`||e===`text-transform`||e===`line-height`||e===`letter-spacing`||e===`word-spacing`||e===`text-shadow`||e===`text-overflow`||e===`white-space`||e===`word-wrap`||e===`word-break`||e===`overflow-wrap`||e===`hyphens`,`isLabelStyle`),o=e(e=>{let{stylesArray:t}=r(e),n=[],i=[],o=[],s=[];return t.forEach(e=>{let t=e[0];a(t)?n.push(e.join(`:`)+` !important`):(i.push(e.join(`:`)+` !important`),t.includes(`stroke`)&&o.push(e.join(`:`)+` !important`),t===`fill`&&s.push(e.join(`:`)+` !important`))}),{labelStyles:n.join(`;`),nodeStyles:i.join(`;`),stylesArray:t,borderStyles:o,backgroundStyles:s}},`styles2String`),s=e((e,n)=>{let{themeVariables:i,handDrawnSeed:a}=t(),{nodeBorder:o,mainBkg:s}=i,{stylesMap:l}=r(e);return Object.assign({roughness:.7,fill:l.get(`fill`)||s,fillStyle:`hachure`,fillWeight:4,hachureGap:5.2,stroke:l.get(`stroke`)||o,seed:a,strokeWidth:l.get(`stroke-width`)?.replace(`px`,``)||1.3,fillLineDash:[0,0],strokeLineDash:c(l.get(`stroke-dasharray`))},n)},`userNodeOverrides`),c=e(e=>{if(!e)return[0,0];let t=e.trim().split(/\s+/).map(Number);if(t.length===1){let e=isNaN(t[0])?0:t[0];return[e,e]}return[isNaN(t[0])?0:t[0],isNaN(t[1])?0:t[1]]},`getStrokeDashArray`);export{s as a,o as i,a as n,n as r,r as t}; \ No newline at end of file +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{x as t}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var n=e(e=>{let{handDrawnSeed:n}=t();return{fill:e,hachureAngle:120,hachureGap:4,fillWeight:2,roughness:.7,stroke:e,seed:n}},`solidStateFill`),r=e(e=>{let t=i([...e.cssCompiledStyles||[],...e.cssStyles||[],...e.labelStyle||[]]);return{stylesMap:t,stylesArray:[...t]}},`compileStyles`),i=e(e=>{let t=new Map;return e.forEach(e=>{let[n,r]=e.split(`:`);t.set(n.trim(),r?.trim())}),t},`styles2Map`),a=e(e=>e===`color`||e===`font-size`||e===`font-family`||e===`font-weight`||e===`font-style`||e===`text-decoration`||e===`text-align`||e===`text-transform`||e===`line-height`||e===`letter-spacing`||e===`word-spacing`||e===`text-shadow`||e===`text-overflow`||e===`white-space`||e===`word-wrap`||e===`word-break`||e===`overflow-wrap`||e===`hyphens`,`isLabelStyle`),o=e(e=>{let{stylesArray:t}=r(e),n=[],i=[],o=[],s=[];return t.forEach(e=>{let t=e[0];a(t)?n.push(e.join(`:`)+` !important`):(i.push(e.join(`:`)+` !important`),t.includes(`stroke`)&&o.push(e.join(`:`)+` !important`),t===`fill`&&s.push(e.join(`:`)+` !important`))}),{labelStyles:n.join(`;`),nodeStyles:i.join(`;`),stylesArray:t,borderStyles:o,backgroundStyles:s}},`styles2String`),s=e((e,n)=>{let{themeVariables:i,handDrawnSeed:a}=t(),{nodeBorder:o,mainBkg:s}=i,{stylesMap:l}=r(e);return Object.assign({roughness:.7,fill:l.get(`fill`)||s,fillStyle:`hachure`,fillWeight:4,hachureGap:5.2,stroke:l.get(`stroke`)||o,seed:a,strokeWidth:l.get(`stroke-width`)?.replace(`px`,``)||1.3,fillLineDash:[0,0],strokeLineDash:c(l.get(`stroke-dasharray`))},n)},`userNodeOverrides`),c=e(e=>{if(!e)return[0,0];let t=e.trim().split(/\s+/).map(Number);if(t.length===1){let e=isNaN(t[0])?0:t[0];return[e,e]}return[isNaN(t[0])?0:t[0],isNaN(t[1])?0:t[1]]},`getStrokeDashArray`);export{s as a,o as i,a as n,n as r,r as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-EX3LRPZG-DRWNsKDf.js b/.vercel/output/static/assets/chunk-EX3LRPZG-CzaF5a2T.js similarity index 98% rename from .vercel/output/static/assets/chunk-EX3LRPZG-DRWNsKDf.js rename to .vercel/output/static/assets/chunk-EX3LRPZG-CzaF5a2T.js index 064f353..c2da566 100644 --- a/.vercel/output/static/assets/chunk-EX3LRPZG-DRWNsKDf.js +++ b/.vercel/output/static/assets/chunk-EX3LRPZG-CzaF5a2T.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{$ as r,H as i,K as a,U as o,a as s,s as c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{g as p,s as m}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as h}from"./chunk-32BRIVSS-BtH22FN8.js";import{t as g}from"./chunk-XXDRQBXY-BuE3VzE_.js";import{t as _}from"./chunk-VR4S4FIN-BJzXasDJ.js";import{r as v}from"./chunk-FWX5IMBZ-CiLc9_ts.js";var y=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,2],r=[1,3],i=[1,4],a=[2,4],o=[1,9],s=[1,11],c=[1,16],l=[1,17],u=[1,18],d=[1,19],f=[1,33],p=[1,20],m=[1,21],h=[1,22],g=[1,23],_=[1,24],v=[1,26],y=[1,27],b=[1,28],x=[1,29],S=[1,30],C=[1,31],w=[1,32],T=[1,35],E=[1,36],D=[1,37],O=[1,38],k=[1,34],A=[1,4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],j=[1,4,5,14,15,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,39,40,41,45,48,51,52,53,54,57],M=[4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],N={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,SD:6,document:7,line:8,statement:9,classDefStatement:10,styleStatement:11,cssClassStatement:12,idStatement:13,DESCR:14,"-->":15,HIDE_EMPTY:16,scale:17,WIDTH:18,COMPOSIT_STATE:19,STRUCT_START:20,STRUCT_STOP:21,STATE_DESCR:22,AS:23,ID:24,FORK:25,JOIN:26,CHOICE:27,CONCURRENT:28,note:29,notePosition:30,NOTE_TEXT:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,CLICK:38,STRING:39,HREF:40,classDef:41,CLASSDEF_ID:42,CLASSDEF_STYLEOPTS:43,DEFAULT:44,style:45,STYLE_IDS:46,STYLEDEF_STYLEOPTS:47,class:48,CLASSENTITY_IDS:49,STYLECLASS:50,direction_tb:51,direction_bt:52,direction_rl:53,direction_lr:54,eol:55,";":56,EDGE_STATE:57,STYLE_SEPARATOR:58,left_of:59,right_of:60,$accept:0,$end:1},terminals_:{2:`error`,4:`SPACE`,5:`NL`,6:`SD`,14:`DESCR`,15:`-->`,16:`HIDE_EMPTY`,17:`scale`,18:`WIDTH`,19:`COMPOSIT_STATE`,20:`STRUCT_START`,21:`STRUCT_STOP`,22:`STATE_DESCR`,23:`AS`,24:`ID`,25:`FORK`,26:`JOIN`,27:`CHOICE`,28:`CONCURRENT`,29:`note`,31:`NOTE_TEXT`,33:`acc_title`,34:`acc_title_value`,35:`acc_descr`,36:`acc_descr_value`,37:`acc_descr_multiline_value`,38:`CLICK`,39:`STRING`,40:`HREF`,41:`classDef`,42:`CLASSDEF_ID`,43:`CLASSDEF_STYLEOPTS`,44:`DEFAULT`,45:`style`,46:`STYLE_IDS`,47:`STYLEDEF_STYLEOPTS`,48:`class`,49:`CLASSENTITY_IDS`,50:`STYLECLASS`,51:`direction_tb`,52:`direction_bt`,53:`direction_rl`,54:`direction_lr`,56:`;`,57:`EDGE_STATE`,58:`STYLE_SEPARATOR`,59:`left_of`,60:`right_of`},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,3],[9,4],[9,1],[9,2],[9,1],[9,4],[9,3],[9,6],[9,1],[9,1],[9,1],[9,1],[9,4],[9,4],[9,1],[9,2],[9,2],[9,1],[9,5],[9,5],[10,3],[10,3],[11,3],[12,3],[32,1],[32,1],[32,1],[32,1],[55,1],[55,1],[13,1],[13,1],[13,3],[13,3],[30,1],[30,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 3:return r.setRootDoc(a[s]),a[s];case 4:this.$=[];break;case 5:a[s]!=`nl`&&(a[s-1].push(a[s]),this.$=a[s-1]);break;case 6:case 7:this.$=a[s];break;case 8:this.$=`nl`;break;case 12:this.$=a[s];break;case 13:let e=a[s-1];e.description=r.trimColon(a[s]),this.$=e;break;case 14:this.$={stmt:`relation`,state1:a[s-2],state2:a[s]};break;case 15:let t=r.trimColon(a[s]);this.$={stmt:`relation`,state1:a[s-3],state2:a[s-1],description:t};break;case 19:this.$={stmt:`state`,id:a[s-3],type:`default`,description:``,doc:a[s-1]};break;case 20:var c=a[s],l=a[s-2].trim();if(a[s].match(`:`)){var u=a[s].split(`:`);c=u[0],l=[l,u[1]]}this.$={stmt:`state`,id:c,type:`default`,description:l};break;case 21:this.$={stmt:`state`,id:a[s-3],type:`default`,description:a[s-5],doc:a[s-1]};break;case 22:this.$={stmt:`state`,id:a[s],type:`fork`};break;case 23:this.$={stmt:`state`,id:a[s],type:`join`};break;case 24:this.$={stmt:`state`,id:a[s],type:`choice`};break;case 25:this.$={stmt:`state`,id:r.getDividerId(),type:`divider`};break;case 26:this.$={stmt:`state`,id:a[s-1].trim(),note:{position:a[s-2].trim(),text:a[s].trim()}};break;case 29:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 30:case 31:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 32:this.$={stmt:`click`,id:a[s-3],url:a[s-2],tooltip:a[s-1]};break;case 33:this.$={stmt:`click`,id:a[s-3],url:a[s-1],tooltip:``};break;case 34:case 35:this.$={stmt:`classDef`,id:a[s-1].trim(),classes:a[s].trim()};break;case 36:this.$={stmt:`style`,id:a[s-1].trim(),styleClass:a[s].trim()};break;case 37:this.$={stmt:`applyClass`,id:a[s-1].trim(),styleClass:a[s].trim()};break;case 38:r.setDirection(`TB`),this.$={stmt:`dir`,value:`TB`};break;case 39:r.setDirection(`BT`),this.$={stmt:`dir`,value:`BT`};break;case 40:r.setDirection(`RL`),this.$={stmt:`dir`,value:`RL`};break;case 41:r.setDirection(`LR`),this.$={stmt:`dir`,value:`LR`};break;case 44:case 45:this.$={stmt:`state`,id:a[s].trim(),type:`default`,description:``};break;case 46:this.$={stmt:`state`,id:a[s-2].trim(),classes:[a[s].trim()],type:`default`,description:``};break;case 47:this.$={stmt:`state`,id:a[s-2].trim(),classes:[a[s].trim()],type:`default`,description:``};break}},`anonymous`),table:[{3:1,4:n,5:r,6:i},{1:[3]},{3:5,4:n,5:r,6:i},{3:6,4:n,5:r,6:i},t([1,4,5,16,17,19,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],a,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:o,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:c,17:l,19:u,22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,5]),{9:39,10:12,11:13,12:14,13:15,16:c,17:l,19:u,22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,7]),t(A,[2,8]),t(A,[2,9]),t(A,[2,10]),t(A,[2,11]),t(A,[2,12],{14:[1,40],15:[1,41]}),t(A,[2,16]),{18:[1,42]},t(A,[2,18],{20:[1,43]}),{23:[1,44]},t(A,[2,22]),t(A,[2,23]),t(A,[2,24]),t(A,[2,25]),{30:45,31:[1,46],59:[1,47],60:[1,48]},t(A,[2,28]),{34:[1,49]},{36:[1,50]},t(A,[2,31]),{13:51,24:f,57:k},{42:[1,52],44:[1,53]},{46:[1,54]},{49:[1,55]},t(j,[2,44],{58:[1,56]}),t(j,[2,45],{58:[1,57]}),t(A,[2,38]),t(A,[2,39]),t(A,[2,40]),t(A,[2,41]),t(A,[2,6]),t(A,[2,13]),{13:58,24:f,57:k},t(A,[2,17]),t(M,a,{7:59}),{24:[1,60]},{24:[1,61]},{23:[1,62]},{24:[2,48]},{24:[2,49]},t(A,[2,29]),t(A,[2,30]),{39:[1,63],40:[1,64]},{43:[1,65]},{43:[1,66]},{47:[1,67]},{50:[1,68]},{24:[1,69]},{24:[1,70]},t(A,[2,14],{14:[1,71]}),{4:o,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:c,17:l,19:u,21:[1,72],22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,20],{20:[1,73]}),{31:[1,74]},{24:[1,75]},{39:[1,76]},{39:[1,77]},t(A,[2,34]),t(A,[2,35]),t(A,[2,36]),t(A,[2,37]),t(j,[2,46]),t(j,[2,47]),t(A,[2,15]),t(A,[2,19]),t(M,a,{7:78}),t(A,[2,26]),t(A,[2,27]),{5:[1,79]},{5:[1,80]},{4:o,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:c,17:l,19:u,21:[1,81],22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,32]),t(A,[2,33]),t(A,[2,21])],defaultActions:{5:[2,1],6:[2,2],47:[2,48],48:[2,49]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{$ as r,H as i,K as a,U as o,a as s,s as c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{g as p,s as m}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as h}from"./chunk-32BRIVSS-DWU3ezKg.js";import{t as g}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as _}from"./chunk-VR4S4FIN-BTo4eV3J.js";import{r as v}from"./chunk-FWX5IMBZ-ComLEIwh.js";var y=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,2],r=[1,3],i=[1,4],a=[2,4],o=[1,9],s=[1,11],c=[1,16],l=[1,17],u=[1,18],d=[1,19],f=[1,33],p=[1,20],m=[1,21],h=[1,22],g=[1,23],_=[1,24],v=[1,26],y=[1,27],b=[1,28],x=[1,29],S=[1,30],C=[1,31],w=[1,32],T=[1,35],E=[1,36],D=[1,37],O=[1,38],k=[1,34],A=[1,4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],j=[1,4,5,14,15,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,39,40,41,45,48,51,52,53,54,57],M=[4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],N={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,SD:6,document:7,line:8,statement:9,classDefStatement:10,styleStatement:11,cssClassStatement:12,idStatement:13,DESCR:14,"-->":15,HIDE_EMPTY:16,scale:17,WIDTH:18,COMPOSIT_STATE:19,STRUCT_START:20,STRUCT_STOP:21,STATE_DESCR:22,AS:23,ID:24,FORK:25,JOIN:26,CHOICE:27,CONCURRENT:28,note:29,notePosition:30,NOTE_TEXT:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,CLICK:38,STRING:39,HREF:40,classDef:41,CLASSDEF_ID:42,CLASSDEF_STYLEOPTS:43,DEFAULT:44,style:45,STYLE_IDS:46,STYLEDEF_STYLEOPTS:47,class:48,CLASSENTITY_IDS:49,STYLECLASS:50,direction_tb:51,direction_bt:52,direction_rl:53,direction_lr:54,eol:55,";":56,EDGE_STATE:57,STYLE_SEPARATOR:58,left_of:59,right_of:60,$accept:0,$end:1},terminals_:{2:`error`,4:`SPACE`,5:`NL`,6:`SD`,14:`DESCR`,15:`-->`,16:`HIDE_EMPTY`,17:`scale`,18:`WIDTH`,19:`COMPOSIT_STATE`,20:`STRUCT_START`,21:`STRUCT_STOP`,22:`STATE_DESCR`,23:`AS`,24:`ID`,25:`FORK`,26:`JOIN`,27:`CHOICE`,28:`CONCURRENT`,29:`note`,31:`NOTE_TEXT`,33:`acc_title`,34:`acc_title_value`,35:`acc_descr`,36:`acc_descr_value`,37:`acc_descr_multiline_value`,38:`CLICK`,39:`STRING`,40:`HREF`,41:`classDef`,42:`CLASSDEF_ID`,43:`CLASSDEF_STYLEOPTS`,44:`DEFAULT`,45:`style`,46:`STYLE_IDS`,47:`STYLEDEF_STYLEOPTS`,48:`class`,49:`CLASSENTITY_IDS`,50:`STYLECLASS`,51:`direction_tb`,52:`direction_bt`,53:`direction_rl`,54:`direction_lr`,56:`;`,57:`EDGE_STATE`,58:`STYLE_SEPARATOR`,59:`left_of`,60:`right_of`},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,3],[9,4],[9,1],[9,2],[9,1],[9,4],[9,3],[9,6],[9,1],[9,1],[9,1],[9,1],[9,4],[9,4],[9,1],[9,2],[9,2],[9,1],[9,5],[9,5],[10,3],[10,3],[11,3],[12,3],[32,1],[32,1],[32,1],[32,1],[55,1],[55,1],[13,1],[13,1],[13,3],[13,3],[30,1],[30,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 3:return r.setRootDoc(a[s]),a[s];case 4:this.$=[];break;case 5:a[s]!=`nl`&&(a[s-1].push(a[s]),this.$=a[s-1]);break;case 6:case 7:this.$=a[s];break;case 8:this.$=`nl`;break;case 12:this.$=a[s];break;case 13:let e=a[s-1];e.description=r.trimColon(a[s]),this.$=e;break;case 14:this.$={stmt:`relation`,state1:a[s-2],state2:a[s]};break;case 15:let t=r.trimColon(a[s]);this.$={stmt:`relation`,state1:a[s-3],state2:a[s-1],description:t};break;case 19:this.$={stmt:`state`,id:a[s-3],type:`default`,description:``,doc:a[s-1]};break;case 20:var c=a[s],l=a[s-2].trim();if(a[s].match(`:`)){var u=a[s].split(`:`);c=u[0],l=[l,u[1]]}this.$={stmt:`state`,id:c,type:`default`,description:l};break;case 21:this.$={stmt:`state`,id:a[s-3],type:`default`,description:a[s-5],doc:a[s-1]};break;case 22:this.$={stmt:`state`,id:a[s],type:`fork`};break;case 23:this.$={stmt:`state`,id:a[s],type:`join`};break;case 24:this.$={stmt:`state`,id:a[s],type:`choice`};break;case 25:this.$={stmt:`state`,id:r.getDividerId(),type:`divider`};break;case 26:this.$={stmt:`state`,id:a[s-1].trim(),note:{position:a[s-2].trim(),text:a[s].trim()}};break;case 29:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 30:case 31:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 32:this.$={stmt:`click`,id:a[s-3],url:a[s-2],tooltip:a[s-1]};break;case 33:this.$={stmt:`click`,id:a[s-3],url:a[s-1],tooltip:``};break;case 34:case 35:this.$={stmt:`classDef`,id:a[s-1].trim(),classes:a[s].trim()};break;case 36:this.$={stmt:`style`,id:a[s-1].trim(),styleClass:a[s].trim()};break;case 37:this.$={stmt:`applyClass`,id:a[s-1].trim(),styleClass:a[s].trim()};break;case 38:r.setDirection(`TB`),this.$={stmt:`dir`,value:`TB`};break;case 39:r.setDirection(`BT`),this.$={stmt:`dir`,value:`BT`};break;case 40:r.setDirection(`RL`),this.$={stmt:`dir`,value:`RL`};break;case 41:r.setDirection(`LR`),this.$={stmt:`dir`,value:`LR`};break;case 44:case 45:this.$={stmt:`state`,id:a[s].trim(),type:`default`,description:``};break;case 46:this.$={stmt:`state`,id:a[s-2].trim(),classes:[a[s].trim()],type:`default`,description:``};break;case 47:this.$={stmt:`state`,id:a[s-2].trim(),classes:[a[s].trim()],type:`default`,description:``};break}},`anonymous`),table:[{3:1,4:n,5:r,6:i},{1:[3]},{3:5,4:n,5:r,6:i},{3:6,4:n,5:r,6:i},t([1,4,5,16,17,19,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],a,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:o,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:c,17:l,19:u,22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,5]),{9:39,10:12,11:13,12:14,13:15,16:c,17:l,19:u,22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,7]),t(A,[2,8]),t(A,[2,9]),t(A,[2,10]),t(A,[2,11]),t(A,[2,12],{14:[1,40],15:[1,41]}),t(A,[2,16]),{18:[1,42]},t(A,[2,18],{20:[1,43]}),{23:[1,44]},t(A,[2,22]),t(A,[2,23]),t(A,[2,24]),t(A,[2,25]),{30:45,31:[1,46],59:[1,47],60:[1,48]},t(A,[2,28]),{34:[1,49]},{36:[1,50]},t(A,[2,31]),{13:51,24:f,57:k},{42:[1,52],44:[1,53]},{46:[1,54]},{49:[1,55]},t(j,[2,44],{58:[1,56]}),t(j,[2,45],{58:[1,57]}),t(A,[2,38]),t(A,[2,39]),t(A,[2,40]),t(A,[2,41]),t(A,[2,6]),t(A,[2,13]),{13:58,24:f,57:k},t(A,[2,17]),t(M,a,{7:59}),{24:[1,60]},{24:[1,61]},{23:[1,62]},{24:[2,48]},{24:[2,49]},t(A,[2,29]),t(A,[2,30]),{39:[1,63],40:[1,64]},{43:[1,65]},{43:[1,66]},{47:[1,67]},{50:[1,68]},{24:[1,69]},{24:[1,70]},t(A,[2,14],{14:[1,71]}),{4:o,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:c,17:l,19:u,21:[1,72],22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,20],{20:[1,73]}),{31:[1,74]},{24:[1,75]},{39:[1,76]},{39:[1,77]},t(A,[2,34]),t(A,[2,35]),t(A,[2,36]),t(A,[2,37]),t(j,[2,46]),t(j,[2,47]),t(A,[2,15]),t(A,[2,19]),t(M,a,{7:78}),t(A,[2,26]),t(A,[2,27]),{5:[1,79]},{5:[1,80]},{4:o,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:c,17:l,19:u,21:[1,81],22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,32]),t(A,[2,33]),t(A,[2,21])],defaultActions:{5:[2,1],6:[2,2],47:[2,48],48:[2,49]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};N.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/chunk-FWX5IMBZ-CiLc9_ts.js b/.vercel/output/static/assets/chunk-FWX5IMBZ-ComLEIwh.js similarity index 59% rename from .vercel/output/static/assets/chunk-FWX5IMBZ-CiLc9_ts.js rename to .vercel/output/static/assets/chunk-FWX5IMBZ-ComLEIwh.js index 35270f6..b405a8c 100644 --- a/.vercel/output/static/assets/chunk-FWX5IMBZ-CiLc9_ts.js +++ b/.vercel/output/static/assets/chunk-FWX5IMBZ-ComLEIwh.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dagre-VKFMJZFB-DLAiBZiA.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-_wZywoZs.js","assets/rolldown-runtime-QTnfLwEv.js","assets/chunk-WYO6CB5R-ajGU-pWR.js","assets/index-DU4A6Ttf.js","assets/react-Biaal4sZ.js","assets/link-DYUXAN0T.js","assets/chunk-ICXQ74PX-fa5hHXws.js","assets/dist-D9sYb5Oa.js","assets/chunk-HOUHSVGY-4s2dJLwR.js","assets/chunk-Q4XR5HBZ-5srkZ5CC.js","assets/chunk-7BUUIJ7U-Bb538aSH.js","assets/chunk-OGEWGWER-Dr-qyYzn.js","assets/graphlib-DS17s2tU.js","assets/dagre-dpRSp0QF.js","assets/map-BaFkSB1l.js","assets/chunk-RYQCIY6F-D_L2RdcQ.js","assets/chunk-C7G6YPKG-DJfjwbsZ.js","assets/chunk-ZGVPDNZ5-zo3h_nOA.js","assets/rough.esm-CSKSodPl.js","assets/chunk-52WLFC77-BBAyrLn9.js","assets/line-CDW8hdKE.js","assets/path-BWPyau1x.js","assets/array-BifhSqXX.js","assets/swimlanes-5IMT3BWC-DCPLHTZa.js","assets/cose-bilkent-JH36ORCC-jfFAOGFt.js","assets/cytoscape.esm-CQFVGiJu.js"])))=>i.map(i=>d[i]); -import{t as e}from"./index-DU4A6Ttf.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-_wZywoZs.js";import{b as r,s as i}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{d as a}from"./chunk-ICXQ74PX-fa5hHXws.js";import{a as o,i as s,s as c}from"./chunk-ZGVPDNZ5-zo3h_nOA.js";import{a as l,i as u,o as d,r as f}from"./chunk-52WLFC77-BBAyrLn9.js";var p={common:i,getConfig:r,insertCluster:s,insertEdge:f,insertEdgeLabel:u,insertMarkers:l,insertNode:o,interpolateToCurve:a,labelHelper:c,log:n,positionEdgeLabel:d},m={},h=t(e=>{for(let t of e)m[t.name]=t},`registerLayoutLoaders`);t(()=>{h([{name:`dagre`,loader:t(async()=>await e(()=>import(`./dagre-VKFMJZFB-DLAiBZiA.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])),`loader`)},{name:`swimlane`,loader:t(async()=>await e(()=>import(`./swimlanes-5IMT3BWC-DCPLHTZa.js`),__vite__mapDeps([25,5,3,6,7,1,2,4,8,9,10,11,12,13,14,17,16,18,19,20,21,22,23,24])),`loader`)},{name:`cose-bilkent`,loader:t(async()=>await e(()=>import(`./cose-bilkent-JH36ORCC-jfFAOGFt.js`),__vite__mapDeps([26,3,1,2,27])),`loader`)}])},`registerDefaultLayoutLoaders`)();var g=t(async(e,t,n)=>{if(!(e.layoutAlgorithm in m))throw Error(`Unknown layout algorithm: ${e.layoutAlgorithm}`);if(e.diagramId)for(let t of e.nodes){let n=t.domId||t.id;t.domId=`${e.diagramId}-${n}`}let r=m[e.layoutAlgorithm],i=await r.loader(),{theme:a,themeVariables:o}=e.config,{useGradient:s,gradientStart:c,gradientStop:l}=o,u=t.attr(`id`);if(t.append(`defs`).append(`filter`).attr(`id`,`${u}-drop-shadow`).attr(`height`,`130%`).attr(`width`,`130%`).append(`feDropShadow`).attr(`dx`,`4`).attr(`dy`,`4`).attr(`stdDeviation`,0).attr(`flood-opacity`,`0.06`).attr(`flood-color`,`${a?.includes(`dark`)?`#FFFFFF`:`#000000`}`),t.append(`defs`).append(`filter`).attr(`id`,`${u}-drop-shadow-small`).attr(`height`,`150%`).attr(`width`,`150%`).append(`feDropShadow`).attr(`dx`,`2`).attr(`dy`,`2`).attr(`stdDeviation`,0).attr(`flood-opacity`,`0.06`).attr(`flood-color`,`${a?.includes(`dark`)?`#FFFFFF`:`#000000`}`),s){let e=t.append(`linearGradient`).attr(`id`,t.attr(`id`)+`-gradient`).attr(`gradientUnits`,`objectBoundingBox`).attr(`x1`,`0%`).attr(`y1`,`0%`).attr(`x2`,`100%`).attr(`y2`,`0%`);e.append(`svg:stop`).attr(`offset`,`0%`).attr(`stop-color`,c).attr(`stop-opacity`,1),e.append(`svg:stop`).attr(`offset`,`100%`).attr(`stop-color`,l).attr(`stop-opacity`,1)}return i.render(e,t,p,{algorithm:r.algorithm},n)},`render`),_=t((e=``,{fallback:t=`dagre`}={})=>{if(e in m)return e;if(t in m)return n.warn(`Layout algorithm ${e} is not registered. Using ${t} as fallback.`),t;throw Error(`Both layout algorithms ${e} and ${t} are not registered.`)},`getRegisteredLayoutAlgorithm`);export{h as n,g as r,_ as t}; \ No newline at end of file +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dagre-VKFMJZFB-Cv2q18CS.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-UMNXGZaF.js","assets/rolldown-runtime-aKtaBQYM.js","assets/chunk-WYO6CB5R-Dv5kDyQC.js","assets/index-CXgd9jpl.js","assets/react-BLJmJXjR.js","assets/utils-BTuSbA5p.js","assets/chunk-ICXQ74PX-Czpgj8Uw.js","assets/dist-qx0Iv9vM.js","assets/chunk-HOUHSVGY-iJuv90UH.js","assets/chunk-Q4XR5HBZ-CQ8zkLYc.js","assets/chunk-7BUUIJ7U-Bb538aSH.js","assets/chunk-OGEWGWER-D-nWYRNR.js","assets/graphlib-DS17s2tU.js","assets/dagre-dpRSp0QF.js","assets/map-BaFkSB1l.js","assets/chunk-RYQCIY6F-Dtr3kkSR.js","assets/chunk-C7G6YPKG-DW-1jWUA.js","assets/chunk-ZGVPDNZ5-DGInJAPD.js","assets/rough.esm-CSKSodPl.js","assets/chunk-52WLFC77-BOCvVCX1.js","assets/line-b9Ala942.js","assets/path-BWPyau1x.js","assets/array-BifhSqXX.js","assets/swimlanes-5IMT3BWC-hyAz1L8O.js","assets/cose-bilkent-JH36ORCC-ClqQrHIF.js","assets/cytoscape.esm-CQFVGiJu.js"])))=>i.map(i=>d[i]); +import{t as e}from"./index-CXgd9jpl.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import{b as r,s as i}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{d as a}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{a as o,i as s,s as c}from"./chunk-ZGVPDNZ5-DGInJAPD.js";import{a as l,i as u,o as d,r as f}from"./chunk-52WLFC77-BOCvVCX1.js";var p={common:i,getConfig:r,insertCluster:s,insertEdge:f,insertEdgeLabel:u,insertMarkers:l,insertNode:o,interpolateToCurve:a,labelHelper:c,log:n,positionEdgeLabel:d},m={},h=t(e=>{for(let t of e)m[t.name]=t},`registerLayoutLoaders`);t(()=>{h([{name:`dagre`,loader:t(async()=>await e(()=>import(`./dagre-VKFMJZFB-Cv2q18CS.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])),`loader`)},{name:`swimlane`,loader:t(async()=>await e(()=>import(`./swimlanes-5IMT3BWC-hyAz1L8O.js`),__vite__mapDeps([25,5,3,6,7,1,2,4,8,9,10,11,12,13,14,17,16,18,19,20,21,22,23,24])),`loader`)},{name:`cose-bilkent`,loader:t(async()=>await e(()=>import(`./cose-bilkent-JH36ORCC-ClqQrHIF.js`),__vite__mapDeps([26,3,1,2,27])),`loader`)}])},`registerDefaultLayoutLoaders`)();var g=t(async(e,t,n)=>{if(!(e.layoutAlgorithm in m))throw Error(`Unknown layout algorithm: ${e.layoutAlgorithm}`);if(e.diagramId)for(let t of e.nodes){let n=t.domId||t.id;t.domId=`${e.diagramId}-${n}`}let r=m[e.layoutAlgorithm],i=await r.loader(),{theme:a,themeVariables:o}=e.config,{useGradient:s,gradientStart:c,gradientStop:l}=o,u=t.attr(`id`);if(t.append(`defs`).append(`filter`).attr(`id`,`${u}-drop-shadow`).attr(`height`,`130%`).attr(`width`,`130%`).append(`feDropShadow`).attr(`dx`,`4`).attr(`dy`,`4`).attr(`stdDeviation`,0).attr(`flood-opacity`,`0.06`).attr(`flood-color`,`${a?.includes(`dark`)?`#FFFFFF`:`#000000`}`),t.append(`defs`).append(`filter`).attr(`id`,`${u}-drop-shadow-small`).attr(`height`,`150%`).attr(`width`,`150%`).append(`feDropShadow`).attr(`dx`,`2`).attr(`dy`,`2`).attr(`stdDeviation`,0).attr(`flood-opacity`,`0.06`).attr(`flood-color`,`${a?.includes(`dark`)?`#FFFFFF`:`#000000`}`),s){let e=t.append(`linearGradient`).attr(`id`,t.attr(`id`)+`-gradient`).attr(`gradientUnits`,`objectBoundingBox`).attr(`x1`,`0%`).attr(`y1`,`0%`).attr(`x2`,`100%`).attr(`y2`,`0%`);e.append(`svg:stop`).attr(`offset`,`0%`).attr(`stop-color`,c).attr(`stop-opacity`,1),e.append(`svg:stop`).attr(`offset`,`100%`).attr(`stop-color`,l).attr(`stop-opacity`,1)}return i.render(e,t,p,{algorithm:r.algorithm},n)},`render`),_=t((e=``,{fallback:t=`dagre`}={})=>{if(e in m)return e;if(t in m)return n.warn(`Layout algorithm ${e} is not registered. Using ${t} as fallback.`),t;throw Error(`Both layout algorithms ${e} and ${t} are not registered.`)},`getRegisteredLayoutAlgorithm`);export{h as n,g as r,_ as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-HOUHSVGY-4s2dJLwR.js b/.vercel/output/static/assets/chunk-HOUHSVGY-iJuv90UH.js similarity index 97% rename from .vercel/output/static/assets/chunk-HOUHSVGY-4s2dJLwR.js rename to .vercel/output/static/assets/chunk-HOUHSVGY-iJuv90UH.js index 820dd20..e168d2b 100644 --- a/.vercel/output/static/assets/chunk-HOUHSVGY-4s2dJLwR.js +++ b/.vercel/output/static/assets/chunk-HOUHSVGY-iJuv90UH.js @@ -1 +1 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{b as n,z as r}from"./chunk-WYO6CB5R-ajGU-pWR.js";var i=Object.freeze({left:0,top:0,width:16,height:16}),a=Object.freeze({rotate:0,vFlip:!1,hFlip:!1}),o=Object.freeze({...i,...a}),s=Object.freeze({...o,body:``,hidden:!1}),c=Object.freeze({width:null,height:null}),l=Object.freeze({...c,...a}),u=(e,t,n,r=``)=>{let i=e.split(`:`);if(e.slice(0,1)===`@`){if(i.length<2||i.length>3)return null;r=i.shift().slice(1)}if(i.length>3||!i.length)return null;if(i.length>1){let e=i.pop(),n=i.pop(),a={provider:i.length>0?i[0]:r,prefix:n,name:e};return t&&!d(a)?null:a}let a=i[0],o=a.split(`-`);if(o.length>1){let e={provider:r,prefix:o.shift(),name:o.join(`-`)};return t&&!d(e)?null:e}if(n&&r===``){let e={provider:r,prefix:``,name:a};return t&&!d(e,n)?null:e}return null},d=(e,t)=>e?!!((t&&e.prefix===``||e.prefix)&&e.name):!1;function f(e,t){let n={};!e.hFlip!=!t.hFlip&&(n.hFlip=!0),!e.vFlip!=!t.vFlip&&(n.vFlip=!0);let r=((e.rotate||0)+(t.rotate||0))%4;return r&&(n.rotate=r),n}function p(e,t){let n=f(e,t);for(let r in s)r in a?r in e&&!(r in n)&&(n[r]=a[r]):r in t?n[r]=t[r]:r in e&&(n[r]=e[r]);return n}function m(e,t){let n=e.icons,r=e.aliases||Object.create(null),i=Object.create(null);function a(e){if(n[e])return i[e]=[];if(!(e in i)){i[e]=null;let t=r[e]&&r[e].parent,n=t&&a(t);n&&(i[e]=[t].concat(n))}return i[e]}return(t||Object.keys(n).concat(Object.keys(r))).forEach(a),i}function h(e,t,n){let r=e.icons,i=e.aliases||Object.create(null),a={};function o(e){a=p(r[e]||i[e],a)}return o(t),n.forEach(o),p(e,a)}function g(e,t){if(e.icons[t])return h(e,t,[]);let n=m(e,[t])[t];return n?h(e,t,n):null}var _=/(-?[0-9.]*[0-9]+[0-9.]*)/g,v=/^-?[0-9.]*[0-9]+[0-9.]*$/g;function y(e,t,n){if(t===1)return e;if(n||=100,typeof e==`number`)return Math.ceil(e*t*n)/n;if(typeof e!=`string`)return e;let r=e.split(_);if(r===null||!r.length)return e;let i=[],a=r.shift(),o=v.test(a);for(;;){if(o){let e=parseFloat(a);isNaN(e)?i.push(a):i.push(Math.ceil(e*t*n)/n)}else i.push(a);if(a=r.shift(),a===void 0)return i.join(``);o=!o}}function b(e,t=`defs`){let n=``,r=e.indexOf(`<`+t);for(;r>=0;){let i=e.indexOf(`>`,r),a=e.indexOf(``,a);if(o===-1)break;n+=e.slice(i+1,a).trim(),e=e.slice(0,r).trim()+e.slice(o+1)}return{defs:n,content:e}}function x(e,t){return e?``+e+``+t:t}function S(e,t,n){let r=b(e);return x(r.defs,t+r.content+n)}var C=e=>e===`unset`||e===`undefined`||e===`none`;function w(e,t){let n={...o,...e},r={...l,...t},i={left:n.left,top:n.top,width:n.width,height:n.height},a=n.body;[n,r].forEach(e=>{let t=[],n=e.hFlip,r=e.vFlip,o=e.rotate;n?r?o+=2:(t.push(`translate(`+(i.width+i.left).toString()+` `+(0-i.top).toString()+`)`),t.push(`scale(-1 1)`),i.top=i.left=0):r&&(t.push(`translate(`+(0-i.left).toString()+` `+(i.height+i.top).toString()+`)`),t.push(`scale(1 -1)`),i.top=i.left=0);let s;switch(o<0&&(o-=Math.floor(o/4)*4),o%=4,o){case 1:s=i.height/2+i.top,t.unshift(`rotate(90 `+s.toString()+` `+s.toString()+`)`);break;case 2:t.unshift(`rotate(180 `+(i.width/2+i.left).toString()+` `+(i.height/2+i.top).toString()+`)`);break;case 3:s=i.width/2+i.left,t.unshift(`rotate(-90 `+s.toString()+` `+s.toString()+`)`);break}o%2==1&&(i.left!==i.top&&(s=i.left,i.left=i.top,i.top=s),i.width!==i.height&&(s=i.width,i.width=i.height,i.height=s)),t.length&&(a=S(a,``,``))});let s=r.width,c=r.height,u=i.width,d=i.height,f,p;s===null?(p=c===null?`1em`:c===`auto`?d:c,f=y(p,u/d)):(f=s===`auto`?u:s,p=c===null?y(f,d/u):c===`auto`?d:c);let m={},h=(e,t)=>{C(t)||(m[e]=t.toString())};h(`width`,f),h(`height`,p);let g=[i.left,i.top,u,d];return m.viewBox=g.join(` `),{attributes:m,viewBox:g,body:a}}var T=/\sid="(\S+)"/g,E=new Map;function D(e){e=e.replace(/[0-9]+$/,``)||`a`;let t=E.get(e)||0;return E.set(e,t+1),t?`${e}${t}`:e}function O(e){let t=[],n;for(;n=T.exec(e);)t.push(n[1]);if(!t.length)return e;let r=`suffix`+(Math.random()*16777216|Date.now()).toString(16);return t.forEach(t=>{let n=D(t),i=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);e=e.replace(RegExp(`([#;"])(`+i+`)([")]|\\.[a-z])`,`g`),`$1`+n+r+`$3`)}),e=e.replace(new RegExp(r,`g`),``),e}function k(e,t){let n=e.indexOf(`xlink:`)===-1?``:` xmlns:xlink="http://www.w3.org/1999/xlink"`;for(let e in t)n+=` `+e+`="`+t[e]+`"`;return``+e+``}var A={body:`?`,height:80,width:80},j=new Map,M=new Map,N=e(e=>{for(let n of e){if(!n.name)throw Error(`Invalid icon loader. Must have a "name" property with non-empty string value.`);if(t.debug(`Registering icon pack:`,n.name),`loader`in n)M.set(n.name,n.loader);else if(`icons`in n)j.set(n.name,n.icons);else throw t.error(`Invalid icon loader:`,n),Error(`Invalid icon loader. Must have either "icons" or "loader" property.`)}},`registerIconPacks`),P=e(async(e,n)=>{let r=u(e,!0,n!==void 0);if(!r)throw Error(`Invalid icon name: ${e}`);let i=r.prefix||n;if(!i)throw Error(`Icon name must contain a prefix: ${e}`);let a=j.get(i);if(!a){let e=M.get(i);if(!e)throw Error(`Icon set not found: ${r.prefix}`);try{a={...await e(),prefix:i},j.set(i,a)}catch(e){throw t.error(e),Error(`Failed to load icon set: ${r.prefix}`)}}let o=g(a,r.name);if(!o)throw Error(`Icon not found: ${e}`);return o},`getRegisteredIconData`),F=e(async e=>{try{return await P(e),!0}catch{return!1}},`isIconAvailable`),I=e(async(e,i,a)=>{let o;try{o=await P(e,i?.fallbackPrefix)}catch(e){t.error(e),o=A}let s=w(o,i);return r(k(O(s.body),{...s.attributes,...a}),n())},`getIconSVG`);export{A as i,F as n,N as r,I as t}; \ No newline at end of file +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{b as n,z as r}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var i=Object.freeze({left:0,top:0,width:16,height:16}),a=Object.freeze({rotate:0,vFlip:!1,hFlip:!1}),o=Object.freeze({...i,...a}),s=Object.freeze({...o,body:``,hidden:!1}),c=Object.freeze({width:null,height:null}),l=Object.freeze({...c,...a}),u=(e,t,n,r=``)=>{let i=e.split(`:`);if(e.slice(0,1)===`@`){if(i.length<2||i.length>3)return null;r=i.shift().slice(1)}if(i.length>3||!i.length)return null;if(i.length>1){let e=i.pop(),n=i.pop(),a={provider:i.length>0?i[0]:r,prefix:n,name:e};return t&&!d(a)?null:a}let a=i[0],o=a.split(`-`);if(o.length>1){let e={provider:r,prefix:o.shift(),name:o.join(`-`)};return t&&!d(e)?null:e}if(n&&r===``){let e={provider:r,prefix:``,name:a};return t&&!d(e,n)?null:e}return null},d=(e,t)=>e?!!((t&&e.prefix===``||e.prefix)&&e.name):!1;function f(e,t){let n={};!e.hFlip!=!t.hFlip&&(n.hFlip=!0),!e.vFlip!=!t.vFlip&&(n.vFlip=!0);let r=((e.rotate||0)+(t.rotate||0))%4;return r&&(n.rotate=r),n}function p(e,t){let n=f(e,t);for(let r in s)r in a?r in e&&!(r in n)&&(n[r]=a[r]):r in t?n[r]=t[r]:r in e&&(n[r]=e[r]);return n}function m(e,t){let n=e.icons,r=e.aliases||Object.create(null),i=Object.create(null);function a(e){if(n[e])return i[e]=[];if(!(e in i)){i[e]=null;let t=r[e]&&r[e].parent,n=t&&a(t);n&&(i[e]=[t].concat(n))}return i[e]}return(t||Object.keys(n).concat(Object.keys(r))).forEach(a),i}function h(e,t,n){let r=e.icons,i=e.aliases||Object.create(null),a={};function o(e){a=p(r[e]||i[e],a)}return o(t),n.forEach(o),p(e,a)}function g(e,t){if(e.icons[t])return h(e,t,[]);let n=m(e,[t])[t];return n?h(e,t,n):null}var _=/(-?[0-9.]*[0-9]+[0-9.]*)/g,v=/^-?[0-9.]*[0-9]+[0-9.]*$/g;function y(e,t,n){if(t===1)return e;if(n||=100,typeof e==`number`)return Math.ceil(e*t*n)/n;if(typeof e!=`string`)return e;let r=e.split(_);if(r===null||!r.length)return e;let i=[],a=r.shift(),o=v.test(a);for(;;){if(o){let e=parseFloat(a);isNaN(e)?i.push(a):i.push(Math.ceil(e*t*n)/n)}else i.push(a);if(a=r.shift(),a===void 0)return i.join(``);o=!o}}function b(e,t=`defs`){let n=``,r=e.indexOf(`<`+t);for(;r>=0;){let i=e.indexOf(`>`,r),a=e.indexOf(``,a);if(o===-1)break;n+=e.slice(i+1,a).trim(),e=e.slice(0,r).trim()+e.slice(o+1)}return{defs:n,content:e}}function x(e,t){return e?``+e+``+t:t}function S(e,t,n){let r=b(e);return x(r.defs,t+r.content+n)}var C=e=>e===`unset`||e===`undefined`||e===`none`;function w(e,t){let n={...o,...e},r={...l,...t},i={left:n.left,top:n.top,width:n.width,height:n.height},a=n.body;[n,r].forEach(e=>{let t=[],n=e.hFlip,r=e.vFlip,o=e.rotate;n?r?o+=2:(t.push(`translate(`+(i.width+i.left).toString()+` `+(0-i.top).toString()+`)`),t.push(`scale(-1 1)`),i.top=i.left=0):r&&(t.push(`translate(`+(0-i.left).toString()+` `+(i.height+i.top).toString()+`)`),t.push(`scale(1 -1)`),i.top=i.left=0);let s;switch(o<0&&(o-=Math.floor(o/4)*4),o%=4,o){case 1:s=i.height/2+i.top,t.unshift(`rotate(90 `+s.toString()+` `+s.toString()+`)`);break;case 2:t.unshift(`rotate(180 `+(i.width/2+i.left).toString()+` `+(i.height/2+i.top).toString()+`)`);break;case 3:s=i.width/2+i.left,t.unshift(`rotate(-90 `+s.toString()+` `+s.toString()+`)`);break}o%2==1&&(i.left!==i.top&&(s=i.left,i.left=i.top,i.top=s),i.width!==i.height&&(s=i.width,i.width=i.height,i.height=s)),t.length&&(a=S(a,``,``))});let s=r.width,c=r.height,u=i.width,d=i.height,f,p;s===null?(p=c===null?`1em`:c===`auto`?d:c,f=y(p,u/d)):(f=s===`auto`?u:s,p=c===null?y(f,d/u):c===`auto`?d:c);let m={},h=(e,t)=>{C(t)||(m[e]=t.toString())};h(`width`,f),h(`height`,p);let g=[i.left,i.top,u,d];return m.viewBox=g.join(` `),{attributes:m,viewBox:g,body:a}}var T=/\sid="(\S+)"/g,E=new Map;function D(e){e=e.replace(/[0-9]+$/,``)||`a`;let t=E.get(e)||0;return E.set(e,t+1),t?`${e}${t}`:e}function O(e){let t=[],n;for(;n=T.exec(e);)t.push(n[1]);if(!t.length)return e;let r=`suffix`+(Math.random()*16777216|Date.now()).toString(16);return t.forEach(t=>{let n=D(t),i=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);e=e.replace(RegExp(`([#;"])(`+i+`)([")]|\\.[a-z])`,`g`),`$1`+n+r+`$3`)}),e=e.replace(new RegExp(r,`g`),``),e}function k(e,t){let n=e.indexOf(`xlink:`)===-1?``:` xmlns:xlink="http://www.w3.org/1999/xlink"`;for(let e in t)n+=` `+e+`="`+t[e]+`"`;return``+e+``}var A={body:`?`,height:80,width:80},j=new Map,M=new Map,N=e(e=>{for(let n of e){if(!n.name)throw Error(`Invalid icon loader. Must have a "name" property with non-empty string value.`);if(t.debug(`Registering icon pack:`,n.name),`loader`in n)M.set(n.name,n.loader);else if(`icons`in n)j.set(n.name,n.icons);else throw t.error(`Invalid icon loader:`,n),Error(`Invalid icon loader. Must have either "icons" or "loader" property.`)}},`registerIconPacks`),P=e(async(e,n)=>{let r=u(e,!0,n!==void 0);if(!r)throw Error(`Invalid icon name: ${e}`);let i=r.prefix||n;if(!i)throw Error(`Icon name must contain a prefix: ${e}`);let a=j.get(i);if(!a){let e=M.get(i);if(!e)throw Error(`Icon set not found: ${r.prefix}`);try{a={...await e(),prefix:i},j.set(i,a)}catch(e){throw t.error(e),Error(`Failed to load icon set: ${r.prefix}`)}}let o=g(a,r.name);if(!o)throw Error(`Icon not found: ${e}`);return o},`getRegisteredIconData`),F=e(async e=>{try{return await P(e),!0}catch{return!1}},`isIconAvailable`),I=e(async(e,i,a)=>{let o;try{o=await P(e,i?.fallbackPrefix)}catch(e){t.error(e),o=A}let s=w(o,i);return r(k(O(s.body),{...s.attributes,...a}),n())},`getIconSVG`);export{A as i,F as n,N as r,I as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-ICXQ74PX-fa5hHXws.js b/.vercel/output/static/assets/chunk-ICXQ74PX-Czpgj8Uw.js similarity index 99% rename from .vercel/output/static/assets/chunk-ICXQ74PX-fa5hHXws.js rename to .vercel/output/static/assets/chunk-ICXQ74PX-Czpgj8Uw.js index 0703300..7f15439 100644 --- a/.vercel/output/static/assets/chunk-ICXQ74PX-fa5hHXws.js +++ b/.vercel/output/static/assets/chunk-ICXQ74PX-Czpgj8Uw.js @@ -1,2 +1,2 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{R as r,h as i,p as a,r as o,s}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as c}from"./dist-D9sYb5Oa.js";function l(e){this._context=e}l.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function u(e){return new l(e)}var d=class{constructor(e,t){this._context=e,this._x=t}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,t,e,t):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+t)/2,e,this._y0,e,t);break}this._x0=e,this._y0=t}};function f(e){return new d(e,!0)}function ee(e){return new d(e,!1)}function p(){}function m(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function h(e){this._context=e}h.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:m(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:m(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function te(e){return new h(e)}function ne(e){this._context=e}ne.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:m(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function re(e){return new ne(e)}function ie(e){this._context=e}ie.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:m(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function ae(e){return new ie(e)}function oe(e,t){this._basis=new h(e),this._beta=t}oe.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var e=this._x,t=this._y,n=e.length-1;if(n>0)for(var r=e[0],i=t[0],a=e[n]-r,o=t[n]-i,s=-1,c;++s<=n;)c=s/n,this._basis.point(this._beta*e[s]+(1-this._beta)*(r+c*a),this._beta*t[s]+(1-this._beta)*(i+c*o));this._x=this._y=null,this._basis.lineEnd()},point:function(e,t){this._x.push(+e),this._y.push(+t)}};var se=(function e(t){function n(e){return t===1?new h(e):new oe(e,t)}return n.beta=function(t){return e(+t)},n})(.85);function g(e,t,n){e._context.bezierCurveTo(e._x1+e._k*(e._x2-e._x0),e._y1+e._k*(e._y2-e._y0),e._x2+e._k*(e._x1-t),e._y2+e._k*(e._y1-n),e._x2,e._y2)}function _(e,t){this._context=e,this._k=(1-t)/6}_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:g(this,this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2,this._x1=e,this._y1=t;break;case 2:this._point=3;default:g(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var ce=(function e(t){function n(e){return new _(e,t)}return n.tension=function(t){return e(+t)},n})(0);function v(e,t){this._context=e,this._k=(1-t)/6}v.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:g(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var le=(function e(t){function n(e){return new v(e,t)}return n.tension=function(t){return e(+t)},n})(0);function y(e,t){this._context=e,this._k=(1-t)/6}y.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:g(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var ue=(function e(t){function n(e){return new y(e,t)}return n.tension=function(t){return e(+t)},n})(0);function b(e,t,n){var r=e._x1,i=e._y1,a=e._x2,o=e._y2;if(e._l01_a>1e-12){var s=2*e._l01_2a+3*e._l01_a*e._l12_a+e._l12_2a,c=3*e._l01_a*(e._l01_a+e._l12_a);r=(r*s-e._x0*e._l12_2a+e._x2*e._l01_2a)/c,i=(i*s-e._y0*e._l12_2a+e._y2*e._l01_2a)/c}if(e._l23_a>1e-12){var l=2*e._l23_2a+3*e._l23_a*e._l12_a+e._l12_2a,u=3*e._l23_a*(e._l23_a+e._l12_a);a=(a*l+e._x1*e._l23_2a-t*e._l12_2a)/u,o=(o*l+e._y1*e._l23_2a-n*e._l12_2a)/u}e._context.bezierCurveTo(r,i,a,o,e._x2,e._y2)}function de(e,t){this._context=e,this._alpha=t}de.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=(n*n+r*r)**+this._alpha)}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3;default:b(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var fe=(function e(t){function n(e){return t?new de(e,t):new _(e,0)}return n.alpha=function(t){return e(+t)},n})(.5);function pe(e,t){this._context=e,this._alpha=t}pe.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=(n*n+r*r)**+this._alpha)}switch(this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:b(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var me=(function e(t){function n(e){return t?new pe(e,t):new v(e,0)}return n.alpha=function(t){return e(+t)},n})(.5);function he(e,t){this._context=e,this._alpha=t}he.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=(n*n+r*r)**+this._alpha)}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:b(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var ge=(function e(t){function n(e){return t?new he(e,t):new y(e,0)}return n.alpha=function(t){return e(+t)},n})(.5);function _e(e){this._context=e}_e.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function ve(e){return new _e(e)}function ye(e){return e<0?-1:1}function be(e,t,n){var r=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(r||i<0&&-0),o=(n-e._y1)/(i||r<0&&-0),s=(a*i+o*r)/(r+i);return(ye(a)+ye(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function xe(e,t){var n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function x(e,t,n){var r=e._x0,i=e._y0,a=e._x1,o=e._y1,s=(a-r)/3;e._context.bezierCurveTo(r+s,i+s*t,a-s,o-s*n,a,o)}function S(e){this._context=e}S.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:x(this,this._t0,xe(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var n=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,x(this,xe(this,n=be(this,e,t)),n);break;default:x(this,this._t0,n=be(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}}};function Se(e){this._context=new Ce(e)}(Se.prototype=Object.create(S.prototype)).point=function(e,t){S.prototype.point.call(this,t,e)};function Ce(e){this._context=e}Ce.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,n,r,i,a){this._context.bezierCurveTo(t,e,r,n,a,i)}};function we(e){return new S(e)}function Te(e){return new Se(e)}function Ee(e){this._context=e}Ee.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,n=e.length;if(n)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else for(var r=De(e),i=De(t),a=0,o=1;o=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[n-1]=(e[n]+i[n-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}this._x=e,this._y=t}};function w(e){return new C(e,.5)}function T(e){return new C(e,0)}function ke(e){return new C(e,1)}function E(e){if(typeof e!=`object`||!e)return!1;if(Object.getPrototypeOf(e)===null)return!0;if(Object.prototype.toString.call(e)!==`[object Object]`){let t=e[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable?!1:e.toString()===`[object ${t}]`}let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Ae(){}function je(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function D(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var Me=`[object RegExp]`,O=`[object String]`,k=`[object Number]`,A=`[object Boolean]`,j=`[object Arguments]`,Ne=`[object Symbol]`,Pe=`[object Date]`,Fe=`[object Map]`,Ie=`[object Set]`,Le=`[object Array]`,Re=`[object ArrayBuffer]`,ze=`[object Object]`,M=`[object DataView]`,Be=`[object Uint8Array]`,Ve=`[object Uint8ClampedArray]`,He=`[object Uint16Array]`,Ue=`[object Uint32Array]`,We=`[object Int8Array]`,Ge=`[object Int16Array]`,Ke=`[object Int32Array]`,qe=`[object Float32Array]`,Je=`[object Float64Array]`,Ye=typeof globalThis==`object`&&globalThis||typeof window==`object`&&window||typeof self==`object`&&self||typeof global==`object`&&global||(function(){return this})();function N(e){return Ye.Buffer!==void 0&&Ye.Buffer.isBuffer(e)}function Xe(e){return Number.isSafeInteger(e)&&e>=0}function Ze(e){return e!=null&&typeof e!=`function`&&Xe(e.length)}function Qe(e){return e===`__proto__`}function P(e){return e==null||typeof e!=`object`&&typeof e!=`function`}function F(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function $e(e,t){return I(e,void 0,e,new Map,t)}function I(e,t,n,r=new Map,i=void 0){let a=i?.(e,t,n,r);if(a!==void 0)return a;if(P(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){let t=Array(e.length);r.set(e,t);for(let a=0;a{let o=t?.(n,r,i,a);if(o!==void 0)return o;if(typeof e==`object`){if(D(e)===`[object Object]`&&typeof e.constructor!=`function`){let t={};return a.set(e,t),L(t,e,i,a),t}switch(Object.prototype.toString.call(e)){case k:case O:case A:{let t=new e.constructor(e?.valueOf());return L(t,e),t}case j:{let t={};return L(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function nt(e){return tt(e)}function R(e){return typeof e==`object`&&!!e&&D(e)===`[object Arguments]`}function z(e){return typeof e==`object`&&!!e}function rt(e){return z(e)&&Ze(e)}function B(e){return F(e)}function V(e,t){if(typeof e!=`function`||t!=null&&typeof t!=`function`)throw TypeError(`Expected a function`);let n=function(...r){let i=t?t.apply(this,r):r[0],a=n.cache;if(a.has(i))return a.get(i);let o=e.apply(this,r);return n.cache=a.set(i,o)||a,o};return n.cache=new(V.Cache||Map),n}V.Cache=Map;function it(e){if(P(e))return e;if(Array.isArray(e)||F(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)return e.slice(0);let t=Object.getPrototypeOf(e);if(t==null)return Object.assign(Object.create(t),e);let n=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new n(e);if(e instanceof RegExp){let t=new n(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new n(e.buffer.slice(0));if(e instanceof Error){let t;return t=e instanceof AggregateError?new n(e.errors,e.message,{cause:e.cause}):new n(e.message,{cause:e.cause}),t.stack=e.stack,Object.assign(t,e),t}return typeof File<`u`&&e instanceof File?new n([e],e.name,{type:e.type,lastModified:e.lastModified}):typeof e==`object`?Object.assign(Object.create(t),e):e}function at(e,...t){let n=t.slice(0,-1),r=t[t.length-1],i=e;for(let e=0;ee.args);r(e),i=o(i,[...e])}else i=n.args;if(!i)return;let s=a(e,t),c=`config`;return i[c]!==void 0&&(s===`flowchart-v2`&&(s=`flowchart`),i[s]=i[c],delete i[c]),i},`detectInit`),dt=e(function(e,n=null){try{let r=RegExp(`[%]{2}(?![{]${lt.source})(?=[}][%]{2}).* +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{R as r,h as i,p as a,r as o,s}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as c}from"./dist-qx0Iv9vM.js";function l(e){this._context=e}l.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function u(e){return new l(e)}var d=class{constructor(e,t){this._context=e,this._x=t}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,t,e,t):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+t)/2,e,this._y0,e,t);break}this._x0=e,this._y0=t}};function f(e){return new d(e,!0)}function ee(e){return new d(e,!1)}function p(){}function m(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function h(e){this._context=e}h.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:m(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:m(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function te(e){return new h(e)}function ne(e){this._context=e}ne.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:m(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function re(e){return new ne(e)}function ie(e){this._context=e}ie.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:m(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function ae(e){return new ie(e)}function oe(e,t){this._basis=new h(e),this._beta=t}oe.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var e=this._x,t=this._y,n=e.length-1;if(n>0)for(var r=e[0],i=t[0],a=e[n]-r,o=t[n]-i,s=-1,c;++s<=n;)c=s/n,this._basis.point(this._beta*e[s]+(1-this._beta)*(r+c*a),this._beta*t[s]+(1-this._beta)*(i+c*o));this._x=this._y=null,this._basis.lineEnd()},point:function(e,t){this._x.push(+e),this._y.push(+t)}};var se=(function e(t){function n(e){return t===1?new h(e):new oe(e,t)}return n.beta=function(t){return e(+t)},n})(.85);function g(e,t,n){e._context.bezierCurveTo(e._x1+e._k*(e._x2-e._x0),e._y1+e._k*(e._y2-e._y0),e._x2+e._k*(e._x1-t),e._y2+e._k*(e._y1-n),e._x2,e._y2)}function _(e,t){this._context=e,this._k=(1-t)/6}_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:g(this,this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2,this._x1=e,this._y1=t;break;case 2:this._point=3;default:g(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var ce=(function e(t){function n(e){return new _(e,t)}return n.tension=function(t){return e(+t)},n})(0);function v(e,t){this._context=e,this._k=(1-t)/6}v.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:g(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var le=(function e(t){function n(e){return new v(e,t)}return n.tension=function(t){return e(+t)},n})(0);function y(e,t){this._context=e,this._k=(1-t)/6}y.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:g(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var ue=(function e(t){function n(e){return new y(e,t)}return n.tension=function(t){return e(+t)},n})(0);function b(e,t,n){var r=e._x1,i=e._y1,a=e._x2,o=e._y2;if(e._l01_a>1e-12){var s=2*e._l01_2a+3*e._l01_a*e._l12_a+e._l12_2a,c=3*e._l01_a*(e._l01_a+e._l12_a);r=(r*s-e._x0*e._l12_2a+e._x2*e._l01_2a)/c,i=(i*s-e._y0*e._l12_2a+e._y2*e._l01_2a)/c}if(e._l23_a>1e-12){var l=2*e._l23_2a+3*e._l23_a*e._l12_a+e._l12_2a,u=3*e._l23_a*(e._l23_a+e._l12_a);a=(a*l+e._x1*e._l23_2a-t*e._l12_2a)/u,o=(o*l+e._y1*e._l23_2a-n*e._l12_2a)/u}e._context.bezierCurveTo(r,i,a,o,e._x2,e._y2)}function de(e,t){this._context=e,this._alpha=t}de.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=(n*n+r*r)**+this._alpha)}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3;default:b(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var fe=(function e(t){function n(e){return t?new de(e,t):new _(e,0)}return n.alpha=function(t){return e(+t)},n})(.5);function pe(e,t){this._context=e,this._alpha=t}pe.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=(n*n+r*r)**+this._alpha)}switch(this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:b(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var me=(function e(t){function n(e){return t?new pe(e,t):new v(e,0)}return n.alpha=function(t){return e(+t)},n})(.5);function he(e,t){this._context=e,this._alpha=t}he.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=(n*n+r*r)**+this._alpha)}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:b(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var ge=(function e(t){function n(e){return t?new he(e,t):new y(e,0)}return n.alpha=function(t){return e(+t)},n})(.5);function _e(e){this._context=e}_e.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function ve(e){return new _e(e)}function ye(e){return e<0?-1:1}function be(e,t,n){var r=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(r||i<0&&-0),o=(n-e._y1)/(i||r<0&&-0),s=(a*i+o*r)/(r+i);return(ye(a)+ye(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function xe(e,t){var n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function x(e,t,n){var r=e._x0,i=e._y0,a=e._x1,o=e._y1,s=(a-r)/3;e._context.bezierCurveTo(r+s,i+s*t,a-s,o-s*n,a,o)}function S(e){this._context=e}S.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:x(this,this._t0,xe(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var n=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,x(this,xe(this,n=be(this,e,t)),n);break;default:x(this,this._t0,n=be(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}}};function Se(e){this._context=new Ce(e)}(Se.prototype=Object.create(S.prototype)).point=function(e,t){S.prototype.point.call(this,t,e)};function Ce(e){this._context=e}Ce.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,n,r,i,a){this._context.bezierCurveTo(t,e,r,n,a,i)}};function we(e){return new S(e)}function Te(e){return new Se(e)}function Ee(e){this._context=e}Ee.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,n=e.length;if(n)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else for(var r=De(e),i=De(t),a=0,o=1;o=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[n-1]=(e[n]+i[n-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}this._x=e,this._y=t}};function w(e){return new C(e,.5)}function T(e){return new C(e,0)}function ke(e){return new C(e,1)}function E(e){if(typeof e!=`object`||!e)return!1;if(Object.getPrototypeOf(e)===null)return!0;if(Object.prototype.toString.call(e)!==`[object Object]`){let t=e[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable?!1:e.toString()===`[object ${t}]`}let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Ae(){}function je(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function D(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var Me=`[object RegExp]`,O=`[object String]`,k=`[object Number]`,A=`[object Boolean]`,j=`[object Arguments]`,Ne=`[object Symbol]`,Pe=`[object Date]`,Fe=`[object Map]`,Ie=`[object Set]`,Le=`[object Array]`,Re=`[object ArrayBuffer]`,ze=`[object Object]`,M=`[object DataView]`,Be=`[object Uint8Array]`,Ve=`[object Uint8ClampedArray]`,He=`[object Uint16Array]`,Ue=`[object Uint32Array]`,We=`[object Int8Array]`,Ge=`[object Int16Array]`,Ke=`[object Int32Array]`,qe=`[object Float32Array]`,Je=`[object Float64Array]`,Ye=typeof globalThis==`object`&&globalThis||typeof window==`object`&&window||typeof self==`object`&&self||typeof global==`object`&&global||(function(){return this})();function N(e){return Ye.Buffer!==void 0&&Ye.Buffer.isBuffer(e)}function Xe(e){return Number.isSafeInteger(e)&&e>=0}function Ze(e){return e!=null&&typeof e!=`function`&&Xe(e.length)}function Qe(e){return e===`__proto__`}function P(e){return e==null||typeof e!=`object`&&typeof e!=`function`}function F(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function $e(e,t){return I(e,void 0,e,new Map,t)}function I(e,t,n,r=new Map,i=void 0){let a=i?.(e,t,n,r);if(a!==void 0)return a;if(P(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){let t=Array(e.length);r.set(e,t);for(let a=0;a{let o=t?.(n,r,i,a);if(o!==void 0)return o;if(typeof e==`object`){if(D(e)===`[object Object]`&&typeof e.constructor!=`function`){let t={};return a.set(e,t),L(t,e,i,a),t}switch(Object.prototype.toString.call(e)){case k:case O:case A:{let t=new e.constructor(e?.valueOf());return L(t,e),t}case j:{let t={};return L(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function nt(e){return tt(e)}function R(e){return typeof e==`object`&&!!e&&D(e)===`[object Arguments]`}function z(e){return typeof e==`object`&&!!e}function rt(e){return z(e)&&Ze(e)}function B(e){return F(e)}function V(e,t){if(typeof e!=`function`||t!=null&&typeof t!=`function`)throw TypeError(`Expected a function`);let n=function(...r){let i=t?t.apply(this,r):r[0],a=n.cache;if(a.has(i))return a.get(i);let o=e.apply(this,r);return n.cache=a.set(i,o)||a,o};return n.cache=new(V.Cache||Map),n}V.Cache=Map;function it(e){if(P(e))return e;if(Array.isArray(e)||F(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)return e.slice(0);let t=Object.getPrototypeOf(e);if(t==null)return Object.assign(Object.create(t),e);let n=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new n(e);if(e instanceof RegExp){let t=new n(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new n(e.buffer.slice(0));if(e instanceof Error){let t;return t=e instanceof AggregateError?new n(e.errors,e.message,{cause:e.cause}):new n(e.message,{cause:e.cause}),t.stack=e.stack,Object.assign(t,e),t}return typeof File<`u`&&e instanceof File?new n([e],e.name,{type:e.type,lastModified:e.lastModified}):typeof e==`object`?Object.assign(Object.create(t),e):e}function at(e,...t){let n=t.slice(0,-1),r=t[t.length-1],i=e;for(let e=0;ee.args);r(e),i=o(i,[...e])}else i=n.args;if(!i)return;let s=a(e,t),c=`config`;return i[c]!==void 0&&(s===`flowchart-v2`&&(s=`flowchart`),i[s]=i[c],delete i[c]),i},`detectInit`),dt=e(function(e,n=null){try{let r=RegExp(`[%]{2}(?![{]${lt.source})(?=[}][%]{2}).* `,`ig`);e=e.trim().replace(r,``).replace(/'/gm,`"`),t.debug(`Detecting diagram directive${n===null?``:` type:`+n} based on the text:${e}`);let a,o=[];for(;(a=i.exec(e))!==null;)if(a.index===i.lastIndex&&i.lastIndex++,a&&!n||n&&a[1]?.match(n)||n&&a[2]?.match(n)){let e=a[1]?a[1]:a[2],t=a[3]?a[3].trim():a[4]?JSON.parse(a[4].trim()):null;o.push({type:e,args:t})}return o.length===0?{type:e,args:null}:o.length===1?o[0]:o}catch(r){return t.error(`ERROR: ${r.message} - Unable to parse directive type: '${n}' based on the text: '${e}'`),{type:void 0,args:null}}},`detectDirective`),ft=e(function(e){return e.replace(i,``)},`removeDirectives`),pt=e(function(e,t){for(let[n,r]of t.entries())if(r.match(e))return n;return-1},`isSubstringInArray`);function U(e,t){return e?ct[`curve${e.charAt(0).toUpperCase()+e.slice(1)}`]??t:t}e(U,`interpolateToCurve`);function mt(e,t){let n=e.trim();if(n)return t.securityLevel===`loose`?n:(0,st.sanitizeUrl)(n)}e(mt,`formatUrl`);var ht=e((e,...n)=>{let r=e.split(`.`),i=r.length-1,a=r[i],o=window;for(let n=0;n{n+=W(e,t),t=e}),G(e,n/2)}e(gt,`traverseEdge`);function _t(e){return e.length===1?e[0]:gt(e)}e(_t,`calcLabelPosition`);var vt=e((e,t=2)=>{let n=10**t;return Math.round(e*n)/n},`roundNumber`),G=e((e,t)=>{let n,r=t;for(let t of e){if(n){let e=W(t,n);if(e===0)return n;if(e=1)return{x:t.x,y:t.y};if(i>0&&i<1)return{x:vt((1-i)*n.x+i*t.x,5),y:vt((1-i)*n.y+i*t.y,5)}}}n=t}throw Error(`Could not find a suitable point for the given distance`)},`calculatePoint`),yt=e((e,n,r)=>{t.info(`our points ${JSON.stringify(n)}`),n[0]!==r&&(n=n.reverse());let i=G(n,25),a=e?10:5,o=Math.atan2(n[0].y-i.y,n[0].x-i.x),s={x:0,y:0};return s.x=Math.sin(o)*a+(n[0].x+i.x)/2,s.y=-Math.cos(o)*a+(n[0].y+i.y)/2,s},`calcCardinalityPosition`);function bt(e,n,r){let i=structuredClone(r);t.info(`our points`,i),n!==`start_left`&&n!==`start_right`&&i.reverse();let a=G(i,25+e),o=10+e*.5,s=Math.atan2(i[0].y-a.y,i[0].x-a.x),c={x:0,y:0};return n===`start_left`?(c.x=Math.sin(s+Math.PI)*o+(i[0].x+a.x)/2,c.y=-Math.cos(s+Math.PI)*o+(i[0].y+a.y)/2):n===`end_right`?(c.x=Math.sin(s-Math.PI)*o+(i[0].x+a.x)/2-5,c.y=-Math.cos(s-Math.PI)*o+(i[0].y+a.y)/2-5):n===`end_left`?(c.x=Math.sin(s)*o+(i[0].x+a.x)/2-5,c.y=-Math.cos(s)*o+(i[0].y+a.y)/2-5):(c.x=Math.sin(s)*o+(i[0].x+a.x)/2,c.y=-Math.cos(s)*o+(i[0].y+a.y)/2),c}e(bt,`calcTerminalLabelPosition`);function K(e){let t=``,n=``;for(let r of e)r!==void 0&&(r.startsWith(`color:`)||r.startsWith(`text-align:`)?n=n+r+`;`:t=t+r+`;`);return{style:t,labelStyle:n}}e(K,`getStylesFromArray`);var xt=0,St=e(()=>(xt++,`id-`+Math.random().toString(36).substr(2,12)+`-`+xt),`generateId`);function Ct(e){let t=``;for(let n=0;nCt(e.length),`random`),Tt=e(function(){return{x:0,y:0,fill:void 0,anchor:`start`,style:`#666`,width:100,height:100,textMargin:0,rx:0,ry:0,valign:void 0,text:``}},`getTextObj`),Et=e(function(e,t){let n=t.text.replace(s.lineBreakRegex,` `),[,r]=Z(t.fontSize),i=e.append(`text`);i.attr(`x`,t.x),i.attr(`y`,t.y),i.style(`text-anchor`,t.anchor),i.style(`font-family`,t.fontFamily),i.style(`font-size`,r),i.style(`font-weight`,t.fontWeight),i.attr(`fill`,t.fill),t.class!==void 0&&i.attr(`class`,t.class);let a=i.append(`tspan`);return a.attr(`x`,t.x+t.textMargin*2),a.attr(`fill`,t.fill),a.text(n),i},`drawSimpleText`),Dt=V((e,t,n)=>{if(!e||(n=Object.assign({fontSize:12,fontWeight:400,fontFamily:`Arial`,joinWith:`
`},n),s.lineBreakRegex.test(e)))return e;let r=e.split(` `).filter(Boolean),i=[],a=``;return r.forEach((e,o)=>{let s=J(`${e} `,n),c=J(a,n);if(s>t){let{hyphenatedStrings:r,remainingWord:o}=Ot(e,t,`-`,n);i.push(a,...r),a=o}else c+s>=t?(i.push(a),a=e):a=[a,e].filter(Boolean).join(` `);o+1===r.length&&i.push(a)}),i.filter(e=>e!==``).join(n.joinWith)},(e,t,n)=>`${e}${t}${n.fontSize}${n.fontWeight}${n.fontFamily}${n.joinWith}`),Ot=V((e,t,n=`-`,r)=>{r=Object.assign({fontSize:12,fontWeight:400,fontFamily:`Arial`,margin:0},r);let i=[...e],a=[],o=``;return i.forEach((e,s)=>{let c=`${o}${e}`;if(J(c,r)>=t){let e=s+1,t=i.length===e,r=`${c}${n}`;a.push(t?c:r),o=``}else o=c}),{hyphenatedStrings:a,remainingWord:o}},(e,t,n=`-`,r)=>`${e}${t}${n}${r.fontSize}${r.fontWeight}${r.fontFamily}`);function q(e,t){return Y(e,t).height}e(q,`calculateTextHeight`);function J(e,t){return Y(e,t).width}e(J,`calculateTextWidth`);var Y=V((e,t)=>{let{fontSize:r=12,fontFamily:i=`Arial`,fontWeight:a=400}=t;if(!e)return{width:0,height:0};let[,o]=Z(r),c=[`sans-serif`,i],l=e.split(s.lineBreakRegex),u=[],d=n(`body`);if(!d.remove)return{width:0,height:0,lineHeight:0};let f=d.append(`svg`);for(let e of c){let t=0,n={width:0,height:0,lineHeight:0};for(let r of l){let i=Tt();i.text=r||`​`;let s=Et(f,i).style(`font-size`,o).style(`font-weight`,a).style(`font-family`,e),c=(s._groups||s)[0][0].getBBox();if(c.width===0&&c.height===0)throw Error(`svg element not in render tree`);n.width=Math.round(Math.max(n.width,c.width)),t=Math.round(c.height),n.height+=t,n.lineHeight=Math.round(Math.max(n.lineHeight,t))}u.push(n)}return f.remove(),u[isNaN(u[1].height)||isNaN(u[1].width)||isNaN(u[1].lineHeight)||u[0].height>u[1].height&&u[0].width>u[1].width&&u[0].lineHeight>u[1].lineHeight?0:1]},(e,t)=>`${e}${t.fontSize}${t.fontWeight}${t.fontFamily}`),kt=class{constructor(e=!1,t){this.count=0,this.count=t?t.length:0,this.next=e?()=>this.count++:()=>Date.now()}static{e(this,`InitIDGenerator`)}},X,At=e(function(e){return X||=document.createElement(`div`),e=escape(e).replace(/%26/g,`&`).replace(/%23/g,`#`).replace(/%3B/g,`;`),X.innerHTML=e,unescape(X.textContent)},`entityDecode`);function jt(e){return`str`in e}e(jt,`isDetailedError`);var Mt=e((e,t,n,r)=>{if(!r)return;let i=e.node()?.getBBox();i&&e.append(`text`).text(r).attr(`text-anchor`,`middle`).attr(`x`,i.x+i.width/2).attr(`y`,-n).attr(`class`,t)},`insertTitle`),Z=e(e=>{if(typeof e==`number`)return[e,e+`px`];let t=parseInt(e??``,10);return Number.isNaN(t)?[void 0,void 0]:e===String(t)?[t,e+`px`]:[t,e]},`parseFontSize`);function Q(e,t){return ot({},e,t)}e(Q,`cleanAndMerge`);var Nt={assignWithDepth:o,wrapLabel:Dt,calculateTextHeight:q,calculateTextWidth:J,calculateTextDimensions:Y,cleanAndMerge:Q,detectInit:ut,detectDirective:dt,isSubstringInArray:pt,interpolateToCurve:U,calcLabelPosition:_t,calcCardinalityPosition:yt,calcTerminalLabelPosition:bt,formatUrl:mt,getStylesFromArray:K,generateId:St,random:wt,runFunc:ht,entityDecode:At,insertTitle:Mt,isLabelCoordinateInPath:$,parseFontSize:Z,InitIDGenerator:kt},Pt=e(function(e){let t=e;return t=t.replace(/style.*:\S*#.*;/g,function(e){return e.substring(0,e.length-1)}),t=t.replace(/classDef.*:\S*#.*;/g,function(e){return e.substring(0,e.length-1)}),t=t.replace(/#\w+;/g,function(e){let t=e.substring(1,e.length-1);return/^\+?\d+$/.test(t)?`fl°°`+t+`¶ß`:`fl°`+t+`¶ß`}),t},`encodeEntities`),Ft=e(function(e){return e.replace(/fl°°/g,`&#`).replace(/fl°/g,`&`).replace(/¶ß/g,`;`)},`decodeEntities`),It=e((e,t,{counter:n=0,prefix:r,suffix:i},a)=>a||`${r?`${r}_`:``}${e}_${t}_${n}${i?`_${i}`:``}`,`getEdgeId`);function Lt(e){return e??null}e(Lt,`handleUndefinedAttr`);function $(e,t){let n=Math.round(e.x),r=Math.round(e.y),i=t.replace(/(\d+\.\d+)/g,e=>Math.round(parseFloat(e)).toString());return i.includes(n.toString())||i.includes(r.toString())}e($,`isLabelCoordinateInPath`);export{ce as $,Je as A,Ne as B,j as C,M as D,A as E,k as F,D as G,Ue as H,ze as I,w as J,ke as K,Me as L,Ke as M,We as N,Pe as O,Fe as P,fe as Q,Ie as R,N as S,Le as T,Be as U,He as V,Ve as W,we as X,Oe as Y,Te as Z,Dt as _,Ft as a,P as b,It as c,U as d,te as et,jt as f,Nt as g,ft as h,Q as i,Ge as j,qe as k,K as l,wt as m,q as n,ee as nt,Pt as o,Z as p,T as q,J as r,u as rt,St as s,Y as t,f as tt,Lt as u,B as v,Re as w,Ze as x,R as y,O as z}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-MOJQB5TN-DR1aBwdH.js b/.vercel/output/static/assets/chunk-MOJQB5TN-Bju_yCKi.js similarity index 98% rename from .vercel/output/static/assets/chunk-MOJQB5TN-DR1aBwdH.js rename to .vercel/output/static/assets/chunk-MOJQB5TN-Bju_yCKi.js index afee331..6492768 100644 --- a/.vercel/output/static/assets/chunk-MOJQB5TN-DR1aBwdH.js +++ b/.vercel/output/static/assets/chunk-MOJQB5TN-Bju_yCKi.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{D as n,a as r,b as i,c as a,x as o,z as s}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as c}from"./chunk-VAUOI2AC-CLN1Ga8_.js";var l=``,u=``,d=``,f=[],p=new Map,m=e(e=>s(e,o()),`sanitizeText`),h=e(e=>{switch(e.type){case`terminal`:return{...e,value:m(e.value)};case`nonterminal`:return{...e,name:m(e.name)};case`sequence`:return{...e,elements:e.elements.map(h)};case`choice`:return{...e,alternatives:e.alternatives.map(h)};case`optional`:return{...e,element:h(e.element)};case`repetition`:return{...e,element:h(e.element),separator:e.separator?h(e.separator):void 0};case`special`:return{...e,text:m(e.text)}}},`sanitizeAstNode`),g=e(()=>{l=``,u=``,d=``,f.length=0,p.clear(),r(),t.debug(`[Railroad] Database cleared`)},`clear`),_=e(e=>{l=m(e),t.debug(`[Railroad] Title set:`,e)},`setTitle`),v=e(()=>l,`getTitle`),y={clear:g,setTitle:_,getTitle:v,addRule:e(e=>{let n={...e,name:m(e.name),definition:h(e.definition),comment:e.comment?m(e.comment):void 0};t.debug(`[Railroad] Adding rule:`,n.name),p.has(n.name)&&t.warn(`[Railroad] Rule '${n.name}' is already defined. Overwriting.`),f.push(n),p.set(n.name,n)},`addRule`),getRules:e(()=>f,`getRules`),getRule:e(e=>p.get(e),`getRule`),setAccTitle:e(e=>{u=m(e).replace(/^\s+/g,``),t.debug(`[Railroad] Accessibility title set:`,e)},`setAccTitle`),getAccTitle:e(()=>u,`getAccTitle`),setAccDescription:e(e=>{d=m(e).replace(/\n\s+/g,` +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{D as n,a as r,b as i,c as a,x as o,z as s}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as c}from"./chunk-VAUOI2AC-AC9pRUsa.js";var l=``,u=``,d=``,f=[],p=new Map,m=e(e=>s(e,o()),`sanitizeText`),h=e(e=>{switch(e.type){case`terminal`:return{...e,value:m(e.value)};case`nonterminal`:return{...e,name:m(e.name)};case`sequence`:return{...e,elements:e.elements.map(h)};case`choice`:return{...e,alternatives:e.alternatives.map(h)};case`optional`:return{...e,element:h(e.element)};case`repetition`:return{...e,element:h(e.element),separator:e.separator?h(e.separator):void 0};case`special`:return{...e,text:m(e.text)}}},`sanitizeAstNode`),g=e(()=>{l=``,u=``,d=``,f.length=0,p.clear(),r(),t.debug(`[Railroad] Database cleared`)},`clear`),_=e(e=>{l=m(e),t.debug(`[Railroad] Title set:`,e)},`setTitle`),v=e(()=>l,`getTitle`),y={clear:g,setTitle:_,getTitle:v,addRule:e(e=>{let n={...e,name:m(e.name),definition:h(e.definition),comment:e.comment?m(e.comment):void 0};t.debug(`[Railroad] Adding rule:`,n.name),p.has(n.name)&&t.warn(`[Railroad] Rule '${n.name}' is already defined. Overwriting.`),f.push(n),p.set(n.name,n)},`addRule`),getRules:e(()=>f,`getRules`),getRule:e(e=>p.get(e),`getRule`),setAccTitle:e(e=>{u=m(e).replace(/^\s+/g,``),t.debug(`[Railroad] Accessibility title set:`,e)},`setAccTitle`),getAccTitle:e(()=>u,`getAccTitle`),setAccDescription:e(e=>{d=m(e).replace(/\n\s+/g,` `),t.debug(`[Railroad] Accessibility description set:`,e)},`setAccDescription`),getAccDescription:e(()=>d,`getAccDescription`),setDiagramTitle:_,getDiagramTitle:v},b={compactMode:!1,padding:10,verticalSeparation:8,horizontalSeparation:10,arcRadius:10,fontSize:14,fontFamily:`monospace`,terminalFill:`#FFFFC0`,terminalStroke:`#000000`,terminalTextColor:`#000000`,nonTerminalFill:`#FFFFFF`,nonTerminalStroke:`#000000`,nonTerminalTextColor:`#000000`,lineColor:`#000000`,strokeWidth:2,markerFill:`#000000`,commentFill:`#E8E8E8`,commentStroke:`#888888`,commentTextColor:`#666666`,specialFill:`#F0E0FF`,specialStroke:`#8800CC`,ruleNameColor:`#000066`,showMarkers:!0,markerRadius:5},x=/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$|^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch)\([\d\s%+,./-]+\)$|^[a-z]+$/i,S=/^[\w "',.-]+$/,C=new Set([`compactMode`,`padding`,`verticalSeparation`,`horizontalSeparation`,`arcRadius`,`fontSize`,`fontFamily`,`terminalFill`,`terminalStroke`,`terminalTextColor`,`nonTerminalFill`,`nonTerminalStroke`,`nonTerminalTextColor`,`lineColor`,`strokeWidth`,`markerFill`,`commentFill`,`commentStroke`,`commentTextColor`,`specialFill`,`specialStroke`,`ruleNameColor`,`showMarkers`,`markerRadius`]),w=e(e=>e?Object.keys(e).every(e=>e===`railroad`||C.has(e)):!1,`isRailroadStyleOptions`),T=e(e=>e?`railroad`in e&&e.railroad?e.railroad:w(e)?e:{}:{},`extractRailroadOverrides`),E=e(e=>{if(!e||w(e))return{};let{railroad:t,svgId:n,theme:r,look:i,...a}=e;return a},`extractThemeOverrides`),D=e((e,t)=>{if(typeof e!=`string`)return t;let n=e.trim();return x.test(n)?n:t},`sanitizeColorValue`),O=e((e,t)=>{if(typeof e!=`string`)return t;let n=e.trim();return S.test(n)?n:t},`sanitizeFontFamilyValue`),k=e((e,t)=>{let n=typeof e==`number`?e:typeof e==`string`?Number.parseFloat(e):NaN;return Number.isFinite(n)&&n>=0?n:t},`sanitizeNumberValue`),A=e(e=>{let t=typeof e==`number`?e:typeof e==`string`?Number.parseFloat(e):NaN;return Number.isFinite(t)&&t>0?t:void 0},`parseThemeFontSize`),j=e(e=>{let t=O(e.fontFamily,b.fontFamily),n=A(e.fontSize)??b.fontSize;return{...b,fontFamily:t,fontSize:n,terminalFill:D(e.secondBkg??e.secondaryColor,b.terminalFill),terminalStroke:D(e.secondaryBorderColor??e.lineColor,b.terminalStroke),terminalTextColor:D(e.secondaryTextColor??e.textColor,b.terminalTextColor),nonTerminalFill:D(e.mainBkg??e.background,b.nonTerminalFill),nonTerminalStroke:D(e.primaryBorderColor??e.lineColor,b.nonTerminalStroke),nonTerminalTextColor:D(e.primaryTextColor??e.textColor,b.nonTerminalTextColor),lineColor:D(e.lineColor,b.lineColor),markerFill:D(e.lineColor,b.markerFill),commentFill:D(e.labelBackground??e.tertiaryColor,b.commentFill),commentStroke:D(e.tertiaryBorderColor??e.lineColor,b.commentStroke),commentTextColor:D(e.tertiaryTextColor??e.textColor,b.commentTextColor),specialFill:D(e.tertiaryColor??e.secondaryColor,b.specialFill),specialStroke:D(e.tertiaryBorderColor??e.secondaryBorderColor,b.specialStroke),ruleNameColor:D(e.titleColor??e.textColor,b.ruleNameColor)}},`buildThemeDefaults`),M=e(e=>{let t=i(),r=j({...n(),...t.themeVariables??{},...E(e)}),a={...t.railroad??{},...T(e)};return{compactMode:a.compactMode??r.compactMode,padding:k(a.padding,r.padding),verticalSeparation:k(a.verticalSeparation,r.verticalSeparation),horizontalSeparation:k(a.horizontalSeparation,r.horizontalSeparation),arcRadius:k(a.arcRadius,r.arcRadius),fontSize:k(a.fontSize,r.fontSize),fontFamily:O(a.fontFamily,r.fontFamily),terminalFill:D(a.terminalFill,r.terminalFill),terminalStroke:D(a.terminalStroke,r.terminalStroke),terminalTextColor:D(a.terminalTextColor,r.terminalTextColor),nonTerminalFill:D(a.nonTerminalFill,r.nonTerminalFill),nonTerminalStroke:D(a.nonTerminalStroke,r.nonTerminalStroke),nonTerminalTextColor:D(a.nonTerminalTextColor,r.nonTerminalTextColor),lineColor:D(a.lineColor,r.lineColor),strokeWidth:k(a.strokeWidth,r.strokeWidth),markerFill:D(a.markerFill,r.markerFill),commentFill:D(a.commentFill,r.commentFill),commentStroke:D(a.commentStroke,r.commentStroke),commentTextColor:D(a.commentTextColor,r.commentTextColor),specialFill:D(a.specialFill,r.specialFill),specialStroke:D(a.specialStroke,r.specialStroke),ruleNameColor:D(a.ruleNameColor,r.ruleNameColor),showMarkers:a.showMarkers??r.showMarkers,markerRadius:k(a.markerRadius,r.markerRadius)}},`buildRailroadStyleOptions`),N=e(e=>{let{fontFamily:t,fontSize:n,terminalFill:r,terminalStroke:i,terminalTextColor:a,nonTerminalFill:o,nonTerminalStroke:s,nonTerminalTextColor:c,lineColor:l,strokeWidth:u,markerFill:d,commentFill:f,commentStroke:p,commentTextColor:m,specialFill:h,specialStroke:g,ruleNameColor:_}=M(e);return` .railroad-diagram { font-family: ${t}; diff --git a/.vercel/output/static/assets/chunk-OGEWGWER-Dr-qyYzn.js b/.vercel/output/static/assets/chunk-OGEWGWER-D-nWYRNR.js similarity index 86% rename from .vercel/output/static/assets/chunk-OGEWGWER-Dr-qyYzn.js rename to .vercel/output/static/assets/chunk-OGEWGWER-D-nWYRNR.js index 4ab3b5f..a3dd93f 100644 --- a/.vercel/output/static/assets/chunk-OGEWGWER-Dr-qyYzn.js +++ b/.vercel/output/static/assets/chunk-OGEWGWER-D-nWYRNR.js @@ -1 +1 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{f as t,x as n}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{p as r}from"./chunk-ICXQ74PX-fa5hHXws.js";var i=e(({flowchart:e})=>{let t=e?.subGraphTitleMargin?.top??0,n=e?.subGraphTitleMargin?.bottom??0;return{subGraphTitleTopMargin:t,subGraphTitleBottomMargin:n,subGraphTitleTotalMargin:t+n}},`getSubGraphTitleMargins`);async function a(i,a){let o=i.getElementsByTagName(`img`);if(!o||o.length===0)return;let s=a.replace(/]*>/g,``).trim()===``;await Promise.all([...o].map(i=>new Promise(a=>{function o(){if(i.style.display=`flex`,i.style.flexDirection=`column`,s){let[e=t.fontSize]=r(n().fontSize?n().fontSize:window.getComputedStyle(document.body).fontSize),a=e*5+`px`;i.style.minWidth=a,i.style.maxWidth=a}else i.style.width=`100%`;a(i)}e(o,`setupImage`),setTimeout(()=>{i.complete&&o()}),i.addEventListener(`error`,o),i.addEventListener(`load`,o)})))}e(a,`configureLabelImages`);export{i as n,a as t}; \ No newline at end of file +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{f as t,x as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{p as r}from"./chunk-ICXQ74PX-Czpgj8Uw.js";var i=e(({flowchart:e})=>{let t=e?.subGraphTitleMargin?.top??0,n=e?.subGraphTitleMargin?.bottom??0;return{subGraphTitleTopMargin:t,subGraphTitleBottomMargin:n,subGraphTitleTotalMargin:t+n}},`getSubGraphTitleMargins`);async function a(i,a){let o=i.getElementsByTagName(`img`);if(!o||o.length===0)return;let s=a.replace(/]*>/g,``).trim()===``;await Promise.all([...o].map(i=>new Promise(a=>{function o(){if(i.style.display=`flex`,i.style.flexDirection=`column`,s){let[e=t.fontSize]=r(n().fontSize?n().fontSize:window.getComputedStyle(document.body).fontSize),a=e*5+`px`;i.style.minWidth=a,i.style.maxWidth=a}else i.style.width=`100%`;a(i)}e(o,`setupImage`),setTimeout(()=>{i.complete&&o()}),i.addEventListener(`error`,o),i.addEventListener(`load`,o)})))}e(a,`configureLabelImages`);export{i as n,a as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-PUDLZKDR-C4aS5M-Y.js b/.vercel/output/static/assets/chunk-PUDLZKDR-hlw4TonS.js similarity index 99% rename from .vercel/output/static/assets/chunk-PUDLZKDR-C4aS5M-Y.js rename to .vercel/output/static/assets/chunk-PUDLZKDR-hlw4TonS.js index 45a436a..82af9d9 100644 --- a/.vercel/output/static/assets/chunk-PUDLZKDR-C4aS5M-Y.js +++ b/.vercel/output/static/assets/chunk-PUDLZKDR-hlw4TonS.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{$ as r,G as i,H as a,K as o,U as s,a as c,d as l,it as u,k as d,s as f,v as p,w as ee,x as m,y as h}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as te}from"./channel-DA-EZjf8.js";import{c as g,g as _}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as ne}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{t as re}from"./chunk-32BRIVSS-BtH22FN8.js";import{t as v}from"./chunk-XXDRQBXY-BuE3VzE_.js";import{t as y}from"./chunk-VR4S4FIN-BJzXasDJ.js";import{o as b}from"./chunk-ZGVPDNZ5-zo3h_nOA.js";import{r as x,t as S}from"./chunk-FWX5IMBZ-CiLc9_ts.js";import{n as C,t as w}from"./chunk-ZIRB5QZD-C6fEPe3t.js";var T=`flowchart-`,E=class{constructor(){this.vertexCounter=0,this.config=m(),this.diagramId=``,this.vertices=new Map,this.edges=[],this.classes=new Map,this.subGraphs=[],this.subGraphLookup=new Map,this.tooltips=new Map,this.subCount=0,this.firstGraphFlag=!0,this.secCount=-1,this.posCrossRef=[],this.funs=[],this.setAccTitle=s,this.setAccDescription=a,this.setDiagramTitle=o,this.getAccTitle=h,this.getAccDescription=p,this.getDiagramTitle=ee,this.funs.push(this.setupToolTips.bind(this)),this.addVertex=this.addVertex.bind(this),this.firstGraph=this.firstGraph.bind(this),this.setDirection=this.setDirection.bind(this),this.addSubGraph=this.addSubGraph.bind(this),this.addLink=this.addLink.bind(this),this.setLink=this.setLink.bind(this),this.updateLink=this.updateLink.bind(this),this.addClass=this.addClass.bind(this),this.setClass=this.setClass.bind(this),this.destructLink=this.destructLink.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setTooltip=this.setTooltip.bind(this),this.updateLinkInterpolate=this.updateLinkInterpolate.bind(this),this.setClickFun=this.setClickFun.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.lex={firstGraph:this.firstGraph.bind(this)},this.clear(),this.setGen(`gen-2`)}static{e(this,`FlowDB`)}sanitizeText(e){return f.sanitizeText(e,this.config)}sanitizeNodeLabelType(e){switch(e){case`markdown`:case`string`:case`text`:return e;default:return`markdown`}}setDiagramId(e){this.diagramId=e}lookUpDomId(e){for(let t of this.vertices.values())if(t.id===e)return this.diagramId?`${this.diagramId}-${t.domId}`:t.domId;return this.diagramId?`${this.diagramId}-${e}`:e}addVertex(e,n,r,i,a,o,s={},c){if(!e||e.trim().length===0)return;let l;if(c!==void 0){let e;e=c.includes(` +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{$ as r,G as i,H as a,K as o,U as s,a as c,d as l,it as u,k as d,s as f,v as p,w as ee,x as m,y as h}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as te}from"./channel-C4fgBBJ4.js";import{c as g,g as _}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as ne}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{t as re}from"./chunk-32BRIVSS-DWU3ezKg.js";import{t as v}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as y}from"./chunk-VR4S4FIN-BTo4eV3J.js";import{o as b}from"./chunk-ZGVPDNZ5-DGInJAPD.js";import{r as x,t as S}from"./chunk-FWX5IMBZ-ComLEIwh.js";import{n as C,t as w}from"./chunk-ZIRB5QZD-C6fEPe3t.js";var T=`flowchart-`,E=class{constructor(){this.vertexCounter=0,this.config=m(),this.diagramId=``,this.vertices=new Map,this.edges=[],this.classes=new Map,this.subGraphs=[],this.subGraphLookup=new Map,this.tooltips=new Map,this.subCount=0,this.firstGraphFlag=!0,this.secCount=-1,this.posCrossRef=[],this.funs=[],this.setAccTitle=s,this.setAccDescription=a,this.setDiagramTitle=o,this.getAccTitle=h,this.getAccDescription=p,this.getDiagramTitle=ee,this.funs.push(this.setupToolTips.bind(this)),this.addVertex=this.addVertex.bind(this),this.firstGraph=this.firstGraph.bind(this),this.setDirection=this.setDirection.bind(this),this.addSubGraph=this.addSubGraph.bind(this),this.addLink=this.addLink.bind(this),this.setLink=this.setLink.bind(this),this.updateLink=this.updateLink.bind(this),this.addClass=this.addClass.bind(this),this.setClass=this.setClass.bind(this),this.destructLink=this.destructLink.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setTooltip=this.setTooltip.bind(this),this.updateLinkInterpolate=this.updateLinkInterpolate.bind(this),this.setClickFun=this.setClickFun.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.lex={firstGraph:this.firstGraph.bind(this)},this.clear(),this.setGen(`gen-2`)}static{e(this,`FlowDB`)}sanitizeText(e){return f.sanitizeText(e,this.config)}sanitizeNodeLabelType(e){switch(e){case`markdown`:case`string`:case`text`:return e;default:return`markdown`}}setDiagramId(e){this.diagramId=e}lookUpDomId(e){for(let t of this.vertices.values())if(t.id===e)return this.diagramId?`${this.diagramId}-${t.domId}`:t.domId;return this.diagramId?`${this.diagramId}-${e}`:e}addVertex(e,n,r,i,a,o,s={},c){if(!e||e.trim().length===0)return;let l;if(c!==void 0){let e;e=c.includes(` `)?c+` `:`{ `+c+` diff --git a/.vercel/output/static/assets/chunk-Q4XR5HBZ-5srkZ5CC.js b/.vercel/output/static/assets/chunk-Q4XR5HBZ-CQ8zkLYc.js similarity index 99% rename from .vercel/output/static/assets/chunk-Q4XR5HBZ-5srkZ5CC.js rename to .vercel/output/static/assets/chunk-Q4XR5HBZ-CQ8zkLYc.js index 563764a..3bde446 100644 --- a/.vercel/output/static/assets/chunk-Q4XR5HBZ-5srkZ5CC.js +++ b/.vercel/output/static/assets/chunk-Q4XR5HBZ-CQ8zkLYc.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{A as r,F as i,b as a,s as o,z as s}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{a as c}from"./chunk-ICXQ74PX-fa5hHXws.js";import{n as l,t as u}from"./chunk-HOUHSVGY-4s2dJLwR.js";function d(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var f=d();function p(e){f=e}var m={exec:()=>null};function h(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(_.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var g=(()=>{try{return!0}catch{return!1}})(),_={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`)},ee=/^(?:[ \t]*(?:\n|$))+/,te=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ne=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,v=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,re=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,y=/(?:[*+-]|\d{1,9}[.)])/,ie=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=h(ie).replace(/bull/g,y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),oe=h(ie).replace(/bull/g,y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),b=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,se=/^[^\n]+/,x=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ce=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,x).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),le=h(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,y).getRegex(),S=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,C=/|$))/,ue=h(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,C).replace(`tag`,S).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),de=h(b).replace(`hr`,v).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,S).getRegex(),w={blockquote:h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,de).getRegex(),code:te,def:ce,fences:ne,heading:re,hr:v,html:ue,lheading:ae,list:le,newline:ee,paragraph:de,table:m,text:se},fe=h(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,v).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,S).getRegex(),pe={...w,lheading:oe,table:fe,paragraph:h(b).replace(`hr`,v).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,fe).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,S).getRegex()},me={...w,html:h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,C).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:m,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h(b).replace(`hr`,v).replace(`heading`,` *#{1,6} *[^ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{A as r,F as i,b as a,s as o,z as s}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{a as c}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{n as l,t as u}from"./chunk-HOUHSVGY-iJuv90UH.js";function d(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var f=d();function p(e){f=e}var m={exec:()=>null};function h(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(_.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var g=(()=>{try{return!0}catch{return!1}})(),_={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`)},ee=/^(?:[ \t]*(?:\n|$))+/,te=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ne=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,v=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,re=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,y=/(?:[*+-]|\d{1,9}[.)])/,ie=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=h(ie).replace(/bull/g,y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),oe=h(ie).replace(/bull/g,y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),b=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,se=/^[^\n]+/,x=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ce=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,x).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),le=h(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,y).getRegex(),S=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,C=/|$))/,ue=h(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,C).replace(`tag`,S).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),de=h(b).replace(`hr`,v).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,S).getRegex(),w={blockquote:h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,de).getRegex(),code:te,def:ce,fences:ne,heading:re,hr:v,html:ue,lheading:ae,list:le,newline:ee,paragraph:de,table:m,text:se},fe=h(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,v).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,S).getRegex(),pe={...w,lheading:oe,table:fe,paragraph:h(b).replace(`hr`,v).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,fe).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,S).getRegex()},me={...w,html:h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,C).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:m,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h(b).replace(`hr`,v).replace(`heading`,` *#{1,6} *[^ ]`).replace(`lheading`,ae).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},he=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ge=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,_e=/^( {2,}|\\)\n(?!\s*$)/,ve=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,g?"(?`+)[^`]+\k(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),D=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Te=h(D,`u`).replace(/punct/g,T).getRegex(),Ee=h(D,`u`).replace(/punct/g,xe).getRegex(),O=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,De=h(O,`gu`).replace(/notPunctSpace/g,ye).replace(/punctSpace/g,E).replace(/punct/g,T).getRegex(),Oe=h(O,`gu`).replace(/notPunctSpace/g,Ce).replace(/punctSpace/g,Se).replace(/punct/g,xe).getRegex(),ke=h(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,ye).replace(/punctSpace/g,E).replace(/punct/g,T).getRegex(),Ae=h(/\\(punct)/,`gu`).replace(/punct/g,T).getRegex(),je=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Me=h(C).replace(`(?:-->|$)`,`-->`).getRegex(),Ne=h(`^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^`).replace(`comment`,Me).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),k=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Pe=h(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace(`label`,k).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),A=h(/^!?\[(label)\]\[(ref)\]/).replace(`label`,k).replace(`ref`,x).getRegex(),j=h(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,x).getRegex(),Fe=h(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,A).replace(`nolink`,j).getRegex(),Ie=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,M={_backpedal:m,anyPunctuation:Ae,autolink:je,blockSkip:we,br:_e,code:ge,del:m,emStrongLDelim:Te,emStrongRDelimAst:De,emStrongRDelimUnd:ke,escape:he,link:Pe,nolink:j,punctuation:be,reflink:A,reflinkSearch:Fe,tag:Ne,text:ve,url:m},Le={...M,link:h(/^!?\[(label)\]\((.*?)\)/).replace(`label`,k).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,k).getRegex()},N={...M,emStrongRDelimAst:Oe,emStrongLDelim:Ee,url:h(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Ie).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:h(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":`>`,'"':`"`,"'":`'`},Be=e=>ze[e];function I(e,t){if(t){if(_.escapeTest.test(e))return e.replace(_.escapeReplace,Be)}else if(_.escapeTestNoEncode.test(e))return e.replace(_.escapeReplaceNoEncode,Be);return e}function Ve(e){try{e=encodeURI(e).replace(_.percentDecode,`%`)}catch{return null}return e}function He(e,t){let n=e.replace(_.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(_.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length0?-2:-1}function We(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function Ge(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(` `).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(` `)}var R=class{options;rules;lexer;constructor(e){this.options=e||f}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=t[0].replace(this.rules.other.codeRemoveIndent,``);return{type:`code`,raw:t[0],codeBlockStyle:`indented`,text:this.options.pedantic?e:L(e,` diff --git a/.vercel/output/static/assets/chunk-RYQCIY6F-D_L2RdcQ.js b/.vercel/output/static/assets/chunk-RYQCIY6F-Dtr3kkSR.js similarity index 99% rename from .vercel/output/static/assets/chunk-RYQCIY6F-D_L2RdcQ.js rename to .vercel/output/static/assets/chunk-RYQCIY6F-Dtr3kkSR.js index 4ade77d..3dfcde6 100644 --- a/.vercel/output/static/assets/chunk-RYQCIY6F-D_L2RdcQ.js +++ b/.vercel/output/static/assets/chunk-RYQCIY6F-Dtr3kkSR.js @@ -1 +1 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{r as n,t as r}from"./graphlib-DS17s2tU.js";import{r as i,t as a}from"./map-BaFkSB1l.js";var o=4;function s(e){return i(e,o)}function c(e){var t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:l(e),edges:u(e)};return n(e.graph())||(t.value=s(e.graph())),t}function l(e){return a(e.nodes(),function(t){var r=e.node(t),i=e.parent(t),a={v:t};return n(r)||(a.value=r),n(i)||(a.parent=i),a})}function u(e){return a(e.edges(),function(t){var r=e.edge(t),i={v:t.v,w:t.w};return n(t.name)||(i.name=t.name),n(r)||(i.value=r),i})}var d=new Map,f=new Map,p=new Map,m=e(()=>{f.clear(),p.clear(),d.clear()},`clear`),h=e((e,n)=>{let r=f.get(n)||[];return t.trace(`In isDescendant`,n,` `,e,` = `,r.includes(e)),r.includes(e)},`isDescendant`),g=e((e,n)=>{let r=f.get(n)||[];return t.info(`Descendants of `,n,` is `,r),t.info(`Edge is `,e),e.v===n||e.w===n?!1:r?r.includes(e.v)||h(e.v,n)||h(e.w,n)||r.includes(e.w):(t.debug(`Tilt, `,n,`,not in descendants`),!1)},`edgeInCluster`),_=e((e,n,r,i)=>{t.warn(`Copying children of `,e,`root`,i,`data`,n.node(e),i);let a=n.children(e)||[];e!==i&&a.push(e),t.warn(`Copying (nodes) clusterId`,e,`nodes`,a),a.forEach(a=>{if(n.children(a).length>0)_(a,n,r,i);else{let o=n.node(a);t.info(`cp `,a,` to `,i,` with parent `,e),r.setNode(a,o),i!==n.parent(a)&&(t.warn(`Setting parent`,a,n.parent(a)),r.setParent(a,n.parent(a))),e!==i&&a!==e?(t.debug(`Setting parent`,a,e),r.setParent(a,e)):(t.info(`In copy `,e,`root`,i,`data`,n.node(e),i),t.debug(`Not Setting parent for node=`,a,`cluster!==rootId`,e!==i,`node!==clusterId`,a!==e));let s=n.edges(a);t.debug(`Copying Edges`,s),s.forEach(a=>{t.info(`Edge`,a);let o=n.edge(a.v,a.w,a.name);t.info(`Edge data`,o,i);try{if(g(a,i)){let e=f.get(i)||[],s=e.includes(a.v)||h(a.v,i)||a.v===i,c=e.includes(a.w)||h(a.w,i)||a.w===i;if(s&&c)t.info(`Copying as `,a.v,a.w,o,a.name),r.setEdge(a.v,a.w,o,a.name),t.info(`newGraph edges `,r.edges(),r.edge(r.edges()[0]));else{let e=s?i:a.v,r=c?i:a.w;t.info(`Rebinding cross-boundary edge as `,e,r,o,a.name),n.setEdge(e,r,o,a.name)}}else t.info(`Skipping copy of edge `,a.v,`-->`,a.w,` rootId: `,i,` clusterId:`,e)}catch(e){t.error(e)}})}t.debug(`Removing node`,a),n.removeNode(a)})},`copy`),v=e((e,t)=>{let n=t.children(e),r=[...n];for(let i of n)p.set(i,e),r=[...r,...v(i,t)];return r},`extractDescendants`),y=e((e,t,n)=>{let r=e.edges().filter(e=>e.v===t||e.w===t),i=e.edges().filter(e=>e.v===n||e.w===n),a=r.map(e=>({v:e.v===t?n:e.v,w:e.w===t?t:e.w})),o=i.map(e=>({v:e.v,w:e.w}));return a.filter(e=>o.some(t=>e.v===t.v&&e.w===t.w))},`findCommonEdges`),b=e((e,n,r)=>{let i=n.children(e);if(t.trace(`Searching children of id `,e,i),i.length<1)return e;let a;for(let e of i){let t=b(e,n,r),i=y(n,r,t);if(t)if(i.length>0)a=t;else return t}return a},`findNonClusterChild`),x=e(e=>!d.has(e)||!d.get(e).externalConnections?e:d.has(e)?d.get(e).id:e,`getAnchorId`),S=e((e,n)=>{if(!e||n>10){t.debug(`Opting out, no graph `);return}else t.debug(`Opting in, graph `);e.nodes().forEach(function(n){e.children(n).length>0&&(t.warn(`Cluster identified`,n,` Replacement id in edges: `,b(n,e,n)),f.set(n,v(n,e)),d.set(n,{id:b(n,e,n),clusterData:e.node(n)}))}),e.nodes().forEach(function(n){let r=e.children(n),i=e.edges();r.length>0?(t.debug(`Cluster identified`,n,f),i.forEach(e=>{h(e.v,n)^h(e.w,n)&&(t.warn(`Edge: `,e,` leaves cluster `,n),t.warn(`Descendants of XXX `,n,`: `,f.get(n)),d.get(n).externalConnections=!0)})):t.debug(`Not a cluster `,n,f)});for(let t of d.keys()){let n=d.get(t).id,r=e.parent(n);r!==t&&d.has(r)&&!d.get(r).externalConnections&&(d.get(t).id=r);let i=e.edges().some(e=>e.v===t);if(n&&d.get(t)?.externalConnections&&i&&E(e,n,t)){let r=D(e,t,e.parent(n));r&&(d.get(t).id=r)}}e.edges().forEach(function(n){let r=e.edge(n);t.warn(`Edge `+n.v+` -> `+n.w+`: `+JSON.stringify(n)),t.warn(`Edge `+n.v+` -> `+n.w+`: `+JSON.stringify(e.edge(n)));let i=n.v,a=n.w;if(t.warn(`Fix XXX`,d,`ids:`,n.v,n.w,`Translating: `,d.get(n.v),` --- `,d.get(n.w)),d.get(n.v)||d.get(n.w)){if(t.warn(`Fixing and trying - removing XXX`,n.v,n.w,n.name),i=x(n.v),a=x(n.w),e.removeEdge(n.v,n.w,n.name),i!==n.v){let t=e.parent(i);d.get(t).externalConnections=!0,r.fromCluster=n.v}if(a!==n.w){let t=e.parent(a);d.get(t).externalConnections=!0,r.toCluster=n.w}t.warn(`Fix Replacing with XXX`,i,a,n.name),e.setEdge(i,a,r,n.name)}}),t.warn(`Adjusted Graph`,c(e)),C(e,0),t.trace(d)},`adjustClustersAndEdges`),C=e((e,n)=>{if(t.warn(`extractor - `,n,c(e),e.children(`D`)),n>10){t.error(`Bailing out`);return}let i=e.nodes(),a=!1;for(let t of i){let n=e.children(t);a||=n.length>0}if(!a){t.debug(`Done, no node has children`,e.nodes());return}t.debug(`Nodes = `,i,n);for(let a of i)if(t.debug(`Extracting node`,a,d,d.has(a)&&!d.get(a).externalConnections,!e.parent(a),e.node(a),e.children(`D`),` Depth `,n),!d.has(a))t.debug(`Not a cluster`,a,n);else if(d.get(a)?.clusterData?.explicitDir&&e.children(a)&&e.children(a).length>0){t.warn(`Cluster with explicit dir, creating subgraph for children`,a,n);let i=d.get(a).clusterData.dir,o=new r({multigraph:!0,compound:!0}).setGraph({rankdir:i,nodesep:50,ranksep:50,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}});_(a,e,o,a);let s=e.node(a)||{};e.setNode(a,{...s,clusterNode:!0,id:a,clusterData:d.get(a).clusterData,label:d.get(a).label,graph:o}),t.warn(`Subgraph for cluster with explicit dir created:`,a,c(o))}else if(!d.get(a).externalConnections&&e.children(a)&&e.children(a).length>0){t.warn(`Cluster without external connections, without a parent and with children`,a,n);let i=e.graph().rankdir===`TB`?`LR`:`TB`;d.get(a)?.clusterData?.dir&&(i=d.get(a).clusterData.dir,t.warn(`Fixing dir`,d.get(a).clusterData.dir,i));let o=new r({multigraph:!0,compound:!0}).setGraph({rankdir:i,nodesep:50,ranksep:50,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}});_(a,e,o,a);let s=e.node(a)||{};e.setNode(a,{...s,clusterNode:!0,id:a,clusterData:d.get(a).clusterData,label:d.get(a).label,graph:o}),t.debug(`Old graph after copy`,c(e))}else t.warn(`Cluster ** `,a,` **not meeting the criteria !externalConnections:`,!d.get(a).externalConnections,` no parent: `,!e.parent(a),` children `,e.children(a)&&e.children(a).length>0,e.children(`D`),n),t.debug(d);i=e.nodes(),t.warn(`New list of nodes`,i);for(let r of i){let i=e.node(r);t.warn(` Now next level`,r,i),i?.clusterNode&&C(i.graph,n+1)}},`extractor`),w=e((e,t)=>{if(t.length===0)return[];let n=Object.assign([],t);return t.forEach(t=>{let r=w(e,e.children(t));n=[...n,...r]}),n},`sorter`),T=e(e=>w(e,e.children()),`sortNodesByHierarchy`),E=e((e,t,n)=>{let r=e.parent(t);for(;r&&r!==n;){let t=d.get(r);if(t&&!t.externalConnections)return!0;r=e.parent(r)}return!1},`isNodeInExtractableCluster`),D=e((e,t,n)=>{let r=e.children(t)??[];for(let i of r){if(i===n||h(i,n))continue;let r=b(i,e,t);if(r&&!E(e,r,t))return r}return null},`findSafeAnchorNode`);export{T as a,b as i,m as n,c as o,d as r,S as t}; \ No newline at end of file +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{r as n,t as r}from"./graphlib-DS17s2tU.js";import{r as i,t as a}from"./map-BaFkSB1l.js";var o=4;function s(e){return i(e,o)}function c(e){var t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:l(e),edges:u(e)};return n(e.graph())||(t.value=s(e.graph())),t}function l(e){return a(e.nodes(),function(t){var r=e.node(t),i=e.parent(t),a={v:t};return n(r)||(a.value=r),n(i)||(a.parent=i),a})}function u(e){return a(e.edges(),function(t){var r=e.edge(t),i={v:t.v,w:t.w};return n(t.name)||(i.name=t.name),n(r)||(i.value=r),i})}var d=new Map,f=new Map,p=new Map,m=e(()=>{f.clear(),p.clear(),d.clear()},`clear`),h=e((e,n)=>{let r=f.get(n)||[];return t.trace(`In isDescendant`,n,` `,e,` = `,r.includes(e)),r.includes(e)},`isDescendant`),g=e((e,n)=>{let r=f.get(n)||[];return t.info(`Descendants of `,n,` is `,r),t.info(`Edge is `,e),e.v===n||e.w===n?!1:r?r.includes(e.v)||h(e.v,n)||h(e.w,n)||r.includes(e.w):(t.debug(`Tilt, `,n,`,not in descendants`),!1)},`edgeInCluster`),_=e((e,n,r,i)=>{t.warn(`Copying children of `,e,`root`,i,`data`,n.node(e),i);let a=n.children(e)||[];e!==i&&a.push(e),t.warn(`Copying (nodes) clusterId`,e,`nodes`,a),a.forEach(a=>{if(n.children(a).length>0)_(a,n,r,i);else{let o=n.node(a);t.info(`cp `,a,` to `,i,` with parent `,e),r.setNode(a,o),i!==n.parent(a)&&(t.warn(`Setting parent`,a,n.parent(a)),r.setParent(a,n.parent(a))),e!==i&&a!==e?(t.debug(`Setting parent`,a,e),r.setParent(a,e)):(t.info(`In copy `,e,`root`,i,`data`,n.node(e),i),t.debug(`Not Setting parent for node=`,a,`cluster!==rootId`,e!==i,`node!==clusterId`,a!==e));let s=n.edges(a);t.debug(`Copying Edges`,s),s.forEach(a=>{t.info(`Edge`,a);let o=n.edge(a.v,a.w,a.name);t.info(`Edge data`,o,i);try{if(g(a,i)){let e=f.get(i)||[],s=e.includes(a.v)||h(a.v,i)||a.v===i,c=e.includes(a.w)||h(a.w,i)||a.w===i;if(s&&c)t.info(`Copying as `,a.v,a.w,o,a.name),r.setEdge(a.v,a.w,o,a.name),t.info(`newGraph edges `,r.edges(),r.edge(r.edges()[0]));else{let e=s?i:a.v,r=c?i:a.w;t.info(`Rebinding cross-boundary edge as `,e,r,o,a.name),n.setEdge(e,r,o,a.name)}}else t.info(`Skipping copy of edge `,a.v,`-->`,a.w,` rootId: `,i,` clusterId:`,e)}catch(e){t.error(e)}})}t.debug(`Removing node`,a),n.removeNode(a)})},`copy`),v=e((e,t)=>{let n=t.children(e),r=[...n];for(let i of n)p.set(i,e),r=[...r,...v(i,t)];return r},`extractDescendants`),y=e((e,t,n)=>{let r=e.edges().filter(e=>e.v===t||e.w===t),i=e.edges().filter(e=>e.v===n||e.w===n),a=r.map(e=>({v:e.v===t?n:e.v,w:e.w===t?t:e.w})),o=i.map(e=>({v:e.v,w:e.w}));return a.filter(e=>o.some(t=>e.v===t.v&&e.w===t.w))},`findCommonEdges`),b=e((e,n,r)=>{let i=n.children(e);if(t.trace(`Searching children of id `,e,i),i.length<1)return e;let a;for(let e of i){let t=b(e,n,r),i=y(n,r,t);if(t)if(i.length>0)a=t;else return t}return a},`findNonClusterChild`),x=e(e=>!d.has(e)||!d.get(e).externalConnections?e:d.has(e)?d.get(e).id:e,`getAnchorId`),S=e((e,n)=>{if(!e||n>10){t.debug(`Opting out, no graph `);return}else t.debug(`Opting in, graph `);e.nodes().forEach(function(n){e.children(n).length>0&&(t.warn(`Cluster identified`,n,` Replacement id in edges: `,b(n,e,n)),f.set(n,v(n,e)),d.set(n,{id:b(n,e,n),clusterData:e.node(n)}))}),e.nodes().forEach(function(n){let r=e.children(n),i=e.edges();r.length>0?(t.debug(`Cluster identified`,n,f),i.forEach(e=>{h(e.v,n)^h(e.w,n)&&(t.warn(`Edge: `,e,` leaves cluster `,n),t.warn(`Descendants of XXX `,n,`: `,f.get(n)),d.get(n).externalConnections=!0)})):t.debug(`Not a cluster `,n,f)});for(let t of d.keys()){let n=d.get(t).id,r=e.parent(n);r!==t&&d.has(r)&&!d.get(r).externalConnections&&(d.get(t).id=r);let i=e.edges().some(e=>e.v===t);if(n&&d.get(t)?.externalConnections&&i&&E(e,n,t)){let r=D(e,t,e.parent(n));r&&(d.get(t).id=r)}}e.edges().forEach(function(n){let r=e.edge(n);t.warn(`Edge `+n.v+` -> `+n.w+`: `+JSON.stringify(n)),t.warn(`Edge `+n.v+` -> `+n.w+`: `+JSON.stringify(e.edge(n)));let i=n.v,a=n.w;if(t.warn(`Fix XXX`,d,`ids:`,n.v,n.w,`Translating: `,d.get(n.v),` --- `,d.get(n.w)),d.get(n.v)||d.get(n.w)){if(t.warn(`Fixing and trying - removing XXX`,n.v,n.w,n.name),i=x(n.v),a=x(n.w),e.removeEdge(n.v,n.w,n.name),i!==n.v){let t=e.parent(i);d.get(t).externalConnections=!0,r.fromCluster=n.v}if(a!==n.w){let t=e.parent(a);d.get(t).externalConnections=!0,r.toCluster=n.w}t.warn(`Fix Replacing with XXX`,i,a,n.name),e.setEdge(i,a,r,n.name)}}),t.warn(`Adjusted Graph`,c(e)),C(e,0),t.trace(d)},`adjustClustersAndEdges`),C=e((e,n)=>{if(t.warn(`extractor - `,n,c(e),e.children(`D`)),n>10){t.error(`Bailing out`);return}let i=e.nodes(),a=!1;for(let t of i){let n=e.children(t);a||=n.length>0}if(!a){t.debug(`Done, no node has children`,e.nodes());return}t.debug(`Nodes = `,i,n);for(let a of i)if(t.debug(`Extracting node`,a,d,d.has(a)&&!d.get(a).externalConnections,!e.parent(a),e.node(a),e.children(`D`),` Depth `,n),!d.has(a))t.debug(`Not a cluster`,a,n);else if(d.get(a)?.clusterData?.explicitDir&&e.children(a)&&e.children(a).length>0){t.warn(`Cluster with explicit dir, creating subgraph for children`,a,n);let i=d.get(a).clusterData.dir,o=new r({multigraph:!0,compound:!0}).setGraph({rankdir:i,nodesep:50,ranksep:50,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}});_(a,e,o,a);let s=e.node(a)||{};e.setNode(a,{...s,clusterNode:!0,id:a,clusterData:d.get(a).clusterData,label:d.get(a).label,graph:o}),t.warn(`Subgraph for cluster with explicit dir created:`,a,c(o))}else if(!d.get(a).externalConnections&&e.children(a)&&e.children(a).length>0){t.warn(`Cluster without external connections, without a parent and with children`,a,n);let i=e.graph().rankdir===`TB`?`LR`:`TB`;d.get(a)?.clusterData?.dir&&(i=d.get(a).clusterData.dir,t.warn(`Fixing dir`,d.get(a).clusterData.dir,i));let o=new r({multigraph:!0,compound:!0}).setGraph({rankdir:i,nodesep:50,ranksep:50,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}});_(a,e,o,a);let s=e.node(a)||{};e.setNode(a,{...s,clusterNode:!0,id:a,clusterData:d.get(a).clusterData,label:d.get(a).label,graph:o}),t.debug(`Old graph after copy`,c(e))}else t.warn(`Cluster ** `,a,` **not meeting the criteria !externalConnections:`,!d.get(a).externalConnections,` no parent: `,!e.parent(a),` children `,e.children(a)&&e.children(a).length>0,e.children(`D`),n),t.debug(d);i=e.nodes(),t.warn(`New list of nodes`,i);for(let r of i){let i=e.node(r);t.warn(` Now next level`,r,i),i?.clusterNode&&C(i.graph,n+1)}},`extractor`),w=e((e,t)=>{if(t.length===0)return[];let n=Object.assign([],t);return t.forEach(t=>{let r=w(e,e.children(t));n=[...n,...r]}),n},`sorter`),T=e(e=>w(e,e.children()),`sortNodesByHierarchy`),E=e((e,t,n)=>{let r=e.parent(t);for(;r&&r!==n;){let t=d.get(r);if(t&&!t.externalConnections)return!0;r=e.parent(r)}return!1},`isNodeInExtractableCluster`),D=e((e,t,n)=>{let r=e.children(t)??[];for(let i of r){if(i===n||h(i,n))continue;let r=b(i,e,t);if(r&&!E(e,r,t))return r}return null},`findSafeAnchorNode`);export{T as a,b as i,m as n,c as o,d as r,S as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-V7JOEXUC-BrpprPvX.js b/.vercel/output/static/assets/chunk-V7JOEXUC-Drt5hFEy.js similarity index 99% rename from .vercel/output/static/assets/chunk-V7JOEXUC-BrpprPvX.js rename to .vercel/output/static/assets/chunk-V7JOEXUC-Drt5hFEy.js index 879333f..6f6feb6 100644 --- a/.vercel/output/static/assets/chunk-V7JOEXUC-BrpprPvX.js +++ b/.vercel/output/static/assets/chunk-V7JOEXUC-Drt5hFEy.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{$ as r,H as i,K as a,M as o,U as s,a as c,s as l,v as u,w as d,x as f,y as p,z as m}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{c as h,g}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as _}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{t as v}from"./chunk-32BRIVSS-BtH22FN8.js";import{t as y}from"./chunk-XXDRQBXY-BuE3VzE_.js";import{t as b}from"./chunk-VR4S4FIN-BJzXasDJ.js";import{r as x,t as S}from"./chunk-FWX5IMBZ-CiLc9_ts.js";var C=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,18],r=[1,19],i=[1,20],a=[1,41],o=[1,26],s=[1,42],c=[1,24],l=[1,25],u=[1,32],d=[1,33],f=[1,34],p=[1,45],m=[1,35],h=[1,36],g=[1,37],_=[1,38],v=[1,27],y=[1,28],b=[1,29],x=[1,30],S=[1,31],C=[1,44],w=[1,46],T=[1,43],E=[1,47],D=[1,9],O=[1,8,9],k=[1,58],A=[1,59],j=[1,60],M=[1,61],N=[1,62],P=[1,63],ee=[1,64],F=[1,8,9,41],te=[1,77],I=[1,8,9,12,13,22,39,41,44,46,68,69,70,71,72,73,74,79,81],L=[1,8,9,12,13,18,20,22,39,41,44,46,47,60,68,69,70,71,72,73,74,79,81,86,100,102,103],R=[13,60,86,100,102,103],z=[13,60,73,74,86,100,102,103],ne=[13,60,68,69,70,71,72,86,100,102,103],B=[1,103],V=[1,121],H=[1,117],U=[1,113],W=[1,119],G=[1,114],K=[1,115],q=[1,116],J=[1,118],Y=[1,120],re=[22,50,60,61,82,86,87,88,89,90],ie=[1,128],X=[12,39],ae=[1,8,9,39,41,44,46],Z=[1,8,9,22],oe=[1,153],se=[1,8,9,61],Q=[1,8,9,22,50,60,61,82,86,87,88,89,90],ce={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,statements:5,graphConfig:6,CLASS_DIAGRAM:7,NEWLINE:8,EOF:9,statement:10,classLabel:11,SQS:12,STR:13,SQE:14,namespaceName:15,alphaNumToken:16,classLiteralName:17,DOT:18,className:19,GENERICTYPE:20,relationStatement:21,LABEL:22,namespaceStatement:23,classStatement:24,memberStatement:25,annotationStatement:26,clickStatement:27,styleStatement:28,cssClassStatement:29,noteStatement:30,classDefStatement:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,namespaceIdentifier:38,STRUCT_START:39,classStatements:40,STRUCT_STOP:41,NAMESPACE:42,classIdentifier:43,STYLE_SEPARATOR:44,members:45,ANNOTATION_START:46,ANNOTATION_END:47,CLASS:48,emptyBody:49,SPACE:50,MEMBER:51,SEPARATOR:52,relation:53,NOTE_FOR:54,noteText:55,NOTE:56,CLASSDEF:57,classList:58,stylesOpt:59,ALPHA:60,COMMA:61,direction_tb:62,direction_bt:63,direction_rl:64,direction_lr:65,relationType:66,lineType:67,AGGREGATION:68,EXTENSION:69,COMPOSITION:70,DEPENDENCY:71,LOLLIPOP:72,LINE:73,DOTTED_LINE:74,CALLBACK:75,LINK:76,LINK_TARGET:77,CLICK:78,CALLBACK_NAME:79,CALLBACK_ARGS:80,HREF:81,STYLE:82,CSSCLASS:83,style:84,styleComponent:85,NUM:86,COLON:87,UNIT:88,BRKT:89,PCT:90,commentToken:91,textToken:92,graphCodeTokens:93,textNoTagsToken:94,TAGSTART:95,TAGEND:96,"==":97,"--":98,DEFAULT:99,MINUS:100,keywords:101,UNICODE_TEXT:102,BQUOTE_STR:103,$accept:0,$end:1},terminals_:{2:`error`,7:`CLASS_DIAGRAM`,8:`NEWLINE`,9:`EOF`,12:`SQS`,13:`STR`,14:`SQE`,18:`DOT`,20:`GENERICTYPE`,22:`LABEL`,33:`acc_title`,34:`acc_title_value`,35:`acc_descr`,36:`acc_descr_value`,37:`acc_descr_multiline_value`,39:`STRUCT_START`,41:`STRUCT_STOP`,42:`NAMESPACE`,44:`STYLE_SEPARATOR`,46:`ANNOTATION_START`,47:`ANNOTATION_END`,48:`CLASS`,50:`SPACE`,51:`MEMBER`,52:`SEPARATOR`,54:`NOTE_FOR`,56:`NOTE`,57:`CLASSDEF`,60:`ALPHA`,61:`COMMA`,62:`direction_tb`,63:`direction_bt`,64:`direction_rl`,65:`direction_lr`,68:`AGGREGATION`,69:`EXTENSION`,70:`COMPOSITION`,71:`DEPENDENCY`,72:`LOLLIPOP`,73:`LINE`,74:`DOTTED_LINE`,75:`CALLBACK`,76:`LINK`,77:`LINK_TARGET`,78:`CLICK`,79:`CALLBACK_NAME`,80:`CALLBACK_ARGS`,81:`HREF`,82:`STYLE`,83:`CSSCLASS`,86:`NUM`,87:`COLON`,88:`UNIT`,89:`BRKT`,90:`PCT`,93:`graphCodeTokens`,95:`TAGSTART`,96:`TAGEND`,97:`==`,98:`--`,99:`DEFAULT`,100:`MINUS`,101:`keywords`,102:`UNICODE_TEXT`,103:`BQUOTE_STR`},productions_:[0,[3,1],[3,1],[4,1],[6,4],[5,1],[5,2],[5,3],[11,3],[15,1],[15,1],[15,3],[15,2],[19,1],[19,3],[19,1],[19,2],[19,2],[19,2],[10,1],[10,2],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,2],[10,2],[10,1],[23,4],[23,5],[38,2],[38,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[24,1],[24,3],[24,4],[24,3],[24,6],[24,4],[24,7],[24,6],[43,2],[43,3],[49,0],[49,2],[49,2],[26,4],[45,1],[45,2],[25,1],[25,2],[25,1],[25,1],[21,3],[21,4],[21,4],[21,5],[30,3],[30,2],[31,3],[58,1],[58,3],[32,1],[32,1],[32,1],[32,1],[53,3],[53,2],[53,2],[53,1],[66,1],[66,1],[66,1],[66,1],[66,1],[67,1],[67,1],[27,3],[27,4],[27,3],[27,4],[27,4],[27,5],[27,3],[27,4],[27,4],[27,5],[27,4],[27,5],[27,5],[27,6],[28,3],[29,3],[59,1],[59,3],[84,1],[84,2],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[91,1],[91,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[94,1],[94,1],[94,1],[94,1],[16,1],[16,1],[16,1],[16,1],[17,1],[55,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 8:this.$=a[s-1];break;case 9:case 10:case 13:case 15:this.$=a[s];break;case 11:case 14:this.$=a[s-2]+`.`+a[s];break;case 12:case 16:this.$=a[s-1]+a[s];break;case 17:case 18:this.$=a[s-1]+`~`+a[s]+`~`;break;case 19:r.addRelation(a[s]);break;case 20:a[s-1].title=r.cleanupLabel(a[s]),r.addRelation(a[s-1]);break;case 31:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 32:case 33:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 34:r.addClassesToNamespace(a[s-3],a[s-1][0],a[s-1][1]),r.popNamespace();break;case 35:r.addClassesToNamespace(a[s-4],a[s-1][0],a[s-1][1]),r.popNamespace();break;case 36:this.$=r.addNamespace(a[s]);break;case 37:this.$=r.addNamespace(a[s-1],a[s]);break;case 38:this.$=[[a[s]],[]];break;case 39:this.$=[[a[s-1]],[]];break;case 40:a[s][0].unshift(a[s-2]),this.$=a[s];break;case 41:this.$=[[],[a[s]]];break;case 42:this.$=[[],[a[s-1]]];break;case 43:a[s][1].unshift(a[s-2]),this.$=a[s];break;case 44:case 45:this.$=[[],[]];break;case 46:this.$=a[s];break;case 48:r.setCssClass(a[s-2],a[s]);break;case 49:r.addMembers(a[s-3],a[s-1]);break;case 51:r.setCssClass(a[s-5],a[s-3]),r.addMembers(a[s-5],a[s-1]);break;case 52:r.addAnnotation(a[s-3],a[s-1]);break;case 53:r.addAnnotation(a[s-6],a[s-4]),r.addMembers(a[s-6],a[s-1]);break;case 54:r.addAnnotation(a[s-5],a[s-3]);break;case 55:this.$=a[s],r.addClass(a[s]);break;case 56:this.$=a[s-1],r.addClass(a[s-1]),r.setClassLabel(a[s-1],a[s]);break;case 60:r.addAnnotation(a[s],a[s-2]);break;case 61:case 74:this.$=[a[s]];break;case 62:a[s].push(a[s-1]),this.$=a[s];break;case 63:break;case 64:r.addMember(a[s-1],r.cleanupLabel(a[s]));break;case 65:break;case 66:break;case 67:this.$={id1:a[s-2],id2:a[s],relation:a[s-1],relationTitle1:`none`,relationTitle2:`none`};break;case 68:this.$={id1:a[s-3],id2:a[s],relation:a[s-1],relationTitle1:a[s-2],relationTitle2:`none`};break;case 69:this.$={id1:a[s-3],id2:a[s],relation:a[s-2],relationTitle1:`none`,relationTitle2:a[s-1]};break;case 70:this.$={id1:a[s-4],id2:a[s],relation:a[s-2],relationTitle1:a[s-3],relationTitle2:a[s-1]};break;case 71:this.$=r.addNote(a[s],a[s-1]);break;case 72:this.$=r.addNote(a[s]);break;case 73:this.$=a[s-2],r.defineClass(a[s-1],a[s]);break;case 75:this.$=a[s-2].concat([a[s]]);break;case 76:r.setDirection(`TB`);break;case 77:r.setDirection(`BT`);break;case 78:r.setDirection(`RL`);break;case 79:r.setDirection(`LR`);break;case 80:this.$={type1:a[s-2],type2:a[s],lineType:a[s-1]};break;case 81:this.$={type1:`none`,type2:a[s],lineType:a[s-1]};break;case 82:this.$={type1:a[s-1],type2:`none`,lineType:a[s]};break;case 83:this.$={type1:`none`,type2:`none`,lineType:a[s]};break;case 84:this.$=r.relationType.AGGREGATION;break;case 85:this.$=r.relationType.EXTENSION;break;case 86:this.$=r.relationType.COMPOSITION;break;case 87:this.$=r.relationType.DEPENDENCY;break;case 88:this.$=r.relationType.LOLLIPOP;break;case 89:this.$=r.lineType.LINE;break;case 90:this.$=r.lineType.DOTTED_LINE;break;case 91:case 97:this.$=a[s-2],r.setClickEvent(a[s-1],a[s]);break;case 92:case 98:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 93:this.$=a[s-2],r.setLink(a[s-1],a[s]);break;case 94:this.$=a[s-3],r.setLink(a[s-2],a[s-1],a[s]);break;case 95:this.$=a[s-3],r.setLink(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 96:this.$=a[s-4],r.setLink(a[s-3],a[s-2],a[s]),r.setTooltip(a[s-3],a[s-1]);break;case 99:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 100:this.$=a[s-4],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setTooltip(a[s-3],a[s]);break;case 101:this.$=a[s-3],r.setLink(a[s-2],a[s]);break;case 102:this.$=a[s-4],r.setLink(a[s-3],a[s-1],a[s]);break;case 103:this.$=a[s-4],r.setLink(a[s-3],a[s-1]),r.setTooltip(a[s-3],a[s]);break;case 104:this.$=a[s-5],r.setLink(a[s-4],a[s-2],a[s]),r.setTooltip(a[s-4],a[s-1]);break;case 105:this.$=a[s-2],r.setCssStyle(a[s-1],a[s]);break;case 106:r.setCssClass(a[s-1],a[s]);break;case 107:this.$=[a[s]];break;case 108:a[s-2].push(a[s]),this.$=a[s-2];break;case 110:this.$=a[s-1]+a[s];break}},`anonymous`),table:[{3:1,4:2,5:3,6:4,7:[1,6],10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:n,35:r,37:i,38:22,42:a,43:23,46:o,48:s,51:c,52:l,54:u,56:d,57:f,60:p,62:m,63:h,64:g,65:_,75:v,76:y,78:b,82:x,83:S,86:C,100:w,102:T,103:E},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,3]},t(D,[2,5],{8:[1,48]}),{8:[1,49]},t(O,[2,19],{22:[1,50]}),t(O,[2,21]),t(O,[2,22]),t(O,[2,23]),t(O,[2,24]),t(O,[2,25]),t(O,[2,26]),t(O,[2,27]),t(O,[2,28]),t(O,[2,29]),t(O,[2,30]),{34:[1,51]},{36:[1,52]},t(O,[2,33]),t(O,[2,63],{53:53,66:56,67:57,13:[1,54],22:[1,55],68:k,69:A,70:j,71:M,72:N,73:P,74:ee}),{39:[1,65]},t(F,[2,47],{39:[1,67],44:[1,66],46:[1,68]}),t(O,[2,65]),t(O,[2,66]),{16:69,60:p,86:C,100:w,102:T},{16:39,17:40,19:70,60:p,86:C,100:w,102:T,103:E},{16:39,17:40,19:71,60:p,86:C,100:w,102:T,103:E},{16:39,17:40,19:72,60:p,86:C,100:w,102:T,103:E},{60:[1,73]},{13:[1,74]},{16:39,17:40,19:75,60:p,86:C,100:w,102:T,103:E},{13:te,55:76},{58:78,60:[1,79]},t(O,[2,76]),t(O,[2,77]),t(O,[2,78]),t(O,[2,79]),t(I,[2,13],{16:39,17:40,19:81,18:[1,80],20:[1,82],60:p,86:C,100:w,102:T,103:E}),t(I,[2,15],{20:[1,83]}),{15:84,16:85,17:86,60:p,86:C,100:w,102:T,103:E},{16:39,17:40,19:87,60:p,86:C,100:w,102:T,103:E},t(L,[2,133]),t(L,[2,134]),t(L,[2,135]),t(L,[2,136]),t([1,8,9,12,13,20,22,39,41,44,46,68,69,70,71,72,73,74,79,81],[2,137]),t(D,[2,6],{10:5,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,19:21,38:22,43:23,16:39,17:40,5:88,33:n,35:r,37:i,42:a,46:o,48:s,51:c,52:l,54:u,56:d,57:f,60:p,62:m,63:h,64:g,65:_,75:v,76:y,78:b,82:x,83:S,86:C,100:w,102:T,103:E}),{5:89,10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:n,35:r,37:i,38:22,42:a,43:23,46:o,48:s,51:c,52:l,54:u,56:d,57:f,60:p,62:m,63:h,64:g,65:_,75:v,76:y,78:b,82:x,83:S,86:C,100:w,102:T,103:E},t(O,[2,20]),t(O,[2,31]),t(O,[2,32]),{13:[1,91],16:39,17:40,19:90,60:p,86:C,100:w,102:T,103:E},{53:92,66:56,67:57,68:k,69:A,70:j,71:M,72:N,73:P,74:ee},t(O,[2,64]),{67:93,73:P,74:ee},t(R,[2,83],{66:94,68:k,69:A,70:j,71:M,72:N}),t(z,[2,84]),t(z,[2,85]),t(z,[2,86]),t(z,[2,87]),t(z,[2,88]),t(ne,[2,89]),t(ne,[2,90]),{8:[1,96],23:99,24:97,30:98,38:22,40:95,42:a,43:23,48:s,54:u,56:d},{16:100,60:p,86:C,100:w,102:T},{41:[1,102],45:101,51:B},{16:104,60:p,86:C,100:w,102:T},{47:[1,105]},{13:[1,106]},{13:[1,107]},{79:[1,108],81:[1,109]},{22:V,50:H,59:110,60:U,82:W,84:111,85:112,86:G,87:K,88:q,89:J,90:Y},{60:[1,122]},{13:te,55:123},t(F,[2,72]),t(F,[2,138]),{22:V,50:H,59:124,60:U,61:[1,125],82:W,84:111,85:112,86:G,87:K,88:q,89:J,90:Y},t(re,[2,74]),{16:39,17:40,19:126,60:p,86:C,100:w,102:T,103:E},t(I,[2,16]),t(I,[2,17]),t(I,[2,18]),{11:127,12:ie,39:[2,36]},t(X,[2,9],{16:85,17:86,15:130,18:[1,129],60:p,86:C,100:w,102:T,103:E}),t(X,[2,10]),t(ae,[2,55],{11:131,12:ie}),t(D,[2,7]),{9:[1,132]},t(Z,[2,67]),{16:39,17:40,19:133,60:p,86:C,100:w,102:T,103:E},{13:[1,135],16:39,17:40,19:134,60:p,86:C,100:w,102:T,103:E},t(R,[2,82],{66:136,68:k,69:A,70:j,71:M,72:N}),t(R,[2,81]),{41:[1,137]},{23:99,24:97,30:98,38:22,40:138,42:a,43:23,48:s,54:u,56:d},{8:[1,139],41:[2,38]},{8:[1,140],41:[2,41]},{8:[1,141],41:[2,44]},t(F,[2,48],{39:[1,142]}),{41:[1,143]},t(F,[2,50]),{41:[2,61],45:144,51:B},{47:[1,145]},{16:39,17:40,19:146,60:p,86:C,100:w,102:T,103:E},t(O,[2,91],{13:[1,147]}),t(O,[2,93],{13:[1,149],77:[1,148]}),t(O,[2,97],{13:[1,150],80:[1,151]}),{13:[1,152]},t(O,[2,105],{61:oe}),t(se,[2,107],{85:154,22:V,50:H,60:U,82:W,86:G,87:K,88:q,89:J,90:Y}),t(Q,[2,109]),t(Q,[2,111]),t(Q,[2,112]),t(Q,[2,113]),t(Q,[2,114]),t(Q,[2,115]),t(Q,[2,116]),t(Q,[2,117]),t(Q,[2,118]),t(Q,[2,119]),t(O,[2,106]),t(F,[2,71]),t(O,[2,73],{61:oe}),{60:[1,155]},t(I,[2,14]),{39:[2,37]},{13:[1,156]},{15:157,16:85,17:86,60:p,86:C,100:w,102:T,103:E},t(X,[2,12]),t(ae,[2,56]),{1:[2,4]},t(Z,[2,69]),t(Z,[2,68]),{16:39,17:40,19:158,60:p,86:C,100:w,102:T,103:E},t(R,[2,80]),t(F,[2,34]),{41:[1,159]},{23:99,24:97,30:98,38:22,40:160,41:[2,39],42:a,43:23,48:s,54:u,56:d},{23:99,24:97,30:98,38:22,40:161,41:[2,42],42:a,43:23,48:s,54:u,56:d},{23:99,24:97,30:98,38:22,40:162,41:[2,45],42:a,43:23,48:s,54:u,56:d},{45:163,51:B},t(F,[2,49]),{41:[2,62]},t(F,[2,52],{39:[1,164]}),t(O,[2,60]),t(O,[2,92]),t(O,[2,94]),t(O,[2,95],{77:[1,165]}),t(O,[2,98]),t(O,[2,99],{13:[1,166]}),t(O,[2,101],{13:[1,168],77:[1,167]}),{22:V,50:H,60:U,82:W,84:169,85:112,86:G,87:K,88:q,89:J,90:Y},t(Q,[2,110]),t(re,[2,75]),{14:[1,170]},t(X,[2,11]),t(Z,[2,70]),t(F,[2,35]),{41:[2,40]},{41:[2,43]},{41:[2,46]},{41:[1,171]},{41:[1,173],45:172,51:B},t(O,[2,96]),t(O,[2,100]),t(O,[2,102]),t(O,[2,103],{77:[1,174]}),t(se,[2,108],{85:154,22:V,50:H,60:U,82:W,86:G,87:K,88:q,89:J,90:Y}),t(ae,[2,8]),t(F,[2,51]),{41:[1,175]},t(F,[2,54]),t(O,[2,104]),t(F,[2,53])],defaultActions:{2:[2,1],3:[2,2],4:[2,3],127:[2,37],132:[2,4],144:[2,62],160:[2,40],161:[2,43],162:[2,46]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{$ as r,H as i,K as a,M as o,U as s,a as c,s as l,v as u,w as d,x as f,y as p,z as m}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{c as h,g}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as _}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{t as v}from"./chunk-32BRIVSS-DWU3ezKg.js";import{t as y}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as b}from"./chunk-VR4S4FIN-BTo4eV3J.js";import{r as x,t as S}from"./chunk-FWX5IMBZ-ComLEIwh.js";var C=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,18],r=[1,19],i=[1,20],a=[1,41],o=[1,26],s=[1,42],c=[1,24],l=[1,25],u=[1,32],d=[1,33],f=[1,34],p=[1,45],m=[1,35],h=[1,36],g=[1,37],_=[1,38],v=[1,27],y=[1,28],b=[1,29],x=[1,30],S=[1,31],C=[1,44],w=[1,46],T=[1,43],E=[1,47],D=[1,9],O=[1,8,9],k=[1,58],A=[1,59],j=[1,60],M=[1,61],N=[1,62],P=[1,63],ee=[1,64],F=[1,8,9,41],te=[1,77],I=[1,8,9,12,13,22,39,41,44,46,68,69,70,71,72,73,74,79,81],L=[1,8,9,12,13,18,20,22,39,41,44,46,47,60,68,69,70,71,72,73,74,79,81,86,100,102,103],R=[13,60,86,100,102,103],z=[13,60,73,74,86,100,102,103],ne=[13,60,68,69,70,71,72,86,100,102,103],B=[1,103],V=[1,121],H=[1,117],U=[1,113],W=[1,119],G=[1,114],K=[1,115],q=[1,116],J=[1,118],Y=[1,120],re=[22,50,60,61,82,86,87,88,89,90],ie=[1,128],X=[12,39],ae=[1,8,9,39,41,44,46],Z=[1,8,9,22],oe=[1,153],se=[1,8,9,61],Q=[1,8,9,22,50,60,61,82,86,87,88,89,90],ce={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,statements:5,graphConfig:6,CLASS_DIAGRAM:7,NEWLINE:8,EOF:9,statement:10,classLabel:11,SQS:12,STR:13,SQE:14,namespaceName:15,alphaNumToken:16,classLiteralName:17,DOT:18,className:19,GENERICTYPE:20,relationStatement:21,LABEL:22,namespaceStatement:23,classStatement:24,memberStatement:25,annotationStatement:26,clickStatement:27,styleStatement:28,cssClassStatement:29,noteStatement:30,classDefStatement:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,namespaceIdentifier:38,STRUCT_START:39,classStatements:40,STRUCT_STOP:41,NAMESPACE:42,classIdentifier:43,STYLE_SEPARATOR:44,members:45,ANNOTATION_START:46,ANNOTATION_END:47,CLASS:48,emptyBody:49,SPACE:50,MEMBER:51,SEPARATOR:52,relation:53,NOTE_FOR:54,noteText:55,NOTE:56,CLASSDEF:57,classList:58,stylesOpt:59,ALPHA:60,COMMA:61,direction_tb:62,direction_bt:63,direction_rl:64,direction_lr:65,relationType:66,lineType:67,AGGREGATION:68,EXTENSION:69,COMPOSITION:70,DEPENDENCY:71,LOLLIPOP:72,LINE:73,DOTTED_LINE:74,CALLBACK:75,LINK:76,LINK_TARGET:77,CLICK:78,CALLBACK_NAME:79,CALLBACK_ARGS:80,HREF:81,STYLE:82,CSSCLASS:83,style:84,styleComponent:85,NUM:86,COLON:87,UNIT:88,BRKT:89,PCT:90,commentToken:91,textToken:92,graphCodeTokens:93,textNoTagsToken:94,TAGSTART:95,TAGEND:96,"==":97,"--":98,DEFAULT:99,MINUS:100,keywords:101,UNICODE_TEXT:102,BQUOTE_STR:103,$accept:0,$end:1},terminals_:{2:`error`,7:`CLASS_DIAGRAM`,8:`NEWLINE`,9:`EOF`,12:`SQS`,13:`STR`,14:`SQE`,18:`DOT`,20:`GENERICTYPE`,22:`LABEL`,33:`acc_title`,34:`acc_title_value`,35:`acc_descr`,36:`acc_descr_value`,37:`acc_descr_multiline_value`,39:`STRUCT_START`,41:`STRUCT_STOP`,42:`NAMESPACE`,44:`STYLE_SEPARATOR`,46:`ANNOTATION_START`,47:`ANNOTATION_END`,48:`CLASS`,50:`SPACE`,51:`MEMBER`,52:`SEPARATOR`,54:`NOTE_FOR`,56:`NOTE`,57:`CLASSDEF`,60:`ALPHA`,61:`COMMA`,62:`direction_tb`,63:`direction_bt`,64:`direction_rl`,65:`direction_lr`,68:`AGGREGATION`,69:`EXTENSION`,70:`COMPOSITION`,71:`DEPENDENCY`,72:`LOLLIPOP`,73:`LINE`,74:`DOTTED_LINE`,75:`CALLBACK`,76:`LINK`,77:`LINK_TARGET`,78:`CLICK`,79:`CALLBACK_NAME`,80:`CALLBACK_ARGS`,81:`HREF`,82:`STYLE`,83:`CSSCLASS`,86:`NUM`,87:`COLON`,88:`UNIT`,89:`BRKT`,90:`PCT`,93:`graphCodeTokens`,95:`TAGSTART`,96:`TAGEND`,97:`==`,98:`--`,99:`DEFAULT`,100:`MINUS`,101:`keywords`,102:`UNICODE_TEXT`,103:`BQUOTE_STR`},productions_:[0,[3,1],[3,1],[4,1],[6,4],[5,1],[5,2],[5,3],[11,3],[15,1],[15,1],[15,3],[15,2],[19,1],[19,3],[19,1],[19,2],[19,2],[19,2],[10,1],[10,2],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,2],[10,2],[10,1],[23,4],[23,5],[38,2],[38,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[24,1],[24,3],[24,4],[24,3],[24,6],[24,4],[24,7],[24,6],[43,2],[43,3],[49,0],[49,2],[49,2],[26,4],[45,1],[45,2],[25,1],[25,2],[25,1],[25,1],[21,3],[21,4],[21,4],[21,5],[30,3],[30,2],[31,3],[58,1],[58,3],[32,1],[32,1],[32,1],[32,1],[53,3],[53,2],[53,2],[53,1],[66,1],[66,1],[66,1],[66,1],[66,1],[67,1],[67,1],[27,3],[27,4],[27,3],[27,4],[27,4],[27,5],[27,3],[27,4],[27,4],[27,5],[27,4],[27,5],[27,5],[27,6],[28,3],[29,3],[59,1],[59,3],[84,1],[84,2],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[91,1],[91,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[94,1],[94,1],[94,1],[94,1],[16,1],[16,1],[16,1],[16,1],[17,1],[55,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 8:this.$=a[s-1];break;case 9:case 10:case 13:case 15:this.$=a[s];break;case 11:case 14:this.$=a[s-2]+`.`+a[s];break;case 12:case 16:this.$=a[s-1]+a[s];break;case 17:case 18:this.$=a[s-1]+`~`+a[s]+`~`;break;case 19:r.addRelation(a[s]);break;case 20:a[s-1].title=r.cleanupLabel(a[s]),r.addRelation(a[s-1]);break;case 31:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 32:case 33:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 34:r.addClassesToNamespace(a[s-3],a[s-1][0],a[s-1][1]),r.popNamespace();break;case 35:r.addClassesToNamespace(a[s-4],a[s-1][0],a[s-1][1]),r.popNamespace();break;case 36:this.$=r.addNamespace(a[s]);break;case 37:this.$=r.addNamespace(a[s-1],a[s]);break;case 38:this.$=[[a[s]],[]];break;case 39:this.$=[[a[s-1]],[]];break;case 40:a[s][0].unshift(a[s-2]),this.$=a[s];break;case 41:this.$=[[],[a[s]]];break;case 42:this.$=[[],[a[s-1]]];break;case 43:a[s][1].unshift(a[s-2]),this.$=a[s];break;case 44:case 45:this.$=[[],[]];break;case 46:this.$=a[s];break;case 48:r.setCssClass(a[s-2],a[s]);break;case 49:r.addMembers(a[s-3],a[s-1]);break;case 51:r.setCssClass(a[s-5],a[s-3]),r.addMembers(a[s-5],a[s-1]);break;case 52:r.addAnnotation(a[s-3],a[s-1]);break;case 53:r.addAnnotation(a[s-6],a[s-4]),r.addMembers(a[s-6],a[s-1]);break;case 54:r.addAnnotation(a[s-5],a[s-3]);break;case 55:this.$=a[s],r.addClass(a[s]);break;case 56:this.$=a[s-1],r.addClass(a[s-1]),r.setClassLabel(a[s-1],a[s]);break;case 60:r.addAnnotation(a[s],a[s-2]);break;case 61:case 74:this.$=[a[s]];break;case 62:a[s].push(a[s-1]),this.$=a[s];break;case 63:break;case 64:r.addMember(a[s-1],r.cleanupLabel(a[s]));break;case 65:break;case 66:break;case 67:this.$={id1:a[s-2],id2:a[s],relation:a[s-1],relationTitle1:`none`,relationTitle2:`none`};break;case 68:this.$={id1:a[s-3],id2:a[s],relation:a[s-1],relationTitle1:a[s-2],relationTitle2:`none`};break;case 69:this.$={id1:a[s-3],id2:a[s],relation:a[s-2],relationTitle1:`none`,relationTitle2:a[s-1]};break;case 70:this.$={id1:a[s-4],id2:a[s],relation:a[s-2],relationTitle1:a[s-3],relationTitle2:a[s-1]};break;case 71:this.$=r.addNote(a[s],a[s-1]);break;case 72:this.$=r.addNote(a[s]);break;case 73:this.$=a[s-2],r.defineClass(a[s-1],a[s]);break;case 75:this.$=a[s-2].concat([a[s]]);break;case 76:r.setDirection(`TB`);break;case 77:r.setDirection(`BT`);break;case 78:r.setDirection(`RL`);break;case 79:r.setDirection(`LR`);break;case 80:this.$={type1:a[s-2],type2:a[s],lineType:a[s-1]};break;case 81:this.$={type1:`none`,type2:a[s],lineType:a[s-1]};break;case 82:this.$={type1:a[s-1],type2:`none`,lineType:a[s]};break;case 83:this.$={type1:`none`,type2:`none`,lineType:a[s]};break;case 84:this.$=r.relationType.AGGREGATION;break;case 85:this.$=r.relationType.EXTENSION;break;case 86:this.$=r.relationType.COMPOSITION;break;case 87:this.$=r.relationType.DEPENDENCY;break;case 88:this.$=r.relationType.LOLLIPOP;break;case 89:this.$=r.lineType.LINE;break;case 90:this.$=r.lineType.DOTTED_LINE;break;case 91:case 97:this.$=a[s-2],r.setClickEvent(a[s-1],a[s]);break;case 92:case 98:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 93:this.$=a[s-2],r.setLink(a[s-1],a[s]);break;case 94:this.$=a[s-3],r.setLink(a[s-2],a[s-1],a[s]);break;case 95:this.$=a[s-3],r.setLink(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 96:this.$=a[s-4],r.setLink(a[s-3],a[s-2],a[s]),r.setTooltip(a[s-3],a[s-1]);break;case 99:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 100:this.$=a[s-4],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setTooltip(a[s-3],a[s]);break;case 101:this.$=a[s-3],r.setLink(a[s-2],a[s]);break;case 102:this.$=a[s-4],r.setLink(a[s-3],a[s-1],a[s]);break;case 103:this.$=a[s-4],r.setLink(a[s-3],a[s-1]),r.setTooltip(a[s-3],a[s]);break;case 104:this.$=a[s-5],r.setLink(a[s-4],a[s-2],a[s]),r.setTooltip(a[s-4],a[s-1]);break;case 105:this.$=a[s-2],r.setCssStyle(a[s-1],a[s]);break;case 106:r.setCssClass(a[s-1],a[s]);break;case 107:this.$=[a[s]];break;case 108:a[s-2].push(a[s]),this.$=a[s-2];break;case 110:this.$=a[s-1]+a[s];break}},`anonymous`),table:[{3:1,4:2,5:3,6:4,7:[1,6],10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:n,35:r,37:i,38:22,42:a,43:23,46:o,48:s,51:c,52:l,54:u,56:d,57:f,60:p,62:m,63:h,64:g,65:_,75:v,76:y,78:b,82:x,83:S,86:C,100:w,102:T,103:E},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,3]},t(D,[2,5],{8:[1,48]}),{8:[1,49]},t(O,[2,19],{22:[1,50]}),t(O,[2,21]),t(O,[2,22]),t(O,[2,23]),t(O,[2,24]),t(O,[2,25]),t(O,[2,26]),t(O,[2,27]),t(O,[2,28]),t(O,[2,29]),t(O,[2,30]),{34:[1,51]},{36:[1,52]},t(O,[2,33]),t(O,[2,63],{53:53,66:56,67:57,13:[1,54],22:[1,55],68:k,69:A,70:j,71:M,72:N,73:P,74:ee}),{39:[1,65]},t(F,[2,47],{39:[1,67],44:[1,66],46:[1,68]}),t(O,[2,65]),t(O,[2,66]),{16:69,60:p,86:C,100:w,102:T},{16:39,17:40,19:70,60:p,86:C,100:w,102:T,103:E},{16:39,17:40,19:71,60:p,86:C,100:w,102:T,103:E},{16:39,17:40,19:72,60:p,86:C,100:w,102:T,103:E},{60:[1,73]},{13:[1,74]},{16:39,17:40,19:75,60:p,86:C,100:w,102:T,103:E},{13:te,55:76},{58:78,60:[1,79]},t(O,[2,76]),t(O,[2,77]),t(O,[2,78]),t(O,[2,79]),t(I,[2,13],{16:39,17:40,19:81,18:[1,80],20:[1,82],60:p,86:C,100:w,102:T,103:E}),t(I,[2,15],{20:[1,83]}),{15:84,16:85,17:86,60:p,86:C,100:w,102:T,103:E},{16:39,17:40,19:87,60:p,86:C,100:w,102:T,103:E},t(L,[2,133]),t(L,[2,134]),t(L,[2,135]),t(L,[2,136]),t([1,8,9,12,13,20,22,39,41,44,46,68,69,70,71,72,73,74,79,81],[2,137]),t(D,[2,6],{10:5,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,19:21,38:22,43:23,16:39,17:40,5:88,33:n,35:r,37:i,42:a,46:o,48:s,51:c,52:l,54:u,56:d,57:f,60:p,62:m,63:h,64:g,65:_,75:v,76:y,78:b,82:x,83:S,86:C,100:w,102:T,103:E}),{5:89,10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:n,35:r,37:i,38:22,42:a,43:23,46:o,48:s,51:c,52:l,54:u,56:d,57:f,60:p,62:m,63:h,64:g,65:_,75:v,76:y,78:b,82:x,83:S,86:C,100:w,102:T,103:E},t(O,[2,20]),t(O,[2,31]),t(O,[2,32]),{13:[1,91],16:39,17:40,19:90,60:p,86:C,100:w,102:T,103:E},{53:92,66:56,67:57,68:k,69:A,70:j,71:M,72:N,73:P,74:ee},t(O,[2,64]),{67:93,73:P,74:ee},t(R,[2,83],{66:94,68:k,69:A,70:j,71:M,72:N}),t(z,[2,84]),t(z,[2,85]),t(z,[2,86]),t(z,[2,87]),t(z,[2,88]),t(ne,[2,89]),t(ne,[2,90]),{8:[1,96],23:99,24:97,30:98,38:22,40:95,42:a,43:23,48:s,54:u,56:d},{16:100,60:p,86:C,100:w,102:T},{41:[1,102],45:101,51:B},{16:104,60:p,86:C,100:w,102:T},{47:[1,105]},{13:[1,106]},{13:[1,107]},{79:[1,108],81:[1,109]},{22:V,50:H,59:110,60:U,82:W,84:111,85:112,86:G,87:K,88:q,89:J,90:Y},{60:[1,122]},{13:te,55:123},t(F,[2,72]),t(F,[2,138]),{22:V,50:H,59:124,60:U,61:[1,125],82:W,84:111,85:112,86:G,87:K,88:q,89:J,90:Y},t(re,[2,74]),{16:39,17:40,19:126,60:p,86:C,100:w,102:T,103:E},t(I,[2,16]),t(I,[2,17]),t(I,[2,18]),{11:127,12:ie,39:[2,36]},t(X,[2,9],{16:85,17:86,15:130,18:[1,129],60:p,86:C,100:w,102:T,103:E}),t(X,[2,10]),t(ae,[2,55],{11:131,12:ie}),t(D,[2,7]),{9:[1,132]},t(Z,[2,67]),{16:39,17:40,19:133,60:p,86:C,100:w,102:T,103:E},{13:[1,135],16:39,17:40,19:134,60:p,86:C,100:w,102:T,103:E},t(R,[2,82],{66:136,68:k,69:A,70:j,71:M,72:N}),t(R,[2,81]),{41:[1,137]},{23:99,24:97,30:98,38:22,40:138,42:a,43:23,48:s,54:u,56:d},{8:[1,139],41:[2,38]},{8:[1,140],41:[2,41]},{8:[1,141],41:[2,44]},t(F,[2,48],{39:[1,142]}),{41:[1,143]},t(F,[2,50]),{41:[2,61],45:144,51:B},{47:[1,145]},{16:39,17:40,19:146,60:p,86:C,100:w,102:T,103:E},t(O,[2,91],{13:[1,147]}),t(O,[2,93],{13:[1,149],77:[1,148]}),t(O,[2,97],{13:[1,150],80:[1,151]}),{13:[1,152]},t(O,[2,105],{61:oe}),t(se,[2,107],{85:154,22:V,50:H,60:U,82:W,86:G,87:K,88:q,89:J,90:Y}),t(Q,[2,109]),t(Q,[2,111]),t(Q,[2,112]),t(Q,[2,113]),t(Q,[2,114]),t(Q,[2,115]),t(Q,[2,116]),t(Q,[2,117]),t(Q,[2,118]),t(Q,[2,119]),t(O,[2,106]),t(F,[2,71]),t(O,[2,73],{61:oe}),{60:[1,155]},t(I,[2,14]),{39:[2,37]},{13:[1,156]},{15:157,16:85,17:86,60:p,86:C,100:w,102:T,103:E},t(X,[2,12]),t(ae,[2,56]),{1:[2,4]},t(Z,[2,69]),t(Z,[2,68]),{16:39,17:40,19:158,60:p,86:C,100:w,102:T,103:E},t(R,[2,80]),t(F,[2,34]),{41:[1,159]},{23:99,24:97,30:98,38:22,40:160,41:[2,39],42:a,43:23,48:s,54:u,56:d},{23:99,24:97,30:98,38:22,40:161,41:[2,42],42:a,43:23,48:s,54:u,56:d},{23:99,24:97,30:98,38:22,40:162,41:[2,45],42:a,43:23,48:s,54:u,56:d},{45:163,51:B},t(F,[2,49]),{41:[2,62]},t(F,[2,52],{39:[1,164]}),t(O,[2,60]),t(O,[2,92]),t(O,[2,94]),t(O,[2,95],{77:[1,165]}),t(O,[2,98]),t(O,[2,99],{13:[1,166]}),t(O,[2,101],{13:[1,168],77:[1,167]}),{22:V,50:H,60:U,82:W,84:169,85:112,86:G,87:K,88:q,89:J,90:Y},t(Q,[2,110]),t(re,[2,75]),{14:[1,170]},t(X,[2,11]),t(Z,[2,70]),t(F,[2,35]),{41:[2,40]},{41:[2,43]},{41:[2,46]},{41:[1,171]},{41:[1,173],45:172,51:B},t(O,[2,96]),t(O,[2,100]),t(O,[2,102]),t(O,[2,103],{77:[1,174]}),t(se,[2,108],{85:154,22:V,50:H,60:U,82:W,86:G,87:K,88:q,89:J,90:Y}),t(ae,[2,8]),t(F,[2,51]),{41:[1,175]},t(F,[2,54]),t(O,[2,104]),t(F,[2,53])],defaultActions:{2:[2,1],3:[2,2],4:[2,3],127:[2,37],132:[2,4],144:[2,62],160:[2,40],161:[2,43],162:[2,46]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};ce.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/chunk-VAUOI2AC-CLN1Ga8_.js b/.vercel/output/static/assets/chunk-VAUOI2AC-AC9pRUsa.js similarity index 60% rename from .vercel/output/static/assets/chunk-VAUOI2AC-CLN1Ga8_.js rename to .vercel/output/static/assets/chunk-VAUOI2AC-AC9pRUsa.js index 09b7d44..a0785ba 100644 --- a/.vercel/output/static/assets/chunk-VAUOI2AC-CLN1Ga8_.js +++ b/.vercel/output/static/assets/chunk-VAUOI2AC-AC9pRUsa.js @@ -1 +1 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-_wZywoZs.js";import{x as n}from"./chunk-WYO6CB5R-ajGU-pWR.js";var r=e(e=>{let{securityLevel:r}=n(),i=t(`body`);return r===`sandbox`&&(i=t((t(`#i${e}`).node()?.contentDocument??document).body)),i.select(`#${e}`)},`selectSvgElement`);export{r as t}; \ No newline at end of file +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{x as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var r=e(e=>{let{securityLevel:r}=n(),i=t(`body`);return r===`sandbox`&&(i=t((t(`#i${e}`).node()?.contentDocument??document).body)),i.select(`#${e}`)},`selectSvgElement`);export{r as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-VR4S4FIN-BJzXasDJ.js b/.vercel/output/static/assets/chunk-VR4S4FIN-BTo4eV3J.js similarity index 77% rename from .vercel/output/static/assets/chunk-VR4S4FIN-BJzXasDJ.js rename to .vercel/output/static/assets/chunk-VR4S4FIN-BTo4eV3J.js index bc0aabb..6e01b65 100644 --- a/.vercel/output/static/assets/chunk-VR4S4FIN-BJzXasDJ.js +++ b/.vercel/output/static/assets/chunk-VR4S4FIN-BTo4eV3J.js @@ -1 +1 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{c as n}from"./chunk-WYO6CB5R-ajGU-pWR.js";var r=e((e,r,o,s)=>{e.attr(`class`,o);let{width:c,height:l,x:u,y:d}=i(e,r);n(e,l,c,s);let f=a(u,d,c,l,r);e.attr(`viewBox`,f),t.debug(`viewBox configured: ${f} with padding: ${r}`)},`setupViewPortForSVG`),i=e((e,t)=>{let n=e.node()?.getBBox()||{width:0,height:0,x:0,y:0};return{width:n.width+t*2,height:n.height+t*2,x:n.x,y:n.y}},`calculateDimensionsWithPadding`),a=e((e,t,n,r,i)=>`${e-i} ${t-i} ${n} ${r}`,`createViewBox`);export{r as t}; \ No newline at end of file +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{c as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var r=e((e,r,o,s)=>{e.attr(`class`,o);let{width:c,height:l,x:u,y:d}=i(e,r);n(e,l,c,s);let f=a(u,d,c,l,r);e.attr(`viewBox`,f),t.debug(`viewBox configured: ${f} with padding: ${r}`)},`setupViewPortForSVG`),i=e((e,t)=>{let n=e.node()?.getBBox()||{width:0,height:0,x:0,y:0};return{width:n.width+t*2,height:n.height+t*2,x:n.x,y:n.y}},`calculateDimensionsWithPadding`),a=e((e,t,n,r,i)=>`${e-i} ${t-i} ${n} ${r}`,`createViewBox`);export{r as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-WYO6CB5R-ajGU-pWR.js b/.vercel/output/static/assets/chunk-WYO6CB5R-Dv5kDyQC.js similarity index 99% rename from .vercel/output/static/assets/chunk-WYO6CB5R-ajGU-pWR.js rename to .vercel/output/static/assets/chunk-WYO6CB5R-Dv5kDyQC.js index 752ffa4..2c2ab99 100644 --- a/.vercel/output/static/assets/chunk-WYO6CB5R-ajGU-pWR.js +++ b/.vercel/output/static/assets/chunk-WYO6CB5R-Dv5kDyQC.js @@ -1,4 +1,4 @@ -import{t as e}from"./index-DU4A6Ttf.js";import{n as t,t as n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{h as r,m as i}from"./src-_wZywoZs.js";var a={min:{r:0,g:0,b:0,s:0,l:0,a:0},max:{r:255,g:255,b:255,h:360,s:100,l:100,a:1},clamp:{r:e=>e>=255?255:e<0?0:e,g:e=>e>=255?255:e<0?0:e,b:e=>e>=255?255:e<0?0:e,h:e=>e%360,s:e=>e>=100?100:e<0?0:e,l:e=>e>=100?100:e<0?0:e,a:e=>e>=1?1:e<0?0:e},toLinear:e=>{let t=e/255;return e>.03928?((t+.055)/1.055)**2.4:t/12.92},hue2rgb:(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e),hsl2rgb:({h:e,s:t,l:n},r)=>{if(!t)return n*2.55;e/=360,t/=100,n/=100;let i=n<.5?n*(1+t):n+t-n*t,o=2*n-i;switch(r){case`r`:return a.hue2rgb(o,i,e+1/3)*255;case`g`:return a.hue2rgb(o,i,e)*255;case`b`:return a.hue2rgb(o,i,e-1/3)*255}},rgb2hsl:({r:e,g:t,b:n},r)=>{e/=255,t/=255,n/=255;let i=Math.max(e,t,n),a=Math.min(e,t,n),o=(i+a)/2;if(r===`l`)return o*100;if(i===a)return 0;let s=i-a,c=o>.5?s/(2-i-a):s/(i+a);if(r===`s`)return c*100;switch(i){case e:return((t-n)/s+(tt>n?Math.min(t,Math.max(n,e)):Math.min(n,Math.max(t,e)),round:e=>Math.round(e*1e10)/1e10},unit:{dec2hex:e=>{let t=Math.round(e).toString(16);return t.length>1?t:`0${t}`}}},s={};for(let e=0;e<=255;e++)s[e]=o.unit.dec2hex(e);var c={ALL:0,RGB:1,HSL:2},l=class{constructor(){this.type=c.ALL}get(){return this.type}set(e){if(this.type&&this.type!==e)throw Error(`Cannot change both RGB and HSL channels at the same time`);this.type=e}reset(){this.type=c.ALL}is(e){return this.type===e}},u=new class{constructor(e,t){this.color=t,this.changed=!1,this.data=e,this.type=new l}set(e,t){return this.color=t,this.changed=!1,this.data=e,this.type.type=c.ALL,this}_ensureHSL(){let e=this.data,{h:t,s:n,l:r}=e;t===void 0&&(e.h=o.channel.rgb2hsl(e,`h`)),n===void 0&&(e.s=o.channel.rgb2hsl(e,`s`)),r===void 0&&(e.l=o.channel.rgb2hsl(e,`l`))}_ensureRGB(){let e=this.data,{r:t,g:n,b:r}=e;t===void 0&&(e.r=o.channel.hsl2rgb(e,`r`)),n===void 0&&(e.g=o.channel.hsl2rgb(e,`g`)),r===void 0&&(e.b=o.channel.hsl2rgb(e,`b`))}get r(){let e=this.data,t=e.r;return!this.type.is(c.HSL)&&t!==void 0?t:(this._ensureHSL(),o.channel.hsl2rgb(e,`r`))}get g(){let e=this.data,t=e.g;return!this.type.is(c.HSL)&&t!==void 0?t:(this._ensureHSL(),o.channel.hsl2rgb(e,`g`))}get b(){let e=this.data,t=e.b;return!this.type.is(c.HSL)&&t!==void 0?t:(this._ensureHSL(),o.channel.hsl2rgb(e,`b`))}get h(){let e=this.data,t=e.h;return!this.type.is(c.RGB)&&t!==void 0?t:(this._ensureRGB(),o.channel.rgb2hsl(e,`h`))}get s(){let e=this.data,t=e.s;return!this.type.is(c.RGB)&&t!==void 0?t:(this._ensureRGB(),o.channel.rgb2hsl(e,`s`))}get l(){let e=this.data,t=e.l;return!this.type.is(c.RGB)&&t!==void 0?t:(this._ensureRGB(),o.channel.rgb2hsl(e,`l`))}get a(){return this.data.a}set r(e){this.type.set(c.RGB),this.changed=!0,this.data.r=e}set g(e){this.type.set(c.RGB),this.changed=!0,this.data.g=e}set b(e){this.type.set(c.RGB),this.changed=!0,this.data.b=e}set h(e){this.type.set(c.HSL),this.changed=!0,this.data.h=e}set s(e){this.type.set(c.HSL),this.changed=!0,this.data.s=e}set l(e){this.type.set(c.HSL),this.changed=!0,this.data.l=e}set a(e){this.changed=!0,this.data.a=e}}({r:0,g:0,b:0,a:0},`transparent`),d={re:/^#((?:[a-f0-9]{2}){2,4}|[a-f0-9]{3})$/i,parse:e=>{if(e.charCodeAt(0)!==35)return;let t=e.match(d.re);if(!t)return;let n=t[1],r=parseInt(n,16),i=n.length,a=i%4==0,o=i>4,s=o?1:17,c=o?8:4,l=a?0:-1,f=o?255:15;return u.set({r:(r>>c*(l+3)&f)*s,g:(r>>c*(l+2)&f)*s,b:(r>>c*(l+1)&f)*s,a:a?(r&f)*s/255:1},e)},stringify:e=>{let{r:t,g:n,b:r,a:i}=e;return i<1?`#${s[Math.round(t)]}${s[Math.round(n)]}${s[Math.round(r)]}${s[Math.round(i*255)]}`:`#${s[Math.round(t)]}${s[Math.round(n)]}${s[Math.round(r)]}`}},f={re:/^hsla?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(?:deg|grad|rad|turn)?)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(%)?))?\s*?\)$/i,hueRe:/^(.+?)(deg|grad|rad|turn)$/i,_hue2deg:e=>{let t=e.match(f.hueRe);if(t){let[,e,n]=t;switch(n){case`grad`:return o.channel.clamp.h(parseFloat(e)*.9);case`rad`:return o.channel.clamp.h(parseFloat(e)*180/Math.PI);case`turn`:return o.channel.clamp.h(parseFloat(e)*360)}}return o.channel.clamp.h(parseFloat(e))},parse:e=>{let t=e.charCodeAt(0);if(t!==104&&t!==72)return;let n=e.match(f.re);if(!n)return;let[,r,i,a,s,c]=n;return u.set({h:f._hue2deg(r),s:o.channel.clamp.s(parseFloat(i)),l:o.channel.clamp.l(parseFloat(a)),a:s?o.channel.clamp.a(c?parseFloat(s)/100:parseFloat(s)):1},e)},stringify:e=>{let{h:t,s:n,l:r,a:i}=e;return i<1?`hsla(${o.lang.round(t)}, ${o.lang.round(n)}%, ${o.lang.round(r)}%, ${i})`:`hsl(${o.lang.round(t)}, ${o.lang.round(n)}%, ${o.lang.round(r)}%)`}},p={colors:{aliceblue:`#f0f8ff`,antiquewhite:`#faebd7`,aqua:`#00ffff`,aquamarine:`#7fffd4`,azure:`#f0ffff`,beige:`#f5f5dc`,bisque:`#ffe4c4`,black:`#000000`,blanchedalmond:`#ffebcd`,blue:`#0000ff`,blueviolet:`#8a2be2`,brown:`#a52a2a`,burlywood:`#deb887`,cadetblue:`#5f9ea0`,chartreuse:`#7fff00`,chocolate:`#d2691e`,coral:`#ff7f50`,cornflowerblue:`#6495ed`,cornsilk:`#fff8dc`,crimson:`#dc143c`,cyanaqua:`#00ffff`,darkblue:`#00008b`,darkcyan:`#008b8b`,darkgoldenrod:`#b8860b`,darkgray:`#a9a9a9`,darkgreen:`#006400`,darkgrey:`#a9a9a9`,darkkhaki:`#bdb76b`,darkmagenta:`#8b008b`,darkolivegreen:`#556b2f`,darkorange:`#ff8c00`,darkorchid:`#9932cc`,darkred:`#8b0000`,darksalmon:`#e9967a`,darkseagreen:`#8fbc8f`,darkslateblue:`#483d8b`,darkslategray:`#2f4f4f`,darkslategrey:`#2f4f4f`,darkturquoise:`#00ced1`,darkviolet:`#9400d3`,deeppink:`#ff1493`,deepskyblue:`#00bfff`,dimgray:`#696969`,dimgrey:`#696969`,dodgerblue:`#1e90ff`,firebrick:`#b22222`,floralwhite:`#fffaf0`,forestgreen:`#228b22`,fuchsia:`#ff00ff`,gainsboro:`#dcdcdc`,ghostwhite:`#f8f8ff`,gold:`#ffd700`,goldenrod:`#daa520`,gray:`#808080`,green:`#008000`,greenyellow:`#adff2f`,grey:`#808080`,honeydew:`#f0fff0`,hotpink:`#ff69b4`,indianred:`#cd5c5c`,indigo:`#4b0082`,ivory:`#fffff0`,khaki:`#f0e68c`,lavender:`#e6e6fa`,lavenderblush:`#fff0f5`,lawngreen:`#7cfc00`,lemonchiffon:`#fffacd`,lightblue:`#add8e6`,lightcoral:`#f08080`,lightcyan:`#e0ffff`,lightgoldenrodyellow:`#fafad2`,lightgray:`#d3d3d3`,lightgreen:`#90ee90`,lightgrey:`#d3d3d3`,lightpink:`#ffb6c1`,lightsalmon:`#ffa07a`,lightseagreen:`#20b2aa`,lightskyblue:`#87cefa`,lightslategray:`#778899`,lightslategrey:`#778899`,lightsteelblue:`#b0c4de`,lightyellow:`#ffffe0`,lime:`#00ff00`,limegreen:`#32cd32`,linen:`#faf0e6`,magenta:`#ff00ff`,maroon:`#800000`,mediumaquamarine:`#66cdaa`,mediumblue:`#0000cd`,mediumorchid:`#ba55d3`,mediumpurple:`#9370db`,mediumseagreen:`#3cb371`,mediumslateblue:`#7b68ee`,mediumspringgreen:`#00fa9a`,mediumturquoise:`#48d1cc`,mediumvioletred:`#c71585`,midnightblue:`#191970`,mintcream:`#f5fffa`,mistyrose:`#ffe4e1`,moccasin:`#ffe4b5`,navajowhite:`#ffdead`,navy:`#000080`,oldlace:`#fdf5e6`,olive:`#808000`,olivedrab:`#6b8e23`,orange:`#ffa500`,orangered:`#ff4500`,orchid:`#da70d6`,palegoldenrod:`#eee8aa`,palegreen:`#98fb98`,paleturquoise:`#afeeee`,palevioletred:`#db7093`,papayawhip:`#ffefd5`,peachpuff:`#ffdab9`,peru:`#cd853f`,pink:`#ffc0cb`,plum:`#dda0dd`,powderblue:`#b0e0e6`,purple:`#800080`,rebeccapurple:`#663399`,red:`#ff0000`,rosybrown:`#bc8f8f`,royalblue:`#4169e1`,saddlebrown:`#8b4513`,salmon:`#fa8072`,sandybrown:`#f4a460`,seagreen:`#2e8b57`,seashell:`#fff5ee`,sienna:`#a0522d`,silver:`#c0c0c0`,skyblue:`#87ceeb`,slateblue:`#6a5acd`,slategray:`#708090`,slategrey:`#708090`,snow:`#fffafa`,springgreen:`#00ff7f`,tan:`#d2b48c`,teal:`#008080`,thistle:`#d8bfd8`,transparent:`#00000000`,turquoise:`#40e0d0`,violet:`#ee82ee`,wheat:`#f5deb3`,white:`#ffffff`,whitesmoke:`#f5f5f5`,yellow:`#ffff00`,yellowgreen:`#9acd32`},parse:e=>{e=e.toLowerCase();let t=p.colors[e];if(t)return d.parse(t)},stringify:e=>{let t=d.stringify(e);for(let e in p.colors)if(p.colors[e]===t)return e}},m={re:/^rgba?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?)))?\s*?\)$/i,parse:e=>{let t=e.charCodeAt(0);if(t!==114&&t!==82)return;let n=e.match(m.re);if(!n)return;let[,r,i,a,s,c,l,d,f]=n;return u.set({r:o.channel.clamp.r(i?parseFloat(r)*2.55:parseFloat(r)),g:o.channel.clamp.g(s?parseFloat(a)*2.55:parseFloat(a)),b:o.channel.clamp.b(l?parseFloat(c)*2.55:parseFloat(c)),a:d?o.channel.clamp.a(f?parseFloat(d)/100:parseFloat(d)):1},e)},stringify:e=>{let{r:t,g:n,b:r,a:i}=e;return i<1?`rgba(${o.lang.round(t)}, ${o.lang.round(n)}, ${o.lang.round(r)}, ${o.lang.round(i)})`:`rgb(${o.lang.round(t)}, ${o.lang.round(n)}, ${o.lang.round(r)})`}},h={format:{keyword:p,hex:d,rgb:m,rgba:m,hsl:f,hsla:f},parse:e=>{if(typeof e!=`string`)return e;let t=d.parse(e)||m.parse(e)||f.parse(e)||p.parse(e);if(t)return t;throw Error(`Unsupported color format: "${e}"`)},stringify:e=>!e.changed&&e.color?e.color:e.type.is(c.HSL)||e.data.r===void 0?f.stringify(e):e.a<1||!Number.isInteger(e.r)||!Number.isInteger(e.g)||!Number.isInteger(e.b)?m.stringify(e):d.stringify(e)},g=(e,t)=>{let n=h.parse(e);for(let e in t)n[e]=o.channel.clamp[e](t[e]);return h.stringify(n)},_=(e,t,n=0,r=1)=>{if(typeof e!=`number`)return g(e,{a:t});let i=u.set({r:o.channel.clamp.r(e),g:o.channel.clamp.g(t),b:o.channel.clamp.b(n),a:o.channel.clamp.a(r)});return h.stringify(i)},ee=e=>{let{r:t,g:n,b:r}=h.parse(e),i=.2126*o.channel.toLinear(t)+.7152*o.channel.toLinear(n)+.0722*o.channel.toLinear(r);return o.lang.round(i)},v=e=>ee(e)>=.5,y=e=>!v(e),b=(e,t,n)=>{let r=h.parse(e),i=r[t],a=o.channel.clamp[t](i+n);return i!==a&&(r[t]=a),h.stringify(r)},x=(e,t)=>b(e,`l`,t),S=(e,t)=>b(e,`l`,-t),C=(e,t)=>{let n=h.parse(e),r={};for(let e in t)t[e]&&(r[e]=n[e]+t[e]);return g(e,r)},te=(e,t,n=50)=>{let{r,g:i,b:a,a:o}=h.parse(e),{r:s,g:c,b:l,a:u}=h.parse(t),d=n/100,f=d*2-1,p=o-u,m=((f*p===-1?f:(f+p)/(1+f*p))+1)/2,g=1-m;return _(r*m+s*g,i*m+c*g,a*m+l*g,o*d+u*(1-d))},w=(e,t=100)=>{let n=h.parse(e);return n.r=255-n.r,n.g=255-n.g,n.b=255-n.b,te(n,e,t)};function ne(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);ne>=255?255:e<0?0:e,g:e=>e>=255?255:e<0?0:e,b:e=>e>=255?255:e<0?0:e,h:e=>e%360,s:e=>e>=100?100:e<0?0:e,l:e=>e>=100?100:e<0?0:e,a:e=>e>=1?1:e<0?0:e},toLinear:e=>{let t=e/255;return e>.03928?((t+.055)/1.055)**2.4:t/12.92},hue2rgb:(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e),hsl2rgb:({h:e,s:t,l:n},r)=>{if(!t)return n*2.55;e/=360,t/=100,n/=100;let i=n<.5?n*(1+t):n+t-n*t,o=2*n-i;switch(r){case`r`:return a.hue2rgb(o,i,e+1/3)*255;case`g`:return a.hue2rgb(o,i,e)*255;case`b`:return a.hue2rgb(o,i,e-1/3)*255}},rgb2hsl:({r:e,g:t,b:n},r)=>{e/=255,t/=255,n/=255;let i=Math.max(e,t,n),a=Math.min(e,t,n),o=(i+a)/2;if(r===`l`)return o*100;if(i===a)return 0;let s=i-a,c=o>.5?s/(2-i-a):s/(i+a);if(r===`s`)return c*100;switch(i){case e:return((t-n)/s+(tt>n?Math.min(t,Math.max(n,e)):Math.min(n,Math.max(t,e)),round:e=>Math.round(e*1e10)/1e10},unit:{dec2hex:e=>{let t=Math.round(e).toString(16);return t.length>1?t:`0${t}`}}},s={};for(let e=0;e<=255;e++)s[e]=o.unit.dec2hex(e);var c={ALL:0,RGB:1,HSL:2},l=class{constructor(){this.type=c.ALL}get(){return this.type}set(e){if(this.type&&this.type!==e)throw Error(`Cannot change both RGB and HSL channels at the same time`);this.type=e}reset(){this.type=c.ALL}is(e){return this.type===e}},u=new class{constructor(e,t){this.color=t,this.changed=!1,this.data=e,this.type=new l}set(e,t){return this.color=t,this.changed=!1,this.data=e,this.type.type=c.ALL,this}_ensureHSL(){let e=this.data,{h:t,s:n,l:r}=e;t===void 0&&(e.h=o.channel.rgb2hsl(e,`h`)),n===void 0&&(e.s=o.channel.rgb2hsl(e,`s`)),r===void 0&&(e.l=o.channel.rgb2hsl(e,`l`))}_ensureRGB(){let e=this.data,{r:t,g:n,b:r}=e;t===void 0&&(e.r=o.channel.hsl2rgb(e,`r`)),n===void 0&&(e.g=o.channel.hsl2rgb(e,`g`)),r===void 0&&(e.b=o.channel.hsl2rgb(e,`b`))}get r(){let e=this.data,t=e.r;return!this.type.is(c.HSL)&&t!==void 0?t:(this._ensureHSL(),o.channel.hsl2rgb(e,`r`))}get g(){let e=this.data,t=e.g;return!this.type.is(c.HSL)&&t!==void 0?t:(this._ensureHSL(),o.channel.hsl2rgb(e,`g`))}get b(){let e=this.data,t=e.b;return!this.type.is(c.HSL)&&t!==void 0?t:(this._ensureHSL(),o.channel.hsl2rgb(e,`b`))}get h(){let e=this.data,t=e.h;return!this.type.is(c.RGB)&&t!==void 0?t:(this._ensureRGB(),o.channel.rgb2hsl(e,`h`))}get s(){let e=this.data,t=e.s;return!this.type.is(c.RGB)&&t!==void 0?t:(this._ensureRGB(),o.channel.rgb2hsl(e,`s`))}get l(){let e=this.data,t=e.l;return!this.type.is(c.RGB)&&t!==void 0?t:(this._ensureRGB(),o.channel.rgb2hsl(e,`l`))}get a(){return this.data.a}set r(e){this.type.set(c.RGB),this.changed=!0,this.data.r=e}set g(e){this.type.set(c.RGB),this.changed=!0,this.data.g=e}set b(e){this.type.set(c.RGB),this.changed=!0,this.data.b=e}set h(e){this.type.set(c.HSL),this.changed=!0,this.data.h=e}set s(e){this.type.set(c.HSL),this.changed=!0,this.data.s=e}set l(e){this.type.set(c.HSL),this.changed=!0,this.data.l=e}set a(e){this.changed=!0,this.data.a=e}}({r:0,g:0,b:0,a:0},`transparent`),d={re:/^#((?:[a-f0-9]{2}){2,4}|[a-f0-9]{3})$/i,parse:e=>{if(e.charCodeAt(0)!==35)return;let t=e.match(d.re);if(!t)return;let n=t[1],r=parseInt(n,16),i=n.length,a=i%4==0,o=i>4,s=o?1:17,c=o?8:4,l=a?0:-1,f=o?255:15;return u.set({r:(r>>c*(l+3)&f)*s,g:(r>>c*(l+2)&f)*s,b:(r>>c*(l+1)&f)*s,a:a?(r&f)*s/255:1},e)},stringify:e=>{let{r:t,g:n,b:r,a:i}=e;return i<1?`#${s[Math.round(t)]}${s[Math.round(n)]}${s[Math.round(r)]}${s[Math.round(i*255)]}`:`#${s[Math.round(t)]}${s[Math.round(n)]}${s[Math.round(r)]}`}},f={re:/^hsla?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(?:deg|grad|rad|turn)?)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(%)?))?\s*?\)$/i,hueRe:/^(.+?)(deg|grad|rad|turn)$/i,_hue2deg:e=>{let t=e.match(f.hueRe);if(t){let[,e,n]=t;switch(n){case`grad`:return o.channel.clamp.h(parseFloat(e)*.9);case`rad`:return o.channel.clamp.h(parseFloat(e)*180/Math.PI);case`turn`:return o.channel.clamp.h(parseFloat(e)*360)}}return o.channel.clamp.h(parseFloat(e))},parse:e=>{let t=e.charCodeAt(0);if(t!==104&&t!==72)return;let n=e.match(f.re);if(!n)return;let[,r,i,a,s,c]=n;return u.set({h:f._hue2deg(r),s:o.channel.clamp.s(parseFloat(i)),l:o.channel.clamp.l(parseFloat(a)),a:s?o.channel.clamp.a(c?parseFloat(s)/100:parseFloat(s)):1},e)},stringify:e=>{let{h:t,s:n,l:r,a:i}=e;return i<1?`hsla(${o.lang.round(t)}, ${o.lang.round(n)}%, ${o.lang.round(r)}%, ${i})`:`hsl(${o.lang.round(t)}, ${o.lang.round(n)}%, ${o.lang.round(r)}%)`}},p={colors:{aliceblue:`#f0f8ff`,antiquewhite:`#faebd7`,aqua:`#00ffff`,aquamarine:`#7fffd4`,azure:`#f0ffff`,beige:`#f5f5dc`,bisque:`#ffe4c4`,black:`#000000`,blanchedalmond:`#ffebcd`,blue:`#0000ff`,blueviolet:`#8a2be2`,brown:`#a52a2a`,burlywood:`#deb887`,cadetblue:`#5f9ea0`,chartreuse:`#7fff00`,chocolate:`#d2691e`,coral:`#ff7f50`,cornflowerblue:`#6495ed`,cornsilk:`#fff8dc`,crimson:`#dc143c`,cyanaqua:`#00ffff`,darkblue:`#00008b`,darkcyan:`#008b8b`,darkgoldenrod:`#b8860b`,darkgray:`#a9a9a9`,darkgreen:`#006400`,darkgrey:`#a9a9a9`,darkkhaki:`#bdb76b`,darkmagenta:`#8b008b`,darkolivegreen:`#556b2f`,darkorange:`#ff8c00`,darkorchid:`#9932cc`,darkred:`#8b0000`,darksalmon:`#e9967a`,darkseagreen:`#8fbc8f`,darkslateblue:`#483d8b`,darkslategray:`#2f4f4f`,darkslategrey:`#2f4f4f`,darkturquoise:`#00ced1`,darkviolet:`#9400d3`,deeppink:`#ff1493`,deepskyblue:`#00bfff`,dimgray:`#696969`,dimgrey:`#696969`,dodgerblue:`#1e90ff`,firebrick:`#b22222`,floralwhite:`#fffaf0`,forestgreen:`#228b22`,fuchsia:`#ff00ff`,gainsboro:`#dcdcdc`,ghostwhite:`#f8f8ff`,gold:`#ffd700`,goldenrod:`#daa520`,gray:`#808080`,green:`#008000`,greenyellow:`#adff2f`,grey:`#808080`,honeydew:`#f0fff0`,hotpink:`#ff69b4`,indianred:`#cd5c5c`,indigo:`#4b0082`,ivory:`#fffff0`,khaki:`#f0e68c`,lavender:`#e6e6fa`,lavenderblush:`#fff0f5`,lawngreen:`#7cfc00`,lemonchiffon:`#fffacd`,lightblue:`#add8e6`,lightcoral:`#f08080`,lightcyan:`#e0ffff`,lightgoldenrodyellow:`#fafad2`,lightgray:`#d3d3d3`,lightgreen:`#90ee90`,lightgrey:`#d3d3d3`,lightpink:`#ffb6c1`,lightsalmon:`#ffa07a`,lightseagreen:`#20b2aa`,lightskyblue:`#87cefa`,lightslategray:`#778899`,lightslategrey:`#778899`,lightsteelblue:`#b0c4de`,lightyellow:`#ffffe0`,lime:`#00ff00`,limegreen:`#32cd32`,linen:`#faf0e6`,magenta:`#ff00ff`,maroon:`#800000`,mediumaquamarine:`#66cdaa`,mediumblue:`#0000cd`,mediumorchid:`#ba55d3`,mediumpurple:`#9370db`,mediumseagreen:`#3cb371`,mediumslateblue:`#7b68ee`,mediumspringgreen:`#00fa9a`,mediumturquoise:`#48d1cc`,mediumvioletred:`#c71585`,midnightblue:`#191970`,mintcream:`#f5fffa`,mistyrose:`#ffe4e1`,moccasin:`#ffe4b5`,navajowhite:`#ffdead`,navy:`#000080`,oldlace:`#fdf5e6`,olive:`#808000`,olivedrab:`#6b8e23`,orange:`#ffa500`,orangered:`#ff4500`,orchid:`#da70d6`,palegoldenrod:`#eee8aa`,palegreen:`#98fb98`,paleturquoise:`#afeeee`,palevioletred:`#db7093`,papayawhip:`#ffefd5`,peachpuff:`#ffdab9`,peru:`#cd853f`,pink:`#ffc0cb`,plum:`#dda0dd`,powderblue:`#b0e0e6`,purple:`#800080`,rebeccapurple:`#663399`,red:`#ff0000`,rosybrown:`#bc8f8f`,royalblue:`#4169e1`,saddlebrown:`#8b4513`,salmon:`#fa8072`,sandybrown:`#f4a460`,seagreen:`#2e8b57`,seashell:`#fff5ee`,sienna:`#a0522d`,silver:`#c0c0c0`,skyblue:`#87ceeb`,slateblue:`#6a5acd`,slategray:`#708090`,slategrey:`#708090`,snow:`#fffafa`,springgreen:`#00ff7f`,tan:`#d2b48c`,teal:`#008080`,thistle:`#d8bfd8`,transparent:`#00000000`,turquoise:`#40e0d0`,violet:`#ee82ee`,wheat:`#f5deb3`,white:`#ffffff`,whitesmoke:`#f5f5f5`,yellow:`#ffff00`,yellowgreen:`#9acd32`},parse:e=>{e=e.toLowerCase();let t=p.colors[e];if(t)return d.parse(t)},stringify:e=>{let t=d.stringify(e);for(let e in p.colors)if(p.colors[e]===t)return e}},m={re:/^rgba?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?)))?\s*?\)$/i,parse:e=>{let t=e.charCodeAt(0);if(t!==114&&t!==82)return;let n=e.match(m.re);if(!n)return;let[,r,i,a,s,c,l,d,f]=n;return u.set({r:o.channel.clamp.r(i?parseFloat(r)*2.55:parseFloat(r)),g:o.channel.clamp.g(s?parseFloat(a)*2.55:parseFloat(a)),b:o.channel.clamp.b(l?parseFloat(c)*2.55:parseFloat(c)),a:d?o.channel.clamp.a(f?parseFloat(d)/100:parseFloat(d)):1},e)},stringify:e=>{let{r:t,g:n,b:r,a:i}=e;return i<1?`rgba(${o.lang.round(t)}, ${o.lang.round(n)}, ${o.lang.round(r)}, ${o.lang.round(i)})`:`rgb(${o.lang.round(t)}, ${o.lang.round(n)}, ${o.lang.round(r)})`}},h={format:{keyword:p,hex:d,rgb:m,rgba:m,hsl:f,hsla:f},parse:e=>{if(typeof e!=`string`)return e;let t=d.parse(e)||m.parse(e)||f.parse(e)||p.parse(e);if(t)return t;throw Error(`Unsupported color format: "${e}"`)},stringify:e=>!e.changed&&e.color?e.color:e.type.is(c.HSL)||e.data.r===void 0?f.stringify(e):e.a<1||!Number.isInteger(e.r)||!Number.isInteger(e.g)||!Number.isInteger(e.b)?m.stringify(e):d.stringify(e)},g=(e,t)=>{let n=h.parse(e);for(let e in t)n[e]=o.channel.clamp[e](t[e]);return h.stringify(n)},_=(e,t,n=0,r=1)=>{if(typeof e!=`number`)return g(e,{a:t});let i=u.set({r:o.channel.clamp.r(e),g:o.channel.clamp.g(t),b:o.channel.clamp.b(n),a:o.channel.clamp.a(r)});return h.stringify(i)},ee=e=>{let{r:t,g:n,b:r}=h.parse(e),i=.2126*o.channel.toLinear(t)+.7152*o.channel.toLinear(n)+.0722*o.channel.toLinear(r);return o.lang.round(i)},v=e=>ee(e)>=.5,y=e=>!v(e),b=(e,t,n)=>{let r=h.parse(e),i=r[t],a=o.channel.clamp[t](i+n);return i!==a&&(r[t]=a),h.stringify(r)},x=(e,t)=>b(e,`l`,t),S=(e,t)=>b(e,`l`,-t),C=(e,t)=>{let n=h.parse(e),r={};for(let e in t)t[e]&&(r[e]=n[e]+t[e]);return g(e,r)},te=(e,t,n=50)=>{let{r,g:i,b:a,a:o}=h.parse(e),{r:s,g:c,b:l,a:u}=h.parse(t),d=n/100,f=d*2-1,p=o-u,m=((f*p===-1?f:(f+p)/(1+f*p))+1)/2,g=1-m;return _(r*m+s*g,i*m+c*g,a*m+l*g,o*d+u*(1-d))},w=(e,t=100)=>{let n=h.parse(e);return n.r=255-n.r,n.g=255-n.g,n.b=255-n.b,te(n,e,t)};function ne(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n`u`?null:A(BigInt.prototype.toString),je=typeof Symbol>`u`?null:A(Symbol.prototype.toString),O=A(Object.prototype.hasOwnProperty),Me=A(Object.prototype.toString),k=A(RegExp.prototype.test),Ne=j(TypeError);function A(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return me(e,t,n)}}function j(e){return function(){return he(e,[...arguments])}}function M(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Se;if(le&&le(e,null),!xe(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(ue(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Pe(e){for(let t=0;t/g),Xe=D(/\${[\w\W]*/g),Ze=D(/^data-[\-\w.\u00B7-\uFFFF]+$/),Qe=D(/^aria-[\-\w]+$/),$e=D(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),et=D(/^(?:\w+script|data):/i),tt=D(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),nt=D(/^html$/i),rt=D(/^[a-z][.\w]*(-[.\w]+)+$/i),it=D(/<[/\w!]/g),at=D(/<[/\w]/g),ot=D(/<\/no(script|embed|frames)/i),st=D(/\/>/i),F={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},ct=function(){return typeof window>`u`?null:window},lt=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},ut=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},dt=function(e,t,n,r){return O(e,t)&&xe(e[t])?M(r.base?N(r.base):{},e[t],r.transform):n};function ft(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ct(),t=e=>ft(e);if(t.version=`3.4.12`,t.removed=[],!e||!e.document||e.document.nodeType!==F.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,o=e.Node,s=e.Element,c=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let l=e.DOMParser,u=e.trustedTypes,d=s.prototype,f=P(d,`cloneNode`),p=P(d,`remove`),m=P(d,`nextSibling`),h=P(d,`childNodes`),g=P(d,`parentNode`),_=P(d,`shadowRoot`),ee=P(d,`attributes`),v=o&&o.prototype?P(o.prototype,`nodeType`):null,y=o&&o.prototype?P(o.prototype,`nodeName`):null;if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let b,x=``,S,C=!1,te=0,w=function(){if(te>0)throw Ne(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},ne=function(e){w(),te++;try{return b.createHTML(e)}finally{te--}},re=function(e){w(),te++;try{return b.createScriptURL(e)}finally{te--}},ie=function(){return C||=(S=lt(u,i),!0),S},ae=n,oe=ae.implementation,se=ae.createNodeIterator,le=ae.createDocumentFragment,ue=ae.getElementsByTagName,de=r.importNode,T=ut();t.isSupported=typeof ce==`function`&&typeof g==`function`&&oe&&oe.createHTMLDocument!==void 0;let pe=Je,me=Ye,he=Xe,Oe=Ze,ke=Qe,Ae=et,je=tt,Me=rt,A=$e,j=null,Pe=M({},[...Le,...Re,...ze,...Ve,...Ue]),I=null,pt=M({},[...We,...Ge,...Ke,...qe]),L=Object.seal(fe(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),R=null,z=null,B=Object.seal(fe(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),mt=!0,ht=!0,gt=!1,_t=!0,V=!1,H=!0,vt=!1,yt=!1,bt=null,xt=null,St=!1,Ct=!1,wt=!1,Tt=!1,Et=!0,Dt=!1,Ot=`user-content-`,kt=!0,At=!1,jt={},U=null,W=M({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),G=null,Mt=M({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Nt=null,Pt=M({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Ft=`http://www.w3.org/1998/Math/MathML`,It=`http://www.w3.org/2000/svg`,K=`http://www.w3.org/1999/xhtml`,q=K,Lt=!1,Rt=null,zt=M({},[Ft,It,K],Ce),J=E([`mi`,`mo`,`mn`,`ms`,`mtext`]),Bt=M({},J),Y=E([`annotation-xml`]),Vt=M({},Y),Ht=M({},[`title`,`style`,`font`,`a`,`script`]),Ut=null,Wt=[`application/xhtml+xml`,`text/html`],X=null,Gt=null,Kt=n.createElement(`form`),qt=function(e){return e instanceof RegExp||e instanceof Function},Jt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Gt&&Gt===e)return;(!e||typeof e!=`object`)&&(e={}),e=N(e),Ut=Wt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,X=Ut===`application/xhtml+xml`?Ce:Se,j=dt(e,`ALLOWED_TAGS`,Pe,{transform:X}),I=dt(e,`ALLOWED_ATTR`,pt,{transform:X}),Rt=dt(e,`ALLOWED_NAMESPACES`,zt,{transform:Ce}),Nt=dt(e,`ADD_URI_SAFE_ATTR`,Pt,{transform:X,base:Pt}),G=dt(e,`ADD_DATA_URI_TAGS`,Mt,{transform:X,base:Mt}),U=dt(e,`FORBID_CONTENTS`,W,{transform:X}),R=dt(e,`FORBID_TAGS`,N({}),{transform:X}),z=dt(e,`FORBID_ATTR`,N({}),{transform:X}),jt=O(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?N(e.USE_PROFILES):e.USE_PROFILES:!1,mt=e.ALLOW_ARIA_ATTR!==!1,ht=e.ALLOW_DATA_ATTR!==!1,gt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,_t=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,V=e.SAFE_FOR_TEMPLATES||!1,H=e.SAFE_FOR_XML!==!1,vt=e.WHOLE_DOCUMENT||!1,Ct=e.RETURN_DOM||!1,wt=e.RETURN_DOM_FRAGMENT||!1,Tt=e.RETURN_TRUSTED_TYPE||!1,St=e.FORCE_BODY||!1,Et=e.SANITIZE_DOM!==!1,Dt=e.SANITIZE_NAMED_PROPS||!1,kt=e.KEEP_CONTENT!==!1,At=e.IN_PLACE||!1,A=Ie(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:$e,q=typeof e.NAMESPACE==`string`?e.NAMESPACE:K,Bt=O(e,`MATHML_TEXT_INTEGRATION_POINTS`)&&e.MATHML_TEXT_INTEGRATION_POINTS&&typeof e.MATHML_TEXT_INTEGRATION_POINTS==`object`?N(e.MATHML_TEXT_INTEGRATION_POINTS):M({},J),Vt=O(e,`HTML_INTEGRATION_POINTS`)&&e.HTML_INTEGRATION_POINTS&&typeof e.HTML_INTEGRATION_POINTS==`object`?N(e.HTML_INTEGRATION_POINTS):M({},Y);let t=O(e,`CUSTOM_ELEMENT_HANDLING`)&&e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING==`object`?N(e.CUSTOM_ELEMENT_HANDLING):fe(null);if(L=fe(null),O(t,`tagNameCheck`)&&qt(t.tagNameCheck)&&(L.tagNameCheck=t.tagNameCheck),O(t,`attributeNameCheck`)&&qt(t.attributeNameCheck)&&(L.attributeNameCheck=t.attributeNameCheck),O(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(L.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),D(L),V&&(ht=!1),wt&&(Ct=!0),jt&&(j=M({},Ue),I=fe(null),jt.html===!0&&(M(j,Le),M(I,We)),jt.svg===!0&&(M(j,Re),M(I,Ge),M(I,qe)),jt.svgFilters===!0&&(M(j,ze),M(I,Ge),M(I,qe)),jt.mathMl===!0&&(M(j,Ve),M(I,Ke),M(I,qe))),B.tagCheck=null,B.attributeCheck=null,O(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?B.tagCheck=e.ADD_TAGS:xe(e.ADD_TAGS)&&(j===Pe&&(j=N(j)),M(j,e.ADD_TAGS,X))),O(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?B.attributeCheck=e.ADD_ATTR:xe(e.ADD_ATTR)&&(I===pt&&(I=N(I)),M(I,e.ADD_ATTR,X))),O(e,`ADD_URI_SAFE_ATTR`)&&xe(e.ADD_URI_SAFE_ATTR)&&M(Nt,e.ADD_URI_SAFE_ATTR,X),O(e,`FORBID_CONTENTS`)&&xe(e.FORBID_CONTENTS)&&(U===W&&(U=N(U)),M(U,e.FORBID_CONTENTS,X)),O(e,`ADD_FORBID_CONTENTS`)&&xe(e.ADD_FORBID_CONTENTS)&&(U===W&&(U=N(U)),M(U,e.ADD_FORBID_CONTENTS,X)),kt&&(j[`#text`]=!0),vt&&M(j,[`html`,`head`,`body`]),j.table&&(M(j,[`tbody`]),delete R.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw Ne(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw Ne(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=b;b=e.TRUSTED_TYPES_POLICY;try{x=ne(``)}catch(e){throw b=t,e}}else e.TRUSTED_TYPES_POLICY===null?(b=void 0,x=``):(b===void 0&&(b=ie()),b&&typeof x==`string`&&(x=ne(``)));E&&E(e),Gt=e},Yt=M({},[...Re,...ze,...Be]),Xt=M({},[...Ve,...He]),Zt=function(e,t,n){return t.namespaceURI===K?e===`svg`:t.namespaceURI===Ft?e===`svg`&&(n===`annotation-xml`||Bt[n]):!!Yt[e]},Qt=function(e,t,n){return t.namespaceURI===K?e===`math`:t.namespaceURI===It?e===`math`&&Vt[n]:!!Xt[e]},$t=function(e,t,n){return t.namespaceURI===It&&!Vt[n]||t.namespaceURI===Ft&&!Bt[n]?!1:!Xt[e]&&(Ht[e]||!Yt[e])},en=function(e){let t=g(e);(!t||!t.tagName)&&(t={namespaceURI:q,tagName:`template`});let n=Se(e.tagName),r=Se(t.tagName);return Rt[e.namespaceURI]?e.namespaceURI===It?Zt(n,t,r):e.namespaceURI===Ft?Qt(n,t,r):e.namespaceURI===K?$t(n,t,r):!!(Ut===`application/xhtml+xml`&&Rt[e.namespaceURI]):!1},tn=function(e){ye(t.removed,{element:e});try{g(e).removeChild(e)}catch{if(p(e),!g(e))throw Ne(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},nn=function(e){an(e);let t=h(e);if(t){let e=[];ge(t,t=>{ye(e,t)}),ge(e,e=>{try{p(e)}catch{}})}let n=ee(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;if(typeof i==`string`)try{e.removeAttribute(i)}catch{}}},Z=function(e,n){try{ye(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{ye(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(Ct||wt)try{tn(n)}catch{}else try{n.setAttribute(e,``)}catch{}},rn=function(e){let t=ee(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;if(!(typeof i!=`string`||I[X(i)]))try{e.removeAttribute(i)}catch{}}},an=function(e){let t=[e];for(;t.length>0;){let e=t.pop();(v?v(e):e.nodeType)===F.element&&rn(e);let n=h(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},on=function(e){if(!H)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=v?v(e):e.nodeType;if(n===F.processingInstruction||n===F.comment&&k(at,e.data)){try{p(e)}catch{}continue}if(n===F.element){let t=e,n=X(y?y(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&n!==`label`&&n!==`output`&&t.removeAttribute(`for`)}catch{}}let r=h(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},sn=function(e){let t=null,r=null;if(St)e=``+e;else{let t=we(e,/^[\r\n\t ]+/);r=t&&t[0]}Ut===`application/xhtml+xml`&&q===K&&(e=``+e+``);let i=b?ne(e):e;if(q===K)try{t=new l().parseFromString(i,Ut)}catch{}if(!t||!t.documentElement){t=oe.createDocument(q,`template`,null);try{t.documentElement.innerHTML=Lt?x:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),q===K?ue.call(t,vt?`html`:`body`)[0]:vt?t.documentElement:a},cn=function(e){return se.call(e.ownerDocument||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},ln=function(e){return e=Te(e,pe,` `),e=Te(e,me,` `),e=Te(e,he,` `),e},un=function(e){e.normalize();let t=se.call(e.ownerDocument||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),n=t.nextNode();for(;n;)n.data=ln(n.data),n=t.nextNode();let r=e.querySelectorAll?.call(e,`template`);r&&ge(r,e=>{Q(e.content)&&un(e.content)})},dn=function(e){let t=y?y(e):null;return typeof t!=`string`||X(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==ee(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==v(e)||e.childNodes!==h(e)},Q=function(e){if(!v||typeof e!=`object`||!e)return!1;try{return v(e)===F.documentFragment}catch{return!1}},fn=function(e){if(!v||typeof e!=`object`||!e)return!1;try{return typeof v(e)==`number`}catch{return!1}};function $(e,n,r){e.length!==0&&ge(e,e=>{e.call(t,n,r,Gt)})}let pn=function(e,t){return!!(H&&e.hasChildNodes()&&!fn(e.firstElementChild)&&k(it,e.textContent)&&k(it,e.innerHTML)||H&&e.namespaceURI===K&&t===`style`&&fn(e.firstElementChild)||e.nodeType===F.processingInstruction||H&&e.nodeType===F.comment&&k(at,e.data))},mn=function(e,t){if(!R[t]&&vn(t)&&(L.tagNameCheck instanceof RegExp&&k(L.tagNameCheck,t)||L.tagNameCheck instanceof Function&&L.tagNameCheck(t)))return!1;if(kt&&!U[t]){let t=g(e),n=h(e);if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=At?n[i]:f(n[i],!0);t.insertBefore(r,m(e))}}}return tn(e),!0},hn=function(e,n){if($(T.beforeSanitizeElements,e,null),e!==n&&g(e)===null)return!0;if(dn(e))return tn(e),!0;let r=X(y?y(e):e.nodeName);if($(T.uponSanitizeElement,e,{tagName:r,allowedTags:j}),e!==n&&g(e)===null)return!0;if(pn(e,r))return tn(e),!0;if(R[r]||!(B.tagCheck instanceof Function&&B.tagCheck(r))&&!j[r]){let t=mn(e,r);return t===!1&&$(T.afterSanitizeElements,e,null),t}if((v?v(e):e.nodeType)===F.element&&!en(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&k(ot,e.innerHTML))return tn(e),!0;if(V&&e.nodeType===F.text){let n=ln(e.textContent);e.textContent!==n&&(ye(t.removed,{element:e.cloneNode()}),e.textContent=n)}return $(T.afterSanitizeElements,e,null),!1},gn=function(e,t,r){if(z[t]||H&&t===`patchsrc`||H&&t===`for`&&e!==`label`&&e!==`output`||Et&&(t===`id`||t===`name`)&&(r in n||r in Kt))return!1;let i=I[t]||B.attributeCheck instanceof Function&&B.attributeCheck(t,e);if(!(ht&&k(Oe,t))&&!(mt&&k(ke,t))){if(!i){if(!(vn(e)&&(L.tagNameCheck instanceof RegExp&&k(L.tagNameCheck,e)||L.tagNameCheck instanceof Function&&L.tagNameCheck(e))&&(L.attributeNameCheck instanceof RegExp&&k(L.attributeNameCheck,t)||L.attributeNameCheck instanceof Function&&L.attributeNameCheck(t,e))||t===`is`&&L.allowCustomizedBuiltInElements&&(L.tagNameCheck instanceof RegExp&&k(L.tagNameCheck,r)||L.tagNameCheck instanceof Function&&L.tagNameCheck(r))))return!1}else if(!Nt[t]&&!k(A,Te(r,je,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&Ee(r,`data:`)===0&&G[e])&&!(gt&&!k(Ae,Te(r,je,``)))&&r)return!1}return!0},_n=M({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),vn=function(e){return!_n[Se(e)]&&k(Me,e)},yn=function(e,t,n,r){if(b&&typeof u==`object`&&typeof u.getAttributeType==`function`&&!n)switch(u.getAttributeType(e,t)){case`TrustedHTML`:return ne(r);case`TrustedScriptURL`:return re(r)}return r},bn=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),dn(e)?tn(e):ve(t.removed)}catch{Z(n,e)}},xn=function(e){$(T.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||dn(e))return;let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:I,forceKeepAttr:void 0},r=t.length,i=X(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=X(o),u=c,d=o===`value`?u:De(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,$(T.uponSanitizeAttribute,e,n),d=n.attrValue,Dt&&(l===`id`||l===`name`)&&Ee(d,Ot)!==0&&(Z(o,e),d=Ot+d),H&&k(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){Z(o,e);continue}if(l===`attributename`&&we(d,`href`)){Z(o,e);continue}if(!n.forceKeepAttr){if(!n.keepAttr){Z(o,e);continue}if(!_t&&k(st,d)){Z(o,e);continue}if(V&&(d=ln(d)),!gn(i,l,d)){Z(o,e);continue}d=yn(i,l,s,d),d!==u&&bn(e,o,s,d)}}$(T.afterSanitizeAttributes,e,null)},Sn=function(e){let t=null,n=cn(e);for($(T.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(T.uponSanitizeShadowNode,t,null),hn(t,e),xn(t),Q(t.content)&&Sn(t.content),(v?v(t):t.nodeType)===F.element){let e=_(t);Q(e)&&(Cn(e),Sn(e))}$(T.afterSanitizeShadowDOM,e,null)},Cn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Sn(e.shadow);continue}let n=e.node,r=(v?v(n):n.nodeType)===F.element,i=h(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=y?y(n):null;if(typeof e==`string`&&X(e)===`template`){let e=n.content;Q(e)&&t.push({node:e,shadow:null})}}if(r){let e=_(n);Q(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(Lt=!e,Lt&&(e=``),typeof e!=`string`&&!fn(e)&&(e=Fe(e),typeof e!=`string`))throw Ne(`dirty is not a string, aborting`);if(!t.isSupported)return e;yt?(j=bt,I=xt):Jt(n),(T.uponSanitizeElement.length>0||T.uponSanitizeAttribute.length>0)&&(j=N(j)),T.uponSanitizeAttribute.length>0&&(I=N(I)),t.removed=[];let c=At&&typeof e!=`string`&&fn(e);if(c){on(e);let t=y?y(e):e.nodeName;if(typeof t==`string`){let n=X(t);if(!j[n]||R[n])throw nn(e),Ne(`root node is forbidden and cannot be sanitized in-place`)}if(dn(e))throw nn(e),Ne(`root node is clobbered and cannot be sanitized in-place`);try{Cn(e)}catch(t){throw nn(e),t}}else if(fn(e))i=sn(``),a=i.ownerDocument.importNode(e,!0),a.nodeType===F.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Cn(a);else{if(!Ct&&!V&&!vt&&e.indexOf(`<`)===-1)return b&&Tt?ne(e):e;if(i=sn(e),!i)return Ct?null:Tt?x:``}i&&St&&tn(i.firstChild);let l=c?e:i,u=cn(l);try{for(;o=u.nextNode();)hn(o,l),xn(o),Q(o.content)&&Sn(o.content)}catch(n){throw c&&(nn(e),ge(t.removed,e=>{e.element&&an(e.element)})),n}if(c)return ge(t.removed,e=>{e.element&&an(e.element)}),V&&un(e),e;if(Ct){if(V&&un(i),wt)for(s=le.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(I.shadowroot||I.shadowrootmode)&&(s=de.call(r,s,!0)),s}let d=vt?i.outerHTML:i.innerHTML;return vt&&j[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&k(nt,i.ownerDocument.doctype.name)&&(d=` `+d),V&&(d=ln(d)),b&&Tt?ne(d):d},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Jt(e),yt=!0,bt=j,xt=I},t.clearConfig=function(){Gt=null,yt=!1,bt=null,xt=null,b=S,x=``},t.isValidAttribute=function(e,t,n){Gt||Jt({});let r=X(e),i=X(t);return gn(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&O(T,e)&&ye(T[e],t)},t.removeHook=function(e,t){if(O(T,e)){if(t!==void 0){let n=_e(T[e],t);return n===-1?void 0:be(T[e],n,1)[0]}return ve(T[e])}},t.removeHooks=function(e){O(T,e)&&(T[e]=[])},t.removeAllHooks=function(){T=ut()},t}var I=ft(),pt=t((e,t,{depth:n=2,clobber:r=!1}={})=>{let i={depth:n,clobber:r};return Array.isArray(t)&&!Array.isArray(e)?(t.forEach(t=>pt(e,t,i)),e):Array.isArray(t)&&Array.isArray(e)?(t.forEach(t=>{e.includes(t)||e.push(t)}),e):e===void 0||n<=0?typeof e==`object`&&e&&typeof t==`object`?Object.assign(e,t):t:(t!==void 0&&typeof e==`object`&&typeof t==`object`&&Object.keys(t).forEach(i=>{typeof t[i]==`object`&&t[i]!==null&&(e[i]===void 0||typeof e[i]==`object`)?(e[i]===void 0&&(e[i]=Array.isArray(t[i])?[]:{}),e[i]=pt(e[i],t[i],{depth:n-1,clobber:r})):(r||typeof e[i]!=`object`&&typeof t[i]!=`object`)&&(e[i]=t[i])}),e)},`assignWithDepth`),L=pt,R=`#ffffff`,z=`#f2f2f2`,B=t((e,t)=>t?C(e,{s:-40,l:10}):C(e,{s:-40,l:-10}),`mkBorder`),mt=class{static{t(this,`Theme`)}constructor(){this.background=`#f4f4f4`,this.primaryColor=`#fff4dd`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#333`,this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.useGradient=!0,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,1))`}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#333`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#333`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||x(this.primaryColor,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.vertLineColor=this.vertLineColor||`navy`,this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.noteFontWeight=this.noteFontWeight||`normal`,this.fontWeight=this.fontWeight||`normal`,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.darkMode?(this.rowOdd=this.rowOdd||S(this.mainBkg,5)||`#ffffff`,this.rowEven=this.rowEven||S(this.mainBkg,10)):(this.rowOdd=this.rowOdd||x(this.mainBkg,75)||`#ffffff`,this.rowEven=this.rowEven||x(this.mainBkg,5)),this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||this.tertiaryColor,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.darkMode)for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},ht=t(e=>{let t=new mt;return t.calculate(e),t},`getThemeVariables`),gt=class{static{t(this,`Theme`)}constructor(){this.background=`#333`,this.primaryColor=`#1f2020`,this.secondaryColor=x(this.primaryColor,16),this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=w(this.background),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.lineColor=w(this.background),this.textColor=w(this.background),this.mainBkg=`#1f2020`,this.secondBkg=`calculated`,this.mainContrastColor=`lightgrey`,this.darkTextColor=x(w(`#323D47`),10),this.lineColor=`calculated`,this.border1=`#ccc`,this.border2=_(255,255,255,.25),this.arrowheadColor=`calculated`,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.labelBackground=`#181818`,this.textColor=`#ccc`,this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg=`calculated`,this.nodeBorder=`calculated`,this.clusterBkg=`calculated`,this.clusterBorder=`calculated`,this.defaultLinkColor=`calculated`,this.titleColor=`#F9FFFE`,this.edgeLabelBackground=`calculated`,this.actorBorder=`calculated`,this.actorBkg=`calculated`,this.actorTextColor=`calculated`,this.actorLineColor=`calculated`,this.signalColor=`calculated`,this.signalTextColor=`calculated`,this.labelBoxBkgColor=`calculated`,this.labelBoxBorderColor=`calculated`,this.labelTextColor=`calculated`,this.loopTextColor=`calculated`,this.noteBorderColor=`calculated`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`calculated`,this.activationBorderColor=`calculated`,this.activationBkgColor=`calculated`,this.sequenceNumberColor=`black`,this.clusterBkg=`#302F3D`,this.sectionBkgColor=S(`#EAE8D9`,30),this.altSectionBkgColor=`calculated`,this.sectionBkgColor2=`#EAE8D9`,this.excludeBkgColor=S(this.sectionBkgColor,10),this.taskBorderColor=_(255,255,255,70),this.taskBkgColor=`calculated`,this.taskTextColor=`calculated`,this.taskTextLightColor=`calculated`,this.taskTextOutsideColor=`calculated`,this.taskTextClickableColor=`#003163`,this.activeTaskBorderColor=_(255,255,255,50),this.activeTaskBkgColor=`#81B1DB`,this.gridColor=`calculated`,this.doneTaskBkgColor=`calculated`,this.doneTaskBorderColor=`grey`,this.critBorderColor=`#E83737`,this.critBkgColor=`#E83737`,this.taskTextDarkColor=`calculated`,this.todayLineColor=`#DB5757`,this.vertLineColor=`#00BFFF`,this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.rowOdd=this.rowOdd||x(this.mainBkg,5)||`#ffffff`,this.rowEven=this.rowEven||S(this.mainBkg,10),this.labelColor=`calculated`,this.errorBkgColor=`#a44141`,this.errorTextColor=`#ddd`,this.useGradient=!0,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,1))`,this.noteFontWeight=this.noteFontWeight||`normal`,this.fontWeight=this.fontWeight||`normal`}updateColors(){this.secondBkg=x(this.mainBkg,16),this.lineColor=this.mainContrastColor,this.arrowheadColor=this.mainContrastColor,this.nodeBkg=this.mainBkg,this.nodeBorder=this.border1,this.clusterBkg=this.secondBkg,this.clusterBorder=this.border2,this.defaultLinkColor=this.lineColor,this.edgeLabelBackground=x(this.labelBackground,25),this.actorBorder=this.border1,this.actorBkg=this.mainBkg,this.actorTextColor=this.mainContrastColor,this.actorLineColor=this.actorBorder,this.signalColor=this.mainContrastColor,this.signalTextColor=this.mainContrastColor,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.mainContrastColor,this.loopTextColor=this.mainContrastColor,this.noteBorderColor=this.secondaryBorderColor,this.noteBkgColor=this.secondBkg,this.noteTextColor=this.secondaryTextColor,this.activationBorderColor=this.border1,this.activationBkgColor=this.secondBkg,this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.background,this.taskBkgColor=x(this.mainBkg,23),this.taskTextColor=this.darkTextColor,this.taskTextLightColor=this.mainContrastColor,this.taskTextOutsideColor=this.taskTextLightColor,this.gridColor=this.mainContrastColor,this.doneTaskBkgColor=this.mainContrastColor,this.taskTextDarkColor=w(this.doneTaskBkgColor),this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#555`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.primaryBorderColor,this.specialStateColor=`#f4f4f4`,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.fillType0=this.primaryColor,this.fillType1=this.secondaryColor,this.fillType2=C(this.primaryColor,{h:64}),this.fillType3=C(this.secondaryColor,{h:64}),this.fillType4=C(this.primaryColor,{h:-64}),this.fillType5=C(this.secondaryColor,{h:-64}),this.fillType6=C(this.primaryColor,{h:128}),this.fillType7=C(this.secondaryColor,{h:128}),this.cScale1=this.cScale1||`#0b0000`,this.cScale2=this.cScale2||`#4d1037`,this.cScale3=this.cScale3||`#3f5258`,this.cScale4=this.cScale4||`#4f2f1b`,this.cScale5=this.cScale5||`#6e0a0a`,this.cScale6=this.cScale6||`#3b0048`,this.cScale7=this.cScale7||`#995a01`,this.cScale8=this.cScale8||`#154706`,this.cScale9=this.cScale9||`#161722`,this.cScale10=this.cScale10||`#00296f`,this.cScale11=this.cScale11||`#01629c`,this.cScale12=this.cScale12||`#010029`,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330});for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},_t=t(e=>{let t=new gt;return t.calculate(e),t},`getThemeVariables`),V=class{static{t(this,`Theme`)}constructor(){this.background=`#f4f4f4`,this.primaryColor=`#ECECFF`,this.secondaryColor=C(this.primaryColor,{h:120}),this.secondaryColor=`#ffffde`,this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.lineColor=w(this.background),this.textColor=w(this.background),this.background=`white`,this.mainBkg=`#ECECFF`,this.secondBkg=`#ffffde`,this.lineColor=`#333333`,this.border1=`#9370DB`,this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.border2=`#aaaa33`,this.arrowheadColor=`#333333`,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.labelBackground=`rgba(232,232,232, 0.8)`,this.textColor=`#333`,this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg=`calculated`,this.nodeBorder=`calculated`,this.clusterBkg=`calculated`,this.clusterBorder=`calculated`,this.defaultLinkColor=`calculated`,this.titleColor=`calculated`,this.edgeLabelBackground=`calculated`,this.actorBorder=`calculated`,this.actorBkg=`calculated`,this.actorTextColor=`black`,this.actorLineColor=`calculated`,this.signalColor=`calculated`,this.signalTextColor=`calculated`,this.labelBoxBkgColor=`calculated`,this.labelBoxBorderColor=`calculated`,this.labelTextColor=`calculated`,this.loopTextColor=`calculated`,this.noteBorderColor=`calculated`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`calculated`,this.activationBorderColor=`#666`,this.activationBkgColor=`#f4f4f4`,this.sequenceNumberColor=`white`,this.clusterBkg=`#FBFBFF`,this.sectionBkgColor=`calculated`,this.altSectionBkgColor=`calculated`,this.sectionBkgColor2=`calculated`,this.excludeBkgColor=`#eeeeee`,this.taskBorderColor=`calculated`,this.taskBkgColor=`calculated`,this.taskTextLightColor=`calculated`,this.taskTextColor=this.taskTextLightColor,this.taskTextDarkColor=`calculated`,this.taskTextOutsideColor=this.taskTextDarkColor,this.taskTextClickableColor=`calculated`,this.activeTaskBorderColor=`calculated`,this.activeTaskBkgColor=`calculated`,this.gridColor=`calculated`,this.doneTaskBkgColor=`calculated`,this.doneTaskBorderColor=`calculated`,this.critBorderColor=`calculated`,this.critBkgColor=`calculated`,this.todayLineColor=`calculated`,this.vertLineColor=`calculated`,this.sectionBkgColor=_(102,102,255,.49),this.altSectionBkgColor=`white`,this.sectionBkgColor2=`#fff400`,this.taskBorderColor=`#534fbc`,this.taskBkgColor=`#8a90dd`,this.taskTextLightColor=`white`,this.taskTextColor=`calculated`,this.taskTextDarkColor=`black`,this.taskTextOutsideColor=`calculated`,this.taskTextClickableColor=`#003163`,this.activeTaskBorderColor=`#534fbc`,this.activeTaskBkgColor=`#bfc7ff`,this.gridColor=`lightgrey`,this.doneTaskBkgColor=`lightgrey`,this.doneTaskBorderColor=`grey`,this.critBorderColor=`#ff8888`,this.critBkgColor=`red`,this.todayLineColor=`red`,this.vertLineColor=`navy`,this.noteFontWeight=this.noteFontWeight||`normal`,this.fontWeight=this.fontWeight||`normal`,this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.rowOdd=`calculated`,this.rowEven=`calculated`,this.labelColor=`black`,this.errorBkgColor=`#552222`,this.errorTextColor=`#552222`,this.useGradient=!1,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow=`drop-shadow(1px 2px 2px rgba(185, 185, 185, 1))`,this.updateColors()}updateColors(){this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.cScalePeer1=this.cScalePeer1||S(this.secondaryColor,45),this.cScalePeer2=this.cScalePeer2||S(this.tertiaryColor,40);for(let e=0;e{this[e]===`calculated`&&(this[e]=void 0)}),typeof e!=`object`){this.updateColors();return}let t=Object.keys(e);t.forEach(t=>{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},H=t(e=>{let t=new V;return t.calculate(e),t},`getThemeVariables`),vt=class{static{t(this,`Theme`)}constructor(){this.background=`#f4f4f4`,this.primaryColor=`#cde498`,this.secondaryColor=`#cdffb2`,this.background=`white`,this.mainBkg=`#cde498`,this.secondBkg=`#cdffb2`,this.lineColor=`green`,this.border1=`#13540c`,this.border2=`#6eaa49`,this.arrowheadColor=`green`,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.tertiaryColor=x(`#cde498`,10),this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.primaryColor),this.lineColor=w(this.background),this.textColor=w(this.background),this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg=`calculated`,this.nodeBorder=`calculated`,this.clusterBkg=`calculated`,this.clusterBorder=`calculated`,this.defaultLinkColor=`calculated`,this.titleColor=`#333`,this.edgeLabelBackground=`#e8e8e8`,this.actorBorder=`calculated`,this.actorBkg=`calculated`,this.actorTextColor=`black`,this.actorLineColor=`calculated`,this.signalColor=`#333`,this.signalTextColor=`#333`,this.labelBoxBkgColor=`calculated`,this.labelBoxBorderColor=`#326932`,this.labelTextColor=`calculated`,this.loopTextColor=`calculated`,this.noteBorderColor=`calculated`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`calculated`,this.activationBorderColor=`#666`,this.activationBkgColor=`#f4f4f4`,this.sequenceNumberColor=`white`,this.sectionBkgColor=`#6eaa49`,this.altSectionBkgColor=`white`,this.sectionBkgColor2=`#6eaa49`,this.excludeBkgColor=`#eeeeee`,this.taskBorderColor=`calculated`,this.taskBkgColor=`#487e3a`,this.taskTextLightColor=`white`,this.taskTextColor=`calculated`,this.taskTextDarkColor=`black`,this.taskTextOutsideColor=`calculated`,this.taskTextClickableColor=`#003163`,this.activeTaskBorderColor=`calculated`,this.activeTaskBkgColor=`calculated`,this.gridColor=`lightgrey`,this.doneTaskBkgColor=`lightgrey`,this.doneTaskBorderColor=`grey`,this.critBorderColor=`#ff8888`,this.critBkgColor=`red`,this.todayLineColor=`red`,this.vertLineColor=`#00BFFF`,this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.noteFontWeight=`normal`,this.fontWeight=`normal`,this.labelColor=`black`,this.errorBkgColor=`#552222`,this.errorTextColor=`#552222`,this.useGradient=!0,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,0.5))`}updateColors(){this.actorBorder=S(this.mainBkg,20),this.actorBkg=this.mainBkg,this.labelBoxBkgColor=this.actorBkg,this.labelTextColor=this.actorTextColor,this.loopTextColor=this.actorTextColor,this.noteBorderColor=this.border2,this.noteTextColor=this.actorTextColor,this.actorLineColor=this.actorBorder,this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.cScalePeer1=this.cScalePeer1||S(this.secondaryColor,45),this.cScalePeer2=this.cScalePeer2||S(this.tertiaryColor,40);for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},yt=t(e=>{let t=new vt;return t.calculate(e),t},`getThemeVariables`),bt=class{static{t(this,`Theme`)}constructor(){this.primaryColor=`#eee`,this.contrast=`#707070`,this.secondaryColor=x(this.contrast,55),this.background=`#ffffff`,this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.lineColor=w(this.background),this.textColor=w(this.background),this.mainBkg=`#eee`,this.secondBkg=`calculated`,this.lineColor=`#666`,this.border1=`#999`,this.border2=`calculated`,this.note=`#ffa`,this.text=`#333`,this.critical=`#d42`,this.done=`#bbb`,this.arrowheadColor=`#333333`,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg=`calculated`,this.nodeBorder=`calculated`,this.clusterBkg=`calculated`,this.clusterBorder=`calculated`,this.defaultLinkColor=`calculated`,this.titleColor=`calculated`,this.edgeLabelBackground=`white`,this.actorBorder=`calculated`,this.actorBkg=`calculated`,this.actorTextColor=`calculated`,this.actorLineColor=this.actorBorder,this.signalColor=`calculated`,this.signalTextColor=`calculated`,this.labelBoxBkgColor=`calculated`,this.labelBoxBorderColor=`calculated`,this.labelTextColor=`calculated`,this.loopTextColor=`calculated`,this.noteBorderColor=`calculated`,this.noteBkgColor=`calculated`,this.noteTextColor=`calculated`,this.activationBorderColor=`#666`,this.activationBkgColor=`#f4f4f4`,this.sequenceNumberColor=`white`,this.sectionBkgColor=`calculated`,this.altSectionBkgColor=`white`,this.sectionBkgColor2=`calculated`,this.excludeBkgColor=`#eeeeee`,this.taskBorderColor=`calculated`,this.taskBkgColor=`calculated`,this.taskTextLightColor=`white`,this.taskTextColor=`calculated`,this.taskTextDarkColor=`calculated`,this.taskTextOutsideColor=`calculated`,this.taskTextClickableColor=`#003163`,this.activeTaskBorderColor=`calculated`,this.activeTaskBkgColor=`calculated`,this.gridColor=`calculated`,this.doneTaskBkgColor=`calculated`,this.doneTaskBorderColor=`calculated`,this.critBkgColor=`calculated`,this.critBorderColor=`calculated`,this.todayLineColor=`calculated`,this.vertLineColor=`calculated`,this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.noteFontWeight=`normal`,this.fontWeight=`normal`,this.rowOdd=this.rowOdd||x(this.mainBkg,75)||`#ffffff`,this.rowEven=this.rowEven||`#f4f4f4`,this.labelColor=`black`,this.errorBkgColor=`#552222`,this.errorTextColor=`#552222`,this.useGradient=!0,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,1))`}updateColors(){this.secondBkg=x(this.contrast,55),this.border2=this.contrast,this.actorBorder=x(this.border1,23),this.actorBkg=this.mainBkg,this.actorTextColor=this.text,this.actorLineColor=this.actorBorder,this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.signalColor=this.text,this.signalTextColor=this.text,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.text,this.loopTextColor=this.text,this.noteBorderColor=`#999`,this.noteBkgColor=`#666`,this.noteTextColor=`#fff`,this.cScale0=this.cScale0||`#555`,this.cScale1=this.cScale1||`#F4F4F4`,this.cScale2=this.cScale2||`#555`,this.cScale3=this.cScale3||`#BBB`,this.cScale4=this.cScale4||`#777`,this.cScale5=this.cScale5||`#999`,this.cScale6=this.cScale6||`#DDD`,this.cScale7=this.cScale7||`#FFF`,this.cScale8=this.cScale8||`#DDD`,this.cScale9=this.cScale9||`#BBB`,this.cScale10=this.cScale10||`#999`,this.cScale11=this.cScale11||`#777`;for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},xt=t(e=>{let t=new bt;return t.calculate(e),t},`getThemeVariables`),St=class{static{t(this,`Theme`)}constructor(){this.background=`#ffffff`,this.primaryColor=`#cccccc`,this.mainBkg=`#ffffff`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#333`,this.THEME_COLOR_LIMIT=12,this.radius=3,this.strokeWidth=2,this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.fontFamily=`arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#000000`,this.stateBorder=`#000000`,this.useGradient=!0,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`drop-shadow( 0px 1px 2px rgba(0, 0, 0, 0.25));`,this.tertiaryColor=`#ffffff`,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.noteFontWeight=`normal`,this.fontWeight=`normal`}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#333`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#333`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor;let e=`#ECECFE`,t=`#E9E9F1`,n=C(e,{h:180,l:5});if(this.sectionBkgColor=this.sectionBkgColor||n,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||t,this.sectionBkgColor2=this.sectionBkgColor2||e,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||e,this.activeTaskBorderColor=this.activeTaskBorderColor||e,this.activeTaskBkgColor=this.activeTaskBkgColor||x(e,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||e,this.cScale1=this.cScale1||t,this.cScale2=this.cScale2||n,this.cScale3=this.cScale3||C(e,{h:30}),this.cScale4=this.cScale4||C(e,{h:60}),this.cScale5=this.cScale5||C(e,{h:90}),this.cScale6=this.cScale6||C(e,{h:120}),this.cScale7=this.cScale7||C(e,{h:150}),this.cScale8=this.cScale8||C(e,{h:210,l:150}),this.cScale9=this.cScale9||C(e,{h:270}),this.cScale10=this.cScale10||C(e,{h:300}),this.cScale11=this.cScale11||C(e,{h:330}),this.darkMode)for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},Ct=t(e=>{let t=new St;return t.calculate(e),t},`getThemeVariables`),wt=class{static{t(this,`Theme`)}constructor(){this.background=`#333`,this.primaryColor=`#1f2020`,this.secondaryColor=x(this.primaryColor,16),this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=w(this.background),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.mainBkg=`#2a2020`,this.secondBkg=`calculated`,this.mainContrastColor=`lightgrey`,this.darkTextColor=x(w(`#323D47`),10),this.border1=`#ccc`,this.border2=_(255,255,255,.25),this.arrowheadColor=w(this.background),this.fontFamily=`arial, sans-serif`,this.fontSize=`14px`,this.labelBackground=`#181818`,this.textColor=`#ccc`,this.THEME_COLOR_LIMIT=12,this.radius=3,this.strokeWidth=1,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#333`,this.THEME_COLOR_LIMIT=12,this.fontFamily=`arial, sans-serif`,this.fontSize=`14px`,this.useGradient=!0,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,0.2))`,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.noteFontWeight=`normal`,this.fontWeight=`normal`}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#333`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#333`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.border1,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||x(this.primaryColor,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.darkMode)for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},Tt=t(e=>{let t=new wt;return t.calculate(e),t},`getThemeVariables`),Et=class{static{t(this,`Theme`)}constructor(){this.background=`#ffffff`,this.primaryColor=`#cccccc`,this.mainBkg=`#ffffff`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#28253D`,this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.primaryBorderColor=B(`#28253D`,this.darkMode),this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#28253D`,this.stateBorder=`#28253D`,this.useGradient=!1,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`url(#drop-shadow)`,this.nodeShadow=!0,this.tertiaryColor=`#ffffff`,this.clusterBkg=`#F9F9FB`,this.clusterBorder=`#BDBCCC`,this.noteBorderColor=`#FACC15`,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.actorBorder=`#28253D`,this.filterColor=`#000000`}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#28253D`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#FEF9C3`,this.noteTextColor=this.noteTextColor||`#28253D`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.noteFontWeight=600,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor;let e=`#ECECFE`,t=`#E9E9F1`,n=C(e,{h:180,l:5});this.sectionBkgColor=this.sectionBkgColor||n,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||t,this.sectionBkgColor2=this.sectionBkgColor2||e,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||e,this.activeTaskBorderColor=this.activeTaskBorderColor||e,this.activeTaskBkgColor=this.activeTaskBkgColor||x(e,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.compositeTitleBackground=`#F9F9FB`,this.altBackground=`#F9F9FB`,this.stateEdgeLabelBackground=`#FFFFFF`,this.fontWeight=600,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor;for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},Dt=t(e=>{let t=new Et;return t.calculate(e),t},`getThemeVariables`),Ot=class{static{t(this,`Theme`)}constructor(){this.background=`#333`,this.primaryColor=`#1f2020`,this.secondaryColor=x(this.primaryColor,16),this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=w(this.background),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.mainBkg=`#111113`,this.secondBkg=`calculated`,this.mainContrastColor=`lightgrey`,this.darkTextColor=x(w(`#323D47`),10),this.border1=`#ccc`,this.border2=_(255,255,255,.25),this.arrowheadColor=w(this.background),this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.labelBackground=`#111113`,this.textColor=`#ccc`,this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.noteBkgColor=this.noteBkgColor??`#FEF9C3`,this.noteTextColor=this.noteTextColor??`#28253D`,this.THEME_COLOR_LIMIT=12,this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#FFFFFF`,this.stateBorder=`#FFFFFF`,this.useGradient=!1,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`url(#drop-shadow)`,this.nodeShadow=!0,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.clusterBkg=`#1E1A2E`,this.clusterBorder=`#BDBCCC`,this.noteBorderColor=`#FACC15`,this.noteFontWeight=600,this.filterColor=`#FFFFFF`}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#FFFFFF`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#FFFFFF`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.border1,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=`#FFFFFF`,this.signalColor=`#FFFFFF`,this.labelBoxBorderColor=`#BDBCCC`,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||x(this.primaryColor,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.compositeBackground=`#16141F`,this.altBackground=`#16141F`,this.compositeTitleBackground=`#16141F`,this.stateEdgeLabelBackground=`#16141F`,this.fontWeight=600,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.darkMode)for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},kt=t(e=>{let t=new Ot;return t.calculate(e),t},`getThemeVariables`),At=class{static{t(this,`Theme`)}constructor(){this.background=`#ffffff`,this.primaryColor=`#cccccc`,this.mainBkg=`#ffffff`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#28253D`,this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#28253D`,this.stateBorder=`#28253D`,this.useGradient=!1,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`url(#drop-shadow)`,this.nodeShadow=!0,this.tertiaryColor=`#ffffff`,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.actorBorder=`#28253D`,this.noteBorderColor=`#FACC15`,this.noteFontWeight=600,this.borderColorArray=[`#E879F9`,`#2DD4BF`,`#FB923C`,`#22D3EE`,`#4ADE80`,`#A78BFA`,`#F87171`,`#FACC15`,`#818CF8`,`#A3E635 `,`#38BDF8`,`#FB7185`],this.bkgColorArray=[`#FDF4FF`,`#F0FDFA`,`#FFF7ED`,`#ECFEFF`,`#F0FDF4`,`#F5F3FF`,`#FEF2F2`,`#FEFCE8`,`#EEF2FF`,`#F7FEE7`,`#F0F9FF`,`#FFF1F2`],this.filterColor=`#000000`}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#28253D`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#28253D`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor;let e=`#ECECFE`,t=`#E9E9F1`,n=C(e,{h:180,l:5});this.sectionBkgColor=this.sectionBkgColor||n,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||t,this.sectionBkgColor2=this.sectionBkgColor2||e,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||e,this.activeTaskBorderColor=this.activeTaskBorderColor||e,this.activeTaskBkgColor=this.activeTaskBkgColor||x(e,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||`#f4a8ff`,this.cScale1=this.cScale1||`#46ecd5`,this.cScale2=this.cScale2||`#ffb86a`,this.cScale3=this.cScale3||`#dab2ff`,this.cScale4=this.cScale4||`#7bf1a8`,this.cScale5=this.cScale5||`#c4b4ff`,this.cScale6=this.cScale6||`#ffa2a2`,this.cScale7=this.cScale7||`#ffdf20`,this.cScale8=this.cScale8||`#a3b3ff`,this.cScale9=this.cScale9||`#bbf451`,this.cScale10=this.cScale10||`#74d4ff`,this.cScale11=this.cScale11||`#ffa1ad`;for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},jt=t(e=>{let t=new At;return t.calculate(e),t},`getThemeVariables`),U=class{static{t(this,`Theme`)}constructor(){this.background=`#333`,this.primaryColor=`#1f2020`,this.secondaryColor=x(this.primaryColor,16),this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=w(this.background),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.mainBkg=`#111113`,this.secondBkg=`calculated`,this.mainContrastColor=`lightgrey`,this.darkTextColor=x(w(`#323D47`),10),this.border1=`#ccc`,this.border2=_(255,255,255,.25),this.arrowheadColor=w(this.background),this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.labelBackground=`#111113`,this.textColor=`#ccc`,this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.noteBkgColor=this.noteBkgColor??`#FEF9C3`,this.noteTextColor=this.noteTextColor??`#28253D`,this.THEME_COLOR_LIMIT=12,this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#FFFFFF`,this.stateBorder=`#FFFFFF`,this.useGradient=!1,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`url(#drop-shadow)`,this.nodeShadow=!0,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.clusterBkg=`#1E1A2E`,this.clusterBorder=`#BDBCCC`,this.noteBorderColor=`#FACC15`,this.noteFontWeight=600,this.borderColorArray=[`#E879F9`,`#2DD4BF`,`#FB923C`,`#22D3EE`,`#4ADE80`,`#A78BFA`,`#F87171`,`#FACC15`,`#818CF8`,`#A3E635 `,`#38BDF8`,`#FB7185`],this.bkgColorArray=[],this.filterColor=`#FFFFFF`}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#FFFFFF`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#FFFFFF`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.border1,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=`#FFFFFF`,this.signalColor=`#FFFFFF`,this.labelBoxBorderColor=`#BDBCCC`,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.rootLabelColor=`#FFFFFF`,this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||x(this.primaryColor,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||`#f4a8ff`,this.cScale1=this.cScale1||`#46ecd5`,this.cScale2=this.cScale2||`#ffb86a`,this.cScale3=this.cScale3||`#dab2ff`,this.cScale4=this.cScale4||`#7bf1a8`,this.cScale5=this.cScale5||`#c4b4ff`,this.cScale6=this.cScale6||`#ffa2a2`,this.cScale7=this.cScale7||`#ffdf20`,this.cScale8=this.cScale8||`#a3b3ff`,this.cScale9=this.cScale9||`#bbf451`,this.cScale10=this.cScale10||`#74d4ff`,this.cScale11=this.cScale11||`#ffa1ad`;for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},W={base:{getThemeVariables:ht},dark:{getThemeVariables:_t},default:{getThemeVariables:H},forest:{getThemeVariables:yt},neutral:{getThemeVariables:xt},neo:{getThemeVariables:Ct},"neo-dark":{getThemeVariables:Tt},redux:{getThemeVariables:Dt},"redux-dark":{getThemeVariables:kt},"redux-color":{getThemeVariables:jt},"redux-dark-color":{getThemeVariables:t(e=>{let t=new U;return t.calculate(e),t},`getThemeVariables`)}},G={flowchart:{useMaxWidth:!0,titleTopMargin:25,subGraphTitleMargin:{top:0,bottom:0},diagramPadding:8,htmlLabels:null,nodeSpacing:50,rankSpacing:50,curve:`basis`,padding:15,defaultRenderer:`dagre-wrapper`,wrappingWidth:200,inheritDir:!1},swimlane:{useMaxWidth:!0,lineHops:`arc`,ignoreCrossLaneEdges:!0,optimizeRanksByCrossings:!0,automaticLaneOrdering:!1},sequence:{useMaxWidth:!0,hideUnusedParticipants:!1,activationWidth:10,diagramMarginX:50,diagramMarginY:10,actorMargin:50,width:150,height:65,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:`center`,mirrorActors:!0,forceMenus:!1,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1,actorFontSize:14,actorFontFamily:`"Open Sans", sans-serif`,actorFontWeight:400,noteFontSize:14,noteFontFamily:`"trebuchet ms", verdana, arial, sans-serif`,noteFontWeight:400,noteAlign:`center`,messageFontSize:16,messageFontFamily:`"trebuchet ms", verdana, arial, sans-serif`,messageFontWeight:400,wrap:!1,wrapPadding:10,labelBoxWidth:50,labelBoxHeight:20},gantt:{useMaxWidth:!0,titleTopMargin:25,barHeight:20,barGap:4,topPadding:50,rightPadding:75,leftPadding:75,gridLineStartPadding:35,fontSize:11,sectionFontSize:11,numberSectionStyles:4,axisFormat:`%Y-%m-%d`,topAxis:!1,displayMode:``,weekday:`sunday`},journey:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,leftMargin:150,maxLabelWidth:360,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:`center`,bottomMarginAdj:1,rightAngles:!1,taskFontSize:14,taskFontFamily:`"Open Sans", sans-serif`,taskMargin:50,activationWidth:10,textPlacement:`fo`,actorColours:[`#8FBC8F`,`#7CFC00`,`#00FFFF`,`#20B2AA`,`#B0E0E6`,`#FFFFE0`],sectionFills:[`#191970`,`#8B008B`,`#4B0082`,`#2F4F4F`,`#800000`,`#8B4513`,`#00008B`],sectionColours:[`#fff`],titleColor:``,titleFontFamily:`"trebuchet ms", verdana, arial, sans-serif`,titleFontSize:`4ex`},class:{useMaxWidth:!0,titleTopMargin:25,arrowMarkerAbsolute:!1,dividerMargin:10,padding:5,textHeight:10,defaultRenderer:`dagre-wrapper`,htmlLabels:!1,hideEmptyMembersBox:!1,hierarchicalNamespaces:!0},state:{useMaxWidth:!0,titleTopMargin:25,dividerMargin:10,sizeUnit:5,padding:8,textHeight:10,titleShift:-15,noteMargin:10,forkWidth:70,forkHeight:7,miniPadding:2,fontSizeFactor:5.02,fontSize:24,labelHeight:16,edgeLengthFactor:`20`,compositTitleSize:35,radius:5,defaultRenderer:`dagre-wrapper`},er:{useMaxWidth:!0,titleTopMargin:25,diagramPadding:20,layoutDirection:`TB`,minEntityWidth:100,minEntityHeight:75,entityPadding:15,nodeSpacing:140,rankSpacing:80,stroke:`gray`,fill:`honeydew`,fontSize:12},pie:{useMaxWidth:!0,textPosition:.75,donutHole:0,legendPosition:`right`,highlightSlice:``},quadrantChart:{useMaxWidth:!0,chartWidth:500,chartHeight:500,titleFontSize:20,titlePadding:10,quadrantPadding:5,xAxisLabelPadding:5,yAxisLabelPadding:5,xAxisLabelFontSize:16,yAxisLabelFontSize:16,quadrantLabelFontSize:16,quadrantTextTopPadding:5,pointTextPadding:5,pointLabelFontSize:12,pointRadius:5,xAxisPosition:`top`,yAxisPosition:`left`,quadrantInternalBorderStrokeWidth:1,quadrantExternalBorderStrokeWidth:2},xyChart:{useMaxWidth:!0,width:700,height:500,titleFontSize:20,titlePadding:10,showDataLabel:!1,showDataLabelOutsideBar:!1,showTitle:!0,xAxis:{$ref:`#/$defs/XYChartAxisConfig`,showLabel:!0,labelFontSize:14,labelPadding:5,showTitle:!0,titleFontSize:16,titlePadding:5,showTick:!0,tickLength:5,tickWidth:2,showAxisLine:!0,axisLineWidth:2,labelRotation:0},yAxis:{$ref:`#/$defs/XYChartAxisConfig`,showLabel:!0,labelFontSize:14,labelPadding:5,showTitle:!0,titleFontSize:16,titlePadding:5,showTick:!0,tickLength:5,tickWidth:2,showAxisLine:!0,axisLineWidth:2,labelRotation:0},chartOrientation:`vertical`,plotReservedSpacePercent:50},requirement:{useMaxWidth:!0,rect_fill:`#f9f9f9`,text_color:`#333`,rect_border_size:`0.5px`,rect_border_color:`#bbb`,rect_min_width:200,rect_min_height:200,fontSize:14,rect_padding:10,line_height:20},mindmap:{useMaxWidth:!0,padding:10,maxNodeWidth:200,layoutAlgorithm:`cose-bilkent`},ishikawa:{useMaxWidth:!0,diagramPadding:20},kanban:{useMaxWidth:!0,padding:8,sectionWidth:200,ticketBaseUrl:``},timeline:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:`center`,bottomMarginAdj:1,rightAngles:!1,taskFontSize:14,taskFontFamily:`"Open Sans", sans-serif`,taskMargin:50,activationWidth:10,textPlacement:`fo`,actorColours:[`#8FBC8F`,`#7CFC00`,`#00FFFF`,`#20B2AA`,`#B0E0E6`,`#FFFFE0`],sectionFills:[`#191970`,`#8B008B`,`#4B0082`,`#2F4F4F`,`#800000`,`#8B4513`,`#00008B`],sectionColours:[`#fff`],disableMulticolor:!1},gitGraph:{useMaxWidth:!0,titleTopMargin:25,diagramPadding:8,nodeLabel:{width:75,height:100,x:-25,y:0},mainBranchName:`main`,mainBranchOrder:0,showCommitLabel:!0,showBranches:!0,rotateCommitLabel:!0,parallelCommits:!1,arrowMarkerAbsolute:!1},c4:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10,c4ShapeInRow:4,nextLinePaddingX:0,c4BoundaryInRow:2,personFontSize:14,personFontFamily:`"Open Sans", sans-serif`,personFontWeight:`normal`,external_personFontSize:14,external_personFontFamily:`"Open Sans", sans-serif`,external_personFontWeight:`normal`,systemFontSize:14,systemFontFamily:`"Open Sans", sans-serif`,systemFontWeight:`normal`,external_systemFontSize:14,external_systemFontFamily:`"Open Sans", sans-serif`,external_systemFontWeight:`normal`,system_dbFontSize:14,system_dbFontFamily:`"Open Sans", sans-serif`,system_dbFontWeight:`normal`,external_system_dbFontSize:14,external_system_dbFontFamily:`"Open Sans", sans-serif`,external_system_dbFontWeight:`normal`,system_queueFontSize:14,system_queueFontFamily:`"Open Sans", sans-serif`,system_queueFontWeight:`normal`,external_system_queueFontSize:14,external_system_queueFontFamily:`"Open Sans", sans-serif`,external_system_queueFontWeight:`normal`,boundaryFontSize:14,boundaryFontFamily:`"Open Sans", sans-serif`,boundaryFontWeight:`normal`,messageFontSize:12,messageFontFamily:`"Open Sans", sans-serif`,messageFontWeight:`normal`,containerFontSize:14,containerFontFamily:`"Open Sans", sans-serif`,containerFontWeight:`normal`,external_containerFontSize:14,external_containerFontFamily:`"Open Sans", sans-serif`,external_containerFontWeight:`normal`,container_dbFontSize:14,container_dbFontFamily:`"Open Sans", sans-serif`,container_dbFontWeight:`normal`,external_container_dbFontSize:14,external_container_dbFontFamily:`"Open Sans", sans-serif`,external_container_dbFontWeight:`normal`,container_queueFontSize:14,container_queueFontFamily:`"Open Sans", sans-serif`,container_queueFontWeight:`normal`,external_container_queueFontSize:14,external_container_queueFontFamily:`"Open Sans", sans-serif`,external_container_queueFontWeight:`normal`,componentFontSize:14,componentFontFamily:`"Open Sans", sans-serif`,componentFontWeight:`normal`,external_componentFontSize:14,external_componentFontFamily:`"Open Sans", sans-serif`,external_componentFontWeight:`normal`,component_dbFontSize:14,component_dbFontFamily:`"Open Sans", sans-serif`,component_dbFontWeight:`normal`,external_component_dbFontSize:14,external_component_dbFontFamily:`"Open Sans", sans-serif`,external_component_dbFontWeight:`normal`,component_queueFontSize:14,component_queueFontFamily:`"Open Sans", sans-serif`,component_queueFontWeight:`normal`,external_component_queueFontSize:14,external_component_queueFontFamily:`"Open Sans", sans-serif`,external_component_queueFontWeight:`normal`,wrap:!0,wrapPadding:10,person_bg_color:`#08427B`,person_border_color:`#073B6F`,external_person_bg_color:`#686868`,external_person_border_color:`#8A8A8A`,system_bg_color:`#1168BD`,system_border_color:`#3C7FC0`,system_db_bg_color:`#1168BD`,system_db_border_color:`#3C7FC0`,system_queue_bg_color:`#1168BD`,system_queue_border_color:`#3C7FC0`,external_system_bg_color:`#999999`,external_system_border_color:`#8A8A8A`,external_system_db_bg_color:`#999999`,external_system_db_border_color:`#8A8A8A`,external_system_queue_bg_color:`#999999`,external_system_queue_border_color:`#8A8A8A`,container_bg_color:`#438DD5`,container_border_color:`#3C7FC0`,container_db_bg_color:`#438DD5`,container_db_border_color:`#3C7FC0`,container_queue_bg_color:`#438DD5`,container_queue_border_color:`#3C7FC0`,external_container_bg_color:`#B3B3B3`,external_container_border_color:`#A6A6A6`,external_container_db_bg_color:`#B3B3B3`,external_container_db_border_color:`#A6A6A6`,external_container_queue_bg_color:`#B3B3B3`,external_container_queue_border_color:`#A6A6A6`,component_bg_color:`#85BBF0`,component_border_color:`#78A8D8`,component_db_bg_color:`#85BBF0`,component_db_border_color:`#78A8D8`,component_queue_bg_color:`#85BBF0`,component_queue_border_color:`#78A8D8`,external_component_bg_color:`#CCCCCC`,external_component_border_color:`#BFBFBF`,external_component_db_bg_color:`#CCCCCC`,external_component_db_border_color:`#BFBFBF`,external_component_queue_bg_color:`#CCCCCC`,external_component_queue_border_color:`#BFBFBF`},sankey:{useMaxWidth:!0,width:600,height:400,linkColor:`gradient`,nodeAlignment:`justify`,showValues:!0,prefix:``,suffix:``,nodeWidth:10,nodePadding:12,labelStyle:`legacy`},block:{useMaxWidth:!0,padding:8},packet:{useMaxWidth:!0,rowHeight:32,bitWidth:32,bitsPerRow:32,showBits:!0,paddingX:5,paddingY:5},treeView:{useMaxWidth:!0,rowIndent:10,paddingX:5,paddingY:5,lineThickness:1,showIcons:!1,defaultIconPack:``,filenameIcons:{},extensionIcons:{}},architecture:{useMaxWidth:!0,padding:40,iconSize:80,fontSize:16,randomize:!1,nodeSeparation:75,idealEdgeLengthMultiplier:1.5,edgeElasticity:.45,numIter:2500,seed:1},eventmodeling:{useMaxWidth:!0,padding:30,rowHeight:32},radar:{useMaxWidth:!0,width:600,height:600,marginTop:50,marginRight:50,marginBottom:50,marginLeft:50,axisScaleFactor:1,axisLabelFactor:1.05,curveTension:.17},venn:{useMaxWidth:!0,width:800,height:450,padding:8,useDebugLayout:!1},cynefin:{useMaxWidth:!0,width:800,height:600,padding:40,showDomainDescriptions:!0,boundaryAmplitude:8,seed:0},theme:`default`,look:`classic`,handDrawnSeed:0,layout:`dagre`,maxTextSize:5e4,maxEdges:500,darkMode:!1,fontFamily:`"trebuchet ms", verdana, arial, sans-serif;`,logLevel:5,securityLevel:`strict`,startOnLoad:!0,arrowMarkerAbsolute:!1,secure:[`secure`,`securityLevel`,`startOnLoad`,`maxTextSize`,`suppressErrorRendering`,`maxEdges`],legacyMathML:!1,forceLegacyMathML:!1,deterministicIds:!1,fontSize:16,markdownAutoWrap:!0,suppressErrorRendering:!1},Mt={...G,deterministicIDSeed:void 0,elk:{mergeEdges:!1,nodePlacementStrategy:`BRANDES_KOEPF`,forceNodeModelOrder:!1,considerModelOrder:`NODES_AND_EDGES`},themeCSS:void 0,themeVariables:W.default.getThemeVariables(),sequence:{...G.sequence,messageFont:t(function(){return{fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},`messageFont`),noteFont:t(function(){return{fontFamily:this.noteFontFamily,fontSize:this.noteFontSize,fontWeight:this.noteFontWeight}},`noteFont`),actorFont:t(function(){return{fontFamily:this.actorFontFamily,fontSize:this.actorFontSize,fontWeight:this.actorFontWeight}},`actorFont`)},class:{hideEmptyMembersBox:!1,hierarchicalNamespaces:!0},gantt:{...G.gantt,tickInterval:void 0,useWidth:void 0},c4:{...G.c4,useWidth:void 0,personFont:t(function(){return{fontFamily:this.personFontFamily,fontSize:this.personFontSize,fontWeight:this.personFontWeight}},`personFont`),flowchart:{...G.flowchart,inheritDir:!1},external_personFont:t(function(){return{fontFamily:this.external_personFontFamily,fontSize:this.external_personFontSize,fontWeight:this.external_personFontWeight}},`external_personFont`),systemFont:t(function(){return{fontFamily:this.systemFontFamily,fontSize:this.systemFontSize,fontWeight:this.systemFontWeight}},`systemFont`),external_systemFont:t(function(){return{fontFamily:this.external_systemFontFamily,fontSize:this.external_systemFontSize,fontWeight:this.external_systemFontWeight}},`external_systemFont`),system_dbFont:t(function(){return{fontFamily:this.system_dbFontFamily,fontSize:this.system_dbFontSize,fontWeight:this.system_dbFontWeight}},`system_dbFont`),external_system_dbFont:t(function(){return{fontFamily:this.external_system_dbFontFamily,fontSize:this.external_system_dbFontSize,fontWeight:this.external_system_dbFontWeight}},`external_system_dbFont`),system_queueFont:t(function(){return{fontFamily:this.system_queueFontFamily,fontSize:this.system_queueFontSize,fontWeight:this.system_queueFontWeight}},`system_queueFont`),external_system_queueFont:t(function(){return{fontFamily:this.external_system_queueFontFamily,fontSize:this.external_system_queueFontSize,fontWeight:this.external_system_queueFontWeight}},`external_system_queueFont`),containerFont:t(function(){return{fontFamily:this.containerFontFamily,fontSize:this.containerFontSize,fontWeight:this.containerFontWeight}},`containerFont`),external_containerFont:t(function(){return{fontFamily:this.external_containerFontFamily,fontSize:this.external_containerFontSize,fontWeight:this.external_containerFontWeight}},`external_containerFont`),container_dbFont:t(function(){return{fontFamily:this.container_dbFontFamily,fontSize:this.container_dbFontSize,fontWeight:this.container_dbFontWeight}},`container_dbFont`),external_container_dbFont:t(function(){return{fontFamily:this.external_container_dbFontFamily,fontSize:this.external_container_dbFontSize,fontWeight:this.external_container_dbFontWeight}},`external_container_dbFont`),container_queueFont:t(function(){return{fontFamily:this.container_queueFontFamily,fontSize:this.container_queueFontSize,fontWeight:this.container_queueFontWeight}},`container_queueFont`),external_container_queueFont:t(function(){return{fontFamily:this.external_container_queueFontFamily,fontSize:this.external_container_queueFontSize,fontWeight:this.external_container_queueFontWeight}},`external_container_queueFont`),componentFont:t(function(){return{fontFamily:this.componentFontFamily,fontSize:this.componentFontSize,fontWeight:this.componentFontWeight}},`componentFont`),external_componentFont:t(function(){return{fontFamily:this.external_componentFontFamily,fontSize:this.external_componentFontSize,fontWeight:this.external_componentFontWeight}},`external_componentFont`),component_dbFont:t(function(){return{fontFamily:this.component_dbFontFamily,fontSize:this.component_dbFontSize,fontWeight:this.component_dbFontWeight}},`component_dbFont`),external_component_dbFont:t(function(){return{fontFamily:this.external_component_dbFontFamily,fontSize:this.external_component_dbFontSize,fontWeight:this.external_component_dbFontWeight}},`external_component_dbFont`),component_queueFont:t(function(){return{fontFamily:this.component_queueFontFamily,fontSize:this.component_queueFontSize,fontWeight:this.component_queueFontWeight}},`component_queueFont`),external_component_queueFont:t(function(){return{fontFamily:this.external_component_queueFontFamily,fontSize:this.external_component_queueFontSize,fontWeight:this.external_component_queueFontWeight}},`external_component_queueFont`),boundaryFont:t(function(){return{fontFamily:this.boundaryFontFamily,fontSize:this.boundaryFontSize,fontWeight:this.boundaryFontWeight}},`boundaryFont`),messageFont:t(function(){return{fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},`messageFont`)},pie:{...G.pie,useWidth:984},xyChart:{...G.xyChart,useWidth:void 0},requirement:{...G.requirement,useWidth:void 0},packet:{...G.packet},eventmodeling:{...G.eventmodeling},treeView:{...G.treeView,useWidth:void 0},radar:{...G.radar},railroad:{...G.railroad,fontSize:void 0,fontFamily:void 0,terminalFill:void 0,terminalStroke:void 0,terminalTextColor:void 0,nonTerminalFill:void 0,nonTerminalStroke:void 0,nonTerminalTextColor:void 0,lineColor:void 0,markerFill:void 0,commentFill:void 0,commentStroke:void 0,commentTextColor:void 0,specialFill:void 0,specialStroke:void 0,ruleNameColor:void 0},ishikawa:{...G.ishikawa},sankey:{...G.sankey,nodeColors:void 0},treemap:{useMaxWidth:!0,padding:10,diagramPadding:8,showValues:!0,nodeWidth:100,nodeHeight:40,borderWidth:1,valueFontSize:12,labelFontSize:14,valueFormat:`,`},venn:{...G.venn},cynefin:{...G.cynefin}},Nt=t((e,t=``)=>Object.keys(e).reduce((n,r)=>Array.isArray(e[r])?n:typeof e[r]==`object`&&e[r]!==null?[...n,t+r,...Nt(e[r],``)]:[...n,t+r],[]),`keyify`),Pt=new Set(Nt(Mt,``)),Ft=Mt,It={nodeColors:/^#[\da-f]{3,8}$|^rgb\([\d\s%,.]+\)$|^hsl\([\d\s%,.]+\)$|^[a-z]+$/i,filenameIcons:/^[\w-]+(?::[\w-]+)?$/,extensionIcons:/^[\w-]+(?::[\w-]+)?$/},K=t((e,t)=>{for(let n of Object.keys(e)){let r=e[n];(n.startsWith(`__`)||n.includes(`proto`)||n.includes(`constr`)||typeof r!=`string`||!t.test(r))&&(i.debug(`sanitize deleting dictionary entry:`,n,r),delete e[n])}},`sanitizeDictionaryConfig`),q=t(e=>{if(i.debug(`sanitizeDirective called with`,e),!(typeof e!=`object`||!e)){if(Array.isArray(e)){e.forEach(e=>q(e));return}for(let t of Object.keys(e)){if(i.debug(`Checking key`,t),t.startsWith(`__`)||t.includes(`proto`)||t.includes(`constr`)||!Pt.has(t)||e[t]==null){i.debug(`sanitize deleting key: `,t),delete e[t];continue}if(typeof e[t]==`object`){let n=It[t];n?K(e[t],n):(i.debug(`sanitizing object`,t),q(e[t]));continue}for(let n of[`themeCSS`,`fontFamily`,`altFontFamily`])t.includes(n)&&(i.debug(`sanitizing css option`,t),e[t]=Lt(e[t]))}if(e.themeVariables)for(let t of Object.keys(e.themeVariables)){let n=e.themeVariables[t];n?.match&&!n.match(/^[\d "#%(),.;A-Za-z]+$/)&&(e.themeVariables[t]=``)}i.debug(`After sanitization`,e)}},`sanitizeDirective`),Lt=t(e=>{let t=0,n=0;for(let r of e){if(t!(e===!1||[`false`,`null`,`0`].includes(String(e).trim().toLowerCase())),`evaluate`),J=L({},Rt),Bt,Y=[],Vt=L({},Rt),Ht=t((e,t)=>{let n=L({},e),r={};for(let e of t)Jt(e),r=L(r,e);if(n=L(n,r),r.theme&&r.theme in W){let e=L(L({},Bt).themeVariables||{},r.themeVariables);n.theme&&n.theme in W&&(n.themeVariables=W[n.theme].getThemeVariables(e))}return Vt=n,en(Vt),Vt},`updateCurrentConfig`),Ut=t(e=>(J=L({},Rt),J=L(J,e),e.theme&&W[e.theme]&&(J.themeVariables=W[e.theme].getThemeVariables(e.themeVariables)),Ht(J,Y),J),`setSiteConfig`),Wt=t(e=>{Bt=L({},e)},`saveConfigFromInitialize`),X=t(e=>(J=L(J,e),Ht(J,Y),J),`updateSiteConfig`),Gt=t(()=>L({},J),`getSiteConfig`),Kt=t(e=>(en(e),L(Vt,e),qt()),`setConfig`),qt=t(()=>L({},Vt),`getConfig`),Jt=t(e=>{e&&([`secure`,...J.secure??[]].forEach(t=>{Object.hasOwn(e,t)&&(i.debug(`Denied attempt to modify a secure key ${t}`,e[t]),delete e[t])}),Object.keys(e).forEach(t=>{t.startsWith(`__`)&&delete e[t]}),Object.keys(e).forEach(t=>{typeof e[t]==`string`&&(e[t].includes(`<`)||e[t].includes(`>`)||e[t].includes(`url(data:`))&&delete e[t],typeof e[t]==`object`&&Jt(e[t])}))},`sanitize`),Yt=t(e=>{q(e),e.fontFamily&&!e.themeVariables?.fontFamily&&(e.themeVariables={...e.themeVariables,fontFamily:e.fontFamily}),Y.push(e),Ht(J,Y)},`addDirective`),Xt=t((e=J)=>{Y=[],Ht(e,Y)},`reset`),Zt={LAZY_LOAD_DEPRECATED:`The configuration options lazyLoadedDiagrams and loadExternalDiagramsAtStartup are deprecated. Please use registerExternalDiagrams instead.`,FLOWCHART_HTML_LABELS_DEPRECATED:`flowchart.htmlLabels is deprecated. Please use global htmlLabels instead.`},Qt={},$t=t(e=>{Qt[e]||(i.warn(Zt[e]),Qt[e]=!0)},`issueWarning`),en=t(e=>{e&&(e.lazyLoadedDiagrams||e.loadExternalDiagramsAtStartup)&&$t(`LAZY_LOAD_DEPRECATED`)},`checkConfig`),tn=t(()=>{let e={};Bt&&(e=L(e,Bt));for(let t of Y)e=L(e,t);return e},`getUserDefinedConfig`),nn=t(e=>(e.flowchart?.htmlLabels!=null&&$t(`FLOWCHART_HTML_LABELS_DEPRECATED`),zt(e.htmlLabels??e.flowchart?.htmlLabels??!0)),`getEffectiveHtmlLabels`),Z=/^([^\S\n\r]*)-{3}\s*[\n\r](.*?)[\n\r]\1-{3}\s*[\n\r]+/s,rn=/%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi,an=/\s*%%.*\n/gm,on=class extends Error{static{t(this,`UnknownDiagramError`)}constructor(e){super(e),this.name=`UnknownDiagramError`}},sn={},cn=t(function(e,t){e=e.replace(Z,``).replace(rn,``).replace(an,` `);for(let[n,{detector:r}]of Object.entries(sn))if(r(e,t))return n;throw new on(`No diagram type detected matching given configuration for text: ${e}`)},`detectType`),ln=t((...e)=>{for(let{id:t,detector:n,loader:r}of e)un(t,n,r)},`registerLazyLoadedDiagrams`),un=t((e,t,n)=>{sn[e]&&i.warn(`Detector with key ${e} already exists. Overwriting.`),sn[e]={detector:t,loader:n},i.debug(`Detector with key ${e} added${n?` with loader`:``}`)},`addDetector`),dn=t(e=>sn[e].loader,`getDiagramLoader`),Q=//gi,fn=t(e=>e?xn(e).replace(/\\n/g,`#br#`).split(`#br#`):[``],`getRows`),$=(()=>{let e=!1;return()=>{e||=(pn(),!0)}})();function pn(){let e=`data-temp-href-target`;I.addHook(`beforeSanitizeAttributes`,t=>{t.tagName===`A`&&t.hasAttribute(`target`)&&t.setAttribute(e,t.getAttribute(`target`)??``)}),I.addHook(`afterSanitizeAttributes`,t=>{t.tagName===`A`&&t.hasAttribute(e)&&(t.setAttribute(`target`,t.getAttribute(e)??``),t.removeAttribute(e),t.getAttribute(`target`)===`_blank`&&t.setAttribute(`rel`,`noopener`))})}t(pn,`setupDompurifyHooks`);var mn=t(e=>($(),I.sanitize(e)),`removeScript`),hn=t((e,t)=>{if(nn(t)){let n=t.securityLevel;n===`antiscript`||n===`strict`||n===`sandbox`?e=mn(e):n!==`loose`&&(e=xn(e),e=e.replace(//g,`>`),e=e.replace(/=/g,`=`),e=bn(e))}return e},`sanitizeMore`),gn=t((e,t)=>e&&(e=t.dompurifyConfig?I.sanitize(hn(e,t),t.dompurifyConfig).toString():I.sanitize(hn(e,t),{FORBID_TAGS:[`style`]}).toString(),e),`sanitizeText`),_n=t((e,t)=>typeof e==`string`?gn(e,t):e.flat().map(e=>gn(e,t)),`sanitizeTextOrArray`),vn=t(e=>Q.test(e),`hasBreaks`),yn=t(e=>e.split(Q),`splitBreaks`),bn=t(e=>e.replace(/#br#/g,`
`),`placeholderToBreak`),xn=t(e=>e.replace(Q,`#br#`),`breakToPlaceholder`),Sn=t(e=>{let t=``;return e&&(t=window.location.protocol+`//`+window.location.host+window.location.pathname+window.location.search,t=CSS.escape(t)),t},`getUrl`),Cn=t(function(...e){let t=e.filter(e=>!isNaN(e));return Math.max(...t)},`getMax`),wn=t(function(...e){let t=e.filter(e=>!isNaN(e));return Math.min(...t)},`getMin`),Tn=t(function(e){let t=e.split(/(,)/),n=[];for(let e=0;e0&&e+1Math.max(0,e.split(t).length-1),`countOccurrence`),Dn=t((e,t)=>{let n=En(e,`~`),r=En(t,`~`);return n===1&&r===1},`shouldCombineSets`),On=t(e=>{let t=En(e,`~`),n=!1;if(t<=1)return e;t%2!=0&&e.startsWith(`~`)&&(e=e.substring(1),n=!0);let r=[...e],i=r.indexOf(`~`),a=r.lastIndexOf(`~`);for(;i!==-1&&a!==-1&&i!==a;)r[i]=`<`,r[a]=`>`,i=r.indexOf(`~`),a=r.lastIndexOf(`~`);return n&&r.unshift(`~`),r.join(``)},`processSet`),kn=t(()=>window.MathMLElement!==void 0,`isMathMLSupported`),An=/\$\$(.*?)\$\$/g,jn=t(e=>(e.match(An)?.length??0)>0,`hasKatex`),Mn=t(async(e,t)=>{let n=document.createElement(`div`);n.innerHTML=await Pn(e,t),n.id=`katex-temp`,n.style.visibility=`hidden`,n.style.position=`absolute`,n.style.top=`0`,document.querySelector(`body`)?.insertAdjacentElement(`beforeend`,n);let r={width:n.clientWidth,height:n.clientHeight};return n.remove(),r},`calculateMathMLDimensions`),Nn=t(async(t,n)=>{if(!jn(t))return t;if(!(kn()||n.legacyMathML||n.forceLegacyMathML))return t.replace(An,`MathML is unsupported in this environment.`);{let{default:r}=await e(async()=>{let{default:e}=await import(`./katex-B7rAX3Vi.js`);return{default:e}},[]),i=n.forceLegacyMathML||!kn()&&n.legacyMathML?`htmlAndMathml`:`mathml`;return t.split(Q).map(e=>jn(e)?`
${e}
`:`
${e}
`).join(``).replace(An,(e,t)=>r.renderToString(t,{throwOnError:!0,displayMode:!0,output:i}).replace(/\n/g,` `).replace(//g,``))}return t.replace(An,`Katex is not supported in @mermaid-js/tiny. Please use the full mermaid library.`)},`renderKatexUnsanitized`),Pn=t(async(e,t)=>gn(await Nn(e,t),t),`renderKatexSanitized`),Fn={getRows:fn,sanitizeText:gn,sanitizeTextOrArray:_n,hasBreaks:vn,splitBreaks:yn,lineBreakRegex:Q,removeScript:mn,getUrl:Sn,evaluate:zt,getMax:Cn,getMin:wn},In=t(function(e,t){for(let n of t)e.attr(n[0],n[1])},`d3Attrs`),Ln=t(function(e,t,n){let r=new Map;return n?(r.set(`width`,`100%`),r.set(`style`,`max-width: ${t}px;`)):(r.set(`height`,e),r.set(`width`,t)),r},`calculateSvgSizeAttrs`),Rn=t(function(e,t,n,r){In(e,Ln(t,n,r))},`configureSvgSize`),zn=t(function(e,t,n,r){let a=t.node().getBBox(),o=a.width,s=a.height;i.info(`SVG bounds: ${o}x${s}`,a);let c=0,l=0;i.info(`Graph bounds: ${c}x${l}`,e),c=o+n*2,l=s+n*2,i.info(`Calculated bounds: ${c}x${l}`),Rn(t,l,c,r);let u=`${a.x-n} ${a.y-n} ${a.width+2*n} ${a.height+2*n}`;t.attr(`viewBox`,u)},`setupGraphViewbox`),Bn={};function Vn(e){return[...e.cssRules].map(e=>e.cssText).join(` diff --git a/.vercel/output/static/assets/chunk-XXDRQBXY-BuE3VzE_.js b/.vercel/output/static/assets/chunk-XXDRQBXY-Bq6zMMOx.js similarity index 75% rename from .vercel/output/static/assets/chunk-XXDRQBXY-BuE3VzE_.js rename to .vercel/output/static/assets/chunk-XXDRQBXY-Bq6zMMOx.js index 011049f..1db543a 100644 --- a/.vercel/output/static/assets/chunk-XXDRQBXY-BuE3VzE_.js +++ b/.vercel/output/static/assets/chunk-XXDRQBXY-Bq6zMMOx.js @@ -1 +1 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-_wZywoZs.js";var n=e((e,n)=>{let r;return n===`sandbox`&&(r=t(`#i`+e)),t(n===`sandbox`?r.nodes()[0].contentDocument.body:`body`).select(`[id="${e}"]`)},`getDiagramElement`);export{n as t}; \ No newline at end of file +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";var n=e((e,n)=>{let r;return n===`sandbox`&&(r=t(`#i`+e)),t(n===`sandbox`?r.nodes()[0].contentDocument.body:`body`).select(`[id="${e}"]`)},`getDiagramElement`);export{n as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/chunk-ZGVPDNZ5-zo3h_nOA.js b/.vercel/output/static/assets/chunk-ZGVPDNZ5-DGInJAPD.js similarity index 99% rename from .vercel/output/static/assets/chunk-ZGVPDNZ5-zo3h_nOA.js rename to .vercel/output/static/assets/chunk-ZGVPDNZ5-DGInJAPD.js index ea9b591..530bb02 100644 --- a/.vercel/output/static/assets/chunk-ZGVPDNZ5-zo3h_nOA.js +++ b/.vercel/output/static/assets/chunk-ZGVPDNZ5-DGInJAPD.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{A as r,B as i,M as a,T as o,b as s,g as c,x as l,z as u}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{a as d,r as f,u as p}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as m}from"./chunk-HOUHSVGY-4s2dJLwR.js";import{n as h}from"./chunk-Q4XR5HBZ-5srkZ5CC.js";import{n as g,t as _}from"./chunk-OGEWGWER-Dr-qyYzn.js";import{a as v,i as y,r as b,t as x}from"./chunk-C7G6YPKG-DJfjwbsZ.js";import{t as S}from"./rough.esm-CSKSodPl.js";var C=e(async(e,t,r)=>{let i,a=t.useHtmlLabels||c(l()?.htmlLabels);i=r||`node default`;let o=e.insert(`g`).attr(`class`,i).attr(`id`,t.domId||t.id),s=o.insert(`g`).attr(`class`,`label`).attr(`style`,p(t.labelStyle)),f;f=t.label===void 0?``:typeof t.label==`string`?t.label:t.label[0];let m=!!t.icon||!!t.img,g=t.labelType===`markdown`,v=await h(s,u(d(f),l()),{useHtmlLabels:a,width:t.width||l().flowchart?.wrappingWidth,classes:g?`markdown-node-label`:``,style:t.labelStyle,addSvgBackground:m,markdown:g},l()),y=v.getBBox(),b=(t?.padding??0)/2;if(a){let e=v.children[0],t=n(v);await _(e,f),y=e.getBoundingClientRect(),t.attr(`width`,y.width),t.attr(`height`,y.height)}return a?s.attr(`transform`,`translate(`+-y.width/2+`, `+-y.height/2+`)`):s.attr(`transform`,`translate(0, `+-y.height/2+`)`),t.centerLabel&&s.attr(`transform`,`translate(`+-y.width/2+`, `+-y.height/2+`)`),s.insert(`rect`,`:first-child`),{shapeSvg:o,bbox:y,halfPadding:b,label:s}},`labelHelper`),w=e(async(e,t,r)=>{let i=r.useHtmlLabels??o(l()),a=e.insert(`g`).attr(`class`,`label`).attr(`style`,r.labelStyle||``),s=await h(a,u(d(t),l()),{useHtmlLabels:i,width:r.width||l()?.flowchart?.wrappingWidth,style:r.labelStyle,addSvgBackground:!!r.icon||!!r.img}),c=s.getBBox(),f=r.padding/2;if(o(l())){let e=s.children[0],t=n(s);c=e.getBoundingClientRect(),t.attr(`width`,c.width),t.attr(`height`,c.height)}return i?a.attr(`transform`,`translate(`+-c.width/2+`, `+-c.height/2+`)`):a.attr(`transform`,`translate(0, `+-c.height/2+`)`),r.centerLabel&&a.attr(`transform`,`translate(`+-c.width/2+`, `+-c.height/2+`)`),a.insert(`rect`,`:first-child`),{shapeSvg:e,bbox:c,halfPadding:f,label:a}},`insertLabel`),T=e((e,t)=>{let n=t.node().getBBox();e.width=n.width,e.height=n.height},`updateNodeBounds`),E=e((e,t)=>(e.look===`handDrawn`?`rough-node`:`node`)+` `+e.cssClasses+` `+(t||``),`getNodeClasses`);function D(e){let t=e.map((e,t)=>`${t===0?`M`:`L`}${e.x},${e.y}`);return t.push(`Z`),t.join(` `)}e(D,`createPathFromPoints`);function O(e,t,n,r,i,a){let o=[],s=n-e,c=r-t,l=s/a,u=2*Math.PI/l,d=t+c/2;for(let t=0;t<=50;t++){let n=e+t/50*s,r=d+i*Math.sin(u*(n-e));o.push({x:n,y:r})}return o}e(O,`generateFullSineWavePoints`);function k(e,t,n,r,i,a){let o=[],s=i*Math.PI/180,c=(a*Math.PI/180-s)/(r-1);for(let i=0;ie.tagName===`path`),r=document.createElementNS(`http://www.w3.org/2000/svg`,`path`),i=n.map(e=>e.getAttribute(`d`)).filter(e=>e!==null).join(` `);r.setAttribute(`d`,i);let a=n.find(e=>e.getAttribute(`fill`)!==`none`),o=n.find(e=>e.getAttribute(`stroke`)!==`none`),s=e((e,t)=>e?.getAttribute(t)??void 0,`getAttr`);if(a){let e={fill:s(a,`fill`),"fill-opacity":s(a,`fill-opacity`)??`1`};Object.entries(e).forEach(([e,t])=>{t&&r.setAttribute(e,t)})}if(o){let e={stroke:s(o,`stroke`),"stroke-width":s(o,`stroke-width`)??`1`,"stroke-opacity":s(o,`stroke-opacity`)??`1`};Object.entries(e).forEach(([e,t])=>{t&&r.setAttribute(e,t)})}let c=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);return c.appendChild(r),c}e(A,`mergePaths`);var j=e((e,t)=>{var n=e.x,r=e.y,i=t.x-n,a=t.y-r,o=e.width/2,s=e.height/2,c,l;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),c=a===0?0:s*i/a,l=s):(i<0&&(o=-o),c=o,l=i===0?0:o*a/i),{x:n+c,y:r+l}},`intersectRect`),M=e(async(e,t,n,r=!1,i=!1)=>{let a=t||``;typeof a==`object`&&(a=a[0]);let s=l(),c=o(s);return await h(e,a,{style:n,isTitle:r,useHtmlLabels:c,markdown:!1,isNode:i,width:1/0},s)},`createLabel`),N=e((e,t,n,r,i)=>[`M`,e+i,t,`H`,e+n-i,`A`,i,i,0,0,1,e+n,t+i,`V`,t+r-i,`A`,i,i,0,0,1,e+n-i,t+r,`H`,e+i,`A`,i,i,0,0,1,e,t+r-i,`V`,t+i,`A`,i,i,0,0,1,e+i,t,`Z`].join(` `),`createRoundedRectPathD`),P=e(async(e,r)=>{let i=l(),{themeVariables:a,handDrawnSeed:o}=i,{clusterBkg:s,clusterBorder:u}=a,d=u,{labelStyles:f,nodeStyles:p,borderStyles:m,backgroundStyles:g}=y(r),_=e.insert(`g`).attr(`class`,`cluster swimlane `+(r.cssClasses||``)).attr(`id`,r.id).attr(`data-id`,r.id).attr(`data-et`,`cluster`).attr(`data-look`,r.look),b=c(i.flowchart.htmlLabels),x=r.direction===`LR`,C=_.insert(`g`).attr(`class`,`cluster-label swimlane-label`),w=await h(C,r.label,{style:r.labelStyle,useHtmlLabels:b,isNode:!0,width:r.width}),T=w.getBBox();if(b){let e=w.children[0],t=n(w);T=e.getBoundingClientRect(),t.attr(`width`,T.width),t.attr(`height`,T.height)}let E=r.padding??0,D=r.width<=T.width+E?T.width+E:r.width;r.width<=T.width+E?r.diff=(D-r.width)/2-E:r.diff=-E;let O=r.height,k=r.y-O/2,A=r.y+O/2,M=r.x-D/2,N=r.swimlaneContentTop===void 0?k+O/3:r.swimlaneContentTop,P=x?4:0,F=T.height+2*P,I,L;if(x){let e=Math.max(F,T.height+2*P),t=M+e,n=Math.max(0,D-e);if(r.look===`handDrawn`){let i=S.svg(_),a=v(r,{roughness:.7,fill:s,stroke:d,fillWeight:3,seed:o}),c=v(r,{roughness:.7,fill:`none`,stroke:d,seed:o}),l=i.rectangle(M,k,e,O,a);I=_.insert(()=>l,`:first-child`);let u=i.rectangle(t,k,n,O,c);L=_.insert(()=>u,`:first-child`),I.select(`path:nth-child(2)`).attr(`style`,m.join(`;`)),I.select(`path`).attr(`style`,g.join(`;`).replace(`fill`,`stroke`))}else I=_.insert(`rect`,`:first-child`),L=_.insert(`rect`,`:first-child`),I.attr(`class`,`swimlane-title`).attr(`style`,p).attr(`x`,M).attr(`y`,k).attr(`width`,e).attr(`height`,O).attr(`fill`,s).attr(`stroke`,d),L.attr(`class`,`swimlane-body`).attr(`style`,p).attr(`x`,t).attr(`y`,k).attr(`width`,n).attr(`height`,O).attr(`fill`,`none`).attr(`stroke`,d);let i=M+e/2,a=r.y;C.attr(`transform`,`translate(${i}, ${a}) rotate(-90) translate(${-T.width/2}, ${-T.height/2})`)}else{let e=Math.max(0,N-k),t=Math.min(F,e),n=k+t,i=Math.max(0,A-n),a=r.x-D/2;if(r.look===`handDrawn`){let e=S.svg(_),c=v(r,{roughness:.7,fill:s,stroke:d,fillWeight:3,seed:o}),l=v(r,{roughness:.7,fill:`none`,stroke:d,seed:o}),u=e.rectangle(a,k,D,t,c);I=_.insert(()=>u,`:first-child`);let f=e.rectangle(a,n,D,i,l);L=_.insert(()=>f,`:first-child`),I.select(`path:nth-child(2)`).attr(`style`,m.join(`;`)),I.select(`path`).attr(`style`,g.join(`;`).replace(`fill`,`stroke`))}else I=_.insert(`rect`,`:first-child`),L=_.insert(`rect`,`:first-child`),I.attr(`class`,`swimlane-title`).attr(`style`,p).attr(`x`,a).attr(`y`,k).attr(`width`,D).attr(`height`,t).attr(`fill`,s).attr(`stroke`,d),L.attr(`class`,`swimlane-body`).attr(`style`,p).attr(`x`,a).attr(`y`,n).attr(`width`,D).attr(`height`,i).attr(`fill`,`none`).attr(`stroke`,d);let c=r.x-T.width/2,l=k+(t-T.height)/2;C.attr(`transform`,`translate(${c}, ${l})`)}if(t.trace(`Swimlane data `,r,JSON.stringify(r)),f){let e=C.select(`span`);e&&e.attr(`style`,f)}return r.offsetX=0,r.width=D,r.height=O,r.offsetY=T.height-E/2,r.intersect=function(e){return j(r,e)},{cluster:_,labelBBox:T}},`swimlane`),F=e(async(e,r)=>{t.info(`Creating subgraph rect for `,r.id,r);let i=l(),{themeVariables:a,handDrawnSeed:s}=i,{clusterBkg:c,clusterBorder:u}=a,{labelStyles:d,nodeStyles:f,borderStyles:p,backgroundStyles:m}=y(r),_=e.insert(`g`).attr(`class`,`cluster `+r.cssClasses).attr(`id`,r.domId).attr(`data-look`,r.look),b=o(i),x=_.insert(`g`).attr(`class`,`cluster-label `),C;C=r.labelType===`markdown`?await h(x,r.label,{style:r.labelStyle,useHtmlLabels:b,isNode:!0,width:r.width}):await M(x,r.label,r.labelStyle||``,!1,!0);let w=C.getBBox();if(o(i)){let e=C.children[0],t=n(C);w=e.getBoundingClientRect(),t.attr(`width`,w.width),t.attr(`height`,w.height)}let T=r.width<=w.width+r.padding?w.width+r.padding:r.width;r.width<=w.width+r.padding?r.diff=(T-r.width)/2-r.padding:r.diff=-r.padding;let E=r.height,D=r.x-T/2,O=r.y-E/2;t.trace(`Data `,r,JSON.stringify(r));let k;if(r.look===`handDrawn`){let e=S.svg(_),n=v(r,{roughness:.7,fill:c,stroke:u,fillWeight:3,seed:s}),i=e.path(N(D,O,T,E,0),n);k=_.insert(()=>(t.debug(`Rough node insert CXC`,i),i),`:first-child`),k.select(`path:nth-child(2)`).attr(`style`,p.join(`;`)),k.select(`path`).attr(`style`,m.join(`;`).replace(`fill`,`stroke`))}else k=_.insert(`rect`,`:first-child`),k.attr(`style`,f).attr(`rx`,r.rx).attr(`ry`,r.ry).attr(`x`,D).attr(`y`,O).attr(`width`,T).attr(`height`,E);let{subGraphTitleTopMargin:A}=g(i);if(x.attr(`transform`,`translate(${r.x-w.width/2}, ${r.y-r.height/2+A})`),d){let e=x.select(`span`);e&&e.attr(`style`,d)}let P=k.node().getBBox();return r.offsetX=0,r.width=P.width,r.height=P.height,r.offsetY=w.height-r.padding/2,r.intersect=function(e){return j(r,e)},{cluster:_,labelBBox:w}},`rect`),I={rect:F,squareRect:F,roundedWithTitle:e(async(e,t)=>{let r=l(),{themeVariables:i,handDrawnSeed:a}=r,{altBackground:s,compositeBackground:c,compositeTitleBackground:u,nodeBorder:d}=i,f=e.insert(`g`).attr(`class`,t.cssClasses).attr(`id`,t.domId).attr(`data-id`,t.id).attr(`data-look`,t.look),p=f.insert(`g`,`:first-child`),m=f.insert(`g`).attr(`class`,`cluster-label`),h=f.append(`rect`),g=await M(m,t.label,t.labelStyle,void 0,!0),_=g.getBBox();if(o(r)){let e=g.children[0],t=n(g);_=e.getBoundingClientRect(),t.attr(`width`,_.width),t.attr(`height`,_.height)}let v=0*t.padding,y=v/2,b=(t.width<=_.width+t.padding?_.width+t.padding:t.width)+v;t.width<=_.width+t.padding?t.diff=(b-t.width)/2-t.padding:t.diff=-t.padding;let x=t.height+v,C=t.height+v-_.height-6,w=t.x-b/2,T=t.y-x/2;t.width=b;let E=t.y-t.height/2-y+_.height+2,D;if(t.look===`handDrawn`){let e=t.cssClasses.includes(`statediagram-cluster-alt`),n=S.svg(f),r=t.rx||t.ry?n.path(N(w,T,b,x,10),{roughness:.7,fill:u,fillStyle:`solid`,stroke:d,seed:a}):n.rectangle(w,T,b,x,{seed:a});D=f.insert(()=>r,`:first-child`);let i=n.rectangle(w,E,b,C,{fill:e?s:c,fillStyle:e?`hachure`:`solid`,stroke:d,seed:a});D=f.insert(()=>r,`:first-child`),h=f.insert(()=>i)}else D=p.insert(`rect`,`:first-child`),D.attr(`class`,`outer`).attr(`x`,w).attr(`y`,T).attr(`width`,b).attr(`height`,x).attr(`data-look`,t.look),h.attr(`class`,`inner`).attr(`x`,w).attr(`y`,E).attr(`width`,b).attr(`height`,C);return m.attr(`transform`,`translate(${t.x-_.width/2}, ${T+1-(o(r)?0:3)})`),t.height=D.node().getBBox().height,t.offsetX=0,t.offsetY=_.height-t.padding/2,t.labelBBox=_,t.intersect=function(e){return j(t,e)},{cluster:f,labelBBox:_}},`roundedWithTitle`),noteGroup:e((e,t)=>{let n=e.insert(`g`).attr(`class`,`note-cluster`).attr(`id`,t.domId),r=n.insert(`rect`,`:first-child`),i=0*t.padding,a=i/2;r.attr(`rx`,t.rx).attr(`ry`,t.ry).attr(`x`,t.x-t.width/2-a).attr(`y`,t.y-t.height/2-a).attr(`width`,t.width+i).attr(`height`,t.height+i).attr(`fill`,`none`);let o=r.node().getBBox();return t.width=o.width,t.height=o.height,t.intersect=function(e){return j(t,e)},{cluster:n,labelBBox:{width:0,height:0}}},`noteGroup`),divider:e((e,t)=>{let{themeVariables:n,handDrawnSeed:r}=l(),{nodeBorder:i}=n,a=e.insert(`g`).attr(`class`,t.cssClasses).attr(`id`,t.domId).attr(`data-look`,t.look),o=a.insert(`g`,`:first-child`),s=0*t.padding,c=t.width+s;t.diff=-t.padding;let u=t.height+s,d=t.x-c/2,f=t.y-u/2;t.width=c;let p;if(t.look===`handDrawn`){let e=S.svg(a).rectangle(d,f,c,u,{fill:`lightgrey`,roughness:.5,strokeLineDash:[5],stroke:i,seed:r});p=a.insert(()=>e,`:first-child`)}else{p=o.insert(`rect`,`:first-child`);let e=`outer`;e=(t.look,`divider`),p.attr(`class`,e).attr(`x`,d).attr(`y`,f).attr(`width`,c).attr(`height`,u).attr(`data-look`,t.look)}return t.height=p.node().getBBox().height,t.offsetX=0,t.offsetY=0,t.intersect=function(e){return j(t,e)},{cluster:a,labelBBox:{}}},`divider`),kanbanSection:e(async(e,r)=>{t.info(`Creating subgraph rect for `,r.id,r);let i=l(),{themeVariables:a,handDrawnSeed:s}=i,{clusterBkg:c,clusterBorder:u}=a,{labelStyles:d,nodeStyles:f,borderStyles:p,backgroundStyles:m}=y(r),_=e.insert(`g`).attr(`class`,`cluster `+r.cssClasses).attr(`id`,r.domId).attr(`data-look`,r.look),b=o(i),x=_.insert(`g`).attr(`class`,`cluster-label `),C=await h(x,r.label,{style:r.labelStyle,useHtmlLabels:b,isNode:!0,width:r.width}),w=C.getBBox();if(o(i)){let e=C.children[0],t=n(C);w=e.getBoundingClientRect(),t.attr(`width`,w.width),t.attr(`height`,w.height)}let T=r.width<=w.width+r.padding?w.width+r.padding:r.width;r.width<=w.width+r.padding?r.diff=(T-r.width)/2-r.padding:r.diff=-r.padding;let E=r.height,D=r.x-T/2,O=r.y-E/2;t.trace(`Data `,r,JSON.stringify(r));let k;if(r.look===`handDrawn`){let e=S.svg(_),n=v(r,{roughness:.7,fill:c,stroke:u,fillWeight:4,seed:s}),i=e.path(N(D,O,T,E,r.rx),n);k=_.insert(()=>(t.debug(`Rough node insert CXC`,i),i),`:first-child`),k.select(`path:nth-child(2)`).attr(`style`,p.join(`;`)),k.select(`path`).attr(`style`,m.join(`;`).replace(`fill`,`stroke`))}else k=_.insert(`rect`,`:first-child`),k.attr(`style`,f).attr(`rx`,r.rx).attr(`ry`,r.ry).attr(`x`,D).attr(`y`,O).attr(`width`,T).attr(`height`,E);let{subGraphTitleTopMargin:A}=g(i);if(x.attr(`transform`,`translate(${r.x-w.width/2}, ${r.y-r.height/2+A})`),d){let e=x.select(`span`);e&&e.attr(`style`,d)}let M=k.node().getBBox();return r.offsetX=0,r.width=M.width,r.height=M.height,r.offsetY=w.height-r.padding/2,r.intersect=function(e){return j(r,e)},{cluster:_,labelBBox:w}},`kanbanSection`),swimlane:P},L=new Map,ee=e(async(e,t)=>{let n=await I[t.shape||`rect`](e,t);return L.set(t.id,n),n},`insertCluster`),R=e(()=>{L=new Map},`clear`);function z(e,t){return e.intersect(t)}e(z,`intersectNode`);var te=z;function B(e,t,n,r){var i=e.x,a=e.y,o=i-r.x,s=a-r.y,c=Math.sqrt(t*t*s*s+n*n*o*o),l=Math.abs(t*n*o/c);r.x0}e(re,`sameSign`);var ie=ne;function W(e,t,n){let r=e.x,i=e.y,a=[],o=1/0,s=1/0;typeof t.forEach==`function`?t.forEach(function(e){o=Math.min(o,e.x),s=Math.min(s,e.y)}):(o=Math.min(o,t.x),s=Math.min(s,t.y));let c=r-e.width/2-o,l=i-e.height/2-s;for(let r=0;r1&&a.sort(function(e,t){let r=e.x-n.x,i=e.y-n.y,a=Math.sqrt(r*r+i*i),o=t.x-n.x,s=t.y-n.y,c=Math.sqrt(o*o+s*s);return au,`:first-child`);return d.attr(`class`,`anchor`).attr(`style`,p(s)),T(n,d),n.intersect=function(e){return t.info(`Circle intersect`,n,1,e),G.circle(n,1,e)},o}e(K,`anchor`);function ae(e,t,n,r,i,a,o){let s=(e+n)/2,c=(t+r)/2,l=Math.atan2(r-t,n-e),u=(n-e)/2,d=(r-t)/2,f=u/i,p=d/a,m=Math.sqrt(f**2+p**2);if(m>1)throw Error(`The given radii are too small to create an arc between the points.`);let h=Math.sqrt(1-m**2),g=s+h*a*Math.sin(l)*(o?-1:1),_=c-h*i*Math.cos(l)*(o?-1:1),v=Math.atan2((t-_)/a,(e-g)/i),y=Math.atan2((r-_)/a,(n-g)/i)-v;o&&y<0&&(y+=2*Math.PI),!o&&y>0&&(y-=2*Math.PI);let b=[];for(let e=0;e<20;e++){let t=v+e/19*y,n=g+i*Math.cos(t),r=_+a*Math.sin(t);b.push({x:n,y:r})}return b}e(ae,`generateArcPoints`);function oe(e,t,n){let[r,i]=[t,n].sort((e,t)=>t-e);return i*(1-Math.sqrt(1-(e/r/2)**2))}e(oe,`calculateArcSagitta`);async function se(t,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let a=n.padding??0,o=n.look===`neo`?16:a,s=n.look===`neo`?12:a,c=e(e=>e+s,`calcTotalHeight`),l=e(e=>{let t=e/2;return[t/(2.5+e/50),t]},`calcEllipseRadius`),{shapeSvg:u,bbox:d}=await C(t,n,E(n)),f=c(n?.height?n?.height:d.height),[p,m]=l(f),h=oe(f,p,m),g=(n?.width?n?.width:d.width)+o*2+h-h,_=f,{cssStyles:b}=n,x=[{x:g/2,y:-_/2},{x:-g/2,y:-_/2},...ae(-g/2,-_/2,-g/2,_/2,p,m,!1),{x:g/2,y:_/2},...ae(g/2,_/2,g/2,-_/2,p,m,!0)],w=S.svg(u),O=v(n,{});n.look!==`handDrawn`&&(O.roughness=0,O.fillStyle=`solid`);let k=D(x),A=w.path(k,O),j=u.insert(()=>A,`:first-child`);return j.attr(`class`,`basic label-container outer-path`),b&&n.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,b),i&&n.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,i),j.attr(`transform`,`translate(${p/2}, 0)`),T(n,j),n.intersect=function(e){return G.polygon(n,x,e)},u}e(se,`bowTieRect`);function q(e,t,n,r){return e.insert(`polygon`,`:first-child`).attr(`points`,r.map(function(e){return e.x+`,`+e.y}).join(` `)).attr(`class`,`label-container`).attr(`transform`,`translate(`+-t/2+`,`+n/2+`)`)}e(q,`insertPolygonShape`);var ce=12;async function le(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?28:i,o=t.look===`neo`?24:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.width??c.width)+(t.look===`neo`?a*2:a+ce),u=(t?.height??c.height)+(t.look===`neo`?o*2:o),d=l,f=-u,p=[{x:0+ce,y:f},{x:d,y:f},{x:d,y:0},{x:0,y:0},{x:0,y:f+ce},{x:0+ce,y:f}],m,{cssStyles:h}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(p),i=e.path(r,n);m=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-l/2}, ${u/2})`),h&&m.attr(`style`,h)}else m=q(s,l,u,p);return r&&m.attr(`style`,r),T(t,m),t.intersect=function(e){return G.polygon(t,p,e)},s}e(le,`card`);function ue(e,t){let{nodeStyles:n}=y(t);t.label=``;let r=e.insert(`g`).attr(`class`,E(t)).attr(`id`,t.domId??t.id),{cssStyles:i}=t,a=Math.max(28,t.width??0),o=[{x:0,y:a/2},{x:a/2,y:0},{x:0,y:-a/2},{x:-a/2,y:0}],s=S.svg(r),c=v(t,{});t.look!==`handDrawn`&&(c.roughness=0,c.fillStyle=`solid`);let l=D(o),u=s.path(l,c),d=r.insert(()=>u,`:first-child`);return i&&t.look!==`handDrawn`&&d.selectAll(`path`).attr(`style`,i),n&&t.look!==`handDrawn`&&d.selectAll(`path`).attr(`style`,n),t.width=28,t.height=28,t.intersect=function(e){return G.polygon(t,o,e)},r}e(ue,`choice`);async function de(e,n,r){let{labelStyles:i,nodeStyles:a}=y(n);n.labelStyle=i;let{shapeSvg:o,bbox:s,halfPadding:c}=await C(e,n,E(n)),l=r?.padding??c,u=n.look===`neo`?s.width/2+32:s.width/2+l,d,{cssStyles:f}=n;if(n.look===`handDrawn`){let e=S.svg(o),t=v(n,{}),r=e.circle(0,0,u*2,t);d=o.insert(()=>r,`:first-child`),d.attr(`class`,`basic label-container`).attr(`style`,p(f))}else d=o.insert(`circle`,`:first-child`).attr(`class`,`basic label-container`).attr(`style`,a).attr(`r`,u).attr(`cx`,0).attr(`cy`,0);return T(n,d),n.calcIntersect=function(e,t){let n=e.width/2;return G.circle(e,n,t)},n.intersect=function(e){return t.info(`Circle intersect`,n,u,e),G.circle(n,u,e)},o}e(de,`circle`);function fe(e){let t=Math.cos(Math.PI/4),n=Math.sin(Math.PI/4),r=e*2,i={x:r/2*t,y:r/2*n},a={x:-(r/2)*t,y:r/2*n},o={x:-(r/2)*t,y:-(r/2)*n},s={x:r/2*t,y:-(r/2)*n};return`M ${a.x},${a.y} L ${s.x},${s.y} +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{A as r,B as i,M as a,T as o,b as s,g as c,x as l,z as u}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{a as d,r as f,u as p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-HOUHSVGY-iJuv90UH.js";import{n as h}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{n as g,t as _}from"./chunk-OGEWGWER-D-nWYRNR.js";import{a as v,i as y,r as b,t as x}from"./chunk-C7G6YPKG-DW-1jWUA.js";import{t as S}from"./rough.esm-CSKSodPl.js";var C=e(async(e,t,r)=>{let i,a=t.useHtmlLabels||c(l()?.htmlLabels);i=r||`node default`;let o=e.insert(`g`).attr(`class`,i).attr(`id`,t.domId||t.id),s=o.insert(`g`).attr(`class`,`label`).attr(`style`,p(t.labelStyle)),f;f=t.label===void 0?``:typeof t.label==`string`?t.label:t.label[0];let m=!!t.icon||!!t.img,g=t.labelType===`markdown`,v=await h(s,u(d(f),l()),{useHtmlLabels:a,width:t.width||l().flowchart?.wrappingWidth,classes:g?`markdown-node-label`:``,style:t.labelStyle,addSvgBackground:m,markdown:g},l()),y=v.getBBox(),b=(t?.padding??0)/2;if(a){let e=v.children[0],t=n(v);await _(e,f),y=e.getBoundingClientRect(),t.attr(`width`,y.width),t.attr(`height`,y.height)}return a?s.attr(`transform`,`translate(`+-y.width/2+`, `+-y.height/2+`)`):s.attr(`transform`,`translate(0, `+-y.height/2+`)`),t.centerLabel&&s.attr(`transform`,`translate(`+-y.width/2+`, `+-y.height/2+`)`),s.insert(`rect`,`:first-child`),{shapeSvg:o,bbox:y,halfPadding:b,label:s}},`labelHelper`),w=e(async(e,t,r)=>{let i=r.useHtmlLabels??o(l()),a=e.insert(`g`).attr(`class`,`label`).attr(`style`,r.labelStyle||``),s=await h(a,u(d(t),l()),{useHtmlLabels:i,width:r.width||l()?.flowchart?.wrappingWidth,style:r.labelStyle,addSvgBackground:!!r.icon||!!r.img}),c=s.getBBox(),f=r.padding/2;if(o(l())){let e=s.children[0],t=n(s);c=e.getBoundingClientRect(),t.attr(`width`,c.width),t.attr(`height`,c.height)}return i?a.attr(`transform`,`translate(`+-c.width/2+`, `+-c.height/2+`)`):a.attr(`transform`,`translate(0, `+-c.height/2+`)`),r.centerLabel&&a.attr(`transform`,`translate(`+-c.width/2+`, `+-c.height/2+`)`),a.insert(`rect`,`:first-child`),{shapeSvg:e,bbox:c,halfPadding:f,label:a}},`insertLabel`),T=e((e,t)=>{let n=t.node().getBBox();e.width=n.width,e.height=n.height},`updateNodeBounds`),E=e((e,t)=>(e.look===`handDrawn`?`rough-node`:`node`)+` `+e.cssClasses+` `+(t||``),`getNodeClasses`);function D(e){let t=e.map((e,t)=>`${t===0?`M`:`L`}${e.x},${e.y}`);return t.push(`Z`),t.join(` `)}e(D,`createPathFromPoints`);function O(e,t,n,r,i,a){let o=[],s=n-e,c=r-t,l=s/a,u=2*Math.PI/l,d=t+c/2;for(let t=0;t<=50;t++){let n=e+t/50*s,r=d+i*Math.sin(u*(n-e));o.push({x:n,y:r})}return o}e(O,`generateFullSineWavePoints`);function k(e,t,n,r,i,a){let o=[],s=i*Math.PI/180,c=(a*Math.PI/180-s)/(r-1);for(let i=0;ie.tagName===`path`),r=document.createElementNS(`http://www.w3.org/2000/svg`,`path`),i=n.map(e=>e.getAttribute(`d`)).filter(e=>e!==null).join(` `);r.setAttribute(`d`,i);let a=n.find(e=>e.getAttribute(`fill`)!==`none`),o=n.find(e=>e.getAttribute(`stroke`)!==`none`),s=e((e,t)=>e?.getAttribute(t)??void 0,`getAttr`);if(a){let e={fill:s(a,`fill`),"fill-opacity":s(a,`fill-opacity`)??`1`};Object.entries(e).forEach(([e,t])=>{t&&r.setAttribute(e,t)})}if(o){let e={stroke:s(o,`stroke`),"stroke-width":s(o,`stroke-width`)??`1`,"stroke-opacity":s(o,`stroke-opacity`)??`1`};Object.entries(e).forEach(([e,t])=>{t&&r.setAttribute(e,t)})}let c=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);return c.appendChild(r),c}e(A,`mergePaths`);var j=e((e,t)=>{var n=e.x,r=e.y,i=t.x-n,a=t.y-r,o=e.width/2,s=e.height/2,c,l;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),c=a===0?0:s*i/a,l=s):(i<0&&(o=-o),c=o,l=i===0?0:o*a/i),{x:n+c,y:r+l}},`intersectRect`),M=e(async(e,t,n,r=!1,i=!1)=>{let a=t||``;typeof a==`object`&&(a=a[0]);let s=l(),c=o(s);return await h(e,a,{style:n,isTitle:r,useHtmlLabels:c,markdown:!1,isNode:i,width:1/0},s)},`createLabel`),N=e((e,t,n,r,i)=>[`M`,e+i,t,`H`,e+n-i,`A`,i,i,0,0,1,e+n,t+i,`V`,t+r-i,`A`,i,i,0,0,1,e+n-i,t+r,`H`,e+i,`A`,i,i,0,0,1,e,t+r-i,`V`,t+i,`A`,i,i,0,0,1,e+i,t,`Z`].join(` `),`createRoundedRectPathD`),P=e(async(e,r)=>{let i=l(),{themeVariables:a,handDrawnSeed:o}=i,{clusterBkg:s,clusterBorder:u}=a,d=u,{labelStyles:f,nodeStyles:p,borderStyles:m,backgroundStyles:g}=y(r),_=e.insert(`g`).attr(`class`,`cluster swimlane `+(r.cssClasses||``)).attr(`id`,r.id).attr(`data-id`,r.id).attr(`data-et`,`cluster`).attr(`data-look`,r.look),b=c(i.flowchart.htmlLabels),x=r.direction===`LR`,C=_.insert(`g`).attr(`class`,`cluster-label swimlane-label`),w=await h(C,r.label,{style:r.labelStyle,useHtmlLabels:b,isNode:!0,width:r.width}),T=w.getBBox();if(b){let e=w.children[0],t=n(w);T=e.getBoundingClientRect(),t.attr(`width`,T.width),t.attr(`height`,T.height)}let E=r.padding??0,D=r.width<=T.width+E?T.width+E:r.width;r.width<=T.width+E?r.diff=(D-r.width)/2-E:r.diff=-E;let O=r.height,k=r.y-O/2,A=r.y+O/2,M=r.x-D/2,N=r.swimlaneContentTop===void 0?k+O/3:r.swimlaneContentTop,P=x?4:0,F=T.height+2*P,I,L;if(x){let e=Math.max(F,T.height+2*P),t=M+e,n=Math.max(0,D-e);if(r.look===`handDrawn`){let i=S.svg(_),a=v(r,{roughness:.7,fill:s,stroke:d,fillWeight:3,seed:o}),c=v(r,{roughness:.7,fill:`none`,stroke:d,seed:o}),l=i.rectangle(M,k,e,O,a);I=_.insert(()=>l,`:first-child`);let u=i.rectangle(t,k,n,O,c);L=_.insert(()=>u,`:first-child`),I.select(`path:nth-child(2)`).attr(`style`,m.join(`;`)),I.select(`path`).attr(`style`,g.join(`;`).replace(`fill`,`stroke`))}else I=_.insert(`rect`,`:first-child`),L=_.insert(`rect`,`:first-child`),I.attr(`class`,`swimlane-title`).attr(`style`,p).attr(`x`,M).attr(`y`,k).attr(`width`,e).attr(`height`,O).attr(`fill`,s).attr(`stroke`,d),L.attr(`class`,`swimlane-body`).attr(`style`,p).attr(`x`,t).attr(`y`,k).attr(`width`,n).attr(`height`,O).attr(`fill`,`none`).attr(`stroke`,d);let i=M+e/2,a=r.y;C.attr(`transform`,`translate(${i}, ${a}) rotate(-90) translate(${-T.width/2}, ${-T.height/2})`)}else{let e=Math.max(0,N-k),t=Math.min(F,e),n=k+t,i=Math.max(0,A-n),a=r.x-D/2;if(r.look===`handDrawn`){let e=S.svg(_),c=v(r,{roughness:.7,fill:s,stroke:d,fillWeight:3,seed:o}),l=v(r,{roughness:.7,fill:`none`,stroke:d,seed:o}),u=e.rectangle(a,k,D,t,c);I=_.insert(()=>u,`:first-child`);let f=e.rectangle(a,n,D,i,l);L=_.insert(()=>f,`:first-child`),I.select(`path:nth-child(2)`).attr(`style`,m.join(`;`)),I.select(`path`).attr(`style`,g.join(`;`).replace(`fill`,`stroke`))}else I=_.insert(`rect`,`:first-child`),L=_.insert(`rect`,`:first-child`),I.attr(`class`,`swimlane-title`).attr(`style`,p).attr(`x`,a).attr(`y`,k).attr(`width`,D).attr(`height`,t).attr(`fill`,s).attr(`stroke`,d),L.attr(`class`,`swimlane-body`).attr(`style`,p).attr(`x`,a).attr(`y`,n).attr(`width`,D).attr(`height`,i).attr(`fill`,`none`).attr(`stroke`,d);let c=r.x-T.width/2,l=k+(t-T.height)/2;C.attr(`transform`,`translate(${c}, ${l})`)}if(t.trace(`Swimlane data `,r,JSON.stringify(r)),f){let e=C.select(`span`);e&&e.attr(`style`,f)}return r.offsetX=0,r.width=D,r.height=O,r.offsetY=T.height-E/2,r.intersect=function(e){return j(r,e)},{cluster:_,labelBBox:T}},`swimlane`),F=e(async(e,r)=>{t.info(`Creating subgraph rect for `,r.id,r);let i=l(),{themeVariables:a,handDrawnSeed:s}=i,{clusterBkg:c,clusterBorder:u}=a,{labelStyles:d,nodeStyles:f,borderStyles:p,backgroundStyles:m}=y(r),_=e.insert(`g`).attr(`class`,`cluster `+r.cssClasses).attr(`id`,r.domId).attr(`data-look`,r.look),b=o(i),x=_.insert(`g`).attr(`class`,`cluster-label `),C;C=r.labelType===`markdown`?await h(x,r.label,{style:r.labelStyle,useHtmlLabels:b,isNode:!0,width:r.width}):await M(x,r.label,r.labelStyle||``,!1,!0);let w=C.getBBox();if(o(i)){let e=C.children[0],t=n(C);w=e.getBoundingClientRect(),t.attr(`width`,w.width),t.attr(`height`,w.height)}let T=r.width<=w.width+r.padding?w.width+r.padding:r.width;r.width<=w.width+r.padding?r.diff=(T-r.width)/2-r.padding:r.diff=-r.padding;let E=r.height,D=r.x-T/2,O=r.y-E/2;t.trace(`Data `,r,JSON.stringify(r));let k;if(r.look===`handDrawn`){let e=S.svg(_),n=v(r,{roughness:.7,fill:c,stroke:u,fillWeight:3,seed:s}),i=e.path(N(D,O,T,E,0),n);k=_.insert(()=>(t.debug(`Rough node insert CXC`,i),i),`:first-child`),k.select(`path:nth-child(2)`).attr(`style`,p.join(`;`)),k.select(`path`).attr(`style`,m.join(`;`).replace(`fill`,`stroke`))}else k=_.insert(`rect`,`:first-child`),k.attr(`style`,f).attr(`rx`,r.rx).attr(`ry`,r.ry).attr(`x`,D).attr(`y`,O).attr(`width`,T).attr(`height`,E);let{subGraphTitleTopMargin:A}=g(i);if(x.attr(`transform`,`translate(${r.x-w.width/2}, ${r.y-r.height/2+A})`),d){let e=x.select(`span`);e&&e.attr(`style`,d)}let P=k.node().getBBox();return r.offsetX=0,r.width=P.width,r.height=P.height,r.offsetY=w.height-r.padding/2,r.intersect=function(e){return j(r,e)},{cluster:_,labelBBox:w}},`rect`),I={rect:F,squareRect:F,roundedWithTitle:e(async(e,t)=>{let r=l(),{themeVariables:i,handDrawnSeed:a}=r,{altBackground:s,compositeBackground:c,compositeTitleBackground:u,nodeBorder:d}=i,f=e.insert(`g`).attr(`class`,t.cssClasses).attr(`id`,t.domId).attr(`data-id`,t.id).attr(`data-look`,t.look),p=f.insert(`g`,`:first-child`),m=f.insert(`g`).attr(`class`,`cluster-label`),h=f.append(`rect`),g=await M(m,t.label,t.labelStyle,void 0,!0),_=g.getBBox();if(o(r)){let e=g.children[0],t=n(g);_=e.getBoundingClientRect(),t.attr(`width`,_.width),t.attr(`height`,_.height)}let v=0*t.padding,y=v/2,b=(t.width<=_.width+t.padding?_.width+t.padding:t.width)+v;t.width<=_.width+t.padding?t.diff=(b-t.width)/2-t.padding:t.diff=-t.padding;let x=t.height+v,C=t.height+v-_.height-6,w=t.x-b/2,T=t.y-x/2;t.width=b;let E=t.y-t.height/2-y+_.height+2,D;if(t.look===`handDrawn`){let e=t.cssClasses.includes(`statediagram-cluster-alt`),n=S.svg(f),r=t.rx||t.ry?n.path(N(w,T,b,x,10),{roughness:.7,fill:u,fillStyle:`solid`,stroke:d,seed:a}):n.rectangle(w,T,b,x,{seed:a});D=f.insert(()=>r,`:first-child`);let i=n.rectangle(w,E,b,C,{fill:e?s:c,fillStyle:e?`hachure`:`solid`,stroke:d,seed:a});D=f.insert(()=>r,`:first-child`),h=f.insert(()=>i)}else D=p.insert(`rect`,`:first-child`),D.attr(`class`,`outer`).attr(`x`,w).attr(`y`,T).attr(`width`,b).attr(`height`,x).attr(`data-look`,t.look),h.attr(`class`,`inner`).attr(`x`,w).attr(`y`,E).attr(`width`,b).attr(`height`,C);return m.attr(`transform`,`translate(${t.x-_.width/2}, ${T+1-(o(r)?0:3)})`),t.height=D.node().getBBox().height,t.offsetX=0,t.offsetY=_.height-t.padding/2,t.labelBBox=_,t.intersect=function(e){return j(t,e)},{cluster:f,labelBBox:_}},`roundedWithTitle`),noteGroup:e((e,t)=>{let n=e.insert(`g`).attr(`class`,`note-cluster`).attr(`id`,t.domId),r=n.insert(`rect`,`:first-child`),i=0*t.padding,a=i/2;r.attr(`rx`,t.rx).attr(`ry`,t.ry).attr(`x`,t.x-t.width/2-a).attr(`y`,t.y-t.height/2-a).attr(`width`,t.width+i).attr(`height`,t.height+i).attr(`fill`,`none`);let o=r.node().getBBox();return t.width=o.width,t.height=o.height,t.intersect=function(e){return j(t,e)},{cluster:n,labelBBox:{width:0,height:0}}},`noteGroup`),divider:e((e,t)=>{let{themeVariables:n,handDrawnSeed:r}=l(),{nodeBorder:i}=n,a=e.insert(`g`).attr(`class`,t.cssClasses).attr(`id`,t.domId).attr(`data-look`,t.look),o=a.insert(`g`,`:first-child`),s=0*t.padding,c=t.width+s;t.diff=-t.padding;let u=t.height+s,d=t.x-c/2,f=t.y-u/2;t.width=c;let p;if(t.look===`handDrawn`){let e=S.svg(a).rectangle(d,f,c,u,{fill:`lightgrey`,roughness:.5,strokeLineDash:[5],stroke:i,seed:r});p=a.insert(()=>e,`:first-child`)}else{p=o.insert(`rect`,`:first-child`);let e=`outer`;e=(t.look,`divider`),p.attr(`class`,e).attr(`x`,d).attr(`y`,f).attr(`width`,c).attr(`height`,u).attr(`data-look`,t.look)}return t.height=p.node().getBBox().height,t.offsetX=0,t.offsetY=0,t.intersect=function(e){return j(t,e)},{cluster:a,labelBBox:{}}},`divider`),kanbanSection:e(async(e,r)=>{t.info(`Creating subgraph rect for `,r.id,r);let i=l(),{themeVariables:a,handDrawnSeed:s}=i,{clusterBkg:c,clusterBorder:u}=a,{labelStyles:d,nodeStyles:f,borderStyles:p,backgroundStyles:m}=y(r),_=e.insert(`g`).attr(`class`,`cluster `+r.cssClasses).attr(`id`,r.domId).attr(`data-look`,r.look),b=o(i),x=_.insert(`g`).attr(`class`,`cluster-label `),C=await h(x,r.label,{style:r.labelStyle,useHtmlLabels:b,isNode:!0,width:r.width}),w=C.getBBox();if(o(i)){let e=C.children[0],t=n(C);w=e.getBoundingClientRect(),t.attr(`width`,w.width),t.attr(`height`,w.height)}let T=r.width<=w.width+r.padding?w.width+r.padding:r.width;r.width<=w.width+r.padding?r.diff=(T-r.width)/2-r.padding:r.diff=-r.padding;let E=r.height,D=r.x-T/2,O=r.y-E/2;t.trace(`Data `,r,JSON.stringify(r));let k;if(r.look===`handDrawn`){let e=S.svg(_),n=v(r,{roughness:.7,fill:c,stroke:u,fillWeight:4,seed:s}),i=e.path(N(D,O,T,E,r.rx),n);k=_.insert(()=>(t.debug(`Rough node insert CXC`,i),i),`:first-child`),k.select(`path:nth-child(2)`).attr(`style`,p.join(`;`)),k.select(`path`).attr(`style`,m.join(`;`).replace(`fill`,`stroke`))}else k=_.insert(`rect`,`:first-child`),k.attr(`style`,f).attr(`rx`,r.rx).attr(`ry`,r.ry).attr(`x`,D).attr(`y`,O).attr(`width`,T).attr(`height`,E);let{subGraphTitleTopMargin:A}=g(i);if(x.attr(`transform`,`translate(${r.x-w.width/2}, ${r.y-r.height/2+A})`),d){let e=x.select(`span`);e&&e.attr(`style`,d)}let M=k.node().getBBox();return r.offsetX=0,r.width=M.width,r.height=M.height,r.offsetY=w.height-r.padding/2,r.intersect=function(e){return j(r,e)},{cluster:_,labelBBox:w}},`kanbanSection`),swimlane:P},L=new Map,ee=e(async(e,t)=>{let n=await I[t.shape||`rect`](e,t);return L.set(t.id,n),n},`insertCluster`),R=e(()=>{L=new Map},`clear`);function z(e,t){return e.intersect(t)}e(z,`intersectNode`);var te=z;function B(e,t,n,r){var i=e.x,a=e.y,o=i-r.x,s=a-r.y,c=Math.sqrt(t*t*s*s+n*n*o*o),l=Math.abs(t*n*o/c);r.x0}e(re,`sameSign`);var ie=ne;function W(e,t,n){let r=e.x,i=e.y,a=[],o=1/0,s=1/0;typeof t.forEach==`function`?t.forEach(function(e){o=Math.min(o,e.x),s=Math.min(s,e.y)}):(o=Math.min(o,t.x),s=Math.min(s,t.y));let c=r-e.width/2-o,l=i-e.height/2-s;for(let r=0;r1&&a.sort(function(e,t){let r=e.x-n.x,i=e.y-n.y,a=Math.sqrt(r*r+i*i),o=t.x-n.x,s=t.y-n.y,c=Math.sqrt(o*o+s*s);return au,`:first-child`);return d.attr(`class`,`anchor`).attr(`style`,p(s)),T(n,d),n.intersect=function(e){return t.info(`Circle intersect`,n,1,e),G.circle(n,1,e)},o}e(K,`anchor`);function ae(e,t,n,r,i,a,o){let s=(e+n)/2,c=(t+r)/2,l=Math.atan2(r-t,n-e),u=(n-e)/2,d=(r-t)/2,f=u/i,p=d/a,m=Math.sqrt(f**2+p**2);if(m>1)throw Error(`The given radii are too small to create an arc between the points.`);let h=Math.sqrt(1-m**2),g=s+h*a*Math.sin(l)*(o?-1:1),_=c-h*i*Math.cos(l)*(o?-1:1),v=Math.atan2((t-_)/a,(e-g)/i),y=Math.atan2((r-_)/a,(n-g)/i)-v;o&&y<0&&(y+=2*Math.PI),!o&&y>0&&(y-=2*Math.PI);let b=[];for(let e=0;e<20;e++){let t=v+e/19*y,n=g+i*Math.cos(t),r=_+a*Math.sin(t);b.push({x:n,y:r})}return b}e(ae,`generateArcPoints`);function oe(e,t,n){let[r,i]=[t,n].sort((e,t)=>t-e);return i*(1-Math.sqrt(1-(e/r/2)**2))}e(oe,`calculateArcSagitta`);async function se(t,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let a=n.padding??0,o=n.look===`neo`?16:a,s=n.look===`neo`?12:a,c=e(e=>e+s,`calcTotalHeight`),l=e(e=>{let t=e/2;return[t/(2.5+e/50),t]},`calcEllipseRadius`),{shapeSvg:u,bbox:d}=await C(t,n,E(n)),f=c(n?.height?n?.height:d.height),[p,m]=l(f),h=oe(f,p,m),g=(n?.width?n?.width:d.width)+o*2+h-h,_=f,{cssStyles:b}=n,x=[{x:g/2,y:-_/2},{x:-g/2,y:-_/2},...ae(-g/2,-_/2,-g/2,_/2,p,m,!1),{x:g/2,y:_/2},...ae(g/2,_/2,g/2,-_/2,p,m,!0)],w=S.svg(u),O=v(n,{});n.look!==`handDrawn`&&(O.roughness=0,O.fillStyle=`solid`);let k=D(x),A=w.path(k,O),j=u.insert(()=>A,`:first-child`);return j.attr(`class`,`basic label-container outer-path`),b&&n.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,b),i&&n.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,i),j.attr(`transform`,`translate(${p/2}, 0)`),T(n,j),n.intersect=function(e){return G.polygon(n,x,e)},u}e(se,`bowTieRect`);function q(e,t,n,r){return e.insert(`polygon`,`:first-child`).attr(`points`,r.map(function(e){return e.x+`,`+e.y}).join(` `)).attr(`class`,`label-container`).attr(`transform`,`translate(`+-t/2+`,`+n/2+`)`)}e(q,`insertPolygonShape`);var ce=12;async function le(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?28:i,o=t.look===`neo`?24:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.width??c.width)+(t.look===`neo`?a*2:a+ce),u=(t?.height??c.height)+(t.look===`neo`?o*2:o),d=l,f=-u,p=[{x:0+ce,y:f},{x:d,y:f},{x:d,y:0},{x:0,y:0},{x:0,y:f+ce},{x:0+ce,y:f}],m,{cssStyles:h}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(p),i=e.path(r,n);m=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-l/2}, ${u/2})`),h&&m.attr(`style`,h)}else m=q(s,l,u,p);return r&&m.attr(`style`,r),T(t,m),t.intersect=function(e){return G.polygon(t,p,e)},s}e(le,`card`);function ue(e,t){let{nodeStyles:n}=y(t);t.label=``;let r=e.insert(`g`).attr(`class`,E(t)).attr(`id`,t.domId??t.id),{cssStyles:i}=t,a=Math.max(28,t.width??0),o=[{x:0,y:a/2},{x:a/2,y:0},{x:0,y:-a/2},{x:-a/2,y:0}],s=S.svg(r),c=v(t,{});t.look!==`handDrawn`&&(c.roughness=0,c.fillStyle=`solid`);let l=D(o),u=s.path(l,c),d=r.insert(()=>u,`:first-child`);return i&&t.look!==`handDrawn`&&d.selectAll(`path`).attr(`style`,i),n&&t.look!==`handDrawn`&&d.selectAll(`path`).attr(`style`,n),t.width=28,t.height=28,t.intersect=function(e){return G.polygon(t,o,e)},r}e(ue,`choice`);async function de(e,n,r){let{labelStyles:i,nodeStyles:a}=y(n);n.labelStyle=i;let{shapeSvg:o,bbox:s,halfPadding:c}=await C(e,n,E(n)),l=r?.padding??c,u=n.look===`neo`?s.width/2+32:s.width/2+l,d,{cssStyles:f}=n;if(n.look===`handDrawn`){let e=S.svg(o),t=v(n,{}),r=e.circle(0,0,u*2,t);d=o.insert(()=>r,`:first-child`),d.attr(`class`,`basic label-container`).attr(`style`,p(f))}else d=o.insert(`circle`,`:first-child`).attr(`class`,`basic label-container`).attr(`style`,a).attr(`r`,u).attr(`cx`,0).attr(`cy`,0);return T(n,d),n.calcIntersect=function(e,t){let n=e.width/2;return G.circle(e,n,t)},n.intersect=function(e){return t.info(`Circle intersect`,n,u,e),G.circle(n,u,e)},o}e(de,`circle`);function fe(e){let t=Math.cos(Math.PI/4),n=Math.sin(Math.PI/4),r=e*2,i={x:r/2*t,y:r/2*n},a={x:-(r/2)*t,y:r/2*n},o={x:-(r/2)*t,y:-(r/2)*n},s={x:r/2*t,y:-(r/2)*n};return`M ${a.x},${a.y} L ${s.x},${s.y} M ${i.x},${i.y} L ${o.x},${o.y}`}e(fe,`createLine`);function pe(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r,n.label=``;let a=e.insert(`g`).attr(`class`,E(n)).attr(`id`,n.domId??n.id),o=Math.max(30,n?.width??0),{cssStyles:s}=n,c=S.svg(a),l=v(n,{});n.look!==`handDrawn`&&(l.roughness=0,l.fillStyle=`solid`);let u=c.circle(0,0,o*2,l),d=fe(o),f=c.path(d,l),p=a.insert(()=>u,`:first-child`);return p.insert(()=>f),p.attr(`class`,`outer-path`),s&&n.look!==`handDrawn`&&p.selectAll(`path`).attr(`style`,s),i&&n.look!==`handDrawn`&&p.selectAll(`path`).attr(`style`,i),T(n,p),n.intersect=function(e){return t.info(`crossedCircle intersect`,n,{radius:o,point:e}),G.circle(n,o,e)},a}e(pe,`crossedCircle`);function J(e,t,n,r=100,i=0,a=180){let o=[],s=i*Math.PI/180,c=(a*Math.PI/180-s)/(r-1);for(let i=0;iw,`:first-child`).attr(`stroke-opacity`,0),O.insert(()=>b,`:first-child`),O.attr(`class`,`text`),f&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,r),O.attr(`transform`,`translate(${d}, 0)`),o.attr(`transform`,`translate(${-l/2+d-(a.x-(a.left??0))},${-u/2+(t.padding??0)/2-(a.y-(a.top??0))})`),T(t,O),t.intersect=function(e){return G.polygon(t,m,e)},i}e(me,`curlyBraceLeft`);function Y(e,t,n,r=100,i=0,a=180){let o=[],s=i*Math.PI/180,c=(a*Math.PI/180-s)/(r-1);for(let i=0;iw,`:first-child`).attr(`stroke-opacity`,0),O.insert(()=>b,`:first-child`),O.attr(`class`,`text`),f&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,r),O.attr(`transform`,`translate(${-d}, 0)`),o.attr(`transform`,`translate(${-l/2+(t.padding??0)/2-(a.x-(a.left??0))},${-u/2+(t.padding??0)/2-(a.y-(a.top??0))})`),T(t,O),t.intersect=function(e){return G.polygon(t,m,e)},i}e(he,`curlyBraceRight`);function X(e,t,n,r=100,i=0,a=180){let o=[],s=i*Math.PI/180,c=(a*Math.PI/180-s)/(r-1);for(let i=0;iA,`:first-child`).attr(`stroke-opacity`,0),j.insert(()=>x,`:first-child`),j.insert(()=>O,`:first-child`),j.attr(`class`,`text`),f&&t.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,r),j.attr(`transform`,`translate(${d-d/4}, 0)`),o.attr(`transform`,`translate(${-l/2+(t.padding??0)/2-(a.x-(a.left??0))},${-u/2+(t.padding??0)/2-(a.y-(a.top??0))})`),T(t,j),t.intersect=function(e){return G.polygon(t,h,e)},i}e(ge,`curlyBraces`);async function _e(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=Math.max(20,(c.width+a*2)*1.25,t?.width??0),u=Math.max(5,c.height+o*2,t?.height??0),d=u/2,{cssStyles:f}=t,p=S.svg(s),m=v(t,{});t.look!==`handDrawn`&&(m.roughness=0,m.fillStyle=`solid`);let h=l,g=u,_=h-d,b=g/4,x=[{x:_,y:0},{x:b,y:0},{x:0,y:g/2},{x:b,y:g},{x:_,y:g},...k(-_,-g/2,d,50,270,90)],w=D(x),O=p.path(w,m),A=s.insert(()=>O,`:first-child`);return A.attr(`class`,`basic label-container outer-path`),f&&t.look!==`handDrawn`&&A.selectChildren(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&A.selectChildren(`path`).attr(`style`,r),A.attr(`transform`,`translate(${-l/2}, ${-u/2})`),T(t,A),t.intersect=function(e){return G.polygon(t,x,e)},s}e(_e,`curvedTrapezoid`);var ve=e((e,t,n,r,i,a)=>[`M${e},${t+a}`,`a${i},${a} 0,0,0 ${n},0`,`a${i},${a} 0,0,0 ${-n},0`,`l0,${r}`,`a${i},${a} 0,0,0 ${n},0`,`l0,${-r}`].join(` `),`createCylinderPathD`),ye=e((e,t,n,r,i,a)=>[`M${e},${t+a}`,`M${e+n},${t+a}`,`a${i},${a} 0,0,0 ${-n},0`,`l0,${r}`,`a${i},${a} 0,0,0 ${n},0`,`l0,${-r}`].join(` `),`createOuterCylinderPathD`),be=e((e,t,n,r,i,a)=>[`M${e-n/2},${-r/2}`,`a${i},${a} 0,0,0 ${n},0`].join(` `),`createInnerCylinderPathD`),xe=8,Se=8;async function Ce(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?24:i,o=t.look===`neo`?24:i;if(t.width||t.height){let e=t.width??0;t.width=(t.width??0)-o,t.widtho,`:first-child`),h=s.insert(()=>a,`:first-child`),h.attr(`class`,`basic label-container`),g&&h.attr(`style`,g)}else{let e=ve(0,0,u,m,d,f);h=s.insert(`path`,`:first-child`).attr(`d`,e).attr(`class`,`basic label-container outer-path`).attr(`style`,p(g)).attr(`style`,r)}return h.attr(`label-offset-y`,f),h.attr(`transform`,`translate(${-u/2}, ${-(m/2+f)})`),T(t,h),l.attr(`transform`,`translate(${-(c.width/2)-(c.x-(c.left??0))}, ${-(c.height/2)+(t.padding??0)/1.5-(c.y-(c.top??0))})`),t.intersect=function(e){let n=G.rect(t,e),r=n.x-(t.x??0);if(d!=0&&(Math.abs(r)<(t.width??0)/2||Math.abs(r)==(t.width??0)/2&&Math.abs(n.y-(t.y??0))>(t.height??0)/2-f)){let i=f*f*(1-r*r/(d*d));i>0&&(i=Math.sqrt(i)),i=f-i,e.y-(t.y??0)>0&&(i=-i),n.y+=i}return n},s}e(Ce,`cylinder`);async function we(e,t,n){let{labelStyles:r,nodeStyles:i}=y(t);t.labelStyle=r;let{shapeSvg:a,bbox:o}=await C(e,t,E(t)),s=Math.max(o.width+n.labelPaddingX*2,t?.width||0),c=Math.max(o.height+n.labelPaddingY*2,t?.height||0),l=-s/2,u=-c/2,d,{rx:f,ry:m}=t,{cssStyles:h}=t;if(n?.rx&&n.ry&&(f=n.rx,m=n.ry),t.look===`handDrawn`){let e=S.svg(a),n=v(t,{}),r=f||m?e.path(N(l,u,s,c,f||0),n):e.rectangle(l,u,s,c,n);d=a.insert(()=>r,`:first-child`),d.attr(`class`,`basic label-container`).attr(`style`,p(h))}else d=a.insert(`rect`,`:first-child`),d.attr(`class`,`basic label-container`).attr(`style`,i).attr(`rx`,p(f)).attr(`ry`,p(m)).attr(`x`,l).attr(`y`,u).attr(`width`,s).attr(`height`,c);return T(t,d),t.calcIntersect=function(e,t){return G.rect(e,t)},t.intersect=function(e){return G.rect(t,e)},a}e(we,`drawRect`);async function Te(e,t){let{cssClasses:n,labelPaddingX:r,labelPaddingY:i,padding:a,width:o,height:s}=t,c=await we(e,t,{rx:0,ry:0,classes:n??``,labelPaddingX:r??(a??0)*2,labelPaddingY:i??a??0});if(t.look===`handDrawn`){let e=S.svg(c),n=v(t,{}),r=c.select(`.basic.label-container > path:nth-child(2)`),i=r.node();if(!i)return c;let a=null;if(i instanceof SVGGraphicsElement)a=i.getBBox();else return c;return c.insert(()=>e.line(a.x,a.y,a.x+a.width,a.y,n),`.basic.label-container g.label`),c.insert(()=>e.line(a.x,a.y+a.height,a.x+a.width,a.y+a.height,n),`.basic.label-container g.label`),r.remove(),c}let l=c.select(`.basic.label-container`),u=(Number(l.attr(`width`))||o)??0,d=(Number(l.attr(`height`))||s)??0;return u>0&&d>0&&l.attr(`stroke-dasharray`,`${u} ${d}`),c}e(Te,`datastore`);async function Ee(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.look===`neo`?16:t.padding??0,a=t.look===`neo`?16:t.padding??0,{shapeSvg:o,bbox:s,label:c}=await C(e,t,E(t)),l=s.width+i,u=s.height+a,d=u*.2,f=-l/2,p=-u/2-d/2,{cssStyles:m}=t,h=S.svg(o),g=v(t,{});t.look!==`handDrawn`&&(g.roughness=0,g.fillStyle=`solid`);let _=[{x:f,y:p+d},{x:-f,y:p+d},{x:-f,y:-p},{x:f,y:-p},{x:f,y:p},{x:-f,y:p},{x:-f,y:p+d}],b=h.polygon(_.map(e=>[e.x,e.y]),g),x=o.insert(()=>b,`:first-child`);return x.attr(`class`,`basic label-container outer-path`),m&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,m),r&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,r),c.attr(`transform`,`translate(${f+(t.padding??0)/2-(s.x-(s.left??0))}, ${p+d+(t.padding??0)/2-(s.y-(s.top??0))})`),T(t,x),t.intersect=function(e){return G.rect(t,e)},o}e(Ee,`dividedRectangle`);async function De(e,n){let{labelStyles:r,nodeStyles:i}=y(n),a=n.look===`neo`?12:5;n.labelStyle=r;let o=n.padding??0,s=n.look===`neo`?16:o,{shapeSvg:c,bbox:l}=await C(e,n,E(n)),u=(n?.width?n?.width/2:l.width/2)+(s??0),d=u-a,f,{cssStyles:m}=n;if(n.look===`handDrawn`){let e=S.svg(c),t=v(n,{roughness:.2,strokeWidth:2.5}),r=v(n,{roughness:.2,strokeWidth:1.5}),i=e.circle(0,0,u*2,t),a=e.circle(0,0,d*2,r);f=c.insert(`g`,`:first-child`),f.attr(`class`,p(n.cssClasses)).attr(`style`,p(m)),f.node()?.appendChild(i),f.node()?.appendChild(a)}else{f=c.insert(`g`,`:first-child`);let e=f.insert(`circle`,`:first-child`),t=f.insert(`circle`);f.attr(`class`,`basic label-container`).attr(`style`,i),e.attr(`class`,`outer-circle`).attr(`style`,i).attr(`r`,u).attr(`cx`,0).attr(`cy`,0),t.attr(`class`,`inner-circle`).attr(`style`,i).attr(`r`,d).attr(`cx`,0).attr(`cy`,0)}return T(n,f),n.intersect=function(e){return t.info(`DoubleCircle intersect`,n,u,e),G.circle(n,u,e)},c}e(De,`doublecircle`);function Oe(e,n,{config:{themeVariables:r}}){let{labelStyles:i,nodeStyles:a}=y(n);n.label=``,n.labelStyle=i;let o=e.insert(`g`).attr(`class`,E(n)).attr(`id`,n.domId??n.id),{cssStyles:s}=n,c=S.svg(o),{nodeBorder:l}=r,u=v(n,{fillStyle:`solid`});n.look!==`handDrawn`&&(u.roughness=0);let d=c.circle(0,0,14,u),f=o.insert(()=>d,`:first-child`);return f.selectAll(`path`).attr(`style`,`fill: ${l} !important;`),s&&s.length>0&&n.look!==`handDrawn`&&f.selectAll(`path`).attr(`style`,s),a&&n.look!==`handDrawn`&&f.selectAll(`path`).attr(`style`,a),T(n,f),n.intersect=function(e){return t.info(`filledCircle intersect`,n,{radius:7,point:e}),G.circle(n,7,e)},o}e(Oe,`filledCircle`);var ke=10,Ae=10;async function je(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let a=n.padding??0,o=n.look===`neo`?a*2:a;(n.width||n.height)&&(n.height=n?.height??0,n.heightb,`:first-child`).attr(`transform`,`translate(${-d/2}, ${d/2})`).attr(`class`,`outer-path`);return m&&n.look!==`handDrawn`&&x.selectChildren(`path`).attr(`style`,m),i&&n.look!==`handDrawn`&&x.selectChildren(`path`).attr(`style`,i),n.width=u,n.height=d,T(n,x),l.attr(`transform`,`translate(${-c.width/2-(c.x-(c.left??0))}, ${-d/2+(n.padding??0)/2+(c.y-(c.top??0))})`),n.intersect=function(e){return t.info(`Triangle intersect`,n,p,e),G.polygon(n,p,e)},s}e(je,`flippedTriangle`);function Me(e,t,{dir:n,config:{state:r,themeVariables:i}}){let{nodeStyles:a}=y(t);t.label=``;let o=e.insert(`g`).attr(`class`,E(t)).attr(`id`,t.domId??t.id),{cssStyles:s}=t,c=Math.max(70,t?.width??0),l=Math.max(10,t?.height??0);n===`LR`&&(c=Math.max(10,t?.width??0),l=Math.max(70,t?.height??0));let u=-1*c/2,d=-1*l/2,f=S.svg(o),p=v(t,{stroke:i.lineColor,fill:i.lineColor});t.look!==`handDrawn`&&(p.roughness=0,p.fillStyle=`solid`);let m=f.rectangle(u,d,c,l,p),h=o.insert(()=>m,`:first-child`);s&&t.look!==`handDrawn`&&h.selectAll(`path`).attr(`style`,s),a&&t.look!==`handDrawn`&&h.selectAll(`path`).attr(`style`,a),T(t,h);let g=r?.padding??0;return t.width&&t.height&&(t.width+=g/2||0,t.height+=g/2||0),t.intersect=function(e){return G.rect(t,e)},o}e(Me,`forkJoin`);async function Ne(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let a=n.look===`neo`?16:n.padding??0,o=n.look===`neo`?12:n.padding??0;(n.width||n.height)&&(n.height=(n?.height??0)-o*2,n.height<10&&(n.height=10),n.width=(n?.width??0)-a*2,n.width<15&&(n.width=15));let{shapeSvg:s,bbox:c}=await C(e,n,E(n)),l=(n?.width?n?.width:Math.max(15,c.width))+a*2,u=(n?.height?n?.height:Math.max(10,c.height))+o*2,d=u/2,{cssStyles:f}=n,p=S.svg(s),m=v(n,{});n.look!==`handDrawn`&&(m.roughness=0,m.fillStyle=`solid`);let h=[{x:-l/2,y:-u/2},{x:l/2-d,y:-u/2},...k(-l/2+d,0,d,50,90,270),{x:l/2-d,y:u/2},{x:-l/2,y:u/2}],g=D(h),_=p.path(g,m),b=s.insert(()=>_,`:first-child`);return b.attr(`class`,`basic label-container outer-path`),f&&n.look!==`handDrawn`&&b.selectChildren(`path`).attr(`style`,f),i&&n.look!==`handDrawn`&&b.selectChildren(`path`).attr(`style`,i),T(n,b),n.intersect=function(e){return t.info(`Pill intersect`,n,{radius:d,point:e}),G.polygon(n,h,e)},s}e(Ne,`halfRoundedRectangle`);var Pe=e((e,t,n,r,i)=>[`M${e+i},${t}`,`L${e+n-i},${t}`,`L${e+n},${t-r/2}`,`L${e+n-i},${t-r}`,`L${e+i},${t-r}`,`L${e},${t-r/2}`,`Z`].join(` `),`createHexagonPathD`);async function Fe(e,t){let{labelStyles:n,nodeStyles:r}=y(t),i=t.look===`neo`?3.5:4;t.labelStyle=n;let a=t.padding??0,o=t.look===`neo`?70:a,s=t.look===`neo`?32:a;if(t.width||t.height){let e=(t.height??0)/i;t.width=(t?.width??0)-2*e-s,t.height=(t.height??0)-o}let{shapeSvg:c,bbox:l}=await C(e,t,E(t)),u=(t?.height?t?.height:l.height)+o,d=u/i,f=(t?.width?t?.width:l.width)+2*d+s,p=[{x:d,y:0},{x:f-d,y:0},{x:f,y:-u/2},{x:f-d,y:-u},{x:d,y:-u},{x:0,y:-u/2}],m,{cssStyles:h}=t;if(t.look===`handDrawn`){let e=S.svg(c),n=v(t,{}),r=Pe(0,0,f,u,d),i=e.path(r,n);m=c.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-f/2}, ${u/2})`),h&&m.attr(`style`,h)}else m=q(c,f,u,p);return r&&m.attr(`style`,r),t.width=f,t.height=u,T(t,m),t.intersect=function(e){return G.polygon(t,p,e)},c}e(Fe,`hexagon`);async function Ie(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.label=``,n.labelStyle=r;let{shapeSvg:a}=await C(e,n,E(n)),o=Math.max(30,n?.width??0),s=Math.max(30,n?.height??0),{cssStyles:c}=n,l=S.svg(a),u=v(n,{});n.look!==`handDrawn`&&(u.roughness=0,u.fillStyle=`solid`);let d=[{x:0,y:0},{x:o,y:0},{x:0,y:s},{x:o,y:s}],f=D(d),p=l.path(f,u),m=a.insert(()=>p,`:first-child`);return m.attr(`class`,`basic label-container outer-path`),c&&n.look!==`handDrawn`&&m.selectChildren(`path`).attr(`style`,c),i&&n.look!==`handDrawn`&&m.selectChildren(`path`).attr(`style`,i),m.attr(`transform`,`translate(${-o/2}, ${-s/2})`),T(n,m),n.intersect=function(e){return t.info(`Pill intersect`,n,{points:d}),G.polygon(n,d,e)},a}e(Ie,`hourglass`);async function Le(e,n,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:a}=y(n);n.labelStyle=a;let o=n.assetHeight??48,s=n.assetWidth??48,c=Math.max(o,s),l=i?.wrappingWidth;n.width=Math.max(c,l??0);let{shapeSvg:u,bbox:d,label:f}=await C(e,n,`icon-shape default`),p=n.pos===`t`,h=c,g=c,{nodeBorder:_}=r,{stylesMap:b}=x(n),w=-g/2,E=-h/2,D=n.label?8:0,O=S.svg(u),k=v(n,{stroke:`none`,fill:`none`});n.look!==`handDrawn`&&(k.roughness=0,k.fillStyle=`solid`);let A=O.rectangle(w,E,g,h,k),j=Math.max(g,d.width),M=h+d.height+D,N=O.rectangle(-j/2,-M/2,j,M,{...k,fill:`transparent`,stroke:`none`}),P=u.insert(()=>A,`:first-child`),F=u.insert(()=>N);if(n.icon){let e=u.append(`g`);e.html(`${await m(n.icon,{height:c,width:c,fallbackPrefix:``})}`);let t=e.node().getBBox(),r=t.width,i=t.height,a=t.x,o=t.y;e.attr(`transform`,`translate(${-r/2-a},${p?d.height/2+D/2-i/2-o:-d.height/2-D/2-i/2-o})`),e.attr(`style`,`color: ${b.get(`stroke`)??_};`)}return f.attr(`transform`,`translate(${-d.width/2-(d.x-(d.left??0))},${p?-M/2:M/2-d.height})`),P.attr(`transform`,`translate(0,${p?d.height/2+D/2:-d.height/2-D/2})`),T(n,F),n.intersect=function(e){if(t.info(`iconSquare intersect`,n,e),!n.label)return G.rect(n,e);let r=n.x??0,i=n.y??0,a=n.height??0,o=[];return o=p?[{x:r-d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2+d.height+D},{x:r+g/2,y:i-a/2+d.height+D},{x:r+g/2,y:i+a/2},{x:r-g/2,y:i+a/2},{x:r-g/2,y:i-a/2+d.height+D},{x:r-d.width/2,y:i-a/2+d.height+D}]:[{x:r-g/2,y:i-a/2},{x:r+g/2,y:i-a/2},{x:r+g/2,y:i-a/2+h},{x:r+d.width/2,y:i-a/2+h},{x:r+d.width/2/2,y:i+a/2},{x:r-d.width/2,y:i+a/2},{x:r-d.width/2,y:i-a/2+h},{x:r-g/2,y:i-a/2+h}],G.polygon(n,o,e)},u}e(Le,`icon`);async function Re(e,n,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:a}=y(n);n.labelStyle=a;let o=n.assetHeight??48,s=n.assetWidth??48,c=Math.max(o,s),l=i?.wrappingWidth;n.width=Math.max(c,l??0);let{shapeSvg:u,bbox:d,label:f}=await C(e,n,`icon-shape default`),p=n.label?8:0,h=n.pos===`t`,{nodeBorder:g,mainBkg:_}=r,{stylesMap:b}=x(n),w=S.svg(u),E=v(n,{});n.look!==`handDrawn`&&(E.roughness=0,E.fillStyle=`solid`),E.stroke=b.get(`fill`)??_;let D=u.append(`g`);n.icon&&D.html(`${await m(n.icon,{height:c,width:c,fallbackPrefix:``})}`);let O=D.node().getBBox(),k=O.width,A=O.height,j=O.x,M=O.y,N=Math.max(k,A)*Math.SQRT2+40,P=w.circle(0,0,N,E),F=Math.max(N,d.width),I=N+d.height+p,L=w.rectangle(-F/2,-I/2,F,I,{...E,fill:`transparent`,stroke:`none`}),ee=u.insert(()=>P,`:first-child`),R=u.insert(()=>L);return D.attr(`transform`,`translate(${-k/2-j},${h?d.height/2+p/2-A/2-M:-d.height/2-p/2-A/2-M})`),D.attr(`style`,`color: ${b.get(`stroke`)??g};`),f.attr(`transform`,`translate(${-d.width/2-(d.x-(d.left??0))},${h?-I/2:I/2-d.height})`),ee.attr(`transform`,`translate(0,${h?d.height/2+p/2:-d.height/2-p/2})`),T(n,R),n.intersect=function(e){return t.info(`iconSquare intersect`,n,e),G.rect(n,e)},u}e(Re,`iconCircle`);async function ze(e,n,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:a}=y(n);n.labelStyle=a;let o=n.assetHeight??48,s=n.assetWidth??48,c=Math.max(o,s),l=i?.wrappingWidth;n.width=Math.max(c,l??0);let{shapeSvg:u,bbox:d,halfPadding:f,label:p}=await C(e,n,`icon-shape default`),h=n.pos===`t`,g=c+f*2,_=c+f*2,{nodeBorder:b,mainBkg:w}=r,{stylesMap:E}=x(n),D=-_/2,O=-g/2,k=n.label?8:0,A=S.svg(u),j=v(n,{});n.look!==`handDrawn`&&(j.roughness=0,j.fillStyle=`solid`),j.stroke=E.get(`fill`)??w;let M=A.path(N(D,O,_,g,5),j),P=Math.max(_,d.width),F=g+d.height+k,I=A.rectangle(-P/2,-F/2,P,F,{...j,fill:`transparent`,stroke:`none`}),L=u.insert(()=>M,`:first-child`).attr(`class`,`icon-shape2`),ee=u.insert(()=>I);if(n.icon){let e=u.append(`g`);e.html(`${await m(n.icon,{height:c,width:c,fallbackPrefix:``})}`);let t=e.node().getBBox(),r=t.width,i=t.height,a=t.x,o=t.y;e.attr(`transform`,`translate(${-r/2-a},${h?d.height/2+k/2-i/2-o:-d.height/2-k/2-i/2-o})`),e.attr(`style`,`color: ${E.get(`stroke`)??b};`)}return p.attr(`transform`,`translate(${-d.width/2-(d.x-(d.left??0))},${h?-F/2:F/2-d.height})`),L.attr(`transform`,`translate(0,${h?d.height/2+k/2:-d.height/2-k/2})`),T(n,ee),n.intersect=function(e){if(t.info(`iconSquare intersect`,n,e),!n.label)return G.rect(n,e);let r=n.x??0,i=n.y??0,a=n.height??0,o=[];return o=h?[{x:r-d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2+d.height+k},{x:r+_/2,y:i-a/2+d.height+k},{x:r+_/2,y:i+a/2},{x:r-_/2,y:i+a/2},{x:r-_/2,y:i-a/2+d.height+k},{x:r-d.width/2,y:i-a/2+d.height+k}]:[{x:r-_/2,y:i-a/2},{x:r+_/2,y:i-a/2},{x:r+_/2,y:i-a/2+g},{x:r+d.width/2,y:i-a/2+g},{x:r+d.width/2/2,y:i+a/2},{x:r-d.width/2,y:i+a/2},{x:r-d.width/2,y:i-a/2+g},{x:r-_/2,y:i-a/2+g}],G.polygon(n,o,e)},u}e(ze,`iconRounded`);async function Be(e,n,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:a}=y(n);n.labelStyle=a;let o=n.assetHeight??48,s=n.assetWidth??48,c=Math.max(o,s),l=i?.wrappingWidth;n.width=Math.max(c,l??0);let{shapeSvg:u,bbox:d,halfPadding:f,label:p}=await C(e,n,`icon-shape default`),h=n.pos===`t`,g=c+f*2,_=c+f*2,{nodeBorder:b,mainBkg:w}=r,{stylesMap:E}=x(n),D=-_/2,O=-g/2,k=n.label?8:0,A=S.svg(u),j=v(n,{});n.look!==`handDrawn`&&(j.roughness=0,j.fillStyle=`solid`),j.stroke=E.get(`fill`)??w;let M=A.path(N(D,O,_,g,.1),j),P=Math.max(_,d.width),F=g+d.height+k,I=A.rectangle(-P/2,-F/2,P,F,{...j,fill:`transparent`,stroke:`none`}),L=u.insert(()=>M,`:first-child`),ee=u.insert(()=>I);if(n.icon){let e=u.append(`g`);e.html(`${await m(n.icon,{height:c,width:c,fallbackPrefix:``})}`);let t=e.node().getBBox(),r=t.width,i=t.height,a=t.x,o=t.y;e.attr(`transform`,`translate(${-r/2-a},${h?d.height/2+k/2-i/2-o:-d.height/2-k/2-i/2-o})`),e.attr(`style`,`color: ${E.get(`stroke`)??b};`)}return p.attr(`transform`,`translate(${-d.width/2-(d.x-(d.left??0))},${h?-F/2:F/2-d.height})`),L.attr(`transform`,`translate(0,${h?d.height/2+k/2:-d.height/2-k/2})`),T(n,ee),n.intersect=function(e){if(t.info(`iconSquare intersect`,n,e),!n.label)return G.rect(n,e);let r=n.x??0,i=n.y??0,a=n.height??0,o=[];return o=h?[{x:r-d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2+d.height+k},{x:r+_/2,y:i-a/2+d.height+k},{x:r+_/2,y:i+a/2},{x:r-_/2,y:i+a/2},{x:r-_/2,y:i-a/2+d.height+k},{x:r-d.width/2,y:i-a/2+d.height+k}]:[{x:r-_/2,y:i-a/2},{x:r+_/2,y:i-a/2},{x:r+_/2,y:i-a/2+g},{x:r+d.width/2,y:i-a/2+g},{x:r+d.width/2/2,y:i+a/2},{x:r-d.width/2,y:i+a/2},{x:r-d.width/2,y:i-a/2+g},{x:r-_/2,y:i-a/2+g}],G.polygon(n,o,e)},u}e(Be,`iconSquare`);async function Ve(e,n,{config:{flowchart:r}}){let i=new Image;i.src=n?.img??``,await i.decode();let a=Number(i.naturalWidth.toString().replace(`px`,``)),o=Number(i.naturalHeight.toString().replace(`px`,``));n.imageAspectRatio=a/o;let{labelStyles:s}=y(n);n.labelStyle=s;let c=r?.wrappingWidth;n.defaultWidth=r?.wrappingWidth;let l=Math.max(n.label?c??0:0,n?.assetWidth??a),u=n.constraint===`on`&&n?.assetHeight?n.assetHeight*n.imageAspectRatio:l,d=n.constraint===`on`?u/n.imageAspectRatio:n?.assetHeight??o;n.width=Math.max(u,c??0);let{shapeSvg:f,bbox:p,label:m}=await C(e,n,`image-shape default`),h=n.pos===`t`,g=-u/2,_=-d/2,b=n.label?8:0,x=S.svg(f),w=v(n,{});n.look!==`handDrawn`&&(w.roughness=0,w.fillStyle=`solid`);let E=x.rectangle(g,_,u,d,w),D=Math.max(u,p.width),O=d+p.height+b,k=x.rectangle(-D/2,-O/2,D,O,{...w,fill:`none`,stroke:`none`}),A=f.insert(()=>E,`:first-child`),j=f.insert(()=>k);if(n.img){let e=f.append(`image`);e.attr(`href`,n.img),e.attr(`width`,u),e.attr(`height`,d),e.attr(`preserveAspectRatio`,`none`),e.attr(`transform`,`translate(${-u/2},${h?O/2-d:-O/2})`)}return m.attr(`transform`,`translate(${-p.width/2-(p.x-(p.left??0))},${h?-d/2-p.height/2-b/2:d/2-p.height/2+b/2})`),A.attr(`transform`,`translate(0,${h?p.height/2+b/2:-p.height/2-b/2})`),T(n,j),n.intersect=function(e){if(t.info(`iconSquare intersect`,n,e),!n.label)return G.rect(n,e);let r=n.x??0,i=n.y??0,a=n.height??0,o=[];return o=h?[{x:r-p.width/2,y:i-a/2},{x:r+p.width/2,y:i-a/2},{x:r+p.width/2,y:i-a/2+p.height+b},{x:r+u/2,y:i-a/2+p.height+b},{x:r+u/2,y:i+a/2},{x:r-u/2,y:i+a/2},{x:r-u/2,y:i-a/2+p.height+b},{x:r-p.width/2,y:i-a/2+p.height+b}]:[{x:r-u/2,y:i-a/2},{x:r+u/2,y:i-a/2},{x:r+u/2,y:i-a/2+d},{x:r+p.width/2,y:i-a/2+d},{x:r+p.width/2/2,y:i+a/2},{x:r-p.width/2,y:i+a/2},{x:r-p.width/2,y:i-a/2+d},{x:r-u/2,y:i-a/2+d}],G.polygon(n,o,e)},f}e(Ve,`imageSquare`);async function He(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=i,o=t.look===`neo`?i*2:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=Math.max(c.width+(o??0)*2,t?.width??0),u=Math.max(c.height+(a??0)*2,t?.height??0),d=[{x:0,y:0},{x:l,y:0},{x:l+3*u/6,y:-u},{x:-3*u/6,y:-u}],f,{cssStyles:p}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(d),i=e.path(r,n);f=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-l/2}, ${u/2})`),p&&f.attr(`style`,p)}else f=q(s,l,u,d);return r&&f.attr(`style`,r),t.width=l,t.height=u,T(t,f),t.intersect=function(e){return G.polygon(t,d,e)},s}e(He,`inv_trapezoid`);async function Ue(e,t){let{shapeSvg:n,bbox:r,label:i}=await C(e,t,`label`),a=n.insert(`rect`,`:first-child`);return a.attr(`width`,.1).attr(`height`,.1),n.attr(`class`,`label edgeLabel`),i.attr(`transform`,`translate(${-(r.width/2)-(r.x-(r.left??0))}, ${-(r.height/2)-(r.y-(r.top??0))})`),T(t,a),t.intersect=function(e){return G.rect(t,e)},n}e(Ue,`labelRect`);async function We(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=i,o=t.look===`neo`?i*2:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.height??c.height)+a,u=(t?.width??c.width)+o,d=[{x:0,y:0},{x:u+3*l/6,y:0},{x:u,y:-l},{x:-(3*l)/6,y:-l}],f,{cssStyles:p}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(d),i=e.path(r,n);f=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-u/2}, ${l/2})`),p&&f.attr(`style`,p)}else f=q(s,u,l,d);return r&&f.attr(`style`,r),t.width=u,t.height=l,T(t,f),t.intersect=function(e){return G.polygon(t,d,e)},s}e(We,`lean_left`);async function Ge(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=i,o=t.look===`neo`?i*2:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.height??c.height)+a,u=(t?.width??c.width)+o,d=[{x:-3*l/6,y:0},{x:u,y:0},{x:u+3*l/6,y:-l},{x:0,y:-l}],f,{cssStyles:p}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(d),i=e.path(r,n);f=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-u/2}, ${l/2})`),p&&f.attr(`style`,p)}else f=q(s,u,l,d);return r&&f.attr(`style`,r),t.width=u,t.height=l,T(t,f),t.intersect=function(e){return G.polygon(t,d,e)},s}e(Ge,`lean_right`);function Ke(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.label=``,n.labelStyle=r;let a=e.insert(`g`).attr(`class`,E(n)).attr(`id`,n.domId??n.id),{cssStyles:o}=n,s=Math.max(35,n?.width??0),c=Math.max(35,n?.height??0),l=[{x:s,y:0},{x:0,y:c+7/2},{x:s-14,y:c+7/2},{x:0,y:2*c},{x:s,y:c-7/2},{x:14,y:c-7/2}],u=S.svg(a),d=v(n,{});n.look!==`handDrawn`&&(d.roughness=0,d.fillStyle=`solid`);let f=D(l),p=u.path(f,d),m=a.insert(()=>p,`:first-child`);return m.attr(`class`,`outer-path`),o&&n.look!==`handDrawn`&&m.selectAll(`path`).attr(`style`,o),i&&n.look!==`handDrawn`&&m.selectAll(`path`).attr(`style`,i),m.attr(`transform`,`translate(-${s/2},${-c})`),T(n,m),n.intersect=function(e){return t.info(`lightningBolt intersect`,n,e),G.polygon(n,l,e)},a}e(Ke,`lightningBolt`);var qe=e((e,t,n,r,i,a,o)=>[`M${e},${t+a}`,`a${i},${a} 0,0,0 ${n},0`,`a${i},${a} 0,0,0 ${-n},0`,`l0,${r}`,`a${i},${a} 0,0,0 ${n},0`,`l0,${-r}`,`M${e},${t+a+o}`,`a${i},${a} 0,0,0 ${n},0`].join(` `),`createCylinderPathD`),Je=e((e,t,n,r,i,a,o)=>[`M${e},${t+a}`,`M${e+n},${t+a}`,`a${i},${a} 0,0,0 ${-n},0`,`l0,${r}`,`a${i},${a} 0,0,0 ${n},0`,`l0,${-r}`,`M${e},${t+a+o}`,`a${i},${a} 0,0,0 ${n},0`].join(` `),`createOuterCylinderPathD`),Ye=e((e,t,n,r,i,a)=>[`M${e-n/2},${-r/2}`,`a${i},${a} 0,0,0 ${n},0`].join(` `),`createInnerCylinderPathD`),Xe=10,Ze=10;async function Qe(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?24:i;if(t.width||t.height){let e=t.width??0;t.width=(t.width??0)-a,t.widtho,`:first-child`).attr(`class`,`line`),g=s.insert(()=>a,`:first-child`),g.attr(`class`,`basic label-container`),_&&g.attr(`style`,_)}else{let e=qe(0,0,u,m,d,f,h);g=s.insert(`path`,`:first-child`).attr(`d`,e).attr(`class`,`basic label-container outer-path`).attr(`style`,p(_)).attr(`style`,r)}return g.attr(`label-offset-y`,f),g.attr(`transform`,`translate(${-u/2}, ${-(m/2+f)})`),T(t,g),l.attr(`transform`,`translate(${-(c.width/2)-(c.x-(c.left??0))}, ${-(c.height/2)+f-(c.y-(c.top??0))})`),t.intersect=function(e){let n=G.rect(t,e),r=n.x-(t.x??0);if(d!=0&&(Math.abs(r)<(t.width??0)/2||Math.abs(r)==(t.width??0)/2&&Math.abs(n.y-(t.y??0))>(t.height??0)/2-f)){let i=f*f*(1-r*r/(d*d));i>0&&(i=Math.sqrt(i)),i=f-i,e.y-(t.y??0)>0&&(i=-i),n.y+=i}return n},s}e(Qe,`linedCylinder`);async function $e(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i;(t.width||t.height)&&(t.width=(t.width??0)*10/11-a*2,t.width<10&&(t.width=10),t.height=(t?.height??0)-o*2,t.height<10&&(t.height=10));let{shapeSvg:s,bbox:c,label:l}=await C(e,t,E(t)),u=(t?.width?t?.width:c.width)+(a??0)*2,d=(t?.height?t?.height:c.height)+(o??0)*2,f=t.look===`neo`?d/4:d/8,p=d+f,{cssStyles:m}=t,h=S.svg(s),g=v(t,{});t.look!==`handDrawn`&&(g.roughness=0,g.fillStyle=`solid`);let _=[{x:-u/2-u/2*.1,y:-p/2},{x:-u/2-u/2*.1,y:p/2},...O(-u/2-u/2*.1,p/2,u/2+u/2*.1,p/2,f,.8),{x:u/2+u/2*.1,y:-p/2},{x:-u/2-u/2*.1,y:-p/2},{x:-u/2,y:-p/2},{x:-u/2,y:p/2*1.1},{x:-u/2,y:-p/2}],b=h.polygon(_.map(e=>[e.x,e.y]),g),x=s.insert(()=>b,`:first-child`);return x.attr(`class`,`basic label-container outer-path`),m&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,m),r&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,r),x.attr(`transform`,`translate(0,${-f/2})`),l.attr(`transform`,`translate(${-u/2+(t.padding??0)+u/2*.1/2-(c.x-(c.left??0))},${-d/2+(t.padding??0)-f/2-(c.y-(c.top??0))})`),T(t,x),t.intersect=function(e){return G.polygon(t,_,e)},s}e($e,`linedWaveEdgedRect`);async function et(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i,s=t.look===`neo`?10:5;(t.width||t.height)&&(t.width=Math.max((t?.width??0)-a*2-2*s,10),t.height=Math.max((t?.height??0)-o*2-2*s,10));let{shapeSvg:c,bbox:l,label:u}=await C(e,t,E(t)),d=(t?.width?t?.width:l.width)+a*2+2*s,f=(t?.height?t?.height:l.height)+o*2+2*s,p=d-2*s,m=f-2*s,h=-p/2,g=-m/2,{cssStyles:_}=t,b=S.svg(c),x=v(t,{}),w=[{x:h-s,y:g+s},{x:h-s,y:g+m+s},{x:h+p-s,y:g+m+s},{x:h+p-s,y:g+m},{x:h+p,y:g+m},{x:h+p,y:g+m-s},{x:h+p+s,y:g+m-s},{x:h+p+s,y:g-s},{x:h+s,y:g-s},{x:h+s,y:g},{x:h,y:g},{x:h,y:g+s}],O=[{x:h,y:g+s},{x:h+p-s,y:g+s},{x:h+p-s,y:g+m},{x:h+p,y:g+m},{x:h+p,y:g},{x:h,y:g}];t.look!==`handDrawn`&&(x.roughness=0,x.fillStyle=`solid`);let k=D(w),j=b.path(k,x),M=D(O),N=b.path(M,x);t.look!==`handDrawn`&&(j=A(j),N=A(N));let P=c.insert(`g`,`:first-child`);return P.insert(()=>j),P.insert(()=>N),P.attr(`class`,`basic label-container outer-path`),_&&t.look!==`handDrawn`&&P.selectAll(`path`).attr(`style`,_),r&&t.look!==`handDrawn`&&P.selectAll(`path`).attr(`style`,r),u.attr(`transform`,`translate(${-(l.width/2)-s-(l.x-(l.left??0))}, ${-(l.height/2)+s-(l.y-(l.top??0))})`),T(t,P),t.intersect=function(e){return G.polygon(t,w,e)},c}e(et,`multiRect`);async function tt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let{shapeSvg:i,bbox:a,label:o}=await C(e,t,E(t)),s=t.padding??0,c=t.look===`neo`?16:s,l=t.look===`neo`?12:s,u=!0;(t.width||t.height)&&(u=!1,t.width=(t?.width??0)-c*2,t.height=(t?.height??0)-l*3);let d=Math.max(a.width,t?.width??0)+c*2,f=Math.max(a.height,t?.height??0)+l*3,p=t.look===`neo`?f/4:f/8,m=f+(u?p/2:-p/2),h=-d/2,g=-m/2,{cssStyles:_}=t,b=O(h-10,g+m+10,h+d-10,g+m+10,p,.8),x=b?.[b.length-1],w=[{x:h-10,y:g+10},{x:h-10,y:g+m+10},...b,{x:h+d-10,y:x.y-10},{x:h+d,y:x.y-10},{x:h+d,y:x.y-20},{x:h+d+10,y:x.y-20},{x:h+d+10,y:g-10},{x:h+10,y:g-10},{x:h+10,y:g},{x:h,y:g},{x:h,y:g+10}],k=[{x:h,y:g+10},{x:h+d-10,y:g+10},{x:h+d-10,y:x.y-10},{x:h+d,y:x.y-10},{x:h+d,y:g},{x:h,y:g}],A=S.svg(i),j=v(t,{});t.look!==`handDrawn`&&(j.roughness=0,j.fillStyle=`solid`);let M=D(w),N=A.path(M,j),P=D(k),F=A.path(P,j),I=i.insert(()=>N,`:first-child`);return I.insert(()=>F),I.attr(`class`,`basic label-container outer-path`),_&&t.look!==`handDrawn`&&I.selectAll(`path`).attr(`style`,_),r&&t.look!==`handDrawn`&&I.selectAll(`path`).attr(`style`,r),I.attr(`transform`,`translate(0,${-p/2})`),o.attr(`transform`,`translate(${-(a.width/2)-10-(a.x-(a.left??0))}, ${-(a.height/2)+10-p/2-(a.y-(a.top??0))})`),T(t,I),t.intersect=function(e){return G.polygon(t,w,e)},i}e(tt,`multiWaveEdgedRectangle`);async function nt(e,t,{config:{themeVariables:n}}){let{labelStyles:r,nodeStyles:i}=y(t);t.labelStyle=r,t.useHtmlLabels||o(s())||(t.centerLabel=!0);let{shapeSvg:a,bbox:c,label:l}=await C(e,t,E(t)),u=Math.max(c.width+(t.padding??0)*2,t?.width??0),d=Math.max(c.height+(t.padding??0)*2,t?.height??0),f=-u/2,p=-d/2,{cssStyles:m}=t,h=S.svg(a),g=v(t,{fill:n.noteBkgColor,stroke:n.noteBorderColor});t.look!==`handDrawn`&&(g.roughness=0,g.fillStyle=`solid`);let _=h.rectangle(f,p,u,d,g),b=a.insert(()=>_,`:first-child`);return b.attr(`class`,`basic label-container outer-path`),l.attr(`class`,`label noteLabel`),m&&t.look!==`handDrawn`&&b.selectAll(`path`).attr(`style`,m),i&&t.look!==`handDrawn`&&b.selectAll(`path`).attr(`style`,i),l.attr(`transform`,`translate(${-c.width/2-(c.x-(c.left??0))}, ${-(c.height/2)-(c.y-(c.top??0))})`),T(t,b),t.intersect=function(e){return G.rect(t,e)},a}e(nt,`note`);var rt=e((e,t,n)=>[`M${e+n/2},${t}`,`L${e+n},${t-n/2}`,`L${e+n/2},${t-n}`,`L${e},${t-n/2}`,`Z`].join(` `),`createDecisionBoxPathD`);async function it(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let{shapeSvg:i,bbox:a}=await C(e,t,E(t)),o=a.width+(t.padding??0)+(a.height+(t.padding??0)),s=.5,c=[{x:o/2,y:0},{x:o,y:-o/2},{x:o/2,y:-o},{x:0,y:-o/2}],l,{cssStyles:u}=t;if(t.look===`handDrawn`){let e=S.svg(i),n=v(t,{}),r=rt(0,0,o),a=e.path(r,n);l=i.insert(()=>a,`:first-child`).attr(`transform`,`translate(${-o/2+s}, ${o/2})`),u&&l.attr(`style`,u)}else l=q(i,o,o,c),l.attr(`transform`,`translate(${-o/2+s}, ${o/2})`);return r&&l.attr(`style`,r),T(t,l),t.calcIntersect=function(e,t){let n=e.width,r=[{x:n/2,y:0},{x:n,y:-n/2},{x:n/2,y:-n},{x:0,y:-n/2}],i=G.polygon(e,r,t);return{x:i.x-.5,y:i.y-.5}},t.intersect=function(e){return this.calcIntersect(t,e)},i}e(it,`question`);async function at(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?21:i??0,o=t.look===`neo`?12:i??0,{shapeSvg:s,bbox:c,label:l}=await C(e,t,E(t)),u=(t?.width??c.width)+(t.look===`neo`?a*2:a),d=(t?.height??c.height)+(t.look===`neo`?o*2:o),f=-u/2,p=-d/2,m=p/2,h=[{x:f+m,y:p},{x:f,y:0},{x:f+m,y:-p},{x:-f,y:-p},{x:-f,y:p}],{cssStyles:g}=t,_=S.svg(s),b=v(t,{});t.look!==`handDrawn`&&(b.roughness=0,b.fillStyle=`solid`);let x=D(h),w=_.path(x,b),O=s.insert(()=>w,`:first-child`);return O.attr(`class`,`basic label-container outer-path`),g&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,g),r&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,r),O.attr(`transform`,`translate(${-m/2},0)`),l.attr(`transform`,`translate(${-m/2-c.width/2-(c.x-(c.left??0))}, ${-(c.height/2)-(c.y-(c.top??0))})`),T(t,O),t.intersect=function(e){return G.polygon(t,h,e)},s}e(at,`rect_left_inv_arrow`);async function ot(e,r){let{labelStyles:i,nodeStyles:a}=y(r);r.labelStyle=i;let s;s=r.cssClasses?`node `+r.cssClasses:`node default`;let c=e.insert(`g`).attr(`class`,s).attr(`id`,r.domId||r.id),u=c.insert(`g`),d=c.insert(`g`).attr(`class`,`label`).attr(`style`,a),f=r.description,p=r.label,m=await M(d,p,r.labelStyle,!0,!0),h={width:0,height:0};if(o(l())){let e=m.children[0],t=n(m);h=e.getBoundingClientRect(),t.attr(`width`,h.width),t.attr(`height`,h.height)}t.info(`Text 2`,f);let g=f||[],_=m.getBBox(),b=await M(d,Array.isArray(g)?g.join(`
`):g,r.labelStyle,!0,!0),x=b.children[0],C=n(b);h=x.getBoundingClientRect(),C.attr(`width`,h.width),C.attr(`height`,h.height);let w=(r.padding||0)/2;n(b).attr(`transform`,`translate( `+(h.width>_.width?0:(_.width-h.width)/2)+`, `+(_.height+w+5)+`)`),n(m).attr(`transform`,`translate( `+(h.width<_.width?0:-(_.width-h.width)/2)+`, 0)`),h=d.node().getBBox(),d.attr(`transform`,`translate(`+-h.width/2+`, `+(-h.height/2-w+3)+`)`);let E=h.width+(r.padding||0),D=h.height+(r.padding||0),O=-h.width/2-w,k=-h.height/2-w,A,j;if(r.look===`handDrawn`){let e=S.svg(c),n=v(r,{}),i=e.path(N(O,k,E,D,r.rx||0),n),a=e.line(-h.width/2-w,-h.height/2-w+_.height+w,h.width/2+w,-h.height/2-w+_.height+w,n);j=c.insert(()=>(t.debug(`Rough node insert CXC`,i),a),`:first-child`),A=c.insert(()=>(t.debug(`Rough node insert CXC`,i),i),`:first-child`)}else A=u.insert(`rect`,`:first-child`),j=u.insert(`line`),A.attr(`class`,`outer title-state`).attr(`style`,a).attr(`x`,-h.width/2-w).attr(`y`,-h.height/2-w).attr(`width`,h.width+(r.padding||0)).attr(`height`,h.height+(r.padding||0)),j.attr(`class`,`divider`).attr(`x1`,-h.width/2-w).attr(`x2`,h.width/2+w).attr(`y1`,-h.height/2-w+_.height+w).attr(`y2`,-h.height/2-w+_.height+w);return T(r,A),r.intersect=function(e){return G.rect(r,e)},c}e(ot,`rectWithTitle`);async function st(e,t,{config:{themeVariables:n}}){let r=n?.radius??5;return we(e,t,{rx:r,ry:r,classes:``,labelPaddingX:(t?.padding??0)*1,labelPaddingY:(t?.padding??0)*1})}e(st,`roundedRect`);var Z=8;async function ct(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.look===`neo`?16:t.padding??0,a=t.look===`neo`?12:t.padding??0,{shapeSvg:o,bbox:s,label:c}=await C(e,t,E(t)),l=(t?.width??s.width)+i*2+(t.look===`neo`?Z:Z*2),u=(t?.height??s.height)+a*2,d=l-Z,f=u,m=Z-l/2,h=-u/2,{cssStyles:g}=t,_=S.svg(o),b=v(t,{});t.look!==`handDrawn`&&(b.roughness=0,b.fillStyle=`solid`);let x=[{x:m,y:h},{x:m+d,y:h},{x:m+d,y:h+f},{x:m-Z,y:h+f},{x:m-Z,y:h},{x:m,y:h},{x:m,y:h+f}],w=_.polygon(x.map(e=>[e.x,e.y]),b),D=o.insert(()=>w,`:first-child`);return D.attr(`class`,`basic label-container outer-path`).attr(`style`,p(g)),r&&t.look!==`handDrawn`&&D.selectAll(`path`).attr(`style`,r),g&&t.look!==`handDrawn`&&D.selectAll(`path`).attr(`style`,r),c.attr(`transform`,`translate(${Z/2-s.width/2-(s.x-(s.left??0))}, ${-(s.height/2)-(s.y-(s.top??0))})`),T(t,D),t.intersect=function(e){return G.rect(t,e)},o}e(ct,`shadedProcess`);async function lt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i;(t.width||t.height)&&(t.width=Math.max((t?.width??0)-a*2,10),t.height=Math.max((t?.height??0)/1.5-o*2,10));let{shapeSvg:s,bbox:c,label:l}=await C(e,t,E(t)),u=(t?.width?t?.width:c.width)+a*2,d=((t?.height?t?.height:c.height)+o*2)*1.5,f=u,p=d/1.5,m=-f/2,h=-p/2,{cssStyles:g}=t,_=S.svg(s),b=v(t,{});t.look!==`handDrawn`&&(b.roughness=0,b.fillStyle=`solid`);let x=[{x:m,y:h},{x:m,y:h+p},{x:m+f,y:h+p},{x:m+f,y:h-p/2}],w=D(x),O=_.path(w,b),k=s.insert(()=>O,`:first-child`);return k.attr(`class`,`basic label-container outer-path`),g&&t.look!==`handDrawn`&&k.selectChildren(`path`).attr(`style`,g),r&&t.look!==`handDrawn`&&k.selectChildren(`path`).attr(`style`,r),k.attr(`transform`,`translate(0, ${p/4})`),l.attr(`transform`,`translate(${-f/2+(t.padding??0)-(c.x-(c.left??0))}, ${-p/4+(t.padding??0)-(c.y-(c.top??0))})`),T(t,k),t.intersect=function(e){return G.polygon(t,x,e)},s}e(lt,`slopedRect`);async function ut(e,t){let n=t.padding??0,r=t.look===`neo`?16:n*2,i=t.look===`neo`?12:n;return we(e,t,{rx:0,ry:0,classes:``,labelPaddingX:t.labelPaddingX??r,labelPaddingY:i})}e(ut,`squareRect`);async function dt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?20:i,o=t.look===`neo`?12:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=c.height+(t.look===`neo`?o*2:o),u=c.width+l/4+(t.look===`neo`?a*2:a),d=l/2,{cssStyles:f}=t,p=S.svg(s),m=v(t,{});t.look!==`handDrawn`&&(m.roughness=0,m.fillStyle=`solid`);let h=[{x:-u/2+d,y:-l/2},{x:u/2-d,y:-l/2},...k(-u/2+d,0,d,50,90,270),{x:u/2-d,y:l/2},...k(u/2-d,0,d,50,270,450)],g=D(h),_=p.path(g,m),b=s.insert(()=>_,`:first-child`);return b.attr(`class`,`basic label-container outer-path`),f&&t.look!==`handDrawn`&&b.selectChildren(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&b.selectChildren(`path`).attr(`style`,r),T(t,b),t.intersect=function(e){return G.polygon(t,h,e)},s}e(dt,`stadium`);async function ft(e,t){return we(e,t,{rx:t.look===`neo`?3:5,ry:t.look===`neo`?3:5,classes:`flowchart-node`})}e(ft,`state`);function pt(e,t,{config:{themeVariables:n}}){let{labelStyles:r,nodeStyles:i}=y(t);t.labelStyle=r;let{cssStyles:a}=t,{lineColor:o,stateBorder:s,nodeBorder:c,nodeShadow:l}=n;(t.width||t.height)&&((t.width??0)<14&&(t.width=14),(t.height??0)<14&&(t.height=14)),t.width||=14,t.height||=14;let u=e.insert(`g`).attr(`class`,`node default`).attr(`id`,t.domId??t.id),d=S.svg(u),f=v(t,{});t.look!==`handDrawn`&&(f.roughness=0,f.fillStyle=`solid`);let p=d.circle(0,0,t.width,{...f,stroke:o,strokeWidth:2}),m=s??c,h=(t.width??0)*5/14,g=d.circle(0,0,h,{...f,fill:m,stroke:m,strokeWidth:2,fillStyle:`solid`}),_=u.insert(()=>p,`:first-child`);if(_.insert(()=>g),t.look!==`handDrawn`&&_.attr(`class`,`outer-path`),a&&_.selectAll(`path`).attr(`style`,a),i&&_.selectAll(`path`).attr(`style`,i),t.width<25&&l&&t.look!==`handDrawn`){let t=e.node()?.ownerSVGElement?.id??``,n=t?`${t}-drop-shadow-small`:`drop-shadow-small`;_.attr(`style`,`filter:url(#${n})`)}return T(t,_),t.intersect=function(e){return G.circle(t,(t.width??0)/2,e)},u}e(pt,`stateEnd`);function mt(e,t,{config:{themeVariables:n}}){let{lineColor:r,nodeShadow:i}=n;(t.width||t.height)&&((t.width??0)<14&&(t.width=14),(t.height??0)<14&&(t.height=14)),t.width||=14,t.height||=14;let a=e.insert(`g`).attr(`class`,`node default`).attr(`id`,t.domId||t.id),o;if(t.look===`handDrawn`){let e=S.svg(a).circle(0,0,t.width,b(r));o=a.insert(()=>e),o.attr(`class`,`state-start`).attr(`r`,(t.width??7)/2).attr(`width`,t.width??14).attr(`height`,t.height??14)}else o=a.insert(`circle`,`:first-child`),o.attr(`class`,`state-start`).attr(`r`,(t.width??7)/2).attr(`width`,t.width??14).attr(`height`,t.height??14);if(t.width<25&&i&&t.look!==`handDrawn`){let t=e.node()?.ownerSVGElement?.id??``,n=t?`${t}-drop-shadow-small`:`drop-shadow-small`;o.attr(`style`,`filter:url(#${n})`)}return T(t,o),t.intersect=function(e){return G.circle(t,(t.width??7)/2,e)},a}e(mt,`stateStart`);var ht=8;async function gt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t?.padding??8,a=t.look===`neo`?28:i,o=t.look===`neo`?12:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.width??c.width)+2*ht+a,u=(t?.height??c.height)+o,d=l-2*ht,f=u,m=-l/2,h=-u/2,g=[{x:0,y:0},{x:d,y:0},{x:d,y:-f},{x:0,y:-f},{x:0,y:0},{x:-8,y:0},{x:d+8,y:0},{x:d+8,y:-f},{x:-8,y:-f},{x:-8,y:0}];if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=e.rectangle(m,h,d+16,f,n),i=e.line(m+ht,h,m+ht,h+f,n),a=e.line(m+ht+d,h,m+ht+d,h+f,n);s.insert(()=>i,`:first-child`),s.insert(()=>a,`:first-child`);let o=s.insert(()=>r,`:first-child`),{cssStyles:c}=t;o.attr(`class`,`basic label-container`).attr(`style`,p(c)),T(t,o)}else{let e=q(s,d,f,g);r&&e.attr(`style`,r),T(t,e)}return t.intersect=function(e){return G.polygon(t,g,e)},s}e(gt,`subroutine`);var _t=.2;async function vt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i;(t.width||t.height)&&(t.height=Math.max((t?.height??0)-o*2,10),t.width=Math.max((t?.width??0)-a*2-_t*(t.height+o*2),10));let{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.height?t?.height:c.height)+o*2,u=_t*l,d=_t*l,f=(t?.width?t?.width:c.width)+a*2+u-u,p=l,m=-f/2,h=-p/2,{cssStyles:g}=t,_=S.svg(s),b=v(t,{}),x=[{x:m-u/2,y:h},{x:m+f+u/2,y:h},{x:m+f+u/2,y:h+p},{x:m-u/2,y:h+p}],w=[{x:m+f-u/2,y:h+p},{x:m+f+u/2,y:h+p},{x:m+f+u/2,y:h+p-d}];t.look!==`handDrawn`&&(b.roughness=0,b.fillStyle=`solid`);let O=D(x),k=_.path(O,b),A=D(w),j=_.path(A,{...b,fillStyle:`solid`}),M=s.insert(()=>j,`:first-child`);return M.insert(()=>k,`:first-child`),M.attr(`class`,`basic label-container outer-path`),g&&t.look!==`handDrawn`&&M.selectAll(`path`).attr(`style`,g),r&&t.look!==`handDrawn`&&M.selectAll(`path`).attr(`style`,r),T(t,M),t.intersect=function(e){return G.polygon(t,x,e)},s}e(vt,`taggedRect`);async function yt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let{shapeSvg:i,bbox:a,label:o}=await C(e,t,E(t)),s=Math.max(a.width+(t.padding??0)*2,t?.width??0),c=Math.max(a.height+(t.padding??0)*2,t?.height??0),l=c/8,u=.2*s,d=.2*c,f=c+l,{cssStyles:p}=t,m=S.svg(i),h=v(t,{});t.look!==`handDrawn`&&(h.roughness=0,h.fillStyle=`solid`);let g=[{x:-s/2-s/2*.1,y:f/2},...O(-s/2-s/2*.1,f/2,s/2+s/2*.1,f/2,l,.8),{x:s/2+s/2*.1,y:-f/2},{x:-s/2-s/2*.1,y:-f/2}],_=-s/2+s/2*.1,b=-f/2-d*.4,x=[{x:_+s-u,y:(b+c)*1.3},{x:_+s,y:b+c-d},{x:_+s,y:(b+c)*.9},...O(_+s,(b+c)*1.25,_+s-u,(b+c)*1.3,-c*.02,.5)],w=D(g),k=m.path(w,h),A=D(x),j=m.path(A,{...h,fillStyle:`solid`}),M=i.insert(()=>j,`:first-child`);return M.insert(()=>k,`:first-child`),M.attr(`class`,`basic label-container outer-path`),p&&t.look!==`handDrawn`&&M.selectAll(`path`).attr(`style`,p),r&&t.look!==`handDrawn`&&M.selectAll(`path`).attr(`style`,r),M.attr(`transform`,`translate(0,${-l/2})`),o.attr(`transform`,`translate(${-s/2+(t.padding??0)-(a.x-(a.left??0))},${-c/2+(t.padding??0)-l/2-(a.y-(a.top??0))})`),T(t,M),t.intersect=function(e){return G.polygon(t,g,e)},i}e(yt,`taggedWaveEdgedRectangle`);async function bt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let{shapeSvg:i,bbox:a}=await C(e,t,E(t)),o=Math.max(a.width+(t.padding??0),t?.width||0),s=Math.max(a.height+(t.padding??0),t?.height||0),c=-o/2,l=-s/2,u=i.insert(`rect`,`:first-child`);return u.attr(`class`,`text`).attr(`style`,r).attr(`rx`,0).attr(`ry`,0).attr(`x`,c).attr(`y`,l).attr(`width`,o).attr(`height`,s),T(t,u),t.intersect=function(e){return G.rect(t,e)},i}e(bt,`text`);var xt=e((e,t,n,r,i,a)=>`M${e},${t} a${i},${a} 0,0,1 0,${-r} l${n},0 diff --git a/.vercel/output/static/assets/classDiagram-OUVF2IWQ-D6qCu_tS.js b/.vercel/output/static/assets/classDiagram-OUVF2IWQ-D6qCu_tS.js new file mode 100644 index 0000000..f51b5b4 --- /dev/null +++ b/.vercel/output/static/assets/classDiagram-OUVF2IWQ-D6qCu_tS.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import{i as t,n,r,t as i}from"./chunk-V7JOEXUC-Drt5hFEy.js";var a={parser:n,get db(){return new i},renderer:r,styles:t,init:e(e=>{e.class||={},e.class.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{a as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/classDiagram-OUVF2IWQ-DgseLdj3.js b/.vercel/output/static/assets/classDiagram-OUVF2IWQ-DgseLdj3.js deleted file mode 100644 index d770817..0000000 --- a/.vercel/output/static/assets/classDiagram-OUVF2IWQ-DgseLdj3.js +++ /dev/null @@ -1 +0,0 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-_wZywoZs.js";import"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import"./chunk-32BRIVSS-BtH22FN8.js";import"./chunk-XXDRQBXY-BuE3VzE_.js";import"./chunk-VR4S4FIN-BJzXasDJ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import"./chunk-ZGVPDNZ5-zo3h_nOA.js";import"./chunk-52WLFC77-BBAyrLn9.js";import"./chunk-FWX5IMBZ-CiLc9_ts.js";import{i as t,n,r,t as i}from"./chunk-V7JOEXUC-BrpprPvX.js";var a={parser:n,get db(){return new i},renderer:r,styles:t,init:e(e=>{e.class||={},e.class.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{a as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/classDiagram-v2-EOCWNBFH-D6qCu_tS.js b/.vercel/output/static/assets/classDiagram-v2-EOCWNBFH-D6qCu_tS.js new file mode 100644 index 0000000..f51b5b4 --- /dev/null +++ b/.vercel/output/static/assets/classDiagram-v2-EOCWNBFH-D6qCu_tS.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import{i as t,n,r,t as i}from"./chunk-V7JOEXUC-Drt5hFEy.js";var a={parser:n,get db(){return new i},renderer:r,styles:t,init:e(e=>{e.class||={},e.class.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{a as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/classDiagram-v2-EOCWNBFH-DgseLdj3.js b/.vercel/output/static/assets/classDiagram-v2-EOCWNBFH-DgseLdj3.js deleted file mode 100644 index d770817..0000000 --- a/.vercel/output/static/assets/classDiagram-v2-EOCWNBFH-DgseLdj3.js +++ /dev/null @@ -1 +0,0 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-_wZywoZs.js";import"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import"./chunk-32BRIVSS-BtH22FN8.js";import"./chunk-XXDRQBXY-BuE3VzE_.js";import"./chunk-VR4S4FIN-BJzXasDJ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import"./chunk-ZGVPDNZ5-zo3h_nOA.js";import"./chunk-52WLFC77-BBAyrLn9.js";import"./chunk-FWX5IMBZ-CiLc9_ts.js";import{i as t,n,r,t as i}from"./chunk-V7JOEXUC-BrpprPvX.js";var a={parser:n,get db(){return new i},renderer:r,styles:t,init:e(e=>{e.class||={},e.class.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{a as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/client-8boibB1R.js b/.vercel/output/static/assets/client-CwgDvMJw.js similarity index 99% rename from .vercel/output/static/assets/client-8boibB1R.js rename to .vercel/output/static/assets/client-CwgDvMJw.js index 8de2c9c..154ec05 100644 --- a/.vercel/output/static/assets/client-8boibB1R.js +++ b/.vercel/output/static/assets/client-CwgDvMJw.js @@ -1,3 +1,3 @@ -import{n as e,r as t}from"./rolldown-runtime-QTnfLwEv.js";import{t as n}from"./react-Biaal4sZ.js";var r=`1.6.25`;function i(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}function a(){let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,`writable`)?e.writable:e.set!==void 0}function o(e){let t=e.split(` +import{i as e,n as t}from"./rolldown-runtime-aKtaBQYM.js";import{t as n}from"./react-BLJmJXjR.js";var r=`1.6.25`;function i(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}function a(){let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,`writable`)?e.writable:e.set!==void 0}function o(e){let t=e.split(` at `);return t.length<=1?e:(t.splice(1,1),t.join(` - at `))}function s(e,t){class n extends e{#e;constructor(...e){if(a()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=o(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),n}var c={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};s(class extends Error{constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:c[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},Error);var l=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},u=i({INVALID_OAUTH_CONFIGURATION:`Invalid OAuth configuration`,TOKEN_URL_NOT_FOUND:`Invalid OAuth configuration. Token URL not found.`,PROVIDER_CONFIG_NOT_FOUND:`No config found for provider`,PROVIDER_ID_REQUIRED:`Provider ID is required`,INVALID_OAUTH_CONFIG:`Invalid OAuth configuration.`,SESSION_REQUIRED:`Session is required`,ISSUER_MISMATCH:`OAuth issuer mismatch. The authorization server issuer does not match the expected value (RFC 9207).`,ISSUER_MISSING:`OAuth issuer parameter missing. The authorization server did not include the required iss parameter (RFC 9207).`}),d=()=>({id:`generic-oauth-client`,version:r,$InferServerPlugin:{},$ERROR_CODES:u}),f=Object.create(null),p=e=>({}),m=new Proxy(f,{get(e,t){return p()[t]??f[t]},has(e,t){return t in p()||t in f},set(e,t,n){let r=p(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=p(!0);return delete n[t],!0},ownKeys(){let e=p(!0);return Object.keys(e)}});m.NODE_ENV;function h(e,t){return typeof process<`u`?{}[e]??t:typeof Deno<`u`?Deno.env.get(e)??t:typeof Bun<`u`?Bun.env[e]??t:t}Object.freeze({get BETTER_AUTH_SECRET(){return h(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return h(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return h(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return h(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return h(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return h(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return h(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});var g=47;function _(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===g;)t--;return t===e.length?e:e.slice(0,t)}function v(e){try{return(_(new URL(e).pathname)||`/`)!==`/`}catch{throw new l(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function y(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new l(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof l?t:new l(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function b(e,t=`/api/auth`){if(y(e),v(e))return e;let n=_(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function ee(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function te(e,t,n,r,i){if(e)return b(e,t);if(r!==!1){let e=m.BETTER_AUTH_URL||m.NEXT_PUBLIC_BETTER_AUTH_URL||m.PUBLIC_BETTER_AUTH_URL||m.NUXT_PUBLIC_BETTER_AUTH_URL||m.NUXT_PUBLIC_AUTH_URL||(m.BASE_URL===`/`?void 0:m.BASE_URL);if(e)return b(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&ee(o,`proto`)&&ee(a,`host`))try{return b(`${o}://${a}`,t)}catch{}if(n){let e=ne(n.url);if(!e)throw new l(`Could not get origin from request. Please provide a valid base URL.`);return b(e,t)}if(typeof window<`u`&&window.location)return b(window.location.origin,t)}function ne(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var re=[`javascript:`,`data:`,`vbscript:`];function ie(e){let t;try{t=new URL(e)}catch{return!0}return!re.includes(t.protocol)}var x=[],S=0,C=null,w=4,ae=globalThis.nanostoresGlobal||={epoch:0},oe=()=>{for(S=0;S{let t=[],n={get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(e){return n.lc=t.push(e),()=>{for(let t=S+w;t(e.events=e.events||{},e.events[n+D]||(e.events[n+D]=r(t=>{e.events[n].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let r=e.events[n],i=r.indexOf(t);r.splice(i,1),r.length||(delete e.events[n],e.events[n+D](),delete e.events[n+D])}),le=(e,t)=>O(e,t,se,t=>{let n=e.set,r=e.setKey;return e.setKey&&=(n,i)=>{let a;if(t({abort:()=>{a=!0},changed:n,newValue:{...e.value,[n]:i}}),!a)return r(n,i)},e.set=e=>{let r;if(t({abort:()=>{r=!0},newValue:e}),!r)return n(e)},()=>{e.set=n,e.setKey=r}}),ue=1e3,de=(e,t)=>O(e,n=>{let r=t(n);r&&e.events[E].push(r)},ce,t=>{let n=e.listen;e.listen=(...r)=>(!e.lc&&!e.active&&(e.active=!0,t()),n(...r));let r=e.off;return e.events[E]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[E])t();e.events[E]=[]}},ue)},()=>{e.listen=n,e.off=r}});function fe(e,t,n){let r=new Set(t);return e.listen((e,i,a)=>{(a===void 0?t.some(t=>e[t]!==i[t]):r.has(a)||r.has(a.split(/\.|\[/)[0]))&&n(e,i,a)})}function pe(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function k(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n{t(e.value,n)&&r()})}var he={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},ge=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,A={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},_e=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function ve(e){return e instanceof Date&&!isNaN(e.getTime())}function ye(e){let t=_e.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return ve(f)?f:null}function be(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in A)return A[s];if(!ge.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(he).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t){r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(a&&typeof t==`string`){let e=ye(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function xe(e,t={strict:!0}){return be(e,t)}var Se={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&ie(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},j=Symbol.for(`better-auth:broadcast-channel`),Ce=()=>Math.floor(Date.now()/1e3),we=class{listeners=new Set;name;constructor(e=`better-auth.message`){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(!(typeof window>`u`))try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:Ce()}))}catch{}}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=e=>{if(e.key!==this.name)return;let t=JSON.parse(e.newValue??`{}`);t?.event!==`session`||!t?.data||this.listeners.forEach(e=>e(t))};return window.addEventListener(`storage`,e),()=>{window.removeEventListener(`storage`,e)}}};function M(e=`better-auth.message`){return globalThis[j]||(globalThis[j]=new we(e)),globalThis[j]}var N=Symbol.for(`better-auth:focus-manager`),Te=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||typeof document>`u`||window.addEventListener===void 0)return()=>{};let e=()=>{document.visibilityState===`visible`&&this.setFocused(!0)};return document.addEventListener(`visibilitychange`,e,!1),()=>{document.removeEventListener(`visibilitychange`,e,!1)}}};function P(){return globalThis[N]||(globalThis[N]=new Te),globalThis[N]}var F=Symbol.for(`better-auth:online-manager`),Ee=class{listeners=new Set;isOnline=typeof navigator<`u`?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener(`online`,e,!1),window.addEventListener(`offline`,t,!1),()=>{window.removeEventListener(`online`,e,!1),window.removeEventListener(`offline`,t,!1)}}};function I(){return globalThis[F]||(globalThis[F]=new Ee),globalThis[F]}var L=()=>Math.floor(Date.now()/1e3),De=5;function Oe(e){let{fetchSession:t,shouldPollSession:n=()=>!0,sessionSignal:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={isInitialized:!1,lastSessionRequest:0},l=()=>s||I().isOnline,u=e=>{if(l()){if(e?.event===`storage`){t();return}if(e?.event===`poll`){c.lastSessionRequest=L(),t();return}if(e?.event===`visibilitychange`){if(L()-c.lastSessionRequest{M().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{n()&&u({event:`poll`})},a*1e3))},p=()=>{c.unsubscribeBroadcast=M().subscribe(()=>{u({event:`storage`})})},m=()=>{o&&(c.unsubscribeFocus=P().subscribe(()=>{u({event:`visibilitychange`})}))},h=()=>{c.unsubscribeOnline=I().subscribe(e=>{e&&u({event:`visibilitychange`})})},g=()=>{c.unsubscribeSignal=r.listen(()=>{t()})};return{init:()=>{c.isInitialized||(c.isInitialized=!0,f(),p(),m(),h(),g(),c.cleanupBroadcastSetup=M().setup(),c.cleanupFocusSetup=P().setup(),c.cleanupOnlineSetup=I().setup())},cleanup:()=>{c.isInitialized&&(c.pollInterval&&=(clearInterval(c.pollInterval),void 0),c.unsubscribeBroadcast&&=(c.unsubscribeBroadcast(),void 0),c.unsubscribeFocus&&=(c.unsubscribeFocus(),void 0),c.unsubscribeOnline&&=(c.unsubscribeOnline(),void 0),c.unsubscribeSignal&&=(c.unsubscribeSignal(),void 0),c.cleanupBroadcastSetup&&=(c.cleanupBroadcastSetup(),void 0),c.cleanupFocusSetup&&=(c.cleanupFocusSetup(),void 0),c.cleanupOnlineSetup&&=(c.cleanupOnlineSetup(),void 0),c.isInitialized=!1,c.lastSessionRequest=0)},triggerRefetch:u,broadcastSessionUpdate:d}}var ke=()=>typeof window>`u`;function R(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Ae(e){return!e||e.session===null&&e.user===null?null:e}function je(e,t){return k(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function Me(e,t){let n=T(!1),r,i=e=>s(e),a=T({data:null,error:null,isPending:!0,isRefetching:!1,refetch:i});me(a,je);let o=e=>{if(r!==e)return;let t=a.get();r=void 0,!(!t.isPending&&!t.isRefetching)&&a.set({...t,isPending:!1,isRefetching:!1,refetch:i})},s=async t=>{r?.abort();let n=new AbortController;r=n;let s=a.get();a.set({...s,isPending:s.data===null,isRefetching:!0,error:null,refetch:i});try{let r=await e(`/get-session`,{method:`GET`,query:t?.query,signal:n.signal});if(n.signal.aborted){o(n);return}let{data:s,error:c}=R(r);if(s?.needsRefresh)try{let t=await e(`/get-session`,{method:`POST`,signal:n.signal});if(n.signal.aborted){o(n);return}({data:s,error:c}=R(t))}catch{if(n.signal.aborted){o(n);return}}if(c){let e=a.get(),t=c?.status===401;a.set({data:t?null:e.data,error:c,isPending:!1,isRefetching:!1,refetch:i});return}let l=Ae(s),u=a.get(),d=u.data!=null&&l!=null&&k(u.data,l)?u.data:l;a.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:i})}catch(e){if(n.signal.aborted){o(n);return}let t=a.get();a.set({data:t.data,error:e,isPending:!1,isRefetching:!1,refetch:i})}},c=()=>{};return de(a,()=>{let e;ke()||(e=setTimeout(()=>{s()},0));let i=Oe({fetchSession:s,shouldPollSession:()=>a.get().data!=null,sessionSignal:n,options:t});return i.init(),c=i.broadcastSessionUpdate,()=>{e&&clearTimeout(e);let t=r;t?.abort(),t&&o(t),i.cleanup()}}),{session:a,$sessionSignal:n,broadcastSessionUpdate:e=>c(e)}}function z(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function B(e,t,n=`.`,r){if(!z(t))return B(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(Array.isArray(a)&&Array.isArray(i[t])?i[t]=[...a,...i[t]]:z(a)&&z(i[t])?i[t]=B(a,i[t],(n?`${n}.`:``)+t.toString(),r):i[t]=a))}return i}function Ne(e){return(...t)=>t.reduce((t,n)=>B(t,n,``,e),{})}var Pe=Ne(),Fe=Object.defineProperty,Ie=Object.defineProperties,Le=Object.getOwnPropertyDescriptors,V=Object.getOwnPropertySymbols,Re=Object.prototype.hasOwnProperty,ze=Object.prototype.propertyIsEnumerable,H=(e,t,n)=>t in e?Fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,U=(e,t)=>{for(var n in t||={})Re.call(t,n)&&H(e,n,t[n]);if(V)for(var n of V(t))ze.call(t,n)&&H(e,n,t[n]);return e},W=(e,t)=>Ie(e,Le(t)),Be=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},Ve=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let r=await i.init?.call(i,e.toString(),t);n=r.options||n,e=r.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},G=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Ge=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ke(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Ge.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function qe(e){try{return JSON.parse(e),!0}catch{return!1}}function Je(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function Ye(e){try{return JSON.parse(e)}catch{return e}}function Xe(e){return typeof e==`function`}function Ze(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&Xe(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&Xe(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function Qe(...e){let t={};for(let n of e)if(n)if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}return t}async function $e(e){let t=new Headers(Qe(e?.headers,await We(e)));if(!t.has(`content-type`)){let n=et(e?.body);n&&t.set(`content-type`,n)}return t}function et(e){return Je(e)?`application/json`:null}function tt(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function nt(e,t){let{body:n}=e;return n?!Je(n)||typeof n==`string`?n:tt(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function rt(e,t){if(t?.method)return t.method.toUpperCase();if(e.startsWith(`@`)){let n=e.split(`@`)[1]?.split(`/`)[0];return ot.includes(n)?n.toUpperCase():t?.body?`POST`:`GET`}return t?.body?`POST`:`GET`}function it(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var at=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function K(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new at(n.issues);return n.value}var ot=[`get`,`post`,`put`,`patch`,`delete`],st=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){let r=e.plugins?.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1)?.schema||e.schema;if(r){let e=t;r.config?.prefix&&e.startsWith(r.config.prefix)&&(e=e.replace(r.config.prefix,``),r.config.baseURL&&(t=t.replace(r.config.prefix,r.config.baseURL))),r.config?.baseURL&&e.startsWith(r.config.baseURL)&&(e=e.replace(r.config.baseURL,``)),e.startsWith(`/`)&&e.charAt(1)===`@`&&(e=e.substring(1));let i=r.schema[e];if(i){let e=n?.headers;if(i.headers&&!n?.disableValidation){let t={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((e,n)=>{t[n.toLowerCase()]=e});else if(typeof n.headers==`object`)for(let[e,r]of Object.entries(n.headers))r!=null&&(t[e.toLowerCase()]=r)}let r=await K(i.headers,t),a={};for(let[e,t]of Object.entries(r))a[e.toLowerCase()]=t;e=a}let r=W(U({},n),{method:i.method,output:i.output,headers:e});return n?.disableValidation||(r=W(U({},r),{body:i.input?await K(i.input,n?.body):n?.body,params:i.params?await K(i.params,n?.params):n?.params,query:i.query?await K(i.query,n?.query):n?.query})),{url:t,options:r}}}return{url:t,options:n}}}),ct=e=>{async function t(t,n){let r=W(U(U({},e),n),{headers:Qe(e?.headers,n?.headers),plugins:[...e?.plugins||[],st(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await q(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await q(t,r)}return t},lt=e=>e===`.`||e===`..`;function ut(e,t){let n=e;for(let[e,r]of t)n=n.replace(e,r);if(lt(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function dt(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``;if(e.startsWith(`@`)){let t=e.toString().split(`@`)[1].split(`/`)[0];ot.includes(t)&&(e=e.replace(`@${t}/`,`/`))}a.endsWith(`/`)||(a+=`/`);let[o,s]=e.replace(a,``).split(`?`),c=new URLSearchParams(s);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)c.append(e,n);continue}else n=JSON.stringify(t);c.set(e,n)}let l=new Map;if(r)if(Array.isArray(r)){let e=o.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];l.set(n,String(e))}}else for(let[e,t]of Object.entries(r))l.set(`:${e}`,String(t));o=o.split(`/`).map(e=>ut(e,l)).join(`/`),o=o.replace(/^\/+/,``);let u=c.toString();return u=u.length>0?`?${u}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${o}${u}`,a):`${a}${o}${u}`}var q=async(e,t)=>{let{hooks:n,url:r,options:i}=await Ve(e,t),a=Ze(i),o=new AbortController,s=i.signal??o.signal,c=dt(r,i),l=await $e(i),u=nt(i,l),d=rt(r,i),f=W(U({},i),{url:c,headers:l,body:u,method:d,signal:s});for(let e of n.onRequest)if(e){let t=await e(f);typeof t==`object`&&t&&Object.assign(f,t)}(`pipeTo`in f&&typeof f.pipeTo==`function`||typeof t?.body?.pipe==`function`)&&(`duplex`in f||(f.duplex=`half`));let{clearTimeout:p}=it(i,o),m=await a(f.url,f);p();let h={response:m,request:f};for(let e of n.onResponse)if(e){let n=await e(W(U({},h),{response:t?.hookOptions?.cloneResponse?m.clone():m}));n instanceof Response?m=n:typeof n==`object`&&n&&(m=n.response)}if(m.ok){if(f.method===`HEAD`)return{data:``,error:null};let e=Ke(m),r={data:null,response:m,request:f};if(e===`json`||e===`text`){let e=await m.text();r.data=await(f.jsonParser??Ye)(e)}else r.data=await m[e]();f?.output&&f.output&&!f.disableValidation&&(r.data=await K(f.output,r.data));for(let e of n.onSuccess)e&&await e(W(U({},r),{response:t?.hookOptions?.cloneResponse?m.clone():m}));return t?.throw?r.data:{data:r.data,error:null}}let g=t?.jsonParser??Ye,_=await m.text(),v=qe(_),y=v?await g(_):null,b={response:m,responseText:_,request:f,error:W(U({},y),{status:m.status,statusText:m.statusText})};for(let e of n.onError)e&&await e(W(U({},b),{response:t?.hookOptions?.cloneResponse?m.clone():m}));if(t?.retry){let r=Ue(t.retry),i=t.retryAttempt??0;if(await r.shouldAttemptRetry(i,m)){for(let e of n.onRetry)e&&await e(h);let a=r.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await q(e,W(U({},t),{retryAttempt:i+1}))}}if(t?.throw)throw new Be(m.status,m.statusText,v?y:_);return{data:null,error:W(U({},y),{status:m.status,statusText:m.statusText})}},ft=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},pt=(e,t)=>{let n=`credentials`in Request.prototype,r=te(e?.baseURL,e?.basePath,void 0,t)??ft(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=ct({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?xe(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[Se],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=Me(d,e),h=e?.plugins||[],g={},_={$sessionSignal:f,session:p},v={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},y=[{signal:`$sessionSignal`,matcher(e){return e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`},callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of h)e.getAtoms&&Object.assign(_,e.getAtoms?.(d)),e.pathMethods&&Object.assign(v,e.pathMethods),e.atomListeners&&y.push(...e.atomListeners);let b={notify:e=>{_[e].set(!_[e].get())},listen:(e,t)=>{_[e].subscribe(t)},atoms:_};for(let t of h)t.getActions&&(g=Pe(t.getActions?.(d,b,e)??{},g));return{get baseURL(){return r},pluginsActions:g,pluginsAtoms:_,pluginPathMethods:v,atomListeners:y,$fetch:d,$store:b}};function mt(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function ht(e){return e.charAt(0).toUpperCase()+e.slice(1)}var gt=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,_t=/['\u2019]/g;function vt(e){return e.replace(_t,``).match(gt)??[]}function yt(e){return vt(e).map(e=>e.toLowerCase()).join(`-`)}function bt(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function xt(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||mt(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(yt).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=bt(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}var J=t(n(),1);function St(e,t={}){let n=(0,J.useRef)(e.get()),{keys:r,deps:i=[e,r]}=t,a=(0,J.useCallback)(t=>{let i=e=>{n.current!==e&&(n.current=e,t())};return i(e.value),r?.length?fe(e,r,i):e.listen(i)},i),o=()=>n.current;return(0,J.useSyncExternalStore)(a,o,o)}function Ct(e){return`use${ht(e)}`}function wt(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,$fetch:i,$store:a,atomListeners:o}=pt(e),s={};for(let[e,t]of Object.entries(r))s[Ct(e)]=()=>St(t);return xt({...n,...s,$fetch:i,$store:a},i,t,r,o)}var Tt=e({authClient:()=>Y,authEnabled:()=>!0,getBearerToken:()=>Z,signIn:()=>Et,signOut:()=>kt}),Y=wt({plugins:[d()],fetchOptions:{onRequest(e){let t=Z();return t&&e.headers.set(`Authorization`,`Bearer ${t}`),e}}}),X=`grok-auth.bearer-token`;function Z(){if(typeof window>`u`)return null;try{return window.sessionStorage.getItem(X)}catch{return null}}function Q(e){if(!(typeof window>`u`))try{e?window.sessionStorage.setItem(X,e):window.sessionStorage.removeItem(X)}catch{}}function $(){return typeof window<`u`&&window.location.hostname.endsWith(`.grok-sandbox.com`)}async function Et(e,t={}){let n=t.callbackURL??`/`,r=t.errorCallbackURL??`/`,i=$()?Dt(e):null;if(Z()||!$())try{await Y.signOut()}catch{}if(Q(null),$()){if(!i)throw Error(`Pop-up blocked — allow pop-ups for sign-in`);let e=await Ot(i);if(!e)throw Error(`Sign-in was cancelled or failed`);Q(e);try{await Y.getSession()}catch{}if(typeof window<`u`){let e=new URL(n,window.location.origin),t=window.location;(e.origin!==t.origin||e.pathname!==t.pathname||e.search!==t.search)&&(window.location.href=n)}return}let{data:a,error:o}=await Y.signIn.oauth2({providerId:e,callbackURL:n,errorCallbackURL:r});if(o)throw Error(o.message??`Sign-in failed`);a?.url&&(window.location.href=a.url)}function Dt(e){let t=`${window.location.origin}/auth/popup?providerId=${encodeURIComponent(e)}`,n=`grok-signin-${Date.now()}`;return window.open(t,n,`popup,width=500,height=650`)}function Ot(e){return new Promise(t=>{let n=window.location.origin,r=!1,i,a=e=>{r||(r=!0,c(),t(e))},o=e=>{if(e.origin!==n)return;let t=e.data;!t||t.source!==`grok-auth-popup`||a(t.token??null)},s=window.setInterval(()=>{e.closed&&(window.clearInterval(s),i=window.setTimeout(()=>a(null),400))},300);function c(){window.clearInterval(s),i!==void 0&&window.clearTimeout(i),window.removeEventListener(`message`,o)}window.addEventListener(`message`,o)})}async function kt(e=`/`){try{await Y.signOut()}finally{Q(null)}window.location.href=e}export{kt as i,Tt as n,Et as r,Y as t}; \ No newline at end of file + at `))}function s(e,t){class n extends e{#e;constructor(...e){if(a()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=o(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),n}var c={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};s(class extends Error{constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:c[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},Error);var l=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},u=i({INVALID_OAUTH_CONFIGURATION:`Invalid OAuth configuration`,TOKEN_URL_NOT_FOUND:`Invalid OAuth configuration. Token URL not found.`,PROVIDER_CONFIG_NOT_FOUND:`No config found for provider`,PROVIDER_ID_REQUIRED:`Provider ID is required`,INVALID_OAUTH_CONFIG:`Invalid OAuth configuration.`,SESSION_REQUIRED:`Session is required`,ISSUER_MISMATCH:`OAuth issuer mismatch. The authorization server issuer does not match the expected value (RFC 9207).`,ISSUER_MISSING:`OAuth issuer parameter missing. The authorization server did not include the required iss parameter (RFC 9207).`}),d=()=>({id:`generic-oauth-client`,version:r,$InferServerPlugin:{},$ERROR_CODES:u}),f=Object.create(null),p=e=>({}),m=new Proxy(f,{get(e,t){return p()[t]??f[t]},has(e,t){return t in p()||t in f},set(e,t,n){let r=p(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=p(!0);return delete n[t],!0},ownKeys(){let e=p(!0);return Object.keys(e)}});m.NODE_ENV;function h(e,t){return typeof process<`u`?{}[e]??t:typeof Deno<`u`?Deno.env.get(e)??t:typeof Bun<`u`?Bun.env[e]??t:t}Object.freeze({get BETTER_AUTH_SECRET(){return h(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return h(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return h(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return h(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return h(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return h(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return h(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});var g=47;function _(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===g;)t--;return t===e.length?e:e.slice(0,t)}function v(e){try{return(_(new URL(e).pathname)||`/`)!==`/`}catch{throw new l(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function y(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new l(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof l?t:new l(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function b(e,t=`/api/auth`){if(y(e),v(e))return e;let n=_(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function ee(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function te(e,t,n,r,i){if(e)return b(e,t);if(r!==!1){let e=m.BETTER_AUTH_URL||m.NEXT_PUBLIC_BETTER_AUTH_URL||m.PUBLIC_BETTER_AUTH_URL||m.NUXT_PUBLIC_BETTER_AUTH_URL||m.NUXT_PUBLIC_AUTH_URL||(m.BASE_URL===`/`?void 0:m.BASE_URL);if(e)return b(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&ee(o,`proto`)&&ee(a,`host`))try{return b(`${o}://${a}`,t)}catch{}if(n){let e=ne(n.url);if(!e)throw new l(`Could not get origin from request. Please provide a valid base URL.`);return b(e,t)}if(typeof window<`u`&&window.location)return b(window.location.origin,t)}function ne(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var re=[`javascript:`,`data:`,`vbscript:`];function ie(e){let t;try{t=new URL(e)}catch{return!0}return!re.includes(t.protocol)}var x=[],S=0,C=null,w=4,ae=globalThis.nanostoresGlobal||={epoch:0},oe=()=>{for(S=0;S{let t=[],n={get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(e){return n.lc=t.push(e),()=>{for(let t=S+w;t(e.events=e.events||{},e.events[n+D]||(e.events[n+D]=r(t=>{e.events[n].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let r=e.events[n],i=r.indexOf(t);r.splice(i,1),r.length||(delete e.events[n],e.events[n+D](),delete e.events[n+D])}),le=(e,t)=>O(e,t,se,t=>{let n=e.set,r=e.setKey;return e.setKey&&=(n,i)=>{let a;if(t({abort:()=>{a=!0},changed:n,newValue:{...e.value,[n]:i}}),!a)return r(n,i)},e.set=e=>{let r;if(t({abort:()=>{r=!0},newValue:e}),!r)return n(e)},()=>{e.set=n,e.setKey=r}}),ue=1e3,de=(e,t)=>O(e,n=>{let r=t(n);r&&e.events[E].push(r)},ce,t=>{let n=e.listen;e.listen=(...r)=>(!e.lc&&!e.active&&(e.active=!0,t()),n(...r));let r=e.off;return e.events[E]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[E])t();e.events[E]=[]}},ue)},()=>{e.listen=n,e.off=r}});function fe(e,t,n){let r=new Set(t);return e.listen((e,i,a)=>{(a===void 0?t.some(t=>e[t]!==i[t]):r.has(a)||r.has(a.split(/\.|\[/)[0]))&&n(e,i,a)})}function pe(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function k(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n{t(e.value,n)&&r()})}var he={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},ge=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,A={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},_e=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function ve(e){return e instanceof Date&&!isNaN(e.getTime())}function ye(e){let t=_e.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return ve(f)?f:null}function be(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in A)return A[s];if(!ge.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(he).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t){r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(a&&typeof t==`string`){let e=ye(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function xe(e,t={strict:!0}){return be(e,t)}var Se={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&ie(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},j=Symbol.for(`better-auth:broadcast-channel`),Ce=()=>Math.floor(Date.now()/1e3),we=class{listeners=new Set;name;constructor(e=`better-auth.message`){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(!(typeof window>`u`))try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:Ce()}))}catch{}}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=e=>{if(e.key!==this.name)return;let t=JSON.parse(e.newValue??`{}`);t?.event!==`session`||!t?.data||this.listeners.forEach(e=>e(t))};return window.addEventListener(`storage`,e),()=>{window.removeEventListener(`storage`,e)}}};function M(e=`better-auth.message`){return globalThis[j]||(globalThis[j]=new we(e)),globalThis[j]}var N=Symbol.for(`better-auth:focus-manager`),Te=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||typeof document>`u`||window.addEventListener===void 0)return()=>{};let e=()=>{document.visibilityState===`visible`&&this.setFocused(!0)};return document.addEventListener(`visibilitychange`,e,!1),()=>{document.removeEventListener(`visibilitychange`,e,!1)}}};function P(){return globalThis[N]||(globalThis[N]=new Te),globalThis[N]}var F=Symbol.for(`better-auth:online-manager`),Ee=class{listeners=new Set;isOnline=typeof navigator<`u`?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener(`online`,e,!1),window.addEventListener(`offline`,t,!1),()=>{window.removeEventListener(`online`,e,!1),window.removeEventListener(`offline`,t,!1)}}};function I(){return globalThis[F]||(globalThis[F]=new Ee),globalThis[F]}var L=()=>Math.floor(Date.now()/1e3),De=5;function Oe(e){let{fetchSession:t,shouldPollSession:n=()=>!0,sessionSignal:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={isInitialized:!1,lastSessionRequest:0},l=()=>s||I().isOnline,u=e=>{if(l()){if(e?.event===`storage`){t();return}if(e?.event===`poll`){c.lastSessionRequest=L(),t();return}if(e?.event===`visibilitychange`){if(L()-c.lastSessionRequest{M().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{n()&&u({event:`poll`})},a*1e3))},p=()=>{c.unsubscribeBroadcast=M().subscribe(()=>{u({event:`storage`})})},m=()=>{o&&(c.unsubscribeFocus=P().subscribe(()=>{u({event:`visibilitychange`})}))},h=()=>{c.unsubscribeOnline=I().subscribe(e=>{e&&u({event:`visibilitychange`})})},g=()=>{c.unsubscribeSignal=r.listen(()=>{t()})};return{init:()=>{c.isInitialized||(c.isInitialized=!0,f(),p(),m(),h(),g(),c.cleanupBroadcastSetup=M().setup(),c.cleanupFocusSetup=P().setup(),c.cleanupOnlineSetup=I().setup())},cleanup:()=>{c.isInitialized&&(c.pollInterval&&=(clearInterval(c.pollInterval),void 0),c.unsubscribeBroadcast&&=(c.unsubscribeBroadcast(),void 0),c.unsubscribeFocus&&=(c.unsubscribeFocus(),void 0),c.unsubscribeOnline&&=(c.unsubscribeOnline(),void 0),c.unsubscribeSignal&&=(c.unsubscribeSignal(),void 0),c.cleanupBroadcastSetup&&=(c.cleanupBroadcastSetup(),void 0),c.cleanupFocusSetup&&=(c.cleanupFocusSetup(),void 0),c.cleanupOnlineSetup&&=(c.cleanupOnlineSetup(),void 0),c.isInitialized=!1,c.lastSessionRequest=0)},triggerRefetch:u,broadcastSessionUpdate:d}}var ke=()=>typeof window>`u`;function R(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Ae(e){return!e||e.session===null&&e.user===null?null:e}function je(e,t){return k(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function Me(e,t){let n=T(!1),r,i=e=>s(e),a=T({data:null,error:null,isPending:!0,isRefetching:!1,refetch:i});me(a,je);let o=e=>{if(r!==e)return;let t=a.get();r=void 0,!(!t.isPending&&!t.isRefetching)&&a.set({...t,isPending:!1,isRefetching:!1,refetch:i})},s=async t=>{r?.abort();let n=new AbortController;r=n;let s=a.get();a.set({...s,isPending:s.data===null,isRefetching:!0,error:null,refetch:i});try{let r=await e(`/get-session`,{method:`GET`,query:t?.query,signal:n.signal});if(n.signal.aborted){o(n);return}let{data:s,error:c}=R(r);if(s?.needsRefresh)try{let t=await e(`/get-session`,{method:`POST`,signal:n.signal});if(n.signal.aborted){o(n);return}({data:s,error:c}=R(t))}catch{if(n.signal.aborted){o(n);return}}if(c){let e=a.get(),t=c?.status===401;a.set({data:t?null:e.data,error:c,isPending:!1,isRefetching:!1,refetch:i});return}let l=Ae(s),u=a.get(),d=u.data!=null&&l!=null&&k(u.data,l)?u.data:l;a.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:i})}catch(e){if(n.signal.aborted){o(n);return}let t=a.get();a.set({data:t.data,error:e,isPending:!1,isRefetching:!1,refetch:i})}},c=()=>{};return de(a,()=>{let e;ke()||(e=setTimeout(()=>{s()},0));let i=Oe({fetchSession:s,shouldPollSession:()=>a.get().data!=null,sessionSignal:n,options:t});return i.init(),c=i.broadcastSessionUpdate,()=>{e&&clearTimeout(e);let t=r;t?.abort(),t&&o(t),i.cleanup()}}),{session:a,$sessionSignal:n,broadcastSessionUpdate:e=>c(e)}}function z(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function B(e,t,n=`.`,r){if(!z(t))return B(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(Array.isArray(a)&&Array.isArray(i[t])?i[t]=[...a,...i[t]]:z(a)&&z(i[t])?i[t]=B(a,i[t],(n?`${n}.`:``)+t.toString(),r):i[t]=a))}return i}function Ne(e){return(...t)=>t.reduce((t,n)=>B(t,n,``,e),{})}var Pe=Ne(),Fe=Object.defineProperty,Ie=Object.defineProperties,Le=Object.getOwnPropertyDescriptors,V=Object.getOwnPropertySymbols,Re=Object.prototype.hasOwnProperty,ze=Object.prototype.propertyIsEnumerable,H=(e,t,n)=>t in e?Fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,U=(e,t)=>{for(var n in t||={})Re.call(t,n)&&H(e,n,t[n]);if(V)for(var n of V(t))ze.call(t,n)&&H(e,n,t[n]);return e},W=(e,t)=>Ie(e,Le(t)),Be=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},Ve=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let r=await i.init?.call(i,e.toString(),t);n=r.options||n,e=r.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},G=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Ge=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ke(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Ge.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function qe(e){try{return JSON.parse(e),!0}catch{return!1}}function Je(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function Ye(e){try{return JSON.parse(e)}catch{return e}}function Xe(e){return typeof e==`function`}function Ze(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&Xe(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&Xe(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function Qe(...e){let t={};for(let n of e)if(n)if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}return t}async function $e(e){let t=new Headers(Qe(e?.headers,await We(e)));if(!t.has(`content-type`)){let n=et(e?.body);n&&t.set(`content-type`,n)}return t}function et(e){return Je(e)?`application/json`:null}function tt(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function nt(e,t){let{body:n}=e;return n?!Je(n)||typeof n==`string`?n:tt(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function rt(e,t){if(t?.method)return t.method.toUpperCase();if(e.startsWith(`@`)){let n=e.split(`@`)[1]?.split(`/`)[0];return ot.includes(n)?n.toUpperCase():t?.body?`POST`:`GET`}return t?.body?`POST`:`GET`}function it(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var at=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function K(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new at(n.issues);return n.value}var ot=[`get`,`post`,`put`,`patch`,`delete`],st=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){let r=e.plugins?.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1)?.schema||e.schema;if(r){let e=t;r.config?.prefix&&e.startsWith(r.config.prefix)&&(e=e.replace(r.config.prefix,``),r.config.baseURL&&(t=t.replace(r.config.prefix,r.config.baseURL))),r.config?.baseURL&&e.startsWith(r.config.baseURL)&&(e=e.replace(r.config.baseURL,``)),e.startsWith(`/`)&&e.charAt(1)===`@`&&(e=e.substring(1));let i=r.schema[e];if(i){let e=n?.headers;if(i.headers&&!n?.disableValidation){let t={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((e,n)=>{t[n.toLowerCase()]=e});else if(typeof n.headers==`object`)for(let[e,r]of Object.entries(n.headers))r!=null&&(t[e.toLowerCase()]=r)}let r=await K(i.headers,t),a={};for(let[e,t]of Object.entries(r))a[e.toLowerCase()]=t;e=a}let r=W(U({},n),{method:i.method,output:i.output,headers:e});return n?.disableValidation||(r=W(U({},r),{body:i.input?await K(i.input,n?.body):n?.body,params:i.params?await K(i.params,n?.params):n?.params,query:i.query?await K(i.query,n?.query):n?.query})),{url:t,options:r}}}return{url:t,options:n}}}),ct=e=>{async function t(t,n){let r=W(U(U({},e),n),{headers:Qe(e?.headers,n?.headers),plugins:[...e?.plugins||[],st(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await q(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await q(t,r)}return t},lt=e=>e===`.`||e===`..`;function ut(e,t){let n=e;for(let[e,r]of t)n=n.replace(e,r);if(lt(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function dt(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``;if(e.startsWith(`@`)){let t=e.toString().split(`@`)[1].split(`/`)[0];ot.includes(t)&&(e=e.replace(`@${t}/`,`/`))}a.endsWith(`/`)||(a+=`/`);let[o,s]=e.replace(a,``).split(`?`),c=new URLSearchParams(s);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)c.append(e,n);continue}else n=JSON.stringify(t);c.set(e,n)}let l=new Map;if(r)if(Array.isArray(r)){let e=o.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];l.set(n,String(e))}}else for(let[e,t]of Object.entries(r))l.set(`:${e}`,String(t));o=o.split(`/`).map(e=>ut(e,l)).join(`/`),o=o.replace(/^\/+/,``);let u=c.toString();return u=u.length>0?`?${u}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${o}${u}`,a):`${a}${o}${u}`}var q=async(e,t)=>{let{hooks:n,url:r,options:i}=await Ve(e,t),a=Ze(i),o=new AbortController,s=i.signal??o.signal,c=dt(r,i),l=await $e(i),u=nt(i,l),d=rt(r,i),f=W(U({},i),{url:c,headers:l,body:u,method:d,signal:s});for(let e of n.onRequest)if(e){let t=await e(f);typeof t==`object`&&t&&Object.assign(f,t)}(`pipeTo`in f&&typeof f.pipeTo==`function`||typeof t?.body?.pipe==`function`)&&(`duplex`in f||(f.duplex=`half`));let{clearTimeout:p}=it(i,o),m=await a(f.url,f);p();let h={response:m,request:f};for(let e of n.onResponse)if(e){let n=await e(W(U({},h),{response:t?.hookOptions?.cloneResponse?m.clone():m}));n instanceof Response?m=n:typeof n==`object`&&n&&(m=n.response)}if(m.ok){if(f.method===`HEAD`)return{data:``,error:null};let e=Ke(m),r={data:null,response:m,request:f};if(e===`json`||e===`text`){let e=await m.text();r.data=await(f.jsonParser??Ye)(e)}else r.data=await m[e]();f?.output&&f.output&&!f.disableValidation&&(r.data=await K(f.output,r.data));for(let e of n.onSuccess)e&&await e(W(U({},r),{response:t?.hookOptions?.cloneResponse?m.clone():m}));return t?.throw?r.data:{data:r.data,error:null}}let g=t?.jsonParser??Ye,_=await m.text(),v=qe(_),y=v?await g(_):null,b={response:m,responseText:_,request:f,error:W(U({},y),{status:m.status,statusText:m.statusText})};for(let e of n.onError)e&&await e(W(U({},b),{response:t?.hookOptions?.cloneResponse?m.clone():m}));if(t?.retry){let r=Ue(t.retry),i=t.retryAttempt??0;if(await r.shouldAttemptRetry(i,m)){for(let e of n.onRetry)e&&await e(h);let a=r.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await q(e,W(U({},t),{retryAttempt:i+1}))}}if(t?.throw)throw new Be(m.status,m.statusText,v?y:_);return{data:null,error:W(U({},y),{status:m.status,statusText:m.statusText})}},ft=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},pt=(e,t)=>{let n=`credentials`in Request.prototype,r=te(e?.baseURL,e?.basePath,void 0,t)??ft(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=ct({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?xe(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[Se],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=Me(d,e),h=e?.plugins||[],g={},_={$sessionSignal:f,session:p},v={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},y=[{signal:`$sessionSignal`,matcher(e){return e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`},callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of h)e.getAtoms&&Object.assign(_,e.getAtoms?.(d)),e.pathMethods&&Object.assign(v,e.pathMethods),e.atomListeners&&y.push(...e.atomListeners);let b={notify:e=>{_[e].set(!_[e].get())},listen:(e,t)=>{_[e].subscribe(t)},atoms:_};for(let t of h)t.getActions&&(g=Pe(t.getActions?.(d,b,e)??{},g));return{get baseURL(){return r},pluginsActions:g,pluginsAtoms:_,pluginPathMethods:v,atomListeners:y,$fetch:d,$store:b}};function mt(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function ht(e){return e.charAt(0).toUpperCase()+e.slice(1)}var gt=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,_t=/['\u2019]/g;function vt(e){return e.replace(_t,``).match(gt)??[]}function yt(e){return vt(e).map(e=>e.toLowerCase()).join(`-`)}function bt(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function xt(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||mt(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(yt).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=bt(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}var J=e(n(),1);function St(e,t={}){let n=(0,J.useRef)(e.get()),{keys:r,deps:i=[e,r]}=t,a=(0,J.useCallback)(t=>{let i=e=>{n.current!==e&&(n.current=e,t())};return i(e.value),r?.length?fe(e,r,i):e.listen(i)},i),o=()=>n.current;return(0,J.useSyncExternalStore)(a,o,o)}function Ct(e){return`use${ht(e)}`}function wt(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,$fetch:i,$store:a,atomListeners:o}=pt(e),s={};for(let[e,t]of Object.entries(r))s[Ct(e)]=()=>St(t);return xt({...n,...s,$fetch:i,$store:a},i,t,r,o)}var Tt=t({authClient:()=>Y,authEnabled:()=>!0,getBearerToken:()=>Z,signIn:()=>Et,signOut:()=>kt}),Y=wt({plugins:[d()],fetchOptions:{onRequest(e){let t=Z();return t&&e.headers.set(`Authorization`,`Bearer ${t}`),e}}}),X=`grok-auth.bearer-token`;function Z(){if(typeof window>`u`)return null;try{return window.sessionStorage.getItem(X)}catch{return null}}function Q(e){if(!(typeof window>`u`))try{e?window.sessionStorage.setItem(X,e):window.sessionStorage.removeItem(X)}catch{}}function $(){return typeof window<`u`&&window.location.hostname.endsWith(`.grok-sandbox.com`)}async function Et(e,t={}){let n=t.callbackURL??`/`,r=t.errorCallbackURL??`/`,i=$()?Dt(e):null;if(Z()||!$())try{await Y.signOut()}catch{}if(Q(null),$()){if(!i)throw Error(`Pop-up blocked — allow pop-ups for sign-in`);let e=await Ot(i);if(!e)throw Error(`Sign-in was cancelled or failed`);Q(e);try{await Y.getSession()}catch{}if(typeof window<`u`){let e=new URL(n,window.location.origin),t=window.location;(e.origin!==t.origin||e.pathname!==t.pathname||e.search!==t.search)&&(window.location.href=n)}return}let{data:a,error:o}=await Y.signIn.oauth2({providerId:e,callbackURL:n,errorCallbackURL:r});if(o)throw Error(o.message??`Sign-in failed`);a?.url&&(window.location.href=a.url)}function Dt(e){let t=`${window.location.origin}/auth/popup?providerId=${encodeURIComponent(e)}`,n=`grok-signin-${Date.now()}`;return window.open(t,n,`popup,width=500,height=650`)}function Ot(e){return new Promise(t=>{let n=window.location.origin,r=!1,i,a=e=>{r||(r=!0,c(),t(e))},o=e=>{if(e.origin!==n)return;let t=e.data;!t||t.source!==`grok-auth-popup`||a(t.token??null)},s=window.setInterval(()=>{e.closed&&(window.clearInterval(s),i=window.setTimeout(()=>a(null),400))},300);function c(){window.clearInterval(s),i!==void 0&&window.clearTimeout(i),window.removeEventListener(`message`,o)}window.addEventListener(`message`,o)})}async function kt(e=`/`){try{await Y.signOut()}finally{Q(null)}window.location.href=e}export{kt as i,Tt as n,Et as r,Y as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/core-CwxXejkd.js b/.vercel/output/static/assets/core-CwxXejkd.js new file mode 100644 index 0000000..7eed138 --- /dev/null +++ b/.vercel/output/static/assets/core-CwxXejkd.js @@ -0,0 +1 @@ +async function e(e,t={},n){return window.__TAURI_INTERNALS__.invoke(e,t,n)}export{e as invoke}; \ No newline at end of file diff --git a/.vercel/output/static/assets/cose-bilkent-JH36ORCC-jfFAOGFt.js b/.vercel/output/static/assets/cose-bilkent-JH36ORCC-ClqQrHIF.js similarity index 99% rename from .vercel/output/static/assets/cose-bilkent-JH36ORCC-jfFAOGFt.js rename to .vercel/output/static/assets/cose-bilkent-JH36ORCC-ClqQrHIF.js index 0ac068d..ad06af1 100644 --- a/.vercel/output/static/assets/cose-bilkent-JH36ORCC-jfFAOGFt.js +++ b/.vercel/output/static/assets/cose-bilkent-JH36ORCC-ClqQrHIF.js @@ -1 +1 @@ -import{r as e,t}from"./rolldown-runtime-QTnfLwEv.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as r,p as i}from"./src-_wZywoZs.js";import{t as a}from"./cytoscape.esm-CQFVGiJu.js";var o=t(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.layoutBase=r():n.layoutBase=r()})(e,function(){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=26)})([(function(e,t,n){function r(){}r.QUALITY=1,r.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,r.DEFAULT_INCREMENTAL=!1,r.DEFAULT_ANIMATION_ON_LAYOUT=!0,r.DEFAULT_ANIMATION_DURING_LAYOUT=!1,r.DEFAULT_ANIMATION_PERIOD=50,r.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,r.DEFAULT_GRAPH_MARGIN=15,r.NODE_DIMENSIONS_INCLUDE_LABELS=!1,r.SIMPLE_NODE_SIZE=40,r.SIMPLE_NODE_HALF_SIZE=r.SIMPLE_NODE_SIZE/2,r.EMPTY_COMPOUND_NODE_SIZE=40,r.MIN_EDGE_LENGTH=1,r.WORLD_BOUNDARY=1e6,r.INITIAL_WORLD_BOUNDARY=r.WORLD_BOUNDARY/1e3,r.WORLD_CENTER_X=1200,r.WORLD_CENTER_Y=900,e.exports=r}),(function(e,t,n){var r=n(2),i=n(8),a=n(9);function o(e,t,n){r.call(this,n),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=n,this.bendpoints=[],this.source=e,this.target=t}for(var s in o.prototype=Object.create(r.prototype),r)o[s]=r[s];o.prototype.getSource=function(){return this.source},o.prototype.getTarget=function(){return this.target},o.prototype.isInterGraph=function(){return this.isInterGraph},o.prototype.getLength=function(){return this.length},o.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},o.prototype.getBendpoints=function(){return this.bendpoints},o.prototype.getLca=function(){return this.lca},o.prototype.getSourceInLca=function(){return this.sourceInLca},o.prototype.getTargetInLca=function(){return this.targetInLca},o.prototype.getOtherEnd=function(e){if(this.source===e)return this.target;if(this.target===e)return this.source;throw`Node is not incident with this edge`},o.prototype.getOtherEndInGraph=function(e,t){for(var n=this.getOtherEnd(e),r=t.getGraphManager().getRoot();;){if(n.getOwner()==t)return n;if(n.getOwner()==r)break;n=n.getOwner().getParent()}return null},o.prototype.updateLength=function(){var e=[,,,,];this.isOverlapingSourceAndTarget=i.getIntersection(this.target.getRect(),this.source.getRect(),e),this.isOverlapingSourceAndTarget||(this.lengthX=e[0]-e[2],this.lengthY=e[1]-e[3],Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},o.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},e.exports=o}),(function(e,t,n){function r(e){this.vGraphObject=e}e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(13),o=n(0),s=n(16),c=n(4);function l(e,t,n,o){n==null&&o==null&&(o=t),r.call(this,o),e.graphManager!=null&&(e=e.graphManager),this.estimatedSize=i.MIN_VALUE,this.inclusionTreeDepth=i.MAX_VALUE,this.vGraphObject=o,this.edges=[],this.graphManager=e,n!=null&&t!=null?this.rect=new a(t.x,t.y,n.width,n.height):this.rect=new a}for(var u in l.prototype=Object.create(r.prototype),r)l[u]=r[u];l.prototype.getEdges=function(){return this.edges},l.prototype.getChild=function(){return this.child},l.prototype.getOwner=function(){return this.owner},l.prototype.getWidth=function(){return this.rect.width},l.prototype.setWidth=function(e){this.rect.width=e},l.prototype.getHeight=function(){return this.rect.height},l.prototype.setHeight=function(e){this.rect.height=e},l.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},l.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},l.prototype.getCenter=function(){return new c(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},l.prototype.getLocation=function(){return new c(this.rect.x,this.rect.y)},l.prototype.getRect=function(){return this.rect},l.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},l.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},l.prototype.setRect=function(e,t){this.rect.x=e.x,this.rect.y=e.y,this.rect.width=t.width,this.rect.height=t.height},l.prototype.setCenter=function(e,t){this.rect.x=e-this.rect.width/2,this.rect.y=t-this.rect.height/2},l.prototype.setLocation=function(e,t){this.rect.x=e,this.rect.y=t},l.prototype.moveBy=function(e,t){this.rect.x+=e,this.rect.y+=t},l.prototype.getEdgeListToNode=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(r.target==e){if(r.source!=n)throw`Incorrect edge source!`;t.push(r)}}),t},l.prototype.getEdgesBetween=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(!(r.source==n||r.target==n))throw`Incorrect edge source and/or target`;(r.target==e||r.source==e)&&t.push(r)}),t},l.prototype.getNeighborsList=function(){var e=new Set,t=this;return t.edges.forEach(function(n){if(n.source==t)e.add(n.target);else{if(n.target!=t)throw`Incorrect incidency!`;e.add(n.source)}}),e},l.prototype.withChildren=function(){var e=new Set,t,n;if(e.add(this),this.child!=null)for(var r=this.child.getNodes(),i=0;it&&(this.rect.x-=(this.labelWidth-t)/2,this.setWidth(this.labelWidth)),this.labelHeight>n&&(this.labelPos==`center`?this.rect.y-=(this.labelHeight-n)/2:this.labelPos==`top`&&(this.rect.y-=this.labelHeight-n),this.setHeight(this.labelHeight))}}},l.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==i.MAX_VALUE)throw`assert failed`;return this.inclusionTreeDepth},l.prototype.transform=function(e){var t=this.rect.x;t>o.WORLD_BOUNDARY?t=o.WORLD_BOUNDARY:t<-o.WORLD_BOUNDARY&&(t=-o.WORLD_BOUNDARY);var n=this.rect.y;n>o.WORLD_BOUNDARY?n=o.WORLD_BOUNDARY:n<-o.WORLD_BOUNDARY&&(n=-o.WORLD_BOUNDARY);var r=new c(t,n),i=e.inverseTransformPoint(r);this.setLocation(i.x,i.y)},l.prototype.getLeft=function(){return this.rect.x},l.prototype.getRight=function(){return this.rect.x+this.rect.width},l.prototype.getTop=function(){return this.rect.y},l.prototype.getBottom=function(){return this.rect.y+this.rect.height},l.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},e.exports=l}),(function(e,t,n){function r(e,t){e==null&&t==null?(this.x=0,this.y=0):(this.x=e,this.y=t)}r.prototype.getX=function(){return this.x},r.prototype.getY=function(){return this.y},r.prototype.setX=function(e){this.x=e},r.prototype.setY=function(e){this.y=e},r.prototype.getDifference=function(e){return new DimensionD(this.x-e.x,this.y-e.y)},r.prototype.getCopy=function(){return new r(this.x,this.y)},r.prototype.translate=function(e){return this.x+=e.width,this.y+=e.height,this},e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(0),o=n(6),s=n(3),c=n(1),l=n(13),u=n(12),d=n(11);function f(e,t,n){r.call(this,n),this.estimatedSize=i.MIN_VALUE,this.margin=a.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=e,t!=null&&t instanceof o?this.graphManager=t:t!=null&&t instanceof Layout&&(this.graphManager=t.graphManager)}for(var p in f.prototype=Object.create(r.prototype),r)f[p]=r[p];f.prototype.getNodes=function(){return this.nodes},f.prototype.getEdges=function(){return this.edges},f.prototype.getGraphManager=function(){return this.graphManager},f.prototype.getParent=function(){return this.parent},f.prototype.getLeft=function(){return this.left},f.prototype.getRight=function(){return this.right},f.prototype.getTop=function(){return this.top},f.prototype.getBottom=function(){return this.bottom},f.prototype.isConnected=function(){return this.isConnected},f.prototype.add=function(e,t,n){if(t==null&&n==null){var r=e;if(this.graphManager==null)throw`Graph has no graph mgr!`;if(this.getNodes().indexOf(r)>-1)throw`Node already in graph!`;return r.owner=this,this.getNodes().push(r),r}else{var i=e;if(!(this.getNodes().indexOf(t)>-1&&this.getNodes().indexOf(n)>-1))throw`Source or target not in graph!`;if(!(t.owner==n.owner&&t.owner==this))throw`Both owners must be this graph!`;return t.owner==n.owner?(i.source=t,i.target=n,i.isInterGraph=!1,this.getEdges().push(i),t.edges.push(i),n!=t&&n.edges.push(i),i):null}},f.prototype.remove=function(e){var t=e;if(e instanceof s){if(t==null)throw`Node is null!`;if(!(t.owner!=null&&t.owner==this))throw`Owner graph is invalid!`;if(this.graphManager==null)throw`Owner graph manager is invalid!`;for(var n=t.edges.slice(),r,i=n.length,a=0;a-1&&u>-1))throw`Source and/or target doesn't know this edge!`;r.source.edges.splice(l,1),r.target!=r.source&&r.target.edges.splice(u,1);var o=r.source.owner.getEdges().indexOf(r);if(o==-1)throw`Not in owner's edge list!`;r.source.owner.getEdges().splice(o,1)}},f.prototype.updateLeftTop=function(){for(var e=i.MAX_VALUE,t=i.MAX_VALUE,n,r,a,o=this.getNodes(),s=o.length,c=0;cn&&(e=n),t>r&&(t=r)}return e==i.MAX_VALUE?null:(a=o[0].getParent().paddingLeft==null?this.margin:o[0].getParent().paddingLeft,this.left=t-a,this.top=e-a,new u(this.left,this.top))},f.prototype.updateBounds=function(e){for(var t=i.MAX_VALUE,n=-i.MAX_VALUE,r=i.MAX_VALUE,a=-i.MAX_VALUE,o,s,c,u,d,f=this.nodes,p=f.length,m=0;mo&&(t=o),nc&&(r=c),ao&&(t=o),nc&&(r=c),a=this.nodes.length){var c=0;n.forEach(function(t){t.owner==e&&c++}),c==this.nodes.length&&(this.isConnected=!0)}},e.exports=f}),(function(e,t,n){var r,i=n(1);function a(e){r=n(5),this.layout=e,this.graphs=[],this.edges=[]}a.prototype.addRoot=function(){var e=this.layout.newGraph(),t=this.layout.newNode(null),n=this.add(e,t);return this.setRootGraph(n),this.rootGraph},a.prototype.add=function(e,t,n,r,i){if(n==null&&r==null&&i==null){if(e==null)throw`Graph is null!`;if(t==null)throw`Parent node is null!`;if(this.graphs.indexOf(e)>-1)throw`Graph already in this graph mgr!`;if(this.graphs.push(e),e.parent!=null)throw`Already has a parent!`;if(t.child!=null)throw`Already has a child!`;return e.parent=t,t.child=e,e}else{i=n,r=t,n=e;var a=r.getOwner(),o=i.getOwner();if(!(a!=null&&a.getGraphManager()==this))throw`Source not in this graph mgr!`;if(!(o!=null&&o.getGraphManager()==this))throw`Target not in this graph mgr!`;if(a==o)return n.isInterGraph=!1,a.add(n,r,i);if(n.isInterGraph=!0,n.source=r,n.target=i,this.edges.indexOf(n)>-1)throw`Edge already in inter-graph edge list!`;if(this.edges.push(n),!(n.source!=null&&n.target!=null))throw`Edge source and/or target is null!`;if(!(n.source.edges.indexOf(n)==-1&&n.target.edges.indexOf(n)==-1))throw`Edge already in source and/or target incidency list!`;return n.source.edges.push(n),n.target.edges.push(n),n}},a.prototype.remove=function(e){if(e instanceof r){var t=e;if(t.getGraphManager()!=this)throw`Graph not in this graph mgr`;if(!(t==this.rootGraph||t.parent!=null&&t.parent.graphManager==this))throw`Invalid parent node!`;var n=[];n=n.concat(t.getEdges());for(var a,o=n.length,s=0;s=t.getRight()?n[0]+=Math.min(t.getX()-e.getX(),e.getRight()-t.getRight()):t.getX()<=e.getX()&&t.getRight()>=e.getRight()&&(n[0]+=Math.min(e.getX()-t.getX(),t.getRight()-e.getRight())),e.getY()<=t.getY()&&e.getBottom()>=t.getBottom()?n[1]+=Math.min(t.getY()-e.getY(),e.getBottom()-t.getBottom()):t.getY()<=e.getY()&&t.getBottom()>=e.getBottom()&&(n[1]+=Math.min(e.getY()-t.getY(),t.getBottom()-e.getBottom()));var a=Math.abs((t.getCenterY()-e.getCenterY())/(t.getCenterX()-e.getCenterX()));t.getCenterY()===e.getCenterY()&&t.getCenterX()===e.getCenterX()&&(a=1);var o=a*n[0],s=n[1]/a;n[0]o)return n[0]=r,n[1]=c,n[2]=a,n[3]=y,!1;if(ia)return n[0]=s,n[1]=i,n[2]=_,n[3]=o,!1;if(ra?(n[0]=u,n[1]=d,C=!0):(n[0]=l,n[1]=c,C=!0):T===D&&(r>a?(n[0]=s,n[1]=c,C=!0):(n[0]=f,n[1]=d,C=!0)),-E===D?a>r?(n[2]=v,n[3]=y,w=!0):(n[2]=_,n[3]=g,w=!0):E===D&&(a>r?(n[2]=h,n[3]=g,w=!0):(n[2]=b,n[3]=y,w=!0)),C&&w)return!1;if(r>a?i>o?(O=this.getCardinalDirection(T,D,4),k=this.getCardinalDirection(E,D,2)):(O=this.getCardinalDirection(-T,D,3),k=this.getCardinalDirection(-E,D,1)):i>o?(O=this.getCardinalDirection(-T,D,1),k=this.getCardinalDirection(-E,D,3)):(O=this.getCardinalDirection(T,D,2),k=this.getCardinalDirection(E,D,4)),!C)switch(O){case 1:j=c,A=r+-m/D,n[0]=A,n[1]=j;break;case 2:A=f,j=i+p*D,n[0]=A,n[1]=j;break;case 3:j=d,A=r+m/D,n[0]=A,n[1]=j;break;case 4:A=u,j=i+-p*D,n[0]=A,n[1]=j;break}if(!w)switch(k){case 1:N=g,M=a+-S/D,n[2]=M,n[3]=N;break;case 2:M=b,N=o+x*D,n[2]=M,n[3]=N;break;case 3:N=y,M=a+S/D,n[2]=M,n[3]=N;break;case 4:M=v,N=o+-x*D,n[2]=M,n[3]=N;break}}return!1},i.getCardinalDirection=function(e,t,n){return e>t?n:1+n%4},i.getIntersection=function(e,t,n,i){if(i==null)return this.getIntersection2(e,t,n);var a=e.x,o=e.y,s=t.x,c=t.y,l=n.x,u=n.y,d=i.x,f=i.y,p=void 0,m=void 0,h=void 0,g=void 0,_=void 0,v=void 0,y=void 0,b=void 0,x=void 0;return h=c-o,_=a-s,y=s*o-a*c,g=f-u,v=l-d,b=d*u-l*f,x=h*v-g*_,x===0?null:(p=(_*b-v*y)/x,m=(g*y-h*b)/x,new r(p,m))},i.angleOfVector=function(e,t,n,r){var i=void 0;return e===n?i=r0?1:e<0?-1:0},r.floor=function(e){return e<0?Math.ceil(e):Math.floor(e)},r.ceil=function(e){return e<0?Math.floor(e):Math.ceil(e)},e.exports=r}),(function(e,t,n){function r(){}r.MAX_VALUE=2147483647,r.MIN_VALUE=-2147483648,e.exports=r}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n0&&t;){for(s.push(l[0]);s.length>0&&t;){var u=s[0];s.splice(0,1),o.add(u);for(var d=u.getEdges(),a=0;a-1&&l.splice(h,1)}o=new Set,c=new Map}}return e},f.prototype.createDummyNodesForBendpoints=function(e){for(var t=[],n=e.source,r=this.graphManager.calcLowestCommonAncestor(e.source,e.target),i=0;i0){for(var i=this.edgeToDummyNodes.get(n),a=0;a=0&&t.splice(d,1),s.getNeighborsList().forEach(function(e){if(n.indexOf(e)<0){var t=r.get(e)-1;t==1&&l.push(e),r.set(e,t)}})}n=n.concat(l),(t.length==1||t.length==2)&&(i=!0,a=t[0])}return a},f.prototype.setGraphManager=function(e){this.graphManager=e},e.exports=f}),(function(e,t,n){function r(){}r.seed=1,r.x=0,r.nextDouble=function(){return r.x=Math.sin(r.seed++)*1e4,r.x-Math.floor(r.x)},e.exports=r}),(function(e,t,n){var r=n(4);function i(e,t){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}i.prototype.getWorldOrgX=function(){return this.lworldOrgX},i.prototype.setWorldOrgX=function(e){this.lworldOrgX=e},i.prototype.getWorldOrgY=function(){return this.lworldOrgY},i.prototype.setWorldOrgY=function(e){this.lworldOrgY=e},i.prototype.getWorldExtX=function(){return this.lworldExtX},i.prototype.setWorldExtX=function(e){this.lworldExtX=e},i.prototype.getWorldExtY=function(){return this.lworldExtY},i.prototype.setWorldExtY=function(e){this.lworldExtY=e},i.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},i.prototype.setDeviceOrgX=function(e){this.ldeviceOrgX=e},i.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},i.prototype.setDeviceOrgY=function(e){this.ldeviceOrgY=e},i.prototype.getDeviceExtX=function(){return this.ldeviceExtX},i.prototype.setDeviceExtX=function(e){this.ldeviceExtX=e},i.prototype.getDeviceExtY=function(){return this.ldeviceExtY},i.prototype.setDeviceExtY=function(e){this.ldeviceExtY=e},i.prototype.transformX=function(e){var t=0,n=this.lworldExtX;return n!=0&&(t=this.ldeviceOrgX+(e-this.lworldOrgX)*this.ldeviceExtX/n),t},i.prototype.transformY=function(e){var t=0,n=this.lworldExtY;return n!=0&&(t=this.ldeviceOrgY+(e-this.lworldOrgY)*this.ldeviceExtY/n),t},i.prototype.inverseTransformX=function(e){var t=0,n=this.ldeviceExtX;return n!=0&&(t=this.lworldOrgX+(e-this.ldeviceOrgX)*this.lworldExtX/n),t},i.prototype.inverseTransformY=function(e){var t=0,n=this.ldeviceExtY;return n!=0&&(t=this.lworldOrgY+(e-this.ldeviceOrgY)*this.lworldExtY/n),t},i.prototype.inverseTransformPoint=function(e){return new r(this.inverseTransformX(e.x),this.inverseTransformY(e.y))},e.exports=i}),(function(e,t,n){function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);ta.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*a.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-a.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT_INCREMENTAL):(e>a.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(a.COOLING_ADAPTATION_FACTOR,1-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*(1-a.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},l.prototype.calcSpringForces=function(){for(var e=this.getAllEdges(),t,n=0;n0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n,r,i,o,s=this.getAllNodes(),c;if(this.useFRGridVariant)for(this.totalIterations%a.GRID_CALCULATION_CHECK_PERIOD==1&&e&&this.updateGrid(),c=new Set,n=0;nc||s>c)&&(e.gravitationForceX=-this.gravityConstant*i,e.gravitationForceY=-this.gravityConstant*a)):(c=t.getEstimatedSize()*this.compoundGravityRangeFactor,(o>c||s>c)&&(e.gravitationForceX=-this.gravityConstant*i*this.compoundGravityConstant,e.gravitationForceY=-this.gravityConstant*a*this.compoundGravityConstant))},l.prototype.isConverged=function(){var e,t=!1;return this.totalIterations>this.maxIterations/3&&(t=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),e=this.totalDisplacement=c.length||u>=c[0].length)){for(var d=0;de}}]),e}()}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;i(this,e),this.sequence1=t,this.sequence2=n,this.match_score=r,this.mismatch_penalty=a,this.gap_penalty=o,this.iMax=t.length+1,this.jMax=n.length+1,this.grid=Array(this.iMax);for(var s=0;s=0;n--){var r=this.listeners[n];r.event===e&&r.callback===t&&this.listeners.splice(n,1)}},i.emit=function(e,t){for(var n=0;n{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(o()):typeof define==`function`&&define.amd?define([`layout-base`],r):typeof e==`object`?e.coseBase=r(o()):n.coseBase=r(n.layoutBase)})(e,function(e){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=7)})([(function(t,n){t.exports=e}),(function(e,t,n){var r=n(0).FDLayoutConstants;function i(){}for(var a in r)i[a]=r[a];i.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,i.DEFAULT_RADIAL_SEPARATION=r.DEFAULT_EDGE_LENGTH,i.DEFAULT_COMPONENT_SEPERATION=60,i.TILE=!0,i.TILING_PADDING_VERTICAL=10,i.TILING_PADDING_HORIZONTAL=10,i.TREE_REDUCTION_ON_INCREMENTAL=!1,e.exports=i}),(function(e,t,n){var r=n(0).FDLayoutEdge;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),(function(e,t,n){var r=n(0).LGraph;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),(function(e,t,n){var r=n(0).LGraphManager;function i(e){r.call(this,e)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),(function(e,t,n){var r=n(0).FDLayoutNode,i=n(0).IMath;function a(e,t,n,i){r.call(this,e,t,n,i)}for(var o in a.prototype=Object.create(r.prototype),r)a[o]=r[o];a.prototype.move=function(){var e=this.graphManager.getLayout();this.displacementX=e.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY=e.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren,Math.abs(this.displacementX)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementX=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementX)),Math.abs(this.displacementY)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementY=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementY)),this.child==null||this.child.getNodes().length==0?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),e.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},a.prototype.propogateDisplacementToChildren=function(e,t){for(var n=this.getChild().getNodes(),r,i=0;i0)this.positionNodesRadially(e);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n),this.positionNodesRandomly()}}else if(c.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n)}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},v.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%l.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-this.coolingCycle**+(Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),t=this.nodesWithGravity.filter(function(t){return e.has(t)});this.graphManager.setAllNodesToApplyGravitation(t),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var n=!this.isTreeGrowing&&!this.isGrowthFinished,r=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(n,r),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},v.prototype.getPositionsData=function(){for(var e=this.graphManager.getAllNodes(),t={},n=0;n1){var s;for(s=0;sr&&(r=Math.floor(o.y)),a=Math.floor(o.x+c.DEFAULT_COMPONENT_SEPERATION)}this.transform(new f(u.WORLD_CENTER_X-o.x/2,u.WORLD_CENTER_Y-o.y/2))},v.radialLayout=function(e,t,n){var r=Math.max(this.maxDiagonalInTree(e),c.DEFAULT_RADIAL_SEPARATION);v.branchRadialLayout(t,null,0,359,0,r);var i=g.calculateBounds(e),a=new _;a.setDeviceOrgX(i.getMinX()),a.setDeviceOrgY(i.getMinY()),a.setWorldOrgX(n.x),a.setWorldOrgY(n.y);for(var o=0;o1;){var _=g[0];g.splice(0,1);var y=u.indexOf(_);y>=0&&u.splice(y,1),p--,d--}m=t==null?0:(u.indexOf(g[0])+1)%p;for(var b=Math.abs(r-n)/d,x=m;f!=d;x=++x%p){var S=u[x].getOtherEnd(e);if(S!=t){var C=(n+f*b)%360,w=(C+b)%360;v.branchRadialLayout(S,e,C,w,i+a,a),f++}}},v.maxDiagonalInTree=function(e){for(var t=m.MIN_VALUE,n=0;nt&&(t=r)}return t},v.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},v.prototype.groupZeroDegreeMembers=function(){var e=this,t={};this.memberGroups={},this.idToDummyNode={};for(var n=[],r=this.graphManager.getAllNodes(),i=0;i1){var r=`DummyCompound_`+n;e.memberGroups[r]=t[n];var i=t[n][0].getParent(),a=new o(e.graphManager);a.id=r,a.paddingLeft=i.paddingLeft||0,a.paddingRight=i.paddingRight||0,a.paddingBottom=i.paddingBottom||0,a.paddingTop=i.paddingTop||0,e.idToDummyNode[r]=a;var s=e.getGraphManager().add(e.newGraph(),a),c=i.getChild();c.add(a);for(var l=0;l=0;e--){var t=this.compoundOrder[e],n=t.id,r=t.paddingLeft,i=t.paddingTop;this.adjustLocations(this.tiledMemberPack[n],t.rect.x,t.rect.y,r,i)}},v.prototype.repopulateZeroDegreeMembers=function(){var e=this,t=this.tiledZeroDegreePack;Object.keys(t).forEach(function(n){var r=e.idToDummyNode[n],i=r.paddingLeft,a=r.paddingTop;e.adjustLocations(t[n],r.rect.x,r.rect.y,i,a)})},v.prototype.getToBeTiled=function(e){var t=e.id;if(this.toBeTiled[t]!=null)return this.toBeTiled[t];var n=e.getChild();if(n==null)return this.toBeTiled[t]=!1,!1;for(var r=n.getNodes(),i=0;i0)return this.toBeTiled[t]=!1,!1;if(a.getChild()==null){this.toBeTiled[a.id]=!1;continue}if(!this.getToBeTiled(a))return this.toBeTiled[t]=!1,!1}return this.toBeTiled[t]=!0,!0},v.prototype.getNodeDegree=function(e){e.id;for(var t=e.getEdges(),n=0,r=0;rc&&(c=u.rect.height)}n+=c+e.verticalPadding}},v.prototype.tileCompoundMembers=function(e,t){var n=this;this.tiledMemberPack=[],Object.keys(e).forEach(function(r){var i=t[r];n.tiledMemberPack[r]=n.tileNodes(e[r],i.paddingLeft+i.paddingRight),i.rect.width=n.tiledMemberPack[r].width,i.rect.height=n.tiledMemberPack[r].height})},v.prototype.tileNodes=function(e,t){var n={rows:[],rowWidth:[],rowHeight:[],width:0,height:t,verticalPadding:c.TILING_PADDING_VERTICAL,horizontalPadding:c.TILING_PADDING_HORIZONTAL};e.sort(function(e,t){return e.rect.width*e.rect.height>t.rect.width*t.rect.height?-1:+(e.rect.width*e.rect.height0&&(a+=e.horizontalPadding),e.rowWidth[n]=a,e.width0&&(o+=e.verticalPadding);var s=0;o>e.rowHeight[n]&&(s=e.rowHeight[n],e.rowHeight[n]=o,s=e.rowHeight[n]-s),e.height+=s,e.rows[n].push(t)},v.prototype.getShortestRowIndex=function(e){for(var t=-1,n=Number.MAX_VALUE,r=0;rn&&(t=r,n=e.rowWidth[r]);return t},v.prototype.canAddHorizontal=function(e,t,n){var r=this.getShortestRowIndex(e);if(r<0)return!0;var i=e.rowWidth[r];if(i+e.horizontalPadding+t<=e.width)return!0;var a=0;e.rowHeight[r]0&&(a=n+e.verticalPadding-e.rowHeight[r]);var o=e.width-i>=t+e.horizontalPadding?(e.height+a)/(i+t+e.horizontalPadding):(e.height+a)/e.width;a=n+e.verticalPadding;var s=e.widtha&&t!=n){r.splice(-1,1),e.rows[n].push(i),e.rowWidth[t]=e.rowWidth[t]-a,e.rowWidth[n]=e.rowWidth[n]+a,e.width=e.rowWidth[instance.getLongestRowIndex(e)];for(var o=Number.MIN_VALUE,s=0;so&&(o=r[s].height);t>0&&(o+=e.verticalPadding);var c=e.rowHeight[t]+e.rowHeight[n];e.rowHeight[t]=o,e.rowHeight[n]0)for(var u=i;u<=a;u++)c[0]+=this.grid[u][o-1].length+this.grid[u][o].length-1;if(a0)for(var u=o;u<=s;u++)c[3]+=this.grid[i-1][u].length+this.grid[i][u].length-1;for(var d=m.MAX_VALUE,f,p,h=0;h{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(s()):typeof define==`function`&&define.amd?define([`cose-base`],r):typeof e==`object`?e.cytoscapeCoseBilkent=r(s()):n.cytoscapeCoseBilkent=r(n.coseBase)})(e,function(e){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=1)})([(function(t,n){t.exports=e}),(function(e,t,n){var r=n(0).layoutBase.LayoutConstants,i=n(0).layoutBase.FDLayoutConstants,a=n(0).CoSEConstants,o=n(0).CoSELayout,s=n(0).CoSENode,c=n(0).layoutBase.PointD,l=n(0).layoutBase.DimensionD,u={ready:function(){},stop:function(){},quality:`default`,nodeDimensionsIncludeLabels:!1,refresh:30,fit:!0,padding:10,randomize:!0,nodeRepulsion:4500,idealEdgeLength:50,edgeElasticity:.45,nestingFactor:.1,gravity:.25,numIter:2500,tile:!0,animate:`end`,animationDuration:500,tilingPaddingVertical:10,tilingPaddingHorizontal:10,gravityRangeCompound:1.5,gravityCompound:1,gravityRange:3.8,initialEnergyOnIncremental:.5};function d(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n}function f(e){this.options=d(u,e),p(this.options)}var p=function(e){e.nodeRepulsion!=null&&(a.DEFAULT_REPULSION_STRENGTH=i.DEFAULT_REPULSION_STRENGTH=e.nodeRepulsion),e.idealEdgeLength!=null&&(a.DEFAULT_EDGE_LENGTH=i.DEFAULT_EDGE_LENGTH=e.idealEdgeLength),e.edgeElasticity!=null&&(a.DEFAULT_SPRING_STRENGTH=i.DEFAULT_SPRING_STRENGTH=e.edgeElasticity),e.nestingFactor!=null&&(a.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=i.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=e.nestingFactor),e.gravity!=null&&(a.DEFAULT_GRAVITY_STRENGTH=i.DEFAULT_GRAVITY_STRENGTH=e.gravity),e.numIter!=null&&(a.MAX_ITERATIONS=i.MAX_ITERATIONS=e.numIter),e.gravityRange!=null&&(a.DEFAULT_GRAVITY_RANGE_FACTOR=i.DEFAULT_GRAVITY_RANGE_FACTOR=e.gravityRange),e.gravityCompound!=null&&(a.DEFAULT_COMPOUND_GRAVITY_STRENGTH=i.DEFAULT_COMPOUND_GRAVITY_STRENGTH=e.gravityCompound),e.gravityRangeCompound!=null&&(a.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=i.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=e.gravityRangeCompound),e.initialEnergyOnIncremental!=null&&(a.DEFAULT_COOLING_FACTOR_INCREMENTAL=i.DEFAULT_COOLING_FACTOR_INCREMENTAL=e.initialEnergyOnIncremental),e.quality==`draft`?r.QUALITY=0:e.quality==`proof`?r.QUALITY=2:r.QUALITY=1,a.NODE_DIMENSIONS_INCLUDE_LABELS=i.NODE_DIMENSIONS_INCLUDE_LABELS=r.NODE_DIMENSIONS_INCLUDE_LABELS=e.nodeDimensionsIncludeLabels,a.DEFAULT_INCREMENTAL=i.DEFAULT_INCREMENTAL=r.DEFAULT_INCREMENTAL=!e.randomize,a.ANIMATE=i.ANIMATE=r.ANIMATE=e.animate,a.TILE=e.tile,a.TILING_PADDING_VERTICAL=typeof e.tilingPaddingVertical==`function`?e.tilingPaddingVertical.call():e.tilingPaddingVertical,a.TILING_PADDING_HORIZONTAL=typeof e.tilingPaddingHorizontal==`function`?e.tilingPaddingHorizontal.call():e.tilingPaddingHorizontal};f.prototype.run=function(){var e,t,n=this.options;this.idToLNode={};var r=this.layout=new o,i=this;i.stopped=!1,this.cy=this.options.cy,this.cy.trigger({type:`layoutstart`,layout:this});var a=r.newGraphManager();this.gm=a;var s=this.options.eles.nodes(),c=this.options.eles.edges();this.root=a.addRoot(),this.processChildrenList(this.root,this.getTopMostNodes(s),r);for(var l=0;l0){var h=n.getGraphManager().add(n.newGraph(),u);this.processChildrenList(h,o,n)}}},f.prototype.stop=function(){return this.stopped=!0,this};var m=function(e){e(`layout`,`cose-bilkent`,f)};typeof cytoscape<`u`&&m(cytoscape),e.exports=m})])})}))(),1);a.use(c.default);function l(e,t){e.forEach(e=>{let n={id:e.id,labelText:e.label,height:e.height,width:e.width,padding:e.padding??0};Object.keys(e).forEach(t=>{[`id`,`label`,`height`,`width`,`padding`,`x`,`y`].includes(t)||(n[t]=e[t])}),t.add({group:`nodes`,data:n,position:{x:e.x??0,y:e.y??0}})})}n(l,`addNodes`);function u(e,t){e.forEach(e=>{let n={id:e.id,source:e.start,target:e.end};Object.keys(e).forEach(t=>{[`id`,`start`,`end`].includes(t)||(n[t]=e[t])}),t.add({group:`edges`,data:n})})}n(u,`addEdges`);function d(e){return new Promise(t=>{let n=i(`body`).append(`div`).attr(`id`,`cy`).attr(`style`,`display:none`),o=a({container:document.getElementById(`cy`),style:[{selector:`edge`,style:{"curve-style":`bezier`}}]});n.remove(),l(e.nodes,o),u(e.edges,o),o.nodes().forEach(function(e){e.layoutDimensions=()=>{let t=e.data();return{w:t.width,h:t.height}}}),o.layout({name:`cose-bilkent`,quality:`proof`,styleEnabled:!1,animate:!1}).run(),o.ready(e=>{r.info(`Cytoscape ready`,e),t(o)})})}n(d,`createCytoscapeInstance`);function f(e){return e.nodes().map(e=>{let t=e.data(),n=e.position(),r={id:t.id,x:n.x,y:n.y};return Object.keys(t).forEach(e=>{e!==`id`&&(r[e]=t[e])}),r})}n(f,`extractPositionedNodes`);function p(e){return e.edges().map(e=>{let t=e.data(),n=e._private.rscratch,r={id:t.id,source:t.source,target:t.target,startX:n.startX,startY:n.startY,midX:n.midX,midY:n.midY,endX:n.endX,endY:n.endY};return Object.keys(t).forEach(e=>{[`id`,`source`,`target`].includes(e)||(r[e]=t[e])}),r})}n(p,`extractPositionedEdges`);async function m(e,t){r.debug(`Starting cose-bilkent layout algorithm`);try{h(e);let t=await d(e),n=f(t),i=p(t);return r.debug(`Layout completed: ${n.length} nodes, ${i.length} edges`),{nodes:n,edges:i}}catch(e){throw r.error(`Error in cose-bilkent layout algorithm:`,e),e}}n(m,`executeCoseBilkentLayout`);function h(e){if(!e)throw Error(`Layout data is required`);if(!e.config)throw Error(`Configuration is required in layout data`);if(!e.rootNode)throw Error(`Root node is required`);if(!e.nodes||!Array.isArray(e.nodes))throw Error(`No nodes found in layout data`);if(!Array.isArray(e.edges))throw Error(`Edges array is required in layout data`);return!0}n(h,`validateLayoutData`);var g=n(async(e,t,{insertCluster:n,insertEdge:r,insertEdgeLabel:i,insertMarkers:a,insertNode:o,log:s,positionEdgeLabel:c},{algorithm:l})=>{let u={},d={},f=t.select(`g`);a(f,e.markers,e.type,e.diagramId);let p=f.insert(`g`).attr(`class`,`subgraphs`),h=f.insert(`g`).attr(`class`,`edgePaths`),g=f.insert(`g`).attr(`class`,`edgeLabels`),_=f.insert(`g`).attr(`class`,`nodes`);s.debug(`Inserting nodes into DOM for dimension calculation`),await Promise.all(e.nodes.map(async t=>{if(t.isGroup){let e={...t};d[t.id]=e,u[t.id]=e,await n(p,t)}else{let n={...t};u[t.id]=n;let r=await o(_,t,{config:e.config,dir:e.direction||`TB`}),i=r.node().getBBox();n.width=i.width,n.height=i.height,n.domId=r,s.debug(`Node ${t.id} dimensions: ${i.width}x${i.height}`)}})),s.debug(`Running cose-bilkent layout algorithm`);let v=await m({...e,nodes:e.nodes.map(e=>{let t=u[e.id];return{...e,width:t.width,height:t.height}})},e.config);s.debug(`Positioning nodes based on layout results`),v.nodes.forEach(e=>{let t=u[e.id];t?.domId&&(t.domId.attr(`transform`,`translate(${e.x}, ${e.y})`),t.x=e.x,t.y=e.y,s.debug(`Positioned node ${t.id} at center (${e.x}, ${e.y})`))}),v.edges.forEach(t=>{let n=e.edges.find(e=>e.id===t.id);n&&(n.points=[{x:t.startX,y:t.startY},{x:t.midX,y:t.midY},{x:t.endX,y:t.endY}])}),s.debug(`Inserting and positioning edges`),await Promise.all(e.edges.map(async t=>{await i(g,t);let n=u[t.start??``],a=u[t.end??``];if(n&&a){let i=v.edges.find(e=>e.id===t.id);if(i){s.debug(`APA01 positionedEdge`,i);let o={...t};c(o,r(h,o,d,e.type,n,a,e.diagramId))}else{let i={...t,points:[{x:n.x||0,y:n.y||0},{x:a.x||0,y:a.y||0}]};c(i,r(h,i,d,e.type,n,a,e.diagramId))}}})),s.debug(`Cose-bilkent rendering completed`)},`render`);export{g as render}; \ No newline at end of file +import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as r,p as i}from"./src-UMNXGZaF.js";import{t as a}from"./cytoscape.esm-CQFVGiJu.js";var o=t(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.layoutBase=r():n.layoutBase=r()})(e,function(){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=26)})([(function(e,t,n){function r(){}r.QUALITY=1,r.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,r.DEFAULT_INCREMENTAL=!1,r.DEFAULT_ANIMATION_ON_LAYOUT=!0,r.DEFAULT_ANIMATION_DURING_LAYOUT=!1,r.DEFAULT_ANIMATION_PERIOD=50,r.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,r.DEFAULT_GRAPH_MARGIN=15,r.NODE_DIMENSIONS_INCLUDE_LABELS=!1,r.SIMPLE_NODE_SIZE=40,r.SIMPLE_NODE_HALF_SIZE=r.SIMPLE_NODE_SIZE/2,r.EMPTY_COMPOUND_NODE_SIZE=40,r.MIN_EDGE_LENGTH=1,r.WORLD_BOUNDARY=1e6,r.INITIAL_WORLD_BOUNDARY=r.WORLD_BOUNDARY/1e3,r.WORLD_CENTER_X=1200,r.WORLD_CENTER_Y=900,e.exports=r}),(function(e,t,n){var r=n(2),i=n(8),a=n(9);function o(e,t,n){r.call(this,n),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=n,this.bendpoints=[],this.source=e,this.target=t}for(var s in o.prototype=Object.create(r.prototype),r)o[s]=r[s];o.prototype.getSource=function(){return this.source},o.prototype.getTarget=function(){return this.target},o.prototype.isInterGraph=function(){return this.isInterGraph},o.prototype.getLength=function(){return this.length},o.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},o.prototype.getBendpoints=function(){return this.bendpoints},o.prototype.getLca=function(){return this.lca},o.prototype.getSourceInLca=function(){return this.sourceInLca},o.prototype.getTargetInLca=function(){return this.targetInLca},o.prototype.getOtherEnd=function(e){if(this.source===e)return this.target;if(this.target===e)return this.source;throw`Node is not incident with this edge`},o.prototype.getOtherEndInGraph=function(e,t){for(var n=this.getOtherEnd(e),r=t.getGraphManager().getRoot();;){if(n.getOwner()==t)return n;if(n.getOwner()==r)break;n=n.getOwner().getParent()}return null},o.prototype.updateLength=function(){var e=[,,,,];this.isOverlapingSourceAndTarget=i.getIntersection(this.target.getRect(),this.source.getRect(),e),this.isOverlapingSourceAndTarget||(this.lengthX=e[0]-e[2],this.lengthY=e[1]-e[3],Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},o.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},e.exports=o}),(function(e,t,n){function r(e){this.vGraphObject=e}e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(13),o=n(0),s=n(16),c=n(4);function l(e,t,n,o){n==null&&o==null&&(o=t),r.call(this,o),e.graphManager!=null&&(e=e.graphManager),this.estimatedSize=i.MIN_VALUE,this.inclusionTreeDepth=i.MAX_VALUE,this.vGraphObject=o,this.edges=[],this.graphManager=e,n!=null&&t!=null?this.rect=new a(t.x,t.y,n.width,n.height):this.rect=new a}for(var u in l.prototype=Object.create(r.prototype),r)l[u]=r[u];l.prototype.getEdges=function(){return this.edges},l.prototype.getChild=function(){return this.child},l.prototype.getOwner=function(){return this.owner},l.prototype.getWidth=function(){return this.rect.width},l.prototype.setWidth=function(e){this.rect.width=e},l.prototype.getHeight=function(){return this.rect.height},l.prototype.setHeight=function(e){this.rect.height=e},l.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},l.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},l.prototype.getCenter=function(){return new c(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},l.prototype.getLocation=function(){return new c(this.rect.x,this.rect.y)},l.prototype.getRect=function(){return this.rect},l.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},l.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},l.prototype.setRect=function(e,t){this.rect.x=e.x,this.rect.y=e.y,this.rect.width=t.width,this.rect.height=t.height},l.prototype.setCenter=function(e,t){this.rect.x=e-this.rect.width/2,this.rect.y=t-this.rect.height/2},l.prototype.setLocation=function(e,t){this.rect.x=e,this.rect.y=t},l.prototype.moveBy=function(e,t){this.rect.x+=e,this.rect.y+=t},l.prototype.getEdgeListToNode=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(r.target==e){if(r.source!=n)throw`Incorrect edge source!`;t.push(r)}}),t},l.prototype.getEdgesBetween=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(!(r.source==n||r.target==n))throw`Incorrect edge source and/or target`;(r.target==e||r.source==e)&&t.push(r)}),t},l.prototype.getNeighborsList=function(){var e=new Set,t=this;return t.edges.forEach(function(n){if(n.source==t)e.add(n.target);else{if(n.target!=t)throw`Incorrect incidency!`;e.add(n.source)}}),e},l.prototype.withChildren=function(){var e=new Set,t,n;if(e.add(this),this.child!=null)for(var r=this.child.getNodes(),i=0;it&&(this.rect.x-=(this.labelWidth-t)/2,this.setWidth(this.labelWidth)),this.labelHeight>n&&(this.labelPos==`center`?this.rect.y-=(this.labelHeight-n)/2:this.labelPos==`top`&&(this.rect.y-=this.labelHeight-n),this.setHeight(this.labelHeight))}}},l.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==i.MAX_VALUE)throw`assert failed`;return this.inclusionTreeDepth},l.prototype.transform=function(e){var t=this.rect.x;t>o.WORLD_BOUNDARY?t=o.WORLD_BOUNDARY:t<-o.WORLD_BOUNDARY&&(t=-o.WORLD_BOUNDARY);var n=this.rect.y;n>o.WORLD_BOUNDARY?n=o.WORLD_BOUNDARY:n<-o.WORLD_BOUNDARY&&(n=-o.WORLD_BOUNDARY);var r=new c(t,n),i=e.inverseTransformPoint(r);this.setLocation(i.x,i.y)},l.prototype.getLeft=function(){return this.rect.x},l.prototype.getRight=function(){return this.rect.x+this.rect.width},l.prototype.getTop=function(){return this.rect.y},l.prototype.getBottom=function(){return this.rect.y+this.rect.height},l.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},e.exports=l}),(function(e,t,n){function r(e,t){e==null&&t==null?(this.x=0,this.y=0):(this.x=e,this.y=t)}r.prototype.getX=function(){return this.x},r.prototype.getY=function(){return this.y},r.prototype.setX=function(e){this.x=e},r.prototype.setY=function(e){this.y=e},r.prototype.getDifference=function(e){return new DimensionD(this.x-e.x,this.y-e.y)},r.prototype.getCopy=function(){return new r(this.x,this.y)},r.prototype.translate=function(e){return this.x+=e.width,this.y+=e.height,this},e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(0),o=n(6),s=n(3),c=n(1),l=n(13),u=n(12),d=n(11);function f(e,t,n){r.call(this,n),this.estimatedSize=i.MIN_VALUE,this.margin=a.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=e,t!=null&&t instanceof o?this.graphManager=t:t!=null&&t instanceof Layout&&(this.graphManager=t.graphManager)}for(var p in f.prototype=Object.create(r.prototype),r)f[p]=r[p];f.prototype.getNodes=function(){return this.nodes},f.prototype.getEdges=function(){return this.edges},f.prototype.getGraphManager=function(){return this.graphManager},f.prototype.getParent=function(){return this.parent},f.prototype.getLeft=function(){return this.left},f.prototype.getRight=function(){return this.right},f.prototype.getTop=function(){return this.top},f.prototype.getBottom=function(){return this.bottom},f.prototype.isConnected=function(){return this.isConnected},f.prototype.add=function(e,t,n){if(t==null&&n==null){var r=e;if(this.graphManager==null)throw`Graph has no graph mgr!`;if(this.getNodes().indexOf(r)>-1)throw`Node already in graph!`;return r.owner=this,this.getNodes().push(r),r}else{var i=e;if(!(this.getNodes().indexOf(t)>-1&&this.getNodes().indexOf(n)>-1))throw`Source or target not in graph!`;if(!(t.owner==n.owner&&t.owner==this))throw`Both owners must be this graph!`;return t.owner==n.owner?(i.source=t,i.target=n,i.isInterGraph=!1,this.getEdges().push(i),t.edges.push(i),n!=t&&n.edges.push(i),i):null}},f.prototype.remove=function(e){var t=e;if(e instanceof s){if(t==null)throw`Node is null!`;if(!(t.owner!=null&&t.owner==this))throw`Owner graph is invalid!`;if(this.graphManager==null)throw`Owner graph manager is invalid!`;for(var n=t.edges.slice(),r,i=n.length,a=0;a-1&&u>-1))throw`Source and/or target doesn't know this edge!`;r.source.edges.splice(l,1),r.target!=r.source&&r.target.edges.splice(u,1);var o=r.source.owner.getEdges().indexOf(r);if(o==-1)throw`Not in owner's edge list!`;r.source.owner.getEdges().splice(o,1)}},f.prototype.updateLeftTop=function(){for(var e=i.MAX_VALUE,t=i.MAX_VALUE,n,r,a,o=this.getNodes(),s=o.length,c=0;cn&&(e=n),t>r&&(t=r)}return e==i.MAX_VALUE?null:(a=o[0].getParent().paddingLeft==null?this.margin:o[0].getParent().paddingLeft,this.left=t-a,this.top=e-a,new u(this.left,this.top))},f.prototype.updateBounds=function(e){for(var t=i.MAX_VALUE,n=-i.MAX_VALUE,r=i.MAX_VALUE,a=-i.MAX_VALUE,o,s,c,u,d,f=this.nodes,p=f.length,m=0;mo&&(t=o),nc&&(r=c),ao&&(t=o),nc&&(r=c),a=this.nodes.length){var c=0;n.forEach(function(t){t.owner==e&&c++}),c==this.nodes.length&&(this.isConnected=!0)}},e.exports=f}),(function(e,t,n){var r,i=n(1);function a(e){r=n(5),this.layout=e,this.graphs=[],this.edges=[]}a.prototype.addRoot=function(){var e=this.layout.newGraph(),t=this.layout.newNode(null),n=this.add(e,t);return this.setRootGraph(n),this.rootGraph},a.prototype.add=function(e,t,n,r,i){if(n==null&&r==null&&i==null){if(e==null)throw`Graph is null!`;if(t==null)throw`Parent node is null!`;if(this.graphs.indexOf(e)>-1)throw`Graph already in this graph mgr!`;if(this.graphs.push(e),e.parent!=null)throw`Already has a parent!`;if(t.child!=null)throw`Already has a child!`;return e.parent=t,t.child=e,e}else{i=n,r=t,n=e;var a=r.getOwner(),o=i.getOwner();if(!(a!=null&&a.getGraphManager()==this))throw`Source not in this graph mgr!`;if(!(o!=null&&o.getGraphManager()==this))throw`Target not in this graph mgr!`;if(a==o)return n.isInterGraph=!1,a.add(n,r,i);if(n.isInterGraph=!0,n.source=r,n.target=i,this.edges.indexOf(n)>-1)throw`Edge already in inter-graph edge list!`;if(this.edges.push(n),!(n.source!=null&&n.target!=null))throw`Edge source and/or target is null!`;if(!(n.source.edges.indexOf(n)==-1&&n.target.edges.indexOf(n)==-1))throw`Edge already in source and/or target incidency list!`;return n.source.edges.push(n),n.target.edges.push(n),n}},a.prototype.remove=function(e){if(e instanceof r){var t=e;if(t.getGraphManager()!=this)throw`Graph not in this graph mgr`;if(!(t==this.rootGraph||t.parent!=null&&t.parent.graphManager==this))throw`Invalid parent node!`;var n=[];n=n.concat(t.getEdges());for(var a,o=n.length,s=0;s=t.getRight()?n[0]+=Math.min(t.getX()-e.getX(),e.getRight()-t.getRight()):t.getX()<=e.getX()&&t.getRight()>=e.getRight()&&(n[0]+=Math.min(e.getX()-t.getX(),t.getRight()-e.getRight())),e.getY()<=t.getY()&&e.getBottom()>=t.getBottom()?n[1]+=Math.min(t.getY()-e.getY(),e.getBottom()-t.getBottom()):t.getY()<=e.getY()&&t.getBottom()>=e.getBottom()&&(n[1]+=Math.min(e.getY()-t.getY(),t.getBottom()-e.getBottom()));var a=Math.abs((t.getCenterY()-e.getCenterY())/(t.getCenterX()-e.getCenterX()));t.getCenterY()===e.getCenterY()&&t.getCenterX()===e.getCenterX()&&(a=1);var o=a*n[0],s=n[1]/a;n[0]o)return n[0]=r,n[1]=c,n[2]=a,n[3]=y,!1;if(ia)return n[0]=s,n[1]=i,n[2]=_,n[3]=o,!1;if(ra?(n[0]=u,n[1]=d,C=!0):(n[0]=l,n[1]=c,C=!0):T===D&&(r>a?(n[0]=s,n[1]=c,C=!0):(n[0]=f,n[1]=d,C=!0)),-E===D?a>r?(n[2]=v,n[3]=y,w=!0):(n[2]=_,n[3]=g,w=!0):E===D&&(a>r?(n[2]=h,n[3]=g,w=!0):(n[2]=b,n[3]=y,w=!0)),C&&w)return!1;if(r>a?i>o?(O=this.getCardinalDirection(T,D,4),k=this.getCardinalDirection(E,D,2)):(O=this.getCardinalDirection(-T,D,3),k=this.getCardinalDirection(-E,D,1)):i>o?(O=this.getCardinalDirection(-T,D,1),k=this.getCardinalDirection(-E,D,3)):(O=this.getCardinalDirection(T,D,2),k=this.getCardinalDirection(E,D,4)),!C)switch(O){case 1:j=c,A=r+-m/D,n[0]=A,n[1]=j;break;case 2:A=f,j=i+p*D,n[0]=A,n[1]=j;break;case 3:j=d,A=r+m/D,n[0]=A,n[1]=j;break;case 4:A=u,j=i+-p*D,n[0]=A,n[1]=j;break}if(!w)switch(k){case 1:N=g,M=a+-S/D,n[2]=M,n[3]=N;break;case 2:M=b,N=o+x*D,n[2]=M,n[3]=N;break;case 3:N=y,M=a+S/D,n[2]=M,n[3]=N;break;case 4:M=v,N=o+-x*D,n[2]=M,n[3]=N;break}}return!1},i.getCardinalDirection=function(e,t,n){return e>t?n:1+n%4},i.getIntersection=function(e,t,n,i){if(i==null)return this.getIntersection2(e,t,n);var a=e.x,o=e.y,s=t.x,c=t.y,l=n.x,u=n.y,d=i.x,f=i.y,p=void 0,m=void 0,h=void 0,g=void 0,_=void 0,v=void 0,y=void 0,b=void 0,x=void 0;return h=c-o,_=a-s,y=s*o-a*c,g=f-u,v=l-d,b=d*u-l*f,x=h*v-g*_,x===0?null:(p=(_*b-v*y)/x,m=(g*y-h*b)/x,new r(p,m))},i.angleOfVector=function(e,t,n,r){var i=void 0;return e===n?i=r0?1:e<0?-1:0},r.floor=function(e){return e<0?Math.ceil(e):Math.floor(e)},r.ceil=function(e){return e<0?Math.floor(e):Math.ceil(e)},e.exports=r}),(function(e,t,n){function r(){}r.MAX_VALUE=2147483647,r.MIN_VALUE=-2147483648,e.exports=r}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n0&&t;){for(s.push(l[0]);s.length>0&&t;){var u=s[0];s.splice(0,1),o.add(u);for(var d=u.getEdges(),a=0;a-1&&l.splice(h,1)}o=new Set,c=new Map}}return e},f.prototype.createDummyNodesForBendpoints=function(e){for(var t=[],n=e.source,r=this.graphManager.calcLowestCommonAncestor(e.source,e.target),i=0;i0){for(var i=this.edgeToDummyNodes.get(n),a=0;a=0&&t.splice(d,1),s.getNeighborsList().forEach(function(e){if(n.indexOf(e)<0){var t=r.get(e)-1;t==1&&l.push(e),r.set(e,t)}})}n=n.concat(l),(t.length==1||t.length==2)&&(i=!0,a=t[0])}return a},f.prototype.setGraphManager=function(e){this.graphManager=e},e.exports=f}),(function(e,t,n){function r(){}r.seed=1,r.x=0,r.nextDouble=function(){return r.x=Math.sin(r.seed++)*1e4,r.x-Math.floor(r.x)},e.exports=r}),(function(e,t,n){var r=n(4);function i(e,t){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}i.prototype.getWorldOrgX=function(){return this.lworldOrgX},i.prototype.setWorldOrgX=function(e){this.lworldOrgX=e},i.prototype.getWorldOrgY=function(){return this.lworldOrgY},i.prototype.setWorldOrgY=function(e){this.lworldOrgY=e},i.prototype.getWorldExtX=function(){return this.lworldExtX},i.prototype.setWorldExtX=function(e){this.lworldExtX=e},i.prototype.getWorldExtY=function(){return this.lworldExtY},i.prototype.setWorldExtY=function(e){this.lworldExtY=e},i.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},i.prototype.setDeviceOrgX=function(e){this.ldeviceOrgX=e},i.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},i.prototype.setDeviceOrgY=function(e){this.ldeviceOrgY=e},i.prototype.getDeviceExtX=function(){return this.ldeviceExtX},i.prototype.setDeviceExtX=function(e){this.ldeviceExtX=e},i.prototype.getDeviceExtY=function(){return this.ldeviceExtY},i.prototype.setDeviceExtY=function(e){this.ldeviceExtY=e},i.prototype.transformX=function(e){var t=0,n=this.lworldExtX;return n!=0&&(t=this.ldeviceOrgX+(e-this.lworldOrgX)*this.ldeviceExtX/n),t},i.prototype.transformY=function(e){var t=0,n=this.lworldExtY;return n!=0&&(t=this.ldeviceOrgY+(e-this.lworldOrgY)*this.ldeviceExtY/n),t},i.prototype.inverseTransformX=function(e){var t=0,n=this.ldeviceExtX;return n!=0&&(t=this.lworldOrgX+(e-this.ldeviceOrgX)*this.lworldExtX/n),t},i.prototype.inverseTransformY=function(e){var t=0,n=this.ldeviceExtY;return n!=0&&(t=this.lworldOrgY+(e-this.ldeviceOrgY)*this.lworldExtY/n),t},i.prototype.inverseTransformPoint=function(e){return new r(this.inverseTransformX(e.x),this.inverseTransformY(e.y))},e.exports=i}),(function(e,t,n){function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);ta.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*a.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-a.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT_INCREMENTAL):(e>a.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(a.COOLING_ADAPTATION_FACTOR,1-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*(1-a.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},l.prototype.calcSpringForces=function(){for(var e=this.getAllEdges(),t,n=0;n0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n,r,i,o,s=this.getAllNodes(),c;if(this.useFRGridVariant)for(this.totalIterations%a.GRID_CALCULATION_CHECK_PERIOD==1&&e&&this.updateGrid(),c=new Set,n=0;nc||s>c)&&(e.gravitationForceX=-this.gravityConstant*i,e.gravitationForceY=-this.gravityConstant*a)):(c=t.getEstimatedSize()*this.compoundGravityRangeFactor,(o>c||s>c)&&(e.gravitationForceX=-this.gravityConstant*i*this.compoundGravityConstant,e.gravitationForceY=-this.gravityConstant*a*this.compoundGravityConstant))},l.prototype.isConverged=function(){var e,t=!1;return this.totalIterations>this.maxIterations/3&&(t=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),e=this.totalDisplacement=c.length||u>=c[0].length)){for(var d=0;de}}]),e}()}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;i(this,e),this.sequence1=t,this.sequence2=n,this.match_score=r,this.mismatch_penalty=a,this.gap_penalty=o,this.iMax=t.length+1,this.jMax=n.length+1,this.grid=Array(this.iMax);for(var s=0;s=0;n--){var r=this.listeners[n];r.event===e&&r.callback===t&&this.listeners.splice(n,1)}},i.emit=function(e,t){for(var n=0;n{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(o()):typeof define==`function`&&define.amd?define([`layout-base`],r):typeof e==`object`?e.coseBase=r(o()):n.coseBase=r(n.layoutBase)})(e,function(e){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=7)})([(function(t,n){t.exports=e}),(function(e,t,n){var r=n(0).FDLayoutConstants;function i(){}for(var a in r)i[a]=r[a];i.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,i.DEFAULT_RADIAL_SEPARATION=r.DEFAULT_EDGE_LENGTH,i.DEFAULT_COMPONENT_SEPERATION=60,i.TILE=!0,i.TILING_PADDING_VERTICAL=10,i.TILING_PADDING_HORIZONTAL=10,i.TREE_REDUCTION_ON_INCREMENTAL=!1,e.exports=i}),(function(e,t,n){var r=n(0).FDLayoutEdge;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),(function(e,t,n){var r=n(0).LGraph;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),(function(e,t,n){var r=n(0).LGraphManager;function i(e){r.call(this,e)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),(function(e,t,n){var r=n(0).FDLayoutNode,i=n(0).IMath;function a(e,t,n,i){r.call(this,e,t,n,i)}for(var o in a.prototype=Object.create(r.prototype),r)a[o]=r[o];a.prototype.move=function(){var e=this.graphManager.getLayout();this.displacementX=e.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY=e.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren,Math.abs(this.displacementX)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementX=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementX)),Math.abs(this.displacementY)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementY=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementY)),this.child==null||this.child.getNodes().length==0?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),e.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},a.prototype.propogateDisplacementToChildren=function(e,t){for(var n=this.getChild().getNodes(),r,i=0;i0)this.positionNodesRadially(e);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n),this.positionNodesRandomly()}}else if(c.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n)}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},v.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%l.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-this.coolingCycle**+(Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),t=this.nodesWithGravity.filter(function(t){return e.has(t)});this.graphManager.setAllNodesToApplyGravitation(t),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var n=!this.isTreeGrowing&&!this.isGrowthFinished,r=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(n,r),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},v.prototype.getPositionsData=function(){for(var e=this.graphManager.getAllNodes(),t={},n=0;n1){var s;for(s=0;sr&&(r=Math.floor(o.y)),a=Math.floor(o.x+c.DEFAULT_COMPONENT_SEPERATION)}this.transform(new f(u.WORLD_CENTER_X-o.x/2,u.WORLD_CENTER_Y-o.y/2))},v.radialLayout=function(e,t,n){var r=Math.max(this.maxDiagonalInTree(e),c.DEFAULT_RADIAL_SEPARATION);v.branchRadialLayout(t,null,0,359,0,r);var i=g.calculateBounds(e),a=new _;a.setDeviceOrgX(i.getMinX()),a.setDeviceOrgY(i.getMinY()),a.setWorldOrgX(n.x),a.setWorldOrgY(n.y);for(var o=0;o1;){var _=g[0];g.splice(0,1);var y=u.indexOf(_);y>=0&&u.splice(y,1),p--,d--}m=t==null?0:(u.indexOf(g[0])+1)%p;for(var b=Math.abs(r-n)/d,x=m;f!=d;x=++x%p){var S=u[x].getOtherEnd(e);if(S!=t){var C=(n+f*b)%360,w=(C+b)%360;v.branchRadialLayout(S,e,C,w,i+a,a),f++}}},v.maxDiagonalInTree=function(e){for(var t=m.MIN_VALUE,n=0;nt&&(t=r)}return t},v.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},v.prototype.groupZeroDegreeMembers=function(){var e=this,t={};this.memberGroups={},this.idToDummyNode={};for(var n=[],r=this.graphManager.getAllNodes(),i=0;i1){var r=`DummyCompound_`+n;e.memberGroups[r]=t[n];var i=t[n][0].getParent(),a=new o(e.graphManager);a.id=r,a.paddingLeft=i.paddingLeft||0,a.paddingRight=i.paddingRight||0,a.paddingBottom=i.paddingBottom||0,a.paddingTop=i.paddingTop||0,e.idToDummyNode[r]=a;var s=e.getGraphManager().add(e.newGraph(),a),c=i.getChild();c.add(a);for(var l=0;l=0;e--){var t=this.compoundOrder[e],n=t.id,r=t.paddingLeft,i=t.paddingTop;this.adjustLocations(this.tiledMemberPack[n],t.rect.x,t.rect.y,r,i)}},v.prototype.repopulateZeroDegreeMembers=function(){var e=this,t=this.tiledZeroDegreePack;Object.keys(t).forEach(function(n){var r=e.idToDummyNode[n],i=r.paddingLeft,a=r.paddingTop;e.adjustLocations(t[n],r.rect.x,r.rect.y,i,a)})},v.prototype.getToBeTiled=function(e){var t=e.id;if(this.toBeTiled[t]!=null)return this.toBeTiled[t];var n=e.getChild();if(n==null)return this.toBeTiled[t]=!1,!1;for(var r=n.getNodes(),i=0;i0)return this.toBeTiled[t]=!1,!1;if(a.getChild()==null){this.toBeTiled[a.id]=!1;continue}if(!this.getToBeTiled(a))return this.toBeTiled[t]=!1,!1}return this.toBeTiled[t]=!0,!0},v.prototype.getNodeDegree=function(e){e.id;for(var t=e.getEdges(),n=0,r=0;rc&&(c=u.rect.height)}n+=c+e.verticalPadding}},v.prototype.tileCompoundMembers=function(e,t){var n=this;this.tiledMemberPack=[],Object.keys(e).forEach(function(r){var i=t[r];n.tiledMemberPack[r]=n.tileNodes(e[r],i.paddingLeft+i.paddingRight),i.rect.width=n.tiledMemberPack[r].width,i.rect.height=n.tiledMemberPack[r].height})},v.prototype.tileNodes=function(e,t){var n={rows:[],rowWidth:[],rowHeight:[],width:0,height:t,verticalPadding:c.TILING_PADDING_VERTICAL,horizontalPadding:c.TILING_PADDING_HORIZONTAL};e.sort(function(e,t){return e.rect.width*e.rect.height>t.rect.width*t.rect.height?-1:+(e.rect.width*e.rect.height0&&(a+=e.horizontalPadding),e.rowWidth[n]=a,e.width0&&(o+=e.verticalPadding);var s=0;o>e.rowHeight[n]&&(s=e.rowHeight[n],e.rowHeight[n]=o,s=e.rowHeight[n]-s),e.height+=s,e.rows[n].push(t)},v.prototype.getShortestRowIndex=function(e){for(var t=-1,n=Number.MAX_VALUE,r=0;rn&&(t=r,n=e.rowWidth[r]);return t},v.prototype.canAddHorizontal=function(e,t,n){var r=this.getShortestRowIndex(e);if(r<0)return!0;var i=e.rowWidth[r];if(i+e.horizontalPadding+t<=e.width)return!0;var a=0;e.rowHeight[r]0&&(a=n+e.verticalPadding-e.rowHeight[r]);var o=e.width-i>=t+e.horizontalPadding?(e.height+a)/(i+t+e.horizontalPadding):(e.height+a)/e.width;a=n+e.verticalPadding;var s=e.widtha&&t!=n){r.splice(-1,1),e.rows[n].push(i),e.rowWidth[t]=e.rowWidth[t]-a,e.rowWidth[n]=e.rowWidth[n]+a,e.width=e.rowWidth[instance.getLongestRowIndex(e)];for(var o=Number.MIN_VALUE,s=0;so&&(o=r[s].height);t>0&&(o+=e.verticalPadding);var c=e.rowHeight[t]+e.rowHeight[n];e.rowHeight[t]=o,e.rowHeight[n]0)for(var u=i;u<=a;u++)c[0]+=this.grid[u][o-1].length+this.grid[u][o].length-1;if(a0)for(var u=o;u<=s;u++)c[3]+=this.grid[i-1][u].length+this.grid[i][u].length-1;for(var d=m.MAX_VALUE,f,p,h=0;h{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(s()):typeof define==`function`&&define.amd?define([`cose-base`],r):typeof e==`object`?e.cytoscapeCoseBilkent=r(s()):n.cytoscapeCoseBilkent=r(n.coseBase)})(e,function(e){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=1)})([(function(t,n){t.exports=e}),(function(e,t,n){var r=n(0).layoutBase.LayoutConstants,i=n(0).layoutBase.FDLayoutConstants,a=n(0).CoSEConstants,o=n(0).CoSELayout,s=n(0).CoSENode,c=n(0).layoutBase.PointD,l=n(0).layoutBase.DimensionD,u={ready:function(){},stop:function(){},quality:`default`,nodeDimensionsIncludeLabels:!1,refresh:30,fit:!0,padding:10,randomize:!0,nodeRepulsion:4500,idealEdgeLength:50,edgeElasticity:.45,nestingFactor:.1,gravity:.25,numIter:2500,tile:!0,animate:`end`,animationDuration:500,tilingPaddingVertical:10,tilingPaddingHorizontal:10,gravityRangeCompound:1.5,gravityCompound:1,gravityRange:3.8,initialEnergyOnIncremental:.5};function d(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n}function f(e){this.options=d(u,e),p(this.options)}var p=function(e){e.nodeRepulsion!=null&&(a.DEFAULT_REPULSION_STRENGTH=i.DEFAULT_REPULSION_STRENGTH=e.nodeRepulsion),e.idealEdgeLength!=null&&(a.DEFAULT_EDGE_LENGTH=i.DEFAULT_EDGE_LENGTH=e.idealEdgeLength),e.edgeElasticity!=null&&(a.DEFAULT_SPRING_STRENGTH=i.DEFAULT_SPRING_STRENGTH=e.edgeElasticity),e.nestingFactor!=null&&(a.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=i.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=e.nestingFactor),e.gravity!=null&&(a.DEFAULT_GRAVITY_STRENGTH=i.DEFAULT_GRAVITY_STRENGTH=e.gravity),e.numIter!=null&&(a.MAX_ITERATIONS=i.MAX_ITERATIONS=e.numIter),e.gravityRange!=null&&(a.DEFAULT_GRAVITY_RANGE_FACTOR=i.DEFAULT_GRAVITY_RANGE_FACTOR=e.gravityRange),e.gravityCompound!=null&&(a.DEFAULT_COMPOUND_GRAVITY_STRENGTH=i.DEFAULT_COMPOUND_GRAVITY_STRENGTH=e.gravityCompound),e.gravityRangeCompound!=null&&(a.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=i.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=e.gravityRangeCompound),e.initialEnergyOnIncremental!=null&&(a.DEFAULT_COOLING_FACTOR_INCREMENTAL=i.DEFAULT_COOLING_FACTOR_INCREMENTAL=e.initialEnergyOnIncremental),e.quality==`draft`?r.QUALITY=0:e.quality==`proof`?r.QUALITY=2:r.QUALITY=1,a.NODE_DIMENSIONS_INCLUDE_LABELS=i.NODE_DIMENSIONS_INCLUDE_LABELS=r.NODE_DIMENSIONS_INCLUDE_LABELS=e.nodeDimensionsIncludeLabels,a.DEFAULT_INCREMENTAL=i.DEFAULT_INCREMENTAL=r.DEFAULT_INCREMENTAL=!e.randomize,a.ANIMATE=i.ANIMATE=r.ANIMATE=e.animate,a.TILE=e.tile,a.TILING_PADDING_VERTICAL=typeof e.tilingPaddingVertical==`function`?e.tilingPaddingVertical.call():e.tilingPaddingVertical,a.TILING_PADDING_HORIZONTAL=typeof e.tilingPaddingHorizontal==`function`?e.tilingPaddingHorizontal.call():e.tilingPaddingHorizontal};f.prototype.run=function(){var e,t,n=this.options;this.idToLNode={};var r=this.layout=new o,i=this;i.stopped=!1,this.cy=this.options.cy,this.cy.trigger({type:`layoutstart`,layout:this});var a=r.newGraphManager();this.gm=a;var s=this.options.eles.nodes(),c=this.options.eles.edges();this.root=a.addRoot(),this.processChildrenList(this.root,this.getTopMostNodes(s),r);for(var l=0;l0){var h=n.getGraphManager().add(n.newGraph(),u);this.processChildrenList(h,o,n)}}},f.prototype.stop=function(){return this.stopped=!0,this};var m=function(e){e(`layout`,`cose-bilkent`,f)};typeof cytoscape<`u`&&m(cytoscape),e.exports=m})])})}))(),1);a.use(c.default);function l(e,t){e.forEach(e=>{let n={id:e.id,labelText:e.label,height:e.height,width:e.width,padding:e.padding??0};Object.keys(e).forEach(t=>{[`id`,`label`,`height`,`width`,`padding`,`x`,`y`].includes(t)||(n[t]=e[t])}),t.add({group:`nodes`,data:n,position:{x:e.x??0,y:e.y??0}})})}n(l,`addNodes`);function u(e,t){e.forEach(e=>{let n={id:e.id,source:e.start,target:e.end};Object.keys(e).forEach(t=>{[`id`,`start`,`end`].includes(t)||(n[t]=e[t])}),t.add({group:`edges`,data:n})})}n(u,`addEdges`);function d(e){return new Promise(t=>{let n=i(`body`).append(`div`).attr(`id`,`cy`).attr(`style`,`display:none`),o=a({container:document.getElementById(`cy`),style:[{selector:`edge`,style:{"curve-style":`bezier`}}]});n.remove(),l(e.nodes,o),u(e.edges,o),o.nodes().forEach(function(e){e.layoutDimensions=()=>{let t=e.data();return{w:t.width,h:t.height}}}),o.layout({name:`cose-bilkent`,quality:`proof`,styleEnabled:!1,animate:!1}).run(),o.ready(e=>{r.info(`Cytoscape ready`,e),t(o)})})}n(d,`createCytoscapeInstance`);function f(e){return e.nodes().map(e=>{let t=e.data(),n=e.position(),r={id:t.id,x:n.x,y:n.y};return Object.keys(t).forEach(e=>{e!==`id`&&(r[e]=t[e])}),r})}n(f,`extractPositionedNodes`);function p(e){return e.edges().map(e=>{let t=e.data(),n=e._private.rscratch,r={id:t.id,source:t.source,target:t.target,startX:n.startX,startY:n.startY,midX:n.midX,midY:n.midY,endX:n.endX,endY:n.endY};return Object.keys(t).forEach(e=>{[`id`,`source`,`target`].includes(e)||(r[e]=t[e])}),r})}n(p,`extractPositionedEdges`);async function m(e,t){r.debug(`Starting cose-bilkent layout algorithm`);try{h(e);let t=await d(e),n=f(t),i=p(t);return r.debug(`Layout completed: ${n.length} nodes, ${i.length} edges`),{nodes:n,edges:i}}catch(e){throw r.error(`Error in cose-bilkent layout algorithm:`,e),e}}n(m,`executeCoseBilkentLayout`);function h(e){if(!e)throw Error(`Layout data is required`);if(!e.config)throw Error(`Configuration is required in layout data`);if(!e.rootNode)throw Error(`Root node is required`);if(!e.nodes||!Array.isArray(e.nodes))throw Error(`No nodes found in layout data`);if(!Array.isArray(e.edges))throw Error(`Edges array is required in layout data`);return!0}n(h,`validateLayoutData`);var g=n(async(e,t,{insertCluster:n,insertEdge:r,insertEdgeLabel:i,insertMarkers:a,insertNode:o,log:s,positionEdgeLabel:c},{algorithm:l})=>{let u={},d={},f=t.select(`g`);a(f,e.markers,e.type,e.diagramId);let p=f.insert(`g`).attr(`class`,`subgraphs`),h=f.insert(`g`).attr(`class`,`edgePaths`),g=f.insert(`g`).attr(`class`,`edgeLabels`),_=f.insert(`g`).attr(`class`,`nodes`);s.debug(`Inserting nodes into DOM for dimension calculation`),await Promise.all(e.nodes.map(async t=>{if(t.isGroup){let e={...t};d[t.id]=e,u[t.id]=e,await n(p,t)}else{let n={...t};u[t.id]=n;let r=await o(_,t,{config:e.config,dir:e.direction||`TB`}),i=r.node().getBBox();n.width=i.width,n.height=i.height,n.domId=r,s.debug(`Node ${t.id} dimensions: ${i.width}x${i.height}`)}})),s.debug(`Running cose-bilkent layout algorithm`);let v=await m({...e,nodes:e.nodes.map(e=>{let t=u[e.id];return{...e,width:t.width,height:t.height}})},e.config);s.debug(`Positioning nodes based on layout results`),v.nodes.forEach(e=>{let t=u[e.id];t?.domId&&(t.domId.attr(`transform`,`translate(${e.x}, ${e.y})`),t.x=e.x,t.y=e.y,s.debug(`Positioned node ${t.id} at center (${e.x}, ${e.y})`))}),v.edges.forEach(t=>{let n=e.edges.find(e=>e.id===t.id);n&&(n.points=[{x:t.startX,y:t.startY},{x:t.midX,y:t.midY},{x:t.endX,y:t.endY}])}),s.debug(`Inserting and positioning edges`),await Promise.all(e.edges.map(async t=>{await i(g,t);let n=u[t.start??``],a=u[t.end??``];if(n&&a){let i=v.edges.find(e=>e.id===t.id);if(i){s.debug(`APA01 positionedEdge`,i);let o={...t};c(o,r(h,o,d,e.type,n,a,e.diagramId))}else{let i={...t,points:[{x:n.x||0,y:n.y||0},{x:a.x||0,y:a.y||0}]};c(i,r(h,i,d,e.type,n,a,e.diagramId))}}})),s.debug(`Cose-bilkent rendering completed`)},`render`);export{g as render}; \ No newline at end of file diff --git a/.vercel/output/static/assets/cynefinDiagram-TSTJHNR4-C8ZTFXQ0.js b/.vercel/output/static/assets/cynefinDiagram-TSTJHNR4-CAKFzgf0.js similarity index 96% rename from .vercel/output/static/assets/cynefinDiagram-TSTJHNR4-C8ZTFXQ0.js rename to .vercel/output/static/assets/cynefinDiagram-TSTJHNR4-CAKFzgf0.js index 3f06d5f..5a55412 100644 --- a/.vercel/output/static/assets/cynefinDiagram-TSTJHNR4-C8ZTFXQ0.js +++ b/.vercel/output/static/assets/cynefinDiagram-TSTJHNR4-CAKFzgf0.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,f as l,v as u,w as d,y as f}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{i as p}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as m}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-AdnthA1k.js";var _=e(()=>({domains:new Map,transitions:[]}),`createDefaultData`),v=_(),y={getDomains:e(()=>v.domains,`getDomains`),getTransitions:e(()=>v.transitions,`getTransitions`),setDomains:e(e=>{if(e)for(let t of e){let e=t.domain,n=(t.items??[]).map(e=>({label:e.label}));v.domains.set(e,{name:e,items:n})}},`setDomains`),setTransitions:e(e=>{e&&(v.transitions=e.filter(e=>e.from===e.to?(t.warn(`Cynefin: self-loop transition on domain "${e.from}" is not meaningful and will be skipped.`),!1):!0).map(e=>({from:e.from,to:e.to,label:e.label||void 0})))},`setTransitions`),getConfig:e(()=>p({...l.cynefin,...s().cynefin}),`getConfig`),clear:e(()=>{o(),v=_()},`clear`),setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:d,getAccDescription:u,setAccDescription:r},b=e(e=>{h(e,y),y.setDomains(e.domains),y.setTransitions(e.transitions)},`populate`),x={parse:e(async e=>{let n=await g(`cynefin`,e);t.debug(n),b(n)},`parse`)};function S(e){let t=e+1831565813|0;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}e(S,`seededRandom`);function C(e){let t=0;for(let n=0;n{let n=e/2,r=t/2;return{complex:{cx:n/2,cy:r/2,x:0,y:0,w:n,h:r},complicated:{cx:n+n/2,cy:r/2,x:n,y:0,w:n,h:r},chaotic:{cx:n/2,cy:r+r/2,x:0,y:r,w:n,h:r},clear:{cx:n+n/2,cy:r+r/2,x:n,y:r,w:n,h:r},confusion:{cx:n,cy:r,x:n*.7,y:r*.7,w:n*.6,h:r*.6}}},`getDomainLayouts`),j=e(()=>p(n(),s().themeVariables).cynefin,`getCynefinDomainColors`),M=3,N={draw:e((e,n,r,i)=>{let a=i.db,o=a.getDomains(),s=a.getTransitions(),l=a.getDiagramTitle(),u=a.getAccTitle(),d=a.getAccDescription(),f=a.getConfig(),p=j();t.debug(`Rendering Cynefin diagram`);let h=f.width,g=f.height,_=f.padding,v=f.showDomainDescriptions,y=f.boundaryAmplitude,b=h+_*2,x=g+_*2,S={complex:p.complexBg,complicated:p.complicatedBg,clear:p.clearBg,chaotic:p.chaoticBg,confusion:p.confusionBg},C=m(n);c(C,x,b,f.useMaxWidth??!0),C.attr(`viewBox`,`0 0 ${b} ${x}`),u&&C.append(`title`).text(u),d&&C.append(`desc`).text(d);let N=C.append(`g`).attr(`transform`,`translate(${_}, ${_})`),P=A(h,g),F=w(f.seed,n),I=N.append(`g`).attr(`class`,`cynefin-backgrounds`),L=[`complex`,`complicated`,`chaotic`,`clear`];for(let e of L){let t=P[e];I.append(`rect`).attr(`class`,`cynefinDomain`).attr(`x`,t.x).attr(`y`,t.y).attr(`width`,t.w).attr(`height`,t.h).attr(`fill`,S[e]).attr(`fill-opacity`,.4).attr(`stroke`,`none`)}let R=N.append(`g`).attr(`class`,`cynefin-boundaries`);R.append(`path`).attr(`class`,`cynefinBoundary`).attr(`d`,T(h,g,F,y)).attr(`fill`,`none`),R.append(`path`).attr(`class`,`cynefinBoundary`).attr(`d`,E(h,g,F+100,y)).attr(`fill`,`none`),R.append(`path`).attr(`class`,`cynefinCliff`).attr(`d`,D(h,g)).attr(`fill`,`none`);let z=h*.15,B=g*.15;N.append(`path`).attr(`class`,`cynefinConfusion`).attr(`d`,O(h/2,g/2,z,B)).attr(`fill`,S.confusion).attr(`fill-opacity`,.5);let V=N.append(`g`).attr(`class`,`cynefin-labels`);for(let e of L){let t=P[e];V.append(`text`).attr(`class`,`cynefinDomainLabel`).attr(`x`,t.cx).attr(`y`,v?t.cy-30:t.cy).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(e.charAt(0).toUpperCase()+e.slice(1))}if(V.append(`text`).attr(`class`,`cynefinDomainLabel`).attr(`x`,h/2).attr(`y`,v?g/2-10:g/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(`Confusion`),v){let e=N.append(`g`).attr(`class`,`cynefin-subtitles`);for(let t of L){let n=P[t],r=k[t];e.append(`text`).attr(`class`,`cynefinSubtitle`).attr(`x`,n.cx).attr(`y`,n.cy-10).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(r.model),e.append(`text`).attr(`class`,`cynefinSubtitle`).attr(`x`,n.cx).attr(`y`,n.cy+5).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(r.practice)}e.append(`text`).attr(`class`,`cynefinSubtitle`).attr(`x`,h/2).attr(`y`,g/2+8).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(k.confusion.practice)}let H=N.append(`g`).attr(`class`,`cynefin-items`);for(let e of[`complex`,`complicated`,`chaotic`,`clear`,`confusion`]){let t=o.get(e);if(!t||t.items.length===0)continue;let n=P[e],r=e===`confusion`,i=t.items,a=0;r&&t.items.length>M&&(a=t.items.length-M,i=t.items.slice(0,M));let s;if(r){let e=v?22:14;s=n.cy+e}else s=n.cy+(v?25:15);if([...i].forEach((t,r)=>{let i=s+r*30,a=H.append(`g`),o=a.append(`text`).attr(`class`,`cynefinItemText`).attr(`x`,0).attr(`y`,26/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`central`).text(t.label),c=t.label.length*7,l=o.node();if(l&&typeof l.getBBox==`function`){let e=l.getBBox();e.width>0&&(c=e.width)}let u=c+20,d=n.cx-u/2;a.attr(`transform`,`translate(${d}, ${i})`),a.insert(`rect`,`text`).attr(`class`,`cynefinItem`).attr(`x`,0).attr(`y`,0).attr(`width`,u).attr(`height`,26).attr(`rx`,4).attr(`ry`,4).attr(`fill`,S[e]).attr(`fill-opacity`,.95),o.attr(`x`,u/2).attr(`y`,26/2)}),a>0){let t=s+i.length*30,r=`+${a} more`,o=H.append(`g`),c=o.append(`text`).attr(`class`,`cynefinItemText`).attr(`x`,0).attr(`y`,26/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`central`).text(r),l=r.length*7,u=c.node();if(u&&typeof u.getBBox==`function`){let e=u.getBBox();e.width>0&&(l=e.width)}let d=l+20,f=n.cx-d/2;o.attr(`transform`,`translate(${f}, ${t})`),o.insert(`rect`,`text`).attr(`class`,`cynefinItemOverflow`).attr(`x`,0).attr(`y`,0).attr(`width`,d).attr(`height`,26).attr(`rx`,4).attr(`ry`,4).attr(`fill`,S[e]).attr(`fill-opacity`,.6),c.attr(`x`,d/2).attr(`y`,26/2)}}if(s.length>0){let e=C.select(`defs`).empty()?C.append(`defs`):C.select(`defs`),r=`cynefin-arrow-${n}`;e.append(`marker`).attr(`id`,r).attr(`viewBox`,`0 0 10 10`).attr(`refX`,9).attr(`refY`,5).attr(`markerWidth`,6).attr(`markerHeight`,6).attr(`orient`,`auto-start-reverse`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`class`,`cynefinArrowHead`);let i=N.append(`g`).attr(`class`,`cynefin-arrows`);s.forEach(e=>{let n=P[e.from],a=P[e.to];if(!n||!a)return;if(e.from===e.to){t.warn(`Cynefin renderer: skipping self-loop on domain "${e.from}"`);return}let o=n.cx,s=n.cy,c=a.cx,l=a.cy,u=(o+c)/2,d=(s+l)/2,f=c-o,p=l-s,m=Math.sqrt(f*f+p*p),h=m*.15,g=-p/m,_=f/m,v=u+g*h,y=d+_*h;i.append(`path`).attr(`class`,`cynefinArrowLine`).attr(`d`,`M${o},${s} Q${v},${y} ${c},${l}`).attr(`fill`,`none`).attr(`marker-end`,`url(#${r})`),e.label&&i.append(`text`).attr(`class`,`cynefinArrowLabel`).attr(`x`,v).attr(`y`,y-6).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`auto`).text(e.label)})}l&&N.append(`text`).attr(`class`,`cynefinTitle`).attr(`x`,h/2).attr(`y`,-_/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(l)},`draw`)},P=e(()=>p(n(),s().themeVariables).cynefin,`getCynefinTheme`),F={parser:x,db:y,renderer:N,styles:e(()=>{let e=P();return` +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,f as l,v as u,w as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-Z7xZAZRH.js";var _=e(()=>({domains:new Map,transitions:[]}),`createDefaultData`),v=_(),y={getDomains:e(()=>v.domains,`getDomains`),getTransitions:e(()=>v.transitions,`getTransitions`),setDomains:e(e=>{if(e)for(let t of e){let e=t.domain,n=(t.items??[]).map(e=>({label:e.label}));v.domains.set(e,{name:e,items:n})}},`setDomains`),setTransitions:e(e=>{e&&(v.transitions=e.filter(e=>e.from===e.to?(t.warn(`Cynefin: self-loop transition on domain "${e.from}" is not meaningful and will be skipped.`),!1):!0).map(e=>({from:e.from,to:e.to,label:e.label||void 0})))},`setTransitions`),getConfig:e(()=>p({...l.cynefin,...s().cynefin}),`getConfig`),clear:e(()=>{o(),v=_()},`clear`),setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:d,getAccDescription:u,setAccDescription:r},b=e(e=>{h(e,y),y.setDomains(e.domains),y.setTransitions(e.transitions)},`populate`),x={parse:e(async e=>{let n=await g(`cynefin`,e);t.debug(n),b(n)},`parse`)};function S(e){let t=e+1831565813|0;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}e(S,`seededRandom`);function C(e){let t=0;for(let n=0;n{let n=e/2,r=t/2;return{complex:{cx:n/2,cy:r/2,x:0,y:0,w:n,h:r},complicated:{cx:n+n/2,cy:r/2,x:n,y:0,w:n,h:r},chaotic:{cx:n/2,cy:r+r/2,x:0,y:r,w:n,h:r},clear:{cx:n+n/2,cy:r+r/2,x:n,y:r,w:n,h:r},confusion:{cx:n,cy:r,x:n*.7,y:r*.7,w:n*.6,h:r*.6}}},`getDomainLayouts`),j=e(()=>p(n(),s().themeVariables).cynefin,`getCynefinDomainColors`),M=3,N={draw:e((e,n,r,i)=>{let a=i.db,o=a.getDomains(),s=a.getTransitions(),l=a.getDiagramTitle(),u=a.getAccTitle(),d=a.getAccDescription(),f=a.getConfig(),p=j();t.debug(`Rendering Cynefin diagram`);let h=f.width,g=f.height,_=f.padding,v=f.showDomainDescriptions,y=f.boundaryAmplitude,b=h+_*2,x=g+_*2,S={complex:p.complexBg,complicated:p.complicatedBg,clear:p.clearBg,chaotic:p.chaoticBg,confusion:p.confusionBg},C=m(n);c(C,x,b,f.useMaxWidth??!0),C.attr(`viewBox`,`0 0 ${b} ${x}`),u&&C.append(`title`).text(u),d&&C.append(`desc`).text(d);let N=C.append(`g`).attr(`transform`,`translate(${_}, ${_})`),P=A(h,g),F=w(f.seed,n),I=N.append(`g`).attr(`class`,`cynefin-backgrounds`),L=[`complex`,`complicated`,`chaotic`,`clear`];for(let e of L){let t=P[e];I.append(`rect`).attr(`class`,`cynefinDomain`).attr(`x`,t.x).attr(`y`,t.y).attr(`width`,t.w).attr(`height`,t.h).attr(`fill`,S[e]).attr(`fill-opacity`,.4).attr(`stroke`,`none`)}let R=N.append(`g`).attr(`class`,`cynefin-boundaries`);R.append(`path`).attr(`class`,`cynefinBoundary`).attr(`d`,T(h,g,F,y)).attr(`fill`,`none`),R.append(`path`).attr(`class`,`cynefinBoundary`).attr(`d`,E(h,g,F+100,y)).attr(`fill`,`none`),R.append(`path`).attr(`class`,`cynefinCliff`).attr(`d`,D(h,g)).attr(`fill`,`none`);let z=h*.15,B=g*.15;N.append(`path`).attr(`class`,`cynefinConfusion`).attr(`d`,O(h/2,g/2,z,B)).attr(`fill`,S.confusion).attr(`fill-opacity`,.5);let V=N.append(`g`).attr(`class`,`cynefin-labels`);for(let e of L){let t=P[e];V.append(`text`).attr(`class`,`cynefinDomainLabel`).attr(`x`,t.cx).attr(`y`,v?t.cy-30:t.cy).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(e.charAt(0).toUpperCase()+e.slice(1))}if(V.append(`text`).attr(`class`,`cynefinDomainLabel`).attr(`x`,h/2).attr(`y`,v?g/2-10:g/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(`Confusion`),v){let e=N.append(`g`).attr(`class`,`cynefin-subtitles`);for(let t of L){let n=P[t],r=k[t];e.append(`text`).attr(`class`,`cynefinSubtitle`).attr(`x`,n.cx).attr(`y`,n.cy-10).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(r.model),e.append(`text`).attr(`class`,`cynefinSubtitle`).attr(`x`,n.cx).attr(`y`,n.cy+5).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(r.practice)}e.append(`text`).attr(`class`,`cynefinSubtitle`).attr(`x`,h/2).attr(`y`,g/2+8).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(k.confusion.practice)}let H=N.append(`g`).attr(`class`,`cynefin-items`);for(let e of[`complex`,`complicated`,`chaotic`,`clear`,`confusion`]){let t=o.get(e);if(!t||t.items.length===0)continue;let n=P[e],r=e===`confusion`,i=t.items,a=0;r&&t.items.length>M&&(a=t.items.length-M,i=t.items.slice(0,M));let s;if(r){let e=v?22:14;s=n.cy+e}else s=n.cy+(v?25:15);if([...i].forEach((t,r)=>{let i=s+r*30,a=H.append(`g`),o=a.append(`text`).attr(`class`,`cynefinItemText`).attr(`x`,0).attr(`y`,26/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`central`).text(t.label),c=t.label.length*7,l=o.node();if(l&&typeof l.getBBox==`function`){let e=l.getBBox();e.width>0&&(c=e.width)}let u=c+20,d=n.cx-u/2;a.attr(`transform`,`translate(${d}, ${i})`),a.insert(`rect`,`text`).attr(`class`,`cynefinItem`).attr(`x`,0).attr(`y`,0).attr(`width`,u).attr(`height`,26).attr(`rx`,4).attr(`ry`,4).attr(`fill`,S[e]).attr(`fill-opacity`,.95),o.attr(`x`,u/2).attr(`y`,26/2)}),a>0){let t=s+i.length*30,r=`+${a} more`,o=H.append(`g`),c=o.append(`text`).attr(`class`,`cynefinItemText`).attr(`x`,0).attr(`y`,26/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`central`).text(r),l=r.length*7,u=c.node();if(u&&typeof u.getBBox==`function`){let e=u.getBBox();e.width>0&&(l=e.width)}let d=l+20,f=n.cx-d/2;o.attr(`transform`,`translate(${f}, ${t})`),o.insert(`rect`,`text`).attr(`class`,`cynefinItemOverflow`).attr(`x`,0).attr(`y`,0).attr(`width`,d).attr(`height`,26).attr(`rx`,4).attr(`ry`,4).attr(`fill`,S[e]).attr(`fill-opacity`,.6),c.attr(`x`,d/2).attr(`y`,26/2)}}if(s.length>0){let e=C.select(`defs`).empty()?C.append(`defs`):C.select(`defs`),r=`cynefin-arrow-${n}`;e.append(`marker`).attr(`id`,r).attr(`viewBox`,`0 0 10 10`).attr(`refX`,9).attr(`refY`,5).attr(`markerWidth`,6).attr(`markerHeight`,6).attr(`orient`,`auto-start-reverse`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`class`,`cynefinArrowHead`);let i=N.append(`g`).attr(`class`,`cynefin-arrows`);s.forEach(e=>{let n=P[e.from],a=P[e.to];if(!n||!a)return;if(e.from===e.to){t.warn(`Cynefin renderer: skipping self-loop on domain "${e.from}"`);return}let o=n.cx,s=n.cy,c=a.cx,l=a.cy,u=(o+c)/2,d=(s+l)/2,f=c-o,p=l-s,m=Math.sqrt(f*f+p*p),h=m*.15,g=-p/m,_=f/m,v=u+g*h,y=d+_*h;i.append(`path`).attr(`class`,`cynefinArrowLine`).attr(`d`,`M${o},${s} Q${v},${y} ${c},${l}`).attr(`fill`,`none`).attr(`marker-end`,`url(#${r})`),e.label&&i.append(`text`).attr(`class`,`cynefinArrowLabel`).attr(`x`,v).attr(`y`,y-6).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`auto`).text(e.label)})}l&&N.append(`text`).attr(`class`,`cynefinTitle`).attr(`x`,h/2).attr(`y`,-_/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(l)},`draw`)},P=e(()=>p(n(),s().themeVariables).cynefin,`getCynefinTheme`),F={parser:x,db:y,renderer:N,styles:e(()=>{let e=P();return` .cynefinDomain { stroke: none; } diff --git a/.vercel/output/static/assets/dagre-VKFMJZFB-DLAiBZiA.js b/.vercel/output/static/assets/dagre-VKFMJZFB-Cv2q18CS.js similarity index 94% rename from .vercel/output/static/assets/dagre-VKFMJZFB-DLAiBZiA.js rename to .vercel/output/static/assets/dagre-VKFMJZFB-Cv2q18CS.js index 054b979..8542000 100644 --- a/.vercel/output/static/assets/dagre-VKFMJZFB-DLAiBZiA.js +++ b/.vercel/output/static/assets/dagre-VKFMJZFB-Cv2q18CS.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{x as n}from"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as r}from"./chunk-OGEWGWER-Dr-qyYzn.js";import{t as i}from"./graphlib-DS17s2tU.js";import{t as a}from"./dagre-dpRSp0QF.js";import{a as o,i as s,n as c,o as l,r as u,t as d}from"./chunk-RYQCIY6F-D_L2RdcQ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import{a as f,c as p,i as m,l as h,n as g,t as _,u as v}from"./chunk-ZGVPDNZ5-zo3h_nOA.js";import{a as y,i as b,o as x,r as S,t as C}from"./chunk-52WLFC77-BBAyrLn9.js";var w=e((e,t,n)=>Math.max(t,Math.min(n,e)),`clamp`),T=e((e=`TB`)=>{switch(e){case`BT`:return`bottom`;case`LR`:return`right`;case`RL`:return`left`;default:return`top`}},`getDefaultSelfLoopSide`),E=e(e=>e===`flowchart`||e===`flowchart-v2`||e===`stateDiagram`,`shouldMergeSelfLoopSegments`),D=e((e,t,n,r,i)=>{let a=[],o=new Set;if(n.forEach(({start:e,end:t})=>{e!==r&&o.add(e),t!==r&&o.add(t)}),o.forEach(t=>{let n=e.node(t);typeof n?.x==`number`&&typeof n?.y==`number`&&a.push(n)}),a.length===0&&n.forEach(({edge:e})=>{(e.points??[]).forEach(e=>{typeof e?.x==`number`&&typeof e?.y==`number`&&a.push(e)})}),a.length===0)return T(i);let s=a.reduce((e,t)=>({x:e.x+t.x/a.length,y:e.y+t.y/a.length}),{x:0,y:0}),c=s.x-t.x,l=s.y-t.y;return Math.abs(c)>Math.abs(l)?c>0?`right`:`left`:Math.abs(l)>0?l>0?`bottom`:`top`:T(i)},`getSelfLoopSide`),O=e((e,t=`top`,n=0,r=0)=>{let i=e.x,a=e.y-n,o=e.width/2,s=e.height/2,c=Math.max(36,Math.min(100,e.width*.8)),l=w(Math.max(r,e.width*.35),36,c),u=w(Math.min(e.width,e.height)*.45,24,48);switch(t){case`bottom`:{let e=a+s;return[{x:i-l/2,y:e},{x:i-l/2,y:e+u},{x:i+l/2,y:e+u},{x:i+l/2,y:e}]}case`right`:{let e=i+o;return[{x:e,y:a-l/2},{x:e+u,y:a-l/2},{x:e+u,y:a+l/2},{x:e,y:a+l/2}]}case`left`:{let e=i-o;return[{x:e,y:a-l/2},{x:e-u,y:a-l/2},{x:e-u,y:a+l/2},{x:e,y:a+l/2}]}default:{let e=a-s;return[{x:i-l/2,y:e},{x:i-l/2,y:e-u},{x:i+l/2,y:e-u},{x:i+l/2,y:e}]}}},`getSelfLoopPoints`),k=e((e,t,n=`top`,r=0,i={})=>{let a=e.x,o=e.y-r,s=i.width??0,c=i.height??0;switch(n){case`bottom`:return{x:a,y:Math.max(...t.map(e=>e.y))+c/2+4};case`right`:return{x:Math.max(...t.map(e=>e.x))+s/2+4,y:o};case`left`:return{x:Math.min(...t.map(e=>e.x))-s/2-4,y:o};default:return{x:a,y:Math.min(...t.map(e=>e.y))-c/2-4}}},`getSelfLoopLabelPosition`),A=e((e,t=0,{mergeSelfLoops:n=!0}={})=>{let r=new Map,i=[],a=e.graph()?.rankdir;return e.edges().forEach(t=>{let a=e.edge(t);if(n&&a.selfLoop){let e=a.selfLoop.id;r.has(e)||r.set(e,[]),r.get(e).push({edge:a,start:t.v,end:t.w})}else i.push({edge:a,start:t.v,end:t.w})}),r.forEach(n=>{if(n.length!==3){n.forEach(e=>i.push(e));return}n.sort((e,t)=>e.edge.selfLoop.order-t.edge.selfLoop.order);let[r,o,s]=n,c=r.edge.originalEdge??o.edge.originalEdge??s.edge.originalEdge??o.edge,l=e.node(c.start);if(!l){n.forEach(e=>i.push(e));return}let u={width:o.edge.width,height:o.edge.height},d=D(e,l,n,c.start,a),f=O(l,d,t,u.width??0),p=k(l,f,d,t,u),m={...o.edge,...c,id:c.id,points:f,start:c.start,end:c.end,x:p.x,y:p.y,width:u.width,height:u.height,labelStyle:o.edge.labelStyle,fromCluster:r.edge.fromCluster??o.edge.fromCluster??s.edge.fromCluster,toCluster:r.edge.toCluster??o.edge.toCluster??s.edge.toCluster};delete m.selfLoop,delete m.originalEdge,i.push({edge:m,start:m.start,end:m.end})}),i},`getEdgesToRender`),j=e(async(n,i,c,d,g,_)=>{t.warn(`Graph in recursive render:XAX`,l(i),g);let y=i.graph().rankdir;t.trace(`Dir in recursive render - dir:`,y);let C=n.insert(`g`).attr(`class`,`root`);i.nodes()?t.info(`Recursive render XXX`,i.nodes()):t.info(`No nodes found for`,i),i.edges().length>0&&t.info(`Recursive edges`,i.edge(i.edges()[0]));let w=C.insert(`g`).attr(`class`,`clusters`),T=C.insert(`g`).attr(`class`,`edgePaths`),D=C.insert(`g`).attr(`class`,`edgeLabels`),O=C.insert(`g`).attr(`class`,`nodes`),k=E(c);await Promise.all(i.nodes().map(async function(e){let n=i.node(e);if(g!==void 0){let n=JSON.parse(JSON.stringify(g.clusterData));t.trace(`Setting data for parent cluster XXX +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{x as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as r}from"./chunk-OGEWGWER-D-nWYRNR.js";import{t as i}from"./graphlib-DS17s2tU.js";import{t as a}from"./dagre-dpRSp0QF.js";import{a as o,i as s,n as c,o as l,r as u,t as d}from"./chunk-RYQCIY6F-Dtr3kkSR.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import{a as f,c as p,i as m,l as h,n as g,t as _,u as v}from"./chunk-ZGVPDNZ5-DGInJAPD.js";import{a as y,i as b,o as x,r as S,t as C}from"./chunk-52WLFC77-BOCvVCX1.js";var w=e((e,t,n)=>Math.max(t,Math.min(n,e)),`clamp`),T=e((e=`TB`)=>{switch(e){case`BT`:return`bottom`;case`LR`:return`right`;case`RL`:return`left`;default:return`top`}},`getDefaultSelfLoopSide`),E=e(e=>e===`flowchart`||e===`flowchart-v2`||e===`stateDiagram`,`shouldMergeSelfLoopSegments`),D=e((e,t,n,r,i)=>{let a=[],o=new Set;if(n.forEach(({start:e,end:t})=>{e!==r&&o.add(e),t!==r&&o.add(t)}),o.forEach(t=>{let n=e.node(t);typeof n?.x==`number`&&typeof n?.y==`number`&&a.push(n)}),a.length===0&&n.forEach(({edge:e})=>{(e.points??[]).forEach(e=>{typeof e?.x==`number`&&typeof e?.y==`number`&&a.push(e)})}),a.length===0)return T(i);let s=a.reduce((e,t)=>({x:e.x+t.x/a.length,y:e.y+t.y/a.length}),{x:0,y:0}),c=s.x-t.x,l=s.y-t.y;return Math.abs(c)>Math.abs(l)?c>0?`right`:`left`:Math.abs(l)>0?l>0?`bottom`:`top`:T(i)},`getSelfLoopSide`),O=e((e,t=`top`,n=0,r=0)=>{let i=e.x,a=e.y-n,o=e.width/2,s=e.height/2,c=Math.max(36,Math.min(100,e.width*.8)),l=w(Math.max(r,e.width*.35),36,c),u=w(Math.min(e.width,e.height)*.45,24,48);switch(t){case`bottom`:{let e=a+s;return[{x:i-l/2,y:e},{x:i-l/2,y:e+u},{x:i+l/2,y:e+u},{x:i+l/2,y:e}]}case`right`:{let e=i+o;return[{x:e,y:a-l/2},{x:e+u,y:a-l/2},{x:e+u,y:a+l/2},{x:e,y:a+l/2}]}case`left`:{let e=i-o;return[{x:e,y:a-l/2},{x:e-u,y:a-l/2},{x:e-u,y:a+l/2},{x:e,y:a+l/2}]}default:{let e=a-s;return[{x:i-l/2,y:e},{x:i-l/2,y:e-u},{x:i+l/2,y:e-u},{x:i+l/2,y:e}]}}},`getSelfLoopPoints`),k=e((e,t,n=`top`,r=0,i={})=>{let a=e.x,o=e.y-r,s=i.width??0,c=i.height??0;switch(n){case`bottom`:return{x:a,y:Math.max(...t.map(e=>e.y))+c/2+4};case`right`:return{x:Math.max(...t.map(e=>e.x))+s/2+4,y:o};case`left`:return{x:Math.min(...t.map(e=>e.x))-s/2-4,y:o};default:return{x:a,y:Math.min(...t.map(e=>e.y))-c/2-4}}},`getSelfLoopLabelPosition`),A=e((e,t=0,{mergeSelfLoops:n=!0}={})=>{let r=new Map,i=[],a=e.graph()?.rankdir;return e.edges().forEach(t=>{let a=e.edge(t);if(n&&a.selfLoop){let e=a.selfLoop.id;r.has(e)||r.set(e,[]),r.get(e).push({edge:a,start:t.v,end:t.w})}else i.push({edge:a,start:t.v,end:t.w})}),r.forEach(n=>{if(n.length!==3){n.forEach(e=>i.push(e));return}n.sort((e,t)=>e.edge.selfLoop.order-t.edge.selfLoop.order);let[r,o,s]=n,c=r.edge.originalEdge??o.edge.originalEdge??s.edge.originalEdge??o.edge,l=e.node(c.start);if(!l){n.forEach(e=>i.push(e));return}let u={width:o.edge.width,height:o.edge.height},d=D(e,l,n,c.start,a),f=O(l,d,t,u.width??0),p=k(l,f,d,t,u),m={...o.edge,...c,id:c.id,points:f,start:c.start,end:c.end,x:p.x,y:p.y,width:u.width,height:u.height,labelStyle:o.edge.labelStyle,fromCluster:r.edge.fromCluster??o.edge.fromCluster??s.edge.fromCluster,toCluster:r.edge.toCluster??o.edge.toCluster??s.edge.toCluster};delete m.selfLoop,delete m.originalEdge,i.push({edge:m,start:m.start,end:m.end})}),i},`getEdgesToRender`),j=e(async(n,i,c,d,g,_)=>{t.warn(`Graph in recursive render:XAX`,l(i),g);let y=i.graph().rankdir;t.trace(`Dir in recursive render - dir:`,y);let C=n.insert(`g`).attr(`class`,`root`);i.nodes()?t.info(`Recursive render XXX`,i.nodes()):t.info(`No nodes found for`,i),i.edges().length>0&&t.info(`Recursive edges`,i.edge(i.edges()[0]));let w=C.insert(`g`).attr(`class`,`clusters`),T=C.insert(`g`).attr(`class`,`edgePaths`),D=C.insert(`g`).attr(`class`,`edgeLabels`),O=C.insert(`g`).attr(`class`,`nodes`),k=E(c);await Promise.all(i.nodes().map(async function(e){let n=i.node(e);if(g!==void 0){let n=JSON.parse(JSON.stringify(g.clusterData));t.trace(`Setting data for parent cluster XXX Node.id = `,e,` data=`,n.height,` Parent cluster`,g.height),i.setNode(g.id,n),i.parent(e)||(t.trace(`Setting parent`,e,g.id),i.setParent(e,g.id,n))}if(t.info(`(Insert) Node XXX`+e+`: `+JSON.stringify(i.node(e))),n?.clusterNode){t.info(`Cluster identified XBX`,e,n.width,i.node(e));let{ranksep:r,nodesep:a}=i.graph();n.graph.setGraph({...n.graph.graph(),ranksep:r+25,nodesep:a});let o=await j(O,n.graph,c,d,i.node(e),_),s=o.elem;v(n,s),n.diff=o.diff||0,t.info(`New compound node after recursive render XAX`,e,`width`,n.width,`height`,n.height),h(s,n)}else i.children(e).length>0?(t.trace(`Cluster - the non recursive path XBX`,e,n.id,n,n.width,`Graph:`,i),t.trace(s(n.id,i)),u.set(n.id,{id:s(n.id,i),node:n})):(t.trace(`Node - the non recursive path XAX`,e,O,i.node(e),y),await f(O,i.node(e),{config:_,dir:y}))})),await e(async()=>{let e=i.edges().map(async function(e){let n=i.edge(e.v,e.w,e.name);if(t.info(`Edge `+e.v+` -> `+e.w+`: `+JSON.stringify(e)),t.info(`Edge `+e.v+` -> `+e.w+`: `,e,` `,JSON.stringify(i.edge(e))),t.info(`Fix`,u,`ids:`,e.v,e.w,`Translating: `,u.get(e.v),u.get(e.w)),k&&n.selfLoop){if(n.selfLoop.order!==1)return;let e=n.id;n.id=n.selfLoop.id,await b(D,n),n.id=e;return}await b(D,n)});await Promise.all(e)},`processEdges`)(),t.info(`Graph before layout:`,JSON.stringify(l(i))),t.info(`############################################# XXX`),t.info(`### Layout ### XXX`),t.info(`############################################# XXX`),a(i),t.info(`Graph after layout:`,JSON.stringify(l(i)));let M=0,{subGraphTitleTotalMargin:N}=r(_);await Promise.all(o(i).map(async function(e){let n=i.node(e);if(t.info(`Position XBX => `+e+`: (`+n.x,`,`+n.y,`) width: `,n.width,` height: `,n.height),n?.clusterNode)n.y+=N,t.info(`A tainted cluster node XBX1`,e,n.id,n.width,n.height,n.x,n.y,i.parent(e)),u.get(n.id).node=n,p(n);else if(i.children(e).length>0){t.info(`A pure cluster node XBX1`,e,n.id,n.x,n.y,n.width,n.height,i.parent(e)),n.height+=N,i.node(n.parentId);let r=n?.padding/2||0,a=n?.labelBBox?.height||0,o=a-r||0;t.debug(`OffsetY`,o,`labelHeight`,a,`halfPadding`,r),await m(w,n),u.get(n.id).node=n}else{let e=i.node(n.parentId);n.y+=N/2,t.info(`A regular node XBX1 - using the padding`,n.id,`parent`,n.parentId,n.width,n.height,n.x,n.y,`offsetY`,n.offsetY,`parent`,e,e?.offsetY,n),p(n)}}));let P=N/2;return A(i,P,{mergeSelfLoops:k}).forEach(function({edge:e,start:n,end:r}){t.info(`Edge `+n+` -> `+r+`: `+JSON.stringify(e),e),e.points.forEach(e=>e.y+=P);let a=i.node(n),o=i.node(r);x(e,S(T,e,u,c,a,o,d))}),i.nodes().forEach(function(e){let n=i.node(e);t.info(e,n.type,n.diff),n.isGroup&&(M=n.diff)}),t.warn(`Returning from recursive render XAX`,C,M),{elem:C,diff:M}},`recursiveRender`),M=e(async(e,r)=>{let a=new i({multigraph:!0,compound:!0}).setGraph({rankdir:e.direction,nodesep:e.config?.nodeSpacing||e.config?.flowchart?.nodeSpacing||e.nodeSpacing,ranksep:e.config?.rankSpacing||e.config?.flowchart?.rankSpacing||e.rankSpacing,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}}),o=r.select(`g`);y(o,e.markers,e.type,e.diagramId),g(),C(),_(),c(),e.nodes.forEach(e=>{a.setNode(e.id,{...e}),e.parentId&&a.setParent(e.id,e.parentId)}),t.debug(`Edges:`,e.edges),e.edges.forEach(e=>{if(e.start===e.end){let t=e.start,n=t+`---`+t+`---1`,r=t+`---`+t+`---2`,i=a.node(t);a.setNode(n,{domId:n,id:n,parentId:i.parentId,labelStyle:``,label:``,padding:0,shape:`labelRect`,style:``,width:10,height:10}),a.setParent(n,i.parentId),a.setNode(r,{domId:r,id:r,parentId:i.parentId,labelStyle:``,padding:0,shape:`labelRect`,label:``,style:``,width:10,height:10}),a.setParent(r,i.parentId);let o=structuredClone(e),s=structuredClone(e),c=structuredClone(e),l=structuredClone(e);s.originalEdge=o,s.selfLoop={id:o.id,order:0},c.originalEdge=o,c.selfLoop={id:o.id,order:1},l.originalEdge=o,l.selfLoop={id:o.id,order:2},s.label=``,s.arrowTypeEnd=`none`,s.endLabelLeft=``,s.endLabelRight=``,s.startLabelLeft=``,s.id=t+`-cyclic-special-1`,c.startLabelRight=``,c.startLabelLeft=``,c.endLabelLeft=``,c.endLabelRight=``,c.arrowTypeStart=`none`,c.arrowTypeEnd=`none`,c.id=t+`-cyclic-special-mid`,l.label=``,l.startLabelRight=``,l.startLabelLeft=``,l.arrowTypeStart=`none`,i.isGroup&&(s.fromCluster=t,l.toCluster=t),l.id=t+`-cyclic-special-2`,l.arrowTypeStart=`none`,a.setEdge(t,n,s,t+`-cyclic-special-0`),a.setEdge(n,r,c,t+`-cyclic-special-1`),a.setEdge(r,t,l,t+`-cyclic-special-2`)}else a.setEdge(e.start,e.end,{...e},e.id)}),t.warn(`Graph at first:`,JSON.stringify(l(a))),d(a),t.warn(`Graph after XAX:`,JSON.stringify(l(a)));let s=n();await j(o,a,e.type,e.diagramId,void 0,s)},`render`);export{A as getEdgesToRender,M as render}; \ No newline at end of file diff --git a/.vercel/output/static/assets/diagram-FQU43EPY-Bu63ejtr.js b/.vercel/output/static/assets/diagram-FQU43EPY-C8Vn5v8I.js similarity index 97% rename from .vercel/output/static/assets/diagram-FQU43EPY-Bu63ejtr.js rename to .vercel/output/static/assets/diagram-FQU43EPY-C8Vn5v8I.js index 12941d5..9aa866f 100644 --- a/.vercel/output/static/assets/diagram-FQU43EPY-Bu63ejtr.js +++ b/.vercel/output/static/assets/diagram-FQU43EPY-C8Vn5v8I.js @@ -1,3 +1,3 @@ -import{T as e}from"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n,p as r}from"./src-_wZywoZs.js";import{H as i,K as a,U as o,Y as s,a as c,b as l,f as u,v as d,w as f,x as p,y as m,z as h}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{_ as g,i as ee,t as te}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as ne}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as re}from"./mermaid-parser.core-AdnthA1k.js";var _=`position frame`,v=`frame positioned`,y=`position relation`,b=`relation positioned`,ie=t(function(e){n.debug(`options str`,e)},`setOptions`),ae=t(function(){return{}},`getOptions`),oe=t(function(){x(),c()},`clear`);function x(){S={}}t(x,`reset`);var se=u.eventmodeling,ce=t(()=>ee({...se,...l().eventmodeling}),`getConfig`),S={};function C(){let e=le,{ast:t}=S,r=E();if(!t)throw Error(`No data for EventModel`);return t.frames.forEach((i,a)=>{let o=N(i,t.dataEntities,r);e=q(e,{$kind:_,index:a,frame:i,textProps:o});let s;B(i)?(n.debug(`source frame`,i.sourceFrames),s=t.frames.filter(e=>i.sourceFrames.some(t=>t.$refText===e.name)),s.forEach(t=>{e=q(e,{$kind:y,index:a,frame:i,sourceFrame:t})})):e=q(e,{$kind:y,index:a,frame:i})}),e={...e,sortedSwimlanesArray:L(e.swimlanes)},e}t(C,`getState`);function w(e){S.ast=e}t(w,`setAst`);var T={swimlaneMinHeight:70,swimlanePadding:15,swimlaneGap:10,boxPadding:10,boxOverlap:90,boxDefaultY:0,boxMinWidth:80,boxMaxWidth:450,boxMinHeight:80,boxMaxHeight:750,contentStartX:250,textMaxWidth:430,boxTextFontWeight:`bold`,boxTextPadding:10,swimlaneTextFontWeight:`bold`,labelUiAutomation:`UI/Automation`,labelUiAutomationPrefix:`UI/A: `,labelCommandReadModel:`Command/Read Model`,labelCommandReadModelPrefix:`C/RM: `,labelEvents:`Events`,labelEventsPrefix:`Stream: `};function E(){return T}t(E,`getDiagramProps`);var le={boxes:[],swimlanes:{},relations:[],maxR:0,sortedSwimlanesArray:[]};function D(e){let t=e.split(`.`);if(t.length===2)return t[0]}t(D,`extractNamespace`);function O(e){let t=e.split(`.`);return t.length===2?t[1]:e}t(O,`extractName`);function k(e,t){if(!(!t||t.length===0))return Object.values(e).find(e=>e.namespace===t)}t(k,`findSwimlaneByNamespace`);function A(e,t,n){return Math.max(t,...Object.keys(e).filter(e=>{let r=Number.parseInt(e);return r>t&&rNumber.parseInt(e)))+1}t(A,`findNextAvailableIndex`);function j(e,t){let n=D(e.entityIdentifier),r=k(t,n);switch(e.modelEntityType){case`ui`:case`pcr`:case`processor`:return r?{index:r.index,label:r.namespace||T.labelUiAutomation}:n?{index:A(t,0,100),label:T.labelUiAutomationPrefix+n}:{index:0,label:T.labelUiAutomation};case`rmo`:case`readmodel`:case`cmd`:case`command`:return r?{index:r.index,label:r.namespace||T.labelCommandReadModel}:n?{index:A(t,100,200),label:T.labelCommandReadModelPrefix+n}:{index:100,label:T.labelCommandReadModel};default:return r?{index:r.index,label:r.namespace||T.labelEvents}:n?{index:A(t,200,300),label:T.labelEventsPrefix+n}:{index:200,label:T.labelEvents}}}t(j,`calculateSwimlaneProps`);function M(e){let{themeVariables:t}=l();switch(e.modelEntityType){case`ui`:return{fill:t.emUiFill??`white`,stroke:t.emUiStroke??`#dbdada`};case`pcr`:case`processor`:return{fill:t.emProcessorFill??`#edb3f6`,stroke:t.emProcessorStroke??`#b88cbf`};case`rmo`:case`readmodel`:return{fill:t.emReadModelFill??`#d3f1a2`,stroke:t.emReadModelStroke??`#a3b732`};case`cmd`:case`command`:return{fill:t.emCommandFill??`#bcd6fe`,stroke:t.emCommandStroke??`#679ac3`};case`evt`:case`event`:return{fill:t.emEventFill??`#ffb778`,stroke:t.emEventStroke??`#c19a0f`};default:return{fill:`red`,stroke:`black`}}}t(M,`calculateEntityVisualProps`);function N(e,t,r){let i=l(),a=h(O(e.entityIdentifier)??``,i),o,s={fontSize:16,fontWeight:700,fontFamily:`"trebuchet ms", verdana, arial, sans-serif`,joinWith:`
`},c=`${g(a,r.textMaxWidth,s)}`;if(e.dataInlineValue&&(o=e.dataInlineValue,o=o.substring(o.indexOf(`{`)+1),o=o.substring(0,o.lastIndexOf(`}`)-1),o=h(o,i),o=g(o,r.textMaxWidth,s),o=o.replaceAll(` `,` `)),e.dataReference){let n=t.find(t=>t.name===e.dataReference?.$refText);n&&(o=n.dataBlockValue,o=o.substring(o.indexOf(`{ +import{T as e}from"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n,p as r}from"./src-UMNXGZaF.js";import{H as i,K as a,U as o,Y as s,a as c,b as l,f as u,v as d,w as f,x as p,y as m,z as h}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{_ as g,i as ee,t as te}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as ne}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as re}from"./mermaid-parser.core-Z7xZAZRH.js";var _=`position frame`,v=`frame positioned`,y=`position relation`,b=`relation positioned`,ie=t(function(e){n.debug(`options str`,e)},`setOptions`),ae=t(function(){return{}},`getOptions`),oe=t(function(){x(),c()},`clear`);function x(){S={}}t(x,`reset`);var se=u.eventmodeling,ce=t(()=>ee({...se,...l().eventmodeling}),`getConfig`),S={};function C(){let e=le,{ast:t}=S,r=E();if(!t)throw Error(`No data for EventModel`);return t.frames.forEach((i,a)=>{let o=N(i,t.dataEntities,r);e=q(e,{$kind:_,index:a,frame:i,textProps:o});let s;B(i)?(n.debug(`source frame`,i.sourceFrames),s=t.frames.filter(e=>i.sourceFrames.some(t=>t.$refText===e.name)),s.forEach(t=>{e=q(e,{$kind:y,index:a,frame:i,sourceFrame:t})})):e=q(e,{$kind:y,index:a,frame:i})}),e={...e,sortedSwimlanesArray:L(e.swimlanes)},e}t(C,`getState`);function w(e){S.ast=e}t(w,`setAst`);var T={swimlaneMinHeight:70,swimlanePadding:15,swimlaneGap:10,boxPadding:10,boxOverlap:90,boxDefaultY:0,boxMinWidth:80,boxMaxWidth:450,boxMinHeight:80,boxMaxHeight:750,contentStartX:250,textMaxWidth:430,boxTextFontWeight:`bold`,boxTextPadding:10,swimlaneTextFontWeight:`bold`,labelUiAutomation:`UI/Automation`,labelUiAutomationPrefix:`UI/A: `,labelCommandReadModel:`Command/Read Model`,labelCommandReadModelPrefix:`C/RM: `,labelEvents:`Events`,labelEventsPrefix:`Stream: `};function E(){return T}t(E,`getDiagramProps`);var le={boxes:[],swimlanes:{},relations:[],maxR:0,sortedSwimlanesArray:[]};function D(e){let t=e.split(`.`);if(t.length===2)return t[0]}t(D,`extractNamespace`);function O(e){let t=e.split(`.`);return t.length===2?t[1]:e}t(O,`extractName`);function k(e,t){if(!(!t||t.length===0))return Object.values(e).find(e=>e.namespace===t)}t(k,`findSwimlaneByNamespace`);function A(e,t,n){return Math.max(t,...Object.keys(e).filter(e=>{let r=Number.parseInt(e);return r>t&&rNumber.parseInt(e)))+1}t(A,`findNextAvailableIndex`);function j(e,t){let n=D(e.entityIdentifier),r=k(t,n);switch(e.modelEntityType){case`ui`:case`pcr`:case`processor`:return r?{index:r.index,label:r.namespace||T.labelUiAutomation}:n?{index:A(t,0,100),label:T.labelUiAutomationPrefix+n}:{index:0,label:T.labelUiAutomation};case`rmo`:case`readmodel`:case`cmd`:case`command`:return r?{index:r.index,label:r.namespace||T.labelCommandReadModel}:n?{index:A(t,100,200),label:T.labelCommandReadModelPrefix+n}:{index:100,label:T.labelCommandReadModel};default:return r?{index:r.index,label:r.namespace||T.labelEvents}:n?{index:A(t,200,300),label:T.labelEventsPrefix+n}:{index:200,label:T.labelEvents}}}t(j,`calculateSwimlaneProps`);function M(e){let{themeVariables:t}=l();switch(e.modelEntityType){case`ui`:return{fill:t.emUiFill??`white`,stroke:t.emUiStroke??`#dbdada`};case`pcr`:case`processor`:return{fill:t.emProcessorFill??`#edb3f6`,stroke:t.emProcessorStroke??`#b88cbf`};case`rmo`:case`readmodel`:return{fill:t.emReadModelFill??`#d3f1a2`,stroke:t.emReadModelStroke??`#a3b732`};case`cmd`:case`command`:return{fill:t.emCommandFill??`#bcd6fe`,stroke:t.emCommandStroke??`#679ac3`};case`evt`:case`event`:return{fill:t.emEventFill??`#ffb778`,stroke:t.emEventStroke??`#c19a0f`};default:return{fill:`red`,stroke:`black`}}}t(M,`calculateEntityVisualProps`);function N(e,t,r){let i=l(),a=h(O(e.entityIdentifier)??``,i),o,s={fontSize:16,fontWeight:700,fontFamily:`"trebuchet ms", verdana, arial, sans-serif`,joinWith:`
`},c=`${g(a,r.textMaxWidth,s)}`;if(e.dataInlineValue&&(o=e.dataInlineValue,o=o.substring(o.indexOf(`{`)+1),o=o.substring(0,o.lastIndexOf(`}`)-1),o=h(o,i),o=g(o,r.textMaxWidth,s),o=o.replaceAll(` `,` `)),e.dataReference){let n=t.find(t=>t.name===e.dataReference?.$refText);n&&(o=n.dataBlockValue,o=o.substring(o.indexOf(`{ `)+2),o=o.substring(0,o.lastIndexOf(`}`)-1),o=h(o,i),o=g(o,r.textMaxWidth,s),o=o.replaceAll(` `,` `),o+=`
`)}let u=o!==void 0;u&&(c+=`

${o}`);let d={fontSize:s.fontSize,fontWeight:s.fontWeight,fontFamily:s.fontFamily},f=te(c,d),p=u?f.width/3:f.width,m={content:c,width:p,height:f.height};return n.debug(`[${e.name}] ${e.entityIdentifier} text`,m),m}t(N,`calculateTextProps`);function P(e,t){let n=t,r=M(n.frame),i={width:n.textProps.width+2*T.boxTextPadding,height:n.textProps.height+2*T.boxTextPadding};return[{$kind:v,frame:n.frame,index:n.index,visual:r,dimension:i,textProps:n.textProps}]}t(P,`decidePositionFrame`);function F(e,t,n){return t===void 0?T.contentStartX:t.index===e.index&&e.r?e.r+T.boxPadding:n===void 0?T.contentStartX:n.r-T.boxOverlap+T.boxPadding}t(F,`calculateX`);function I(e,t){let n=[...e.map(e=>e.r),t];return Math.max(...n)}t(I,`calculateMaxRight`);function L(e){return Object.values(e).sort((e,t)=>e.index-t.index)}t(L,`sortedSwimlanesArray`);function R(e,t){let n=t,r=j(n.frame,e.swimlanes),i;i=r.index in e.swimlanes?e.swimlanes[r.index]:{index:r.index,label:r.label,r:0,y:r.index*T.swimlaneMinHeight+T.swimlaneGap,height:T.swimlaneMinHeight,maxHeight:T.swimlaneMinHeight};let a=e.boxes.length>0?e.boxes[e.boxes.length-1]:void 0,o=e.previousSwimlaneNumber===void 0?void 0:e.swimlanes[e.previousSwimlaneNumber],s={width:Math.max(T.boxMinWidth,Math.min(T.boxMaxWidth,n.dimension.width))+2*T.boxPadding,height:Math.max(T.boxMinHeight,Math.min(T.boxMaxHeight,n.dimension.height))+2*T.boxPadding},c=F(i,o,a),l=c+s.width+T.boxPadding,u=I(Object.values(e.swimlanes),l);i.r=c+s.width,i.maxHeight=Math.max(i.maxHeight,s.height),i.height=Math.max(T.swimlaneMinHeight,i.maxHeight)+2*T.swimlanePadding;let d={x:c,y:T.swimlanePadding+i.y,r:l,dimension:s,leftSibling:!1,swimlane:i,visual:n.visual,text:n.textProps.content,frame:n.frame,index:n.index},f={...e,boxes:[...e.boxes,d],swimlanes:{...e.swimlanes,[`${i.index}`]:i},previousSwimlaneNumber:r.index,previousFrame:n.frame,maxR:u},p=L(f.swimlanes);p.length>0&&(p[0].y=0);for(let e=1;e0}t(B,`hasSourceFrame`);function V(e,t){if(t!=null)return e.find(e=>e.frame.name===t.name)}t(V,`findBoxByFrame`);function H(e,t,n){if(!(n<0))for(let r=n;r>=0;r--){let n=e[r];if(n.swimlane.index!==t)return n}}t(H,`findBoxByLineIndex`);function U(t,n){let r=n;if(e(r.frame)||z(r.index,r.frame))return[];let i=V(t.boxes,r.frame);if(i===void 0)throw Error(`Target box not found for frame ${r.frame.name}`);let a;return a=r.sourceFrame?V(t.boxes,r.sourceFrame):H(t.boxes,i.swimlane.index,r.index-1),a===void 0?[]:[{$kind:b,frame:r.frame,index:r.index,sourceBox:a,targetBox:i}]}t(U,`decidePositionRelation`);function W(e,t){let n=t,r={visual:{fill:`none`,stroke:`#000`},source:{x:n.sourceBox.x,y:n.sourceBox.y},target:{x:n.targetBox.x,y:n.targetBox.y},sourceBox:n.sourceBox,targetBox:n.targetBox};return{...e,relations:[...e.relations,r]}}t(W,`evolveRelationPositioned`);var ue={[_]:P,[y]:U},de={[v]:R,[b]:W};function G(e,t){let r=ue[t.$kind];if(r==null)return[];let i=r(e,t);return n.debug(`decided events`,i),i}t(G,`decide`);function K(e,t){let r=t.reduce((e,t)=>{let n=de[t.$kind];return n==null?e:n(e,t)},e);return n.debug(`evolve events`,{state:e,newState:r,events:t}),r}t(K,`evolve`);function q(e,t){return K(e,G(e,t))}t(q,`dispatch`);var J={getConfig:ce,setOptions:ie,getOptions:ae,clear:oe,setAccTitle:o,getAccTitle:m,getAccDescription:d,setAccDescription:i,setDiagramTitle:a,getDiagramTitle:f,setAst:w,getDiagramProps:E,getState:C},fe={parse:t(async e=>{let t=await re(`eventmodeling`,e);n.debug(t),J.setAst(t),ne(t,J)},`parse`)},Y=p()?.eventmodeling;function X(e,t){return n=>{let r=n.swimlane.y+t.swimlanePadding,i=e.append(`g`).attr(`class`,`em-box`);i.append(`rect`).attr(`x`,n.x).attr(`y`,r).attr(`rx`,`3`).attr(`width`,n.dimension.width).attr(`height`,n.dimension.height).attr(`stroke`,n.visual.stroke).attr(`fill`,n.visual.fill),i.append(`foreignObject`).attr(`x`,n.x+t.boxPadding).attr(`y`,r+10).attr(`width`,n.dimension.width-2*t.boxPadding).attr(`height`,n.dimension.height-2*t.boxPadding).append(`xhtml:div`).style(`display`,`table`).style(`height`,`100%`).style(`width`,`100%`).append(`span`).style(`display`,`table-cell`).style(`text-align`,`center`).style(`vertical-align`,`middle`).html(n.text)}}t(X,`renderD3Box`);function Z(e,t){return e>t}t(Z,`dirUpwards`);function Q(e,t,r,i){return a=>{let o=a.sourceBox.swimlane.y+t.swimlanePadding,s=a.targetBox.swimlane.y+t.swimlanePadding,c=Z(o,s),l=a.sourceBox.x+a.sourceBox.dimension.width*2/3,u=a.targetBox.x+a.targetBox.dimension.width/3,d,f;n.debug(`rendering relation up=${c} for `,{sourceBox:a.sourceBox,targetBox:a.targetBox}),c?(d=o,f=s+a.targetBox.dimension.height):(d=o+a.sourceBox.dimension.height,f=s);let p=i.emRelationStroke??a.visual.stroke;e.append(`path`).attr(`class`,`em-relation`).attr(`fill`,a.visual.fill).attr(`stroke`,p).attr(`stroke-width`,`1`).attr(`marker-end`,`url(#${r})`).attr(`d`,`M${l} ${d} L${u} ${f}`)}}t(Q,`renderD3Relation`);function $(e,t,n,r){return i=>{let a=e.append(`g`).attr(`class`,`em-swimlane`),o=r.emSwimlaneBackgroundOdd??`rgb(250,250,250)`,s=r.emSwimlaneBackgroundStroke??`rgb(240,240,240)`;a.append(`rect`).attr(`x`,0).attr(`y`,i.y).attr(`rx`,`3`).attr(`width`,t+n.swimlanePadding).attr(`height`,i.height).attr(`fill`,o).attr(`stroke`,s),a.append(`text`).attr(`font-weight`,n.swimlaneTextFontWeight).attr(`x`,30).attr(`y`,i.y+30).text(i.label)}}t($,`renderD3Swimlane`);var pe={parser:fe,db:J,renderer:{draw:t(function(e,t,i,a){if(n.debug(`in eventmodeling renderer`,e+` `,`id:`,t,i),!Y)throw Error(`EventModeling config not found`);let o=a.db,{themeVariables:c,eventmodeling:l}=p(),u=r(`[id="${t}"]`),d=o.getDiagramProps(),f=o.getState(),m=`em-arrowhead-${t}`,h=c.emArrowhead??`#000000`;f.sortedSwimlanesArray.forEach($(u,f.maxR,d,c)),f.boxes.forEach(X(u,d)),f.relations.forEach(Q(u,d,m,c)),u.append(`defs`).append(`marker`).attr(`id`,m).attr(`markerWidth`,`10`).attr(`markerHeight`,`7`).attr(`refX`,`10`).attr(`refY`,`3.5`).attr(`orient`,`auto`).append(`polygon`).attr(`points`,`0 0, 10 3.5, 0 7`).attr(`fill`,h),s(void 0,u,l?.padding??30,l?.useMaxWidth)},`draw`)},styles:t(e=>``,`getStyles`)};export{pe as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/diagram-G47NLZAW-By0HJNEW.js b/.vercel/output/static/assets/diagram-G47NLZAW-B5XCVQOu.js similarity index 97% rename from .vercel/output/static/assets/diagram-G47NLZAW-By0HJNEW.js rename to .vercel/output/static/assets/diagram-G47NLZAW-B5XCVQOu.js index db5961b..e6a7d73 100644 --- a/.vercel/output/static/assets/diagram-G47NLZAW-By0HJNEW.js +++ b/.vercel/output/static/assets/diagram-G47NLZAW-B5XCVQOu.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{D as r,H as i,K as a,U as o,a as s,b as c,c as l,f as u,v as d,w as f,y as p}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as m}from"./ordinal-hYBb2elL.js";import{t as h}from"./defaultLocale-C8Fc0cco.js";import{i as g}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as _}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{t as v}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as y}from"./mermaid-parser.core-AdnthA1k.js";import{t as b}from"./chunk-VR4S4FIN-BJzXasDJ.js";import{i as x,n as S}from"./chunk-C7G6YPKG-DJfjwbsZ.js";function C(e){var t=0,n=e.children,r=n&&n.length;if(!r)t=1;else for(;--r>=0;)t+=n[r].value;e.value=t}function w(){return this.eachAfter(C)}function T(e,t){let n=-1;for(let r of this)e.call(t,r,++n,this);return this}function E(e,t){for(var n=this,r=[n],i,a,o=-1;n=r.pop();)if(e.call(t,n,++o,this),i=n.children)for(a=i.length-1;a>=0;--a)r.push(i[a]);return this}function D(e,t){for(var n=this,r=[n],i=[],a,o,s,c=-1;n=r.pop();)if(i.push(n),a=n.children)for(o=0,s=a.length;o=0;)n+=r[i].value;t.value=n})}function A(e){return this.eachBefore(function(t){t.children&&t.children.sort(e)})}function j(e){for(var t=this,n=M(t,e),r=[t];t!==n;)t=t.parent,r.push(t);for(var i=r.length;e!==n;)r.splice(i,0,e),e=e.parent;return r}function M(e,t){if(e===t)return e;var n=e.ancestors(),r=t.ancestors(),i=null;for(e=n.pop(),t=r.pop();e===t;)i=e,e=n.pop(),t=r.pop();return i}function N(){for(var e=this,t=[e];e=e.parent;)t.push(e);return t}function P(){return Array.from(this)}function F(){var e=[];return this.eachBefore(function(t){t.children||e.push(t)}),e}function I(){var e=this,t=[];return e.each(function(n){n!==e&&t.push({source:n.parent,target:n})}),t}function*L(){var e=this,t,n=[e],r,i,a;do for(t=n.reverse(),n=[];e=t.pop();)if(yield e,r=e.children)for(i=0,a=r.length;i=0;--s)i.push(a=o[s]=new W(o[s])),a.parent=r,a.depth=r.depth+1;return n.eachBefore(U)}function z(){return R(this).eachBefore(H)}function B(e){return e.children}function V(e){return Array.isArray(e)?e[1]:null}function H(e){e.data.value!==void 0&&(e.value=e.data.value),e.data=e.data.data}function U(e){var t=0;do e.height=t;while((e=e.parent)&&e.height<++t)}function W(e){this.data=e,this.depth=this.height=0,this.parent=null}W.prototype=R.prototype={constructor:W,count:w,each:T,eachAfter:D,eachBefore:E,find:O,sum:k,sort:A,path:j,ancestors:N,descendants:P,leaves:F,links:I,copy:z,[Symbol.iterator]:L};function G(e){if(typeof e!=`function`)throw Error();return e}function K(){return 0}function q(e){return function(){return e}}function J(e){e.x0=Math.round(e.x0),e.y0=Math.round(e.y0),e.x1=Math.round(e.x1),e.y1=Math.round(e.y1)}function ee(e,t,n,r,i){for(var a=e.children,o,s=-1,c=a.length,l=e.value&&(r-t)/e.value;++sv&&(v=l),S=g*g*x,y=Math.max(v/S,S/_),y>b){g-=l;break}b=y}o.push(c={value:g,dice:p1?t:1)},n})(ne);function ae(){var e=ie,t=!1,n=1,r=1,i=[0],a=K,o=K,s=K,c=K,l=K;function u(e){return e.x0=e.y0=0,e.x1=n,e.y1=r,e.eachBefore(d),i=[0],t&&e.eachBefore(J),e}function d(t){var n=i[t.depth],r=t.x0+n,u=t.y0+n,d=t.x1-n,f=t.y1-n;d{S(e)&&(n?.textStyles?n.textStyles.push(e):n.textStyles=[e]),n?.styles?n.styles.push(e):n.styles=[e]}),this.classes.set(e,n)}getClasses(){return this.classes}getStylesForClass(e){return this.classes.get(e)?.styles??[]}clear(){s(),this.nodes=[],this.levels=new Map,this.outerNodes=[],this.classes=new Map,this.root=void 0}};function X(e){if(!e.length)return[];let t=[],n=[];return e.forEach(e=>{let r={name:e.name,children:e.type===`Leaf`?void 0:[]};for(r.classSelector=e?.classSelector,e?.cssCompiledStyles&&(r.cssCompiledStyles=e.cssCompiledStyles),e.type===`Leaf`&&e.value!==void 0&&(r.value=e.value);n.length>0&&n[n.length-1].level>=e.level;)n.pop();if(n.length===0)t.push(r);else{let e=n[n.length-1].node;e.children?e.children.push(r):e.children=[r]}e.type!==`Leaf`&&n.push({node:r,level:e.level})}),t}e(X,`buildHierarchy`);var oe=e((t,n)=>{v(t,n);let r=[];for(let e of t.TreemapRows??[])e.$type===`ClassDefStatement`&&n.addClass(e.className??``,e.styleText??``);for(let e of t.TreemapRows??[]){let t=e.item;if(!t)continue;let i=e.indent?parseInt(e.indent):0,a=se(t),o=t.classSelector?n.getStylesForClass(t.classSelector):[],s=o.length>0?o:void 0,c={level:i,name:a,type:t.$type,value:t.value,classSelector:t.classSelector,cssCompiledStyles:s};r.push(c)}let i=X(r),a=e((e,t)=>{for(let r of e)n.addNode(r,t),r.children&&r.children.length>0&&a(r.children,t+1)},`addNodesRecursively`);a(i,0)},`populate`),se=e(e=>e.name?String(e.name):``,`getItemName`),Z={parser:{yy:void 0},parse:e(async e=>{try{let n=await y(`treemap`,e);t.debug(`Treemap AST:`,n);let r=Z.parser?.yy;if(!(r instanceof Y))throw Error(`parser.parser?.yy was not a TreemapDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);oe(n,r)}catch(e){throw t.error(`Error parsing treemap:`,e),e}},`parse`)},ce=10,Q=10,$=25,le={draw:e((r,i,a,o)=>{let s=o.db,u=s.getConfig(),d=u.padding??ce,f=s.getDiagramTitle(),p=s.getRoot(),{themeVariables:g}=c();if(!p)return;let v=f?30:0,y=_(i),S=u.nodeWidth?u.nodeWidth*Q:960,C=u.nodeHeight?u.nodeHeight*Q:500,w=S,T=C+v;y.attr(`viewBox`,`0 0 ${w} ${T}`),l(y,T,w,u.useMaxWidth);let E;try{let t=u.valueFormat||`,`;if(t===`$0,0`)E=e(e=>`$`+h(`,`)(e),`valueFormat`);else if(t.startsWith(`$`)&&t.includes(`,`)){let n=/\.\d+/.exec(t),r=n?n[0]:``;E=e(e=>`$`+h(`,`+r)(e),`valueFormat`)}else if(t.startsWith(`$`)){let n=t.substring(1);E=e(e=>`$`+h(n||``)(e),`valueFormat`)}else E=h(t)}catch(e){t.error(`Error creating format function:`,e),E=h(`,`)}let D=m().range([`transparent`,g.cScale0,g.cScale1,g.cScale2,g.cScale3,g.cScale4,g.cScale5,g.cScale6,g.cScale7,g.cScale8,g.cScale9,g.cScale10,g.cScale11]),O=m().range([`transparent`,g.cScalePeer0,g.cScalePeer1,g.cScalePeer2,g.cScalePeer3,g.cScalePeer4,g.cScalePeer5,g.cScalePeer6,g.cScalePeer7,g.cScalePeer8,g.cScalePeer9,g.cScalePeer10,g.cScalePeer11]),k=m().range([g.cScaleLabel0,g.cScaleLabel1,g.cScaleLabel2,g.cScaleLabel3,g.cScaleLabel4,g.cScaleLabel5,g.cScaleLabel6,g.cScaleLabel7,g.cScaleLabel8,g.cScaleLabel9,g.cScaleLabel10,g.cScaleLabel11]);f&&y.append(`text`).attr(`x`,w/2).attr(`y`,v/2).attr(`class`,`treemapTitle`).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(f);let A=y.append(`g`).attr(`transform`,`translate(0, ${v})`).attr(`class`,`treemapContainer`),j=R(p).sum(e=>e.value??0).sort((e,t)=>(t.value??0)-(e.value??0)),M=ae().size([S,C]).paddingTop(e=>e.children&&e.children.length>0?$+Q:0).paddingInner(d).paddingLeft(e=>e.children&&e.children.length>0?Q:0).paddingRight(e=>e.children&&e.children.length>0?Q:0).paddingBottom(e=>e.children&&e.children.length>0?Q:0).round(!0)(j),N=M.descendants().filter(e=>e.children&&e.children.length>0),P=A.selectAll(`.treemapSection`).data(N).enter().append(`g`).attr(`class`,`treemapSection`).attr(`transform`,e=>`translate(${e.x0},${e.y0})`);P.append(`rect`).attr(`width`,e=>e.x1-e.x0).attr(`height`,$).attr(`class`,`treemapSectionHeader`).attr(`fill`,`none`).attr(`fill-opacity`,.6).attr(`stroke-width`,.6).attr(`style`,e=>e.depth===0?`display: none;`:``),P.append(`clipPath`).attr(`id`,(e,t)=>`clip-section-${i}-${t}`).append(`rect`).attr(`width`,e=>Math.max(0,e.x1-e.x0-12)).attr(`height`,$),P.append(`rect`).attr(`width`,e=>e.x1-e.x0).attr(`height`,e=>e.y1-e.y0).attr(`class`,(e,t)=>`treemapSection section${t}`).attr(`fill`,e=>D(e.data.name)).attr(`fill-opacity`,.6).attr(`stroke`,e=>O(e.data.name)).attr(`stroke-width`,2).attr(`stroke-opacity`,.4).attr(`style`,e=>{if(e.depth===0)return`display: none;`;let t=x({cssCompiledStyles:e.data.cssCompiledStyles});return t.nodeStyles+`;`+t.borderStyles.join(`;`)}),P.append(`text`).attr(`class`,`treemapSectionLabel`).attr(`x`,6).attr(`y`,$/2).attr(`dominant-baseline`,`middle`).text(e=>e.depth===0?``:e.data.name).attr(`font-weight`,`bold`).attr(`clip-path`,(e,t)=>`url(#clip-section-${i}-${t})`).attr(`style`,e=>e.depth===0?`display: none;`:`dominant-baseline: middle; font-size: 12px; fill:`+k(e.data.name)+`; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`)).each(function(e){if(e.depth===0)return;let t=n(this),r=e.data.name;t.text(r);let i=e.x1-e.x0,a;a=u.showValues!==!1&&e.value?i-10-30-10-6:i-6-6;let o=Math.max(15,a),s=t.node();if(s.getComputedTextLength()>o){let e=r;for(;e.length>0;){if(e=r.substring(0,e.length-1),e.length===0){t.text(`...`),s.getComputedTextLength()>o&&t.text(``);break}if(t.text(e+`...`),s.getComputedTextLength()<=o)break}}}),u.showValues!==!1&&P.append(`text`).attr(`class`,`treemapSectionValue`).attr(`x`,e=>e.x1-e.x0-10).attr(`y`,$/2).attr(`text-anchor`,`end`).attr(`dominant-baseline`,`middle`).text(e=>e.value?E(e.value):``).attr(`font-style`,`italic`).attr(`style`,e=>e.depth===0?`display: none;`:`text-anchor: end; dominant-baseline: middle; font-size: 10px; fill:`+k(e.data.name)+`; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`));let F=M.leaves(),I=F.length>20,L=I?16:38,z=I?14:28,B=I?4:8,V=I?4:6,H=I?2:4,U=I?8:10,W=I?1:2,G=A.selectAll(`.treemapLeafGroup`).data(F).enter().append(`g`).attr(`class`,(e,t)=>`treemapNode treemapLeafGroup leaf${t}${e.data.classSelector?` ${e.data.classSelector}`:``}x`).attr(`transform`,e=>`translate(${e.x0},${e.y0})`);G.append(`rect`).attr(`width`,e=>e.x1-e.x0).attr(`height`,e=>e.y1-e.y0).attr(`class`,`treemapLeaf`).attr(`fill`,e=>e.parent?D(e.parent.data.name):D(e.data.name)).attr(`style`,e=>x({cssCompiledStyles:e.data.cssCompiledStyles}).nodeStyles).attr(`fill-opacity`,.3).attr(`stroke`,e=>e.parent?D(e.parent.data.name):D(e.data.name)).attr(`stroke-width`,3),G.append(`clipPath`).attr(`id`,(e,t)=>`clip-${i}-${t}`).append(`rect`).attr(`width`,e=>Math.max(0,e.x1-e.x0-4)).attr(`height`,e=>Math.max(0,e.y1-e.y0-4)),G.append(`text`).attr(`class`,`treemapLabel`).attr(`x`,e=>(e.x1-e.x0)/2).attr(`y`,e=>(e.y1-e.y0)/2).attr(`style`,e=>`text-anchor: middle; dominant-baseline: middle; font-size: ${L}px;fill:`+k(e.data.name)+`;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`)).attr(`clip-path`,(e,t)=>`url(#clip-${i}-${t})`).text(e=>e.data.name).each(function(e){let t=n(this),r=e.x1-e.x0,i=e.y1-e.y0,a=t.node(),o=r-2*H,s=i-2*H;if(oo&&c>B;)c--,t.style(`font-size`,`${c}px`);let u=Math.max(V,Math.min(z,Math.round(c*l))),d=c+W+u;for(;d>s&&c>B&&(c--,u=Math.max(V,Math.min(z,Math.round(c*l))),!(uo||c(e.x1-e.x0)/2).attr(`y`,function(e){return(e.y1-e.y0)/2}).attr(`style`,e=>`text-anchor: middle; dominant-baseline: hanging; font-size: ${z}px;fill:`+k(e.data.name)+`;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`)).attr(`clip-path`,(e,t)=>`url(#clip-${i}-${t})`).text(e=>e.value?E(e.value):``).each(function(e){let t=n(this),r=this.parentNode;if(!r){t.style(`display`,`none`);return}let i=n(r).select(`.treemapLabel`);if(i.empty()||i.style(`display`)===`none`){t.style(`display`,`none`);return}let a=parseFloat(i.style(`font-size`)),o=Math.max(V,Math.min(z,Math.round(a*.6)));t.style(`font-size`,`${o}px`);let s=(e.y1-e.y0)/2+a/2+W;t.attr(`y`,s);let c=e.x1-e.x0,l=e.y1-e.y0-4,u=c-2*H;t.node().getComputedTextLength()>u||s+o>l||o{let t=g(r(),c().themeVariables),n=g(ue,e),i=n.titleColor??t.titleColor,a=n.labelColor??t.textColor,o=n.valueColor??t.textColor;return` +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{D as r,H as i,K as a,U as o,a as s,b as c,c as l,f as u,v as d,w as f,y as p}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as m}from"./ordinal-hYBb2elL.js";import{t as h}from"./defaultLocale-C8Fc0cco.js";import{i as g}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as _}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as v}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as y}from"./mermaid-parser.core-Z7xZAZRH.js";import{t as b}from"./chunk-VR4S4FIN-BTo4eV3J.js";import{i as x,n as S}from"./chunk-C7G6YPKG-DW-1jWUA.js";function C(e){var t=0,n=e.children,r=n&&n.length;if(!r)t=1;else for(;--r>=0;)t+=n[r].value;e.value=t}function w(){return this.eachAfter(C)}function T(e,t){let n=-1;for(let r of this)e.call(t,r,++n,this);return this}function E(e,t){for(var n=this,r=[n],i,a,o=-1;n=r.pop();)if(e.call(t,n,++o,this),i=n.children)for(a=i.length-1;a>=0;--a)r.push(i[a]);return this}function D(e,t){for(var n=this,r=[n],i=[],a,o,s,c=-1;n=r.pop();)if(i.push(n),a=n.children)for(o=0,s=a.length;o=0;)n+=r[i].value;t.value=n})}function A(e){return this.eachBefore(function(t){t.children&&t.children.sort(e)})}function j(e){for(var t=this,n=M(t,e),r=[t];t!==n;)t=t.parent,r.push(t);for(var i=r.length;e!==n;)r.splice(i,0,e),e=e.parent;return r}function M(e,t){if(e===t)return e;var n=e.ancestors(),r=t.ancestors(),i=null;for(e=n.pop(),t=r.pop();e===t;)i=e,e=n.pop(),t=r.pop();return i}function N(){for(var e=this,t=[e];e=e.parent;)t.push(e);return t}function P(){return Array.from(this)}function F(){var e=[];return this.eachBefore(function(t){t.children||e.push(t)}),e}function I(){var e=this,t=[];return e.each(function(n){n!==e&&t.push({source:n.parent,target:n})}),t}function*L(){var e=this,t,n=[e],r,i,a;do for(t=n.reverse(),n=[];e=t.pop();)if(yield e,r=e.children)for(i=0,a=r.length;i=0;--s)i.push(a=o[s]=new W(o[s])),a.parent=r,a.depth=r.depth+1;return n.eachBefore(U)}function z(){return R(this).eachBefore(H)}function B(e){return e.children}function V(e){return Array.isArray(e)?e[1]:null}function H(e){e.data.value!==void 0&&(e.value=e.data.value),e.data=e.data.data}function U(e){var t=0;do e.height=t;while((e=e.parent)&&e.height<++t)}function W(e){this.data=e,this.depth=this.height=0,this.parent=null}W.prototype=R.prototype={constructor:W,count:w,each:T,eachAfter:D,eachBefore:E,find:O,sum:k,sort:A,path:j,ancestors:N,descendants:P,leaves:F,links:I,copy:z,[Symbol.iterator]:L};function G(e){if(typeof e!=`function`)throw Error();return e}function K(){return 0}function q(e){return function(){return e}}function J(e){e.x0=Math.round(e.x0),e.y0=Math.round(e.y0),e.x1=Math.round(e.x1),e.y1=Math.round(e.y1)}function ee(e,t,n,r,i){for(var a=e.children,o,s=-1,c=a.length,l=e.value&&(r-t)/e.value;++sv&&(v=l),S=g*g*x,y=Math.max(v/S,S/_),y>b){g-=l;break}b=y}o.push(c={value:g,dice:p1?t:1)},n})(ne);function ae(){var e=ie,t=!1,n=1,r=1,i=[0],a=K,o=K,s=K,c=K,l=K;function u(e){return e.x0=e.y0=0,e.x1=n,e.y1=r,e.eachBefore(d),i=[0],t&&e.eachBefore(J),e}function d(t){var n=i[t.depth],r=t.x0+n,u=t.y0+n,d=t.x1-n,f=t.y1-n;d{S(e)&&(n?.textStyles?n.textStyles.push(e):n.textStyles=[e]),n?.styles?n.styles.push(e):n.styles=[e]}),this.classes.set(e,n)}getClasses(){return this.classes}getStylesForClass(e){return this.classes.get(e)?.styles??[]}clear(){s(),this.nodes=[],this.levels=new Map,this.outerNodes=[],this.classes=new Map,this.root=void 0}};function X(e){if(!e.length)return[];let t=[],n=[];return e.forEach(e=>{let r={name:e.name,children:e.type===`Leaf`?void 0:[]};for(r.classSelector=e?.classSelector,e?.cssCompiledStyles&&(r.cssCompiledStyles=e.cssCompiledStyles),e.type===`Leaf`&&e.value!==void 0&&(r.value=e.value);n.length>0&&n[n.length-1].level>=e.level;)n.pop();if(n.length===0)t.push(r);else{let e=n[n.length-1].node;e.children?e.children.push(r):e.children=[r]}e.type!==`Leaf`&&n.push({node:r,level:e.level})}),t}e(X,`buildHierarchy`);var oe=e((t,n)=>{v(t,n);let r=[];for(let e of t.TreemapRows??[])e.$type===`ClassDefStatement`&&n.addClass(e.className??``,e.styleText??``);for(let e of t.TreemapRows??[]){let t=e.item;if(!t)continue;let i=e.indent?parseInt(e.indent):0,a=se(t),o=t.classSelector?n.getStylesForClass(t.classSelector):[],s=o.length>0?o:void 0,c={level:i,name:a,type:t.$type,value:t.value,classSelector:t.classSelector,cssCompiledStyles:s};r.push(c)}let i=X(r),a=e((e,t)=>{for(let r of e)n.addNode(r,t),r.children&&r.children.length>0&&a(r.children,t+1)},`addNodesRecursively`);a(i,0)},`populate`),se=e(e=>e.name?String(e.name):``,`getItemName`),Z={parser:{yy:void 0},parse:e(async e=>{try{let n=await y(`treemap`,e);t.debug(`Treemap AST:`,n);let r=Z.parser?.yy;if(!(r instanceof Y))throw Error(`parser.parser?.yy was not a TreemapDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);oe(n,r)}catch(e){throw t.error(`Error parsing treemap:`,e),e}},`parse`)},ce=10,Q=10,$=25,le={draw:e((r,i,a,o)=>{let s=o.db,u=s.getConfig(),d=u.padding??ce,f=s.getDiagramTitle(),p=s.getRoot(),{themeVariables:g}=c();if(!p)return;let v=f?30:0,y=_(i),S=u.nodeWidth?u.nodeWidth*Q:960,C=u.nodeHeight?u.nodeHeight*Q:500,w=S,T=C+v;y.attr(`viewBox`,`0 0 ${w} ${T}`),l(y,T,w,u.useMaxWidth);let E;try{let t=u.valueFormat||`,`;if(t===`$0,0`)E=e(e=>`$`+h(`,`)(e),`valueFormat`);else if(t.startsWith(`$`)&&t.includes(`,`)){let n=/\.\d+/.exec(t),r=n?n[0]:``;E=e(e=>`$`+h(`,`+r)(e),`valueFormat`)}else if(t.startsWith(`$`)){let n=t.substring(1);E=e(e=>`$`+h(n||``)(e),`valueFormat`)}else E=h(t)}catch(e){t.error(`Error creating format function:`,e),E=h(`,`)}let D=m().range([`transparent`,g.cScale0,g.cScale1,g.cScale2,g.cScale3,g.cScale4,g.cScale5,g.cScale6,g.cScale7,g.cScale8,g.cScale9,g.cScale10,g.cScale11]),O=m().range([`transparent`,g.cScalePeer0,g.cScalePeer1,g.cScalePeer2,g.cScalePeer3,g.cScalePeer4,g.cScalePeer5,g.cScalePeer6,g.cScalePeer7,g.cScalePeer8,g.cScalePeer9,g.cScalePeer10,g.cScalePeer11]),k=m().range([g.cScaleLabel0,g.cScaleLabel1,g.cScaleLabel2,g.cScaleLabel3,g.cScaleLabel4,g.cScaleLabel5,g.cScaleLabel6,g.cScaleLabel7,g.cScaleLabel8,g.cScaleLabel9,g.cScaleLabel10,g.cScaleLabel11]);f&&y.append(`text`).attr(`x`,w/2).attr(`y`,v/2).attr(`class`,`treemapTitle`).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(f);let A=y.append(`g`).attr(`transform`,`translate(0, ${v})`).attr(`class`,`treemapContainer`),j=R(p).sum(e=>e.value??0).sort((e,t)=>(t.value??0)-(e.value??0)),M=ae().size([S,C]).paddingTop(e=>e.children&&e.children.length>0?$+Q:0).paddingInner(d).paddingLeft(e=>e.children&&e.children.length>0?Q:0).paddingRight(e=>e.children&&e.children.length>0?Q:0).paddingBottom(e=>e.children&&e.children.length>0?Q:0).round(!0)(j),N=M.descendants().filter(e=>e.children&&e.children.length>0),P=A.selectAll(`.treemapSection`).data(N).enter().append(`g`).attr(`class`,`treemapSection`).attr(`transform`,e=>`translate(${e.x0},${e.y0})`);P.append(`rect`).attr(`width`,e=>e.x1-e.x0).attr(`height`,$).attr(`class`,`treemapSectionHeader`).attr(`fill`,`none`).attr(`fill-opacity`,.6).attr(`stroke-width`,.6).attr(`style`,e=>e.depth===0?`display: none;`:``),P.append(`clipPath`).attr(`id`,(e,t)=>`clip-section-${i}-${t}`).append(`rect`).attr(`width`,e=>Math.max(0,e.x1-e.x0-12)).attr(`height`,$),P.append(`rect`).attr(`width`,e=>e.x1-e.x0).attr(`height`,e=>e.y1-e.y0).attr(`class`,(e,t)=>`treemapSection section${t}`).attr(`fill`,e=>D(e.data.name)).attr(`fill-opacity`,.6).attr(`stroke`,e=>O(e.data.name)).attr(`stroke-width`,2).attr(`stroke-opacity`,.4).attr(`style`,e=>{if(e.depth===0)return`display: none;`;let t=x({cssCompiledStyles:e.data.cssCompiledStyles});return t.nodeStyles+`;`+t.borderStyles.join(`;`)}),P.append(`text`).attr(`class`,`treemapSectionLabel`).attr(`x`,6).attr(`y`,$/2).attr(`dominant-baseline`,`middle`).text(e=>e.depth===0?``:e.data.name).attr(`font-weight`,`bold`).attr(`clip-path`,(e,t)=>`url(#clip-section-${i}-${t})`).attr(`style`,e=>e.depth===0?`display: none;`:`dominant-baseline: middle; font-size: 12px; fill:`+k(e.data.name)+`; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`)).each(function(e){if(e.depth===0)return;let t=n(this),r=e.data.name;t.text(r);let i=e.x1-e.x0,a;a=u.showValues!==!1&&e.value?i-10-30-10-6:i-6-6;let o=Math.max(15,a),s=t.node();if(s.getComputedTextLength()>o){let e=r;for(;e.length>0;){if(e=r.substring(0,e.length-1),e.length===0){t.text(`...`),s.getComputedTextLength()>o&&t.text(``);break}if(t.text(e+`...`),s.getComputedTextLength()<=o)break}}}),u.showValues!==!1&&P.append(`text`).attr(`class`,`treemapSectionValue`).attr(`x`,e=>e.x1-e.x0-10).attr(`y`,$/2).attr(`text-anchor`,`end`).attr(`dominant-baseline`,`middle`).text(e=>e.value?E(e.value):``).attr(`font-style`,`italic`).attr(`style`,e=>e.depth===0?`display: none;`:`text-anchor: end; dominant-baseline: middle; font-size: 10px; fill:`+k(e.data.name)+`; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`));let F=M.leaves(),I=F.length>20,L=I?16:38,z=I?14:28,B=I?4:8,V=I?4:6,H=I?2:4,U=I?8:10,W=I?1:2,G=A.selectAll(`.treemapLeafGroup`).data(F).enter().append(`g`).attr(`class`,(e,t)=>`treemapNode treemapLeafGroup leaf${t}${e.data.classSelector?` ${e.data.classSelector}`:``}x`).attr(`transform`,e=>`translate(${e.x0},${e.y0})`);G.append(`rect`).attr(`width`,e=>e.x1-e.x0).attr(`height`,e=>e.y1-e.y0).attr(`class`,`treemapLeaf`).attr(`fill`,e=>e.parent?D(e.parent.data.name):D(e.data.name)).attr(`style`,e=>x({cssCompiledStyles:e.data.cssCompiledStyles}).nodeStyles).attr(`fill-opacity`,.3).attr(`stroke`,e=>e.parent?D(e.parent.data.name):D(e.data.name)).attr(`stroke-width`,3),G.append(`clipPath`).attr(`id`,(e,t)=>`clip-${i}-${t}`).append(`rect`).attr(`width`,e=>Math.max(0,e.x1-e.x0-4)).attr(`height`,e=>Math.max(0,e.y1-e.y0-4)),G.append(`text`).attr(`class`,`treemapLabel`).attr(`x`,e=>(e.x1-e.x0)/2).attr(`y`,e=>(e.y1-e.y0)/2).attr(`style`,e=>`text-anchor: middle; dominant-baseline: middle; font-size: ${L}px;fill:`+k(e.data.name)+`;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`)).attr(`clip-path`,(e,t)=>`url(#clip-${i}-${t})`).text(e=>e.data.name).each(function(e){let t=n(this),r=e.x1-e.x0,i=e.y1-e.y0,a=t.node(),o=r-2*H,s=i-2*H;if(oo&&c>B;)c--,t.style(`font-size`,`${c}px`);let u=Math.max(V,Math.min(z,Math.round(c*l))),d=c+W+u;for(;d>s&&c>B&&(c--,u=Math.max(V,Math.min(z,Math.round(c*l))),!(uo||c(e.x1-e.x0)/2).attr(`y`,function(e){return(e.y1-e.y0)/2}).attr(`style`,e=>`text-anchor: middle; dominant-baseline: hanging; font-size: ${z}px;fill:`+k(e.data.name)+`;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`)).attr(`clip-path`,(e,t)=>`url(#clip-${i}-${t})`).text(e=>e.value?E(e.value):``).each(function(e){let t=n(this),r=this.parentNode;if(!r){t.style(`display`,`none`);return}let i=n(r).select(`.treemapLabel`);if(i.empty()||i.style(`display`)===`none`){t.style(`display`,`none`);return}let a=parseFloat(i.style(`font-size`)),o=Math.max(V,Math.min(z,Math.round(a*.6)));t.style(`font-size`,`${o}px`);let s=(e.y1-e.y0)/2+a/2+W;t.attr(`y`,s);let c=e.x1-e.x0,l=e.y1-e.y0-4,u=c-2*H;t.node().getComputedTextLength()>u||s+o>l||o{let t=g(r(),c().themeVariables),n=g(ue,e),i=n.titleColor??t.titleColor,a=n.labelColor??t.textColor,o=n.valueColor??t.textColor;return` .treemapNode.section { stroke: ${n.sectionStrokeColor}; stroke-width: ${n.sectionStrokeWidth}; diff --git a/.vercel/output/static/assets/diagram-NH7WQ7WH-DwPDSx0m.js b/.vercel/output/static/assets/diagram-NH7WQ7WH-Btsva5Mx.js similarity index 91% rename from .vercel/output/static/assets/diagram-NH7WQ7WH-DwPDSx0m.js rename to .vercel/output/static/assets/diagram-NH7WQ7WH-Btsva5Mx.js index 3231656..0d4adff 100644 --- a/.vercel/output/static/assets/diagram-NH7WQ7WH-DwPDSx0m.js +++ b/.vercel/output/static/assets/diagram-NH7WQ7WH-Btsva5Mx.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{H as n,K as r,U as i,a,b as o,c as s,f as c,v as l,w as u,y as d}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{i as f}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as p}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{t as m}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as h}from"./mermaid-parser.core-AdnthA1k.js";var g=c.packet,_=class{constructor(){this.packet=[],this.setAccTitle=i,this.getAccTitle=d,this.setDiagramTitle=r,this.getDiagramTitle=u,this.getAccDescription=l,this.setAccDescription=n}static{e(this,`PacketDB`)}getConfig(){let e=f({...g,...o().packet});return e.showBits&&(e.paddingY+=10),e}getPacket(){return this.packet}pushWord(e){e.length>0&&this.packet.push(e)}clear(){a(),this.packet=[]}},v=1e4,y=e((e,n)=>{m(e,n);let r=-1,i=[],a=1,{bitsPerRow:o}=n.getConfig();for(let{start:s,end:c,bits:l,label:u}of e.blocks){if(s!==void 0&&c!==void 0&&c{if(e.start===void 0)throw Error(`start should have been set during first phase`);if(e.end===void 0)throw Error(`end should have been set during first phase`);if(e.start>e.end)throw Error(`Block start ${e.start} is greater than block end ${e.end}.`);if(e.end+1<=t*n)return[e,void 0];let r=t*n-1,i=t*n;return[{start:e.start,end:r,label:e.label,bits:r-e.start},{start:i,end:e.end,label:e.label,bits:e.end-i}]},`getNextFittingBlock`),x={parser:{yy:void 0},parse:e(async e=>{let n=await h(`packet`,e),r=x.parser?.yy;if(!(r instanceof _))throw Error(`parser.parser?.yy was not a PacketDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);t.debug(n),y(n,r)},`parse`)},S=e((e,t,n,r)=>{let i=r.db,a=i.getConfig(),{rowHeight:o,paddingY:c,bitWidth:l,bitsPerRow:u}=a,d=i.getPacket(),f=i.getDiagramTitle(),m=o+c,h=m*(d.length+1)-(f?0:o),g=l*u+2,_=p(t);_.attr(`viewBox`,`0 0 ${g} ${h}`),s(_,h,g,a.useMaxWidth);for(let[e,t]of d.entries())C(_,t,e,a);_.append(`text`).text(f).attr(`x`,g/2).attr(`y`,h-m/2).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`).attr(`class`,`packetTitle`)},`draw`),C=e((e,t,n,{rowHeight:r,paddingX:i,paddingY:a,bitWidth:o,bitsPerRow:s,showBits:c})=>{let l=e.append(`g`),u=n*(r+a)+a;for(let e of t){let t=e.start%s*o+1,n=(e.end-e.start+1)*o-i;if(l.append(`rect`).attr(`x`,t).attr(`y`,u).attr(`width`,n).attr(`height`,r).attr(`class`,`packetBlock`),l.append(`text`).attr(`x`,t+n/2).attr(`y`,u+r/2).attr(`class`,`packetLabel`).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`).text(e.label),!c)continue;let a=e.end===e.start,d=u-2;l.append(`text`).attr(`x`,t+(a?n/2:0)).attr(`y`,d).attr(`class`,`packetByte start`).attr(`dominant-baseline`,`auto`).attr(`text-anchor`,a?`middle`:`start`).text(e.start),a||l.append(`text`).attr(`x`,t+n).attr(`y`,d).attr(`class`,`packetByte end`).attr(`dominant-baseline`,`auto`).attr(`text-anchor`,`end`).text(e.end)}},`drawWord`),w={draw:S},T={byteFontSize:`10px`,startByteColor:`black`,endByteColor:`black`,labelColor:`black`,labelFontSize:`12px`,titleColor:`black`,titleFontSize:`14px`,blockStrokeColor:`black`,blockStrokeWidth:`1`,blockFillColor:`#efefef`},E={parser:x,get db(){return new _},renderer:w,styles:e(({packet:e}={})=>{let t=f(T,e);return` +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,b as o,c as s,f as c,v as l,w as u,y as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as f}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as p}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as m}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as h}from"./mermaid-parser.core-Z7xZAZRH.js";var g=c.packet,_=class{constructor(){this.packet=[],this.setAccTitle=i,this.getAccTitle=d,this.setDiagramTitle=r,this.getDiagramTitle=u,this.getAccDescription=l,this.setAccDescription=n}static{e(this,`PacketDB`)}getConfig(){let e=f({...g,...o().packet});return e.showBits&&(e.paddingY+=10),e}getPacket(){return this.packet}pushWord(e){e.length>0&&this.packet.push(e)}clear(){a(),this.packet=[]}},v=1e4,y=e((e,n)=>{m(e,n);let r=-1,i=[],a=1,{bitsPerRow:o}=n.getConfig();for(let{start:s,end:c,bits:l,label:u}of e.blocks){if(s!==void 0&&c!==void 0&&c{if(e.start===void 0)throw Error(`start should have been set during first phase`);if(e.end===void 0)throw Error(`end should have been set during first phase`);if(e.start>e.end)throw Error(`Block start ${e.start} is greater than block end ${e.end}.`);if(e.end+1<=t*n)return[e,void 0];let r=t*n-1,i=t*n;return[{start:e.start,end:r,label:e.label,bits:r-e.start},{start:i,end:e.end,label:e.label,bits:e.end-i}]},`getNextFittingBlock`),x={parser:{yy:void 0},parse:e(async e=>{let n=await h(`packet`,e),r=x.parser?.yy;if(!(r instanceof _))throw Error(`parser.parser?.yy was not a PacketDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);t.debug(n),y(n,r)},`parse`)},S=e((e,t,n,r)=>{let i=r.db,a=i.getConfig(),{rowHeight:o,paddingY:c,bitWidth:l,bitsPerRow:u}=a,d=i.getPacket(),f=i.getDiagramTitle(),m=o+c,h=m*(d.length+1)-(f?0:o),g=l*u+2,_=p(t);_.attr(`viewBox`,`0 0 ${g} ${h}`),s(_,h,g,a.useMaxWidth);for(let[e,t]of d.entries())C(_,t,e,a);_.append(`text`).text(f).attr(`x`,g/2).attr(`y`,h-m/2).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`).attr(`class`,`packetTitle`)},`draw`),C=e((e,t,n,{rowHeight:r,paddingX:i,paddingY:a,bitWidth:o,bitsPerRow:s,showBits:c})=>{let l=e.append(`g`),u=n*(r+a)+a;for(let e of t){let t=e.start%s*o+1,n=(e.end-e.start+1)*o-i;if(l.append(`rect`).attr(`x`,t).attr(`y`,u).attr(`width`,n).attr(`height`,r).attr(`class`,`packetBlock`),l.append(`text`).attr(`x`,t+n/2).attr(`y`,u+r/2).attr(`class`,`packetLabel`).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`).text(e.label),!c)continue;let a=e.end===e.start,d=u-2;l.append(`text`).attr(`x`,t+(a?n/2:0)).attr(`y`,d).attr(`class`,`packetByte start`).attr(`dominant-baseline`,`auto`).attr(`text-anchor`,a?`middle`:`start`).text(e.start),a||l.append(`text`).attr(`x`,t+n).attr(`y`,d).attr(`class`,`packetByte end`).attr(`dominant-baseline`,`auto`).attr(`text-anchor`,`end`).text(e.end)}},`drawWord`),w={draw:S},T={byteFontSize:`10px`,startByteColor:`black`,endByteColor:`black`,labelColor:`black`,labelFontSize:`12px`,titleColor:`black`,titleFontSize:`14px`,blockStrokeColor:`black`,blockStrokeWidth:`1`,blockFillColor:`#efefef`},E={parser:x,get db(){return new _},renderer:w,styles:e(({packet:e}={})=>{let t=f(T,e);return` .packetByte { font-size: ${t.byteFontSize}; } diff --git a/.vercel/output/static/assets/diagram-OA4YK3LP-DVPjeDc1.js b/.vercel/output/static/assets/diagram-OA4YK3LP-B1b6NwZz.js similarity index 95% rename from .vercel/output/static/assets/diagram-OA4YK3LP-DVPjeDc1.js rename to .vercel/output/static/assets/diagram-OA4YK3LP-B1b6NwZz.js index 7743ea2..338e2b6 100644 --- a/.vercel/output/static/assets/diagram-OA4YK3LP-DVPjeDc1.js +++ b/.vercel/output/static/assets/diagram-OA4YK3LP-B1b6NwZz.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{H as n,K as r,U as i,a,b as o,c as s,f as c,v as l,w as u,y as d,z as f}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{i as p}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as m}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-AdnthA1k.js";import{r as _,t as v}from"./chunk-HOUHSVGY-4s2dJLwR.js";import{t as y}from"./chunk-2Q5K7J3B-C1jixKkw.js";var b=/[─━│┃└┗├┣]/,x=/[└┗├┣]/,S=/[─━]/,C=/^[\s│┃]+$/,w=/^\s*(title[\t ]|accTitle[\t ]*:|accDescr[\t ]*[:{])/,T=/^\s*%%/,E=` `;function D(e){return e.some(e=>b.test(e))}e(D,`isBoxDrawingFormat`);function O(e){for(let t of e){let e=x.exec(t);if(e?.index&&e.index>0)return e.index}return 4}e(O,`inferSegmentWidth`);function k(e,t){return e.replace(/\bline\s+(\d+)\b/gi,(e,n)=>{let r=parseInt(n,10),i=t.get(r);return i?`line ${i}`:e})}e(k,`remapErrorLines`);function A(e){let t=e.split(` +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,b as o,c as s,f as c,v as l,w as u,y as d,z as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-Z7xZAZRH.js";import{r as _,t as v}from"./chunk-HOUHSVGY-iJuv90UH.js";import{t as y}from"./chunk-2Q5K7J3B-C1jixKkw.js";var b=/[─━│┃└┗├┣]/,x=/[└┗├┣]/,S=/[─━]/,C=/^[\s│┃]+$/,w=/^\s*(title[\t ]|accTitle[\t ]*:|accDescr[\t ]*[:{])/,T=/^\s*%%/,E=` `;function D(e){return e.some(e=>b.test(e))}e(D,`isBoxDrawingFormat`);function O(e){for(let t of e){let e=x.exec(t);if(e?.index&&e.index>0)return e.index}return 4}e(O,`inferSegmentWidth`);function k(e,t){return e.replace(/\bline\s+(\d+)\b/gi,(e,n)=>{let r=parseInt(n,10),i=t.get(r);return i?`line ${i}`:e})}e(k,`remapErrorLines`);function A(e){let t=e.split(` `),n=new Map,r=-1;for(let[e,n]of t.entries())if(n.trim()===`treeView-beta`){r=e;break}if(r===-1)return{text:e,lineMap:n};let i=[];for(let e=r+1;e({cnt:1,stack:[{id:0,level:-1,name:`/`,nodeType:`directory`,children:[]}]})),M=e(()=>{j.reset(),a()},`clear`),N=e(()=>j.records.stack[0],`getRoot`),P=e(()=>j.records.cnt,`getCount`),F=c.treeView,I={clear:M,addNode:e((e,t,n,r,i,a)=>{for(;e<=j.records.stack[j.records.stack.length-1].level;)j.records.stack.pop();let o={id:j.records.cnt++,level:e,name:t,nodeType:n,icon:i,cssClass:r,description:a,children:[]};j.records.stack[j.records.stack.length-1].children.push(o),j.records.stack.push(o)},`addNode`),getRoot:N,getCount:P,getConfig:e(()=>p(F,o().treeView),`getConfig`),getAccTitle:d,getAccDescription:l,getDiagramTitle:u,setAccDescription:n,setAccTitle:i,setDiagramTitle:r},L=e(e=>{h(e,I);for(let t of e.nodes){let e=typeof t.indent==`number`?t.indent:0,n=t.name,r=n.endsWith(`/`);r&&(n=n.slice(0,-1));let i=r?`directory`:`file`,a=t.classAnnotation||void 0,s=t.iconAnnotation,c=s===void 0?void 0:s||`none`,l=t.descAnnotation||void 0,u=l?f(l,o()):void 0;I.addNode(e,n,i,a,c,u)}},`populate`),R={parse:e(async e=>{let{text:n,lineMap:r}=A(e);try{let e=await g(`treeView`,n);t.debug(e),L(e)}catch(e){throw r.size>0&&e instanceof Error&&(e.message=k(e.message,r)),e}},`parse`)},z={prefix:`mermaid-treeview`,height:24,width:24,icons:{folder:{body:``},file:{body:``}}};function B(e,t){let n=t?.filenameIcons?.[e];if(n)return n;let r=e.lastIndexOf(`.`);if(r>0){let n=e.substring(r).toLowerCase(),i=t?.extensionIcons;return i?.[n]??i?.[n.slice(1)]}}e(B,`detectIcon`);function V(e,t){return e.includes(`:`)?e:e in z.icons||!t?`${z.prefix}:${e}`:`${t}:${e}`}e(V,`qualifyIcon`);function H(e,t){if(e.icon!==`none`){if(e.icon)return V(e.icon,t.defaultIconPack);if(t.showIcons){if(e.nodeType===`file`){let n=B(e.name,t);if(n===`none`)return;if(n)return V(n,t.defaultIconPack)}return`${z.prefix}:${e.nodeType===`directory`?`folder`:`file`}`}}}e(H,`getNodeIcon`),_([{name:z.prefix,icons:z}]);var U=14,W=4,G=16,K=e((e,t)=>`tv-icon-${e}-${t.replace(/[^\w-]/g,`-`)}`,`iconSymbolId`),q=e(async(t,n,r,i)=>{let a=new Set,o=e(e=>{let t=H(e,r);t&&a.add(t),e.children.forEach(o)},`collect`);if(o(n),a.size===0)return;let s=await Promise.all([...a].map(async e=>({icon:e,svg:await v(e,{height:U,width:U})}))),c=t.append(`defs`);for(let{icon:e,svg:t}of s)c.append(`g`).attr(`id`,K(i,e)).html(t)},`injectIconDefs`),J=e((e,t,n,r,i,a)=>{let o=r.append(`g`),s=`treeView-node-label`;n.nodeType===`directory`&&(s+=` treeView-node-dir`),n.cssClass&&(s+=` ${n.cssClass}`);let c=U+W,l=H(n,i),u=l!==void 0;l&&o.append(`use`).attr(`xlink:href`,`#${K(a,l)}`).attr(`x`,e+i.paddingX).attr(`y`,t+i.paddingY).attr(`class`,`treeView-node-icon`);let d=o.append(`text`).text(n.name).attr(`dominant-baseline`,`middle`).attr(`class`,s),{height:f,width:p}=d.node().getBBox(),m=f+i.paddingY*2,h=e+i.paddingX+(u?c:0);d.attr(`x`,h),d.attr(`y`,t+m/2);let g=h+p;return n.BBox={x:e,y:t,width:p+i.paddingX*2+(u?c:0),height:m},n.cssClass?.split(/\s+/).includes(`highlight`)&&o.insert(`rect`,`:first-child`).attr(`x`,e).attr(`y`,t+1).attr(`width`,0).attr(`height`,m-2).attr(`rx`,3).attr(`class`,`treeView-highlight-bg`),{node:n,nodeGroup:o,labelRightEdge:g,centerY:t+m/2}},`positionLabel`),Y=e((e,t,n,r,i,a)=>e.append(`line`).attr(`x1`,t).attr(`y1`,n).attr(`x2`,r).attr(`y2`,i).attr(`stroke-width`,a).attr(`class`,`treeView-node-line`),`positionLine`),X=e((t,n,r,i)=>{let a=0,o=0,s=[],c=e((e,t,n,r)=>{let c=r*(n.rowIndent+n.paddingX),l=J(c,a,t,e,n,i);s.push(l);let{height:u,width:d}=t.BBox;Y(e,c-n.rowIndent,a+u/2,c,a+u/2,n.lineThickness),o=Math.max(o,c+d),a+=u},`drawNode`),l=e((e,n=0)=>{c(t,e,r,n),e.children.forEach(e=>{l(e,n+1)});let{x:i,y:a,height:o}=e.BBox;if(e.children.length){let{y:n,height:s}=e.children[e.children.length-1].BBox;Y(t,i+r.paddingX,a+o,i+r.paddingX,n+s/2+r.lineThickness/2,r.lineThickness)}},`processNode`);l(n);let u=s.filter(e=>e.node.description);if(u.length>0){let e=Math.max(...s.map(e=>e.labelRightEdge))+G;for(let t of u){let n=t.nodeGroup.append(`text`).text(t.node.description).attr(`dominant-baseline`,`middle`).attr(`class`,`treeView-node-description`).attr(`x`,e).attr(`y`,t.centerY).node().getBBox();o=Math.max(o,e+n.width+r.paddingX)}}for(let e of s)if(e.node.cssClass?.split(/\s+/).includes(`highlight`)){let t=e.nodeGroup.select(`.treeView-highlight-bg`);if(!t.empty()){let n=o-e.node.BBox.x+8;t.attr(`width`,n),o=Math.max(o,e.node.BBox.x+n+2)}}return{totalHeight:a,totalWidth:o}},`drawTree`),Z={draw:e(async(e,n,r,i)=>{t.debug(`Rendering treeView diagram `+e);let a=i.db,o=a.getRoot(),c=a.getConfig(),l=m(n);await q(l,o,c,n);let u=l.append(`g`);u.attr(`class`,`tree-view`);let{totalHeight:d,totalWidth:f}=X(u,o,c,n);l.attr(`viewBox`,`-${c.lineThickness/2} 0 ${f} ${d}`),s(l,d,f,c.useMaxWidth)},`draw`)},Q={labelFontSize:`16px`,labelColor:`black`,lineColor:`black`,iconColor:`#546e7a`,descriptionColor:`#6a9955`,highlightBg:`rgba(255, 193, 7, 0.15)`,highlightStroke:`#ffc107`},$={db:I,renderer:Z,parser:R,styles:e(({treeView:e})=>{let{labelFontSize:t,labelColor:n,lineColor:r,iconColor:i,descriptionColor:a,highlightBg:o,highlightStroke:s}=p(Q,e);return` diff --git a/.vercel/output/static/assets/diagram-WEI45ONY-DZoJ0aZU.js b/.vercel/output/static/assets/diagram-WEI45ONY-DzxhBgyP.js similarity index 94% rename from .vercel/output/static/assets/diagram-WEI45ONY-DZoJ0aZU.js rename to .vercel/output/static/assets/diagram-WEI45ONY-DzxhBgyP.js index 958755e..bf57f53 100644 --- a/.vercel/output/static/assets/diagram-WEI45ONY-DZoJ0aZU.js +++ b/.vercel/output/static/assets/diagram-WEI45ONY-DzxhBgyP.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,f as l,v as u,w as d,y as f}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{i as p}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as m}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-AdnthA1k.js";var _={showLegend:!0,ticks:5,max:null,min:0,graticule:`circle`},v={axes:[],curves:[],options:_},y=structuredClone(v),b=l.radar,x=e(()=>p({...b,...s().radar}),`getConfig`),S=e(()=>y.axes,`getAxes`),C=e(()=>y.curves,`getCurves`),w=e(()=>y.options,`getOptions`),T=e(e=>{y.axes=e.map(e=>({name:e.name,label:e.label??e.name}))},`setAxes`),E=e(e=>{y.curves=e.map(e=>({name:e.name,label:e.label??e.name,entries:D(e.entries)}))},`setCurves`),D=e(e=>{if(e[0].axis==null)return e.map(e=>e.value);let t=S();if(t.length===0)throw Error(`Axes must be populated before curves for reference entries`);return t.map(t=>{let n=e.find(e=>e.axis?.$refText===t.name);if(n===void 0)throw Error(`Missing entry for axis `+t.label);return n.value})},`computeCurveEntries`),O={getAxes:S,getCurves:C,getOptions:w,setAxes:T,setCurves:E,setOptions:e(e=>{let t=e.reduce((e,t)=>(e[t.name]=t,e),{});y.options={showLegend:t.showLegend?.value??_.showLegend,ticks:t.ticks?.value??_.ticks,max:t.max?.value??_.max,min:t.min?.value??_.min,graticule:t.graticule?.value??_.graticule}},`setOptions`),getConfig:x,clear:e(()=>{o(),y=structuredClone(v)},`clear`),setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:d,getAccDescription:u,setAccDescription:r},k=e(e=>{h(e,O);let{axes:t,curves:n,options:r}=e;O.setAxes(t),O.setCurves(n),O.setOptions(r)},`populate`),A={parse:e(async e=>{let n=await g(`radar`,e);t.debug(n),k(n)},`parse`)},j=e((e,t,n,r)=>{let i=r.db,a=i.getAxes(),o=i.getCurves(),s=i.getOptions(),c=i.getConfig(),l=i.getDiagramTitle(),u=M(m(t),c),d=s.max??Math.max(...o.map(e=>Math.max(...e.entries))),f=s.min,p=Math.min(c.width,c.height)/2;N(u,a,p,s.ticks,s.graticule),P(u,a,p,c),F(u,a,o,f,d,s.graticule,c),R(u,o,s.showLegend,c),u.append(`text`).attr(`class`,`radarTitle`).text(l).attr(`x`,0).attr(`y`,-c.height/2-c.marginTop)},`draw`),M=e((e,t)=>{let n=t.width+t.marginLeft+t.marginRight,r=t.height+t.marginTop+t.marginBottom,i={x:t.marginLeft+t.width/2,y:t.marginTop+t.height/2};return c(e,r,n,t.useMaxWidth??!0),e.attr(`viewBox`,`0 0 ${n} ${r}`).attr(`overflow`,`visible`),e.append(`g`).attr(`transform`,`translate(${i.x}, ${i.y})`)},`drawFrame`),N=e((e,t,n,r,i)=>{if(i===`circle`)for(let t=0;t{let n=2*t*Math.PI/i-Math.PI/2;return`${o*Math.cos(n)},${o*Math.sin(n)}`}).join(` `);e.append(`polygon`).attr(`points`,s).attr(`class`,`radarGraticule`)}}},`drawGraticule`),P=e((e,t,n,r)=>{let i=t.length;for(let a=0;a.01?`start`:c<-.01?`end`:`middle`,d=l>.01?`hanging`:l<-.01?`auto`:`central`;e.append(`text`).text(o).attr(`x`,n*r.axisLabelFactor*c+4*c).attr(`y`,n*r.axisLabelFactor*l+4*l).attr(`text-anchor`,u).attr(`dominant-baseline`,d).attr(`class`,`radarAxisLabel`)}},`drawAxes`);function F(e,t,n,r,i,a,o){let s=t.length,c=Math.min(o.width,o.height)/2;n.forEach((t,n)=>{if(t.entries.length!==s)return;let l=t.entries.map((e,t)=>{let n=2*Math.PI*t/s-Math.PI/2,a=I(e,r,i,c);return{x:a*Math.cos(n),y:a*Math.sin(n)}});a===`circle`?e.append(`path`).attr(`d`,L(l,o.curveTension)).attr(`class`,`radarCurve-${n}`):a===`polygon`&&e.append(`polygon`).attr(`points`,l.map(e=>`${e.x},${e.y}`).join(` `)).attr(`class`,`radarCurve-${n}`)})}e(F,`drawCurves`);function I(e,t,n,r){return r*(Math.min(Math.max(e,t),n)-t)/(n-t)}e(I,`relativeRadius`);function L(e,t){let n=e.length,r=`M${e[0].x},${e[0].y}`;for(let i=0;i{let r=e.append(`g`).attr(`transform`,`translate(${i}, ${a+n*20})`);r.append(`rect`).attr(`width`,12).attr(`height`,12).attr(`class`,`radarLegendBox-${n}`),r.append(`text`).attr(`x`,16).attr(`y`,0).attr(`class`,`radarLegendText`).text(t.label)})}e(R,`drawLegend`);var z={draw:j},B=e((e,t)=>{let n=``;for(let r=0;rp({...b,...s().radar}),`getConfig`),S=e(()=>y.axes,`getAxes`),C=e(()=>y.curves,`getCurves`),w=e(()=>y.options,`getOptions`),T=e(e=>{y.axes=e.map(e=>({name:e.name,label:e.label??e.name}))},`setAxes`),E=e(e=>{y.curves=e.map(e=>({name:e.name,label:e.label??e.name,entries:D(e.entries)}))},`setCurves`),D=e(e=>{if(e[0].axis==null)return e.map(e=>e.value);let t=S();if(t.length===0)throw Error(`Axes must be populated before curves for reference entries`);return t.map(t=>{let n=e.find(e=>e.axis?.$refText===t.name);if(n===void 0)throw Error(`Missing entry for axis `+t.label);return n.value})},`computeCurveEntries`),O={getAxes:S,getCurves:C,getOptions:w,setAxes:T,setCurves:E,setOptions:e(e=>{let t=e.reduce((e,t)=>(e[t.name]=t,e),{});y.options={showLegend:t.showLegend?.value??_.showLegend,ticks:t.ticks?.value??_.ticks,max:t.max?.value??_.max,min:t.min?.value??_.min,graticule:t.graticule?.value??_.graticule}},`setOptions`),getConfig:x,clear:e(()=>{o(),y=structuredClone(v)},`clear`),setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:d,getAccDescription:u,setAccDescription:r},k=e(e=>{h(e,O);let{axes:t,curves:n,options:r}=e;O.setAxes(t),O.setCurves(n),O.setOptions(r)},`populate`),A={parse:e(async e=>{let n=await g(`radar`,e);t.debug(n),k(n)},`parse`)},j=e((e,t,n,r)=>{let i=r.db,a=i.getAxes(),o=i.getCurves(),s=i.getOptions(),c=i.getConfig(),l=i.getDiagramTitle(),u=M(m(t),c),d=s.max??Math.max(...o.map(e=>Math.max(...e.entries))),f=s.min,p=Math.min(c.width,c.height)/2;N(u,a,p,s.ticks,s.graticule),P(u,a,p,c),F(u,a,o,f,d,s.graticule,c),R(u,o,s.showLegend,c),u.append(`text`).attr(`class`,`radarTitle`).text(l).attr(`x`,0).attr(`y`,-c.height/2-c.marginTop)},`draw`),M=e((e,t)=>{let n=t.width+t.marginLeft+t.marginRight,r=t.height+t.marginTop+t.marginBottom,i={x:t.marginLeft+t.width/2,y:t.marginTop+t.height/2};return c(e,r,n,t.useMaxWidth??!0),e.attr(`viewBox`,`0 0 ${n} ${r}`).attr(`overflow`,`visible`),e.append(`g`).attr(`transform`,`translate(${i.x}, ${i.y})`)},`drawFrame`),N=e((e,t,n,r,i)=>{if(i===`circle`)for(let t=0;t{let n=2*t*Math.PI/i-Math.PI/2;return`${o*Math.cos(n)},${o*Math.sin(n)}`}).join(` `);e.append(`polygon`).attr(`points`,s).attr(`class`,`radarGraticule`)}}},`drawGraticule`),P=e((e,t,n,r)=>{let i=t.length;for(let a=0;a.01?`start`:c<-.01?`end`:`middle`,d=l>.01?`hanging`:l<-.01?`auto`:`central`;e.append(`text`).text(o).attr(`x`,n*r.axisLabelFactor*c+4*c).attr(`y`,n*r.axisLabelFactor*l+4*l).attr(`text-anchor`,u).attr(`dominant-baseline`,d).attr(`class`,`radarAxisLabel`)}},`drawAxes`);function F(e,t,n,r,i,a,o){let s=t.length,c=Math.min(o.width,o.height)/2;n.forEach((t,n)=>{if(t.entries.length!==s)return;let l=t.entries.map((e,t)=>{let n=2*Math.PI*t/s-Math.PI/2,a=I(e,r,i,c);return{x:a*Math.cos(n),y:a*Math.sin(n)}});a===`circle`?e.append(`path`).attr(`d`,L(l,o.curveTension)).attr(`class`,`radarCurve-${n}`):a===`polygon`&&e.append(`polygon`).attr(`points`,l.map(e=>`${e.x},${e.y}`).join(` `)).attr(`class`,`radarCurve-${n}`)})}e(F,`drawCurves`);function I(e,t,n,r){return r*(Math.min(Math.max(e,t),n)-t)/(n-t)}e(I,`relativeRadius`);function L(e,t){let n=e.length,r=`M${e[0].x},${e[0].y}`;for(let i=0;i{let r=e.append(`g`).attr(`transform`,`translate(${i}, ${a+n*20})`);r.append(`rect`).attr(`width`,12).attr(`height`,12).attr(`class`,`radarLegendBox-${n}`),r.append(`text`).attr(`x`,16).attr(`y`,0).attr(`class`,`radarLegendText`).text(t.label)})}e(R,`drawLegend`);var z={draw:j},B=e((e,t)=>{let n=``;for(let r=0;r1?0:e<-1?l:Math.acos(e)}function p(e){return e>=1?u:e<=-1?-u:Math.asin(e)}var m=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BLANK_URL=e.relativeFirstCharacters=e.whitespaceEscapeCharsRegex=e.urlSchemeRegex=e.ctrlCharactersRegex=e.htmlCtrlEntityRegex=e.htmlEntitiesRegex=e.invalidProtocolRegex=void 0,e.invalidProtocolRegex=/^([^\w]*)(javascript|data|vbscript)/im,e.htmlEntitiesRegex=/&#(\w+)(^\w|;)?/g,e.htmlCtrlEntityRegex=/&(newline|tab);/gi,e.ctrlCharactersRegex=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,e.urlSchemeRegex=/^.+(:|:)/gim,e.whitespaceEscapeCharsRegex=/(\\|%5[cC])((%(6[eE]|72|74))|[nrt])/g,e.relativeFirstCharacters=[`.`,`/`],e.BLANK_URL=`about:blank`})),h=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.sanitizeUrl=o;var t=m();function n(e){return t.relativeFirstCharacters.indexOf(e[0])>-1}function r(e){return e.replace(t.ctrlCharactersRegex,``).replace(t.htmlEntitiesRegex,function(e,t){return String.fromCharCode(t)})}function i(e){return URL.canParse(e)}function a(e){try{return decodeURIComponent(e)}catch{return e}}function o(e){if(!e)return t.BLANK_URL;var o,s=a(e.trim());do s=r(s).replace(t.htmlCtrlEntityRegex,``).replace(t.ctrlCharactersRegex,``).replace(t.whitespaceEscapeCharsRegex,``).trim(),s=a(s),o=s.match(t.ctrlCharactersRegex)||s.match(t.htmlEntitiesRegex)||s.match(t.htmlCtrlEntityRegex)||s.match(t.whitespaceEscapeCharsRegex);while(o&&o.length>0);var c=s;if(!c)return t.BLANK_URL;if(n(c))return c;var l=c.trimStart(),u=l.match(t.urlSchemeRegex);if(!u)return c;var d=u[0].toLowerCase().trim();if(t.invalidProtocolRegex.test(d))return t.BLANK_URL;var f=l.replace(/\\/g,`/`);if(d===`mailto:`||d.includes(`://`))return f;if(d===`http:`||d===`https:`){if(!i(f))return t.BLANK_URL;var p=new URL(f);return p.protocol=p.protocol.toLowerCase(),p.hostname=p.hostname.toLowerCase(),p.toString()}return f}}));export{n as a,u as c,l as d,o as f,p as i,i as l,d as m,t as n,r as o,s as p,f as r,c as s,h as t,a as u}; \ No newline at end of file +import{t as e}from"./rolldown-runtime-aKtaBQYM.js";var t=Math.abs,n=Math.atan2,r=Math.cos,i=Math.max,a=Math.min,o=Math.sin,s=Math.sqrt,c=1e-12,l=Math.PI,u=l/2,d=2*l;function f(e){return e>1?0:e<-1?l:Math.acos(e)}function p(e){return e>=1?u:e<=-1?-u:Math.asin(e)}var m=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BLANK_URL=e.relativeFirstCharacters=e.whitespaceEscapeCharsRegex=e.urlSchemeRegex=e.ctrlCharactersRegex=e.htmlCtrlEntityRegex=e.htmlEntitiesRegex=e.invalidProtocolRegex=void 0,e.invalidProtocolRegex=/^([^\w]*)(javascript|data|vbscript)/im,e.htmlEntitiesRegex=/&#(\w+)(^\w|;)?/g,e.htmlCtrlEntityRegex=/&(newline|tab);/gi,e.ctrlCharactersRegex=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,e.urlSchemeRegex=/^.+(:|:)/gim,e.whitespaceEscapeCharsRegex=/(\\|%5[cC])((%(6[eE]|72|74))|[nrt])/g,e.relativeFirstCharacters=[`.`,`/`],e.BLANK_URL=`about:blank`})),h=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.sanitizeUrl=o;var t=m();function n(e){return t.relativeFirstCharacters.indexOf(e[0])>-1}function r(e){return e.replace(t.ctrlCharactersRegex,``).replace(t.htmlEntitiesRegex,function(e,t){return String.fromCharCode(t)})}function i(e){return URL.canParse(e)}function a(e){try{return decodeURIComponent(e)}catch{return e}}function o(e){if(!e)return t.BLANK_URL;var o,s=a(e.trim());do s=r(s).replace(t.htmlCtrlEntityRegex,``).replace(t.ctrlCharactersRegex,``).replace(t.whitespaceEscapeCharsRegex,``).trim(),s=a(s),o=s.match(t.ctrlCharactersRegex)||s.match(t.htmlEntitiesRegex)||s.match(t.htmlCtrlEntityRegex)||s.match(t.whitespaceEscapeCharsRegex);while(o&&o.length>0);var c=s;if(!c)return t.BLANK_URL;if(n(c))return c;var l=c.trimStart(),u=l.match(t.urlSchemeRegex);if(!u)return c;var d=u[0].toLowerCase().trim();if(t.invalidProtocolRegex.test(d))return t.BLANK_URL;var f=l.replace(/\\/g,`/`);if(d===`mailto:`||d.includes(`://`))return f;if(d===`http:`||d===`https:`){if(!i(f))return t.BLANK_URL;var p=new URL(f);return p.protocol=p.protocol.toLowerCase(),p.hostname=p.hostname.toLowerCase(),p.toString()}return f}}));export{n as a,u as c,l as d,o as f,p as i,i as l,d as m,t as n,r as o,s as p,f as r,c as s,h as t,a as u}; \ No newline at end of file diff --git a/.vercel/output/static/assets/ebnfDiagram-CCIWWBDH-Df0TcF3M.js b/.vercel/output/static/assets/ebnfDiagram-CCIWWBDH-DiJBARG_.js similarity index 84% rename from .vercel/output/static/assets/ebnfDiagram-CCIWWBDH-Df0TcF3M.js rename to .vercel/output/static/assets/ebnfDiagram-CCIWWBDH-DiJBARG_.js index 5b29c4c..bf5a450 100644 --- a/.vercel/output/static/assets/ebnfDiagram-CCIWWBDH-Df0TcF3M.js +++ b/.vercel/output/static/assets/ebnfDiagram-CCIWWBDH-DiJBARG_.js @@ -1 +1 @@ -import{n as e}from"./chunk-U6XO7XAA-CR0BSRFR.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-_wZywoZs.js";import"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-VAUOI2AC-CLN1Ga8_.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-DR1aBwdH.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-AdnthA1k.js";var c=e().RailroadEbnf.parser.LangiumParser,l=t(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformChoice`),u=t(e=>{let t=e.elements.map(p);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformSequence`),d=t(e=>{switch(e.$type){case`EbnfTerminal`:return{type:`terminal`,value:e.value};case`EbnfNonTerminal`:return{type:`nonterminal`,name:e.name};case`EbnfSpecial`:return{type:`special`,text:e.text};case`EbnfGroup`:return l(e.element);case`EbnfOptional`:return{type:`optional`,element:l(e.element)};case`EbnfRepetition`:return{type:`repetition`,element:l(e.element),min:0,max:1/0};default:throw Error(`Unsupported EBNF primary node: ${e.$type}`)}},`transformPrimary`),f=t((e,t)=>{switch(t.$type){case`EbnfOptionalPostfix`:return{type:`optional`,element:e};case`EbnfZeroOrMorePostfix`:return{type:`repetition`,element:e,min:0,max:1/0};case`EbnfOneOrMorePostfix`:return{type:`repetition`,element:e,min:1,max:1/0};case`EbnfExceptionPostfix`:return{type:`sequence`,elements:[e,{type:`terminal`,value:`-`},d(t.except)]};default:throw Error(`Unsupported EBNF postfix node: ${t.$type}`)}},`transformPostfix`),p=t(e=>e.postfixes.reduce((e,t)=>f(e,t),d(e.base)),`transformTerm`),m=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),h=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(m(e)))},`populateDb`),g={parser:{parse:t(e=>{a.clear(),n.debug(`[EBNF Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[EBNF Parser] Parsed rules:`,r.rules.length),h(r),n.debug(`[EBNF Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{g as diagram}; \ No newline at end of file +import{n as e}from"./chunk-U6XO7XAA-CR0BSRFR.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-Bju_yCKi.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-Z7xZAZRH.js";var c=e().RailroadEbnf.parser.LangiumParser,l=t(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformChoice`),u=t(e=>{let t=e.elements.map(p);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformSequence`),d=t(e=>{switch(e.$type){case`EbnfTerminal`:return{type:`terminal`,value:e.value};case`EbnfNonTerminal`:return{type:`nonterminal`,name:e.name};case`EbnfSpecial`:return{type:`special`,text:e.text};case`EbnfGroup`:return l(e.element);case`EbnfOptional`:return{type:`optional`,element:l(e.element)};case`EbnfRepetition`:return{type:`repetition`,element:l(e.element),min:0,max:1/0};default:throw Error(`Unsupported EBNF primary node: ${e.$type}`)}},`transformPrimary`),f=t((e,t)=>{switch(t.$type){case`EbnfOptionalPostfix`:return{type:`optional`,element:e};case`EbnfZeroOrMorePostfix`:return{type:`repetition`,element:e,min:0,max:1/0};case`EbnfOneOrMorePostfix`:return{type:`repetition`,element:e,min:1,max:1/0};case`EbnfExceptionPostfix`:return{type:`sequence`,elements:[e,{type:`terminal`,value:`-`},d(t.except)]};default:throw Error(`Unsupported EBNF postfix node: ${t.$type}`)}},`transformPostfix`),p=t(e=>e.postfixes.reduce((e,t)=>f(e,t),d(e.base)),`transformTerm`),m=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),h=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(m(e)))},`populateDb`),g={parser:{parse:t(e=>{a.clear(),n.debug(`[EBNF Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[EBNF Parser] Parsed rules:`,r.rules.length),h(r),n.debug(`[EBNF Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{g as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/erDiagram-Q63AITRT-CAHSPkSj.js b/.vercel/output/static/assets/erDiagram-Q63AITRT-BwmdWLsf.js similarity index 97% rename from .vercel/output/static/assets/erDiagram-Q63AITRT-CAHSPkSj.js rename to .vercel/output/static/assets/erDiagram-Q63AITRT-BwmdWLsf.js index a822b5f..9a5e629 100644 --- a/.vercel/output/static/assets/erDiagram-Q63AITRT-CAHSPkSj.js +++ b/.vercel/output/static/assets/erDiagram-Q63AITRT-BwmdWLsf.js @@ -1,4 +1,4 @@ -import{n as e,t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n,p as r}from"./src-_wZywoZs.js";import{H as i,K as a,U as o,a as s,it as c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as p}from"./channel-DA-EZjf8.js";import{c as m,g as h}from"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import{t as g}from"./chunk-XXDRQBXY-BuE3VzE_.js";import{t as _}from"./chunk-VR4S4FIN-BJzXasDJ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import"./chunk-ZGVPDNZ5-zo3h_nOA.js";import"./chunk-52WLFC77-BBAyrLn9.js";import{r as v,t as y}from"./chunk-FWX5IMBZ-CiLc9_ts.js";var b=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[6,8,10,22,24,26,28,33,34,35,36,37,40,43,44,48,50,51,52],r=[1,10],i=[1,11],a=[1,12],o=[1,13],s=[1,23],c=[1,24],l=[1,25],u=[1,26],d=[1,27],f=[1,19],p=[1,28],m=[1,29],h=[1,20],g=[1,18],_=[1,21],v=[1,22],y=[1,36],b=[1,37],x=[1,38],S=[1,39],C=[1,40],w=[6,8,10,13,15,17,20,21,22,24,26,28,33,34,35,36,37,40,43,44,48,50,51,52,66,67,68,69,70],T=[1,45],E=[1,46],D=[1,55],O=[40,48,50,51,52,71,72],k=[1,66],A=[1,64],j=[1,61],M=[1,65],N=[1,67],P=[6,8,10,13,17,22,24,26,28,33,34,35,36,37,40,41,42,43,44,48,49,50,51,52,66,67,68,69,70],F=[66,67,68,69,70],I=[1,85],L=[1,84],R=[1,82],z=[1,83],B=[6,10,42,47],V=[6,10,13,41,42,47,48,49],H=[1,93],U=[1,92],W=[1,91],G=[19,58],K=[1,102],q=[1,101],J=[19,58,61,63],Y={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,ER_DIAGRAM:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NEWLINE:10,entityName:11,relSpec:12,COLON:13,role:14,STYLE_SEPARATOR:15,idList:16,BLOCK_START:17,attributes:18,BLOCK_STOP:19,SQS:20,SQE:21,title:22,title_value:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,direction:29,classDefStatement:30,classStatement:31,styleStatement:32,direction_tb:33,direction_bt:34,direction_rl:35,direction_lr:36,CLASSDEF:37,stylesOpt:38,separator:39,UNICODE_TEXT:40,STYLE_TEXT:41,COMMA:42,CLASS:43,STYLE:44,style:45,styleComponent:46,SEMI:47,NUM:48,BRKT:49,ENTITY_NAME:50,DECIMAL_NUM:51,ENTITY_ONE:52,attribute:53,attributeType:54,attributeName:55,attributeKeyTypeList:56,attributeComment:57,ATTRIBUTE_WORD:58,"?":59,attributeKeyType:60,",":61,ATTRIBUTE_KEY:62,COMMENT:63,cardinality:64,relType:65,ZERO_OR_ONE:66,ZERO_OR_MORE:67,ONE_OR_MORE:68,ONLY_ONE:69,MD_PARENT:70,NON_IDENTIFYING:71,IDENTIFYING:72,WORD:73,$accept:0,$end:1},terminals_:{2:`error`,4:`ER_DIAGRAM`,6:`EOF`,8:`SPACE`,10:`NEWLINE`,13:`COLON`,15:`STYLE_SEPARATOR`,17:`BLOCK_START`,19:`BLOCK_STOP`,20:`SQS`,21:`SQE`,22:`title`,23:`title_value`,24:`acc_title`,25:`acc_title_value`,26:`acc_descr`,27:`acc_descr_value`,28:`acc_descr_multiline_value`,33:`direction_tb`,34:`direction_bt`,35:`direction_rl`,36:`direction_lr`,37:`CLASSDEF`,40:`UNICODE_TEXT`,41:`STYLE_TEXT`,42:`COMMA`,43:`CLASS`,44:`STYLE`,47:`SEMI`,48:`NUM`,49:`BRKT`,50:`ENTITY_NAME`,51:`DECIMAL_NUM`,52:`ENTITY_ONE`,58:`ATTRIBUTE_WORD`,59:`?`,61:`,`,62:`ATTRIBUTE_KEY`,63:`COMMENT`,66:`ZERO_OR_ONE`,67:`ZERO_OR_MORE`,68:`ONE_OR_MORE`,69:`ONLY_ONE`,70:`MD_PARENT`,71:`NON_IDENTIFYING`,72:`IDENTIFYING`,73:`WORD`},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[9,5],[9,9],[9,7],[9,7],[9,4],[9,6],[9,3],[9,5],[9,1],[9,3],[9,7],[9,9],[9,6],[9,8],[9,4],[9,6],[9,2],[9,2],[9,2],[9,1],[9,1],[9,1],[9,1],[9,1],[29,1],[29,1],[29,1],[29,1],[30,4],[16,1],[16,1],[16,3],[16,3],[31,3],[32,4],[38,1],[38,3],[45,1],[45,2],[39,1],[39,1],[39,1],[46,1],[46,1],[46,1],[46,1],[11,1],[11,1],[11,1],[11,1],[11,1],[18,1],[18,2],[53,2],[53,3],[53,3],[53,4],[54,1],[54,2],[55,1],[56,1],[56,3],[60,1],[57,1],[12,3],[64,1],[64,1],[64,1],[64,1],[64,1],[65,1],[65,1],[14,1],[14,1],[14,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:break;case 2:this.$=[];break;case 3:a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 5:this.$=a[s];break;case 6:case 7:this.$=[];break;case 8:r.addEntity(a[s-4]),r.addEntity(a[s-2]),r.addRelationship(a[s-4],a[s],a[s-2],a[s-3]);break;case 9:r.addEntity(a[s-8]),r.addEntity(a[s-4]),r.addRelationship(a[s-8],a[s],a[s-4],a[s-5]),r.setClass([a[s-8]],a[s-6]),r.setClass([a[s-4]],a[s-2]);break;case 10:r.addEntity(a[s-6]),r.addEntity(a[s-2]),r.addRelationship(a[s-6],a[s],a[s-2],a[s-3]),r.setClass([a[s-6]],a[s-4]);break;case 11:r.addEntity(a[s-6]),r.addEntity(a[s-4]),r.addRelationship(a[s-6],a[s],a[s-4],a[s-5]),r.setClass([a[s-4]],a[s-2]);break;case 12:r.addEntity(a[s-3]),r.addAttributes(a[s-3],a[s-1]);break;case 13:r.addEntity(a[s-5]),r.addAttributes(a[s-5],a[s-1]),r.setClass([a[s-5]],a[s-3]);break;case 14:r.addEntity(a[s-2]);break;case 15:r.addEntity(a[s-4]),r.setClass([a[s-4]],a[s-2]);break;case 16:r.addEntity(a[s]);break;case 17:r.addEntity(a[s-2]),r.setClass([a[s-2]],a[s]);break;case 18:r.addEntity(a[s-6],a[s-4]),r.addAttributes(a[s-6],a[s-1]);break;case 19:r.addEntity(a[s-8],a[s-6]),r.addAttributes(a[s-8],a[s-1]),r.setClass([a[s-8]],a[s-3]);break;case 20:r.addEntity(a[s-5],a[s-3]);break;case 21:r.addEntity(a[s-7],a[s-5]),r.setClass([a[s-7]],a[s-2]);break;case 22:r.addEntity(a[s-3],a[s-1]);break;case 23:r.addEntity(a[s-5],a[s-3]),r.setClass([a[s-5]],a[s]);break;case 24:case 25:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 26:case 27:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 32:r.setDirection(`TB`);break;case 33:r.setDirection(`BT`);break;case 34:r.setDirection(`RL`);break;case 35:r.setDirection(`LR`);break;case 36:this.$=a[s-3],r.addClass(a[s-2],a[s-1]);break;case 37:case 38:case 59:case 68:this.$=[a[s]];break;case 39:case 40:this.$=a[s-2].concat([a[s]]);break;case 41:this.$=a[s-2],r.setClass(a[s-1],a[s]);break;case 42:this.$=a[s-3],r.addCssStyles(a[s-2],a[s-1]);break;case 43:this.$=[a[s]];break;case 44:a[s-2].push(a[s]),this.$=a[s-2];break;case 46:this.$=a[s-1]+a[s];break;case 54:case 80:case 81:this.$=a[s].replace(/"/g,``);break;case 55:case 56:case 57:case 58:case 82:this.$=a[s];break;case 60:a[s].push(a[s-1]),this.$=a[s];break;case 61:this.$={type:a[s-1],name:a[s]};break;case 62:this.$={type:a[s-2],name:a[s-1],keys:a[s]};break;case 63:this.$={type:a[s-2],name:a[s-1],comment:a[s]};break;case 64:this.$={type:a[s-3],name:a[s-2],keys:a[s-1],comment:a[s]};break;case 65:case 67:case 70:this.$=a[s];break;case 66:this.$=a[s-1]+a[s];break;case 69:a[s-2].push(a[s]),this.$=a[s-2];break;case 71:this.$=a[s].replace(/"/g,``);break;case 72:this.$={cardA:a[s],relType:a[s-1],cardB:a[s-2]};break;case 73:this.$=r.Cardinality.ZERO_OR_ONE;break;case 74:this.$=r.Cardinality.ZERO_OR_MORE;break;case 75:this.$=r.Cardinality.ONE_OR_MORE;break;case 76:this.$=r.Cardinality.ONLY_ONE;break;case 77:this.$=r.Cardinality.MD_PARENT;break;case 78:this.$=r.Identification.NON_IDENTIFYING;break;case 79:this.$=r.Identification.IDENTIFYING;break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},t(n,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:9,22:r,24:i,26:a,28:o,29:14,30:15,31:16,32:17,33:s,34:c,35:l,36:u,37:d,40:f,43:p,44:m,48:h,50:g,51:_,52:v},t(n,[2,7],{1:[2,1]}),t(n,[2,3]),{9:30,11:9,22:r,24:i,26:a,28:o,29:14,30:15,31:16,32:17,33:s,34:c,35:l,36:u,37:d,40:f,43:p,44:m,48:h,50:g,51:_,52:v},t(n,[2,5]),t(n,[2,6]),t(n,[2,16],{12:31,64:35,15:[1,32],17:[1,33],20:[1,34],66:y,67:b,68:x,69:S,70:C}),{23:[1,41]},{25:[1,42]},{27:[1,43]},t(n,[2,27]),t(n,[2,28]),t(n,[2,29]),t(n,[2,30]),t(n,[2,31]),t(w,[2,54]),t(w,[2,55]),t(w,[2,56]),t(w,[2,57]),t(w,[2,58]),t(n,[2,32]),t(n,[2,33]),t(n,[2,34]),t(n,[2,35]),{16:44,40:T,41:E},{16:47,40:T,41:E},{16:48,40:T,41:E},t(n,[2,4]),{11:49,40:f,48:h,50:g,51:_,52:v},{16:50,40:T,41:E},{18:51,19:[1,52],53:53,54:54,58:D},{11:56,40:f,48:h,50:g,51:_,52:v},{65:57,71:[1,58],72:[1,59]},t(O,[2,73]),t(O,[2,74]),t(O,[2,75]),t(O,[2,76]),t(O,[2,77]),t(n,[2,24]),t(n,[2,25]),t(n,[2,26]),{13:k,38:60,41:A,42:j,45:62,46:63,48:M,49:N},t(P,[2,37]),t(P,[2,38]),{16:68,40:T,41:E,42:j},{13:k,38:69,41:A,42:j,45:62,46:63,48:M,49:N},{13:[1,70],15:[1,71]},t(n,[2,17],{64:35,12:72,17:[1,73],42:j,66:y,67:b,68:x,69:S,70:C}),{19:[1,74]},t(n,[2,14]),{18:75,19:[2,59],53:53,54:54,58:D},{55:76,58:[1,77]},{58:[2,65],59:[1,78]},{21:[1,79]},{64:80,66:y,67:b,68:x,69:S,70:C},t(F,[2,78]),t(F,[2,79]),{6:I,10:L,39:81,42:R,47:z},{40:[1,86],41:[1,87]},t(B,[2,43],{46:88,13:k,41:A,48:M,49:N}),t(V,[2,45]),t(V,[2,50]),t(V,[2,51]),t(V,[2,52]),t(V,[2,53]),t(n,[2,41],{42:j}),{6:I,10:L,39:89,42:R,47:z},{14:90,40:H,50:U,73:W},{16:94,40:T,41:E},{11:95,40:f,48:h,50:g,51:_,52:v},{18:96,19:[1,97],53:53,54:54,58:D},t(n,[2,12]),{19:[2,60]},t(G,[2,61],{56:98,57:99,60:100,62:K,63:q}),t([19,58,62,63],[2,67]),{58:[2,66]},t(n,[2,22],{15:[1,104],17:[1,103]}),t([40,48,50,51,52],[2,72]),t(n,[2,36]),{13:k,41:A,45:105,46:63,48:M,49:N},t(n,[2,47]),t(n,[2,48]),t(n,[2,49]),t(P,[2,39]),t(P,[2,40]),t(V,[2,46]),t(n,[2,42]),t(n,[2,8]),t(n,[2,80]),t(n,[2,81]),t(n,[2,82]),{13:[1,106],42:j},{13:[1,108],15:[1,107]},{19:[1,109]},t(n,[2,15]),t(G,[2,62],{57:110,61:[1,111],63:q}),t(G,[2,63]),t(J,[2,68]),t(G,[2,71]),t(J,[2,70]),{18:112,19:[1,113],53:53,54:54,58:D},{16:114,40:T,41:E},t(B,[2,44],{46:88,13:k,41:A,48:M,49:N}),{14:115,40:H,50:U,73:W},{16:116,40:T,41:E},{14:117,40:H,50:U,73:W},t(n,[2,13]),t(G,[2,64]),{60:118,62:K},{19:[1,119]},t(n,[2,20]),t(n,[2,23],{17:[1,120],42:j}),t(n,[2,11]),{13:[1,121],42:j},t(n,[2,10]),t(J,[2,69]),t(n,[2,18]),{18:122,19:[1,123],53:53,54:54,58:D},{14:124,40:H,50:U,73:W},{19:[1,125]},t(n,[2,21]),t(n,[2,9]),t(n,[2,19])],defaultActions:{75:[2,60],78:[2,66]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e,t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n,p as r}from"./src-UMNXGZaF.js";import{H as i,K as a,U as o,a as s,it as c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as p}from"./channel-C4fgBBJ4.js";import{c as m,g as h}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import{t as g}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as _}from"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import{r as v,t as y}from"./chunk-FWX5IMBZ-ComLEIwh.js";var b=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[6,8,10,22,24,26,28,33,34,35,36,37,40,43,44,48,50,51,52],r=[1,10],i=[1,11],a=[1,12],o=[1,13],s=[1,23],c=[1,24],l=[1,25],u=[1,26],d=[1,27],f=[1,19],p=[1,28],m=[1,29],h=[1,20],g=[1,18],_=[1,21],v=[1,22],y=[1,36],b=[1,37],x=[1,38],S=[1,39],C=[1,40],w=[6,8,10,13,15,17,20,21,22,24,26,28,33,34,35,36,37,40,43,44,48,50,51,52,66,67,68,69,70],T=[1,45],E=[1,46],D=[1,55],O=[40,48,50,51,52,71,72],k=[1,66],A=[1,64],j=[1,61],M=[1,65],N=[1,67],P=[6,8,10,13,17,22,24,26,28,33,34,35,36,37,40,41,42,43,44,48,49,50,51,52,66,67,68,69,70],F=[66,67,68,69,70],I=[1,85],L=[1,84],R=[1,82],z=[1,83],B=[6,10,42,47],V=[6,10,13,41,42,47,48,49],H=[1,93],U=[1,92],W=[1,91],G=[19,58],K=[1,102],q=[1,101],J=[19,58,61,63],Y={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,ER_DIAGRAM:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NEWLINE:10,entityName:11,relSpec:12,COLON:13,role:14,STYLE_SEPARATOR:15,idList:16,BLOCK_START:17,attributes:18,BLOCK_STOP:19,SQS:20,SQE:21,title:22,title_value:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,direction:29,classDefStatement:30,classStatement:31,styleStatement:32,direction_tb:33,direction_bt:34,direction_rl:35,direction_lr:36,CLASSDEF:37,stylesOpt:38,separator:39,UNICODE_TEXT:40,STYLE_TEXT:41,COMMA:42,CLASS:43,STYLE:44,style:45,styleComponent:46,SEMI:47,NUM:48,BRKT:49,ENTITY_NAME:50,DECIMAL_NUM:51,ENTITY_ONE:52,attribute:53,attributeType:54,attributeName:55,attributeKeyTypeList:56,attributeComment:57,ATTRIBUTE_WORD:58,"?":59,attributeKeyType:60,",":61,ATTRIBUTE_KEY:62,COMMENT:63,cardinality:64,relType:65,ZERO_OR_ONE:66,ZERO_OR_MORE:67,ONE_OR_MORE:68,ONLY_ONE:69,MD_PARENT:70,NON_IDENTIFYING:71,IDENTIFYING:72,WORD:73,$accept:0,$end:1},terminals_:{2:`error`,4:`ER_DIAGRAM`,6:`EOF`,8:`SPACE`,10:`NEWLINE`,13:`COLON`,15:`STYLE_SEPARATOR`,17:`BLOCK_START`,19:`BLOCK_STOP`,20:`SQS`,21:`SQE`,22:`title`,23:`title_value`,24:`acc_title`,25:`acc_title_value`,26:`acc_descr`,27:`acc_descr_value`,28:`acc_descr_multiline_value`,33:`direction_tb`,34:`direction_bt`,35:`direction_rl`,36:`direction_lr`,37:`CLASSDEF`,40:`UNICODE_TEXT`,41:`STYLE_TEXT`,42:`COMMA`,43:`CLASS`,44:`STYLE`,47:`SEMI`,48:`NUM`,49:`BRKT`,50:`ENTITY_NAME`,51:`DECIMAL_NUM`,52:`ENTITY_ONE`,58:`ATTRIBUTE_WORD`,59:`?`,61:`,`,62:`ATTRIBUTE_KEY`,63:`COMMENT`,66:`ZERO_OR_ONE`,67:`ZERO_OR_MORE`,68:`ONE_OR_MORE`,69:`ONLY_ONE`,70:`MD_PARENT`,71:`NON_IDENTIFYING`,72:`IDENTIFYING`,73:`WORD`},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[9,5],[9,9],[9,7],[9,7],[9,4],[9,6],[9,3],[9,5],[9,1],[9,3],[9,7],[9,9],[9,6],[9,8],[9,4],[9,6],[9,2],[9,2],[9,2],[9,1],[9,1],[9,1],[9,1],[9,1],[29,1],[29,1],[29,1],[29,1],[30,4],[16,1],[16,1],[16,3],[16,3],[31,3],[32,4],[38,1],[38,3],[45,1],[45,2],[39,1],[39,1],[39,1],[46,1],[46,1],[46,1],[46,1],[11,1],[11,1],[11,1],[11,1],[11,1],[18,1],[18,2],[53,2],[53,3],[53,3],[53,4],[54,1],[54,2],[55,1],[56,1],[56,3],[60,1],[57,1],[12,3],[64,1],[64,1],[64,1],[64,1],[64,1],[65,1],[65,1],[14,1],[14,1],[14,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:break;case 2:this.$=[];break;case 3:a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 5:this.$=a[s];break;case 6:case 7:this.$=[];break;case 8:r.addEntity(a[s-4]),r.addEntity(a[s-2]),r.addRelationship(a[s-4],a[s],a[s-2],a[s-3]);break;case 9:r.addEntity(a[s-8]),r.addEntity(a[s-4]),r.addRelationship(a[s-8],a[s],a[s-4],a[s-5]),r.setClass([a[s-8]],a[s-6]),r.setClass([a[s-4]],a[s-2]);break;case 10:r.addEntity(a[s-6]),r.addEntity(a[s-2]),r.addRelationship(a[s-6],a[s],a[s-2],a[s-3]),r.setClass([a[s-6]],a[s-4]);break;case 11:r.addEntity(a[s-6]),r.addEntity(a[s-4]),r.addRelationship(a[s-6],a[s],a[s-4],a[s-5]),r.setClass([a[s-4]],a[s-2]);break;case 12:r.addEntity(a[s-3]),r.addAttributes(a[s-3],a[s-1]);break;case 13:r.addEntity(a[s-5]),r.addAttributes(a[s-5],a[s-1]),r.setClass([a[s-5]],a[s-3]);break;case 14:r.addEntity(a[s-2]);break;case 15:r.addEntity(a[s-4]),r.setClass([a[s-4]],a[s-2]);break;case 16:r.addEntity(a[s]);break;case 17:r.addEntity(a[s-2]),r.setClass([a[s-2]],a[s]);break;case 18:r.addEntity(a[s-6],a[s-4]),r.addAttributes(a[s-6],a[s-1]);break;case 19:r.addEntity(a[s-8],a[s-6]),r.addAttributes(a[s-8],a[s-1]),r.setClass([a[s-8]],a[s-3]);break;case 20:r.addEntity(a[s-5],a[s-3]);break;case 21:r.addEntity(a[s-7],a[s-5]),r.setClass([a[s-7]],a[s-2]);break;case 22:r.addEntity(a[s-3],a[s-1]);break;case 23:r.addEntity(a[s-5],a[s-3]),r.setClass([a[s-5]],a[s]);break;case 24:case 25:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 26:case 27:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 32:r.setDirection(`TB`);break;case 33:r.setDirection(`BT`);break;case 34:r.setDirection(`RL`);break;case 35:r.setDirection(`LR`);break;case 36:this.$=a[s-3],r.addClass(a[s-2],a[s-1]);break;case 37:case 38:case 59:case 68:this.$=[a[s]];break;case 39:case 40:this.$=a[s-2].concat([a[s]]);break;case 41:this.$=a[s-2],r.setClass(a[s-1],a[s]);break;case 42:this.$=a[s-3],r.addCssStyles(a[s-2],a[s-1]);break;case 43:this.$=[a[s]];break;case 44:a[s-2].push(a[s]),this.$=a[s-2];break;case 46:this.$=a[s-1]+a[s];break;case 54:case 80:case 81:this.$=a[s].replace(/"/g,``);break;case 55:case 56:case 57:case 58:case 82:this.$=a[s];break;case 60:a[s].push(a[s-1]),this.$=a[s];break;case 61:this.$={type:a[s-1],name:a[s]};break;case 62:this.$={type:a[s-2],name:a[s-1],keys:a[s]};break;case 63:this.$={type:a[s-2],name:a[s-1],comment:a[s]};break;case 64:this.$={type:a[s-3],name:a[s-2],keys:a[s-1],comment:a[s]};break;case 65:case 67:case 70:this.$=a[s];break;case 66:this.$=a[s-1]+a[s];break;case 69:a[s-2].push(a[s]),this.$=a[s-2];break;case 71:this.$=a[s].replace(/"/g,``);break;case 72:this.$={cardA:a[s],relType:a[s-1],cardB:a[s-2]};break;case 73:this.$=r.Cardinality.ZERO_OR_ONE;break;case 74:this.$=r.Cardinality.ZERO_OR_MORE;break;case 75:this.$=r.Cardinality.ONE_OR_MORE;break;case 76:this.$=r.Cardinality.ONLY_ONE;break;case 77:this.$=r.Cardinality.MD_PARENT;break;case 78:this.$=r.Identification.NON_IDENTIFYING;break;case 79:this.$=r.Identification.IDENTIFYING;break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},t(n,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:9,22:r,24:i,26:a,28:o,29:14,30:15,31:16,32:17,33:s,34:c,35:l,36:u,37:d,40:f,43:p,44:m,48:h,50:g,51:_,52:v},t(n,[2,7],{1:[2,1]}),t(n,[2,3]),{9:30,11:9,22:r,24:i,26:a,28:o,29:14,30:15,31:16,32:17,33:s,34:c,35:l,36:u,37:d,40:f,43:p,44:m,48:h,50:g,51:_,52:v},t(n,[2,5]),t(n,[2,6]),t(n,[2,16],{12:31,64:35,15:[1,32],17:[1,33],20:[1,34],66:y,67:b,68:x,69:S,70:C}),{23:[1,41]},{25:[1,42]},{27:[1,43]},t(n,[2,27]),t(n,[2,28]),t(n,[2,29]),t(n,[2,30]),t(n,[2,31]),t(w,[2,54]),t(w,[2,55]),t(w,[2,56]),t(w,[2,57]),t(w,[2,58]),t(n,[2,32]),t(n,[2,33]),t(n,[2,34]),t(n,[2,35]),{16:44,40:T,41:E},{16:47,40:T,41:E},{16:48,40:T,41:E},t(n,[2,4]),{11:49,40:f,48:h,50:g,51:_,52:v},{16:50,40:T,41:E},{18:51,19:[1,52],53:53,54:54,58:D},{11:56,40:f,48:h,50:g,51:_,52:v},{65:57,71:[1,58],72:[1,59]},t(O,[2,73]),t(O,[2,74]),t(O,[2,75]),t(O,[2,76]),t(O,[2,77]),t(n,[2,24]),t(n,[2,25]),t(n,[2,26]),{13:k,38:60,41:A,42:j,45:62,46:63,48:M,49:N},t(P,[2,37]),t(P,[2,38]),{16:68,40:T,41:E,42:j},{13:k,38:69,41:A,42:j,45:62,46:63,48:M,49:N},{13:[1,70],15:[1,71]},t(n,[2,17],{64:35,12:72,17:[1,73],42:j,66:y,67:b,68:x,69:S,70:C}),{19:[1,74]},t(n,[2,14]),{18:75,19:[2,59],53:53,54:54,58:D},{55:76,58:[1,77]},{58:[2,65],59:[1,78]},{21:[1,79]},{64:80,66:y,67:b,68:x,69:S,70:C},t(F,[2,78]),t(F,[2,79]),{6:I,10:L,39:81,42:R,47:z},{40:[1,86],41:[1,87]},t(B,[2,43],{46:88,13:k,41:A,48:M,49:N}),t(V,[2,45]),t(V,[2,50]),t(V,[2,51]),t(V,[2,52]),t(V,[2,53]),t(n,[2,41],{42:j}),{6:I,10:L,39:89,42:R,47:z},{14:90,40:H,50:U,73:W},{16:94,40:T,41:E},{11:95,40:f,48:h,50:g,51:_,52:v},{18:96,19:[1,97],53:53,54:54,58:D},t(n,[2,12]),{19:[2,60]},t(G,[2,61],{56:98,57:99,60:100,62:K,63:q}),t([19,58,62,63],[2,67]),{58:[2,66]},t(n,[2,22],{15:[1,104],17:[1,103]}),t([40,48,50,51,52],[2,72]),t(n,[2,36]),{13:k,41:A,45:105,46:63,48:M,49:N},t(n,[2,47]),t(n,[2,48]),t(n,[2,49]),t(P,[2,39]),t(P,[2,40]),t(V,[2,46]),t(n,[2,42]),t(n,[2,8]),t(n,[2,80]),t(n,[2,81]),t(n,[2,82]),{13:[1,106],42:j},{13:[1,108],15:[1,107]},{19:[1,109]},t(n,[2,15]),t(G,[2,62],{57:110,61:[1,111],63:q}),t(G,[2,63]),t(J,[2,68]),t(G,[2,71]),t(J,[2,70]),{18:112,19:[1,113],53:53,54:54,58:D},{16:114,40:T,41:E},t(B,[2,44],{46:88,13:k,41:A,48:M,49:N}),{14:115,40:H,50:U,73:W},{16:116,40:T,41:E},{14:117,40:H,50:U,73:W},t(n,[2,13]),t(G,[2,64]),{60:118,62:K},{19:[1,119]},t(n,[2,20]),t(n,[2,23],{17:[1,120],42:j}),t(n,[2,11]),{13:[1,121],42:j},t(n,[2,10]),t(J,[2,69]),t(n,[2,18]),{18:122,19:[1,123],53:53,54:54,58:D},{14:124,40:H,50:U,73:W},{19:[1,125]},t(n,[2,21]),t(n,[2,9]),t(n,[2,19])],defaultActions:{75:[2,60],78:[2,66]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};Y.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/flowDiagram-23GEKE2U-mMOyit70.js b/.vercel/output/static/assets/flowDiagram-23GEKE2U-mMOyit70.js new file mode 100644 index 0000000..9be8115 --- /dev/null +++ b/.vercel/output/static/assets/flowDiagram-23GEKE2U-mMOyit70.js @@ -0,0 +1 @@ +import"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import"./chunk-ZIRB5QZD-C6fEPe3t.js";import{n as e}from"./chunk-PUDLZKDR-hlw4TonS.js";export{e as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/flowDiagram-23GEKE2U-t-mmaSW1.js b/.vercel/output/static/assets/flowDiagram-23GEKE2U-t-mmaSW1.js deleted file mode 100644 index 1585336..0000000 --- a/.vercel/output/static/assets/flowDiagram-23GEKE2U-t-mmaSW1.js +++ /dev/null @@ -1 +0,0 @@ -import"./src-_wZywoZs.js";import"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import"./chunk-32BRIVSS-BtH22FN8.js";import"./chunk-XXDRQBXY-BuE3VzE_.js";import"./chunk-VR4S4FIN-BJzXasDJ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import"./chunk-ZGVPDNZ5-zo3h_nOA.js";import"./chunk-52WLFC77-BBAyrLn9.js";import"./chunk-FWX5IMBZ-CiLc9_ts.js";import"./chunk-ZIRB5QZD-C6fEPe3t.js";import{n as e}from"./chunk-PUDLZKDR-C4aS5M-Y.js";export{e as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/ganttDiagram-NO4QXBWP-Ca9aFZDA.js b/.vercel/output/static/assets/ganttDiagram-NO4QXBWP-BFiNAWzu.js similarity index 99% rename from .vercel/output/static/assets/ganttDiagram-NO4QXBWP-Ca9aFZDA.js rename to .vercel/output/static/assets/ganttDiagram-NO4QXBWP-BFiNAWzu.js index 6ac266d..105834d 100644 --- a/.vercel/output/static/assets/ganttDiagram-NO4QXBWP-Ca9aFZDA.js +++ b/.vercel/output/static/assets/ganttDiagram-NO4QXBWP-BFiNAWzu.js @@ -1,4 +1,4 @@ -import{r as e,t}from"./rolldown-runtime-QTnfLwEv.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{a as r,c as i,d as a,f as o,g as s,i as c,m as l,p as u,s as d,u as f}from"./src-_wZywoZs.js";import{H as p,K as m,U as h,a as g,c as _,s as v,v as y,w as b,x,y as S}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{a as C,i as w,n as T,r as E,t as D}from"./linear-B7l8qgEw.js";import{t as O}from"./init-D6jRqBbL.js";import{t as k}from"./dist-D9sYb5Oa.js";import{g as ee}from"./chunk-ICXQ74PX-fa5hHXws.js";function A(e,t){let n;if(t===void 0)for(let t of e)t!=null&&(n=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n=i)&&(n=i)}return n}function te(e,t){let n;if(t===void 0)for(let t of e)t!=null&&(n>t||n===void 0&&t>=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}return n}function ne(e){return e}var j=1,re=2,ie=3,ae=4,oe=1e-6;function se(e){return`translate(`+e+`,0)`}function ce(e){return`translate(0,`+e+`)`}function le(e){return t=>+e(t)}function ue(e,t){return t=Math.max(0,e.bandwidth()-t*2)/2,e.round()&&(t=Math.round(t)),n=>+e(n)+t}function de(){return!this.__axis}function fe(e,t){var n=[],r=null,i=null,a=6,o=6,s=3,c=typeof window<`u`&&window.devicePixelRatio>1?0:.5,l=e===j||e===ae?-1:1,u=e===ae||e===re?`x`:`y`,d=e===j||e===ie?se:ce;function f(f){var p=r??(t.ticks?t.ticks.apply(t,n):t.domain()),m=i??(t.tickFormat?t.tickFormat.apply(t,n):ne),h=Math.max(a,0)+s,g=t.range(),_=+g[0]+c,v=+g[g.length-1]+c,y=(t.bandwidth?ue:le)(t.copy(),c),b=f.selection?f.selection():f,x=b.selectAll(`.domain`).data([null]),S=b.selectAll(`.tick`).data(p,t).order(),C=S.exit(),w=S.enter().append(`g`).attr(`class`,`tick`),T=S.select(`line`),E=S.select(`text`);x=x.merge(x.enter().insert(`path`,`.tick`).attr(`class`,`domain`).attr(`stroke`,`currentColor`)),S=S.merge(w),T=T.merge(w.append(`line`).attr(`stroke`,`currentColor`).attr(u+`2`,l*a)),E=E.merge(w.append(`text`).attr(`fill`,`currentColor`).attr(u,l*h).attr(`dy`,e===j?`0em`:e===ie?`0.71em`:`0.32em`)),f!==b&&(x=x.transition(f),S=S.transition(f),T=T.transition(f),E=E.transition(f),C=C.transition(f).attr(`opacity`,oe).attr(`transform`,function(e){return isFinite(e=y(e))?d(e+c):this.getAttribute(`transform`)}),w.attr(`opacity`,oe).attr(`transform`,function(e){var t=this.parentNode.__axis;return d((t&&isFinite(t=t(e))?t:y(e))+c)})),C.remove(),x.attr(`d`,e===ae||e===re?o?`M`+l*o+`,`+_+`H`+c+`V`+v+`H`+l*o:`M`+c+`,`+_+`V`+v:o?`M`+_+`,`+l*o+`V`+c+`H`+v+`V`+l*o:`M`+_+`,`+c+`H`+v),S.attr(`opacity`,1).attr(`transform`,function(e){return d(y(e)+c)}),T.attr(u+`2`,l*a),E.attr(u,l*h).text(m),b.filter(de).attr(`fill`,`none`).attr(`font-size`,10).attr(`font-family`,`sans-serif`).attr(`text-anchor`,e===re?`start`:e===ae?`end`:`middle`),b.each(function(){this.__axis=y})}return f.scale=function(e){return arguments.length?(t=e,f):t},f.ticks=function(){return n=Array.from(arguments),f},f.tickArguments=function(e){return arguments.length?(n=e==null?[]:Array.from(e),f):n.slice()},f.tickValues=function(e){return arguments.length?(r=e==null?null:Array.from(e),f):r&&r.slice()},f.tickFormat=function(e){return arguments.length?(i=e,f):i},f.tickSize=function(e){return arguments.length?(a=o=+e,f):a},f.tickSizeInner=function(e){return arguments.length?(a=+e,f):a},f.tickSizeOuter=function(e){return arguments.length?(o=+e,f):o},f.tickPadding=function(e){return arguments.length?(s=+e,f):s},f.offset=function(e){return arguments.length?(c=+e,f):c},f}function pe(e){return fe(j,e)}function me(e){return fe(ie,e)}var he=Math.PI/180,ge=180/Math.PI,_e=18,ve=.96422,ye=1,be=.82521,xe=4/29,Se=6/29,Ce=3*Se*Se,we=Se*Se*Se;function Te(e){if(e instanceof M)return new M(e.l,e.a,e.b,e.opacity);if(e instanceof N)return Ne(e);e instanceof i||(e=f(e));var t=Ae(e.r),n=Ae(e.g),r=Ae(e.b),a=De((.2225045*t+.7168786*n+.0606169*r)/ye),o,s;return t===n&&n===r?o=s=a:(o=De((.4360747*t+.3850649*n+.1430804*r)/ve),s=De((.0139322*t+.0971045*n+.7141733*r)/be)),new M(116*a-16,500*(o-a),200*(a-s),e.opacity)}function Ee(e,t,n,r){return arguments.length===1?Te(e):new M(e,t,n,r??1)}function M(e,t,n,r){this.l=+e,this.a=+t,this.b=+n,this.opacity=+r}a(M,Ee,o(d,{brighter(e){return new M(this.l+_e*(e??1),this.a,this.b,this.opacity)},darker(e){return new M(this.l-_e*(e??1),this.a,this.b,this.opacity)},rgb(){var e=(this.l+16)/116,t=isNaN(this.a)?e:e+this.a/500,n=isNaN(this.b)?e:e-this.b/200;return t=ve*Oe(t),e=ye*Oe(e),n=be*Oe(n),new i(ke(3.1338561*t-1.6168667*e-.4906146*n),ke(-.9787684*t+1.9161415*e+.033454*n),ke(.0719453*t-.2289914*e+1.4052427*n),this.opacity)}}));function De(e){return e>we?e**(1/3):e/Ce+xe}function Oe(e){return e>Se?e*e*e:Ce*(e-xe)}function ke(e){return 255*(e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055)}function Ae(e){return(e/=255)<=.04045?e/12.92:((e+.055)/1.055)**2.4}function je(e){if(e instanceof N)return new N(e.h,e.c,e.l,e.opacity);if(e instanceof M||(e=Te(e)),e.a===0&&e.b===0)return new N(NaN,0(e(t=new Date(+t)),t),i.ceil=n=>(e(n=new Date(n-1)),t(n,1),e(n),n),i.round=e=>{let t=i(e),n=i.ceil(e);return e-t(t(e=new Date(+e),n==null?1:Math.floor(n)),e),i.range=(n,r,a)=>{let o=[];if(n=i.ceil(n),a=a==null?1:Math.floor(a),!(n0))return o;let s;do o.push(s=new Date(+n)),t(n,a),e(n);while(sP(t=>{if(t>=t)for(;e(t),!n(t);)t.setTime(t-1)},(e,r)=>{if(e>=e)if(r<0)for(;++r<=0;)for(;t(e,-1),!n(e););else for(;--r>=0;)for(;t(e,1),!n(e););}),n&&(i.count=(t,r)=>(Le.setTime(+t),Re.setTime(+r),e(Le),e(Re),Math.floor(n(Le,Re))),i.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?i.filter(r?t=>r(t)%e===0:t=>i.count(0,t)%e===0):i)),i}var ze=P(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);ze.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?P(t=>{t.setTime(Math.floor(t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>(n-t)/e):ze),ze.range;var F=1e3,I=F*60,L=I*60,R=L*24,Be=R*7,Ve=R*30,He=R*365,z=P(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*F)},(e,t)=>(t-e)/F,e=>e.getUTCSeconds());z.range;var Ue=P(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*F)},(e,t)=>{e.setTime(+e+t*I)},(e,t)=>(t-e)/I,e=>e.getMinutes());Ue.range;var We=P(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*I)},(e,t)=>(t-e)/I,e=>e.getUTCMinutes());We.range;var Ge=P(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*F-e.getMinutes()*I)},(e,t)=>{e.setTime(+e+t*L)},(e,t)=>(t-e)/L,e=>e.getHours());Ge.range;var Ke=P(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*L)},(e,t)=>(t-e)/L,e=>e.getUTCHours());Ke.range;var B=P(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*I)/R,e=>e.getDate()-1);B.range;var qe=P(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/R,e=>e.getUTCDate()-1);qe.range;var Je=P(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/R,e=>Math.floor(e/R));Je.range;function V(e){return P(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t*7)},(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*I)/Be)}var Ye=V(0),Xe=V(1),Ze=V(2),Qe=V(3),H=V(4),$e=V(5),et=V(6);Ye.range,Xe.range,Ze.range,Qe.range,H.range,$e.range,et.range;function U(e){return P(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t*7)},(e,t)=>(t-e)/Be)}var tt=U(0),nt=U(1),rt=U(2),it=U(3),at=U(4),ot=U(5),st=U(6);tt.range,nt.range,rt.range,it.range,at.range,ot.range,st.range;var ct=P(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());ct.range;var lt=P(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());lt.range;var W=P(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());W.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:P(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*e)}),W.range;var G=P(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());G.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:P(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*e)}),G.range;function ut(e,t,n,r,i,a){let o=[[z,1,F],[z,5,5*F],[z,15,15*F],[z,30,30*F],[a,1,I],[a,5,5*I],[a,15,15*I],[a,30,30*I],[i,1,L],[i,3,3*L],[i,6,6*L],[i,12,12*L],[r,1,R],[r,2,2*R],[n,1,Be],[t,1,Ve],[t,3,3*Ve],[e,1,He]];function s(e,t,n){let r=te).right(o,i);if(a===o.length)return e.every(w(t/He,n/He,r));if(a===0)return ze.every(Math.max(w(t,n,r),1));let[s,c]=o[i/o[a-1][2]53)return null;`w`in r||(r.w=1),`Z`in r?(a=gt(_t(r.y,0,1)),o=a.getUTCDay(),a=o>4||o===0?nt.ceil(a):nt(a),a=qe.offset(a,(r.V-1)*7),r.y=a.getUTCFullYear(),r.m=a.getUTCMonth(),r.d=a.getUTCDate()+(r.w+6)%7):(a=ht(_t(r.y,0,1)),o=a.getDay(),a=o>4||o===0?Xe.ceil(a):Xe(a),a=B.offset(a,(r.V-1)*7),r.y=a.getFullYear(),r.m=a.getMonth(),r.d=a.getDate()+(r.w+6)%7)}else(`W`in r||`U`in r)&&(`w`in r||(r.w=`u`in r?r.u%7:+(`W`in r)),o=`Z`in r?gt(_t(r.y,0,1)).getUTCDay():ht(_t(r.y,0,1)).getDay(),r.m=0,r.d=`W`in r?(r.w+6)%7+r.W*7-(o+5)%7:r.w+r.U*7-(o+6)%7);return`Z`in r?(r.H+=r.Z/100|0,r.M+=r.Z%100,gt(r)):ht(r)}}function w(e,t,n,r){for(var i=0,a=t.length,o=n.length,s,c;i=o)return-1;if(s=t.charCodeAt(i++),s===37){if(s=t.charAt(i++),c=x[s in yt?t.charAt(i++):s],!c||(r=c(e,n,r))<0)return-1}else if(s!=n.charCodeAt(r++))return-1}return r}function T(e,t,n){var r=l.exec(t.slice(n));return r?(e.p=u.get(r[0].toLowerCase()),n+r[0].length):-1}function E(e,t,n){var r=p.exec(t.slice(n));return r?(e.w=m.get(r[0].toLowerCase()),n+r[0].length):-1}function D(e,t,n){var r=d.exec(t.slice(n));return r?(e.w=f.get(r[0].toLowerCase()),n+r[0].length):-1}function O(e,t,n){var r=_.exec(t.slice(n));return r?(e.m=v.get(r[0].toLowerCase()),n+r[0].length):-1}function k(e,t,n){var r=h.exec(t.slice(n));return r?(e.m=g.get(r[0].toLowerCase()),n+r[0].length):-1}function ee(e,n,r){return w(e,t,n,r)}function A(e,t,r){return w(e,n,t,r)}function te(e,t,n){return w(e,r,t,n)}function ne(e){return o[e.getDay()]}function j(e){return a[e.getDay()]}function re(e){return c[e.getMonth()]}function ie(e){return s[e.getMonth()]}function ae(e){return i[+(e.getHours()>=12)]}function oe(e){return 1+~~(e.getMonth()/3)}function se(e){return o[e.getUTCDay()]}function ce(e){return a[e.getUTCDay()]}function le(e){return c[e.getUTCMonth()]}function ue(e){return s[e.getUTCMonth()]}function de(e){return i[+(e.getUTCHours()>=12)]}function fe(e){return 1+~~(e.getUTCMonth()/3)}return{format:function(e){var t=S(e+=``,y);return t.toString=function(){return e},t},parse:function(e){var t=C(e+=``,!1);return t.toString=function(){return e},t},utcFormat:function(e){var t=S(e+=``,b);return t.toString=function(){return e},t},utcParse:function(e){var t=C(e+=``,!0);return t.toString=function(){return e},t}}}var yt={"-":``,_:` `,0:`0`},K=/^\s*\d+/,bt=/^%/,xt=/[\\^$*+?|[\]().{}]/g;function q(e,t,n){var r=e<0?`-`:``,i=(r?-e:e)+``,a=i.length;return r+(a[e.toLowerCase(),t]))}function Tt(e,t,n){var r=K.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function Et(e,t,n){var r=K.exec(t.slice(n,n+1));return r?(e.u=+r[0],n+r[0].length):-1}function Dt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.U=+r[0],n+r[0].length):-1}function Ot(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.V=+r[0],n+r[0].length):-1}function kt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.W=+r[0],n+r[0].length):-1}function At(e,t,n){var r=K.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function jt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Mt(e,t,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(e.Z=r[1]?0:-(r[2]+(r[3]||`00`)),n+r[0].length):-1}function Nt(e,t,n){var r=K.exec(t.slice(n,n+1));return r?(e.q=r[0]*3-3,n+r[0].length):-1}function Pt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function Ft(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function It(e,t,n){var r=K.exec(t.slice(n,n+3));return r?(e.m=0,e.d=+r[0],n+r[0].length):-1}function Lt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function Rt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function zt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function Bt(e,t,n){var r=K.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function Vt(e,t,n){var r=K.exec(t.slice(n,n+6));return r?(e.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function Ht(e,t,n){var r=bt.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function Ut(e,t,n){var r=K.exec(t.slice(n));return r?(e.Q=+r[0],n+r[0].length):-1}function Wt(e,t,n){var r=K.exec(t.slice(n));return r?(e.s=+r[0],n+r[0].length):-1}function Gt(e,t){return q(e.getDate(),t,2)}function Kt(e,t){return q(e.getHours(),t,2)}function qt(e,t){return q(e.getHours()%12||12,t,2)}function Jt(e,t){return q(1+B.count(W(e),e),t,3)}function Yt(e,t){return q(e.getMilliseconds(),t,3)}function Xt(e,t){return Yt(e,t)+`000`}function Zt(e,t){return q(e.getMonth()+1,t,2)}function Qt(e,t){return q(e.getMinutes(),t,2)}function $t(e,t){return q(e.getSeconds(),t,2)}function en(e){var t=e.getDay();return t===0?7:t}function tn(e,t){return q(Ye.count(W(e)-1,e),t,2)}function nn(e){var t=e.getDay();return t>=4||t===0?H(e):H.ceil(e)}function rn(e,t){return e=nn(e),q(H.count(W(e),e)+(W(e).getDay()===4),t,2)}function an(e){return e.getDay()}function on(e,t){return q(Xe.count(W(e)-1,e),t,2)}function sn(e,t){return q(e.getFullYear()%100,t,2)}function cn(e,t){return e=nn(e),q(e.getFullYear()%100,t,2)}function ln(e,t){return q(e.getFullYear()%1e4,t,4)}function un(e,t){var n=e.getDay();return e=n>=4||n===0?H(e):H.ceil(e),q(e.getFullYear()%1e4,t,4)}function dn(e){var t=e.getTimezoneOffset();return(t>0?`-`:(t*=-1,`+`))+q(t/60|0,`0`,2)+q(t%60,`0`,2)}function fn(e,t){return q(e.getUTCDate(),t,2)}function pn(e,t){return q(e.getUTCHours(),t,2)}function mn(e,t){return q(e.getUTCHours()%12||12,t,2)}function hn(e,t){return q(1+qe.count(G(e),e),t,3)}function gn(e,t){return q(e.getUTCMilliseconds(),t,3)}function _n(e,t){return gn(e,t)+`000`}function vn(e,t){return q(e.getUTCMonth()+1,t,2)}function yn(e,t){return q(e.getUTCMinutes(),t,2)}function bn(e,t){return q(e.getUTCSeconds(),t,2)}function xn(e){var t=e.getUTCDay();return t===0?7:t}function Sn(e,t){return q(tt.count(G(e)-1,e),t,2)}function Cn(e){var t=e.getUTCDay();return t>=4||t===0?at(e):at.ceil(e)}function wn(e,t){return e=Cn(e),q(at.count(G(e),e)+(G(e).getUTCDay()===4),t,2)}function Tn(e){return e.getUTCDay()}function En(e,t){return q(nt.count(G(e)-1,e),t,2)}function Dn(e,t){return q(e.getUTCFullYear()%100,t,2)}function On(e,t){return e=Cn(e),q(e.getUTCFullYear()%100,t,2)}function kn(e,t){return q(e.getUTCFullYear()%1e4,t,4)}function An(e,t){var n=e.getUTCDay();return e=n>=4||n===0?at(e):at.ceil(e),q(e.getUTCFullYear()%1e4,t,4)}function jn(){return`+0000`}function Mn(){return`%`}function Nn(e){return+e}function Pn(e){return Math.floor(e/1e3)}var Fn,In;Ln({dateTime:`%x, %X`,date:`%-m/%-d/%Y`,time:`%-I:%M:%S %p`,periods:[`AM`,`PM`],days:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],shortDays:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],months:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],shortMonths:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`]});function Ln(e){return Fn=vt(e),In=Fn.format,Fn.parse,Fn.utcFormat,Fn.utcParse,Fn}function Rn(e){return new Date(e)}function zn(e){return e instanceof Date?+e:+new Date(+e)}function Bn(e,t,n,r,i,a,o,s,c,l){var u=T(),d=u.invert,f=u.domain,p=l(`.%L`),m=l(`:%S`),h=l(`%I:%M`),g=l(`%I %p`),_=l(`%a %d`),v=l(`%b %d`),y=l(`%B`),b=l(`%Y`);function x(e){return(c(e){(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_isoWeek=r()})(e,(function(){return function(e,t,n){var r=function(e){return e.add(4-e.isoWeekday(),`day`)},i=t.prototype;i.isoWeekYear=function(){return r(this).year()},i.isoWeek=function(e){if(!this.$utils().u(e))return this.add(7*(e-this.isoWeek()),`day`);var t,i,a,o,s=r(this),c=(t=this.isoWeekYear(),i=this.$u,a=(i?n.utc:n)().year(t).startOf(`year`),o=4-a.isoWeekday(),a.isoWeekday()>4&&(o+=7),a.add(o,`day`));return s.diff(c,`week`)+1},i.isoWeekday=function(e){return this.$utils().u(e)?this.day()||7:this.day(this.day()%7?e:e-7)};var a=i.startOf;i.startOf=function(e,t){var n=this.$utils(),r=!!n.u(t)||t;return n.p(e)===`isoweek`?r?this.date(this.date()-(this.isoWeekday()-1)).startOf(`day`):this.date(this.date()-1-(this.isoWeekday()-1)+7).endOf(`day`):a.bind(this)(e,t)}}}))})),Un=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_customParseFormat=r()})(e,(function(){var e={LTS:`h:mm:ss A`,LT:`h:mm A`,L:`MM/DD/YYYY`,LL:`MMMM D, YYYY`,LLL:`MMMM D, YYYY h:mm A`,LLLL:`dddd, MMMM D, YYYY h:mm A`},t=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,n=/\d/,r=/\d\d/,i=/\d\d?/,a=/\d*[^-_:/,()\s\d]+/,o={},s=function(e){return(e=+e)+(e>68?1900:2e3)},c=function(e){return function(t){this[e]=+t}},l=[/[+-]\d\d:?(\d\d)?|Z/,function(e){(this.zone||={}).offset=function(e){if(!e||e===`Z`)return 0;var t=e.match(/([+-]|\d\d)/g),n=60*t[1]+(+t[2]||0);return n===0?0:t[0]===`+`?-n:n}(e)}],u=function(e){var t=o[e];return t&&(t.indexOf?t:t.s.concat(t.f))},d=function(e,t){var n,r=o.meridiem;if(r){for(var i=1;i<=24;i+=1)if(e.indexOf(r(i,0,t))>-1){n=i>12;break}}else n=e===(t?`pm`:`PM`);return n},f={A:[a,function(e){this.afternoon=d(e,!1)}],a:[a,function(e){this.afternoon=d(e,!0)}],Q:[n,function(e){this.month=3*(e-1)+1}],S:[n,function(e){this.milliseconds=100*e}],SS:[r,function(e){this.milliseconds=10*e}],SSS:[/\d{3}/,function(e){this.milliseconds=+e}],s:[i,c(`seconds`)],ss:[i,c(`seconds`)],m:[i,c(`minutes`)],mm:[i,c(`minutes`)],H:[i,c(`hours`)],h:[i,c(`hours`)],HH:[i,c(`hours`)],hh:[i,c(`hours`)],D:[i,c(`day`)],DD:[r,c(`day`)],Do:[a,function(e){var t=o.ordinal,n=e.match(/\d+/);if(this.day=n[0],t)for(var r=1;r<=31;r+=1)t(r).replace(/\[|\]/g,``)===e&&(this.day=r)}],w:[i,c(`week`)],ww:[r,c(`week`)],M:[i,c(`month`)],MM:[r,c(`month`)],MMM:[a,function(e){var t=u(`months`),n=(u(`monthsShort`)||t.map((function(e){return e.slice(0,3)}))).indexOf(e)+1;if(n<1)throw Error();this.month=n%12||n}],MMMM:[a,function(e){var t=u(`months`).indexOf(e)+1;if(t<1)throw Error();this.month=t%12||t}],Y:[/[+-]?\d+/,c(`year`)],YY:[r,function(e){this.year=s(e)}],YYYY:[/\d{4}/,c(`year`)],Z:l,ZZ:l};function p(n){for(var r=n,i=o&&o.formats,a=(n=r.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(t,n,r){var a=r&&r.toUpperCase();return n||i[r]||e[r]||i[a].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(e,t,n){return t||n.slice(1)}))}))).match(t),s=a.length,c=0;c-1)return new Date((t===`X`?1e3:1)*e);var i=p(t)(e),a=i.year,o=i.month,s=i.day,c=i.hours,l=i.minutes,u=i.seconds,d=i.milliseconds,f=i.zone,m=i.week,h=new Date,g=s||(a||o?1:h.getDate()),_=a||h.getFullYear(),v=0;a&&!o||(v=o>0?o-1:h.getMonth());var y,b=c||0,x=l||0,S=u||0,C=d||0;return f?new Date(Date.UTC(_,v,g,b,x,S,C+60*f.offset*1e3)):n?new Date(Date.UTC(_,v,g,b,x,S,C)):(y=new Date(_,v,g,b,x,S,C),m&&(y=r(y).week(m).toDate()),y)}catch{return new Date(``)}}(t,s,r,n),this.init(),d&&!0!==d&&(this.$L=this.locale(d).$L),u&&t!=this.format(s)&&(this.$d=new Date(``)),o={}}else if(s instanceof Array)for(var f=s.length,m=1;m<=f;m+=1){a[1]=s[m-1];var h=n.apply(this,a);if(h.isValid()){this.$d=h.$d,this.$L=h.$L,this.init();break}m===f&&(this.$d=new Date(``))}else i.call(this,e)}}}))})),Wn=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_advancedFormat=r()})(e,(function(){return function(e,t){var n=t.prototype,r=n.format;n.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return r.bind(this)(e);var i=this.$utils(),a=(e||`YYYY-MM-DDTHH:mm:ssZ`).replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,(function(e){switch(e){case`Q`:return Math.ceil((t.$M+1)/3);case`Do`:return n.ordinal(t.$D);case`gggg`:return t.weekYear();case`GGGG`:return t.isoWeekYear();case`wo`:return n.ordinal(t.week(),`W`);case`w`:case`ww`:return i.s(t.week(),e===`w`?1:2,`0`);case`W`:case`WW`:return i.s(t.isoWeek(),e===`W`?1:2,`0`);case`k`:case`kk`:return i.s(String(t.$H===0?24:t.$H),e===`k`?1:2,`0`);case`X`:return Math.floor(t.$d.getTime()/1e3);case`x`:return t.$d.getTime();case`z`:return`[`+t.offsetName()+`]`;case`zzz`:return`[`+t.offsetName(`long`)+`]`;default:return e}}));return r.bind(this)(a)}}}))})),Gn=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_duration=r()})(e,(function(){var e,t,n=1e3,r=6e4,i=36e5,a=864e5,o=31536e6,s=2628e6,c=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,l=/\[([^\]]+)]|YYYY|YY|Y|M{1,2}|D{1,2}|H{1,2}|m{1,2}|s{1,2}|SSS/g,u={years:o,months:s,days:a,hours:i,minutes:r,seconds:n,milliseconds:1,weeks:6048e5},d=function(e){return e instanceof v},f=function(e,t,n){return new v(e,n,t.$l)},p=function(e){return t.p(e)+`s`},m=function(e){return e<0},h=function(e){return m(e)?Math.ceil(e):Math.floor(e)},g=function(e){return Math.abs(e)},_=function(e,t){return e?m(e)?{negative:!0,format:``+g(e)+t}:{negative:!1,format:``+e+t}:{negative:!1,format:``}},v=function(){function m(e,t,n){var r=this;if(this.$d={},this.$l=n,e===void 0&&(this.$ms=0,this.parseFromMilliseconds()),t)return f(e*u[p(t)],this);if(typeof e==`number`)return this.$ms=e,this.parseFromMilliseconds(),this;if(typeof e==`object`)return Object.keys(e).forEach((function(t){r.$d[p(t)]=e[t]})),this.calMilliseconds(),this;if(typeof e==`string`){var i=e.match(c);if(i){var a=i.slice(2).map((function(e){return e==null?0:Number(e)}));return this.$d.years=a[0],this.$d.months=a[1],this.$d.weeks=a[2],this.$d.days=a[3],this.$d.hours=a[4],this.$d.minutes=a[5],this.$d.seconds=a[6],this.calMilliseconds(),this}}return this}var g=m.prototype;return g.calMilliseconds=function(){var e=this;this.$ms=Object.keys(this.$d).reduce((function(t,n){return t+(e.$d[n]||0)*u[n]}),0)},g.parseFromMilliseconds=function(){var e=this.$ms;this.$d.years=h(e/o),e%=o,this.$d.months=h(e/s),e%=s,this.$d.days=h(e/a),e%=a,this.$d.hours=h(e/i),e%=i,this.$d.minutes=h(e/r),e%=r,this.$d.seconds=h(e/n),e%=n,this.$d.milliseconds=e},g.toISOString=function(){var e=_(this.$d.years,`Y`),t=_(this.$d.months,`M`),n=+this.$d.days||0;this.$d.weeks&&(n+=7*this.$d.weeks);var r=_(n,`D`),i=_(this.$d.hours,`H`),a=_(this.$d.minutes,`M`),o=this.$d.seconds||0;this.$d.milliseconds&&(o+=this.$d.milliseconds/1e3,o=Math.round(1e3*o)/1e3);var s=_(o,`S`),c=e.negative||t.negative||r.negative||i.negative||a.negative||s.negative,l=i.format||a.format||s.format?`T`:``,u=(c?`-`:``)+`P`+e.format+t.format+r.format+l+i.format+a.format+s.format;return u===`P`||u===`-P`?`P0D`:u},g.toJSON=function(){return this.toISOString()},g.format=function(e){var n=e||`YYYY-MM-DDTHH:mm:ss`,r={Y:this.$d.years,YY:t.s(this.$d.years,2,`0`),YYYY:t.s(this.$d.years,4,`0`),M:this.$d.months,MM:t.s(this.$d.months,2,`0`),D:this.$d.days,DD:t.s(this.$d.days,2,`0`),H:this.$d.hours,HH:t.s(this.$d.hours,2,`0`),m:this.$d.minutes,mm:t.s(this.$d.minutes,2,`0`),s:this.$d.seconds,ss:t.s(this.$d.seconds,2,`0`),SSS:t.s(this.$d.milliseconds,3,`0`)};return n.replace(l,(function(e,t){return t||String(r[e])}))},g.as=function(e){return this.$ms/u[p(e)]},g.get=function(e){var t=this.$ms,n=p(e);return n===`milliseconds`?t%=1e3:t=n===`weeks`?h(t/u[n]):this.$d[n],t||0},g.add=function(e,t,n){var r;return r=t?e*u[p(t)]:d(e)?e.$ms:f(e,this).$ms,f(this.$ms+r*(n?-1:1),this)},g.subtract=function(e,t){return this.add(e,t,!0)},g.locale=function(e){var t=this.clone();return t.$l=e,t},g.clone=function(){return f(this.$ms,this)},g.humanize=function(t){return e().add(this.$ms,`ms`).locale(this.$l).fromNow(!t)},g.valueOf=function(){return this.asMilliseconds()},g.milliseconds=function(){return this.get(`milliseconds`)},g.asMilliseconds=function(){return this.as(`milliseconds`)},g.seconds=function(){return this.get(`seconds`)},g.asSeconds=function(){return this.as(`seconds`)},g.minutes=function(){return this.get(`minutes`)},g.asMinutes=function(){return this.as(`minutes`)},g.hours=function(){return this.get(`hours`)},g.asHours=function(){return this.as(`hours`)},g.days=function(){return this.get(`days`)},g.asDays=function(){return this.as(`days`)},g.weeks=function(){return this.get(`weeks`)},g.asWeeks=function(){return this.as(`weeks`)},g.months=function(){return this.get(`months`)},g.asMonths=function(){return this.as(`months`)},g.years=function(){return this.get(`years`)},g.asYears=function(){return this.as(`years`)},m}(),y=function(e,t,n){return e.add(t.years()*n,`y`).add(t.months()*n,`M`).add(t.days()*n,`d`).add(t.hours()*n,`h`).add(t.minutes()*n,`m`).add(t.seconds()*n,`s`).add(t.milliseconds()*n,`ms`)};return function(n,r,i){e=i,t=i().$utils(),i.duration=function(e,t){return f(e,{$l:i.locale()},t)},i.isDuration=d;var a=r.prototype.add,o=r.prototype.subtract;r.prototype.add=function(e,t){return d(e)?y(this,e,1):a.bind(this)(e,t)},r.prototype.subtract=function(e,t){return d(e)?y(this,e,-1):o.bind(this)(e,t)}}}))})),Kn=k(),J=e(s(),1),qn=e(Hn(),1),Jn=e(Un(),1),Yn=e(Wn(),1),Xn=e(Gn(),1),Zn=(function(){var e=n(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),t=[6,8,10,12,13,14,15,16,17,18,20,21,22,23,24,25,26,27,28,29,30,31,33,35,36,38,40],r=[1,26],i=[1,27],a=[1,28],o=[1,29],s=[1,30],c=[1,31],l=[1,32],u=[1,33],d=[1,34],f=[1,9],p=[1,10],m=[1,11],h=[1,12],g=[1,13],_=[1,14],v=[1,15],y=[1,16],b=[1,19],x=[1,20],S=[1,21],C=[1,22],w=[1,23],T=[1,25],E=[1,35],D={trace:n(function(){},`trace`),yy:{},symbols_:{error:2,start:3,gantt:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NL:10,weekday:11,weekday_monday:12,weekday_tuesday:13,weekday_wednesday:14,weekday_thursday:15,weekday_friday:16,weekday_saturday:17,weekday_sunday:18,weekend:19,weekend_friday:20,weekend_saturday:21,dateFormat:22,inclusiveEndDates:23,topAxis:24,axisFormat:25,tickInterval:26,excludes:27,includes:28,todayMarker:29,title:30,acc_title:31,acc_title_value:32,acc_descr:33,acc_descr_value:34,acc_descr_multiline_value:35,section:36,clickStatement:37,taskTxt:38,taskData:39,click:40,callbackname:41,callbackargs:42,href:43,clickStatementDebug:44,$accept:0,$end:1},terminals_:{2:`error`,4:`gantt`,6:`EOF`,8:`SPACE`,10:`NL`,12:`weekday_monday`,13:`weekday_tuesday`,14:`weekday_wednesday`,15:`weekday_thursday`,16:`weekday_friday`,17:`weekday_saturday`,18:`weekday_sunday`,20:`weekend_friday`,21:`weekend_saturday`,22:`dateFormat`,23:`inclusiveEndDates`,24:`topAxis`,25:`axisFormat`,26:`tickInterval`,27:`excludes`,28:`includes`,29:`todayMarker`,30:`title`,31:`acc_title`,32:`acc_title_value`,33:`acc_descr`,34:`acc_descr_value`,35:`acc_descr_multiline_value`,36:`section`,38:`taskTxt`,39:`taskData`,40:`click`,41:`callbackname`,42:`callbackargs`,43:`href`},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[19,1],[19,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,1],[9,2],[37,2],[37,3],[37,3],[37,4],[37,3],[37,4],[37,2],[44,2],[44,3],[44,3],[44,4],[44,3],[44,4],[44,2]],performAction:n(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 2:this.$=[];break;case 3:a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 5:this.$=a[s];break;case 6:case 7:this.$=[];break;case 8:r.setWeekday(`monday`);break;case 9:r.setWeekday(`tuesday`);break;case 10:r.setWeekday(`wednesday`);break;case 11:r.setWeekday(`thursday`);break;case 12:r.setWeekday(`friday`);break;case 13:r.setWeekday(`saturday`);break;case 14:r.setWeekday(`sunday`);break;case 15:r.setWeekend(`friday`);break;case 16:r.setWeekend(`saturday`);break;case 17:r.setDateFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 18:r.enableInclusiveEndDates(),this.$=a[s].substr(18);break;case 19:r.TopAxis(),this.$=a[s].substr(8);break;case 20:r.setAxisFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 21:r.setTickInterval(a[s].substr(13)),this.$=a[s].substr(13);break;case 22:r.setExcludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 23:r.setIncludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 24:r.setTodayMarker(a[s].substr(12)),this.$=a[s].substr(12);break;case 27:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 28:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 29:case 30:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 31:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 33:r.addTask(a[s-1],a[s]),this.$=`task`;break;case 34:this.$=a[s-1],r.setClickEvent(a[s-1],a[s],null);break;case 35:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 36:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],null),r.setLink(a[s-2],a[s]);break;case 37:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setLink(a[s-3],a[s]);break;case 38:this.$=a[s-2],r.setClickEvent(a[s-2],a[s],null),r.setLink(a[s-2],a[s-1]);break;case 39:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-1],a[s]),r.setLink(a[s-3],a[s-2]);break;case 40:this.$=a[s-1],r.setLink(a[s-1],a[s]);break;case 41:case 47:this.$=a[s-1]+` `+a[s];break;case 42:case 43:case 45:this.$=a[s-2]+` `+a[s-1]+` `+a[s];break;case 44:case 46:this.$=a[s-3]+` `+a[s-2]+` `+a[s-1]+` `+a[s];break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},e(t,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:17,12:r,13:i,14:a,15:o,16:s,17:c,18:l,19:18,20:u,21:d,22:f,23:p,24:m,25:h,26:g,27:_,28:v,29:y,30:b,31:x,33:S,35:C,36:w,37:24,38:T,40:E},e(t,[2,7],{1:[2,1]}),e(t,[2,3]),{9:36,11:17,12:r,13:i,14:a,15:o,16:s,17:c,18:l,19:18,20:u,21:d,22:f,23:p,24:m,25:h,26:g,27:_,28:v,29:y,30:b,31:x,33:S,35:C,36:w,37:24,38:T,40:E},e(t,[2,5]),e(t,[2,6]),e(t,[2,17]),e(t,[2,18]),e(t,[2,19]),e(t,[2,20]),e(t,[2,21]),e(t,[2,22]),e(t,[2,23]),e(t,[2,24]),e(t,[2,25]),e(t,[2,26]),e(t,[2,27]),{32:[1,37]},{34:[1,38]},e(t,[2,30]),e(t,[2,31]),e(t,[2,32]),{39:[1,39]},e(t,[2,8]),e(t,[2,9]),e(t,[2,10]),e(t,[2,11]),e(t,[2,12]),e(t,[2,13]),e(t,[2,14]),e(t,[2,15]),e(t,[2,16]),{41:[1,40],43:[1,41]},e(t,[2,4]),e(t,[2,28]),e(t,[2,29]),e(t,[2,33]),e(t,[2,34],{42:[1,42],43:[1,43]}),e(t,[2,40],{41:[1,44]}),e(t,[2,35],{43:[1,45]}),e(t,[2,36]),e(t,[2,38],{42:[1,46]}),e(t,[2,37]),e(t,[2,39])],defaultActions:{},parseError:n(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:n(function(e){var t=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(e,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}n(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=t.symbols_[e]||e),e}n(x,`lex`);for(var S,C,w,T,E,D={},O,k,ee,A;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var te=``;for(O in A=[],s[w])this.terminals_[O]&&O>f&&A.push(`'`+this.terminals_[O]+`'`);te=h.showPosition?`Parse error on line `+(l+1)+`: +import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{a as r,c as i,d as a,f as o,g as s,i as c,m as l,p as u,s as d,u as f}from"./src-UMNXGZaF.js";import{H as p,K as m,U as h,a as g,c as _,s as v,v as y,w as b,x,y as S}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{a as C,i as w,n as T,r as E,t as D}from"./linear-DhAcoVP9.js";import{t as O}from"./init-D6jRqBbL.js";import{t as k}from"./dist-qx0Iv9vM.js";import{g as ee}from"./chunk-ICXQ74PX-Czpgj8Uw.js";function A(e,t){let n;if(t===void 0)for(let t of e)t!=null&&(n=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n=i)&&(n=i)}return n}function te(e,t){let n;if(t===void 0)for(let t of e)t!=null&&(n>t||n===void 0&&t>=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}return n}function ne(e){return e}var j=1,re=2,ie=3,ae=4,oe=1e-6;function se(e){return`translate(`+e+`,0)`}function ce(e){return`translate(0,`+e+`)`}function le(e){return t=>+e(t)}function ue(e,t){return t=Math.max(0,e.bandwidth()-t*2)/2,e.round()&&(t=Math.round(t)),n=>+e(n)+t}function de(){return!this.__axis}function fe(e,t){var n=[],r=null,i=null,a=6,o=6,s=3,c=typeof window<`u`&&window.devicePixelRatio>1?0:.5,l=e===j||e===ae?-1:1,u=e===ae||e===re?`x`:`y`,d=e===j||e===ie?se:ce;function f(f){var p=r??(t.ticks?t.ticks.apply(t,n):t.domain()),m=i??(t.tickFormat?t.tickFormat.apply(t,n):ne),h=Math.max(a,0)+s,g=t.range(),_=+g[0]+c,v=+g[g.length-1]+c,y=(t.bandwidth?ue:le)(t.copy(),c),b=f.selection?f.selection():f,x=b.selectAll(`.domain`).data([null]),S=b.selectAll(`.tick`).data(p,t).order(),C=S.exit(),w=S.enter().append(`g`).attr(`class`,`tick`),T=S.select(`line`),E=S.select(`text`);x=x.merge(x.enter().insert(`path`,`.tick`).attr(`class`,`domain`).attr(`stroke`,`currentColor`)),S=S.merge(w),T=T.merge(w.append(`line`).attr(`stroke`,`currentColor`).attr(u+`2`,l*a)),E=E.merge(w.append(`text`).attr(`fill`,`currentColor`).attr(u,l*h).attr(`dy`,e===j?`0em`:e===ie?`0.71em`:`0.32em`)),f!==b&&(x=x.transition(f),S=S.transition(f),T=T.transition(f),E=E.transition(f),C=C.transition(f).attr(`opacity`,oe).attr(`transform`,function(e){return isFinite(e=y(e))?d(e+c):this.getAttribute(`transform`)}),w.attr(`opacity`,oe).attr(`transform`,function(e){var t=this.parentNode.__axis;return d((t&&isFinite(t=t(e))?t:y(e))+c)})),C.remove(),x.attr(`d`,e===ae||e===re?o?`M`+l*o+`,`+_+`H`+c+`V`+v+`H`+l*o:`M`+c+`,`+_+`V`+v:o?`M`+_+`,`+l*o+`V`+c+`H`+v+`V`+l*o:`M`+_+`,`+c+`H`+v),S.attr(`opacity`,1).attr(`transform`,function(e){return d(y(e)+c)}),T.attr(u+`2`,l*a),E.attr(u,l*h).text(m),b.filter(de).attr(`fill`,`none`).attr(`font-size`,10).attr(`font-family`,`sans-serif`).attr(`text-anchor`,e===re?`start`:e===ae?`end`:`middle`),b.each(function(){this.__axis=y})}return f.scale=function(e){return arguments.length?(t=e,f):t},f.ticks=function(){return n=Array.from(arguments),f},f.tickArguments=function(e){return arguments.length?(n=e==null?[]:Array.from(e),f):n.slice()},f.tickValues=function(e){return arguments.length?(r=e==null?null:Array.from(e),f):r&&r.slice()},f.tickFormat=function(e){return arguments.length?(i=e,f):i},f.tickSize=function(e){return arguments.length?(a=o=+e,f):a},f.tickSizeInner=function(e){return arguments.length?(a=+e,f):a},f.tickSizeOuter=function(e){return arguments.length?(o=+e,f):o},f.tickPadding=function(e){return arguments.length?(s=+e,f):s},f.offset=function(e){return arguments.length?(c=+e,f):c},f}function pe(e){return fe(j,e)}function me(e){return fe(ie,e)}var he=Math.PI/180,ge=180/Math.PI,_e=18,ve=.96422,ye=1,be=.82521,xe=4/29,Se=6/29,Ce=3*Se*Se,we=Se*Se*Se;function Te(e){if(e instanceof M)return new M(e.l,e.a,e.b,e.opacity);if(e instanceof N)return Ne(e);e instanceof i||(e=f(e));var t=Ae(e.r),n=Ae(e.g),r=Ae(e.b),a=De((.2225045*t+.7168786*n+.0606169*r)/ye),o,s;return t===n&&n===r?o=s=a:(o=De((.4360747*t+.3850649*n+.1430804*r)/ve),s=De((.0139322*t+.0971045*n+.7141733*r)/be)),new M(116*a-16,500*(o-a),200*(a-s),e.opacity)}function Ee(e,t,n,r){return arguments.length===1?Te(e):new M(e,t,n,r??1)}function M(e,t,n,r){this.l=+e,this.a=+t,this.b=+n,this.opacity=+r}a(M,Ee,o(d,{brighter(e){return new M(this.l+_e*(e??1),this.a,this.b,this.opacity)},darker(e){return new M(this.l-_e*(e??1),this.a,this.b,this.opacity)},rgb(){var e=(this.l+16)/116,t=isNaN(this.a)?e:e+this.a/500,n=isNaN(this.b)?e:e-this.b/200;return t=ve*Oe(t),e=ye*Oe(e),n=be*Oe(n),new i(ke(3.1338561*t-1.6168667*e-.4906146*n),ke(-.9787684*t+1.9161415*e+.033454*n),ke(.0719453*t-.2289914*e+1.4052427*n),this.opacity)}}));function De(e){return e>we?e**(1/3):e/Ce+xe}function Oe(e){return e>Se?e*e*e:Ce*(e-xe)}function ke(e){return 255*(e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055)}function Ae(e){return(e/=255)<=.04045?e/12.92:((e+.055)/1.055)**2.4}function je(e){if(e instanceof N)return new N(e.h,e.c,e.l,e.opacity);if(e instanceof M||(e=Te(e)),e.a===0&&e.b===0)return new N(NaN,0(e(t=new Date(+t)),t),i.ceil=n=>(e(n=new Date(n-1)),t(n,1),e(n),n),i.round=e=>{let t=i(e),n=i.ceil(e);return e-t(t(e=new Date(+e),n==null?1:Math.floor(n)),e),i.range=(n,r,a)=>{let o=[];if(n=i.ceil(n),a=a==null?1:Math.floor(a),!(n0))return o;let s;do o.push(s=new Date(+n)),t(n,a),e(n);while(sP(t=>{if(t>=t)for(;e(t),!n(t);)t.setTime(t-1)},(e,r)=>{if(e>=e)if(r<0)for(;++r<=0;)for(;t(e,-1),!n(e););else for(;--r>=0;)for(;t(e,1),!n(e););}),n&&(i.count=(t,r)=>(Le.setTime(+t),Re.setTime(+r),e(Le),e(Re),Math.floor(n(Le,Re))),i.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?i.filter(r?t=>r(t)%e===0:t=>i.count(0,t)%e===0):i)),i}var ze=P(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);ze.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?P(t=>{t.setTime(Math.floor(t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>(n-t)/e):ze),ze.range;var F=1e3,I=F*60,L=I*60,R=L*24,Be=R*7,Ve=R*30,He=R*365,z=P(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*F)},(e,t)=>(t-e)/F,e=>e.getUTCSeconds());z.range;var Ue=P(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*F)},(e,t)=>{e.setTime(+e+t*I)},(e,t)=>(t-e)/I,e=>e.getMinutes());Ue.range;var We=P(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*I)},(e,t)=>(t-e)/I,e=>e.getUTCMinutes());We.range;var Ge=P(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*F-e.getMinutes()*I)},(e,t)=>{e.setTime(+e+t*L)},(e,t)=>(t-e)/L,e=>e.getHours());Ge.range;var Ke=P(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*L)},(e,t)=>(t-e)/L,e=>e.getUTCHours());Ke.range;var B=P(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*I)/R,e=>e.getDate()-1);B.range;var qe=P(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/R,e=>e.getUTCDate()-1);qe.range;var Je=P(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/R,e=>Math.floor(e/R));Je.range;function V(e){return P(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t*7)},(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*I)/Be)}var Ye=V(0),Xe=V(1),Ze=V(2),Qe=V(3),H=V(4),$e=V(5),et=V(6);Ye.range,Xe.range,Ze.range,Qe.range,H.range,$e.range,et.range;function U(e){return P(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t*7)},(e,t)=>(t-e)/Be)}var tt=U(0),nt=U(1),rt=U(2),it=U(3),at=U(4),ot=U(5),st=U(6);tt.range,nt.range,rt.range,it.range,at.range,ot.range,st.range;var ct=P(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());ct.range;var lt=P(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());lt.range;var W=P(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());W.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:P(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*e)}),W.range;var G=P(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());G.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:P(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*e)}),G.range;function ut(e,t,n,r,i,a){let o=[[z,1,F],[z,5,5*F],[z,15,15*F],[z,30,30*F],[a,1,I],[a,5,5*I],[a,15,15*I],[a,30,30*I],[i,1,L],[i,3,3*L],[i,6,6*L],[i,12,12*L],[r,1,R],[r,2,2*R],[n,1,Be],[t,1,Ve],[t,3,3*Ve],[e,1,He]];function s(e,t,n){let r=te).right(o,i);if(a===o.length)return e.every(w(t/He,n/He,r));if(a===0)return ze.every(Math.max(w(t,n,r),1));let[s,c]=o[i/o[a-1][2]53)return null;`w`in r||(r.w=1),`Z`in r?(a=gt(_t(r.y,0,1)),o=a.getUTCDay(),a=o>4||o===0?nt.ceil(a):nt(a),a=qe.offset(a,(r.V-1)*7),r.y=a.getUTCFullYear(),r.m=a.getUTCMonth(),r.d=a.getUTCDate()+(r.w+6)%7):(a=ht(_t(r.y,0,1)),o=a.getDay(),a=o>4||o===0?Xe.ceil(a):Xe(a),a=B.offset(a,(r.V-1)*7),r.y=a.getFullYear(),r.m=a.getMonth(),r.d=a.getDate()+(r.w+6)%7)}else(`W`in r||`U`in r)&&(`w`in r||(r.w=`u`in r?r.u%7:+(`W`in r)),o=`Z`in r?gt(_t(r.y,0,1)).getUTCDay():ht(_t(r.y,0,1)).getDay(),r.m=0,r.d=`W`in r?(r.w+6)%7+r.W*7-(o+5)%7:r.w+r.U*7-(o+6)%7);return`Z`in r?(r.H+=r.Z/100|0,r.M+=r.Z%100,gt(r)):ht(r)}}function w(e,t,n,r){for(var i=0,a=t.length,o=n.length,s,c;i=o)return-1;if(s=t.charCodeAt(i++),s===37){if(s=t.charAt(i++),c=x[s in yt?t.charAt(i++):s],!c||(r=c(e,n,r))<0)return-1}else if(s!=n.charCodeAt(r++))return-1}return r}function T(e,t,n){var r=l.exec(t.slice(n));return r?(e.p=u.get(r[0].toLowerCase()),n+r[0].length):-1}function E(e,t,n){var r=p.exec(t.slice(n));return r?(e.w=m.get(r[0].toLowerCase()),n+r[0].length):-1}function D(e,t,n){var r=d.exec(t.slice(n));return r?(e.w=f.get(r[0].toLowerCase()),n+r[0].length):-1}function O(e,t,n){var r=_.exec(t.slice(n));return r?(e.m=v.get(r[0].toLowerCase()),n+r[0].length):-1}function k(e,t,n){var r=h.exec(t.slice(n));return r?(e.m=g.get(r[0].toLowerCase()),n+r[0].length):-1}function ee(e,n,r){return w(e,t,n,r)}function A(e,t,r){return w(e,n,t,r)}function te(e,t,n){return w(e,r,t,n)}function ne(e){return o[e.getDay()]}function j(e){return a[e.getDay()]}function re(e){return c[e.getMonth()]}function ie(e){return s[e.getMonth()]}function ae(e){return i[+(e.getHours()>=12)]}function oe(e){return 1+~~(e.getMonth()/3)}function se(e){return o[e.getUTCDay()]}function ce(e){return a[e.getUTCDay()]}function le(e){return c[e.getUTCMonth()]}function ue(e){return s[e.getUTCMonth()]}function de(e){return i[+(e.getUTCHours()>=12)]}function fe(e){return 1+~~(e.getUTCMonth()/3)}return{format:function(e){var t=S(e+=``,y);return t.toString=function(){return e},t},parse:function(e){var t=C(e+=``,!1);return t.toString=function(){return e},t},utcFormat:function(e){var t=S(e+=``,b);return t.toString=function(){return e},t},utcParse:function(e){var t=C(e+=``,!0);return t.toString=function(){return e},t}}}var yt={"-":``,_:` `,0:`0`},K=/^\s*\d+/,bt=/^%/,xt=/[\\^$*+?|[\]().{}]/g;function q(e,t,n){var r=e<0?`-`:``,i=(r?-e:e)+``,a=i.length;return r+(a[e.toLowerCase(),t]))}function Tt(e,t,n){var r=K.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function Et(e,t,n){var r=K.exec(t.slice(n,n+1));return r?(e.u=+r[0],n+r[0].length):-1}function Dt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.U=+r[0],n+r[0].length):-1}function Ot(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.V=+r[0],n+r[0].length):-1}function kt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.W=+r[0],n+r[0].length):-1}function At(e,t,n){var r=K.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function jt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Mt(e,t,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(e.Z=r[1]?0:-(r[2]+(r[3]||`00`)),n+r[0].length):-1}function Nt(e,t,n){var r=K.exec(t.slice(n,n+1));return r?(e.q=r[0]*3-3,n+r[0].length):-1}function Pt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function Ft(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function It(e,t,n){var r=K.exec(t.slice(n,n+3));return r?(e.m=0,e.d=+r[0],n+r[0].length):-1}function Lt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function Rt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function zt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function Bt(e,t,n){var r=K.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function Vt(e,t,n){var r=K.exec(t.slice(n,n+6));return r?(e.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function Ht(e,t,n){var r=bt.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function Ut(e,t,n){var r=K.exec(t.slice(n));return r?(e.Q=+r[0],n+r[0].length):-1}function Wt(e,t,n){var r=K.exec(t.slice(n));return r?(e.s=+r[0],n+r[0].length):-1}function Gt(e,t){return q(e.getDate(),t,2)}function Kt(e,t){return q(e.getHours(),t,2)}function qt(e,t){return q(e.getHours()%12||12,t,2)}function Jt(e,t){return q(1+B.count(W(e),e),t,3)}function Yt(e,t){return q(e.getMilliseconds(),t,3)}function Xt(e,t){return Yt(e,t)+`000`}function Zt(e,t){return q(e.getMonth()+1,t,2)}function Qt(e,t){return q(e.getMinutes(),t,2)}function $t(e,t){return q(e.getSeconds(),t,2)}function en(e){var t=e.getDay();return t===0?7:t}function tn(e,t){return q(Ye.count(W(e)-1,e),t,2)}function nn(e){var t=e.getDay();return t>=4||t===0?H(e):H.ceil(e)}function rn(e,t){return e=nn(e),q(H.count(W(e),e)+(W(e).getDay()===4),t,2)}function an(e){return e.getDay()}function on(e,t){return q(Xe.count(W(e)-1,e),t,2)}function sn(e,t){return q(e.getFullYear()%100,t,2)}function cn(e,t){return e=nn(e),q(e.getFullYear()%100,t,2)}function ln(e,t){return q(e.getFullYear()%1e4,t,4)}function un(e,t){var n=e.getDay();return e=n>=4||n===0?H(e):H.ceil(e),q(e.getFullYear()%1e4,t,4)}function dn(e){var t=e.getTimezoneOffset();return(t>0?`-`:(t*=-1,`+`))+q(t/60|0,`0`,2)+q(t%60,`0`,2)}function fn(e,t){return q(e.getUTCDate(),t,2)}function pn(e,t){return q(e.getUTCHours(),t,2)}function mn(e,t){return q(e.getUTCHours()%12||12,t,2)}function hn(e,t){return q(1+qe.count(G(e),e),t,3)}function gn(e,t){return q(e.getUTCMilliseconds(),t,3)}function _n(e,t){return gn(e,t)+`000`}function vn(e,t){return q(e.getUTCMonth()+1,t,2)}function yn(e,t){return q(e.getUTCMinutes(),t,2)}function bn(e,t){return q(e.getUTCSeconds(),t,2)}function xn(e){var t=e.getUTCDay();return t===0?7:t}function Sn(e,t){return q(tt.count(G(e)-1,e),t,2)}function Cn(e){var t=e.getUTCDay();return t>=4||t===0?at(e):at.ceil(e)}function wn(e,t){return e=Cn(e),q(at.count(G(e),e)+(G(e).getUTCDay()===4),t,2)}function Tn(e){return e.getUTCDay()}function En(e,t){return q(nt.count(G(e)-1,e),t,2)}function Dn(e,t){return q(e.getUTCFullYear()%100,t,2)}function On(e,t){return e=Cn(e),q(e.getUTCFullYear()%100,t,2)}function kn(e,t){return q(e.getUTCFullYear()%1e4,t,4)}function An(e,t){var n=e.getUTCDay();return e=n>=4||n===0?at(e):at.ceil(e),q(e.getUTCFullYear()%1e4,t,4)}function jn(){return`+0000`}function Mn(){return`%`}function Nn(e){return+e}function Pn(e){return Math.floor(e/1e3)}var Fn,In;Ln({dateTime:`%x, %X`,date:`%-m/%-d/%Y`,time:`%-I:%M:%S %p`,periods:[`AM`,`PM`],days:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],shortDays:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],months:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],shortMonths:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`]});function Ln(e){return Fn=vt(e),In=Fn.format,Fn.parse,Fn.utcFormat,Fn.utcParse,Fn}function Rn(e){return new Date(e)}function zn(e){return e instanceof Date?+e:+new Date(+e)}function Bn(e,t,n,r,i,a,o,s,c,l){var u=T(),d=u.invert,f=u.domain,p=l(`.%L`),m=l(`:%S`),h=l(`%I:%M`),g=l(`%I %p`),_=l(`%a %d`),v=l(`%b %d`),y=l(`%B`),b=l(`%Y`);function x(e){return(c(e){(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_isoWeek=r()})(e,(function(){return function(e,t,n){var r=function(e){return e.add(4-e.isoWeekday(),`day`)},i=t.prototype;i.isoWeekYear=function(){return r(this).year()},i.isoWeek=function(e){if(!this.$utils().u(e))return this.add(7*(e-this.isoWeek()),`day`);var t,i,a,o,s=r(this),c=(t=this.isoWeekYear(),i=this.$u,a=(i?n.utc:n)().year(t).startOf(`year`),o=4-a.isoWeekday(),a.isoWeekday()>4&&(o+=7),a.add(o,`day`));return s.diff(c,`week`)+1},i.isoWeekday=function(e){return this.$utils().u(e)?this.day()||7:this.day(this.day()%7?e:e-7)};var a=i.startOf;i.startOf=function(e,t){var n=this.$utils(),r=!!n.u(t)||t;return n.p(e)===`isoweek`?r?this.date(this.date()-(this.isoWeekday()-1)).startOf(`day`):this.date(this.date()-1-(this.isoWeekday()-1)+7).endOf(`day`):a.bind(this)(e,t)}}}))})),Un=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_customParseFormat=r()})(e,(function(){var e={LTS:`h:mm:ss A`,LT:`h:mm A`,L:`MM/DD/YYYY`,LL:`MMMM D, YYYY`,LLL:`MMMM D, YYYY h:mm A`,LLLL:`dddd, MMMM D, YYYY h:mm A`},t=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,n=/\d/,r=/\d\d/,i=/\d\d?/,a=/\d*[^-_:/,()\s\d]+/,o={},s=function(e){return(e=+e)+(e>68?1900:2e3)},c=function(e){return function(t){this[e]=+t}},l=[/[+-]\d\d:?(\d\d)?|Z/,function(e){(this.zone||={}).offset=function(e){if(!e||e===`Z`)return 0;var t=e.match(/([+-]|\d\d)/g),n=60*t[1]+(+t[2]||0);return n===0?0:t[0]===`+`?-n:n}(e)}],u=function(e){var t=o[e];return t&&(t.indexOf?t:t.s.concat(t.f))},d=function(e,t){var n,r=o.meridiem;if(r){for(var i=1;i<=24;i+=1)if(e.indexOf(r(i,0,t))>-1){n=i>12;break}}else n=e===(t?`pm`:`PM`);return n},f={A:[a,function(e){this.afternoon=d(e,!1)}],a:[a,function(e){this.afternoon=d(e,!0)}],Q:[n,function(e){this.month=3*(e-1)+1}],S:[n,function(e){this.milliseconds=100*e}],SS:[r,function(e){this.milliseconds=10*e}],SSS:[/\d{3}/,function(e){this.milliseconds=+e}],s:[i,c(`seconds`)],ss:[i,c(`seconds`)],m:[i,c(`minutes`)],mm:[i,c(`minutes`)],H:[i,c(`hours`)],h:[i,c(`hours`)],HH:[i,c(`hours`)],hh:[i,c(`hours`)],D:[i,c(`day`)],DD:[r,c(`day`)],Do:[a,function(e){var t=o.ordinal,n=e.match(/\d+/);if(this.day=n[0],t)for(var r=1;r<=31;r+=1)t(r).replace(/\[|\]/g,``)===e&&(this.day=r)}],w:[i,c(`week`)],ww:[r,c(`week`)],M:[i,c(`month`)],MM:[r,c(`month`)],MMM:[a,function(e){var t=u(`months`),n=(u(`monthsShort`)||t.map((function(e){return e.slice(0,3)}))).indexOf(e)+1;if(n<1)throw Error();this.month=n%12||n}],MMMM:[a,function(e){var t=u(`months`).indexOf(e)+1;if(t<1)throw Error();this.month=t%12||t}],Y:[/[+-]?\d+/,c(`year`)],YY:[r,function(e){this.year=s(e)}],YYYY:[/\d{4}/,c(`year`)],Z:l,ZZ:l};function p(n){for(var r=n,i=o&&o.formats,a=(n=r.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(t,n,r){var a=r&&r.toUpperCase();return n||i[r]||e[r]||i[a].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(e,t,n){return t||n.slice(1)}))}))).match(t),s=a.length,c=0;c-1)return new Date((t===`X`?1e3:1)*e);var i=p(t)(e),a=i.year,o=i.month,s=i.day,c=i.hours,l=i.minutes,u=i.seconds,d=i.milliseconds,f=i.zone,m=i.week,h=new Date,g=s||(a||o?1:h.getDate()),_=a||h.getFullYear(),v=0;a&&!o||(v=o>0?o-1:h.getMonth());var y,b=c||0,x=l||0,S=u||0,C=d||0;return f?new Date(Date.UTC(_,v,g,b,x,S,C+60*f.offset*1e3)):n?new Date(Date.UTC(_,v,g,b,x,S,C)):(y=new Date(_,v,g,b,x,S,C),m&&(y=r(y).week(m).toDate()),y)}catch{return new Date(``)}}(t,s,r,n),this.init(),d&&!0!==d&&(this.$L=this.locale(d).$L),u&&t!=this.format(s)&&(this.$d=new Date(``)),o={}}else if(s instanceof Array)for(var f=s.length,m=1;m<=f;m+=1){a[1]=s[m-1];var h=n.apply(this,a);if(h.isValid()){this.$d=h.$d,this.$L=h.$L,this.init();break}m===f&&(this.$d=new Date(``))}else i.call(this,e)}}}))})),Wn=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_advancedFormat=r()})(e,(function(){return function(e,t){var n=t.prototype,r=n.format;n.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return r.bind(this)(e);var i=this.$utils(),a=(e||`YYYY-MM-DDTHH:mm:ssZ`).replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,(function(e){switch(e){case`Q`:return Math.ceil((t.$M+1)/3);case`Do`:return n.ordinal(t.$D);case`gggg`:return t.weekYear();case`GGGG`:return t.isoWeekYear();case`wo`:return n.ordinal(t.week(),`W`);case`w`:case`ww`:return i.s(t.week(),e===`w`?1:2,`0`);case`W`:case`WW`:return i.s(t.isoWeek(),e===`W`?1:2,`0`);case`k`:case`kk`:return i.s(String(t.$H===0?24:t.$H),e===`k`?1:2,`0`);case`X`:return Math.floor(t.$d.getTime()/1e3);case`x`:return t.$d.getTime();case`z`:return`[`+t.offsetName()+`]`;case`zzz`:return`[`+t.offsetName(`long`)+`]`;default:return e}}));return r.bind(this)(a)}}}))})),Gn=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_duration=r()})(e,(function(){var e,t,n=1e3,r=6e4,i=36e5,a=864e5,o=31536e6,s=2628e6,c=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,l=/\[([^\]]+)]|YYYY|YY|Y|M{1,2}|D{1,2}|H{1,2}|m{1,2}|s{1,2}|SSS/g,u={years:o,months:s,days:a,hours:i,minutes:r,seconds:n,milliseconds:1,weeks:6048e5},d=function(e){return e instanceof v},f=function(e,t,n){return new v(e,n,t.$l)},p=function(e){return t.p(e)+`s`},m=function(e){return e<0},h=function(e){return m(e)?Math.ceil(e):Math.floor(e)},g=function(e){return Math.abs(e)},_=function(e,t){return e?m(e)?{negative:!0,format:``+g(e)+t}:{negative:!1,format:``+e+t}:{negative:!1,format:``}},v=function(){function m(e,t,n){var r=this;if(this.$d={},this.$l=n,e===void 0&&(this.$ms=0,this.parseFromMilliseconds()),t)return f(e*u[p(t)],this);if(typeof e==`number`)return this.$ms=e,this.parseFromMilliseconds(),this;if(typeof e==`object`)return Object.keys(e).forEach((function(t){r.$d[p(t)]=e[t]})),this.calMilliseconds(),this;if(typeof e==`string`){var i=e.match(c);if(i){var a=i.slice(2).map((function(e){return e==null?0:Number(e)}));return this.$d.years=a[0],this.$d.months=a[1],this.$d.weeks=a[2],this.$d.days=a[3],this.$d.hours=a[4],this.$d.minutes=a[5],this.$d.seconds=a[6],this.calMilliseconds(),this}}return this}var g=m.prototype;return g.calMilliseconds=function(){var e=this;this.$ms=Object.keys(this.$d).reduce((function(t,n){return t+(e.$d[n]||0)*u[n]}),0)},g.parseFromMilliseconds=function(){var e=this.$ms;this.$d.years=h(e/o),e%=o,this.$d.months=h(e/s),e%=s,this.$d.days=h(e/a),e%=a,this.$d.hours=h(e/i),e%=i,this.$d.minutes=h(e/r),e%=r,this.$d.seconds=h(e/n),e%=n,this.$d.milliseconds=e},g.toISOString=function(){var e=_(this.$d.years,`Y`),t=_(this.$d.months,`M`),n=+this.$d.days||0;this.$d.weeks&&(n+=7*this.$d.weeks);var r=_(n,`D`),i=_(this.$d.hours,`H`),a=_(this.$d.minutes,`M`),o=this.$d.seconds||0;this.$d.milliseconds&&(o+=this.$d.milliseconds/1e3,o=Math.round(1e3*o)/1e3);var s=_(o,`S`),c=e.negative||t.negative||r.negative||i.negative||a.negative||s.negative,l=i.format||a.format||s.format?`T`:``,u=(c?`-`:``)+`P`+e.format+t.format+r.format+l+i.format+a.format+s.format;return u===`P`||u===`-P`?`P0D`:u},g.toJSON=function(){return this.toISOString()},g.format=function(e){var n=e||`YYYY-MM-DDTHH:mm:ss`,r={Y:this.$d.years,YY:t.s(this.$d.years,2,`0`),YYYY:t.s(this.$d.years,4,`0`),M:this.$d.months,MM:t.s(this.$d.months,2,`0`),D:this.$d.days,DD:t.s(this.$d.days,2,`0`),H:this.$d.hours,HH:t.s(this.$d.hours,2,`0`),m:this.$d.minutes,mm:t.s(this.$d.minutes,2,`0`),s:this.$d.seconds,ss:t.s(this.$d.seconds,2,`0`),SSS:t.s(this.$d.milliseconds,3,`0`)};return n.replace(l,(function(e,t){return t||String(r[e])}))},g.as=function(e){return this.$ms/u[p(e)]},g.get=function(e){var t=this.$ms,n=p(e);return n===`milliseconds`?t%=1e3:t=n===`weeks`?h(t/u[n]):this.$d[n],t||0},g.add=function(e,t,n){var r;return r=t?e*u[p(t)]:d(e)?e.$ms:f(e,this).$ms,f(this.$ms+r*(n?-1:1),this)},g.subtract=function(e,t){return this.add(e,t,!0)},g.locale=function(e){var t=this.clone();return t.$l=e,t},g.clone=function(){return f(this.$ms,this)},g.humanize=function(t){return e().add(this.$ms,`ms`).locale(this.$l).fromNow(!t)},g.valueOf=function(){return this.asMilliseconds()},g.milliseconds=function(){return this.get(`milliseconds`)},g.asMilliseconds=function(){return this.as(`milliseconds`)},g.seconds=function(){return this.get(`seconds`)},g.asSeconds=function(){return this.as(`seconds`)},g.minutes=function(){return this.get(`minutes`)},g.asMinutes=function(){return this.as(`minutes`)},g.hours=function(){return this.get(`hours`)},g.asHours=function(){return this.as(`hours`)},g.days=function(){return this.get(`days`)},g.asDays=function(){return this.as(`days`)},g.weeks=function(){return this.get(`weeks`)},g.asWeeks=function(){return this.as(`weeks`)},g.months=function(){return this.get(`months`)},g.asMonths=function(){return this.as(`months`)},g.years=function(){return this.get(`years`)},g.asYears=function(){return this.as(`years`)},m}(),y=function(e,t,n){return e.add(t.years()*n,`y`).add(t.months()*n,`M`).add(t.days()*n,`d`).add(t.hours()*n,`h`).add(t.minutes()*n,`m`).add(t.seconds()*n,`s`).add(t.milliseconds()*n,`ms`)};return function(n,r,i){e=i,t=i().$utils(),i.duration=function(e,t){return f(e,{$l:i.locale()},t)},i.isDuration=d;var a=r.prototype.add,o=r.prototype.subtract;r.prototype.add=function(e,t){return d(e)?y(this,e,1):a.bind(this)(e,t)},r.prototype.subtract=function(e,t){return d(e)?y(this,e,-1):o.bind(this)(e,t)}}}))})),Kn=k(),J=e(s(),1),qn=e(Hn(),1),Jn=e(Un(),1),Yn=e(Wn(),1),Xn=e(Gn(),1),Zn=(function(){var e=n(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),t=[6,8,10,12,13,14,15,16,17,18,20,21,22,23,24,25,26,27,28,29,30,31,33,35,36,38,40],r=[1,26],i=[1,27],a=[1,28],o=[1,29],s=[1,30],c=[1,31],l=[1,32],u=[1,33],d=[1,34],f=[1,9],p=[1,10],m=[1,11],h=[1,12],g=[1,13],_=[1,14],v=[1,15],y=[1,16],b=[1,19],x=[1,20],S=[1,21],C=[1,22],w=[1,23],T=[1,25],E=[1,35],D={trace:n(function(){},`trace`),yy:{},symbols_:{error:2,start:3,gantt:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NL:10,weekday:11,weekday_monday:12,weekday_tuesday:13,weekday_wednesday:14,weekday_thursday:15,weekday_friday:16,weekday_saturday:17,weekday_sunday:18,weekend:19,weekend_friday:20,weekend_saturday:21,dateFormat:22,inclusiveEndDates:23,topAxis:24,axisFormat:25,tickInterval:26,excludes:27,includes:28,todayMarker:29,title:30,acc_title:31,acc_title_value:32,acc_descr:33,acc_descr_value:34,acc_descr_multiline_value:35,section:36,clickStatement:37,taskTxt:38,taskData:39,click:40,callbackname:41,callbackargs:42,href:43,clickStatementDebug:44,$accept:0,$end:1},terminals_:{2:`error`,4:`gantt`,6:`EOF`,8:`SPACE`,10:`NL`,12:`weekday_monday`,13:`weekday_tuesday`,14:`weekday_wednesday`,15:`weekday_thursday`,16:`weekday_friday`,17:`weekday_saturday`,18:`weekday_sunday`,20:`weekend_friday`,21:`weekend_saturday`,22:`dateFormat`,23:`inclusiveEndDates`,24:`topAxis`,25:`axisFormat`,26:`tickInterval`,27:`excludes`,28:`includes`,29:`todayMarker`,30:`title`,31:`acc_title`,32:`acc_title_value`,33:`acc_descr`,34:`acc_descr_value`,35:`acc_descr_multiline_value`,36:`section`,38:`taskTxt`,39:`taskData`,40:`click`,41:`callbackname`,42:`callbackargs`,43:`href`},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[19,1],[19,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,1],[9,2],[37,2],[37,3],[37,3],[37,4],[37,3],[37,4],[37,2],[44,2],[44,3],[44,3],[44,4],[44,3],[44,4],[44,2]],performAction:n(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 2:this.$=[];break;case 3:a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 5:this.$=a[s];break;case 6:case 7:this.$=[];break;case 8:r.setWeekday(`monday`);break;case 9:r.setWeekday(`tuesday`);break;case 10:r.setWeekday(`wednesday`);break;case 11:r.setWeekday(`thursday`);break;case 12:r.setWeekday(`friday`);break;case 13:r.setWeekday(`saturday`);break;case 14:r.setWeekday(`sunday`);break;case 15:r.setWeekend(`friday`);break;case 16:r.setWeekend(`saturday`);break;case 17:r.setDateFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 18:r.enableInclusiveEndDates(),this.$=a[s].substr(18);break;case 19:r.TopAxis(),this.$=a[s].substr(8);break;case 20:r.setAxisFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 21:r.setTickInterval(a[s].substr(13)),this.$=a[s].substr(13);break;case 22:r.setExcludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 23:r.setIncludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 24:r.setTodayMarker(a[s].substr(12)),this.$=a[s].substr(12);break;case 27:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 28:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 29:case 30:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 31:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 33:r.addTask(a[s-1],a[s]),this.$=`task`;break;case 34:this.$=a[s-1],r.setClickEvent(a[s-1],a[s],null);break;case 35:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 36:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],null),r.setLink(a[s-2],a[s]);break;case 37:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setLink(a[s-3],a[s]);break;case 38:this.$=a[s-2],r.setClickEvent(a[s-2],a[s],null),r.setLink(a[s-2],a[s-1]);break;case 39:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-1],a[s]),r.setLink(a[s-3],a[s-2]);break;case 40:this.$=a[s-1],r.setLink(a[s-1],a[s]);break;case 41:case 47:this.$=a[s-1]+` `+a[s];break;case 42:case 43:case 45:this.$=a[s-2]+` `+a[s-1]+` `+a[s];break;case 44:case 46:this.$=a[s-3]+` `+a[s-2]+` `+a[s-1]+` `+a[s];break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},e(t,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:17,12:r,13:i,14:a,15:o,16:s,17:c,18:l,19:18,20:u,21:d,22:f,23:p,24:m,25:h,26:g,27:_,28:v,29:y,30:b,31:x,33:S,35:C,36:w,37:24,38:T,40:E},e(t,[2,7],{1:[2,1]}),e(t,[2,3]),{9:36,11:17,12:r,13:i,14:a,15:o,16:s,17:c,18:l,19:18,20:u,21:d,22:f,23:p,24:m,25:h,26:g,27:_,28:v,29:y,30:b,31:x,33:S,35:C,36:w,37:24,38:T,40:E},e(t,[2,5]),e(t,[2,6]),e(t,[2,17]),e(t,[2,18]),e(t,[2,19]),e(t,[2,20]),e(t,[2,21]),e(t,[2,22]),e(t,[2,23]),e(t,[2,24]),e(t,[2,25]),e(t,[2,26]),e(t,[2,27]),{32:[1,37]},{34:[1,38]},e(t,[2,30]),e(t,[2,31]),e(t,[2,32]),{39:[1,39]},e(t,[2,8]),e(t,[2,9]),e(t,[2,10]),e(t,[2,11]),e(t,[2,12]),e(t,[2,13]),e(t,[2,14]),e(t,[2,15]),e(t,[2,16]),{41:[1,40],43:[1,41]},e(t,[2,4]),e(t,[2,28]),e(t,[2,29]),e(t,[2,33]),e(t,[2,34],{42:[1,42],43:[1,43]}),e(t,[2,40],{41:[1,44]}),e(t,[2,35],{43:[1,45]}),e(t,[2,36]),e(t,[2,38],{42:[1,46]}),e(t,[2,37]),e(t,[2,39])],defaultActions:{},parseError:n(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:n(function(e){var t=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(e,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}n(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=t.symbols_[e]||e),e}n(x,`lex`);for(var S,C,w,T,E,D={},O,k,ee,A;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var te=``;for(O in A=[],s[w])this.terminals_[O]&&O>f&&A.push(`'`+this.terminals_[O]+`'`);te=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+A.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(te,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:A})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),ee=s[r[r.length-2]][r[r.length-1]],r.push(ee);break;case 3:return!0}}return!0},`parse`)};D.lexer=(function(){return{EOF:1,parseError:n(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:n(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:n(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:n(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:n(function(){return this._more=!0,this},`more`),reject:n(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:n(function(e){this.unput(this.match.slice(e))},`less`),pastInput:n(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:n(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:n(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/gitGraphDiagram-IHSO6WYX-B4amBdmg.js b/.vercel/output/static/assets/gitGraphDiagram-IHSO6WYX-CPtw8GFs.js similarity index 99% rename from .vercel/output/static/assets/gitGraphDiagram-IHSO6WYX-B4amBdmg.js rename to .vercel/output/static/assets/gitGraphDiagram-IHSO6WYX-CPtw8GFs.js index afdf2b2..fdc61da 100644 --- a/.vercel/output/static/assets/gitGraphDiagram-IHSO6WYX-B4amBdmg.js +++ b/.vercel/output/static/assets/gitGraphDiagram-IHSO6WYX-CPtw8GFs.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{H as r,K as i,U as a,Y as o,a as s,b as c,f as l,s as u,v as d,w as f,x as p,y as m}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{g as h,i as g,m as _}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as v}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as y}from"./mermaid-parser.core-AdnthA1k.js";import{t as b}from"./chunk-2Q5K7J3B-C1jixKkw.js";var x={NORMAL:0,REVERSE:1,HIGHLIGHT:2,MERGE:3,CHERRY_PICK:4},ee=l.gitGraph,S=e(()=>g({...ee,...c().gitGraph}),`getConfig`),C=new b(()=>{let e=S(),t=e.mainBranchName,n=e.mainBranchOrder;return{mainBranchName:t,commits:new Map,head:null,branchConfig:new Map([[t,{name:t,order:n}]]),branches:new Map([[t,null]]),currBranch:t,direction:`LR`,seq:0,options:{}}});function w(){return _({length:7})}e(w,`getID`);function T(e,t){let n=Object.create(null);return e.reduce((e,r)=>{let i=t(r);return n[i]||(n[i]=!0,e.push(r)),e},[])}e(T,`uniqBy`);var te=e(function(e){C.records.direction=e},`setDirection`),ne=e(function(e){t.debug(`options str`,e),e=e?.trim(),e||=`{}`;try{C.records.options=JSON.parse(e)}catch(e){t.error(`error while parsing gitGraph options`,e.message)}},`setOptions`),re=e(function(){return C.records.options},`getOptions`),ie=e(function(e){let n=e.msg,r=e.id,i=e.type,a=e.tags;t.info(`commit`,n,r,i,a),t.debug(`Entering commit:`,n,r,i,a);let o=S();r=u.sanitizeText(r,o),n=u.sanitizeText(n,o),a=a?.map(e=>u.sanitizeText(e,o));let s={id:r||C.records.seq+`-`+w(),message:n,seq:C.records.seq++,type:i??x.NORMAL,tags:a??[],parents:C.records.head==null?[]:[C.records.head.id],branch:C.records.currBranch};C.records.head=s,t.info(`main branch`,o.mainBranchName),C.records.commits.has(s.id)&&t.warn(`Commit ID ${s.id} already exists`),C.records.commits.set(s.id,s),C.records.branches.set(C.records.currBranch,s.id),t.debug(`in pushCommit `+s.id)},`commit`),ae=e(function(e){let n=e.name,r=e.order;if(n=u.sanitizeText(n,S()),C.records.branches.has(n))throw Error(`Trying to create an existing branch. (Help: Either use a new name if you want create a new branch or try using "checkout ${n}")`);C.records.branches.set(n,C.records.head==null?null:C.records.head.id),C.records.branchConfig.set(n,{name:n,order:r}),E(n),t.debug(`in createBranch`)},`branch`),oe=e(e=>{let n=e.branch,r=e.id,i=e.type,a=e.tags,o=S();n=u.sanitizeText(n,o),r&&=u.sanitizeText(r,o);let s=C.records.branches.get(C.records.currBranch),c=C.records.branches.get(n),l=s?C.records.commits.get(s):void 0,d=c?C.records.commits.get(c):void 0;if(l&&d&&l.branch===n)throw Error(`Cannot merge branch '${n}' into itself.`);if(C.records.currBranch===n){let e=Error(`Incorrect usage of "merge". Cannot merge a branch to itself`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`branch abc`]},e}if(l===void 0||!l){let e=Error(`Incorrect usage of "merge". Current branch (${C.records.currBranch})has no commits`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`commit`]},e}if(!C.records.branches.has(n)){let e=Error(`Incorrect usage of "merge". Branch to be merged (`+n+`) does not exist`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`branch ${n}`]},e}if(d===void 0||!d){let e=Error(`Incorrect usage of "merge". Branch to be merged (`+n+`) has no commits`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`"commit"`]},e}if(l===d){let e=Error(`Incorrect usage of "merge". Both branches have same head`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`branch abc`]},e}if(r&&C.records.commits.has(r)){let e=Error(`Incorrect usage of "merge". Commit with id:`+r+` already exists, use different custom id`);throw e.hash={text:`merge ${n} ${r} ${i} ${a?.join(` `)}`,token:`merge ${n} ${r} ${i} ${a?.join(` `)}`,expected:[`merge ${n} ${r}_UNIQUE ${i} ${a?.join(` `)}`]},e}let f=c||``,p={id:r||`${C.records.seq}-${w()}`,message:`merged branch ${n} into ${C.records.currBranch}`,seq:C.records.seq++,parents:C.records.head==null?[]:[C.records.head.id,f],branch:C.records.currBranch,type:x.MERGE,customType:i,customId:!!r,tags:a??[]};C.records.head=p,C.records.commits.set(p.id,p),C.records.branches.set(C.records.currBranch,p.id),t.debug(C.records.branches),t.debug(`in mergeBranch`)},`merge`),se=e(function(e){let n=e.id,r=e.targetId,i=e.tags,a=e.parent;t.debug(`Entering cherryPick:`,n,r,i);let o=S();if(n=u.sanitizeText(n,o),r=u.sanitizeText(r,o),i=i?.map(e=>u.sanitizeText(e,o)),a=u.sanitizeText(a,o),!n||!C.records.commits.has(n)){let e=Error(`Incorrect usage of "cherryPick". Source commit id should exist and provided`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let s=C.records.commits.get(n);if(s===void 0||!s)throw Error(`Incorrect usage of "cherryPick". Source commit id should exist and provided`);if(a&&!(Array.isArray(s.parents)&&s.parents.includes(a)))throw Error(`Invalid operation: The specified parent commit is not an immediate parent of the cherry-picked commit.`);let c=s.branch;if(s.type===x.MERGE&&!a)throw Error(`Incorrect usage of cherry-pick: If the source commit is a merge commit, an immediate parent commit must be specified.`);if(!r||!C.records.commits.has(r)){if(c===C.records.currBranch){let e=Error(`Incorrect usage of "cherryPick". Source commit is already on current branch`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let e=C.records.branches.get(C.records.currBranch);if(e===void 0||!e){let e=Error(`Incorrect usage of "cherry-pick". Current branch (${C.records.currBranch})has no commits`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let o=C.records.commits.get(e);if(o===void 0||!o){let e=Error(`Incorrect usage of "cherry-pick". Current branch (${C.records.currBranch})has no commits`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let l={id:C.records.seq+`-`+w(),message:`cherry-picked ${s?.message} into ${C.records.currBranch}`,seq:C.records.seq++,parents:C.records.head==null?[]:[C.records.head.id,s.id],branch:C.records.currBranch,type:x.CHERRY_PICK,tags:i?i.filter(Boolean):[`cherry-pick:${s.id}${s.type===x.MERGE?`|parent:${a}`:``}`]};C.records.head=l,C.records.commits.set(l.id,l),C.records.branches.set(C.records.currBranch,l.id),t.debug(C.records.branches),t.debug(`in cherryPick`)}},`cherryPick`),E=e(function(e){if(e=u.sanitizeText(e,S()),C.records.branches.has(e)){C.records.currBranch=e;let t=C.records.branches.get(C.records.currBranch);t===void 0||!t?C.records.head=null:C.records.head=C.records.commits.get(t)??null}else{let t=Error(`Trying to checkout branch which is not yet created. (Help try using "branch ${e}")`);throw t.hash={text:`checkout ${e}`,token:`checkout ${e}`,expected:[`branch ${e}`]},t}},`checkout`);function D(e,t,n){let r=e.indexOf(t);r===-1?e.push(n):e.splice(r,1,n)}e(D,`upsert`);function O(e){let n=e.reduce((e,t)=>e.seq>t.seq?e:t,e[0]),r=``;e.forEach(function(e){e===n?r+=` *`:r+=` |`});let i=[r,n.id,n.seq];for(let e in C.records.branches)C.records.branches.get(e)===n.id&&i.push(e);if(t.debug(i.join(` `)),n.parents&&n.parents.length==2&&n.parents[0]&&n.parents[1]){let t=C.records.commits.get(n.parents[0]);D(e,n,t),n.parents[1]&&e.push(C.records.commits.get(n.parents[1]))}else if(n.parents.length==0)return;else if(n.parents[0]){let t=C.records.commits.get(n.parents[0]);D(e,n,t)}e=T(e,e=>e.id),O(e)}e(O,`prettyPrintCommitHistory`);var ce=e(function(){t.debug(C.records.commits);let e=k()[0];O([e])},`prettyPrint`),le=e(function(){C.reset(),s()},`clear`),ue=e(function(){return[...C.records.branchConfig.values()].map((e,t)=>e.order!==null&&e.order!==void 0?e:{...e,order:parseFloat(`0.${t}`)}).sort((e,t)=>(e.order??0)-(t.order??0)).map(({name:e})=>({name:e}))},`getBranchesAsObjArray`),de=e(function(){return C.records.branches},`getBranches`),fe=e(function(){return C.records.commits},`getCommits`),k=e(function(){let e=[...C.records.commits.values()];return e.forEach(function(e){t.debug(e.id)}),e.sort((e,t)=>e.seq-t.seq),e},`getCommitsArray`),A={commitType:x,getConfig:S,setDirection:te,setOptions:ne,getOptions:re,commit:ie,branch:ae,merge:oe,cherryPick:se,checkout:E,prettyPrint:ce,clear:le,getBranchesAsObjArray:ue,getBranches:de,getCommits:fe,getCommitsArray:k,getCurrentBranch:e(function(){return C.records.currBranch},`getCurrentBranch`),getDirection:e(function(){return C.records.direction},`getDirection`),getHead:e(function(){return C.records.head},`getHead`),setAccTitle:a,getAccTitle:m,getAccDescription:d,setAccDescription:r,setDiagramTitle:i,getDiagramTitle:f},pe=e((e,t)=>{v(e,t),e.dir&&t.setDirection(e.dir);for(let n of e.statements)me(n,t)},`populate`),me=e((n,r)=>{let i={Commit:e(e=>r.commit(he(e)),`Commit`),Branch:e(e=>r.branch(ge(e)),`Branch`),Merge:e(e=>r.merge(_e(e)),`Merge`),Checkout:e(e=>r.checkout(ve(e)),`Checkout`),CherryPicking:e(e=>r.cherryPick(ye(e)),`CherryPicking`)}[n.$type];i?i(n):t.error(`Unknown statement type: ${n.$type}`)},`parseStatement`),he=e(e=>({id:e.id,msg:e.message??``,type:e.type===void 0?x.NORMAL:x[e.type],tags:e.tags??void 0}),`parseCommit`),ge=e(e=>({name:e.name,order:e.order??0}),`parseBranch`),_e=e(e=>({branch:e.branch,id:e.id??``,type:e.type===void 0?void 0:x[e.type],tags:e.tags??void 0}),`parseMerge`),ve=e(e=>e.branch,`parseCheckout`),ye=e(e=>({id:e.id,targetId:``,tags:e.tags?.length===0?void 0:e.tags,parent:e.parent}),`parseCherryPicking`),be={parse:e(async e=>{let n=await y(`gitGraph`,e);t.debug(n),pe(n,A)},`parse`)},j=10,M=40,N=4,P=2,F=8,I=new Set([`redux`,`redux-dark`,`redux-color`,`redux-dark-color`]),L=12,R=new Set([`redux-color`,`redux-dark-color`]),xe=new Set([`dark`,`redux-dark`,`redux-dark-color`,`neo-dark`]),z=e((e,t,n=!1)=>n&&e>0?(e-1)%(t-1)+1:e%t,`calcColorIndex`),B=new Map,V=new Map,H=30,U=new Map,W=[],G=0,K=`LR`,q=e(()=>{B.clear(),V.clear(),U.clear(),G=0,W=[],K=`LR`},`clear`),J=e(e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);return(typeof e==`string`?e.split(/\\n|\n|/gi):e).forEach(e=>{let n=document.createElementNS(`http://www.w3.org/2000/svg`,`tspan`);n.setAttributeNS(`http://www.w3.org/XML/1998/namespace`,`xml:space`,`preserve`),n.setAttribute(`dy`,`1em`),n.setAttribute(`x`,`0`),n.setAttribute(`class`,`row`),n.textContent=e.trim(),t.appendChild(n)}),t},`drawText`),Y=e(t=>{let n,r,i;return K===`BT`?(r=e((e,t)=>e<=t,`comparisonFunc`),i=1/0):(r=e((e,t)=>e>=t,`comparisonFunc`),i=0),t.forEach(e=>{let t=K===`TB`||K==`BT`?V.get(e)?.y:V.get(e)?.x;t!==void 0&&r(t,i)&&(n=e,i=t)}),n},`findClosestParent`),Se=e(e=>{let t=``,n=1/0;return e.forEach(e=>{let r=V.get(e).y;r<=n&&(t=e,n=r)}),t||void 0},`findClosestParentBT`),Ce=e((e,t,n)=>{let r=n,i=n,a=[];e.forEach(e=>{let n=t.get(e);if(!n)throw Error(`Commit not found for key ${e}`);n.parents.length?(r=Te(n),i=Math.max(r,i)):a.push(n),Ee(n,r)}),r=i,a.forEach(e=>{De(e,r,n)}),e.forEach(e=>{let n=t.get(e);if(n?.parents.length){let e=Se(n.parents);r=V.get(e).y-M,r<=i&&(i=r);let t=B.get(n.branch).pos,a=r-j;V.set(n.id,{x:t,y:a})}})},`setParallelBTPos`),we=e(e=>{let t=Y(e.parents.filter(e=>e!==null));if(!t)throw Error(`Closest parent not found for commit ${e.id}`);let n=V.get(t)?.y;if(n===void 0)throw Error(`Closest parent position not found for commit ${e.id}`);return n},`findClosestParentPos`),Te=e(e=>we(e)+M,`calculateCommitPosition`),Ee=e((e,t)=>{let n=B.get(e.branch);if(!n)throw Error(`Branch not found for commit ${e.id}`);let r=n.pos,i=t+j;return V.set(e.id,{x:r,y:i}),{x:r,y:i}},`setCommitPosition`),De=e((e,t,n)=>{let r=B.get(e.branch);if(!r)throw Error(`Branch not found for commit ${e.id}`);let i=t+n,a=r.pos;V.set(e.id,{x:a,y:i})},`setRootPosition`),Oe=e((e,t,n,r,i,a)=>{let{theme:o}=p(),s=I.has(o??``),c=R.has(o??``),l=xe.has(o??``);if(a===x.HIGHLIGHT)e.append(`rect`).attr(`x`,n.x-10+(s?3:0)).attr(`y`,n.y-10+(s?3:0)).attr(`width`,s?14:20).attr(`height`,s?14:20).attr(`class`,`commit ${t.id} commit-highlight${z(i,F,c)} ${r}-outer`),e.append(`rect`).attr(`x`,n.x-6+(s?2:0)).attr(`y`,n.y-6+(s?2:0)).attr(`width`,s?8:12).attr(`height`,s?8:12).attr(`class`,`commit ${t.id} commit${z(i,F,c)} ${r}-inner`);else if(a===x.CHERRY_PICK)e.append(`circle`).attr(`cx`,n.x).attr(`cy`,n.y).attr(`r`,s?7:10).attr(`class`,`commit ${t.id} ${r}`),e.append(`circle`).attr(`cx`,n.x-3).attr(`cy`,n.y+2).attr(`r`,s?2.5:2.75).attr(`fill`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`),e.append(`circle`).attr(`cx`,n.x+3).attr(`cy`,n.y+2).attr(`r`,s?2.5:2.75).attr(`fill`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`),e.append(`line`).attr(`x1`,n.x+3).attr(`y1`,n.y+1).attr(`x2`,n.x).attr(`y2`,n.y-5).attr(`stroke`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`),e.append(`line`).attr(`x1`,n.x-3).attr(`y1`,n.y+1).attr(`x2`,n.x).attr(`y2`,n.y-5).attr(`stroke`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`);else{let o=e.append(`circle`);if(o.attr(`cx`,n.x),o.attr(`cy`,n.y),o.attr(`r`,s?7:10),o.attr(`class`,`commit ${t.id} commit${z(i,F,c)}`),a===x.MERGE){let a=e.append(`circle`);a.attr(`cx`,n.x),a.attr(`cy`,n.y),a.attr(`r`,s?5:6),a.attr(`class`,`commit ${r} ${t.id} commit${z(i,F,c)}`)}if(a===x.REVERSE){let a=e.append(`path`),o=s?4:5;a.attr(`d`,`M ${n.x-o},${n.y-o}L${n.x+o},${n.y+o}M${n.x-o},${n.y+o}L${n.x+o},${n.y-o}`).attr(`class`,`commit ${r} ${t.id} commit${z(i,F,c)}`)}}},`drawCommitBullet`),ke=e((e,t,n,r,i)=>{if(t.type!==x.CHERRY_PICK&&(t.customId&&t.type===x.MERGE||t.type!==x.MERGE)&&i.showCommitLabel){let a=e.append(`g`),o=a.insert(`rect`).attr(`class`,`commit-label-bkg`),s=a.append(`text`).attr(`x`,r).attr(`y`,n.y+25).attr(`class`,`commit-label`).text(t.id),c=s.node()?.getBBox();if(c&&(o.attr(`x`,n.posWithOffset-c.width/2-P).attr(`y`,n.y+13.5).attr(`width`,c.width+2*P).attr(`height`,c.height+2*P),K===`TB`||K===`BT`?(o.attr(`x`,n.x-(c.width+4*N+5)).attr(`y`,n.y-12),s.attr(`x`,n.x-(c.width+4*N)).attr(`y`,n.y+c.height-12)):s.attr(`x`,n.posWithOffset-c.width/2),i.rotateCommitLabel))if(K===`TB`||K===`BT`)s.attr(`transform`,`rotate(-45, `+n.x+`, `+n.y+`)`),o.attr(`transform`,`rotate(-45, `+n.x+`, `+n.y+`)`);else{let e=-7.5-(c.width+10)/25*9.5,t=10+c.width/25*8.5;a.attr(`transform`,`translate(`+e+`, `+t+`) rotate(-45, `+r+`, `+n.y+`)`)}}},`drawCommitLabel`),Ae=e((e,t,n,r)=>{if(t.tags.length>0){let i=0,a=0,o=0,s=[];for(let r of t.tags.reverse()){let t=e.insert(`polygon`),c=e.append(`circle`),l=e.append(`text`).attr(`y`,n.y-16-i).attr(`class`,`tag-label`).text(r),u=l.node()?.getBBox();if(!u)throw Error(`Tag bbox not found`);a=Math.max(a,u.width),o=Math.max(o,u.height),l.attr(`x`,n.posWithOffset-u.width/2),s.push({tag:l,hole:c,rect:t,yOffset:i}),i+=20}for(let{tag:e,hole:t,rect:i,yOffset:c}of s){let s=o/2,l=n.y-19.2-c;if(i.attr(`class`,`tag-label-bkg`).attr(`points`,` +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{H as r,K as i,U as a,Y as o,a as s,b as c,f as l,s as u,v as d,w as f,x as p,y as m}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{g as h,i as g,m as _}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as v}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as y}from"./mermaid-parser.core-Z7xZAZRH.js";import{t as b}from"./chunk-2Q5K7J3B-C1jixKkw.js";var x={NORMAL:0,REVERSE:1,HIGHLIGHT:2,MERGE:3,CHERRY_PICK:4},ee=l.gitGraph,S=e(()=>g({...ee,...c().gitGraph}),`getConfig`),C=new b(()=>{let e=S(),t=e.mainBranchName,n=e.mainBranchOrder;return{mainBranchName:t,commits:new Map,head:null,branchConfig:new Map([[t,{name:t,order:n}]]),branches:new Map([[t,null]]),currBranch:t,direction:`LR`,seq:0,options:{}}});function w(){return _({length:7})}e(w,`getID`);function T(e,t){let n=Object.create(null);return e.reduce((e,r)=>{let i=t(r);return n[i]||(n[i]=!0,e.push(r)),e},[])}e(T,`uniqBy`);var te=e(function(e){C.records.direction=e},`setDirection`),ne=e(function(e){t.debug(`options str`,e),e=e?.trim(),e||=`{}`;try{C.records.options=JSON.parse(e)}catch(e){t.error(`error while parsing gitGraph options`,e.message)}},`setOptions`),re=e(function(){return C.records.options},`getOptions`),ie=e(function(e){let n=e.msg,r=e.id,i=e.type,a=e.tags;t.info(`commit`,n,r,i,a),t.debug(`Entering commit:`,n,r,i,a);let o=S();r=u.sanitizeText(r,o),n=u.sanitizeText(n,o),a=a?.map(e=>u.sanitizeText(e,o));let s={id:r||C.records.seq+`-`+w(),message:n,seq:C.records.seq++,type:i??x.NORMAL,tags:a??[],parents:C.records.head==null?[]:[C.records.head.id],branch:C.records.currBranch};C.records.head=s,t.info(`main branch`,o.mainBranchName),C.records.commits.has(s.id)&&t.warn(`Commit ID ${s.id} already exists`),C.records.commits.set(s.id,s),C.records.branches.set(C.records.currBranch,s.id),t.debug(`in pushCommit `+s.id)},`commit`),ae=e(function(e){let n=e.name,r=e.order;if(n=u.sanitizeText(n,S()),C.records.branches.has(n))throw Error(`Trying to create an existing branch. (Help: Either use a new name if you want create a new branch or try using "checkout ${n}")`);C.records.branches.set(n,C.records.head==null?null:C.records.head.id),C.records.branchConfig.set(n,{name:n,order:r}),E(n),t.debug(`in createBranch`)},`branch`),oe=e(e=>{let n=e.branch,r=e.id,i=e.type,a=e.tags,o=S();n=u.sanitizeText(n,o),r&&=u.sanitizeText(r,o);let s=C.records.branches.get(C.records.currBranch),c=C.records.branches.get(n),l=s?C.records.commits.get(s):void 0,d=c?C.records.commits.get(c):void 0;if(l&&d&&l.branch===n)throw Error(`Cannot merge branch '${n}' into itself.`);if(C.records.currBranch===n){let e=Error(`Incorrect usage of "merge". Cannot merge a branch to itself`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`branch abc`]},e}if(l===void 0||!l){let e=Error(`Incorrect usage of "merge". Current branch (${C.records.currBranch})has no commits`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`commit`]},e}if(!C.records.branches.has(n)){let e=Error(`Incorrect usage of "merge". Branch to be merged (`+n+`) does not exist`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`branch ${n}`]},e}if(d===void 0||!d){let e=Error(`Incorrect usage of "merge". Branch to be merged (`+n+`) has no commits`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`"commit"`]},e}if(l===d){let e=Error(`Incorrect usage of "merge". Both branches have same head`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`branch abc`]},e}if(r&&C.records.commits.has(r)){let e=Error(`Incorrect usage of "merge". Commit with id:`+r+` already exists, use different custom id`);throw e.hash={text:`merge ${n} ${r} ${i} ${a?.join(` `)}`,token:`merge ${n} ${r} ${i} ${a?.join(` `)}`,expected:[`merge ${n} ${r}_UNIQUE ${i} ${a?.join(` `)}`]},e}let f=c||``,p={id:r||`${C.records.seq}-${w()}`,message:`merged branch ${n} into ${C.records.currBranch}`,seq:C.records.seq++,parents:C.records.head==null?[]:[C.records.head.id,f],branch:C.records.currBranch,type:x.MERGE,customType:i,customId:!!r,tags:a??[]};C.records.head=p,C.records.commits.set(p.id,p),C.records.branches.set(C.records.currBranch,p.id),t.debug(C.records.branches),t.debug(`in mergeBranch`)},`merge`),se=e(function(e){let n=e.id,r=e.targetId,i=e.tags,a=e.parent;t.debug(`Entering cherryPick:`,n,r,i);let o=S();if(n=u.sanitizeText(n,o),r=u.sanitizeText(r,o),i=i?.map(e=>u.sanitizeText(e,o)),a=u.sanitizeText(a,o),!n||!C.records.commits.has(n)){let e=Error(`Incorrect usage of "cherryPick". Source commit id should exist and provided`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let s=C.records.commits.get(n);if(s===void 0||!s)throw Error(`Incorrect usage of "cherryPick". Source commit id should exist and provided`);if(a&&!(Array.isArray(s.parents)&&s.parents.includes(a)))throw Error(`Invalid operation: The specified parent commit is not an immediate parent of the cherry-picked commit.`);let c=s.branch;if(s.type===x.MERGE&&!a)throw Error(`Incorrect usage of cherry-pick: If the source commit is a merge commit, an immediate parent commit must be specified.`);if(!r||!C.records.commits.has(r)){if(c===C.records.currBranch){let e=Error(`Incorrect usage of "cherryPick". Source commit is already on current branch`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let e=C.records.branches.get(C.records.currBranch);if(e===void 0||!e){let e=Error(`Incorrect usage of "cherry-pick". Current branch (${C.records.currBranch})has no commits`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let o=C.records.commits.get(e);if(o===void 0||!o){let e=Error(`Incorrect usage of "cherry-pick". Current branch (${C.records.currBranch})has no commits`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let l={id:C.records.seq+`-`+w(),message:`cherry-picked ${s?.message} into ${C.records.currBranch}`,seq:C.records.seq++,parents:C.records.head==null?[]:[C.records.head.id,s.id],branch:C.records.currBranch,type:x.CHERRY_PICK,tags:i?i.filter(Boolean):[`cherry-pick:${s.id}${s.type===x.MERGE?`|parent:${a}`:``}`]};C.records.head=l,C.records.commits.set(l.id,l),C.records.branches.set(C.records.currBranch,l.id),t.debug(C.records.branches),t.debug(`in cherryPick`)}},`cherryPick`),E=e(function(e){if(e=u.sanitizeText(e,S()),C.records.branches.has(e)){C.records.currBranch=e;let t=C.records.branches.get(C.records.currBranch);t===void 0||!t?C.records.head=null:C.records.head=C.records.commits.get(t)??null}else{let t=Error(`Trying to checkout branch which is not yet created. (Help try using "branch ${e}")`);throw t.hash={text:`checkout ${e}`,token:`checkout ${e}`,expected:[`branch ${e}`]},t}},`checkout`);function D(e,t,n){let r=e.indexOf(t);r===-1?e.push(n):e.splice(r,1,n)}e(D,`upsert`);function O(e){let n=e.reduce((e,t)=>e.seq>t.seq?e:t,e[0]),r=``;e.forEach(function(e){e===n?r+=` *`:r+=` |`});let i=[r,n.id,n.seq];for(let e in C.records.branches)C.records.branches.get(e)===n.id&&i.push(e);if(t.debug(i.join(` `)),n.parents&&n.parents.length==2&&n.parents[0]&&n.parents[1]){let t=C.records.commits.get(n.parents[0]);D(e,n,t),n.parents[1]&&e.push(C.records.commits.get(n.parents[1]))}else if(n.parents.length==0)return;else if(n.parents[0]){let t=C.records.commits.get(n.parents[0]);D(e,n,t)}e=T(e,e=>e.id),O(e)}e(O,`prettyPrintCommitHistory`);var ce=e(function(){t.debug(C.records.commits);let e=k()[0];O([e])},`prettyPrint`),le=e(function(){C.reset(),s()},`clear`),ue=e(function(){return[...C.records.branchConfig.values()].map((e,t)=>e.order!==null&&e.order!==void 0?e:{...e,order:parseFloat(`0.${t}`)}).sort((e,t)=>(e.order??0)-(t.order??0)).map(({name:e})=>({name:e}))},`getBranchesAsObjArray`),de=e(function(){return C.records.branches},`getBranches`),fe=e(function(){return C.records.commits},`getCommits`),k=e(function(){let e=[...C.records.commits.values()];return e.forEach(function(e){t.debug(e.id)}),e.sort((e,t)=>e.seq-t.seq),e},`getCommitsArray`),A={commitType:x,getConfig:S,setDirection:te,setOptions:ne,getOptions:re,commit:ie,branch:ae,merge:oe,cherryPick:se,checkout:E,prettyPrint:ce,clear:le,getBranchesAsObjArray:ue,getBranches:de,getCommits:fe,getCommitsArray:k,getCurrentBranch:e(function(){return C.records.currBranch},`getCurrentBranch`),getDirection:e(function(){return C.records.direction},`getDirection`),getHead:e(function(){return C.records.head},`getHead`),setAccTitle:a,getAccTitle:m,getAccDescription:d,setAccDescription:r,setDiagramTitle:i,getDiagramTitle:f},pe=e((e,t)=>{v(e,t),e.dir&&t.setDirection(e.dir);for(let n of e.statements)me(n,t)},`populate`),me=e((n,r)=>{let i={Commit:e(e=>r.commit(he(e)),`Commit`),Branch:e(e=>r.branch(ge(e)),`Branch`),Merge:e(e=>r.merge(_e(e)),`Merge`),Checkout:e(e=>r.checkout(ve(e)),`Checkout`),CherryPicking:e(e=>r.cherryPick(ye(e)),`CherryPicking`)}[n.$type];i?i(n):t.error(`Unknown statement type: ${n.$type}`)},`parseStatement`),he=e(e=>({id:e.id,msg:e.message??``,type:e.type===void 0?x.NORMAL:x[e.type],tags:e.tags??void 0}),`parseCommit`),ge=e(e=>({name:e.name,order:e.order??0}),`parseBranch`),_e=e(e=>({branch:e.branch,id:e.id??``,type:e.type===void 0?void 0:x[e.type],tags:e.tags??void 0}),`parseMerge`),ve=e(e=>e.branch,`parseCheckout`),ye=e(e=>({id:e.id,targetId:``,tags:e.tags?.length===0?void 0:e.tags,parent:e.parent}),`parseCherryPicking`),be={parse:e(async e=>{let n=await y(`gitGraph`,e);t.debug(n),pe(n,A)},`parse`)},j=10,M=40,N=4,P=2,F=8,I=new Set([`redux`,`redux-dark`,`redux-color`,`redux-dark-color`]),L=12,R=new Set([`redux-color`,`redux-dark-color`]),xe=new Set([`dark`,`redux-dark`,`redux-dark-color`,`neo-dark`]),z=e((e,t,n=!1)=>n&&e>0?(e-1)%(t-1)+1:e%t,`calcColorIndex`),B=new Map,V=new Map,H=30,U=new Map,W=[],G=0,K=`LR`,q=e(()=>{B.clear(),V.clear(),U.clear(),G=0,W=[],K=`LR`},`clear`),J=e(e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);return(typeof e==`string`?e.split(/\\n|\n|/gi):e).forEach(e=>{let n=document.createElementNS(`http://www.w3.org/2000/svg`,`tspan`);n.setAttributeNS(`http://www.w3.org/XML/1998/namespace`,`xml:space`,`preserve`),n.setAttribute(`dy`,`1em`),n.setAttribute(`x`,`0`),n.setAttribute(`class`,`row`),n.textContent=e.trim(),t.appendChild(n)}),t},`drawText`),Y=e(t=>{let n,r,i;return K===`BT`?(r=e((e,t)=>e<=t,`comparisonFunc`),i=1/0):(r=e((e,t)=>e>=t,`comparisonFunc`),i=0),t.forEach(e=>{let t=K===`TB`||K==`BT`?V.get(e)?.y:V.get(e)?.x;t!==void 0&&r(t,i)&&(n=e,i=t)}),n},`findClosestParent`),Se=e(e=>{let t=``,n=1/0;return e.forEach(e=>{let r=V.get(e).y;r<=n&&(t=e,n=r)}),t||void 0},`findClosestParentBT`),Ce=e((e,t,n)=>{let r=n,i=n,a=[];e.forEach(e=>{let n=t.get(e);if(!n)throw Error(`Commit not found for key ${e}`);n.parents.length?(r=Te(n),i=Math.max(r,i)):a.push(n),Ee(n,r)}),r=i,a.forEach(e=>{De(e,r,n)}),e.forEach(e=>{let n=t.get(e);if(n?.parents.length){let e=Se(n.parents);r=V.get(e).y-M,r<=i&&(i=r);let t=B.get(n.branch).pos,a=r-j;V.set(n.id,{x:t,y:a})}})},`setParallelBTPos`),we=e(e=>{let t=Y(e.parents.filter(e=>e!==null));if(!t)throw Error(`Closest parent not found for commit ${e.id}`);let n=V.get(t)?.y;if(n===void 0)throw Error(`Closest parent position not found for commit ${e.id}`);return n},`findClosestParentPos`),Te=e(e=>we(e)+M,`calculateCommitPosition`),Ee=e((e,t)=>{let n=B.get(e.branch);if(!n)throw Error(`Branch not found for commit ${e.id}`);let r=n.pos,i=t+j;return V.set(e.id,{x:r,y:i}),{x:r,y:i}},`setCommitPosition`),De=e((e,t,n)=>{let r=B.get(e.branch);if(!r)throw Error(`Branch not found for commit ${e.id}`);let i=t+n,a=r.pos;V.set(e.id,{x:a,y:i})},`setRootPosition`),Oe=e((e,t,n,r,i,a)=>{let{theme:o}=p(),s=I.has(o??``),c=R.has(o??``),l=xe.has(o??``);if(a===x.HIGHLIGHT)e.append(`rect`).attr(`x`,n.x-10+(s?3:0)).attr(`y`,n.y-10+(s?3:0)).attr(`width`,s?14:20).attr(`height`,s?14:20).attr(`class`,`commit ${t.id} commit-highlight${z(i,F,c)} ${r}-outer`),e.append(`rect`).attr(`x`,n.x-6+(s?2:0)).attr(`y`,n.y-6+(s?2:0)).attr(`width`,s?8:12).attr(`height`,s?8:12).attr(`class`,`commit ${t.id} commit${z(i,F,c)} ${r}-inner`);else if(a===x.CHERRY_PICK)e.append(`circle`).attr(`cx`,n.x).attr(`cy`,n.y).attr(`r`,s?7:10).attr(`class`,`commit ${t.id} ${r}`),e.append(`circle`).attr(`cx`,n.x-3).attr(`cy`,n.y+2).attr(`r`,s?2.5:2.75).attr(`fill`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`),e.append(`circle`).attr(`cx`,n.x+3).attr(`cy`,n.y+2).attr(`r`,s?2.5:2.75).attr(`fill`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`),e.append(`line`).attr(`x1`,n.x+3).attr(`y1`,n.y+1).attr(`x2`,n.x).attr(`y2`,n.y-5).attr(`stroke`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`),e.append(`line`).attr(`x1`,n.x-3).attr(`y1`,n.y+1).attr(`x2`,n.x).attr(`y2`,n.y-5).attr(`stroke`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`);else{let o=e.append(`circle`);if(o.attr(`cx`,n.x),o.attr(`cy`,n.y),o.attr(`r`,s?7:10),o.attr(`class`,`commit ${t.id} commit${z(i,F,c)}`),a===x.MERGE){let a=e.append(`circle`);a.attr(`cx`,n.x),a.attr(`cy`,n.y),a.attr(`r`,s?5:6),a.attr(`class`,`commit ${r} ${t.id} commit${z(i,F,c)}`)}if(a===x.REVERSE){let a=e.append(`path`),o=s?4:5;a.attr(`d`,`M ${n.x-o},${n.y-o}L${n.x+o},${n.y+o}M${n.x-o},${n.y+o}L${n.x+o},${n.y-o}`).attr(`class`,`commit ${r} ${t.id} commit${z(i,F,c)}`)}}},`drawCommitBullet`),ke=e((e,t,n,r,i)=>{if(t.type!==x.CHERRY_PICK&&(t.customId&&t.type===x.MERGE||t.type!==x.MERGE)&&i.showCommitLabel){let a=e.append(`g`),o=a.insert(`rect`).attr(`class`,`commit-label-bkg`),s=a.append(`text`).attr(`x`,r).attr(`y`,n.y+25).attr(`class`,`commit-label`).text(t.id),c=s.node()?.getBBox();if(c&&(o.attr(`x`,n.posWithOffset-c.width/2-P).attr(`y`,n.y+13.5).attr(`width`,c.width+2*P).attr(`height`,c.height+2*P),K===`TB`||K===`BT`?(o.attr(`x`,n.x-(c.width+4*N+5)).attr(`y`,n.y-12),s.attr(`x`,n.x-(c.width+4*N)).attr(`y`,n.y+c.height-12)):s.attr(`x`,n.posWithOffset-c.width/2),i.rotateCommitLabel))if(K===`TB`||K===`BT`)s.attr(`transform`,`rotate(-45, `+n.x+`, `+n.y+`)`),o.attr(`transform`,`rotate(-45, `+n.x+`, `+n.y+`)`);else{let e=-7.5-(c.width+10)/25*9.5,t=10+c.width/25*8.5;a.attr(`transform`,`translate(`+e+`, `+t+`) rotate(-45, `+r+`, `+n.y+`)`)}}},`drawCommitLabel`),Ae=e((e,t,n,r)=>{if(t.tags.length>0){let i=0,a=0,o=0,s=[];for(let r of t.tags.reverse()){let t=e.insert(`polygon`),c=e.append(`circle`),l=e.append(`text`).attr(`y`,n.y-16-i).attr(`class`,`tag-label`).text(r),u=l.node()?.getBBox();if(!u)throw Error(`Tag bbox not found`);a=Math.max(a,u.width),o=Math.max(o,u.height),l.attr(`x`,n.posWithOffset-u.width/2),s.push({tag:l,hole:c,rect:t,yOffset:i}),i+=20}for(let{tag:e,hole:t,rect:i,yOffset:c}of s){let s=o/2,l=n.y-19.2-c;if(i.attr(`class`,`tag-label-bkg`).attr(`points`,` ${r-a/2-N/2},${l+P} ${r-a/2-N/2},${l-P} ${n.posWithOffset-a/2-N},${l-s-P} diff --git a/.vercel/output/static/assets/index-CXgd9jpl.js b/.vercel/output/static/assets/index-CXgd9jpl.js new file mode 100644 index 0000000..6fa379b --- /dev/null +++ b/.vercel/output/static/assets/index-CXgd9jpl.js @@ -0,0 +1,22 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/routes-BDn33g5C.js","assets/rolldown-runtime-aKtaBQYM.js","assets/react-BLJmJXjR.js","assets/utils-BTuSbA5p.js","assets/client-CwgDvMJw.js","assets/input-mze7gZ5r.js","assets/login-xkhUej_P.js"])))=>i.map(i=>d[i]); +import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{t as n}from"./react-BLJmJXjR.js";import{A as r,B as i,C as a,D as o,E as s,F as c,G as l,H as u,I as d,L as f,M as p,N as m,O as h,P as g,R as _,S as v,T as y,U as b,V as x,W as S,_ as C,a as w,b as ee,c as te,d as ne,f as re,g as ie,h as ae,i as oe,j as se,k as ce,l as le,m as E,n as D,o as ue,p as de,s as fe,u as pe,v as me,w as O,x as he,y as ge,z as _e}from"./utils-BTuSbA5p.js";var ve=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,re());else{var t=n(l);t!==null&&oe(x,t.startTime-e)}}var S=!1,C=-1,w=5,ee=-1;function te(){return g?!0:!(e.unstable_now()-eet&&te());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&oe(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?re():S=!1}}}var re;if(typeof y==`function`)re=function(){y(ne)};else if(typeof MessageChannel<`u`){var ie=new MessageChannel,ae=ie.port2;ie.port1.onmessage=ne,re=function(){ae.postMessage(null)}}else re=function(){_(ne,0)};function oe(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,oe(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,re()))),r},e.unstable_shouldYield=te,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),ye=t(((e,t)=>{t.exports=ve()})),be=t((e=>{var t=ye(),r=n(),i=l();function a(e){var t=`https://react.dev/errors/`+e;if(1fe||(e.current=de[fe],de[fe]=null,fe--)}function O(e,t){fe++,de[fe]=e.current,e.current=t}var he=pe(null),ge=pe(null),_e=pe(null),ve=pe(null);function be(e,t){switch(O(_e,t),O(ge,e),O(he,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Hd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Hd(t),e=Ud(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}me(he),O(he,e)}function xe(){me(he),me(ge),me(_e)}function Se(e){e.memoizedState!==null&&O(ve,e);var t=he.current,n=Ud(t,e.type);t!==n&&(O(ge,e),O(he,n))}function Ce(e){ge.current===e&&(me(he),me(ge)),ve.current===e&&(me(ve),$f._currentValue=ue)}var we,Te;function Ee(e){if(we===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);we=t&&t[1]||``,Te=-1)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{De=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ee(n):``}function ke(e,t){switch(e.tag){case 26:case 27:case 5:return Ee(e.type);case 16:return Ee(`Lazy`);case 13:return e.child!==t&&t!==null?Ee(`Suspense Fallback`):Ee(`Suspense`);case 19:return Ee(`SuspenseList`);case 0:case 15:return Oe(e.type,!1);case 11:return Oe(e.type.render,!1);case 1:return Oe(e.type,!0);case 31:return Ee(`Activity`);default:return``}}function Ae(e){try{var t=``,n=null;do t+=ke(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var je=Object.prototype.hasOwnProperty,Me=t.unstable_scheduleCallback,Ne=t.unstable_cancelCallback,Pe=t.unstable_shouldYield,Fe=t.unstable_requestPaint,Ie=t.unstable_now,Le=t.unstable_getCurrentPriorityLevel,Re=t.unstable_ImmediatePriority,ze=t.unstable_UserBlockingPriority,Be=t.unstable_NormalPriority,Ve=t.unstable_LowPriority,He=t.unstable_IdlePriority,Ue=t.log,We=t.unstable_setDisableYieldValue,Ge=null,Ke=null;function qe(e){if(typeof Ue==`function`&&We(e),Ke&&typeof Ke.setStrictMode==`function`)try{Ke.setStrictMode(Ge,e)}catch{}}var Je=Math.clz32?Math.clz32:Ze,Ye=Math.log,Xe=Math.LN2;function Ze(e){return e>>>=0,e===0?32:31-(Ye(e)/Xe|0)|0}var Qe=256,$e=262144,et=4194304;function tt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function nt(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=tt(n))):i=tt(o):i=tt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=tt(n))):i=tt(o)):i=tt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function rt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function it(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function at(){var e=et;return et<<=1,!(et&62914560)&&(et=4194304),e}function ot(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function st(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function ct(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),xn=!1;if(bn)try{var Sn={};Object.defineProperty(Sn,"passive",{get:function(){xn=!0}}),window.addEventListener(`test`,Sn,Sn),window.removeEventListener(`test`,Sn,Sn)}catch{xn=!1}var Cn=null,wn=null,Tn=null;function k(){if(Tn)return Tn;var e,t=wn,n=t.length,r,i=`value`in Cn?Cn.value:Cn.textContent,a=i.length;for(e=0;e=nr),ar=` `,or=!1;function sr(e,t){switch(e){case`keyup`:return er.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function cr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var lr=!1;function ur(e,t){switch(e){case`compositionend`:return cr(t);case`keypress`:return t.which===32?(or=!0,ar):null;case`textInput`:return e=t.data,e===ar&&or?null:e;default:return null}}function dr(e,t){if(lr)return e===`compositionend`||!tr&&sr(e,t)?(e=k(),Tn=wn=Cn=null,lr=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Nr(n)}}function Fr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Fr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ir(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=qt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=qt(e.document)}return t}function Lr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Rr=bn&&`documentMode`in document&&11>=document.documentMode,zr=null,Br=null,Vr=null,Hr=!1;function Ur(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Hr||zr==null||zr!==qt(r)||(r=zr,`selectionStart`in r&&Lr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Vr&&Mr(Vr,r)||(Vr=r,r=Dd(Br,`onSelect`),0>=o,i-=o,Fi=1<<32-Je(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),N&&Li(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),N&&Li(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return N&&Li(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),N&&Li(i,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===v&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case g:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===v){if(r.tag===7){n(e,r.sibling),c=i(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===ne&&Pa(l)===r.type){n(e,r.sibling),c=i(r,o.props),Ba(c,o),c.return=e,e=c;break a}n(e,r);break}else t(e,r);r=r.sibling}o.type===v?(c=Si(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=xi(o.type,o.key,o.props,null,e.mode,c),Ba(c,o),c.return=e,e=c)}return s(e);case _:a:{for(l=o.key;r!==null;){if(r.key===l)if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=i(r,o.children||[]),c.return=e,e=c;break a}else{n(e,r);break}else t(e,r);r=r.sibling}c=Ti(o,e.mode,c),c.return=e,e=c}return s(e);case ne:return o=Pa(o),b(e,r,o,c)}if(le(o))return h(e,r,o,c);if(oe(o)){if(l=oe(o),typeof l!=`function`)throw Error(a(150));return o=l.call(o),y(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,za(o),c);if(o.$$typeof===S)return b(e,r,ca(e,o),c);Va(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=i(r,o),c.return=e,e=c):(n(e,r),c=Ci(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Ra=0;var i=b(e,t,n,r);return La=null,i}catch(t){if(t===Oa||t===Aa)throw t;var a=_i(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Ua=Ha(!0),Wa=Ha(!1),Ga=!1;function Ka(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function qa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ja(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ya(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,K&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=mi(e),pi(e,null,n),t}return ui(e,r,t,n),mi(e)}function Xa(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ut(e,n)}}function Za(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Qa=!1;function $a(){if(Qa){var e=ya;if(e!==null)throw e}}function eo(e,t,n,r){Qa=!1;var i=e.updateQueue;Ga=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(Y&f)===f:(r&f)===f){f!==0&&f===va&&(Qa=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,f);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,f=typeof h==`function`?h.call(_,d,f):h,f==null)break a;d=m({},d,f);break a;case 2:Ga=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Kl|=o,e.lanes=o,e.memoizedState=d}}function to(e,t){if(typeof e!=`function`)throw Error(a(191,e));e.call(t)}function no(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=E.T,s={};E.T=s,Fs(e,!1,t,n);try{var c=i(),l=E.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ps(e,t,Sa(c,r),mu(e)):Ps(e,t,r,mu(e))}catch(n){Ps(e,t,{then:function(){},status:`rejected`,reason:n},mu())}finally{D.p=a,o!==null&&s.types!==null&&(o.types=s.types),E.T=o}}function ws(){}function Ts(e,t,n,r){if(e.tag!==5)throw Error(a(476));var i=Es(e).queue;Cs(e,i,t,ue,n===null?ws:function(){return Ds(e),n(r)})}function Es(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ue,baseState:ue,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Lo,lastRenderedState:ue},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Lo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Ds(e){var t=Es(e);t.next===null&&(t=e.alternate.memoizedState),Ps(e,t.next.queue,{},mu())}function Os(){return sa($f)}function ks(){return Mo().memoizedState}function As(){return Mo().memoizedState}function js(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=mu();e=Ja(n);var r=Ya(t,e,n);r!==null&&(gu(r,t,n),Xa(r,t,n)),t={cache:ma()},e.payload=t;return}t=t.return}}function Ms(e,t,n){var r=mu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Is(e)?Ls(t,n):(n=di(e,t,n,r),n!==null&&(gu(n,e,r),Rs(n,t,r)))}function Ns(e,t,n){Ps(e,t,n,mu())}function Ps(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Is(e))Ls(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,jr(s,o))return ui(e,t,i,0),q===null&&li(),!1}catch{}if(n=di(e,t,i,r),n!==null)return gu(n,e,r),Rs(n,t,r),!0}return!1}function Fs(e,t,n,r){if(r={lane:2,revertLane:fd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Is(e)){if(t)throw Error(a(479))}else t=di(e,n,r,2),t!==null&&gu(t,e,2)}function Is(e){var t=e.alternate;return e===L||t!==null&&t===L}function Ls(e,t){yo=vo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Rs(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ut(e,n)}}var zs={readContext:sa,use:Fo,useCallback:B,useContext:B,useEffect:B,useImperativeHandle:B,useLayoutEffect:B,useInsertionEffect:B,useMemo:B,useReducer:B,useRef:B,useState:B,useDebugValue:B,useDeferredValue:B,useTransition:B,useSyncExternalStore:B,useId:B,useHostTransitionStatus:B,useFormState:B,useActionState:B,useOptimistic:B,useMemoCache:B,useCacheRefresh:B};zs.useEffectEvent=B;var Bs={readContext:sa,use:Fo,useCallback:function(e,t){return jo().memoizedState=[e,t===void 0?null:t],e},useContext:sa,useEffect:us,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),cs(4194308,4,gs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return cs(4194308,4,e,t)},useInsertionEffect:function(e,t){cs(4,2,e,t)},useMemo:function(e,t){var n=jo();t=t===void 0?null:t;var r=e();if(bo){qe(!0);try{e()}finally{qe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=jo();if(n!==void 0){var i=n(t);if(bo){qe(!0);try{n(t)}finally{qe(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Ms.bind(null,L,e),[r.memoizedState,e]},useRef:function(e){var t=jo();return e={current:e},t.memoizedState=e},useState:function(e){e=Ko(e);var t=e.queue,n=Ns.bind(null,L,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:vs,useDeferredValue:function(e,t){return xs(jo(),e,t)},useTransition:function(){var e=Ko(!1);return e=Cs.bind(null,L,e.queue,!0,!1),jo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=L,i=jo();if(N){if(n===void 0)throw Error(a(407));n=n()}else{if(n=t(),q===null)throw Error(a(349));Y&127||Vo(r,t,n)}i.memoizedState=n;var o={value:n,getSnapshot:t};return i.queue=o,us(Uo.bind(null,r,o,e),[e]),r.flags|=2048,os(9,{destroy:void 0},Ho.bind(null,r,o,n,t),null),n},useId:function(){var e=jo(),t=q.identifierPrefix;if(N){var n=Ii,r=Fi;n=(r&~(1<<32-Je(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=xo++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(i,{is:r.is}):s.createElement(i)}}o[_t]=t,o[vt]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Fd(o,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Pc(t)}}return W(t),Fc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Pc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(a(166));if(e=_e.current,Ji(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=j,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[_t]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Nd(e.nodeValue,n)),e||Gi(t,!0)}else e=Vd(e).createTextNode(r),e[_t]=t,t.stateNode=e}return W(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Ji(t),n!==null){if(e===null){if(!r)throw Error(a(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(a(557));e[_t]=t}else Yi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;W(t),e=!1}else n=Xi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(ho(t),t):(ho(t),null);if(t.flags&128)throw Error(a(558))}return W(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=Ji(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(a(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(a(317));i[_t]=t}else Yi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;W(t),i=!1}else i=Xi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(ho(t),t):(ho(t),null)}return ho(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Lc(t,t.updateQueue),W(t),null);case 4:return xe(),e===null&&Cd(t.stateNode.containerInfo),W(t),null;case 10:return P(t.type),W(t),null;case 19:if(me(I),r=t.memoizedState,r===null)return W(t),null;if(i=(t.flags&128)!=0,o=r.rendering,o===null)if(i)Rc(r,!1);else{if(Gl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=go(e),o!==null){for(t.flags|=128,Rc(r,!1),e=o.updateQueue,t.updateQueue=e,Lc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)bi(n,e),n=n.sibling;return O(I,I.current&1|2),N&&Li(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ie()>nu&&(t.flags|=128,i=!0,Rc(r,!1),t.lanes=4194304)}else{if(!i)if(e=go(o),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,Lc(t,e),Rc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!N)return W(t),null}else 2*Ie()-r.renderingStartTime>nu&&n!==536870912&&(t.flags|=128,i=!0,Rc(r,!1),t.lanes=4194304);r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(W(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ie(),e.sibling=null,n=I.current,O(I,i?n&1|2:n&1),N&&Li(t,r.treeForkCount),e);case 22:case 23:return ho(t),so(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(W(t),t.subtreeFlags&6&&(t.flags|=8192)):W(t),n=t.updateQueue,n!==null&&Lc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&me(wa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),P(pa),W(t),null;case 25:return null;case 30:return null}throw Error(a(156,t.tag))}function Bc(e,t){switch(Bi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return P(pa),xe(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Ce(t),null;case 31:if(t.memoizedState!==null){if(ho(t),t.alternate===null)throw Error(a(340));Yi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ho(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(a(340));Yi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return me(I),null;case 4:return xe(),null;case 10:return P(t.type),null;case 22:case 23:return ho(t),so(),e!==null&&me(wa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return P(pa),null;case 25:return null;default:return null}}function Vc(e,t){switch(Bi(t),t.tag){case 3:P(pa),xe();break;case 26:case 27:case 5:Ce(t);break;case 4:xe();break;case 31:t.memoizedState!==null&&ho(t);break;case 13:ho(t);break;case 19:me(I);break;case 10:P(t.type);break;case 22:case 23:ho(t),so(),e!==null&&me(wa);break;case 24:P(pa)}}function Hc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Z(t,t.return,e)}}function Uc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Z(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Z(t,t.return,e)}}function Wc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{no(t,n)}catch(t){Z(e,e.return,t)}}}function Gc(e,t,n){n.props=qs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Z(e,t,n)}}function Kc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Z(e,t,n)}}function qc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){Z(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Z(e,t,n)}else n.current=null}function Jc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Z(e,e.return,t)}}function Yc(e,t,n){try{var r=e.stateNode;Id(r,e.type,n,t),r[vt]=t}catch(t){Z(e,e.return,t)}}function Xc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Qd(e.type)||e.tag===4}function Zc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Xc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Qd(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Qc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=dn));else if(r!==4&&(r===27&&Qd(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Qc(e,t,n),e=e.sibling;e!==null;)Qc(e,t,n),e=e.sibling}function $c(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&Qd(e.type)&&(n=e.stateNode),e=e.child,e!==null))for($c(e,t,n),e=e.sibling;e!==null;)$c(e,t,n),e=e.sibling}function el(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Fd(t,r,n),t[_t]=e,t[vt]=n}catch(t){Z(e,e.return,t)}}var tl=!1,nl=!1,rl=!1,il=typeof WeakSet==`function`?WeakSet:Set,al=null;function ol(e,t){if(e=e.containerInfo,zd=cp,e=Ir(e),Lr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||i!==0&&f.nodeType!==3||(c=s+i),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===i&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Bd={focusedElem:e,selectionRange:n},cp=!1,al=t;al!==null;)if(t=al,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,al=e;else for(;al!==null;){switch(t=al,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Fd(o,r,n),o[_t]=e,At(o),r=o;break a;case`link`:var s=Hf(`link`,`href`,i).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Pr(s,h),v=Pr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,E.T=null,n=uu,uu=null;var o=ou,s=cu;if(au=0,su=ou=null,cu=0,K&6)throw Error(a(331));var c=K;if(K|=4,Fl(o.current),Dl(o,o.current,s,n),K=c,ad(0,!1),Ke&&typeof Ke.onPostCommitFiberRoot==`function`)try{Ke.onPostCommitFiberRoot(Ge,o)}catch{}return!0}finally{D.p=i,E.T=r,Hu(e,t)}}function Gu(e,t,n){t=Di(n,t),t=$s(e.stateNode,t,2),e=Ya(e,t,2),e!==null&&(st(e,2),id(e))}function Z(e,t,n){if(e.tag===3)Gu(e,e,n);else for(;t!==null;){if(t.tag===3){Gu(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(iu===null||!iu.has(r))){e=Di(n,e),n=ec(2),r=Ya(t,n,2),r!==null&&(tc(n,r,t,e),st(r,2),id(r));break}}t=t.return}}function Ku(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new zl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Ul=!0,i.add(n),e=qu.bind(null,e,t,n),t.then(e,e))}function qu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,q===e&&(Y&n)===n&&(Gl===4||Gl===3&&(Y&62914560)===Y&&300>Ie()-eu?!(K&2)&&Cu(e,0):Jl|=n,Xl===Y&&(Xl=0)),id(e)}function Ju(e,t){t===0&&(t=at()),e=fi(e,t),e!==null&&(st(e,t),id(e))}function Yu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ju(e,n)}function Xu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(a(314))}r!==null&&r.delete(t),Ju(e,n)}function Zu(e,t){return Me(e,t)}var Qu=null,$u=null,ed=!1,td=!1,nd=!1,rd=0;function id(e){e!==$u&&e.next===null&&($u===null?Qu=$u=e:$u=$u.next=e),td=!0,ed||(ed=!0,dd())}function ad(e,t){if(!nd&&td){nd=!0;do for(var n=!1,r=Qu;r!==null;){if(!t)if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Je(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,ud(r,a))}else a=Y,a=nt(r,r===q?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||rt(r,a)||(n=!0,ud(r,a));r=r.next}while(n);nd=!1}}function od(){sd()}function sd(){td=ed=!1;var e=0;rd!==0&&Kd()&&(e=rd);for(var t=Ie(),n=null,r=Qu;r!==null;){var i=r.next,a=cd(r,t);a===0?(r.next=null,n===null?Qu=i:n.next=i,i===null&&($u=n)):(n=r,(e!==0||a&3)&&(td=!0)),r=i}au!==0&&au!==5||ad(e,!1),rd!==0&&(rd=0)}function cd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Ld(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Sf(e,t,n){var r=xf;if(r&&typeof t==`string`&&t){var i=Yt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),gf.has(i)||(gf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Fd(t,`link`,e),At(t),r.head.appendChild(t)))}}function Cf(e){vf.D(e),Sf(`dns-prefetch`,e,null)}function wf(e,t){vf.C(e,t),Sf(`preconnect`,e,t)}function Tf(e,t,n){vf.L(e,t,n);var r=xf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Yt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Yt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Yt(n.imageSizes)+`"]`)):i+=`[href="`+Yt(e)+`"]`;var a=i;switch(t){case`style`:a=jf(e);break;case`script`:a=Ff(e)}hf.has(a)||(e=m({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),hf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Mf(a))||t===`script`&&r.querySelector(If(a))||(t=r.createElement(`link`),Fd(t,`link`,e),At(t),r.head.appendChild(t)))}}function Ef(e,t){vf.m(e,t);var n=xf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Yt(r)+`"][href="`+Yt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Ff(e)}if(!hf.has(a)&&(e=m({rel:`modulepreload`,href:e},t),hf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(If(a)))return}r=n.createElement(`link`),Fd(r,`link`,e),At(r),n.head.appendChild(r)}}}function Df(e,t,n){vf.S(e,t,n);var r=xf;if(r&&e){var i=kt(r).hoistableStyles,a=jf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Mf(a)))s.loading=5;else{e=m({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=hf.get(a))&&zf(e,n);var c=o=r.createElement(`link`);At(c),Fd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Rf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Of(e,t){vf.X(e,t);var n=xf;if(n&&e){var r=kt(n).hoistableScripts,i=Ff(e),a=r.get(i);a||(a=n.querySelector(If(i)),a||(e=m({src:e,async:!0},t),(t=hf.get(i))&&Bf(e,t),a=n.createElement(`script`),At(a),Fd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function kf(e,t){vf.M(e,t);var n=xf;if(n&&e){var r=kt(n).hoistableScripts,i=Ff(e),a=r.get(i);a||(a=n.querySelector(If(i)),a||(e=m({src:e,async:!0,type:`module`},t),(t=hf.get(i))&&Bf(e,t),a=n.createElement(`script`),At(a),Fd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Af(e,t,n,r){var i=(i=_e.current)?_f(i):null;if(!i)throw Error(a(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=jf(n.href),n=kt(i).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=jf(n.href);var o=kt(i).hoistableStyles,s=o.get(e);if(s||(i=i.ownerDocument||i,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=i.querySelector(Mf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),hf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},hf.set(e,n),o||Pf(i,e,n,s.state))),t&&r===null)throw Error(a(528,``));return s}if(t&&r!==null)throw Error(a(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Ff(n),n=kt(i).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(a(444,e))}}function jf(e){return`href="`+Yt(e)+`"`}function Mf(e){return`link[rel="stylesheet"][`+e+`]`}function Nf(e){return m({},e,{"data-precedence":e.precedence,precedence:null})}function Pf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Fd(t,`link`,n),At(t),e.head.appendChild(t))}function Ff(e){return`[src="`+Yt(e)+`"]`}function If(e){return`script[async]`+e}function Lf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Yt(n.href)+`"]`);if(r)return t.instance=r,At(r),r;var i=m({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),At(r),Fd(r,`style`,i),Rf(r,n.precedence,e),t.instance=r;case`stylesheet`:i=jf(n.href);var o=e.querySelector(Mf(i));if(o)return t.state.loading|=4,t.instance=o,At(o),o;r=Nf(n),(i=hf.get(i))&&zf(r,i),o=(e.ownerDocument||e).createElement(`link`),At(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Fd(o,`link`,r),t.state.loading|=4,Rf(o,n.precedence,e),t.instance=o;case`script`:return o=Ff(n.src),(i=e.querySelector(If(o)))?(t.instance=i,At(i),i):(r=n,(i=hf.get(o))&&(r=m({},n),Bf(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),At(i),Fd(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(a(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Rf(r,n.precedence,e));return t.instance}function Rf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Wf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Gf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Kf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=jf(r.href),a=t.querySelector(Mf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Yf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,At(a);return}a=t.ownerDocument||t,r=Nf(r),(i=hf.get(i))&&zf(r,i),a=a.createElement(`link`),At(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Fd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Yf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var qf=0;function Jf(e,t){return e.stylesheets&&e.count===0&&Zf(e,e.stylesheets),0qf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Yf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Zf(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Xf=null;function Zf(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Xf=new Map,t.forEach(Qf,e),Xf=null,Yf.call(e))}function Qf(e,t){if(!(t.state.loading&4)){var n=Xf.get(e);if(n)var r=n.get(null);else{n=new Map,Xf.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=be()})),Se=`__TSS_CONTEXT`,Ce=Symbol.for(`TSS_SERVER_FUNCTION`),we=Symbol.for(`TSS_SERVER_FUNCTION_FACTORY`),Te=`application/x-tss-framed`,Ee={JSON:0,CHUNK:1,END:2,ERROR:3};`${Te}`;var De=/;\s*v=(\d+)/;function Oe(e){let t=e.match(De);return t?parseInt(t[1],10):void 0}function ke(e){let t=Oe(e);if(t!==void 0&&t!==1)throw Error(`Incompatible framed protocol version: server=${t}, client=1. Please ensure client and server are using compatible versions.`)}var Ae=()=>window.__TSS_START_OPTIONS__;function je(e){return e?.isNotFound===!0}function Me(){try{return sessionStorage}catch{return}}var Ne=`tsr-scroll-restoration-v1_3`,Pe=Me();function Fe(){try{return JSON.parse(Pe?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function Ie(){try{Pe?.setItem(Ne,JSON.stringify(Le))}catch{}}var Le=Fe(),Re=`data-scroll-restoration-id`,ze=e=>e.state.__TSR_key||e.href;function Be(e){let t=e.getAttribute(Re);if(t)return`[${Re}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var Ve=!1,He=`window`;function Ue(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function We(e){let t=new Set;for(let n of e){if(n===He)continue;let e=Ue(n);e&&t.add(e)}return t}function Ge(e,t){let n=t??e.options.scrollRestoration,r=e._scroll;n&&(r.restoring=!0);let i=e.options.getScrollRestorationKey||ze,a=new Set,o=e=>{let t=Le[e]||={};for(let e of a)e===document?t[He]={scrollX,scrollY}:e.isConnected&&(t[Be(e)]={scrollX:e.scrollLeft,scrollY:e.scrollTop})};n&&!r.restoration&&(r.restoration=!0,Ve=!1,history.scrollRestoration=`manual`,document.addEventListener(`scroll`,e=>{Ve||a.add(e.target)},!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(i(e.fromLocation)),a.clear()}),addEventListener(`pagehide`,()=>{o(i(e.stores.resolvedLocation.get()??e.stores.location.get())),Ie()})),!r.reset&&(r.reset=!0,e.subscribe(`onRendered`,t=>{let n=e.options.scrollRestorationBehavior,o=e.options.scrollToTopSelectors,s=r.next,c=r.hash,l;if(a.clear(),r.next=!0,r.hash=!1,typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let u=i(t.toLocation),d=t.fromLocation&&i(t.fromLocation);if(r.restoring&&d&&d!==u){let e=Le[d];if(e){let t=Le[u];for(let n in e){if(n===He){if(s)continue}else{let e=Ue(n);if(!e||s&&o&&(l??=We(o),l.has(e)))continue}t||=Le[u]={},t[n]??=e[n]}}}Ve=!0;try{let e=t.toLocation.hash,i=t.toLocation.state.__hashScrollIntoViewOptions??!0,a=!1;if(s){!e&&o&&(l??=We(o));let t=e&&i&&c,s=r.restoring?Le[u]:void 0;if(s)for(let e in s){let{scrollX:r,scrollY:i}=s[e];if(e===He){if(t)continue;scrollTo({top:i,left:r,behavior:n}),a=!0}else{let t=Ue(e);t&&(t.scrollLeft=r,t.scrollTop=i,l?.delete(t))}}if(!e){let e={top:0,left:0,behavior:n};if(a||scrollTo(e),l)for(let t of l)t.scrollTo(e)}}!a&&e&&i&&document.getElementById(e)?.scrollIntoView(i)}finally{Ve=!1}}))}function Ke(e,t=String){let n=new URLSearchParams;for(let r in e){let i=e[r];i!==void 0&&n.set(r,t(i))}return n.toString()}function qe(e){return e?e===`false`?!1:e===`true`?!0:e*0==0&&+e+``===e?+e:e:``}function Je(e){let t=new URLSearchParams(e),n=Object.create(null);for(let[e,r]of t.entries()){let t=n[e];t==null?n[e]=qe(r):Array.isArray(t)?t.push(qe(r)):n[e]=[t,qe(r)]}return n}var Ye=Ze(JSON.parse),Xe=Qe(JSON.stringify,JSON.parse);function Ze(e){return t=>{t[0]===`?`&&(t=t.substring(1));let n=Je(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function Qe(e,t){let n=typeof t==`function`;function r(r){if(typeof r==`object`&&r)try{return e(r)}catch{}else if(n&&typeof r==`string`)try{return t(r),e(r)}catch{}return r}return e=>{let t=Ke(e,r);return t?`?${t}`:``}}var $e=`__root__`;function et(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function tt(e){return e instanceof Response&&!!e.options}function nt(e){if(typeof e==`object`&&e&&e.isSerializedRedirect)return et(e)}function rt(e){return{input:({url:t})=>{for(let n of e)t=at(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=ot(e[n],t);return t}}}function it(e){let t=ge(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=C([`/`,t,e.pathname]),e)}}function at(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function ot(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function st(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i,init:a}=t,o=new Map,s=new Map,c=new Map,l=n(e.status),u=n(e.loadedAt),d=n(e.isLoading),f=n(e.isTransitioning),p=n(e.location),m=n(e.resolvedLocation),g=n(e.statusCode),_=n(e.redirect),v=n([]),y=n([]),b=n([]),x=r(()=>ct(o,v.get())),S=r(()=>ct(s,y.get())),C=r(()=>ct(c,b.get())),w=r(()=>v.get()[0]),ee=r(()=>v.get().some(e=>o.get(e)?.get().status===`pending`)),te=r(()=>({locationHref:p.get().href,resolvedLocationHref:m.get()?.href,status:l.get()})),ne=r(()=>({status:l.get(),loadedAt:u.get(),isLoading:d.get(),isTransitioning:f.get(),matches:x.get(),location:p.get(),resolvedLocation:m.get(),statusCode:g.get(),redirect:_.get()})),re=h(64);function ie(e){let t=re.get(e);return t||(t=r(()=>{let t=v.get();for(let n of t){let t=o.get(n);if(t&&t.routeId===e)return t.get()}}),re.set(e,t)),t}let ae={status:l,loadedAt:u,isLoading:d,isTransitioning:f,location:p,resolvedLocation:m,statusCode:g,redirect:_,matchesId:v,pendingIds:y,cachedIds:b,matches:x,pendingMatches:S,cachedMatches:C,firstId:w,hasPending:ee,matchRouteDeps:te,matchStores:o,pendingMatchStores:s,cachedMatchStores:c,__store:ne,getRouteMatchStore:ie,setMatches:oe,setPending:se,setCached:ce};oe(e.matches),a?.(ae);function oe(e){lt(e,o,v,n,i)}function se(e){lt(e,s,y,n,i)}function ce(e){lt(e,c,b,n,i)}return ae}function ct(e,t){let n=[];for(let r of t){let t=e.get(r);t&&n.push(t.get())}return n}function lt(e,t,n,r,i){let a=e.map(e=>e.id),o=new Set(a);i(()=>{for(let e of t.keys())o.has(e)||t.delete(e);for(let n of e){let e=t.get(n.id);if(!e){let e=r(n);e.routeId=n.routeId,t.set(n.id,e);continue}e.routeId=n.routeId,e.get()!==n&&e.set(n)}se(n.get(),a)||n.set(a)})}var ut=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},dt=e=>e.stores.matchesId.get().some(t=>e.stores.matchStores.get(t)?.get()._forcePending),ft=(e,t)=>!!(e.preload&&!e.router.stores.matchStores.has(t)),pt=(e,t,n=!0)=>{let r={...e.router.options.context??{}},i=n?t:t-1;for(let t=0;t<=i;t++){let n=e.matches[t];if(!n)continue;let i=e.router.getMatch(n.id);i&&Object.assign(r,i.__routeContext,i.__beforeLoadContext)}return r},mt=(e,t)=>{if(!e.matches.length)return;let n=t.routeId,r=e.matches.findIndex(t=>t.routeId===e.router.routeTree.id),i=r>=0?r:0,a=n?e.matches.findIndex(e=>e.routeId===n):e.firstBadMatchIndex??e.matches.length-1;a<0&&(a=i);for(let t=a;t>=0;t--){let n=e.matches[t];if(e.router.looseRoutesById[n.routeId].options.notFoundComponent)return t}return n?a:i},ht=(e,t,n)=>{if(!(!tt(n)&&!je(n)))throw tt(n)&&n.redirectHandled&&!n.options.reloadDocument?n:(t&&(t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0,t._nonReactive.error=n,e.updateMatch(t.id,r=>({...r,status:tt(n)?`redirected`:je(n)?`notFound`:r.status===`pending`?`success`:r.status,context:pt(e,t.index),isFetching:!1,error:n})),je(n)&&!n.routeId&&(n.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()),tt(n)&&(e.rendered=!0,n.options._fromLocation=e.location,n.redirectHandled=!0,n=e.router.resolveRedirect(n)),n)},gt=(e,t)=>{let n=e.router.getMatch(t);return!!(!n||n._nonReactive.dehydrated)},_t=(e,t,n)=>{let r=pt(e,n);e.updateMatch(t,e=>({...e,context:r}))},vt=(e,t,n)=>{let{id:r,routeId:i}=e.matches[t],a=e.router.looseRoutesById[i];if(n instanceof Promise)throw n;e.firstBadMatchIndex??=t,ht(e,e.router.getMatch(r),n);try{a.options.onError?.(n)}catch(t){n=t,ht(e,e.router.getMatch(r),n)}e.updateMatch(r,e=>(e._nonReactive.beforeLoadPromise?.resolve(),e._nonReactive.beforeLoadPromise=void 0,e._nonReactive.loadPromise?.resolve(),{...e,error:n,status:`error`,isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!tt(n)&&!je(n)&&(e.serialError??=n)},yt=(e,t,n,r)=>{if(r._nonReactive.pendingTimeout!==void 0)return;let i=n.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!ft(e,t)&&(n.options.loader||n.options.beforeLoad||At(n))&&typeof i==`number`&&i!==1/0&&(n.options.pendingComponent??e.router.options?.defaultPendingComponent)){let t=setTimeout(()=>{ut(e)},i);r._nonReactive.pendingTimeout=t}},bt=(e,t,n)=>{let r=e.router.getMatch(t);if(!r._nonReactive.beforeLoadPromise&&!r._nonReactive.loaderPromise)return;yt(e,t,n,r);let i=()=>{let n=e.router.getMatch(t);n.preload&&(n.status===`redirected`||n.status===`notFound`)&&ht(e,n,n.error)};return r._nonReactive.beforeLoadPromise?r._nonReactive.beforeLoadPromise.then(i):i()},xt=(e,t,n,r)=>{let i=e.router.getMatch(t),a=i._nonReactive.loadPromise;i._nonReactive.loadPromise=p(()=>{a?.resolve(),a=void 0});let{paramsError:o,searchError:s}=i;o&&vt(e,n,o),s&&vt(e,n,s),yt(e,t,r,i);let c=new AbortController,l=!1,u=()=>{l||(l=!0,e.updateMatch(t,e=>({...e,isFetching:`beforeLoad`,fetchCount:e.fetchCount+1,abortController:c})))},d=()=>{i._nonReactive.beforeLoadPromise?.resolve(),i._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,e=>({...e,isFetching:!1}))};if(!r.options.beforeLoad){e.router.batch(()=>{u(),d()});return}i._nonReactive.beforeLoadPromise=p();let f={...pt(e,n,!1),...i.__routeContext},{search:m,params:h,cause:g}=i,_=ft(e,t),v={search:m,abortController:c,params:h,preload:_,context:f,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:_?`preload`:g,matches:e.matches,routeId:r.id,...e.router.options.additionalContext},y=r=>{if(r===void 0){e.router.batch(()=>{u(),d()});return}(tt(r)||je(r))&&(u(),vt(e,n,r)),e.router.batch(()=>{u(),e.updateMatch(t,e=>({...e,__beforeLoadContext:r})),d()})},b;try{if(b=r.options.beforeLoad(v),x(b))return u(),b.catch(t=>{vt(e,n,t)}).then(y)}catch(t){u(),vt(e,n,t)}y(b)},St=(e,t)=>{let{id:n,routeId:r}=e.matches[t],i=e.router.looseRoutesById[r],a=()=>s(),o=()=>xt(e,n,t,i),s=()=>{if(gt(e,n))return;let t=bt(e,n,i);return x(t)?t.then(o):o()};return a()},Ct=(e,t,n)=>{let r=e.router.getMatch(t);if(!r||!n.options.head&&!n.options.scripts&&!n.options.headers)return;let i={ssr:e.router.options.ssr,matches:e.matches,match:r,params:r.params,loaderData:r.loaderData};return Promise.all([n.options.head?.(i),n.options.scripts?.(i),n.options.headers?.(i)]).then(([e,t,n])=>({meta:e?.meta,links:e?.links,headScripts:e?.scripts,headers:n,scripts:t,styles:e?.styles}))},wt=(e,t,n,r,i)=>{let a=t[r-1],{params:o,loaderDeps:s,abortController:c,cause:l}=e.router.getMatch(n),u=pt(e,r),d=ft(e,n);return{params:o,deps:s,preload:!!d,parentMatchPromise:a,abortController:c,context:u,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),cause:d?`preload`:l,route:i,...e.router.options.additionalContext}},Tt=async(e,t,n,r,i)=>{try{let a=e.router.getMatch(n);try{kt(i);let o=i.options.loader,s=typeof o==`function`?o:o?.handler,c=s?.(wt(e,t,n,r,i)),l=!!s&&x(c);if((l||i._lazyPromise||i._componentsPromise||i.options.head||i.options.scripts||i.options.headers||a._nonReactive.minPendingPromise)&&e.updateMatch(n,e=>({...e,isFetching:`loader`})),s){let t=l?await c:c;ht(e,e.router.getMatch(n),t),t!==void 0&&e.updateMatch(n,e=>({...e,loaderData:t}))}i._lazyPromise&&await i._lazyPromise;let u=a._nonReactive.minPendingPromise;u&&await u,i._componentsPromise&&await i._componentsPromise,e.updateMatch(n,t=>({...t,error:void 0,context:pt(e,r),status:`success`,isFetching:!1,updatedAt:Date.now()}))}catch(t){let o=t;if(o?.name===`AbortError`){if(a.abortController.signal.aborted){a._nonReactive.loaderPromise?.resolve(),a._nonReactive.loaderPromise=void 0;return}e.updateMatch(n,t=>({...t,status:t.status===`pending`?`success`:t.status,isFetching:!1,context:pt(e,r)}));return}let s=a._nonReactive.minPendingPromise;s&&await s,je(t)&&await i.options.notFoundComponent?.preload?.(),ht(e,e.router.getMatch(n),t);try{i.options.onError?.(t)}catch(t){o=t,ht(e,e.router.getMatch(n),t)}!tt(o)&&!je(o)&&await kt(i,[`errorComponent`]),e.updateMatch(n,t=>({...t,error:o,context:pt(e,r),status:`error`,isFetching:!1}))}}catch(t){let r=e.router.getMatch(n);r&&(r._nonReactive.loaderPromise=void 0),ht(e,r,t)}},Et=async(e,t,n)=>{async function r(r,a,c,l,d){let f=Date.now()-a.updatedAt,p=r?d.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:d.options.staleTime??e.router.options.defaultStaleTime??0,m=d.options.shouldReload,h=typeof m==`function`?m(wt(e,t,i,n,d)):m,{status:g,invalid:_}=l,v=f>=p&&(!!e.forceStaleReload||l.cause===`enter`||c!==void 0&&c!==l.id);o=g===`success`&&(_||(h??v)),r&&d.options.preload===!1||(o&&!e.sync&&u?(s=!0,(async()=>{try{await Tt(e,t,i,n,d);let r=e.router.getMatch(i);r._nonReactive.loaderPromise?.resolve(),r._nonReactive.loadPromise?.resolve(),r._nonReactive.loaderPromise=void 0,r._nonReactive.loadPromise=void 0}catch(t){tt(t)&&await e.router.navigate(t.options)}})()):g!==`success`||o?await Tt(e,t,i,n,d):_t(e,i,n))}let{id:i,routeId:a}=e.matches[n],o=!1,s=!1,c=e.router.looseRoutesById[a],l=c.options.loader,u=((typeof l==`function`?void 0:l?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!==`blocking`;if(gt(e,i)){if(!e.router.getMatch(i))return e.matches[n];_t(e,i,n)}else{let t=e.router.getMatch(i),o=e.router.stores.matchesId.get()[n],s=(o&&e.router.stores.matchStores.get(o)||null)?.routeId===a?o:e.router.stores.matches.get().find(e=>e.routeId===a)?.id,l=ft(e,i);if(t._nonReactive.loaderPromise){if(t.status===`success`&&!e.sync&&!t.preload&&u)return t;await t._nonReactive.loaderPromise;let n=e.router.getMatch(i),a=n._nonReactive.error||n.error;a&&ht(e,n,a),n.status===`pending`&&await r(l,t,s,n,c)}else{let n=l&&!e.router.stores.matchStores.has(i),a=e.router.getMatch(i);a._nonReactive.loaderPromise=p(),n!==a.preload&&e.updateMatch(i,e=>({...e,preload:n})),await r(l,t,s,a,c)}}let d=e.router.getMatch(i);s||(d._nonReactive.loaderPromise?.resolve(),d._nonReactive.loadPromise?.resolve(),d._nonReactive.loadPromise=void 0),clearTimeout(d._nonReactive.pendingTimeout),d._nonReactive.pendingTimeout=void 0,s||(d._nonReactive.loaderPromise=void 0),d._nonReactive.dehydrated=void 0;let f=s?d.isFetching:!1;return f!==d.isFetching||d.invalid!==!1?(e.updateMatch(i,e=>({...e,isFetching:f,invalid:!1})),e.router.getMatch(i)):d};async function Dt(e){let t=e,n=[];dt(t.router)&&ut(t);let r;for(let e=0;e({...e,...a?{status:`success`,globalNotFound:!0,error:void 0}:{status:`notFound`,error:l},isFetching:!1})),u=e,await kt(r,[`notFoundComponent`])}else if(!t.preload){let e=t.matches[0];e.globalNotFound||t.router.getMatch(e.id)?.globalNotFound&&t.updateMatch(e.id,e=>({...e,globalNotFound:!1,error:void 0}))}if(t.serialError&&t.firstBadMatchIndex!==void 0){let e=t.router.looseRoutesById[t.matches[t.firstBadMatchIndex].routeId];await kt(e,[`errorComponent`])}for(let e=0;e<=u;e++){let{id:n,routeId:r}=t.matches[e],i=t.router.looseRoutesById[r];try{let e=Ct(t,n,i);if(e){let r=await e;t.updateMatch(n,e=>({...e,...r}))}}catch(e){console.error(`Error executing head for route ${r}:`,e)}}let d=ut(t);if(x(d)&&await d,l)throw l;if(t.serialError&&!t.preload&&!t.onReady)throw t.serialError;return t.matches}function Ot(e,t){let n=t.map(t=>e.options[t]?.preload?.()).filter(Boolean);if(n.length!==0)return Promise.all(n)}function kt(e,t=jt){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(t=>{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);let n=()=>e._componentsLoaded?void 0:t===jt?(()=>{if(e._componentsPromise===void 0){let t=Ot(e,jt);t?e._componentsPromise=t.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():Ot(e,t);return e._lazyPromise?e._lazyPromise.then(n):n()}function At(e){for(let t of jt)if(e.options[t]?.preload)return!0;return!1}var jt=[`component`,`errorComponent`,`pendingComponent`,`notFoundComponent`],Mt=`__TSR_index`,Nt=`popstate`,Pt=`beforeunload`;function Ft(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=zt(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[Mt];i=It(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[Mt];i=It(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[Mt]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function It(e,t){t||={};let n=Bt();return{...t,key:n,__TSR_key:n,[Mt]:e}}function Lt(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>zt(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=Bt();t.history.replaceState({[Mt]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_,v=()=>{g&&(C._ignoreSubscribers=!0,(g.isPush?t.history.pushState:t.history.replaceState)(g.state,``,g.href),C._ignoreSubscribers=!1,g=void 0,_=void 0,u=void 0)},y=(e,t,n)=>{let r=s(t);_||(u=l),l=zt(t,n),g={href:r,state:n,isPush:g?.isPush||e===`push`},_||=Promise.resolve().then(()=>v())},b=e=>{l=c(),C.notify({type:e})},x=async()=>{if(f){f=!1;return}let e=c(),n=e.state[Mt]-l.state[Mt],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),C.notify(u);return}}}l=c(),C.notify(u)},S=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},C=Ft({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>y(`push`,e,t),replaceState:(e,t)=>y(`replace`,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(Pt,S,{capture:!0}),t.removeEventListener(Nt,x)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Pt,S,{capture:!0}),t.addEventListener(Nt,x),t.history.pushState=function(...e){let r=n.apply(t.history,e);return C._ignoreSubscribers||b(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return C._ignoreSubscribers||b(`REPLACE`),n},C}function Rt(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function zt(e,t){let n=Rt(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=Bt();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[Mt]:0,key:a,__TSR_key:a}}}function Bt(){return(Math.random()+1).toString(36).substring(7)}function Vt(e){return e instanceof Error?{name:e.name,message:e.message}:{data:e}}function Ht(e,t){let n=t,r=e;return{fromLocation:n,toLocation:r,pathChanged:n?.pathname!==r.pathname,hrefChanged:n?.href!==r.href,hashChanged:n?.hash!==r.hash}}var Ut=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=e=>e(),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=ae(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=Lt()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!==`null`?this.origin=window.origin:this.origin=`http://localhost`),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=h(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=st(Kt(this.latestLocation),e),Ge(this)}let a=!1,o=this.options.basepath??`/`,s=this.options.rewrite;if(r||n!==o||i!==s){this.basepath=o;let e=[],t=ge(o);t&&t!==`/`&&e.push(it({basepath:o})),s&&e.push(s),this.rewrite=e.length===0?void 0:e.length===1?e[0]:rt(e),this.history&&this.updateLatestLocation(),a=!0}a&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<`u`&&`CSS`in window&&typeof window.CSS?.supports==`function`&&(this.isViewTransitionTypesSupported=window.CSS.supports(`selector(:active-view-transition-type(a))`))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=o(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&s(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{this.subscribers.forEach(t=>{t.eventType===e.type&&t.fn(e)})},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:m(e).path,external:!1,searchStr:o,search:b(t?.search,i),hash:m(r.slice(1)).path,state:S(t?.state,a)}}let o=new URL(i,this.origin),s=at(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:m(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:b(t?.search,c),hash:m(s.hash.slice(1)).path,state:S(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>me({base:e,to:t.includes(`//`)?E(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>Jt({pathname:e,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=e=>{let t=this.getMatch(e);t&&(t.abortController.abort(),clearTimeout(t._nonReactive.pendingTimeout),t._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(e=>{this.cancelMatch(e)}),this.stores.matchesId.get().forEach(e=>{if(this.stores.pendingMatchStores.has(e))return;let t=this.stores.matchStores.get(e)?.get();t&&(t.status===`pending`||t.isFetching===`loader`)&&this.cancelMatch(e)})},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this.pendingBuiltLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r.fullPath,a=t.to?`${t.to}`:void 0,o=r.search,s=Object.assign(Object.create(null),r.params),l=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),u=a?this.resolvePathWithBase(l,a):l,d=t.params===!1||t.params===null?Object.create(null):(t.params??!0)===!0?s:Object.assign(s,f(t.params,s)),p=this.routesByPath[he(u)],h;if(p)h=this.getRouteBranch(p);else if(u.includes(`$`))h=[];else{let e=this.getMatchedRoutes(u);h=e.matchedRoutes,this.options.notFoundRoute&&(!e.foundRoute||e.foundRoute.path!==`/`&&e.routeParams[`**`])&&(h=[...h,this.options.notFoundRoute])}if(h.length&&_(d))for(let e of h){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(d,t(d))}catch{}}let g=e.leaveParams?u:m(ie({path:u,params:d,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,v=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};h.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,qt(t.options.validateSearch,{...e,...v}))}catch{}}),v=e}v=Yt({search:v,dest:t,destRoutes:h,_includeValidateSearch:e._includeValidateSearch}),v=b(o,v);let y=this.options.stringifySearch(v),x=t.hash===!0?n.hash:t.hash?f(t.hash,n.hash):void 0,C=x?`#${x}`:``,w=t.state===!0?n.state:t.state?f(t.state,n.state):{};w=S(n.state,w);let ee=`${g}${y}${C}`,te,ne,re=!1;if(this.rewrite){let e=new URL(ee,this.origin),t=ot(this.rewrite,e);te=e.href.replace(e.origin,``),t.origin===this.origin?ne=t.pathname+t.search+t.hash:(ne=t.href,re=!0)}else te=c(ee),ne=te;return{publicHref:ne,href:te,pathname:g,search:v,searchStr:y,state:w,hash:x??``,external:re,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),o=r?t(r):void 0;if(!o){let n=Object.create(null);if(this.options.routeMasks){let s=a(i.pathname,this.processedTree);if(s){Object.assign(n,s.rawParams);let{from:i,params:a,...c}=s.route,l=a===!1||a===null?Object.create(null):(a??!0)===!0?n:Object.assign(n,f(a,n));r={from:e.from,...c,params:l},o=t(r)}}}return o&&(i.maskedLocation=o),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=()=>{let e=[`key`,`__TSR_key`,`__TSR_index`,`__hashScrollIntoViewOptions`];e.forEach(e=>{n.state[e]=this.latestLocation.state[e]});let t=g(n.state,this.latestLocation.state);return e.forEach(e=>{delete n.state[e]}),t},a=he(this.latestLocation.href)===he(n.href),o=this.commitLocationPromise;if(this.commitLocationPromise=p(()=>{o?.resolve(),o=void 0}),a&&i())this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t})}return this._scroll.next=n.resetScroll??!0,this.history.subscribers.size||this.load(r?{action:{type:r}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,href:a,...o}={})=>{if(a){let t=this.history.location.state.__TSR_index,n=zt(a,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);o.to=at(this.rewrite,r).pathname,o.search=this.options.parseSearch(n.search),o.hash=n.hash.slice(1)}let s=this.buildLocation({...o,_includeValidateSearch:!0});this.pendingBuiltLocation=s;let c=this.commitLocation({...s,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return queueMicrotask(()=>{this.pendingBuiltLocation===s&&(this.pendingBuiltLocation=void 0)}),c},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(_e(t,this.protocolAllowlist))return;if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return}i.replace?window.location.replace(t):window.location.href=t;return}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();let e=this.matchRoutes(this.latestLocation),t=this.stores.cachedMatches.get().filter(t=>!e.some(e=>e.id===t.id));this.batch(()=>{this.stores.status.set(`pending`),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(e),this.stores.setCached(t)})},this.load=async e=>{let t=e?.action?.type,n,r,i,a=this.stores.resolvedLocation.get()??this.stores.location.get();for(i=new Promise(o=>{this.startTransition(async()=>{try{this.beforeLoad(),t&&(this._scroll.hash=t===`PUSH`||t===`REPLACE`);let n=this.latestLocation,r=Ht(n,this.stores.resolvedLocation.get());this.stores.redirect.get()||this.emit({type:`onBeforeNavigate`,...r}),this.emit({type:`onBeforeLoad`,...r}),await Dt({router:this,sync:e?.sync,forceStaleReload:a.href===n.href,matches:this.stores.pendingMatches.get(),location:n,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let e=null,t=null,n=null,r=null;this.batch(()=>{let i=this.stores.pendingMatches.get(),a=i.length,o=this.stores.matches.get();e=a?o.filter(e=>!this.stores.pendingMatchStores.has(e.id)):null;let s=new Set;for(let e of this.stores.pendingMatchStores.values())e.routeId&&s.add(e.routeId);let c=new Set;for(let e of this.stores.matchStores.values())e.routeId&&c.add(e.routeId);t=a?o.filter(e=>!s.has(e.routeId)):null,n=a?i.filter(e=>!c.has(e.routeId)):null,r=a?i.filter(e=>c.has(e.routeId)):o,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),a&&(this.stores.setMatches(i),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...e.filter(e=>e.status!==`error`&&e.status!==`notFound`&&e.status!==`redirected`)]),this.clearExpiredCache())});for(let[e,i]of[[t,`onLeave`],[n,`onEnter`],[r,`onStay`]])if(e)for(let t of e)this.looseRoutesById[t.routeId].options[i]?.(t)})})}})}catch(e){tt(e)?(n=e,this.navigate({...n.options,replace:!0,ignoreBlocker:!0})):je(e)&&(r=e);let t=n?n.status:r?404:this.stores.matches.get().some(e=>e.status===`error`)?500:200;this.batch(()=>{this.stores.statusCode.set(t),this.stores.redirect.set(n)})}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),o()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let o;this.hasNotFoundMatch()?o=404:this.stores.matches.get().some(e=>e.status===`error`)&&(o=500),o!==void 0&&this.stores.statusCode.set(o)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document<`u`&&`startViewTransition`in document&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&this.isViewTransitionTypesSupported){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(Ht(r,i)):t.types;if(a===!1){e();return}n={update:e,types:a}}else n=e;document.startViewTransition(n)}else e()},this.updateMatch=(e,t)=>{this.startTransition(()=>{let n=this.stores.pendingMatchStores.get(e);if(n){n.set(t);return}let r=this.stores.matchStores.get(e);if(r){r.set(t);return}let i=this.stores.cachedMatchStores.get(e);if(i){let n=t(i.get());n.status===`redirected`?this.stores.cachedMatchStores.delete(e)&&this.stores.cachedIds.set(t=>t.filter(t=>t!==e)):i.set(n)}})},this.getMatch=e=>this.stores.cachedMatchStores.get(e)?.get()??this.stores.pendingMatchStores.get(e)?.get()??this.stores.matchStores.get(e)?.get(),this.invalidate=e=>{let t=t=>e?.filter?.(t)??!0?{...t,invalid:!0,...e?.forcePending||t.status===`error`||t.status===`notFound`?{status:`pending`,error:void 0}:void 0}:t;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(t)),this.stores.setCached(this.stores.cachedMatches.get().map(t)),this.stores.setPending(this.stores.pendingMatches.get().map(t))}),this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.getParsedLocationHref=e=>e.publicHref||`/`,this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=e.options._builtLocation??this.buildLocation(e.options),n=this.getParsedLocationHref(t);e.options.href=n,e.headers.set(`Location`,n)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&_e(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=e?.filter;t===void 0?this.stores.setCached([]):this.stores.setCached(this.stores.cachedMatches.get().filter(e=>!t(e)))},this.clearExpiredCache=()=>{let e=Date.now();this.clearCache({filter:t=>{let n=this.looseRoutesById[t.routeId];if(!n.options.loader)return!0;let r=(t.preload?n.options.preloadGcTime??this.options.defaultPreloadGcTime:n.options.gcTime??this.options.defaultGcTime)??300*1e3;return t.status===`error`||e-t.updatedAt>=r}})},this.loadRouteChunk=kt,this.preloadRoute=async e=>{let t=e._builtLocation??this.buildLocation(e),n=this.matchRoutes(t,{throwOnError:!0,preload:!0,dest:e}),r=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),i=new Set([...r,...this.stores.cachedIds.get()]),a=n.filter(e=>!i.has(e.id));if(a.length){let e=this.stores.cachedMatches.get();this.stores.setCached([...e,...a])}try{return n=await Dt({router:this,matches:n,location:t,preload:!0,updateMatch:(e,t)=>{r.has(e)?n=n.map(n=>n.id===e?t(n):n):this.updateMatch(e,t)}}),n}catch(e){if(tt(e))return e.options.reloadDocument?void 0:await this.preloadRoute({...e.options,_fromLocation:t});je(e)||console.error(e);return}},this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n);if(t?.pending&&this.stores.status.get()!==`pending`)return!1;let i=(t?.pending===void 0?!this.stores.isLoading.get():t.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),a=y(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,i.pathname,this.processedTree);return!a||e.params&&!g(a.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?g(i.search,r.search,{partial:!0})?a.rawParams:!1:a.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(e=>e.status===`notFound`||e.globalNotFound),this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??Xe,parseSearch:e.parseSearch??Ye,protocolAllowlist:e.protocolAllowlist??r}),typeof document<`u`&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=v(e),this.routeBranchCache.set(e,t)),t}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,t){let n=this.getMatchedRoutes(e.pathname),{foundRoute:r,routeParams:i}=n,{matchedRoutes:a}=n,o=!1;(r?r.path!==`/`&&i[`**`]:he(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?Zt(this.options.notFoundMode,a):void 0,c=Array(a.length),l=new Map;for(let e of this.stores.matchStores.values())e.routeId&&l.set(e.routeId,e.get());for(let n=0;nthis.navigate({...t,_fromLocation:e}),buildLocation:this.buildLocation,cause:n.cause,abortController:n.abortController,preload:!!n.preload,matches:c,routeId:r.id};n.__routeContext=r.options.context(t)??void 0}n.context={...a,...n.__routeContext,...n.__beforeLoadContext}}}return c}matchRoutesLightweight(e){let t=u(this.stores.matchesId.get()),n=this.lightweightCache.get(e);if(n&&n[0]===t)return n[1];let{matchedRoutes:r,routeParams:i}=this.getMatchedRoutes(e.pathname),a=u(r),o={...e.search};for(let e of r)try{Object.assign(o,qt(e.options.validateSearch,o))}catch{}let s=t&&this.stores.matchStores.get(t)?.get(),c=s&&s.routeId===a.id&&s.pathname===e.pathname,l;if(c)l=s.params;else{let e=Object.assign(Object.create(null),i);for(let t of r)try{Qt(t,e)}catch{}l=e}let d={matchedRoutes:r,fullPath:a.fullPath,search:o,params:l};return this.lightweightCache.set(e,[t,d]),d}},Wt=class extends Error{},Gt=class extends Error{};function Kt(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:`idle`,resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function qt(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new Wt(`Async validation not supported`);if(n.issues)throw new Wt(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function Jt({pathname:e,routesById:t,processedTree:n}){let r=Object.create(null),i=he(e),a,o=O(i,n,!0);return o&&(a=o.route,Object.assign(r,o.rawParams)),{matchedRoutes:o?.branch||[t.__root__],routeParams:r,foundRoute:a}}function Yt({search:e,dest:t,destRoutes:n,_includeValidateSearch:r}){return Xt(n)(e,t,r??!1)}function Xt(e){let t,n,r=[];for(let t of e){let e=t.options;`search`in e?e.search?.middlewares&&r.push(...e.search.middlewares):(e.preSearchFilters||e.postSearchFilters)&&r.push(({search:t,next:n})=>{let r=n(e.preSearchFilters?e.preSearchFilters.reduce((e,t)=>t(e),t):t);return e.postSearchFilters?e.postSearchFilters.reduce((e,t)=>t(e),r):r});let i=e.validateSearch;i&&r.push(({search:e,next:t,meta:r})=>{let a=t(e);if(n)try{let e=qt(i,a);if(r&&e)for(let t in e)t in a||(r.defaulted||=new Map).set(t,e[t]);return{...a,...e}}catch{}return a})}let i=(e,n,a)=>{if(e>=r.length){if(!t.search)return{};if(t.search===!0)return n;let e=f(t.search,n);return a&&(a.explicit=e),e}return r[e]({search:n,next:(t,n)=>{if(n){let n=a||{};return{search:i(e+1,t,n),meta:n}}return i(e+1,t,a)},meta:a})};return function(e,r,a){return t=r,n=a,i(0,e)}}function Zt(e,t){if(e!==`root`)for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.children)return n.id}return $e}function Qt(e,t){let n=e.options.params?.parse??e.options.parseParams;if(n){let e=n(t);if(e===!1)throw Error(`Route params.parse returned false for a matched route`);Object.assign(t,e)}}var $t=Symbol.for(`TSR_DEFERRED_PROMISE`);function en(e,t){let n=e;return n[$t]?n:(n[$t]={status:`pending`},n.then(e=>{n[$t].status=`success`,n[$t].data=e}).catch(e=>{n[$t].status=`error`,n[$t].error={data:(t?.serializeError??Vt)(e),__isServerError:!0}}),n)}function tn(e,t){if(e)return typeof e==`string`?e:e[t]}function nn(e){return e?.scriptFormat??`module`}function rn(e,t,n){let r=an(t),i=tn(n,`script`)??r.crossOrigin;return{...nn(e)===`iife`?{rel:`preload`,as:`script`}:{rel:`modulepreload`},href:r.href,...i?{crossOrigin:i}:{}}}function an(e){return typeof e==`string`?{href:e,crossOrigin:void 0}:e}function on(e,t){if(t.length===0)return;if(t.length===1){e.push(t[0]);return}let n=new Set;for(let r of t){let t=JSON.stringify(r);n.has(t)||(n.add(t),e.push(r))}}function sn(e){return typeof e==`string`?{href:e,crossOrigin:void 0}:e}var cn=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=$e:this.parentRoute||ce();let r=n?$e:t?.path;r&&r!==`/`&&(r=ee(r));let i=t?.id||r,a=n?$e:C([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=C([`/`,a]));let o=a===`__root__`?`/`:C([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=he(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>et({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},ln=class extends cn{constructor(e){super(e)}},un=(e=>(e[e.AggregateError=1]=`AggregateError`,e[e.ArrowFunction=2]=`ArrowFunction`,e[e.ErrorPrototypeStack=4]=`ErrorPrototypeStack`,e[e.ObjectAssign=8]=`ObjectAssign`,e[e.BigIntTypedArray=16]=`BigIntTypedArray`,e[e.RegExp=32]=`RegExp`,e))(un||{}),dn=Symbol.asyncIterator,fn=Symbol.hasInstance,pn=Symbol.isConcatSpreadable,mn=Symbol.iterator,hn=Symbol.match,gn=Symbol.matchAll,_n=Symbol.replace,vn=Symbol.search,yn=Symbol.species,bn=Symbol.split,xn=Symbol.toPrimitive,Sn=Symbol.toStringTag,Cn=Symbol.unscopables,wn={[dn]:0,[fn]:1,[pn]:2,[mn]:3,[hn]:4,[gn]:5,[_n]:6,[vn]:7,[yn]:8,[bn]:9,[xn]:10,[Sn]:11,[Cn]:12},Tn={0:dn,1:fn,2:pn,3:mn,4:hn,5:gn,6:_n,7:vn,8:yn,9:bn,10:xn,11:Sn,12:Cn},k=void 0,En={2:!0,3:!1,1:k,0:null,4:-0,5:1/0,6:-1/0,7:NaN},Dn={0:`Error`,1:`EvalError`,2:`RangeError`,3:`ReferenceError`,4:`SyntaxError`,5:`TypeError`,6:`URIError`},On={0:Error,1:EvalError,2:RangeError,3:ReferenceError,4:SyntaxError,5:TypeError,6:URIError};function A(e,t,n,r,i,a,o,s,c,l,u,d){return{t:e,i:t,s:n,c:r,m:i,p:a,e:o,a:s,f:c,b:l,o:u,l:d}}function kn(e){return A(2,k,e,k,k,k,k,k,k,k,k,k)}var An=kn(2),jn=kn(3),Mn=kn(1),Nn=kn(0),Pn=kn(4),Fn=kn(5),In=kn(6),Ln=kn(7);function Rn(e){switch(e){case`"`:return`\\"`;case`\\`:return`\\\\`;case` +`:return`\\n`;case`\r`:return`\\r`;case`\b`:return`\\b`;case` `:return`\\t`;case`\f`:return`\\f`;case`<`:return`\\x3C`;case`\u2028`:return`\\u2028`;case`\u2029`:return`\\u2029`;default:return k}}function zn(e){let t=``,n=0,r;for(let i=0,a=e.length;iTr(e),Dr=class extends Error{constructor(e,t){super(Er(e,t)),this.cause=t}},Or=class extends Dr{constructor(e){super(`parsing`,e)}},kr=class extends Dr{constructor(e){super(`deserialization`,e)}};function Ar(e){return`Seroval Error (specific: ${e})`}var jr=class extends Error{constructor(e){super(Ar(1)),this.value=e}},Mr=class extends Error{constructor(e){super(Ar(2))}},Nr=class extends Error{constructor(e){super(Ar(3))}},Pr=class extends Error{constructor(e){super(Ar(4))}},Fr=class extends Error{constructor(e){super(Ar(5)),this.value=e}},Ir=class extends Error{constructor(e){super(Ar(6))}},Lr=class extends Error{constructor(e){super(Ar(7))}},Rr=class extends Error{constructor(e){super(Ar(8))}},zr=class extends Error{constructor(e){super(Ar(9))}},Br=class{constructor(e,t){this.value=e,this.replacement=t}},Vr=()=>{let e={p:0,s:0,f:0};return e.p=new Promise((t,n)=>{e.s=t,e.f=n}),e};Vr.toString(),((e,t)=>{e.s(t),e.p.s=1,e.p.v=t}).toString(),((e,t)=>{e.f(t),e.p.s=2,e.p.v=t}).toString();var Hr=()=>{let e=[],t=[],n=!0,r=!1,i=0,a=(e,n,r)=>{for(r=0;r{for(i=0,a=e.length;i(n&&(r=i++,t[r]=e),o(e),()=>{n&&(t[r]=t[i],t[i--]=void 0)});return{__SEROVAL_STREAM__:!0,on:e=>s(e),next:t=>{n&&(e.push(t),a(t,`next`))},throw:i=>{n&&(e.push(i),a(i,`throw`),n=!1,r=!1,t.length=0)},return:i=>{n&&(e.push(i),a(i,`return`),n=!1,r=!0,t.length=0)}}};Hr.toString();var Ur=e=>t=>()=>{let n=0,r={[e]:()=>r,next:()=>{if(n>t.d)return{done:!0,value:void 0};let e=n++,r=t.v[e];if(e===t.t)throw r;return{done:e===t.d,value:r}}};return r};Ur.toString();var Wr=(e,t)=>n=>()=>{let r=0,i=-1,a=!1,o=[],s=[],c=(e=0,t=s.length)=>{for(;e{let t=s.shift();t&&t.s({done:!1,value:e}),o.push(e)},throw:e=>{let t=s.shift();t&&t.f(e),c(),i=o.length,a=!0,o.push(e)},return:e=>{let t=s.shift();t&&t.s({done:!0,value:e}),c(),i=o.length,o.push(e)}});let l={[e]:()=>l,next:()=>{if(i===-1){let e=r++;if(e>=o.length){let e=t();return s.push(e),e.p}return{done:!1,value:o[e]}}if(r>i)return{done:!0,value:void 0};let e=r++,n=o[e];if(e!==i)return{done:!1,value:n};if(a)throw n;return{done:!0,value:n}}};return l};Wr.toString();var Gr=e=>{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e{}),t}var ri=Wr(dn,Vr);function ii(e){return ri(e)}async function ai(e){try{return[1,await e]}catch(e){return[0,e]}}function oi(e,t){return{plugins:t.plugins,mode:e,marked:new Set,features:63^(t.disabledFeatures||0),refs:t.refs||new Map,depthLimit:t.depthLimit||1e3}}function si(e,t){e.marked.add(t)}function ci(e,t){let n=e.refs.size;return e.refs.set(t,n),n}function li(e,t){let n=e.refs.get(t);return n==null?{type:0,value:ci(e,t)}:(si(e,n),{type:1,value:nr(n)})}function ui(e,t){let n=li(e,t);return n.type===1?n:Gn(t)?{type:2,value:or(n.value,t)}:n}function di(e,t){let n=ui(e,t);if(n.type!==0)return n.value;if(t in wn)return ar(n.value,t);throw new jr(t)}function fi(e,t){let n=li(e,$r[t]);return n.type===1?n.value:A(26,n.value,t,k,k,k,k,k,k,k,k,k)}function pi(e){let t=li(e,Zr);return t.type===1?t.value:A(27,t.value,k,k,k,k,k,k,di(e,mn),k,k,k)}function mi(e){let t=li(e,Qr);return t.type===1?t.value:A(29,t.value,k,k,k,k,k,[fi(e,1),di(e,dn)],k,k,k,k)}function hi(e,t,n,r){return A(n?11:10,e,k,k,k,r,k,k,k,k,Qn(t),k)}function gi(e,t,n,r){return A(8,t,k,k,k,k,{k:n,v:r},k,fi(e,0),k,k,k)}function _i(e,t,n){let r=new Uint8Array(n),i=``;for(let e=0,t=r.length;e{si(this.base,t),zi(this,e,n).then(e=>{a.push(yr(t,e))},e=>{i(e),o()})},throw:n=>{si(this.base,t),zi(this,e,n).then(e=>{a.push(br(t,e)),r(a),o()},e=>{i(e),o()})},return:n=>{si(this.base,t),zi(this,e,n).then(e=>{a.push(xr(t,e)),r(a),o()},e=>{i(e),o()})}})}async function Fi(e,t,n,r){return vr(n,fi(e.base,4),await new Promise(Pi.bind(e,t,n,r)))}async function Ii(e,t,n,r){let i=[];for(let n=0,a=r.v.length;n=e.base.depthLimit)throw new zr(e.base.depthLimit);switch(typeof n){case`boolean`:return n?An:jn;case`undefined`:return Mn;case`string`:return er(n);case`number`:return $n(n);case`bigint`:return tr(n);case`object`:if(n){let r=ui(e.base,n);return r.type===0?await Li(e,t+1,r.value,n):r.value}return Nn;case`symbol`:return di(e.base,n);case`function`:return Ri(e,t,n);default:throw new jr(n)}}async function Bi(e,t){try{return await zi(e,0,t)}catch(e){throw e instanceof Or?e:new Or(e)}}var Vi=(e=>(e[e.Vanilla=1]=`Vanilla`,e[e.Cross=2]=`Cross`,e))(Vi||{});function j(e){return e}function M(e,t){for(let n=0,r=t.length;n0)for(let a=0,o=n.v,s=i.length;aqi)throw new Rr(t);return P(e,t.i,new RegExp(n,t.m))}throw new Mr(t)}function pa(e,t,n){let r=P(e,n.i,new Set);for(let i=0,a=n.a,o=a.length;iGi)throw new Rr(t);return P(e,t.i,Gr(Vn(t.s)))}function ga(e,t,n){let r=Hi(n.c),i=F(e,t,n.f),a=n.b??0;if(a<0||a>i.byteLength)throw new Rr(n);return P(e,n.i,new r(i,a,n.l))}function _a(e,t,n){let r=F(e,t,n.f),i=n.b??0;if(i<0||i>r.byteLength)throw new Rr(n);return P(e,n.i,new DataView(r,i,n.l))}function va(e,t,n,r){if(n.p){let i=la(e,t,n.p,{});Object.defineProperties(r,Object.getOwnPropertyDescriptors(i))}return r}function ya(e,t,n){return va(e,t,n,P(e,n.i,AggregateError([],Vn(n.m))))}function ba(e,t,n){let r=na(n,On,n.s);return va(e,t,n,P(e,n.i,new r(Vn(n.m))))}function xa(e,t,n){let r=Vr(),i=P(e,n.i,r.p),a=F(e,t,n.f);return n.s?r.s(a):r.f(a),i}function Sa(e,t,n){return P(e,n.i,Object(F(e,t,n.f)))}function Ca(e,t,n){let r=e.base.plugins;if(r){let i=Vn(n.c);for(let a=0,o=r.length;ae.base.depthLimit)throw new zr(e.base.depthLimit);switch(t+=1,n.t){case 2:return na(n,En,n.s);case 0:return Number(n.s);case 1:return Vn(String(n.s));case 3:if(String(n.s).length>Ki)throw new Rr(n);return BigInt(n.s);case 4:return e.base.refs.get(n.i);case 18:return ra(e,n);case 9:return ia(e,t,n);case 10:case 11:return ua(e,t,n);case 5:return da(e,n);case 6:return fa(e,n);case 7:return pa(e,t,n);case 8:return ma(e,t,n);case 19:return ha(e,n);case 16:case 15:return ga(e,t,n);case 20:return _a(e,t,n);case 14:return ya(e,t,n);case 13:return ba(e,t,n);case 12:return xa(e,t,n);case 17:return na(n,Tn,n.s);case 21:return Sa(e,t,n);case 25:return Ca(e,t,n);case 22:return wa(e,n);case 23:return Ta(e,t,n);case 24:return Ea(e,t,n);case 28:return Da(e,t,n);case 30:return Oa(e,t,n);case 31:return ka(e,t,n);case 32:return Aa(e,t,n);case 33:return ja(e,t,n);case 34:return Ma(e,t,n);case 27:return Na(e,t,n);case 29:return Pa(e,t,n);case 35:return Fa(e,t,n);default:throw new Mr(n)}}function Ia(e,t){try{return F(e,0,t)}catch(e){throw new kr(e)}}var La=(()=>T).toString();/=>/.test(La);function Ra(e,t){return Ia(Zi({plugins:N(t.plugins),refs:t.refs,features:t.features,disabledFeatures:t.disabledFeatures,depthLimit:t.depthLimit}),e)}async function za(e,t={}){let n=vi(1,{plugins:N(t.plugins),disabledFeatures:t.disabledFeatures});return{t:await Bi(n,e),f:n.base.features,m:Array.from(n.base.marked)}}function Ba(e){return e}function Va(e){return j({tag:`$TSR/t/`+e.key,test:e.test,parse:{sync(t,n,r){return{v:n.parse(e.toSerializable(t))}},async async(t,n,r){return{v:await n.parse(e.toSerializable(t))}},stream(t,n,r){return{v:n.parse(e.toSerializable(t))}}},serialize:void 0,deserialize(t,n,r){return e.fromSerializable(n.deserialize(t.v))}})}var Ha=class{constructor(e,t){this.stream=e,this.hint=t?.hint??`binary`}},Ua=globalThis.Buffer,Wa=!!Ua&&typeof Ua.from==`function`;function Ga(e){if(e.length===0)return``;if(Wa)return Ua.from(e).toString(`base64`);let t=32768,n=[];for(let r=0;rnew ReadableStream({start(t){e.on({next(e){try{t.enqueue(Ka(e))}catch{}},throw(e){t.error(e)},return(){try{t.close()}catch{}}})}}),Xa=new TextEncoder,Za=e=>new ReadableStream({start(t){e.on({next(e){try{typeof e==`string`?t.enqueue(Xa.encode(e)):t.enqueue(Ka(e.$b64))}catch{}},throw(e){t.error(e)},return(){try{t.close()}catch{}}})}}),Qa=`(s=>new ReadableStream({start(c){s.on({next(b){try{const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i{const e=new TextEncoder();return new ReadableStream({start(c){s.on({next(v){try{if(typeof v==='string'){c.enqueue(e.encode(v))}else{const d=atob(v.$b64),a=new Uint8Array(d.length);for(let i=0;i{try{for(;;){let{done:e,value:r}=await n.read();if(e){t.return(void 0);break}t.next(Ga(r))}}catch(e){t.throw(e)}finally{n.releaseLock()}})(),t}function to(e){let t=ti(),n=e.getReader(),r=new TextDecoder(`utf-8`,{fatal:!0});return(async()=>{try{for(;;){let{done:e,value:i}=await n.read();if(e){try{let e=r.decode();e.length>0&&t.next(e)}catch{}t.return(void 0);break}try{let e=r.decode(i,{stream:!0});e.length>0&&t.next(e)}catch{t.next({$b64:Ga(i)})}}}catch(e){t.throw(e)}finally{n.releaseLock()}})(),t}var no=j({tag:`tss/RawStream`,extends:[j({tag:`tss/RawStreamFactory`,test(e){return e===qa},parse:{sync(e,t,n){return{}},async async(e,t,n){return{}},stream(e,t,n){return{}}},serialize(e,t,n){return Qa},deserialize(e,t,n){return qa}}),j({tag:`tss/RawStreamFactoryText`,test(e){return e===Ja},parse:{sync(e,t,n){return{}},async async(e,t,n){return{}},stream(e,t,n){return{}}},serialize(e,t,n){return $a},deserialize(e,t,n){return Ja}})],test(e){return e instanceof Ha},parse:{sync(e,t,n){let r=e.hint===`text`?Ja:qa;return{hint:t.parse(e.hint),factory:t.parse(r),stream:t.parse(ti())}},async async(e,t,n){let r=e.hint===`text`?Ja:qa,i=e.hint===`text`?to(e.stream):eo(e.stream);return{hint:await t.parse(e.hint),factory:await t.parse(r),stream:await t.parse(i)}},stream(e,t,n){let r=e.hint===`text`?Ja:qa,i=e.hint===`text`?to(e.stream):eo(e.stream);return{hint:t.parse(e.hint),factory:t.parse(r),stream:t.parse(i)}}},serialize(e,t,n){return`(`+t.serialize(e.factory)+`)(`+t.serialize(e.stream)+`)`},deserialize(e,t,n){let r=t.deserialize(e.stream);return t.deserialize(e.hint)===`text`?Za(r):Ya(r)}});function ro(e){return j({tag:`tss/RawStream`,test:()=>!1,parse:{},serialize(){throw Error(`RawStreamDeserializePlugin.serialize should not be called. Client only deserializes.`)},deserialize(t,n,r){return e(typeof n?.deserialize==`function`?n.deserialize(t.streamId):t.streamId)}})}var io=j({tag:`$TSR/Error`,test(e){return e instanceof Error},parse:{sync(e,t){return{message:t.parse(e.message)}},async async(e,t){return{message:await t.parse(e.message)}},stream(e,t){return{message:t.parse(e.message)}}},serialize(e,t){return`new Error(`+t.serialize(e.message)+`)`},deserialize(e,t){return Error(t.deserialize(e.message))}}),ao={},oo=e=>new ReadableStream({start:t=>{e.on({next:e=>{try{t.enqueue(e)}catch{}},throw:e=>{t.error(e)},return:()=>{try{t.close()}catch{}}})}}),so=j({tag:`seroval-plugins/web/ReadableStreamFactory`,test(e){return e===ao},parse:{sync(){return ao},async async(){return await Promise.resolve(ao)},stream(){return ao}},serialize(){return oo.toString()},deserialize(){return ao}});async function co(e,t){try{let n=await t.read();n.done?(e.return(n.value),t.releaseLock()):(e.next(n.value),await co(e,t))}catch(t){e.throw(t)}}function lo(e){e.cancel().catch(()=>{}),e.releaseLock()}function uo(e){let t=ti(),n=e.getReader(),r=lo.bind(null,n);return co(t,n).catch(r),[t,r]}var fo=[io,no,j({tag:`seroval/plugins/web/ReadableStream`,extends:[so],test(e){return typeof ReadableStream>`u`?!1:e instanceof ReadableStream},parse:{sync(e,t){return{factory:t.parse(ao),stream:t.parse(ti())}},async async(e,t){return{factory:await t.parse(ao),stream:await t.parse(uo(e)[0])}},stream(e,t){let[n,r]=uo(e);return t.addCleanup(r),{factory:t.parse(ao),stream:t.parse(n)}}},serialize(e,t){return`(`+t.serialize(e.factory)+`)(`+t.serialize(e.stream)+`)`},deserialize(e,t){return oo(t.deserialize(e.stream))}})];function po(){return[...(Ae()?.serializationAdapters)?.map(Va)??[],...fo]}var mo=new TextDecoder,ho=new Uint8Array,I=16*1024*1024,go=32*1024*1024,_o=1024,L=1e5;function R(e){let t=new Map,n=new Map,r=new Set,i=!1,a=null,o=0,s,c=new ReadableStream({start(e){s=e},cancel(){i=!0;try{a?.cancel()}catch{}t.forEach(e=>{try{e.error(Error(`Framed response cancelled`))}catch{}}),t.clear(),n.clear(),r.clear()}});function l(e){let i=n.get(e);if(i)return i;if(r.has(e))return new ReadableStream({start(e){e.close()}});if(n.size>=_o)throw Error(`Too many raw streams in framed response (max ${_o})`);let a=new ReadableStream({start(n){t.set(e,n)},cancel(){r.add(e),t.delete(e),n.delete(e)}});return n.set(e,a),a}function u(e){return l(e),t.get(e)}return(async()=>{let n=e.getReader();a=n;let c=[],l=0;function d(){if(l<9)return null;let e=c[0];if(e.length>=9)return{type:e[0],streamId:(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0,length:(e[5]<<24|e[6]<<16|e[7]<<8|e[8])>>>0};let t=new Uint8Array(9),n=0,r=9;for(let e=0;e0;e++){let i=c[e],a=Math.min(i.length,r);t.set(i.subarray(0,a),n),n+=a,r-=a}return{type:t[0],streamId:(t[1]<<24|t[2]<<16|t[3]<<8|t[4])>>>0,length:(t[5]<<24|t[6]<<16|t[7]<<8|t[8])>>>0}}function f(e){if(e===0)return ho;let t=c[0];if(t&&t.length>=e){let n=t.subarray(0,e);return t.length===e?c.shift():c[0]=t.subarray(e),l-=e,n}let n=new Uint8Array(e),r=0,i=e;for(;i>0&&c.length>0;){let e=c[0];if(!e)break;let t=Math.min(e.length,i);n.set(e.subarray(0,t),r),r+=t,i-=t,t===e.length?c.shift():c[0]=e.subarray(t)}return l-=e,n}try{for(;;){let{done:e,value:a}=await n.read();if(i||e)break;if(a){if(l+a.length>go)throw Error(`Framed response buffer exceeded ${go} bytes`);for(c.push(a),l+=a.length;;){let e=d();if(!e)break;let{type:n,streamId:i,length:a}=e;if(n!==Ee.JSON&&n!==Ee.CHUNK&&n!==Ee.END&&n!==Ee.ERROR)throw Error(`Unknown frame type: ${n}`);if(n===Ee.JSON){if(i!==0)throw Error(`Invalid JSON frame streamId (expected 0)`)}else if(i===0)throw Error(`Invalid raw frame streamId (expected non-zero)`);if(a>I)throw Error(`Frame payload too large: ${a} bytes (max ${I})`);let c=9+a;if(lL)throw Error(`Too many frames in framed response (max ${L})`);f(9);let p=f(a);switch(n){case Ee.JSON:try{s.enqueue(mo.decode(p))}catch{}break;case Ee.CHUNK:{let e=u(i);e&&e.enqueue(p);break}case Ee.END:{let e=u(i);if(r.add(i),e){try{e.close()}catch{}t.delete(i)}break}case Ee.ERROR:{let e=u(i);if(r.add(i),e){let n=mo.decode(p);e.error(Error(n)),t.delete(i)}break}}}}}if(l!==0)throw Error(`Incomplete frame at end of framed response`);try{s.close()}catch{}t.forEach(e=>{try{e.close()}catch{}}),t.clear()}catch(e){try{s.error(e)}catch{}t.forEach(t=>{try{t.error(e)}catch{}}),t.clear()}finally{try{n.releaseLock()}catch{}a=null}})(),{getOrCreateStream:l,jsonChunks:c}}var z=null;async function vo(e){e.length>0&&await Promise.allSettled(e)}var yo=Object.prototype.hasOwnProperty;function bo(e){for(let t in e)if(yo.call(e,t))return!0;return!1}async function xo(e,t,n){z||=po();let r=t[0],i=r.fetch??n,a=r.data instanceof FormData?`formData`:`payload`,o=r.headers?new Headers(r.headers):new Headers;if(o.set(`x-tsr-serverFn`,`true`),a===`payload`&&o.set(`accept`,`${Te}, application/x-ndjson, application/json`),r.method===`GET`){if(a===`formData`)throw Error(`FormData is not supported with GET requests`);let t=await So(r);if(t!==void 0){let n=Ke({payload:t});e.includes(`?`)?e+=`&${n}`:e+=`?${n}`}}let s;if(r.method===`POST`){let e=await wo(r);e?.contentType&&o.set(`content-type`,e.contentType),s=e?.body}return await B(async()=>i(e,{method:r.method,headers:o,signal:r.signal,body:s}))}async function So(e){let t=!1,n={};if(e.data!==void 0&&(t=!0,n.data=e.data),e.context&&bo(e.context)&&(t=!0,n.context=e.context),t)return Co(n)}async function Co(e){return JSON.stringify(await Promise.resolve(za(e,{plugins:z})))}async function wo(e){if(e.data instanceof FormData){let t;return e.context&&bo(e.context)&&(t=await Co(e.context)),t!==void 0&&e.data.set(Se,t),{body:e.data}}let t=await So(e);if(t)return{body:t,contentType:`application/json`}}async function B(e){let t;try{t=await e()}catch(e){if(e instanceof Response)t=e;else throw console.log(e),e}if(t.headers.get(`x-tss-raw`)===`true`)return t;let n=t.headers.get(`content-type`);if(n||ce(),t.headers.get(`x-tss-serialized`)){let e;if(n.includes(`application/x-tss-framed`)){if(ke(n),!t.body)throw Error(`No response body for framed response`);let{getOrCreateStream:r,jsonChunks:i}=R(t.body),a=[ro(r),...z||[]],o=new Map;e=await To({jsonStream:i,onMessage:e=>Ra(e,{refs:o,plugins:a}),onError(e,t){console.error(e,t)}})}else if(n.includes(`application/json`)){let n=await t.json(),r=[];try{e=Ra(n,{plugins:z})}finally{}await vo(r)}if(e||ce(),e instanceof Error)throw e;return e}if(n.includes(`application/json`)){let e=await t.json(),n=nt(e);if(n)throw n;if(je(e))throw e;return e}if(!t.ok)throw Error(await t.text());return t}async function To({jsonStream:e,onMessage:t,onError:n}){let r=e.getReader(),{value:i,done:a}=await r.read();if(a||!i)throw Error(`Stream ended before first object`);let o=JSON.parse(i),s=!1,c=(async()=>{try{for(;;){let{value:e,done:i}=await r.read();if(i)break;if(e)try{let n=[];try{t(JSON.parse(e))}finally{}await vo(n)}catch(t){n?.(`Invalid JSON: ${e}`,t)}}}catch(e){s||n?.(`Stream processing error:`,e)}})(),l,u=[];try{l=t(o)}catch(e){throw s=!0,r.cancel().catch(()=>{}),e}return await vo(u),Promise.resolve(l).catch(()=>{s=!0,r.cancel().catch(()=>{})}),c.finally(()=>{try{r.releaseLock()}catch{}}),l}function Eo(e){let t=`/_serverFn/`+e;return Object.assign((...e)=>{let n=Ae()?.serverFns?.fetch;return xo(t,e,n??fetch)},{url:t,serverFnMeta:{id:e},[Ce]:!0})}var Do=Ba({key:`$TSS/serverfn`,test:e=>typeof e!=`function`||!(Ce in e)?!1:!!e[Ce],toSerializable:({serverFnMeta:e})=>({functionId:e.id}),fromSerializable:({functionId:e})=>Eo(e)});function Oo(e){return e.replaceAll(`\0`,`/`).replaceAll(`�`,`/`)}function ko(e,t){e.id=t.i,e.__beforeLoadContext=t.b,e.loaderData=t.l,e.status=t.s,e.ssr=t.ssr,e.updatedAt=t.u,e.error=t.e,t.g!==void 0&&(e.globalNotFound=t.g)}async function Ao(e){window.$_TSR||ce();let t=e.options.serializationAdapters;if(t?.length){let e=new Map;t.forEach(t=>{e.set(t.key,t.fromSerializable)}),window.$_TSR.t=e,window.$_TSR.buffer.forEach(e=>e())}window.$_TSR.initialized=!0,window.$_TSR.router||ce();let n=window.$_TSR.router;n.matches.forEach(e=>{e.i=Oo(e.i)}),n.lastMatchId&&=Oo(n.lastMatchId);let{manifest:r,dehydratedData:i,lastMatchId:a}=n;e.ssr={manifest:r};let o=document.querySelector(`meta[property="csp-nonce"]`)?.content;e.options.ssr={nonce:o},await e.options.hydrate?.(i);let s=e.matchRoutes(e.stores.location.get()),c=Promise.all(s.map(t=>e.loadRouteChunk(e.looseRoutesById[t.routeId])));function l(t){let n=e.looseRoutesById[t.routeId].options.pendingMinMs??e.options.defaultPendingMinMs;if(n){let r=p();t._nonReactive.minPendingPromise=r,t._forcePending=!0,setTimeout(()=>{r.resolve(),e.updateMatch(t.id,e=>(e._nonReactive.minPendingPromise=void 0,{...e,_forcePending:void 0}))},n)}}function u(t){let n=e.looseRoutesById[t.routeId];n&&(n.options.ssr=t.ssr)}let d;s.forEach(e=>{let t=n.matches.find(t=>t.i===e.id);if(!t){e._nonReactive.dehydrated=!1,e.ssr=!1,u(e);return}ko(e,t),u(e),e._nonReactive.dehydrated=e.ssr!==!1,(e.ssr===`data-only`||e.ssr===!1)&&d===void 0&&(d=e.index,l(e))}),e.stores.setMatches(s);let f=e.stores.matches.get(),m=e.stores.location.get();await Promise.all(f.map(async t=>{try{let n=e.looseRoutesById[t.routeId],r=f[t.index-1]?.context??e.options.context;if(n.options.context){let i={deps:t.loaderDeps,params:t.params,context:r??{},location:m,navigate:t=>e.navigate({...t,_fromLocation:m}),buildLocation:e.buildLocation,cause:t.cause,abortController:t.abortController,preload:!1,matches:s,routeId:n.id};t.__routeContext=n.options.context(i)??void 0}t.context={...r,...t.__routeContext,...t.__beforeLoadContext};let i={ssr:e.options.ssr,matches:f,match:t,params:t.params,loaderData:t.loaderData},a=await n.options.head?.(i),o=await n.options.scripts?.(i);t.meta=a?.meta,t.links=a?.links,t.headScripts=a?.scripts,t.styles=a?.styles,t.scripts=o}catch(e){if(je(e))t.error={isNotFound:!0},console.error(`NotFound error during hydration for routeId: ${t.routeId}`,e);else throw t.error=e,console.error(`Error during hydration for route ${t.routeId}:`,e),e}}));let h=s[s.length-1].id!==a;if(!s.some(e=>e.ssr===!1)&&!h)return s.forEach(e=>{e._nonReactive.dehydrated=void 0}),e.stores.resolvedLocation.set(e.stores.location.get()),c;let g=Promise.resolve().then(()=>e.load()).catch(e=>{console.error(`Error during router hydration:`,e)});if(h){let t=s[1];t||ce(),l(t),t._displayPending=!0,t._nonReactive.displayPendingPromise=g,g.then(()=>{e.batch(()=>{e.stores.status.get()===`pending`&&(e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())),e.updateMatch(t.id,e=>({...e,_displayPending:void 0,displayPendingPromise:void 0}))})})}return c}var V=e(n(),1),H=pe();function jo({promise:e}){if(ne)return ne(e);let t=en(e);if(t[$t].status===`pending`)throw t;if(t[$t].status===`error`)throw t[$t].error;return t[$t].data}function Mo(e){let t=(0,H.jsx)(No,{...e});return e.fallback?(0,H.jsx)(V.Suspense,{fallback:e.fallback,children:t}):t}function No(e){let t=jo(e);return e.children(t)}function Po(e){let t=e.errorComponent??Io;return(0,H.jsx)(Fo,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:n,reset:r})=>n?V.createElement(t,{error:n,reset:r}):e.children})}var Fo=class extends V.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,t){this.props.onCatch&&this.props.onCatch(e,t)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function Io({error:e}){let[t,n]=V.useState(!1);return(0,H.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,H.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,H.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,H.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,H.jsx)(`div`,{children:(0,H.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,H.jsx)(`code`,{children:e.message}):null})}):null]})}var Lo=V.createContext(void 0),Ro=V.createContext(void 0),U=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(U||{});function zo({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function Bo(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var Vo=[],Ho=0,{link:Uo,unlink:Wo,propagate:Go,checkDirty:Ko,shallowPropagate:qo}=zo({update(e){return e._update()},notify(e){Vo[Yo++]=e,e.flags&=~U.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=U.Mutable|U.Dirty,$o(e))}}),Jo=0,Yo=0,Xo,Zo=0;function Qo(e){try{++Zo,e()}finally{--Zo||es()}}function $o(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Wo(n,e)}function es(){if(!(Zo>0)){for(;Jo{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=Xo,o=t?.compare??Object.is;if(n)Xo=i,++Ho,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=U.Mutable|U.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{Xo=a,n&&(i.flags&=~U.RecursedCheck),$o(i)}}};return n?(i.flags=U.Mutable|U.Dirty,i.get=function(){let e=i.flags;if(e&U.Dirty||e&U.Pending&&Ko(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&qo(e)}}else e&U.Pending&&(i.flags=e&~U.Pending);return Xo!==void 0&&Uo(i,Xo,Ho),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Go(e),qo(e),es())}},i}function ns(e){let t=()=>{let t=Xo;Xo=n,++Ho,n.depsTail=void 0,n.flags=U.Watching|U.RecursedCheck;try{return e()}finally{Xo=t,n.flags&=~U.RecursedCheck,$o(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:U.Watching|U.RecursedCheck,notify(){let e=this.flags;e&U.Dirty||e&U.Pending&&Ko(this.deps,this)?t():this.flags=U.Watching},stop(){this.flags=U.None,this.depsTail=void 0,$o(this)}};return t(),n}var rs={get(){},subscribe(){return{unsubscribe(){}}}};function is(e,t){let n=V.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=S(n.current,i):i}}function as(e){let t=ue(),n=V.useContext(e.from?Ro:Lo),r=e.from?t.stores.getRouteMatchStore(e.from):t.stores.matchStores.get(n),i=is(e,t),a=w(r??rs,e=>e?i(e):rs);if(a!==rs)return a;(e.shouldThrow??!0)&&ce()}function os(e){return as({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function ss(e){let{select:t,...n}=e;return as({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function cs(e){return as({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function ls(e){return as({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function us(e){let t=ue();return V.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function ds(e){let t=ue(),n=us(),r=V.useRef(null);return re(()=>{r.current!==e&&(n(e),r.current=e)},[t,e,n]),null}function fs(e){return as({...e,select:t=>e.select?e.select(t.context):t.context})}var ps=class extends cn{constructor(e){super(e),this.useMatch=e=>as({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>fs({...e,from:this.id}),this.useSearch=e=>ls({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>cs({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>ss({...e,from:this.id}),this.useLoaderData=e=>os({...e,from:this.id}),this.useNavigate=()=>us({from:this.fullPath}),this.Link=V.forwardRef((e,t)=>(0,H.jsx)(oe,{ref:t,from:this.fullPath,...e}))}};function ms(e){return new ps(e)}var hs=class extends ln{constructor(e){super(e),this.useMatch=e=>as({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>fs({...e,from:this.id}),this.useSearch=e=>ls({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>cs({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>ss({...e,from:this.id}),this.useLoaderData=e=>os({...e,from:this.id}),this.useNavigate=()=>us({from:this.fullPath}),this.Link=V.forwardRef((e,t)=>(0,H.jsx)(oe,{ref:t,from:this.fullPath,...e}))}};function gs(e){return new hs(e)}function _s(e){return new vs(e,{silent:!0}).createRoute}var vs=class{constructor(e,t){this.path=e,this.createRoute=e=>{let t=ms(e);return t.isRoot=!1,t},this.silent=t?.silent}};function ys(e,t){let n,r,a,o,s=()=>(n||=e().then(e=>{n=void 0,r=e[t??`default`]}).catch(e=>{if(a=e,i(a)&&a instanceof Error&&typeof window<`u`&&typeof sessionStorage<`u`){let e=`tanstack_router_reload:${a.message}`;sessionStorage.getItem(e)||(sessionStorage.setItem(e,`1`),o=!0)}}),n),c=function(e){if(o)throw window.location.reload(),new Promise(()=>{});if(a)throw a;if(!r)if(ne)ne(s());else throw s();return V.createElement(r,e)};return c.preload=s,c}function bs(e){let t=ue(),n=`not-found-${w(t.stores.location,e=>e.pathname)}-${w(t.stores.status,e=>e)}`;return(0,H.jsx)(Po,{getResetKey:()=>n,onCatch:(t,n)=>{if(je(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(je(t))return e.fallback?.(t);throw t},children:e.children})}function xs(){return(0,H.jsx)(`p`,{children:`Not Found`})}function Ss(e){return(0,H.jsx)(H.Fragment,{children:e.children})}function Cs(e,t,n){return t.options.notFoundComponent?(0,H.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,H.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,H.jsx)(xs,{})}var ws=(e,t)=>e.routeId===t.routeId&&e._displayPending===t._displayPending,Ts=(e,t)=>e[0]===t[0]&&e[1]===t[1],Es=V.memo(function({matchId:e}){let t=ue(),n=t.stores.matchStores.get(e);n||ce();let r=w(t.stores.loadedAt,e=>e),i=w(n,e=>e,ws);return(0,H.jsx)(Ds,{router:t,matchId:e,resetKey:r,matchState:V.useMemo(()=>{let e=i.routeId,n=t.routesById[e].parentRoute?.id;return{routeId:e,ssr:i.ssr,_displayPending:i._displayPending,parentRouteId:n}},[i._displayPending,i.routeId,i.ssr,t.routesById])})});function Ds({router:e,matchId:t,resetKey:n,matchState:r}){let i=e.routesById[r.routeId],a=i.options.pendingComponent??e.options.defaultPendingComponent,o=a?(0,H.jsx)(a,{}):null,s=i.options.errorComponent??e.options.defaultErrorComponent,c=i.options.onCatch??e.options.defaultOnCatch,l=i.isRoot?i.options.notFoundComponent??e.options.notFoundRoute?.options.component:i.options.notFoundComponent,u=r.ssr===!1||r.ssr===`data-only`,d=(!i.isRoot||i.options.wrapInSuspense||u)&&(i.options.wrapInSuspense??a??(i.options.errorComponent?.preload||u))?V.Suspense:Ss,f=s?Po:Ss,p=l?bs:Ss;return(0,H.jsxs)(i.isRoot?i.options.shellComponent??Ss:Ss,{children:[(0,H.jsx)(Lo.Provider,{value:t,children:(0,H.jsx)(d,{fallback:o,children:(0,H.jsx)(f,{getResetKey:()=>n,errorComponent:s||Io,onCatch:(e,t)=>{if(je(e))throw e.routeId??=r.routeId,e;c?.(e,t)},children:(0,H.jsx)(p,{fallback:e=>{if(e.routeId??=r.routeId,!l||e.routeId&&e.routeId!==r.routeId||!e.routeId&&!i.isRoot)throw e;return V.createElement(l,e)},children:u||r._displayPending?(0,H.jsx)(te,{fallback:o,children:(0,H.jsx)(ks,{matchId:t})}):(0,H.jsx)(ks,{matchId:t})})})})}),r.parentRouteId===`__root__`?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Os,{}),(e.options.scrollRestoration,null)]}):null]})}function Os(){let e=ue(),t=V.useRef();return re(()=>{let n=e.stores.resolvedLocation.get(),r=t.current;n&&(!r||r.href!==n.href)&&e.emit({type:`onRendered`,...Ht(e.stores.location.get(),r??n)}),t.current=n},[w(e.stores.resolvedLocation,e=>e?.state.__TSR_key),e]),null}var ks=V.memo(function({matchId:e}){let t=ue(),n=(e,n)=>t.getMatch(e.id)?._nonReactive[n]??e._nonReactive[n],r=t.stores.matchStores.get(e);r||ce();let i=w(r,e=>e),a=i.routeId,o=t.routesById[a],s=V.useMemo(()=>{let e=(t.routesById[a].options.remountDeps??t.options.defaultRemountDeps)?.({routeId:a,loaderDeps:i.loaderDeps,params:i._strictParams,search:i._strictSearch});return e?JSON.stringify(e):void 0},[a,i.loaderDeps,i._strictParams,i._strictSearch,t.options.defaultRemountDeps,t.routesById]),c=V.useMemo(()=>{let e=o.options.component??t.options.defaultComponent;return e?(0,H.jsx)(e,{},s):(0,H.jsx)(As,{})},[s,o.options.component,t.options.defaultComponent]);if(i._displayPending)throw n(i,`displayPendingPromise`);if(i._forcePending)throw n(i,`minPendingPromise`);if(i.status===`pending`){let e=o.options.pendingMinMs??t.options.defaultPendingMinMs;if(e){let n=t.getMatch(i.id);if(n&&!n._nonReactive.minPendingPromise){let t=p();n._nonReactive.minPendingPromise=t,setTimeout(()=>{t.resolve(),n._nonReactive.minPendingPromise=void 0},e)}}throw n(i,`loadPromise`)}if(i.status===`notFound`)return je(i.error)||ce(),Cs(t,o,i.error);if(i.status===`redirected`)throw tt(i.error)||ce(),n(i,`loadPromise`);if(i.status===`error`)throw i.error;return c}),As=V.memo(function(){let e=ue(),t=V.useContext(Lo),n,r=!1,i;{let a=t?e.stores.matchStores.get(t):void 0;[n,r]=w(a,e=>[e?.routeId,e?.globalNotFound??!1],Ts),i=w(e.stores.matchesId,e=>e[e.findIndex(e=>e===t)+1])}let a=n?e.routesById[n]:void 0,o=e.options.defaultPendingComponent?(0,H.jsx)(e.options.defaultPendingComponent,{}):null;if(r)return a||ce(),Cs(e,a,void 0);if(!i)return null;let s=(0,H.jsx)(Es,{matchId:i});return n===`__root__`?(0,H.jsx)(V.Suspense,{fallback:o,children:s}):s});function js(){let e=ue(),t=V.useRef({router:e,mounted:!1}),[n,r]=V.useState(!1),i=w(e.stores.isLoading,e=>e),a=w(e.stores.hasPending,e=>e),o=de(i),s=i||n||a,c=de(s),l=i||a,u=de(l);return e.startTransition=e=>{r(!0),V.startTransition(()=>{e(),r(!1)})},V.useEffect(()=>{let t=e.history.subscribe(e.load),n=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return he(e.latestLocation.publicHref)!==he(n.publicHref)&&e.commitLocation({...n,replace:!0}),()=>{t()}},[e,e.history]),re(()=>{typeof window<`u`&&e.ssr||t.current.router===e&&t.current.mounted||(t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(e){console.error(e)}})())},[e]),re(()=>{o&&!i&&e.emit({type:`onLoad`,...Ht(e.stores.location.get(),e.stores.resolvedLocation.get())})},[o,e,i]),re(()=>{u&&!l&&e.emit({type:`onBeforeRouteMount`,...Ht(e.stores.location.get(),e.stores.resolvedLocation.get())})},[l,u,e]),re(()=>{if(c&&!s){let t=Ht(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:`onResolved`,...t}),Qo(()=>{e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())})}},[s,c,e]),null}function Ms(){let e=ue(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,n=t?(0,H.jsx)(t,{}):null,r=(0,H.jsxs)(typeof document<`u`&&e.ssr?Ss:V.Suspense,{fallback:n,children:[(0,H.jsx)(js,{}),(0,H.jsx)(Ns,{})]});return e.options.InnerWrap?(0,H.jsx)(e.options.InnerWrap,{children:r}):r}function Ns(){let e=ue(),t=w(e.stores.firstId,e=>e),n=w(e.stores.loadedAt,e=>e),r=t?(0,H.jsx)(Es,{matchId:t}):null;return(0,H.jsx)(Lo.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:(0,H.jsx)(Po,{getResetKey:()=>n,errorComponent:Io,onCatch:void 0,children:r})})}var Ps=e=>({createMutableStore:ts,createReadonlyStore:ts,batch:Qo}),Fs=e=>new Is(e),Is=class extends Ut{constructor(e){super(e,Ps)}};function Ls({router:e,children:t,...n}){_(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,H.jsx)(fe.Provider,{value:e,children:t});return e.options.Wrap?(0,H.jsx)(e.options.Wrap,{children:r}):r}function Rs({router:e,...t}){return(0,H.jsx)(Ls,{router:e,...t,children:(0,H.jsx)(Ms,{})})}function zs(e,t){if(t)for(let[n,r]of Object.entries(t))n!==`suppressHydrationWarning`&&r!==void 0&&r!==!1&&e.setAttribute(n,typeof r==`boolean`?``:String(r))}function Bs(e){let{attrs:t,children:n,nonce:r,preventScriptHoist:i}=e;switch(e.tag){case`title`:return(0,H.jsx)(`title`,{...t,suppressHydrationWarning:!0,children:n});case`meta`:return(0,H.jsx)(`meta`,{...t,suppressHydrationWarning:!0});case`link`:return(0,H.jsx)(`link`,{...t,precedence:t?.precedence??(t?.rel===`stylesheet`?`default`:void 0),nonce:r,suppressHydrationWarning:!0});case`style`:return e.inlineCss,(0,H.jsx)(`style`,{...t,dangerouslySetInnerHTML:{__html:n},nonce:r});case`script`:return(0,H.jsx)(Vs,{attrs:t,preventScriptHoist:i,children:n});default:return null}}function Vs({attrs:e,children:t,preventScriptHoist:n}){ue();let r=le(),i=typeof e?.type==`string`&&e.type!==``&&e.type!==`text/javascript`&&e.type!==`module`;if(V.useEffect(()=>{if(!i){if(e?.src){let t=(()=>{try{let t=document.baseURI||window.location.href;return new URL(e.src,t).href}catch{return e.src}})();for(let e of document.querySelectorAll(`script[src]`))if(e.src===t)return;let n=document.createElement(`script`);return zs(n,e),document.head.appendChild(n),()=>n.remove()}if(typeof t==`string`){let n=typeof e?.type==`string`?e.type:`text/javascript`,r=typeof e?.nonce==`string`?e.nonce:void 0;for(let e of document.querySelectorAll(`script:not([src])`)){if(!(e instanceof HTMLScriptElement))continue;let i=e.getAttribute(`type`)??`text/javascript`,a=e.getAttribute(`nonce`)??void 0;if(e.textContent===t&&i===n&&a===r)return}let i=document.createElement(`script`);return i.textContent=t,zs(i,e),document.head.appendChild(i),()=>i.remove()}}},[e,t,i]),i&&typeof t==`string`)return(0,H.jsx)(`script`,{...e,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:t}});if(!r){if(e?.src)return(0,H.jsx)(`script`,{...e,suppressHydrationWarning:!0});if(typeof t==`string`)return(0,H.jsx)(`script`,{...e,dangerouslySetInnerHTML:{__html:t},suppressHydrationWarning:!0})}return null}var Hs=e=>{let t=ue(),n=t.options.ssr?.nonce,r=w(t.stores.matches,e=>e.map(e=>e.meta).filter(e=>e!==void 0),g),i=V.useMemo(()=>{let e=[],t={},i;for(let a=r.length-1;a>=0;a--){let o=r[a];for(let r=o.length-1;r>=0;r--){let a=o[r];if(a)if(a.title)i||={tag:`title`,children:a.title};else if(`script:ld+json`in a)try{let t=JSON.stringify(a[`script:ld+json`]);e.push({tag:`script`,attrs:{type:`application/ld+json`},children:d(t)})}catch{}else{let r=a.name??a.property;if(r){if(t[r])continue;t[r]=!0}e.push({tag:`meta`,attrs:{...a,nonce:n}})}}}return i&&e.push(i),n&&e.push({tag:`meta`,attrs:{property:`csp-nonce`,content:n}}),e.reverse(),e},[r,n]),a=w(t.stores.matches,e=>e.flatMap(e=>e.links??[]).filter(e=>e!==void 0).map(e=>({tag:`link`,attrs:{...e,nonce:n}})),g),o=w(t.stores.matches,r=>{let i=t.ssr?.manifest,a=[];return i?(r.forEach(t=>{i.routes[t.routeId]?.css?.forEach(t=>{let r=sn(t);a.push({tag:`link`,attrs:{rel:`stylesheet`,...r,crossOrigin:tn(e,`stylesheet`)??r.crossOrigin,suppressHydrationWarning:!0,nonce:n}})})}),i.inlineStyle&&a.push({tag:`style`,attrs:{...i.inlineStyle.attrs,nonce:n},children:i.inlineStyle.children,inlineCss:!0}),a):a},g),s=w(t.stores.matches,r=>{let i=[],a=t.ssr?.manifest;return a&&r.forEach(t=>{a.routes[t.routeId]?.preloads?.forEach(t=>{i.push({tag:`link`,attrs:{...rn(a,t,e),nonce:n}})})}),i},g),c=w(t.stores.matches,e=>e.flatMap(e=>e.styles??[]).filter(e=>e!==void 0).map(({children:e,...t})=>({tag:`style`,attrs:{...t,nonce:n},children:e})),g),l=w(t.stores.matches,e=>e.flatMap(e=>e.headScripts??[]).filter(e=>e!==void 0).map(({children:e,...t})=>({tag:`script`,attrs:{...t,nonce:n},children:e})),g),u=[];return on(u,i),u.push(...s),on(u,a),u.push(...o),on(u,c),on(u,l),u};function Us(e){let t=Hs(e.assetCrossOrigin),n=ue().options.ssr?.nonce;return(0,H.jsx)(H.Fragment,{children:t.map(e=>(0,V.createElement)(Bs,{...e,key:`tsr-meta-${JSON.stringify(e)}`,nonce:n}))})}var Ws=()=>{let e=ue(),t=e.options.ssr?.nonce,n=n=>{let r=[],i=e.ssr?.manifest;if(!i)return[];for(let e of n){let n=i.routes[e.routeId]?.scripts;if(n)for(let e of n)r.push({tag:`script`,attrs:{...e.attrs,nonce:t},children:e.children,...typeof e.attrs?.src==`string`?{preventScriptHoist:!0}:{}})}return r},r=e=>e.map(e=>e.scripts).flat(1).filter(Boolean).map(({children:e,...n})=>({tag:`script`,attrs:{...n,suppressHydrationWarning:!0,nonce:t},children:e})),i=w(e.stores.matches,n,g);return Gs(e,w(e.stores.matches,r,g),i)};function Gs(e,t,n){let r=[...t,...n];return(0,H.jsx)(H.Fragment,{children:r.map((e,t)=>(0,V.createElement)(Bs,{...e,key:`tsr-scripts-${e.tag}-${t}`}))})}function Ks({children:e}){return(0,H.jsx)(H.Fragment,{children:e})}var qs=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},Js=(e=>e?qs(e):qs),Ys=e=>e;function Xs(e,t=Ys){let n=V.useSyncExternalStore(e.subscribe,V.useCallback(()=>t(e.getState()),[e,t]),V.useCallback(()=>t(e.getInitialState()),[e,t]));return V.useDebugValue(n),n}var Zs=e=>{let t=Js(e),n=e=>Xs(t,e);return Object.assign(n,t),n},Qs=(e=>e?Zs(e):Zs);function $s(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var ec=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return ec(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return ec(t)(e)}}}},tc=(e,t)=>(n,r,i)=>{let a={storage:$s(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(e,t)=>(f(e,t),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return ec(u.getItem.bind(u))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p};function nc(...e){return e.map(e=>({id:D(`b`),type:e.type,content:e.content??``,checked:e.checked,collapsed:e.collapsed,indent:e.indent??0,showSource:e.showSource,aiOutput:e.aiOutput}))}function rc(e){let t=Date.now();return{id:D(`page`),title:``,icon:`📄`,cover:null,parentId:null,favorite:!1,createdAt:t,updatedAt:t,blocks:nc({type:`paragraph`,content:``}),archived:!1,...e}}function ic(){let e=rc({title:`Getting Started`,icon:`🚀`,cover:`warm`,favorite:!0,blocks:nc({type:`paragraph`,content:`Welcome to ForgeNotes — notes, AI assist, Mermaid diagrams, and optional database sync.`},{type:`heading1`,content:`What you can do`},{type:`bullet`,content:`Create pages from the sidebar`},{type:`bullet`,content:`Type / for block types — try AI and Mermaid`},{type:`bullet`,content:`Hover a block → ⋮⋮ menu → Edit with AI`},{type:`bullet`,content:`Sign in to sync pages to the database`},{type:`bullet`,content:`Search with ⌘K / Ctrl+K`},{type:`heading2`,content:`Try AI`},{type:`ai`,content:`Summarize this page as three bullets for a new teammate`},{type:`heading2`,content:`Mermaid`},{type:`mermaid`,content:`flowchart LR + Write[Write notes] --> AI[AI block] + AI --> Diagram[Mermaid] + Diagram --> Ship[Ship]`,showSource:!1},{type:`heading2`,content:`Basics`},{type:`todo`,content:`Rename this page title`,checked:!1},{type:`todo`,content:`Run the AI block above`,checked:!1},{type:`todo`,content:`Toggle Mermaid source / preview`,checked:!0},{type:`callout`,content:`Tip: slash /ai or /mermaid. AI uses Grok when XAI_API_KEY is set; otherwise a local demo mode.`},{type:`quote`,content:`Write first. Organize later.`},{type:`code`,content:`function hello() { + console.log("hello workspace"); +}`},{type:`divider`,content:``},{type:`paragraph`,content:`This starter page is yours — edit freely or start a blank page.`})}),t=rc({title:`Product Spec`,icon:`📋`,parentId:e.id,blocks:nc({type:`heading1`,content:`Overview`},{type:`paragraph`,content:`A lightweight personal knowledge base with nested pages, AI, and diagrams.`},{type:`heading2`,content:`Goals`},{type:`numbered`,content:`Capture ideas without friction`},{type:`numbered`,content:`Structure docs with nested pages`},{type:`numbered`,content:`Use AI for summaries and checklists`},{type:`heading2`,content:`Non-goals`},{type:`bullet`,content:`Real-time multiplayer (for now)`},{type:`bullet`,content:`Full offline multi-device without sign-in`},{type:`mermaid`,content:`sequenceDiagram + participant U as User + participant A as App + participant D as Database + U->>A: Edit page + A->>D: Save (when signed in)`,showSource:!1})}),n=rc({title:`Weekly Notes`,icon:`📅`,favorite:!0,cover:`cool`,blocks:nc({type:`heading1`,content:`This week`},{type:`todo`,content:`Ship the block editor`,checked:!0},{type:`todo`,content:`Add AI + Mermaid`,checked:!0},{type:`todo`,content:`Write release notes`,checked:!1},{type:`heading2`,content:`Notes`},{type:`paragraph`,content:`Keep daily fragments here. Promote anything durable into its own page.`},{type:`ai`,content:`Turn the todos and notes above into a short status update for stakeholders`},{type:`callout`,content:`Use favorites for the 2–3 pages you open every day.`})});return{pages:[e,t,n,rc({title:`Reading List`,icon:`📚`,blocks:nc({type:`heading2`,content:`Queue`},{type:`todo`,content:`Atomic Habits — James Clear`,checked:!1},{type:`todo`,content:`The Design of Everyday Things`,checked:!1},{type:`todo`,content:`Staff Engineer — Will Larson`,checked:!0},{type:`heading2`,content:`Quotes`},{type:`quote`,content:`Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away.`})}),rc({title:`Meeting Notes`,icon:`🗒`,parentId:n.id,blocks:nc({type:`heading1`,content:`Kickoff`},{type:`paragraph`,content:`Attendees: design, eng, product`},{type:`bullet`,content:`Align on v1 scope`},{type:`bullet`,content:`Decide on editor primitives`},{type:`bullet`,content:`Ship a polished demo`},{type:`divider`,content:``},{type:`heading3`,content:`Action items`},{type:`todo`,content:`Draft IA for sidebar`,checked:!0},{type:`todo`,content:`Prototype slash menu`,checked:!0},{type:`todo`,content:`Add AI edit-with-block`,checked:!0})})],activePageId:e.id}}var ac=`📄.📝.📋.📚.💡.🎯.🚀.⭐.🏠.📁.🗂.📅.✅.🔧.🎨.🧠.🌱.🔥.☕.🗒.📦.🧭.🛠.💬.📊.🔍.✨.🏷.📎.🛡`.split(`.`),oc={warm:{label:`Warm`,className:`bg-gradient-to-br from-stone-200 via-amber-100/80 to-orange-100/60`},cool:{label:`Cool`,className:`bg-gradient-to-br from-slate-200 via-sky-100/70 to-stone-100`},soft:{label:`Soft`,className:`bg-gradient-to-br from-zinc-200 via-neutral-100 to-stone-50`},ink:{label:`Ink`,className:`bg-gradient-to-br from-zinc-800 via-stone-700 to-neutral-800`}};function sc(e){return{...e,updatedAt:Date.now()}}function cc(e,t){let n=new Set([t]),r=!0;for(;r;){r=!1;for(let t of e)t.parentId&&n.has(t.parentId)&&!n.has(t.id)&&(n.add(t.id),r=!0)}return n}function lc(e){return e.map(e=>({...e,id:D(`b`)}))}var uc=ic(),dc=Qs()(tc((e,t)=>({name:`ForgeNotes`,pages:uc.pages,activePageId:uc.activePageId,sidebarOpen:!0,theme:`light`,hydrated:!1,storageMode:`local`,syncStatus:`local`,setHydrated:t=>e({hydrated:t}),setName:t=>e({name:t}),setSidebarOpen:t=>e({sidebarOpen:t}),toggleSidebar:()=>e(e=>({sidebarOpen:!e.sidebarOpen})),setTheme:t=>e({theme:t}),setActivePage:t=>e({activePageId:t}),setStorageMode:t=>e({storageMode:t}),setSyncStatus:t=>e({syncStatus:t}),loadFromRemote:t=>e({name:t.name,pages:t.pages,activePageId:t.activePageId,sidebarOpen:t.sidebarOpen,theme:t.theme,storageMode:`database`,syncStatus:`saved`,hydrated:!0}),getPage:e=>t().pages.find(t=>t.id===e),getChildren:e=>t().pages.filter(t=>!t.archived&&t.parentId===e).sort((e,t)=>e.createdAt-t.createdAt),createPage:t=>{let n=rc({parentId:t?.parentId??null,title:t?.title??``,icon:t?.icon});return e(e=>({pages:[...e.pages,n],activePageId:n.id})),n.id},updatePage:(t,n)=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,...n}):e)})),deletePage:n=>{let r=cc(t().pages,n);e(e=>{let t=e.pages.map(e=>r.has(e.id)?sc({...e,archived:!0,favorite:!1}):e),n=e.activePageId;return n&&r.has(n)&&(n=t.find(e=>!e.archived&&!r.has(e.id))?.id??null),{pages:t,activePageId:n}})},restorePage:t=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,archived:!1,parentId:null}):e)})),permanentlyDeletePage:n=>{let r=cc(t().pages,n);e(e=>{let t=e.pages.filter(e=>!r.has(e.id)),n=e.activePageId;return n&&r.has(n)&&(n=t.find(e=>!e.archived)?.id??null),{pages:t,activePageId:n}})},duplicatePage:n=>{let r=t().pages.find(e=>e.id===n);if(!r)return null;let i=rc({title:r.title?`${r.title} (copy)`:`Untitled (copy)`,icon:r.icon,cover:r.cover,parentId:r.parentId,favorite:!1,blocks:lc(r.blocks)});return e(e=>({pages:[...e.pages,i],activePageId:i.id})),i.id},movePage:(n,r)=>{n!==r&&(r&&cc(t().pages,n).has(r)||e(e=>({pages:e.pages.map(e=>e.id===n?sc({...e,parentId:r}):e)})))},setBlocks:(t,n)=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,blocks:n}):e)})),updateBlock:(t,n,r)=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,blocks:e.blocks.map(e=>e.id===n?{...e,...r}:e)}):e)})),insertBlock:(t,n,r=`paragraph`,i=``)=>{let a={id:D(`b`),type:r,content:i,indent:0};return e(e=>({pages:e.pages.map(e=>{if(e.id!==t)return e;let r=[...e.blocks];if(!n)r.unshift(a);else{let e=r.findIndex(e=>e.id===n);e>=0?r.splice(e+1,0,a):r.push(a)}return sc({...e,blocks:r})})})),a.id},deleteBlock:(t,n)=>e(e=>({pages:e.pages.map(e=>{if(e.id!==t)return e;let r=e.blocks.filter(e=>e.id!==n);return r.length===0&&(r=[{id:D(`b`),type:`paragraph`,content:``,indent:0}]),sc({...e,blocks:r})})})),changeBlockType:(t,n,r)=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,blocks:e.blocks.map(e=>e.id===n?{...e,type:r,checked:r===`todo`?e.checked??!1:void 0}:e)}):e)})),moveBlock:(t,n,r)=>e(e=>({pages:e.pages.map(e=>{if(e.id!==t)return e;let i=[...e.blocks],a=i.findIndex(e=>e.id===n);if(a<0)return e;let o=r===`up`?a-1:a+1;if(o<0||o>=i.length)return e;let s=i[a];return i[a]=i[o],i[o]=s,sc({...e,blocks:i})})})),importPages:(t,n)=>e(e=>({pages:[...e.pages,...t],activePageId:n??t[0]?.id??e.activePageId})),resetWorkspace:()=>{let t=ic();e({name:`ForgeNotes`,pages:t.pages,activePageId:t.activePageId,sidebarOpen:!0,theme:`light`,storageMode:`local`,syncStatus:`local`})}}),{name:`workspace-v1`,partialize:e=>({name:e.name,pages:e.pages,activePageId:e.activePageId,sidebarOpen:e.sidebarOpen,theme:e.theme}),onRehydrateStorage:()=>e=>{e?.setHydrated(!0)}}));function fc(){let e=dc(e=>e.theme);(0,V.useEffect)(()=>{let t=document.documentElement;e===`dark`?t.classList.add(`dark`):t.classList.remove(`dark`)},[e])}var pc=`forgenotes-zoom`,mc=[.75,.85,1,1.15,1.3,1.5,1.75,2];function hc(e){let t=0;for(let n=1;n`u`)return 1;let e=Number.parseFloat(window.localStorage.getItem(pc)??``);return!Number.isFinite(e)||e<=0?1:Math.min(mc.at(-1),Math.max(mc[0],e))}function vc(e){document.documentElement.style.fontSize=e===1?``:`${e*100}%`}function yc(){(0,V.useEffect)(()=>{let e=_c();vc(e);let t=t=>{if(!(t.metaKey||t.ctrlKey)||t.altKey)return;let n=t.key===`=`||t.key===`+`?1:t.key===`-`||t.key===`_`?-1:t.key===`0`?0:null;if(n===null)return;let r=gc(e,n);t.preventDefault(),r!==e&&(e=r,vc(e),window.localStorage.setItem(pc,String(e)))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[])}function bc(){(0,V.useEffect)(()=>{},[])}var xc=`/assets/styles-Peq6Rcdg.css`,Sc=gs({head:()=>({meta:[{charSet:`utf-8`},{name:`viewport`,content:`width=device-width, initial-scale=1`},{title:`ForgeNotes — notes, AI & harness`},{name:`description`,content:`ForgeNotes is a Notion-style workspace for notes, AI (Deep Agents & coding CLIs), markdown, and agent workflows.`}],links:[{rel:`stylesheet`,href:xc}]}),component:Cc});function Cc(){return fc(),yc(),bc(),(0,H.jsxs)(`html`,{lang:`en`,suppressHydrationWarning:!0,children:[(0,H.jsx)(`head`,{children:(0,H.jsx)(Us,{})}),(0,H.jsxs)(`body`,{children:[(0,H.jsx)(Ks,{children:(0,H.jsx)(As,{})}),(0,H.jsx)(Ws,{})]})]})}var wc=`modulepreload`,Tc=function(e){return`/`+e},Ec={},Dc=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Tc(t,n),t=s(t),t in Ec)return;Ec[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:wc,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Oc=_s(`/`)({component:ys(()=>Dc(()=>import(`./routes-BDn33g5C.js`),__vite__mapDeps([0,1,2,3,4,5])),`component`)}),kc=_s(`/login`)({component:ys(()=>Dc(()=>import(`./login-xkhUej_P.js`),__vite__mapDeps([6,1,2,3,4,5])),`component`)}),Ac={IndexRoute:Oc.update({id:`/`,path:`/`,getParentRoute:()=>Sc}),LoginRoute:kc.update({id:`/login`,path:`/login`,getParentRoute:()=>Sc})},jc=Sc._addFileChildren(Ac);function Mc(){return Fs({routeTree:jc})}async function Nc(){let e=await Mc(),t=[];return window.__TSS_START_OPTIONS__={serializationAdapters:t},t.push(Do),e.options.serializationAdapters&&t.push(...e.options.serializationAdapters),e.update({basepath:``,serializationAdapters:t}),e.stores.matchesId.get().length||await Ao(e),e}var Pc=Nc;async function Fc(){let e=await Pc();return window.$_TSR?.h(),e}var Ic;function Lc(){return Ic||=Fc(),(0,H.jsx)(Mo,{promise:Ic,children:e=>(0,H.jsx)(Rs,{router:e})})}var Rc=xe();(0,V.startTransition)(()=>{(0,Rc.hydrateRoot)(document,(0,H.jsx)(V.StrictMode,{children:(0,H.jsx)(Lc,{})}))});export{rc as a,ds as c,nt as d,Ae as f,ac as i,Eo as l,dc as n,tc as o,we as p,oc as r,Qs as s,Dc as t,tt as u}; \ No newline at end of file diff --git a/.vercel/output/static/assets/index-DU4A6Ttf.js b/.vercel/output/static/assets/index-DU4A6Ttf.js deleted file mode 100644 index 0f76b81..0000000 --- a/.vercel/output/static/assets/index-DU4A6Ttf.js +++ /dev/null @@ -1,12 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/routes-C6kpKjAV.js","assets/rolldown-runtime-QTnfLwEv.js","assets/react-Biaal4sZ.js","assets/link-DYUXAN0T.js","assets/client-8boibB1R.js","assets/use-current-user-BkYwj4ZJ.js","assets/login-C3NWOInE.js"])))=>i.map(i=>d[i]); -import{r as e,t}from"./rolldown-runtime-QTnfLwEv.js";import{t as n}from"./react-Biaal4sZ.js";import{A as r,B as i,C as a,D as o,E as s,F as c,H as l,I as u,L as d,M as f,N as p,O as m,P as h,R as g,S as _,T as v,V as y,_ as b,a as x,b as S,c as C,d as ee,f as te,g as ne,h as re,i as ie,j as ae,k as oe,l as se,m as ce,n as w,o as le,p as E,r as D,s as ue,t as de,u as fe,v as pe,w as me,x as O,y as he,z as ge}from"./link-DYUXAN0T.js";var _e=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,ie());else{var t=n(l);t!==null&&se(x,t.startTime-e)}}var S=!1,C=-1,ee=5,te=-1;function ne(){return g?!0:!(e.unstable_now()-tet&&ne());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&se(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ie():S=!1}}}var ie;if(typeof y==`function`)ie=function(){y(re)};else if(typeof MessageChannel<`u`){var ae=new MessageChannel,oe=ae.port2;ae.port1.onmessage=re,ie=function(){oe.postMessage(null)}}else ie=function(){_(re,0)};function se(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,se(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,ie()))),r},e.unstable_shouldYield=ne,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),ve=t(((e,t)=>{t.exports=_e()})),ye=t((e=>{var t=ve(),r=n(),i=l();function a(e){var t=`https://react.dev/errors/`+e;if(1fe||(e.current=de[fe],de[fe]=null,fe--)}function O(e,t){fe++,de[fe]=e.current,e.current=t}var he=pe(null),ge=pe(null),_e=pe(null),ye=pe(null);function be(e,t){switch(O(_e,t),O(ge,e),O(he,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Hd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Hd(t),e=Ud(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}me(he),O(he,e)}function xe(){me(he),me(ge),me(_e)}function Se(e){e.memoizedState!==null&&O(ye,e);var t=he.current,n=Ud(t,e.type);t!==n&&(O(ge,e),O(he,n))}function Ce(e){ge.current===e&&(me(he),me(ge)),ye.current===e&&(me(ye),$f._currentValue=ue)}var we,Te;function Ee(e){if(we===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);we=t&&t[1]||``,Te=-1)`:-1i||c[r]!==l[i]){var u=` -`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{De=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ee(n):``}function ke(e,t){switch(e.tag){case 26:case 27:case 5:return Ee(e.type);case 16:return Ee(`Lazy`);case 13:return e.child!==t&&t!==null?Ee(`Suspense Fallback`):Ee(`Suspense`);case 19:return Ee(`SuspenseList`);case 0:case 15:return Oe(e.type,!1);case 11:return Oe(e.type.render,!1);case 1:return Oe(e.type,!0);case 31:return Ee(`Activity`);default:return``}}function Ae(e){try{var t=``,n=null;do t+=ke(e,n),n=e,e=e.return;while(e);return t}catch(e){return` -Error generating stack: `+e.message+` -`+e.stack}}var je=Object.prototype.hasOwnProperty,Me=t.unstable_scheduleCallback,Ne=t.unstable_cancelCallback,Pe=t.unstable_shouldYield,Fe=t.unstable_requestPaint,Ie=t.unstable_now,Le=t.unstable_getCurrentPriorityLevel,Re=t.unstable_ImmediatePriority,ze=t.unstable_UserBlockingPriority,Be=t.unstable_NormalPriority,Ve=t.unstable_LowPriority,He=t.unstable_IdlePriority,Ue=t.log,We=t.unstable_setDisableYieldValue,Ge=null,Ke=null;function qe(e){if(typeof Ue==`function`&&We(e),Ke&&typeof Ke.setStrictMode==`function`)try{Ke.setStrictMode(Ge,e)}catch{}}var Je=Math.clz32?Math.clz32:Ze,Ye=Math.log,Xe=Math.LN2;function Ze(e){return e>>>=0,e===0?32:31-(Ye(e)/Xe|0)|0}var Qe=256,$e=262144,et=4194304;function tt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function nt(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=tt(n))):i=tt(o):i=tt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=tt(n))):i=tt(o)):i=tt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function rt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function it(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function at(){var e=et;return et<<=1,!(et&62914560)&&(et=4194304),e}function ot(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function st(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function ct(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),bn=!1;if(yn)try{var xn={};Object.defineProperty(xn,"passive",{get:function(){bn=!0}}),window.addEventListener(`test`,xn,xn),window.removeEventListener(`test`,xn,xn)}catch{bn=!1}var Sn=null,Cn=null,A=null;function wn(){if(A)return A;var e,t=Cn,n=t.length,r,i=`value`in Sn?Sn.value:Sn.textContent,a=i.length;for(e=0;e=tr),ir=` `,ar=!1;function or(e,t){switch(e){case`keyup`:return $n.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function sr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var cr=!1;function lr(e,t){switch(e){case`compositionend`:return sr(t);case`keypress`:return t.which===32?(ar=!0,ir):null;case`textInput`:return e=t.data,e===ir&&ar?null:e;default:return null}}function ur(e,t){if(cr)return e===`compositionend`||!er&&or(e,t)?(e=wn(),A=Cn=Sn=null,cr=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Mr(n)}}function Pr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Pr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Fr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Kt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Kt(e.document)}return t}function Ir(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Lr=yn&&`documentMode`in document&&11>=document.documentMode,Rr=null,zr=null,Br=null,Vr=!1;function Hr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Vr||Rr==null||Rr!==Kt(r)||(r=Rr,`selectionStart`in r&&Ir(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Br&&jr(Br,r)||(Br=r,r=Dd(zr,`onSelect`),0>=o,i-=o,Pi=1<<32-Je(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),N&&Ii(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),N&&Ii(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return N&&Ii(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),N&&Ii(i,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===v&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case g:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===v){if(r.tag===7){n(e,r.sibling),c=i(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===re&&Pa(l)===r.type){n(e,r.sibling),c=i(r,o.props),Ba(c,o),c.return=e,e=c;break a}n(e,r);break}else t(e,r);r=r.sibling}o.type===v?(c=xi(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=bi(o.type,o.key,o.props,null,e.mode,c),Ba(c,o),c.return=e,e=c)}return s(e);case _:a:{for(l=o.key;r!==null;){if(r.key===l)if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=i(r,o.children||[]),c.return=e,e=c;break a}else{n(e,r);break}else t(e,r);r=r.sibling}c=wi(o,e.mode,c),c.return=e,e=c}return s(e);case re:return o=Pa(o),b(e,r,o,c)}if(le(o))return h(e,r,o,c);if(se(o)){if(l=se(o),typeof l!=`function`)throw Error(a(150));return o=l.call(o),y(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,za(o),c);if(o.$$typeof===S)return b(e,r,ca(e,o),c);Va(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=i(r,o),c.return=e,e=c):(n(e,r),c=Si(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Ra=0;var i=b(e,t,n,r);return La=null,i}catch(t){if(t===Oa||t===Aa)throw t;var a=gi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Ua=Ha(!0),Wa=Ha(!1),Ga=!1;function Ka(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function qa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ja(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ya(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,K&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=pi(e),fi(e,null,n),t}return li(e,r,t,n),pi(e)}function Xa(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ut(e,n)}}function Za(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Qa=!1;function $a(){if(Qa){var e=ya;if(e!==null)throw e}}function eo(e,t,n,r){Qa=!1;var i=e.updateQueue;Ga=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(Y&f)===f:(r&f)===f){f!==0&&f===va&&(Qa=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,f);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,f=typeof h==`function`?h.call(_,d,f):h,f==null)break a;d=m({},d,f);break a;case 2:Ga=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Kl|=o,e.lanes=o,e.memoizedState=d}}function to(e,t){if(typeof e!=`function`)throw Error(a(191,e));e.call(t)}function no(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=E.T,s={};E.T=s,Fs(e,!1,t,n);try{var c=i(),l=E.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ps(e,t,Sa(c,r),mu(e)):Ps(e,t,r,mu(e))}catch(n){Ps(e,t,{then:function(){},status:`rejected`,reason:n},mu())}finally{D.p=a,o!==null&&s.types!==null&&(o.types=s.types),E.T=o}}function ws(){}function Ts(e,t,n,r){if(e.tag!==5)throw Error(a(476));var i=Es(e).queue;Cs(e,i,t,ue,n===null?ws:function(){return Ds(e),n(r)})}function Es(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ue,baseState:ue,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Lo,lastRenderedState:ue},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Lo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Ds(e){var t=Es(e);t.next===null&&(t=e.alternate.memoizedState),Ps(e,t.next.queue,{},mu())}function Os(){return sa($f)}function ks(){return Mo().memoizedState}function As(){return Mo().memoizedState}function js(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=mu();e=Ja(n);var r=Ya(t,e,n);r!==null&&(gu(r,t,n),Xa(r,t,n)),t={cache:ma()},e.payload=t;return}t=t.return}}function Ms(e,t,n){var r=mu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Is(e)?Ls(t,n):(n=ui(e,t,n,r),n!==null&&(gu(n,e,r),Rs(n,t,r)))}function Ns(e,t,n){Ps(e,t,n,mu())}function Ps(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Is(e))Ls(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Ar(s,o))return li(e,t,i,0),q===null&&ci(),!1}catch{}if(n=ui(e,t,i,r),n!==null)return gu(n,e,r),Rs(n,t,r),!0}return!1}function Fs(e,t,n,r){if(r={lane:2,revertLane:fd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Is(e)){if(t)throw Error(a(479))}else t=ui(e,n,r,2),t!==null&&gu(t,e,2)}function Is(e){var t=e.alternate;return e===L||t!==null&&t===L}function Ls(e,t){yo=vo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Rs(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ut(e,n)}}var zs={readContext:sa,use:Fo,useCallback:B,useContext:B,useEffect:B,useImperativeHandle:B,useLayoutEffect:B,useInsertionEffect:B,useMemo:B,useReducer:B,useRef:B,useState:B,useDebugValue:B,useDeferredValue:B,useTransition:B,useSyncExternalStore:B,useId:B,useHostTransitionStatus:B,useFormState:B,useActionState:B,useOptimistic:B,useMemoCache:B,useCacheRefresh:B};zs.useEffectEvent=B;var Bs={readContext:sa,use:Fo,useCallback:function(e,t){return jo().memoizedState=[e,t===void 0?null:t],e},useContext:sa,useEffect:us,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),cs(4194308,4,gs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return cs(4194308,4,e,t)},useInsertionEffect:function(e,t){cs(4,2,e,t)},useMemo:function(e,t){var n=jo();t=t===void 0?null:t;var r=e();if(bo){qe(!0);try{e()}finally{qe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=jo();if(n!==void 0){var i=n(t);if(bo){qe(!0);try{n(t)}finally{qe(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Ms.bind(null,L,e),[r.memoizedState,e]},useRef:function(e){var t=jo();return e={current:e},t.memoizedState=e},useState:function(e){e=Ko(e);var t=e.queue,n=Ns.bind(null,L,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:vs,useDeferredValue:function(e,t){return xs(jo(),e,t)},useTransition:function(){var e=Ko(!1);return e=Cs.bind(null,L,e.queue,!0,!1),jo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=L,i=jo();if(N){if(n===void 0)throw Error(a(407));n=n()}else{if(n=t(),q===null)throw Error(a(349));Y&127||Vo(r,t,n)}i.memoizedState=n;var o={value:n,getSnapshot:t};return i.queue=o,us(Uo.bind(null,r,o,e),[e]),r.flags|=2048,os(9,{destroy:void 0},Ho.bind(null,r,o,n,t),null),n},useId:function(){var e=jo(),t=q.identifierPrefix;if(N){var n=Fi,r=Pi;n=(r&~(1<<32-Je(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=xo++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(i,{is:r.is}):s.createElement(i)}}o[k]=t,o[_t]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Fd(o,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Pc(t)}}return W(t),Fc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Pc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(a(166));if(e=_e.current,Ji(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=Vi,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[k]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Nd(e.nodeValue,n)),e||Gi(t,!0)}else e=Vd(e).createTextNode(r),e[k]=t,t.stateNode=e}return W(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Ji(t),n!==null){if(e===null){if(!r)throw Error(a(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(a(557));e[k]=t}else Yi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;W(t),e=!1}else n=Xi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(ho(t),t):(ho(t),null);if(t.flags&128)throw Error(a(558))}return W(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=Ji(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(a(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(a(317));i[k]=t}else Yi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;W(t),i=!1}else i=Xi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(ho(t),t):(ho(t),null)}return ho(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Lc(t,t.updateQueue),W(t),null);case 4:return xe(),e===null&&Cd(t.stateNode.containerInfo),W(t),null;case 10:return ta(t.type),W(t),null;case 19:if(me(I),r=t.memoizedState,r===null)return W(t),null;if(i=(t.flags&128)!=0,o=r.rendering,o===null)if(i)Rc(r,!1);else{if(Gl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=go(e),o!==null){for(t.flags|=128,Rc(r,!1),e=o.updateQueue,t.updateQueue=e,Lc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)yi(n,e),n=n.sibling;return O(I,I.current&1|2),N&&Ii(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ie()>nu&&(t.flags|=128,i=!0,Rc(r,!1),t.lanes=4194304)}else{if(!i)if(e=go(o),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,Lc(t,e),Rc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!N)return W(t),null}else 2*Ie()-r.renderingStartTime>nu&&n!==536870912&&(t.flags|=128,i=!0,Rc(r,!1),t.lanes=4194304);r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(W(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ie(),e.sibling=null,n=I.current,O(I,i?n&1|2:n&1),N&&Ii(t,r.treeForkCount),e);case 22:case 23:return ho(t),so(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(W(t),t.subtreeFlags&6&&(t.flags|=8192)):W(t),n=t.updateQueue,n!==null&&Lc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&me(wa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),ta(pa),W(t),null;case 25:return null;case 30:return null}throw Error(a(156,t.tag))}function Bc(e,t){switch(zi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ta(pa),xe(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Ce(t),null;case 31:if(t.memoizedState!==null){if(ho(t),t.alternate===null)throw Error(a(340));Yi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ho(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(a(340));Yi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return me(I),null;case 4:return xe(),null;case 10:return ta(t.type),null;case 22:case 23:return ho(t),so(),e!==null&&me(wa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return ta(pa),null;case 25:return null;default:return null}}function Vc(e,t){switch(zi(t),t.tag){case 3:ta(pa),xe();break;case 26:case 27:case 5:Ce(t);break;case 4:xe();break;case 31:t.memoizedState!==null&&ho(t);break;case 13:ho(t);break;case 19:me(I);break;case 10:ta(t.type);break;case 22:case 23:ho(t),so(),e!==null&&me(wa);break;case 24:ta(pa)}}function Hc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Z(t,t.return,e)}}function Uc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Z(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Z(t,t.return,e)}}function Wc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{no(t,n)}catch(t){Z(e,e.return,t)}}}function Gc(e,t,n){n.props=qs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Z(e,t,n)}}function Kc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Z(e,t,n)}}function qc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){Z(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Z(e,t,n)}else n.current=null}function Jc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Z(e,e.return,t)}}function Yc(e,t,n){try{var r=e.stateNode;Id(r,e.type,n,t),r[_t]=t}catch(t){Z(e,e.return,t)}}function Xc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Qd(e.type)||e.tag===4}function Zc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Xc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Qd(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Qc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=un));else if(r!==4&&(r===27&&Qd(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Qc(e,t,n),e=e.sibling;e!==null;)Qc(e,t,n),e=e.sibling}function $c(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&Qd(e.type)&&(n=e.stateNode),e=e.child,e!==null))for($c(e,t,n),e=e.sibling;e!==null;)$c(e,t,n),e=e.sibling}function el(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Fd(t,r,n),t[k]=e,t[_t]=n}catch(t){Z(e,e.return,t)}}var tl=!1,nl=!1,rl=!1,il=typeof WeakSet==`function`?WeakSet:Set,al=null;function ol(e,t){if(e=e.containerInfo,zd=cp,e=Fr(e),Ir(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||i!==0&&f.nodeType!==3||(c=s+i),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===i&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Bd={focusedElem:e,selectionRange:n},cp=!1,al=t;al!==null;)if(t=al,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,al=e;else for(;al!==null;){switch(t=al,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Fd(o,r,n),o[k]=e,kt(o),r=o;break a;case`link`:var s=Hf(`link`,`href`,i).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Nr(s,h),v=Nr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,E.T=null,n=uu,uu=null;var o=ou,s=cu;if(au=0,su=ou=null,cu=0,K&6)throw Error(a(331));var c=K;if(K|=4,Fl(o.current),Dl(o,o.current,s,n),K=c,ad(0,!1),Ke&&typeof Ke.onPostCommitFiberRoot==`function`)try{Ke.onPostCommitFiberRoot(Ge,o)}catch{}return!0}finally{D.p=i,E.T=r,Hu(e,t)}}function Gu(e,t,n){t=Ei(n,t),t=$s(e.stateNode,t,2),e=Ya(e,t,2),e!==null&&(st(e,2),id(e))}function Z(e,t,n){if(e.tag===3)Gu(e,e,n);else for(;t!==null;){if(t.tag===3){Gu(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(iu===null||!iu.has(r))){e=Ei(n,e),n=ec(2),r=Ya(t,n,2),r!==null&&(tc(n,r,t,e),st(r,2),id(r));break}}t=t.return}}function Ku(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new zl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Ul=!0,i.add(n),e=qu.bind(null,e,t,n),t.then(e,e))}function qu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,q===e&&(Y&n)===n&&(Gl===4||Gl===3&&(Y&62914560)===Y&&300>Ie()-eu?!(K&2)&&Cu(e,0):Jl|=n,Xl===Y&&(Xl=0)),id(e)}function Ju(e,t){t===0&&(t=at()),e=di(e,t),e!==null&&(st(e,t),id(e))}function Yu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ju(e,n)}function Xu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(a(314))}r!==null&&r.delete(t),Ju(e,n)}function Zu(e,t){return Me(e,t)}var Qu=null,$u=null,ed=!1,td=!1,nd=!1,rd=0;function id(e){e!==$u&&e.next===null&&($u===null?Qu=$u=e:$u=$u.next=e),td=!0,ed||(ed=!0,dd())}function ad(e,t){if(!nd&&td){nd=!0;do for(var n=!1,r=Qu;r!==null;){if(!t)if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Je(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,ud(r,a))}else a=Y,a=nt(r,r===q?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||rt(r,a)||(n=!0,ud(r,a));r=r.next}while(n);nd=!1}}function od(){sd()}function sd(){td=ed=!1;var e=0;rd!==0&&Kd()&&(e=rd);for(var t=Ie(),n=null,r=Qu;r!==null;){var i=r.next,a=cd(r,t);a===0?(r.next=null,n===null?Qu=i:n.next=i,i===null&&($u=n)):(n=r,(e!==0||a&3)&&(td=!0)),r=i}au!==0&&au!==5||ad(e,!1),rd!==0&&(rd=0)}function cd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Ld(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Sf(e,t,n){var r=xf;if(r&&typeof t==`string`&&t){var i=Jt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),gf.has(i)||(gf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Fd(t,`link`,e),kt(t),r.head.appendChild(t)))}}function Cf(e){vf.D(e),Sf(`dns-prefetch`,e,null)}function wf(e,t){vf.C(e,t),Sf(`preconnect`,e,t)}function Tf(e,t,n){vf.L(e,t,n);var r=xf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Jt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Jt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Jt(n.imageSizes)+`"]`)):i+=`[href="`+Jt(e)+`"]`;var a=i;switch(t){case`style`:a=jf(e);break;case`script`:a=Ff(e)}hf.has(a)||(e=m({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),hf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Mf(a))||t===`script`&&r.querySelector(If(a))||(t=r.createElement(`link`),Fd(t,`link`,e),kt(t),r.head.appendChild(t)))}}function Ef(e,t){vf.m(e,t);var n=xf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Jt(r)+`"][href="`+Jt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Ff(e)}if(!hf.has(a)&&(e=m({rel:`modulepreload`,href:e},t),hf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(If(a)))return}r=n.createElement(`link`),Fd(r,`link`,e),kt(r),n.head.appendChild(r)}}}function Df(e,t,n){vf.S(e,t,n);var r=xf;if(r&&e){var i=Ot(r).hoistableStyles,a=jf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Mf(a)))s.loading=5;else{e=m({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=hf.get(a))&&zf(e,n);var c=o=r.createElement(`link`);kt(c),Fd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Rf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Of(e,t){vf.X(e,t);var n=xf;if(n&&e){var r=Ot(n).hoistableScripts,i=Ff(e),a=r.get(i);a||(a=n.querySelector(If(i)),a||(e=m({src:e,async:!0},t),(t=hf.get(i))&&Bf(e,t),a=n.createElement(`script`),kt(a),Fd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function kf(e,t){vf.M(e,t);var n=xf;if(n&&e){var r=Ot(n).hoistableScripts,i=Ff(e),a=r.get(i);a||(a=n.querySelector(If(i)),a||(e=m({src:e,async:!0,type:`module`},t),(t=hf.get(i))&&Bf(e,t),a=n.createElement(`script`),kt(a),Fd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Af(e,t,n,r){var i=(i=_e.current)?_f(i):null;if(!i)throw Error(a(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=jf(n.href),n=Ot(i).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=jf(n.href);var o=Ot(i).hoistableStyles,s=o.get(e);if(s||(i=i.ownerDocument||i,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=i.querySelector(Mf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),hf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},hf.set(e,n),o||Pf(i,e,n,s.state))),t&&r===null)throw Error(a(528,``));return s}if(t&&r!==null)throw Error(a(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Ff(n),n=Ot(i).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(a(444,e))}}function jf(e){return`href="`+Jt(e)+`"`}function Mf(e){return`link[rel="stylesheet"][`+e+`]`}function Nf(e){return m({},e,{"data-precedence":e.precedence,precedence:null})}function Pf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Fd(t,`link`,n),kt(t),e.head.appendChild(t))}function Ff(e){return`[src="`+Jt(e)+`"]`}function If(e){return`script[async]`+e}function Lf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Jt(n.href)+`"]`);if(r)return t.instance=r,kt(r),r;var i=m({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),kt(r),Fd(r,`style`,i),Rf(r,n.precedence,e),t.instance=r;case`stylesheet`:i=jf(n.href);var o=e.querySelector(Mf(i));if(o)return t.state.loading|=4,t.instance=o,kt(o),o;r=Nf(n),(i=hf.get(i))&&zf(r,i),o=(e.ownerDocument||e).createElement(`link`),kt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Fd(o,`link`,r),t.state.loading|=4,Rf(o,n.precedence,e),t.instance=o;case`script`:return o=Ff(n.src),(i=e.querySelector(If(o)))?(t.instance=i,kt(i),i):(r=n,(i=hf.get(o))&&(r=m({},n),Bf(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),kt(i),Fd(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(a(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Rf(r,n.precedence,e));return t.instance}function Rf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Wf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Gf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Kf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=jf(r.href),a=t.querySelector(Mf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Yf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,kt(a);return}a=t.ownerDocument||t,r=Nf(r),(i=hf.get(i))&&zf(r,i),a=a.createElement(`link`),kt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Fd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Yf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var qf=0;function Jf(e,t){return e.stylesheets&&e.count===0&&Zf(e,e.stylesheets),0qf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Yf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Zf(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Xf=null;function Zf(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Xf=new Map,t.forEach(Qf,e),Xf=null,Yf.call(e))}function Qf(e,t){if(!(t.state.loading&4)){var n=Xf.get(e);if(n)var r=n.get(null);else{n=new Map,Xf.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=ye()})),xe=`__TSS_CONTEXT`,Se=Symbol.for(`TSS_SERVER_FUNCTION`),Ce=Symbol.for(`TSS_SERVER_FUNCTION_FACTORY`),we=`application/x-tss-framed`,Te={JSON:0,CHUNK:1,END:2,ERROR:3};`${we}`;var Ee=/;\s*v=(\d+)/;function De(e){let t=e.match(Ee);return t?parseInt(t[1],10):void 0}function Oe(e){let t=De(e);if(t!==void 0&&t!==1)throw Error(`Incompatible framed protocol version: server=${t}, client=1. Please ensure client and server are using compatible versions.`)}var ke=()=>window.__TSS_START_OPTIONS__;function Ae(e){return e?.isNotFound===!0}function je(){try{return sessionStorage}catch{return}}var Me=`tsr-scroll-restoration-v1_3`,Ne=je();function Pe(){try{return JSON.parse(Ne?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function Fe(){try{Ne?.setItem(Me,JSON.stringify(Ie))}catch{}}var Ie=Pe(),Le=`data-scroll-restoration-id`,Re=e=>e.state.__TSR_key||e.href;function ze(e){let t=e.getAttribute(Le);if(t)return`[${Le}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var Be=!1,Ve=`window`;function He(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function Ue(e){let t=new Set;for(let n of e){if(n===Ve)continue;let e=He(n);e&&t.add(e)}return t}function We(e,t){let n=t??e.options.scrollRestoration,r=e._scroll;n&&(r.restoring=!0);let i=e.options.getScrollRestorationKey||Re,a=new Set,o=e=>{let t=Ie[e]||={};for(let e of a)e===document?t[Ve]={scrollX,scrollY}:e.isConnected&&(t[ze(e)]={scrollX:e.scrollLeft,scrollY:e.scrollTop})};n&&!r.restoration&&(r.restoration=!0,Be=!1,history.scrollRestoration=`manual`,document.addEventListener(`scroll`,e=>{Be||a.add(e.target)},!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(i(e.fromLocation)),a.clear()}),addEventListener(`pagehide`,()=>{o(i(e.stores.resolvedLocation.get()??e.stores.location.get())),Fe()})),!r.reset&&(r.reset=!0,e.subscribe(`onRendered`,t=>{let n=e.options.scrollRestorationBehavior,o=e.options.scrollToTopSelectors,s=r.next,c=r.hash,l;if(a.clear(),r.next=!0,r.hash=!1,typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let u=i(t.toLocation),d=t.fromLocation&&i(t.fromLocation);if(r.restoring&&d&&d!==u){let e=Ie[d];if(e){let t=Ie[u];for(let n in e){if(n===Ve){if(s)continue}else{let e=He(n);if(!e||s&&o&&(l??=Ue(o),l.has(e)))continue}t||=Ie[u]={},t[n]??=e[n]}}}Be=!0;try{let e=t.toLocation.hash,i=t.toLocation.state.__hashScrollIntoViewOptions??!0,a=!1;if(s){!e&&o&&(l??=Ue(o));let t=e&&i&&c,s=r.restoring?Ie[u]:void 0;if(s)for(let e in s){let{scrollX:r,scrollY:i}=s[e];if(e===Ve){if(t)continue;scrollTo({top:i,left:r,behavior:n}),a=!0}else{let t=He(e);t&&(t.scrollLeft=r,t.scrollTop=i,l?.delete(t))}}if(!e){let e={top:0,left:0,behavior:n};if(a||scrollTo(e),l)for(let t of l)t.scrollTo(e)}}!a&&e&&i&&document.getElementById(e)?.scrollIntoView(i)}finally{Be=!1}}))}function Ge(e,t=String){let n=new URLSearchParams;for(let r in e){let i=e[r];i!==void 0&&n.set(r,t(i))}return n.toString()}function Ke(e){return e?e===`false`?!1:e===`true`?!0:e*0==0&&+e+``===e?+e:e:``}function qe(e){let t=new URLSearchParams(e),n=Object.create(null);for(let[e,r]of t.entries()){let t=n[e];t==null?n[e]=Ke(r):Array.isArray(t)?t.push(Ke(r)):n[e]=[t,Ke(r)]}return n}var Je=Xe(JSON.parse),Ye=Ze(JSON.stringify,JSON.parse);function Xe(e){return t=>{t[0]===`?`&&(t=t.substring(1));let n=qe(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function Ze(e,t){let n=typeof t==`function`;function r(r){if(typeof r==`object`&&r)try{return e(r)}catch{}else if(n&&typeof r==`string`)try{return t(r),e(r)}catch{}return r}return e=>{let t=Ge(e,r);return t?`?${t}`:``}}var Qe=`__root__`;function $e(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function et(e){return e instanceof Response&&!!e.options}function tt(e){if(typeof e==`object`&&e&&e.isSerializedRedirect)return $e(e)}function nt(e){return{input:({url:t})=>{for(let n of e)t=it(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=at(e[n],t);return t}}}function rt(e){let t=ne(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=ce([`/`,t,e.pathname]),e)}}function it(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function at(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function ot(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i,init:a}=t,o=new Map,s=new Map,c=new Map,l=n(e.status),u=n(e.loadedAt),d=n(e.isLoading),f=n(e.isTransitioning),p=n(e.location),m=n(e.resolvedLocation),h=n(e.statusCode),g=n(e.redirect),_=n([]),y=n([]),b=n([]),x=r(()=>st(o,_.get())),S=r(()=>st(s,y.get())),C=r(()=>st(c,b.get())),ee=r(()=>_.get()[0]),te=r(()=>_.get().some(e=>o.get(e)?.get().status===`pending`)),ne=r(()=>({locationHref:p.get().href,resolvedLocationHref:m.get()?.href,status:l.get()})),re=r(()=>({status:l.get(),loadedAt:u.get(),isLoading:d.get(),isTransitioning:f.get(),matches:x.get(),location:p.get(),resolvedLocation:m.get(),statusCode:h.get(),redirect:g.get()})),ie=v(64);function ae(e){let t=ie.get(e);return t||(t=r(()=>{let t=_.get();for(let n of t){let t=o.get(n);if(t&&t.routeId===e)return t.get()}}),ie.set(e,t)),t}let oe={status:l,loadedAt:u,isLoading:d,isTransitioning:f,location:p,resolvedLocation:m,statusCode:h,redirect:g,matchesId:_,pendingIds:y,cachedIds:b,matches:x,pendingMatches:S,cachedMatches:C,firstId:ee,hasPending:te,matchRouteDeps:ne,matchStores:o,pendingMatchStores:s,cachedMatchStores:c,__store:re,getRouteMatchStore:ae,setMatches:se,setPending:ce,setCached:w};se(e.matches),a?.(oe);function se(e){ct(e,o,_,n,i)}function ce(e){ct(e,s,y,n,i)}function w(e){ct(e,c,b,n,i)}return oe}function st(e,t){let n=[];for(let r of t){let t=e.get(r);t&&n.push(t.get())}return n}function ct(e,t,n,r,i){let a=e.map(e=>e.id),o=new Set(a);i(()=>{for(let e of t.keys())o.has(e)||t.delete(e);for(let n of e){let e=t.get(n.id);if(!e){let e=r(n);e.routeId=n.routeId,t.set(n.id,e);continue}e.routeId=n.routeId,e.get()!==n&&e.set(n)}m(n.get(),a)||n.set(a)})}var lt=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},ut=e=>e.stores.matchesId.get().some(t=>e.stores.matchStores.get(t)?.get()._forcePending),dt=(e,t)=>!!(e.preload&&!e.router.stores.matchStores.has(t)),ft=(e,t,n=!0)=>{let r={...e.router.options.context??{}},i=n?t:t-1;for(let t=0;t<=i;t++){let n=e.matches[t];if(!n)continue;let i=e.router.getMatch(n.id);i&&Object.assign(r,i.__routeContext,i.__beforeLoadContext)}return r},pt=(e,t)=>{if(!e.matches.length)return;let n=t.routeId,r=e.matches.findIndex(t=>t.routeId===e.router.routeTree.id),i=r>=0?r:0,a=n?e.matches.findIndex(e=>e.routeId===n):e.firstBadMatchIndex??e.matches.length-1;a<0&&(a=i);for(let t=a;t>=0;t--){let n=e.matches[t];if(e.router.looseRoutesById[n.routeId].options.notFoundComponent)return t}return n?a:i},mt=(e,t,n)=>{if(!(!et(n)&&!Ae(n)))throw et(n)&&n.redirectHandled&&!n.options.reloadDocument?n:(t&&(t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0,t._nonReactive.error=n,e.updateMatch(t.id,r=>({...r,status:et(n)?`redirected`:Ae(n)?`notFound`:r.status===`pending`?`success`:r.status,context:ft(e,t.index),isFetching:!1,error:n})),Ae(n)&&!n.routeId&&(n.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()),et(n)&&(e.rendered=!0,n.options._fromLocation=e.location,n.redirectHandled=!0,n=e.router.resolveRedirect(n)),n)},ht=(e,t)=>{let n=e.router.getMatch(t);return!!(!n||n._nonReactive.dehydrated)},gt=(e,t,n)=>{let r=ft(e,n);e.updateMatch(t,e=>({...e,context:r}))},k=(e,t,n)=>{let{id:r,routeId:i}=e.matches[t],a=e.router.looseRoutesById[i];if(n instanceof Promise)throw n;e.firstBadMatchIndex??=t,mt(e,e.router.getMatch(r),n);try{a.options.onError?.(n)}catch(t){n=t,mt(e,e.router.getMatch(r),n)}e.updateMatch(r,e=>(e._nonReactive.beforeLoadPromise?.resolve(),e._nonReactive.beforeLoadPromise=void 0,e._nonReactive.loadPromise?.resolve(),{...e,error:n,status:`error`,isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!et(n)&&!Ae(n)&&(e.serialError??=n)},_t=(e,t,n,r)=>{if(r._nonReactive.pendingTimeout!==void 0)return;let i=n.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!dt(e,t)&&(n.options.loader||n.options.beforeLoad||Ot(n))&&typeof i==`number`&&i!==1/0&&(n.options.pendingComponent??e.router.options?.defaultPendingComponent)){let t=setTimeout(()=>{lt(e)},i);r._nonReactive.pendingTimeout=t}},vt=(e,t,n)=>{let r=e.router.getMatch(t);if(!r._nonReactive.beforeLoadPromise&&!r._nonReactive.loaderPromise)return;_t(e,t,n,r);let i=()=>{let n=e.router.getMatch(t);n.preload&&(n.status===`redirected`||n.status===`notFound`)&&mt(e,n,n.error)};return r._nonReactive.beforeLoadPromise?r._nonReactive.beforeLoadPromise.then(i):i()},yt=(e,t,n,r)=>{let i=e.router.getMatch(t),a=i._nonReactive.loadPromise;i._nonReactive.loadPromise=oe(()=>{a?.resolve(),a=void 0});let{paramsError:o,searchError:s}=i;o&&k(e,n,o),s&&k(e,n,s),_t(e,t,r,i);let c=new AbortController,l=!1,u=()=>{l||(l=!0,e.updateMatch(t,e=>({...e,isFetching:`beforeLoad`,fetchCount:e.fetchCount+1,abortController:c})))},d=()=>{i._nonReactive.beforeLoadPromise?.resolve(),i._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,e=>({...e,isFetching:!1}))};if(!r.options.beforeLoad){e.router.batch(()=>{u(),d()});return}i._nonReactive.beforeLoadPromise=oe();let f={...ft(e,n,!1),...i.__routeContext},{search:p,params:m,cause:h}=i,_=dt(e,t),v={search:p,abortController:c,params:m,preload:_,context:f,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:_?`preload`:h,matches:e.matches,routeId:r.id,...e.router.options.additionalContext},y=r=>{if(r===void 0){e.router.batch(()=>{u(),d()});return}(et(r)||Ae(r))&&(u(),k(e,n,r)),e.router.batch(()=>{u(),e.updateMatch(t,e=>({...e,__beforeLoadContext:r})),d()})},b;try{if(b=r.options.beforeLoad(v),g(b))return u(),b.catch(t=>{k(e,n,t)}).then(y)}catch(t){u(),k(e,n,t)}y(b)},bt=(e,t)=>{let{id:n,routeId:r}=e.matches[t],i=e.router.looseRoutesById[r],a=()=>s(),o=()=>yt(e,n,t,i),s=()=>{if(ht(e,n))return;let t=vt(e,n,i);return g(t)?t.then(o):o()};return a()},xt=(e,t,n)=>{let r=e.router.getMatch(t);if(!r||!n.options.head&&!n.options.scripts&&!n.options.headers)return;let i={ssr:e.router.options.ssr,matches:e.matches,match:r,params:r.params,loaderData:r.loaderData};return Promise.all([n.options.head?.(i),n.options.scripts?.(i),n.options.headers?.(i)]).then(([e,t,n])=>({meta:e?.meta,links:e?.links,headScripts:e?.scripts,headers:n,scripts:t,styles:e?.styles}))},St=(e,t,n,r,i)=>{let a=t[r-1],{params:o,loaderDeps:s,abortController:c,cause:l}=e.router.getMatch(n),u=ft(e,r),d=dt(e,n);return{params:o,deps:s,preload:!!d,parentMatchPromise:a,abortController:c,context:u,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),cause:d?`preload`:l,route:i,...e.router.options.additionalContext}},Ct=async(e,t,n,r,i)=>{try{let a=e.router.getMatch(n);try{Dt(i);let o=i.options.loader,s=typeof o==`function`?o:o?.handler,c=s?.(St(e,t,n,r,i)),l=!!s&&g(c);if((l||i._lazyPromise||i._componentsPromise||i.options.head||i.options.scripts||i.options.headers||a._nonReactive.minPendingPromise)&&e.updateMatch(n,e=>({...e,isFetching:`loader`})),s){let t=l?await c:c;mt(e,e.router.getMatch(n),t),t!==void 0&&e.updateMatch(n,e=>({...e,loaderData:t}))}i._lazyPromise&&await i._lazyPromise;let u=a._nonReactive.minPendingPromise;u&&await u,i._componentsPromise&&await i._componentsPromise,e.updateMatch(n,t=>({...t,error:void 0,context:ft(e,r),status:`success`,isFetching:!1,updatedAt:Date.now()}))}catch(t){let o=t;if(o?.name===`AbortError`){if(a.abortController.signal.aborted){a._nonReactive.loaderPromise?.resolve(),a._nonReactive.loaderPromise=void 0;return}e.updateMatch(n,t=>({...t,status:t.status===`pending`?`success`:t.status,isFetching:!1,context:ft(e,r)}));return}let s=a._nonReactive.minPendingPromise;s&&await s,Ae(t)&&await i.options.notFoundComponent?.preload?.(),mt(e,e.router.getMatch(n),t);try{i.options.onError?.(t)}catch(t){o=t,mt(e,e.router.getMatch(n),t)}!et(o)&&!Ae(o)&&await Dt(i,[`errorComponent`]),e.updateMatch(n,t=>({...t,error:o,context:ft(e,r),status:`error`,isFetching:!1}))}}catch(t){let r=e.router.getMatch(n);r&&(r._nonReactive.loaderPromise=void 0),mt(e,r,t)}},wt=async(e,t,n)=>{async function r(r,a,c,l,d){let f=Date.now()-a.updatedAt,p=r?d.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:d.options.staleTime??e.router.options.defaultStaleTime??0,m=d.options.shouldReload,h=typeof m==`function`?m(St(e,t,i,n,d)):m,{status:g,invalid:_}=l,v=f>=p&&(!!e.forceStaleReload||l.cause===`enter`||c!==void 0&&c!==l.id);o=g===`success`&&(_||(h??v)),r&&d.options.preload===!1||(o&&!e.sync&&u?(s=!0,(async()=>{try{await Ct(e,t,i,n,d);let r=e.router.getMatch(i);r._nonReactive.loaderPromise?.resolve(),r._nonReactive.loadPromise?.resolve(),r._nonReactive.loaderPromise=void 0,r._nonReactive.loadPromise=void 0}catch(t){et(t)&&await e.router.navigate(t.options)}})()):g!==`success`||o?await Ct(e,t,i,n,d):gt(e,i,n))}let{id:i,routeId:a}=e.matches[n],o=!1,s=!1,c=e.router.looseRoutesById[a],l=c.options.loader,u=((typeof l==`function`?void 0:l?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!==`blocking`;if(ht(e,i)){if(!e.router.getMatch(i))return e.matches[n];gt(e,i,n)}else{let t=e.router.getMatch(i),o=e.router.stores.matchesId.get()[n],s=(o&&e.router.stores.matchStores.get(o)||null)?.routeId===a?o:e.router.stores.matches.get().find(e=>e.routeId===a)?.id,l=dt(e,i);if(t._nonReactive.loaderPromise){if(t.status===`success`&&!e.sync&&!t.preload&&u)return t;await t._nonReactive.loaderPromise;let n=e.router.getMatch(i),a=n._nonReactive.error||n.error;a&&mt(e,n,a),n.status===`pending`&&await r(l,t,s,n,c)}else{let n=l&&!e.router.stores.matchStores.has(i),a=e.router.getMatch(i);a._nonReactive.loaderPromise=oe(),n!==a.preload&&e.updateMatch(i,e=>({...e,preload:n})),await r(l,t,s,a,c)}}let d=e.router.getMatch(i);s||(d._nonReactive.loaderPromise?.resolve(),d._nonReactive.loadPromise?.resolve(),d._nonReactive.loadPromise=void 0),clearTimeout(d._nonReactive.pendingTimeout),d._nonReactive.pendingTimeout=void 0,s||(d._nonReactive.loaderPromise=void 0),d._nonReactive.dehydrated=void 0;let f=s?d.isFetching:!1;return f!==d.isFetching||d.invalid!==!1?(e.updateMatch(i,e=>({...e,isFetching:f,invalid:!1})),e.router.getMatch(i)):d};async function Tt(e){let t=e,n=[];ut(t.router)&<(t);let r;for(let e=0;e({...e,...a?{status:`success`,globalNotFound:!0,error:void 0}:{status:`notFound`,error:u},isFetching:!1})),d=e,await Dt(r,[`notFoundComponent`])}else if(!t.preload){let e=t.matches[0];e.globalNotFound||t.router.getMatch(e.id)?.globalNotFound&&t.updateMatch(e.id,e=>({...e,globalNotFound:!1,error:void 0}))}if(t.serialError&&t.firstBadMatchIndex!==void 0){let e=t.router.looseRoutesById[t.matches[t.firstBadMatchIndex].routeId];await Dt(e,[`errorComponent`])}for(let e=0;e<=d;e++){let{id:n,routeId:r}=t.matches[e],i=t.router.looseRoutesById[r];try{let e=xt(t,n,i);if(e){let r=await e;t.updateMatch(n,e=>({...e,...r}))}}catch(e){console.error(`Error executing head for route ${r}:`,e)}}let f=lt(t);if(g(f)&&await f,u)throw u;if(t.serialError&&!t.preload&&!t.onReady)throw t.serialError;return t.matches}function Et(e,t){let n=t.map(t=>e.options[t]?.preload?.()).filter(Boolean);if(n.length!==0)return Promise.all(n)}function Dt(e,t=kt){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(t=>{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);let n=()=>e._componentsLoaded?void 0:t===kt?(()=>{if(e._componentsPromise===void 0){let t=Et(e,kt);t?e._componentsPromise=t.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():Et(e,t);return e._lazyPromise?e._lazyPromise.then(n):n()}function Ot(e){for(let t of kt)if(e.options[t]?.preload)return!0;return!1}var kt=[`component`,`errorComponent`,`pendingComponent`,`notFoundComponent`],At=`__TSR_index`,jt=`popstate`,Mt=`beforeunload`;function Nt(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=Lt(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[At];i=Pt(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[At];i=Pt(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[At]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function Pt(e,t){t||={};let n=Rt();return{...t,key:n,__TSR_key:n,[At]:e}}function Ft(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>Lt(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=Rt();t.history.replaceState({[At]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_,v=()=>{g&&(C._ignoreSubscribers=!0,(g.isPush?t.history.pushState:t.history.replaceState)(g.state,``,g.href),C._ignoreSubscribers=!1,g=void 0,_=void 0,u=void 0)},y=(e,t,n)=>{let r=s(t);_||(u=l),l=Lt(t,n),g={href:r,state:n,isPush:g?.isPush||e===`push`},_||=Promise.resolve().then(()=>v())},b=e=>{l=c(),C.notify({type:e})},x=async()=>{if(f){f=!1;return}let e=c(),n=e.state[At]-l.state[At],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),C.notify(u);return}}}l=c(),C.notify(u)},S=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},C=Nt({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>y(`push`,e,t),replaceState:(e,t)=>y(`replace`,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(Mt,S,{capture:!0}),t.removeEventListener(jt,x)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Mt,S,{capture:!0}),t.addEventListener(jt,x),t.history.pushState=function(...e){let r=n.apply(t.history,e);return C._ignoreSubscribers||b(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return C._ignoreSubscribers||b(`REPLACE`),n},C}function It(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function Lt(e,t){let n=It(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=Rt();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[At]:0,key:a,__TSR_key:a}}}function Rt(){return(Math.random()+1).toString(36).substring(7)}function zt(e){return e instanceof Error?{name:e.name,message:e.message}:{data:e}}function Bt(e,t){let n=t,r=e;return{fromLocation:n,toLocation:r,pathChanged:n?.pathname!==r.pathname,hrefChanged:n?.href!==r.href,hashChanged:n?.hash!==r.hash}}var Vt=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=e=>e(),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=te(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=Ft()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!==`null`?this.origin=window.origin:this.origin=`http://localhost`),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=v(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=ot(Wt(this.latestLocation),e),We(this)}let a=!1,o=this.options.basepath??`/`,s=this.options.rewrite;if(r||n!==o||i!==s){this.basepath=o;let e=[],t=ne(o);t&&t!==`/`&&e.push(rt({basepath:o})),s&&e.push(s),this.rewrite=e.length===0?void 0:e.length===1?e[0]:nt(e),this.history&&this.updateLatestLocation(),a=!0}a&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<`u`&&`CSS`in window&&typeof window.CSS?.supports==`function`&&(this.isViewTransitionTypesSupported=window.CSS.supports(`selector(:active-view-transition-type(a))`))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=me(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&a(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{this.subscribers.forEach(t=>{t.eventType===e.type&&t.fn(e)})},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:a,href:o,state:s})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let o=this.options.parseSearch(n),c=this.options.stringifySearch(o);return{href:e+c+a,publicHref:e+c+a,pathname:r(e).path,external:!1,searchStr:c,search:i(t?.search,o),hash:r(a.slice(1)).path,state:y(t?.state,s)}}let c=new URL(o,this.origin),l=it(this.rewrite,c),u=this.options.parseSearch(l.search),d=this.options.stringifySearch(u);return l.search=d,{href:l.href.replace(l.origin,``),publicHref:o,pathname:r(l.pathname).path,external:!!this.rewrite&&l.origin!==this.origin,searchStr:d,search:i(t?.search,u),hash:r(l.hash.slice(1)).path,state:y(t?.state,s)}},a=n(e),{__tempLocation:o,__tempKey:s}=a.state;if(o&&(!s||s===this.tempLocationKey)){let e=n(o);return e.state.key=a.state.key,e.state.__TSR_key=a.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:a}}return a},this.resolvePathWithBase=(e,t)=>re({base:e,to:t.includes(`//`)?ee(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>Kt({pathname:e,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=e=>{let t=this.getMatch(e);t&&(t.abortController.abort(),clearTimeout(t._nonReactive.pendingTimeout),t._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(e=>{this.cancelMatch(e)}),this.stores.matchesId.get().forEach(e=>{if(this.stores.pendingMatchStores.has(e))return;let t=this.stores.matchStores.get(e)?.get();t&&(t.status===`pending`||t.isFetching===`loader`)&&this.cancelMatch(e)})},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this.pendingBuiltLocation||this.latestLocation,a=this.matchRoutesLightweight(n);t.from;let o=t.unsafeRelative===`path`?n.pathname:t.from??a.fullPath,s=t.to?`${t.to}`:void 0,l=a.search,u=Object.assign(Object.create(null),a.params),d=s?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(o,`.`),p=s?this.resolvePathWithBase(d,s):d,m=t.params===!1||t.params===null?Object.create(null):(t.params??!0)===!0?u:Object.assign(u,h(t.params,u)),g=this.routesByPath[pe(p)],_;if(g)_=this.getRouteBranch(g);else if(p.includes(`$`))_=[];else{let e=this.getMatchedRoutes(p);_=e.matchedRoutes,this.options.notFoundRoute&&(!e.foundRoute||e.foundRoute.path!==`/`&&e.routeParams[`**`])&&(_=[..._,this.options.notFoundRoute])}if(_.length&&c(m))for(let e of _){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(m,t(m))}catch{}}let v=e.leaveParams?p:r(E({path:p,params:m,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,b=l;if(e._includeValidateSearch&&this.options.search?.strict){let e={};_.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,Gt(t.options.validateSearch,{...e,...b}))}catch{}}),b=e}b=qt({search:b,dest:t,destRoutes:_,_includeValidateSearch:e._includeValidateSearch}),b=i(l,b);let x=this.options.stringifySearch(b),S=t.hash===!0?n.hash:t.hash?h(t.hash,n.hash):void 0,C=S?`#${S}`:``,ee=t.state===!0?n.state:t.state?h(t.state,n.state):{};ee=y(n.state,ee);let te=`${v}${x}${C}`,ne,re,ie=!1;if(this.rewrite){let e=new URL(te,this.origin),t=at(this.rewrite,e);ne=e.href.replace(e.origin,``),t.origin===this.origin?re=t.pathname+t.search+t.hash:(re=t.href,ie=!0)}else ne=f(te),re=ne;return{publicHref:re,href:ne,pathname:v,search:b,searchStr:x,state:ee,hash:S??``,external:ie,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),a=r?t(r):void 0;if(!a){let n=Object.create(null);if(this.options.routeMasks){let o=S(i.pathname,this.processedTree);if(o){Object.assign(n,o.rawParams);let{from:i,params:s,...c}=o.route,l=s===!1||s===null?Object.create(null):(s??!0)===!0?n:Object.assign(n,h(s,n));r={from:e.from,...c,params:l},a=t(r)}}}return a&&(i.maskedLocation=a),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=()=>{let e=[`key`,`__TSR_key`,`__TSR_index`,`__hashScrollIntoViewOptions`];e.forEach(e=>{n.state[e]=this.latestLocation.state[e]});let t=ae(n.state,this.latestLocation.state);return e.forEach(e=>{delete n.state[e]}),t},a=pe(this.latestLocation.href)===pe(n.href),o=this.commitLocationPromise;if(this.commitLocationPromise=oe(()=>{o?.resolve(),o=void 0}),a&&i())this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t})}return this._scroll.next=n.resetScroll??!0,this.history.subscribers.size||this.load(r?{action:{type:r}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,href:a,...o}={})=>{if(a){let t=this.history.location.state.__TSR_index,n=Lt(a,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);o.to=it(this.rewrite,r).pathname,o.search=this.options.parseSearch(n.search),o.hash=n.hash.slice(1)}let s=this.buildLocation({...o,_includeValidateSearch:!0});this.pendingBuiltLocation=s;let c=this.commitLocation({...s,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return queueMicrotask(()=>{this.pendingBuiltLocation===s&&(this.pendingBuiltLocation=void 0)}),c},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(u(t,this.protocolAllowlist))return;if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return}i.replace?window.location.replace(t):window.location.href=t;return}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();let e=this.matchRoutes(this.latestLocation),t=this.stores.cachedMatches.get().filter(t=>!e.some(e=>e.id===t.id));this.batch(()=>{this.stores.status.set(`pending`),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(e),this.stores.setCached(t)})},this.load=async e=>{let t=e?.action?.type,n,r,i,a=this.stores.resolvedLocation.get()??this.stores.location.get();for(i=new Promise(o=>{this.startTransition(async()=>{try{this.beforeLoad(),t&&(this._scroll.hash=t===`PUSH`||t===`REPLACE`);let n=this.latestLocation,r=Bt(n,this.stores.resolvedLocation.get());this.stores.redirect.get()||this.emit({type:`onBeforeNavigate`,...r}),this.emit({type:`onBeforeLoad`,...r}),await Tt({router:this,sync:e?.sync,forceStaleReload:a.href===n.href,matches:this.stores.pendingMatches.get(),location:n,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let e=null,t=null,n=null,r=null;this.batch(()=>{let i=this.stores.pendingMatches.get(),a=i.length,o=this.stores.matches.get();e=a?o.filter(e=>!this.stores.pendingMatchStores.has(e.id)):null;let s=new Set;for(let e of this.stores.pendingMatchStores.values())e.routeId&&s.add(e.routeId);let c=new Set;for(let e of this.stores.matchStores.values())e.routeId&&c.add(e.routeId);t=a?o.filter(e=>!s.has(e.routeId)):null,n=a?i.filter(e=>!c.has(e.routeId)):null,r=a?i.filter(e=>c.has(e.routeId)):o,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),a&&(this.stores.setMatches(i),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...e.filter(e=>e.status!==`error`&&e.status!==`notFound`&&e.status!==`redirected`)]),this.clearExpiredCache())});for(let[e,i]of[[t,`onLeave`],[n,`onEnter`],[r,`onStay`]])if(e)for(let t of e)this.looseRoutesById[t.routeId].options[i]?.(t)})})}})}catch(e){et(e)?(n=e,this.navigate({...n.options,replace:!0,ignoreBlocker:!0})):Ae(e)&&(r=e);let t=n?n.status:r?404:this.stores.matches.get().some(e=>e.status===`error`)?500:200;this.batch(()=>{this.stores.statusCode.set(t),this.stores.redirect.set(n)})}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),o()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let o;this.hasNotFoundMatch()?o=404:this.stores.matches.get().some(e=>e.status===`error`)&&(o=500),o!==void 0&&this.stores.statusCode.set(o)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document<`u`&&`startViewTransition`in document&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&this.isViewTransitionTypesSupported){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(Bt(r,i)):t.types;if(a===!1){e();return}n={update:e,types:a}}else n=e;document.startViewTransition(n)}else e()},this.updateMatch=(e,t)=>{this.startTransition(()=>{let n=this.stores.pendingMatchStores.get(e);if(n){n.set(t);return}let r=this.stores.matchStores.get(e);if(r){r.set(t);return}let i=this.stores.cachedMatchStores.get(e);if(i){let n=t(i.get());n.status===`redirected`?this.stores.cachedMatchStores.delete(e)&&this.stores.cachedIds.set(t=>t.filter(t=>t!==e)):i.set(n)}})},this.getMatch=e=>this.stores.cachedMatchStores.get(e)?.get()??this.stores.pendingMatchStores.get(e)?.get()??this.stores.matchStores.get(e)?.get(),this.invalidate=e=>{let t=t=>e?.filter?.(t)??!0?{...t,invalid:!0,...e?.forcePending||t.status===`error`||t.status===`notFound`?{status:`pending`,error:void 0}:void 0}:t;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(t)),this.stores.setCached(this.stores.cachedMatches.get().map(t)),this.stores.setPending(this.stores.pendingMatches.get().map(t))}),this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.getParsedLocationHref=e=>e.publicHref||`/`,this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=e.options._builtLocation??this.buildLocation(e.options),n=this.getParsedLocationHref(t);e.options.href=n,e.headers.set(`Location`,n)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&u(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=e?.filter;t===void 0?this.stores.setCached([]):this.stores.setCached(this.stores.cachedMatches.get().filter(e=>!t(e)))},this.clearExpiredCache=()=>{let e=Date.now();this.clearCache({filter:t=>{let n=this.looseRoutesById[t.routeId];if(!n.options.loader)return!0;let r=(t.preload?n.options.preloadGcTime??this.options.defaultPreloadGcTime:n.options.gcTime??this.options.defaultGcTime)??300*1e3;return t.status===`error`||e-t.updatedAt>=r}})},this.loadRouteChunk=Dt,this.preloadRoute=async e=>{let t=e._builtLocation??this.buildLocation(e),n=this.matchRoutes(t,{throwOnError:!0,preload:!0,dest:e}),r=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),i=new Set([...r,...this.stores.cachedIds.get()]),a=n.filter(e=>!i.has(e.id));if(a.length){let e=this.stores.cachedMatches.get();this.stores.setCached([...e,...a])}try{return n=await Tt({router:this,matches:n,location:t,preload:!0,updateMatch:(e,t)=>{r.has(e)?n=n.map(n=>n.id===e?t(n):n):this.updateMatch(e,t)}}),n}catch(e){if(et(e))return e.options.reloadDocument?void 0:await this.preloadRoute({...e.options,_fromLocation:t});Ae(e)||console.error(e);return}},this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n);if(t?.pending&&this.stores.status.get()!==`pending`)return!1;let i=(t?.pending===void 0?!this.stores.isLoading.get():t.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),a=_(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,i.pathname,this.processedTree);return!a||e.params&&!ae(a.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?ae(i.search,r.search,{partial:!0})?a.rawParams:!1:a.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(e=>e.status===`notFound`||e.globalNotFound),this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??Ye,parseSearch:e.parseSearch??Je,protocolAllowlist:e.protocolAllowlist??o}),typeof document<`u`&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=he(e),this.routeBranchCache.set(e,t)),t}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,t){let n=this.getMatchedRoutes(e.pathname),{foundRoute:r,routeParams:a}=n,{matchedRoutes:o}=n,s=!1;(r?r.path!==`/`&&a[`**`]:pe(e.pathname))&&(this.options.notFoundRoute?o=[...o,this.options.notFoundRoute]:s=!0);let c=s?Yt(this.options.notFoundMode,o):void 0,l=Array(o.length),u=new Map;for(let e of this.stores.matchStores.values())e.routeId&&u.set(e.routeId,e.get());for(let n=0;nthis.navigate({...t,_fromLocation:e}),buildLocation:this.buildLocation,cause:n.cause,abortController:n.abortController,preload:!!n.preload,matches:l,routeId:r.id};n.__routeContext=r.options.context(t)??void 0}n.context={...a,...n.__routeContext,...n.__beforeLoadContext}}}return l}matchRoutesLightweight(e){let t=ge(this.stores.matchesId.get()),n=this.lightweightCache.get(e);if(n&&n[0]===t)return n[1];let{matchedRoutes:r,routeParams:i}=this.getMatchedRoutes(e.pathname),a=ge(r),o={...e.search};for(let e of r)try{Object.assign(o,Gt(e.options.validateSearch,o))}catch{}let s=t&&this.stores.matchStores.get(t)?.get(),c=s&&s.routeId===a.id&&s.pathname===e.pathname,l;if(c)l=s.params;else{let e=Object.assign(Object.create(null),i);for(let t of r)try{Xt(t,e)}catch{}l=e}let u={matchedRoutes:r,fullPath:a.fullPath,search:o,params:l};return this.lightweightCache.set(e,[t,u]),u}},Ht=class extends Error{},Ut=class extends Error{};function Wt(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:`idle`,resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function Gt(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new Ht(`Async validation not supported`);if(n.issues)throw new Ht(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function Kt({pathname:e,routesById:t,processedTree:n}){let r=Object.create(null),i=pe(e),a,o=O(i,n,!0);return o&&(a=o.route,Object.assign(r,o.rawParams)),{matchedRoutes:o?.branch||[t.__root__],routeParams:r,foundRoute:a}}function qt({search:e,dest:t,destRoutes:n,_includeValidateSearch:r}){return Jt(n)(e,t,r??!1)}function Jt(e){let t,n,r=[];for(let t of e){let e=t.options;`search`in e?e.search?.middlewares&&r.push(...e.search.middlewares):(e.preSearchFilters||e.postSearchFilters)&&r.push(({search:t,next:n})=>{let r=n(e.preSearchFilters?e.preSearchFilters.reduce((e,t)=>t(e),t):t);return e.postSearchFilters?e.postSearchFilters.reduce((e,t)=>t(e),r):r});let i=e.validateSearch;i&&r.push(({search:e,next:t,meta:r})=>{let a=t(e);if(n)try{let e=Gt(i,a);if(r&&e)for(let t in e)t in a||(r.defaulted||=new Map).set(t,e[t]);return{...a,...e}}catch{}return a})}let i=(e,n,a)=>{if(e>=r.length){if(!t.search)return{};if(t.search===!0)return n;let e=h(t.search,n);return a&&(a.explicit=e),e}return r[e]({search:n,next:(t,n)=>{if(n){let n=a||{};return{search:i(e+1,t,n),meta:n}}return i(e+1,t,a)},meta:a})};return function(e,r,a){return t=r,n=a,i(0,e)}}function Yt(e,t){if(e!==`root`)for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.children)return n.id}return Qe}function Xt(e,t){let n=e.options.params?.parse??e.options.parseParams;if(n){let e=n(t);if(e===!1)throw Error(`Route params.parse returned false for a matched route`);Object.assign(t,e)}}var Zt=Symbol.for(`TSR_DEFERRED_PROMISE`);function Qt(e,t){let n=e;return n[Zt]?n:(n[Zt]={status:`pending`},n.then(e=>{n[Zt].status=`success`,n[Zt].data=e}).catch(e=>{n[Zt].status=`error`,n[Zt].error={data:(t?.serializeError??zt)(e),__isServerError:!0}}),n)}function $t(e,t){if(e)return typeof e==`string`?e:e[t]}function en(e){return e?.scriptFormat??`module`}function tn(e,t,n){let r=nn(t),i=$t(n,`script`)??r.crossOrigin;return{...en(e)===`iife`?{rel:`preload`,as:`script`}:{rel:`modulepreload`},href:r.href,...i?{crossOrigin:i}:{}}}function nn(e){return typeof e==`string`?{href:e,crossOrigin:void 0}:e}function rn(e,t){if(t.length===0)return;if(t.length===1){e.push(t[0]);return}let n=new Set;for(let r of t){let t=JSON.stringify(r);n.has(t)||(n.add(t),e.push(r))}}function an(e){return typeof e==`string`?{href:e,crossOrigin:void 0}:e}var on=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=Qe:this.parentRoute||s();let r=n?Qe:t?.path;r&&r!==`/`&&(r=b(r));let i=t?.id||r,a=n?Qe:ce([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=ce([`/`,a]));let o=a===`__root__`?`/`:ce([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=pe(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>$e({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},sn=class extends on{constructor(e){super(e)}},cn=(e=>(e[e.AggregateError=1]=`AggregateError`,e[e.ArrowFunction=2]=`ArrowFunction`,e[e.ErrorPrototypeStack=4]=`ErrorPrototypeStack`,e[e.ObjectAssign=8]=`ObjectAssign`,e[e.BigIntTypedArray=16]=`BigIntTypedArray`,e[e.RegExp=32]=`RegExp`,e))(cn||{}),ln=Symbol.asyncIterator,un=Symbol.hasInstance,dn=Symbol.isConcatSpreadable,fn=Symbol.iterator,pn=Symbol.match,mn=Symbol.matchAll,hn=Symbol.replace,gn=Symbol.search,_n=Symbol.species,vn=Symbol.split,yn=Symbol.toPrimitive,bn=Symbol.toStringTag,xn=Symbol.unscopables,Sn={[ln]:0,[un]:1,[dn]:2,[fn]:3,[pn]:4,[mn]:5,[hn]:6,[gn]:7,[_n]:8,[vn]:9,[yn]:10,[bn]:11,[xn]:12},Cn={0:ln,1:un,2:dn,3:fn,4:pn,5:mn,6:hn,7:gn,8:_n,9:vn,10:yn,11:bn,12:xn},A=void 0,wn={2:!0,3:!1,1:A,0:null,4:-0,5:1/0,6:-1/0,7:NaN},Tn={0:`Error`,1:`EvalError`,2:`RangeError`,3:`ReferenceError`,4:`SyntaxError`,5:`TypeError`,6:`URIError`},En={0:Error,1:EvalError,2:RangeError,3:ReferenceError,4:SyntaxError,5:TypeError,6:URIError};function j(e,t,n,r,i,a,o,s,c,l,u,d){return{t:e,i:t,s:n,c:r,m:i,p:a,e:o,a:s,f:c,b:l,o:u,l:d}}function Dn(e){return j(2,A,e,A,A,A,A,A,A,A,A,A)}var On=Dn(2),kn=Dn(3),An=Dn(1),jn=Dn(0),Mn=Dn(4),Nn=Dn(5),Pn=Dn(6),Fn=Dn(7);function In(e){switch(e){case`"`:return`\\"`;case`\\`:return`\\\\`;case` -`:return`\\n`;case`\r`:return`\\r`;case`\b`:return`\\b`;case` `:return`\\t`;case`\f`:return`\\f`;case`<`:return`\\x3C`;case`\u2028`:return`\\u2028`;case`\u2029`:return`\\u2029`;default:return A}}function Ln(e){let t=``,n=0,r;for(let i=0,a=e.length;iCr(e),Tr=class extends Error{constructor(e,t){super(wr(e,t)),this.cause=t}},Er=class extends Tr{constructor(e){super(`parsing`,e)}},Dr=class extends Tr{constructor(e){super(`deserialization`,e)}};function Or(e){return`Seroval Error (specific: ${e})`}var kr=class extends Error{constructor(e){super(Or(1)),this.value=e}},Ar=class extends Error{constructor(e){super(Or(2))}},jr=class extends Error{constructor(e){super(Or(3))}},Mr=class extends Error{constructor(e){super(Or(4))}},Nr=class extends Error{constructor(e){super(Or(5)),this.value=e}},Pr=class extends Error{constructor(e){super(Or(6))}},Fr=class extends Error{constructor(e){super(Or(7))}},Ir=class extends Error{constructor(e){super(Or(8))}},Lr=class extends Error{constructor(e){super(Or(9))}},Rr=class{constructor(e,t){this.value=e,this.replacement=t}},zr=()=>{let e={p:0,s:0,f:0};return e.p=new Promise((t,n)=>{e.s=t,e.f=n}),e};zr.toString(),((e,t)=>{e.s(t),e.p.s=1,e.p.v=t}).toString(),((e,t)=>{e.f(t),e.p.s=2,e.p.v=t}).toString();var Br=()=>{let e=[],t=[],n=!0,r=!1,i=0,a=(e,n,r)=>{for(r=0;r{for(i=0,a=e.length;i(n&&(r=i++,t[r]=e),o(e),()=>{n&&(t[r]=t[i],t[i--]=void 0)});return{__SEROVAL_STREAM__:!0,on:e=>s(e),next:t=>{n&&(e.push(t),a(t,`next`))},throw:i=>{n&&(e.push(i),a(i,`throw`),n=!1,r=!1,t.length=0)},return:i=>{n&&(e.push(i),a(i,`return`),n=!1,r=!0,t.length=0)}}};Br.toString();var Vr=e=>t=>()=>{let n=0,r={[e]:()=>r,next:()=>{if(n>t.d)return{done:!0,value:void 0};let e=n++,r=t.v[e];if(e===t.t)throw r;return{done:e===t.d,value:r}}};return r};Vr.toString();var Hr=(e,t)=>n=>()=>{let r=0,i=-1,a=!1,o=[],s=[],c=(e=0,t=s.length)=>{for(;e{let t=s.shift();t&&t.s({done:!1,value:e}),o.push(e)},throw:e=>{let t=s.shift();t&&t.f(e),c(),i=o.length,a=!0,o.push(e)},return:e=>{let t=s.shift();t&&t.s({done:!0,value:e}),c(),i=o.length,o.push(e)}});let l={[e]:()=>l,next:()=>{if(i===-1){let e=r++;if(e>=o.length){let e=t();return s.push(e),e.p}return{done:!1,value:o[e]}}if(r>i)return{done:!0,value:void 0};let e=r++,n=o[e];if(e!==i)return{done:!1,value:n};if(a)throw n;return{done:!0,value:n}}};return l};Hr.toString();var Ur=e=>{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e{}),t}var ti=Hr(ln,zr);function ni(e){return ti(e)}async function ri(e){try{return[1,await e]}catch(e){return[0,e]}}function ii(e,t){return{plugins:t.plugins,mode:e,marked:new Set,features:63^(t.disabledFeatures||0),refs:t.refs||new Map,depthLimit:t.depthLimit||1e3}}function ai(e,t){e.marked.add(t)}function oi(e,t){let n=e.refs.size;return e.refs.set(t,n),n}function si(e,t){let n=e.refs.get(t);return n==null?{type:0,value:oi(e,t)}:(ai(e,n),{type:1,value:er(n)})}function ci(e,t){let n=si(e,t);return n.type===1?n:Un(t)?{type:2,value:ir(n.value,t)}:n}function li(e,t){let n=ci(e,t);if(n.type!==0)return n.value;if(t in Sn)return rr(n.value,t);throw new kr(t)}function ui(e,t){let n=si(e,Zr[t]);return n.type===1?n.value:j(26,n.value,t,A,A,A,A,A,A,A,A,A)}function di(e){let t=si(e,Yr);return t.type===1?t.value:j(27,t.value,A,A,A,A,A,A,li(e,fn),A,A,A)}function fi(e){let t=si(e,Xr);return t.type===1?t.value:j(29,t.value,A,A,A,A,A,[ui(e,1),li(e,ln)],A,A,A,A)}function pi(e,t,n,r){return j(n?11:10,e,A,A,A,r,A,A,A,A,Xn(t),A)}function mi(e,t,n,r){return j(8,t,A,A,A,A,{k:n,v:r},A,ui(e,0),A,A,A)}function hi(e,t,n){let r=new Uint8Array(n),i=``;for(let e=0,t=r.length;e{ai(this.base,t),Li(this,e,n).then(e=>{a.push(_r(t,e))},e=>{i(e),o()})},throw:n=>{ai(this.base,t),Li(this,e,n).then(e=>{a.push(vr(t,e)),r(a),o()},e=>{i(e),o()})},return:n=>{ai(this.base,t),Li(this,e,n).then(e=>{a.push(yr(t,e)),r(a),o()},e=>{i(e),o()})}})}async function Ni(e,t,n,r){return gr(n,ui(e.base,4),await new Promise(Mi.bind(e,t,n,r)))}async function Pi(e,t,n,r){let i=[];for(let n=0,a=r.v.length;n=e.base.depthLimit)throw new Lr(e.base.depthLimit);switch(typeof n){case`boolean`:return n?On:kn;case`undefined`:return An;case`string`:return Qn(n);case`number`:return Zn(n);case`bigint`:return $n(n);case`object`:if(n){let r=ci(e.base,n);return r.type===0?await Fi(e,t+1,r.value,n):r.value}return jn;case`symbol`:return li(e.base,n);case`function`:return Ii(e,t,n);default:throw new kr(n)}}async function Ri(e,t){try{return await Li(e,0,t)}catch(e){throw e instanceof Er?e:new Er(e)}}var zi=(e=>(e[e.Vanilla=1]=`Vanilla`,e[e.Cross=2]=`Cross`,e))(zi||{});function Bi(e){return e}function Vi(e,t){for(let n=0,r=t.length;n0)for(let a=0,o=n.v,s=i.length;aKi)throw new Ir(t);return P(e,t.i,new RegExp(n,t.m))}throw new Ar(t)}function fa(e,t,n){let r=P(e,n.i,new Set);for(let i=0,a=n.a,o=a.length;iWi)throw new Ir(t);return P(e,t.i,Ur(zn(t.s)))}function ha(e,t,n){let r=N(n.c),i=F(e,t,n.f),a=n.b??0;if(a<0||a>i.byteLength)throw new Ir(n);return P(e,n.i,new r(i,a,n.l))}function ga(e,t,n){let r=F(e,t,n.f),i=n.b??0;if(i<0||i>r.byteLength)throw new Ir(n);return P(e,n.i,new DataView(r,i,n.l))}function _a(e,t,n,r){if(n.p){let i=ca(e,t,n.p,{});Object.defineProperties(r,Object.getOwnPropertyDescriptors(i))}return r}function va(e,t,n){return _a(e,t,n,P(e,n.i,AggregateError([],zn(n.m))))}function ya(e,t,n){let r=ta(n,En,n.s);return _a(e,t,n,P(e,n.i,new r(zn(n.m))))}function ba(e,t,n){let r=zr(),i=P(e,n.i,r.p),a=F(e,t,n.f);return n.s?r.s(a):r.f(a),i}function xa(e,t,n){return P(e,n.i,Object(F(e,t,n.f)))}function Sa(e,t,n){let r=e.base.plugins;if(r){let i=zn(n.c);for(let a=0,o=r.length;ae.base.depthLimit)throw new Lr(e.base.depthLimit);switch(t+=1,n.t){case 2:return ta(n,wn,n.s);case 0:return Number(n.s);case 1:return zn(String(n.s));case 3:if(String(n.s).length>Gi)throw new Ir(n);return BigInt(n.s);case 4:return e.base.refs.get(n.i);case 18:return na(e,n);case 9:return ra(e,t,n);case 10:case 11:return la(e,t,n);case 5:return ua(e,n);case 6:return da(e,n);case 7:return fa(e,t,n);case 8:return pa(e,t,n);case 19:return ma(e,n);case 16:case 15:return ha(e,t,n);case 20:return ga(e,t,n);case 14:return va(e,t,n);case 13:return ya(e,t,n);case 12:return ba(e,t,n);case 17:return ta(n,Cn,n.s);case 21:return xa(e,t,n);case 25:return Sa(e,t,n);case 22:return Ca(e,n);case 23:return wa(e,t,n);case 24:return Ta(e,t,n);case 28:return Ea(e,t,n);case 30:return Da(e,t,n);case 31:return Oa(e,t,n);case 32:return ka(e,t,n);case 33:return Aa(e,t,n);case 34:return ja(e,t,n);case 27:return Ma(e,t,n);case 29:return Na(e,t,n);case 35:return Pa(e,t,n);default:throw new Ar(n)}}function Fa(e,t){try{return F(e,0,t)}catch(e){throw new Dr(e)}}var Ia=(()=>T).toString();/=>/.test(Ia);function La(e,t){return Fa(Xi({plugins:M(t.plugins),refs:t.refs,features:t.features,disabledFeatures:t.disabledFeatures,depthLimit:t.depthLimit}),e)}async function Ra(e,t={}){let n=gi(1,{plugins:M(t.plugins),disabledFeatures:t.disabledFeatures});return{t:await Ri(n,e),f:n.base.features,m:Array.from(n.base.marked)}}function za(e){return e}function Ba(e){return Bi({tag:`$TSR/t/`+e.key,test:e.test,parse:{sync(t,n,r){return{v:n.parse(e.toSerializable(t))}},async async(t,n,r){return{v:await n.parse(e.toSerializable(t))}},stream(t,n,r){return{v:n.parse(e.toSerializable(t))}}},serialize:void 0,deserialize(t,n,r){return e.fromSerializable(n.deserialize(t.v))}})}var Va=class{constructor(e,t){this.stream=e,this.hint=t?.hint??`binary`}},Ha=globalThis.Buffer,Ua=!!Ha&&typeof Ha.from==`function`;function Wa(e){if(e.length===0)return``;if(Ua)return Ha.from(e).toString(`base64`);let t=32768,n=[];for(let r=0;rnew ReadableStream({start(t){e.on({next(e){try{t.enqueue(Ga(e))}catch{}},throw(e){t.error(e)},return(){try{t.close()}catch{}}})}}),Ya=new TextEncoder,Xa=e=>new ReadableStream({start(t){e.on({next(e){try{typeof e==`string`?t.enqueue(Ya.encode(e)):t.enqueue(Ga(e.$b64))}catch{}},throw(e){t.error(e)},return(){try{t.close()}catch{}}})}}),Za=`(s=>new ReadableStream({start(c){s.on({next(b){try{const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i{const e=new TextEncoder();return new ReadableStream({start(c){s.on({next(v){try{if(typeof v==='string'){c.enqueue(e.encode(v))}else{const d=atob(v.$b64),a=new Uint8Array(d.length);for(let i=0;i{try{for(;;){let{done:e,value:r}=await n.read();if(e){t.return(void 0);break}t.next(Wa(r))}}catch(e){t.throw(e)}finally{n.releaseLock()}})(),t}function eo(e){let t=$r(),n=e.getReader(),r=new TextDecoder(`utf-8`,{fatal:!0});return(async()=>{try{for(;;){let{done:e,value:i}=await n.read();if(e){try{let e=r.decode();e.length>0&&t.next(e)}catch{}t.return(void 0);break}try{let e=r.decode(i,{stream:!0});e.length>0&&t.next(e)}catch{t.next({$b64:Wa(i)})}}}catch(e){t.throw(e)}finally{n.releaseLock()}})(),t}var to=Bi({tag:`tss/RawStream`,extends:[Bi({tag:`tss/RawStreamFactory`,test(e){return e===Ka},parse:{sync(e,t,n){return{}},async async(e,t,n){return{}},stream(e,t,n){return{}}},serialize(e,t,n){return Za},deserialize(e,t,n){return Ka}}),Bi({tag:`tss/RawStreamFactoryText`,test(e){return e===qa},parse:{sync(e,t,n){return{}},async async(e,t,n){return{}},stream(e,t,n){return{}}},serialize(e,t,n){return Qa},deserialize(e,t,n){return qa}})],test(e){return e instanceof Va},parse:{sync(e,t,n){let r=e.hint===`text`?qa:Ka;return{hint:t.parse(e.hint),factory:t.parse(r),stream:t.parse($r())}},async async(e,t,n){let r=e.hint===`text`?qa:Ka,i=e.hint===`text`?eo(e.stream):$a(e.stream);return{hint:await t.parse(e.hint),factory:await t.parse(r),stream:await t.parse(i)}},stream(e,t,n){let r=e.hint===`text`?qa:Ka,i=e.hint===`text`?eo(e.stream):$a(e.stream);return{hint:t.parse(e.hint),factory:t.parse(r),stream:t.parse(i)}}},serialize(e,t,n){return`(`+t.serialize(e.factory)+`)(`+t.serialize(e.stream)+`)`},deserialize(e,t,n){let r=t.deserialize(e.stream);return t.deserialize(e.hint)===`text`?Xa(r):Ja(r)}});function no(e){return Bi({tag:`tss/RawStream`,test:()=>!1,parse:{},serialize(){throw Error(`RawStreamDeserializePlugin.serialize should not be called. Client only deserializes.`)},deserialize(t,n,r){return e(typeof n?.deserialize==`function`?n.deserialize(t.streamId):t.streamId)}})}var ro=Bi({tag:`$TSR/Error`,test(e){return e instanceof Error},parse:{sync(e,t){return{message:t.parse(e.message)}},async async(e,t){return{message:await t.parse(e.message)}},stream(e,t){return{message:t.parse(e.message)}}},serialize(e,t){return`new Error(`+t.serialize(e.message)+`)`},deserialize(e,t){return Error(t.deserialize(e.message))}}),io={},ao=e=>new ReadableStream({start:t=>{e.on({next:e=>{try{t.enqueue(e)}catch{}},throw:e=>{t.error(e)},return:()=>{try{t.close()}catch{}}})}}),oo=Bi({tag:`seroval-plugins/web/ReadableStreamFactory`,test(e){return e===io},parse:{sync(){return io},async async(){return await Promise.resolve(io)},stream(){return io}},serialize(){return ao.toString()},deserialize(){return io}});async function so(e,t){try{let n=await t.read();n.done?(e.return(n.value),t.releaseLock()):(e.next(n.value),await so(e,t))}catch(t){e.throw(t)}}function co(e){e.cancel().catch(()=>{}),e.releaseLock()}function lo(e){let t=$r(),n=e.getReader(),r=co.bind(null,n);return so(t,n).catch(r),[t,r]}var uo=[ro,to,Bi({tag:`seroval/plugins/web/ReadableStream`,extends:[oo],test(e){return typeof ReadableStream>`u`?!1:e instanceof ReadableStream},parse:{sync(e,t){return{factory:t.parse(io),stream:t.parse($r())}},async async(e,t){return{factory:await t.parse(io),stream:await t.parse(lo(e)[0])}},stream(e,t){let[n,r]=lo(e);return t.addCleanup(r),{factory:t.parse(io),stream:t.parse(n)}}},serialize(e,t){return`(`+t.serialize(e.factory)+`)(`+t.serialize(e.stream)+`)`},deserialize(e,t){return ao(t.deserialize(e.stream))}})];function fo(){return[...(ke()?.serializationAdapters)?.map(Ba)??[],...uo]}var po=new TextDecoder,mo=new Uint8Array,ho=16*1024*1024,I=32*1024*1024,go=1024,_o=1e5;function L(e){let t=new Map,n=new Map,r=new Set,i=!1,a=null,o=0,s,c=new ReadableStream({start(e){s=e},cancel(){i=!0;try{a?.cancel()}catch{}t.forEach(e=>{try{e.error(Error(`Framed response cancelled`))}catch{}}),t.clear(),n.clear(),r.clear()}});function l(e){let i=n.get(e);if(i)return i;if(r.has(e))return new ReadableStream({start(e){e.close()}});if(n.size>=go)throw Error(`Too many raw streams in framed response (max ${go})`);let a=new ReadableStream({start(n){t.set(e,n)},cancel(){r.add(e),t.delete(e),n.delete(e)}});return n.set(e,a),a}function u(e){return l(e),t.get(e)}return(async()=>{let n=e.getReader();a=n;let c=[],l=0;function d(){if(l<9)return null;let e=c[0];if(e.length>=9)return{type:e[0],streamId:(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0,length:(e[5]<<24|e[6]<<16|e[7]<<8|e[8])>>>0};let t=new Uint8Array(9),n=0,r=9;for(let e=0;e0;e++){let i=c[e],a=Math.min(i.length,r);t.set(i.subarray(0,a),n),n+=a,r-=a}return{type:t[0],streamId:(t[1]<<24|t[2]<<16|t[3]<<8|t[4])>>>0,length:(t[5]<<24|t[6]<<16|t[7]<<8|t[8])>>>0}}function f(e){if(e===0)return mo;let t=c[0];if(t&&t.length>=e){let n=t.subarray(0,e);return t.length===e?c.shift():c[0]=t.subarray(e),l-=e,n}let n=new Uint8Array(e),r=0,i=e;for(;i>0&&c.length>0;){let e=c[0];if(!e)break;let t=Math.min(e.length,i);n.set(e.subarray(0,t),r),r+=t,i-=t,t===e.length?c.shift():c[0]=e.subarray(t)}return l-=e,n}try{for(;;){let{done:e,value:a}=await n.read();if(i||e)break;if(a){if(l+a.length>I)throw Error(`Framed response buffer exceeded ${I} bytes`);for(c.push(a),l+=a.length;;){let e=d();if(!e)break;let{type:n,streamId:i,length:a}=e;if(n!==Te.JSON&&n!==Te.CHUNK&&n!==Te.END&&n!==Te.ERROR)throw Error(`Unknown frame type: ${n}`);if(n===Te.JSON){if(i!==0)throw Error(`Invalid JSON frame streamId (expected 0)`)}else if(i===0)throw Error(`Invalid raw frame streamId (expected non-zero)`);if(a>ho)throw Error(`Frame payload too large: ${a} bytes (max ${ho})`);let c=9+a;if(l_o)throw Error(`Too many frames in framed response (max ${_o})`);f(9);let p=f(a);switch(n){case Te.JSON:try{s.enqueue(po.decode(p))}catch{}break;case Te.CHUNK:{let e=u(i);e&&e.enqueue(p);break}case Te.END:{let e=u(i);if(r.add(i),e){try{e.close()}catch{}t.delete(i)}break}case Te.ERROR:{let e=u(i);if(r.add(i),e){let n=po.decode(p);e.error(Error(n)),t.delete(i)}break}}}}}if(l!==0)throw Error(`Incomplete frame at end of framed response`);try{s.close()}catch{}t.forEach(e=>{try{e.close()}catch{}}),t.clear()}catch(e){try{s.error(e)}catch{}t.forEach(t=>{try{t.error(e)}catch{}}),t.clear()}finally{try{n.releaseLock()}catch{}a=null}})(),{getOrCreateStream:l,jsonChunks:c}}var R=null;async function z(e){e.length>0&&await Promise.allSettled(e)}var vo=Object.prototype.hasOwnProperty;function yo(e){for(let t in e)if(vo.call(e,t))return!0;return!1}async function bo(e,t,n){R||=fo();let r=t[0],i=r.fetch??n,a=r.data instanceof FormData?`formData`:`payload`,o=r.headers?new Headers(r.headers):new Headers;if(o.set(`x-tsr-serverFn`,`true`),a===`payload`&&o.set(`accept`,`${we}, application/x-ndjson, application/json`),r.method===`GET`){if(a===`formData`)throw Error(`FormData is not supported with GET requests`);let t=await xo(r);if(t!==void 0){let n=Ge({payload:t});e.includes(`?`)?e+=`&${n}`:e+=`?${n}`}}let s;if(r.method===`POST`){let e=await Co(r);e?.contentType&&o.set(`content-type`,e.contentType),s=e?.body}return await wo(async()=>i(e,{method:r.method,headers:o,signal:r.signal,body:s}))}async function xo(e){let t=!1,n={};if(e.data!==void 0&&(t=!0,n.data=e.data),e.context&&yo(e.context)&&(t=!0,n.context=e.context),t)return So(n)}async function So(e){return JSON.stringify(await Promise.resolve(Ra(e,{plugins:R})))}async function Co(e){if(e.data instanceof FormData){let t;return e.context&&yo(e.context)&&(t=await So(e.context)),t!==void 0&&e.data.set(xe,t),{body:e.data}}let t=await xo(e);if(t)return{body:t,contentType:`application/json`}}async function wo(e){let t;try{t=await e()}catch(e){if(e instanceof Response)t=e;else throw console.log(e),e}if(t.headers.get(`x-tss-raw`)===`true`)return t;let n=t.headers.get(`content-type`);if(n||s(),t.headers.get(`x-tss-serialized`)){let e;if(n.includes(`application/x-tss-framed`)){if(Oe(n),!t.body)throw Error(`No response body for framed response`);let{getOrCreateStream:r,jsonChunks:i}=L(t.body),a=[no(r),...R||[]],o=new Map;e=await B({jsonStream:i,onMessage:e=>La(e,{refs:o,plugins:a}),onError(e,t){console.error(e,t)}})}else if(n.includes(`application/json`)){let n=await t.json(),r=[];try{e=La(n,{plugins:R})}finally{}await z(r)}if(e||s(),e instanceof Error)throw e;return e}if(n.includes(`application/json`)){let e=await t.json(),n=tt(e);if(n)throw n;if(Ae(e))throw e;return e}if(!t.ok)throw Error(await t.text());return t}async function B({jsonStream:e,onMessage:t,onError:n}){let r=e.getReader(),{value:i,done:a}=await r.read();if(a||!i)throw Error(`Stream ended before first object`);let o=JSON.parse(i),s=!1,c=(async()=>{try{for(;;){let{value:e,done:i}=await r.read();if(i)break;if(e)try{let n=[];try{t(JSON.parse(e))}finally{}await z(n)}catch(t){n?.(`Invalid JSON: ${e}`,t)}}}catch(e){s||n?.(`Stream processing error:`,e)}})(),l,u=[];try{l=t(o)}catch(e){throw s=!0,r.cancel().catch(()=>{}),e}return await z(u),Promise.resolve(l).catch(()=>{s=!0,r.cancel().catch(()=>{})}),c.finally(()=>{try{r.releaseLock()}catch{}}),l}function To(e){let t=`/_serverFn/`+e;return Object.assign((...e)=>{let n=ke()?.serverFns?.fetch;return bo(t,e,n??fetch)},{url:t,serverFnMeta:{id:e},[Se]:!0})}var Eo=za({key:`$TSS/serverfn`,test:e=>typeof e!=`function`||!(Se in e)?!1:!!e[Se],toSerializable:({serverFnMeta:e})=>({functionId:e.id}),fromSerializable:({functionId:e})=>To(e)});function Do(e){return e.replaceAll(`\0`,`/`).replaceAll(`�`,`/`)}function Oo(e,t){e.id=t.i,e.__beforeLoadContext=t.b,e.loaderData=t.l,e.status=t.s,e.ssr=t.ssr,e.updatedAt=t.u,e.error=t.e,t.g!==void 0&&(e.globalNotFound=t.g)}async function ko(e){window.$_TSR||s();let t=e.options.serializationAdapters;if(t?.length){let e=new Map;t.forEach(t=>{e.set(t.key,t.fromSerializable)}),window.$_TSR.t=e,window.$_TSR.buffer.forEach(e=>e())}window.$_TSR.initialized=!0,window.$_TSR.router||s();let n=window.$_TSR.router;n.matches.forEach(e=>{e.i=Do(e.i)}),n.lastMatchId&&=Do(n.lastMatchId);let{manifest:r,dehydratedData:i,lastMatchId:a}=n;e.ssr={manifest:r};let o=document.querySelector(`meta[property="csp-nonce"]`)?.content;e.options.ssr={nonce:o},await e.options.hydrate?.(i);let c=e.matchRoutes(e.stores.location.get()),l=Promise.all(c.map(t=>e.loadRouteChunk(e.looseRoutesById[t.routeId])));function u(t){let n=e.looseRoutesById[t.routeId].options.pendingMinMs??e.options.defaultPendingMinMs;if(n){let r=oe();t._nonReactive.minPendingPromise=r,t._forcePending=!0,setTimeout(()=>{r.resolve(),e.updateMatch(t.id,e=>(e._nonReactive.minPendingPromise=void 0,{...e,_forcePending:void 0}))},n)}}function d(t){let n=e.looseRoutesById[t.routeId];n&&(n.options.ssr=t.ssr)}let f;c.forEach(e=>{let t=n.matches.find(t=>t.i===e.id);if(!t){e._nonReactive.dehydrated=!1,e.ssr=!1,d(e);return}Oo(e,t),d(e),e._nonReactive.dehydrated=e.ssr!==!1,(e.ssr===`data-only`||e.ssr===!1)&&f===void 0&&(f=e.index,u(e))}),e.stores.setMatches(c);let p=e.stores.matches.get(),m=e.stores.location.get();await Promise.all(p.map(async t=>{try{let n=e.looseRoutesById[t.routeId],r=p[t.index-1]?.context??e.options.context;if(n.options.context){let i={deps:t.loaderDeps,params:t.params,context:r??{},location:m,navigate:t=>e.navigate({...t,_fromLocation:m}),buildLocation:e.buildLocation,cause:t.cause,abortController:t.abortController,preload:!1,matches:c,routeId:n.id};t.__routeContext=n.options.context(i)??void 0}t.context={...r,...t.__routeContext,...t.__beforeLoadContext};let i={ssr:e.options.ssr,matches:p,match:t,params:t.params,loaderData:t.loaderData},a=await n.options.head?.(i),o=await n.options.scripts?.(i);t.meta=a?.meta,t.links=a?.links,t.headScripts=a?.scripts,t.styles=a?.styles,t.scripts=o}catch(e){if(Ae(e))t.error={isNotFound:!0},console.error(`NotFound error during hydration for routeId: ${t.routeId}`,e);else throw t.error=e,console.error(`Error during hydration for route ${t.routeId}:`,e),e}}));let h=c[c.length-1].id!==a;if(!c.some(e=>e.ssr===!1)&&!h)return c.forEach(e=>{e._nonReactive.dehydrated=void 0}),e.stores.resolvedLocation.set(e.stores.location.get()),l;let g=Promise.resolve().then(()=>e.load()).catch(e=>{console.error(`Error during router hydration:`,e)});if(h){let t=c[1];t||s(),u(t),t._displayPending=!0,t._nonReactive.displayPendingPromise=g,g.then(()=>{e.batch(()=>{e.stores.status.get()===`pending`&&(e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())),e.updateMatch(t.id,e=>({...e,_displayPending:void 0,displayPendingPromise:void 0}))})})}return l}var V=e(n(),1),H=ue();function Ao({promise:e}){if(C)return C(e);let t=Qt(e);if(t[Zt].status===`pending`)throw t;if(t[Zt].status===`error`)throw t[Zt].error;return t[Zt].data}function jo(e){let t=(0,H.jsx)(Mo,{...e});return e.fallback?(0,H.jsx)(V.Suspense,{fallback:e.fallback,children:t}):t}function Mo(e){let t=Ao(e);return e.children(t)}function No(e){let t=e.errorComponent??Fo;return(0,H.jsx)(Po,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:n,reset:r})=>n?V.createElement(t,{error:n,reset:r}):e.children})}var Po=class extends V.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,t){this.props.onCatch&&this.props.onCatch(e,t)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function Fo({error:e}){let[t,n]=V.useState(!1);return(0,H.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,H.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,H.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,H.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,H.jsx)(`div`,{children:(0,H.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,H.jsx)(`code`,{children:e.message}):null})}):null]})}var Io=V.createContext(void 0),Lo=V.createContext(void 0),U=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(U||{});function Ro({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function zo(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var Bo=[],Vo=0,{link:Ho,unlink:Uo,propagate:Wo,checkDirty:Go,shallowPropagate:Ko}=Ro({update(e){return e._update()},notify(e){Bo[Jo++]=e,e.flags&=~U.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=U.Mutable|U.Dirty,Qo(e))}}),qo=0,Jo=0,Yo,Xo=0;function Zo(e){try{++Xo,e()}finally{--Xo||$o()}}function Qo(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Uo(n,e)}function $o(){if(!(Xo>0)){for(;qo{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=Yo,o=t?.compare??Object.is;if(n)Yo=i,++Vo,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=U.Mutable|U.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{Yo=a,n&&(i.flags&=~U.RecursedCheck),Qo(i)}}};return n?(i.flags=U.Mutable|U.Dirty,i.get=function(){let e=i.flags;if(e&U.Dirty||e&U.Pending&&Go(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&Ko(e)}}else e&U.Pending&&(i.flags=e&~U.Pending);return Yo!==void 0&&Ho(i,Yo,Vo),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Wo(e),Ko(e),$o())}},i}function ts(e){let t=()=>{let t=Yo;Yo=n,++Vo,n.depsTail=void 0,n.flags=U.Watching|U.RecursedCheck;try{return e()}finally{Yo=t,n.flags&=~U.RecursedCheck,Qo(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:U.Watching|U.RecursedCheck,notify(){let e=this.flags;e&U.Dirty||e&U.Pending&&Go(this.deps,this)?t():this.flags=U.Watching},stop(){this.flags=U.None,this.depsTail=void 0,Qo(this)}};return t(),n}var ns={get(){},subscribe(){return{unsubscribe(){}}}};function rs(e,t){let n=V.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=y(n.current,i):i}}function is(e){let t=D(),n=V.useContext(e.from?Lo:Io),r=e.from?t.stores.getRouteMatchStore(e.from):t.stores.matchStores.get(n),i=rs(e,t),a=w(r??ns,e=>e?i(e):ns);if(a!==ns)return a;(e.shouldThrow??!0)&&s()}function as(e){return is({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function os(e){let{select:t,...n}=e;return is({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function ss(e){return is({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function cs(e){return is({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function ls(e){let t=D();return V.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function us(e){let t=D(),n=ls(),r=V.useRef(null);return se(()=>{r.current!==e&&(n(e),r.current=e)},[t,e,n]),null}function ds(e){return is({...e,select:t=>e.select?e.select(t.context):t.context})}var fs=class extends on{constructor(e){super(e),this.useMatch=e=>is({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ds({...e,from:this.id}),this.useSearch=e=>cs({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ss({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>os({...e,from:this.id}),this.useLoaderData=e=>as({...e,from:this.id}),this.useNavigate=()=>ls({from:this.fullPath}),this.Link=V.forwardRef((e,t)=>(0,H.jsx)(de,{ref:t,from:this.fullPath,...e}))}};function ps(e){return new fs(e)}var ms=class extends sn{constructor(e){super(e),this.useMatch=e=>is({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>ds({...e,from:this.id}),this.useSearch=e=>cs({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>ss({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>os({...e,from:this.id}),this.useLoaderData=e=>as({...e,from:this.id}),this.useNavigate=()=>ls({from:this.fullPath}),this.Link=V.forwardRef((e,t)=>(0,H.jsx)(de,{ref:t,from:this.fullPath,...e}))}};function hs(e){return new ms(e)}function gs(e){return new _s(e,{silent:!0}).createRoute}var _s=class{constructor(e,t){this.path=e,this.createRoute=e=>{let t=ps(e);return t.isRoot=!1,t},this.silent=t?.silent}};function vs(e,t){let n,r,i,a,o=()=>(n||=e().then(e=>{n=void 0,r=e[t??`default`]}).catch(e=>{if(i=e,d(i)&&i instanceof Error&&typeof window<`u`&&typeof sessionStorage<`u`){let e=`tanstack_router_reload:${i.message}`;sessionStorage.getItem(e)||(sessionStorage.setItem(e,`1`),a=!0)}}),n),s=function(e){if(a)throw window.location.reload(),new Promise(()=>{});if(i)throw i;if(!r)if(C)C(o());else throw o();return V.createElement(r,e)};return s.preload=o,s}function ys(e){let t=D(),n=`not-found-${w(t.stores.location,e=>e.pathname)}-${w(t.stores.status,e=>e)}`;return(0,H.jsx)(No,{getResetKey:()=>n,onCatch:(t,n)=>{if(Ae(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(Ae(t))return e.fallback?.(t);throw t},children:e.children})}function bs(){return(0,H.jsx)(`p`,{children:`Not Found`})}function xs(e){return(0,H.jsx)(H.Fragment,{children:e.children})}function Ss(e,t,n){return t.options.notFoundComponent?(0,H.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,H.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,H.jsx)(bs,{})}var Cs=(e,t)=>e.routeId===t.routeId&&e._displayPending===t._displayPending,ws=(e,t)=>e[0]===t[0]&&e[1]===t[1],Ts=V.memo(function({matchId:e}){let t=D(),n=t.stores.matchStores.get(e);n||s();let r=w(t.stores.loadedAt,e=>e),i=w(n,e=>e,Cs);return(0,H.jsx)(Es,{router:t,matchId:e,resetKey:r,matchState:V.useMemo(()=>{let e=i.routeId,n=t.routesById[e].parentRoute?.id;return{routeId:e,ssr:i.ssr,_displayPending:i._displayPending,parentRouteId:n}},[i._displayPending,i.routeId,i.ssr,t.routesById])})});function Es({router:e,matchId:t,resetKey:n,matchState:r}){let i=e.routesById[r.routeId],a=i.options.pendingComponent??e.options.defaultPendingComponent,o=a?(0,H.jsx)(a,{}):null,s=i.options.errorComponent??e.options.defaultErrorComponent,c=i.options.onCatch??e.options.defaultOnCatch,l=i.isRoot?i.options.notFoundComponent??e.options.notFoundRoute?.options.component:i.options.notFoundComponent,u=r.ssr===!1||r.ssr===`data-only`,d=(!i.isRoot||i.options.wrapInSuspense||u)&&(i.options.wrapInSuspense??a??(i.options.errorComponent?.preload||u))?V.Suspense:xs,f=s?No:xs,p=l?ys:xs;return(0,H.jsxs)(i.isRoot?i.options.shellComponent??xs:xs,{children:[(0,H.jsx)(Io.Provider,{value:t,children:(0,H.jsx)(d,{fallback:o,children:(0,H.jsx)(f,{getResetKey:()=>n,errorComponent:s||Fo,onCatch:(e,t)=>{if(Ae(e))throw e.routeId??=r.routeId,e;c?.(e,t)},children:(0,H.jsx)(p,{fallback:e=>{if(e.routeId??=r.routeId,!l||e.routeId&&e.routeId!==r.routeId||!e.routeId&&!i.isRoot)throw e;return V.createElement(l,e)},children:u||r._displayPending?(0,H.jsx)(x,{fallback:o,children:(0,H.jsx)(Os,{matchId:t})}):(0,H.jsx)(Os,{matchId:t})})})})}),r.parentRouteId===`__root__`?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Ds,{}),(e.options.scrollRestoration,null)]}):null]})}function Ds(){let e=D(),t=V.useRef();return se(()=>{let n=e.stores.resolvedLocation.get(),r=t.current;n&&(!r||r.href!==n.href)&&e.emit({type:`onRendered`,...Bt(e.stores.location.get(),r??n)}),t.current=n},[w(e.stores.resolvedLocation,e=>e?.state.__TSR_key),e]),null}var Os=V.memo(function({matchId:e}){let t=D(),n=(e,n)=>t.getMatch(e.id)?._nonReactive[n]??e._nonReactive[n],r=t.stores.matchStores.get(e);r||s();let i=w(r,e=>e),a=i.routeId,o=t.routesById[a],c=V.useMemo(()=>{let e=(t.routesById[a].options.remountDeps??t.options.defaultRemountDeps)?.({routeId:a,loaderDeps:i.loaderDeps,params:i._strictParams,search:i._strictSearch});return e?JSON.stringify(e):void 0},[a,i.loaderDeps,i._strictParams,i._strictSearch,t.options.defaultRemountDeps,t.routesById]),l=V.useMemo(()=>{let e=o.options.component??t.options.defaultComponent;return e?(0,H.jsx)(e,{},c):(0,H.jsx)(ks,{})},[c,o.options.component,t.options.defaultComponent]);if(i._displayPending)throw n(i,`displayPendingPromise`);if(i._forcePending)throw n(i,`minPendingPromise`);if(i.status===`pending`){let e=o.options.pendingMinMs??t.options.defaultPendingMinMs;if(e){let n=t.getMatch(i.id);if(n&&!n._nonReactive.minPendingPromise){let t=oe();n._nonReactive.minPendingPromise=t,setTimeout(()=>{t.resolve(),n._nonReactive.minPendingPromise=void 0},e)}}throw n(i,`loadPromise`)}if(i.status===`notFound`)return Ae(i.error)||s(),Ss(t,o,i.error);if(i.status===`redirected`)throw et(i.error)||s(),n(i,`loadPromise`);if(i.status===`error`)throw i.error;return l}),ks=V.memo(function(){let e=D(),t=V.useContext(Io),n,r=!1,i;{let a=t?e.stores.matchStores.get(t):void 0;[n,r]=w(a,e=>[e?.routeId,e?.globalNotFound??!1],ws),i=w(e.stores.matchesId,e=>e[e.findIndex(e=>e===t)+1])}let a=n?e.routesById[n]:void 0,o=e.options.defaultPendingComponent?(0,H.jsx)(e.options.defaultPendingComponent,{}):null;if(r)return a||s(),Ss(e,a,void 0);if(!i)return null;let c=(0,H.jsx)(Ts,{matchId:i});return n===`__root__`?(0,H.jsx)(V.Suspense,{fallback:o,children:c}):c});function As(){let e=D(),t=V.useRef({router:e,mounted:!1}),[n,r]=V.useState(!1),i=w(e.stores.isLoading,e=>e),a=w(e.stores.hasPending,e=>e),o=fe(i),s=i||n||a,c=fe(s),l=i||a,u=fe(l);return e.startTransition=e=>{r(!0),V.startTransition(()=>{e(),r(!1)})},V.useEffect(()=>{let t=e.history.subscribe(e.load),n=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return pe(e.latestLocation.publicHref)!==pe(n.publicHref)&&e.commitLocation({...n,replace:!0}),()=>{t()}},[e,e.history]),se(()=>{typeof window<`u`&&e.ssr||t.current.router===e&&t.current.mounted||(t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(e){console.error(e)}})())},[e]),se(()=>{o&&!i&&e.emit({type:`onLoad`,...Bt(e.stores.location.get(),e.stores.resolvedLocation.get())})},[o,e,i]),se(()=>{u&&!l&&e.emit({type:`onBeforeRouteMount`,...Bt(e.stores.location.get(),e.stores.resolvedLocation.get())})},[l,u,e]),se(()=>{if(c&&!s){let t=Bt(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:`onResolved`,...t}),Zo(()=>{e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())})}},[s,c,e]),null}function js(){let e=D(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,n=t?(0,H.jsx)(t,{}):null,r=(0,H.jsxs)(typeof document<`u`&&e.ssr?xs:V.Suspense,{fallback:n,children:[(0,H.jsx)(As,{}),(0,H.jsx)(Ms,{})]});return e.options.InnerWrap?(0,H.jsx)(e.options.InnerWrap,{children:r}):r}function Ms(){let e=D(),t=w(e.stores.firstId,e=>e),n=w(e.stores.loadedAt,e=>e),r=t?(0,H.jsx)(Ts,{matchId:t}):null;return(0,H.jsx)(Io.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:(0,H.jsx)(No,{getResetKey:()=>n,errorComponent:Fo,onCatch:void 0,children:r})})}var Ns=e=>({createMutableStore:es,createReadonlyStore:es,batch:Zo}),Ps=e=>new Fs(e),Fs=class extends Vt{constructor(e){super(e,Ns)}};function Is({router:e,children:t,...n}){c(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,H.jsx)(ie.Provider,{value:e,children:t});return e.options.Wrap?(0,H.jsx)(e.options.Wrap,{children:r}):r}function Ls({router:e,...t}){return(0,H.jsx)(Is,{router:e,...t,children:(0,H.jsx)(js,{})})}function Rs(e,t){if(t)for(let[n,r]of Object.entries(t))n!==`suppressHydrationWarning`&&r!==void 0&&r!==!1&&e.setAttribute(n,typeof r==`boolean`?``:String(r))}function zs(e){let{attrs:t,children:n,nonce:r,preventScriptHoist:i}=e;switch(e.tag){case`title`:return(0,H.jsx)(`title`,{...t,suppressHydrationWarning:!0,children:n});case`meta`:return(0,H.jsx)(`meta`,{...t,suppressHydrationWarning:!0});case`link`:return(0,H.jsx)(`link`,{...t,precedence:t?.precedence??(t?.rel===`stylesheet`?`default`:void 0),nonce:r,suppressHydrationWarning:!0});case`style`:return e.inlineCss,(0,H.jsx)(`style`,{...t,dangerouslySetInnerHTML:{__html:n},nonce:r});case`script`:return(0,H.jsx)(Bs,{attrs:t,preventScriptHoist:i,children:n});default:return null}}function Bs({attrs:e,children:t,preventScriptHoist:n}){D();let r=le(),i=typeof e?.type==`string`&&e.type!==``&&e.type!==`text/javascript`&&e.type!==`module`;if(V.useEffect(()=>{if(!i){if(e?.src){let t=(()=>{try{let t=document.baseURI||window.location.href;return new URL(e.src,t).href}catch{return e.src}})();for(let e of document.querySelectorAll(`script[src]`))if(e.src===t)return;let n=document.createElement(`script`);return Rs(n,e),document.head.appendChild(n),()=>n.remove()}if(typeof t==`string`){let n=typeof e?.type==`string`?e.type:`text/javascript`,r=typeof e?.nonce==`string`?e.nonce:void 0;for(let e of document.querySelectorAll(`script:not([src])`)){if(!(e instanceof HTMLScriptElement))continue;let i=e.getAttribute(`type`)??`text/javascript`,a=e.getAttribute(`nonce`)??void 0;if(e.textContent===t&&i===n&&a===r)return}let i=document.createElement(`script`);return i.textContent=t,Rs(i,e),document.head.appendChild(i),()=>i.remove()}}},[e,t,i]),i&&typeof t==`string`)return(0,H.jsx)(`script`,{...e,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:t}});if(!r){if(e?.src)return(0,H.jsx)(`script`,{...e,suppressHydrationWarning:!0});if(typeof t==`string`)return(0,H.jsx)(`script`,{...e,dangerouslySetInnerHTML:{__html:t},suppressHydrationWarning:!0})}return null}var Vs=e=>{let t=D(),n=t.options.ssr?.nonce,r=w(t.stores.matches,e=>e.map(e=>e.meta).filter(e=>e!==void 0),ae),i=V.useMemo(()=>{let e=[],t={},i;for(let a=r.length-1;a>=0;a--){let o=r[a];for(let r=o.length-1;r>=0;r--){let a=o[r];if(a)if(a.title)i||={tag:`title`,children:a.title};else if(`script:ld+json`in a)try{let t=JSON.stringify(a[`script:ld+json`]);e.push({tag:`script`,attrs:{type:`application/ld+json`},children:p(t)})}catch{}else{let r=a.name??a.property;if(r){if(t[r])continue;t[r]=!0}e.push({tag:`meta`,attrs:{...a,nonce:n}})}}}return i&&e.push(i),n&&e.push({tag:`meta`,attrs:{property:`csp-nonce`,content:n}}),e.reverse(),e},[r,n]),a=w(t.stores.matches,e=>e.flatMap(e=>e.links??[]).filter(e=>e!==void 0).map(e=>({tag:`link`,attrs:{...e,nonce:n}})),ae),o=w(t.stores.matches,r=>{let i=t.ssr?.manifest,a=[];return i?(r.forEach(t=>{i.routes[t.routeId]?.css?.forEach(t=>{let r=an(t);a.push({tag:`link`,attrs:{rel:`stylesheet`,...r,crossOrigin:$t(e,`stylesheet`)??r.crossOrigin,suppressHydrationWarning:!0,nonce:n}})})}),i.inlineStyle&&a.push({tag:`style`,attrs:{...i.inlineStyle.attrs,nonce:n},children:i.inlineStyle.children,inlineCss:!0}),a):a},ae),s=w(t.stores.matches,r=>{let i=[],a=t.ssr?.manifest;return a&&r.forEach(t=>{a.routes[t.routeId]?.preloads?.forEach(t=>{i.push({tag:`link`,attrs:{...tn(a,t,e),nonce:n}})})}),i},ae),c=w(t.stores.matches,e=>e.flatMap(e=>e.styles??[]).filter(e=>e!==void 0).map(({children:e,...t})=>({tag:`style`,attrs:{...t,nonce:n},children:e})),ae),l=w(t.stores.matches,e=>e.flatMap(e=>e.headScripts??[]).filter(e=>e!==void 0).map(({children:e,...t})=>({tag:`script`,attrs:{...t,nonce:n},children:e})),ae),u=[];return rn(u,i),u.push(...s),rn(u,a),u.push(...o),rn(u,c),rn(u,l),u};function Hs(e){let t=Vs(e.assetCrossOrigin),n=D().options.ssr?.nonce;return(0,H.jsx)(H.Fragment,{children:t.map(e=>(0,V.createElement)(zs,{...e,key:`tsr-meta-${JSON.stringify(e)}`,nonce:n}))})}var Us=()=>{let e=D(),t=e.options.ssr?.nonce,n=n=>{let r=[],i=e.ssr?.manifest;if(!i)return[];for(let e of n){let n=i.routes[e.routeId]?.scripts;if(n)for(let e of n)r.push({tag:`script`,attrs:{...e.attrs,nonce:t},children:e.children,...typeof e.attrs?.src==`string`?{preventScriptHoist:!0}:{}})}return r},r=e=>e.map(e=>e.scripts).flat(1).filter(Boolean).map(({children:e,...n})=>({tag:`script`,attrs:{...n,suppressHydrationWarning:!0,nonce:t},children:e})),i=w(e.stores.matches,n,ae);return Ws(e,w(e.stores.matches,r,ae),i)};function Ws(e,t,n){let r=[...t,...n];return(0,H.jsx)(H.Fragment,{children:r.map((e,t)=>(0,V.createElement)(zs,{...e,key:`tsr-scripts-${e.tag}-${t}`}))})}function Gs({children:e}){return(0,H.jsx)(H.Fragment,{children:e})}var Ks=`/assets/styles-Dja5CCtV.css`,qs=hs({head:()=>({meta:[{charSet:`utf-8`},{name:`viewport`,content:`width=device-width, initial-scale=1`},{title:`Workspace — notes & docs`},{name:`description`,content:`A calm Notion-style workspace for notes, pages, and plans.`}],links:[{rel:`stylesheet`,href:Ks}]}),component:Js});function Js(){return(0,H.jsxs)(`html`,{lang:`en`,suppressHydrationWarning:!0,children:[(0,H.jsx)(`head`,{children:(0,H.jsx)(Hs,{})}),(0,H.jsxs)(`body`,{children:[(0,H.jsx)(Gs,{children:(0,H.jsx)(ks,{})}),(0,H.jsx)(Us,{})]})]})}var Ys=`modulepreload`,Xs=function(e){return`/`+e},Zs={},Qs=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Xs(t,n),t=s(t),t in Zs)return;Zs[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Ys,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},$s=gs(`/`)({component:vs(()=>Qs(()=>import(`./routes-C6kpKjAV.js`),__vite__mapDeps([0,1,2,3,4,5])),`component`)}),ec=gs(`/login`)({component:vs(()=>Qs(()=>import(`./login-C3NWOInE.js`),__vite__mapDeps([6,3,1,2,4,5])),`component`)}),tc={IndexRoute:$s.update({id:`/`,path:`/`,getParentRoute:()=>qs}),LoginRoute:ec.update({id:`/login`,path:`/login`,getParentRoute:()=>qs})},nc=qs._addFileChildren(tc);function rc(){return Ps({routeTree:nc})}async function ic(){let e=await rc(),t=[];return window.__TSS_START_OPTIONS__={serializationAdapters:t},t.push(Eo),e.options.serializationAdapters&&t.push(...e.options.serializationAdapters),e.update({basepath:``,serializationAdapters:t}),e.stores.matchesId.get().length||await ko(e),e}var ac=ic;async function oc(){let e=await ac();return window.$_TSR?.h(),e}var sc;function cc(){return sc||=oc(),(0,H.jsx)(jo,{promise:sc,children:e=>(0,H.jsx)(Ls,{router:e})})}var lc=be();(0,V.startTransition)(()=>{(0,lc.hydrateRoot)(document,(0,H.jsx)(V.StrictMode,{children:(0,H.jsx)(cc,{})}))});export{tt as a,et as i,us as n,ke as o,To as r,Ce as s,Qs as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/infoDiagram-FWYZ7A6U-M92teQJC.js b/.vercel/output/static/assets/infoDiagram-FWYZ7A6U-BY1UX4W6.js similarity index 70% rename from .vercel/output/static/assets/infoDiagram-FWYZ7A6U-M92teQJC.js rename to .vercel/output/static/assets/infoDiagram-FWYZ7A6U-BY1UX4W6.js index 2e5a4b9..cc3455f 100644 --- a/.vercel/output/static/assets/infoDiagram-FWYZ7A6U-M92teQJC.js +++ b/.vercel/output/static/assets/infoDiagram-FWYZ7A6U-BY1UX4W6.js @@ -1,2 +1,2 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{c as n}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as r}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{n as i}from"./mermaid-parser.core-AdnthA1k.js";var a={parse:e(async e=>{let n=await i(`info`,e);t.debug(n)},`parse`)},o={version:`11.16.0`},s={parser:a,db:{getVersion:e(()=>o.version,`getVersion`)},renderer:{draw:e((e,i,a)=>{t.debug(`rendering info diagram +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{c as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as r}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as i}from"./mermaid-parser.core-Z7xZAZRH.js";var a={parse:e(async e=>{let n=await i(`info`,e);t.debug(n)},`parse`)},o={version:`11.16.0`},s={parser:a,db:{getVersion:e(()=>o.version,`getVersion`)},renderer:{draw:e((e,i,a)=>{t.debug(`rendering info diagram `+e);let o=r(i);n(o,100,400,!0),o.append(`g`).append(`text`).attr(`x`,100).attr(`y`,40).attr(`class`,`version`).attr(`font-size`,32).style(`text-anchor`,`middle`).text(`v${a}`)},`draw`)}};export{s as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/input-mze7gZ5r.js b/.vercel/output/static/assets/input-mze7gZ5r.js new file mode 100644 index 0000000..fa8d0a3 --- /dev/null +++ b/.vercel/output/static/assets/input-mze7gZ5r.js @@ -0,0 +1 @@ +import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./react-BLJmJXjR.js";import{r as n,t as r,u as i}from"./utils-BTuSbA5p.js";import{t as a}from"./client-CwgDvMJw.js";var o=e(t(),1),s=Object.defineProperty,c=(e,t)=>s(e,`name`,{value:t,configurable:!0});function l(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}c(l,`setRef`);function u(...e){return t=>{let n=!1,r=e.map(e=>{let r=l(e,t);return!n&&typeof r==`function`&&(n=!0),r});if(n)return()=>{for(let t=0;tp(e,`name`,{value:t,configurable:!0}),h=m(((e,t)=>{let n={...t};for(let r in t){let i=e[r],a=t[r];if(/^on[A-Z]/.test(r))if(i&&a){let e=typeof i==`function`,t=typeof a==`function`;n[r]=(...n)=>{let r=t?a(...n):void 0;return e&&i(...n),r}}else i&&(n[r]=i);else r===`style`?n[r]={...typeof i==`object`?i:null,...typeof a==`object`?a:null}:r===`className`?n[r]=[i,a].filter(Boolean).join(` `):r===`aria-describedby`&&(n[r]=g(a,i))}return{...e,...n}}),`mergeProps`);function g(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}m(g,`concatAriaDescribedby`);var _=o.createContext(h);_.displayName=`SlotContext`;function v(e){let t=o.forwardRef((t,n)=>{let r=o.useContext(_),{children:i,mergeProps:a=r,...s}=t,c=null,l=!1,u=[];E(i)&&typeof A==`function`&&(i=A(i._payload)),o.Children.forEach(i,e=>{if(w(e)){l=!0;let t=e,n=`child`in t.props?t.props.child:t.props.children;E(n)&&typeof A==`function`&&(n=A(n._payload)),c=S(t,n),u.push(c?.props?.children)}else u.push(e)}),c?c=o.cloneElement(c,void 0,u):!l&&o.Children.count(i)===1&&o.isValidElement(i)&&(c=i);let f=c?C(c):void 0,p=d(n,f);if(!c){if(i||i===0)throw Error(l?k(e):O(e));return i}let m=a(s,c.props??{});return c.type!==o.Fragment&&(m.ref=n?p:f),o.cloneElement(c,m)});return t.displayName=`${e}.Slot`,t}m(v,`createSlot`);var y=v(`Slot`),b=Symbol.for(`radix.slottable`);function x(e){let t=m(e=>`child`in e?e.children(e.child):e.children,`Slottable`);return t.displayName=`${e}.Slottable`,t.__radixId=b,t}m(x,`createSlottable`);var S=m((e,t)=>{if(`child`in e.props){let t=e.props.child;return o.isValidElement(t)?o.cloneElement(t,void 0,e.props.children(t.props.children)):null}return o.isValidElement(t)?t:null},`getSlottableElementFromSlottable`);function C(e){let t=Object.getOwnPropertyDescriptor(e.props,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}m(C,`getElementRef`);function w(e){return o.isValidElement(e)&&typeof e.type==`function`&&`__radixId`in e.type&&e.type.__radixId===b}m(w,`isSlottable`);var T=Symbol.for(`react.lazy`);function E(e){return typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===T&&`_payload`in e&&D(e._payload)}m(E,`isLazyComponent`);function D(e){return typeof e==`object`&&!!e&&`then`in e}m(D,`isPromiseLike`);var O=m(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,`createSlotError`),k=m(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,`createSlottableError`),A=o.use,j=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,M=n,N=((e,t)=>n=>{if(t?.variants==null)return M(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=j(t)||j(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return M(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)})(`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[background-color,color,opacity,box-shadow,transform] duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:pointer-events-none disabled:opacity-50 active:scale-[0.98] [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/90`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,ghost:`hover:bg-muted text-foreground`,outline:`border border-border bg-transparent hover:bg-muted`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,soft:`bg-muted text-foreground hover:bg-muted/80`},size:{default:`h-9 px-3.5 py-2`,sm:`h-8 rounded-md px-2.5 text-xs`,lg:`h-10 rounded-lg px-4`,icon:`h-8 w-8`,"icon-sm":`h-7 w-7`}},defaultVariants:{variant:`default`,size:`default`}}),P=o.forwardRef(({className:e,variant:t,size:n,asChild:i=!1,...a},o)=>(0,f.jsx)(i?y:`button`,{className:r(N({variant:t,size:n,className:e})),ref:o,...a}));P.displayName=`Button`;function F(){let{data:e,isPending:t}=a.useSession(),n=e?.user;return{user:n?{id:n.id,displayName:n.name??null,primaryEmail:n.email??null,profileImageUrl:n.image??null,isDevFallback:!1}:null,isPending:t}}function I(){return F().user}var L=o.forwardRef(({className:e,type:t,...n},i)=>(0,f.jsx)(`input`,{type:t,className:r(`flex h-9 w-full rounded-md border border-border bg-background px-3 py-1 text-sm text-foreground shadow-none transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50`,e),ref:i,...n}));L.displayName=`Input`;export{v as a,d as c,P as i,I as n,x as o,F as r,u as s,L as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/ishikawaDiagram-FXEZZL3T-HpUKQ9Yc.js b/.vercel/output/static/assets/ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js similarity index 98% rename from .vercel/output/static/assets/ishikawaDiagram-FXEZZL3T-HpUKQ9Yc.js rename to .vercel/output/static/assets/ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js index 7a4fc9e..284aace 100644 --- a/.vercel/output/static/assets/ishikawaDiagram-FXEZZL3T-HpUKQ9Yc.js +++ b/.vercel/output/static/assets/ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-_wZywoZs.js";import{H as t,K as n,U as r,a as i,c as a,s as o,v as s,w as c,x as l,y as u}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{p as d}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as f}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{t as p}from"./rough.esm-CSKSodPl.js";var m=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,14],i=[1,12],a=[1,13],o=[6,7,8],s=[1,20],c=[1,18],l=[1,19],u=[6,7,11],d=[1,6,13,14],f=[1,23],p=[1,24],m=[1,6,7,11,13,14],h={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,ishikawa:4,spaceLines:5,SPACELINE:6,NL:7,ISHIKAWA:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,TEXT:14,$accept:0,$end:1},terminals_:{2:`error`,6:`SPACELINE`,7:`NL`,8:`ISHIKAWA`,11:`EOF`,13:`SPACELIST`,14:`TEXT`},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,2],[12,1],[12,1],[12,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 6:case 7:return r;case 15:r.addNode(a[s-1].length,a[s].trim());break;case 16:r.addNode(0,a[s].trim());break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],8:n},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:n},{6:r,7:[1,10],9:9,12:11,13:i,14:a},t(o,[2,3]),{1:[2,2]},t(o,[2,4]),t(o,[2,5]),{1:[2,6],6:r,12:15,13:i,14:a},{6:r,9:16,12:11,13:i,14:a},{6:s,7:c,10:17,11:l},t(u,[2,18],{14:[1,21]}),t(u,[2,16]),t(u,[2,17]),{6:s,7:c,10:22,11:l},{1:[2,7],6:r,12:15,13:i,14:a},t(d,[2,14],{7:f,11:p}),t(m,[2,8]),t(m,[2,9]),t(m,[2,10]),t(u,[2,15]),t(d,[2,13],{7:f,11:p}),t(m,[2,11]),t(m,[2,12])],defaultActions:{2:[2,1],6:[2,2]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-UMNXGZaF.js";import{H as t,K as n,U as r,a as i,c as a,s as o,v as s,w as c,x as l,y as u}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{p as d}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as f}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as p}from"./rough.esm-CSKSodPl.js";var m=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,14],i=[1,12],a=[1,13],o=[6,7,8],s=[1,20],c=[1,18],l=[1,19],u=[6,7,11],d=[1,6,13,14],f=[1,23],p=[1,24],m=[1,6,7,11,13,14],h={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,ishikawa:4,spaceLines:5,SPACELINE:6,NL:7,ISHIKAWA:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,TEXT:14,$accept:0,$end:1},terminals_:{2:`error`,6:`SPACELINE`,7:`NL`,8:`ISHIKAWA`,11:`EOF`,13:`SPACELIST`,14:`TEXT`},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,2],[12,1],[12,1],[12,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 6:case 7:return r;case 15:r.addNode(a[s-1].length,a[s].trim());break;case 16:r.addNode(0,a[s].trim());break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],8:n},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:n},{6:r,7:[1,10],9:9,12:11,13:i,14:a},t(o,[2,3]),{1:[2,2]},t(o,[2,4]),t(o,[2,5]),{1:[2,6],6:r,12:15,13:i,14:a},{6:r,9:16,12:11,13:i,14:a},{6:s,7:c,10:17,11:l},t(u,[2,18],{14:[1,21]}),t(u,[2,16]),t(u,[2,17]),{6:s,7:c,10:22,11:l},{1:[2,7],6:r,12:15,13:i,14:a},t(d,[2,14],{7:f,11:p}),t(m,[2,8]),t(m,[2,9]),t(m,[2,10]),t(u,[2,15]),t(d,[2,13],{7:f,11:p}),t(m,[2,11]),t(m,[2,12])],defaultActions:{2:[2,1],6:[2,2]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};h.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/journeyDiagram-5HDEW3XC-DyhbVNP5.js b/.vercel/output/static/assets/journeyDiagram-5HDEW3XC-CCn-uNlj.js similarity index 98% rename from .vercel/output/static/assets/journeyDiagram-5HDEW3XC-DyhbVNP5.js rename to .vercel/output/static/assets/journeyDiagram-5HDEW3XC-CCn-uNlj.js index f3dc73a..88cb2d8 100644 --- a/.vercel/output/static/assets/journeyDiagram-5HDEW3XC-DyhbVNP5.js +++ b/.vercel/output/static/assets/journeyDiagram-5HDEW3XC-CCn-uNlj.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-_wZywoZs.js";import{H as n,K as r,U as i,a,c as o,v as s,w as c,x as l,y as u}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as d}from"./arc-BjSQqbzd.js";import{t as f}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{a as p,n as m,o as h,s as g}from"./chunk-32BRIVSS-BtH22FN8.js";var _=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[6,8,10,11,12,14,16,17,18],r=[1,9],i=[1,10],a=[1,11],o=[1,12],s=[1,13],c=[1,14],l={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,journey:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NEWLINE:10,title:11,acc_title:12,acc_title_value:13,acc_descr:14,acc_descr_value:15,acc_descr_multiline_value:16,section:17,taskName:18,taskData:19,$accept:0,$end:1},terminals_:{2:`error`,4:`journey`,6:`EOF`,8:`SPACE`,10:`NEWLINE`,11:`title`,12:`acc_title`,13:`acc_title_value`,14:`acc_descr`,15:`acc_descr_value`,16:`acc_descr_multiline_value`,17:`section`,18:`taskName`,19:`taskData`},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,2]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 2:this.$=[];break;case 3:a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 5:this.$=a[s];break;case 6:case 7:this.$=[];break;case 8:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 9:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 10:case 11:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 12:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 13:r.addTask(a[s-1],a[s]),this.$=`task`;break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},t(n,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:r,12:i,14:a,16:o,17:s,18:c},t(n,[2,7],{1:[2,1]}),t(n,[2,3]),{9:15,11:r,12:i,14:a,16:o,17:s,18:c},t(n,[2,5]),t(n,[2,6]),t(n,[2,8]),{13:[1,16]},{15:[1,17]},t(n,[2,11]),t(n,[2,12]),{19:[1,18]},t(n,[2,4]),t(n,[2,9]),t(n,[2,10]),t(n,[2,13])],defaultActions:{},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,c as o,v as s,w as c,x as l,y as u}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as d}from"./arc-DqK6O3qL.js";import{t as f}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{a as p,n as m,o as h,s as g}from"./chunk-32BRIVSS-DWU3ezKg.js";var _=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[6,8,10,11,12,14,16,17,18],r=[1,9],i=[1,10],a=[1,11],o=[1,12],s=[1,13],c=[1,14],l={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,journey:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NEWLINE:10,title:11,acc_title:12,acc_title_value:13,acc_descr:14,acc_descr_value:15,acc_descr_multiline_value:16,section:17,taskName:18,taskData:19,$accept:0,$end:1},terminals_:{2:`error`,4:`journey`,6:`EOF`,8:`SPACE`,10:`NEWLINE`,11:`title`,12:`acc_title`,13:`acc_title_value`,14:`acc_descr`,15:`acc_descr_value`,16:`acc_descr_multiline_value`,17:`section`,18:`taskName`,19:`taskData`},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,2]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 2:this.$=[];break;case 3:a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 5:this.$=a[s];break;case 6:case 7:this.$=[];break;case 8:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 9:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 10:case 11:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 12:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 13:r.addTask(a[s-1],a[s]),this.$=`task`;break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},t(n,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:r,12:i,14:a,16:o,17:s,18:c},t(n,[2,7],{1:[2,1]}),t(n,[2,3]),{9:15,11:r,12:i,14:a,16:o,17:s,18:c},t(n,[2,5]),t(n,[2,6]),t(n,[2,8]),{13:[1,16]},{15:[1,17]},t(n,[2,11]),t(n,[2,12]),{19:[1,18]},t(n,[2,4]),t(n,[2,9]),t(n,[2,10]),t(n,[2,13])],defaultActions:{},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};l.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/kanban-definition-HUTT4EX6-CgzuYK19.js b/.vercel/output/static/assets/kanban-definition-HUTT4EX6-CW9CwpnR.js similarity index 97% rename from .vercel/output/static/assets/kanban-definition-HUTT4EX6-CgzuYK19.js rename to .vercel/output/static/assets/kanban-definition-HUTT4EX6-CW9CwpnR.js index 7e2eeb1..1d105a8 100644 --- a/.vercel/output/static/assets/kanban-definition-HUTT4EX6-CgzuYK19.js +++ b/.vercel/output/static/assets/kanban-definition-HUTT4EX6-CW9CwpnR.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{J as n,et as r,f as i,rt as a,tt as o,x as s,z as c}from"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-ICXQ74PX-fa5hHXws.js";import{t as l}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import{t as u}from"./chunk-5VM5RSS4-ZNzvKenW.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import{a as d,c as f,i as p}from"./chunk-ZGVPDNZ5-zo3h_nOA.js";import{n as m,t as h}from"./chunk-ZIRB5QZD-C6fEPe3t.js";var g=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,13],i=[1,12],a=[1,15],o=[1,16],s=[1,20],c=[1,19],l=[6,7,8],u=[1,26],d=[1,24],f=[1,25],p=[6,7,11],m=[1,31],h=[6,7,11,24],g=[1,6,13,16,17,20,23],_=[1,35],v=[1,36],y=[1,6,7,11,13,16,17,20,23],b=[1,38],x={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mindMap:4,spaceLines:5,SPACELINE:6,NL:7,KANBAN:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,node:14,shapeData:15,ICON:16,CLASS:17,nodeWithId:18,nodeWithoutId:19,NODE_DSTART:20,NODE_DESCR:21,NODE_DEND:22,NODE_ID:23,SHAPE_DATA:24,$accept:0,$end:1},terminals_:{2:`error`,6:`SPACELINE`,7:`NL`,8:`KANBAN`,11:`EOF`,13:`SPACELIST`,16:`ICON`,17:`CLASS`,20:`NODE_DSTART`,21:`NODE_DESCR`,22:`NODE_DEND`,23:`NODE_ID`,24:`SHAPE_DATA`},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,3],[12,2],[12,2],[12,2],[12,1],[12,2],[12,1],[12,1],[12,1],[12,1],[14,1],[14,1],[19,3],[18,1],[18,4],[15,2],[15,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 6:case 7:return r;case 8:r.getLogger().trace(`Stop NL `);break;case 9:r.getLogger().trace(`Stop EOF `);break;case 11:r.getLogger().trace(`Stop NL2 `);break;case 12:r.getLogger().trace(`Stop EOF2 `);break;case 15:r.getLogger().info(`Node: `,a[s-1].id),r.addNode(a[s-2].length,a[s-1].id,a[s-1].descr,a[s-1].type,a[s]);break;case 16:r.getLogger().info(`Node: `,a[s].id),r.addNode(a[s-1].length,a[s].id,a[s].descr,a[s].type);break;case 17:r.getLogger().trace(`Icon: `,a[s]),r.decorateNode({icon:a[s]});break;case 18:case 23:r.decorateNode({class:a[s]});break;case 19:r.getLogger().trace(`SPACELIST`);break;case 20:r.getLogger().trace(`Node: `,a[s-1].id),r.addNode(0,a[s-1].id,a[s-1].descr,a[s-1].type,a[s]);break;case 21:r.getLogger().trace(`Node: `,a[s].id),r.addNode(0,a[s].id,a[s].descr,a[s].type);break;case 22:r.decorateNode({icon:a[s]});break;case 27:r.getLogger().trace(`node found ..`,a[s-2]),this.$={id:a[s-1],descr:a[s-1],type:r.getType(a[s-2],a[s])};break;case 28:this.$={id:a[s],descr:a[s],type:0};break;case 29:r.getLogger().trace(`node found ..`,a[s-3]),this.$={id:a[s-3],descr:a[s-1],type:r.getType(a[s-2],a[s])};break;case 30:this.$=a[s-1]+a[s];break;case 31:this.$=a[s];break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],8:n},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:n},{6:r,7:[1,10],9:9,12:11,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},t(l,[2,3]),{1:[2,2]},t(l,[2,4]),t(l,[2,5]),{1:[2,6],6:r,12:21,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},{6:r,9:22,12:11,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},{6:u,7:d,10:23,11:f},t(p,[2,24],{18:17,19:18,14:27,16:[1,28],17:[1,29],20:s,23:c}),t(p,[2,19]),t(p,[2,21],{15:30,24:m}),t(p,[2,22]),t(p,[2,23]),t(h,[2,25]),t(h,[2,26]),t(h,[2,28],{20:[1,32]}),{21:[1,33]},{6:u,7:d,10:34,11:f},{1:[2,7],6:r,12:21,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},t(g,[2,14],{7:_,11:v}),t(y,[2,8]),t(y,[2,9]),t(y,[2,10]),t(p,[2,16],{15:37,24:m}),t(p,[2,17]),t(p,[2,18]),t(p,[2,20],{24:b}),t(h,[2,31]),{21:[1,39]},{22:[1,40]},t(g,[2,13],{7:_,11:v}),t(y,[2,11]),t(y,[2,12]),t(p,[2,15],{24:b}),t(h,[2,30]),{22:[1,41]},t(h,[2,27]),t(h,[2,29])],defaultActions:{2:[2,1],6:[2,2]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{J as n,et as r,f as i,rt as a,tt as o,x as s,z as c}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as l}from"./chunk-VAUOI2AC-AC9pRUsa.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{t as u}from"./chunk-5VM5RSS4-ZNzvKenW.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import{a as d,c as f,i as p}from"./chunk-ZGVPDNZ5-DGInJAPD.js";import{n as m,t as h}from"./chunk-ZIRB5QZD-C6fEPe3t.js";var g=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,13],i=[1,12],a=[1,15],o=[1,16],s=[1,20],c=[1,19],l=[6,7,8],u=[1,26],d=[1,24],f=[1,25],p=[6,7,11],m=[1,31],h=[6,7,11,24],g=[1,6,13,16,17,20,23],_=[1,35],v=[1,36],y=[1,6,7,11,13,16,17,20,23],b=[1,38],x={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mindMap:4,spaceLines:5,SPACELINE:6,NL:7,KANBAN:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,node:14,shapeData:15,ICON:16,CLASS:17,nodeWithId:18,nodeWithoutId:19,NODE_DSTART:20,NODE_DESCR:21,NODE_DEND:22,NODE_ID:23,SHAPE_DATA:24,$accept:0,$end:1},terminals_:{2:`error`,6:`SPACELINE`,7:`NL`,8:`KANBAN`,11:`EOF`,13:`SPACELIST`,16:`ICON`,17:`CLASS`,20:`NODE_DSTART`,21:`NODE_DESCR`,22:`NODE_DEND`,23:`NODE_ID`,24:`SHAPE_DATA`},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,3],[12,2],[12,2],[12,2],[12,1],[12,2],[12,1],[12,1],[12,1],[12,1],[14,1],[14,1],[19,3],[18,1],[18,4],[15,2],[15,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 6:case 7:return r;case 8:r.getLogger().trace(`Stop NL `);break;case 9:r.getLogger().trace(`Stop EOF `);break;case 11:r.getLogger().trace(`Stop NL2 `);break;case 12:r.getLogger().trace(`Stop EOF2 `);break;case 15:r.getLogger().info(`Node: `,a[s-1].id),r.addNode(a[s-2].length,a[s-1].id,a[s-1].descr,a[s-1].type,a[s]);break;case 16:r.getLogger().info(`Node: `,a[s].id),r.addNode(a[s-1].length,a[s].id,a[s].descr,a[s].type);break;case 17:r.getLogger().trace(`Icon: `,a[s]),r.decorateNode({icon:a[s]});break;case 18:case 23:r.decorateNode({class:a[s]});break;case 19:r.getLogger().trace(`SPACELIST`);break;case 20:r.getLogger().trace(`Node: `,a[s-1].id),r.addNode(0,a[s-1].id,a[s-1].descr,a[s-1].type,a[s]);break;case 21:r.getLogger().trace(`Node: `,a[s].id),r.addNode(0,a[s].id,a[s].descr,a[s].type);break;case 22:r.decorateNode({icon:a[s]});break;case 27:r.getLogger().trace(`node found ..`,a[s-2]),this.$={id:a[s-1],descr:a[s-1],type:r.getType(a[s-2],a[s])};break;case 28:this.$={id:a[s],descr:a[s],type:0};break;case 29:r.getLogger().trace(`node found ..`,a[s-3]),this.$={id:a[s-3],descr:a[s-1],type:r.getType(a[s-2],a[s])};break;case 30:this.$=a[s-1]+a[s];break;case 31:this.$=a[s];break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],8:n},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:n},{6:r,7:[1,10],9:9,12:11,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},t(l,[2,3]),{1:[2,2]},t(l,[2,4]),t(l,[2,5]),{1:[2,6],6:r,12:21,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},{6:r,9:22,12:11,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},{6:u,7:d,10:23,11:f},t(p,[2,24],{18:17,19:18,14:27,16:[1,28],17:[1,29],20:s,23:c}),t(p,[2,19]),t(p,[2,21],{15:30,24:m}),t(p,[2,22]),t(p,[2,23]),t(h,[2,25]),t(h,[2,26]),t(h,[2,28],{20:[1,32]}),{21:[1,33]},{6:u,7:d,10:34,11:f},{1:[2,7],6:r,12:21,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},t(g,[2,14],{7:_,11:v}),t(y,[2,8]),t(y,[2,9]),t(y,[2,10]),t(p,[2,16],{15:37,24:m}),t(p,[2,17]),t(p,[2,18]),t(p,[2,20],{24:b}),t(h,[2,31]),{21:[1,39]},{22:[1,40]},t(g,[2,13],{7:_,11:v}),t(y,[2,11]),t(y,[2,12]),t(p,[2,15],{24:b}),t(h,[2,30]),{22:[1,41]},t(h,[2,27]),t(h,[2,29])],defaultActions:{2:[2,1],6:[2,2]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};x.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/line-CDW8hdKE.js b/.vercel/output/static/assets/line-b9Ala942.js similarity index 93% rename from .vercel/output/static/assets/line-CDW8hdKE.js rename to .vercel/output/static/assets/line-b9Ala942.js index bccd61d..74bfb70 100644 --- a/.vercel/output/static/assets/line-CDW8hdKE.js +++ b/.vercel/output/static/assets/line-b9Ala942.js @@ -1 +1 @@ -import{n as e,t}from"./path-BWPyau1x.js";import{t as n}from"./array-BifhSqXX.js";import{rt as r}from"./chunk-ICXQ74PX-fa5hHXws.js";function i(e){return e[0]}function a(e){return e[1]}function o(o,s){var c=e(!0),l=null,u=r,d=null,f=t(p);o=typeof o==`function`?o:o===void 0?i:e(o),s=typeof s==`function`?s:s===void 0?a:e(s);function p(e){var t,r=(e=n(e)).length,i,a=!1,p;for(l??(d=u(p=f())),t=0;t<=r;++t)!(tt?1:e>=t?0:NaN}function d(e,t){return e==null||t==null?NaN:te?1:t>=e?0:NaN}function f(e){let t,n,r;e.length===2?(t=e===u||e===d?e:p,n=e,r=e):(t=u,n=(t,n)=>u(e(t),n),r=(t,n)=>e(t)-n);function i(e,r,i=0,a=e.length){if(i>>1;n(e[t],r)<0?i=t+1:a=t}while(i>>1;n(e[t],r)<=0?i=t+1:a=t}while(in&&r(e[o-1],t)>-r(e[o],t)?o-1:o}return{left:i,center:o,right:a}}function p(){return 0}function m(e){return e===null?NaN:+e}var h=f(u),g=h.right;h.left,f(m).center;var _=Math.sqrt(50),v=Math.sqrt(10),y=Math.sqrt(2);function b(e,t,n){let r=(t-e)/Math.max(0,n),i=Math.floor(Math.log10(r)),a=r/10**i,o=a>=_?10:a>=v?5:a>=y?2:1,s,c,l;return i<0?(l=10**-i/o,s=Math.round(e*l),c=Math.round(t*l),s/lt&&--c,l=-l):(l=10**i*o,s=Math.round(e/l),c=Math.round(t/l),s*lt&&--c),c0))return[];if(e===t)return[e];let r=t=i))return[];let s=a-i+1,c=Array(s);if(r)if(o<0)for(let e=0;et&&(n=e,e=t,t=n),function(n){return Math.max(e,Math.min(t,n))}}function B(e,t,n){var r=e[0],i=e[1],a=t[0],o=t[1];return i2?V:B,l=u=null,f}function f(t){return t==null||isNaN(t=+t)?o:(l||=c(e.map(i),n,r))(i(s(t)))}return f.invert=function(r){return s(a((u||=c(n,e.map(i),t))(r)))},f.domain=function(t){return arguments.length?(e=Array.from(t,F),d()):e.slice()},f.range=function(e){return arguments.length?(n=Array.from(e),d()):n.slice()},f.rangeRound=function(e){return n=Array.from(e),r=A,d()},f.clamp=function(e){return arguments.length?(s=e?!0:L,d()):s!==L},f.interpolate=function(e){return arguments.length?(r=e,d()):r},f.unknown=function(e){return arguments.length?(o=e,f):o},function(e,t){return i=e,a=t,d()}}function W(){return U()(L,L)}function G(e,t,n,r){var i=C(e,t,n),a;switch(r=s(r??`,f`),r.type){case`s`:var l=Math.max(Math.abs(e),Math.abs(t));return r.precision==null&&!isNaN(a=M(i,l))&&(r.precision=a),o(r,l);case``:case`e`:case`g`:case`p`:case`r`:r.precision==null&&!isNaN(a=N(i,Math.max(Math.abs(e),Math.abs(t))))&&(r.precision=a-(r.type===`e`));break;case`f`:case`%`:r.precision==null&&!isNaN(a=j(i))&&(r.precision=a-(r.type===`%`)*2);break}return c(r)}function K(e){var t=e.domain;return e.ticks=function(e){var n=t();return x(n[0],n[n.length-1],e??10)},e.tickFormat=function(e,n){var r=t();return G(r[0],r[r.length-1],e??10,n)},e.nice=function(n){n??=10;var r=t(),i=0,a=r.length-1,o=r[i],s=r[a],c,l,u=10;for(s0;){if(l=S(o,s,n),l===c)return r[i]=o,r[a]=s,t(r);if(l>0)o=Math.floor(o/l)*l,s=Math.ceil(s/l)*l;else if(l<0)o=Math.ceil(o*l)/l,s=Math.floor(s*l)/l;else break;c=l}return e},e}function q(){var e=W();return e.copy=function(){return H(e,q())},l.apply(e,arguments),K(e)}export{f as a,C as i,W as n,H as r,q as t}; \ No newline at end of file +import{l as e,n as t,o as n,r,t as i}from"./src-UMNXGZaF.js";import{i as a,n as o,r as s,t as c}from"./defaultLocale-C8Fc0cco.js";import{t as l}from"./init-D6jRqBbL.js";function u(e,t){return e==null||t==null?NaN:et?1:e>=t?0:NaN}function d(e,t){return e==null||t==null?NaN:te?1:t>=e?0:NaN}function f(e){let t,n,r;e.length===2?(t=e===u||e===d?e:p,n=e,r=e):(t=u,n=(t,n)=>u(e(t),n),r=(t,n)=>e(t)-n);function i(e,r,i=0,a=e.length){if(i>>1;n(e[t],r)<0?i=t+1:a=t}while(i>>1;n(e[t],r)<=0?i=t+1:a=t}while(in&&r(e[o-1],t)>-r(e[o],t)?o-1:o}return{left:i,center:o,right:a}}function p(){return 0}function m(e){return e===null?NaN:+e}var h=f(u),g=h.right;h.left,f(m).center;var _=Math.sqrt(50),v=Math.sqrt(10),y=Math.sqrt(2);function b(e,t,n){let r=(t-e)/Math.max(0,n),i=Math.floor(Math.log10(r)),a=r/10**i,o=a>=_?10:a>=v?5:a>=y?2:1,s,c,l;return i<0?(l=10**-i/o,s=Math.round(e*l),c=Math.round(t*l),s/lt&&--c,l=-l):(l=10**i*o,s=Math.round(e/l),c=Math.round(t/l),s*lt&&--c),c0))return[];if(e===t)return[e];let r=t=i))return[];let s=a-i+1,c=Array(s);if(r)if(o<0)for(let e=0;et&&(n=e,e=t,t=n),function(n){return Math.max(e,Math.min(t,n))}}function B(e,t,n){var r=e[0],i=e[1],a=t[0],o=t[1];return i2?V:B,l=u=null,f}function f(t){return t==null||isNaN(t=+t)?o:(l||=c(e.map(i),n,r))(i(s(t)))}return f.invert=function(r){return s(a((u||=c(n,e.map(i),t))(r)))},f.domain=function(t){return arguments.length?(e=Array.from(t,F),d()):e.slice()},f.range=function(e){return arguments.length?(n=Array.from(e),d()):n.slice()},f.rangeRound=function(e){return n=Array.from(e),r=A,d()},f.clamp=function(e){return arguments.length?(s=e?!0:L,d()):s!==L},f.interpolate=function(e){return arguments.length?(r=e,d()):r},f.unknown=function(e){return arguments.length?(o=e,f):o},function(e,t){return i=e,a=t,d()}}function W(){return U()(L,L)}function G(e,t,n,r){var i=C(e,t,n),a;switch(r=s(r??`,f`),r.type){case`s`:var l=Math.max(Math.abs(e),Math.abs(t));return r.precision==null&&!isNaN(a=M(i,l))&&(r.precision=a),o(r,l);case``:case`e`:case`g`:case`p`:case`r`:r.precision==null&&!isNaN(a=N(i,Math.max(Math.abs(e),Math.abs(t))))&&(r.precision=a-(r.type===`e`));break;case`f`:case`%`:r.precision==null&&!isNaN(a=j(i))&&(r.precision=a-(r.type===`%`)*2);break}return c(r)}function K(e){var t=e.domain;return e.ticks=function(e){var n=t();return x(n[0],n[n.length-1],e??10)},e.tickFormat=function(e,n){var r=t();return G(r[0],r[r.length-1],e??10,n)},e.nice=function(n){n??=10;var r=t(),i=0,a=r.length-1,o=r[i],s=r[a],c,l,u=10;for(s0;){if(l=S(o,s,n),l===c)return r[i]=o,r[a]=s,t(r);if(l>0)o=Math.floor(o/l)*l,s=Math.ceil(s/l)*l;else if(l<0)o=Math.ceil(o*l)/l,s=Math.floor(s*l)/l;else break;c=l}return e},e}function q(){var e=W();return e.copy=function(){return H(e,q())},l.apply(e,arguments),K(e)}export{f as a,C as i,W as n,H as r,q as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/link-DYUXAN0T.js b/.vercel/output/static/assets/link-DYUXAN0T.js deleted file mode 100644 index 3554a36..0000000 --- a/.vercel/output/static/assets/link-DYUXAN0T.js +++ /dev/null @@ -1 +0,0 @@ -import{r as e,t}from"./rolldown-runtime-QTnfLwEv.js";import{t as n}from"./react-Biaal4sZ.js";var r=t((e=>{var t=n();function r(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=r()}));function a(e){return e[e.length-1]}function o(e){return typeof e==`function`}function s(e,t){return o(e)?e(t):e}var c=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable;function u(e){for(let t in e)if(c.call(e,t))return!0;return!1}var d=()=>Object.create(null),f=(e,t)=>p(e,t,d);function p(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=_(e)&&_(i);if(!a&&!(h(e)&&h(i)))return i;let o=a?e:m(e);if(!o)return i;let s=a?i:m(i);if(!s)return i;let l=o.length,u=s.length,d=a?Array(u):n(),f=0;for(let t=0;ti||!v(e[o],t[o],n)))return!1;return i===a}return!1}function y(e){let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.status=`pending`,r.resolve=n=>{r.status=`resolved`,r.value=n,t(n),e?.(n)},r.reject=e=>{r.status=`rejected`,n(e)},r}function b(e){return typeof e?.message==`string`?e.message.startsWith(`Failed to fetch dynamically imported module`)||e.message.startsWith(`error loading dynamically imported module`)||e.message.startsWith(`Importing a module script failed`):!1}function x(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}var S=/[\x00-\x1f\x7f"<>`{}]/g;function C(e){return e.replace(S,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function w(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return C(t)}var T=[`http:`,`https:`,`mailto:`,`tel:`];function E(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}var D={"&":`\\u0026`,">":`\\u003e`,"<":`\\u003c`,"\u2028":`\\u2028`,"\u2029":`\\u2029`},O=/[&><\u2028\u2029]/g;function k(e){return e.replace(O,e=>D[e])}function ee(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=w(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=w(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function te(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function ne(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var j=4,ie=5;function ae(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function oe(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=ae(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=I(1,n.fullPath??n.from,f,p,m);o=e,e.depth=a,e.parent=i,i.dynamic??=[],i.dynamic.push(e)}break}case 3:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.optional?.find(e=>!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=I(3,n.fullPath??n.from,f,p,m);o=e,e.parent=i,e.depth=a,i.optional??=[],i.optional.push(e)}break}case 2:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),l=c&&!!(t||s),f=t?l?t:t.toLowerCase():void 0,p=s?l?s:s.toLowerCase():void 0,m=I(2,n.fullPath??n.from,l,f,p);o=m,m.parent=i,m.depth=a,i.wildcard??=[],i.wildcard.push(m)}}i=o}if(l&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=F(n.fullPath??n.from);e.kind=ie,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let u=(n.path||!n.children)&&!n.isRoot;if(u&&r.endsWith(`/`)){let e=F(n.fullPath??n.from);e.kind=j,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=l??null,i.priority=n.options?.params?.priority??0,u&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(let r of n.children)M(e,t,r,s,i,a,o)}function N(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function P(e){if(e.pathless)for(let t of e.pathless)P(t);if(e.static)for(let t of e.static.values())P(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())P(t);if(e.dynamic?.length){e.dynamic.sort(N);for(let t of e.dynamic)P(t)}if(e.optional?.length){e.optional.sort(N);for(let t of e.optional)P(t)}if(e.wildcard?.length){e.wildcard.sort(N);for(let t of e.wildcard)P(t)}}function F(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function I(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function L(e,t){let n=F(`/`),r=new Uint16Array(6);for(let t of e)M(!1,r,t,1,n,0);P(n),t.masksTree=n,t.flatCache=A(1e3)}function se(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=V(e,t.masksTree);return t.flatCache.set(e,r),r}function ce(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=F(`/`),M(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),V(r,o,n)}function R(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=V(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=U(a.route)),t.matchCache.set(r,a),a}function z(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function B(e,t=!1,n){let r=F(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return M(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&re(),a[e.id]=e,s!==0&&e.path){let t=z(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),P(r),{processedTree:{segmentTree:r,singleCache:A(1e3),matchCache:A(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function V(e,t,n=!1){let r=e.split(`/`),i=ue(e,r,t,n);if(!i)return null;let[a]=H(e,r,i);return{route:i.node.route,rawParams:a}}function H(e,t,n){let r=le(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s=0;e--){let n=i.wildcard[e],{prefix:r,suffix:o}=n;if(!(r&&(v||!(n.caseSensitive?y:b??=y.toLowerCase()).startsWith(r)))){if(o){if(v)continue;let e=t.slice(a).join(`/`).slice(-o.length);if((n.caseSensitive?e:e.toLowerCase())!==o)continue}c.push({node:n,index:s,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}if(i.optional){let e=d|1<=0;n--){let r=i.optional[n];c.push({node:r,index:a,skipped:e,depth:t,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v)for(let e=i.optional.length-1;e>=0;e--){let n=i.optional[e],{prefix:r,suffix:o}=n;if(r||o){let e=n.caseSensitive?y:b??=y.toLowerCase();if(r&&!e.startsWith(r)||o&&!e.endsWith(o))continue}c.push({node:n,index:a+1,skipped:d,depth:t,statics:p,dynamics:m,optionals:h+W(s,a),extract:g,rawParams:_})}}if(!v&&i.dynamic&&y)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?y:b??=y.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}c.push({node:t,index:a+1,skipped:d,depth:f+1,statics:p,dynamics:m+W(s,a),optionals:h,extract:g,rawParams:_})}if(!v&&i.staticInsensitive){let e=i.staticInsensitive.get(b??=y.toLowerCase());e&&c.push({node:e,index:a+1,skipped:d,depth:f+1,statics:p+W(s,a),dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v&&i.static){let e=i.static.get(y);e&&c.push({node:e,index:a+1,skipped:d,depth:f+1,statics:p+W(s,a),dynamics:m,optionals:h,extract:g,rawParams:_})}if(i.pathless){let e=f+1;for(let t=i.pathless.length-1;t>=0;t--){let n=i.pathless[t];c.push({node:n,index:a,skipped:d,depth:e,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}}if(u)return u;if(r&&l){let n=l.index;for(let e=0;ee.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===j)>(e.node.kind===j)||t.node.kind===j==(e.node.kind===j)&&t.depth>e.depth)))}function q(e){return J(e.filter(e=>e!==void 0).join(`/`))}function J(e){return e.replace(/\/{2,}/g,`/`)}function Y(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function fe(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function pe(e){return fe(Y(e))}function X(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function me(e,t,n){return X(e,n)===X(t,n)}function he({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t.startsWith(`/`),o=!i&&t===`.`,s;if(r){s=i?t:o?e:e+`\0`+t;let n=r.get(s);if(n)return n}let c;if(o)c=e.split(`/`);else if(i)c=t.split(`/`);else{for(c=e.split(`/`);c.length>1&&a(c)===``;)c.pop();let n=t.split(`/`);for(let e=0,t=n.length;e1&&(a(c)===``?n===`never`&&c.pop():n===`always`&&c.push(``));let l=J(c.join(`/`))||`/`;return s&&r&&r.set(s,l),l}function ge(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function _e(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>ye(e,n)).join(`/`):ye(r,n):r}function ve({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s{if(!e.current||r.disabled||typeof IntersectionObserver!=`function`)return;let i=new IntersectionObserver(([e])=>{t(e)},n);return i.observe(e.current),()=>{i.disconnect()}},[t,n,r.disabled,e])}function Te(e){let t=Z.useRef(null);return Z.useImperativeHandle(e,()=>t.current,[]),t}var Ee=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),De=t(((e,t)=>{t.exports=Ee()})),Oe=De();function ke({children:e,fallback:t=null}){return Ae()?(0,Oe.jsx)(Z.Fragment,{children:e}):(0,Oe.jsx)(Z.Fragment,{children:t})}function Ae(){return Z.useSyncExternalStore(je,()=>!0,()=>!1)}function je(){return()=>{}}var Me=Z.createContext(null);function Ne(e){return Z.useContext(Me)}var Pe=t((e=>{var t=n();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=t.useState,o=t.useEffect,s=t.useLayoutEffect,c=t.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!i(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),Fe=t(((e,t)=>{t.exports=Pe()})),Ie=t((e=>{var t=n(),r=Fe();function i(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:i,o=r.useSyncExternalStore,s=t.useRef,c=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),Le=t(((e,t)=>{t.exports=Ie()}))();function Re(e,t){return e===t}function ze(e,t,n=Re){let r=(0,Z.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,Z.useCallback)(()=>e?.get(),[e]);return(0,Le.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var Be=e(i(),1);function Ve(e,t){let n=Ne(),r=Te(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:c,preload:l,preloadDelay:u,preloadIntentProximity:d,hashScrollIntoView:f,replace:p,startTransition:m,resetScroll:h,viewTransition:g,children:_,target:y,disabled:b,style:x,className:S,onClick:C,onBlur:w,onFocus:T,onMouseEnter:D,onMouseLeave:O,onTouchStart:k,ignoreBlocker:ee,params:te,search:ne,hash:re,state:A,mask:j,reloadDocument:ie,unsafeRelative:ae,from:oe,_fromLocation:M,...N}=e,P=Ae(),F=Z.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),I=ze(n.stores.location,e=>e,(e,t)=>e.href===t.href),L=Z.useMemo(()=>{let e={_fromLocation:I,...F};return n.buildLocation(e)},[n,I,F]),se=L.maskedLocation?L.maskedLocation.publicHref:L.publicHref,ce=L.maskedLocation?L.maskedLocation.external:L.external,R=Z.useMemo(()=>Je(se,ce,n.history,b),[b,ce,se,n.history]),z=Z.useMemo(()=>{if(R?.external)return E(R.href,n.protocolAllowlist)?void 0:R.href;if(!Ye(c)&&!(typeof c!=`string`||c.indexOf(`:`)===-1))try{return new URL(c),E(c,n.protocolAllowlist)?void 0:c}catch{}},[c,R,n.protocolAllowlist]),B=Z.useMemo(()=>{if(z)return!1;if(o?.exact){if(!me(I.pathname,L.pathname,n.basepath))return!1}else{let e=X(I.pathname,n.basepath),t=X(L.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!v(I.search,L.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:!o?.includeHash||P&&I.hash===L.hash},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,I,z,P,L.hash,L.pathname,L.search,n.basepath]),V=B?s(i,{})??Ue:He,H=B?He:s(a,{})??He,U=[S,V.className,H.className].filter(Boolean).join(` `),le=(x||V.style||H.style)&&{...x,...V.style,...H.style},[ue,W]=Z.useState(!1),de=Z.useRef(!1),G=e.reloadDocument||z?!1:l??n.options.defaultPreload,K=u??n.options.defaultPreloadDelay??0,q=Z.useCallback(()=>{n.preloadRoute({...F,_builtLocation:L}).catch(e=>{console.warn(e),console.warn(be)})},[n,F,L]);we(r,Z.useCallback(e=>{e?.isIntersecting&&q()},[q]),qe,{disabled:!!b||G!==`viewport`}),Z.useEffect(()=>{de.current||!b&&G===`render`&&(q(),de.current=!0)},[b,q,G]);let J=e=>{let t=e.currentTarget.getAttribute(`target`),r=y===void 0?t:y;if(!b&&!Ze(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,Be.flushSync)(()=>{W(!0)});let t=n.subscribe(`onResolved`,()=>{t(),W(!1)});n.navigate({...F,replace:p,resetScroll:h,hashScrollIntoView:f,startTransition:m,viewTransition:g,ignoreBlocker:ee})}};if(z)return{...N,ref:r,href:z,..._&&{children:_},...y&&{target:y},...b&&{disabled:b},...x&&{style:x},...S&&{className:S},...C&&{onClick:C},...w&&{onBlur:w},...T&&{onFocus:T},...D&&{onMouseEnter:D},...O&&{onMouseLeave:O},...k&&{onTouchStart:k}};let Y=e=>{if(b||G!==`intent`)return;if(!K){q();return}let t=e.currentTarget;if(Q.has(t))return;let n=setTimeout(()=>{Q.delete(t),q()},K);Q.set(t,n)},fe=e=>{b||G!==`intent`||q()},pe=e=>{if(b||!G||!K)return;let t=e.currentTarget,n=Q.get(t);n&&(clearTimeout(n),Q.delete(t))};return{...N,...V,...H,href:R?.href,ref:r,onClick:$([C,J]),onBlur:$([w,pe]),onFocus:$([T,Y]),onMouseEnter:$([D,Y]),onMouseLeave:$([O,pe]),onTouchStart:$([k,fe]),disabled:!!b,target:y,...le&&{style:le},...U&&{className:U},...b&&We,...B&&Ge,...P&&ue&&Ke}}var He={},Ue={className:`active`},We={role:`link`,"aria-disabled":!0},Ge={"data-status":`active`,"aria-current":`page`},Ke={"data-transitioning":`transitioning`},Q=new WeakMap,qe={rootMargin:`100px`},$=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function Je(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function Ye(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var Xe=Z.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=Ve(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return Z.createElement(`a`,t,o)}return Z.createElement(n,a,o)});function Ze(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}export{ee as A,f as B,L as C,T as D,re as E,u as F,i as H,E as I,b as L,te as M,k as N,ne as O,s as P,x as R,ce as S,A as T,p as V,Y as _,ke as a,se as b,xe as c,J as d,ge as f,pe as g,he as h,Me as i,v as j,y as k,Se as l,q as m,ze as n,Ae as o,ve as p,Ne as r,De as s,Xe as t,Ce as u,fe as v,B as w,R as x,U as y,a as z}; \ No newline at end of file diff --git a/.vercel/output/static/assets/login-C3NWOInE.js b/.vercel/output/static/assets/login-C3NWOInE.js deleted file mode 100644 index 7a93982..0000000 --- a/.vercel/output/static/assets/login-C3NWOInE.js +++ /dev/null @@ -1 +0,0 @@ -import{s as e,t}from"./link-DYUXAN0T.js";import{n}from"./index-DU4A6Ttf.js";import{r}from"./client-8boibB1R.js";import{n as i,r as a}from"./use-current-user-BkYwj4ZJ.js";var o=[{providerId:`grok-google`,idp:`google`,label:`Google`},{providerId:`grok-x`,idp:`twitter`,label:`X`}],s=e();function c(){let{user:e,isPending:c}=i();return!c&&e?(0,s.jsx)(n,{to:`/`}):(0,s.jsx)(`main`,{className:`grid min-h-dvh place-items-center bg-background px-6 text-foreground`,children:(0,s.jsxs)(`div`,{className:`w-full max-w-sm space-y-6`,children:[(0,s.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,s.jsx)(`div`,{className:`mx-auto flex size-12 items-center justify-center rounded-xl bg-foreground text-lg font-semibold text-background`,children:`W`}),(0,s.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Sign in to Workspace`}),(0,s.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Your pages save to the cloud database when you're signed in. Guests keep a local copy in this browser only.`})]}),(0,s.jsx)(`div`,{className:`space-y-2`,children:o.map(e=>(0,s.jsxs)(a,{type:`button`,variant:`outline`,className:`h-11 w-full justify-center`,onClick:()=>void r(e.providerId,{callbackURL:`/`}),children:[`Continue with `,e.label]},e.providerId))}),(0,s.jsx)(`p`,{className:`text-center text-sm text-muted-foreground`,children:(0,s.jsx)(t,{to:`/`,className:`underline-offset-4 hover:underline`,children:`Continue as guest`})})]})})}export{c as component}; \ No newline at end of file diff --git a/.vercel/output/static/assets/login-xkhUej_P.js b/.vercel/output/static/assets/login-xkhUej_P.js new file mode 100644 index 0000000..17c179c --- /dev/null +++ b/.vercel/output/static/assets/login-xkhUej_P.js @@ -0,0 +1 @@ +import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./react-BLJmJXjR.js";import{i as n,u as r}from"./utils-BTuSbA5p.js";import{c as i}from"./index-CXgd9jpl.js";import{r as a,t as o}from"./client-CwgDvMJw.js";import{i as s,r as c,t as l}from"./input-mze7gZ5r.js";var u=[{providerId:`grok-google`,idp:`google`,label:`Google`},{providerId:`grok-x`,idp:`twitter`,label:`X`}],d=e(t()),f=r();function p(){if(typeof window>`u`)return!1;let e=window.location.hostname;return e===`localhost`||e===`127.0.0.1`||e===`[::1]`}function m(){let{user:e,isPending:t}=c(),[r,m]=(0,d.useState)(``),[h,g]=(0,d.useState)(``),[_,v]=(0,d.useState)(``),[y,b]=(0,d.useState)(`signin`),[x,S]=(0,d.useState)(!1),[C,w]=(0,d.useState)(null),[T,E]=(0,d.useState)(!1);if((0,d.useEffect)(()=>E(p()),[]),!t&&e)return(0,f.jsx)(i,{to:`/`});async function D(e){e.preventDefault(),w(null),S(!0);try{if(y===`signup`){let{error:e}=await o.signUp.email({email:r.trim(),password:h,name:_.trim()||r.trim().split(`@`)[0]||`User`});if(e)throw Error(e.message??`Sign-up failed`)}else{let{error:e}=await o.signIn.email({email:r.trim(),password:h});if(e)throw Error(e.message??`Sign-in failed`)}window.location.href=`/`}catch(e){w(e instanceof Error?e.message:`Authentication failed`)}finally{S(!1)}}async function O(e){w(null),S(!0);try{await a(e,{callbackURL:`/`})}catch(e){let t=e instanceof Error?e.message:`Sign-in failed`;/invalid redirect/i.test(t)||T?w(`Google / X sign-in needs a public app URL registered with the Grok auth broker. On this machine use email & password, or open the app in a Grok live preview / deployed host.`):w(t),S(!1)}}return(0,f.jsx)(`main`,{className:`grid min-h-dvh place-items-center bg-background px-6 text-foreground`,children:(0,f.jsxs)(`div`,{className:`w-full max-w-sm space-y-6`,children:[(0,f.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,f.jsx)(`div`,{className:`mx-auto flex size-12 items-center justify-center rounded-xl bg-foreground text-lg font-semibold text-background`,children:`F`}),(0,f.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Sign in to ForgeNotes`}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Signed-in pages sync to the database. Guests keep a local copy only.`})]}),T&&(0,f.jsxs)(`p`,{className:`rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-left text-xs leading-relaxed text-amber-950 dark:text-amber-100`,children:[(0,f.jsx)(`strong`,{className:`font-medium`,children:`Desktop / local note:`}),` Continue with Google or X uses the shared Grok auth broker, which only accepts callbacks from`,` `,(0,f.jsx)(`code`,{className:`rounded bg-black/5 px-1 dark:bg-white/10`,children:`*.grok-sandbox.com`}),` `,`(or a deployed app with its own broker credentials). For this Tauri / localhost window, use `,(0,f.jsx)(`strong`,{children:`email & password`}),` below.`]}),(0,f.jsxs)(`div`,{className:`space-y-4`,children:[(0,f.jsxs)(`form`,{onSubmit:D,className:`space-y-3`,children:[y===`signup`&&(0,f.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,f.jsx)(`label`,{htmlFor:`name`,className:`text-xs font-medium text-muted-foreground`,children:`Name`}),(0,f.jsx)(l,{id:`name`,autoComplete:`name`,value:_,onChange:e=>v(e.target.value),placeholder:`Your name`,disabled:x})]}),(0,f.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,f.jsx)(`label`,{htmlFor:`email`,className:`text-xs font-medium text-muted-foreground`,children:`Email`}),(0,f.jsx)(l,{id:`email`,type:`email`,autoComplete:`email`,required:!0,value:r,onChange:e=>m(e.target.value),placeholder:`you@example.com`,disabled:x})]}),(0,f.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,f.jsx)(`label`,{htmlFor:`password`,className:`text-xs font-medium text-muted-foreground`,children:`Password`}),(0,f.jsx)(l,{id:`password`,type:`password`,autoComplete:y===`signup`?`new-password`:`current-password`,required:!0,minLength:8,value:h,onChange:e=>g(e.target.value),placeholder:`At least 8 characters`,disabled:x})]}),(0,f.jsx)(s,{type:`submit`,className:`h-11 w-full`,disabled:x,children:x?`Working…`:y===`signup`?`Create account`:`Sign in with email`}),(0,f.jsx)(`button`,{type:`button`,className:`w-full text-center text-xs text-muted-foreground underline-offset-4 hover:underline`,disabled:x,onClick:()=>{b(e=>e===`signin`?`signup`:`signin`),w(null)},children:y===`signup`?`Already have an account? Sign in`:`Need an account? Sign up`})]}),(0,f.jsxs)(`div`,{className:`relative py-1`,children:[(0,f.jsx)(`div`,{className:`absolute inset-0 flex items-center`,children:(0,f.jsx)(`span`,{className:`w-full border-t border-border`})}),(0,f.jsx)(`div`,{className:`relative flex justify-center text-xs uppercase`,children:(0,f.jsx)(`span`,{className:`bg-background px-2 text-muted-foreground`,children:`or`})})]}),(0,f.jsx)(`div`,{className:`space-y-2`,children:u.map(e=>(0,f.jsxs)(s,{type:`button`,variant:`outline`,className:`h-11 w-full justify-center`,disabled:x,onClick:()=>void O(e.providerId),children:[`Continue with `,e.label]},e.providerId))})]}),C&&(0,f.jsx)(`p`,{className:`rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive`,children:C}),(0,f.jsx)(`p`,{className:`text-center text-sm text-muted-foreground`,children:(0,f.jsx)(n,{to:`/`,className:`underline-offset-4 hover:underline`,children:`Continue as guest`})})]})})}export{m as component}; \ No newline at end of file diff --git a/.vercel/output/static/assets/mermaid-parser.core-AdnthA1k.js b/.vercel/output/static/assets/mermaid-parser.core-Z7xZAZRH.js similarity index 99% rename from .vercel/output/static/assets/mermaid-parser.core-AdnthA1k.js rename to .vercel/output/static/assets/mermaid-parser.core-Z7xZAZRH.js index c064934..77bf37d 100644 --- a/.vercel/output/static/assets/mermaid-parser.core-AdnthA1k.js +++ b/.vercel/output/static/assets/mermaid-parser.core-Z7xZAZRH.js @@ -1,4 +1,4 @@ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/info-DKCQHKI2-DIc7uC4I.js","assets/chunk-KEIR6QF5-Dj-OpFgW.js","assets/chunk-BIQX33UG-CuPbkyWp.js","assets/packet-7NZHBO7P-D2duWGIK.js","assets/chunk-EMLP6XTP-BoneA0Uo.js","assets/pie-RZYD4A2V-CynqTUkZ.js","assets/chunk-YOTPTUD7-CjHV8V6f.js","assets/treeView-QDETBFTQ-CygwzEgj.js","assets/chunk-CQNSW5MT-BbEh_krl.js","assets/architecture-TIHT7OUA-BWqzHezU.js","assets/chunk-MOZMSUNE-BgA8jCvb.js","assets/gitGraph-TEB2WS4Q-Do0SQOtM.js","assets/chunk-CYSBUYHQ-CbOq7Rc1.js","assets/eventmodeling-45OFAUF4-Dp0gpjhg.js","assets/chunk-5JV3BV7I-DKfYBAeY.js","assets/radar-I7S5WNFK-fIKE12aT.js","assets/chunk-QBLGF6JB-C9zGMqvP.js","assets/railroad-3IZDKUUU-Bgx8HJTj.js","assets/chunk-5TONJI2A-DOX2waSJ.js","assets/railroad-ebnf-EBAXGLYW-C74h3s_I.js","assets/chunk-U6XO7XAA-CR0BSRFR.js","assets/railroad-abnf-AHOZXSZD-Nh6k60mH.js","assets/chunk-5HE753X5-o8-OCfIL.js","assets/railroad-peg-LSFZ7HO6-0hT-lN-u.js","assets/chunk-JG7HCLWE-Dk4_aECj.js","assets/treemap-6X3UGDF4-BbCXbaXr.js","assets/chunk-R7FJI6CG-BpBhcF6R.js","assets/wardley-OPB4EBWU-BjXxCRf_.js","assets/chunk-5FCAYU7R-DNtJmW0j.js","assets/cynefin-VYW2F7L2-4m18BxUG.js","assets/chunk-OSBZ3O6U-CX9EQ5t2.js"])))=>i.map(i=>d[i]); -import{t as e}from"./index-DU4A6Ttf.js";import{x as t}from"./chunk-KEIR6QF5-Dj-OpFgW.js";import"./chunk-MOZMSUNE-BgA8jCvb.js";import"./chunk-OSBZ3O6U-CX9EQ5t2.js";import"./chunk-5JV3BV7I-DKfYBAeY.js";import"./chunk-CYSBUYHQ-CbOq7Rc1.js";import"./chunk-BIQX33UG-CuPbkyWp.js";import"./chunk-EMLP6XTP-BoneA0Uo.js";import"./chunk-YOTPTUD7-CjHV8V6f.js";import"./chunk-QBLGF6JB-C9zGMqvP.js";import"./chunk-5TONJI2A-DOX2waSJ.js";import"./chunk-5HE753X5-o8-OCfIL.js";import"./chunk-U6XO7XAA-CR0BSRFR.js";import"./chunk-JG7HCLWE-Dk4_aECj.js";import"./chunk-CQNSW5MT-BbEh_krl.js";import"./chunk-R7FJI6CG-BpBhcF6R.js";import"./chunk-5FCAYU7R-DNtJmW0j.js";var n={},r={info:t(async()=>{let{createInfoServices:t}=await e(async()=>{let{createInfoServices:e}=await import(`./info-DKCQHKI2-DIc7uC4I.js`);return{createInfoServices:e}},__vite__mapDeps([0,1,2]));n.info=t().Info.parser.LangiumParser},`info`),packet:t(async()=>{let{createPacketServices:t}=await e(async()=>{let{createPacketServices:e}=await import(`./packet-7NZHBO7P-D2duWGIK.js`);return{createPacketServices:e}},__vite__mapDeps([3,1,4]));n.packet=t().Packet.parser.LangiumParser},`packet`),pie:t(async()=>{let{createPieServices:t}=await e(async()=>{let{createPieServices:e}=await import(`./pie-RZYD4A2V-CynqTUkZ.js`);return{createPieServices:e}},__vite__mapDeps([5,1,6]));n.pie=t().Pie.parser.LangiumParser},`pie`),treeView:t(async()=>{let{createTreeViewServices:t}=await e(async()=>{let{createTreeViewServices:e}=await import(`./treeView-QDETBFTQ-CygwzEgj.js`);return{createTreeViewServices:e}},__vite__mapDeps([7,1,8]));n.treeView=t().TreeView.parser.LangiumParser},`treeView`),architecture:t(async()=>{let{createArchitectureServices:t}=await e(async()=>{let{createArchitectureServices:e}=await import(`./architecture-TIHT7OUA-BWqzHezU.js`);return{createArchitectureServices:e}},__vite__mapDeps([9,1,10]));n.architecture=t().Architecture.parser.LangiumParser},`architecture`),gitGraph:t(async()=>{let{createGitGraphServices:t}=await e(async()=>{let{createGitGraphServices:e}=await import(`./gitGraph-TEB2WS4Q-Do0SQOtM.js`);return{createGitGraphServices:e}},__vite__mapDeps([11,1,12]));n.gitGraph=t().GitGraph.parser.LangiumParser},`gitGraph`),eventmodeling:t(async()=>{let{createEventModelingServices:t}=await e(async()=>{let{createEventModelingServices:e}=await import(`./eventmodeling-45OFAUF4-Dp0gpjhg.js`);return{createEventModelingServices:e}},__vite__mapDeps([13,1,14]));n.eventmodeling=t().EventModel.parser.LangiumParser},`eventmodeling`),radar:t(async()=>{let{createRadarServices:t}=await e(async()=>{let{createRadarServices:e}=await import(`./radar-I7S5WNFK-fIKE12aT.js`);return{createRadarServices:e}},__vite__mapDeps([15,1,16]));n.radar=t().Radar.parser.LangiumParser},`radar`),railroad:t(async()=>{let{createRailroadServices:t}=await e(async()=>{let{createRailroadServices:e}=await import(`./railroad-3IZDKUUU-Bgx8HJTj.js`);return{createRailroadServices:e}},__vite__mapDeps([17,1,18]));n.railroad=t().Railroad.parser.LangiumParser},`railroad`),railroadEbnf:t(async()=>{let{createRailroadEbnfServices:t}=await e(async()=>{let{createRailroadEbnfServices:e}=await import(`./railroad-ebnf-EBAXGLYW-C74h3s_I.js`);return{createRailroadEbnfServices:e}},__vite__mapDeps([19,1,20]));n.railroadEbnf=t().RailroadEbnf.parser.LangiumParser},`railroadEbnf`),railroadAbnf:t(async()=>{let{createRailroadAbnfServices:t}=await e(async()=>{let{createRailroadAbnfServices:e}=await import(`./railroad-abnf-AHOZXSZD-Nh6k60mH.js`);return{createRailroadAbnfServices:e}},__vite__mapDeps([21,1,22]));n.railroadAbnf=t().RailroadAbnf.parser.LangiumParser},`railroadAbnf`),railroadPeg:t(async()=>{let{createRailroadPegServices:t}=await e(async()=>{let{createRailroadPegServices:e}=await import(`./railroad-peg-LSFZ7HO6-0hT-lN-u.js`);return{createRailroadPegServices:e}},__vite__mapDeps([23,1,24]));n.railroadPeg=t().RailroadPeg.parser.LangiumParser},`railroadPeg`),treemap:t(async()=>{let{createTreemapServices:t}=await e(async()=>{let{createTreemapServices:e}=await import(`./treemap-6X3UGDF4-BbCXbaXr.js`);return{createTreemapServices:e}},__vite__mapDeps([25,1,26]));n.treemap=t().Treemap.parser.LangiumParser},`treemap`),wardley:t(async()=>{let{createWardleyServices:t}=await e(async()=>{let{createWardleyServices:e}=await import(`./wardley-OPB4EBWU-BjXxCRf_.js`);return{createWardleyServices:e}},__vite__mapDeps([27,1,28]));n.wardley=t().Wardley.parser.LangiumParser},`wardley`),cynefin:t(async()=>{let{createCynefinServices:t}=await e(async()=>{let{createCynefinServices:e}=await import(`./cynefin-VYW2F7L2-4m18BxUG.js`);return{createCynefinServices:e}},__vite__mapDeps([29,1,30]));n.cynefin=t().Cynefin.parser.LangiumParser},`cynefin`)};async function i(e,t){let i=r[e];if(!i)throw Error(`Unknown diagram type: ${e}`);n[e]||await i();let o=n[e].parse(t);if(o.lexerErrors.length>0||o.parserErrors.length>0)throw new a(o);return o.value}t(i,`parse`);var a=class extends Error{constructor(e){let t=e.lexerErrors.map(e=>`Lexer error on line ${e.line!==void 0&&!isNaN(e.line)?e.line:`?`}, column ${e.column!==void 0&&!isNaN(e.column)?e.column:`?`}: ${e.message}`).join(` +import{t as e}from"./index-CXgd9jpl.js";import{x as t}from"./chunk-KEIR6QF5-Dj-OpFgW.js";import"./chunk-MOZMSUNE-BgA8jCvb.js";import"./chunk-OSBZ3O6U-CX9EQ5t2.js";import"./chunk-5JV3BV7I-DKfYBAeY.js";import"./chunk-CYSBUYHQ-CbOq7Rc1.js";import"./chunk-BIQX33UG-CuPbkyWp.js";import"./chunk-EMLP6XTP-BoneA0Uo.js";import"./chunk-YOTPTUD7-CjHV8V6f.js";import"./chunk-QBLGF6JB-C9zGMqvP.js";import"./chunk-5TONJI2A-DOX2waSJ.js";import"./chunk-5HE753X5-o8-OCfIL.js";import"./chunk-U6XO7XAA-CR0BSRFR.js";import"./chunk-JG7HCLWE-Dk4_aECj.js";import"./chunk-CQNSW5MT-BbEh_krl.js";import"./chunk-R7FJI6CG-BpBhcF6R.js";import"./chunk-5FCAYU7R-DNtJmW0j.js";var n={},r={info:t(async()=>{let{createInfoServices:t}=await e(async()=>{let{createInfoServices:e}=await import(`./info-DKCQHKI2-DIc7uC4I.js`);return{createInfoServices:e}},__vite__mapDeps([0,1,2]));n.info=t().Info.parser.LangiumParser},`info`),packet:t(async()=>{let{createPacketServices:t}=await e(async()=>{let{createPacketServices:e}=await import(`./packet-7NZHBO7P-D2duWGIK.js`);return{createPacketServices:e}},__vite__mapDeps([3,1,4]));n.packet=t().Packet.parser.LangiumParser},`packet`),pie:t(async()=>{let{createPieServices:t}=await e(async()=>{let{createPieServices:e}=await import(`./pie-RZYD4A2V-CynqTUkZ.js`);return{createPieServices:e}},__vite__mapDeps([5,1,6]));n.pie=t().Pie.parser.LangiumParser},`pie`),treeView:t(async()=>{let{createTreeViewServices:t}=await e(async()=>{let{createTreeViewServices:e}=await import(`./treeView-QDETBFTQ-CygwzEgj.js`);return{createTreeViewServices:e}},__vite__mapDeps([7,1,8]));n.treeView=t().TreeView.parser.LangiumParser},`treeView`),architecture:t(async()=>{let{createArchitectureServices:t}=await e(async()=>{let{createArchitectureServices:e}=await import(`./architecture-TIHT7OUA-BWqzHezU.js`);return{createArchitectureServices:e}},__vite__mapDeps([9,1,10]));n.architecture=t().Architecture.parser.LangiumParser},`architecture`),gitGraph:t(async()=>{let{createGitGraphServices:t}=await e(async()=>{let{createGitGraphServices:e}=await import(`./gitGraph-TEB2WS4Q-Do0SQOtM.js`);return{createGitGraphServices:e}},__vite__mapDeps([11,1,12]));n.gitGraph=t().GitGraph.parser.LangiumParser},`gitGraph`),eventmodeling:t(async()=>{let{createEventModelingServices:t}=await e(async()=>{let{createEventModelingServices:e}=await import(`./eventmodeling-45OFAUF4-Dp0gpjhg.js`);return{createEventModelingServices:e}},__vite__mapDeps([13,1,14]));n.eventmodeling=t().EventModel.parser.LangiumParser},`eventmodeling`),radar:t(async()=>{let{createRadarServices:t}=await e(async()=>{let{createRadarServices:e}=await import(`./radar-I7S5WNFK-fIKE12aT.js`);return{createRadarServices:e}},__vite__mapDeps([15,1,16]));n.radar=t().Radar.parser.LangiumParser},`radar`),railroad:t(async()=>{let{createRailroadServices:t}=await e(async()=>{let{createRailroadServices:e}=await import(`./railroad-3IZDKUUU-Bgx8HJTj.js`);return{createRailroadServices:e}},__vite__mapDeps([17,1,18]));n.railroad=t().Railroad.parser.LangiumParser},`railroad`),railroadEbnf:t(async()=>{let{createRailroadEbnfServices:t}=await e(async()=>{let{createRailroadEbnfServices:e}=await import(`./railroad-ebnf-EBAXGLYW-C74h3s_I.js`);return{createRailroadEbnfServices:e}},__vite__mapDeps([19,1,20]));n.railroadEbnf=t().RailroadEbnf.parser.LangiumParser},`railroadEbnf`),railroadAbnf:t(async()=>{let{createRailroadAbnfServices:t}=await e(async()=>{let{createRailroadAbnfServices:e}=await import(`./railroad-abnf-AHOZXSZD-Nh6k60mH.js`);return{createRailroadAbnfServices:e}},__vite__mapDeps([21,1,22]));n.railroadAbnf=t().RailroadAbnf.parser.LangiumParser},`railroadAbnf`),railroadPeg:t(async()=>{let{createRailroadPegServices:t}=await e(async()=>{let{createRailroadPegServices:e}=await import(`./railroad-peg-LSFZ7HO6-0hT-lN-u.js`);return{createRailroadPegServices:e}},__vite__mapDeps([23,1,24]));n.railroadPeg=t().RailroadPeg.parser.LangiumParser},`railroadPeg`),treemap:t(async()=>{let{createTreemapServices:t}=await e(async()=>{let{createTreemapServices:e}=await import(`./treemap-6X3UGDF4-BbCXbaXr.js`);return{createTreemapServices:e}},__vite__mapDeps([25,1,26]));n.treemap=t().Treemap.parser.LangiumParser},`treemap`),wardley:t(async()=>{let{createWardleyServices:t}=await e(async()=>{let{createWardleyServices:e}=await import(`./wardley-OPB4EBWU-BjXxCRf_.js`);return{createWardleyServices:e}},__vite__mapDeps([27,1,28]));n.wardley=t().Wardley.parser.LangiumParser},`wardley`),cynefin:t(async()=>{let{createCynefinServices:t}=await e(async()=>{let{createCynefinServices:e}=await import(`./cynefin-VYW2F7L2-4m18BxUG.js`);return{createCynefinServices:e}},__vite__mapDeps([29,1,30]));n.cynefin=t().Cynefin.parser.LangiumParser},`cynefin`)};async function i(e,t){let i=r[e];if(!i)throw Error(`Unknown diagram type: ${e}`);n[e]||await i();let o=n[e].parse(t);if(o.lexerErrors.length>0||o.parserErrors.length>0)throw new a(o);return o.value}t(i,`parse`);var a=class extends Error{constructor(e){let t=e.lexerErrors.map(e=>`Lexer error on line ${e.line!==void 0&&!isNaN(e.line)?e.line:`?`}, column ${e.column!==void 0&&!isNaN(e.column)?e.column:`?`}: ${e.message}`).join(` `),n=e.parserErrors.map(e=>`Parse error on line ${e.token.startLine!==void 0&&!isNaN(e.token.startLine)?e.token.startLine:`?`}, column ${e.token.startColumn!==void 0&&!isNaN(e.token.startColumn)?e.token.startColumn:`?`}: ${e.message}`).join(` `);super(`Parsing failed: ${t} ${n}`),this.result=e}static{t(this,`MermaidParseError`)}};export{i as n,a as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/mermaid.core-BrAYfHNA.js b/.vercel/output/static/assets/mermaid.core-lwoghoVk.js similarity index 81% rename from .vercel/output/static/assets/mermaid.core-BrAYfHNA.js rename to .vercel/output/static/assets/mermaid.core-lwoghoVk.js index 5f9c2b7..280727f 100644 --- a/.vercel/output/static/assets/mermaid.core-BrAYfHNA.js +++ b/.vercel/output/static/assets/mermaid.core-lwoghoVk.js @@ -1,6 +1,6 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/c4Diagram-LMCZKHZV-DwxrqiYd.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-_wZywoZs.js","assets/rolldown-runtime-QTnfLwEv.js","assets/chunk-WYO6CB5R-ajGU-pWR.js","assets/index-DU4A6Ttf.js","assets/react-Biaal4sZ.js","assets/link-DYUXAN0T.js","assets/dist-D9sYb5Oa.js","assets/chunk-ICXQ74PX-fa5hHXws.js","assets/chunk-32BRIVSS-BtH22FN8.js","assets/flowDiagram-23GEKE2U-t-mmaSW1.js","assets/chunk-HOUHSVGY-4s2dJLwR.js","assets/chunk-Q4XR5HBZ-5srkZ5CC.js","assets/chunk-7BUUIJ7U-Bb538aSH.js","assets/chunk-OGEWGWER-Dr-qyYzn.js","assets/chunk-XXDRQBXY-BuE3VzE_.js","assets/chunk-VR4S4FIN-BJzXasDJ.js","assets/chunk-C7G6YPKG-DJfjwbsZ.js","assets/chunk-ZGVPDNZ5-zo3h_nOA.js","assets/rough.esm-CSKSodPl.js","assets/chunk-52WLFC77-BBAyrLn9.js","assets/line-CDW8hdKE.js","assets/path-BWPyau1x.js","assets/array-BifhSqXX.js","assets/chunk-FWX5IMBZ-CiLc9_ts.js","assets/chunk-ZIRB5QZD-C6fEPe3t.js","assets/chunk-PUDLZKDR-C4aS5M-Y.js","assets/channel-DA-EZjf8.js","assets/chunk-5VM5RSS4-ZNzvKenW.js","assets/swimlanesDiagram-G3AALYLV-BaT0JTBD.js","assets/erDiagram-Q63AITRT-CAHSPkSj.js","assets/gitGraphDiagram-IHSO6WYX-B4amBdmg.js","assets/chunk-JWPE2WC7-DVXcaiue.js","assets/mermaid-parser.core-AdnthA1k.js","assets/chunk-KEIR6QF5-Dj-OpFgW.js","assets/chunk-MOZMSUNE-BgA8jCvb.js","assets/chunk-OSBZ3O6U-CX9EQ5t2.js","assets/chunk-5JV3BV7I-DKfYBAeY.js","assets/chunk-CYSBUYHQ-CbOq7Rc1.js","assets/chunk-BIQX33UG-CuPbkyWp.js","assets/chunk-EMLP6XTP-BoneA0Uo.js","assets/chunk-YOTPTUD7-CjHV8V6f.js","assets/chunk-QBLGF6JB-C9zGMqvP.js","assets/chunk-5TONJI2A-DOX2waSJ.js","assets/chunk-5HE753X5-o8-OCfIL.js","assets/chunk-U6XO7XAA-CR0BSRFR.js","assets/chunk-JG7HCLWE-Dk4_aECj.js","assets/chunk-CQNSW5MT-BbEh_krl.js","assets/chunk-R7FJI6CG-BpBhcF6R.js","assets/chunk-5FCAYU7R-DNtJmW0j.js","assets/chunk-2Q5K7J3B-C1jixKkw.js","assets/ganttDiagram-NO4QXBWP-Ca9aFZDA.js","assets/linear-B7l8qgEw.js","assets/defaultLocale-C8Fc0cco.js","assets/init-D6jRqBbL.js","assets/infoDiagram-FWYZ7A6U-M92teQJC.js","assets/chunk-VAUOI2AC-CLN1Ga8_.js","assets/pieDiagram-ENE6RG2P-z6Ips8-s.js","assets/ordinal-hYBb2elL.js","assets/arc-BjSQqbzd.js","assets/quadrantDiagram-ABIIQ3AL-BM3e0Rzq.js","assets/xychartDiagram-FW5EYKEG-CmsUFOjZ.js","assets/requirementDiagram-TGXJPOKE-2PeqVsa7.js","assets/sequenceDiagram-DBY2YBRQ-BEJBrPsj.js","assets/classDiagram-OUVF2IWQ-DgseLdj3.js","assets/chunk-V7JOEXUC-BrpprPvX.js","assets/classDiagram-v2-EOCWNBFH-DgseLdj3.js","assets/stateDiagram-2N3HPSRC-BX-IhzND.js","assets/graphlib-DS17s2tU.js","assets/dagre-dpRSp0QF.js","assets/map-BaFkSB1l.js","assets/chunk-EX3LRPZG-DRWNsKDf.js","assets/stateDiagram-v2-6OUMAXLB-Dko8ZR-a.js","assets/journeyDiagram-5HDEW3XC-DyhbVNP5.js","assets/timeline-definition-FHXFAJF6-B3seWFFu.js","assets/mindmap-definition-LN4V7U3C-BkmDR9lz.js","assets/kanban-definition-HUTT4EX6-CgzuYK19.js","assets/sankeyDiagram-HTMAVEWB-CyFfG4DT.js","assets/diagram-NH7WQ7WH-DwPDSx0m.js","assets/diagram-WEI45ONY-DZoJ0aZU.js","assets/blockDiagram-677ZJIJ3-DNbsA_px.js","assets/diagram-OA4YK3LP-DVPjeDc1.js","assets/architectureDiagram-ZJ3FMSHR-BvJsh0sh.js","assets/cytoscape.esm-CQFVGiJu.js","assets/diagram-FQU43EPY-Bu63ejtr.js","assets/ishikawaDiagram-FXEZZL3T-HpUKQ9Yc.js","assets/vennDiagram-L72KCM5P-BsI8bHzd.js","assets/diagram-G47NLZAW-By0HJNEW.js","assets/wardleyDiagram-EHGQE667-CrSiGNM9.js","assets/cynefinDiagram-TSTJHNR4-C8ZTFXQ0.js","assets/railroadDiagram-RFXS5EU6-CrinQzap.js","assets/chunk-MOJQB5TN-DR1aBwdH.js","assets/ebnfDiagram-CCIWWBDH-Df0TcF3M.js","assets/abnfDiagram-VRR7QNED-CXuHdQsQ.js","assets/pegDiagram-2B236MQR-CpskF6nO.js"])))=>i.map(i=>d[i]); -import{t as e}from"./index-DU4A6Ttf.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{h as n,m as r,p as i}from"./src-_wZywoZs.js";import{$ as a,C as o,E as s,I as c,L as l,N as u,P as d,Q as f,S as p,T as m,V as h,W as g,X as _,Z as v,_ as y,b,c as x,g as S,l as C,m as w,n as ee,p as T,q as te,r as ne,t as re,u as ie}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{S as ae,a as oe,f as E,g as D,h as se,i as ce,o as le,v as ue,x as de,y as fe}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as pe}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{r as me}from"./chunk-HOUHSVGY-4s2dJLwR.js";import{r as he}from"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import"./chunk-ZGVPDNZ5-zo3h_nOA.js";import"./chunk-52WLFC77-BBAyrLn9.js";import{n as ge}from"./chunk-FWX5IMBZ-CiLc9_ts.js";import{n as _e,t as ve}from"./chunk-ZIRB5QZD-C6fEPe3t.js";function ye(e){let t=e?.constructor;return e===(typeof t==`function`?t.prototype:Object.prototype)}function be(e){if(e==null)return!0;if(de(e))return typeof e.splice!=`function`&&typeof e!=`string`&&!ae(e)&&!ue(e)&&!fe(e)?!1:e.length===0;if(typeof e==`object`||typeof e==`function`){if(e instanceof Map||e instanceof Set)return e.size===0;let t=Object.keys(e);return ye(e)?t.filter(e=>e!==`constructor`).length===0:t.length===0}return!0}var O=`comm`,xe=`rule`,Se=`decl`,Ce=`@import`,we=`@namespace`,Te=`@keyframes`,Ee=`@layer`,De=Math.abs,k=String.fromCharCode;function Oe(e){return e.trim()}function A(e,t,n){return e.replace(t,n)}function j(e,t){return e.charCodeAt(t)|0}function M(e,t,n){return e.slice(t,n)}function N(e){return e.length}function ke(e){return e.length}function P(e,t){return t.push(e),e}var F=1,I=1,Ae=0,L=0,R=0,z=``;function B(e,t,n,r,i,a,o,s){return{value:e,root:t,parent:n,type:r,props:i,children:a,line:F,column:I,length:o,return:``,siblings:s}}function je(){return R}function Me(){return R=L>0?j(z,--L):0,I--,R===10&&(I=1,F--),R}function V(){return R=L2||G(R)>3?``:` `}function Ie(e,t){for(;--t&&V()&&!(R<48||R>102||R>57&&R<65||R>70&&R<97););return W(e,U()+(t<6&&H()==32&&V()==32))}function q(e){for(;V();)switch(R){case e:return L;case 34:case 39:e!==34&&e!==39&&q(R);break;case 40:e===41&&q(e);break;case 92:V();break}return L}function Le(e,t){for(;V()&&e+R!==57&&!(e+R===84&&H()===47););return`/*`+W(t,L-1)+`*`+k(e===47?e:V())}function Re(e){for(;!G(H());)V();return W(e,L)}function ze(e){return Pe(J(``,null,null,null,[``],e=Ne(e),0,[0],e))}function J(e,t,n,r,i,a,o,s,c){for(var l=0,u=0,d=o,f=0,p=0,m=0,h=1,g=1,_=1,v=0,y=0,b=``,x=i,S=a,C=r,w=b;g;)switch(m=y,y=V()){case 40:m!=108&&j(w,d-1)==58?(v++,w+=`(`):w+=K(y);break;case 41:v--,w+=`)`;break;case 34:case 39:case 91:w+=K(y);break;case 9:case 10:case 13:case 32:if(v>0){w+=k(y);break}w+=Fe(m);break;case 92:w+=Ie(U()-1,7);continue;case 47:switch(H()){case 42:case 47:P(Ve(Le(V(),U()),t,n,c),c),(G(m||1)==5||G(H()||1)==5)&&N(w)&&M(w,-1,void 0)!==` `&&(w+=` `);break;default:w+=`/`}break;case 123*h:s[l++]=N(w)*_;case 125*h:case 59:case 0:if(v>0&&y){w+=k(y);break}switch(y){case 0:case 125:g=0;case 59+u:_==-1&&(w=A(w,/\f/g,``)),p>0&&(N(w)-d||h===0)&&P(p>32?He(w+`;`,r,n,d-1,c):He(A(w,` `,``)+`;`,r,n,d-2,c),c);break;case 59:w+=`;`;default:if(P(C=Be(w,t,n,l,u,i,s,b,x=[],S=[],d,a),a),y===123)if(u===0)J(w,t,C,C,x,a,d,s,S);else{switch(f){case 99:if(j(w,3)===110)break;case 108:if(j(w,2)===97)break;default:u=0;case 100:case 109:case 115:}u?J(e,C,C,r&&P(Be(e,C,C,0,0,i,s,b,i,x=[],d,S),S),i,S,d,s,r?x:S):J(w,C,C,C,[``],S,0,s,S)}}l=u=p=0,h=_=1,b=w=``,d=o;break;case 58:d=1+N(w),p=m;default:if(h<1){if(y==123)--h;else if(y==125&&h++==0&&Me()==125)continue}switch(w+=k(y),y*h){case 38:_=u>0?1:(w+=`\f`,-1);break;case 44:if(v>0)break;s[l++]=(N(w)-1)*_,_=1;break;case 64:H()===45&&(w+=K(V())),f=H(),u=d=N(b=w+=Re(U())),y++;break;case 45:m===45&&N(w)==2&&(h=0)}}return a}function Be(e,t,n,r,i,a,o,s,c,l,u,d){for(var f=i-1,p=i===0?a:[``],m=ke(p),h=0,g=0,_=0;h0?p[v]+` `+y:A(y,/&\f/g,p[v])))&&(c[_++]=b);return B(e,t,n,i===0?xe:s,c,l,u,d)}function Ve(e,t,n,r){return B(e,t,n,O,k(je()),M(e,2,-2),0,r)}function He(e,t,n,r,i){return B(e,t,n,Se,M(e,0,r),M(e,r+1,-1),r,i)}function Ue(e,t){for(var n=``,r=0;r/^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./c4Diagram-LMCZKHZV-DwxrqiYd.js`);return{diagram:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));return{id:Ke,diagram:t}},`loader`)},Je=`flowchart`,Ye={id:Je,detector:t((e,t)=>t?.flowchart?.defaultRenderer===`dagre-wrapper`||t?.flowchart?.defaultRenderer===`elk`?!1:/^\s*graph/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./flowDiagram-23GEKE2U-t-mmaSW1.js`);return{diagram:e}},__vite__mapDeps([11,2,3,1,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:Je,diagram:t}},`loader`)},Xe=`flowchart-v2`,Ze={id:Xe,detector:t((e,t)=>t?.flowchart?.defaultRenderer===`dagre-d3`?!1:(t?.flowchart?.defaultRenderer===`elk`&&(t.layout=`elk`),/^\s*graph/.test(e)&&t?.flowchart?.defaultRenderer===`dagre-wrapper`?!0:/^\s*flowchart/.test(e)),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./flowDiagram-23GEKE2U-t-mmaSW1.js`);return{diagram:e}},__vite__mapDeps([11,2,3,1,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:Xe,diagram:t}},`loader`)},Qe=`swimlane`,$e={id:Qe,detector:t(e=>/^\s*swimlane-beta\b/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./swimlanesDiagram-G3AALYLV-BaT0JTBD.js`);return{diagram:e}},__vite__mapDeps([30,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:Qe,diagram:t}},`loader`)},et=`er`,tt={id:et,detector:t(e=>/^\s*erDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./erDiagram-Q63AITRT-CAHSPkSj.js`);return{diagram:e}},__vite__mapDeps([31,1,2,3,4,5,6,7,28,9,8,12,13,14,15,16,17,18,19,20,21,22,23,24,25]));return{id:et,diagram:t}},`loader`)},nt=`gitGraph`,rt={id:nt,detector:t(e=>/^\s*gitGraph/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./gitGraphDiagram-IHSO6WYX-B4amBdmg.js`);return{diagram:e}},__vite__mapDeps([32,1,2,3,4,5,6,7,9,8,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51]));return{id:nt,diagram:t}},`loader`)},it=`gantt`,at={id:it,detector:t(e=>/^\s*gantt/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./ganttDiagram-NO4QXBWP-Ca9aFZDA.js`);return{diagram:e}},__vite__mapDeps([52,3,1,2,4,5,6,7,53,54,55,8,9]));return{id:it,diagram:t}},`loader`)},ot=`info`,st={id:ot,detector:t(e=>/^\s*info/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./infoDiagram-FWYZ7A6U-M92teQJC.js`);return{diagram:e}},__vite__mapDeps([56,1,2,3,4,5,6,7,57,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:ot,diagram:t}},`loader`)},ct=`pie`,lt={id:ct,detector:t(e=>/^\s*pie/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./pieDiagram-ENE6RG2P-z6Ips8-s.js`);return{diagram:e}},__vite__mapDeps([58,1,2,3,4,5,6,7,59,55,23,8,60,24,9,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:ct,diagram:t}},`loader`)},ut=`quadrantChart`,dt={id:ut,detector:t(e=>/^\s*quadrantChart/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./quadrantDiagram-ABIIQ3AL-BM3e0Rzq.js`);return{diagram:e}},__vite__mapDeps([61,1,2,3,4,5,6,7,53,54,55]));return{id:ut,diagram:t}},`loader`)},ft=`xychart`,pt={id:ft,detector:t(e=>/^\s*xychart(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./xychartDiagram-FW5EYKEG-CmsUFOjZ.js`);return{diagram:e}},__vite__mapDeps([62,1,2,3,4,5,6,7,53,54,55,59,9,8,22,23,24,57,12,13]));return{id:ft,diagram:t}},`loader`)},mt=`requirement`,ht={id:mt,detector:t(e=>/^\s*requirement(Diagram)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./requirementDiagram-TGXJPOKE-2PeqVsa7.js`);return{diagram:e}},__vite__mapDeps([63,1,2,3,4,5,6,7,9,8,12,13,14,15,16,17,18,19,20,21,22,23,24,25]));return{id:mt,diagram:t}},`loader`)},gt=`sequence`,_t={id:gt,detector:t(e=>/^\s*sequenceDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./sequenceDiagram-DBY2YBRQ-BEJBrPsj.js`);return{diagram:e}},__vite__mapDeps([64,1,2,3,4,5,6,7,8,9,10,51,26]));return{id:gt,diagram:t}},`loader`)},vt=`class`,yt={id:vt,detector:t((e,t)=>t?.class?.defaultRenderer!==`dagre-wrapper`&&/^\s*classDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./classDiagram-OUVF2IWQ-DgseLdj3.js`);return{diagram:e}},__vite__mapDeps([65,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,66,29]));return{id:vt,diagram:t}},`loader`)},bt=`classDiagram`,xt={id:bt,detector:t((e,t)=>/^\s*classDiagram/.test(e)&&t?.class?.defaultRenderer===`dagre-wrapper`?!0:/^\s*classDiagram-v2/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./classDiagram-v2-EOCWNBFH-DgseLdj3.js`);return{diagram:e}},__vite__mapDeps([67,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,66,29]));return{id:bt,diagram:t}},`loader`)},St=`state`,Ct={id:St,detector:t((e,t)=>t?.state?.defaultRenderer!==`dagre-wrapper`&&/^\s*stateDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./stateDiagram-2N3HPSRC-BX-IhzND.js`);return{diagram:e}},__vite__mapDeps([68,1,2,3,4,5,6,7,9,8,22,23,24,12,13,14,15,69,70,71,10,16,17,18,19,20,21,25,72]));return{id:St,diagram:t}},`loader`)},wt=`stateDiagram`,Tt={id:wt,detector:t((e,t)=>!!(/^\s*stateDiagram-v2/.test(e)||/^\s*stateDiagram/.test(e)&&t?.state?.defaultRenderer===`dagre-wrapper`),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./stateDiagram-v2-6OUMAXLB-Dko8ZR-a.js`);return{diagram:e}},__vite__mapDeps([73,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,72]));return{id:wt,diagram:t}},`loader`)},Et=`journey`,Dt={id:Et,detector:t(e=>/^\s*journey/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./journeyDiagram-5HDEW3XC-DyhbVNP5.js`);return{diagram:e}},__vite__mapDeps([74,1,2,3,4,5,6,7,60,23,8,29,10]));return{id:Et,diagram:t}},`loader`)},Ot={draw:t((e,t,n)=>{r.debug(`rendering svg for syntax error -`);let i=pe(t),a=i.append(`g`);i.attr(`viewBox`,`0 0 2412 512`),x(i,100,512,!0),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z`),a.append(`text`).attr(`class`,`error-text`).attr(`x`,1440).attr(`y`,250).attr(`font-size`,`150px`).style(`text-anchor`,`middle`).text(`Syntax error in text`),a.append(`text`).attr(`class`,`error-text`).attr(`x`,1250).attr(`y`,400).attr(`font-size`,`100px`).style(`text-anchor`,`middle`).text(`mermaid version ${n}`)},`draw`)},kt=Ot,At={db:{},renderer:Ot,parser:{parse:t(()=>{},`parse`)}},jt=`flowchart-elk`,Mt={id:jt,detector:t((e,t={})=>/^\s*flowchart-elk/.test(e)||/^\s*(flowchart|graph)/.test(e)&&t?.flowchart?.defaultRenderer===`elk`?(t.layout=`elk`,!0):!1,`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./flowDiagram-23GEKE2U-t-mmaSW1.js`);return{diagram:e}},__vite__mapDeps([11,2,3,1,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:jt,diagram:t}},`loader`)},Nt=`timeline`,Pt={id:Nt,detector:t(e=>/^\s*timeline/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./timeline-definition-FHXFAJF6-B3seWFFu.js`);return{diagram:e}},__vite__mapDeps([75,1,2,3,4,5,6,7,60,23,8,9,57]));return{id:Nt,diagram:t}},`loader`)},Ft=`mindmap`,It={id:Ft,detector:t(e=>/^\s*mindmap/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./mindmap-definition-LN4V7U3C-BkmDR9lz.js`);return{diagram:e}},__vite__mapDeps([76,1,2,3,4,5,6,7,9,8,12,13,14,15,16,17,18,19,20,21,22,23,24,25]));return{id:Ft,diagram:t}},`loader`)},Lt=`kanban`,Rt={id:Lt,detector:t(e=>/^\s*kanban/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./kanban-definition-HUTT4EX6-CgzuYK19.js`);return{diagram:e}},__vite__mapDeps([77,1,2,3,4,5,6,7,9,8,57,12,13,29,15,18,19,20,26]));return{id:Lt,diagram:t}},`loader`)},zt=`sankey`,Bt={id:zt,detector:t(e=>/^\s*sankey(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./sankeyDiagram-HTMAVEWB-CyFfG4DT.js`);return{diagram:e}},__vite__mapDeps([78,1,2,3,4,5,6,7,59,55]));return{id:zt,diagram:t}},`loader`)},Vt=`packet`,Ht={id:Vt,detector:t(e=>/^\s*packet(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-NH7WQ7WH-DwPDSx0m.js`);return{diagram:e}},__vite__mapDeps([79,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:Vt,diagram:t}},`loader`)},Ut=`radar`,Wt={id:Ut,detector:t(e=>/^\s*radar-beta/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-WEI45ONY-DZoJ0aZU.js`);return{diagram:e}},__vite__mapDeps([80,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:Ut,diagram:t}},`loader`)},Gt=`block`,Kt={id:Gt,detector:t(e=>/^\s*block(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./blockDiagram-677ZJIJ3-DNbsA_px.js`);return{diagram:e}},__vite__mapDeps([81,1,2,3,4,5,6,7,28,9,8,22,23,24,12,13,29,14,15,69]));return{id:Gt,diagram:t}},`loader`)},qt=`treeView`,Jt={id:qt,detector:t(e=>/^\s*treeView-beta/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-OA4YK3LP-DVPjeDc1.js`);return{diagram:e}},__vite__mapDeps([82,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,12,51]));return{id:qt,diagram:t}},`loader`)},Yt=`architecture`,Xt={id:Yt,detector:t(e=>/^\s*architecture/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./architectureDiagram-ZJ3FMSHR-BvJsh0sh.js`);return{diagram:e}},__vite__mapDeps([83,3,1,2,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,12,13,84]));return{id:Yt,diagram:t}},`loader`)},Zt=`eventmodeling`,Qt={id:Zt,detector:t(e=>/^\s*eventmodeling/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-FQU43EPY-Bu63ejtr.js`);return{diagram:e}},__vite__mapDeps([85,35,1,2,3,4,5,6,7,9,8,33,34,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:Zt,diagram:t}},`loader`)},$t=`ishikawa`,en={id:$t,detector:t(e=>/^\s*ishikawa(-beta)?\b/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./ishikawaDiagram-FXEZZL3T-HpUKQ9Yc.js`);return{diagram:e}},__vite__mapDeps([86,1,2,3,4,5,6,7,9,8,57,20]));return{id:$t,diagram:t}},`loader`)},tn=`venn`,nn={id:tn,detector:t(e=>/^\s*venn-beta/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./vennDiagram-L72KCM5P-BsI8bHzd.js`);return{diagram:e}},__vite__mapDeps([87,1,2,3,4,5,6,7,9,8,57,20]));return{id:tn,diagram:t}},`loader`)},rn=`treemap`,an={id:rn,detector:t(e=>/^\s*treemap/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-G47NLZAW-By0HJNEW.js`);return{diagram:e}},__vite__mapDeps([88,1,2,3,4,5,6,7,59,55,54,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,17,18]));return{id:rn,diagram:t}},`loader`)},on=`wardley`,sn={id:on,detector:t(e=>/^\s*wardley-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./wardleyDiagram-EHGQE667-CrSiGNM9.js`);return{diagram:e}},__vite__mapDeps([89,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:on,diagram:t}},`loader`)},cn=`cynefin`,ln={id:cn,detector:t(e=>/^\s*cynefin-beta(?:[\s:]|$)/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./cynefinDiagram-TSTJHNR4-C8ZTFXQ0.js`);return{diagram:e}},__vite__mapDeps([90,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:cn,diagram:t}},`loader`)},un=`railroad`,dn={id:un,detector:t(e=>/^\s*railroad-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./railroadDiagram-RFXS5EU6-CrinQzap.js`);return{diagram:e}},__vite__mapDeps([91,44,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,45,46,47,48,49,50]));return{id:un,diagram:t}},`loader`)},fn=`railroadEbnf`,pn={id:fn,detector:t(e=>/^\s*railroad-ebnf-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./ebnfDiagram-CCIWWBDH-Df0TcF3M.js`);return{diagram:e}},__vite__mapDeps([93,46,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,44,45,47,48,49,50]));return{id:fn,diagram:t}},`loader`)},mn=`railroadAbnf`,hn={id:mn,detector:t(e=>/^\s*railroad-abnf-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./abnfDiagram-VRR7QNED-CXuHdQsQ.js`);return{diagram:e}},__vite__mapDeps([94,45,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,44,46,47,48,49,50]));return{id:mn,diagram:t}},`loader`)},gn=`railroadPeg`,_n={id:gn,detector:t(e=>/^\s*railroad-peg-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./pegDiagram-2B236MQR-CpskF6nO.js`);return{diagram:e}},__vite__mapDeps([95,47,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,44,45,46,48,49,50]));return{id:gn,diagram:t}},`loader`)},vn=!1,Y=t(()=>{vn||(vn=!0,u(`error`,At,e=>e.toLowerCase().trim()===`error`),u(`---`,{db:{clear:t(()=>{},`clear`)},styles:{},renderer:{draw:t(()=>{},`draw`)},parser:{parse:t(()=>{throw Error("Diagrams beginning with --- are not valid. If you were trying to use a YAML front-matter, please ensure that you've correctly opened and closed the YAML front-matter with un-indented `---` blocks")},`parse`)},init:t(()=>null,`init`)},e=>e.toLowerCase().trimStart().startsWith(`---`)),d(Mt,It,Xt),d(qe,Rt,xt,yt,tt,at,st,lt,ht,_t,$e,Ze,Ye,Pt,rt,Tt,Ct,Dt,dt,Bt,Ht,pt,Kt,Qt,Jt,Wt,en,an,dn,pn,hn,_n,nn,sn,ln))},`addDiagrams`),yn=t(async()=>{r.debug(`Loading registered diagrams`);let e=(await Promise.allSettled(Object.entries(w).map(async([e,{detector:t,loader:n}])=>{if(n)try{p(e)}catch{try{let{diagram:e,id:r}=await n();u(r,e,t)}catch(t){throw r.error(`Failed to load external diagram with key ${e}. Removing from detectors.`),delete w[e],t}}}))).filter(e=>e.status===`rejected`);if(e.length>0){r.error(`Failed to load ${e.length} external diagrams`);for(let t of e)r.error(t);throw Error(`Failed to load ${e.length} external diagrams`)}},`loadRegisteredDiagrams`),bn=`graphics-document document`;function xn(e,t){e.attr(`role`,bn),t!==``&&e.attr(`aria-roledescription`,t)}t(xn,`setA11yDiagramInfo`);function Sn(e,t,n,r){if(e.insert!==void 0){if(n){let t=`chart-desc-${r}`;e.attr(`aria-describedby`,t),e.insert(`desc`,`:first-child`).attr(`id`,t).text(n)}if(t){let n=`chart-title-${r}`;e.attr(`aria-labelledby`,n),e.insert(`title`,`:first-child`).attr(`id`,n).text(t)}}}t(Sn,`addSVGa11yTitleDescription`);var Cn=class e{constructor(e,t,n,r,i){this.type=e,this.text=t,this.db=n,this.parser=r,this.renderer=i}static{t(this,`Diagram`)}static async fromText(t,n={}){let r=b(),i=T(t,r);t=le(t)+` +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/c4Diagram-LMCZKHZV-B2PQ0JjZ.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-UMNXGZaF.js","assets/rolldown-runtime-aKtaBQYM.js","assets/chunk-WYO6CB5R-Dv5kDyQC.js","assets/index-CXgd9jpl.js","assets/react-BLJmJXjR.js","assets/utils-BTuSbA5p.js","assets/dist-qx0Iv9vM.js","assets/chunk-ICXQ74PX-Czpgj8Uw.js","assets/chunk-32BRIVSS-DWU3ezKg.js","assets/flowDiagram-23GEKE2U-mMOyit70.js","assets/chunk-HOUHSVGY-iJuv90UH.js","assets/chunk-Q4XR5HBZ-CQ8zkLYc.js","assets/chunk-7BUUIJ7U-Bb538aSH.js","assets/chunk-OGEWGWER-D-nWYRNR.js","assets/chunk-XXDRQBXY-Bq6zMMOx.js","assets/chunk-VR4S4FIN-BTo4eV3J.js","assets/chunk-C7G6YPKG-DW-1jWUA.js","assets/chunk-ZGVPDNZ5-DGInJAPD.js","assets/rough.esm-CSKSodPl.js","assets/chunk-52WLFC77-BOCvVCX1.js","assets/line-b9Ala942.js","assets/path-BWPyau1x.js","assets/array-BifhSqXX.js","assets/chunk-FWX5IMBZ-ComLEIwh.js","assets/chunk-ZIRB5QZD-C6fEPe3t.js","assets/chunk-PUDLZKDR-hlw4TonS.js","assets/channel-C4fgBBJ4.js","assets/chunk-5VM5RSS4-ZNzvKenW.js","assets/swimlanesDiagram-G3AALYLV-CGWZF_2o.js","assets/erDiagram-Q63AITRT-BwmdWLsf.js","assets/gitGraphDiagram-IHSO6WYX-CPtw8GFs.js","assets/chunk-JWPE2WC7-DVXcaiue.js","assets/mermaid-parser.core-Z7xZAZRH.js","assets/chunk-KEIR6QF5-Dj-OpFgW.js","assets/chunk-MOZMSUNE-BgA8jCvb.js","assets/chunk-OSBZ3O6U-CX9EQ5t2.js","assets/chunk-5JV3BV7I-DKfYBAeY.js","assets/chunk-CYSBUYHQ-CbOq7Rc1.js","assets/chunk-BIQX33UG-CuPbkyWp.js","assets/chunk-EMLP6XTP-BoneA0Uo.js","assets/chunk-YOTPTUD7-CjHV8V6f.js","assets/chunk-QBLGF6JB-C9zGMqvP.js","assets/chunk-5TONJI2A-DOX2waSJ.js","assets/chunk-5HE753X5-o8-OCfIL.js","assets/chunk-U6XO7XAA-CR0BSRFR.js","assets/chunk-JG7HCLWE-Dk4_aECj.js","assets/chunk-CQNSW5MT-BbEh_krl.js","assets/chunk-R7FJI6CG-BpBhcF6R.js","assets/chunk-5FCAYU7R-DNtJmW0j.js","assets/chunk-2Q5K7J3B-C1jixKkw.js","assets/ganttDiagram-NO4QXBWP-BFiNAWzu.js","assets/linear-DhAcoVP9.js","assets/defaultLocale-C8Fc0cco.js","assets/init-D6jRqBbL.js","assets/infoDiagram-FWYZ7A6U-BY1UX4W6.js","assets/chunk-VAUOI2AC-AC9pRUsa.js","assets/pieDiagram-ENE6RG2P-BBPaHS9V.js","assets/ordinal-hYBb2elL.js","assets/arc-DqK6O3qL.js","assets/quadrantDiagram-ABIIQ3AL-UafGc-sH.js","assets/xychartDiagram-FW5EYKEG-HaTasnSW.js","assets/requirementDiagram-TGXJPOKE-Bk3E4jWx.js","assets/sequenceDiagram-DBY2YBRQ-CUG55-r_.js","assets/classDiagram-OUVF2IWQ-D6qCu_tS.js","assets/chunk-V7JOEXUC-Drt5hFEy.js","assets/classDiagram-v2-EOCWNBFH-D6qCu_tS.js","assets/stateDiagram-2N3HPSRC-u60ROSPY.js","assets/graphlib-DS17s2tU.js","assets/dagre-dpRSp0QF.js","assets/map-BaFkSB1l.js","assets/chunk-EX3LRPZG-CzaF5a2T.js","assets/stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js","assets/journeyDiagram-5HDEW3XC-CCn-uNlj.js","assets/timeline-definition-FHXFAJF6-DFMIv6oI.js","assets/mindmap-definition-LN4V7U3C-Bib4remL.js","assets/kanban-definition-HUTT4EX6-CW9CwpnR.js","assets/sankeyDiagram-HTMAVEWB-oWnBtA7E.js","assets/diagram-NH7WQ7WH-Btsva5Mx.js","assets/diagram-WEI45ONY-DzxhBgyP.js","assets/blockDiagram-677ZJIJ3-Dn3HALPW.js","assets/diagram-OA4YK3LP-B1b6NwZz.js","assets/architectureDiagram-ZJ3FMSHR-DevFyLmc.js","assets/cytoscape.esm-CQFVGiJu.js","assets/diagram-FQU43EPY-C8Vn5v8I.js","assets/ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js","assets/vennDiagram-L72KCM5P-DkYnXwoc.js","assets/diagram-G47NLZAW-B5XCVQOu.js","assets/wardleyDiagram-EHGQE667-BewauNW1.js","assets/cynefinDiagram-TSTJHNR4-CAKFzgf0.js","assets/railroadDiagram-RFXS5EU6-D7w_TgGh.js","assets/chunk-MOJQB5TN-Bju_yCKi.js","assets/ebnfDiagram-CCIWWBDH-DiJBARG_.js","assets/abnfDiagram-VRR7QNED-DLdRCqX4.js","assets/pegDiagram-2B236MQR-CPt8QfP3.js"])))=>i.map(i=>d[i]); +import{t as e}from"./index-CXgd9jpl.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{h as n,m as r,p as i}from"./src-UMNXGZaF.js";import{$ as a,C as o,E as s,I as c,L as l,N as u,P as d,Q as f,S as p,T as m,V as h,W as g,X as _,Z as v,_ as y,b,c as x,g as S,l as C,m as w,n as ee,p as T,q as te,r as ne,t as re,u as ie}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{S as ae,a as oe,f as E,g as D,h as se,i as ce,o as le,v as ue,x as de,y as fe}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as pe}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{r as me}from"./chunk-HOUHSVGY-iJuv90UH.js";import{r as he}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import{n as ge}from"./chunk-FWX5IMBZ-ComLEIwh.js";import{n as _e,t as ve}from"./chunk-ZIRB5QZD-C6fEPe3t.js";function ye(e){let t=e?.constructor;return e===(typeof t==`function`?t.prototype:Object.prototype)}function be(e){if(e==null)return!0;if(de(e))return typeof e.splice!=`function`&&typeof e!=`string`&&!ae(e)&&!ue(e)&&!fe(e)?!1:e.length===0;if(typeof e==`object`||typeof e==`function`){if(e instanceof Map||e instanceof Set)return e.size===0;let t=Object.keys(e);return ye(e)?t.filter(e=>e!==`constructor`).length===0:t.length===0}return!0}var O=`comm`,xe=`rule`,Se=`decl`,Ce=`@import`,we=`@namespace`,Te=`@keyframes`,Ee=`@layer`,De=Math.abs,k=String.fromCharCode;function Oe(e){return e.trim()}function A(e,t,n){return e.replace(t,n)}function j(e,t){return e.charCodeAt(t)|0}function M(e,t,n){return e.slice(t,n)}function N(e){return e.length}function ke(e){return e.length}function P(e,t){return t.push(e),e}var F=1,I=1,Ae=0,L=0,R=0,z=``;function B(e,t,n,r,i,a,o,s){return{value:e,root:t,parent:n,type:r,props:i,children:a,line:F,column:I,length:o,return:``,siblings:s}}function je(){return R}function Me(){return R=L>0?j(z,--L):0,I--,R===10&&(I=1,F--),R}function V(){return R=L2||G(R)>3?``:` `}function Ie(e,t){for(;--t&&V()&&!(R<48||R>102||R>57&&R<65||R>70&&R<97););return W(e,U()+(t<6&&H()==32&&V()==32))}function q(e){for(;V();)switch(R){case e:return L;case 34:case 39:e!==34&&e!==39&&q(R);break;case 40:e===41&&q(e);break;case 92:V();break}return L}function Le(e,t){for(;V()&&e+R!==57&&!(e+R===84&&H()===47););return`/*`+W(t,L-1)+`*`+k(e===47?e:V())}function Re(e){for(;!G(H());)V();return W(e,L)}function ze(e){return Pe(J(``,null,null,null,[``],e=Ne(e),0,[0],e))}function J(e,t,n,r,i,a,o,s,c){for(var l=0,u=0,d=o,f=0,p=0,m=0,h=1,g=1,_=1,v=0,y=0,b=``,x=i,S=a,C=r,w=b;g;)switch(m=y,y=V()){case 40:m!=108&&j(w,d-1)==58?(v++,w+=`(`):w+=K(y);break;case 41:v--,w+=`)`;break;case 34:case 39:case 91:w+=K(y);break;case 9:case 10:case 13:case 32:if(v>0){w+=k(y);break}w+=Fe(m);break;case 92:w+=Ie(U()-1,7);continue;case 47:switch(H()){case 42:case 47:P(Ve(Le(V(),U()),t,n,c),c),(G(m||1)==5||G(H()||1)==5)&&N(w)&&M(w,-1,void 0)!==` `&&(w+=` `);break;default:w+=`/`}break;case 123*h:s[l++]=N(w)*_;case 125*h:case 59:case 0:if(v>0&&y){w+=k(y);break}switch(y){case 0:case 125:g=0;case 59+u:_==-1&&(w=A(w,/\f/g,``)),p>0&&(N(w)-d||h===0)&&P(p>32?He(w+`;`,r,n,d-1,c):He(A(w,` `,``)+`;`,r,n,d-2,c),c);break;case 59:w+=`;`;default:if(P(C=Be(w,t,n,l,u,i,s,b,x=[],S=[],d,a),a),y===123)if(u===0)J(w,t,C,C,x,a,d,s,S);else{switch(f){case 99:if(j(w,3)===110)break;case 108:if(j(w,2)===97)break;default:u=0;case 100:case 109:case 115:}u?J(e,C,C,r&&P(Be(e,C,C,0,0,i,s,b,i,x=[],d,S),S),i,S,d,s,r?x:S):J(w,C,C,C,[``],S,0,s,S)}}l=u=p=0,h=_=1,b=w=``,d=o;break;case 58:d=1+N(w),p=m;default:if(h<1){if(y==123)--h;else if(y==125&&h++==0&&Me()==125)continue}switch(w+=k(y),y*h){case 38:_=u>0?1:(w+=`\f`,-1);break;case 44:if(v>0)break;s[l++]=(N(w)-1)*_,_=1;break;case 64:H()===45&&(w+=K(V())),f=H(),u=d=N(b=w+=Re(U())),y++;break;case 45:m===45&&N(w)==2&&(h=0)}}return a}function Be(e,t,n,r,i,a,o,s,c,l,u,d){for(var f=i-1,p=i===0?a:[``],m=ke(p),h=0,g=0,_=0;h0?p[v]+` `+y:A(y,/&\f/g,p[v])))&&(c[_++]=b);return B(e,t,n,i===0?xe:s,c,l,u,d)}function Ve(e,t,n,r){return B(e,t,n,O,k(je()),M(e,2,-2),0,r)}function He(e,t,n,r,i){return B(e,t,n,Se,M(e,0,r),M(e,r+1,-1),r,i)}function Ue(e,t){for(var n=``,r=0;r/^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./c4Diagram-LMCZKHZV-B2PQ0JjZ.js`);return{diagram:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));return{id:Ke,diagram:t}},`loader`)},Je=`flowchart`,Ye={id:Je,detector:t((e,t)=>t?.flowchart?.defaultRenderer===`dagre-wrapper`||t?.flowchart?.defaultRenderer===`elk`?!1:/^\s*graph/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./flowDiagram-23GEKE2U-mMOyit70.js`);return{diagram:e}},__vite__mapDeps([11,2,3,1,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:Je,diagram:t}},`loader`)},Xe=`flowchart-v2`,Ze={id:Xe,detector:t((e,t)=>t?.flowchart?.defaultRenderer===`dagre-d3`?!1:(t?.flowchart?.defaultRenderer===`elk`&&(t.layout=`elk`),/^\s*graph/.test(e)&&t?.flowchart?.defaultRenderer===`dagre-wrapper`?!0:/^\s*flowchart/.test(e)),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./flowDiagram-23GEKE2U-mMOyit70.js`);return{diagram:e}},__vite__mapDeps([11,2,3,1,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:Xe,diagram:t}},`loader`)},Qe=`swimlane`,$e={id:Qe,detector:t(e=>/^\s*swimlane-beta\b/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./swimlanesDiagram-G3AALYLV-CGWZF_2o.js`);return{diagram:e}},__vite__mapDeps([30,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:Qe,diagram:t}},`loader`)},et=`er`,tt={id:et,detector:t(e=>/^\s*erDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./erDiagram-Q63AITRT-BwmdWLsf.js`);return{diagram:e}},__vite__mapDeps([31,1,2,3,4,5,6,7,28,9,8,12,13,14,15,16,17,18,19,20,21,22,23,24,25]));return{id:et,diagram:t}},`loader`)},nt=`gitGraph`,rt={id:nt,detector:t(e=>/^\s*gitGraph/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./gitGraphDiagram-IHSO6WYX-CPtw8GFs.js`);return{diagram:e}},__vite__mapDeps([32,1,2,3,4,5,6,7,9,8,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51]));return{id:nt,diagram:t}},`loader`)},it=`gantt`,at={id:it,detector:t(e=>/^\s*gantt/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./ganttDiagram-NO4QXBWP-BFiNAWzu.js`);return{diagram:e}},__vite__mapDeps([52,3,1,2,4,5,6,7,53,54,55,8,9]));return{id:it,diagram:t}},`loader`)},ot=`info`,st={id:ot,detector:t(e=>/^\s*info/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./infoDiagram-FWYZ7A6U-BY1UX4W6.js`);return{diagram:e}},__vite__mapDeps([56,1,2,3,4,5,6,7,57,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:ot,diagram:t}},`loader`)},ct=`pie`,lt={id:ct,detector:t(e=>/^\s*pie/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./pieDiagram-ENE6RG2P-BBPaHS9V.js`);return{diagram:e}},__vite__mapDeps([58,1,2,3,4,5,6,7,59,55,23,8,60,24,9,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:ct,diagram:t}},`loader`)},ut=`quadrantChart`,dt={id:ut,detector:t(e=>/^\s*quadrantChart/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./quadrantDiagram-ABIIQ3AL-UafGc-sH.js`);return{diagram:e}},__vite__mapDeps([61,1,2,3,4,5,6,7,53,54,55]));return{id:ut,diagram:t}},`loader`)},ft=`xychart`,pt={id:ft,detector:t(e=>/^\s*xychart(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./xychartDiagram-FW5EYKEG-HaTasnSW.js`);return{diagram:e}},__vite__mapDeps([62,1,2,3,4,5,6,7,53,54,55,59,9,8,22,23,24,57,12,13]));return{id:ft,diagram:t}},`loader`)},mt=`requirement`,ht={id:mt,detector:t(e=>/^\s*requirement(Diagram)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./requirementDiagram-TGXJPOKE-Bk3E4jWx.js`);return{diagram:e}},__vite__mapDeps([63,1,2,3,4,5,6,7,9,8,12,13,14,15,16,17,18,19,20,21,22,23,24,25]));return{id:mt,diagram:t}},`loader`)},gt=`sequence`,_t={id:gt,detector:t(e=>/^\s*sequenceDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./sequenceDiagram-DBY2YBRQ-CUG55-r_.js`);return{diagram:e}},__vite__mapDeps([64,1,2,3,4,5,6,7,8,9,10,51,26]));return{id:gt,diagram:t}},`loader`)},vt=`class`,yt={id:vt,detector:t((e,t)=>t?.class?.defaultRenderer!==`dagre-wrapper`&&/^\s*classDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./classDiagram-OUVF2IWQ-D6qCu_tS.js`);return{diagram:e}},__vite__mapDeps([65,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,66,29]));return{id:vt,diagram:t}},`loader`)},bt=`classDiagram`,xt={id:bt,detector:t((e,t)=>/^\s*classDiagram/.test(e)&&t?.class?.defaultRenderer===`dagre-wrapper`?!0:/^\s*classDiagram-v2/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./classDiagram-v2-EOCWNBFH-D6qCu_tS.js`);return{diagram:e}},__vite__mapDeps([67,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,66,29]));return{id:bt,diagram:t}},`loader`)},St=`state`,Ct={id:St,detector:t((e,t)=>t?.state?.defaultRenderer!==`dagre-wrapper`&&/^\s*stateDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./stateDiagram-2N3HPSRC-u60ROSPY.js`);return{diagram:e}},__vite__mapDeps([68,1,2,3,4,5,6,7,9,8,22,23,24,12,13,14,15,69,70,71,10,16,17,18,19,20,21,25,72]));return{id:St,diagram:t}},`loader`)},wt=`stateDiagram`,Tt={id:wt,detector:t((e,t)=>!!(/^\s*stateDiagram-v2/.test(e)||/^\s*stateDiagram/.test(e)&&t?.state?.defaultRenderer===`dagre-wrapper`),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js`);return{diagram:e}},__vite__mapDeps([73,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,72]));return{id:wt,diagram:t}},`loader`)},Et=`journey`,Dt={id:Et,detector:t(e=>/^\s*journey/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./journeyDiagram-5HDEW3XC-CCn-uNlj.js`);return{diagram:e}},__vite__mapDeps([74,1,2,3,4,5,6,7,60,23,8,29,10]));return{id:Et,diagram:t}},`loader`)},Ot={draw:t((e,t,n)=>{r.debug(`rendering svg for syntax error +`);let i=pe(t),a=i.append(`g`);i.attr(`viewBox`,`0 0 2412 512`),x(i,100,512,!0),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z`),a.append(`text`).attr(`class`,`error-text`).attr(`x`,1440).attr(`y`,250).attr(`font-size`,`150px`).style(`text-anchor`,`middle`).text(`Syntax error in text`),a.append(`text`).attr(`class`,`error-text`).attr(`x`,1250).attr(`y`,400).attr(`font-size`,`100px`).style(`text-anchor`,`middle`).text(`mermaid version ${n}`)},`draw`)},kt=Ot,At={db:{},renderer:Ot,parser:{parse:t(()=>{},`parse`)}},jt=`flowchart-elk`,Mt={id:jt,detector:t((e,t={})=>/^\s*flowchart-elk/.test(e)||/^\s*(flowchart|graph)/.test(e)&&t?.flowchart?.defaultRenderer===`elk`?(t.layout=`elk`,!0):!1,`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./flowDiagram-23GEKE2U-mMOyit70.js`);return{diagram:e}},__vite__mapDeps([11,2,3,1,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:jt,diagram:t}},`loader`)},Nt=`timeline`,Pt={id:Nt,detector:t(e=>/^\s*timeline/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./timeline-definition-FHXFAJF6-DFMIv6oI.js`);return{diagram:e}},__vite__mapDeps([75,1,2,3,4,5,6,7,60,23,8,9,57]));return{id:Nt,diagram:t}},`loader`)},Ft=`mindmap`,It={id:Ft,detector:t(e=>/^\s*mindmap/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./mindmap-definition-LN4V7U3C-Bib4remL.js`);return{diagram:e}},__vite__mapDeps([76,1,2,3,4,5,6,7,9,8,12,13,14,15,16,17,18,19,20,21,22,23,24,25]));return{id:Ft,diagram:t}},`loader`)},Lt=`kanban`,Rt={id:Lt,detector:t(e=>/^\s*kanban/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./kanban-definition-HUTT4EX6-CW9CwpnR.js`);return{diagram:e}},__vite__mapDeps([77,1,2,3,4,5,6,7,9,8,57,12,13,29,15,18,19,20,26]));return{id:Lt,diagram:t}},`loader`)},zt=`sankey`,Bt={id:zt,detector:t(e=>/^\s*sankey(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./sankeyDiagram-HTMAVEWB-oWnBtA7E.js`);return{diagram:e}},__vite__mapDeps([78,1,2,3,4,5,6,7,59,55]));return{id:zt,diagram:t}},`loader`)},Vt=`packet`,Ht={id:Vt,detector:t(e=>/^\s*packet(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-NH7WQ7WH-Btsva5Mx.js`);return{diagram:e}},__vite__mapDeps([79,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:Vt,diagram:t}},`loader`)},Ut=`radar`,Wt={id:Ut,detector:t(e=>/^\s*radar-beta/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-WEI45ONY-DzxhBgyP.js`);return{diagram:e}},__vite__mapDeps([80,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:Ut,diagram:t}},`loader`)},Gt=`block`,Kt={id:Gt,detector:t(e=>/^\s*block(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./blockDiagram-677ZJIJ3-Dn3HALPW.js`);return{diagram:e}},__vite__mapDeps([81,1,2,3,4,5,6,7,28,9,8,22,23,24,12,13,29,14,15,69]));return{id:Gt,diagram:t}},`loader`)},qt=`treeView`,Jt={id:qt,detector:t(e=>/^\s*treeView-beta/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-OA4YK3LP-B1b6NwZz.js`);return{diagram:e}},__vite__mapDeps([82,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,12,51]));return{id:qt,diagram:t}},`loader`)},Yt=`architecture`,Xt={id:Yt,detector:t(e=>/^\s*architecture/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./architectureDiagram-ZJ3FMSHR-DevFyLmc.js`);return{diagram:e}},__vite__mapDeps([83,3,1,2,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,12,13,84]));return{id:Yt,diagram:t}},`loader`)},Zt=`eventmodeling`,Qt={id:Zt,detector:t(e=>/^\s*eventmodeling/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-FQU43EPY-C8Vn5v8I.js`);return{diagram:e}},__vite__mapDeps([85,35,1,2,3,4,5,6,7,9,8,33,34,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:Zt,diagram:t}},`loader`)},$t=`ishikawa`,en={id:$t,detector:t(e=>/^\s*ishikawa(-beta)?\b/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js`);return{diagram:e}},__vite__mapDeps([86,1,2,3,4,5,6,7,9,8,57,20]));return{id:$t,diagram:t}},`loader`)},tn=`venn`,nn={id:tn,detector:t(e=>/^\s*venn-beta/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./vennDiagram-L72KCM5P-DkYnXwoc.js`);return{diagram:e}},__vite__mapDeps([87,1,2,3,4,5,6,7,9,8,57,20]));return{id:tn,diagram:t}},`loader`)},rn=`treemap`,an={id:rn,detector:t(e=>/^\s*treemap/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-G47NLZAW-B5XCVQOu.js`);return{diagram:e}},__vite__mapDeps([88,1,2,3,4,5,6,7,59,55,54,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,17,18]));return{id:rn,diagram:t}},`loader`)},on=`wardley`,sn={id:on,detector:t(e=>/^\s*wardley-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./wardleyDiagram-EHGQE667-BewauNW1.js`);return{diagram:e}},__vite__mapDeps([89,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:on,diagram:t}},`loader`)},cn=`cynefin`,ln={id:cn,detector:t(e=>/^\s*cynefin-beta(?:[\s:]|$)/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./cynefinDiagram-TSTJHNR4-CAKFzgf0.js`);return{diagram:e}},__vite__mapDeps([90,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:cn,diagram:t}},`loader`)},un=`railroad`,dn={id:un,detector:t(e=>/^\s*railroad-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./railroadDiagram-RFXS5EU6-D7w_TgGh.js`);return{diagram:e}},__vite__mapDeps([91,44,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,45,46,47,48,49,50]));return{id:un,diagram:t}},`loader`)},fn=`railroadEbnf`,pn={id:fn,detector:t(e=>/^\s*railroad-ebnf-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./ebnfDiagram-CCIWWBDH-DiJBARG_.js`);return{diagram:e}},__vite__mapDeps([93,46,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,44,45,47,48,49,50]));return{id:fn,diagram:t}},`loader`)},mn=`railroadAbnf`,hn={id:mn,detector:t(e=>/^\s*railroad-abnf-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./abnfDiagram-VRR7QNED-DLdRCqX4.js`);return{diagram:e}},__vite__mapDeps([94,45,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,44,46,47,48,49,50]));return{id:mn,diagram:t}},`loader`)},gn=`railroadPeg`,_n={id:gn,detector:t(e=>/^\s*railroad-peg-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./pegDiagram-2B236MQR-CPt8QfP3.js`);return{diagram:e}},__vite__mapDeps([95,47,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,44,45,46,48,49,50]));return{id:gn,diagram:t}},`loader`)},vn=!1,Y=t(()=>{vn||(vn=!0,u(`error`,At,e=>e.toLowerCase().trim()===`error`),u(`---`,{db:{clear:t(()=>{},`clear`)},styles:{},renderer:{draw:t(()=>{},`draw`)},parser:{parse:t(()=>{throw Error("Diagrams beginning with --- are not valid. If you were trying to use a YAML front-matter, please ensure that you've correctly opened and closed the YAML front-matter with un-indented `---` blocks")},`parse`)},init:t(()=>null,`init`)},e=>e.toLowerCase().trimStart().startsWith(`---`)),d(Mt,It,Xt),d(qe,Rt,xt,yt,tt,at,st,lt,ht,_t,$e,Ze,Ye,Pt,rt,Tt,Ct,Dt,dt,Bt,Ht,pt,Kt,Qt,Jt,Wt,en,an,dn,pn,hn,_n,nn,sn,ln))},`addDiagrams`),yn=t(async()=>{r.debug(`Loading registered diagrams`);let e=(await Promise.allSettled(Object.entries(w).map(async([e,{detector:t,loader:n}])=>{if(n)try{p(e)}catch{try{let{diagram:e,id:r}=await n();u(r,e,t)}catch(t){throw r.error(`Failed to load external diagram with key ${e}. Removing from detectors.`),delete w[e],t}}}))).filter(e=>e.status===`rejected`);if(e.length>0){r.error(`Failed to load ${e.length} external diagrams`);for(let t of e)r.error(t);throw Error(`Failed to load ${e.length} external diagrams`)}},`loadRegisteredDiagrams`),bn=`graphics-document document`;function xn(e,t){e.attr(`role`,bn),t!==``&&e.attr(`aria-roledescription`,t)}t(xn,`setA11yDiagramInfo`);function Sn(e,t,n,r){if(e.insert!==void 0){if(n){let t=`chart-desc-${r}`;e.attr(`aria-describedby`,t),e.insert(`desc`,`:first-child`).attr(`id`,t).text(n)}if(t){let n=`chart-title-${r}`;e.attr(`aria-labelledby`,n),e.insert(`title`,`:first-child`).attr(`id`,n).text(t)}}}t(Sn,`addSVGa11yTitleDescription`);var Cn=class e{constructor(e,t,n,r,i){this.type=e,this.text=t,this.db=n,this.parser=r,this.renderer=i}static{t(this,`Diagram`)}static async fromText(t,n={}){let r=b(),i=T(t,r);t=le(t)+` `;try{p(i)}catch{let e=o(i);if(!e)throw new re(`Diagram ${i} not found.`);let{id:t,diagram:n}=await e();u(t,n)}let{db:a,parser:s,renderer:c,init:l}=p(i);return s.parser&&(s.parser.yy=a),a.clear?.(),l?.(r),n.title&&a.setDiagramTitle?.(n.title),await s.parse(t),new e(i,t,a,s,c)}async render(e,t){await this.renderer.draw(this.text,e,t,this)}getParser(){return this.parser}getType(){return this.type}},wn=[],Tn=t(()=>{wn.forEach(e=>{e()}),wn=[]},`attachFunctions`),En=t(e=>e.replace(/^\s*%%(?!{)[^\n]+\n?/gm,``).trimStart(),`cleanupComments`);function Dn(e){let t=e.match(y);if(!t)return{text:e,metadata:{}};let n=t[1],r=_e(n?t[2].split(` `).map(e=>e.startsWith(n)?e.slice(n.length):e).join(` `):t[2],{schema:ve})??{};r=typeof r==`object`&&!Array.isArray(r)?r:{};let i={};return r.displayMode&&(i.displayMode=r.displayMode.toString()),r.title&&(i.title=r.title.toString()),r.config&&(i.config=r.config),{text:e.slice(t[0].length),metadata:i}}t(Dn,`extractFrontMatter`);var On=t(e=>e.replace(/\r\n?/g,` diff --git a/.vercel/output/static/assets/mindmap-definition-LN4V7U3C-BkmDR9lz.js b/.vercel/output/static/assets/mindmap-definition-LN4V7U3C-Bib4remL.js similarity index 97% rename from .vercel/output/static/assets/mindmap-definition-LN4V7U3C-BkmDR9lz.js rename to .vercel/output/static/assets/mindmap-definition-LN4V7U3C-Bib4remL.js index 5974962..c25c0b2 100644 --- a/.vercel/output/static/assets/mindmap-definition-LN4V7U3C-BkmDR9lz.js +++ b/.vercel/output/static/assets/mindmap-definition-LN4V7U3C-Bib4remL.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{b as n,et as r,f as i,k as a,rt as o,tt as s,x as c,z as l}from"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import{t as u}from"./chunk-XXDRQBXY-BuE3VzE_.js";import{t as d}from"./chunk-VR4S4FIN-BJzXasDJ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import"./chunk-ZGVPDNZ5-zo3h_nOA.js";import"./chunk-52WLFC77-BBAyrLn9.js";import{r as f,t as p}from"./chunk-FWX5IMBZ-CiLc9_ts.js";var m=[];for(let e=0;e<256;++e)m.push((e+256).toString(16).slice(1));function h(e,t=0){return(m[e[t+0]]+m[e[t+1]]+m[e[t+2]]+m[e[t+3]]+`-`+m[e[t+4]]+m[e[t+5]]+`-`+m[e[t+6]]+m[e[t+7]]+`-`+m[e[t+8]]+m[e[t+9]]+`-`+m[e[t+10]]+m[e[t+11]]+m[e[t+12]]+m[e[t+13]]+m[e[t+14]]+m[e[t+15]]).toLowerCase()}var g=new Uint8Array(16);function _(){return crypto.getRandomValues(g)}function v(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():y(e,t,n)}function y(e,t,n){e||={};let r=e.random??e.rng?.()??_();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return h(r)}var b=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,13],i=[1,12],a=[1,15],o=[1,16],s=[1,20],c=[1,19],l=[6,7,8],u=[1,26],d=[1,24],f=[1,25],p=[6,7,11],m=[1,6,13,15,16,19,22],h=[1,33],g=[1,34],_=[1,6,7,11,13,15,16,19,22],v={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mindMap:4,spaceLines:5,SPACELINE:6,NL:7,MINDMAP:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,node:14,ICON:15,CLASS:16,nodeWithId:17,nodeWithoutId:18,NODE_DSTART:19,NODE_DESCR:20,NODE_DEND:21,NODE_ID:22,$accept:0,$end:1},terminals_:{2:`error`,6:`SPACELINE`,7:`NL`,8:`MINDMAP`,11:`EOF`,13:`SPACELIST`,15:`ICON`,16:`CLASS`,19:`NODE_DSTART`,20:`NODE_DESCR`,21:`NODE_DEND`,22:`NODE_ID`},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,2],[12,2],[12,2],[12,1],[12,1],[12,1],[12,1],[12,1],[14,1],[14,1],[18,3],[17,1],[17,4]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 6:case 7:return r;case 8:r.getLogger().trace(`Stop NL `);break;case 9:r.getLogger().trace(`Stop EOF `);break;case 11:r.getLogger().trace(`Stop NL2 `);break;case 12:r.getLogger().trace(`Stop EOF2 `);break;case 15:r.getLogger().info(`Node: `,a[s].id),r.addNode(a[s-1].length,a[s].id,a[s].descr,a[s].type);break;case 16:r.getLogger().trace(`Icon: `,a[s]),r.decorateNode({icon:a[s]});break;case 17:case 21:r.decorateNode({class:a[s]});break;case 18:r.getLogger().trace(`SPACELIST`);break;case 19:r.getLogger().trace(`Node: `,a[s].id),r.addNode(0,a[s].id,a[s].descr,a[s].type);break;case 20:r.decorateNode({icon:a[s]});break;case 25:r.getLogger().trace(`node found ..`,a[s-2]),this.$={id:a[s-1],descr:a[s-1],type:r.getType(a[s-2],a[s])};break;case 26:this.$={id:a[s],descr:a[s],type:r.nodeType.DEFAULT};break;case 27:r.getLogger().trace(`node found ..`,a[s-3]),this.$={id:a[s-3],descr:a[s-1],type:r.getType(a[s-2],a[s])};break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],8:n},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:n},{6:r,7:[1,10],9:9,12:11,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},t(l,[2,3]),{1:[2,2]},t(l,[2,4]),t(l,[2,5]),{1:[2,6],6:r,12:21,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},{6:r,9:22,12:11,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},{6:u,7:d,10:23,11:f},t(p,[2,22],{17:17,18:18,14:27,15:[1,28],16:[1,29],19:s,22:c}),t(p,[2,18]),t(p,[2,19]),t(p,[2,20]),t(p,[2,21]),t(p,[2,23]),t(p,[2,24]),t(p,[2,26],{19:[1,30]}),{20:[1,31]},{6:u,7:d,10:32,11:f},{1:[2,7],6:r,12:21,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},t(m,[2,14],{7:h,11:g}),t(_,[2,8]),t(_,[2,9]),t(_,[2,10]),t(p,[2,15]),t(p,[2,16]),t(p,[2,17]),{20:[1,35]},{21:[1,36]},t(m,[2,13],{7:h,11:g}),t(_,[2,11]),t(_,[2,12]),{21:[1,37]},t(p,[2,25]),t(p,[2,27])],defaultActions:{2:[2,1],6:[2,2]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{b as n,et as r,f as i,k as a,rt as o,tt as s,x as c,z as l}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import{t as u}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as d}from"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import{r as f,t as p}from"./chunk-FWX5IMBZ-ComLEIwh.js";var m=[];for(let e=0;e<256;++e)m.push((e+256).toString(16).slice(1));function h(e,t=0){return(m[e[t+0]]+m[e[t+1]]+m[e[t+2]]+m[e[t+3]]+`-`+m[e[t+4]]+m[e[t+5]]+`-`+m[e[t+6]]+m[e[t+7]]+`-`+m[e[t+8]]+m[e[t+9]]+`-`+m[e[t+10]]+m[e[t+11]]+m[e[t+12]]+m[e[t+13]]+m[e[t+14]]+m[e[t+15]]).toLowerCase()}var g=new Uint8Array(16);function _(){return crypto.getRandomValues(g)}function v(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():y(e,t,n)}function y(e,t,n){e||={};let r=e.random??e.rng?.()??_();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return h(r)}var b=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,13],i=[1,12],a=[1,15],o=[1,16],s=[1,20],c=[1,19],l=[6,7,8],u=[1,26],d=[1,24],f=[1,25],p=[6,7,11],m=[1,6,13,15,16,19,22],h=[1,33],g=[1,34],_=[1,6,7,11,13,15,16,19,22],v={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mindMap:4,spaceLines:5,SPACELINE:6,NL:7,MINDMAP:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,node:14,ICON:15,CLASS:16,nodeWithId:17,nodeWithoutId:18,NODE_DSTART:19,NODE_DESCR:20,NODE_DEND:21,NODE_ID:22,$accept:0,$end:1},terminals_:{2:`error`,6:`SPACELINE`,7:`NL`,8:`MINDMAP`,11:`EOF`,13:`SPACELIST`,15:`ICON`,16:`CLASS`,19:`NODE_DSTART`,20:`NODE_DESCR`,21:`NODE_DEND`,22:`NODE_ID`},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,2],[12,2],[12,2],[12,1],[12,1],[12,1],[12,1],[12,1],[14,1],[14,1],[18,3],[17,1],[17,4]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 6:case 7:return r;case 8:r.getLogger().trace(`Stop NL `);break;case 9:r.getLogger().trace(`Stop EOF `);break;case 11:r.getLogger().trace(`Stop NL2 `);break;case 12:r.getLogger().trace(`Stop EOF2 `);break;case 15:r.getLogger().info(`Node: `,a[s].id),r.addNode(a[s-1].length,a[s].id,a[s].descr,a[s].type);break;case 16:r.getLogger().trace(`Icon: `,a[s]),r.decorateNode({icon:a[s]});break;case 17:case 21:r.decorateNode({class:a[s]});break;case 18:r.getLogger().trace(`SPACELIST`);break;case 19:r.getLogger().trace(`Node: `,a[s].id),r.addNode(0,a[s].id,a[s].descr,a[s].type);break;case 20:r.decorateNode({icon:a[s]});break;case 25:r.getLogger().trace(`node found ..`,a[s-2]),this.$={id:a[s-1],descr:a[s-1],type:r.getType(a[s-2],a[s])};break;case 26:this.$={id:a[s],descr:a[s],type:r.nodeType.DEFAULT};break;case 27:r.getLogger().trace(`node found ..`,a[s-3]),this.$={id:a[s-3],descr:a[s-1],type:r.getType(a[s-2],a[s])};break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],8:n},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:n},{6:r,7:[1,10],9:9,12:11,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},t(l,[2,3]),{1:[2,2]},t(l,[2,4]),t(l,[2,5]),{1:[2,6],6:r,12:21,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},{6:r,9:22,12:11,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},{6:u,7:d,10:23,11:f},t(p,[2,22],{17:17,18:18,14:27,15:[1,28],16:[1,29],19:s,22:c}),t(p,[2,18]),t(p,[2,19]),t(p,[2,20]),t(p,[2,21]),t(p,[2,23]),t(p,[2,24]),t(p,[2,26],{19:[1,30]}),{20:[1,31]},{6:u,7:d,10:32,11:f},{1:[2,7],6:r,12:21,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},t(m,[2,14],{7:h,11:g}),t(_,[2,8]),t(_,[2,9]),t(_,[2,10]),t(p,[2,15]),t(p,[2,16]),t(p,[2,17]),{20:[1,35]},{21:[1,36]},t(m,[2,13],{7:h,11:g}),t(_,[2,11]),t(_,[2,12]),{21:[1,37]},t(p,[2,25]),t(p,[2,27])],defaultActions:{2:[2,1],6:[2,2]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};v.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/pegDiagram-2B236MQR-CpskF6nO.js b/.vercel/output/static/assets/pegDiagram-2B236MQR-CPt8QfP3.js similarity index 84% rename from .vercel/output/static/assets/pegDiagram-2B236MQR-CpskF6nO.js rename to .vercel/output/static/assets/pegDiagram-2B236MQR-CPt8QfP3.js index 993a697..1516455 100644 --- a/.vercel/output/static/assets/pegDiagram-2B236MQR-CpskF6nO.js +++ b/.vercel/output/static/assets/pegDiagram-2B236MQR-CPt8QfP3.js @@ -1 +1 @@ -import{n as e}from"./chunk-JG7HCLWE-Dk4_aECj.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-_wZywoZs.js";import"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-VAUOI2AC-CLN1Ga8_.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-DR1aBwdH.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-AdnthA1k.js";var c=e().RailroadPeg.parser.LangiumParser,l=t(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformOrderedChoice`),u=t(e=>{let t=e.elements.map(d);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformSequence`),d=t(e=>{let t=p(e.suffix);return e.operator?{type:`special`,text:e.operator===`&`?`&${f(t)}`:`!${f(t)}`}:t},`transformPrefix`),f=t(e=>{switch(e.type){case`terminal`:return`"${e.value}"`;case`nonterminal`:return e.name;case`special`:return e.text;default:return`(...)`}},`nodeToLabel`),p=t(e=>{let t=m(e.primary);if(!e.operator)return t;switch(e.operator){case`?`:return{type:`optional`,element:t};case`*`:return{type:`repetition`,element:t,min:0,max:1/0};case`+`:return{type:`repetition`,element:t,min:1,max:1/0};default:throw Error(`Unsupported PEG suffix operator: ${e.operator}`)}},`transformSuffix`),m=t(e=>{switch(e.$type){case`PegLiteral`:return{type:`terminal`,value:e.value};case`PegIdentifier`:return{type:`nonterminal`,name:e.name};case`PegGroup`:return l(e.element);case`PegAny`:return{type:`special`,text:e.dot};default:throw Error(`Unsupported PEG primary node: ${e.$type}`)}},`transformPrimary`),h=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),g=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(h(e)))},`populateDb`),_={parser:{parse:t(e=>{a.clear(),n.debug(`[PEG Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[PEG Parser] Parsed rules:`,r.rules.length),g(r),n.debug(`[PEG Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{_ as diagram}; \ No newline at end of file +import{n as e}from"./chunk-JG7HCLWE-Dk4_aECj.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-Bju_yCKi.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-Z7xZAZRH.js";var c=e().RailroadPeg.parser.LangiumParser,l=t(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformOrderedChoice`),u=t(e=>{let t=e.elements.map(d);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformSequence`),d=t(e=>{let t=p(e.suffix);return e.operator?{type:`special`,text:e.operator===`&`?`&${f(t)}`:`!${f(t)}`}:t},`transformPrefix`),f=t(e=>{switch(e.type){case`terminal`:return`"${e.value}"`;case`nonterminal`:return e.name;case`special`:return e.text;default:return`(...)`}},`nodeToLabel`),p=t(e=>{let t=m(e.primary);if(!e.operator)return t;switch(e.operator){case`?`:return{type:`optional`,element:t};case`*`:return{type:`repetition`,element:t,min:0,max:1/0};case`+`:return{type:`repetition`,element:t,min:1,max:1/0};default:throw Error(`Unsupported PEG suffix operator: ${e.operator}`)}},`transformSuffix`),m=t(e=>{switch(e.$type){case`PegLiteral`:return{type:`terminal`,value:e.value};case`PegIdentifier`:return{type:`nonterminal`,name:e.name};case`PegGroup`:return l(e.element);case`PegAny`:return{type:`special`,text:e.dot};default:throw Error(`Unsupported PEG primary node: ${e.$type}`)}},`transformPrimary`),h=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),g=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(h(e)))},`populateDb`),_={parser:{parse:t(e=>{a.clear(),n.debug(`[PEG Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[PEG Parser] Parsed rules:`,r.rules.length),g(r),n.debug(`[PEG Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{_ as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/pieDiagram-ENE6RG2P-z6Ips8-s.js b/.vercel/output/static/assets/pieDiagram-ENE6RG2P-BBPaHS9V.js similarity index 92% rename from .vercel/output/static/assets/pieDiagram-ENE6RG2P-z6Ips8-s.js rename to .vercel/output/static/assets/pieDiagram-ENE6RG2P-BBPaHS9V.js index 23d709e..26f2daf 100644 --- a/.vercel/output/static/assets/pieDiagram-ENE6RG2P-z6Ips8-s.js +++ b/.vercel/output/static/assets/pieDiagram-ENE6RG2P-BBPaHS9V.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{H as n,K as r,U as i,a,c as o,f as s,v as c,w as l,x as u,y as d}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as f}from"./ordinal-hYBb2elL.js";import{n as p}from"./path-BWPyau1x.js";import{m}from"./dist-D9sYb5Oa.js";import{t as h}from"./arc-BjSQqbzd.js";import{t as g}from"./array-BifhSqXX.js";import{i as _,p as v}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as y}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{t as b}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as x}from"./mermaid-parser.core-AdnthA1k.js";function S(e,t){return te?1:t>=e?0:NaN}function C(e){return e}function w(){var e=C,t=S,n=null,r=p(0),i=p(m),a=p(0);function o(o){var s,c=(o=g(o)).length,l,u,d=0,f=Array(c),p=Array(c),h=+r.apply(this,arguments),_=Math.min(m,Math.max(-m,i.apply(this,arguments)-h)),v,y=Math.min(Math.abs(_)/c,a.apply(this,arguments)),b=y*(_<0?-1:1),x;for(s=0;s0&&(d+=x);for(t==null?n!=null&&f.sort(function(e,t){return n(o[e],o[t])}):f.sort(function(e,n){return t(p[e],p[n])}),s=0,u=d?(_-c*b)/d:0;s0?x*u:0)+b,p[l]={data:o[l],index:s,value:x,startAngle:h,endAngle:v,padAngle:y};return p}return o.value=function(t){return arguments.length?(e=typeof t==`function`?t:p(+t),o):e},o.sortValues=function(e){return arguments.length?(t=e,n=null,o):t},o.sort=function(e){return arguments.length?(n=e,t=null,o):n},o.startAngle=function(e){return arguments.length?(r=typeof e==`function`?e:p(+e),o):r},o.endAngle=function(e){return arguments.length?(i=typeof e==`function`?e:p(+e),o):i},o.padAngle=function(e){return arguments.length?(a=typeof e==`function`?e:p(+e),o):a},o}var T=s.pie,E={sections:new Map,showData:!1,config:T},D=E.sections,O=E.showData,k=structuredClone(T),A={getConfig:e(()=>structuredClone(k),`getConfig`),clear:e(()=>{D=new Map,O=E.showData,a()},`clear`),setDiagramTitle:r,getDiagramTitle:l,setAccTitle:i,getAccTitle:d,setAccDescription:n,getAccDescription:c,addSection:e(({label:e,value:n})=>{if(n<0)throw Error(`"${e}" has invalid value: ${n}. Negative values are not allowed in pie charts. All slice values must be >= 0.`);D.has(e)||(D.set(e,n),t.debug(`added new section: ${e}, with value: ${n}`))},`addSection`),getSections:e(()=>D,`getSections`),setShowData:e(e=>{O=e},`setShowData`),getShowData:e(()=>O,`getShowData`)},j=e((e,t)=>{b(e,t),t.setShowData(e.showData),e.sections.map(t.addSection)},`populateDb`),M={parse:e(async e=>{let n=await x(`pie`,e);t.debug(n),j(n,A)},`parse`)},N=e(e=>` +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,c as o,f as s,v as c,w as l,x as u,y as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as f}from"./ordinal-hYBb2elL.js";import{n as p}from"./path-BWPyau1x.js";import{m}from"./dist-qx0Iv9vM.js";import{t as h}from"./arc-DqK6O3qL.js";import{t as g}from"./array-BifhSqXX.js";import{i as _,p as v}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as y}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as b}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as x}from"./mermaid-parser.core-Z7xZAZRH.js";function S(e,t){return te?1:t>=e?0:NaN}function C(e){return e}function w(){var e=C,t=S,n=null,r=p(0),i=p(m),a=p(0);function o(o){var s,c=(o=g(o)).length,l,u,d=0,f=Array(c),p=Array(c),h=+r.apply(this,arguments),_=Math.min(m,Math.max(-m,i.apply(this,arguments)-h)),v,y=Math.min(Math.abs(_)/c,a.apply(this,arguments)),b=y*(_<0?-1:1),x;for(s=0;s0&&(d+=x);for(t==null?n!=null&&f.sort(function(e,t){return n(o[e],o[t])}):f.sort(function(e,n){return t(p[e],p[n])}),s=0,u=d?(_-c*b)/d:0;s0?x*u:0)+b,p[l]={data:o[l],index:s,value:x,startAngle:h,endAngle:v,padAngle:y};return p}return o.value=function(t){return arguments.length?(e=typeof t==`function`?t:p(+t),o):e},o.sortValues=function(e){return arguments.length?(t=e,n=null,o):t},o.sort=function(e){return arguments.length?(n=e,t=null,o):n},o.startAngle=function(e){return arguments.length?(r=typeof e==`function`?e:p(+e),o):r},o.endAngle=function(e){return arguments.length?(i=typeof e==`function`?e:p(+e),o):i},o.padAngle=function(e){return arguments.length?(a=typeof e==`function`?e:p(+e),o):a},o}var T=s.pie,E={sections:new Map,showData:!1,config:T},D=E.sections,O=E.showData,k=structuredClone(T),A={getConfig:e(()=>structuredClone(k),`getConfig`),clear:e(()=>{D=new Map,O=E.showData,a()},`clear`),setDiagramTitle:r,getDiagramTitle:l,setAccTitle:i,getAccTitle:d,setAccDescription:n,getAccDescription:c,addSection:e(({label:e,value:n})=>{if(n<0)throw Error(`"${e}" has invalid value: ${n}. Negative values are not allowed in pie charts. All slice values must be >= 0.`);D.has(e)||(D.set(e,n),t.debug(`added new section: ${e}, with value: ${n}`))},`addSection`),getSections:e(()=>D,`getSections`),setShowData:e(e=>{O=e},`setShowData`),getShowData:e(()=>O,`getShowData`)},j=e((e,t)=>{b(e,t),t.setShowData(e.showData),e.sections.map(t.addSection)},`populateDb`),M={parse:e(async e=>{let n=await x(`pie`,e);t.debug(n),j(n,A)},`parse`)},N=e(e=>` .pieCircle{ stroke: ${e.pieStrokeColor}; stroke-width : ${e.pieStrokeWidth}; diff --git a/.vercel/output/static/assets/quadrantDiagram-ABIIQ3AL-BM3e0Rzq.js b/.vercel/output/static/assets/quadrantDiagram-ABIIQ3AL-UafGc-sH.js similarity index 99% rename from .vercel/output/static/assets/quadrantDiagram-ABIIQ3AL-BM3e0Rzq.js rename to .vercel/output/static/assets/quadrantDiagram-ABIIQ3AL-UafGc-sH.js index 6f1f30b..a1aa0dd 100644 --- a/.vercel/output/static/assets/quadrantDiagram-ABIIQ3AL-BM3e0Rzq.js +++ b/.vercel/output/static/assets/quadrantDiagram-ABIIQ3AL-UafGc-sH.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{D as r,H as i,K as a,U as o,a as s,c,f as l,v as u,w as d,x as f,y as p,z as m}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as h}from"./linear-B7l8qgEw.js";var g=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,3],r=[1,4],i=[1,5],a=[1,6],o=[1,7],s=[1,4,5,10,12,13,14,15,18,25,35,37,39,41,42,48,50,51,52,53,54,55,56,57,60,61,63,64,65,66,67],c=[1,4,5,10,12,13,14,15,18,25,28,35,37,39,41,42,48,50,51,52,53,54,55,56,57,60,61,63,64,65,66,67],l=[55,56,57],u=[2,36],d=[1,37],f=[1,36],p=[1,38],m=[1,35],h=[1,43],g=[1,41],_=[1,45],v=[1,14],y=[1,23],b=[1,18],x=[1,19],S=[1,20],C=[1,21],w=[1,22],T=[1,24],E=[1,25],D=[1,26],O=[1,27],k=[1,28],A=[1,29],j=[1,32],M=[1,33],N=[1,34],P=[1,39],F=[1,40],I=[1,42],L=[1,44],R=[1,63],z=[1,62],B=[4,5,8,10,12,13,14,15,18,44,47,49,55,56,57,63,64,65,66,67],ee=[1,66],te=[1,67],ne=[1,68],re=[1,69],ie=[1,70],ae=[1,71],oe=[1,72],se=[1,73],ce=[1,74],le=[1,75],ue=[1,76],de=[1,77],V=[4,5,6,7,8,9,10,11,12,13,14,15,18],H=[1,91],U=[1,92],W=[1,93],G=[1,100],K=[1,94],q=[1,97],J=[1,95],Y=[1,96],X=[1,98],Z=[1,99],fe=[1,103],pe=[10,55,56,57],Q=[4,5,6,8,10,11,13,17,18,19,20,55,56,57],me={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,idStringToken:3,ALPHA:4,NUM:5,NODE_STRING:6,DOWN:7,MINUS:8,DEFAULT:9,COMMA:10,COLON:11,AMP:12,BRKT:13,MULT:14,UNICODE_TEXT:15,styleComponent:16,UNIT:17,SPACE:18,STYLE:19,PCT:20,idString:21,style:22,stylesOpt:23,classDefStatement:24,CLASSDEF:25,start:26,eol:27,QUADRANT:28,document:29,line:30,statement:31,axisDetails:32,quadrantDetails:33,points:34,title:35,title_value:36,acc_title:37,acc_title_value:38,acc_descr:39,acc_descr_value:40,acc_descr_multiline_value:41,section:42,text:43,point_start:44,point_x:45,point_y:46,class_name:47,"X-AXIS":48,"AXIS-TEXT-DELIMITER":49,"Y-AXIS":50,QUADRANT_1:51,QUADRANT_2:52,QUADRANT_3:53,QUADRANT_4:54,NEWLINE:55,SEMI:56,EOF:57,alphaNumToken:58,textNoTagsToken:59,STR:60,MD_STR:61,alphaNum:62,PUNCTUATION:63,PLUS:64,EQUALS:65,DOT:66,UNDERSCORE:67,$accept:0,$end:1},terminals_:{2:`error`,4:`ALPHA`,5:`NUM`,6:`NODE_STRING`,7:`DOWN`,8:`MINUS`,9:`DEFAULT`,10:`COMMA`,11:`COLON`,12:`AMP`,13:`BRKT`,14:`MULT`,15:`UNICODE_TEXT`,17:`UNIT`,18:`SPACE`,19:`STYLE`,20:`PCT`,25:`CLASSDEF`,28:`QUADRANT`,35:`title`,36:`title_value`,37:`acc_title`,38:`acc_title_value`,39:`acc_descr`,40:`acc_descr_value`,41:`acc_descr_multiline_value`,42:`section`,44:`point_start`,45:`point_x`,46:`point_y`,47:`class_name`,48:`X-AXIS`,49:`AXIS-TEXT-DELIMITER`,50:`Y-AXIS`,51:`QUADRANT_1`,52:`QUADRANT_2`,53:`QUADRANT_3`,54:`QUADRANT_4`,55:`NEWLINE`,56:`SEMI`,57:`EOF`,60:`STR`,61:`MD_STR`,63:`PUNCTUATION`,64:`PLUS`,65:`EQUALS`,66:`DOT`,67:`UNDERSCORE`},productions_:[0,[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[21,1],[21,2],[22,1],[22,2],[23,1],[23,3],[24,5],[26,2],[26,2],[26,2],[29,0],[29,2],[30,2],[31,0],[31,1],[31,2],[31,1],[31,1],[31,1],[31,2],[31,2],[31,2],[31,1],[31,1],[34,4],[34,5],[34,5],[34,6],[32,4],[32,3],[32,2],[32,4],[32,3],[32,2],[33,2],[33,2],[33,2],[33,2],[27,1],[27,1],[27,1],[43,1],[43,2],[43,1],[43,1],[62,1],[62,2],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[59,1],[59,1],[59,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 23:this.$=a[s];break;case 24:this.$=a[s-1]+``+a[s];break;case 26:this.$=a[s-1]+a[s];break;case 27:this.$=[a[s].trim()];break;case 28:a[s-2].push(a[s].trim()),this.$=a[s-2];break;case 29:this.$=a[s-4],r.addClass(a[s-2],a[s]);break;case 37:this.$=[];break;case 42:this.$=a[s].trim(),r.setDiagramTitle(this.$);break;case 43:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 44:case 45:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 46:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 47:r.addPoint(a[s-3],``,a[s-1],a[s],[]);break;case 48:r.addPoint(a[s-4],a[s-3],a[s-1],a[s],[]);break;case 49:r.addPoint(a[s-4],``,a[s-2],a[s-1],a[s]);break;case 50:r.addPoint(a[s-5],a[s-4],a[s-2],a[s-1],a[s]);break;case 51:r.setXAxisLeftText(a[s-2]),r.setXAxisRightText(a[s]);break;case 52:a[s-1].text+=` ⟶ `,r.setXAxisLeftText(a[s-1]);break;case 53:r.setXAxisLeftText(a[s]);break;case 54:r.setYAxisBottomText(a[s-2]),r.setYAxisTopText(a[s]);break;case 55:a[s-1].text+=` ⟶ `,r.setYAxisBottomText(a[s-1]);break;case 56:r.setYAxisBottomText(a[s]);break;case 57:r.setQuadrant1Text(a[s]);break;case 58:r.setQuadrant2Text(a[s]);break;case 59:r.setQuadrant3Text(a[s]);break;case 60:r.setQuadrant4Text(a[s]);break;case 64:this.$={text:a[s],type:`text`};break;case 65:this.$={text:a[s-1].text+``+a[s],type:a[s-1].type};break;case 66:this.$={text:a[s],type:`text`};break;case 67:this.$={text:a[s],type:`markdown`};break;case 68:this.$=a[s];break;case 69:this.$=a[s-1]+``+a[s];break}},`anonymous`),table:[{18:n,26:1,27:2,28:r,55:i,56:a,57:o},{1:[3]},{18:n,26:8,27:2,28:r,55:i,56:a,57:o},{18:n,26:9,27:2,28:r,55:i,56:a,57:o},t(s,[2,33],{29:10}),t(c,[2,61]),t(c,[2,62]),t(c,[2,63]),{1:[2,30]},{1:[2,31]},t(l,u,{30:11,31:12,24:13,32:15,33:16,34:17,43:30,58:31,1:[2,32],4:d,5:f,10:p,12:m,13:h,14:g,15:_,18:v,25:y,35:b,37:x,39:S,41:C,42:w,48:T,50:E,51:D,52:O,53:k,54:A,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),t(s,[2,34]),{27:46,55:i,56:a,57:o},t(l,[2,37]),t(l,u,{24:13,32:15,33:16,34:17,43:30,58:31,31:47,4:d,5:f,10:p,12:m,13:h,14:g,15:_,18:v,25:y,35:b,37:x,39:S,41:C,42:w,48:T,50:E,51:D,52:O,53:k,54:A,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),t(l,[2,39]),t(l,[2,40]),t(l,[2,41]),{36:[1,48]},{38:[1,49]},{40:[1,50]},t(l,[2,45]),t(l,[2,46]),{18:[1,51]},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:52,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:53,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:54,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:55,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:56,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:57,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,44:[1,58],47:[1,59],58:61,59:60,63:N,64:P,65:F,66:I,67:L},t(B,[2,64]),t(B,[2,66]),t(B,[2,67]),t(B,[2,70]),t(B,[2,71]),t(B,[2,72]),t(B,[2,73]),t(B,[2,74]),t(B,[2,75]),t(B,[2,76]),t(B,[2,77]),t(B,[2,78]),t(B,[2,79]),t(B,[2,80]),t(B,[2,81]),t(s,[2,35]),t(l,[2,38]),t(l,[2,42]),t(l,[2,43]),t(l,[2,44]),{3:65,4:ee,5:te,6:ne,7:re,8:ie,9:ae,10:oe,11:se,12:ce,13:le,14:ue,15:de,21:64},t(l,[2,53],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,49:[1,78],63:N,64:P,65:F,66:I,67:L}),t(l,[2,56],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,49:[1,79],63:N,64:P,65:F,66:I,67:L}),t(l,[2,57],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,58],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,59],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,60],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),{45:[1,80]},{44:[1,81]},t(B,[2,65]),t(B,[2,82]),t(B,[2,83]),t(B,[2,84]),{3:83,4:ee,5:te,6:ne,7:re,8:ie,9:ae,10:oe,11:se,12:ce,13:le,14:ue,15:de,18:[1,82]},t(V,[2,23]),t(V,[2,1]),t(V,[2,2]),t(V,[2,3]),t(V,[2,4]),t(V,[2,5]),t(V,[2,6]),t(V,[2,7]),t(V,[2,8]),t(V,[2,9]),t(V,[2,10]),t(V,[2,11]),t(V,[2,12]),t(l,[2,52],{58:31,43:84,4:d,5:f,10:p,12:m,13:h,14:g,15:_,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),t(l,[2,55],{58:31,43:85,4:d,5:f,10:p,12:m,13:h,14:g,15:_,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),{46:[1,86]},{45:[1,87]},{4:H,5:U,6:W,8:G,11:K,13:q,16:90,17:J,18:Y,19:X,20:Z,22:89,23:88},t(V,[2,24]),t(l,[2,51],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,54],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,47],{22:89,16:90,23:101,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z}),{46:[1,102]},t(l,[2,29],{10:fe}),t(pe,[2,27],{16:104,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z}),t(Q,[2,25]),t(Q,[2,13]),t(Q,[2,14]),t(Q,[2,15]),t(Q,[2,16]),t(Q,[2,17]),t(Q,[2,18]),t(Q,[2,19]),t(Q,[2,20]),t(Q,[2,21]),t(Q,[2,22]),t(l,[2,49],{10:fe}),t(l,[2,48],{22:89,16:90,23:105,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z}),{4:H,5:U,6:W,8:G,11:K,13:q,16:90,17:J,18:Y,19:X,20:Z,22:106},t(Q,[2,26]),t(l,[2,50],{10:fe}),t(pe,[2,28],{16:104,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z})],defaultActions:{8:[2,30],9:[2,31]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{D as r,H as i,K as a,U as o,a as s,c,f as l,v as u,w as d,x as f,y as p,z as m}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as h}from"./linear-DhAcoVP9.js";var g=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,3],r=[1,4],i=[1,5],a=[1,6],o=[1,7],s=[1,4,5,10,12,13,14,15,18,25,35,37,39,41,42,48,50,51,52,53,54,55,56,57,60,61,63,64,65,66,67],c=[1,4,5,10,12,13,14,15,18,25,28,35,37,39,41,42,48,50,51,52,53,54,55,56,57,60,61,63,64,65,66,67],l=[55,56,57],u=[2,36],d=[1,37],f=[1,36],p=[1,38],m=[1,35],h=[1,43],g=[1,41],_=[1,45],v=[1,14],y=[1,23],b=[1,18],x=[1,19],S=[1,20],C=[1,21],w=[1,22],T=[1,24],E=[1,25],D=[1,26],O=[1,27],k=[1,28],A=[1,29],j=[1,32],M=[1,33],N=[1,34],P=[1,39],F=[1,40],I=[1,42],L=[1,44],R=[1,63],z=[1,62],B=[4,5,8,10,12,13,14,15,18,44,47,49,55,56,57,63,64,65,66,67],ee=[1,66],te=[1,67],ne=[1,68],re=[1,69],ie=[1,70],ae=[1,71],oe=[1,72],se=[1,73],ce=[1,74],le=[1,75],ue=[1,76],de=[1,77],V=[4,5,6,7,8,9,10,11,12,13,14,15,18],H=[1,91],U=[1,92],W=[1,93],G=[1,100],K=[1,94],q=[1,97],J=[1,95],Y=[1,96],X=[1,98],Z=[1,99],fe=[1,103],pe=[10,55,56,57],Q=[4,5,6,8,10,11,13,17,18,19,20,55,56,57],me={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,idStringToken:3,ALPHA:4,NUM:5,NODE_STRING:6,DOWN:7,MINUS:8,DEFAULT:9,COMMA:10,COLON:11,AMP:12,BRKT:13,MULT:14,UNICODE_TEXT:15,styleComponent:16,UNIT:17,SPACE:18,STYLE:19,PCT:20,idString:21,style:22,stylesOpt:23,classDefStatement:24,CLASSDEF:25,start:26,eol:27,QUADRANT:28,document:29,line:30,statement:31,axisDetails:32,quadrantDetails:33,points:34,title:35,title_value:36,acc_title:37,acc_title_value:38,acc_descr:39,acc_descr_value:40,acc_descr_multiline_value:41,section:42,text:43,point_start:44,point_x:45,point_y:46,class_name:47,"X-AXIS":48,"AXIS-TEXT-DELIMITER":49,"Y-AXIS":50,QUADRANT_1:51,QUADRANT_2:52,QUADRANT_3:53,QUADRANT_4:54,NEWLINE:55,SEMI:56,EOF:57,alphaNumToken:58,textNoTagsToken:59,STR:60,MD_STR:61,alphaNum:62,PUNCTUATION:63,PLUS:64,EQUALS:65,DOT:66,UNDERSCORE:67,$accept:0,$end:1},terminals_:{2:`error`,4:`ALPHA`,5:`NUM`,6:`NODE_STRING`,7:`DOWN`,8:`MINUS`,9:`DEFAULT`,10:`COMMA`,11:`COLON`,12:`AMP`,13:`BRKT`,14:`MULT`,15:`UNICODE_TEXT`,17:`UNIT`,18:`SPACE`,19:`STYLE`,20:`PCT`,25:`CLASSDEF`,28:`QUADRANT`,35:`title`,36:`title_value`,37:`acc_title`,38:`acc_title_value`,39:`acc_descr`,40:`acc_descr_value`,41:`acc_descr_multiline_value`,42:`section`,44:`point_start`,45:`point_x`,46:`point_y`,47:`class_name`,48:`X-AXIS`,49:`AXIS-TEXT-DELIMITER`,50:`Y-AXIS`,51:`QUADRANT_1`,52:`QUADRANT_2`,53:`QUADRANT_3`,54:`QUADRANT_4`,55:`NEWLINE`,56:`SEMI`,57:`EOF`,60:`STR`,61:`MD_STR`,63:`PUNCTUATION`,64:`PLUS`,65:`EQUALS`,66:`DOT`,67:`UNDERSCORE`},productions_:[0,[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[21,1],[21,2],[22,1],[22,2],[23,1],[23,3],[24,5],[26,2],[26,2],[26,2],[29,0],[29,2],[30,2],[31,0],[31,1],[31,2],[31,1],[31,1],[31,1],[31,2],[31,2],[31,2],[31,1],[31,1],[34,4],[34,5],[34,5],[34,6],[32,4],[32,3],[32,2],[32,4],[32,3],[32,2],[33,2],[33,2],[33,2],[33,2],[27,1],[27,1],[27,1],[43,1],[43,2],[43,1],[43,1],[62,1],[62,2],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[59,1],[59,1],[59,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 23:this.$=a[s];break;case 24:this.$=a[s-1]+``+a[s];break;case 26:this.$=a[s-1]+a[s];break;case 27:this.$=[a[s].trim()];break;case 28:a[s-2].push(a[s].trim()),this.$=a[s-2];break;case 29:this.$=a[s-4],r.addClass(a[s-2],a[s]);break;case 37:this.$=[];break;case 42:this.$=a[s].trim(),r.setDiagramTitle(this.$);break;case 43:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 44:case 45:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 46:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 47:r.addPoint(a[s-3],``,a[s-1],a[s],[]);break;case 48:r.addPoint(a[s-4],a[s-3],a[s-1],a[s],[]);break;case 49:r.addPoint(a[s-4],``,a[s-2],a[s-1],a[s]);break;case 50:r.addPoint(a[s-5],a[s-4],a[s-2],a[s-1],a[s]);break;case 51:r.setXAxisLeftText(a[s-2]),r.setXAxisRightText(a[s]);break;case 52:a[s-1].text+=` ⟶ `,r.setXAxisLeftText(a[s-1]);break;case 53:r.setXAxisLeftText(a[s]);break;case 54:r.setYAxisBottomText(a[s-2]),r.setYAxisTopText(a[s]);break;case 55:a[s-1].text+=` ⟶ `,r.setYAxisBottomText(a[s-1]);break;case 56:r.setYAxisBottomText(a[s]);break;case 57:r.setQuadrant1Text(a[s]);break;case 58:r.setQuadrant2Text(a[s]);break;case 59:r.setQuadrant3Text(a[s]);break;case 60:r.setQuadrant4Text(a[s]);break;case 64:this.$={text:a[s],type:`text`};break;case 65:this.$={text:a[s-1].text+``+a[s],type:a[s-1].type};break;case 66:this.$={text:a[s],type:`text`};break;case 67:this.$={text:a[s],type:`markdown`};break;case 68:this.$=a[s];break;case 69:this.$=a[s-1]+``+a[s];break}},`anonymous`),table:[{18:n,26:1,27:2,28:r,55:i,56:a,57:o},{1:[3]},{18:n,26:8,27:2,28:r,55:i,56:a,57:o},{18:n,26:9,27:2,28:r,55:i,56:a,57:o},t(s,[2,33],{29:10}),t(c,[2,61]),t(c,[2,62]),t(c,[2,63]),{1:[2,30]},{1:[2,31]},t(l,u,{30:11,31:12,24:13,32:15,33:16,34:17,43:30,58:31,1:[2,32],4:d,5:f,10:p,12:m,13:h,14:g,15:_,18:v,25:y,35:b,37:x,39:S,41:C,42:w,48:T,50:E,51:D,52:O,53:k,54:A,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),t(s,[2,34]),{27:46,55:i,56:a,57:o},t(l,[2,37]),t(l,u,{24:13,32:15,33:16,34:17,43:30,58:31,31:47,4:d,5:f,10:p,12:m,13:h,14:g,15:_,18:v,25:y,35:b,37:x,39:S,41:C,42:w,48:T,50:E,51:D,52:O,53:k,54:A,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),t(l,[2,39]),t(l,[2,40]),t(l,[2,41]),{36:[1,48]},{38:[1,49]},{40:[1,50]},t(l,[2,45]),t(l,[2,46]),{18:[1,51]},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:52,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:53,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:54,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:55,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:56,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:57,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,44:[1,58],47:[1,59],58:61,59:60,63:N,64:P,65:F,66:I,67:L},t(B,[2,64]),t(B,[2,66]),t(B,[2,67]),t(B,[2,70]),t(B,[2,71]),t(B,[2,72]),t(B,[2,73]),t(B,[2,74]),t(B,[2,75]),t(B,[2,76]),t(B,[2,77]),t(B,[2,78]),t(B,[2,79]),t(B,[2,80]),t(B,[2,81]),t(s,[2,35]),t(l,[2,38]),t(l,[2,42]),t(l,[2,43]),t(l,[2,44]),{3:65,4:ee,5:te,6:ne,7:re,8:ie,9:ae,10:oe,11:se,12:ce,13:le,14:ue,15:de,21:64},t(l,[2,53],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,49:[1,78],63:N,64:P,65:F,66:I,67:L}),t(l,[2,56],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,49:[1,79],63:N,64:P,65:F,66:I,67:L}),t(l,[2,57],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,58],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,59],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,60],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),{45:[1,80]},{44:[1,81]},t(B,[2,65]),t(B,[2,82]),t(B,[2,83]),t(B,[2,84]),{3:83,4:ee,5:te,6:ne,7:re,8:ie,9:ae,10:oe,11:se,12:ce,13:le,14:ue,15:de,18:[1,82]},t(V,[2,23]),t(V,[2,1]),t(V,[2,2]),t(V,[2,3]),t(V,[2,4]),t(V,[2,5]),t(V,[2,6]),t(V,[2,7]),t(V,[2,8]),t(V,[2,9]),t(V,[2,10]),t(V,[2,11]),t(V,[2,12]),t(l,[2,52],{58:31,43:84,4:d,5:f,10:p,12:m,13:h,14:g,15:_,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),t(l,[2,55],{58:31,43:85,4:d,5:f,10:p,12:m,13:h,14:g,15:_,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),{46:[1,86]},{45:[1,87]},{4:H,5:U,6:W,8:G,11:K,13:q,16:90,17:J,18:Y,19:X,20:Z,22:89,23:88},t(V,[2,24]),t(l,[2,51],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,54],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,47],{22:89,16:90,23:101,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z}),{46:[1,102]},t(l,[2,29],{10:fe}),t(pe,[2,27],{16:104,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z}),t(Q,[2,25]),t(Q,[2,13]),t(Q,[2,14]),t(Q,[2,15]),t(Q,[2,16]),t(Q,[2,17]),t(Q,[2,18]),t(Q,[2,19]),t(Q,[2,20]),t(Q,[2,21]),t(Q,[2,22]),t(l,[2,49],{10:fe}),t(l,[2,48],{22:89,16:90,23:105,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z}),{4:H,5:U,6:W,8:G,11:K,13:q,16:90,17:J,18:Y,19:X,20:Z,22:106},t(Q,[2,26]),t(l,[2,50],{10:fe}),t(pe,[2,28],{16:104,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z})],defaultActions:{8:[2,30],9:[2,31]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};me.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/railroadDiagram-RFXS5EU6-CrinQzap.js b/.vercel/output/static/assets/railroadDiagram-RFXS5EU6-D7w_TgGh.js similarity index 81% rename from .vercel/output/static/assets/railroadDiagram-RFXS5EU6-CrinQzap.js rename to .vercel/output/static/assets/railroadDiagram-RFXS5EU6-D7w_TgGh.js index 5871fcf..3276078 100644 --- a/.vercel/output/static/assets/railroadDiagram-RFXS5EU6-CrinQzap.js +++ b/.vercel/output/static/assets/railroadDiagram-RFXS5EU6-D7w_TgGh.js @@ -1 +1 @@ -import{n as e}from"./chunk-5TONJI2A-DOX2waSJ.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-_wZywoZs.js";import"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-VAUOI2AC-CLN1Ga8_.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-DR1aBwdH.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-AdnthA1k.js";var c=e().Railroad.parser.LangiumParser,l=t(e=>{switch(e.$type){case`RailroadTerminalExpr`:return{type:`terminal`,value:e.value};case`RailroadNonTerminalExpr`:return{type:`nonterminal`,name:e.name};case`RailroadSpecialExpr`:return{type:`special`,text:e.text};case`RailroadSequenceExpr`:{let t=e.elements.map(l);return t.length===1?t[0]:{type:`sequence`,elements:t}}case`RailroadChoiceExpr`:{let t=e.alternatives.map(l);return t.length===1?t[0]:{type:`choice`,alternatives:t}}case`RailroadOptionalExpr`:return{type:`optional`,element:l(e.element)};case`RailroadOneOrMoreExpr`:return{type:`repetition`,element:l(e.element),min:1,max:1/0};case`RailroadZeroOrMoreExpr`:return{type:`repetition`,element:l(e.element),min:0,max:1/0};default:throw Error(`Unsupported railroad expression: ${e.$type}`)}},`transformExpression`),u=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),d=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(u(e)))},`populateDb`),f={parser:{parse:t(e=>{a.clear(),n.debug(`[Railroad Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[Railroad Parser] Parsed rules:`,r.rules.length),d(r),n.debug(`[Railroad Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{f as diagram}; \ No newline at end of file +import{n as e}from"./chunk-5TONJI2A-DOX2waSJ.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-Bju_yCKi.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-Z7xZAZRH.js";var c=e().Railroad.parser.LangiumParser,l=t(e=>{switch(e.$type){case`RailroadTerminalExpr`:return{type:`terminal`,value:e.value};case`RailroadNonTerminalExpr`:return{type:`nonterminal`,name:e.name};case`RailroadSpecialExpr`:return{type:`special`,text:e.text};case`RailroadSequenceExpr`:{let t=e.elements.map(l);return t.length===1?t[0]:{type:`sequence`,elements:t}}case`RailroadChoiceExpr`:{let t=e.alternatives.map(l);return t.length===1?t[0]:{type:`choice`,alternatives:t}}case`RailroadOptionalExpr`:return{type:`optional`,element:l(e.element)};case`RailroadOneOrMoreExpr`:return{type:`repetition`,element:l(e.element),min:1,max:1/0};case`RailroadZeroOrMoreExpr`:return{type:`repetition`,element:l(e.element),min:0,max:1/0};default:throw Error(`Unsupported railroad expression: ${e.$type}`)}},`transformExpression`),u=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),d=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(u(e)))},`populateDb`),f={parser:{parse:t(e=>{a.clear(),n.debug(`[Railroad Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[Railroad Parser] Parsed rules:`,r.rules.length),d(r),n.debug(`[Railroad Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{f as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/react-Biaal4sZ.js b/.vercel/output/static/assets/react-BLJmJXjR.js similarity index 99% rename from .vercel/output/static/assets/react-Biaal4sZ.js rename to .vercel/output/static/assets/react-BLJmJXjR.js index 398444a..3a483f5 100644 --- a/.vercel/output/static/assets/react-Biaal4sZ.js +++ b/.vercel/output/static/assets/react-BLJmJXjR.js @@ -1 +1 @@ -import{t as e}from"./rolldown-runtime-QTnfLwEv.js";var t=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{n.exports=t()}));export{n as t}; \ No newline at end of file +import{t as e}from"./rolldown-runtime-aKtaBQYM.js";var t=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{n.exports=t()}));export{n as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/requirementDiagram-TGXJPOKE-2PeqVsa7.js b/.vercel/output/static/assets/requirementDiagram-TGXJPOKE-Bk3E4jWx.js similarity index 97% rename from .vercel/output/static/assets/requirementDiagram-TGXJPOKE-2PeqVsa7.js rename to .vercel/output/static/assets/requirementDiagram-TGXJPOKE-Bk3E4jWx.js index 7c71c83..399bc68 100644 --- a/.vercel/output/static/assets/requirementDiagram-TGXJPOKE-2PeqVsa7.js +++ b/.vercel/output/static/assets/requirementDiagram-TGXJPOKE-Bk3E4jWx.js @@ -1,4 +1,4 @@ -import{n as e,t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-_wZywoZs.js";import{H as r,K as i,U as a,a as o,b as s,v as c,w as l,x as u,y as d}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{g as f}from"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import{t as p}from"./chunk-XXDRQBXY-BuE3VzE_.js";import{t as m}from"./chunk-VR4S4FIN-BJzXasDJ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import"./chunk-ZGVPDNZ5-zo3h_nOA.js";import"./chunk-52WLFC77-BBAyrLn9.js";import{r as h,t as g}from"./chunk-FWX5IMBZ-CiLc9_ts.js";var _=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,3],r=[1,4],i=[1,5],a=[1,6],o=[5,6,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,77,89,90],s=[1,22],c=[2,7],l=[1,26],u=[1,27],d=[1,28],f=[1,29],p=[1,33],m=[1,34],h=[1,35],g=[1,36],_=[1,37],v=[1,38],y=[1,24],b=[1,31],x=[1,32],S=[1,30],C=[1,39],w=[1,40],T=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,77,89,90],E=[1,61],D=[89,90],O=[5,8,9,11,13,21,22,23,24,27,29,41,42,43,44,45,46,54,61,63,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],k=[27,29],ee=[1,70],A=[1,71],te=[1,72],ne=[1,73],re=[1,74],ie=[1,75],ae=[1,76],j=[1,83],M=[1,80],N=[1,84],P=[1,85],F=[1,86],I=[1,87],L=[1,88],R=[1,89],z=[1,90],B=[1,91],V=[1,92],oe=[5,8,9,11,13,21,22,23,24,27,41,42,43,44,45,46,54,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],H=[63,64],se=[1,101],ce=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,76,77,89,90],U=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],W=[1,110],G=[1,106],K=[1,107],q=[1,108],J=[1,109],Y=[1,111],X=[1,116],Z=[1,117],Q=[1,114],$=[1,115],le={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,directive:4,NEWLINE:5,RD:6,diagram:7,EOF:8,acc_title:9,acc_title_value:10,acc_descr:11,acc_descr_value:12,acc_descr_multiline_value:13,requirementDef:14,elementDef:15,relationshipDef:16,direction:17,styleStatement:18,classDefStatement:19,classStatement:20,direction_tb:21,direction_bt:22,direction_rl:23,direction_lr:24,requirementType:25,requirementName:26,STRUCT_START:27,requirementBody:28,STYLE_SEPARATOR:29,idList:30,ID:31,COLONSEP:32,id:33,TEXT:34,text:35,RISK:36,riskLevel:37,VERIFYMTHD:38,verifyType:39,STRUCT_STOP:40,REQUIREMENT:41,FUNCTIONAL_REQUIREMENT:42,INTERFACE_REQUIREMENT:43,PERFORMANCE_REQUIREMENT:44,PHYSICAL_REQUIREMENT:45,DESIGN_CONSTRAINT:46,LOW_RISK:47,MED_RISK:48,HIGH_RISK:49,VERIFY_ANALYSIS:50,VERIFY_DEMONSTRATION:51,VERIFY_INSPECTION:52,VERIFY_TEST:53,ELEMENT:54,elementName:55,elementBody:56,TYPE:57,type:58,DOCREF:59,ref:60,END_ARROW_L:61,relationship:62,LINE:63,END_ARROW_R:64,CONTAINS:65,COPIES:66,DERIVES:67,SATISFIES:68,VERIFIES:69,REFINES:70,TRACES:71,CLASSDEF:72,stylesOpt:73,CLASS:74,ALPHA:75,COMMA:76,STYLE:77,style:78,styleComponent:79,NUM:80,COLON:81,UNIT:82,SPACE:83,BRKT:84,PCT:85,MINUS:86,LABEL:87,SEMICOLON:88,unqString:89,qString:90,$accept:0,$end:1},terminals_:{2:`error`,5:`NEWLINE`,6:`RD`,8:`EOF`,9:`acc_title`,10:`acc_title_value`,11:`acc_descr`,12:`acc_descr_value`,13:`acc_descr_multiline_value`,21:`direction_tb`,22:`direction_bt`,23:`direction_rl`,24:`direction_lr`,27:`STRUCT_START`,29:`STYLE_SEPARATOR`,31:`ID`,32:`COLONSEP`,34:`TEXT`,36:`RISK`,38:`VERIFYMTHD`,40:`STRUCT_STOP`,41:`REQUIREMENT`,42:`FUNCTIONAL_REQUIREMENT`,43:`INTERFACE_REQUIREMENT`,44:`PERFORMANCE_REQUIREMENT`,45:`PHYSICAL_REQUIREMENT`,46:`DESIGN_CONSTRAINT`,47:`LOW_RISK`,48:`MED_RISK`,49:`HIGH_RISK`,50:`VERIFY_ANALYSIS`,51:`VERIFY_DEMONSTRATION`,52:`VERIFY_INSPECTION`,53:`VERIFY_TEST`,54:`ELEMENT`,57:`TYPE`,59:`DOCREF`,61:`END_ARROW_L`,63:`LINE`,64:`END_ARROW_R`,65:`CONTAINS`,66:`COPIES`,67:`DERIVES`,68:`SATISFIES`,69:`VERIFIES`,70:`REFINES`,71:`TRACES`,72:`CLASSDEF`,74:`CLASS`,75:`ALPHA`,76:`COMMA`,77:`STYLE`,80:`NUM`,81:`COLON`,82:`UNIT`,83:`SPACE`,84:`BRKT`,85:`PCT`,86:`MINUS`,87:`LABEL`,88:`SEMICOLON`,89:`unqString`,90:`qString`},productions_:[0,[3,3],[3,2],[3,4],[4,2],[4,2],[4,1],[7,0],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[17,1],[17,1],[17,1],[17,1],[14,5],[14,7],[28,5],[28,5],[28,5],[28,5],[28,2],[28,1],[25,1],[25,1],[25,1],[25,1],[25,1],[25,1],[37,1],[37,1],[37,1],[39,1],[39,1],[39,1],[39,1],[15,5],[15,7],[56,5],[56,5],[56,2],[56,1],[16,5],[16,5],[62,1],[62,1],[62,1],[62,1],[62,1],[62,1],[62,1],[19,3],[20,3],[20,3],[30,1],[30,3],[30,1],[30,3],[18,3],[73,1],[73,3],[78,1],[78,2],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[26,1],[26,1],[33,1],[33,1],[35,1],[35,1],[55,1],[55,1],[58,1],[58,1],[60,1],[60,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 4:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 5:case 6:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 7:this.$=[];break;case 17:r.setDirection(`TB`);break;case 18:r.setDirection(`BT`);break;case 19:r.setDirection(`RL`);break;case 20:r.setDirection(`LR`);break;case 21:r.addRequirement(a[s-3],a[s-4]);break;case 22:r.addRequirement(a[s-5],a[s-6]),r.setClass([a[s-5]],a[s-3]);break;case 23:r.setNewReqId(a[s-2]);break;case 24:r.setNewReqText(a[s-2]);break;case 25:r.setNewReqRisk(a[s-2]);break;case 26:r.setNewReqVerifyMethod(a[s-2]);break;case 29:this.$=r.RequirementType.REQUIREMENT;break;case 30:this.$=r.RequirementType.FUNCTIONAL_REQUIREMENT;break;case 31:this.$=r.RequirementType.INTERFACE_REQUIREMENT;break;case 32:this.$=r.RequirementType.PERFORMANCE_REQUIREMENT;break;case 33:this.$=r.RequirementType.PHYSICAL_REQUIREMENT;break;case 34:this.$=r.RequirementType.DESIGN_CONSTRAINT;break;case 35:this.$=r.RiskLevel.LOW_RISK;break;case 36:this.$=r.RiskLevel.MED_RISK;break;case 37:this.$=r.RiskLevel.HIGH_RISK;break;case 38:this.$=r.VerifyType.VERIFY_ANALYSIS;break;case 39:this.$=r.VerifyType.VERIFY_DEMONSTRATION;break;case 40:this.$=r.VerifyType.VERIFY_INSPECTION;break;case 41:this.$=r.VerifyType.VERIFY_TEST;break;case 42:r.addElement(a[s-3]);break;case 43:r.addElement(a[s-5]),r.setClass([a[s-5]],a[s-3]);break;case 44:r.setNewElementType(a[s-2]);break;case 45:r.setNewElementDocRef(a[s-2]);break;case 48:r.addRelationship(a[s-2],a[s],a[s-4]);break;case 49:r.addRelationship(a[s-2],a[s-4],a[s]);break;case 50:this.$=r.Relationships.CONTAINS;break;case 51:this.$=r.Relationships.COPIES;break;case 52:this.$=r.Relationships.DERIVES;break;case 53:this.$=r.Relationships.SATISFIES;break;case 54:this.$=r.Relationships.VERIFIES;break;case 55:this.$=r.Relationships.REFINES;break;case 56:this.$=r.Relationships.TRACES;break;case 57:this.$=a[s-2],r.defineClass(a[s-1],a[s]);break;case 58:r.setClass(a[s-1],a[s]);break;case 59:r.setClass([a[s-2]],a[s]);break;case 60:case 62:this.$=[a[s]];break;case 61:case 63:this.$=a[s-2].concat([a[s]]);break;case 64:this.$=a[s-2],r.setCssStyle(a[s-1],a[s]);break;case 65:this.$=[a[s]];break;case 66:a[s-2].push(a[s]),this.$=a[s-2];break;case 68:this.$=a[s-1]+a[s];break}},`anonymous`),table:[{3:1,4:2,6:n,9:r,11:i,13:a},{1:[3]},{3:8,4:2,5:[1,7],6:n,9:r,11:i,13:a},{5:[1,9]},{10:[1,10]},{12:[1,11]},t(o,[2,6]),{3:12,4:2,6:n,9:r,11:i,13:a},{1:[2,2]},{4:17,5:s,7:13,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},t(o,[2,4]),t(o,[2,5]),{1:[2,1]},{8:[1,41]},{4:17,5:s,7:42,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:43,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:44,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:45,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:46,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:47,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:48,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:49,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:50,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{26:51,89:[1,52],90:[1,53]},{55:54,89:[1,55],90:[1,56]},{29:[1,59],61:[1,57],63:[1,58]},t(T,[2,17]),t(T,[2,18]),t(T,[2,19]),t(T,[2,20]),{30:60,33:62,75:E,89:C,90:w},{30:63,33:62,75:E,89:C,90:w},{30:64,33:62,75:E,89:C,90:w},t(D,[2,29]),t(D,[2,30]),t(D,[2,31]),t(D,[2,32]),t(D,[2,33]),t(D,[2,34]),t(O,[2,81]),t(O,[2,82]),{1:[2,3]},{8:[2,8]},{8:[2,9]},{8:[2,10]},{8:[2,11]},{8:[2,12]},{8:[2,13]},{8:[2,14]},{8:[2,15]},{8:[2,16]},{27:[1,65],29:[1,66]},t(k,[2,79]),t(k,[2,80]),{27:[1,67],29:[1,68]},t(k,[2,85]),t(k,[2,86]),{62:69,65:ee,66:A,67:te,68:ne,69:re,70:ie,71:ae},{62:77,65:ee,66:A,67:te,68:ne,69:re,70:ie,71:ae},{30:78,33:62,75:E,89:C,90:w},{73:79,75:j,76:M,78:81,79:82,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V},t(oe,[2,60]),t(oe,[2,62]),{73:93,75:j,76:M,78:81,79:82,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V},{30:94,33:62,75:E,76:M,89:C,90:w},{5:[1,95]},{30:96,33:62,75:E,89:C,90:w},{5:[1,97]},{30:98,33:62,75:E,89:C,90:w},{63:[1,99]},t(H,[2,50]),t(H,[2,51]),t(H,[2,52]),t(H,[2,53]),t(H,[2,54]),t(H,[2,55]),t(H,[2,56]),{64:[1,100]},t(T,[2,59],{76:M}),t(T,[2,64],{76:se}),{33:103,75:[1,102],89:C,90:w},t(ce,[2,65],{79:104,75:j,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V}),t(U,[2,67]),t(U,[2,69]),t(U,[2,70]),t(U,[2,71]),t(U,[2,72]),t(U,[2,73]),t(U,[2,74]),t(U,[2,75]),t(U,[2,76]),t(U,[2,77]),t(U,[2,78]),t(T,[2,57],{76:se}),t(T,[2,58],{76:M}),{5:W,28:105,31:G,34:K,36:q,38:J,40:Y},{27:[1,112],76:M},{5:X,40:Z,56:113,57:Q,59:$},{27:[1,118],76:M},{33:119,89:C,90:w},{33:120,89:C,90:w},{75:j,78:121,79:82,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V},t(oe,[2,61]),t(oe,[2,63]),t(U,[2,68]),t(T,[2,21]),{32:[1,122]},{32:[1,123]},{32:[1,124]},{32:[1,125]},{5:W,28:126,31:G,34:K,36:q,38:J,40:Y},t(T,[2,28]),{5:[1,127]},t(T,[2,42]),{32:[1,128]},{32:[1,129]},{5:X,40:Z,56:130,57:Q,59:$},t(T,[2,47]),{5:[1,131]},t(T,[2,48]),t(T,[2,49]),t(ce,[2,66],{79:104,75:j,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V}),{33:132,89:C,90:w},{35:133,89:[1,134],90:[1,135]},{37:136,47:[1,137],48:[1,138],49:[1,139]},{39:140,50:[1,141],51:[1,142],52:[1,143],53:[1,144]},t(T,[2,27]),{5:W,28:145,31:G,34:K,36:q,38:J,40:Y},{58:146,89:[1,147],90:[1,148]},{60:149,89:[1,150],90:[1,151]},t(T,[2,46]),{5:X,40:Z,56:152,57:Q,59:$},{5:[1,153]},{5:[1,154]},{5:[2,83]},{5:[2,84]},{5:[1,155]},{5:[2,35]},{5:[2,36]},{5:[2,37]},{5:[1,156]},{5:[2,38]},{5:[2,39]},{5:[2,40]},{5:[2,41]},t(T,[2,22]),{5:[1,157]},{5:[2,87]},{5:[2,88]},{5:[1,158]},{5:[2,89]},{5:[2,90]},t(T,[2,43]),{5:W,28:159,31:G,34:K,36:q,38:J,40:Y},{5:W,28:160,31:G,34:K,36:q,38:J,40:Y},{5:W,28:161,31:G,34:K,36:q,38:J,40:Y},{5:W,28:162,31:G,34:K,36:q,38:J,40:Y},{5:X,40:Z,56:163,57:Q,59:$},{5:X,40:Z,56:164,57:Q,59:$},t(T,[2,23]),t(T,[2,24]),t(T,[2,25]),t(T,[2,26]),t(T,[2,44]),t(T,[2,45])],defaultActions:{8:[2,2],12:[2,1],41:[2,3],42:[2,8],43:[2,9],44:[2,10],45:[2,11],46:[2,12],47:[2,13],48:[2,14],49:[2,15],50:[2,16],134:[2,83],135:[2,84],137:[2,35],138:[2,36],139:[2,37],141:[2,38],142:[2,39],143:[2,40],144:[2,41],147:[2,87],148:[2,88],150:[2,89],151:[2,90]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,ee,A;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var te=``;for(O in A=[],s[w])this.terminals_[O]&&O>f&&A.push(`'`+this.terminals_[O]+`'`);te=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e,t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import{H as r,K as i,U as a,a as o,b as s,v as c,w as l,x as u,y as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{g as f}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import{t as p}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as m}from"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import{r as h,t as g}from"./chunk-FWX5IMBZ-ComLEIwh.js";var _=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,3],r=[1,4],i=[1,5],a=[1,6],o=[5,6,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,77,89,90],s=[1,22],c=[2,7],l=[1,26],u=[1,27],d=[1,28],f=[1,29],p=[1,33],m=[1,34],h=[1,35],g=[1,36],_=[1,37],v=[1,38],y=[1,24],b=[1,31],x=[1,32],S=[1,30],C=[1,39],w=[1,40],T=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,77,89,90],E=[1,61],D=[89,90],O=[5,8,9,11,13,21,22,23,24,27,29,41,42,43,44,45,46,54,61,63,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],k=[27,29],ee=[1,70],A=[1,71],te=[1,72],ne=[1,73],re=[1,74],ie=[1,75],ae=[1,76],j=[1,83],M=[1,80],N=[1,84],P=[1,85],F=[1,86],I=[1,87],L=[1,88],R=[1,89],z=[1,90],B=[1,91],V=[1,92],oe=[5,8,9,11,13,21,22,23,24,27,41,42,43,44,45,46,54,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],H=[63,64],se=[1,101],ce=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,76,77,89,90],U=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],W=[1,110],G=[1,106],K=[1,107],q=[1,108],J=[1,109],Y=[1,111],X=[1,116],Z=[1,117],Q=[1,114],$=[1,115],le={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,directive:4,NEWLINE:5,RD:6,diagram:7,EOF:8,acc_title:9,acc_title_value:10,acc_descr:11,acc_descr_value:12,acc_descr_multiline_value:13,requirementDef:14,elementDef:15,relationshipDef:16,direction:17,styleStatement:18,classDefStatement:19,classStatement:20,direction_tb:21,direction_bt:22,direction_rl:23,direction_lr:24,requirementType:25,requirementName:26,STRUCT_START:27,requirementBody:28,STYLE_SEPARATOR:29,idList:30,ID:31,COLONSEP:32,id:33,TEXT:34,text:35,RISK:36,riskLevel:37,VERIFYMTHD:38,verifyType:39,STRUCT_STOP:40,REQUIREMENT:41,FUNCTIONAL_REQUIREMENT:42,INTERFACE_REQUIREMENT:43,PERFORMANCE_REQUIREMENT:44,PHYSICAL_REQUIREMENT:45,DESIGN_CONSTRAINT:46,LOW_RISK:47,MED_RISK:48,HIGH_RISK:49,VERIFY_ANALYSIS:50,VERIFY_DEMONSTRATION:51,VERIFY_INSPECTION:52,VERIFY_TEST:53,ELEMENT:54,elementName:55,elementBody:56,TYPE:57,type:58,DOCREF:59,ref:60,END_ARROW_L:61,relationship:62,LINE:63,END_ARROW_R:64,CONTAINS:65,COPIES:66,DERIVES:67,SATISFIES:68,VERIFIES:69,REFINES:70,TRACES:71,CLASSDEF:72,stylesOpt:73,CLASS:74,ALPHA:75,COMMA:76,STYLE:77,style:78,styleComponent:79,NUM:80,COLON:81,UNIT:82,SPACE:83,BRKT:84,PCT:85,MINUS:86,LABEL:87,SEMICOLON:88,unqString:89,qString:90,$accept:0,$end:1},terminals_:{2:`error`,5:`NEWLINE`,6:`RD`,8:`EOF`,9:`acc_title`,10:`acc_title_value`,11:`acc_descr`,12:`acc_descr_value`,13:`acc_descr_multiline_value`,21:`direction_tb`,22:`direction_bt`,23:`direction_rl`,24:`direction_lr`,27:`STRUCT_START`,29:`STYLE_SEPARATOR`,31:`ID`,32:`COLONSEP`,34:`TEXT`,36:`RISK`,38:`VERIFYMTHD`,40:`STRUCT_STOP`,41:`REQUIREMENT`,42:`FUNCTIONAL_REQUIREMENT`,43:`INTERFACE_REQUIREMENT`,44:`PERFORMANCE_REQUIREMENT`,45:`PHYSICAL_REQUIREMENT`,46:`DESIGN_CONSTRAINT`,47:`LOW_RISK`,48:`MED_RISK`,49:`HIGH_RISK`,50:`VERIFY_ANALYSIS`,51:`VERIFY_DEMONSTRATION`,52:`VERIFY_INSPECTION`,53:`VERIFY_TEST`,54:`ELEMENT`,57:`TYPE`,59:`DOCREF`,61:`END_ARROW_L`,63:`LINE`,64:`END_ARROW_R`,65:`CONTAINS`,66:`COPIES`,67:`DERIVES`,68:`SATISFIES`,69:`VERIFIES`,70:`REFINES`,71:`TRACES`,72:`CLASSDEF`,74:`CLASS`,75:`ALPHA`,76:`COMMA`,77:`STYLE`,80:`NUM`,81:`COLON`,82:`UNIT`,83:`SPACE`,84:`BRKT`,85:`PCT`,86:`MINUS`,87:`LABEL`,88:`SEMICOLON`,89:`unqString`,90:`qString`},productions_:[0,[3,3],[3,2],[3,4],[4,2],[4,2],[4,1],[7,0],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[17,1],[17,1],[17,1],[17,1],[14,5],[14,7],[28,5],[28,5],[28,5],[28,5],[28,2],[28,1],[25,1],[25,1],[25,1],[25,1],[25,1],[25,1],[37,1],[37,1],[37,1],[39,1],[39,1],[39,1],[39,1],[15,5],[15,7],[56,5],[56,5],[56,2],[56,1],[16,5],[16,5],[62,1],[62,1],[62,1],[62,1],[62,1],[62,1],[62,1],[19,3],[20,3],[20,3],[30,1],[30,3],[30,1],[30,3],[18,3],[73,1],[73,3],[78,1],[78,2],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[26,1],[26,1],[33,1],[33,1],[35,1],[35,1],[55,1],[55,1],[58,1],[58,1],[60,1],[60,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 4:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 5:case 6:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 7:this.$=[];break;case 17:r.setDirection(`TB`);break;case 18:r.setDirection(`BT`);break;case 19:r.setDirection(`RL`);break;case 20:r.setDirection(`LR`);break;case 21:r.addRequirement(a[s-3],a[s-4]);break;case 22:r.addRequirement(a[s-5],a[s-6]),r.setClass([a[s-5]],a[s-3]);break;case 23:r.setNewReqId(a[s-2]);break;case 24:r.setNewReqText(a[s-2]);break;case 25:r.setNewReqRisk(a[s-2]);break;case 26:r.setNewReqVerifyMethod(a[s-2]);break;case 29:this.$=r.RequirementType.REQUIREMENT;break;case 30:this.$=r.RequirementType.FUNCTIONAL_REQUIREMENT;break;case 31:this.$=r.RequirementType.INTERFACE_REQUIREMENT;break;case 32:this.$=r.RequirementType.PERFORMANCE_REQUIREMENT;break;case 33:this.$=r.RequirementType.PHYSICAL_REQUIREMENT;break;case 34:this.$=r.RequirementType.DESIGN_CONSTRAINT;break;case 35:this.$=r.RiskLevel.LOW_RISK;break;case 36:this.$=r.RiskLevel.MED_RISK;break;case 37:this.$=r.RiskLevel.HIGH_RISK;break;case 38:this.$=r.VerifyType.VERIFY_ANALYSIS;break;case 39:this.$=r.VerifyType.VERIFY_DEMONSTRATION;break;case 40:this.$=r.VerifyType.VERIFY_INSPECTION;break;case 41:this.$=r.VerifyType.VERIFY_TEST;break;case 42:r.addElement(a[s-3]);break;case 43:r.addElement(a[s-5]),r.setClass([a[s-5]],a[s-3]);break;case 44:r.setNewElementType(a[s-2]);break;case 45:r.setNewElementDocRef(a[s-2]);break;case 48:r.addRelationship(a[s-2],a[s],a[s-4]);break;case 49:r.addRelationship(a[s-2],a[s-4],a[s]);break;case 50:this.$=r.Relationships.CONTAINS;break;case 51:this.$=r.Relationships.COPIES;break;case 52:this.$=r.Relationships.DERIVES;break;case 53:this.$=r.Relationships.SATISFIES;break;case 54:this.$=r.Relationships.VERIFIES;break;case 55:this.$=r.Relationships.REFINES;break;case 56:this.$=r.Relationships.TRACES;break;case 57:this.$=a[s-2],r.defineClass(a[s-1],a[s]);break;case 58:r.setClass(a[s-1],a[s]);break;case 59:r.setClass([a[s-2]],a[s]);break;case 60:case 62:this.$=[a[s]];break;case 61:case 63:this.$=a[s-2].concat([a[s]]);break;case 64:this.$=a[s-2],r.setCssStyle(a[s-1],a[s]);break;case 65:this.$=[a[s]];break;case 66:a[s-2].push(a[s]),this.$=a[s-2];break;case 68:this.$=a[s-1]+a[s];break}},`anonymous`),table:[{3:1,4:2,6:n,9:r,11:i,13:a},{1:[3]},{3:8,4:2,5:[1,7],6:n,9:r,11:i,13:a},{5:[1,9]},{10:[1,10]},{12:[1,11]},t(o,[2,6]),{3:12,4:2,6:n,9:r,11:i,13:a},{1:[2,2]},{4:17,5:s,7:13,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},t(o,[2,4]),t(o,[2,5]),{1:[2,1]},{8:[1,41]},{4:17,5:s,7:42,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:43,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:44,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:45,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:46,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:47,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:48,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:49,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:50,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{26:51,89:[1,52],90:[1,53]},{55:54,89:[1,55],90:[1,56]},{29:[1,59],61:[1,57],63:[1,58]},t(T,[2,17]),t(T,[2,18]),t(T,[2,19]),t(T,[2,20]),{30:60,33:62,75:E,89:C,90:w},{30:63,33:62,75:E,89:C,90:w},{30:64,33:62,75:E,89:C,90:w},t(D,[2,29]),t(D,[2,30]),t(D,[2,31]),t(D,[2,32]),t(D,[2,33]),t(D,[2,34]),t(O,[2,81]),t(O,[2,82]),{1:[2,3]},{8:[2,8]},{8:[2,9]},{8:[2,10]},{8:[2,11]},{8:[2,12]},{8:[2,13]},{8:[2,14]},{8:[2,15]},{8:[2,16]},{27:[1,65],29:[1,66]},t(k,[2,79]),t(k,[2,80]),{27:[1,67],29:[1,68]},t(k,[2,85]),t(k,[2,86]),{62:69,65:ee,66:A,67:te,68:ne,69:re,70:ie,71:ae},{62:77,65:ee,66:A,67:te,68:ne,69:re,70:ie,71:ae},{30:78,33:62,75:E,89:C,90:w},{73:79,75:j,76:M,78:81,79:82,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V},t(oe,[2,60]),t(oe,[2,62]),{73:93,75:j,76:M,78:81,79:82,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V},{30:94,33:62,75:E,76:M,89:C,90:w},{5:[1,95]},{30:96,33:62,75:E,89:C,90:w},{5:[1,97]},{30:98,33:62,75:E,89:C,90:w},{63:[1,99]},t(H,[2,50]),t(H,[2,51]),t(H,[2,52]),t(H,[2,53]),t(H,[2,54]),t(H,[2,55]),t(H,[2,56]),{64:[1,100]},t(T,[2,59],{76:M}),t(T,[2,64],{76:se}),{33:103,75:[1,102],89:C,90:w},t(ce,[2,65],{79:104,75:j,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V}),t(U,[2,67]),t(U,[2,69]),t(U,[2,70]),t(U,[2,71]),t(U,[2,72]),t(U,[2,73]),t(U,[2,74]),t(U,[2,75]),t(U,[2,76]),t(U,[2,77]),t(U,[2,78]),t(T,[2,57],{76:se}),t(T,[2,58],{76:M}),{5:W,28:105,31:G,34:K,36:q,38:J,40:Y},{27:[1,112],76:M},{5:X,40:Z,56:113,57:Q,59:$},{27:[1,118],76:M},{33:119,89:C,90:w},{33:120,89:C,90:w},{75:j,78:121,79:82,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V},t(oe,[2,61]),t(oe,[2,63]),t(U,[2,68]),t(T,[2,21]),{32:[1,122]},{32:[1,123]},{32:[1,124]},{32:[1,125]},{5:W,28:126,31:G,34:K,36:q,38:J,40:Y},t(T,[2,28]),{5:[1,127]},t(T,[2,42]),{32:[1,128]},{32:[1,129]},{5:X,40:Z,56:130,57:Q,59:$},t(T,[2,47]),{5:[1,131]},t(T,[2,48]),t(T,[2,49]),t(ce,[2,66],{79:104,75:j,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V}),{33:132,89:C,90:w},{35:133,89:[1,134],90:[1,135]},{37:136,47:[1,137],48:[1,138],49:[1,139]},{39:140,50:[1,141],51:[1,142],52:[1,143],53:[1,144]},t(T,[2,27]),{5:W,28:145,31:G,34:K,36:q,38:J,40:Y},{58:146,89:[1,147],90:[1,148]},{60:149,89:[1,150],90:[1,151]},t(T,[2,46]),{5:X,40:Z,56:152,57:Q,59:$},{5:[1,153]},{5:[1,154]},{5:[2,83]},{5:[2,84]},{5:[1,155]},{5:[2,35]},{5:[2,36]},{5:[2,37]},{5:[1,156]},{5:[2,38]},{5:[2,39]},{5:[2,40]},{5:[2,41]},t(T,[2,22]),{5:[1,157]},{5:[2,87]},{5:[2,88]},{5:[1,158]},{5:[2,89]},{5:[2,90]},t(T,[2,43]),{5:W,28:159,31:G,34:K,36:q,38:J,40:Y},{5:W,28:160,31:G,34:K,36:q,38:J,40:Y},{5:W,28:161,31:G,34:K,36:q,38:J,40:Y},{5:W,28:162,31:G,34:K,36:q,38:J,40:Y},{5:X,40:Z,56:163,57:Q,59:$},{5:X,40:Z,56:164,57:Q,59:$},t(T,[2,23]),t(T,[2,24]),t(T,[2,25]),t(T,[2,26]),t(T,[2,44]),t(T,[2,45])],defaultActions:{8:[2,2],12:[2,1],41:[2,3],42:[2,8],43:[2,9],44:[2,10],45:[2,11],46:[2,12],47:[2,13],48:[2,14],49:[2,15],50:[2,16],134:[2,83],135:[2,84],137:[2,35],138:[2,36],139:[2,37],141:[2,38],142:[2,39],143:[2,40],144:[2,41],147:[2,87],148:[2,88],150:[2,89],151:[2,90]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,ee,A;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var te=``;for(O in A=[],s[w])this.terminals_[O]&&O>f&&A.push(`'`+this.terminals_[O]+`'`);te=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+A.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(te,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:A})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),ee=s[r[r.length-2]][r[r.length-1]],r.push(ee);break;case 3:return!0}}return!0},`parse`)};le.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/rolldown-runtime-QTnfLwEv.js b/.vercel/output/static/assets/rolldown-runtime-aKtaBQYM.js similarity index 59% rename from .vercel/output/static/assets/rolldown-runtime-QTnfLwEv.js rename to .vercel/output/static/assets/rolldown-runtime-aKtaBQYM.js index 8d9db23..8e7d307 100644 --- a/.vercel/output/static/assets/rolldown-runtime-QTnfLwEv.js +++ b/.vercel/output/static/assets/rolldown-runtime-aKtaBQYM.js @@ -1 +1 @@ -var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));export{s as n,l as r,o as t}; \ No newline at end of file +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});export{l as i,s as n,u as r,o as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/routes-BDn33g5C.js b/.vercel/output/static/assets/routes-BDn33g5C.js new file mode 100644 index 0000000..55c290f --- /dev/null +++ b/.vercel/output/static/assets/routes-BDn33g5C.js @@ -0,0 +1,67 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-lwoghoVk.js","assets/index-CXgd9jpl.js","assets/rolldown-runtime-aKtaBQYM.js","assets/react-BLJmJXjR.js","assets/utils-BTuSbA5p.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-UMNXGZaF.js","assets/chunk-WYO6CB5R-Dv5kDyQC.js","assets/chunk-ICXQ74PX-Czpgj8Uw.js","assets/dist-qx0Iv9vM.js","assets/chunk-VAUOI2AC-AC9pRUsa.js","assets/chunk-HOUHSVGY-iJuv90UH.js","assets/chunk-Q4XR5HBZ-CQ8zkLYc.js","assets/chunk-7BUUIJ7U-Bb538aSH.js","assets/chunk-OGEWGWER-D-nWYRNR.js","assets/chunk-C7G6YPKG-DW-1jWUA.js","assets/chunk-ZGVPDNZ5-DGInJAPD.js","assets/rough.esm-CSKSodPl.js","assets/chunk-52WLFC77-BOCvVCX1.js","assets/line-b9Ala942.js","assets/path-BWPyau1x.js","assets/array-BifhSqXX.js","assets/chunk-FWX5IMBZ-ComLEIwh.js","assets/chunk-ZIRB5QZD-C6fEPe3t.js","assets/client-CwgDvMJw.js"])))=>i.map(i=>d[i]); +import{i as e,r as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}from"./react-BLJmJXjR.js";import{G as i,i as a,n as o,t as s,u as c}from"./utils-BTuSbA5p.js";import{a as l,d as u,f as d,i as f,l as p,n as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./index-CXgd9jpl.js";import{i as x}from"./client-CwgDvMJw.js";import{a as S,c as C,i as w,n as T,o as E,r as D,s as O,t as k}from"./input-mze7gZ5r.js";function A(e){if(Array.isArray(e))return e.flatMap(e=>A(e));if(typeof e!=`string`)return[];let t=[],n=0,r,i,a,o,s,c=()=>{for(;n(i=e.charAt(n),i!==`=`&&i!==`;`&&i!==`,`);for(;n=e.length)&&t.push(e.slice(r))}return t}function j(e){return e instanceof Headers?e:Array.isArray(e)||typeof e==`object`?new Headers(e):null}function M(...e){return e.reduce((e,t)=>{let n=j(t);if(!n)return e;for(let[t,r]of n.entries())t===`set-cookie`?A(r).forEach(t=>e.append(`set-cookie`,t)):e.set(t,r);return e},new Headers)}var N=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),P=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),F=e=>{let t=P(e);return t.charAt(0).toUpperCase()+t.slice(1)},I=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),L=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0},R={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},z=e(r()),B=(0,z.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,z.createElement)(`svg`,{ref:c,...R,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:I(`lucide`,i),...!a&&!L(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,z.createElement)(e,t)),...Array.isArray(a)?a:[a]])),V=(e,t)=>{let n=(0,z.forwardRef)(({className:n,...r},i)=>(0,z.createElement)(B,{ref:i,iconNode:t,className:I(`lucide-${N(F(e))}`,`lucide-${e}`,n),...r}));return n.displayName=F(e),n},ee=V(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),H=V(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),te=V(`arrow-right`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),ne=V(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),re=V(`bot`,[[`path`,{d:`M12 8V4H8`,key:`hb8ula`}],[`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`,key:`enze0r`}],[`path`,{d:`M2 14h2`,key:`vft8re`}],[`path`,{d:`M20 14h2`,key:`4cs60a`}],[`path`,{d:`M15 13v2`,key:`1xurst`}],[`path`,{d:`M9 13v2`,key:`rq6x2g`}]]),U=V(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),ie=V(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),ae=V(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),W=V(`cloud-off`,[[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M5.782 5.782A7 7 0 0 0 9 19h8.5a4.5 4.5 0 0 0 1.307-.193`,key:`yfwify`}],[`path`,{d:`M21.532 16.5A4.5 4.5 0 0 0 17.5 10h-1.79A7.008 7.008 0 0 0 10 5.07`,key:`jlfiyv`}]]),oe=V(`cloud`,[[`path`,{d:`M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z`,key:`p7xjir`}]]),se=V(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),ce=V(`copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),le=V(`download`,[[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`polyline`,{points:`7 10 12 15 17 10`,key:`2ggqvy`}],[`line`,{x1:`12`,x2:`12`,y1:`15`,y2:`3`,key:`1vk2je`}]]),ue=V(`ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),de=V(`eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),fe=V(`file-down`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M12 18v-6`,key:`17g6i2`}],[`path`,{d:`m9 15 3 3 3-3`,key:`1npd3o`}]]),pe=V(`file-text`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),me=V(`folder-input`,[[`path`,{d:`M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1`,key:`fm4g5t`}],[`path`,{d:`M2 13h10`,key:`pgb2dq`}],[`path`,{d:`m9 16 3-3-3-3`,key:`6m91ic`}]]),he=V(`folder-open`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),ge=V(`folder-output`,[[`path`,{d:`M2 7.5V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-1.5`,key:`1yk7aj`}],[`path`,{d:`M2 13h10`,key:`pgb2dq`}],[`path`,{d:`m5 10-3 3 3 3`,key:`1r8ie0`}]]),_e=V(`folder-plus`,[[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`M9 13h6`,key:`1uhe8q`}],[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),ve=V(`grip-vertical`,[[`circle`,{cx:`9`,cy:`12`,r:`1`,key:`1vctgf`}],[`circle`,{cx:`9`,cy:`5`,r:`1`,key:`hp0tcf`}],[`circle`,{cx:`9`,cy:`19`,r:`1`,key:`fkjjf6`}],[`circle`,{cx:`15`,cy:`12`,r:`1`,key:`1tmaij`}],[`circle`,{cx:`15`,cy:`5`,r:`1`,key:`19l28e`}],[`circle`,{cx:`15`,cy:`19`,r:`1`,key:`f4zoj3`}]]),ye=V(`hard-drive`,[[`line`,{x1:`22`,x2:`2`,y1:`12`,y2:`12`,key:`1y58io`}],[`path`,{d:`M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z`,key:`oot6mr`}],[`line`,{x1:`6`,x2:`6.01`,y1:`16`,y2:`16`,key:`sgf278`}],[`line`,{x1:`10`,x2:`10.01`,y1:`16`,y2:`16`,key:`1l4acy`}]]),be=V(`heading-1`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`m17 12 3-2v8`,key:`1hhhft`}]]),xe=V(`heading-2`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1`,key:`9jr5yi`}]]),Se=V(`heading-3`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2`,key:`68ncm8`}],[`path`,{d:`M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2`,key:`1ejuhz`}]]),Ce=V(`image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),we=V(`link-2`,[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]),Te=V(`list-ordered`,[[`path`,{d:`M10 12h11`,key:`6m4ad9`}],[`path`,{d:`M10 18h11`,key:`11hvi2`}],[`path`,{d:`M10 6h11`,key:`c7qv1k`}],[`path`,{d:`M4 10h2`,key:`16xx2s`}],[`path`,{d:`M4 6h1v4`,key:`cnovpq`}],[`path`,{d:`M6 18H4c0-1 2-2 2-3s-1-1.5-2-1`,key:`m9a95d`}]]),Ee=V(`list-todo`,[[`rect`,{x:`3`,y:`5`,width:`6`,height:`6`,rx:`1`,key:`1defrl`}],[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`path`,{d:`M13 6h8`,key:`15sg57`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 18h8`,key:`oe0vm4`}]]),De=V(`list-tree`,[[`path`,{d:`M21 12h-8`,key:`1bmf0i`}],[`path`,{d:`M21 6H8`,key:`1pqkrb`}],[`path`,{d:`M21 18h-8`,key:`1tm79t`}],[`path`,{d:`M3 6v4c0 1.1.9 2 2 2h3`,key:`1ywdgy`}],[`path`,{d:`M3 10v6c0 1.1.9 2 2 2h3`,key:`2wc746`}]]),Oe=V(`list`,[[`path`,{d:`M3 12h.01`,key:`nlz23k`}],[`path`,{d:`M3 18h.01`,key:`1tta3j`}],[`path`,{d:`M3 6h.01`,key:`1rqtza`}],[`path`,{d:`M8 12h13`,key:`1za7za`}],[`path`,{d:`M8 18h13`,key:`1lx6n3`}],[`path`,{d:`M8 6h13`,key:`ik3vkj`}]]),ke=V(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),Ae=V(`log-in`,[[`path`,{d:`M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4`,key:`u53s6r`}],[`polyline`,{points:`10 17 15 12 10 7`,key:`1ail0h`}],[`line`,{x1:`15`,x2:`3`,y1:`12`,y2:`12`,key:`v6grx8`}]]),je=V(`menu`,[[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 18h16`,key:`19g7jn`}],[`path`,{d:`M4 6h16`,key:`1o0s65`}]]),Me=V(`message-square`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}]]),Ne=V(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),Pe=V(`monitor`,[[`rect`,{width:`20`,height:`14`,x:`2`,y:`3`,rx:`2`,key:`48i651`}],[`line`,{x1:`8`,x2:`16`,y1:`21`,y2:`21`,key:`1svkeh`}],[`line`,{x1:`12`,x2:`12`,y1:`17`,y2:`21`,key:`vw1qmm`}]]),Fe=V(`moon`,[[`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`,key:`a7tn18`}]]),Ie=V(`panel-left-close`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`m16 15-3-3 3-3`,key:`14y99z`}]]),Le=V(`panel-left`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}]]),Re=V(`play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]),ze=V(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Be=V(`plug`,[[`path`,{d:`M12 22v-5`,key:`1ega77`}],[`path`,{d:`M9 8V2`,key:`14iosj`}],[`path`,{d:`M15 8V2`,key:`18g5xt`}],[`path`,{d:`M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z`,key:`osxo6l`}]]),Ve=V(`quote`,[[`path`,{d:`M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`rib7q0`}],[`path`,{d:`M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`1ymkrd`}]]),He=V(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Ue=V(`save`,[[`path`,{d:`M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,key:`1c8476`}],[`path`,{d:`M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7`,key:`1ydtos`}],[`path`,{d:`M7 3v4a1 1 0 0 0 1 1h7`,key:`t51u73`}]]),We=V(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Ge=V(`settings`,[[`path`,{d:`M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z`,key:`1qme2f`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),Ke=V(`sparkles`,[[`path`,{d:`M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z`,key:`4pj2yx`}],[`path`,{d:`M20 3v4`,key:`1olli1`}],[`path`,{d:`M22 5h-4`,key:`1gvqau`}],[`path`,{d:`M4 17v2`,key:`vumght`}],[`path`,{d:`M5 18H3`,key:`zchphs`}]]),qe=V(`square-check-big`,[[`path`,{d:`M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.5`,key:`1uzm8b`}],[`path`,{d:`m9 11 3 3L22 4`,key:`1pflzl`}]]),Je=V(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Ye=V(`star`,[[`path`,{d:`M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z`,key:`r04s7s`}]]),Xe=V(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Ze=V(`table-2`,[[`path`,{d:`M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18`,key:`gugj83`}]]),Qe=V(`terminal`,[[`polyline`,{points:`4 17 10 11 4 5`,key:`akl6gq`}],[`line`,{x1:`12`,x2:`20`,y1:`19`,y2:`19`,key:`q2wloq`}]]),$e=V(`trash-2`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6`,key:`4alrt4`}],[`path`,{d:`M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2`,key:`v07s0e`}],[`line`,{x1:`10`,x2:`10`,y1:`11`,y2:`17`,key:`1uufr5`}],[`line`,{x1:`14`,x2:`14`,y1:`11`,y2:`17`,key:`xtxkd`}]]),et=V(`type`,[[`polyline`,{points:`4 7 4 4 20 4 20 7`,key:`1nosan`}],[`line`,{x1:`9`,x2:`15`,y1:`20`,y2:`20`,key:`swin9y`}],[`line`,{x1:`12`,x2:`12`,y1:`4`,y2:`20`,key:`1tx1rr`}]]),tt=V(`unlink`,[[`path`,{d:`m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71`,key:`yqzxt4`}],[`path`,{d:`m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71`,key:`4qinb0`}],[`line`,{x1:`8`,x2:`8`,y1:`2`,y2:`5`,key:`1041cp`}],[`line`,{x1:`2`,x2:`5`,y1:`8`,y2:`8`,key:`14m1p5`}],[`line`,{x1:`16`,x2:`16`,y1:`19`,y2:`22`,key:`rzdirn`}],[`line`,{x1:`19`,x2:`22`,y1:`16`,y2:`16`,key:`ox905f`}]]),nt=V(`upload`,[[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`polyline`,{points:`17 8 12 3 7 8`,key:`t8dd8p`}],[`line`,{x1:`12`,x2:`12`,y1:`3`,y2:`15`,key:`widbto`}]]),rt=V(`wand-sparkles`,[[`path`,{d:`m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72`,key:`ul74o6`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`M5 6v4`,key:`ilb8ba`}],[`path`,{d:`M19 14v4`,key:`blhpug`}],[`path`,{d:`M10 2v2`,key:`7u0qdc`}],[`path`,{d:`M7 8H3`,key:`zfb6yr`}],[`path`,{d:`M21 16h-4`,key:`1cnmox`}],[`path`,{d:`M11 3H9`,key:`1obp7u`}]]),it=V(`wifi`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M2 8.82a15 15 0 0 1 20 0`,key:`dnpr2z`}],[`path`,{d:`M5 12.859a10 10 0 0 1 14 0`,key:`1x1e6c`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}]]),at=V(`workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]),ot=V(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),st=V(`zap`,[[`path`,{d:`M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z`,key:`1xq2db`}]]),ct=Object.defineProperty,lt=(e,t)=>ct(e,`name`,{value:t,configurable:!0}),ut=!!(typeof window<`u`&&window.document&&window.document.createElement);function G(e,t,{checkForDefaultPrevented:n=!0}={}){return lt(function(r){if(e?.(r),n===!1||!r||!r.defaultPrevented)return t?.(r)},`handleEvent`)}lt(G,`composeEventHandlers`);function dt(e){if(!ut)throw Error(`Cannot access window outside of the DOM`);return e?.ownerDocument?.defaultView??window}lt(dt,`getOwnerWindow`);function ft(e){if(!ut)throw Error(`Cannot access document outside of the DOM`);return e?.ownerDocument??document}lt(ft,`getOwnerDocument`);function pt(e,t=!1){let{activeElement:n}=ft(e);if(!n?.nodeName)return null;if(mt(n)&&n.contentDocument)return pt(n.contentDocument.body,t);if(t){let e=n.getAttribute(`aria-activedescendant`);if(e){let t=ft(n).getElementById(e);if(t)return t}}return n}lt(pt,`getActiveElement`);function mt(e){return e.tagName===`IFRAME`}lt(mt,`isFrame`);var K=c(),ht=Object.defineProperty,gt=(e,t)=>ht(e,`name`,{value:t,configurable:!0});function _t(e,t){let n=z.createContext(t);n.displayName=e+`Context`;let r=gt(e=>{let{children:t,...r}=e,i=z.useMemo(()=>r,Object.values(r));return(0,K.jsx)(n.Provider,{value:i,children:t})},`Provider`);r.displayName=e+`Provider`;function i(r,i={}){let{optional:a=!1}=i,o=z.useContext(n);if(o)return o;if(t!==void 0)return t;if(!a)throw Error(`\`${r}\` must be used within \`${e}\``)}return gt(i,`useContext`),[r,i]}gt(_t,`createContext`);function vt(e,t=[]){let n=[];function r(t,r){let i=z.createContext(r);i.displayName=t+`Context`;let a=n.length;n=[...n,r];let o=gt(t=>{let{scope:n,children:r,...o}=t,s=n?.[e]?.[a]||i,c=z.useMemo(()=>o,Object.values(o));return(0,K.jsx)(s.Provider,{value:c,children:r})},`Provider`);o.displayName=t+`Provider`;function s(n,o,s={}){let{optional:c=!1}=s,l=o?.[e]?.[a]||i,u=z.useContext(l);if(u)return u;if(r!==void 0)return r;if(!c)throw Error(`\`${n}\` must be used within \`${t}\``)}return gt(s,`useContext`),[o,s]}gt(r,`createContext`);let i=gt(()=>{let t=n.map(e=>z.createContext(e));return gt(function(n){let r=n?.[e]||t;return z.useMemo(()=>({[`__scope${e}`]:{...n,[e]:r}}),[n,r])},`useScope`)},`createScope`);return i.scopeName=e,[r,yt(i,...t)]}gt(vt,`createContextScope`);function yt(...e){let t=e[0];if(e.length===1)return t;let n=gt(()=>{let n=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return gt(function(e){let r=n.reduce((t,{useScope:n,scopeName:r})=>{let i=n(e)[`__scope${r}`];return{...t,...i}},{});return z.useMemo(()=>({[`__scope${t.scopeName}`]:r}),[r])},`useComposedScopes`)},`createScope`);return n.scopeName=t.scopeName,n}gt(yt,`composeContextScopes`);var bt=e(i(),1),xt=Object.defineProperty,St=(e,t)=>xt(e,`name`,{value:t,configurable:!0}),q=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`].reduce((e,t)=>{let n=S(`Primitive.${t}`),r=z.forwardRef((e,r)=>{let{asChild:i,...a}=e,o=i?n:t;return typeof window<`u`&&(window[Symbol.for(`radix-ui`)]=!0),(0,K.jsx)(o,{...a,ref:r})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Ct(e,t){e&&bt.flushSync(()=>e.dispatchEvent(t))}St(Ct,`dispatchDiscreteCustomEvent`);var wt=Object.defineProperty,Tt=(e,t)=>wt(e,`name`,{value:t,configurable:!0});function Et(e){let t=z.useRef(e);return z.useEffect(()=>{t.current=e}),z.useMemo(()=>((...e)=>t.current?.(...e)),[])}Tt(Et,`useCallbackRef`);var Dt=Object.defineProperty,J=(e,t)=>Dt(e,`name`,{value:t,configurable:!0}),Ot=`dismissableLayer.update`,kt=`dismissableLayer.pointerDownOutside`,At=`dismissableLayer.focusOutside`,jt,Mt=z.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Nt=z.forwardRef(J(function(e,t){let{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,u=z.useContext(Mt),[d,f]=z.useState(null),p=d?.ownerDocument??globalThis?.document,[,m]=z.useState({}),h=C(t,f),g=Array.from(u.layers),[_]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),v=_?g.indexOf(_):-1,y=d?g.indexOf(d):-1,b=u.layersWithOutsidePointerEventsDisabled.size>0,x=y>=v,S=z.useRef(!1),w=It(e=>{a?.(e),s?.(e),e.defaultPrevented||c?.()},{ownerDocument:p,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:S,dismissableSurfaces:u.dismissableSurfaces,shouldHandlePointerDownOutside:z.useCallback(e=>{if(!(e instanceof Node))return!1;let t=[...u.branches].some(t=>t.contains(e));return x&&!t},[u.branches,x])}),T=Lt(e=>{if(r&&S.current)return;let t=e.target;[...u.branches].some(e=>e.contains(t))||(o?.(e),s?.(e),e.defaultPrevented||c?.())},p),E=d?y===g.length-1:!1,D=Et(e=>{e.key===`Escape`&&(i?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))});return z.useEffect(()=>{if(E)return p.addEventListener(`keydown`,D,{capture:!0}),()=>p.removeEventListener(`keydown`,D,{capture:!0})},[p,E,D]),z.useEffect(()=>{if(d)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(jt=p.body.style.pointerEvents,p.body.style.pointerEvents=`none`),u.layersWithOutsidePointerEventsDisabled.add(d)),u.layers.add(d),Rt(),()=>{n&&(u.layersWithOutsidePointerEventsDisabled.delete(d),u.layersWithOutsidePointerEventsDisabled.size===0&&(p.body.style.pointerEvents=jt))}},[d,p,n,u]),z.useEffect(()=>()=>{d&&(u.layers.delete(d),u.layersWithOutsidePointerEventsDisabled.delete(d),Rt())},[d,u]),z.useEffect(()=>{let e=J(()=>m({}),`handleUpdate`);return document.addEventListener(Ot,e),()=>document.removeEventListener(Ot,e)},[]),(0,K.jsx)(q.div,{...l,ref:h,style:{pointerEvents:b?x?`auto`:`none`:void 0,...e.style},onFocusCapture:G(e.onFocusCapture,T.onFocusCapture),onBlurCapture:G(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:G(e.onPointerDownCapture,w.onPointerDownCapture)})},`DismissableLayer`));function Pt(){let e=z.useContext(Mt),[t,n]=z.useState(null);return z.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}J(Pt,`useDismissableLayerSurface`);var Ft=J(()=>!0,`IS_TRUE`);function It(e,t){let{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:o=Ft}=t,s=Et(e),c=z.useRef(!1),l=z.useRef(!1),u=z.useRef(new Map),d=z.useRef(()=>{});return z.useEffect(()=>{function e(){l.current=!1,i.current=!1,u.current.clear()}J(e,`resetOutsideInteraction`);function t(){return Array.from(u.current.values()).some(Boolean)}J(t,`isOutsideInteractionIntercepted`);function f(e){if(!l.current)return;let t=e.target;t instanceof Node&&[...a].some(e=>e.contains(t))||u.current.set(e.type,!0),e.type===`click`&&window.setTimeout(()=>{l.current&&d.current()},0)}J(f,`handleInteractionCapture`);function p(e){l.current&&u.current.set(e.type,!1)}J(p,`handleInteractionBubble`);let m=J(a=>{if(a.target&&!c.current){let f=function(){n.removeEventListener(`click`,d.current);let r=t();e(),r||zt(kt,s,p,{discrete:!0})};if(J(f,`handleAndDispatchPointerDownOutsideEvent`),!o(a.target)){n.removeEventListener(`click`,d.current),e(),c.current=!1;return}let p={originalEvent:a};l.current=!0,i.current=r&&a.button===0,u.current.clear(),!r||a.button!==0?f():(n.removeEventListener(`click`,d.current),d.current=f,n.addEventListener(`click`,d.current,{once:!0}))}else n.removeEventListener(`click`,d.current),e();c.current=!1},`handlePointerDown`),h=[`pointerup`,`mousedown`,`mouseup`,`touchstart`,`touchend`,`click`];for(let e of h)n.addEventListener(e,f,!0),n.addEventListener(e,p);let g=window.setTimeout(()=>{n.addEventListener(`pointerdown`,m)},0);return()=>{window.clearTimeout(g),n.removeEventListener(`pointerdown`,m),n.removeEventListener(`click`,d.current);for(let e of h)n.removeEventListener(e,f,!0),n.removeEventListener(e,p)}},[n,s,r,i,a,o]),{onPointerDownCapture:J(()=>c.current=!0,`onPointerDownCapture`)}}J(It,`usePointerDownOutside`);function Lt(e,t=globalThis?.document){let n=Et(e),r=z.useRef(!1);return z.useEffect(()=>{let e=J(e=>{e.target&&!r.current&&zt(At,n,{originalEvent:e},{discrete:!1})},`handleFocus`);return t.addEventListener(`focusin`,e),()=>t.removeEventListener(`focusin`,e)},[t,n]),{onFocusCapture:J(()=>r.current=!0,`onFocusCapture`),onBlurCapture:J(()=>r.current=!1,`onBlurCapture`)}}J(Lt,`useFocusOutside`);function Rt(){let e=new CustomEvent(Ot);document.dispatchEvent(e)}J(Rt,`dispatchUpdate`);function zt(e,t,n,{discrete:r}){let i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Ct(i,a):i.dispatchEvent(a)}J(zt,`handleAndDispatchCustomEvent`);var Bt=globalThis?.document?z.useLayoutEffect:()=>{},Vt=Object.defineProperty,Ht=(e,t)=>Vt(e,`name`,{value:t,configurable:!0}),Ut=z.useId||(()=>void 0),Wt=0;function Y(e){let[t,n]=z.useState(Ut());return Bt(()=>{e||n(e=>e??String(Wt++))},[e]),e||(t?`radix-${t}`:``)}Ht(Y,`useId`);var Gt=[`top`,`right`,`bottom`,`left`],Kt=Math.min,qt=Math.max,Jt=Math.round,Yt=Math.floor,Xt=e=>({x:e,y:e}),Zt={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function Qt(e,t,n){return qt(e,Kt(t,n))}function $t(e,t){return typeof e==`function`?e(t):e}function en(e){return e.split(`-`)[0]}function tn(e){return e.split(`-`)[1]}function nn(e){return e===`x`?`y`:`x`}function rn(e){return e===`y`?`height`:`width`}function an(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function on(e){return nn(an(e))}function sn(e,t,n){n===void 0&&(n=!1);let r=tn(e),i=on(e),a=rn(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=gn(o)),[o,gn(o)]}function cn(e){let t=gn(e);return[ln(e),t,ln(t)]}function ln(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var un=[`left`,`right`],dn=[`right`,`left`],fn=[`top`,`bottom`],pn=[`bottom`,`top`];function mn(e,t,n){switch(e){case`top`:case`bottom`:return n?t?dn:un:t?un:dn;case`left`:case`right`:return t?fn:pn;default:return[]}}function hn(e,t,n,r){let i=tn(e),a=mn(en(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(ln)))),a}function gn(e){let t=en(e);return Zt[t]+e.slice(t.length)}function _n(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function vn(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:_n(e)}function yn(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function bn(e,t,n){let{reference:r,floating:i}=e,a=an(t),o=on(t),s=rn(o),c=en(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=tn(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function xn(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=$t(t,e),p=vn(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=yn(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=yn(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var Sn=50,Cn=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:xn},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=bn(l,r,c),f=r,p=0,m={};for(let n=0;n({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=$t(e,t)||{};if(l==null)return{};let d=vn(u),f={x:n,y:r},p=on(i),m=rn(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l)),C=S?S[y]:0;(!C||!await(o.isElement==null?void 0:o.isElement(S)))&&(C=s.floating[y]||a.floating[m]);let w=b/2-x/2,T=C/2-h[m]/2-1,E=Kt(d[_],T),D=Kt(d[v],T),O=C-h[m]-D,k=C/2-h[m]/2+w,A=Qt(E,k,O),j=!c.arrow&&tn(i)!=null&&k!==A&&a.reference[m]/2-(ke<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(!(u===`alignment`&&_!==an(t))||T.every(e=>an(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=an(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o;break}if(r!==n)return{reset:{placement:n}}}return{}}}};function En(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Dn(e){return Gt.some(t=>e[t]>=0)}var On=function(e){return e===void 0&&(e={}),{name:`hide`,options:e,async fn(t){let{rects:n,platform:r}=t,{strategy:i=`referenceHidden`,...a}=$t(e,t);switch(i){case`referenceHidden`:{let e=En(await r.detectOverflow(t,{...a,elementContext:`reference`}),n.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:Dn(e)}}}case`escaped`:{let e=En(await r.detectOverflow(t,{...a,altBoundary:!0}),n.floating);return{data:{escapedOffsets:e,escaped:Dn(e)}}}default:return{}}}}},kn=new Set([`left`,`top`]);async function An(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=en(n),s=tn(n),c=an(n)===`y`,l=kn.has(o)?-1:1,u=a&&c?-1:1,d=$t(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var jn=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await An(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},Mn=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=$t(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=an(i),p=nn(f),m=u[p],h=u[f],g=(e,t)=>Qt(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},Nn=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=$t(e,t),u={x:n,y:r},d=an(i),f=nn(d),p=u[f],m=u[d],h=$t(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;pn&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=kn.has(en(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);mr&&(m=r)}return{[f]:p,[d]:m}}}},Pn=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=$t(e,t),c=await i.detectOverflow(t,s),l=en(n),u=tn(n),d=an(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=Kt(p-c[m],g),y=Kt(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*qt(c.left,c.right):S=p-2*qt(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function Fn(){return typeof window<`u`}function In(e){return zn(e)?(e.nodeName||``).toLowerCase():`#document`}function Ln(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Rn(e){return((zn(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function zn(e){return Fn()?e instanceof Node||e instanceof Ln(e).Node:!1}function Bn(e){return Fn()?e instanceof Element||e instanceof Ln(e).Element:!1}function Vn(e){return Fn()?e instanceof HTMLElement||e instanceof Ln(e).HTMLElement:!1}function Hn(e){return!Fn()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof Ln(e).ShadowRoot}function Un(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=er(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function Wn(e){return/^(table|td|th)$/.test(In(e))}function Gn(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var Kn=/transform|translate|scale|rotate|perspective|filter/,qn=/paint|layout|strict|content/,Jn=e=>!!e&&e!==`none`,Yn;function Xn(e){let t=Bn(e)?er(e):e;return Jn(t.transform)||Jn(t.translate)||Jn(t.scale)||Jn(t.rotate)||Jn(t.perspective)||!Qn()&&(Jn(t.backdropFilter)||Jn(t.filter))||Kn.test(t.willChange||``)||qn.test(t.contain||``)}function Zn(e){let t=nr(e);for(;Vn(t)&&!$n(t);){if(Xn(t))return t;if(Gn(t))return null;t=nr(t)}return null}function Qn(){return Yn??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),Yn}function $n(e){return/^(html|body|#document)$/.test(In(e))}function er(e){return Ln(e).getComputedStyle(e)}function tr(e){return Bn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function nr(e){if(In(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||Hn(e)&&e.host||Rn(e);return Hn(t)?t.host:t}function rr(e){let t=nr(e);return $n(t)?(e.ownerDocument||e).body:Vn(t)&&Un(t)?t:rr(t)}function ir(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=rr(e),i=r===e.ownerDocument?.body,a=Ln(r);if(i){let e=ar(a);return t.concat(a,a.visualViewport||[],Un(r)?r:[],e&&n?ir(e):[])}else return t.concat(r,ir(r,[],n))}function ar(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function or(e){let t=er(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=Vn(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=Jt(n)!==a||Jt(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function sr(e){return Bn(e)?e:e.contextElement}function cr(e){let t=sr(e);if(!Vn(t))return Xt(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=or(t),o=(a?Jt(n.width):n.width)/r,s=(a?Jt(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var lr=Xt(0);function ur(e){let t=Ln(e);return!Qn()||!t.visualViewport?lr:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function dr(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Ln(e)}function fr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=sr(e),o=Xt(1);t&&(r?Bn(r)&&(o=cr(r)):o=cr(e));let s=dr(a,n,r)?ur(a):Xt(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=Ln(a),t=Bn(r)?Ln(r):r,n=e,i=ar(n);for(;i&&t!==n;){let e=cr(i),t=i.getBoundingClientRect(),r=er(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=Ln(i),i=ar(n)}}return yn({width:u,height:d,x:c,y:l})}function pr(e,t){let n=tr(e).scrollLeft;return t?t.left+n:fr(Rn(e)).left+n}function mr(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-pr(e,n),y:n.top+t.scrollTop}}function hr(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=Rn(r),s=t?Gn(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=Xt(1),u=Xt(0),d=Vn(r);if((d||!a)&&((In(r)!==`body`||Un(o))&&(c=tr(r)),d)){let e=fr(r);l=cr(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?mr(o,c):Xt(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function gr(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function _r(e){let t=tr(e),n=e.ownerDocument.body,r=qt(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=qt(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+pr(e),o=-t.scrollTop;return er(n).direction===`rtl`&&(a+=qt(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var vr=25;function yr(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=Ln(e),a=Rn(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!Qn()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(pr(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=vr&&(s-=o)}return{width:s,height:c,x:l,y:u}}function br(e,t){let n=fr(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=cr(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function xr(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=yr(e,n,t);else if(t===`document`)r=_r(Rn(e));else if(Bn(t))r=br(t,n);else{let n=ur(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return yn(r)}function Sr(e,t){let n=t.get(e);if(n)return n;let r=ir(e,[],!1).filter(e=>Bn(e)&&In(e)!==`body`),i=null,a=er(e).position===`fixed`,o=a?nr(e):e;for(;Bn(o)&&!$n(o);){let e=er(o),t=Xn(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=nr(o)}return t.set(e,r),r}function Cr(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?Gn(t)?[]:Sr(t,this._c):[].concat(n),r],o=xr(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=Ln(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function Pr(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=sr(e),u=i||a?[...l?ir(l):[],...t?ir(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?Nr(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?fr(e):null;c&&g();function g(){let t=fr(e);h&&!Mr(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var Fr=jn,Ir=Mn,Lr=Tn,Rr=Pn,zr=On,Br=wn,Vr=Nn,Hr=(e,t,n)=>{let r=new Map,i=n??{},a={...jr,...i.platform,_c:r};return Cn(e,t,{...i,platform:a})},Ur=typeof document<`u`?z.useLayoutEffect:function(){};function Wr(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e==`function`&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Wr(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!Wr(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function Gr(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Kr(e,t){let n=Gr(e);return Math.round(t*n)/n}function qr(e){let t=z.useRef(e);return Ur(()=>{t.current=e}),t}function Jr(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=z.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=z.useState(r);Wr(f,r)||p(r);let[m,h]=z.useState(null),[g,_]=z.useState(null),v=z.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=z.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=z.useRef(null),C=z.useRef(null),w=z.useRef(u),T=c!=null,E=qr(c),D=qr(i),O=qr(l),k=z.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),Hr(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};A.current&&!Wr(w.current,t)&&(w.current=t,bt.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);Ur(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let A=z.useRef(!1);Ur(()=>(A.current=!0,()=>{A.current=!1}),[]),Ur(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,k);k()}},[b,x,k,E,T]);let j=z.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),M=z.useMemo(()=>({reference:b,floating:x}),[b,x]),N=z.useMemo(()=>{let e={position:n,left:0,top:0};if(!M.floating)return e;let t=Kr(M.floating,u.x),r=Kr(M.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...Gr(M.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,M.floating,u.x,u.y]);return z.useMemo(()=>({...u,update:k,refs:j,elements:M,floatingStyles:N}),[u,k,j,M,N])}var Yr=e=>{function t(e){return{}.hasOwnProperty.call(e,`current`)}return{name:`arrow`,options:e,fn(n){let{element:r,padding:i}=typeof e==`function`?e(n):e;return r&&t(r)?r.current==null?{}:Br({element:r.current,padding:i}).fn(n):r?Br({element:r,padding:i}).fn(n):{}}}},Xr=(e,t)=>{let n=Fr(e);return{name:n.name,fn:n.fn,options:[e,t]}},Zr=(e,t)=>{let n=Ir(e);return{name:n.name,fn:n.fn,options:[e,t]}},Qr=(e,t)=>({fn:Vr(e).fn,options:[e,t]}),$r=(e,t)=>{let n=Lr(e);return{name:n.name,fn:n.fn,options:[e,t]}},ei=(e,t)=>{let n=Rr(e);return{name:n.name,fn:n.fn,options:[e,t]}},ti=(e,t)=>{let n=zr(e);return{name:n.name,fn:n.fn,options:[e,t]}},ni=(e,t)=>{let n=Yr(e);return{name:n.name,fn:n.fn,options:[e,t]}},ri=Object.defineProperty,ii=(e,t)=>ri(e,`name`,{value:t,configurable:!0});function ai(e){let[t,n]=z.useState(void 0);return Bt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});let t=new ResizeObserver(t=>{if(!Array.isArray(t)||!t.length)return;let r=t[0],i,a;if(`borderBoxSize`in r){let e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;i=t.inlineSize,a=t.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return t.observe(e,{box:`border-box`}),()=>t.unobserve(e)}else n(void 0)},[e]),t}ii(ai,`useSize`);var oi=Object.defineProperty,si=(e,t)=>oi(e,`name`,{value:t,configurable:!0}),ci=`Popper`,[li,ui]=vt(ci),[di,fi]=li(ci),pi=si(e=>{let{__scopePopper:t,children:n}=e,[r,i]=z.useState(null),[a,o]=z.useState(void 0);return(0,K.jsx)(di,{scope:t,anchor:r,onAnchorChange:i,placementState:a,setPlacementState:o,children:n})},`Popper`),mi=`PopperAnchor`,hi=z.forwardRef(si(function(e,t){let{__scopePopper:n,virtualRef:r,...i}=e,a=fi(mi,n),o=z.useRef(null),s=a.onAnchorChange,c=C(t,z.useCallback(e=>{o.current=e,e&&s(e)},[s])),l=z.useRef(null);z.useEffect(()=>{if(!r)return;let e=l.current;l.current=r.current,e!==l.current&&s(l.current)});let u=a.placementState&&Si(a.placementState),d=u?.[0],f=u?.[1];return r?null:(0,K.jsx)(q.div,{"data-radix-popper-side":d,"data-radix-popper-align":f,...i,ref:c})},`PopperAnchor`)),gi=`PopperContent`,[_i,vi]=li(gi),yi=z.forwardRef(si(function(e,t){let{__scopePopper:n,side:r=`bottom`,sideOffset:i=0,align:a=`center`,alignOffset:o=0,arrowPadding:s=0,avoidCollisions:c=!0,collisionBoundary:l=[],collisionPadding:u=0,sticky:d=`partial`,hideWhenDetached:f=!1,updatePositionStrategy:p=`optimized`,onPlaced:m,...h}=e,g=fi(gi,n),[_,v]=z.useState(null),y=C(t,v),[b,x]=z.useState(null),S=ai(b),w=S?.width??0,T=S?.height??0,E=r+(a===`center`?``:`-`+a),D=typeof u==`number`?u:{top:0,right:0,bottom:0,left:0,...u},O=Array.isArray(l)?l:[l],k=O.length>0,A={padding:D,boundary:O.filter(bi),altBoundary:k},{refs:j,floatingStyles:M,placement:N,isPositioned:P,middlewareData:F}=Jr({strategy:`fixed`,placement:E,whileElementsMounted:si((...e)=>Pr(...e,{animationFrame:p===`always`}),`whileElementsMounted`),elements:{reference:g.anchor},middleware:[Xr({mainAxis:i+T,alignmentAxis:o}),c&&Zr({mainAxis:!0,crossAxis:!1,limiter:d===`partial`?Qr():void 0,...A}),c&&$r({...A}),ei({...A,apply:si(({elements:e,rects:t,availableWidth:n,availableHeight:r})=>{let{width:i,height:a}=t.reference,o=e.floating.style;o.setProperty(`--radix-popper-available-width`,`${n}px`),o.setProperty(`--radix-popper-available-height`,`${r}px`),o.setProperty(`--radix-popper-anchor-width`,`${i}px`),o.setProperty(`--radix-popper-anchor-height`,`${a}px`)},`apply`)}),b&&ni({element:b,padding:s}),xi({arrowWidth:w,arrowHeight:T}),f&&ti({strategy:`referenceHidden`,...A,boundary:k?A.boundary:void 0})]}),I=g.setPlacementState;Bt(()=>(I(N),()=>{I(void 0)}),[N,I]);let[L,R]=Si(N),B=Et(m);Bt(()=>{P&&B?.()},[P,B]);let V=F.arrow?.x,ee=F.arrow?.y,H=F.arrow?.centerOffset!==0,[te,ne]=z.useState();return Bt(()=>{_&&ne(window.getComputedStyle(_).zIndex)},[_]),(0,K.jsx)(`div`,{ref:j.setFloating,"data-radix-popper-content-wrapper":``,style:{...M,transform:P?M.transform:`translate(0, -200%)`,minWidth:`max-content`,zIndex:te,"--radix-popper-transform-origin":[F.transformOrigin?.x,F.transformOrigin?.y].join(` `),...F.hide?.referenceHidden&&{visibility:`hidden`,pointerEvents:`none`}},dir:e.dir,children:(0,K.jsx)(_i,{scope:n,placedSide:L,placedAlign:R,onArrowChange:x,arrowX:V,arrowY:ee,shouldHideArrow:H,children:(0,K.jsx)(q.div,{"data-side":L,"data-align":R,...h,ref:y,style:{...h.style,animation:P?h.style?.animation:`none`}})})})},`PopperContent`));function bi(e){return e!==null}si(bi,`isNotNull`);var xi=si(e=>({name:`transformOrigin`,options:e,fn(t){let{placement:n,rects:r,middlewareData:i}=t,a=i.arrow?.centerOffset!==0,o=a?0:e.arrowWidth,s=a?0:e.arrowHeight,[c,l]=Si(n),u={start:`0%`,center:`50%`,end:`100%`}[l],d=(i.arrow?.x??0)+o/2,f=(i.arrow?.y??0)+s/2,p=``,m=``;return c===`bottom`?(p=a?u:`${d}px`,m=`${-s}px`):c===`top`?(p=a?u:`${d}px`,m=`${r.floating.height+s}px`):c===`right`?(p=`${-s}px`,m=a?u:`${f}px`):c===`left`&&(p=`${r.floating.width+s}px`,m=a?u:`${f}px`),{data:{x:p,y:m}}}}),`transformOrigin`);function Si(e){let[t,n=`center`]=e.split(`-`);return[t,n]}si(Si,`getSideAndAlignFromPlacement`);var Ci=Object.defineProperty,wi=z.forwardRef(((e,t)=>Ci(e,`name`,{value:t,configurable:!0}))(function(e,t){let{container:n,...r}=e,[i,a]=z.useState(!1);Bt(()=>a(!0),[]);let o=n||i&&globalThis?.document?.body;return o?bt.createPortal((0,K.jsx)(q.div,{...r,ref:t}),o):null},`Portal`)),Ti=Object.defineProperty,Ei=(e,t)=>Ti(e,`name`,{value:t,configurable:!0});function Di(e,t){return z.useReducer((e,n)=>t[e][n]??e,e)}Ei(Di,`useStateMachine`);var Oi=Ei(e=>{let{present:t,children:n}=e,r=ki(t),i=typeof n==`function`?n({present:r.isPresent}):z.Children.only(n),a=ji(r.ref,Ni(i));return typeof n==`function`||r.isPresent?z.cloneElement(i,{ref:a}):null},`Presence`);function ki(e){let[t,n]=z.useState(),r=z.useRef(null),i=z.useRef(e),a=z.useRef(`none`),o=z.useRef(void 0),[s,c]=Di(e?`mounted`:`unmounted`,{mounted:{UNMOUNT:`unmounted`,ANIMATION_OUT:`unmountSuspended`},unmountSuspended:{MOUNT:`mounted`,ANIMATION_END:`unmounted`},unmounted:{MOUNT:`mounted`}});return z.useEffect(()=>{s===`mounted`?(a.current=o.current??Mi(r.current),o.current=void 0):a.current=`none`},[s]),Bt(()=>{let t=r.current,n=i.current;if(n!==e){let r=a.current,s=Mi(t);e?(o.current=s,c(`MOUNT`)):s===`none`||t?.display===`none`?c(`UNMOUNT`):c(n&&r!==s?`ANIMATION_OUT`:`UNMOUNT`),i.current=e}},[e,c]),Bt(()=>{if(t){let e,n=t.ownerDocument.defaultView??window,o=Ei(a=>{let o=Mi(r.current).includes(CSS.escape(a.animationName));if(a.target===t&&o&&(c(`ANIMATION_END`),!i.current)){let r=t.style.animationFillMode;t.style.animationFillMode=`forwards`,e=n.setTimeout(()=>{t.style.animationFillMode===`forwards`&&(t.style.animationFillMode=r)})}},`handleAnimationEnd`),s=Ei(e=>{e.target===t&&(a.current=Mi(r.current))},`handleAnimationStart`);return t.addEventListener(`animationstart`,s),t.addEventListener(`animationcancel`,o),t.addEventListener(`animationend`,o),()=>{n.clearTimeout(e),t.removeEventListener(`animationstart`,s),t.removeEventListener(`animationcancel`,o),t.removeEventListener(`animationend`,o)}}else c(`ANIMATION_END`)},[t,c]),{isPresent:[`mounted`,`unmountSuspended`].includes(s),ref:z.useCallback(e=>{if(e){let t=getComputedStyle(e);r.current=t,o.current=Mi(t)}else r.current=null;n(e)},[])}}Ei(ki,`usePresence`);function Ai(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}Ei(Ai,`setRef`);function ji(...e){let t=z.useRef(e);return t.current=e,z.useCallback(e=>{let n=t.current,r=!1,i=n.map(t=>{let n=Ai(t,e);return!r&&typeof n==`function`&&(r=!0),n});if(r)return()=>{for(let e=0;ePi(e,`name`,{value:t,configurable:!0}),Ii=z.useEffectEvent,Li=z.useInsertionEffect;function Ri(e){if(typeof Ii==`function`)return Ii(e);let t=z.useRef(()=>{throw Error(`Cannot call an event handler while rendering.`)});return typeof Li==`function`?Li(()=>{t.current=e}):Bt(()=>{t.current=e}),z.useMemo(()=>((...e)=>t.current?.(...e)),[])}Fi(Ri,`useEffectEvent`);var zi=Object.defineProperty,Bi=(e,t)=>zi(e,`name`,{value:t,configurable:!0}),Vi=z.useInsertionEffect||Bt;function Hi({prop:e,defaultProp:t,onChange:n=Bi(()=>{},`onChange`),caller:r}){let[i,a,o]=Ui({defaultProp:t,onChange:n}),s=e!==void 0;return[s?e:i,z.useCallback(t=>{if(s){let n=Wi(t)?t(e):t;n!==e&&o.current?.(n)}else a(t)},[s,e,a,o])]}Bi(Hi,`useControllableState`);function Ui({defaultProp:e,onChange:t}){let[n,r]=z.useState(e),i=z.useRef(n),a=z.useRef(t);return Vi(()=>{a.current=t},[t]),z.useEffect(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}Bi(Ui,`useUncontrolledState`);function Wi(e){return typeof e==`function`}Bi(Wi,`isFunction`);var Gi=Symbol(`RADIX:SYNC_STATE`);function Ki(e,t,n,r){let{prop:i,defaultProp:a,onChange:o,caller:s}=t,c=i!==void 0,l=Ri(o),u=[{...n,state:a}];r&&u.push(r);let[d,f]=z.useReducer((t,n)=>{if(n.type===Gi)return{...t,state:n.state};let r=e(t,n);return c&&!Object.is(r.state,t.state)&&l(r.state),r},...u),p=d.state,m=z.useRef(p);z.useEffect(()=>{m.current!==p&&(m.current=p,c||l(p))},[p,m,c]);let h=z.useMemo(()=>i===void 0?d:{...d,state:i},[d,i]);return z.useEffect(()=>{c&&!Object.is(i,d.state)&&f({type:Gi,state:i})},[i,d.state,c]),[h,f]}Bi(Ki,`useControllableStateReducer`);var qi=Object.defineProperty,Ji=(e,t)=>qi(e,`name`,{value:t,configurable:!0}),[Yi,Xi]=vt(`Tooltip`,[ui]);ui();var Zi=`TooltipProvider`,Qi=700,[$i,ea]=Yi(Zi),ta=Ji(e=>{let{__scopeTooltip:t,delayDuration:n=Qi,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,o=z.useRef(!0),s=z.useRef(!1),c=z.useRef(0);return z.useEffect(()=>{let e=c.current;return()=>window.clearTimeout(e)},[]),(0,K.jsx)($i,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:z.useCallback(()=>{r<=0||(window.clearTimeout(c.current),o.current=!1)},[r]),onClose:z.useCallback(()=>{r<=0||(window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.current=!0,r))},[r]),isPointerInTransitRef:s,onPointerInTransitChange:z.useCallback(e=>{s.current=e},[]),disableHoverableContent:i,children:a})},`TooltipProvider`),[na,ra]=Yi(`Tooltip`),[ia,aa]=Yi(`TooltipPortal`,{forceMount:void 0});E(`TooltipContent`);function oa(e,t){let n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return`left`;case i:return`right`;case n:return`top`;case r:return`bottom`;default:throw Error(`unreachable`)}}Ji(oa,`getExitSideFromRect`);function sa(e,t,n=5){let r=[];switch(t){case`top`:r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case`bottom`:r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case`left`:r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case`right`:r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}Ji(sa,`getPaddedExitPoints`);function ca(e){let{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}Ji(ca,`getPointsFromRect`);function la(e,t){let{x:n,y:r}=e,i=!1;for(let e=0,a=t.length-1;er!=d>r&&n<(u-c)*(r-l)/(d-l)+c&&(i=!i)}return i}Ji(la,`isPointInPolygon`);function ua(e){let t=e.slice();return t.sort((e,t)=>e.xt.x?1:e.yt.y)),da(t)}Ji(ua,`getHull`);function da(e){if(e.length<=1)return e.slice();let t=[];for(let n=0;n=2;){let e=t[t.length-1],n=t[t.length-2];if((e.x-n.x)*(r.y-n.y)>=(e.y-n.y)*(r.x-n.x))t.pop();else break}t.push(r)}t.pop();let n=[];for(let t=e.length-1;t>=0;t--){let r=e[t];for(;n.length>=2;){let e=n[n.length-1],t=n[n.length-2];if((e.x-t.x)*(r.y-t.y)>=(e.y-t.y)*(r.x-t.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}Ji(da,`getHullPresorted`);function fa(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}Ji(fa,`concatAriaDescribedby`);var pa=ta,ma=Object.defineProperty,ha=(e,t)=>ma(e,`name`,{value:t,configurable:!0}),ga=z.createContext(void 0);function _a(e){let t=z.useContext(ga);return e||t||`ltr`}ha(_a,`useDirection`);var va=Object.defineProperty,ya=(e,t)=>va(e,`name`,{value:t,configurable:!0});function ba(e,[t,n]){return Math.min(n,Math.max(t,e))}ya(ba,`clamp`);var xa=Object.defineProperty,X=(e,t)=>xa(e,`name`,{value:t,configurable:!0});function Sa(e,t){return z.useReducer((e,n)=>t[e][n]??e,e)}X(Sa,`useStateMachine`);var Ca=`ScrollArea`,[wa,Ta]=vt(Ca),[Ea,Da]=wa(Ca),Oa=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,type:r=`hover`,dir:i,scrollHideDelay:a=600,...o}=e,[s,c]=z.useState(null),[l,u]=z.useState(null),[d,f]=z.useState(null),[p,m]=z.useState(null),[h,g]=z.useState(null),[_,v]=z.useState(0),[y,b]=z.useState(0),[x,S]=z.useState(!1),[w,T]=z.useState(!1),E=C(t,c),D=_a(i);return(0,K.jsx)(Ea,{scope:n,type:r,dir:D,scrollHideDelay:a,scrollArea:s,viewport:l,onViewportChange:u,content:d,onContentChange:f,scrollbarX:p,onScrollbarXChange:m,scrollbarXEnabled:x,onScrollbarXEnabledChange:S,scrollbarY:h,onScrollbarYChange:g,scrollbarYEnabled:w,onScrollbarYEnabledChange:T,onCornerWidthChange:v,onCornerHeightChange:b,children:(0,K.jsx)(q.div,{dir:D,...o,ref:E,style:{position:`relative`,"--radix-scroll-area-corner-width":_+`px`,"--radix-scroll-area-corner-height":y+`px`,...e.style}})})},`ScrollArea`)),ka=`ScrollAreaViewport`,Aa=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,children:r,nonce:i,...a}=e,o=Da(ka,n),s=C(t,z.useRef(null),o.onViewportChange);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ja,{nonce:i}),(0,K.jsx)(q.div,{"data-radix-scroll-area-viewport":``,...a,ref:s,style:{overflowX:o.scrollbarXEnabled?`scroll`:`hidden`,overflowY:o.scrollbarYEnabled?`scroll`:`hidden`,...e.style},children:(0,K.jsx)(`div`,{ref:o.onContentChange,style:{minWidth:`100%`,display:`table`},children:r})})]})},`ScrollAreaViewport`)),ja=z.memo(X(function({nonce:e}){return(0,K.jsx)(`style`,{dangerouslySetInnerHTML:{__html:`[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}`},nonce:e})},`ScrollAreaViewportStyle`),(e,t)=>e.nonce===t.nonce),Ma=`ScrollAreaScrollbar`,Na=z.forwardRef(X(function(e,t){let{forceMount:n,...r}=e,i=Da(Ma,e.__scopeScrollArea),{onScrollbarXEnabledChange:a,onScrollbarYEnabledChange:o}=i,s=e.orientation===`horizontal`;return z.useEffect(()=>(s?a(!0):o(!0),()=>{s?a(!1):o(!1)}),[s,a,o]),i.type===`hover`?(0,K.jsx)(Pa,{...r,ref:t,forceMount:n}):i.type===`scroll`?(0,K.jsx)(Fa,{...r,ref:t,forceMount:n}):i.type===`auto`?(0,K.jsx)(Ia,{...r,ref:t,forceMount:n}):i.type===`always`?(0,K.jsx)(La,{...r,ref:t,"data-state":`visible`}):null},`ScrollAreaScrollbar`)),Pa=z.forwardRef(X(function(e,t){let{forceMount:n,...r}=e,i=Da(Ma,e.__scopeScrollArea),[a,o]=z.useState(!1);return z.useEffect(()=>{let e=i.scrollArea,t=0;if(e){let n=X(()=>{window.clearTimeout(t),o(!0)},`handlePointerEnter`),r=X(()=>{t=window.setTimeout(()=>o(!1),i.scrollHideDelay)},`handlePointerLeave`);return e.addEventListener(`pointerenter`,n),e.addEventListener(`pointerleave`,r),()=>{window.clearTimeout(t),e.removeEventListener(`pointerenter`,n),e.removeEventListener(`pointerleave`,r)}}},[i.scrollArea,i.scrollHideDelay]),(0,K.jsx)(Oi,{present:n||a,children:(0,K.jsx)(Ia,{"data-state":a?`visible`:`hidden`,...r,ref:t})})},`ScrollAreaScrollbarHover`)),Fa=z.forwardRef(X(function(e,t){let{forceMount:n,...r}=e,i=Da(Ma,e.__scopeScrollArea),a=e.orientation===`horizontal`,o=ro(()=>c(`SCROLL_END`),100),[s,c]=Sa(`hidden`,{hidden:{SCROLL:`scrolling`},scrolling:{SCROLL_END:`idle`,POINTER_ENTER:`interacting`},interacting:{SCROLL:`interacting`,POINTER_LEAVE:`idle`},idle:{HIDE:`hidden`,SCROLL:`scrolling`,POINTER_ENTER:`interacting`}});return z.useEffect(()=>{if(s===`idle`){let e=window.setTimeout(()=>c(`HIDE`),i.scrollHideDelay);return()=>window.clearTimeout(e)}},[s,i.scrollHideDelay,c]),z.useEffect(()=>{let e=i.viewport,t=a?`scrollLeft`:`scrollTop`;if(e){let n=e[t],r=X(()=>{let r=e[t];n!==r&&(c(`SCROLL`),o()),n=r},`handleScroll`);return e.addEventListener(`scroll`,r),()=>e.removeEventListener(`scroll`,r)}},[i.viewport,a,c,o]),(0,K.jsx)(Oi,{present:n||s!==`hidden`,children:(0,K.jsx)(La,{"data-state":s===`hidden`?`hidden`:`visible`,...r,ref:t,onPointerEnter:G(e.onPointerEnter,()=>c(`POINTER_ENTER`)),onPointerLeave:G(e.onPointerLeave,()=>c(`POINTER_LEAVE`))})})},`ScrollAreaScrollbarScroll`)),Ia=z.forwardRef(X(function(e,t){let n=Da(Ma,e.__scopeScrollArea),{forceMount:r,...i}=e,[a,o]=z.useState(!1),s=e.orientation===`horizontal`,c=ro(()=>{if(n.viewport){let e=n.viewport.offsetWidth0&&l<1,onThumbChange:X(e=>a.current=e,`onThumbChange`),onThumbPointerUp:X(()=>o.current=0,`onThumbPointerUp`),onThumbPointerDown:X(e=>o.current=e,`onThumbPointerDown`)};function d(e,t){return Qa(e,o.current,s,t)}return X(d,`getScrollPosition`),n===`horizontal`?(0,K.jsx)(Ra,{...u,ref:t,onThumbPositionChange:()=>{if(i.viewport&&a.current){let e=i.viewport.scrollLeft,t=$a(e,s,i.dir);a.current.style.transform=`translate3d(${t}px, 0, 0)`}},onWheelScroll:e=>{i.viewport&&(i.viewport.scrollLeft=e)},onDragScroll:e=>{i.viewport&&(i.viewport.scrollLeft=d(e,i.dir))}}):n===`vertical`?(0,K.jsx)(za,{...u,ref:t,onThumbPositionChange:()=>{if(i.viewport&&a.current){let e=i.viewport.scrollTop,t=$a(e,s);a.current.style.transform=`translate3d(0, ${t}px, 0)`}},onWheelScroll:e=>{i.viewport&&(i.viewport.scrollTop=e)},onDragScroll:e=>{i.viewport&&(i.viewport.scrollTop=d(e))}}):null},`ScrollAreaScrollbarVisible`)),Ra=z.forwardRef(X(function(e,t){let{sizes:n,onSizesChange:r,...i}=e,a=Da(Ma,e.__scopeScrollArea),[o,s]=z.useState(),c=z.useRef(null),l=C(t,c,a.onScrollbarXChange);return z.useEffect(()=>{c.current&&s(getComputedStyle(c.current))},[c]),(0,K.jsx)(Ha,{"data-orientation":`horizontal`,...i,ref:l,sizes:n,style:{bottom:0,left:a.dir===`rtl`?`var(--radix-scroll-area-corner-width)`:0,right:a.dir===`ltr`?`var(--radix-scroll-area-corner-width)`:0,"--radix-scroll-area-thumb-width":Za(n)+`px`,...e.style},onThumbPointerDown:t=>e.onThumbPointerDown(t.x),onDragScroll:t=>e.onDragScroll(t.x),onWheelScroll:(t,n)=>{if(a.viewport){let r=a.viewport.scrollLeft+t.deltaX;e.onWheelScroll(r),to(r,n)&&t.preventDefault()}},onResize:()=>{c.current&&a.viewport&&o&&r({content:a.viewport.scrollWidth,viewport:a.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:Ya(o.paddingLeft),paddingEnd:Ya(o.paddingRight)}})}})},`ScrollAreaScrollbarX`)),za=z.forwardRef(X(function(e,t){let{sizes:n,onSizesChange:r,...i}=e,a=Da(Ma,e.__scopeScrollArea),[o,s]=z.useState(),c=z.useRef(null),l=C(t,c,a.onScrollbarYChange);return z.useEffect(()=>{c.current&&s(getComputedStyle(c.current))},[c]),(0,K.jsx)(Ha,{"data-orientation":`vertical`,...i,ref:l,sizes:n,style:{top:0,right:a.dir===`ltr`?0:void 0,left:a.dir===`rtl`?0:void 0,bottom:`var(--radix-scroll-area-corner-height)`,"--radix-scroll-area-thumb-height":Za(n)+`px`,...e.style},onThumbPointerDown:t=>e.onThumbPointerDown(t.y),onDragScroll:t=>e.onDragScroll(t.y),onWheelScroll:(t,n)=>{if(a.viewport){let r=a.viewport.scrollTop+t.deltaY;e.onWheelScroll(r),to(r,n)&&t.preventDefault()}},onResize:()=>{c.current&&a.viewport&&o&&r({content:a.viewport.scrollHeight,viewport:a.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:Ya(o.paddingTop),paddingEnd:Ya(o.paddingBottom)}})}})},`ScrollAreaScrollbarY`)),[Ba,Va]=wa(Ma),Ha=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,sizes:r,hasThumb:i,onThumbChange:a,onThumbPointerUp:o,onThumbPointerDown:s,onThumbPositionChange:c,onDragScroll:l,onWheelScroll:u,onResize:d,...f}=e,p=Da(Ma,n),[m,h]=z.useState(null),g=C(t,h),_=z.useRef(null),v=z.useRef(``),y=p.viewport,b=r.content-r.viewport,x=Et(u),S=Et(c),w=ro(d,10);function T(e){if(_.current){let t=e.clientX-_.current.left,n=e.clientY-_.current.top;l({x:t,y:n})}}return X(T,`handleDragScroll`),z.useEffect(()=>{let e=X(e=>{let t=e.target;m?.contains(t)&&x(e,b)},`handleWheel`);return document.addEventListener(`wheel`,e,{passive:!1}),()=>document.removeEventListener(`wheel`,e,{passive:!1})},[y,m,b,x]),z.useEffect(S,[r,S]),io(m,w),io(p.content,w),(0,K.jsx)(Ba,{scope:n,scrollbar:m,hasThumb:i,onThumbChange:Et(a),onThumbPointerUp:Et(o),onThumbPositionChange:S,onThumbPointerDown:Et(s),children:(0,K.jsx)(q.div,{...f,ref:g,style:{position:`absolute`,...f.style},onPointerDown:G(e.onPointerDown,e=>{e.button===0&&(e.target.setPointerCapture(e.pointerId),_.current=m.getBoundingClientRect(),v.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect=`none`,p.viewport&&(p.viewport.style.scrollBehavior=`auto`),T(e))}),onPointerMove:G(e.onPointerMove,T),onPointerUp:G(e.onPointerUp,e=>{let t=e.target;t.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId),document.body.style.webkitUserSelect=v.current,p.viewport&&(p.viewport.style.scrollBehavior=``),_.current=null})})})},`ScrollAreaScrollbarImpl`)),Ua=`ScrollAreaThumb`,Wa=z.forwardRef(X(function(e,t){let{forceMount:n,...r}=e,i=Va(Ua,e.__scopeScrollArea);return(0,K.jsx)(Oi,{present:n||i.hasThumb,children:(0,K.jsx)(Ga,{ref:t,...r})})},`ScrollAreaThumb`)),Ga=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,style:r,...i}=e,a=Da(Ua,n),o=Va(Ua,n),{onThumbPositionChange:s}=o,c=C(t,o.onThumbChange),l=z.useRef(void 0),u=ro(()=>{l.current&&=(l.current(),void 0)},100);return z.useEffect(()=>{let e=a.viewport;if(e){let t=X(()=>{if(u(),!l.current){let t=no(e,s);l.current=t,s()}},`handleScroll`);return s(),e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)}},[a.viewport,u,s]),(0,K.jsx)(q.div,{"data-state":o.hasThumb?`visible`:`hidden`,...i,ref:c,style:{width:`var(--radix-scroll-area-thumb-width)`,height:`var(--radix-scroll-area-thumb-height)`,...r},onPointerDownCapture:G(e.onPointerDownCapture,e=>{let t=e.target.getBoundingClientRect(),n=e.clientX-t.left,r=e.clientY-t.top;o.onThumbPointerDown({x:n,y:r})}),onPointerUp:G(e.onPointerUp,o.onThumbPointerUp)})},`ScrollAreaThumbImpl`)),Ka=`ScrollAreaCorner`,qa=z.forwardRef(X(function(e,t){let n=Da(Ka,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!==`scroll`&&r?(0,K.jsx)(Ja,{...e,ref:t}):null},`ScrollAreaCorner`)),Ja=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,...r}=e,i=Da(Ka,n),[a,o]=z.useState(0),[s,c]=z.useState(0),l=!!(a&&s),{onCornerWidthChange:u,onCornerHeightChange:d}=i;return io(i.scrollbarX,()=>{let e=i.scrollbarX?.offsetHeight||0;i.onCornerHeightChange(e),c(e)}),io(i.scrollbarY,()=>{let e=i.scrollbarY?.offsetWidth||0;i.onCornerWidthChange(e),o(e)}),z.useEffect(()=>()=>{u(0),d(0)},[u,d]),l?(0,K.jsx)(q.div,{...r,ref:t,style:{width:a,height:s,position:`absolute`,right:i.dir===`ltr`?0:void 0,left:i.dir===`rtl`?0:void 0,bottom:0,...e.style}}):null},`ScrollAreaCornerImpl`));function Ya(e){return e?parseInt(e,10):0}X(Ya,`toInt`);function Xa(e,t){let n=e/t;return isNaN(n)?0:n}X(Xa,`getThumbRatio`);function Za(e){let t=Xa(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}X(Za,`getThumbSize`);function Qa(e,t,n,r=`ltr`){let i=Za(n),a=i/2,o=t||a,s=i-o,c=n.scrollbar.paddingStart+o,l=n.scrollbar.size-n.scrollbar.paddingEnd-s,u=n.content-n.viewport,d=r===`ltr`?[0,u]:[u*-1,0];return eo([c,l],d)(e)}X(Qa,`getScrollPositionFromPointer`);function $a(e,t,n=`ltr`){let r=Za(t),i=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,a=t.scrollbar.size-i,o=t.content-t.viewport,s=a-r,c=ba(e,n===`ltr`?[0,o]:[o*-1,0]);return eo([0,o],[0,s])(c)}X($a,`getThumbOffsetFromScroll`);function eo(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];let r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}X(eo,`linearScale`);function to(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return X((function i(){let a={left:e.scrollLeft,top:e.scrollTop},o=n.left!==a.left,s=n.top!==a.top;(o||s)&&t(),n=a,r=window.requestAnimationFrame(i)}),`loop`)(),()=>window.cancelAnimationFrame(r)},`addUnlinkedScrollListener`);function ro(e,t){let n=Et(e),r=z.useRef(0);return z.useEffect(()=>()=>window.clearTimeout(r.current),[]),z.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}X(ro,`useDebounceCallback`);function io(e,t){let n=Et(t);Bt(()=>{let t=0;if(e){let r=new ResizeObserver(()=>{cancelAnimationFrame(t),t=window.requestAnimationFrame(n)});return r.observe(e),()=>{window.cancelAnimationFrame(t),r.unobserve(e)}}},[e,n])}X(io,`useResizeObserver`);function ao({className:e,children:t,...n}){return(0,K.jsxs)(Oa,{className:s(`relative overflow-hidden`,e),...n,children:[(0,K.jsx)(Aa,{className:`h-full w-full rounded-[inherit]`,children:t}),(0,K.jsx)(oo,{}),(0,K.jsx)(qa,{})]})}function oo({className:e,orientation:t=`vertical`,...n}){return(0,K.jsx)(Na,{orientation:t,className:s(`flex touch-none select-none transition-colors`,t===`vertical`&&`h-full w-2 border-l border-l-transparent p-px`,t===`horizontal`&&`h-2 flex-col border-t border-t-transparent p-px`,e),...n,children:(0,K.jsx)(Wa,{className:`relative flex-1 rounded-full bg-border`})})}var so=Object.defineProperty,Z=(e,t)=>so(e,`name`,{value:t,configurable:!0});function co(e){let t=e+`CollectionProvider`,[n,r]=vt(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=Z(e=>{let{scope:t,children:n}=e,r=z.useRef(null),a=z.useRef(new Map).current;return(0,K.jsx)(i,{scope:t,itemMap:a,collectionRef:r,children:n})},`CollectionProvider`);o.displayName=t;let s=e+`CollectionSlot`,c=S(s),l=z.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=C(t,a(s,n).collectionRef);return(0,K.jsx)(c,{ref:i,children:r})});l.displayName=s;let u=e+`CollectionItemSlot`,d=`data-radix-collection-item`,f=S(u),p=z.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=z.useRef(null),s=C(t,o),c=a(u,n);return z.useEffect(()=>(c.itemMap.set(o,{ref:o,...i}),()=>void c.itemMap.delete(o))),(0,K.jsx)(f,{[d]:``,ref:s,children:r})});p.displayName=u;function m(t){let n=a(e+`CollectionConsumer`,t);return z.useCallback(()=>{let e=n.collectionRef.current;if(!e)return[];let t=Array.from(e.querySelectorAll(`[${d}]`));return Array.from(n.itemMap.values()).sort((e,n)=>t.indexOf(e.ref.current)-t.indexOf(n.ref.current))},[n.collectionRef,n.itemMap])}return Z(m,`useCollection`),[{Provider:o,Slot:l,ItemSlot:p},m,r]}Z(co,`createCollection`);var lo=new WeakMap,uo=class e extends Map{static{Z(this,`OrderedDict`)}#e;constructor(e){super(e),this.#e=[...super.keys()],lo.set(this,!0)}set(e,t){return lo.get(this)&&(this.has(e)?this.#e[this.#e.indexOf(e)]=e:this.#e.push(e)),super.set(e,t),this}insert(e,t,n){let r=this.has(t),i=this.#e.length,a=mo(e),o=a>=0?a:i+a,s=o<0||o>=i?-1:o;if(s===this.size||r&&s===this.size-1||s===-1)return this.set(t,n),this;let c=this.size+ +!r;a<0&&o++;let l=[...this.#e],u,d=!1;for(let e=o;e=this.size&&(r=this.size-1),this.at(r)}keyFrom(e,t){let n=this.indexOf(e);if(n===-1)return;let r=n+t;return r<0&&(r=0),r>=this.size&&(r=this.size-1),this.keyAt(r)}find(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return r;n++}}findIndex(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return n;n++}return-1}filter(t,n){let r=[],i=0;for(let e of this)Reflect.apply(t,n,[e,i,this])&&r.push(e),i++;return new e(r)}map(t,n){let r=[],i=0;for(let e of this)r.push([e[0],Reflect.apply(t,n,[e,i,this])]),i++;return new e(r)}reduce(...e){let[t,n]=e,r=0,i=n??this.at(0);for(let n of this)i=r===0&&e.length===1?n:Reflect.apply(t,this,[i,n,r,this]),r++;return i}reduceRight(...e){let[t,n]=e,r=n??this.at(-1);for(let n=this.size-1;n>=0;n--){let i=this.at(n);r=n===this.size-1&&e.length===1?i:Reflect.apply(t,this,[r,i,n,this])}return r}toSorted(t){let n=[...this.entries()].sort(t);return new e(n)}toReversed(){let t=new e;for(let e=this.size-1;e>=0;e--){let n=this.keyAt(e),r=this.get(n);t.set(n,r)}return t}toSpliced(...t){let n=[...this.entries()];return n.splice(...t),new e(n)}slice(t,n){let r=new e,i=this.size-1;if(t===void 0)return r;t<0&&(t+=this.size),n!==void 0&&n>0&&(i=n-1);for(let e=t;e<=i;e++){let t=this.keyAt(e),n=this.get(t);r.set(t,n)}return r}every(e,t){let n=0;for(let r of this){if(!Reflect.apply(e,t,[r,n,this]))return!1;n++}return!0}some(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return!0;n++}return!1}};function fo(e,t){if(`at`in Array.prototype)return Array.prototype.at.call(e,t);let n=po(e,t);return n===-1?void 0:e[n]}Z(fo,`at`);function po(e,t){let n=e.length,r=mo(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}Z(po,`toSafeIndex`);function mo(e){return e!==e||e===0?0:Math.trunc(e)}Z(mo,`toSafeInteger`);function ho(e){let t=e+`CollectionProvider`,[n,r]=vt(t),[i,a]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new uo,setItemMap:Z(()=>void 0,`setItemMap`)}),o=Z(({state:e,...t})=>e?(0,K.jsx)(c,{...t,state:e}):(0,K.jsx)(s,{...t}),`CollectionProvider`);o.displayName=t;let s=Z(e=>{let t=h();return(0,K.jsx)(c,{...e,state:t})},`CollectionInit`);s.displayName=t+`Init`;let c=Z(e=>{let{scope:t,children:n,state:r}=e,a=z.useRef(null),[o,s]=z.useState(null),c=C(a,s),[l,u]=r;return z.useEffect(()=>{if(!o)return;let e=yo(()=>{});return e.observe(o,{childList:!0,subtree:!0}),()=>{e.disconnect()}},[o]),(0,K.jsx)(i,{scope:t,itemMap:l,setItemMap:u,collectionRef:c,collectionRefObject:a,collectionElement:o,children:n})},`CollectionProviderImpl`);c.displayName=t+`Impl`;let l=e+`CollectionSlot`,u=S(l),d=z.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=C(t,a(l,n).collectionRef);return(0,K.jsx)(u,{ref:i,children:r})});d.displayName=l;let f=e+`CollectionItemSlot`,p=S(f),m=z.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=z.useRef(null),[s,c]=z.useState(null),l=C(t,o,c),{setItemMap:u}=a(f,n),d=z.useRef(i);go(d.current,i)||(d.current=i);let m=d.current;return z.useEffect(()=>{let e=m;return u(t=>s?t.has(s)?t.set(s,{...e,element:s}).toSorted(vo):(t.set(s,{...e,element:s}),t.toSorted(vo)):t),()=>{u(e=>!s||!e.has(s)?e:(e.delete(s),new uo(e)))}},[s,m,u]),(0,K.jsx)(p,{"data-radix-collection-item":``,ref:l,children:r})});m.displayName=f;function h(){return z.useState(new uo)}Z(h,`useInitCollection`);function g(t){let{itemMap:n}=a(e+`CollectionConsumer`,t);return n}return Z(g,`useCollection`),[{Provider:o,Slot:d,ItemSlot:m},{createCollectionScope:r,useCollection:g,useInitCollection:h}]}Z(ho,`createCollection`);function go(e,t){if(e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e==null||t==null)return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||e[r]!==t[r])return!1;return!0}Z(go,`shallowEqual`);function _o(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}Z(_o,`isElementPreceding`);function vo(e,t){return!e[1].element||!t[1].element?0:_o(e[1].element,t[1].element)?-1:1}Z(vo,`sortByDocumentPosition`);function yo(e){return new MutationObserver(t=>{for(let n of t)if(n.type===`childList`){e();return}})}Z(yo,`getChildListObserver`);var bo=Object.defineProperty,xo=(e,t)=>bo(e,`name`,{value:t,configurable:!0}),So=0,Co=null;function wo(e){return To(),e.children}xo(wo,`FocusGuards`);function To(){z.useEffect(()=>{Co||={start:Eo(),end:Eo()};let{start:e,end:t}=Co;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement(`afterbegin`,e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement(`beforeend`,t),So++,()=>{So===1&&(Co?.start.remove(),Co?.end.remove(),Co=null),So=Math.max(0,So-1)}},[])}xo(To,`useFocusGuards`);function Eo(){let e=document.createElement(`span`);return e.setAttribute(`data-radix-focus-guard`,``),e.tabIndex=0,e.style.outline=`none`,e.style.opacity=`0`,e.style.position=`fixed`,e.style.pointerEvents=`none`,e}xo(Eo,`createFocusGuard`);var Do=Object.defineProperty,Oo=(e,t)=>Do(e,`name`,{value:t,configurable:!0}),ko=`focusScope.autoFocusOnMount`,Ao=`focusScope.autoFocusOnUnmount`,jo={bubbles:!1,cancelable:!0},Mo=z.forwardRef(Oo(function(e,t){let{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...o}=e,[s,c]=z.useState(null),l=Et(i),u=Et(a),d=z.useRef(null),f=C(t,c),p=z.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;z.useEffect(()=>{if(r){let e=function(e){if(p.paused||!s)return;let t=e.target;s.contains(t)?d.current=t:zo(d.current,{select:!0})},t=function(e){if(p.paused||!s)return;let t=e.relatedTarget;t!==null&&(s.contains(t)||zo(d.current,{select:!0}))},n=function(e){if(document.activeElement===document.body)for(let t of e)t.removedNodes.length>0&&zo(s)};Oo(e,`handleFocusIn`),Oo(t,`handleFocusOut`),Oo(n,`handleMutations`),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t);let r=new MutationObserver(n);return s&&r.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t),r.disconnect()}}},[r,s,p.paused]),z.useEffect(()=>{if(s){Bo.add(p);let e=document.activeElement;if(!s.contains(e)){let t=new CustomEvent(ko,jo);s.addEventListener(ko,l),s.dispatchEvent(t),t.defaultPrevented||(No(Uo(Fo(s)),{select:!0}),document.activeElement===e&&zo(s))}return()=>{s.removeEventListener(ko,l),setTimeout(()=>{let t=new CustomEvent(Ao,jo);s.addEventListener(Ao,u),s.dispatchEvent(t),t.defaultPrevented||zo(e??document.body,{select:!0}),s.removeEventListener(Ao,u),Bo.remove(p)},0)}}},[s,l,u,p]);let m=z.useCallback(e=>{if(!n&&!r||p.paused)return;let t=e.key===`Tab`&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){let t=e.currentTarget,[r,a]=Po(t);r&&a?!e.shiftKey&&i===a?(e.preventDefault(),n&&zo(r,{select:!0})):e.shiftKey&&i===r&&(e.preventDefault(),n&&zo(a,{select:!0})):i===t&&e.preventDefault()}},[n,r,p.paused]);return(0,K.jsx)(q.div,{tabIndex:-1,...o,ref:f,onKeyDown:m})},`FocusScope`));function No(e,{select:t=!1}={}){let n=document.activeElement;for(let r of e)if(zo(r,{select:t}),document.activeElement!==n)return}Oo(No,`focusFirst`);function Po(e){let t=Fo(e);return[Io(t,e),Io(t.reverse(),e)]}Oo(Po,`getTabbableEdges`);function Fo(e){let t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:Oo(e=>{let t=e.tagName===`INPUT`&&e.type===`hidden`;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},`acceptNode`)});for(;n.nextNode();)t.push(n.currentNode);return t}Oo(Fo,`getTabbableCandidates`);function Io(e,t){let n=typeof t.checkVisibility==`function`&&t.checkVisibility({checkVisibilityCSS:!0});for(let r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):Lo(r,{upTo:t})))return r}Oo(Io,`findVisible`);function Lo(e,{upTo:t}){if(getComputedStyle(e).visibility===`hidden`)return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display===`none`)return!0;e=e.parentElement}return!1}Oo(Lo,`isHidden`);function Ro(e){return e instanceof HTMLInputElement&&`select`in e}Oo(Ro,`isSelectableInput`);function zo(e,{select:t=!1}={}){if(e&&e.focus){let n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Ro(e)&&t&&e.select()}}Oo(zo,`focus`);var Bo=Vo();function Vo(){let e=[];return{add(t){let n=e[0];t!==n&&n?.pause(),e=Ho(e,t),e.unshift(t)},remove(t){e=Ho(e,t),e[0]?.resume()}}}Oo(Vo,`createFocusScopesStack`);function Ho(e,t){let n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}Oo(Ho,`arrayRemove`);function Uo(e){return e.filter(e=>e.tagName!==`A`)}Oo(Uo,`removeLinks`);var Wo=Object.defineProperty,Go=(e,t)=>Wo(e,`name`,{value:t,configurable:!0}),Ko=!1;function qo(){let[e,t]=z.useState(Ko);return z.useEffect(()=>{Ko||(Ko=!0,t(!0))},[]),e}Go(qo,`useIsHydrated`);var Jo=z.useSyncExternalStore;function Yo(){return()=>{}}Go(Yo,`subscribe`);function Xo(){return Jo(Yo,()=>!0,()=>!1)}Go(Xo,`useIsHydratedModern`);var Zo=typeof Jo==`function`?Xo:qo,Qo=Object.defineProperty,$o=(e,t)=>Qo(e,`name`,{value:t,configurable:!0}),es=`rovingFocusGroup.onEntryFocus`,ts={bubbles:!1,cancelable:!0},ns=`RovingFocusGroup`,[rs,is,as]=co(ns),[os,ss]=vt(ns,[as]),[cs,ls]=os(ns),us=z.forwardRef($o(function(e,t){return(0,K.jsx)(rs.Provider,{scope:e.__scopeRovingFocusGroup,children:(0,K.jsx)(rs.Slot,{scope:e.__scopeRovingFocusGroup,children:(0,K.jsx)(ds,{...e,ref:t})})})},`RovingFocusGroup`)),ds=z.forwardRef($o(function(e,t){let{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:a,currentTabStopId:o,defaultCurrentTabStopId:s,onCurrentTabStopIdChange:c,onEntryFocus:l,preventScrollOnEntryFocus:u=!1,...d}=e,f=z.useRef(null),p=C(t,f),m=_a(a),[h,g]=Hi({prop:o,defaultProp:s??null,onChange:c,caller:ns}),[_,v]=z.useState(!1),y=Et(l),b=is(n),x=z.useRef(!1),[S,w]=z.useState(0);return z.useEffect(()=>{let e=f.current;if(e)return e.addEventListener(es,y),()=>e.removeEventListener(es,y)},[y]),(0,K.jsx)(cs,{scope:n,orientation:r,dir:m,loop:i,currentTabStopId:h,onItemFocus:z.useCallback(e=>g(e),[g]),onItemShiftTab:z.useCallback(()=>v(!0),[]),onFocusableItemAdd:z.useCallback(()=>w(e=>e+1),[]),onFocusableItemRemove:z.useCallback(()=>w(e=>e-1),[]),children:(0,K.jsx)(q.div,{tabIndex:_||S===0?-1:0,"data-orientation":r,...d,ref:p,style:{outline:`none`,...e.style},onMouseDown:G(e.onMouseDown,()=>{x.current=!0}),onFocus:G(e.onFocus,e=>{let t=!x.current;if(e.target===e.currentTarget&&t&&!_){let t=new CustomEvent(es,ts);if(e.currentTarget.dispatchEvent(t),!t.defaultPrevented){let e=b().filter(e=>e.focusable);_s([e.find(e=>e.active),e.find(e=>e.id===h),...e].filter(Boolean).map(e=>e.ref.current),u)}}x.current=!1}),onBlur:G(e.onBlur,()=>v(!1))})})},`RovingFocusGroupImpl`)),fs=`RovingFocusGroupItem`,ps=z.forwardRef($o(function(e,t){let{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:a,children:o,...s}=e,c=Y(),l=a||c,u=ls(fs,n),d=u.currentTabStopId===l,f=is(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:h}=u,g=Zo();return Bt(()=>{if(!(!g||!r))return p(),()=>m()},[g,r,p,m]),z.useEffect(()=>{if(!(g||!r))return p(),()=>m()},[g,r,p,m]),(0,K.jsx)(rs.ItemSlot,{scope:n,id:l,focusable:r,active:i,children:(0,K.jsx)(q.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...s,ref:t,onMouseDown:G(e.onMouseDown,e=>{r?u.onItemFocus(l):e.preventDefault()}),onFocus:G(e.onFocus,()=>u.onItemFocus(l)),onKeyDown:G(e.onKeyDown,e=>{if(e.key===`Tab`&&e.shiftKey){u.onItemShiftTab();return}if(e.target!==e.currentTarget)return;let t=gs(e,u.orientation,u.dir);if(t!==void 0){if(e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)return;e.preventDefault();let n=f().filter(e=>e.focusable).map(e=>e.ref.current);if(t===`last`)n.reverse();else if(t===`prev`||t===`next`){t===`prev`&&n.reverse();let r=n.indexOf(e.currentTarget);n=u.loop?vs(n,r+1):n.slice(r+1)}setTimeout(()=>_s(n))}}),children:typeof o==`function`?o({isCurrentTabStop:d,hasTabStop:h!=null}):o})})},`RovingFocusGroupItem`)),ms={ArrowLeft:`prev`,ArrowUp:`prev`,ArrowRight:`next`,ArrowDown:`next`,PageUp:`first`,Home:`first`,PageDown:`last`,End:`last`};function hs(e,t){return t===`rtl`?e===`ArrowLeft`?`ArrowRight`:e===`ArrowRight`?`ArrowLeft`:e:e}$o(hs,`getDirectionAwareKey`);function gs(e,t,n){let r=hs(e.key,n);if(!(t===`vertical`&&[`ArrowLeft`,`ArrowRight`].includes(r))&&!(t===`horizontal`&&[`ArrowUp`,`ArrowDown`].includes(r)))return ms[r]}$o(gs,`getFocusIntent`);function _s(e,t=!1){let n=document.activeElement;for(let r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}$o(_s,`focusFirst`);function vs(e,t){return e.map((n,r)=>e[(t+r)%e.length])}$o(vs,`wrapArray`);var ys=function(e){return typeof document>`u`?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},bs=new WeakMap,xs=new WeakMap,Ss={},Cs=0,ws=function(e){return e&&(e.host||ws(e.parentNode))},Ts=function(e,t){return t.map(function(t){if(e.contains(t))return t;var n=ws(t);return n&&e.contains(n)?n:(console.error(`aria-hidden`,t,`in not contained inside`,e,`. Doing nothing`),null)}).filter(function(e){return!!e})},Es=function(e,t,n,r){var i=Ts(t,Array.isArray(e)?e:[e]);Ss[n]||(Ss[n]=new WeakMap);var a=Ss[n],o=[],s=new Set,c=new Set(i),l=function(e){!e||s.has(e)||(s.add(e),l(e.parentNode))};i.forEach(l);var u=function(e){!e||c.has(e)||Array.prototype.forEach.call(e.children,function(e){if(s.has(e))u(e);else try{var t=e.getAttribute(r),i=t!==null&&t!==`false`,c=(bs.get(e)||0)+1,l=(a.get(e)||0)+1;bs.set(e,c),a.set(e,l),o.push(e),c===1&&i&&xs.set(e,!0),l===1&&e.setAttribute(n,`true`),i||e.setAttribute(r,`true`)}catch(t){console.error(`aria-hidden: cannot operate on `,e,t)}})};return u(t),s.clear(),Cs++,function(){o.forEach(function(e){var t=bs.get(e)-1,i=a.get(e)-1;bs.set(e,t),a.set(e,i),t||(xs.has(e)||e.removeAttribute(r),xs.delete(e)),i||e.removeAttribute(n)}),Cs--,Cs||(bs=new WeakMap,bs=new WeakMap,xs=new WeakMap,Ss={})}},Ds=function(e,t,n){n===void 0&&(n=`data-aria-hidden`);var r=Array.from(Array.isArray(e)?e:[e]),i=t||ys(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll(`[aria-live], script`))),Es(r,i,n,`aria-hidden`)):function(){return null}},Os=function(){return Os=Object.assign||function(e){for(var t,n=1,r=arguments.length;n`u`)return nc;var t=ic(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},oc=tc(),sc=`data-scroll-locked`,cc=function(e,t,n,r){var i=e.left,a=e.top,o=e.right,s=e.gap;return n===void 0&&(n=`margin`),` + .${Ns} { + overflow: hidden ${r}; + padding-right: ${s}px ${r}; + } + body[${sc}] { + overflow: hidden ${r}; + overscroll-behavior: contain; + ${[t&&`position: relative ${r};`,n===`margin`&&` + padding-left: ${i}px; + padding-top: ${a}px; + padding-right: ${o}px; + margin-left:0; + margin-top:0; + margin-right: ${s}px ${r}; + `,n===`padding`&&`padding-right: ${s}px ${r};`].filter(Boolean).join(``)} + } + + .${js} { + right: ${s}px ${r}; + } + + .${Ms} { + margin-right: ${s}px ${r}; + } + + .${js} .${js} { + right: 0 ${r}; + } + + .${Ms} .${Ms} { + margin-right: 0 ${r}; + } + + body[${sc}] { + ${Ps}: ${s}px; + } +`},lc=function(){var e=parseInt(document.body.getAttribute(`data-scroll-locked`)||`0`,10);return isFinite(e)?e:0},uc=function(){z.useEffect(function(){return document.body.setAttribute(sc,(lc()+1).toString()),function(){var e=lc()-1;e<=0?document.body.removeAttribute(sc):document.body.setAttribute(sc,e.toString())}},[])},dc=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?`margin`:r;uc();var a=z.useMemo(function(){return ac(i)},[i]);return z.createElement(oc,{styles:cc(a,!t,i,n?``:`!important`)})},fc=!1;if(typeof window<`u`)try{var pc=Object.defineProperty({},"passive",{get:function(){return fc=!0,!0}});window.addEventListener(`test`,pc,pc),window.removeEventListener(`test`,pc,pc)}catch{fc=!1}var mc=fc?{passive:!1}:!1,hc=function(e){return e.tagName===`TEXTAREA`},gc=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!==`hidden`&&!(n.overflowY===n.overflowX&&!hc(e)&&n[t]===`visible`)},_c=function(e){return gc(e,`overflowY`)},vc=function(e){return gc(e,`overflowX`)},yc=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<`u`&&r instanceof ShadowRoot&&(r=r.host),Sc(e,r)){var i=Cc(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},bc=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},xc=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},Sc=function(e,t){return e===`v`?_c(t):vc(t)},Cc=function(e,t){return e===`v`?bc(t):xc(t)},wc=function(e,t){return e===`h`&&t===`rtl`?-1:1},Tc=function(e,t,n,r,i){var a=wc(e,window.getComputedStyle(t).direction),o=a*r,s=n.target,c=t.contains(s),l=!1,u=o>0,d=0,f=0;do{if(!s)break;var p=Cc(e,s),m=p[0],h=p[1]-p[2]-a*m;(m||h)&&Sc(e,s)&&(d+=h,f+=m);var g=s.parentNode;s=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}while(!c&&s!==document.body||c&&(t.contains(s)||t===s));return(u&&(i&&Math.abs(d)<1||!i&&o>d)||!u&&(i&&Math.abs(f)<1||!i&&-o>f))&&(l=!0),l},Ec=function(e){return`changedTouches`in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Dc=function(e){return[e.deltaX,e.deltaY]},Oc=function(e){return e&&`current`in e?e.current:e},kc=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Ac=function(e){return` + .block-interactivity-${e} {pointer-events: none;} + .allow-interactivity-${e} {pointer-events: all;} +`},jc=0,Mc=[];function Nc(e){var t=z.useRef([]),n=z.useRef([0,0]),r=z.useRef(),i=z.useState(jc++)[0],a=z.useState(tc)[0],o=z.useRef(e);z.useEffect(function(){o.current=e},[e]),z.useEffect(function(){if(e.inert){document.body.classList.add(`block-interactivity-${i}`);var t=As([e.lockRef.current],(e.shards||[]).map(Oc),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add(`allow-interactivity-${i}`)}),function(){document.body.classList.remove(`block-interactivity-${i}`),t.forEach(function(e){return e.classList.remove(`allow-interactivity-${i}`)})}}},[e.inert,e.lockRef.current,e.shards]);var s=z.useCallback(function(e,t){if(`touches`in e&&e.touches.length===2||e.type===`wheel`&&e.ctrlKey)return!o.current.allowPinchZoom;var i=Ec(e),a=n.current,s=`deltaX`in e?e.deltaX:a[0]-i[0],c=`deltaY`in e?e.deltaY:a[1]-i[1],l,u=e.target,d=Math.abs(s)>Math.abs(c)?`h`:`v`;if(`touches`in e&&d===`h`&&u.type===`range`)return!1;var f=window.getSelection(),p=f&&f.anchorNode;if(p&&(p===u||p.contains(u)))return!1;var m=yc(d,u);if(!m)return!0;if(m?l=d:(l=d===`v`?`h`:`v`,m=yc(d,u)),!m)return!1;if(!r.current&&`changedTouches`in e&&(s||c)&&(r.current=l),!l)return!0;var h=r.current||l;return Tc(h,t,e,h===`h`?s:c,!0)},[]),c=z.useCallback(function(e){var n=e;if(!(!Mc.length||Mc[Mc.length-1]!==a)){var r=`deltaY`in n?Dc(n):Ec(n),i=t.current.filter(function(e){return e.name===n.type&&(e.target===n.target||n.target===e.shadowParent)&&kc(e.delta,r)})[0];if(i&&i.should){n.cancelable&&n.preventDefault();return}if(!i){var c=(o.current.shards||[]).map(Oc).filter(Boolean).filter(function(e){return e.contains(n.target)});(c.length>0?s(n,c[0]):!o.current.noIsolation)&&n.cancelable&&n.preventDefault()}}},[]),l=z.useCallback(function(e,n,r,i){var a={name:e,delta:n,target:r,should:i,shadowParent:Pc(r)};t.current.push(a),setTimeout(function(){t.current=t.current.filter(function(e){return e!==a})},1)},[]),u=z.useCallback(function(e){n.current=Ec(e),r.current=void 0},[]),d=z.useCallback(function(t){l(t.type,Dc(t),t.target,s(t,e.lockRef.current))},[]),f=z.useCallback(function(t){l(t.type,Ec(t),t.target,s(t,e.lockRef.current))},[]);z.useEffect(function(){return Mc.push(a),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener(`wheel`,c,mc),document.addEventListener(`touchmove`,c,mc),document.addEventListener(`touchstart`,u,mc),function(){Mc=Mc.filter(function(e){return e!==a}),document.removeEventListener(`wheel`,c,mc),document.removeEventListener(`touchmove`,c,mc),document.removeEventListener(`touchstart`,u,mc)}},[]);var p=e.removeScrollBar,m=e.inert;return z.createElement(z.Fragment,null,m?z.createElement(a,{styles:Ac(i)}):null,p?z.createElement(dc,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Pc(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Fc=Ws(Gs,Nc),Ic=z.forwardRef(function(e,t){return z.createElement(qs,Os({},e,{ref:t,sideCar:Fc}))});Ic.classNames=qs.classNames;var Lc=Object.defineProperty,Q=(e,t)=>Lc(e,`name`,{value:t,configurable:!0}),Rc=[`Enter`,` `],zc=[`ArrowDown`,`PageUp`,`Home`],Bc=[`ArrowUp`,`PageDown`,`End`],Vc=[...zc,...Bc],Hc={ltr:[...Rc,`ArrowRight`],rtl:[...Rc,`ArrowLeft`]},Uc={ltr:[`ArrowLeft`],rtl:[`ArrowRight`]},Wc=`Menu`,[Gc,Kc,qc]=co(Wc),[Jc,Yc]=vt(Wc,[qc,ui,ss]),Xc=ui(),Zc=ss(),[Qc,$c]=Jc(Wc),[el,tl]=Jc(Wc),nl=Q(e=>{let{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:a,modal:o=!0}=e,s=Xc(t),[c,l]=z.useState(null),u=z.useRef(!1),d=Et(a),f=_a(i);return z.useEffect(()=>{let e=Q(()=>{u.current=!0,document.addEventListener(`pointerdown`,t,{capture:!0,once:!0}),document.addEventListener(`pointermove`,t,{capture:!0,once:!0})},`handleKeyDown`),t=Q(()=>u.current=!1,`handlePointer`);return document.addEventListener(`keydown`,e,{capture:!0}),()=>{document.removeEventListener(`keydown`,e,{capture:!0}),document.removeEventListener(`pointerdown`,t,{capture:!0}),document.removeEventListener(`pointermove`,t,{capture:!0})}},[]),z.useEffect(()=>{if(!n)return;let e=Q(()=>d(!1),`handleBlur`);return window.addEventListener(`blur`,e),()=>window.removeEventListener(`blur`,e)},[n,d]),(0,K.jsx)(pi,{...s,children:(0,K.jsx)(Qc,{scope:t,open:n,onOpenChange:d,content:c,onContentChange:l,children:(0,K.jsx)(el,{scope:t,onClose:z.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:f,modal:o,children:r})})})},`Menu`),rl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,...r}=e,i=Xc(n);return(0,K.jsx)(hi,{...i,...r,ref:t})},`MenuAnchor`)),il=`MenuPortal`,[al,ol]=Jc(il,{forceMount:void 0}),sl=Q(e=>{let{__scopeMenu:t,forceMount:n,children:r,container:i}=e,a=$c(il,t);return(0,K.jsx)(al,{scope:t,forceMount:n,children:(0,K.jsx)(Oi,{present:n||a.open,children:(0,K.jsx)(wi,{asChild:!0,container:i,children:r})})})},`MenuPortal`),cl=`MenuContent`,[ll,ul]=Jc(cl),dl=z.forwardRef(Q(function(e,t){let n=ol(cl,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,a=$c(cl,e.__scopeMenu),o=tl(cl,e.__scopeMenu);return(0,K.jsx)(Gc.Provider,{scope:e.__scopeMenu,children:(0,K.jsx)(Oi,{present:r||a.open,children:(0,K.jsx)(Gc.Slot,{scope:e.__scopeMenu,children:o.modal?(0,K.jsx)(fl,{...i,ref:t}):(0,K.jsx)(pl,{...i,ref:t})})})})},`MenuContent`)),fl=z.forwardRef(Q(function(e,t){let n=$c(cl,e.__scopeMenu),r=z.useRef(null),i=C(t,r);return z.useEffect(()=>{let e=r.current;if(e)return Ds(e)},[]),(0,K.jsx)(hl,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:G(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})},`MenuRootContentModal`)),pl=z.forwardRef(Q(function(e,t){let n=$c(cl,e.__scopeMenu);return(0,K.jsx)(hl,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})},`MenuRootContentNonModal`)),ml=S(`MenuContent.ScrollLock`),hl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEntryFocus:c,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,disableOutsideScroll:m,...h}=e,g=$c(cl,n),_=tl(cl,n),v=Xc(n),y=Zc(n),b=Kc(n),[x,S]=z.useState(null),w=z.useRef(null),T=C(t,w,g.onContentChange),E=z.useRef(0),D=z.useRef(``),O=z.useRef(0),k=z.useRef(null),A=z.useRef(`right`),j=z.useRef(0),M=m?Ic:z.Fragment,N=m?{as:ml,allowPinchZoom:!0}:void 0,P=Q(e=>{let t=D.current+e,n=b().filter(e=>!e.disabled),r=document.activeElement,i=n.find(e=>e.ref.current===r)?.textValue,a=zl(n.map(e=>e.textValue),t,i),o=n.find(e=>e.textValue===a)?.ref.current;Q((function e(t){D.current=t,window.clearTimeout(E.current),t!==``&&(E.current=window.setTimeout(()=>e(``),1e3))}),`updateSearch`)(t),o&&setTimeout(()=>o.focus())},`handleTypeaheadSearch`);z.useEffect(()=>()=>window.clearTimeout(E.current),[]),To();let F=z.useCallback(e=>A.current===k.current?.side&&Vl(e,k.current?.area),[]);return(0,K.jsx)(ll,{scope:n,searchRef:D,onItemEnter:z.useCallback(e=>{F(e)&&e.preventDefault()},[F]),onItemLeave:z.useCallback(e=>{F(e)||(w.current?.focus(),S(null))},[F]),onTriggerLeave:z.useCallback(e=>{F(e)&&e.preventDefault()},[F]),pointerGraceTimerRef:O,onPointerGraceIntentChange:z.useCallback(e=>{k.current=e},[]),children:(0,K.jsx)(M,{...N,children:(0,K.jsx)(Mo,{asChild:!0,trapped:i,onMountAutoFocus:G(a,e=>{e.preventDefault(),w.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:(0,K.jsx)(Nt,{asChild:!0,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,children:(0,K.jsx)(us,{asChild:!0,...y,dir:_.dir,orientation:`vertical`,loop:r,currentTabStopId:x,onCurrentTabStopIdChange:S,onEntryFocus:G(c,e=>{_.isUsingKeyboardRef.current||e.preventDefault()}),preventScrollOnEntryFocus:!0,children:(0,K.jsx)(yi,{role:`menu`,"aria-orientation":`vertical`,"data-state":Pl(g.open),"data-radix-menu-content":``,dir:_.dir,...v,...h,ref:T,style:{outline:`none`,...h.style},onKeyDown:G(h.onKeyDown,e=>{let t=e.target.closest(`[data-radix-menu-content]`)===e.currentTarget,n=e.ctrlKey||e.altKey||e.metaKey,r=e.key.length===1;t&&(e.key===`Tab`&&e.preventDefault(),!n&&r&&P(e.key));let i=w.current;if(e.target!==i||!Vc.includes(e.key))return;e.preventDefault();let a=b().filter(e=>!e.disabled).map(e=>e.ref.current);Bc.includes(e.key)&&a.reverse(),Ll(a)}),onBlur:G(e.onBlur,e=>{e.currentTarget.contains(e.target)||(window.clearTimeout(E.current),D.current=``)}),onPointerMove:G(e.onPointerMove,Hl(e=>{let t=e.target,n=j.current!==e.clientX;if(e.currentTarget.contains(t)&&n){let t=e.clientX>j.current?`right`:`left`;A.current=t,j.current=e.clientX}}))})})})})})})},`MenuContentImpl`)),gl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,...r}=e;return(0,K.jsx)(q.div,{...r,ref:t})},`MenuLabel`)),_l=`MenuItem`,vl=`menu.itemSelect`,yl=z.forwardRef(Q(function(e,t){let{disabled:n=!1,onSelect:r,...i}=e,a=z.useRef(null),o=tl(_l,e.__scopeMenu),s=ul(_l,e.__scopeMenu),c=C(t,a),l=z.useRef(!1),u=Q(()=>{let e=a.current;if(!n&&e){let t=new CustomEvent(vl,{bubbles:!0,cancelable:!0});e.addEventListener(vl,e=>r?.(e),{once:!0}),Ct(e,t),t.defaultPrevented?l.current=!1:o.onClose()}},`handleSelect`);return(0,K.jsx)(bl,{...i,ref:c,disabled:n,onClick:G(e.onClick,u),onPointerDown:t=>{e.onPointerDown?.(t),l.current=!0},onPointerUp:G(e.onPointerUp,e=>{l.current||e.currentTarget?.click()}),onKeyDown:G(e.onKeyDown,e=>{n||e.target!==e.currentTarget||s.searchRef.current!==``&&e.key===` `||Rc.includes(e.key)&&(e.currentTarget.click(),e.preventDefault())})})},`MenuItem`)),bl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,disabled:r=!1,textValue:i,...a}=e,o=ul(_l,n),s=Zc(n),c=z.useRef(null),l=C(t,c),[u,d]=z.useState(!1),[f,p]=z.useState(``);return z.useEffect(()=>{let e=c.current;e&&p((e.textContent??``).trim())},[a.children]),(0,K.jsx)(Gc.ItemSlot,{scope:n,disabled:r,textValue:i??f,children:(0,K.jsx)(ps,{asChild:!0,...s,focusable:!r,children:(0,K.jsx)(q.div,{role:`menuitem`,"data-highlighted":u?``:void 0,"aria-disabled":r||void 0,"data-disabled":r?``:void 0,...a,ref:l,onPointerMove:G(e.onPointerMove,Hl(e=>{r?o.onItemLeave(e):(o.onItemEnter(e),e.defaultPrevented||e.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:G(e.onPointerLeave,Hl(e=>o.onItemLeave(e))),onFocus:G(e.onFocus,()=>d(!0)),onBlur:G(e.onBlur,()=>d(!1))})})})},`MenuItemImpl`)),[xl,Sl]=Jc(`MenuRadioGroup`,{value:void 0,onValueChange:Q(()=>{},`onValueChange`)}),[Cl,wl]=Jc(`MenuItemIndicator`,{checked:!1}),Tl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,...r}=e;return(0,K.jsx)(q.div,{role:`separator`,"aria-orientation":`horizontal`,...r,ref:t})},`MenuSeparator`)),El=`MenuSub`,[Dl,Ol]=Jc(El),kl=Q(e=>{let{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,a=$c(El,t),o=Xc(t),[s,c]=z.useState(null),[l,u]=z.useState(null),d=Et(i);return z.useEffect(()=>(a.open===!1&&d(!1),()=>d(!1)),[a.open,d]),(0,K.jsx)(pi,{...o,children:(0,K.jsx)(Qc,{scope:t,open:r,onOpenChange:d,content:l,onContentChange:u,children:(0,K.jsx)(Dl,{scope:t,contentId:Y(),triggerId:Y(),trigger:s,onTriggerChange:c,children:n})})})},`MenuSub`),Al=`MenuSubTrigger`,jl=z.forwardRef(Q(function(e,t){let n=$c(Al,e.__scopeMenu),r=tl(Al,e.__scopeMenu),i=Ol(Al,e.__scopeMenu),a=ul(Al,e.__scopeMenu),o=z.useRef(null),{pointerGraceTimerRef:s,onPointerGraceIntentChange:c}=a,l={__scopeMenu:e.__scopeMenu},u=z.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);z.useEffect(()=>u,[u]),z.useEffect(()=>{let e=s.current;return()=>{window.clearTimeout(e),c(null)}},[s,c]);let d=C(t,i.onTriggerChange);return(0,K.jsx)(rl,{asChild:!0,...l,children:(0,K.jsx)(bl,{id:i.triggerId,"aria-haspopup":`menu`,"aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":Pl(n.open),...e,ref:d,onClick:t=>{e.onClick?.(t),!(e.disabled||t.defaultPrevented)&&(t.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:G(e.onPointerMove,Hl(t=>{a.onItemEnter(t),!t.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(a.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:G(e.onPointerLeave,Hl(e=>{u();let t=n.content?.getBoundingClientRect();if(t){let r=n.content?.dataset.side,i=r===`right`,o=i?-5:5,c=t[i?`left`:`right`],l=t[i?`right`:`left`];a.onPointerGraceIntentChange({area:[{x:e.clientX+o,y:e.clientY},{x:c,y:t.top},{x:l,y:t.top},{x:l,y:t.bottom},{x:c,y:t.bottom}],side:r}),window.clearTimeout(s.current),s.current=window.setTimeout(()=>a.onPointerGraceIntentChange(null),300)}else{if(a.onTriggerLeave(e),e.defaultPrevented)return;a.onPointerGraceIntentChange(null)}})),onKeyDown:G(e.onKeyDown,t=>{e.disabled||t.target!==t.currentTarget||a.searchRef.current!==``&&t.key===` `||Hc[r.dir].includes(t.key)&&(n.onOpenChange(!0),n.content?.focus(),t.preventDefault())})})})},`MenuSubTrigger`)),Ml=`MenuSubContent`,Nl=z.forwardRef(Q(function(e,t){let n=ol(cl,e.__scopeMenu),{forceMount:r=n.forceMount,align:i=`start`,...a}=e,o=$c(cl,e.__scopeMenu),s=tl(cl,e.__scopeMenu),c=Ol(Ml,e.__scopeMenu),l=z.useRef(null),u=C(t,l);return(0,K.jsx)(Gc.Provider,{scope:e.__scopeMenu,children:(0,K.jsx)(Oi,{present:r||o.open,children:(0,K.jsx)(Gc.Slot,{scope:e.__scopeMenu,children:(0,K.jsx)(hl,{id:c.contentId,"aria-labelledby":c.triggerId,...a,ref:u,align:i,side:s.dir===`rtl`?`left`:`right`,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:e=>{s.isUsingKeyboardRef.current&&l.current?.focus(),e.preventDefault()},onCloseAutoFocus:e=>e.preventDefault(),onFocusOutside:G(e.onFocusOutside,e=>{e.target!==c.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:G(e.onEscapeKeyDown,e=>{s.onClose(),e.preventDefault()}),onKeyDown:G(e.onKeyDown,e=>{let t=e.currentTarget.contains(e.target),n=Uc[s.dir].includes(e.key);t&&n&&(o.onOpenChange(!1),c.trigger?.focus(),e.preventDefault())})})})})})},`MenuSubContent`));function Pl(e){return e?`open`:`closed`}Q(Pl,`getOpenState`);function Fl(e){return e===`indeterminate`}Q(Fl,`isIndeterminate`);function Il(e){return Fl(e)?`indeterminate`:e?`checked`:`unchecked`}Q(Il,`getCheckedState`);function Ll(e){let t=document.activeElement;for(let n of e)if(n===t||(n.focus(),document.activeElement!==t))return}Q(Ll,`focusFirst`);function Rl(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Q(Rl,`wrapArray`);function zl(e,t,n){let r=t.length>1&&Array.from(t).every(e=>e===t[0])?t[0]:t,i=n?e.indexOf(n):-1,a=Rl(e,Math.max(i,0));r.length===1&&(a=a.filter(e=>e!==n));let o=a.find(e=>e.toLowerCase().startsWith(r.toLowerCase()));return o===n?void 0:o}Q(zl,`getNextMatch`);function Bl(e,t){let{x:n,y:r}=e,i=!1;for(let e=0,a=t.length-1;er!=d>r&&n<(u-c)*(r-l)/(d-l)+c&&(i=!i)}return i}Q(Bl,`isPointInPolygon`);function Vl(e,t){return t?Bl({x:e.clientX,y:e.clientY},t):!1}Q(Vl,`isPointerInGraceArea`);function Hl(e){return t=>t.pointerType===`mouse`?e(t):void 0}Q(Hl,`whenMouse`);var Ul=Object.defineProperty,Wl=(e,t)=>Ul(e,`name`,{value:t,configurable:!0}),Gl=`DropdownMenu`,[Kl,ql]=vt(Gl,[Yc]),Jl=Yc(),[Yl,Xl]=Kl(Gl),Zl=Wl(e=>{let{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:a,onOpenChange:o,modal:s=!0}=e,c=Jl(t),l=z.useRef(null),[u,d]=Hi({prop:i,defaultProp:a??!1,onChange:o,caller:Gl});return(0,K.jsx)(Yl,{scope:t,triggerId:Y(),triggerRef:l,contentId:Y(),open:u,onOpenChange:d,onOpenToggle:z.useCallback(()=>d(e=>!e),[d]),modal:s,children:(0,K.jsx)(nl,{...c,open:u,onOpenChange:d,dir:r,modal:s,children:n})})},`DropdownMenu`),Ql=`DropdownMenuTrigger`,$l=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,a=Xl(Ql,n),o=Jl(n),s=C(t,a.triggerRef);return(0,K.jsx)(rl,{asChild:!0,...o,children:(0,K.jsx)(q.button,{type:`button`,id:a.triggerId,"aria-haspopup":`menu`,"aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":a.open?`open`:`closed`,"data-disabled":r?``:void 0,disabled:r,...i,ref:s,onPointerDown:G(e.onPointerDown,e=>{!r&&e.button===0&&e.ctrlKey===!1&&(a.onOpenToggle(),a.open||e.preventDefault())}),onKeyDown:G(e.onKeyDown,e=>{r||([`Enter`,` `].includes(e.key)&&a.onOpenToggle(),e.key===`ArrowDown`&&a.onOpenChange(!0),[`Enter`,` `,`ArrowDown`].includes(e.key)&&e.preventDefault())})})})},`DropdownMenuTrigger`)),eu=Wl(e=>{let{__scopeDropdownMenu:t,...n}=e,r=Jl(t);return(0,K.jsx)(sl,{...r,...n})},`DropdownMenuPortal`),tu=`DropdownMenuContent`,nu=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Xl(tu,n),a=Jl(n),o=z.useRef(!1);return(0,K.jsx)(dl,{id:i.contentId,"aria-labelledby":i.triggerId,...a,...r,ref:t,onCloseAutoFocus:G(e.onCloseAutoFocus,e=>{o.current||i.triggerRef.current?.focus(),o.current=!1,e.preventDefault()}),onInteractOutside:G(e.onInteractOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0,r=t.button===2||n;(!i.modal||r)&&(o.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-dropdown-menu-content-available-width":`var(--radix-popper-available-width)`,"--radix-dropdown-menu-content-available-height":`var(--radix-popper-available-height)`,"--radix-dropdown-menu-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-dropdown-menu-trigger-height":`var(--radix-popper-anchor-height)`}})},`DropdownMenuContent`)),ru=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(gl,{...i,...r,ref:t})},`DropdownMenuLabel`)),iu=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(yl,{...i,...r,ref:t})},`DropdownMenuItem`)),au=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(Tl,{...i,...r,ref:t})},`DropdownMenuSeparator`)),ou=Wl(e=>{let{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:i,defaultOpen:a}=e,o=Jl(t),[s,c]=Hi({prop:r,defaultProp:a??!1,onChange:i,caller:`DropdownMenuSub`});return(0,K.jsx)(kl,{...o,open:s,onOpenChange:c,children:n})},`DropdownMenuSub`),su=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(jl,{...i,...r,ref:t})},`DropdownMenuSubTrigger`)),cu=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(Nl,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-dropdown-menu-content-available-width":`var(--radix-popper-available-width)`,"--radix-dropdown-menu-content-available-height":`var(--radix-popper-available-height)`,"--radix-dropdown-menu-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-dropdown-menu-trigger-height":`var(--radix-popper-anchor-height)`}})},`DropdownMenuSubContent`)),lu=Zl,uu=$l,du=ou;function fu({className:e,inset:t,children:n,...r}){return(0,K.jsxs)(su,{className:s(`flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-muted data-[state=open]:bg-muted`,t&&`pl-8`,e),...r,children:[n,(0,K.jsx)(ae,{className:`ml-auto size-4 opacity-60`})]})}function pu({className:e,...t}){return(0,K.jsx)(cu,{className:s(`z-50 min-w-40 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg`,e),...t})}function mu({className:e,sideOffset:t=4,...n}){return(0,K.jsx)(eu,{children:(0,K.jsx)(nu,{sideOffset:t,className:s(`z-50 min-w-44 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95`,e),...n})})}function hu({className:e,inset:t,...n}){return(0,K.jsx)(iu,{className:s(`relative flex cursor-default select-none items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50`,t&&`pl-8`,e),...n})}function gu({className:e,inset:t,...n}){return(0,K.jsx)(ru,{className:s(`px-2 py-1.5 text-xs font-medium text-muted-foreground`,t&&`pl-8`,e),...n})}function _u({className:e,...t}){return(0,K.jsx)(au,{className:s(`-mx-1 my-1 h-px bg-border`,e),...t})}var vu=Object.defineProperty,yu=(e,t)=>vu(e,`name`,{value:t,configurable:!0}),bu=`Dialog`,[xu,Su]=vt(bu),[Cu,wu]=xu(bu),Tu=yu(e=>{let{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!0}=e,s=z.useRef(null),c=z.useRef(null),[l,u]=Hi({prop:r,defaultProp:i??!1,onChange:a,caller:bu}),[d,f]=z.useState(0),[p,m]=z.useState(0);return(0,K.jsx)(Cu,{scope:t,triggerRef:s,contentRef:c,contentId:Y(),titleId:Y(),descriptionId:Y(),titlePresent:d>0,descriptionPresent:p>0,setTitleCount:f,setDescriptionCount:m,open:l,onOpenChange:u,onOpenToggle:z.useCallback(()=>u(e=>!e),[u]),modal:o,children:n})},`Dialog`),Eu=`DialogPortal`,[Du,Ou]=xu(Eu,{forceMount:void 0}),ku=yu(e=>{let{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=wu(Eu,t);return(0,K.jsx)(Du,{scope:t,forceMount:n,children:z.Children.map(r,e=>(0,K.jsx)(Oi,{present:n||a.open,children:(0,K.jsx)(wi,{asChild:!0,container:i,children:e})}))})},`DialogPortal`),Au=`DialogOverlay`,ju=z.forwardRef(yu(function(e,t){let n=Ou(Au,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=wu(Au,e.__scopeDialog);return a.modal?(0,K.jsx)(Oi,{present:r||a.open,children:(0,K.jsx)(Nu,{...i,ref:t})}):null},`DialogOverlay`)),Mu=S(`DialogOverlay.RemoveScroll`),Nu=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,...r}=e,i=wu(Au,n),a=C(t,Pt());return(0,K.jsx)(Ic,{as:Mu,allowPinchZoom:!0,shards:[i.contentRef],children:(0,K.jsx)(q.div,{"data-state":Wu(i.open),...r,ref:a,style:{pointerEvents:`auto`,...r.style}})})},`DialogOverlayImpl`)),Pu=`DialogContent`,Fu=z.forwardRef(yu(function(e,t){let n=Ou(Pu,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=wu(Pu,e.__scopeDialog);return(0,K.jsx)(Oi,{present:r||a.open,children:a.modal?(0,K.jsx)(Iu,{...i,ref:t}):(0,K.jsx)(Lu,{...i,ref:t})})},`DialogContent`)),Iu=z.forwardRef(yu(function(e,t){let n=wu(Pu,e.__scopeDialog),r=z.useRef(null),i=C(t,n.contentRef,r);return z.useEffect(()=>{let e=r.current;if(e)return Ds(e)},[]),(0,K.jsx)(Ru,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:G(e.onCloseAutoFocus,e=>{e.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:G(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0;(t.button===2||n)&&e.preventDefault()}),onFocusOutside:G(e.onFocusOutside,e=>e.preventDefault())})},`DialogContentModal`)),Lu=z.forwardRef(yu(function(e,t){let n=wu(Pu,e.__scopeDialog),r=z.useRef(!1),i=z.useRef(!1);return(0,K.jsx)(Ru,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})},`DialogContentNonModal`)),Ru=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,"aria-describedby":o,...s}=e,c=wu(Pu,n);return To(),(0,K.jsx)(K.Fragment,{children:(0,K.jsx)(Mo,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,K.jsx)(Nt,{role:`dialog`,id:c.contentId,"aria-labelledby":c.titlePresent?c.titleId:void 0,"aria-describedby":c.descriptionPresent?Uu(o,c.descriptionId):o,"data-state":Wu(c.open),...s,ref:t,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})},`DialogContentImpl`)),zu=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,...r}=e,i=wu(`DialogTitle`,n),{setTitleCount:a}=i;return Bt(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,K.jsx)(q.h2,{id:i.titleId,...r,ref:t})},`DialogTitle`)),Bu=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,...r}=e,i=wu(`DialogDescription`,n),{setDescriptionCount:a}=i;return Bt(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,K.jsx)(q.p,{id:i.descriptionId,...r,ref:t})},`DialogDescription`)),Vu=`DialogClose`,Hu=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,...r}=e,i=wu(Vu,n);return(0,K.jsx)(q.button,{type:`button`,...r,ref:t,onClick:G(e.onClick,()=>i.onOpenChange(!1))})},`DialogClose`));function Uu(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}yu(Uu,`concatAriaDescribedby`);function Wu(e){return e?`open`:`closed`}yu(Wu,`getState`);var Gu=Tu,Ku=ku;function qu({className:e,...t}){return(0,K.jsx)(ju,{className:s(`fixed inset-0 z-50 bg-black/40 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0`,e),...t})}function Ju({className:e,children:t,...n}){return(0,K.jsxs)(Ku,{children:[(0,K.jsx)(qu,{}),(0,K.jsxs)(Fu,{className:s(`fixed left-1/2 top-1/2 z-50 grid w-[calc(100%-2rem)] max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border border-border bg-background p-6 shadow-xl duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95`,e),...n,children:[t,(0,K.jsxs)(Hu,{className:`absolute right-3 top-3 rounded-md p-1.5 text-muted-foreground opacity-70 transition-opacity hover:bg-muted hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring/40`,children:[(0,K.jsx)(ot,{className:`size-4`}),(0,K.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function Yu({className:e,...t}){return(0,K.jsx)(`div`,{className:s(`flex flex-col gap-1.5 text-left`,e),...t})}function Xu({className:e,...t}){return(0,K.jsx)(zu,{className:s(`text-lg font-semibold leading-none tracking-tight`,e),...t})}function Zu({className:e,...t}){return(0,K.jsx)(Bu,{className:s(`text-sm text-muted-foreground`,e),...t})}function Qu(){let e=T();if(!e)return null;let t=e.displayName??e.primaryEmail??`Account`;return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.profileImageUrl?(0,K.jsx)(`img`,{src:e.profileImageUrl,alt:``,className:`h-8 w-8 rounded-full object-cover`}):(0,K.jsx)(`span`,{className:`grid h-8 w-8 place-items-center rounded-full bg-black/10 text-sm font-medium dark:bg-white/20`,children:t.charAt(0).toUpperCase()}),(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:t}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>void x(),className:`cursor-pointer text-sm underline-offset-4 opacity-70 hover:underline`,children:`Sign out`})]})}function $u(e){return e!==`__proto__`&&e!==`constructor`&&e!==`prototype`}function ed(e,t){let n=Object.create(null);if(e)for(let t of Object.keys(e))$u(t)&&(n[t]=e[t]);if(t&&typeof t==`object`)for(let e of Object.keys(t))$u(e)&&(n[e]=t[e]);return n}function td(e){if(!e)return Object.create(null);let t=Object.create(null);for(let n of Object.keys(e))$u(n)&&(t[n]=e[n]);return t}var nd=()=>{throw Error(`createServerOnlyFn() functions can only be called on the server!`)},$=(e,t)=>{let n=t||e||{};n.method===void 0&&(n.method=`GET`);let r=e=>$(void 0,{...n,validator:e,inputValidator:e});return Object.assign(e=>$(void 0,{...n,...e}),{options:n,middleware:e=>{let t=[...n.middleware||[]];e.map(e=>{g in e?e.options.middleware&&t.push(...e.options.middleware):t.push(e)});let r=$(void 0,{...n,middleware:t});return r[g]=!0,r},validator:r,inputValidator:r,handler:(...e)=>{let[t,r]=e,i={...n,extractedFn:t,serverFn:r},a=[...i.middleware||[],od(i)];return t.method=n.method,Object.assign(async e=>{let n=await rd(a,`client`,{...t,...i,data:e?.data,headers:e?.headers,signal:e?.signal,fetch:e?.fetch,context:td()}),r=u(n.error);if(r)throw r;if(n.error)throw n.error;return n.result},{...t,method:n.method,__executeServer:async e=>{let n=nd(),r=n.contextAfterGlobalMiddlewares;return await rd(a,`server`,{...t,...e,serverFnMeta:t.serverFnMeta,context:ed(e.context,r),request:n.request}).then(e=>({result:e.result,error:e.error,context:e.sendContext}))}})}})};async function rd(e,t,n){let r=id([...d()?.functionMiddleware||[],...e]);if(t===`server`){let e=nd({throwIfNotFound:!1});e?.executedRequestMiddlewares&&(r=r.filter(t=>!e.executedRequestMiddlewares.has(t)))}let i=async e=>{let n=r.shift();if(!n)return e;try{let r=`validator`in n.options?n.options.validator:void 0;!r&&`inputValidator`in n.options&&(r=n.options.inputValidator),r&&t===`server`&&(e.data=await ad(r,e.data));let a;if(t===`client`?`client`in n.options&&(a=n.options.client):`server`in n.options&&(a=n.options.server),a){let t=async(t={})=>{let n=await i({...e,...t,context:ed(e.context,t.context),sendContext:ed(e.sendContext,t.sendContext),headers:M(e.headers,t.headers),_callSiteFetch:e._callSiteFetch,fetch:e._callSiteFetch??t.fetch??e.fetch,result:t.result===void 0?t instanceof Response?t:e.result:t.result,error:t.error??e.error});if(n.error)throw n.error;return n},n=await a({...e,next:t});if(b(n))return{...e,error:n};if(n instanceof Response)return{...e,result:n};if(!n)throw Error(`User middleware returned undefined. You must call next() or return a result in your middlewares.`);return n}return i(e)}catch(t){return{...e,error:t}}};return i({...n,headers:n.headers||{},sendContext:n.sendContext||{},context:n.context||td(),_callSiteFetch:n.fetch})}function id(e,t=100){let n=new Set,r=[],i=(e,a)=>{if(a>t)throw Error(`Middleware nesting depth exceeded maximum of ${t}. Check for circular references.`);e.forEach(e=>{e.options.middleware&&i(e.options.middleware,a+1),n.has(e)||(n.add(e),r.push(e))})};return i(e,0),r}async function ad(e,t){if(e==null)return{};if(`~standard`in e){let n=await e[`~standard`].validate(t);if(n.issues)throw Error(JSON.stringify(n.issues,void 0,2));return n.value}if(`parse`in e)return e.parse(t);if(typeof e==`function`)return e(t);throw Error(`Invalid validator type!`)}function od(e){return{"~types":void 0,options:{inputValidator:e.validator??e.inputValidator,client:async({next:t,sendContext:n,fetch:r,...i})=>{let a={...i,context:n,fetch:r};return t(await e.extractedFn?.(a))},server:async({next:t,...n})=>{let r=await e.serverFn?.(n);return t({...n,result:r})}}}}var sd=(e,t)=>{let n={type:`request`,...t||e},r=e=>sd({},Object.assign(n,{validator:e,inputValidator:e}));return{options:n,middleware:e=>sd({},Object.assign(n,{middleware:e})),validator:r,inputValidator:r,client:e=>sd({},Object.assign(n,{client:e})),server:e=>sd({},Object.assign(n,{server:e}))}},cd=$({method:`POST`}).handler(p(`76d08ea8f0b0103fcaf7055c8b138a9579e4124d0d2f62a0686a1011273cd47a`)),ld=$({method:`POST`}).handler(p(`5e6a13ce7e871cac8b1efc1cf5ccb213d79a60710661cd7012f69f2c7ccb6982`)),ud=$({method:`POST`}).handler(p(`1e62b13d94b613cf423e7774bb51046a7dfc3005d0164d46cbd5f39fd41e65ae`)),dd=$({method:`GET`}).handler(p(`5252add61246cf72a4fa382b4734734c4e8ea74302302ba378f1ecb54d53868d`)),fd=$({method:`GET`}).handler(p(`9bf431d4df4d57d04f011720753080a98c88face5f4f24058da2b17f8da151b8`));$({method:`POST`}).handler(p(`12c220cad66e7d4a3abab6da0b2bab6053a48aee4b6a0cde9d321705b501bd69`));var pd=[`summarize-page`,`edit-block`,`action-items`,`table-from-notes`,`mermaid-diagram`,`custom-page-task`],md={xai:[`grok-4.5`,`grok-4`,`grok-3`,`grok-3-mini`,`grok-2`],anthropic:[`claude-sonnet-4-6`,`claude-opus-4-6`,`claude-haiku-4-5-20251001`,`claude-3-5-sonnet-latest`],openai:[`gpt-4.1`,`gpt-4.1-mini`,`gpt-4o`,`o4-mini`,`gpt-4o-mini`],ollama:[`llama3.2`,`llama3.1`,`mistral`,`qwen2.5`,`gemma3`,`deepseek-r1`],openai_compatible:[`gpt-4o`,`llama3.1`,`custom-model`]},hd={deepagents:{label:`LangChain Deep Agents`,description:`In-process agent with skills + MCP tools.`,needsApiKey:!0,isCli:!1},direct:{label:`Direct model API`,description:`Single-shot chat via provider API (streamable).`,needsApiKey:!0,isCli:!1},"claude-cli":{label:`Claude Code CLI`,description:"Shell out to `claude` with stream-json when available.",needsApiKey:!1,isCli:!0},"codex-cli":{label:`Codex CLI`,description:"Shell out to `codex exec` (streams stdout).",needsApiKey:!1,isCli:!0},"grok-cli":{label:`Grok CLI`,description:"Shell out to `grok chat --stream` / Grok Build.",needsApiKey:!1,isCli:!0},local:{label:`Local demo`,description:`No remote model — offline placeholders.`,needsApiKey:!1,isCli:!1}},gd={xai:{label:`xAI · Grok`,description:`Grok models via the xAI API (OpenAI-compatible).`,keyLabel:`xAI API key`,keyPlaceholder:`xai-…`,needsKey:!0},anthropic:{label:`Anthropic · Claude`,description:`Claude models (Sonnet, Opus, Haiku).`,keyLabel:`Anthropic API key`,keyPlaceholder:`sk-ant-…`,needsKey:!0},openai:{label:`OpenAI`,description:`GPT and o-series models from OpenAI.`,keyLabel:`OpenAI API key`,keyPlaceholder:`sk-…`,needsKey:!0},ollama:{label:`Ollama (local)`,description:`Run open models on your machine or LAN.`,keyLabel:`API key (optional)`,keyPlaceholder:`Usually blank`,needsKey:!1,baseUrlDefault:`http://127.0.0.1:11434`,baseUrlHint:`Ollama OpenAI-compatible base (no /v1 suffix needed).`},openai_compatible:{label:`OpenAI-compatible`,description:`Any OpenAI-style endpoint (Groq, Together, Azure proxy, etc.).`,keyLabel:`API key`,keyPlaceholder:`Optional / required by host`,needsKey:!1,baseUrlDefault:`https://api.example.com/v1`,baseUrlHint:`Must include /v1 if the host expects it.`}};function _d(){return{setupComplete:!1,enabled:!0,backend:`deepagents`,provider:`xai`,model:md.xai[0],apiKey:``,baseUrl:``,temperature:.35,recursionLimit:40,mcpServers:[],enabledSkills:[...pd],preferStreaming:!0}}var vd=v()(h((e,t)=>({..._d(),hydrated:!1,setHydrated:t=>e({hydrated:t}),patch:t=>e(e=>({...e,...t})),reset:()=>e({..._d(),hydrated:!0}),setProviderDefaults:t=>e(e=>{let n={xai:`grok-4.5`,anthropic:`claude-sonnet-4-6`,openai:`gpt-4.1`,ollama:`llama3.2`,openai_compatible:`gpt-4o`},r=t===`ollama`?e.baseUrl||`http://127.0.0.1:11434`:t===`openai_compatible`?e.baseUrl||`https://api.example.com/v1`:``;return{provider:t,model:n[t],baseUrl:r}}),addMcpServer:t=>{let n=o(`mcp`),r={id:n,name:t?.name??`New MCP server`,enabled:t?.enabled??!0,transport:t?.transport??`http`,url:t?.url??`https://`,authToken:t?.authToken??``,headersText:t?.headersText??``,command:t?.command??`npx`,argsText:t?.argsText??`-y @modelcontextprotocol/server-everything`,envText:t?.envText??``};return e(e=>({mcpServers:[...e.mcpServers,r]})),n},updateMcpServer:(t,n)=>e(e=>({mcpServers:e.mcpServers.map(e=>e.id===t?{...e,...n}:e)})),removeMcpServer:t=>e(e=>({mcpServers:e.mcpServers.filter(e=>e.id!==t)})),getSettings:()=>{let e=t();return{setupComplete:e.setupComplete,enabled:e.enabled,backend:e.backend,provider:e.provider,model:e.model,apiKey:e.apiKey,baseUrl:e.baseUrl,temperature:e.temperature,recursionLimit:e.recursionLimit,mcpServers:e.mcpServers,enabledSkills:e.enabledSkills,preferStreaming:e.preferStreaming!==!1}}}),{name:`workspace-ai-settings-v1`,partialize:e=>({setupComplete:e.setupComplete,enabled:e.enabled,backend:e.backend,provider:e.provider,model:e.model,apiKey:e.apiKey,baseUrl:e.baseUrl,temperature:e.temperature,recursionLimit:e.recursionLimit,mcpServers:e.mcpServers,enabledSkills:e.enabledSkills,preferStreaming:e.preferStreaming!==!1}),onRehydrateStorage:()=>e=>{e?.setHydrated(!0)}}));function yd(){return vd.getState().getSettings()}var bd=[{id:`welcome`,title:`Welcome`},{id:`provider`,title:`Provider`},{id:`credentials`,title:`Credentials`},{id:`mcp`,title:`MCP tools`},{id:`skills`,title:`Skills`},{id:`review`,title:`Test & finish`}];function xd({open:e,onOpenChange:t,initialStep:n=`welcome`}){let r=vd(),[i,a]=(0,z.useState)(0),[o,c]=(0,z.useState)(!1),[l,u]=(0,z.useState)(null),[d,f]=(0,z.useState)(null),[p,m]=(0,z.useState)([]);(0,z.useEffect)(()=>{if(!e)return;let t=bd.findIndex(e=>e.id===n);a(t>=0?t:0),u(null),fd().then(e=>m(e.map(e=>({id:e.id,label:e.label,available:e.available})))).catch(()=>m([]))},[e,n]);let h=bd[i],g=r.backend===`claude-cli`||r.backend===`codex-cli`||r.backend===`grok-cli`,_=()=>r.getSettings(),v=(0,z.useMemo)(()=>h.id===`provider`?!!r.backend:h.id===`credentials`?g?!0:r.provider===`openai_compatible`&&!r.baseUrl.trim()?!1:!!r.model.trim():!0,[h.id,r.backend,r.provider,r.baseUrl,r.model,g]),y=e=>{u(null),a(t=>Math.min(bd.length-1,Math.max(0,t+e)))},b=()=>{r.patch({setupComplete:!0,enabled:!0}),t(!1)},x=async()=>{c(!0),u(null);try{let e=await ld({data:{clientSettings:_()}});u({ok:e.ok,message:e.message})}catch(e){u({ok:!1,message:e instanceof Error?e.message:`Test failed`})}finally{c(!1)}},S=async e=>{f(e.id);try{let t=await ud({data:{server:e}});r.updateMcpServer(e.id,{lastTestOk:t.ok,lastTestMessage:t.message,lastToolCount:t.toolNames?.length??0})}catch(t){r.updateMcpServer(e.id,{lastTestOk:!1,lastTestMessage:t instanceof Error?t.message:`Test failed`})}finally{f(null)}};return(0,K.jsx)(Gu,{open:e,onOpenChange:t,children:(0,K.jsxs)(Ju,{className:`flex max-h-[90vh] max-w-2xl flex-col gap-0 overflow-hidden p-0`,children:[(0,K.jsxs)(`div`,{className:`border-b border-border px-6 py-4`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsxs)(Xu,{className:`flex items-center gap-2`,children:[(0,K.jsx)(Ke,{className:`size-4`}),`AI setup · Deep Agents & coding CLIs`]}),(0,K.jsx)(Zu,{children:`Connect an API model, or shell out to Claude Code / Codex / Grok CLIs with streaming.`})]}),(0,K.jsx)(`ol`,{className:`mt-4 flex flex-wrap gap-1.5`,children:bd.map((e,t)=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,"data-testid":`wizard-step-${e.id}`,"aria-current":t===i?`step`:void 0,onClick:()=>a(t),className:s(`rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors`,t===i?`bg-foreground text-background`:tr.setProviderDefaults(e),onBackend:e=>r.patch({backend:e}),onPreferStreaming:e=>r.patch({preferStreaming:e})}),h.id===`credentials`&&(g?(0,K.jsx)(wd,{backend:r.backend,cliStatus:p}):(0,K.jsx)(Td,{provider:r.provider,model:r.model,apiKey:r.apiKey,baseUrl:r.baseUrl,temperature:r.temperature,recursionLimit:r.recursionLimit,onChange:e=>r.patch(e)})),h.id===`mcp`&&(0,K.jsx)(Ed,{servers:r.mcpServers,testingId:d,onAdd:()=>r.addMcpServer(),onUpdate:(e,t)=>r.updateMcpServer(e,t),onRemove:e=>r.removeMcpServer(e),onTest:e=>void S(e)}),h.id===`skills`&&(0,K.jsx)(Dd,{enabled:r.enabledSkills,onToggle:e=>{let t=new Set(r.enabledSkills);t.has(e)?t.delete(e):t.add(e),r.patch({enabledSkills:[...t]})},onAll:()=>r.patch({enabledSkills:[...pd]})}),h.id===`review`&&(0,K.jsx)(Od,{settings:_(),testing:o,testResult:l,onTest:()=>void x()})]}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-t border-border px-6 py-4`,children:[(0,K.jsxs)(w,{type:`button`,variant:`ghost`,disabled:i===0,onClick:()=>y(-1),children:[(0,K.jsx)(H,{className:`size-4`}),` Back`]}),(0,K.jsx)(`div`,{className:`flex gap-2`,children:h.id===`review`?(0,K.jsxs)(w,{type:`button`,onClick:b,children:[(0,K.jsx)(U,{className:`size-4`}),` Save & finish`]}):(0,K.jsxs)(w,{type:`button`,disabled:!v,onClick:()=>y(1),children:[`Continue `,(0,K.jsx)(te,{className:`size-4`})]})})]})]})})}function Sd(){return(0,K.jsxs)(`div`,{className:`space-y-4 text-sm leading-relaxed text-muted-foreground`,children:[(0,K.jsxs)(`p`,{className:`text-base text-foreground`,children:[`Generate and edit content with `,(0,K.jsx)(`strong`,{children:`Deep Agents`}),`, provider APIs, or`,` `,(0,K.jsx)(`strong`,{children:`coding CLIs`}),` (Claude Code, Codex, Grok) — with streaming when available.`]}),(0,K.jsxs)(`ul`,{className:`list-inside list-disc space-y-1.5`,children:[(0,K.jsx)(`li`,{children:`API path: Grok / Claude / OpenAI / Ollama keys (browser-stored)`}),(0,K.jsxs)(`li`,{children:[`CLI path: `,(0,K.jsx)(`code`,{className:`text-xs`,children:`claude`}),`, `,(0,K.jsx)(`code`,{className:`text-xs`,children:`codex`}),`,`,` `,(0,K.jsx)(`code`,{className:`text-xs`,children:`grok`}),` already logged in on the host`]}),(0,K.jsx)(`li`,{children:`Streaming tokens over SSE for live previews in AI blocks and edit dialogs`}),(0,K.jsx)(`li`,{children:`Optional MCP servers + workspace skills for Deep Agents mode`})]})]})}function Cd({provider:e,backend:t,preferStreaming:n,cliStatus:r,onProvider:i,onBackend:a,onPreferStreaming:o}){let c=Object.keys(gd),l=Object.keys(hd),u=hd[t]?.isCli;return(0,K.jsxs)(`div`,{className:`space-y-5`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`h3`,{className:`mb-2 flex items-center gap-2 text-sm font-medium text-foreground`,children:[(0,K.jsx)(Qe,{className:`size-4`}),` Generation backend`]}),(0,K.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:l.map(e=>{let n=hd[e],i=r.find(t=>t.id===e);return(0,K.jsxs)(`button`,{type:`button`,onClick:()=>a(e),className:s(`rounded-xl border px-3 py-3 text-left transition-colors`,t===e?`border-foreground bg-muted/60`:`border-border hover:bg-muted/40`),children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[n.label,n.isCli&&(0,K.jsx)(`span`,{className:s(`rounded-full px-1.5 py-0.5 text-[10px] font-medium`,i?.available?`bg-emerald-500/15 text-emerald-700 dark:text-emerald-300`:`bg-muted text-muted-foreground`),children:i?i.available?`on PATH`:`not found`:`CLI`})]}),(0,K.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:n.description})]},e)})})]}),(0,K.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:n,onChange:e=>o(e.target.checked)}),`Prefer streaming output (SSE) when the backend supports it`]}),!u&&(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{className:`mb-2 text-sm font-medium text-foreground`,children:`Model provider (API)`}),(0,K.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:c.map(t=>{let n=gd[t];return(0,K.jsxs)(`button`,{type:`button`,onClick:()=>i(t),className:s(`rounded-xl border px-3 py-3 text-left transition-colors`,e===t?`border-foreground bg-muted/60`:`border-border hover:bg-muted/40`),children:[(0,K.jsx)(`div`,{className:`text-sm font-semibold text-foreground`,children:n.label}),(0,K.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:n.description})]},t)})})]})]})}function wd({backend:e,cliStatus:t}){let n=t.find(t=>t.id===e);return(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,K.jsx)(`div`,{className:s(`rounded-lg border px-3 py-2 text-xs`,n?.available?`border-emerald-500/40 bg-emerald-500/10 text-emerald-900 dark:text-emerald-200`:`border-border bg-muted/40 text-muted-foreground`),children:n?.available?`${hd[e]?.label??e} is available on PATH.`:`${hd[e]?.label??e} was not found on PATH in this environment. Install it on the machine running the app server.`}),(0,K.jsx)(`ul`,{className:`list-inside list-disc space-y-1.5 text-muted-foreground`,children:({"claude-cli":["Install Claude Code CLI and run `claude login`","Streaming uses `claude -p … --output-format stream-json`","Falls back to plain `-p` if stream-json is unavailable"],"codex-cli":[`Install Codex CLI and authenticate`,"Streaming uses `codex exec` stdout",`Workspace AI never stores your Codex credentials`],"grok-cli":["Install Grok CLI / Grok Build (`grok login` or XAI_API_KEY)","Streaming prefers `grok chat --stream`","Falls back to `grok -p` / chat without stream flags"]}[e]??[`Authenticate the CLI on the host machine.`]).map(e=>(0,K.jsx)(`li`,{children:e},e))}),(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No API key is stored in the workspace for CLI backends — auth is handled by the CLI itself.`})]})}function Td({provider:e,model:t,apiKey:n,baseUrl:r,temperature:i,recursionLimit:a,onChange:o}){let s=gd[e],c=md[e],l=e===`ollama`||e===`openai_compatible`;return(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsxs)(`div`,{className:`rounded-lg border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground`,children:[`Provider: `,(0,K.jsx)(`span`,{className:`font-medium text-foreground`,children:s.label})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:s.keyLabel}),(0,K.jsx)(k,{type:`password`,autoComplete:`off`,placeholder:s.keyPlaceholder,value:n,onChange:e=>o({apiKey:e.target.value})}),(0,K.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:`Stored in this browser’s local storage. Not written to the project repo.`})]}),l&&(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:`Base URL`}),(0,K.jsx)(k,{placeholder:s.baseUrlDefault,value:r,onChange:e=>o({baseUrl:e.target.value})}),s.baseUrlHint&&(0,K.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:s.baseUrlHint})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:`Model`}),(0,K.jsx)(`select`,{className:`h-9 w-full rounded-md border border-border bg-background px-2 text-sm`,value:t,onChange:e=>o({model:e.target.value}),children:c.map(e=>(0,K.jsx)(`option`,{value:e,children:e},e))}),(0,K.jsx)(k,{className:`mt-1`,placeholder:`Or type a custom model id`,value:t,onChange:e=>o({model:e.target.value})})]}),(0,K.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsxs)(`span`,{className:`text-sm font-medium`,children:[`Temperature (`,i.toFixed(2),`)`]}),(0,K.jsx)(`input`,{type:`range`,min:0,max:1.2,step:.05,value:i,onChange:e=>o({temperature:Number(e.target.value)}),className:`w-full`})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:`Agent recursion limit`}),(0,K.jsx)(k,{type:`number`,min:8,max:80,value:a,onChange:e=>o({recursionLimit:Number(e.target.value)||40})})]})]})]})}function Ed({servers:e,testingId:t,onAdd:n,onUpdate:r,onRemove:i,onTest:a}){return(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`MCP tools are used when backend is `,(0,K.jsx)(`strong`,{children:`Deep Agents`}),`.`]}),(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`outline`,onClick:n,children:[(0,K.jsx)(ze,{className:`size-3.5`}),` Add server`]})]}),e.length===0&&(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No MCP servers yet.`}),e.map(e=>(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(Be,{className:`size-4 text-muted-foreground`}),(0,K.jsx)(k,{value:e.name,onChange:t=>r(e.id,{name:t.target.value}),className:`h-8`}),(0,K.jsxs)(`label`,{className:`flex items-center gap-1 text-xs`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:e.enabled,onChange:t=>r(e.id,{enabled:t.target.checked})}),`On`]}),(0,K.jsx)(w,{type:`button`,size:`icon-sm`,variant:`ghost`,onClick:()=>i(e.id),children:(0,K.jsx)($e,{className:`size-3.5`})})]}),(0,K.jsxs)(`select`,{className:`h-8 w-full rounded-md border border-border bg-background px-2 text-xs`,value:e.transport,onChange:t=>r(e.id,{transport:t.target.value}),children:[(0,K.jsx)(`option`,{value:`http`,children:`HTTP`}),(0,K.jsx)(`option`,{value:`sse`,children:`SSE`}),(0,K.jsx)(`option`,{value:`stdio`,children:`stdio`})]}),e.transport===`stdio`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(k,{placeholder:`command`,value:e.command??``,onChange:t=>r(e.id,{command:t.target.value})}),(0,K.jsx)(k,{placeholder:`args (space-separated)`,value:e.argsText??``,onChange:t=>r(e.id,{argsText:t.target.value})})]}):(0,K.jsx)(k,{placeholder:`https://…`,value:e.url??``,onChange:t=>r(e.id,{url:t.target.value})}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`secondary`,disabled:t===e.id,onClick:()=>a(e),children:[t===e.id?(0,K.jsx)(ke,{className:`size-3.5 animate-spin`}):(0,K.jsx)(it,{className:`size-3.5`}),`Test`]}),e.lastTestMessage&&(0,K.jsx)(`span`,{className:s(`text-[11px]`,e.lastTestOk?`text-emerald-600`:`text-destructive`),children:e.lastTestMessage})]})]},e.id))]})}function Dd({enabled:e,onToggle:t,onAll:n}){return(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Skills for Deep Agents mode.`}),(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`ghost`,onClick:n,children:`Enable all`})]}),(0,K.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:pd.map(n=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(n),className:s(`rounded-lg border px-3 py-2 text-left text-sm`,e.includes(n)?`border-foreground bg-muted/50`:`border-border text-muted-foreground`),children:(0,K.jsx)(`span`,{className:`font-medium`,children:n})},n))})]})}function Od({settings:e,testing:t,testResult:n,onTest:r}){return(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,K.jsxs)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-xs`,children:[(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`Backend`}),(0,K.jsx)(`dd`,{className:`font-medium`,children:hd[e.backend]?.label??e.backend}),(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`Streaming`}),(0,K.jsx)(`dd`,{children:e.preferStreaming===!1?`Off`:`Preferred`}),!hd[e.backend]?.isCli&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`Provider`}),(0,K.jsxs)(`dd`,{children:[gd[e.provider]?.label,` · `,e.model]}),(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`API key`}),(0,K.jsx)(`dd`,{children:e.apiKey?`Set`:`Not set`})]}),(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`MCP servers`}),(0,K.jsxs)(`dd`,{children:[e.mcpServers.filter(e=>e.enabled).length,` enabled`]}),(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`Skills`}),(0,K.jsx)(`dd`,{children:e.enabledSkills.length})]}),(0,K.jsxs)(w,{type:`button`,variant:`secondary`,disabled:t,onClick:r,children:[t?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(it,{className:`size-4`}),`Test connection`]}),n&&(0,K.jsx)(`p`,{className:s(`text-xs`,n.ok?`text-emerald-600`:`text-destructive`),children:n.message})]})}function kd({onOpen:e}){let t=vd(e=>e.setupComplete),n=vd(e=>e.backend);return t?null:(0,K.jsxs)(`button`,{type:`button`,onClick:e,className:`flex w-full items-center gap-2 rounded-lg border border-dashed border-border bg-background px-3 py-2 text-left text-xs text-muted-foreground hover:bg-muted/40`,children:[(0,K.jsx)(Ke,{className:`size-3.5 shrink-0`}),(0,K.jsxs)(`span`,{children:[`Set up AI — Grok, Claude, Codex CLI, MCP…`,` `,(0,K.jsxs)(`span`,{className:`text-foreground`,children:[`(`,hd[n]?.label??n,`)`]})]})]})}var Ad={id:`mount_sample`,name:`Sample notes (linked)`,kind:`server`,serverPath:`/workspace/markdown-samples`,createdAt:Date.now()},jd=v()(h((e,t)=>({mounts:[Ad],selection:null,hydrated:!1,setHydrated:t=>e({hydrated:t}),setSelection:t=>e({selection:t}),addServerMount:(t,n)=>{let r=o(`mount`);return e(e=>({mounts:[...e.mounts,{id:r,name:t||`Linked folder`,kind:`server`,serverPath:n,createdAt:Date.now()}]})),r},addBrowserMount:t=>{let n=o(`mount`);return e(e=>({mounts:[...e.mounts,{id:n,name:t||`Local folder`,kind:`browser`,createdAt:Date.now()}]})),n},removeMount:t=>e(e=>({mounts:e.mounts.filter(e=>e.id!==t),selection:e.selection?.mountId===t?null:e.selection})),renameMount:(t,n)=>e(e=>({mounts:e.mounts.map(e=>e.id===t?{...e,name:n}:e)})),...(function(){return{}})()}),{name:`workspace-md-mounts-v1`,partialize:e=>({mounts:e.mounts}),onRehydrateStorage:()=>e=>{e?.setHydrated(!0),e&&!e.mounts.some(e=>e.id===`mount_sample`)&&(e.mounts=[Ad,...e.mounts])}})),Md=`workspace-md-handles`,Nd=`handles`;function Pd(){return new Promise((e,t)=>{let n=indexedDB.open(Md,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Nd)||e.createObjectStore(Nd)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function Fd(e,t){let n=await Pd();await new Promise((r,i)=>{let a=n.transaction(Nd,`readwrite`);a.objectStore(Nd).put(t,e),a.oncomplete=()=>r(),a.onerror=()=>i(a.error)}),n.close()}async function Id(e){let t=await Pd(),n=await new Promise((n,r)=>{let i=t.transaction(Nd,`readonly`).objectStore(Nd).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)});return t.close(),n}async function Ld(e,t=``){let n=[];for await(let[r,i]of e.entries()){if(r.startsWith(`.`))continue;let e=t?`${t}/${r}`:r;i.kind===`directory`?n.push({name:r,relPath:e,kind:`dir`}):r.toLowerCase().endsWith(`.md`)&&n.push({name:r,relPath:e,kind:`file`})}return n.sort((e,t)=>e.kind===t.kind?e.name.localeCompare(t.name):e.kind===`dir`?-1:1)}async function Rd(e,t){let n=t.split(`/`).filter(Boolean),r=e;for(let e=0;e`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var Gd=e=>{switch(e){case`success`:return Jd;case`info`:return Xd;case`warning`:return Yd;case`error`:return Zd;default:return null}},Kd=Array(12).fill(0),qd=({visible:e,className:t})=>z.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},z.createElement(`div`,{className:`sonner-spinner`},Kd.map((e,t)=>z.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),Jd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),Yd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),Xd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),Zd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),Qd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},z.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),z.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),$d=()=>{let[e,t]=z.useState(document.hidden);return z.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},ef=1,tf=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:ef++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0||e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],z.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(rf(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||ef++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},nf=(e,t)=>{let n=t?.id||ef++;return tf.addToast({title:e,...t,id:n}),n},rf=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,af=Object.assign(nf,{success:tf.success,info:tf.info,warning:tf.warning,error:tf.error,custom:tf.custom,message:tf.message,promise:tf.promise,dismiss:tf.dismiss,loading:tf.loading},{getHistory:()=>tf.toasts,getToasts:()=>tf.getActiveToasts()});Wd(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function of(e){return e.label!==void 0}var sf=3,cf=`24px`,lf=`16px`,uf=4e3,df=356,ff=14,pf=45,mf=200;function hf(...e){return e.filter(Boolean).join(` `)}function gf(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var _f=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:T=`Close toast`}=e,[E,D]=z.useState(null),[O,k]=z.useState(null),[A,j]=z.useState(!1),[M,N]=z.useState(!1),[P,F]=z.useState(!1),[I,L]=z.useState(!1),[R,B]=z.useState(!1),[V,ee]=z.useState(0),[H,te]=z.useState(0),ne=z.useRef(n.duration||y||uf),re=z.useRef(null),U=z.useRef(null),ie=c===0,ae=c+1<=o,W=n.type,oe=n.dismissible!==!1,se=n.className||``,ce=n.descriptionClassName||``,le=z.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),ue=z.useMemo(()=>n.closeButton??p,[n.closeButton,p]),de=z.useMemo(()=>n.duration||y||uf,[n.duration,y]),fe=z.useRef(0),pe=z.useRef(0),me=z.useRef(0),he=z.useRef(null),[ge,_e]=b.split(`-`),ve=z.useMemo(()=>s.reduce((e,t,n)=>n>=le?e:e+t.height,0),[s,le]),ye=$d(),be=n.invert||t,xe=W===`loading`;pe.current=z.useMemo(()=>le*x+ve,[le,ve]),z.useEffect(()=>{ne.current=de},[de]),z.useEffect(()=>{j(!0)},[]),z.useEffect(()=>{let e=U.current;if(e){let t=e.getBoundingClientRect().height;return te(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),z.useLayoutEffect(()=>{if(!A)return;let e=U.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,te(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[A,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let Se=z.useCallback(()=>{N(!0),ee(pe.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},mf)},[n,d,a,pe]);z.useEffect(()=>{if(n.promise&&W===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||ye?(()=>{if(me.current{n.onAutoClose==null||n.onAutoClose.call(n,n),Se()},ne.current)),()=>clearTimeout(e)},[u,i,n,W,ye,Se]),z.useEffect(()=>{n.delete&&(Se(),n.onDismiss==null||n.onDismiss.call(n,n))},[Se,n.delete]);function Ce(){return w?.loading?z.createElement(`div`,{className:hf(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":W===`loading`},w.loading):z.createElement(qd,{className:hf(C?.loader,n?.classNames?.loader),visible:W===`loading`})}let we=n.icon||w?.[W]||Gd(W);return z.createElement(`li`,{tabIndex:0,ref:U,className:hf(_,se,C?.toast,n?.classNames?.toast,C?.default,C?.[W],n?.classNames?.[W]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":A,"data-promise":!!n.promise,"data-swiped":R,"data-removed":M,"data-visible":ae,"data-y-position":ge,"data-x-position":_e,"data-index":c,"data-front":ie,"data-swiping":P,"data-dismissible":oe,"data-type":W,"data-invert":be,"data-swipe-out":I,"data-swipe-direction":O,"data-expanded":!!(u||S&&A),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${M?V:pe.current}px`,"--initial-height":S?`auto`:`${H}px`,...m,...n.style},onDragEnd:()=>{F(!1),D(null),he.current=null},onPointerDown:e=>{e.button!==2&&(xe||!oe||(re.current=new Date,ee(pe.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(F(!0),he.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(I||!oe)return;he.current=null;let e=Number(U.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(U.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-re.current?.getTime(),i=E===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=pf||a>.11){ee(pe.current),n.onDismiss==null||n.onDismiss.call(n,n),k(E===`x`?e>0?`right`:`left`:t>0?`down`:`up`),Se(),L(!0);return}else{var o,s;(o=U.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=U.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`)}B(!1),F(!1),D(null)},onPointerMove:t=>{var n,r;if(!he.current||!oe||window.getSelection()?.toString().length>0)return;let i=t.clientY-he.current.y,a=t.clientX-he.current.x,o=e.swipeDirections??gf(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&D(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(E===`y`){if(o.includes(`top`)||o.includes(`bottom`))if(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)s.y=i;else{let e=i*c(i);s.y=Math.abs(e)0)s.x=a;else{let e=a*c(a);s.x=Math.abs(e)0||Math.abs(s.y)>0)&&B(!0),(n=U.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=U.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},ue&&!n.jsx&&W!==`loading`?z.createElement(`button`,{"aria-label":T,"data-disabled":xe,"data-close-button":!0,onClick:xe||!oe?()=>{}:()=>{Se(),n.onDismiss==null||n.onDismiss.call(n,n)},className:hf(C?.closeButton,n?.classNames?.closeButton)},w?.close??Qd):null,(W||n.icon||n.promise)&&n.icon!==null&&(w?.[W]!==null||n.icon)?z.createElement(`div`,{"data-icon":``,className:hf(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Ce():null,n.type===`loading`?null:we):null,z.createElement(`div`,{"data-content":``,className:hf(C?.content,n?.classNames?.content)},z.createElement(`div`,{"data-title":``,className:hf(C?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?z.createElement(`div`,{"data-description":``,className:hf(v,ce,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),z.isValidElement(n.cancel)?n.cancel:n.cancel&&of(n.cancel)?z.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{of(n.cancel)&&oe&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),Se())},className:hf(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,z.isValidElement(n.action)?n.action:n.action&&of(n.action)?z.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{of(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&Se())},className:hf(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function vf(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function yf(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?lf:cf;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var bf=z.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=sf,toastOptions:g,dir:_=vf(),gap:v=ff,icons:y,containerAriaLabel:b=`Notifications`}=e,[x,S]=z.useState([]),C=z.useMemo(()=>n?x.filter(e=>e.toasterId===n):x.filter(e=>!e.toasterId),[x,n]),w=z.useMemo(()=>Array.from(new Set([i].concat(C.filter(e=>e.position).map(e=>e.position)))),[C,i]),[T,E]=z.useState([]),[D,O]=z.useState(!1),[k,A]=z.useState(!1),[j,M]=z.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),N=z.useRef(null),P=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),F=z.useRef(null),I=z.useRef(!1),L=z.useCallback(e=>{S(t=>(t.find(t=>t.id===e.id)?.delete||tf.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return z.useEffect(()=>tf.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{bt.flushSync(()=>{S(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[x]),z.useEffect(()=>{if(d!==`system`){M(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?M(`dark`):M(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{M(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{M(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),z.useEffect(()=>{x.length<=1&&O(!1)},[x]),z.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;O(!0),(t=N.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===N.current||N.current?.contains(document.activeElement))&&O(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),z.useEffect(()=>{if(N.current)return()=>{F.current&&(F.current.focus({preventScroll:!0}),F.current=null,I.current=!1)}},[N.current]),z.createElement(`section`,{ref:t,"aria-label":`${b} ${P}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},w.map((t,n)=>{let[i,a]=t.split(`-`);return C.length?z.createElement(`ol`,{key:t,dir:_===`auto`?vf():_,tabIndex:-1,ref:N,className:c,"data-sonner-toaster":!0,"data-sonner-theme":j,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${T[0]?.height||0}px`,"--width":`${df}px`,"--gap":`${v}px`,...m,...yf(l,u)},onBlur:e=>{I.current&&!e.currentTarget.contains(e.relatedTarget)&&(I.current=!1,F.current&&=(F.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||I.current||(I.current=!0,F.current=e.relatedTarget)},onMouseEnter:()=>O(!0),onMouseMove:()=>O(!0),onMouseLeave:()=>{k||O(!1)},onDragEnd:()=>O(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||A(!0)},onPointerUp:()=>A(!1)},C.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>z.createElement(_f,{key:n.id,icons:y,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:k,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:L,toasts:C.filter(e=>e.position==n.position),heights:T.filter(e=>e.position==n.position),setHeights:E,expandByDefault:o,gap:v,expanded:D,swipeDirections:e.swipeDirections}))):null}))});function xf({open:e,onOpenChange:t}){let n=jd(e=>e.addServerMount),r=jd(e=>e.addBrowserMount),i=jd(e=>e.setSelection),[a,o]=(0,z.useState)(`Linked notes`),[s,c]=(0,z.useState)(`/workspace/markdown-samples`),[l,u]=(0,z.useState)(!1),d=async()=>{u(!0);try{await Bd({data:{root:s,relPath:``}});let e=n(a||`Linked folder`,s);i({mountId:e,relPath:``}),af.success(`Folder linked (view only until you open a file)`),t(!1)}catch(e){af.error(e instanceof Error?e.message:`Could not open path`)}finally{u(!1)}},f=async()=>{let e=window;if(typeof e.showDirectoryPicker!=`function`){af.error(`Your browser doesn’t support folder access. Use a server path instead.`);return}u(!0);try{let n=await e.showDirectoryPicker({mode:`readwrite`}),o=r(a||n.name||`Local folder`);await Fd(o,n),i({mountId:o,relPath:``}),af.success(`Local folder linked without importing`),t(!1)}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;af.error(e instanceof Error?e.message:`Could not link folder`)}finally{u(!1)}};return(0,K.jsx)(Gu,{open:e,onOpenChange:t,children:(0,K.jsxs)(Ju,{className:`max-w-md`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsxs)(Xu,{className:`flex items-center gap-2`,children:[(0,K.jsx)(we,{className:`size-4`}),`Link markdown folder`]}),(0,K.jsxs)(Zu,{children:[`Browse `,(0,K.jsx)(`code`,{className:`text-xs`,children:`.md`}),` files in the same UI`,` `,(0,K.jsx)(`strong`,{children:`without importing`}),` them into the workspace.`]})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5 text-sm`,children:[(0,K.jsx)(`span`,{className:`font-medium`,children:`Display name`}),(0,K.jsx)(k,{value:a,onChange:e=>o(e.target.value)})]}),(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border p-3`,children:[(0,K.jsxs)(`p`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,K.jsx)(ye,{className:`size-4`}),` This computer`]}),(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Uses the browser’s folder picker. Files stay on disk; we only read/write when you open or save.`}),(0,K.jsxs)(w,{type:`button`,disabled:l,onClick:()=>void f(),children:[l?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(_e,{className:`size-4`}),`Choose local folder`]})]}),(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border p-3`,children:[(0,K.jsx)(`p`,{className:`text-sm font-medium`,children:`Server path (sandbox / deploy host)`}),(0,K.jsx)(k,{value:s,onChange:e=>c(e.target.value),placeholder:`/workspace/markdown-samples`}),(0,K.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Allowed under `,(0,K.jsx)(`code`,{children:`/workspace`}),`. Sample:`,` `,(0,K.jsx)(`code`,{children:`/workspace/markdown-samples`})]}),(0,K.jsx)(w,{type:`button`,variant:`secondary`,disabled:l,onClick:()=>void d(),children:`Link server folder`})]})]})})}var Sf=e(n(((e,n)=>{(function(t){typeof e==`object`&&n!==void 0?n.exports=t():typeof define==`function`&&define.amd?define([],t):(typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:this).JSZip=t()})(function(){return function e(n,r,i){function a(s,c){if(!r[s]){if(!n[s]){var l=typeof t==`function`&&t;if(!c&&l)return l(s,!0);if(o)return o(s,!0);var u=Error(`Cannot find module '`+s+`'`);throw u.code=`MODULE_NOT_FOUND`,u}var d=r[s]={exports:{}};n[s][0].call(d.exports,function(e){var t=n[s][1][e];return a(t||e)},d,d.exports,e,n,r,i)}return r[s].exports}for(var o=typeof t==`function`&&t,s=0;s>2,s=(3&t)<<4|n>>4,c=1>6:64,l=2>4,n=(15&o)<<4|(s=a.indexOf(e.charAt(l++)))>>2,r=(3&s)<<6|(c=a.indexOf(e.charAt(l++))),f[u++]=t,s!==64&&(f[u++]=n),c!==64&&(f[u++]=r);return f}},{"./support":30,"./utils":32}],2:[function(e,t,n){var r=e(`./external`),i=e(`./stream/DataWorker`),a=e(`./stream/Crc32Probe`),o=e(`./stream/DataLengthProbe`);function s(e,t,n,r,i){this.compressedSize=e,this.uncompressedSize=t,this.crc32=n,this.compression=r,this.compressedContent=i}s.prototype={getContentWorker:function(){var e=new i(r.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o(`data_length`)),t=this;return e.on(`end`,function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw Error(`Bug : uncompressed data size mismatch`)}),e},getCompressedWorker:function(){return new i(r.Promise.resolve(this.compressedContent)).withStreamInfo(`compressedSize`,this.compressedSize).withStreamInfo(`uncompressedSize`,this.uncompressedSize).withStreamInfo(`crc32`,this.crc32).withStreamInfo(`compression`,this.compression)}},s.createWorkerFrom=function(e,t,n){return e.pipe(new a).pipe(new o(`uncompressedSize`)).pipe(t.compressWorker(n)).pipe(new o(`compressedSize`)).withStreamInfo(`compression`,t)},t.exports=s},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,n){var r=e(`./stream/GenericWorker`);n.STORE={magic:`\0\0`,compressWorker:function(){return new r(`STORE compression`)},uncompressWorker:function(){return new r(`STORE decompression`)}},n.DEFLATE=e(`./flate`)},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,n){var r=e(`./utils`),i=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t){return e!==void 0&&e.length?r.getTypeOf(e)===`string`?function(e,t,n,r){var a=i,o=r+n;e^=-1;for(var s=r;s>>8^a[255&(e^t.charCodeAt(s))];return-1^e}(0|t,e,e.length,0):function(e,t,n,r){var a=i,o=r+n;e^=-1;for(var s=r;s>>8^a[255&(e^t[s])];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,n){n.base64=!1,n.binary=!1,n.dir=!1,n.createFolders=!0,n.date=null,n.compression=null,n.compressionOptions=null,n.comment=null,n.unixPermissions=null,n.dosPermissions=null},{}],6:[function(e,t,n){var r=null;r=typeof Promise<`u`?Promise:e(`lie`),t.exports={Promise:r}},{lie:37}],7:[function(e,t,n){var r=typeof Uint8Array<`u`&&typeof Uint16Array<`u`&&typeof Uint32Array<`u`,i=e(`pako`),a=e(`./utils`),o=e(`./stream/GenericWorker`),s=r?`uint8array`:`array`;function c(e,t){o.call(this,`FlateWorker/`+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}n.magic=`\b\0`,a.inherits(c,o),c.prototype.processChunk=function(e){this.meta=e.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(s,e.data),!1)},c.prototype.flush=function(){o.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},c.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},c.prototype._createPako=function(){this._pako=new i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},n.compressWorker=function(e){return new c(`Deflate`,e)},n.uncompressWorker=function(){return new c(`Inflate`,{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,n){function r(e,t){var n,r=``;for(n=0;n>>=8;return r}function i(e,t,n,i,o,u){var d,f,p=e.file,m=e.compression,h=u!==s.utf8encode,g=a.transformTo(`string`,u(p.name)),_=a.transformTo(`string`,s.utf8encode(p.name)),v=p.comment,y=a.transformTo(`string`,u(v)),b=a.transformTo(`string`,s.utf8encode(v)),x=_.length!==p.name.length,S=b.length!==v.length,C=``,w=``,T=``,E=p.dir,D=p.date,O={crc32:0,compressedSize:0,uncompressedSize:0};t&&!n||(O.crc32=e.crc32,O.compressedSize=e.compressedSize,O.uncompressedSize=e.uncompressedSize);var k=0;t&&(k|=8),h||!x&&!S||(k|=2048);var A=0,j=0;E&&(A|=16),o===`UNIX`?(j=798,A|=function(e,t){var n=e;return e||(n=t?16893:33204),(65535&n)<<16}(p.unixPermissions,E)):(j=20,A|=function(e){return 63&(e||0)}(p.dosPermissions)),d=D.getUTCHours(),d<<=6,d|=D.getUTCMinutes(),d<<=5,d|=D.getUTCSeconds()/2,f=D.getUTCFullYear()-1980,f<<=4,f|=D.getUTCMonth()+1,f<<=5,f|=D.getUTCDate(),x&&(w=r(1,1)+r(c(g),4)+_,C+=`up`+r(w.length,2)+w),S&&(T=r(1,1)+r(c(y),4)+b,C+=`uc`+r(T.length,2)+T);var M=``;return M+=` +\0`,M+=r(k,2),M+=m.magic,M+=r(d,2),M+=r(f,2),M+=r(O.crc32,4),M+=r(O.compressedSize,4),M+=r(O.uncompressedSize,4),M+=r(g.length,2),M+=r(C.length,2),{fileRecord:l.LOCAL_FILE_HEADER+M+g+C,dirRecord:l.CENTRAL_FILE_HEADER+r(j,2)+M+r(y.length,2)+`\0\0\0\0`+r(A,4)+r(i,4)+g+C+y}}var a=e(`../utils`),o=e(`../stream/GenericWorker`),s=e(`../utf8`),c=e(`../crc32`),l=e(`../signature`);function u(e,t,n,r){o.call(this,`ZipFileWorker`),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=n,this.encodeFileName=r,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(u,o),u.prototype.push=function(e){var t=e.meta.percent||0,n=this.entriesCount,r=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,o.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:n?(t+100*(n-r-1))/n:100}}))},u.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var n=i(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:n.fileRecord,meta:{percent:0}})}else this.accumulate=!0},u.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,n=i(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(n.dirRecord),t)this.push({data:function(e){return l.DATA_DESCRIPTOR+r(e.crc32,4)+r(e.compressedSize,4)+r(e.uncompressedSize,4)}(e),meta:{percent:100}});else for(this.push({data:n.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},u.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t=this.index;t--)n=(n<<8)+this.byteAt(t);return this.index+=e,n},readString:function(e){return r.transformTo(`string`,this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=i},{"../utils":32}],19:[function(e,t,n){var r=e(`./Uint8ArrayReader`);function i(e){r.call(this,e)}e(`../utils`).inherits(i,r),i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,n){var r=e(`./DataReader`);function i(e){r.call(this,e)}e(`../utils`).inherits(i,r),i.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},i.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},i.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i},{"../utils":32,"./DataReader":18}],21:[function(e,t,n){var r=e(`./ArrayReader`);function i(e){r.call(this,e)}e(`../utils`).inherits(i,r),i.prototype.readData=function(e){if(this.checkOffset(e),e===0)return new Uint8Array;var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,n){var r=e(`../utils`),i=e(`../support`),a=e(`./ArrayReader`),o=e(`./StringReader`),s=e(`./NodeBufferReader`),c=e(`./Uint8ArrayReader`);t.exports=function(e){var t=r.getTypeOf(e);return r.checkSupport(t),t!==`string`||i.uint8array?t===`nodebuffer`?new s(e):i.uint8array?new c(r.transformTo(`uint8array`,e)):new a(r.transformTo(`array`,e)):new o(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,n){n.LOCAL_FILE_HEADER=`PK`,n.CENTRAL_FILE_HEADER=`PK`,n.CENTRAL_DIRECTORY_END=`PK`,n.ZIP64_CENTRAL_DIRECTORY_LOCATOR=`PK\x07`,n.ZIP64_CENTRAL_DIRECTORY_END=`PK`,n.DATA_DESCRIPTOR=`PK\x07\b`},{}],24:[function(e,t,n){var r=e(`./GenericWorker`),i=e(`../utils`);function a(e){r.call(this,`ConvertWorker to `+e),this.destType=e}i.inherits(a,r),a.prototype.processChunk=function(e){this.push({data:i.transformTo(this.destType,e.data),meta:e.meta})},t.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,n){var r=e(`./GenericWorker`),i=e(`../crc32`);function a(){r.call(this,`Crc32Probe`),this.withStreamInfo(`crc32`,0)}e(`../utils`).inherits(a,r),a.prototype.processChunk=function(e){this.streamInfo.crc32=i(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,n){var r=e(`../utils`),i=e(`./GenericWorker`);function a(e){i.call(this,`DataLengthProbe for `+e),this.propName=e,this.withStreamInfo(e,0)}r.inherits(a,i),a.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}i.prototype.processChunk.call(this,e)},t.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,n){var r=e(`../utils`),i=e(`./GenericWorker`);function a(e){i.call(this,`DataWorker`);var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type=``,this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=r.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}r.inherits(a,i),a.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,r.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(r.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case`string`:e=this.data.substring(this.index,t);break;case`uint8array`:e=this.data.subarray(this.index,t);break;case`array`:case`nodebuffer`:e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,n){function r(e){this.name=e||`default`,this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}r.prototype={push:function(e){this.emit(`data`,e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit(`end`),this.cleanUp(),this.isFinished=!0}catch(e){this.emit(`error`,e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit(`error`,e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var n=0;n `+e:e}},t.exports=r},{}],29:[function(e,t,n){var r=e(`../utils`),i=e(`./ConvertWorker`),a=e(`./GenericWorker`),o=e(`../base64`),s=e(`../support`),c=e(`../external`),l=null;if(s.nodestream)try{l=e(`../nodejs/NodejsStreamOutputAdapter`)}catch{}function u(e,t){return new c.Promise(function(n,i){var a=[],s=e._internalType,c=e._outputType,l=e._mimeType;e.on(`data`,function(e,n){a.push(e),t&&t(n)}).on(`error`,function(e){a=[],i(e)}).on(`end`,function(){try{n(function(e,t,n){switch(e){case`blob`:return r.newBlob(r.transformTo(`arraybuffer`,t),n);case`base64`:return o.encode(t);default:return r.transformTo(e,t)}}(c,function(e,t){var n,r=0,i=null,a=0;for(n=0;n`u`)n.blob=!1;else{var r=new ArrayBuffer(0);try{n.blob=new Blob([r],{type:`application/zip`}).size===0}catch{try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);i.append(r),n.blob=i.getBlob(`application/zip`).size===0}catch{n.blob=!1}}}try{n.nodestream=!!e(`readable-stream`).Readable}catch{n.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,n){for(var r=e(`./utils`),i=e(`./support`),a=e(`./nodejsUtils`),o=e(`./stream/GenericWorker`),s=Array(256),c=0;c<256;c++)s[c]=252<=c?6:248<=c?5:240<=c?4:224<=c?3:192<=c?2:1;s[254]=s[254]=1;function l(){o.call(this,`utf-8 decode`),this.leftOver=null}function u(){o.call(this,`utf-8 encode`)}n.utf8encode=function(e){return i.nodebuffer?a.newBufferFrom(e,`utf-8`):function(e){var t,n,r,a,o,s=e.length,c=0;for(a=0;a>>6:(n<65536?t[o++]=224|n>>>12:(t[o++]=240|n>>>18,t[o++]=128|n>>>12&63),t[o++]=128|n>>>6&63),t[o++]=128|63&n);return t}(e)},n.utf8decode=function(e){return i.nodebuffer?r.transformTo(`nodebuffer`,e).toString(`utf-8`):function(e){var t,n,i,a,o=e.length,c=Array(2*o);for(t=n=0;t>10&1023,c[n++]=56320|1023&i)}return c.length!==n&&(c.subarray?c=c.subarray(0,n):c.length=n),r.applyFromCharCode(c)}(e=r.transformTo(i.uint8array?`uint8array`:`array`,e))},r.inherits(l,o),l.prototype.processChunk=function(e){var t=r.transformTo(i.uint8array?`uint8array`:`array`,e.data);if(this.leftOver&&this.leftOver.length){if(i.uint8array){var a=t;(t=new Uint8Array(a.length+this.leftOver.length)).set(this.leftOver,0),t.set(a,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var o=function(e,t){var n;for((t||=e.length)>e.length&&(t=e.length),n=t-1;0<=n&&(192&e[n])==128;)n--;return n<0||n===0?t:n+s[e[n]]>t?n:t}(t),c=t;o!==t.length&&(i.uint8array?(c=t.subarray(0,o),this.leftOver=t.subarray(o,t.length)):(c=t.slice(0,o),this.leftOver=t.slice(o,t.length))),this.push({data:n.utf8decode(c),meta:e.meta})},l.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:n.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},n.Utf8DecodeWorker=l,r.inherits(u,o),u.prototype.processChunk=function(e){this.push({data:n.utf8encode(e.data),meta:e.meta})},n.Utf8EncodeWorker=u},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,n){var r=e(`./support`),i=e(`./base64`),a=e(`./nodejsUtils`),o=e(`./external`);function s(e){return e}function c(e,t){for(var n=0;n>8;this.dir=!!(16&this.externalFileAttributes),e==0&&(this.dosPermissions=63&this.externalFileAttributes),e==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!==`/`||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=r(this.extraFields[1].value);this.uncompressedSize===i.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===i.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===i.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===i.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,n,r,i=e.index+this.extraFieldsLength;for(this.extraFields||={};e.index+4>>6:(n<65536?t[o++]=224|n>>>12:(t[o++]=240|n>>>18,t[o++]=128|n>>>12&63),t[o++]=128|n>>>6&63),t[o++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new r.Buf8(e.length),n=0,i=t.length;n>10&1023,l[r++]=56320|1023&i)}return c(l,r)},n.utf8border=function(e,t){var n;for((t||=e.length)>e.length&&(t=e.length),n=t-1;0<=n&&(192&e[n])==128;)n--;return n<0||n===0?t:n+o[e[n]]>t?n:t}},{"./common":41}],43:[function(e,t,n){t.exports=function(e,t,n,r){for(var i=65535&e|0,a=e>>>16&65535|0,o=0;n!==0;){for(n-=o=2e3>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var a=r,o=i+n;e^=-1;for(var s=i;s>>8^a[255&(e^t[s])];return-1^e}},{}],46:[function(e,t,n){var r,i=e(`../utils/common`),a=e(`./trees`),o=e(`./adler32`),s=e(`./crc32`),c=e(`./messages`),l=0,u=4,d=0,f=-2,p=-1,m=4,h=2,g=8,_=9,v=286,y=30,b=19,x=2*v+1,S=15,C=3,w=258,T=w+C+1,E=42,D=113,O=1,k=2,A=3,j=4;function M(e,t){return e.msg=c[t],t}function N(e){return(e<<1)-(4e.avail_out&&(n=e.avail_out),n!==0&&(i.arraySet(e.output,t.pending_buf,t.pending_out,n,e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))}function I(e,t){a._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,F(e.strm)}function L(e,t){e.pending_buf[e.pending++]=t}function R(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function z(e,t){var n,r,i=e.max_chain_length,a=e.strstart,o=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-T?e.strstart-(e.w_size-T):0,l=e.window,u=e.w_mask,d=e.prev,f=e.strstart+w,p=l[a+o-1],m=l[a+o];e.prev_length>=e.good_match&&(i>>=2),s>e.lookahead&&(s=e.lookahead);do if(l[(n=t)+o]===m&&l[n+o-1]===p&&l[n]===l[a]&&l[++n]===l[a+1]){a+=2,n++;do;while(l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&ac&&--i!=0);return o<=e.lookahead?o:e.lookahead}function B(e){var t,n,r,a,c,l,u,d,f,p,m=e.w_size;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=m+(m-T)){for(i.arraySet(e.window,e.window,m,m,0),e.match_start-=m,e.strstart-=m,e.block_start-=m,t=n=e.hash_size;r=e.head[--t],e.head[t]=m<=r?r-m:0,--n;);for(t=n=m;r=e.prev[--t],e.prev[t]=m<=r?r-m:0,--n;);a+=m}if(e.strm.avail_in===0)break;if(l=e.strm,u=e.window,d=e.strstart+e.lookahead,f=a,p=void 0,p=l.avail_in,f=C)for(c=e.strstart-e.insert,e.ins_h=e.window[c],e.ins_h=(e.ins_h<=C&&(e.ins_h=(e.ins_h<=C)if(r=a._tr_tally(e,e.strstart-e.match_start,e.match_length-C),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=C){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<=C&&(e.ins_h=(e.ins_h<=C&&e.match_length<=e.prev_length){for(i=e.strstart+e.lookahead-C,r=a._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-C),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=i&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(n=e.pending_buf_size-5);;){if(e.lookahead<=1){if(B(e),e.lookahead===0&&t===l)return O;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+n;if((e.strstart===0||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,I(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-T&&(I(e,!1),e.strm.avail_out===0))return O}return e.insert=0,t===u?(I(e,!0),e.strm.avail_out===0?A:j):(e.strstart>e.block_start&&(I(e,!1),e.strm.avail_out),O)}),new H(4,4,8,4,V),new H(4,5,16,8,V),new H(4,6,32,32,V),new H(4,4,16,16,ee),new H(8,16,32,32,ee),new H(8,16,128,128,ee),new H(8,32,128,256,ee),new H(32,128,258,1024,ee),new H(32,258,258,4096,ee)],n.deflateInit=function(e,t){return U(e,t,g,15,8,0)},n.deflateInit2=U,n.deflateReset=re,n.deflateResetKeep=ne,n.deflateSetHeader=function(e,t){return e&&e.state&&e.state.wrap===2?(e.state.gzhead=t,d):f},n.deflate=function(e,t){var n,i,o,c;if(!e||!e.state||5>8&255),L(i,i.gzhead.time>>16&255),L(i,i.gzhead.time>>24&255),L(i,i.level===9?2:2<=i.strategy||i.level<2?4:0),L(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(L(i,255&i.gzhead.extra.length),L(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=s(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69):(L(i,0),L(i,0),L(i,0),L(i,0),L(i,0),L(i,i.level===9?2:2<=i.strategy||i.level<2?4:0),L(i,3),i.status=D);else{var p=g+(i.w_bits-8<<4)<<8;p|=(2<=i.strategy||i.level<2?0:i.level<6?1:i.level===6?2:3)<<6,i.strstart!==0&&(p|=32),p+=31-p%31,i.status=D,R(i,p),i.strstart!==0&&(R(i,e.adler>>>16),R(i,65535&e.adler)),e.adler=1}if(i.status===69)if(i.gzhead.extra){for(o=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>o&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),F(e),o=i.pending,i.pending!==i.pending_buf_size));)L(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>o&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=73)}else i.status=73;if(i.status===73)if(i.gzhead.name){o=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>o&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),F(e),o=i.pending,i.pending===i.pending_buf_size)){c=1;break}c=i.gzindexo&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),c===0&&(i.gzindex=0,i.status=91)}else i.status=91;if(i.status===91)if(i.gzhead.comment){o=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>o&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),F(e),o=i.pending,i.pending===i.pending_buf_size)){c=1;break}c=i.gzindexo&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),c===0&&(i.status=103)}else i.status=103;if(i.status===103&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&F(e),i.pending+2<=i.pending_buf_size&&(L(i,255&e.adler),L(i,e.adler>>8&255),e.adler=0,i.status=D)):i.status=D),i.pending!==0){if(F(e),e.avail_out===0)return i.last_flush=-1,d}else if(e.avail_in===0&&N(t)<=N(n)&&t!==u)return M(e,-5);if(i.status===666&&e.avail_in!==0)return M(e,-5);if(e.avail_in!==0||i.lookahead!==0||t!==l&&i.status!==666){var m=i.strategy===2?function(e,t){for(var n;;){if(e.lookahead===0&&(B(e),e.lookahead===0)){if(t===l)return O;break}if(e.match_length=0,n=a._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(I(e,!1),e.strm.avail_out===0))return O}return e.insert=0,t===u?(I(e,!0),e.strm.avail_out===0?A:j):e.last_lit&&(I(e,!1),e.strm.avail_out===0)?O:k}(i,t):i.strategy===3?function(e,t){for(var n,r,i,o,s=e.window;;){if(e.lookahead<=w){if(B(e),e.lookahead<=w&&t===l)return O;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=C&&0e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=C?(n=a._tr_tally(e,1,e.match_length-C),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=a._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(I(e,!1),e.strm.avail_out===0))return O}return e.insert=0,t===u?(I(e,!0),e.strm.avail_out===0?A:j):e.last_lit&&(I(e,!1),e.strm.avail_out===0)?O:k}(i,t):r[i.level].func(i,t);if(m!==A&&m!==j||(i.status=666),m===O||m===A)return e.avail_out===0&&(i.last_flush=-1),d;if(m===k&&(t===1?a._tr_align(i):t!==5&&(a._tr_stored_block(i,0,0,!1),t===3&&(P(i.head),i.lookahead===0&&(i.strstart=0,i.block_start=0,i.insert=0))),F(e),e.avail_out===0))return i.last_flush=-1,d}return t===u?i.wrap<=0?1:(i.wrap===2?(L(i,255&e.adler),L(i,e.adler>>8&255),L(i,e.adler>>16&255),L(i,e.adler>>24&255),L(i,255&e.total_in),L(i,e.total_in>>8&255),L(i,e.total_in>>16&255),L(i,e.total_in>>24&255)):(R(i,e.adler>>>16),R(i,65535&e.adler)),F(e),0=n.w_size&&(s===0&&(P(n.head),n.strstart=0,n.block_start=0,n.insert=0),p=new i.Buf8(n.w_size),i.arraySet(p,t,m-n.w_size,n.w_size,0),t=p,m=n.w_size),c=e.avail_in,l=e.next_in,u=e.input,e.avail_in=m,e.next_in=0,e.input=t,B(n);n.lookahead>=C;){for(r=n.strstart,a=n.lookahead-(C-1);n.ins_h=(n.ins_h<>>=b=y>>>24,m-=b,(b=y>>>16&255)==0)E[a++]=65535&y;else{if(!(16&b)){if(!(64&b)){y=h[(65535&y)+(p&(1<>>=b,m-=b),m<15&&(p+=T[r++]<>>=b=y>>>24,m-=b,!(16&(b=y>>>16&255))){if(!(64&b)){y=g[(65535&y)+(p&(1<>>=b,m-=b,(b=a-o)>3,p&=(1<<(m-=x<<3))-1,e.next_in=r,e.next_out=a,e.avail_in=r>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function _(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg=``,t.wrap&&(e.adler=1&t.wrap),t.mode=f,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new r.Buf32(p),t.distcode=t.distdyn=new r.Buf32(m),t.sane=1,t.back=-1,u):d}function v(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,_(e)):d}function y(e,t){var n,r;return e&&e.state?(r=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15=o.wsize?(r.arraySet(o.window,t,n-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(i<(a=o.wsize-o.wnext)&&(a=i),r.arraySet(o.window,t,n-i,a,o.wnext),(i-=a)?(r.arraySet(o.window,t,n-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,n.check=a(n.check,B,2,0),x=b=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&b)<<8)+(b>>8))%31){e.msg=`incorrect header check`,n.mode=30;break}if((15&b)!=8){e.msg=`unknown compression method`,n.mode=30;break}if(x-=4,F=8+(15&(b>>>=4)),n.wbits===0)n.wbits=F;else if(F>n.wbits){e.msg=`invalid window size`,n.mode=30;break}n.dmax=1<>8&1),512&n.flags&&(B[0]=255&b,B[1]=b>>>8&255,n.check=a(n.check,B,2,0)),x=b=0,n.mode=3;case 3:for(;x<32;){if(v===0)break e;v--,b+=p[g++]<>>8&255,B[2]=b>>>16&255,B[3]=b>>>24&255,n.check=a(n.check,B,4,0)),x=b=0,n.mode=4;case 4:for(;x<16;){if(v===0)break e;v--,b+=p[g++]<>8),512&n.flags&&(B[0]=255&b,B[1]=b>>>8&255,n.check=a(n.check,B,2,0)),x=b=0,n.mode=5;case 5:if(1024&n.flags){for(;x<16;){if(v===0)break e;v--,b+=p[g++]<>>8&255,n.check=a(n.check,B,2,0)),x=b=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&(v<(E=n.length)&&(E=v),E&&(n.head&&(F=n.head.extra_len-n.length,n.head.extra||(n.head.extra=Array(n.head.extra_len)),r.arraySet(n.head.extra,p,g,E,F)),512&n.flags&&(n.check=a(n.check,p,E,g)),v-=E,g+=E,n.length-=E),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(v===0)break e;for(E=0;F=p[g+E++],n.head&&F&&n.length<65536&&(n.head.name+=String.fromCharCode(F)),F&&E>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;x<32;){if(v===0)break e;v--,b+=p[g++]<>>=7&x,x-=7&x,n.mode=27;break}for(;x<3;){if(v===0)break e;v--,b+=p[g++]<>>=1)){case 0:n.mode=14;break;case 1:if(w(n),n.mode=20,t!==6)break;b>>>=2,x-=2;break e;case 2:n.mode=17;break;case 3:e.msg=`invalid block type`,n.mode=30}b>>>=2,x-=2;break;case 14:for(b>>>=7&x,x-=7&x;x<32;){if(v===0)break e;v--,b+=p[g++]<>>16^65535)){e.msg=`invalid stored block lengths`,n.mode=30;break}if(n.length=65535&b,x=b=0,n.mode=15,t===6)break e;case 15:n.mode=16;case 16:if(E=n.length){if(v>>=5,x-=5,n.ndist=1+(31&b),b>>>=5,x-=5,n.ncode=4+(15&b),b>>>=4,x-=4,286>>=3,x-=3}for(;n.have<19;)n.lens[V[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,L={bits:n.lenbits},I=s(0,n.lens,0,19,n.lencode,0,n.work,L),n.lenbits=L.bits,I){e.msg=`invalid code lengths set`,n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have>>16&255,j=65535&z,!((k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>>=k,x-=k,n.lens[n.have++]=j;else{if(j===16){for(R=k+2;x>>=k,x-=k,n.have===0){e.msg=`invalid bit length repeat`,n.mode=30;break}F=n.lens[n.have-1],E=3+(3&b),b>>>=2,x-=2}else if(j===17){for(R=k+3;x>>=k)),b>>>=3,x-=3}else{for(R=k+7;x>>=k)),b>>>=7,x-=7}if(n.have+E>n.nlen+n.ndist){e.msg=`invalid bit length repeat`,n.mode=30;break}for(;E--;)n.lens[n.have++]=F}}if(n.mode===30)break;if(n.lens[256]===0){e.msg=`invalid code -- missing end-of-block`,n.mode=30;break}if(n.lenbits=9,L={bits:n.lenbits},I=s(c,n.lens,0,n.nlen,n.lencode,0,n.work,L),n.lenbits=L.bits,I){e.msg=`invalid literal/lengths set`,n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,L={bits:n.distbits},I=s(l,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,L),n.distbits=L.bits,I){e.msg=`invalid distances set`,n.mode=30;break}if(n.mode=20,t===6)break e;case 20:n.mode=21;case 21:if(6<=v&&258<=y){e.next_out=_,e.avail_out=y,e.next_in=g,e.avail_in=v,n.hold=b,n.bits=x,o(e,C),_=e.next_out,m=e.output,y=e.avail_out,g=e.next_in,p=e.input,v=e.avail_in,b=n.hold,x=n.bits,n.mode===12&&(n.back=-1);break}for(n.back=0;A=(z=n.lencode[b&(1<>>16&255,j=65535&z,!((k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>M)])>>>16&255,j=65535&z,!(M+(k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>>=M,x-=M,n.back+=M}if(b>>>=k,x-=k,n.back+=k,n.length=j,A===0){n.mode=26;break}if(32&A){n.back=-1,n.mode=12;break}if(64&A){e.msg=`invalid literal/length code`,n.mode=30;break}n.extra=15&A,n.mode=22;case 22:if(n.extra){for(R=n.extra;x>>=n.extra,x-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;A=(z=n.distcode[b&(1<>>16&255,j=65535&z,!((k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>M)])>>>16&255,j=65535&z,!(M+(k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>>=M,x-=M,n.back+=M}if(b>>>=k,x-=k,n.back+=k,64&A){e.msg=`invalid distance code`,n.mode=30;break}n.offset=j,n.extra=15&A,n.mode=24;case 24:if(n.extra){for(R=n.extra;x>>=n.extra,x-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg=`invalid distance too far back`,n.mode=30;break}n.mode=25;case 25:if(y===0)break e;if(E=C-y,n.offset>E){if((E=n.offset-E)>n.whave&&n.sane){e.msg=`invalid distance too far back`,n.mode=30;break}D=E>n.wnext?(E-=n.wnext,n.wsize-E):n.wnext-E,E>n.length&&(E=n.length),O=n.window}else O=m,D=_-n.offset,E=n.length;for(yv?(b=L[R+d[w]],N[P+d[w]]):(b=96,0),p=1<>k)+(m-=p)]=y<<24|b<<16|x|0,m!==0;);for(p=1<>=1;if(p===0?M=0:(M&=p-1,M+=p),w++,--F[C]==0){if(C===E)break;C=t[n+d[w]]}if(D>>7)]}function L(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function R(e,t,n){e.bi_valid>h-n?(e.bi_buf|=t<>h-e.bi_valid,e.bi_valid+=n-h):(e.bi_buf|=t<>>=1,n<<=1,0<--t;);return n>>>1}function V(e,t,n){var r,i,a=Array(m+1),o=0;for(r=1;r<=m;r++)a[r]=o=o+n[r-1]<<1;for(i=0;i<=t;i++){var s=e[2*i+1];s!==0&&(e[2*i]=B(a[s]++,s))}}function ee(e){var t;for(t=0;t>1;1<=n;n--)ne(e,a,n);for(i=c;n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],ne(e,a,1),r=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=r,a[2*i]=a[2*n]+a[2*r],e.depth[i]=(e.depth[n]>=e.depth[r]?e.depth[n]:e.depth[r])+1,a[2*n+1]=a[2*r+1]=i,e.heap[1]=i++,ne(e,a,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var n,r,i,a,o,s,c=t.dyn_tree,l=t.max_code,u=t.stat_desc.static_tree,d=t.stat_desc.has_stree,f=t.stat_desc.extra_bits,h=t.stat_desc.extra_base,g=t.stat_desc.max_length,_=0;for(a=0;a<=m;a++)e.bl_count[a]=0;for(c[2*e.heap[e.heap_max]+1]=0,n=e.heap_max+1;n>=7;r>>=1)if(1&n&&e.dyn_ltree[2*t]!==0)return i;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return a;for(t=32;t>>3,(s=e.static_len+3+7>>>3)<=o&&(o=s)):o=s=n+5,n+4<=o&&t!==-1?oe(e,t,n,r):e.strategy===4||s===o?(R(e,2+ +!!r,3),re(e,T,E)):(R(e,4+ +!!r,3),function(e,t,n,r){var i;for(R(e,t-257,5),R(e,n-1,5),R(e,r-4,4),i=0;i>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&n,e.last_lit++,t===0?e.dyn_ltree[2*n]++:(e.matches++,t--,e.dyn_ltree[2*(O[n]+l+1)]++,e.dyn_dtree[2*I(t)]++),e.last_lit===e.lit_bufsize-1},n._tr_align=function(e){R(e,2,3),z(e,_,T),function(e){e.bi_valid===16?(L(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":41}],53:[function(e,t,n){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=``,this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,n){(function(e){(function(e,t){if(!e.setImmediate){var n,r,i,a,o=1,s={},c=!1,l=e.document,u=Object.getPrototypeOf&&Object.getPrototypeOf(e);u=u&&u.setTimeout?u:e,n={}.toString.call(e.process)===`[object process]`?function(e){process.nextTick(function(){f(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage(``,`*`),e.onmessage=n,t}}()?(a=`setImmediate$`+Math.random()+`$`,e.addEventListener?e.addEventListener(`message`,p,!1):e.attachEvent(`onmessage`,p),function(t){e.postMessage(a+t,`*`)}):e.MessageChannel?((i=new MessageChannel).port1.onmessage=function(e){f(e.data)},function(e){i.port2.postMessage(e)}):l&&`onreadystatechange`in l.createElement(`script`)?(r=l.documentElement,function(e){var t=l.createElement(`script`);t.onreadystatechange=function(){f(e),t.onreadystatechange=null,r.removeChild(t),t=null},r.appendChild(t)}):function(e){setTimeout(f,0,e)},u.setImmediate=function(e){typeof e!=`function`&&(e=Function(``+e));for(var t=Array(arguments.length-1),r=0;r`u`?e===void 0?this:e:self)}).call(this,typeof global<`u`?global:typeof self<`u`?self:typeof window<`u`?window:{})},{}]},{},[10])(10)})}))(),1);function Cf(e){let t=[e.title||``];for(let n of e.blocks)n.type===`divider`||n.type===`ai`||n.content?.trim()&&t.push(n.content.trim());return t.join(` +`)}function wf(e){let t=[],n=0;for(let r of e){let e=r.content??``;switch(r.type){case`heading1`:t.push(`# ${e}`),n=0;break;case`heading2`:t.push(`## ${e}`),n=0;break;case`heading3`:t.push(`### ${e}`),n=0;break;case`bullet`:t.push(`${` `.repeat(r.indent??0)}- ${e}`),n=0;break;case`numbered`:n+=1,t.push(`${` `.repeat(r.indent??0)}${n}. ${e}`);break;case`todo`:t.push(`${` `.repeat(r.indent??0)}- [${r.checked?`x`:` `}] ${e}`),n=0;break;case`quote`:t.push(e.split(` +`).map(e=>`> ${e}`).join(` +`)),n=0;break;case`callout`:t.push(`> 💡 ${e}`),n=0;break;case`code`:t.push("```"),t.push(e),t.push("```"),n=0;break;case`mermaid`:t.push("```mermaid"),t.push(e),t.push("```"),n=0;break;case`divider`:t.push(`---`),n=0;break;case`toggle`:t.push(`
${e||`Toggle`}`),t.push(``),t.push(`
`),n=0;break;case`ai`:break;default:t.push(e),n=0}t.push(``)}return t.join(` +`).replace(/\n{3,}/g,` + +`).trim()+` +`}function Tf(e){let t=e.title||`Untitled`,n=wf(e.blocks);return n.startsWith(`# ${t}`)?n:`# ${t}\n\n${n}`}function Ef(e,t,n){return{id:o(`b`),type:e,content:t,indent:0,...n}}function Df(e){let t=e.replace(/\r\n/g,` +`),n=[],r=t.split(` +`),i=0;for(;i`)){let e=[];for(;i`);)e.push(r[i].replace(/^>\s?/,``)),i+=1;let t=e.join(` +`);t.startsWith(`💡`)||t.startsWith(`:bulb:`)?n.push(Ef(`callout`,t.replace(/^💡\s*|^:bulb:\s*/,``))):n.push(Ef(`quote`,t));continue}if(!e.trim()){i+=1;continue}let l=[e];for(i+=1;i`)||e.startsWith("```")||/^[-*+]\s/.test(e)||/^\d+\.\s/.test(e)||/^---+\s*$/.test(e))break;l.push(e),i+=1}n.push(Ef(`paragraph`,l.join(` +`)))}return n.length===0&&n.push(Ef(`paragraph`,``)),n}function Of(e,t){let n=e.match(/^#\s+(.+)$/m);return n?.[1]?.trim()?n[1].trim().slice(0,200):t.replace(/\.md$/i,``)||`Untitled`}function kf(e){return(e||`untitled`).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function Af(e,t,n=20){let r=t.trim().toLowerCase();if(!r)return[];let i=r.split(/\s+/).filter(Boolean),a=[];for(let t of e){if(t.archived)continue;let e=Cf(t),n=`${t.title}\n${e}`.toLowerCase(),o=0;t.title.toLowerCase().includes(r)&&(o+=2);for(let e of i)n.includes(e)&&(o+=1);let s=t.title.toLowerCase(),c=0;for(let e=0;e120?`…`:``);if(u>=0){let e=Math.max(0,u-40),t=Math.min(l.length,u+r.length+80);d=(e>0?`…`:``)+l.slice(e,t)+(t=2?`keyword`:`similarity`})}return a.sort((e,t)=>t.score-e.score).slice(0,n)}function jf(e,t){let n=new Map;for(let t of e){if(t.archived)continue;let e=n.get(t.parentId)??[];e.push(t),n.set(t.parentId,e)}let r=[],i=t=>{let a=e.find(e=>e.id===t);if(!(!a||a.archived)){r.push(a);for(let e of n.get(t)??[])i(e.id)}};return i(t),r}function Mf(e,t){if(!e.has(t))return e.add(t),t;let n=2;for(;e.has(`${t}-${n}`);)n+=1;let r=`${t}-${n}`;return e.add(r),r}async function Nf(e,t){let n=new Sf.default,r=t.hierarchy?jf(e,t.rootId):e.filter(e=>e.id===t.rootId);if(r.length===0)throw Error(`Page not found`);let i=e.find(e=>e.id===t.rootId),a=new Set,o=new Map,s=Mf(a,kf(i.title||`page`));if(n.file(`${s}.md`,Tf(i)),o.set(i.id,s),t.hierarchy)for(let e of r){if(e.id===i.id)continue;let t=e.parentId?o.get(e.parentId):s;if(!t)continue;let r=Mf(a,`${t}/${kf(e.title||`page`)}`);n.file(`${r}.md`,Tf(e)),o.set(e.id,r)}return{blob:await n.generateAsync({type:`blob`}),filename:`${kf(i.title||`export`)}${t.hierarchy?`-tree`:``}.zip`}}function Pf(e,t,n=null){let r=Of(t,e.split(/[/\\]/).pop()||`page.md`),i=t;return i=i.replace(RegExp(`^#\\s+${Ff(r)}\\s*\\n+`),``),{tempId:o(`imp`),title:r,icon:`📝`,parentTempId:n,blocks:Df(i),relPath:e}}function Ff(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function If(e){let t=e.map(e=>({path:e.path.replace(/\\/g,`/`).replace(/^\.\//,``),content:e.content})).filter(e=>e.path.toLowerCase().endsWith(`.md`)),n=new Map,r=[],i=e=>{if(!e||e===`.`)return null;if(n.has(e))return n.get(e);let t=e.split(`/`),a=t[t.length-1],s=t.slice(0,-1).join(`/`),c=s?i(s):null,l=o(`imp`);return n.set(e,l),r.push({tempId:l,title:a,icon:`📁`,parentTempId:c,blocks:[{id:o(`b`),type:`paragraph`,content:`Folder: ${a}`,indent:0}],relPath:e+`/`}),l};t.sort((e,t)=>e.path.localeCompare(t.path));for(let e of t){let t=e.path.split(`/`),n=t.pop(),a=t.join(`/`),o=a?i(a):null;r.push(Pf(n,e.content,o)),r[r.length-1].relPath=e.path}return r}function Lf(e,t){let n=new Map,r=[],i=[];for(let t of e)n.set(t.tempId,o(`page`));for(let a of e){let e=n.get(a.tempId),o=a.parentTempId?n.get(a.parentTempId)??t:t,s=l({id:e,title:a.title,icon:a.icon,parentId:o,blocks:a.blocks});r.push(s),a.parentTempId||i.push(e)}return{pages:r,rootIds:i}}function Rf(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),URL.revokeObjectURL(n)}function zf({open:e,onOpenChange:t,initialTab:n=`export`,pageId:r}){let i=m(e=>e.pages),a=m(e=>e.activePageId),o=m(e=>e.importPages),s=m(e=>e.setActivePage),c=r??a,l=i.find(e=>e.id===c),[u,d]=(0,z.useState)(n),[f,p]=(0,z.useState)(!0),[h,g]=(0,z.useState)(!1),[_,v]=(0,z.useState)(`/workspace/markdown-mounts/export`),[y,b]=(0,z.useState)(!0),x=(0,z.useRef)(null),S=(0,z.useRef)(null),C=async()=>{if(c){g(!0);try{let{blob:e,filename:t}=await Nf(i,{rootId:c,hierarchy:f});Rf(e,t),af.success(`Markdown zip downloaded`)}catch(e){af.error(e instanceof Error?e.message:`Export failed`)}finally{g(!1)}}},T=()=>{if(!l)return;let e=Tf(l);Rf(new Blob([e],{type:`text/markdown`}),`${kf(l.title||`page`)}.md`),af.success(`Markdown file downloaded`)},E=async()=>{if(c){g(!0);try{let{blob:e}=await Nf(i,{rootId:c,hierarchy:f}),t=await Sf.default.loadAsync(e),n=[],r=Object.keys(t.files);for(let e of r){let r=t.files[e];r.dir||n.push({relPath:e,content:await r.async(`string`)})}let a=await Ud({data:{targetDir:_,files:n}});af.success(`Wrote ${a.count} files to ${a.dir}`)}catch(e){af.error(e instanceof Error?e.message:`Server export failed`)}finally{g(!1)}}},D=e=>{let{pages:n,rootIds:r}=Lf(e.length===1?[Pf(e[0].path,e[0].content)]:If(e),y?c??null:null);o(n,r[0]??n[0]?.id??null),r[0]&&s(r[0]),af.success(`Imported ${n.length} page${n.length===1?``:`s`}`),t(!1)},O=async e=>{if(e?.length){g(!0);try{let t=[];for(let n of Array.from(e))if(!(!n.name.toLowerCase().endsWith(`.md`)&&!n.name.toLowerCase().endsWith(`.zip`)))if(n.name.toLowerCase().endsWith(`.zip`)){let e=await Sf.default.loadAsync(await n.arrayBuffer());for(let n of Object.keys(e.files)){let r=e.files[n];r.dir||!n.toLowerCase().endsWith(`.md`)||t.push({path:n,content:await r.async(`string`)})}}else{let e=n.webkitRelativePath||n.name;t.push({path:e,content:await n.text()})}if(!t.length){af.error(`No markdown files found`);return}D(t)}catch(e){af.error(e instanceof Error?e.message:`Import failed`)}finally{g(!1)}}};return(0,K.jsx)(Gu,{open:e,onOpenChange:t,children:(0,K.jsxs)(Ju,{className:`max-w-lg`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsxs)(Xu,{className:`flex items-center gap-2`,children:[(0,K.jsx)(ge,{className:`size-4`}),`Markdown import / export`]}),(0,K.jsxs)(Zu,{children:[`Move pages as folders of `,(0,K.jsx)(`code`,{className:`text-xs`,children:`.md`}),` files — or export a hierarchy.`]})]}),(0,K.jsx)(`div`,{className:`flex gap-1 rounded-lg border border-border p-1`,children:[`export`,`import`].map(e=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>d(e),className:u===e?`flex-1 rounded-md bg-foreground px-3 py-1.5 text-sm font-medium text-background`:`flex-1 rounded-md px-3 py-1.5 text-sm text-muted-foreground hover:bg-muted`,children:e===`export`?`Export`:`Import`},e))}),u===`export`?(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,K.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Current page:`,` `,(0,K.jsxs)(`span`,{className:`font-medium text-foreground`,children:[l?.icon,` `,l?.title||`Untitled`]})]}),(0,K.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:f,onChange:e=>p(e.target.checked)}),`Include child pages (folder hierarchy)`]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsxs)(w,{type:`button`,disabled:h||!l,onClick:()=>void C(),children:[h?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(le,{className:`size-4`}),`Download as .zip`]}),(0,K.jsx)(w,{type:`button`,variant:`outline`,disabled:!l||f,onClick:T,children:`Download single .md`})]}),(0,K.jsxs)(`div`,{className:`space-y-2 rounded-lg border border-border p-3`,children:[(0,K.jsx)(`p`,{className:`text-xs font-medium text-foreground`,children:`Write to server folder`}),(0,K.jsx)(k,{value:_,onChange:e=>v(e.target.value)}),(0,K.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Allowed under `,(0,K.jsx)(`code`,{children:`/workspace`}),` (e.g.`,` `,(0,K.jsx)(`code`,{children:`/workspace/markdown-mounts/export`}),`)`]}),(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`secondary`,disabled:h||!l,onClick:()=>void E(),children:[(0,K.jsx)(ge,{className:`size-3.5`}),` Write markdown dir`]})]})]}):(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,K.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:y,onChange:e=>b(e.target.checked)}),`Nest under current page`]}),(0,K.jsx)(`input`,{ref:x,type:`file`,accept:`.md,.zip,text/markdown,application/zip`,multiple:!0,className:`hidden`,onChange:e=>void O(e.target.files)}),(0,K.jsx)(`input`,{ref:S,type:`file`,webkitdirectory:``,directory:``,multiple:!0,className:`hidden`,onChange:e=>void O(e.target.files)}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsxs)(w,{type:`button`,disabled:h,onClick:()=>x.current?.click(),children:[h?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(nt,{className:`size-4`}),`Import .md or .zip`]}),(0,K.jsxs)(w,{type:`button`,variant:`outline`,disabled:h,onClick:()=>S.current?.click(),children:[(0,K.jsx)(me,{className:`size-4`}),` Import folder of markdown`]})]}),(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Folders become parent pages; each `,(0,K.jsx)(`code`,{children:`.md`}),` becomes a page. Content is copied into the workspace (unlike linked mounts).`]})]})]})})}var Bf=$({method:`GET`}).handler(p(`19e00543f0313fe7905c045b33772265c61fa51d18574d69244c3f084698fddb`));$({method:`GET`}).handler(p(`9869410eeb67daab81f5d2ed574198eae379b3efb7eb41fe5a887f5ee51051d9`));var Vf=$({method:`POST`}).handler(p(`3a3b06354c92fa523d323b08f8cb2c04194a6d325c5629dfe4c092272682e98a`)),Hf=$({method:`POST`}).handler(p(`64ebef571e60681eaece2b296de9be5f6f33209c413aad1e4ff65d57e56c9c83`));function Uf({open:e,onOpenChange:t}){let[n,r]=(0,z.useState)([]),[i,a]=(0,z.useState)([]),[o,c]=(0,z.useState)([]),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(`mock`),[h,g]=(0,z.useState)(`JWT authentication`),[_,v]=(0,z.useState)(`hello`),[y,b]=(0,z.useState)(`What is a meta-harness?`),[x,S]=(0,z.useState)(`jwt-auth.yaml`),[C,T]=(0,z.useState)(null),[E,D]=(0,z.useState)(`workflow`),[O,A]=(0,z.useState)(null);if((0,z.useEffect)(()=>{e&&(u(!0),A(null),Bf().then(e=>{r(e.backends),a(e.agents),c(e.workflows),e.agents[0]&&v(e.agents[0].replace(/\.ya?ml$/,``));let t=e.workflows.find(e=>e.includes(`jwt`));t?S(t):e.workflows[0]&&S(e.workflows[0])}).catch(e=>A(e instanceof Error?e.message:`Failed to load harness`)).finally(()=>u(!1)))},[e]),!e)return null;let j=async()=>{f(!0),T(null),A(null);try{let e=await Hf({data:{workflow:x,feature:h||`feature`,backend:p||`mock`}});T(e),af.success(`Workflow done · ${e.runId}`)}catch(e){let t=e instanceof Error?e.message:`Run failed`;A(t),af.error(t)}finally{f(!1)}},M=async()=>{f(!0),T(null),A(null);try{let e=await Vf({data:{agent:_,message:y,backend:p||`mock`}});T(e),af.success(`Agent done · ${e.runId}`)}catch(e){let t=e instanceof Error?e.message:`Run failed`;A(t),af.error(t)}finally{f(!1)}};return(0,K.jsxs)(`div`,{className:`fixed inset-0 z-[120] flex items-center justify-center p-4`,children:[(0,K.jsx)(`button`,{type:`button`,className:`absolute inset-0 z-0 bg-black/40`,"aria-label":`Dismiss`,onClick:()=>{d||t(!1)}}),(0,K.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`harness-title`,className:`relative z-10 flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-border bg-background shadow-2xl`,onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsxs)(`div`,{className:`border-b border-border px-6 py-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`h2`,{id:`harness-title`,className:`flex items-center gap-2 text-lg font-semibold`,children:[(0,K.jsx)(Qe,{className:`size-4`}),`Meta-harness · CLI agents`]}),(0,K.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Plan → Implement → Review → Validate. Swap backends without rewriting the workflow.`})]}),(0,K.jsx)(`button`,{type:`button`,className:`rounded-md p-1.5 text-muted-foreground hover:bg-muted`,onClick:()=>t(!1),"aria-label":`Close`,children:(0,K.jsx)(ot,{className:`size-4`})})]}),(0,K.jsx)(`div`,{className:`mt-3 flex flex-wrap gap-1.5`,children:[[`workflow`,`Workflow`,at],[`agent`,`Single agent`,re],[`backends`,`Backends`,st]].map(([e,t,n])=>(0,K.jsxs)(`button`,{type:`button`,onClick:()=>D(e),className:s(`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium`,E===e?`bg-foreground text-background`:`bg-muted text-muted-foreground`),children:[(0,K.jsx)(n,{className:`size-3`}),t]},e))})]}),(0,K.jsx)(`div`,{className:`min-h-0 flex-1 space-y-4 overflow-y-auto px-6 py-5 text-sm`,children:l?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,K.jsx)(ke,{className:`size-4 animate-spin`}),` Loading harness…`]}):(0,K.jsxs)(K.Fragment,{children:[O&&(0,K.jsx)(`div`,{className:`rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive`,children:O}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Backend slot (executor.harness)`}),(0,K.jsx)(`select`,{className:`h-9 w-full rounded-md border border-border bg-background px-2 text-sm`,value:p,onChange:e=>m(e.target.value),children:n.map(e=>(0,K.jsxs)(`option`,{value:e.id,children:[e.available?`●`:`○`,` `,e.label,` (`,e.id,`)`]},e.id))})]}),E===`workflow`&&(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Workflow`}),(0,K.jsx)(`select`,{className:`h-9 w-full rounded-md border border-border bg-background px-2 text-sm`,value:x,onChange:e=>S(e.target.value),children:o.map(e=>(0,K.jsx)(`option`,{value:e,children:e},e))})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Feature`}),(0,K.jsx)(k,{value:h,onChange:e=>g(e.target.value)})]}),(0,K.jsxs)(w,{type:`button`,disabled:d||!x,onClick:()=>void j(),children:[d?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(Re,{className:`size-4`}),`Run workflow`]}),(0,K.jsx)(`pre`,{className:`overflow-x-auto rounded-lg border border-border bg-muted/40 p-3 text-[11px] leading-relaxed text-muted-foreground`,children:`wks harness workflow ${x.replace(/\.ya?ml$/,``)} \\\n --feature "${h}" --backend ${p}`})]}),E===`agent`&&(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Agent YAML`}),(0,K.jsx)(`select`,{className:`h-9 w-full rounded-md border border-border bg-background px-2 text-sm`,value:_,onChange:e=>v(e.target.value),children:i.map(e=>(0,K.jsx)(`option`,{value:e.replace(/\.ya?ml$/,``),children:e},e))})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Message`}),(0,K.jsx)(k,{value:y,onChange:e=>b(e.target.value)})]}),(0,K.jsxs)(w,{type:`button`,disabled:d,onClick:()=>void M(),children:[d?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(Re,{className:`size-4`}),`Run agent`]}),(0,K.jsx)(`pre`,{className:`overflow-x-auto rounded-lg border border-border bg-muted/40 p-3 text-[11px] text-muted-foreground`,children:`wks harness run ${_} --message "${y}" --backend ${p}`})]}),E===`backends`&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Install CLIs locally for live runs; `,(0,K.jsx)(`strong`,{children:`mock`}),` always works in preview. Grok Build via `,(0,K.jsx)(`code`,{children:`grok agent stdio`}),` (ACP).`]}),n.map(e=>(0,K.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-border px-3 py-2`,children:[(0,K.jsx)(`span`,{className:s(`mt-0.5 size-2 shrink-0 rounded-full`,e.available?`bg-emerald-500`:`bg-muted-foreground/40`)}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(`div`,{className:`font-medium`,children:e.label}),(0,K.jsxs)(`div`,{className:`text-[11px] text-muted-foreground`,children:[(0,K.jsx)(`code`,{children:e.id}),e.command?` · ${e.command}`:``]}),e.notes&&(0,K.jsx)(`p`,{className:`mt-0.5 text-[11px] text-muted-foreground`,children:e.notes})]}),e.available&&(0,K.jsx)(U,{className:`size-3.5 text-emerald-600`})]},e.id))]}),C&&(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border p-3`,"data-testid":`harness-result`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[(0,K.jsx)(`span`,{className:s(`rounded-full px-2 py-0.5 font-medium`,C.ok?`bg-emerald-500/15 text-emerald-800 dark:text-emerald-300`:`bg-destructive/10 text-destructive`),children:C.ok?`ok`:`failed`}),(0,K.jsxs)(`span`,{"data-volatile":!0,className:`text-muted-foreground`,children:[C.runId,` · `,C.backend,` · `,C.durationMs,`ms`]}),C.planPath&&(0,K.jsxs)(`span`,{className:`text-muted-foreground`,children:[`plan: `,C.planPath]})]}),(0,K.jsx)(`pre`,{className:`max-h-48 overflow-auto whitespace-pre-wrap rounded-md bg-muted/50 p-2 text-[11px] leading-relaxed`,children:C.summary})]})]})})]})]})}function Wf(){if(typeof window>`u`)return!1;let e=window;return!!(e.__TAURI_INTERNALS__||e.__TAURI__||e.__WORKSPACE_DESKTOP__)}async function Gf(){if(!Wf())return null;try{let{invoke:e}=await y(async()=>{let{invoke:e}=await import(`./core-CwxXejkd.js`);return{invoke:e}},[]);return await e(`desktop_info`)}catch{return{isDesktop:!0}}}function Kf({icon:e,label:t,onClick:n}){return(0,K.jsxs)(`button`,{type:`button`,onClick:n,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-sidebar-fg transition-colors hover:bg-sidebar-hover`,children:[e,(0,K.jsx)(`span`,{className:`truncate`,children:t})]})}function qf({onOpenSearch:e,mobile:t,onNavigate:n}){let r=m(e=>e.name),i=m(e=>e.pages),o=m(e=>e.activePageId),c=m(e=>e.theme),l=m(e=>e.storageMode),u=m(e=>e.syncStatus),d=m(e=>e.setActivePage),f=m(e=>e.createPage),p=m(e=>e.deletePage),h=m(e=>e.restorePage),g=m(e=>e.permanentlyDeletePage),_=m(e=>e.duplicatePage),v=m(e=>e.updatePage),y=m(e=>e.toggleSidebar),b=m(e=>e.setTheme),x=m(e=>e.setName),S=m(e=>e.resetWorkspace),{user:C}=D(),[T,E]=(0,z.useState)({}),[O,k]=(0,z.useState)(!1),[A,j]=(0,z.useState)(!1),[M,N]=(0,z.useState)(!1),[P,F]=(0,z.useState)(`welcome`),I=vd(),[L,R]=(0,z.useState)(!1),[B,V]=(0,z.useState)(!1),[ee,H]=(0,z.useState)(!1),te=jd(e=>e.mounts),ne=jd(e=>e.selection),re=jd(e=>e.setSelection),U=jd(e=>e.removeMount),[se,le]=(0,z.useState)({mount_sample:!0}),[de,pe]=(0,z.useState)({}),[me,he]=(0,z.useState)(null),[ge,_e]=(0,z.useState)(null);(0,z.useEffect)(()=>{Wf()&&Gf().then(e=>{e?.isDesktop&&he(e.platform?`Desktop · ${e.platform}`:`Desktop app`)})},[]),(0,z.useEffect)(()=>{dd().then(e=>{let t=e.clis;t?.length&&_e(t.map(e=>`${e.label.split(` `)[0]} ${e.available?`✓`:`·`}`).join(` · `))}).catch(()=>_e(null))},[]);let ve=(0,z.useCallback)(e=>{d(e),re(null),n?.()},[d,re,n]),ye=(0,z.useMemo)(()=>i.filter(e=>!e.archived&&e.favorite),[i]),be=(0,z.useMemo)(()=>i.filter(e=>e.archived),[i]),xe=(0,z.useMemo)(()=>i.filter(e=>!e.archived&&!e.parentId).sort((e,t)=>e.createdAt-t.createdAt),[i]),Se=(0,z.useCallback)(e=>i.filter(t=>!t.archived&&t.parentId===e).sort((e,t)=>e.createdAt-t.createdAt),[i]),Ce=async e=>{let t=te.find(t=>t.id===e);if(t)try{if(t.kind===`server`&&t.serverPath){let n=await Bd({data:{root:t.serverPath,relPath:``}}),r=Array.isArray(n)?n:[];pe(t=>({...t,[e]:r.map(e=>({name:e.name,relPath:e.relPath,kind:e.kind}))}))}else if(t.kind===`browser`){let t=await Id(e);if(!t){pe(t=>({...t,[e]:[]}));return}let n=await Ld(t,``);pe(t=>({...t,[e]:n}))}}catch{pe(t=>({...t,[e]:[]}))}},Te=(e,t)=>{re({mountId:e,relPath:t}),d(null),n?.()},Ee=(e,t)=>(e===null?xe:Se(e)).map(e=>{let n=Se(e.id).length>0,r=T[e.id]??t<1;return(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`div`,{className:s(`group flex items-center gap-0.5 rounded-md pr-1`,o===e.id&&!ne?`bg-sidebar-active text-foreground`:`hover:bg-sidebar-hover`),style:{paddingLeft:8+t*12},children:[(0,K.jsx)(`button`,{type:`button`,className:`flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground`,onClick:()=>E(t=>({...t,[e.id]:!r})),"aria-label":r?`Collapse`:`Expand`,children:n?r?(0,K.jsx)(ie,{className:`size-3.5`}):(0,K.jsx)(ae,{className:`size-3.5`}):(0,K.jsx)(`span`,{className:`size-3.5`})}),(0,K.jsxs)(`button`,{type:`button`,className:`flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm`,onClick:()=>ve(e.id),children:[(0,K.jsx)(`span`,{className:`shrink-0 text-sm`,children:e.icon||`📄`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.title||`Untitled`})]}),(0,K.jsxs)(`div`,{"data-hover-reveal":!0,className:`flex items-center opacity-0 group-hover:opacity-100`,children:[(0,K.jsxs)(lu,{children:[(0,K.jsx)(uu,{asChild:!0,children:(0,K.jsx)(`button`,{type:`button`,className:`flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10`,"aria-label":`Page menu`,children:(0,K.jsx)(ue,{className:`size-3.5 text-muted-foreground`})})}),(0,K.jsxs)(mu,{align:`start`,className:`w-48`,children:[(0,K.jsxs)(hu,{onClick:()=>v(e.id,{favorite:!e.favorite}),children:[(0,K.jsx)(Ye,{className:`size-4`}),e.favorite?`Unfavorite`:`Favorite`]}),(0,K.jsxs)(hu,{onClick:()=>{f({parentId:e.id}),E(t=>({...t,[e.id]:!0}))},children:[(0,K.jsx)(ze,{className:`size-4`}),` Add sub-page`]}),(0,K.jsxs)(hu,{onClick:()=>_(e.id),children:[(0,K.jsx)(ce,{className:`size-4`}),` Duplicate`]}),(0,K.jsx)(_u,{}),(0,K.jsxs)(hu,{className:`text-destructive focus:text-destructive`,onClick:()=>p(e.id),children:[(0,K.jsx)($e,{className:`size-4`}),` Delete`]})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10`,"aria-label":`New sub-page`,onClick:()=>{f({parentId:e.id}),E(t=>({...t,[e.id]:!0}))},children:(0,K.jsx)(ze,{className:`size-3.5 text-muted-foreground`})})]})]}),n&&r&&Ee(e.id,t+1)]},e.id)}),De=l===`database`?u===`saving`||u===`pending`?(0,K.jsx)(oe,{className:`size-3.5 animate-pulse text-muted-foreground`}):u===`error`?(0,K.jsx)(W,{className:`size-3.5 text-destructive`}):(0,K.jsx)(oe,{className:`size-3.5 text-emerald-600`}):(0,K.jsx)(W,{className:`size-3.5 text-muted-foreground`});return(0,K.jsxs)(`aside`,{className:s(`flex h-full flex-col border-r border-sidebar-border bg-sidebar text-sidebar-fg`,t?`w-full`:`w-[260px] min-w-[260px]`),children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-3`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-sidebar-hover`,onClick:()=>j(!0),children:[(0,K.jsx)(`span`,{className:`flex size-6 shrink-0 items-center justify-center rounded-md bg-foreground text-[11px] font-semibold text-background`,children:r.slice(0,1).toUpperCase()||`W`}),(0,K.jsx)(`span`,{className:`truncate text-sm font-semibold text-foreground`,children:r}),De]}),!t&&(0,K.jsx)(`button`,{type:`button`,className:`flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-sidebar-hover`,onClick:()=>y(),"aria-label":`Collapse sidebar`,children:(0,K.jsx)(Ie,{className:`size-4`})})]}),me&&(0,K.jsxs)(`div`,{className:`mx-3 mb-1 flex items-center gap-1.5 rounded-md bg-muted/50 px-2 py-1 text-[10px] font-medium text-muted-foreground`,children:[(0,K.jsx)(Pe,{className:`size-3`}),me]}),(0,K.jsxs)(`div`,{className:`space-y-0.5 px-2 py-1`,children:[(0,K.jsx)(Kf,{icon:(0,K.jsx)(We,{className:`size-4`}),label:`Search`,onClick:e}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(ze,{className:`size-4`}),label:`New page`,onClick:()=>{let e=f();ve(e)}}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(fe,{className:`size-4`}),label:`Import / export`,onClick:()=>V(!0)}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(we,{className:`size-4`}),label:`Link markdown`,onClick:()=>R(!0)}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(Qe,{className:`size-4`}),label:`Agent harness`,onClick:()=>H(!0)})]}),(0,K.jsxs)(ao,{className:`min-h-0 flex-1 px-2`,children:[ye.length>0&&(0,K.jsxs)(`div`,{className:`mb-3`,children:[(0,K.jsx)(`div`,{className:`px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Favorites`}),ye.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:s(`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm`,o===e.id&&!ne?`bg-sidebar-active text-foreground`:`hover:bg-sidebar-hover`),onClick:()=>ve(e.id),children:[(0,K.jsx)(`span`,{children:e.icon||`📄`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.title||`Untitled`})]},e.id))]}),(0,K.jsxs)(`div`,{className:`mb-3`,children:[(0,K.jsx)(`div`,{className:`px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Private`}),Ee(null,0),xe.length===0&&(0,K.jsx)(`p`,{className:`px-2 py-2 text-xs text-muted-foreground`,children:`No pages yet`})]}),(0,K.jsxs)(`div`,{className:`mb-3`,children:[(0,K.jsx)(`div`,{className:`px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Linked markdown`}),te.map(e=>{let t=se[e.id]??!1,n=de[e.id]??[];return(0,K.jsxs)(`div`,{className:`mb-0.5`,children:[(0,K.jsxs)(`div`,{className:`group flex items-center gap-0.5 rounded-md pr-1 hover:bg-sidebar-hover`,children:[(0,K.jsx)(`button`,{type:`button`,className:`flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground`,onClick:()=>{le(n=>({...n,[e.id]:!t})),t||Ce(e.id)},children:t?(0,K.jsx)(ie,{className:`size-3.5`}):(0,K.jsx)(ae,{className:`size-3.5`})}),(0,K.jsxs)(`button`,{type:`button`,className:`flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm`,onClick:()=>{le(t=>({...t,[e.id]:!0})),Ce(e.id),Te(e.id,``)},children:[(0,K.jsx)(we,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,K.jsx)(`span`,{className:`truncate font-medium`,children:e.name})]}),(0,K.jsx)(`button`,{type:`button`,"data-hover-reveal":!0,className:`flex size-6 items-center justify-center rounded opacity-0 group-hover:opacity-100 hover:bg-black/5`,title:`Unlink`,onClick:()=>U(e.id),children:(0,K.jsx)(tt,{className:`size-3 text-muted-foreground`})})]}),t&&n.map(t=>(0,K.jsxs)(`button`,{type:`button`,className:s(`flex w-full items-center gap-2 rounded-md py-1.5 pl-8 pr-2 text-left text-sm`,ne?.mountId===e.id&&ne.relPath===t.relPath?`bg-sidebar-active text-foreground`:`text-sidebar-fg hover:bg-sidebar-hover`),onClick:()=>void Te(e.id,t.relPath),children:[(0,K.jsx)(`span`,{className:`text-xs`,children:t.kind===`dir`?`📁`:`📝`}),(0,K.jsx)(`span`,{className:`truncate`,children:t.name})]},t.relPath))]},e.id)}),(0,K.jsx)(`p`,{className:`px-2 py-1 text-[11px] text-muted-foreground`,children:`Link folder (no import)`})]})]}),(0,K.jsxs)(`div`,{className:`space-y-0.5 border-t border-sidebar-border px-2 py-2`,children:[!C&&(0,K.jsxs)(a,{to:`/login`,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-sidebar-hover`,children:[(0,K.jsx)(Ae,{className:`size-4`}),`Sign in to sync`]}),C&&(0,K.jsx)(`div`,{className:`px-1 py-1`,children:(0,K.jsx)(Qu,{})}),!C&&(0,K.jsx)(`p`,{className:`px-2 py-0.5 text-[11px] text-muted-foreground`,children:`Local only · Sign in to sync`}),(0,K.jsx)(Kf,{icon:(0,K.jsx)($e,{className:`size-4`}),label:`Trash`,onClick:()=>k(!0)}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(Ge,{className:`size-4`}),label:`Settings`,onClick:()=>j(!0)})]}),(0,K.jsx)(Gu,{open:O,onOpenChange:k,children:(0,K.jsxs)(Ju,{className:`max-w-md`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsx)(Xu,{children:`Trash`}),(0,K.jsx)(Zu,{children:`Restored pages return to the top level of your workspace.`})]}),(0,K.jsxs)(`div`,{className:`max-h-72 space-y-1 overflow-y-auto`,children:[be.length===0&&(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Trash is empty`}),be.map(e=>(0,K.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-border px-2 py-1.5`,children:[(0,K.jsx)(`span`,{children:e.icon||`📄`}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm`,children:e.title||`Untitled`}),(0,K.jsx)(w,{size:`sm`,variant:`outline`,onClick:()=>h(e.id),children:`Restore`}),(0,K.jsx)(w,{size:`sm`,variant:`ghost`,className:`text-destructive`,onClick:()=>g(e.id),children:`Delete`})]},e.id))]})]})}),(0,K.jsx)(Gu,{open:A,onOpenChange:j,children:(0,K.jsxs)(Ju,{className:`max-w-md`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsx)(Xu,{children:`Settings`}),(0,K.jsx)(Zu,{children:`Workspace preferences and AI`})]}),(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[me&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs`,children:[(0,K.jsx)(Pe,{className:`size-3.5`}),`Running as `,me,(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`· Tauri standalone`})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Workspace name`}),(0,K.jsx)(`input`,{className:`h-9 w-full rounded-md border border-border bg-background px-3 text-sm`,value:r,onChange:e=>x(e.target.value)})]}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`span`,{className:`text-sm`,children:`Theme`}),(0,K.jsxs)(`div`,{className:`flex gap-1`,children:[(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:c===`light`?`default`:`outline`,onClick:()=>b(`light`),children:[(0,K.jsx)(Xe,{className:`size-3.5`}),` Light`]}),(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:c===`dark`?`default`:`outline`,onClick:()=>b(`dark`),children:[(0,K.jsx)(Fe,{className:`size-3.5`}),` Dark`]})]})]}),(0,K.jsxs)(`div`,{className:`rounded-lg border border-border p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 font-medium`,children:[(0,K.jsx)(Ke,{className:`size-4`}),` AI`]}),(0,K.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Backend: `,hd[I.backend]?.label??I.backend,!hd[I.backend]?.isCli&&(0,K.jsxs)(K.Fragment,{children:[` `,`· `,gd[I.provider]?.label,` · `,I.model]})]}),ge&&(0,K.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`CLIs: `,ge]}),(0,K.jsx)(w,{type:`button`,size:`sm`,className:`mt-2`,variant:`secondary`,onClick:()=>{F(`provider`),N(!0)},children:`Configure AI`})]}),(0,K.jsxs)(`div`,{className:`rounded-lg border border-border p-3 text-xs text-muted-foreground`,children:[`Storage: `,l===`database`?`Database (synced)`:`Local only`,l===`database`&&` · ${u}`]}),(0,K.jsxs)(w,{type:`button`,variant:`outline`,className:`w-full text-destructive`,onClick:()=>{confirm(`Reset workspace to seed pages? This cannot be undone.`)&&(S(),j(!1))},children:[(0,K.jsx)(He,{className:`size-4`}),` Reset workspace`]})]})]})}),(0,K.jsx)(zf,{open:B,onOpenChange:V}),(0,K.jsx)(xf,{open:L,onOpenChange:R}),(0,K.jsx)(Uf,{open:ee,onOpenChange:H}),(0,K.jsx)(xd,{open:M,onOpenChange:N,initialStep:P})]})}var Jf=Object.defineProperty,Yf=(e,t)=>Jf(e,`name`,{value:t,configurable:!0}),Xf=`Popover`,[Zf,Qf]=vt(Xf,[ui]),$f=ui(),[ep,tp]=Zf(Xf),np=Yf(e=>{let{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!1}=e,s=$f(t),c=z.useRef(null),[l,u]=z.useState(!1),[d,f]=z.useState(0),[p,m]=z.useState(0),[h,g]=Hi({prop:r,defaultProp:i??!1,onChange:a,caller:Xf});return(0,K.jsx)(pi,{...s,children:(0,K.jsx)(ep,{scope:t,contentId:Y(),titleId:Y(),descriptionId:Y(),titlePresent:d>0,descriptionPresent:p>0,setTitleCount:f,setDescriptionCount:m,triggerRef:c,open:h,onOpenChange:g,onOpenToggle:z.useCallback(()=>g(e=>!e),[g]),hasCustomAnchor:l,onCustomAnchorAdd:z.useCallback(()=>u(!0),[]),onCustomAnchorRemove:z.useCallback(()=>u(!1),[]),modal:o,children:n})})},`Popover`),rp=`PopoverTrigger`,ip=z.forwardRef(Yf(function(e,t){let{__scopePopover:n,...r}=e,i=tp(rp,n),a=$f(n),o=C(t,i.triggerRef),s=(0,K.jsx)(q.button,{type:`button`,"aria-haspopup":`dialog`,"aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":hp(i.open),...r,ref:o,onClick:G(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?s:(0,K.jsx)(hi,{asChild:!0,...a,children:s})},`PopoverTrigger`)),ap=`PopoverPortal`,[op,sp]=Zf(ap,{forceMount:void 0}),cp=Yf(e=>{let{__scopePopover:t,forceMount:n,children:r,container:i}=e,a=tp(ap,t);return(0,K.jsx)(op,{scope:t,forceMount:n,children:(0,K.jsx)(Oi,{present:n||a.open,children:(0,K.jsx)(wi,{asChild:!0,container:i,children:r})})})},`PopoverPortal`),lp=`PopoverContent`,up=z.forwardRef(Yf(function(e,t){let n=sp(lp,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,a=tp(lp,e.__scopePopover);return(0,K.jsx)(Oi,{present:r||a.open,children:a.modal?(0,K.jsx)(fp,{...i,ref:t}):(0,K.jsx)(pp,{...i,ref:t})})},`PopoverContent`)),dp=S(`PopoverContent.RemoveScroll`),fp=z.forwardRef(Yf(function(e,t){let n=tp(lp,e.__scopePopover),r=z.useRef(null),i=C(t,r),a=z.useRef(!1);return z.useEffect(()=>{let e=r.current;if(e)return Ds(e)},[]),(0,K.jsx)(Ic,{as:dp,allowPinchZoom:!0,children:(0,K.jsx)(mp,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:G(e.onCloseAutoFocus,e=>{e.preventDefault(),a.current||n.triggerRef.current?.focus()}),onPointerDownOutside:G(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0,r=t.button===2||n;a.current=r},{checkForDefaultPrevented:!1}),onFocusOutside:G(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})},`PopoverContentModal`)),pp=z.forwardRef(Yf(function(e,t){let n=tp(lp,e.__scopePopover),r=z.useRef(!1),i=z.useRef(!1);return(0,K.jsx)(mp,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})},`PopoverContentNonModal`)),mp=z.forwardRef(Yf(function(e,t){let{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:o,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:l,onInteractOutside:u,"aria-describedby":d,...f}=e,p=tp(lp,n),m=$f(n);return To(),(0,K.jsx)(Mo,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,K.jsx)(Nt,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:u,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:l,onDismiss:()=>p.onOpenChange(!1),deferPointerDownOutside:!0,children:(0,K.jsx)(yi,{"data-state":hp(p.open),role:`dialog`,id:p.contentId,"aria-labelledby":p.titlePresent?p.titleId:void 0,"aria-describedby":p.descriptionPresent?gp(d,p.descriptionId):d,...m,...f,ref:t,style:{...f.style,"--radix-popover-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-popover-content-available-width":`var(--radix-popper-available-width)`,"--radix-popover-content-available-height":`var(--radix-popper-available-height)`,"--radix-popover-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-popover-trigger-height":`var(--radix-popper-anchor-height)`}})})})},`PopoverContentImpl`));function hp(e){return e?`open`:`closed`}Yf(hp,`getState`);function gp(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}Yf(gp,`concatAriaDescribedby`);var _p=np,vp=ip;function yp({className:e,align:t=`center`,sideOffset:n=6,...r}){return(0,K.jsx)(cp,{children:(0,K.jsx)(up,{align:t,sideOffset:n,className:s(`z-50 w-72 rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-lg outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95`,e),...r})})}var bp=[{type:`paragraph`,label:`Text`,description:`Just start writing with plain text.`,icon:et,keywords:[`text`,`paragraph`,`plain`],placeholder:`Type '/' for commands`},{type:`heading1`,label:`Heading 1`,description:`Big section heading.`,icon:be,keywords:[`h1`,`title`,`heading`],placeholder:`Heading 1`},{type:`heading2`,label:`Heading 2`,description:`Medium section heading.`,icon:xe,keywords:[`h2`,`heading`,`subtitle`],placeholder:`Heading 2`},{type:`heading3`,label:`Heading 3`,description:`Small section heading.`,icon:Se,keywords:[`h3`,`heading`],placeholder:`Heading 3`},{type:`bullet`,label:`Bulleted list`,description:`Create a simple bulleted list.`,icon:Oe,keywords:[`ul`,`list`,`bullet`,`unordered`],placeholder:`List item`},{type:`numbered`,label:`Numbered list`,description:`Create a list with numbering.`,icon:Te,keywords:[`ol`,`list`,`number`,`ordered`],placeholder:`List item`},{type:`todo`,label:`To-do list`,description:`Track tasks with a to-do checkbox.`,icon:qe,keywords:[`todo`,`task`,`checkbox`,`check`],placeholder:`To-do`},{type:`toggle`,label:`Toggle`,description:`Hide and show content inside.`,icon:ae,keywords:[`toggle`,`collapse`,`details`],placeholder:`Toggle heading`},{type:`quote`,label:`Quote`,description:`Capture a quote.`,icon:Ve,keywords:[`quote`,`blockquote`,`cite`],placeholder:`Empty quote`},{type:`callout`,label:`Callout`,description:`Make writing stand out.`,icon:Me,keywords:[`callout`,`note`,`info`,`tip`],placeholder:`Callout`},{type:`code`,label:`Code`,description:`Capture a code snippet.`,icon:se,keywords:[`code`,`snippet`,`pre`],placeholder:`Code`},{type:`mermaid`,label:`Mermaid`,description:`Diagram with Mermaid syntax.`,icon:at,keywords:[`mermaid`,`diagram`,`flowchart`,`sequence`,`graph`],placeholder:`flowchart TD + A[Start] --> B[End]`},{type:`ai`,label:`AI`,description:`Generate from the rest of this page.`,icon:Ke,keywords:[`ai`,`gpt`,`grok`,`summary`,`assistant`,`llm`],placeholder:`Summarize this page as a launch checklist…`},{type:`divider`,label:`Divider`,description:`Visually divide blocks.`,icon:Ne,keywords:[`divider`,`line`,`hr`,`separator`],placeholder:``}];function xp(e){return bp.find(t=>t.type===e)??bp[0]}function Sp(e){let t=e.trim().toLowerCase();return t?bp.filter(e=>e.label.toLowerCase().includes(t)||e.description.toLowerCase().includes(t)||e.keywords.some(e=>e.includes(t))):bp}function Cp({query:e,selectedIndex:t,onSelect:n,onHover:r,position:i}){let a=(0,z.useMemo)(()=>Sp(e),[e]),o=(0,z.useRef)(null);return(0,z.useEffect)(()=>{(o.current?.querySelector(`[data-index="${t}"]`))?.scrollIntoView({block:`nearest`})},[t]),a.length===0?(0,K.jsx)(`div`,{className:`fixed z-50 w-72 overflow-hidden rounded-xl border border-border bg-popover p-3 text-sm text-muted-foreground shadow-xl`,style:{top:i.top,left:i.left},children:`No matching blocks`}):(0,K.jsxs)(`div`,{ref:o,className:`fixed z-50 max-h-72 w-72 overflow-y-auto rounded-xl border border-border bg-popover p-1.5 shadow-xl`,style:{top:i.top,left:Math.min(i.left,window.innerWidth-300)},role:`listbox`,children:[(0,K.jsx)(`div`,{className:`px-2 py-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:`Basic blocks`}),a.map((e,i)=>{let a=e.icon;return(0,K.jsxs)(`button`,{type:`button`,"data-index":i,role:`option`,"aria-selected":i===t,className:s(`flex w-full items-start gap-2.5 rounded-lg px-2 py-2 text-left transition-colors`,i===t?`bg-muted`:`hover:bg-muted/70`),onMouseEnter:()=>r(i),onMouseDown:t=>{t.preventDefault(),n(e.type)},children:[(0,K.jsx)(`span`,{className:`mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground`,children:(0,K.jsx)(a,{className:`size-4`})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),(0,K.jsx)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:e.description})]})]},e.type)})]})}var wp=null;function Tp(){return wp||=y(()=>import(`./mermaid.core-lwoghoVk.js`).then(e=>{let t=e.default;return t.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),t}),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23])),wp}function Ep({source:e,className:t}){let n=(0,z.useId)().replace(/:/g,``),r=(0,z.useRef)(null),[i,a]=(0,z.useState)(null),[o,c]=(0,z.useState)(``);return(0,z.useEffect)(()=>{let t=!1,r=e.trim();if(!r){c(``),a(null);return}return(async()=>{try{let e=await Tp();e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`});let i=`mmd_${n}_${Math.random().toString(36).slice(2,8)}`,{svg:o}=await e.render(i,r);t||(c(o),a(null))}catch(e){t||(c(``),a(e instanceof Error?e.message:`Invalid Mermaid diagram`))}})(),()=>{t=!0}},[e,n]),e.trim()?i?(0,K.jsx)(`div`,{className:`rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive`,children:i}):(0,K.jsx)(`div`,{ref:r,className:s(`overflow-x-auto rounded-md border border-border bg-background px-3 py-4 [&_svg]:mx-auto [&_svg]:max-w-full`,t),dangerouslySetInnerHTML:o?{__html:o}:void 0}):(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Write Mermaid syntax (e.g. flowchart TD) — diagram previews here.`})}async function Dp(e){let t=await fetch(`/api/ai/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({...e.request,clientSettings:e.clientSettings,backend:e.backend}),signal:e.signal});if(!t.ok){let e=await t.text().catch(()=>t.statusText);throw Error(e||`Stream failed (${t.status})`)}if(!t.body)throw Error(`No response body for stream`);let n=t.body.getReader(),r=new TextDecoder,i=``,a=``,o=null,s=null;for(;;){let{done:t,value:c}=await n.read();if(t)break;i+=r.decode(c,{stream:!0});let l=i.split(` + +`);i=l.pop()??``;for(let t of l){let n=t.split(` +`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim()).join(``);if(!n)continue;let r;try{r=JSON.parse(n)}catch{continue}r.type===`token`&&r.text?(a+=r.text,e.onToken?.(r.text,a)):r.type===`status`&&r.message?e.onStatus?.(r.message):r.type===`done`?(r.text&&(a=r.text),o=r.result?r.result:{text:a,provider:`local`},e.onDone?.(o,a)):r.type===`error`&&(s=r.message||`Stream error`,e.onError?.(s))}}if(s&&!o&&!a.trim())throw Error(s);return o??{text:a,provider:`local`}}var Op=[{action:`summarize`,label:`Summary`,icon:pe,hint:`Condense the page`},{action:`action_items`,label:`Todos`,icon:Ee,hint:`Extract action items`},{action:`table`,label:`Table`,icon:Ze,hint:`Markdown table`},{action:`outline`,label:`Outline`,icon:De,hint:`Hierarchical outline`},{action:`mermaid`,label:`Diagram`,icon:at,hint:`Mermaid flowchart`}];function kp(e,t){return e===`claude-cli`?`Claude Code CLI`:e===`codex-cli`?`Codex CLI`:e===`grok-cli`?`Grok CLI`:e===`deepagents`?`Deep Agents · ${t??`model`}`:e===`direct`?t??`Direct API`:e===`xai`?t??`Grok`:`Local demo AI`}function Ap({content:e,aiOutput:t,aiError:n,pageTitle:r,pageText:i,onChangePrompt:a,onResult:o}){let[s,c]=(0,z.useState)(!1),[l,u]=(0,z.useState)(null),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(``),[h,g]=(0,z.useState)(null),_=(0,z.useRef)(null),v=()=>{_.current?.abort(),_.current=null,c(!1),g(`Stopped`)},y=async(t,n)=>{c(!0),m(``),g(null);let a=yd(),s=a.preferStreaming!==!1,l=a.backend===`claude-cli`||a.backend===`codex-cli`||a.backend===`grok-cli`,d=s&&(l||a.backend===`direct`||a.backend===`deepagents`);try{if(d){let s=new AbortController;_.current=s;let c=await Dp({request:{action:t,instruction:n??e,pageTitle:r,pageText:i},clientSettings:a,backend:a.backend,signal:s.signal,onToken:(e,t)=>m(t),onStatus:e=>g(e)});u(kp(c.provider,c.model)),o({output:c.text||(c.blocks?c.blocks.map(e=>`${e.type}: ${e.content}`).join(` +`):``),blocks:c.blocks}),m(``)}else{let s=await cd({data:{action:t,instruction:n??e,pageTitle:r,pageText:i,clientSettings:a}});u(kp(s.provider,s.model)),o({output:s.text||(s.blocks?s.blocks.map(e=>`${e.type}: ${e.content}`).join(` +`):``),blocks:s.blocks})}}catch(e){e?.name===`AbortError`?o({output:p,error:`Generation stopped`}):o({output:``,error:e instanceof Error?e.message:`AI request failed`})}finally{_.current=null,c(!1),g(null)}},b=yd(),x=hd[b.backend]?.label??b.backend;return(0,K.jsxs)(`div`,{className:`w-full space-y-3 rounded-xl border border-border bg-muted/30 p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-medium text-foreground`,children:[(0,K.jsx)(`span`,{className:`flex size-7 items-center justify-center rounded-md bg-foreground text-background`,children:(0,K.jsx)(Ke,{className:`size-3.5`})}),`AI block`,(0,K.jsx)(`span`,{className:`ml-auto text-[11px] font-normal text-muted-foreground`,children:l??x})]}),(0,K.jsx)(kd,{onOpen:()=>f(!0)}),(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Uses page context. Backends: Deep Agents, API keys, or coding CLIs (Claude Code / Codex / Grok) with live streaming when available.`}),(0,K.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:Op.map(e=>{let t=e.icon;return(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`outline`,className:`bg-background`,disabled:s,title:e.hint,onClick:()=>void y(e.action),children:[(0,K.jsx)(t,{className:`size-3.5`}),e.label]},e.action)})}),(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsx)(`textarea`,{className:`min-h-[64px] flex-1 resize-y rounded-md border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring/30`,placeholder:`Custom instruction…`,value:e,onChange:e=>a(e.target.value),disabled:s}),s?(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`destructive`,onClick:v,children:[(0,K.jsx)(Je,{className:`size-3.5`}),`Stop`]}):(0,K.jsxs)(w,{type:`button`,size:`sm`,disabled:!e.trim(),onClick:()=>void y(`custom`,e),children:[(0,K.jsx)(Re,{className:`size-3.5`}),`Run`]})]}),(s||p)&&(0,K.jsxs)(`div`,{className:`rounded-lg border border-border bg-background p-3`,children:[(0,K.jsxs)(`div`,{className:`mb-1 flex items-center gap-2 text-[11px] text-muted-foreground`,children:[s&&(0,K.jsx)(ke,{className:`size-3 animate-spin`}),h??(s?`Streaming…`:`Preview`)]}),(0,K.jsx)(`pre`,{className:`max-h-40 overflow-auto whitespace-pre-wrap text-xs leading-relaxed`,children:p||`…`})]}),n&&(0,K.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),t&&!p&&(0,K.jsx)(`pre`,{className:`max-h-48 overflow-auto rounded-lg border border-border bg-background p-3 text-xs`,children:t}),(0,K.jsx)(xd,{open:d,onOpenChange:f})]})}var jp=[{id:`improve`,label:`Improve`,instruction:`Improve clarity and flow while preserving meaning.`},{id:`shorter`,label:`Shorter`,instruction:`Make this shorter and more concise.`},{id:`longer`,label:`Expand`,instruction:`Expand this with one more sentence of useful detail.`},{id:`fix`,label:`Fix grammar`,instruction:`Fix grammar and spelling only.`},{id:`pro`,label:`Professional`,instruction:`Rewrite in a clear, professional tone.`}];function Mp(e,t){return e===`claude-cli`?`Claude Code CLI`:e===`codex-cli`?`Codex CLI`:e===`grok-cli`?`Grok CLI`:e===`deepagents`?`Deep Agents · ${t??`model`}`:e===`direct`?t??`Direct API`:e===`xai`?t??`Grok`:`Local demo AI`}function Np({open:e,onOpenChange:t,blockText:n,blockType:r,pageTitle:i,pageText:a,onApply:o}){let[c,l]=(0,z.useState)(``),[u,d]=(0,z.useState)(null),[f,p]=(0,z.useState)(!1),[m,h]=(0,z.useState)(null),[g,_]=(0,z.useState)(null),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)(!1),S=(0,z.useRef)(null),C=()=>{S.current?.abort(),S.current=null,p(!1)},T=async e=>{p(!0),h(null),d(``),y(null);let t=yd(),o=t.preferStreaming!==!1,s=t.backend===`claude-cli`||t.backend===`codex-cli`||t.backend===`grok-cli`,c=o&&(s||t.backend===`direct`||t.backend===`deepagents`);try{if(c){let o=new AbortController;S.current=o;let s=await Dp({request:{action:`edit_block`,instruction:e,blockText:n,blockType:r,pageTitle:i,pageText:a},clientSettings:t,backend:t.backend,signal:o.signal,onToken:(e,t)=>d(t),onStatus:e=>y(e)});d(s.text),_(Mp(s.provider,s.model))}else{let o=await cd({data:{action:`edit_block`,instruction:e,blockText:n,blockType:r,pageTitle:i,pageText:a,clientSettings:t}});d(o.text),_(Mp(o.provider,o.model))}}catch(e){e?.name!==`AbortError`&&h(e instanceof Error?e.message:`AI request failed`)}finally{S.current=null,p(!1),y(null)}};return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Gu,{open:e,onOpenChange:e=>{e||(C(),d(null),h(null),l(``)),t(e)},children:(0,K.jsxs)(Ju,{className:`max-w-lg`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsxs)(Xu,{className:`flex items-center gap-2`,children:[(0,K.jsx)(Ke,{className:`size-4`}),`Edit block with AI`]}),(0,K.jsxs)(Zu,{children:[`Rewrite this block. Uses your configured backend (API or Claude / Codex / Grok CLI) with streaming when available.`,g&&(0,K.jsx)(`span`,{className:`mt-1 block text-xs text-muted-foreground`,children:g})]})]}),(0,K.jsx)(kd,{onOpen:()=>x(!0)}),(0,K.jsxs)(`div`,{className:`rounded-md border border-border bg-muted/40 p-2 text-xs text-muted-foreground`,children:[(0,K.jsx)(`span`,{className:`font-medium text-foreground`,children:`Original`}),(0,K.jsx)(`p`,{className:`mt-1 line-clamp-4 whitespace-pre-wrap`,children:n||`(empty)`})]}),(0,K.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:jp.map(e=>(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`outline`,disabled:f,onClick:()=>void T(e.instruction),children:[(0,K.jsx)(rt,{className:`size-3.5`}),e.label]},e.id))}),(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsx)(`input`,{className:`h-9 flex-1 rounded-md border border-border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring/30`,placeholder:`Custom instruction…`,value:c,onChange:e=>l(e.target.value),disabled:f,onKeyDown:e=>{e.key===`Enter`&&c.trim()&&T(c.trim())}}),f?(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`destructive`,onClick:C,children:[(0,K.jsx)(Je,{className:`size-3.5`}),`Stop`]}):(0,K.jsx)(w,{type:`button`,size:`sm`,disabled:!c.trim(),onClick:()=>void T(c.trim()),children:`Run`})]}),f&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,K.jsx)(ke,{className:`size-3.5 animate-spin`}),v??`Generating…`]}),m&&(0,K.jsx)(`p`,{className:`text-xs text-destructive`,children:m}),u!=null&&u!==``&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:`Preview`}),(0,K.jsx)(`pre`,{className:s(`max-h-48 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-background p-3 text-sm`,f&&`opacity-80`),children:u}),(0,K.jsx)(w,{type:`button`,className:`w-full`,disabled:f,onClick:()=>{o(u),t(!1)},children:`Apply to block`})]})]})}),(0,K.jsx)(xd,{open:b,onOpenChange:x})]})}function Pp({block:e,index:t,isFocused:n,listNumber:r,pageTitle:i,pageText:a,onFocus:o,onChange:c,onTypeChange:l,onToggleCheck:u,onToggleCollapse:d,onEnter:f,onBackspaceEmpty:p,onMove:m,onDelete:h,onIndent:g,onPatch:_,onAiInsert:v,focusRequest:y,onFocusHandled:b,inputRefs:x}){let S=xp(e.type),C=(0,z.useRef)(null),T=(0,z.useRef)(null),[E,D]=(0,z.useState)(!1),[O,k]=(0,z.useState)(``),[A,j]=(0,z.useState)(0),[M,N]=(0,z.useState)({top:0,left:0}),[P,F]=(0,z.useState)(!1),[I,L]=(0,z.useState)(!1),R=(0,z.useCallback)(t=>{C.current=t,t?x.current.set(e.id,t):x.current.delete(e.id)},[e.id,x]),B=(0,z.useCallback)(()=>{let e=C.current;e&&(e.style.height=`0px`,e.style.height=`${Math.max(e.scrollHeight,28)}px`)},[]);(0,z.useEffect)(()=>{B()},[e.content,e.type,B]),(0,z.useEffect)(()=>{if(y!==e.id)return;let t=C.current;if(t){t.focus();let e=t.value.length;t.setSelectionRange(e,e)}b()},[y,e.id,b]);let V=e=>{let t=T.current;if(!t)return;let n=t.getBoundingClientRect(),r=Math.min(n.left+48,window.innerWidth-300),i=n.bottom+280>window.innerHeight?Math.max(8,n.top-280):n.bottom+4;N({top:i,left:r}),k(e),j(0),D(!0)},ee=()=>{D(!1),k(``),j(0)},H=t=>{let n=e.content,r=n.lastIndexOf(`/`),i=r>=0?n.slice(0,r):n;c(e.id,i),l(e.id,t),ee(),requestAnimationFrame(()=>{x.current.get(e.id)?.focus()})},te=t=>{c(e.id,t),requestAnimationFrame(B);let n=t.lastIndexOf(`/`);if(n>=0){let e=t.slice(n+1),r=t[n-1];if((n===0||r===` `||r===` +`)&&!e.includes(` +`)){V(e);return}}E&&ee()},ne=t=>{if(E){let e=Sp(O);if(t.key===`ArrowDown`){t.preventDefault(),j(t=>(t+1)%Math.max(e.length,1));return}if(t.key===`ArrowUp`){t.preventDefault(),j(t=>(t-1+Math.max(e.length,1))%Math.max(e.length,1));return}if(t.key===`Enter`||t.key===`Tab`){t.preventDefault();let n=e[A];n&&H(n.type);return}if(t.key===`Escape`){t.preventDefault(),ee();return}}if(t.key===`Enter`&&!t.shiftKey&&e.type!==`code`&&e.type!==`mermaid`){t.preventDefault(),f(e.id);return}if(t.key===`Backspace`){let n=t.currentTarget;if(!n.value&&n.selectionStart===0){t.preventDefault(),p(e.id);return}}t.key===`Tab`&&(t.preventDefault(),g(e.id,t.shiftKey?-1:1)),t.key===`ArrowUp`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),m(e.id,`up`)),t.key===`ArrowDown`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),m(e.id,`down`))},re={paddingLeft:`${(e.indent??0)*1.5}rem`},ie=e.type!==`divider`&&e.type!==`ai`&&e.type!==`mermaid`;if(e.type===`divider`)return(0,K.jsxs)(`div`,{ref:T,"data-block-id":e.id,"data-block-type":e.type,className:`group relative flex items-center gap-1 py-2`,style:re,onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,K.jsx)(Fp,{visible:P||n,canAiEdit:!1,onAdd:()=>f(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>l(e.id,t),onAiEdit:()=>L(!0)}),(0,K.jsx)(`hr`,{className:`w-full border-0 border-t border-border`})]});if(e.type===`ai`)return(0,K.jsxs)(`div`,{ref:T,"data-block-id":e.id,"data-block-type":e.type,className:`group relative py-1`,style:re,onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,K.jsx)(Fp,{visible:P||n,canAiEdit:!1,onAdd:()=>f(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>l(e.id,t),onAiEdit:()=>void 0}),(0,K.jsx)(`div`,{className:`pl-1`,children:(0,K.jsx)(Ap,{content:e.content,aiOutput:e.aiOutput,aiError:e.aiError,pageTitle:i,pageText:a,onChangePrompt:t=>c(e.id,t),onResult:({output:t,blocks:n,error:r})=>{_(e.id,{aiOutput:t,aiError:r}),n?.length&&v(e.id,n)}})})]});if(e.type===`mermaid`){let t=e.showSource??!e.content.trim();return(0,K.jsxs)(`div`,{ref:T,"data-block-id":e.id,"data-block-type":e.type,className:`group relative py-1`,style:re,onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,K.jsx)(Fp,{visible:P||n,canAiEdit:!1,onAdd:()=>f(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>l(e.id,t),onAiEdit:()=>void 0}),(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border bg-muted/20 p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:`Mermaid`}),(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 text-muted-foreground`,onClick:()=>_(e.id,{showSource:!t}),children:t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(de,{className:`size-3.5`}),` Preview`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(se,{className:`size-3.5`}),` Edit source`]})})]}),t?(0,K.jsx)(`textarea`,{ref:R,value:e.content,onChange:e=>te(e.target.value),onFocus:()=>o(e.id),onKeyDown:ne,placeholder:S.placeholder,rows:Math.max(4,e.content.split(` +`).length),spellCheck:!1,className:`w-full resize-y rounded-md border border-border bg-background px-3 py-2 font-mono text-sm leading-relaxed text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/40`}):(0,K.jsx)(Ep,{source:e.content})]}),E&&(0,K.jsx)(Cp,{query:O,selectedIndex:A,onSelect:H,onHover:j,position:M})]})}let W=s(`block w-full resize-none overflow-hidden border-0 bg-background p-0 text-foreground shadow-none outline-none ring-0 focus:outline-none focus:ring-0`,`placeholder:text-muted-foreground/60`,e.type===`paragraph`&&`text-base leading-relaxed`,e.type===`heading1`&&`text-3xl font-semibold leading-tight tracking-tight`,e.type===`heading2`&&`text-2xl font-semibold leading-tight tracking-tight`,e.type===`heading3`&&`text-xl font-semibold leading-snug tracking-tight`,(e.type===`bullet`||e.type===`numbered`)&&`text-base leading-relaxed`,e.type===`todo`&&s(`text-base leading-relaxed`,e.checked&&`text-muted-foreground line-through`),e.type===`toggle`&&`text-base font-medium leading-relaxed`,e.type===`quote`&&`text-base leading-relaxed text-muted-foreground`,e.type===`callout`&&`text-base leading-relaxed`,e.type===`code`&&`min-h-16 font-mono text-sm leading-relaxed`);return(0,K.jsxs)(`div`,{ref:T,"data-block-id":e.id,"data-block-type":e.type,className:s(`group relative flex items-start gap-1 rounded-md py-0.5`,n&&`bg-muted/40`),style:re,onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,K.jsx)(Fp,{visible:P||n,canAiEdit:ie,onAdd:()=>f(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>l(e.id,t),onAiEdit:()=>L(!0)}),(0,K.jsxs)(`div`,{className:s(`flex min-w-0 flex-1 items-start gap-2 rounded-md px-1 py-1`,e.type===`callout`&&`border border-border bg-muted/50 px-3 py-2.5`,e.type===`quote`&&`border-l-2 border-foreground/25 pl-3`,e.type===`code`&&`border border-border bg-muted/60 px-3 py-2.5`),children:[e.type===`bullet`&&(0,K.jsx)(`span`,{className:`mt-2.5 size-1.5 shrink-0 rounded-full bg-foreground/80`}),e.type===`numbered`&&(0,K.jsxs)(`span`,{className:`mt-1 w-5 shrink-0 text-right text-sm tabular-nums text-muted-foreground`,children:[r??t+1,`.`]}),e.type===`todo`&&(0,K.jsx)(`button`,{type:`button`,className:s(`mt-1.5 flex size-4 shrink-0 items-center justify-center rounded border transition-colors`,e.checked?`border-primary bg-primary text-primary-foreground`:`border-border bg-background hover:border-foreground/40`),onClick:()=>u(e.id),"aria-label":e.checked?`Mark incomplete`:`Mark complete`,children:e.checked&&(0,K.jsx)(U,{className:`size-3`,strokeWidth:3})}),e.type===`toggle`&&(0,K.jsx)(`button`,{type:`button`,className:`mt-1 flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted`,onClick:()=>d(e.id),"aria-label":e.collapsed?`Expand`:`Collapse`,children:(0,K.jsx)(ae,{className:s(`size-4 text-muted-foreground transition-transform duration-150`,!e.collapsed&&`rotate-90`)})}),e.type===`callout`&&(0,K.jsx)(`span`,{className:`mt-1 shrink-0 text-base leading-none`,"aria-hidden":!0,children:`💡`}),(0,K.jsx)(`textarea`,{ref:R,value:e.content,onChange:e=>te(e.target.value),onFocus:()=>o(e.id),onKeyDown:ne,placeholder:S.placeholder,rows:1,spellCheck:e.type!==`code`,className:W})]}),E&&(0,K.jsx)(Cp,{query:O,selectedIndex:A,onSelect:H,onHover:j,position:M}),ie&&(0,K.jsx)(Np,{open:I,onOpenChange:L,blockText:e.content,blockType:e.type,pageTitle:i,pageText:a,onApply:t=>c(e.id,t)})]})}function Fp({visible:e,canAiEdit:t,onAdd:n,onMoveUp:r,onMoveDown:i,onDelete:a,onTypeChange:o,onAiEdit:c}){return(0,K.jsxs)(`div`,{"data-hover-reveal":!0,className:s(`absolute -left-12 top-1 flex items-center gap-0.5 opacity-0 transition-opacity max-sm:-left-10`,e&&`opacity-100`),children:[(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`text-muted-foreground`,onClick:n,"aria-label":`Add block below`,children:(0,K.jsx)(ze,{className:`size-3.5`})}),(0,K.jsxs)(lu,{children:[(0,K.jsx)(uu,{asChild:!0,children:(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`text-muted-foreground`,"aria-label":`Block menu`,children:(0,K.jsx)(ve,{className:`size-3.5`})})}),(0,K.jsxs)(mu,{align:`start`,className:`w-48`,children:[(0,K.jsx)(gu,{children:`Block`}),t&&(0,K.jsxs)(hu,{onClick:c,children:[(0,K.jsx)(Ke,{className:`size-4`}),` Edit with AI`]}),(0,K.jsxs)(hu,{onClick:r,children:[(0,K.jsx)(ne,{className:`size-4`}),` Move up`]}),(0,K.jsxs)(hu,{onClick:i,children:[(0,K.jsx)(ee,{className:`size-4`}),` Move down`]}),(0,K.jsxs)(du,{children:[(0,K.jsxs)(fu,{children:[(0,K.jsx)(ue,{className:`size-4`}),` Turn into`]}),(0,K.jsx)(pu,{className:`max-h-64 overflow-y-auto`,children:bp.map(e=>{let t=e.icon;return(0,K.jsxs)(hu,{onClick:()=>o(e.type),children:[(0,K.jsx)(t,{className:`size-4`}),` `,e.label]},e.type)})})]}),(0,K.jsx)(_u,{}),(0,K.jsxs)(hu,{className:`text-destructive focus:text-destructive`,onClick:a,children:[(0,K.jsx)($e,{className:`size-4`}),` Delete`]})]})]})]})}function Ip(e){return e.blocks.filter(e=>e.type!==`ai`&&e.type!==`divider`).map(e=>`${e.type===`heading1`?`# `:e.type===`heading2`?`## `:e.type===`heading3`?`### `:e.type===`bullet`?`- `:e.type===`numbered`?`1. `:e.type===`todo`?e.checked?`[x] `:`[ ] `:e.type===`quote`?`> `:(e.type===`code`||e.type,``)}${e.content}`.trim()).filter(Boolean).join(` +`)}function Lp({page:e}){let t=m(e=>e.updatePage),n=m(e=>e.updateBlock),r=m(e=>e.insertBlock),i=m(e=>e.deleteBlock),a=m(e=>e.changeBlockType),c=m(e=>e.moveBlock),l=m(e=>e.deletePage),u=m(e=>e.duplicatePage),d=m(e=>e.createPage),p=m(e=>e.setBlocks),[h,g]=(0,z.useState)(null),[v,y]=(0,z.useState)(null),b=(0,z.useRef)(new Map),x=(0,z.useRef)(null),S=(0,z.useMemo)(()=>Ip(e),[e]),C=(0,z.useMemo)(()=>{let t=new Map,n=0;for(let r of e.blocks)r.type===`numbered`?(n+=1,t.set(r.id,n)):n=0;return t},[e.blocks]);(0,z.useEffect)(()=>{let e=x.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[e.title]);let T=(0,z.useCallback)(t=>{let n=r(e.id,t,`paragraph`,``);y(n),g(n)},[r,e.id]),E=(0,z.useCallback)(t=>{let n=e.blocks.findIndex(e=>e.id===t);if(n<0)return;let r=e.blocks[n-1];i(e.id,t),r&&(y(r.id),g(r.id))},[i,e.blocks,e.id]),D=(0,z.useCallback)((t,r)=>{let i=e.blocks.find(e=>e.id===t);if(!i)return;let a=Math.max(0,Math.min(4,(i.indent??0)+r));n(e.id,t,{indent:a})},[e.blocks,e.id,n]),O=(0,z.useCallback)((t,n)=>{let r=e.blocks.findIndex(e=>e.id===t);if(r<0||n.length===0)return;let i=n.map(e=>({id:o(`b`),type:e.type,content:e.content,indent:0,checked:e.type!==`todo`&&void 0,showSource:e.type!==`mermaid`&&void 0})),a=[...e.blocks];a.splice(r+1,0,...i),p(e.id,a),y(i[0].id)},[e.blocks,e.id,p]),k=e.cover?_[e.cover]:null;return(0,K.jsxs)(`div`,{className:`mx-auto w-full max-w-3xl px-4 pb-32 pt-4 sm:px-12 sm:pt-8`,children:[k?(0,K.jsxs)(`div`,{className:`group/cover relative -mx-4 mb-2 h-36 overflow-hidden rounded-xl sm:-mx-6 sm:h-44`,children:[(0,K.jsx)(`div`,{className:s(`absolute inset-0`,k.className)}),(0,K.jsx)(`div`,{"data-hover-reveal":!0,className:`absolute bottom-3 right-3 opacity-0 transition-opacity group-hover/cover:opacity-100`,children:(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`secondary`,className:`bg-background/90 shadow-sm backdrop-blur-sm`,onClick:()=>t(e.id,{cover:null}),children:`Remove cover`})})]}):null,(0,K.jsxs)(`div`,{className:`mb-1 flex flex-wrap items-end gap-2`,children:[(0,K.jsxs)(_p,{children:[(0,K.jsx)(vp,{asChild:!0,children:(0,K.jsx)(`button`,{type:`button`,className:`flex size-16 items-center justify-center rounded-xl text-4xl transition-colors hover:bg-muted`,"aria-label":`Change page icon`,children:e.icon})}),(0,K.jsxs)(yp,{align:`start`,className:`w-72`,children:[(0,K.jsx)(`div`,{className:`mb-2 text-xs font-medium text-muted-foreground`,children:`Page icon`}),(0,K.jsx)(`div`,{className:`grid grid-cols-8 gap-1`,children:f.map(n=>(0,K.jsx)(`button`,{type:`button`,className:s(`flex size-8 items-center justify-center rounded-md text-lg transition-colors hover:bg-muted`,e.icon===n&&`bg-muted ring-1 ring-border`),onClick:()=>t(e.id,{icon:n}),children:n},n))})]})]}),(0,K.jsxs)(`div`,{className:`mb-2 flex flex-1 flex-wrap items-center gap-1`,children:[(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,onClick:()=>t(e.id,{favorite:!e.favorite}),children:[(0,K.jsx)(Ye,{className:s(`size-3.5`,e.favorite&&`fill-amber-400 text-amber-500`)}),e.favorite?`Unfavorite`:`Favorite`]}),(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,onClick:()=>{let t=e.blocks[e.blocks.length-1],n=r(e.id,t?.id??null,`ai`,``);y(n)},children:[(0,K.jsx)(Ke,{className:`size-3.5`}),`AI block`]}),(0,K.jsxs)(lu,{children:[(0,K.jsx)(uu,{asChild:!0,children:(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,children:[(0,K.jsx)(Ce,{className:`size-3.5`}),`Cover`]})}),(0,K.jsxs)(mu,{align:`start`,children:[Object.entries(_).map(([n,r])=>(0,K.jsxs)(hu,{onClick:()=>t(e.id,{cover:n}),children:[(0,K.jsx)(`span`,{className:s(`mr-2 size-4 rounded`,r.className)}),r.label]},n)),e.cover&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(_u,{}),(0,K.jsx)(hu,{onClick:()=>t(e.id,{cover:null}),children:`Remove cover`})]})]})]}),(0,K.jsxs)(lu,{children:[(0,K.jsx)(uu,{asChild:!0,children:(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`ghost`,"aria-label":`Page actions`,className:`text-muted-foreground`,children:(0,K.jsx)(ue,{className:`size-3.5`})})}),(0,K.jsxs)(mu,{align:`start`,children:[(0,K.jsxs)(hu,{onClick:()=>d({parentId:e.id}),children:[(0,K.jsx)(ze,{className:`size-4`}),` Add sub-page`]}),(0,K.jsxs)(hu,{onClick:()=>u(e.id),children:[(0,K.jsx)(ce,{className:`size-4`}),` Duplicate`]}),(0,K.jsx)(_u,{}),(0,K.jsxs)(hu,{className:`text-destructive focus:text-destructive`,onClick:()=>l(e.id),children:[(0,K.jsx)($e,{className:`size-4`}),` Move to trash`]})]})]})]})]}),(0,K.jsx)(`textarea`,{ref:x,value:e.title,onChange:n=>t(e.id,{title:n.target.value}),placeholder:`Untitled`,rows:1,className:`mb-4 w-full resize-none overflow-hidden bg-transparent text-4xl font-bold tracking-tight text-foreground outline-none placeholder:text-muted-foreground/50`,onKeyDown:t=>{if(t.key===`Enter`){t.preventDefault();let n=e.blocks[0];n&&(y(n.id),g(n.id))}}}),(0,K.jsx)(`div`,{className:`relative space-y-0.5 pl-10 sm:pl-12`,children:e.blocks.map((t,r)=>(0,K.jsx)(Pp,{pageId:e.id,block:t,index:r,isFocused:h===t.id,listNumber:C.get(t.id),pageTitle:e.title,pageText:S,onFocus:g,onChange:(t,r)=>n(e.id,t,{content:r}),onTypeChange:(t,n)=>a(e.id,t,n),onToggleCheck:t=>{let r=e.blocks.find(e=>e.id===t);r&&n(e.id,t,{checked:!r.checked})},onToggleCollapse:t=>{let r=e.blocks.find(e=>e.id===t);r&&n(e.id,t,{collapsed:!r.collapsed})},onEnter:T,onBackspaceEmpty:E,onMove:(t,n)=>c(e.id,t,n),onDelete:t=>i(e.id,t),onIndent:D,onPatch:(t,r)=>n(e.id,t,r),onAiInsert:O,focusRequest:v,onFocusHandled:()=>y(null),inputRefs:b},t.id))}),(0,K.jsx)(`button`,{type:`button`,className:`mt-2 ml-10 min-h-16 w-[calc(100%-2.5rem)] cursor-text rounded-md sm:ml-12 sm:w-[calc(100%-3rem)]`,"aria-label":`Add block at end`,onClick:()=>{let t=e.blocks[e.blocks.length-1];if(t&&t.type===`paragraph`&&!t.content)y(t.id),g(t.id);else{let n=r(e.id,t?.id??null,`paragraph`,``);y(n),g(n)}}})]})}var Rp=1,zp=.9,Bp=.8,Vp=.17,Hp=.1,Up=.999,Wp=.9999,Gp=.99,Kp=/[\\\/_+.#"@\[\(\{&]/,qp=/[\\\/_+.#"@\[\(\{&]/g,Jp=/[\s-]/,Yp=/[\s-]/g;function Xp(e,t,n,r,i,a,o){if(a===t.length)return i===e.length?Rp:Gp;var s=`${i},${a}`;if(o[s]!==void 0)return o[s];for(var c=r.charAt(a),l=n.indexOf(c,i),u=0,d,f,p,m;l>=0;)d=Xp(e,t,n,r,l+1,a+1,o),d>u&&(l===i?d*=Rp:Kp.test(e.charAt(l-1))?(d*=Bp,p=e.slice(i,l-1).match(qp),p&&i>0&&(d*=Up**+p.length)):Jp.test(e.charAt(l-1))?(d*=zp,m=e.slice(i,l-1).match(Yp),m&&i>0&&(d*=Up**+m.length)):(d*=Vp,i>0&&(d*=Up**+(l-i))),e.charAt(l)!==t.charAt(a)&&(d*=Wp)),(dd&&(d=f*Hp)),d>u&&(u=d),l=n.indexOf(c,l+1);return o[s]=u,u}function Zp(e){return e.toLowerCase().replace(Yp,` `)}function Qp(e,t,n){return e=n&&n.length>0?`${e+` `+n.join(` `)}`:e,Xp(e,t,Zp(e),Zp(t),0,0,{})}var $p=`[cmdk-group=""]`,em=`[cmdk-group-items=""]`,tm=`[cmdk-group-heading=""]`,nm=`[cmdk-item=""]`,rm=`${nm}:not([aria-disabled="true"])`,im=`cmdk-item-select`,am=`data-value`,om=(e,t,n)=>Qp(e,t,n),sm=z.createContext(void 0),cm=()=>z.useContext(sm),lm=z.createContext(void 0),um=()=>z.useContext(lm),dm=z.createContext(void 0),fm=z.forwardRef((e,t)=>{let n=Em(()=>({search:``,value:e.value??e.defaultValue??``,selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}})),r=Em(()=>new Set),i=Em(()=>new Map),a=Em(()=>new Map),o=Em(()=>new Set),s=wm(e),{label:c,children:l,value:u,onValueChange:d,filter:f,shouldFilter:p,loop:m,disablePointerSelection:h=!1,vimBindings:g=!0,..._}=e,v=Y(),y=Y(),b=Y(),x=z.useRef(null),S=km();Tm(()=>{if(u!==void 0){let e=u.trim();n.current.value=e,C.emit()}},[u]),Tm(()=>{S(6,k)},[]);let C=z.useMemo(()=>({subscribe:e=>(o.current.add(e),()=>o.current.delete(e)),snapshot:()=>n.current,setState:(e,t,r)=>{var i,a,o;if(!Object.is(n.current[e],t)){if(n.current[e]=t,e===`search`)O(),E(),S(1,D);else if(e===`value`){if(document.activeElement.hasAttribute(`cmdk-input`)||document.activeElement.hasAttribute(`cmdk-root`)){let e=document.getElementById(b);e?e.focus():(i=document.getElementById(v))==null||i.focus()}if(S(7,()=>{n.current.selectedItemId=A()?.id,C.emit()}),r||S(5,k),s.current?.value!==void 0){let e=t??``;(o=(a=s.current).onValueChange)==null||o.call(a,e);return}}C.emit()}},emit:()=>{o.current.forEach(e=>e())}}),[]),w=z.useMemo(()=>({value:(e,t,r)=>{t!==a.current.get(e)?.value&&(a.current.set(e,{value:t,keywords:r}),n.current.filtered.items.set(e,T(t,r)),S(2,()=>{E(),C.emit()}))},item:(e,t)=>(r.current.add(e),t&&(i.current.has(t)?i.current.get(t).add(e):i.current.set(t,new Set([e]))),S(3,()=>{O(),E(),n.current.value||D(),C.emit()}),()=>{a.current.delete(e),r.current.delete(e),n.current.filtered.items.delete(e);let t=A();S(4,()=>{O(),t?.getAttribute(`id`)===e&&D(),C.emit()})}),group:e=>(i.current.has(e)||i.current.set(e,new Set),()=>{a.current.delete(e),i.current.delete(e)}),filter:()=>s.current.shouldFilter,label:c||e[`aria-label`],getDisablePointerSelection:()=>s.current.disablePointerSelection,listId:v,inputId:b,labelId:y,listInnerRef:x}),[]);function T(e,t){let r=s.current?.filter??om;return e?r(e,n.current.search,t):0}function E(){if(!n.current.search||s.current.shouldFilter===!1)return;let e=n.current.filtered.items,t=[];n.current.filtered.groups.forEach(n=>{let r=i.current.get(n),a=0;r.forEach(t=>{let n=e.get(t);a=Math.max(n,a)}),t.push([n,a])});let r=x.current;j().sort((t,n)=>{let r=t.getAttribute(`id`),i=n.getAttribute(`id`);return(e.get(i)??0)-(e.get(r)??0)}).forEach(e=>{let t=e.closest(em);t?t.appendChild(e.parentElement===t?e:e.closest(`${em} > *`)):r.appendChild(e.parentElement===r?e:e.closest(`${em} > *`))}),t.sort((e,t)=>t[1]-e[1]).forEach(e=>{let t=x.current?.querySelector(`${$p}[${am}="${encodeURIComponent(e[0])}"]`);t?.parentElement.appendChild(t)})}function D(){let e=j().find(e=>e.getAttribute(`aria-disabled`)!==`true`)?.getAttribute(am);C.setState(`value`,e||void 0)}function O(){if(!n.current.search||s.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let e=0;for(let t of r.current){let r=T(a.current.get(t)?.value??``,a.current.get(t)?.keywords??[]);n.current.filtered.items.set(t,r),r>0&&e++}for(let[e,t]of i.current)for(let r of t)if(n.current.filtered.items.get(r)>0){n.current.filtered.groups.add(e);break}n.current.filtered.count=e}function k(){var e;let t=A();t&&(t.parentElement?.firstChild===t&&((e=t.closest($p)?.querySelector(tm))==null||e.scrollIntoView({block:`nearest`})),t.scrollIntoView({block:`nearest`}))}function A(){return x.current?.querySelector(`${nm}[aria-selected="true"]`)}function j(){return Array.from(x.current?.querySelectorAll(rm)||[])}function M(e){let t=j()[e];t&&C.setState(`value`,t.getAttribute(am))}function N(e){var t;let n=A(),r=j(),i=r.findIndex(e=>e===n),a=r[i+e];(t=s.current)!=null&&t.loop&&(a=i+e<0?r[r.length-1]:i+e===r.length?r[0]:r[i+e]),a&&C.setState(`value`,a.getAttribute(am))}function P(e){let t=A()?.closest($p),n;for(;t&&!n;)t=e>0?Sm(t,$p):Cm(t,$p),n=t?.querySelector(rm);n?C.setState(`value`,n.getAttribute(am)):N(e)}let F=()=>M(j().length-1),I=e=>{e.preventDefault(),e.metaKey?F():e.altKey?P(1):N(1)},L=e=>{e.preventDefault(),e.metaKey?M(0):e.altKey?P(-1):N(-1)};return z.createElement(q.div,{ref:t,tabIndex:-1,..._,"cmdk-root":``,onKeyDown:e=>{var t;(t=_.onKeyDown)==null||t.call(_,e);let n=e.nativeEvent.isComposing||e.keyCode===229;if(!(e.defaultPrevented||n))switch(e.key){case`n`:case`j`:g&&e.ctrlKey&&I(e);break;case`ArrowDown`:I(e);break;case`p`:case`k`:g&&e.ctrlKey&&L(e);break;case`ArrowUp`:L(e);break;case`Home`:e.preventDefault(),M(0);break;case`End`:e.preventDefault(),F();break;case`Enter`:{e.preventDefault();let t=A();if(t){let e=new Event(im);t.dispatchEvent(e)}}}}},z.createElement(`label`,{"cmdk-label":``,htmlFor:w.inputId,id:w.labelId,style:Mm},c),jm(e,e=>z.createElement(lm.Provider,{value:C},z.createElement(sm.Provider,{value:w},e))))}),pm=z.forwardRef((e,t)=>{let n=Y(),r=z.useRef(null),i=z.useContext(dm),a=cm(),o=wm(e),s=o.current?.forceMount??i?.forceMount;Tm(()=>{if(!s)return a.item(n,i?.id)},[s]);let c=Om(n,r,[e.value,e.children,r],e.keywords),l=um(),u=Dm(e=>e.value&&e.value===c.current),d=Dm(e=>s||a.filter()===!1?!0:!e.search||e.filtered.items.get(n)>0);z.useEffect(()=>{let t=r.current;if(!(!t||e.disabled))return t.addEventListener(im,f),()=>t.removeEventListener(im,f)},[d,e.onSelect,e.disabled]);function f(){var e,t;p(),(t=(e=o.current).onSelect)==null||t.call(e,c.current)}function p(){l.setState(`value`,c.current,!0)}if(!d)return null;let{disabled:m,value:h,onSelect:g,forceMount:_,keywords:v,...y}=e;return z.createElement(q.div,{ref:O(r,t),...y,id:n,"cmdk-item":``,role:`option`,"aria-disabled":!!m,"aria-selected":!!u,"data-disabled":!!m,"data-selected":!!u,onPointerMove:m||a.getDisablePointerSelection()?void 0:p,onClick:m?void 0:f},e.children)}),mm=z.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...a}=e,o=Y(),s=z.useRef(null),c=z.useRef(null),l=Y(),u=cm(),d=Dm(e=>i||u.filter()===!1?!0:!e.search||e.filtered.groups.has(o));Tm(()=>u.group(o),[]),Om(o,s,[e.value,e.heading,c]);let f=z.useMemo(()=>({id:o,forceMount:i}),[i]);return z.createElement(q.div,{ref:O(s,t),...a,"cmdk-group":``,role:`presentation`,hidden:!d||void 0},n&&z.createElement(`div`,{ref:c,"cmdk-group-heading":``,"aria-hidden":!0,id:l},n),jm(e,e=>z.createElement(`div`,{"cmdk-group-items":``,role:`group`,"aria-labelledby":n?l:void 0},z.createElement(dm.Provider,{value:f},e))))}),hm=z.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=z.useRef(null),a=Dm(e=>!e.search);return!n&&!a?null:z.createElement(q.div,{ref:O(i,t),...r,"cmdk-separator":``,role:`separator`})}),gm=z.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,a=um(),o=Dm(e=>e.search),s=Dm(e=>e.selectedItemId),c=cm();return z.useEffect(()=>{e.value!=null&&a.setState(`search`,e.value)},[e.value]),z.createElement(q.input,{ref:t,...r,"cmdk-input":``,autoComplete:`off`,autoCorrect:`off`,spellCheck:!1,"aria-autocomplete":`list`,role:`combobox`,"aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":s,id:c.inputId,type:`text`,value:i?e.value:o,onChange:e=>{i||a.setState(`search`,e.target.value),n?.(e.target.value)}})}),_m=z.forwardRef((e,t)=>{let{children:n,label:r=`Suggestions`,...i}=e,a=z.useRef(null),o=z.useRef(null),s=Dm(e=>e.selectedItemId),c=cm();return z.useEffect(()=>{if(o.current&&a.current){let e=o.current,t=a.current,n,r=new ResizeObserver(()=>{n=requestAnimationFrame(()=>{let n=e.offsetHeight;t.style.setProperty(`--cmdk-list-height`,n.toFixed(1)+`px`)})});return r.observe(e),()=>{cancelAnimationFrame(n),r.unobserve(e)}}},[]),z.createElement(q.div,{ref:O(a,t),...i,"cmdk-list":``,role:`listbox`,tabIndex:-1,"aria-activedescendant":s,"aria-label":r,id:c.listId},jm(e,e=>z.createElement(`div`,{ref:O(o,c.listInnerRef),"cmdk-list-sizer":``},e)))}),vm=z.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:a,container:o,...s}=e;return z.createElement(Tu,{open:n,onOpenChange:r},z.createElement(ku,{container:o},z.createElement(ju,{"cmdk-overlay":``,className:i}),z.createElement(Fu,{"aria-label":e.label,"cmdk-dialog":``,className:a},z.createElement(fm,{ref:t,...s}))))}),ym=z.forwardRef((e,t)=>Dm(e=>e.filtered.count===0)?z.createElement(q.div,{ref:t,...e,"cmdk-empty":``,role:`presentation`}):null),bm=z.forwardRef((e,t)=>{let{progress:n,children:r,label:i=`Loading...`,...a}=e;return z.createElement(q.div,{ref:t,...a,"cmdk-loading":``,role:`progressbar`,"aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},jm(e,e=>z.createElement(`div`,{"aria-hidden":!0},e)))}),xm=Object.assign(fm,{List:_m,Item:pm,Input:gm,Group:mm,Separator:hm,Dialog:vm,Empty:ym,Loading:bm});function Sm(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function Cm(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function wm(e){let t=z.useRef(e);return Tm(()=>{t.current=e}),t}var Tm=typeof window>`u`?z.useEffect:z.useLayoutEffect;function Em(e){let t=z.useRef();return t.current===void 0&&(t.current=e()),t}function Dm(e){let t=um(),n=()=>e(t.snapshot());return z.useSyncExternalStore(t.subscribe,n,n)}function Om(e,t,n,r=[]){let i=z.useRef(),a=cm();return Tm(()=>{var o;let s=(()=>{for(let e of n){if(typeof e==`string`)return e.trim();if(typeof e==`object`&&`current`in e)return e.current?e.current.textContent?.trim():i.current}})(),c=r.map(e=>e.trim());a.value(e,s,c),(o=t.current)==null||o.setAttribute(am,s),i.current=s}),i}var km=()=>{let[e,t]=z.useState(),n=Em(()=>new Map);return Tm(()=>{n.current.forEach(e=>e()),n.current=new Map},[e]),(e,r)=>{n.current.set(e,r),t({})}};function Am(e){let t=e.type;return typeof t==`function`?t(e.props):`render`in t?t.render(e.props):e}function jm({asChild:e,children:t},n){return e&&z.isValidElement(t)?z.cloneElement(Am(t),{ref:t.ref},n(t.props.children)):n(t)}var Mm={position:`absolute`,width:`1px`,height:`1px`,padding:`0`,margin:`-1px`,overflow:`hidden`,clip:`rect(0, 0, 0, 0)`,whiteSpace:`nowrap`,borderWidth:`0`},Nm=sd({type:`function`}).client(async({next:e})=>{let{getBearerToken:t}=await y(async()=>{let{getBearerToken:e}=await import(`./client-CwgDvMJw.js`).then(e=>e.n);return{getBearerToken:e}},__vite__mapDeps([24,2,3]));return e({sendContext:{bearerToken:t()??void 0}})}),Pm=$({method:`POST`}).middleware([Nm]).handler(p(`a98064319e8852a83544a57d2b08358536b8e71b7accdbbc3c7a0bc01b34e11a`));function Fm({open:e,onOpenChange:t}){let n=m(e=>e.pages),r=m(e=>e.storageMode),i=m(e=>e.setActivePage),a=m(e=>e.createPage),[o,c]=(0,z.useState)(``),[l,u]=(0,z.useState)([]),[d,f]=(0,z.useState)(!1),[p,h]=(0,z.useState)(!1),[g,_]=(0,z.useState)(`local`);(0,z.useEffect)(()=>{e||(c(``),u([]))},[e]),(0,z.useEffect)(()=>{let n=n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()===`k`&&(n.preventDefault(),t(!e))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]),(0,z.useEffect)(()=>{if(!e)return;let t=o.trim();if(!t){u([]),f(!1);return}let i=!1;f(!0);let a=setTimeout(()=>{(async()=>{try{if(r===`database`){let e=await Pm({data:{query:t,limit:24}});if(i)return;u(e.hits),h(e.trgm),_(`postgres`)}else{let e=Af(n,t,24);if(i)return;u(e),h(!1),_(`local`)}}catch{if(i)return;u(Af(n,t,24)),_(`local`)}finally{i||f(!1)}})()},180);return()=>{i=!0,clearTimeout(a)}},[o,e,r,n]);let v=(0,z.useMemo)(()=>n.filter(e=>!e.archived).slice(0,30),[n]);if(!e)return null;let y=o.trim().length>0;return(0,K.jsxs)(`div`,{className:`fixed inset-0 z-[100]`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 bg-black/40`,onClick:()=>t(!1),"aria-hidden":!0}),(0,K.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Command palette`,"data-testid":`command-palette`,className:`absolute left-1/2 top-[18%] w-[min(560px,calc(100%-2rem))] -translate-x-1/2 overflow-hidden rounded-xl border border-border bg-popover shadow-2xl`,children:(0,K.jsxs)(xm,{className:`flex flex-col`,label:`Search pages`,shouldFilter:!1,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border px-3`,children:[(0,K.jsx)(We,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(xm.Input,{value:o,onValueChange:c,placeholder:r===`database`?`Search pages (Postgres keyword + similarity)…`:`Search pages…`,className:`h-12 w-full bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground`,autoFocus:!0}),d?(0,K.jsx)(ke,{className:`size-4 animate-spin text-muted-foreground`}):(0,K.jsx)(`kbd`,{className:`hidden rounded border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground sm:inline`,children:`ESC`})]}),y&&(0,K.jsx)(`div`,{className:`border-b border-border px-3 py-1.5 text-[11px] text-muted-foreground`,children:g===`postgres`?`Postgres full-text${p?` + pg_trgm similarity`:` + ILIKE fallback`}`:`Local search (sign in to sync for Postgres search)`}),(0,K.jsxs)(xm.List,{className:`max-h-80 overflow-y-auto p-2`,children:[(0,K.jsx)(xm.Group,{heading:`Actions`,className:`[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground`,children:(0,K.jsxs)(xm.Item,{value:`new page create`,onSelect:()=>{a(),t(!1)},className:s(`flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-sm aria-selected:bg-muted`),children:[(0,K.jsx)(ze,{className:`size-4 text-muted-foreground`}),`New page`]})}),(0,K.jsx)(xm.Group,{heading:y?`Results`:`Pages`,className:`mt-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground`,children:(y?l:v.map(Im)).map(e=>(0,K.jsxs)(xm.Item,{value:`${e.title} ${e.pageId}`,onSelect:()=>{i(e.pageId),window.dispatchEvent(new CustomEvent(`workspace:clear-mount`)),t(!1)},className:`flex cursor-pointer flex-col gap-0.5 rounded-md px-2 py-2 text-sm aria-selected:bg-muted`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-base leading-none`,children:e.icon}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-medium`,children:e.title||`Untitled`}),e.favorite&&(0,K.jsx)(Ye,{className:`size-3.5 fill-amber-400 text-amber-500`}),y&&(0,K.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:e.mode}),(0,K.jsx)(pe,{className:`size-3.5 text-muted-foreground`})]}),y&&e.snippet&&(0,K.jsx)(`p`,{className:`line-clamp-2 pl-7 text-xs text-muted-foreground`,children:e.snippet})]},e.pageId))}),y&&l.length===0&&(0,K.jsx)(`p`,{className:`py-8 text-center text-sm text-muted-foreground`,children:d?`Searching…`:`No pages found`})]})]})})]})}function Im(e){return{pageId:e.id,title:e.title,icon:e.icon,parentId:e.parentId,favorite:e.favorite,snippet:``,score:0,mode:`keyword`}}function Lm(){let e=jd(e=>e.mounts),t=jd(e=>e.selection),n=jd(e=>e.setSelection),r=e.find(e=>e.id===t?.mountId),[i,a]=(0,z.useState)([]),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)([]),[p,m]=(0,z.useState)(``),[h,g]=(0,z.useState)(!1),[_,v]=(0,z.useState)(!1),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)(null),[C,T]=(0,z.useState)(`browse`),E=(0,z.useCallback)(async(e=``)=>{if(r){g(!0),S(null);try{if(r.kind===`server`&&r.serverPath){let t=await Bd({data:{root:r.serverPath,relPath:e}});a(t)}else{let t=await Id(r.id);if(!t)throw Error(`Local folder permission lost — re-link the folder.`);let n=t;if(e)for(let t of e.split(`/`).filter(Boolean))n=await n.getDirectoryHandle(t);let i=await Ld(n,e);a(i.map(t=>({...t,relPath:e?`${e}/${t.name}`:t.name})))}c(e),T(`browse`)}catch(e){S(e instanceof Error?e.message:`Failed to list folder`)}finally{g(!1)}}},[r]),D=(0,z.useCallback)(async e=>{if(r){g(!0),S(null);try{let t=``;if(r.kind===`server`&&r.serverPath)t=(await Vd({data:{root:r.serverPath,relPath:e}})).content;else{let n=await Id(r.id);if(!n)throw Error(`Local folder permission lost — re-link the folder.`);t=await Rd(n,e)}u(t);let i=Of(t,e.split(`/`).pop()||`note`);m(i),f(Df(t.replace(RegExp(`^#\\s+${i}\\s*\\n+`),``))),b(!1),T(`file`),n({mountId:r.id,relPath:e})}catch(e){S(e instanceof Error?e.message:`Failed to read file`)}finally{g(!1)}}},[r,n]);(0,z.useEffect)(()=>{r&&(t?.relPath&&t.relPath.toLowerCase().endsWith(`.md`)?D(t.relPath):E(t?.relPath&&!t.relPath.endsWith(`.md`)?t.relPath:``))},[r?.id]);let O=async()=>{if(!(!r||!t?.relPath)){v(!0),S(null);try{let e=Tf({id:`x`,title:p,icon:`📝`,cover:null,parentId:null,favorite:!1,createdAt:0,updatedAt:0,blocks:d});if(r.kind===`server`&&r.serverPath)await Hd({data:{root:r.serverPath,relPath:t.relPath,content:e}});else{let n=await Id(r.id);if(!n)throw Error(`Local folder permission lost`);await zd(n,t.relPath,e)}u(e),b(!1)}catch(e){S(e instanceof Error?e.message:`Save failed`)}finally{v(!1)}}};if(!r||!t)return(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-2 p-8 text-center text-muted-foreground`,children:[(0,K.jsx)(we,{className:`size-8 opacity-40`}),(0,K.jsx)(`p`,{className:`text-sm`,children:`Select a linked markdown file from the sidebar.`})]});let k=(C===`file`?t.relPath:s).split(`/`).filter(Boolean);return(0,K.jsxs)(`div`,{className:`mx-auto w-full max-w-3xl px-4 pb-32 pt-6 sm:px-12`,children:[(0,K.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 font-medium text-foreground`,children:[(0,K.jsx)(we,{className:`size-3`}),` Linked · not imported`]}),(0,K.jsx)(`button`,{type:`button`,className:`hover:text-foreground`,onClick:()=>void E(``),children:r.name}),k.map((e,t)=>{let n=k.slice(0,t+1).join(`/`),r=t===k.length-1&&C===`file`;return(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{children:`/`}),r?(0,K.jsx)(`span`,{className:`text-foreground`,children:e}):(0,K.jsx)(`button`,{type:`button`,className:`hover:text-foreground`,onClick:()=>{e.toLowerCase().endsWith(`.md`)?D(n):E(n)},children:e})]},n)})]}),x&&(0,K.jsx)(`div`,{className:`mb-4 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive`,children:x}),h?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 py-12 text-sm text-muted-foreground`,children:[(0,K.jsx)(ke,{className:`size-4 animate-spin`}),` Loading…`]}):C===`browse`?(0,K.jsxs)(`div`,{className:`space-y-1`,children:[s&&(0,K.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted`,onClick:()=>{let e=s.split(`/`).slice(0,-1).join(`/`);E(e)},children:[(0,K.jsx)(he,{className:`size-4 text-muted-foreground`}),`..`]}),i.length===0&&(0,K.jsx)(`p`,{className:`py-8 text-center text-sm text-muted-foreground`,children:`No markdown files here`}),i.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted`,onClick:()=>{e.kind===`dir`?E(e.relPath):D(e.relPath)},children:[(0,K.jsx)(`span`,{children:e.kind===`dir`?`📁`:`📝`}),(0,K.jsx)(`span`,{className:`font-medium`,children:e.name})]},e.relPath))]}):(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2`,children:[(0,K.jsx)(`input`,{className:`min-w-0 flex-1 bg-transparent text-3xl font-bold tracking-tight outline-none`,value:p,onChange:e=>{m(e.target.value),b(!0)}}),(0,K.jsxs)(w,{type:`button`,size:`sm`,disabled:!y||_,onClick:()=>void O(),children:[_?(0,K.jsx)(ke,{className:`size-3.5 animate-spin`}):(0,K.jsx)(Ue,{className:`size-3.5`}),`Save to disk`]})]}),(0,K.jsxs)(`div`,{className:`relative space-y-0.5 pl-2`,children:[d.map((e,t)=>(0,K.jsxs)(`div`,{className:`rounded-md py-1`,children:[(0,K.jsx)(`textarea`,{className:`w-full resize-y rounded-md border border-transparent bg-transparent px-1 py-1 text-base leading-relaxed outline-none hover:border-border focus:border-border focus:bg-background`,rows:Math.max(1,e.content.split(` +`).length),value:e.content,onChange:t=>{let n=d.map(n=>n.id===e.id?{...n,content:t.target.value}:n);f(n),b(!0)},placeholder:e.type}),(0,K.jsx)(`div`,{className:`px-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:e.type})]},e.id)),(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-2`,onClick:()=>{f([...d,{id:o(`b`),type:`paragraph`,content:``,indent:0}]),b(!0)},children:`Add block`})]}),(0,K.jsxs)(`p`,{className:`mt-8 text-xs text-muted-foreground`,children:[`Edits write back to the linked file. This page is `,(0,K.jsx)(`strong`,{children:`not`}),` stored in your workspace until you Import.`]})]})]})}var Rm=$({method:`GET`}).middleware([Nm]).handler(p(`e3fb77d67dfdadad5d019581d79338a7f7cf2e42797c44110574e289b39fd293`)),zm=$({method:`POST`}).middleware([Nm]).handler(p(`7bd9976b9723bbefb2399d41723684e8ed7d3bfcf4f814066bb422e47b4bb658`)),Bm=null,Vm=!1,Hm=!1,Um=!1,Wm=!1,Gm=null;function Km(){let e=m.getState();return{name:e.name,theme:e.theme,activePageId:e.activePageId,sidebarOpen:e.sidebarOpen,pages:e.pages}}function qm(){Gm?.(),Gm=m.subscribe((e,t)=>{!Um||!Wm||e.name===t.name&&e.theme===t.theme&&e.activePageId===t.activePageId&&e.sidebarOpen===t.sidebarOpen&&e.pages===t.pages||Ym()})}async function Jm(){try{let e=await Rm();return Wm=!1,m.setState({name:e.name,theme:e.theme,activePageId:e.activePageId,sidebarOpen:e.sidebarOpen,pages:e.pages,hydrated:!0,syncStatus:`saved`,storageMode:`database`}),Um=!0,Wm=!0,qm(),e.source}catch{return Um=!1,Wm=!1,Gm?.(),Gm=null,m.setState({storageMode:`local`,syncStatus:`local`,hydrated:!0}),`error`}}function Ym(){!Um||!Wm||(m.setState({syncStatus:`pending`}),Bm&&clearTimeout(Bm),Bm=setTimeout(()=>{Xm()},600))}async function Xm(){if(Um){if(Vm){Hm=!0;return}Vm=!0,m.setState({syncStatus:`saving`});try{await zm({data:Km()}),m.setState({syncStatus:`saved`})}catch{m.setState({syncStatus:`error`})}finally{Vm=!1,Hm&&(Hm=!1,Ym())}}}async function Zm(){if(Bm&&=(clearTimeout(Bm),null),Um)try{await zm({data:Km()}),m.setState({syncStatus:`saved`})}catch{m.setState({syncStatus:`error`})}}function Qm(){Um=!1,Wm=!1,Gm?.(),Gm=null,m.setState({storageMode:`local`,syncStatus:`local`,hydrated:!0})}function $m(){let e=m(e=>e.pages),t=m(e=>e.activePageId),n=m(e=>e.sidebarOpen),r=m(e=>e.theme),i=m(e=>e.hydrated),o=m(e=>e.storageMode),c=m(e=>e.syncStatus),l=m(e=>e.setSidebarOpen),u=m(e=>e.toggleSidebar),d=m(e=>e.setActivePage),f=m(e=>e.setTheme),p=m(e=>e.updatePage),h=m(e=>e.createPage),g=m(e=>e.setHydrated),_=jd(e=>e.selection),v=jd(e=>e.mounts),y=jd(e=>e.setSelection),b=v.find(e=>e.id===_?.mountId),{user:x,isPending:S}=D(),[C,T]=(0,z.useState)(!1),[E,O]=(0,z.useState)(!1),[k,A]=(0,z.useState)(!1),[j,M]=(0,z.useState)(!1);(0,z.useEffect)(()=>{let e=m.persist.onFinishHydration(()=>{x||g(!0)});return m.persist.hasHydrated()&&!x&&g(!0),e},[g,x]),(0,z.useEffect)(()=>{if(S)return;let e=!1;async function t(){x?(A(!0),await Jm(),e||A(!1)):(Qm(),m.persist.hasHydrated()&&g(!0))}return t(),()=>{e=!0}},[x,S,g]),(0,z.useEffect)(()=>{let e=()=>{o===`database`&&Zm()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[o]),(0,z.useEffect)(()=>{let e=()=>y(null);return window.addEventListener(`workspace:clear-mount`,e),()=>window.removeEventListener(`workspace:clear-mount`,e)},[y]);let N=!!(_&&b),P=N?void 0:e.find(e=>e.id===t&&!e.archived),F=(()=>{if(!P)return[];let t=[],n=P,r=new Map(e.map(e=>[e.id,e]));for(;n;)t.unshift(n),n=n.parentId?r.get(n.parentId):void 0;return t})();return!i||S||k?(0,K.jsx)(`div`,{className:`flex h-dvh items-center justify-center bg-background text-muted-foreground`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-3`,children:[(0,K.jsx)(`div`,{className:`size-8 animate-pulse rounded-lg bg-muted`}),(0,K.jsx)(`p`,{className:`text-sm`,children:k?`Loading workspace from database…`:`Loading workspace…`})]})}):(0,K.jsx)(pa,{delayDuration:300,children:(0,K.jsxs)(`div`,{className:`flex h-dvh overflow-hidden bg-background text-foreground`,children:[(0,K.jsx)(`div`,{className:s(`hidden h-full shrink-0 transition-[width,opacity] duration-200 md:block`,n?`w-[260px] opacity-100`:`w-0 overflow-hidden opacity-0`),children:n&&(0,K.jsx)(qf,{onOpenSearch:()=>T(!0)})}),E&&(0,K.jsxs)(`div`,{className:`fixed inset-0 z-50 md:hidden`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 bg-black/40`,onClick:()=>O(!1),"aria-hidden":!0}),(0,K.jsx)(`div`,{className:`absolute inset-y-0 left-0 w-[min(280px,88vw)] shadow-xl`,children:(0,K.jsx)(qf,{mobile:!0,onOpenSearch:()=>{O(!1),T(!0)},onNavigate:()=>O(!1)})})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,K.jsxs)(`header`,{className:`flex h-11 shrink-0 items-center gap-1 border-b border-border px-2 sm:px-3`,children:[(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`md:hidden`,onClick:()=>O(!0),"aria-label":`Open sidebar`,children:(0,K.jsx)(je,{className:`size-4`})}),!n&&(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`hidden md:inline-flex`,onClick:u,"aria-label":`Open sidebar`,children:(0,K.jsx)(Le,{className:`size-4`})}),(0,K.jsxs)(`nav`,{className:`flex min-w-0 flex-1 items-center gap-0.5 overflow-hidden text-sm`,children:[N?(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5 px-1.5 text-muted-foreground`,children:[(0,K.jsx)(we,{className:`size-3.5`}),(0,K.jsxs)(`span`,{className:`truncate font-medium text-foreground`,children:[b?.name,_?.relPath?` / ${_.relPath}`:``]})]}):F.map((e,t)=>(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-0.5`,children:[t>0&&(0,K.jsx)(ae,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,K.jsxs)(`button`,{type:`button`,className:s(`max-w-[140px] truncate rounded px-1.5 py-0.5 transition-colors hover:bg-muted sm:max-w-[200px]`,t===F.length-1?`font-medium text-foreground`:`text-muted-foreground`),onClick:()=>d(e.id),children:[(0,K.jsx)(`span`,{className:`mr-1`,children:e.icon}),e.title||`Untitled`]})]},e.id)),!P&&!N&&(0,K.jsx)(`span`,{className:`px-1.5 text-muted-foreground`,children:`No page selected`})]}),(0,K.jsx)(eh,{mode:o,status:c}),(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>f(r===`dark`?`light`:`dark`),"aria-label":r===`dark`?`Switch to light theme`:`Switch to dark theme`,children:r===`dark`?(0,K.jsx)(Xe,{className:`size-4 text-muted-foreground`}):(0,K.jsx)(Fe,{className:`size-4 text-muted-foreground`})}),(P||N)&&(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,title:`Import / export markdown`,onClick:()=>M(!0),children:(0,K.jsx)(fe,{className:`size-4 text-muted-foreground`})}),P&&(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>p(P.id,{favorite:!P.favorite}),"aria-label":P.favorite?`Unfavorite`:`Favorite`,children:(0,K.jsx)(Ye,{className:s(`size-4`,P.favorite?`fill-amber-400 text-amber-500`:`text-muted-foreground`)})}),(0,K.jsx)(`div`,{className:`ml-1 hidden items-center gap-2 sm:flex`,children:x?(0,K.jsx)(Qu,{}):(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`outline`,asChild:!0,children:(0,K.jsx)(a,{to:`/login`,children:`Sign in to sync`})})})]}),(0,K.jsx)(`main`,{className:`min-h-0 flex-1 overflow-y-auto`,children:N?(0,K.jsx)(Lm,{},`${_.mountId}:${_.relPath}`):P?(0,K.jsx)(Lp,{page:P},P.id):(0,K.jsx)(th,{onCreate:()=>h(),onOpenSidebar:()=>{l(!0),O(!0)}})})]}),(0,K.jsx)(Fm,{open:C,onOpenChange:T}),(0,K.jsx)(zf,{open:j,onOpenChange:M}),(0,K.jsx)(bf,{position:`bottom-right`,theme:r,toastOptions:{className:`border border-border bg-background text-foreground`}})]})})}function eh({mode:e,status:t}){if(e===`local`)return(0,K.jsxs)(`span`,{className:`hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground sm:inline-flex`,title:`Guest mode — data stays in this browser`,children:[(0,K.jsx)(W,{className:`size-3`}),`Local only`]});let n=t===`saving`||t===`pending`?`Saving…`:t===`error`?`Sync error`:`Saved to DB`;return(0,K.jsxs)(`span`,{className:s(`hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] sm:inline-flex`,t===`error`?`text-destructive`:`text-muted-foreground`),title:`Signed in — workspace syncs to Postgres`,children:[t===`saving`||t===`pending`?(0,K.jsx)(ke,{className:`size-3 animate-spin`}):(0,K.jsx)(oe,{className:`size-3`}),n]})}function th({onCreate:e,onOpenSidebar:t}){return(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-4 p-8 text-center`,children:[(0,K.jsx)(`p`,{className:`text-lg font-medium`,children:`No page open`}),(0,K.jsx)(`p`,{className:`max-w-sm text-sm text-muted-foreground`,children:`Create a page, open one from the sidebar, or link a markdown folder without importing.`}),(0,K.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[(0,K.jsx)(w,{type:`button`,onClick:e,children:`New page`}),(0,K.jsx)(w,{type:`button`,variant:`outline`,onClick:t,children:`Open sidebar`})]})]})}function nh(){return(0,K.jsx)($m,{})}export{nh as component}; \ No newline at end of file diff --git a/.vercel/output/static/assets/routes-C6kpKjAV.js b/.vercel/output/static/assets/routes-C6kpKjAV.js deleted file mode 100644 index 2d284de..0000000 --- a/.vercel/output/static/assets/routes-C6kpKjAV.js +++ /dev/null @@ -1,58 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-BrAYfHNA.js","assets/index-DU4A6Ttf.js","assets/rolldown-runtime-QTnfLwEv.js","assets/react-Biaal4sZ.js","assets/link-DYUXAN0T.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-_wZywoZs.js","assets/chunk-WYO6CB5R-ajGU-pWR.js","assets/chunk-ICXQ74PX-fa5hHXws.js","assets/dist-D9sYb5Oa.js","assets/chunk-VAUOI2AC-CLN1Ga8_.js","assets/chunk-HOUHSVGY-4s2dJLwR.js","assets/chunk-Q4XR5HBZ-5srkZ5CC.js","assets/chunk-7BUUIJ7U-Bb538aSH.js","assets/chunk-OGEWGWER-Dr-qyYzn.js","assets/chunk-C7G6YPKG-DJfjwbsZ.js","assets/chunk-ZGVPDNZ5-zo3h_nOA.js","assets/rough.esm-CSKSodPl.js","assets/chunk-52WLFC77-BBAyrLn9.js","assets/line-CDW8hdKE.js","assets/path-BWPyau1x.js","assets/array-BifhSqXX.js","assets/chunk-FWX5IMBZ-CiLc9_ts.js","assets/chunk-ZIRB5QZD-C6fEPe3t.js","assets/client-8boibB1R.js"])))=>i.map(i=>d[i]); -import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{t}from"./react-Biaal4sZ.js";import{H as n,s as r,t as i}from"./link-DYUXAN0T.js";import{a,i as o,o as s,r as c,s as l,t as u}from"./index-DU4A6Ttf.js";import{i as d}from"./client-8boibB1R.js";import{a as f,c as p,i as m,l as h,n as g,o as _,r as v,s as y,t as b}from"./use-current-user-BkYwj4ZJ.js";function x(e){if(Array.isArray(e))return e.flatMap(e=>x(e));if(typeof e!=`string`)return[];let t=[],n=0,r,i,a,o,s,c=()=>{for(;n(i=e.charAt(n),i!==`=`&&i!==`;`&&i!==`,`);for(;n=e.length)&&t.push(e.slice(r))}return t}function S(e){return e instanceof Headers?e:Array.isArray(e)||typeof e==`object`?new Headers(e):null}function C(...e){return e.reduce((e,t)=>{let n=S(t);if(!n)return e;for(let[t,r]of n.entries())t===`set-cookie`?x(r).forEach(t=>e.append(`set-cookie`,t)):e.set(t,r);return e},new Headers)}var w=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),T=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),E=e=>{let t=T(e);return t.charAt(0).toUpperCase()+t.slice(1)},D=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),O=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0},k={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},A=e(t()),j=(0,A.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,A.createElement)(`svg`,{ref:c,...k,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:D(`lucide`,i),...!a&&!O(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,A.createElement)(e,t)),...Array.isArray(a)?a:[a]])),M=(e,t)=>{let n=(0,A.forwardRef)(({className:n,...r},i)=>(0,A.createElement)(j,{ref:i,iconNode:t,className:D(`lucide-${w(E(e))}`,`lucide-${e}`,n),...r}));return n.displayName=E(e),n},N=M(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),P=M(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),ee=M(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),F=M(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),I=M(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),L=M(`cloud-off`,[[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M5.782 5.782A7 7 0 0 0 9 19h8.5a4.5 4.5 0 0 0 1.307-.193`,key:`yfwify`}],[`path`,{d:`M21.532 16.5A4.5 4.5 0 0 0 17.5 10h-1.79A7.008 7.008 0 0 0 10 5.07`,key:`jlfiyv`}]]),te=M(`cloud`,[[`path`,{d:`M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z`,key:`p7xjir`}]]),ne=M(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),re=M(`copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),ie=M(`ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),ae=M(`eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),oe=M(`file-plus`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M9 15h6`,key:`cctwl0`}],[`path`,{d:`M12 18v-6`,key:`17g6i2`}]]),se=M(`file-text`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),ce=M(`grip-vertical`,[[`circle`,{cx:`9`,cy:`12`,r:`1`,key:`1vctgf`}],[`circle`,{cx:`9`,cy:`5`,r:`1`,key:`hp0tcf`}],[`circle`,{cx:`9`,cy:`19`,r:`1`,key:`fkjjf6`}],[`circle`,{cx:`15`,cy:`12`,r:`1`,key:`1tmaij`}],[`circle`,{cx:`15`,cy:`5`,r:`1`,key:`19l28e`}],[`circle`,{cx:`15`,cy:`19`,r:`1`,key:`f4zoj3`}]]),le=M(`heading-1`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`m17 12 3-2v8`,key:`1hhhft`}]]),ue=M(`heading-2`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1`,key:`9jr5yi`}]]),de=M(`heading-3`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2`,key:`68ncm8`}],[`path`,{d:`M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2`,key:`1ejuhz`}]]),R=M(`image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),fe=M(`list-ordered`,[[`path`,{d:`M10 12h11`,key:`6m4ad9`}],[`path`,{d:`M10 18h11`,key:`11hvi2`}],[`path`,{d:`M10 6h11`,key:`c7qv1k`}],[`path`,{d:`M4 10h2`,key:`16xx2s`}],[`path`,{d:`M4 6h1v4`,key:`cnovpq`}],[`path`,{d:`M6 18H4c0-1 2-2 2-3s-1-1.5-2-1`,key:`m9a95d`}]]),pe=M(`list-todo`,[[`rect`,{x:`3`,y:`5`,width:`6`,height:`6`,rx:`1`,key:`1defrl`}],[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`path`,{d:`M13 6h8`,key:`15sg57`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 18h8`,key:`oe0vm4`}]]),me=M(`list-tree`,[[`path`,{d:`M21 12h-8`,key:`1bmf0i`}],[`path`,{d:`M21 6H8`,key:`1pqkrb`}],[`path`,{d:`M21 18h-8`,key:`1tm79t`}],[`path`,{d:`M3 6v4c0 1.1.9 2 2 2h3`,key:`1ywdgy`}],[`path`,{d:`M3 10v6c0 1.1.9 2 2 2h3`,key:`2wc746`}]]),he=M(`list`,[[`path`,{d:`M3 12h.01`,key:`nlz23k`}],[`path`,{d:`M3 18h.01`,key:`1tta3j`}],[`path`,{d:`M3 6h.01`,key:`1rqtza`}],[`path`,{d:`M8 12h13`,key:`1za7za`}],[`path`,{d:`M8 18h13`,key:`1lx6n3`}],[`path`,{d:`M8 6h13`,key:`ik3vkj`}]]),ge=M(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),_e=M(`log-in`,[[`path`,{d:`M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4`,key:`u53s6r`}],[`polyline`,{points:`10 17 15 12 10 7`,key:`1ail0h`}],[`line`,{x1:`15`,x2:`3`,y1:`12`,y2:`12`,key:`v6grx8`}]]),ve=M(`menu`,[[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 18h16`,key:`19g7jn`}],[`path`,{d:`M4 6h16`,key:`1o0s65`}]]),ye=M(`message-square`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}]]),be=M(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),xe=M(`moon`,[[`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`,key:`a7tn18`}]]),Se=M(`panel-left-close`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`m16 15-3-3 3-3`,key:`14y99z`}]]),Ce=M(`panel-left`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}]]),we=M(`play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]),Te=M(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Ee=M(`quote`,[[`path`,{d:`M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`rib7q0`}],[`path`,{d:`M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`1ymkrd`}]]),De=M(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Oe=M(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),ke=M(`settings`,[[`path`,{d:`M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z`,key:`1qme2f`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),Ae=M(`sparkles`,[[`path`,{d:`M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z`,key:`4pj2yx`}],[`path`,{d:`M20 3v4`,key:`1olli1`}],[`path`,{d:`M22 5h-4`,key:`1gvqau`}],[`path`,{d:`M4 17v2`,key:`vumght`}],[`path`,{d:`M5 18H3`,key:`zchphs`}]]),je=M(`square-check-big`,[[`path`,{d:`M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.5`,key:`1uzm8b`}],[`path`,{d:`m9 11 3 3L22 4`,key:`1pflzl`}]]),Me=M(`star`,[[`path`,{d:`M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z`,key:`r04s7s`}]]),Ne=M(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Pe=M(`table-2`,[[`path`,{d:`M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18`,key:`gugj83`}]]),Fe=M(`trash-2`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6`,key:`4alrt4`}],[`path`,{d:`M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2`,key:`v07s0e`}],[`line`,{x1:`10`,x2:`10`,y1:`11`,y2:`17`,key:`1uufr5`}],[`line`,{x1:`14`,x2:`14`,y1:`11`,y2:`17`,key:`xtxkd`}]]),Ie=M(`type`,[[`polyline`,{points:`4 7 4 4 20 4 20 7`,key:`1nosan`}],[`line`,{x1:`9`,x2:`15`,y1:`20`,y2:`20`,key:`swin9y`}],[`line`,{x1:`12`,x2:`12`,y1:`4`,y2:`20`,key:`1tx1rr`}]]),Le=M(`wand-sparkles`,[[`path`,{d:`m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72`,key:`ul74o6`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`M5 6v4`,key:`ilb8ba`}],[`path`,{d:`M19 14v4`,key:`blhpug`}],[`path`,{d:`M10 2v2`,key:`7u0qdc`}],[`path`,{d:`M7 8H3`,key:`zfb6yr`}],[`path`,{d:`M21 16h-4`,key:`1cnmox`}],[`path`,{d:`M11 3H9`,key:`1obp7u`}]]),Re=M(`workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]),ze=M(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),Be=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},Ve=(e=>e?Be(e):Be),He=e=>e;function Ue(e,t=He){let n=A.useSyncExternalStore(e.subscribe,A.useCallback(()=>t(e.getState()),[e,t]),A.useCallback(()=>t(e.getInitialState()),[e,t]));return A.useDebugValue(n),n}var We=e=>{let t=Ve(e),n=e=>Ue(t,e);return Object.assign(n,t),n},Ge=(e=>e?We(e):We);function Ke(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var qe=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return qe(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return qe(t)(e)}}}},Je=(e,t)=>(n,r,i)=>{let a={storage:Ke(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(e,t)=>(f(e,t),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return qe(u.getItem.bind(u))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p};function Ye(...e){return e.map(e=>({id:h(`b`),type:e.type,content:e.content??``,checked:e.checked,collapsed:e.collapsed,indent:e.indent??0,showSource:e.showSource,aiOutput:e.aiOutput}))}function Xe(e){let t=Date.now();return{id:h(`page`),title:``,icon:`📄`,cover:null,parentId:null,favorite:!1,createdAt:t,updatedAt:t,blocks:Ye({type:`paragraph`,content:``}),archived:!1,...e}}function Ze(){let e=Xe({title:`Getting Started`,icon:`🚀`,cover:`warm`,favorite:!0,blocks:Ye({type:`paragraph`,content:`Welcome to your workspace — notes, AI assist, Mermaid diagrams, and optional database sync.`},{type:`heading1`,content:`What you can do`},{type:`bullet`,content:`Create pages from the sidebar`},{type:`bullet`,content:`Type / for block types — try AI and Mermaid`},{type:`bullet`,content:`Hover a block → ⋮⋮ menu → Edit with AI`},{type:`bullet`,content:`Sign in to sync pages to the database`},{type:`bullet`,content:`Search with ⌘K / Ctrl+K`},{type:`heading2`,content:`Try AI`},{type:`ai`,content:`Summarize this page as three bullets for a new teammate`},{type:`heading2`,content:`Mermaid`},{type:`mermaid`,content:`flowchart LR - Write[Write notes] --> AI[AI block] - AI --> Diagram[Mermaid] - Diagram --> Ship[Ship]`,showSource:!1},{type:`heading2`,content:`Basics`},{type:`todo`,content:`Rename this page title`,checked:!1},{type:`todo`,content:`Run the AI block above`,checked:!1},{type:`todo`,content:`Toggle Mermaid source / preview`,checked:!0},{type:`callout`,content:`Tip: slash /ai or /mermaid. AI uses Grok when XAI_API_KEY is set; otherwise a local demo mode.`},{type:`quote`,content:`Write first. Organize later.`},{type:`code`,content:`function hello() { - console.log("hello workspace"); -}`},{type:`divider`,content:``},{type:`paragraph`,content:`This starter page is yours — edit freely or start a blank page.`})}),t=Xe({title:`Product Spec`,icon:`📋`,parentId:e.id,blocks:Ye({type:`heading1`,content:`Overview`},{type:`paragraph`,content:`A lightweight personal knowledge base with nested pages, AI, and diagrams.`},{type:`heading2`,content:`Goals`},{type:`numbered`,content:`Capture ideas without friction`},{type:`numbered`,content:`Structure docs with nested pages`},{type:`numbered`,content:`Use AI for summaries and checklists`},{type:`heading2`,content:`Non-goals`},{type:`bullet`,content:`Real-time multiplayer (for now)`},{type:`bullet`,content:`Full offline multi-device without sign-in`},{type:`mermaid`,content:`sequenceDiagram - participant U as User - participant A as App - participant D as Database - U->>A: Edit page - A->>D: Save (when signed in)`,showSource:!1})}),n=Xe({title:`Weekly Notes`,icon:`📅`,favorite:!0,cover:`cool`,blocks:Ye({type:`heading1`,content:`This week`},{type:`todo`,content:`Ship the block editor`,checked:!0},{type:`todo`,content:`Add AI + Mermaid`,checked:!0},{type:`todo`,content:`Write release notes`,checked:!1},{type:`heading2`,content:`Notes`},{type:`paragraph`,content:`Keep daily fragments here. Promote anything durable into its own page.`},{type:`ai`,content:`Turn the todos and notes above into a short status update for stakeholders`},{type:`callout`,content:`Use favorites for the 2–3 pages you open every day.`})});return{pages:[e,t,n,Xe({title:`Reading List`,icon:`📚`,blocks:Ye({type:`heading2`,content:`Queue`},{type:`todo`,content:`Atomic Habits — James Clear`,checked:!1},{type:`todo`,content:`The Design of Everyday Things`,checked:!1},{type:`todo`,content:`Staff Engineer — Will Larson`,checked:!0},{type:`heading2`,content:`Quotes`},{type:`quote`,content:`Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away.`})}),Xe({title:`Meeting Notes`,icon:`🗒`,parentId:n.id,blocks:Ye({type:`heading1`,content:`Kickoff`},{type:`paragraph`,content:`Attendees: design, eng, product`},{type:`bullet`,content:`Align on v1 scope`},{type:`bullet`,content:`Decide on editor primitives`},{type:`bullet`,content:`Ship a polished demo`},{type:`divider`,content:``},{type:`heading3`,content:`Action items`},{type:`todo`,content:`Draft IA for sidebar`,checked:!0},{type:`todo`,content:`Prototype slash menu`,checked:!0},{type:`todo`,content:`Add AI edit-with-block`,checked:!0})})],activePageId:e.id}}var Qe=`📄.📝.📋.📚.💡.🎯.🚀.⭐.🏠.📁.🗂.📅.✅.🔧.🎨.🧠.🌱.🔥.☕.🗒.📦.🧭.🛠.💬.📊.🔍.✨.🏷.📎.🛡`.split(`.`),$e={warm:{label:`Warm`,className:`bg-gradient-to-br from-stone-200 via-amber-100/80 to-orange-100/60`},cool:{label:`Cool`,className:`bg-gradient-to-br from-slate-200 via-sky-100/70 to-stone-100`},soft:{label:`Soft`,className:`bg-gradient-to-br from-zinc-200 via-neutral-100 to-stone-50`},ink:{label:`Ink`,className:`bg-gradient-to-br from-zinc-800 via-stone-700 to-neutral-800`}};function et(e){return{...e,updatedAt:Date.now()}}function tt(e,t){let n=new Set([t]),r=!0;for(;r;){r=!1;for(let t of e)t.parentId&&n.has(t.parentId)&&!n.has(t.id)&&(n.add(t.id),r=!0)}return n}var nt=Ze(),z=Ge()(Je((e,t)=>({name:`Rick's Workspace`,pages:nt.pages,activePageId:nt.activePageId,sidebarOpen:!0,theme:`light`,hydrated:!1,storageMode:`local`,syncStatus:`local`,setHydrated:t=>e({hydrated:t}),setName:t=>e({name:t}),setSidebarOpen:t=>e({sidebarOpen:t}),toggleSidebar:()=>e(e=>({sidebarOpen:!e.sidebarOpen})),setTheme:t=>e({theme:t}),setActivePage:t=>e({activePageId:t}),getPage:e=>t().pages.find(t=>t.id===e),getChildren:e=>t().pages.filter(t=>!t.archived&&t.parentId===e).sort((e,t)=>e.createdAt-t.createdAt),createPage:(t={})=>{let n=Xe({parentId:t.parentId??null,title:t.title??``,icon:t.icon??`📄`});return e(e=>({pages:[...e.pages,n],activePageId:n.id})),n.id},updatePage:(t,n)=>e(e=>({pages:e.pages.map(e=>e.id===t?et({...e,...n}):e)})),deletePage:n=>{let r=tt(t().pages,n);e(e=>{let t=e.pages.map(e=>r.has(e.id)?et({...e,archived:!0}):e),n=e.activePageId;return n&&r.has(n)&&(n=t.find(e=>!e.archived)?.id??null),{pages:t,activePageId:n}})},restorePage:t=>e(e=>({pages:e.pages.map(e=>e.id===t?et({...e,archived:!1}):e)})),permanentlyDeletePage:n=>{let r=tt(t().pages,n);e(e=>{let t=e.pages.filter(e=>!r.has(e.id)),n=e.activePageId;return n&&r.has(n)&&(n=t.find(e=>!e.archived)?.id??null),{pages:t,activePageId:n}})},duplicatePage:n=>{let r=t().getPage(n);if(!r)return null;let i={...r,id:h(`page`),title:r.title?`${r.title} (copy)`:`Untitled (copy)`,createdAt:Date.now(),updatedAt:Date.now(),favorite:!1,archived:!1,blocks:r.blocks.map(e=>({...e,id:h(`b`)}))};return e(e=>({pages:[...e.pages,i],activePageId:i.id})),i.id},movePage:(n,r)=>{r!==n&&(r&&tt(t().pages,n).has(r)||e(e=>({pages:e.pages.map(e=>e.id===n?et({...e,parentId:r}):e)})))},setBlocks:(t,n)=>e(e=>({pages:e.pages.map(e=>e.id===t?et({...e,blocks:n}):e)})),updateBlock:(t,n,r)=>e(e=>({pages:e.pages.map(e=>e.id===t?et({...e,blocks:e.blocks.map(e=>e.id===n?{...e,...r}:e)}):e)})),insertBlock:(t,n,r=`paragraph`,i=``)=>{let a={id:h(`b`),type:r,content:i,indent:0,checked:r!==`todo`&&void 0};return e(e=>({pages:e.pages.map(e=>{if(e.id!==t)return e;let r=[...e.blocks];if(!n)r.unshift(a);else{let e=r.findIndex(e=>e.id===n);e===-1?r.push(a):r.splice(e+1,0,a)}return et({...e,blocks:r})})})),a.id},deleteBlock:(t,n)=>e(e=>({pages:e.pages.map(e=>e.id===t?e.blocks.length<=1?et({...e,blocks:[{id:h(`b`),type:`paragraph`,content:``,indent:0}]}):et({...e,blocks:e.blocks.filter(e=>e.id!==n)}):e)})),changeBlockType:(t,n,r)=>e(e=>({pages:e.pages.map(e=>e.id===t?et({...e,blocks:e.blocks.map(e=>e.id===n?{...e,type:r,checked:r===`todo`?e.checked??!1:void 0,collapsed:r===`toggle`?e.collapsed??!1:void 0}:e)}):e)})),moveBlock:(t,n,r)=>e(e=>({pages:e.pages.map(e=>{if(e.id!==t)return e;let i=[...e.blocks],a=i.findIndex(e=>e.id===n);if(a<0)return e;let o=r===`up`?a-1:a+1;return o<0||o>=i.length?e:([i[a],i[o]]=[i[o],i[a]],et({...e,blocks:i}))})})),resetWorkspace:()=>{let t=Ze();e({name:`Rick's Workspace`,pages:t.pages,activePageId:t.activePageId,sidebarOpen:!0,theme:`light`})}}),{name:`notion-clone-workspace-v1`,partialize:e=>({name:e.name,pages:e.pages,activePageId:e.activePageId,sidebarOpen:e.sidebarOpen,theme:e.theme}),onRehydrateStorage:()=>e=>{e?.setHydrated(!0)}})),rt=Object.defineProperty,it=(e,t)=>rt(e,`name`,{value:t,configurable:!0}),at=!!(typeof window<`u`&&window.document&&window.document.createElement);function B(e,t,{checkForDefaultPrevented:n=!0}={}){return it(function(r){if(e?.(r),n===!1||!r||!r.defaultPrevented)return t?.(r)},`handleEvent`)}it(B,`composeEventHandlers`);function ot(e){if(!at)throw Error(`Cannot access window outside of the DOM`);return e?.ownerDocument?.defaultView??window}it(ot,`getOwnerWindow`);function st(e){if(!at)throw Error(`Cannot access document outside of the DOM`);return e?.ownerDocument??document}it(st,`getOwnerDocument`);function ct(e,t=!1){let{activeElement:n}=st(e);if(!n?.nodeName)return null;if(lt(n)&&n.contentDocument)return ct(n.contentDocument.body,t);if(t){let e=n.getAttribute(`aria-activedescendant`);if(e){let t=st(n).getElementById(e);if(t)return t}}return n}it(ct,`getActiveElement`);function lt(e){return e.tagName===`IFRAME`}it(lt,`isFrame`);var V=r(),ut=Object.defineProperty,dt=(e,t)=>ut(e,`name`,{value:t,configurable:!0});function ft(e,t){let n=A.createContext(t);n.displayName=e+`Context`;let r=dt(e=>{let{children:t,...r}=e,i=A.useMemo(()=>r,Object.values(r));return(0,V.jsx)(n.Provider,{value:i,children:t})},`Provider`);r.displayName=e+`Provider`;function i(r,i={}){let{optional:a=!1}=i,o=A.useContext(n);if(o)return o;if(t!==void 0)return t;if(!a)throw Error(`\`${r}\` must be used within \`${e}\``)}return dt(i,`useContext`),[r,i]}dt(ft,`createContext`);function pt(e,t=[]){let n=[];function r(t,r){let i=A.createContext(r);i.displayName=t+`Context`;let a=n.length;n=[...n,r];let o=dt(t=>{let{scope:n,children:r,...o}=t,s=n?.[e]?.[a]||i,c=A.useMemo(()=>o,Object.values(o));return(0,V.jsx)(s.Provider,{value:c,children:r})},`Provider`);o.displayName=t+`Provider`;function s(n,o,s={}){let{optional:c=!1}=s,l=o?.[e]?.[a]||i,u=A.useContext(l);if(u)return u;if(r!==void 0)return r;if(!c)throw Error(`\`${n}\` must be used within \`${t}\``)}return dt(s,`useContext`),[o,s]}dt(r,`createContext`);let i=dt(()=>{let t=n.map(e=>A.createContext(e));return dt(function(n){let r=n?.[e]||t;return A.useMemo(()=>({[`__scope${e}`]:{...n,[e]:r}}),[n,r])},`useScope`)},`createScope`);return i.scopeName=e,[r,mt(i,...t)]}dt(pt,`createContextScope`);function mt(...e){let t=e[0];if(e.length===1)return t;let n=dt(()=>{let n=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return dt(function(e){let r=n.reduce((t,{useScope:n,scopeName:r})=>{let i=n(e)[`__scope${r}`];return{...t,...i}},{});return A.useMemo(()=>({[`__scope${t.scopeName}`]:r}),[r])},`useComposedScopes`)},`createScope`);return n.scopeName=t.scopeName,n}dt(mt,`composeContextScopes`);var ht=e(n(),1),gt=Object.defineProperty,_t=(e,t)=>gt(e,`name`,{value:t,configurable:!0}),H=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`].reduce((e,t)=>{let n=m(`Primitive.${t}`),r=A.forwardRef((e,r)=>{let{asChild:i,...a}=e,o=i?n:t;return typeof window<`u`&&(window[Symbol.for(`radix-ui`)]=!0),(0,V.jsx)(o,{...a,ref:r})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function vt(e,t){e&&ht.flushSync(()=>e.dispatchEvent(t))}_t(vt,`dispatchDiscreteCustomEvent`);var yt=Object.defineProperty,bt=(e,t)=>yt(e,`name`,{value:t,configurable:!0});function U(e){let t=A.useRef(e);return A.useEffect(()=>{t.current=e}),A.useMemo(()=>((...e)=>t.current?.(...e)),[])}bt(U,`useCallbackRef`);var xt=Object.defineProperty,W=(e,t)=>xt(e,`name`,{value:t,configurable:!0}),St=`dismissableLayer.update`,Ct=`dismissableLayer.pointerDownOutside`,wt=`dismissableLayer.focusOutside`,Tt,Et=A.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Dt=A.forwardRef(W(function(e,t){let{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,u=A.useContext(Et),[d,f]=A.useState(null),p=d?.ownerDocument??globalThis?.document,[,m]=A.useState({}),h=y(t,f),g=Array.from(u.layers),[_]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),v=_?g.indexOf(_):-1,b=d?g.indexOf(d):-1,x=u.layersWithOutsidePointerEventsDisabled.size>0,S=b>=v,C=A.useRef(!1),w=At(e=>{a?.(e),s?.(e),e.defaultPrevented||c?.()},{ownerDocument:p,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:C,dismissableSurfaces:u.dismissableSurfaces,shouldHandlePointerDownOutside:A.useCallback(e=>{if(!(e instanceof Node))return!1;let t=[...u.branches].some(t=>t.contains(e));return S&&!t},[u.branches,S])}),T=jt(e=>{if(r&&C.current)return;let t=e.target;[...u.branches].some(e=>e.contains(t))||(o?.(e),s?.(e),e.defaultPrevented||c?.())},p),E=d?b===g.length-1:!1,D=U(e=>{e.key===`Escape`&&(i?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))});return A.useEffect(()=>{if(E)return p.addEventListener(`keydown`,D,{capture:!0}),()=>p.removeEventListener(`keydown`,D,{capture:!0})},[p,E,D]),A.useEffect(()=>{if(d)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(Tt=p.body.style.pointerEvents,p.body.style.pointerEvents=`none`),u.layersWithOutsidePointerEventsDisabled.add(d)),u.layers.add(d),Mt(),()=>{n&&(u.layersWithOutsidePointerEventsDisabled.delete(d),u.layersWithOutsidePointerEventsDisabled.size===0&&(p.body.style.pointerEvents=Tt))}},[d,p,n,u]),A.useEffect(()=>()=>{d&&(u.layers.delete(d),u.layersWithOutsidePointerEventsDisabled.delete(d),Mt())},[d,u]),A.useEffect(()=>{let e=W(()=>m({}),`handleUpdate`);return document.addEventListener(St,e),()=>document.removeEventListener(St,e)},[]),(0,V.jsx)(H.div,{...l,ref:h,style:{pointerEvents:x?S?`auto`:`none`:void 0,...e.style},onFocusCapture:B(e.onFocusCapture,T.onFocusCapture),onBlurCapture:B(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:B(e.onPointerDownCapture,w.onPointerDownCapture)})},`DismissableLayer`));function Ot(){let e=A.useContext(Et),[t,n]=A.useState(null);return A.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}W(Ot,`useDismissableLayerSurface`);var kt=W(()=>!0,`IS_TRUE`);function At(e,t){let{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:o=kt}=t,s=U(e),c=A.useRef(!1),l=A.useRef(!1),u=A.useRef(new Map),d=A.useRef(()=>{});return A.useEffect(()=>{function e(){l.current=!1,i.current=!1,u.current.clear()}W(e,`resetOutsideInteraction`);function t(){return Array.from(u.current.values()).some(Boolean)}W(t,`isOutsideInteractionIntercepted`);function f(e){if(!l.current)return;let t=e.target;t instanceof Node&&[...a].some(e=>e.contains(t))||u.current.set(e.type,!0),e.type===`click`&&window.setTimeout(()=>{l.current&&d.current()},0)}W(f,`handleInteractionCapture`);function p(e){l.current&&u.current.set(e.type,!1)}W(p,`handleInteractionBubble`);let m=W(a=>{if(a.target&&!c.current){let f=function(){n.removeEventListener(`click`,d.current);let r=t();e(),r||Nt(Ct,s,p,{discrete:!0})};if(W(f,`handleAndDispatchPointerDownOutsideEvent`),!o(a.target)){n.removeEventListener(`click`,d.current),e(),c.current=!1;return}let p={originalEvent:a};l.current=!0,i.current=r&&a.button===0,u.current.clear(),!r||a.button!==0?f():(n.removeEventListener(`click`,d.current),d.current=f,n.addEventListener(`click`,d.current,{once:!0}))}else n.removeEventListener(`click`,d.current),e();c.current=!1},`handlePointerDown`),h=[`pointerup`,`mousedown`,`mouseup`,`touchstart`,`touchend`,`click`];for(let e of h)n.addEventListener(e,f,!0),n.addEventListener(e,p);let g=window.setTimeout(()=>{n.addEventListener(`pointerdown`,m)},0);return()=>{window.clearTimeout(g),n.removeEventListener(`pointerdown`,m),n.removeEventListener(`click`,d.current);for(let e of h)n.removeEventListener(e,f,!0),n.removeEventListener(e,p)}},[n,s,r,i,a,o]),{onPointerDownCapture:W(()=>c.current=!0,`onPointerDownCapture`)}}W(At,`usePointerDownOutside`);function jt(e,t=globalThis?.document){let n=U(e),r=A.useRef(!1);return A.useEffect(()=>{let e=W(e=>{e.target&&!r.current&&Nt(wt,n,{originalEvent:e},{discrete:!1})},`handleFocus`);return t.addEventListener(`focusin`,e),()=>t.removeEventListener(`focusin`,e)},[t,n]),{onFocusCapture:W(()=>r.current=!0,`onFocusCapture`),onBlurCapture:W(()=>r.current=!1,`onBlurCapture`)}}W(jt,`useFocusOutside`);function Mt(){let e=new CustomEvent(St);document.dispatchEvent(e)}W(Mt,`dispatchUpdate`);function Nt(e,t,n,{discrete:r}){let i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?vt(i,a):i.dispatchEvent(a)}W(Nt,`handleAndDispatchCustomEvent`);var G=globalThis?.document?A.useLayoutEffect:()=>{},Pt=Object.defineProperty,Ft=(e,t)=>Pt(e,`name`,{value:t,configurable:!0}),It=A.useId||(()=>void 0),Lt=0;function K(e){let[t,n]=A.useState(It());return G(()=>{e||n(e=>e??String(Lt++))},[e]),e||(t?`radix-${t}`:``)}Ft(K,`useId`);var Rt=[`top`,`right`,`bottom`,`left`],zt=Math.min,Bt=Math.max,Vt=Math.round,Ht=Math.floor,Ut=e=>({x:e,y:e}),Wt={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function Gt(e,t,n){return Bt(e,zt(t,n))}function Kt(e,t){return typeof e==`function`?e(t):e}function qt(e){return e.split(`-`)[0]}function Jt(e){return e.split(`-`)[1]}function Yt(e){return e===`x`?`y`:`x`}function Xt(e){return e===`y`?`height`:`width`}function Zt(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function Qt(e){return Yt(Zt(e))}function $t(e,t,n){n===void 0&&(n=!1);let r=Jt(e),i=Qt(e),a=Xt(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=ln(o)),[o,ln(o)]}function en(e){let t=ln(e);return[tn(e),t,tn(t)]}function tn(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var nn=[`left`,`right`],rn=[`right`,`left`],an=[`top`,`bottom`],on=[`bottom`,`top`];function sn(e,t,n){switch(e){case`top`:case`bottom`:return n?t?rn:nn:t?nn:rn;case`left`:case`right`:return t?an:on;default:return[]}}function cn(e,t,n,r){let i=Jt(e),a=sn(qt(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(tn)))),a}function ln(e){let t=qt(e);return Wt[t]+e.slice(t.length)}function un(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function dn(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:un(e)}function fn(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function pn(e,t,n){let{reference:r,floating:i}=e,a=Zt(t),o=Qt(t),s=Xt(o),c=qt(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=Jt(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function mn(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=Kt(t,e),p=dn(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=fn(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=fn(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var hn=50,gn=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:mn},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=pn(l,r,c),f=r,p=0,m={};for(let n=0;n({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=Kt(e,t)||{};if(l==null)return{};let d=dn(u),f={x:n,y:r},p=Qt(i),m=Xt(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l)),C=S?S[y]:0;(!C||!await(o.isElement==null?void 0:o.isElement(S)))&&(C=s.floating[y]||a.floating[m]);let w=b/2-x/2,T=C/2-h[m]/2-1,E=zt(d[_],T),D=zt(d[v],T),O=C-h[m]-D,k=C/2-h[m]/2+w,A=Gt(E,k,O),j=!c.arrow&&Jt(i)!=null&&k!==A&&a.reference[m]/2-(ke<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(!(u===`alignment`&&_!==Zt(t))||T.every(e=>Zt(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=Zt(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o;break}if(r!==n)return{reset:{placement:n}}}return{}}}};function yn(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function bn(e){return Rt.some(t=>e[t]>=0)}var xn=function(e){return e===void 0&&(e={}),{name:`hide`,options:e,async fn(t){let{rects:n,platform:r}=t,{strategy:i=`referenceHidden`,...a}=Kt(e,t);switch(i){case`referenceHidden`:{let e=yn(await r.detectOverflow(t,{...a,elementContext:`reference`}),n.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:bn(e)}}}case`escaped`:{let e=yn(await r.detectOverflow(t,{...a,altBoundary:!0}),n.floating);return{data:{escapedOffsets:e,escaped:bn(e)}}}default:return{}}}}},Sn=new Set([`left`,`top`]);async function Cn(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=qt(n),s=Jt(n),c=Zt(n)===`y`,l=Sn.has(o)?-1:1,u=a&&c?-1:1,d=Kt(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var wn=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await Cn(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},Tn=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=Kt(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=Zt(i),p=Yt(f),m=u[p],h=u[f],g=(e,t)=>Gt(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},En=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=Kt(e,t),u={x:n,y:r},d=Zt(i),f=Yt(d),p=u[f],m=u[d],h=Kt(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;pn&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=Sn.has(qt(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);mr&&(m=r)}return{[f]:p,[d]:m}}}},Dn=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=Kt(e,t),c=await i.detectOverflow(t,s),l=qt(n),u=Jt(n),d=Zt(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=zt(p-c[m],g),y=zt(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*Bt(c.left,c.right):S=p-2*Bt(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function On(){return typeof window<`u`}function kn(e){return jn(e)?(e.nodeName||``).toLowerCase():`#document`}function q(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function An(e){return((jn(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function jn(e){return On()?e instanceof Node||e instanceof q(e).Node:!1}function Mn(e){return On()?e instanceof Element||e instanceof q(e).Element:!1}function Nn(e){return On()?e instanceof HTMLElement||e instanceof q(e).HTMLElement:!1}function Pn(e){return!On()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof q(e).ShadowRoot}function Fn(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=Kn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function In(e){return/^(table|td|th)$/.test(kn(e))}function Ln(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var Rn=/transform|translate|scale|rotate|perspective|filter/,zn=/paint|layout|strict|content/,Bn=e=>!!e&&e!==`none`,Vn;function Hn(e){let t=Mn(e)?Kn(e):e;return Bn(t.transform)||Bn(t.translate)||Bn(t.scale)||Bn(t.rotate)||Bn(t.perspective)||!Wn()&&(Bn(t.backdropFilter)||Bn(t.filter))||Rn.test(t.willChange||``)||zn.test(t.contain||``)}function Un(e){let t=Jn(e);for(;Nn(t)&&!Gn(t);){if(Hn(t))return t;if(Ln(t))return null;t=Jn(t)}return null}function Wn(){return Vn??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),Vn}function Gn(e){return/^(html|body|#document)$/.test(kn(e))}function Kn(e){return q(e).getComputedStyle(e)}function qn(e){return Mn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Jn(e){if(kn(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||Pn(e)&&e.host||An(e);return Pn(t)?t.host:t}function Yn(e){let t=Jn(e);return Gn(t)?(e.ownerDocument||e).body:Nn(t)&&Fn(t)?t:Yn(t)}function Xn(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=Yn(e),i=r===e.ownerDocument?.body,a=q(r);if(i){let e=Zn(a);return t.concat(a,a.visualViewport||[],Fn(r)?r:[],e&&n?Xn(e):[])}else return t.concat(r,Xn(r,[],n))}function Zn(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Qn(e){let t=Kn(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=Nn(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=Vt(n)!==a||Vt(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function $n(e){return Mn(e)?e:e.contextElement}function er(e){let t=$n(e);if(!Nn(t))return Ut(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=Qn(t),o=(a?Vt(n.width):n.width)/r,s=(a?Vt(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var tr=Ut(0);function nr(e){let t=q(e);return!Wn()||!t.visualViewport?tr:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function rr(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===q(e)}function ir(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=$n(e),o=Ut(1);t&&(r?Mn(r)&&(o=er(r)):o=er(e));let s=rr(a,n,r)?nr(a):Ut(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=q(a),t=Mn(r)?q(r):r,n=e,i=Zn(n);for(;i&&t!==n;){let e=er(i),t=i.getBoundingClientRect(),r=Kn(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=q(i),i=Zn(n)}}return fn({width:u,height:d,x:c,y:l})}function ar(e,t){let n=qn(e).scrollLeft;return t?t.left+n:ir(An(e)).left+n}function or(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ar(e,n),y:n.top+t.scrollTop}}function sr(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=An(r),s=t?Ln(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=Ut(1),u=Ut(0),d=Nn(r);if((d||!a)&&((kn(r)!==`body`||Fn(o))&&(c=qn(r)),d)){let e=ir(r);l=er(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?or(o,c):Ut(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function cr(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function lr(e){let t=qn(e),n=e.ownerDocument.body,r=Bt(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Bt(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+ar(e),o=-t.scrollTop;return Kn(n).direction===`rtl`&&(a+=Bt(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var ur=25;function dr(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=q(e),a=An(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!Wn()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(ar(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=ur&&(s-=o)}return{width:s,height:c,x:l,y:u}}function fr(e,t){let n=ir(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=er(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function pr(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=dr(e,n,t);else if(t===`document`)r=lr(An(e));else if(Mn(t))r=fr(t,n);else{let n=nr(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return fn(r)}function mr(e,t){let n=t.get(e);if(n)return n;let r=Xn(e,[],!1).filter(e=>Mn(e)&&kn(e)!==`body`),i=null,a=Kn(e).position===`fixed`,o=a?Jn(e):e;for(;Mn(o)&&!Gn(o);){let e=Kn(o),t=Hn(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=Jn(o)}return t.set(e,r),r}function hr(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?Ln(t)?[]:mr(t,this._c):[].concat(n),r],o=pr(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=q(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function Er(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=$n(e),u=i||a?[...l?Xn(l):[],...t?Xn(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?Tr(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?ir(e):null;c&&g();function g(){let t=ir(e);h&&!wr(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var Dr=wn,Or=Tn,kr=vn,Ar=Dn,jr=xn,Mr=_n,Nr=En,Pr=(e,t,n)=>{let r=new Map,i=n??{},a={...Cr,...i.platform,_c:r};return gn(e,t,{...i,platform:a})},Fr=typeof document<`u`?A.useLayoutEffect:function(){};function Ir(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e==`function`&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ir(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!Ir(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function Lr(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Rr(e,t){let n=Lr(e);return Math.round(t*n)/n}function zr(e){let t=A.useRef(e);return Fr(()=>{t.current=e}),t}function Br(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=A.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=A.useState(r);Ir(f,r)||p(r);let[m,h]=A.useState(null),[g,_]=A.useState(null),v=A.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=A.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=A.useRef(null),C=A.useRef(null),w=A.useRef(u),T=c!=null,E=zr(c),D=zr(i),O=zr(l),k=A.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),Pr(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};j.current&&!Ir(w.current,t)&&(w.current=t,ht.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);Fr(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let j=A.useRef(!1);Fr(()=>(j.current=!0,()=>{j.current=!1}),[]),Fr(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,k);k()}},[b,x,k,E,T]);let M=A.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),N=A.useMemo(()=>({reference:b,floating:x}),[b,x]),P=A.useMemo(()=>{let e={position:n,left:0,top:0};if(!N.floating)return e;let t=Rr(N.floating,u.x),r=Rr(N.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...Lr(N.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,N.floating,u.x,u.y]);return A.useMemo(()=>({...u,update:k,refs:M,elements:N,floatingStyles:P}),[u,k,M,N,P])}var Vr=e=>{function t(e){return{}.hasOwnProperty.call(e,`current`)}return{name:`arrow`,options:e,fn(n){let{element:r,padding:i}=typeof e==`function`?e(n):e;return r&&t(r)?r.current==null?{}:Mr({element:r.current,padding:i}).fn(n):r?Mr({element:r,padding:i}).fn(n):{}}}},Hr=(e,t)=>{let n=Dr(e);return{name:n.name,fn:n.fn,options:[e,t]}},Ur=(e,t)=>{let n=Or(e);return{name:n.name,fn:n.fn,options:[e,t]}},Wr=(e,t)=>({fn:Nr(e).fn,options:[e,t]}),Gr=(e,t)=>{let n=kr(e);return{name:n.name,fn:n.fn,options:[e,t]}},Kr=(e,t)=>{let n=Ar(e);return{name:n.name,fn:n.fn,options:[e,t]}},qr=(e,t)=>{let n=jr(e);return{name:n.name,fn:n.fn,options:[e,t]}},Jr=(e,t)=>{let n=Vr(e);return{name:n.name,fn:n.fn,options:[e,t]}},Yr=Object.defineProperty,Xr=(e,t)=>Yr(e,`name`,{value:t,configurable:!0});function Zr(e){let[t,n]=A.useState(void 0);return G(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});let t=new ResizeObserver(t=>{if(!Array.isArray(t)||!t.length)return;let r=t[0],i,a;if(`borderBoxSize`in r){let e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;i=t.inlineSize,a=t.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return t.observe(e,{box:`border-box`}),()=>t.unobserve(e)}else n(void 0)},[e]),t}Xr(Zr,`useSize`);var Qr=Object.defineProperty,$r=(e,t)=>Qr(e,`name`,{value:t,configurable:!0}),ei=`Popper`,[ti,ni]=pt(ei),[ri,ii]=ti(ei),ai=$r(e=>{let{__scopePopper:t,children:n}=e,[r,i]=A.useState(null),[a,o]=A.useState(void 0);return(0,V.jsx)(ri,{scope:t,anchor:r,onAnchorChange:i,placementState:a,setPlacementState:o,children:n})},`Popper`),oi=`PopperAnchor`,si=A.forwardRef($r(function(e,t){let{__scopePopper:n,virtualRef:r,...i}=e,a=ii(oi,n),o=A.useRef(null),s=a.onAnchorChange,c=y(t,A.useCallback(e=>{o.current=e,e&&s(e)},[s])),l=A.useRef(null);A.useEffect(()=>{if(!r)return;let e=l.current;l.current=r.current,e!==l.current&&s(l.current)});let u=a.placementState&&mi(a.placementState),d=u?.[0],f=u?.[1];return r?null:(0,V.jsx)(H.div,{"data-radix-popper-side":d,"data-radix-popper-align":f,...i,ref:c})},`PopperAnchor`)),ci=`PopperContent`,[li,ui]=ti(ci),di=A.forwardRef($r(function(e,t){let{__scopePopper:n,side:r=`bottom`,sideOffset:i=0,align:a=`center`,alignOffset:o=0,arrowPadding:s=0,avoidCollisions:c=!0,collisionBoundary:l=[],collisionPadding:u=0,sticky:d=`partial`,hideWhenDetached:f=!1,updatePositionStrategy:p=`optimized`,onPlaced:m,...h}=e,g=ii(ci,n),[_,v]=A.useState(null),b=y(t,v),[x,S]=A.useState(null),C=Zr(x),w=C?.width??0,T=C?.height??0,E=r+(a===`center`?``:`-`+a),D=typeof u==`number`?u:{top:0,right:0,bottom:0,left:0,...u},O=Array.isArray(l)?l:[l],k=O.length>0,j={padding:D,boundary:O.filter(fi),altBoundary:k},{refs:M,floatingStyles:N,placement:P,isPositioned:ee,middlewareData:F}=Br({strategy:`fixed`,placement:E,whileElementsMounted:$r((...e)=>Er(...e,{animationFrame:p===`always`}),`whileElementsMounted`),elements:{reference:g.anchor},middleware:[Hr({mainAxis:i+T,alignmentAxis:o}),c&&Ur({mainAxis:!0,crossAxis:!1,limiter:d===`partial`?Wr():void 0,...j}),c&&Gr({...j}),Kr({...j,apply:$r(({elements:e,rects:t,availableWidth:n,availableHeight:r})=>{let{width:i,height:a}=t.reference,o=e.floating.style;o.setProperty(`--radix-popper-available-width`,`${n}px`),o.setProperty(`--radix-popper-available-height`,`${r}px`),o.setProperty(`--radix-popper-anchor-width`,`${i}px`),o.setProperty(`--radix-popper-anchor-height`,`${a}px`)},`apply`)}),x&&Jr({element:x,padding:s}),pi({arrowWidth:w,arrowHeight:T}),f&&qr({strategy:`referenceHidden`,...j,boundary:k?j.boundary:void 0})]}),I=g.setPlacementState;G(()=>(I(P),()=>{I(void 0)}),[P,I]);let[L,te]=mi(P),ne=U(m);G(()=>{ee&&ne?.()},[ee,ne]);let re=F.arrow?.x,ie=F.arrow?.y,ae=F.arrow?.centerOffset!==0,[oe,se]=A.useState();return G(()=>{_&&se(window.getComputedStyle(_).zIndex)},[_]),(0,V.jsx)(`div`,{ref:M.setFloating,"data-radix-popper-content-wrapper":``,style:{...N,transform:ee?N.transform:`translate(0, -200%)`,minWidth:`max-content`,zIndex:oe,"--radix-popper-transform-origin":[F.transformOrigin?.x,F.transformOrigin?.y].join(` `),...F.hide?.referenceHidden&&{visibility:`hidden`,pointerEvents:`none`}},dir:e.dir,children:(0,V.jsx)(li,{scope:n,placedSide:L,placedAlign:te,onArrowChange:S,arrowX:re,arrowY:ie,shouldHideArrow:ae,children:(0,V.jsx)(H.div,{"data-side":L,"data-align":te,...h,ref:b,style:{...h.style,animation:ee?h.style?.animation:`none`}})})})},`PopperContent`));function fi(e){return e!==null}$r(fi,`isNotNull`);var pi=$r(e=>({name:`transformOrigin`,options:e,fn(t){let{placement:n,rects:r,middlewareData:i}=t,a=i.arrow?.centerOffset!==0,o=a?0:e.arrowWidth,s=a?0:e.arrowHeight,[c,l]=mi(n),u={start:`0%`,center:`50%`,end:`100%`}[l],d=(i.arrow?.x??0)+o/2,f=(i.arrow?.y??0)+s/2,p=``,m=``;return c===`bottom`?(p=a?u:`${d}px`,m=`${-s}px`):c===`top`?(p=a?u:`${d}px`,m=`${r.floating.height+s}px`):c===`right`?(p=`${-s}px`,m=a?u:`${f}px`):c===`left`&&(p=`${r.floating.width+s}px`,m=a?u:`${f}px`),{data:{x:p,y:m}}}}),`transformOrigin`);function mi(e){let[t,n=`center`]=e.split(`-`);return[t,n]}$r(mi,`getSideAndAlignFromPlacement`);var hi=Object.defineProperty,gi=A.forwardRef(((e,t)=>hi(e,`name`,{value:t,configurable:!0}))(function(e,t){let{container:n,...r}=e,[i,a]=A.useState(!1);G(()=>a(!0),[]);let o=n||i&&globalThis?.document?.body;return o?ht.createPortal((0,V.jsx)(H.div,{...r,ref:t}),o):null},`Portal`)),_i=Object.defineProperty,vi=(e,t)=>_i(e,`name`,{value:t,configurable:!0});function yi(e,t){return A.useReducer((e,n)=>t[e][n]??e,e)}vi(yi,`useStateMachine`);var bi=vi(e=>{let{present:t,children:n}=e,r=xi(t),i=typeof n==`function`?n({present:r.isPresent}):A.Children.only(n),a=Ci(r.ref,Ti(i));return typeof n==`function`||r.isPresent?A.cloneElement(i,{ref:a}):null},`Presence`);function xi(e){let[t,n]=A.useState(),r=A.useRef(null),i=A.useRef(e),a=A.useRef(`none`),o=A.useRef(void 0),[s,c]=yi(e?`mounted`:`unmounted`,{mounted:{UNMOUNT:`unmounted`,ANIMATION_OUT:`unmountSuspended`},unmountSuspended:{MOUNT:`mounted`,ANIMATION_END:`unmounted`},unmounted:{MOUNT:`mounted`}});return A.useEffect(()=>{s===`mounted`?(a.current=o.current??wi(r.current),o.current=void 0):a.current=`none`},[s]),G(()=>{let t=r.current,n=i.current;if(n!==e){let r=a.current,s=wi(t);e?(o.current=s,c(`MOUNT`)):s===`none`||t?.display===`none`?c(`UNMOUNT`):c(n&&r!==s?`ANIMATION_OUT`:`UNMOUNT`),i.current=e}},[e,c]),G(()=>{if(t){let e,n=t.ownerDocument.defaultView??window,o=vi(a=>{let o=wi(r.current).includes(CSS.escape(a.animationName));if(a.target===t&&o&&(c(`ANIMATION_END`),!i.current)){let r=t.style.animationFillMode;t.style.animationFillMode=`forwards`,e=n.setTimeout(()=>{t.style.animationFillMode===`forwards`&&(t.style.animationFillMode=r)})}},`handleAnimationEnd`),s=vi(e=>{e.target===t&&(a.current=wi(r.current))},`handleAnimationStart`);return t.addEventListener(`animationstart`,s),t.addEventListener(`animationcancel`,o),t.addEventListener(`animationend`,o),()=>{n.clearTimeout(e),t.removeEventListener(`animationstart`,s),t.removeEventListener(`animationcancel`,o),t.removeEventListener(`animationend`,o)}}else c(`ANIMATION_END`)},[t,c]),{isPresent:[`mounted`,`unmountSuspended`].includes(s),ref:A.useCallback(e=>{if(e){let t=getComputedStyle(e);r.current=t,o.current=wi(t)}else r.current=null;n(e)},[])}}vi(xi,`usePresence`);function Si(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}vi(Si,`setRef`);function Ci(...e){let t=A.useRef(e);return t.current=e,A.useCallback(e=>{let n=t.current,r=!1,i=n.map(t=>{let n=Si(t,e);return!r&&typeof n==`function`&&(r=!0),n});if(r)return()=>{for(let e=0;eEi(e,`name`,{value:t,configurable:!0}),Oi=A.useEffectEvent,ki=A.useInsertionEffect;function Ai(e){if(typeof Oi==`function`)return Oi(e);let t=A.useRef(()=>{throw Error(`Cannot call an event handler while rendering.`)});return typeof ki==`function`?ki(()=>{t.current=e}):G(()=>{t.current=e}),A.useMemo(()=>((...e)=>t.current?.(...e)),[])}Di(Ai,`useEffectEvent`);var ji=Object.defineProperty,Mi=(e,t)=>ji(e,`name`,{value:t,configurable:!0}),Ni=A.useInsertionEffect||G;function Pi({prop:e,defaultProp:t,onChange:n=Mi(()=>{},`onChange`),caller:r}){let[i,a,o]=Fi({defaultProp:t,onChange:n}),s=e!==void 0;return[s?e:i,A.useCallback(t=>{if(s){let n=Ii(t)?t(e):t;n!==e&&o.current?.(n)}else a(t)},[s,e,a,o])]}Mi(Pi,`useControllableState`);function Fi({defaultProp:e,onChange:t}){let[n,r]=A.useState(e),i=A.useRef(n),a=A.useRef(t);return Ni(()=>{a.current=t},[t]),A.useEffect(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}Mi(Fi,`useUncontrolledState`);function Ii(e){return typeof e==`function`}Mi(Ii,`isFunction`);var Li=Symbol(`RADIX:SYNC_STATE`);function Ri(e,t,n,r){let{prop:i,defaultProp:a,onChange:o,caller:s}=t,c=i!==void 0,l=Ai(o),u=[{...n,state:a}];r&&u.push(r);let[d,f]=A.useReducer((t,n)=>{if(n.type===Li)return{...t,state:n.state};let r=e(t,n);return c&&!Object.is(r.state,t.state)&&l(r.state),r},...u),p=d.state,m=A.useRef(p);A.useEffect(()=>{m.current!==p&&(m.current=p,c||l(p))},[p,m,c]);let h=A.useMemo(()=>i===void 0?d:{...d,state:i},[d,i]);return A.useEffect(()=>{c&&!Object.is(i,d.state)&&f({type:Li,state:i})},[i,d.state,c]),[h,f]}Mi(Ri,`useControllableStateReducer`);var zi=Object.defineProperty,Bi=(e,t)=>zi(e,`name`,{value:t,configurable:!0}),[Vi,Hi]=pt(`Tooltip`,[ni]);ni();var Ui=`TooltipProvider`,Wi=700,[Gi,Ki]=Vi(Ui),qi=Bi(e=>{let{__scopeTooltip:t,delayDuration:n=Wi,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,o=A.useRef(!0),s=A.useRef(!1),c=A.useRef(0);return A.useEffect(()=>{let e=c.current;return()=>window.clearTimeout(e)},[]),(0,V.jsx)(Gi,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:A.useCallback(()=>{r<=0||(window.clearTimeout(c.current),o.current=!1)},[r]),onClose:A.useCallback(()=>{r<=0||(window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.current=!0,r))},[r]),isPointerInTransitRef:s,onPointerInTransitChange:A.useCallback(e=>{s.current=e},[]),disableHoverableContent:i,children:a})},`TooltipProvider`),[Ji,Yi]=Vi(`Tooltip`),[Xi,Zi]=Vi(`TooltipPortal`,{forceMount:void 0});f(`TooltipContent`);function Qi(e,t){let n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return`left`;case i:return`right`;case n:return`top`;case r:return`bottom`;default:throw Error(`unreachable`)}}Bi(Qi,`getExitSideFromRect`);function $i(e,t,n=5){let r=[];switch(t){case`top`:r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case`bottom`:r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case`left`:r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case`right`:r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}Bi($i,`getPaddedExitPoints`);function ea(e){let{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}Bi(ea,`getPointsFromRect`);function ta(e,t){let{x:n,y:r}=e,i=!1;for(let e=0,a=t.length-1;er!=d>r&&n<(u-c)*(r-l)/(d-l)+c&&(i=!i)}return i}Bi(ta,`isPointInPolygon`);function na(e){let t=e.slice();return t.sort((e,t)=>e.xt.x?1:e.yt.y)),ra(t)}Bi(na,`getHull`);function ra(e){if(e.length<=1)return e.slice();let t=[];for(let n=0;n=2;){let e=t[t.length-1],n=t[t.length-2];if((e.x-n.x)*(r.y-n.y)>=(e.y-n.y)*(r.x-n.x))t.pop();else break}t.push(r)}t.pop();let n=[];for(let t=e.length-1;t>=0;t--){let r=e[t];for(;n.length>=2;){let e=n[n.length-1],t=n[n.length-2];if((e.x-t.x)*(r.y-t.y)>=(e.y-t.y)*(r.x-t.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}Bi(ra,`getHullPresorted`);function ia(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}Bi(ia,`concatAriaDescribedby`);var aa=qi,oa=Object.defineProperty,sa=(e,t)=>oa(e,`name`,{value:t,configurable:!0}),ca=A.createContext(void 0);function la(e){let t=A.useContext(ca);return e||t||`ltr`}sa(la,`useDirection`);var ua=Object.defineProperty,da=(e,t)=>ua(e,`name`,{value:t,configurable:!0});function fa(e,[t,n]){return Math.min(n,Math.max(t,e))}da(fa,`clamp`);var pa=Object.defineProperty,J=(e,t)=>pa(e,`name`,{value:t,configurable:!0});function ma(e,t){return A.useReducer((e,n)=>t[e][n]??e,e)}J(ma,`useStateMachine`);var ha=`ScrollArea`,[ga,_a]=pt(ha),[va,ya]=ga(ha),ba=A.forwardRef(J(function(e,t){let{__scopeScrollArea:n,type:r=`hover`,dir:i,scrollHideDelay:a=600,...o}=e,[s,c]=A.useState(null),[l,u]=A.useState(null),[d,f]=A.useState(null),[p,m]=A.useState(null),[h,g]=A.useState(null),[_,v]=A.useState(0),[b,x]=A.useState(0),[S,C]=A.useState(!1),[w,T]=A.useState(!1),E=y(t,c),D=la(i);return(0,V.jsx)(va,{scope:n,type:r,dir:D,scrollHideDelay:a,scrollArea:s,viewport:l,onViewportChange:u,content:d,onContentChange:f,scrollbarX:p,onScrollbarXChange:m,scrollbarXEnabled:S,onScrollbarXEnabledChange:C,scrollbarY:h,onScrollbarYChange:g,scrollbarYEnabled:w,onScrollbarYEnabledChange:T,onCornerWidthChange:v,onCornerHeightChange:x,children:(0,V.jsx)(H.div,{dir:D,...o,ref:E,style:{position:`relative`,"--radix-scroll-area-corner-width":_+`px`,"--radix-scroll-area-corner-height":b+`px`,...e.style}})})},`ScrollArea`)),xa=`ScrollAreaViewport`,Sa=A.forwardRef(J(function(e,t){let{__scopeScrollArea:n,children:r,nonce:i,...a}=e,o=ya(xa,n),s=y(t,A.useRef(null),o.onViewportChange);return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Ca,{nonce:i}),(0,V.jsx)(H.div,{"data-radix-scroll-area-viewport":``,...a,ref:s,style:{overflowX:o.scrollbarXEnabled?`scroll`:`hidden`,overflowY:o.scrollbarYEnabled?`scroll`:`hidden`,...e.style},children:(0,V.jsx)(`div`,{ref:o.onContentChange,style:{minWidth:`100%`,display:`table`},children:r})})]})},`ScrollAreaViewport`)),Ca=A.memo(J(function({nonce:e}){return(0,V.jsx)(`style`,{dangerouslySetInnerHTML:{__html:`[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}`},nonce:e})},`ScrollAreaViewportStyle`),(e,t)=>e.nonce===t.nonce),wa=`ScrollAreaScrollbar`,Ta=A.forwardRef(J(function(e,t){let{forceMount:n,...r}=e,i=ya(wa,e.__scopeScrollArea),{onScrollbarXEnabledChange:a,onScrollbarYEnabledChange:o}=i,s=e.orientation===`horizontal`;return A.useEffect(()=>(s?a(!0):o(!0),()=>{s?a(!1):o(!1)}),[s,a,o]),i.type===`hover`?(0,V.jsx)(Ea,{...r,ref:t,forceMount:n}):i.type===`scroll`?(0,V.jsx)(Da,{...r,ref:t,forceMount:n}):i.type===`auto`?(0,V.jsx)(Oa,{...r,ref:t,forceMount:n}):i.type===`always`?(0,V.jsx)(ka,{...r,ref:t,"data-state":`visible`}):null},`ScrollAreaScrollbar`)),Ea=A.forwardRef(J(function(e,t){let{forceMount:n,...r}=e,i=ya(wa,e.__scopeScrollArea),[a,o]=A.useState(!1);return A.useEffect(()=>{let e=i.scrollArea,t=0;if(e){let n=J(()=>{window.clearTimeout(t),o(!0)},`handlePointerEnter`),r=J(()=>{t=window.setTimeout(()=>o(!1),i.scrollHideDelay)},`handlePointerLeave`);return e.addEventListener(`pointerenter`,n),e.addEventListener(`pointerleave`,r),()=>{window.clearTimeout(t),e.removeEventListener(`pointerenter`,n),e.removeEventListener(`pointerleave`,r)}}},[i.scrollArea,i.scrollHideDelay]),(0,V.jsx)(bi,{present:n||a,children:(0,V.jsx)(Oa,{"data-state":a?`visible`:`hidden`,...r,ref:t})})},`ScrollAreaScrollbarHover`)),Da=A.forwardRef(J(function(e,t){let{forceMount:n,...r}=e,i=ya(wa,e.__scopeScrollArea),a=e.orientation===`horizontal`,o=Ya(()=>c(`SCROLL_END`),100),[s,c]=ma(`hidden`,{hidden:{SCROLL:`scrolling`},scrolling:{SCROLL_END:`idle`,POINTER_ENTER:`interacting`},interacting:{SCROLL:`interacting`,POINTER_LEAVE:`idle`},idle:{HIDE:`hidden`,SCROLL:`scrolling`,POINTER_ENTER:`interacting`}});return A.useEffect(()=>{if(s===`idle`){let e=window.setTimeout(()=>c(`HIDE`),i.scrollHideDelay);return()=>window.clearTimeout(e)}},[s,i.scrollHideDelay,c]),A.useEffect(()=>{let e=i.viewport,t=a?`scrollLeft`:`scrollTop`;if(e){let n=e[t],r=J(()=>{let r=e[t];n!==r&&(c(`SCROLL`),o()),n=r},`handleScroll`);return e.addEventListener(`scroll`,r),()=>e.removeEventListener(`scroll`,r)}},[i.viewport,a,c,o]),(0,V.jsx)(bi,{present:n||s!==`hidden`,children:(0,V.jsx)(ka,{"data-state":s===`hidden`?`hidden`:`visible`,...r,ref:t,onPointerEnter:B(e.onPointerEnter,()=>c(`POINTER_ENTER`)),onPointerLeave:B(e.onPointerLeave,()=>c(`POINTER_LEAVE`))})})},`ScrollAreaScrollbarScroll`)),Oa=A.forwardRef(J(function(e,t){let n=ya(wa,e.__scopeScrollArea),{forceMount:r,...i}=e,[a,o]=A.useState(!1),s=e.orientation===`horizontal`,c=Ya(()=>{if(n.viewport){let e=n.viewport.offsetWidth0&&l<1,onThumbChange:J(e=>a.current=e,`onThumbChange`),onThumbPointerUp:J(()=>o.current=0,`onThumbPointerUp`),onThumbPointerDown:J(e=>o.current=e,`onThumbPointerDown`)};function d(e,t){return Wa(e,o.current,s,t)}return J(d,`getScrollPosition`),n===`horizontal`?(0,V.jsx)(Aa,{...u,ref:t,onThumbPositionChange:()=>{if(i.viewport&&a.current){let e=i.viewport.scrollLeft,t=Ga(e,s,i.dir);a.current.style.transform=`translate3d(${t}px, 0, 0)`}},onWheelScroll:e=>{i.viewport&&(i.viewport.scrollLeft=e)},onDragScroll:e=>{i.viewport&&(i.viewport.scrollLeft=d(e,i.dir))}}):n===`vertical`?(0,V.jsx)(ja,{...u,ref:t,onThumbPositionChange:()=>{if(i.viewport&&a.current){let e=i.viewport.scrollTop,t=Ga(e,s);a.current.style.transform=`translate3d(0, ${t}px, 0)`}},onWheelScroll:e=>{i.viewport&&(i.viewport.scrollTop=e)},onDragScroll:e=>{i.viewport&&(i.viewport.scrollTop=d(e))}}):null},`ScrollAreaScrollbarVisible`)),Aa=A.forwardRef(J(function(e,t){let{sizes:n,onSizesChange:r,...i}=e,a=ya(wa,e.__scopeScrollArea),[o,s]=A.useState(),c=A.useRef(null),l=y(t,c,a.onScrollbarXChange);return A.useEffect(()=>{c.current&&s(getComputedStyle(c.current))},[c]),(0,V.jsx)(Pa,{"data-orientation":`horizontal`,...i,ref:l,sizes:n,style:{bottom:0,left:a.dir===`rtl`?`var(--radix-scroll-area-corner-width)`:0,right:a.dir===`ltr`?`var(--radix-scroll-area-corner-width)`:0,"--radix-scroll-area-thumb-width":Ua(n)+`px`,...e.style},onThumbPointerDown:t=>e.onThumbPointerDown(t.x),onDragScroll:t=>e.onDragScroll(t.x),onWheelScroll:(t,n)=>{if(a.viewport){let r=a.viewport.scrollLeft+t.deltaX;e.onWheelScroll(r),qa(r,n)&&t.preventDefault()}},onResize:()=>{c.current&&a.viewport&&o&&r({content:a.viewport.scrollWidth,viewport:a.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:Va(o.paddingLeft),paddingEnd:Va(o.paddingRight)}})}})},`ScrollAreaScrollbarX`)),ja=A.forwardRef(J(function(e,t){let{sizes:n,onSizesChange:r,...i}=e,a=ya(wa,e.__scopeScrollArea),[o,s]=A.useState(),c=A.useRef(null),l=y(t,c,a.onScrollbarYChange);return A.useEffect(()=>{c.current&&s(getComputedStyle(c.current))},[c]),(0,V.jsx)(Pa,{"data-orientation":`vertical`,...i,ref:l,sizes:n,style:{top:0,right:a.dir===`ltr`?0:void 0,left:a.dir===`rtl`?0:void 0,bottom:`var(--radix-scroll-area-corner-height)`,"--radix-scroll-area-thumb-height":Ua(n)+`px`,...e.style},onThumbPointerDown:t=>e.onThumbPointerDown(t.y),onDragScroll:t=>e.onDragScroll(t.y),onWheelScroll:(t,n)=>{if(a.viewport){let r=a.viewport.scrollTop+t.deltaY;e.onWheelScroll(r),qa(r,n)&&t.preventDefault()}},onResize:()=>{c.current&&a.viewport&&o&&r({content:a.viewport.scrollHeight,viewport:a.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:Va(o.paddingTop),paddingEnd:Va(o.paddingBottom)}})}})},`ScrollAreaScrollbarY`)),[Ma,Na]=ga(wa),Pa=A.forwardRef(J(function(e,t){let{__scopeScrollArea:n,sizes:r,hasThumb:i,onThumbChange:a,onThumbPointerUp:o,onThumbPointerDown:s,onThumbPositionChange:c,onDragScroll:l,onWheelScroll:u,onResize:d,...f}=e,p=ya(wa,n),[m,h]=A.useState(null),g=y(t,h),_=A.useRef(null),v=A.useRef(``),b=p.viewport,x=r.content-r.viewport,S=U(u),C=U(c),w=Ya(d,10);function T(e){if(_.current){let t=e.clientX-_.current.left,n=e.clientY-_.current.top;l({x:t,y:n})}}return J(T,`handleDragScroll`),A.useEffect(()=>{let e=J(e=>{let t=e.target;m?.contains(t)&&S(e,x)},`handleWheel`);return document.addEventListener(`wheel`,e,{passive:!1}),()=>document.removeEventListener(`wheel`,e,{passive:!1})},[b,m,x,S]),A.useEffect(C,[r,C]),Xa(m,w),Xa(p.content,w),(0,V.jsx)(Ma,{scope:n,scrollbar:m,hasThumb:i,onThumbChange:U(a),onThumbPointerUp:U(o),onThumbPositionChange:C,onThumbPointerDown:U(s),children:(0,V.jsx)(H.div,{...f,ref:g,style:{position:`absolute`,...f.style},onPointerDown:B(e.onPointerDown,e=>{e.button===0&&(e.target.setPointerCapture(e.pointerId),_.current=m.getBoundingClientRect(),v.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect=`none`,p.viewport&&(p.viewport.style.scrollBehavior=`auto`),T(e))}),onPointerMove:B(e.onPointerMove,T),onPointerUp:B(e.onPointerUp,e=>{let t=e.target;t.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId),document.body.style.webkitUserSelect=v.current,p.viewport&&(p.viewport.style.scrollBehavior=``),_.current=null})})})},`ScrollAreaScrollbarImpl`)),Fa=`ScrollAreaThumb`,Ia=A.forwardRef(J(function(e,t){let{forceMount:n,...r}=e,i=Na(Fa,e.__scopeScrollArea);return(0,V.jsx)(bi,{present:n||i.hasThumb,children:(0,V.jsx)(La,{ref:t,...r})})},`ScrollAreaThumb`)),La=A.forwardRef(J(function(e,t){let{__scopeScrollArea:n,style:r,...i}=e,a=ya(Fa,n),o=Na(Fa,n),{onThumbPositionChange:s}=o,c=y(t,o.onThumbChange),l=A.useRef(void 0),u=Ya(()=>{l.current&&=(l.current(),void 0)},100);return A.useEffect(()=>{let e=a.viewport;if(e){let t=J(()=>{if(u(),!l.current){let t=Ja(e,s);l.current=t,s()}},`handleScroll`);return s(),e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)}},[a.viewport,u,s]),(0,V.jsx)(H.div,{"data-state":o.hasThumb?`visible`:`hidden`,...i,ref:c,style:{width:`var(--radix-scroll-area-thumb-width)`,height:`var(--radix-scroll-area-thumb-height)`,...r},onPointerDownCapture:B(e.onPointerDownCapture,e=>{let t=e.target.getBoundingClientRect(),n=e.clientX-t.left,r=e.clientY-t.top;o.onThumbPointerDown({x:n,y:r})}),onPointerUp:B(e.onPointerUp,o.onThumbPointerUp)})},`ScrollAreaThumbImpl`)),Ra=`ScrollAreaCorner`,za=A.forwardRef(J(function(e,t){let n=ya(Ra,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!==`scroll`&&r?(0,V.jsx)(Ba,{...e,ref:t}):null},`ScrollAreaCorner`)),Ba=A.forwardRef(J(function(e,t){let{__scopeScrollArea:n,...r}=e,i=ya(Ra,n),[a,o]=A.useState(0),[s,c]=A.useState(0),l=!!(a&&s),{onCornerWidthChange:u,onCornerHeightChange:d}=i;return Xa(i.scrollbarX,()=>{let e=i.scrollbarX?.offsetHeight||0;i.onCornerHeightChange(e),c(e)}),Xa(i.scrollbarY,()=>{let e=i.scrollbarY?.offsetWidth||0;i.onCornerWidthChange(e),o(e)}),A.useEffect(()=>()=>{u(0),d(0)},[u,d]),l?(0,V.jsx)(H.div,{...r,ref:t,style:{width:a,height:s,position:`absolute`,right:i.dir===`ltr`?0:void 0,left:i.dir===`rtl`?0:void 0,bottom:0,...e.style}}):null},`ScrollAreaCornerImpl`));function Va(e){return e?parseInt(e,10):0}J(Va,`toInt`);function Ha(e,t){let n=e/t;return isNaN(n)?0:n}J(Ha,`getThumbRatio`);function Ua(e){let t=Ha(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}J(Ua,`getThumbSize`);function Wa(e,t,n,r=`ltr`){let i=Ua(n),a=i/2,o=t||a,s=i-o,c=n.scrollbar.paddingStart+o,l=n.scrollbar.size-n.scrollbar.paddingEnd-s,u=n.content-n.viewport,d=r===`ltr`?[0,u]:[u*-1,0];return Ka([c,l],d)(e)}J(Wa,`getScrollPositionFromPointer`);function Ga(e,t,n=`ltr`){let r=Ua(t),i=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,a=t.scrollbar.size-i,o=t.content-t.viewport,s=a-r,c=fa(e,n===`ltr`?[0,o]:[o*-1,0]);return Ka([0,o],[0,s])(c)}J(Ga,`getThumbOffsetFromScroll`);function Ka(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];let r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}J(Ka,`linearScale`);function qa(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return J((function i(){let a={left:e.scrollLeft,top:e.scrollTop},o=n.left!==a.left,s=n.top!==a.top;(o||s)&&t(),n=a,r=window.requestAnimationFrame(i)}),`loop`)(),()=>window.cancelAnimationFrame(r)},`addUnlinkedScrollListener`);function Ya(e,t){let n=U(e),r=A.useRef(0);return A.useEffect(()=>()=>window.clearTimeout(r.current),[]),A.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}J(Ya,`useDebounceCallback`);function Xa(e,t){let n=U(t);G(()=>{let t=0;if(e){let r=new ResizeObserver(()=>{cancelAnimationFrame(t),t=window.requestAnimationFrame(n)});return r.observe(e),()=>{window.cancelAnimationFrame(t),r.unobserve(e)}}},[e,n])}J(Xa,`useResizeObserver`);function Za({className:e,children:t,...n}){return(0,V.jsxs)(ba,{className:p(`relative overflow-hidden`,e),...n,children:[(0,V.jsx)(Sa,{className:`h-full w-full rounded-[inherit]`,children:t}),(0,V.jsx)(Qa,{}),(0,V.jsx)(za,{})]})}function Qa({className:e,orientation:t=`vertical`,...n}){return(0,V.jsx)(Ta,{orientation:t,className:p(`flex touch-none select-none transition-colors`,t===`vertical`&&`h-full w-2 border-l border-l-transparent p-px`,t===`horizontal`&&`h-2 flex-col border-t border-t-transparent p-px`,e),...n,children:(0,V.jsx)(Ia,{className:`relative flex-1 rounded-full bg-border`})})}var $a=Object.defineProperty,Y=(e,t)=>$a(e,`name`,{value:t,configurable:!0});function eo(e){let t=e+`CollectionProvider`,[n,r]=pt(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=Y(e=>{let{scope:t,children:n}=e,r=A.useRef(null),a=A.useRef(new Map).current;return(0,V.jsx)(i,{scope:t,itemMap:a,collectionRef:r,children:n})},`CollectionProvider`);o.displayName=t;let s=e+`CollectionSlot`,c=m(s),l=A.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=y(t,a(s,n).collectionRef);return(0,V.jsx)(c,{ref:i,children:r})});l.displayName=s;let u=e+`CollectionItemSlot`,d=`data-radix-collection-item`,f=m(u),p=A.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=A.useRef(null),s=y(t,o),c=a(u,n);return A.useEffect(()=>(c.itemMap.set(o,{ref:o,...i}),()=>void c.itemMap.delete(o))),(0,V.jsx)(f,{[d]:``,ref:s,children:r})});p.displayName=u;function h(t){let n=a(e+`CollectionConsumer`,t);return A.useCallback(()=>{let e=n.collectionRef.current;if(!e)return[];let t=Array.from(e.querySelectorAll(`[${d}]`));return Array.from(n.itemMap.values()).sort((e,n)=>t.indexOf(e.ref.current)-t.indexOf(n.ref.current))},[n.collectionRef,n.itemMap])}return Y(h,`useCollection`),[{Provider:o,Slot:l,ItemSlot:p},h,r]}Y(eo,`createCollection`);var to=new WeakMap,no=class e extends Map{static{Y(this,`OrderedDict`)}#e;constructor(e){super(e),this.#e=[...super.keys()],to.set(this,!0)}set(e,t){return to.get(this)&&(this.has(e)?this.#e[this.#e.indexOf(e)]=e:this.#e.push(e)),super.set(e,t),this}insert(e,t,n){let r=this.has(t),i=this.#e.length,a=ao(e),o=a>=0?a:i+a,s=o<0||o>=i?-1:o;if(s===this.size||r&&s===this.size-1||s===-1)return this.set(t,n),this;let c=this.size+ +!r;a<0&&o++;let l=[...this.#e],u,d=!1;for(let e=o;e=this.size&&(r=this.size-1),this.at(r)}keyFrom(e,t){let n=this.indexOf(e);if(n===-1)return;let r=n+t;return r<0&&(r=0),r>=this.size&&(r=this.size-1),this.keyAt(r)}find(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return r;n++}}findIndex(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return n;n++}return-1}filter(t,n){let r=[],i=0;for(let e of this)Reflect.apply(t,n,[e,i,this])&&r.push(e),i++;return new e(r)}map(t,n){let r=[],i=0;for(let e of this)r.push([e[0],Reflect.apply(t,n,[e,i,this])]),i++;return new e(r)}reduce(...e){let[t,n]=e,r=0,i=n??this.at(0);for(let n of this)i=r===0&&e.length===1?n:Reflect.apply(t,this,[i,n,r,this]),r++;return i}reduceRight(...e){let[t,n]=e,r=n??this.at(-1);for(let n=this.size-1;n>=0;n--){let i=this.at(n);r=n===this.size-1&&e.length===1?i:Reflect.apply(t,this,[r,i,n,this])}return r}toSorted(t){let n=[...this.entries()].sort(t);return new e(n)}toReversed(){let t=new e;for(let e=this.size-1;e>=0;e--){let n=this.keyAt(e),r=this.get(n);t.set(n,r)}return t}toSpliced(...t){let n=[...this.entries()];return n.splice(...t),new e(n)}slice(t,n){let r=new e,i=this.size-1;if(t===void 0)return r;t<0&&(t+=this.size),n!==void 0&&n>0&&(i=n-1);for(let e=t;e<=i;e++){let t=this.keyAt(e),n=this.get(t);r.set(t,n)}return r}every(e,t){let n=0;for(let r of this){if(!Reflect.apply(e,t,[r,n,this]))return!1;n++}return!0}some(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return!0;n++}return!1}};function ro(e,t){if(`at`in Array.prototype)return Array.prototype.at.call(e,t);let n=io(e,t);return n===-1?void 0:e[n]}Y(ro,`at`);function io(e,t){let n=e.length,r=ao(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}Y(io,`toSafeIndex`);function ao(e){return e!==e||e===0?0:Math.trunc(e)}Y(ao,`toSafeInteger`);function oo(e){let t=e+`CollectionProvider`,[n,r]=pt(t),[i,a]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new no,setItemMap:Y(()=>void 0,`setItemMap`)}),o=Y(({state:e,...t})=>e?(0,V.jsx)(c,{...t,state:e}):(0,V.jsx)(s,{...t}),`CollectionProvider`);o.displayName=t;let s=Y(e=>{let t=g();return(0,V.jsx)(c,{...e,state:t})},`CollectionInit`);s.displayName=t+`Init`;let c=Y(e=>{let{scope:t,children:n,state:r}=e,a=A.useRef(null),[o,s]=A.useState(null),c=y(a,s),[l,u]=r;return A.useEffect(()=>{if(!o)return;let e=uo(()=>{});return e.observe(o,{childList:!0,subtree:!0}),()=>{e.disconnect()}},[o]),(0,V.jsx)(i,{scope:t,itemMap:l,setItemMap:u,collectionRef:c,collectionRefObject:a,collectionElement:o,children:n})},`CollectionProviderImpl`);c.displayName=t+`Impl`;let l=e+`CollectionSlot`,u=m(l),d=A.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=y(t,a(l,n).collectionRef);return(0,V.jsx)(u,{ref:i,children:r})});d.displayName=l;let f=e+`CollectionItemSlot`,p=m(f),h=A.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=A.useRef(null),[s,c]=A.useState(null),l=y(t,o,c),{setItemMap:u}=a(f,n),d=A.useRef(i);so(d.current,i)||(d.current=i);let m=d.current;return A.useEffect(()=>{let e=m;return u(t=>s?t.has(s)?t.set(s,{...e,element:s}).toSorted(lo):(t.set(s,{...e,element:s}),t.toSorted(lo)):t),()=>{u(e=>!s||!e.has(s)?e:(e.delete(s),new no(e)))}},[s,m,u]),(0,V.jsx)(p,{"data-radix-collection-item":``,ref:l,children:r})});h.displayName=f;function g(){return A.useState(new no)}Y(g,`useInitCollection`);function _(t){let{itemMap:n}=a(e+`CollectionConsumer`,t);return n}return Y(_,`useCollection`),[{Provider:o,Slot:d,ItemSlot:h},{createCollectionScope:r,useCollection:_,useInitCollection:g}]}Y(oo,`createCollection`);function so(e,t){if(e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e==null||t==null)return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||e[r]!==t[r])return!1;return!0}Y(so,`shallowEqual`);function co(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}Y(co,`isElementPreceding`);function lo(e,t){return!e[1].element||!t[1].element?0:co(e[1].element,t[1].element)?-1:1}Y(lo,`sortByDocumentPosition`);function uo(e){return new MutationObserver(t=>{for(let n of t)if(n.type===`childList`){e();return}})}Y(uo,`getChildListObserver`);var fo=Object.defineProperty,po=(e,t)=>fo(e,`name`,{value:t,configurable:!0}),mo=0,ho=null;function go(e){return _o(),e.children}po(go,`FocusGuards`);function _o(){A.useEffect(()=>{ho||={start:vo(),end:vo()};let{start:e,end:t}=ho;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement(`afterbegin`,e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement(`beforeend`,t),mo++,()=>{mo===1&&(ho?.start.remove(),ho?.end.remove(),ho=null),mo=Math.max(0,mo-1)}},[])}po(_o,`useFocusGuards`);function vo(){let e=document.createElement(`span`);return e.setAttribute(`data-radix-focus-guard`,``),e.tabIndex=0,e.style.outline=`none`,e.style.opacity=`0`,e.style.position=`fixed`,e.style.pointerEvents=`none`,e}po(vo,`createFocusGuard`);var yo=Object.defineProperty,X=(e,t)=>yo(e,`name`,{value:t,configurable:!0}),bo=`focusScope.autoFocusOnMount`,xo=`focusScope.autoFocusOnUnmount`,So={bubbles:!1,cancelable:!0},Co=A.forwardRef(X(function(e,t){let{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...o}=e,[s,c]=A.useState(null),l=U(i),u=U(a),d=A.useRef(null),f=y(t,c),p=A.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;A.useEffect(()=>{if(r){let e=function(e){if(p.paused||!s)return;let t=e.target;s.contains(t)?d.current=t:Ao(d.current,{select:!0})},t=function(e){if(p.paused||!s)return;let t=e.relatedTarget;t!==null&&(s.contains(t)||Ao(d.current,{select:!0}))},n=function(e){if(document.activeElement===document.body)for(let t of e)t.removedNodes.length>0&&Ao(s)};X(e,`handleFocusIn`),X(t,`handleFocusOut`),X(n,`handleMutations`),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t);let r=new MutationObserver(n);return s&&r.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t),r.disconnect()}}},[r,s,p.paused]),A.useEffect(()=>{if(s){jo.add(p);let e=document.activeElement;if(!s.contains(e)){let t=new CustomEvent(bo,So);s.addEventListener(bo,l),s.dispatchEvent(t),t.defaultPrevented||(wo(Po(Eo(s)),{select:!0}),document.activeElement===e&&Ao(s))}return()=>{s.removeEventListener(bo,l),setTimeout(()=>{let t=new CustomEvent(xo,So);s.addEventListener(xo,u),s.dispatchEvent(t),t.defaultPrevented||Ao(e??document.body,{select:!0}),s.removeEventListener(xo,u),jo.remove(p)},0)}}},[s,l,u,p]);let m=A.useCallback(e=>{if(!n&&!r||p.paused)return;let t=e.key===`Tab`&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){let t=e.currentTarget,[r,a]=To(t);r&&a?!e.shiftKey&&i===a?(e.preventDefault(),n&&Ao(r,{select:!0})):e.shiftKey&&i===r&&(e.preventDefault(),n&&Ao(a,{select:!0})):i===t&&e.preventDefault()}},[n,r,p.paused]);return(0,V.jsx)(H.div,{tabIndex:-1,...o,ref:f,onKeyDown:m})},`FocusScope`));function wo(e,{select:t=!1}={}){let n=document.activeElement;for(let r of e)if(Ao(r,{select:t}),document.activeElement!==n)return}X(wo,`focusFirst`);function To(e){let t=Eo(e);return[Do(t,e),Do(t.reverse(),e)]}X(To,`getTabbableEdges`);function Eo(e){let t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:X(e=>{let t=e.tagName===`INPUT`&&e.type===`hidden`;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},`acceptNode`)});for(;n.nextNode();)t.push(n.currentNode);return t}X(Eo,`getTabbableCandidates`);function Do(e,t){let n=typeof t.checkVisibility==`function`&&t.checkVisibility({checkVisibilityCSS:!0});for(let r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):Oo(r,{upTo:t})))return r}X(Do,`findVisible`);function Oo(e,{upTo:t}){if(getComputedStyle(e).visibility===`hidden`)return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display===`none`)return!0;e=e.parentElement}return!1}X(Oo,`isHidden`);function ko(e){return e instanceof HTMLInputElement&&`select`in e}X(ko,`isSelectableInput`);function Ao(e,{select:t=!1}={}){if(e&&e.focus){let n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&ko(e)&&t&&e.select()}}X(Ao,`focus`);var jo=Mo();function Mo(){let e=[];return{add(t){let n=e[0];t!==n&&n?.pause(),e=No(e,t),e.unshift(t)},remove(t){e=No(e,t),e[0]?.resume()}}}X(Mo,`createFocusScopesStack`);function No(e,t){let n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}X(No,`arrayRemove`);function Po(e){return e.filter(e=>e.tagName!==`A`)}X(Po,`removeLinks`);var Fo=Object.defineProperty,Io=(e,t)=>Fo(e,`name`,{value:t,configurable:!0}),Lo=!1;function Ro(){let[e,t]=A.useState(Lo);return A.useEffect(()=>{Lo||(Lo=!0,t(!0))},[]),e}Io(Ro,`useIsHydrated`);var zo=A.useSyncExternalStore;function Bo(){return()=>{}}Io(Bo,`subscribe`);function Vo(){return zo(Bo,()=>!0,()=>!1)}Io(Vo,`useIsHydratedModern`);var Ho=typeof zo==`function`?Vo:Ro,Uo=Object.defineProperty,Wo=(e,t)=>Uo(e,`name`,{value:t,configurable:!0}),Go=`rovingFocusGroup.onEntryFocus`,Ko={bubbles:!1,cancelable:!0},qo=`RovingFocusGroup`,[Jo,Yo,Xo]=eo(qo),[Zo,Qo]=pt(qo,[Xo]),[$o,es]=Zo(qo),ts=A.forwardRef(Wo(function(e,t){return(0,V.jsx)(Jo.Provider,{scope:e.__scopeRovingFocusGroup,children:(0,V.jsx)(Jo.Slot,{scope:e.__scopeRovingFocusGroup,children:(0,V.jsx)(ns,{...e,ref:t})})})},`RovingFocusGroup`)),ns=A.forwardRef(Wo(function(e,t){let{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:a,currentTabStopId:o,defaultCurrentTabStopId:s,onCurrentTabStopIdChange:c,onEntryFocus:l,preventScrollOnEntryFocus:u=!1,...d}=e,f=A.useRef(null),p=y(t,f),m=la(a),[h,g]=Pi({prop:o,defaultProp:s??null,onChange:c,caller:qo}),[_,v]=A.useState(!1),b=U(l),x=Yo(n),S=A.useRef(!1),[C,w]=A.useState(0);return A.useEffect(()=>{let e=f.current;if(e)return e.addEventListener(Go,b),()=>e.removeEventListener(Go,b)},[b]),(0,V.jsx)($o,{scope:n,orientation:r,dir:m,loop:i,currentTabStopId:h,onItemFocus:A.useCallback(e=>g(e),[g]),onItemShiftTab:A.useCallback(()=>v(!0),[]),onFocusableItemAdd:A.useCallback(()=>w(e=>e+1),[]),onFocusableItemRemove:A.useCallback(()=>w(e=>e-1),[]),children:(0,V.jsx)(H.div,{tabIndex:_||C===0?-1:0,"data-orientation":r,...d,ref:p,style:{outline:`none`,...e.style},onMouseDown:B(e.onMouseDown,()=>{S.current=!0}),onFocus:B(e.onFocus,e=>{let t=!S.current;if(e.target===e.currentTarget&&t&&!_){let t=new CustomEvent(Go,Ko);if(e.currentTarget.dispatchEvent(t),!t.defaultPrevented){let e=x().filter(e=>e.focusable);cs([e.find(e=>e.active),e.find(e=>e.id===h),...e].filter(Boolean).map(e=>e.ref.current),u)}}S.current=!1}),onBlur:B(e.onBlur,()=>v(!1))})})},`RovingFocusGroupImpl`)),rs=`RovingFocusGroupItem`,is=A.forwardRef(Wo(function(e,t){let{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:a,children:o,...s}=e,c=K(),l=a||c,u=es(rs,n),d=u.currentTabStopId===l,f=Yo(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:h}=u,g=Ho();return G(()=>{if(!(!g||!r))return p(),()=>m()},[g,r,p,m]),A.useEffect(()=>{if(!(g||!r))return p(),()=>m()},[g,r,p,m]),(0,V.jsx)(Jo.ItemSlot,{scope:n,id:l,focusable:r,active:i,children:(0,V.jsx)(H.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...s,ref:t,onMouseDown:B(e.onMouseDown,e=>{r?u.onItemFocus(l):e.preventDefault()}),onFocus:B(e.onFocus,()=>u.onItemFocus(l)),onKeyDown:B(e.onKeyDown,e=>{if(e.key===`Tab`&&e.shiftKey){u.onItemShiftTab();return}if(e.target!==e.currentTarget)return;let t=ss(e,u.orientation,u.dir);if(t!==void 0){if(e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)return;e.preventDefault();let n=f().filter(e=>e.focusable).map(e=>e.ref.current);if(t===`last`)n.reverse();else if(t===`prev`||t===`next`){t===`prev`&&n.reverse();let r=n.indexOf(e.currentTarget);n=u.loop?ls(n,r+1):n.slice(r+1)}setTimeout(()=>cs(n))}}),children:typeof o==`function`?o({isCurrentTabStop:d,hasTabStop:h!=null}):o})})},`RovingFocusGroupItem`)),as={ArrowLeft:`prev`,ArrowUp:`prev`,ArrowRight:`next`,ArrowDown:`next`,PageUp:`first`,Home:`first`,PageDown:`last`,End:`last`};function os(e,t){return t===`rtl`?e===`ArrowLeft`?`ArrowRight`:e===`ArrowRight`?`ArrowLeft`:e:e}Wo(os,`getDirectionAwareKey`);function ss(e,t,n){let r=os(e.key,n);if(!(t===`vertical`&&[`ArrowLeft`,`ArrowRight`].includes(r))&&!(t===`horizontal`&&[`ArrowUp`,`ArrowDown`].includes(r)))return as[r]}Wo(ss,`getFocusIntent`);function cs(e,t=!1){let n=document.activeElement;for(let r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}Wo(cs,`focusFirst`);function ls(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Wo(ls,`wrapArray`);var us=function(e){return typeof document>`u`?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},ds=new WeakMap,fs=new WeakMap,ps={},ms=0,hs=function(e){return e&&(e.host||hs(e.parentNode))},gs=function(e,t){return t.map(function(t){if(e.contains(t))return t;var n=hs(t);return n&&e.contains(n)?n:(console.error(`aria-hidden`,t,`in not contained inside`,e,`. Doing nothing`),null)}).filter(function(e){return!!e})},_s=function(e,t,n,r){var i=gs(t,Array.isArray(e)?e:[e]);ps[n]||(ps[n]=new WeakMap);var a=ps[n],o=[],s=new Set,c=new Set(i),l=function(e){!e||s.has(e)||(s.add(e),l(e.parentNode))};i.forEach(l);var u=function(e){!e||c.has(e)||Array.prototype.forEach.call(e.children,function(e){if(s.has(e))u(e);else try{var t=e.getAttribute(r),i=t!==null&&t!==`false`,c=(ds.get(e)||0)+1,l=(a.get(e)||0)+1;ds.set(e,c),a.set(e,l),o.push(e),c===1&&i&&fs.set(e,!0),l===1&&e.setAttribute(n,`true`),i||e.setAttribute(r,`true`)}catch(t){console.error(`aria-hidden: cannot operate on `,e,t)}})};return u(t),s.clear(),ms++,function(){o.forEach(function(e){var t=ds.get(e)-1,i=a.get(e)-1;ds.set(e,t),a.set(e,i),t||(fs.has(e)||e.removeAttribute(r),fs.delete(e)),i||e.removeAttribute(n)}),ms--,ms||(ds=new WeakMap,ds=new WeakMap,fs=new WeakMap,ps={})}},vs=function(e,t,n){n===void 0&&(n=`data-aria-hidden`);var r=Array.from(Array.isArray(e)?e:[e]),i=t||us(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll(`[aria-live], script`))),_s(r,i,n,`aria-hidden`)):function(){return null}},ys=function(){return ys=Object.assign||function(e){for(var t,n=1,r=arguments.length;n`u`)return qs;var t=Ys(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Zs=Ks(),Qs=`data-scroll-locked`,$s=function(e,t,n,r){var i=e.left,a=e.top,o=e.right,s=e.gap;return n===void 0&&(n=`margin`),` - .${ws} { - overflow: hidden ${r}; - padding-right: ${s}px ${r}; - } - body[${Qs}] { - overflow: hidden ${r}; - overscroll-behavior: contain; - ${[t&&`position: relative ${r};`,n===`margin`&&` - padding-left: ${i}px; - padding-top: ${a}px; - padding-right: ${o}px; - margin-left:0; - margin-top:0; - margin-right: ${s}px ${r}; - `,n===`padding`&&`padding-right: ${s}px ${r};`].filter(Boolean).join(``)} - } - - .${Ss} { - right: ${s}px ${r}; - } - - .${Cs} { - margin-right: ${s}px ${r}; - } - - .${Ss} .${Ss} { - right: 0 ${r}; - } - - .${Cs} .${Cs} { - margin-right: 0 ${r}; - } - - body[${Qs}] { - ${Ts}: ${s}px; - } -`},ec=function(){var e=parseInt(document.body.getAttribute(`data-scroll-locked`)||`0`,10);return isFinite(e)?e:0},tc=function(){A.useEffect(function(){return document.body.setAttribute(Qs,(ec()+1).toString()),function(){var e=ec()-1;e<=0?document.body.removeAttribute(Qs):document.body.setAttribute(Qs,e.toString())}},[])},nc=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?`margin`:r;tc();var a=A.useMemo(function(){return Xs(i)},[i]);return A.createElement(Zs,{styles:$s(a,!t,i,n?``:`!important`)})},rc=!1;if(typeof window<`u`)try{var ic=Object.defineProperty({},"passive",{get:function(){return rc=!0,!0}});window.addEventListener(`test`,ic,ic),window.removeEventListener(`test`,ic,ic)}catch{rc=!1}var ac=rc?{passive:!1}:!1,oc=function(e){return e.tagName===`TEXTAREA`},sc=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!==`hidden`&&!(n.overflowY===n.overflowX&&!oc(e)&&n[t]===`visible`)},cc=function(e){return sc(e,`overflowY`)},lc=function(e){return sc(e,`overflowX`)},uc=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<`u`&&r instanceof ShadowRoot&&(r=r.host),pc(e,r)){var i=mc(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},dc=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},fc=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},pc=function(e,t){return e===`v`?cc(t):lc(t)},mc=function(e,t){return e===`v`?dc(t):fc(t)},hc=function(e,t){return e===`h`&&t===`rtl`?-1:1},gc=function(e,t,n,r,i){var a=hc(e,window.getComputedStyle(t).direction),o=a*r,s=n.target,c=t.contains(s),l=!1,u=o>0,d=0,f=0;do{if(!s)break;var p=mc(e,s),m=p[0],h=p[1]-p[2]-a*m;(m||h)&&pc(e,s)&&(d+=h,f+=m);var g=s.parentNode;s=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}while(!c&&s!==document.body||c&&(t.contains(s)||t===s));return(u&&(i&&Math.abs(d)<1||!i&&o>d)||!u&&(i&&Math.abs(f)<1||!i&&-o>f))&&(l=!0),l},_c=function(e){return`changedTouches`in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},vc=function(e){return[e.deltaX,e.deltaY]},yc=function(e){return e&&`current`in e?e.current:e},bc=function(e,t){return e[0]===t[0]&&e[1]===t[1]},xc=function(e){return` - .block-interactivity-${e} {pointer-events: none;} - .allow-interactivity-${e} {pointer-events: all;} -`},Sc=0,Cc=[];function wc(e){var t=A.useRef([]),n=A.useRef([0,0]),r=A.useRef(),i=A.useState(Sc++)[0],a=A.useState(Ks)[0],o=A.useRef(e);A.useEffect(function(){o.current=e},[e]),A.useEffect(function(){if(e.inert){document.body.classList.add(`block-interactivity-${i}`);var t=xs([e.lockRef.current],(e.shards||[]).map(yc),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add(`allow-interactivity-${i}`)}),function(){document.body.classList.remove(`block-interactivity-${i}`),t.forEach(function(e){return e.classList.remove(`allow-interactivity-${i}`)})}}},[e.inert,e.lockRef.current,e.shards]);var s=A.useCallback(function(e,t){if(`touches`in e&&e.touches.length===2||e.type===`wheel`&&e.ctrlKey)return!o.current.allowPinchZoom;var i=_c(e),a=n.current,s=`deltaX`in e?e.deltaX:a[0]-i[0],c=`deltaY`in e?e.deltaY:a[1]-i[1],l,u=e.target,d=Math.abs(s)>Math.abs(c)?`h`:`v`;if(`touches`in e&&d===`h`&&u.type===`range`)return!1;var f=window.getSelection(),p=f&&f.anchorNode;if(p&&(p===u||p.contains(u)))return!1;var m=uc(d,u);if(!m)return!0;if(m?l=d:(l=d===`v`?`h`:`v`,m=uc(d,u)),!m)return!1;if(!r.current&&`changedTouches`in e&&(s||c)&&(r.current=l),!l)return!0;var h=r.current||l;return gc(h,t,e,h===`h`?s:c,!0)},[]),c=A.useCallback(function(e){var n=e;if(!(!Cc.length||Cc[Cc.length-1]!==a)){var r=`deltaY`in n?vc(n):_c(n),i=t.current.filter(function(e){return e.name===n.type&&(e.target===n.target||n.target===e.shadowParent)&&bc(e.delta,r)})[0];if(i&&i.should){n.cancelable&&n.preventDefault();return}if(!i){var c=(o.current.shards||[]).map(yc).filter(Boolean).filter(function(e){return e.contains(n.target)});(c.length>0?s(n,c[0]):!o.current.noIsolation)&&n.cancelable&&n.preventDefault()}}},[]),l=A.useCallback(function(e,n,r,i){var a={name:e,delta:n,target:r,should:i,shadowParent:Tc(r)};t.current.push(a),setTimeout(function(){t.current=t.current.filter(function(e){return e!==a})},1)},[]),u=A.useCallback(function(e){n.current=_c(e),r.current=void 0},[]),d=A.useCallback(function(t){l(t.type,vc(t),t.target,s(t,e.lockRef.current))},[]),f=A.useCallback(function(t){l(t.type,_c(t),t.target,s(t,e.lockRef.current))},[]);A.useEffect(function(){return Cc.push(a),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener(`wheel`,c,ac),document.addEventListener(`touchmove`,c,ac),document.addEventListener(`touchstart`,u,ac),function(){Cc=Cc.filter(function(e){return e!==a}),document.removeEventListener(`wheel`,c,ac),document.removeEventListener(`touchmove`,c,ac),document.removeEventListener(`touchstart`,u,ac)}},[]);var p=e.removeScrollBar,m=e.inert;return A.createElement(A.Fragment,null,m?A.createElement(a,{styles:xc(i)}):null,p?A.createElement(nc,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Tc(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Ec=Fs(Is,wc),Dc=A.forwardRef(function(e,t){return A.createElement(Rs,ys({},e,{ref:t,sideCar:Ec}))});Dc.classNames=Rs.classNames;var Oc=Object.defineProperty,Z=(e,t)=>Oc(e,`name`,{value:t,configurable:!0}),kc=[`Enter`,` `],Ac=[`ArrowDown`,`PageUp`,`Home`],jc=[`ArrowUp`,`PageDown`,`End`],Mc=[...Ac,...jc],Nc={ltr:[...kc,`ArrowRight`],rtl:[...kc,`ArrowLeft`]},Pc={ltr:[`ArrowLeft`],rtl:[`ArrowRight`]},Fc=`Menu`,[Ic,Lc,Rc]=eo(Fc),[zc,Bc]=pt(Fc,[Rc,ni,Qo]),Vc=ni(),Hc=Qo(),[Uc,Wc]=zc(Fc),[Gc,Kc]=zc(Fc),qc=Z(e=>{let{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:a,modal:o=!0}=e,s=Vc(t),[c,l]=A.useState(null),u=A.useRef(!1),d=U(a),f=la(i);return A.useEffect(()=>{let e=Z(()=>{u.current=!0,document.addEventListener(`pointerdown`,t,{capture:!0,once:!0}),document.addEventListener(`pointermove`,t,{capture:!0,once:!0})},`handleKeyDown`),t=Z(()=>u.current=!1,`handlePointer`);return document.addEventListener(`keydown`,e,{capture:!0}),()=>{document.removeEventListener(`keydown`,e,{capture:!0}),document.removeEventListener(`pointerdown`,t,{capture:!0}),document.removeEventListener(`pointermove`,t,{capture:!0})}},[]),A.useEffect(()=>{if(!n)return;let e=Z(()=>d(!1),`handleBlur`);return window.addEventListener(`blur`,e),()=>window.removeEventListener(`blur`,e)},[n,d]),(0,V.jsx)(ai,{...s,children:(0,V.jsx)(Uc,{scope:t,open:n,onOpenChange:d,content:c,onContentChange:l,children:(0,V.jsx)(Gc,{scope:t,onClose:A.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:f,modal:o,children:r})})})},`Menu`),Jc=A.forwardRef(Z(function(e,t){let{__scopeMenu:n,...r}=e,i=Vc(n);return(0,V.jsx)(si,{...i,...r,ref:t})},`MenuAnchor`)),Yc=`MenuPortal`,[Xc,Zc]=zc(Yc,{forceMount:void 0}),Qc=Z(e=>{let{__scopeMenu:t,forceMount:n,children:r,container:i}=e,a=Wc(Yc,t);return(0,V.jsx)(Xc,{scope:t,forceMount:n,children:(0,V.jsx)(bi,{present:n||a.open,children:(0,V.jsx)(gi,{asChild:!0,container:i,children:r})})})},`MenuPortal`),$c=`MenuContent`,[el,tl]=zc($c),nl=A.forwardRef(Z(function(e,t){let n=Zc($c,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,a=Wc($c,e.__scopeMenu),o=Kc($c,e.__scopeMenu);return(0,V.jsx)(Ic.Provider,{scope:e.__scopeMenu,children:(0,V.jsx)(bi,{present:r||a.open,children:(0,V.jsx)(Ic.Slot,{scope:e.__scopeMenu,children:o.modal?(0,V.jsx)(rl,{...i,ref:t}):(0,V.jsx)(il,{...i,ref:t})})})})},`MenuContent`)),rl=A.forwardRef(Z(function(e,t){let n=Wc($c,e.__scopeMenu),r=A.useRef(null),i=y(t,r);return A.useEffect(()=>{let e=r.current;if(e)return vs(e)},[]),(0,V.jsx)(ol,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:B(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})},`MenuRootContentModal`)),il=A.forwardRef(Z(function(e,t){let n=Wc($c,e.__scopeMenu);return(0,V.jsx)(ol,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})},`MenuRootContentNonModal`)),al=m(`MenuContent.ScrollLock`),ol=A.forwardRef(Z(function(e,t){let{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEntryFocus:c,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,disableOutsideScroll:m,...h}=e,g=Wc($c,n),_=Kc($c,n),v=Vc(n),b=Hc(n),x=Lc(n),[S,C]=A.useState(null),w=A.useRef(null),T=y(t,w,g.onContentChange),E=A.useRef(0),D=A.useRef(``),O=A.useRef(0),k=A.useRef(null),j=A.useRef(`right`),M=A.useRef(0),N=m?Dc:A.Fragment,P=m?{as:al,allowPinchZoom:!0}:void 0,ee=Z(e=>{let t=D.current+e,n=x().filter(e=>!e.disabled),r=document.activeElement,i=n.find(e=>e.ref.current===r)?.textValue,a=Al(n.map(e=>e.textValue),t,i),o=n.find(e=>e.textValue===a)?.ref.current;Z((function e(t){D.current=t,window.clearTimeout(E.current),t!==``&&(E.current=window.setTimeout(()=>e(``),1e3))}),`updateSearch`)(t),o&&setTimeout(()=>o.focus())},`handleTypeaheadSearch`);A.useEffect(()=>()=>window.clearTimeout(E.current),[]),_o();let F=A.useCallback(e=>j.current===k.current?.side&&Ml(e,k.current?.area),[]);return(0,V.jsx)(el,{scope:n,searchRef:D,onItemEnter:A.useCallback(e=>{F(e)&&e.preventDefault()},[F]),onItemLeave:A.useCallback(e=>{F(e)||(w.current?.focus(),C(null))},[F]),onTriggerLeave:A.useCallback(e=>{F(e)&&e.preventDefault()},[F]),pointerGraceTimerRef:O,onPointerGraceIntentChange:A.useCallback(e=>{k.current=e},[]),children:(0,V.jsx)(N,{...P,children:(0,V.jsx)(Co,{asChild:!0,trapped:i,onMountAutoFocus:B(a,e=>{e.preventDefault(),w.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:(0,V.jsx)(Dt,{asChild:!0,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,children:(0,V.jsx)(ts,{asChild:!0,...b,dir:_.dir,orientation:`vertical`,loop:r,currentTabStopId:S,onCurrentTabStopIdChange:C,onEntryFocus:B(c,e=>{_.isUsingKeyboardRef.current||e.preventDefault()}),preventScrollOnEntryFocus:!0,children:(0,V.jsx)(di,{role:`menu`,"aria-orientation":`vertical`,"data-state":Tl(g.open),"data-radix-menu-content":``,dir:_.dir,...v,...h,ref:T,style:{outline:`none`,...h.style},onKeyDown:B(h.onKeyDown,e=>{let t=e.target.closest(`[data-radix-menu-content]`)===e.currentTarget,n=e.ctrlKey||e.altKey||e.metaKey,r=e.key.length===1;t&&(e.key===`Tab`&&e.preventDefault(),!n&&r&&ee(e.key));let i=w.current;if(e.target!==i||!Mc.includes(e.key))return;e.preventDefault();let a=x().filter(e=>!e.disabled).map(e=>e.ref.current);jc.includes(e.key)&&a.reverse(),Ol(a)}),onBlur:B(e.onBlur,e=>{e.currentTarget.contains(e.target)||(window.clearTimeout(E.current),D.current=``)}),onPointerMove:B(e.onPointerMove,Nl(e=>{let t=e.target,n=M.current!==e.clientX;if(e.currentTarget.contains(t)&&n){let t=e.clientX>M.current?`right`:`left`;j.current=t,M.current=e.clientX}}))})})})})})})},`MenuContentImpl`)),sl=A.forwardRef(Z(function(e,t){let{__scopeMenu:n,...r}=e;return(0,V.jsx)(H.div,{...r,ref:t})},`MenuLabel`)),cl=`MenuItem`,ll=`menu.itemSelect`,ul=A.forwardRef(Z(function(e,t){let{disabled:n=!1,onSelect:r,...i}=e,a=A.useRef(null),o=Kc(cl,e.__scopeMenu),s=tl(cl,e.__scopeMenu),c=y(t,a),l=A.useRef(!1),u=Z(()=>{let e=a.current;if(!n&&e){let t=new CustomEvent(ll,{bubbles:!0,cancelable:!0});e.addEventListener(ll,e=>r?.(e),{once:!0}),vt(e,t),t.defaultPrevented?l.current=!1:o.onClose()}},`handleSelect`);return(0,V.jsx)(dl,{...i,ref:c,disabled:n,onClick:B(e.onClick,u),onPointerDown:t=>{e.onPointerDown?.(t),l.current=!0},onPointerUp:B(e.onPointerUp,e=>{l.current||e.currentTarget?.click()}),onKeyDown:B(e.onKeyDown,e=>{n||e.target!==e.currentTarget||s.searchRef.current!==``&&e.key===` `||kc.includes(e.key)&&(e.currentTarget.click(),e.preventDefault())})})},`MenuItem`)),dl=A.forwardRef(Z(function(e,t){let{__scopeMenu:n,disabled:r=!1,textValue:i,...a}=e,o=tl(cl,n),s=Hc(n),c=A.useRef(null),l=y(t,c),[u,d]=A.useState(!1),[f,p]=A.useState(``);return A.useEffect(()=>{let e=c.current;e&&p((e.textContent??``).trim())},[a.children]),(0,V.jsx)(Ic.ItemSlot,{scope:n,disabled:r,textValue:i??f,children:(0,V.jsx)(is,{asChild:!0,...s,focusable:!r,children:(0,V.jsx)(H.div,{role:`menuitem`,"data-highlighted":u?``:void 0,"aria-disabled":r||void 0,"data-disabled":r?``:void 0,...a,ref:l,onPointerMove:B(e.onPointerMove,Nl(e=>{r?o.onItemLeave(e):(o.onItemEnter(e),e.defaultPrevented||e.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:B(e.onPointerLeave,Nl(e=>o.onItemLeave(e))),onFocus:B(e.onFocus,()=>d(!0)),onBlur:B(e.onBlur,()=>d(!1))})})})},`MenuItemImpl`)),[fl,pl]=zc(`MenuRadioGroup`,{value:void 0,onValueChange:Z(()=>{},`onValueChange`)}),[ml,hl]=zc(`MenuItemIndicator`,{checked:!1}),gl=A.forwardRef(Z(function(e,t){let{__scopeMenu:n,...r}=e;return(0,V.jsx)(H.div,{role:`separator`,"aria-orientation":`horizontal`,...r,ref:t})},`MenuSeparator`)),_l=`MenuSub`,[vl,yl]=zc(_l),bl=Z(e=>{let{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,a=Wc(_l,t),o=Vc(t),[s,c]=A.useState(null),[l,u]=A.useState(null),d=U(i);return A.useEffect(()=>(a.open===!1&&d(!1),()=>d(!1)),[a.open,d]),(0,V.jsx)(ai,{...o,children:(0,V.jsx)(Uc,{scope:t,open:r,onOpenChange:d,content:l,onContentChange:u,children:(0,V.jsx)(vl,{scope:t,contentId:K(),triggerId:K(),trigger:s,onTriggerChange:c,children:n})})})},`MenuSub`),xl=`MenuSubTrigger`,Sl=A.forwardRef(Z(function(e,t){let n=Wc(xl,e.__scopeMenu),r=Kc(xl,e.__scopeMenu),i=yl(xl,e.__scopeMenu),a=tl(xl,e.__scopeMenu),o=A.useRef(null),{pointerGraceTimerRef:s,onPointerGraceIntentChange:c}=a,l={__scopeMenu:e.__scopeMenu},u=A.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);A.useEffect(()=>u,[u]),A.useEffect(()=>{let e=s.current;return()=>{window.clearTimeout(e),c(null)}},[s,c]);let d=y(t,i.onTriggerChange);return(0,V.jsx)(Jc,{asChild:!0,...l,children:(0,V.jsx)(dl,{id:i.triggerId,"aria-haspopup":`menu`,"aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":Tl(n.open),...e,ref:d,onClick:t=>{e.onClick?.(t),!(e.disabled||t.defaultPrevented)&&(t.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:B(e.onPointerMove,Nl(t=>{a.onItemEnter(t),!t.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(a.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:B(e.onPointerLeave,Nl(e=>{u();let t=n.content?.getBoundingClientRect();if(t){let r=n.content?.dataset.side,i=r===`right`,o=i?-5:5,c=t[i?`left`:`right`],l=t[i?`right`:`left`];a.onPointerGraceIntentChange({area:[{x:e.clientX+o,y:e.clientY},{x:c,y:t.top},{x:l,y:t.top},{x:l,y:t.bottom},{x:c,y:t.bottom}],side:r}),window.clearTimeout(s.current),s.current=window.setTimeout(()=>a.onPointerGraceIntentChange(null),300)}else{if(a.onTriggerLeave(e),e.defaultPrevented)return;a.onPointerGraceIntentChange(null)}})),onKeyDown:B(e.onKeyDown,t=>{e.disabled||t.target!==t.currentTarget||a.searchRef.current!==``&&t.key===` `||Nc[r.dir].includes(t.key)&&(n.onOpenChange(!0),n.content?.focus(),t.preventDefault())})})})},`MenuSubTrigger`)),Cl=`MenuSubContent`,wl=A.forwardRef(Z(function(e,t){let n=Zc($c,e.__scopeMenu),{forceMount:r=n.forceMount,align:i=`start`,...a}=e,o=Wc($c,e.__scopeMenu),s=Kc($c,e.__scopeMenu),c=yl(Cl,e.__scopeMenu),l=A.useRef(null),u=y(t,l);return(0,V.jsx)(Ic.Provider,{scope:e.__scopeMenu,children:(0,V.jsx)(bi,{present:r||o.open,children:(0,V.jsx)(Ic.Slot,{scope:e.__scopeMenu,children:(0,V.jsx)(ol,{id:c.contentId,"aria-labelledby":c.triggerId,...a,ref:u,align:i,side:s.dir===`rtl`?`left`:`right`,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:e=>{s.isUsingKeyboardRef.current&&l.current?.focus(),e.preventDefault()},onCloseAutoFocus:e=>e.preventDefault(),onFocusOutside:B(e.onFocusOutside,e=>{e.target!==c.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:B(e.onEscapeKeyDown,e=>{s.onClose(),e.preventDefault()}),onKeyDown:B(e.onKeyDown,e=>{let t=e.currentTarget.contains(e.target),n=Pc[s.dir].includes(e.key);t&&n&&(o.onOpenChange(!1),c.trigger?.focus(),e.preventDefault())})})})})})},`MenuSubContent`));function Tl(e){return e?`open`:`closed`}Z(Tl,`getOpenState`);function El(e){return e===`indeterminate`}Z(El,`isIndeterminate`);function Dl(e){return El(e)?`indeterminate`:e?`checked`:`unchecked`}Z(Dl,`getCheckedState`);function Ol(e){let t=document.activeElement;for(let n of e)if(n===t||(n.focus(),document.activeElement!==t))return}Z(Ol,`focusFirst`);function kl(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Z(kl,`wrapArray`);function Al(e,t,n){let r=t.length>1&&Array.from(t).every(e=>e===t[0])?t[0]:t,i=n?e.indexOf(n):-1,a=kl(e,Math.max(i,0));r.length===1&&(a=a.filter(e=>e!==n));let o=a.find(e=>e.toLowerCase().startsWith(r.toLowerCase()));return o===n?void 0:o}Z(Al,`getNextMatch`);function jl(e,t){let{x:n,y:r}=e,i=!1;for(let e=0,a=t.length-1;er!=d>r&&n<(u-c)*(r-l)/(d-l)+c&&(i=!i)}return i}Z(jl,`isPointInPolygon`);function Ml(e,t){return t?jl({x:e.clientX,y:e.clientY},t):!1}Z(Ml,`isPointerInGraceArea`);function Nl(e){return t=>t.pointerType===`mouse`?e(t):void 0}Z(Nl,`whenMouse`);var Pl=Object.defineProperty,Fl=(e,t)=>Pl(e,`name`,{value:t,configurable:!0}),Il=`DropdownMenu`,[Ll,Rl]=pt(Il,[Bc]),zl=Bc(),[Bl,Vl]=Ll(Il),Hl=Fl(e=>{let{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:a,onOpenChange:o,modal:s=!0}=e,c=zl(t),l=A.useRef(null),[u,d]=Pi({prop:i,defaultProp:a??!1,onChange:o,caller:Il});return(0,V.jsx)(Bl,{scope:t,triggerId:K(),triggerRef:l,contentId:K(),open:u,onOpenChange:d,onOpenToggle:A.useCallback(()=>d(e=>!e),[d]),modal:s,children:(0,V.jsx)(qc,{...c,open:u,onOpenChange:d,dir:r,modal:s,children:n})})},`DropdownMenu`),Ul=`DropdownMenuTrigger`,Wl=A.forwardRef(Fl(function(e,t){let{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,a=Vl(Ul,n),o=zl(n),s=y(t,a.triggerRef);return(0,V.jsx)(Jc,{asChild:!0,...o,children:(0,V.jsx)(H.button,{type:`button`,id:a.triggerId,"aria-haspopup":`menu`,"aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":a.open?`open`:`closed`,"data-disabled":r?``:void 0,disabled:r,...i,ref:s,onPointerDown:B(e.onPointerDown,e=>{!r&&e.button===0&&e.ctrlKey===!1&&(a.onOpenToggle(),a.open||e.preventDefault())}),onKeyDown:B(e.onKeyDown,e=>{r||([`Enter`,` `].includes(e.key)&&a.onOpenToggle(),e.key===`ArrowDown`&&a.onOpenChange(!0),[`Enter`,` `,`ArrowDown`].includes(e.key)&&e.preventDefault())})})})},`DropdownMenuTrigger`)),Gl=Fl(e=>{let{__scopeDropdownMenu:t,...n}=e,r=zl(t);return(0,V.jsx)(Qc,{...r,...n})},`DropdownMenuPortal`),Kl=`DropdownMenuContent`,ql=A.forwardRef(Fl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Vl(Kl,n),a=zl(n),o=A.useRef(!1);return(0,V.jsx)(nl,{id:i.contentId,"aria-labelledby":i.triggerId,...a,...r,ref:t,onCloseAutoFocus:B(e.onCloseAutoFocus,e=>{o.current||i.triggerRef.current?.focus(),o.current=!1,e.preventDefault()}),onInteractOutside:B(e.onInteractOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0,r=t.button===2||n;(!i.modal||r)&&(o.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-dropdown-menu-content-available-width":`var(--radix-popper-available-width)`,"--radix-dropdown-menu-content-available-height":`var(--radix-popper-available-height)`,"--radix-dropdown-menu-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-dropdown-menu-trigger-height":`var(--radix-popper-anchor-height)`}})},`DropdownMenuContent`)),Jl=A.forwardRef(Fl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=zl(n);return(0,V.jsx)(sl,{...i,...r,ref:t})},`DropdownMenuLabel`)),Yl=A.forwardRef(Fl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=zl(n);return(0,V.jsx)(ul,{...i,...r,ref:t})},`DropdownMenuItem`)),Xl=A.forwardRef(Fl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=zl(n);return(0,V.jsx)(gl,{...i,...r,ref:t})},`DropdownMenuSeparator`)),Zl=Fl(e=>{let{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:i,defaultOpen:a}=e,o=zl(t),[s,c]=Pi({prop:r,defaultProp:a??!1,onChange:i,caller:`DropdownMenuSub`});return(0,V.jsx)(bl,{...o,open:s,onOpenChange:c,children:n})},`DropdownMenuSub`),Ql=A.forwardRef(Fl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=zl(n);return(0,V.jsx)(Sl,{...i,...r,ref:t})},`DropdownMenuSubTrigger`)),$l=A.forwardRef(Fl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=zl(n);return(0,V.jsx)(wl,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-dropdown-menu-content-available-width":`var(--radix-popper-available-width)`,"--radix-dropdown-menu-content-available-height":`var(--radix-popper-available-height)`,"--radix-dropdown-menu-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-dropdown-menu-trigger-height":`var(--radix-popper-anchor-height)`}})},`DropdownMenuSubContent`)),eu=Hl,tu=Wl,nu=Zl;function ru({className:e,inset:t,children:n,...r}){return(0,V.jsxs)(Ql,{className:p(`flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-muted data-[state=open]:bg-muted`,t&&`pl-8`,e),...r,children:[n,(0,V.jsx)(I,{className:`ml-auto size-4 opacity-60`})]})}function iu({className:e,...t}){return(0,V.jsx)($l,{className:p(`z-50 min-w-40 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg`,e),...t})}function au({className:e,sideOffset:t=4,...n}){return(0,V.jsx)(Gl,{children:(0,V.jsx)(ql,{sideOffset:t,className:p(`z-50 min-w-44 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95`,e),...n})})}function Q({className:e,inset:t,...n}){return(0,V.jsx)(Yl,{className:p(`relative flex cursor-default select-none items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50`,t&&`pl-8`,e),...n})}function ou({className:e,inset:t,...n}){return(0,V.jsx)(Jl,{className:p(`px-2 py-1.5 text-xs font-medium text-muted-foreground`,t&&`pl-8`,e),...n})}function su({className:e,...t}){return(0,V.jsx)(Xl,{className:p(`-mx-1 my-1 h-px bg-border`,e),...t})}var cu=Object.defineProperty,lu=(e,t)=>cu(e,`name`,{value:t,configurable:!0}),uu=`Dialog`,[du,fu]=pt(uu),[pu,mu]=du(uu),hu=lu(e=>{let{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!0}=e,s=A.useRef(null),c=A.useRef(null),[l,u]=Pi({prop:r,defaultProp:i??!1,onChange:a,caller:uu}),[d,f]=A.useState(0),[p,m]=A.useState(0);return(0,V.jsx)(pu,{scope:t,triggerRef:s,contentRef:c,contentId:K(),titleId:K(),descriptionId:K(),titlePresent:d>0,descriptionPresent:p>0,setTitleCount:f,setDescriptionCount:m,open:l,onOpenChange:u,onOpenToggle:A.useCallback(()=>u(e=>!e),[u]),modal:o,children:n})},`Dialog`),gu=`DialogPortal`,[_u,vu]=du(gu,{forceMount:void 0}),yu=lu(e=>{let{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=mu(gu,t);return(0,V.jsx)(_u,{scope:t,forceMount:n,children:A.Children.map(r,e=>(0,V.jsx)(bi,{present:n||a.open,children:(0,V.jsx)(gi,{asChild:!0,container:i,children:e})}))})},`DialogPortal`),bu=`DialogOverlay`,xu=A.forwardRef(lu(function(e,t){let n=vu(bu,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=mu(bu,e.__scopeDialog);return a.modal?(0,V.jsx)(bi,{present:r||a.open,children:(0,V.jsx)(Cu,{...i,ref:t})}):null},`DialogOverlay`)),Su=m(`DialogOverlay.RemoveScroll`),Cu=A.forwardRef(lu(function(e,t){let{__scopeDialog:n,...r}=e,i=mu(bu,n),a=y(t,Ot());return(0,V.jsx)(Dc,{as:Su,allowPinchZoom:!0,shards:[i.contentRef],children:(0,V.jsx)(H.div,{"data-state":Pu(i.open),...r,ref:a,style:{pointerEvents:`auto`,...r.style}})})},`DialogOverlayImpl`)),wu=`DialogContent`,Tu=A.forwardRef(lu(function(e,t){let n=vu(wu,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=mu(wu,e.__scopeDialog);return(0,V.jsx)(bi,{present:r||a.open,children:a.modal?(0,V.jsx)(Eu,{...i,ref:t}):(0,V.jsx)(Du,{...i,ref:t})})},`DialogContent`)),Eu=A.forwardRef(lu(function(e,t){let n=mu(wu,e.__scopeDialog),r=A.useRef(null),i=y(t,n.contentRef,r);return A.useEffect(()=>{let e=r.current;if(e)return vs(e)},[]),(0,V.jsx)(Ou,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:B(e.onCloseAutoFocus,e=>{e.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:B(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0;(t.button===2||n)&&e.preventDefault()}),onFocusOutside:B(e.onFocusOutside,e=>e.preventDefault())})},`DialogContentModal`)),Du=A.forwardRef(lu(function(e,t){let n=mu(wu,e.__scopeDialog),r=A.useRef(!1),i=A.useRef(!1);return(0,V.jsx)(Ou,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})},`DialogContentNonModal`)),Ou=A.forwardRef(lu(function(e,t){let{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,"aria-describedby":o,...s}=e,c=mu(wu,n);return _o(),(0,V.jsx)(V.Fragment,{children:(0,V.jsx)(Co,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,V.jsx)(Dt,{role:`dialog`,id:c.contentId,"aria-labelledby":c.titlePresent?c.titleId:void 0,"aria-describedby":c.descriptionPresent?Nu(o,c.descriptionId):o,"data-state":Pu(c.open),...s,ref:t,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})},`DialogContentImpl`)),ku=A.forwardRef(lu(function(e,t){let{__scopeDialog:n,...r}=e,i=mu(`DialogTitle`,n),{setTitleCount:a}=i;return G(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,V.jsx)(H.h2,{id:i.titleId,...r,ref:t})},`DialogTitle`)),Au=A.forwardRef(lu(function(e,t){let{__scopeDialog:n,...r}=e,i=mu(`DialogDescription`,n),{setDescriptionCount:a}=i;return G(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,V.jsx)(H.p,{id:i.descriptionId,...r,ref:t})},`DialogDescription`)),ju=`DialogClose`,Mu=A.forwardRef(lu(function(e,t){let{__scopeDialog:n,...r}=e,i=mu(ju,n);return(0,V.jsx)(H.button,{type:`button`,...r,ref:t,onClick:B(e.onClick,()=>i.onOpenChange(!1))})},`DialogClose`));function Nu(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}lu(Nu,`concatAriaDescribedby`);function Pu(e){return e?`open`:`closed`}lu(Pu,`getState`);var Fu=hu,Iu=yu;function Lu({className:e,...t}){return(0,V.jsx)(xu,{className:p(`fixed inset-0 z-50 bg-black/40 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0`,e),...t})}function Ru({className:e,children:t,...n}){return(0,V.jsxs)(Iu,{children:[(0,V.jsx)(Lu,{}),(0,V.jsxs)(Tu,{className:p(`fixed left-1/2 top-1/2 z-50 grid w-[calc(100%-2rem)] max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border border-border bg-background p-6 shadow-xl duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95`,e),...n,children:[t,(0,V.jsxs)(Mu,{className:`absolute right-3 top-3 rounded-md p-1.5 text-muted-foreground opacity-70 transition-opacity hover:bg-muted hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring/40`,children:[(0,V.jsx)(ze,{className:`size-4`}),(0,V.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function zu({className:e,...t}){return(0,V.jsx)(`div`,{className:p(`flex flex-col gap-1.5 text-left`,e),...t})}function Bu({className:e,...t}){return(0,V.jsx)(ku,{className:p(`text-lg font-semibold leading-none tracking-tight`,e),...t})}function Vu({className:e,...t}){return(0,V.jsx)(Au,{className:p(`text-sm text-muted-foreground`,e),...t})}function Hu(){let e=b();if(!e)return null;let t=e.displayName??e.primaryEmail??`Account`;return(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.profileImageUrl?(0,V.jsx)(`img`,{src:e.profileImageUrl,alt:``,className:`h-8 w-8 rounded-full object-cover`}):(0,V.jsx)(`span`,{className:`grid h-8 w-8 place-items-center rounded-full bg-black/10 text-sm font-medium dark:bg-white/20`,children:t.charAt(0).toUpperCase()}),(0,V.jsx)(`span`,{className:`text-sm font-medium`,children:t}),(0,V.jsx)(`button`,{type:`button`,onClick:()=>void d(),className:`cursor-pointer text-sm underline-offset-4 opacity-70 hover:underline`,children:`Sign out`})]})}function Uu({onOpenSearch:e,mobile:t,onNavigate:n}){let r=z(e=>e.name),a=z(e=>e.pages),o=z(e=>e.activePageId),s=z(e=>e.theme),c=z(e=>e.storageMode),l=z(e=>e.syncStatus),u=z(e=>e.setActivePage),d=z(e=>e.createPage),f=z(e=>e.deletePage),m=z(e=>e.restorePage),h=z(e=>e.permanentlyDeletePage),_=z(e=>e.duplicatePage),y=z(e=>e.updatePage),b=z(e=>e.toggleSidebar),x=z(e=>e.setTheme),S=z(e=>e.setName),C=z(e=>e.resetWorkspace),{user:w}=g(),[T,E]=(0,A.useState)({}),[D,O]=(0,A.useState)(!1),[k,j]=(0,A.useState)(!1),M=a.filter(e=>!e.archived),N=a.filter(e=>e.archived),P=M.filter(e=>e.favorite),ee=(0,A.useMemo)(()=>{let e=new Map;for(let t of M){let n=t.parentId,r=e.get(n)??[];r.push(t),e.set(n,r)}for(let[,t]of e)t.sort((e,t)=>e.createdAt-t.createdAt);return e},[M]),ne=e=>{u(e),n?.()},ae=e=>{E(t=>({...t,[e]:!t[e]}))},se=(e,t=0)=>(ee.get(e)??[]).map(e=>{let n=(ee.get(e.id)??[]).length>0,r=T[e.id]??t<1;return(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:p(`group flex items-center gap-0.5 rounded-md pr-1 text-sm transition-colors`,o===e.id?`bg-sidebar-active text-foreground`:`text-sidebar-fg hover:bg-sidebar-hover`),style:{paddingLeft:`${8+t*12}px`},children:[(0,V.jsx)(`button`,{type:`button`,className:p(`flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-black/5 dark:hover:bg-white/10`,!n&&`opacity-0`),onClick:()=>ae(e.id),"aria-label":r?`Collapse`:`Expand`,tabIndex:n?0:-1,children:r?(0,V.jsx)(F,{className:`size-3.5`}):(0,V.jsx)(I,{className:`size-3.5`})}),(0,V.jsxs)(`button`,{type:`button`,className:`flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left`,onClick:()=>ne(e.id),children:[(0,V.jsx)(`span`,{className:`shrink-0 text-sm leading-none`,children:e.icon}),(0,V.jsx)(`span`,{className:`truncate font-medium`,children:e.title||`Untitled`})]}),(0,V.jsxs)(`div`,{className:`flex shrink-0 items-center opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100`,children:[(0,V.jsxs)(eu,{children:[(0,V.jsx)(tu,{asChild:!0,children:(0,V.jsx)(`button`,{type:`button`,className:`flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10`,"aria-label":`Page options`,children:(0,V.jsx)(ie,{className:`size-3.5 text-muted-foreground`})})}),(0,V.jsxs)(au,{align:`start`,className:`w-48`,children:[(0,V.jsxs)(Q,{onClick:()=>y(e.id,{favorite:!e.favorite}),children:[(0,V.jsx)(Me,{className:`size-4`}),e.favorite?`Remove favorite`:`Add to favorites`]}),(0,V.jsxs)(Q,{onClick:()=>d({parentId:e.id}),children:[(0,V.jsx)(Te,{className:`size-4`}),` Add sub-page`]}),(0,V.jsxs)(Q,{onClick:()=>_(e.id),children:[(0,V.jsx)(re,{className:`size-4`}),` Duplicate`]}),(0,V.jsx)(su,{}),(0,V.jsxs)(Q,{className:`text-destructive focus:text-destructive`,onClick:()=>f(e.id),children:[(0,V.jsx)(Fe,{className:`size-4`}),` Delete`]})]})]}),(0,V.jsx)(`button`,{type:`button`,className:`flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10`,"aria-label":`New sub-page`,onClick:()=>{d({parentId:e.id}),E(t=>({...t,[e.id]:!0}))},children:(0,V.jsx)(Te,{className:`size-3.5 text-muted-foreground`})})]})]}),n&&r&&se(e.id,t+1)]},e.id)});return(0,V.jsxs)(`aside`,{className:p(`flex h-full flex-col border-r border-sidebar-border bg-sidebar text-sidebar-fg`,t?`w-full`:`w-[260px] min-w-[260px]`),children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-3`,children:[(0,V.jsxs)(`button`,{type:`button`,className:`flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-sidebar-hover`,onClick:()=>j(!0),children:[(0,V.jsx)(`span`,{className:`flex size-6 shrink-0 items-center justify-center rounded-md bg-foreground text-[11px] font-semibold text-background`,children:r.slice(0,1).toUpperCase()||`W`}),(0,V.jsx)(`span`,{className:`truncate text-sm font-semibold text-foreground`,children:r}),(0,V.jsx)(F,{className:`size-3.5 shrink-0 text-muted-foreground`})]}),!t&&(0,V.jsx)(v,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`shrink-0 text-muted-foreground`,onClick:b,"aria-label":`Close sidebar`,children:(0,V.jsx)(Se,{className:`size-4`})})]}),(0,V.jsxs)(`div`,{className:`space-y-0.5 px-2 py-2`,children:[(0,V.jsx)(Wu,{icon:(0,V.jsx)(Oe,{className:`size-4`}),label:`Search`,shortcut:`⌘K`,onClick:e}),(0,V.jsx)(Wu,{icon:(0,V.jsx)(oe,{className:`size-4`}),label:`New page`,onClick:()=>d()})]}),(0,V.jsxs)(Za,{className:`flex-1 px-2`,children:[P.length>0&&(0,V.jsxs)(`div`,{className:`mb-3`,children:[(0,V.jsx)(`div`,{className:`px-2 py-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:`Favorites`}),P.map(e=>(0,V.jsxs)(`button`,{type:`button`,onClick:()=>ne(e.id),className:p(`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors`,o===e.id?`bg-sidebar-active text-foreground`:`text-sidebar-fg hover:bg-sidebar-hover`),children:[(0,V.jsx)(`span`,{className:`text-sm leading-none`,children:e.icon}),(0,V.jsx)(`span`,{className:`truncate font-medium`,children:e.title||`Untitled`})]},`fav-${e.id}`))]}),(0,V.jsxs)(`div`,{className:`mb-3`,children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-between px-2 py-1`,children:[(0,V.jsx)(`span`,{className:`text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:`Private`}),(0,V.jsx)(`button`,{type:`button`,className:`flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-sidebar-hover`,onClick:()=>d(),"aria-label":`New page`,children:(0,V.jsx)(Te,{className:`size-3.5`})})]}),se(null),M.filter(e=>!e.parentId).length===0&&(0,V.jsx)(`p`,{className:`px-2 py-2 text-xs text-muted-foreground`,children:`No pages yet`})]})]}),(0,V.jsxs)(`div`,{className:`space-y-0.5 border-t border-sidebar-border p-2`,children:[(0,V.jsx)(`div`,{className:`flex items-center gap-2 rounded-md px-2 py-1.5 text-xs text-muted-foreground`,children:c===`database`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(te,{className:`size-3.5 shrink-0`}),(0,V.jsx)(`span`,{className:`truncate`,children:l===`error`?`Database sync error`:l===`saving`||l===`pending`?`Saving to database…`:`Synced to database`})]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(L,{className:`size-3.5 shrink-0`}),(0,V.jsx)(`span`,{className:`truncate`,children:`Local browser only`})]})}),(0,V.jsx)(`div`,{className:`px-1 py-1`,children:w?(0,V.jsx)(Hu,{}):(0,V.jsxs)(i,{to:`/login`,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-fg transition-colors hover:bg-sidebar-hover`,onClick:n,children:[(0,V.jsx)(_e,{className:`size-4 text-muted-foreground`}),`Sign in to sync`]})}),(0,V.jsx)(Wu,{icon:(0,V.jsx)(Fe,{className:`size-4`}),label:`Trash`,onClick:()=>O(!0)}),(0,V.jsx)(Wu,{icon:(0,V.jsx)(ke,{className:`size-4`}),label:`Settings`,onClick:()=>j(!0)})]}),(0,V.jsx)(Fu,{open:D,onOpenChange:O,children:(0,V.jsxs)(Ru,{className:`max-w-md`,children:[(0,V.jsxs)(zu,{children:[(0,V.jsx)(Bu,{children:`Trash`}),(0,V.jsx)(Vu,{children:`Restored pages return to the top level of your workspace.`})]}),(0,V.jsxs)(`div`,{className:`max-h-72 space-y-1 overflow-y-auto`,children:[N.length===0&&(0,V.jsx)(`p`,{className:`py-8 text-center text-sm text-muted-foreground`,children:`Trash is empty`}),N.map(e=>(0,V.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border border-border px-3 py-2`,children:[(0,V.jsx)(`span`,{children:e.icon}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium`,children:e.title||`Untitled`}),(0,V.jsx)(v,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>m(e.id),children:`Restore`}),(0,V.jsx)(v,{type:`button`,size:`sm`,variant:`ghost`,className:`text-destructive`,onClick:()=>h(e.id),children:`Delete`})]},e.id))]})]})}),(0,V.jsx)(Fu,{open:k,onOpenChange:j,children:(0,V.jsxs)(Ru,{className:`max-w-md`,children:[(0,V.jsxs)(zu,{children:[(0,V.jsx)(Bu,{children:`Workspace settings`}),(0,V.jsx)(Vu,{children:c===`database`?`Changes save to your database automatically.`:`Guest data stays in this browser. Sign in to sync to the database.`})]}),(0,V.jsxs)(`div`,{className:`space-y-4`,children:[(0,V.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,V.jsx)(`span`,{className:`text-sm font-medium`,children:`Workspace name`}),(0,V.jsx)(`input`,{className:`flex h-9 w-full rounded-md border border-border bg-background px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/40`,value:r,onChange:e=>S(e.target.value)})]}),(0,V.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,V.jsx)(`span`,{className:`text-sm font-medium`,children:`Appearance`}),(0,V.jsxs)(`div`,{className:`flex gap-2`,children:[(0,V.jsxs)(v,{type:`button`,variant:s===`light`?`secondary`:`outline`,className:`flex-1`,onClick:()=>x(`light`),children:[(0,V.jsx)(Ne,{className:`size-4`}),` Light`]}),(0,V.jsxs)(v,{type:`button`,variant:s===`dark`?`secondary`:`outline`,className:`flex-1`,onClick:()=>x(`dark`),children:[(0,V.jsx)(xe,{className:`size-4`}),` Dark`]})]})]}),(0,V.jsxs)(`div`,{className:`rounded-lg border border-border bg-muted/40 p-3 text-xs leading-relaxed text-muted-foreground`,children:[(0,V.jsx)(`p`,{className:`font-medium text-foreground`,children:`Storage`}),(0,V.jsx)(`p`,{className:`mt-1`,children:c===`database`?`Postgres (Neon when deployed, embedded PGLite in this preview).`:`Browser localStorage only. Sign in to use the database.`})]}),(0,V.jsxs)(v,{type:`button`,variant:`outline`,className:`w-full`,onClick:()=>{C(),j(!1)},children:[(0,V.jsx)(De,{className:`size-4`}),` Reset demo content`]})]})]})})]})}function Wu({icon:e,label:t,shortcut:n,onClick:r}){return(0,V.jsxs)(`button`,{type:`button`,onClick:r,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm text-sidebar-fg transition-colors hover:bg-sidebar-hover`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,V.jsx)(`span`,{className:`flex-1 text-left font-medium`,children:t}),n&&(0,V.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:n})]})}var Gu=Object.defineProperty,Ku=(e,t)=>Gu(e,`name`,{value:t,configurable:!0}),qu=`Popover`,[Ju,Yu]=pt(qu,[ni]),Xu=ni(),[Zu,Qu]=Ju(qu),$u=Ku(e=>{let{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!1}=e,s=Xu(t),c=A.useRef(null),[l,u]=A.useState(!1),[d,f]=A.useState(0),[p,m]=A.useState(0),[h,g]=Pi({prop:r,defaultProp:i??!1,onChange:a,caller:qu});return(0,V.jsx)(ai,{...s,children:(0,V.jsx)(Zu,{scope:t,contentId:K(),titleId:K(),descriptionId:K(),titlePresent:d>0,descriptionPresent:p>0,setTitleCount:f,setDescriptionCount:m,triggerRef:c,open:h,onOpenChange:g,onOpenToggle:A.useCallback(()=>g(e=>!e),[g]),hasCustomAnchor:l,onCustomAnchorAdd:A.useCallback(()=>u(!0),[]),onCustomAnchorRemove:A.useCallback(()=>u(!1),[]),modal:o,children:n})})},`Popover`),ed=`PopoverTrigger`,td=A.forwardRef(Ku(function(e,t){let{__scopePopover:n,...r}=e,i=Qu(ed,n),a=Xu(n),o=y(t,i.triggerRef),s=(0,V.jsx)(H.button,{type:`button`,"aria-haspopup":`dialog`,"aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":fd(i.open),...r,ref:o,onClick:B(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?s:(0,V.jsx)(si,{asChild:!0,...a,children:s})},`PopoverTrigger`)),nd=`PopoverPortal`,[rd,id]=Ju(nd,{forceMount:void 0}),ad=Ku(e=>{let{__scopePopover:t,forceMount:n,children:r,container:i}=e,a=Qu(nd,t);return(0,V.jsx)(rd,{scope:t,forceMount:n,children:(0,V.jsx)(bi,{present:n||a.open,children:(0,V.jsx)(gi,{asChild:!0,container:i,children:r})})})},`PopoverPortal`),od=`PopoverContent`,sd=A.forwardRef(Ku(function(e,t){let n=id(od,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,a=Qu(od,e.__scopePopover);return(0,V.jsx)(bi,{present:r||a.open,children:a.modal?(0,V.jsx)(ld,{...i,ref:t}):(0,V.jsx)(ud,{...i,ref:t})})},`PopoverContent`)),cd=m(`PopoverContent.RemoveScroll`),ld=A.forwardRef(Ku(function(e,t){let n=Qu(od,e.__scopePopover),r=A.useRef(null),i=y(t,r),a=A.useRef(!1);return A.useEffect(()=>{let e=r.current;if(e)return vs(e)},[]),(0,V.jsx)(Dc,{as:cd,allowPinchZoom:!0,children:(0,V.jsx)(dd,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:B(e.onCloseAutoFocus,e=>{e.preventDefault(),a.current||n.triggerRef.current?.focus()}),onPointerDownOutside:B(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0,r=t.button===2||n;a.current=r},{checkForDefaultPrevented:!1}),onFocusOutside:B(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})},`PopoverContentModal`)),ud=A.forwardRef(Ku(function(e,t){let n=Qu(od,e.__scopePopover),r=A.useRef(!1),i=A.useRef(!1);return(0,V.jsx)(dd,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})},`PopoverContentNonModal`)),dd=A.forwardRef(Ku(function(e,t){let{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:o,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:l,onInteractOutside:u,"aria-describedby":d,...f}=e,p=Qu(od,n),m=Xu(n);return _o(),(0,V.jsx)(Co,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,V.jsx)(Dt,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:u,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:l,onDismiss:()=>p.onOpenChange(!1),deferPointerDownOutside:!0,children:(0,V.jsx)(di,{"data-state":fd(p.open),role:`dialog`,id:p.contentId,"aria-labelledby":p.titlePresent?p.titleId:void 0,"aria-describedby":p.descriptionPresent?pd(d,p.descriptionId):d,...m,...f,ref:t,style:{...f.style,"--radix-popover-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-popover-content-available-width":`var(--radix-popper-available-width)`,"--radix-popover-content-available-height":`var(--radix-popper-available-height)`,"--radix-popover-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-popover-trigger-height":`var(--radix-popper-anchor-height)`}})})})},`PopoverContentImpl`));function fd(e){return e?`open`:`closed`}Ku(fd,`getState`);function pd(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}Ku(pd,`concatAriaDescribedby`);var md=$u,hd=td;function gd({className:e,align:t=`center`,sideOffset:n=6,...r}){return(0,V.jsx)(ad,{children:(0,V.jsx)(sd,{align:t,sideOffset:n,className:p(`z-50 w-72 rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-lg outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95`,e),...r})})}var _d=[{type:`paragraph`,label:`Text`,description:`Just start writing with plain text.`,icon:Ie,keywords:[`text`,`paragraph`,`plain`],placeholder:`Type '/' for commands`},{type:`heading1`,label:`Heading 1`,description:`Big section heading.`,icon:le,keywords:[`h1`,`title`,`heading`],placeholder:`Heading 1`},{type:`heading2`,label:`Heading 2`,description:`Medium section heading.`,icon:ue,keywords:[`h2`,`heading`,`subtitle`],placeholder:`Heading 2`},{type:`heading3`,label:`Heading 3`,description:`Small section heading.`,icon:de,keywords:[`h3`,`heading`],placeholder:`Heading 3`},{type:`bullet`,label:`Bulleted list`,description:`Create a simple bulleted list.`,icon:he,keywords:[`ul`,`list`,`bullet`,`unordered`],placeholder:`List item`},{type:`numbered`,label:`Numbered list`,description:`Create a list with numbering.`,icon:fe,keywords:[`ol`,`list`,`number`,`ordered`],placeholder:`List item`},{type:`todo`,label:`To-do list`,description:`Track tasks with a to-do checkbox.`,icon:je,keywords:[`todo`,`task`,`checkbox`,`check`],placeholder:`To-do`},{type:`toggle`,label:`Toggle`,description:`Hide and show content inside.`,icon:I,keywords:[`toggle`,`collapse`,`details`],placeholder:`Toggle heading`},{type:`quote`,label:`Quote`,description:`Capture a quote.`,icon:Ee,keywords:[`quote`,`blockquote`,`cite`],placeholder:`Empty quote`},{type:`callout`,label:`Callout`,description:`Make writing stand out.`,icon:ye,keywords:[`callout`,`note`,`info`,`tip`],placeholder:`Callout`},{type:`code`,label:`Code`,description:`Capture a code snippet.`,icon:ne,keywords:[`code`,`snippet`,`pre`],placeholder:`Code`},{type:`mermaid`,label:`Mermaid`,description:`Diagram with Mermaid syntax.`,icon:Re,keywords:[`mermaid`,`diagram`,`flowchart`,`sequence`,`graph`],placeholder:`flowchart TD - A[Start] --> B[End]`},{type:`ai`,label:`AI`,description:`Generate from the rest of this page.`,icon:Ae,keywords:[`ai`,`gpt`,`grok`,`summary`,`assistant`,`llm`],placeholder:`Summarize this page as a launch checklist…`},{type:`divider`,label:`Divider`,description:`Visually divide blocks.`,icon:be,keywords:[`divider`,`line`,`hr`,`separator`],placeholder:``}];function vd(e){return _d.find(t=>t.type===e)??_d[0]}function yd(e){let t=e.trim().toLowerCase();return t?_d.filter(e=>e.label.toLowerCase().includes(t)||e.description.toLowerCase().includes(t)||e.keywords.some(e=>e.includes(t))):_d}function bd({query:e,selectedIndex:t,onSelect:n,onHover:r,position:i}){let a=(0,A.useMemo)(()=>yd(e),[e]),o=(0,A.useRef)(null);return(0,A.useEffect)(()=>{(o.current?.querySelector(`[data-index="${t}"]`))?.scrollIntoView({block:`nearest`})},[t]),a.length===0?(0,V.jsx)(`div`,{className:`fixed z-50 w-72 overflow-hidden rounded-xl border border-border bg-popover p-3 text-sm text-muted-foreground shadow-xl`,style:{top:i.top,left:i.left},children:`No matching blocks`}):(0,V.jsxs)(`div`,{ref:o,className:`fixed z-50 max-h-72 w-72 overflow-y-auto rounded-xl border border-border bg-popover p-1.5 shadow-xl`,style:{top:i.top,left:Math.min(i.left,window.innerWidth-300)},role:`listbox`,children:[(0,V.jsx)(`div`,{className:`px-2 py-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:`Basic blocks`}),a.map((e,i)=>{let a=e.icon;return(0,V.jsxs)(`button`,{type:`button`,"data-index":i,role:`option`,"aria-selected":i===t,className:p(`flex w-full items-start gap-2.5 rounded-lg px-2 py-2 text-left transition-colors`,i===t?`bg-muted`:`hover:bg-muted/70`),onMouseEnter:()=>r(i),onMouseDown:t=>{t.preventDefault(),n(e.type)},children:[(0,V.jsx)(`span`,{className:`mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground`,children:(0,V.jsx)(a,{className:`size-4`})}),(0,V.jsxs)(`span`,{className:`min-w-0`,children:[(0,V.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),(0,V.jsx)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:e.description})]})]},e.type)})]})}var xd=null;function Sd(){return xd||=u(()=>import(`./mermaid.core-BrAYfHNA.js`).then(e=>{let t=e.default;return t.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),t}),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23])),xd}function Cd({source:e,className:t}){let n=(0,A.useId)().replace(/:/g,``),r=(0,A.useRef)(null),[i,a]=(0,A.useState)(null),[o,s]=(0,A.useState)(``);return(0,A.useEffect)(()=>{let t=!1,r=e.trim();if(!r){s(``),a(null);return}return(async()=>{try{let e=await Sd();e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`});let i=`mmd_${n}_${Math.random().toString(36).slice(2,8)}`,{svg:o}=await e.render(i,r);t||(s(o),a(null))}catch(e){t||(s(``),a(e instanceof Error?e.message:`Invalid Mermaid diagram`))}})(),()=>{t=!0}},[e,n]),e.trim()?i?(0,V.jsx)(`div`,{className:`rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive`,children:i}):(0,V.jsx)(`div`,{ref:r,className:p(`overflow-x-auto rounded-md border border-border bg-background px-3 py-4 [&_svg]:mx-auto [&_svg]:max-w-full`,t),dangerouslySetInnerHTML:o?{__html:o}:void 0}):(0,V.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Write Mermaid syntax (e.g. flowchart TD) — diagram previews here.`})}function wd(e){return e!==`__proto__`&&e!==`constructor`&&e!==`prototype`}function Td(e,t){let n=Object.create(null);if(e)for(let t of Object.keys(e))wd(t)&&(n[t]=e[t]);if(t&&typeof t==`object`)for(let e of Object.keys(t))wd(e)&&(n[e]=t[e]);return n}function Ed(e){if(!e)return Object.create(null);let t=Object.create(null);for(let n of Object.keys(e))wd(n)&&(t[n]=e[n]);return t}var Dd=()=>{throw Error(`createServerOnlyFn() functions can only be called on the server!`)},Od=(e,t)=>{let n=t||e||{};n.method===void 0&&(n.method=`GET`);let r=e=>Od(void 0,{...n,validator:e,inputValidator:e});return Object.assign(e=>Od(void 0,{...n,...e}),{options:n,middleware:e=>{let t=[...n.middleware||[]];e.map(e=>{l in e?e.options.middleware&&t.push(...e.options.middleware):t.push(e)});let r=Od(void 0,{...n,middleware:t});return r[l]=!0,r},validator:r,inputValidator:r,handler:(...e)=>{let[t,r]=e,i={...n,extractedFn:t,serverFn:r},o=[...i.middleware||[],Md(i)];return t.method=n.method,Object.assign(async e=>{let n=await kd(o,`client`,{...t,...i,data:e?.data,headers:e?.headers,signal:e?.signal,fetch:e?.fetch,context:Ed()}),r=a(n.error);if(r)throw r;if(n.error)throw n.error;return n.result},{...t,method:n.method,__executeServer:async e=>{let n=Dd(),r=n.contextAfterGlobalMiddlewares;return await kd(o,`server`,{...t,...e,serverFnMeta:t.serverFnMeta,context:Td(e.context,r),request:n.request}).then(e=>({result:e.result,error:e.error,context:e.sendContext}))}})}})};async function kd(e,t,n){let r=Ad([...s()?.functionMiddleware||[],...e]);if(t===`server`){let e=Dd({throwIfNotFound:!1});e?.executedRequestMiddlewares&&(r=r.filter(t=>!e.executedRequestMiddlewares.has(t)))}let i=async e=>{let n=r.shift();if(!n)return e;try{let r=`validator`in n.options?n.options.validator:void 0;!r&&`inputValidator`in n.options&&(r=n.options.inputValidator),r&&t===`server`&&(e.data=await jd(r,e.data));let a;if(t===`client`?`client`in n.options&&(a=n.options.client):`server`in n.options&&(a=n.options.server),a){let t=async(t={})=>{let n=await i({...e,...t,context:Td(e.context,t.context),sendContext:Td(e.sendContext,t.sendContext),headers:C(e.headers,t.headers),_callSiteFetch:e._callSiteFetch,fetch:e._callSiteFetch??t.fetch??e.fetch,result:t.result===void 0?t instanceof Response?t:e.result:t.result,error:t.error??e.error});if(n.error)throw n.error;return n},n=await a({...e,next:t});if(o(n))return{...e,error:n};if(n instanceof Response)return{...e,result:n};if(!n)throw Error(`User middleware returned undefined. You must call next() or return a result in your middlewares.`);return n}return i(e)}catch(t){return{...e,error:t}}};return i({...n,headers:n.headers||{},sendContext:n.sendContext||{},context:n.context||Ed(),_callSiteFetch:n.fetch})}function Ad(e,t=100){let n=new Set,r=[],i=(e,a)=>{if(a>t)throw Error(`Middleware nesting depth exceeded maximum of ${t}. Check for circular references.`);e.forEach(e=>{e.options.middleware&&i(e.options.middleware,a+1),n.has(e)||(n.add(e),r.push(e))})};return i(e,0),r}async function jd(e,t){if(e==null)return{};if(`~standard`in e){let n=await e[`~standard`].validate(t);if(n.issues)throw Error(JSON.stringify(n.issues,void 0,2));return n.value}if(`parse`in e)return e.parse(t);if(typeof e==`function`)return e(t);throw Error(`Invalid validator type!`)}function Md(e){return{"~types":void 0,options:{inputValidator:e.validator??e.inputValidator,client:async({next:t,sendContext:n,fetch:r,...i})=>{let a={...i,context:n,fetch:r};return t(await e.extractedFn?.(a))},server:async({next:t,...n})=>{let r=await e.serverFn?.(n);return t({...n,result:r})}}}}var Nd=(e,t)=>{let n={type:`request`,...t||e},r=e=>Nd({},Object.assign(n,{validator:e,inputValidator:e}));return{options:n,middleware:e=>Nd({},Object.assign(n,{middleware:e})),validator:r,inputValidator:r,client:e=>Nd({},Object.assign(n,{client:e})),server:e=>Nd({},Object.assign(n,{server:e}))}},Pd=Od({method:`POST`}).handler(c(`76d08ea8f0b0103fcaf7055c8b138a9579e4124d0d2f62a0686a1011273cd47a`));Od({method:`GET`}).handler(c(`5252add61246cf72a4fa382b4734734c4e8ea74302302ba378f1ecb54d53868d`));var Fd=[{action:`summarize`,label:`Summary`,icon:se,hint:`Condense the page`},{action:`action_items`,label:`Todos`,icon:pe,hint:`Extract action items`},{action:`table`,label:`Table`,icon:Pe,hint:`Markdown table`},{action:`outline`,label:`Outline`,icon:me,hint:`Hierarchical outline`},{action:`mermaid`,label:`Diagram`,icon:Re,hint:`Mermaid flowchart`}];function Id({content:e,aiOutput:t,aiError:n,pageTitle:r,pageText:i,onChangePrompt:a,onResult:o}){let[s,c]=(0,A.useState)(!1),[l,u]=(0,A.useState)(null),d=async(t,n)=>{c(!0);try{let a=await Pd({data:{action:t,instruction:n??e,pageTitle:r,pageText:i}});u(a.provider===`xai`?a.model??`Grok`:`Local demo AI`),o({output:a.text||(a.blocks?a.blocks.map(e=>`${e.type}: ${e.content}`).join(` -`):``),blocks:a.blocks})}catch(e){o({output:``,error:e instanceof Error?e.message:`AI request failed`})}finally{c(!1)}};return(0,V.jsxs)(`div`,{className:`w-full space-y-3 rounded-xl border border-border bg-muted/30 p-3`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-medium text-foreground`,children:[(0,V.jsx)(`span`,{className:`flex size-7 items-center justify-center rounded-md bg-foreground text-background`,children:(0,V.jsx)(Ae,{className:`size-3.5`})}),`AI block`,l&&(0,V.jsx)(`span`,{className:`ml-auto text-[11px] font-normal text-muted-foreground`,children:l})]}),(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Uses the rest of this page as context. Inserts results below this block.`}),(0,V.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:Fd.map(e=>{let t=e.icon;return(0,V.jsxs)(v,{type:`button`,size:`sm`,variant:`outline`,className:`bg-background`,disabled:s,title:e.hint,onClick:()=>void d(e.action),children:[(0,V.jsx)(t,{className:`size-3.5`}),e.label]},e.action)})}),(0,V.jsx)(`textarea`,{value:e,onChange:e=>a(e.target.value),placeholder:`Custom instruction — e.g. Turn this into a launch checklist…`,rows:2,className:`w-full resize-y rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/40`}),(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsxs)(v,{type:`button`,size:`sm`,disabled:s||!e.trim(),onClick:()=>void d(`custom`,e.trim()),children:[s?(0,V.jsx)(ge,{className:`size-3.5 animate-spin`}):(0,V.jsx)(we,{className:`size-3.5`}),`Run custom`]}),s&&(0,V.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Thinking…`})]}),n&&(0,V.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),t&&!n&&(0,V.jsx)(`div`,{className:p(`rounded-md border border-border bg-background px-3 py-2 text-xs text-muted-foreground`),children:`Last run applied below this block.`})]})}var Ld=[{id:`improve`,label:`Improve`,instruction:`Improve clarity and flow while preserving meaning.`},{id:`shorter`,label:`Shorter`,instruction:`Make this shorter and more concise.`},{id:`longer`,label:`Expand`,instruction:`Expand this with one more sentence of useful detail.`},{id:`fix`,label:`Fix grammar`,instruction:`Fix grammar and spelling only.`},{id:`pro`,label:`Professional`,instruction:`Rewrite in a clear, professional tone.`}];function Rd({open:e,onOpenChange:t,blockText:n,blockType:r,pageTitle:i,pageText:a,onApply:o}){let[s,c]=(0,A.useState)(``),[l,u]=(0,A.useState)(null),[d,f]=(0,A.useState)(!1),[m,h]=(0,A.useState)(null),[g,_]=(0,A.useState)(null),y=async e=>{f(!0),h(null);try{let t=await Pd({data:{action:`edit_block`,instruction:e,blockText:n,blockType:r,pageTitle:i,pageText:a}});u(t.text),_(t.provider===`xai`?t.model??`Grok`:`Local demo AI`)}catch(e){h(e instanceof Error?e.message:`AI request failed`)}finally{f(!1)}};return(0,V.jsx)(Fu,{open:e,onOpenChange:e=>{e||(u(null),h(null),c(``)),t(e)},children:(0,V.jsxs)(Ru,{className:`max-w-lg`,children:[(0,V.jsxs)(zu,{children:[(0,V.jsxs)(Bu,{className:`flex items-center gap-2`,children:[(0,V.jsx)(Ae,{className:`size-4`}),`Edit block with AI`]}),(0,V.jsxs)(Vu,{children:[`Rewrite this block. Uses Grok when `,(0,V.jsx)(`code`,{className:`text-xs`,children:`XAI_API_KEY`}),` is set; otherwise a local demo fallback.`]})]}),(0,V.jsxs)(`div`,{className:`space-y-3`,children:[(0,V.jsxs)(`div`,{className:`rounded-lg border border-border bg-muted/40 px-3 py-2 text-sm text-muted-foreground`,children:[(0,V.jsx)(`div`,{className:`mb-1 text-[11px] font-medium uppercase tracking-wide`,children:`Original`}),(0,V.jsx)(`p`,{className:`whitespace-pre-wrap text-foreground`,children:n||`(empty)`})]}),(0,V.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:Ld.map(e=>(0,V.jsx)(v,{type:`button`,size:`sm`,variant:`outline`,disabled:d,onClick:()=>void y(e.instruction),children:e.label},e.id))}),(0,V.jsxs)(`div`,{className:`flex gap-2`,children:[(0,V.jsx)(`input`,{className:`flex h-9 min-w-0 flex-1 rounded-md border border-border bg-background px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/40`,placeholder:`Custom instruction…`,value:s,onChange:e=>c(e.target.value),onKeyDown:e=>{e.key===`Enter`&&s.trim()&&y(s.trim())}}),(0,V.jsxs)(v,{type:`button`,disabled:d||!s.trim(),onClick:()=>void y(s.trim()),children:[d?(0,V.jsx)(ge,{className:`size-4 animate-spin`}):(0,V.jsx)(Le,{className:`size-4`}),`Run`]})]}),m&&(0,V.jsx)(`p`,{className:`text-sm text-destructive`,children:m}),l!=null&&(0,V.jsxs)(`div`,{className:`space-y-2`,children:[(0,V.jsxs)(`div`,{className:`rounded-lg border border-border bg-background px-3 py-2 text-sm`,children:[(0,V.jsxs)(`div`,{className:`mb-1 flex items-center justify-between text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:[(0,V.jsx)(`span`,{children:`Suggestion`}),g&&(0,V.jsx)(`span`,{className:`normal-case`,children:g})]}),(0,V.jsx)(`p`,{className:p(`whitespace-pre-wrap text-foreground`),children:l})]}),(0,V.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,V.jsx)(v,{type:`button`,variant:`ghost`,onClick:()=>u(null),children:`Discard`}),(0,V.jsx)(v,{type:`button`,onClick:()=>{o(l),t(!1),u(null),c(``)},children:`Replace block`})]})]})]})]})})}function zd({block:e,index:t,isFocused:n,listNumber:r,pageTitle:i,pageText:a,onFocus:o,onChange:s,onTypeChange:c,onToggleCheck:l,onToggleCollapse:u,onEnter:d,onBackspaceEmpty:f,onMove:m,onDelete:h,onIndent:g,onPatch:_,onAiInsert:y,focusRequest:b,onFocusHandled:x,inputRefs:S}){let C=vd(e.type),w=(0,A.useRef)(null),T=(0,A.useRef)(null),[E,D]=(0,A.useState)(!1),[O,k]=(0,A.useState)(``),[j,M]=(0,A.useState)(0),[N,P]=(0,A.useState)({top:0,left:0}),[F,L]=(0,A.useState)(!1),[te,re]=(0,A.useState)(!1),ie=(0,A.useCallback)(t=>{w.current=t,t?S.current.set(e.id,t):S.current.delete(e.id)},[e.id,S]),oe=(0,A.useCallback)(()=>{let e=w.current;e&&(e.style.height=`0px`,e.style.height=`${Math.max(e.scrollHeight,28)}px`)},[]);(0,A.useEffect)(()=>{oe()},[e.content,e.type,oe]),(0,A.useEffect)(()=>{if(b!==e.id)return;let t=w.current;if(t){t.focus();let e=t.value.length;t.setSelectionRange(e,e)}x()},[b,e.id,x]);let se=e=>{let t=T.current;if(!t)return;let n=t.getBoundingClientRect(),r=Math.min(n.left+48,window.innerWidth-300),i=n.bottom+280>window.innerHeight?Math.max(8,n.top-280):n.bottom+4;P({top:i,left:r}),k(e),M(0),D(!0)},ce=()=>{D(!1),k(``),M(0)},le=t=>{let n=e.content,r=n.lastIndexOf(`/`),i=r>=0?n.slice(0,r):n;s(e.id,i),c(e.id,t),ce(),requestAnimationFrame(()=>{S.current.get(e.id)?.focus()})},ue=t=>{s(e.id,t),requestAnimationFrame(oe);let n=t.lastIndexOf(`/`);if(n>=0){let e=t.slice(n+1),r=t[n-1];if((n===0||r===` `||r===` -`)&&!e.includes(` -`)){se(e);return}}E&&ce()},de=t=>{if(E){let e=yd(O);if(t.key===`ArrowDown`){t.preventDefault(),M(t=>(t+1)%Math.max(e.length,1));return}if(t.key===`ArrowUp`){t.preventDefault(),M(t=>(t-1+Math.max(e.length,1))%Math.max(e.length,1));return}if(t.key===`Enter`||t.key===`Tab`){t.preventDefault();let n=e[j];n&&le(n.type);return}if(t.key===`Escape`){t.preventDefault(),ce();return}}if(t.key===`Enter`&&!t.shiftKey&&e.type!==`code`&&e.type!==`mermaid`){t.preventDefault(),d(e.id);return}if(t.key===`Backspace`){let n=t.currentTarget;if(!n.value&&n.selectionStart===0){t.preventDefault(),f(e.id);return}}t.key===`Tab`&&(t.preventDefault(),g(e.id,t.shiftKey?-1:1)),t.key===`ArrowUp`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),m(e.id,`up`)),t.key===`ArrowDown`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),m(e.id,`down`))},R={paddingLeft:`${(e.indent??0)*1.5}rem`},fe=e.type!==`divider`&&e.type!==`ai`&&e.type!==`mermaid`;if(e.type===`divider`)return(0,V.jsxs)(`div`,{ref:T,className:`group relative flex items-center gap-1 py-2`,style:R,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),children:[(0,V.jsx)(Bd,{visible:F||n,canAiEdit:!1,onAdd:()=>d(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>c(e.id,t),onAiEdit:()=>re(!0)}),(0,V.jsx)(`hr`,{className:`w-full border-0 border-t border-border`})]});if(e.type===`ai`)return(0,V.jsxs)(`div`,{ref:T,className:`group relative py-1`,style:R,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),children:[(0,V.jsx)(Bd,{visible:F||n,canAiEdit:!1,onAdd:()=>d(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>c(e.id,t),onAiEdit:()=>void 0}),(0,V.jsx)(`div`,{className:`pl-1`,children:(0,V.jsx)(Id,{content:e.content,aiOutput:e.aiOutput,aiError:e.aiError,pageTitle:i,pageText:a,onChangePrompt:t=>s(e.id,t),onResult:({output:t,blocks:n,error:r})=>{_(e.id,{aiOutput:t,aiError:r}),n?.length&&y(e.id,n)}})})]});if(e.type===`mermaid`){let t=e.showSource??!e.content.trim();return(0,V.jsxs)(`div`,{ref:T,className:`group relative py-1`,style:R,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),children:[(0,V.jsx)(Bd,{visible:F||n,canAiEdit:!1,onAdd:()=>d(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>c(e.id,t),onAiEdit:()=>void 0}),(0,V.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border bg-muted/20 p-3`,children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,V.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:`Mermaid`}),(0,V.jsx)(v,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 text-muted-foreground`,onClick:()=>_(e.id,{showSource:!t}),children:t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(ae,{className:`size-3.5`}),` Preview`]}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(ne,{className:`size-3.5`}),` Edit source`]})})]}),t?(0,V.jsx)(`textarea`,{ref:ie,value:e.content,onChange:e=>ue(e.target.value),onFocus:()=>o(e.id),onKeyDown:de,placeholder:C.placeholder,rows:Math.max(4,e.content.split(` -`).length),spellCheck:!1,className:`w-full resize-y rounded-md border border-border bg-background px-3 py-2 font-mono text-sm leading-relaxed text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/40`}):(0,V.jsx)(Cd,{source:e.content})]}),E&&(0,V.jsx)(bd,{query:O,selectedIndex:j,onSelect:le,onHover:M,position:N})]})}let pe=p(`block w-full resize-none overflow-hidden border-0 bg-background p-0 text-foreground shadow-none outline-none ring-0 focus:outline-none focus:ring-0`,`placeholder:text-muted-foreground/60`,e.type===`paragraph`&&`text-base leading-relaxed`,e.type===`heading1`&&`text-3xl font-semibold leading-tight tracking-tight`,e.type===`heading2`&&`text-2xl font-semibold leading-tight tracking-tight`,e.type===`heading3`&&`text-xl font-semibold leading-snug tracking-tight`,(e.type===`bullet`||e.type===`numbered`)&&`text-base leading-relaxed`,e.type===`todo`&&p(`text-base leading-relaxed`,e.checked&&`text-muted-foreground line-through`),e.type===`toggle`&&`text-base font-medium leading-relaxed`,e.type===`quote`&&`text-base leading-relaxed text-muted-foreground`,e.type===`callout`&&`text-base leading-relaxed`,e.type===`code`&&`min-h-16 font-mono text-sm leading-relaxed`);return(0,V.jsxs)(`div`,{ref:T,className:p(`group relative flex items-start gap-1 rounded-md py-0.5`,n&&`bg-muted/40`),style:R,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),children:[(0,V.jsx)(Bd,{visible:F||n,canAiEdit:fe,onAdd:()=>d(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>c(e.id,t),onAiEdit:()=>re(!0)}),(0,V.jsxs)(`div`,{className:p(`flex min-w-0 flex-1 items-start gap-2 rounded-md px-1 py-1`,e.type===`callout`&&`border border-border bg-muted/50 px-3 py-2.5`,e.type===`quote`&&`border-l-2 border-foreground/25 pl-3`,e.type===`code`&&`border border-border bg-muted/60 px-3 py-2.5`),children:[e.type===`bullet`&&(0,V.jsx)(`span`,{className:`mt-2.5 size-1.5 shrink-0 rounded-full bg-foreground/80`}),e.type===`numbered`&&(0,V.jsxs)(`span`,{className:`mt-1 w-5 shrink-0 text-right text-sm tabular-nums text-muted-foreground`,children:[r??t+1,`.`]}),e.type===`todo`&&(0,V.jsx)(`button`,{type:`button`,className:p(`mt-1.5 flex size-4 shrink-0 items-center justify-center rounded border transition-colors`,e.checked?`border-primary bg-primary text-primary-foreground`:`border-border bg-background hover:border-foreground/40`),onClick:()=>l(e.id),"aria-label":e.checked?`Mark incomplete`:`Mark complete`,children:e.checked&&(0,V.jsx)(ee,{className:`size-3`,strokeWidth:3})}),e.type===`toggle`&&(0,V.jsx)(`button`,{type:`button`,className:`mt-1 flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted`,onClick:()=>u(e.id),"aria-label":e.collapsed?`Expand`:`Collapse`,children:(0,V.jsx)(I,{className:p(`size-4 text-muted-foreground transition-transform duration-150`,!e.collapsed&&`rotate-90`)})}),e.type===`callout`&&(0,V.jsx)(`span`,{className:`mt-1 shrink-0 text-base leading-none`,"aria-hidden":!0,children:`💡`}),(0,V.jsx)(`textarea`,{ref:ie,value:e.content,onChange:e=>ue(e.target.value),onFocus:()=>o(e.id),onKeyDown:de,placeholder:C.placeholder,rows:1,spellCheck:e.type!==`code`,className:pe})]}),E&&(0,V.jsx)(bd,{query:O,selectedIndex:j,onSelect:le,onHover:M,position:N}),fe&&(0,V.jsx)(Rd,{open:te,onOpenChange:re,blockText:e.content,blockType:e.type,pageTitle:i,pageText:a,onApply:t=>s(e.id,t)})]})}function Bd({visible:e,canAiEdit:t,onAdd:n,onMoveUp:r,onMoveDown:i,onDelete:a,onTypeChange:o,onAiEdit:s}){return(0,V.jsxs)(`div`,{className:p(`absolute -left-12 top-1 flex items-center gap-0.5 opacity-0 transition-opacity max-sm:-left-10`,e&&`opacity-100`),children:[(0,V.jsx)(v,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`text-muted-foreground`,onClick:n,"aria-label":`Add block below`,children:(0,V.jsx)(Te,{className:`size-3.5`})}),(0,V.jsxs)(eu,{children:[(0,V.jsx)(tu,{asChild:!0,children:(0,V.jsx)(v,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`text-muted-foreground`,"aria-label":`Block menu`,children:(0,V.jsx)(ce,{className:`size-3.5`})})}),(0,V.jsxs)(au,{align:`start`,className:`w-48`,children:[(0,V.jsx)(ou,{children:`Block`}),t&&(0,V.jsxs)(Q,{onClick:s,children:[(0,V.jsx)(Ae,{className:`size-4`}),` Edit with AI`]}),(0,V.jsxs)(Q,{onClick:r,children:[(0,V.jsx)(P,{className:`size-4`}),` Move up`]}),(0,V.jsxs)(Q,{onClick:i,children:[(0,V.jsx)(N,{className:`size-4`}),` Move down`]}),(0,V.jsxs)(nu,{children:[(0,V.jsxs)(ru,{children:[(0,V.jsx)(ie,{className:`size-4`}),` Turn into`]}),(0,V.jsx)(iu,{className:`max-h-64 overflow-y-auto`,children:_d.map(e=>{let t=e.icon;return(0,V.jsxs)(Q,{onClick:()=>o(e.type),children:[(0,V.jsx)(t,{className:`size-4`}),` `,e.label]},e.type)})})]}),(0,V.jsx)(su,{}),(0,V.jsxs)(Q,{className:`text-destructive focus:text-destructive`,onClick:a,children:[(0,V.jsx)(Fe,{className:`size-4`}),` Delete`]})]})]})]})}function Vd(e){return e.blocks.filter(e=>e.type!==`ai`&&e.type!==`divider`).map(e=>`${e.type===`heading1`?`# `:e.type===`heading2`?`## `:e.type===`heading3`?`### `:e.type===`bullet`?`- `:e.type===`numbered`?`1. `:e.type===`todo`?e.checked?`[x] `:`[ ] `:e.type===`quote`?`> `:(e.type===`code`||e.type,``)}${e.content}`.trim()).filter(Boolean).join(` -`)}function Hd({page:e}){let t=z(e=>e.updatePage),n=z(e=>e.updateBlock),r=z(e=>e.insertBlock),i=z(e=>e.deleteBlock),a=z(e=>e.changeBlockType),o=z(e=>e.moveBlock),s=z(e=>e.deletePage),c=z(e=>e.duplicatePage),l=z(e=>e.createPage),u=z(e=>e.setBlocks),[d,f]=(0,A.useState)(null),[m,g]=(0,A.useState)(null),_=(0,A.useRef)(new Map),y=(0,A.useRef)(null),b=(0,A.useMemo)(()=>Vd(e),[e]),x=(0,A.useMemo)(()=>{let t=new Map,n=0;for(let r of e.blocks)r.type===`numbered`?(n+=1,t.set(r.id,n)):n=0;return t},[e.blocks]);(0,A.useEffect)(()=>{let e=y.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[e.title]);let S=(0,A.useCallback)(t=>{let n=r(e.id,t,`paragraph`,``);g(n),f(n)},[r,e.id]),C=(0,A.useCallback)(t=>{let n=e.blocks.findIndex(e=>e.id===t);if(n<0)return;let r=e.blocks[n-1];i(e.id,t),r&&(g(r.id),f(r.id))},[i,e.blocks,e.id]),w=(0,A.useCallback)((t,r)=>{let i=e.blocks.find(e=>e.id===t);if(!i)return;let a=Math.max(0,Math.min(4,(i.indent??0)+r));n(e.id,t,{indent:a})},[e.blocks,e.id,n]),T=(0,A.useCallback)((t,n)=>{let r=e.blocks.findIndex(e=>e.id===t);if(r<0||n.length===0)return;let i=n.map(e=>({id:h(`b`),type:e.type,content:e.content,indent:0,checked:e.type!==`todo`&&void 0,showSource:e.type!==`mermaid`&&void 0})),a=[...e.blocks];a.splice(r+1,0,...i),u(e.id,a),g(i[0].id)},[e.blocks,e.id,u]),E=e.cover?$e[e.cover]:null;return(0,V.jsxs)(`div`,{className:`mx-auto w-full max-w-3xl px-4 pb-32 pt-4 sm:px-12 sm:pt-8`,children:[E?(0,V.jsxs)(`div`,{className:`group/cover relative -mx-4 mb-2 h-36 overflow-hidden rounded-xl sm:-mx-6 sm:h-44`,children:[(0,V.jsx)(`div`,{className:p(`absolute inset-0`,E.className)}),(0,V.jsx)(`div`,{className:`absolute bottom-3 right-3 opacity-0 transition-opacity group-hover/cover:opacity-100`,children:(0,V.jsx)(v,{type:`button`,size:`sm`,variant:`secondary`,className:`bg-background/90 shadow-sm backdrop-blur-sm`,onClick:()=>t(e.id,{cover:null}),children:`Remove cover`})})]}):null,(0,V.jsxs)(`div`,{className:`mb-1 flex flex-wrap items-end gap-2`,children:[(0,V.jsxs)(md,{children:[(0,V.jsx)(hd,{asChild:!0,children:(0,V.jsx)(`button`,{type:`button`,className:`flex size-16 items-center justify-center rounded-xl text-4xl transition-colors hover:bg-muted`,"aria-label":`Change page icon`,children:e.icon})}),(0,V.jsxs)(gd,{align:`start`,className:`w-72`,children:[(0,V.jsx)(`div`,{className:`mb-2 text-xs font-medium text-muted-foreground`,children:`Page icon`}),(0,V.jsx)(`div`,{className:`grid grid-cols-8 gap-1`,children:Qe.map(n=>(0,V.jsx)(`button`,{type:`button`,className:p(`flex size-8 items-center justify-center rounded-md text-lg transition-colors hover:bg-muted`,e.icon===n&&`bg-muted ring-1 ring-border`),onClick:()=>t(e.id,{icon:n}),children:n},n))})]})]}),(0,V.jsxs)(`div`,{className:`mb-2 flex flex-1 flex-wrap items-center gap-1`,children:[(0,V.jsxs)(v,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,onClick:()=>t(e.id,{favorite:!e.favorite}),children:[(0,V.jsx)(Me,{className:p(`size-3.5`,e.favorite&&`fill-amber-400 text-amber-500`)}),e.favorite?`Unfavorite`:`Favorite`]}),(0,V.jsxs)(v,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,onClick:()=>{let t=e.blocks[e.blocks.length-1],n=r(e.id,t?.id??null,`ai`,``);g(n)},children:[(0,V.jsx)(Ae,{className:`size-3.5`}),`AI block`]}),(0,V.jsxs)(eu,{children:[(0,V.jsx)(tu,{asChild:!0,children:(0,V.jsxs)(v,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,children:[(0,V.jsx)(R,{className:`size-3.5`}),`Cover`]})}),(0,V.jsxs)(au,{align:`start`,children:[Object.entries($e).map(([n,r])=>(0,V.jsxs)(Q,{onClick:()=>t(e.id,{cover:n}),children:[(0,V.jsx)(`span`,{className:p(`mr-2 size-4 rounded`,r.className)}),r.label]},n)),e.cover&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(su,{}),(0,V.jsx)(Q,{onClick:()=>t(e.id,{cover:null}),children:`Remove cover`})]})]})]}),(0,V.jsxs)(eu,{children:[(0,V.jsx)(tu,{asChild:!0,children:(0,V.jsx)(v,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,children:(0,V.jsx)(ie,{className:`size-3.5`})})}),(0,V.jsxs)(au,{align:`start`,children:[(0,V.jsxs)(Q,{onClick:()=>l({parentId:e.id}),children:[(0,V.jsx)(Te,{className:`size-4`}),` Add sub-page`]}),(0,V.jsxs)(Q,{onClick:()=>c(e.id),children:[(0,V.jsx)(re,{className:`size-4`}),` Duplicate`]}),(0,V.jsx)(su,{}),(0,V.jsxs)(Q,{className:`text-destructive focus:text-destructive`,onClick:()=>s(e.id),children:[(0,V.jsx)(Fe,{className:`size-4`}),` Move to trash`]})]})]})]})]}),(0,V.jsx)(`textarea`,{ref:y,value:e.title,onChange:n=>t(e.id,{title:n.target.value}),placeholder:`Untitled`,rows:1,className:`mb-4 w-full resize-none overflow-hidden bg-transparent text-4xl font-bold tracking-tight text-foreground outline-none placeholder:text-muted-foreground/50`,onKeyDown:t=>{if(t.key===`Enter`){t.preventDefault();let n=e.blocks[0];n&&(g(n.id),f(n.id))}}}),(0,V.jsx)(`div`,{className:`relative space-y-0.5 pl-10 sm:pl-12`,children:e.blocks.map((t,r)=>(0,V.jsx)(zd,{pageId:e.id,block:t,index:r,isFocused:d===t.id,listNumber:x.get(t.id),pageTitle:e.title,pageText:b,onFocus:f,onChange:(t,r)=>n(e.id,t,{content:r}),onTypeChange:(t,n)=>a(e.id,t,n),onToggleCheck:t=>{let r=e.blocks.find(e=>e.id===t);r&&n(e.id,t,{checked:!r.checked})},onToggleCollapse:t=>{let r=e.blocks.find(e=>e.id===t);r&&n(e.id,t,{collapsed:!r.collapsed})},onEnter:S,onBackspaceEmpty:C,onMove:(t,n)=>o(e.id,t,n),onDelete:t=>i(e.id,t),onIndent:w,onPatch:(t,r)=>n(e.id,t,r),onAiInsert:T,focusRequest:m,onFocusHandled:()=>g(null),inputRefs:_},t.id))}),(0,V.jsx)(`button`,{type:`button`,className:`mt-2 ml-10 min-h-16 w-[calc(100%-2.5rem)] cursor-text rounded-md sm:ml-12 sm:w-[calc(100%-3rem)]`,"aria-label":`Add block at end`,onClick:()=>{let t=e.blocks[e.blocks.length-1];if(t&&t.type===`paragraph`&&!t.content)g(t.id),f(t.id);else{let n=r(e.id,t?.id??null,`paragraph`,``);g(n),f(n)}}})]})}var Ud=1,Wd=.9,Gd=.8,Kd=.17,qd=.1,Jd=.999,Yd=.9999,Xd=.99,Zd=/[\\\/_+.#"@\[\(\{&]/,Qd=/[\\\/_+.#"@\[\(\{&]/g,$d=/[\s-]/,ef=/[\s-]/g;function tf(e,t,n,r,i,a,o){if(a===t.length)return i===e.length?Ud:Xd;var s=`${i},${a}`;if(o[s]!==void 0)return o[s];for(var c=r.charAt(a),l=n.indexOf(c,i),u=0,d,f,p,m;l>=0;)d=tf(e,t,n,r,l+1,a+1,o),d>u&&(l===i?d*=Ud:Zd.test(e.charAt(l-1))?(d*=Gd,p=e.slice(i,l-1).match(Qd),p&&i>0&&(d*=Jd**+p.length)):$d.test(e.charAt(l-1))?(d*=Wd,m=e.slice(i,l-1).match(ef),m&&i>0&&(d*=Jd**+m.length)):(d*=Kd,i>0&&(d*=Jd**+(l-i))),e.charAt(l)!==t.charAt(a)&&(d*=Yd)),(dd&&(d=f*qd)),d>u&&(u=d),l=n.indexOf(c,l+1);return o[s]=u,u}function nf(e){return e.toLowerCase().replace(ef,` `)}function rf(e,t,n){return e=n&&n.length>0?`${e+` `+n.join(` `)}`:e,tf(e,t,nf(e),nf(t),0,0,{})}var af=`[cmdk-group=""]`,of=`[cmdk-group-items=""]`,sf=`[cmdk-group-heading=""]`,cf=`[cmdk-item=""]`,lf=`${cf}:not([aria-disabled="true"])`,uf=`cmdk-item-select`,df=`data-value`,ff=(e,t,n)=>rf(e,t,n),pf=A.createContext(void 0),mf=()=>A.useContext(pf),hf=A.createContext(void 0),gf=()=>A.useContext(hf),_f=A.createContext(void 0),vf=A.forwardRef((e,t)=>{let n=Mf(()=>({search:``,value:e.value??e.defaultValue??``,selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}})),r=Mf(()=>new Set),i=Mf(()=>new Map),a=Mf(()=>new Map),o=Mf(()=>new Set),s=Af(e),{label:c,children:l,value:u,onValueChange:d,filter:f,shouldFilter:p,loop:m,disablePointerSelection:h=!1,vimBindings:g=!0,..._}=e,v=K(),y=K(),b=K(),x=A.useRef(null),S=Ff();jf(()=>{if(u!==void 0){let e=u.trim();n.current.value=e,C.emit()}},[u]),jf(()=>{S(6,k)},[]);let C=A.useMemo(()=>({subscribe:e=>(o.current.add(e),()=>o.current.delete(e)),snapshot:()=>n.current,setState:(e,t,r)=>{var i,a,o;if(!Object.is(n.current[e],t)){if(n.current[e]=t,e===`search`)O(),E(),S(1,D);else if(e===`value`){if(document.activeElement.hasAttribute(`cmdk-input`)||document.activeElement.hasAttribute(`cmdk-root`)){let e=document.getElementById(b);e?e.focus():(i=document.getElementById(v))==null||i.focus()}if(S(7,()=>{n.current.selectedItemId=j()?.id,C.emit()}),r||S(5,k),s.current?.value!==void 0){let e=t??``;(o=(a=s.current).onValueChange)==null||o.call(a,e);return}}C.emit()}},emit:()=>{o.current.forEach(e=>e())}}),[]),w=A.useMemo(()=>({value:(e,t,r)=>{t!==a.current.get(e)?.value&&(a.current.set(e,{value:t,keywords:r}),n.current.filtered.items.set(e,T(t,r)),S(2,()=>{E(),C.emit()}))},item:(e,t)=>(r.current.add(e),t&&(i.current.has(t)?i.current.get(t).add(e):i.current.set(t,new Set([e]))),S(3,()=>{O(),E(),n.current.value||D(),C.emit()}),()=>{a.current.delete(e),r.current.delete(e),n.current.filtered.items.delete(e);let t=j();S(4,()=>{O(),t?.getAttribute(`id`)===e&&D(),C.emit()})}),group:e=>(i.current.has(e)||i.current.set(e,new Set),()=>{a.current.delete(e),i.current.delete(e)}),filter:()=>s.current.shouldFilter,label:c||e[`aria-label`],getDisablePointerSelection:()=>s.current.disablePointerSelection,listId:v,inputId:b,labelId:y,listInnerRef:x}),[]);function T(e,t){let r=s.current?.filter??ff;return e?r(e,n.current.search,t):0}function E(){if(!n.current.search||s.current.shouldFilter===!1)return;let e=n.current.filtered.items,t=[];n.current.filtered.groups.forEach(n=>{let r=i.current.get(n),a=0;r.forEach(t=>{let n=e.get(t);a=Math.max(n,a)}),t.push([n,a])});let r=x.current;M().sort((t,n)=>{let r=t.getAttribute(`id`),i=n.getAttribute(`id`);return(e.get(i)??0)-(e.get(r)??0)}).forEach(e=>{let t=e.closest(of);t?t.appendChild(e.parentElement===t?e:e.closest(`${of} > *`)):r.appendChild(e.parentElement===r?e:e.closest(`${of} > *`))}),t.sort((e,t)=>t[1]-e[1]).forEach(e=>{let t=x.current?.querySelector(`${af}[${df}="${encodeURIComponent(e[0])}"]`);t?.parentElement.appendChild(t)})}function D(){let e=M().find(e=>e.getAttribute(`aria-disabled`)!==`true`)?.getAttribute(df);C.setState(`value`,e||void 0)}function O(){if(!n.current.search||s.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let e=0;for(let t of r.current){let r=T(a.current.get(t)?.value??``,a.current.get(t)?.keywords??[]);n.current.filtered.items.set(t,r),r>0&&e++}for(let[e,t]of i.current)for(let r of t)if(n.current.filtered.items.get(r)>0){n.current.filtered.groups.add(e);break}n.current.filtered.count=e}function k(){var e;let t=j();t&&(t.parentElement?.firstChild===t&&((e=t.closest(af)?.querySelector(sf))==null||e.scrollIntoView({block:`nearest`})),t.scrollIntoView({block:`nearest`}))}function j(){return x.current?.querySelector(`${cf}[aria-selected="true"]`)}function M(){return Array.from(x.current?.querySelectorAll(lf)||[])}function N(e){let t=M()[e];t&&C.setState(`value`,t.getAttribute(df))}function P(e){var t;let n=j(),r=M(),i=r.findIndex(e=>e===n),a=r[i+e];(t=s.current)!=null&&t.loop&&(a=i+e<0?r[r.length-1]:i+e===r.length?r[0]:r[i+e]),a&&C.setState(`value`,a.getAttribute(df))}function ee(e){let t=j()?.closest(af),n;for(;t&&!n;)t=e>0?Of(t,af):kf(t,af),n=t?.querySelector(lf);n?C.setState(`value`,n.getAttribute(df)):P(e)}let F=()=>N(M().length-1),I=e=>{e.preventDefault(),e.metaKey?F():e.altKey?ee(1):P(1)},L=e=>{e.preventDefault(),e.metaKey?N(0):e.altKey?ee(-1):P(-1)};return A.createElement(H.div,{ref:t,tabIndex:-1,..._,"cmdk-root":``,onKeyDown:e=>{var t;(t=_.onKeyDown)==null||t.call(_,e);let n=e.nativeEvent.isComposing||e.keyCode===229;if(!(e.defaultPrevented||n))switch(e.key){case`n`:case`j`:g&&e.ctrlKey&&I(e);break;case`ArrowDown`:I(e);break;case`p`:case`k`:g&&e.ctrlKey&&L(e);break;case`ArrowUp`:L(e);break;case`Home`:e.preventDefault(),N(0);break;case`End`:e.preventDefault(),F();break;case`Enter`:{e.preventDefault();let t=j();if(t){let e=new Event(uf);t.dispatchEvent(e)}}}}},A.createElement(`label`,{"cmdk-label":``,htmlFor:w.inputId,id:w.labelId,style:Rf},c),Lf(e,e=>A.createElement(hf.Provider,{value:C},A.createElement(pf.Provider,{value:w},e))))}),yf=A.forwardRef((e,t)=>{let n=K(),r=A.useRef(null),i=A.useContext(_f),a=mf(),o=Af(e),s=o.current?.forceMount??i?.forceMount;jf(()=>{if(!s)return a.item(n,i?.id)},[s]);let c=Pf(n,r,[e.value,e.children,r],e.keywords),l=gf(),u=Nf(e=>e.value&&e.value===c.current),d=Nf(e=>s||a.filter()===!1?!0:!e.search||e.filtered.items.get(n)>0);A.useEffect(()=>{let t=r.current;if(!(!t||e.disabled))return t.addEventListener(uf,f),()=>t.removeEventListener(uf,f)},[d,e.onSelect,e.disabled]);function f(){var e,t;p(),(t=(e=o.current).onSelect)==null||t.call(e,c.current)}function p(){l.setState(`value`,c.current,!0)}if(!d)return null;let{disabled:m,value:h,onSelect:g,forceMount:v,keywords:y,...b}=e;return A.createElement(H.div,{ref:_(r,t),...b,id:n,"cmdk-item":``,role:`option`,"aria-disabled":!!m,"aria-selected":!!u,"data-disabled":!!m,"data-selected":!!u,onPointerMove:m||a.getDisablePointerSelection()?void 0:p,onClick:m?void 0:f},e.children)}),bf=A.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...a}=e,o=K(),s=A.useRef(null),c=A.useRef(null),l=K(),u=mf(),d=Nf(e=>i||u.filter()===!1?!0:!e.search||e.filtered.groups.has(o));jf(()=>u.group(o),[]),Pf(o,s,[e.value,e.heading,c]);let f=A.useMemo(()=>({id:o,forceMount:i}),[i]);return A.createElement(H.div,{ref:_(s,t),...a,"cmdk-group":``,role:`presentation`,hidden:!d||void 0},n&&A.createElement(`div`,{ref:c,"cmdk-group-heading":``,"aria-hidden":!0,id:l},n),Lf(e,e=>A.createElement(`div`,{"cmdk-group-items":``,role:`group`,"aria-labelledby":n?l:void 0},A.createElement(_f.Provider,{value:f},e))))}),xf=A.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=A.useRef(null),a=Nf(e=>!e.search);return!n&&!a?null:A.createElement(H.div,{ref:_(i,t),...r,"cmdk-separator":``,role:`separator`})}),Sf=A.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,a=gf(),o=Nf(e=>e.search),s=Nf(e=>e.selectedItemId),c=mf();return A.useEffect(()=>{e.value!=null&&a.setState(`search`,e.value)},[e.value]),A.createElement(H.input,{ref:t,...r,"cmdk-input":``,autoComplete:`off`,autoCorrect:`off`,spellCheck:!1,"aria-autocomplete":`list`,role:`combobox`,"aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":s,id:c.inputId,type:`text`,value:i?e.value:o,onChange:e=>{i||a.setState(`search`,e.target.value),n?.(e.target.value)}})}),Cf=A.forwardRef((e,t)=>{let{children:n,label:r=`Suggestions`,...i}=e,a=A.useRef(null),o=A.useRef(null),s=Nf(e=>e.selectedItemId),c=mf();return A.useEffect(()=>{if(o.current&&a.current){let e=o.current,t=a.current,n,r=new ResizeObserver(()=>{n=requestAnimationFrame(()=>{let n=e.offsetHeight;t.style.setProperty(`--cmdk-list-height`,n.toFixed(1)+`px`)})});return r.observe(e),()=>{cancelAnimationFrame(n),r.unobserve(e)}}},[]),A.createElement(H.div,{ref:_(a,t),...i,"cmdk-list":``,role:`listbox`,tabIndex:-1,"aria-activedescendant":s,"aria-label":r,id:c.listId},Lf(e,e=>A.createElement(`div`,{ref:_(o,c.listInnerRef),"cmdk-list-sizer":``},e)))}),wf=A.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:a,container:o,...s}=e;return A.createElement(hu,{open:n,onOpenChange:r},A.createElement(yu,{container:o},A.createElement(xu,{"cmdk-overlay":``,className:i}),A.createElement(Tu,{"aria-label":e.label,"cmdk-dialog":``,className:a},A.createElement(vf,{ref:t,...s}))))}),Tf=A.forwardRef((e,t)=>Nf(e=>e.filtered.count===0)?A.createElement(H.div,{ref:t,...e,"cmdk-empty":``,role:`presentation`}):null),Ef=A.forwardRef((e,t)=>{let{progress:n,children:r,label:i=`Loading...`,...a}=e;return A.createElement(H.div,{ref:t,...a,"cmdk-loading":``,role:`progressbar`,"aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Lf(e,e=>A.createElement(`div`,{"aria-hidden":!0},e)))}),Df=Object.assign(vf,{List:Cf,Item:yf,Input:Sf,Group:bf,Separator:xf,Dialog:wf,Empty:Tf,Loading:Ef});function Of(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function kf(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Af(e){let t=A.useRef(e);return jf(()=>{t.current=e}),t}var jf=typeof window>`u`?A.useEffect:A.useLayoutEffect;function Mf(e){let t=A.useRef();return t.current===void 0&&(t.current=e()),t}function Nf(e){let t=gf(),n=()=>e(t.snapshot());return A.useSyncExternalStore(t.subscribe,n,n)}function Pf(e,t,n,r=[]){let i=A.useRef(),a=mf();return jf(()=>{var o;let s=(()=>{for(let e of n){if(typeof e==`string`)return e.trim();if(typeof e==`object`&&`current`in e)return e.current?e.current.textContent?.trim():i.current}})(),c=r.map(e=>e.trim());a.value(e,s,c),(o=t.current)==null||o.setAttribute(df,s),i.current=s}),i}var Ff=()=>{let[e,t]=A.useState(),n=Mf(()=>new Map);return jf(()=>{n.current.forEach(e=>e()),n.current=new Map},[e]),(e,r)=>{n.current.set(e,r),t({})}};function If(e){let t=e.type;return typeof t==`function`?t(e.props):`render`in t?t.render(e.props):e}function Lf({asChild:e,children:t},n){return e&&A.isValidElement(t)?A.cloneElement(If(t),{ref:t.ref},n(t.props.children)):n(t)}var Rf={position:`absolute`,width:`1px`,height:`1px`,padding:`0`,margin:`-1px`,overflow:`hidden`,clip:`rect(0, 0, 0, 0)`,whiteSpace:`nowrap`,borderWidth:`0`};function zf({open:e,onOpenChange:t}){let n=z(e=>e.pages),r=z(e=>e.setActivePage),i=z(e=>e.createPage),[a,o]=(0,A.useState)(``);(0,A.useEffect)(()=>{e||o(``)},[e]),(0,A.useEffect)(()=>{let n=n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()===`k`&&(n.preventDefault(),t(!e))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]);let s=(0,A.useMemo)(()=>n.filter(e=>!e.archived),[n]);return e?(0,V.jsxs)(`div`,{className:`fixed inset-0 z-[100]`,children:[(0,V.jsx)(`div`,{className:`absolute inset-0 bg-black/40`,onClick:()=>t(!1),"aria-hidden":!0}),(0,V.jsx)(`div`,{className:`absolute left-1/2 top-[18%] w-[min(560px,calc(100%-2rem))] -translate-x-1/2 overflow-hidden rounded-xl border border-border bg-popover shadow-2xl`,children:(0,V.jsxs)(Df,{className:`flex flex-col`,label:`Search pages`,shouldFilter:!0,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border px-3`,children:[(0,V.jsx)(Oe,{className:`size-4 shrink-0 text-muted-foreground`}),(0,V.jsx)(Df.Input,{value:a,onValueChange:o,placeholder:`Search pages…`,className:`h-12 w-full bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground`,autoFocus:!0}),(0,V.jsx)(`kbd`,{className:`hidden rounded border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground sm:inline`,children:`ESC`})]}),(0,V.jsxs)(Df.List,{className:`max-h-80 overflow-y-auto p-2`,children:[(0,V.jsx)(Df.Empty,{className:`py-8 text-center text-sm text-muted-foreground`,children:`No pages found`}),(0,V.jsx)(Df.Group,{heading:`Actions`,className:`[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground`,children:(0,V.jsxs)(Df.Item,{value:`new page create`,onSelect:()=>{i(),t(!1)},className:p(`flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-sm aria-selected:bg-muted`),children:[(0,V.jsx)(Te,{className:`size-4 text-muted-foreground`}),`New page`]})}),(0,V.jsx)(Df.Group,{heading:`Pages`,className:`mt-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground`,children:s.map(e=>(0,V.jsxs)(Df.Item,{value:`${e.title} ${e.icon} untitled`,onSelect:()=>{r(e.id),t(!1)},className:`flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-sm aria-selected:bg-muted`,children:[(0,V.jsx)(`span`,{className:`text-base leading-none`,children:e.icon}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-medium`,children:e.title||`Untitled`}),e.favorite&&(0,V.jsx)(Me,{className:`size-3.5 fill-amber-400 text-amber-500`}),(0,V.jsx)(se,{className:`size-3.5 text-muted-foreground`})]},e.id))})]})]})})]}):null}function Bf(e){if(!e||typeof document>`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var Vf=e=>{switch(e){case`success`:return Wf;case`info`:return Kf;case`warning`:return Gf;case`error`:return qf;default:return null}},Hf=Array(12).fill(0),Uf=({visible:e,className:t})=>A.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},A.createElement(`div`,{className:`sonner-spinner`},Hf.map((e,t)=>A.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),Wf=A.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},A.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),Gf=A.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},A.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),Kf=A.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},A.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),qf=A.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},A.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),Jf=A.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},A.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),A.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),Yf=()=>{let[e,t]=A.useState(document.hidden);return A.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},Xf=1,$=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:Xf++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0||e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],A.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(Qf(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!A.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!A.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!A.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!A.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||Xf++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Zf=(e,t)=>{let n=t?.id||Xf++;return $.addToast({title:e,...t,id:n}),n},Qf=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`;Object.assign(Zf,{success:$.success,info:$.info,warning:$.warning,error:$.error,custom:$.custom,message:$.message,promise:$.promise,dismiss:$.dismiss,loading:$.loading},{getHistory:()=>$.toasts,getToasts:()=>$.getActiveToasts()}),Bf(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function $f(e){return e.label!==void 0}var ep=3,tp=`24px`,np=`16px`,rp=4e3,ip=356,ap=14,op=45,sp=200;function cp(...e){return e.filter(Boolean).join(` `)}function lp(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var up=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:T=`Close toast`}=e,[E,D]=A.useState(null),[O,k]=A.useState(null),[j,M]=A.useState(!1),[N,P]=A.useState(!1),[ee,F]=A.useState(!1),[I,L]=A.useState(!1),[te,ne]=A.useState(!1),[re,ie]=A.useState(0),[ae,oe]=A.useState(0),se=A.useRef(n.duration||y||rp),ce=A.useRef(null),le=A.useRef(null),ue=c===0,de=c+1<=o,R=n.type,fe=n.dismissible!==!1,pe=n.className||``,me=n.descriptionClassName||``,he=A.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),ge=A.useMemo(()=>n.closeButton??p,[n.closeButton,p]),_e=A.useMemo(()=>n.duration||y||rp,[n.duration,y]),ve=A.useRef(0),ye=A.useRef(0),be=A.useRef(0),xe=A.useRef(null),[Se,Ce]=b.split(`-`),we=A.useMemo(()=>s.reduce((e,t,n)=>n>=he?e:e+t.height,0),[s,he]),Te=Yf(),Ee=n.invert||t,De=R===`loading`;ye.current=A.useMemo(()=>he*x+we,[he,we]),A.useEffect(()=>{se.current=_e},[_e]),A.useEffect(()=>{M(!0)},[]),A.useEffect(()=>{let e=le.current;if(e){let t=e.getBoundingClientRect().height;return oe(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),A.useLayoutEffect(()=>{if(!j)return;let e=le.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,oe(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[j,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let Oe=A.useCallback(()=>{P(!0),ie(ye.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},sp)},[n,d,a,ye]);A.useEffect(()=>{if(n.promise&&R===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||Te?(()=>{if(be.current{n.onAutoClose==null||n.onAutoClose.call(n,n),Oe()},se.current)),()=>clearTimeout(e)},[u,i,n,R,Te,Oe]),A.useEffect(()=>{n.delete&&(Oe(),n.onDismiss==null||n.onDismiss.call(n,n))},[Oe,n.delete]);function ke(){return w?.loading?A.createElement(`div`,{className:cp(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":R===`loading`},w.loading):A.createElement(Uf,{className:cp(C?.loader,n?.classNames?.loader),visible:R===`loading`})}let Ae=n.icon||w?.[R]||Vf(R);return A.createElement(`li`,{tabIndex:0,ref:le,className:cp(_,pe,C?.toast,n?.classNames?.toast,C?.default,C?.[R],n?.classNames?.[R]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":j,"data-promise":!!n.promise,"data-swiped":te,"data-removed":N,"data-visible":de,"data-y-position":Se,"data-x-position":Ce,"data-index":c,"data-front":ue,"data-swiping":ee,"data-dismissible":fe,"data-type":R,"data-invert":Ee,"data-swipe-out":I,"data-swipe-direction":O,"data-expanded":!!(u||S&&j),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${N?re:ye.current}px`,"--initial-height":S?`auto`:`${ae}px`,...m,...n.style},onDragEnd:()=>{F(!1),D(null),xe.current=null},onPointerDown:e=>{e.button!==2&&(De||!fe||(ce.current=new Date,ie(ye.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(F(!0),xe.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(I||!fe)return;xe.current=null;let e=Number(le.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(le.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-ce.current?.getTime(),i=E===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=op||a>.11){ie(ye.current),n.onDismiss==null||n.onDismiss.call(n,n),k(E===`x`?e>0?`right`:`left`:t>0?`down`:`up`),Oe(),L(!0);return}else{var o,s;(o=le.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=le.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`)}ne(!1),F(!1),D(null)},onPointerMove:t=>{var n,r;if(!xe.current||!fe||window.getSelection()?.toString().length>0)return;let i=t.clientY-xe.current.y,a=t.clientX-xe.current.x,o=e.swipeDirections??lp(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&D(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(E===`y`){if(o.includes(`top`)||o.includes(`bottom`))if(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)s.y=i;else{let e=i*c(i);s.y=Math.abs(e)0)s.x=a;else{let e=a*c(a);s.x=Math.abs(e)0||Math.abs(s.y)>0)&&ne(!0),(n=le.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=le.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},ge&&!n.jsx&&R!==`loading`?A.createElement(`button`,{"aria-label":T,"data-disabled":De,"data-close-button":!0,onClick:De||!fe?()=>{}:()=>{Oe(),n.onDismiss==null||n.onDismiss.call(n,n)},className:cp(C?.closeButton,n?.classNames?.closeButton)},w?.close??Jf):null,(R||n.icon||n.promise)&&n.icon!==null&&(w?.[R]!==null||n.icon)?A.createElement(`div`,{"data-icon":``,className:cp(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||ke():null,n.type===`loading`?null:Ae):null,A.createElement(`div`,{"data-content":``,className:cp(C?.content,n?.classNames?.content)},A.createElement(`div`,{"data-title":``,className:cp(C?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?A.createElement(`div`,{"data-description":``,className:cp(v,me,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),A.isValidElement(n.cancel)?n.cancel:n.cancel&&$f(n.cancel)?A.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{$f(n.cancel)&&fe&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),Oe())},className:cp(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,A.isValidElement(n.action)?n.action:n.action&&$f(n.action)?A.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{$f(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&Oe())},className:cp(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function dp(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function fp(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?np:tp;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var pp=A.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=ep,toastOptions:g,dir:_=dp(),gap:v=ap,icons:y,containerAriaLabel:b=`Notifications`}=e,[x,S]=A.useState([]),C=A.useMemo(()=>n?x.filter(e=>e.toasterId===n):x.filter(e=>!e.toasterId),[x,n]),w=A.useMemo(()=>Array.from(new Set([i].concat(C.filter(e=>e.position).map(e=>e.position)))),[C,i]),[T,E]=A.useState([]),[D,O]=A.useState(!1),[k,j]=A.useState(!1),[M,N]=A.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),P=A.useRef(null),ee=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),F=A.useRef(null),I=A.useRef(!1),L=A.useCallback(e=>{S(t=>(t.find(t=>t.id===e.id)?.delete||$.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return A.useEffect(()=>$.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{ht.flushSync(()=>{S(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[x]),A.useEffect(()=>{if(d!==`system`){N(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?N(`dark`):N(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{N(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{N(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),A.useEffect(()=>{x.length<=1&&O(!1)},[x]),A.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;O(!0),(t=P.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===P.current||P.current?.contains(document.activeElement))&&O(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),A.useEffect(()=>{if(P.current)return()=>{F.current&&(F.current.focus({preventScroll:!0}),F.current=null,I.current=!1)}},[P.current]),A.createElement(`section`,{ref:t,"aria-label":`${b} ${ee}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},w.map((t,n)=>{let[i,a]=t.split(`-`);return C.length?A.createElement(`ol`,{key:t,dir:_===`auto`?dp():_,tabIndex:-1,ref:P,className:c,"data-sonner-toaster":!0,"data-sonner-theme":M,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${T[0]?.height||0}px`,"--width":`${ip}px`,"--gap":`${v}px`,...m,...fp(l,u)},onBlur:e=>{I.current&&!e.currentTarget.contains(e.relatedTarget)&&(I.current=!1,F.current&&=(F.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||I.current||(I.current=!0,F.current=e.relatedTarget)},onMouseEnter:()=>O(!0),onMouseMove:()=>O(!0),onMouseLeave:()=>{k||O(!1)},onDragEnd:()=>O(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||j(!0)},onPointerUp:()=>j(!1)},C.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>A.createElement(up,{key:n.id,icons:y,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:k,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:L,toasts:C.filter(e=>e.position==n.position),heights:T.filter(e=>e.position==n.position),setHeights:E,expandByDefault:o,gap:v,expanded:D,swipeDirections:e.swipeDirections}))):null}))}),mp=Nd({type:`function`}).client(async({next:e})=>{let{getBearerToken:t}=await u(async()=>{let{getBearerToken:e}=await import(`./client-8boibB1R.js`).then(e=>e.n);return{getBearerToken:e}},__vite__mapDeps([24,2,3]));return e({sendContext:{bearerToken:t()??void 0}})}),hp=Od({method:`GET`}).middleware([mp]).handler(c(`e3fb77d67dfdadad5d019581d79338a7f7cf2e42797c44110574e289b39fd293`)),gp=Od({method:`POST`}).middleware([mp]).handler(c(`7bd9976b9723bbefb2399d41723684e8ed7d3bfcf4f814066bb422e47b4bb658`)),_p=null,vp=!1,yp=!1,bp=!1,xp=!1,Sp=null;function Cp(){let e=z.getState();return{name:e.name,theme:e.theme,activePageId:e.activePageId,sidebarOpen:e.sidebarOpen,pages:e.pages}}function wp(){Sp?.(),Sp=z.subscribe((e,t)=>{!bp||!xp||e.name===t.name&&e.theme===t.theme&&e.activePageId===t.activePageId&&e.sidebarOpen===t.sidebarOpen&&e.pages===t.pages||Ep()})}async function Tp(){try{let e=await hp();return xp=!1,z.setState({name:e.name,theme:e.theme,activePageId:e.activePageId,sidebarOpen:e.sidebarOpen,pages:e.pages,hydrated:!0,syncStatus:`saved`,storageMode:`database`}),bp=!0,xp=!0,wp(),e.source}catch{return bp=!1,xp=!1,Sp?.(),Sp=null,z.setState({storageMode:`local`,syncStatus:`local`,hydrated:!0}),`error`}}function Ep(){!bp||!xp||(z.setState({syncStatus:`pending`}),_p&&clearTimeout(_p),_p=setTimeout(()=>{Dp()},600))}async function Dp(){if(bp){if(vp){yp=!0;return}vp=!0,z.setState({syncStatus:`saving`});try{await gp({data:Cp()}),z.setState({syncStatus:`saved`})}catch{z.setState({syncStatus:`error`})}finally{vp=!1,yp&&(yp=!1,Ep())}}}async function Op(){if(_p&&=(clearTimeout(_p),null),bp)try{await gp({data:Cp()}),z.setState({syncStatus:`saved`})}catch{z.setState({syncStatus:`error`})}}function kp(){bp=!1,xp=!1,Sp?.(),Sp=null,z.setState({storageMode:`local`,syncStatus:`local`,hydrated:!0})}function Ap(){let e=z(e=>e.pages),t=z(e=>e.activePageId),n=z(e=>e.sidebarOpen),r=z(e=>e.theme),a=z(e=>e.hydrated),o=z(e=>e.storageMode),s=z(e=>e.syncStatus),c=z(e=>e.setSidebarOpen),l=z(e=>e.toggleSidebar),u=z(e=>e.setActivePage),d=z(e=>e.updatePage),f=z(e=>e.createPage),m=z(e=>e.setHydrated),{user:h,isPending:_}=g(),[y,b]=(0,A.useState)(!1),[x,S]=(0,A.useState)(!1),[C,w]=(0,A.useState)(!1);(0,A.useEffect)(()=>{let e=z.persist.onFinishHydration(()=>{h||m(!0)});return z.persist.hasHydrated()&&!h&&m(!0),e},[m,h]),(0,A.useEffect)(()=>{if(_)return;let e=!1;async function t(){h?(w(!0),await Tp(),e||w(!1)):(kp(),z.persist.hasHydrated()&&m(!0))}return t(),()=>{e=!0}},[h,_,m]),(0,A.useEffect)(()=>{let e=()=>{o===`database`&&Op()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[o]),(0,A.useEffect)(()=>{let e=document.documentElement;r===`dark`?e.classList.add(`dark`):e.classList.remove(`dark`)},[r]);let T=e.find(e=>e.id===t&&!e.archived),E=(()=>{if(!T)return[];let t=[],n=T,r=new Map(e.map(e=>[e.id,e]));for(;n;)t.unshift(n),n=n.parentId?r.get(n.parentId):void 0;return t})();return!a||_||C?(0,V.jsx)(`div`,{className:`flex h-dvh items-center justify-center bg-background text-muted-foreground`,children:(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-3`,children:[(0,V.jsx)(`div`,{className:`size-8 animate-pulse rounded-lg bg-muted`}),(0,V.jsx)(`p`,{className:`text-sm`,children:C?`Loading workspace from database…`:`Loading workspace…`})]})}):(0,V.jsx)(aa,{delayDuration:300,children:(0,V.jsxs)(`div`,{className:`flex h-dvh overflow-hidden bg-background text-foreground`,children:[(0,V.jsx)(`div`,{className:p(`hidden h-full shrink-0 transition-[width,opacity] duration-200 md:block`,n?`w-[260px] opacity-100`:`w-0 opacity-0 overflow-hidden`),children:n&&(0,V.jsx)(Uu,{onOpenSearch:()=>b(!0)})}),x&&(0,V.jsxs)(`div`,{className:`fixed inset-0 z-50 md:hidden`,children:[(0,V.jsx)(`div`,{className:`absolute inset-0 bg-black/40`,onClick:()=>S(!1),"aria-hidden":!0}),(0,V.jsx)(`div`,{className:`absolute inset-y-0 left-0 w-[min(280px,88vw)] shadow-xl`,children:(0,V.jsx)(Uu,{mobile:!0,onOpenSearch:()=>{S(!1),b(!0)},onNavigate:()=>S(!1)})})]}),(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,V.jsxs)(`header`,{className:`flex h-11 shrink-0 items-center gap-1 border-b border-border px-2 sm:px-3`,children:[(0,V.jsx)(v,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`md:hidden`,onClick:()=>S(!0),"aria-label":`Open sidebar`,children:(0,V.jsx)(ve,{className:`size-4`})}),!n&&(0,V.jsx)(v,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`hidden md:inline-flex`,onClick:l,"aria-label":`Open sidebar`,children:(0,V.jsx)(Ce,{className:`size-4`})}),(0,V.jsxs)(`nav`,{className:`flex min-w-0 flex-1 items-center gap-0.5 overflow-hidden text-sm`,children:[E.map((e,t)=>(0,V.jsxs)(`span`,{className:`flex min-w-0 items-center gap-0.5`,children:[t>0&&(0,V.jsx)(I,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,V.jsxs)(`button`,{type:`button`,className:p(`max-w-[140px] truncate rounded px-1.5 py-0.5 transition-colors hover:bg-muted sm:max-w-[200px]`,t===E.length-1?`font-medium text-foreground`:`text-muted-foreground`),onClick:()=>u(e.id),children:[(0,V.jsx)(`span`,{className:`mr-1`,children:e.icon}),e.title||`Untitled`]})]},e.id)),!T&&(0,V.jsx)(`span`,{className:`px-1.5 text-muted-foreground`,children:`No page selected`})]}),(0,V.jsx)(jp,{mode:o,status:s}),T&&(0,V.jsx)(v,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>d(T.id,{favorite:!T.favorite}),"aria-label":T.favorite?`Unfavorite`:`Favorite`,children:(0,V.jsx)(Me,{className:p(`size-4`,T.favorite?`fill-amber-400 text-amber-500`:`text-muted-foreground`)})}),(0,V.jsx)(`div`,{className:`ml-1 hidden items-center gap-2 sm:flex`,children:h?(0,V.jsx)(Hu,{}):(0,V.jsx)(v,{type:`button`,size:`sm`,variant:`outline`,asChild:!0,children:(0,V.jsx)(i,{to:`/login`,children:`Sign in to sync`})})})]}),(0,V.jsx)(`main`,{className:`min-h-0 flex-1 overflow-y-auto`,children:T?(0,V.jsx)(Hd,{page:T},T.id):(0,V.jsx)(Mp,{onCreate:()=>f(),onOpenSidebar:()=>{c(!0),S(!0)}})})]}),(0,V.jsx)(zf,{open:y,onOpenChange:b}),(0,V.jsx)(pp,{position:`bottom-right`,theme:r,toastOptions:{className:`border border-border bg-background text-foreground`}})]})})}function jp({mode:e,status:t}){if(e===`local`)return(0,V.jsxs)(`span`,{className:`hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground sm:inline-flex`,title:`Guest mode — data stays in this browser`,children:[(0,V.jsx)(L,{className:`size-3`}),`Local only`]});let n=t===`saving`||t===`pending`?`Saving…`:t===`error`?`Sync error`:`Saved to DB`;return(0,V.jsxs)(`span`,{className:p(`hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] sm:inline-flex`,t===`error`?`text-destructive`:`text-muted-foreground`),title:`Signed in — workspace syncs to Postgres`,children:[t===`saving`||t===`pending`?(0,V.jsx)(ge,{className:`size-3 animate-spin`}):(0,V.jsx)(te,{className:`size-3`}),n]})}function Mp({onCreate:e,onOpenSidebar:t}){return(0,V.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-4 px-6 text-center`,children:[(0,V.jsx)(`div`,{className:`flex size-14 items-center justify-center rounded-2xl border border-border bg-muted text-2xl`,children:`📄`}),(0,V.jsxs)(`div`,{className:`space-y-1`,children:[(0,V.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:`No pages yet`}),(0,V.jsx)(`p`,{className:`max-w-sm text-sm text-muted-foreground`,children:`Create a page to start writing, or restore one from trash.`})]}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-center gap-2`,children:[(0,V.jsx)(v,{type:`button`,onClick:e,children:`New page`}),(0,V.jsx)(v,{type:`button`,variant:`outline`,onClick:t,children:`Open sidebar`})]})]})}function Np(){return(0,V.jsx)(Ap,{})}export{Np as component}; \ No newline at end of file diff --git a/.vercel/output/static/assets/sankeyDiagram-HTMAVEWB-CyFfG4DT.js b/.vercel/output/static/assets/sankeyDiagram-HTMAVEWB-oWnBtA7E.js similarity index 99% rename from .vercel/output/static/assets/sankeyDiagram-HTMAVEWB-CyFfG4DT.js rename to .vercel/output/static/assets/sankeyDiagram-HTMAVEWB-oWnBtA7E.js index afe83f4..ce4503d 100644 --- a/.vercel/output/static/assets/sankeyDiagram-HTMAVEWB-CyFfG4DT.js +++ b/.vercel/output/static/assets/sankeyDiagram-HTMAVEWB-oWnBtA7E.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-_wZywoZs.js";import{H as n,J as r,K as i,U as a,a as o,d as s,s as c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as p}from"./ordinal-hYBb2elL.js";function m(e){for(var t=e.length/6|0,n=Array(t),r=0;r=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n=i)&&(n=i)}return n}function _(e,t){let n;if(t===void 0)for(let t of e)t!=null&&(n>t||n===void 0&&t>=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}return n}function v(e,t){let n=0;if(t===void 0)for(let t of e)(t=+t)&&(n+=t);else{let r=-1;for(let i of e)(i=+t(i,++r,e))&&(n+=i)}return n}function y(e){return e.target.depth}function b(e){return e.depth}function x(e,t){return t-1-e.height}function S(e,t){return e.sourceLinks.length?e.depth:t-1}function C(e){return e.targetLinks.length?e.depth:e.sourceLinks.length?_(e.sourceLinks,y)-1:0}function w(e){return function(){return e}}function T(e,t){return D(e.source,t.source)||e.index-t.index}function E(e,t){return D(e.target,t.target)||e.index-t.index}function D(e,t){return e.y0-t.y0}function O(e){return e.value}function k(e){return e.index}function A(e){return e.nodes}function j(e){return e.links}function M(e,t){let n=e.get(t);if(!n)throw Error(`missing: `+t);return n}function N({nodes:e}){for(let t of e){let e=t.y0,n=e;for(let n of t.sourceLinks)n.y0=e+n.width/2,e+=n.width;for(let e of t.targetLinks)e.y1=n+e.width/2,n+=e.width}}function P(){let e=0,t=0,n=1,r=1,i=24,a=8,o,s=k,c=S,l,u,d=A,f=j,p=6;function m(){let e={nodes:d.apply(null,arguments),links:f.apply(null,arguments)};return h(e),y(e),b(e),x(e),F(e),N(e),e}m.update=function(e){return N(e),e},m.nodeId=function(e){return arguments.length?(s=typeof e==`function`?e:w(e),m):s},m.nodeAlign=function(e){return arguments.length?(c=typeof e==`function`?e:w(e),m):c},m.nodeSort=function(e){return arguments.length?(l=e,m):l},m.nodeWidth=function(e){return arguments.length?(i=+e,m):i},m.nodePadding=function(e){return arguments.length?(a=o=+e,m):a},m.nodes=function(e){return arguments.length?(d=typeof e==`function`?e:w(e),m):d},m.links=function(e){return arguments.length?(f=typeof e==`function`?e:w(e),m):f},m.linkSort=function(e){return arguments.length?(u=e,m):u},m.size=function(i){return arguments.length?(e=t=0,n=+i[0],r=+i[1],m):[n-e,r-t]},m.extent=function(i){return arguments.length?(e=+i[0][0],n=+i[1][0],t=+i[0][1],r=+i[1][1],m):[[e,t],[n,r]]},m.iterations=function(e){return arguments.length?(p=+e,m):p};function h({nodes:e,links:t}){for(let[t,n]of e.entries())n.index=t,n.sourceLinks=[],n.targetLinks=[];let n=new Map(e.map((t,n)=>[s(t,n,e),t]));for(let[e,r]of t.entries()){r.index=e;let{source:t,target:i}=r;typeof t!=`object`&&(t=r.source=M(n,t)),typeof i!=`object`&&(i=r.target=M(n,i)),t.sourceLinks.push(r),i.targetLinks.push(r)}if(u!=null)for(let{sourceLinks:t,targetLinks:n}of e)t.sort(u),n.sort(u)}function y({nodes:e}){for(let t of e)t.value=t.fixedValue===void 0?Math.max(v(t.sourceLinks,O),v(t.targetLinks,O)):t.fixedValue}function b({nodes:e}){let t=e.length,n=new Set(e),r=new Set,i=0;for(;n.size;){for(let e of n){e.depth=i;for(let{target:t}of e.sourceLinks)r.add(t)}if(++i>t)throw Error(`circular link`);n=r,r=new Set}}function x({nodes:e}){let t=e.length,n=new Set(e),r=new Set,i=0;for(;n.size;){for(let e of n){e.height=i;for(let{source:t}of e.targetLinks)r.add(t)}if(++i>t)throw Error(`circular link`);n=r,r=new Set}}function C({nodes:t}){let r=g(t,e=>e.depth)+1,a=(n-e-i)/(r-1),o=Array(r);for(let n of t){let t=Math.max(0,Math.min(r-1,Math.floor(c.call(null,n,r))));n.layer=t,n.x0=e+t*a,n.x1=n.x0+i,o[t]?o[t].push(n):o[t]=[n]}if(l)for(let e of o)e.sort(l);return o}function P(e){let n=_(e,e=>(r-t-(e.length-1)*o)/v(e,O));for(let i of e){let e=t;for(let t of i){t.y0=e,t.y1=e+t.value*n,e=t.y1+o;for(let e of t.sourceLinks)e.width=e.value*n}e=(r-e+o)/(i.length+1);for(let t=0;te.length)-1)),P(n);for(let e=0;e0))continue;let i=(n/r-e.y0)*t;e.y0+=i,e.y1+=i,V(e)}l===void 0&&i.sort(D),R(i,n)}}function L(e,t,n){for(let r=e.length-2;r>=0;--r){let i=e[r];for(let e of i){let n=0,r=0;for(let{target:t,value:i}of e.sourceLinks){let a=i*(t.layer-e.layer);n+=W(e,t)*a,r+=a}if(!(r>0))continue;let i=(n/r-e.y0)*t;e.y0+=i,e.y1+=i,V(e)}l===void 0&&i.sort(D),R(i,n)}}function R(e,n){let i=e.length>>1,a=e[i];B(e,a.y0-o,i-1,n),z(e,a.y1+o,i+1,n),B(e,r,e.length-1,n),z(e,t,0,n)}function z(e,t,n,r){for(;n1e-6&&(i.y0+=a,i.y1+=a),t=i.y1+o}}function B(e,t,n,r){for(;n>=0;--n){let i=e[n],a=(i.y1-t)*r;a>1e-6&&(i.y0-=a,i.y1-=a),t=i.y0-o}}function V({sourceLinks:e,targetLinks:t}){if(u===void 0){for(let{source:{sourceLinks:e}}of t)e.sort(E);for(let{target:{targetLinks:t}}of e)t.sort(T)}}function H(e){if(u===void 0)for(let{sourceLinks:t,targetLinks:n}of e)t.sort(E),n.sort(T)}function U(e,t){let n=e.y0-(e.sourceLinks.length-1)*o/2;for(let{target:r,width:i}of e.sourceLinks){if(r===t)break;n+=i+o}for(let{source:r,width:i}of t.targetLinks){if(r===e)break;n-=i}return n}function W(e,t){let n=t.y0-(t.targetLinks.length-1)*o/2;for(let{source:r,width:i}of t.targetLinks){if(r===e)break;n+=i+o}for(let{target:r,width:i}of e.sourceLinks){if(r===t)break;n-=i}return n}return m}var F=Math.PI,I=2*F,L=1e-6,R=I-L;function z(){this._x0=this._y0=this._x1=this._y1=null,this._=``}function B(){return new z}z.prototype=B.prototype={constructor:z,moveTo:function(e,t){this._+=`M`+(this._x0=this._x1=+e)+`,`+(this._y0=this._y1=+t)},closePath:function(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._+=`Z`)},lineTo:function(e,t){this._+=`L`+(this._x1=+e)+`,`+(this._y1=+t)},quadraticCurveTo:function(e,t,n,r){this._+=`Q`+ +e+`,`+ +t+`,`+(this._x1=+n)+`,`+(this._y1=+r)},bezierCurveTo:function(e,t,n,r,i,a){this._+=`C`+ +e+`,`+ +t+`,`+ +n+`,`+ +r+`,`+(this._x1=+i)+`,`+(this._y1=+a)},arcTo:function(e,t,n,r,i){e=+e,t=+t,n=+n,r=+r,i=+i;var a=this._x1,o=this._y1,s=n-e,c=r-t,l=a-e,u=o-t,d=l*l+u*u;if(i<0)throw Error(`negative radius: `+i);if(this._x1===null)this._+=`M`+(this._x1=e)+`,`+(this._y1=t);else if(d>L)if(!(Math.abs(u*s-c*l)>L)||!i)this._+=`L`+(this._x1=e)+`,`+(this._y1=t);else{var f=n-a,p=r-o,m=s*s+c*c,h=f*f+p*p,g=Math.sqrt(m),_=Math.sqrt(d),v=i*Math.tan((F-Math.acos((m+d-h)/(2*g*_)))/2),y=v/_,b=v/g;Math.abs(y-1)>L&&(this._+=`L`+(e+y*l)+`,`+(t+y*u)),this._+=`A`+i+`,`+i+`,0,0,`+ +(u*f>l*p)+`,`+(this._x1=e+b*s)+`,`+(this._y1=t+b*c)}},arc:function(e,t,n,r,i,a){e=+e,t=+t,n=+n,a=!!a;var o=n*Math.cos(r),s=n*Math.sin(r),c=e+o,l=t+s,u=1^a,d=a?r-i:i-r;if(n<0)throw Error(`negative radius: `+n);this._x1===null?this._+=`M`+c+`,`+l:(Math.abs(this._x1-c)>L||Math.abs(this._y1-l)>L)&&(this._+=`L`+c+`,`+l),n&&(d<0&&(d=d%I+I),d>R?this._+=`A`+n+`,`+n+`,0,1,`+u+`,`+(e-o)+`,`+(t-s)+`A`+n+`,`+n+`,0,1,`+u+`,`+(this._x1=c)+`,`+(this._y1=l):d>L&&(this._+=`A`+n+`,`+n+`,0,`+ +(d>=F)+`,`+u+`,`+(this._x1=e+n*Math.cos(i))+`,`+(this._y1=t+n*Math.sin(i))))},rect:function(e,t,n,r){this._+=`M`+(this._x0=this._x1=+e)+`,`+(this._y0=this._y1=+t)+`h`+ +n+`v`+ +r+`h`+-n+`Z`},toString:function(){return this._}};function V(e){return function(){return e}}function H(e){return e[0]}function U(e){return e[1]}var W=Array.prototype.slice;function G(e){return e.source}function ee(e){return e.target}function te(e){var t=G,n=ee,r=H,i=U,a=null;function o(){var o,s=W.call(arguments),c=t.apply(this,s),l=n.apply(this,s);if(a||=o=B(),e(a,+r.apply(this,(s[0]=c,s)),+i.apply(this,s),+r.apply(this,(s[0]=l,s)),+i.apply(this,s)),o)return a=null,o+``||null}return o.source=function(e){return arguments.length?(t=e,o):t},o.target=function(e){return arguments.length?(n=e,o):n},o.x=function(e){return arguments.length?(r=typeof e==`function`?e:V(+e),o):r},o.y=function(e){return arguments.length?(i=typeof e==`function`?e:V(+e),o):i},o.context=function(e){return arguments.length?(a=e??null,o):a},o}function ne(e,t,n,r,i){e.moveTo(t,n),e.bezierCurveTo(t=(t+r)/2,n,t,i,r,i)}function re(){return te(ne)}function ie(e){return[e.source.x1,e.y0]}function ae(e){return[e.target.x0,e.y1]}function K(){return re().source(ie).target(ae)}var q=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,9],r=[1,10],i=[1,5,10,12],a={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,SANKEY:4,NEWLINE:5,csv:6,opt_eof:7,record:8,csv_tail:9,EOF:10,"field[source]":11,COMMA:12,"field[target]":13,"field[value]":14,field:15,escaped:16,non_escaped:17,DQUOTE:18,ESCAPED_TEXT:19,NON_ESCAPED_TEXT:20,$accept:0,$end:1},terminals_:{2:`error`,4:`SANKEY`,5:`NEWLINE`,10:`EOF`,11:`field[source]`,12:`COMMA`,13:`field[target]`,14:`field[value]`,18:`DQUOTE`,19:`ESCAPED_TEXT`,20:`NON_ESCAPED_TEXT`},productions_:[0,[3,4],[6,2],[9,2],[9,0],[7,1],[7,0],[8,5],[15,1],[15,1],[16,3],[17,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 7:let e=r.findOrCreateNode(a[s-4].trim().replaceAll(`""`,`"`)),t=r.findOrCreateNode(a[s-2].trim().replaceAll(`""`,`"`)),n=parseFloat(a[s].trim());r.addLink(e,t,n);break;case 8:case 9:case 11:this.$=a[s];break;case 10:this.$=a[s-1];break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},{5:[1,3]},{6:4,8:5,15:6,16:7,17:8,18:n,20:r},{1:[2,6],7:11,10:[1,12]},t(r,[2,4],{9:13,5:[1,14]}),{12:[1,15]},t(i,[2,8]),t(i,[2,9]),{19:[1,16]},t(i,[2,11]),{1:[2,1]},{1:[2,5]},t(r,[2,2]),{6:17,8:5,15:6,16:7,17:8,18:n,20:r},{15:18,16:7,17:8,18:n,20:r},{18:[1,19]},t(r,[2,3]),{12:[1,20]},t(i,[2,10]),{15:21,16:7,17:8,18:n,20:r},t([1,5,10],[2,7])],defaultActions:{11:[2,1],12:[2,5]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{H as n,J as r,K as i,U as a,a as o,d as s,s as c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as p}from"./ordinal-hYBb2elL.js";function m(e){for(var t=e.length/6|0,n=Array(t),r=0;r=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n=i)&&(n=i)}return n}function _(e,t){let n;if(t===void 0)for(let t of e)t!=null&&(n>t||n===void 0&&t>=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}return n}function v(e,t){let n=0;if(t===void 0)for(let t of e)(t=+t)&&(n+=t);else{let r=-1;for(let i of e)(i=+t(i,++r,e))&&(n+=i)}return n}function y(e){return e.target.depth}function b(e){return e.depth}function x(e,t){return t-1-e.height}function S(e,t){return e.sourceLinks.length?e.depth:t-1}function C(e){return e.targetLinks.length?e.depth:e.sourceLinks.length?_(e.sourceLinks,y)-1:0}function w(e){return function(){return e}}function T(e,t){return D(e.source,t.source)||e.index-t.index}function E(e,t){return D(e.target,t.target)||e.index-t.index}function D(e,t){return e.y0-t.y0}function O(e){return e.value}function k(e){return e.index}function A(e){return e.nodes}function j(e){return e.links}function M(e,t){let n=e.get(t);if(!n)throw Error(`missing: `+t);return n}function N({nodes:e}){for(let t of e){let e=t.y0,n=e;for(let n of t.sourceLinks)n.y0=e+n.width/2,e+=n.width;for(let e of t.targetLinks)e.y1=n+e.width/2,n+=e.width}}function P(){let e=0,t=0,n=1,r=1,i=24,a=8,o,s=k,c=S,l,u,d=A,f=j,p=6;function m(){let e={nodes:d.apply(null,arguments),links:f.apply(null,arguments)};return h(e),y(e),b(e),x(e),F(e),N(e),e}m.update=function(e){return N(e),e},m.nodeId=function(e){return arguments.length?(s=typeof e==`function`?e:w(e),m):s},m.nodeAlign=function(e){return arguments.length?(c=typeof e==`function`?e:w(e),m):c},m.nodeSort=function(e){return arguments.length?(l=e,m):l},m.nodeWidth=function(e){return arguments.length?(i=+e,m):i},m.nodePadding=function(e){return arguments.length?(a=o=+e,m):a},m.nodes=function(e){return arguments.length?(d=typeof e==`function`?e:w(e),m):d},m.links=function(e){return arguments.length?(f=typeof e==`function`?e:w(e),m):f},m.linkSort=function(e){return arguments.length?(u=e,m):u},m.size=function(i){return arguments.length?(e=t=0,n=+i[0],r=+i[1],m):[n-e,r-t]},m.extent=function(i){return arguments.length?(e=+i[0][0],n=+i[1][0],t=+i[0][1],r=+i[1][1],m):[[e,t],[n,r]]},m.iterations=function(e){return arguments.length?(p=+e,m):p};function h({nodes:e,links:t}){for(let[t,n]of e.entries())n.index=t,n.sourceLinks=[],n.targetLinks=[];let n=new Map(e.map((t,n)=>[s(t,n,e),t]));for(let[e,r]of t.entries()){r.index=e;let{source:t,target:i}=r;typeof t!=`object`&&(t=r.source=M(n,t)),typeof i!=`object`&&(i=r.target=M(n,i)),t.sourceLinks.push(r),i.targetLinks.push(r)}if(u!=null)for(let{sourceLinks:t,targetLinks:n}of e)t.sort(u),n.sort(u)}function y({nodes:e}){for(let t of e)t.value=t.fixedValue===void 0?Math.max(v(t.sourceLinks,O),v(t.targetLinks,O)):t.fixedValue}function b({nodes:e}){let t=e.length,n=new Set(e),r=new Set,i=0;for(;n.size;){for(let e of n){e.depth=i;for(let{target:t}of e.sourceLinks)r.add(t)}if(++i>t)throw Error(`circular link`);n=r,r=new Set}}function x({nodes:e}){let t=e.length,n=new Set(e),r=new Set,i=0;for(;n.size;){for(let e of n){e.height=i;for(let{source:t}of e.targetLinks)r.add(t)}if(++i>t)throw Error(`circular link`);n=r,r=new Set}}function C({nodes:t}){let r=g(t,e=>e.depth)+1,a=(n-e-i)/(r-1),o=Array(r);for(let n of t){let t=Math.max(0,Math.min(r-1,Math.floor(c.call(null,n,r))));n.layer=t,n.x0=e+t*a,n.x1=n.x0+i,o[t]?o[t].push(n):o[t]=[n]}if(l)for(let e of o)e.sort(l);return o}function P(e){let n=_(e,e=>(r-t-(e.length-1)*o)/v(e,O));for(let i of e){let e=t;for(let t of i){t.y0=e,t.y1=e+t.value*n,e=t.y1+o;for(let e of t.sourceLinks)e.width=e.value*n}e=(r-e+o)/(i.length+1);for(let t=0;te.length)-1)),P(n);for(let e=0;e0))continue;let i=(n/r-e.y0)*t;e.y0+=i,e.y1+=i,V(e)}l===void 0&&i.sort(D),R(i,n)}}function L(e,t,n){for(let r=e.length-2;r>=0;--r){let i=e[r];for(let e of i){let n=0,r=0;for(let{target:t,value:i}of e.sourceLinks){let a=i*(t.layer-e.layer);n+=W(e,t)*a,r+=a}if(!(r>0))continue;let i=(n/r-e.y0)*t;e.y0+=i,e.y1+=i,V(e)}l===void 0&&i.sort(D),R(i,n)}}function R(e,n){let i=e.length>>1,a=e[i];B(e,a.y0-o,i-1,n),z(e,a.y1+o,i+1,n),B(e,r,e.length-1,n),z(e,t,0,n)}function z(e,t,n,r){for(;n1e-6&&(i.y0+=a,i.y1+=a),t=i.y1+o}}function B(e,t,n,r){for(;n>=0;--n){let i=e[n],a=(i.y1-t)*r;a>1e-6&&(i.y0-=a,i.y1-=a),t=i.y0-o}}function V({sourceLinks:e,targetLinks:t}){if(u===void 0){for(let{source:{sourceLinks:e}}of t)e.sort(E);for(let{target:{targetLinks:t}}of e)t.sort(T)}}function H(e){if(u===void 0)for(let{sourceLinks:t,targetLinks:n}of e)t.sort(E),n.sort(T)}function U(e,t){let n=e.y0-(e.sourceLinks.length-1)*o/2;for(let{target:r,width:i}of e.sourceLinks){if(r===t)break;n+=i+o}for(let{source:r,width:i}of t.targetLinks){if(r===e)break;n-=i}return n}function W(e,t){let n=t.y0-(t.targetLinks.length-1)*o/2;for(let{source:r,width:i}of t.targetLinks){if(r===e)break;n+=i+o}for(let{target:r,width:i}of e.sourceLinks){if(r===t)break;n-=i}return n}return m}var F=Math.PI,I=2*F,L=1e-6,R=I-L;function z(){this._x0=this._y0=this._x1=this._y1=null,this._=``}function B(){return new z}z.prototype=B.prototype={constructor:z,moveTo:function(e,t){this._+=`M`+(this._x0=this._x1=+e)+`,`+(this._y0=this._y1=+t)},closePath:function(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._+=`Z`)},lineTo:function(e,t){this._+=`L`+(this._x1=+e)+`,`+(this._y1=+t)},quadraticCurveTo:function(e,t,n,r){this._+=`Q`+ +e+`,`+ +t+`,`+(this._x1=+n)+`,`+(this._y1=+r)},bezierCurveTo:function(e,t,n,r,i,a){this._+=`C`+ +e+`,`+ +t+`,`+ +n+`,`+ +r+`,`+(this._x1=+i)+`,`+(this._y1=+a)},arcTo:function(e,t,n,r,i){e=+e,t=+t,n=+n,r=+r,i=+i;var a=this._x1,o=this._y1,s=n-e,c=r-t,l=a-e,u=o-t,d=l*l+u*u;if(i<0)throw Error(`negative radius: `+i);if(this._x1===null)this._+=`M`+(this._x1=e)+`,`+(this._y1=t);else if(d>L)if(!(Math.abs(u*s-c*l)>L)||!i)this._+=`L`+(this._x1=e)+`,`+(this._y1=t);else{var f=n-a,p=r-o,m=s*s+c*c,h=f*f+p*p,g=Math.sqrt(m),_=Math.sqrt(d),v=i*Math.tan((F-Math.acos((m+d-h)/(2*g*_)))/2),y=v/_,b=v/g;Math.abs(y-1)>L&&(this._+=`L`+(e+y*l)+`,`+(t+y*u)),this._+=`A`+i+`,`+i+`,0,0,`+ +(u*f>l*p)+`,`+(this._x1=e+b*s)+`,`+(this._y1=t+b*c)}},arc:function(e,t,n,r,i,a){e=+e,t=+t,n=+n,a=!!a;var o=n*Math.cos(r),s=n*Math.sin(r),c=e+o,l=t+s,u=1^a,d=a?r-i:i-r;if(n<0)throw Error(`negative radius: `+n);this._x1===null?this._+=`M`+c+`,`+l:(Math.abs(this._x1-c)>L||Math.abs(this._y1-l)>L)&&(this._+=`L`+c+`,`+l),n&&(d<0&&(d=d%I+I),d>R?this._+=`A`+n+`,`+n+`,0,1,`+u+`,`+(e-o)+`,`+(t-s)+`A`+n+`,`+n+`,0,1,`+u+`,`+(this._x1=c)+`,`+(this._y1=l):d>L&&(this._+=`A`+n+`,`+n+`,0,`+ +(d>=F)+`,`+u+`,`+(this._x1=e+n*Math.cos(i))+`,`+(this._y1=t+n*Math.sin(i))))},rect:function(e,t,n,r){this._+=`M`+(this._x0=this._x1=+e)+`,`+(this._y0=this._y1=+t)+`h`+ +n+`v`+ +r+`h`+-n+`Z`},toString:function(){return this._}};function V(e){return function(){return e}}function H(e){return e[0]}function U(e){return e[1]}var W=Array.prototype.slice;function G(e){return e.source}function ee(e){return e.target}function te(e){var t=G,n=ee,r=H,i=U,a=null;function o(){var o,s=W.call(arguments),c=t.apply(this,s),l=n.apply(this,s);if(a||=o=B(),e(a,+r.apply(this,(s[0]=c,s)),+i.apply(this,s),+r.apply(this,(s[0]=l,s)),+i.apply(this,s)),o)return a=null,o+``||null}return o.source=function(e){return arguments.length?(t=e,o):t},o.target=function(e){return arguments.length?(n=e,o):n},o.x=function(e){return arguments.length?(r=typeof e==`function`?e:V(+e),o):r},o.y=function(e){return arguments.length?(i=typeof e==`function`?e:V(+e),o):i},o.context=function(e){return arguments.length?(a=e??null,o):a},o}function ne(e,t,n,r,i){e.moveTo(t,n),e.bezierCurveTo(t=(t+r)/2,n,t,i,r,i)}function re(){return te(ne)}function ie(e){return[e.source.x1,e.y0]}function ae(e){return[e.target.x0,e.y1]}function K(){return re().source(ie).target(ae)}var q=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,9],r=[1,10],i=[1,5,10,12],a={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,SANKEY:4,NEWLINE:5,csv:6,opt_eof:7,record:8,csv_tail:9,EOF:10,"field[source]":11,COMMA:12,"field[target]":13,"field[value]":14,field:15,escaped:16,non_escaped:17,DQUOTE:18,ESCAPED_TEXT:19,NON_ESCAPED_TEXT:20,$accept:0,$end:1},terminals_:{2:`error`,4:`SANKEY`,5:`NEWLINE`,10:`EOF`,11:`field[source]`,12:`COMMA`,13:`field[target]`,14:`field[value]`,18:`DQUOTE`,19:`ESCAPED_TEXT`,20:`NON_ESCAPED_TEXT`},productions_:[0,[3,4],[6,2],[9,2],[9,0],[7,1],[7,0],[8,5],[15,1],[15,1],[16,3],[17,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 7:let e=r.findOrCreateNode(a[s-4].trim().replaceAll(`""`,`"`)),t=r.findOrCreateNode(a[s-2].trim().replaceAll(`""`,`"`)),n=parseFloat(a[s].trim());r.addLink(e,t,n);break;case 8:case 9:case 11:this.$=a[s];break;case 10:this.$=a[s-1];break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},{5:[1,3]},{6:4,8:5,15:6,16:7,17:8,18:n,20:r},{1:[2,6],7:11,10:[1,12]},t(r,[2,4],{9:13,5:[1,14]}),{12:[1,15]},t(i,[2,8]),t(i,[2,9]),{19:[1,16]},t(i,[2,11]),{1:[2,1]},{1:[2,5]},t(r,[2,2]),{6:17,8:5,15:6,16:7,17:8,18:n,20:r},{15:18,16:7,17:8,18:n,20:r},{18:[1,19]},t(r,[2,3]),{12:[1,20]},t(i,[2,10]),{15:21,16:7,17:8,18:n,20:r},t([1,5,10],[2,7])],defaultActions:{11:[2,1],12:[2,5]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};a.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/sequenceDiagram-DBY2YBRQ-BEJBrPsj.js b/.vercel/output/static/assets/sequenceDiagram-DBY2YBRQ-CUG55-r_.js similarity index 99% rename from .vercel/output/static/assets/sequenceDiagram-DBY2YBRQ-BEJBrPsj.js rename to .vercel/output/static/assets/sequenceDiagram-DBY2YBRQ-CUG55-r_.js index 1e47557..0e4ba18 100644 --- a/.vercel/output/static/assets/sequenceDiagram-DBY2YBRQ-BEJBrPsj.js +++ b/.vercel/output/static/assets/sequenceDiagram-DBY2YBRQ-CUG55-r_.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-_wZywoZs.js";import{A as r,F as i,G as a,H as o,K as s,O as c,U as l,a as u,b as d,c as f,i as p,r as m,s as h,v as g,w as _,x as v,y,z as b}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as x}from"./dist-D9sYb5Oa.js";import{g as S,p as C}from"./chunk-ICXQ74PX-fa5hHXws.js";import{a as w,c as T,i as E,n as D,r as O,s as k}from"./chunk-32BRIVSS-BtH22FN8.js";import{t as A}from"./chunk-2Q5K7J3B-C1jixKkw.js";import{n as j,t as M}from"./chunk-ZIRB5QZD-C6fEPe3t.js";var N=x(),P=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,2],r=[1,3],i=[1,4],a=[2,4],o=[1,9],s=[1,11],c=[1,12],l=[1,14],u=[1,15],d=[1,17],f=[1,18],p=[1,19],m=[1,25],h=[1,26],g=[1,27],_=[1,28],v=[1,29],y=[1,30],b=[1,31],x=[1,32],S=[1,33],C=[1,34],w=[1,35],T=[1,36],E=[1,37],D=[1,38],O=[1,39],k=[1,40],A=[1,42],j=[1,43],M=[1,44],N=[1,45],P=[1,46],F=[1,47],I=[1,4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,48,49,50,51,53,54,56,61,62,63,64,73],ee=[1,74],L=[1,80],R=[1,81],te=[1,82],ne=[1,83],z=[1,84],B=[1,85],V=[1,86],re=[1,87],H=[1,88],U=[1,89],W=[1,90],ie=[1,91],ae=[1,92],oe=[1,93],G=[1,94],se=[1,95],K=[1,96],ce=[1,97],le=[1,98],ue=[1,99],de=[1,100],fe=[1,101],pe=[1,102],me=[1,103],he=[1,104],ge=[1,105],_e=[2,78],ve=[4,5,17,51,53,54],ye=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,51,53,54,56,61,62,63,64,73],be=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,50,51,53,54,56,61,62,63,64,73],xe=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,49,51,53,54,56,61,62,63,64,73],Se=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,48,51,53,54,56,61,62,63,64,73],Ce=[5,52],q=[70,71,72,73],J=[1,151],we={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,SPACE:4,NEWLINE:5,SD:6,document:7,line:8,statement:9,INVALID:10,box_section:11,box_line:12,participant_statement:13,create:14,box:15,restOfLine:16,end:17,signal:18,autonumber:19,NUM:20,off:21,activate:22,actor:23,deactivate:24,note_statement:25,links_statement:26,link_statement:27,properties_statement:28,details_statement:29,title:30,legacy_title:31,acc_title:32,acc_title_value:33,acc_descr:34,acc_descr_value:35,acc_descr_multiline_value:36,loop:37,rect:38,opt:39,alt:40,else_sections:41,par:42,par_sections:43,par_over:44,critical:45,option_sections:46,break:47,option:48,and:49,else:50,participant:51,AS:52,participant_actor:53,destroy:54,actor_with_config:55,note:56,placement:57,text2:58,over:59,actor_pair:60,links:61,link:62,properties:63,details:64,spaceList:65,",":66,left_of:67,right_of:68,signaltype:69,"+":70,"-":71,"()":72,ACTOR:73,config_object:74,CONFIG_START:75,CONFIG_CONTENT:76,CONFIG_END:77,SOLID_OPEN_ARROW:78,DOTTED_OPEN_ARROW:79,SOLID_ARROW:80,SOLID_ARROW_TOP:81,SOLID_ARROW_BOTTOM:82,STICK_ARROW_TOP:83,STICK_ARROW_BOTTOM:84,SOLID_ARROW_TOP_DOTTED:85,SOLID_ARROW_BOTTOM_DOTTED:86,STICK_ARROW_TOP_DOTTED:87,STICK_ARROW_BOTTOM_DOTTED:88,SOLID_ARROW_TOP_REVERSE:89,SOLID_ARROW_BOTTOM_REVERSE:90,STICK_ARROW_TOP_REVERSE:91,STICK_ARROW_BOTTOM_REVERSE:92,SOLID_ARROW_TOP_REVERSE_DOTTED:93,SOLID_ARROW_BOTTOM_REVERSE_DOTTED:94,STICK_ARROW_TOP_REVERSE_DOTTED:95,STICK_ARROW_BOTTOM_REVERSE_DOTTED:96,BIDIRECTIONAL_SOLID_ARROW:97,DOTTED_ARROW:98,BIDIRECTIONAL_DOTTED_ARROW:99,SOLID_CROSS:100,DOTTED_CROSS:101,SOLID_POINT:102,DOTTED_POINT:103,TXT:104,$accept:0,$end:1},terminals_:{2:`error`,4:`SPACE`,5:`NEWLINE`,6:`SD`,10:`INVALID`,14:`create`,15:`box`,16:`restOfLine`,17:`end`,19:`autonumber`,20:`NUM`,21:`off`,22:`activate`,24:`deactivate`,30:`title`,31:`legacy_title`,32:`acc_title`,33:`acc_title_value`,34:`acc_descr`,35:`acc_descr_value`,36:`acc_descr_multiline_value`,37:`loop`,38:`rect`,39:`opt`,40:`alt`,42:`par`,44:`par_over`,45:`critical`,47:`break`,48:`option`,49:`and`,50:`else`,51:`participant`,52:`AS`,53:`participant_actor`,54:`destroy`,56:`note`,59:`over`,61:`links`,62:`link`,63:`properties`,64:`details`,66:`,`,67:`left_of`,68:`right_of`,70:`+`,71:`-`,72:`()`,73:`ACTOR`,75:`CONFIG_START`,76:`CONFIG_CONTENT`,77:`CONFIG_END`,78:`SOLID_OPEN_ARROW`,79:`DOTTED_OPEN_ARROW`,80:`SOLID_ARROW`,81:`SOLID_ARROW_TOP`,82:`SOLID_ARROW_BOTTOM`,83:`STICK_ARROW_TOP`,84:`STICK_ARROW_BOTTOM`,85:`SOLID_ARROW_TOP_DOTTED`,86:`SOLID_ARROW_BOTTOM_DOTTED`,87:`STICK_ARROW_TOP_DOTTED`,88:`STICK_ARROW_BOTTOM_DOTTED`,89:`SOLID_ARROW_TOP_REVERSE`,90:`SOLID_ARROW_BOTTOM_REVERSE`,91:`STICK_ARROW_TOP_REVERSE`,92:`STICK_ARROW_BOTTOM_REVERSE`,93:`SOLID_ARROW_TOP_REVERSE_DOTTED`,94:`SOLID_ARROW_BOTTOM_REVERSE_DOTTED`,95:`STICK_ARROW_TOP_REVERSE_DOTTED`,96:`STICK_ARROW_BOTTOM_REVERSE_DOTTED`,97:`BIDIRECTIONAL_SOLID_ARROW`,98:`DOTTED_ARROW`,99:`BIDIRECTIONAL_DOTTED_ARROW`,100:`SOLID_CROSS`,101:`DOTTED_CROSS`,102:`SOLID_POINT`,103:`DOTTED_POINT`,104:`TXT`},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[8,1],[11,0],[11,2],[12,2],[12,1],[12,1],[9,1],[9,2],[9,4],[9,2],[9,4],[9,3],[9,3],[9,2],[9,3],[9,3],[9,2],[9,2],[9,2],[9,2],[9,2],[9,1],[9,1],[9,2],[9,2],[9,1],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[46,1],[46,4],[43,1],[43,4],[41,1],[41,4],[13,5],[13,3],[13,5],[13,3],[13,3],[13,5],[13,3],[13,5],[13,3],[25,4],[25,4],[26,3],[27,3],[28,3],[29,3],[65,2],[65,1],[60,3],[60,1],[57,1],[57,1],[18,5],[18,5],[18,5],[18,5],[18,6],[18,4],[55,2],[74,3],[23,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[58,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 3:return r.apply(a[s]),a[s];case 4:case 10:this.$=[];break;case 5:case 11:a[s-1].push(a[s]),this.$=a[s-1];break;case 6:case 7:case 12:case 13:this.$=a[s];break;case 8:case 9:case 14:this.$=[];break;case 16:a[s].type=`createParticipant`,this.$=a[s];break;case 17:a[s-1].unshift({type:`boxStart`,boxData:r.parseBoxData(a[s-2])}),a[s-1].push({type:`boxEnd`,boxText:a[s-2]}),this.$=a[s-1];break;case 19:this.$={type:`sequenceIndex`,sequenceIndex:Number(a[s-2]),sequenceIndexStep:Number(a[s-1]),sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 20:this.$={type:`sequenceIndex`,sequenceIndex:Number(a[s-1]),sequenceIndexStep:1,sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 21:this.$={type:`sequenceIndex`,sequenceVisible:!1,signalType:r.LINETYPE.AUTONUMBER};break;case 22:this.$={type:`sequenceIndex`,sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 23:this.$={type:`activeStart`,signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1].actor};break;case 24:this.$={type:`activeEnd`,signalType:r.LINETYPE.ACTIVE_END,actor:a[s-1].actor};break;case 30:r.setDiagramTitle(a[s].substring(6)),this.$=a[s].substring(6);break;case 31:r.setDiagramTitle(a[s].substring(7)),this.$=a[s].substring(7);break;case 32:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 33:case 34:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 35:a[s-1].unshift({type:`loopStart`,loopText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.LOOP_START}),a[s-1].push({type:`loopEnd`,loopText:a[s-2],signalType:r.LINETYPE.LOOP_END}),this.$=a[s-1];break;case 36:a[s-1].unshift({type:`rectStart`,color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_START}),a[s-1].push({type:`rectEnd`,color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_END}),this.$=a[s-1];break;case 37:a[s-1].unshift({type:`optStart`,optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_START}),a[s-1].push({type:`optEnd`,optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_END}),this.$=a[s-1];break;case 38:a[s-1].unshift({type:`altStart`,altText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.ALT_START}),a[s-1].push({type:`altEnd`,signalType:r.LINETYPE.ALT_END}),this.$=a[s-1];break;case 39:a[s-1].unshift({type:`parStart`,parText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.PAR_START}),a[s-1].push({type:`parEnd`,signalType:r.LINETYPE.PAR_END}),this.$=a[s-1];break;case 40:a[s-1].unshift({type:`parStart`,parText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.PAR_OVER_START}),a[s-1].push({type:`parEnd`,signalType:r.LINETYPE.PAR_END}),this.$=a[s-1];break;case 41:a[s-1].unshift({type:`criticalStart`,criticalText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.CRITICAL_START}),a[s-1].push({type:`criticalEnd`,signalType:r.LINETYPE.CRITICAL_END}),this.$=a[s-1];break;case 42:a[s-1].unshift({type:`breakStart`,breakText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_START}),a[s-1].push({type:`breakEnd`,optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_END}),this.$=a[s-1];break;case 44:this.$=a[s-3].concat([{type:`option`,optionText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.CRITICAL_OPTION},a[s]]);break;case 46:this.$=a[s-3].concat([{type:`and`,parText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.PAR_AND},a[s]]);break;case 48:this.$=a[s-3].concat([{type:`else`,altText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.ALT_ELSE},a[s]]);break;case 49:a[s-3].draw=`participant`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 50:a[s-1].draw=`participant`,a[s-1].type=`addParticipant`,this.$=a[s-1];break;case 51:a[s-3].draw=`actor`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 52:case 57:a[s-1].draw=`actor`,a[s-1].type=`addParticipant`,this.$=a[s-1];break;case 53:a[s-1].type=`destroyParticipant`,this.$=a[s-1];break;case 54:a[s-3].draw=`participant`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 55:a[s-1].draw=`participant`,a[s-1].type=`addParticipant`,this.$=a[s-1];break;case 56:a[s-3].draw=`actor`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 58:this.$=[a[s-1],{type:`addNote`,placement:a[s-2],actor:a[s-1].actor,text:a[s]}];break;case 59:a[s-2]=[].concat(a[s-1],a[s-1]).slice(0,2),a[s-2][0]=a[s-2][0].actor,a[s-2][1]=a[s-2][1].actor,this.$=[a[s-1],{type:`addNote`,placement:r.PLACEMENT.OVER,actor:a[s-2].slice(0,2),text:a[s]}];break;case 60:this.$=[a[s-1],{type:`addLinks`,actor:a[s-1].actor,text:a[s]}];break;case 61:this.$=[a[s-1],{type:`addALink`,actor:a[s-1].actor,text:a[s]}];break;case 62:this.$=[a[s-1],{type:`addProperties`,actor:a[s-1].actor,text:a[s]}];break;case 63:this.$=[a[s-1],{type:`addDetails`,actor:a[s-1].actor,text:a[s]}];break;case 66:this.$=[a[s-2],a[s]];break;case 67:this.$=a[s];break;case 68:this.$=r.PLACEMENT.LEFTOF;break;case 69:this.$=r.PLACEMENT.RIGHTOF;break;case 70:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s],activate:!0},{type:`activeStart`,signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1].actor}];break;case 71:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s]},{type:`activeEnd`,signalType:r.LINETYPE.ACTIVE_END,actor:a[s-4].actor}];break;case 72:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s],activate:!0,centralConnection:r.LINETYPE.CENTRAL_CONNECTION},{type:`centralConnection`,signalType:r.LINETYPE.CENTRAL_CONNECTION,actor:a[s-1].actor}];break;case 73:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-2],msg:a[s],activate:!1,centralConnection:r.LINETYPE.CENTRAL_CONNECTION_REVERSE},{type:`centralConnectionReverse`,signalType:r.LINETYPE.CENTRAL_CONNECTION_REVERSE,actor:a[s-4].actor}];break;case 74:this.$=[a[s-5],a[s-1],{type:`addMessage`,from:a[s-5].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s],activate:!0,centralConnection:r.LINETYPE.CENTRAL_CONNECTION_DUAL},{type:`centralConnection`,signalType:r.LINETYPE.CENTRAL_CONNECTION,actor:a[s-1].actor},{type:`centralConnectionReverse`,signalType:r.LINETYPE.CENTRAL_CONNECTION_REVERSE,actor:a[s-5].actor}];break;case 75:this.$=[a[s-3],a[s-1],{type:`addMessage`,from:a[s-3].actor,to:a[s-1].actor,signalType:a[s-2],msg:a[s]}];break;case 76:this.$={type:`addParticipant`,actor:a[s-1],config:a[s]};break;case 77:this.$=a[s-1].trim();break;case 78:this.$={type:`addParticipant`,actor:a[s]};break;case 79:this.$=r.LINETYPE.SOLID_OPEN;break;case 80:this.$=r.LINETYPE.DOTTED_OPEN;break;case 81:this.$=r.LINETYPE.SOLID;break;case 82:this.$=r.LINETYPE.SOLID_TOP;break;case 83:this.$=r.LINETYPE.SOLID_BOTTOM;break;case 84:this.$=r.LINETYPE.STICK_TOP;break;case 85:this.$=r.LINETYPE.STICK_BOTTOM;break;case 86:this.$=r.LINETYPE.SOLID_TOP_DOTTED;break;case 87:this.$=r.LINETYPE.SOLID_BOTTOM_DOTTED;break;case 88:this.$=r.LINETYPE.STICK_TOP_DOTTED;break;case 89:this.$=r.LINETYPE.STICK_BOTTOM_DOTTED;break;case 90:this.$=r.LINETYPE.SOLID_ARROW_TOP_REVERSE;break;case 91:this.$=r.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE;break;case 92:this.$=r.LINETYPE.STICK_ARROW_TOP_REVERSE;break;case 93:this.$=r.LINETYPE.STICK_ARROW_BOTTOM_REVERSE;break;case 94:this.$=r.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED;break;case 95:this.$=r.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED;break;case 96:this.$=r.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED;break;case 97:this.$=r.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED;break;case 98:this.$=r.LINETYPE.BIDIRECTIONAL_SOLID;break;case 99:this.$=r.LINETYPE.DOTTED;break;case 100:this.$=r.LINETYPE.BIDIRECTIONAL_DOTTED;break;case 101:this.$=r.LINETYPE.SOLID_CROSS;break;case 102:this.$=r.LINETYPE.DOTTED_CROSS;break;case 103:this.$=r.LINETYPE.SOLID_POINT;break;case 104:this.$=r.LINETYPE.DOTTED_POINT;break;case 105:this.$=r.parseMessage(a[s].trim().substring(1));break}},`anonymous`),table:[{3:1,4:n,5:r,6:i},{1:[3]},{3:5,4:n,5:r,6:i},{3:6,4:n,5:r,6:i},t([1,4,5,10,14,15,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,51,53,54,56,61,62,63,64,73],a,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},t(I,[2,5]),{9:48,13:13,14:l,15:u,18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},t(I,[2,7]),t(I,[2,8]),t(I,[2,9]),t(I,[2,15]),{13:49,51:D,53:O,54:k},{16:[1,50]},{5:[1,51]},{5:[1,54],20:[1,52],21:[1,53]},{23:55,73:F},{23:56,73:F},{5:[1,57]},{5:[1,58]},{5:[1,59]},{5:[1,60]},{5:[1,61]},t(I,[2,30]),t(I,[2,31]),{33:[1,62]},{35:[1,63]},t(I,[2,34]),{16:[1,64]},{16:[1,65]},{16:[1,66]},{16:[1,67]},{16:[1,68]},{16:[1,69]},{16:[1,70]},{16:[1,71]},{23:72,55:73,73:ee},{23:75,55:76,73:ee},{23:77,73:F},{69:78,72:[1,79],78:L,79:R,80:te,81:ne,82:z,83:B,84:V,85:re,86:H,87:U,88:W,89:ie,90:ae,91:oe,92:G,93:se,94:K,95:ce,96:le,97:ue,98:de,99:fe,100:pe,101:me,102:he,103:ge},{57:106,59:[1,107],67:[1,108],68:[1,109]},{23:110,73:F},{23:111,73:F},{23:112,73:F},{23:113,73:F},t([5,66,72,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104],_e),t(I,[2,6]),t(I,[2,16]),t(ve,[2,10],{11:114}),t(I,[2,18]),{5:[1,116],20:[1,115]},{5:[1,117]},t(I,[2,22]),{5:[1,118]},{5:[1,119]},t(I,[2,25]),t(I,[2,26]),t(I,[2,27]),t(I,[2,28]),t(I,[2,29]),t(I,[2,32]),t(I,[2,33]),t(ye,a,{7:120}),t(ye,a,{7:121}),t(ye,a,{7:122}),t(be,a,{41:123,7:124}),t(xe,a,{43:125,7:126}),t(xe,a,{7:126,43:127}),t(Se,a,{46:128,7:129}),t(ye,a,{7:130}),{5:[1,132],52:[1,131]},{5:[1,134],52:[1,133]},t(Ce,_e,{74:135,75:[1,136]}),{5:[1,138],52:[1,137]},{5:[1,140],52:[1,139]},{5:[1,141]},{23:145,70:[1,142],71:[1,143],72:[1,144],73:F},{69:146,78:L,79:R,80:te,81:ne,82:z,83:B,84:V,85:re,86:H,87:U,88:W,89:ie,90:ae,91:oe,92:G,93:se,94:K,95:ce,96:le,97:ue,98:de,99:fe,100:pe,101:me,102:he,103:ge},t(q,[2,79]),t(q,[2,80]),t(q,[2,81]),t(q,[2,82]),t(q,[2,83]),t(q,[2,84]),t(q,[2,85]),t(q,[2,86]),t(q,[2,87]),t(q,[2,88]),t(q,[2,89]),t(q,[2,90]),t(q,[2,91]),t(q,[2,92]),t(q,[2,93]),t(q,[2,94]),t(q,[2,95]),t(q,[2,96]),t(q,[2,97]),t(q,[2,98]),t(q,[2,99]),t(q,[2,100]),t(q,[2,101]),t(q,[2,102]),t(q,[2,103]),t(q,[2,104]),{23:147,73:F},{23:149,60:148,73:F},{73:[2,68]},{73:[2,69]},{58:150,104:J},{58:152,104:J},{58:153,104:J},{58:154,104:J},{4:[1,157],5:[1,159],12:156,13:158,17:[1,155],51:D,53:O,54:k},{5:[1,160]},t(I,[2,20]),t(I,[2,21]),t(I,[2,23]),t(I,[2,24]),{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,161],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,162],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,163],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{17:[1,164]},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[2,47],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,50:[1,165],51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{17:[1,166]},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[2,45],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,49:[1,167],51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{17:[1,168]},{17:[1,169]},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[2,43],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,48:[1,170],51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,171],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{16:[1,172]},t(I,[2,50]),{16:[1,173]},t(I,[2,55]),t(Ce,[2,76]),{76:[1,174]},{16:[1,175]},t(I,[2,52]),{16:[1,176]},t(I,[2,57]),t(I,[2,53]),{23:177,73:F},{23:178,73:F},{23:179,73:F},{58:180,104:J},{23:181,72:[1,182],73:F},{58:183,104:J},{58:184,104:J},{66:[1,185],104:[2,67]},{5:[2,60]},{5:[2,105]},{5:[2,61]},{5:[2,62]},{5:[2,63]},t(I,[2,17]),t(ve,[2,11]),{13:186,51:D,53:O,54:k},t(ve,[2,13]),t(ve,[2,14]),t(I,[2,19]),t(I,[2,35]),t(I,[2,36]),t(I,[2,37]),t(I,[2,38]),{16:[1,187]},t(I,[2,39]),{16:[1,188]},t(I,[2,40]),t(I,[2,41]),{16:[1,189]},t(I,[2,42]),{5:[1,190]},{5:[1,191]},{77:[1,192]},{5:[1,193]},{5:[1,194]},{58:195,104:J},{58:196,104:J},{58:197,104:J},{5:[2,75]},{58:198,104:J},{23:199,73:F},{5:[2,58]},{5:[2,59]},{23:200,73:F},t(ve,[2,12]),t(be,a,{7:124,41:201}),t(xe,a,{7:126,43:202}),t(Se,a,{7:129,46:203}),t(I,[2,49]),t(I,[2,54]),t(Ce,[2,77]),t(I,[2,51]),t(I,[2,56]),{5:[2,70]},{5:[2,71]},{5:[2,72]},{5:[2,73]},{58:204,104:J},{104:[2,66]},{17:[2,48]},{17:[2,46]},{17:[2,44]},{5:[2,74]}],defaultActions:{5:[2,1],6:[2,2],108:[2,68],109:[2,69],150:[2,60],151:[2,105],152:[2,61],153:[2,62],154:[2,63],180:[2,75],183:[2,58],184:[2,59],195:[2,70],196:[2,71],197:[2,72],198:[2,73],200:[2,66],201:[2,48],202:[2,46],203:[2,44],204:[2,74]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{A as r,F as i,G as a,H as o,K as s,O as c,U as l,a as u,b as d,c as f,i as p,r as m,s as h,v as g,w as _,x as v,y,z as b}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as x}from"./dist-qx0Iv9vM.js";import{g as S,p as C}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{a as w,c as T,i as E,n as D,r as O,s as k}from"./chunk-32BRIVSS-DWU3ezKg.js";import{t as A}from"./chunk-2Q5K7J3B-C1jixKkw.js";import{n as j,t as M}from"./chunk-ZIRB5QZD-C6fEPe3t.js";var N=x(),P=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,2],r=[1,3],i=[1,4],a=[2,4],o=[1,9],s=[1,11],c=[1,12],l=[1,14],u=[1,15],d=[1,17],f=[1,18],p=[1,19],m=[1,25],h=[1,26],g=[1,27],_=[1,28],v=[1,29],y=[1,30],b=[1,31],x=[1,32],S=[1,33],C=[1,34],w=[1,35],T=[1,36],E=[1,37],D=[1,38],O=[1,39],k=[1,40],A=[1,42],j=[1,43],M=[1,44],N=[1,45],P=[1,46],F=[1,47],I=[1,4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,48,49,50,51,53,54,56,61,62,63,64,73],ee=[1,74],L=[1,80],R=[1,81],te=[1,82],ne=[1,83],z=[1,84],B=[1,85],V=[1,86],re=[1,87],H=[1,88],U=[1,89],W=[1,90],ie=[1,91],ae=[1,92],oe=[1,93],G=[1,94],se=[1,95],K=[1,96],ce=[1,97],le=[1,98],ue=[1,99],de=[1,100],fe=[1,101],pe=[1,102],me=[1,103],he=[1,104],ge=[1,105],_e=[2,78],ve=[4,5,17,51,53,54],ye=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,51,53,54,56,61,62,63,64,73],be=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,50,51,53,54,56,61,62,63,64,73],xe=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,49,51,53,54,56,61,62,63,64,73],Se=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,48,51,53,54,56,61,62,63,64,73],Ce=[5,52],q=[70,71,72,73],J=[1,151],we={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,SPACE:4,NEWLINE:5,SD:6,document:7,line:8,statement:9,INVALID:10,box_section:11,box_line:12,participant_statement:13,create:14,box:15,restOfLine:16,end:17,signal:18,autonumber:19,NUM:20,off:21,activate:22,actor:23,deactivate:24,note_statement:25,links_statement:26,link_statement:27,properties_statement:28,details_statement:29,title:30,legacy_title:31,acc_title:32,acc_title_value:33,acc_descr:34,acc_descr_value:35,acc_descr_multiline_value:36,loop:37,rect:38,opt:39,alt:40,else_sections:41,par:42,par_sections:43,par_over:44,critical:45,option_sections:46,break:47,option:48,and:49,else:50,participant:51,AS:52,participant_actor:53,destroy:54,actor_with_config:55,note:56,placement:57,text2:58,over:59,actor_pair:60,links:61,link:62,properties:63,details:64,spaceList:65,",":66,left_of:67,right_of:68,signaltype:69,"+":70,"-":71,"()":72,ACTOR:73,config_object:74,CONFIG_START:75,CONFIG_CONTENT:76,CONFIG_END:77,SOLID_OPEN_ARROW:78,DOTTED_OPEN_ARROW:79,SOLID_ARROW:80,SOLID_ARROW_TOP:81,SOLID_ARROW_BOTTOM:82,STICK_ARROW_TOP:83,STICK_ARROW_BOTTOM:84,SOLID_ARROW_TOP_DOTTED:85,SOLID_ARROW_BOTTOM_DOTTED:86,STICK_ARROW_TOP_DOTTED:87,STICK_ARROW_BOTTOM_DOTTED:88,SOLID_ARROW_TOP_REVERSE:89,SOLID_ARROW_BOTTOM_REVERSE:90,STICK_ARROW_TOP_REVERSE:91,STICK_ARROW_BOTTOM_REVERSE:92,SOLID_ARROW_TOP_REVERSE_DOTTED:93,SOLID_ARROW_BOTTOM_REVERSE_DOTTED:94,STICK_ARROW_TOP_REVERSE_DOTTED:95,STICK_ARROW_BOTTOM_REVERSE_DOTTED:96,BIDIRECTIONAL_SOLID_ARROW:97,DOTTED_ARROW:98,BIDIRECTIONAL_DOTTED_ARROW:99,SOLID_CROSS:100,DOTTED_CROSS:101,SOLID_POINT:102,DOTTED_POINT:103,TXT:104,$accept:0,$end:1},terminals_:{2:`error`,4:`SPACE`,5:`NEWLINE`,6:`SD`,10:`INVALID`,14:`create`,15:`box`,16:`restOfLine`,17:`end`,19:`autonumber`,20:`NUM`,21:`off`,22:`activate`,24:`deactivate`,30:`title`,31:`legacy_title`,32:`acc_title`,33:`acc_title_value`,34:`acc_descr`,35:`acc_descr_value`,36:`acc_descr_multiline_value`,37:`loop`,38:`rect`,39:`opt`,40:`alt`,42:`par`,44:`par_over`,45:`critical`,47:`break`,48:`option`,49:`and`,50:`else`,51:`participant`,52:`AS`,53:`participant_actor`,54:`destroy`,56:`note`,59:`over`,61:`links`,62:`link`,63:`properties`,64:`details`,66:`,`,67:`left_of`,68:`right_of`,70:`+`,71:`-`,72:`()`,73:`ACTOR`,75:`CONFIG_START`,76:`CONFIG_CONTENT`,77:`CONFIG_END`,78:`SOLID_OPEN_ARROW`,79:`DOTTED_OPEN_ARROW`,80:`SOLID_ARROW`,81:`SOLID_ARROW_TOP`,82:`SOLID_ARROW_BOTTOM`,83:`STICK_ARROW_TOP`,84:`STICK_ARROW_BOTTOM`,85:`SOLID_ARROW_TOP_DOTTED`,86:`SOLID_ARROW_BOTTOM_DOTTED`,87:`STICK_ARROW_TOP_DOTTED`,88:`STICK_ARROW_BOTTOM_DOTTED`,89:`SOLID_ARROW_TOP_REVERSE`,90:`SOLID_ARROW_BOTTOM_REVERSE`,91:`STICK_ARROW_TOP_REVERSE`,92:`STICK_ARROW_BOTTOM_REVERSE`,93:`SOLID_ARROW_TOP_REVERSE_DOTTED`,94:`SOLID_ARROW_BOTTOM_REVERSE_DOTTED`,95:`STICK_ARROW_TOP_REVERSE_DOTTED`,96:`STICK_ARROW_BOTTOM_REVERSE_DOTTED`,97:`BIDIRECTIONAL_SOLID_ARROW`,98:`DOTTED_ARROW`,99:`BIDIRECTIONAL_DOTTED_ARROW`,100:`SOLID_CROSS`,101:`DOTTED_CROSS`,102:`SOLID_POINT`,103:`DOTTED_POINT`,104:`TXT`},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[8,1],[11,0],[11,2],[12,2],[12,1],[12,1],[9,1],[9,2],[9,4],[9,2],[9,4],[9,3],[9,3],[9,2],[9,3],[9,3],[9,2],[9,2],[9,2],[9,2],[9,2],[9,1],[9,1],[9,2],[9,2],[9,1],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[46,1],[46,4],[43,1],[43,4],[41,1],[41,4],[13,5],[13,3],[13,5],[13,3],[13,3],[13,5],[13,3],[13,5],[13,3],[25,4],[25,4],[26,3],[27,3],[28,3],[29,3],[65,2],[65,1],[60,3],[60,1],[57,1],[57,1],[18,5],[18,5],[18,5],[18,5],[18,6],[18,4],[55,2],[74,3],[23,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[58,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 3:return r.apply(a[s]),a[s];case 4:case 10:this.$=[];break;case 5:case 11:a[s-1].push(a[s]),this.$=a[s-1];break;case 6:case 7:case 12:case 13:this.$=a[s];break;case 8:case 9:case 14:this.$=[];break;case 16:a[s].type=`createParticipant`,this.$=a[s];break;case 17:a[s-1].unshift({type:`boxStart`,boxData:r.parseBoxData(a[s-2])}),a[s-1].push({type:`boxEnd`,boxText:a[s-2]}),this.$=a[s-1];break;case 19:this.$={type:`sequenceIndex`,sequenceIndex:Number(a[s-2]),sequenceIndexStep:Number(a[s-1]),sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 20:this.$={type:`sequenceIndex`,sequenceIndex:Number(a[s-1]),sequenceIndexStep:1,sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 21:this.$={type:`sequenceIndex`,sequenceVisible:!1,signalType:r.LINETYPE.AUTONUMBER};break;case 22:this.$={type:`sequenceIndex`,sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 23:this.$={type:`activeStart`,signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1].actor};break;case 24:this.$={type:`activeEnd`,signalType:r.LINETYPE.ACTIVE_END,actor:a[s-1].actor};break;case 30:r.setDiagramTitle(a[s].substring(6)),this.$=a[s].substring(6);break;case 31:r.setDiagramTitle(a[s].substring(7)),this.$=a[s].substring(7);break;case 32:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 33:case 34:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 35:a[s-1].unshift({type:`loopStart`,loopText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.LOOP_START}),a[s-1].push({type:`loopEnd`,loopText:a[s-2],signalType:r.LINETYPE.LOOP_END}),this.$=a[s-1];break;case 36:a[s-1].unshift({type:`rectStart`,color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_START}),a[s-1].push({type:`rectEnd`,color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_END}),this.$=a[s-1];break;case 37:a[s-1].unshift({type:`optStart`,optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_START}),a[s-1].push({type:`optEnd`,optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_END}),this.$=a[s-1];break;case 38:a[s-1].unshift({type:`altStart`,altText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.ALT_START}),a[s-1].push({type:`altEnd`,signalType:r.LINETYPE.ALT_END}),this.$=a[s-1];break;case 39:a[s-1].unshift({type:`parStart`,parText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.PAR_START}),a[s-1].push({type:`parEnd`,signalType:r.LINETYPE.PAR_END}),this.$=a[s-1];break;case 40:a[s-1].unshift({type:`parStart`,parText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.PAR_OVER_START}),a[s-1].push({type:`parEnd`,signalType:r.LINETYPE.PAR_END}),this.$=a[s-1];break;case 41:a[s-1].unshift({type:`criticalStart`,criticalText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.CRITICAL_START}),a[s-1].push({type:`criticalEnd`,signalType:r.LINETYPE.CRITICAL_END}),this.$=a[s-1];break;case 42:a[s-1].unshift({type:`breakStart`,breakText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_START}),a[s-1].push({type:`breakEnd`,optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_END}),this.$=a[s-1];break;case 44:this.$=a[s-3].concat([{type:`option`,optionText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.CRITICAL_OPTION},a[s]]);break;case 46:this.$=a[s-3].concat([{type:`and`,parText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.PAR_AND},a[s]]);break;case 48:this.$=a[s-3].concat([{type:`else`,altText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.ALT_ELSE},a[s]]);break;case 49:a[s-3].draw=`participant`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 50:a[s-1].draw=`participant`,a[s-1].type=`addParticipant`,this.$=a[s-1];break;case 51:a[s-3].draw=`actor`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 52:case 57:a[s-1].draw=`actor`,a[s-1].type=`addParticipant`,this.$=a[s-1];break;case 53:a[s-1].type=`destroyParticipant`,this.$=a[s-1];break;case 54:a[s-3].draw=`participant`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 55:a[s-1].draw=`participant`,a[s-1].type=`addParticipant`,this.$=a[s-1];break;case 56:a[s-3].draw=`actor`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 58:this.$=[a[s-1],{type:`addNote`,placement:a[s-2],actor:a[s-1].actor,text:a[s]}];break;case 59:a[s-2]=[].concat(a[s-1],a[s-1]).slice(0,2),a[s-2][0]=a[s-2][0].actor,a[s-2][1]=a[s-2][1].actor,this.$=[a[s-1],{type:`addNote`,placement:r.PLACEMENT.OVER,actor:a[s-2].slice(0,2),text:a[s]}];break;case 60:this.$=[a[s-1],{type:`addLinks`,actor:a[s-1].actor,text:a[s]}];break;case 61:this.$=[a[s-1],{type:`addALink`,actor:a[s-1].actor,text:a[s]}];break;case 62:this.$=[a[s-1],{type:`addProperties`,actor:a[s-1].actor,text:a[s]}];break;case 63:this.$=[a[s-1],{type:`addDetails`,actor:a[s-1].actor,text:a[s]}];break;case 66:this.$=[a[s-2],a[s]];break;case 67:this.$=a[s];break;case 68:this.$=r.PLACEMENT.LEFTOF;break;case 69:this.$=r.PLACEMENT.RIGHTOF;break;case 70:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s],activate:!0},{type:`activeStart`,signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1].actor}];break;case 71:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s]},{type:`activeEnd`,signalType:r.LINETYPE.ACTIVE_END,actor:a[s-4].actor}];break;case 72:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s],activate:!0,centralConnection:r.LINETYPE.CENTRAL_CONNECTION},{type:`centralConnection`,signalType:r.LINETYPE.CENTRAL_CONNECTION,actor:a[s-1].actor}];break;case 73:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-2],msg:a[s],activate:!1,centralConnection:r.LINETYPE.CENTRAL_CONNECTION_REVERSE},{type:`centralConnectionReverse`,signalType:r.LINETYPE.CENTRAL_CONNECTION_REVERSE,actor:a[s-4].actor}];break;case 74:this.$=[a[s-5],a[s-1],{type:`addMessage`,from:a[s-5].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s],activate:!0,centralConnection:r.LINETYPE.CENTRAL_CONNECTION_DUAL},{type:`centralConnection`,signalType:r.LINETYPE.CENTRAL_CONNECTION,actor:a[s-1].actor},{type:`centralConnectionReverse`,signalType:r.LINETYPE.CENTRAL_CONNECTION_REVERSE,actor:a[s-5].actor}];break;case 75:this.$=[a[s-3],a[s-1],{type:`addMessage`,from:a[s-3].actor,to:a[s-1].actor,signalType:a[s-2],msg:a[s]}];break;case 76:this.$={type:`addParticipant`,actor:a[s-1],config:a[s]};break;case 77:this.$=a[s-1].trim();break;case 78:this.$={type:`addParticipant`,actor:a[s]};break;case 79:this.$=r.LINETYPE.SOLID_OPEN;break;case 80:this.$=r.LINETYPE.DOTTED_OPEN;break;case 81:this.$=r.LINETYPE.SOLID;break;case 82:this.$=r.LINETYPE.SOLID_TOP;break;case 83:this.$=r.LINETYPE.SOLID_BOTTOM;break;case 84:this.$=r.LINETYPE.STICK_TOP;break;case 85:this.$=r.LINETYPE.STICK_BOTTOM;break;case 86:this.$=r.LINETYPE.SOLID_TOP_DOTTED;break;case 87:this.$=r.LINETYPE.SOLID_BOTTOM_DOTTED;break;case 88:this.$=r.LINETYPE.STICK_TOP_DOTTED;break;case 89:this.$=r.LINETYPE.STICK_BOTTOM_DOTTED;break;case 90:this.$=r.LINETYPE.SOLID_ARROW_TOP_REVERSE;break;case 91:this.$=r.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE;break;case 92:this.$=r.LINETYPE.STICK_ARROW_TOP_REVERSE;break;case 93:this.$=r.LINETYPE.STICK_ARROW_BOTTOM_REVERSE;break;case 94:this.$=r.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED;break;case 95:this.$=r.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED;break;case 96:this.$=r.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED;break;case 97:this.$=r.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED;break;case 98:this.$=r.LINETYPE.BIDIRECTIONAL_SOLID;break;case 99:this.$=r.LINETYPE.DOTTED;break;case 100:this.$=r.LINETYPE.BIDIRECTIONAL_DOTTED;break;case 101:this.$=r.LINETYPE.SOLID_CROSS;break;case 102:this.$=r.LINETYPE.DOTTED_CROSS;break;case 103:this.$=r.LINETYPE.SOLID_POINT;break;case 104:this.$=r.LINETYPE.DOTTED_POINT;break;case 105:this.$=r.parseMessage(a[s].trim().substring(1));break}},`anonymous`),table:[{3:1,4:n,5:r,6:i},{1:[3]},{3:5,4:n,5:r,6:i},{3:6,4:n,5:r,6:i},t([1,4,5,10,14,15,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,51,53,54,56,61,62,63,64,73],a,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},t(I,[2,5]),{9:48,13:13,14:l,15:u,18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},t(I,[2,7]),t(I,[2,8]),t(I,[2,9]),t(I,[2,15]),{13:49,51:D,53:O,54:k},{16:[1,50]},{5:[1,51]},{5:[1,54],20:[1,52],21:[1,53]},{23:55,73:F},{23:56,73:F},{5:[1,57]},{5:[1,58]},{5:[1,59]},{5:[1,60]},{5:[1,61]},t(I,[2,30]),t(I,[2,31]),{33:[1,62]},{35:[1,63]},t(I,[2,34]),{16:[1,64]},{16:[1,65]},{16:[1,66]},{16:[1,67]},{16:[1,68]},{16:[1,69]},{16:[1,70]},{16:[1,71]},{23:72,55:73,73:ee},{23:75,55:76,73:ee},{23:77,73:F},{69:78,72:[1,79],78:L,79:R,80:te,81:ne,82:z,83:B,84:V,85:re,86:H,87:U,88:W,89:ie,90:ae,91:oe,92:G,93:se,94:K,95:ce,96:le,97:ue,98:de,99:fe,100:pe,101:me,102:he,103:ge},{57:106,59:[1,107],67:[1,108],68:[1,109]},{23:110,73:F},{23:111,73:F},{23:112,73:F},{23:113,73:F},t([5,66,72,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104],_e),t(I,[2,6]),t(I,[2,16]),t(ve,[2,10],{11:114}),t(I,[2,18]),{5:[1,116],20:[1,115]},{5:[1,117]},t(I,[2,22]),{5:[1,118]},{5:[1,119]},t(I,[2,25]),t(I,[2,26]),t(I,[2,27]),t(I,[2,28]),t(I,[2,29]),t(I,[2,32]),t(I,[2,33]),t(ye,a,{7:120}),t(ye,a,{7:121}),t(ye,a,{7:122}),t(be,a,{41:123,7:124}),t(xe,a,{43:125,7:126}),t(xe,a,{7:126,43:127}),t(Se,a,{46:128,7:129}),t(ye,a,{7:130}),{5:[1,132],52:[1,131]},{5:[1,134],52:[1,133]},t(Ce,_e,{74:135,75:[1,136]}),{5:[1,138],52:[1,137]},{5:[1,140],52:[1,139]},{5:[1,141]},{23:145,70:[1,142],71:[1,143],72:[1,144],73:F},{69:146,78:L,79:R,80:te,81:ne,82:z,83:B,84:V,85:re,86:H,87:U,88:W,89:ie,90:ae,91:oe,92:G,93:se,94:K,95:ce,96:le,97:ue,98:de,99:fe,100:pe,101:me,102:he,103:ge},t(q,[2,79]),t(q,[2,80]),t(q,[2,81]),t(q,[2,82]),t(q,[2,83]),t(q,[2,84]),t(q,[2,85]),t(q,[2,86]),t(q,[2,87]),t(q,[2,88]),t(q,[2,89]),t(q,[2,90]),t(q,[2,91]),t(q,[2,92]),t(q,[2,93]),t(q,[2,94]),t(q,[2,95]),t(q,[2,96]),t(q,[2,97]),t(q,[2,98]),t(q,[2,99]),t(q,[2,100]),t(q,[2,101]),t(q,[2,102]),t(q,[2,103]),t(q,[2,104]),{23:147,73:F},{23:149,60:148,73:F},{73:[2,68]},{73:[2,69]},{58:150,104:J},{58:152,104:J},{58:153,104:J},{58:154,104:J},{4:[1,157],5:[1,159],12:156,13:158,17:[1,155],51:D,53:O,54:k},{5:[1,160]},t(I,[2,20]),t(I,[2,21]),t(I,[2,23]),t(I,[2,24]),{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,161],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,162],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,163],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{17:[1,164]},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[2,47],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,50:[1,165],51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{17:[1,166]},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[2,45],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,49:[1,167],51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{17:[1,168]},{17:[1,169]},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[2,43],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,48:[1,170],51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,171],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{16:[1,172]},t(I,[2,50]),{16:[1,173]},t(I,[2,55]),t(Ce,[2,76]),{76:[1,174]},{16:[1,175]},t(I,[2,52]),{16:[1,176]},t(I,[2,57]),t(I,[2,53]),{23:177,73:F},{23:178,73:F},{23:179,73:F},{58:180,104:J},{23:181,72:[1,182],73:F},{58:183,104:J},{58:184,104:J},{66:[1,185],104:[2,67]},{5:[2,60]},{5:[2,105]},{5:[2,61]},{5:[2,62]},{5:[2,63]},t(I,[2,17]),t(ve,[2,11]),{13:186,51:D,53:O,54:k},t(ve,[2,13]),t(ve,[2,14]),t(I,[2,19]),t(I,[2,35]),t(I,[2,36]),t(I,[2,37]),t(I,[2,38]),{16:[1,187]},t(I,[2,39]),{16:[1,188]},t(I,[2,40]),t(I,[2,41]),{16:[1,189]},t(I,[2,42]),{5:[1,190]},{5:[1,191]},{77:[1,192]},{5:[1,193]},{5:[1,194]},{58:195,104:J},{58:196,104:J},{58:197,104:J},{5:[2,75]},{58:198,104:J},{23:199,73:F},{5:[2,58]},{5:[2,59]},{23:200,73:F},t(ve,[2,12]),t(be,a,{7:124,41:201}),t(xe,a,{7:126,43:202}),t(Se,a,{7:129,46:203}),t(I,[2,49]),t(I,[2,54]),t(Ce,[2,77]),t(I,[2,51]),t(I,[2,56]),{5:[2,70]},{5:[2,71]},{5:[2,72]},{5:[2,73]},{58:204,104:J},{104:[2,66]},{17:[2,48]},{17:[2,46]},{17:[2,44]},{5:[2,74]}],defaultActions:{5:[2,1],6:[2,2],108:[2,68],109:[2,69],150:[2,60],151:[2,105],152:[2,61],153:[2,62],154:[2,63],180:[2,75],183:[2,58],184:[2,59],195:[2,70],196:[2,71],197:[2,72],198:[2,73],200:[2,66],201:[2,48],202:[2,46],203:[2,44],204:[2,74]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};we.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/src-_wZywoZs.js b/.vercel/output/static/assets/src-UMNXGZaF.js similarity index 99% rename from .vercel/output/static/assets/src-_wZywoZs.js rename to .vercel/output/static/assets/src-UMNXGZaF.js index e64a5fa..ef716e8 100644 --- a/.vercel/output/static/assets/src-_wZywoZs.js +++ b/.vercel/output/static/assets/src-UMNXGZaF.js @@ -1 +1 @@ -import{r as e,t}from"./rolldown-runtime-QTnfLwEv.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";var r=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs=r()})(e,(function(){var e=1e3,t=6e4,n=36e5,r=`millisecond`,i=`second`,a=`minute`,o=`hour`,s=`day`,c=`week`,l=`month`,u=`quarter`,d=`year`,f=`date`,p=`Invalid Date`,m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:`en`,weekdays:`Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday`.split(`_`),months:`January_February_March_April_May_June_July_August_September_October_November_December`.split(`_`),ordinal:function(e){var t=[`th`,`st`,`nd`,`rd`],n=e%100;return`[`+e+(t[(n-20)%10]||t[n]||t[0])+`]`}},_=function(e,t,n){var r=String(e);return!r||r.length>=t?e:``+Array(t+1-r.length).join(n)+e},v={s:_,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?`+`:`-`)+_(r,2,`0`)+`:`+_(i,2,`0`)},m:function e(t,n){if(t.date()1)return e(o[0])}else{var s=t.name;b[s]=t,i=s}return!r&&i&&(y=i),i||!r&&y},w=function(e,t){if(S(e))return e.clone();var n=typeof t==`object`?t:{};return n.date=e,n.args=arguments,new E(n)},T=v;T.l=C,T.i=S,T.w=function(e,t){return w(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var E=function(){function g(e){this.$L=C(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[x]=!0}var _=g.prototype;return _.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(t===null)return new Date(NaN);if(T.u(t))return new Date;if(t instanceof Date)return new Date(t);if(typeof t==`string`&&!/Z$/i.test(t)){var r=t.match(m);if(r){var i=r[2]-1||0,a=(r[7]||`0`).substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)}}return new Date(t)}(e),this.init()},_.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},_.$utils=function(){return T},_.isValid=function(){return this.$d.toString()!==p},_.isSame=function(e,t){var n=w(e);return this.startOf(t)<=n&&n<=this.endOf(t)},_.isAfter=function(e,t){return w(e){},`trace`),debug:n((...e)=>{},`debug`),info:n((...e)=>{},`info`),warn:n((...e)=>{},`warn`),error:n((...e)=>{},`error`),fatal:n((...e)=>{},`fatal`)},s=n(function(e=`fatal`){let t=a.fatal;typeof e==`string`?e.toLowerCase()in a&&(t=a[e]):typeof e==`number`&&(t=e),o.trace=()=>{},o.debug=()=>{},o.info=()=>{},o.warn=()=>{},o.error=()=>{},o.fatal=()=>{},t<=a.fatal&&(o.fatal=console.error?console.error.bind(console,c(`FATAL`),`color: orange`):console.log.bind(console,`\x1B[35m`,c(`FATAL`))),t<=a.error&&(o.error=console.error?console.error.bind(console,c(`ERROR`),`color: orange`):console.log.bind(console,`\x1B[31m`,c(`ERROR`))),t<=a.warn&&(o.warn=console.warn?console.warn.bind(console,c(`WARN`),`color: orange`):console.log.bind(console,`\x1B[33m`,c(`WARN`))),t<=a.info&&(o.info=console.info?console.info.bind(console,c(`INFO`),`color: lightblue`):console.log.bind(console,`\x1B[34m`,c(`INFO`))),t<=a.debug&&(o.debug=console.debug?console.debug.bind(console,c(`DEBUG`),`color: lightgreen`):console.log.bind(console,`\x1B[32m`,c(`DEBUG`))),t<=a.trace&&(o.trace=console.debug?console.debug.bind(console,c(`TRACE`),`color: lightgreen`):console.log.bind(console,`\x1B[32m`,c(`TRACE`)))},`setLogLevel`),c=n(e=>`%c${(0,i.default)().format(`ss.SSS`)} : ${e} : `,`format`),l={value:()=>{}};function u(){for(var e=0,t=arguments.length,n={},r;e=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw Error(`unknown type: `+e);return{type:e,name:n}})}d.prototype=u.prototype={constructor:d,on:function(e,t){var n=this._,r=f(e+``,n),i,a=-1,o=r.length;if(arguments.length<2){for(;++a0)for(var n=Array(i),r=0,i,a;r=0&&(t=e.slice(0,n))!==`xmlns`&&(e=e.slice(n+1)),h.hasOwnProperty(t)?{space:h[t],local:e}:e}function _(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===`http://www.w3.org/1999/xhtml`&&t.documentElement.namespaceURI===`http://www.w3.org/1999/xhtml`?t.createElement(e):t.createElementNS(n,e)}}function v(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function y(e){var t=g(e);return(t.local?v:_)(t)}function b(){}function x(e){return e==null?b:function(){return this.querySelector(e)}}function S(e){typeof e!=`function`&&(e=x(e));for(var t=this._groups,n=t.length,r=Array(n),i=0;i=v&&(v=_+1);!(b=g[v])&&++v=0;)(o=r[i])&&(a&&o.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(o,a),a=o);return this}function we(e){e||=Te;function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}for(var n=this._groups,r=n.length,i=Array(r),a=0;at?1:e>=t?0:NaN}function Ee(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function De(){return Array.from(this)}function Oe(){for(var e=this._groups,t=0,n=e.length;t1?this.each((t==null?Be:typeof t==`function`?He:Ve)(e,t,n??``)):O(this.node(),e)}function O(e,t){return e.style.getPropertyValue(t)||ze(e).getComputedStyle(e,null).getPropertyValue(t)}function We(e){return function(){delete this[e]}}function Ge(e,t){return function(){this[e]=t}}function Ke(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function qe(e,t){return arguments.length>1?this.each((t==null?We:typeof t==`function`?Ke:Ge)(e,t)):this.node()[e]}function Je(e){return e.trim().split(/^|\s+/)}function Ye(e){return e.classList||new Xe(e)}function Xe(e){this._node=e,this._names=Je(e.getAttribute(`class`)||``)}Xe.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute(`class`,this._names.join(` `)))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute(`class`,this._names.join(` `)))},contains:function(e){return this._names.indexOf(e)>=0}};function Ze(e,t){for(var n=Ye(e),r=-1,i=t.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}function Et(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,a;n>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?L(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?L(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Vt.exec(e))?new R(t[1],t[2],t[3],1):(t=Ht.exec(e))?new R(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Ut.exec(e))?L(t[1],t[2],t[3],t[4]):(t=Wt.exec(e))?L(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Gt.exec(e))?an(t[1],t[2]/100,t[3]/100,1):(t=Kt.exec(e))?an(t[1],t[2]/100,t[3]/100,t[4]):qt.hasOwnProperty(e)?Qt(qt[e]):e===`transparent`?new R(NaN,NaN,NaN,0):null}function Qt(e){return new R(e>>16&255,e>>8&255,e&255,1)}function L(e,t,n,r){return r<=0&&(e=t=n=NaN),new R(e,t,n,r)}function $t(e){return e instanceof j||(e=I(e)),e?(e=e.rgb(),new R(e.r,e.g,e.b,e.opacity)):new R}function en(e,t,n,r){return arguments.length===1?$t(e):new R(e,t,n,r??1)}function R(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Lt(R,en,Rt(j,{brighter(e){return e=e==null?zt:zt**+e,new R(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?M:M**+e,new R(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new R(B(this.r),B(this.g),B(this.b),z(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:tn,formatHex:tn,formatHex8:nn,formatRgb:rn,toString:rn}));function tn(){return`#${V(this.r)}${V(this.g)}${V(this.b)}`}function nn(){return`#${V(this.r)}${V(this.g)}${V(this.b)}${V((isNaN(this.opacity)?1:this.opacity)*255)}`}function rn(){let e=z(this.opacity);return`${e===1?`rgb(`:`rgba(`}${B(this.r)}, ${B(this.g)}, ${B(this.b)}${e===1?`)`:`, ${e})`}`}function z(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function B(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function V(e){return e=B(e),(e<16?`0`:``)+e.toString(16)}function an(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new H(e,t,n,r)}function on(e){if(e instanceof H)return new H(e.h,e.s,e.l,e.opacity);if(e instanceof j||(e=I(e)),!e)return new H;if(e instanceof H)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=t===a?(n-r)/s+(n0&&c<1?0:o,new H(o,s,c,e.opacity)}function sn(e,t,n,r){return arguments.length===1?on(e):new H(e,t,n,r??1)}function H(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Lt(H,sn,Rt(j,{brighter(e){return e=e==null?zt:zt**+e,new H(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?M:M**+e,new H(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new R(ln(e>=240?e-240:e+120,i,r),ln(e,i,r),ln(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new H(cn(this.h),U(this.s),U(this.l),z(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=z(this.opacity);return`${e===1?`hsl(`:`hsla(`}${cn(this.h)}, ${U(this.s)*100}%, ${U(this.l)*100}%${e===1?`)`:`, ${e})`}`}}));function cn(e){return e=(e||0)%360,e<0?e+360:e}function U(e){return Math.max(0,Math.min(1,e||0))}function ln(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}var un=e=>()=>e;function dn(e,t){return function(n){return e+n*t}}function fn(e,t,n){return e**=+n,t=t**+n-e,n=1/n,function(r){return(e+r*t)**+n}}function pn(e,t){var n=t-e;return n?dn(e,n>180||n<-180?n-360*Math.round(n/360):n):un(isNaN(e)?t:e)}function mn(e){return(e=+e)==1?hn:function(t,n){return n-t?fn(t,n,e):un(isNaN(t)?n:t)}}function hn(e,t){var n=t-e;return n?dn(e,n):un(isNaN(e)?t:e)}var gn=(function e(t){var n=mn(t);function r(e,t){var r=n((e=en(e)).r,(t=en(t)).r),i=n(e.g,t.g),a=n(e.b,t.b),o=hn(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=a(t),e.opacity=o(t),e+``}}return r.gamma=e,r})(1);function W(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var _n=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,vn=new RegExp(_n.source,`g`);function yn(e){return function(){return e}}function bn(e){return function(t){return e(t)+``}}function xn(e,t){var n=_n.lastIndex=vn.lastIndex=0,r,i,a,o=-1,s=[],c=[];for(e+=``,t+=``;(r=_n.exec(e))&&(i=vn.exec(t));)(a=i.index)>n&&(a=t.slice(n,a),s[o]?s[o]+=a:s[++o]=a),(r=r[0])===(i=i[0])?s[o]?s[o]+=i:s[++o]=i:(s[++o]=null,c.push({i:o,x:W(r,i)})),n=vn.lastIndex;return n180?t+=360:t-e>180&&(e+=360),a.push({i:n.push(i(n)+`rotate(`,null,r)-2,x:W(e,t)}))}function s(e,t,n,a){e===t?t&&n.push(i(n)+`skewX(`+t+r):a.push({i:n.push(i(n)+`skewX(`,null,r)-2,x:W(e,t)})}function c(e,t,n,r,a,o){if(e!==n||t!==r){var s=a.push(i(a)+`scale(`,null,`,`,null,`)`);o.push({i:s-4,x:W(e,n)},{i:s-2,x:W(t,r)})}else(n!==1||r!==1)&&a.push(i(a)+`scale(`+n+`,`+r+`)`)}return function(t,n){var r=[],i=[];return t=e(t),n=e(n),a(t.translateX,t.translateY,n.translateX,n.translateY,r,i),o(t.rotate,n.rotate,r,i),s(t.skewX,n.skewX,r,i),c(t.scaleX,t.scaleY,n.scaleX,n.scaleY,r,i),t=n=null,function(e){for(var t=-1,n=i.length,a;++t=0&&e._call.call(void 0,t),e=e._next;--G}function Un(){q=(Fn=J.now())+In,G=jn=0;try{Hn()}finally{G=0,Gn(),q=0}}function Wn(){var e=J.now(),t=e-Fn;t>Nn&&(In-=t,Fn=e)}function Gn(){for(var e,t=Pn,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Pn=n);K=e,Kn(r)}function Kn(e){G||(jn&&=clearTimeout(jn),e-q>24?(e<1/0&&(jn=setTimeout(Un,e-J.now()-In)),Mn&&=clearInterval(Mn)):(Mn||=(Fn=J.now(),setInterval(Wn,Nn)),G=1,Ln(Un)))}function qn(e,t,n){var r=new Bn;return t=t==null?0:+t,r.restart(n=>{r.stop(),e(n+t)},t,n),r}var Jn=u(`start`,`end`,`cancel`,`interrupt`),Yn=[];function Xn(e,t,n,r,i,a){var o=e.__transition;if(!o)e.__transition={};else if(n in o)return;Qn(e,n,{name:t,index:r,group:i,on:Jn,tween:Yn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:0})}function Zn(e,t){var n=X(e,t);if(n.state>0)throw Error(`too late; already scheduled`);return n}function Y(e,t){var n=X(e,t);if(n.state>3)throw Error(`too late; already running`);return n}function X(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw Error(`transition not found`);return n}function Qn(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=Vn(a,0,n.time);function a(e){n.state=1,n.timer.restart(o,n.delay,n.time),n.delay<=e&&o(e-n.delay)}function o(a){var l,u,d,f;if(n.state!==1)return c();for(l in r)if(f=r[l],f.name===n.name){if(f.state===3)return qn(o);f.state===4?(f.state=6,f.timer.stop(),f.on.call(`interrupt`,e,e.__data__,f.index,f.group),delete r[l]):+l2&&r.state<5,r.state=6,r.timer.stop(),r.on.call(i?`interrupt`:`cancel`,e,e.__data__,r.index,r.group),delete n[o]}a&&delete e.__transition}}function er(e){return this.each(function(){$n(this,e)})}function tr(e,t){var n,r;return function(){var i=Y(this,e),a=i.tween;if(a!==n){r=n=a;for(var o=0,s=r.length;o=0&&(e=e.slice(0,t)),!e||e===`start`})}function jr(e,t,n){var r,i,a=Ar(t)?Zn:Y;return function(){var o=a(this,e),s=o.on;s!==r&&(i=(r=s).copy()).on(t,n),o.on=i}}function Mr(e,t){var n=this._id;return arguments.length<2?X(this.node(),n).on.on(e):this.each(jr(n,e,t))}function Nr(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function Pr(){return this.on(`end.remove`,Nr(this._id))}function Fr(e){var t=this._name,n=this._id;typeof e!=`function`&&(e=x(e));for(var r=this._groups,i=r.length,a=Array(i),o=0;o{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs=r()})(e,(function(){var e=1e3,t=6e4,n=36e5,r=`millisecond`,i=`second`,a=`minute`,o=`hour`,s=`day`,c=`week`,l=`month`,u=`quarter`,d=`year`,f=`date`,p=`Invalid Date`,m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:`en`,weekdays:`Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday`.split(`_`),months:`January_February_March_April_May_June_July_August_September_October_November_December`.split(`_`),ordinal:function(e){var t=[`th`,`st`,`nd`,`rd`],n=e%100;return`[`+e+(t[(n-20)%10]||t[n]||t[0])+`]`}},_=function(e,t,n){var r=String(e);return!r||r.length>=t?e:``+Array(t+1-r.length).join(n)+e},v={s:_,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?`+`:`-`)+_(r,2,`0`)+`:`+_(i,2,`0`)},m:function e(t,n){if(t.date()1)return e(o[0])}else{var s=t.name;b[s]=t,i=s}return!r&&i&&(y=i),i||!r&&y},w=function(e,t){if(S(e))return e.clone();var n=typeof t==`object`?t:{};return n.date=e,n.args=arguments,new E(n)},T=v;T.l=C,T.i=S,T.w=function(e,t){return w(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var E=function(){function g(e){this.$L=C(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[x]=!0}var _=g.prototype;return _.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(t===null)return new Date(NaN);if(T.u(t))return new Date;if(t instanceof Date)return new Date(t);if(typeof t==`string`&&!/Z$/i.test(t)){var r=t.match(m);if(r){var i=r[2]-1||0,a=(r[7]||`0`).substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)}}return new Date(t)}(e),this.init()},_.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},_.$utils=function(){return T},_.isValid=function(){return this.$d.toString()!==p},_.isSame=function(e,t){var n=w(e);return this.startOf(t)<=n&&n<=this.endOf(t)},_.isAfter=function(e,t){return w(e){},`trace`),debug:n((...e)=>{},`debug`),info:n((...e)=>{},`info`),warn:n((...e)=>{},`warn`),error:n((...e)=>{},`error`),fatal:n((...e)=>{},`fatal`)},s=n(function(e=`fatal`){let t=a.fatal;typeof e==`string`?e.toLowerCase()in a&&(t=a[e]):typeof e==`number`&&(t=e),o.trace=()=>{},o.debug=()=>{},o.info=()=>{},o.warn=()=>{},o.error=()=>{},o.fatal=()=>{},t<=a.fatal&&(o.fatal=console.error?console.error.bind(console,c(`FATAL`),`color: orange`):console.log.bind(console,`\x1B[35m`,c(`FATAL`))),t<=a.error&&(o.error=console.error?console.error.bind(console,c(`ERROR`),`color: orange`):console.log.bind(console,`\x1B[31m`,c(`ERROR`))),t<=a.warn&&(o.warn=console.warn?console.warn.bind(console,c(`WARN`),`color: orange`):console.log.bind(console,`\x1B[33m`,c(`WARN`))),t<=a.info&&(o.info=console.info?console.info.bind(console,c(`INFO`),`color: lightblue`):console.log.bind(console,`\x1B[34m`,c(`INFO`))),t<=a.debug&&(o.debug=console.debug?console.debug.bind(console,c(`DEBUG`),`color: lightgreen`):console.log.bind(console,`\x1B[32m`,c(`DEBUG`))),t<=a.trace&&(o.trace=console.debug?console.debug.bind(console,c(`TRACE`),`color: lightgreen`):console.log.bind(console,`\x1B[32m`,c(`TRACE`)))},`setLogLevel`),c=n(e=>`%c${(0,i.default)().format(`ss.SSS`)} : ${e} : `,`format`),l={value:()=>{}};function u(){for(var e=0,t=arguments.length,n={},r;e=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw Error(`unknown type: `+e);return{type:e,name:n}})}d.prototype=u.prototype={constructor:d,on:function(e,t){var n=this._,r=f(e+``,n),i,a=-1,o=r.length;if(arguments.length<2){for(;++a0)for(var n=Array(i),r=0,i,a;r=0&&(t=e.slice(0,n))!==`xmlns`&&(e=e.slice(n+1)),h.hasOwnProperty(t)?{space:h[t],local:e}:e}function _(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===`http://www.w3.org/1999/xhtml`&&t.documentElement.namespaceURI===`http://www.w3.org/1999/xhtml`?t.createElement(e):t.createElementNS(n,e)}}function v(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function y(e){var t=g(e);return(t.local?v:_)(t)}function b(){}function x(e){return e==null?b:function(){return this.querySelector(e)}}function S(e){typeof e!=`function`&&(e=x(e));for(var t=this._groups,n=t.length,r=Array(n),i=0;i=v&&(v=_+1);!(b=g[v])&&++v=0;)(o=r[i])&&(a&&o.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(o,a),a=o);return this}function we(e){e||=Te;function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}for(var n=this._groups,r=n.length,i=Array(r),a=0;at?1:e>=t?0:NaN}function Ee(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function De(){return Array.from(this)}function Oe(){for(var e=this._groups,t=0,n=e.length;t1?this.each((t==null?Be:typeof t==`function`?He:Ve)(e,t,n??``)):O(this.node(),e)}function O(e,t){return e.style.getPropertyValue(t)||ze(e).getComputedStyle(e,null).getPropertyValue(t)}function We(e){return function(){delete this[e]}}function Ge(e,t){return function(){this[e]=t}}function Ke(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function qe(e,t){return arguments.length>1?this.each((t==null?We:typeof t==`function`?Ke:Ge)(e,t)):this.node()[e]}function Je(e){return e.trim().split(/^|\s+/)}function Ye(e){return e.classList||new Xe(e)}function Xe(e){this._node=e,this._names=Je(e.getAttribute(`class`)||``)}Xe.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute(`class`,this._names.join(` `)))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute(`class`,this._names.join(` `)))},contains:function(e){return this._names.indexOf(e)>=0}};function Ze(e,t){for(var n=Ye(e),r=-1,i=t.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}function Et(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,a;n>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?L(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?L(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Vt.exec(e))?new R(t[1],t[2],t[3],1):(t=Ht.exec(e))?new R(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Ut.exec(e))?L(t[1],t[2],t[3],t[4]):(t=Wt.exec(e))?L(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Gt.exec(e))?an(t[1],t[2]/100,t[3]/100,1):(t=Kt.exec(e))?an(t[1],t[2]/100,t[3]/100,t[4]):qt.hasOwnProperty(e)?Qt(qt[e]):e===`transparent`?new R(NaN,NaN,NaN,0):null}function Qt(e){return new R(e>>16&255,e>>8&255,e&255,1)}function L(e,t,n,r){return r<=0&&(e=t=n=NaN),new R(e,t,n,r)}function $t(e){return e instanceof j||(e=I(e)),e?(e=e.rgb(),new R(e.r,e.g,e.b,e.opacity)):new R}function en(e,t,n,r){return arguments.length===1?$t(e):new R(e,t,n,r??1)}function R(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Lt(R,en,Rt(j,{brighter(e){return e=e==null?zt:zt**+e,new R(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?M:M**+e,new R(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new R(B(this.r),B(this.g),B(this.b),z(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:tn,formatHex:tn,formatHex8:nn,formatRgb:rn,toString:rn}));function tn(){return`#${V(this.r)}${V(this.g)}${V(this.b)}`}function nn(){return`#${V(this.r)}${V(this.g)}${V(this.b)}${V((isNaN(this.opacity)?1:this.opacity)*255)}`}function rn(){let e=z(this.opacity);return`${e===1?`rgb(`:`rgba(`}${B(this.r)}, ${B(this.g)}, ${B(this.b)}${e===1?`)`:`, ${e})`}`}function z(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function B(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function V(e){return e=B(e),(e<16?`0`:``)+e.toString(16)}function an(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new H(e,t,n,r)}function on(e){if(e instanceof H)return new H(e.h,e.s,e.l,e.opacity);if(e instanceof j||(e=I(e)),!e)return new H;if(e instanceof H)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=t===a?(n-r)/s+(n0&&c<1?0:o,new H(o,s,c,e.opacity)}function sn(e,t,n,r){return arguments.length===1?on(e):new H(e,t,n,r??1)}function H(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Lt(H,sn,Rt(j,{brighter(e){return e=e==null?zt:zt**+e,new H(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?M:M**+e,new H(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new R(ln(e>=240?e-240:e+120,i,r),ln(e,i,r),ln(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new H(cn(this.h),U(this.s),U(this.l),z(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=z(this.opacity);return`${e===1?`hsl(`:`hsla(`}${cn(this.h)}, ${U(this.s)*100}%, ${U(this.l)*100}%${e===1?`)`:`, ${e})`}`}}));function cn(e){return e=(e||0)%360,e<0?e+360:e}function U(e){return Math.max(0,Math.min(1,e||0))}function ln(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}var un=e=>()=>e;function dn(e,t){return function(n){return e+n*t}}function fn(e,t,n){return e**=+n,t=t**+n-e,n=1/n,function(r){return(e+r*t)**+n}}function pn(e,t){var n=t-e;return n?dn(e,n>180||n<-180?n-360*Math.round(n/360):n):un(isNaN(e)?t:e)}function mn(e){return(e=+e)==1?hn:function(t,n){return n-t?fn(t,n,e):un(isNaN(t)?n:t)}}function hn(e,t){var n=t-e;return n?dn(e,n):un(isNaN(e)?t:e)}var gn=(function e(t){var n=mn(t);function r(e,t){var r=n((e=en(e)).r,(t=en(t)).r),i=n(e.g,t.g),a=n(e.b,t.b),o=hn(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=a(t),e.opacity=o(t),e+``}}return r.gamma=e,r})(1);function W(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var _n=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,vn=new RegExp(_n.source,`g`);function yn(e){return function(){return e}}function bn(e){return function(t){return e(t)+``}}function xn(e,t){var n=_n.lastIndex=vn.lastIndex=0,r,i,a,o=-1,s=[],c=[];for(e+=``,t+=``;(r=_n.exec(e))&&(i=vn.exec(t));)(a=i.index)>n&&(a=t.slice(n,a),s[o]?s[o]+=a:s[++o]=a),(r=r[0])===(i=i[0])?s[o]?s[o]+=i:s[++o]=i:(s[++o]=null,c.push({i:o,x:W(r,i)})),n=vn.lastIndex;return n180?t+=360:t-e>180&&(e+=360),a.push({i:n.push(i(n)+`rotate(`,null,r)-2,x:W(e,t)}))}function s(e,t,n,a){e===t?t&&n.push(i(n)+`skewX(`+t+r):a.push({i:n.push(i(n)+`skewX(`,null,r)-2,x:W(e,t)})}function c(e,t,n,r,a,o){if(e!==n||t!==r){var s=a.push(i(a)+`scale(`,null,`,`,null,`)`);o.push({i:s-4,x:W(e,n)},{i:s-2,x:W(t,r)})}else(n!==1||r!==1)&&a.push(i(a)+`scale(`+n+`,`+r+`)`)}return function(t,n){var r=[],i=[];return t=e(t),n=e(n),a(t.translateX,t.translateY,n.translateX,n.translateY,r,i),o(t.rotate,n.rotate,r,i),s(t.skewX,n.skewX,r,i),c(t.scaleX,t.scaleY,n.scaleX,n.scaleY,r,i),t=n=null,function(e){for(var t=-1,n=i.length,a;++t=0&&e._call.call(void 0,t),e=e._next;--G}function Un(){q=(Fn=J.now())+In,G=jn=0;try{Hn()}finally{G=0,Gn(),q=0}}function Wn(){var e=J.now(),t=e-Fn;t>Nn&&(In-=t,Fn=e)}function Gn(){for(var e,t=Pn,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Pn=n);K=e,Kn(r)}function Kn(e){G||(jn&&=clearTimeout(jn),e-q>24?(e<1/0&&(jn=setTimeout(Un,e-J.now()-In)),Mn&&=clearInterval(Mn)):(Mn||=(Fn=J.now(),setInterval(Wn,Nn)),G=1,Ln(Un)))}function qn(e,t,n){var r=new Bn;return t=t==null?0:+t,r.restart(n=>{r.stop(),e(n+t)},t,n),r}var Jn=u(`start`,`end`,`cancel`,`interrupt`),Yn=[];function Xn(e,t,n,r,i,a){var o=e.__transition;if(!o)e.__transition={};else if(n in o)return;Qn(e,n,{name:t,index:r,group:i,on:Jn,tween:Yn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:0})}function Zn(e,t){var n=X(e,t);if(n.state>0)throw Error(`too late; already scheduled`);return n}function Y(e,t){var n=X(e,t);if(n.state>3)throw Error(`too late; already running`);return n}function X(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw Error(`transition not found`);return n}function Qn(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=Vn(a,0,n.time);function a(e){n.state=1,n.timer.restart(o,n.delay,n.time),n.delay<=e&&o(e-n.delay)}function o(a){var l,u,d,f;if(n.state!==1)return c();for(l in r)if(f=r[l],f.name===n.name){if(f.state===3)return qn(o);f.state===4?(f.state=6,f.timer.stop(),f.on.call(`interrupt`,e,e.__data__,f.index,f.group),delete r[l]):+l2&&r.state<5,r.state=6,r.timer.stop(),r.on.call(i?`interrupt`:`cancel`,e,e.__data__,r.index,r.group),delete n[o]}a&&delete e.__transition}}function er(e){return this.each(function(){$n(this,e)})}function tr(e,t){var n,r;return function(){var i=Y(this,e),a=i.tween;if(a!==n){r=n=a;for(var o=0,s=r.length;o=0&&(e=e.slice(0,t)),!e||e===`start`})}function jr(e,t,n){var r,i,a=Ar(t)?Zn:Y;return function(){var o=a(this,e),s=o.on;s!==r&&(i=(r=s).copy()).on(t,n),o.on=i}}function Mr(e,t){var n=this._id;return arguments.length<2?X(this.node(),n).on.on(e):this.each(jr(n,e,t))}function Nr(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function Pr(){return this.on(`end.remove`,Nr(this._id))}function Fr(e){var t=this._name,n=this._id;typeof e!=`function`&&(e=x(e));for(var r=this._groups,i=r.length,a=Array(i),o=0;oe.append(`circle`).attr(`class`,`start-state`).attr(`r`,o().state.sizeUnit).attr(`cx`,o().state.padding+o().state.sizeUnit).attr(`cy`,o().state.padding+o().state.sizeUnit),`drawStartState`),g=e(e=>e.append(`line`).style(`stroke`,`grey`).style(`stroke-dasharray`,`3`).attr(`x1`,o().state.textHeight).attr(`class`,`divider`).attr(`x2`,o().state.textHeight*2).attr(`y1`,0).attr(`y2`,0),`drawDivider`),_=e((e,t)=>{let n=e.append(`text`).attr(`x`,2*o().state.padding).attr(`y`,o().state.textHeight+2*o().state.padding).attr(`font-size`,o().state.fontSize).attr(`class`,`state-title`).text(t.id),r=n.node().getBBox();return e.insert(`rect`,`:first-child`).attr(`x`,o().state.padding).attr(`y`,o().state.padding).attr(`width`,r.width+2*o().state.padding).attr(`height`,r.height+2*o().state.padding).attr(`rx`,o().state.radius),n},`drawSimpleState`),v=e((t,n)=>{let r=e(function(e,t,n){let r=e.append(`tspan`).attr(`x`,2*o().state.padding).text(t);n||r.attr(`dy`,o().state.textHeight)},`addTspan`),i=t.append(`text`).attr(`x`,2*o().state.padding).attr(`y`,o().state.textHeight+1.3*o().state.padding).attr(`font-size`,o().state.fontSize).attr(`class`,`state-title`).text(n.descriptions[0]).node().getBBox(),a=i.height,s=t.append(`text`).attr(`x`,o().state.padding).attr(`y`,a+o().state.padding*.4+o().state.dividerMargin+o().state.textHeight).attr(`class`,`state-description`),c=!0,l=!0;n.descriptions.forEach(function(e){c||(r(s,e,l),l=!1),c=!1});let u=t.append(`line`).attr(`x1`,o().state.padding).attr(`y1`,o().state.padding+a+o().state.dividerMargin/2).attr(`y2`,o().state.padding+a+o().state.dividerMargin/2).attr(`class`,`descr-divider`),d=s.node().getBBox(),f=Math.max(d.width,i.width);return u.attr(`x2`,f+3*o().state.padding),t.insert(`rect`,`:first-child`).attr(`x`,o().state.padding).attr(`y`,o().state.padding).attr(`width`,f+2*o().state.padding).attr(`height`,d.height+a+2*o().state.padding).attr(`rx`,o().state.radius),t},`drawDescrState`),y=e((e,t,n)=>{let r=o().state.padding,i=2*o().state.padding,a=e.node().getBBox(),s=a.width,c=a.x,l=e.append(`text`).attr(`x`,0).attr(`y`,o().state.titleShift).attr(`font-size`,o().state.fontSize).attr(`class`,`state-title`).text(t.id),u=l.node().getBBox().width+i,d=Math.max(u,s);d===s&&(d+=i);let f,p=e.node().getBBox();t.doc,f=c-r,u>s&&(f=(s-d)/2+r),Math.abs(c-p.x)s&&(f=c-(u-s)/2);let m=1-o().state.textHeight;return e.insert(`rect`,`:first-child`).attr(`x`,f).attr(`y`,m).attr(`class`,n?`alt-composit`:`composit`).attr(`width`,d).attr(`height`,p.height+o().state.textHeight+o().state.titleShift+1).attr(`rx`,`0`),l.attr(`x`,f+r),u<=s&&l.attr(`x`,c+(d-i)/2-u/2+r),e.insert(`rect`,`:first-child`).attr(`x`,f).attr(`y`,o().state.titleShift-o().state.textHeight-o().state.padding).attr(`width`,d).attr(`height`,o().state.textHeight*3).attr(`rx`,o().state.radius),e.insert(`rect`,`:first-child`).attr(`x`,f).attr(`y`,o().state.titleShift-o().state.textHeight-o().state.padding).attr(`width`,d).attr(`height`,p.height+3+2*o().state.textHeight).attr(`rx`,o().state.radius),e},`addTitleAndBox`),b=e(e=>(e.append(`circle`).attr(`class`,`end-state-outer`).attr(`r`,o().state.sizeUnit+o().state.miniPadding).attr(`cx`,o().state.padding+o().state.sizeUnit+o().state.miniPadding).attr(`cy`,o().state.padding+o().state.sizeUnit+o().state.miniPadding),e.append(`circle`).attr(`class`,`end-state-inner`).attr(`r`,o().state.sizeUnit).attr(`cx`,o().state.padding+o().state.sizeUnit+2).attr(`cy`,o().state.padding+o().state.sizeUnit+2)),`drawEndState`),x=e((e,t)=>{let n=o().state.forkWidth,r=o().state.forkHeight;if(t.parentId){let e=n;n=r,r=e}return e.append(`rect`).style(`stroke`,`black`).style(`fill`,`black`).attr(`width`,n).attr(`height`,r).attr(`x`,o().state.padding).attr(`y`,o().state.padding)},`drawForkJoinState`),S=e((e,t,n,r)=>{let i=0,s=r.append(`text`);s.style(`text-anchor`,`start`),s.attr(`class`,`noteText`);let c=e.replace(/\r\n/g,`
`);c=c.replace(/\n/g,`
`);let l=c.split(a.lineBreakRegex),u=1.25*o().state.noteMargin;for(let e of l){let r=e.trim();if(r.length>0){let e=s.append(`tspan`);if(e.text(r),u===0){let t=e.node().getBBox();u+=t.height}i+=u,e.attr(`x`,t+o().state.noteMargin),e.attr(`y`,n+i+1.25*o().state.noteMargin)}}return{textWidth:s.node().getBBox().width,textHeight:i}},`_drawLongText`),C=e((e,t)=>{t.attr(`class`,`state-note`);let n=t.append(`rect`).attr(`x`,0).attr(`y`,o().state.padding),{textWidth:r,textHeight:i}=S(e,0,0,t.append(`g`));return n.attr(`height`,i+2*o().state.noteMargin),n.attr(`width`,r+o().state.noteMargin*2),n},`drawNote`),w=e(function(e,t){let n=t.id,r={id:n,label:t.id,width:0,height:0},i=e.append(`g`).attr(`id`,n).attr(`class`,`stateGroup`);t.type===`start`&&h(i),t.type===`end`&&b(i),(t.type===`fork`||t.type===`join`)&&x(i,t),t.type===`note`&&C(t.note.text,i),t.type===`divider`&&g(i),t.type==="default"&&t.descriptions.length===0&&_(i,t),t.type==="default"&&t.descriptions.length>0&&v(i,t);let a=i.node().getBBox();return r.width=a.width+2*o().state.padding,r.height=a.height+2*o().state.padding,r},`drawState`),T=0,E=e(function(n,i,u){let d=e(function(e){switch(e){case m.relationType.AGGREGATION:return`aggregation`;case m.relationType.EXTENSION:return`extension`;case m.relationType.COMPOSITION:return`composition`;case m.relationType.DEPENDENCY:return`dependency`}},`getRelationType`);i.points=i.points.filter(e=>!Number.isNaN(e.y));let f=i.points,p=l().x(function(e){return e.x}).y(function(e){return e.y}).curve(s),h=n.append(`path`).attr(`d`,p(f)).attr(`id`,`edge`+T).attr(`class`,`transition`),g=``;if(o().state.arrowMarkerAbsolute&&(g=r(!0)),h.attr(`marker-end`,`url(`+g+`#`+d(m.relationType.DEPENDENCY)+`End)`),u.title!==void 0){let e=n.append(`g`).attr(`class`,`stateLabel`),{x:r,y:s}=c.calcLabelPosition(i.points),l=a.getRows(u.title),d=0,f=[],p=0,m=0;for(let n=0;n<=l.length;n++){let i=e.append(`text`).attr(`text-anchor`,`middle`).text(l[n]).attr(`x`,r).attr(`y`,s+d),a=i.node().getBBox();p=Math.max(p,a.width),m=Math.min(m,a.x),t.info(a.x,r,s+d),d===0&&(d=i.node().getBBox().height,t.info(`Title height`,d,s)),f.push(i)}let h=d*l.length;if(l.length>1){let e=(l.length-1)*d*.5;f.forEach((t,n)=>t.attr(`y`,s+n*d-e)),h=d*l.length}let g=e.node().getBBox();e.insert(`rect`,`:first-child`).attr(`class`,`box`).attr(`x`,r-p/2-o().state.padding/2).attr(`y`,s-h/2-o().state.padding/2-3.5).attr(`width`,p+o().state.padding).attr(`height`,h+o().state.padding),t.info(g)}T++},`drawEdge`),D,O={},k=e(function(){},`setConf`),A=e(function(e){e.append(`defs`).append(`marker`).attr(`id`,`dependencyEnd`).attr(`refX`,19).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L9,13 L14,7 L9,1 Z`)},`insertMarkers`),j=e(function(e,r,a,s){D=o().state;let c=o().securityLevel,l;c===`sandbox`&&(l=n(`#i`+r));let u=n(c===`sandbox`?l.nodes()[0].contentDocument.body:`body`),d=c===`sandbox`?l.nodes()[0].contentDocument:document;t.debug(`Rendering diagram `+e);let f=u.select(`[id='${r}']`);A(f),N(s.db.getRootDoc(),f.append(`g`).attr(`id`,r+`-root`),void 0,!1,u,d,s);let p=D.padding,m=f.node().getBBox(),h=m.width+p*2,g=m.height+p*2;i(f,g,h*1.75,D.useMaxWidth),f.attr(`viewBox`,`${m.x-D.padding} ${m.y-D.padding} `+h+` `+g)},`draw`),M=e(e=>e?e.length*D.fontSizeFactor:1,`getLabelWidth`),N=e((e,n,r,i,o,s,c)=>{let l=new u({compound:!0,multigraph:!0}),f,p=!0;for(f=0;f{let t=e.parentElement,n=0,r=0;t&&(t.parentElement&&(n=t.parentElement.getBBox().width),r=parseInt(t.getAttribute(`data-x-shift`),10),Number.isNaN(r)&&(r=0)),e.setAttribute(`x1`,0-r+8),e.setAttribute(`x2`,n-r-8)})):t.debug(`No Node `+e+`: `+JSON.stringify(l.node(e)))});let b=v.getBBox();l.edges().forEach(function(e){e!==void 0&&l.edge(e)!==void 0&&(t.debug(`Edge `+e.v+` -> `+e.w+`: `+JSON.stringify(l.edge(e))),E(n,l.edge(e),l.edge(e).relation))}),b=v.getBBox();let x={id:r||`root`,label:r||`root`,width:0,height:0};return x.width=b.width+2*D.padding,x.height=b.height+2*D.padding,t.debug(`Doc rendered`,x,l),x},`renderDoc`),P={parser:p,get db(){return new m(1)},renderer:{setConf:k,draw:j},styles:f,init:e(e=>{e.state||={},e.state.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{P as diagram}; \ No newline at end of file +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{O as r,c as i,s as a,x as o}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{et as s,g as c}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as l}from"./line-b9Ala942.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import{t as u}from"./graphlib-DS17s2tU.js";import{t as d}from"./dagre-dpRSp0QF.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import{i as f,n as p,t as m}from"./chunk-EX3LRPZG-CzaF5a2T.js";var h=e(e=>e.append(`circle`).attr(`class`,`start-state`).attr(`r`,o().state.sizeUnit).attr(`cx`,o().state.padding+o().state.sizeUnit).attr(`cy`,o().state.padding+o().state.sizeUnit),`drawStartState`),g=e(e=>e.append(`line`).style(`stroke`,`grey`).style(`stroke-dasharray`,`3`).attr(`x1`,o().state.textHeight).attr(`class`,`divider`).attr(`x2`,o().state.textHeight*2).attr(`y1`,0).attr(`y2`,0),`drawDivider`),_=e((e,t)=>{let n=e.append(`text`).attr(`x`,2*o().state.padding).attr(`y`,o().state.textHeight+2*o().state.padding).attr(`font-size`,o().state.fontSize).attr(`class`,`state-title`).text(t.id),r=n.node().getBBox();return e.insert(`rect`,`:first-child`).attr(`x`,o().state.padding).attr(`y`,o().state.padding).attr(`width`,r.width+2*o().state.padding).attr(`height`,r.height+2*o().state.padding).attr(`rx`,o().state.radius),n},`drawSimpleState`),v=e((t,n)=>{let r=e(function(e,t,n){let r=e.append(`tspan`).attr(`x`,2*o().state.padding).text(t);n||r.attr(`dy`,o().state.textHeight)},`addTspan`),i=t.append(`text`).attr(`x`,2*o().state.padding).attr(`y`,o().state.textHeight+1.3*o().state.padding).attr(`font-size`,o().state.fontSize).attr(`class`,`state-title`).text(n.descriptions[0]).node().getBBox(),a=i.height,s=t.append(`text`).attr(`x`,o().state.padding).attr(`y`,a+o().state.padding*.4+o().state.dividerMargin+o().state.textHeight).attr(`class`,`state-description`),c=!0,l=!0;n.descriptions.forEach(function(e){c||(r(s,e,l),l=!1),c=!1});let u=t.append(`line`).attr(`x1`,o().state.padding).attr(`y1`,o().state.padding+a+o().state.dividerMargin/2).attr(`y2`,o().state.padding+a+o().state.dividerMargin/2).attr(`class`,`descr-divider`),d=s.node().getBBox(),f=Math.max(d.width,i.width);return u.attr(`x2`,f+3*o().state.padding),t.insert(`rect`,`:first-child`).attr(`x`,o().state.padding).attr(`y`,o().state.padding).attr(`width`,f+2*o().state.padding).attr(`height`,d.height+a+2*o().state.padding).attr(`rx`,o().state.radius),t},`drawDescrState`),y=e((e,t,n)=>{let r=o().state.padding,i=2*o().state.padding,a=e.node().getBBox(),s=a.width,c=a.x,l=e.append(`text`).attr(`x`,0).attr(`y`,o().state.titleShift).attr(`font-size`,o().state.fontSize).attr(`class`,`state-title`).text(t.id),u=l.node().getBBox().width+i,d=Math.max(u,s);d===s&&(d+=i);let f,p=e.node().getBBox();t.doc,f=c-r,u>s&&(f=(s-d)/2+r),Math.abs(c-p.x)s&&(f=c-(u-s)/2);let m=1-o().state.textHeight;return e.insert(`rect`,`:first-child`).attr(`x`,f).attr(`y`,m).attr(`class`,n?`alt-composit`:`composit`).attr(`width`,d).attr(`height`,p.height+o().state.textHeight+o().state.titleShift+1).attr(`rx`,`0`),l.attr(`x`,f+r),u<=s&&l.attr(`x`,c+(d-i)/2-u/2+r),e.insert(`rect`,`:first-child`).attr(`x`,f).attr(`y`,o().state.titleShift-o().state.textHeight-o().state.padding).attr(`width`,d).attr(`height`,o().state.textHeight*3).attr(`rx`,o().state.radius),e.insert(`rect`,`:first-child`).attr(`x`,f).attr(`y`,o().state.titleShift-o().state.textHeight-o().state.padding).attr(`width`,d).attr(`height`,p.height+3+2*o().state.textHeight).attr(`rx`,o().state.radius),e},`addTitleAndBox`),b=e(e=>(e.append(`circle`).attr(`class`,`end-state-outer`).attr(`r`,o().state.sizeUnit+o().state.miniPadding).attr(`cx`,o().state.padding+o().state.sizeUnit+o().state.miniPadding).attr(`cy`,o().state.padding+o().state.sizeUnit+o().state.miniPadding),e.append(`circle`).attr(`class`,`end-state-inner`).attr(`r`,o().state.sizeUnit).attr(`cx`,o().state.padding+o().state.sizeUnit+2).attr(`cy`,o().state.padding+o().state.sizeUnit+2)),`drawEndState`),x=e((e,t)=>{let n=o().state.forkWidth,r=o().state.forkHeight;if(t.parentId){let e=n;n=r,r=e}return e.append(`rect`).style(`stroke`,`black`).style(`fill`,`black`).attr(`width`,n).attr(`height`,r).attr(`x`,o().state.padding).attr(`y`,o().state.padding)},`drawForkJoinState`),S=e((e,t,n,r)=>{let i=0,s=r.append(`text`);s.style(`text-anchor`,`start`),s.attr(`class`,`noteText`);let c=e.replace(/\r\n/g,`
`);c=c.replace(/\n/g,`
`);let l=c.split(a.lineBreakRegex),u=1.25*o().state.noteMargin;for(let e of l){let r=e.trim();if(r.length>0){let e=s.append(`tspan`);if(e.text(r),u===0){let t=e.node().getBBox();u+=t.height}i+=u,e.attr(`x`,t+o().state.noteMargin),e.attr(`y`,n+i+1.25*o().state.noteMargin)}}return{textWidth:s.node().getBBox().width,textHeight:i}},`_drawLongText`),C=e((e,t)=>{t.attr(`class`,`state-note`);let n=t.append(`rect`).attr(`x`,0).attr(`y`,o().state.padding),{textWidth:r,textHeight:i}=S(e,0,0,t.append(`g`));return n.attr(`height`,i+2*o().state.noteMargin),n.attr(`width`,r+o().state.noteMargin*2),n},`drawNote`),w=e(function(e,t){let n=t.id,r={id:n,label:t.id,width:0,height:0},i=e.append(`g`).attr(`id`,n).attr(`class`,`stateGroup`);t.type===`start`&&h(i),t.type===`end`&&b(i),(t.type===`fork`||t.type===`join`)&&x(i,t),t.type===`note`&&C(t.note.text,i),t.type===`divider`&&g(i),t.type==="default"&&t.descriptions.length===0&&_(i,t),t.type==="default"&&t.descriptions.length>0&&v(i,t);let a=i.node().getBBox();return r.width=a.width+2*o().state.padding,r.height=a.height+2*o().state.padding,r},`drawState`),T=0,E=e(function(n,i,u){let d=e(function(e){switch(e){case m.relationType.AGGREGATION:return`aggregation`;case m.relationType.EXTENSION:return`extension`;case m.relationType.COMPOSITION:return`composition`;case m.relationType.DEPENDENCY:return`dependency`}},`getRelationType`);i.points=i.points.filter(e=>!Number.isNaN(e.y));let f=i.points,p=l().x(function(e){return e.x}).y(function(e){return e.y}).curve(s),h=n.append(`path`).attr(`d`,p(f)).attr(`id`,`edge`+T).attr(`class`,`transition`),g=``;if(o().state.arrowMarkerAbsolute&&(g=r(!0)),h.attr(`marker-end`,`url(`+g+`#`+d(m.relationType.DEPENDENCY)+`End)`),u.title!==void 0){let e=n.append(`g`).attr(`class`,`stateLabel`),{x:r,y:s}=c.calcLabelPosition(i.points),l=a.getRows(u.title),d=0,f=[],p=0,m=0;for(let n=0;n<=l.length;n++){let i=e.append(`text`).attr(`text-anchor`,`middle`).text(l[n]).attr(`x`,r).attr(`y`,s+d),a=i.node().getBBox();p=Math.max(p,a.width),m=Math.min(m,a.x),t.info(a.x,r,s+d),d===0&&(d=i.node().getBBox().height,t.info(`Title height`,d,s)),f.push(i)}let h=d*l.length;if(l.length>1){let e=(l.length-1)*d*.5;f.forEach((t,n)=>t.attr(`y`,s+n*d-e)),h=d*l.length}let g=e.node().getBBox();e.insert(`rect`,`:first-child`).attr(`class`,`box`).attr(`x`,r-p/2-o().state.padding/2).attr(`y`,s-h/2-o().state.padding/2-3.5).attr(`width`,p+o().state.padding).attr(`height`,h+o().state.padding),t.info(g)}T++},`drawEdge`),D,O={},k=e(function(){},`setConf`),A=e(function(e){e.append(`defs`).append(`marker`).attr(`id`,`dependencyEnd`).attr(`refX`,19).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L9,13 L14,7 L9,1 Z`)},`insertMarkers`),j=e(function(e,r,a,s){D=o().state;let c=o().securityLevel,l;c===`sandbox`&&(l=n(`#i`+r));let u=n(c===`sandbox`?l.nodes()[0].contentDocument.body:`body`),d=c===`sandbox`?l.nodes()[0].contentDocument:document;t.debug(`Rendering diagram `+e);let f=u.select(`[id='${r}']`);A(f),N(s.db.getRootDoc(),f.append(`g`).attr(`id`,r+`-root`),void 0,!1,u,d,s);let p=D.padding,m=f.node().getBBox(),h=m.width+p*2,g=m.height+p*2;i(f,g,h*1.75,D.useMaxWidth),f.attr(`viewBox`,`${m.x-D.padding} ${m.y-D.padding} `+h+` `+g)},`draw`),M=e(e=>e?e.length*D.fontSizeFactor:1,`getLabelWidth`),N=e((e,n,r,i,o,s,c)=>{let l=new u({compound:!0,multigraph:!0}),f,p=!0;for(f=0;f{let t=e.parentElement,n=0,r=0;t&&(t.parentElement&&(n=t.parentElement.getBBox().width),r=parseInt(t.getAttribute(`data-x-shift`),10),Number.isNaN(r)&&(r=0)),e.setAttribute(`x1`,0-r+8),e.setAttribute(`x2`,n-r-8)})):t.debug(`No Node `+e+`: `+JSON.stringify(l.node(e)))});let b=v.getBBox();l.edges().forEach(function(e){e!==void 0&&l.edge(e)!==void 0&&(t.debug(`Edge `+e.v+` -> `+e.w+`: `+JSON.stringify(l.edge(e))),E(n,l.edge(e),l.edge(e).relation))}),b=v.getBBox();let x={id:r||`root`,label:r||`root`,width:0,height:0};return x.width=b.width+2*D.padding,x.height=b.height+2*D.padding,t.debug(`Doc rendered`,x,l),x},`renderDoc`),P={parser:p,get db(){return new m(1)},renderer:{setConf:k,draw:j},styles:f,init:e(e=>{e.state||={},e.state.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{P as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js b/.vercel/output/static/assets/stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js new file mode 100644 index 0000000..a370a28 --- /dev/null +++ b/.vercel/output/static/assets/stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import{i as t,n,r,t as i}from"./chunk-EX3LRPZG-CzaF5a2T.js";var a={parser:n,get db(){return new i(2)},renderer:r,styles:t,init:e(e=>{e.state||={},e.state.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{a as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/stateDiagram-v2-6OUMAXLB-Dko8ZR-a.js b/.vercel/output/static/assets/stateDiagram-v2-6OUMAXLB-Dko8ZR-a.js deleted file mode 100644 index 9413f42..0000000 --- a/.vercel/output/static/assets/stateDiagram-v2-6OUMAXLB-Dko8ZR-a.js +++ /dev/null @@ -1 +0,0 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-_wZywoZs.js";import"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import"./chunk-32BRIVSS-BtH22FN8.js";import"./chunk-XXDRQBXY-BuE3VzE_.js";import"./chunk-VR4S4FIN-BJzXasDJ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import"./chunk-ZGVPDNZ5-zo3h_nOA.js";import"./chunk-52WLFC77-BBAyrLn9.js";import"./chunk-FWX5IMBZ-CiLc9_ts.js";import{i as t,n,r,t as i}from"./chunk-EX3LRPZG-DRWNsKDf.js";var a={parser:n,get db(){return new i(2)},renderer:r,styles:t,init:e(e=>{e.state||={},e.state.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{a as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/styles-Dja5CCtV.css b/.vercel/output/static/assets/styles-Dja5CCtV.css deleted file mode 100644 index 95b79ca..0000000 --- a/.vercel/output/static/assets/styles-Dja5CCtV.css +++ /dev/null @@ -1,2 +0,0 @@ -/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */ -@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0}}}@layer theme{:root,:host{--font-sans:"Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, -apple-system, sans-serif;--font-mono:ui-monospace, "SF Mono", Menlo, Consolas, monospace;--color-orange-100:oklch(95.4% .038 75.164);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-500:oklch(76.9% .188 70.08);--color-sky-100:oklch(95.1% .026 236.824);--color-slate-200:oklch(92.9% .013 255.508);--color-zinc-200:oklch(92% .004 286.32);--color-zinc-800:oklch(27.4% .006 286.033);--color-neutral-100:oklch(97% 0 none);--color-neutral-300:oklch(87% 0 none);--color-neutral-500:oklch(55.6% 0 none);--color-neutral-700:oklch(37.1% 0 none);--color-neutral-800:oklch(26.9% 0 none);--color-neutral-900:oklch(20.5% 0 none);--color-stone-50:oklch(98.5% .001 106.423);--color-stone-100:oklch(97% .001 106.424);--color-stone-200:oklch(92.3% .003 48.717);--color-stone-700:oklch(37.4% .01 67.558);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-3xl:48rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wide:.025em;--tracking-widest:.1em;--leading-tight:1.25;--leading-snug:1.375;--leading-normal:1.5;--leading-relaxed:1.625;--radius-xs:.125rem;--radius-sm:.375rem;--radius-md:.5rem;--radius-lg:.75rem;--radius-xl:1rem;--radius-2xl:1rem;--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-background:#fff;--color-foreground:#1a1a1a;--color-card:#fff;--color-popover:#fff;--color-popover-foreground:#1a1a1a;--color-primary:#1a1a1a;--color-primary-foreground:#fafafa;--color-secondary:#f2f1ee;--color-secondary-foreground:#1a1a1a;--color-muted:#f2f1ee;--color-muted-foreground:#6b6b6b;--color-destructive:#c2410c;--color-destructive-foreground:#fafafa;--color-border:#e8e7e4;--color-ring:#a3a3a3;--color-sidebar:#f7f6f3;--color-sidebar-fg:#3f3f3f;--color-sidebar-border:#ebeae6;--color-sidebar-hover:#efeee9;--color-sidebar-active:#e8e7e2}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{border-color:var(--color-border)}html{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizelegibility}body{background-color:var(--color-background);font-family:var(--font-sans);color:var(--color-foreground);min-height:100dvh;margin:0}button:not(:disabled),[role=button]:not(:disabled){cursor:pointer}[contenteditable]:empty:before{content:attr(data-placeholder);color:#6b6b6b8c}@supports (color:color-mix(in lab, red, red)){[contenteditable]:empty:before{color:color-mix(in oklab, var(--color-muted-foreground) 55%, transparent)}}[contenteditable]:empty:before{pointer-events:none}*{scrollbar-width:thin;scrollbar-color:#1a1a1a2e transparent}@supports (color:color-mix(in lab, red, red)){*{scrollbar-color:color-mix(in oklab, var(--color-foreground) 18%, transparent) transparent}}}@layer components;@layer utilities{.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:0}.inset-y-0{inset-block:0}.top-1{top:var(--spacing)}.top-1\/2{top:50%}.top-3{top:calc(var(--spacing) * 3)}.top-\[18\%\]{top:18%}.right-1{right:var(--spacing)}.right-2{right:calc(var(--spacing) * 2)}.right-3{right:calc(var(--spacing) * 3)}.right-4{right:calc(var(--spacing) * 4)}.bottom-3{bottom:calc(var(--spacing) * 3)}.-left-12{left:calc(var(--spacing) * -12)}.left-0{left:0}.left-1{left:var(--spacing)}.left-1\/2{left:50%}.left-2{left:calc(var(--spacing) * 2)}.left-3{left:calc(var(--spacing) * 3)}.left-4{left:calc(var(--spacing) * 4)}.z-50{z-index:50}.z-\[100\]{z-index:100}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.-mx-4{margin-inline:calc(var(--spacing) * -4)}.mx-auto{margin-inline:auto}.my-1{margin-block:var(--spacing)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-2\.5{margin-top:calc(var(--spacing) * 2.5)}.mr-1{margin-right:var(--spacing)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mb-1{margin-bottom:var(--spacing)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.ml-1{margin-left:var(--spacing)}.ml-10{margin-left:calc(var(--spacing) * 10)}.ml-auto{margin-left:auto}.ml-px{margin-left:1px}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.size-1\.5{width:calc(var(--spacing) * 1.5);height:calc(var(--spacing) * 1.5)}.size-3{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.size-3\.5{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-5{width:calc(var(--spacing) * 5);height:calc(var(--spacing) * 5)}.size-6{width:calc(var(--spacing) * 6);height:calc(var(--spacing) * 6)}.size-7{width:calc(var(--spacing) * 7);height:calc(var(--spacing) * 7)}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.size-12{width:calc(var(--spacing) * 12);height:calc(var(--spacing) * 12)}.size-14{width:calc(var(--spacing) * 14);height:calc(var(--spacing) * 14)}.size-16{width:calc(var(--spacing) * 16);height:calc(var(--spacing) * 16)}.h-2{height:calc(var(--spacing) * 2)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-11{height:calc(var(--spacing) * 11)}.h-12{height:calc(var(--spacing) * 12)}.h-36{height:calc(var(--spacing) * 36)}.h-dvh{height:100dvh}.h-full{height:100%}.h-px{height:1px}.max-h-64{max-height:calc(var(--spacing) * 64)}.max-h-72{max-height:calc(var(--spacing) * 72)}.max-h-80{max-height:calc(var(--spacing) * 80)}.min-h-0{min-height:0}.min-h-16{min-height:calc(var(--spacing) * 16)}.min-h-dvh{min-height:100dvh}.min-h-screen{min-height:100vh}.w-0{width:0}.w-2{width:calc(var(--spacing) * 2)}.w-5{width:calc(var(--spacing) * 5)}.w-7{width:calc(var(--spacing) * 7)}.w-8{width:calc(var(--spacing) * 8)}.w-48{width:calc(var(--spacing) * 48)}.w-72{width:calc(var(--spacing) * 72)}.w-\[260px\]{width:260px}.w-\[calc\(100\%-2\.5rem\)\]{width:calc(100% - 2.5rem)}.w-\[calc\(100\%-2rem\)\]{width:calc(100% - 2rem)}.w-\[min\(280px\,88vw\)\]{width:min(280px,88vw)}.w-\[min\(560px\,calc\(100\%-2rem\)\)\]{width:min(560px,100% - 2rem)}.w-full{width:100%}.w-px{width:1px}.max-w-3xl{max-width:var(--container-3xl)}.max-w-\[140px\]{max-width:140px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.min-w-0{min-width:0}.min-w-40{min-width:calc(var(--spacing) * 40)}.min-w-44{min-width:calc(var(--spacing) * 44)}.min-w-\[260px\]{min-width:260px}.flex-1{flex:1}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x) var(--tw-scale-y)}.scale-\[0\.25\]{scale:.25}.rotate-90{rotate:90deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.animate-in{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.cursor-text{cursor:text}.touch-none{touch-action:none}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.grid-cols-8{grid-template-columns:repeat(8,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-2\.5{gap:calc(var(--spacing) * 2.5)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(var(--spacing) * var(--tw-space-y-reverse));margin-block-end:calc(var(--spacing) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-border{border-color:var(--color-border)}.border-destructive\/30{border-color:#c2410c4d}@supports (color:color-mix(in lab, red, red)){.border-destructive\/30{border-color:color-mix(in oklab, var(--color-destructive) 30%, transparent)}}.border-foreground\/25{border-color:#1a1a1a40}@supports (color:color-mix(in lab, red, red)){.border-foreground\/25{border-color:color-mix(in oklab, var(--color-foreground) 25%, transparent)}}.border-neutral-300{border-color:var(--color-neutral-300)}.border-primary{border-color:var(--color-primary)}.border-sidebar-border{border-color:var(--color-sidebar-border)}.border-t-transparent{border-top-color:#0000}.border-l-transparent{border-left-color:#0000}.bg-background{background-color:var(--color-background)}.bg-background\/90{background-color:#ffffffe6}@supports (color:color-mix(in lab, red, red)){.bg-background\/90{background-color:color-mix(in oklab, var(--color-background) 90%, transparent)}}.bg-black{background-color:var(--color-black)}.bg-black\/10{background-color:#0000001a}@supports (color:color-mix(in lab, red, red)){.bg-black\/10{background-color:color-mix(in oklab, var(--color-black) 10%, transparent)}}.bg-black\/40{background-color:#0006}@supports (color:color-mix(in lab, red, red)){.bg-black\/40{background-color:color-mix(in oklab, var(--color-black) 40%, transparent)}}.bg-border{background-color:var(--color-border)}.bg-card{background-color:var(--color-card)}.bg-destructive{background-color:var(--color-destructive)}.bg-destructive\/5{background-color:#c2410c0d}@supports (color:color-mix(in lab, red, red)){.bg-destructive\/5{background-color:color-mix(in oklab, var(--color-destructive) 5%, transparent)}}.bg-foreground{background-color:var(--color-foreground)}.bg-foreground\/80{background-color:#1a1a1acc}@supports (color:color-mix(in lab, red, red)){.bg-foreground\/80{background-color:color-mix(in oklab, var(--color-foreground) 80%, transparent)}}.bg-muted{background-color:var(--color-muted)}.bg-muted\/20{background-color:#f2f1ee33}@supports (color:color-mix(in lab, red, red)){.bg-muted\/20{background-color:color-mix(in oklab, var(--color-muted) 20%, transparent)}}.bg-muted\/30{background-color:#f2f1ee4d}@supports (color:color-mix(in lab, red, red)){.bg-muted\/30{background-color:color-mix(in oklab, var(--color-muted) 30%, transparent)}}.bg-muted\/40{background-color:#f2f1ee66}@supports (color:color-mix(in lab, red, red)){.bg-muted\/40{background-color:color-mix(in oklab, var(--color-muted) 40%, transparent)}}.bg-muted\/50{background-color:#f2f1ee80}@supports (color:color-mix(in lab, red, red)){.bg-muted\/50{background-color:color-mix(in oklab, var(--color-muted) 50%, transparent)}}.bg-muted\/60{background-color:#f2f1ee99}@supports (color:color-mix(in lab, red, red)){.bg-muted\/60{background-color:color-mix(in oklab, var(--color-muted) 60%, transparent)}}.bg-popover{background-color:var(--color-popover)}.bg-primary{background-color:var(--color-primary)}.bg-secondary{background-color:var(--color-secondary)}.bg-sidebar{background-color:var(--color-sidebar)}.bg-sidebar-active{background-color:var(--color-sidebar-active)}.bg-transparent{background-color:#0000}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-slate-200{--tw-gradient-from:var(--color-slate-200);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-stone-200{--tw-gradient-from:var(--color-stone-200);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-zinc-200{--tw-gradient-from:var(--color-zinc-200);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-zinc-800{--tw-gradient-from:var(--color-zinc-800);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.via-amber-100\/80{--tw-gradient-via:#fef3c6cc}@supports (color:color-mix(in lab, red, red)){.via-amber-100\/80{--tw-gradient-via:color-mix(in oklab, var(--color-amber-100) 80%, transparent)}}.via-amber-100\/80{--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-neutral-100{--tw-gradient-via:var(--color-neutral-100);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-sky-100\/70{--tw-gradient-via:#dff2feb3}@supports (color:color-mix(in lab, red, red)){.via-sky-100\/70{--tw-gradient-via:color-mix(in oklab, var(--color-sky-100) 70%, transparent)}}.via-sky-100\/70{--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-stone-700{--tw-gradient-via:var(--color-stone-700);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-neutral-800{--tw-gradient-to:var(--color-neutral-800);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-orange-100\/60{--tw-gradient-to:#ffedd599}@supports (color:color-mix(in lab, red, red)){.to-orange-100\/60{--tw-gradient-to:color-mix(in oklab, var(--color-orange-100) 60%, transparent)}}.to-orange-100\/60{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-stone-50{--tw-gradient-to:var(--color-stone-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-stone-100{--tw-gradient-to:var(--color-stone-100);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.fill-amber-400{fill:var(--color-amber-400)}.object-cover{object-fit:cover}.p-0{padding:0}.p-1{padding:var(--spacing)}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-\[16px\]{padding:16px}.p-px{padding:1px}.px-1{padding-inline:var(--spacing)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-3\.5{padding-inline:calc(var(--spacing) * 3.5)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-8{padding-block:calc(var(--spacing) * 8)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pr-1{padding-right:var(--spacing)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-3\.5{padding-right:calc(var(--spacing) * 3.5)}.pb-1{padding-bottom:var(--spacing)}.pb-32{padding-bottom:calc(var(--spacing) * 32)}.pl-1{padding-left:var(--spacing)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-8{padding-left:calc(var(--spacing) * 8)}.pl-10{padding-left:calc(var(--spacing) * 10)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[13px\]{font-size:13px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-snug{--tw-leading:var(--leading-snug);line-height:var(--leading-snug)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-balance{text-wrap:balance}.text-wrap{text-wrap:wrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-amber-500{color:var(--color-amber-500)}.text-background{color:var(--color-background)}.text-destructive{color:var(--color-destructive)}.text-destructive-foreground{color:var(--color-destructive-foreground)}.text-foreground{color:var(--color-foreground)}.text-muted-foreground{color:var(--color-muted-foreground)}.text-neutral-500{color:var(--color-neutral-500)}.text-popover-foreground{color:var(--color-popover-foreground)}.text-primary-foreground{color:var(--color-primary-foreground)}.text-secondary-foreground{color:var(--color-secondary-foreground)}.text-sidebar-fg{color:var(--color-sidebar-fg)}.text-white{color:var(--color-white)}.normal-case{text-transform:none}.uppercase{text-transform:uppercase}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.line-through{text-decoration-line:line-through}.underline-offset-4{text-underline-offset:4px}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.opacity-0{opacity:0}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a), 0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-0{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-border{--tw-ring-color:var(--color-border)}.ring-ring{--tw-ring-color:var(--color-ring)}.outline,.outline-1{outline-style:var(--tw-outline-style);outline-width:1px}.-outline-offset-1{outline-offset:calc(1px * -1)}.outline-black\/10{outline-color:#0000001a}@supports (color:color-mix(in lab, red, red)){.outline-black\/10{outline-color:color-mix(in oklab, var(--color-black) 10%, transparent)}}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.blur-\[4px\]{--tw-blur:blur(4px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.blur-none{--tw-blur: ;filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.grayscale{--tw-grayscale:grayscale(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.sepia{--tw-sepia:sepia(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[background-color\,color\,opacity\,box-shadow\,transform\]{transition-property:background-color,color,opacity,box-shadow,transform;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[box-shadow\]{transition-property:box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[opacity\,filter\,scale\]{transition-property:opacity,filter,scale;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[scale\,background-color\]{transition-property:scale,background-color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[scale\,opacity\,filter\]{transition-property:scale,opacity,filter;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[width\,opacity\]{transition-property:width,opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-\[cubic-bezier\(0\.2\,0\,0\,1\)\]{--tw-ease:cubic-bezier(.2,0,0,1);transition-timing-function:cubic-bezier(.2,0,0,1)}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.fade-in-0{--tw-enter-opacity:0}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.zoom-in-95{--tw-enter-scale:.95}.paused{animation-play-state:paused}.running{animation-play-state:running}.zoom-in{--tw-enter-scale:0}.group-focus-within\:opacity-100:is(:where(.group):focus-within *){opacity:1}@media (hover:hover){.group-hover\:opacity-100:is(:where(.group):hover *),.group-hover\/cover\:opacity-100:is(:where(.group\/cover):hover *){opacity:1}}.placeholder\:text-muted-foreground::placeholder{color:var(--color-muted-foreground)}.placeholder\:text-muted-foreground\/50::placeholder{color:#6b6b6b80}@supports (color:color-mix(in lab, red, red)){.placeholder\:text-muted-foreground\/50::placeholder{color:color-mix(in oklab, var(--color-muted-foreground) 50%, transparent)}}.placeholder\:text-muted-foreground\/60::placeholder{color:#6b6b6b99}@supports (color:color-mix(in lab, red, red)){.placeholder\:text-muted-foreground\/60::placeholder{color:color-mix(in oklab, var(--color-muted-foreground) 60%, transparent)}}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:top-1\/2:after{content:var(--tw-content);top:50%}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:size-10:after{content:var(--tw-content);width:calc(var(--spacing) * 10);height:calc(var(--spacing) * 10)}.after\:-translate-1\/2:after{content:var(--tw-content);--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}@media (hover:hover){.hover\:border-foreground\/40:hover{border-color:#1a1a1a66}@supports (color:color-mix(in lab, red, red)){.hover\:border-foreground\/40:hover{border-color:color-mix(in oklab, var(--color-foreground) 40%, transparent)}}.hover\:bg-black\/5:hover{background-color:#0000000d}@supports (color:color-mix(in lab, red, red)){.hover\:bg-black\/5:hover{background-color:color-mix(in oklab, var(--color-black) 5%, transparent)}}.hover\:bg-destructive\/90:hover{background-color:#c2410ce6}@supports (color:color-mix(in lab, red, red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab, var(--color-destructive) 90%, transparent)}}.hover\:bg-muted:hover{background-color:var(--color-muted)}.hover\:bg-muted\/70:hover{background-color:#f2f1eeb3}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/70:hover{background-color:color-mix(in oklab, var(--color-muted) 70%, transparent)}}.hover\:bg-muted\/80:hover{background-color:#f2f1eecc}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/80:hover{background-color:color-mix(in oklab, var(--color-muted) 80%, transparent)}}.hover\:bg-neutral-100:hover{background-color:var(--color-neutral-100)}.hover\:bg-primary\/90:hover{background-color:#1a1a1ae6}@supports (color:color-mix(in lab, red, red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab, var(--color-primary) 90%, transparent)}}.hover\:bg-secondary\/80:hover{background-color:#f2f1eecc}@supports (color:color-mix(in lab, red, red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab, var(--color-secondary) 80%, transparent)}}.hover\:bg-sidebar-hover:hover{background-color:var(--color-sidebar-hover)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}}.focus\:bg-muted:focus{background-color:var(--color-muted)}.focus\:text-destructive:focus{color:var(--color-destructive)}.focus\:ring-0:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-ring\/40:focus{--tw-ring-color:#a3a3a366}@supports (color:color-mix(in lab, red, red)){.focus\:ring-ring\/40:focus{--tw-ring-color:color-mix(in oklab, var(--color-ring) 40%, transparent)}}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-ring\/40:focus-visible{--tw-ring-color:#a3a3a366}@supports (color:color-mix(in lab, red, red)){.focus-visible\:ring-ring\/40:focus-visible{--tw-ring-color:color-mix(in oklab, var(--color-ring) 40%, transparent)}}.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.active\:scale-\[0\.96\]:active{scale:.96}.active\:scale-\[0\.98\]:active{scale:.98}.active\:not-disabled\:scale-\[0\.96\]:active:not(:disabled){scale:.96}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.aria-selected\:bg-muted[aria-selected=true]{background-color:var(--color-muted)}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale:.95}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:bg-muted[data-state=open]{background-color:var(--color-muted)}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale:.95}@media not all and (width>=40rem){.max-sm\:-left-10{left:calc(var(--spacing) * -10)}}@media (width>=40rem){.sm\:-mx-6{margin-inline:calc(var(--spacing) * -6)}.sm\:ml-12{margin-left:calc(var(--spacing) * 12)}.sm\:flex{display:flex}.sm\:inline{display:inline}.sm\:inline-flex{display:inline-flex}.sm\:h-44{height:calc(var(--spacing) * 44)}.sm\:w-\[calc\(100\%-3rem\)\]{width:calc(100% - 3rem)}.sm\:max-w-\[200px\]{max-width:200px}.sm\:px-3{padding-inline:calc(var(--spacing) * 3)}.sm\:px-12{padding-inline:calc(var(--spacing) * 12)}.sm\:pt-8{padding-top:calc(var(--spacing) * 8)}.sm\:pl-12{padding-left:calc(var(--spacing) * 12)}}@media (width>=48rem){.md\:block{display:block}.md\:hidden{display:none}.md\:inline-flex{display:inline-flex}}.dark\:border-neutral-700:is(.dark *){border-color:var(--color-neutral-700)}.dark\:bg-white\/20:is(.dark *){background-color:#fff3}@supports (color:color-mix(in lab, red, red)){.dark\:bg-white\/20:is(.dark *){background-color:color-mix(in oklab, var(--color-white) 20%, transparent)}}.dark\:outline-white\/10:is(.dark *){outline-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.dark\:outline-white\/10:is(.dark *){outline-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}@media (hover:hover){.dark\:hover\:bg-neutral-900:is(.dark *):hover{background-color:var(--color-neutral-900)}.dark\:hover\:bg-white\/10:is(.dark *):hover{background-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.dark\:hover\:bg-white\/10:is(.dark *):hover{background-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-block:calc(var(--spacing) * 1.5)}.\[\&_\[cmdk-group-heading\]\]\:text-\[11px\] [cmdk-group-heading]{font-size:11px}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\[\&_\[cmdk-group-heading\]\]\:tracking-wide [cmdk-group-heading]{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:var(--color-muted-foreground)}.\[\&_\[cmdk-group-heading\]\]\:uppercase [cmdk-group-heading]{text-transform:uppercase}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:mx-auto svg{margin-inline:auto}.\[\&_svg\]\:size-4 svg{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&_svg\]\:max-w-full svg{max-width:100%}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}}@property --tw-animation-delay{syntax:"*";inherits:false;initial-value:0s}@property --tw-animation-direction{syntax:"*";inherits:false;initial-value:normal}@property --tw-animation-duration{syntax:"*";inherits:false}@property --tw-animation-fill-mode{syntax:"*";inherits:false;initial-value:none}@property --tw-animation-iteration-count{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-translate-y{syntax:"*";inherits:false;initial-value:0}.dark{--color-background:#191919;--color-foreground:#e8e8e8;--color-card:#202020;--color-card-foreground:#e8e8e8;--color-popover:#252525;--color-popover-foreground:#e8e8e8;--color-primary:#e8e8e8;--color-primary-foreground:#191919;--color-secondary:#2a2a2a;--color-secondary-foreground:#e8e8e8;--color-muted:#2a2a2a;--color-muted-foreground:#9b9b9b;--color-accent:#2a2a2a;--color-accent-foreground:#e8e8e8;--color-destructive:#ea580c;--color-destructive-foreground:#fafafa;--color-border:#333;--color-input:#333;--color-ring:#6b6b6b;--color-sidebar:#202020;--color-sidebar-fg:#cfcfcf;--color-sidebar-border:#2e2e2e;--color-sidebar-hover:#2a2a2a;--color-sidebar-active:#2f2f2f}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-content{syntax:"*";inherits:false;initial-value:""}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0)scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1))rotate(var(--tw-enter-rotate,0));filter:blur(var(--tw-enter-blur,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0)scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1))rotate(var(--tw-exit-rotate,0));filter:blur(var(--tw-exit-blur,0))}} diff --git a/.vercel/output/static/assets/styles-Peq6Rcdg.css b/.vercel/output/static/assets/styles-Peq6Rcdg.css new file mode 100644 index 0000000..e9b9b31 --- /dev/null +++ b/.vercel/output/static/assets/styles-Peq6Rcdg.css @@ -0,0 +1,2 @@ +/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-pan-x:initial;--tw-pan-y:initial;--tw-pinch-zoom:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0}}}@layer theme{:root,:host{--font-sans:"Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, -apple-system, sans-serif;--font-mono:ui-monospace, "SF Mono", Menlo, Consolas, monospace;--color-orange-100:oklch(95.4% .038 75.164);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-950:oklch(27.9% .077 45.635);--color-emerald-200:oklch(90.5% .093 164.15);--color-emerald-300:oklch(84.5% .143 164.978);--color-emerald-500:oklch(69.6% .17 162.48);--color-emerald-600:oklch(59.6% .145 163.225);--color-emerald-700:oklch(50.8% .118 165.612);--color-emerald-800:oklch(43.2% .095 166.913);--color-emerald-900:oklch(37.8% .077 168.94);--color-sky-100:oklch(95.1% .026 236.824);--color-slate-200:oklch(92.9% .013 255.508);--color-zinc-200:oklch(92% .004 286.32);--color-zinc-800:oklch(27.4% .006 286.033);--color-neutral-100:oklch(97% 0 none);--color-neutral-300:oklch(87% 0 none);--color-neutral-500:oklch(55.6% 0 none);--color-neutral-700:oklch(37.1% 0 none);--color-neutral-800:oklch(26.9% 0 none);--color-neutral-900:oklch(20.5% 0 none);--color-stone-50:oklch(98.5% .001 106.423);--color-stone-100:oklch(97% .001 106.424);--color-stone-200:oklch(92.3% .003 48.717);--color-stone-700:oklch(37.4% .01 67.558);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-2xl:42rem;--container-3xl:48rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wide:.025em;--tracking-widest:.1em;--leading-tight:1.25;--leading-snug:1.375;--leading-normal:1.5;--leading-relaxed:1.625;--radius-xs:.125rem;--radius-sm:.375rem;--radius-md:.5rem;--radius-lg:.75rem;--radius-xl:1rem;--radius-2xl:1rem;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-background:#fff;--color-foreground:#1a1a1a;--color-card:#fff;--color-popover:#fff;--color-popover-foreground:#1a1a1a;--color-primary:#1a1a1a;--color-primary-foreground:#fafafa;--color-secondary:#f2f1ee;--color-secondary-foreground:#1a1a1a;--color-muted:#f2f1ee;--color-muted-foreground:#6b6b6b;--color-accent:#f2f1ee;--color-destructive:#c2410c;--color-destructive-foreground:#fafafa;--color-border:#e8e7e4;--color-input:#e8e7e4;--color-ring:#a3a3a3;--color-sidebar:#f7f6f3;--color-sidebar-fg:#3f3f3f;--color-sidebar-border:#ebeae6;--color-sidebar-hover:#efeee9;--color-sidebar-active:#e8e7e2}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{border-color:var(--color-border)}html{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizelegibility}body{background-color:var(--color-background);font-family:var(--font-sans);color:var(--color-foreground);min-height:100dvh;margin:0}button:not(:disabled),[role=button]:not(:disabled){cursor:pointer}[contenteditable]:empty:before{content:attr(data-placeholder);color:#6b6b6b8c}@supports (color:color-mix(in lab, red, red)){[contenteditable]:empty:before{color:color-mix(in oklab, var(--color-muted-foreground) 55%, transparent)}}[contenteditable]:empty:before{pointer-events:none}*{scrollbar-width:thin;scrollbar-color:#1a1a1a2e transparent}@supports (color:color-mix(in lab, red, red)){*{scrollbar-color:color-mix(in oklab, var(--color-foreground) 18%, transparent) transparent}}}@layer components;@layer utilities{.\@container{container-type:inline-size}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.not-sr-only{clip-path:none;white-space:normal;width:auto;height:auto;margin:0;padding:0;position:static;overflow:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:0}.inset-y-0{inset-block:0}.top-1{top:var(--spacing)}.top-1\/2{top:50%}.top-3{top:calc(var(--spacing) * 3)}.top-\[18\%\]{top:18%}.right-1{right:var(--spacing)}.right-2{right:calc(var(--spacing) * 2)}.right-3{right:calc(var(--spacing) * 3)}.right-4{right:calc(var(--spacing) * 4)}.bottom-3{bottom:calc(var(--spacing) * 3)}.-left-12{left:calc(var(--spacing) * -12)}.left-0{left:0}.left-1{left:var(--spacing)}.left-1\/2{left:50%}.left-2{left:calc(var(--spacing) * 2)}.left-3{left:calc(var(--spacing) * 3)}.left-4{left:calc(var(--spacing) * 4)}.isolate{isolation:isolate}.isolation-auto{isolation:auto}.z-0{z-index:0}.z-10{z-index:10}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[120\]{z-index:120}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.-mx-4{margin-inline:calc(var(--spacing) * -4)}.mx-3{margin-inline:calc(var(--spacing) * 3)}.mx-auto{margin-inline:auto}.my-1{margin-block:var(--spacing)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-2\.5{margin-top:calc(var(--spacing) * 2.5)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mr-1{margin-right:var(--spacing)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mb-0\.5{margin-bottom:calc(var(--spacing) * .5)}.mb-1{margin-bottom:var(--spacing)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.ml-1{margin-left:var(--spacing)}.ml-10{margin-left:calc(var(--spacing) * 10)}.ml-auto{margin-left:auto}.ml-px{margin-left:1px}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-4{-webkit-line-clamp:4;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.block{display:block}.contents{display:contents}.flex{display:flex}.flow-root{display:flow-root}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.inline-grid{display:inline-grid}.inline-table{display:inline-table}.list-item{display:list-item}.table{display:table}.table-caption{display:table-caption}.table-cell{display:table-cell}.table-column{display:table-column}.table-column-group{display:table-column-group}.table-footer-group{display:table-footer-group}.table-header-group{display:table-header-group}.table-row{display:table-row}.table-row-group{display:table-row-group}.size-1{width:var(--spacing);height:var(--spacing)}.size-1\.5{width:calc(var(--spacing) * 1.5);height:calc(var(--spacing) * 1.5)}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.size-3{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.size-3\.5{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-5{width:calc(var(--spacing) * 5);height:calc(var(--spacing) * 5)}.size-6{width:calc(var(--spacing) * 6);height:calc(var(--spacing) * 6)}.size-7{width:calc(var(--spacing) * 7);height:calc(var(--spacing) * 7)}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.size-12{width:calc(var(--spacing) * 12);height:calc(var(--spacing) * 12)}.size-16{width:calc(var(--spacing) * 16);height:calc(var(--spacing) * 16)}.h-2{height:calc(var(--spacing) * 2)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-11{height:calc(var(--spacing) * 11)}.h-12{height:calc(var(--spacing) * 12)}.h-36{height:calc(var(--spacing) * 36)}.h-40{height:calc(var(--spacing) * 40)}.h-84{height:calc(var(--spacing) * 84)}.h-120{height:calc(var(--spacing) * 120)}.h-dvh{height:100dvh}.h-full{height:100%}.h-px{height:1px}.max-h-40{max-height:calc(var(--spacing) * 40)}.max-h-48{max-height:calc(var(--spacing) * 48)}.max-h-64{max-height:calc(var(--spacing) * 64)}.max-h-72{max-height:calc(var(--spacing) * 72)}.max-h-80{max-height:calc(var(--spacing) * 80)}.max-h-\[90vh\]{max-height:90vh}.min-h-0{min-height:0}.min-h-16{min-height:calc(var(--spacing) * 16)}.min-h-\[64px\]{min-height:64px}.min-h-dvh{min-height:100dvh}.min-h-screen{min-height:100vh}.w-0{width:0}.w-2{width:calc(var(--spacing) * 2)}.w-5{width:calc(var(--spacing) * 5)}.w-7{width:calc(var(--spacing) * 7)}.w-8{width:calc(var(--spacing) * 8)}.w-48{width:calc(var(--spacing) * 48)}.w-72{width:calc(var(--spacing) * 72)}.w-\[260px\]{width:260px}.w-\[calc\(100\%-2\.5rem\)\]{width:calc(100% - 2.5rem)}.w-\[calc\(100\%-2rem\)\]{width:calc(100% - 2rem)}.w-\[min\(280px\,88vw\)\]{width:min(280px,88vw)}.w-\[min\(560px\,calc\(100\%-2rem\)\)\]{width:min(560px,100% - 2rem)}.w-full{width:100%}.w-px{width:1px}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-\[140px\]{max-width:140px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.min-w-0{min-width:0}.min-w-40{min-width:calc(var(--spacing) * 40)}.min-w-44{min-width:calc(var(--spacing) * 44)}.min-w-\[260px\]{min-width:260px}.flex-1{flex:1}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-none{translate:none}.scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x) var(--tw-scale-y)}.scale-3d{scale:var(--tw-scale-x) var(--tw-scale-y) var(--tw-scale-z)}.scale-\[0\.25\]{scale:.25}.rotate-90{rotate:90deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.transform\!{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)!important}.animate-in{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.cursor-text{cursor:text}.touch-pinch-zoom{--tw-pinch-zoom:pinch-zoom;touch-action:var(--tw-pan-x,) var(--tw-pan-y,) var(--tw-pinch-zoom,)}.touch-none{touch-action:none}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.grid-cols-8{grid-template-columns:repeat(8,minmax(0,1fr))}.grid-cols-\[auto_1fr\]{grid-template-columns:auto 1fr}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-0{gap:0}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-2\.5{gap:calc(var(--spacing) * 2.5)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(var(--spacing) * var(--tw-space-y-reverse));margin-block-end:calc(var(--spacing) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-reverse>:not(:last-child)){--tw-space-y-reverse:1}.gap-x-4{column-gap:calc(var(--spacing) * 4)}:where(.space-x-reverse>:not(:last-child)){--tw-space-x-reverse:1}.gap-y-2{row-gap:calc(var(--spacing) * 2)}:where(.divide-x>:not(:last-child)){--tw-divide-x-reverse:0;border-inline-style:var(--tw-border-style);border-inline-start-width:calc(1px * var(--tw-divide-x-reverse));border-inline-end-width:calc(1px * calc(1 - var(--tw-divide-x-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-y-reverse>:not(:last-child)){--tw-divide-y-reverse:1}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-s{border-start-start-radius:.25rem;border-end-start-radius:.25rem}.rounded-ss{border-start-start-radius:.25rem}.rounded-e{border-start-end-radius:.25rem;border-end-end-radius:.25rem}.rounded-se{border-start-end-radius:.25rem}.rounded-ee{border-end-end-radius:.25rem}.rounded-es{border-end-start-radius:.25rem}.rounded-t{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.rounded-l{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.rounded-tl{border-top-left-radius:.25rem}.rounded-r{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.rounded-tr{border-top-right-radius:.25rem}.rounded-b{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.rounded-br{border-bottom-right-radius:.25rem}.rounded-bl{border-bottom-left-radius:.25rem}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-x{border-inline-style:var(--tw-border-style);border-inline-width:1px}.border-y{border-block-style:var(--tw-border-style);border-block-width:1px}.border-s{border-inline-start-style:var(--tw-border-style);border-inline-start-width:1px}.border-e{border-inline-end-style:var(--tw-border-style);border-inline-end-width:1px}.border-bs{border-block-start-style:var(--tw-border-style);border-block-start-width:1px}.border-be{border-block-end-style:var(--tw-border-style);border-block-end-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-amber-500\/30{border-color:#f99c004d}@supports (color:color-mix(in lab, red, red)){.border-amber-500\/30{border-color:color-mix(in oklab, var(--color-amber-500) 30%, transparent)}}.border-border{border-color:var(--color-border)}.border-destructive\/30{border-color:#c2410c4d}@supports (color:color-mix(in lab, red, red)){.border-destructive\/30{border-color:color-mix(in oklab, var(--color-destructive) 30%, transparent)}}.border-emerald-500\/40{border-color:#00bb7f66}@supports (color:color-mix(in lab, red, red)){.border-emerald-500\/40{border-color:color-mix(in oklab, var(--color-emerald-500) 40%, transparent)}}.border-foreground{border-color:var(--color-foreground)}.border-foreground\/25{border-color:#1a1a1a40}@supports (color:color-mix(in lab, red, red)){.border-foreground\/25{border-color:color-mix(in oklab, var(--color-foreground) 25%, transparent)}}.border-neutral-300{border-color:var(--color-neutral-300)}.border-primary{border-color:var(--color-primary)}.border-sidebar-border{border-color:var(--color-sidebar-border)}.border-transparent{border-color:#0000}.border-t-transparent{border-top-color:#0000}.border-l-transparent{border-left-color:#0000}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab, red, red)){.bg-amber-500\/10{background-color:color-mix(in oklab, var(--color-amber-500) 10%, transparent)}}.bg-background{background-color:var(--color-background)}.bg-background\/90{background-color:#ffffffe6}@supports (color:color-mix(in lab, red, red)){.bg-background\/90{background-color:color-mix(in oklab, var(--color-background) 90%, transparent)}}.bg-black{background-color:var(--color-black)}.bg-black\/5{background-color:#0000000d}@supports (color:color-mix(in lab, red, red)){.bg-black\/5{background-color:color-mix(in oklab, var(--color-black) 5%, transparent)}}.bg-black\/10{background-color:#0000001a}@supports (color:color-mix(in lab, red, red)){.bg-black\/10{background-color:color-mix(in oklab, var(--color-black) 10%, transparent)}}.bg-black\/40{background-color:#0006}@supports (color:color-mix(in lab, red, red)){.bg-black\/40{background-color:color-mix(in oklab, var(--color-black) 40%, transparent)}}.bg-border{background-color:var(--color-border)}.bg-card{background-color:var(--color-card)}.bg-destructive{background-color:var(--color-destructive)}.bg-destructive\/5{background-color:#c2410c0d}@supports (color:color-mix(in lab, red, red)){.bg-destructive\/5{background-color:color-mix(in oklab, var(--color-destructive) 5%, transparent)}}.bg-destructive\/10{background-color:#c2410c1a}@supports (color:color-mix(in lab, red, red)){.bg-destructive\/10{background-color:color-mix(in oklab, var(--color-destructive) 10%, transparent)}}.bg-emerald-500{background-color:var(--color-emerald-500)}.bg-emerald-500\/10{background-color:#00bb7f1a}@supports (color:color-mix(in lab, red, red)){.bg-emerald-500\/10{background-color:color-mix(in oklab, var(--color-emerald-500) 10%, transparent)}}.bg-emerald-500\/15{background-color:#00bb7f26}@supports (color:color-mix(in lab, red, red)){.bg-emerald-500\/15{background-color:color-mix(in oklab, var(--color-emerald-500) 15%, transparent)}}.bg-foreground{background-color:var(--color-foreground)}.bg-foreground\/80{background-color:#1a1a1acc}@supports (color:color-mix(in lab, red, red)){.bg-foreground\/80{background-color:color-mix(in oklab, var(--color-foreground) 80%, transparent)}}.bg-muted{background-color:var(--color-muted)}.bg-muted-foreground\/40{background-color:#6b6b6b66}@supports (color:color-mix(in lab, red, red)){.bg-muted-foreground\/40{background-color:color-mix(in oklab, var(--color-muted-foreground) 40%, transparent)}}.bg-muted\/20{background-color:#f2f1ee33}@supports (color:color-mix(in lab, red, red)){.bg-muted\/20{background-color:color-mix(in oklab, var(--color-muted) 20%, transparent)}}.bg-muted\/30{background-color:#f2f1ee4d}@supports (color:color-mix(in lab, red, red)){.bg-muted\/30{background-color:color-mix(in oklab, var(--color-muted) 30%, transparent)}}.bg-muted\/40{background-color:#f2f1ee66}@supports (color:color-mix(in lab, red, red)){.bg-muted\/40{background-color:color-mix(in oklab, var(--color-muted) 40%, transparent)}}.bg-muted\/50{background-color:#f2f1ee80}@supports (color:color-mix(in lab, red, red)){.bg-muted\/50{background-color:color-mix(in oklab, var(--color-muted) 50%, transparent)}}.bg-muted\/60{background-color:#f2f1ee99}@supports (color:color-mix(in lab, red, red)){.bg-muted\/60{background-color:color-mix(in oklab, var(--color-muted) 60%, transparent)}}.bg-popover{background-color:var(--color-popover)}.bg-primary{background-color:var(--color-primary)}.bg-secondary{background-color:var(--color-secondary)}.bg-sidebar{background-color:var(--color-sidebar)}.bg-sidebar-active{background-color:var(--color-sidebar-active)}.bg-transparent{background-color:#0000}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-slate-200{--tw-gradient-from:var(--color-slate-200);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-stone-200{--tw-gradient-from:var(--color-stone-200);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-zinc-200{--tw-gradient-from:var(--color-zinc-200);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-zinc-800{--tw-gradient-from:var(--color-zinc-800);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.via-amber-100\/80{--tw-gradient-via:#fef3c6cc}@supports (color:color-mix(in lab, red, red)){.via-amber-100\/80{--tw-gradient-via:color-mix(in oklab, var(--color-amber-100) 80%, transparent)}}.via-amber-100\/80{--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-neutral-100{--tw-gradient-via:var(--color-neutral-100);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-sky-100\/70{--tw-gradient-via:#dff2feb3}@supports (color:color-mix(in lab, red, red)){.via-sky-100\/70{--tw-gradient-via:color-mix(in oklab, var(--color-sky-100) 70%, transparent)}}.via-sky-100\/70{--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-stone-700{--tw-gradient-via:var(--color-stone-700);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-neutral-800{--tw-gradient-to:var(--color-neutral-800);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-orange-100\/60{--tw-gradient-to:#ffedd599}@supports (color:color-mix(in lab, red, red)){.to-orange-100\/60{--tw-gradient-to:color-mix(in oklab, var(--color-orange-100) 60%, transparent)}}.to-orange-100\/60{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-stone-50{--tw-gradient-to:var(--color-stone-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-stone-100{--tw-gradient-to:var(--color-stone-100);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.bg-repeat{background-repeat:repeat}.mask-no-clip{-webkit-mask-clip:no-clip;mask-clip:no-clip}.mask-repeat{-webkit-mask-repeat:repeat;mask-repeat:repeat}.fill-amber-400{fill:var(--color-amber-400)}.object-cover{object-fit:cover}.p-0{padding:0}.p-1{padding:var(--spacing)}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-\[16px\]{padding:16px}.p-px{padding:1px}.px-1{padding-inline:var(--spacing)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-3\.5{padding-inline:calc(var(--spacing) * 3.5)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-5{padding-block:calc(var(--spacing) * 5)}.py-8{padding-block:calc(var(--spacing) * 8)}.py-12{padding-block:calc(var(--spacing) * 12)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-6{padding-top:calc(var(--spacing) * 6)}.pr-1{padding-right:var(--spacing)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-3\.5{padding-right:calc(var(--spacing) * 3.5)}.pb-1{padding-bottom:var(--spacing)}.pb-32{padding-bottom:calc(var(--spacing) * 32)}.pl-1{padding-left:var(--spacing)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-7{padding-left:calc(var(--spacing) * 7)}.pl-8{padding-left:calc(var(--spacing) * 8)}.pl-10{padding-left:calc(var(--spacing) * 10)}.pl-12{padding-left:calc(var(--spacing) * 12)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[13px\]{font-size:13px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-snug{--tw-leading:var(--leading-snug);line-height:var(--leading-snug)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-balance{text-wrap:balance}.text-wrap{text-wrap:wrap}.text-clip{text-overflow:clip}.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-amber-500{color:var(--color-amber-500)}.text-amber-950{color:var(--color-amber-950)}.text-background{color:var(--color-background)}.text-destructive{color:var(--color-destructive)}.text-destructive-foreground{color:var(--color-destructive-foreground)}.text-emerald-600{color:var(--color-emerald-600)}.text-emerald-700{color:var(--color-emerald-700)}.text-emerald-800{color:var(--color-emerald-800)}.text-emerald-900{color:var(--color-emerald-900)}.text-foreground{color:var(--color-foreground)}.text-muted-foreground{color:var(--color-muted-foreground)}.text-neutral-500{color:var(--color-neutral-500)}.text-popover-foreground{color:var(--color-popover-foreground)}.text-primary-foreground{color:var(--color-primary-foreground)}.text-secondary-foreground{color:var(--color-secondary-foreground)}.text-sidebar-fg{color:var(--color-sidebar-fg)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.normal-case{text-transform:none}.uppercase{text-transform:uppercase}.italic{font-style:italic}.italic\!{font-style:italic!important}.not-italic{font-style:normal}.diagonal-fractions{--tw-numeric-fraction:diagonal-fractions;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.lining-nums{--tw-numeric-figure:lining-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.oldstyle-nums{--tw-numeric-figure:oldstyle-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.ordinal{--tw-ordinal:ordinal;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.proportional-nums{--tw-numeric-spacing:proportional-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.slashed-zero{--tw-slashed-zero:slashed-zero;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.stacked-fractions{--tw-numeric-fraction:stacked-fractions;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.normal-nums{font-variant-numeric:normal}.line-through{text-decoration-line:line-through}.no-underline{text-decoration-line:none}.overline{text-decoration-line:overline}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.subpixel-antialiased{-webkit-font-smoothing:auto;-moz-osx-font-smoothing:auto}.opacity-0{opacity:0}.opacity-1{opacity:.01}.opacity-40{opacity:.4}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-80{opacity:.8}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a), 0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-0{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.inset-ring{--tw-inset-ring-shadow:inset 0 0 0 1px var(--tw-inset-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-border{--tw-ring-color:var(--color-border)}.ring-ring{--tw-ring-color:var(--color-ring)}.outline,.outline-1{outline-style:var(--tw-outline-style);outline-width:1px}.-outline-offset-1{outline-offset:calc(1px * -1)}.outline-black\/10{outline-color:#0000001a}@supports (color:color-mix(in lab, red, red)){.outline-black\/10{outline-color:color-mix(in oklab, var(--color-black) 10%, transparent)}}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.blur\!{--tw-blur:blur(8px)!important;filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)!important}.blur-\[4px\]{--tw-blur:blur(4px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.blur-none{--tw-blur: ;filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.drop-shadow{--tw-drop-shadow-size:drop-shadow(0 1px 2px var(--tw-drop-shadow-color,#0000001a)) drop-shadow(0 1px 1px var(--tw-drop-shadow-color,#0000000f));--tw-drop-shadow:drop-shadow(0 1px 2px #0000001a) drop-shadow(0 1px 1px #0000000f);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.grayscale{--tw-grayscale:grayscale(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.sepia{--tw-sepia:sepia(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-grayscale{--tw-backdrop-grayscale:grayscale(100%);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-invert{--tw-backdrop-invert:invert(100%);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-sepia{--tw-backdrop-sepia:sepia(100%);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[background-color\,color\,opacity\,box-shadow\,transform\]{transition-property:background-color,color,opacity,box-shadow,transform;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[box-shadow\]{transition-property:box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[opacity\,filter\,scale\]{transition-property:opacity,filter,scale;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[scale\,background-color\]{transition-property:scale,background-color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[scale\,opacity\,filter\]{transition-property:scale,opacity,filter;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[width\,opacity\]{transition-property:width,opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-\[cubic-bezier\(0\.2\,0\,0\,1\)\]{--tw-ease:cubic-bezier(.2,0,0,1);transition-timing-function:cubic-bezier(.2,0,0,1)}.ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.fade-in-0{--tw-enter-opacity:0}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.zoom-in-95{--tw-enter-scale:.95}:where(.divide-x-reverse>:not(:last-child)){--tw-divide-x-reverse:1}.paused{animation-play-state:paused}.ring-inset{--tw-ring-inset:inset}.running{animation-play-state:running}.zoom-in{--tw-enter-scale:0}.zoom-out{--tw-exit-scale:0}@media (hover:hover){.group-hover\:opacity-100:is(:where(.group):hover *),.group-hover\/cover\:opacity-100:is(:where(.group\/cover):hover *){opacity:1}}.placeholder\:text-muted-foreground::placeholder{color:var(--color-muted-foreground)}.placeholder\:text-muted-foreground\/50::placeholder{color:#6b6b6b80}@supports (color:color-mix(in lab, red, red)){.placeholder\:text-muted-foreground\/50::placeholder{color:color-mix(in oklab, var(--color-muted-foreground) 50%, transparent)}}.placeholder\:text-muted-foreground\/60::placeholder{color:#6b6b6b99}@supports (color:color-mix(in lab, red, red)){.placeholder\:text-muted-foreground\/60::placeholder{color:color-mix(in oklab, var(--color-muted-foreground) 60%, transparent)}}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:top-1\/2:after{content:var(--tw-content);top:50%}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:size-10:after{content:var(--tw-content);width:calc(var(--spacing) * 10);height:calc(var(--spacing) * 10)}.after\:-translate-1\/2:after{content:var(--tw-content);--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}@media (hover:hover){.hover\:border-border:hover{border-color:var(--color-border)}.hover\:border-foreground\/40:hover{border-color:#1a1a1a66}@supports (color:color-mix(in lab, red, red)){.hover\:border-foreground\/40:hover{border-color:color-mix(in oklab, var(--color-foreground) 40%, transparent)}}.hover\:bg-black\/5:hover{background-color:#0000000d}@supports (color:color-mix(in lab, red, red)){.hover\:bg-black\/5:hover{background-color:color-mix(in oklab, var(--color-black) 5%, transparent)}}.hover\:bg-destructive\/90:hover{background-color:#c2410ce6}@supports (color:color-mix(in lab, red, red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab, var(--color-destructive) 90%, transparent)}}.hover\:bg-muted:hover{background-color:var(--color-muted)}.hover\:bg-muted\/40:hover{background-color:#f2f1ee66}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/40:hover{background-color:color-mix(in oklab, var(--color-muted) 40%, transparent)}}.hover\:bg-muted\/70:hover{background-color:#f2f1eeb3}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/70:hover{background-color:color-mix(in oklab, var(--color-muted) 70%, transparent)}}.hover\:bg-muted\/80:hover{background-color:#f2f1eecc}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/80:hover{background-color:color-mix(in oklab, var(--color-muted) 80%, transparent)}}.hover\:bg-neutral-100:hover{background-color:var(--color-neutral-100)}.hover\:bg-primary\/90:hover{background-color:#1a1a1ae6}@supports (color:color-mix(in lab, red, red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab, var(--color-primary) 90%, transparent)}}.hover\:bg-secondary\/80:hover{background-color:#f2f1eecc}@supports (color:color-mix(in lab, red, red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab, var(--color-secondary) 80%, transparent)}}.hover\:bg-sidebar-hover:hover{background-color:var(--color-sidebar-hover)}.hover\:text-foreground:hover{color:var(--color-foreground)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}}.focus\:border-border:focus{border-color:var(--color-border)}.focus\:bg-background:focus{background-color:var(--color-background)}.focus\:bg-muted:focus{background-color:var(--color-muted)}.focus\:text-destructive:focus{color:var(--color-destructive)}.focus\:ring-0:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-ring\/30:focus{--tw-ring-color:#a3a3a34d}@supports (color:color-mix(in lab, red, red)){.focus\:ring-ring\/30:focus{--tw-ring-color:color-mix(in oklab, var(--color-ring) 30%, transparent)}}.focus\:ring-ring\/40:focus{--tw-ring-color:#a3a3a366}@supports (color:color-mix(in lab, red, red)){.focus\:ring-ring\/40:focus{--tw-ring-color:color-mix(in oklab, var(--color-ring) 40%, transparent)}}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-ring\/40:focus-visible{--tw-ring-color:#a3a3a366}@supports (color:color-mix(in lab, red, red)){.focus-visible\:ring-ring\/40:focus-visible{--tw-ring-color:color-mix(in oklab, var(--color-ring) 40%, transparent)}}.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.active\:scale-\[0\.96\]:active{scale:.96}.active\:scale-\[0\.98\]:active{scale:.98}.active\:not-disabled\:scale-\[0\.96\]:active:not(:disabled){scale:.96}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.aria-selected\:bg-muted[aria-selected=true]{background-color:var(--color-muted)}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale:.95}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:bg-muted[data-state=open]{background-color:var(--color-muted)}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale:.95}@media not all and (width>=40rem){.max-sm\:-left-10{left:calc(var(--spacing) * -10)}}@media (width>=40rem){.sm\:-mx-6{margin-inline:calc(var(--spacing) * -6)}.sm\:ml-12{margin-left:calc(var(--spacing) * 12)}.sm\:flex{display:flex}.sm\:inline{display:inline}.sm\:inline-flex{display:inline-flex}.sm\:h-44{height:calc(var(--spacing) * 44)}.sm\:w-\[calc\(100\%-3rem\)\]{width:calc(100% - 3rem)}.sm\:max-w-\[200px\]{max-width:200px}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:px-3{padding-inline:calc(var(--spacing) * 3)}.sm\:px-12{padding-inline:calc(var(--spacing) * 12)}.sm\:pt-8{padding-top:calc(var(--spacing) * 8)}.sm\:pl-12{padding-left:calc(var(--spacing) * 12)}}@media (width>=48rem){.md\:block{display:block}.md\:hidden{display:none}.md\:inline-flex{display:inline-flex}}.dark\:border-neutral-700:is(.dark *){border-color:var(--color-neutral-700)}.dark\:bg-white\/10:is(.dark *){background-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.dark\:bg-white\/10:is(.dark *){background-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}.dark\:bg-white\/20:is(.dark *){background-color:#fff3}@supports (color:color-mix(in lab, red, red)){.dark\:bg-white\/20:is(.dark *){background-color:color-mix(in oklab, var(--color-white) 20%, transparent)}}.dark\:text-amber-100:is(.dark *){color:var(--color-amber-100)}.dark\:text-emerald-200:is(.dark *){color:var(--color-emerald-200)}.dark\:text-emerald-300:is(.dark *){color:var(--color-emerald-300)}.dark\:outline-white\/10:is(.dark *){outline-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.dark\:outline-white\/10:is(.dark *){outline-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}@media (hover:hover){.dark\:hover\:bg-neutral-900:is(.dark *):hover{background-color:var(--color-neutral-900)}.dark\:hover\:bg-white\/10:is(.dark *):hover{background-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.dark\:hover\:bg-white\/10:is(.dark *):hover{background-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-block:calc(var(--spacing) * 1.5)}.\[\&_\[cmdk-group-heading\]\]\:text-\[11px\] [cmdk-group-heading]{font-size:11px}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\[\&_\[cmdk-group-heading\]\]\:tracking-wide [cmdk-group-heading]{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:var(--color-muted-foreground)}.\[\&_\[cmdk-group-heading\]\]\:uppercase [cmdk-group-heading]{text-transform:uppercase}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:mx-auto svg{margin-inline:auto}.\[\&_svg\]\:size-4 svg{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&_svg\]\:max-w-full svg{max-width:100%}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}}@property --tw-animation-delay{syntax:"*";inherits:false;initial-value:0s}@property --tw-animation-direction{syntax:"*";inherits:false;initial-value:normal}@property --tw-animation-duration{syntax:"*";inherits:false}@property --tw-animation-fill-mode{syntax:"*";inherits:false;initial-value:none}@property --tw-animation-iteration-count{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-translate-y{syntax:"*";inherits:false;initial-value:0}.dark{--color-background:#191919;--color-foreground:#e8e8e8;--color-card:#202020;--color-card-foreground:#e8e8e8;--color-popover:#252525;--color-popover-foreground:#e8e8e8;--color-primary:#e8e8e8;--color-primary-foreground:#191919;--color-secondary:#2a2a2a;--color-secondary-foreground:#e8e8e8;--color-muted:#2a2a2a;--color-muted-foreground:#9b9b9b;--color-accent:#2a2a2a;--color-accent-foreground:#e8e8e8;--color-destructive:#ea580c;--color-destructive-foreground:#fafafa;--color-border:#333;--color-input:#333;--color-ring:#6b6b6b;--color-sidebar:#202020;--color-sidebar-fg:#cfcfcf;--color-sidebar-border:#2e2e2e;--color-sidebar-hover:#2a2a2a;--color-sidebar-active:#2f2f2f}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}.ui-freeze *,.ui-freeze :before,.ui-freeze :after{caret-color:#0000!important;transition:none!important;animation:none!important}.ui-freeze [data-sonner-toaster]{display:none!important}.ui-freeze [data-volatile]{visibility:hidden!important}.ui-reveal [data-hover-reveal]{opacity:1!important}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-pan-x{syntax:"*";inherits:false}@property --tw-pan-y{syntax:"*";inherits:false}@property --tw-pinch-zoom{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-space-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-content{syntax:"*";inherits:false;initial-value:""}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0)scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1))rotate(var(--tw-enter-rotate,0));filter:blur(var(--tw-enter-blur,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0)scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1))rotate(var(--tw-exit-rotate,0));filter:blur(var(--tw-exit-blur,0))}} diff --git a/.vercel/output/static/assets/swimlanes-5IMT3BWC-DCPLHTZa.js b/.vercel/output/static/assets/swimlanes-5IMT3BWC-hyAz1L8O.js similarity index 99% rename from .vercel/output/static/assets/swimlanes-5IMT3BWC-DCPLHTZa.js rename to .vercel/output/static/assets/swimlanes-5IMT3BWC-hyAz1L8O.js index 8b45626..62a43b1 100644 --- a/.vercel/output/static/assets/swimlanes-5IMT3BWC-DCPLHTZa.js +++ b/.vercel/output/static/assets/swimlanes-5IMT3BWC-hyAz1L8O.js @@ -1,2 +1,2 @@ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/sizeCapture-X5ZJPWSS-B0uUizjq.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js"])))=>i.map(i=>d[i]); -import{t as e}from"./index-DU4A6Ttf.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-_wZywoZs.js";import{b as r,x as i}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{g as a}from"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import{r as o}from"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as s}from"./chunk-OGEWGWER-Dr-qyYzn.js";import{t as c}from"./graphlib-DS17s2tU.js";import{n as l}from"./chunk-RYQCIY6F-D_L2RdcQ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import{a as u,c as d,i as f,n as p,t as m}from"./chunk-ZGVPDNZ5-zo3h_nOA.js";import{a as h,i as g,n as _,r as v,s as y,t as b}from"./chunk-52WLFC77-BBAyrLn9.js";async function x(t,n){let r=new c({multigraph:!0,compound:!0}),a=[...n.edges],o=i(),s=t.insert(`g`).attr(`class`,`root`),l=s.insert(`g`).attr(`class`,`clusters`),d=s.insert(`g`).attr(`class`,`edges edgePath`),f=s.insert(`g`).attr(`class`,`edgeLabels`),p=s.insert(`g`).attr(`class`,`nodes`),m=new Map,h=t.node()!=null;await Promise.all(n.nodes.map(async e=>{if(e.isGroup)r.setNode(e.id,{...e});else{if(h){let t=await u(p,e,{config:o,dir:e.dir}),n=t.node()?.getBBox()??{width:0,height:0};m.set(e.id,t),e.width=n.width,e.height=n.height}r.setNode(e.id,{...e})}}));for(let e of a)r.setEdge(e.start,e.end,{...e},e.id),n.edges.some(t=>t.id===e.id)||n.edges.push(e);if(globalThis.mermaidCaptureSizes){let{captureNodeSizes:r}=await e(async()=>{let{captureNodeSizes:e}=await import(`./sizeCapture-X5ZJPWSS-B0uUizjq.js`);return{captureNodeSizes:e}},__vite__mapDeps([0,1]));r(t,n)}return{graph:r,groups:{clusters:l,edgePaths:d,edgeLabels:f,nodes:p,rootGroups:s},nodeElements:m}}t(x,`createGraphWithElements`);var S=5,C=1e-5,w=1e-6;function T(e){let t=[];for(let n=0;n=1-w||f<=w||f>=1-w?null:{point:{x:e.x+d*i,y:e.y+d*a},tA:d,tB:f}}t(E,`segmentIntersection`);function D(e){return Math.abs(e.b.x-e.a.x)>=Math.abs(e.b.y-e.a.y)}t(D,`isHorizontalSeg`);function O(e){let t=[];for(let n=0;n=Math.abs(n)?+(t>=0):+(n>=0)}t(j,`getArcSweepFlag`);var ee=.001;function te(e,t){if(e.length<2)return e.map(e=>({...e}));let n=e.map(e=>({...e})),r=t.arrowTypeStart&&o[t.arrowTypeStart];if(r){let t=e[0],i=e[1],a=Math.atan2(i.y-t.y,i.x-t.x);n[0].x=t.x+r*Math.cos(a),n[0].y=t.y+r*Math.sin(a)}let i=t.arrowTypeEnd&&o[t.arrowTypeEnd];if(i){let t=e.length,r=e[t-2],a=e[t-1],o=Math.atan2(a.y-r.y,a.x-r.x);n[t-1].x=a.x-i*Math.cos(o),n[t-1].y=a.y-i*Math.sin(o)}return n}t(te,`applyMarkerOffsets`);function M(e,t,n,r,i){let a=e.point.x,o=e.point.y,s={x:a-t*e.r,y:o-n*e.r},c={x:a+t*e.r,y:o+n*e.r},l=[`L${A(s)}`];return i===`arc`?l.push(`A${k(e.r)},${k(e.r)} 0 0 ${r} ${A(c)}`):l.push(`M${A(c)}`),l}t(M,`emitJump`);function ne(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=n.x-t.x,s=n.y-t.y,c=Math.hypot(i,a),l=Math.hypot(o,s);if(c0){let t=ne(i[e-1],i[e],i[e+1]??i[e],S);t&&(f=t.cutLen)}let p=r,m=null;a&&ee.t-t.t);for(let e of h)e.r=Math.min(e.r,e.d-f,p-e.d);for(let e=0;et){let n=t/2;h[e].r=Math.min(h[e].r,n),h[e+1].r=Math.min(h[e+1].r,n)}}for(let e of h)e.r=2?r:null}catch{return null}}t(ie,`decodeDataPoints`);function ae(e,t,n){if(!n.enabled)return;let r=e.node();if(!r)return;let i=new Map;for(let e of t)i.set(e.id,e);let a=[],o=new Map;for(let e of t){let t=typeof CSS<`u`&&CSS.escape?CSS.escape(e.id):e.id,n=r.querySelector(`path[data-id="${t}"]`);if(!n)continue;o.set(e.id,n);let i=ie(n.getAttribute(`data-points`))??e.points;a.push({...e,points:i})}let s=O(a);if(s.length===0)return;let c=new Map;for(let e of s){let t=c.get(e.jumpEdgeId)??[];t.push(e),c.set(e.jumpEdgeId,t)}for(let e of a){let t=c.get(e.id);if(!t||t.length===0)continue;let r=i.get(e.id)?.curve;if(r!==void 0&&!P(r))continue;let a=o.get(e.id);if(!a||r===void 0&&!re(a.getAttribute(`d`)??``))continue;let s=a.getAttribute(`style`)??``,l=/stroke-dasharray\s*:\s*0\s+([\d.]+)\s+[\d.]+\s+([\d.]+)/.exec(s),u=l?Number.parseFloat(l[1]):null,d=l?Number.parseFloat(l[2]):null,f=N(e,t,n);if(a.setAttribute(`d`,f),u!==null&&d!==null&&typeof a.getTotalLength==`function`){let e=a.getTotalLength(),t=`0 ${u} ${Math.max(0,e-u-d)} ${d}`,n=s.replace(/stroke-dasharray\s*:[^;]*;?/g,`stroke-dasharray: ${t};`).replace(/;\s*;+/g,`;`);a.setAttribute(`style`,n)}}}t(ae,`applyLineJumpsToSvg`);async function oe(e,t){for(let n of e.nodes)n.isGroup?await f(t.clusters,n):d(n);let n=new Map;for(let t of e.nodes)t?.id&&n.set(t.id,t);for(let r of e.edges){let i=r.start?n.get(r.start)??{}:{},a=r.end?n.get(r.end)??{}:{},o=v(t.edgePaths,{...r},{},e.type,i,a,e.diagramId);r.label&&await g(t.rootGroups,r),r.label&&se(r,o)}let r=e.config?.swimlane?.lineHops;if(r!==!1){let n=r===`gap`?`gap`:`arc`,i=e.edges.filter(e=>Array.isArray(e.points)&&e.points.length>=2).map(e=>({id:e.id,points:e.points,curve:e.curve,arrowTypeStart:e.arrowTypeStart,arrowTypeEnd:e.arrowTypeEnd}));ae(t.edgePaths,i,{enabled:!0,jumpRadius:6,jumpStyle:n})}}t(oe,`adjustLayout`);function se(e,t){let i=t?.updatedPath??t?.originalPath,{subGraphTitleTotalMargin:o}=s({flowchart:r().flowchart??{}});if(e.label){let r=_.get(e.id),s=e.x,c=e.y;if(i){let r=a.calcLabelPosition(i);n.debug(`Moving label `+e.label+` from (`,s,`,`,c,`) to (`,r.x,`,`,r.y,`) abc88`),t&&(s=r.x,c=r.y)}r.attr(`transform`,`translate(${s}, ${c+o/2})`)}if(e?.startLabelLeft){let t=y.get(e.id).startLeft,n=e?.x,r=e?.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_left`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}if(e.startLabelRight){let t=y.get(e.id).startRight,n=e.x,r=e.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_right`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}if(e.endLabelLeft){let t=y.get(e.id).endLeft,n=e.x,r=e.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_left`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}if(e.endLabelRight){let t=y.get(e.id).endRight,n=e.x,r=e.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_right`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}}t(se,`positionEdgeLabel`);var ce=`__swimlane_default__`,le=21,ue=20;function de(e){return Math.max(e.padding??ue,ue)}t(de,`topLaneHorizontalPadding`);function fe(e){let{x:t,y:n,width:r,height:i}=e,a=e.swimlaneContentTop;if(typeof t!=`number`||typeof n!=`number`||typeof r!=`number`||typeof i!=`number`||typeof a!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(a)||r<=0||i<=0){delete e.groupTitleRect;return}let o=n-i/2,s=Math.min(a,n+i/2),c=o+Math.min(le,Math.max(0,s-o));if(c<=o){delete e.groupTitleRect;return}e.groupTitleRect={left:t-r/2,right:t+r/2,top:o,bottom:c}}t(fe,`assignTopLaneTitleRect`);function pe(e){let t=e.direction,n=e.nodes??=[];for(let n of e.nodes??[])n.isGroup&&!n.parentId&&(n.shape=`swimlane`,t&&(n.direction=t));let r=n.filter(e=>!e.isGroup&&!e.parentId);if(r.length===0)return;let i=n.find(e=>e.id===ce);i?i.isGroup&&(i.shape=`swimlane`,t&&(i.direction=t)):(i={id:ce,label:``,isGroup:!0,shape:`swimlane`,padding:20,...t?{direction:t}:{}},n.push(i));for(let e of r)e.parentId=ce}t(pe,`prepareLayoutForSwimlanes`);function F(e){let t=new Map;for(let n of e.nodes??[])t.set(n.id,n);let n=[];for(let t of e.edges??[]){let e=typeof t.start==`string`?t.start:void 0,r=typeof t.end==`string`?t.end:void 0;!e||!r||t.labelNodeId||n.push({id:t.id,src:e,dst:r,ref:t})}let r=e.nodes??[],i=r.filter(e=>e.isGroup),a=r.filter(e=>!e.isGroup);return{nodes:[...[...i].reverse(),...a].map(e=>e.id),edges:n,layout:e,nodeById:t}}t(F,`toGraphView`);function I(e,t,n,r){let{layout:i}=e,a=e.nodeById,o=r?.layerGap??100,s=r?.nodeGap??40,c=0;for(let e of t.layers){let t=0;for(let r of e){let e=a.get(r);if(!e){t++;continue}e.layer=c,e.order=t;let i=n.x[r]??t*s,l=n.y[r]??c*o;e.x=i,e.y=l,t++}c++}let l=i.nodes??[],u=new Map,d=[];for(let e of l){if(!e?.isGroup)continue;e.parentId||d.push(e);let t=l.filter(t=>t.parentId===e.id),r=1/0,i=-1/0,a=1/0,o=-1/0;for(let e of t){let t=e.x??n.x[e.id],s=e.y??n.y[e.id],c=e.width??0,l=e.height??0;t!=null&&s!=null&&(r=Math.min(r,t-c/2),i=Math.max(i,t+c/2),a=Math.min(a,s-l/2),o=Math.max(o,s+l/2))}if(r===1/0||a===1/0)e.x=e.x??0,e.y=e.y??0,e.width=e.width??0,e.height=e.height??0;else{let t=e.padding??20,n=e.parentId?t:2*de(e),s=t,c=Math.max(0,i-r)+n,l=Math.max(0,o-a)+s,d=(r+i)/2,f=(a+o)/2;e.x=d,e.y=f,e.width=c,e.height=l,u.set(e.id,{minX:r,maxX:i,minY:a,maxY:o})}}if(d.length>0&&u.size>0){let e=1/0,t=-1/0,n=0;for(let r of d){let i=r.padding??20;i>n&&(n=i);let a=u.get(r.id);a&&(e=Math.min(e,a.minY),t=Math.max(t,a.maxY))}if(e!==1/0&&t!==-1/0){let r=Math.max(0,t-e)+2*Math.max(n,36),i=(e+t)/2;for(let t of d)t.y=i,t.height=r,t.swimlaneContentTop=e;let a=[...d].sort((e,t)=>(e.x??0)-(t.x??0)),o=[],s=[],c=[];for(let e of a){let t=u.get(e.id);if(!t)continue;let n=Math.max(0,t.maxX-t.minX)+2*de(e),r=(t.minX+t.maxX)/2;o.push(e.id),s.push(r),c.push(n)}let l=o.length;if(l>0){let e=new Map;if(l===1)e.set(o[0],c[0]);else{let t=[];for(let e=0;e0&&i>0?{cx:t,cy:n,rect:Ee(t,n,r,i)}:void 0}t(ge,`measuredNodeRect`);function _e(e){if(e.isGroup)return;let t=ge(e);if(t)return{id:String(e.id??``),cx:t.cx,cy:t.cy,rect:t.rect}}t(_e,`nodeBoundsInfoFor`);function R(e,t,n=L){return Math.abs(e.x-t.x)n}t(V,`isHorizontalSegment`);function H(e,t,n=L){return z(e,t,n)&&Math.abs(e.y-t.y)>n}t(H,`isVerticalSegment`);function U(e,t,n,r){return Math.max(0,Math.min(Math.max(e,t),Math.max(n,r))-Math.max(Math.min(e,t),Math.min(n,r)))}t(U,`overlapLength`);function ve(e,t,n=L){return e.horizontal&&t.horizontal&&B(e.a,t.a,n)?U(e.a.x,e.b.x,t.a.x,t.b.x):e.vertical&&t.vertical&&z(e.a,t.a,n)?U(e.a.y,e.b.y,t.a.y,t.b.y):0}t(ve,`sameAxisSegmentOverlapLength`);function ye(e,t=L){let n=[];for(let r=0;r0?n[n.length-1]:void 0;(!e||!R(e,r,t))&&n.push({x:r.x,y:r.y})}return n}t(G,`dedupeConsecutivePoints`);function be(e,t=L){if(!e||e.length!==4)return;let[n,r,i,a]=e;return V(n,r,t)&&H(r,i,t)&&V(i,a,t)?{kind:`HVH`,p0:n,p1:r,p2:i,p3:a}:H(n,r,t)&&V(r,i,t)&&H(i,a,t)?{kind:`VHV`,p0:n,p1:r,p2:i,p3:a}:void 0}t(be,`classifyThreeSegmentRoute`);function xe(e,t,n,r=0){let i=Math.min(e.x,t.x),a=Math.max(e.x,t.x),o=Math.min(e.y,t.y),s=Math.max(e.y,t.y);return a>n.left-r&&in.top-r&&ot.left+n&&e.xt.top+n&&e.y=t.right&&e.top<=t.top&&e.bottom>=t.bottom}t(Ce,`rectContainsRect`);function we(e,t){return e.leftt.left&&e.topt.top}t(we,`rectsOverlap`);function Te(e,t){return{left:e.left-t,right:e.right+t,top:e.top-t,bottom:e.bottom+t}}t(Te,`inflateRect`);function Ee(e,t,n,r){return{left:e-n/2,right:e+n/2,top:t-r/2,bottom:t+r/2}}t(Ee,`rectFromCenterSize`);function K(e){return ge(e)?.rect}t(K,`rectOfNodeBounds`);function De(e,t){switch(t){case`top`:return{x:e.cx,y:e.rect.top};case`bottom`:return{x:e.cx,y:e.rect.bottom};case`left`:return{x:e.rect.left,y:e.cy};case`right`:return{x:e.rect.right,y:e.cy}}}t(De,`portForRectSide`);function Oe(e,t,n,r,i,a=L){let o=t===`left`||t===`right`,s=r===`left`||r===`right`;if(o&&s){if(t===`right`&&r===`left`&&e.xn.x){if(B(e,n,a))return[e,n];let t=(e.x+n.x)/2;return[e,{x:t,y:e.y},{x:t,y:n.y},n]}if(t===r){if(B(e,n,a))return;let r=t===`left`?Math.min(e.x,n.x)-i:Math.max(e.x,n.x)+i;return[e,{x:r,y:e.y},{x:r,y:n.y},n]}return}if(!o&&!s){if(t===r){if(z(e,n,a))return;let r=t===`top`?Math.min(e.y,n.y)-i:Math.max(e.y,n.y)+i;return[e,{x:e.x,y:r},{x:n.x,y:r},n]}if(!(t===`bottom`&&r===`top`&&e.yn.y))return;if(z(e,n,a))return[e,n];let o=(e.y+n.y)/2;return[e,{x:e.x,y:o},{x:n.x,y:o},n]}if(o&&!s){let i=t===`right`&&n.x>e.x||t===`left`&&n.xn.y;return i&&a?[e,{x:n.x,y:e.y},n]:void 0}let c=t===`bottom`&&n.y>e.y||t===`top`&&n.yn.x;return c&&l?[e,{x:e.x,y:n.y},n]:void 0}t(Oe,`buildOrthogonalPortPath`);function ke(e,t,n,r){return t===`left`||t===`right`?[e,{x:r,y:e.y},{x:r,y:n.y},n]:[e,{x:e.x,y:r},{x:n.x,y:r},n]}t(ke,`buildSameSideTrackPath`);function Ae(e){let t=new Map,n=[];for(let r of e){if(r.isEdgeLabel)continue;let e=_e(r);e&&(t.set(e.id,e),n.push({id:e.id,rect:e.rect}))}return{nodeInfoById:t,realNodeRects:n}}t(Ae,`collectRealNodeBounds`);function je(e){let t=[],n=[];for(let r of e){let e=_e(r);if(!e)continue;let i={id:e.id,rect:e.rect};r.isEdgeLabel?n.push(i):t.push(i)}return{realNodeRects:t,labelNodeRects:n}}t(je,`collectNodeRectEntries`);function Me(e,{includeEdgeLabels:t=!0}={}){let n=[];for(let r of e){if(r.isGroup||!t&&r.isEdgeLabel)continue;let e=r.x??0,i=r.y??0,a=r.width??0,o=r.height??0;n.push({nodeId:r.id,...Ee(e,i,a,o)})}return n}t(Me,`collectLayoutNodeRects`);function Ne(e,t,n=L){let r=e.start,i=e.end;if(!r||!i)return;let a=t.get(r),o=t.get(i);if(!(!a||!o))return{srcId:r,dstId:i,srcInfo:a,dstInfo:o,collinearX:Math.abs(a.cx-o.cx)m||f_)return!1;let v=Math.abs(h-u.a.x)i:a&&s&&B(e,n,i)?U(e.x,t.x,n.x,r.x)>i:!1}t(Fe,`sameAxisSegmentsOverlap`);function Ie(e,t,n,r,{epsilon:i=L,skipDegenerateOther:a=!1}={}){for(let o of n){if(o===r||o.isLayoutOnly)continue;let n=o.points;if(!(!n||n.length<2))for(let r=0;rf+i&&mh+i&&dr+L&&e=2?t[t.length-2]:void 0,n=e&&z(e,r)?{x:r.x,y:i.y}:{x:i.x,y:r.y};t.push(n)}t.push(i)}let n=[];for(let e of t){let t=n[n.length-1];(!t||!R(t,e))&&n.push(e)}return n}t(Ve,`orthogonalizePolyline`);function He(e){if(e.length<3)return e;let t=[...e];for(let e=0;e<32;e++){let e=Be(t);if(t=e.points,!e.changed)break}return t}t(He,`simplifyPolyline`);var J=.001,Ue=.5,We=4;function Ge(e,t,n){let r=e;if(r.isLayoutOnly||!r.points||r.points.length=0&&i=e.length)return e;let a=i-r;if(a<0||a>=e.length)return e;let o=Ke(e[i],e[a],t);return n?[o,...e.slice(i)]:[...e.slice(0,i+1),o]}t(qe,`clipEndpoint`);function Je(e,t){for(let n of e){let e=Ge(n,t,2);if(!e)continue;let r=[...e.points];e.srcRect&&(r=qe(r,e.srcRect,!0)),e.dstRect&&(r=qe(r,e.dstRect,!1)),r=He(Ve(r)),r=at(r,e.srcRect,e.dstRect),e.edge.points=He(Ve(r))}}t(Je,`clipEdgeEndpointsToNodeBoundaries`);function Ye(e,t,n,r=!1){if(B(e,t,J)){if(t.yn.bottom+J)return t;if(r){if(e.xn.right+J)return{x:n.right,y:e.y}}return{x:Math.abs(t.x-n.left)<=Math.abs(t.x-n.right)?n.left:n.right,y:e.y}}if(z(e,t,J)){if(t.xn.right+J)return t;if(r){if(e.yn.bottom+J)return{x:e.x,y:n.bottom}}let i=Math.abs(t.y-n.top)<=Math.abs(t.y-n.bottom);return{x:e.x,y:i?n.top:n.bottom}}return t}t(Ye,`snapEndpointToBoundary`);function Xe(e,t,n){let r=e[t];for(let i=t+n;i>=0&&ie.lo)),n=Math.min(...e.map(e=>e.hi));if(!(t>n))return{lo:t,hi:n}}t($e,`intersectRanges`);function et(e,t){return t===`left`||t===`right`?Ze(e.top,e.bottom):Ze(e.left,e.right)}t(et,`clearanceRangeForSide`);function tt(e,t,n){let r=e.y>=n.top-J&&e.y<=n.bottom+J,i=e.x>=n.left-J&&e.x<=n.right+J;if(B(e,t,J)&&r){if(Math.abs(e.x-n.left)0?$e(a):void 0}t(rt,`straightClearanceRange`);function it(e,t,n,r,i){let a=rt(e,t,n,r,i);if(!a)return;let o=i?e.y:e.x,s=Math.min(a.hi,Math.max(a.lo,o));if(!(Math.abs(s-o)({...e}));for(let s=t;s>=0&&s=n.left-J&&Math.max(e.x,t.x)<=n.right+J,i=Math.min(e.y,t.y)>=n.top-J&&Math.max(e.y,t.y)<=n.bottom+J;if(Math.abs(e.y-n.top)r.bottom+J;case`left`:return B(t,n,J)&&n.xr.right+J}}t(ut,`leavesOutward`);function dt(e,t,n){if(e.length<3)return e;if(n){let n=lt(e[0],e[1],t);return n&&ut(n,e[1],e[2],t)?e.slice(1):e}let r=e.length-1,i=lt(e[r-1],e[r],t);return i&&ut(i,e[r-1],e[r-2],t)?e.slice(0,r):e}t(dt,`collapseOwnBorderStub`);function ft(e,t,n){let r=e;if(t){let e=Xe(r,0,1);if(e){let n=Ye(e,r[0],t);n!==r[0]&&(r=[n,...r.slice(1)])}r=dt(r,t,!0)}if(n){let e=r.length-1,t=Xe(r,e,-1);if(t){let i=Ye(t,r[e],n,!0);i!==r[e]&&(r=[...r.slice(0,e),i])}r=dt(r,n,!1)}let i=at(r,t,n);return i!==r||r.length===2?i:(t&&(r=ct(r,t,!0)),n&&(r=ct(r,n,!1)),r)}t(ft,`snapAndCollapseEndpoints`);function pt(e,t){for(let n of e){let e=Ge(n,t,2);if(!e)continue;let r=ft(G(e.points,J),e.srcRect,e.dstRect);if(r.length<3){e.edge.points=r;continue}let i=[r[0],{...r[0]},...r.slice(1,-1),r[r.length-1],{...r[r.length-1]}];e.edge.points=i}}t(pt,`prepareEdgeEndpointsForRenderer`);function mt(e){return new Map(e.map(e=>[e.id,e]))}t(mt,`buildNodeMap`);function ht(e,t){let n=e.parentId,r=null;for(;n;){let e=t.get(n);if(!e?.isGroup)break;r=e.id,n=e.parentId}return r}t(ht,`resolveTopLevelGroupId`);function gt(e,t){let n=0,r=e.parentId;for(;r;){let e=t.get(r);if(!e?.isGroup)break;n++,r=e.parentId}return n}t(gt,`groupDepth`);function _t(e){let t=1/0,n=-1/0,r=1/0,i=-1/0;for(let a of e){let e=a.x,o=a.y;if(typeof e!=`number`||typeof o!=`number`)continue;let s=a.width??0,c=a.height??0;t=Math.min(t,e-s/2),n=Math.max(n,e+s/2),r=Math.min(r,o-c/2),i=Math.max(i,o+c/2)}return t===1/0||r===1/0?null:{minX:t,maxX:n,minY:r,maxY:i}}t(_t,`boundsForChildren`);function vt(e,t){let n=e.padding??20;e.x=(t.minX+t.maxX)/2,e.y=(t.minY+t.maxY)/2,e.width=Math.max(0,t.maxX-t.minX)+n,e.height=Math.max(0,t.maxY-t.minY)+n}t(vt,`applyGroupBounds`);function yt(e){let t=mt(e),n=e.filter(e=>e.isGroup&&e.parentId).sort((e,n)=>gt(n,t)-gt(e,t));for(let t of n){let n=_t(e.filter(e=>e.parentId===t.id));n&&vt(t,n)}}t(yt,`recomputeNestedGroupBounds`);function bt(e,n){let r=e.nodes??[],i=e.edges??[],a=r.filter(e=>!e.isGroup),o=1/0,s=-1/0;for(let e of a){let t=e[n];typeof t==`number`&&(o=Math.min(o,t),s=Math.max(s,t))}if(!Number.isFinite(o)||!Number.isFinite(s))return!1;let c=t(e=>o+s-e,`mirror`);for(let e of r){let t=e[n];typeof t==`number`&&(e[n]=c(t));let r=e.groupTitleRect;r&&(e.groupTitleRect=n===`x`?{...r,left:c(r.right),right:c(r.left)}:{...r,top:c(r.bottom),bottom:c(r.top)})}for(let e of i)for(let t of e.points??[])t[n]=c(t[n]);return!0}t(bt,`mirrorAxis`);function xt(e){return!(e.nodes??[]).some(e=>!e.isGroup)||bt(e,`y`)}t(xt,`applyBtDirectionTransform`);function St(e,t=`LR`){let n=e.nodes??[],r=e.edges??[],i=n.filter(e=>!e.isGroup),a=1/0,o=1/0;for(let e of i){let t=e.x??0,n=e.y??0;t0?Math.max(1,l/u):1;for(let e of i){let t=e.x??0,n=((e.y??0)-o)*d+36,r=t-a;e.x=n,e.y=r}for(let e of r)if(e.points)for(let t of e.points){let e=t.x,n=(t.y-o)*d+36,r=e-a;t.x=n,t.y=r}yt(n);let f=n.filter(e=>e.isGroup&&!e.parentId);if(f.length===0)return t===`RL`&&bt(e,`x`),!0;let p=mt(n),m=new Map;for(let e of n){if(e.isGroup)continue;let t=ht(e,p);if(!t)continue;let n=m.get(t)??[];n.push(e),m.set(t,n)}let h=0;for(let e of f){let t=e.padding??0;t>h&&(h=t)}let g=[],_=1/0,v=-1/0;for(let e of f){let t=_t(m.get(e.id)??[]);t&&(_=Math.min(_,t.minX),v=Math.max(v,t.maxX),g.push({lane:e,contentTop:t.minY,contentBottom:t.maxY,centerY:(t.minY+t.maxY)/2}))}if(_===1/0||v===-1/0)return!0;let y=Math.max(0,v-_)+2*Math.max(h,10),b=36+y,x=(_+v)/2-y/2-36,S=x+b/2,C=Math.max(h,36);g.sort((e,t)=>e.centerY-t.centerY);for(let e=0;ed.cy?g.bottom:g.top,t=d.cx+n;if(t<=g.left+Ct||t>=g.right-Ct)continue;i={x:t,y:e},a={x:t,y:o.y},c={x:o.x,y:o.y}}else{let e=f.cx>d.cx?g.right:g.left,t=d.cy+n;if(t<=g.top+Ct||t>=g.bottom-Ct)continue;i={x:e,y:t},a={x:o.x,y:t},c={x:o.x,y:o.y}}let p=R(i,a,Ct),m=R(a,c,Ct);if(p&&m||!p&&q(i,a,r,[l],1)||!m&&q(a,c,r,[u],1))continue;let _=!p&&Ie(i,a,e,t,{epsilon:Ct,skipDegenerateOther:!0}),v=!m&&Ie(a,c,e,t,{epsilon:Ct,skipDegenerateOther:!0});if(!(_||v)){h=p?[a,c]:m?[i,a]:[i,a,c];break}}h&&(t.points=h)}}t(Et,`portSwapToLShape`);function Dt(e,n){let r=.001,{realNodeRects:i,labelNodeRects:a}=je(n.values());for(let o of e){if(o.isLayoutOnly)continue;let s=o.points;if(!s||s.length<4)continue;let c=G(s,r);if(c.length<4)continue;let l=c.length-1,u=c[l],d=c[l-1],f=c[l-2],p=u.x-d.x,m=u.y-d.y,h=Math.hypot(p,m);if(h>=10||h0;O={x:f.x,y:E},k={x:e?D.right:D.left,y:E}}if(q(O,k,i,S?[S]:[],-2)||q(O,k,a,[],-2))continue;if(C){let e=n.get(C),t=e?K(e):void 0;if(t&&Se(O,t,2))continue}let A=t((e,t)=>`${e.x.toFixed(3)},${e.y.toFixed(3)}|${t.x.toFixed(3)},${t.y.toFixed(3)}`,`ownSegmentKey`),j=new Set;for(let e=0;e{for(let i of e){if(i===o||i.isLayoutOnly)continue;let e=i.points;if(!(!e||e.length<2))for(let i=0;i=0){let e=c[l-3],t=[C,S].filter(e=>!!e);if(q(e,O,i,t,-2)||ee(e,O))continue}let te=[...c.slice(0,l-2),O,k];o.points=te;let M=o.labelNodeId;if(M){let e=n.get(M);if(e){let t=e.width??0,n=e.height??0;if(t>0&&n>0){let i,a,o=-1;for(let e=0;e=t+2||d&&l>=n+2)&&l>o&&(o=l,i=(s.x+c.x)/2,a=(s.y+c.y)/2)}i!==void 0&&a!==void 0&&(e.x=i,e.y=a)}}}}}t(Dt,`collapseShortTerminalStub`);var Y=.001,X=8,Z=ye,Ot=t((e,t)=>z(e,t,Y)||B(e,t,Y),`orthogonallyAligned`);function kt(e,n){let r=t((e,t)=>{let n=e.x??0,r=e.y??0,i=t.x-n,a=t.y-r,o=(e.width??0)/2,s=(e.height??0)/2;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),{x:n+(a===0?0:s*i/a),y:r+s}):(i<0&&(o=-o),{x:n+o,y:r+(i===0?0:o*a/i)})},`rectIntersect`),i=t((e,t)=>{let i=G(e.points??[]);if(i.length<2)return;let a=t?e.start:e.end,o=a?n.get(a):void 0,s=o?K(o):void 0;if(!o||!a||!s)return;let c=t?i[0]:i[i.length-1],l=t?i[1]:i[i.length-2],u=r(o,c),d=c;if(Ot(l,u)&&(d=l),z(u,d,Y))return{edge:e,edgeId:String(e.id??``),nodeId:a,atStart:t,orientation:`V`,coord:u.x,min:Math.min(u.y,d.y),max:Math.max(u.y,d.y),boundary:u,railEnd:d,rect:s};if(B(u,d,Y))return{edge:e,edgeId:String(e.id??``),nodeId:a,atStart:t,orientation:`H`,coord:u.y,min:Math.min(u.x,d.x),max:Math.max(u.x,d.x),boundary:u,railEnd:d,rect:s}},`terminalLaneFor`),a=t((e,t)=>Math.max(0,Math.min(e.max,t.max)-Math.max(e.min,t.min)),`projectedOverlapLength`),o=t((e,t)=>e.nodeId!==t.nodeId||e.orientation!==t.orientation?!1:e.orientation===`H`?(Math.abs(e.boundary.x-e.rect.left)<1||Math.abs(e.boundary.x-e.rect.right)<1)&&z(e.boundary,t.boundary,1):(Math.abs(e.boundary.y-e.rect.top)<1||Math.abs(e.boundary.y-e.rect.bottom)<1)&&B(e.boundary,t.boundary,1),`sameTerminalFace`),s=t((e,t)=>e.nodeId!==t.nodeId||e.orientation!==t.orientation?!1:a(e,t)>=X&&Math.abs(e.coord-t.coord)<.5,`exactTerminalLaneConflict`),c=t((e,t)=>{if(e.nodeId!==t.nodeId||e.orientation!==t.orientation||e.orientation!==`H`||e.atStart===t.atStart)return!1;let n=a(e,t);if(n2*r?!1:o(e,t)&&Math.abs(e.coord-t.coord)<16},`nearTerminalLaneConflict`),l=t((e,n)=>{let r=G(e.edge.points??[]);if(r.length<2)return;let i=e.orientation===`V`?{x:e.boundary.x+n,y:e.boundary.y}:{x:e.boundary.x,y:e.boundary.y+n},a=e.orientation===`V`?{x:e.railEnd.x+n,y:e.railEnd.y}:{x:e.railEnd.x,y:e.railEnd.y+n};if(!t(()=>Math.abs(e.boundary.y-e.rect.top)<1||Math.abs(e.boundary.y-e.rect.bottom)<1?B(i,e.boundary,Y)&&i.x>=e.rect.left+1&&i.x<=e.rect.right-1:Math.abs(e.boundary.x-e.rect.left)<1||Math.abs(e.boundary.x-e.rect.right)<1?z(i,e.boundary,Y)&&i.y>=e.rect.top+1&&i.y<=e.rect.bottom-1:!1,`boundaryStaysOnSameFace`)())return;if(e.atStart){let t=r.length>1&&R(r[1],e.railEnd,Y),n=r.slice(t?2:1),o=n[0];return o&&!Ot(o,a)?void 0:[i,a,...n]}let o=r.length>1&&R(r[r.length-2],e.railEnd,Y),s=r.slice(0,o?-2:-1),c=s[s.length-1];if(!(c&&!Ot(c,a)))return[...s,a,i]},`shiftedCandidate`),u=t(e=>{let t=e.edge,r=G(t.points??[]);if(r.length!==2)return!1;let i=t.start,a=t.end,o=i?n.get(i):void 0,s=a?n.get(a):void 0;if(!o||!s)return!1;let c=o.x??0,l=o.y??0,u=s.x??0,d=s.y??0,[f,p]=r;return B(f,p,Y)&&Math.abs(l-d)<1&&Math.abs(c-u)>1||z(f,p,Y)&&Math.abs(c-u)<1&&Math.abs(l-d)>1},`laneIsStraightCollinearConnector`),d=[-7,7,-14,14,-21,21];for(let t=0;t<8;t++){let t=e.filter(e=>!e.isLayoutOnly).flatMap(e=>[i(e,!0),i(e,!1)]).filter(e=>!!e),n=!1;for(let e=0;e{let n=u(e),r=u(t);return n===r?Number(!t.atStart)-Number(!e.atStart):Number(n)-Number(r)});for(let e of p){for(let r of d){let a=l(e,r);if(!a)continue;let o=i({...e.edge,points:a},e.atStart);if(!(!o||t.some(t=>t.edge!==e.edge&&(s(o,t)||f&&c(o,t))))){e.edge.points=a,n=!0;break}}if(n)break}}if(!n)return}}t(kt,`separateSharedRenderedTerminalLanes`);function At(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=t((t,n)=>{let a=t.start,o=t.end,s=Z(n);if(s.length!==n.length-1)return!1;let c=[a,o].filter(e=>!!e);for(let e of s)if(q(e.a,e.b,r,c,-2)||q(e.a,e.b,i,[],-2))return!1;for(let n of e){if(n===t||n.isLayoutOnly)continue;let e=n.points;if(!(!e||e.length<2)){for(let t of s)for(let n of Z(G(e)))if(ve(t,n,.5)>=X||Le(t.a,t.b,n.a,n.b,Y))return!1}}return!0},`candidateIsSafe`),o=t((e,t)=>{if(t+4>=e.length)return;let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3],o=e[t+4],s=V(n,r)&&H(r,i)&&V(i,a)&&H(a,o)&&z(n,a,Y)&&z(n,o,Y)&&z(r,i,Y)&&(r.x-n.x)*(a.x-i.x)<0,c=H(n,r)&&V(r,i)&&H(i,a)&&V(a,o)&&B(n,a,Y)&&B(n,o,Y)&&B(r,i,Y)&&(r.y-n.y)*(a.y-i.y)<0;if(s||c)return G([...e.slice(0,t+1),o,...e.slice(t+5)]);if(t+5>=e.length)return;let l=e[t+5],u=H(n,r)&&V(r,i)&&H(i,a)&&V(a,o)&&H(o,l)&&z(n,o,Y)&&z(n,l,Y)&&z(i,a,Y)&&(i.x-r.x)*(o.x-a.x)<0,d=V(n,r)&&H(r,i)&&V(i,a)&&H(a,o)&&V(o,l)&&B(n,o,Y)&&B(n,l,Y)&&B(i,a,Y)&&(i.y-r.y)*(o.y-a.y)<0;if(!(!u&&!d))return G([...e.slice(0,t+1),l,...e.slice(t+6)])},`withoutDogleg`);for(let t=0;t<8;t++){let t=!1;for(let n of e){if(n.isLayoutOnly)continue;let e=G(n.points??[]);for(let r=0;r<=e.length-5;r++){let i=o(e,r);if(!(!i||!a(n,i))){n.points=i,t=!0;break}}if(t)break}if(!t)return}}t(At,`collapseRedundantRectangularDoglegs`);function jt(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=e.filter(e=>!e.isLayoutOnly),o=t((e,t,n)=>G(e===t?n??[]:e.points??[]),`pointsFor`),s=t((e,t)=>{let n=0;for(let r=0;r{let t=Z(e);if(t.length!==3)return;let n=t[1];if(!(t[0].horizontal===n.horizontal||t[2].horizontal===n.horizontal))return{index:n.index,horizontal:n.horizontal,vertical:n.vertical,segment:n}},`middleRail`),l=t((e,t)=>{let n=[e.start,e.end].filter(e=>!!e);return r.filter(e=>{if(n.includes(e.id))return!1;let r=e.rect;return t.horizontal?U(t.a.x,t.b.x,r.left,r.right)>=X&&t.a.y>=r.top-2&&t.a.y<=r.bottom+2:U(t.a.y,t.b.y,r.top,r.bottom)>=X&&t.a.x>=r.left-2&&t.a.x<=r.right+2})},`blockingRectsFor`),u=t((e,t,n)=>{let r=e.map(e=>({...e}));if(t.horizontal)r[t.index].y=n,r[t.index+1].y=n;else if(t.vertical)r[t.index].x=n,r[t.index+1].x=n;else return;let i=He(G(r));return Z(i).length===i.length-1?i:void 0},`candidateByMovingRail`),d=t((e,t,n)=>{let c=[e.start,e.end].filter(e=>!!e),l=Z(t);if(l.length!==t.length-1)return!1;for(let e of l)if(q(e.a,e.b,r,c,-2)||q(e.a,e.b,i,[],-2))return!1;for(let t of a)if(t!==e){for(let e of l)for(let n of Z(o(t)))if(ve(e,n,.5)>=X)return!1}return s(e,t)<=n},`candidateIsSafe`);for(let e=0;e<8;e++){let e=s(),t=!1;for(let n of a){let r=o(n),i=c(r);if(!i)continue;let a=l(n,i.segment);if(a.length===0)continue;let s=i.horizontal?[Math.min(...a.map(e=>e.rect.top))-20,Math.max(...a.map(e=>e.rect.bottom))+20]:[Math.min(...a.map(e=>e.rect.left))-20,Math.max(...a.map(e=>e.rect.right))+20];for(let a of s){let o=u(r,i.segment,a);if(!(!o||!d(n,o,e))){n.points=o,t=!0;break}}if(t)break}if(!t)return}}t(jt,`liftObstacleHuggingSameSideRails`);function Mt(e,n){let r=t(e=>{let t=e.groupTitleRect;if(!(!t||typeof t.left!=`number`||typeof t.right!=`number`||typeof t.top!=`number`||typeof t.bottom!=`number`||!Number.isFinite(t.left)||!Number.isFinite(t.right)||!Number.isFinite(t.top)||!Number.isFinite(t.bottom)||t.right<=t.left||t.bottom<=t.top))return{left:t.left,right:t.right,top:t.top,bottom:t.bottom}},`validTitleRect`),i=t(e=>{if(!e.isGroup||e.parentId)return;let t=e.direction,n=typeof t==`string`?t.toUpperCase():``;if(n===`LR`||n===`RL`||n===`BT`)return;let i=r(e),a=e.y,o=e.height;if(!i||typeof a!=`number`||typeof o!=`number`||!Number.isFinite(a)||!Number.isFinite(o)||o<=0)return;let s=i.right-i.left,c=i.bottom-i.top;if(!(c<=0||s{if(!e.horizontal)return!1;let n=e.a.y;return n<=t.top+Y||n>=t.bottom-Y?!1:U(e.a.x,e.b.x,t.left,t.right)>=X},`horizontalSegmentIntersectsTitle`),o=[...n.values()].map(i).filter(e=>!!e);if(o.length===0)return;let s=0;for(let t of e){if(t.isLayoutOnly)continue;let e=G(t.points??[]);for(let t of Z(e))for(let e of o)a(t,e.rect)&&(s=Math.max(s,e.rect.bottom-t.a.y+4))}if(!(s<=Y))for(let e of o){let t=e.node.y,n=e.node.height;typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||n<=0||(e.node.y=t-s/2,e.node.height=n+s,e.node.groupTitleRect={...e.rect,top:e.rect.top-s,bottom:e.rect.bottom-s})}}t(Mt,`liftTopLaneTitleBandsAboveRails`);function Nt(e,n){let r=t(e=>{let t=e.groupTitleRect;if(!(!t||typeof t.left!=`number`||typeof t.right!=`number`||typeof t.top!=`number`||typeof t.bottom!=`number`||!Number.isFinite(t.left)||!Number.isFinite(t.right)||!Number.isFinite(t.top)||!Number.isFinite(t.bottom)||t.right<=t.left||t.bottom<=t.top))return{left:t.left,right:t.right,top:t.top,bottom:t.bottom}},`validTitleRect`),i=t(e=>{if(!e.isGroup||e.parentId||e.direction!==`LR`)return;let t=r(e),n=e.x,i=e.width;if(!t||typeof n!=`number`||typeof i!=`number`||!Number.isFinite(n)||!Number.isFinite(i)||i<=0)return;let a=t.right-t.left,o=t.bottom-t.top;if(!(a<=0||o{if(!e.vertical)return!1;let n=e.a.x;return n<=t.left+Y||n>=t.right-Y?!1:U(e.a.y,e.b.y,t.top,t.bottom)>=X},`verticalSegmentIntersectsTitle`),o=t((e,t)=>{if(!e.horizontal)return!1;let n=e.a.y;return n<=t.top+Y||n>=t.bottom-Y?!1:U(e.a.x,e.b.x,t.left,t.right)>=X},`horizontalSegmentIntersectsTitle`),s=[...n.values()].map(i).filter(e=>!!e);if(s.length===0)return;let c=0;for(let t of e){if(t.isLayoutOnly)continue;let e=G(t.points??[]);for(let t of Z(e))for(let e of s)if(a(t,e.rect))c=Math.max(c,e.rect.right-t.a.x+4);else if(o(t,e.rect)){let n=Math.min(t.a.x,t.b.x);c=Math.max(c,e.rect.right-n+4)}}if(!(c<=Y))for(let e of s){let t=e.node.x,n=e.node.width;typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||n<=0||(e.node.x=t-c/2,e.node.width=n+c,e.node.groupTitleRect={...e.rect,left:e.rect.left-c,right:e.rect.right-c})}}t(Nt,`shiftLeftLaneTitleBandsLeftOfRails`);function Pt(e,n){let{realNodeRects:r}=je(n.values()),i=e.filter(e=>!e.isLayoutOnly),a=t((e,t=new Map)=>G(t.get(e)??e.points??[]),`replacementPointsFor`),o=t((e=new Map)=>{let t=0;for(let n=0;ni.reduce((t,n)=>t+W(a(n,e)),0),`totalBends`),c=t(e=>{let t=a(e);if(t.length<4)return;let n=t[t.length-2],r=t[t.length-1];if(!(!V(n,r,Y)&&!H(n,r,Y)))return{tailStart:n,terminal:r}},`terminalTailFor`),l=t((e,t)=>{let n=a(e);if(n.length<3)return;let r=n[0],i=n[1],o;if(V(r,i,Y))o={x:i.x,y:t.tailStart.y};else if(H(r,i,Y))o={x:t.tailStart.x,y:i.y};else return;let s=He(G([r,i,o,t.tailStart,t.terminal]));return Z(s).length===s.length-1?s:void 0},`candidateWithDestinationTail`),u=t((e,t)=>{let n=[e.start,e.end].filter(e=>!!e);for(let e of Z(t))if(q(e.a,e.b,r,n,-2))return!0;return!1},`pathHasNodeHit`),d=t((e,t,n)=>{for(let r of i)if(r!==e){for(let e of Z(t))for(let t of Z(a(r,n)))if(ve(e,t,.5)>=X)return!0}return!1},`pathHasSharedTrack`),f=t((e,t,n)=>!u(e,t)&&!d(e,t,n),`candidateIsSafe`),p=t(()=>{let e=new Map;for(let t of i){let r=t.end;if(!r||!n.has(r)||a(t).length<4)continue;let i=e.get(r)??[];i.push(t),e.set(r,i)}return e},`edgesByDestination`);for(let e=0;e<4;e++){let e=o();if(e===0)return;let t=s(),n,r=e,i=t;for(let t of p().values())for(let a=0;a=e||y>r||y===r&&b>=i||(n=v,r=y,i=b)}if(!n)return;for(let[e,t]of n)e.points=t}}t(Pt,`swapDestinationTerminalTailsToReduceCrossings`);function Ft(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=e.filter(e=>!e.isLayoutOnly),o=t((e,t=new Map)=>G(t.get(e)??e.points??[]),`replacementPointsFor`),s=t((e=new Map)=>{let t=0;for(let n=0;na.reduce((t,n)=>t+W(o(n,e)),0),`totalBends`),l=t(e=>{let t=e.start,r=e.end,i=t?n.get(t):void 0,a=r?n.get(r):void 0,o=i?K(i):void 0,s=a?K(a):void 0;return o&&s?{src:o,dst:s}:void 0},`endpointRectsFor`),u=t((e,t,n)=>{if(n.index<=0||n.index+1>=t.length-1)return;let r=l(e);if(r){if(n.vertical){let i=n.a.x,a=Math.min(r.src.left,r.dst.left),o=Math.max(r.src.right,r.dst.right),s=io+Y?`right`:void 0;return s?{edge:e,points:t,segmentIndex:n.index,axis:`vertical`,side:s,coord:i,min:Math.min(n.a.y,n.b.y),max:Math.max(n.a.y,n.b.y)}:void 0}if(n.horizontal){let i=n.a.y,a=Math.min(r.src.top,r.dst.top),o=Math.max(r.src.bottom,r.dst.bottom),s=io+Y?`bottom`:void 0;return s?{edge:e,points:t,segmentIndex:n.index,axis:`horizontal`,side:s,coord:i,min:Math.min(n.a.x,n.b.x),max:Math.max(n.a.x,n.b.x)}:void 0}}},`externalRailForSegment`),d=t(()=>{let e=[];for(let t of a){let n=o(t);for(let r of Z(n)){let i=u(t,n,r);i&&e.push(i)}}return e},`collectExternalRails`),f=t((e,t)=>e.edge!==t.edge&&e.axis===t.axis&&e.side===t.side&&U(e.min,e.max,t.min,t.max)>=X,`railsInteract`),p=t(e=>{let t=[],n=new Set;for(let r of e){if(n.has(r))continue;let i=[r],a=[];for(n.add(r);i.length>0;){let t=i.pop();a.push(t);for(let r of e)!n.has(r)&&f(t,r)&&(n.add(r),i.push(r))}a.length>1&&t.push(a)}return t},`connectedComponents`),m=t(e=>{let t=[];for(let n of e)t.some(e=>Math.abs(e-n.coord){let n=e.map(e=>e.coord),r=m(e),i=[];if(e.length<=6){let a=Array(r.length).fill(!1),o=[],s=t(()=>{if(o.length===e.length){o.some((e,t)=>Math.abs(e-n[t])>=Y)&&i.push([...o]);return}for(let[e,t]of r.entries())a[e]||(a[e]=!0,o.push(t),s(),o.pop(),a[e]=!1)},`visit`);return s(),i}for(let e=0;e{let n=new Map;for(let[r,i]of e.entries()){let e=t[r],a=n.get(i.edge)??i.points.map(e=>({x:e.x,y:e.y}));i.axis===`vertical`?(a[i.segmentIndex].x=e,a[i.segmentIndex+1].x=e):(a[i.segmentIndex].y=e,a[i.segmentIndex+1].y=e),n.set(i.edge,a)}let r=new Map;for(let[e,t]of n){let n=He(G(t));if(Z(n).length!==n.length-1)return;r.set(e,n)}return r},`replacementsForAssignment`),_=t(e=>{for(let[t,n]of e){let e=[t.start,t.end].filter(e=>!!e);for(let t of Z(n))if(q(t.a,t.b,r,e,-2)||q(t.a,t.b,i,[],-2))return!1}for(let t=0;t=X)return!1}}return!0},`candidateIsSafe`);for(let e=0;e<4;e++){let e=s();if(e===0)return;let t,n=e,r=c(),i=1/0;for(let a of p(d()))for(let o of h(a)){let l=g(a,o);if(!l||!_(l))continue;let u=s(l);if(u>=e)continue;let d=c(l),f=a.reduce((e,t,n)=>e+Math.abs(o[n]-t.coord),0);u>n||u===n&&(d>r||d===r&&f>=i)||(t=l,n=u,r=d,i=f)}if(!t)return;for(let[e,n]of t)e.points=n}}t(Ft,`reassignCrossingExternalRailChannels`);function It(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=e.filter(e=>!e.isLayoutOnly),o=t((e,t,n)=>G(e===t?n??[]:e.points??[]),`pointsFor`),s=t(e=>Z(e).reduce((e,t)=>{let n=t.a.x-t.b.x,r=t.a.y-t.b.y;return e+Math.hypot(n,r)},0),`pathLength`),c=t((e,t)=>{let n=0;for(let r=0;r{if(e.horizontal){let n=e.a.y;return(Math.abs(n-t.top)<1||Math.abs(n-t.bottom)<1)&&U(e.a.x,e.b.x,t.left,t.right)>=X}if(e.vertical){let n=e.a.x;return(Math.abs(n-t.left)<1||Math.abs(n-t.right)<1)&&U(e.a.y,e.b.y,t.top,t.bottom)>=X}return!1},`segmentRunsAlongRectBorder`),u=t(e=>{let t=[e.start,e.end].filter(e=>!!e),r=[];for(let e of t){let t=n.get(e),i=t?K(t):void 0;i&&r.push(i)}return r},`endpointRectsFor`),d=t((e,t)=>{if(t+3>=e.length)return[];let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3],o=V(n,r,Y)&&H(r,i,Y)&&V(i,a,Y),s=H(n,r,Y)&&V(r,i,Y)&&H(i,a,Y);if(!o&&!s||!(o?Math.sign(r.x-n.x)!==Math.sign(a.x-i.x):Math.sign(r.y-n.y)!==Math.sign(a.y-i.y)))return[];let c=z(n,a,Y)||B(n,a,Y)?[]:[{x:n.x,y:a.y},{x:a.x,y:n.y}],l=c.length===0?[[...e.slice(0,t+1),...e.slice(t+3)]]:c.map(n=>[...e.slice(0,t+1),n,...e.slice(t+3)]),u=new Set;return l.map(e=>He(G(e))).filter(e=>{if(Z(e).length!==e.length-1||!e.some(e=>R(e,a,Y)))return!1;let t=e.map(e=>`${e.x.toFixed(3)},${e.y.toFixed(3)}`).join(`|`);return u.has(t)?!1:(u.add(t),!0)})},`shortcutCandidatesAt`),f=t((e,t,n)=>{let s=[e.start,e.end].filter(e=>!!e),d=u(e);for(let e of Z(t))if(q(e.a,e.b,r,s,-2)||q(e.a,e.b,i,[],-2)||d.some(t=>l(e,t)))return!1;for(let n of a)if(n!==e){for(let e of Z(t))for(let t of Z(o(n)))if(ve(e,t,.5)>=X)return!1}return c(e,t)<=n},`candidateIsSafe`);for(let e=0;e<8;e++){let e=c(),t,n,r=e,i=1/0,l=1/0;for(let u of a){let a=o(u),p=W(a,Y),m=s(a);for(let o=0;o<=a.length-4;o++)for(let h of d(a,o)){let a=W(h,Y),o=s(h);if(!(ar||d===r&&(a>i||a===i&&o>=l)||(t=u,n=h,r=d,i=a,l=o)}}if(!t||!n)return;t.points=n}}t(It,`shortcutRedundantOrthogonalJogs`);function Lt(e,n){let r=[];for(let e of n.values()){if(e.isGroup||e.isEdgeLabel)continue;let t=e.x??0,n=e.y??0,i=K(e);i&&r.push({id:String(e.id??``),cx:t,cy:n,rect:i})}if(r.length===0)return;let i=new Map(r.map(e=>[e.id,e])),a=r.map(e=>({id:e.id,rect:e.rect})),o=[`top`,`bottom`,`left`,`right`],s={top:Math.min(...r.map(e=>e.rect.top))-20,bottom:Math.max(...r.map(e=>e.rect.bottom))+20,left:Math.min(...r.map(e=>e.rect.left))-20,right:Math.max(...r.map(e=>e.rect.right))+20},c=e.filter(e=>!e.isLayoutOnly),l=new Map(c.map((e,t)=>[e,t])),u=t(e=>{let t=e===`left`||e===`top`?-1:1,n=[];for(let r=0;r<=2;r++)n.push(s[e]+t*20*r);return n},`outwardTracksForSide`),d=t((e,t=new Map)=>G(t.get(e)??e.points??[]),`replacementPointsFor`),f=t((e,t)=>{let n=0;for(let r of e)for(let e of t)Le(r.a,r.b,e.a,e.b,Y)&&n++;return n},`crossingCountBetweenSegments`),p=t((e,t)=>f(Z(e),Z(t)),`crossingCountBetweenPaths`),m=t((e=new Map)=>{let n=0,r=[],i=new Set,a=[],o=t(e=>{i.has(e)||(i.add(e),a.push(e))},`addEdge`);for(let t=0;t0&&(n+=l,r.push({first:i,second:t,count:l}),o(i),o(t))}}return a.sort((e,t)=>(l.get(e)??0)-(l.get(t)??0)),{count:n,pairs:r,edgeSet:i,edges:a}},`crossingSnapshot`),h=t((e,t)=>{let n=new Set(t.keys());if(n.size===0)return e.count;let r=0;for(let t of e.pairs)(n.has(t.first)||n.has(t.second))&&(r+=t.count);let i=0;for(let e=0;e{let t=new Map;for(let n of e.pairs){let e=t.get(n.first)??new Set;e.add(n.second),t.set(n.first,e);let r=t.get(n.second)??new Set;r.add(n.first),t.set(n.second,r)}let n=[],r=new Set;for(let i of e.edges){if(r.has(i))continue;let e=[i],a=[];for(r.add(i);e.length>0;){let n=e.pop();a.push(n);for(let i of t.get(n)??[])r.has(i)||(r.add(i),e.push(i))}a.sort((e,t)=>(l.get(e)??0)-(l.get(t)??0)),a.length>1&&n.push(a)}return n},`crossingComponents`),_=t(e=>[e.start,e.end].filter(e=>!!e),`endpointIdsFor`),v=t(e=>{let t=[];for(let n of g(e)){let e=new Set(n),r=new Set(n.flatMap(e=>_(e))),i=[...n];for(let t of c)e.has(t)||_(t).some(e=>r.has(e))&&i.push(t);i.sort((e,t)=>(l.get(e)??0)-(l.get(t)??0)),t.push(i)}return t},`pairSearchGroups`),y=t((e,t,n)=>h(e,new Map([[t,n]])),`crossingCountWithSingleReplacement`),b=t(e=>{let t=new Map;for(let n of e.pairs)t.set(n.first,(t.get(n.first)??0)+n.count),t.set(n.second,(t.get(n.second)??0)+n.count);return t},`currentCrossingsByEdge`),x=t(e=>e.slice(1).reduce((t,n,r)=>{let i=e[r];return t+Math.abs(n.x-i.x)+Math.abs(n.y-i.y)},0),`pathLength`),S=t((e=new Map)=>c.reduce((t,n)=>t+W(d(n,e)),0),`totalBends`),C=t((e=new Map)=>c.reduce((t,n)=>t+x(d(n,e)),0),`totalLength`),w=t((e,t,n=new Map)=>{let r=Z(t);for(let t of c)if(t!==e){for(let e of r)for(let r of Z(d(t,n)))if(ve(e,r,.5)>=X)return!0}return!1},`pathHasSegmentConflict`),T=t((e,t)=>{let n=[e.start,e.end].filter(e=>!!e);for(let e of Z(t))if(q(e.a,e.b,a,n,-2))return!0;return!1},`pathHitsNode`),E=t((e,t)=>{let n=He(G(t));Z(n).length===n.length-1&&e.push(n)},`pushOrthogonalCandidate`),D=t(e=>e===`left`||e===`right`,`sideIsHorizontal`),O=t((e,t,n)=>{switch(t){case`left`:return Math.min(e.x,n.x)-20;case`right`:return Math.max(e.x,n.x)+20;case`top`:return Math.min(e.y,n.y)-20;case`bottom`:return Math.max(e.y,n.y)+20}},`localTrackForSameSide`),k=t((e,t,n,r)=>{let i=n===`left`||n===`top`?-1:1,a=[O(t,n,r),s[n]];for(let o of a)for(let a=0;a<=2;a++)E(e,ke(t,n,r,o+i*20*a))},`addSameSideCandidates`),A=t((e,t,n,r,i)=>{for(let a of u(n))for(let n of u(i))E(e,[t,{x:a,y:t.y},{x:a,y:n},{x:r.x,y:n},r])},`addHorizontalToVerticalCandidates`),j=t((e,t,n,r,i)=>{for(let a of u(n))for(let n of u(i))E(e,[t,{x:t.x,y:a},{x:n,y:a},{x:n,y:r.y},r])},`addVerticalToHorizontalCandidates`),ee=t((e,t,n,r,i)=>{let a=[...u(`top`),...u(`bottom`)];for(let o of u(n))for(let n of u(i))for(let i of a)E(e,[t,{x:o,y:t.y},{x:o,y:i},{x:n,y:i},{x:n,y:r.y},r])},`addHorizontalPairCandidates`),te=t((e,t,n,r,i)=>{let a=[...u(`left`),...u(`right`)];for(let o of u(n))for(let n of u(i))for(let i of a)E(e,[t,{x:t.x,y:o},{x:i,y:o},{x:i,y:n},{x:r.x,y:n},r])},`addVerticalPairCandidates`),M=t(e=>{let t=new Set;return e.map(e=>G(e)).filter(e=>{let n=e.map(e=>`${e.x.toFixed(3)},${e.y.toFixed(3)}`).join(`|`);return t.has(n)||e.length<2?!1:(t.add(n),!0)})},`dedupeCandidatePaths`),ne=t((e,t,n,r)=>{let i=[],a=Oe(e,t,n,r,20,Y);a&&E(i,a),t===r&&k(i,e,t,n);let o=D(t),s=D(r);return o&&!s?A(i,e,t,n,r):!o&&s?j(i,e,t,n,r):o?ee(i,e,t,n,r):te(i,e,t,n,r),M(i)},`buildCandidatesForSides`),N=t((e,t,n,r)=>{let i=[...u(`left`),...u(`right`)],a=[...u(`top`),...u(`bottom`)];for(let s of o){let o=De(r,s),c=s===`top`||s===`bottom`?u(s):a;for(let r of i){E(e,[t,n,{x:r,y:n.y},{x:r,y:o.y},o]);for(let i of c)E(e,[t,n,{x:r,y:n.y},{x:r,y:i},{x:o.x,y:i},o])}}},`addVerticalDepartureOuterTrackCandidates`),re=t((e,t,n,r)=>{let i=[...u(`left`),...u(`right`)],a=[...u(`top`),...u(`bottom`)];for(let s of o){let o=De(r,s),c=s===`left`||s===`right`?u(s):i;for(let r of a){E(e,[t,n,{x:n.x,y:r},{x:o.x,y:r},o]);for(let i of c)E(e,[t,n,{x:n.x,y:r},{x:i,y:r},{x:i,y:o.y},o])}}},`addHorizontalDepartureOuterTrackCandidates`),P=t(e=>{let t=e.start,n=e.end,r=n?i.get(n):void 0;if(!t||!r)return[];let a=G(e.points??[]);if(a.length<4)return[];let o=a[0],s=a[1],c=[];return H(o,s,Y)?N(c,o,s,r):V(o,s,Y)&&re(c,o,s,r),c},`terminalPreservingOuterTrackCandidates`),ie=t(e=>{let t=e.start,n=e.end,r=t?i.get(t):void 0,a=n?i.get(n):void 0;if(!r||!a)return[];let s=[];for(let e of o){let t=De(r,e);for(let n of o)s.push(...ne(t,e,De(a,n),n))}return s.push(...P(e)),s},`candidatePathsFor`),ae=t(()=>new Map(c.map(e=>[e,Z(d(e))])),`currentSegmentsByEdge`),oe=t((e,t,n)=>{let r=new Set;for(let i of c){if(i===e)continue;let a=n.get(i)??Z(d(i));t.some(e=>a.some(t=>ve(e,t,.5)>=X))&&r.add(i)}return r},`sharedTrackConflictsFor`),se=t((e,t,n,r)=>{let i=new Set;return ie(e).map(e=>He(G(e))).filter(t=>{if(T(e,t))return!1;let n=t.map(e=>`${e.x.toFixed(3)},${e.y.toFixed(3)}`).join(`|`);return i.has(n)||t.length<2?!1:(i.add(n),!0)}).map(i=>{let a=Z(i),o=0;for(let t of c)t!==e&&(o+=f(a,n.get(t)??Z(d(t))));return{candidate:i,candidateSegments:a,crossings:t.count-(r.get(e)??0)+o,bends:W(i,Y),totalBends:W(i),length:x(i)}}).filter(({crossings:e})=>e<=t.count).sort((e,t)=>e.crossings-t.crossings||e.bends-t.bends||e.length-t.length).slice(0,48).map(t=>({path:t.candidate,segments:t.candidateSegments,sharedTrackConflicts:oe(e,t.candidateSegments,n),totalBends:t.totalBends,length:t.length}))},`pairCandidatesFor`),ce=t((e,t,n,r,i,a)=>{let o=0;for(let n of e.pairs)(n.first===t||n.second===t||n.first===r||n.second===r)&&(o+=n.count);let s=f(n.segments,i.segments);for(let e of c){if(e===t||e===r)continue;let o=a.get(e)??Z(d(e));s+=f(n.segments,o)+f(i.segments,o)}return e.count-o+s},`pairCrossingCount`),le=t((e,t)=>{for(let n of e.sharedTrackConflicts)if(n!==t)return!1;return!0},`conflictsOnlyWith`),ue=t((e,t)=>e.segments.some(e=>t.segments.some(t=>ve(e,t,.5)>=X)),`candidatesShareTrack`),de=t((e,t,n,r)=>le(t,n.edge)&&le(r,e.edge)&&!ue(t,r),`pairCandidatesAreCompatible`),fe=t((e,t,n,r,i)=>{let a=ce(e.current,t.edge,n,r.edge,i,e.baseSegments);if(!(a>=e.current.count))return{replacements:new Map([[t.edge,n.path],[r.edge,i.path]]),crossings:a,bends:e.currentBends-(e.baseBendsByEdge.get(t.edge)??0)-(e.baseBendsByEdge.get(r.edge)??0)+n.totalBends+i.totalBends,length:e.currentLength-(e.baseLengthByEdge.get(t.edge)??0)-(e.baseLengthByEdge.get(r.edge)??0)+n.length+i.length}},`scorePairReplacement`),pe=t((e,t)=>e.crossings{let i=r;for(let r of t.candidates)for(let a of n.candidates){if(!de(t,r,n,a))continue;let o=fe(e,t,r,n,a);o&&pe(o,i)&&(i=o)}return i},`bestScoreForOptionPair`),I=t(e=>{let t=S(),n=C(),r=ae(),i=b(e),a=new Map(c.map(e=>[e,W(d(e))])),o=new Map(c.map(e=>[e,x(d(e))])),s=new Map,l=v(e);for(let t of l)for(let n of t){if(s.has(n))continue;let t=se(n,e,r,i);t.length>0&&s.set(n,{edge:n,candidates:t})}let u={replacements:new Map,crossings:e.count,bends:t,length:n},f={current:e,currentBends:t,currentLength:n,baseBendsByEdge:a,baseLengthByEdge:o,baseSegments:r};for(let t of l){let n=new Set(t.filter(t=>e.edgeSet.has(t))),r=t.map(e=>s.get(e)).filter(e=>!!e);for(let e=0;e0?u.replacements:void 0},`bestPairedReplacement`);for(let e=0;e<4;e++){let e=m(),t=e.count;if(t===0)return;let n,r,i=t,a=1/0;for(let o of e.edges){let s=W(d(o),Y);for(let c of ie(o)){let l=T(o,c),u=!l&&w(o,c),d=y(e,o,c),f=W(c,Y);l||u||(di||d===i&&f>=a||(n=o,r=c,i=d,a=f))}}if(n&&r){n.points=r;continue}let o=I(e);if(!o)return;for(let[e,t]of o)e.points=t}}t(Lt,`resolveRenderedOrthogonalCrossings`);var Rt=.001,zt=8;function Bt(e,n){let{nodeInfoById:r,realNodeRects:i}=Ae(n),a=[`top`,`bottom`,`left`,`right`],o={top:Math.min(...i.map(e=>e.rect.top))-20,bottom:Math.max(...i.map(e=>e.rect.bottom))+20,left:Math.min(...i.map(e=>e.rect.left))-20,right:Math.max(...i.map(e=>e.rect.right))+20},s=t((e,t,n,r)=>{let i=[],a=Oe(e,t,n,r,20,Rt);return a&&i.push(a),t===r&&i.push(ke(e,t,n,o[t])),i},`buildOrthogonalPathCandidates`),c=t((e,t)=>{for(let n=0;n{let i=0,a=ye(t,Rt),o=n.start,s=n.end;for(let t of e){if(t===n||t.isLayoutOnly)continue;let e=t.start,c=t.end;if(!r&&o&&s&&(e===o||e===s||c===o||c===s))continue;let l=t.points;if(!(!l||l.length<2))for(let e of a)for(let t of ye(l,Rt)){if(Pe(e.a,e.b,t.a,t.b,Rt,Rt)){i++;continue}ve(e,t,Rt)>=zt&&i++}}return i},`pathConflictCount`),u=t((e,t)=>{let n=Math.abs(e.y-t.rect.top),r=Math.abs(e.y-t.rect.bottom),i=Math.abs(e.x-t.rect.left),a=Math.abs(e.x-t.rect.right),o=`top`,s=n;return r{let r=d.get(e)??[];r.push({side:t,edgeId:n}),d.set(e,r)},`addFaceClaim`);for(let t of e){if(t.isLayoutOnly)continue;let e=t.points??[];if(e.length<1)continue;let n=t.id??``,i=t.start,a=t.end;if(i){let t=r.get(i);t&&f(i,u(e[0],t),n)}if(a){let t=r.get(a);t&&f(a,u(e[e.length-1],t),n)}}let p=t((e,t,n)=>d.get(e)?.some(e=>e.edgeId!==n&&e.side===t)??!1,`faceIsClaimed`);for(let t of e){if(t.isLayoutOnly)continue;let e=t.points;if(!e||e.length<2)continue;let n=W(e,Rt);if(n<4)continue;let i=t.start,o=t.end;if(!i||!o)continue;let m=r.get(i),h=r.get(o);if(!m||!h)continue;let g=t.id??``,_=l(e,t,!0),v=l(e,t),y,b=_,x=n;for(let e of a){if(p(i,e,g))continue;let n=De(m,e);for(let r of a){if(p(o,r,g))continue;let a=De(h,r);for(let u of s(n,e,a,r)){if(c(u,[i,o]))continue;let e=W(u,Rt);if(_>0){let n=l(u,t,!0);if(n>b||n===b&&e>=x)continue;b=n,x=e,y=u;continue}l(u,t)>v||ee.edgeId!==g));let n=d.get(o);n&&d.set(o,n.filter(e=>e.edgeId!==g)),f(i,u(y[0],m),g),f(o,u(y[y.length-1],h),g)}}}t(Bt,`simplifyDetouredEdges`);var Q=.001,Vt=10,Ht=7;function Ut(e,t){let n=t?0:e.length-1,r=t?1:-1,i=e[n],a=e[n+r];if(!i||!a)return;let o=a.x-i.x,s=a.y-i.y;if(!(Math.abs(o)+Math.abs(s)t&&we(e,Wt(t)))}t(Gt,`labelOverlapsOwnMarker`);function Kt(e,n){let r=[];for(let t of e){if(t.isLayoutOnly)continue;let e=t.points;if(!(!e||e.length<2))for(let n=0;n{let n=Te(t,3);for(let{nodeId:t,rect:r}of i)if(t!==e&&we(n,r))return!0;return!1},`labelOverlapsForeignNode`),s=t((e,t)=>{let n=Te(t,3);for(let t of r)if(t.edgeId!==e&&xe(t.p1,t.p2,n))return!0;return!1},`labelOverlapsForeignEdge`),c=t((e,t,n)=>o(e,n)||s(t,n),`labelOverlapsAnything`),l=[],u=t(e=>{for(let{id:t,rect:n}of a)if(Ce(n,e))return t},`findContainingLane`),d=t((e,t)=>l.some(n=>n.labelId!==e&&we(t,n.rect)),`overlapsPlacedLabel`);for(let r of e){if(r.isLayoutOnly)continue;let e=r.labelNodeId;if(!e)continue;let i=n.get(e);if(!i)continue;let f=r.points;if(!f||f.length<2)continue;let p=i.width??0,m=i.height??0;if(p<=0||m<=0)continue;let h=[];for(let e=0;e=Q&&i>=Q||h.push({idx:e,length:r+i,orientation:r>=Q?`horizontal`:`vertical`,midX:(t.x+n.x)/2,midY:(t.y+n.y)/2})}if(h.length===0)continue;let g=h.length>=3?h.filter(e=>e.idx>0&&e.idx0?g:h,v=p>=m?`horizontal`:`vertical`,y=t(e=>[...e].sort((e,t)=>{let n=e.orientation===v;if(n!==(t.orientation===v))return n?-1:1;let r=e.length>=(e.orientation===`horizontal`?p:m)+2;return r===t.length>=(t.orientation===`horizontal`?p:m)+2?t.length-e.length:r?-1:1}),`rankSegments`),b=h[0],x=h[h.length-1],S=[.5,.25,.75,.05,.95,.15,.85,.1,.9],C=t((e,t)=>{let n=f[e.idx],r=f[e.idx+1];return{midX:n.x+(r.x-n.x)*t,midY:n.y+(r.y-n.y)*t}},`anchorAtT`),w=t((e,t,n)=>Math.min(n,Math.max(t,e)),`clamp`),T=t((e,t)=>e.midX>=t.left-Q&&e.midX<=t.right+Q&&e.midY>=t.top-Q&&e.midY<=t.bottom+Q,`pointInsideRectInclusive`),E=t(e=>{let t=Ee(e.midX,e.midY,p,m),n=u(t);if(n)return{laneId:n,anchor:e,rect:t};let r=a.find(({rect:t})=>T(e,t));if(!r)return;let i=r.rect.left+p/2+1,o=r.rect.right-p/2-1,s=r.rect.top+m/2+1,c=r.rect.bottom-m/2-1;if(i>o||s>c)return;let l={midX:w(e.midX,i,o),midY:w(e.midY,s,c)},d=Ee(l.midX,l.midY,p,m);return T(e,d)?{laneId:r.id,anchor:l,rect:d}:void 0},`placementForAnchor`),D=t((e,t,n)=>e.orientation===`horizontal`?Math.abs(t.midX-n.x):Math.abs(t.midY-n.y),`distanceAlongSegment`),O=t((e,t)=>{let n=(e.orientation===`horizontal`?p/2:m/2)+12;if(e===b){let r=f[e.idx];if(D(e,t,r)+Q{let n=y(t);for(let t of n)for(let n of S){let i=C(t,n);if(!O(t,i))continue;let a=E(i);if(a&&!Gt(a.rect,f)&&!d(e,a.rect)&&!c(e,r.id,a.rect))return{laneId:a.laneId,anchor:a.anchor}}},`tryPool`),A=t((t,n,i=!1)=>{let a=y(t);for(let t of a){let a={midX:t.midX,midY:t.midY};if(n&&!O(t,a))continue;let c=E(a);if(c&&!Gt(c.rect,f)&&!d(e,c.rect)&&!o(e,c.rect)&&(i||!s(r.id,c.rect)))return{laneId:c.laneId,anchor:c.anchor}}},`findLaneContainingFallback`),j=k(_)??(_.lengtht.labelId===e);n>=0?l[n]={labelId:e,rect:t}:l.push({labelId:e,rect:t})}}}t(Kt,`anchorLabelsToPolyline`);var qt=1e-6,Jt=8/2,Yt=3;function Xt(e,t){return e{let s=Xt(r,i),c=0,l=t(e=>{if(!e)return;let t=a.get(e);if(!t)return;let n=o===`x`?t.w/2:t.h/2;n>c&&(c=n)},`consider`);l(n.labelNodeId);for(let t of e){if(t===n||t.isLayoutOnly)continue;let e=t.start,r=t.end;!e||!r||Xt(e,r)===s&&l(t.labelNodeId)}return c>0?c+Yt:0},`labelClearanceFor`);for(let t of e){if(t.isLayoutOnly)continue;let n=t.points;if(!be(n,qt))continue;let a=Ne(t,r,qt);if(!a)continue;let{srcId:s,dstId:c,srcInfo:l,dstInfo:u,collinearX:d,collinearY:f}=a;if(d===f)continue;let p,m;if(d){let e=u.cy>l.cy;p={x:l.cx,y:e?l.rect.bottom:l.rect.top},m={x:u.cx,y:e?u.rect.top:u.rect.bottom}}else{let e=u.cx>l.cx;p={x:e?l.rect.right:l.rect.left,y:l.cy},m={x:e?u.rect.left:u.rect.right,y:u.cy}}if(q(p,m,i,[s,c],1))continue;let h=o(t,s,c,d?`x`:`y`),g=h>Jt?h:Jt,_=[0,g,-g];for(let n of _){let r={...p},a={...m};if(d){if(r.x+=n,a.x+=n,r.x<=l.rect.left||r.x>=l.rect.right||a.x<=u.rect.left||a.x>=u.rect.right)continue}else if(r.y+=n,a.y+=n,r.y<=l.rect.top||r.y>=l.rect.bottom||a.y<=u.rect.top||a.y>=u.rect.bottom)continue;if(!q(r,a,i,[s,c],1)&&!Ie(r,a,e,t,{epsilon:qt})){t.points=[r,a];break}}}}t(Zt,`straightenCollinearSiblingDetours`);function Qt(e,n){let r=.001,{realNodeRects:i,labelNodeRects:a}=je(n.values()),o=t((e,t)=>ye(t,r).map(n=>({...n,edge:e,interior:n.index>=1&&n.index<=t.length-3})),`segmentsFor`),s=t(()=>{let t=[];for(let n of e){if(n.isLayoutOnly)continue;let e=n.points;!e||e.length<2||t.push(...o(n,G(e)))}return t},`allSegments`),c=t((e,t)=>e.horizontal&&t.horizontal?U(e.a.x,e.b.x,t.a.x,t.b.x)>=8&&Math.abs(e.a.y-t.a.y)<7:e.vertical&&t.vertical?U(e.a.y,e.b.y,t.a.y,t.b.y)>=8&&Math.abs(e.a.x-t.a.x)<7:!1,`hasCrowdedParallelTrack`),l=t((t,n)=>{let s=t.start,l=t.end,u=o(t,n);if(u.length!==n.length-1)return!1;let d=[s,l].filter(e=>!!e),f=t.labelNodeId?[t.labelNodeId]:[];for(let e of u)if(q(e.a,e.b,i,d,-2)||q(e.a,e.b,a,f,-2))return!1;for(let n of e){if(n===t||n.isLayoutOnly)continue;let e=n.points;if(!(!e||e.length<2)){for(let t of u)for(let i of o(n,G(e)))if(c(t,i)||Le(t.a,t.b,i.a,i.b,r))return!1}}return!0},`candidateIsSafe`),u=t((e,t)=>{let n=G(e.edge.points??[]);if(n.length<4||e.index>=n.length-1)return;let r=n.map(e=>({...e}));if(e.horizontal)r[e.index].y+=t,r[e.index+1].y+=t;else if(e.vertical)r[e.index].x+=t,r[e.index+1].x+=t;else return;return o(e.edge,r).length===r.length-1?r:void 0},`shiftedCandidate`),d=t((e,t)=>({x:e.x??(t.left+t.right)/2,y:e.y??(t.top+t.bottom)/2}),`nodeCenter`),f=t(e=>{let t=e.edge,r=G(t.points??[]);if(r.length!==4||e.index!==1)return;let i=t.start?n.get(t.start):void 0,a=t.end?n.get(t.end):void 0,o=i?K(i):void 0,s=a?K(a):void 0,c=r.slice(e.index+2);if(!(!i||!a||!o||!s||c.length===0))return{sourceCenter:d(i,o),targetCenter:d(a,s),sourceRect:o,tail:c}},`sourceDetourContextFor`),p=t((e,t,n,i,a,o)=>{let s=i.y>=n.y,c=s?a.bottom:a.top,l=c+(s?20:-20);if(s&&e.b.y<=l+r||!s&&e.b.y>=l-r)return;let u=e.a.x+t;return G([{x:n.x,y:c},{x:n.x,y:l},{x:u,y:l},{x:u,y:e.b.y},...o],r)},`verticalSourceDetour`),m=t((e,t,n,i,a,o)=>{let s=i.x>=n.x,c=s?a.right:a.left,l=c+(s?20:-20);if(s&&e.b.x<=l+r||!s&&e.b.x>=l-r)return;let u=e.a.y+t;return G([{x:c,y:n.y},{x:l,y:n.y},{x:l,y:u},{x:e.b.x,y:u},...o],r)},`horizontalSourceDetour`),h=t((e,t)=>{let n=f(e);if(n){if(e.vertical)return p(e,t,n.sourceCenter,n.targetCenter,n.sourceRect,n.tail);if(e.horizontal)return m(e,t,n.sourceCenter,n.targetCenter,n.sourceRect,n.tail)}},`sourceDetourCandidate`),g=[-7,7,-14,14,-21,21];for(let e=0;e<12;e++){let e=s(),t=!1;for(let n=0;ne.interior);for(let e of o){for(let n of g){let r=u(e,n);if(r&&l(e.edge,r)){e.edge.points=r,t=!0;break}let i=h(e,n);if(i&&l(e.edge,i)){e.edge.points=i,t=!0;break}}if(t)break}}if(!t)return}}t(Qt,`nudgeSharedInteriorSubpaths`);function $t(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=r.x-n.x,s=r.y-n.y,c=i*s-a*o;if(Math.abs(c)<1e-10)return!1;let l=n.x-e.x,u=n.y-e.y,d=(l*s-u*o)/c,f=(l*a-u*i)/c,p=.01;return d>p&&d<1-p&&f>p&&f<1-p}t($t,`segmentsIntersect`);function en(e){let t=e.nodes??[],r=e.edges??[],i=[];if(!r.length||!t.length)return i;let a=Me(t),o=[];for(let e of r){if(e.isLayoutOnly)continue;let t=e.points;if(!t||t.length<2)continue;let n=e.start,r=e.end,s=e.labelNodeId,c=e.id??`${n}->${r}`;for(let e of a)if(!(e.nodeId===n||e.nodeId===r)&&!(s&&e.nodeId===s)){for(let n=0;n0){let e=i.filter(e=>e.type===`edge-node-overlap`).length,t=i.filter(e=>e.type===`edge-edge-crossing`).length;n.warn(`[SWIMLANE_VALIDATE] ${i.length} issue(s) detected: ${e} edge-node overlap(s), ${t} edge crossing(s)`);for(let e of i)n.warn(`[SWIMLANE_VALIDATE] ${e.type}: ${e.detail}`)}return i}t(en,`validateSwimlanesLayout`);function tn(e,n){let r=e.nodes??[],i=e.edges??[],a=r.filter(e=>!e.isGroup);if((n===`LR`||n===`RL`)&&a.length>0&&!St(e,n)||n===`BT`&&a.length>0&&!xt(e))return;for(let e of i){if(e.isLayoutOnly)continue;let t=e.points;!t||t.length<2||(e.points=He(Ve(t)))}Bt(i,r),Zt(i,r),Et(i,r);let o=new Map;for(let e of r)o.set(String(e.id),e);Kt(i,o),Je(i,o),Dt(i,o),Qt(i,o),kt(i,o),At(i,o),jt(i,o),Pt(i,o);let s=t(()=>{Lt(i,o),Ft(i,o),It(i,o),Kt(i,o),pt(i,o),jt(i,o),Kt(i,o),pt(i,o)},`finalizeRenderedEdges`);s(),Qt(i,o),s(),Mt(i,o),Nt(i,o),Mt(i,o),Nt(i,o)}t(tn,`postProcessSwimlaneLayout`);function nn(e){let t=new Map(e.nodeById),n=new Set,r=[];for(let i of e.edges){if(!t.has(i.src)||!t.has(i.dst))continue;let e=`${i.id}:${i.src}->${i.dst}`;n.has(e)||(n.add(e),r.push(i))}return{nodes:[...t.keys()],edges:r,layout:e.layout,nodeById:t}}t(nn,`normalizeGraph`);function rn(e,t){return e.edges.filter(e=>e.dst===t)}t(rn,`incoming`);function an(e){let t=new Map;for(let n of e.nodes)t.set(n,[]);for(let n of e.edges)t.get(n.src).push(n.dst);return t}t(an,`buildSuccessorMap`);function on(e){let t=an(e);for(let e of t.values())e.sort((e,t)=>e.localeCompare(t));return t}t(on,`buildSortedSuccessorMap`);function sn(e){let t=new Map;for(let n of e.nodes)t.set(n,0);for(let n of e.edges)t.set(n.dst,(t.get(n.dst)??0)+1);return t}t(sn,`buildInDegreeMap`);function cn(e){return[...e.entries()].filter(([,e])=>e===0).map(([e])=>e).sort((e,t)=>e.localeCompare(t))}t(cn,`sortedZeroInDegreeNodes`);function ln(e,t=()=>!0){let n=new Map,r=new Map;for(let t of e.nodes)n.set(t,[]),r.set(t,[]);for(let i of e.edges)t(i)&&(r.get(i.src).push(i.dst),n.get(i.dst).push(i.src));return{preds:n,succs:r}}t(ln,`buildPredecessorSuccessorMaps`);function un(e,t,n,r){let i=0;for(let t of e.nodes)r?.skipGroups&&e.nodeById.get(t)?.isGroup||(i=Math.max(i,n[t]??0));let a=Array.from({length:i+1},()=>[]);for(let i of t)r?.skipGroups&&e.nodeById.get(i)?.isGroup||a[Math.max(0,n[i]??0)].push(i);return a}t(un,`buildLayersFromRanks`);function dn(e){let t=sn(e),n=cn(t),r=[],i=on(e);for(;n.length;){let e=n.shift();r.push(e);for(let r of i.get(e)??[])if(t.set(r,(t.get(r)??0)-1),(t.get(r)??0)===0){let e=0;for(;e{if(i-t<=1)return 0;let a=t+i>>1,o=r(t,a)+r(a,i),s=t,c=a,l=t;for(;s=i||se.dst===t.dst?e.id.localeCompare(t.id):e.dst.localeCompare(t.dst));let i=Object.create(null);for(let e of n.nodes)i[e]=0;let a=[],o=t(e=>{i[e]=1;for(let t of r.get(e)??[]){let e=t.dst;i[e]===0?o(e):i[e]===1&&a.push(t)}i[e]=2},`dfs`),s=[...n.nodes].sort((e,t)=>e.localeCompare(t));for(let e of s)i[e]===0&&o(e);let c=new Set(a.map(e=>`${e.id}:${e.src}->${e.dst}`)),l=n.edges.map(e=>c.has(`${e.id}:${e.src}->${e.dst}`)?{id:e.id,src:e.dst,dst:e.src,weight:e.weight,ref:e.ref}:e);return{acyclic:{nodes:[...n.nodes],edges:l,layout:n.layout,nodeById:new Map(n.nodeById)},reversed:a}}t(mn,`removeCycles_DFS`);function hn(e){let n=new Map,r=t(t=>{if(n.has(t))return n.get(t);let i=e.nodeById.get(t);if(!i)return n.set(t,null),null;let a=i.parentId;if(!a)return n.set(t,null),null;let o=r(a)??a;return n.set(t,o),o},`resolve`);for(let t of e.nodes)r(t);return n}t(hn,`buildTopLaneMap`);function gn(e){let t=hn(e);return e=>t.get(e)??null}t(gn,`createTopLaneResolver`);function _n(e){let t=[];for(let n of e.layout.nodes??[])n.isGroup&&!n.parentId&&t.push(n.id);return[...new Set(t)].reverse()}t(_n,`buildTopLaneOrder`);function vn(e,t){let n=_n(e);if(!t||t.length===0)return n;let r=new Set(n),i=new Set,a=[];for(let e of t)!r.has(e)||i.has(e)||(i.add(e),a.push(e));for(let e of n)i.has(e)||a.push(e);return a}t(vn,`resolveTopLaneOrder`);var yn={EPSILON:1e-6},bn={GRAVITY_ITERATIONS:8,MAX_CROSSING_OPTIMIZATION_PASSES:4,DEFAULT_COMPACT_SINGLE_INPUT:!0},xn={DEFAULT_LAYER_GAP:100,DEFAULT_NODE_GAP:40};function Sn(e,n){let r=nn(e),i=n?.laneOf??(()=>null),a=n?.rankHint,{preds:o}=ln(r);for(let e of o.values())e.sort((e,t)=>e.localeCompare(t));let s=dn(r)??[...r.nodes].sort((e,t)=>e.localeCompare(t)),c=new Map;for(let[e,t]of s.entries())c.set(t,e);let l=new Map,u=new Map;for(let e of r.nodes)u.set(e,[]);for(let e of s){let t=(o.get(e)??[]).filter(e=>l.has(e));if(t.length>0){let n=Cn(e,t,{laneOf:i,rankHint:a,topoIndex:c});l.set(e,n),u.get(n).push(e)}else l.has(e)||l.set(e,null)}for(let e of r.nodes)l.has(e)||l.set(e,null);let d=new Set;for(let e of r.nodes)(l.get(e)??null)===null&&d.add(e);let f=[...d].sort((e,t)=>{let n=c.get(e)??0,r=c.get(t)??0;return n===r?e.localeCompare(t):n-r}),p=wn(r),m=new Map;for(let[e,t]of p.entries())m.set(e,[...t].sort((e,t)=>e.localeCompare(t)));let h=Tn(m),g=En(m),_=new Map;for(let e of r.nodes)_.set(e,[]);for(let e of g)for(let t of e.nodes){let n=_.get(t);n?n.push(e.id):_.set(t,[e.id])}let v=[],y=[],b=new Set,x=t(e=>{if(!b.has(e)){b.add(e),v.push(e);for(let t of u.get(e)??[])x(t);y.push(e)}},`walk`);for(let e of f)x(e);for(let e of s)x(e);return{parent:l,children:u,roots:f,componentOf:h,blocks:g,nodeBlocks:_,adjacency:m,preorder:v,postorder:y,topologicalOrder:s}}t(Sn,`buildDrivingTree`);function Cn(e,t,n){let r=n.laneOf(e);return[...t].sort((e,t)=>{let i=n.laneOf(e),a=n.laneOf(t),o=i!=null&&i===r;if(o!==(a!=null&&a===r))return o?-1:1;let s=n.rankHint?.[e],c=n.rankHint?.[t];if(s!=null&&c!=null&&s!==c)return c-s;let l=n.topoIndex.get(e)??0,u=n.topoIndex.get(t)??0;return l===u?e.localeCompare(t):l-u})[0]}t(Cn,`chooseParent`);function wn(e){let t=new Map;for(let n of e.nodes)t.set(n,new Set);for(let n of e.edges)t.get(n.src).add(n.dst),t.get(n.dst).add(n.src);return t}t(wn,`buildAdjacency`);function Tn(e){let t=new Map,n=0;for(let r of e.keys()){if(t.has(r))continue;let i=[r];for(;i.length>0;){let r=i.pop();if(!t.has(r)){t.set(r,n);for(let n of e.get(r)??[])t.has(n)||i.push(n)}}n++}return t}t(Tn,`assignComponents`);function En(e){let n=new Map,r=new Map,i=[],a=[],o=0,s=t((t,c)=>{n.set(t,++o),r.set(t,o);for(let l of e.get(t)??[])l!==c&&(n.has(l)?(n.get(l)??0)<(n.get(t)??0)&&(i.push([t,l]),r.set(t,Math.min(r.get(t)??o,n.get(l)??o))):(i.push([t,l]),s(l,t),r.set(t,Math.min(r.get(t)??o,r.get(l)??o)),(r.get(l)??0)>=(n.get(t)??0)&&a.push(Dn(t,l,i,a.length))))},`visit`);for(let t of e.keys())n.has(t)||s(t,null);return a}t(En,`computeBlocks`);function Dn(e,t,n,r){let i=[],a=new Set;for(;n.length>0;){let r=n.pop();if(i.push(r),a.add(r[0]),a.add(r[1]),r[0]===e&&r[1]===t||r[0]===t&&r[1]===e)break}return{id:r,edges:i,nodes:[...a]}}t(Dn,`popBlock`);function On(e,n,r){let i=[...e.nodes],a=new Map;for(let[e,t]of i.entries())a.set(t,e);let o=i.length,s=Array(o).fill(-1),c=Array(o).fill(0),l=[],u=new Set;for(let e of i){let t=r.parent.get(e)??null,n=a.get(e);n!=null&&(t??(s[n]=-1,c[n]=0,u.has(e)||(u.add(e),l.push(e))))}for(;l.length>0;){let e=l.shift(),t=a.get(e);if(t==null)continue;let n=r.children.get(e)??[];for(let e of n){if(u.has(e))continue;let n=a.get(e);n!=null&&(s[n]=t,c[n]=c[t]+1,u.add(e),l.push(e))}}for(let e of i){if(u.has(e))continue;let t=a.get(e);t!=null&&(s[t]=-1,c[t]=0,u.add(e))}let d=Math.max(1,Math.ceil(Math.log2(Math.max(1,o)))+1),f=Array.from({length:d},()=>Array(o).fill(-1));for(let e=0;e{if(e===-1||t===-1)return-1;c[e]>t&1&&(e=f[t][e],e===-1))return-1;if(e===t)return e;for(let n=d-1;n>=0;n--){let r=f[n][e],i=f[n][t];r===-1||i===-1||r!==i&&(e=r,t=i)}return f[0][e]},`lcaIndex`),m=Array.from({length:o},()=>new Map);for(let t of e.edges){let e=t.src,r=t.dst,i=n[e],o=n[r];if(i==null||o==null||(i>o&&([e,r]=[r,e],[i,o]=[o,i]),i==null||o==null||i===o))continue;let s=a.get(e),c=a.get(r);if(s==null||c==null)continue;let l=p(s,c);if(l===-1)continue;let u=m[l];for(let e=i;e{if(t.size!==0)for(let[n,r]of t)e.set(n,(e.get(n)??0)+r)},`mergeInto`),_=new Set,v=t(e=>{let t=a.get(e);_.add(e);let i=t==null?void 0:m[t],o=i?new Map(i):new Map,s=r.children.get(e)??[];for(let t of s){let r=v(t),i=n[e];if(i!=null){let a=h.get(e);a||(a=new Map,h.set(e,a));let o=r.get(i)??0,s=n[t];s!=null&&s>i&&(o+=1),a.set(t,o)}g(o,r)}return o},`dfs`);for(let e of r.roots)_.has(e)||v(e);for(let e of i)_.has(e)||v(e);return h}t(On,`computeSubtreeCrossCounts`);function kn(e,n,r){let i=new Map,a=t(e=>{let t=r[e]??0,o=[...n.get(e)??[]];o.sort(An(r));for(let e of o){a(e);let n=i.get(e);n!=null&&(t=Math.min(t,n))}i.set(e,t)},`annotate`);for(let t of e)a(t);return i}t(kn,`annotateMinimumLayers`);function An(e){return(t,n)=>{let r=e[t]??0,i=e[n]??0;return r===i?t.localeCompare(n):r-i}}t(An,`compareByRankThenId`);function jn(e,n,r,i){let a=0;for(let e of n){let t=r[e]??0;t>a&&(a=t)}let o=Array.from({length:a+1},()=>[]),s=new Set,c=t(e=>{if(s.has(e))return;s.add(e);let t=r[e]??0;o[t]||(o[t]=[]),o[t].push(e);for(let t of i(e))c(t)},`emit`);for(let t of e)c(t);for(let e of n)if(!s.has(e)){let t=r[e]??0;o[t]||(o[t]=[]),o[t].push(e),s.add(e)}return o}t(jn,`emitNodesInTreeOrder`);function Mn(e){let t=[];for(let n of e){let e=new Set,r=[];for(let t of n)e.has(t)||(e.add(t),r.push(t));t.push(r)}return t}t(Mn,`deduplicateLayers`);function Nn(e,t,n,r){return i=>{let a=e.get(i)??[];if(a.length===0)return[];let o=t[i]??0,s=[],c=[],l=n.get(i);for(let e of a){let t=r.get(e)??o;t>o?s.push({child:e,min:t}):c.push(e)}return s.sort((e,t)=>e.min===t.min?e.child.localeCompare(t.child):e.min-t.min),c.sort((e,t)=>{let n=l?.get(e)??0,i=l?.get(t)??0;if(n!==i)return n-i;let a=r.get(e)??o,s=r.get(t)??o;return a===s?e.localeCompare(t):a-s}),[...s.map(e=>e.child),...c]}}t(Nn,`createChildOrderer`);function Pn(e,t,n){let r=Sn(e,{rankHint:t,laneOf:n}),{children:i,roots:a}=r;for(let t of e.nodes)i.has(t)||i.set(t,[]);let o=On(e,t,r),s=[...a].sort(An(t)),c=Nn(i,t,o,kn(s,i,t)),l=jn(s,e.nodes,t,c);return l=Mn(l),l}t(Pn,`buildMultitreeLayerOrder`);function Fn(e,t,n){let r=new Set(e),i=new Set(t),a=fn(t),o=[];for(let e of n)r.has(e.src)&&i.has(e.dst)&&o.push(a.get(e.dst));return pn(o)}t(Fn,`countCrossingsBetweenAdjacent`);function In(e,t,n){let r=[];for(let e of t){let t=n[e.src],i=n[e.dst];if(t==null||i==null||t===i)continue;let a=e.src,o=e.dst,s=t,c=i;t>i&&(a=e.dst,o=e.src,s=i,c=t);for(let t=s;t(n[t]??0)-(n[e]??0));for(let s of o){let o=n[s]??0;if(o===0)continue;let c=0;for(let e of r.get(s)??[])c=Math.max(c,(n[e]??0)+1);if(c>=o)continue;let l=o;n[s]=c;let u=In(Pn(e,n,i),e.edges,n);u(t[e]??0)-(t[n]??0)||e.localeCompare(n));for(let i of r){let r=n(i);if(!r)continue;let a=e.edges.filter(e=>e.src===i);if(a.length===0)continue;let o=!1,s=0;for(let e of a){let t=n(e.dst);t==null||t===r?o=!0:s++}if(s===0||o)continue;let c=0,l=!1;for(let t of e.edges){if(t.dst!==i)continue;let e=n(t.src);e&&(e===r?l=!0:c++)}if(c>0||!l)continue;let u=t[i]??0,d=u+s,f=0;for(let n of e.edges)n.dst===i&&(f=Math.max(f,(t[n.src]??0)+1));let p=Math.max(u,f,d);p!==u&&(t[i]=p)}}t(Rn,`adjustCrossLaneSources`);function zn(e,t){let n=nn(e),r=dn(n)??[...n.nodes].sort(),i=t?.compactSingleInput??!1,a=gn(n),o=Object.create(null);for(let e of r){let r=rn(n,e),s=t?.ignoreCrossLaneEdges?r.filter(t=>{let n=a(t.src),r=a(e);return!n||!r||n===r}):r;if(s.length===0)o[e]=0;else if(i&&s.length===1){let t=s[0].src;a(t)===a(e)?o[e]=(o[t]??0)+1:o[e]=o[t]??0}else{let t=-1/0;for(let e of s)t=Math.max(t,(o[e.src]??0)+1);o[e]=t===-1/0?0:t}}return(t?.optimizeRanksByCrossings??!1)&&(o=Ln(n,o)),t?.ignoreCrossLaneEdges&&Rn(n,o),{layers:Pn(n,o,a),rankOf:o,dummy:new Set}}t(zn,`assignLayers_LongestPath`);function Bn(e,n){let r=nn(e),i={...zn(r,{compactSingleInput:n?.compactSingleInput,ignoreCrossLaneEdges:n?.ignoreCrossLaneEdges,optimizeRanksByCrossings:n?.optimizeRanksByCrossings}).rankOf},a=gn(r),{preds:o,succs:s}=ln(r,e=>{if(n?.ignoreCrossLaneEdges){let t=a(e.src),n=a(e.dst);if(t&&n&&t!==n)return!1}return!0}),c=dn(r)??[...r.nodes],l=[...c].reverse(),u=t((e,t)=>{let n=0;for(let t of o.get(e)??[])n=Math.max(n,(i[t]??0)+1);let r=1/0,a=s.get(e)??[];return a.length>0&&(r=Math.min(...a.map(e=>(i[e]??0)-1))),Number.isFinite(r)||(r=Math.max(n,t)),Math.min(Math.max(t,n),r)},`clampFeasible`),d=bn.GRAVITY_ITERATIONS,f=t(e=>{let t=!1;for(let n of e){let e=o.get(n)??[],r=s.get(n)??[];if(e.length===0&&r.length===0)continue;let a=e.length>0?e.reduce((e,t)=>e+(i[t]??0)+1,0)/e.length:i[n]??0,c=r.length>0?r.reduce((e,t)=>e+(i[t]??0)-1,0)/r.length:i[n]??0,l=Math.round((a+c)/2),d=u(n,l);d!==i[n]&&(i[n]=d,t=!0)}return t},`relaxOrder`);for(let e=0;e0){let n=Math.min(...t.map(e=>(i[e]??0)-1));(i[e]??0)>n&&(i[e]=n)}}return{layers:un(r,c,i),rankOf:i,dummy:new Set}}t(Bn,`assignLayers_Gravity`);function Vn(e){let t=sn(e),n=on(e),r=cn(t),i=[];for(;r.length>0;){let e=[];for(let a of r){i.push(a);for(let r of n.get(a)??[])t.set(r,(t.get(r)??0)-1),(t.get(r)??0)===0&&e.push(r)}r=e.sort((e,t)=>e.localeCompare(t))}return i.length===e.nodes.length?i:null}t(Vn,`topoSortByGenerationIfAcyclic`);function Hn(e,n){let r=nn(e),i=n?.direction===`LR`?Vn(r)??[...r.nodes].sort():dn(r)??[...r.nodes].sort(),a=gn(r),o=t(e=>a(e)??e,`laneOf`),s=Object.create(null),c=new Map,l=t((e,t)=>n?.ignoreCrossLaneEdges??!0?+(o(e)===o(t)):1,`edgeWeight`);for(let e of i){if(r.nodeById.get(e)?.isGroup)continue;let t=rn(r,e),n=0;if(t.length>0)for(let r of t){let t=r.src,i=s[t]??0;n=Math.max(n,i+l(t,e))}let i=o(e),a=c.get(i)??0,u=Math.max(n,a);s[e]=u,c.set(i,u+1)}return{layers:un(r,i,s,{skipGroups:!0}),rankOf:s,dummy:new Set}}t(Hn,`assignLayers_LaneAwareCompact`);function Un(e,n){let r=nn(n),{rankOf:i}=e,a=e.layers.map(e=>[...e]),o=new Set(e.dummy?[...e.dummy]:[]),s=0,c=new Map(r.nodeById),l=t(e=>{let t=`placeholder-${s++}`,n={id:t,isGroup:!1,isDummy:!0,width:0,height:0};for(c.set(t,n),o.add(t);a.length<=e;)a.push([]);return a[e].push(t),i[t]=e,t},`addDummyAt`),u=[...r.edges].sort((e,t)=>e.id===t.id?e.src===t.src?e.dst.localeCompare(t.dst):e.src.localeCompare(t.src):e.id.localeCompare(t.id)),d=[];for(let e of u){let t=i[e.src]??0,n=i[e.dst]??0;if(n-t<=1){d.push(e);continue}let r=e.src;for(let i=t+1,a=0;i!r.nodes.includes(e))],edges:d,layout:r.layout,nodeById:c};return{layering:{layers:a,rankOf:i,dummy:o},graphWithDummies:f}}t(Un,`makeProperLayering`);function Wn(e){let t=e.length;if(t===0)return 1/0;let n=[...e].sort((e,t)=>e-t);return t%2==1?n[(t-1)/2]:.5*(n[t/2-1]+n[t/2])}t(Wn,`median`);function Gn(e){return e.length===0?1/0:e.reduce((e,t)=>e+t,0)/e.length}t(Gn,`barycenter`);function Kn(e,t,n,r){let i=new Map;for(let t of e)i.set(t,[]);for(let e of n)r===`down`?t.has(e.src)&&i.has(e.dst)&&i.get(e.dst).push(t.get(e.src)):t.has(e.dst)&&i.has(e.src)&&i.get(e.src).push(t.get(e.dst));return i}t(Kn,`neighborPositionsFor`);function qn(e,t,n){let r=n.get(e)??0,i=n.get(t)??0;return r===i?e.localeCompare(t):r-i}t(qn,`currentOrderTieBreak`);function Jn(e,t,n){let r=new Set(e),i=new Set(t),a=fn(e),o=fn(t),s=[];for(let e of n)r.has(e.src)&&i.has(e.dst)&&s.push({u:a.get(e.src),v:o.get(e.dst)});return s.sort((e,t)=>e.u===t.u?e.v-t.v:e.u-t.u),pn(s.map(e=>e.v))}t(Jn,`countCrossingsBetweenAdjacent`);function Yn(e,t,n){return[...e].sort((e,r)=>{let i=Wn(t.get(e)??[]),a=Wn(t.get(r)??[]);return i===a?qn(e,r,n):isFinite(i)?isFinite(a)?i-a:-1:1})}t(Yn,`sortByHeuristic`);function Xn(e,t,n,r,i,a){let o=fn(e),s=fn(t),c=Kn(t,o,n,r);if(!i||!a||a.length===0)return Yn(t,c,s);let l=new Map;for(let e of t){let t=i(e),n=l.get(t)??[];n.push(e),l.set(t,n)}let u=[];for(let e of a){let t=l.get(e);if(!t||t.length===0)continue;let n=Yn(t,c,s);u.push(...n)}let d=l.get(null);if(d&&d.length>0){let e=Yn(d,c,s);for(let t of e){let e=Gn(c.get(t)??[]),n=u.length;if(isFinite(e)){for(let[t,r]of u.entries())if(es.has(e.src)&&c.has(e.dst)),d=l?r.filter(e=>c.has(e.src)&&l.has(e.dst)):void 0,f=t(t=>{let n=Jn(e,t,u);return d&&i&&(n+=Jn(t,i,d)),n},`crossingScore`),p=a?new Map:null;if(a&&p)for(let e of n)p.set(e,a(e));let m=!0,h=f(o);for(;m;){m=!1;for(let e=0;e+1[...e]),i=t.edges,a=gn(t),o=vn(t,n?.laneOrder);for(let e=0;e<3;e++){for(let e=1;e=0;e--)r[e]=Xn(r[e+1],r[e],i,`up`,a,o),r[e]=Zn(r[e+1],r[e],i,r[e-1],a)}return{layers:r}}t(Qn,`orderLayers`);function $n(e,n,r){let i=r?.layerGap??xn.DEFAULT_LAYER_GAP,a=r?.nodeGap??xn.DEFAULT_NODE_GAP,o=r?.laneGap??a*2,s=r?.direction??`TB`,c=s===`LR`||s===`RL`,l=e.layers,u=Object.create(null),d=Object.create(null),f=t(e=>n.nodeById.get(e),`getNode`),p=t(e=>f(e)?.width??0,`getWidth`),m=t(e=>f(e)?.height??0,`getHeight`),h=gn(n),g=vn(n,r?.laneOrder),_=l.map(e=>e.reduce((e,t)=>Math.max(e,m(t)),0)),v=[];if(c)for(let e=0;e+1Math.max(e,p(t)),0),n=l[e+1].reduce((e,t)=>Math.max(e,p(t)),0),r=_[e],a=_[e+1],o=r/2+a/2,s=(t+n)/2,c=Math.max(0,s-o-i);v.push(c)}let y=new Set;for(let e of l)for(let t of e)y.add(h(t));let b=y.has(null),x=g.filter(e=>y.has(e)),S=[...b?[null]:[],...x],C=Object.create(null);for(let e of x)C[e]=0;b&&(C.null=0);for(let e of l){let t=Object.create(null),n=[];for(let r of e){let e=h(r);e===null?n.push(r):(t[e]||=[]).push(r)}for(let[e,n]of Object.entries(t)){let t=n.reduce((e,t)=>e+p(t),0)+a*Math.max(0,n.length-1);C[e]=Math.max(C[e]??0,t)}if(b&&n.length){let e=n.reduce((e,t)=>e+p(t),0)+a*Math.max(0,n.length-1);C.null=Math.max(C.null??0,e)}}let w=new Map;{let e=S.map(e=>(e===null?C.null:C[e])??0),t=-(e.reduce((e,t)=>e+t,0)+o*Math.max(0,S.length-1))/2;for(let n=0;np(e)),r=i-(e.reduce((e,t)=>e+t,0)+a*(t.length-1))/2;for(let[i,o]of t.entries()){let t=e[i];u[o]=r+t/2,d[o]=T+n/2,r+=t+a}}}let o=v[e]??0;T+=n+i+o}let E=new Map;for(let e of n.edges){let t=e.ref.id;E.has(t)||E.set(t,[]),E.get(t).push(e)}for(let[,e]of E){if(e.length===0)continue;let t=e[0].ref,r=t.start,i=t.end;if(r==null||i==null)continue;let a=Math.round(((u[r]??0)+(u[i]??0))/2),o=new Set;for(let t of e)o.add(t.src),o.add(t.dst);for(let e of o)e===r||e===i||n.nodeById.get(e)?.isDummy&&(u[e]=a)}return{x:u,y:d}}t($n,`assignCoordinates`);var er=8;function tr(e){let t=2166136261;for(let n=0;n>>0}t(tr,`hashString`);function nr(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}t(nr,`mulberry32`);function rr(e,t){let n=[...e],r=nr(t);for(let e=n.length-1;e>0;e--){let t=Math.floor(r()*(e+1));[n[e],n[t]]=[n[t],n[e]]}return n}t(rr,`deterministicShuffle`);function ir(e,t){let n=0;for(let[r,i]of e.entries())n+=Math.abs(r-(t.get(i)??r));return n}t(ir,`sourceDistance`);function ar(e,t){let n=new Map;for(let[t,r]of e.entries())n.set(r,t);let r=0;for(let{a:e,b:i,weight:a}of t){let t=n.get(e),o=n.get(i);t==null||o==null||(r+=a*Math.abs(t-o))}return r}t(ar,`laneArrangementCost`);function or(e){let t=_n(e);if(t.length<2)return[];let n=new Map(t.map((e,t)=>[e,t])),r=gn(e),i=new Map;for(let t of e.layout.edges??[]){if(t.isLayoutOnly)continue;let a=typeof t.start==`string`?t.start:void 0,o=typeof t.end==`string`?t.end:void 0;if(!a||!o||!e.nodeById.has(a)||!e.nodeById.has(o))continue;let s=r(a),c=r(o);if(!s||!c||s===c)continue;let l=n.get(s),u=n.get(c);if(l==null||u==null)continue;let[d,f]=l<=u?[s,c]:[c,s],p=`${d}\0${f}`,m=i.get(p);m?m.weight++:i.set(p,{a:d,b:f,weight:1})}return[...i.values()]}t(or,`buildWeightedLaneEdges`);function sr(e,t,n){let r=[...e],i=ar(r,t),a=!0,o=0,s=Math.max(1,r.length);for(;a&&oe.a===t.a?e.b.localeCompare(t.b):e.a.localeCompare(t.a)).map(({a:e,b:t,weight:n})=>`${e}:${t}:${n}`).join(`|`);return tr(`${e.join(`|`)}#${r}#${n}`)}t(lr,`seedForRestart`);function ur(e,t={}){let n=_n(e);if(n.length<2)return n;let r=or(e);if(r.length===0)return n;let i=new Map(n.map((e,t)=>[e,t])),a=sr(n,r,i),o=Math.max(0,t.restarts??er);for(let e=0;e$&&c*3>=s?o>0?`bottom`:`top`:s>$?a>0?`right`:`left`:n}t(vr,`chooseOrthogonalSide`);function yr(e,t){return Math.abs(e.to-t.from)<$||Math.abs(e.to-t.to)<$?e.to:e.from}t(yr,`sharedLineEndpointCoord`);function br(e,t){return e.orient===`vertical`?{x:e.coord,y:t}:{x:t,y:e.coord}}t(br,`pointOnLine`);function xr(e,n){let r=e.nodes??[],i=e.edges??[],a=[];for(let e of i)e.isLayoutOnly||a.push({...e,__originalEdge:e});let o=new Map,s=new Map,c=[],l=n===`LR`;for(let e of r)o.set(e.id,e);let u=r.filter(e=>e.isGroup&&!e.parentId);for(let e of u){let n={id:e.id},i=t(e=>{s.set(e.id,n),r.filter(t=>t.parentId===e.id).forEach(i)},`assignLane`);i(e)}let d=r.filter(e=>!e.isGroup&&!e.isEdgeLabel).map(e=>{let t=e.width??10,n=e.height??10,r=e.x??0,i=e.y??0,a=fr;return{nodeId:e.id,minX:r-t/2-a,maxX:r+t/2+a,minY:i-n/2-a,maxY:i+n/2+a,visualXHalfExtent:l?n/2+a:t/2+a}}),f=t((e,t,n,r)=>{let i=c.find(n=>n.orientation===e&&Math.abs(n.coord-t)<1);return i||(i={id:`pipe-${e}-${t.toFixed(0)}`,orientation:e,coord:t,spanMin:n,spanMax:r,tracks:[]},c.push(i)),i.spanMin=Math.min(i.spanMin,n),i.spanMax=Math.max(i.spanMax,r),i},`getOrAddPipe`),p=t((e,t)=>{let n=e.width??10,r=e.height??10,i=e.x??0,a=e.y??0;switch(t){case`top`:return{x:i,y:a-r/2};case`bottom`:return{x:i,y:a+r/2};case`left`:return{x:i-n/2,y:a};case`right`:return{x:i+n/2,y:a}}},`portForSide`),m=t((e,t,n)=>p(e,vr(e,t,n?`bottom`:`top`)),`getOrthogonalPort`),h=[],g=[],_=new Set,v=1e3,y=t((e,t,n)=>{if(h.length===0)return 0;let r=Math.abs(t.y-n.y)<$,i=Math.abs(t.x-n.x)<$;if(!r&&!i)return 0;let a=0;if(r){let r=t.y,i=Math.min(t.x,n.x)-$,o=Math.max(t.x,n.x)+$;if(o<=i)return 0;for(let t of h)t.edgeIndex===e||t.orientation!==`vertical`||t.pipe.coordo||t.from-$<=r&&t.to+$>=r&&(a+=v)}else if(i){let r=t.x,i=Math.min(t.y,n.y)-$,o=Math.max(t.y,n.y)+$;if(o<=i)return 0;for(let t of h)t.edgeIndex===e||t.orientation!==`horizontal`||t.pipe.coordo||t.from-$<=r&&t.to+$>=r&&(a+=v)}return a},`crossingPenalty`),b=a.map((e,t)=>{if(!e.start||!e.end)return{idx:t,crossLane:0,dx:0,dy:0};let n=o.get(e.start),r=o.get(e.end),i=s.get(e.start),a=s.get(e.end);return{idx:t,crossLane:i&&a&&i.id!==a.id?1:0,dx:n&&r?Math.abs((r.x??0)-(n.x??0)):0,dy:n&&r?Math.abs((r.y??0)-(n.y??0)):0}}).sort((e,t)=>{if(e.crossLane!==t.crossLane)return t.crossLane-e.crossLane;let n=e.dx+e.dy,r=t.dx+t.dy;return Math.abs(n-r)>1?n-r:e.idx-t.idx}).map(e=>e.idx),x=t((e,t,n,r)=>{let i=Math.min(e.x,t.x),a=Math.max(e.x,t.x),o=Math.min(e.y,t.y),s=Math.max(e.y,t.y);return!!d.find(c=>n&&c.nodeId===n||r&&c.nodeId===r?!1:Math.abs(e.x-t.x)>$?c.minYe.y&&c.maxX>i&&c.minXe.x&&c.maxY>o&&c.minYvr(e,t,`bottom`),`determineSide`),T=new Map;for(let[e,t]of a.entries()){if(!t.start||!t.end||t.start===t.end||t.points&&t.points.length>0)continue;let n=o.get(t.start),r=o.get(t.end);if(!n||!r)continue;let i=(r.x??0)-(n.x??0),a=(r.y??0)-(n.y??0);T.set(e,{edgeIdx:e,srcId:t.start,dstId:t.end,srcSide:w(n,{x:r.x??0,y:r.y??0}),dstSide:w(r,{x:n.x??0,y:n.y??0}),absDx:Math.abs(i),absDy:Math.abs(a),dxSign:Math.sign(i),dySign:Math.sign(a)})}let E=t(e=>e.srcSide===`top`||e.srcSide===`bottom`?e.absDx===0?1/0:e.absDy/e.absDx:e.absDy===0?1/0:e.absDx/e.absDy,`preferenceStrength`),D=t(e=>e.srcSide===`top`||e.srcSide===`bottom`?e.dxSign>=0?`right`:`left`:e.dySign>=0?`bottom`:`top`,`secondarySide`),O=new Map;for(let e of T.values()){let t=`${e.srcId}:${e.srcSide}`;O.has(t)||O.set(t,[]),O.get(t).push(e)}let k=new Map,A=t((e,t)=>`${e}:${t}`,`loadKey`);for(let e of T.values())k.set(A(e.srcId,e.srcSide),(k.get(A(e.srcId,e.srcSide))??0)+1),k.set(A(e.dstId,e.dstSide),(k.get(A(e.dstId,e.dstSide))??0)+1);for(let e of O.values())if(!(e.length<2)){e.sort((e,t)=>{let n=E(e),r=E(t);return Math.abs(n-r)>1e-9?r-n:e.edgeIdx-t.edgeIdx});for(let t=1;t=i||(k.set(A(n.srcId,n.srcSide),i-1),k.set(A(n.srcId,r),a+1),n.srcSide=r)}}let j=t(e=>{let t=e?.shape;return t===`question`||t===`diamond`},`isDiamondNode`),ee=new Map;for(let e of T.values())ee.has(e.dstId)||ee.set(e.dstId,new Set),ee.get(e.dstId).add(e.dstSide);for(let e of T.values()){if(!j(o.get(e.srcId)))continue;let t=ee.get(e.srcId);if(!t?.has(e.srcSide))continue;let n=D(e);if(t.has(n)||(k.get(A(e.srcId,n))??0)>0)continue;let r=k.get(A(e.srcId,e.srcSide))??0;k.set(A(e.srcId,e.srcSide),Math.max(0,r-1)),k.set(A(e.srcId,n),1),e.srcSide=n}for(let e of T.values()){let{edgeIdx:t,srcId:n,dstId:r,srcSide:i,dstSide:a}=e,s=o.get(n),c=o.get(r),l=`${n}:${i}:src`,u=i===`top`||i===`bottom`?c.x??0:c.y??0;S.has(l)||S.set(l,[]),S.get(l).push({edgeIdx:t,oppositeCoord:u});let d=`${r}:${a}:dst`,f=a===`top`||a===`bottom`?s.x??0:s.y??0;S.has(d)||S.set(d,[]),S.get(d).push({edgeIdx:t,oppositeCoord:f})}let te=new Map;for(let[e,t]of S){if(t.length<2)continue;t.sort((e,t)=>e.oppositeCoord-t.oppositeCoord);let n=e.split(`:`),r=n.slice(0,-2).join(`:`),i=n[n.length-2],a=n[n.length-1],s=o.get(r);if(!s)continue;let c=i===`left`||i===`right`?s.height??10:s.width??10,l=s.shape,u=l===`question`||l===`diamond`?c*.3:c,d=Math.min(20,Math.max(8,u/(t.length+1))),f=-(d*(t.length-1))/2;for(let[e,n]of t.entries()){let t=f+e*d,r=`${n.edgeIdx}:${a}`;te.set(r,t)}}let M=t(e=>!!a[e]?.labelNodeId,`edgeHasLabelNode`),ne=t((e,t)=>e?(S.get(`${e}:${t}:src`)??[]).some(({edgeIdx:e})=>M(e))||(S.get(`${e}:${t}:dst`)??[]).some(({edgeIdx:e})=>M(e)):!1,`faceHasLabelNode`),N=t((e,t,n)=>t===`top`||t===`bottom`?{x:e.x+n,y:e.y}:{x:e.x,y:e.y+n},`applyPortOffset`),re=t((e,t,n)=>{let r=T.get(e),i={x:n.x??0,y:n.y??0},a={x:t.x??0,y:t.y??0},o=r?.srcSide??w(t,i),s=r?.dstSide??w(n,a),c=r?p(t,r.srcSide):m(t,i,!0),l=r?p(n,r.dstSide):m(n,a,!1),u=te.get(`${e}:src`),d=te.get(`${e}:dst`);return u!==void 0&&(c=N(c,o,u)),d!==void 0&&(l=N(l,s,d)),{pSrcPort:c,pDstPort:l,srcSide:o,dstSide:s}},`portsForEdge`);for(let e of b){let n=a[e];if(g[e]=[],!n.start||!n.end||n.points&&n.points.length>0||n.start===n.end)continue;let r=o.get(n.start),i=o.get(n.end);if(!r||!i)continue;let{pSrcPort:s,pDstPort:u,srcSide:p,dstSide:m}=re(e,r,i),v={...s},b={...u},w=p===`top`||p===`bottom`,T=m===`top`||m===`bottom`;w?v.y=s.y>(r.y??0)?s.y+gr:s.y-gr:v.x=s.x>(r.x??0)?s.x+gr:s.x-gr,T?b.y=u.y>(i.y??0)?u.y+gr:u.y-gr:b.x=u.x>(i.x??0)?u.x+gr:u.x-gr;let E=t((e,t)=>{for(let n of d)if(!t.includes(n.nodeId)&&e.x>n.minX&&e.xn.minY&&e.y{if(i){let i=e.y>(t.y??0);return{x:(n.x??0)>=e.x?r.maxX+pr:r.minX-pr,y:i?r.maxY+mr:r.minY-mr,leavesPositiveSide:i}}let a=e.x>(t.x??0),o=(n.y??0)>=e.y;return{x:a?r.maxX+pr:r.minX-pr,y:o?r.maxY+mr:r.minY-mr,leavesPositiveSide:a}},`obstacleDetour`),O=[],k=[n.start,n.end],A=E(v,k);if(A.inside&&A.obstacle){let e=A.obstacle;if(w){let t=D(s,r,i,e,!0);v.x=t.x,v.y=t.y;let n=t.leavesPositiveSide?Math.min(e.minY-2,s.y+gr):Math.max(e.maxY+2,s.y-gr);O=[{x:s.x,y:n},{x:t.x,y:n},{x:t.x,y:t.y}]}else{let t=D(s,r,i,e,!1),n=t.leavesPositiveSide?Math.min(e.minX-2,s.x+gr):Math.max(e.maxX+2,s.x-gr);v.x=t.x,v.y=t.y,O=[{x:n,y:s.y},{x:n,y:t.y},{x:t.x,y:t.y}]}}let j=[],ee=E(b,k);if(ee.inside&&ee.obstacle){let e=ee.obstacle;if(T){let t=D(u,i,r,e,!0);b.x=t.x,b.y=t.y,j=[{x:t.x,y:t.y},{x:u.x,y:t.y}]}else{let t=D(u,i,r,e,!1);b.x=t.x,b.y=t.y,j=[{x:t.x,y:t.y},{x:t.x,y:u.y}]}}if(O.length===0&&j.length===0){let t=pr,r=Math.abs(v.x-b.x)1||c>1,d=C.get(n.start??``)??0,f=C.get(n.end??``)??0,g=o>1&&ne(n.start,p)||c>1&&ne(n.end,m);if((r||i)&&!a&&(!l||l&&!g&&(o<=1||d<=2)&&(c<=1||f<=2))&&!x(s,u,n.start,n.end)){n.points=[{...s},{...v},{...b},{...u}],_.add(e);let t=i?`horizontal`:`vertical`,r=i?s.y:s.x,a=i?Math.min(s.x,u.x):Math.min(s.y,u.y),o=i?Math.max(s.x,u.x):Math.max(s.y,u.y),c={id:`fast-path-${t}-${r.toFixed(0)}-${e}`,orientation:t,coord:r,spanMin:a,spanMax:o,tracks:[]};h.push({edgeIndex:e,segmentIndex:0,orientation:t,pipe:c,trackIndex:0,from:a,to:o});continue}}v.x=f(`vertical`,v.x,v.y,v.y).coord,b.x=f(`vertical`,b.x,b.y,b.y).coord;let M=Math.min(v.x,b.x)-50,N=Math.max(v.x,b.x)+50,P=Math.min(v.y,b.y)-50,ie=Math.max(v.y,b.y)+50;for(let e of d){let t=Math.min(v.x,b.x),n=Math.max(v.x,b.x),r=Math.min(v.y,b.y),i=Math.max(v.y,b.y);e.minXt&&e.minYr&&(M=Math.min(M,e.minX-hr),N=Math.max(N,e.maxX+hr),P=Math.min(P,e.minY-hr),ie=Math.max(ie,e.maxY+hr))}for(let e of d){if(e.maxXN||e.maxYie)continue;let t=pr;f(`horizontal`,e.minY-t,M,N),f(`horizontal`,e.maxY+t,M,N);let n=mr;f(`vertical`,e.minX-n,P,ie),f(`vertical`,e.maxX+n,P,ie)}f(`horizontal`,v.y,M,N),f(`horizontal`,b.y,M,N);let ae=c.filter(e=>e.orientation===`horizontal`&&e.coord>=P&&e.coord<=ie),oe=c.filter(e=>e.orientation===`vertical`&&e.coord>=M&&e.coord<=N),se=t((e,t)=>`${e.toFixed(1)},${t.toFixed(1)}`,`getKey`),ce=se(v.x,v.y),le=se(b.x,b.y),ue=new Map,de=new Map,fe=new Map,pe=new Set,F=[];ue.set(ce,0),fe.set(ce,`n`),F.push({key:ce,f:Math.hypot(b.x-v.x,b.y-v.y),pt:v}),pe.add(ce);let I=[],me=t((e,t)=>x(e,t,n.start,n.end),`checkSegmentBlocked`),he={x:b.x,y:v.y},L=me(v,he),ge=me(he,b),_e=L||ge,R={x:v.x,y:b.y},z=me(v,R),B=me(R,b);if(_e?z||B||(I=Math.abs(v.x-b.x)<$?[v,b]:[v,R,b]):I=Math.abs(v.y-b.y)<$||Math.abs(v.x-b.x)<$?[v,b]:[v,he,b],I.length===0)for(;F.length>0;){F.sort((e,t)=>e.f-t.f);let t=F.shift();if(pe.delete(t.key),t.key===le){let e=le,t=b;for(I=[t];de.has(e);){let n=de.get(e);I.unshift(n),t=n,e=se(n.x,n.y)}break}let r=t.pt.x,i=t.pt.y,a=oe.sort((e,t)=>e.coord-t.coord),o=a.findIndex(e=>Math.abs(e.coord-r)<1),s=ae.sort((e,t)=>e.coord-t.coord),c=s.findIndex(e=>Math.abs(e.coord-i)<1),l=[];o>0&&l.push({x:a[o-1].coord,y:i}),o>=0&&o0&&l.push({x:r,y:s[c-1].coord}),c>=0&&ce.nodeId===n.start||e.nodeId===n.end?!1:o===s?e.minXr&&e.maxY>c&&e.minYi&&e.maxX>o&&e.minX10&&x<-5||g<-10&&x>5)&&(m=Math.abs(x)*100),(h>10&&_<-5||h<-10&&_>5)&&(m+=Math.abs(_)*50);let S=0,C=fe.get(t.key)??`n`,w=Math.abs(_)>$?`h`:`v`;C!==`n`&&C!==w&&(S=50);let T=f+p+m+S,E=(ue.get(t.key)??1/0)+T,D=Math.abs(b.x-a.x)+Math.abs(b.y-a.y);if(E<(ue.get(u)??1/0))if(de.set(u,t.pt),ue.set(u,E),fe.set(u,w),!pe.has(u))F.push({key:u,f:E+D,pt:a}),pe.add(u);else{let e=F.findIndex(e=>e.key===u);e!==-1&&(F[e].f=E+D)}}}if(I.length===0&&(I=[v,{x:v.x,y:b.y},b]),I.length>4){let e=I[0],n=I[I.length-1],r=Math.min(e.x,n.x),i=Math.max(e.x,n.x),a=Math.min(e.y,n.y),o=Math.max(e.y,n.y);for(let e of I)r=Math.min(r,e.x),i=Math.max(i,e.x),a=Math.min(a,e.y),o=Math.max(o,e.y);let s=i>Math.max(e.x,n.x),c=re.minXr&&e.minYa);if(s.length>0){let r=Math.max(e.x,n.x);for(let e of s){let n=(e.minX+e.maxX)/2;if(e.visualXHalfExtent===void 0||isNaN(e.visualXHalfExtent))continue;let i=n+e.visualXHalfExtent+t;r=Math.max(r,i)}isNaN(r)||(i=r)}}if(c){let i=d.filter(r=>r.minXMath.min(e.y,n.y));if(i.length>0){let a=Math.min(e.x,n.x);for(let e of i){let n=(e.minX+e.maxX)/2-e.visualXHalfExtent-t;a=Math.min(a,n)}r=a}}}let u=t(t=>{let r=n.y>e.y,i=d.filter(t=>{let r=Math.min(e.x,n.x)t.minX,i=Math.min(e.y,n.y)t.minY;return r&&i}),a=i;if(l&&i.length>0){let e=i.filter(e=>e.minXt);e.length>0&&(a=e)}if(a.length===0)return n.y;let o=pr;if(r){let e=Math.max(...a.map(e=>e.maxY))+o;if(ee.minY))-o;if(e>n.y+$)return e}return n.y},`findBestReturnY`),f=t(t=>{let r=u(t),i={x:t,y:e.y},a={x:t,y:r},o={x:n.x,y:r},s=me(e,i),c=me(i,a),l=me(a,o),d=r!==n.y&&me(o,n);return!s&&!c&&!l&&!d?Math.abs(r-n.y)<$?[e,i,a,n]:[e,i,a,o,n]:null},`trySimplifyWithDetourX`),p=s&&!c?f(i):c&&!s?f(r):null;p&&(I=p)}let V=[s,...O,...I,...j.reverse(),u];if(V.length>=3){let e=V[V.length-1],t=V[V.length-2],n=V[V.length-3],r=Math.abs(n.y-t.y)<$&&Math.abs(t.y-e.y)<$,i=Math.abs(n.x-t.x)<$&&Math.abs(t.x-e.x)<$;if(r){let r=Math.sign(t.x-n.x),i=Math.sign(e.x-n.x);r!==0&&r===i&&Math.abs(t.x-n.x)>Math.abs(e.x-n.x)&&V.splice(-2,1)}else if(i){let r=Math.sign(t.y-n.y),i=Math.sign(e.y-n.y);r!==0&&r===i&&Math.abs(t.y-n.y)>Math.abs(e.y-n.y)&&V.splice(-2,1)}}let H=[V[0]];for(let e=1;et.x!=r.x>n.x){H.push(n);continue}continue}if(Math.abs(t.x-n.x)<$&&Math.abs(n.x-r.x)<$){if(n.y>t.y!=r.y>n.y){H.push(n);continue}continue}H.push(n)}H.push(V[V.length-1]);for(let t=0;te.from{let i=!r.segments.some(n=>(n.edgeIndex!==t.edgeIndex||n.segmentIndex!==t.segmentIndex)&&P(n,e)),a=!n.segments.some(n=>(n.edgeIndex!==e.edgeIndex||n.segmentIndex!==e.segmentIndex)&&P(n,t));return i&&a?(e.trackIndex=r.index,t.trackIndex=n.index,n.segments=[...n.segments.filter(t=>t.edgeIndex!==e.edgeIndex||t.segmentIndex!==e.segmentIndex),{edgeIndex:t.edgeIndex,segmentIndex:t.segmentIndex,from:t.from,to:t.to}],r.segments=[...r.segments.filter(e=>e.edgeIndex!==t.edgeIndex||e.segmentIndex!==t.segmentIndex),{edgeIndex:e.edgeIndex,segmentIndex:e.segmentIndex,from:e.from,to:e.to}],!0):!1},`trySwapSegmentsAcrossTracks`),ae=t(e=>{let t=e.tracks.length;return e.tracks[t]={index:t,coord:e.coord,segments:[]},t},`createNewTrack`),oe=t((e,t)=>{let n=e.pipe.tracks[e.trackIndex];n.segments=n.segments.filter(t=>t.edgeIndex!==e.edgeIndex||t.segmentIndex!==e.segmentIndex),e.trackIndex=t,e.pipe.tracks[t].segments.push({edgeIndex:e.edgeIndex,segmentIndex:e.segmentIndex,from:e.from,to:e.to})},`moveSegmentToTrack`),se=t((e,t)=>{let n=g[e.edgeIndex];for(let r of n){let n=h[r];n.pipe===e.pipe&&oe(n,t)}},`moveSegmentChainToTrack`),ce=t(e=>{let t=g[e.edgeIndex],n=t.indexOf(h.indexOf(e)),r=[];return n>0&&r.push(h[t[n-1]]),n{if(e.orientation===t.orientation)return!1;let n=e.orientation===`horizontal`?e:t,r=e.orientation===`horizontal`?t:e;return r.pipe.coord>n.from&&r.pipe.coordr.from&&n.pipe.coord{for(let n of e.tracks)if(!n.segments.some(e=>(e.edgeIndex!==t.edgeIndex||e.segmentIndex!==t.segmentIndex)&&P(e,t)))return n.index;return-1},`findAvailableTrack`),de=t((e,t)=>{if(e.trackIndex===t.trackIndex)return P(e,t);let n=ce(e),r=ce(t);return n.some(e=>r.some(t=>le(e,t)))},`segmentsConflict`),fe=t((e,t,n)=>{if(ie(e,t,e.pipe.tracks[e.trackIndex],t.pipe.tracks[t.trackIndex]))return;let r=ue(e.pipe,t);n(t,r===-1?ae(e.pipe):r)},`resolveTrackConflict`),pe=t(e=>{let t=0;for(let n=0;n{if(F.has(e))return F.get(e);let t=g[e];if(t.length===0){let t={dest:0,deviation:0,base:0,delta:0};return F.set(e,t),t}let n=h[t[0]].pipe.coord,r=n;for(let e=1;eMath.abs(t-n)?e:t;break}}let i=Math.abs(r-n),a={dest:r,deviation:i,base:n,delta:r-n};return F.set(e,a),a},`getDestInfo`),me=t(()=>{let e=0,n=new Map;for(let[e,t]of a.entries())g[e].length!==0&&t.start&&(n.has(t.start)||n.set(t.start,[]),n.get(t.start).push(e));let r=t(e=>{let t=a[e];if(!t.start||!t.end)return 0;let n=o.get(t.start),r=o.get(t.end);if(!n||!r)return 0;let i=(r.x??0)-(n.x??0),s=(r.y??0)-(n.y??0);return Math.abs(i)+Math.abs(s)},`getEdgeDistance`);for(let t of n.values()){t.sort((e,t)=>{let n=I(e),i=I(t);if(Math.abs(n.deviation-i.deviation)>1)return n.deviation-i.deviation;if(Math.abs(n.dest-i.dest)>1)return n.dest-i.dest;let a=r(e),o=r(t);if(Math.abs(a-o)>1)return o-a;let s=g[e].length,c=g[t].length;if(s!==c)return s-c;if(s===1){let n=g[e][0],r=g[t][0];if(h[n]&&h[r]){let e=h[n],t=h[r],i=Math.abs(e.to-e.from),a=Math.abs(t.to-t.from);if(Math.abs(i-a)>1)return i-a}}return 0});let n=t.map(e=>h[g[e][0]]);e+=pe(n)}return e},`fixSourceHandleCrossings`),he=t(()=>{let e=0,n=new Map;for(let[e,t]of a.entries())g[e].length!==0&&t.end&&(n.has(t.end)||n.set(t.end,[]),n.get(t.end).push(e));for(let r of n.values()){r.sort((e,n)=>{let r=t(e=>{let t=g[e];if(t.length<2)return 0;let n=h[t[t.length-2]];return Math.abs(n.to-n.from)},`getDist`),i=r(e),a=r(n);return Math.abs(i-a)>.1?i-a:e-n});let n=r.map(e=>h[g[e][g[e].length-1]]);e+=pe(n)}return e},`fixTargetHandleCrossings`),L=t(()=>{let e=0;for(let t of c){let n=[];for(let e of t.tracks)for(let t of e.segments){let e=g[t.edgeIndex].find(e=>h[e].segmentIndex===t.segmentIndex);e!==void 0&&n.push(h[e])}n.sort((e,t)=>e.edgeIndex-t.edgeIndex||e.segmentIndex-t.segmentIndex);for(let t=0;t{e.segments.forEach(t=>{n.push({edgeIndex:t.edgeIndex,segmentIndex:t.segmentIndex,trackIndex:e.index,from:t.from,to:t.to})})}),n.sort((e,t)=>e.from-t.from);let r=[];if(n.length>0){let e=[n[0]],t=n[0].to;for(let i=1;ir.add(e.trackIndex));let i=new Map;n.forEach(e=>{let t=I(e.edgeIndex);i.set(e.trackIndex,(i.get(e.trackIndex)??0)+t.delta)});let a=[...r].filter(e=>(i.get(e)??0)<-1),o=[...r].filter(e=>(i.get(e)??0)>1),s=[...r].filter(e=>Math.abs(i.get(e)??0)<=1);a.sort((e,t)=>(i.get(t)??0)-(i.get(e)??0)),o.sort((e,t)=>(i.get(e)??0)-(i.get(t)??0));let c=t((t,r)=>{n.filter(e=>e.trackIndex===t).forEach(t=>{let n=_.has(t.edgeIndex)?e.coord:r;_e.set(`${t.edgeIndex}-${t.segmentIndex}`,n)})},`assignCoord`),l=0;for(let t of a)l++,c(t,e.coord-l*_r);if(s.length===0&&r.size>0){let e=[...r].sort((e,t)=>Math.abs(i.get(e)??0)-Math.abs(i.get(t)??0))[0],t=a.indexOf(e);t!==-1&&a.splice(t,1);let n=o.indexOf(e);n!==-1&&o.splice(n,1),s.push(e)}let u=0;for(let t of s){if(u===0)c(t,e.coord);else{let n=u%2==1?1:-1,r=Math.ceil(u/2);c(t,e.coord+n*r*_r*.5)}u++}let d=0;for(let t of o)d++,c(t,e.coord+d*_r)}}for(let[e,t]of a.entries()){let n=g[e]??[];if(n.length===0)continue;let r=[],{pSrcPort:i,pDstPort:a}=re(e,o.get(t.start),o.get(t.end)),s=n.map(e=>{let t=h[e],n=_e.get(`${t.edgeIndex}-${t.segmentIndex}`)??t.pipe.coord;return{orient:t.orientation,coord:n,from:t.from,to:t.to}});r.push(i);for(let e=0;e$&&r.push(br(t,i)),c&&o.orient===t.orient)if(Math.abs(t.coord-o.coord)>$){let e=t.orient===`vertical`?(i+o.from)/2:yr(t,o);r.push(br(t,e),br(o,e))}else(e===0||e===s.length-2)&&r.push(br(t,yr(t,o)));else if(c)r.push(br(t,o.coord));else{let e=Math.abs(t.from-i)$||Math.abs(c.y-a.y)>$)&&r.push(a);let l=[];r.length>0&&l.push(r[0]);for(let e=1;e$||Math.abs(t.y-n.y)>$)&&l.push(t)}t.points=l}for(let e of a){let t=e.__originalEdge;t&&e.points&&(t.points=e.points)}e.edges=(e.edges??[]).filter(e=>!e.isLayoutOnly);let R=t((e,t)=>{let n=t.x??0,r=t.y??0,i=t.width??0,a=t.height??0;if(i<=0||a<=0)return e;let o=n-i/2,s=n+i/2,c=r-a/2,l=r+a/2;if(e.xs||e.yl)return e;let u=e.x-o,d=s-e.x,f=e.y-c,p=l-e.y,m=Math.min(u,d,f,p);return m===u?{x:o,y:e.y}:m===d?{x:s,y:e.y}:m===f?{x:e.x,y:c}:{x:e.x,y:l}},`nodeBoundaryClamp`);for(let t of e.edges){let e=t.points;if(!e||e.length<2)continue;let n=t.start,r=t.end,i=n?o.get(n):void 0,a=r?o.get(r):void 0;i&&(e[0]=R(e[0],i)),a&&(e[e.length-1]=R(e[e.length-1],a))}return e}t(xr,`routeEdgesOrthogonal`);function Sr(e){return e.direction??`TB`}t(Sr,`getSwimlaneDirection`);function Cr(e){let t=F(e),n=e.config.flowchart?.nodeSpacing??40,r=e.config.flowchart?.rankSpacing??100,i=e.config.swimlane?.ignoreCrossLaneEdges??!0,a=e.config.swimlane?.optimizeRanksByCrossings??!0,o=e.config.swimlane?.automaticLaneOrdering??!1,s=Sr(e),{ordered:c,coordinates:l}=dr(t,{nodeGap:n,layerGap:r,ignoreCrossLaneEdges:i,optimizeRanksByCrossings:a,automaticLaneOrdering:o,direction:s});I(t,c,l,{nodeGap:n,layerGap:r});for(let t of e.edges??[])delete t.points;xr(e,s);for(let t of e.edges??[])(!t.curve||t.curve===`basis`)&&(t.curve=`rounded`);return tn(e,s),en(e),s}t(Cr,`runSwimlaneLayoutCore`);async function wr(e,t){let n=t.select(`g`);h(n,e.markers,e.type,e.diagramId),p(),b(),m(),l(),pe(e);let r=he(e);e.nodes=r.nodes,e.edges=r.edges;let{groups:i}=await x(n,e);Cr(e),await oe(e,i)}t(wr,`render`);export{wr as render}; \ No newline at end of file +import{t as e}from"./index-CXgd9jpl.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import{b as r,x as i}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{g as a}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{r as o}from"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as s}from"./chunk-OGEWGWER-D-nWYRNR.js";import{t as c}from"./graphlib-DS17s2tU.js";import{n as l}from"./chunk-RYQCIY6F-Dtr3kkSR.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import{a as u,c as d,i as f,n as p,t as m}from"./chunk-ZGVPDNZ5-DGInJAPD.js";import{a as h,i as g,n as _,r as v,s as y,t as b}from"./chunk-52WLFC77-BOCvVCX1.js";async function x(t,n){let r=new c({multigraph:!0,compound:!0}),a=[...n.edges],o=i(),s=t.insert(`g`).attr(`class`,`root`),l=s.insert(`g`).attr(`class`,`clusters`),d=s.insert(`g`).attr(`class`,`edges edgePath`),f=s.insert(`g`).attr(`class`,`edgeLabels`),p=s.insert(`g`).attr(`class`,`nodes`),m=new Map,h=t.node()!=null;await Promise.all(n.nodes.map(async e=>{if(e.isGroup)r.setNode(e.id,{...e});else{if(h){let t=await u(p,e,{config:o,dir:e.dir}),n=t.node()?.getBBox()??{width:0,height:0};m.set(e.id,t),e.width=n.width,e.height=n.height}r.setNode(e.id,{...e})}}));for(let e of a)r.setEdge(e.start,e.end,{...e},e.id),n.edges.some(t=>t.id===e.id)||n.edges.push(e);if(globalThis.mermaidCaptureSizes){let{captureNodeSizes:r}=await e(async()=>{let{captureNodeSizes:e}=await import(`./sizeCapture-X5ZJPWSS-B0uUizjq.js`);return{captureNodeSizes:e}},__vite__mapDeps([0,1]));r(t,n)}return{graph:r,groups:{clusters:l,edgePaths:d,edgeLabels:f,nodes:p,rootGroups:s},nodeElements:m}}t(x,`createGraphWithElements`);var S=5,C=1e-5,w=1e-6;function T(e){let t=[];for(let n=0;n=1-w||f<=w||f>=1-w?null:{point:{x:e.x+d*i,y:e.y+d*a},tA:d,tB:f}}t(E,`segmentIntersection`);function D(e){return Math.abs(e.b.x-e.a.x)>=Math.abs(e.b.y-e.a.y)}t(D,`isHorizontalSeg`);function O(e){let t=[];for(let n=0;n=Math.abs(n)?+(t>=0):+(n>=0)}t(j,`getArcSweepFlag`);var ee=.001;function te(e,t){if(e.length<2)return e.map(e=>({...e}));let n=e.map(e=>({...e})),r=t.arrowTypeStart&&o[t.arrowTypeStart];if(r){let t=e[0],i=e[1],a=Math.atan2(i.y-t.y,i.x-t.x);n[0].x=t.x+r*Math.cos(a),n[0].y=t.y+r*Math.sin(a)}let i=t.arrowTypeEnd&&o[t.arrowTypeEnd];if(i){let t=e.length,r=e[t-2],a=e[t-1],o=Math.atan2(a.y-r.y,a.x-r.x);n[t-1].x=a.x-i*Math.cos(o),n[t-1].y=a.y-i*Math.sin(o)}return n}t(te,`applyMarkerOffsets`);function M(e,t,n,r,i){let a=e.point.x,o=e.point.y,s={x:a-t*e.r,y:o-n*e.r},c={x:a+t*e.r,y:o+n*e.r},l=[`L${A(s)}`];return i===`arc`?l.push(`A${k(e.r)},${k(e.r)} 0 0 ${r} ${A(c)}`):l.push(`M${A(c)}`),l}t(M,`emitJump`);function ne(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=n.x-t.x,s=n.y-t.y,c=Math.hypot(i,a),l=Math.hypot(o,s);if(c0){let t=ne(i[e-1],i[e],i[e+1]??i[e],S);t&&(f=t.cutLen)}let p=r,m=null;a&&ee.t-t.t);for(let e of h)e.r=Math.min(e.r,e.d-f,p-e.d);for(let e=0;et){let n=t/2;h[e].r=Math.min(h[e].r,n),h[e+1].r=Math.min(h[e+1].r,n)}}for(let e of h)e.r=2?r:null}catch{return null}}t(ie,`decodeDataPoints`);function ae(e,t,n){if(!n.enabled)return;let r=e.node();if(!r)return;let i=new Map;for(let e of t)i.set(e.id,e);let a=[],o=new Map;for(let e of t){let t=typeof CSS<`u`&&CSS.escape?CSS.escape(e.id):e.id,n=r.querySelector(`path[data-id="${t}"]`);if(!n)continue;o.set(e.id,n);let i=ie(n.getAttribute(`data-points`))??e.points;a.push({...e,points:i})}let s=O(a);if(s.length===0)return;let c=new Map;for(let e of s){let t=c.get(e.jumpEdgeId)??[];t.push(e),c.set(e.jumpEdgeId,t)}for(let e of a){let t=c.get(e.id);if(!t||t.length===0)continue;let r=i.get(e.id)?.curve;if(r!==void 0&&!P(r))continue;let a=o.get(e.id);if(!a||r===void 0&&!re(a.getAttribute(`d`)??``))continue;let s=a.getAttribute(`style`)??``,l=/stroke-dasharray\s*:\s*0\s+([\d.]+)\s+[\d.]+\s+([\d.]+)/.exec(s),u=l?Number.parseFloat(l[1]):null,d=l?Number.parseFloat(l[2]):null,f=N(e,t,n);if(a.setAttribute(`d`,f),u!==null&&d!==null&&typeof a.getTotalLength==`function`){let e=a.getTotalLength(),t=`0 ${u} ${Math.max(0,e-u-d)} ${d}`,n=s.replace(/stroke-dasharray\s*:[^;]*;?/g,`stroke-dasharray: ${t};`).replace(/;\s*;+/g,`;`);a.setAttribute(`style`,n)}}}t(ae,`applyLineJumpsToSvg`);async function oe(e,t){for(let n of e.nodes)n.isGroup?await f(t.clusters,n):d(n);let n=new Map;for(let t of e.nodes)t?.id&&n.set(t.id,t);for(let r of e.edges){let i=r.start?n.get(r.start)??{}:{},a=r.end?n.get(r.end)??{}:{},o=v(t.edgePaths,{...r},{},e.type,i,a,e.diagramId);r.label&&await g(t.rootGroups,r),r.label&&se(r,o)}let r=e.config?.swimlane?.lineHops;if(r!==!1){let n=r===`gap`?`gap`:`arc`,i=e.edges.filter(e=>Array.isArray(e.points)&&e.points.length>=2).map(e=>({id:e.id,points:e.points,curve:e.curve,arrowTypeStart:e.arrowTypeStart,arrowTypeEnd:e.arrowTypeEnd}));ae(t.edgePaths,i,{enabled:!0,jumpRadius:6,jumpStyle:n})}}t(oe,`adjustLayout`);function se(e,t){let i=t?.updatedPath??t?.originalPath,{subGraphTitleTotalMargin:o}=s({flowchart:r().flowchart??{}});if(e.label){let r=_.get(e.id),s=e.x,c=e.y;if(i){let r=a.calcLabelPosition(i);n.debug(`Moving label `+e.label+` from (`,s,`,`,c,`) to (`,r.x,`,`,r.y,`) abc88`),t&&(s=r.x,c=r.y)}r.attr(`transform`,`translate(${s}, ${c+o/2})`)}if(e?.startLabelLeft){let t=y.get(e.id).startLeft,n=e?.x,r=e?.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_left`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}if(e.startLabelRight){let t=y.get(e.id).startRight,n=e.x,r=e.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_right`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}if(e.endLabelLeft){let t=y.get(e.id).endLeft,n=e.x,r=e.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_left`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}if(e.endLabelRight){let t=y.get(e.id).endRight,n=e.x,r=e.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_right`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}}t(se,`positionEdgeLabel`);var ce=`__swimlane_default__`,le=21,ue=20;function de(e){return Math.max(e.padding??ue,ue)}t(de,`topLaneHorizontalPadding`);function fe(e){let{x:t,y:n,width:r,height:i}=e,a=e.swimlaneContentTop;if(typeof t!=`number`||typeof n!=`number`||typeof r!=`number`||typeof i!=`number`||typeof a!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(a)||r<=0||i<=0){delete e.groupTitleRect;return}let o=n-i/2,s=Math.min(a,n+i/2),c=o+Math.min(le,Math.max(0,s-o));if(c<=o){delete e.groupTitleRect;return}e.groupTitleRect={left:t-r/2,right:t+r/2,top:o,bottom:c}}t(fe,`assignTopLaneTitleRect`);function pe(e){let t=e.direction,n=e.nodes??=[];for(let n of e.nodes??[])n.isGroup&&!n.parentId&&(n.shape=`swimlane`,t&&(n.direction=t));let r=n.filter(e=>!e.isGroup&&!e.parentId);if(r.length===0)return;let i=n.find(e=>e.id===ce);i?i.isGroup&&(i.shape=`swimlane`,t&&(i.direction=t)):(i={id:ce,label:``,isGroup:!0,shape:`swimlane`,padding:20,...t?{direction:t}:{}},n.push(i));for(let e of r)e.parentId=ce}t(pe,`prepareLayoutForSwimlanes`);function F(e){let t=new Map;for(let n of e.nodes??[])t.set(n.id,n);let n=[];for(let t of e.edges??[]){let e=typeof t.start==`string`?t.start:void 0,r=typeof t.end==`string`?t.end:void 0;!e||!r||t.labelNodeId||n.push({id:t.id,src:e,dst:r,ref:t})}let r=e.nodes??[],i=r.filter(e=>e.isGroup),a=r.filter(e=>!e.isGroup);return{nodes:[...[...i].reverse(),...a].map(e=>e.id),edges:n,layout:e,nodeById:t}}t(F,`toGraphView`);function I(e,t,n,r){let{layout:i}=e,a=e.nodeById,o=r?.layerGap??100,s=r?.nodeGap??40,c=0;for(let e of t.layers){let t=0;for(let r of e){let e=a.get(r);if(!e){t++;continue}e.layer=c,e.order=t;let i=n.x[r]??t*s,l=n.y[r]??c*o;e.x=i,e.y=l,t++}c++}let l=i.nodes??[],u=new Map,d=[];for(let e of l){if(!e?.isGroup)continue;e.parentId||d.push(e);let t=l.filter(t=>t.parentId===e.id),r=1/0,i=-1/0,a=1/0,o=-1/0;for(let e of t){let t=e.x??n.x[e.id],s=e.y??n.y[e.id],c=e.width??0,l=e.height??0;t!=null&&s!=null&&(r=Math.min(r,t-c/2),i=Math.max(i,t+c/2),a=Math.min(a,s-l/2),o=Math.max(o,s+l/2))}if(r===1/0||a===1/0)e.x=e.x??0,e.y=e.y??0,e.width=e.width??0,e.height=e.height??0;else{let t=e.padding??20,n=e.parentId?t:2*de(e),s=t,c=Math.max(0,i-r)+n,l=Math.max(0,o-a)+s,d=(r+i)/2,f=(a+o)/2;e.x=d,e.y=f,e.width=c,e.height=l,u.set(e.id,{minX:r,maxX:i,minY:a,maxY:o})}}if(d.length>0&&u.size>0){let e=1/0,t=-1/0,n=0;for(let r of d){let i=r.padding??20;i>n&&(n=i);let a=u.get(r.id);a&&(e=Math.min(e,a.minY),t=Math.max(t,a.maxY))}if(e!==1/0&&t!==-1/0){let r=Math.max(0,t-e)+2*Math.max(n,36),i=(e+t)/2;for(let t of d)t.y=i,t.height=r,t.swimlaneContentTop=e;let a=[...d].sort((e,t)=>(e.x??0)-(t.x??0)),o=[],s=[],c=[];for(let e of a){let t=u.get(e.id);if(!t)continue;let n=Math.max(0,t.maxX-t.minX)+2*de(e),r=(t.minX+t.maxX)/2;o.push(e.id),s.push(r),c.push(n)}let l=o.length;if(l>0){let e=new Map;if(l===1)e.set(o[0],c[0]);else{let t=[];for(let e=0;e0&&i>0?{cx:t,cy:n,rect:Ee(t,n,r,i)}:void 0}t(ge,`measuredNodeRect`);function _e(e){if(e.isGroup)return;let t=ge(e);if(t)return{id:String(e.id??``),cx:t.cx,cy:t.cy,rect:t.rect}}t(_e,`nodeBoundsInfoFor`);function R(e,t,n=L){return Math.abs(e.x-t.x)n}t(V,`isHorizontalSegment`);function H(e,t,n=L){return z(e,t,n)&&Math.abs(e.y-t.y)>n}t(H,`isVerticalSegment`);function U(e,t,n,r){return Math.max(0,Math.min(Math.max(e,t),Math.max(n,r))-Math.max(Math.min(e,t),Math.min(n,r)))}t(U,`overlapLength`);function ve(e,t,n=L){return e.horizontal&&t.horizontal&&B(e.a,t.a,n)?U(e.a.x,e.b.x,t.a.x,t.b.x):e.vertical&&t.vertical&&z(e.a,t.a,n)?U(e.a.y,e.b.y,t.a.y,t.b.y):0}t(ve,`sameAxisSegmentOverlapLength`);function ye(e,t=L){let n=[];for(let r=0;r0?n[n.length-1]:void 0;(!e||!R(e,r,t))&&n.push({x:r.x,y:r.y})}return n}t(G,`dedupeConsecutivePoints`);function be(e,t=L){if(!e||e.length!==4)return;let[n,r,i,a]=e;return V(n,r,t)&&H(r,i,t)&&V(i,a,t)?{kind:`HVH`,p0:n,p1:r,p2:i,p3:a}:H(n,r,t)&&V(r,i,t)&&H(i,a,t)?{kind:`VHV`,p0:n,p1:r,p2:i,p3:a}:void 0}t(be,`classifyThreeSegmentRoute`);function xe(e,t,n,r=0){let i=Math.min(e.x,t.x),a=Math.max(e.x,t.x),o=Math.min(e.y,t.y),s=Math.max(e.y,t.y);return a>n.left-r&&in.top-r&&ot.left+n&&e.xt.top+n&&e.y=t.right&&e.top<=t.top&&e.bottom>=t.bottom}t(Ce,`rectContainsRect`);function we(e,t){return e.leftt.left&&e.topt.top}t(we,`rectsOverlap`);function Te(e,t){return{left:e.left-t,right:e.right+t,top:e.top-t,bottom:e.bottom+t}}t(Te,`inflateRect`);function Ee(e,t,n,r){return{left:e-n/2,right:e+n/2,top:t-r/2,bottom:t+r/2}}t(Ee,`rectFromCenterSize`);function K(e){return ge(e)?.rect}t(K,`rectOfNodeBounds`);function De(e,t){switch(t){case`top`:return{x:e.cx,y:e.rect.top};case`bottom`:return{x:e.cx,y:e.rect.bottom};case`left`:return{x:e.rect.left,y:e.cy};case`right`:return{x:e.rect.right,y:e.cy}}}t(De,`portForRectSide`);function Oe(e,t,n,r,i,a=L){let o=t===`left`||t===`right`,s=r===`left`||r===`right`;if(o&&s){if(t===`right`&&r===`left`&&e.xn.x){if(B(e,n,a))return[e,n];let t=(e.x+n.x)/2;return[e,{x:t,y:e.y},{x:t,y:n.y},n]}if(t===r){if(B(e,n,a))return;let r=t===`left`?Math.min(e.x,n.x)-i:Math.max(e.x,n.x)+i;return[e,{x:r,y:e.y},{x:r,y:n.y},n]}return}if(!o&&!s){if(t===r){if(z(e,n,a))return;let r=t===`top`?Math.min(e.y,n.y)-i:Math.max(e.y,n.y)+i;return[e,{x:e.x,y:r},{x:n.x,y:r},n]}if(!(t===`bottom`&&r===`top`&&e.yn.y))return;if(z(e,n,a))return[e,n];let o=(e.y+n.y)/2;return[e,{x:e.x,y:o},{x:n.x,y:o},n]}if(o&&!s){let i=t===`right`&&n.x>e.x||t===`left`&&n.xn.y;return i&&a?[e,{x:n.x,y:e.y},n]:void 0}let c=t===`bottom`&&n.y>e.y||t===`top`&&n.yn.x;return c&&l?[e,{x:e.x,y:n.y},n]:void 0}t(Oe,`buildOrthogonalPortPath`);function ke(e,t,n,r){return t===`left`||t===`right`?[e,{x:r,y:e.y},{x:r,y:n.y},n]:[e,{x:e.x,y:r},{x:n.x,y:r},n]}t(ke,`buildSameSideTrackPath`);function Ae(e){let t=new Map,n=[];for(let r of e){if(r.isEdgeLabel)continue;let e=_e(r);e&&(t.set(e.id,e),n.push({id:e.id,rect:e.rect}))}return{nodeInfoById:t,realNodeRects:n}}t(Ae,`collectRealNodeBounds`);function je(e){let t=[],n=[];for(let r of e){let e=_e(r);if(!e)continue;let i={id:e.id,rect:e.rect};r.isEdgeLabel?n.push(i):t.push(i)}return{realNodeRects:t,labelNodeRects:n}}t(je,`collectNodeRectEntries`);function Me(e,{includeEdgeLabels:t=!0}={}){let n=[];for(let r of e){if(r.isGroup||!t&&r.isEdgeLabel)continue;let e=r.x??0,i=r.y??0,a=r.width??0,o=r.height??0;n.push({nodeId:r.id,...Ee(e,i,a,o)})}return n}t(Me,`collectLayoutNodeRects`);function Ne(e,t,n=L){let r=e.start,i=e.end;if(!r||!i)return;let a=t.get(r),o=t.get(i);if(!(!a||!o))return{srcId:r,dstId:i,srcInfo:a,dstInfo:o,collinearX:Math.abs(a.cx-o.cx)m||f_)return!1;let v=Math.abs(h-u.a.x)i:a&&s&&B(e,n,i)?U(e.x,t.x,n.x,r.x)>i:!1}t(Fe,`sameAxisSegmentsOverlap`);function Ie(e,t,n,r,{epsilon:i=L,skipDegenerateOther:a=!1}={}){for(let o of n){if(o===r||o.isLayoutOnly)continue;let n=o.points;if(!(!n||n.length<2))for(let r=0;rf+i&&mh+i&&dr+L&&e=2?t[t.length-2]:void 0,n=e&&z(e,r)?{x:r.x,y:i.y}:{x:i.x,y:r.y};t.push(n)}t.push(i)}let n=[];for(let e of t){let t=n[n.length-1];(!t||!R(t,e))&&n.push(e)}return n}t(Ve,`orthogonalizePolyline`);function He(e){if(e.length<3)return e;let t=[...e];for(let e=0;e<32;e++){let e=Be(t);if(t=e.points,!e.changed)break}return t}t(He,`simplifyPolyline`);var J=.001,Ue=.5,We=4;function Ge(e,t,n){let r=e;if(r.isLayoutOnly||!r.points||r.points.length=0&&i=e.length)return e;let a=i-r;if(a<0||a>=e.length)return e;let o=Ke(e[i],e[a],t);return n?[o,...e.slice(i)]:[...e.slice(0,i+1),o]}t(qe,`clipEndpoint`);function Je(e,t){for(let n of e){let e=Ge(n,t,2);if(!e)continue;let r=[...e.points];e.srcRect&&(r=qe(r,e.srcRect,!0)),e.dstRect&&(r=qe(r,e.dstRect,!1)),r=He(Ve(r)),r=at(r,e.srcRect,e.dstRect),e.edge.points=He(Ve(r))}}t(Je,`clipEdgeEndpointsToNodeBoundaries`);function Ye(e,t,n,r=!1){if(B(e,t,J)){if(t.yn.bottom+J)return t;if(r){if(e.xn.right+J)return{x:n.right,y:e.y}}return{x:Math.abs(t.x-n.left)<=Math.abs(t.x-n.right)?n.left:n.right,y:e.y}}if(z(e,t,J)){if(t.xn.right+J)return t;if(r){if(e.yn.bottom+J)return{x:e.x,y:n.bottom}}let i=Math.abs(t.y-n.top)<=Math.abs(t.y-n.bottom);return{x:e.x,y:i?n.top:n.bottom}}return t}t(Ye,`snapEndpointToBoundary`);function Xe(e,t,n){let r=e[t];for(let i=t+n;i>=0&&ie.lo)),n=Math.min(...e.map(e=>e.hi));if(!(t>n))return{lo:t,hi:n}}t($e,`intersectRanges`);function et(e,t){return t===`left`||t===`right`?Ze(e.top,e.bottom):Ze(e.left,e.right)}t(et,`clearanceRangeForSide`);function tt(e,t,n){let r=e.y>=n.top-J&&e.y<=n.bottom+J,i=e.x>=n.left-J&&e.x<=n.right+J;if(B(e,t,J)&&r){if(Math.abs(e.x-n.left)0?$e(a):void 0}t(rt,`straightClearanceRange`);function it(e,t,n,r,i){let a=rt(e,t,n,r,i);if(!a)return;let o=i?e.y:e.x,s=Math.min(a.hi,Math.max(a.lo,o));if(!(Math.abs(s-o)({...e}));for(let s=t;s>=0&&s=n.left-J&&Math.max(e.x,t.x)<=n.right+J,i=Math.min(e.y,t.y)>=n.top-J&&Math.max(e.y,t.y)<=n.bottom+J;if(Math.abs(e.y-n.top)r.bottom+J;case`left`:return B(t,n,J)&&n.xr.right+J}}t(ut,`leavesOutward`);function dt(e,t,n){if(e.length<3)return e;if(n){let n=lt(e[0],e[1],t);return n&&ut(n,e[1],e[2],t)?e.slice(1):e}let r=e.length-1,i=lt(e[r-1],e[r],t);return i&&ut(i,e[r-1],e[r-2],t)?e.slice(0,r):e}t(dt,`collapseOwnBorderStub`);function ft(e,t,n){let r=e;if(t){let e=Xe(r,0,1);if(e){let n=Ye(e,r[0],t);n!==r[0]&&(r=[n,...r.slice(1)])}r=dt(r,t,!0)}if(n){let e=r.length-1,t=Xe(r,e,-1);if(t){let i=Ye(t,r[e],n,!0);i!==r[e]&&(r=[...r.slice(0,e),i])}r=dt(r,n,!1)}let i=at(r,t,n);return i!==r||r.length===2?i:(t&&(r=ct(r,t,!0)),n&&(r=ct(r,n,!1)),r)}t(ft,`snapAndCollapseEndpoints`);function pt(e,t){for(let n of e){let e=Ge(n,t,2);if(!e)continue;let r=ft(G(e.points,J),e.srcRect,e.dstRect);if(r.length<3){e.edge.points=r;continue}let i=[r[0],{...r[0]},...r.slice(1,-1),r[r.length-1],{...r[r.length-1]}];e.edge.points=i}}t(pt,`prepareEdgeEndpointsForRenderer`);function mt(e){return new Map(e.map(e=>[e.id,e]))}t(mt,`buildNodeMap`);function ht(e,t){let n=e.parentId,r=null;for(;n;){let e=t.get(n);if(!e?.isGroup)break;r=e.id,n=e.parentId}return r}t(ht,`resolveTopLevelGroupId`);function gt(e,t){let n=0,r=e.parentId;for(;r;){let e=t.get(r);if(!e?.isGroup)break;n++,r=e.parentId}return n}t(gt,`groupDepth`);function _t(e){let t=1/0,n=-1/0,r=1/0,i=-1/0;for(let a of e){let e=a.x,o=a.y;if(typeof e!=`number`||typeof o!=`number`)continue;let s=a.width??0,c=a.height??0;t=Math.min(t,e-s/2),n=Math.max(n,e+s/2),r=Math.min(r,o-c/2),i=Math.max(i,o+c/2)}return t===1/0||r===1/0?null:{minX:t,maxX:n,minY:r,maxY:i}}t(_t,`boundsForChildren`);function vt(e,t){let n=e.padding??20;e.x=(t.minX+t.maxX)/2,e.y=(t.minY+t.maxY)/2,e.width=Math.max(0,t.maxX-t.minX)+n,e.height=Math.max(0,t.maxY-t.minY)+n}t(vt,`applyGroupBounds`);function yt(e){let t=mt(e),n=e.filter(e=>e.isGroup&&e.parentId).sort((e,n)=>gt(n,t)-gt(e,t));for(let t of n){let n=_t(e.filter(e=>e.parentId===t.id));n&&vt(t,n)}}t(yt,`recomputeNestedGroupBounds`);function bt(e,n){let r=e.nodes??[],i=e.edges??[],a=r.filter(e=>!e.isGroup),o=1/0,s=-1/0;for(let e of a){let t=e[n];typeof t==`number`&&(o=Math.min(o,t),s=Math.max(s,t))}if(!Number.isFinite(o)||!Number.isFinite(s))return!1;let c=t(e=>o+s-e,`mirror`);for(let e of r){let t=e[n];typeof t==`number`&&(e[n]=c(t));let r=e.groupTitleRect;r&&(e.groupTitleRect=n===`x`?{...r,left:c(r.right),right:c(r.left)}:{...r,top:c(r.bottom),bottom:c(r.top)})}for(let e of i)for(let t of e.points??[])t[n]=c(t[n]);return!0}t(bt,`mirrorAxis`);function xt(e){return!(e.nodes??[]).some(e=>!e.isGroup)||bt(e,`y`)}t(xt,`applyBtDirectionTransform`);function St(e,t=`LR`){let n=e.nodes??[],r=e.edges??[],i=n.filter(e=>!e.isGroup),a=1/0,o=1/0;for(let e of i){let t=e.x??0,n=e.y??0;t0?Math.max(1,l/u):1;for(let e of i){let t=e.x??0,n=((e.y??0)-o)*d+36,r=t-a;e.x=n,e.y=r}for(let e of r)if(e.points)for(let t of e.points){let e=t.x,n=(t.y-o)*d+36,r=e-a;t.x=n,t.y=r}yt(n);let f=n.filter(e=>e.isGroup&&!e.parentId);if(f.length===0)return t===`RL`&&bt(e,`x`),!0;let p=mt(n),m=new Map;for(let e of n){if(e.isGroup)continue;let t=ht(e,p);if(!t)continue;let n=m.get(t)??[];n.push(e),m.set(t,n)}let h=0;for(let e of f){let t=e.padding??0;t>h&&(h=t)}let g=[],_=1/0,v=-1/0;for(let e of f){let t=_t(m.get(e.id)??[]);t&&(_=Math.min(_,t.minX),v=Math.max(v,t.maxX),g.push({lane:e,contentTop:t.minY,contentBottom:t.maxY,centerY:(t.minY+t.maxY)/2}))}if(_===1/0||v===-1/0)return!0;let y=Math.max(0,v-_)+2*Math.max(h,10),b=36+y,x=(_+v)/2-y/2-36,S=x+b/2,C=Math.max(h,36);g.sort((e,t)=>e.centerY-t.centerY);for(let e=0;ed.cy?g.bottom:g.top,t=d.cx+n;if(t<=g.left+Ct||t>=g.right-Ct)continue;i={x:t,y:e},a={x:t,y:o.y},c={x:o.x,y:o.y}}else{let e=f.cx>d.cx?g.right:g.left,t=d.cy+n;if(t<=g.top+Ct||t>=g.bottom-Ct)continue;i={x:e,y:t},a={x:o.x,y:t},c={x:o.x,y:o.y}}let p=R(i,a,Ct),m=R(a,c,Ct);if(p&&m||!p&&q(i,a,r,[l],1)||!m&&q(a,c,r,[u],1))continue;let _=!p&&Ie(i,a,e,t,{epsilon:Ct,skipDegenerateOther:!0}),v=!m&&Ie(a,c,e,t,{epsilon:Ct,skipDegenerateOther:!0});if(!(_||v)){h=p?[a,c]:m?[i,a]:[i,a,c];break}}h&&(t.points=h)}}t(Et,`portSwapToLShape`);function Dt(e,n){let r=.001,{realNodeRects:i,labelNodeRects:a}=je(n.values());for(let o of e){if(o.isLayoutOnly)continue;let s=o.points;if(!s||s.length<4)continue;let c=G(s,r);if(c.length<4)continue;let l=c.length-1,u=c[l],d=c[l-1],f=c[l-2],p=u.x-d.x,m=u.y-d.y,h=Math.hypot(p,m);if(h>=10||h0;O={x:f.x,y:E},k={x:e?D.right:D.left,y:E}}if(q(O,k,i,S?[S]:[],-2)||q(O,k,a,[],-2))continue;if(C){let e=n.get(C),t=e?K(e):void 0;if(t&&Se(O,t,2))continue}let A=t((e,t)=>`${e.x.toFixed(3)},${e.y.toFixed(3)}|${t.x.toFixed(3)},${t.y.toFixed(3)}`,`ownSegmentKey`),j=new Set;for(let e=0;e{for(let i of e){if(i===o||i.isLayoutOnly)continue;let e=i.points;if(!(!e||e.length<2))for(let i=0;i=0){let e=c[l-3],t=[C,S].filter(e=>!!e);if(q(e,O,i,t,-2)||ee(e,O))continue}let te=[...c.slice(0,l-2),O,k];o.points=te;let M=o.labelNodeId;if(M){let e=n.get(M);if(e){let t=e.width??0,n=e.height??0;if(t>0&&n>0){let i,a,o=-1;for(let e=0;e=t+2||d&&l>=n+2)&&l>o&&(o=l,i=(s.x+c.x)/2,a=(s.y+c.y)/2)}i!==void 0&&a!==void 0&&(e.x=i,e.y=a)}}}}}t(Dt,`collapseShortTerminalStub`);var Y=.001,X=8,Z=ye,Ot=t((e,t)=>z(e,t,Y)||B(e,t,Y),`orthogonallyAligned`);function kt(e,n){let r=t((e,t)=>{let n=e.x??0,r=e.y??0,i=t.x-n,a=t.y-r,o=(e.width??0)/2,s=(e.height??0)/2;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),{x:n+(a===0?0:s*i/a),y:r+s}):(i<0&&(o=-o),{x:n+o,y:r+(i===0?0:o*a/i)})},`rectIntersect`),i=t((e,t)=>{let i=G(e.points??[]);if(i.length<2)return;let a=t?e.start:e.end,o=a?n.get(a):void 0,s=o?K(o):void 0;if(!o||!a||!s)return;let c=t?i[0]:i[i.length-1],l=t?i[1]:i[i.length-2],u=r(o,c),d=c;if(Ot(l,u)&&(d=l),z(u,d,Y))return{edge:e,edgeId:String(e.id??``),nodeId:a,atStart:t,orientation:`V`,coord:u.x,min:Math.min(u.y,d.y),max:Math.max(u.y,d.y),boundary:u,railEnd:d,rect:s};if(B(u,d,Y))return{edge:e,edgeId:String(e.id??``),nodeId:a,atStart:t,orientation:`H`,coord:u.y,min:Math.min(u.x,d.x),max:Math.max(u.x,d.x),boundary:u,railEnd:d,rect:s}},`terminalLaneFor`),a=t((e,t)=>Math.max(0,Math.min(e.max,t.max)-Math.max(e.min,t.min)),`projectedOverlapLength`),o=t((e,t)=>e.nodeId!==t.nodeId||e.orientation!==t.orientation?!1:e.orientation===`H`?(Math.abs(e.boundary.x-e.rect.left)<1||Math.abs(e.boundary.x-e.rect.right)<1)&&z(e.boundary,t.boundary,1):(Math.abs(e.boundary.y-e.rect.top)<1||Math.abs(e.boundary.y-e.rect.bottom)<1)&&B(e.boundary,t.boundary,1),`sameTerminalFace`),s=t((e,t)=>e.nodeId!==t.nodeId||e.orientation!==t.orientation?!1:a(e,t)>=X&&Math.abs(e.coord-t.coord)<.5,`exactTerminalLaneConflict`),c=t((e,t)=>{if(e.nodeId!==t.nodeId||e.orientation!==t.orientation||e.orientation!==`H`||e.atStart===t.atStart)return!1;let n=a(e,t);if(n2*r?!1:o(e,t)&&Math.abs(e.coord-t.coord)<16},`nearTerminalLaneConflict`),l=t((e,n)=>{let r=G(e.edge.points??[]);if(r.length<2)return;let i=e.orientation===`V`?{x:e.boundary.x+n,y:e.boundary.y}:{x:e.boundary.x,y:e.boundary.y+n},a=e.orientation===`V`?{x:e.railEnd.x+n,y:e.railEnd.y}:{x:e.railEnd.x,y:e.railEnd.y+n};if(!t(()=>Math.abs(e.boundary.y-e.rect.top)<1||Math.abs(e.boundary.y-e.rect.bottom)<1?B(i,e.boundary,Y)&&i.x>=e.rect.left+1&&i.x<=e.rect.right-1:Math.abs(e.boundary.x-e.rect.left)<1||Math.abs(e.boundary.x-e.rect.right)<1?z(i,e.boundary,Y)&&i.y>=e.rect.top+1&&i.y<=e.rect.bottom-1:!1,`boundaryStaysOnSameFace`)())return;if(e.atStart){let t=r.length>1&&R(r[1],e.railEnd,Y),n=r.slice(t?2:1),o=n[0];return o&&!Ot(o,a)?void 0:[i,a,...n]}let o=r.length>1&&R(r[r.length-2],e.railEnd,Y),s=r.slice(0,o?-2:-1),c=s[s.length-1];if(!(c&&!Ot(c,a)))return[...s,a,i]},`shiftedCandidate`),u=t(e=>{let t=e.edge,r=G(t.points??[]);if(r.length!==2)return!1;let i=t.start,a=t.end,o=i?n.get(i):void 0,s=a?n.get(a):void 0;if(!o||!s)return!1;let c=o.x??0,l=o.y??0,u=s.x??0,d=s.y??0,[f,p]=r;return B(f,p,Y)&&Math.abs(l-d)<1&&Math.abs(c-u)>1||z(f,p,Y)&&Math.abs(c-u)<1&&Math.abs(l-d)>1},`laneIsStraightCollinearConnector`),d=[-7,7,-14,14,-21,21];for(let t=0;t<8;t++){let t=e.filter(e=>!e.isLayoutOnly).flatMap(e=>[i(e,!0),i(e,!1)]).filter(e=>!!e),n=!1;for(let e=0;e{let n=u(e),r=u(t);return n===r?Number(!t.atStart)-Number(!e.atStart):Number(n)-Number(r)});for(let e of p){for(let r of d){let a=l(e,r);if(!a)continue;let o=i({...e.edge,points:a},e.atStart);if(!(!o||t.some(t=>t.edge!==e.edge&&(s(o,t)||f&&c(o,t))))){e.edge.points=a,n=!0;break}}if(n)break}}if(!n)return}}t(kt,`separateSharedRenderedTerminalLanes`);function At(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=t((t,n)=>{let a=t.start,o=t.end,s=Z(n);if(s.length!==n.length-1)return!1;let c=[a,o].filter(e=>!!e);for(let e of s)if(q(e.a,e.b,r,c,-2)||q(e.a,e.b,i,[],-2))return!1;for(let n of e){if(n===t||n.isLayoutOnly)continue;let e=n.points;if(!(!e||e.length<2)){for(let t of s)for(let n of Z(G(e)))if(ve(t,n,.5)>=X||Le(t.a,t.b,n.a,n.b,Y))return!1}}return!0},`candidateIsSafe`),o=t((e,t)=>{if(t+4>=e.length)return;let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3],o=e[t+4],s=V(n,r)&&H(r,i)&&V(i,a)&&H(a,o)&&z(n,a,Y)&&z(n,o,Y)&&z(r,i,Y)&&(r.x-n.x)*(a.x-i.x)<0,c=H(n,r)&&V(r,i)&&H(i,a)&&V(a,o)&&B(n,a,Y)&&B(n,o,Y)&&B(r,i,Y)&&(r.y-n.y)*(a.y-i.y)<0;if(s||c)return G([...e.slice(0,t+1),o,...e.slice(t+5)]);if(t+5>=e.length)return;let l=e[t+5],u=H(n,r)&&V(r,i)&&H(i,a)&&V(a,o)&&H(o,l)&&z(n,o,Y)&&z(n,l,Y)&&z(i,a,Y)&&(i.x-r.x)*(o.x-a.x)<0,d=V(n,r)&&H(r,i)&&V(i,a)&&H(a,o)&&V(o,l)&&B(n,o,Y)&&B(n,l,Y)&&B(i,a,Y)&&(i.y-r.y)*(o.y-a.y)<0;if(!(!u&&!d))return G([...e.slice(0,t+1),l,...e.slice(t+6)])},`withoutDogleg`);for(let t=0;t<8;t++){let t=!1;for(let n of e){if(n.isLayoutOnly)continue;let e=G(n.points??[]);for(let r=0;r<=e.length-5;r++){let i=o(e,r);if(!(!i||!a(n,i))){n.points=i,t=!0;break}}if(t)break}if(!t)return}}t(At,`collapseRedundantRectangularDoglegs`);function jt(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=e.filter(e=>!e.isLayoutOnly),o=t((e,t,n)=>G(e===t?n??[]:e.points??[]),`pointsFor`),s=t((e,t)=>{let n=0;for(let r=0;r{let t=Z(e);if(t.length!==3)return;let n=t[1];if(!(t[0].horizontal===n.horizontal||t[2].horizontal===n.horizontal))return{index:n.index,horizontal:n.horizontal,vertical:n.vertical,segment:n}},`middleRail`),l=t((e,t)=>{let n=[e.start,e.end].filter(e=>!!e);return r.filter(e=>{if(n.includes(e.id))return!1;let r=e.rect;return t.horizontal?U(t.a.x,t.b.x,r.left,r.right)>=X&&t.a.y>=r.top-2&&t.a.y<=r.bottom+2:U(t.a.y,t.b.y,r.top,r.bottom)>=X&&t.a.x>=r.left-2&&t.a.x<=r.right+2})},`blockingRectsFor`),u=t((e,t,n)=>{let r=e.map(e=>({...e}));if(t.horizontal)r[t.index].y=n,r[t.index+1].y=n;else if(t.vertical)r[t.index].x=n,r[t.index+1].x=n;else return;let i=He(G(r));return Z(i).length===i.length-1?i:void 0},`candidateByMovingRail`),d=t((e,t,n)=>{let c=[e.start,e.end].filter(e=>!!e),l=Z(t);if(l.length!==t.length-1)return!1;for(let e of l)if(q(e.a,e.b,r,c,-2)||q(e.a,e.b,i,[],-2))return!1;for(let t of a)if(t!==e){for(let e of l)for(let n of Z(o(t)))if(ve(e,n,.5)>=X)return!1}return s(e,t)<=n},`candidateIsSafe`);for(let e=0;e<8;e++){let e=s(),t=!1;for(let n of a){let r=o(n),i=c(r);if(!i)continue;let a=l(n,i.segment);if(a.length===0)continue;let s=i.horizontal?[Math.min(...a.map(e=>e.rect.top))-20,Math.max(...a.map(e=>e.rect.bottom))+20]:[Math.min(...a.map(e=>e.rect.left))-20,Math.max(...a.map(e=>e.rect.right))+20];for(let a of s){let o=u(r,i.segment,a);if(!(!o||!d(n,o,e))){n.points=o,t=!0;break}}if(t)break}if(!t)return}}t(jt,`liftObstacleHuggingSameSideRails`);function Mt(e,n){let r=t(e=>{let t=e.groupTitleRect;if(!(!t||typeof t.left!=`number`||typeof t.right!=`number`||typeof t.top!=`number`||typeof t.bottom!=`number`||!Number.isFinite(t.left)||!Number.isFinite(t.right)||!Number.isFinite(t.top)||!Number.isFinite(t.bottom)||t.right<=t.left||t.bottom<=t.top))return{left:t.left,right:t.right,top:t.top,bottom:t.bottom}},`validTitleRect`),i=t(e=>{if(!e.isGroup||e.parentId)return;let t=e.direction,n=typeof t==`string`?t.toUpperCase():``;if(n===`LR`||n===`RL`||n===`BT`)return;let i=r(e),a=e.y,o=e.height;if(!i||typeof a!=`number`||typeof o!=`number`||!Number.isFinite(a)||!Number.isFinite(o)||o<=0)return;let s=i.right-i.left,c=i.bottom-i.top;if(!(c<=0||s{if(!e.horizontal)return!1;let n=e.a.y;return n<=t.top+Y||n>=t.bottom-Y?!1:U(e.a.x,e.b.x,t.left,t.right)>=X},`horizontalSegmentIntersectsTitle`),o=[...n.values()].map(i).filter(e=>!!e);if(o.length===0)return;let s=0;for(let t of e){if(t.isLayoutOnly)continue;let e=G(t.points??[]);for(let t of Z(e))for(let e of o)a(t,e.rect)&&(s=Math.max(s,e.rect.bottom-t.a.y+4))}if(!(s<=Y))for(let e of o){let t=e.node.y,n=e.node.height;typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||n<=0||(e.node.y=t-s/2,e.node.height=n+s,e.node.groupTitleRect={...e.rect,top:e.rect.top-s,bottom:e.rect.bottom-s})}}t(Mt,`liftTopLaneTitleBandsAboveRails`);function Nt(e,n){let r=t(e=>{let t=e.groupTitleRect;if(!(!t||typeof t.left!=`number`||typeof t.right!=`number`||typeof t.top!=`number`||typeof t.bottom!=`number`||!Number.isFinite(t.left)||!Number.isFinite(t.right)||!Number.isFinite(t.top)||!Number.isFinite(t.bottom)||t.right<=t.left||t.bottom<=t.top))return{left:t.left,right:t.right,top:t.top,bottom:t.bottom}},`validTitleRect`),i=t(e=>{if(!e.isGroup||e.parentId||e.direction!==`LR`)return;let t=r(e),n=e.x,i=e.width;if(!t||typeof n!=`number`||typeof i!=`number`||!Number.isFinite(n)||!Number.isFinite(i)||i<=0)return;let a=t.right-t.left,o=t.bottom-t.top;if(!(a<=0||o{if(!e.vertical)return!1;let n=e.a.x;return n<=t.left+Y||n>=t.right-Y?!1:U(e.a.y,e.b.y,t.top,t.bottom)>=X},`verticalSegmentIntersectsTitle`),o=t((e,t)=>{if(!e.horizontal)return!1;let n=e.a.y;return n<=t.top+Y||n>=t.bottom-Y?!1:U(e.a.x,e.b.x,t.left,t.right)>=X},`horizontalSegmentIntersectsTitle`),s=[...n.values()].map(i).filter(e=>!!e);if(s.length===0)return;let c=0;for(let t of e){if(t.isLayoutOnly)continue;let e=G(t.points??[]);for(let t of Z(e))for(let e of s)if(a(t,e.rect))c=Math.max(c,e.rect.right-t.a.x+4);else if(o(t,e.rect)){let n=Math.min(t.a.x,t.b.x);c=Math.max(c,e.rect.right-n+4)}}if(!(c<=Y))for(let e of s){let t=e.node.x,n=e.node.width;typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||n<=0||(e.node.x=t-c/2,e.node.width=n+c,e.node.groupTitleRect={...e.rect,left:e.rect.left-c,right:e.rect.right-c})}}t(Nt,`shiftLeftLaneTitleBandsLeftOfRails`);function Pt(e,n){let{realNodeRects:r}=je(n.values()),i=e.filter(e=>!e.isLayoutOnly),a=t((e,t=new Map)=>G(t.get(e)??e.points??[]),`replacementPointsFor`),o=t((e=new Map)=>{let t=0;for(let n=0;ni.reduce((t,n)=>t+W(a(n,e)),0),`totalBends`),c=t(e=>{let t=a(e);if(t.length<4)return;let n=t[t.length-2],r=t[t.length-1];if(!(!V(n,r,Y)&&!H(n,r,Y)))return{tailStart:n,terminal:r}},`terminalTailFor`),l=t((e,t)=>{let n=a(e);if(n.length<3)return;let r=n[0],i=n[1],o;if(V(r,i,Y))o={x:i.x,y:t.tailStart.y};else if(H(r,i,Y))o={x:t.tailStart.x,y:i.y};else return;let s=He(G([r,i,o,t.tailStart,t.terminal]));return Z(s).length===s.length-1?s:void 0},`candidateWithDestinationTail`),u=t((e,t)=>{let n=[e.start,e.end].filter(e=>!!e);for(let e of Z(t))if(q(e.a,e.b,r,n,-2))return!0;return!1},`pathHasNodeHit`),d=t((e,t,n)=>{for(let r of i)if(r!==e){for(let e of Z(t))for(let t of Z(a(r,n)))if(ve(e,t,.5)>=X)return!0}return!1},`pathHasSharedTrack`),f=t((e,t,n)=>!u(e,t)&&!d(e,t,n),`candidateIsSafe`),p=t(()=>{let e=new Map;for(let t of i){let r=t.end;if(!r||!n.has(r)||a(t).length<4)continue;let i=e.get(r)??[];i.push(t),e.set(r,i)}return e},`edgesByDestination`);for(let e=0;e<4;e++){let e=o();if(e===0)return;let t=s(),n,r=e,i=t;for(let t of p().values())for(let a=0;a=e||y>r||y===r&&b>=i||(n=v,r=y,i=b)}if(!n)return;for(let[e,t]of n)e.points=t}}t(Pt,`swapDestinationTerminalTailsToReduceCrossings`);function Ft(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=e.filter(e=>!e.isLayoutOnly),o=t((e,t=new Map)=>G(t.get(e)??e.points??[]),`replacementPointsFor`),s=t((e=new Map)=>{let t=0;for(let n=0;na.reduce((t,n)=>t+W(o(n,e)),0),`totalBends`),l=t(e=>{let t=e.start,r=e.end,i=t?n.get(t):void 0,a=r?n.get(r):void 0,o=i?K(i):void 0,s=a?K(a):void 0;return o&&s?{src:o,dst:s}:void 0},`endpointRectsFor`),u=t((e,t,n)=>{if(n.index<=0||n.index+1>=t.length-1)return;let r=l(e);if(r){if(n.vertical){let i=n.a.x,a=Math.min(r.src.left,r.dst.left),o=Math.max(r.src.right,r.dst.right),s=io+Y?`right`:void 0;return s?{edge:e,points:t,segmentIndex:n.index,axis:`vertical`,side:s,coord:i,min:Math.min(n.a.y,n.b.y),max:Math.max(n.a.y,n.b.y)}:void 0}if(n.horizontal){let i=n.a.y,a=Math.min(r.src.top,r.dst.top),o=Math.max(r.src.bottom,r.dst.bottom),s=io+Y?`bottom`:void 0;return s?{edge:e,points:t,segmentIndex:n.index,axis:`horizontal`,side:s,coord:i,min:Math.min(n.a.x,n.b.x),max:Math.max(n.a.x,n.b.x)}:void 0}}},`externalRailForSegment`),d=t(()=>{let e=[];for(let t of a){let n=o(t);for(let r of Z(n)){let i=u(t,n,r);i&&e.push(i)}}return e},`collectExternalRails`),f=t((e,t)=>e.edge!==t.edge&&e.axis===t.axis&&e.side===t.side&&U(e.min,e.max,t.min,t.max)>=X,`railsInteract`),p=t(e=>{let t=[],n=new Set;for(let r of e){if(n.has(r))continue;let i=[r],a=[];for(n.add(r);i.length>0;){let t=i.pop();a.push(t);for(let r of e)!n.has(r)&&f(t,r)&&(n.add(r),i.push(r))}a.length>1&&t.push(a)}return t},`connectedComponents`),m=t(e=>{let t=[];for(let n of e)t.some(e=>Math.abs(e-n.coord){let n=e.map(e=>e.coord),r=m(e),i=[];if(e.length<=6){let a=Array(r.length).fill(!1),o=[],s=t(()=>{if(o.length===e.length){o.some((e,t)=>Math.abs(e-n[t])>=Y)&&i.push([...o]);return}for(let[e,t]of r.entries())a[e]||(a[e]=!0,o.push(t),s(),o.pop(),a[e]=!1)},`visit`);return s(),i}for(let e=0;e{let n=new Map;for(let[r,i]of e.entries()){let e=t[r],a=n.get(i.edge)??i.points.map(e=>({x:e.x,y:e.y}));i.axis===`vertical`?(a[i.segmentIndex].x=e,a[i.segmentIndex+1].x=e):(a[i.segmentIndex].y=e,a[i.segmentIndex+1].y=e),n.set(i.edge,a)}let r=new Map;for(let[e,t]of n){let n=He(G(t));if(Z(n).length!==n.length-1)return;r.set(e,n)}return r},`replacementsForAssignment`),_=t(e=>{for(let[t,n]of e){let e=[t.start,t.end].filter(e=>!!e);for(let t of Z(n))if(q(t.a,t.b,r,e,-2)||q(t.a,t.b,i,[],-2))return!1}for(let t=0;t=X)return!1}}return!0},`candidateIsSafe`);for(let e=0;e<4;e++){let e=s();if(e===0)return;let t,n=e,r=c(),i=1/0;for(let a of p(d()))for(let o of h(a)){let l=g(a,o);if(!l||!_(l))continue;let u=s(l);if(u>=e)continue;let d=c(l),f=a.reduce((e,t,n)=>e+Math.abs(o[n]-t.coord),0);u>n||u===n&&(d>r||d===r&&f>=i)||(t=l,n=u,r=d,i=f)}if(!t)return;for(let[e,n]of t)e.points=n}}t(Ft,`reassignCrossingExternalRailChannels`);function It(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=e.filter(e=>!e.isLayoutOnly),o=t((e,t,n)=>G(e===t?n??[]:e.points??[]),`pointsFor`),s=t(e=>Z(e).reduce((e,t)=>{let n=t.a.x-t.b.x,r=t.a.y-t.b.y;return e+Math.hypot(n,r)},0),`pathLength`),c=t((e,t)=>{let n=0;for(let r=0;r{if(e.horizontal){let n=e.a.y;return(Math.abs(n-t.top)<1||Math.abs(n-t.bottom)<1)&&U(e.a.x,e.b.x,t.left,t.right)>=X}if(e.vertical){let n=e.a.x;return(Math.abs(n-t.left)<1||Math.abs(n-t.right)<1)&&U(e.a.y,e.b.y,t.top,t.bottom)>=X}return!1},`segmentRunsAlongRectBorder`),u=t(e=>{let t=[e.start,e.end].filter(e=>!!e),r=[];for(let e of t){let t=n.get(e),i=t?K(t):void 0;i&&r.push(i)}return r},`endpointRectsFor`),d=t((e,t)=>{if(t+3>=e.length)return[];let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3],o=V(n,r,Y)&&H(r,i,Y)&&V(i,a,Y),s=H(n,r,Y)&&V(r,i,Y)&&H(i,a,Y);if(!o&&!s||!(o?Math.sign(r.x-n.x)!==Math.sign(a.x-i.x):Math.sign(r.y-n.y)!==Math.sign(a.y-i.y)))return[];let c=z(n,a,Y)||B(n,a,Y)?[]:[{x:n.x,y:a.y},{x:a.x,y:n.y}],l=c.length===0?[[...e.slice(0,t+1),...e.slice(t+3)]]:c.map(n=>[...e.slice(0,t+1),n,...e.slice(t+3)]),u=new Set;return l.map(e=>He(G(e))).filter(e=>{if(Z(e).length!==e.length-1||!e.some(e=>R(e,a,Y)))return!1;let t=e.map(e=>`${e.x.toFixed(3)},${e.y.toFixed(3)}`).join(`|`);return u.has(t)?!1:(u.add(t),!0)})},`shortcutCandidatesAt`),f=t((e,t,n)=>{let s=[e.start,e.end].filter(e=>!!e),d=u(e);for(let e of Z(t))if(q(e.a,e.b,r,s,-2)||q(e.a,e.b,i,[],-2)||d.some(t=>l(e,t)))return!1;for(let n of a)if(n!==e){for(let e of Z(t))for(let t of Z(o(n)))if(ve(e,t,.5)>=X)return!1}return c(e,t)<=n},`candidateIsSafe`);for(let e=0;e<8;e++){let e=c(),t,n,r=e,i=1/0,l=1/0;for(let u of a){let a=o(u),p=W(a,Y),m=s(a);for(let o=0;o<=a.length-4;o++)for(let h of d(a,o)){let a=W(h,Y),o=s(h);if(!(ar||d===r&&(a>i||a===i&&o>=l)||(t=u,n=h,r=d,i=a,l=o)}}if(!t||!n)return;t.points=n}}t(It,`shortcutRedundantOrthogonalJogs`);function Lt(e,n){let r=[];for(let e of n.values()){if(e.isGroup||e.isEdgeLabel)continue;let t=e.x??0,n=e.y??0,i=K(e);i&&r.push({id:String(e.id??``),cx:t,cy:n,rect:i})}if(r.length===0)return;let i=new Map(r.map(e=>[e.id,e])),a=r.map(e=>({id:e.id,rect:e.rect})),o=[`top`,`bottom`,`left`,`right`],s={top:Math.min(...r.map(e=>e.rect.top))-20,bottom:Math.max(...r.map(e=>e.rect.bottom))+20,left:Math.min(...r.map(e=>e.rect.left))-20,right:Math.max(...r.map(e=>e.rect.right))+20},c=e.filter(e=>!e.isLayoutOnly),l=new Map(c.map((e,t)=>[e,t])),u=t(e=>{let t=e===`left`||e===`top`?-1:1,n=[];for(let r=0;r<=2;r++)n.push(s[e]+t*20*r);return n},`outwardTracksForSide`),d=t((e,t=new Map)=>G(t.get(e)??e.points??[]),`replacementPointsFor`),f=t((e,t)=>{let n=0;for(let r of e)for(let e of t)Le(r.a,r.b,e.a,e.b,Y)&&n++;return n},`crossingCountBetweenSegments`),p=t((e,t)=>f(Z(e),Z(t)),`crossingCountBetweenPaths`),m=t((e=new Map)=>{let n=0,r=[],i=new Set,a=[],o=t(e=>{i.has(e)||(i.add(e),a.push(e))},`addEdge`);for(let t=0;t0&&(n+=l,r.push({first:i,second:t,count:l}),o(i),o(t))}}return a.sort((e,t)=>(l.get(e)??0)-(l.get(t)??0)),{count:n,pairs:r,edgeSet:i,edges:a}},`crossingSnapshot`),h=t((e,t)=>{let n=new Set(t.keys());if(n.size===0)return e.count;let r=0;for(let t of e.pairs)(n.has(t.first)||n.has(t.second))&&(r+=t.count);let i=0;for(let e=0;e{let t=new Map;for(let n of e.pairs){let e=t.get(n.first)??new Set;e.add(n.second),t.set(n.first,e);let r=t.get(n.second)??new Set;r.add(n.first),t.set(n.second,r)}let n=[],r=new Set;for(let i of e.edges){if(r.has(i))continue;let e=[i],a=[];for(r.add(i);e.length>0;){let n=e.pop();a.push(n);for(let i of t.get(n)??[])r.has(i)||(r.add(i),e.push(i))}a.sort((e,t)=>(l.get(e)??0)-(l.get(t)??0)),a.length>1&&n.push(a)}return n},`crossingComponents`),_=t(e=>[e.start,e.end].filter(e=>!!e),`endpointIdsFor`),v=t(e=>{let t=[];for(let n of g(e)){let e=new Set(n),r=new Set(n.flatMap(e=>_(e))),i=[...n];for(let t of c)e.has(t)||_(t).some(e=>r.has(e))&&i.push(t);i.sort((e,t)=>(l.get(e)??0)-(l.get(t)??0)),t.push(i)}return t},`pairSearchGroups`),y=t((e,t,n)=>h(e,new Map([[t,n]])),`crossingCountWithSingleReplacement`),b=t(e=>{let t=new Map;for(let n of e.pairs)t.set(n.first,(t.get(n.first)??0)+n.count),t.set(n.second,(t.get(n.second)??0)+n.count);return t},`currentCrossingsByEdge`),x=t(e=>e.slice(1).reduce((t,n,r)=>{let i=e[r];return t+Math.abs(n.x-i.x)+Math.abs(n.y-i.y)},0),`pathLength`),S=t((e=new Map)=>c.reduce((t,n)=>t+W(d(n,e)),0),`totalBends`),C=t((e=new Map)=>c.reduce((t,n)=>t+x(d(n,e)),0),`totalLength`),w=t((e,t,n=new Map)=>{let r=Z(t);for(let t of c)if(t!==e){for(let e of r)for(let r of Z(d(t,n)))if(ve(e,r,.5)>=X)return!0}return!1},`pathHasSegmentConflict`),T=t((e,t)=>{let n=[e.start,e.end].filter(e=>!!e);for(let e of Z(t))if(q(e.a,e.b,a,n,-2))return!0;return!1},`pathHitsNode`),E=t((e,t)=>{let n=He(G(t));Z(n).length===n.length-1&&e.push(n)},`pushOrthogonalCandidate`),D=t(e=>e===`left`||e===`right`,`sideIsHorizontal`),O=t((e,t,n)=>{switch(t){case`left`:return Math.min(e.x,n.x)-20;case`right`:return Math.max(e.x,n.x)+20;case`top`:return Math.min(e.y,n.y)-20;case`bottom`:return Math.max(e.y,n.y)+20}},`localTrackForSameSide`),k=t((e,t,n,r)=>{let i=n===`left`||n===`top`?-1:1,a=[O(t,n,r),s[n]];for(let o of a)for(let a=0;a<=2;a++)E(e,ke(t,n,r,o+i*20*a))},`addSameSideCandidates`),A=t((e,t,n,r,i)=>{for(let a of u(n))for(let n of u(i))E(e,[t,{x:a,y:t.y},{x:a,y:n},{x:r.x,y:n},r])},`addHorizontalToVerticalCandidates`),j=t((e,t,n,r,i)=>{for(let a of u(n))for(let n of u(i))E(e,[t,{x:t.x,y:a},{x:n,y:a},{x:n,y:r.y},r])},`addVerticalToHorizontalCandidates`),ee=t((e,t,n,r,i)=>{let a=[...u(`top`),...u(`bottom`)];for(let o of u(n))for(let n of u(i))for(let i of a)E(e,[t,{x:o,y:t.y},{x:o,y:i},{x:n,y:i},{x:n,y:r.y},r])},`addHorizontalPairCandidates`),te=t((e,t,n,r,i)=>{let a=[...u(`left`),...u(`right`)];for(let o of u(n))for(let n of u(i))for(let i of a)E(e,[t,{x:t.x,y:o},{x:i,y:o},{x:i,y:n},{x:r.x,y:n},r])},`addVerticalPairCandidates`),M=t(e=>{let t=new Set;return e.map(e=>G(e)).filter(e=>{let n=e.map(e=>`${e.x.toFixed(3)},${e.y.toFixed(3)}`).join(`|`);return t.has(n)||e.length<2?!1:(t.add(n),!0)})},`dedupeCandidatePaths`),ne=t((e,t,n,r)=>{let i=[],a=Oe(e,t,n,r,20,Y);a&&E(i,a),t===r&&k(i,e,t,n);let o=D(t),s=D(r);return o&&!s?A(i,e,t,n,r):!o&&s?j(i,e,t,n,r):o?ee(i,e,t,n,r):te(i,e,t,n,r),M(i)},`buildCandidatesForSides`),N=t((e,t,n,r)=>{let i=[...u(`left`),...u(`right`)],a=[...u(`top`),...u(`bottom`)];for(let s of o){let o=De(r,s),c=s===`top`||s===`bottom`?u(s):a;for(let r of i){E(e,[t,n,{x:r,y:n.y},{x:r,y:o.y},o]);for(let i of c)E(e,[t,n,{x:r,y:n.y},{x:r,y:i},{x:o.x,y:i},o])}}},`addVerticalDepartureOuterTrackCandidates`),re=t((e,t,n,r)=>{let i=[...u(`left`),...u(`right`)],a=[...u(`top`),...u(`bottom`)];for(let s of o){let o=De(r,s),c=s===`left`||s===`right`?u(s):i;for(let r of a){E(e,[t,n,{x:n.x,y:r},{x:o.x,y:r},o]);for(let i of c)E(e,[t,n,{x:n.x,y:r},{x:i,y:r},{x:i,y:o.y},o])}}},`addHorizontalDepartureOuterTrackCandidates`),P=t(e=>{let t=e.start,n=e.end,r=n?i.get(n):void 0;if(!t||!r)return[];let a=G(e.points??[]);if(a.length<4)return[];let o=a[0],s=a[1],c=[];return H(o,s,Y)?N(c,o,s,r):V(o,s,Y)&&re(c,o,s,r),c},`terminalPreservingOuterTrackCandidates`),ie=t(e=>{let t=e.start,n=e.end,r=t?i.get(t):void 0,a=n?i.get(n):void 0;if(!r||!a)return[];let s=[];for(let e of o){let t=De(r,e);for(let n of o)s.push(...ne(t,e,De(a,n),n))}return s.push(...P(e)),s},`candidatePathsFor`),ae=t(()=>new Map(c.map(e=>[e,Z(d(e))])),`currentSegmentsByEdge`),oe=t((e,t,n)=>{let r=new Set;for(let i of c){if(i===e)continue;let a=n.get(i)??Z(d(i));t.some(e=>a.some(t=>ve(e,t,.5)>=X))&&r.add(i)}return r},`sharedTrackConflictsFor`),se=t((e,t,n,r)=>{let i=new Set;return ie(e).map(e=>He(G(e))).filter(t=>{if(T(e,t))return!1;let n=t.map(e=>`${e.x.toFixed(3)},${e.y.toFixed(3)}`).join(`|`);return i.has(n)||t.length<2?!1:(i.add(n),!0)}).map(i=>{let a=Z(i),o=0;for(let t of c)t!==e&&(o+=f(a,n.get(t)??Z(d(t))));return{candidate:i,candidateSegments:a,crossings:t.count-(r.get(e)??0)+o,bends:W(i,Y),totalBends:W(i),length:x(i)}}).filter(({crossings:e})=>e<=t.count).sort((e,t)=>e.crossings-t.crossings||e.bends-t.bends||e.length-t.length).slice(0,48).map(t=>({path:t.candidate,segments:t.candidateSegments,sharedTrackConflicts:oe(e,t.candidateSegments,n),totalBends:t.totalBends,length:t.length}))},`pairCandidatesFor`),ce=t((e,t,n,r,i,a)=>{let o=0;for(let n of e.pairs)(n.first===t||n.second===t||n.first===r||n.second===r)&&(o+=n.count);let s=f(n.segments,i.segments);for(let e of c){if(e===t||e===r)continue;let o=a.get(e)??Z(d(e));s+=f(n.segments,o)+f(i.segments,o)}return e.count-o+s},`pairCrossingCount`),le=t((e,t)=>{for(let n of e.sharedTrackConflicts)if(n!==t)return!1;return!0},`conflictsOnlyWith`),ue=t((e,t)=>e.segments.some(e=>t.segments.some(t=>ve(e,t,.5)>=X)),`candidatesShareTrack`),de=t((e,t,n,r)=>le(t,n.edge)&&le(r,e.edge)&&!ue(t,r),`pairCandidatesAreCompatible`),fe=t((e,t,n,r,i)=>{let a=ce(e.current,t.edge,n,r.edge,i,e.baseSegments);if(!(a>=e.current.count))return{replacements:new Map([[t.edge,n.path],[r.edge,i.path]]),crossings:a,bends:e.currentBends-(e.baseBendsByEdge.get(t.edge)??0)-(e.baseBendsByEdge.get(r.edge)??0)+n.totalBends+i.totalBends,length:e.currentLength-(e.baseLengthByEdge.get(t.edge)??0)-(e.baseLengthByEdge.get(r.edge)??0)+n.length+i.length}},`scorePairReplacement`),pe=t((e,t)=>e.crossings{let i=r;for(let r of t.candidates)for(let a of n.candidates){if(!de(t,r,n,a))continue;let o=fe(e,t,r,n,a);o&&pe(o,i)&&(i=o)}return i},`bestScoreForOptionPair`),I=t(e=>{let t=S(),n=C(),r=ae(),i=b(e),a=new Map(c.map(e=>[e,W(d(e))])),o=new Map(c.map(e=>[e,x(d(e))])),s=new Map,l=v(e);for(let t of l)for(let n of t){if(s.has(n))continue;let t=se(n,e,r,i);t.length>0&&s.set(n,{edge:n,candidates:t})}let u={replacements:new Map,crossings:e.count,bends:t,length:n},f={current:e,currentBends:t,currentLength:n,baseBendsByEdge:a,baseLengthByEdge:o,baseSegments:r};for(let t of l){let n=new Set(t.filter(t=>e.edgeSet.has(t))),r=t.map(e=>s.get(e)).filter(e=>!!e);for(let e=0;e0?u.replacements:void 0},`bestPairedReplacement`);for(let e=0;e<4;e++){let e=m(),t=e.count;if(t===0)return;let n,r,i=t,a=1/0;for(let o of e.edges){let s=W(d(o),Y);for(let c of ie(o)){let l=T(o,c),u=!l&&w(o,c),d=y(e,o,c),f=W(c,Y);l||u||(di||d===i&&f>=a||(n=o,r=c,i=d,a=f))}}if(n&&r){n.points=r;continue}let o=I(e);if(!o)return;for(let[e,t]of o)e.points=t}}t(Lt,`resolveRenderedOrthogonalCrossings`);var Rt=.001,zt=8;function Bt(e,n){let{nodeInfoById:r,realNodeRects:i}=Ae(n),a=[`top`,`bottom`,`left`,`right`],o={top:Math.min(...i.map(e=>e.rect.top))-20,bottom:Math.max(...i.map(e=>e.rect.bottom))+20,left:Math.min(...i.map(e=>e.rect.left))-20,right:Math.max(...i.map(e=>e.rect.right))+20},s=t((e,t,n,r)=>{let i=[],a=Oe(e,t,n,r,20,Rt);return a&&i.push(a),t===r&&i.push(ke(e,t,n,o[t])),i},`buildOrthogonalPathCandidates`),c=t((e,t)=>{for(let n=0;n{let i=0,a=ye(t,Rt),o=n.start,s=n.end;for(let t of e){if(t===n||t.isLayoutOnly)continue;let e=t.start,c=t.end;if(!r&&o&&s&&(e===o||e===s||c===o||c===s))continue;let l=t.points;if(!(!l||l.length<2))for(let e of a)for(let t of ye(l,Rt)){if(Pe(e.a,e.b,t.a,t.b,Rt,Rt)){i++;continue}ve(e,t,Rt)>=zt&&i++}}return i},`pathConflictCount`),u=t((e,t)=>{let n=Math.abs(e.y-t.rect.top),r=Math.abs(e.y-t.rect.bottom),i=Math.abs(e.x-t.rect.left),a=Math.abs(e.x-t.rect.right),o=`top`,s=n;return r{let r=d.get(e)??[];r.push({side:t,edgeId:n}),d.set(e,r)},`addFaceClaim`);for(let t of e){if(t.isLayoutOnly)continue;let e=t.points??[];if(e.length<1)continue;let n=t.id??``,i=t.start,a=t.end;if(i){let t=r.get(i);t&&f(i,u(e[0],t),n)}if(a){let t=r.get(a);t&&f(a,u(e[e.length-1],t),n)}}let p=t((e,t,n)=>d.get(e)?.some(e=>e.edgeId!==n&&e.side===t)??!1,`faceIsClaimed`);for(let t of e){if(t.isLayoutOnly)continue;let e=t.points;if(!e||e.length<2)continue;let n=W(e,Rt);if(n<4)continue;let i=t.start,o=t.end;if(!i||!o)continue;let m=r.get(i),h=r.get(o);if(!m||!h)continue;let g=t.id??``,_=l(e,t,!0),v=l(e,t),y,b=_,x=n;for(let e of a){if(p(i,e,g))continue;let n=De(m,e);for(let r of a){if(p(o,r,g))continue;let a=De(h,r);for(let u of s(n,e,a,r)){if(c(u,[i,o]))continue;let e=W(u,Rt);if(_>0){let n=l(u,t,!0);if(n>b||n===b&&e>=x)continue;b=n,x=e,y=u;continue}l(u,t)>v||ee.edgeId!==g));let n=d.get(o);n&&d.set(o,n.filter(e=>e.edgeId!==g)),f(i,u(y[0],m),g),f(o,u(y[y.length-1],h),g)}}}t(Bt,`simplifyDetouredEdges`);var Q=.001,Vt=10,Ht=7;function Ut(e,t){let n=t?0:e.length-1,r=t?1:-1,i=e[n],a=e[n+r];if(!i||!a)return;let o=a.x-i.x,s=a.y-i.y;if(!(Math.abs(o)+Math.abs(s)t&&we(e,Wt(t)))}t(Gt,`labelOverlapsOwnMarker`);function Kt(e,n){let r=[];for(let t of e){if(t.isLayoutOnly)continue;let e=t.points;if(!(!e||e.length<2))for(let n=0;n{let n=Te(t,3);for(let{nodeId:t,rect:r}of i)if(t!==e&&we(n,r))return!0;return!1},`labelOverlapsForeignNode`),s=t((e,t)=>{let n=Te(t,3);for(let t of r)if(t.edgeId!==e&&xe(t.p1,t.p2,n))return!0;return!1},`labelOverlapsForeignEdge`),c=t((e,t,n)=>o(e,n)||s(t,n),`labelOverlapsAnything`),l=[],u=t(e=>{for(let{id:t,rect:n}of a)if(Ce(n,e))return t},`findContainingLane`),d=t((e,t)=>l.some(n=>n.labelId!==e&&we(t,n.rect)),`overlapsPlacedLabel`);for(let r of e){if(r.isLayoutOnly)continue;let e=r.labelNodeId;if(!e)continue;let i=n.get(e);if(!i)continue;let f=r.points;if(!f||f.length<2)continue;let p=i.width??0,m=i.height??0;if(p<=0||m<=0)continue;let h=[];for(let e=0;e=Q&&i>=Q||h.push({idx:e,length:r+i,orientation:r>=Q?`horizontal`:`vertical`,midX:(t.x+n.x)/2,midY:(t.y+n.y)/2})}if(h.length===0)continue;let g=h.length>=3?h.filter(e=>e.idx>0&&e.idx0?g:h,v=p>=m?`horizontal`:`vertical`,y=t(e=>[...e].sort((e,t)=>{let n=e.orientation===v;if(n!==(t.orientation===v))return n?-1:1;let r=e.length>=(e.orientation===`horizontal`?p:m)+2;return r===t.length>=(t.orientation===`horizontal`?p:m)+2?t.length-e.length:r?-1:1}),`rankSegments`),b=h[0],x=h[h.length-1],S=[.5,.25,.75,.05,.95,.15,.85,.1,.9],C=t((e,t)=>{let n=f[e.idx],r=f[e.idx+1];return{midX:n.x+(r.x-n.x)*t,midY:n.y+(r.y-n.y)*t}},`anchorAtT`),w=t((e,t,n)=>Math.min(n,Math.max(t,e)),`clamp`),T=t((e,t)=>e.midX>=t.left-Q&&e.midX<=t.right+Q&&e.midY>=t.top-Q&&e.midY<=t.bottom+Q,`pointInsideRectInclusive`),E=t(e=>{let t=Ee(e.midX,e.midY,p,m),n=u(t);if(n)return{laneId:n,anchor:e,rect:t};let r=a.find(({rect:t})=>T(e,t));if(!r)return;let i=r.rect.left+p/2+1,o=r.rect.right-p/2-1,s=r.rect.top+m/2+1,c=r.rect.bottom-m/2-1;if(i>o||s>c)return;let l={midX:w(e.midX,i,o),midY:w(e.midY,s,c)},d=Ee(l.midX,l.midY,p,m);return T(e,d)?{laneId:r.id,anchor:l,rect:d}:void 0},`placementForAnchor`),D=t((e,t,n)=>e.orientation===`horizontal`?Math.abs(t.midX-n.x):Math.abs(t.midY-n.y),`distanceAlongSegment`),O=t((e,t)=>{let n=(e.orientation===`horizontal`?p/2:m/2)+12;if(e===b){let r=f[e.idx];if(D(e,t,r)+Q{let n=y(t);for(let t of n)for(let n of S){let i=C(t,n);if(!O(t,i))continue;let a=E(i);if(a&&!Gt(a.rect,f)&&!d(e,a.rect)&&!c(e,r.id,a.rect))return{laneId:a.laneId,anchor:a.anchor}}},`tryPool`),A=t((t,n,i=!1)=>{let a=y(t);for(let t of a){let a={midX:t.midX,midY:t.midY};if(n&&!O(t,a))continue;let c=E(a);if(c&&!Gt(c.rect,f)&&!d(e,c.rect)&&!o(e,c.rect)&&(i||!s(r.id,c.rect)))return{laneId:c.laneId,anchor:c.anchor}}},`findLaneContainingFallback`),j=k(_)??(_.lengtht.labelId===e);n>=0?l[n]={labelId:e,rect:t}:l.push({labelId:e,rect:t})}}}t(Kt,`anchorLabelsToPolyline`);var qt=1e-6,Jt=8/2,Yt=3;function Xt(e,t){return e{let s=Xt(r,i),c=0,l=t(e=>{if(!e)return;let t=a.get(e);if(!t)return;let n=o===`x`?t.w/2:t.h/2;n>c&&(c=n)},`consider`);l(n.labelNodeId);for(let t of e){if(t===n||t.isLayoutOnly)continue;let e=t.start,r=t.end;!e||!r||Xt(e,r)===s&&l(t.labelNodeId)}return c>0?c+Yt:0},`labelClearanceFor`);for(let t of e){if(t.isLayoutOnly)continue;let n=t.points;if(!be(n,qt))continue;let a=Ne(t,r,qt);if(!a)continue;let{srcId:s,dstId:c,srcInfo:l,dstInfo:u,collinearX:d,collinearY:f}=a;if(d===f)continue;let p,m;if(d){let e=u.cy>l.cy;p={x:l.cx,y:e?l.rect.bottom:l.rect.top},m={x:u.cx,y:e?u.rect.top:u.rect.bottom}}else{let e=u.cx>l.cx;p={x:e?l.rect.right:l.rect.left,y:l.cy},m={x:e?u.rect.left:u.rect.right,y:u.cy}}if(q(p,m,i,[s,c],1))continue;let h=o(t,s,c,d?`x`:`y`),g=h>Jt?h:Jt,_=[0,g,-g];for(let n of _){let r={...p},a={...m};if(d){if(r.x+=n,a.x+=n,r.x<=l.rect.left||r.x>=l.rect.right||a.x<=u.rect.left||a.x>=u.rect.right)continue}else if(r.y+=n,a.y+=n,r.y<=l.rect.top||r.y>=l.rect.bottom||a.y<=u.rect.top||a.y>=u.rect.bottom)continue;if(!q(r,a,i,[s,c],1)&&!Ie(r,a,e,t,{epsilon:qt})){t.points=[r,a];break}}}}t(Zt,`straightenCollinearSiblingDetours`);function Qt(e,n){let r=.001,{realNodeRects:i,labelNodeRects:a}=je(n.values()),o=t((e,t)=>ye(t,r).map(n=>({...n,edge:e,interior:n.index>=1&&n.index<=t.length-3})),`segmentsFor`),s=t(()=>{let t=[];for(let n of e){if(n.isLayoutOnly)continue;let e=n.points;!e||e.length<2||t.push(...o(n,G(e)))}return t},`allSegments`),c=t((e,t)=>e.horizontal&&t.horizontal?U(e.a.x,e.b.x,t.a.x,t.b.x)>=8&&Math.abs(e.a.y-t.a.y)<7:e.vertical&&t.vertical?U(e.a.y,e.b.y,t.a.y,t.b.y)>=8&&Math.abs(e.a.x-t.a.x)<7:!1,`hasCrowdedParallelTrack`),l=t((t,n)=>{let s=t.start,l=t.end,u=o(t,n);if(u.length!==n.length-1)return!1;let d=[s,l].filter(e=>!!e),f=t.labelNodeId?[t.labelNodeId]:[];for(let e of u)if(q(e.a,e.b,i,d,-2)||q(e.a,e.b,a,f,-2))return!1;for(let n of e){if(n===t||n.isLayoutOnly)continue;let e=n.points;if(!(!e||e.length<2)){for(let t of u)for(let i of o(n,G(e)))if(c(t,i)||Le(t.a,t.b,i.a,i.b,r))return!1}}return!0},`candidateIsSafe`),u=t((e,t)=>{let n=G(e.edge.points??[]);if(n.length<4||e.index>=n.length-1)return;let r=n.map(e=>({...e}));if(e.horizontal)r[e.index].y+=t,r[e.index+1].y+=t;else if(e.vertical)r[e.index].x+=t,r[e.index+1].x+=t;else return;return o(e.edge,r).length===r.length-1?r:void 0},`shiftedCandidate`),d=t((e,t)=>({x:e.x??(t.left+t.right)/2,y:e.y??(t.top+t.bottom)/2}),`nodeCenter`),f=t(e=>{let t=e.edge,r=G(t.points??[]);if(r.length!==4||e.index!==1)return;let i=t.start?n.get(t.start):void 0,a=t.end?n.get(t.end):void 0,o=i?K(i):void 0,s=a?K(a):void 0,c=r.slice(e.index+2);if(!(!i||!a||!o||!s||c.length===0))return{sourceCenter:d(i,o),targetCenter:d(a,s),sourceRect:o,tail:c}},`sourceDetourContextFor`),p=t((e,t,n,i,a,o)=>{let s=i.y>=n.y,c=s?a.bottom:a.top,l=c+(s?20:-20);if(s&&e.b.y<=l+r||!s&&e.b.y>=l-r)return;let u=e.a.x+t;return G([{x:n.x,y:c},{x:n.x,y:l},{x:u,y:l},{x:u,y:e.b.y},...o],r)},`verticalSourceDetour`),m=t((e,t,n,i,a,o)=>{let s=i.x>=n.x,c=s?a.right:a.left,l=c+(s?20:-20);if(s&&e.b.x<=l+r||!s&&e.b.x>=l-r)return;let u=e.a.y+t;return G([{x:c,y:n.y},{x:l,y:n.y},{x:l,y:u},{x:e.b.x,y:u},...o],r)},`horizontalSourceDetour`),h=t((e,t)=>{let n=f(e);if(n){if(e.vertical)return p(e,t,n.sourceCenter,n.targetCenter,n.sourceRect,n.tail);if(e.horizontal)return m(e,t,n.sourceCenter,n.targetCenter,n.sourceRect,n.tail)}},`sourceDetourCandidate`),g=[-7,7,-14,14,-21,21];for(let e=0;e<12;e++){let e=s(),t=!1;for(let n=0;ne.interior);for(let e of o){for(let n of g){let r=u(e,n);if(r&&l(e.edge,r)){e.edge.points=r,t=!0;break}let i=h(e,n);if(i&&l(e.edge,i)){e.edge.points=i,t=!0;break}}if(t)break}}if(!t)return}}t(Qt,`nudgeSharedInteriorSubpaths`);function $t(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=r.x-n.x,s=r.y-n.y,c=i*s-a*o;if(Math.abs(c)<1e-10)return!1;let l=n.x-e.x,u=n.y-e.y,d=(l*s-u*o)/c,f=(l*a-u*i)/c,p=.01;return d>p&&d<1-p&&f>p&&f<1-p}t($t,`segmentsIntersect`);function en(e){let t=e.nodes??[],r=e.edges??[],i=[];if(!r.length||!t.length)return i;let a=Me(t),o=[];for(let e of r){if(e.isLayoutOnly)continue;let t=e.points;if(!t||t.length<2)continue;let n=e.start,r=e.end,s=e.labelNodeId,c=e.id??`${n}->${r}`;for(let e of a)if(!(e.nodeId===n||e.nodeId===r)&&!(s&&e.nodeId===s)){for(let n=0;n0){let e=i.filter(e=>e.type===`edge-node-overlap`).length,t=i.filter(e=>e.type===`edge-edge-crossing`).length;n.warn(`[SWIMLANE_VALIDATE] ${i.length} issue(s) detected: ${e} edge-node overlap(s), ${t} edge crossing(s)`);for(let e of i)n.warn(`[SWIMLANE_VALIDATE] ${e.type}: ${e.detail}`)}return i}t(en,`validateSwimlanesLayout`);function tn(e,n){let r=e.nodes??[],i=e.edges??[],a=r.filter(e=>!e.isGroup);if((n===`LR`||n===`RL`)&&a.length>0&&!St(e,n)||n===`BT`&&a.length>0&&!xt(e))return;for(let e of i){if(e.isLayoutOnly)continue;let t=e.points;!t||t.length<2||(e.points=He(Ve(t)))}Bt(i,r),Zt(i,r),Et(i,r);let o=new Map;for(let e of r)o.set(String(e.id),e);Kt(i,o),Je(i,o),Dt(i,o),Qt(i,o),kt(i,o),At(i,o),jt(i,o),Pt(i,o);let s=t(()=>{Lt(i,o),Ft(i,o),It(i,o),Kt(i,o),pt(i,o),jt(i,o),Kt(i,o),pt(i,o)},`finalizeRenderedEdges`);s(),Qt(i,o),s(),Mt(i,o),Nt(i,o),Mt(i,o),Nt(i,o)}t(tn,`postProcessSwimlaneLayout`);function nn(e){let t=new Map(e.nodeById),n=new Set,r=[];for(let i of e.edges){if(!t.has(i.src)||!t.has(i.dst))continue;let e=`${i.id}:${i.src}->${i.dst}`;n.has(e)||(n.add(e),r.push(i))}return{nodes:[...t.keys()],edges:r,layout:e.layout,nodeById:t}}t(nn,`normalizeGraph`);function rn(e,t){return e.edges.filter(e=>e.dst===t)}t(rn,`incoming`);function an(e){let t=new Map;for(let n of e.nodes)t.set(n,[]);for(let n of e.edges)t.get(n.src).push(n.dst);return t}t(an,`buildSuccessorMap`);function on(e){let t=an(e);for(let e of t.values())e.sort((e,t)=>e.localeCompare(t));return t}t(on,`buildSortedSuccessorMap`);function sn(e){let t=new Map;for(let n of e.nodes)t.set(n,0);for(let n of e.edges)t.set(n.dst,(t.get(n.dst)??0)+1);return t}t(sn,`buildInDegreeMap`);function cn(e){return[...e.entries()].filter(([,e])=>e===0).map(([e])=>e).sort((e,t)=>e.localeCompare(t))}t(cn,`sortedZeroInDegreeNodes`);function ln(e,t=()=>!0){let n=new Map,r=new Map;for(let t of e.nodes)n.set(t,[]),r.set(t,[]);for(let i of e.edges)t(i)&&(r.get(i.src).push(i.dst),n.get(i.dst).push(i.src));return{preds:n,succs:r}}t(ln,`buildPredecessorSuccessorMaps`);function un(e,t,n,r){let i=0;for(let t of e.nodes)r?.skipGroups&&e.nodeById.get(t)?.isGroup||(i=Math.max(i,n[t]??0));let a=Array.from({length:i+1},()=>[]);for(let i of t)r?.skipGroups&&e.nodeById.get(i)?.isGroup||a[Math.max(0,n[i]??0)].push(i);return a}t(un,`buildLayersFromRanks`);function dn(e){let t=sn(e),n=cn(t),r=[],i=on(e);for(;n.length;){let e=n.shift();r.push(e);for(let r of i.get(e)??[])if(t.set(r,(t.get(r)??0)-1),(t.get(r)??0)===0){let e=0;for(;e{if(i-t<=1)return 0;let a=t+i>>1,o=r(t,a)+r(a,i),s=t,c=a,l=t;for(;s=i||se.dst===t.dst?e.id.localeCompare(t.id):e.dst.localeCompare(t.dst));let i=Object.create(null);for(let e of n.nodes)i[e]=0;let a=[],o=t(e=>{i[e]=1;for(let t of r.get(e)??[]){let e=t.dst;i[e]===0?o(e):i[e]===1&&a.push(t)}i[e]=2},`dfs`),s=[...n.nodes].sort((e,t)=>e.localeCompare(t));for(let e of s)i[e]===0&&o(e);let c=new Set(a.map(e=>`${e.id}:${e.src}->${e.dst}`)),l=n.edges.map(e=>c.has(`${e.id}:${e.src}->${e.dst}`)?{id:e.id,src:e.dst,dst:e.src,weight:e.weight,ref:e.ref}:e);return{acyclic:{nodes:[...n.nodes],edges:l,layout:n.layout,nodeById:new Map(n.nodeById)},reversed:a}}t(mn,`removeCycles_DFS`);function hn(e){let n=new Map,r=t(t=>{if(n.has(t))return n.get(t);let i=e.nodeById.get(t);if(!i)return n.set(t,null),null;let a=i.parentId;if(!a)return n.set(t,null),null;let o=r(a)??a;return n.set(t,o),o},`resolve`);for(let t of e.nodes)r(t);return n}t(hn,`buildTopLaneMap`);function gn(e){let t=hn(e);return e=>t.get(e)??null}t(gn,`createTopLaneResolver`);function _n(e){let t=[];for(let n of e.layout.nodes??[])n.isGroup&&!n.parentId&&t.push(n.id);return[...new Set(t)].reverse()}t(_n,`buildTopLaneOrder`);function vn(e,t){let n=_n(e);if(!t||t.length===0)return n;let r=new Set(n),i=new Set,a=[];for(let e of t)!r.has(e)||i.has(e)||(i.add(e),a.push(e));for(let e of n)i.has(e)||a.push(e);return a}t(vn,`resolveTopLaneOrder`);var yn={EPSILON:1e-6},bn={GRAVITY_ITERATIONS:8,MAX_CROSSING_OPTIMIZATION_PASSES:4,DEFAULT_COMPACT_SINGLE_INPUT:!0},xn={DEFAULT_LAYER_GAP:100,DEFAULT_NODE_GAP:40};function Sn(e,n){let r=nn(e),i=n?.laneOf??(()=>null),a=n?.rankHint,{preds:o}=ln(r);for(let e of o.values())e.sort((e,t)=>e.localeCompare(t));let s=dn(r)??[...r.nodes].sort((e,t)=>e.localeCompare(t)),c=new Map;for(let[e,t]of s.entries())c.set(t,e);let l=new Map,u=new Map;for(let e of r.nodes)u.set(e,[]);for(let e of s){let t=(o.get(e)??[]).filter(e=>l.has(e));if(t.length>0){let n=Cn(e,t,{laneOf:i,rankHint:a,topoIndex:c});l.set(e,n),u.get(n).push(e)}else l.has(e)||l.set(e,null)}for(let e of r.nodes)l.has(e)||l.set(e,null);let d=new Set;for(let e of r.nodes)(l.get(e)??null)===null&&d.add(e);let f=[...d].sort((e,t)=>{let n=c.get(e)??0,r=c.get(t)??0;return n===r?e.localeCompare(t):n-r}),p=wn(r),m=new Map;for(let[e,t]of p.entries())m.set(e,[...t].sort((e,t)=>e.localeCompare(t)));let h=Tn(m),g=En(m),_=new Map;for(let e of r.nodes)_.set(e,[]);for(let e of g)for(let t of e.nodes){let n=_.get(t);n?n.push(e.id):_.set(t,[e.id])}let v=[],y=[],b=new Set,x=t(e=>{if(!b.has(e)){b.add(e),v.push(e);for(let t of u.get(e)??[])x(t);y.push(e)}},`walk`);for(let e of f)x(e);for(let e of s)x(e);return{parent:l,children:u,roots:f,componentOf:h,blocks:g,nodeBlocks:_,adjacency:m,preorder:v,postorder:y,topologicalOrder:s}}t(Sn,`buildDrivingTree`);function Cn(e,t,n){let r=n.laneOf(e);return[...t].sort((e,t)=>{let i=n.laneOf(e),a=n.laneOf(t),o=i!=null&&i===r;if(o!==(a!=null&&a===r))return o?-1:1;let s=n.rankHint?.[e],c=n.rankHint?.[t];if(s!=null&&c!=null&&s!==c)return c-s;let l=n.topoIndex.get(e)??0,u=n.topoIndex.get(t)??0;return l===u?e.localeCompare(t):l-u})[0]}t(Cn,`chooseParent`);function wn(e){let t=new Map;for(let n of e.nodes)t.set(n,new Set);for(let n of e.edges)t.get(n.src).add(n.dst),t.get(n.dst).add(n.src);return t}t(wn,`buildAdjacency`);function Tn(e){let t=new Map,n=0;for(let r of e.keys()){if(t.has(r))continue;let i=[r];for(;i.length>0;){let r=i.pop();if(!t.has(r)){t.set(r,n);for(let n of e.get(r)??[])t.has(n)||i.push(n)}}n++}return t}t(Tn,`assignComponents`);function En(e){let n=new Map,r=new Map,i=[],a=[],o=0,s=t((t,c)=>{n.set(t,++o),r.set(t,o);for(let l of e.get(t)??[])l!==c&&(n.has(l)?(n.get(l)??0)<(n.get(t)??0)&&(i.push([t,l]),r.set(t,Math.min(r.get(t)??o,n.get(l)??o))):(i.push([t,l]),s(l,t),r.set(t,Math.min(r.get(t)??o,r.get(l)??o)),(r.get(l)??0)>=(n.get(t)??0)&&a.push(Dn(t,l,i,a.length))))},`visit`);for(let t of e.keys())n.has(t)||s(t,null);return a}t(En,`computeBlocks`);function Dn(e,t,n,r){let i=[],a=new Set;for(;n.length>0;){let r=n.pop();if(i.push(r),a.add(r[0]),a.add(r[1]),r[0]===e&&r[1]===t||r[0]===t&&r[1]===e)break}return{id:r,edges:i,nodes:[...a]}}t(Dn,`popBlock`);function On(e,n,r){let i=[...e.nodes],a=new Map;for(let[e,t]of i.entries())a.set(t,e);let o=i.length,s=Array(o).fill(-1),c=Array(o).fill(0),l=[],u=new Set;for(let e of i){let t=r.parent.get(e)??null,n=a.get(e);n!=null&&(t??(s[n]=-1,c[n]=0,u.has(e)||(u.add(e),l.push(e))))}for(;l.length>0;){let e=l.shift(),t=a.get(e);if(t==null)continue;let n=r.children.get(e)??[];for(let e of n){if(u.has(e))continue;let n=a.get(e);n!=null&&(s[n]=t,c[n]=c[t]+1,u.add(e),l.push(e))}}for(let e of i){if(u.has(e))continue;let t=a.get(e);t!=null&&(s[t]=-1,c[t]=0,u.add(e))}let d=Math.max(1,Math.ceil(Math.log2(Math.max(1,o)))+1),f=Array.from({length:d},()=>Array(o).fill(-1));for(let e=0;e{if(e===-1||t===-1)return-1;c[e]>t&1&&(e=f[t][e],e===-1))return-1;if(e===t)return e;for(let n=d-1;n>=0;n--){let r=f[n][e],i=f[n][t];r===-1||i===-1||r!==i&&(e=r,t=i)}return f[0][e]},`lcaIndex`),m=Array.from({length:o},()=>new Map);for(let t of e.edges){let e=t.src,r=t.dst,i=n[e],o=n[r];if(i==null||o==null||(i>o&&([e,r]=[r,e],[i,o]=[o,i]),i==null||o==null||i===o))continue;let s=a.get(e),c=a.get(r);if(s==null||c==null)continue;let l=p(s,c);if(l===-1)continue;let u=m[l];for(let e=i;e{if(t.size!==0)for(let[n,r]of t)e.set(n,(e.get(n)??0)+r)},`mergeInto`),_=new Set,v=t(e=>{let t=a.get(e);_.add(e);let i=t==null?void 0:m[t],o=i?new Map(i):new Map,s=r.children.get(e)??[];for(let t of s){let r=v(t),i=n[e];if(i!=null){let a=h.get(e);a||(a=new Map,h.set(e,a));let o=r.get(i)??0,s=n[t];s!=null&&s>i&&(o+=1),a.set(t,o)}g(o,r)}return o},`dfs`);for(let e of r.roots)_.has(e)||v(e);for(let e of i)_.has(e)||v(e);return h}t(On,`computeSubtreeCrossCounts`);function kn(e,n,r){let i=new Map,a=t(e=>{let t=r[e]??0,o=[...n.get(e)??[]];o.sort(An(r));for(let e of o){a(e);let n=i.get(e);n!=null&&(t=Math.min(t,n))}i.set(e,t)},`annotate`);for(let t of e)a(t);return i}t(kn,`annotateMinimumLayers`);function An(e){return(t,n)=>{let r=e[t]??0,i=e[n]??0;return r===i?t.localeCompare(n):r-i}}t(An,`compareByRankThenId`);function jn(e,n,r,i){let a=0;for(let e of n){let t=r[e]??0;t>a&&(a=t)}let o=Array.from({length:a+1},()=>[]),s=new Set,c=t(e=>{if(s.has(e))return;s.add(e);let t=r[e]??0;o[t]||(o[t]=[]),o[t].push(e);for(let t of i(e))c(t)},`emit`);for(let t of e)c(t);for(let e of n)if(!s.has(e)){let t=r[e]??0;o[t]||(o[t]=[]),o[t].push(e),s.add(e)}return o}t(jn,`emitNodesInTreeOrder`);function Mn(e){let t=[];for(let n of e){let e=new Set,r=[];for(let t of n)e.has(t)||(e.add(t),r.push(t));t.push(r)}return t}t(Mn,`deduplicateLayers`);function Nn(e,t,n,r){return i=>{let a=e.get(i)??[];if(a.length===0)return[];let o=t[i]??0,s=[],c=[],l=n.get(i);for(let e of a){let t=r.get(e)??o;t>o?s.push({child:e,min:t}):c.push(e)}return s.sort((e,t)=>e.min===t.min?e.child.localeCompare(t.child):e.min-t.min),c.sort((e,t)=>{let n=l?.get(e)??0,i=l?.get(t)??0;if(n!==i)return n-i;let a=r.get(e)??o,s=r.get(t)??o;return a===s?e.localeCompare(t):a-s}),[...s.map(e=>e.child),...c]}}t(Nn,`createChildOrderer`);function Pn(e,t,n){let r=Sn(e,{rankHint:t,laneOf:n}),{children:i,roots:a}=r;for(let t of e.nodes)i.has(t)||i.set(t,[]);let o=On(e,t,r),s=[...a].sort(An(t)),c=Nn(i,t,o,kn(s,i,t)),l=jn(s,e.nodes,t,c);return l=Mn(l),l}t(Pn,`buildMultitreeLayerOrder`);function Fn(e,t,n){let r=new Set(e),i=new Set(t),a=fn(t),o=[];for(let e of n)r.has(e.src)&&i.has(e.dst)&&o.push(a.get(e.dst));return pn(o)}t(Fn,`countCrossingsBetweenAdjacent`);function In(e,t,n){let r=[];for(let e of t){let t=n[e.src],i=n[e.dst];if(t==null||i==null||t===i)continue;let a=e.src,o=e.dst,s=t,c=i;t>i&&(a=e.dst,o=e.src,s=i,c=t);for(let t=s;t(n[t]??0)-(n[e]??0));for(let s of o){let o=n[s]??0;if(o===0)continue;let c=0;for(let e of r.get(s)??[])c=Math.max(c,(n[e]??0)+1);if(c>=o)continue;let l=o;n[s]=c;let u=In(Pn(e,n,i),e.edges,n);u(t[e]??0)-(t[n]??0)||e.localeCompare(n));for(let i of r){let r=n(i);if(!r)continue;let a=e.edges.filter(e=>e.src===i);if(a.length===0)continue;let o=!1,s=0;for(let e of a){let t=n(e.dst);t==null||t===r?o=!0:s++}if(s===0||o)continue;let c=0,l=!1;for(let t of e.edges){if(t.dst!==i)continue;let e=n(t.src);e&&(e===r?l=!0:c++)}if(c>0||!l)continue;let u=t[i]??0,d=u+s,f=0;for(let n of e.edges)n.dst===i&&(f=Math.max(f,(t[n.src]??0)+1));let p=Math.max(u,f,d);p!==u&&(t[i]=p)}}t(Rn,`adjustCrossLaneSources`);function zn(e,t){let n=nn(e),r=dn(n)??[...n.nodes].sort(),i=t?.compactSingleInput??!1,a=gn(n),o=Object.create(null);for(let e of r){let r=rn(n,e),s=t?.ignoreCrossLaneEdges?r.filter(t=>{let n=a(t.src),r=a(e);return!n||!r||n===r}):r;if(s.length===0)o[e]=0;else if(i&&s.length===1){let t=s[0].src;a(t)===a(e)?o[e]=(o[t]??0)+1:o[e]=o[t]??0}else{let t=-1/0;for(let e of s)t=Math.max(t,(o[e.src]??0)+1);o[e]=t===-1/0?0:t}}return(t?.optimizeRanksByCrossings??!1)&&(o=Ln(n,o)),t?.ignoreCrossLaneEdges&&Rn(n,o),{layers:Pn(n,o,a),rankOf:o,dummy:new Set}}t(zn,`assignLayers_LongestPath`);function Bn(e,n){let r=nn(e),i={...zn(r,{compactSingleInput:n?.compactSingleInput,ignoreCrossLaneEdges:n?.ignoreCrossLaneEdges,optimizeRanksByCrossings:n?.optimizeRanksByCrossings}).rankOf},a=gn(r),{preds:o,succs:s}=ln(r,e=>{if(n?.ignoreCrossLaneEdges){let t=a(e.src),n=a(e.dst);if(t&&n&&t!==n)return!1}return!0}),c=dn(r)??[...r.nodes],l=[...c].reverse(),u=t((e,t)=>{let n=0;for(let t of o.get(e)??[])n=Math.max(n,(i[t]??0)+1);let r=1/0,a=s.get(e)??[];return a.length>0&&(r=Math.min(...a.map(e=>(i[e]??0)-1))),Number.isFinite(r)||(r=Math.max(n,t)),Math.min(Math.max(t,n),r)},`clampFeasible`),d=bn.GRAVITY_ITERATIONS,f=t(e=>{let t=!1;for(let n of e){let e=o.get(n)??[],r=s.get(n)??[];if(e.length===0&&r.length===0)continue;let a=e.length>0?e.reduce((e,t)=>e+(i[t]??0)+1,0)/e.length:i[n]??0,c=r.length>0?r.reduce((e,t)=>e+(i[t]??0)-1,0)/r.length:i[n]??0,l=Math.round((a+c)/2),d=u(n,l);d!==i[n]&&(i[n]=d,t=!0)}return t},`relaxOrder`);for(let e=0;e0){let n=Math.min(...t.map(e=>(i[e]??0)-1));(i[e]??0)>n&&(i[e]=n)}}return{layers:un(r,c,i),rankOf:i,dummy:new Set}}t(Bn,`assignLayers_Gravity`);function Vn(e){let t=sn(e),n=on(e),r=cn(t),i=[];for(;r.length>0;){let e=[];for(let a of r){i.push(a);for(let r of n.get(a)??[])t.set(r,(t.get(r)??0)-1),(t.get(r)??0)===0&&e.push(r)}r=e.sort((e,t)=>e.localeCompare(t))}return i.length===e.nodes.length?i:null}t(Vn,`topoSortByGenerationIfAcyclic`);function Hn(e,n){let r=nn(e),i=n?.direction===`LR`?Vn(r)??[...r.nodes].sort():dn(r)??[...r.nodes].sort(),a=gn(r),o=t(e=>a(e)??e,`laneOf`),s=Object.create(null),c=new Map,l=t((e,t)=>n?.ignoreCrossLaneEdges??!0?+(o(e)===o(t)):1,`edgeWeight`);for(let e of i){if(r.nodeById.get(e)?.isGroup)continue;let t=rn(r,e),n=0;if(t.length>0)for(let r of t){let t=r.src,i=s[t]??0;n=Math.max(n,i+l(t,e))}let i=o(e),a=c.get(i)??0,u=Math.max(n,a);s[e]=u,c.set(i,u+1)}return{layers:un(r,i,s,{skipGroups:!0}),rankOf:s,dummy:new Set}}t(Hn,`assignLayers_LaneAwareCompact`);function Un(e,n){let r=nn(n),{rankOf:i}=e,a=e.layers.map(e=>[...e]),o=new Set(e.dummy?[...e.dummy]:[]),s=0,c=new Map(r.nodeById),l=t(e=>{let t=`placeholder-${s++}`,n={id:t,isGroup:!1,isDummy:!0,width:0,height:0};for(c.set(t,n),o.add(t);a.length<=e;)a.push([]);return a[e].push(t),i[t]=e,t},`addDummyAt`),u=[...r.edges].sort((e,t)=>e.id===t.id?e.src===t.src?e.dst.localeCompare(t.dst):e.src.localeCompare(t.src):e.id.localeCompare(t.id)),d=[];for(let e of u){let t=i[e.src]??0,n=i[e.dst]??0;if(n-t<=1){d.push(e);continue}let r=e.src;for(let i=t+1,a=0;i!r.nodes.includes(e))],edges:d,layout:r.layout,nodeById:c};return{layering:{layers:a,rankOf:i,dummy:o},graphWithDummies:f}}t(Un,`makeProperLayering`);function Wn(e){let t=e.length;if(t===0)return 1/0;let n=[...e].sort((e,t)=>e-t);return t%2==1?n[(t-1)/2]:.5*(n[t/2-1]+n[t/2])}t(Wn,`median`);function Gn(e){return e.length===0?1/0:e.reduce((e,t)=>e+t,0)/e.length}t(Gn,`barycenter`);function Kn(e,t,n,r){let i=new Map;for(let t of e)i.set(t,[]);for(let e of n)r===`down`?t.has(e.src)&&i.has(e.dst)&&i.get(e.dst).push(t.get(e.src)):t.has(e.dst)&&i.has(e.src)&&i.get(e.src).push(t.get(e.dst));return i}t(Kn,`neighborPositionsFor`);function qn(e,t,n){let r=n.get(e)??0,i=n.get(t)??0;return r===i?e.localeCompare(t):r-i}t(qn,`currentOrderTieBreak`);function Jn(e,t,n){let r=new Set(e),i=new Set(t),a=fn(e),o=fn(t),s=[];for(let e of n)r.has(e.src)&&i.has(e.dst)&&s.push({u:a.get(e.src),v:o.get(e.dst)});return s.sort((e,t)=>e.u===t.u?e.v-t.v:e.u-t.u),pn(s.map(e=>e.v))}t(Jn,`countCrossingsBetweenAdjacent`);function Yn(e,t,n){return[...e].sort((e,r)=>{let i=Wn(t.get(e)??[]),a=Wn(t.get(r)??[]);return i===a?qn(e,r,n):isFinite(i)?isFinite(a)?i-a:-1:1})}t(Yn,`sortByHeuristic`);function Xn(e,t,n,r,i,a){let o=fn(e),s=fn(t),c=Kn(t,o,n,r);if(!i||!a||a.length===0)return Yn(t,c,s);let l=new Map;for(let e of t){let t=i(e),n=l.get(t)??[];n.push(e),l.set(t,n)}let u=[];for(let e of a){let t=l.get(e);if(!t||t.length===0)continue;let n=Yn(t,c,s);u.push(...n)}let d=l.get(null);if(d&&d.length>0){let e=Yn(d,c,s);for(let t of e){let e=Gn(c.get(t)??[]),n=u.length;if(isFinite(e)){for(let[t,r]of u.entries())if(es.has(e.src)&&c.has(e.dst)),d=l?r.filter(e=>c.has(e.src)&&l.has(e.dst)):void 0,f=t(t=>{let n=Jn(e,t,u);return d&&i&&(n+=Jn(t,i,d)),n},`crossingScore`),p=a?new Map:null;if(a&&p)for(let e of n)p.set(e,a(e));let m=!0,h=f(o);for(;m;){m=!1;for(let e=0;e+1[...e]),i=t.edges,a=gn(t),o=vn(t,n?.laneOrder);for(let e=0;e<3;e++){for(let e=1;e=0;e--)r[e]=Xn(r[e+1],r[e],i,`up`,a,o),r[e]=Zn(r[e+1],r[e],i,r[e-1],a)}return{layers:r}}t(Qn,`orderLayers`);function $n(e,n,r){let i=r?.layerGap??xn.DEFAULT_LAYER_GAP,a=r?.nodeGap??xn.DEFAULT_NODE_GAP,o=r?.laneGap??a*2,s=r?.direction??`TB`,c=s===`LR`||s===`RL`,l=e.layers,u=Object.create(null),d=Object.create(null),f=t(e=>n.nodeById.get(e),`getNode`),p=t(e=>f(e)?.width??0,`getWidth`),m=t(e=>f(e)?.height??0,`getHeight`),h=gn(n),g=vn(n,r?.laneOrder),_=l.map(e=>e.reduce((e,t)=>Math.max(e,m(t)),0)),v=[];if(c)for(let e=0;e+1Math.max(e,p(t)),0),n=l[e+1].reduce((e,t)=>Math.max(e,p(t)),0),r=_[e],a=_[e+1],o=r/2+a/2,s=(t+n)/2,c=Math.max(0,s-o-i);v.push(c)}let y=new Set;for(let e of l)for(let t of e)y.add(h(t));let b=y.has(null),x=g.filter(e=>y.has(e)),S=[...b?[null]:[],...x],C=Object.create(null);for(let e of x)C[e]=0;b&&(C.null=0);for(let e of l){let t=Object.create(null),n=[];for(let r of e){let e=h(r);e===null?n.push(r):(t[e]||=[]).push(r)}for(let[e,n]of Object.entries(t)){let t=n.reduce((e,t)=>e+p(t),0)+a*Math.max(0,n.length-1);C[e]=Math.max(C[e]??0,t)}if(b&&n.length){let e=n.reduce((e,t)=>e+p(t),0)+a*Math.max(0,n.length-1);C.null=Math.max(C.null??0,e)}}let w=new Map;{let e=S.map(e=>(e===null?C.null:C[e])??0),t=-(e.reduce((e,t)=>e+t,0)+o*Math.max(0,S.length-1))/2;for(let n=0;np(e)),r=i-(e.reduce((e,t)=>e+t,0)+a*(t.length-1))/2;for(let[i,o]of t.entries()){let t=e[i];u[o]=r+t/2,d[o]=T+n/2,r+=t+a}}}let o=v[e]??0;T+=n+i+o}let E=new Map;for(let e of n.edges){let t=e.ref.id;E.has(t)||E.set(t,[]),E.get(t).push(e)}for(let[,e]of E){if(e.length===0)continue;let t=e[0].ref,r=t.start,i=t.end;if(r==null||i==null)continue;let a=Math.round(((u[r]??0)+(u[i]??0))/2),o=new Set;for(let t of e)o.add(t.src),o.add(t.dst);for(let e of o)e===r||e===i||n.nodeById.get(e)?.isDummy&&(u[e]=a)}return{x:u,y:d}}t($n,`assignCoordinates`);var er=8;function tr(e){let t=2166136261;for(let n=0;n>>0}t(tr,`hashString`);function nr(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}t(nr,`mulberry32`);function rr(e,t){let n=[...e],r=nr(t);for(let e=n.length-1;e>0;e--){let t=Math.floor(r()*(e+1));[n[e],n[t]]=[n[t],n[e]]}return n}t(rr,`deterministicShuffle`);function ir(e,t){let n=0;for(let[r,i]of e.entries())n+=Math.abs(r-(t.get(i)??r));return n}t(ir,`sourceDistance`);function ar(e,t){let n=new Map;for(let[t,r]of e.entries())n.set(r,t);let r=0;for(let{a:e,b:i,weight:a}of t){let t=n.get(e),o=n.get(i);t==null||o==null||(r+=a*Math.abs(t-o))}return r}t(ar,`laneArrangementCost`);function or(e){let t=_n(e);if(t.length<2)return[];let n=new Map(t.map((e,t)=>[e,t])),r=gn(e),i=new Map;for(let t of e.layout.edges??[]){if(t.isLayoutOnly)continue;let a=typeof t.start==`string`?t.start:void 0,o=typeof t.end==`string`?t.end:void 0;if(!a||!o||!e.nodeById.has(a)||!e.nodeById.has(o))continue;let s=r(a),c=r(o);if(!s||!c||s===c)continue;let l=n.get(s),u=n.get(c);if(l==null||u==null)continue;let[d,f]=l<=u?[s,c]:[c,s],p=`${d}\0${f}`,m=i.get(p);m?m.weight++:i.set(p,{a:d,b:f,weight:1})}return[...i.values()]}t(or,`buildWeightedLaneEdges`);function sr(e,t,n){let r=[...e],i=ar(r,t),a=!0,o=0,s=Math.max(1,r.length);for(;a&&oe.a===t.a?e.b.localeCompare(t.b):e.a.localeCompare(t.a)).map(({a:e,b:t,weight:n})=>`${e}:${t}:${n}`).join(`|`);return tr(`${e.join(`|`)}#${r}#${n}`)}t(lr,`seedForRestart`);function ur(e,t={}){let n=_n(e);if(n.length<2)return n;let r=or(e);if(r.length===0)return n;let i=new Map(n.map((e,t)=>[e,t])),a=sr(n,r,i),o=Math.max(0,t.restarts??er);for(let e=0;e$&&c*3>=s?o>0?`bottom`:`top`:s>$?a>0?`right`:`left`:n}t(vr,`chooseOrthogonalSide`);function yr(e,t){return Math.abs(e.to-t.from)<$||Math.abs(e.to-t.to)<$?e.to:e.from}t(yr,`sharedLineEndpointCoord`);function br(e,t){return e.orient===`vertical`?{x:e.coord,y:t}:{x:t,y:e.coord}}t(br,`pointOnLine`);function xr(e,n){let r=e.nodes??[],i=e.edges??[],a=[];for(let e of i)e.isLayoutOnly||a.push({...e,__originalEdge:e});let o=new Map,s=new Map,c=[],l=n===`LR`;for(let e of r)o.set(e.id,e);let u=r.filter(e=>e.isGroup&&!e.parentId);for(let e of u){let n={id:e.id},i=t(e=>{s.set(e.id,n),r.filter(t=>t.parentId===e.id).forEach(i)},`assignLane`);i(e)}let d=r.filter(e=>!e.isGroup&&!e.isEdgeLabel).map(e=>{let t=e.width??10,n=e.height??10,r=e.x??0,i=e.y??0,a=fr;return{nodeId:e.id,minX:r-t/2-a,maxX:r+t/2+a,minY:i-n/2-a,maxY:i+n/2+a,visualXHalfExtent:l?n/2+a:t/2+a}}),f=t((e,t,n,r)=>{let i=c.find(n=>n.orientation===e&&Math.abs(n.coord-t)<1);return i||(i={id:`pipe-${e}-${t.toFixed(0)}`,orientation:e,coord:t,spanMin:n,spanMax:r,tracks:[]},c.push(i)),i.spanMin=Math.min(i.spanMin,n),i.spanMax=Math.max(i.spanMax,r),i},`getOrAddPipe`),p=t((e,t)=>{let n=e.width??10,r=e.height??10,i=e.x??0,a=e.y??0;switch(t){case`top`:return{x:i,y:a-r/2};case`bottom`:return{x:i,y:a+r/2};case`left`:return{x:i-n/2,y:a};case`right`:return{x:i+n/2,y:a}}},`portForSide`),m=t((e,t,n)=>p(e,vr(e,t,n?`bottom`:`top`)),`getOrthogonalPort`),h=[],g=[],_=new Set,v=1e3,y=t((e,t,n)=>{if(h.length===0)return 0;let r=Math.abs(t.y-n.y)<$,i=Math.abs(t.x-n.x)<$;if(!r&&!i)return 0;let a=0;if(r){let r=t.y,i=Math.min(t.x,n.x)-$,o=Math.max(t.x,n.x)+$;if(o<=i)return 0;for(let t of h)t.edgeIndex===e||t.orientation!==`vertical`||t.pipe.coordo||t.from-$<=r&&t.to+$>=r&&(a+=v)}else if(i){let r=t.x,i=Math.min(t.y,n.y)-$,o=Math.max(t.y,n.y)+$;if(o<=i)return 0;for(let t of h)t.edgeIndex===e||t.orientation!==`horizontal`||t.pipe.coordo||t.from-$<=r&&t.to+$>=r&&(a+=v)}return a},`crossingPenalty`),b=a.map((e,t)=>{if(!e.start||!e.end)return{idx:t,crossLane:0,dx:0,dy:0};let n=o.get(e.start),r=o.get(e.end),i=s.get(e.start),a=s.get(e.end);return{idx:t,crossLane:i&&a&&i.id!==a.id?1:0,dx:n&&r?Math.abs((r.x??0)-(n.x??0)):0,dy:n&&r?Math.abs((r.y??0)-(n.y??0)):0}}).sort((e,t)=>{if(e.crossLane!==t.crossLane)return t.crossLane-e.crossLane;let n=e.dx+e.dy,r=t.dx+t.dy;return Math.abs(n-r)>1?n-r:e.idx-t.idx}).map(e=>e.idx),x=t((e,t,n,r)=>{let i=Math.min(e.x,t.x),a=Math.max(e.x,t.x),o=Math.min(e.y,t.y),s=Math.max(e.y,t.y);return!!d.find(c=>n&&c.nodeId===n||r&&c.nodeId===r?!1:Math.abs(e.x-t.x)>$?c.minYe.y&&c.maxX>i&&c.minXe.x&&c.maxY>o&&c.minYvr(e,t,`bottom`),`determineSide`),T=new Map;for(let[e,t]of a.entries()){if(!t.start||!t.end||t.start===t.end||t.points&&t.points.length>0)continue;let n=o.get(t.start),r=o.get(t.end);if(!n||!r)continue;let i=(r.x??0)-(n.x??0),a=(r.y??0)-(n.y??0);T.set(e,{edgeIdx:e,srcId:t.start,dstId:t.end,srcSide:w(n,{x:r.x??0,y:r.y??0}),dstSide:w(r,{x:n.x??0,y:n.y??0}),absDx:Math.abs(i),absDy:Math.abs(a),dxSign:Math.sign(i),dySign:Math.sign(a)})}let E=t(e=>e.srcSide===`top`||e.srcSide===`bottom`?e.absDx===0?1/0:e.absDy/e.absDx:e.absDy===0?1/0:e.absDx/e.absDy,`preferenceStrength`),D=t(e=>e.srcSide===`top`||e.srcSide===`bottom`?e.dxSign>=0?`right`:`left`:e.dySign>=0?`bottom`:`top`,`secondarySide`),O=new Map;for(let e of T.values()){let t=`${e.srcId}:${e.srcSide}`;O.has(t)||O.set(t,[]),O.get(t).push(e)}let k=new Map,A=t((e,t)=>`${e}:${t}`,`loadKey`);for(let e of T.values())k.set(A(e.srcId,e.srcSide),(k.get(A(e.srcId,e.srcSide))??0)+1),k.set(A(e.dstId,e.dstSide),(k.get(A(e.dstId,e.dstSide))??0)+1);for(let e of O.values())if(!(e.length<2)){e.sort((e,t)=>{let n=E(e),r=E(t);return Math.abs(n-r)>1e-9?r-n:e.edgeIdx-t.edgeIdx});for(let t=1;t=i||(k.set(A(n.srcId,n.srcSide),i-1),k.set(A(n.srcId,r),a+1),n.srcSide=r)}}let j=t(e=>{let t=e?.shape;return t===`question`||t===`diamond`},`isDiamondNode`),ee=new Map;for(let e of T.values())ee.has(e.dstId)||ee.set(e.dstId,new Set),ee.get(e.dstId).add(e.dstSide);for(let e of T.values()){if(!j(o.get(e.srcId)))continue;let t=ee.get(e.srcId);if(!t?.has(e.srcSide))continue;let n=D(e);if(t.has(n)||(k.get(A(e.srcId,n))??0)>0)continue;let r=k.get(A(e.srcId,e.srcSide))??0;k.set(A(e.srcId,e.srcSide),Math.max(0,r-1)),k.set(A(e.srcId,n),1),e.srcSide=n}for(let e of T.values()){let{edgeIdx:t,srcId:n,dstId:r,srcSide:i,dstSide:a}=e,s=o.get(n),c=o.get(r),l=`${n}:${i}:src`,u=i===`top`||i===`bottom`?c.x??0:c.y??0;S.has(l)||S.set(l,[]),S.get(l).push({edgeIdx:t,oppositeCoord:u});let d=`${r}:${a}:dst`,f=a===`top`||a===`bottom`?s.x??0:s.y??0;S.has(d)||S.set(d,[]),S.get(d).push({edgeIdx:t,oppositeCoord:f})}let te=new Map;for(let[e,t]of S){if(t.length<2)continue;t.sort((e,t)=>e.oppositeCoord-t.oppositeCoord);let n=e.split(`:`),r=n.slice(0,-2).join(`:`),i=n[n.length-2],a=n[n.length-1],s=o.get(r);if(!s)continue;let c=i===`left`||i===`right`?s.height??10:s.width??10,l=s.shape,u=l===`question`||l===`diamond`?c*.3:c,d=Math.min(20,Math.max(8,u/(t.length+1))),f=-(d*(t.length-1))/2;for(let[e,n]of t.entries()){let t=f+e*d,r=`${n.edgeIdx}:${a}`;te.set(r,t)}}let M=t(e=>!!a[e]?.labelNodeId,`edgeHasLabelNode`),ne=t((e,t)=>e?(S.get(`${e}:${t}:src`)??[]).some(({edgeIdx:e})=>M(e))||(S.get(`${e}:${t}:dst`)??[]).some(({edgeIdx:e})=>M(e)):!1,`faceHasLabelNode`),N=t((e,t,n)=>t===`top`||t===`bottom`?{x:e.x+n,y:e.y}:{x:e.x,y:e.y+n},`applyPortOffset`),re=t((e,t,n)=>{let r=T.get(e),i={x:n.x??0,y:n.y??0},a={x:t.x??0,y:t.y??0},o=r?.srcSide??w(t,i),s=r?.dstSide??w(n,a),c=r?p(t,r.srcSide):m(t,i,!0),l=r?p(n,r.dstSide):m(n,a,!1),u=te.get(`${e}:src`),d=te.get(`${e}:dst`);return u!==void 0&&(c=N(c,o,u)),d!==void 0&&(l=N(l,s,d)),{pSrcPort:c,pDstPort:l,srcSide:o,dstSide:s}},`portsForEdge`);for(let e of b){let n=a[e];if(g[e]=[],!n.start||!n.end||n.points&&n.points.length>0||n.start===n.end)continue;let r=o.get(n.start),i=o.get(n.end);if(!r||!i)continue;let{pSrcPort:s,pDstPort:u,srcSide:p,dstSide:m}=re(e,r,i),v={...s},b={...u},w=p===`top`||p===`bottom`,T=m===`top`||m===`bottom`;w?v.y=s.y>(r.y??0)?s.y+gr:s.y-gr:v.x=s.x>(r.x??0)?s.x+gr:s.x-gr,T?b.y=u.y>(i.y??0)?u.y+gr:u.y-gr:b.x=u.x>(i.x??0)?u.x+gr:u.x-gr;let E=t((e,t)=>{for(let n of d)if(!t.includes(n.nodeId)&&e.x>n.minX&&e.xn.minY&&e.y{if(i){let i=e.y>(t.y??0);return{x:(n.x??0)>=e.x?r.maxX+pr:r.minX-pr,y:i?r.maxY+mr:r.minY-mr,leavesPositiveSide:i}}let a=e.x>(t.x??0),o=(n.y??0)>=e.y;return{x:a?r.maxX+pr:r.minX-pr,y:o?r.maxY+mr:r.minY-mr,leavesPositiveSide:a}},`obstacleDetour`),O=[],k=[n.start,n.end],A=E(v,k);if(A.inside&&A.obstacle){let e=A.obstacle;if(w){let t=D(s,r,i,e,!0);v.x=t.x,v.y=t.y;let n=t.leavesPositiveSide?Math.min(e.minY-2,s.y+gr):Math.max(e.maxY+2,s.y-gr);O=[{x:s.x,y:n},{x:t.x,y:n},{x:t.x,y:t.y}]}else{let t=D(s,r,i,e,!1),n=t.leavesPositiveSide?Math.min(e.minX-2,s.x+gr):Math.max(e.maxX+2,s.x-gr);v.x=t.x,v.y=t.y,O=[{x:n,y:s.y},{x:n,y:t.y},{x:t.x,y:t.y}]}}let j=[],ee=E(b,k);if(ee.inside&&ee.obstacle){let e=ee.obstacle;if(T){let t=D(u,i,r,e,!0);b.x=t.x,b.y=t.y,j=[{x:t.x,y:t.y},{x:u.x,y:t.y}]}else{let t=D(u,i,r,e,!1);b.x=t.x,b.y=t.y,j=[{x:t.x,y:t.y},{x:t.x,y:u.y}]}}if(O.length===0&&j.length===0){let t=pr,r=Math.abs(v.x-b.x)1||c>1,d=C.get(n.start??``)??0,f=C.get(n.end??``)??0,g=o>1&&ne(n.start,p)||c>1&&ne(n.end,m);if((r||i)&&!a&&(!l||l&&!g&&(o<=1||d<=2)&&(c<=1||f<=2))&&!x(s,u,n.start,n.end)){n.points=[{...s},{...v},{...b},{...u}],_.add(e);let t=i?`horizontal`:`vertical`,r=i?s.y:s.x,a=i?Math.min(s.x,u.x):Math.min(s.y,u.y),o=i?Math.max(s.x,u.x):Math.max(s.y,u.y),c={id:`fast-path-${t}-${r.toFixed(0)}-${e}`,orientation:t,coord:r,spanMin:a,spanMax:o,tracks:[]};h.push({edgeIndex:e,segmentIndex:0,orientation:t,pipe:c,trackIndex:0,from:a,to:o});continue}}v.x=f(`vertical`,v.x,v.y,v.y).coord,b.x=f(`vertical`,b.x,b.y,b.y).coord;let M=Math.min(v.x,b.x)-50,N=Math.max(v.x,b.x)+50,P=Math.min(v.y,b.y)-50,ie=Math.max(v.y,b.y)+50;for(let e of d){let t=Math.min(v.x,b.x),n=Math.max(v.x,b.x),r=Math.min(v.y,b.y),i=Math.max(v.y,b.y);e.minXt&&e.minYr&&(M=Math.min(M,e.minX-hr),N=Math.max(N,e.maxX+hr),P=Math.min(P,e.minY-hr),ie=Math.max(ie,e.maxY+hr))}for(let e of d){if(e.maxXN||e.maxYie)continue;let t=pr;f(`horizontal`,e.minY-t,M,N),f(`horizontal`,e.maxY+t,M,N);let n=mr;f(`vertical`,e.minX-n,P,ie),f(`vertical`,e.maxX+n,P,ie)}f(`horizontal`,v.y,M,N),f(`horizontal`,b.y,M,N);let ae=c.filter(e=>e.orientation===`horizontal`&&e.coord>=P&&e.coord<=ie),oe=c.filter(e=>e.orientation===`vertical`&&e.coord>=M&&e.coord<=N),se=t((e,t)=>`${e.toFixed(1)},${t.toFixed(1)}`,`getKey`),ce=se(v.x,v.y),le=se(b.x,b.y),ue=new Map,de=new Map,fe=new Map,pe=new Set,F=[];ue.set(ce,0),fe.set(ce,`n`),F.push({key:ce,f:Math.hypot(b.x-v.x,b.y-v.y),pt:v}),pe.add(ce);let I=[],me=t((e,t)=>x(e,t,n.start,n.end),`checkSegmentBlocked`),he={x:b.x,y:v.y},L=me(v,he),ge=me(he,b),_e=L||ge,R={x:v.x,y:b.y},z=me(v,R),B=me(R,b);if(_e?z||B||(I=Math.abs(v.x-b.x)<$?[v,b]:[v,R,b]):I=Math.abs(v.y-b.y)<$||Math.abs(v.x-b.x)<$?[v,b]:[v,he,b],I.length===0)for(;F.length>0;){F.sort((e,t)=>e.f-t.f);let t=F.shift();if(pe.delete(t.key),t.key===le){let e=le,t=b;for(I=[t];de.has(e);){let n=de.get(e);I.unshift(n),t=n,e=se(n.x,n.y)}break}let r=t.pt.x,i=t.pt.y,a=oe.sort((e,t)=>e.coord-t.coord),o=a.findIndex(e=>Math.abs(e.coord-r)<1),s=ae.sort((e,t)=>e.coord-t.coord),c=s.findIndex(e=>Math.abs(e.coord-i)<1),l=[];o>0&&l.push({x:a[o-1].coord,y:i}),o>=0&&o0&&l.push({x:r,y:s[c-1].coord}),c>=0&&ce.nodeId===n.start||e.nodeId===n.end?!1:o===s?e.minXr&&e.maxY>c&&e.minYi&&e.maxX>o&&e.minX10&&x<-5||g<-10&&x>5)&&(m=Math.abs(x)*100),(h>10&&_<-5||h<-10&&_>5)&&(m+=Math.abs(_)*50);let S=0,C=fe.get(t.key)??`n`,w=Math.abs(_)>$?`h`:`v`;C!==`n`&&C!==w&&(S=50);let T=f+p+m+S,E=(ue.get(t.key)??1/0)+T,D=Math.abs(b.x-a.x)+Math.abs(b.y-a.y);if(E<(ue.get(u)??1/0))if(de.set(u,t.pt),ue.set(u,E),fe.set(u,w),!pe.has(u))F.push({key:u,f:E+D,pt:a}),pe.add(u);else{let e=F.findIndex(e=>e.key===u);e!==-1&&(F[e].f=E+D)}}}if(I.length===0&&(I=[v,{x:v.x,y:b.y},b]),I.length>4){let e=I[0],n=I[I.length-1],r=Math.min(e.x,n.x),i=Math.max(e.x,n.x),a=Math.min(e.y,n.y),o=Math.max(e.y,n.y);for(let e of I)r=Math.min(r,e.x),i=Math.max(i,e.x),a=Math.min(a,e.y),o=Math.max(o,e.y);let s=i>Math.max(e.x,n.x),c=re.minXr&&e.minYa);if(s.length>0){let r=Math.max(e.x,n.x);for(let e of s){let n=(e.minX+e.maxX)/2;if(e.visualXHalfExtent===void 0||isNaN(e.visualXHalfExtent))continue;let i=n+e.visualXHalfExtent+t;r=Math.max(r,i)}isNaN(r)||(i=r)}}if(c){let i=d.filter(r=>r.minXMath.min(e.y,n.y));if(i.length>0){let a=Math.min(e.x,n.x);for(let e of i){let n=(e.minX+e.maxX)/2-e.visualXHalfExtent-t;a=Math.min(a,n)}r=a}}}let u=t(t=>{let r=n.y>e.y,i=d.filter(t=>{let r=Math.min(e.x,n.x)t.minX,i=Math.min(e.y,n.y)t.minY;return r&&i}),a=i;if(l&&i.length>0){let e=i.filter(e=>e.minXt);e.length>0&&(a=e)}if(a.length===0)return n.y;let o=pr;if(r){let e=Math.max(...a.map(e=>e.maxY))+o;if(ee.minY))-o;if(e>n.y+$)return e}return n.y},`findBestReturnY`),f=t(t=>{let r=u(t),i={x:t,y:e.y},a={x:t,y:r},o={x:n.x,y:r},s=me(e,i),c=me(i,a),l=me(a,o),d=r!==n.y&&me(o,n);return!s&&!c&&!l&&!d?Math.abs(r-n.y)<$?[e,i,a,n]:[e,i,a,o,n]:null},`trySimplifyWithDetourX`),p=s&&!c?f(i):c&&!s?f(r):null;p&&(I=p)}let V=[s,...O,...I,...j.reverse(),u];if(V.length>=3){let e=V[V.length-1],t=V[V.length-2],n=V[V.length-3],r=Math.abs(n.y-t.y)<$&&Math.abs(t.y-e.y)<$,i=Math.abs(n.x-t.x)<$&&Math.abs(t.x-e.x)<$;if(r){let r=Math.sign(t.x-n.x),i=Math.sign(e.x-n.x);r!==0&&r===i&&Math.abs(t.x-n.x)>Math.abs(e.x-n.x)&&V.splice(-2,1)}else if(i){let r=Math.sign(t.y-n.y),i=Math.sign(e.y-n.y);r!==0&&r===i&&Math.abs(t.y-n.y)>Math.abs(e.y-n.y)&&V.splice(-2,1)}}let H=[V[0]];for(let e=1;et.x!=r.x>n.x){H.push(n);continue}continue}if(Math.abs(t.x-n.x)<$&&Math.abs(n.x-r.x)<$){if(n.y>t.y!=r.y>n.y){H.push(n);continue}continue}H.push(n)}H.push(V[V.length-1]);for(let t=0;te.from{let i=!r.segments.some(n=>(n.edgeIndex!==t.edgeIndex||n.segmentIndex!==t.segmentIndex)&&P(n,e)),a=!n.segments.some(n=>(n.edgeIndex!==e.edgeIndex||n.segmentIndex!==e.segmentIndex)&&P(n,t));return i&&a?(e.trackIndex=r.index,t.trackIndex=n.index,n.segments=[...n.segments.filter(t=>t.edgeIndex!==e.edgeIndex||t.segmentIndex!==e.segmentIndex),{edgeIndex:t.edgeIndex,segmentIndex:t.segmentIndex,from:t.from,to:t.to}],r.segments=[...r.segments.filter(e=>e.edgeIndex!==t.edgeIndex||e.segmentIndex!==t.segmentIndex),{edgeIndex:e.edgeIndex,segmentIndex:e.segmentIndex,from:e.from,to:e.to}],!0):!1},`trySwapSegmentsAcrossTracks`),ae=t(e=>{let t=e.tracks.length;return e.tracks[t]={index:t,coord:e.coord,segments:[]},t},`createNewTrack`),oe=t((e,t)=>{let n=e.pipe.tracks[e.trackIndex];n.segments=n.segments.filter(t=>t.edgeIndex!==e.edgeIndex||t.segmentIndex!==e.segmentIndex),e.trackIndex=t,e.pipe.tracks[t].segments.push({edgeIndex:e.edgeIndex,segmentIndex:e.segmentIndex,from:e.from,to:e.to})},`moveSegmentToTrack`),se=t((e,t)=>{let n=g[e.edgeIndex];for(let r of n){let n=h[r];n.pipe===e.pipe&&oe(n,t)}},`moveSegmentChainToTrack`),ce=t(e=>{let t=g[e.edgeIndex],n=t.indexOf(h.indexOf(e)),r=[];return n>0&&r.push(h[t[n-1]]),n{if(e.orientation===t.orientation)return!1;let n=e.orientation===`horizontal`?e:t,r=e.orientation===`horizontal`?t:e;return r.pipe.coord>n.from&&r.pipe.coordr.from&&n.pipe.coord{for(let n of e.tracks)if(!n.segments.some(e=>(e.edgeIndex!==t.edgeIndex||e.segmentIndex!==t.segmentIndex)&&P(e,t)))return n.index;return-1},`findAvailableTrack`),de=t((e,t)=>{if(e.trackIndex===t.trackIndex)return P(e,t);let n=ce(e),r=ce(t);return n.some(e=>r.some(t=>le(e,t)))},`segmentsConflict`),fe=t((e,t,n)=>{if(ie(e,t,e.pipe.tracks[e.trackIndex],t.pipe.tracks[t.trackIndex]))return;let r=ue(e.pipe,t);n(t,r===-1?ae(e.pipe):r)},`resolveTrackConflict`),pe=t(e=>{let t=0;for(let n=0;n{if(F.has(e))return F.get(e);let t=g[e];if(t.length===0){let t={dest:0,deviation:0,base:0,delta:0};return F.set(e,t),t}let n=h[t[0]].pipe.coord,r=n;for(let e=1;eMath.abs(t-n)?e:t;break}}let i=Math.abs(r-n),a={dest:r,deviation:i,base:n,delta:r-n};return F.set(e,a),a},`getDestInfo`),me=t(()=>{let e=0,n=new Map;for(let[e,t]of a.entries())g[e].length!==0&&t.start&&(n.has(t.start)||n.set(t.start,[]),n.get(t.start).push(e));let r=t(e=>{let t=a[e];if(!t.start||!t.end)return 0;let n=o.get(t.start),r=o.get(t.end);if(!n||!r)return 0;let i=(r.x??0)-(n.x??0),s=(r.y??0)-(n.y??0);return Math.abs(i)+Math.abs(s)},`getEdgeDistance`);for(let t of n.values()){t.sort((e,t)=>{let n=I(e),i=I(t);if(Math.abs(n.deviation-i.deviation)>1)return n.deviation-i.deviation;if(Math.abs(n.dest-i.dest)>1)return n.dest-i.dest;let a=r(e),o=r(t);if(Math.abs(a-o)>1)return o-a;let s=g[e].length,c=g[t].length;if(s!==c)return s-c;if(s===1){let n=g[e][0],r=g[t][0];if(h[n]&&h[r]){let e=h[n],t=h[r],i=Math.abs(e.to-e.from),a=Math.abs(t.to-t.from);if(Math.abs(i-a)>1)return i-a}}return 0});let n=t.map(e=>h[g[e][0]]);e+=pe(n)}return e},`fixSourceHandleCrossings`),he=t(()=>{let e=0,n=new Map;for(let[e,t]of a.entries())g[e].length!==0&&t.end&&(n.has(t.end)||n.set(t.end,[]),n.get(t.end).push(e));for(let r of n.values()){r.sort((e,n)=>{let r=t(e=>{let t=g[e];if(t.length<2)return 0;let n=h[t[t.length-2]];return Math.abs(n.to-n.from)},`getDist`),i=r(e),a=r(n);return Math.abs(i-a)>.1?i-a:e-n});let n=r.map(e=>h[g[e][g[e].length-1]]);e+=pe(n)}return e},`fixTargetHandleCrossings`),L=t(()=>{let e=0;for(let t of c){let n=[];for(let e of t.tracks)for(let t of e.segments){let e=g[t.edgeIndex].find(e=>h[e].segmentIndex===t.segmentIndex);e!==void 0&&n.push(h[e])}n.sort((e,t)=>e.edgeIndex-t.edgeIndex||e.segmentIndex-t.segmentIndex);for(let t=0;t{e.segments.forEach(t=>{n.push({edgeIndex:t.edgeIndex,segmentIndex:t.segmentIndex,trackIndex:e.index,from:t.from,to:t.to})})}),n.sort((e,t)=>e.from-t.from);let r=[];if(n.length>0){let e=[n[0]],t=n[0].to;for(let i=1;ir.add(e.trackIndex));let i=new Map;n.forEach(e=>{let t=I(e.edgeIndex);i.set(e.trackIndex,(i.get(e.trackIndex)??0)+t.delta)});let a=[...r].filter(e=>(i.get(e)??0)<-1),o=[...r].filter(e=>(i.get(e)??0)>1),s=[...r].filter(e=>Math.abs(i.get(e)??0)<=1);a.sort((e,t)=>(i.get(t)??0)-(i.get(e)??0)),o.sort((e,t)=>(i.get(e)??0)-(i.get(t)??0));let c=t((t,r)=>{n.filter(e=>e.trackIndex===t).forEach(t=>{let n=_.has(t.edgeIndex)?e.coord:r;_e.set(`${t.edgeIndex}-${t.segmentIndex}`,n)})},`assignCoord`),l=0;for(let t of a)l++,c(t,e.coord-l*_r);if(s.length===0&&r.size>0){let e=[...r].sort((e,t)=>Math.abs(i.get(e)??0)-Math.abs(i.get(t)??0))[0],t=a.indexOf(e);t!==-1&&a.splice(t,1);let n=o.indexOf(e);n!==-1&&o.splice(n,1),s.push(e)}let u=0;for(let t of s){if(u===0)c(t,e.coord);else{let n=u%2==1?1:-1,r=Math.ceil(u/2);c(t,e.coord+n*r*_r*.5)}u++}let d=0;for(let t of o)d++,c(t,e.coord+d*_r)}}for(let[e,t]of a.entries()){let n=g[e]??[];if(n.length===0)continue;let r=[],{pSrcPort:i,pDstPort:a}=re(e,o.get(t.start),o.get(t.end)),s=n.map(e=>{let t=h[e],n=_e.get(`${t.edgeIndex}-${t.segmentIndex}`)??t.pipe.coord;return{orient:t.orientation,coord:n,from:t.from,to:t.to}});r.push(i);for(let e=0;e$&&r.push(br(t,i)),c&&o.orient===t.orient)if(Math.abs(t.coord-o.coord)>$){let e=t.orient===`vertical`?(i+o.from)/2:yr(t,o);r.push(br(t,e),br(o,e))}else(e===0||e===s.length-2)&&r.push(br(t,yr(t,o)));else if(c)r.push(br(t,o.coord));else{let e=Math.abs(t.from-i)$||Math.abs(c.y-a.y)>$)&&r.push(a);let l=[];r.length>0&&l.push(r[0]);for(let e=1;e$||Math.abs(t.y-n.y)>$)&&l.push(t)}t.points=l}for(let e of a){let t=e.__originalEdge;t&&e.points&&(t.points=e.points)}e.edges=(e.edges??[]).filter(e=>!e.isLayoutOnly);let R=t((e,t)=>{let n=t.x??0,r=t.y??0,i=t.width??0,a=t.height??0;if(i<=0||a<=0)return e;let o=n-i/2,s=n+i/2,c=r-a/2,l=r+a/2;if(e.xs||e.yl)return e;let u=e.x-o,d=s-e.x,f=e.y-c,p=l-e.y,m=Math.min(u,d,f,p);return m===u?{x:o,y:e.y}:m===d?{x:s,y:e.y}:m===f?{x:e.x,y:c}:{x:e.x,y:l}},`nodeBoundaryClamp`);for(let t of e.edges){let e=t.points;if(!e||e.length<2)continue;let n=t.start,r=t.end,i=n?o.get(n):void 0,a=r?o.get(r):void 0;i&&(e[0]=R(e[0],i)),a&&(e[e.length-1]=R(e[e.length-1],a))}return e}t(xr,`routeEdgesOrthogonal`);function Sr(e){return e.direction??`TB`}t(Sr,`getSwimlaneDirection`);function Cr(e){let t=F(e),n=e.config.flowchart?.nodeSpacing??40,r=e.config.flowchart?.rankSpacing??100,i=e.config.swimlane?.ignoreCrossLaneEdges??!0,a=e.config.swimlane?.optimizeRanksByCrossings??!0,o=e.config.swimlane?.automaticLaneOrdering??!1,s=Sr(e),{ordered:c,coordinates:l}=dr(t,{nodeGap:n,layerGap:r,ignoreCrossLaneEdges:i,optimizeRanksByCrossings:a,automaticLaneOrdering:o,direction:s});I(t,c,l,{nodeGap:n,layerGap:r});for(let t of e.edges??[])delete t.points;xr(e,s);for(let t of e.edges??[])(!t.curve||t.curve===`basis`)&&(t.curve=`rounded`);return tn(e,s),en(e),s}t(Cr,`runSwimlaneLayoutCore`);async function wr(e,t){let n=t.select(`g`);h(n,e.markers,e.type,e.diagramId),p(),b(),m(),l(),pe(e);let r=he(e);e.nodes=r.nodes,e.edges=r.edges;let{groups:i}=await x(n,e);Cr(e),await oe(e,i)}t(wr,`render`);export{wr as render}; \ No newline at end of file diff --git a/.vercel/output/static/assets/swimlanesDiagram-G3AALYLV-BaT0JTBD.js b/.vercel/output/static/assets/swimlanesDiagram-G3AALYLV-BaT0JTBD.js deleted file mode 100644 index f0d76ab..0000000 --- a/.vercel/output/static/assets/swimlanesDiagram-G3AALYLV-BaT0JTBD.js +++ /dev/null @@ -1,8 +0,0 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-_wZywoZs.js";import"./chunk-WYO6CB5R-ajGU-pWR.js";import"./chunk-ICXQ74PX-fa5hHXws.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import"./chunk-Q4XR5HBZ-5srkZ5CC.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-Dr-qyYzn.js";import"./chunk-32BRIVSS-BtH22FN8.js";import"./chunk-XXDRQBXY-BuE3VzE_.js";import"./chunk-VR4S4FIN-BJzXasDJ.js";import"./chunk-C7G6YPKG-DJfjwbsZ.js";import"./chunk-ZGVPDNZ5-zo3h_nOA.js";import"./chunk-52WLFC77-BBAyrLn9.js";import"./chunk-FWX5IMBZ-CiLc9_ts.js";import"./chunk-ZIRB5QZD-C6fEPe3t.js";import{r as t,t as n}from"./chunk-PUDLZKDR-C4aS5M-Y.js";var r=n({defaultLayout:`swimlane`,styles:e(e=>`${t(e)} - .swimlane.cluster rect { - stroke: ${e.clusterBorder} !important; - } - [data-look="neo"].cluster rect { - filter: none; - } -`,`getStyles`)});export{r as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/swimlanesDiagram-G3AALYLV-CGWZF_2o.js b/.vercel/output/static/assets/swimlanesDiagram-G3AALYLV-CGWZF_2o.js new file mode 100644 index 0000000..6e69ac7 --- /dev/null +++ b/.vercel/output/static/assets/swimlanesDiagram-G3AALYLV-CGWZF_2o.js @@ -0,0 +1,8 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import"./chunk-ZIRB5QZD-C6fEPe3t.js";import{r as t,t as n}from"./chunk-PUDLZKDR-hlw4TonS.js";var r=n({defaultLayout:`swimlane`,styles:e(e=>`${t(e)} + .swimlane.cluster rect { + stroke: ${e.clusterBorder} !important; + } + [data-look="neo"].cluster rect { + filter: none; + } +`,`getStyles`)});export{r as diagram}; \ No newline at end of file diff --git a/.vercel/output/static/assets/timeline-definition-FHXFAJF6-B3seWFFu.js b/.vercel/output/static/assets/timeline-definition-FHXFAJF6-DFMIv6oI.js similarity index 99% rename from .vercel/output/static/assets/timeline-definition-FHXFAJF6-B3seWFFu.js rename to .vercel/output/static/assets/timeline-definition-FHXFAJF6-DFMIv6oI.js index d1f4f1a..45f929e 100644 --- a/.vercel/output/static/assets/timeline-definition-FHXFAJF6-B3seWFFu.js +++ b/.vercel/output/static/assets/timeline-definition-FHXFAJF6-DFMIv6oI.js @@ -1,4 +1,4 @@ -import{n as e,t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n,p as r}from"./src-_wZywoZs.js";import{J as i,a,b as o,et as s,o as c,rt as l,tt as u,x as d}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as f}from"./arc-BjSQqbzd.js";import{p}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as m}from"./chunk-VAUOI2AC-CLN1Ga8_.js";var h=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[6,11,13,14,15,17,19,20,23,24],r=[1,12],i=[1,13],a=[1,14],o=[1,15],s=[1,16],c=[1,19],l=[1,20],u={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,timeline_header:4,document:5,EOF:6,timeline:7,timeline_lr:8,timeline_td:9,line:10,SPACE:11,statement:12,NEWLINE:13,title:14,acc_title:15,acc_title_value:16,acc_descr:17,acc_descr_value:18,acc_descr_multiline_value:19,section:20,period_statement:21,event_statement:22,period:23,event:24,$accept:0,$end:1},terminals_:{2:`error`,6:`EOF`,7:`timeline`,8:`timeline_lr`,9:`timeline_td`,11:`SPACE`,13:`NEWLINE`,14:`title`,15:`acc_title`,16:`acc_title_value`,17:`acc_descr`,18:`acc_descr_value`,19:`acc_descr_multiline_value`,20:`section`,23:`period`,24:`event`},productions_:[0,[3,3],[4,1],[4,1],[4,1],[5,0],[5,2],[10,2],[10,1],[10,1],[10,1],[12,1],[12,2],[12,2],[12,1],[12,1],[12,1],[12,1],[21,1],[22,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 3:r.setDirection(`LR`);break;case 4:r.setDirection(`TD`);break;case 5:this.$=[];break;case 6:a[s-1].push(a[s]),this.$=a[s-1];break;case 7:case 8:this.$=a[s];break;case 9:case 10:this.$=[];break;case 11:r.getCommonDb().setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 12:this.$=a[s].trim(),r.getCommonDb().setAccTitle(this.$);break;case 13:case 14:this.$=a[s].trim(),r.getCommonDb().setAccDescription(this.$);break;case 15:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 18:r.addTask(a[s],0,``),this.$=a[s];break;case 19:r.addEvent(a[s].substr(2)),this.$=a[s];break}},`anonymous`),table:[{3:1,4:2,7:[1,3],8:[1,4],9:[1,5]},{1:[3]},t(n,[2,5],{5:6}),t(n,[2,2]),t(n,[2,3]),t(n,[2,4]),{6:[1,7],10:8,11:[1,9],12:10,13:[1,11],14:r,15:i,17:a,19:o,20:s,21:17,22:18,23:c,24:l},t(n,[2,10],{1:[2,1]}),t(n,[2,6]),{12:21,14:r,15:i,17:a,19:o,20:s,21:17,22:18,23:c,24:l},t(n,[2,8]),t(n,[2,9]),t(n,[2,11]),{16:[1,22]},{18:[1,23]},t(n,[2,14]),t(n,[2,15]),t(n,[2,16]),t(n,[2,17]),t(n,[2,18]),t(n,[2,19]),t(n,[2,7]),t(n,[2,12]),t(n,[2,13])],defaultActions:{},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e,t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n,p as r}from"./src-UMNXGZaF.js";import{J as i,a,b as o,et as s,o as c,rt as l,tt as u,x as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as f}from"./arc-DqK6O3qL.js";import{p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-VAUOI2AC-AC9pRUsa.js";var h=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[6,11,13,14,15,17,19,20,23,24],r=[1,12],i=[1,13],a=[1,14],o=[1,15],s=[1,16],c=[1,19],l=[1,20],u={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,timeline_header:4,document:5,EOF:6,timeline:7,timeline_lr:8,timeline_td:9,line:10,SPACE:11,statement:12,NEWLINE:13,title:14,acc_title:15,acc_title_value:16,acc_descr:17,acc_descr_value:18,acc_descr_multiline_value:19,section:20,period_statement:21,event_statement:22,period:23,event:24,$accept:0,$end:1},terminals_:{2:`error`,6:`EOF`,7:`timeline`,8:`timeline_lr`,9:`timeline_td`,11:`SPACE`,13:`NEWLINE`,14:`title`,15:`acc_title`,16:`acc_title_value`,17:`acc_descr`,18:`acc_descr_value`,19:`acc_descr_multiline_value`,20:`section`,23:`period`,24:`event`},productions_:[0,[3,3],[4,1],[4,1],[4,1],[5,0],[5,2],[10,2],[10,1],[10,1],[10,1],[12,1],[12,2],[12,2],[12,1],[12,1],[12,1],[12,1],[21,1],[22,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 3:r.setDirection(`LR`);break;case 4:r.setDirection(`TD`);break;case 5:this.$=[];break;case 6:a[s-1].push(a[s]),this.$=a[s-1];break;case 7:case 8:this.$=a[s];break;case 9:case 10:this.$=[];break;case 11:r.getCommonDb().setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 12:this.$=a[s].trim(),r.getCommonDb().setAccTitle(this.$);break;case 13:case 14:this.$=a[s].trim(),r.getCommonDb().setAccDescription(this.$);break;case 15:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 18:r.addTask(a[s],0,``),this.$=a[s];break;case 19:r.addEvent(a[s].substr(2)),this.$=a[s];break}},`anonymous`),table:[{3:1,4:2,7:[1,3],8:[1,4],9:[1,5]},{1:[3]},t(n,[2,5],{5:6}),t(n,[2,2]),t(n,[2,3]),t(n,[2,4]),{6:[1,7],10:8,11:[1,9],12:10,13:[1,11],14:r,15:i,17:a,19:o,20:s,21:17,22:18,23:c,24:l},t(n,[2,10],{1:[2,1]}),t(n,[2,6]),{12:21,14:r,15:i,17:a,19:o,20:s,21:17,22:18,23:c,24:l},t(n,[2,8]),t(n,[2,9]),t(n,[2,11]),{16:[1,22]},{18:[1,23]},t(n,[2,14]),t(n,[2,15]),t(n,[2,16]),t(n,[2,17]),t(n,[2,18]),t(n,[2,19]),t(n,[2,7]),t(n,[2,12]),t(n,[2,13])],defaultActions:{},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};u.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.vercel/output/static/assets/use-current-user-BkYwj4ZJ.js b/.vercel/output/static/assets/use-current-user-BkYwj4ZJ.js deleted file mode 100644 index f5e0090..0000000 --- a/.vercel/output/static/assets/use-current-user-BkYwj4ZJ.js +++ /dev/null @@ -1 +0,0 @@ -import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{t}from"./react-Biaal4sZ.js";import{s as n}from"./link-DYUXAN0T.js";import{t as r}from"./client-8boibB1R.js";var i=e(t(),1),a=n();function o(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`)if(Array.isArray(e)){var i=e.length;for(t=0;t{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),u=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),d=`-`,f=[],p=`arbitrary..`,m=e=>{let t=_(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return g(e);let n=e.split(d);return h(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?c(i,t):t:i||f}return n[e]||f}}},h=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=h(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(d):e.slice(t).join(d),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?p+r:void 0})(),_=e=>{let{theme:t,classGroups:n}=e;return ee(n,t)},ee=(e,t)=>{let n=u();for(let r in e){let i=e[r];v(i,n,r,t)}return n},v=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){te(e,t,n);return}if(typeof e==`function`){ne(e,t,n,r);return}re(e,t,n,r)},te=(e,t,n)=>{let r=e===``?t:b(t,e);r.classGroupId=n},ne=(e,t,n,r)=>{if(x(e)){v(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(l(n,e))},re=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(d),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,ie=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},S=`!`,C=`:`,ae=[],w=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),T=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return w(t,l,c,u)};if(t){let e=t+C,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):w(ae,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},E=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},D=e=>({cache:ie(e.cacheSize),parseClassName:T(e),sortModifiers:E(e),postfixLookupClassGroupIds:O(e),...m(e)}),O=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(k),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),ee=f?_+S:_,v=ee+g;if(s.indexOf(v)>-1)continue;s.push(v);let y=i(g,h);for(let e=0;e0?` `+l:l)}return l},oe=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=D(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=A(e,n);return i(e,a),a};return a=o,(...e)=>a(oe(...e))},M=[],N=e=>{let t=t=>t[e]||M;return t.isThemeGetter=!0,t},P=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,F=/^\((?:(\w[\w-]*):)?(.+)\)$/i,I=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,ce=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,L=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,le=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,R=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,z=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,B=e=>I.test(e),V=e=>!!e&&!Number.isNaN(Number(e)),H=e=>!!e&&Number.isInteger(Number(e)),ue=e=>e.endsWith(`%`)&&V(e.slice(0,-1)),U=e=>ce.test(e),de=()=>!0,W=e=>L.test(e)&&!le.test(e),G=()=>!1,fe=e=>R.test(e),pe=e=>z.test(e),me=e=>!K(e)&&!Y(e),he=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),ge=e=>Z(e,Ae,G),K=e=>P.test(e),q=e=>Z(e,je,W),_e=e=>Z(e,Me,V),ve=e=>Z(e,Pe,de),ye=e=>Z(e,Ne,G),be=e=>Z(e,Oe,G),xe=e=>Z(e,ke,pe),J=e=>Z(e,Fe,fe),Y=e=>F.test(e),X=e=>Q(e,je),Se=e=>Q(e,Ne),Ce=e=>Q(e,Oe),we=e=>Q(e,Ae),Te=e=>Q(e,ke),Ee=e=>Q(e,Fe,!0),De=e=>Q(e,Pe,!0),Z=(e,t,n)=>{let r=P.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Q=(e,t,n=!1)=>{let r=F.exec(e);return r?r[1]?t(r[1]):n:!1},Oe=e=>e===`position`||e===`percentage`,ke=e=>e===`image`||e===`url`,Ae=e=>e===`length`||e===`size`||e===`bg-size`,je=e=>e===`length`,Me=e=>e===`number`,Ne=e=>e===`family-name`,Pe=e=>e===`number`||e===`weight`,Fe=e=>e===`shadow`,Ie=se(()=>{let e=N(`color`),t=N(`font`),n=N(`text`),r=N(`font-weight`),i=N(`tracking`),a=N(`leading`),o=N(`breakpoint`),s=N(`container`),c=N(`spacing`),l=N(`radius`),u=N(`shadow`),d=N(`inset-shadow`),f=N(`text-shadow`),p=N(`drop-shadow`),m=N(`blur`),h=N(`perspective`),g=N(`aspect`),_=N(`ease`),ee=N(`animate`),v=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],y=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],te=()=>[...y(),Y,K],ne=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],re=()=>[`auto`,`contain`,`none`],b=()=>[Y,K,c],x=()=>[B,`full`,`auto`,...b()],ie=()=>[H,`none`,`subgrid`,Y,K],S=()=>[`auto`,{span:[`full`,H,Y,K]},H,Y,K],C=()=>[H,`auto`,Y,K],ae=()=>[`auto`,`min`,`max`,`fr`,Y,K],w=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],T=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],E=()=>[`auto`,...b()],D=()=>[B,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...b()],O=()=>[B,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...b()],k=()=>[B,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...b()],A=()=>[e,Y,K],oe=()=>[...y(),Ce,be,{position:[Y,K]}],j=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],se=()=>[`auto`,`cover`,`contain`,we,ge,{size:[Y,K]}],M=()=>[ue,X,q],P=()=>[``,`none`,`full`,l,Y,K],F=()=>[``,V,X,q],I=()=>[`solid`,`dashed`,`dotted`,`double`],ce=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],L=()=>[V,ue,Ce,be],le=()=>[``,`none`,m,Y,K],R=()=>[`none`,V,Y,K],z=()=>[`none`,V,Y,K],W=()=>[V,Y,K],G=()=>[B,`full`,...b()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[U],breakpoint:[U],color:[de],container:[U],"drop-shadow":[U],ease:[`in`,`out`,`in-out`],font:[me],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[U],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[U],shadow:[U],spacing:[`px`,V],text:[U],"text-shadow":[U],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,B,K,Y,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,Y,K]}],"container-named":[he],columns:[{columns:[V,K,Y,s]}],"break-after":[{"break-after":v()}],"break-before":[{"break-before":v()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:te()}],overflow:[{overflow:ne()}],"overflow-x":[{"overflow-x":ne()}],"overflow-y":[{"overflow-y":ne()}],overscroll:[{overscroll:re()}],"overscroll-x":[{"overscroll-x":re()}],"overscroll-y":[{"overscroll-y":re()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:x()}],"inset-x":[{"inset-x":x()}],"inset-y":[{"inset-y":x()}],start:[{"inset-s":x(),start:x()}],end:[{"inset-e":x(),end:x()}],"inset-bs":[{"inset-bs":x()}],"inset-be":[{"inset-be":x()}],top:[{top:x()}],right:[{right:x()}],bottom:[{bottom:x()}],left:[{left:x()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[H,`auto`,Y,K]}],basis:[{basis:[B,`full`,`auto`,s,...b()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[V,B,`auto`,`initial`,`none`,K]}],grow:[{grow:[``,V,Y,K]}],shrink:[{shrink:[``,V,Y,K]}],order:[{order:[H,`first`,`last`,`none`,Y,K]}],"grid-cols":[{"grid-cols":ie()}],"col-start-end":[{col:S()}],"col-start":[{"col-start":C()}],"col-end":[{"col-end":C()}],"grid-rows":[{"grid-rows":ie()}],"row-start-end":[{row:S()}],"row-start":[{"row-start":C()}],"row-end":[{"row-end":C()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":ae()}],"auto-rows":[{"auto-rows":ae()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...w(),`normal`]}],"justify-items":[{"justify-items":[...T(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...T()]}],"align-content":[{content:[`normal`,...w()]}],"align-items":[{items:[...T(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...T(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":w()}],"place-items":[{"place-items":[...T(),`baseline`]}],"place-self":[{"place-self":[`auto`,...T()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pbs:[{pbs:b()}],pbe:[{pbe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mbs:[{mbs:E()}],mbe:[{mbe:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":b()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":b()}],"space-y-reverse":[`space-y-reverse`],size:[{size:D()}],"inline-size":[{inline:[`auto`,...O()]}],"min-inline-size":[{"min-inline":[`auto`,...O()]}],"max-inline-size":[{"max-inline":[`none`,...O()]}],"block-size":[{block:[`auto`,...k()]}],"min-block-size":[{"min-block":[`auto`,...k()]}],"max-block-size":[{"max-block":[`none`,...k()]}],w:[{w:[s,`screen`,...D()]}],"min-w":[{"min-w":[s,`screen`,`none`,...D()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...D()]}],h:[{h:[`screen`,`lh`,...D()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...D()]}],"max-h":[{"max-h":[`screen`,`lh`,...D()]}],"font-size":[{text:[`base`,n,X,q]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,De,ve]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,ue,K]}],"font-family":[{font:[Se,ye,t]}],"font-features":[{"font-features":[K]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,Y,K]}],"line-clamp":[{"line-clamp":[V,`none`,Y,_e]}],leading:[{leading:[a,...b()]}],"list-image":[{"list-image":[`none`,Y,K]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,Y,K]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:A()}],"text-color":[{text:A()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...I(),`wavy`]}],"text-decoration-thickness":[{decoration:[V,`from-font`,`auto`,Y,q]}],"text-decoration-color":[{decoration:A()}],"underline-offset":[{"underline-offset":[V,`auto`,Y,K]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:b()}],"tab-size":[{tab:[H,Y,K]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,Y,K]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,Y,K]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:oe()}],"bg-repeat":[{bg:j()}],"bg-size":[{bg:se()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},H,Y,K],radial:[``,Y,K],conic:[H,Y,K]},Te,xe]}],"bg-color":[{bg:A()}],"gradient-from-pos":[{from:M()}],"gradient-via-pos":[{via:M()}],"gradient-to-pos":[{to:M()}],"gradient-from":[{from:A()}],"gradient-via":[{via:A()}],"gradient-to":[{to:A()}],rounded:[{rounded:P()}],"rounded-s":[{"rounded-s":P()}],"rounded-e":[{"rounded-e":P()}],"rounded-t":[{"rounded-t":P()}],"rounded-r":[{"rounded-r":P()}],"rounded-b":[{"rounded-b":P()}],"rounded-l":[{"rounded-l":P()}],"rounded-ss":[{"rounded-ss":P()}],"rounded-se":[{"rounded-se":P()}],"rounded-ee":[{"rounded-ee":P()}],"rounded-es":[{"rounded-es":P()}],"rounded-tl":[{"rounded-tl":P()}],"rounded-tr":[{"rounded-tr":P()}],"rounded-br":[{"rounded-br":P()}],"rounded-bl":[{"rounded-bl":P()}],"border-w":[{border:F()}],"border-w-x":[{"border-x":F()}],"border-w-y":[{"border-y":F()}],"border-w-s":[{"border-s":F()}],"border-w-e":[{"border-e":F()}],"border-w-bs":[{"border-bs":F()}],"border-w-be":[{"border-be":F()}],"border-w-t":[{"border-t":F()}],"border-w-r":[{"border-r":F()}],"border-w-b":[{"border-b":F()}],"border-w-l":[{"border-l":F()}],"divide-x":[{"divide-x":F()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":F()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...I(),`hidden`,`none`]}],"divide-style":[{divide:[...I(),`hidden`,`none`]}],"border-color":[{border:A()}],"border-color-x":[{"border-x":A()}],"border-color-y":[{"border-y":A()}],"border-color-s":[{"border-s":A()}],"border-color-e":[{"border-e":A()}],"border-color-bs":[{"border-bs":A()}],"border-color-be":[{"border-be":A()}],"border-color-t":[{"border-t":A()}],"border-color-r":[{"border-r":A()}],"border-color-b":[{"border-b":A()}],"border-color-l":[{"border-l":A()}],"divide-color":[{divide:A()}],"outline-style":[{outline:[...I(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[V,Y,K]}],"outline-w":[{outline:[``,V,X,q]}],"outline-color":[{outline:A()}],shadow:[{shadow:[``,`none`,u,Ee,J]}],"shadow-color":[{shadow:A()}],"inset-shadow":[{"inset-shadow":[`none`,d,Ee,J]}],"inset-shadow-color":[{"inset-shadow":A()}],"ring-w":[{ring:F()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:A()}],"ring-offset-w":[{"ring-offset":[V,q]}],"ring-offset-color":[{"ring-offset":A()}],"inset-ring-w":[{"inset-ring":F()}],"inset-ring-color":[{"inset-ring":A()}],"text-shadow":[{"text-shadow":[`none`,f,Ee,J]}],"text-shadow-color":[{"text-shadow":A()}],opacity:[{opacity:[V,Y,K]}],"mix-blend":[{"mix-blend":[...ce(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[V]}],"mask-image-linear-from-pos":[{"mask-linear-from":L()}],"mask-image-linear-to-pos":[{"mask-linear-to":L()}],"mask-image-linear-from-color":[{"mask-linear-from":A()}],"mask-image-linear-to-color":[{"mask-linear-to":A()}],"mask-image-t-from-pos":[{"mask-t-from":L()}],"mask-image-t-to-pos":[{"mask-t-to":L()}],"mask-image-t-from-color":[{"mask-t-from":A()}],"mask-image-t-to-color":[{"mask-t-to":A()}],"mask-image-r-from-pos":[{"mask-r-from":L()}],"mask-image-r-to-pos":[{"mask-r-to":L()}],"mask-image-r-from-color":[{"mask-r-from":A()}],"mask-image-r-to-color":[{"mask-r-to":A()}],"mask-image-b-from-pos":[{"mask-b-from":L()}],"mask-image-b-to-pos":[{"mask-b-to":L()}],"mask-image-b-from-color":[{"mask-b-from":A()}],"mask-image-b-to-color":[{"mask-b-to":A()}],"mask-image-l-from-pos":[{"mask-l-from":L()}],"mask-image-l-to-pos":[{"mask-l-to":L()}],"mask-image-l-from-color":[{"mask-l-from":A()}],"mask-image-l-to-color":[{"mask-l-to":A()}],"mask-image-x-from-pos":[{"mask-x-from":L()}],"mask-image-x-to-pos":[{"mask-x-to":L()}],"mask-image-x-from-color":[{"mask-x-from":A()}],"mask-image-x-to-color":[{"mask-x-to":A()}],"mask-image-y-from-pos":[{"mask-y-from":L()}],"mask-image-y-to-pos":[{"mask-y-to":L()}],"mask-image-y-from-color":[{"mask-y-from":A()}],"mask-image-y-to-color":[{"mask-y-to":A()}],"mask-image-radial":[{"mask-radial":[Y,K]}],"mask-image-radial-from-pos":[{"mask-radial-from":L()}],"mask-image-radial-to-pos":[{"mask-radial-to":L()}],"mask-image-radial-from-color":[{"mask-radial-from":A()}],"mask-image-radial-to-color":[{"mask-radial-to":A()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":y()}],"mask-image-conic-pos":[{"mask-conic":[V]}],"mask-image-conic-from-pos":[{"mask-conic-from":L()}],"mask-image-conic-to-pos":[{"mask-conic-to":L()}],"mask-image-conic-from-color":[{"mask-conic-from":A()}],"mask-image-conic-to-color":[{"mask-conic-to":A()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:oe()}],"mask-repeat":[{mask:j()}],"mask-size":[{mask:se()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,Y,K]}],filter:[{filter:[``,`none`,Y,K]}],blur:[{blur:le()}],brightness:[{brightness:[V,Y,K]}],contrast:[{contrast:[V,Y,K]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,Ee,J]}],"drop-shadow-color":[{"drop-shadow":A()}],grayscale:[{grayscale:[``,V,Y,K]}],"hue-rotate":[{"hue-rotate":[V,Y,K]}],invert:[{invert:[``,V,Y,K]}],saturate:[{saturate:[V,Y,K]}],sepia:[{sepia:[``,V,Y,K]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,Y,K]}],"backdrop-blur":[{"backdrop-blur":le()}],"backdrop-brightness":[{"backdrop-brightness":[V,Y,K]}],"backdrop-contrast":[{"backdrop-contrast":[V,Y,K]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,V,Y,K]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[V,Y,K]}],"backdrop-invert":[{"backdrop-invert":[``,V,Y,K]}],"backdrop-opacity":[{"backdrop-opacity":[V,Y,K]}],"backdrop-saturate":[{"backdrop-saturate":[V,Y,K]}],"backdrop-sepia":[{"backdrop-sepia":[``,V,Y,K]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,Y,K]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[V,`initial`,Y,K]}],ease:[{ease:[`linear`,`initial`,_,Y,K]}],delay:[{delay:[V,Y,K]}],animate:[{animate:[`none`,ee,Y,K]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,Y,K]}],"perspective-origin":[{"perspective-origin":te()}],rotate:[{rotate:R()}],"rotate-x":[{"rotate-x":R()}],"rotate-y":[{"rotate-y":R()}],"rotate-z":[{"rotate-z":R()}],scale:[{scale:z()}],"scale-x":[{"scale-x":z()}],"scale-y":[{"scale-y":z()}],"scale-z":[{"scale-z":z()}],"scale-3d":[`scale-3d`],skew:[{skew:W()}],"skew-x":[{"skew-x":W()}],"skew-y":[{"skew-y":W()}],transform:[{transform:[Y,K,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:te()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:G()}],"translate-x":[{"translate-x":G()}],"translate-y":[{"translate-y":G()}],"translate-z":[{"translate-z":G()}],"translate-none":[`translate-none`],zoom:[{zoom:[H,Y,K]}],accent:[{accent:A()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:A()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,Y,K]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":A()}],"scrollbar-track-color":[{"scrollbar-track":A()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mbs":[{"scroll-mbs":b()}],"scroll-mbe":[{"scroll-mbe":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pbs":[{"scroll-pbs":b()}],"scroll-pbe":[{"scroll-pbe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,Y,K]}],fill:[{fill:[`none`,...A()]}],"stroke-w":[{stroke:[V,X,q,_e]}],stroke:[{stroke:[`none`,...A()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function Le(...e){return Ie(s(e))}function Re(e=`id`){return`${e}_${Math.random().toString(36).slice(2,10)}${Date.now().toString(36).slice(-4)}`}var ze=Object.defineProperty,Be=(e,t)=>ze(e,`name`,{value:t,configurable:!0});function Ve(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}Be(Ve,`setRef`);function He(...e){return t=>{let n=!1,r=e.map(e=>{let r=Ve(e,t);return!n&&typeof r==`function`&&(n=!0),r});if(n)return()=>{for(let t=0;tWe(e,`name`,{value:t,configurable:!0}),Ge=$(((e,t)=>{let n={...t};for(let r in t){let i=e[r],a=t[r];if(/^on[A-Z]/.test(r))if(i&&a){let e=typeof i==`function`,t=typeof a==`function`;n[r]=(...n)=>{let r=t?a(...n):void 0;return e&&i(...n),r}}else i&&(n[r]=i);else r===`style`?n[r]={...typeof i==`object`?i:null,...typeof a==`object`?a:null}:r===`className`?n[r]=[i,a].filter(Boolean).join(` `):r===`aria-describedby`&&(n[r]=Ke(a,i))}return{...e,...n}}),`mergeProps`);function Ke(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}$(Ke,`concatAriaDescribedby`);var qe=i.createContext(Ge);qe.displayName=`SlotContext`;function Je(e){let t=i.forwardRef((t,n)=>{let r=i.useContext(qe),{children:a,mergeProps:o=r,...s}=t,c=null,l=!1,u=[];nt(a)&&typeof ot==`function`&&(a=ot(a._payload)),i.Children.forEach(a,e=>{if(et(e)){l=!0;let t=e,n=`child`in t.props?t.props.child:t.props.children;nt(n)&&typeof ot==`function`&&(n=ot(n._payload)),c=Qe(t,n),u.push(c?.props?.children)}else u.push(e)}),c?c=i.cloneElement(c,void 0,u):!l&&i.Children.count(a)===1&&i.isValidElement(a)&&(c=a);let d=c?$e(c):void 0,f=Ue(n,d);if(!c){if(a||a===0)throw Error(l?at(e):it(e));return a}let p=o(s,c.props??{});return c.type!==i.Fragment&&(p.ref=n?f:d),i.cloneElement(c,p)});return t.displayName=`${e}.Slot`,t}$(Je,`createSlot`);var Ye=Je(`Slot`),Xe=Symbol.for(`radix.slottable`);function Ze(e){let t=$(e=>`child`in e?e.children(e.child):e.children,`Slottable`);return t.displayName=`${e}.Slottable`,t.__radixId=Xe,t}$(Ze,`createSlottable`);var Qe=$((e,t)=>{if(`child`in e.props){let t=e.props.child;return i.isValidElement(t)?i.cloneElement(t,void 0,e.props.children(t.props.children)):null}return i.isValidElement(t)?t:null},`getSlottableElementFromSlottable`);function $e(e){let t=Object.getOwnPropertyDescriptor(e.props,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}$($e,`getElementRef`);function et(e){return i.isValidElement(e)&&typeof e.type==`function`&&`__radixId`in e.type&&e.type.__radixId===Xe}$(et,`isSlottable`);var tt=Symbol.for(`react.lazy`);function nt(e){return typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===tt&&`_payload`in e&&rt(e._payload)}$(nt,`isLazyComponent`);function rt(e){return typeof e==`object`&&!!e&&`then`in e}$(rt,`isPromiseLike`);var it=$(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,`createSlotError`),at=$(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,`createSlottableError`),ot=i.use,st=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,ct=s,lt=((e,t)=>n=>{if(t?.variants==null)return ct(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=st(t)||st(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return ct(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)})(`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[background-color,color,opacity,box-shadow,transform] duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:pointer-events-none disabled:opacity-50 active:scale-[0.98] [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/90`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,ghost:`hover:bg-muted text-foreground`,outline:`border border-border bg-transparent hover:bg-muted`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,soft:`bg-muted text-foreground hover:bg-muted/80`},size:{default:`h-9 px-3.5 py-2`,sm:`h-8 rounded-md px-2.5 text-xs`,lg:`h-10 rounded-lg px-4`,icon:`h-8 w-8`,"icon-sm":`h-7 w-7`}},defaultVariants:{variant:`default`,size:`default`}}),ut=i.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...i},o)=>(0,a.jsx)(r?Ye:`button`,{className:Le(lt({variant:t,size:n,className:e})),ref:o,...i}));ut.displayName=`Button`;function dt(){let{data:e,isPending:t}=r.useSession(),n=e?.user;return{user:n?{id:n.id,displayName:n.name??null,primaryEmail:n.email??null,profileImageUrl:n.image??null,isDevFallback:!1}:null,isPending:t}}function ft(){return dt().user}export{Ze as a,Le as c,Je as i,Re as l,dt as n,He as o,ut as r,Ue as s,ft as t}; \ No newline at end of file diff --git a/.vercel/output/static/assets/utils-BTuSbA5p.js b/.vercel/output/static/assets/utils-BTuSbA5p.js new file mode 100644 index 0000000..3dad154 --- /dev/null +++ b/.vercel/output/static/assets/utils-BTuSbA5p.js @@ -0,0 +1 @@ +import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{t as n}from"./react-BLJmJXjR.js";var r=t((e=>{var t=n();function r(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=r()}));function a(e){return e[e.length-1]}function o(e){return typeof e==`function`}function s(e,t){return o(e)?e(t):e}var c=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable;function u(e){for(let t in e)if(c.call(e,t))return!0;return!1}var d=()=>Object.create(null),f=(e,t)=>p(e,t,d);function p(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=_(e)&&_(i);if(!a&&!(h(e)&&h(i)))return i;let o=a?e:m(e);if(!o)return i;let s=a?i:m(i);if(!s)return i;let l=o.length,u=s.length,d=a?Array(u):n(),f=0;for(let t=0;ti||!v(e[o],t[o],n)))return!1;return i===a}return!1}function y(e){let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.status=`pending`,r.resolve=n=>{r.status=`resolved`,r.value=n,t(n),e?.(n)},r.reject=e=>{r.status=`rejected`,n(e)},r}function b(e){return typeof e?.message==`string`?e.message.startsWith(`Failed to fetch dynamically imported module`)||e.message.startsWith(`error loading dynamically imported module`)||e.message.startsWith(`Importing a module script failed`):!1}function x(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}var ee=/[\x00-\x1f\x7f"<>`{}]/g;function S(e){return e.replace(ee,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function C(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return S(t)}var w=[`http:`,`https:`,`mailto:`,`tel:`];function te(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}var ne={"&":`\\u0026`,">":`\\u003e`,"<":`\\u003c`,"\u2028":`\\u2028`,"\u2029":`\\u2029`},T=/[&><\u2028\u2029]/g;function re(e){return e.replace(T,e=>ne[e])}function ie(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=C(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=C(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function E(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function D(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var k=4,A=5;function oe(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function se(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=oe(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=P(1,n.fullPath??n.from,f,p,m);o=e,e.depth=a,e.parent=i,i.dynamic??=[],i.dynamic.push(e)}break}case 3:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.optional?.find(e=>!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=P(3,n.fullPath??n.from,f,p,m);o=e,e.parent=i,e.depth=a,i.optional??=[],i.optional.push(e)}break}case 2:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),l=c&&!!(t||s),f=t?l?t:t.toLowerCase():void 0,p=s?l?s:s.toLowerCase():void 0,m=P(2,n.fullPath??n.from,l,f,p);o=m,m.parent=i,m.depth=a,i.wildcard??=[],i.wildcard.push(m)}}i=o}if(l&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=N(n.fullPath??n.from);e.kind=A,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let u=(n.path||!n.children)&&!n.isRoot;if(u&&r.endsWith(`/`)){let e=N(n.fullPath??n.from);e.kind=k,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=l??null,i.priority=n.options?.params?.priority??0,u&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(let r of n.children)ce(e,t,r,s,i,a,o)}function j(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function M(e){if(e.pathless)for(let t of e.pathless)M(t);if(e.static)for(let t of e.static.values())M(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())M(t);if(e.dynamic?.length){e.dynamic.sort(j);for(let t of e.dynamic)M(t)}if(e.optional?.length){e.optional.sort(j);for(let t of e.optional)M(t)}if(e.wildcard?.length){e.wildcard.sort(j);for(let t of e.wildcard)M(t)}}function N(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function P(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function F(e,t){let n=N(`/`),r=new Uint16Array(6);for(let t of e)ce(!1,r,t,1,n,0);M(n),t.masksTree=n,t.flatCache=ae(1e3)}function I(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=B(e,t.masksTree);return t.flatCache.set(e,r),r}function le(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=N(`/`),ce(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),B(r,o,n)}function L(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=B(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=de(a.route)),t.matchCache.set(r,a),a}function R(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function z(e,t=!1,n){let r=N(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return ce(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&O(),a[e.id]=e,s!==0&&e.path){let t=R(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),M(r),{processedTree:{segmentTree:r,singleCache:ae(1e3),matchCache:ae(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function B(e,t,n=!1){let r=e.split(`/`),i=pe(e,r,t,n);if(!i)return null;let[a]=ue(e,r,i);return{route:i.node.route,rawParams:a}}function ue(e,t,n){let r=fe(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s=0;e--){let n=i.wildcard[e],{prefix:r,suffix:o}=n;if(!(r&&(v||!(n.caseSensitive?y:b??=y.toLowerCase()).startsWith(r)))){if(o){if(v)continue;let e=t.slice(a).join(`/`).slice(-o.length);if((n.caseSensitive?e:e.toLowerCase())!==o)continue}c.push({node:n,index:s,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}if(i.optional){let e=d|1<=0;n--){let r=i.optional[n];c.push({node:r,index:a,skipped:e,depth:t,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v)for(let e=i.optional.length-1;e>=0;e--){let n=i.optional[e],{prefix:r,suffix:o}=n;if(r||o){let e=n.caseSensitive?y:b??=y.toLowerCase();if(r&&!e.startsWith(r)||o&&!e.endsWith(o))continue}c.push({node:n,index:a+1,skipped:d,depth:t,statics:p,dynamics:m,optionals:h+me(s,a),extract:g,rawParams:_})}}if(!v&&i.dynamic&&y)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?y:b??=y.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}c.push({node:t,index:a+1,skipped:d,depth:f+1,statics:p,dynamics:m+me(s,a),optionals:h,extract:g,rawParams:_})}if(!v&&i.staticInsensitive){let e=i.staticInsensitive.get(b??=y.toLowerCase());e&&c.push({node:e,index:a+1,skipped:d,depth:f+1,statics:p+me(s,a),dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v&&i.static){let e=i.static.get(y);e&&c.push({node:e,index:a+1,skipped:d,depth:f+1,statics:p+me(s,a),dynamics:m,optionals:h,extract:g,rawParams:_})}if(i.pathless){let e=f+1;for(let t=i.pathless.length-1;t>=0;t--){let n=i.pathless[t];c.push({node:n,index:a,skipped:d,depth:e,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}}if(u)return u;if(r&&l){let n=l.index;for(let e=0;ee.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===k)>(e.node.kind===k)||t.node.kind===k==(e.node.kind===k)&&t.depth>e.depth)))}function U(e){return ge(e.filter(e=>e!==void 0).join(`/`))}function ge(e){return e.replace(/\/{2,}/g,`/`)}function _e(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function ve(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function ye(e){return ve(_e(e))}function be(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function xe(e,t,n){return be(e,n)===be(t,n)}function Se({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t.startsWith(`/`),o=!i&&t===`.`,s;if(r){s=i?t:o?e:e+`\0`+t;let n=r.get(s);if(n)return n}let c;if(o)c=e.split(`/`);else if(i)c=t.split(`/`);else{for(c=e.split(`/`);c.length>1&&a(c)===``;)c.pop();let n=t.split(`/`);for(let e=0,t=n.length;e1&&(a(c)===``?n===`never`&&c.pop():n===`always`&&c.push(``));let l=ge(c.join(`/`))||`/`;return s&&r&&r.set(s,l),l}function Ce(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function we(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Ee(e,n)).join(`/`):Ee(r,n):r}function Te({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s{if(!e.current||r.disabled||typeof IntersectionObserver!=`function`)return;let i=new IntersectionObserver(([e])=>{t(e)},n);return i.observe(e.current),()=>{i.disconnect()}},[t,n,r.disabled,e])}function Me(e){let t=W.useRef(null);return W.useImperativeHandle(e,()=>t.current,[]),t}var Ne=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),Pe=t(((e,t)=>{t.exports=Ne()})),Fe=Pe();function Ie({children:e,fallback:t=null}){return Le()?(0,Fe.jsx)(W.Fragment,{children:e}):(0,Fe.jsx)(W.Fragment,{children:t})}function Le(){return W.useSyncExternalStore(Re,()=>!0,()=>!1)}function Re(){return()=>{}}var ze=W.createContext(null);function Be(e){return W.useContext(ze)}var Ve=t((e=>{var t=n();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=t.useState,o=t.useEffect,s=t.useLayoutEffect,c=t.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!i(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),He=t(((e,t)=>{t.exports=Ve()})),Ue=t((e=>{var t=n(),r=He();function i(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:i,o=r.useSyncExternalStore,s=t.useRef,c=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),We=t(((e,t)=>{t.exports=Ue()}))();function Ge(e,t){return e===t}function Ke(e,t,n=Ge){let r=(0,W.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,W.useCallback)(()=>e?.get(),[e]);return(0,We.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var qe=e(i(),1);function Je(e,t){let n=Be(),r=Me(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:c,preload:l,preloadDelay:u,preloadIntentProximity:d,hashScrollIntoView:f,replace:p,startTransition:m,resetScroll:h,viewTransition:g,children:_,target:y,disabled:b,style:x,className:ee,onClick:S,onBlur:C,onFocus:w,onMouseEnter:ne,onMouseLeave:T,onTouchStart:re,ignoreBlocker:ie,params:E,search:D,hash:O,state:ae,mask:k,reloadDocument:A,unsafeRelative:oe,from:se,_fromLocation:ce,...j}=e,M=Le(),N=W.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),P=Ke(n.stores.location,e=>e,(e,t)=>e.href===t.href),F=W.useMemo(()=>{let e={_fromLocation:P,...N};return n.buildLocation(e)},[n,P,N]),I=F.maskedLocation?F.maskedLocation.publicHref:F.publicHref,le=F.maskedLocation?F.maskedLocation.external:F.external,L=W.useMemo(()=>rt(I,le,n.history,b),[b,le,I,n.history]),R=W.useMemo(()=>{if(L?.external)return te(L.href,n.protocolAllowlist)?void 0:L.href;if(!it(c)&&!(typeof c!=`string`||c.indexOf(`:`)===-1))try{return new URL(c),te(c,n.protocolAllowlist)?void 0:c}catch{}},[c,L,n.protocolAllowlist]),z=W.useMemo(()=>{if(R)return!1;if(o?.exact){if(!xe(P.pathname,F.pathname,n.basepath))return!1}else{let e=be(P.pathname,n.basepath),t=be(F.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!v(P.search,F.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:!o?.includeHash||M&&P.hash===F.hash},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,P,R,M,F.hash,F.pathname,F.search,n.basepath]),B=z?s(i,{})??Xe:Ye,ue=z?Ye:s(a,{})??Ye,de=[ee,B.className,ue.className].filter(Boolean).join(` `),fe=(x||B.style||ue.style)&&{...x,...B.style,...ue.style},[pe,me]=W.useState(!1),he=W.useRef(!1),V=e.reloadDocument||R?!1:l??n.options.defaultPreload,H=u??n.options.defaultPreloadDelay??0,U=W.useCallback(()=>{n.preloadRoute({...N,_builtLocation:F}).catch(e=>{console.warn(e),console.warn(De)})},[n,N,F]);je(r,W.useCallback(e=>{e?.isIntersecting&&U()},[U]),tt,{disabled:!!b||V!==`viewport`}),W.useEffect(()=>{he.current||!b&&V===`render`&&(U(),he.current=!0)},[b,U,V]);let ge=e=>{let t=e.currentTarget.getAttribute(`target`),r=y===void 0?t:y;if(!b&&!ot(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,qe.flushSync)(()=>{me(!0)});let t=n.subscribe(`onResolved`,()=>{t(),me(!1)});n.navigate({...N,replace:p,resetScroll:h,hashScrollIntoView:f,startTransition:m,viewTransition:g,ignoreBlocker:ie})}};if(R)return{...j,ref:r,href:R,..._&&{children:_},...y&&{target:y},...b&&{disabled:b},...x&&{style:x},...ee&&{className:ee},...S&&{onClick:S},...C&&{onBlur:C},...w&&{onFocus:w},...ne&&{onMouseEnter:ne},...T&&{onMouseLeave:T},...re&&{onTouchStart:re}};let _e=e=>{if(b||V!==`intent`)return;if(!H){U();return}let t=e.currentTarget;if(et.has(t))return;let n=setTimeout(()=>{et.delete(t),U()},H);et.set(t,n)},ve=e=>{b||V!==`intent`||U()},ye=e=>{if(b||!V||!H)return;let t=e.currentTarget,n=et.get(t);n&&(clearTimeout(n),et.delete(t))};return{...j,...B,...ue,href:L?.href,ref:r,onClick:nt([S,ge]),onBlur:nt([C,ye]),onFocus:nt([w,_e]),onMouseEnter:nt([ne,_e]),onMouseLeave:nt([T,ye]),onTouchStart:nt([re,ve]),disabled:!!b,target:y,...fe&&{style:fe},...de&&{className:de},...b&&Ze,...z&&Qe,...M&&pe&&$e}}var Ye={},Xe={className:`active`},Ze={role:`link`,"aria-disabled":!0},Qe={"data-status":`active`,"aria-current":`page`},$e={"data-transitioning":`transitioning`},et=new WeakMap,tt={rootMargin:`100px`},nt=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function rt(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function it(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var at=W.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=Je(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return W.createElement(`a`,t,o)}return W.createElement(n,a,o)});function ot(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function st(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`)if(Array.isArray(e)){var i=e.length;for(t=0;t{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),dt=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),ft=`-`,pt=[],mt=`arbitrary..`,ht=e=>{let t=vt(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return _t(e);let n=e.split(ft);return gt(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?lt(i,t):t:i||pt}return n[e]||pt}}},gt=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=gt(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(ft):e.slice(t).join(ft),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?mt+r:void 0})(),vt=e=>{let{theme:t,classGroups:n}=e;return yt(n,t)},yt=(e,t)=>{let n=dt();for(let r in e){let i=e[r];bt(i,n,r,t)}return n},bt=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){St(e,t,n);return}if(typeof e==`function`){Ct(e,t,n,r);return}wt(e,t,n,r)},St=(e,t,n)=>{let r=e===``?t:Tt(t,e);r.classGroupId=n},Ct=(e,t,n,r)=>{if(Et(e)){bt(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(ut(n,e))},wt=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(ft),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,Dt=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},Ot=`!`,kt=`:`,At=[],jt=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Mt=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return jt(t,l,c,u)};if(t){let e=t+kt,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):jt(At,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},Nt=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},Pt=e=>({cache:Dt(e.cacheSize),parseClassName:Mt(e),sortModifiers:Nt(e),postfixLookupClassGroupIds:Ft(e),...ht(e)}),Ft=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(It),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+Ot:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},Rt=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=Pt(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=Lt(e,n);return i(e,a),a};return a=o,(...e)=>a(Rt(...e))},Vt=[],G=e=>{let t=t=>t[e]||Vt;return t.isThemeGetter=!0,t},Ht=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Ut=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Wt=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Gt=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Kt=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,qt=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Jt=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Yt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,K=e=>Wt.test(e),q=e=>!!e&&!Number.isNaN(Number(e)),J=e=>!!e&&Number.isInteger(Number(e)),Xt=e=>e.endsWith(`%`)&&q(e.slice(0,-1)),Y=e=>Gt.test(e),Zt=()=>!0,Qt=e=>Kt.test(e)&&!qt.test(e),$t=()=>!1,en=e=>Jt.test(e),tn=e=>Yt.test(e),nn=e=>!X(e)&&!Z(e),rn=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),an=e=>Q(e,Sn,$t),X=e=>Ht.test(e),on=e=>Q(e,Cn,Qt),sn=e=>Q(e,wn,q),cn=e=>Q(e,En,Zt),ln=e=>Q(e,Tn,$t),un=e=>Q(e,bn,$t),dn=e=>Q(e,xn,tn),fn=e=>Q(e,Dn,en),Z=e=>Ut.test(e),pn=e=>$(e,Cn),mn=e=>$(e,Tn),hn=e=>$(e,bn),gn=e=>$(e,Sn),_n=e=>$(e,xn),vn=e=>$(e,Dn,!0),yn=e=>$(e,En,!0),Q=(e,t,n)=>{let r=Ht.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},$=(e,t,n=!1)=>{let r=Ut.exec(e);return r?r[1]?t(r[1]):n:!1},bn=e=>e===`position`||e===`percentage`,xn=e=>e===`image`||e===`url`,Sn=e=>e===`length`||e===`size`||e===`bg-size`,Cn=e=>e===`length`,wn=e=>e===`number`,Tn=e=>e===`family-name`,En=e=>e===`number`||e===`weight`,Dn=e=>e===`shadow`,On=Bt(()=>{let e=G(`color`),t=G(`font`),n=G(`text`),r=G(`font-weight`),i=G(`tracking`),a=G(`leading`),o=G(`breakpoint`),s=G(`container`),c=G(`spacing`),l=G(`radius`),u=G(`shadow`),d=G(`inset-shadow`),f=G(`text-shadow`),p=G(`drop-shadow`),m=G(`blur`),h=G(`perspective`),g=G(`aspect`),_=G(`ease`),v=G(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),Z,X],ee=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],S=()=>[`auto`,`contain`,`none`],C=()=>[Z,X,c],w=()=>[K,`full`,`auto`,...C()],te=()=>[J,`none`,`subgrid`,Z,X],ne=()=>[`auto`,{span:[`full`,J,Z,X]},J,Z,X],T=()=>[J,`auto`,Z,X],re=()=>[`auto`,`min`,`max`,`fr`,Z,X],ie=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],E=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],D=()=>[`auto`,...C()],O=()=>[K,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...C()],ae=()=>[K,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...C()],k=()=>[K,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...C()],A=()=>[e,Z,X],oe=()=>[...b(),hn,un,{position:[Z,X]}],se=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],ce=()=>[`auto`,`cover`,`contain`,gn,an,{size:[Z,X]}],j=()=>[Xt,pn,on],M=()=>[``,`none`,`full`,l,Z,X],N=()=>[``,q,pn,on],P=()=>[`solid`,`dashed`,`dotted`,`double`],F=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],I=()=>[q,Xt,hn,un],le=()=>[``,`none`,m,Z,X],L=()=>[`none`,q,Z,X],R=()=>[`none`,q,Z,X],z=()=>[q,Z,X],B=()=>[K,`full`,...C()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[Y],breakpoint:[Y],color:[Zt],container:[Y],"drop-shadow":[Y],ease:[`in`,`out`,`in-out`],font:[nn],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[Y],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[Y],shadow:[Y],spacing:[`px`,q],text:[Y],"text-shadow":[Y],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,K,X,Z,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,Z,X]}],"container-named":[rn],columns:[{columns:[q,X,Z,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:ee()}],"overflow-x":[{"overflow-x":ee()}],"overflow-y":[{"overflow-y":ee()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:w()}],"inset-x":[{"inset-x":w()}],"inset-y":[{"inset-y":w()}],start:[{"inset-s":w(),start:w()}],end:[{"inset-e":w(),end:w()}],"inset-bs":[{"inset-bs":w()}],"inset-be":[{"inset-be":w()}],top:[{top:w()}],right:[{right:w()}],bottom:[{bottom:w()}],left:[{left:w()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[J,`auto`,Z,X]}],basis:[{basis:[K,`full`,`auto`,s,...C()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[q,K,`auto`,`initial`,`none`,X]}],grow:[{grow:[``,q,Z,X]}],shrink:[{shrink:[``,q,Z,X]}],order:[{order:[J,`first`,`last`,`none`,Z,X]}],"grid-cols":[{"grid-cols":te()}],"col-start-end":[{col:ne()}],"col-start":[{"col-start":T()}],"col-end":[{"col-end":T()}],"grid-rows":[{"grid-rows":te()}],"row-start-end":[{row:ne()}],"row-start":[{"row-start":T()}],"row-end":[{"row-end":T()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":re()}],"auto-rows":[{"auto-rows":re()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...ie(),`normal`]}],"justify-items":[{"justify-items":[...E(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...E()]}],"align-content":[{content:[`normal`,...ie()]}],"align-items":[{items:[...E(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...E(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":ie()}],"place-items":[{"place-items":[...E(),`baseline`]}],"place-self":[{"place-self":[`auto`,...E()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pbs:[{pbs:C()}],pbe:[{pbe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:D()}],mx:[{mx:D()}],my:[{my:D()}],ms:[{ms:D()}],me:[{me:D()}],mbs:[{mbs:D()}],mbe:[{mbe:D()}],mt:[{mt:D()}],mr:[{mr:D()}],mb:[{mb:D()}],ml:[{ml:D()}],"space-x":[{"space-x":C()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":C()}],"space-y-reverse":[`space-y-reverse`],size:[{size:O()}],"inline-size":[{inline:[`auto`,...ae()]}],"min-inline-size":[{"min-inline":[`auto`,...ae()]}],"max-inline-size":[{"max-inline":[`none`,...ae()]}],"block-size":[{block:[`auto`,...k()]}],"min-block-size":[{"min-block":[`auto`,...k()]}],"max-block-size":[{"max-block":[`none`,...k()]}],w:[{w:[s,`screen`,...O()]}],"min-w":[{"min-w":[s,`screen`,`none`,...O()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...O()]}],h:[{h:[`screen`,`lh`,...O()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...O()]}],"max-h":[{"max-h":[`screen`,`lh`,...O()]}],"font-size":[{text:[`base`,n,pn,on]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,yn,cn]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,Xt,X]}],"font-family":[{font:[mn,ln,t]}],"font-features":[{"font-features":[X]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,Z,X]}],"line-clamp":[{"line-clamp":[q,`none`,Z,sn]}],leading:[{leading:[a,...C()]}],"list-image":[{"list-image":[`none`,Z,X]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,Z,X]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:A()}],"text-color":[{text:A()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...P(),`wavy`]}],"text-decoration-thickness":[{decoration:[q,`from-font`,`auto`,Z,on]}],"text-decoration-color":[{decoration:A()}],"underline-offset":[{"underline-offset":[q,`auto`,Z,X]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:C()}],"tab-size":[{tab:[J,Z,X]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,Z,X]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,Z,X]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:oe()}],"bg-repeat":[{bg:se()}],"bg-size":[{bg:ce()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},J,Z,X],radial:[``,Z,X],conic:[J,Z,X]},_n,dn]}],"bg-color":[{bg:A()}],"gradient-from-pos":[{from:j()}],"gradient-via-pos":[{via:j()}],"gradient-to-pos":[{to:j()}],"gradient-from":[{from:A()}],"gradient-via":[{via:A()}],"gradient-to":[{to:A()}],rounded:[{rounded:M()}],"rounded-s":[{"rounded-s":M()}],"rounded-e":[{"rounded-e":M()}],"rounded-t":[{"rounded-t":M()}],"rounded-r":[{"rounded-r":M()}],"rounded-b":[{"rounded-b":M()}],"rounded-l":[{"rounded-l":M()}],"rounded-ss":[{"rounded-ss":M()}],"rounded-se":[{"rounded-se":M()}],"rounded-ee":[{"rounded-ee":M()}],"rounded-es":[{"rounded-es":M()}],"rounded-tl":[{"rounded-tl":M()}],"rounded-tr":[{"rounded-tr":M()}],"rounded-br":[{"rounded-br":M()}],"rounded-bl":[{"rounded-bl":M()}],"border-w":[{border:N()}],"border-w-x":[{"border-x":N()}],"border-w-y":[{"border-y":N()}],"border-w-s":[{"border-s":N()}],"border-w-e":[{"border-e":N()}],"border-w-bs":[{"border-bs":N()}],"border-w-be":[{"border-be":N()}],"border-w-t":[{"border-t":N()}],"border-w-r":[{"border-r":N()}],"border-w-b":[{"border-b":N()}],"border-w-l":[{"border-l":N()}],"divide-x":[{"divide-x":N()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":N()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...P(),`hidden`,`none`]}],"divide-style":[{divide:[...P(),`hidden`,`none`]}],"border-color":[{border:A()}],"border-color-x":[{"border-x":A()}],"border-color-y":[{"border-y":A()}],"border-color-s":[{"border-s":A()}],"border-color-e":[{"border-e":A()}],"border-color-bs":[{"border-bs":A()}],"border-color-be":[{"border-be":A()}],"border-color-t":[{"border-t":A()}],"border-color-r":[{"border-r":A()}],"border-color-b":[{"border-b":A()}],"border-color-l":[{"border-l":A()}],"divide-color":[{divide:A()}],"outline-style":[{outline:[...P(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[q,Z,X]}],"outline-w":[{outline:[``,q,pn,on]}],"outline-color":[{outline:A()}],shadow:[{shadow:[``,`none`,u,vn,fn]}],"shadow-color":[{shadow:A()}],"inset-shadow":[{"inset-shadow":[`none`,d,vn,fn]}],"inset-shadow-color":[{"inset-shadow":A()}],"ring-w":[{ring:N()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:A()}],"ring-offset-w":[{"ring-offset":[q,on]}],"ring-offset-color":[{"ring-offset":A()}],"inset-ring-w":[{"inset-ring":N()}],"inset-ring-color":[{"inset-ring":A()}],"text-shadow":[{"text-shadow":[`none`,f,vn,fn]}],"text-shadow-color":[{"text-shadow":A()}],opacity:[{opacity:[q,Z,X]}],"mix-blend":[{"mix-blend":[...F(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":F()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[q]}],"mask-image-linear-from-pos":[{"mask-linear-from":I()}],"mask-image-linear-to-pos":[{"mask-linear-to":I()}],"mask-image-linear-from-color":[{"mask-linear-from":A()}],"mask-image-linear-to-color":[{"mask-linear-to":A()}],"mask-image-t-from-pos":[{"mask-t-from":I()}],"mask-image-t-to-pos":[{"mask-t-to":I()}],"mask-image-t-from-color":[{"mask-t-from":A()}],"mask-image-t-to-color":[{"mask-t-to":A()}],"mask-image-r-from-pos":[{"mask-r-from":I()}],"mask-image-r-to-pos":[{"mask-r-to":I()}],"mask-image-r-from-color":[{"mask-r-from":A()}],"mask-image-r-to-color":[{"mask-r-to":A()}],"mask-image-b-from-pos":[{"mask-b-from":I()}],"mask-image-b-to-pos":[{"mask-b-to":I()}],"mask-image-b-from-color":[{"mask-b-from":A()}],"mask-image-b-to-color":[{"mask-b-to":A()}],"mask-image-l-from-pos":[{"mask-l-from":I()}],"mask-image-l-to-pos":[{"mask-l-to":I()}],"mask-image-l-from-color":[{"mask-l-from":A()}],"mask-image-l-to-color":[{"mask-l-to":A()}],"mask-image-x-from-pos":[{"mask-x-from":I()}],"mask-image-x-to-pos":[{"mask-x-to":I()}],"mask-image-x-from-color":[{"mask-x-from":A()}],"mask-image-x-to-color":[{"mask-x-to":A()}],"mask-image-y-from-pos":[{"mask-y-from":I()}],"mask-image-y-to-pos":[{"mask-y-to":I()}],"mask-image-y-from-color":[{"mask-y-from":A()}],"mask-image-y-to-color":[{"mask-y-to":A()}],"mask-image-radial":[{"mask-radial":[Z,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":I()}],"mask-image-radial-to-pos":[{"mask-radial-to":I()}],"mask-image-radial-from-color":[{"mask-radial-from":A()}],"mask-image-radial-to-color":[{"mask-radial-to":A()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[q]}],"mask-image-conic-from-pos":[{"mask-conic-from":I()}],"mask-image-conic-to-pos":[{"mask-conic-to":I()}],"mask-image-conic-from-color":[{"mask-conic-from":A()}],"mask-image-conic-to-color":[{"mask-conic-to":A()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:oe()}],"mask-repeat":[{mask:se()}],"mask-size":[{mask:ce()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,Z,X]}],filter:[{filter:[``,`none`,Z,X]}],blur:[{blur:le()}],brightness:[{brightness:[q,Z,X]}],contrast:[{contrast:[q,Z,X]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,vn,fn]}],"drop-shadow-color":[{"drop-shadow":A()}],grayscale:[{grayscale:[``,q,Z,X]}],"hue-rotate":[{"hue-rotate":[q,Z,X]}],invert:[{invert:[``,q,Z,X]}],saturate:[{saturate:[q,Z,X]}],sepia:[{sepia:[``,q,Z,X]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,Z,X]}],"backdrop-blur":[{"backdrop-blur":le()}],"backdrop-brightness":[{"backdrop-brightness":[q,Z,X]}],"backdrop-contrast":[{"backdrop-contrast":[q,Z,X]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,q,Z,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[q,Z,X]}],"backdrop-invert":[{"backdrop-invert":[``,q,Z,X]}],"backdrop-opacity":[{"backdrop-opacity":[q,Z,X]}],"backdrop-saturate":[{"backdrop-saturate":[q,Z,X]}],"backdrop-sepia":[{"backdrop-sepia":[``,q,Z,X]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,Z,X]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[q,`initial`,Z,X]}],ease:[{ease:[`linear`,`initial`,_,Z,X]}],delay:[{delay:[q,Z,X]}],animate:[{animate:[`none`,v,Z,X]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,Z,X]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:L()}],"rotate-x":[{"rotate-x":L()}],"rotate-y":[{"rotate-y":L()}],"rotate-z":[{"rotate-z":L()}],scale:[{scale:R()}],"scale-x":[{"scale-x":R()}],"scale-y":[{"scale-y":R()}],"scale-z":[{"scale-z":R()}],"scale-3d":[`scale-3d`],skew:[{skew:z()}],"skew-x":[{"skew-x":z()}],"skew-y":[{"skew-y":z()}],transform:[{transform:[Z,X,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:B()}],"translate-x":[{"translate-x":B()}],"translate-y":[{"translate-y":B()}],"translate-z":[{"translate-z":B()}],"translate-none":[`translate-none`],zoom:[{zoom:[J,Z,X]}],accent:[{accent:A()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:A()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,Z,X]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":A()}],"scrollbar-track-color":[{"scrollbar-track":A()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mbs":[{"scroll-mbs":C()}],"scroll-mbe":[{"scroll-mbe":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pbs":[{"scroll-pbs":C()}],"scroll-pbe":[{"scroll-pbe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,Z,X]}],fill:[{fill:[`none`,...A()]}],"stroke-w":[{stroke:[q,pn,on,sn]}],stroke:[{stroke:[`none`,...A()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function kn(...e){return On(ct(e))}function An(e=`id`){return`${e}_${Math.random().toString(36).slice(2,10)}${Date.now().toString(36).slice(-4)}`}export{w as A,b as B,I as C,z as D,F as E,E as F,i as G,a as H,re as I,s as L,y as M,ie as N,ae as O,v as P,u as R,de as S,le as T,f as U,x as V,p as W,U as _,Ke as a,_e as b,Ie as c,Oe as d,ke as f,Te as g,Ce as h,at as i,D as j,O as k,Le as l,ge as m,An as n,Be as o,Ae as p,ct as r,ze as s,kn as t,Pe as u,Se as v,L as w,ve as x,ye as y,te as z}; \ No newline at end of file diff --git a/.vercel/output/static/assets/vennDiagram-L72KCM5P-BsI8bHzd.js b/.vercel/output/static/assets/vennDiagram-L72KCM5P-DkYnXwoc.js similarity index 99% rename from .vercel/output/static/assets/vennDiagram-L72KCM5P-BsI8bHzd.js rename to .vercel/output/static/assets/vennDiagram-L72KCM5P-DkYnXwoc.js index 44f515f..95deb1e 100644 --- a/.vercel/output/static/assets/vennDiagram-L72KCM5P-BsI8bHzd.js +++ b/.vercel/output/static/assets/vennDiagram-L72KCM5P-DkYnXwoc.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-_wZywoZs.js";import{H as n,K as r,U as i,a,b as o,c as s,et as c,f as l,nt as u,rt as d,tt as f,v as p,w as m,y as h}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{i as g}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as _}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{t as v}from"./rough.esm-CSKSodPl.js";var y=(e,t)=>u(e,`a`,-t),b=1e-10;function x(e,t){let n=C(e),r=n.filter(t=>S(t,e)),i=0,a=0,o=[];if(r.length>1){let t=O(r);for(let e=0;et.angle-e.angle);let n=r[r.length-1];for(let t=0;tr.radius*2&&(d=r.radius*2),(l==null||l.width>d)&&(l={circle:r,width:d,p1:s,p2:n,large:d>r.radius,sweep:!0})}l!=null&&(o.push(l),i+=w(l.circle.radius,l.width),n=s)}}else{let t=e[0];for(let n=1;nMath.abs(t.radius-e[r].radius)){n=!0;break}n?i=a=0:(i=t.radius*t.radius*Math.PI,o.push({circle:t,p1:{x:t.x,y:t.y+t.radius},p2:{x:t.x-b,y:t.y+t.radius},width:t.radius*2,large:!0,sweep:!0}))}return a/=2,t&&(t.area=i+a,t.arcArea=i,t.polygonArea=a,t.arcs=o,t.innerPoints=r,t.intersectionPoints=n),i+a}function S(e,t){return t.every(t=>T(e,t)=e+t)return 0;if(n<=Math.abs(e-t))return Math.PI*Math.min(e,t)*Math.min(e,t);let r=e-(n*n-t*t+e*e)/(2*n),i=t-(n*n-e*e+t*t)/(2*n);return w(e,r)+w(t,i)}function D(e,t){let n=T(e,t),r=e.radius,i=t.radius;if(n>=r+i||n<=Math.abs(r-i))return[];let a=(r*r-i*i+n*n)/(2*n),o=Math.sqrt(r*r-a*a),s=e.x+a*(t.x-e.x)/n,c=e.y+a*(t.y-e.y)/n,l=-(t.y-e.y)*(o/n),u=-(t.x-e.x)*(o/n);return[{x:s+l,y:c-u},{x:s-l,y:c+u}]}function O(e){let t={x:0,y:0};for(let n of e)t.x+=n.x,t.y+=n.y;return t.x/=e.length,t.y/=e.length,t}function k(e,t,n,r){r||={};let i=r.maxIterations||100,a=r.tolerance||1e-10,o=e(t),s=e(n),c=n-t;if(o*s>0)throw`Initial bisect points must have opposite signs`;if(o===0)return t;if(s===0)return n;for(let n=0;n=0&&(t=n),Math.abs(c)A(t))}function M(e,t){let n=0;for(let r=0;re.fx-t.fx,_=t.slice(),v=t.slice(),y=t.slice(),b=t.slice();for(let t=0;t{let t=e.slice();return t.fx=e.fx,t.id=e.id,t});e.sort((e,t)=>e.id-t.id),n.history.push({x:m[0].slice(),fx:m[0].fx,simplex:e})}f=0;for(let e=0;e=m[p-1].fx){let n=!1;if(v.fx>t.fx?(F(y,1+u,_,-u,t),y.fx=e(y),y.fx=1)break;for(let t=1;ts+a*i*c||l>=p)f=i;else{if(Math.abs(d)<=-o*c)return i;d*(f-u)>=0&&(f=u),u=i,p=l}return 0}for(let m=0;m<10;++m){if(F(r.x,1,n.x,i,t),l=r.fx=e(r.x,r.fxprime),d=M(r.fxprime,t),l>s+a*i*c||m&&l>=u)return p(f,i,u);if(Math.abs(d)<=-o*c)return i;if(d>=0)return p(i,f,l);u=l,f=i,i*=2}return i}function R(e,t,n){let r={x:t.slice(),fx:0,fxprime:t.slice()},i={x:t.slice(),fx:0,fxprime:t.slice()},a=t.slice(),o,s,c=1,l;n||={},l=n.maxIterations||t.length*20,r.fx=e(r.x,r.fxprime),o=r.fxprime.slice(),P(o,r.fxprime,-1);for(let t=0;t{let t={};for(let n=0;nE(e,t,r)-n,0,e+t)}function ne(e,t={}){let n=t.distinct,r=e.map(e=>Object.assign({},e));function i(e){return e.join(`;`)}if(n){let e=new Map;for(let t of r)for(let n=0;ne===t?0:ee.sets.length===2).forEach(e=>{let a=n[e.sets[0]],o=n[e.sets[1]],s=z(Math.sqrt(t[a].size/Math.PI),Math.sqrt(t[o].size/Math.PI),e.size);r[a][o]=r[o][a]=s;let c=0;e.size+1e-10>=Math.min(t[a].size,t[o].size)?c=1:e.size<=1e-10&&(c=-1),i[a][o]=i[o][a]=c}),{distances:r,constraints:i}}function ie(e,t,n,r){for(let e=0;e0&&m<=d||f<0&&m>=d||(i+=2*h*h,t[2*a]+=4*h*(o-l),t[2*a+1]+=4*h*(s-u),t[2*c]+=4*h*(l-o),t[2*c+1]+=4*h*(u-s))}}return i}function ae(e,t={}){let n=se(e,t),r=t.lossFunction||B;if(e.length>=8){let i=oe(e,t),a=r(i,e),o=r(n,e);a+1e-8e.map(e=>e/s));let c=(e,t)=>ie(e,t,a,o),l=null;for(let e=0;ee.sets.length===2);for(let t of e){let e=t.weight==null?1:t.weight,n=t.sets[0],a=t.sets[1];t.size+te>=Math.min(r[n].size,r[a].size)&&(e=0),i[n].push({set:a,size:t.size,weight:e}),i[a].push({set:n,size:t.size,weight:e})}let a=[];Object.keys(i).forEach(e=>{let t=0;for(let n=0;ne[t]));let i=r.weight==null?1:r.weight;n+=i*(t-r.size)*(t-r.size)}return n}function ce(e,t){let n=0;for(let r of t){if(r.sets.length===1)continue;let t;if(r.sets.length===2){let n=e[r.sets[0]],i=e[r.sets[1]];t=E(n.radius,i.radius,T(n,i))}else t=x(r.sets.map(t=>e[t]));let i=r.weight==null?1:r.weight,a=Math.log((t+1)/(r.size+1));n+=i*a*a}return n}function le(e,t,n){if(n==null?e.sort((e,t)=>t.radius-e.radius):e.sort(n),e.length>0){let t=e[0].x,n=e[0].y;for(let r of e)r.x-=t,r.y-=n}if(e.length===2&&T(e[0],e[1])1){let n=Math.atan2(e[1].x,e[1].y)-t,r=Math.cos(n),i=Math.sin(n);for(let t of e){let e=t.x,n=t.y;t.x=r*e-i*n,t.y=i*e+r*n}}if(e.length>2){let n=Math.atan2(e[2].x,e[2].y)-t;for(;n<0;)n+=2*Math.PI;for(;n>2*Math.PI;)n-=2*Math.PI;if(n>Math.PI){let t=e[1].y/(1e-10+e[1].x);for(let n of e){var r=(n.x+t*n.y)/(1+t*t);n.x=2*r-n.x,n.y=2*r*t-n.y}}}}function ue(e){e.forEach(e=>{e.parent=e});function t(e){return e.parent!==e&&(e.parent=t(e.parent)),e.parent}function n(e,n){let r=t(e);r.parent=t(n)}for(let t=0;t{delete e.parent}),Array.from(r.values())}function V(e){let t=t=>({max:e.reduce((e,n)=>Math.max(e,n[t]+n.radius),-1/0),min:e.reduce((e,n)=>Math.min(e,n[t]-n.radius),1/0)});return{xRange:t(`x`),yRange:t(`y`)}}function de(e,t,n){t??=Math.PI/2;let r=me(e).map(e=>Object.assign({},e)),i=ue(r);for(let e of i){le(e,t,n);let r=V(e);e.size=(r.xRange.max-r.xRange.min)*(r.yRange.max-r.yRange.min),e.bounds=r}i.sort((e,t)=>t.size-e.size),r=i[0];let a=r.bounds,o=(a.xRange.max-a.xRange.min)/50;function s(e,t,n){if(!e)return;let i=e.bounds,s,c;if(t)s=a.xRange.max-i.xRange.min+o;else{s=a.xRange.max-i.xRange.max;let e=(i.xRange.max-i.xRange.min)/2-(a.xRange.max-a.xRange.min)/2;e<0&&(s+=e)}if(n)c=a.yRange.max-i.yRange.min+o;else{c=a.yRange.max-i.yRange.max;let e=(i.yRange.max-i.yRange.min)/2-(a.yRange.max-a.yRange.min)/2;e<0&&(c+=e)}for(let t of e)t.x+=s,t.y+=c,r.push(t)}let c=1;for(;c({radius:u*e.radius,x:r+d+(e.x-o.min)*u,y:r+f+(e.y-s.min)*u,setid:e.setid})))}function pe(e){let t={};for(let n of e)t[n.setid]=n;return t}function me(e){return Object.keys(e).map(t=>Object.assign(e[t],{setid:t}))}function he(e={}){let t=!1,n=600,r=350,i=15,a=1e3,o=Math.PI/2,s=!0,c=null,l=!0,u=!0,d=null,f=null,p=!1,m=null,h=e&&e.symmetricalTextCentre?e.symmetricalTextCentre:!1,g={},_=e&&e.colourScheme?e.colourScheme:e&&e.colorScheme?e.colorScheme:[`#1f77b4`,`#ff7f0e`,`#2ca02c`,`#d62728`,`#9467bd`,`#8c564b`,`#e377c2`,`#7f7f7f`,`#bcbd22`,`#17becf`],v=0,y=function(e){if(e in g)return g[e];var t=g[e]=_[v];return v+=1,v>=_.length&&(v=0),t},b=ee,x=B;function S(g){let _=g.datum(),v=new Set;_.forEach(e=>{e.size==0&&e.sets.length==1&&v.add(e.sets[0])}),_=_.filter(e=>!e.sets.some(e=>v.has(e)));let S={},C={};if(_.length>0){let e=b(_,{lossFunction:x,distinct:p});s&&(e=de(e,o,f)),S=fe(e,n,r,i,c),C=ve(S,_,h)}let w={};_.forEach(e=>{e.label&&(w[e.sets]=e.label)});function T(e){if(e.sets in w)return w[e.sets];if(e.sets.length==1)return``+e.sets[0]}g.selectAll(`svg`).data([S]).enter().append(`svg`);let E=g.select(`svg`);t?E.attr(`viewBox`,`0 0 ${n} ${r}`):E.attr(`width`,n).attr(`height`,r);let D={},O=!1;E.selectAll(`.venn-area path`).each(function(e){let t=this.getAttribute(`d`);e.sets.length==1&&t&&!p&&(O=!0,D[e.sets[0]]=be(t))});function k(e){return t=>Ce(e.sets.map(e=>{let i=D[e],a=S[e];return i||={x:n/2,y:r/2,radius:1},a||={x:n/2,y:r/2,radius:1},{x:i.x*(1-t)+a.x*t,y:i.y*(1-t)+a.y*t,radius:i.radius*(1-t)+a.radius*t}}),m)}let A=E.selectAll(`.venn-area`).data(_,e=>e.sets),j=A.enter().append(`g`).attr(`class`,e=>`venn-area venn-${e.sets.length==1?`circle`:`intersection`}${e.colour||e.color?` venn-coloured`:``}`).attr(`data-venn-sets`,e=>e.sets.join(`_`)),M=j.append(`path`),N=j.append(`text`).attr(`class`,`label`).text(e=>T(e)).attr(`text-anchor`,`middle`).attr(`dy`,`.35em`).attr(`x`,n/2).attr(`y`,r/2);u&&(M.style(`fill-opacity`,`0`).filter(e=>e.sets.length==1).style(`fill`,e=>e.colour?e.colour:e.color?e.color:y(e.sets)).style(`fill-opacity`,`.25`),N.style(`fill`,t=>t.colour||t.color?`#FFF`:e.textFill?e.textFill:t.sets.length==1?y(t.sets):`#444`));function P(e){return typeof e.transition==`function`?e.transition(`venn`).duration(a):e}let F=g;O&&typeof F.transition==`function`?(F=P(g),F.selectAll(`path`).attrTween(`d`,k)):F.selectAll(`path`).attr(`d`,e=>Ce(e.sets.map(e=>S[e])),m);let I=F.selectAll(`text`).filter(e=>e.sets in C).text(e=>T(e)).attr(`x`,e=>Math.floor(C[e.sets].x)).attr(`y`,e=>Math.floor(C[e.sets].y));l&&(O?`on`in I?I.on(`end`,H(S,T)):I.each(`end`,H(S,T)):I.each(H(S,T)));let L=P(A.exit()).remove();typeof A.transition==`function`&&L.selectAll(`path`).attrTween(`d`,k);let R=L.selectAll(`text`).attr(`x`,n/2).attr(`y`,r/2);return d!==null&&(N.style(`font-size`,`0px`),I.style(`font-size`,d),R.style(`font-size`,`0px`)),{circles:S,textCentres:C,nodes:A,enter:j,update:F,exit:L}}return S.wrap=function(e){return arguments.length?(l=e,S):l},S.useViewBox=function(){return t=!0,S},S.width=function(e){return arguments.length?(n=e,S):n},S.height=function(e){return arguments.length?(r=e,S):r},S.padding=function(e){return arguments.length?(i=e,S):i},S.distinct=function(e){return arguments.length?(p=e,S):p},S.colours=function(e){return arguments.length?(y=e,S):y},S.colors=function(e){return arguments.length?(y=e,S):y},S.fontSize=function(e){return arguments.length?(d=e,S):d},S.round=function(e){return arguments.length?(m=e,S):m},S.duration=function(e){return arguments.length?(a=e,S):a},S.layoutFunction=function(e){return arguments.length?(b=e,S):b},S.normalize=function(e){return arguments.length?(s=e,S):s},S.scaleToFit=function(e){return arguments.length?(c=e,S):c},S.styled=function(e){return arguments.length?(u=e,S):u},S.orientation=function(e){return arguments.length?(o=e,S):o},S.orientationOrder=function(e){return arguments.length?(f=e,S):f},S.lossFunction=function(e){return arguments.length?(x=e==="default"?B:e===`logRatio`?ce:e,S):x},S}function H(e,t){return function(n){let r=this,i=e[n.sets[0]].radius||50,a=t(n)||``,o=a.split(/\s+/).reverse(),s=(a.length+o.length)/3,c=o.pop(),l=[c],u=0,d=1.1;r.textContent=null;let f=[];function p(e){let t=r.ownerDocument.createElementNS(r.namespaceURI,`tspan`);return t.textContent=e,f.push(t),r.append(t),t}let m=p(c);for(;c=o.pop(),c;){l.push(c);let e=l.join(` `);m.textContent=e,e.length>s&&m.getComputedTextLength()>i&&(l.pop(),m.textContent=l.join(` `),l=[c],m=p(c),u++)}let h=.35-u*d/2,g=r.getAttribute(`x`),_=r.getAttribute(`y`);f.forEach((e,t)=>{e.setAttribute(`x`,g),e.setAttribute(`y`,_),e.setAttribute(`dy`,`${h+t*d}em`)})}}function U(e,t,n){let r=t[0].radius-T(t[0],e);for(let n=1;n=a&&(i=r[n],a=o)}let o=I(n=>-1*U({x:n[0],y:n[1]},e,t),[i.x,i.y],{maxIterations:500,minErrorDelta:1e-10}).x,s={x:n?0:o[0],y:o[1]},c=!0;for(let t of e)if(T(s,t)>t.radius){c=!1;break}for(let e of t)if(T(s,e)e.p1))}function _e(e){let t={},n=Object.keys(e);for(let e of n)t[e]=[];for(let r=0;r0&&console.log(`WARNING: area `+o+` not represented on screen`)}return r}function ye(e,t,n){let r=[];return r.push(` +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,b as o,c as s,et as c,f as l,nt as u,rt as d,tt as f,v as p,w as m,y as h}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as g}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as _}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as v}from"./rough.esm-CSKSodPl.js";var y=(e,t)=>u(e,`a`,-t),b=1e-10;function x(e,t){let n=C(e),r=n.filter(t=>S(t,e)),i=0,a=0,o=[];if(r.length>1){let t=O(r);for(let e=0;et.angle-e.angle);let n=r[r.length-1];for(let t=0;tr.radius*2&&(d=r.radius*2),(l==null||l.width>d)&&(l={circle:r,width:d,p1:s,p2:n,large:d>r.radius,sweep:!0})}l!=null&&(o.push(l),i+=w(l.circle.radius,l.width),n=s)}}else{let t=e[0];for(let n=1;nMath.abs(t.radius-e[r].radius)){n=!0;break}n?i=a=0:(i=t.radius*t.radius*Math.PI,o.push({circle:t,p1:{x:t.x,y:t.y+t.radius},p2:{x:t.x-b,y:t.y+t.radius},width:t.radius*2,large:!0,sweep:!0}))}return a/=2,t&&(t.area=i+a,t.arcArea=i,t.polygonArea=a,t.arcs=o,t.innerPoints=r,t.intersectionPoints=n),i+a}function S(e,t){return t.every(t=>T(e,t)=e+t)return 0;if(n<=Math.abs(e-t))return Math.PI*Math.min(e,t)*Math.min(e,t);let r=e-(n*n-t*t+e*e)/(2*n),i=t-(n*n-e*e+t*t)/(2*n);return w(e,r)+w(t,i)}function D(e,t){let n=T(e,t),r=e.radius,i=t.radius;if(n>=r+i||n<=Math.abs(r-i))return[];let a=(r*r-i*i+n*n)/(2*n),o=Math.sqrt(r*r-a*a),s=e.x+a*(t.x-e.x)/n,c=e.y+a*(t.y-e.y)/n,l=-(t.y-e.y)*(o/n),u=-(t.x-e.x)*(o/n);return[{x:s+l,y:c-u},{x:s-l,y:c+u}]}function O(e){let t={x:0,y:0};for(let n of e)t.x+=n.x,t.y+=n.y;return t.x/=e.length,t.y/=e.length,t}function k(e,t,n,r){r||={};let i=r.maxIterations||100,a=r.tolerance||1e-10,o=e(t),s=e(n),c=n-t;if(o*s>0)throw`Initial bisect points must have opposite signs`;if(o===0)return t;if(s===0)return n;for(let n=0;n=0&&(t=n),Math.abs(c)A(t))}function M(e,t){let n=0;for(let r=0;re.fx-t.fx,_=t.slice(),v=t.slice(),y=t.slice(),b=t.slice();for(let t=0;t{let t=e.slice();return t.fx=e.fx,t.id=e.id,t});e.sort((e,t)=>e.id-t.id),n.history.push({x:m[0].slice(),fx:m[0].fx,simplex:e})}f=0;for(let e=0;e=m[p-1].fx){let n=!1;if(v.fx>t.fx?(F(y,1+u,_,-u,t),y.fx=e(y),y.fx=1)break;for(let t=1;ts+a*i*c||l>=p)f=i;else{if(Math.abs(d)<=-o*c)return i;d*(f-u)>=0&&(f=u),u=i,p=l}return 0}for(let m=0;m<10;++m){if(F(r.x,1,n.x,i,t),l=r.fx=e(r.x,r.fxprime),d=M(r.fxprime,t),l>s+a*i*c||m&&l>=u)return p(f,i,u);if(Math.abs(d)<=-o*c)return i;if(d>=0)return p(i,f,l);u=l,f=i,i*=2}return i}function R(e,t,n){let r={x:t.slice(),fx:0,fxprime:t.slice()},i={x:t.slice(),fx:0,fxprime:t.slice()},a=t.slice(),o,s,c=1,l;n||={},l=n.maxIterations||t.length*20,r.fx=e(r.x,r.fxprime),o=r.fxprime.slice(),P(o,r.fxprime,-1);for(let t=0;t{let t={};for(let n=0;nE(e,t,r)-n,0,e+t)}function ne(e,t={}){let n=t.distinct,r=e.map(e=>Object.assign({},e));function i(e){return e.join(`;`)}if(n){let e=new Map;for(let t of r)for(let n=0;ne===t?0:ee.sets.length===2).forEach(e=>{let a=n[e.sets[0]],o=n[e.sets[1]],s=z(Math.sqrt(t[a].size/Math.PI),Math.sqrt(t[o].size/Math.PI),e.size);r[a][o]=r[o][a]=s;let c=0;e.size+1e-10>=Math.min(t[a].size,t[o].size)?c=1:e.size<=1e-10&&(c=-1),i[a][o]=i[o][a]=c}),{distances:r,constraints:i}}function ie(e,t,n,r){for(let e=0;e0&&m<=d||f<0&&m>=d||(i+=2*h*h,t[2*a]+=4*h*(o-l),t[2*a+1]+=4*h*(s-u),t[2*c]+=4*h*(l-o),t[2*c+1]+=4*h*(u-s))}}return i}function ae(e,t={}){let n=se(e,t),r=t.lossFunction||B;if(e.length>=8){let i=oe(e,t),a=r(i,e),o=r(n,e);a+1e-8e.map(e=>e/s));let c=(e,t)=>ie(e,t,a,o),l=null;for(let e=0;ee.sets.length===2);for(let t of e){let e=t.weight==null?1:t.weight,n=t.sets[0],a=t.sets[1];t.size+te>=Math.min(r[n].size,r[a].size)&&(e=0),i[n].push({set:a,size:t.size,weight:e}),i[a].push({set:n,size:t.size,weight:e})}let a=[];Object.keys(i).forEach(e=>{let t=0;for(let n=0;ne[t]));let i=r.weight==null?1:r.weight;n+=i*(t-r.size)*(t-r.size)}return n}function ce(e,t){let n=0;for(let r of t){if(r.sets.length===1)continue;let t;if(r.sets.length===2){let n=e[r.sets[0]],i=e[r.sets[1]];t=E(n.radius,i.radius,T(n,i))}else t=x(r.sets.map(t=>e[t]));let i=r.weight==null?1:r.weight,a=Math.log((t+1)/(r.size+1));n+=i*a*a}return n}function le(e,t,n){if(n==null?e.sort((e,t)=>t.radius-e.radius):e.sort(n),e.length>0){let t=e[0].x,n=e[0].y;for(let r of e)r.x-=t,r.y-=n}if(e.length===2&&T(e[0],e[1])1){let n=Math.atan2(e[1].x,e[1].y)-t,r=Math.cos(n),i=Math.sin(n);for(let t of e){let e=t.x,n=t.y;t.x=r*e-i*n,t.y=i*e+r*n}}if(e.length>2){let n=Math.atan2(e[2].x,e[2].y)-t;for(;n<0;)n+=2*Math.PI;for(;n>2*Math.PI;)n-=2*Math.PI;if(n>Math.PI){let t=e[1].y/(1e-10+e[1].x);for(let n of e){var r=(n.x+t*n.y)/(1+t*t);n.x=2*r-n.x,n.y=2*r*t-n.y}}}}function ue(e){e.forEach(e=>{e.parent=e});function t(e){return e.parent!==e&&(e.parent=t(e.parent)),e.parent}function n(e,n){let r=t(e);r.parent=t(n)}for(let t=0;t{delete e.parent}),Array.from(r.values())}function V(e){let t=t=>({max:e.reduce((e,n)=>Math.max(e,n[t]+n.radius),-1/0),min:e.reduce((e,n)=>Math.min(e,n[t]-n.radius),1/0)});return{xRange:t(`x`),yRange:t(`y`)}}function de(e,t,n){t??=Math.PI/2;let r=me(e).map(e=>Object.assign({},e)),i=ue(r);for(let e of i){le(e,t,n);let r=V(e);e.size=(r.xRange.max-r.xRange.min)*(r.yRange.max-r.yRange.min),e.bounds=r}i.sort((e,t)=>t.size-e.size),r=i[0];let a=r.bounds,o=(a.xRange.max-a.xRange.min)/50;function s(e,t,n){if(!e)return;let i=e.bounds,s,c;if(t)s=a.xRange.max-i.xRange.min+o;else{s=a.xRange.max-i.xRange.max;let e=(i.xRange.max-i.xRange.min)/2-(a.xRange.max-a.xRange.min)/2;e<0&&(s+=e)}if(n)c=a.yRange.max-i.yRange.min+o;else{c=a.yRange.max-i.yRange.max;let e=(i.yRange.max-i.yRange.min)/2-(a.yRange.max-a.yRange.min)/2;e<0&&(c+=e)}for(let t of e)t.x+=s,t.y+=c,r.push(t)}let c=1;for(;c({radius:u*e.radius,x:r+d+(e.x-o.min)*u,y:r+f+(e.y-s.min)*u,setid:e.setid})))}function pe(e){let t={};for(let n of e)t[n.setid]=n;return t}function me(e){return Object.keys(e).map(t=>Object.assign(e[t],{setid:t}))}function he(e={}){let t=!1,n=600,r=350,i=15,a=1e3,o=Math.PI/2,s=!0,c=null,l=!0,u=!0,d=null,f=null,p=!1,m=null,h=e&&e.symmetricalTextCentre?e.symmetricalTextCentre:!1,g={},_=e&&e.colourScheme?e.colourScheme:e&&e.colorScheme?e.colorScheme:[`#1f77b4`,`#ff7f0e`,`#2ca02c`,`#d62728`,`#9467bd`,`#8c564b`,`#e377c2`,`#7f7f7f`,`#bcbd22`,`#17becf`],v=0,y=function(e){if(e in g)return g[e];var t=g[e]=_[v];return v+=1,v>=_.length&&(v=0),t},b=ee,x=B;function S(g){let _=g.datum(),v=new Set;_.forEach(e=>{e.size==0&&e.sets.length==1&&v.add(e.sets[0])}),_=_.filter(e=>!e.sets.some(e=>v.has(e)));let S={},C={};if(_.length>0){let e=b(_,{lossFunction:x,distinct:p});s&&(e=de(e,o,f)),S=fe(e,n,r,i,c),C=ve(S,_,h)}let w={};_.forEach(e=>{e.label&&(w[e.sets]=e.label)});function T(e){if(e.sets in w)return w[e.sets];if(e.sets.length==1)return``+e.sets[0]}g.selectAll(`svg`).data([S]).enter().append(`svg`);let E=g.select(`svg`);t?E.attr(`viewBox`,`0 0 ${n} ${r}`):E.attr(`width`,n).attr(`height`,r);let D={},O=!1;E.selectAll(`.venn-area path`).each(function(e){let t=this.getAttribute(`d`);e.sets.length==1&&t&&!p&&(O=!0,D[e.sets[0]]=be(t))});function k(e){return t=>Ce(e.sets.map(e=>{let i=D[e],a=S[e];return i||={x:n/2,y:r/2,radius:1},a||={x:n/2,y:r/2,radius:1},{x:i.x*(1-t)+a.x*t,y:i.y*(1-t)+a.y*t,radius:i.radius*(1-t)+a.radius*t}}),m)}let A=E.selectAll(`.venn-area`).data(_,e=>e.sets),j=A.enter().append(`g`).attr(`class`,e=>`venn-area venn-${e.sets.length==1?`circle`:`intersection`}${e.colour||e.color?` venn-coloured`:``}`).attr(`data-venn-sets`,e=>e.sets.join(`_`)),M=j.append(`path`),N=j.append(`text`).attr(`class`,`label`).text(e=>T(e)).attr(`text-anchor`,`middle`).attr(`dy`,`.35em`).attr(`x`,n/2).attr(`y`,r/2);u&&(M.style(`fill-opacity`,`0`).filter(e=>e.sets.length==1).style(`fill`,e=>e.colour?e.colour:e.color?e.color:y(e.sets)).style(`fill-opacity`,`.25`),N.style(`fill`,t=>t.colour||t.color?`#FFF`:e.textFill?e.textFill:t.sets.length==1?y(t.sets):`#444`));function P(e){return typeof e.transition==`function`?e.transition(`venn`).duration(a):e}let F=g;O&&typeof F.transition==`function`?(F=P(g),F.selectAll(`path`).attrTween(`d`,k)):F.selectAll(`path`).attr(`d`,e=>Ce(e.sets.map(e=>S[e])),m);let I=F.selectAll(`text`).filter(e=>e.sets in C).text(e=>T(e)).attr(`x`,e=>Math.floor(C[e.sets].x)).attr(`y`,e=>Math.floor(C[e.sets].y));l&&(O?`on`in I?I.on(`end`,H(S,T)):I.each(`end`,H(S,T)):I.each(H(S,T)));let L=P(A.exit()).remove();typeof A.transition==`function`&&L.selectAll(`path`).attrTween(`d`,k);let R=L.selectAll(`text`).attr(`x`,n/2).attr(`y`,r/2);return d!==null&&(N.style(`font-size`,`0px`),I.style(`font-size`,d),R.style(`font-size`,`0px`)),{circles:S,textCentres:C,nodes:A,enter:j,update:F,exit:L}}return S.wrap=function(e){return arguments.length?(l=e,S):l},S.useViewBox=function(){return t=!0,S},S.width=function(e){return arguments.length?(n=e,S):n},S.height=function(e){return arguments.length?(r=e,S):r},S.padding=function(e){return arguments.length?(i=e,S):i},S.distinct=function(e){return arguments.length?(p=e,S):p},S.colours=function(e){return arguments.length?(y=e,S):y},S.colors=function(e){return arguments.length?(y=e,S):y},S.fontSize=function(e){return arguments.length?(d=e,S):d},S.round=function(e){return arguments.length?(m=e,S):m},S.duration=function(e){return arguments.length?(a=e,S):a},S.layoutFunction=function(e){return arguments.length?(b=e,S):b},S.normalize=function(e){return arguments.length?(s=e,S):s},S.scaleToFit=function(e){return arguments.length?(c=e,S):c},S.styled=function(e){return arguments.length?(u=e,S):u},S.orientation=function(e){return arguments.length?(o=e,S):o},S.orientationOrder=function(e){return arguments.length?(f=e,S):f},S.lossFunction=function(e){return arguments.length?(x=e==="default"?B:e===`logRatio`?ce:e,S):x},S}function H(e,t){return function(n){let r=this,i=e[n.sets[0]].radius||50,a=t(n)||``,o=a.split(/\s+/).reverse(),s=(a.length+o.length)/3,c=o.pop(),l=[c],u=0,d=1.1;r.textContent=null;let f=[];function p(e){let t=r.ownerDocument.createElementNS(r.namespaceURI,`tspan`);return t.textContent=e,f.push(t),r.append(t),t}let m=p(c);for(;c=o.pop(),c;){l.push(c);let e=l.join(` `);m.textContent=e,e.length>s&&m.getComputedTextLength()>i&&(l.pop(),m.textContent=l.join(` `),l=[c],m=p(c),u++)}let h=.35-u*d/2,g=r.getAttribute(`x`),_=r.getAttribute(`y`);f.forEach((e,t)=>{e.setAttribute(`x`,g),e.setAttribute(`y`,_),e.setAttribute(`dy`,`${h+t*d}em`)})}}function U(e,t,n){let r=t[0].radius-T(t[0],e);for(let n=1;n=a&&(i=r[n],a=o)}let o=I(n=>-1*U({x:n[0],y:n[1]},e,t),[i.x,i.y],{maxIterations:500,minErrorDelta:1e-10}).x,s={x:n?0:o[0],y:o[1]},c=!0;for(let t of e)if(T(s,t)>t.radius){c=!1;break}for(let e of t)if(T(s,e)e.p1))}function _e(e){let t={},n=Object.keys(e);for(let e of n)t[e]=[];for(let r=0;r0&&console.log(`WARNING: area `+o+` not represented on screen`)}return r}function ye(e,t,n){let r=[];return r.push(` M`,e,t),r.push(` m`,-n,0),r.push(` a`,n,n,0,1,0,n*2,0),r.push(` diff --git a/.vercel/output/static/assets/wardleyDiagram-EHGQE667-CrSiGNM9.js b/.vercel/output/static/assets/wardleyDiagram-EHGQE667-BewauNW1.js similarity index 98% rename from .vercel/output/static/assets/wardleyDiagram-EHGQE667-CrSiGNM9.js rename to .vercel/output/static/assets/wardleyDiagram-EHGQE667-BewauNW1.js index a03833e..eddd590 100644 --- a/.vercel/output/static/assets/wardleyDiagram-EHGQE667-CrSiGNM9.js +++ b/.vercel/output/static/assets/wardleyDiagram-EHGQE667-BewauNW1.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{i as p}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as m}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-AdnthA1k.js";var _=e((e,t)=>{let n=e<=1?e*100:e;if(n<0||n>100)throw Error(`${t} must be between 0-1 (decimal) or 0-100 (percentage). Received: ${e}`);return n},`toPercent`),v=e((e,t,n)=>({x:_(t,`${n} evolution`),y:_(e,`${n} visibility`)}),`toCoordinates`),y=e(e=>{if(e){if(e===`+<>`)return`bidirectional`;if(e===`+<`)return`backward`;if(e===`+>`)return`forward`}},`getFlowFromPort`),b=e(e=>{if(!e?.startsWith(`+`))return{};let t=/^\+'([^']*)'/.exec(e)?.[1];return e.includes(`<>`)?{flow:`bidirectional`,label:t}:e.includes(`<`)?{flow:`backward`,label:t}:e.includes(`>`)?{flow:`forward`,label:t}:{label:t}},`extractFlowFromArrow`),x=e((e,t)=>{if(h(e,t),e.size&&t.setSize(e.size.width,e.size.height),e.evolution){let n=e.evolution.stages.map(e=>e.secondName?`${e.name.trim()} / ${e.secondName.trim()}`:e.name.trim()),r=e.evolution.stages.filter(e=>e.boundary!==void 0).map(e=>e.boundary);t.updateAxes({stages:n,stageBoundaries:r})}if(e.anchors.forEach(e=>{let n=v(e.visibility,e.evolution,`Anchor "${e.name}"`);t.addNode(e.name,e.name,n.x,n.y,`anchor`)}),e.components.forEach(e=>{let n=v(e.visibility,e.evolution,`Component "${e.name}"`),r=e.label?(e.label.negX?-1:1)*e.label.offsetX:void 0,i=e.label?(e.label.negY?-1:1)*e.label.offsetY:void 0,a=e.decorator?.strategy;t.addNode(e.name,e.name,n.x,n.y,`component`,r,i,e.inertia,a)}),e.notes.forEach(e=>{let n=v(e.visibility,e.evolution,`Note "${e.text}"`);t.addNote(e.text,n.x,n.y)}),e.pipelines.forEach(e=>{let n=t.getNode(e.parent);if(!n||typeof n.y!=`number`)throw Error(`Pipeline "${e.parent}" must reference an existing component with coordinates.`);let r=n.y;t.startPipeline(e.parent),e.components.forEach(n=>{let i=`${e.parent}_${n.name}`,a=n.label?(n.label.negX?-1:1)*n.label.offsetX:void 0,o=n.label?(n.label.negY?-1:1)*n.label.offsetY:void 0,s=_(n.evolution,`Pipeline component "${n.name}" evolution`);t.addNode(i,n.name,s,r,`pipeline-component`,a,o),t.addPipelineComponent(e.parent,i)})}),e.links.forEach(e=>{let n=!!e.arrow&&(e.arrow.includes(`-.->`)||e.arrow.includes(`.-.`)),r=y(e.fromPort)??y(e.toPort),{flow:i,label:a}=b(e.arrow);!r&&i&&(r=i);let o=e.linkLabel,s=a??o;t.addLink(t.resolveNodeId(e.from),t.resolveNodeId(e.to),n,s,r)}),e.evolves.forEach(e=>{let n=t.getNode(e.component);if(n?.y!==void 0){let r=_(e.target,`Evolve target for "${e.component}"`);t.addTrend(e.component,r,n.y)}}),e.annotations.length>0){let n=e.annotations[0],r=v(n.x,n.y,`Annotations box`);t.setAnnotationsBox(r.x,r.y)}e.annotation.forEach(e=>{let n=v(e.x,e.y,`Annotation ${e.number}`);t.addAnnotation(e.number,[{x:n.x,y:n.y}],e.text)}),e.accelerators.forEach(e=>{let n=v(e.x,e.y,`Accelerator "${e.name}"`);t.addAccelerator(e.name,n.x,n.y)}),e.deaccelerators.forEach(e=>{let n=v(e.x,e.y,`Deaccelerator "${e.name}"`);t.addDeaccelerator(e.name,n.x,n.y)})},`populateDb`),S={parser:{yy:void 0},parse:e(async e=>{let n=await g(`wardley`,e);t.debug(n);let r=S.parser?.yy;if(!r||typeof r.addNode!=`function`)throw Error(`parser.parser?.yy was not a WardleyDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);x(n,r)},`parse`)},C=new class{constructor(){this.nodes=new Map,this.links=[],this.trends=new Map,this.pipelines=new Map,this.annotations=[],this.notes=[],this.accelerators=[],this.deaccelerators=[],this.axes={}}static{e(this,`WardleyBuilder`)}addNode(e){let t=this.nodes.get(e.id)??{id:e.id,label:e.label},n={...t,...e,className:e.className??t.className,labelOffsetX:e.labelOffsetX??t.labelOffsetX,labelOffsetY:e.labelOffsetY??t.labelOffsetY};this.nodes.set(e.id,n)}addLink(e){this.links.push(e)}addTrend(e){this.trends.set(e.nodeId,e)}startPipeline(e){this.pipelines.set(e,{nodeId:e,componentIds:[]});let t=this.nodes.get(e);t&&(t.isPipelineParent=!0)}addPipelineComponent(e,t){let n=this.pipelines.get(e);n&&n.componentIds.push(t);let r=this.nodes.get(t);r&&(r.inPipeline=!0)}addAnnotation(e){this.annotations.push(e)}addNote(e){this.notes.push(e)}addAccelerator(e){this.accelerators.push(e)}addDeaccelerator(e){this.deaccelerators.push(e)}setAnnotationsBox(e,t){this.annotationsBox={x:e,y:t}}setAxes(e){this.axes={...this.axes,...e}}setSize(e,t){this.size={width:e,height:t}}getNode(e){return this.nodes.get(e)}resolveNodeId(e){if(this.nodes.has(e))return e;for(let[t,n]of this.nodes)if(n.label===e)return t;return e}build(){let e=[];for(let t of this.nodes.values()){if(typeof t.x!=`number`||typeof t.y!=`number`)throw Error(`Node "${t.label}" is missing coordinates`);e.push(t)}return{nodes:e,links:[...this.links],trends:[...this.trends.values()],pipelines:[...this.pipelines.values()],annotations:[...this.annotations],notes:[...this.notes],accelerators:[...this.accelerators],deaccelerators:[...this.deaccelerators],annotationsBox:this.annotationsBox,axes:{...this.axes},size:this.size}}clear(){this.nodes.clear(),this.links=[],this.trends.clear(),this.pipelines.clear(),this.annotations=[],this.notes=[],this.accelerators=[],this.deaccelerators=[],this.annotationsBox=void 0,this.axes={},this.size=void 0}};function w(){return d()[`wardley-beta`]}e(w,`getConfig`);function T(e,t,n,r,i,a,o,s,c){C.addNode({id:e,label:t,x:n,y:r,className:i,labelOffsetX:a,labelOffsetY:o,inertia:s,sourceStrategy:c})}e(T,`addNode`);function E(e,t,n=!1,r,i){C.addLink({source:e,target:t,dashed:n,label:r,flow:i})}e(E,`addLink`);function D(e,t,n){C.addTrend({nodeId:e,targetX:t,targetY:n})}e(D,`addTrend`);function O(e,t,n){C.addAnnotation({number:e,coordinates:t,text:n})}e(O,`addAnnotation`);function k(e,t,n){C.addNote({text:e,x:t,y:n})}e(k,`addNote`);function A(e,t,n){C.addAccelerator({name:e,x:t,y:n})}e(A,`addAccelerator`);function j(e,t,n){C.addDeaccelerator({name:e,x:t,y:n})}e(j,`addDeaccelerator`);function M(e,t){C.setAnnotationsBox(e,t)}e(M,`setAnnotationsBox`);function N(e,t){C.setSize(e,t)}e(N,`setSize`);function P(e){C.startPipeline(e)}e(P,`startPipeline`);function F(e,t){C.addPipelineComponent(e,t)}e(F,`addPipelineComponent`);function I(e){C.setAxes(e)}e(I,`updateAxes`);function L(e){return C.getNode(e)}e(L,`getNode`);function R(e){return C.resolveNodeId(e)}e(R,`resolveNodeId`);function z(){return C.build()}e(z,`getWardleyData`);function B(){C.clear(),o()}e(B,`clear`);var V={getConfig:w,addNode:T,addLink:E,addTrend:D,addAnnotation:O,addNote:k,addAccelerator:A,addDeaccelerator:j,setAnnotationsBox:M,setSize:N,startPipeline:P,addPipelineComponent:F,updateAxes:I,getNode:L,resolveNodeId:R,getWardleyData:z,clear:B,setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:u,getAccDescription:l,setAccDescription:r},H=[`Genesis`,`Custom Built`,`Product`,`Commodity`],U=e(()=>{let{themeVariables:e}=d();return{backgroundColor:e.wardley?.backgroundColor??e.background??`#fff`,axisColor:e.wardley?.axisColor??`#000`,axisTextColor:e.wardley?.axisTextColor??e.primaryTextColor??`#222`,gridColor:e.wardley?.gridColor??`rgba(100, 100, 100, 0.2)`,componentFill:e.wardley?.componentFill??`#fff`,componentStroke:e.wardley?.componentStroke??`#000`,componentLabelColor:e.wardley?.componentLabelColor??e.primaryTextColor??`#222`,linkStroke:e.wardley?.linkStroke??`#000`,evolutionStroke:e.wardley?.evolutionStroke??`#dc3545`,annotationStroke:e.wardley?.annotationStroke??`#000`,annotationTextColor:e.wardley?.annotationTextColor??e.primaryTextColor??`#222`,annotationFill:e.wardley?.annotationFill??e.background??`#fff`}},`getTheme`),W=e(()=>{let e=d()[`wardley-beta`];return{width:e?.width??900,height:e?.height??600,padding:e?.padding??48,nodeRadius:e?.nodeRadius??6,nodeLabelOffset:e?.nodeLabelOffset??8,axisFontSize:e?.axisFontSize??12,labelFontSize:e?.labelFontSize??10,showGrid:e?.showGrid??!1,useMaxWidth:e?.useMaxWidth??!0}},`getConfigValues`),G={parser:S,db:V,renderer:{draw:e((n,r,i,a)=>{t.debug(`Rendering Wardley map +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-Z7xZAZRH.js";var _=e((e,t)=>{let n=e<=1?e*100:e;if(n<0||n>100)throw Error(`${t} must be between 0-1 (decimal) or 0-100 (percentage). Received: ${e}`);return n},`toPercent`),v=e((e,t,n)=>({x:_(t,`${n} evolution`),y:_(e,`${n} visibility`)}),`toCoordinates`),y=e(e=>{if(e){if(e===`+<>`)return`bidirectional`;if(e===`+<`)return`backward`;if(e===`+>`)return`forward`}},`getFlowFromPort`),b=e(e=>{if(!e?.startsWith(`+`))return{};let t=/^\+'([^']*)'/.exec(e)?.[1];return e.includes(`<>`)?{flow:`bidirectional`,label:t}:e.includes(`<`)?{flow:`backward`,label:t}:e.includes(`>`)?{flow:`forward`,label:t}:{label:t}},`extractFlowFromArrow`),x=e((e,t)=>{if(h(e,t),e.size&&t.setSize(e.size.width,e.size.height),e.evolution){let n=e.evolution.stages.map(e=>e.secondName?`${e.name.trim()} / ${e.secondName.trim()}`:e.name.trim()),r=e.evolution.stages.filter(e=>e.boundary!==void 0).map(e=>e.boundary);t.updateAxes({stages:n,stageBoundaries:r})}if(e.anchors.forEach(e=>{let n=v(e.visibility,e.evolution,`Anchor "${e.name}"`);t.addNode(e.name,e.name,n.x,n.y,`anchor`)}),e.components.forEach(e=>{let n=v(e.visibility,e.evolution,`Component "${e.name}"`),r=e.label?(e.label.negX?-1:1)*e.label.offsetX:void 0,i=e.label?(e.label.negY?-1:1)*e.label.offsetY:void 0,a=e.decorator?.strategy;t.addNode(e.name,e.name,n.x,n.y,`component`,r,i,e.inertia,a)}),e.notes.forEach(e=>{let n=v(e.visibility,e.evolution,`Note "${e.text}"`);t.addNote(e.text,n.x,n.y)}),e.pipelines.forEach(e=>{let n=t.getNode(e.parent);if(!n||typeof n.y!=`number`)throw Error(`Pipeline "${e.parent}" must reference an existing component with coordinates.`);let r=n.y;t.startPipeline(e.parent),e.components.forEach(n=>{let i=`${e.parent}_${n.name}`,a=n.label?(n.label.negX?-1:1)*n.label.offsetX:void 0,o=n.label?(n.label.negY?-1:1)*n.label.offsetY:void 0,s=_(n.evolution,`Pipeline component "${n.name}" evolution`);t.addNode(i,n.name,s,r,`pipeline-component`,a,o),t.addPipelineComponent(e.parent,i)})}),e.links.forEach(e=>{let n=!!e.arrow&&(e.arrow.includes(`-.->`)||e.arrow.includes(`.-.`)),r=y(e.fromPort)??y(e.toPort),{flow:i,label:a}=b(e.arrow);!r&&i&&(r=i);let o=e.linkLabel,s=a??o;t.addLink(t.resolveNodeId(e.from),t.resolveNodeId(e.to),n,s,r)}),e.evolves.forEach(e=>{let n=t.getNode(e.component);if(n?.y!==void 0){let r=_(e.target,`Evolve target for "${e.component}"`);t.addTrend(e.component,r,n.y)}}),e.annotations.length>0){let n=e.annotations[0],r=v(n.x,n.y,`Annotations box`);t.setAnnotationsBox(r.x,r.y)}e.annotation.forEach(e=>{let n=v(e.x,e.y,`Annotation ${e.number}`);t.addAnnotation(e.number,[{x:n.x,y:n.y}],e.text)}),e.accelerators.forEach(e=>{let n=v(e.x,e.y,`Accelerator "${e.name}"`);t.addAccelerator(e.name,n.x,n.y)}),e.deaccelerators.forEach(e=>{let n=v(e.x,e.y,`Deaccelerator "${e.name}"`);t.addDeaccelerator(e.name,n.x,n.y)})},`populateDb`),S={parser:{yy:void 0},parse:e(async e=>{let n=await g(`wardley`,e);t.debug(n);let r=S.parser?.yy;if(!r||typeof r.addNode!=`function`)throw Error(`parser.parser?.yy was not a WardleyDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);x(n,r)},`parse`)},C=new class{constructor(){this.nodes=new Map,this.links=[],this.trends=new Map,this.pipelines=new Map,this.annotations=[],this.notes=[],this.accelerators=[],this.deaccelerators=[],this.axes={}}static{e(this,`WardleyBuilder`)}addNode(e){let t=this.nodes.get(e.id)??{id:e.id,label:e.label},n={...t,...e,className:e.className??t.className,labelOffsetX:e.labelOffsetX??t.labelOffsetX,labelOffsetY:e.labelOffsetY??t.labelOffsetY};this.nodes.set(e.id,n)}addLink(e){this.links.push(e)}addTrend(e){this.trends.set(e.nodeId,e)}startPipeline(e){this.pipelines.set(e,{nodeId:e,componentIds:[]});let t=this.nodes.get(e);t&&(t.isPipelineParent=!0)}addPipelineComponent(e,t){let n=this.pipelines.get(e);n&&n.componentIds.push(t);let r=this.nodes.get(t);r&&(r.inPipeline=!0)}addAnnotation(e){this.annotations.push(e)}addNote(e){this.notes.push(e)}addAccelerator(e){this.accelerators.push(e)}addDeaccelerator(e){this.deaccelerators.push(e)}setAnnotationsBox(e,t){this.annotationsBox={x:e,y:t}}setAxes(e){this.axes={...this.axes,...e}}setSize(e,t){this.size={width:e,height:t}}getNode(e){return this.nodes.get(e)}resolveNodeId(e){if(this.nodes.has(e))return e;for(let[t,n]of this.nodes)if(n.label===e)return t;return e}build(){let e=[];for(let t of this.nodes.values()){if(typeof t.x!=`number`||typeof t.y!=`number`)throw Error(`Node "${t.label}" is missing coordinates`);e.push(t)}return{nodes:e,links:[...this.links],trends:[...this.trends.values()],pipelines:[...this.pipelines.values()],annotations:[...this.annotations],notes:[...this.notes],accelerators:[...this.accelerators],deaccelerators:[...this.deaccelerators],annotationsBox:this.annotationsBox,axes:{...this.axes},size:this.size}}clear(){this.nodes.clear(),this.links=[],this.trends.clear(),this.pipelines.clear(),this.annotations=[],this.notes=[],this.accelerators=[],this.deaccelerators=[],this.annotationsBox=void 0,this.axes={},this.size=void 0}};function w(){return d()[`wardley-beta`]}e(w,`getConfig`);function T(e,t,n,r,i,a,o,s,c){C.addNode({id:e,label:t,x:n,y:r,className:i,labelOffsetX:a,labelOffsetY:o,inertia:s,sourceStrategy:c})}e(T,`addNode`);function E(e,t,n=!1,r,i){C.addLink({source:e,target:t,dashed:n,label:r,flow:i})}e(E,`addLink`);function D(e,t,n){C.addTrend({nodeId:e,targetX:t,targetY:n})}e(D,`addTrend`);function O(e,t,n){C.addAnnotation({number:e,coordinates:t,text:n})}e(O,`addAnnotation`);function k(e,t,n){C.addNote({text:e,x:t,y:n})}e(k,`addNote`);function A(e,t,n){C.addAccelerator({name:e,x:t,y:n})}e(A,`addAccelerator`);function j(e,t,n){C.addDeaccelerator({name:e,x:t,y:n})}e(j,`addDeaccelerator`);function M(e,t){C.setAnnotationsBox(e,t)}e(M,`setAnnotationsBox`);function N(e,t){C.setSize(e,t)}e(N,`setSize`);function P(e){C.startPipeline(e)}e(P,`startPipeline`);function F(e,t){C.addPipelineComponent(e,t)}e(F,`addPipelineComponent`);function I(e){C.setAxes(e)}e(I,`updateAxes`);function L(e){return C.getNode(e)}e(L,`getNode`);function R(e){return C.resolveNodeId(e)}e(R,`resolveNodeId`);function z(){return C.build()}e(z,`getWardleyData`);function B(){C.clear(),o()}e(B,`clear`);var V={getConfig:w,addNode:T,addLink:E,addTrend:D,addAnnotation:O,addNote:k,addAccelerator:A,addDeaccelerator:j,setAnnotationsBox:M,setSize:N,startPipeline:P,addPipelineComponent:F,updateAxes:I,getNode:L,resolveNodeId:R,getWardleyData:z,clear:B,setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:u,getAccDescription:l,setAccDescription:r},H=[`Genesis`,`Custom Built`,`Product`,`Commodity`],U=e(()=>{let{themeVariables:e}=d();return{backgroundColor:e.wardley?.backgroundColor??e.background??`#fff`,axisColor:e.wardley?.axisColor??`#000`,axisTextColor:e.wardley?.axisTextColor??e.primaryTextColor??`#222`,gridColor:e.wardley?.gridColor??`rgba(100, 100, 100, 0.2)`,componentFill:e.wardley?.componentFill??`#fff`,componentStroke:e.wardley?.componentStroke??`#000`,componentLabelColor:e.wardley?.componentLabelColor??e.primaryTextColor??`#222`,linkStroke:e.wardley?.linkStroke??`#000`,evolutionStroke:e.wardley?.evolutionStroke??`#dc3545`,annotationStroke:e.wardley?.annotationStroke??`#000`,annotationTextColor:e.wardley?.annotationTextColor??e.primaryTextColor??`#222`,annotationFill:e.wardley?.annotationFill??e.background??`#fff`}},`getTheme`),W=e(()=>{let e=d()[`wardley-beta`];return{width:e?.width??900,height:e?.height??600,padding:e?.padding??48,nodeRadius:e?.nodeRadius??6,nodeLabelOffset:e?.nodeLabelOffset??8,axisFontSize:e?.axisFontSize??12,labelFontSize:e?.labelFontSize??10,showGrid:e?.showGrid??!1,useMaxWidth:e?.useMaxWidth??!0}},`getConfigValues`),G={parser:S,db:V,renderer:{draw:e((n,r,i,a)=>{t.debug(`Rendering Wardley map `+n);let o=W(),s=U(),l=o.nodeRadius*1.6,u=a.db,d=u.getWardleyData(),f=u.getDiagramTitle(),p=d.size?.width??o.width,h=d.size?.height??o.height,g=m(r);g.selectAll(`*`).remove(),c(g,h,p,o.useMaxWidth),g.attr(`viewBox`,`0 0 ${p} ${h}`);let _=g.append(`g`).attr(`class`,`wardley-map`),v=g.append(`defs`);v.append(`marker`).attr(`id`,`arrow-${r}`).attr(`viewBox`,`0 0 10 10`).attr(`refX`,9).attr(`refY`,5).attr(`markerWidth`,6).attr(`markerHeight`,6).attr(`orient`,`auto-start-reverse`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`fill`,s.evolutionStroke).attr(`stroke`,`none`),v.append(`marker`).attr(`id`,`link-arrow-end-${r}`).attr(`viewBox`,`0 0 10 10`).attr(`refX`,9).attr(`refY`,5).attr(`markerWidth`,5).attr(`markerHeight`,5).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`fill`,s.linkStroke).attr(`stroke`,`none`),v.append(`marker`).attr(`id`,`link-arrow-start-${r}`).attr(`viewBox`,`0 0 10 10`).attr(`refX`,1).attr(`refY`,5).attr(`markerWidth`,5).attr(`markerHeight`,5).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 10 0 L 0 5 L 10 10 z`).attr(`fill`,s.linkStroke).attr(`stroke`,`none`),_.append(`rect`).attr(`class`,`wardley-background`).attr(`width`,p).attr(`height`,h).attr(`fill`,s.backgroundColor);let y=p-o.padding*2,b=h-o.padding*2;f&&_.append(`text`).attr(`class`,`wardley-title`).attr(`x`,p/2).attr(`y`,o.padding/2).attr(`fill`,s.axisTextColor).attr(`font-size`,o.axisFontSize*1.05).attr(`font-weight`,`bold`).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(f);let x=e(e=>o.padding+e/100*y,`projectX`),S=e(e=>h-o.padding-e/100*b,`projectY`),C=_.append(`g`).attr(`class`,`wardley-axes`);C.append(`line`).attr(`x1`,o.padding).attr(`x2`,p-o.padding).attr(`y1`,h-o.padding).attr(`y2`,h-o.padding).attr(`stroke`,s.axisColor).attr(`stroke-width`,1),C.append(`line`).attr(`x1`,o.padding).attr(`x2`,o.padding).attr(`y1`,o.padding).attr(`y2`,h-o.padding).attr(`stroke`,s.axisColor).attr(`stroke-width`,1);let w=d.axes.xLabel??`Evolution`,T=d.axes.yLabel??`Visibility`;C.append(`text`).attr(`class`,`wardley-axis-label wardley-axis-label-x`).attr(`x`,o.padding+y/2).attr(`y`,h-o.padding/4).attr(`fill`,s.axisTextColor).attr(`font-size`,o.axisFontSize).attr(`font-weight`,`bold`).attr(`text-anchor`,`middle`).text(w),C.append(`text`).attr(`class`,`wardley-axis-label wardley-axis-label-y`).attr(`x`,o.padding/3).attr(`y`,o.padding+b/2).attr(`fill`,s.axisTextColor).attr(`font-size`,o.axisFontSize).attr(`font-weight`,`bold`).attr(`text-anchor`,`middle`).attr(`transform`,`rotate(-90 ${o.padding/3} ${o.padding+b/2})`).text(T);let E=d.axes.stages&&d.axes.stages.length>0?d.axes.stages:H;if(E.length>0){let e=_.append(`g`).attr(`class`,`wardley-stages`),t=d.axes.stageBoundaries,n=[];if(t&&t.length===E.length){let e=0;t.forEach(t=>{n.push({start:e,end:t}),e=t})}else{let e=1/E.length;E.forEach((t,r)=>{n.push({start:r*e,end:(r+1)*e})})}E.forEach((t,r)=>{let i=n[r],a=o.padding+i.start*y,c=(a+(o.padding+i.end*y))/2;r>0&&e.append(`line`).attr(`x1`,a).attr(`x2`,a).attr(`y1`,o.padding).attr(`y2`,h-o.padding).attr(`stroke`,`#000`).attr(`stroke-width`,1).attr(`stroke-dasharray`,`5 5`).attr(`opacity`,.8),e.append(`text`).attr(`class`,`wardley-stage-label`).attr(`x`,c).attr(`y`,h-o.padding/1.5).attr(`fill`,s.axisTextColor).attr(`font-size`,o.axisFontSize-2).attr(`text-anchor`,`middle`).text(t)})}if(o.showGrid){let e=_.append(`g`).attr(`class`,`wardley-grid`);for(let t=1;t<4;t++){let n=t/4,r=o.padding+y*n;e.append(`line`).attr(`x1`,r).attr(`x2`,r).attr(`y1`,o.padding).attr(`y2`,h-o.padding).attr(`stroke`,s.gridColor).attr(`stroke-dasharray`,`2 6`),e.append(`line`).attr(`x1`,o.padding).attr(`x2`,p-o.padding).attr(`y1`,h-o.padding-b*n).attr(`y2`,h-o.padding-b*n).attr(`stroke`,s.gridColor).attr(`stroke-dasharray`,`2 6`)}}let D=new Map;if(d.nodes.forEach(e=>{D.set(e.id,{x:x(e.x),y:S(e.y),node:e})}),d.pipelines.length>0){let e=_.append(`g`).attr(`class`,`wardley-pipelines`),t=_.append(`g`).attr(`class`,`wardley-pipeline-links`);d.pipelines.forEach(n=>{if(n.componentIds.length===0)return;let r=n.componentIds.map(e=>({id:e,pos:D.get(e),node:d.nodes.find(t=>t.id===e)})).filter(e=>e.pos&&e.node).sort((e,t)=>e.node.x-t.node.x);for(let e=0;e{let t=D.get(e);t&&(i=Math.min(i,t.x),a=Math.max(a,t.x),c=t.y)}),i!==1/0&&a!==-1/0){let t=o.nodeRadius*4,r=c-t/2,u=D.get(n.nodeId);u&&(u.x=(i+a)/2,u.y=r-l/6),e.append(`rect`).attr(`class`,`wardley-pipeline-box`).attr(`x`,i-15).attr(`y`,r).attr(`width`,a-i+30).attr(`height`,t).attr(`fill`,`none`).attr(`stroke`,s.axisColor).attr(`stroke-width`,1.5).attr(`rx`,4).attr(`ry`,4)}})}let O=_.append(`g`).attr(`class`,`wardley-links`),k=new Map;d.pipelines.forEach(e=>{k.set(e.nodeId,new Set(e.componentIds))});let A=d.links.filter(e=>!(!D.has(e.source)||!D.has(e.target)||k.get(e.target)?.has(e.source)));O.selectAll(`line`).data(A).enter().append(`line`).attr(`class`,e=>`wardley-link${e.dashed?` wardley-link--dashed`:``}`).attr(`x1`,e=>{let t=D.get(e.source),n=D.get(e.target),r=d.nodes.find(t=>t.id===e.source).isPipelineParent?l/Math.sqrt(2):o.nodeRadius,i=n.x-t.x,a=n.y-t.y,s=Math.sqrt(i*i+a*a);return t.x+i/s*r}).attr(`y1`,e=>{let t=D.get(e.source),n=D.get(e.target),r=d.nodes.find(t=>t.id===e.source).isPipelineParent?l/Math.sqrt(2):o.nodeRadius,i=n.x-t.x,a=n.y-t.y,s=Math.sqrt(i*i+a*a);return t.y+a/s*r}).attr(`x2`,e=>{let t=D.get(e.source),n=D.get(e.target),r=d.nodes.find(t=>t.id===e.target).isPipelineParent?l/Math.sqrt(2):o.nodeRadius,i=t.x-n.x,a=t.y-n.y,s=Math.sqrt(i*i+a*a);return n.x+i/s*r}).attr(`y2`,e=>{let t=D.get(e.source),n=D.get(e.target),r=d.nodes.find(t=>t.id===e.target).isPipelineParent?l/Math.sqrt(2):o.nodeRadius,i=t.x-n.x,a=t.y-n.y,s=Math.sqrt(i*i+a*a);return n.y+a/s*r}).attr(`stroke`,s.linkStroke).attr(`stroke-width`,1).attr(`stroke-dasharray`,e=>e.dashed?`6 6`:null).attr(`marker-end`,e=>e.flow===`forward`||e.flow===`bidirectional`?`url(#link-arrow-end-${r})`:null).attr(`marker-start`,e=>e.flow===`backward`||e.flow===`bidirectional`?`url(#link-arrow-start-${r})`:null),O.selectAll(`text`).data(A.filter(e=>e.label)).enter().append(`text`).attr(`class`,`wardley-link-label`).attr(`x`,e=>{let t=D.get(e.source),n=D.get(e.target),r=(t.x+n.x)/2,i=n.y-t.y,a=n.x-t.x;return r+i/Math.sqrt(a*a+i*i)*8}).attr(`y`,e=>{let t=D.get(e.source),n=D.get(e.target),r=(t.y+n.y)/2,i=n.x-t.x,a=n.y-t.y,o=Math.sqrt(i*i+a*a);return r+-i/o*8}).attr(`fill`,s.axisTextColor).attr(`font-size`,o.labelFontSize).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).attr(`transform`,e=>{let t=D.get(e.source),n=D.get(e.target),r=(t.x+n.x)/2,i=(t.y+n.y)/2,a=n.x-t.x,o=n.y-t.y,s=Math.sqrt(a*a+o*o),c=o/s,l=-a/s,u=r+c*8,d=i+l*8,f=Math.atan2(o,a)*180/Math.PI;return(f>90||f<-90)&&(f+=180),`rotate(${f} ${u} ${d})`}).text(e=>e.label);let j=_.append(`g`).attr(`class`,`wardley-trends`),M=d.trends.map(e=>{let t=D.get(e.nodeId);if(!t)return null;let n=x(e.targetX),r=S(e.targetY),i=n-t.x,a=r-t.y,s=Math.sqrt(i*i+a*a),c=o.nodeRadius+2;return{origin:t,targetX:n,targetY:r,adjustedX2:s>c?n-i/s*c:n,adjustedY2:s>c?r-a/s*c:r}}).filter(e=>e!==null);j.selectAll(`line`).data(M).enter().append(`line`).attr(`class`,`wardley-trend`).attr(`x1`,e=>e.origin.x).attr(`y1`,e=>e.origin.y).attr(`x2`,e=>e.adjustedX2).attr(`y2`,e=>e.adjustedY2).attr(`stroke`,s.evolutionStroke).attr(`stroke-width`,1).attr(`stroke-dasharray`,`4 4`).attr(`marker-end`,`url(#arrow-${r})`);let N=_.append(`g`).attr(`class`,`wardley-nodes`).selectAll(`g`).data(d.nodes).enter().append(`g`).attr(`class`,e=>[`wardley-node`,e.className?`wardley-node--${e.className}`:``].filter(Boolean).join(` `));N.filter(e=>e.sourceStrategy===`outsource`).append(`circle`).attr(`class`,`wardley-outsource-overlay`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius*2).attr(`fill`,`#666`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),N.filter(e=>e.sourceStrategy===`buy`).append(`circle`).attr(`class`,`wardley-buy-overlay`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius*2).attr(`fill`,`#ccc`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),N.filter(e=>e.sourceStrategy===`build`).append(`circle`).attr(`class`,`wardley-build-overlay`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius*2).attr(`fill`,`#eee`).attr(`stroke`,`#000`).attr(`stroke-width`,1);let P=N.filter(e=>e.sourceStrategy===`market`);P.append(`circle`).attr(`class`,`wardley-market-overlay`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius*2).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),N.filter(e=>!e.isPipelineParent&&e.sourceStrategy!==`market`&&e.className!==`anchor`).append(`circle`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius).attr(`fill`,s.componentFill).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1);let F=o.nodeRadius*.7,I=o.nodeRadius*1.2;if(P.append(`line`).attr(`class`,`wardley-market-line`).attr(`x1`,e=>D.get(e.id).x).attr(`y1`,e=>D.get(e.id).y-I).attr(`x2`,e=>D.get(e.id).x-I*Math.cos(Math.PI/6)).attr(`y2`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),P.append(`line`).attr(`class`,`wardley-market-line`).attr(`x1`,e=>D.get(e.id).x-I*Math.cos(Math.PI/6)).attr(`y1`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`x2`,e=>D.get(e.id).x+I*Math.cos(Math.PI/6)).attr(`y2`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),P.append(`line`).attr(`class`,`wardley-market-line`).attr(`x1`,e=>D.get(e.id).x+I*Math.cos(Math.PI/6)).attr(`y1`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`x2`,e=>D.get(e.id).x).attr(`y2`,e=>D.get(e.id).y-I).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),P.append(`circle`).attr(`class`,`wardley-market-dot`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y-I).attr(`r`,F).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,2),P.append(`circle`).attr(`class`,`wardley-market-dot`).attr(`cx`,e=>D.get(e.id).x-I*Math.cos(Math.PI/6)).attr(`cy`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`r`,F).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,2),P.append(`circle`).attr(`class`,`wardley-market-dot`).attr(`cx`,e=>D.get(e.id).x+I*Math.cos(Math.PI/6)).attr(`cy`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`r`,F).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,2),N.filter(e=>e.isPipelineParent===!0).append(`rect`).attr(`x`,e=>D.get(e.id).x-l/2).attr(`y`,e=>D.get(e.id).y-l/2).attr(`width`,l).attr(`height`,l).attr(`fill`,s.componentFill).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),N.filter(e=>e.inertia===!0).append(`line`).attr(`class`,`wardley-inertia`).attr(`x1`,e=>{let t=D.get(e.id),n=e.isPipelineParent?l/2+15:o.nodeRadius+15;return e.sourceStrategy&&(n+=o.nodeRadius+10),t.x+n}).attr(`y1`,e=>{let t=D.get(e.id),n=e.isPipelineParent?l:o.nodeRadius*2;return t.y-n/2}).attr(`x2`,e=>{let t=D.get(e.id),n=e.isPipelineParent?l/2+15:o.nodeRadius+15;return e.sourceStrategy&&(n+=o.nodeRadius+10),t.x+n}).attr(`y2`,e=>{let t=D.get(e.id),n=e.isPipelineParent?l:o.nodeRadius*2;return t.y+n/2}).attr(`stroke`,s.componentStroke).attr(`stroke-width`,6),N.append(`text`).attr(`x`,e=>{let t=D.get(e.id);if(e.className===`anchor`)return e.labelOffsetX===void 0?t.x:t.x+e.labelOffsetX;let n=o.nodeLabelOffset;e.sourceStrategy&&e.labelOffsetX===void 0&&(n+=10);let r=e.labelOffsetX??n;return t.x+r}).attr(`y`,e=>{let t=D.get(e.id);if(e.className===`anchor`)return e.labelOffsetY===void 0?t.y-3:t.y+e.labelOffsetY;let n=-o.nodeLabelOffset;e.sourceStrategy&&e.labelOffsetY===void 0&&(n-=10);let r=e.labelOffsetY??n;return t.y+r}).attr(`class`,`wardley-node-label`).attr(`fill`,e=>e.className===`evolved`?s.evolutionStroke:e.className===`anchor`?`#000`:s.componentLabelColor).attr(`font-size`,o.labelFontSize).attr(`font-weight`,e=>e.className===`anchor`?`bold`:`normal`).attr(`text-anchor`,e=>e.className===`anchor`?`middle`:`start`).attr(`dominant-baseline`,e=>e.className===`anchor`?`middle`:`auto`).text(e=>e.label),d.annotations.length>0){let e=_.append(`g`).attr(`class`,`wardley-annotations`);if(d.annotations.forEach(t=>{let n=t.coordinates.map(e=>({x:x(e.x),y:S(e.y)}));if(n.length>1)for(let t=0;t{let r=e.append(`g`).attr(`class`,`wardley-annotation`);r.append(`circle`).attr(`cx`,n.x).attr(`cy`,n.y).attr(`r`,10).attr(`fill`,`white`).attr(`stroke`,s.axisColor).attr(`stroke-width`,1.5),r.append(`text`).attr(`x`,n.x).attr(`y`,n.y).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`central`).attr(`font-size`,10).attr(`fill`,s.axisTextColor).attr(`font-weight`,`bold`).text(t.number)})}),d.annotationsBox){let t=x(d.annotationsBox.x),n=S(d.annotationsBox.y),r=e.append(`g`).attr(`class`,`wardley-annotations-box`),i=[...d.annotations].filter(e=>e.text).sort((e,t)=>e.number-t.number),a=[];if(i.forEach((e,i)=>{let o=r.append(`text`).attr(`x`,t+10).attr(`y`,n+10+(i+1)*16).attr(`font-size`,11).attr(`fill`,s.axisTextColor).attr(`text-anchor`,`start`).attr(`dominant-baseline`,`middle`).text(`${e.number}. ${e.text}`);a.push(o)}),a.length>0){let e=0,c=0;a.forEach(t=>{let n=t.node(),r=n.getComputedTextLength();e=Math.max(e,r);let i=n.getBBox();c=Math.max(c,i.height)});let l=e+20+105,u=i.length*16+20+c/2,d=o.padding,f=p-o.padding-l,m=o.padding,g=h-o.padding-u;t=Math.max(d,Math.min(t,f)),n=Math.max(m,Math.min(n,g)),a.forEach((e,r)=>{e.attr(`x`,t+10).attr(`y`,n+10+(r+1)*16)}),r.insert(`rect`,`text`).attr(`x`,t).attr(`y`,n).attr(`width`,l).attr(`height`,u).attr(`fill`,`white`).attr(`stroke`,s.axisColor).attr(`stroke-width`,1.5).attr(`rx`,4).attr(`ry`,4)}}}if(d.notes.length>0){let e=_.append(`g`).attr(`class`,`wardley-notes`);d.notes.forEach(t=>{let n=x(t.x),r=S(t.y);e.append(`text`).attr(`x`,n).attr(`y`,r).attr(`text-anchor`,`start`).attr(`font-size`,11).attr(`fill`,s.axisTextColor).attr(`font-weight`,`bold`).text(t.text)})}if(d.accelerators.length>0){let e=_.append(`g`).attr(`class`,`wardley-accelerators`);d.accelerators.forEach(t=>{let n=x(t.x),r=S(t.y),i=` M ${n} ${r-30/2} L ${n+60-20} ${r-30/2} diff --git a/.vercel/output/static/assets/xychartDiagram-FW5EYKEG-CmsUFOjZ.js b/.vercel/output/static/assets/xychartDiagram-FW5EYKEG-HaTasnSW.js similarity index 99% rename from .vercel/output/static/assets/xychartDiagram-FW5EYKEG-CmsUFOjZ.js rename to .vercel/output/static/assets/xychartDiagram-FW5EYKEG-HaTasnSW.js index 6b43149..8c00a6f 100644 --- a/.vercel/output/static/assets/xychartDiagram-FW5EYKEG-CmsUFOjZ.js +++ b/.vercel/output/static/assets/xychartDiagram-FW5EYKEG-HaTasnSW.js @@ -1,4 +1,4 @@ -import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-_wZywoZs.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,f as l,v as u,w as d,y as f,z as p}from"./chunk-WYO6CB5R-ajGU-pWR.js";import{t as m}from"./linear-B7l8qgEw.js";import{t as h}from"./ordinal-hYBb2elL.js";import{t as g}from"./init-D6jRqBbL.js";import{i as _}from"./chunk-ICXQ74PX-fa5hHXws.js";import{t as v}from"./line-CDW8hdKE.js";import{t as y}from"./chunk-VAUOI2AC-CLN1Ga8_.js";import"./chunk-HOUHSVGY-4s2dJLwR.js";import{t as b}from"./chunk-Q4XR5HBZ-5srkZ5CC.js";function x(e,t,n){e=+e,t=+t,n=(i=arguments.length)<2?(t=e,e=0,1):i<3?1:+n;for(var r=-1,i=Math.max(0,Math.ceil((t-e)/n))|0,a=Array(i);++rf&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,f as l,v as u,w as d,y as f,z as p}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as m}from"./linear-DhAcoVP9.js";import{t as h}from"./ordinal-hYBb2elL.js";import{t as g}from"./init-D6jRqBbL.js";import{i as _}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as v}from"./line-b9Ala942.js";import{t as y}from"./chunk-VAUOI2AC-AC9pRUsa.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import{t as b}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";function x(e,t,n){e=+e,t=+t,n=(i=arguments.length)<2?(t=e,e=0,1):i<3?1:+n;for(var r=-1,i=Math.max(0,Math.ceil((t-e)/n))|0,a=Array(i);++rf&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: `+h.showPosition()+` Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};A.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` diff --git a/.work/todo.jsonl b/.work/todo.jsonl index 19879fc..b519ebe 100644 --- a/.work/todo.jsonl +++ b/.work/todo.jsonl @@ -35,3 +35,4 @@ {"actor":"richardhightower","ev":"01KZ2N3TGMB3NBAKBZBXZPMHH3","item":"01KZ2MM83PJSTBEFWA953QPTSS","op":"close","set":{"resolution":"Explicit empty state outside both cmdk groups; Command.Empty was dead code","status":"done"},"ts":"2026-08-03T01:51:47Z"} {"actor":"richardhightower","ev":"01KZ2N3TNS3RD3WJDE8J92W3JQ","item":"01KYZ8XMGPWDJ8KXXK23KV47NT","op":"close","set":{"resolution":"All 11 screens specified, 47 wireframes, 30 captures, rubrics walked; 3 defects found and fixed","status":"done"},"ts":"2026-08-03T01:51:47Z"} {"actor":"richardhightower","ev":"01KZ2N3TV3T28RPS0ASD1F4QYT","item":"01KYZ8X1X1V76HYNK8B5JYMD9W","op":"close","set":{"resolution":"Loop complete end to end: spec, wireframe, addressability, capture, rubric walk, CI gate","status":"done"},"ts":"2026-08-03T01:51:48Z"} +{"actor":"richardhightower","ev":"01KZ3Z46SDCBA57YHAF7C3HCTD","item":"01KZ3Z46SDWDGVD3CFZ0Z1S9FB","op":"create","set":{"discovered_during":"01KYZ8X1X1V76HYNK8B5JYMD9W","kind":"bug","level":"task","milestone":"v0.3.1","priority":"P2","status":"todo","title":"cargo tauri build fails: scrubbed icon filename has no image extension","unplanned":true},"ts":"2026-08-03T14:06:00Z"} diff --git a/CLAUDE.md b/CLAUDE.md index 1f04419..43533f0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -285,9 +285,16 @@ writes** by `context.userId`. the code can set `__Host-`-prefixed names itself; `__Host-` forbids a `Domain` attribute, which is what stops a sibling `*.grok.me` app from injecting a session cookie. Do not "fix" it. -**Known latent bug:** `src-tauri/tauri.conf.json` lists an icon named -`icons/henry.w@example.net` — a scrubbing artifact from `128x128@2x.png`. Harmless today -(file and reference agree) but wrong; fixing it means renaming the file and the config together. +**Fixed in v0.3.1, and it was never harmless.** `tauri.conf.json` used to list an icon +named `icons/henry.w@example.net` — a scrubbing artifact from `128x128@2x.png`. This file +previously called that harmless because the file and the reference agreed. They did, and +it still broke the build: the bundler infers image format from the extension, `.net` is +not one, and `cargo tauri build` died with `Failed to create app icon: The image format +could not be determined`. That is exactly why the desktop packaging path stayed +unexercised — the first person to run it hit a wall. + +Generalises past this one file: **"the references agree" is not "it works."** The +consistency was checkable by reading; the format inference was not. ## Conventions diff --git a/dist-desktop/assets/abnfDiagram-VRR7QNED-DLdRCqX4.js b/dist-desktop/assets/abnfDiagram-VRR7QNED-DLdRCqX4.js new file mode 100644 index 0000000..3198c78 --- /dev/null +++ b/dist-desktop/assets/abnfDiagram-VRR7QNED-DLdRCqX4.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-5HE753X5-o8-OCfIL.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-Bju_yCKi.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-Z7xZAZRH.js";var c=e().RailroadAbnf.parser.LangiumParser,l=t(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformAlternation`),u=t(e=>{let t=e.elements.map(f);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformConcatenation`),d=t(e=>{if(e.includes(`*`)){let[t,n]=e.split(`*`);return{min:t?parseInt(t,10):0,max:n?parseInt(n,10):1/0}}let t=parseInt(e,10);return{min:t,max:t}},`parseRepeat`),f=t(e=>{let t=p(e.primary);if(!e.repeat)return t;let{min:n,max:r}=d(e.repeat);return n===0&&r===1?{type:`optional`,element:t}:{type:`repetition`,element:t,min:n,max:r}},`transformElement`),p=t(e=>{switch(e.$type){case`AbnfStringLiteral`:return{type:`terminal`,value:e.value};case`AbnfNumVal`:return{type:`terminal`,value:e.value};case`AbnfRuleName`:return{type:`nonterminal`,name:e.name};case`AbnfGroup`:return l(e.element);case`AbnfOptionalGroup`:return{type:`optional`,element:l(e.element)};default:throw Error(`Unsupported ABNF primary node: ${e.$type}`)}},`transformPrimary`),m=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),h=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(m(e)))},`populateDb`),g={parser:{parse:t(e=>{a.clear(),n.debug(`[ABNF Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[ABNF Parser] Parsed rules:`,r.rules.length),h(r),n.debug(`[ABNF Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{g as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/arc-DqK6O3qL.js b/dist-desktop/assets/arc-DqK6O3qL.js new file mode 100644 index 0000000..5046079 --- /dev/null +++ b/dist-desktop/assets/arc-DqK6O3qL.js @@ -0,0 +1 @@ +import{n as e,t}from"./path-BWPyau1x.js";import{a as n,c as r,d as i,f as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,u as p}from"./dist-qx0Iv9vM.js";function m(e){return e.innerRadius}function h(e){return e.outerRadius}function g(e){return e.startAngle}function _(e){return e.endAngle}function v(e){return e&&e.padAngle}function y(e,t,n,r,i,a,o,s){var c=n-e,l=r-t,u=o-i,d=s-a,f=d*c-u*l;if(!(f*f<1e-12))return f=(u*(t-a)-d*(e-i))/f,[e+f*c,t+f*l]}function b(e,t,n,r,i,a,o){var c=e-n,l=t-r,u=(o?a:-a)/d(c*c+l*l),f=u*l,p=-u*c,m=e+f,h=t+p,g=n+f,_=r+p,v=(m+g)/2,y=(h+_)/2,b=g-m,x=_-h,S=b*b+x*x,C=i-a,w=m*_-g*h,T=(x<0?-1:1)*d(s(0,C*C*S-w*w)),E=(w*x-b*T)/S,D=(-w*b-x*T)/S,O=(w*x+b*T)/S,k=(-w*b+x*T)/S,A=E-v,j=D-y,M=O-v,N=k-y;return A*A+j*j>M*M+N*N&&(E=O,D=k),{cx:E,cy:D,x01:-f,y01:-p,x11:E*(i/C-1),y11:D*(i/C-1)}}function x(){var s=m,x=h,S=e(0),C=null,w=g,T=_,E=v,D=null,O=t(k);function k(){var e,t,m=+s.apply(this,arguments),h=+x.apply(this,arguments),g=w.apply(this,arguments)-r,_=T.apply(this,arguments)-r,v=l(_-g),k=_>g;if(D||=e=O(),h1e-12))D.moveTo(0,0);else if(v>c-1e-12)D.moveTo(h*u(g),h*a(g)),D.arc(0,0,h,g,_,!k),m>1e-12&&(D.moveTo(m*u(_),m*a(_)),D.arc(0,0,m,_,g,k));else{var A=g,j=_,M=g,N=_,P=v,F=v,I=E.apply(this,arguments)/2,L=I>1e-12&&(C?+C.apply(this,arguments):d(m*m+h*h)),R=p(l(h-m)/2,+S.apply(this,arguments)),z=R,B=R,V,H;if(L>1e-12){var U=o(L/m*a(I)),W=o(L/h*a(I));(P-=U*2)>1e-12?(U*=k?1:-1,M+=U,N-=U):(P=0,M=N=(g+_)/2),(F-=W*2)>1e-12?(W*=k?1:-1,A+=W,j-=W):(F=0,A=j=(g+_)/2)}var G=h*u(A),K=h*a(A),q=m*u(N),J=m*a(N);if(R>1e-12){var Y=h*u(j),X=h*a(j),Z=m*u(M),Q=m*a(M),$;if(v1e-12?B>1e-12?(V=b(Z,Q,G,K,h,B,k),H=b(Y,X,q,J,h,B,k),D.moveTo(V.cx+V.x01,V.cy+V.y01),B1e-12)||!(P>1e-12)?D.lineTo(q,J):z>1e-12?(V=b(q,J,Y,X,m,-z,k),H=b(G,K,Z,Q,m,-z,k),D.lineTo(V.cx+V.x01,V.cy+V.y01),z{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.layoutBase=r():n.layoutBase=r()})(e,function(){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=28)})([(function(e,t,n){function r(){}r.QUALITY=1,r.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,r.DEFAULT_INCREMENTAL=!1,r.DEFAULT_ANIMATION_ON_LAYOUT=!0,r.DEFAULT_ANIMATION_DURING_LAYOUT=!1,r.DEFAULT_ANIMATION_PERIOD=50,r.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,r.DEFAULT_GRAPH_MARGIN=15,r.NODE_DIMENSIONS_INCLUDE_LABELS=!1,r.SIMPLE_NODE_SIZE=40,r.SIMPLE_NODE_HALF_SIZE=r.SIMPLE_NODE_SIZE/2,r.EMPTY_COMPOUND_NODE_SIZE=40,r.MIN_EDGE_LENGTH=1,r.WORLD_BOUNDARY=1e6,r.INITIAL_WORLD_BOUNDARY=r.WORLD_BOUNDARY/1e3,r.WORLD_CENTER_X=1200,r.WORLD_CENTER_Y=900,e.exports=r}),(function(e,t,n){var r=n(2),i=n(8),a=n(9);function o(e,t,n){r.call(this,n),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=n,this.bendpoints=[],this.source=e,this.target=t}for(var s in o.prototype=Object.create(r.prototype),r)o[s]=r[s];o.prototype.getSource=function(){return this.source},o.prototype.getTarget=function(){return this.target},o.prototype.isInterGraph=function(){return this.isInterGraph},o.prototype.getLength=function(){return this.length},o.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},o.prototype.getBendpoints=function(){return this.bendpoints},o.prototype.getLca=function(){return this.lca},o.prototype.getSourceInLca=function(){return this.sourceInLca},o.prototype.getTargetInLca=function(){return this.targetInLca},o.prototype.getOtherEnd=function(e){if(this.source===e)return this.target;if(this.target===e)return this.source;throw`Node is not incident with this edge`},o.prototype.getOtherEndInGraph=function(e,t){for(var n=this.getOtherEnd(e),r=t.getGraphManager().getRoot();;){if(n.getOwner()==t)return n;if(n.getOwner()==r)break;n=n.getOwner().getParent()}return null},o.prototype.updateLength=function(){var e=[,,,,];this.isOverlapingSourceAndTarget=i.getIntersection(this.target.getRect(),this.source.getRect(),e),this.isOverlapingSourceAndTarget||(this.lengthX=e[0]-e[2],this.lengthY=e[1]-e[3],Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},o.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},e.exports=o}),(function(e,t,n){function r(e){this.vGraphObject=e}e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(13),o=n(0),s=n(16),c=n(5);function l(e,t,n,o){n==null&&o==null&&(o=t),r.call(this,o),e.graphManager!=null&&(e=e.graphManager),this.estimatedSize=i.MIN_VALUE,this.inclusionTreeDepth=i.MAX_VALUE,this.vGraphObject=o,this.edges=[],this.graphManager=e,n!=null&&t!=null?this.rect=new a(t.x,t.y,n.width,n.height):this.rect=new a}for(var u in l.prototype=Object.create(r.prototype),r)l[u]=r[u];l.prototype.getEdges=function(){return this.edges},l.prototype.getChild=function(){return this.child},l.prototype.getOwner=function(){return this.owner},l.prototype.getWidth=function(){return this.rect.width},l.prototype.setWidth=function(e){this.rect.width=e},l.prototype.getHeight=function(){return this.rect.height},l.prototype.setHeight=function(e){this.rect.height=e},l.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},l.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},l.prototype.getCenter=function(){return new c(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},l.prototype.getLocation=function(){return new c(this.rect.x,this.rect.y)},l.prototype.getRect=function(){return this.rect},l.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},l.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},l.prototype.setRect=function(e,t){this.rect.x=e.x,this.rect.y=e.y,this.rect.width=t.width,this.rect.height=t.height},l.prototype.setCenter=function(e,t){this.rect.x=e-this.rect.width/2,this.rect.y=t-this.rect.height/2},l.prototype.setLocation=function(e,t){this.rect.x=e,this.rect.y=t},l.prototype.moveBy=function(e,t){this.rect.x+=e,this.rect.y+=t},l.prototype.getEdgeListToNode=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(r.target==e){if(r.source!=n)throw`Incorrect edge source!`;t.push(r)}}),t},l.prototype.getEdgesBetween=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(!(r.source==n||r.target==n))throw`Incorrect edge source and/or target`;(r.target==e||r.source==e)&&t.push(r)}),t},l.prototype.getNeighborsList=function(){var e=new Set,t=this;return t.edges.forEach(function(n){if(n.source==t)e.add(n.target);else{if(n.target!=t)throw`Incorrect incidency!`;e.add(n.source)}}),e},l.prototype.withChildren=function(){var e=new Set,t,n;if(e.add(this),this.child!=null)for(var r=this.child.getNodes(),i=0;it?(this.rect.x-=(this.labelWidth-t)/2,this.setWidth(this.labelWidth)):this.labelPosHorizontal==`right`&&this.setWidth(t+this.labelWidth)),this.labelHeight&&(this.labelPosVertical==`top`?(this.rect.y-=this.labelHeight,this.setHeight(n+this.labelHeight)):this.labelPosVertical==`center`&&this.labelHeight>n?(this.rect.y-=(this.labelHeight-n)/2,this.setHeight(this.labelHeight)):this.labelPosVertical==`bottom`&&this.setHeight(n+this.labelHeight))}}},l.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==i.MAX_VALUE)throw`assert failed`;return this.inclusionTreeDepth},l.prototype.transform=function(e){var t=this.rect.x;t>o.WORLD_BOUNDARY?t=o.WORLD_BOUNDARY:t<-o.WORLD_BOUNDARY&&(t=-o.WORLD_BOUNDARY);var n=this.rect.y;n>o.WORLD_BOUNDARY?n=o.WORLD_BOUNDARY:n<-o.WORLD_BOUNDARY&&(n=-o.WORLD_BOUNDARY);var r=new c(t,n),i=e.inverseTransformPoint(r);this.setLocation(i.x,i.y)},l.prototype.getLeft=function(){return this.rect.x},l.prototype.getRight=function(){return this.rect.x+this.rect.width},l.prototype.getTop=function(){return this.rect.y},l.prototype.getBottom=function(){return this.rect.y+this.rect.height},l.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},e.exports=l}),(function(e,t,n){var r=n(0);function i(){}for(var a in r)i[a]=r[a];i.MAX_ITERATIONS=2500,i.DEFAULT_EDGE_LENGTH=50,i.DEFAULT_SPRING_STRENGTH=.45,i.DEFAULT_REPULSION_STRENGTH=4500,i.DEFAULT_GRAVITY_STRENGTH=.4,i.DEFAULT_COMPOUND_GRAVITY_STRENGTH=1,i.DEFAULT_GRAVITY_RANGE_FACTOR=3.8,i.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=1.5,i.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION=!0,i.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION=!0,i.DEFAULT_COOLING_FACTOR_INCREMENTAL=.3,i.COOLING_ADAPTATION_FACTOR=.33,i.ADAPTATION_LOWER_NODE_LIMIT=1e3,i.ADAPTATION_UPPER_NODE_LIMIT=5e3,i.MAX_NODE_DISPLACEMENT_INCREMENTAL=100,i.MAX_NODE_DISPLACEMENT=i.MAX_NODE_DISPLACEMENT_INCREMENTAL*3,i.MIN_REPULSION_DIST=i.DEFAULT_EDGE_LENGTH/10,i.CONVERGENCE_CHECK_PERIOD=100,i.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=.1,i.MIN_EDGE_LENGTH=1,i.GRID_CALCULATION_CHECK_PERIOD=10,e.exports=i}),(function(e,t,n){function r(e,t){e==null&&t==null?(this.x=0,this.y=0):(this.x=e,this.y=t)}r.prototype.getX=function(){return this.x},r.prototype.getY=function(){return this.y},r.prototype.setX=function(e){this.x=e},r.prototype.setY=function(e){this.y=e},r.prototype.getDifference=function(e){return new DimensionD(this.x-e.x,this.y-e.y)},r.prototype.getCopy=function(){return new r(this.x,this.y)},r.prototype.translate=function(e){return this.x+=e.width,this.y+=e.height,this},e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(0),o=n(7),s=n(3),c=n(1),l=n(13),u=n(12),d=n(11);function f(e,t,n){r.call(this,n),this.estimatedSize=i.MIN_VALUE,this.margin=a.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=e,t!=null&&t instanceof o?this.graphManager=t:t!=null&&t instanceof Layout&&(this.graphManager=t.graphManager)}for(var p in f.prototype=Object.create(r.prototype),r)f[p]=r[p];f.prototype.getNodes=function(){return this.nodes},f.prototype.getEdges=function(){return this.edges},f.prototype.getGraphManager=function(){return this.graphManager},f.prototype.getParent=function(){return this.parent},f.prototype.getLeft=function(){return this.left},f.prototype.getRight=function(){return this.right},f.prototype.getTop=function(){return this.top},f.prototype.getBottom=function(){return this.bottom},f.prototype.isConnected=function(){return this.isConnected},f.prototype.add=function(e,t,n){if(t==null&&n==null){var r=e;if(this.graphManager==null)throw`Graph has no graph mgr!`;if(this.getNodes().indexOf(r)>-1)throw`Node already in graph!`;return r.owner=this,this.getNodes().push(r),r}else{var i=e;if(!(this.getNodes().indexOf(t)>-1&&this.getNodes().indexOf(n)>-1))throw`Source or target not in graph!`;if(!(t.owner==n.owner&&t.owner==this))throw`Both owners must be this graph!`;return t.owner==n.owner?(i.source=t,i.target=n,i.isInterGraph=!1,this.getEdges().push(i),t.edges.push(i),n!=t&&n.edges.push(i),i):null}},f.prototype.remove=function(e){var t=e;if(e instanceof s){if(t==null)throw`Node is null!`;if(!(t.owner!=null&&t.owner==this))throw`Owner graph is invalid!`;if(this.graphManager==null)throw`Owner graph manager is invalid!`;for(var n=t.edges.slice(),r,i=n.length,a=0;a-1&&u>-1))throw`Source and/or target doesn't know this edge!`;r.source.edges.splice(l,1),r.target!=r.source&&r.target.edges.splice(u,1);var o=r.source.owner.getEdges().indexOf(r);if(o==-1)throw`Not in owner's edge list!`;r.source.owner.getEdges().splice(o,1)}},f.prototype.updateLeftTop=function(){for(var e=i.MAX_VALUE,t=i.MAX_VALUE,n,r,a,o=this.getNodes(),s=o.length,c=0;cn&&(e=n),t>r&&(t=r)}return e==i.MAX_VALUE?null:(a=o[0].getParent().paddingLeft==null?this.margin:o[0].getParent().paddingLeft,this.left=t-a,this.top=e-a,new u(this.left,this.top))},f.prototype.updateBounds=function(e){for(var t=i.MAX_VALUE,n=-i.MAX_VALUE,r=i.MAX_VALUE,a=-i.MAX_VALUE,o,s,c,u,d,f=this.nodes,p=f.length,m=0;mo&&(t=o),nc&&(r=c),ao&&(t=o),nc&&(r=c),a=this.nodes.length){var c=0;n.forEach(function(t){t.owner==e&&c++}),c==this.nodes.length&&(this.isConnected=!0)}},e.exports=f}),(function(e,t,n){var r,i=n(1);function a(e){r=n(6),this.layout=e,this.graphs=[],this.edges=[]}a.prototype.addRoot=function(){var e=this.layout.newGraph(),t=this.layout.newNode(null),n=this.add(e,t);return this.setRootGraph(n),this.rootGraph},a.prototype.add=function(e,t,n,r,i){if(n==null&&r==null&&i==null){if(e==null)throw`Graph is null!`;if(t==null)throw`Parent node is null!`;if(this.graphs.indexOf(e)>-1)throw`Graph already in this graph mgr!`;if(this.graphs.push(e),e.parent!=null)throw`Already has a parent!`;if(t.child!=null)throw`Already has a child!`;return e.parent=t,t.child=e,e}else{i=n,r=t,n=e;var a=r.getOwner(),o=i.getOwner();if(!(a!=null&&a.getGraphManager()==this))throw`Source not in this graph mgr!`;if(!(o!=null&&o.getGraphManager()==this))throw`Target not in this graph mgr!`;if(a==o)return n.isInterGraph=!1,a.add(n,r,i);if(n.isInterGraph=!0,n.source=r,n.target=i,this.edges.indexOf(n)>-1)throw`Edge already in inter-graph edge list!`;if(this.edges.push(n),!(n.source!=null&&n.target!=null))throw`Edge source and/or target is null!`;if(!(n.source.edges.indexOf(n)==-1&&n.target.edges.indexOf(n)==-1))throw`Edge already in source and/or target incidency list!`;return n.source.edges.push(n),n.target.edges.push(n),n}},a.prototype.remove=function(e){if(e instanceof r){var t=e;if(t.getGraphManager()!=this)throw`Graph not in this graph mgr`;if(!(t==this.rootGraph||t.parent!=null&&t.parent.graphManager==this))throw`Invalid parent node!`;var n=[];n=n.concat(t.getEdges());for(var a,o=n.length,s=0;s=t.getRight()?n[0]+=Math.min(t.getX()-e.getX(),e.getRight()-t.getRight()):t.getX()<=e.getX()&&t.getRight()>=e.getRight()&&(n[0]+=Math.min(e.getX()-t.getX(),t.getRight()-e.getRight())),e.getY()<=t.getY()&&e.getBottom()>=t.getBottom()?n[1]+=Math.min(t.getY()-e.getY(),e.getBottom()-t.getBottom()):t.getY()<=e.getY()&&t.getBottom()>=e.getBottom()&&(n[1]+=Math.min(e.getY()-t.getY(),t.getBottom()-e.getBottom()));var a=Math.abs((t.getCenterY()-e.getCenterY())/(t.getCenterX()-e.getCenterX()));t.getCenterY()===e.getCenterY()&&t.getCenterX()===e.getCenterX()&&(a=1);var o=a*n[0],s=n[1]/a;n[0]o)return n[0]=r,n[1]=c,n[2]=a,n[3]=y,!1;if(ia)return n[0]=s,n[1]=i,n[2]=_,n[3]=o,!1;if(ra?(n[0]=u,n[1]=d,C=!0):(n[0]=l,n[1]=c,C=!0):T===D&&(r>a?(n[0]=s,n[1]=c,C=!0):(n[0]=f,n[1]=d,C=!0)),-E===D?a>r?(n[2]=v,n[3]=y,w=!0):(n[2]=_,n[3]=g,w=!0):E===D&&(a>r?(n[2]=h,n[3]=g,w=!0):(n[2]=b,n[3]=y,w=!0)),C&&w)return!1;if(r>a?i>o?(O=this.getCardinalDirection(T,D,4),k=this.getCardinalDirection(E,D,2)):(O=this.getCardinalDirection(-T,D,3),k=this.getCardinalDirection(-E,D,1)):i>o?(O=this.getCardinalDirection(-T,D,1),k=this.getCardinalDirection(-E,D,3)):(O=this.getCardinalDirection(T,D,2),k=this.getCardinalDirection(E,D,4)),!C)switch(O){case 1:j=c,A=r+-m/D,n[0]=A,n[1]=j;break;case 2:A=f,j=i+p*D,n[0]=A,n[1]=j;break;case 3:j=d,A=r+m/D,n[0]=A,n[1]=j;break;case 4:A=u,j=i+-p*D,n[0]=A,n[1]=j;break}if(!w)switch(k){case 1:N=g,M=a+-S/D,n[2]=M,n[3]=N;break;case 2:M=b,N=o+x*D,n[2]=M,n[3]=N;break;case 3:N=y,M=a+S/D,n[2]=M,n[3]=N;break;case 4:M=v,N=o+-x*D,n[2]=M,n[3]=N;break}}return!1},i.getCardinalDirection=function(e,t,n){return e>t?n:1+n%4},i.getIntersection=function(e,t,n,i){if(i==null)return this.getIntersection2(e,t,n);var a=e.x,o=e.y,s=t.x,c=t.y,l=n.x,u=n.y,d=i.x,f=i.y,p=void 0,m=void 0,h=void 0,g=void 0,_=void 0,v=void 0,y=void 0,b=void 0,x=void 0;return h=c-o,_=a-s,y=s*o-a*c,g=f-u,v=l-d,b=d*u-l*f,x=h*v-g*_,x===0?null:(p=(_*b-v*y)/x,m=(g*y-h*b)/x,new r(p,m))},i.angleOfVector=function(e,t,n,r){var i=void 0;return e===n?i=r=0){var u=(-c+Math.sqrt(c*c-4*s*l))/(2*s),d=(-c-Math.sqrt(c*c-4*s*l))/(2*s);return u>=0&&u<=1?[u]:d>=0&&d<=1?[d]:null}else return null},i.HALF_PI=.5*Math.PI,i.ONE_AND_HALF_PI=1.5*Math.PI,i.TWO_PI=2*Math.PI,i.THREE_PI=3*Math.PI,e.exports=i}),(function(e,t,n){function r(){}r.sign=function(e){return e>0?1:e<0?-1:0},r.floor=function(e){return e<0?Math.ceil(e):Math.floor(e)},r.ceil=function(e){return e<0?Math.floor(e):Math.ceil(e)},e.exports=r}),(function(e,t,n){function r(){}r.MAX_VALUE=2147483647,r.MIN_VALUE=-2147483648,e.exports=r}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n0&&t;){for(s.push(l[0]);s.length>0&&t;){var u=s[0];s.splice(0,1),o.add(u);for(var d=u.getEdges(),a=0;a-1&&l.splice(h,1)}o=new Set,c=new Map}}return e},f.prototype.createDummyNodesForBendpoints=function(e){for(var t=[],n=e.source,r=this.graphManager.calcLowestCommonAncestor(e.source,e.target),i=0;i0){for(var i=this.edgeToDummyNodes.get(n),a=0;a=0&&t.splice(d,1),s.getNeighborsList().forEach(function(e){if(n.indexOf(e)<0){var t=r.get(e)-1;t==1&&l.push(e),r.set(e,t)}})}n=n.concat(l),(t.length==1||t.length==2)&&(i=!0,a=t[0])}return a},f.prototype.setGraphManager=function(e){this.graphManager=e},e.exports=f}),(function(e,t,n){function r(){}r.seed=1,r.x=0,r.nextDouble=function(){return r.x=Math.sin(r.seed++)*1e4,r.x-Math.floor(r.x)},e.exports=r}),(function(e,t,n){var r=n(5);function i(e,t){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}i.prototype.getWorldOrgX=function(){return this.lworldOrgX},i.prototype.setWorldOrgX=function(e){this.lworldOrgX=e},i.prototype.getWorldOrgY=function(){return this.lworldOrgY},i.prototype.setWorldOrgY=function(e){this.lworldOrgY=e},i.prototype.getWorldExtX=function(){return this.lworldExtX},i.prototype.setWorldExtX=function(e){this.lworldExtX=e},i.prototype.getWorldExtY=function(){return this.lworldExtY},i.prototype.setWorldExtY=function(e){this.lworldExtY=e},i.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},i.prototype.setDeviceOrgX=function(e){this.ldeviceOrgX=e},i.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},i.prototype.setDeviceOrgY=function(e){this.ldeviceOrgY=e},i.prototype.getDeviceExtX=function(){return this.ldeviceExtX},i.prototype.setDeviceExtX=function(e){this.ldeviceExtX=e},i.prototype.getDeviceExtY=function(){return this.ldeviceExtY},i.prototype.setDeviceExtY=function(e){this.ldeviceExtY=e},i.prototype.transformX=function(e){var t=0,n=this.lworldExtX;return n!=0&&(t=this.ldeviceOrgX+(e-this.lworldOrgX)*this.ldeviceExtX/n),t},i.prototype.transformY=function(e){var t=0,n=this.lworldExtY;return n!=0&&(t=this.ldeviceOrgY+(e-this.lworldOrgY)*this.ldeviceExtY/n),t},i.prototype.inverseTransformX=function(e){var t=0,n=this.ldeviceExtX;return n!=0&&(t=this.lworldOrgX+(e-this.ldeviceOrgX)*this.lworldExtX/n),t},i.prototype.inverseTransformY=function(e){var t=0,n=this.ldeviceExtY;return n!=0&&(t=this.lworldOrgY+(e-this.ldeviceOrgY)*this.lworldExtY/n),t},i.prototype.inverseTransformPoint=function(e){return new r(this.inverseTransformX(e.x),this.inverseTransformY(e.y))},e.exports=i}),(function(e,t,n){function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);ta.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*a.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-a.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT_INCREMENTAL):(e>a.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(a.COOLING_ADAPTATION_FACTOR,1-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*(1-a.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.displacementThresholdPerNode=3*a.DEFAULT_EDGE_LENGTH/100,this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},l.prototype.calcSpringForces=function(){for(var e=this.getAllEdges(),t,n=0;n0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n,r,i,o,s=this.getAllNodes(),c;if(this.useFRGridVariant)for(this.totalIterations%a.GRID_CALCULATION_CHECK_PERIOD==1&&e&&this.updateGrid(),c=new Set,n=0;nc||s>c)&&(e.gravitationForceX=-this.gravityConstant*i,e.gravitationForceY=-this.gravityConstant*a)):(c=t.getEstimatedSize()*this.compoundGravityRangeFactor,(o>c||s>c)&&(e.gravitationForceX=-this.gravityConstant*i*this.compoundGravityConstant,e.gravitationForceY=-this.gravityConstant*a*this.compoundGravityConstant))},l.prototype.isConverged=function(){var e,t=!1;return this.totalIterations>this.maxIterations/3&&(t=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),e=this.totalDisplacement=c.length||u>=c[0].length)){for(var d=0;de}}]),e}()}),(function(e,t,n){function r(){}r.svd=function(e){this.U=null,this.V=null,this.s=null,this.m=0,this.n=0,this.m=e.length,this.n=e[0].length;var t=Math.min(this.m,this.n);this.s=function(e){for(var t=[];e-->0;)t.push(0);return t}(Math.min(this.m+1,this.n)),this.U=function(e){return function e(t){if(t.length==0)return 0;for(var n=[],r=0;r0;)t.push(0);return t}(this.n),i=function(e){for(var t=[];e-->0;)t.push(0);return t}(this.m),a=!0,o=!0,s=Math.min(this.m-1,this.n),c=Math.max(0,Math.min(this.n-2,this.m)),l=0;l=0;k--)if(this.s[k]!==0){for(var A=k+1;A=0;L--){if(function(e,t){return e&&t}(L0;){var U=void 0,W=void 0;for(U=E-2;U>=-1&&U!==-1;U--)if(Math.abs(n[U])<=re+ne*(Math.abs(this.s[U])+Math.abs(this.s[U+1]))){n[U]=0;break}if(U===E-2)W=4;else{var G=void 0;for(G=E-1;G>=U&&G!==U;G--){var ie=(G===E?0:Math.abs(n[G]))+(G===U+1?0:Math.abs(n[G-1]));if(Math.abs(this.s[G])<=re+ne*ie){this.s[G]=0;break}}G===U?W=3:G===E-1?W=1:(W=2,U=G)}switch(U++,W){case 1:var K=n[E-2];n[E-2]=0;for(var q=E-2;q>=U;q--){var J=r.hypot(this.s[q],K),Y=this.s[q]/J,X=K/J;if(this.s[q]=J,q!==U&&(K=-X*n[q-1],n[q-1]=Y*n[q-1]),o)for(var Z=0;Z=this.s[U+1]);){var De=this.s[U];if(this.s[U]=this.s[U+1],this.s[U+1]=De,o&&UMath.abs(t)?(n=t/e,n=Math.abs(e)*Math.sqrt(1+n*n)):t==0?n=0:(n=e/t,n=Math.abs(t)*Math.sqrt(1+n*n)),n},e.exports=r}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;i(this,e),this.sequence1=t,this.sequence2=n,this.match_score=r,this.mismatch_penalty=a,this.gap_penalty=o,this.iMax=t.length+1,this.jMax=n.length+1,this.grid=Array(this.iMax);for(var s=0;s=0;n--){var r=this.listeners[n];r.event===e&&r.callback===t&&this.listeners.splice(n,1)}},i.emit=function(e,t){for(var n=0;n{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(D()):typeof define==`function`&&define.amd?define([`layout-base`],r):typeof e==`object`?e.coseBase=r(D()):n.coseBase=r(n.layoutBase)})(e,function(e){return(()=>{var t={45:((e,t,n)=>{var r={};r.layoutBase=n(551),r.CoSEConstants=n(806),r.CoSEEdge=n(767),r.CoSEGraph=n(880),r.CoSEGraphManager=n(578),r.CoSELayout=n(765),r.CoSENode=n(991),r.ConstraintHandler=n(902),e.exports=r}),806:((e,t,n)=>{var r=n(551).FDLayoutConstants;function i(){}for(var a in r)i[a]=r[a];i.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,i.DEFAULT_RADIAL_SEPARATION=r.DEFAULT_EDGE_LENGTH,i.DEFAULT_COMPONENT_SEPERATION=60,i.TILE=!0,i.TILING_PADDING_VERTICAL=10,i.TILING_PADDING_HORIZONTAL=10,i.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,i.ENFORCE_CONSTRAINTS=!0,i.APPLY_LAYOUT=!0,i.RELAX_MOVEMENT_ON_CONSTRAINTS=!0,i.TREE_REDUCTION_ON_INCREMENTAL=!0,i.PURE_INCREMENTAL=i.DEFAULT_INCREMENTAL,e.exports=i}),767:((e,t,n)=>{var r=n(551).FDLayoutEdge;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),880:((e,t,n)=>{var r=n(551).LGraph;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),578:((e,t,n)=>{var r=n(551).LGraphManager;function i(e){r.call(this,e)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),765:((e,t,n)=>{var r=n(551).FDLayout,i=n(578),a=n(880),o=n(991),s=n(767),c=n(806),l=n(902),u=n(551).FDLayoutConstants,d=n(551).LayoutConstants,f=n(551).Point,p=n(551).PointD,m=n(551).DimensionD,h=n(551).Layout,g=n(551).Integer,_=n(551).IGeometry,v=n(551).LGraph,y=n(551).Transform,b=n(551).LinkedList;function x(){r.call(this),this.toBeTiled={},this.constraints={}}for(var S in x.prototype=Object.create(r.prototype),r)x[S]=r[S];x.prototype.newGraphManager=function(){var e=new i(this);return this.graphManager=e,e},x.prototype.newGraph=function(e){return new a(null,this.graphManager,e)},x.prototype.newNode=function(e){return new o(this.graphManager,e)},x.prototype.newEdge=function(e){return new s(null,null,e)},x.prototype.initParameters=function(){r.prototype.initParameters.call(this,arguments),this.isSubLayout||(c.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=c.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=c.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.gravityConstant=u.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=u.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=u.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=u.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1)},x.prototype.initSpringEmbedder=function(){r.prototype.initSpringEmbedder.call(this),this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/u.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=.04,this.coolingAdjuster=1},x.prototype.layout=function(){return d.DEFAULT_CREATE_BENDS_AS_NEEDED&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},x.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),!this.incremental){var e=this.getFlatForest();if(e.length>0)this.positionNodesRadially(e);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n),this.positionNodesRandomly()}}else if(c.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n)}return Object.keys(this.constraints).length>0&&(l.handleConstraints(this),this.initConstraintVariables()),this.initSpringEmbedder(),c.APPLY_LAYOUT&&this.runSpringEmbedder(),!0},x.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%u.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-this.coolingCycle**+(Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),t=this.nodesWithGravity.filter(function(t){return e.has(t)});this.graphManager.setAllNodesToApplyGravitation(t),this.graphManager.updateBounds(),this.updateGrid(),c.PURE_INCREMENTAL?this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL/2:this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),c.PURE_INCREMENTAL?this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL/2*((100-this.afterGrowthIterations)/100):this.coolingFactor=u.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var n=!this.isTreeGrowing&&!this.isGrowthFinished,r=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(n,r),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},x.prototype.getPositionsData=function(){for(var e=this.graphManager.getAllNodes(),t={},n=0;n0&&this.updateDisplacements();for(var n=0;n0&&(r.fixedNodeWeight=a)}}if(this.constraints.relativePlacementConstraint){var o=new Map,s=new Map;if(this.dummyToNodeForVerticalAlignment=new Map,this.dummyToNodeForHorizontalAlignment=new Map,this.fixedNodesOnHorizontal=new Set,this.fixedNodesOnVertical=new Set,this.fixedNodeSet.forEach(function(t){e.fixedNodesOnHorizontal.add(t),e.fixedNodesOnVertical.add(t)}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var l=this.constraints.alignmentConstraint.vertical,n=0;n=2*e.length/3;r--)t=Math.floor(Math.random()*(r+1)),n=e[r],e[r]=e[t],e[t]=n;return e},this.nodesInRelativeHorizontal=[],this.nodesInRelativeVertical=[],this.nodeToRelativeConstraintMapHorizontal=new Map,this.nodeToRelativeConstraintMapVertical=new Map,this.nodeToTempPositionMapHorizontal=new Map,this.nodeToTempPositionMapVertical=new Map,this.constraints.relativePlacementConstraint.forEach(function(t){if(t.left){var n=o.has(t.left)?o.get(t.left):t.left,r=o.has(t.right)?o.get(t.right):t.right;e.nodesInRelativeHorizontal.includes(n)||(e.nodesInRelativeHorizontal.push(n),e.nodeToRelativeConstraintMapHorizontal.set(n,[]),e.dummyToNodeForVerticalAlignment.has(n)?e.nodeToTempPositionMapHorizontal.set(n,e.idToNodeMap.get(e.dummyToNodeForVerticalAlignment.get(n)[0]).getCenterX()):e.nodeToTempPositionMapHorizontal.set(n,e.idToNodeMap.get(n).getCenterX())),e.nodesInRelativeHorizontal.includes(r)||(e.nodesInRelativeHorizontal.push(r),e.nodeToRelativeConstraintMapHorizontal.set(r,[]),e.dummyToNodeForVerticalAlignment.has(r)?e.nodeToTempPositionMapHorizontal.set(r,e.idToNodeMap.get(e.dummyToNodeForVerticalAlignment.get(r)[0]).getCenterX()):e.nodeToTempPositionMapHorizontal.set(r,e.idToNodeMap.get(r).getCenterX())),e.nodeToRelativeConstraintMapHorizontal.get(n).push({right:r,gap:t.gap}),e.nodeToRelativeConstraintMapHorizontal.get(r).push({left:n,gap:t.gap})}else{var i=s.has(t.top)?s.get(t.top):t.top,a=s.has(t.bottom)?s.get(t.bottom):t.bottom;e.nodesInRelativeVertical.includes(i)||(e.nodesInRelativeVertical.push(i),e.nodeToRelativeConstraintMapVertical.set(i,[]),e.dummyToNodeForHorizontalAlignment.has(i)?e.nodeToTempPositionMapVertical.set(i,e.idToNodeMap.get(e.dummyToNodeForHorizontalAlignment.get(i)[0]).getCenterY()):e.nodeToTempPositionMapVertical.set(i,e.idToNodeMap.get(i).getCenterY())),e.nodesInRelativeVertical.includes(a)||(e.nodesInRelativeVertical.push(a),e.nodeToRelativeConstraintMapVertical.set(a,[]),e.dummyToNodeForHorizontalAlignment.has(a)?e.nodeToTempPositionMapVertical.set(a,e.idToNodeMap.get(e.dummyToNodeForHorizontalAlignment.get(a)[0]).getCenterY()):e.nodeToTempPositionMapVertical.set(a,e.idToNodeMap.get(a).getCenterY())),e.nodeToRelativeConstraintMapVertical.get(i).push({bottom:a,gap:t.gap}),e.nodeToRelativeConstraintMapVertical.get(a).push({top:i,gap:t.gap})}});else{var d=new Map,f=new Map;this.constraints.relativePlacementConstraint.forEach(function(e){if(e.left){var t=o.has(e.left)?o.get(e.left):e.left,n=o.has(e.right)?o.get(e.right):e.right;d.has(t)?d.get(t).push(n):d.set(t,[n]),d.has(n)?d.get(n).push(t):d.set(n,[t])}else{var r=s.has(e.top)?s.get(e.top):e.top,i=s.has(e.bottom)?s.get(e.bottom):e.bottom;f.has(r)?f.get(r).push(i):f.set(r,[i]),f.has(i)?f.get(i).push(r):f.set(i,[r])}});var p=function(e,t){var n=[],r=[],i=new b,a=new Set,o=0;return e.forEach(function(s,c){if(!a.has(c)){n[o]=[],r[o]=!1;var l=c;for(i.push(l),a.add(l),n[o].push(l);i.length!=0;)l=i.shift(),t.has(l)&&(r[o]=!0),e.get(l).forEach(function(e){a.has(e)||(i.push(e),a.add(e),n[o].push(e))});o++}}),{components:n,isFixed:r}},m=p(d,e.fixedNodesOnHorizontal);this.componentsOnHorizontal=m.components,this.fixedComponentsOnHorizontal=m.isFixed;var h=p(f,e.fixedNodesOnVertical);this.componentsOnVertical=h.components,this.fixedComponentsOnVertical=h.isFixed}}},x.prototype.updateDisplacements=function(){var e=this;if(this.constraints.fixedNodeConstraint&&this.constraints.fixedNodeConstraint.forEach(function(t){var n=e.idToNodeMap.get(t.nodeId);n.displacementX=0,n.displacementY=0}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var t=this.constraints.alignmentConstraint.vertical,n=0;n1){var s;for(s=0;sr&&(r=Math.floor(o.y)),a=Math.floor(o.x+c.DEFAULT_COMPONENT_SEPERATION)}this.transform(new p(d.WORLD_CENTER_X-o.x/2,d.WORLD_CENTER_Y-o.y/2))},x.radialLayout=function(e,t,n){var r=Math.max(this.maxDiagonalInTree(e),c.DEFAULT_RADIAL_SEPARATION);x.branchRadialLayout(t,null,0,359,0,r);var i=v.calculateBounds(e),a=new y;a.setDeviceOrgX(i.getMinX()),a.setDeviceOrgY(i.getMinY()),a.setWorldOrgX(n.x),a.setWorldOrgY(n.y);for(var o=0;o1;){var g=h[0];h.splice(0,1);var v=u.indexOf(g);v>=0&&u.splice(v,1),p--,d--}m=t==null?0:(u.indexOf(h[0])+1)%p;for(var y=Math.abs(r-n)/d,b=m;f!=d;b=++b%p){var S=u[b].getOtherEnd(e);if(S!=t){var C=(n+f*y)%360,w=(C+y)%360;x.branchRadialLayout(S,e,C,w,i+a,a),f++}}},x.maxDiagonalInTree=function(e){for(var t=g.MIN_VALUE,n=0;nt&&(t=r)}return t},x.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},x.prototype.groupZeroDegreeMembers=function(){var e=this,t={};this.memberGroups={},this.idToDummyNode={};for(var n=[],r=this.graphManager.getAllNodes(),i=0;i1){var r=`DummyCompound_`+n;e.memberGroups[r]=t[n];var i=t[n][0].getParent(),a=new o(e.graphManager);a.id=r,a.paddingLeft=i.paddingLeft||0,a.paddingRight=i.paddingRight||0,a.paddingBottom=i.paddingBottom||0,a.paddingTop=i.paddingTop||0,e.idToDummyNode[r]=a;var s=e.getGraphManager().add(e.newGraph(),a),c=i.getChild();c.add(a);for(var l=0;li?(r.rect.x-=(r.labelWidth-i)/2,r.setWidth(r.labelWidth),r.labelMarginLeft=(r.labelWidth-i)/2):r.labelPosHorizontal==`right`&&r.setWidth(i+r.labelWidth)),r.labelHeight&&(r.labelPosVertical==`top`?(r.rect.y-=r.labelHeight,r.setHeight(a+r.labelHeight),r.labelMarginTop=r.labelHeight):r.labelPosVertical==`center`&&r.labelHeight>a?(r.rect.y-=(r.labelHeight-a)/2,r.setHeight(r.labelHeight),r.labelMarginTop=(r.labelHeight-a)/2):r.labelPosVertical==`bottom`&&r.setHeight(a+r.labelHeight))}})},x.prototype.repopulateCompounds=function(){for(var e=this.compoundOrder.length-1;e>=0;e--){var t=this.compoundOrder[e],n=t.id,r=t.paddingLeft,i=t.paddingTop,a=t.labelMarginLeft,o=t.labelMarginTop;this.adjustLocations(this.tiledMemberPack[n],t.rect.x,t.rect.y,r,i,a,o)}},x.prototype.repopulateZeroDegreeMembers=function(){var e=this,t=this.tiledZeroDegreePack;Object.keys(t).forEach(function(n){var r=e.idToDummyNode[n],i=r.paddingLeft,a=r.paddingTop,o=r.labelMarginLeft,s=r.labelMarginTop;e.adjustLocations(t[n],r.rect.x,r.rect.y,i,a,o,s)})},x.prototype.getToBeTiled=function(e){var t=e.id;if(this.toBeTiled[t]!=null)return this.toBeTiled[t];var n=e.getChild();if(n==null)return this.toBeTiled[t]=!1,!1;for(var r=n.getNodes(),i=0;i0)return this.toBeTiled[t]=!1,!1;if(a.getChild()==null){this.toBeTiled[a.id]=!1;continue}if(!this.getToBeTiled(a))return this.toBeTiled[t]=!1,!1}return this.toBeTiled[t]=!0,!0},x.prototype.getNodeDegree=function(e){e.id;for(var t=e.getEdges(),n=0,r=0;ru&&(u=f.rect.height)}n+=u+e.verticalPadding}},x.prototype.tileCompoundMembers=function(e,t){var n=this;this.tiledMemberPack=[],Object.keys(e).forEach(function(r){var i=t[r];if(n.tiledMemberPack[r]=n.tileNodes(e[r],i.paddingLeft+i.paddingRight),i.rect.width=n.tiledMemberPack[r].width,i.rect.height=n.tiledMemberPack[r].height,i.setCenter(n.tiledMemberPack[r].centerX,n.tiledMemberPack[r].centerY),i.labelMarginLeft=0,i.labelMarginTop=0,c.NODE_DIMENSIONS_INCLUDE_LABELS){var a=i.rect.width,o=i.rect.height;i.labelWidth&&(i.labelPosHorizontal==`left`?(i.rect.x-=i.labelWidth,i.setWidth(a+i.labelWidth),i.labelMarginLeft=i.labelWidth):i.labelPosHorizontal==`center`&&i.labelWidth>a?(i.rect.x-=(i.labelWidth-a)/2,i.setWidth(i.labelWidth),i.labelMarginLeft=(i.labelWidth-a)/2):i.labelPosHorizontal==`right`&&i.setWidth(a+i.labelWidth)),i.labelHeight&&(i.labelPosVertical==`top`?(i.rect.y-=i.labelHeight,i.setHeight(o+i.labelHeight),i.labelMarginTop=i.labelHeight):i.labelPosVertical==`center`&&i.labelHeight>o?(i.rect.y-=(i.labelHeight-o)/2,i.setHeight(i.labelHeight),i.labelMarginTop=(i.labelHeight-o)/2):i.labelPosVertical==`bottom`&&i.setHeight(o+i.labelHeight))}})},x.prototype.tileNodes=function(e,t){var n=this.tileNodesByFavoringDim(e,t,!0),r=this.tileNodesByFavoringDim(e,t,!1),i=this.getOrgRatio(n);return this.getOrgRatio(r)s&&(s=e.getWidth())});var l=a/i,u=o/i,d=(n-r)**2+4*(l+r)*(u+n)*i,f=(r-n+Math.sqrt(d))/(2*(l+r)),p;t?(p=Math.ceil(f),p==f&&p++):p=Math.floor(f);var m=p*(l+r)-r;return s>m&&(m=s),m+=r*2,m},x.prototype.tileNodesByFavoringDim=function(e,t,n){var r=c.TILING_PADDING_VERTICAL,i=c.TILING_PADDING_HORIZONTAL,a=c.TILING_COMPARE_BY,o={rows:[],rowWidth:[],rowHeight:[],width:0,height:t,verticalPadding:r,horizontalPadding:i,centerX:0,centerY:0};a&&(o.idealRowWidth=this.calcIdealRowWidth(e,n));var s=function(e){return e.rect.width*e.rect.height},l=function(e,t){return s(t)-s(e)};e.sort(function(e,t){var n=l;return o.idealRowWidth?(n=a,n(e.id,t.id)):n(e,t)});for(var u=0,d=0,f=0;f0&&(a+=e.horizontalPadding),e.rowWidth[n]=a,e.width0&&(o+=e.verticalPadding);var s=0;o>e.rowHeight[n]&&(s=e.rowHeight[n],e.rowHeight[n]=o,s=e.rowHeight[n]-s),e.height+=s,e.rows[n].push(t)},x.prototype.getShortestRowIndex=function(e){for(var t=-1,n=Number.MAX_VALUE,r=0;rn&&(t=r,n=e.rowWidth[r]);return t},x.prototype.canAddHorizontal=function(e,t,n){if(e.idealRowWidth){var r=e.rows.length-1;return e.rowWidth[r]+t+e.horizontalPadding<=e.idealRowWidth}var i=this.getShortestRowIndex(e);if(i<0)return!0;var a=e.rowWidth[i];if(a+e.horizontalPadding+t<=e.width)return!0;var o=0;e.rowHeight[i]0&&(o=n+e.verticalPadding-e.rowHeight[i]);var s=e.width-a>=t+e.horizontalPadding?(e.height+o)/(a+t+e.horizontalPadding):(e.height+o)/e.width;o=n+e.verticalPadding;var c=e.widtha&&t!=n){r.splice(-1,1),e.rows[n].push(i),e.rowWidth[t]=e.rowWidth[t]-a,e.rowWidth[n]=e.rowWidth[n]+a,e.width=e.rowWidth[instance.getLongestRowIndex(e)];for(var o=Number.MIN_VALUE,s=0;so&&(o=r[s].height);t>0&&(o+=e.verticalPadding);var c=e.rowHeight[t]+e.rowHeight[n];e.rowHeight[t]=o,e.rowHeight[n]0)for(var d=i;d<=a;d++)l[0]+=this.grid[d][o-1].length+this.grid[d][o].length-1;if(a0)for(var d=o;d<=s;d++)l[3]+=this.grid[i-1][d].length+this.grid[i][d].length-1;for(var f=g.MAX_VALUE,p,m,h=0;h{var r=n(551).FDLayoutNode,i=n(551).IMath;function a(e,t,n,i){r.call(this,e,t,n,i)}for(var o in a.prototype=Object.create(r.prototype),r)a[o]=r[o];a.prototype.calculateDisplacement=function(){var e=this.graphManager.getLayout();this.getChild()!=null&&this.fixedNodeWeight?(this.displacementX+=e.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.fixedNodeWeight,this.displacementY+=e.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.fixedNodeWeight):(this.displacementX+=e.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY+=e.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren),Math.abs(this.displacementX)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementX=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementX)),Math.abs(this.displacementY)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementY=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementY)),this.child&&this.child.getNodes().length>0&&this.propogateDisplacementToChildren(this.displacementX,this.displacementY)},a.prototype.propogateDisplacementToChildren=function(e,t){for(var n=this.getChild().getNodes(),r,i=0;i{function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t0){var a=0;r.forEach(function(e){t==`horizontal`?(f.set(e,c.has(e)?l[c.get(e)]:i.get(e)),a+=f.get(e)):(f.set(e,c.has(e)?u[c.get(e)]:i.get(e)),a+=f.get(e))}),a/=r.length,e.forEach(function(e){n.has(e)||f.set(e,a)})}else{var o=0;e.forEach(function(e){t==`horizontal`?o+=c.has(e)?l[c.get(e)]:i.get(e):o+=c.has(e)?u[c.get(e)]:i.get(e)}),o/=e.length,e.forEach(function(e){f.set(e,o)})}});for(var h=function(){var r=m.shift();e.get(r).forEach(function(e){if(f.get(e.id)o&&(o=v),ys&&(s=y)}}catch(e){p=!0,m=e}finally{try{!d&&h.return&&h.return()}finally{if(p)throw m}}var b=(r+o)/2-(a+s)/2,x=!0,S=!1,C=void 0;try{for(var w=e[Symbol.iterator](),T;!(x=(T=w.next()).done);x=!0){var E=T.value;f.set(E,f.get(E)+b)}}catch(e){S=!0,C=e}finally{try{!x&&w.return&&w.return()}finally{if(S)throw C}}})}return f},v=function(e){var t=0,n=0,r=0,i=0;if(e.forEach(function(e){e.left?l[c.get(e.left)]-l[c.get(e.right)]>=0?t++:n++:u[c.get(e.top)]-u[c.get(e.bottom)]>=0?r++:i++}),t>n&&r>i)for(var a=0;an)for(var o=0;oi)for(var s=0;s1)t.fixedNodeConstraint.forEach(function(e,t){S[t]=[e.position.x,e.position.y],C[t]=[l[c.get(e.nodeId)],u[c.get(e.nodeId)]]}),w=!0;else if(t.alignmentConstraint)(function(){var e=0;if(t.alignmentConstraint.vertical){for(var n=t.alignmentConstraint.vertical,i=function(t){var i=new Set;n[t].forEach(function(e){i.add(e)});var a=new Set([].concat(r(i)).filter(function(e){return E.has(e)})),o=void 0;o=a.size>0?l[c.get(a.values().next().value)]:g(i).x,n[t].forEach(function(t){S[e]=[o,u[c.get(t)]],C[e]=[l[c.get(t)],u[c.get(t)]],e++})},a=0;a0?l[c.get(i.values().next().value)]:g(n).y,o[t].forEach(function(t){S[e]=[l[c.get(t)],a],C[e]=[l[c.get(t)],u[c.get(t)]],e++})},d=0;dA&&(A=k[M].length,j=M);if(A0){var W={x:0,y:0};t.fixedNodeConstraint.forEach(function(e,t){var n={x:l[c.get(e.nodeId)],y:u[c.get(e.nodeId)]},r=e.position,i=h(r,n);W.x+=i.x,W.y+=i.y}),W.x/=t.fixedNodeConstraint.length,W.y/=t.fixedNodeConstraint.length,l.forEach(function(e,t){l[t]+=W.x}),u.forEach(function(e,t){u[t]+=W.y}),t.fixedNodeConstraint.forEach(function(e){l[c.get(e.nodeId)]=e.position.x,u[c.get(e.nodeId)]=e.position.y})}if(t.alignmentConstraint){if(t.alignmentConstraint.vertical)for(var G=t.alignmentConstraint.vertical,ie=function(e){var t=new Set;G[e].forEach(function(e){t.add(e)});var n=new Set([].concat(r(t)).filter(function(e){return E.has(e)})),i=void 0;i=n.size>0?l[c.get(n.values().next().value)]:g(t).x,t.forEach(function(e){E.has(e)||(l[c.get(e)]=i)})},K=0;K0?u[c.get(n.values().next().value)]:g(t).y,t.forEach(function(e){E.has(e)||(u[c.get(e)]=i)})},Y=0;Y{t.exports=e})},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}return r(45)})()})})),k=e(t(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(O()):typeof define==`function`&&define.amd?define([`cose-base`],r):typeof e==`object`?e.cytoscapeFcose=r(O()):n.cytoscapeFcose=r(n.coseBase)})(e,function(e){return(()=>{var t={658:(e=>{e.exports=Object.assign==null?function(e){return[...arguments].slice(1).forEach(function(t){Object.keys(t).forEach(function(n){return e[n]=t[n]})}),e}:Object.assign.bind(Object)}),548:((e,t,n)=>{var r=function(){function e(e,t){var n=[],r=!0,i=!1,a=void 0;try{for(var o=e[Symbol.iterator](),s;!(r=(s=o.next()).done)&&(n.push(s.value),!(t&&n.length===t));r=!0);}catch(e){i=!0,a=e}finally{try{!r&&o.return&&o.return()}finally{if(i)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw TypeError(`Invalid attempt to destructure non-iterable instance`)}}(),i=n(140).layoutBase.LinkedList,a={};a.getTopMostNodes=function(e){for(var t={},n=0;n0&&l.merge(e)});for(var u=0;u1){l=s[0],u=l.connectedEdges().length,s.forEach(function(e){e.connectedEdges().length0&&r.set(`dummy`+(r.size+1),p),m},a.relocateComponent=function(e,t,n){if(!n.fixedNodeConstraint){var i=1/0,a=-1/0,o=1/0,s=-1/0;if(n.quality==`draft`){var c=!0,l=!1,u=void 0;try{for(var d=t.nodeIndexes[Symbol.iterator](),f;!(c=(f=d.next()).done);c=!0){var p=f.value,m=r(p,2),h=m[0],g=m[1],_=n.cy.getElementById(h);if(_){var v=_.boundingBox(),y=t.xCoords[g]-v.w/2,b=t.xCoords[g]+v.w/2,x=t.yCoords[g]-v.h/2,S=t.yCoords[g]+v.h/2;ya&&(a=b),xs&&(s=S)}}}catch(e){l=!0,u=e}finally{try{!c&&d.return&&d.return()}finally{if(l)throw u}}var C=e.x-(a+i)/2,w=e.y-(s+o)/2;t.xCoords=t.xCoords.map(function(e){return e+C}),t.yCoords=t.yCoords.map(function(e){return e+w})}else{Object.keys(t).forEach(function(e){var n=t[e],r=n.getRect().x,c=n.getRect().x+n.getRect().width,l=n.getRect().y,u=n.getRect().y+n.getRect().height;ra&&(a=c),ls&&(s=u)});var T=e.x-(a+i)/2,E=e.y-(s+o)/2;Object.keys(t).forEach(function(e){var n=t[e];n.setCenter(n.getCenterX()+T,n.getCenterY()+E)})}}},a.calcBoundingBox=function(e,t,n,r){for(var i=2**53-1,a=-(2**53-1),o=2**53-1,s=-(2**53-1),c=void 0,l=void 0,u=void 0,d=void 0,f=e.descendants().not(`:parent`),p=f.length,m=0;mc&&(i=c),au&&(o=u),s{var r=n(548),i=n(140).CoSELayout,a=n(140).CoSENode,o=n(140).layoutBase.PointD,s=n(140).layoutBase.DimensionD,c=n(140).layoutBase.LayoutConstants,l=n(140).layoutBase.FDLayoutConstants,u=n(140).CoSEConstants;e.exports={coseLayout:function(e,t){var n=e.cy,d=e.eles,f=d.nodes(),p=d.edges(),m=void 0,h=void 0,g=void 0,_={};e.randomize&&(m=t.nodeIndexes,h=t.xCoords,g=t.yCoords);var v=function(e){return typeof e==`function`},y=function(e,t){return v(e)?e(t):e},b=r.calcParentsWithoutChildren(n,d),x=function e(t,n,i,c){for(var l=n.length,u=0;u0){var S=void 0;S=i.getGraphManager().add(i.newGraph(),p),e(S,f,i,c)}}},S=function(t,n,r){for(var i=0,a=0,o=0;o0?u.DEFAULT_EDGE_LENGTH=l.DEFAULT_EDGE_LENGTH=i/a:v(e.idealEdgeLength)?u.DEFAULT_EDGE_LENGTH=l.DEFAULT_EDGE_LENGTH=50:u.DEFAULT_EDGE_LENGTH=l.DEFAULT_EDGE_LENGTH=e.idealEdgeLength,u.MIN_REPULSION_DIST=l.MIN_REPULSION_DIST=l.DEFAULT_EDGE_LENGTH/10,u.DEFAULT_RADIAL_SEPARATION=l.DEFAULT_EDGE_LENGTH)},C=function(e,t){t.fixedNodeConstraint&&(e.constraints.fixedNodeConstraint=t.fixedNodeConstraint),t.alignmentConstraint&&(e.constraints.alignmentConstraint=t.alignmentConstraint),t.relativePlacementConstraint&&(e.constraints.relativePlacementConstraint=t.relativePlacementConstraint)};e.nestingFactor!=null&&(u.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=l.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=e.nestingFactor),e.gravity!=null&&(u.DEFAULT_GRAVITY_STRENGTH=l.DEFAULT_GRAVITY_STRENGTH=e.gravity),e.numIter!=null&&(u.MAX_ITERATIONS=l.MAX_ITERATIONS=e.numIter),e.gravityRange!=null&&(u.DEFAULT_GRAVITY_RANGE_FACTOR=l.DEFAULT_GRAVITY_RANGE_FACTOR=e.gravityRange),e.gravityCompound!=null&&(u.DEFAULT_COMPOUND_GRAVITY_STRENGTH=l.DEFAULT_COMPOUND_GRAVITY_STRENGTH=e.gravityCompound),e.gravityRangeCompound!=null&&(u.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=l.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=e.gravityRangeCompound),e.initialEnergyOnIncremental!=null&&(u.DEFAULT_COOLING_FACTOR_INCREMENTAL=l.DEFAULT_COOLING_FACTOR_INCREMENTAL=e.initialEnergyOnIncremental),e.tilingCompareBy!=null&&(u.TILING_COMPARE_BY=e.tilingCompareBy),e.quality==`proof`?c.QUALITY=2:c.QUALITY=0,u.NODE_DIMENSIONS_INCLUDE_LABELS=l.NODE_DIMENSIONS_INCLUDE_LABELS=c.NODE_DIMENSIONS_INCLUDE_LABELS=e.nodeDimensionsIncludeLabels,u.DEFAULT_INCREMENTAL=l.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=!e.randomize,u.ANIMATE=l.ANIMATE=c.ANIMATE=e.animate,u.TILE=e.tile,u.TILING_PADDING_VERTICAL=typeof e.tilingPaddingVertical==`function`?e.tilingPaddingVertical.call():e.tilingPaddingVertical,u.TILING_PADDING_HORIZONTAL=typeof e.tilingPaddingHorizontal==`function`?e.tilingPaddingHorizontal.call():e.tilingPaddingHorizontal,u.DEFAULT_INCREMENTAL=l.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=!0,u.PURE_INCREMENTAL=!e.randomize,c.DEFAULT_UNIFORM_LEAF_NODE_SIZES=e.uniformNodeDimensions,e.step==`transformed`&&(u.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,u.ENFORCE_CONSTRAINTS=!1,u.APPLY_LAYOUT=!1),e.step==`enforced`&&(u.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,u.ENFORCE_CONSTRAINTS=!0,u.APPLY_LAYOUT=!1),e.step==`cose`&&(u.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,u.ENFORCE_CONSTRAINTS=!1,u.APPLY_LAYOUT=!0),e.step==`all`&&(e.randomize?u.TRANSFORM_ON_CONSTRAINT_HANDLING=!0:u.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,u.ENFORCE_CONSTRAINTS=!0,u.APPLY_LAYOUT=!0),e.fixedNodeConstraint||e.alignmentConstraint||e.relativePlacementConstraint?u.TREE_REDUCTION_ON_INCREMENTAL=!1:u.TREE_REDUCTION_ON_INCREMENTAL=!0;var w=new i,T=w.newGraphManager();return x(T.addRoot(),r.getTopMostNodes(f),w,e),S(w,T,p),C(w,e),w.runLayout(),_}}}),212:((e,t,n)=>{var r=function(){function e(e,t){for(var n=0;n0)if(f){var p=o.getTopMostNodes(t.eles.nodes());if(l=o.connectComponents(n,t.eles,p),l.forEach(function(e){var t=e.boundingBox();u.push({x:t.x1+t.w/2,y:t.y1+t.h/2})}),t.randomize&&l.forEach(function(e){t.eles=e,i.push(s(t))}),t.quality=="default"||t.quality==`proof`){var m=n.collection();if(t.tile){var h=new Map,g=[],_=[],v=0,y={nodeIndexes:h,xCoords:g,yCoords:_},b=[];if(l.forEach(function(e,t){e.edges().length==0&&(e.nodes().forEach(function(t,n){m.merge(e.nodes()[n]),t.isParent()||(y.nodeIndexes.set(e.nodes()[n].id(),v++),y.xCoords.push(e.nodes()[0].position().x),y.yCoords.push(e.nodes()[0].position().y))}),b.push(t))}),m.length>1){var x=m.boundingBox();u.push({x:x.x1+x.w/2,y:x.y1+x.h/2}),l.push(m),i.push(y);for(var S=b.length-1;S>=0;S--)l.splice(b[S],1),i.splice(b[S],1),u.splice(b[S],1)}}l.forEach(function(e,n){t.eles=e,a.push(c(t,i[n])),o.relocateComponent(u[n],a[n],t)})}else l.forEach(function(e,n){o.relocateComponent(u[n],i[n],t)});var C=new Set;if(l.length>1){var w=[],T=r.filter(function(e){return e.css(`display`)==`none`});l.forEach(function(e,n){var r=void 0;if(t.quality==`draft`&&(r=i[n].nodeIndexes),e.nodes().not(T).length>0){var s={};s.edges=[],s.nodes=[];var c=void 0;e.nodes().not(T).forEach(function(e){if(t.quality==`draft`)if(!e.isParent())c=r.get(e.id()),s.nodes.push({x:i[n].xCoords[c]-e.boundingbox().w/2,y:i[n].yCoords[c]-e.boundingbox().h/2,width:e.boundingbox().w,height:e.boundingbox().h});else{var l=o.calcBoundingBox(e,i[n].xCoords,i[n].yCoords,r);s.nodes.push({x:l.topLeftX,y:l.topLeftY,width:l.width,height:l.height})}else a[n][e.id()]&&s.nodes.push({x:a[n][e.id()].getLeft(),y:a[n][e.id()].getTop(),width:a[n][e.id()].getWidth(),height:a[n][e.id()].getHeight()})}),e.edges().forEach(function(e){var c=e.source(),l=e.target();if(c.css(`display`)!=`none`&&l.css(`display`)!=`none`)if(t.quality==`draft`){var u=r.get(c.id()),d=r.get(l.id()),f=[],p=[];if(c.isParent()){var m=o.calcBoundingBox(c,i[n].xCoords,i[n].yCoords,r);f.push(m.topLeftX+m.width/2),f.push(m.topLeftY+m.height/2)}else f.push(i[n].xCoords[u]),f.push(i[n].yCoords[u]);if(l.isParent()){var h=o.calcBoundingBox(l,i[n].xCoords,i[n].yCoords,r);p.push(h.topLeftX+h.width/2),p.push(h.topLeftY+h.height/2)}else p.push(i[n].xCoords[d]),p.push(i[n].yCoords[d]);s.edges.push({startX:f[0],startY:f[1],endX:p[0],endY:p[1]})}else a[n][c.id()]&&a[n][l.id()]&&s.edges.push({startX:a[n][c.id()].getCenterX(),startY:a[n][c.id()].getCenterY(),endX:a[n][l.id()].getCenterX(),endY:a[n][l.id()].getCenterY()})}),s.nodes.length>0&&(w.push(s),C.add(n))}});var E=d.packComponents(w,t.randomize).shifts;if(t.quality==`draft`)i.forEach(function(e,t){var n=e.xCoords.map(function(e){return e+E[t].dx}),r=e.yCoords.map(function(e){return e+E[t].dy});e.xCoords=n,e.yCoords=r});else{var D=0;C.forEach(function(e){Object.keys(a[e]).forEach(function(t){var n=a[e][t];n.setCenter(n.getCenterX()+E[D].dx,n.getCenterY()+E[D].dy)}),D++})}}}else{var O=t.eles.boundingBox();if(u.push({x:O.x1+O.w/2,y:O.y1+O.h/2}),t.randomize){var k=s(t);i.push(k)}t.quality=="default"||t.quality==`proof`?(a.push(c(t,i[0])),o.relocateComponent(u[0],a[0],t)):o.relocateComponent(u[0],i[0],t)}var A=function(e,n){if(t.quality=="default"||t.quality==`proof`){typeof e==`number`&&(e=n);var r=void 0,o=void 0,s=e.data(`id`);return a.forEach(function(e){s in e&&(r={x:e[s].getRect().getCenterX(),y:e[s].getRect().getCenterY()},o=e[s])}),t.nodeDimensionsIncludeLabels&&(o.labelWidth&&(o.labelPosHorizontal==`left`?r.x+=o.labelWidth/2:o.labelPosHorizontal==`right`&&(r.x-=o.labelWidth/2)),o.labelHeight&&(o.labelPosVertical==`top`?r.y+=o.labelHeight/2:o.labelPosVertical==`bottom`&&(r.y-=o.labelHeight/2))),r??={x:e.position(`x`),y:e.position(`y`)},{x:r.x,y:r.y}}else{var c=void 0;return i.forEach(function(t){var n=t.nodeIndexes.get(e.id());n!=null&&(c={x:t.xCoords[n],y:t.yCoords[n]})}),c??={x:e.position(`x`),y:e.position(`y`)},{x:c.x,y:c.y}}};if(t.quality=="default"||t.quality==`proof`||t.randomize){var j=o.calcParentsWithoutChildren(n,r),M=r.filter(function(e){return e.css(`display`)==`none`});t.eles=r.not(M),r.nodes().not(`:parent`).not(M).layoutPositions(e,t,A),j.length>0&&j.forEach(function(e){e.position(A(e))})}else console.log(`If randomize option is set to false, then quality option must be 'default' or 'proof'.`)}}]),e}()}),657:((e,t,n)=>{var r=n(548),i=n(140).layoutBase.Matrix,a=n(140).layoutBase.SVD;e.exports={spectralLayout:function(e){var t=e.cy,n=e.eles,o=n.nodes(),s=n.nodes(`:parent`),c=new Map,l=new Map,u=new Map,d=[],f=[],p=[],m=[],h=[],g=[],_=[],v=[],y=void 0,b=1e8,x=1e-9,S=e.piTol,C=e.samplingType,w=e.nodeSeparation,T=void 0,E=function(){for(var e=0,t=0,n=!1;t=i;){o=r[i++];for(var m=d[o],_=0;_u&&(u=h[x],f=x)}return f},O=function(e){var t=void 0;if(e){t=Math.floor(Math.random()*y);for(var n=0;n=1)break;u=l}for(var h=0;h=1)break;u=l}for(var b=0;b0&&(r.isParent()?d[t].push(u.get(r.id())):d[t].push(r.id()))})});var B=function(e){var n=l.get(e),r=void 0;c.get(e).forEach(function(i){r=t.getElementById(i).isParent()?u.get(i):i,d[n].push(r),d[l.get(r)].push(e)})},V=!0,ee=!1,te=void 0;try{for(var H=c.keys()[Symbol.iterator](),ne;!(V=(ne=H.next()).done);V=!0){var re=ne.value;B(re)}}catch(e){ee=!0,te=e}finally{try{!V&&H.return&&H.return()}finally{if(ee)throw te}}y=l.size;var U=void 0;if(y>2){T=y{var r=n(212),i=function(e){e&&e(`layout`,`fcose`,r)};typeof cytoscape<`u`&&i(cytoscape),e.exports=i}),140:(t=>{t.exports=e})},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e](a,a.exports,r),a.exports}return r(579)})()})}))(),1),A={L:`left`,R:`right`,T:`top`,B:`bottom`},j={L:n(e=>`${e},${e/2} 0,${e} 0,0`,`L`),R:n(e=>`0,${e/2} ${e},0 ${e},${e}`,`R`),T:n(e=>`0,0 ${e},0 ${e/2},${e}`,`T`),B:n(e=>`${e/2},0 ${e},${e} 0,${e}`,`B`)},M={L:n((e,t)=>e-t+2,`L`),R:n((e,t)=>e-2,`R`),T:n((e,t)=>e-t+2,`T`),B:n((e,t)=>e-2,`B`)},N=n(function(e){return F(e)?e===`L`?`R`:`L`:e===`T`?`B`:`T`},`getOppositeArchitectureDirection`),P=n(function(e){let t=e;return t===`L`||t===`R`||t===`T`||t===`B`},`isArchitectureDirection`),F=n(function(e){let t=e;return t===`L`||t===`R`},`isArchitectureDirectionX`),I=n(function(e){let t=e;return t===`T`||t===`B`},`isArchitectureDirectionY`),L=n(function(e,t){let n=F(e)&&I(t),r=I(e)&&F(t);return n||r},`isArchitectureDirectionXY`),R=n(function(e){let t=e[0],n=e[1],r=F(t)&&I(n),i=I(t)&&F(n);return r||i},`isArchitecturePairXY`),z=n(function(e){return e!==`LL`&&e!==`RR`&&e!==`TT`&&e!==`BB`},`isValidArchitectureDirectionPair`),B=n(function(e,t){let n=`${e}${t}`;return z(n)?n:void 0},`getArchitectureDirectionPair`),V=n(function([e,t],n){let r=n[0],i=n[1];return F(r)?I(i)?[e+(r===`L`?-1:1),t+(i===`T`?1:-1)]:[e+(r===`L`?-1:1),t]:F(i)?[e+(i===`L`?1:-1),t+(r===`T`?1:-1)]:[e,t+(r===`T`?1:-1)]},`shiftPositionByArchitectureDirectionPair`),ee=n(function(e){return e===`LT`||e===`TL`?[1,1]:e===`BL`||e===`LB`?[1,-1]:e===`BR`||e===`RB`?[-1,-1]:[-1,1]},`getArchitectureDirectionXYFactors`),te=n(function(e,t){return L(e,t)?`bend`:F(e)?`horizontal`:`vertical`},`getArchitectureDirectionAlignment`),H=n(function(e){return e.type===`service`},`isArchitectureService`),ne=n(function(e){return e.type===`junction`},`isArchitectureJunction`),re=n(e=>e.data(),`edgeData`),U=n(e=>e.data(),`nodeData`),W=d.architecture,G=class{constructor(){this.nodes={},this.groups={},this.edges=[],this.layoutHints=[],this.registeredIds={},this.elements={},this.diagramId=``,this.setAccTitle=c,this.getAccTitle=h,this.setDiagramTitle=s,this.getDiagramTitle=p,this.getAccDescription=f,this.setAccDescription=a,this.clear()}static{n(this,`ArchitectureDB`)}setDiagramId(e){this.diagramId=e}getDiagramId(){return this.diagramId}clear(){this.nodes={},this.groups={},this.edges=[],this.layoutHints=[],this.registeredIds={},this.dataStructures=void 0,this.elements={},this.diagramId=``,l()}addService({id:e,icon:t,in:n,title:r,iconText:i}){if(this.registeredIds[e]!==void 0)throw Error(`The service id [${e}] is already in use by another ${this.registeredIds[e]}`);if(n!==void 0){if(e===n)throw Error(`The service [${e}] cannot be placed within itself`);if(this.registeredIds[n]===void 0)throw Error(`The service [${e}]'s parent does not exist. Please make sure the parent is created before this service`);if(this.registeredIds[n]===`node`)throw Error(`The service [${e}]'s parent is not a group`)}this.registeredIds[e]=`node`,this.nodes[e]={id:e,type:`service`,icon:t,iconText:i,title:r,edges:[],in:n}}getServices(){return Object.values(this.nodes).filter(H)}addJunction({id:e,in:t}){if(this.registeredIds[e]!==void 0)throw Error(`The junction id [${e}] is already in use by another ${this.registeredIds[e]}`);if(t!==void 0){if(e===t)throw Error(`The junction [${e}] cannot be placed within itself`);if(this.registeredIds[t]===void 0)throw Error(`The junction [${e}]'s parent does not exist. Please make sure the parent is created before this junction`);if(this.registeredIds[t]===`node`)throw Error(`The junction [${e}]'s parent is not a group`)}this.registeredIds[e]=`node`,this.nodes[e]={id:e,type:`junction`,edges:[],in:t}}getJunctions(){return Object.values(this.nodes).filter(ne)}getNodes(){return Object.values(this.nodes)}getNode(e){return this.nodes[e]??null}addGroup({id:e,icon:t,in:n,title:r}){if(this.registeredIds?.[e]!==void 0)throw Error(`The group id [${e}] is already in use by another ${this.registeredIds[e]}`);if(n!==void 0){if(e===n)throw Error(`The group [${e}] cannot be placed within itself`);if(this.registeredIds?.[n]===void 0)throw Error(`The group [${e}]'s parent does not exist. Please make sure the parent is created before this group`);if(this.registeredIds?.[n]===`node`)throw Error(`The group [${e}]'s parent is not a group`)}this.registeredIds[e]=`group`,this.groups[e]={id:e,icon:t,title:r,in:n}}getGroups(){return Object.values(this.groups)}addEdge({lhsId:e,rhsId:t,lhsDir:n,rhsDir:r,lhsInto:i,rhsInto:a,lhsGroup:o,rhsGroup:s,title:c}){if(!P(n))throw Error(`Invalid direction given for left hand side of edge ${e}--${t}. Expected (L,R,T,B) got ${String(n)}`);if(!P(r))throw Error(`Invalid direction given for right hand side of edge ${e}--${t}. Expected (L,R,T,B) got ${String(r)}`);if(this.nodes[e]===void 0&&this.groups[e]===void 0)throw Error(`The left-hand id [${e}] does not yet exist. Please create the service/group before declaring an edge to it.`);if(this.nodes[t]===void 0&&this.groups[t]===void 0)throw Error(`The right-hand id [${t}] does not yet exist. Please create the service/group before declaring an edge to it.`);let l=this.nodes[e].in,u=this.nodes[t].in;if(o&&l&&u&&l==u)throw Error(`The left-hand id [${e}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);if(s&&l&&u&&l==u)throw Error(`The right-hand id [${t}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);let d={lhsId:e,lhsDir:n,lhsInto:i,lhsGroup:o,rhsId:t,rhsDir:r,rhsInto:a,rhsGroup:s,title:c};this.edges.push(d),this.nodes[e]&&this.nodes[t]&&(this.nodes[e].edges.push(this.edges[this.edges.length-1]),this.nodes[t].edges.push(this.edges[this.edges.length-1]))}getEdges(){return this.edges}addLayoutHint(e){if(e.members.length<2)throw Error(`An align directive requires at least two members; got ${e.members.length}`);let t=new Set;e.members.forEach(n=>{if(this.registeredIds[n]!==`node`)throw Error(`align ${e.direction} references [${n}], which is not a service or junction`);if(t.has(n))throw Error(`align ${e.direction} lists [${n}] more than once`);t.add(n)}),this.layoutHints.push(e)}getLayoutHints(){return this.layoutHints}getDataStructures(){if(this.dataStructures===void 0){let e={},t=Object.entries(this.nodes).reduce((t,[n,r])=>(t[n]=r.edges.reduce((t,r)=>{let i=this.getNode(r.lhsId)?.in,a=this.getNode(r.rhsId)?.in;if(i&&a&&i!==a){let t=te(r.lhsDir,r.rhsDir);t!==`bend`&&(e[i]??={},e[i][a]=t,e[a]??={},e[a][i]=t)}if(r.lhsId===n){let e=B(r.lhsDir,r.rhsDir);e&&(t[e]=r.rhsId)}else{let e=B(r.rhsDir,r.lhsDir);e&&(t[e]=r.lhsId)}return t},{}),t),{}),r=Object.keys(t)[0],i={[r]:1},a=Object.keys(t).reduce((e,t)=>t===r?e:{...e,[t]:1},{}),o=n(e=>{let n={[e]:[0,0]},r=[e];for(;r.length>0;){let e=r.shift();if(e){i[e]=1,delete a[e];let o=t[e],[s,c]=n[e];Object.entries(o).forEach(([e,t])=>{i[t]||(n[t]=V([s,c],e),r.push(t))})}}return n},`BFS`),s=[o(r)];for(;Object.keys(a).length>0;)s.push(o(Object.keys(a)[0]));this.dataStructures={adjList:t,spatialMaps:s,groupAlignments:e}}return this.dataStructures}setElementForId(e,t){this.elements[e]=t}getElementById(e){return this.elements[e]}getConfig(){return v({...W,...u().architecture})}getConfigField(e){return this.getConfig()[e]}},ie=n((e,t)=>{b(e,t),e.groups.map(e=>t.addGroup(e)),e.services.map(e=>t.addService({...e,type:`service`})),e.junctions.map(e=>t.addJunction({...e,type:`junction`})),e.edges.map(e=>t.addEdge(e)),e.alignments?.map(e=>t.addLayoutHint({direction:e.direction,members:[...e.members]}))},`populateDb`),K={parser:{yy:void 0},parse:n(async e=>{let t=await x(`architecture`,e);r.debug(t);let n=K.parser?.yy;if(!(n instanceof G))throw Error(`parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);ie(t,n)},`parse`)},q=n(e=>` + .edge { + stroke-width: ${e.archEdgeWidth}; + stroke: ${e.archEdgeColor}; + fill: none; + } + + .arrow { + fill: ${e.archEdgeArrowColor}; + } + + .node-bkg { + fill: none; + stroke: ${e.archGroupBorderColor}; + stroke-width: ${e.archGroupBorderWidth}; + stroke-dasharray: 8; + } + .node-icon-text { + display: flex; + align-items: center; + } + + .node-icon-text > div { + color: #fff; + margin: 1px; + height: fit-content; + text-align: center; + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + } +`,`getStyles`);function J(e,t){if(e===0)return t();let n=Math.random,r=e>>>0;Math.random=function(){r=r+1831565813>>>0;let e=r;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296};try{return t()}finally{Math.random=n}}n(J,`withSeededRandom`);var Y=n(e=>`${e}`,`wrapIcon`),X={prefix:`mermaid-architecture`,height:80,width:80,icons:{database:{body:Y(``)},server:{body:Y(``)},disk:{body:Y(``)},internet:{body:Y(``)},cloud:{body:Y(``)},unknown:S,blank:{body:Y(``)}}},Z=n(async function(e,t,n,r){let i=n.getConfigField(`padding`),a=n.getConfigField(`iconSize`),o=a/2,s=a/6,c=s/2;await Promise.all(t.edges().map(async t=>{let{source:a,sourceDir:l,sourceArrow:u,sourceGroup:d,target:f,targetDir:p,targetArrow:h,targetGroup:g,label:v}=re(t),{x:y,y:b}=t[0].sourceEndpoint(),{x,y:S}=t[0].midpoint(),{x:C,y:w}=t[0].targetEndpoint(),E=i+4;if(d&&(F(l)?y+=l===`L`?-E:E:b+=l===`T`?-E:E+18),g&&(F(p)?C+=p===`L`?-E:E:w+=p===`T`?-E:E+18),!d&&n.getNode(a)?.type===`junction`&&(F(l)?y+=l===`L`?o:-o:b+=l===`T`?o:-o),!g&&n.getNode(f)?.type===`junction`&&(F(p)?C+=p===`L`?o:-o:w+=p===`T`?o:-o),t[0]._private.rscratch){let t=e.insert(`g`);if(t.insert(`path`).attr(`d`,`M ${y},${b} L ${x},${S} L${C},${w} `).attr(`class`,`edge`).attr(`id`,`${r}-${_(a,f,{prefix:`L`})}`),u){let e=F(l)?M[l](y,s):y-c,n=I(l)?M[l](b,s):b-c;t.insert(`polygon`).attr(`points`,j[l](s)).attr(`transform`,`translate(${e},${n})`).attr(`class`,`arrow`)}if(h){let e=F(p)?M[p](C,s):C-c,n=I(p)?M[p](w,s):w-c;t.insert(`polygon`).attr(`points`,j[p](s)).attr(`transform`,`translate(${e},${n})`).attr(`class`,`arrow`)}if(v){let e=L(l,p)?`XY`:F(l)?`X`:`Y`,n=0;n=e===`X`?Math.abs(y-C):e===`Y`?Math.abs(b-w)/1.5:Math.abs(y-C)/2;let r=t.append(`g`);if(await T(r,v,{useHtmlLabels:!1,width:n,classes:`architecture-service-label`},m()),r.attr(`dy`,`1em`).attr(`alignment-baseline`,`middle`).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`),e===`X`)r.attr(`transform`,`translate(`+x+`, `+S+`)`);else if(e===`Y`)r.attr(`transform`,`translate(`+x+`, `+S+`) rotate(-90)`);else if(e===`XY`){let e=B(l,p);if(e&&R(e)){let t=r.node().getBoundingClientRect(),[n,i]=ee(e);r.attr(`dominant-baseline`,`auto`).attr(`transform`,`rotate(${-1*n*i*45})`);let a=r.node().getBoundingClientRect();r.attr(`transform`,` + translate(${x}, ${S-t.height/2}) + translate(${n*a.width/2}, ${i*a.height/2}) + rotate(${-1*n*i*45}, 0, ${t.height/2}) + `)}}}}}))},`drawEdges`),ae=n(async function(e,t,n,r){let i=n.getConfigField(`padding`)*.75,a=n.getConfigField(`fontSize`),o=n.getConfigField(`iconSize`)/2;await Promise.all(t.nodes().map(async t=>{let s=U(t);if(s.type===`group`){let{h:c,w:l,x1:u,y1:d}=t.boundingBox(),f=e.append(`rect`);f.attr(`id`,`${r}-group-${s.id}`).attr(`x`,u+o).attr(`y`,d+o).attr(`width`,l).attr(`height`,c).attr(`class`,`node-bkg`);let p=e.append(`g`),h=u,g=d;if(s.icon){let e=p.append(`g`);e.html(`${await w(s.icon,{height:i,width:i,fallbackPrefix:X.prefix})}`),e.attr(`transform`,`translate(`+(h+o+1)+`, `+(g+o+1)+`)`),h+=i,g+=a/2-1-2}if(s.label){let e=p.append(`g`);await T(e,s.label,{useHtmlLabels:!1,width:l,classes:`architecture-service-label`},m()),e.attr(`dy`,`1em`).attr(`alignment-baseline`,`middle`).attr(`dominant-baseline`,`start`).attr(`text-anchor`,`start`),e.attr(`transform`,`translate(`+(h+o+4)+`, `+(g+o+2)+`)`)}n.setElementForId(s.id,f)}}))},`drawGroups`),Q=n(async function(e,t,n,r){let i=m();for(let a of n){let n=t.append(`g`),o=e.getConfigField(`iconSize`);if(a.title){let e=n.append(`g`);await T(e,a.title,{useHtmlLabels:!1,width:o*1.5,classes:`architecture-service-label`},i),e.attr(`dy`,`1em`).attr(`alignment-baseline`,`middle`).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`),e.attr(`transform`,`translate(`+o/2+`, `+o+`)`)}let s=n.append(`g`);if(a.icon)s.html(`${await w(a.icon,{height:o,width:o,fallbackPrefix:X.prefix})}`);else if(a.iconText){s.html(`${await w(`blank`,{height:o,width:o,fallbackPrefix:X.prefix})}`);let e=s.append(`g`).append(`foreignObject`).attr(`width`,o).attr(`height`,o).append(`div`).attr(`class`,`node-icon-text`).attr(`style`,`height: ${o}px;`).append(`div`).html(g(a.iconText,i)),t=parseInt(window.getComputedStyle(e.node(),null).getPropertyValue(`font-size`).replace(/\D/g,``))??16;e.attr(`style`,`-webkit-line-clamp: ${Math.floor((o-2)/t)};`)}else s.append(`path`).attr(`class`,`node-bkg`).attr(`id`,`${r}-node-${a.id}`).attr(`d`,`M0,${o} V5 Q0,0 5,0 H${o-5} Q${o},0 ${o},5 V${o} Z`);n.attr(`id`,`${r}-service-${a.id}`).attr(`class`,`architecture-service`);let{width:c,height:l}=n.node().getBBox();a.width=c,a.height=l,e.setElementForId(a.id,n)}return 0},`drawServices`),oe=n(function(e,t,n,r){n.forEach(n=>{let i=t.append(`g`),a=e.getConfigField(`iconSize`);i.append(`g`).append(`rect`).attr(`id`,`${r}-node-${n.id}`).attr(`fill-opacity`,`0`).attr(`width`,a).attr(`height`,a),i.attr(`class`,`architecture-junction`);let{width:o,height:s}=i._groups[0][0].getBBox();i.width=o,i.height=s,e.setElementForId(n.id,i)})},`drawJunctions`);C([{name:X.prefix,icons:X}]),E.use(k.default);function se(e,t,n){e.forEach(e=>{t.add({group:`nodes`,data:{type:`service`,id:e.id,icon:e.icon,label:e.title,parent:e.in,width:n.getConfigField(`iconSize`),height:n.getConfigField(`iconSize`)},classes:`node-service`})})}n(se,`addServices`);function ce(e,t,n){e.forEach(e=>{t.add({group:`nodes`,data:{type:`junction`,id:e.id,parent:e.in,width:n.getConfigField(`iconSize`),height:n.getConfigField(`iconSize`)},classes:`node-junction`})})}n(ce,`addJunctions`);function le(e,t){t.nodes().map(t=>{let n=U(t);n.type!==`group`&&(n.x=t.position().x,n.y=t.position().y,e.getElementById(n.id).attr(`transform`,`translate(`+(n.x||0)+`,`+(n.y||0)+`)`))})}n(le,`positionNodes`);function ue(e,t){e.forEach(e=>{t.add({group:`nodes`,data:{type:`group`,id:e.id,icon:e.icon,label:e.title,parent:e.in},classes:`node-group`})})}n(ue,`addGroups`);function de(e,t){e.forEach(e=>{let{lhsId:n,rhsId:r,lhsInto:i,lhsGroup:a,rhsInto:o,lhsDir:s,rhsDir:c,rhsGroup:l,title:u}=e,d=L(e.lhsDir,e.rhsDir)?`segments`:`straight`,f={id:`${n}-${r}`,label:u,source:n,sourceDir:s,sourceArrow:i,sourceGroup:a,sourceEndpoint:s===`L`?`0 50%`:s===`R`?`100% 50%`:s===`T`?`50% 0`:`50% 100%`,target:r,targetDir:c,targetArrow:o,targetGroup:l,targetEndpoint:c===`L`?`0 50%`:c===`R`?`100% 50%`:c===`T`?`50% 0`:`50% 100%`};t.add({group:`edges`,data:f,classes:d})})}n(de,`addEdges`);function fe(e,t,r,i=[]){let a=n((e,t)=>Object.entries(e).reduce((e,[n,i])=>{let a=0,o=Object.entries(i);if(o.length===1)return e[n]=o[0][1],e;for(let i=0;i{let n={},r={};return Object.entries(t).forEach(([t,[i,a]])=>{let o=e.getNode(t)?.in??`default`;n[a]??={},n[a][o]??=[],n[a][o].push(t),r[i]??={},r[i][o]??=[],r[i][o].push(t)}),{horiz:Object.values(a(n,`horizontal`)).filter(e=>e.length>1),vert:Object.values(a(r,`vertical`)).filter(e=>e.length>1)}}).reduce(([e,t],{horiz:n,vert:r})=>[[...e,...n],[...t,...r]],[[],[]]),c=new Set;i.forEach(e=>e.members.forEach(e=>c.add(e)));let l=n(e=>e.filter(e=>!e.some(e=>c.has(e))),`dropOverlapping`),u=l(o),d=l(s);return i.forEach(e=>{e.members.length<2||(e.direction===`row`?u.push([...e.members]):d.push([...e.members]))}),{horizontal:u,vertical:d}}n(fe,`getAlignments`);function pe(e,t,r=[]){let i=[],a=t.getConfigField(`iconSize`),o=t.getConfigField(`idealEdgeLengthMultiplier`),s=o*a,c=new Set;r.forEach(e=>{for(let t=0;t`${e[0]},${e[1]}`,`posToStr`),u=n(e=>e.split(`,`).map(e=>parseInt(e)),`strToPos`);return e.forEach(e=>{let t=Object.fromEntries(Object.entries(e).map(([e,t])=>[l(t),e])),n=[l([0,0])],r={},s={L:[-1,0],R:[1,0],T:[0,1],B:[0,-1]};for(;n.length>0;){let e=n.shift();if(e){r[e]=1;let d=t[e];if(d){let f=u(e);Object.entries(s).forEach(([e,s])=>{let u=l([f[0]+s[0],f[1]+s[1]]),p=t[u];if(p&&!r[u]){if(n.push(u),c.has(`${d}|${p}`))return;i.push({[A[e]]:p,[A[N(e)]]:d,gap:o*a})}})}}}}),i}n(pe,`getRelativeConstraints`);function me(e,t,a,o,s,{spatialMaps:c,groupAlignments:l}){return new Promise(u=>{let d=i(`body`).append(`div`).attr(`id`,`cy`).attr(`style`,`display:none`),f=E({container:document.getElementById(`cy`),style:[{selector:`edge`,style:{"curve-style":`straight`,"source-endpoint":`data(sourceEndpoint)`,"target-endpoint":`data(targetEndpoint)`}},{selector:`edge[label]`,style:{label:`data(label)`}},{selector:`edge.segments`,style:{"curve-style":`segments`,"segment-weights":`0`,"segment-distances":[.5],"edge-distances":`endpoints`,"source-endpoint":`data(sourceEndpoint)`,"target-endpoint":`data(targetEndpoint)`}},{selector:`node`,style:{"compound-sizing-wrt-labels":`include`}},{selector:`node[label]`,style:{"text-valign":`bottom`,"text-halign":`center`,"font-size":`${s.getConfigField(`fontSize`)}px`}},{selector:`.node-service`,style:{label:`data(label)`,width:`data(width)`,height:`data(height)`}},{selector:`.node-junction`,style:{width:`data(width)`,height:`data(height)`}},{selector:`.node-group`,style:{padding:`${s.getConfigField(`padding`)}px`}}],layout:{name:`grid`,boundingBox:{x1:0,x2:100,y1:0,y2:100}}});d.remove(),ue(a,f),se(e,f,s),ce(t,f,s),de(o,f);let p=s.getLayoutHints(),m=fe(s,c,l,p),h=pe(c,s,p),g=s.getConfigField(`iconSize`),_=s.getConfigField(`idealEdgeLengthMultiplier`)*g,v=.5*g,y=s.getConfigField(`edgeElasticity`),b=s.getConfigField(`seed`),x=f.layout({name:`fcose`,quality:`proof`,randomize:s.getConfigField(`randomize`),nodeSeparation:s.getConfigField(`nodeSeparation`),numIter:s.getConfigField(`numIter`),styleEnabled:!1,animate:!1,nodeDimensionsIncludeLabels:!1,idealEdgeLength(e){let[t,n]=e.connectedNodes(),{parent:r}=U(t),{parent:i}=U(n);return r===i?_:v},edgeElasticity(e){let[t,n]=e.connectedNodes(),{parent:r}=U(t),{parent:i}=U(n);return r===i?y:.001},alignmentConstraint:m,relativePlacementConstraint:h});x.one(`layoutstop`,()=>{function e(e,t,n,r){let i,a,{x:o,y:s}=e,{x:c,y:l}=t;a=(r-s+(o-n)*(s-l)/(o-c))/Math.sqrt(1+((s-l)/(o-c))**2),i=Math.sqrt((r-s)**2+(n-o)**2-a**2);let u=Math.sqrt((c-o)**2+(l-s)**2);i/=u;let d=(c-o)*(r-s)-(l-s)*(n-o);switch(!0){case d>=0:d=1;break;case d<0:d=-1;break}let f=(c-o)*(n-o)+(l-s)*(r-s);switch(!0){case f>=0:f=1;break;case f<0:f=-1;break}return a=Math.abs(a)*d,i*=f,{distances:a,weights:i}}n(e,`getSegmentWeights`),f.startBatch();for(let t of Object.values(f.edges()))if(t.data?.()){let{x:n,y:r}=t.source().position(),{x:i,y:a}=t.target().position();if(n!==i&&r!==a){let n=t.sourceEndpoint(),r=t.targetEndpoint(),{sourceDir:i}=re(t),[a,o]=I(i)?[n.x,r.y]:[r.x,n.y],{weights:s,distances:c}=e(n,r,a,o);t.style(`segment-distances`,c),t.style(`segment-weights`,s)}}f.endBatch(),J(b,()=>x.run())});try{J(b,()=>x.run())}catch(e){throw e instanceof RangeError&&e.message.includes(`Invalid array length`)?Error("Architecture layout failed: a declared `align row|column` directive likely contradicts the edge directions, or two declared alignments overlap on a shared node. Check that the order of members in each `align` chain is consistent with the edges between them, and that no node appears in two `align` directives along the same axis."):e}f.ready(e=>{r.info(`Ready`,e),u(f)})})}n(me,`layoutArchitecture`);var he={parser:K,get db(){return new G},renderer:{draw:n(async(e,t,n,r)=>{let i=r.db;i.setDiagramId(t);let a=i.getServices(),s=i.getJunctions(),c=i.getGroups(),l=i.getEdges(),u=i.getDataStructures(),d=y(t),f=d.append(`g`);f.attr(`class`,`architecture-edges`);let p=d.append(`g`);p.attr(`class`,`architecture-services`);let m=d.append(`g`);m.attr(`class`,`architecture-groups`),await Q(i,p,a,t),oe(i,p,s,t);let h=await me(a,s,c,l,i,u);await Z(f,h,i,t),await ae(m,h,i,t),le(i,h),o(void 0,d,i.getConfigField(`padding`),i.getConfigField(`useMaxWidth`))},`draw`)},styles:q};export{he as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/array-BifhSqXX.js b/dist-desktop/assets/array-BifhSqXX.js new file mode 100644 index 0000000..b0a084a --- /dev/null +++ b/dist-desktop/assets/array-BifhSqXX.js @@ -0,0 +1 @@ +Array.prototype.slice;function e(e){return typeof e==`object`&&`length`in e?e:Array.from(e)}export{e as t}; \ No newline at end of file diff --git a/dist-desktop/assets/blockDiagram-677ZJIJ3-Dn3HALPW.js b/dist-desktop/assets/blockDiagram-677ZJIJ3-Dn3HALPW.js new file mode 100644 index 0000000..537ca0a --- /dev/null +++ b/dist-desktop/assets/blockDiagram-677ZJIJ3-Dn3HALPW.js @@ -0,0 +1,132 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{O as r,T as i,a,b as o,c as s,it as c,s as l,x as u,z as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as f}from"./channel-C4fgBBJ4.js";import{A as p,B as m,C as h,D as g,E as _,F as v,G as y,H as b,I as x,L as S,M as C,N as w,O as T,P as E,R as D,T as O,U as k,V as A,W as j,a as M,b as ee,et as te,g as N,j as ne,k as re,l as ie,v as ae,w as oe,z as se}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as ce}from"./line-b9Ala942.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import{n as P}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{t as le}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{n as ue,t as F}from"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as de,t as fe}from"./chunk-OGEWGWER-D-nWYRNR.js";import{t as pe}from"./graphlib-DS17s2tU.js";function me(e){return Array.isArray(e)}function he(e){if(ee(e))return e;let t=y(e);if(!ge(e))return{};if(me(e)){let t=Array.from(e);return e.length>0&&typeof e[0]==`string`&&Object.hasOwn(e,`index`)&&(t.index=e.index,t.input=e.input),t}if(ae(e)){let t=e,n=t.constructor;return new n(t.buffer,t.byteOffset,t.length)}if(t===`[object ArrayBuffer]`)return new ArrayBuffer(e.byteLength);if(t===`[object DataView]`){let t=e,n=t.buffer,r=t.byteOffset,i=t.byteLength,a=new ArrayBuffer(i),o=new Uint8Array(n,r,i);return new Uint8Array(a).set(o),new DataView(a)}if(t===`[object Boolean]`||t===`[object Number]`||t===`[object String]`){let n=e.constructor,r=new n(e.valueOf());return t===`[object String]`?ye(r,e):_e(r,e),r}if(t===`[object Date]`)return new Date(Number(e));if(t===`[object RegExp]`){let t=e,n=new RegExp(t.source,t.flags);return n.lastIndex=t.lastIndex,n}if(t===`[object Symbol]`)return Object(Symbol.prototype.valueOf.call(e));if(t===`[object Map]`){let t=e,n=new Map;return t.forEach((e,t)=>{n.set(t,e)}),n}if(t===`[object Set]`){let t=e,n=new Set;return t.forEach(e=>{n.add(e)}),n}if(t===`[object Arguments]`){let t=e,n={};return _e(n,t),n.length=t.length,n[Symbol.iterator]=t[Symbol.iterator],n}let n={};return be(n,e),_e(n,e),ve(n,e),n}function ge(e){switch(y(e)){case h:case O:case oe:case g:case _:case T:case re:case p:case w:case ne:case C:case E:case v:case x:case S:case D:case se:case m:case k:case j:case A:case b:return!0;default:return!1}}function _e(e,t){for(let n in t)Object.hasOwn(t,n)&&(e[n]=t[n])}function ve(e,t){let n=Object.getOwnPropertySymbols(t);for(let r=0;r=n)&&(e[r]=t[r])}function be(e,t){let n=Object.getPrototypeOf(t);n!==null&&typeof t.constructor==`function`&&Object.setPrototypeOf(e,n)}var xe=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,15],r=[1,7],i=[1,13],a=[1,14],o=[1,19],s=[1,16],c=[1,17],l=[1,18],u=[8,30],d=[8,10,21,28,29,30,31,39,43,46],f=[1,23],p=[1,24],m=[8,10,15,16,21,28,29,30,31,39,43,46],h=[8,10,15,16,21,27,28,29,30,31,39,43,46],g=[1,49],_={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,spaceLines:3,SPACELINE:4,NL:5,separator:6,SPACE:7,EOF:8,start:9,BLOCK_DIAGRAM_KEY:10,document:11,stop:12,statement:13,link:14,LINK:15,START_LINK:16,LINK_LABEL:17,STR:18,nodeStatement:19,columnsStatement:20,SPACE_BLOCK:21,blockStatement:22,classDefStatement:23,cssClassStatement:24,styleStatement:25,node:26,SIZE:27,COLUMNS:28,"id-block":29,end:30,NODE_ID:31,nodeShapeNLabel:32,dirList:33,DIR:34,NODE_DSTART:35,NODE_DEND:36,BLOCK_ARROW_START:37,BLOCK_ARROW_END:38,classDef:39,CLASSDEF_ID:40,CLASSDEF_STYLEOPTS:41,DEFAULT:42,class:43,CLASSENTITY_IDS:44,STYLECLASS:45,style:46,STYLE_ENTITY_IDS:47,STYLE_DEFINITION_DATA:48,$accept:0,$end:1},terminals_:{2:`error`,4:`SPACELINE`,5:`NL`,7:`SPACE`,8:`EOF`,10:`BLOCK_DIAGRAM_KEY`,15:`LINK`,16:`START_LINK`,17:`LINK_LABEL`,18:`STR`,21:`SPACE_BLOCK`,27:`SIZE`,28:`COLUMNS`,29:`id-block`,30:`end`,31:`NODE_ID`,34:`DIR`,35:`NODE_DSTART`,36:`NODE_DEND`,37:`BLOCK_ARROW_START`,38:`BLOCK_ARROW_END`,39:`classDef`,40:`CLASSDEF_ID`,41:`CLASSDEF_STYLEOPTS`,42:`DEFAULT`,43:`class`,44:`CLASSENTITY_IDS`,45:`STYLECLASS`,46:`style`,47:`STYLE_ENTITY_IDS`,48:`STYLE_DEFINITION_DATA`},productions_:[0,[3,1],[3,2],[3,2],[6,1],[6,1],[6,1],[9,3],[12,1],[12,1],[12,2],[12,2],[11,1],[11,2],[14,1],[14,4],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[19,3],[19,2],[19,1],[20,1],[22,4],[22,3],[26,1],[26,2],[33,1],[33,2],[32,3],[32,4],[23,3],[23,3],[24,3],[25,3]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 4:r.getLogger().debug(`Rule: separator (NL) `);break;case 5:r.getLogger().debug(`Rule: separator (Space) `);break;case 6:r.getLogger().debug(`Rule: separator (EOF) `);break;case 7:r.getLogger().debug(`Rule: hierarchy: `,a[s-1]),r.setHierarchy(a[s-1]);break;case 8:r.getLogger().debug(`Stop NL `);break;case 9:r.getLogger().debug(`Stop EOF `);break;case 10:r.getLogger().debug(`Stop NL2 `);break;case 11:r.getLogger().debug(`Stop EOF2 `);break;case 12:r.getLogger().debug(`Rule: statement: `,a[s]),typeof a[s].length==`number`?this.$=a[s]:this.$=[a[s]];break;case 13:r.getLogger().debug(`Rule: statement #2: `,a[s-1]),this.$=[a[s-1]].concat(a[s]);break;case 14:r.getLogger().debug(`Rule: link: `,a[s],e),this.$={edgeTypeStr:a[s],label:``};break;case 15:r.getLogger().debug(`Rule: LABEL link: `,a[s-3],a[s-1],a[s]),this.$={edgeTypeStr:a[s],label:a[s-1]};break;case 18:let t=parseInt(a[s]),n=r.generateId();this.$={id:n,type:`space`,label:``,width:t,children:[]};break;case 23:r.getLogger().debug(`Rule: (nodeStatement link node) `,a[s-2],a[s-1],a[s],` typestr: `,a[s-1].edgeTypeStr);let i=r.edgeStrToEdgeData(a[s-1].edgeTypeStr),o=r.edgeStrToEdgeStartData(a[s-1].edgeTypeStr),c=r.edgeStrToThickness(a[s-1].edgeTypeStr),l=r.edgeStrToPattern(a[s-1].edgeTypeStr);this.$=[{id:a[s-2].id,label:a[s-2].label,type:a[s-2].type,directions:a[s-2].directions},{id:a[s-2].id+`-`+a[s].id,start:a[s-2].id,end:a[s].id,label:a[s-1].label,type:`edge`,thickness:c,pattern:l,directions:a[s].directions,arrowTypeEnd:i,arrowTypeStart:o},{id:a[s].id,label:a[s].label,type:r.typeStr2Type(a[s].typeStr),directions:a[s].directions}];break;case 24:r.getLogger().debug(`Rule: nodeStatement (abc88 node size) `,a[s-1],a[s]),this.$={id:a[s-1].id,label:a[s-1].label,type:r.typeStr2Type(a[s-1].typeStr),directions:a[s-1].directions,widthInColumns:parseInt(a[s],10)};break;case 25:r.getLogger().debug(`Rule: nodeStatement (node) `,a[s]),this.$={id:a[s].id,label:a[s].label,type:r.typeStr2Type(a[s].typeStr),directions:a[s].directions,widthInColumns:1};break;case 26:r.getLogger().debug(`APA123`,this?this:`na`),r.getLogger().debug(`COLUMNS: `,a[s]),this.$={type:`column-setting`,columns:a[s]===`auto`?-1:parseInt(a[s])};break;case 27:r.getLogger().debug(`Rule: id-block statement : `,a[s-2],a[s-1]),r.generateId(),this.$={...a[s-2],type:`composite`,children:a[s-1]};break;case 28:r.getLogger().debug(`Rule: blockStatement : `,a[s-2],a[s-1],a[s]);let u=r.generateId();this.$={id:u,type:`composite`,label:``,children:a[s-1]};break;case 29:r.getLogger().debug(`Rule: node (NODE_ID separator): `,a[s]),this.$={id:a[s]};break;case 30:r.getLogger().debug(`Rule: node (NODE_ID nodeShapeNLabel separator): `,a[s-1],a[s]),this.$={id:a[s-1],label:a[s].label,typeStr:a[s].typeStr,directions:a[s].directions};break;case 31:r.getLogger().debug(`Rule: dirList: `,a[s]),this.$=[a[s]];break;case 32:r.getLogger().debug(`Rule: dirList: `,a[s-1],a[s]),this.$=[a[s-1]].concat(a[s]);break;case 33:r.getLogger().debug(`Rule: nodeShapeNLabel: `,a[s-2],a[s-1],a[s]),this.$={typeStr:a[s-2]+a[s],label:a[s-1]};break;case 34:r.getLogger().debug(`Rule: BLOCK_ARROW nodeShapeNLabel: `,a[s-3],a[s-2],` #3:`,a[s-1],a[s]),this.$={typeStr:a[s-3]+a[s],label:a[s-2],directions:a[s-1]};break;case 35:case 36:this.$={type:`classDef`,id:a[s-1].trim(),css:a[s].trim()};break;case 37:this.$={type:`applyClass`,id:a[s-1].trim(),styleClass:a[s].trim()};break;case 38:this.$={type:`applyStyles`,id:a[s-1].trim(),stylesStr:a[s].trim()};break}},`anonymous`),table:[{9:1,10:[1,2]},{1:[3]},{10:n,11:3,13:4,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:a,31:o,39:s,43:c,46:l},{8:[1,20]},t(u,[2,12],{13:4,19:5,20:6,22:8,23:9,24:10,25:11,26:12,11:21,10:n,21:r,28:i,29:a,31:o,39:s,43:c,46:l}),t(d,[2,16],{14:22,15:f,16:p}),t(d,[2,17]),t(d,[2,18]),t(d,[2,19]),t(d,[2,20]),t(d,[2,21]),t(d,[2,22]),t(m,[2,25],{27:[1,25]}),t(d,[2,26]),{19:26,26:12,31:o},{10:n,11:27,13:4,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:a,31:o,39:s,43:c,46:l},{40:[1,28],42:[1,29]},{44:[1,30]},{47:[1,31]},t(h,[2,29],{32:32,35:[1,33],37:[1,34]}),{1:[2,7]},t(u,[2,13]),{26:35,31:o},{31:[2,14]},{17:[1,36]},t(m,[2,24]),{10:n,11:37,13:4,14:22,15:f,16:p,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:a,31:o,39:s,43:c,46:l},{30:[1,38]},{41:[1,39]},{41:[1,40]},{45:[1,41]},{48:[1,42]},t(h,[2,30]),{18:[1,43]},{18:[1,44]},t(m,[2,23]),{18:[1,45]},{30:[1,46]},t(d,[2,28]),t(d,[2,35]),t(d,[2,36]),t(d,[2,37]),t(d,[2,38]),{36:[1,47]},{33:48,34:g},{15:[1,50]},t(d,[2,27]),t(h,[2,33]),{38:[1,51]},{33:52,34:g,38:[2,31]},{31:[2,15]},t(h,[2,34]),{38:[2,32]}],defaultActions:{20:[2,7],23:[2,14],50:[2,15],52:[2,32]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};_.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{},performAction:e(function(e,t,n,r){switch(n){case 0:return e.getLogger().debug(`Found block-beta`),10;case 1:return e.getLogger().debug(`Found id-block`),29;case 2:return e.getLogger().debug(`Found block`),10;case 3:e.getLogger().debug(`.`,t.yytext);break;case 4:e.getLogger().debug(`_`,t.yytext);break;case 5:return 5;case 6:return t.yytext=-1,28;case 7:return t.yytext=t.yytext.replace(/columns\s+/,``),e.getLogger().debug(`COLUMNS (LEX)`,t.yytext),28;case 8:this.pushState(`md_string`);break;case 9:return`MD_STR`;case 10:this.popState();break;case 11:this.pushState(`string`);break;case 12:e.getLogger().debug(`LEX: POPPING STR:`,t.yytext),this.popState();break;case 13:return e.getLogger().debug(`LEX: STR end:`,t.yytext),`STR`;case 14:return t.yytext=t.yytext.replace(/space\:/,``),e.getLogger().debug(`SPACE NUM (LEX)`,t.yytext),21;case 15:return t.yytext=`1`,e.getLogger().debug(`COLUMNS (LEX)`,t.yytext),21;case 16:return 42;case 17:return`LINKSTYLE`;case 18:return`INTERPOLATE`;case 19:return this.pushState(`CLASSDEF`),39;case 20:return this.popState(),this.pushState(`CLASSDEFID`),`DEFAULT_CLASSDEF_ID`;case 21:return this.popState(),this.pushState(`CLASSDEFID`),40;case 22:return this.popState(),41;case 23:return this.pushState(`CLASS`),43;case 24:return this.popState(),this.pushState(`CLASS_STYLE`),44;case 25:return this.popState(),45;case 26:return this.pushState(`STYLE_STMNT`),46;case 27:return this.popState(),this.pushState(`STYLE_DEFINITION`),47;case 28:return this.popState(),48;case 29:return this.pushState(`acc_title`),`acc_title`;case 30:return this.popState(),`acc_title_value`;case 31:return this.pushState(`acc_descr`),`acc_descr`;case 32:return this.popState(),`acc_descr_value`;case 33:this.pushState(`acc_descr_multiline`);break;case 34:this.popState();break;case 35:return`acc_descr_multiline_value`;case 36:return 30;case 37:return this.popState(),e.getLogger().debug(`Lex: ((`),`NODE_DEND`;case 38:return this.popState(),e.getLogger().debug(`Lex: ((`),`NODE_DEND`;case 39:return this.popState(),e.getLogger().debug(`Lex: ))`),`NODE_DEND`;case 40:return this.popState(),e.getLogger().debug(`Lex: ((`),`NODE_DEND`;case 41:return this.popState(),e.getLogger().debug(`Lex: ((`),`NODE_DEND`;case 42:return this.popState(),e.getLogger().debug(`Lex: (-`),`NODE_DEND`;case 43:return this.popState(),e.getLogger().debug(`Lex: -)`),`NODE_DEND`;case 44:return this.popState(),e.getLogger().debug(`Lex: ((`),`NODE_DEND`;case 45:return this.popState(),e.getLogger().debug(`Lex: ]]`),`NODE_DEND`;case 46:return this.popState(),e.getLogger().debug(`Lex: (`),`NODE_DEND`;case 47:return this.popState(),e.getLogger().debug(`Lex: ])`),`NODE_DEND`;case 48:return this.popState(),e.getLogger().debug(`Lex: /]`),`NODE_DEND`;case 49:return this.popState(),e.getLogger().debug(`Lex: /]`),`NODE_DEND`;case 50:return this.popState(),e.getLogger().debug(`Lex: )]`),`NODE_DEND`;case 51:return this.popState(),e.getLogger().debug(`Lex: )`),`NODE_DEND`;case 52:return this.popState(),e.getLogger().debug(`Lex: ]>`),`NODE_DEND`;case 53:return this.popState(),e.getLogger().debug(`Lex: ]`),`NODE_DEND`;case 54:return e.getLogger().debug(`Lexa: -)`),this.pushState(`NODE`),35;case 55:return e.getLogger().debug(`Lexa: (-`),this.pushState(`NODE`),35;case 56:return e.getLogger().debug(`Lexa: ))`),this.pushState(`NODE`),35;case 57:return e.getLogger().debug(`Lexa: )`),this.pushState(`NODE`),35;case 58:return e.getLogger().debug(`Lex: (((`),this.pushState(`NODE`),35;case 59:return e.getLogger().debug(`Lexa: )`),this.pushState(`NODE`),35;case 60:return e.getLogger().debug(`Lexa: )`),this.pushState(`NODE`),35;case 61:return e.getLogger().debug(`Lexa: )`),this.pushState(`NODE`),35;case 62:return e.getLogger().debug(`Lexc: >`),this.pushState(`NODE`),35;case 63:return e.getLogger().debug(`Lexa: ([`),this.pushState(`NODE`),35;case 64:return e.getLogger().debug(`Lexa: )`),this.pushState(`NODE`),35;case 65:return this.pushState(`NODE`),35;case 66:return this.pushState(`NODE`),35;case 67:return this.pushState(`NODE`),35;case 68:return this.pushState(`NODE`),35;case 69:return this.pushState(`NODE`),35;case 70:return this.pushState(`NODE`),35;case 71:return this.pushState(`NODE`),35;case 72:return e.getLogger().debug(`Lexa: [`),this.pushState(`NODE`),35;case 73:return this.pushState(`BLOCK_ARROW`),e.getLogger().debug(`LEX ARR START`),37;case 74:return e.getLogger().debug(`Lex: NODE_ID`,t.yytext),31;case 75:return e.getLogger().debug(`Lex: EOF`,t.yytext),8;case 76:this.pushState(`md_string`);break;case 77:this.pushState(`md_string`);break;case 78:return`NODE_DESCR`;case 79:this.popState();break;case 80:e.getLogger().debug(`Lex: Starting string`),this.pushState(`string`);break;case 81:e.getLogger().debug(`LEX ARR: Starting string`),this.pushState(`string`);break;case 82:return e.getLogger().debug(`LEX: NODE_DESCR:`,t.yytext),`NODE_DESCR`;case 83:e.getLogger().debug(`LEX POPPING`),this.popState();break;case 84:e.getLogger().debug(`Lex: =>BAE`),this.pushState(`ARROW_DIR`);break;case 85:return t.yytext=t.yytext.replace(/^,\s*/,``),e.getLogger().debug(`Lex (right): dir:`,t.yytext),`DIR`;case 86:return t.yytext=t.yytext.replace(/^,\s*/,``),e.getLogger().debug(`Lex (left):`,t.yytext),`DIR`;case 87:return t.yytext=t.yytext.replace(/^,\s*/,``),e.getLogger().debug(`Lex (x):`,t.yytext),`DIR`;case 88:return t.yytext=t.yytext.replace(/^,\s*/,``),e.getLogger().debug(`Lex (y):`,t.yytext),`DIR`;case 89:return t.yytext=t.yytext.replace(/^,\s*/,``),e.getLogger().debug(`Lex (up):`,t.yytext),`DIR`;case 90:return t.yytext=t.yytext.replace(/^,\s*/,``),e.getLogger().debug(`Lex (down):`,t.yytext),`DIR`;case 91:return t.yytext=`]>`,e.getLogger().debug(`Lex (ARROW_DIR end):`,t.yytext),this.popState(),this.popState(),`BLOCK_ARROW_END`;case 92:return e.getLogger().debug(`Lex: LINK`,`#`+t.yytext+`#`),15;case 93:return e.getLogger().debug(`Lex: LINK`,t.yytext),15;case 94:return e.getLogger().debug(`Lex: LINK`,t.yytext),15;case 95:return e.getLogger().debug(`Lex: LINK`,t.yytext),15;case 96:return e.getLogger().debug(`Lex: START_LINK`,t.yytext),this.pushState(`LLABEL`),16;case 97:return e.getLogger().debug(`Lex: START_LINK`,t.yytext),this.pushState(`LLABEL`),16;case 98:return e.getLogger().debug(`Lex: START_LINK`,t.yytext),this.pushState(`LLABEL`),16;case 99:this.pushState(`md_string`);break;case 100:return e.getLogger().debug(`Lex: Starting string`),this.pushState(`string`),`LINK_LABEL`;case 101:return this.popState(),e.getLogger().debug(`Lex: LINK`,`#`+t.yytext+`#`),15;case 102:return this.popState(),e.getLogger().debug(`Lex: LINK`,t.yytext),15;case 103:return this.popState(),e.getLogger().debug(`Lex: LINK`,t.yytext),15;case 104:return e.getLogger().debug(`Lex: COLON`,t.yytext),t.yytext=t.yytext.slice(1),27}},`anonymous`),rules:[/^(?:block-beta\b)/,/^(?:block:)/,/^(?:block\b)/,/^(?:[\s]+)/,/^(?:[\n]+)/,/^(?:((\u000D\u000A)|(\u000A)))/,/^(?:columns\s+auto\b)/,/^(?:columns\s+[\d]+)/,/^(?:["][`])/,/^(?:[^`"]+)/,/^(?:[`]["])/,/^(?:["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:space[:]\d+)/,/^(?:space\b)/,/^(?:default\b)/,/^(?:linkStyle\b)/,/^(?:interpolate\b)/,/^(?:classDef\s+)/,/^(?:DEFAULT\s+)/,/^(?:\w+\s+)/,/^(?:[^\n]*)/,/^(?:class\s+)/,/^(?:(\w+)+((,\s*\w+)*))/,/^(?:[^\n]*)/,/^(?:style\s+)/,/^(?:(\w+)+((,\s*\w+)*))/,/^(?:[^\n]*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:end\b\s*)/,/^(?:\(\(\()/,/^(?:\)\)\))/,/^(?:[\)]\))/,/^(?:\}\})/,/^(?:\})/,/^(?:\(-)/,/^(?:-\))/,/^(?:\(\()/,/^(?:\]\])/,/^(?:\()/,/^(?:\]\))/,/^(?:\\\])/,/^(?:\/\])/,/^(?:\)\])/,/^(?:[\)])/,/^(?:\]>)/,/^(?:[\]])/,/^(?:-\))/,/^(?:\(-)/,/^(?:\)\))/,/^(?:\))/,/^(?:\(\(\()/,/^(?:\(\()/,/^(?:\{\{)/,/^(?:\{)/,/^(?:>)/,/^(?:\(\[)/,/^(?:\()/,/^(?:\[\[)/,/^(?:\[\|)/,/^(?:\[\()/,/^(?:\)\)\))/,/^(?:\[\\)/,/^(?:\[\/)/,/^(?:\[\\)/,/^(?:\[)/,/^(?:<\[)/,/^(?:[^\(\[\n\-\)\{\}\s\<\>:=]+)/,/^(?:$)/,/^(?:["][`])/,/^(?:["][`])/,/^(?:[^`"]+)/,/^(?:[`]["])/,/^(?:["])/,/^(?:["])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:\]>\s*\()/,/^(?:,?\s*right\s*)/,/^(?:,?\s*left\s*)/,/^(?:,?\s*x\s*)/,/^(?:,?\s*y\s*)/,/^(?:,?\s*up\s*)/,/^(?:,?\s*down\s*)/,/^(?:\)\s*)/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?:\s*~~[\~]+\s*)/,/^(?:\s*[xo<]?--\s*)/,/^(?:\s*[xo<]?==\s*)/,/^(?:\s*[xo<]?-\.\s*)/,/^(?:["][`])/,/^(?:["])/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?::\d+)/],conditions:{STYLE_DEFINITION:{rules:[28],inclusive:!1},STYLE_STMNT:{rules:[27],inclusive:!1},CLASSDEFID:{rules:[22],inclusive:!1},CLASSDEF:{rules:[20,21],inclusive:!1},CLASS_STYLE:{rules:[25],inclusive:!1},CLASS:{rules:[24],inclusive:!1},LLABEL:{rules:[99,100,101,102,103],inclusive:!1},ARROW_DIR:{rules:[85,86,87,88,89,90,91],inclusive:!1},BLOCK_ARROW:{rules:[76,81,84],inclusive:!1},NODE:{rules:[37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,77,80],inclusive:!1},md_string:{rules:[9,10,78,79],inclusive:!1},space:{rules:[],inclusive:!1},string:{rules:[12,13,82,83],inclusive:!1},acc_descr_multiline:{rules:[34,35],inclusive:!1},acc_descr:{rules:[32],inclusive:!1},acc_title:{rules:[30],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8,11,14,15,16,17,18,19,23,26,29,31,33,36,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,92,93,94,95,96,97,98,104],inclusive:!0}}}})();function v(){this.yy={}}return e(v,`Parser`),v.prototype=_,_.Parser=v,new v})();xe.parser=xe;var Se=xe,I=new Map,Ce=[],we=new Map,Te=`color`,Ee=`fill`,De=`bgFill`,Oe=`,`,L=new Map,ke=``,Ae=e(e=>l.sanitizeText(e,u()),`sanitizeText`),je=e(function(e,t=``){let n=L.get(e);n||(n={id:e,styles:[],textStyles:[]},L.set(e,n)),t?.split(Oe).forEach(e=>{let t=e.replace(/([^;]*);/,`$1`).trim();if(RegExp(Te).exec(e)){let e=t.replace(Ee,De).replace(Te,Ee);n.textStyles.push(e)}n.styles.push(t)})},`addStyleClass`),Me=e(function(e,t=``){let n=I.get(e);t!=null&&(n.styles=t.split(Oe))},`addStyle2Node`),Ne=e(function(e,t){e.split(`,`).forEach(function(e){let n=I.get(e);if(n===void 0){let t=e.trim();n={id:t,type:`na`,children:[]},I.set(t,n)}n.classes||=[],n.classes.push(t)})},`setCssClass`),Pe=e((e,n)=>{let r=e.flat(),i=[],a=r.find(e=>e?.type===`column-setting`)?.columns??-1;for(let e of r){if(typeof a==`number`&&a>0&&e.type!==`column-setting`&&typeof e.widthInColumns==`number`&&e.widthInColumns>a&&t.warn(`Block ${e.id} width ${e.widthInColumns} exceeds configured column width ${a}`),e.label&&=Ae(e.label),e.type===`classDef`){je(e.id,e.css);continue}if(e.type===`applyClass`){Ne(e.id,e?.styleClass??``);continue}if(e.type===`applyStyles`){e?.stylesStr&&Me(e.id,e?.stylesStr);continue}if(e.type===`column-setting`)n.columns=e.columns??-1;else if(e.type===`edge`){let t=(we.get(e.id)??0)+1;we.set(e.id,t),e.id=t+`-`+e.id,Ce.push(e)}else{e.label||(e.type===`composite`?e.label=``:e.label=e.id);let t=I.get(e.id);if(t===void 0?I.set(e.id,e):(e.type!==`na`&&(t.type=e.type),e.label!==e.id&&(t.label=e.label)),e.children&&Pe(e.children,e),e.type===`space`){let t=e.width??1;for(let n=0;n{t.debug(`Clear called`),a(),R={id:`root`,type:`composite`,children:[],columns:-1},I=new Map([[`root`,R]]),Fe=[],L=new Map,Ce=[],we=new Map,ke=``},`clear`);function Le(e){switch(t.debug(`typeStr2Type`,e),e){case`[]`:return`square`;case`()`:return t.debug(`we have a round`),`round`;case`(())`:return`circle`;case`>]`:return`rect_left_inv_arrow`;case`{}`:return`diamond`;case`{{}}`:return`hexagon`;case`([])`:return`stadium`;case`[[]]`:return`subroutine`;case`[()]`:return`cylinder`;case`((()))`:return`doublecircle`;case`[//]`:return`lean_right`;case`[\\\\]`:return`lean_left`;case`[/\\]`:return`trapezoid`;case`[\\/]`:return`inv_trapezoid`;case`<[]>`:return`block_arrow`;default:return`na`}}e(Le,`typeStr2Type`);function Re(e){switch(t.debug(`typeStr2Type`,e),e){case`==`:return`thick`;default:return`normal`}}e(Re,`edgeTypeStr2Type`);function ze(e){switch(e.trim().slice(-1)){case`x`:return`arrow_cross`;case`o`:return`arrow_circle`;case`>`:return`arrow_point`;default:return``}}e(ze,`edgeStrToEdgeData`);function Be(e){switch(e.trim().charAt(0)){case`x`:return`arrow_cross`;case`o`:return`arrow_circle`;case`<`:return`arrow_point`;default:return`arrow_open`}}e(Be,`edgeStrToEdgeStartData`);function Ve(e){return e.includes(`==`)?`thick`:`normal`}e(Ve,`edgeStrToThickness`);function He(e){return e.includes(`.-`)?`dotted`:`solid`}e(He,`edgeStrToPattern`);var Ue=0,We={getConfig:e(()=>o().block,`getConfig`),typeStr2Type:Le,edgeTypeStr2Type:Re,edgeStrToEdgeData:ze,edgeStrToEdgeStartData:Be,edgeStrToThickness:Ve,edgeStrToPattern:He,getLogger:e(()=>t,`getLogger`),getBlocksFlat:e(()=>[...I.values()],`getBlocksFlat`),getBlocks:e(()=>Fe||[],`getBlocks`),getEdges:e(()=>Ce,`getEdges`),setHierarchy:e(e=>{R.children=e,Pe(e,R),Fe=R.children},`setHierarchy`),getBlock:e(e=>I.get(e),`getBlock`),setBlock:e(e=>{I.set(e.id,e)},`setBlock`),getColumns:e(e=>{let t=I.get(e);return t?t.columns?t.columns:t.children?t.children.length:-1:-1},`getColumns`),getClasses:e(function(){return L},`getClasses`),clear:Ie,generateId:e(()=>(Ue++,`id-`+Math.random().toString(36).substr(2,12)+`-`+Ue),`generateId`),setDiagramId:e(e=>{ke=e},`setDiagramId`),getDiagramId:e(()=>ke,`getDiagramId`)},z=e((e,t)=>{let n=f;return c(n(e,`r`),n(e,`g`),n(e,`b`),t)},`fade`),Ge=e(e=>`.label { + font-family: ${e.fontFamily}; + color: ${e.nodeTextColor||e.textColor}; + } + .cluster-label text { + fill: ${e.titleColor}; + } + .cluster-label span,p { + color: ${e.titleColor}; + } + + + + .label text,span,p { + fill: ${e.nodeTextColor||e.textColor}; + color: ${e.nodeTextColor||e.textColor}; + } + + .node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; + stroke-width: 1px; + } + .flowchart-label text { + text-anchor: middle; + } + // .flowchart-label .text-outer-tspan { + // text-anchor: middle; + // } + // .flowchart-label .text-inner-tspan { + // text-anchor: start; + // } + + .node .label { + text-align: center; + } + .node.clickable { + cursor: pointer; + } + + .arrowheadPath { + fill: ${e.arrowheadColor}; + } + + .edgePath .path { + stroke: ${e.lineColor}; + stroke-width: 2.0px; + } + + .flowchart-link { + stroke: ${e.lineColor}; + fill: none; + } + + .edgeLabel { + background-color: ${e.edgeLabelBackground}; + /* + * This is for backward compatibility with existing code that didn't + * add a \`
`+(n?i:I(i,!0))+`
+`:`
`+(n?i:I(i,!0))+`
+`}blockquote({tokens:e}){return`
+${this.parser.parse(e)}
+`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
+`}list(e){let t=e.ordered,n=e.start,r=``;for(let t=0;t +`+r+` +`}listitem(e){let t=``;if(e.task){let n=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type===`paragraph`?(e.tokens[0].text=n+` `+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type===`text`&&(e.tokens[0].tokens[0].text=n+` `+I(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:`text`,raw:n+` `,text:n+` `,escaped:!0}):t+=n+` `}return t+=this.parser.parse(e.tokens,!!e.loose),`
  • ${t}
  • +`}checkbox({checked:e}){return``}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t=``,n=``;for(let t=0;t${r}`,` + +`+t+` +`+r+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${I(e,!0)}`}br(e){return`
    `}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Ve(e);if(i===null)return r;e=i;let a=`
    `+r+``,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Ve(e);if(i===null)return I(n);e=i;let a=`${n}`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:I(e.text)}},V=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}},H=class e{options;renderer;textRenderer;constructor(e){this.options=e||f,this.options.renderer=this.options.renderer||new B,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new V}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e,t=!0){let n=``;for(let r=0;r{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new B(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new R(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new U;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];U.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&U.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return z.lex(e,t??this.defaults)}parser(e,t){return H.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer():e?z.lex:z.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser():e?H.parse:H.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer():e?z.lex:z.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser():e?H.parse:H.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let e=`

    An error occurred:

    `+I(n.message+``,!0)+`
    `;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function G(e,t){return W.parse(e,t)}G.options=G.setOptions=function(e){return W.setOptions(e),G.defaults=W.defaults,p(G.defaults),G},G.getDefaults=d,G.defaults=f,G.use=function(...e){return W.use(...e),G.defaults=W.defaults,p(G.defaults),G},G.walkTokens=function(e,t){return W.walkTokens(e,t)},G.parseInline=W.parseInline,G.Parser=H,G.parser=H.parse,G.Renderer=B,G.TextRenderer=V,G.Lexer=z,G.lexer=z.lex,G.Tokenizer=R,G.Hooks=U,G.parse=G,G.options,G.setOptions,G.use,G.walkTokens,G.parseInline,H.parse,z.lex;function Ke(e){var t=[...arguments].slice(1),n=Array.from(typeof e==`string`?[e]:e);n[n.length-1]=n[n.length-1].replace(/\r?\n([\t ]*)$/,``);var r=n.reduce(function(e,t){var n=t.match(/\n([\t ]+|(?!\s).)/g);return n?e.concat(n.map(function(e){return e.match(/[\t ]/g)?.length??0})):e},[]);if(r.length){var i=RegExp(` +[ ]{${Math.min.apply(Math,r)}}`,`g`);n=n.map(function(e){return e.replace(i,` +`)})}n[0]=n[0].replace(/^\r?\n/,``);var a=n[0];return t.forEach(function(e,t){var r=a.match(/(?:^|\n)( *)$/),i=r?r[1]:``,o=e;typeof e==`string`&&e.includes(` +`)&&(o=String(e).split(` +`).map(function(e,t){return t===0?e:`${i}${e}`}).join(` +`)),a+=o+n[t+1]}),a}function qe(e,{markdownAutoWrap:t}){return Ke(e.replace(//g,` +`).replace(/\n{2,}/g,` +`))}e(qe,`preprocessMarkdown`);function Je(e){return e.split(/\\n|\n|/gi).map(e=>e.trim().match(/<[^>]+>|[^\s<>]+/g)?.map(e=>({content:e,type:`normal`}))??[])}e(Je,`nonMarkdownToLines`);function Ye(t,n={}){let r=qe(t,n),i=G.lexer(r),a=[[]],o=0;function s(e,t=`normal`){e.type===`text`?e.text.split(` +`).forEach((e,n)=>{n!==0&&(o++,a.push([])),e.split(` `).forEach(e=>{e=e.replace(/'/g,`'`),e&&a[o].push({content:e,type:t})})}):e.type===`strong`||e.type===`em`?e.tokens.forEach(t=>{s(t,e.type)}):e.type===`html`&&a[o].push({content:e.text,type:`normal`})}return e(s,`processNode`),i.forEach(e=>{e.type===`paragraph`?e.tokens?.forEach(e=>{s(e)}):e.type===`html`?a[o].push({content:e.text,type:`normal`}):a[o].push({content:e.raw,type:`normal`})}),a}e(Ye,`markdownToLines`);function Xe(e){return e?`

    ${e.replace(/\\n|\n/g,`
    `)}

    `:``}e(Xe,`nonMarkdownToHTML`);function Ze(n,{markdownAutoWrap:r}={}){let i=G.lexer(n);function a(e){return e.type===`text`?r===!1?e.text.replace(/\n */g,`
    `).replace(/ /g,` `):e.text.replace(/\n */g,`
    `):e.type===`strong`?`${e.tokens?.map(a).join(``)}`:e.type===`em`?`${e.tokens?.map(a).join(``)}`:e.type===`paragraph`?`

    ${e.tokens?.map(a).join(``)}

    `:e.type===`space`?``:e.type===`html`?`${e.text}`:e.type===`escape`?e.text:(t.warn(`Unsupported markdown: ${e.type}`),e.raw)}return e(a,`output`),i.map(a).join(``)}e(Ze,`markdownToHTML`);function Qe(e){return Intl.Segmenter?[...new Intl.Segmenter().segment(e)].map(e=>e.segment):[...e]}e(Qe,`splitTextToChars`);function $e(e,t){return K(e,[],Qe(t.content),t.type)}e($e,`splitWordToFitWidth`);function K(e,t,n,r){if(n.length===0)return[{content:t.join(``),type:r},{content:``,type:r}];let[i,...a]=n,o=[...t,i];return e([{content:o.join(``),type:r}])?K(e,o,a,r):(t.length===0&&i&&(t.push(i),n.shift()),[{content:t.join(``),type:r},{content:n.join(``),type:r}])}e(K,`splitWordToFitWidthRecursion`);function et(e,t){if(e.some(({content:e})=>e.includes(` +`)))throw Error(`splitLineToFitWidth does not support newlines in the line`);return q(e,t)}e(et,`splitLineToFitWidth`);function q(e,t,n=[],r=[]){if(e.length===0)return r.length>0&&n.push(r),n.length>0?n:[];let i=``;e[0].content===` `&&(i=` `,e.shift());let a=e.shift()??{content:` `,type:`normal`},o=[...r];if(i!==``&&o.push({content:i,type:`normal`}),o.push(a),t(o))return q(e,t,n,o);if(r.length>0)n.push(r),e.unshift(a);else if(a.content){let[r,i]=$e(t,a);n.push([r]),i.content&&e.unshift(i)}return q(e,t,n)}e(q,`splitLineToFitWidthRecursion`);function J(e,t){t&&e.attr(`style`,t)}e(J,`applyStyle`);var tt=16384;async function Y(e,t,n,c,l=!1,u=a()){let d=e.append(`foreignObject`);d.attr(`width`,`${Math.min(10*n,tt)}px`),d.attr(`height`,`${Math.min(10*n,tt)}px`);let f=d.append(`xhtml:div`),p=r(t.label)?await i(t.label.replace(o.lineBreakRegex,` +`),u):s(t.label,u),m=t.isNode?`nodeLabel`:`edgeLabel`,h=f.append(`span`);h.html(p),J(h,t.labelStyle),h.attr(`class`,`${m} ${c}`),J(f,t.labelStyle),f.style(`display`,`table-cell`),f.style(`white-space`,`nowrap`),f.style(`line-height`,`1.5`),n!==1/0&&(f.style(`max-width`,n+`px`),f.style(`text-align`,`center`)),f.attr(`xmlns`,`http://www.w3.org/1999/xhtml`),l&&f.attr(`class`,`labelBkg`);let g=f.node().getBoundingClientRect();return g.width===n&&(f.style(`display`,`table`),f.style(`white-space`,`break-spaces`),f.style(`width`,n+`px`),g=f.node().getBoundingClientRect()),d.node()}e(Y,`addHtmlSpan`);function X(e,t,n,r=!1){let i=e.append(`tspan`).attr(`class`,`text-outer-tspan`).attr(`x`,0).attr(`y`,t*n-.1+`em`).attr(`dy`,n+`em`);return r&&i.attr(`text-anchor`,`middle`),i}e(X,`createTspan`);function nt(e,t,n){let r=e.append(`text`),i=X(r,1,t);Q(i,n);let a=i.node().getComputedTextLength();return r.remove(),a}e(nt,`computeWidthOfText`);function rt(e,t,n){let r=e.append(`text`),i=X(r,1,t);Q(i,[{content:n,type:`normal`}]);let a=i.node()?.getBoundingClientRect();return a&&r.remove(),a}e(rt,`computeDimensionOfText`);function it(t,n,r,i=!1,a=!1){let o=1.1,s=n.append(`g`),c=s.insert(`rect`).attr(`class`,`background`).attr(`style`,`stroke: none`),l=s.append(`text`).attr(`y`,`-10.1`);a&&l.attr(`text-anchor`,`middle`);let u=0;for(let n of r){let r=e(e=>nt(s,o,e)<=t,`checkWidth`),i=r(n)?[n]:et(n,r);for(let e of i)Q(X(l,u,o,a),e),u++}if(i){let e=l.node().getBBox();return c.attr(`x`,e.x-2).attr(`y`,e.y-2).attr(`width`,e.width+4).attr(`height`,e.height+4),s.node()}else return l.node()}e(it,`createFormattedText`);function Z(e){return e.replace(/&(amp|lt|gt);/g,(e,t)=>{switch(t){case`amp`:return`&`;case`lt`:return`<`;case`gt`:return`>`;default:return e}})}e(Z,`decodeHTMLEntities`);function Q(e,t){e.text(``),t.forEach((t,n)=>{let r=e.append(`tspan`).attr(`font-style`,t.type===`em`?`italic`:`normal`).attr(`class`,`text-inner-tspan`).attr(`font-weight`,t.type===`strong`?`bold`:`normal`);n===0?r.text(Z(t.content)):r.text(` `+Z(t.content))})}e(Q,`updateTextContentAndStyles`);async function $(e,t={}){let n=[];e.replace(/(fa[bklrs]?):fa-([\w-]+)/g,(e,r,i)=>(n.push((async()=>{let n=`${r}:${i}`;return await l(n)?await u(n,void 0,{class:`label-icon`}):``})()),e));let r=await Promise.all(n);return e.replace(/(fa[bklrs]?):fa-([\w-]+)/g,()=>r.shift()??``)}e($,`replaceIconSubstring`);var at=e(async(e,i=``,{style:a=``,isTitle:o=!1,classes:s=``,useHtmlLabels:l=!0,markdown:u=!0,isNode:d=!0,width:f=200,addSvgBackground:p=!1}={},m)=>{if(t.debug(`XYZ createText`,i,a,o,s,l,d,`addSvgBackground: `,p),l){let t=await $(c(u?Ze(i,m):Xe(i)),m),n=i.replace(/\\\\/g,`\\`);return await Y(e,{isNode:d,label:r(i)?n:t,labelStyle:a.replace(`fill:`,`color:`)},f,s,p,m)}else{let t=c(i.replace(//g,`
    `)),r=it(f,e,u?Ye(t.replace(`
    `,`
    `),m):Je(t),i?p:!1,!d);if(d){/stroke:/.exec(a)&&(a=a.replace(`stroke:`,`lineColor:`));let e=a.replace(/stroke:[^;]+;?/g,``).replace(/stroke-width:[^;]+;?/g,``).replace(/fill:[^;]+;?/g,``).replace(/color:/g,`fill:`);n(r).attr(`style`,e)}else{let e=a.replace(/stroke:[^;]+;?/g,``).replace(/stroke-width:[^;]+;?/g,``).replace(/fill:[^;]+;?/g,``).replace(/background:/g,`fill:`);n(r).select(`rect`).attr(`style`,e.replace(/background:/g,`fill:`));let t=a.replace(/stroke:[^;]+;?/g,``).replace(/stroke-width:[^;]+;?/g,``).replace(/fill:[^;]+;?/g,``).replace(/color:/g,`fill:`);n(r).select(`text`).attr(`style`,t)}return o?n(r).selectAll(`tspan.text-outer-tspan`).classed(`title-row`,!0):n(r).selectAll(`tspan.text-outer-tspan`).classed(`row`,!0),r}},`createText`);export{at as n,Ke as r,rt as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-QBLGF6JB-C9zGMqvP.js b/dist-desktop/assets/chunk-QBLGF6JB-C9zGMqvP.js new file mode 100644 index 0000000..516b2f7 --- /dev/null +++ b/dist-desktop/assets/chunk-QBLGF6JB-C9zGMqvP.js @@ -0,0 +1 @@ +import{C as e,S as t,i as n,o as r,p as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`RadarTokenBuilder`)}constructor(){super([`radar-beta`])}},u={parser:{TokenBuilder:c(()=>new l,`TokenBuilder`),ValueConverter:c(()=>new n,`ValueConverter`)}};function d(n=r){let a=s(e(n),o),c=s(t({shared:a}),i,u);return a.ServiceRegistry.register(c),{shared:a,Radar:c}}c(d,`createRadarServices`);export{d as n,u as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-R7FJI6CG-BpBhcF6R.js b/dist-desktop/assets/chunk-R7FJI6CG-BpBhcF6R.js new file mode 100644 index 0000000..f75900c --- /dev/null +++ b/dist-desktop/assets/chunk-R7FJI6CG-BpBhcF6R.js @@ -0,0 +1 @@ +import{C as e,S as t,n,o as r,t as i,u as a,w as o,x as s,y as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends i{static{s(this,`TreemapTokenBuilder`)}constructor(){super([`treemap`])}},u=/classDef\s+([A-Z_a-z]\w+)(?:\s+([^\n\r;]*))?;?/,d=class extends n{static{s(this,`TreemapValueConverter`)}runCustomConverter(e,t,n){if(e.name===`NUMBER2`)return parseFloat(t.replace(/,/g,``));if(e.name===`SEPARATOR`||e.name===`STRING2`)return t.substring(1,t.length-1);if(e.name===`INDENTATION`)return t.length;if(e.name===`ClassDef`){if(typeof t!=`string`)return t;let e=u.exec(t);if(e)return{$type:`ClassDefStatement`,className:e[1],styleText:e[2]||void 0}}}};function f(e){let t=e.validation.TreemapValidator,n=e.validation.ValidationRegistry;if(n){let e={Treemap:t.checkSingleRoot.bind(t)};n.register(e,t)}}s(f,`registerValidationChecks`);var p=class{static{s(this,`TreemapValidator`)}checkSingleRoot(e,t){let n;for(let r of e.TreemapRows)r.item&&(n===void 0&&r.indent===void 0?n=0:(r.indent===void 0||n!==void 0&&n>=parseInt(r.indent,10))&&t(`error`,`Multiple root nodes are not allowed in a treemap.`,{node:r,property:`item`}))}},m={parser:{TokenBuilder:s(()=>new l,`TokenBuilder`),ValueConverter:s(()=>new d,`ValueConverter`)},validation:{TreemapValidator:s(()=>new p,`TreemapValidator`)}};function h(n=r){let i=o(e(n),a),s=o(t({shared:i}),c,m);return i.ServiceRegistry.register(s),f(s),{shared:i,Treemap:s}}s(h,`createTreemapServices`);export{h as n,m as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-RYQCIY6F-Dtr3kkSR.js b/dist-desktop/assets/chunk-RYQCIY6F-Dtr3kkSR.js new file mode 100644 index 0000000..3dfcde6 --- /dev/null +++ b/dist-desktop/assets/chunk-RYQCIY6F-Dtr3kkSR.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{r as n,t as r}from"./graphlib-DS17s2tU.js";import{r as i,t as a}from"./map-BaFkSB1l.js";var o=4;function s(e){return i(e,o)}function c(e){var t={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:l(e),edges:u(e)};return n(e.graph())||(t.value=s(e.graph())),t}function l(e){return a(e.nodes(),function(t){var r=e.node(t),i=e.parent(t),a={v:t};return n(r)||(a.value=r),n(i)||(a.parent=i),a})}function u(e){return a(e.edges(),function(t){var r=e.edge(t),i={v:t.v,w:t.w};return n(t.name)||(i.name=t.name),n(r)||(i.value=r),i})}var d=new Map,f=new Map,p=new Map,m=e(()=>{f.clear(),p.clear(),d.clear()},`clear`),h=e((e,n)=>{let r=f.get(n)||[];return t.trace(`In isDescendant`,n,` `,e,` = `,r.includes(e)),r.includes(e)},`isDescendant`),g=e((e,n)=>{let r=f.get(n)||[];return t.info(`Descendants of `,n,` is `,r),t.info(`Edge is `,e),e.v===n||e.w===n?!1:r?r.includes(e.v)||h(e.v,n)||h(e.w,n)||r.includes(e.w):(t.debug(`Tilt, `,n,`,not in descendants`),!1)},`edgeInCluster`),_=e((e,n,r,i)=>{t.warn(`Copying children of `,e,`root`,i,`data`,n.node(e),i);let a=n.children(e)||[];e!==i&&a.push(e),t.warn(`Copying (nodes) clusterId`,e,`nodes`,a),a.forEach(a=>{if(n.children(a).length>0)_(a,n,r,i);else{let o=n.node(a);t.info(`cp `,a,` to `,i,` with parent `,e),r.setNode(a,o),i!==n.parent(a)&&(t.warn(`Setting parent`,a,n.parent(a)),r.setParent(a,n.parent(a))),e!==i&&a!==e?(t.debug(`Setting parent`,a,e),r.setParent(a,e)):(t.info(`In copy `,e,`root`,i,`data`,n.node(e),i),t.debug(`Not Setting parent for node=`,a,`cluster!==rootId`,e!==i,`node!==clusterId`,a!==e));let s=n.edges(a);t.debug(`Copying Edges`,s),s.forEach(a=>{t.info(`Edge`,a);let o=n.edge(a.v,a.w,a.name);t.info(`Edge data`,o,i);try{if(g(a,i)){let e=f.get(i)||[],s=e.includes(a.v)||h(a.v,i)||a.v===i,c=e.includes(a.w)||h(a.w,i)||a.w===i;if(s&&c)t.info(`Copying as `,a.v,a.w,o,a.name),r.setEdge(a.v,a.w,o,a.name),t.info(`newGraph edges `,r.edges(),r.edge(r.edges()[0]));else{let e=s?i:a.v,r=c?i:a.w;t.info(`Rebinding cross-boundary edge as `,e,r,o,a.name),n.setEdge(e,r,o,a.name)}}else t.info(`Skipping copy of edge `,a.v,`-->`,a.w,` rootId: `,i,` clusterId:`,e)}catch(e){t.error(e)}})}t.debug(`Removing node`,a),n.removeNode(a)})},`copy`),v=e((e,t)=>{let n=t.children(e),r=[...n];for(let i of n)p.set(i,e),r=[...r,...v(i,t)];return r},`extractDescendants`),y=e((e,t,n)=>{let r=e.edges().filter(e=>e.v===t||e.w===t),i=e.edges().filter(e=>e.v===n||e.w===n),a=r.map(e=>({v:e.v===t?n:e.v,w:e.w===t?t:e.w})),o=i.map(e=>({v:e.v,w:e.w}));return a.filter(e=>o.some(t=>e.v===t.v&&e.w===t.w))},`findCommonEdges`),b=e((e,n,r)=>{let i=n.children(e);if(t.trace(`Searching children of id `,e,i),i.length<1)return e;let a;for(let e of i){let t=b(e,n,r),i=y(n,r,t);if(t)if(i.length>0)a=t;else return t}return a},`findNonClusterChild`),x=e(e=>!d.has(e)||!d.get(e).externalConnections?e:d.has(e)?d.get(e).id:e,`getAnchorId`),S=e((e,n)=>{if(!e||n>10){t.debug(`Opting out, no graph `);return}else t.debug(`Opting in, graph `);e.nodes().forEach(function(n){e.children(n).length>0&&(t.warn(`Cluster identified`,n,` Replacement id in edges: `,b(n,e,n)),f.set(n,v(n,e)),d.set(n,{id:b(n,e,n),clusterData:e.node(n)}))}),e.nodes().forEach(function(n){let r=e.children(n),i=e.edges();r.length>0?(t.debug(`Cluster identified`,n,f),i.forEach(e=>{h(e.v,n)^h(e.w,n)&&(t.warn(`Edge: `,e,` leaves cluster `,n),t.warn(`Descendants of XXX `,n,`: `,f.get(n)),d.get(n).externalConnections=!0)})):t.debug(`Not a cluster `,n,f)});for(let t of d.keys()){let n=d.get(t).id,r=e.parent(n);r!==t&&d.has(r)&&!d.get(r).externalConnections&&(d.get(t).id=r);let i=e.edges().some(e=>e.v===t);if(n&&d.get(t)?.externalConnections&&i&&E(e,n,t)){let r=D(e,t,e.parent(n));r&&(d.get(t).id=r)}}e.edges().forEach(function(n){let r=e.edge(n);t.warn(`Edge `+n.v+` -> `+n.w+`: `+JSON.stringify(n)),t.warn(`Edge `+n.v+` -> `+n.w+`: `+JSON.stringify(e.edge(n)));let i=n.v,a=n.w;if(t.warn(`Fix XXX`,d,`ids:`,n.v,n.w,`Translating: `,d.get(n.v),` --- `,d.get(n.w)),d.get(n.v)||d.get(n.w)){if(t.warn(`Fixing and trying - removing XXX`,n.v,n.w,n.name),i=x(n.v),a=x(n.w),e.removeEdge(n.v,n.w,n.name),i!==n.v){let t=e.parent(i);d.get(t).externalConnections=!0,r.fromCluster=n.v}if(a!==n.w){let t=e.parent(a);d.get(t).externalConnections=!0,r.toCluster=n.w}t.warn(`Fix Replacing with XXX`,i,a,n.name),e.setEdge(i,a,r,n.name)}}),t.warn(`Adjusted Graph`,c(e)),C(e,0),t.trace(d)},`adjustClustersAndEdges`),C=e((e,n)=>{if(t.warn(`extractor - `,n,c(e),e.children(`D`)),n>10){t.error(`Bailing out`);return}let i=e.nodes(),a=!1;for(let t of i){let n=e.children(t);a||=n.length>0}if(!a){t.debug(`Done, no node has children`,e.nodes());return}t.debug(`Nodes = `,i,n);for(let a of i)if(t.debug(`Extracting node`,a,d,d.has(a)&&!d.get(a).externalConnections,!e.parent(a),e.node(a),e.children(`D`),` Depth `,n),!d.has(a))t.debug(`Not a cluster`,a,n);else if(d.get(a)?.clusterData?.explicitDir&&e.children(a)&&e.children(a).length>0){t.warn(`Cluster with explicit dir, creating subgraph for children`,a,n);let i=d.get(a).clusterData.dir,o=new r({multigraph:!0,compound:!0}).setGraph({rankdir:i,nodesep:50,ranksep:50,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}});_(a,e,o,a);let s=e.node(a)||{};e.setNode(a,{...s,clusterNode:!0,id:a,clusterData:d.get(a).clusterData,label:d.get(a).label,graph:o}),t.warn(`Subgraph for cluster with explicit dir created:`,a,c(o))}else if(!d.get(a).externalConnections&&e.children(a)&&e.children(a).length>0){t.warn(`Cluster without external connections, without a parent and with children`,a,n);let i=e.graph().rankdir===`TB`?`LR`:`TB`;d.get(a)?.clusterData?.dir&&(i=d.get(a).clusterData.dir,t.warn(`Fixing dir`,d.get(a).clusterData.dir,i));let o=new r({multigraph:!0,compound:!0}).setGraph({rankdir:i,nodesep:50,ranksep:50,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}});_(a,e,o,a);let s=e.node(a)||{};e.setNode(a,{...s,clusterNode:!0,id:a,clusterData:d.get(a).clusterData,label:d.get(a).label,graph:o}),t.debug(`Old graph after copy`,c(e))}else t.warn(`Cluster ** `,a,` **not meeting the criteria !externalConnections:`,!d.get(a).externalConnections,` no parent: `,!e.parent(a),` children `,e.children(a)&&e.children(a).length>0,e.children(`D`),n),t.debug(d);i=e.nodes(),t.warn(`New list of nodes`,i);for(let r of i){let i=e.node(r);t.warn(` Now next level`,r,i),i?.clusterNode&&C(i.graph,n+1)}},`extractor`),w=e((e,t)=>{if(t.length===0)return[];let n=Object.assign([],t);return t.forEach(t=>{let r=w(e,e.children(t));n=[...n,...r]}),n},`sorter`),T=e(e=>w(e,e.children()),`sortNodesByHierarchy`),E=e((e,t,n)=>{let r=e.parent(t);for(;r&&r!==n;){let t=d.get(r);if(t&&!t.externalConnections)return!0;r=e.parent(r)}return!1},`isNodeInExtractableCluster`),D=e((e,t,n)=>{let r=e.children(t)??[];for(let i of r){if(i===n||h(i,n))continue;let r=b(i,e,t);if(r&&!E(e,r,t))return r}return null},`findSafeAnchorNode`);export{T as a,b as i,m as n,c as o,d as r,S as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-U6XO7XAA-CR0BSRFR.js b/dist-desktop/assets/chunk-U6XO7XAA-CR0BSRFR.js new file mode 100644 index 0000000..9298b06 --- /dev/null +++ b/dist-desktop/assets/chunk-U6XO7XAA-CR0BSRFR.js @@ -0,0 +1,2 @@ +import{C as e,S as t,h as n,n as r,o as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`RailroadEbnfTokenBuilder`)}constructor(){super([`railroad-ebnf-beta`])}},u=c(e=>{let t=e.slice(1,-1),n=``;for(let e=0;enew l,`TokenBuilder`),ValueConverter:c(()=>new d,`ValueConverter`)}};function p(r=i){let a=s(e(r),o),c=s(t({shared:a}),n,f);return a.ServiceRegistry.register(c),{shared:a,RailroadEbnf:c}}c(p,`createRailroadEbnfServices`);export{p as n,f as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-V7JOEXUC-Drt5hFEy.js b/dist-desktop/assets/chunk-V7JOEXUC-Drt5hFEy.js new file mode 100644 index 0000000..6f6feb6 --- /dev/null +++ b/dist-desktop/assets/chunk-V7JOEXUC-Drt5hFEy.js @@ -0,0 +1,206 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{$ as r,H as i,K as a,M as o,U as s,a as c,s as l,v as u,w as d,x as f,y as p,z as m}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{c as h,g}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as _}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{t as v}from"./chunk-32BRIVSS-DWU3ezKg.js";import{t as y}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as b}from"./chunk-VR4S4FIN-BTo4eV3J.js";import{r as x,t as S}from"./chunk-FWX5IMBZ-ComLEIwh.js";var C=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,18],r=[1,19],i=[1,20],a=[1,41],o=[1,26],s=[1,42],c=[1,24],l=[1,25],u=[1,32],d=[1,33],f=[1,34],p=[1,45],m=[1,35],h=[1,36],g=[1,37],_=[1,38],v=[1,27],y=[1,28],b=[1,29],x=[1,30],S=[1,31],C=[1,44],w=[1,46],T=[1,43],E=[1,47],D=[1,9],O=[1,8,9],k=[1,58],A=[1,59],j=[1,60],M=[1,61],N=[1,62],P=[1,63],ee=[1,64],F=[1,8,9,41],te=[1,77],I=[1,8,9,12,13,22,39,41,44,46,68,69,70,71,72,73,74,79,81],L=[1,8,9,12,13,18,20,22,39,41,44,46,47,60,68,69,70,71,72,73,74,79,81,86,100,102,103],R=[13,60,86,100,102,103],z=[13,60,73,74,86,100,102,103],ne=[13,60,68,69,70,71,72,86,100,102,103],B=[1,103],V=[1,121],H=[1,117],U=[1,113],W=[1,119],G=[1,114],K=[1,115],q=[1,116],J=[1,118],Y=[1,120],re=[22,50,60,61,82,86,87,88,89,90],ie=[1,128],X=[12,39],ae=[1,8,9,39,41,44,46],Z=[1,8,9,22],oe=[1,153],se=[1,8,9,61],Q=[1,8,9,22,50,60,61,82,86,87,88,89,90],ce={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,statements:5,graphConfig:6,CLASS_DIAGRAM:7,NEWLINE:8,EOF:9,statement:10,classLabel:11,SQS:12,STR:13,SQE:14,namespaceName:15,alphaNumToken:16,classLiteralName:17,DOT:18,className:19,GENERICTYPE:20,relationStatement:21,LABEL:22,namespaceStatement:23,classStatement:24,memberStatement:25,annotationStatement:26,clickStatement:27,styleStatement:28,cssClassStatement:29,noteStatement:30,classDefStatement:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,namespaceIdentifier:38,STRUCT_START:39,classStatements:40,STRUCT_STOP:41,NAMESPACE:42,classIdentifier:43,STYLE_SEPARATOR:44,members:45,ANNOTATION_START:46,ANNOTATION_END:47,CLASS:48,emptyBody:49,SPACE:50,MEMBER:51,SEPARATOR:52,relation:53,NOTE_FOR:54,noteText:55,NOTE:56,CLASSDEF:57,classList:58,stylesOpt:59,ALPHA:60,COMMA:61,direction_tb:62,direction_bt:63,direction_rl:64,direction_lr:65,relationType:66,lineType:67,AGGREGATION:68,EXTENSION:69,COMPOSITION:70,DEPENDENCY:71,LOLLIPOP:72,LINE:73,DOTTED_LINE:74,CALLBACK:75,LINK:76,LINK_TARGET:77,CLICK:78,CALLBACK_NAME:79,CALLBACK_ARGS:80,HREF:81,STYLE:82,CSSCLASS:83,style:84,styleComponent:85,NUM:86,COLON:87,UNIT:88,BRKT:89,PCT:90,commentToken:91,textToken:92,graphCodeTokens:93,textNoTagsToken:94,TAGSTART:95,TAGEND:96,"==":97,"--":98,DEFAULT:99,MINUS:100,keywords:101,UNICODE_TEXT:102,BQUOTE_STR:103,$accept:0,$end:1},terminals_:{2:`error`,7:`CLASS_DIAGRAM`,8:`NEWLINE`,9:`EOF`,12:`SQS`,13:`STR`,14:`SQE`,18:`DOT`,20:`GENERICTYPE`,22:`LABEL`,33:`acc_title`,34:`acc_title_value`,35:`acc_descr`,36:`acc_descr_value`,37:`acc_descr_multiline_value`,39:`STRUCT_START`,41:`STRUCT_STOP`,42:`NAMESPACE`,44:`STYLE_SEPARATOR`,46:`ANNOTATION_START`,47:`ANNOTATION_END`,48:`CLASS`,50:`SPACE`,51:`MEMBER`,52:`SEPARATOR`,54:`NOTE_FOR`,56:`NOTE`,57:`CLASSDEF`,60:`ALPHA`,61:`COMMA`,62:`direction_tb`,63:`direction_bt`,64:`direction_rl`,65:`direction_lr`,68:`AGGREGATION`,69:`EXTENSION`,70:`COMPOSITION`,71:`DEPENDENCY`,72:`LOLLIPOP`,73:`LINE`,74:`DOTTED_LINE`,75:`CALLBACK`,76:`LINK`,77:`LINK_TARGET`,78:`CLICK`,79:`CALLBACK_NAME`,80:`CALLBACK_ARGS`,81:`HREF`,82:`STYLE`,83:`CSSCLASS`,86:`NUM`,87:`COLON`,88:`UNIT`,89:`BRKT`,90:`PCT`,93:`graphCodeTokens`,95:`TAGSTART`,96:`TAGEND`,97:`==`,98:`--`,99:`DEFAULT`,100:`MINUS`,101:`keywords`,102:`UNICODE_TEXT`,103:`BQUOTE_STR`},productions_:[0,[3,1],[3,1],[4,1],[6,4],[5,1],[5,2],[5,3],[11,3],[15,1],[15,1],[15,3],[15,2],[19,1],[19,3],[19,1],[19,2],[19,2],[19,2],[10,1],[10,2],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,2],[10,2],[10,1],[23,4],[23,5],[38,2],[38,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[24,1],[24,3],[24,4],[24,3],[24,6],[24,4],[24,7],[24,6],[43,2],[43,3],[49,0],[49,2],[49,2],[26,4],[45,1],[45,2],[25,1],[25,2],[25,1],[25,1],[21,3],[21,4],[21,4],[21,5],[30,3],[30,2],[31,3],[58,1],[58,3],[32,1],[32,1],[32,1],[32,1],[53,3],[53,2],[53,2],[53,1],[66,1],[66,1],[66,1],[66,1],[66,1],[67,1],[67,1],[27,3],[27,4],[27,3],[27,4],[27,4],[27,5],[27,3],[27,4],[27,4],[27,5],[27,4],[27,5],[27,5],[27,6],[28,3],[29,3],[59,1],[59,3],[84,1],[84,2],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[91,1],[91,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[94,1],[94,1],[94,1],[94,1],[16,1],[16,1],[16,1],[16,1],[17,1],[55,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 8:this.$=a[s-1];break;case 9:case 10:case 13:case 15:this.$=a[s];break;case 11:case 14:this.$=a[s-2]+`.`+a[s];break;case 12:case 16:this.$=a[s-1]+a[s];break;case 17:case 18:this.$=a[s-1]+`~`+a[s]+`~`;break;case 19:r.addRelation(a[s]);break;case 20:a[s-1].title=r.cleanupLabel(a[s]),r.addRelation(a[s-1]);break;case 31:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 32:case 33:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 34:r.addClassesToNamespace(a[s-3],a[s-1][0],a[s-1][1]),r.popNamespace();break;case 35:r.addClassesToNamespace(a[s-4],a[s-1][0],a[s-1][1]),r.popNamespace();break;case 36:this.$=r.addNamespace(a[s]);break;case 37:this.$=r.addNamespace(a[s-1],a[s]);break;case 38:this.$=[[a[s]],[]];break;case 39:this.$=[[a[s-1]],[]];break;case 40:a[s][0].unshift(a[s-2]),this.$=a[s];break;case 41:this.$=[[],[a[s]]];break;case 42:this.$=[[],[a[s-1]]];break;case 43:a[s][1].unshift(a[s-2]),this.$=a[s];break;case 44:case 45:this.$=[[],[]];break;case 46:this.$=a[s];break;case 48:r.setCssClass(a[s-2],a[s]);break;case 49:r.addMembers(a[s-3],a[s-1]);break;case 51:r.setCssClass(a[s-5],a[s-3]),r.addMembers(a[s-5],a[s-1]);break;case 52:r.addAnnotation(a[s-3],a[s-1]);break;case 53:r.addAnnotation(a[s-6],a[s-4]),r.addMembers(a[s-6],a[s-1]);break;case 54:r.addAnnotation(a[s-5],a[s-3]);break;case 55:this.$=a[s],r.addClass(a[s]);break;case 56:this.$=a[s-1],r.addClass(a[s-1]),r.setClassLabel(a[s-1],a[s]);break;case 60:r.addAnnotation(a[s],a[s-2]);break;case 61:case 74:this.$=[a[s]];break;case 62:a[s].push(a[s-1]),this.$=a[s];break;case 63:break;case 64:r.addMember(a[s-1],r.cleanupLabel(a[s]));break;case 65:break;case 66:break;case 67:this.$={id1:a[s-2],id2:a[s],relation:a[s-1],relationTitle1:`none`,relationTitle2:`none`};break;case 68:this.$={id1:a[s-3],id2:a[s],relation:a[s-1],relationTitle1:a[s-2],relationTitle2:`none`};break;case 69:this.$={id1:a[s-3],id2:a[s],relation:a[s-2],relationTitle1:`none`,relationTitle2:a[s-1]};break;case 70:this.$={id1:a[s-4],id2:a[s],relation:a[s-2],relationTitle1:a[s-3],relationTitle2:a[s-1]};break;case 71:this.$=r.addNote(a[s],a[s-1]);break;case 72:this.$=r.addNote(a[s]);break;case 73:this.$=a[s-2],r.defineClass(a[s-1],a[s]);break;case 75:this.$=a[s-2].concat([a[s]]);break;case 76:r.setDirection(`TB`);break;case 77:r.setDirection(`BT`);break;case 78:r.setDirection(`RL`);break;case 79:r.setDirection(`LR`);break;case 80:this.$={type1:a[s-2],type2:a[s],lineType:a[s-1]};break;case 81:this.$={type1:`none`,type2:a[s],lineType:a[s-1]};break;case 82:this.$={type1:a[s-1],type2:`none`,lineType:a[s]};break;case 83:this.$={type1:`none`,type2:`none`,lineType:a[s]};break;case 84:this.$=r.relationType.AGGREGATION;break;case 85:this.$=r.relationType.EXTENSION;break;case 86:this.$=r.relationType.COMPOSITION;break;case 87:this.$=r.relationType.DEPENDENCY;break;case 88:this.$=r.relationType.LOLLIPOP;break;case 89:this.$=r.lineType.LINE;break;case 90:this.$=r.lineType.DOTTED_LINE;break;case 91:case 97:this.$=a[s-2],r.setClickEvent(a[s-1],a[s]);break;case 92:case 98:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 93:this.$=a[s-2],r.setLink(a[s-1],a[s]);break;case 94:this.$=a[s-3],r.setLink(a[s-2],a[s-1],a[s]);break;case 95:this.$=a[s-3],r.setLink(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 96:this.$=a[s-4],r.setLink(a[s-3],a[s-2],a[s]),r.setTooltip(a[s-3],a[s-1]);break;case 99:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 100:this.$=a[s-4],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setTooltip(a[s-3],a[s]);break;case 101:this.$=a[s-3],r.setLink(a[s-2],a[s]);break;case 102:this.$=a[s-4],r.setLink(a[s-3],a[s-1],a[s]);break;case 103:this.$=a[s-4],r.setLink(a[s-3],a[s-1]),r.setTooltip(a[s-3],a[s]);break;case 104:this.$=a[s-5],r.setLink(a[s-4],a[s-2],a[s]),r.setTooltip(a[s-4],a[s-1]);break;case 105:this.$=a[s-2],r.setCssStyle(a[s-1],a[s]);break;case 106:r.setCssClass(a[s-1],a[s]);break;case 107:this.$=[a[s]];break;case 108:a[s-2].push(a[s]),this.$=a[s-2];break;case 110:this.$=a[s-1]+a[s];break}},`anonymous`),table:[{3:1,4:2,5:3,6:4,7:[1,6],10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:n,35:r,37:i,38:22,42:a,43:23,46:o,48:s,51:c,52:l,54:u,56:d,57:f,60:p,62:m,63:h,64:g,65:_,75:v,76:y,78:b,82:x,83:S,86:C,100:w,102:T,103:E},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,3]},t(D,[2,5],{8:[1,48]}),{8:[1,49]},t(O,[2,19],{22:[1,50]}),t(O,[2,21]),t(O,[2,22]),t(O,[2,23]),t(O,[2,24]),t(O,[2,25]),t(O,[2,26]),t(O,[2,27]),t(O,[2,28]),t(O,[2,29]),t(O,[2,30]),{34:[1,51]},{36:[1,52]},t(O,[2,33]),t(O,[2,63],{53:53,66:56,67:57,13:[1,54],22:[1,55],68:k,69:A,70:j,71:M,72:N,73:P,74:ee}),{39:[1,65]},t(F,[2,47],{39:[1,67],44:[1,66],46:[1,68]}),t(O,[2,65]),t(O,[2,66]),{16:69,60:p,86:C,100:w,102:T},{16:39,17:40,19:70,60:p,86:C,100:w,102:T,103:E},{16:39,17:40,19:71,60:p,86:C,100:w,102:T,103:E},{16:39,17:40,19:72,60:p,86:C,100:w,102:T,103:E},{60:[1,73]},{13:[1,74]},{16:39,17:40,19:75,60:p,86:C,100:w,102:T,103:E},{13:te,55:76},{58:78,60:[1,79]},t(O,[2,76]),t(O,[2,77]),t(O,[2,78]),t(O,[2,79]),t(I,[2,13],{16:39,17:40,19:81,18:[1,80],20:[1,82],60:p,86:C,100:w,102:T,103:E}),t(I,[2,15],{20:[1,83]}),{15:84,16:85,17:86,60:p,86:C,100:w,102:T,103:E},{16:39,17:40,19:87,60:p,86:C,100:w,102:T,103:E},t(L,[2,133]),t(L,[2,134]),t(L,[2,135]),t(L,[2,136]),t([1,8,9,12,13,20,22,39,41,44,46,68,69,70,71,72,73,74,79,81],[2,137]),t(D,[2,6],{10:5,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,19:21,38:22,43:23,16:39,17:40,5:88,33:n,35:r,37:i,42:a,46:o,48:s,51:c,52:l,54:u,56:d,57:f,60:p,62:m,63:h,64:g,65:_,75:v,76:y,78:b,82:x,83:S,86:C,100:w,102:T,103:E}),{5:89,10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:n,35:r,37:i,38:22,42:a,43:23,46:o,48:s,51:c,52:l,54:u,56:d,57:f,60:p,62:m,63:h,64:g,65:_,75:v,76:y,78:b,82:x,83:S,86:C,100:w,102:T,103:E},t(O,[2,20]),t(O,[2,31]),t(O,[2,32]),{13:[1,91],16:39,17:40,19:90,60:p,86:C,100:w,102:T,103:E},{53:92,66:56,67:57,68:k,69:A,70:j,71:M,72:N,73:P,74:ee},t(O,[2,64]),{67:93,73:P,74:ee},t(R,[2,83],{66:94,68:k,69:A,70:j,71:M,72:N}),t(z,[2,84]),t(z,[2,85]),t(z,[2,86]),t(z,[2,87]),t(z,[2,88]),t(ne,[2,89]),t(ne,[2,90]),{8:[1,96],23:99,24:97,30:98,38:22,40:95,42:a,43:23,48:s,54:u,56:d},{16:100,60:p,86:C,100:w,102:T},{41:[1,102],45:101,51:B},{16:104,60:p,86:C,100:w,102:T},{47:[1,105]},{13:[1,106]},{13:[1,107]},{79:[1,108],81:[1,109]},{22:V,50:H,59:110,60:U,82:W,84:111,85:112,86:G,87:K,88:q,89:J,90:Y},{60:[1,122]},{13:te,55:123},t(F,[2,72]),t(F,[2,138]),{22:V,50:H,59:124,60:U,61:[1,125],82:W,84:111,85:112,86:G,87:K,88:q,89:J,90:Y},t(re,[2,74]),{16:39,17:40,19:126,60:p,86:C,100:w,102:T,103:E},t(I,[2,16]),t(I,[2,17]),t(I,[2,18]),{11:127,12:ie,39:[2,36]},t(X,[2,9],{16:85,17:86,15:130,18:[1,129],60:p,86:C,100:w,102:T,103:E}),t(X,[2,10]),t(ae,[2,55],{11:131,12:ie}),t(D,[2,7]),{9:[1,132]},t(Z,[2,67]),{16:39,17:40,19:133,60:p,86:C,100:w,102:T,103:E},{13:[1,135],16:39,17:40,19:134,60:p,86:C,100:w,102:T,103:E},t(R,[2,82],{66:136,68:k,69:A,70:j,71:M,72:N}),t(R,[2,81]),{41:[1,137]},{23:99,24:97,30:98,38:22,40:138,42:a,43:23,48:s,54:u,56:d},{8:[1,139],41:[2,38]},{8:[1,140],41:[2,41]},{8:[1,141],41:[2,44]},t(F,[2,48],{39:[1,142]}),{41:[1,143]},t(F,[2,50]),{41:[2,61],45:144,51:B},{47:[1,145]},{16:39,17:40,19:146,60:p,86:C,100:w,102:T,103:E},t(O,[2,91],{13:[1,147]}),t(O,[2,93],{13:[1,149],77:[1,148]}),t(O,[2,97],{13:[1,150],80:[1,151]}),{13:[1,152]},t(O,[2,105],{61:oe}),t(se,[2,107],{85:154,22:V,50:H,60:U,82:W,86:G,87:K,88:q,89:J,90:Y}),t(Q,[2,109]),t(Q,[2,111]),t(Q,[2,112]),t(Q,[2,113]),t(Q,[2,114]),t(Q,[2,115]),t(Q,[2,116]),t(Q,[2,117]),t(Q,[2,118]),t(Q,[2,119]),t(O,[2,106]),t(F,[2,71]),t(O,[2,73],{61:oe}),{60:[1,155]},t(I,[2,14]),{39:[2,37]},{13:[1,156]},{15:157,16:85,17:86,60:p,86:C,100:w,102:T,103:E},t(X,[2,12]),t(ae,[2,56]),{1:[2,4]},t(Z,[2,69]),t(Z,[2,68]),{16:39,17:40,19:158,60:p,86:C,100:w,102:T,103:E},t(R,[2,80]),t(F,[2,34]),{41:[1,159]},{23:99,24:97,30:98,38:22,40:160,41:[2,39],42:a,43:23,48:s,54:u,56:d},{23:99,24:97,30:98,38:22,40:161,41:[2,42],42:a,43:23,48:s,54:u,56:d},{23:99,24:97,30:98,38:22,40:162,41:[2,45],42:a,43:23,48:s,54:u,56:d},{45:163,51:B},t(F,[2,49]),{41:[2,62]},t(F,[2,52],{39:[1,164]}),t(O,[2,60]),t(O,[2,92]),t(O,[2,94]),t(O,[2,95],{77:[1,165]}),t(O,[2,98]),t(O,[2,99],{13:[1,166]}),t(O,[2,101],{13:[1,168],77:[1,167]}),{22:V,50:H,60:U,82:W,84:169,85:112,86:G,87:K,88:q,89:J,90:Y},t(Q,[2,110]),t(re,[2,75]),{14:[1,170]},t(X,[2,11]),t(Z,[2,70]),t(F,[2,35]),{41:[2,40]},{41:[2,43]},{41:[2,46]},{41:[1,171]},{41:[1,173],45:172,51:B},t(O,[2,96]),t(O,[2,100]),t(O,[2,102]),t(O,[2,103],{77:[1,174]}),t(se,[2,108],{85:154,22:V,50:H,60:U,82:W,86:G,87:K,88:q,89:J,90:Y}),t(ae,[2,8]),t(F,[2,51]),{41:[1,175]},t(F,[2,54]),t(O,[2,104]),t(F,[2,53])],defaultActions:{2:[2,1],3:[2,2],4:[2,3],127:[2,37],132:[2,4],144:[2,62],160:[2,40],161:[2,43],162:[2,46]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};ce.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{},performAction:e(function(e,t,n,r){switch(n){case 0:return 62;case 1:return 63;case 2:return 64;case 3:return 65;case 4:break;case 5:break;case 6:return this.begin(`acc_title`),33;case 7:return this.popState(),`acc_title_value`;case 8:return this.begin(`acc_descr`),35;case 9:return this.popState(),`acc_descr_value`;case 10:this.begin(`acc_descr_multiline`);break;case 11:this.popState();break;case 12:return`acc_descr_multiline_value`;case 13:return 8;case 14:break;case 15:return 7;case 16:return 7;case 17:return`EDGE_STATE`;case 18:this.begin(`callback_name`);break;case 19:this.popState();break;case 20:this.popState(),this.begin(`callback_args`);break;case 21:return 79;case 22:this.popState();break;case 23:return 80;case 24:this.popState();break;case 25:return`STR`;case 26:this.begin(`string`);break;case 27:return 82;case 28:return 57;case 29:return this.begin(`namespace`),42;case 30:return this.popState(),8;case 31:break;case 32:return this.begin(`namespace-body`),39;case 33:this.popState(),this.less(0);break;case 34:return this.popState(),41;case 35:return`EOF_IN_STRUCT`;case 36:return 8;case 37:break;case 38:return`EDGE_STATE`;case 39:return this.begin(`class`),48;case 40:return this.popState(),8;case 41:break;case 42:return this.popState(),this.popState(),41;case 43:return this.begin(`class-body`),39;case 44:return this.popState(),41;case 45:return`EOF_IN_STRUCT`;case 46:return`EDGE_STATE`;case 47:return`OPEN_IN_STRUCT`;case 48:break;case 49:return`MEMBER`;case 50:return 83;case 51:return 75;case 52:return 76;case 53:return 78;case 54:return 54;case 55:return 56;case 56:return 46;case 57:return 47;case 58:return 81;case 59:this.popState();break;case 60:return`GENERICTYPE`;case 61:this.begin(`generic`);break;case 62:this.popState();break;case 63:return`BQUOTE_STR`;case 64:this.begin(`bqstring`);break;case 65:return 77;case 66:return 77;case 67:return 77;case 68:return 77;case 69:return 69;case 70:return 69;case 71:return 71;case 72:return 71;case 73:return 70;case 74:return 68;case 75:return 72;case 76:return 73;case 77:return 74;case 78:return 22;case 79:return 44;case 80:return 100;case 81:return 18;case 82:return`PLUS`;case 83:return 87;case 84:return 61;case 85:return 89;case 86:return 89;case 87:return 90;case 88:return`EQUALS`;case 89:return`EQUALS`;case 90:return 60;case 91:return 12;case 92:return 14;case 93:return`PUNCTUATION`;case 94:return 86;case 95:return 102;case 96:return 50;case 97:return 50;case 98:return 9}},`anonymous`),rules:[/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:%%(?!\{)*[^\n]*(\r?\n?)+)/,/^(?:%%[^\n]*(\r?\n)*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:classDiagram-v2\b)/,/^(?:classDiagram\b)/,/^(?:\[\*\])/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:["])/,/^(?:[^"]*)/,/^(?:["])/,/^(?:style\b)/,/^(?:classDef\b)/,/^(?:namespace\b)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:[{])/,/^(?:[}])/,/^(?:[}])/,/^(?:$)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:\[\*\])/,/^(?:class\b)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:[}])/,/^(?:[{])/,/^(?:[}])/,/^(?:$)/,/^(?:\[\*\])/,/^(?:[{])/,/^(?:[\n])/,/^(?:[^{}\n]*)/,/^(?:cssClass\b)/,/^(?:callback\b)/,/^(?:link\b)/,/^(?:click\b)/,/^(?:note for\b)/,/^(?:note\b)/,/^(?:<<)/,/^(?:>>)/,/^(?:href\b)/,/^(?:[~])/,/^(?:[^~]*)/,/^(?:~)/,/^(?:[`])/,/^(?:[^`]+)/,/^(?:[`])/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:\s*<\|)/,/^(?:\s*\|>)/,/^(?:\s*>)/,/^(?:\s*<)/,/^(?:\s*\*)/,/^(?:\s*o\b)/,/^(?:\s*\(\))/,/^(?:--)/,/^(?:\.\.)/,/^(?::{1}[^:\n;]+)/,/^(?::{3})/,/^(?:-)/,/^(?:\.)/,/^(?:\+)/,/^(?::)/,/^(?:,)/,/^(?:#)/,/^(?:#)/,/^(?:%)/,/^(?:=)/,/^(?:=)/,/^(?:\w+)/,/^(?:\[)/,/^(?:\])/,/^(?:[!"#$%&'*+,-.`?\\/])/,/^(?:[0-9]+)/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\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\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\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\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-\u0C33\u0C35-\u0C39\u0C3D]|[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\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-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\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\u2183\u2184]|[\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\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\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])/,/^(?:\s)/,/^(?:\s)/,/^(?:$)/],conditions:{"namespace-body":{rules:[26,29,34,35,36,37,38,39,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},namespace:{rules:[26,29,30,31,32,33,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},"class-body":{rules:[26,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},class:{rules:[26,40,41,42,43,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},acc_descr_multiline:{rules:[11,12,26,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},acc_descr:{rules:[9,26,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},acc_title:{rules:[7,26,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},callback_args:{rules:[22,23,26,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},callback_name:{rules:[19,20,21,26,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},href:{rules:[26,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},struct:{rules:[26,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},generic:{rules:[26,50,51,52,53,54,55,56,57,58,59,60,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},bqstring:{rules:[26,50,51,52,53,54,55,56,57,58,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},string:{rules:[24,25,26,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,8,10,13,14,15,16,17,18,26,27,28,29,39,50,51,52,53,54,55,56,57,58,61,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98],inclusive:!0}}}})();function $(){this.yy={}}return e($,`Parser`),$.prototype=ce,ce.Parser=$,new $})();C.parser=C;var w=C,T=[`#`,`+`,`~`,`-`,``],E=class{static{e(this,`ClassMember`)}constructor(e,t){this.memberType=t,this.visibility=``,this.classifier=``,this.text=``;let n=m(e,f());this.parseMember(n)}getDisplayDetails(){let e=this.visibility+o(this.id);this.memberType===`method`&&(e+=`(${o(this.parameters.trim())})`,this.returnType&&(e+=` : `+o(this.returnType))),e=e.trim();let t=this.parseClassifier();return{displayText:e,cssStyle:t}}parseMember(e){let t=``;if(this.memberType===`method`){let n=/([#+~-])?(.+)\((.*)\)([\s$*])?(.*)([$*])?/.exec(e);if(n){let e=n[1]?n[1].trim():``;if(T.includes(e)&&(this.visibility=e),this.id=n[2],this.parameters=n[3]?n[3].trim():``,t=n[4]?n[4].trim():``,this.returnType=n[5]?n[5].trim():``,t===``){let e=this.returnType.substring(this.returnType.length-1);/[$*]/.exec(e)&&(t=e,this.returnType=this.returnType.substring(0,this.returnType.length-1))}}}else{let n=e.length,r=e.substring(0,1),i=e.substring(n-1);T.includes(r)&&(this.visibility=r),/[$*]/.exec(i)&&(t=i),this.id=e.substring(this.visibility===``?0:1,t===``?n:n-1)}this.classifier=t,this.id=this.id.startsWith(` `)?` `+this.id.trim():this.id.trim();let n=`${this.visibility?`\\`+this.visibility:``}${o(this.id)}${this.memberType===`method`?`(${o(this.parameters)})${this.returnType?` : `+o(this.returnType):``}`:``}`;this.text=n.replaceAll(`<`,`<`).replaceAll(`>`,`>`),this.text.startsWith(`\\<`)&&(this.text=this.text.replace(`\\<`,`~`))}parseClassifier(){switch(this.classifier){case`*`:return`font-style:italic;`;case`$`:return`text-decoration:underline;`;default:return``}}},D=`classId-`,O=0,k=e(e=>l.sanitizeText(e,f()),`sanitizeText`),A=class o{constructor(){this.relations=[],this.classes=new Map,this.styleClasses=new Map,this.notes=new Map,this.interfaces=[],this.namespaces=new Map,this.namespaceCounter=0,this.namespaceStack=[],this.diagramId=``,this.functions=[],this.lineType={LINE:0,DOTTED_LINE:1},this.relationType={AGGREGATION:0,EXTENSION:1,COMPOSITION:2,DEPENDENCY:3,LOLLIPOP:4},this.setupToolTips=e(e=>{let t=v();n(e).select(`svg`).selectAll(`g`).filter(function(){return n(this).attr(`title`)!==null}).on(`mouseover`,e=>{let i=n(e.currentTarget),a=i.attr(`title`);if(!a)return;let o=e.currentTarget.getBoundingClientRect();t.transition().duration(200).style(`opacity`,`.9`),t.html(r.sanitize(a)).style(`left`,`${window.scrollX+o.left+o.width/2}px`).style(`top`,`${window.scrollY+o.bottom+4}px`),i.classed(`hover`,!0)}).on(`mouseout`,e=>{t.transition().duration(500).style(`opacity`,0),n(e.currentTarget).classed(`hover`,!1)})},`setupToolTips`),this.direction=`TB`,this.setAccTitle=s,this.getAccTitle=p,this.setAccDescription=i,this.getAccDescription=u,this.setDiagramTitle=a,this.getDiagramTitle=d,this.getConfig=e(()=>f().class,`getConfig`),this.functions.push(this.setupToolTips.bind(this)),this.clear(),this.addRelation=this.addRelation.bind(this),this.addClassesToNamespace=this.addClassesToNamespace.bind(this),this.addNamespace=this.addNamespace.bind(this),this.popNamespace=this.popNamespace.bind(this),this.setCssClass=this.setCssClass.bind(this),this.addMembers=this.addMembers.bind(this),this.addClass=this.addClass.bind(this),this.setClassLabel=this.setClassLabel.bind(this),this.addAnnotation=this.addAnnotation.bind(this),this.addMember=this.addMember.bind(this),this.cleanupLabel=this.cleanupLabel.bind(this),this.addNote=this.addNote.bind(this),this.defineClass=this.defineClass.bind(this),this.setDirection=this.setDirection.bind(this),this.setLink=this.setLink.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.clear=this.clear.bind(this),this.setTooltip=this.setTooltip.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setCssStyle=this.setCssStyle.bind(this)}static{e(this,`ClassDB`)}splitClassNameAndType(e){let t=l.sanitizeText(e,f()),n=``,r=t;if(t.indexOf(`~`)>0){let e=t.split(`~`);r=k(e[0]),n=k(e[1])}return{className:r,type:n}}setClassLabel(e,t){let n=l.sanitizeText(e,f());t&&=k(t);let{className:r}=this.splitClassNameAndType(n);this.classes.get(r).label=t,this.classes.get(r).text=`${t}${this.classes.get(r).type?`<${this.classes.get(r).type}>`:``}`}addClass(e){let t=l.sanitizeText(e,f()),{className:n,type:r}=this.splitClassNameAndType(t);if(this.classes.has(n))return;let i=l.sanitizeText(n,f());this.classes.set(i,{id:i,type:r,label:i,text:`${i}${r?`<${r}>`:``}`,shape:`classBox`,cssClasses:`default`,methods:[],members:[],annotations:[],styles:[],domId:D+i+`-`+O}),O++}addInterface(e,t){let n={id:`interface${this.interfaces.length}`,label:e,classId:t};this.interfaces.push(n)}setDiagramId(e){this.diagramId=e}lookUpDomId(e){let t=l.sanitizeText(e,f());if(this.classes.has(t)){let e=this.classes.get(t).domId;return this.diagramId?`${this.diagramId}-${e}`:e}throw Error(`Class not found: `+t)}clear(){this.relations=[],this.classes=new Map,this.notes=new Map,this.interfaces=[],this.functions=[],this.functions.push(this.setupToolTips.bind(this)),this.namespaces=new Map,this.namespaceCounter=0,this.namespaceStack=[],this.diagramId=``,this.direction=`TB`,c()}getClass(e){return this.classes.get(e)}getClasses(){return this.classes}getRelations(){return this.relations}getNote(e){let t=typeof e==`number`?`note${e}`:e;return this.notes.get(t)}getNotes(){return this.notes}addRelation(e){t.debug(`Adding relation: `+JSON.stringify(e));let n=[this.relationType.LOLLIPOP,this.relationType.AGGREGATION,this.relationType.COMPOSITION,this.relationType.DEPENDENCY,this.relationType.EXTENSION];e.relation.type1===this.relationType.LOLLIPOP&&!n.includes(e.relation.type2)?(this.addClass(e.id2),this.addInterface(e.id1,e.id2),e.id1=`interface${this.interfaces.length-1}`):e.relation.type2===this.relationType.LOLLIPOP&&!n.includes(e.relation.type1)?(this.addClass(e.id1),this.addInterface(e.id2,e.id1),e.id2=`interface${this.interfaces.length-1}`):(this.addClass(e.id1),this.addClass(e.id2)),e.id1=this.splitClassNameAndType(e.id1).className,e.id2=this.splitClassNameAndType(e.id2).className,e.relationTitle1=l.sanitizeText(e.relationTitle1.trim(),f()),e.relationTitle2=l.sanitizeText(e.relationTitle2.trim(),f()),this.relations.push(e)}addAnnotation(e,t){let n=this.splitClassNameAndType(e).className;this.classes.get(n).annotations.push(t)}addMember(e,t){this.addClass(e);let n=this.splitClassNameAndType(e).className,r=this.classes.get(n);if(typeof t==`string`){let e=t.trim();e.startsWith(`<<`)&&e.endsWith(`>>`)?r.annotations.push(k(e.substring(2,e.length-2))):e.indexOf(`)`)>0?r.methods.push(new E(e,`method`)):e&&r.members.push(new E(e,`attribute`))}}addMembers(e,t){Array.isArray(t)&&(t.reverse(),t.forEach(t=>this.addMember(e,t)))}addNote(e,t){let n=this.notes.size,r={id:`note${n}`,class:t,text:e,index:n};return this.notes.set(r.id,r),r.id}cleanupLabel(e){return e.startsWith(`:`)&&(e=e.substring(1)),k(e.trim())}setCssClass(e,t){e.split(`,`).forEach(e=>{let n=e;/\d/.exec(e[0])&&(n=D+n),n=this.splitClassNameAndType(n).className;let r=this.classes.get(n);r&&(r.cssClasses+=` `+t)})}defineClass(e,t){for(let n of e){let e=this.styleClasses.get(n);e===void 0&&(e={id:n,styles:[],textStyles:[]},this.styleClasses.set(n,e)),t&&t.forEach(t=>{if(/color/.exec(t)){let n=t.replace(`fill`,`bgFill`);e.textStyles.push(n)}e.styles.push(t)}),this.classes.forEach(e=>{e.cssClasses.includes(n)&&e.styles.push(...t.flatMap(e=>e.split(`,`)))})}}setTooltip(e,t){e.split(`,`).forEach(e=>{if(t!==void 0){let n=this.splitClassNameAndType(e).className,r=this.classes.get(n);r&&(r.tooltip=k(t))}})}getTooltip(e,t){return t&&this.namespaces.has(t)?this.namespaces.get(t).classes.get(e).tooltip:this.classes.get(e).tooltip}setLink(e,t,n){let r=f();e.split(`,`).forEach(e=>{let i=e;/\d/.exec(e[0])&&(i=D+i),i=this.splitClassNameAndType(i).className;let a=this.classes.get(i);a&&(a.link=g.formatUrl(t,r),r.securityLevel===`sandbox`?a.linkTarget=`_top`:typeof n==`string`?a.linkTarget=k(n):a.linkTarget=`_blank`)}),this.setCssClass(e,`clickable`)}setClickEvent(e,t,n){e.split(`,`).forEach(e=>{this.setClickFunc(e,t,n);let r=this.splitClassNameAndType(e).className,i=this.classes.get(r);i&&(i.haveCallback=!0)}),this.setCssClass(e,`clickable`)}setClickFunc(e,t,n){let r=l.sanitizeText(e,f());if(f().securityLevel!==`loose`||t===void 0)return;let i=this.splitClassNameAndType(r).className;if(this.classes.has(i)){let e=[];if(typeof n==`string`){e=n.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(let t=0;t{let n=this.lookUpDomId(i),r=document.querySelector(`[id="${n}"]`);r!==null&&r.addEventListener(`click`,()=>{g.runFunc(t,...e)},!1)})}}bindFunctions(e){this.functions.forEach(t=>{t(e)})}escapeHtml(e){return e.replace(/&/g,`&`).replace(//g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}getDirection(){return this.direction}setDirection(e){this.direction=e}static resolveQualifiedId(e,t){let n=t.at(-1);return n?`${n}.${e}`:e}static getAncestorIds(e){let t=e.split(`.`),n=Array(t.length);n[0]=t[0];for(let e=1;e0?i[e-1]:void 0,o=e===i.length-1,s=o&&t?t:r[e];this.namespaces.has(n)?o&&(this.namespaces.get(n).explicit=!0):this.namespaces.set(n,this.createNamespaceNode(n,s,a,o)),a&&this.linkParentChild(a,n)}return n}popNamespace(){this.namespaceStack.pop()}getNamespace(e){return this.namespaces.get(e)}getNamespaces(){return this.namespaces}addClassesToNamespace(e,t,n){if(this.namespaces.has(e)){for(let n of t){let{className:t}=this.splitClassNameAndType(n),r=this.getClass(t);r.parent=e,this.namespaces.get(e).classes.set(t,r)}for(let t of n){let n=this.getNote(t);n.parent=e,this.namespaces.get(e).notes.set(t,n)}}}setCssStyle(e,t){let n=this.classes.get(e);if(!(!t||!n))for(let e of t)e.includes(`,`)?n.styles.push(...e.split(`,`)):n.styles.push(e)}getArrowMarker(e){let t;switch(e){case 0:t=`aggregation`;break;case 1:t=`extension`;break;case 2:t=`composition`;break;case 3:t=`dependency`;break;case 4:t=`lollipop`;break;default:t=`none`}return t}resolveExplicitAncestor(e){let t=e;for(;t;){let e=this.namespaces.get(t);if(!e)return;if(e.explicit)return t;t=e.parent}}getData(){let e=[],t=[],n=f(),r=n.class?.hierarchicalNamespaces??!0;for(let t of this.namespaces.values()){if(!r&&!t.explicit)continue;let i={id:t.id,label:r?t.label:t.id,isGroup:!0,padding:n.class.padding??16,shape:`rect`,cssStyles:[],look:n.look,parentId:r?t.parent:void 0};e.push(i)}for(let t of this.classes.values()){let i=r?t.parent:this.resolveExplicitAncestor(t.parent),a={...t,type:void 0,isGroup:!1,parentId:i,look:n.look};e.push(a)}for(let i of this.notes.values()){let a=r?i.parent:this.resolveExplicitAncestor(i.parent),o={id:i.id,label:i.text,isGroup:!1,shape:`note`,padding:n.class.padding??6,cssStyles:[`text-align: left`,`white-space: nowrap`,`fill: ${n.themeVariables.noteBkgColor}`,`stroke: ${n.themeVariables.noteBorderColor}`],look:n.look,parentId:a,labelType:`markdown`};e.push(o);let s=this.classes.get(i.class)?.id;if(s){let e={id:`edgeNote${i.index}`,start:i.id,end:s,type:`normal`,thickness:`normal`,classes:`relation`,arrowTypeStart:`none`,arrowTypeEnd:`none`,arrowheadStyle:``,labelStyle:[``],style:[`fill: none`],pattern:`dotted`,look:n.look};t.push(e)}}for(let t of this.interfaces){let r={id:t.id,label:t.label,isGroup:!1,shape:`rect`,cssStyles:[`opacity: 0;`],look:n.look};e.push(r)}let i=0;for(let e of this.relations){i++;let r={id:h(e.id1,e.id2,{prefix:`id`,counter:i}),start:e.id1,end:e.id2,type:`normal`,label:e.title,labelpos:`c`,thickness:`normal`,classes:`relation`,arrowTypeStart:this.getArrowMarker(e.relation.type1),arrowTypeEnd:this.getArrowMarker(e.relation.type2),startLabelRight:e.relationTitle1===`none`?``:e.relationTitle1,endLabelLeft:e.relationTitle2===`none`?``:e.relationTitle2,arrowheadStyle:``,labelStyle:[`display: inline-block`],style:e.style||``,pattern:e.relation.lineType==1?`dashed`:`solid`,look:n.look,labelType:`markdown`};t.push(r)}return{nodes:e,edges:t,other:{},config:n,direction:this.getDirection()}}},j=e(e=>`g.classGroup text { + fill: ${e.nodeBorder||e.classText}; + stroke: none; + font-family: ${e.fontFamily}; + font-size: 10px; + + .title { + font-weight: bolder; + } + +} + + .cluster-label text { + fill: ${e.titleColor}; + } + .cluster-label span { + color: ${e.titleColor}; + } + .cluster-label span p { + background-color: transparent; + } + + .cluster rect { + fill: ${e.clusterBkg}; + stroke: ${e.clusterBorder}; + stroke-width: 1px; + } + + .cluster text { + fill: ${e.titleColor}; + } + + .cluster span { + color: ${e.titleColor}; + } + +.nodeLabel, .edgeLabel { + color: ${e.classText}; +} + +.noteLabel .nodeLabel, .noteLabel .edgeLabel { + color: ${e.noteTextColor}; +} +.edgeLabel .label rect { + fill: ${e.mainBkg}; +} +.label text { + fill: ${e.classText}; +} + +.labelBkg { + background: ${e.mainBkg}; +} +.edgeLabel .label span { + background: ${e.mainBkg}; +} + +.classTitle { + font-weight: bolder; +} +.node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; + stroke-width: ${e.strokeWidth}; + } + + +.divider { + stroke: ${e.nodeBorder}; + stroke-width: 1; +} + +g.clickable { + cursor: pointer; +} + +g.classGroup rect { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; +} + +g.classGroup line { + stroke: ${e.nodeBorder}; + stroke-width: 1; +} + +.classLabel .box { + stroke: none; + stroke-width: 0; + fill: ${e.mainBkg}; + opacity: 0.5; +} + +.classLabel .label { + fill: ${e.nodeBorder}; + font-size: 10px; +} + +.relation { + stroke: ${e.lineColor}; + stroke-width: ${e.strokeWidth}; + fill: none; +} + +.dashed-line{ + stroke-dasharray: 3; +} + +.dotted-line{ + stroke-dasharray: 1 2; +} + +[id$="-compositionStart"], .composition { + fill: ${e.lineColor} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +[id$="-compositionEnd"], .composition { + fill: ${e.lineColor} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +[id$="-dependencyStart"], .dependency { + fill: ${e.lineColor} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +[id$="-dependencyEnd"], .dependency { + fill: ${e.lineColor} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +[id$="-extensionStart"], .extension { + fill: transparent !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +[id$="-extensionEnd"], .extension { + fill: transparent !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +[id$="-aggregationStart"], .aggregation { + fill: transparent !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +[id$="-aggregationEnd"], .aggregation { + fill: transparent !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +[id$="-lollipopStart"], .lollipop { + fill: ${e.mainBkg} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +[id$="-lollipopEnd"], .lollipop { + fill: ${e.mainBkg} !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; +} + +.edgeTerminals { + font-size: 11px; + line-height: initial; +} + +.classTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${e.textColor}; +} + +.edgeLabel[data-look="neo"] { + background-color: ${e.edgeLabelBackground}; + p { + background-color: ${e.edgeLabelBackground}; + } + rect { + opacity: 0.5; + background-color: ${e.edgeLabelBackground}; + fill: ${e.edgeLabelBackground}; + } + text-align: center; +} + ${_()} +`,`getStyles`),M={getClasses:e(function(e,t){return t.db.getClasses()},`getClasses`),draw:e(async function(e,n,r,i){t.info(`REF0:`),t.info(`Drawing class diagram (v3)`,n);let{securityLevel:a,state:o,layout:s}=f();i.db.setDiagramId(n);let c=i.db.getData(),l=y(n,a);c.type=i.type,c.layoutAlgorithm=S(s),c.nodeSpacing=o?.nodeSpacing||50,c.rankSpacing=o?.rankSpacing||50,c.markers=[`aggregation`,`extension`,`composition`,`dependency`,`lollipop`],c.diagramId=n,await x(c,l),g.insertTitle(l,`classDiagramTitleText`,o?.titleTopMargin??25,i.db.getDiagramTitle()),b(l,8,`classDiagram`,o?.useMaxWidth??!0)},`draw`),getDir:e((e,t=`TB`)=>{if(!e.doc)return t;let n=t;for(let t of e.doc)t.stmt===`dir`&&(n=t.value);return n},`getDir`)};export{j as i,w as n,M as r,A as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-VAUOI2AC-AC9pRUsa.js b/dist-desktop/assets/chunk-VAUOI2AC-AC9pRUsa.js new file mode 100644 index 0000000..a0785ba --- /dev/null +++ b/dist-desktop/assets/chunk-VAUOI2AC-AC9pRUsa.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{x as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var r=e(e=>{let{securityLevel:r}=n(),i=t(`body`);return r===`sandbox`&&(i=t((t(`#i${e}`).node()?.contentDocument??document).body)),i.select(`#${e}`)},`selectSvgElement`);export{r as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-VR4S4FIN-BTo4eV3J.js b/dist-desktop/assets/chunk-VR4S4FIN-BTo4eV3J.js new file mode 100644 index 0000000..6e01b65 --- /dev/null +++ b/dist-desktop/assets/chunk-VR4S4FIN-BTo4eV3J.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{c as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var r=e((e,r,o,s)=>{e.attr(`class`,o);let{width:c,height:l,x:u,y:d}=i(e,r);n(e,l,c,s);let f=a(u,d,c,l,r);e.attr(`viewBox`,f),t.debug(`viewBox configured: ${f} with padding: ${r}`)},`setupViewPortForSVG`),i=e((e,t)=>{let n=e.node()?.getBBox()||{width:0,height:0,x:0,y:0};return{width:n.width+t*2,height:n.height+t*2,x:n.x,y:n.y}},`calculateDimensionsWithPadding`),a=e((e,t,n,r,i)=>`${e-i} ${t-i} ${n} ${r}`,`createViewBox`);export{r as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-WYO6CB5R-Dv5kDyQC.js b/dist-desktop/assets/chunk-WYO6CB5R-Dv5kDyQC.js new file mode 100644 index 0000000..2c2ab99 --- /dev/null +++ b/dist-desktop/assets/chunk-WYO6CB5R-Dv5kDyQC.js @@ -0,0 +1,127 @@ +import{t as e}from"./index-CXgd9jpl.js";import{n as t,t as n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{h as r,m as i}from"./src-UMNXGZaF.js";var a={min:{r:0,g:0,b:0,s:0,l:0,a:0},max:{r:255,g:255,b:255,h:360,s:100,l:100,a:1},clamp:{r:e=>e>=255?255:e<0?0:e,g:e=>e>=255?255:e<0?0:e,b:e=>e>=255?255:e<0?0:e,h:e=>e%360,s:e=>e>=100?100:e<0?0:e,l:e=>e>=100?100:e<0?0:e,a:e=>e>=1?1:e<0?0:e},toLinear:e=>{let t=e/255;return e>.03928?((t+.055)/1.055)**2.4:t/12.92},hue2rgb:(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e),hsl2rgb:({h:e,s:t,l:n},r)=>{if(!t)return n*2.55;e/=360,t/=100,n/=100;let i=n<.5?n*(1+t):n+t-n*t,o=2*n-i;switch(r){case`r`:return a.hue2rgb(o,i,e+1/3)*255;case`g`:return a.hue2rgb(o,i,e)*255;case`b`:return a.hue2rgb(o,i,e-1/3)*255}},rgb2hsl:({r:e,g:t,b:n},r)=>{e/=255,t/=255,n/=255;let i=Math.max(e,t,n),a=Math.min(e,t,n),o=(i+a)/2;if(r===`l`)return o*100;if(i===a)return 0;let s=i-a,c=o>.5?s/(2-i-a):s/(i+a);if(r===`s`)return c*100;switch(i){case e:return((t-n)/s+(tt>n?Math.min(t,Math.max(n,e)):Math.min(n,Math.max(t,e)),round:e=>Math.round(e*1e10)/1e10},unit:{dec2hex:e=>{let t=Math.round(e).toString(16);return t.length>1?t:`0${t}`}}},s={};for(let e=0;e<=255;e++)s[e]=o.unit.dec2hex(e);var c={ALL:0,RGB:1,HSL:2},l=class{constructor(){this.type=c.ALL}get(){return this.type}set(e){if(this.type&&this.type!==e)throw Error(`Cannot change both RGB and HSL channels at the same time`);this.type=e}reset(){this.type=c.ALL}is(e){return this.type===e}},u=new class{constructor(e,t){this.color=t,this.changed=!1,this.data=e,this.type=new l}set(e,t){return this.color=t,this.changed=!1,this.data=e,this.type.type=c.ALL,this}_ensureHSL(){let e=this.data,{h:t,s:n,l:r}=e;t===void 0&&(e.h=o.channel.rgb2hsl(e,`h`)),n===void 0&&(e.s=o.channel.rgb2hsl(e,`s`)),r===void 0&&(e.l=o.channel.rgb2hsl(e,`l`))}_ensureRGB(){let e=this.data,{r:t,g:n,b:r}=e;t===void 0&&(e.r=o.channel.hsl2rgb(e,`r`)),n===void 0&&(e.g=o.channel.hsl2rgb(e,`g`)),r===void 0&&(e.b=o.channel.hsl2rgb(e,`b`))}get r(){let e=this.data,t=e.r;return!this.type.is(c.HSL)&&t!==void 0?t:(this._ensureHSL(),o.channel.hsl2rgb(e,`r`))}get g(){let e=this.data,t=e.g;return!this.type.is(c.HSL)&&t!==void 0?t:(this._ensureHSL(),o.channel.hsl2rgb(e,`g`))}get b(){let e=this.data,t=e.b;return!this.type.is(c.HSL)&&t!==void 0?t:(this._ensureHSL(),o.channel.hsl2rgb(e,`b`))}get h(){let e=this.data,t=e.h;return!this.type.is(c.RGB)&&t!==void 0?t:(this._ensureRGB(),o.channel.rgb2hsl(e,`h`))}get s(){let e=this.data,t=e.s;return!this.type.is(c.RGB)&&t!==void 0?t:(this._ensureRGB(),o.channel.rgb2hsl(e,`s`))}get l(){let e=this.data,t=e.l;return!this.type.is(c.RGB)&&t!==void 0?t:(this._ensureRGB(),o.channel.rgb2hsl(e,`l`))}get a(){return this.data.a}set r(e){this.type.set(c.RGB),this.changed=!0,this.data.r=e}set g(e){this.type.set(c.RGB),this.changed=!0,this.data.g=e}set b(e){this.type.set(c.RGB),this.changed=!0,this.data.b=e}set h(e){this.type.set(c.HSL),this.changed=!0,this.data.h=e}set s(e){this.type.set(c.HSL),this.changed=!0,this.data.s=e}set l(e){this.type.set(c.HSL),this.changed=!0,this.data.l=e}set a(e){this.changed=!0,this.data.a=e}}({r:0,g:0,b:0,a:0},`transparent`),d={re:/^#((?:[a-f0-9]{2}){2,4}|[a-f0-9]{3})$/i,parse:e=>{if(e.charCodeAt(0)!==35)return;let t=e.match(d.re);if(!t)return;let n=t[1],r=parseInt(n,16),i=n.length,a=i%4==0,o=i>4,s=o?1:17,c=o?8:4,l=a?0:-1,f=o?255:15;return u.set({r:(r>>c*(l+3)&f)*s,g:(r>>c*(l+2)&f)*s,b:(r>>c*(l+1)&f)*s,a:a?(r&f)*s/255:1},e)},stringify:e=>{let{r:t,g:n,b:r,a:i}=e;return i<1?`#${s[Math.round(t)]}${s[Math.round(n)]}${s[Math.round(r)]}${s[Math.round(i*255)]}`:`#${s[Math.round(t)]}${s[Math.round(n)]}${s[Math.round(r)]}`}},f={re:/^hsla?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(?:deg|grad|rad|turn)?)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(%)?))?\s*?\)$/i,hueRe:/^(.+?)(deg|grad|rad|turn)$/i,_hue2deg:e=>{let t=e.match(f.hueRe);if(t){let[,e,n]=t;switch(n){case`grad`:return o.channel.clamp.h(parseFloat(e)*.9);case`rad`:return o.channel.clamp.h(parseFloat(e)*180/Math.PI);case`turn`:return o.channel.clamp.h(parseFloat(e)*360)}}return o.channel.clamp.h(parseFloat(e))},parse:e=>{let t=e.charCodeAt(0);if(t!==104&&t!==72)return;let n=e.match(f.re);if(!n)return;let[,r,i,a,s,c]=n;return u.set({h:f._hue2deg(r),s:o.channel.clamp.s(parseFloat(i)),l:o.channel.clamp.l(parseFloat(a)),a:s?o.channel.clamp.a(c?parseFloat(s)/100:parseFloat(s)):1},e)},stringify:e=>{let{h:t,s:n,l:r,a:i}=e;return i<1?`hsla(${o.lang.round(t)}, ${o.lang.round(n)}%, ${o.lang.round(r)}%, ${i})`:`hsl(${o.lang.round(t)}, ${o.lang.round(n)}%, ${o.lang.round(r)}%)`}},p={colors:{aliceblue:`#f0f8ff`,antiquewhite:`#faebd7`,aqua:`#00ffff`,aquamarine:`#7fffd4`,azure:`#f0ffff`,beige:`#f5f5dc`,bisque:`#ffe4c4`,black:`#000000`,blanchedalmond:`#ffebcd`,blue:`#0000ff`,blueviolet:`#8a2be2`,brown:`#a52a2a`,burlywood:`#deb887`,cadetblue:`#5f9ea0`,chartreuse:`#7fff00`,chocolate:`#d2691e`,coral:`#ff7f50`,cornflowerblue:`#6495ed`,cornsilk:`#fff8dc`,crimson:`#dc143c`,cyanaqua:`#00ffff`,darkblue:`#00008b`,darkcyan:`#008b8b`,darkgoldenrod:`#b8860b`,darkgray:`#a9a9a9`,darkgreen:`#006400`,darkgrey:`#a9a9a9`,darkkhaki:`#bdb76b`,darkmagenta:`#8b008b`,darkolivegreen:`#556b2f`,darkorange:`#ff8c00`,darkorchid:`#9932cc`,darkred:`#8b0000`,darksalmon:`#e9967a`,darkseagreen:`#8fbc8f`,darkslateblue:`#483d8b`,darkslategray:`#2f4f4f`,darkslategrey:`#2f4f4f`,darkturquoise:`#00ced1`,darkviolet:`#9400d3`,deeppink:`#ff1493`,deepskyblue:`#00bfff`,dimgray:`#696969`,dimgrey:`#696969`,dodgerblue:`#1e90ff`,firebrick:`#b22222`,floralwhite:`#fffaf0`,forestgreen:`#228b22`,fuchsia:`#ff00ff`,gainsboro:`#dcdcdc`,ghostwhite:`#f8f8ff`,gold:`#ffd700`,goldenrod:`#daa520`,gray:`#808080`,green:`#008000`,greenyellow:`#adff2f`,grey:`#808080`,honeydew:`#f0fff0`,hotpink:`#ff69b4`,indianred:`#cd5c5c`,indigo:`#4b0082`,ivory:`#fffff0`,khaki:`#f0e68c`,lavender:`#e6e6fa`,lavenderblush:`#fff0f5`,lawngreen:`#7cfc00`,lemonchiffon:`#fffacd`,lightblue:`#add8e6`,lightcoral:`#f08080`,lightcyan:`#e0ffff`,lightgoldenrodyellow:`#fafad2`,lightgray:`#d3d3d3`,lightgreen:`#90ee90`,lightgrey:`#d3d3d3`,lightpink:`#ffb6c1`,lightsalmon:`#ffa07a`,lightseagreen:`#20b2aa`,lightskyblue:`#87cefa`,lightslategray:`#778899`,lightslategrey:`#778899`,lightsteelblue:`#b0c4de`,lightyellow:`#ffffe0`,lime:`#00ff00`,limegreen:`#32cd32`,linen:`#faf0e6`,magenta:`#ff00ff`,maroon:`#800000`,mediumaquamarine:`#66cdaa`,mediumblue:`#0000cd`,mediumorchid:`#ba55d3`,mediumpurple:`#9370db`,mediumseagreen:`#3cb371`,mediumslateblue:`#7b68ee`,mediumspringgreen:`#00fa9a`,mediumturquoise:`#48d1cc`,mediumvioletred:`#c71585`,midnightblue:`#191970`,mintcream:`#f5fffa`,mistyrose:`#ffe4e1`,moccasin:`#ffe4b5`,navajowhite:`#ffdead`,navy:`#000080`,oldlace:`#fdf5e6`,olive:`#808000`,olivedrab:`#6b8e23`,orange:`#ffa500`,orangered:`#ff4500`,orchid:`#da70d6`,palegoldenrod:`#eee8aa`,palegreen:`#98fb98`,paleturquoise:`#afeeee`,palevioletred:`#db7093`,papayawhip:`#ffefd5`,peachpuff:`#ffdab9`,peru:`#cd853f`,pink:`#ffc0cb`,plum:`#dda0dd`,powderblue:`#b0e0e6`,purple:`#800080`,rebeccapurple:`#663399`,red:`#ff0000`,rosybrown:`#bc8f8f`,royalblue:`#4169e1`,saddlebrown:`#8b4513`,salmon:`#fa8072`,sandybrown:`#f4a460`,seagreen:`#2e8b57`,seashell:`#fff5ee`,sienna:`#a0522d`,silver:`#c0c0c0`,skyblue:`#87ceeb`,slateblue:`#6a5acd`,slategray:`#708090`,slategrey:`#708090`,snow:`#fffafa`,springgreen:`#00ff7f`,tan:`#d2b48c`,teal:`#008080`,thistle:`#d8bfd8`,transparent:`#00000000`,turquoise:`#40e0d0`,violet:`#ee82ee`,wheat:`#f5deb3`,white:`#ffffff`,whitesmoke:`#f5f5f5`,yellow:`#ffff00`,yellowgreen:`#9acd32`},parse:e=>{e=e.toLowerCase();let t=p.colors[e];if(t)return d.parse(t)},stringify:e=>{let t=d.stringify(e);for(let e in p.colors)if(p.colors[e]===t)return e}},m={re:/^rgba?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?)))?\s*?\)$/i,parse:e=>{let t=e.charCodeAt(0);if(t!==114&&t!==82)return;let n=e.match(m.re);if(!n)return;let[,r,i,a,s,c,l,d,f]=n;return u.set({r:o.channel.clamp.r(i?parseFloat(r)*2.55:parseFloat(r)),g:o.channel.clamp.g(s?parseFloat(a)*2.55:parseFloat(a)),b:o.channel.clamp.b(l?parseFloat(c)*2.55:parseFloat(c)),a:d?o.channel.clamp.a(f?parseFloat(d)/100:parseFloat(d)):1},e)},stringify:e=>{let{r:t,g:n,b:r,a:i}=e;return i<1?`rgba(${o.lang.round(t)}, ${o.lang.round(n)}, ${o.lang.round(r)}, ${o.lang.round(i)})`:`rgb(${o.lang.round(t)}, ${o.lang.round(n)}, ${o.lang.round(r)})`}},h={format:{keyword:p,hex:d,rgb:m,rgba:m,hsl:f,hsla:f},parse:e=>{if(typeof e!=`string`)return e;let t=d.parse(e)||m.parse(e)||f.parse(e)||p.parse(e);if(t)return t;throw Error(`Unsupported color format: "${e}"`)},stringify:e=>!e.changed&&e.color?e.color:e.type.is(c.HSL)||e.data.r===void 0?f.stringify(e):e.a<1||!Number.isInteger(e.r)||!Number.isInteger(e.g)||!Number.isInteger(e.b)?m.stringify(e):d.stringify(e)},g=(e,t)=>{let n=h.parse(e);for(let e in t)n[e]=o.channel.clamp[e](t[e]);return h.stringify(n)},_=(e,t,n=0,r=1)=>{if(typeof e!=`number`)return g(e,{a:t});let i=u.set({r:o.channel.clamp.r(e),g:o.channel.clamp.g(t),b:o.channel.clamp.b(n),a:o.channel.clamp.a(r)});return h.stringify(i)},ee=e=>{let{r:t,g:n,b:r}=h.parse(e),i=.2126*o.channel.toLinear(t)+.7152*o.channel.toLinear(n)+.0722*o.channel.toLinear(r);return o.lang.round(i)},v=e=>ee(e)>=.5,y=e=>!v(e),b=(e,t,n)=>{let r=h.parse(e),i=r[t],a=o.channel.clamp[t](i+n);return i!==a&&(r[t]=a),h.stringify(r)},x=(e,t)=>b(e,`l`,t),S=(e,t)=>b(e,`l`,-t),C=(e,t)=>{let n=h.parse(e),r={};for(let e in t)t[e]&&(r[e]=n[e]+t[e]);return g(e,r)},te=(e,t,n=50)=>{let{r,g:i,b:a,a:o}=h.parse(e),{r:s,g:c,b:l,a:u}=h.parse(t),d=n/100,f=d*2-1,p=o-u,m=((f*p===-1?f:(f+p)/(1+f*p))+1)/2,g=1-m;return _(r*m+s*g,i*m+c*g,a*m+l*g,o*d+u*(1-d))},w=(e,t=100)=>{let n=h.parse(e);return n.r=255-n.r,n.g=255-n.g,n.b=255-n.b,te(n,e,t)};function ne(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n`u`?null:A(BigInt.prototype.toString),je=typeof Symbol>`u`?null:A(Symbol.prototype.toString),O=A(Object.prototype.hasOwnProperty),Me=A(Object.prototype.toString),k=A(RegExp.prototype.test),Ne=j(TypeError);function A(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return me(e,t,n)}}function j(e){return function(){return he(e,[...arguments])}}function M(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Se;if(le&&le(e,null),!xe(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(ue(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Pe(e){for(let t=0;t/g),Xe=D(/\${[\w\W]*/g),Ze=D(/^data-[\-\w.\u00B7-\uFFFF]+$/),Qe=D(/^aria-[\-\w]+$/),$e=D(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),et=D(/^(?:\w+script|data):/i),tt=D(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),nt=D(/^html$/i),rt=D(/^[a-z][.\w]*(-[.\w]+)+$/i),it=D(/<[/\w!]/g),at=D(/<[/\w]/g),ot=D(/<\/no(script|embed|frames)/i),st=D(/\/>/i),F={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},ct=function(){return typeof window>`u`?null:window},lt=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},ut=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},dt=function(e,t,n,r){return O(e,t)&&xe(e[t])?M(r.base?N(r.base):{},e[t],r.transform):n};function ft(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ct(),t=e=>ft(e);if(t.version=`3.4.12`,t.removed=[],!e||!e.document||e.document.nodeType!==F.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,o=e.Node,s=e.Element,c=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let l=e.DOMParser,u=e.trustedTypes,d=s.prototype,f=P(d,`cloneNode`),p=P(d,`remove`),m=P(d,`nextSibling`),h=P(d,`childNodes`),g=P(d,`parentNode`),_=P(d,`shadowRoot`),ee=P(d,`attributes`),v=o&&o.prototype?P(o.prototype,`nodeType`):null,y=o&&o.prototype?P(o.prototype,`nodeName`):null;if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let b,x=``,S,C=!1,te=0,w=function(){if(te>0)throw Ne(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},ne=function(e){w(),te++;try{return b.createHTML(e)}finally{te--}},re=function(e){w(),te++;try{return b.createScriptURL(e)}finally{te--}},ie=function(){return C||=(S=lt(u,i),!0),S},ae=n,oe=ae.implementation,se=ae.createNodeIterator,le=ae.createDocumentFragment,ue=ae.getElementsByTagName,de=r.importNode,T=ut();t.isSupported=typeof ce==`function`&&typeof g==`function`&&oe&&oe.createHTMLDocument!==void 0;let pe=Je,me=Ye,he=Xe,Oe=Ze,ke=Qe,Ae=et,je=tt,Me=rt,A=$e,j=null,Pe=M({},[...Le,...Re,...ze,...Ve,...Ue]),I=null,pt=M({},[...We,...Ge,...Ke,...qe]),L=Object.seal(fe(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),R=null,z=null,B=Object.seal(fe(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),mt=!0,ht=!0,gt=!1,_t=!0,V=!1,H=!0,vt=!1,yt=!1,bt=null,xt=null,St=!1,Ct=!1,wt=!1,Tt=!1,Et=!0,Dt=!1,Ot=`user-content-`,kt=!0,At=!1,jt={},U=null,W=M({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),G=null,Mt=M({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Nt=null,Pt=M({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Ft=`http://www.w3.org/1998/Math/MathML`,It=`http://www.w3.org/2000/svg`,K=`http://www.w3.org/1999/xhtml`,q=K,Lt=!1,Rt=null,zt=M({},[Ft,It,K],Ce),J=E([`mi`,`mo`,`mn`,`ms`,`mtext`]),Bt=M({},J),Y=E([`annotation-xml`]),Vt=M({},Y),Ht=M({},[`title`,`style`,`font`,`a`,`script`]),Ut=null,Wt=[`application/xhtml+xml`,`text/html`],X=null,Gt=null,Kt=n.createElement(`form`),qt=function(e){return e instanceof RegExp||e instanceof Function},Jt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Gt&&Gt===e)return;(!e||typeof e!=`object`)&&(e={}),e=N(e),Ut=Wt.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,X=Ut===`application/xhtml+xml`?Ce:Se,j=dt(e,`ALLOWED_TAGS`,Pe,{transform:X}),I=dt(e,`ALLOWED_ATTR`,pt,{transform:X}),Rt=dt(e,`ALLOWED_NAMESPACES`,zt,{transform:Ce}),Nt=dt(e,`ADD_URI_SAFE_ATTR`,Pt,{transform:X,base:Pt}),G=dt(e,`ADD_DATA_URI_TAGS`,Mt,{transform:X,base:Mt}),U=dt(e,`FORBID_CONTENTS`,W,{transform:X}),R=dt(e,`FORBID_TAGS`,N({}),{transform:X}),z=dt(e,`FORBID_ATTR`,N({}),{transform:X}),jt=O(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?N(e.USE_PROFILES):e.USE_PROFILES:!1,mt=e.ALLOW_ARIA_ATTR!==!1,ht=e.ALLOW_DATA_ATTR!==!1,gt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,_t=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,V=e.SAFE_FOR_TEMPLATES||!1,H=e.SAFE_FOR_XML!==!1,vt=e.WHOLE_DOCUMENT||!1,Ct=e.RETURN_DOM||!1,wt=e.RETURN_DOM_FRAGMENT||!1,Tt=e.RETURN_TRUSTED_TYPE||!1,St=e.FORCE_BODY||!1,Et=e.SANITIZE_DOM!==!1,Dt=e.SANITIZE_NAMED_PROPS||!1,kt=e.KEEP_CONTENT!==!1,At=e.IN_PLACE||!1,A=Ie(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:$e,q=typeof e.NAMESPACE==`string`?e.NAMESPACE:K,Bt=O(e,`MATHML_TEXT_INTEGRATION_POINTS`)&&e.MATHML_TEXT_INTEGRATION_POINTS&&typeof e.MATHML_TEXT_INTEGRATION_POINTS==`object`?N(e.MATHML_TEXT_INTEGRATION_POINTS):M({},J),Vt=O(e,`HTML_INTEGRATION_POINTS`)&&e.HTML_INTEGRATION_POINTS&&typeof e.HTML_INTEGRATION_POINTS==`object`?N(e.HTML_INTEGRATION_POINTS):M({},Y);let t=O(e,`CUSTOM_ELEMENT_HANDLING`)&&e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING==`object`?N(e.CUSTOM_ELEMENT_HANDLING):fe(null);if(L=fe(null),O(t,`tagNameCheck`)&&qt(t.tagNameCheck)&&(L.tagNameCheck=t.tagNameCheck),O(t,`attributeNameCheck`)&&qt(t.attributeNameCheck)&&(L.attributeNameCheck=t.attributeNameCheck),O(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(L.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),D(L),V&&(ht=!1),wt&&(Ct=!0),jt&&(j=M({},Ue),I=fe(null),jt.html===!0&&(M(j,Le),M(I,We)),jt.svg===!0&&(M(j,Re),M(I,Ge),M(I,qe)),jt.svgFilters===!0&&(M(j,ze),M(I,Ge),M(I,qe)),jt.mathMl===!0&&(M(j,Ve),M(I,Ke),M(I,qe))),B.tagCheck=null,B.attributeCheck=null,O(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?B.tagCheck=e.ADD_TAGS:xe(e.ADD_TAGS)&&(j===Pe&&(j=N(j)),M(j,e.ADD_TAGS,X))),O(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?B.attributeCheck=e.ADD_ATTR:xe(e.ADD_ATTR)&&(I===pt&&(I=N(I)),M(I,e.ADD_ATTR,X))),O(e,`ADD_URI_SAFE_ATTR`)&&xe(e.ADD_URI_SAFE_ATTR)&&M(Nt,e.ADD_URI_SAFE_ATTR,X),O(e,`FORBID_CONTENTS`)&&xe(e.FORBID_CONTENTS)&&(U===W&&(U=N(U)),M(U,e.FORBID_CONTENTS,X)),O(e,`ADD_FORBID_CONTENTS`)&&xe(e.ADD_FORBID_CONTENTS)&&(U===W&&(U=N(U)),M(U,e.ADD_FORBID_CONTENTS,X)),kt&&(j[`#text`]=!0),vt&&M(j,[`html`,`head`,`body`]),j.table&&(M(j,[`tbody`]),delete R.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw Ne(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw Ne(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=b;b=e.TRUSTED_TYPES_POLICY;try{x=ne(``)}catch(e){throw b=t,e}}else e.TRUSTED_TYPES_POLICY===null?(b=void 0,x=``):(b===void 0&&(b=ie()),b&&typeof x==`string`&&(x=ne(``)));E&&E(e),Gt=e},Yt=M({},[...Re,...ze,...Be]),Xt=M({},[...Ve,...He]),Zt=function(e,t,n){return t.namespaceURI===K?e===`svg`:t.namespaceURI===Ft?e===`svg`&&(n===`annotation-xml`||Bt[n]):!!Yt[e]},Qt=function(e,t,n){return t.namespaceURI===K?e===`math`:t.namespaceURI===It?e===`math`&&Vt[n]:!!Xt[e]},$t=function(e,t,n){return t.namespaceURI===It&&!Vt[n]||t.namespaceURI===Ft&&!Bt[n]?!1:!Xt[e]&&(Ht[e]||!Yt[e])},en=function(e){let t=g(e);(!t||!t.tagName)&&(t={namespaceURI:q,tagName:`template`});let n=Se(e.tagName),r=Se(t.tagName);return Rt[e.namespaceURI]?e.namespaceURI===It?Zt(n,t,r):e.namespaceURI===Ft?Qt(n,t,r):e.namespaceURI===K?$t(n,t,r):!!(Ut===`application/xhtml+xml`&&Rt[e.namespaceURI]):!1},tn=function(e){ye(t.removed,{element:e});try{g(e).removeChild(e)}catch{if(p(e),!g(e))throw Ne(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},nn=function(e){an(e);let t=h(e);if(t){let e=[];ge(t,t=>{ye(e,t)}),ge(e,e=>{try{p(e)}catch{}})}let n=ee(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;if(typeof i==`string`)try{e.removeAttribute(i)}catch{}}},Z=function(e,n){try{ye(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{ye(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(Ct||wt)try{tn(n)}catch{}else try{n.setAttribute(e,``)}catch{}},rn=function(e){let t=ee(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;if(!(typeof i!=`string`||I[X(i)]))try{e.removeAttribute(i)}catch{}}},an=function(e){let t=[e];for(;t.length>0;){let e=t.pop();(v?v(e):e.nodeType)===F.element&&rn(e);let n=h(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},on=function(e){if(!H)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=v?v(e):e.nodeType;if(n===F.processingInstruction||n===F.comment&&k(at,e.data)){try{p(e)}catch{}continue}if(n===F.element){let t=e,n=X(y?y(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&n!==`label`&&n!==`output`&&t.removeAttribute(`for`)}catch{}}let r=h(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},sn=function(e){let t=null,r=null;if(St)e=``+e;else{let t=we(e,/^[\r\n\t ]+/);r=t&&t[0]}Ut===`application/xhtml+xml`&&q===K&&(e=``+e+``);let i=b?ne(e):e;if(q===K)try{t=new l().parseFromString(i,Ut)}catch{}if(!t||!t.documentElement){t=oe.createDocument(q,`template`,null);try{t.documentElement.innerHTML=Lt?x:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),q===K?ue.call(t,vt?`html`:`body`)[0]:vt?t.documentElement:a},cn=function(e){return se.call(e.ownerDocument||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},ln=function(e){return e=Te(e,pe,` `),e=Te(e,me,` `),e=Te(e,he,` `),e},un=function(e){e.normalize();let t=se.call(e.ownerDocument||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),n=t.nextNode();for(;n;)n.data=ln(n.data),n=t.nextNode();let r=e.querySelectorAll?.call(e,`template`);r&&ge(r,e=>{Q(e.content)&&un(e.content)})},dn=function(e){let t=y?y(e):null;return typeof t!=`string`||X(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==ee(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==v(e)||e.childNodes!==h(e)},Q=function(e){if(!v||typeof e!=`object`||!e)return!1;try{return v(e)===F.documentFragment}catch{return!1}},fn=function(e){if(!v||typeof e!=`object`||!e)return!1;try{return typeof v(e)==`number`}catch{return!1}};function $(e,n,r){e.length!==0&&ge(e,e=>{e.call(t,n,r,Gt)})}let pn=function(e,t){return!!(H&&e.hasChildNodes()&&!fn(e.firstElementChild)&&k(it,e.textContent)&&k(it,e.innerHTML)||H&&e.namespaceURI===K&&t===`style`&&fn(e.firstElementChild)||e.nodeType===F.processingInstruction||H&&e.nodeType===F.comment&&k(at,e.data))},mn=function(e,t){if(!R[t]&&vn(t)&&(L.tagNameCheck instanceof RegExp&&k(L.tagNameCheck,t)||L.tagNameCheck instanceof Function&&L.tagNameCheck(t)))return!1;if(kt&&!U[t]){let t=g(e),n=h(e);if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=At?n[i]:f(n[i],!0);t.insertBefore(r,m(e))}}}return tn(e),!0},hn=function(e,n){if($(T.beforeSanitizeElements,e,null),e!==n&&g(e)===null)return!0;if(dn(e))return tn(e),!0;let r=X(y?y(e):e.nodeName);if($(T.uponSanitizeElement,e,{tagName:r,allowedTags:j}),e!==n&&g(e)===null)return!0;if(pn(e,r))return tn(e),!0;if(R[r]||!(B.tagCheck instanceof Function&&B.tagCheck(r))&&!j[r]){let t=mn(e,r);return t===!1&&$(T.afterSanitizeElements,e,null),t}if((v?v(e):e.nodeType)===F.element&&!en(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&k(ot,e.innerHTML))return tn(e),!0;if(V&&e.nodeType===F.text){let n=ln(e.textContent);e.textContent!==n&&(ye(t.removed,{element:e.cloneNode()}),e.textContent=n)}return $(T.afterSanitizeElements,e,null),!1},gn=function(e,t,r){if(z[t]||H&&t===`patchsrc`||H&&t===`for`&&e!==`label`&&e!==`output`||Et&&(t===`id`||t===`name`)&&(r in n||r in Kt))return!1;let i=I[t]||B.attributeCheck instanceof Function&&B.attributeCheck(t,e);if(!(ht&&k(Oe,t))&&!(mt&&k(ke,t))){if(!i){if(!(vn(e)&&(L.tagNameCheck instanceof RegExp&&k(L.tagNameCheck,e)||L.tagNameCheck instanceof Function&&L.tagNameCheck(e))&&(L.attributeNameCheck instanceof RegExp&&k(L.attributeNameCheck,t)||L.attributeNameCheck instanceof Function&&L.attributeNameCheck(t,e))||t===`is`&&L.allowCustomizedBuiltInElements&&(L.tagNameCheck instanceof RegExp&&k(L.tagNameCheck,r)||L.tagNameCheck instanceof Function&&L.tagNameCheck(r))))return!1}else if(!Nt[t]&&!k(A,Te(r,je,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&Ee(r,`data:`)===0&&G[e])&&!(gt&&!k(Ae,Te(r,je,``)))&&r)return!1}return!0},_n=M({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),vn=function(e){return!_n[Se(e)]&&k(Me,e)},yn=function(e,t,n,r){if(b&&typeof u==`object`&&typeof u.getAttributeType==`function`&&!n)switch(u.getAttributeType(e,t)){case`TrustedHTML`:return ne(r);case`TrustedScriptURL`:return re(r)}return r},bn=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),dn(e)?tn(e):ve(t.removed)}catch{Z(n,e)}},xn=function(e){$(T.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||dn(e))return;let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:I,forceKeepAttr:void 0},r=t.length,i=X(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=X(o),u=c,d=o===`value`?u:De(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,$(T.uponSanitizeAttribute,e,n),d=n.attrValue,Dt&&(l===`id`||l===`name`)&&Ee(d,Ot)!==0&&(Z(o,e),d=Ot+d),H&&k(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){Z(o,e);continue}if(l===`attributename`&&we(d,`href`)){Z(o,e);continue}if(!n.forceKeepAttr){if(!n.keepAttr){Z(o,e);continue}if(!_t&&k(st,d)){Z(o,e);continue}if(V&&(d=ln(d)),!gn(i,l,d)){Z(o,e);continue}d=yn(i,l,s,d),d!==u&&bn(e,o,s,d)}}$(T.afterSanitizeAttributes,e,null)},Sn=function(e){let t=null,n=cn(e);for($(T.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if($(T.uponSanitizeShadowNode,t,null),hn(t,e),xn(t),Q(t.content)&&Sn(t.content),(v?v(t):t.nodeType)===F.element){let e=_(t);Q(e)&&(Cn(e),Sn(e))}$(T.afterSanitizeShadowDOM,e,null)},Cn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Sn(e.shadow);continue}let n=e.node,r=(v?v(n):n.nodeType)===F.element,i=h(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=y?y(n):null;if(typeof e==`string`&&X(e)===`template`){let e=n.content;Q(e)&&t.push({node:e,shadow:null})}}if(r){let e=_(n);Q(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(Lt=!e,Lt&&(e=``),typeof e!=`string`&&!fn(e)&&(e=Fe(e),typeof e!=`string`))throw Ne(`dirty is not a string, aborting`);if(!t.isSupported)return e;yt?(j=bt,I=xt):Jt(n),(T.uponSanitizeElement.length>0||T.uponSanitizeAttribute.length>0)&&(j=N(j)),T.uponSanitizeAttribute.length>0&&(I=N(I)),t.removed=[];let c=At&&typeof e!=`string`&&fn(e);if(c){on(e);let t=y?y(e):e.nodeName;if(typeof t==`string`){let n=X(t);if(!j[n]||R[n])throw nn(e),Ne(`root node is forbidden and cannot be sanitized in-place`)}if(dn(e))throw nn(e),Ne(`root node is clobbered and cannot be sanitized in-place`);try{Cn(e)}catch(t){throw nn(e),t}}else if(fn(e))i=sn(``),a=i.ownerDocument.importNode(e,!0),a.nodeType===F.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Cn(a);else{if(!Ct&&!V&&!vt&&e.indexOf(`<`)===-1)return b&&Tt?ne(e):e;if(i=sn(e),!i)return Ct?null:Tt?x:``}i&&St&&tn(i.firstChild);let l=c?e:i,u=cn(l);try{for(;o=u.nextNode();)hn(o,l),xn(o),Q(o.content)&&Sn(o.content)}catch(n){throw c&&(nn(e),ge(t.removed,e=>{e.element&&an(e.element)})),n}if(c)return ge(t.removed,e=>{e.element&&an(e.element)}),V&&un(e),e;if(Ct){if(V&&un(i),wt)for(s=le.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(I.shadowroot||I.shadowrootmode)&&(s=de.call(r,s,!0)),s}let d=vt?i.outerHTML:i.innerHTML;return vt&&j[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&k(nt,i.ownerDocument.doctype.name)&&(d=` +`+d),V&&(d=ln(d)),b&&Tt?ne(d):d},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Jt(e),yt=!0,bt=j,xt=I},t.clearConfig=function(){Gt=null,yt=!1,bt=null,xt=null,b=S,x=``},t.isValidAttribute=function(e,t,n){Gt||Jt({});let r=X(e),i=X(t);return gn(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&O(T,e)&&ye(T[e],t)},t.removeHook=function(e,t){if(O(T,e)){if(t!==void 0){let n=_e(T[e],t);return n===-1?void 0:be(T[e],n,1)[0]}return ve(T[e])}},t.removeHooks=function(e){O(T,e)&&(T[e]=[])},t.removeAllHooks=function(){T=ut()},t}var I=ft(),pt=t((e,t,{depth:n=2,clobber:r=!1}={})=>{let i={depth:n,clobber:r};return Array.isArray(t)&&!Array.isArray(e)?(t.forEach(t=>pt(e,t,i)),e):Array.isArray(t)&&Array.isArray(e)?(t.forEach(t=>{e.includes(t)||e.push(t)}),e):e===void 0||n<=0?typeof e==`object`&&e&&typeof t==`object`?Object.assign(e,t):t:(t!==void 0&&typeof e==`object`&&typeof t==`object`&&Object.keys(t).forEach(i=>{typeof t[i]==`object`&&t[i]!==null&&(e[i]===void 0||typeof e[i]==`object`)?(e[i]===void 0&&(e[i]=Array.isArray(t[i])?[]:{}),e[i]=pt(e[i],t[i],{depth:n-1,clobber:r})):(r||typeof e[i]!=`object`&&typeof t[i]!=`object`)&&(e[i]=t[i])}),e)},`assignWithDepth`),L=pt,R=`#ffffff`,z=`#f2f2f2`,B=t((e,t)=>t?C(e,{s:-40,l:10}):C(e,{s:-40,l:-10}),`mkBorder`),mt=class{static{t(this,`Theme`)}constructor(){this.background=`#f4f4f4`,this.primaryColor=`#fff4dd`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#333`,this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.useGradient=!0,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,1))`}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#333`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#333`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||x(this.primaryColor,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.vertLineColor=this.vertLineColor||`navy`,this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.noteFontWeight=this.noteFontWeight||`normal`,this.fontWeight=this.fontWeight||`normal`,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.darkMode?(this.rowOdd=this.rowOdd||S(this.mainBkg,5)||`#ffffff`,this.rowEven=this.rowEven||S(this.mainBkg,10)):(this.rowOdd=this.rowOdd||x(this.mainBkg,75)||`#ffffff`,this.rowEven=this.rowEven||x(this.mainBkg,5)),this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||this.tertiaryColor,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.darkMode)for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},ht=t(e=>{let t=new mt;return t.calculate(e),t},`getThemeVariables`),gt=class{static{t(this,`Theme`)}constructor(){this.background=`#333`,this.primaryColor=`#1f2020`,this.secondaryColor=x(this.primaryColor,16),this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=w(this.background),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.lineColor=w(this.background),this.textColor=w(this.background),this.mainBkg=`#1f2020`,this.secondBkg=`calculated`,this.mainContrastColor=`lightgrey`,this.darkTextColor=x(w(`#323D47`),10),this.lineColor=`calculated`,this.border1=`#ccc`,this.border2=_(255,255,255,.25),this.arrowheadColor=`calculated`,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.labelBackground=`#181818`,this.textColor=`#ccc`,this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg=`calculated`,this.nodeBorder=`calculated`,this.clusterBkg=`calculated`,this.clusterBorder=`calculated`,this.defaultLinkColor=`calculated`,this.titleColor=`#F9FFFE`,this.edgeLabelBackground=`calculated`,this.actorBorder=`calculated`,this.actorBkg=`calculated`,this.actorTextColor=`calculated`,this.actorLineColor=`calculated`,this.signalColor=`calculated`,this.signalTextColor=`calculated`,this.labelBoxBkgColor=`calculated`,this.labelBoxBorderColor=`calculated`,this.labelTextColor=`calculated`,this.loopTextColor=`calculated`,this.noteBorderColor=`calculated`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`calculated`,this.activationBorderColor=`calculated`,this.activationBkgColor=`calculated`,this.sequenceNumberColor=`black`,this.clusterBkg=`#302F3D`,this.sectionBkgColor=S(`#EAE8D9`,30),this.altSectionBkgColor=`calculated`,this.sectionBkgColor2=`#EAE8D9`,this.excludeBkgColor=S(this.sectionBkgColor,10),this.taskBorderColor=_(255,255,255,70),this.taskBkgColor=`calculated`,this.taskTextColor=`calculated`,this.taskTextLightColor=`calculated`,this.taskTextOutsideColor=`calculated`,this.taskTextClickableColor=`#003163`,this.activeTaskBorderColor=_(255,255,255,50),this.activeTaskBkgColor=`#81B1DB`,this.gridColor=`calculated`,this.doneTaskBkgColor=`calculated`,this.doneTaskBorderColor=`grey`,this.critBorderColor=`#E83737`,this.critBkgColor=`#E83737`,this.taskTextDarkColor=`calculated`,this.todayLineColor=`#DB5757`,this.vertLineColor=`#00BFFF`,this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.rowOdd=this.rowOdd||x(this.mainBkg,5)||`#ffffff`,this.rowEven=this.rowEven||S(this.mainBkg,10),this.labelColor=`calculated`,this.errorBkgColor=`#a44141`,this.errorTextColor=`#ddd`,this.useGradient=!0,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,1))`,this.noteFontWeight=this.noteFontWeight||`normal`,this.fontWeight=this.fontWeight||`normal`}updateColors(){this.secondBkg=x(this.mainBkg,16),this.lineColor=this.mainContrastColor,this.arrowheadColor=this.mainContrastColor,this.nodeBkg=this.mainBkg,this.nodeBorder=this.border1,this.clusterBkg=this.secondBkg,this.clusterBorder=this.border2,this.defaultLinkColor=this.lineColor,this.edgeLabelBackground=x(this.labelBackground,25),this.actorBorder=this.border1,this.actorBkg=this.mainBkg,this.actorTextColor=this.mainContrastColor,this.actorLineColor=this.actorBorder,this.signalColor=this.mainContrastColor,this.signalTextColor=this.mainContrastColor,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.mainContrastColor,this.loopTextColor=this.mainContrastColor,this.noteBorderColor=this.secondaryBorderColor,this.noteBkgColor=this.secondBkg,this.noteTextColor=this.secondaryTextColor,this.activationBorderColor=this.border1,this.activationBkgColor=this.secondBkg,this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.background,this.taskBkgColor=x(this.mainBkg,23),this.taskTextColor=this.darkTextColor,this.taskTextLightColor=this.mainContrastColor,this.taskTextOutsideColor=this.taskTextLightColor,this.gridColor=this.mainContrastColor,this.doneTaskBkgColor=this.mainContrastColor,this.taskTextDarkColor=w(this.doneTaskBkgColor),this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#555`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.primaryBorderColor,this.specialStateColor=`#f4f4f4`,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.fillType0=this.primaryColor,this.fillType1=this.secondaryColor,this.fillType2=C(this.primaryColor,{h:64}),this.fillType3=C(this.secondaryColor,{h:64}),this.fillType4=C(this.primaryColor,{h:-64}),this.fillType5=C(this.secondaryColor,{h:-64}),this.fillType6=C(this.primaryColor,{h:128}),this.fillType7=C(this.secondaryColor,{h:128}),this.cScale1=this.cScale1||`#0b0000`,this.cScale2=this.cScale2||`#4d1037`,this.cScale3=this.cScale3||`#3f5258`,this.cScale4=this.cScale4||`#4f2f1b`,this.cScale5=this.cScale5||`#6e0a0a`,this.cScale6=this.cScale6||`#3b0048`,this.cScale7=this.cScale7||`#995a01`,this.cScale8=this.cScale8||`#154706`,this.cScale9=this.cScale9||`#161722`,this.cScale10=this.cScale10||`#00296f`,this.cScale11=this.cScale11||`#01629c`,this.cScale12=this.cScale12||`#010029`,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330});for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},_t=t(e=>{let t=new gt;return t.calculate(e),t},`getThemeVariables`),V=class{static{t(this,`Theme`)}constructor(){this.background=`#f4f4f4`,this.primaryColor=`#ECECFF`,this.secondaryColor=C(this.primaryColor,{h:120}),this.secondaryColor=`#ffffde`,this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.lineColor=w(this.background),this.textColor=w(this.background),this.background=`white`,this.mainBkg=`#ECECFF`,this.secondBkg=`#ffffde`,this.lineColor=`#333333`,this.border1=`#9370DB`,this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.border2=`#aaaa33`,this.arrowheadColor=`#333333`,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.labelBackground=`rgba(232,232,232, 0.8)`,this.textColor=`#333`,this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg=`calculated`,this.nodeBorder=`calculated`,this.clusterBkg=`calculated`,this.clusterBorder=`calculated`,this.defaultLinkColor=`calculated`,this.titleColor=`calculated`,this.edgeLabelBackground=`calculated`,this.actorBorder=`calculated`,this.actorBkg=`calculated`,this.actorTextColor=`black`,this.actorLineColor=`calculated`,this.signalColor=`calculated`,this.signalTextColor=`calculated`,this.labelBoxBkgColor=`calculated`,this.labelBoxBorderColor=`calculated`,this.labelTextColor=`calculated`,this.loopTextColor=`calculated`,this.noteBorderColor=`calculated`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`calculated`,this.activationBorderColor=`#666`,this.activationBkgColor=`#f4f4f4`,this.sequenceNumberColor=`white`,this.clusterBkg=`#FBFBFF`,this.sectionBkgColor=`calculated`,this.altSectionBkgColor=`calculated`,this.sectionBkgColor2=`calculated`,this.excludeBkgColor=`#eeeeee`,this.taskBorderColor=`calculated`,this.taskBkgColor=`calculated`,this.taskTextLightColor=`calculated`,this.taskTextColor=this.taskTextLightColor,this.taskTextDarkColor=`calculated`,this.taskTextOutsideColor=this.taskTextDarkColor,this.taskTextClickableColor=`calculated`,this.activeTaskBorderColor=`calculated`,this.activeTaskBkgColor=`calculated`,this.gridColor=`calculated`,this.doneTaskBkgColor=`calculated`,this.doneTaskBorderColor=`calculated`,this.critBorderColor=`calculated`,this.critBkgColor=`calculated`,this.todayLineColor=`calculated`,this.vertLineColor=`calculated`,this.sectionBkgColor=_(102,102,255,.49),this.altSectionBkgColor=`white`,this.sectionBkgColor2=`#fff400`,this.taskBorderColor=`#534fbc`,this.taskBkgColor=`#8a90dd`,this.taskTextLightColor=`white`,this.taskTextColor=`calculated`,this.taskTextDarkColor=`black`,this.taskTextOutsideColor=`calculated`,this.taskTextClickableColor=`#003163`,this.activeTaskBorderColor=`#534fbc`,this.activeTaskBkgColor=`#bfc7ff`,this.gridColor=`lightgrey`,this.doneTaskBkgColor=`lightgrey`,this.doneTaskBorderColor=`grey`,this.critBorderColor=`#ff8888`,this.critBkgColor=`red`,this.todayLineColor=`red`,this.vertLineColor=`navy`,this.noteFontWeight=this.noteFontWeight||`normal`,this.fontWeight=this.fontWeight||`normal`,this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.rowOdd=`calculated`,this.rowEven=`calculated`,this.labelColor=`black`,this.errorBkgColor=`#552222`,this.errorTextColor=`#552222`,this.useGradient=!1,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow=`drop-shadow(1px 2px 2px rgba(185, 185, 185, 1))`,this.updateColors()}updateColors(){this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.cScalePeer1=this.cScalePeer1||S(this.secondaryColor,45),this.cScalePeer2=this.cScalePeer2||S(this.tertiaryColor,40);for(let e=0;e{this[e]===`calculated`&&(this[e]=void 0)}),typeof e!=`object`){this.updateColors();return}let t=Object.keys(e);t.forEach(t=>{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},H=t(e=>{let t=new V;return t.calculate(e),t},`getThemeVariables`),vt=class{static{t(this,`Theme`)}constructor(){this.background=`#f4f4f4`,this.primaryColor=`#cde498`,this.secondaryColor=`#cdffb2`,this.background=`white`,this.mainBkg=`#cde498`,this.secondBkg=`#cdffb2`,this.lineColor=`green`,this.border1=`#13540c`,this.border2=`#6eaa49`,this.arrowheadColor=`green`,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.tertiaryColor=x(`#cde498`,10),this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.primaryColor),this.lineColor=w(this.background),this.textColor=w(this.background),this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg=`calculated`,this.nodeBorder=`calculated`,this.clusterBkg=`calculated`,this.clusterBorder=`calculated`,this.defaultLinkColor=`calculated`,this.titleColor=`#333`,this.edgeLabelBackground=`#e8e8e8`,this.actorBorder=`calculated`,this.actorBkg=`calculated`,this.actorTextColor=`black`,this.actorLineColor=`calculated`,this.signalColor=`#333`,this.signalTextColor=`#333`,this.labelBoxBkgColor=`calculated`,this.labelBoxBorderColor=`#326932`,this.labelTextColor=`calculated`,this.loopTextColor=`calculated`,this.noteBorderColor=`calculated`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`calculated`,this.activationBorderColor=`#666`,this.activationBkgColor=`#f4f4f4`,this.sequenceNumberColor=`white`,this.sectionBkgColor=`#6eaa49`,this.altSectionBkgColor=`white`,this.sectionBkgColor2=`#6eaa49`,this.excludeBkgColor=`#eeeeee`,this.taskBorderColor=`calculated`,this.taskBkgColor=`#487e3a`,this.taskTextLightColor=`white`,this.taskTextColor=`calculated`,this.taskTextDarkColor=`black`,this.taskTextOutsideColor=`calculated`,this.taskTextClickableColor=`#003163`,this.activeTaskBorderColor=`calculated`,this.activeTaskBkgColor=`calculated`,this.gridColor=`lightgrey`,this.doneTaskBkgColor=`lightgrey`,this.doneTaskBorderColor=`grey`,this.critBorderColor=`#ff8888`,this.critBkgColor=`red`,this.todayLineColor=`red`,this.vertLineColor=`#00BFFF`,this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.noteFontWeight=`normal`,this.fontWeight=`normal`,this.labelColor=`black`,this.errorBkgColor=`#552222`,this.errorTextColor=`#552222`,this.useGradient=!0,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,0.5))`}updateColors(){this.actorBorder=S(this.mainBkg,20),this.actorBkg=this.mainBkg,this.labelBoxBkgColor=this.actorBkg,this.labelTextColor=this.actorTextColor,this.loopTextColor=this.actorTextColor,this.noteBorderColor=this.border2,this.noteTextColor=this.actorTextColor,this.actorLineColor=this.actorBorder,this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.cScalePeer1=this.cScalePeer1||S(this.secondaryColor,45),this.cScalePeer2=this.cScalePeer2||S(this.tertiaryColor,40);for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},yt=t(e=>{let t=new vt;return t.calculate(e),t},`getThemeVariables`),bt=class{static{t(this,`Theme`)}constructor(){this.primaryColor=`#eee`,this.contrast=`#707070`,this.secondaryColor=x(this.contrast,55),this.background=`#ffffff`,this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.lineColor=w(this.background),this.textColor=w(this.background),this.mainBkg=`#eee`,this.secondBkg=`calculated`,this.lineColor=`#666`,this.border1=`#999`,this.border2=`calculated`,this.note=`#ffa`,this.text=`#333`,this.critical=`#d42`,this.done=`#bbb`,this.arrowheadColor=`#333333`,this.fontFamily=`"trebuchet ms", verdana, arial, sans-serif`,this.fontSize=`16px`,this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg=`calculated`,this.nodeBorder=`calculated`,this.clusterBkg=`calculated`,this.clusterBorder=`calculated`,this.defaultLinkColor=`calculated`,this.titleColor=`calculated`,this.edgeLabelBackground=`white`,this.actorBorder=`calculated`,this.actorBkg=`calculated`,this.actorTextColor=`calculated`,this.actorLineColor=this.actorBorder,this.signalColor=`calculated`,this.signalTextColor=`calculated`,this.labelBoxBkgColor=`calculated`,this.labelBoxBorderColor=`calculated`,this.labelTextColor=`calculated`,this.loopTextColor=`calculated`,this.noteBorderColor=`calculated`,this.noteBkgColor=`calculated`,this.noteTextColor=`calculated`,this.activationBorderColor=`#666`,this.activationBkgColor=`#f4f4f4`,this.sequenceNumberColor=`white`,this.sectionBkgColor=`calculated`,this.altSectionBkgColor=`white`,this.sectionBkgColor2=`calculated`,this.excludeBkgColor=`#eeeeee`,this.taskBorderColor=`calculated`,this.taskBkgColor=`calculated`,this.taskTextLightColor=`white`,this.taskTextColor=`calculated`,this.taskTextDarkColor=`calculated`,this.taskTextOutsideColor=`calculated`,this.taskTextClickableColor=`#003163`,this.activeTaskBorderColor=`calculated`,this.activeTaskBkgColor=`calculated`,this.gridColor=`calculated`,this.doneTaskBkgColor=`calculated`,this.doneTaskBorderColor=`calculated`,this.critBkgColor=`calculated`,this.critBorderColor=`calculated`,this.todayLineColor=`calculated`,this.vertLineColor=`calculated`,this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.noteFontWeight=`normal`,this.fontWeight=`normal`,this.rowOdd=this.rowOdd||x(this.mainBkg,75)||`#ffffff`,this.rowEven=this.rowEven||`#f4f4f4`,this.labelColor=`black`,this.errorBkgColor=`#552222`,this.errorTextColor=`#552222`,this.useGradient=!0,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,1))`}updateColors(){this.secondBkg=x(this.contrast,55),this.border2=this.contrast,this.actorBorder=x(this.border1,23),this.actorBkg=this.mainBkg,this.actorTextColor=this.text,this.actorLineColor=this.actorBorder,this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.signalColor=this.text,this.signalTextColor=this.text,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.text,this.loopTextColor=this.text,this.noteBorderColor=`#999`,this.noteBkgColor=`#666`,this.noteTextColor=`#fff`,this.cScale0=this.cScale0||`#555`,this.cScale1=this.cScale1||`#F4F4F4`,this.cScale2=this.cScale2||`#555`,this.cScale3=this.cScale3||`#BBB`,this.cScale4=this.cScale4||`#777`,this.cScale5=this.cScale5||`#999`,this.cScale6=this.cScale6||`#DDD`,this.cScale7=this.cScale7||`#FFF`,this.cScale8=this.cScale8||`#DDD`,this.cScale9=this.cScale9||`#BBB`,this.cScale10=this.cScale10||`#999`,this.cScale11=this.cScale11||`#777`;for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},xt=t(e=>{let t=new bt;return t.calculate(e),t},`getThemeVariables`),St=class{static{t(this,`Theme`)}constructor(){this.background=`#ffffff`,this.primaryColor=`#cccccc`,this.mainBkg=`#ffffff`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#333`,this.THEME_COLOR_LIMIT=12,this.radius=3,this.strokeWidth=2,this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.fontFamily=`arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#000000`,this.stateBorder=`#000000`,this.useGradient=!0,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`drop-shadow( 0px 1px 2px rgba(0, 0, 0, 0.25));`,this.tertiaryColor=`#ffffff`,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.noteFontWeight=`normal`,this.fontWeight=`normal`}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#333`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#333`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor;let e=`#ECECFE`,t=`#E9E9F1`,n=C(e,{h:180,l:5});if(this.sectionBkgColor=this.sectionBkgColor||n,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||t,this.sectionBkgColor2=this.sectionBkgColor2||e,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||e,this.activeTaskBorderColor=this.activeTaskBorderColor||e,this.activeTaskBkgColor=this.activeTaskBkgColor||x(e,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||e,this.cScale1=this.cScale1||t,this.cScale2=this.cScale2||n,this.cScale3=this.cScale3||C(e,{h:30}),this.cScale4=this.cScale4||C(e,{h:60}),this.cScale5=this.cScale5||C(e,{h:90}),this.cScale6=this.cScale6||C(e,{h:120}),this.cScale7=this.cScale7||C(e,{h:150}),this.cScale8=this.cScale8||C(e,{h:210,l:150}),this.cScale9=this.cScale9||C(e,{h:270}),this.cScale10=this.cScale10||C(e,{h:300}),this.cScale11=this.cScale11||C(e,{h:330}),this.darkMode)for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},Ct=t(e=>{let t=new St;return t.calculate(e),t},`getThemeVariables`),wt=class{static{t(this,`Theme`)}constructor(){this.background=`#333`,this.primaryColor=`#1f2020`,this.secondaryColor=x(this.primaryColor,16),this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=w(this.background),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.mainBkg=`#2a2020`,this.secondBkg=`calculated`,this.mainContrastColor=`lightgrey`,this.darkTextColor=x(w(`#323D47`),10),this.border1=`#ccc`,this.border2=_(255,255,255,.25),this.arrowheadColor=w(this.background),this.fontFamily=`arial, sans-serif`,this.fontSize=`14px`,this.labelBackground=`#181818`,this.textColor=`#ccc`,this.THEME_COLOR_LIMIT=12,this.radius=3,this.strokeWidth=1,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#333`,this.THEME_COLOR_LIMIT=12,this.fontFamily=`arial, sans-serif`,this.fontSize=`14px`,this.useGradient=!0,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`drop-shadow( 1px 2px 2px rgba(185,185,185,0.2))`,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.noteFontWeight=`normal`,this.fontWeight=`normal`}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#333`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#333`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.border1,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||x(this.primaryColor,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.darkMode)for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},Tt=t(e=>{let t=new wt;return t.calculate(e),t},`getThemeVariables`),Et=class{static{t(this,`Theme`)}constructor(){this.background=`#ffffff`,this.primaryColor=`#cccccc`,this.mainBkg=`#ffffff`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#28253D`,this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.primaryBorderColor=B(`#28253D`,this.darkMode),this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#28253D`,this.stateBorder=`#28253D`,this.useGradient=!1,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`url(#drop-shadow)`,this.nodeShadow=!0,this.tertiaryColor=`#ffffff`,this.clusterBkg=`#F9F9FB`,this.clusterBorder=`#BDBCCC`,this.noteBorderColor=`#FACC15`,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.actorBorder=`#28253D`,this.filterColor=`#000000`}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#28253D`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#FEF9C3`,this.noteTextColor=this.noteTextColor||`#28253D`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.noteFontWeight=600,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor;let e=`#ECECFE`,t=`#E9E9F1`,n=C(e,{h:180,l:5});this.sectionBkgColor=this.sectionBkgColor||n,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||t,this.sectionBkgColor2=this.sectionBkgColor2||e,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||e,this.activeTaskBorderColor=this.activeTaskBorderColor||e,this.activeTaskBkgColor=this.activeTaskBkgColor||x(e,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.compositeTitleBackground=`#F9F9FB`,this.altBackground=`#F9F9FB`,this.stateEdgeLabelBackground=`#FFFFFF`,this.fontWeight=600,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor;for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},Dt=t(e=>{let t=new Et;return t.calculate(e),t},`getThemeVariables`),Ot=class{static{t(this,`Theme`)}constructor(){this.background=`#333`,this.primaryColor=`#1f2020`,this.secondaryColor=x(this.primaryColor,16),this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=w(this.background),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.mainBkg=`#111113`,this.secondBkg=`calculated`,this.mainContrastColor=`lightgrey`,this.darkTextColor=x(w(`#323D47`),10),this.border1=`#ccc`,this.border2=_(255,255,255,.25),this.arrowheadColor=w(this.background),this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.labelBackground=`#111113`,this.textColor=`#ccc`,this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.noteBkgColor=this.noteBkgColor??`#FEF9C3`,this.noteTextColor=this.noteTextColor??`#28253D`,this.THEME_COLOR_LIMIT=12,this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#FFFFFF`,this.stateBorder=`#FFFFFF`,this.useGradient=!1,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`url(#drop-shadow)`,this.nodeShadow=!0,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.clusterBkg=`#1E1A2E`,this.clusterBorder=`#BDBCCC`,this.noteBorderColor=`#FACC15`,this.noteFontWeight=600,this.filterColor=`#FFFFFF`}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#FFFFFF`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#FFFFFF`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.border1,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=`#FFFFFF`,this.signalColor=`#FFFFFF`,this.labelBoxBorderColor=`#BDBCCC`,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||x(this.primaryColor,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.compositeBackground=`#16141F`,this.altBackground=`#16141F`,this.compositeTitleBackground=`#16141F`,this.stateEdgeLabelBackground=`#16141F`,this.fontWeight=600,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||C(this.primaryColor,{h:30}),this.cScale4=this.cScale4||C(this.primaryColor,{h:60}),this.cScale5=this.cScale5||C(this.primaryColor,{h:90}),this.cScale6=this.cScale6||C(this.primaryColor,{h:120}),this.cScale7=this.cScale7||C(this.primaryColor,{h:150}),this.cScale8=this.cScale8||C(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||C(this.primaryColor,{h:270}),this.cScale10=this.cScale10||C(this.primaryColor,{h:300}),this.cScale11=this.cScale11||C(this.primaryColor,{h:330}),this.darkMode)for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},kt=t(e=>{let t=new Ot;return t.calculate(e),t},`getThemeVariables`),At=class{static{t(this,`Theme`)}constructor(){this.background=`#ffffff`,this.primaryColor=`#cccccc`,this.mainBkg=`#ffffff`,this.noteBkgColor=`#fff5ad`,this.noteTextColor=`#28253D`,this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.primaryBorderColor=B(this.primaryColor,this.darkMode),this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#28253D`,this.stateBorder=`#28253D`,this.useGradient=!1,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`url(#drop-shadow)`,this.nodeShadow=!0,this.tertiaryColor=`#ffffff`,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.actorBorder=`#28253D`,this.noteBorderColor=`#FACC15`,this.noteFontWeight=600,this.borderColorArray=[`#E879F9`,`#2DD4BF`,`#FB923C`,`#22D3EE`,`#4ADE80`,`#A78BFA`,`#F87171`,`#FACC15`,`#818CF8`,`#A3E635 `,`#38BDF8`,`#FB7185`],this.bkgColorArray=[`#FDF4FF`,`#F0FDFA`,`#FFF7ED`,`#ECFEFF`,`#F0FDF4`,`#F5F3FF`,`#FEF2F2`,`#FEFCE8`,`#EEF2FF`,`#F7FEE7`,`#F0F9FF`,`#FFF1F2`],this.filterColor=`#000000`}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#28253D`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#28253D`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor;let e=`#ECECFE`,t=`#E9E9F1`,n=C(e,{h:180,l:5});this.sectionBkgColor=this.sectionBkgColor||n,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||t,this.sectionBkgColor2=this.sectionBkgColor2||e,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||e,this.activeTaskBorderColor=this.activeTaskBorderColor||e,this.activeTaskBkgColor=this.activeTaskBkgColor||x(e,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||`#f4a8ff`,this.cScale1=this.cScale1||`#46ecd5`,this.cScale2=this.cScale2||`#ffb86a`,this.cScale3=this.cScale3||`#dab2ff`,this.cScale4=this.cScale4||`#7bf1a8`,this.cScale5=this.cScale5||`#c4b4ff`,this.cScale6=this.cScale6||`#ffa2a2`,this.cScale7=this.cScale7||`#ffdf20`,this.cScale8=this.cScale8||`#a3b3ff`,this.cScale9=this.cScale9||`#bbf451`,this.cScale10=this.cScale10||`#74d4ff`,this.cScale11=this.cScale11||`#ffa1ad`;for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},jt=t(e=>{let t=new At;return t.calculate(e),t},`getThemeVariables`),U=class{static{t(this,`Theme`)}constructor(){this.background=`#333`,this.primaryColor=`#1f2020`,this.secondaryColor=x(this.primaryColor,16),this.tertiaryColor=C(this.primaryColor,{h:-160}),this.primaryBorderColor=w(this.background),this.secondaryBorderColor=B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=B(this.tertiaryColor,this.darkMode),this.primaryTextColor=w(this.primaryColor),this.secondaryTextColor=w(this.secondaryColor),this.tertiaryTextColor=w(this.tertiaryColor),this.mainBkg=`#111113`,this.secondBkg=`calculated`,this.mainContrastColor=`lightgrey`,this.darkTextColor=x(w(`#323D47`),10),this.border1=`#ccc`,this.border2=_(255,255,255,.25),this.arrowheadColor=w(this.background),this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.labelBackground=`#111113`,this.textColor=`#ccc`,this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.noteBkgColor=this.noteBkgColor??`#FEF9C3`,this.noteTextColor=this.noteTextColor??`#28253D`,this.THEME_COLOR_LIMIT=12,this.fontFamily=`"Recursive Variable", arial, sans-serif`,this.fontSize=`14px`,this.nodeBorder=`#FFFFFF`,this.stateBorder=`#FFFFFF`,this.useGradient=!1,this.gradientStart=`#0042eb`,this.gradientStop=`#eb0042`,this.dropShadow=`url(#drop-shadow)`,this.nodeShadow=!0,this.archEdgeColor=`calculated`,this.archEdgeArrowColor=`calculated`,this.archEdgeWidth=`3`,this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth=`2px`,this.clusterBkg=`#1E1A2E`,this.clusterBorder=`#BDBCCC`,this.noteBorderColor=`#FACC15`,this.noteFontWeight=600,this.borderColorArray=[`#E879F9`,`#2DD4BF`,`#FB923C`,`#22D3EE`,`#4ADE80`,`#A78BFA`,`#F87171`,`#FACC15`,`#818CF8`,`#A3E635 `,`#38BDF8`,`#FB7185`],this.bkgColorArray=[],this.filterColor=`#FFFFFF`}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?`#eee`:`#FFFFFF`),this.secondaryColor=this.secondaryColor||C(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||C(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||B(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||B(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||B(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||B(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||`#fff5ad`,this.noteTextColor=this.noteTextColor||`#FFFFFF`,this.secondaryTextColor=this.secondaryTextColor||w(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||w(this.tertiaryColor),this.lineColor=this.lineColor||w(this.background),this.arrowheadColor=this.arrowheadColor||w(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.border1,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?S(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=`#FFFFFF`,this.signalColor=`#FFFFFF`,this.labelBoxBorderColor=`#BDBCCC`,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||S(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||w(this.lineColor),this.rectBkgColor=this.rectBkgColor||this.tertiaryColor,this.rootLabelColor=`#FFFFFF`,this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||`white`,this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||`#eeeeee`,this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||x(this.primaryColor,23),this.gridColor=this.gridColor||`lightgrey`,this.doneTaskBkgColor=this.doneTaskBkgColor||`lightgrey`,this.doneTaskBorderColor=this.doneTaskBorderColor||`grey`,this.critBorderColor=this.critBorderColor||`#ff8888`,this.critBkgColor=this.critBkgColor||`red`,this.todayLineColor=this.todayLineColor||`red`,this.taskTextColor=this.taskTextColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||`#003163`,this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||`#f0f0f0`,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||`#f4a8ff`,this.cScale1=this.cScale1||`#46ecd5`,this.cScale2=this.cScale2||`#ffb86a`,this.cScale3=this.cScale3||`#dab2ff`,this.cScale4=this.cScale4||`#7bf1a8`,this.cScale5=this.cScale5||`#c4b4ff`,this.cScale6=this.cScale6||`#ffa2a2`,this.cScale7=this.cScale7||`#ffdf20`,this.cScale8=this.cScale8||`#a3b3ff`,this.cScale9=this.cScale9||`#bbf451`,this.cScale10=this.cScale10||`#74d4ff`,this.cScale11=this.cScale11||`#ffa1ad`;for(let e=0;e{this[t]=e[t]}),this.updateColors(),t.forEach(t=>{this[t]=e[t]})}},W={base:{getThemeVariables:ht},dark:{getThemeVariables:_t},default:{getThemeVariables:H},forest:{getThemeVariables:yt},neutral:{getThemeVariables:xt},neo:{getThemeVariables:Ct},"neo-dark":{getThemeVariables:Tt},redux:{getThemeVariables:Dt},"redux-dark":{getThemeVariables:kt},"redux-color":{getThemeVariables:jt},"redux-dark-color":{getThemeVariables:t(e=>{let t=new U;return t.calculate(e),t},`getThemeVariables`)}},G={flowchart:{useMaxWidth:!0,titleTopMargin:25,subGraphTitleMargin:{top:0,bottom:0},diagramPadding:8,htmlLabels:null,nodeSpacing:50,rankSpacing:50,curve:`basis`,padding:15,defaultRenderer:`dagre-wrapper`,wrappingWidth:200,inheritDir:!1},swimlane:{useMaxWidth:!0,lineHops:`arc`,ignoreCrossLaneEdges:!0,optimizeRanksByCrossings:!0,automaticLaneOrdering:!1},sequence:{useMaxWidth:!0,hideUnusedParticipants:!1,activationWidth:10,diagramMarginX:50,diagramMarginY:10,actorMargin:50,width:150,height:65,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:`center`,mirrorActors:!0,forceMenus:!1,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1,actorFontSize:14,actorFontFamily:`"Open Sans", sans-serif`,actorFontWeight:400,noteFontSize:14,noteFontFamily:`"trebuchet ms", verdana, arial, sans-serif`,noteFontWeight:400,noteAlign:`center`,messageFontSize:16,messageFontFamily:`"trebuchet ms", verdana, arial, sans-serif`,messageFontWeight:400,wrap:!1,wrapPadding:10,labelBoxWidth:50,labelBoxHeight:20},gantt:{useMaxWidth:!0,titleTopMargin:25,barHeight:20,barGap:4,topPadding:50,rightPadding:75,leftPadding:75,gridLineStartPadding:35,fontSize:11,sectionFontSize:11,numberSectionStyles:4,axisFormat:`%Y-%m-%d`,topAxis:!1,displayMode:``,weekday:`sunday`},journey:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,leftMargin:150,maxLabelWidth:360,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:`center`,bottomMarginAdj:1,rightAngles:!1,taskFontSize:14,taskFontFamily:`"Open Sans", sans-serif`,taskMargin:50,activationWidth:10,textPlacement:`fo`,actorColours:[`#8FBC8F`,`#7CFC00`,`#00FFFF`,`#20B2AA`,`#B0E0E6`,`#FFFFE0`],sectionFills:[`#191970`,`#8B008B`,`#4B0082`,`#2F4F4F`,`#800000`,`#8B4513`,`#00008B`],sectionColours:[`#fff`],titleColor:``,titleFontFamily:`"trebuchet ms", verdana, arial, sans-serif`,titleFontSize:`4ex`},class:{useMaxWidth:!0,titleTopMargin:25,arrowMarkerAbsolute:!1,dividerMargin:10,padding:5,textHeight:10,defaultRenderer:`dagre-wrapper`,htmlLabels:!1,hideEmptyMembersBox:!1,hierarchicalNamespaces:!0},state:{useMaxWidth:!0,titleTopMargin:25,dividerMargin:10,sizeUnit:5,padding:8,textHeight:10,titleShift:-15,noteMargin:10,forkWidth:70,forkHeight:7,miniPadding:2,fontSizeFactor:5.02,fontSize:24,labelHeight:16,edgeLengthFactor:`20`,compositTitleSize:35,radius:5,defaultRenderer:`dagre-wrapper`},er:{useMaxWidth:!0,titleTopMargin:25,diagramPadding:20,layoutDirection:`TB`,minEntityWidth:100,minEntityHeight:75,entityPadding:15,nodeSpacing:140,rankSpacing:80,stroke:`gray`,fill:`honeydew`,fontSize:12},pie:{useMaxWidth:!0,textPosition:.75,donutHole:0,legendPosition:`right`,highlightSlice:``},quadrantChart:{useMaxWidth:!0,chartWidth:500,chartHeight:500,titleFontSize:20,titlePadding:10,quadrantPadding:5,xAxisLabelPadding:5,yAxisLabelPadding:5,xAxisLabelFontSize:16,yAxisLabelFontSize:16,quadrantLabelFontSize:16,quadrantTextTopPadding:5,pointTextPadding:5,pointLabelFontSize:12,pointRadius:5,xAxisPosition:`top`,yAxisPosition:`left`,quadrantInternalBorderStrokeWidth:1,quadrantExternalBorderStrokeWidth:2},xyChart:{useMaxWidth:!0,width:700,height:500,titleFontSize:20,titlePadding:10,showDataLabel:!1,showDataLabelOutsideBar:!1,showTitle:!0,xAxis:{$ref:`#/$defs/XYChartAxisConfig`,showLabel:!0,labelFontSize:14,labelPadding:5,showTitle:!0,titleFontSize:16,titlePadding:5,showTick:!0,tickLength:5,tickWidth:2,showAxisLine:!0,axisLineWidth:2,labelRotation:0},yAxis:{$ref:`#/$defs/XYChartAxisConfig`,showLabel:!0,labelFontSize:14,labelPadding:5,showTitle:!0,titleFontSize:16,titlePadding:5,showTick:!0,tickLength:5,tickWidth:2,showAxisLine:!0,axisLineWidth:2,labelRotation:0},chartOrientation:`vertical`,plotReservedSpacePercent:50},requirement:{useMaxWidth:!0,rect_fill:`#f9f9f9`,text_color:`#333`,rect_border_size:`0.5px`,rect_border_color:`#bbb`,rect_min_width:200,rect_min_height:200,fontSize:14,rect_padding:10,line_height:20},mindmap:{useMaxWidth:!0,padding:10,maxNodeWidth:200,layoutAlgorithm:`cose-bilkent`},ishikawa:{useMaxWidth:!0,diagramPadding:20},kanban:{useMaxWidth:!0,padding:8,sectionWidth:200,ticketBaseUrl:``},timeline:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:`center`,bottomMarginAdj:1,rightAngles:!1,taskFontSize:14,taskFontFamily:`"Open Sans", sans-serif`,taskMargin:50,activationWidth:10,textPlacement:`fo`,actorColours:[`#8FBC8F`,`#7CFC00`,`#00FFFF`,`#20B2AA`,`#B0E0E6`,`#FFFFE0`],sectionFills:[`#191970`,`#8B008B`,`#4B0082`,`#2F4F4F`,`#800000`,`#8B4513`,`#00008B`],sectionColours:[`#fff`],disableMulticolor:!1},gitGraph:{useMaxWidth:!0,titleTopMargin:25,diagramPadding:8,nodeLabel:{width:75,height:100,x:-25,y:0},mainBranchName:`main`,mainBranchOrder:0,showCommitLabel:!0,showBranches:!0,rotateCommitLabel:!0,parallelCommits:!1,arrowMarkerAbsolute:!1},c4:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10,c4ShapeInRow:4,nextLinePaddingX:0,c4BoundaryInRow:2,personFontSize:14,personFontFamily:`"Open Sans", sans-serif`,personFontWeight:`normal`,external_personFontSize:14,external_personFontFamily:`"Open Sans", sans-serif`,external_personFontWeight:`normal`,systemFontSize:14,systemFontFamily:`"Open Sans", sans-serif`,systemFontWeight:`normal`,external_systemFontSize:14,external_systemFontFamily:`"Open Sans", sans-serif`,external_systemFontWeight:`normal`,system_dbFontSize:14,system_dbFontFamily:`"Open Sans", sans-serif`,system_dbFontWeight:`normal`,external_system_dbFontSize:14,external_system_dbFontFamily:`"Open Sans", sans-serif`,external_system_dbFontWeight:`normal`,system_queueFontSize:14,system_queueFontFamily:`"Open Sans", sans-serif`,system_queueFontWeight:`normal`,external_system_queueFontSize:14,external_system_queueFontFamily:`"Open Sans", sans-serif`,external_system_queueFontWeight:`normal`,boundaryFontSize:14,boundaryFontFamily:`"Open Sans", sans-serif`,boundaryFontWeight:`normal`,messageFontSize:12,messageFontFamily:`"Open Sans", sans-serif`,messageFontWeight:`normal`,containerFontSize:14,containerFontFamily:`"Open Sans", sans-serif`,containerFontWeight:`normal`,external_containerFontSize:14,external_containerFontFamily:`"Open Sans", sans-serif`,external_containerFontWeight:`normal`,container_dbFontSize:14,container_dbFontFamily:`"Open Sans", sans-serif`,container_dbFontWeight:`normal`,external_container_dbFontSize:14,external_container_dbFontFamily:`"Open Sans", sans-serif`,external_container_dbFontWeight:`normal`,container_queueFontSize:14,container_queueFontFamily:`"Open Sans", sans-serif`,container_queueFontWeight:`normal`,external_container_queueFontSize:14,external_container_queueFontFamily:`"Open Sans", sans-serif`,external_container_queueFontWeight:`normal`,componentFontSize:14,componentFontFamily:`"Open Sans", sans-serif`,componentFontWeight:`normal`,external_componentFontSize:14,external_componentFontFamily:`"Open Sans", sans-serif`,external_componentFontWeight:`normal`,component_dbFontSize:14,component_dbFontFamily:`"Open Sans", sans-serif`,component_dbFontWeight:`normal`,external_component_dbFontSize:14,external_component_dbFontFamily:`"Open Sans", sans-serif`,external_component_dbFontWeight:`normal`,component_queueFontSize:14,component_queueFontFamily:`"Open Sans", sans-serif`,component_queueFontWeight:`normal`,external_component_queueFontSize:14,external_component_queueFontFamily:`"Open Sans", sans-serif`,external_component_queueFontWeight:`normal`,wrap:!0,wrapPadding:10,person_bg_color:`#08427B`,person_border_color:`#073B6F`,external_person_bg_color:`#686868`,external_person_border_color:`#8A8A8A`,system_bg_color:`#1168BD`,system_border_color:`#3C7FC0`,system_db_bg_color:`#1168BD`,system_db_border_color:`#3C7FC0`,system_queue_bg_color:`#1168BD`,system_queue_border_color:`#3C7FC0`,external_system_bg_color:`#999999`,external_system_border_color:`#8A8A8A`,external_system_db_bg_color:`#999999`,external_system_db_border_color:`#8A8A8A`,external_system_queue_bg_color:`#999999`,external_system_queue_border_color:`#8A8A8A`,container_bg_color:`#438DD5`,container_border_color:`#3C7FC0`,container_db_bg_color:`#438DD5`,container_db_border_color:`#3C7FC0`,container_queue_bg_color:`#438DD5`,container_queue_border_color:`#3C7FC0`,external_container_bg_color:`#B3B3B3`,external_container_border_color:`#A6A6A6`,external_container_db_bg_color:`#B3B3B3`,external_container_db_border_color:`#A6A6A6`,external_container_queue_bg_color:`#B3B3B3`,external_container_queue_border_color:`#A6A6A6`,component_bg_color:`#85BBF0`,component_border_color:`#78A8D8`,component_db_bg_color:`#85BBF0`,component_db_border_color:`#78A8D8`,component_queue_bg_color:`#85BBF0`,component_queue_border_color:`#78A8D8`,external_component_bg_color:`#CCCCCC`,external_component_border_color:`#BFBFBF`,external_component_db_bg_color:`#CCCCCC`,external_component_db_border_color:`#BFBFBF`,external_component_queue_bg_color:`#CCCCCC`,external_component_queue_border_color:`#BFBFBF`},sankey:{useMaxWidth:!0,width:600,height:400,linkColor:`gradient`,nodeAlignment:`justify`,showValues:!0,prefix:``,suffix:``,nodeWidth:10,nodePadding:12,labelStyle:`legacy`},block:{useMaxWidth:!0,padding:8},packet:{useMaxWidth:!0,rowHeight:32,bitWidth:32,bitsPerRow:32,showBits:!0,paddingX:5,paddingY:5},treeView:{useMaxWidth:!0,rowIndent:10,paddingX:5,paddingY:5,lineThickness:1,showIcons:!1,defaultIconPack:``,filenameIcons:{},extensionIcons:{}},architecture:{useMaxWidth:!0,padding:40,iconSize:80,fontSize:16,randomize:!1,nodeSeparation:75,idealEdgeLengthMultiplier:1.5,edgeElasticity:.45,numIter:2500,seed:1},eventmodeling:{useMaxWidth:!0,padding:30,rowHeight:32},radar:{useMaxWidth:!0,width:600,height:600,marginTop:50,marginRight:50,marginBottom:50,marginLeft:50,axisScaleFactor:1,axisLabelFactor:1.05,curveTension:.17},venn:{useMaxWidth:!0,width:800,height:450,padding:8,useDebugLayout:!1},cynefin:{useMaxWidth:!0,width:800,height:600,padding:40,showDomainDescriptions:!0,boundaryAmplitude:8,seed:0},theme:`default`,look:`classic`,handDrawnSeed:0,layout:`dagre`,maxTextSize:5e4,maxEdges:500,darkMode:!1,fontFamily:`"trebuchet ms", verdana, arial, sans-serif;`,logLevel:5,securityLevel:`strict`,startOnLoad:!0,arrowMarkerAbsolute:!1,secure:[`secure`,`securityLevel`,`startOnLoad`,`maxTextSize`,`suppressErrorRendering`,`maxEdges`],legacyMathML:!1,forceLegacyMathML:!1,deterministicIds:!1,fontSize:16,markdownAutoWrap:!0,suppressErrorRendering:!1},Mt={...G,deterministicIDSeed:void 0,elk:{mergeEdges:!1,nodePlacementStrategy:`BRANDES_KOEPF`,forceNodeModelOrder:!1,considerModelOrder:`NODES_AND_EDGES`},themeCSS:void 0,themeVariables:W.default.getThemeVariables(),sequence:{...G.sequence,messageFont:t(function(){return{fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},`messageFont`),noteFont:t(function(){return{fontFamily:this.noteFontFamily,fontSize:this.noteFontSize,fontWeight:this.noteFontWeight}},`noteFont`),actorFont:t(function(){return{fontFamily:this.actorFontFamily,fontSize:this.actorFontSize,fontWeight:this.actorFontWeight}},`actorFont`)},class:{hideEmptyMembersBox:!1,hierarchicalNamespaces:!0},gantt:{...G.gantt,tickInterval:void 0,useWidth:void 0},c4:{...G.c4,useWidth:void 0,personFont:t(function(){return{fontFamily:this.personFontFamily,fontSize:this.personFontSize,fontWeight:this.personFontWeight}},`personFont`),flowchart:{...G.flowchart,inheritDir:!1},external_personFont:t(function(){return{fontFamily:this.external_personFontFamily,fontSize:this.external_personFontSize,fontWeight:this.external_personFontWeight}},`external_personFont`),systemFont:t(function(){return{fontFamily:this.systemFontFamily,fontSize:this.systemFontSize,fontWeight:this.systemFontWeight}},`systemFont`),external_systemFont:t(function(){return{fontFamily:this.external_systemFontFamily,fontSize:this.external_systemFontSize,fontWeight:this.external_systemFontWeight}},`external_systemFont`),system_dbFont:t(function(){return{fontFamily:this.system_dbFontFamily,fontSize:this.system_dbFontSize,fontWeight:this.system_dbFontWeight}},`system_dbFont`),external_system_dbFont:t(function(){return{fontFamily:this.external_system_dbFontFamily,fontSize:this.external_system_dbFontSize,fontWeight:this.external_system_dbFontWeight}},`external_system_dbFont`),system_queueFont:t(function(){return{fontFamily:this.system_queueFontFamily,fontSize:this.system_queueFontSize,fontWeight:this.system_queueFontWeight}},`system_queueFont`),external_system_queueFont:t(function(){return{fontFamily:this.external_system_queueFontFamily,fontSize:this.external_system_queueFontSize,fontWeight:this.external_system_queueFontWeight}},`external_system_queueFont`),containerFont:t(function(){return{fontFamily:this.containerFontFamily,fontSize:this.containerFontSize,fontWeight:this.containerFontWeight}},`containerFont`),external_containerFont:t(function(){return{fontFamily:this.external_containerFontFamily,fontSize:this.external_containerFontSize,fontWeight:this.external_containerFontWeight}},`external_containerFont`),container_dbFont:t(function(){return{fontFamily:this.container_dbFontFamily,fontSize:this.container_dbFontSize,fontWeight:this.container_dbFontWeight}},`container_dbFont`),external_container_dbFont:t(function(){return{fontFamily:this.external_container_dbFontFamily,fontSize:this.external_container_dbFontSize,fontWeight:this.external_container_dbFontWeight}},`external_container_dbFont`),container_queueFont:t(function(){return{fontFamily:this.container_queueFontFamily,fontSize:this.container_queueFontSize,fontWeight:this.container_queueFontWeight}},`container_queueFont`),external_container_queueFont:t(function(){return{fontFamily:this.external_container_queueFontFamily,fontSize:this.external_container_queueFontSize,fontWeight:this.external_container_queueFontWeight}},`external_container_queueFont`),componentFont:t(function(){return{fontFamily:this.componentFontFamily,fontSize:this.componentFontSize,fontWeight:this.componentFontWeight}},`componentFont`),external_componentFont:t(function(){return{fontFamily:this.external_componentFontFamily,fontSize:this.external_componentFontSize,fontWeight:this.external_componentFontWeight}},`external_componentFont`),component_dbFont:t(function(){return{fontFamily:this.component_dbFontFamily,fontSize:this.component_dbFontSize,fontWeight:this.component_dbFontWeight}},`component_dbFont`),external_component_dbFont:t(function(){return{fontFamily:this.external_component_dbFontFamily,fontSize:this.external_component_dbFontSize,fontWeight:this.external_component_dbFontWeight}},`external_component_dbFont`),component_queueFont:t(function(){return{fontFamily:this.component_queueFontFamily,fontSize:this.component_queueFontSize,fontWeight:this.component_queueFontWeight}},`component_queueFont`),external_component_queueFont:t(function(){return{fontFamily:this.external_component_queueFontFamily,fontSize:this.external_component_queueFontSize,fontWeight:this.external_component_queueFontWeight}},`external_component_queueFont`),boundaryFont:t(function(){return{fontFamily:this.boundaryFontFamily,fontSize:this.boundaryFontSize,fontWeight:this.boundaryFontWeight}},`boundaryFont`),messageFont:t(function(){return{fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},`messageFont`)},pie:{...G.pie,useWidth:984},xyChart:{...G.xyChart,useWidth:void 0},requirement:{...G.requirement,useWidth:void 0},packet:{...G.packet},eventmodeling:{...G.eventmodeling},treeView:{...G.treeView,useWidth:void 0},radar:{...G.radar},railroad:{...G.railroad,fontSize:void 0,fontFamily:void 0,terminalFill:void 0,terminalStroke:void 0,terminalTextColor:void 0,nonTerminalFill:void 0,nonTerminalStroke:void 0,nonTerminalTextColor:void 0,lineColor:void 0,markerFill:void 0,commentFill:void 0,commentStroke:void 0,commentTextColor:void 0,specialFill:void 0,specialStroke:void 0,ruleNameColor:void 0},ishikawa:{...G.ishikawa},sankey:{...G.sankey,nodeColors:void 0},treemap:{useMaxWidth:!0,padding:10,diagramPadding:8,showValues:!0,nodeWidth:100,nodeHeight:40,borderWidth:1,valueFontSize:12,labelFontSize:14,valueFormat:`,`},venn:{...G.venn},cynefin:{...G.cynefin}},Nt=t((e,t=``)=>Object.keys(e).reduce((n,r)=>Array.isArray(e[r])?n:typeof e[r]==`object`&&e[r]!==null?[...n,t+r,...Nt(e[r],``)]:[...n,t+r],[]),`keyify`),Pt=new Set(Nt(Mt,``)),Ft=Mt,It={nodeColors:/^#[\da-f]{3,8}$|^rgb\([\d\s%,.]+\)$|^hsl\([\d\s%,.]+\)$|^[a-z]+$/i,filenameIcons:/^[\w-]+(?::[\w-]+)?$/,extensionIcons:/^[\w-]+(?::[\w-]+)?$/},K=t((e,t)=>{for(let n of Object.keys(e)){let r=e[n];(n.startsWith(`__`)||n.includes(`proto`)||n.includes(`constr`)||typeof r!=`string`||!t.test(r))&&(i.debug(`sanitize deleting dictionary entry:`,n,r),delete e[n])}},`sanitizeDictionaryConfig`),q=t(e=>{if(i.debug(`sanitizeDirective called with`,e),!(typeof e!=`object`||!e)){if(Array.isArray(e)){e.forEach(e=>q(e));return}for(let t of Object.keys(e)){if(i.debug(`Checking key`,t),t.startsWith(`__`)||t.includes(`proto`)||t.includes(`constr`)||!Pt.has(t)||e[t]==null){i.debug(`sanitize deleting key: `,t),delete e[t];continue}if(typeof e[t]==`object`){let n=It[t];n?K(e[t],n):(i.debug(`sanitizing object`,t),q(e[t]));continue}for(let n of[`themeCSS`,`fontFamily`,`altFontFamily`])t.includes(n)&&(i.debug(`sanitizing css option`,t),e[t]=Lt(e[t]))}if(e.themeVariables)for(let t of Object.keys(e.themeVariables)){let n=e.themeVariables[t];n?.match&&!n.match(/^[\d "#%(),.;A-Za-z]+$/)&&(e.themeVariables[t]=``)}i.debug(`After sanitization`,e)}},`sanitizeDirective`),Lt=t(e=>{let t=0,n=0;for(let r of e){if(t!(e===!1||[`false`,`null`,`0`].includes(String(e).trim().toLowerCase())),`evaluate`),J=L({},Rt),Bt,Y=[],Vt=L({},Rt),Ht=t((e,t)=>{let n=L({},e),r={};for(let e of t)Jt(e),r=L(r,e);if(n=L(n,r),r.theme&&r.theme in W){let e=L(L({},Bt).themeVariables||{},r.themeVariables);n.theme&&n.theme in W&&(n.themeVariables=W[n.theme].getThemeVariables(e))}return Vt=n,en(Vt),Vt},`updateCurrentConfig`),Ut=t(e=>(J=L({},Rt),J=L(J,e),e.theme&&W[e.theme]&&(J.themeVariables=W[e.theme].getThemeVariables(e.themeVariables)),Ht(J,Y),J),`setSiteConfig`),Wt=t(e=>{Bt=L({},e)},`saveConfigFromInitialize`),X=t(e=>(J=L(J,e),Ht(J,Y),J),`updateSiteConfig`),Gt=t(()=>L({},J),`getSiteConfig`),Kt=t(e=>(en(e),L(Vt,e),qt()),`setConfig`),qt=t(()=>L({},Vt),`getConfig`),Jt=t(e=>{e&&([`secure`,...J.secure??[]].forEach(t=>{Object.hasOwn(e,t)&&(i.debug(`Denied attempt to modify a secure key ${t}`,e[t]),delete e[t])}),Object.keys(e).forEach(t=>{t.startsWith(`__`)&&delete e[t]}),Object.keys(e).forEach(t=>{typeof e[t]==`string`&&(e[t].includes(`<`)||e[t].includes(`>`)||e[t].includes(`url(data:`))&&delete e[t],typeof e[t]==`object`&&Jt(e[t])}))},`sanitize`),Yt=t(e=>{q(e),e.fontFamily&&!e.themeVariables?.fontFamily&&(e.themeVariables={...e.themeVariables,fontFamily:e.fontFamily}),Y.push(e),Ht(J,Y)},`addDirective`),Xt=t((e=J)=>{Y=[],Ht(e,Y)},`reset`),Zt={LAZY_LOAD_DEPRECATED:`The configuration options lazyLoadedDiagrams and loadExternalDiagramsAtStartup are deprecated. Please use registerExternalDiagrams instead.`,FLOWCHART_HTML_LABELS_DEPRECATED:`flowchart.htmlLabels is deprecated. Please use global htmlLabels instead.`},Qt={},$t=t(e=>{Qt[e]||(i.warn(Zt[e]),Qt[e]=!0)},`issueWarning`),en=t(e=>{e&&(e.lazyLoadedDiagrams||e.loadExternalDiagramsAtStartup)&&$t(`LAZY_LOAD_DEPRECATED`)},`checkConfig`),tn=t(()=>{let e={};Bt&&(e=L(e,Bt));for(let t of Y)e=L(e,t);return e},`getUserDefinedConfig`),nn=t(e=>(e.flowchart?.htmlLabels!=null&&$t(`FLOWCHART_HTML_LABELS_DEPRECATED`),zt(e.htmlLabels??e.flowchart?.htmlLabels??!0)),`getEffectiveHtmlLabels`),Z=/^([^\S\n\r]*)-{3}\s*[\n\r](.*?)[\n\r]\1-{3}\s*[\n\r]+/s,rn=/%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi,an=/\s*%%.*\n/gm,on=class extends Error{static{t(this,`UnknownDiagramError`)}constructor(e){super(e),this.name=`UnknownDiagramError`}},sn={},cn=t(function(e,t){e=e.replace(Z,``).replace(rn,``).replace(an,` +`);for(let[n,{detector:r}]of Object.entries(sn))if(r(e,t))return n;throw new on(`No diagram type detected matching given configuration for text: ${e}`)},`detectType`),ln=t((...e)=>{for(let{id:t,detector:n,loader:r}of e)un(t,n,r)},`registerLazyLoadedDiagrams`),un=t((e,t,n)=>{sn[e]&&i.warn(`Detector with key ${e} already exists. Overwriting.`),sn[e]={detector:t,loader:n},i.debug(`Detector with key ${e} added${n?` with loader`:``}`)},`addDetector`),dn=t(e=>sn[e].loader,`getDiagramLoader`),Q=//gi,fn=t(e=>e?xn(e).replace(/\\n/g,`#br#`).split(`#br#`):[``],`getRows`),$=(()=>{let e=!1;return()=>{e||=(pn(),!0)}})();function pn(){let e=`data-temp-href-target`;I.addHook(`beforeSanitizeAttributes`,t=>{t.tagName===`A`&&t.hasAttribute(`target`)&&t.setAttribute(e,t.getAttribute(`target`)??``)}),I.addHook(`afterSanitizeAttributes`,t=>{t.tagName===`A`&&t.hasAttribute(e)&&(t.setAttribute(`target`,t.getAttribute(e)??``),t.removeAttribute(e),t.getAttribute(`target`)===`_blank`&&t.setAttribute(`rel`,`noopener`))})}t(pn,`setupDompurifyHooks`);var mn=t(e=>($(),I.sanitize(e)),`removeScript`),hn=t((e,t)=>{if(nn(t)){let n=t.securityLevel;n===`antiscript`||n===`strict`||n===`sandbox`?e=mn(e):n!==`loose`&&(e=xn(e),e=e.replace(//g,`>`),e=e.replace(/=/g,`=`),e=bn(e))}return e},`sanitizeMore`),gn=t((e,t)=>e&&(e=t.dompurifyConfig?I.sanitize(hn(e,t),t.dompurifyConfig).toString():I.sanitize(hn(e,t),{FORBID_TAGS:[`style`]}).toString(),e),`sanitizeText`),_n=t((e,t)=>typeof e==`string`?gn(e,t):e.flat().map(e=>gn(e,t)),`sanitizeTextOrArray`),vn=t(e=>Q.test(e),`hasBreaks`),yn=t(e=>e.split(Q),`splitBreaks`),bn=t(e=>e.replace(/#br#/g,`
    `),`placeholderToBreak`),xn=t(e=>e.replace(Q,`#br#`),`breakToPlaceholder`),Sn=t(e=>{let t=``;return e&&(t=window.location.protocol+`//`+window.location.host+window.location.pathname+window.location.search,t=CSS.escape(t)),t},`getUrl`),Cn=t(function(...e){let t=e.filter(e=>!isNaN(e));return Math.max(...t)},`getMax`),wn=t(function(...e){let t=e.filter(e=>!isNaN(e));return Math.min(...t)},`getMin`),Tn=t(function(e){let t=e.split(/(,)/),n=[];for(let e=0;e0&&e+1Math.max(0,e.split(t).length-1),`countOccurrence`),Dn=t((e,t)=>{let n=En(e,`~`),r=En(t,`~`);return n===1&&r===1},`shouldCombineSets`),On=t(e=>{let t=En(e,`~`),n=!1;if(t<=1)return e;t%2!=0&&e.startsWith(`~`)&&(e=e.substring(1),n=!0);let r=[...e],i=r.indexOf(`~`),a=r.lastIndexOf(`~`);for(;i!==-1&&a!==-1&&i!==a;)r[i]=`<`,r[a]=`>`,i=r.indexOf(`~`),a=r.lastIndexOf(`~`);return n&&r.unshift(`~`),r.join(``)},`processSet`),kn=t(()=>window.MathMLElement!==void 0,`isMathMLSupported`),An=/\$\$(.*?)\$\$/g,jn=t(e=>(e.match(An)?.length??0)>0,`hasKatex`),Mn=t(async(e,t)=>{let n=document.createElement(`div`);n.innerHTML=await Pn(e,t),n.id=`katex-temp`,n.style.visibility=`hidden`,n.style.position=`absolute`,n.style.top=`0`,document.querySelector(`body`)?.insertAdjacentElement(`beforeend`,n);let r={width:n.clientWidth,height:n.clientHeight};return n.remove(),r},`calculateMathMLDimensions`),Nn=t(async(t,n)=>{if(!jn(t))return t;if(!(kn()||n.legacyMathML||n.forceLegacyMathML))return t.replace(An,`MathML is unsupported in this environment.`);{let{default:r}=await e(async()=>{let{default:e}=await import(`./katex-B7rAX3Vi.js`);return{default:e}},[]),i=n.forceLegacyMathML||!kn()&&n.legacyMathML?`htmlAndMathml`:`mathml`;return t.split(Q).map(e=>jn(e)?`
    ${e}
    `:`
    ${e}
    `).join(``).replace(An,(e,t)=>r.renderToString(t,{throwOnError:!0,displayMode:!0,output:i}).replace(/\n/g,` `).replace(//g,``))}return t.replace(An,`Katex is not supported in @mermaid-js/tiny. Please use the full mermaid library.`)},`renderKatexUnsanitized`),Pn=t(async(e,t)=>gn(await Nn(e,t),t),`renderKatexSanitized`),Fn={getRows:fn,sanitizeText:gn,sanitizeTextOrArray:_n,hasBreaks:vn,splitBreaks:yn,lineBreakRegex:Q,removeScript:mn,getUrl:Sn,evaluate:zt,getMax:Cn,getMin:wn},In=t(function(e,t){for(let n of t)e.attr(n[0],n[1])},`d3Attrs`),Ln=t(function(e,t,n){let r=new Map;return n?(r.set(`width`,`100%`),r.set(`style`,`max-width: ${t}px;`)):(r.set(`height`,e),r.set(`width`,t)),r},`calculateSvgSizeAttrs`),Rn=t(function(e,t,n,r){In(e,Ln(t,n,r))},`configureSvgSize`),zn=t(function(e,t,n,r){let a=t.node().getBBox(),o=a.width,s=a.height;i.info(`SVG bounds: ${o}x${s}`,a);let c=0,l=0;i.info(`Graph bounds: ${c}x${l}`,e),c=o+n*2,l=s+n*2,i.info(`Calculated bounds: ${c}x${l}`),Rn(t,l,c,r);let u=`${a.x-n} ${a.y-n} ${a.width+2*n} ${a.height+2*n}`;t.attr(`viewBox`,u)},`setupGraphViewbox`),Bn={};function Vn(e){return[...e.cssRules].map(e=>e.cssText).join(` +`)}t(Vn,`cssStyleSheetToString`);var Hn=t((e,t,n,r)=>{let a=``;return e in Bn&&Bn[e]?a=Bn[e]({...n,svgId:r}):i.warn(`No theme found for ${e}`),` & { + font-family: ${n.fontFamily}; + font-size: ${n.fontSize}; + fill: ${n.textColor} + } + @keyframes edge-animation-frame { + from { + stroke-dashoffset: 0; + } + } + @keyframes dash { + to { + stroke-dashoffset: 0; + } + } + & .edge-animation-slow { + stroke-dasharray: 9,5 !important; + stroke-dashoffset: 900; + animation: dash 50s linear infinite; + stroke-linecap: round; + } + & .edge-animation-fast { + stroke-dasharray: 9,5 !important; + stroke-dashoffset: 900; + animation: dash 20s linear infinite; + stroke-linecap: round; + } + /* Classes common for multiple diagrams */ + + & .error-icon { + fill: ${n.errorBkgColor}; + } + & .error-text { + fill: ${n.errorTextColor}; + stroke: ${n.errorTextColor}; + } + + & .edge-thickness-normal { + stroke-width: ${n.strokeWidth??1}px; + } + & .edge-thickness-thick { + stroke-width: 3.5px + } + & .edge-pattern-solid { + stroke-dasharray: 0; + } + & .edge-thickness-invisible { + stroke-width: 0; + fill: none; + } + & .edge-pattern-dashed{ + stroke-dasharray: 3; + } + .edge-pattern-dotted { + stroke-dasharray: 2; + } + + & .marker { + fill: ${n.lineColor}; + stroke: ${n.lineColor}; + } + & .marker.cross { + stroke: ${n.lineColor}; + } + + & svg { + font-family: ${n.fontFamily}; + font-size: ${n.fontSize}; + } + & p { + margin: 0 + } + + ${a} + .node .neo-node { + stroke: ${n.nodeBorder}; + } + + [data-look="neo"].node rect, [data-look="neo"].cluster rect, [data-look="neo"].node polygon { + stroke: ${n.useGradient?`url(`+r+`-gradient)`:n.nodeBorder}; + filter: ${n.dropShadow?n.dropShadow.replace(`url(#drop-shadow)`,`url(${r}-drop-shadow)`):`none`}; + } + [data-look="neo"].swimlane.cluster rect { + filter: none; + } + + + [data-look="neo"].node path { + stroke: ${n.useGradient?`url(`+r+`-gradient)`:n.nodeBorder}; + stroke-width: ${n.strokeWidth??1}px; + } + + [data-look="neo"].node .outer-path { + filter: ${n.dropShadow?n.dropShadow.replace(`url(#drop-shadow)`,`url(${r}-drop-shadow)`):`none`}; + } + + [data-look="neo"].node .neo-line path { + stroke: ${n.nodeBorder}; + filter: none; + } + + [data-look="neo"].node circle{ + stroke: ${n.useGradient?`url(`+r+`-gradient)`:n.nodeBorder}; + filter: ${n.dropShadow?n.dropShadow.replace(`url(#drop-shadow)`,`url(${r}-drop-shadow)`):`none`}; + } + + [data-look="neo"].node circle .state-start{ + fill: #000000; + } + + [data-look="neo"].icon-shape .icon { + fill: ${n.useGradient?`url(`+r+`-gradient)`:n.nodeBorder}; + filter: ${n.dropShadow?n.dropShadow.replace(`url(#drop-shadow)`,`url(${r}-drop-shadow)`):`none`}; + } + + [data-look="neo"].icon-shape .icon-neo path { + stroke: ${n.useGradient?`url(`+r+`-gradient)`:n.nodeBorder}; + filter: ${n.dropShadow?n.dropShadow.replace(`url(#drop-shadow)`,`url(${r}-drop-shadow)`):`none`}; + } + + ${t} +`},`getStyles`),Un=t((e,t)=>{t!==void 0&&(Bn[e]=t)},`addStylesForDiagram`),Wn=Hn,Gn={};n(Gn,{clear:()=>Xn,getAccDescription:()=>er,getAccTitle:()=>Qn,getDiagramTitle:()=>nr,setAccDescription:()=>$n,setAccTitle:()=>Zn,setDiagramTitle:()=>tr});var Kn=``,qn=``,Jn=``,Yn=t(e=>gn(e,qt()),`sanitizeText`),Xn=t(()=>{Kn=``,Jn=``,qn=``},`clear`),Zn=t(e=>{Kn=Yn(e).replace(/^\s+/g,``)},`setAccTitle`),Qn=t(()=>Kn,`getAccTitle`),$n=t(e=>{Jn=Yn(e).replace(/\n\s+/g,` +`)},`setAccDescription`),er=t(()=>Jn,`getAccDescription`),tr=t(e=>{qn=Yn(e)},`setDiagramTitle`),nr=t(()=>qn,`getDiagramTitle`),rr=i,ir=r,ar=qt,or=Kt,sr=Rt,cr=t(e=>gn(e,ar()),`sanitizeText`),lr=zn,ur=t(()=>Gn,`getCommonDb`),dr={},fr=t((e,t,n)=>{dr[e]&&rr.warn(`Diagram with id ${e} already registered. Overwriting.`),dr[e]=t,n&&un(e,n),Un(e,t.styles),t.injectUtils?.(rr,ir,ar,cr,lr,ur(),()=>{})},`registerDiagram`),pr=t(e=>{if(e in dr)return dr[e];throw new mr(e)},`getDiagram`),mr=class extends Error{static{t(this,`DiagramNotFoundError`)}constructor(e){super(`Diagram ${e} not found.`)}};export{I as $,jn as A,cr as B,dn as C,H as D,Gt as E,Pn as F,or as G,$n as H,Xt as I,zn as J,tr as K,Lt as L,Tn as M,fr as N,Sn as O,ln as P,X as Q,q as R,pr as S,nn as T,Zn as U,Wt as V,Kt as W,Wn as X,lr as Y,W as Z,Z as _,Xn as a,h as at,qt as b,Rn as c,sr as d,S as et,Ft as f,zt as g,rn as h,Mn as i,_ as it,Q as j,tn as k,Vn as l,sn as m,Yt as n,b as nt,Gn as o,o as ot,cn as p,Ut as q,L as r,y as rt,Fn as s,on as t,x as tt,Rt as u,er as v,nr as w,ar as x,Qn as y,gn as z}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-XXDRQBXY-Bq6zMMOx.js b/dist-desktop/assets/chunk-XXDRQBXY-Bq6zMMOx.js new file mode 100644 index 0000000..1db543a --- /dev/null +++ b/dist-desktop/assets/chunk-XXDRQBXY-Bq6zMMOx.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";var n=e((e,n)=>{let r;return n===`sandbox`&&(r=t(`#i`+e)),t(n===`sandbox`?r.nodes()[0].contentDocument.body:`body`).select(`[id="${e}"]`)},`getDiagramElement`);export{n as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-Y2CYZVJY-DsF7k-Jl.js b/dist-desktop/assets/chunk-Y2CYZVJY-DsF7k-Jl.js new file mode 100644 index 0000000..70c3d40 --- /dev/null +++ b/dist-desktop/assets/chunk-Y2CYZVJY-DsF7k-Jl.js @@ -0,0 +1 @@ +var e=Object.defineProperty,t=(t,n)=>e(t,`name`,{value:n,configurable:!0}),n=(t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})};export{t as n,n as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-YOTPTUD7-CjHV8V6f.js b/dist-desktop/assets/chunk-YOTPTUD7-CjHV8V6f.js new file mode 100644 index 0000000..3b9e741 --- /dev/null +++ b/dist-desktop/assets/chunk-YOTPTUD7-CjHV8V6f.js @@ -0,0 +1 @@ +import{C as e,S as t,f as n,n as r,o as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`PieTokenBuilder`)}constructor(){super([`pie`,`showData`])}},u=class extends r{static{c(this,`PieValueConverter`)}runCustomConverter(e,t,n){if(e.name===`PIE_SECTION_LABEL`)return t.replace(/"/g,``).trim()}},d={parser:{TokenBuilder:c(()=>new l,`TokenBuilder`),ValueConverter:c(()=>new u,`ValueConverter`)}};function f(r=i){let a=s(e(r),o),c=s(t({shared:a}),n,d);return a.ServiceRegistry.register(c),{shared:a,Pie:c}}c(f,`createPieServices`);export{f as n,d as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-ZGVPDNZ5-DGInJAPD.js b/dist-desktop/assets/chunk-ZGVPDNZ5-DGInJAPD.js new file mode 100644 index 0000000..530bb02 --- /dev/null +++ b/dist-desktop/assets/chunk-ZGVPDNZ5-DGInJAPD.js @@ -0,0 +1,62 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{A as r,B as i,M as a,T as o,b as s,g as c,x as l,z as u}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{a as d,r as f,u as p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-HOUHSVGY-iJuv90UH.js";import{n as h}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{n as g,t as _}from"./chunk-OGEWGWER-D-nWYRNR.js";import{a as v,i as y,r as b,t as x}from"./chunk-C7G6YPKG-DW-1jWUA.js";import{t as S}from"./rough.esm-CSKSodPl.js";var C=e(async(e,t,r)=>{let i,a=t.useHtmlLabels||c(l()?.htmlLabels);i=r||`node default`;let o=e.insert(`g`).attr(`class`,i).attr(`id`,t.domId||t.id),s=o.insert(`g`).attr(`class`,`label`).attr(`style`,p(t.labelStyle)),f;f=t.label===void 0?``:typeof t.label==`string`?t.label:t.label[0];let m=!!t.icon||!!t.img,g=t.labelType===`markdown`,v=await h(s,u(d(f),l()),{useHtmlLabels:a,width:t.width||l().flowchart?.wrappingWidth,classes:g?`markdown-node-label`:``,style:t.labelStyle,addSvgBackground:m,markdown:g},l()),y=v.getBBox(),b=(t?.padding??0)/2;if(a){let e=v.children[0],t=n(v);await _(e,f),y=e.getBoundingClientRect(),t.attr(`width`,y.width),t.attr(`height`,y.height)}return a?s.attr(`transform`,`translate(`+-y.width/2+`, `+-y.height/2+`)`):s.attr(`transform`,`translate(0, `+-y.height/2+`)`),t.centerLabel&&s.attr(`transform`,`translate(`+-y.width/2+`, `+-y.height/2+`)`),s.insert(`rect`,`:first-child`),{shapeSvg:o,bbox:y,halfPadding:b,label:s}},`labelHelper`),w=e(async(e,t,r)=>{let i=r.useHtmlLabels??o(l()),a=e.insert(`g`).attr(`class`,`label`).attr(`style`,r.labelStyle||``),s=await h(a,u(d(t),l()),{useHtmlLabels:i,width:r.width||l()?.flowchart?.wrappingWidth,style:r.labelStyle,addSvgBackground:!!r.icon||!!r.img}),c=s.getBBox(),f=r.padding/2;if(o(l())){let e=s.children[0],t=n(s);c=e.getBoundingClientRect(),t.attr(`width`,c.width),t.attr(`height`,c.height)}return i?a.attr(`transform`,`translate(`+-c.width/2+`, `+-c.height/2+`)`):a.attr(`transform`,`translate(0, `+-c.height/2+`)`),r.centerLabel&&a.attr(`transform`,`translate(`+-c.width/2+`, `+-c.height/2+`)`),a.insert(`rect`,`:first-child`),{shapeSvg:e,bbox:c,halfPadding:f,label:a}},`insertLabel`),T=e((e,t)=>{let n=t.node().getBBox();e.width=n.width,e.height=n.height},`updateNodeBounds`),E=e((e,t)=>(e.look===`handDrawn`?`rough-node`:`node`)+` `+e.cssClasses+` `+(t||``),`getNodeClasses`);function D(e){let t=e.map((e,t)=>`${t===0?`M`:`L`}${e.x},${e.y}`);return t.push(`Z`),t.join(` `)}e(D,`createPathFromPoints`);function O(e,t,n,r,i,a){let o=[],s=n-e,c=r-t,l=s/a,u=2*Math.PI/l,d=t+c/2;for(let t=0;t<=50;t++){let n=e+t/50*s,r=d+i*Math.sin(u*(n-e));o.push({x:n,y:r})}return o}e(O,`generateFullSineWavePoints`);function k(e,t,n,r,i,a){let o=[],s=i*Math.PI/180,c=(a*Math.PI/180-s)/(r-1);for(let i=0;ie.tagName===`path`),r=document.createElementNS(`http://www.w3.org/2000/svg`,`path`),i=n.map(e=>e.getAttribute(`d`)).filter(e=>e!==null).join(` `);r.setAttribute(`d`,i);let a=n.find(e=>e.getAttribute(`fill`)!==`none`),o=n.find(e=>e.getAttribute(`stroke`)!==`none`),s=e((e,t)=>e?.getAttribute(t)??void 0,`getAttr`);if(a){let e={fill:s(a,`fill`),"fill-opacity":s(a,`fill-opacity`)??`1`};Object.entries(e).forEach(([e,t])=>{t&&r.setAttribute(e,t)})}if(o){let e={stroke:s(o,`stroke`),"stroke-width":s(o,`stroke-width`)??`1`,"stroke-opacity":s(o,`stroke-opacity`)??`1`};Object.entries(e).forEach(([e,t])=>{t&&r.setAttribute(e,t)})}let c=document.createElementNS(`http://www.w3.org/2000/svg`,`g`);return c.appendChild(r),c}e(A,`mergePaths`);var j=e((e,t)=>{var n=e.x,r=e.y,i=t.x-n,a=t.y-r,o=e.width/2,s=e.height/2,c,l;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),c=a===0?0:s*i/a,l=s):(i<0&&(o=-o),c=o,l=i===0?0:o*a/i),{x:n+c,y:r+l}},`intersectRect`),M=e(async(e,t,n,r=!1,i=!1)=>{let a=t||``;typeof a==`object`&&(a=a[0]);let s=l(),c=o(s);return await h(e,a,{style:n,isTitle:r,useHtmlLabels:c,markdown:!1,isNode:i,width:1/0},s)},`createLabel`),N=e((e,t,n,r,i)=>[`M`,e+i,t,`H`,e+n-i,`A`,i,i,0,0,1,e+n,t+i,`V`,t+r-i,`A`,i,i,0,0,1,e+n-i,t+r,`H`,e+i,`A`,i,i,0,0,1,e,t+r-i,`V`,t+i,`A`,i,i,0,0,1,e+i,t,`Z`].join(` `),`createRoundedRectPathD`),P=e(async(e,r)=>{let i=l(),{themeVariables:a,handDrawnSeed:o}=i,{clusterBkg:s,clusterBorder:u}=a,d=u,{labelStyles:f,nodeStyles:p,borderStyles:m,backgroundStyles:g}=y(r),_=e.insert(`g`).attr(`class`,`cluster swimlane `+(r.cssClasses||``)).attr(`id`,r.id).attr(`data-id`,r.id).attr(`data-et`,`cluster`).attr(`data-look`,r.look),b=c(i.flowchart.htmlLabels),x=r.direction===`LR`,C=_.insert(`g`).attr(`class`,`cluster-label swimlane-label`),w=await h(C,r.label,{style:r.labelStyle,useHtmlLabels:b,isNode:!0,width:r.width}),T=w.getBBox();if(b){let e=w.children[0],t=n(w);T=e.getBoundingClientRect(),t.attr(`width`,T.width),t.attr(`height`,T.height)}let E=r.padding??0,D=r.width<=T.width+E?T.width+E:r.width;r.width<=T.width+E?r.diff=(D-r.width)/2-E:r.diff=-E;let O=r.height,k=r.y-O/2,A=r.y+O/2,M=r.x-D/2,N=r.swimlaneContentTop===void 0?k+O/3:r.swimlaneContentTop,P=x?4:0,F=T.height+2*P,I,L;if(x){let e=Math.max(F,T.height+2*P),t=M+e,n=Math.max(0,D-e);if(r.look===`handDrawn`){let i=S.svg(_),a=v(r,{roughness:.7,fill:s,stroke:d,fillWeight:3,seed:o}),c=v(r,{roughness:.7,fill:`none`,stroke:d,seed:o}),l=i.rectangle(M,k,e,O,a);I=_.insert(()=>l,`:first-child`);let u=i.rectangle(t,k,n,O,c);L=_.insert(()=>u,`:first-child`),I.select(`path:nth-child(2)`).attr(`style`,m.join(`;`)),I.select(`path`).attr(`style`,g.join(`;`).replace(`fill`,`stroke`))}else I=_.insert(`rect`,`:first-child`),L=_.insert(`rect`,`:first-child`),I.attr(`class`,`swimlane-title`).attr(`style`,p).attr(`x`,M).attr(`y`,k).attr(`width`,e).attr(`height`,O).attr(`fill`,s).attr(`stroke`,d),L.attr(`class`,`swimlane-body`).attr(`style`,p).attr(`x`,t).attr(`y`,k).attr(`width`,n).attr(`height`,O).attr(`fill`,`none`).attr(`stroke`,d);let i=M+e/2,a=r.y;C.attr(`transform`,`translate(${i}, ${a}) rotate(-90) translate(${-T.width/2}, ${-T.height/2})`)}else{let e=Math.max(0,N-k),t=Math.min(F,e),n=k+t,i=Math.max(0,A-n),a=r.x-D/2;if(r.look===`handDrawn`){let e=S.svg(_),c=v(r,{roughness:.7,fill:s,stroke:d,fillWeight:3,seed:o}),l=v(r,{roughness:.7,fill:`none`,stroke:d,seed:o}),u=e.rectangle(a,k,D,t,c);I=_.insert(()=>u,`:first-child`);let f=e.rectangle(a,n,D,i,l);L=_.insert(()=>f,`:first-child`),I.select(`path:nth-child(2)`).attr(`style`,m.join(`;`)),I.select(`path`).attr(`style`,g.join(`;`).replace(`fill`,`stroke`))}else I=_.insert(`rect`,`:first-child`),L=_.insert(`rect`,`:first-child`),I.attr(`class`,`swimlane-title`).attr(`style`,p).attr(`x`,a).attr(`y`,k).attr(`width`,D).attr(`height`,t).attr(`fill`,s).attr(`stroke`,d),L.attr(`class`,`swimlane-body`).attr(`style`,p).attr(`x`,a).attr(`y`,n).attr(`width`,D).attr(`height`,i).attr(`fill`,`none`).attr(`stroke`,d);let c=r.x-T.width/2,l=k+(t-T.height)/2;C.attr(`transform`,`translate(${c}, ${l})`)}if(t.trace(`Swimlane data `,r,JSON.stringify(r)),f){let e=C.select(`span`);e&&e.attr(`style`,f)}return r.offsetX=0,r.width=D,r.height=O,r.offsetY=T.height-E/2,r.intersect=function(e){return j(r,e)},{cluster:_,labelBBox:T}},`swimlane`),F=e(async(e,r)=>{t.info(`Creating subgraph rect for `,r.id,r);let i=l(),{themeVariables:a,handDrawnSeed:s}=i,{clusterBkg:c,clusterBorder:u}=a,{labelStyles:d,nodeStyles:f,borderStyles:p,backgroundStyles:m}=y(r),_=e.insert(`g`).attr(`class`,`cluster `+r.cssClasses).attr(`id`,r.domId).attr(`data-look`,r.look),b=o(i),x=_.insert(`g`).attr(`class`,`cluster-label `),C;C=r.labelType===`markdown`?await h(x,r.label,{style:r.labelStyle,useHtmlLabels:b,isNode:!0,width:r.width}):await M(x,r.label,r.labelStyle||``,!1,!0);let w=C.getBBox();if(o(i)){let e=C.children[0],t=n(C);w=e.getBoundingClientRect(),t.attr(`width`,w.width),t.attr(`height`,w.height)}let T=r.width<=w.width+r.padding?w.width+r.padding:r.width;r.width<=w.width+r.padding?r.diff=(T-r.width)/2-r.padding:r.diff=-r.padding;let E=r.height,D=r.x-T/2,O=r.y-E/2;t.trace(`Data `,r,JSON.stringify(r));let k;if(r.look===`handDrawn`){let e=S.svg(_),n=v(r,{roughness:.7,fill:c,stroke:u,fillWeight:3,seed:s}),i=e.path(N(D,O,T,E,0),n);k=_.insert(()=>(t.debug(`Rough node insert CXC`,i),i),`:first-child`),k.select(`path:nth-child(2)`).attr(`style`,p.join(`;`)),k.select(`path`).attr(`style`,m.join(`;`).replace(`fill`,`stroke`))}else k=_.insert(`rect`,`:first-child`),k.attr(`style`,f).attr(`rx`,r.rx).attr(`ry`,r.ry).attr(`x`,D).attr(`y`,O).attr(`width`,T).attr(`height`,E);let{subGraphTitleTopMargin:A}=g(i);if(x.attr(`transform`,`translate(${r.x-w.width/2}, ${r.y-r.height/2+A})`),d){let e=x.select(`span`);e&&e.attr(`style`,d)}let P=k.node().getBBox();return r.offsetX=0,r.width=P.width,r.height=P.height,r.offsetY=w.height-r.padding/2,r.intersect=function(e){return j(r,e)},{cluster:_,labelBBox:w}},`rect`),I={rect:F,squareRect:F,roundedWithTitle:e(async(e,t)=>{let r=l(),{themeVariables:i,handDrawnSeed:a}=r,{altBackground:s,compositeBackground:c,compositeTitleBackground:u,nodeBorder:d}=i,f=e.insert(`g`).attr(`class`,t.cssClasses).attr(`id`,t.domId).attr(`data-id`,t.id).attr(`data-look`,t.look),p=f.insert(`g`,`:first-child`),m=f.insert(`g`).attr(`class`,`cluster-label`),h=f.append(`rect`),g=await M(m,t.label,t.labelStyle,void 0,!0),_=g.getBBox();if(o(r)){let e=g.children[0],t=n(g);_=e.getBoundingClientRect(),t.attr(`width`,_.width),t.attr(`height`,_.height)}let v=0*t.padding,y=v/2,b=(t.width<=_.width+t.padding?_.width+t.padding:t.width)+v;t.width<=_.width+t.padding?t.diff=(b-t.width)/2-t.padding:t.diff=-t.padding;let x=t.height+v,C=t.height+v-_.height-6,w=t.x-b/2,T=t.y-x/2;t.width=b;let E=t.y-t.height/2-y+_.height+2,D;if(t.look===`handDrawn`){let e=t.cssClasses.includes(`statediagram-cluster-alt`),n=S.svg(f),r=t.rx||t.ry?n.path(N(w,T,b,x,10),{roughness:.7,fill:u,fillStyle:`solid`,stroke:d,seed:a}):n.rectangle(w,T,b,x,{seed:a});D=f.insert(()=>r,`:first-child`);let i=n.rectangle(w,E,b,C,{fill:e?s:c,fillStyle:e?`hachure`:`solid`,stroke:d,seed:a});D=f.insert(()=>r,`:first-child`),h=f.insert(()=>i)}else D=p.insert(`rect`,`:first-child`),D.attr(`class`,`outer`).attr(`x`,w).attr(`y`,T).attr(`width`,b).attr(`height`,x).attr(`data-look`,t.look),h.attr(`class`,`inner`).attr(`x`,w).attr(`y`,E).attr(`width`,b).attr(`height`,C);return m.attr(`transform`,`translate(${t.x-_.width/2}, ${T+1-(o(r)?0:3)})`),t.height=D.node().getBBox().height,t.offsetX=0,t.offsetY=_.height-t.padding/2,t.labelBBox=_,t.intersect=function(e){return j(t,e)},{cluster:f,labelBBox:_}},`roundedWithTitle`),noteGroup:e((e,t)=>{let n=e.insert(`g`).attr(`class`,`note-cluster`).attr(`id`,t.domId),r=n.insert(`rect`,`:first-child`),i=0*t.padding,a=i/2;r.attr(`rx`,t.rx).attr(`ry`,t.ry).attr(`x`,t.x-t.width/2-a).attr(`y`,t.y-t.height/2-a).attr(`width`,t.width+i).attr(`height`,t.height+i).attr(`fill`,`none`);let o=r.node().getBBox();return t.width=o.width,t.height=o.height,t.intersect=function(e){return j(t,e)},{cluster:n,labelBBox:{width:0,height:0}}},`noteGroup`),divider:e((e,t)=>{let{themeVariables:n,handDrawnSeed:r}=l(),{nodeBorder:i}=n,a=e.insert(`g`).attr(`class`,t.cssClasses).attr(`id`,t.domId).attr(`data-look`,t.look),o=a.insert(`g`,`:first-child`),s=0*t.padding,c=t.width+s;t.diff=-t.padding;let u=t.height+s,d=t.x-c/2,f=t.y-u/2;t.width=c;let p;if(t.look===`handDrawn`){let e=S.svg(a).rectangle(d,f,c,u,{fill:`lightgrey`,roughness:.5,strokeLineDash:[5],stroke:i,seed:r});p=a.insert(()=>e,`:first-child`)}else{p=o.insert(`rect`,`:first-child`);let e=`outer`;e=(t.look,`divider`),p.attr(`class`,e).attr(`x`,d).attr(`y`,f).attr(`width`,c).attr(`height`,u).attr(`data-look`,t.look)}return t.height=p.node().getBBox().height,t.offsetX=0,t.offsetY=0,t.intersect=function(e){return j(t,e)},{cluster:a,labelBBox:{}}},`divider`),kanbanSection:e(async(e,r)=>{t.info(`Creating subgraph rect for `,r.id,r);let i=l(),{themeVariables:a,handDrawnSeed:s}=i,{clusterBkg:c,clusterBorder:u}=a,{labelStyles:d,nodeStyles:f,borderStyles:p,backgroundStyles:m}=y(r),_=e.insert(`g`).attr(`class`,`cluster `+r.cssClasses).attr(`id`,r.domId).attr(`data-look`,r.look),b=o(i),x=_.insert(`g`).attr(`class`,`cluster-label `),C=await h(x,r.label,{style:r.labelStyle,useHtmlLabels:b,isNode:!0,width:r.width}),w=C.getBBox();if(o(i)){let e=C.children[0],t=n(C);w=e.getBoundingClientRect(),t.attr(`width`,w.width),t.attr(`height`,w.height)}let T=r.width<=w.width+r.padding?w.width+r.padding:r.width;r.width<=w.width+r.padding?r.diff=(T-r.width)/2-r.padding:r.diff=-r.padding;let E=r.height,D=r.x-T/2,O=r.y-E/2;t.trace(`Data `,r,JSON.stringify(r));let k;if(r.look===`handDrawn`){let e=S.svg(_),n=v(r,{roughness:.7,fill:c,stroke:u,fillWeight:4,seed:s}),i=e.path(N(D,O,T,E,r.rx),n);k=_.insert(()=>(t.debug(`Rough node insert CXC`,i),i),`:first-child`),k.select(`path:nth-child(2)`).attr(`style`,p.join(`;`)),k.select(`path`).attr(`style`,m.join(`;`).replace(`fill`,`stroke`))}else k=_.insert(`rect`,`:first-child`),k.attr(`style`,f).attr(`rx`,r.rx).attr(`ry`,r.ry).attr(`x`,D).attr(`y`,O).attr(`width`,T).attr(`height`,E);let{subGraphTitleTopMargin:A}=g(i);if(x.attr(`transform`,`translate(${r.x-w.width/2}, ${r.y-r.height/2+A})`),d){let e=x.select(`span`);e&&e.attr(`style`,d)}let M=k.node().getBBox();return r.offsetX=0,r.width=M.width,r.height=M.height,r.offsetY=w.height-r.padding/2,r.intersect=function(e){return j(r,e)},{cluster:_,labelBBox:w}},`kanbanSection`),swimlane:P},L=new Map,ee=e(async(e,t)=>{let n=await I[t.shape||`rect`](e,t);return L.set(t.id,n),n},`insertCluster`),R=e(()=>{L=new Map},`clear`);function z(e,t){return e.intersect(t)}e(z,`intersectNode`);var te=z;function B(e,t,n,r){var i=e.x,a=e.y,o=i-r.x,s=a-r.y,c=Math.sqrt(t*t*s*s+n*n*o*o),l=Math.abs(t*n*o/c);r.x0}e(re,`sameSign`);var ie=ne;function W(e,t,n){let r=e.x,i=e.y,a=[],o=1/0,s=1/0;typeof t.forEach==`function`?t.forEach(function(e){o=Math.min(o,e.x),s=Math.min(s,e.y)}):(o=Math.min(o,t.x),s=Math.min(s,t.y));let c=r-e.width/2-o,l=i-e.height/2-s;for(let r=0;r1&&a.sort(function(e,t){let r=e.x-n.x,i=e.y-n.y,a=Math.sqrt(r*r+i*i),o=t.x-n.x,s=t.y-n.y,c=Math.sqrt(o*o+s*s);return au,`:first-child`);return d.attr(`class`,`anchor`).attr(`style`,p(s)),T(n,d),n.intersect=function(e){return t.info(`Circle intersect`,n,1,e),G.circle(n,1,e)},o}e(K,`anchor`);function ae(e,t,n,r,i,a,o){let s=(e+n)/2,c=(t+r)/2,l=Math.atan2(r-t,n-e),u=(n-e)/2,d=(r-t)/2,f=u/i,p=d/a,m=Math.sqrt(f**2+p**2);if(m>1)throw Error(`The given radii are too small to create an arc between the points.`);let h=Math.sqrt(1-m**2),g=s+h*a*Math.sin(l)*(o?-1:1),_=c-h*i*Math.cos(l)*(o?-1:1),v=Math.atan2((t-_)/a,(e-g)/i),y=Math.atan2((r-_)/a,(n-g)/i)-v;o&&y<0&&(y+=2*Math.PI),!o&&y>0&&(y-=2*Math.PI);let b=[];for(let e=0;e<20;e++){let t=v+e/19*y,n=g+i*Math.cos(t),r=_+a*Math.sin(t);b.push({x:n,y:r})}return b}e(ae,`generateArcPoints`);function oe(e,t,n){let[r,i]=[t,n].sort((e,t)=>t-e);return i*(1-Math.sqrt(1-(e/r/2)**2))}e(oe,`calculateArcSagitta`);async function se(t,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let a=n.padding??0,o=n.look===`neo`?16:a,s=n.look===`neo`?12:a,c=e(e=>e+s,`calcTotalHeight`),l=e(e=>{let t=e/2;return[t/(2.5+e/50),t]},`calcEllipseRadius`),{shapeSvg:u,bbox:d}=await C(t,n,E(n)),f=c(n?.height?n?.height:d.height),[p,m]=l(f),h=oe(f,p,m),g=(n?.width?n?.width:d.width)+o*2+h-h,_=f,{cssStyles:b}=n,x=[{x:g/2,y:-_/2},{x:-g/2,y:-_/2},...ae(-g/2,-_/2,-g/2,_/2,p,m,!1),{x:g/2,y:_/2},...ae(g/2,_/2,g/2,-_/2,p,m,!0)],w=S.svg(u),O=v(n,{});n.look!==`handDrawn`&&(O.roughness=0,O.fillStyle=`solid`);let k=D(x),A=w.path(k,O),j=u.insert(()=>A,`:first-child`);return j.attr(`class`,`basic label-container outer-path`),b&&n.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,b),i&&n.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,i),j.attr(`transform`,`translate(${p/2}, 0)`),T(n,j),n.intersect=function(e){return G.polygon(n,x,e)},u}e(se,`bowTieRect`);function q(e,t,n,r){return e.insert(`polygon`,`:first-child`).attr(`points`,r.map(function(e){return e.x+`,`+e.y}).join(` `)).attr(`class`,`label-container`).attr(`transform`,`translate(`+-t/2+`,`+n/2+`)`)}e(q,`insertPolygonShape`);var ce=12;async function le(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?28:i,o=t.look===`neo`?24:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.width??c.width)+(t.look===`neo`?a*2:a+ce),u=(t?.height??c.height)+(t.look===`neo`?o*2:o),d=l,f=-u,p=[{x:0+ce,y:f},{x:d,y:f},{x:d,y:0},{x:0,y:0},{x:0,y:f+ce},{x:0+ce,y:f}],m,{cssStyles:h}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(p),i=e.path(r,n);m=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-l/2}, ${u/2})`),h&&m.attr(`style`,h)}else m=q(s,l,u,p);return r&&m.attr(`style`,r),T(t,m),t.intersect=function(e){return G.polygon(t,p,e)},s}e(le,`card`);function ue(e,t){let{nodeStyles:n}=y(t);t.label=``;let r=e.insert(`g`).attr(`class`,E(t)).attr(`id`,t.domId??t.id),{cssStyles:i}=t,a=Math.max(28,t.width??0),o=[{x:0,y:a/2},{x:a/2,y:0},{x:0,y:-a/2},{x:-a/2,y:0}],s=S.svg(r),c=v(t,{});t.look!==`handDrawn`&&(c.roughness=0,c.fillStyle=`solid`);let l=D(o),u=s.path(l,c),d=r.insert(()=>u,`:first-child`);return i&&t.look!==`handDrawn`&&d.selectAll(`path`).attr(`style`,i),n&&t.look!==`handDrawn`&&d.selectAll(`path`).attr(`style`,n),t.width=28,t.height=28,t.intersect=function(e){return G.polygon(t,o,e)},r}e(ue,`choice`);async function de(e,n,r){let{labelStyles:i,nodeStyles:a}=y(n);n.labelStyle=i;let{shapeSvg:o,bbox:s,halfPadding:c}=await C(e,n,E(n)),l=r?.padding??c,u=n.look===`neo`?s.width/2+32:s.width/2+l,d,{cssStyles:f}=n;if(n.look===`handDrawn`){let e=S.svg(o),t=v(n,{}),r=e.circle(0,0,u*2,t);d=o.insert(()=>r,`:first-child`),d.attr(`class`,`basic label-container`).attr(`style`,p(f))}else d=o.insert(`circle`,`:first-child`).attr(`class`,`basic label-container`).attr(`style`,a).attr(`r`,u).attr(`cx`,0).attr(`cy`,0);return T(n,d),n.calcIntersect=function(e,t){let n=e.width/2;return G.circle(e,n,t)},n.intersect=function(e){return t.info(`Circle intersect`,n,u,e),G.circle(n,u,e)},o}e(de,`circle`);function fe(e){let t=Math.cos(Math.PI/4),n=Math.sin(Math.PI/4),r=e*2,i={x:r/2*t,y:r/2*n},a={x:-(r/2)*t,y:r/2*n},o={x:-(r/2)*t,y:-(r/2)*n},s={x:r/2*t,y:-(r/2)*n};return`M ${a.x},${a.y} L ${s.x},${s.y} + M ${i.x},${i.y} L ${o.x},${o.y}`}e(fe,`createLine`);function pe(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r,n.label=``;let a=e.insert(`g`).attr(`class`,E(n)).attr(`id`,n.domId??n.id),o=Math.max(30,n?.width??0),{cssStyles:s}=n,c=S.svg(a),l=v(n,{});n.look!==`handDrawn`&&(l.roughness=0,l.fillStyle=`solid`);let u=c.circle(0,0,o*2,l),d=fe(o),f=c.path(d,l),p=a.insert(()=>u,`:first-child`);return p.insert(()=>f),p.attr(`class`,`outer-path`),s&&n.look!==`handDrawn`&&p.selectAll(`path`).attr(`style`,s),i&&n.look!==`handDrawn`&&p.selectAll(`path`).attr(`style`,i),T(n,p),n.intersect=function(e){return t.info(`crossedCircle intersect`,n,{radius:o,point:e}),G.circle(n,o,e)},a}e(pe,`crossedCircle`);function J(e,t,n,r=100,i=0,a=180){let o=[],s=i*Math.PI/180,c=(a*Math.PI/180-s)/(r-1);for(let i=0;iw,`:first-child`).attr(`stroke-opacity`,0),O.insert(()=>b,`:first-child`),O.attr(`class`,`text`),f&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,r),O.attr(`transform`,`translate(${d}, 0)`),o.attr(`transform`,`translate(${-l/2+d-(a.x-(a.left??0))},${-u/2+(t.padding??0)/2-(a.y-(a.top??0))})`),T(t,O),t.intersect=function(e){return G.polygon(t,m,e)},i}e(me,`curlyBraceLeft`);function Y(e,t,n,r=100,i=0,a=180){let o=[],s=i*Math.PI/180,c=(a*Math.PI/180-s)/(r-1);for(let i=0;iw,`:first-child`).attr(`stroke-opacity`,0),O.insert(()=>b,`:first-child`),O.attr(`class`,`text`),f&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,r),O.attr(`transform`,`translate(${-d}, 0)`),o.attr(`transform`,`translate(${-l/2+(t.padding??0)/2-(a.x-(a.left??0))},${-u/2+(t.padding??0)/2-(a.y-(a.top??0))})`),T(t,O),t.intersect=function(e){return G.polygon(t,m,e)},i}e(he,`curlyBraceRight`);function X(e,t,n,r=100,i=0,a=180){let o=[],s=i*Math.PI/180,c=(a*Math.PI/180-s)/(r-1);for(let i=0;iA,`:first-child`).attr(`stroke-opacity`,0),j.insert(()=>x,`:first-child`),j.insert(()=>O,`:first-child`),j.attr(`class`,`text`),f&&t.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,r),j.attr(`transform`,`translate(${d-d/4}, 0)`),o.attr(`transform`,`translate(${-l/2+(t.padding??0)/2-(a.x-(a.left??0))},${-u/2+(t.padding??0)/2-(a.y-(a.top??0))})`),T(t,j),t.intersect=function(e){return G.polygon(t,h,e)},i}e(ge,`curlyBraces`);async function _e(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=Math.max(20,(c.width+a*2)*1.25,t?.width??0),u=Math.max(5,c.height+o*2,t?.height??0),d=u/2,{cssStyles:f}=t,p=S.svg(s),m=v(t,{});t.look!==`handDrawn`&&(m.roughness=0,m.fillStyle=`solid`);let h=l,g=u,_=h-d,b=g/4,x=[{x:_,y:0},{x:b,y:0},{x:0,y:g/2},{x:b,y:g},{x:_,y:g},...k(-_,-g/2,d,50,270,90)],w=D(x),O=p.path(w,m),A=s.insert(()=>O,`:first-child`);return A.attr(`class`,`basic label-container outer-path`),f&&t.look!==`handDrawn`&&A.selectChildren(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&A.selectChildren(`path`).attr(`style`,r),A.attr(`transform`,`translate(${-l/2}, ${-u/2})`),T(t,A),t.intersect=function(e){return G.polygon(t,x,e)},s}e(_e,`curvedTrapezoid`);var ve=e((e,t,n,r,i,a)=>[`M${e},${t+a}`,`a${i},${a} 0,0,0 ${n},0`,`a${i},${a} 0,0,0 ${-n},0`,`l0,${r}`,`a${i},${a} 0,0,0 ${n},0`,`l0,${-r}`].join(` `),`createCylinderPathD`),ye=e((e,t,n,r,i,a)=>[`M${e},${t+a}`,`M${e+n},${t+a}`,`a${i},${a} 0,0,0 ${-n},0`,`l0,${r}`,`a${i},${a} 0,0,0 ${n},0`,`l0,${-r}`].join(` `),`createOuterCylinderPathD`),be=e((e,t,n,r,i,a)=>[`M${e-n/2},${-r/2}`,`a${i},${a} 0,0,0 ${n},0`].join(` `),`createInnerCylinderPathD`),xe=8,Se=8;async function Ce(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?24:i,o=t.look===`neo`?24:i;if(t.width||t.height){let e=t.width??0;t.width=(t.width??0)-o,t.widtho,`:first-child`),h=s.insert(()=>a,`:first-child`),h.attr(`class`,`basic label-container`),g&&h.attr(`style`,g)}else{let e=ve(0,0,u,m,d,f);h=s.insert(`path`,`:first-child`).attr(`d`,e).attr(`class`,`basic label-container outer-path`).attr(`style`,p(g)).attr(`style`,r)}return h.attr(`label-offset-y`,f),h.attr(`transform`,`translate(${-u/2}, ${-(m/2+f)})`),T(t,h),l.attr(`transform`,`translate(${-(c.width/2)-(c.x-(c.left??0))}, ${-(c.height/2)+(t.padding??0)/1.5-(c.y-(c.top??0))})`),t.intersect=function(e){let n=G.rect(t,e),r=n.x-(t.x??0);if(d!=0&&(Math.abs(r)<(t.width??0)/2||Math.abs(r)==(t.width??0)/2&&Math.abs(n.y-(t.y??0))>(t.height??0)/2-f)){let i=f*f*(1-r*r/(d*d));i>0&&(i=Math.sqrt(i)),i=f-i,e.y-(t.y??0)>0&&(i=-i),n.y+=i}return n},s}e(Ce,`cylinder`);async function we(e,t,n){let{labelStyles:r,nodeStyles:i}=y(t);t.labelStyle=r;let{shapeSvg:a,bbox:o}=await C(e,t,E(t)),s=Math.max(o.width+n.labelPaddingX*2,t?.width||0),c=Math.max(o.height+n.labelPaddingY*2,t?.height||0),l=-s/2,u=-c/2,d,{rx:f,ry:m}=t,{cssStyles:h}=t;if(n?.rx&&n.ry&&(f=n.rx,m=n.ry),t.look===`handDrawn`){let e=S.svg(a),n=v(t,{}),r=f||m?e.path(N(l,u,s,c,f||0),n):e.rectangle(l,u,s,c,n);d=a.insert(()=>r,`:first-child`),d.attr(`class`,`basic label-container`).attr(`style`,p(h))}else d=a.insert(`rect`,`:first-child`),d.attr(`class`,`basic label-container`).attr(`style`,i).attr(`rx`,p(f)).attr(`ry`,p(m)).attr(`x`,l).attr(`y`,u).attr(`width`,s).attr(`height`,c);return T(t,d),t.calcIntersect=function(e,t){return G.rect(e,t)},t.intersect=function(e){return G.rect(t,e)},a}e(we,`drawRect`);async function Te(e,t){let{cssClasses:n,labelPaddingX:r,labelPaddingY:i,padding:a,width:o,height:s}=t,c=await we(e,t,{rx:0,ry:0,classes:n??``,labelPaddingX:r??(a??0)*2,labelPaddingY:i??a??0});if(t.look===`handDrawn`){let e=S.svg(c),n=v(t,{}),r=c.select(`.basic.label-container > path:nth-child(2)`),i=r.node();if(!i)return c;let a=null;if(i instanceof SVGGraphicsElement)a=i.getBBox();else return c;return c.insert(()=>e.line(a.x,a.y,a.x+a.width,a.y,n),`.basic.label-container g.label`),c.insert(()=>e.line(a.x,a.y+a.height,a.x+a.width,a.y+a.height,n),`.basic.label-container g.label`),r.remove(),c}let l=c.select(`.basic.label-container`),u=(Number(l.attr(`width`))||o)??0,d=(Number(l.attr(`height`))||s)??0;return u>0&&d>0&&l.attr(`stroke-dasharray`,`${u} ${d}`),c}e(Te,`datastore`);async function Ee(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.look===`neo`?16:t.padding??0,a=t.look===`neo`?16:t.padding??0,{shapeSvg:o,bbox:s,label:c}=await C(e,t,E(t)),l=s.width+i,u=s.height+a,d=u*.2,f=-l/2,p=-u/2-d/2,{cssStyles:m}=t,h=S.svg(o),g=v(t,{});t.look!==`handDrawn`&&(g.roughness=0,g.fillStyle=`solid`);let _=[{x:f,y:p+d},{x:-f,y:p+d},{x:-f,y:-p},{x:f,y:-p},{x:f,y:p},{x:-f,y:p},{x:-f,y:p+d}],b=h.polygon(_.map(e=>[e.x,e.y]),g),x=o.insert(()=>b,`:first-child`);return x.attr(`class`,`basic label-container outer-path`),m&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,m),r&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,r),c.attr(`transform`,`translate(${f+(t.padding??0)/2-(s.x-(s.left??0))}, ${p+d+(t.padding??0)/2-(s.y-(s.top??0))})`),T(t,x),t.intersect=function(e){return G.rect(t,e)},o}e(Ee,`dividedRectangle`);async function De(e,n){let{labelStyles:r,nodeStyles:i}=y(n),a=n.look===`neo`?12:5;n.labelStyle=r;let o=n.padding??0,s=n.look===`neo`?16:o,{shapeSvg:c,bbox:l}=await C(e,n,E(n)),u=(n?.width?n?.width/2:l.width/2)+(s??0),d=u-a,f,{cssStyles:m}=n;if(n.look===`handDrawn`){let e=S.svg(c),t=v(n,{roughness:.2,strokeWidth:2.5}),r=v(n,{roughness:.2,strokeWidth:1.5}),i=e.circle(0,0,u*2,t),a=e.circle(0,0,d*2,r);f=c.insert(`g`,`:first-child`),f.attr(`class`,p(n.cssClasses)).attr(`style`,p(m)),f.node()?.appendChild(i),f.node()?.appendChild(a)}else{f=c.insert(`g`,`:first-child`);let e=f.insert(`circle`,`:first-child`),t=f.insert(`circle`);f.attr(`class`,`basic label-container`).attr(`style`,i),e.attr(`class`,`outer-circle`).attr(`style`,i).attr(`r`,u).attr(`cx`,0).attr(`cy`,0),t.attr(`class`,`inner-circle`).attr(`style`,i).attr(`r`,d).attr(`cx`,0).attr(`cy`,0)}return T(n,f),n.intersect=function(e){return t.info(`DoubleCircle intersect`,n,u,e),G.circle(n,u,e)},c}e(De,`doublecircle`);function Oe(e,n,{config:{themeVariables:r}}){let{labelStyles:i,nodeStyles:a}=y(n);n.label=``,n.labelStyle=i;let o=e.insert(`g`).attr(`class`,E(n)).attr(`id`,n.domId??n.id),{cssStyles:s}=n,c=S.svg(o),{nodeBorder:l}=r,u=v(n,{fillStyle:`solid`});n.look!==`handDrawn`&&(u.roughness=0);let d=c.circle(0,0,14,u),f=o.insert(()=>d,`:first-child`);return f.selectAll(`path`).attr(`style`,`fill: ${l} !important;`),s&&s.length>0&&n.look!==`handDrawn`&&f.selectAll(`path`).attr(`style`,s),a&&n.look!==`handDrawn`&&f.selectAll(`path`).attr(`style`,a),T(n,f),n.intersect=function(e){return t.info(`filledCircle intersect`,n,{radius:7,point:e}),G.circle(n,7,e)},o}e(Oe,`filledCircle`);var ke=10,Ae=10;async function je(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let a=n.padding??0,o=n.look===`neo`?a*2:a;(n.width||n.height)&&(n.height=n?.height??0,n.heightb,`:first-child`).attr(`transform`,`translate(${-d/2}, ${d/2})`).attr(`class`,`outer-path`);return m&&n.look!==`handDrawn`&&x.selectChildren(`path`).attr(`style`,m),i&&n.look!==`handDrawn`&&x.selectChildren(`path`).attr(`style`,i),n.width=u,n.height=d,T(n,x),l.attr(`transform`,`translate(${-c.width/2-(c.x-(c.left??0))}, ${-d/2+(n.padding??0)/2+(c.y-(c.top??0))})`),n.intersect=function(e){return t.info(`Triangle intersect`,n,p,e),G.polygon(n,p,e)},s}e(je,`flippedTriangle`);function Me(e,t,{dir:n,config:{state:r,themeVariables:i}}){let{nodeStyles:a}=y(t);t.label=``;let o=e.insert(`g`).attr(`class`,E(t)).attr(`id`,t.domId??t.id),{cssStyles:s}=t,c=Math.max(70,t?.width??0),l=Math.max(10,t?.height??0);n===`LR`&&(c=Math.max(10,t?.width??0),l=Math.max(70,t?.height??0));let u=-1*c/2,d=-1*l/2,f=S.svg(o),p=v(t,{stroke:i.lineColor,fill:i.lineColor});t.look!==`handDrawn`&&(p.roughness=0,p.fillStyle=`solid`);let m=f.rectangle(u,d,c,l,p),h=o.insert(()=>m,`:first-child`);s&&t.look!==`handDrawn`&&h.selectAll(`path`).attr(`style`,s),a&&t.look!==`handDrawn`&&h.selectAll(`path`).attr(`style`,a),T(t,h);let g=r?.padding??0;return t.width&&t.height&&(t.width+=g/2||0,t.height+=g/2||0),t.intersect=function(e){return G.rect(t,e)},o}e(Me,`forkJoin`);async function Ne(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let a=n.look===`neo`?16:n.padding??0,o=n.look===`neo`?12:n.padding??0;(n.width||n.height)&&(n.height=(n?.height??0)-o*2,n.height<10&&(n.height=10),n.width=(n?.width??0)-a*2,n.width<15&&(n.width=15));let{shapeSvg:s,bbox:c}=await C(e,n,E(n)),l=(n?.width?n?.width:Math.max(15,c.width))+a*2,u=(n?.height?n?.height:Math.max(10,c.height))+o*2,d=u/2,{cssStyles:f}=n,p=S.svg(s),m=v(n,{});n.look!==`handDrawn`&&(m.roughness=0,m.fillStyle=`solid`);let h=[{x:-l/2,y:-u/2},{x:l/2-d,y:-u/2},...k(-l/2+d,0,d,50,90,270),{x:l/2-d,y:u/2},{x:-l/2,y:u/2}],g=D(h),_=p.path(g,m),b=s.insert(()=>_,`:first-child`);return b.attr(`class`,`basic label-container outer-path`),f&&n.look!==`handDrawn`&&b.selectChildren(`path`).attr(`style`,f),i&&n.look!==`handDrawn`&&b.selectChildren(`path`).attr(`style`,i),T(n,b),n.intersect=function(e){return t.info(`Pill intersect`,n,{radius:d,point:e}),G.polygon(n,h,e)},s}e(Ne,`halfRoundedRectangle`);var Pe=e((e,t,n,r,i)=>[`M${e+i},${t}`,`L${e+n-i},${t}`,`L${e+n},${t-r/2}`,`L${e+n-i},${t-r}`,`L${e+i},${t-r}`,`L${e},${t-r/2}`,`Z`].join(` `),`createHexagonPathD`);async function Fe(e,t){let{labelStyles:n,nodeStyles:r}=y(t),i=t.look===`neo`?3.5:4;t.labelStyle=n;let a=t.padding??0,o=t.look===`neo`?70:a,s=t.look===`neo`?32:a;if(t.width||t.height){let e=(t.height??0)/i;t.width=(t?.width??0)-2*e-s,t.height=(t.height??0)-o}let{shapeSvg:c,bbox:l}=await C(e,t,E(t)),u=(t?.height?t?.height:l.height)+o,d=u/i,f=(t?.width?t?.width:l.width)+2*d+s,p=[{x:d,y:0},{x:f-d,y:0},{x:f,y:-u/2},{x:f-d,y:-u},{x:d,y:-u},{x:0,y:-u/2}],m,{cssStyles:h}=t;if(t.look===`handDrawn`){let e=S.svg(c),n=v(t,{}),r=Pe(0,0,f,u,d),i=e.path(r,n);m=c.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-f/2}, ${u/2})`),h&&m.attr(`style`,h)}else m=q(c,f,u,p);return r&&m.attr(`style`,r),t.width=f,t.height=u,T(t,m),t.intersect=function(e){return G.polygon(t,p,e)},c}e(Fe,`hexagon`);async function Ie(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.label=``,n.labelStyle=r;let{shapeSvg:a}=await C(e,n,E(n)),o=Math.max(30,n?.width??0),s=Math.max(30,n?.height??0),{cssStyles:c}=n,l=S.svg(a),u=v(n,{});n.look!==`handDrawn`&&(u.roughness=0,u.fillStyle=`solid`);let d=[{x:0,y:0},{x:o,y:0},{x:0,y:s},{x:o,y:s}],f=D(d),p=l.path(f,u),m=a.insert(()=>p,`:first-child`);return m.attr(`class`,`basic label-container outer-path`),c&&n.look!==`handDrawn`&&m.selectChildren(`path`).attr(`style`,c),i&&n.look!==`handDrawn`&&m.selectChildren(`path`).attr(`style`,i),m.attr(`transform`,`translate(${-o/2}, ${-s/2})`),T(n,m),n.intersect=function(e){return t.info(`Pill intersect`,n,{points:d}),G.polygon(n,d,e)},a}e(Ie,`hourglass`);async function Le(e,n,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:a}=y(n);n.labelStyle=a;let o=n.assetHeight??48,s=n.assetWidth??48,c=Math.max(o,s),l=i?.wrappingWidth;n.width=Math.max(c,l??0);let{shapeSvg:u,bbox:d,label:f}=await C(e,n,`icon-shape default`),p=n.pos===`t`,h=c,g=c,{nodeBorder:_}=r,{stylesMap:b}=x(n),w=-g/2,E=-h/2,D=n.label?8:0,O=S.svg(u),k=v(n,{stroke:`none`,fill:`none`});n.look!==`handDrawn`&&(k.roughness=0,k.fillStyle=`solid`);let A=O.rectangle(w,E,g,h,k),j=Math.max(g,d.width),M=h+d.height+D,N=O.rectangle(-j/2,-M/2,j,M,{...k,fill:`transparent`,stroke:`none`}),P=u.insert(()=>A,`:first-child`),F=u.insert(()=>N);if(n.icon){let e=u.append(`g`);e.html(`${await m(n.icon,{height:c,width:c,fallbackPrefix:``})}`);let t=e.node().getBBox(),r=t.width,i=t.height,a=t.x,o=t.y;e.attr(`transform`,`translate(${-r/2-a},${p?d.height/2+D/2-i/2-o:-d.height/2-D/2-i/2-o})`),e.attr(`style`,`color: ${b.get(`stroke`)??_};`)}return f.attr(`transform`,`translate(${-d.width/2-(d.x-(d.left??0))},${p?-M/2:M/2-d.height})`),P.attr(`transform`,`translate(0,${p?d.height/2+D/2:-d.height/2-D/2})`),T(n,F),n.intersect=function(e){if(t.info(`iconSquare intersect`,n,e),!n.label)return G.rect(n,e);let r=n.x??0,i=n.y??0,a=n.height??0,o=[];return o=p?[{x:r-d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2+d.height+D},{x:r+g/2,y:i-a/2+d.height+D},{x:r+g/2,y:i+a/2},{x:r-g/2,y:i+a/2},{x:r-g/2,y:i-a/2+d.height+D},{x:r-d.width/2,y:i-a/2+d.height+D}]:[{x:r-g/2,y:i-a/2},{x:r+g/2,y:i-a/2},{x:r+g/2,y:i-a/2+h},{x:r+d.width/2,y:i-a/2+h},{x:r+d.width/2/2,y:i+a/2},{x:r-d.width/2,y:i+a/2},{x:r-d.width/2,y:i-a/2+h},{x:r-g/2,y:i-a/2+h}],G.polygon(n,o,e)},u}e(Le,`icon`);async function Re(e,n,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:a}=y(n);n.labelStyle=a;let o=n.assetHeight??48,s=n.assetWidth??48,c=Math.max(o,s),l=i?.wrappingWidth;n.width=Math.max(c,l??0);let{shapeSvg:u,bbox:d,label:f}=await C(e,n,`icon-shape default`),p=n.label?8:0,h=n.pos===`t`,{nodeBorder:g,mainBkg:_}=r,{stylesMap:b}=x(n),w=S.svg(u),E=v(n,{});n.look!==`handDrawn`&&(E.roughness=0,E.fillStyle=`solid`),E.stroke=b.get(`fill`)??_;let D=u.append(`g`);n.icon&&D.html(`${await m(n.icon,{height:c,width:c,fallbackPrefix:``})}`);let O=D.node().getBBox(),k=O.width,A=O.height,j=O.x,M=O.y,N=Math.max(k,A)*Math.SQRT2+40,P=w.circle(0,0,N,E),F=Math.max(N,d.width),I=N+d.height+p,L=w.rectangle(-F/2,-I/2,F,I,{...E,fill:`transparent`,stroke:`none`}),ee=u.insert(()=>P,`:first-child`),R=u.insert(()=>L);return D.attr(`transform`,`translate(${-k/2-j},${h?d.height/2+p/2-A/2-M:-d.height/2-p/2-A/2-M})`),D.attr(`style`,`color: ${b.get(`stroke`)??g};`),f.attr(`transform`,`translate(${-d.width/2-(d.x-(d.left??0))},${h?-I/2:I/2-d.height})`),ee.attr(`transform`,`translate(0,${h?d.height/2+p/2:-d.height/2-p/2})`),T(n,R),n.intersect=function(e){return t.info(`iconSquare intersect`,n,e),G.rect(n,e)},u}e(Re,`iconCircle`);async function ze(e,n,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:a}=y(n);n.labelStyle=a;let o=n.assetHeight??48,s=n.assetWidth??48,c=Math.max(o,s),l=i?.wrappingWidth;n.width=Math.max(c,l??0);let{shapeSvg:u,bbox:d,halfPadding:f,label:p}=await C(e,n,`icon-shape default`),h=n.pos===`t`,g=c+f*2,_=c+f*2,{nodeBorder:b,mainBkg:w}=r,{stylesMap:E}=x(n),D=-_/2,O=-g/2,k=n.label?8:0,A=S.svg(u),j=v(n,{});n.look!==`handDrawn`&&(j.roughness=0,j.fillStyle=`solid`),j.stroke=E.get(`fill`)??w;let M=A.path(N(D,O,_,g,5),j),P=Math.max(_,d.width),F=g+d.height+k,I=A.rectangle(-P/2,-F/2,P,F,{...j,fill:`transparent`,stroke:`none`}),L=u.insert(()=>M,`:first-child`).attr(`class`,`icon-shape2`),ee=u.insert(()=>I);if(n.icon){let e=u.append(`g`);e.html(`${await m(n.icon,{height:c,width:c,fallbackPrefix:``})}`);let t=e.node().getBBox(),r=t.width,i=t.height,a=t.x,o=t.y;e.attr(`transform`,`translate(${-r/2-a},${h?d.height/2+k/2-i/2-o:-d.height/2-k/2-i/2-o})`),e.attr(`style`,`color: ${E.get(`stroke`)??b};`)}return p.attr(`transform`,`translate(${-d.width/2-(d.x-(d.left??0))},${h?-F/2:F/2-d.height})`),L.attr(`transform`,`translate(0,${h?d.height/2+k/2:-d.height/2-k/2})`),T(n,ee),n.intersect=function(e){if(t.info(`iconSquare intersect`,n,e),!n.label)return G.rect(n,e);let r=n.x??0,i=n.y??0,a=n.height??0,o=[];return o=h?[{x:r-d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2+d.height+k},{x:r+_/2,y:i-a/2+d.height+k},{x:r+_/2,y:i+a/2},{x:r-_/2,y:i+a/2},{x:r-_/2,y:i-a/2+d.height+k},{x:r-d.width/2,y:i-a/2+d.height+k}]:[{x:r-_/2,y:i-a/2},{x:r+_/2,y:i-a/2},{x:r+_/2,y:i-a/2+g},{x:r+d.width/2,y:i-a/2+g},{x:r+d.width/2/2,y:i+a/2},{x:r-d.width/2,y:i+a/2},{x:r-d.width/2,y:i-a/2+g},{x:r-_/2,y:i-a/2+g}],G.polygon(n,o,e)},u}e(ze,`iconRounded`);async function Be(e,n,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:a}=y(n);n.labelStyle=a;let o=n.assetHeight??48,s=n.assetWidth??48,c=Math.max(o,s),l=i?.wrappingWidth;n.width=Math.max(c,l??0);let{shapeSvg:u,bbox:d,halfPadding:f,label:p}=await C(e,n,`icon-shape default`),h=n.pos===`t`,g=c+f*2,_=c+f*2,{nodeBorder:b,mainBkg:w}=r,{stylesMap:E}=x(n),D=-_/2,O=-g/2,k=n.label?8:0,A=S.svg(u),j=v(n,{});n.look!==`handDrawn`&&(j.roughness=0,j.fillStyle=`solid`),j.stroke=E.get(`fill`)??w;let M=A.path(N(D,O,_,g,.1),j),P=Math.max(_,d.width),F=g+d.height+k,I=A.rectangle(-P/2,-F/2,P,F,{...j,fill:`transparent`,stroke:`none`}),L=u.insert(()=>M,`:first-child`),ee=u.insert(()=>I);if(n.icon){let e=u.append(`g`);e.html(`${await m(n.icon,{height:c,width:c,fallbackPrefix:``})}`);let t=e.node().getBBox(),r=t.width,i=t.height,a=t.x,o=t.y;e.attr(`transform`,`translate(${-r/2-a},${h?d.height/2+k/2-i/2-o:-d.height/2-k/2-i/2-o})`),e.attr(`style`,`color: ${E.get(`stroke`)??b};`)}return p.attr(`transform`,`translate(${-d.width/2-(d.x-(d.left??0))},${h?-F/2:F/2-d.height})`),L.attr(`transform`,`translate(0,${h?d.height/2+k/2:-d.height/2-k/2})`),T(n,ee),n.intersect=function(e){if(t.info(`iconSquare intersect`,n,e),!n.label)return G.rect(n,e);let r=n.x??0,i=n.y??0,a=n.height??0,o=[];return o=h?[{x:r-d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2},{x:r+d.width/2,y:i-a/2+d.height+k},{x:r+_/2,y:i-a/2+d.height+k},{x:r+_/2,y:i+a/2},{x:r-_/2,y:i+a/2},{x:r-_/2,y:i-a/2+d.height+k},{x:r-d.width/2,y:i-a/2+d.height+k}]:[{x:r-_/2,y:i-a/2},{x:r+_/2,y:i-a/2},{x:r+_/2,y:i-a/2+g},{x:r+d.width/2,y:i-a/2+g},{x:r+d.width/2/2,y:i+a/2},{x:r-d.width/2,y:i+a/2},{x:r-d.width/2,y:i-a/2+g},{x:r-_/2,y:i-a/2+g}],G.polygon(n,o,e)},u}e(Be,`iconSquare`);async function Ve(e,n,{config:{flowchart:r}}){let i=new Image;i.src=n?.img??``,await i.decode();let a=Number(i.naturalWidth.toString().replace(`px`,``)),o=Number(i.naturalHeight.toString().replace(`px`,``));n.imageAspectRatio=a/o;let{labelStyles:s}=y(n);n.labelStyle=s;let c=r?.wrappingWidth;n.defaultWidth=r?.wrappingWidth;let l=Math.max(n.label?c??0:0,n?.assetWidth??a),u=n.constraint===`on`&&n?.assetHeight?n.assetHeight*n.imageAspectRatio:l,d=n.constraint===`on`?u/n.imageAspectRatio:n?.assetHeight??o;n.width=Math.max(u,c??0);let{shapeSvg:f,bbox:p,label:m}=await C(e,n,`image-shape default`),h=n.pos===`t`,g=-u/2,_=-d/2,b=n.label?8:0,x=S.svg(f),w=v(n,{});n.look!==`handDrawn`&&(w.roughness=0,w.fillStyle=`solid`);let E=x.rectangle(g,_,u,d,w),D=Math.max(u,p.width),O=d+p.height+b,k=x.rectangle(-D/2,-O/2,D,O,{...w,fill:`none`,stroke:`none`}),A=f.insert(()=>E,`:first-child`),j=f.insert(()=>k);if(n.img){let e=f.append(`image`);e.attr(`href`,n.img),e.attr(`width`,u),e.attr(`height`,d),e.attr(`preserveAspectRatio`,`none`),e.attr(`transform`,`translate(${-u/2},${h?O/2-d:-O/2})`)}return m.attr(`transform`,`translate(${-p.width/2-(p.x-(p.left??0))},${h?-d/2-p.height/2-b/2:d/2-p.height/2+b/2})`),A.attr(`transform`,`translate(0,${h?p.height/2+b/2:-p.height/2-b/2})`),T(n,j),n.intersect=function(e){if(t.info(`iconSquare intersect`,n,e),!n.label)return G.rect(n,e);let r=n.x??0,i=n.y??0,a=n.height??0,o=[];return o=h?[{x:r-p.width/2,y:i-a/2},{x:r+p.width/2,y:i-a/2},{x:r+p.width/2,y:i-a/2+p.height+b},{x:r+u/2,y:i-a/2+p.height+b},{x:r+u/2,y:i+a/2},{x:r-u/2,y:i+a/2},{x:r-u/2,y:i-a/2+p.height+b},{x:r-p.width/2,y:i-a/2+p.height+b}]:[{x:r-u/2,y:i-a/2},{x:r+u/2,y:i-a/2},{x:r+u/2,y:i-a/2+d},{x:r+p.width/2,y:i-a/2+d},{x:r+p.width/2/2,y:i+a/2},{x:r-p.width/2,y:i+a/2},{x:r-p.width/2,y:i-a/2+d},{x:r-u/2,y:i-a/2+d}],G.polygon(n,o,e)},f}e(Ve,`imageSquare`);async function He(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=i,o=t.look===`neo`?i*2:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=Math.max(c.width+(o??0)*2,t?.width??0),u=Math.max(c.height+(a??0)*2,t?.height??0),d=[{x:0,y:0},{x:l,y:0},{x:l+3*u/6,y:-u},{x:-3*u/6,y:-u}],f,{cssStyles:p}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(d),i=e.path(r,n);f=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-l/2}, ${u/2})`),p&&f.attr(`style`,p)}else f=q(s,l,u,d);return r&&f.attr(`style`,r),t.width=l,t.height=u,T(t,f),t.intersect=function(e){return G.polygon(t,d,e)},s}e(He,`inv_trapezoid`);async function Ue(e,t){let{shapeSvg:n,bbox:r,label:i}=await C(e,t,`label`),a=n.insert(`rect`,`:first-child`);return a.attr(`width`,.1).attr(`height`,.1),n.attr(`class`,`label edgeLabel`),i.attr(`transform`,`translate(${-(r.width/2)-(r.x-(r.left??0))}, ${-(r.height/2)-(r.y-(r.top??0))})`),T(t,a),t.intersect=function(e){return G.rect(t,e)},n}e(Ue,`labelRect`);async function We(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=i,o=t.look===`neo`?i*2:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.height??c.height)+a,u=(t?.width??c.width)+o,d=[{x:0,y:0},{x:u+3*l/6,y:0},{x:u,y:-l},{x:-(3*l)/6,y:-l}],f,{cssStyles:p}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(d),i=e.path(r,n);f=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-u/2}, ${l/2})`),p&&f.attr(`style`,p)}else f=q(s,u,l,d);return r&&f.attr(`style`,r),t.width=u,t.height=l,T(t,f),t.intersect=function(e){return G.polygon(t,d,e)},s}e(We,`lean_left`);async function Ge(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=i,o=t.look===`neo`?i*2:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.height??c.height)+a,u=(t?.width??c.width)+o,d=[{x:-3*l/6,y:0},{x:u,y:0},{x:u+3*l/6,y:-l},{x:0,y:-l}],f,{cssStyles:p}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(d),i=e.path(r,n);f=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-u/2}, ${l/2})`),p&&f.attr(`style`,p)}else f=q(s,u,l,d);return r&&f.attr(`style`,r),t.width=u,t.height=l,T(t,f),t.intersect=function(e){return G.polygon(t,d,e)},s}e(Ge,`lean_right`);function Ke(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.label=``,n.labelStyle=r;let a=e.insert(`g`).attr(`class`,E(n)).attr(`id`,n.domId??n.id),{cssStyles:o}=n,s=Math.max(35,n?.width??0),c=Math.max(35,n?.height??0),l=[{x:s,y:0},{x:0,y:c+7/2},{x:s-14,y:c+7/2},{x:0,y:2*c},{x:s,y:c-7/2},{x:14,y:c-7/2}],u=S.svg(a),d=v(n,{});n.look!==`handDrawn`&&(d.roughness=0,d.fillStyle=`solid`);let f=D(l),p=u.path(f,d),m=a.insert(()=>p,`:first-child`);return m.attr(`class`,`outer-path`),o&&n.look!==`handDrawn`&&m.selectAll(`path`).attr(`style`,o),i&&n.look!==`handDrawn`&&m.selectAll(`path`).attr(`style`,i),m.attr(`transform`,`translate(-${s/2},${-c})`),T(n,m),n.intersect=function(e){return t.info(`lightningBolt intersect`,n,e),G.polygon(n,l,e)},a}e(Ke,`lightningBolt`);var qe=e((e,t,n,r,i,a,o)=>[`M${e},${t+a}`,`a${i},${a} 0,0,0 ${n},0`,`a${i},${a} 0,0,0 ${-n},0`,`l0,${r}`,`a${i},${a} 0,0,0 ${n},0`,`l0,${-r}`,`M${e},${t+a+o}`,`a${i},${a} 0,0,0 ${n},0`].join(` `),`createCylinderPathD`),Je=e((e,t,n,r,i,a,o)=>[`M${e},${t+a}`,`M${e+n},${t+a}`,`a${i},${a} 0,0,0 ${-n},0`,`l0,${r}`,`a${i},${a} 0,0,0 ${n},0`,`l0,${-r}`,`M${e},${t+a+o}`,`a${i},${a} 0,0,0 ${n},0`].join(` `),`createOuterCylinderPathD`),Ye=e((e,t,n,r,i,a)=>[`M${e-n/2},${-r/2}`,`a${i},${a} 0,0,0 ${n},0`].join(` `),`createInnerCylinderPathD`),Xe=10,Ze=10;async function Qe(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?24:i;if(t.width||t.height){let e=t.width??0;t.width=(t.width??0)-a,t.widtho,`:first-child`).attr(`class`,`line`),g=s.insert(()=>a,`:first-child`),g.attr(`class`,`basic label-container`),_&&g.attr(`style`,_)}else{let e=qe(0,0,u,m,d,f,h);g=s.insert(`path`,`:first-child`).attr(`d`,e).attr(`class`,`basic label-container outer-path`).attr(`style`,p(_)).attr(`style`,r)}return g.attr(`label-offset-y`,f),g.attr(`transform`,`translate(${-u/2}, ${-(m/2+f)})`),T(t,g),l.attr(`transform`,`translate(${-(c.width/2)-(c.x-(c.left??0))}, ${-(c.height/2)+f-(c.y-(c.top??0))})`),t.intersect=function(e){let n=G.rect(t,e),r=n.x-(t.x??0);if(d!=0&&(Math.abs(r)<(t.width??0)/2||Math.abs(r)==(t.width??0)/2&&Math.abs(n.y-(t.y??0))>(t.height??0)/2-f)){let i=f*f*(1-r*r/(d*d));i>0&&(i=Math.sqrt(i)),i=f-i,e.y-(t.y??0)>0&&(i=-i),n.y+=i}return n},s}e(Qe,`linedCylinder`);async function $e(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i;(t.width||t.height)&&(t.width=(t.width??0)*10/11-a*2,t.width<10&&(t.width=10),t.height=(t?.height??0)-o*2,t.height<10&&(t.height=10));let{shapeSvg:s,bbox:c,label:l}=await C(e,t,E(t)),u=(t?.width?t?.width:c.width)+(a??0)*2,d=(t?.height?t?.height:c.height)+(o??0)*2,f=t.look===`neo`?d/4:d/8,p=d+f,{cssStyles:m}=t,h=S.svg(s),g=v(t,{});t.look!==`handDrawn`&&(g.roughness=0,g.fillStyle=`solid`);let _=[{x:-u/2-u/2*.1,y:-p/2},{x:-u/2-u/2*.1,y:p/2},...O(-u/2-u/2*.1,p/2,u/2+u/2*.1,p/2,f,.8),{x:u/2+u/2*.1,y:-p/2},{x:-u/2-u/2*.1,y:-p/2},{x:-u/2,y:-p/2},{x:-u/2,y:p/2*1.1},{x:-u/2,y:-p/2}],b=h.polygon(_.map(e=>[e.x,e.y]),g),x=s.insert(()=>b,`:first-child`);return x.attr(`class`,`basic label-container outer-path`),m&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,m),r&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,r),x.attr(`transform`,`translate(0,${-f/2})`),l.attr(`transform`,`translate(${-u/2+(t.padding??0)+u/2*.1/2-(c.x-(c.left??0))},${-d/2+(t.padding??0)-f/2-(c.y-(c.top??0))})`),T(t,x),t.intersect=function(e){return G.polygon(t,_,e)},s}e($e,`linedWaveEdgedRect`);async function et(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i,s=t.look===`neo`?10:5;(t.width||t.height)&&(t.width=Math.max((t?.width??0)-a*2-2*s,10),t.height=Math.max((t?.height??0)-o*2-2*s,10));let{shapeSvg:c,bbox:l,label:u}=await C(e,t,E(t)),d=(t?.width?t?.width:l.width)+a*2+2*s,f=(t?.height?t?.height:l.height)+o*2+2*s,p=d-2*s,m=f-2*s,h=-p/2,g=-m/2,{cssStyles:_}=t,b=S.svg(c),x=v(t,{}),w=[{x:h-s,y:g+s},{x:h-s,y:g+m+s},{x:h+p-s,y:g+m+s},{x:h+p-s,y:g+m},{x:h+p,y:g+m},{x:h+p,y:g+m-s},{x:h+p+s,y:g+m-s},{x:h+p+s,y:g-s},{x:h+s,y:g-s},{x:h+s,y:g},{x:h,y:g},{x:h,y:g+s}],O=[{x:h,y:g+s},{x:h+p-s,y:g+s},{x:h+p-s,y:g+m},{x:h+p,y:g+m},{x:h+p,y:g},{x:h,y:g}];t.look!==`handDrawn`&&(x.roughness=0,x.fillStyle=`solid`);let k=D(w),j=b.path(k,x),M=D(O),N=b.path(M,x);t.look!==`handDrawn`&&(j=A(j),N=A(N));let P=c.insert(`g`,`:first-child`);return P.insert(()=>j),P.insert(()=>N),P.attr(`class`,`basic label-container outer-path`),_&&t.look!==`handDrawn`&&P.selectAll(`path`).attr(`style`,_),r&&t.look!==`handDrawn`&&P.selectAll(`path`).attr(`style`,r),u.attr(`transform`,`translate(${-(l.width/2)-s-(l.x-(l.left??0))}, ${-(l.height/2)+s-(l.y-(l.top??0))})`),T(t,P),t.intersect=function(e){return G.polygon(t,w,e)},c}e(et,`multiRect`);async function tt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let{shapeSvg:i,bbox:a,label:o}=await C(e,t,E(t)),s=t.padding??0,c=t.look===`neo`?16:s,l=t.look===`neo`?12:s,u=!0;(t.width||t.height)&&(u=!1,t.width=(t?.width??0)-c*2,t.height=(t?.height??0)-l*3);let d=Math.max(a.width,t?.width??0)+c*2,f=Math.max(a.height,t?.height??0)+l*3,p=t.look===`neo`?f/4:f/8,m=f+(u?p/2:-p/2),h=-d/2,g=-m/2,{cssStyles:_}=t,b=O(h-10,g+m+10,h+d-10,g+m+10,p,.8),x=b?.[b.length-1],w=[{x:h-10,y:g+10},{x:h-10,y:g+m+10},...b,{x:h+d-10,y:x.y-10},{x:h+d,y:x.y-10},{x:h+d,y:x.y-20},{x:h+d+10,y:x.y-20},{x:h+d+10,y:g-10},{x:h+10,y:g-10},{x:h+10,y:g},{x:h,y:g},{x:h,y:g+10}],k=[{x:h,y:g+10},{x:h+d-10,y:g+10},{x:h+d-10,y:x.y-10},{x:h+d,y:x.y-10},{x:h+d,y:g},{x:h,y:g}],A=S.svg(i),j=v(t,{});t.look!==`handDrawn`&&(j.roughness=0,j.fillStyle=`solid`);let M=D(w),N=A.path(M,j),P=D(k),F=A.path(P,j),I=i.insert(()=>N,`:first-child`);return I.insert(()=>F),I.attr(`class`,`basic label-container outer-path`),_&&t.look!==`handDrawn`&&I.selectAll(`path`).attr(`style`,_),r&&t.look!==`handDrawn`&&I.selectAll(`path`).attr(`style`,r),I.attr(`transform`,`translate(0,${-p/2})`),o.attr(`transform`,`translate(${-(a.width/2)-10-(a.x-(a.left??0))}, ${-(a.height/2)+10-p/2-(a.y-(a.top??0))})`),T(t,I),t.intersect=function(e){return G.polygon(t,w,e)},i}e(tt,`multiWaveEdgedRectangle`);async function nt(e,t,{config:{themeVariables:n}}){let{labelStyles:r,nodeStyles:i}=y(t);t.labelStyle=r,t.useHtmlLabels||o(s())||(t.centerLabel=!0);let{shapeSvg:a,bbox:c,label:l}=await C(e,t,E(t)),u=Math.max(c.width+(t.padding??0)*2,t?.width??0),d=Math.max(c.height+(t.padding??0)*2,t?.height??0),f=-u/2,p=-d/2,{cssStyles:m}=t,h=S.svg(a),g=v(t,{fill:n.noteBkgColor,stroke:n.noteBorderColor});t.look!==`handDrawn`&&(g.roughness=0,g.fillStyle=`solid`);let _=h.rectangle(f,p,u,d,g),b=a.insert(()=>_,`:first-child`);return b.attr(`class`,`basic label-container outer-path`),l.attr(`class`,`label noteLabel`),m&&t.look!==`handDrawn`&&b.selectAll(`path`).attr(`style`,m),i&&t.look!==`handDrawn`&&b.selectAll(`path`).attr(`style`,i),l.attr(`transform`,`translate(${-c.width/2-(c.x-(c.left??0))}, ${-(c.height/2)-(c.y-(c.top??0))})`),T(t,b),t.intersect=function(e){return G.rect(t,e)},a}e(nt,`note`);var rt=e((e,t,n)=>[`M${e+n/2},${t}`,`L${e+n},${t-n/2}`,`L${e+n/2},${t-n}`,`L${e},${t-n/2}`,`Z`].join(` `),`createDecisionBoxPathD`);async function it(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let{shapeSvg:i,bbox:a}=await C(e,t,E(t)),o=a.width+(t.padding??0)+(a.height+(t.padding??0)),s=.5,c=[{x:o/2,y:0},{x:o,y:-o/2},{x:o/2,y:-o},{x:0,y:-o/2}],l,{cssStyles:u}=t;if(t.look===`handDrawn`){let e=S.svg(i),n=v(t,{}),r=rt(0,0,o),a=e.path(r,n);l=i.insert(()=>a,`:first-child`).attr(`transform`,`translate(${-o/2+s}, ${o/2})`),u&&l.attr(`style`,u)}else l=q(i,o,o,c),l.attr(`transform`,`translate(${-o/2+s}, ${o/2})`);return r&&l.attr(`style`,r),T(t,l),t.calcIntersect=function(e,t){let n=e.width,r=[{x:n/2,y:0},{x:n,y:-n/2},{x:n/2,y:-n},{x:0,y:-n/2}],i=G.polygon(e,r,t);return{x:i.x-.5,y:i.y-.5}},t.intersect=function(e){return this.calcIntersect(t,e)},i}e(it,`question`);async function at(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?21:i??0,o=t.look===`neo`?12:i??0,{shapeSvg:s,bbox:c,label:l}=await C(e,t,E(t)),u=(t?.width??c.width)+(t.look===`neo`?a*2:a),d=(t?.height??c.height)+(t.look===`neo`?o*2:o),f=-u/2,p=-d/2,m=p/2,h=[{x:f+m,y:p},{x:f,y:0},{x:f+m,y:-p},{x:-f,y:-p},{x:-f,y:p}],{cssStyles:g}=t,_=S.svg(s),b=v(t,{});t.look!==`handDrawn`&&(b.roughness=0,b.fillStyle=`solid`);let x=D(h),w=_.path(x,b),O=s.insert(()=>w,`:first-child`);return O.attr(`class`,`basic label-container outer-path`),g&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,g),r&&t.look!==`handDrawn`&&O.selectAll(`path`).attr(`style`,r),O.attr(`transform`,`translate(${-m/2},0)`),l.attr(`transform`,`translate(${-m/2-c.width/2-(c.x-(c.left??0))}, ${-(c.height/2)-(c.y-(c.top??0))})`),T(t,O),t.intersect=function(e){return G.polygon(t,h,e)},s}e(at,`rect_left_inv_arrow`);async function ot(e,r){let{labelStyles:i,nodeStyles:a}=y(r);r.labelStyle=i;let s;s=r.cssClasses?`node `+r.cssClasses:`node default`;let c=e.insert(`g`).attr(`class`,s).attr(`id`,r.domId||r.id),u=c.insert(`g`),d=c.insert(`g`).attr(`class`,`label`).attr(`style`,a),f=r.description,p=r.label,m=await M(d,p,r.labelStyle,!0,!0),h={width:0,height:0};if(o(l())){let e=m.children[0],t=n(m);h=e.getBoundingClientRect(),t.attr(`width`,h.width),t.attr(`height`,h.height)}t.info(`Text 2`,f);let g=f||[],_=m.getBBox(),b=await M(d,Array.isArray(g)?g.join(`
    `):g,r.labelStyle,!0,!0),x=b.children[0],C=n(b);h=x.getBoundingClientRect(),C.attr(`width`,h.width),C.attr(`height`,h.height);let w=(r.padding||0)/2;n(b).attr(`transform`,`translate( `+(h.width>_.width?0:(_.width-h.width)/2)+`, `+(_.height+w+5)+`)`),n(m).attr(`transform`,`translate( `+(h.width<_.width?0:-(_.width-h.width)/2)+`, 0)`),h=d.node().getBBox(),d.attr(`transform`,`translate(`+-h.width/2+`, `+(-h.height/2-w+3)+`)`);let E=h.width+(r.padding||0),D=h.height+(r.padding||0),O=-h.width/2-w,k=-h.height/2-w,A,j;if(r.look===`handDrawn`){let e=S.svg(c),n=v(r,{}),i=e.path(N(O,k,E,D,r.rx||0),n),a=e.line(-h.width/2-w,-h.height/2-w+_.height+w,h.width/2+w,-h.height/2-w+_.height+w,n);j=c.insert(()=>(t.debug(`Rough node insert CXC`,i),a),`:first-child`),A=c.insert(()=>(t.debug(`Rough node insert CXC`,i),i),`:first-child`)}else A=u.insert(`rect`,`:first-child`),j=u.insert(`line`),A.attr(`class`,`outer title-state`).attr(`style`,a).attr(`x`,-h.width/2-w).attr(`y`,-h.height/2-w).attr(`width`,h.width+(r.padding||0)).attr(`height`,h.height+(r.padding||0)),j.attr(`class`,`divider`).attr(`x1`,-h.width/2-w).attr(`x2`,h.width/2+w).attr(`y1`,-h.height/2-w+_.height+w).attr(`y2`,-h.height/2-w+_.height+w);return T(r,A),r.intersect=function(e){return G.rect(r,e)},c}e(ot,`rectWithTitle`);async function st(e,t,{config:{themeVariables:n}}){let r=n?.radius??5;return we(e,t,{rx:r,ry:r,classes:``,labelPaddingX:(t?.padding??0)*1,labelPaddingY:(t?.padding??0)*1})}e(st,`roundedRect`);var Z=8;async function ct(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.look===`neo`?16:t.padding??0,a=t.look===`neo`?12:t.padding??0,{shapeSvg:o,bbox:s,label:c}=await C(e,t,E(t)),l=(t?.width??s.width)+i*2+(t.look===`neo`?Z:Z*2),u=(t?.height??s.height)+a*2,d=l-Z,f=u,m=Z-l/2,h=-u/2,{cssStyles:g}=t,_=S.svg(o),b=v(t,{});t.look!==`handDrawn`&&(b.roughness=0,b.fillStyle=`solid`);let x=[{x:m,y:h},{x:m+d,y:h},{x:m+d,y:h+f},{x:m-Z,y:h+f},{x:m-Z,y:h},{x:m,y:h},{x:m,y:h+f}],w=_.polygon(x.map(e=>[e.x,e.y]),b),D=o.insert(()=>w,`:first-child`);return D.attr(`class`,`basic label-container outer-path`).attr(`style`,p(g)),r&&t.look!==`handDrawn`&&D.selectAll(`path`).attr(`style`,r),g&&t.look!==`handDrawn`&&D.selectAll(`path`).attr(`style`,r),c.attr(`transform`,`translate(${Z/2-s.width/2-(s.x-(s.left??0))}, ${-(s.height/2)-(s.y-(s.top??0))})`),T(t,D),t.intersect=function(e){return G.rect(t,e)},o}e(ct,`shadedProcess`);async function lt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i;(t.width||t.height)&&(t.width=Math.max((t?.width??0)-a*2,10),t.height=Math.max((t?.height??0)/1.5-o*2,10));let{shapeSvg:s,bbox:c,label:l}=await C(e,t,E(t)),u=(t?.width?t?.width:c.width)+a*2,d=((t?.height?t?.height:c.height)+o*2)*1.5,f=u,p=d/1.5,m=-f/2,h=-p/2,{cssStyles:g}=t,_=S.svg(s),b=v(t,{});t.look!==`handDrawn`&&(b.roughness=0,b.fillStyle=`solid`);let x=[{x:m,y:h},{x:m,y:h+p},{x:m+f,y:h+p},{x:m+f,y:h-p/2}],w=D(x),O=_.path(w,b),k=s.insert(()=>O,`:first-child`);return k.attr(`class`,`basic label-container outer-path`),g&&t.look!==`handDrawn`&&k.selectChildren(`path`).attr(`style`,g),r&&t.look!==`handDrawn`&&k.selectChildren(`path`).attr(`style`,r),k.attr(`transform`,`translate(0, ${p/4})`),l.attr(`transform`,`translate(${-f/2+(t.padding??0)-(c.x-(c.left??0))}, ${-p/4+(t.padding??0)-(c.y-(c.top??0))})`),T(t,k),t.intersect=function(e){return G.polygon(t,x,e)},s}e(lt,`slopedRect`);async function ut(e,t){let n=t.padding??0,r=t.look===`neo`?16:n*2,i=t.look===`neo`?12:n;return we(e,t,{rx:0,ry:0,classes:``,labelPaddingX:t.labelPaddingX??r,labelPaddingY:i})}e(ut,`squareRect`);async function dt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?20:i,o=t.look===`neo`?12:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=c.height+(t.look===`neo`?o*2:o),u=c.width+l/4+(t.look===`neo`?a*2:a),d=l/2,{cssStyles:f}=t,p=S.svg(s),m=v(t,{});t.look!==`handDrawn`&&(m.roughness=0,m.fillStyle=`solid`);let h=[{x:-u/2+d,y:-l/2},{x:u/2-d,y:-l/2},...k(-u/2+d,0,d,50,90,270),{x:u/2-d,y:l/2},...k(u/2-d,0,d,50,270,450)],g=D(h),_=p.path(g,m),b=s.insert(()=>_,`:first-child`);return b.attr(`class`,`basic label-container outer-path`),f&&t.look!==`handDrawn`&&b.selectChildren(`path`).attr(`style`,f),r&&t.look!==`handDrawn`&&b.selectChildren(`path`).attr(`style`,r),T(t,b),t.intersect=function(e){return G.polygon(t,h,e)},s}e(dt,`stadium`);async function ft(e,t){return we(e,t,{rx:t.look===`neo`?3:5,ry:t.look===`neo`?3:5,classes:`flowchart-node`})}e(ft,`state`);function pt(e,t,{config:{themeVariables:n}}){let{labelStyles:r,nodeStyles:i}=y(t);t.labelStyle=r;let{cssStyles:a}=t,{lineColor:o,stateBorder:s,nodeBorder:c,nodeShadow:l}=n;(t.width||t.height)&&((t.width??0)<14&&(t.width=14),(t.height??0)<14&&(t.height=14)),t.width||=14,t.height||=14;let u=e.insert(`g`).attr(`class`,`node default`).attr(`id`,t.domId??t.id),d=S.svg(u),f=v(t,{});t.look!==`handDrawn`&&(f.roughness=0,f.fillStyle=`solid`);let p=d.circle(0,0,t.width,{...f,stroke:o,strokeWidth:2}),m=s??c,h=(t.width??0)*5/14,g=d.circle(0,0,h,{...f,fill:m,stroke:m,strokeWidth:2,fillStyle:`solid`}),_=u.insert(()=>p,`:first-child`);if(_.insert(()=>g),t.look!==`handDrawn`&&_.attr(`class`,`outer-path`),a&&_.selectAll(`path`).attr(`style`,a),i&&_.selectAll(`path`).attr(`style`,i),t.width<25&&l&&t.look!==`handDrawn`){let t=e.node()?.ownerSVGElement?.id??``,n=t?`${t}-drop-shadow-small`:`drop-shadow-small`;_.attr(`style`,`filter:url(#${n})`)}return T(t,_),t.intersect=function(e){return G.circle(t,(t.width??0)/2,e)},u}e(pt,`stateEnd`);function mt(e,t,{config:{themeVariables:n}}){let{lineColor:r,nodeShadow:i}=n;(t.width||t.height)&&((t.width??0)<14&&(t.width=14),(t.height??0)<14&&(t.height=14)),t.width||=14,t.height||=14;let a=e.insert(`g`).attr(`class`,`node default`).attr(`id`,t.domId||t.id),o;if(t.look===`handDrawn`){let e=S.svg(a).circle(0,0,t.width,b(r));o=a.insert(()=>e),o.attr(`class`,`state-start`).attr(`r`,(t.width??7)/2).attr(`width`,t.width??14).attr(`height`,t.height??14)}else o=a.insert(`circle`,`:first-child`),o.attr(`class`,`state-start`).attr(`r`,(t.width??7)/2).attr(`width`,t.width??14).attr(`height`,t.height??14);if(t.width<25&&i&&t.look!==`handDrawn`){let t=e.node()?.ownerSVGElement?.id??``,n=t?`${t}-drop-shadow-small`:`drop-shadow-small`;o.attr(`style`,`filter:url(#${n})`)}return T(t,o),t.intersect=function(e){return G.circle(t,(t.width??7)/2,e)},a}e(mt,`stateStart`);var ht=8;async function gt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t?.padding??8,a=t.look===`neo`?28:i,o=t.look===`neo`?12:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.width??c.width)+2*ht+a,u=(t?.height??c.height)+o,d=l-2*ht,f=u,m=-l/2,h=-u/2,g=[{x:0,y:0},{x:d,y:0},{x:d,y:-f},{x:0,y:-f},{x:0,y:0},{x:-8,y:0},{x:d+8,y:0},{x:d+8,y:-f},{x:-8,y:-f},{x:-8,y:0}];if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=e.rectangle(m,h,d+16,f,n),i=e.line(m+ht,h,m+ht,h+f,n),a=e.line(m+ht+d,h,m+ht+d,h+f,n);s.insert(()=>i,`:first-child`),s.insert(()=>a,`:first-child`);let o=s.insert(()=>r,`:first-child`),{cssStyles:c}=t;o.attr(`class`,`basic label-container`).attr(`style`,p(c)),T(t,o)}else{let e=q(s,d,f,g);r&&e.attr(`style`,r),T(t,e)}return t.intersect=function(e){return G.polygon(t,g,e)},s}e(gt,`subroutine`);var _t=.2;async function vt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i;(t.width||t.height)&&(t.height=Math.max((t?.height??0)-o*2,10),t.width=Math.max((t?.width??0)-a*2-_t*(t.height+o*2),10));let{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.height?t?.height:c.height)+o*2,u=_t*l,d=_t*l,f=(t?.width?t?.width:c.width)+a*2+u-u,p=l,m=-f/2,h=-p/2,{cssStyles:g}=t,_=S.svg(s),b=v(t,{}),x=[{x:m-u/2,y:h},{x:m+f+u/2,y:h},{x:m+f+u/2,y:h+p},{x:m-u/2,y:h+p}],w=[{x:m+f-u/2,y:h+p},{x:m+f+u/2,y:h+p},{x:m+f+u/2,y:h+p-d}];t.look!==`handDrawn`&&(b.roughness=0,b.fillStyle=`solid`);let O=D(x),k=_.path(O,b),A=D(w),j=_.path(A,{...b,fillStyle:`solid`}),M=s.insert(()=>j,`:first-child`);return M.insert(()=>k,`:first-child`),M.attr(`class`,`basic label-container outer-path`),g&&t.look!==`handDrawn`&&M.selectAll(`path`).attr(`style`,g),r&&t.look!==`handDrawn`&&M.selectAll(`path`).attr(`style`,r),T(t,M),t.intersect=function(e){return G.polygon(t,x,e)},s}e(vt,`taggedRect`);async function yt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let{shapeSvg:i,bbox:a,label:o}=await C(e,t,E(t)),s=Math.max(a.width+(t.padding??0)*2,t?.width??0),c=Math.max(a.height+(t.padding??0)*2,t?.height??0),l=c/8,u=.2*s,d=.2*c,f=c+l,{cssStyles:p}=t,m=S.svg(i),h=v(t,{});t.look!==`handDrawn`&&(h.roughness=0,h.fillStyle=`solid`);let g=[{x:-s/2-s/2*.1,y:f/2},...O(-s/2-s/2*.1,f/2,s/2+s/2*.1,f/2,l,.8),{x:s/2+s/2*.1,y:-f/2},{x:-s/2-s/2*.1,y:-f/2}],_=-s/2+s/2*.1,b=-f/2-d*.4,x=[{x:_+s-u,y:(b+c)*1.3},{x:_+s,y:b+c-d},{x:_+s,y:(b+c)*.9},...O(_+s,(b+c)*1.25,_+s-u,(b+c)*1.3,-c*.02,.5)],w=D(g),k=m.path(w,h),A=D(x),j=m.path(A,{...h,fillStyle:`solid`}),M=i.insert(()=>j,`:first-child`);return M.insert(()=>k,`:first-child`),M.attr(`class`,`basic label-container outer-path`),p&&t.look!==`handDrawn`&&M.selectAll(`path`).attr(`style`,p),r&&t.look!==`handDrawn`&&M.selectAll(`path`).attr(`style`,r),M.attr(`transform`,`translate(0,${-l/2})`),o.attr(`transform`,`translate(${-s/2+(t.padding??0)-(a.x-(a.left??0))},${-c/2+(t.padding??0)-l/2-(a.y-(a.top??0))})`),T(t,M),t.intersect=function(e){return G.polygon(t,g,e)},i}e(yt,`taggedWaveEdgedRectangle`);async function bt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let{shapeSvg:i,bbox:a}=await C(e,t,E(t)),o=Math.max(a.width+(t.padding??0),t?.width||0),s=Math.max(a.height+(t.padding??0),t?.height||0),c=-o/2,l=-s/2,u=i.insert(`rect`,`:first-child`);return u.attr(`class`,`text`).attr(`style`,r).attr(`rx`,0).attr(`ry`,0).attr(`x`,c).attr(`y`,l).attr(`width`,o).attr(`height`,s),T(t,u),t.intersect=function(e){return G.rect(t,e)},i}e(bt,`text`);var xt=e((e,t,n,r,i,a)=>`M${e},${t} + a${i},${a} 0,0,1 0,${-r} + l${n},0 + a${i},${a} 0,0,1 0,${r} + M${n},${-r} + a${i},${a} 0,0,0 0,${r} + l${-n},0`,`createCylinderPathD`),St=e((e,t,n,r,i,a)=>[`M${e},${t}`,`M${e+n},${t}`,`a${i},${a} 0,0,0 0,${-r}`,`l${-n},0`,`a${i},${a} 0,0,0 0,${r}`,`l${n},0`].join(` `),`createOuterCylinderPathD`),Ct=e((e,t,n,r,i,a)=>[`M${e+n/2},${-r/2}`,`a${i},${a} 0,0,0 0,${r}`].join(` `),`createInnerCylinderPathD`),wt=5,Tt=10;async function Et(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?12:i/2;if(t.width||t.height){let e=t.height??0;t.height=(t.height??0)-a,t.heighta,`:first-child`),h=o.insert(()=>i,`:first-child`),h.attr(`class`,`basic label-container`),m&&h.attr(`style`,m)}else{let e=xt(0,0,f,l,d,u);h=o.insert(`path`,`:first-child`).attr(`d`,e).attr(`class`,`basic label-container`).attr(`style`,p(m)).attr(`style`,r),h.attr(`class`,`basic label-container outer-path`),m&&h.selectAll(`path`).attr(`style`,m),r&&h.selectAll(`path`).attr(`style`,r)}return h.attr(`label-offset-x`,d),h.attr(`transform`,`translate(${-f/2}, ${l/2} )`),c.attr(`transform`,`translate(${-(s.width/2)-d-(s.x-(s.left??0))}, ${-(s.height/2)-(s.y-(s.top??0))})`),T(t,h),t.intersect=function(e){let n=G.rect(t,e),r=n.y-(t.y??0);if(u!=0&&(Math.abs(r)<(t.height??0)/2||Math.abs(r)==(t.height??0)/2&&Math.abs(n.x-(t.x??0))>(t.width??0)/2-d)){let i=d*d*(1-r*r/(u*u));i!=0&&(i=Math.sqrt(Math.abs(i))),i=d-i,e.x-(t.x??0)>0&&(i=-i),n.x+=i}return n},o}e(Et,`tiltedCylinder`);async function Dt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=(t.look,i),o=t.look===`neo`?i*2:i,{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.height??c.height)+a,u=(t?.width??c.width)+o,d=[{x:-3*l/6,y:0},{x:u+3*l/6,y:0},{x:u,y:-l},{x:0,y:-l}],f,{cssStyles:p}=t;if(t.look===`handDrawn`){let e=S.svg(s),n=v(t,{}),r=D(d),i=e.path(r,n);f=s.insert(()=>i,`:first-child`).attr(`transform`,`translate(${-u/2}, ${l/2})`),p&&f.attr(`style`,p)}else f=q(s,u,l,d);return r&&f.attr(`style`,r),t.width=u,t.height=l,T(t,f),t.intersect=function(e){return G.polygon(t,d,e)},s}e(Dt,`trapezoid`);async function Ot(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i;(t.width||t.height)&&(t.height=(t.height??0)-o*2,t.height<5&&(t.height=5),t.width=(t.width??0)-a*2,t.width<15&&(t.width=15));let{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.width?t?.width:c.width)+a*2,u=(t?.height?t?.height:c.height)+o*2,{cssStyles:d}=t,f=S.svg(s),p=v(t,{});t.look!==`handDrawn`&&(p.roughness=0,p.fillStyle=`solid`);let m=[{x:-l/2*.8,y:-u/2},{x:l/2*.8,y:-u/2},{x:l/2,y:-u/2*.6},{x:l/2,y:u/2},{x:-l/2,y:u/2},{x:-l/2,y:-u/2*.6}],h=D(m),g=f.path(h,p),_=s.insert(()=>g,`:first-child`);return _.attr(`class`,`basic label-container outer-path`),d&&t.look!==`handDrawn`&&_.selectChildren(`path`).attr(`style`,d),r&&t.look!==`handDrawn`&&_.selectChildren(`path`).attr(`style`,r),T(t,_),t.intersect=function(e){return G.polygon(t,m,e)},s}e(Ot,`trapezoidalPentagon`);var kt=10,At=10;async function jt(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let a=n.padding??0,o=n.look===`neo`?a*2:a;(n.width||n.height)&&(n.width=((n?.width??0)-o)/2,n.widthO,`:first-child`).attr(`transform`,`translate(${-m/2}, ${m/2})`).attr(`class`,`outer-path`);return _&&n.look!==`handDrawn`&&k.selectChildren(`path`).attr(`style`,_),i&&n.look!==`handDrawn`&&k.selectChildren(`path`).attr(`style`,i),n.width=p,n.height=m,T(n,k),d.attr(`transform`,`translate(${-u.width/2-(u.x-(u.left??0))}, ${m/2-(u.height+(n.padding??0)/(f?2:1)-(u.y-(u.top??0)))})`),n.intersect=function(e){return t.info(`Triangle intersect`,n,g,e),G.polygon(n,g,e)},s}e(jt,`triangle`);async function Mt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?12:i,s=!0;(t.width||t.height)&&(s=!1,t.width=(t?.width??0)-a*2,t.width<10&&(t.width=10),t.height=(t?.height??0)-o*2,t.height<10&&(t.height=10));let{shapeSvg:c,bbox:l,label:u}=await C(e,t,E(t)),d=(t?.width?t?.width:l.width)+(a??0)*2,f=(t?.height?t?.height:l.height)+(o??0)*2,p=t.look===`neo`?f/4:f/8,m=f+(s?p:-p),{cssStyles:h}=t,g=14-d,_=g>0?g/2:0,b=S.svg(c),x=v(t,{});t.look!==`handDrawn`&&(x.roughness=0,x.fillStyle=`solid`);let w=[{x:-d/2-_,y:m/2},...O(-d/2-_,m/2,d/2+_,m/2,p,.8),{x:d/2+_,y:-m/2},{x:-d/2-_,y:-m/2}],k=D(w),A=b.path(k,x),j=c.insert(()=>A,`:first-child`);return j.attr(`class`,`basic label-container outer-path`),h&&t.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,h),r&&t.look!==`handDrawn`&&j.selectAll(`path`).attr(`style`,r),j.attr(`transform`,`translate(0,${-p/2})`),u.attr(`transform`,`translate(${-d/2+(t.padding??0)-(l.x-(l.left??0))},${-f/2+(t.padding??0)-p-(l.y-(l.top??0))})`),T(t,j),t.intersect=function(e){return G.polygon(t,w,e)},c}e(Mt,`waveEdgedRectangle`);async function Nt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.padding??0,a=t.look===`neo`?16:i,o=t.look===`neo`?20:i;if(t.width||t.height){t.width=t?.width??0,t.width<20&&(t.width=20),t.height=t?.height??0,t.height<10&&(t.height=10);let e=Math.min(t.height*.2,t.height/4);t.height=Math.ceil(t.height-o-20/9*e),t.width-=a*2}let{shapeSvg:s,bbox:c}=await C(e,t,E(t)),l=(t?.width?t?.width:c.width)+a*2,u=(t?.height?t?.height:c.height)+o,d=u/8,f=u+d*2,{cssStyles:p}=t,m=S.svg(s),h=v(t,{});t.look!==`handDrawn`&&(h.roughness=0,h.fillStyle=`solid`);let g=[{x:-l/2,y:f/2},...O(-l/2,f/2,l/2,f/2,d,1),{x:l/2,y:-f/2},...O(l/2,-f/2,-l/2,-f/2,d,-1)],_=D(g),b=m.path(_,h),x=s.insert(()=>b,`:first-child`);return x.attr(`class`,`basic label-container`),p&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,p),r&&t.look!==`handDrawn`&&x.selectAll(`path`).attr(`style`,r),T(t,x),t.intersect=function(e){return G.polygon(t,g,e)},s}e(Nt,`waveRectangle`);var Q=10;async function Pt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let i=t.look===`neo`?16:t.padding??0,a=t.look===`neo`?12:t.padding??0;(t.width||t.height)&&(t.width=Math.max((t?.width??0)-i*2-Q,10),t.height=Math.max((t?.height??0)-a*2-Q,10));let{shapeSvg:o,bbox:s,label:c}=await C(e,t,E(t)),l=(t?.width?t?.width:s.width)+i*2+Q,u=(t?.height?t?.height:s.height)+a*2+Q,d=l-Q,f=u-Q,p=-d/2,m=-f/2,{cssStyles:h}=t,g=S.svg(o),_=v(t,{}),b=[{x:p-Q,y:m-Q},{x:p-Q,y:m+f},{x:p+d,y:m+f},{x:p+d,y:m-Q}],x=`M${p-Q},${m-Q} L${p+d},${m-Q} L${p+d},${m+f} L${p-Q},${m+f} L${p-Q},${m-Q} + M${p-Q},${m} L${p+d},${m} + M${p},${m-Q} L${p},${m+f}`;t.look!==`handDrawn`&&(_.roughness=0,_.fillStyle=`solid`);let w=g.path(x,_),D=o.insert(()=>w,`:first-child`);return D.attr(`transform`,`translate(${Q/2}, ${Q/2})`),D.attr(`class`,`basic label-container outer-path`),h&&t.look!==`handDrawn`&&D.selectAll(`path`).attr(`style`,h),r&&t.look!==`handDrawn`&&D.selectAll(`path`).attr(`style`,r),c.attr(`transform`,`translate(${-(s.width/2)+Q/2-(s.x-(s.left??0))}, ${-(s.height/2)+Q/2-(s.y-(s.top??0))})`),T(t,D),t.intersect=function(e){return G.polygon(t,b,e)},o}e(Pt,`windowPane`);var Ft=new Set([`redux-color`,`redux-dark-color`]),It=new Set([`redux`,`redux-dark`,`redux-color`,`redux-dark-color`]);async function Lt(e,t){let r=t;r.alias&&(t.label=r.alias);let{theme:i,themeVariables:a}=s(),{rowEven:o,rowOdd:l,nodeBorder:u,borderColorArray:d}=a;if(t.look===`handDrawn`){let{themeVariables:n}=s(),{background:r}=n;await Lt(e,{...t,id:t.id+`-background`,domId:(t.domId||t.id)+`-background`,look:`default`,cssStyles:[`stroke: none`,`fill: ${r}`]})}let p=s();t.useHtmlLabels=p.htmlLabels;let m=p.er?.diagramPadding??10,h=p.er?.entityPadding??6,{cssStyles:g}=t,{labelStyles:_,nodeStyles:b}=y(t);if(r.attributes.length===0&&t.label){let n={rx:0,ry:0,labelPaddingX:m,labelPaddingY:m*1.5,classes:``};f(t.label,p)+n.labelPaddingX*20){let e=w.width+m*2-(A+j+M+N);A+=e/I,j+=e/I,M>0&&(M+=e/I),N>0&&(N+=e/I)}let ee=A+j+M+N,R=S.svg(C),z=v(t,{});t.look!==`handDrawn`&&(z.roughness=0,z.fillStyle=`solid`);let te=0;k.length>0&&(te=k.reduce((e,t)=>e+(t?.rowHeight??0),0));let B=Math.max(L.width+m*2,t?.width||0,ee),V=Math.max((te??0)+w.height,t?.height||0),H=-B/2,U=-V/2;if(C.selectAll(`g:not(:first-child)`).each((e,t,r)=>{let i=n(r[t]),a=i.attr(`transform`),o=0,s=0;if(a){let e=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(a);e&&(o=parseFloat(e[1]),s=parseFloat(e[2]),i.attr(`class`).includes(`attribute-name`)?o+=A:i.attr(`class`).includes(`attribute-keys`)?o+=A+j:i.attr(`class`).includes(`attribute-comment`)&&(o+=A+j+M))}i.attr(`transform`,`translate(${H+m/2+o}, ${s+U+w.height+h/2})`)}),C.select(`.name`).attr(`transform`,`translate(`+-w.width/2+`, `+(U+h/2)+`)`),i!=null&&Ft.has(i)){let e=r.colorIndex??0;C.attr(`data-color-id`,`color-${e%d.length}`)}let ne=R.rectangle(H,U,B,V,z),re=C.insert(()=>ne,`:first-child`).attr(`class`,`outer-path`).attr(`style`,g.join(``));O.push(0);for(let[e,t]of k.entries()){let n=(e+1)%2==0&&t.yOffset!==0,r=R.rectangle(H,w.height+U+t?.yOffset,B,t?.rowHeight,{...z,fill:n?o:l,stroke:u});C.insert(()=>r,`g.label`).attr(`style`,g.join(``)).attr(`class`,`row-rect-${n?`even`:`odd`}`)}let ie=1e-4,W=zt(H,w.height+U,B+H,w.height+U,ie),K=R.polygon(W.map(e=>[e.x,e.y]),z);if(C.insert(()=>K).attr(`class`,`divider`),W=zt(A+H,w.height+U,A+H,V+U,ie),K=R.polygon(W.map(e=>[e.x,e.y]),z),C.insert(()=>K).attr(`class`,`divider`),P){let e=A+j+H;W=zt(e,w.height+U,e,V+U,ie),K=R.polygon(W.map(e=>[e.x,e.y]),z),C.insert(()=>K).attr(`class`,`divider`)}if(F){let e=A+j+M+H;W=zt(e,w.height+U,e,V+U,ie),K=R.polygon(W.map(e=>[e.x,e.y]),z),C.insert(()=>K).attr(`class`,`divider`)}for(let e of O){let t=w.height+U+e;W=zt(H,t,B+H,t,ie),K=R.polygon(W.map(e=>[e.x,e.y]),z),C.insert(()=>K).attr(`class`,`divider`)}if(T(t,re),b&&t.look!==`handDrawn`)if(i!=null&&It.has(i))C.selectAll(`path`).attr(`style`,b);else{let e=b.split(`;`)?.filter(e=>e.includes(`stroke`))?.map(e=>`${e}`).join(`; `);C.selectAll(`path`).attr(`style`,e??``),C.selectAll(`.row-rect-even path`).attr(`style`,b)}return t.intersect=function(e){return G.rect(t,e)},C}e(Lt,`erBox`);async function Rt(e,t,r,i=0,o=0,s=[],l=``){let u=e.insert(`g`).attr(`class`,`label ${s.join(` `)}`).attr(`transform`,`translate(${i}, ${o})`).attr(`style`,l);t!==a(t)&&(t=a(t),t=t.replaceAll(`<`,`<`).replaceAll(`>`,`>`));let d=u.node().appendChild(await h(u,t,{width:f(t,r)+100,style:l,useHtmlLabels:r.htmlLabels},r));if(t.includes(`<`)||t.includes(`>`)){let e=d.children[0];for(e.textContent=e.textContent.replaceAll(`<`,`<`).replaceAll(`>`,`>`);e.childNodes[0];)e=e.childNodes[0],e.textContent=e.textContent.replaceAll(`<`,`<`).replaceAll(`>`,`>`)}let p=d.getBBox();if(c(r.htmlLabels)){let e=d.children[0];e.style.textAlign=`start`;let t=n(d);p=e.getBoundingClientRect(),t.attr(`width`,p.width),t.attr(`height`,p.height)}return p}e(Rt,`addText`);function zt(e,t,n,r,i){return e===n?[{x:e-i/2,y:t},{x:e+i/2,y:t},{x:n+i/2,y:r},{x:n-i/2,y:r}]:[{x:e,y:t-i/2},{x:e,y:t+i/2},{x:n,y:r+i/2},{x:n,y:r-i/2}]}e(zt,`lineToPolygon`);async function Bt(e,t,n,r,i=n.class.padding??12){let a=r?0:3,o=e.insert(`g`).attr(`class`,E(t)).attr(`id`,t.domId||t.id),s=null,c=null,l=null,u=null,d=0,f=0,p=0;if(s=o.insert(`g`).attr(`class`,`annotation-group text`),t.annotations.length>0){let e=t.annotations[0];await Vt(s,{text:`\xAB${e}\xBB`},0),d=s.node().getBBox().height}c=o.insert(`g`).attr(`class`,`label-group text`),await Vt(c,t,0,[`font-weight: bolder`]);let m=c.node().getBBox();f=m.height,l=o.insert(`g`).attr(`class`,`members-group text`);let h=0;for(let e of t.members){let t=await Vt(l,e,h,[e.parseClassifier()]);h+=t+a}p=l.node().getBBox().height,p<=0&&(p=i/2),u=o.insert(`g`).attr(`class`,`methods-group text`);let g=0;for(let e of t.methods){let t=await Vt(u,e,g,[e.parseClassifier()]);g+=t+a}let _=o.node().getBBox();if(s!==null){let e=s.node().getBBox();s.attr(`transform`,`translate(${-e.width/2})`)}return c.attr(`transform`,`translate(${-m.width/2}, ${d})`),_=o.node().getBBox(),l.attr(`transform`,`translate(0, ${d+f+i*2})`),_=o.node().getBBox(),u.attr(`transform`,`translate(0, ${d+f+(p?p+i*4:i*2)})`),_=o.node().getBBox(),{shapeSvg:o,bbox:_}}e(Bt,`textHelper`);async function Vt(t,a,o,l=[]){let u=t.insert(`g`).attr(`class`,`label`).attr(`style`,l.join(`; `)),p=s(),m=`useHtmlLabels`in a?a.useHtmlLabels:c(p.htmlLabels)??!0,g=``;g=`text`in a?a.text:a.label,!m&&g.startsWith(`\\`)&&(g=g.substring(1)),r(g)&&(m=!0);let _=await h(u,i(d(g)),{width:f(g,p)+50,classes:`markdown-node-label`,useHtmlLabels:m},p),v,y=1;if(m){let t=_.children[0],r=n(_);y=t.innerHTML.split(`
    `).length,t.innerHTML.includes(``)&&(y+=t.innerHTML.split(``).length-1);let i=t.getElementsByTagName(`img`);if(i){let t=g.replace(/]*>/g,``).trim()===``;await Promise.all([...i].map(n=>new Promise(r=>{function i(){if(n.style.display=`flex`,n.style.flexDirection=`column`,t){let e=p.fontSize?.toString()??window.getComputedStyle(document.body).fontSize,t=parseInt(e,10)*5+`px`;n.style.minWidth=t,n.style.maxWidth=t}else n.style.width=`100%`;r(n)}e(i,`setupImage`),setTimeout(()=>{n.complete&&i()}),n.addEventListener(`error`,i),n.addEventListener(`load`,i)})))}v=t.getBoundingClientRect(),r.attr(`width`,v.width),r.attr(`height`,v.height)}else{l.includes(`font-weight: bolder`)&&n(_).selectAll(`tspan`).attr(`font-weight`,``),y=_.children.length;let e=_.children[0];(_.textContent===``||_.textContent.includes(`>`))&&(e.textContent=g[0]+g.substring(1).replaceAll(`>`,`>`).replaceAll(`<`,`<`).trim(),g[1]===` `&&(e.textContent=e.textContent[0]+` `+e.textContent.substring(1))),e.textContent===`undefined`&&(e.textContent=``),v=_.getBBox()}return u.attr(`transform`,`translate(0,`+(-v.height/(2*y)+o)+`)`),v.height}e(Vt,`addText`);async function Ht(e,t){let r=l(),{themeVariables:i}=r,{useGradient:a}=i,o=r.class.padding??12,s=o,u=t.useHtmlLabels??c(r.htmlLabels)??!0,d=t;d.annotations=d.annotations??[],d.members=d.members??[],d.methods=d.methods??[];let{shapeSvg:f,bbox:p}=await Bt(e,t,r,u,s),{labelStyles:m,nodeStyles:h}=y(t);t.labelStyle=m,t.cssStyles=d.styles||``;let g=d.styles?.join(`;`)||h||``;t.cssStyles||=g.replaceAll(`!important`,``).split(`;`);let _=d.members.length===0&&d.methods.length===0&&!r.class?.hideEmptyMembersBox,b=S.svg(f),x=v(t,{});t.look!==`handDrawn`&&(x.roughness=0,x.fillStyle=`solid`);let C=Math.max(t.width??0,p.width),w=Math.max(t.height??0,p.height),E=(t.height??0)>p.height;d.members.length===0&&d.methods.length===0?w+=s:d.members.length>0&&d.methods.length===0&&(w+=s*2);let D=-C/2,O=-w/2,k=_?o*2:d.members.length===0&&d.methods.length===0?-o:0;E&&(k=o*2);let A=b.rectangle(D-o,O-o-(_?o:d.members.length===0&&d.methods.length===0?-o/2:0),C+2*o,w+2*o+k,x),j=f.insert(()=>A,`:first-child`);j.attr(`class`,`basic label-container outer-path`);let M=j.node().getBBox(),N=f.select(`.annotation-group`).node().getBBox().height-(_?o/2:0)||0,P=f.select(`.label-group`).node().getBBox().height-(_?o/2:0)||0,F=f.select(`.members-group`).node().getBBox().height-(_?o/2:0)||0,I=(N+P+O+o-(O-o-(_?o:d.members.length===0&&d.methods.length===0?-o/2:0)))/2;if(f.selectAll(`.text`).each((e,t,i)=>{let a=n(i[t]),c=a.attr(`transform`),l=0;if(c){let e=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(c);e&&(l=parseFloat(e[2]))}let p=l+O+o-(_?o:d.members.length===0&&d.methods.length===0?-o/2:0);if(a.attr(`class`).includes(`methods-group`)){let e=Math.max(F,s/2);p=E?Math.max(I,N+P+e+O+s*2+o)+s*2:N+P+e+O+s*4+o}d.members.length===0&&d.methods.length===0&&r.class?.hideEmptyMembersBox&&(p=d.annotations.length>0?l-s:l),u||(p-=4);let m=D;(a.attr(`class`).includes(`label-group`)||a.attr(`class`).includes(`annotation-group`))&&(m=-a.node()?.getBBox().width/2||0,f.selectAll(`text`).each(function(e,t,n){window.getComputedStyle(n[t]).textAnchor===`middle`&&(m=0)})),a.attr(`transform`,`translate(${m}, ${p})`)}),d.members.length>0||d.methods.length>0||_){let e=N+P+O+o,n=b.line(M.x,e,M.x+M.width,e+.001,x);f.insert(()=>n).attr(`class`,`divider${t.look===`neo`&&!a?` neo-line`:``}`).attr(`style`,g)}if(_||d.members.length>0||d.methods.length>0){let e=N+P+F+O+s*2+o,n=b.line(M.x,E?Math.max(I,e):e,M.x+M.width,(E?Math.max(I,e):e)+.001,x);f.insert(()=>n).attr(`class`,`divider${t.look===`neo`&&!a?` neo-line`:``}`).attr(`style`,g)}if(d.look!==`handDrawn`&&f.selectAll(`path`).attr(`style`,g),j.select(`:nth-child(2)`).attr(`style`,g),f.selectAll(`.divider`).select(`path`).attr(`style`,g),t.labelStyle?f.selectAll(`span`).attr(`style`,t.labelStyle):f.selectAll(`span`).attr(`style`,g),!u){let e=RegExp(/color\s*:\s*([^;]*)/),t=e.exec(g);if(t){let e=t[0].replace(`color`,`fill`);f.selectAll(`tspan`).attr(`style`,e)}else if(m){let t=e.exec(m);if(t){let e=t[0].replace(`color`,`fill`);f.selectAll(`tspan`).attr(`style`,e)}}}return T(t,j),t.intersect=function(e){return G.rect(t,e)},f}e(Ht,`classBox`);async function Ut(e,t){let{labelStyles:r,nodeStyles:i}=y(t);t.labelStyle=r;let a=t,o=t,s=`verifyMethod`in t,c=E(t),{themeVariables:u}=l(),{borderColorArray:d,requirementEdgeLabelBackground:f}=u,p=e.insert(`g`).attr(`class`,c).attr(`id`,t.domId??t.id),m;m=s?await $(p,`<<${a.type}>>`,0,t.labelStyle):await $(p,`<<Element>>`,0,t.labelStyle);let h=m,g=await $(p,a.name,h,t.labelStyle+`; font-weight: bold;`);if(h+=g+20,s){let e=await $(p,`${a.requirementId?`ID: ${a.requirementId}`:``}`,h,t.labelStyle);h+=e;let n=await $(p,`${a.text?`Text: ${a.text}`:``}`,h,t.labelStyle);h+=n;let r=await $(p,`${a.risk?`Risk: ${a.risk}`:``}`,h,t.labelStyle);h+=r,await $(p,`${a.verifyMethod?`Verification: ${a.verifyMethod}`:``}`,h,t.labelStyle)}else{let e=await $(p,`${o.type?`Type: ${o.type}`:``}`,h,t.labelStyle);h+=e,await $(p,`${o.docRef?`Doc Ref: ${o.docRef}`:``}`,h,t.labelStyle)}let _=(p.node()?.getBBox().width??200)+20,b=(p.node()?.getBBox().height??200)+20,x=-_/2,C=-b/2,w=S.svg(p),D=v(t,{});t.look!==`handDrawn`&&(D.roughness=0,D.fillStyle=`solid`);let O=w.rectangle(x,C,_,b,D),k=p.insert(()=>O,`:first-child`);if(k.attr(`class`,`basic label-container outer-path`).attr(`style`,i),d?.length){let e=t.colorIndex??0;p.attr(`data-color-id`,`color-${e%d.length}`)}if(p.selectAll(`.label`).each((e,t,r)=>{let i=n(r[t]),a=i.attr(`transform`),o=0,s=0;if(a){let e=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(a);e&&(o=parseFloat(e[1]),s=parseFloat(e[2]))}let c=s-b/2,l=x+20/2;(t===0||t===1)&&(l=o),i.attr(`transform`,`translate(${l}, ${c+20})`)}),h>m+g+20){let e=C+m+g+20,n;if(t.look===`neo`){let t=.001,r=[[x,e],[x+_,e],[x+_,e+t],[x,e+t]];n=w.polygon(r,D)}else n=w.line(x,e,x+_,e,D);p.insert(()=>n).attr(`class`,`divider`)}return T(t,k),t.intersect=function(e){return G.rect(t,e)},i&&t.look!==`handDrawn`&&(f||d?.length)&&p.selectAll(`path`).attr(`style`,i),p}e(Ut,`requirementBox`);async function $(e,t,r,a=``){if(t===``)return 0;let o=e.insert(`g`).attr(`class`,`label`).attr(`style`,a),s=l(),c=s.htmlLabels??!0,u=await h(o,i(d(t)),{width:f(t,s)+50,classes:`markdown-node-label`,useHtmlLabels:c,style:a},s),p;if(c){let e=u.children[0],t=n(u);p=e.getBoundingClientRect(),t.attr(`width`,p.width),t.attr(`height`,p.height)}else{let e=u.children[0];for(let t of e.children)a&&t.setAttribute(`style`,a);p=u.getBBox(),p.height+=6}return o.attr(`transform`,`translate(${-p.width/2},${-p.height/2+r})`),p.height}e($,`addText`);var Wt=e(e=>{switch(e){case`Very High`:return`red`;case`High`:return`orange`;case`Medium`:return null;case`Low`:return`blue`;case`Very Low`:return`lightblue`}},`colorFromPriority`);async function Gt(e,t,{config:n}){let{labelStyles:r,nodeStyles:i}=y(t);t.labelStyle=r||``;let a=t.width;t.width=(t.width??200)-10;let{shapeSvg:o,bbox:s,label:c}=await C(e,t,E(t)),l=t.padding||10,u=``,d;`ticket`in t&&t.ticket&&n?.kanban?.ticketBaseUrl&&(u=n?.kanban?.ticketBaseUrl.replace(`#TICKET#`,t.ticket),d=o.insert(`svg:a`,`:first-child`).attr(`class`,`kanban-ticket-link`).attr(`xlink:href`,u).attr(`target`,`_blank`));let f={useHtmlLabels:t.useHtmlLabels,labelStyle:t.labelStyle||``,width:t.width,img:t.img,padding:t.padding||8,centerLabel:!1},p,m;d?{label:p,bbox:m}=await w(d,`ticket`in t&&t.ticket||``,f):{label:p,bbox:m}=await w(o,`ticket`in t&&t.ticket||``,f);let{label:h,bbox:g}=await w(o,`assigned`in t&&t.assigned||``,f);t.width=a;let _=t?.width||0,b=Math.max(m.height,g.height)/2,x=Math.max(s.height+20,t?.height||0)+b,D=-_/2,O=-x/2;c.attr(`transform`,`translate(`+(l-_/2)+`, `+(-b-s.height/2)+`)`),p.attr(`transform`,`translate(`+(l-_/2)+`, `+(-b+s.height/2)+`)`),h.attr(`transform`,`translate(`+(l+_/2-g.width-20)+`, `+(-b+s.height/2)+`)`);let k,{rx:A,ry:j}=t,{cssStyles:M}=t;if(t.look===`handDrawn`){let e=S.svg(o),n=v(t,{}),r=A||j?e.path(N(D,O,_,x,A||0),n):e.rectangle(D,O,_,x,n);k=o.insert(()=>r,`:first-child`),k.attr(`class`,`basic label-container`).attr(`style`,M||null)}else{k=o.insert(`rect`,`:first-child`),k.attr(`class`,`basic label-container __APA__`).attr(`style`,i).attr(`rx`,A??5).attr(`ry`,j??5).attr(`x`,D).attr(`y`,O).attr(`width`,_).attr(`height`,x);let e=`priority`in t&&t.priority;if(e){let t=o.append(`line`),n=D+2,r=O+Math.floor((A??0)/2),i=O+x-Math.floor((A??0)/2);t.attr(`x1`,n).attr(`y1`,r).attr(`x2`,n).attr(`y2`,i).attr(`stroke-width`,`4`).attr(`stroke`,Wt(e))}}return T(t,k),t.height=x,t.intersect=function(e){return G.rect(t,e)},o}e(Gt,`kanbanItem`);async function Kt(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let{shapeSvg:a,bbox:o,halfPadding:s,label:c}=await C(e,n,E(n)),l=o.width+10*s,u=o.height+8*s,d=.15*l,{cssStyles:f}=n,m=o.width+20,h=o.height+20,g=Math.max(l,m),_=Math.max(u,h);c.attr(`transform`,`translate(${-o.width/2}, ${-o.height/2})`);let b,x=`M0 0 + a${d},${d} 1 0,0 ${g*.25},${-1*_*.1} + a${d},${d} 1 0,0 ${g*.25},0 + a${d},${d} 1 0,0 ${g*.25},0 + a${d},${d} 1 0,0 ${g*.25},${_*.1} + + a${d},${d} 1 0,0 ${g*.15},${_*.33} + a${d*.8},${d*.8} 1 0,0 0,${_*.34} + a${d},${d} 1 0,0 ${-1*g*.15},${_*.33} + + a${d},${d} 1 0,0 ${-1*g*.25},${_*.15} + a${d},${d} 1 0,0 ${-1*g*.25},0 + a${d},${d} 1 0,0 ${-1*g*.25},0 + a${d},${d} 1 0,0 ${-1*g*.25},${-1*_*.15} + + a${d},${d} 1 0,0 ${-1*g*.1},${-1*_*.33} + a${d*.8},${d*.8} 1 0,0 0,${-1*_*.34} + a${d},${d} 1 0,0 ${g*.1},${-1*_*.33} + H0 V0 Z`;if(n.look===`handDrawn`){let e=S.svg(a),t=v(n,{}),r=e.path(x,t);b=a.insert(()=>r,`:first-child`),b.attr(`class`,`basic label-container`).attr(`style`,p(f))}else b=a.insert(`path`,`:first-child`).attr(`class`,`basic label-container`).attr(`style`,i).attr(`d`,x);return b.attr(`transform`,`translate(${-g/2}, ${-_/2})`),T(n,b),n.calcIntersect=function(e,t){return G.rect(e,t)},n.intersect=function(e){return t.info(`Bang intersect`,n,e),G.rect(n,e)},a}e(Kt,`bang`);async function qt(e,n){let{labelStyles:r,nodeStyles:i}=y(n);n.labelStyle=r;let{shapeSvg:a,bbox:o,halfPadding:s,label:c}=await C(e,n,E(n)),l=o.width+2*s,u=o.height+2*s,d=.15*l,f=.25*l,m=.35*l,h=.2*l,{cssStyles:g}=n,_,b=`M0 0 + a${d},${d} 0 0,1 ${l*.25},${-1*l*.1} + a${m},${m} 1 0,1 ${l*.4},${-1*l*.1} + a${f},${f} 1 0,1 ${l*.35},${l*.2} + + a${d},${d} 1 0,1 ${l*.15},${u*.35} + a${h},${h} 1 0,1 ${-1*l*.15},${u*.65} + + a${f},${d} 1 0,1 ${-1*l*.25},${l*.15} + a${m},${m} 1 0,1 ${-1*l*.5},0 + a${d},${d} 1 0,1 ${-1*l*.25},${-1*l*.15} + + a${d},${d} 1 0,1 ${-1*l*.1},${-1*u*.35} + a${h},${h} 1 0,1 ${l*.1},${-1*u*.65} + H0 V0 Z`;if(n.look===`handDrawn`){let e=S.svg(a),t=v(n,{}),r=e.path(b,t);_=a.insert(()=>r,`:first-child`),_.attr(`class`,`basic label-container`).attr(`style`,p(g))}else _=a.insert(`path`,`:first-child`).attr(`class`,`basic label-container`).attr(`style`,i).attr(`d`,b);return c.attr(`transform`,`translate(${-o.width/2}, ${-o.height/2})`),_.attr(`transform`,`translate(${-l/2}, ${-u/2})`),T(n,_),n.calcIntersect=function(e,t){return G.rect(e,t)},n.intersect=function(e){return t.info(`Cloud intersect`,n,e),G.rect(n,e)},a}e(qt,`cloud`);async function Jt(e,t){let{labelStyles:n,nodeStyles:r}=y(t);t.labelStyle=n;let{shapeSvg:i,bbox:a,halfPadding:o,label:s}=await C(e,t,E(t)),c=a.width+8*o,l=a.height+2*o,u=t.look===`neo`?` + M${-c/2} ${l/2-5} + v${-l+10} + q0,-5 5,-5 + h${c-10} + q5,0 5,5 + v${l-5} + H${-c/2} + Z + `:` + M${-c/2} ${l/2-5} + v${-l+10} + q0,-5 5,-5 + h${c-10} + q5,0 5,5 + v${l-10} + q0,5 -5,5 + h${-(c-10)} + q-5,0 -5,-5 + Z + `;if(!t.domId)throw Error(`defaultMindmapNode: node "${t.id}" is missing a domId \u2014 was render.ts domId prefixing skipped?`);let d=i.append(`path`).attr(`id`,t.domId).attr(`class`,`node-bkg node-`+t.type).attr(`style`,r).attr(`d`,u);return i.append(`line`).attr(`class`,`node-line-`).attr(`x1`,-c/2).attr(`y1`,l/2).attr(`x2`,c/2).attr(`y2`,l/2),s.attr(`transform`,`translate(${-a.width/2}, ${-a.height/2})`),i.append(()=>s.node()),T(t,d),t.calcIntersect=function(e,t){return G.rect(e,t)},t.intersect=function(e){return G.rect(t,e)},i}e(Jt,`defaultMindmapNode`);async function Yt(e,t){return de(e,t,{padding:t.padding??0})}e(Yt,`mindmapCircle`);var Xt=[{semanticName:`Process`,name:`Rectangle`,shortName:`rect`,description:`Standard process shape`,aliases:[`proc`,`process`,`rectangle`],internalAliases:[`squareRect`],handler:ut},{semanticName:`Event`,name:`Rounded Rectangle`,shortName:`rounded`,description:`Represents an event`,aliases:[`event`],internalAliases:[`roundedRect`],handler:st},{semanticName:`Terminal Point`,name:`Stadium`,shortName:`stadium`,description:`Terminal point`,aliases:[`terminal`,`pill`],handler:dt},{semanticName:`Subprocess`,name:`Framed Rectangle`,shortName:`fr-rect`,description:`Subprocess`,aliases:[`subprocess`,`subproc`,`framed-rectangle`,`subroutine`],handler:gt},{semanticName:`Database`,name:`Cylinder`,shortName:`cyl`,description:`Database storage`,aliases:[`db`,`database`,`cylinder`],handler:Ce},{semanticName:`Data Store`,name:`Data Store`,shortName:`datastore`,description:`Data flow diagram data store`,aliases:[`data-store`],handler:Te},{semanticName:`Start`,name:`Circle`,shortName:`circle`,description:`Starting point`,aliases:[`circ`],handler:de},{semanticName:`Bang`,name:`Bang`,shortName:`bang`,description:`Bang`,aliases:[`bang`],handler:Kt},{semanticName:`Cloud`,name:`Cloud`,shortName:`cloud`,description:`cloud`,aliases:[`cloud`],handler:qt},{semanticName:`Decision`,name:`Diamond`,shortName:`diam`,description:`Decision-making step`,aliases:[`decision`,`diamond`,`question`],handler:it},{semanticName:`Prepare Conditional`,name:`Hexagon`,shortName:`hex`,description:`Preparation or condition step`,aliases:[`hexagon`,`prepare`],handler:Fe},{semanticName:`Data Input/Output`,name:`Lean Right`,shortName:`lean-r`,description:`Represents input or output`,aliases:[`lean-right`,`in-out`],internalAliases:[`lean_right`],handler:Ge},{semanticName:`Data Input/Output`,name:`Lean Left`,shortName:`lean-l`,description:`Represents output or input`,aliases:[`lean-left`,`out-in`],internalAliases:[`lean_left`],handler:We},{semanticName:`Priority Action`,name:`Trapezoid Base Bottom`,shortName:`trap-b`,description:`Priority action`,aliases:[`priority`,`trapezoid-bottom`,`trapezoid`],handler:Dt},{semanticName:`Manual Operation`,name:`Trapezoid Base Top`,shortName:`trap-t`,description:`Represents a manual task`,aliases:[`manual`,`trapezoid-top`,`inv-trapezoid`],internalAliases:[`inv_trapezoid`],handler:He},{semanticName:`Stop`,name:`Double Circle`,shortName:`dbl-circ`,description:`Represents a stop point`,aliases:[`double-circle`],internalAliases:[`doublecircle`],handler:De},{semanticName:`Text Block`,name:`Text Block`,shortName:`text`,description:`Text block`,handler:bt},{semanticName:`Card`,name:`Notched Rectangle`,shortName:`notch-rect`,description:`Represents a card`,aliases:[`card`,`notched-rectangle`],handler:le},{semanticName:`Lined/Shaded Process`,name:`Lined Rectangle`,shortName:`lin-rect`,description:`Lined process shape`,aliases:[`lined-rectangle`,`lined-process`,`lin-proc`,`shaded-process`],handler:ct},{semanticName:`Start`,name:`Small Circle`,shortName:`sm-circ`,description:`Small starting point`,aliases:[`start`,`small-circle`],internalAliases:[`stateStart`],handler:mt},{semanticName:`Stop`,name:`Framed Circle`,shortName:`fr-circ`,description:`Stop point`,aliases:[`stop`,`framed-circle`],internalAliases:[`stateEnd`],handler:pt},{semanticName:`Fork/Join`,name:`Filled Rectangle`,shortName:`fork`,description:`Fork or join in process flow`,aliases:[`join`],internalAliases:[`forkJoin`],handler:Me},{semanticName:`Collate`,name:`Hourglass`,shortName:`hourglass`,description:`Represents a collate operation`,aliases:[`hourglass`,`collate`],handler:Ie},{semanticName:`Comment`,name:`Curly Brace`,shortName:`brace`,description:`Adds a comment`,aliases:[`comment`,`brace-l`],handler:me},{semanticName:`Comment Right`,name:`Curly Brace`,shortName:`brace-r`,description:`Adds a comment`,handler:he},{semanticName:`Comment with braces on both sides`,name:`Curly Braces`,shortName:`braces`,description:`Adds a comment`,handler:ge},{semanticName:`Com Link`,name:`Lightning Bolt`,shortName:`bolt`,description:`Communication link`,aliases:[`com-link`,`lightning-bolt`],handler:Ke},{semanticName:`Document`,name:`Document`,shortName:`doc`,description:`Represents a document`,aliases:[`doc`,`document`],handler:Mt},{semanticName:`Delay`,name:`Half-Rounded Rectangle`,shortName:`delay`,description:`Represents a delay`,aliases:[`half-rounded-rectangle`],handler:Ne},{semanticName:`Direct Access Storage`,name:`Horizontal Cylinder`,shortName:`h-cyl`,description:`Direct access storage`,aliases:[`das`,`horizontal-cylinder`],handler:Et},{semanticName:`Disk Storage`,name:`Lined Cylinder`,shortName:`lin-cyl`,description:`Disk storage`,aliases:[`disk`,`lined-cylinder`],handler:Qe},{semanticName:`Display`,name:`Curved Trapezoid`,shortName:`curv-trap`,description:`Represents a display`,aliases:[`curved-trapezoid`,`display`],handler:_e},{semanticName:`Divided Process`,name:`Divided Rectangle`,shortName:`div-rect`,description:`Divided process shape`,aliases:[`div-proc`,`divided-rectangle`,`divided-process`],handler:Ee},{semanticName:`Extract`,name:`Triangle`,shortName:`tri`,description:`Extraction process`,aliases:[`extract`,`triangle`],handler:jt},{semanticName:`Internal Storage`,name:`Window Pane`,shortName:`win-pane`,description:`Internal storage`,aliases:[`internal-storage`,`window-pane`],handler:Pt},{semanticName:`Junction`,name:`Filled Circle`,shortName:`f-circ`,description:`Junction point`,aliases:[`junction`,`filled-circle`],handler:Oe},{semanticName:`Loop Limit`,name:`Trapezoidal Pentagon`,shortName:`notch-pent`,description:`Loop limit step`,aliases:[`loop-limit`,`notched-pentagon`],handler:Ot},{semanticName:`Manual File`,name:`Flipped Triangle`,shortName:`flip-tri`,description:`Manual file operation`,aliases:[`manual-file`,`flipped-triangle`],handler:je},{semanticName:`Manual Input`,name:`Sloped Rectangle`,shortName:`sl-rect`,description:`Manual input step`,aliases:[`manual-input`,`sloped-rectangle`],handler:lt},{semanticName:`Multi-Document`,name:`Stacked Document`,shortName:`docs`,description:`Multiple documents`,aliases:[`documents`,`st-doc`,`stacked-document`],handler:tt},{semanticName:`Multi-Process`,name:`Stacked Rectangle`,shortName:`st-rect`,description:`Multiple processes`,aliases:[`procs`,`processes`,`stacked-rectangle`],handler:et},{semanticName:`Stored Data`,name:`Bow Tie Rectangle`,shortName:`bow-rect`,description:`Stored data`,aliases:[`stored-data`,`bow-tie-rectangle`],handler:se},{semanticName:`Summary`,name:`Crossed Circle`,shortName:`cross-circ`,description:`Summary`,aliases:[`summary`,`crossed-circle`],handler:pe},{semanticName:`Tagged Document`,name:`Tagged Document`,shortName:`tag-doc`,description:`Tagged document`,aliases:[`tag-doc`,`tagged-document`],handler:yt},{semanticName:`Tagged Process`,name:`Tagged Rectangle`,shortName:`tag-rect`,description:`Tagged process`,aliases:[`tagged-rectangle`,`tag-proc`,`tagged-process`],handler:vt},{semanticName:`Paper Tape`,name:`Flag`,shortName:`flag`,description:`Paper tape`,aliases:[`paper-tape`],handler:Nt},{semanticName:`Odd`,name:`Odd`,shortName:`odd`,description:`Odd shape`,internalAliases:[`rect_left_inv_arrow`],handler:at},{semanticName:`Lined Document`,name:`Lined Document`,shortName:`lin-doc`,description:`Lined document`,aliases:[`lined-document`],handler:$e}],Zt=e(()=>{let e=[...Object.entries({state:ft,choice:ue,note:nt,rectWithTitle:ot,labelRect:Ue,iconSquare:Be,iconCircle:Re,icon:Le,iconRounded:ze,imageSquare:Ve,anchor:K,kanbanItem:Gt,mindmapCircle:Yt,defaultMindmapNode:Jt,classBox:Ht,erBox:Lt,requirementBox:Ut}),...Xt.flatMap(e=>[e.shortName,...`aliases`in e?e.aliases:[],...`internalAliases`in e?e.internalAliases:[]].map(t=>[t,e.handler]))];return Object.fromEntries(e)},`generateShapeMap`)();function Qt(e){return e in Zt}e(Qt,`isValidShape`);var $t=new Map;async function en(e,t,n){let r,i;t.shape===`rect`&&(t.rx&&t.ry?t.shape=`roundedRect`:t.shape=`squareRect`);let a=t.shape?Zt[t.shape]:void 0;if(!a)throw Error(`No such shape: ${t.shape}. Please check your syntax.`);if(t.link){let o;n.config.securityLevel===`sandbox`?o=`_top`:t.linkTarget&&(o=t.linkTarget||`_blank`),r=e.insert(`svg:a`).attr(`xlink:href`,t.link).attr(`target`,o??null),i=await a(r,t,n)}else i=await a(e,t,n),r=i;return r.attr(`data-look`,p(t.look)),t.tooltip&&i.attr(`title`,t.tooltip),$t.set(t.id,r),t.haveCallback&&r.attr(`class`,r.attr(`class`)+` clickable`),r}e(en,`insertNode`);var tn=e((e,t)=>{$t.set(t.id,e)},`setNodeElem`),nn=e(()=>{$t.clear()},`clear`),rn=e(e=>{let n=$t.get(e.id);t.trace(`Transforming node`,e.diff,e,`translate(`+(e.x-e.width/2-5)+`, `+e.width/2+`)`);let r=e.diff||0;return e.clusterNode?n.attr(`transform`,`translate(`+(e.x+r-e.width/2)+`, `+(e.y-e.height/2-8)+`)`):n.attr(`transform`,`translate(`+e.x+`, `+e.y+`)`),r},`positionNode`);export{en as a,rn as c,ee as i,tn as l,nn as n,Qt as o,M as r,C as s,R as t,T as u}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-ZIRB5QZD-C6fEPe3t.js b/dist-desktop/assets/chunk-ZIRB5QZD-C6fEPe3t.js new file mode 100644 index 0000000..a523465 --- /dev/null +++ b/dist-desktop/assets/chunk-ZIRB5QZD-C6fEPe3t.js @@ -0,0 +1,32 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";function t(e){return e==null}e(t,`isNothing`);function n(e){return typeof e==`object`&&!!e}e(n,`isObject`);function r(e){return Array.isArray(e)?e:t(e)?[]:[e]}e(r,`toArray`);function i(e,t){var n,r,i,a;if(t)for(a=Object.keys(t),n=0,r=a.length;ns&&(a=` ... `,t=r-s+a.length),n-r>s&&(o=` ...`,n=r+s-o.length),{str:a+e.slice(t,n).replace(/\t/g,`→`)+o,pos:r-t+a.length}}e(d,`getLine`);function f(e,t){return s.repeat(` `,t-e.length)+e}e(f,`padStart`);function p(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||=79,typeof t.indent!=`number`&&(t.indent=1),typeof t.linesBefore!=`number`&&(t.linesBefore=3),typeof t.linesAfter!=`number`&&(t.linesAfter=2);for(var n=/\r?\n|\r|\0/g,r=[0],i=[],a,o=-1;a=n.exec(e.buffer);)i.push(a.index),r.push(a.index+a[0].length),e.position<=a.index&&o<0&&(o=r.length-2);o<0&&(o=r.length-1);var c=``,l,u,p=Math.min(e.line+t.linesAfter,i.length).toString().length,m=t.maxLength-(t.indent+p+3);for(l=1;l<=t.linesBefore&&!(o-l<0);l++)u=d(e.buffer,r[o-l],i[o-l],e.position-(r[o]-r[o-l]),m),c=s.repeat(` `,t.indent)+f((e.line-l+1).toString(),p)+` | `+u.str+` +`+c;for(u=d(e.buffer,r[o],i[o],e.position,m),c+=s.repeat(` `,t.indent)+f((e.line+1).toString(),p)+` | `+u.str+` +`,c+=s.repeat(`-`,t.indent+p+3+u.pos)+`^ +`,l=1;l<=t.linesAfter&&!(o+l>=i.length);l++)u=d(e.buffer,r[o+l],i[o+l],e.position-(r[o]-r[o+l]),m),c+=s.repeat(` `,t.indent)+f((e.line+l+1).toString(),p)+` | `+u.str+` +`;return c.replace(/\n$/,``)}e(p,`makeSnippet`);var m=p,h=[`kind`,`multi`,`resolve`,`construct`,`instanceOf`,`predicate`,`represent`,`representName`,`defaultStyle`,`styleAliases`],g=[`scalar`,`sequence`,`mapping`];function _(e){var t={};return e!==null&&Object.keys(e).forEach(function(n){e[n].forEach(function(e){t[String(e)]=n})}),t}e(_,`compileStyleAliases`);function v(e,t){if(t||={},Object.keys(t).forEach(function(t){if(h.indexOf(t)===-1)throw new u(`Unknown option "`+t+`" is met in definition of "`+e+`" YAML type.`)}),this.options=t,this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=_(t.styleAliases||null),g.indexOf(this.kind)===-1)throw new u(`Unknown kind "`+this.kind+`" is specified for "`+e+`" YAML type.`)}e(v,`Type$1`);var y=v;function b(e,t){var n=[];return e[t].forEach(function(e){var t=n.length;n.forEach(function(n,r){n.tag===e.tag&&n.kind===e.kind&&n.multi===e.multi&&(t=r)}),n[t]=e}),n}e(b,`compileList`);function ee(){var t={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}},n,r;function i(e){e.multi?(t.multi[e.kind].push(e),t.multi.fallback.push(e)):t[e.kind][e.tag]=t.fallback[e.tag]=e}for(e(i,`collectType`),n=0,r=arguments.length;n=0?`0b`+e.toString(2):`-0b`+e.toString(2).slice(1)},`binary`),octal:e(function(e){return e>=0?`0o`+e.toString(8):`-0o`+e.toString(8).slice(1)},`octal`),decimal:e(function(e){return e.toString(10)},`decimal`),hexadecimal:e(function(e){return e>=0?`0x`+e.toString(16).toUpperCase():`-0x`+e.toString(16).toUpperCase().slice(1)},`hexadecimal`)},defaultStyle:`decimal`,styleAliases:{binary:[2,`bin`],octal:[8,`oct`],decimal:[10,`dec`],hexadecimal:[16,`hex`]}}),_e=RegExp(`^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$`);function ve(e){return!(e===null||!_e.test(e)||e[e.length-1]===`_`)}e(ve,`resolveYamlFloat`);function ye(e){var t=e.replace(/_/g,``).toLowerCase(),n=t[0]===`-`?-1:1;return`+-`.indexOf(t[0])>=0&&(t=t.slice(1)),t===`.inf`?n===1?1/0:-1/0:t===`.nan`?NaN:n*parseFloat(t,10)}e(ye,`constructYamlFloat`);var be=/^[-+]?[0-9]+e/;function xe(e,t){var n;if(isNaN(e))switch(t){case`lowercase`:return`.nan`;case`uppercase`:return`.NAN`;case`camelcase`:return`.NaN`}else if(e===1/0)switch(t){case`lowercase`:return`.inf`;case`uppercase`:return`.INF`;case`camelcase`:return`.Inf`}else if(e===-1/0)switch(t){case`lowercase`:return`-.inf`;case`uppercase`:return`-.INF`;case`camelcase`:return`-.Inf`}else if(s.isNegativeZero(e))return`-0.0`;return n=e.toString(10),be.test(n)?n.replace(`e`,`.e`):n}e(xe,`representYamlFloat`);function Se(e){return Object.prototype.toString.call(e)===`[object Number]`&&(e%1!=0||s.isNegativeZero(e))}e(Se,`isFloat`);var Ce=new y(`tag:yaml.org,2002:float`,{kind:`scalar`,resolve:ve,construct:ye,predicate:Se,represent:xe,defaultStyle:`lowercase`}),we=te.extend({implicit:[ae,le,ge,Ce]}),Te=we,Ee=RegExp(`^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$`),De=RegExp(`^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$`);function Oe(e){return e===null?!1:Ee.exec(e)!==null||De.exec(e)!==null}e(Oe,`resolveYamlTimestamp`);function ke(e){var t,n,r,i,a,o,s,c=0,l=null,u,d,f;if(t=Ee.exec(e),t===null&&(t=De.exec(e)),t===null)throw Error(`Date resolve error`);if(n=+t[1],r=t[2]-1,i=+t[3],!t[4])return new Date(Date.UTC(n,r,i));if(a=+t[4],o=+t[5],s=+t[6],t[7]){for(c=t[7].slice(0,3);c.length<3;)c+=`0`;c=+c}return t[9]&&(u=+t[10],d=+(t[11]||0),l=(u*60+d)*6e4,t[9]===`-`&&(l=-l)),f=new Date(Date.UTC(n,r,i,a,o,s,c)),l&&f.setTime(f.getTime()-l),f}e(ke,`constructYamlTimestamp`);function Ae(e){return e.toISOString()}e(Ae,`representYamlTimestamp`);var je=new y(`tag:yaml.org,2002:timestamp`,{kind:`scalar`,resolve:Oe,construct:ke,instanceOf:Date,represent:Ae});function Me(e){return e===`<<`||e===null}e(Me,`resolveYamlMerge`);var Ne=new y(`tag:yaml.org,2002:merge`,{kind:`scalar`,resolve:Me}),S=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= +\r`;function Pe(e){if(e===null)return!1;var t,n,r=0,i=e.length,a=S;for(n=0;n64)){if(t<0)return!1;r+=6}return r%8==0}e(Pe,`resolveYamlBinary`);function Fe(e){var t,n,r=e.replace(/[\r\n=]/g,``),i=r.length,a=S,o=0,s=[];for(t=0;t>16&255),s.push(o>>8&255),s.push(o&255)),o=o<<6|a.indexOf(r.charAt(t));return n=i%4*6,n===0?(s.push(o>>16&255),s.push(o>>8&255),s.push(o&255)):n===18?(s.push(o>>10&255),s.push(o>>2&255)):n===12&&s.push(o>>4&255),new Uint8Array(s)}e(Fe,`constructYamlBinary`);function Ie(e){var t=``,n=0,r,i,a=e.length,o=S;for(r=0;r>18&63],t+=o[n>>12&63],t+=o[n>>6&63],t+=o[n&63]),n=(n<<8)+e[r];return i=a%3,i===0?(t+=o[n>>18&63],t+=o[n>>12&63],t+=o[n>>6&63],t+=o[n&63]):i===2?(t+=o[n>>10&63],t+=o[n>>4&63],t+=o[n<<2&63],t+=o[64]):i===1&&(t+=o[n>>2&63],t+=o[n<<4&63],t+=o[64],t+=o[64]),t}e(Ie,`representYamlBinary`);function Le(e){return Object.prototype.toString.call(e)===`[object Uint8Array]`}e(Le,`isBinary`);var Re=new y(`tag:yaml.org,2002:binary`,{kind:`scalar`,resolve:Pe,construct:Fe,predicate:Le,represent:Ie}),ze=Object.prototype.hasOwnProperty,Be=Object.prototype.toString;function Ve(e){if(e===null)return!0;var t=[],n,r,i,a,o,s=e;for(n=0,r=s.length;n>10)+55296,(e-65536&1023)+56320)}e(ft,`charFromCodepoint`);function pt(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!0,value:n}):e[t]=n}e(pt,`setProperty`);var mt=Array(256),ht=Array(256);for(M=0;M<256;M++)mt[M]=+!!dt(M),ht[M]=dt(M);var M;function gt(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||Qe,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}e(gt,`State$1`);function _t(e,t){var n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=m(n),new u(t,n)}e(_t,`generateError`);function N(e,t){throw _t(e,t)}e(N,`throwError`);function P(e,t){e.onWarning&&e.onWarning.call(null,_t(e,t))}e(P,`throwWarning`);var vt={YAML:e(function(e,t,n){var r,i,a;e.version!==null&&N(e,`duplication of %YAML directive`),n.length!==1&&N(e,`YAML directive accepts exactly one argument`),r=/^([0-9]+)\.([0-9]+)$/.exec(n[0]),r===null&&N(e,`ill-formed argument of the YAML directive`),i=parseInt(r[1],10),a=parseInt(r[2],10),i!==1&&N(e,`unacceptable YAML version of the document`),e.version=n[0],e.checkLineBreaks=a<2,a!==1&&a!==2&&P(e,`unsupported YAML version of the document`)},`handleYamlDirective`),TAG:e(function(e,t,n){var r,i;n.length!==2&&N(e,`TAG directive accepts exactly two arguments`),r=n[0],i=n[1],ot.test(r)||N(e,`ill-formed tag handle (first argument) of the TAG directive`),C.call(e.tagMap,r)&&N(e,`there is a previously declared suffix for "`+r+`" tag handle`),st.test(i)||N(e,`ill-formed tag prefix (second argument) of the TAG directive`);try{i=decodeURIComponent(i)}catch{N(e,`tag prefix is malformed: `+i)}e.tagMap[r]=i},`handleTagDirective`)};function F(e,t,n,r){var i,a,o,s;if(t1&&(e.result+=s.repeat(` +`,t-1))}e(B,`writeFoldedLines`);function bt(e,t,n){var r,i,a,o,s,c,l,u,d=e.kind,f=e.result,p=e.input.charCodeAt(e.position);if(A(p)||j(p)||p===35||p===38||p===42||p===33||p===124||p===62||p===39||p===34||p===37||p===64||p===96||(p===63||p===45)&&(i=e.input.charCodeAt(e.position+1),A(i)||n&&j(i)))return!1;for(e.kind=`scalar`,e.result=``,a=o=e.position,s=!1;p!==0;){if(p===58){if(i=e.input.charCodeAt(e.position+1),A(i)||n&&j(i))break}else if(p===35){if(r=e.input.charCodeAt(e.position-1),A(r))break}else if(e.position===e.lineStart&&z(e)||n&&j(p))break;else if(O(p))if(c=e.line,l=e.lineStart,u=e.lineIndent,R(e,!1,-1),e.lineIndent>=t){s=!0,p=e.input.charCodeAt(e.position);continue}else{e.position=o,e.line=c,e.lineStart=l,e.lineIndent=u;break}s&&=(F(e,a,o,!1),B(e,e.line-c),a=o=e.position,!1),k(p)||(o=e.position+1),p=e.input.charCodeAt(++e.position)}return F(e,a,o,!1),e.result?!0:(e.kind=d,e.result=f,!1)}e(bt,`readPlainScalar`);function xt(e,t){var n=e.input.charCodeAt(e.position),r,i;if(n!==39)return!1;for(e.kind=`scalar`,e.result=``,e.position++,r=i=e.position;(n=e.input.charCodeAt(e.position))!==0;)if(n===39)if(F(e,r,e.position,!0),n=e.input.charCodeAt(++e.position),n===39)r=e.position,e.position++,i=e.position;else return!0;else O(n)?(F(e,r,i,!0),B(e,R(e,!1,t)),r=i=e.position):e.position===e.lineStart&&z(e)?N(e,`unexpected end of the document within a single quoted scalar`):(e.position++,i=e.position);N(e,`unexpected end of the stream within a single quoted scalar`)}e(xt,`readSingleQuotedScalar`);function St(e,t){var n,r,i,a,o,s=e.input.charCodeAt(e.position);if(s!==34)return!1;for(e.kind=`scalar`,e.result=``,e.position++,n=r=e.position;(s=e.input.charCodeAt(e.position))!==0;)if(s===34)return F(e,n,e.position,!0),e.position++,!0;else if(s===92){if(F(e,n,e.position,!0),s=e.input.charCodeAt(++e.position),O(s))R(e,!1,t);else if(s<256&&mt[s])e.result+=ht[s],e.position++;else if((o=lt(s))>0){for(i=o,a=0;i>0;i--)s=e.input.charCodeAt(++e.position),(o=ct(s))>=0?a=(a<<4)+o:N(e,`expected hexadecimal character`);e.result+=ft(a),e.position++}else N(e,`unknown escape sequence`);n=r=e.position}else O(s)?(F(e,n,r,!0),B(e,R(e,!1,t)),n=r=e.position):e.position===e.lineStart&&z(e)?N(e,`unexpected end of the document within a double quoted scalar`):(e.position++,r=e.position);N(e,`unexpected end of the stream within a double quoted scalar`)}e(St,`readDoubleQuotedScalar`);function Ct(e,t){var n=!0,r,i,a,o=e.tag,s,c=e.anchor,l,u,d,f,p,m=Object.create(null),h,g,_,v=e.input.charCodeAt(e.position);if(v===91)u=93,p=!1,s=[];else if(v===123)u=125,p=!0,s={};else return!1;for(e.anchor!==null&&(e.anchorMap[e.anchor]=s),v=e.input.charCodeAt(++e.position);v!==0;){if(R(e,!0,t),v=e.input.charCodeAt(e.position),v===u)return e.position++,e.tag=o,e.anchor=c,e.kind=p?`mapping`:`sequence`,e.result=s,!0;n?v===44&&N(e,`expected the node content, but found ','`):N(e,`missed comma between flow collection entries`),g=h=_=null,d=f=!1,v===63&&(l=e.input.charCodeAt(e.position+1),A(l)&&(d=f=!0,e.position++,R(e,!0,t))),r=e.line,i=e.lineStart,a=e.position,V(e,t,w,!1,!0),g=e.tag,h=e.result,R(e,!0,t),v=e.input.charCodeAt(e.position),(f||e.line===r)&&v===58&&(d=!0,v=e.input.charCodeAt(++e.position),R(e,!0,t),V(e,t,w,!1,!0),_=e.result),p?I(e,s,m,g,h,_,r,i,a):d?s.push(I(e,null,m,g,h,_,r,i,a)):s.push(h),R(e,!0,t),v=e.input.charCodeAt(e.position),v===44?(n=!0,v=e.input.charCodeAt(++e.position)):n=!1}N(e,`unexpected end of the stream within a flow collection`)}e(Ct,`readFlowCollection`);function wt(e,t){var n,r,i=E,a=!1,o=!1,c=t,l=0,u=!1,d,f=e.input.charCodeAt(e.position);if(f===124)r=!1;else if(f===62)r=!0;else return!1;for(e.kind=`scalar`,e.result=``;f!==0;)if(f=e.input.charCodeAt(++e.position),f===43||f===45)E===i?i=f===43?nt:tt:N(e,`repeat of a chomping mode identifier`);else if((d=ut(f))>=0)d===0?N(e,`bad explicit indentation width of a block scalar; it cannot be less than one`):o?N(e,`repeat of an indentation width identifier`):(c=t+d-1,o=!0);else break;if(k(f)){do f=e.input.charCodeAt(++e.position);while(k(f));if(f===35)do f=e.input.charCodeAt(++e.position);while(!O(f)&&f!==0)}for(;f!==0;){for(L(e),e.lineIndent=0,f=e.input.charCodeAt(e.position);(!o||e.lineIndentc&&(c=e.lineIndent),O(f)){l++;continue}if(e.lineIndentt)&&c!==0)N(e,`bad indentation of a sequence entry`);else if(e.lineIndentt)&&(g&&(o=e.line,s=e.lineStart,c=e.position),V(e,t,T,!0,i)&&(g?m=e.result:h=e.result),g||(I(e,d,f,p,m,h,o,s,c),p=m=h=null),R(e,!0,-1),v=e.input.charCodeAt(e.position)),(e.line===a||e.lineIndent>t)&&v!==0)N(e,`bad indentation of a mapping entry`);else if(e.lineIndentt?c=1:e.lineIndent===t?c=0:e.lineIndentt?c=1:e.lineIndent===t?c=0:e.lineIndent tag; it should be "scalar", not "`+e.kind+`"`),d=0,f=e.implicitTypes.length;d`),e.result!==null&&m.kind!==e.kind&&N(e,`unacceptable node kind for !<`+e.tag+`> tag; it should be "`+m.kind+`", not "`+e.kind+`"`),m.resolve(e.result,e.tag)?(e.result=m.construct(e.result,e.tag),e.anchor!==null&&(e.anchorMap[e.anchor]=e.result)):N(e,`cannot resolve a node with !<`+e.tag+`> explicit tag`)}return e.listener!==null&&e.listener(`close`,e),e.tag!==null||e.anchor!==null||u}e(V,`composeNode`);function At(e){var t=e.position,n,r,i,a=!1,o;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);(o=e.input.charCodeAt(e.position))!==0&&(R(e,!0,-1),o=e.input.charCodeAt(e.position),!(e.lineIndent>0||o!==37));){for(a=!0,o=e.input.charCodeAt(++e.position),n=e.position;o!==0&&!A(o);)o=e.input.charCodeAt(++e.position);for(r=e.input.slice(n,e.position),i=[],r.length<1&&N(e,`directive name must not be less than one character in length`);o!==0;){for(;k(o);)o=e.input.charCodeAt(++e.position);if(o===35){do o=e.input.charCodeAt(++e.position);while(o!==0&&!O(o));break}if(O(o))break;for(n=e.position;o!==0&&!A(o);)o=e.input.charCodeAt(++e.position);i.push(e.input.slice(n,e.position))}o!==0&&L(e),C.call(vt,r)?vt[r](e,r,i):P(e,`unknown document directive "`+r+`"`)}if(R(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45?(e.position+=3,R(e,!0,-1)):a&&N(e,`directives end mark is expected`),V(e,e.lineIndent-1,T,!1,!0),R(e,!0,-1),e.checkLineBreaks&&it.test(e.input.slice(t,e.position))&&P(e,`non-ASCII line breaks are interpreted as content`),e.documents.push(e.result),e.position===e.lineStart&&z(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,R(e,!0,-1));return}if(e.position=55296&&n<=56319&&t+1=56320&&r<=57343)?(n-55296)*1024+r-56320+65536:n}e(Y,`codePointAt`);function yn(e){return/^\n* /.test(e)}e(yn,`needIndentIndicator`);var bn=1,xn=2,Sn=3,Cn=4,X=5;function wn(e,t,n,r,i,a,o,s){var c,l=0,u=null,d=!1,f=!1,p=r!==-1,m=-1,h=_n(Y(e,0))&&vn(Y(e,e.length-1));if(t||o)for(c=0;c=65536?c+=2:c++){if(l=Y(e,c),!J(l))return X;h&&=gn(l,u,s),u=l}else{for(c=0;c=65536?c+=2:c++){if(l=Y(e,c),l===H)d=!0,p&&(f||=c-m-1>r&&e[m+1]!==` `,m=c);else if(!J(l))return X;h&&=gn(l,u,s),u=l}f||=p&&c-m-1>r&&e[m+1]!==` `}return!d&&!f?h&&!o&&!i(e)?bn:a===G?X:xn:n>9&&yn(e)?X:o?a===G?X:xn:f?Cn:Sn}e(wn,`chooseScalarStyle`);function Tn(t,n,r,i,a){t.dump=(function(){if(n.length===0)return t.quotingType===G?`""`:`''`;if(!t.noCompatMode&&(sn.indexOf(n)!==-1||cn.test(n)))return t.quotingType===G?`"`+n+`"`:`'`+n+`'`;var o=t.indent*Math.max(1,r),s=t.lineWidth===-1?-1:Math.max(Math.min(t.lineWidth,40),t.lineWidth-o),c=i||t.flowLevel>-1&&r>=t.flowLevel;function l(e){return mn(t,e)}switch(e(l,`testAmbiguity`),wn(n,c,t.indent,s,l,t.quotingType,t.forceQuotes&&!i,a)){case bn:return n;case xn:return`'`+n.replace(/'/g,`''`)+`'`;case Sn:return`|`+En(n,t.indent)+Dn(pn(n,o));case Cn:return`>`+En(n,t.indent)+Dn(pn(On(n,s),o));case X:return`"`+An(n)+`"`;default:throw new u(`impossible error: invalid scalar style`)}})()}e(Tn,`writeScalar`);function En(e,t){var n=yn(e)?String(t):``,r=e[e.length-1]===` +`;return n+(r&&(e[e.length-2]===` +`||e===` +`)?`+`:r?``:`-`)+` +`}e(En,`blockHeader`);function Dn(e){return e[e.length-1]===` +`?e.slice(0,-1):e}e(Dn,`dropEndingNewline`);function On(e,t){for(var n=/(\n+)([^\n]*)/g,r=(function(){var r=e.indexOf(` +`);return r=r===-1?e.length:r,n.lastIndex=r,kn(e.slice(0,r),t)})(),i=e[0]===` +`||e[0]===` `,a,o;o=n.exec(e);){var s=o[1],c=o[2];a=c[0]===` `,r+=s+(!i&&!a&&c!==``?` +`:``)+kn(c,t),i=a}return r}e(On,`foldString`);function kn(e,t){if(e===``||e[0]===` `)return e;for(var n=/ [^ ]/g,r,i=0,a,o=0,s=0,c=``;r=n.exec(e);)s=r.index,s-i>t&&(a=o>i?o:s,c+=` +`+e.slice(i,a),i=a+1),o=s;return c+=` +`,e.length-i>t&&o>i?c+=e.slice(i,o)+` +`+e.slice(o+1):c+=e.slice(i),c.slice(1)}e(kn,`foldLine`);function An(e){for(var t=``,n=0,r,i=0;i=65536?i+=2:i++)n=Y(e,i),r=W[n],!r&&J(n)?(t+=e[i],n>=65536&&(t+=e[i+1])):t+=r||un(n);return t}e(An,`escapeString`);function jn(e,t,n){var r=``,i=e.tag,a,o,s;for(a=0,o=n.length;a1024&&(u+=`? `),u+=e.dump+(e.condenseFlow?`"`:``)+`:`+(e.condenseFlow?``:` `),Q(e,t,l,!1,!1)&&(u+=e.dump,r+=u));e.tag=i,e.dump=`{`+r+`}`}e(Nn,`writeFlowMapping`);function Pn(e,t,n,r){var i=``,a=e.tag,o=Object.keys(n),s,c,l,d,f,p;if(e.sortKeys===!0)o.sort();else if(typeof e.sortKeys==`function`)o.sort(e.sortKeys);else if(e.sortKeys)throw new u(`sortKeys must be a boolean or a function`);for(s=0,c=o.length;s1024,f&&(e.dump&&H===e.dump.charCodeAt(0)?p+=`?`:p+=`? `),p+=e.dump,f&&(p+=K(e,t)),Q(e,t+1,d,!0,f)&&(e.dump&&H===e.dump.charCodeAt(0)?p+=`:`:p+=`: `,p+=e.dump,i+=p));e.tag=a,e.dump=i||`{}`}e(Pn,`writeBlockMapping`);function Z(e,t,n){var r,i=n?e.explicitTypes:e.implicitTypes,a,o,s,c;for(a=0,o=i.length;a tag resolver accepts not "`+c+`" style`);e.dump=r}return!0}return!1}e(Z,`detectType`);function Q(e,t,n,r,i,a,o){e.tag=null,e.dump=n,Z(e,n,!1)||Z(e,n,!0);var s=Ft.call(e.dump),c=r,l;r&&=e.flowLevel<0||e.flowLevel>t;var d=s===`[object Object]`||s===`[object Array]`,f,p;if(d&&(f=e.duplicates.indexOf(n),p=f!==-1),(e.tag!==null&&e.tag!==`?`||p||e.indent!==2&&t>0)&&(i=!1),p&&e.usedDuplicates[f])e.dump=`*ref_`+f;else{if(d&&p&&!e.usedDuplicates[f]&&(e.usedDuplicates[f]=!0),s===`[object Object]`)r&&Object.keys(e.dump).length!==0?(Pn(e,t,e.dump,i),p&&(e.dump=`&ref_`+f+e.dump)):(Nn(e,t,e.dump),p&&(e.dump=`&ref_`+f+` `+e.dump));else if(s===`[object Array]`)r&&e.dump.length!==0?(e.noArrayIndent&&!o&&t>0?Mn(e,t-1,e.dump,i):Mn(e,t,e.dump,i),p&&(e.dump=`&ref_`+f+e.dump)):(jn(e,t,e.dump),p&&(e.dump=`&ref_`+f+` `+e.dump));else if(s===`[object String]`)e.tag!==`?`&&Tn(e,e.dump,t,a,c);else if(s===`[object Undefined]`)return!1;else{if(e.skipInvalid)return!1;throw new u(`unacceptable kind of an object to dump `+s)}e.tag!==null&&e.tag!==`?`&&(l=encodeURI(e.tag[0]===`!`?e.tag.slice(1):e.tag).replace(/!/g,`%21`),l=e.tag[0]===`!`?`!`+l:l.slice(0,18)===`tag:yaml.org,2002:`?`!!`+l.slice(18):`!<`+l+`>`,e.dump=l+` `+e.dump)}return!0}e(Q,`writeNode`);function Fn(e,t){var n=[],r=[],i,a;for($(e,n,r),i=0,a=r.length;i{e.class||={},e.class.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{a as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/classDiagram-v2-EOCWNBFH-D6qCu_tS.js b/dist-desktop/assets/classDiagram-v2-EOCWNBFH-D6qCu_tS.js new file mode 100644 index 0000000..f51b5b4 --- /dev/null +++ b/dist-desktop/assets/classDiagram-v2-EOCWNBFH-D6qCu_tS.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import{i as t,n,r,t as i}from"./chunk-V7JOEXUC-Drt5hFEy.js";var a={parser:n,get db(){return new i},renderer:r,styles:t,init:e(e=>{e.class||={},e.class.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{a as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/client-CwgDvMJw.js b/dist-desktop/assets/client-CwgDvMJw.js new file mode 100644 index 0000000..154ec05 --- /dev/null +++ b/dist-desktop/assets/client-CwgDvMJw.js @@ -0,0 +1,3 @@ +import{i as e,n as t}from"./rolldown-runtime-aKtaBQYM.js";import{t as n}from"./react-BLJmJXjR.js";var r=`1.6.25`;function i(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}function a(){let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,`writable`)?e.writable:e.set!==void 0}function o(e){let t=e.split(` + at `);return t.length<=1?e:(t.splice(1,1),t.join(` + at `))}function s(e,t){class n extends e{#e;constructor(...e){if(a()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=o(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),n}var c={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};s(class extends Error{constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:c[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},Error);var l=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},u=i({INVALID_OAUTH_CONFIGURATION:`Invalid OAuth configuration`,TOKEN_URL_NOT_FOUND:`Invalid OAuth configuration. Token URL not found.`,PROVIDER_CONFIG_NOT_FOUND:`No config found for provider`,PROVIDER_ID_REQUIRED:`Provider ID is required`,INVALID_OAUTH_CONFIG:`Invalid OAuth configuration.`,SESSION_REQUIRED:`Session is required`,ISSUER_MISMATCH:`OAuth issuer mismatch. The authorization server issuer does not match the expected value (RFC 9207).`,ISSUER_MISSING:`OAuth issuer parameter missing. The authorization server did not include the required iss parameter (RFC 9207).`}),d=()=>({id:`generic-oauth-client`,version:r,$InferServerPlugin:{},$ERROR_CODES:u}),f=Object.create(null),p=e=>({}),m=new Proxy(f,{get(e,t){return p()[t]??f[t]},has(e,t){return t in p()||t in f},set(e,t,n){let r=p(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=p(!0);return delete n[t],!0},ownKeys(){let e=p(!0);return Object.keys(e)}});m.NODE_ENV;function h(e,t){return typeof process<`u`?{}[e]??t:typeof Deno<`u`?Deno.env.get(e)??t:typeof Bun<`u`?Bun.env[e]??t:t}Object.freeze({get BETTER_AUTH_SECRET(){return h(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return h(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return h(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return h(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return h(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return h(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return h(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});var g=47;function _(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===g;)t--;return t===e.length?e:e.slice(0,t)}function v(e){try{return(_(new URL(e).pathname)||`/`)!==`/`}catch{throw new l(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function y(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new l(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof l?t:new l(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function b(e,t=`/api/auth`){if(y(e),v(e))return e;let n=_(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function ee(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function te(e,t,n,r,i){if(e)return b(e,t);if(r!==!1){let e=m.BETTER_AUTH_URL||m.NEXT_PUBLIC_BETTER_AUTH_URL||m.PUBLIC_BETTER_AUTH_URL||m.NUXT_PUBLIC_BETTER_AUTH_URL||m.NUXT_PUBLIC_AUTH_URL||(m.BASE_URL===`/`?void 0:m.BASE_URL);if(e)return b(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&ee(o,`proto`)&&ee(a,`host`))try{return b(`${o}://${a}`,t)}catch{}if(n){let e=ne(n.url);if(!e)throw new l(`Could not get origin from request. Please provide a valid base URL.`);return b(e,t)}if(typeof window<`u`&&window.location)return b(window.location.origin,t)}function ne(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var re=[`javascript:`,`data:`,`vbscript:`];function ie(e){let t;try{t=new URL(e)}catch{return!0}return!re.includes(t.protocol)}var x=[],S=0,C=null,w=4,ae=globalThis.nanostoresGlobal||={epoch:0},oe=()=>{for(S=0;S{let t=[],n={get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(e){return n.lc=t.push(e),()=>{for(let t=S+w;t(e.events=e.events||{},e.events[n+D]||(e.events[n+D]=r(t=>{e.events[n].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let r=e.events[n],i=r.indexOf(t);r.splice(i,1),r.length||(delete e.events[n],e.events[n+D](),delete e.events[n+D])}),le=(e,t)=>O(e,t,se,t=>{let n=e.set,r=e.setKey;return e.setKey&&=(n,i)=>{let a;if(t({abort:()=>{a=!0},changed:n,newValue:{...e.value,[n]:i}}),!a)return r(n,i)},e.set=e=>{let r;if(t({abort:()=>{r=!0},newValue:e}),!r)return n(e)},()=>{e.set=n,e.setKey=r}}),ue=1e3,de=(e,t)=>O(e,n=>{let r=t(n);r&&e.events[E].push(r)},ce,t=>{let n=e.listen;e.listen=(...r)=>(!e.lc&&!e.active&&(e.active=!0,t()),n(...r));let r=e.off;return e.events[E]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[E])t();e.events[E]=[]}},ue)},()=>{e.listen=n,e.off=r}});function fe(e,t,n){let r=new Set(t);return e.listen((e,i,a)=>{(a===void 0?t.some(t=>e[t]!==i[t]):r.has(a)||r.has(a.split(/\.|\[/)[0]))&&n(e,i,a)})}function pe(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function k(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n{t(e.value,n)&&r()})}var he={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},ge=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,A={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},_e=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function ve(e){return e instanceof Date&&!isNaN(e.getTime())}function ye(e){let t=_e.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return ve(f)?f:null}function be(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in A)return A[s];if(!ge.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(he).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t){r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(a&&typeof t==`string`){let e=ye(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function xe(e,t={strict:!0}){return be(e,t)}var Se={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&ie(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},j=Symbol.for(`better-auth:broadcast-channel`),Ce=()=>Math.floor(Date.now()/1e3),we=class{listeners=new Set;name;constructor(e=`better-auth.message`){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(!(typeof window>`u`))try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:Ce()}))}catch{}}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=e=>{if(e.key!==this.name)return;let t=JSON.parse(e.newValue??`{}`);t?.event!==`session`||!t?.data||this.listeners.forEach(e=>e(t))};return window.addEventListener(`storage`,e),()=>{window.removeEventListener(`storage`,e)}}};function M(e=`better-auth.message`){return globalThis[j]||(globalThis[j]=new we(e)),globalThis[j]}var N=Symbol.for(`better-auth:focus-manager`),Te=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||typeof document>`u`||window.addEventListener===void 0)return()=>{};let e=()=>{document.visibilityState===`visible`&&this.setFocused(!0)};return document.addEventListener(`visibilitychange`,e,!1),()=>{document.removeEventListener(`visibilitychange`,e,!1)}}};function P(){return globalThis[N]||(globalThis[N]=new Te),globalThis[N]}var F=Symbol.for(`better-auth:online-manager`),Ee=class{listeners=new Set;isOnline=typeof navigator<`u`?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener(`online`,e,!1),window.addEventListener(`offline`,t,!1),()=>{window.removeEventListener(`online`,e,!1),window.removeEventListener(`offline`,t,!1)}}};function I(){return globalThis[F]||(globalThis[F]=new Ee),globalThis[F]}var L=()=>Math.floor(Date.now()/1e3),De=5;function Oe(e){let{fetchSession:t,shouldPollSession:n=()=>!0,sessionSignal:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={isInitialized:!1,lastSessionRequest:0},l=()=>s||I().isOnline,u=e=>{if(l()){if(e?.event===`storage`){t();return}if(e?.event===`poll`){c.lastSessionRequest=L(),t();return}if(e?.event===`visibilitychange`){if(L()-c.lastSessionRequest{M().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{n()&&u({event:`poll`})},a*1e3))},p=()=>{c.unsubscribeBroadcast=M().subscribe(()=>{u({event:`storage`})})},m=()=>{o&&(c.unsubscribeFocus=P().subscribe(()=>{u({event:`visibilitychange`})}))},h=()=>{c.unsubscribeOnline=I().subscribe(e=>{e&&u({event:`visibilitychange`})})},g=()=>{c.unsubscribeSignal=r.listen(()=>{t()})};return{init:()=>{c.isInitialized||(c.isInitialized=!0,f(),p(),m(),h(),g(),c.cleanupBroadcastSetup=M().setup(),c.cleanupFocusSetup=P().setup(),c.cleanupOnlineSetup=I().setup())},cleanup:()=>{c.isInitialized&&(c.pollInterval&&=(clearInterval(c.pollInterval),void 0),c.unsubscribeBroadcast&&=(c.unsubscribeBroadcast(),void 0),c.unsubscribeFocus&&=(c.unsubscribeFocus(),void 0),c.unsubscribeOnline&&=(c.unsubscribeOnline(),void 0),c.unsubscribeSignal&&=(c.unsubscribeSignal(),void 0),c.cleanupBroadcastSetup&&=(c.cleanupBroadcastSetup(),void 0),c.cleanupFocusSetup&&=(c.cleanupFocusSetup(),void 0),c.cleanupOnlineSetup&&=(c.cleanupOnlineSetup(),void 0),c.isInitialized=!1,c.lastSessionRequest=0)},triggerRefetch:u,broadcastSessionUpdate:d}}var ke=()=>typeof window>`u`;function R(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Ae(e){return!e||e.session===null&&e.user===null?null:e}function je(e,t){return k(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function Me(e,t){let n=T(!1),r,i=e=>s(e),a=T({data:null,error:null,isPending:!0,isRefetching:!1,refetch:i});me(a,je);let o=e=>{if(r!==e)return;let t=a.get();r=void 0,!(!t.isPending&&!t.isRefetching)&&a.set({...t,isPending:!1,isRefetching:!1,refetch:i})},s=async t=>{r?.abort();let n=new AbortController;r=n;let s=a.get();a.set({...s,isPending:s.data===null,isRefetching:!0,error:null,refetch:i});try{let r=await e(`/get-session`,{method:`GET`,query:t?.query,signal:n.signal});if(n.signal.aborted){o(n);return}let{data:s,error:c}=R(r);if(s?.needsRefresh)try{let t=await e(`/get-session`,{method:`POST`,signal:n.signal});if(n.signal.aborted){o(n);return}({data:s,error:c}=R(t))}catch{if(n.signal.aborted){o(n);return}}if(c){let e=a.get(),t=c?.status===401;a.set({data:t?null:e.data,error:c,isPending:!1,isRefetching:!1,refetch:i});return}let l=Ae(s),u=a.get(),d=u.data!=null&&l!=null&&k(u.data,l)?u.data:l;a.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:i})}catch(e){if(n.signal.aborted){o(n);return}let t=a.get();a.set({data:t.data,error:e,isPending:!1,isRefetching:!1,refetch:i})}},c=()=>{};return de(a,()=>{let e;ke()||(e=setTimeout(()=>{s()},0));let i=Oe({fetchSession:s,shouldPollSession:()=>a.get().data!=null,sessionSignal:n,options:t});return i.init(),c=i.broadcastSessionUpdate,()=>{e&&clearTimeout(e);let t=r;t?.abort(),t&&o(t),i.cleanup()}}),{session:a,$sessionSignal:n,broadcastSessionUpdate:e=>c(e)}}function z(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function B(e,t,n=`.`,r){if(!z(t))return B(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(Array.isArray(a)&&Array.isArray(i[t])?i[t]=[...a,...i[t]]:z(a)&&z(i[t])?i[t]=B(a,i[t],(n?`${n}.`:``)+t.toString(),r):i[t]=a))}return i}function Ne(e){return(...t)=>t.reduce((t,n)=>B(t,n,``,e),{})}var Pe=Ne(),Fe=Object.defineProperty,Ie=Object.defineProperties,Le=Object.getOwnPropertyDescriptors,V=Object.getOwnPropertySymbols,Re=Object.prototype.hasOwnProperty,ze=Object.prototype.propertyIsEnumerable,H=(e,t,n)=>t in e?Fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,U=(e,t)=>{for(var n in t||={})Re.call(t,n)&&H(e,n,t[n]);if(V)for(var n of V(t))ze.call(t,n)&&H(e,n,t[n]);return e},W=(e,t)=>Ie(e,Le(t)),Be=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},Ve=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let r=await i.init?.call(i,e.toString(),t);n=r.options||n,e=r.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},G=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Ge=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Ke(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Ge.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function qe(e){try{return JSON.parse(e),!0}catch{return!1}}function Je(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function Ye(e){try{return JSON.parse(e)}catch{return e}}function Xe(e){return typeof e==`function`}function Ze(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&Xe(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&Xe(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function Qe(...e){let t={};for(let n of e)if(n)if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}return t}async function $e(e){let t=new Headers(Qe(e?.headers,await We(e)));if(!t.has(`content-type`)){let n=et(e?.body);n&&t.set(`content-type`,n)}return t}function et(e){return Je(e)?`application/json`:null}function tt(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function nt(e,t){let{body:n}=e;return n?!Je(n)||typeof n==`string`?n:tt(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function rt(e,t){if(t?.method)return t.method.toUpperCase();if(e.startsWith(`@`)){let n=e.split(`@`)[1]?.split(`/`)[0];return ot.includes(n)?n.toUpperCase():t?.body?`POST`:`GET`}return t?.body?`POST`:`GET`}function it(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var at=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function K(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new at(n.issues);return n.value}var ot=[`get`,`post`,`put`,`patch`,`delete`],st=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){let r=e.plugins?.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1)?.schema||e.schema;if(r){let e=t;r.config?.prefix&&e.startsWith(r.config.prefix)&&(e=e.replace(r.config.prefix,``),r.config.baseURL&&(t=t.replace(r.config.prefix,r.config.baseURL))),r.config?.baseURL&&e.startsWith(r.config.baseURL)&&(e=e.replace(r.config.baseURL,``)),e.startsWith(`/`)&&e.charAt(1)===`@`&&(e=e.substring(1));let i=r.schema[e];if(i){let e=n?.headers;if(i.headers&&!n?.disableValidation){let t={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((e,n)=>{t[n.toLowerCase()]=e});else if(typeof n.headers==`object`)for(let[e,r]of Object.entries(n.headers))r!=null&&(t[e.toLowerCase()]=r)}let r=await K(i.headers,t),a={};for(let[e,t]of Object.entries(r))a[e.toLowerCase()]=t;e=a}let r=W(U({},n),{method:i.method,output:i.output,headers:e});return n?.disableValidation||(r=W(U({},r),{body:i.input?await K(i.input,n?.body):n?.body,params:i.params?await K(i.params,n?.params):n?.params,query:i.query?await K(i.query,n?.query):n?.query})),{url:t,options:r}}}return{url:t,options:n}}}),ct=e=>{async function t(t,n){let r=W(U(U({},e),n),{headers:Qe(e?.headers,n?.headers),plugins:[...e?.plugins||[],st(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await q(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await q(t,r)}return t},lt=e=>e===`.`||e===`..`;function ut(e,t){let n=e;for(let[e,r]of t)n=n.replace(e,r);if(lt(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function dt(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``;if(e.startsWith(`@`)){let t=e.toString().split(`@`)[1].split(`/`)[0];ot.includes(t)&&(e=e.replace(`@${t}/`,`/`))}a.endsWith(`/`)||(a+=`/`);let[o,s]=e.replace(a,``).split(`?`),c=new URLSearchParams(s);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)c.append(e,n);continue}else n=JSON.stringify(t);c.set(e,n)}let l=new Map;if(r)if(Array.isArray(r)){let e=o.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];l.set(n,String(e))}}else for(let[e,t]of Object.entries(r))l.set(`:${e}`,String(t));o=o.split(`/`).map(e=>ut(e,l)).join(`/`),o=o.replace(/^\/+/,``);let u=c.toString();return u=u.length>0?`?${u}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${o}${u}`,a):`${a}${o}${u}`}var q=async(e,t)=>{let{hooks:n,url:r,options:i}=await Ve(e,t),a=Ze(i),o=new AbortController,s=i.signal??o.signal,c=dt(r,i),l=await $e(i),u=nt(i,l),d=rt(r,i),f=W(U({},i),{url:c,headers:l,body:u,method:d,signal:s});for(let e of n.onRequest)if(e){let t=await e(f);typeof t==`object`&&t&&Object.assign(f,t)}(`pipeTo`in f&&typeof f.pipeTo==`function`||typeof t?.body?.pipe==`function`)&&(`duplex`in f||(f.duplex=`half`));let{clearTimeout:p}=it(i,o),m=await a(f.url,f);p();let h={response:m,request:f};for(let e of n.onResponse)if(e){let n=await e(W(U({},h),{response:t?.hookOptions?.cloneResponse?m.clone():m}));n instanceof Response?m=n:typeof n==`object`&&n&&(m=n.response)}if(m.ok){if(f.method===`HEAD`)return{data:``,error:null};let e=Ke(m),r={data:null,response:m,request:f};if(e===`json`||e===`text`){let e=await m.text();r.data=await(f.jsonParser??Ye)(e)}else r.data=await m[e]();f?.output&&f.output&&!f.disableValidation&&(r.data=await K(f.output,r.data));for(let e of n.onSuccess)e&&await e(W(U({},r),{response:t?.hookOptions?.cloneResponse?m.clone():m}));return t?.throw?r.data:{data:r.data,error:null}}let g=t?.jsonParser??Ye,_=await m.text(),v=qe(_),y=v?await g(_):null,b={response:m,responseText:_,request:f,error:W(U({},y),{status:m.status,statusText:m.statusText})};for(let e of n.onError)e&&await e(W(U({},b),{response:t?.hookOptions?.cloneResponse?m.clone():m}));if(t?.retry){let r=Ue(t.retry),i=t.retryAttempt??0;if(await r.shouldAttemptRetry(i,m)){for(let e of n.onRetry)e&&await e(h);let a=r.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await q(e,W(U({},t),{retryAttempt:i+1}))}}if(t?.throw)throw new Be(m.status,m.statusText,v?y:_);return{data:null,error:W(U({},y),{status:m.status,statusText:m.statusText})}},ft=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},pt=(e,t)=>{let n=`credentials`in Request.prototype,r=te(e?.baseURL,e?.basePath,void 0,t)??ft(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=ct({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?xe(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[Se],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=Me(d,e),h=e?.plugins||[],g={},_={$sessionSignal:f,session:p},v={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},y=[{signal:`$sessionSignal`,matcher(e){return e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`},callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of h)e.getAtoms&&Object.assign(_,e.getAtoms?.(d)),e.pathMethods&&Object.assign(v,e.pathMethods),e.atomListeners&&y.push(...e.atomListeners);let b={notify:e=>{_[e].set(!_[e].get())},listen:(e,t)=>{_[e].subscribe(t)},atoms:_};for(let t of h)t.getActions&&(g=Pe(t.getActions?.(d,b,e)??{},g));return{get baseURL(){return r},pluginsActions:g,pluginsAtoms:_,pluginPathMethods:v,atomListeners:y,$fetch:d,$store:b}};function mt(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function ht(e){return e.charAt(0).toUpperCase()+e.slice(1)}var gt=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,_t=/['\u2019]/g;function vt(e){return e.replace(_t,``).match(gt)??[]}function yt(e){return vt(e).map(e=>e.toLowerCase()).join(`-`)}function bt(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function xt(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||mt(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(yt).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=bt(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}var J=e(n(),1);function St(e,t={}){let n=(0,J.useRef)(e.get()),{keys:r,deps:i=[e,r]}=t,a=(0,J.useCallback)(t=>{let i=e=>{n.current!==e&&(n.current=e,t())};return i(e.value),r?.length?fe(e,r,i):e.listen(i)},i),o=()=>n.current;return(0,J.useSyncExternalStore)(a,o,o)}function Ct(e){return`use${ht(e)}`}function wt(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,$fetch:i,$store:a,atomListeners:o}=pt(e),s={};for(let[e,t]of Object.entries(r))s[Ct(e)]=()=>St(t);return xt({...n,...s,$fetch:i,$store:a},i,t,r,o)}var Tt=t({authClient:()=>Y,authEnabled:()=>!0,getBearerToken:()=>Z,signIn:()=>Et,signOut:()=>kt}),Y=wt({plugins:[d()],fetchOptions:{onRequest(e){let t=Z();return t&&e.headers.set(`Authorization`,`Bearer ${t}`),e}}}),X=`grok-auth.bearer-token`;function Z(){if(typeof window>`u`)return null;try{return window.sessionStorage.getItem(X)}catch{return null}}function Q(e){if(!(typeof window>`u`))try{e?window.sessionStorage.setItem(X,e):window.sessionStorage.removeItem(X)}catch{}}function $(){return typeof window<`u`&&window.location.hostname.endsWith(`.grok-sandbox.com`)}async function Et(e,t={}){let n=t.callbackURL??`/`,r=t.errorCallbackURL??`/`,i=$()?Dt(e):null;if(Z()||!$())try{await Y.signOut()}catch{}if(Q(null),$()){if(!i)throw Error(`Pop-up blocked — allow pop-ups for sign-in`);let e=await Ot(i);if(!e)throw Error(`Sign-in was cancelled or failed`);Q(e);try{await Y.getSession()}catch{}if(typeof window<`u`){let e=new URL(n,window.location.origin),t=window.location;(e.origin!==t.origin||e.pathname!==t.pathname||e.search!==t.search)&&(window.location.href=n)}return}let{data:a,error:o}=await Y.signIn.oauth2({providerId:e,callbackURL:n,errorCallbackURL:r});if(o)throw Error(o.message??`Sign-in failed`);a?.url&&(window.location.href=a.url)}function Dt(e){let t=`${window.location.origin}/auth/popup?providerId=${encodeURIComponent(e)}`,n=`grok-signin-${Date.now()}`;return window.open(t,n,`popup,width=500,height=650`)}function Ot(e){return new Promise(t=>{let n=window.location.origin,r=!1,i,a=e=>{r||(r=!0,c(),t(e))},o=e=>{if(e.origin!==n)return;let t=e.data;!t||t.source!==`grok-auth-popup`||a(t.token??null)},s=window.setInterval(()=>{e.closed&&(window.clearInterval(s),i=window.setTimeout(()=>a(null),400))},300);function c(){window.clearInterval(s),i!==void 0&&window.clearTimeout(i),window.removeEventListener(`message`,o)}window.addEventListener(`message`,o)})}async function kt(e=`/`){try{await Y.signOut()}finally{Q(null)}window.location.href=e}export{kt as i,Tt as n,Et as r,Y as t}; \ No newline at end of file diff --git a/dist-desktop/assets/core-CwxXejkd.js b/dist-desktop/assets/core-CwxXejkd.js new file mode 100644 index 0000000..7eed138 --- /dev/null +++ b/dist-desktop/assets/core-CwxXejkd.js @@ -0,0 +1 @@ +async function e(e,t={},n){return window.__TAURI_INTERNALS__.invoke(e,t,n)}export{e as invoke}; \ No newline at end of file diff --git a/dist-desktop/assets/cose-bilkent-JH36ORCC-ClqQrHIF.js b/dist-desktop/assets/cose-bilkent-JH36ORCC-ClqQrHIF.js new file mode 100644 index 0000000..ad06af1 --- /dev/null +++ b/dist-desktop/assets/cose-bilkent-JH36ORCC-ClqQrHIF.js @@ -0,0 +1 @@ +import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as r,p as i}from"./src-UMNXGZaF.js";import{t as a}from"./cytoscape.esm-CQFVGiJu.js";var o=t(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.layoutBase=r():n.layoutBase=r()})(e,function(){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=26)})([(function(e,t,n){function r(){}r.QUALITY=1,r.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,r.DEFAULT_INCREMENTAL=!1,r.DEFAULT_ANIMATION_ON_LAYOUT=!0,r.DEFAULT_ANIMATION_DURING_LAYOUT=!1,r.DEFAULT_ANIMATION_PERIOD=50,r.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,r.DEFAULT_GRAPH_MARGIN=15,r.NODE_DIMENSIONS_INCLUDE_LABELS=!1,r.SIMPLE_NODE_SIZE=40,r.SIMPLE_NODE_HALF_SIZE=r.SIMPLE_NODE_SIZE/2,r.EMPTY_COMPOUND_NODE_SIZE=40,r.MIN_EDGE_LENGTH=1,r.WORLD_BOUNDARY=1e6,r.INITIAL_WORLD_BOUNDARY=r.WORLD_BOUNDARY/1e3,r.WORLD_CENTER_X=1200,r.WORLD_CENTER_Y=900,e.exports=r}),(function(e,t,n){var r=n(2),i=n(8),a=n(9);function o(e,t,n){r.call(this,n),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=n,this.bendpoints=[],this.source=e,this.target=t}for(var s in o.prototype=Object.create(r.prototype),r)o[s]=r[s];o.prototype.getSource=function(){return this.source},o.prototype.getTarget=function(){return this.target},o.prototype.isInterGraph=function(){return this.isInterGraph},o.prototype.getLength=function(){return this.length},o.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},o.prototype.getBendpoints=function(){return this.bendpoints},o.prototype.getLca=function(){return this.lca},o.prototype.getSourceInLca=function(){return this.sourceInLca},o.prototype.getTargetInLca=function(){return this.targetInLca},o.prototype.getOtherEnd=function(e){if(this.source===e)return this.target;if(this.target===e)return this.source;throw`Node is not incident with this edge`},o.prototype.getOtherEndInGraph=function(e,t){for(var n=this.getOtherEnd(e),r=t.getGraphManager().getRoot();;){if(n.getOwner()==t)return n;if(n.getOwner()==r)break;n=n.getOwner().getParent()}return null},o.prototype.updateLength=function(){var e=[,,,,];this.isOverlapingSourceAndTarget=i.getIntersection(this.target.getRect(),this.source.getRect(),e),this.isOverlapingSourceAndTarget||(this.lengthX=e[0]-e[2],this.lengthY=e[1]-e[3],Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},o.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},e.exports=o}),(function(e,t,n){function r(e){this.vGraphObject=e}e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(13),o=n(0),s=n(16),c=n(4);function l(e,t,n,o){n==null&&o==null&&(o=t),r.call(this,o),e.graphManager!=null&&(e=e.graphManager),this.estimatedSize=i.MIN_VALUE,this.inclusionTreeDepth=i.MAX_VALUE,this.vGraphObject=o,this.edges=[],this.graphManager=e,n!=null&&t!=null?this.rect=new a(t.x,t.y,n.width,n.height):this.rect=new a}for(var u in l.prototype=Object.create(r.prototype),r)l[u]=r[u];l.prototype.getEdges=function(){return this.edges},l.prototype.getChild=function(){return this.child},l.prototype.getOwner=function(){return this.owner},l.prototype.getWidth=function(){return this.rect.width},l.prototype.setWidth=function(e){this.rect.width=e},l.prototype.getHeight=function(){return this.rect.height},l.prototype.setHeight=function(e){this.rect.height=e},l.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},l.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},l.prototype.getCenter=function(){return new c(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},l.prototype.getLocation=function(){return new c(this.rect.x,this.rect.y)},l.prototype.getRect=function(){return this.rect},l.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},l.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},l.prototype.setRect=function(e,t){this.rect.x=e.x,this.rect.y=e.y,this.rect.width=t.width,this.rect.height=t.height},l.prototype.setCenter=function(e,t){this.rect.x=e-this.rect.width/2,this.rect.y=t-this.rect.height/2},l.prototype.setLocation=function(e,t){this.rect.x=e,this.rect.y=t},l.prototype.moveBy=function(e,t){this.rect.x+=e,this.rect.y+=t},l.prototype.getEdgeListToNode=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(r.target==e){if(r.source!=n)throw`Incorrect edge source!`;t.push(r)}}),t},l.prototype.getEdgesBetween=function(e){var t=[],n=this;return n.edges.forEach(function(r){if(!(r.source==n||r.target==n))throw`Incorrect edge source and/or target`;(r.target==e||r.source==e)&&t.push(r)}),t},l.prototype.getNeighborsList=function(){var e=new Set,t=this;return t.edges.forEach(function(n){if(n.source==t)e.add(n.target);else{if(n.target!=t)throw`Incorrect incidency!`;e.add(n.source)}}),e},l.prototype.withChildren=function(){var e=new Set,t,n;if(e.add(this),this.child!=null)for(var r=this.child.getNodes(),i=0;it&&(this.rect.x-=(this.labelWidth-t)/2,this.setWidth(this.labelWidth)),this.labelHeight>n&&(this.labelPos==`center`?this.rect.y-=(this.labelHeight-n)/2:this.labelPos==`top`&&(this.rect.y-=this.labelHeight-n),this.setHeight(this.labelHeight))}}},l.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==i.MAX_VALUE)throw`assert failed`;return this.inclusionTreeDepth},l.prototype.transform=function(e){var t=this.rect.x;t>o.WORLD_BOUNDARY?t=o.WORLD_BOUNDARY:t<-o.WORLD_BOUNDARY&&(t=-o.WORLD_BOUNDARY);var n=this.rect.y;n>o.WORLD_BOUNDARY?n=o.WORLD_BOUNDARY:n<-o.WORLD_BOUNDARY&&(n=-o.WORLD_BOUNDARY);var r=new c(t,n),i=e.inverseTransformPoint(r);this.setLocation(i.x,i.y)},l.prototype.getLeft=function(){return this.rect.x},l.prototype.getRight=function(){return this.rect.x+this.rect.width},l.prototype.getTop=function(){return this.rect.y},l.prototype.getBottom=function(){return this.rect.y+this.rect.height},l.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},e.exports=l}),(function(e,t,n){function r(e,t){e==null&&t==null?(this.x=0,this.y=0):(this.x=e,this.y=t)}r.prototype.getX=function(){return this.x},r.prototype.getY=function(){return this.y},r.prototype.setX=function(e){this.x=e},r.prototype.setY=function(e){this.y=e},r.prototype.getDifference=function(e){return new DimensionD(this.x-e.x,this.y-e.y)},r.prototype.getCopy=function(){return new r(this.x,this.y)},r.prototype.translate=function(e){return this.x+=e.width,this.y+=e.height,this},e.exports=r}),(function(e,t,n){var r=n(2),i=n(10),a=n(0),o=n(6),s=n(3),c=n(1),l=n(13),u=n(12),d=n(11);function f(e,t,n){r.call(this,n),this.estimatedSize=i.MIN_VALUE,this.margin=a.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=e,t!=null&&t instanceof o?this.graphManager=t:t!=null&&t instanceof Layout&&(this.graphManager=t.graphManager)}for(var p in f.prototype=Object.create(r.prototype),r)f[p]=r[p];f.prototype.getNodes=function(){return this.nodes},f.prototype.getEdges=function(){return this.edges},f.prototype.getGraphManager=function(){return this.graphManager},f.prototype.getParent=function(){return this.parent},f.prototype.getLeft=function(){return this.left},f.prototype.getRight=function(){return this.right},f.prototype.getTop=function(){return this.top},f.prototype.getBottom=function(){return this.bottom},f.prototype.isConnected=function(){return this.isConnected},f.prototype.add=function(e,t,n){if(t==null&&n==null){var r=e;if(this.graphManager==null)throw`Graph has no graph mgr!`;if(this.getNodes().indexOf(r)>-1)throw`Node already in graph!`;return r.owner=this,this.getNodes().push(r),r}else{var i=e;if(!(this.getNodes().indexOf(t)>-1&&this.getNodes().indexOf(n)>-1))throw`Source or target not in graph!`;if(!(t.owner==n.owner&&t.owner==this))throw`Both owners must be this graph!`;return t.owner==n.owner?(i.source=t,i.target=n,i.isInterGraph=!1,this.getEdges().push(i),t.edges.push(i),n!=t&&n.edges.push(i),i):null}},f.prototype.remove=function(e){var t=e;if(e instanceof s){if(t==null)throw`Node is null!`;if(!(t.owner!=null&&t.owner==this))throw`Owner graph is invalid!`;if(this.graphManager==null)throw`Owner graph manager is invalid!`;for(var n=t.edges.slice(),r,i=n.length,a=0;a-1&&u>-1))throw`Source and/or target doesn't know this edge!`;r.source.edges.splice(l,1),r.target!=r.source&&r.target.edges.splice(u,1);var o=r.source.owner.getEdges().indexOf(r);if(o==-1)throw`Not in owner's edge list!`;r.source.owner.getEdges().splice(o,1)}},f.prototype.updateLeftTop=function(){for(var e=i.MAX_VALUE,t=i.MAX_VALUE,n,r,a,o=this.getNodes(),s=o.length,c=0;cn&&(e=n),t>r&&(t=r)}return e==i.MAX_VALUE?null:(a=o[0].getParent().paddingLeft==null?this.margin:o[0].getParent().paddingLeft,this.left=t-a,this.top=e-a,new u(this.left,this.top))},f.prototype.updateBounds=function(e){for(var t=i.MAX_VALUE,n=-i.MAX_VALUE,r=i.MAX_VALUE,a=-i.MAX_VALUE,o,s,c,u,d,f=this.nodes,p=f.length,m=0;mo&&(t=o),nc&&(r=c),ao&&(t=o),nc&&(r=c),a=this.nodes.length){var c=0;n.forEach(function(t){t.owner==e&&c++}),c==this.nodes.length&&(this.isConnected=!0)}},e.exports=f}),(function(e,t,n){var r,i=n(1);function a(e){r=n(5),this.layout=e,this.graphs=[],this.edges=[]}a.prototype.addRoot=function(){var e=this.layout.newGraph(),t=this.layout.newNode(null),n=this.add(e,t);return this.setRootGraph(n),this.rootGraph},a.prototype.add=function(e,t,n,r,i){if(n==null&&r==null&&i==null){if(e==null)throw`Graph is null!`;if(t==null)throw`Parent node is null!`;if(this.graphs.indexOf(e)>-1)throw`Graph already in this graph mgr!`;if(this.graphs.push(e),e.parent!=null)throw`Already has a parent!`;if(t.child!=null)throw`Already has a child!`;return e.parent=t,t.child=e,e}else{i=n,r=t,n=e;var a=r.getOwner(),o=i.getOwner();if(!(a!=null&&a.getGraphManager()==this))throw`Source not in this graph mgr!`;if(!(o!=null&&o.getGraphManager()==this))throw`Target not in this graph mgr!`;if(a==o)return n.isInterGraph=!1,a.add(n,r,i);if(n.isInterGraph=!0,n.source=r,n.target=i,this.edges.indexOf(n)>-1)throw`Edge already in inter-graph edge list!`;if(this.edges.push(n),!(n.source!=null&&n.target!=null))throw`Edge source and/or target is null!`;if(!(n.source.edges.indexOf(n)==-1&&n.target.edges.indexOf(n)==-1))throw`Edge already in source and/or target incidency list!`;return n.source.edges.push(n),n.target.edges.push(n),n}},a.prototype.remove=function(e){if(e instanceof r){var t=e;if(t.getGraphManager()!=this)throw`Graph not in this graph mgr`;if(!(t==this.rootGraph||t.parent!=null&&t.parent.graphManager==this))throw`Invalid parent node!`;var n=[];n=n.concat(t.getEdges());for(var a,o=n.length,s=0;s=t.getRight()?n[0]+=Math.min(t.getX()-e.getX(),e.getRight()-t.getRight()):t.getX()<=e.getX()&&t.getRight()>=e.getRight()&&(n[0]+=Math.min(e.getX()-t.getX(),t.getRight()-e.getRight())),e.getY()<=t.getY()&&e.getBottom()>=t.getBottom()?n[1]+=Math.min(t.getY()-e.getY(),e.getBottom()-t.getBottom()):t.getY()<=e.getY()&&t.getBottom()>=e.getBottom()&&(n[1]+=Math.min(e.getY()-t.getY(),t.getBottom()-e.getBottom()));var a=Math.abs((t.getCenterY()-e.getCenterY())/(t.getCenterX()-e.getCenterX()));t.getCenterY()===e.getCenterY()&&t.getCenterX()===e.getCenterX()&&(a=1);var o=a*n[0],s=n[1]/a;n[0]o)return n[0]=r,n[1]=c,n[2]=a,n[3]=y,!1;if(ia)return n[0]=s,n[1]=i,n[2]=_,n[3]=o,!1;if(ra?(n[0]=u,n[1]=d,C=!0):(n[0]=l,n[1]=c,C=!0):T===D&&(r>a?(n[0]=s,n[1]=c,C=!0):(n[0]=f,n[1]=d,C=!0)),-E===D?a>r?(n[2]=v,n[3]=y,w=!0):(n[2]=_,n[3]=g,w=!0):E===D&&(a>r?(n[2]=h,n[3]=g,w=!0):(n[2]=b,n[3]=y,w=!0)),C&&w)return!1;if(r>a?i>o?(O=this.getCardinalDirection(T,D,4),k=this.getCardinalDirection(E,D,2)):(O=this.getCardinalDirection(-T,D,3),k=this.getCardinalDirection(-E,D,1)):i>o?(O=this.getCardinalDirection(-T,D,1),k=this.getCardinalDirection(-E,D,3)):(O=this.getCardinalDirection(T,D,2),k=this.getCardinalDirection(E,D,4)),!C)switch(O){case 1:j=c,A=r+-m/D,n[0]=A,n[1]=j;break;case 2:A=f,j=i+p*D,n[0]=A,n[1]=j;break;case 3:j=d,A=r+m/D,n[0]=A,n[1]=j;break;case 4:A=u,j=i+-p*D,n[0]=A,n[1]=j;break}if(!w)switch(k){case 1:N=g,M=a+-S/D,n[2]=M,n[3]=N;break;case 2:M=b,N=o+x*D,n[2]=M,n[3]=N;break;case 3:N=y,M=a+S/D,n[2]=M,n[3]=N;break;case 4:M=v,N=o+-x*D,n[2]=M,n[3]=N;break}}return!1},i.getCardinalDirection=function(e,t,n){return e>t?n:1+n%4},i.getIntersection=function(e,t,n,i){if(i==null)return this.getIntersection2(e,t,n);var a=e.x,o=e.y,s=t.x,c=t.y,l=n.x,u=n.y,d=i.x,f=i.y,p=void 0,m=void 0,h=void 0,g=void 0,_=void 0,v=void 0,y=void 0,b=void 0,x=void 0;return h=c-o,_=a-s,y=s*o-a*c,g=f-u,v=l-d,b=d*u-l*f,x=h*v-g*_,x===0?null:(p=(_*b-v*y)/x,m=(g*y-h*b)/x,new r(p,m))},i.angleOfVector=function(e,t,n,r){var i=void 0;return e===n?i=r0?1:e<0?-1:0},r.floor=function(e){return e<0?Math.ceil(e):Math.floor(e)},r.ceil=function(e){return e<0?Math.floor(e):Math.ceil(e)},e.exports=r}),(function(e,t,n){function r(){}r.MAX_VALUE=2147483647,r.MIN_VALUE=-2147483648,e.exports=r}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n0&&t;){for(s.push(l[0]);s.length>0&&t;){var u=s[0];s.splice(0,1),o.add(u);for(var d=u.getEdges(),a=0;a-1&&l.splice(h,1)}o=new Set,c=new Map}}return e},f.prototype.createDummyNodesForBendpoints=function(e){for(var t=[],n=e.source,r=this.graphManager.calcLowestCommonAncestor(e.source,e.target),i=0;i0){for(var i=this.edgeToDummyNodes.get(n),a=0;a=0&&t.splice(d,1),s.getNeighborsList().forEach(function(e){if(n.indexOf(e)<0){var t=r.get(e)-1;t==1&&l.push(e),r.set(e,t)}})}n=n.concat(l),(t.length==1||t.length==2)&&(i=!0,a=t[0])}return a},f.prototype.setGraphManager=function(e){this.graphManager=e},e.exports=f}),(function(e,t,n){function r(){}r.seed=1,r.x=0,r.nextDouble=function(){return r.x=Math.sin(r.seed++)*1e4,r.x-Math.floor(r.x)},e.exports=r}),(function(e,t,n){var r=n(4);function i(e,t){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}i.prototype.getWorldOrgX=function(){return this.lworldOrgX},i.prototype.setWorldOrgX=function(e){this.lworldOrgX=e},i.prototype.getWorldOrgY=function(){return this.lworldOrgY},i.prototype.setWorldOrgY=function(e){this.lworldOrgY=e},i.prototype.getWorldExtX=function(){return this.lworldExtX},i.prototype.setWorldExtX=function(e){this.lworldExtX=e},i.prototype.getWorldExtY=function(){return this.lworldExtY},i.prototype.setWorldExtY=function(e){this.lworldExtY=e},i.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},i.prototype.setDeviceOrgX=function(e){this.ldeviceOrgX=e},i.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},i.prototype.setDeviceOrgY=function(e){this.ldeviceOrgY=e},i.prototype.getDeviceExtX=function(){return this.ldeviceExtX},i.prototype.setDeviceExtX=function(e){this.ldeviceExtX=e},i.prototype.getDeviceExtY=function(){return this.ldeviceExtY},i.prototype.setDeviceExtY=function(e){this.ldeviceExtY=e},i.prototype.transformX=function(e){var t=0,n=this.lworldExtX;return n!=0&&(t=this.ldeviceOrgX+(e-this.lworldOrgX)*this.ldeviceExtX/n),t},i.prototype.transformY=function(e){var t=0,n=this.lworldExtY;return n!=0&&(t=this.ldeviceOrgY+(e-this.lworldOrgY)*this.ldeviceExtY/n),t},i.prototype.inverseTransformX=function(e){var t=0,n=this.ldeviceExtX;return n!=0&&(t=this.lworldOrgX+(e-this.ldeviceOrgX)*this.lworldExtX/n),t},i.prototype.inverseTransformY=function(e){var t=0,n=this.ldeviceExtY;return n!=0&&(t=this.lworldOrgY+(e-this.ldeviceOrgY)*this.lworldExtY/n),t},i.prototype.inverseTransformPoint=function(e){return new r(this.inverseTransformX(e.x),this.inverseTransformY(e.y))},e.exports=i}),(function(e,t,n){function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);ta.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*a.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-a.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT_INCREMENTAL):(e>a.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(a.COOLING_ADAPTATION_FACTOR,1-(e-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*(1-a.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},l.prototype.calcSpringForces=function(){for(var e=this.getAllEdges(),t,n=0;n0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n,r,i,o,s=this.getAllNodes(),c;if(this.useFRGridVariant)for(this.totalIterations%a.GRID_CALCULATION_CHECK_PERIOD==1&&e&&this.updateGrid(),c=new Set,n=0;nc||s>c)&&(e.gravitationForceX=-this.gravityConstant*i,e.gravitationForceY=-this.gravityConstant*a)):(c=t.getEstimatedSize()*this.compoundGravityRangeFactor,(o>c||s>c)&&(e.gravitationForceX=-this.gravityConstant*i*this.compoundGravityConstant,e.gravitationForceY=-this.gravityConstant*a*this.compoundGravityConstant))},l.prototype.isConverged=function(){var e,t=!1;return this.totalIterations>this.maxIterations/3&&(t=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),e=this.totalDisplacement=c.length||u>=c[0].length)){for(var d=0;de}}]),e}()}),(function(e,t,n){var r=function(){function e(e,t){for(var n=0;n2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;i(this,e),this.sequence1=t,this.sequence2=n,this.match_score=r,this.mismatch_penalty=a,this.gap_penalty=o,this.iMax=t.length+1,this.jMax=n.length+1,this.grid=Array(this.iMax);for(var s=0;s=0;n--){var r=this.listeners[n];r.event===e&&r.callback===t&&this.listeners.splice(n,1)}},i.emit=function(e,t){for(var n=0;n{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(o()):typeof define==`function`&&define.amd?define([`layout-base`],r):typeof e==`object`?e.coseBase=r(o()):n.coseBase=r(n.layoutBase)})(e,function(e){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=7)})([(function(t,n){t.exports=e}),(function(e,t,n){var r=n(0).FDLayoutConstants;function i(){}for(var a in r)i[a]=r[a];i.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,i.DEFAULT_RADIAL_SEPARATION=r.DEFAULT_EDGE_LENGTH,i.DEFAULT_COMPONENT_SEPERATION=60,i.TILE=!0,i.TILING_PADDING_VERTICAL=10,i.TILING_PADDING_HORIZONTAL=10,i.TREE_REDUCTION_ON_INCREMENTAL=!1,e.exports=i}),(function(e,t,n){var r=n(0).FDLayoutEdge;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),(function(e,t,n){var r=n(0).LGraph;function i(e,t,n){r.call(this,e,t,n)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),(function(e,t,n){var r=n(0).LGraphManager;function i(e){r.call(this,e)}for(var a in i.prototype=Object.create(r.prototype),r)i[a]=r[a];e.exports=i}),(function(e,t,n){var r=n(0).FDLayoutNode,i=n(0).IMath;function a(e,t,n,i){r.call(this,e,t,n,i)}for(var o in a.prototype=Object.create(r.prototype),r)a[o]=r[o];a.prototype.move=function(){var e=this.graphManager.getLayout();this.displacementX=e.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY=e.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren,Math.abs(this.displacementX)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementX=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementX)),Math.abs(this.displacementY)>e.coolingFactor*e.maxNodeDisplacement&&(this.displacementY=e.coolingFactor*e.maxNodeDisplacement*i.sign(this.displacementY)),this.child==null||this.child.getNodes().length==0?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),e.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},a.prototype.propogateDisplacementToChildren=function(e,t){for(var n=this.getChild().getNodes(),r,i=0;i0)this.positionNodesRadially(e);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n),this.positionNodesRandomly()}}else if(c.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var t=new Set(this.getAllNodes()),n=this.nodesWithGravity.filter(function(e){return t.has(e)});this.graphManager.setAllNodesToApplyGravitation(n)}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},v.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%l.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-this.coolingCycle**+(Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var e=new Set(this.getAllNodes()),t=this.nodesWithGravity.filter(function(t){return e.has(t)});this.graphManager.setAllNodesToApplyGravitation(t),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=l.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var n=!this.isTreeGrowing&&!this.isGrowthFinished,r=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(n,r),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},v.prototype.getPositionsData=function(){for(var e=this.graphManager.getAllNodes(),t={},n=0;n1){var s;for(s=0;sr&&(r=Math.floor(o.y)),a=Math.floor(o.x+c.DEFAULT_COMPONENT_SEPERATION)}this.transform(new f(u.WORLD_CENTER_X-o.x/2,u.WORLD_CENTER_Y-o.y/2))},v.radialLayout=function(e,t,n){var r=Math.max(this.maxDiagonalInTree(e),c.DEFAULT_RADIAL_SEPARATION);v.branchRadialLayout(t,null,0,359,0,r);var i=g.calculateBounds(e),a=new _;a.setDeviceOrgX(i.getMinX()),a.setDeviceOrgY(i.getMinY()),a.setWorldOrgX(n.x),a.setWorldOrgY(n.y);for(var o=0;o1;){var _=g[0];g.splice(0,1);var y=u.indexOf(_);y>=0&&u.splice(y,1),p--,d--}m=t==null?0:(u.indexOf(g[0])+1)%p;for(var b=Math.abs(r-n)/d,x=m;f!=d;x=++x%p){var S=u[x].getOtherEnd(e);if(S!=t){var C=(n+f*b)%360,w=(C+b)%360;v.branchRadialLayout(S,e,C,w,i+a,a),f++}}},v.maxDiagonalInTree=function(e){for(var t=m.MIN_VALUE,n=0;nt&&(t=r)}return t},v.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},v.prototype.groupZeroDegreeMembers=function(){var e=this,t={};this.memberGroups={},this.idToDummyNode={};for(var n=[],r=this.graphManager.getAllNodes(),i=0;i1){var r=`DummyCompound_`+n;e.memberGroups[r]=t[n];var i=t[n][0].getParent(),a=new o(e.graphManager);a.id=r,a.paddingLeft=i.paddingLeft||0,a.paddingRight=i.paddingRight||0,a.paddingBottom=i.paddingBottom||0,a.paddingTop=i.paddingTop||0,e.idToDummyNode[r]=a;var s=e.getGraphManager().add(e.newGraph(),a),c=i.getChild();c.add(a);for(var l=0;l=0;e--){var t=this.compoundOrder[e],n=t.id,r=t.paddingLeft,i=t.paddingTop;this.adjustLocations(this.tiledMemberPack[n],t.rect.x,t.rect.y,r,i)}},v.prototype.repopulateZeroDegreeMembers=function(){var e=this,t=this.tiledZeroDegreePack;Object.keys(t).forEach(function(n){var r=e.idToDummyNode[n],i=r.paddingLeft,a=r.paddingTop;e.adjustLocations(t[n],r.rect.x,r.rect.y,i,a)})},v.prototype.getToBeTiled=function(e){var t=e.id;if(this.toBeTiled[t]!=null)return this.toBeTiled[t];var n=e.getChild();if(n==null)return this.toBeTiled[t]=!1,!1;for(var r=n.getNodes(),i=0;i0)return this.toBeTiled[t]=!1,!1;if(a.getChild()==null){this.toBeTiled[a.id]=!1;continue}if(!this.getToBeTiled(a))return this.toBeTiled[t]=!1,!1}return this.toBeTiled[t]=!0,!0},v.prototype.getNodeDegree=function(e){e.id;for(var t=e.getEdges(),n=0,r=0;rc&&(c=u.rect.height)}n+=c+e.verticalPadding}},v.prototype.tileCompoundMembers=function(e,t){var n=this;this.tiledMemberPack=[],Object.keys(e).forEach(function(r){var i=t[r];n.tiledMemberPack[r]=n.tileNodes(e[r],i.paddingLeft+i.paddingRight),i.rect.width=n.tiledMemberPack[r].width,i.rect.height=n.tiledMemberPack[r].height})},v.prototype.tileNodes=function(e,t){var n={rows:[],rowWidth:[],rowHeight:[],width:0,height:t,verticalPadding:c.TILING_PADDING_VERTICAL,horizontalPadding:c.TILING_PADDING_HORIZONTAL};e.sort(function(e,t){return e.rect.width*e.rect.height>t.rect.width*t.rect.height?-1:+(e.rect.width*e.rect.height0&&(a+=e.horizontalPadding),e.rowWidth[n]=a,e.width0&&(o+=e.verticalPadding);var s=0;o>e.rowHeight[n]&&(s=e.rowHeight[n],e.rowHeight[n]=o,s=e.rowHeight[n]-s),e.height+=s,e.rows[n].push(t)},v.prototype.getShortestRowIndex=function(e){for(var t=-1,n=Number.MAX_VALUE,r=0;rn&&(t=r,n=e.rowWidth[r]);return t},v.prototype.canAddHorizontal=function(e,t,n){var r=this.getShortestRowIndex(e);if(r<0)return!0;var i=e.rowWidth[r];if(i+e.horizontalPadding+t<=e.width)return!0;var a=0;e.rowHeight[r]0&&(a=n+e.verticalPadding-e.rowHeight[r]);var o=e.width-i>=t+e.horizontalPadding?(e.height+a)/(i+t+e.horizontalPadding):(e.height+a)/e.width;a=n+e.verticalPadding;var s=e.widtha&&t!=n){r.splice(-1,1),e.rows[n].push(i),e.rowWidth[t]=e.rowWidth[t]-a,e.rowWidth[n]=e.rowWidth[n]+a,e.width=e.rowWidth[instance.getLongestRowIndex(e)];for(var o=Number.MIN_VALUE,s=0;so&&(o=r[s].height);t>0&&(o+=e.verticalPadding);var c=e.rowHeight[t]+e.rowHeight[n];e.rowHeight[t]=o,e.rowHeight[n]0)for(var u=i;u<=a;u++)c[0]+=this.grid[u][o-1].length+this.grid[u][o].length-1;if(a0)for(var u=o;u<=s;u++)c[3]+=this.grid[i-1][u].length+this.grid[i][u].length-1;for(var d=m.MAX_VALUE,f,p,h=0;h{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r(s()):typeof define==`function`&&define.amd?define([`cose-base`],r):typeof e==`object`?e.cytoscapeCoseBilkent=r(s()):n.cytoscapeCoseBilkent=r(n.coseBase)})(e,function(e){return(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=1)})([(function(t,n){t.exports=e}),(function(e,t,n){var r=n(0).layoutBase.LayoutConstants,i=n(0).layoutBase.FDLayoutConstants,a=n(0).CoSEConstants,o=n(0).CoSELayout,s=n(0).CoSENode,c=n(0).layoutBase.PointD,l=n(0).layoutBase.DimensionD,u={ready:function(){},stop:function(){},quality:`default`,nodeDimensionsIncludeLabels:!1,refresh:30,fit:!0,padding:10,randomize:!0,nodeRepulsion:4500,idealEdgeLength:50,edgeElasticity:.45,nestingFactor:.1,gravity:.25,numIter:2500,tile:!0,animate:`end`,animationDuration:500,tilingPaddingVertical:10,tilingPaddingHorizontal:10,gravityRangeCompound:1.5,gravityCompound:1,gravityRange:3.8,initialEnergyOnIncremental:.5};function d(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n}function f(e){this.options=d(u,e),p(this.options)}var p=function(e){e.nodeRepulsion!=null&&(a.DEFAULT_REPULSION_STRENGTH=i.DEFAULT_REPULSION_STRENGTH=e.nodeRepulsion),e.idealEdgeLength!=null&&(a.DEFAULT_EDGE_LENGTH=i.DEFAULT_EDGE_LENGTH=e.idealEdgeLength),e.edgeElasticity!=null&&(a.DEFAULT_SPRING_STRENGTH=i.DEFAULT_SPRING_STRENGTH=e.edgeElasticity),e.nestingFactor!=null&&(a.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=i.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=e.nestingFactor),e.gravity!=null&&(a.DEFAULT_GRAVITY_STRENGTH=i.DEFAULT_GRAVITY_STRENGTH=e.gravity),e.numIter!=null&&(a.MAX_ITERATIONS=i.MAX_ITERATIONS=e.numIter),e.gravityRange!=null&&(a.DEFAULT_GRAVITY_RANGE_FACTOR=i.DEFAULT_GRAVITY_RANGE_FACTOR=e.gravityRange),e.gravityCompound!=null&&(a.DEFAULT_COMPOUND_GRAVITY_STRENGTH=i.DEFAULT_COMPOUND_GRAVITY_STRENGTH=e.gravityCompound),e.gravityRangeCompound!=null&&(a.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=i.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=e.gravityRangeCompound),e.initialEnergyOnIncremental!=null&&(a.DEFAULT_COOLING_FACTOR_INCREMENTAL=i.DEFAULT_COOLING_FACTOR_INCREMENTAL=e.initialEnergyOnIncremental),e.quality==`draft`?r.QUALITY=0:e.quality==`proof`?r.QUALITY=2:r.QUALITY=1,a.NODE_DIMENSIONS_INCLUDE_LABELS=i.NODE_DIMENSIONS_INCLUDE_LABELS=r.NODE_DIMENSIONS_INCLUDE_LABELS=e.nodeDimensionsIncludeLabels,a.DEFAULT_INCREMENTAL=i.DEFAULT_INCREMENTAL=r.DEFAULT_INCREMENTAL=!e.randomize,a.ANIMATE=i.ANIMATE=r.ANIMATE=e.animate,a.TILE=e.tile,a.TILING_PADDING_VERTICAL=typeof e.tilingPaddingVertical==`function`?e.tilingPaddingVertical.call():e.tilingPaddingVertical,a.TILING_PADDING_HORIZONTAL=typeof e.tilingPaddingHorizontal==`function`?e.tilingPaddingHorizontal.call():e.tilingPaddingHorizontal};f.prototype.run=function(){var e,t,n=this.options;this.idToLNode={};var r=this.layout=new o,i=this;i.stopped=!1,this.cy=this.options.cy,this.cy.trigger({type:`layoutstart`,layout:this});var a=r.newGraphManager();this.gm=a;var s=this.options.eles.nodes(),c=this.options.eles.edges();this.root=a.addRoot(),this.processChildrenList(this.root,this.getTopMostNodes(s),r);for(var l=0;l0){var h=n.getGraphManager().add(n.newGraph(),u);this.processChildrenList(h,o,n)}}},f.prototype.stop=function(){return this.stopped=!0,this};var m=function(e){e(`layout`,`cose-bilkent`,f)};typeof cytoscape<`u`&&m(cytoscape),e.exports=m})])})}))(),1);a.use(c.default);function l(e,t){e.forEach(e=>{let n={id:e.id,labelText:e.label,height:e.height,width:e.width,padding:e.padding??0};Object.keys(e).forEach(t=>{[`id`,`label`,`height`,`width`,`padding`,`x`,`y`].includes(t)||(n[t]=e[t])}),t.add({group:`nodes`,data:n,position:{x:e.x??0,y:e.y??0}})})}n(l,`addNodes`);function u(e,t){e.forEach(e=>{let n={id:e.id,source:e.start,target:e.end};Object.keys(e).forEach(t=>{[`id`,`start`,`end`].includes(t)||(n[t]=e[t])}),t.add({group:`edges`,data:n})})}n(u,`addEdges`);function d(e){return new Promise(t=>{let n=i(`body`).append(`div`).attr(`id`,`cy`).attr(`style`,`display:none`),o=a({container:document.getElementById(`cy`),style:[{selector:`edge`,style:{"curve-style":`bezier`}}]});n.remove(),l(e.nodes,o),u(e.edges,o),o.nodes().forEach(function(e){e.layoutDimensions=()=>{let t=e.data();return{w:t.width,h:t.height}}}),o.layout({name:`cose-bilkent`,quality:`proof`,styleEnabled:!1,animate:!1}).run(),o.ready(e=>{r.info(`Cytoscape ready`,e),t(o)})})}n(d,`createCytoscapeInstance`);function f(e){return e.nodes().map(e=>{let t=e.data(),n=e.position(),r={id:t.id,x:n.x,y:n.y};return Object.keys(t).forEach(e=>{e!==`id`&&(r[e]=t[e])}),r})}n(f,`extractPositionedNodes`);function p(e){return e.edges().map(e=>{let t=e.data(),n=e._private.rscratch,r={id:t.id,source:t.source,target:t.target,startX:n.startX,startY:n.startY,midX:n.midX,midY:n.midY,endX:n.endX,endY:n.endY};return Object.keys(t).forEach(e=>{[`id`,`source`,`target`].includes(e)||(r[e]=t[e])}),r})}n(p,`extractPositionedEdges`);async function m(e,t){r.debug(`Starting cose-bilkent layout algorithm`);try{h(e);let t=await d(e),n=f(t),i=p(t);return r.debug(`Layout completed: ${n.length} nodes, ${i.length} edges`),{nodes:n,edges:i}}catch(e){throw r.error(`Error in cose-bilkent layout algorithm:`,e),e}}n(m,`executeCoseBilkentLayout`);function h(e){if(!e)throw Error(`Layout data is required`);if(!e.config)throw Error(`Configuration is required in layout data`);if(!e.rootNode)throw Error(`Root node is required`);if(!e.nodes||!Array.isArray(e.nodes))throw Error(`No nodes found in layout data`);if(!Array.isArray(e.edges))throw Error(`Edges array is required in layout data`);return!0}n(h,`validateLayoutData`);var g=n(async(e,t,{insertCluster:n,insertEdge:r,insertEdgeLabel:i,insertMarkers:a,insertNode:o,log:s,positionEdgeLabel:c},{algorithm:l})=>{let u={},d={},f=t.select(`g`);a(f,e.markers,e.type,e.diagramId);let p=f.insert(`g`).attr(`class`,`subgraphs`),h=f.insert(`g`).attr(`class`,`edgePaths`),g=f.insert(`g`).attr(`class`,`edgeLabels`),_=f.insert(`g`).attr(`class`,`nodes`);s.debug(`Inserting nodes into DOM for dimension calculation`),await Promise.all(e.nodes.map(async t=>{if(t.isGroup){let e={...t};d[t.id]=e,u[t.id]=e,await n(p,t)}else{let n={...t};u[t.id]=n;let r=await o(_,t,{config:e.config,dir:e.direction||`TB`}),i=r.node().getBBox();n.width=i.width,n.height=i.height,n.domId=r,s.debug(`Node ${t.id} dimensions: ${i.width}x${i.height}`)}})),s.debug(`Running cose-bilkent layout algorithm`);let v=await m({...e,nodes:e.nodes.map(e=>{let t=u[e.id];return{...e,width:t.width,height:t.height}})},e.config);s.debug(`Positioning nodes based on layout results`),v.nodes.forEach(e=>{let t=u[e.id];t?.domId&&(t.domId.attr(`transform`,`translate(${e.x}, ${e.y})`),t.x=e.x,t.y=e.y,s.debug(`Positioned node ${t.id} at center (${e.x}, ${e.y})`))}),v.edges.forEach(t=>{let n=e.edges.find(e=>e.id===t.id);n&&(n.points=[{x:t.startX,y:t.startY},{x:t.midX,y:t.midY},{x:t.endX,y:t.endY}])}),s.debug(`Inserting and positioning edges`),await Promise.all(e.edges.map(async t=>{await i(g,t);let n=u[t.start??``],a=u[t.end??``];if(n&&a){let i=v.edges.find(e=>e.id===t.id);if(i){s.debug(`APA01 positionedEdge`,i);let o={...t};c(o,r(h,o,d,e.type,n,a,e.diagramId))}else{let i={...t,points:[{x:n.x||0,y:n.y||0},{x:a.x||0,y:a.y||0}]};c(i,r(h,i,d,e.type,n,a,e.diagramId))}}})),s.debug(`Cose-bilkent rendering completed`)},`render`);export{g as render}; \ No newline at end of file diff --git a/dist-desktop/assets/cynefin-VYW2F7L2-4m18BxUG.js b/dist-desktop/assets/cynefin-VYW2F7L2-4m18BxUG.js new file mode 100644 index 0000000..ac41342 --- /dev/null +++ b/dist-desktop/assets/cynefin-VYW2F7L2-4m18BxUG.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-OSBZ3O6U-CX9EQ5t2.js";export{e as createCynefinServices}; \ No newline at end of file diff --git a/dist-desktop/assets/cynefinDiagram-TSTJHNR4-CAKFzgf0.js b/dist-desktop/assets/cynefinDiagram-TSTJHNR4-CAKFzgf0.js new file mode 100644 index 0000000..5a55412 --- /dev/null +++ b/dist-desktop/assets/cynefinDiagram-TSTJHNR4-CAKFzgf0.js @@ -0,0 +1,62 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,f as l,v as u,w as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-Z7xZAZRH.js";var _=e(()=>({domains:new Map,transitions:[]}),`createDefaultData`),v=_(),y={getDomains:e(()=>v.domains,`getDomains`),getTransitions:e(()=>v.transitions,`getTransitions`),setDomains:e(e=>{if(e)for(let t of e){let e=t.domain,n=(t.items??[]).map(e=>({label:e.label}));v.domains.set(e,{name:e,items:n})}},`setDomains`),setTransitions:e(e=>{e&&(v.transitions=e.filter(e=>e.from===e.to?(t.warn(`Cynefin: self-loop transition on domain "${e.from}" is not meaningful and will be skipped.`),!1):!0).map(e=>({from:e.from,to:e.to,label:e.label||void 0})))},`setTransitions`),getConfig:e(()=>p({...l.cynefin,...s().cynefin}),`getConfig`),clear:e(()=>{o(),v=_()},`clear`),setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:d,getAccDescription:u,setAccDescription:r},b=e(e=>{h(e,y),y.setDomains(e.domains),y.setTransitions(e.transitions)},`populate`),x={parse:e(async e=>{let n=await g(`cynefin`,e);t.debug(n),b(n)},`parse`)};function S(e){let t=e+1831565813|0;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}e(S,`seededRandom`);function C(e){let t=0;for(let n=0;n{let n=e/2,r=t/2;return{complex:{cx:n/2,cy:r/2,x:0,y:0,w:n,h:r},complicated:{cx:n+n/2,cy:r/2,x:n,y:0,w:n,h:r},chaotic:{cx:n/2,cy:r+r/2,x:0,y:r,w:n,h:r},clear:{cx:n+n/2,cy:r+r/2,x:n,y:r,w:n,h:r},confusion:{cx:n,cy:r,x:n*.7,y:r*.7,w:n*.6,h:r*.6}}},`getDomainLayouts`),j=e(()=>p(n(),s().themeVariables).cynefin,`getCynefinDomainColors`),M=3,N={draw:e((e,n,r,i)=>{let a=i.db,o=a.getDomains(),s=a.getTransitions(),l=a.getDiagramTitle(),u=a.getAccTitle(),d=a.getAccDescription(),f=a.getConfig(),p=j();t.debug(`Rendering Cynefin diagram`);let h=f.width,g=f.height,_=f.padding,v=f.showDomainDescriptions,y=f.boundaryAmplitude,b=h+_*2,x=g+_*2,S={complex:p.complexBg,complicated:p.complicatedBg,clear:p.clearBg,chaotic:p.chaoticBg,confusion:p.confusionBg},C=m(n);c(C,x,b,f.useMaxWidth??!0),C.attr(`viewBox`,`0 0 ${b} ${x}`),u&&C.append(`title`).text(u),d&&C.append(`desc`).text(d);let N=C.append(`g`).attr(`transform`,`translate(${_}, ${_})`),P=A(h,g),F=w(f.seed,n),I=N.append(`g`).attr(`class`,`cynefin-backgrounds`),L=[`complex`,`complicated`,`chaotic`,`clear`];for(let e of L){let t=P[e];I.append(`rect`).attr(`class`,`cynefinDomain`).attr(`x`,t.x).attr(`y`,t.y).attr(`width`,t.w).attr(`height`,t.h).attr(`fill`,S[e]).attr(`fill-opacity`,.4).attr(`stroke`,`none`)}let R=N.append(`g`).attr(`class`,`cynefin-boundaries`);R.append(`path`).attr(`class`,`cynefinBoundary`).attr(`d`,T(h,g,F,y)).attr(`fill`,`none`),R.append(`path`).attr(`class`,`cynefinBoundary`).attr(`d`,E(h,g,F+100,y)).attr(`fill`,`none`),R.append(`path`).attr(`class`,`cynefinCliff`).attr(`d`,D(h,g)).attr(`fill`,`none`);let z=h*.15,B=g*.15;N.append(`path`).attr(`class`,`cynefinConfusion`).attr(`d`,O(h/2,g/2,z,B)).attr(`fill`,S.confusion).attr(`fill-opacity`,.5);let V=N.append(`g`).attr(`class`,`cynefin-labels`);for(let e of L){let t=P[e];V.append(`text`).attr(`class`,`cynefinDomainLabel`).attr(`x`,t.cx).attr(`y`,v?t.cy-30:t.cy).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(e.charAt(0).toUpperCase()+e.slice(1))}if(V.append(`text`).attr(`class`,`cynefinDomainLabel`).attr(`x`,h/2).attr(`y`,v?g/2-10:g/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(`Confusion`),v){let e=N.append(`g`).attr(`class`,`cynefin-subtitles`);for(let t of L){let n=P[t],r=k[t];e.append(`text`).attr(`class`,`cynefinSubtitle`).attr(`x`,n.cx).attr(`y`,n.cy-10).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(r.model),e.append(`text`).attr(`class`,`cynefinSubtitle`).attr(`x`,n.cx).attr(`y`,n.cy+5).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(r.practice)}e.append(`text`).attr(`class`,`cynefinSubtitle`).attr(`x`,h/2).attr(`y`,g/2+8).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(k.confusion.practice)}let H=N.append(`g`).attr(`class`,`cynefin-items`);for(let e of[`complex`,`complicated`,`chaotic`,`clear`,`confusion`]){let t=o.get(e);if(!t||t.items.length===0)continue;let n=P[e],r=e===`confusion`,i=t.items,a=0;r&&t.items.length>M&&(a=t.items.length-M,i=t.items.slice(0,M));let s;if(r){let e=v?22:14;s=n.cy+e}else s=n.cy+(v?25:15);if([...i].forEach((t,r)=>{let i=s+r*30,a=H.append(`g`),o=a.append(`text`).attr(`class`,`cynefinItemText`).attr(`x`,0).attr(`y`,26/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`central`).text(t.label),c=t.label.length*7,l=o.node();if(l&&typeof l.getBBox==`function`){let e=l.getBBox();e.width>0&&(c=e.width)}let u=c+20,d=n.cx-u/2;a.attr(`transform`,`translate(${d}, ${i})`),a.insert(`rect`,`text`).attr(`class`,`cynefinItem`).attr(`x`,0).attr(`y`,0).attr(`width`,u).attr(`height`,26).attr(`rx`,4).attr(`ry`,4).attr(`fill`,S[e]).attr(`fill-opacity`,.95),o.attr(`x`,u/2).attr(`y`,26/2)}),a>0){let t=s+i.length*30,r=`+${a} more`,o=H.append(`g`),c=o.append(`text`).attr(`class`,`cynefinItemText`).attr(`x`,0).attr(`y`,26/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`central`).text(r),l=r.length*7,u=c.node();if(u&&typeof u.getBBox==`function`){let e=u.getBBox();e.width>0&&(l=e.width)}let d=l+20,f=n.cx-d/2;o.attr(`transform`,`translate(${f}, ${t})`),o.insert(`rect`,`text`).attr(`class`,`cynefinItemOverflow`).attr(`x`,0).attr(`y`,0).attr(`width`,d).attr(`height`,26).attr(`rx`,4).attr(`ry`,4).attr(`fill`,S[e]).attr(`fill-opacity`,.6),c.attr(`x`,d/2).attr(`y`,26/2)}}if(s.length>0){let e=C.select(`defs`).empty()?C.append(`defs`):C.select(`defs`),r=`cynefin-arrow-${n}`;e.append(`marker`).attr(`id`,r).attr(`viewBox`,`0 0 10 10`).attr(`refX`,9).attr(`refY`,5).attr(`markerWidth`,6).attr(`markerHeight`,6).attr(`orient`,`auto-start-reverse`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`class`,`cynefinArrowHead`);let i=N.append(`g`).attr(`class`,`cynefin-arrows`);s.forEach(e=>{let n=P[e.from],a=P[e.to];if(!n||!a)return;if(e.from===e.to){t.warn(`Cynefin renderer: skipping self-loop on domain "${e.from}"`);return}let o=n.cx,s=n.cy,c=a.cx,l=a.cy,u=(o+c)/2,d=(s+l)/2,f=c-o,p=l-s,m=Math.sqrt(f*f+p*p),h=m*.15,g=-p/m,_=f/m,v=u+g*h,y=d+_*h;i.append(`path`).attr(`class`,`cynefinArrowLine`).attr(`d`,`M${o},${s} Q${v},${y} ${c},${l}`).attr(`fill`,`none`).attr(`marker-end`,`url(#${r})`),e.label&&i.append(`text`).attr(`class`,`cynefinArrowLabel`).attr(`x`,v).attr(`y`,y-6).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`auto`).text(e.label)})}l&&N.append(`text`).attr(`class`,`cynefinTitle`).attr(`x`,h/2).attr(`y`,-_/2).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(l)},`draw`)},P=e(()=>p(n(),s().themeVariables).cynefin,`getCynefinTheme`),F={parser:x,db:y,renderer:N,styles:e(()=>{let e=P();return` + .cynefinDomain { + stroke: none; + } + .cynefinDomainLabel { + font-size: ${e.domainFontSize}px; + font-weight: bold; + fill: ${e.labelColor}; + } + .cynefinSubtitle { + font-size: ${e.itemFontSize-1}px; + fill: ${e.textColor}; + font-style: italic; + } + .cynefinItem { + fill-opacity: 0.95; + stroke: ${e.boundaryColor}; + stroke-width: 1; + } + .cynefinItemText { + font-size: ${e.itemFontSize}px; + fill: ${e.textColor}; + } + .cynefinItemOverflow { + fill-opacity: 0.6; + stroke: ${e.boundaryColor}; + stroke-width: 1; + stroke-dasharray: 3 2; + } + .cynefinBoundary { + stroke: ${e.boundaryColor}; + stroke-width: ${e.boundaryWidth}; + stroke-dasharray: 6 3; + } + .cynefinCliff { + stroke: ${e.cliffColor}; + stroke-width: ${e.cliffWidth}; + } + .cynefinConfusion { + stroke: ${e.boundaryColor}; + stroke-width: 1.5; + stroke-dasharray: 4 2; + } + .cynefinArrowLine { + stroke: ${e.arrowColor}; + stroke-width: ${e.arrowWidth}; + fill: none; + } + .cynefinArrowHead { + fill: ${e.arrowColor}; + stroke: none; + } + .cynefinArrowLabel { + font-size: ${e.itemFontSize-1}px; + fill: ${e.textColor}; + } + .cynefinTitle { + font-size: ${e.domainFontSize+2}px; + font-weight: bold; + fill: ${e.labelColor}; + } + `},`styles`)};export{F as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/cytoscape.esm-CQFVGiJu.js b/dist-desktop/assets/cytoscape.esm-CQFVGiJu.js new file mode 100644 index 0000000..6fb80b4 --- /dev/null +++ b/dist-desktop/assets/cytoscape.esm-CQFVGiJu.js @@ -0,0 +1,321 @@ +function e(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function s(e,t,n){return(t=h(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function l(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function u(){throw TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function d(){throw TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function f(e,n){return t(e)||l(e,n)||_(e,n)||u()}function p(e){return n(e)||c(e)||_(e)||d()}function m(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return String(e)}function h(e){var t=m(e,`string`);return typeof t==`symbol`?t:t+``}function g(e){"@babel/helpers - typeof";return g=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},g(e)}function _(t,n){if(t){if(typeof t==`string`)return e(t,n);var r={}.toString.call(t).slice(8,-1);return r===`Object`&&t.constructor&&(r=t.constructor.name),r===`Map`||r===`Set`?Array.from(t):r===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}var v=typeof window>`u`?null:window,y=v?v.navigator:null;v&&v.document;var b=g(``),x=g({}),S=g(function(){}),C=typeof HTMLElement>`u`?`undefined`:g(HTMLElement),w=function(e){return e&&e.instanceString&&E(e.instanceString)?e.instanceString():null},T=function(e){return e!=null&&g(e)==b},E=function(e){return e!=null&&g(e)===S},D=function(e){return!N(e)&&(Array.isArray?Array.isArray(e):e!=null&&e instanceof Array)},O=function(e){return e!=null&&g(e)===x&&!D(e)&&e.constructor===Object},k=function(e){return e!=null&&g(e)===x},A=function(e){return e!=null&&g(e)===g(1)&&!isNaN(e)},j=function(e){return A(e)&&Math.floor(e)===e},M=function(e){if(C!==`undefined`)return e!=null&&e instanceof HTMLElement},N=function(e){return P(e)||F(e)},P=function(e){return w(e)===`collection`&&e._private.single},F=function(e){return w(e)===`collection`&&!e._private.single},I=function(e){return w(e)===`core`},L=function(e){return w(e)===`stylesheet`},R=function(e){return w(e)===`event`},z=function(e){return e==null||!!(e===``||e.match(/^\s+$/))},B=function(e){return typeof HTMLElement>`u`?!1:e instanceof HTMLElement},V=function(e){return O(e)&&A(e.x1)&&A(e.x2)&&A(e.y1)&&A(e.y2)},H=function(e){return k(e)&&E(e.then)},U=function(){return y&&y.userAgent.match(/msie|trident|edge/i)},W=function(e,t){t||=function(){if(arguments.length===1)return arguments[0];if(arguments.length===0)return`undefined`;for(var e=[],t=0;tt)},ce=function(e,t){return-1*se(e,t)},X=Object.assign==null?function(e){for(var t=arguments,n=1;n1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}var u=RegExp(`^`+re+`$`).exec(e);if(u){if(n=parseInt(u[1]),n<0?n=(360- -1*n%360)%360:n>360&&(n%=360),n/=360,r=parseFloat(u[2]),r<0||r>100||(r/=100,i=parseFloat(u[3]),i<0||i>100)||(i/=100,a=u[4],a!==void 0&&(a=parseFloat(a),a<0||a>1)))return;if(r===0)o=s=c=Math.round(i*255);else{var d=i<.5?i*(1+r):i+r-i*r,f=2*i-d;o=Math.round(255*l(f,d,n+1/3)),s=Math.round(255*l(f,d,n)),c=Math.round(255*l(f,d,n-1/3))}t=[o,s,c,a]}return t},de=function(e){var t,n=RegExp(`^`+te+`$`).exec(e);if(n){t=[];for(var r=[],i=1;i<=3;i++){var a=n[i];if(a[a.length-1]===`%`&&(r[i]=!0),a=parseFloat(a),r[i]&&(a=a/100*255),a<0||a>255)return;t.push(Math.floor(a))}var o=r[1]||r[2]||r[3],s=r[1]&&r[2]&&r[3];if(o&&!s)return;var c=n[4];if(c!==void 0){if(c=parseFloat(c),c<0||c>1)return;t.push(c)}}return t},fe=function(e){return me[e.toLowerCase()]},pe=function(e){return(D(e)?e:null)||fe(e)||le(e)||de(e)||ue(e)},me={transparent:[0,0,0,0],aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},he=function(e){for(var t=e.map,n=e.keys,r=n.length,i=0;i=s||t<0||_&&n>=d}function C(){var e=t();if(S(e))return w(e);p=setTimeout(C,x(e))}function w(e){return p=void 0,v&&l?y(e):(l=u=void 0,f)}function T(){p!==void 0&&clearTimeout(p),h=0,l=m=u=p=void 0}function E(){return p===void 0?f:w(t())}function D(){var e=t(),n=S(e);if(l=arguments,u=this,m=e,n){if(p===void 0)return b(m);if(_)return clearTimeout(p),p=setTimeout(C,s),y(m)}return p===void 0&&(p=setTimeout(C,s)),f}return D.cancel=T,D.flush=E,D}return it=o,it}var st=ve(ot()),ct=v?v.performance:null,lt=ct&&ct.now?function(){return ct.now()}:function(){return Date.now()},ut=function(){if(v){if(v.requestAnimationFrame)return function(e){v.requestAnimationFrame(e)};if(v.mozRequestAnimationFrame)return function(e){v.mozRequestAnimationFrame(e)};if(v.webkitRequestAnimationFrame)return function(e){v.webkitRequestAnimationFrame(e)};if(v.msRequestAnimationFrame)return function(e){v.msRequestAnimationFrame(e)}}return function(e){e&&setTimeout(function(){e(lt())},1e3/60)}}(),dt=function(e){return ut(e)},ft=lt,pt=9261,mt=65599,ht=5381,gt=function(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:pt,n;n=e.next(),!n.done;)t=t*mt+n.value|0;return t},_t=function(e){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:pt)*mt+e|0},vt=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ht;return(t<<5)+t+e|0},yt=function(e,t){return e*2097152+t},bt=function(e){return e[0]*2097152+e[1]},xt=function(e,t){return[_t(e[0],t[0]),vt(e[1],t[1])]},St=function(e,t){var n={value:0,done:!1},r=0,i=e.length;return gt({next:function(){return r=0;r--)e[r]===t&&e.splice(r,1)},Jt=function(e){e.splice(0,e.length)},Yt=function(e,t){for(var n=0;n`u`?`undefined`:g(Set))===$t?en:Set,nn=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(e===void 0||t===void 0||!I(e)){Lt(`An element must have a core reference and parameters set`);return}var r=t.group;if(r??=t.data&&t.data.source!=null&&t.data.target!=null?`edges`:`nodes`,r!==`nodes`&&r!==`edges`){Lt("An element must be of type `nodes` or `edges`; you specified `"+r+"`");return}this.length=1,this[0]=this;var i=this._private={cy:e,single:!0,data:t.data||{},position:t.position||{x:0,y:0},autoWidth:void 0,autoHeight:void 0,autoPadding:void 0,compoundBoundsClean:!1,listeners:[],group:r,style:{},rstyle:{},styleCxts:[],styleKeys:{},removed:!0,selected:!!t.selected,selectable:t.selectable===void 0||!!t.selectable,locked:!!t.locked,grabbed:!1,grabbable:t.grabbable===void 0||!!t.grabbable,pannable:t.pannable===void 0?r===`edges`:!!t.pannable,active:!1,classes:new tn,animation:{current:[],queue:[]},rscratch:{},scratch:t.scratch||{},edges:[],children:[],parent:t.parent&&t.parent.isNode()?t.parent:null,traversalCache:{},backgrounding:!1,bbCache:null,bbCacheShift:{x:0,y:0},bodyBounds:null,overlayBounds:null,labelBounds:{all:null,source:null,target:null,main:null},arrowBounds:{source:null,target:null,"mid-source":null,"mid-target":null}};if(i.position.x??(i.position.x=0),i.position.y??(i.position.y=0),t.renderedPosition){var a=t.renderedPosition,o=e.pan(),s=e.zoom();i.position={x:(a.x-o.x)/s,y:(a.y-o.y)/s}}var c=[];D(t.classes)?c=t.classes:T(t.classes)&&(c=t.classes.split(/\s+/));for(var l=0,u=c.length;lt)},l=function(e,t,i,a,o){var s;if(i??=0,o??=n,i<0)throw Error(`lo must be non-negative`);for(a??=e.length;in;0<=n?t++:t--)l.push(t);return l}).apply(this).reverse(),c=[],a=0,o=s.length;ah;0<=h?++f:--f)g.push(a(e,r));return g},m=function(e,t,r,i){var a,o,s;for(i??=n,a=e[r];r>t;){if(s=r-1>>1,o=e[s],i(a,o)<0){e[r]=o,r=s;continue}break}return e[r]=a},h=function(e,t,r){var i,a,o,s,c;for(r??=n,a=e.length,c=t,o=e[t],i=2*t+1;i0;){var x=_.pop(),S=h(x),C=x.id();if(d[C]=S,S!==1/0)for(var w=x.neighborhood().intersect(p),E=0;E0)for(n.unshift(t);u[i];){var a=u[i];n.unshift(a.edge),n.unshift(a.node),r=a.node,i=r.id()}return o.spawn(n)}}}},gn={kruskal:function(e){e||=function(e){return 1};for(var t=this.byGroup(),n=t.nodes,r=t.edges,i=n.length,a=Array(i),o=n,s=function(e){for(var t=0;t0;){if(b(),S++,y===l){for(var C=[],w=i,T=l,E=g[T];C.unshift(w),E!=null&&C.unshift(E),w=h[T],w!=null;)T=w.id(),E=g[T];return{found:!0,distance:u[y],path:this.spawn(C),steps:S}}f[y]=!0;for(var D=v._private.edges,O=0;OE&&(p[w]=E,g[w]=C,_[w]=y),!i){var D=C*l+S;!i&&p[D]>E&&(p[D]=E,g[D]=S,_[D]=y)}}}for(var O=0;O1&&arguments[1]!==void 0?arguments[1]:a,r=v(e),i=[],o=r;;){if(o==null)return t.spawn();var c=_(o),l=c.edge,u=c.pred;if(i.unshift(o[0]),o.same(n)&&i.length>0)break;l!=null&&i.unshift(l),o=u}return s.spawn(i)},x=0;x=0;l--){var u=c[l],d=u[1],f=u[2];(t[d]===o&&t[f]===s||t[d]===s&&t[f]===o)&&c.splice(l,1)}for(var p=0;pr;)t=wn(Math.floor(Math.random()*t.length),e,t),n--;return t},En={kargerStein:function(){var e=this,t=this.byGroup(),n=t.nodes,r=t.edges;r.unmergeBy(function(e){return e.isLoop()});var i=n.length,a=r.length,o=Math.ceil((Math.log(i)/Math.LN2)**2),s=Math.floor(i/Cn);if(i<2){Lt(`At least 2 nodes are required for Karger-Stein algorithm`);return}for(var c=[],l=0;l1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,r=1/0,i=t;i1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,r=-1/0,i=t;i1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,r=0,i=0,a=t;a1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!0;r?e=e.slice(t,n):(n0&&e.splice(0,t));for(var o=0,s=e.length-1;s>=0;s--){var c=e[s];a?isFinite(c)||(e[s]=-1/0,o++):e.splice(s,1)}i&&e.sort(function(e,t){return e-t});var l=e.length,u=Math.floor(l/2);return l%2==0?(e[u-1+o]+e[u+o])/2:e[u+1+o]},Fn=function(e){return Math.PI*e/180},In=function(e,t){return Math.atan2(t,e)-Math.PI/2},Ln=Math.log2||function(e){return Math.log(e)/Math.log(2)},Rn=function(e){return e>0?1:e<0?-1:0},zn=function(e,t){return Math.sqrt(Bn(e,t))},Bn=function(e,t){var n=t.x-e.x,r=t.y-e.y;return n*n+r*r},Vn=function(e){for(var t=e.length,n=0,r=0;r=e.x1&&e.y2>=e.y1)return{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,w:e.x2-e.x1,h:e.y2-e.y1};if(e.w!=null&&e.h!=null&&e.w>=0&&e.h>=0)return{x1:e.x1,y1:e.y1,x2:e.x1+e.w,y2:e.y1+e.h,w:e.w,h:e.h}}},qn=function(e){return{x1:e.x1,x2:e.x2,w:e.w,y1:e.y1,y2:e.y2,h:e.h}},Jn=function(e){e.x1=1/0,e.y1=1/0,e.x2=-1/0,e.y2=-1/0,e.w=0,e.h=0},Yn=function(e,t){e.x1=Math.min(e.x1,t.x1),e.x2=Math.max(e.x2,t.x2),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,t.y1),e.y2=Math.max(e.y2,t.y2),e.h=e.y2-e.y1},Xn=function(e,t,n){e.x1=Math.min(e.x1,t),e.x2=Math.max(e.x2,t),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,n),e.y2=Math.max(e.y2,n),e.h=e.y2-e.y1},Zn=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return e.x1-=t,e.x2+=t,e.y1-=t,e.y2+=t,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},Qn=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[0],n,r,i,a;if(t.length===1)n=r=i=a=t[0];else if(t.length===2)n=i=t[0],a=r=t[1];else if(t.length===4){var o=f(t,4);n=o[0],r=o[1],i=o[2],a=o[3]}return e.x1-=a,e.x2+=r,e.y1-=n,e.y2+=i,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},$n=function(e,t){e.x1=t.x1,e.y1=t.y1,e.x2=t.x2,e.y2=t.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1},er=function(e,t){return!(e.x1>t.x2||t.x1>e.x2||e.x2t.y2||t.y1>e.y2)},tr=function(e,t,n){return e.x1<=t&&t<=e.x2&&e.y1<=n&&n<=e.y2},nr=function(e,t){return tr(e,t.x,t.y)},rr=function(e,t){return tr(e,t.x1,t.y1)&&tr(e,t.x2,t.y2)},ir=Math.hypot??function(e,t){return Math.sqrt(e*e+t*t)};function ar(e,t){if(e.length<3)throw Error(`Need at least 3 vertices`);var n=function(e,t){return{x:e.x+t.x,y:e.y+t.y}},r=function(e,t){return{x:e.x-t.x,y:e.y-t.y}},i=function(e,t){return{x:e.x*t,y:e.y*t}},a=function(e,t){return e.x*t.y-e.y*t.x},o=function(e){var t=ir(e.x,e.y);return t===0?{x:0,y:0}:{x:e.x/t,y:e.y/t}},s=function(e){for(var t=0,n=0;n7&&arguments[7]!==void 0?arguments[7]:`auto`,c=s===`auto`?jr(i,a):s,l=i/2,u=a/2;c=Math.min(c,l,u);var d=c!==l,f=c!==u,p;if(d){var m=n-l+c-o,h=r-u-o;if(p=Cr(e,t,n,r,m,h,n+l-c+o,h,!1),p.length>0)return p}if(f){var g=n+l+o;if(p=Cr(e,t,n,r,g,r-u+c-o,g,r+u-c+o,!1),p.length>0)return p}if(d){var _=n-l+c-o,v=r+u+o;if(p=Cr(e,t,n,r,_,v,n+l-c+o,v,!1),p.length>0)return p}if(f){var y=n-l-o;if(p=Cr(e,t,n,r,y,r-u+c-o,y,r+u-c+o,!1),p.length>0)return p}var b,x=n-l+c,S=r-u+c;if(b=xr(e,t,n,r,x,S,c+o),b.length>0&&b[0]<=x&&b[1]<=S)return[b[0],b[1]];var C=n+l-c,w=r-u+c;if(b=xr(e,t,n,r,C,w,c+o),b.length>0&&b[0]>=C&&b[1]<=w)return[b[0],b[1]];var T=n+l-c,E=r+u-c;if(b=xr(e,t,n,r,T,E,c+o),b.length>0&&b[0]>=T&&b[1]>=E)return[b[0],b[1]];var D=n-l+c,O=r+u-c;return b=xr(e,t,n,r,D,O,c+o),b.length>0&&b[0]<=D&&b[1]>=O?[b[0],b[1]]:[]},cr=function(e,t,n,r,i,a,o){var s=o,c=Math.min(n,i),l=Math.max(n,i),u=Math.min(r,a),d=Math.max(r,a);return c-s<=e&&e<=l+s&&u-s<=t&&t<=d+s},lr=function(e,t,n,r,i,a,o,s,c){var l={x1:Math.min(n,o,i)-c,x2:Math.max(n,o,i)+c,y1:Math.min(r,s,a)-c,y2:Math.max(r,s,a)+c};return!(el.x2||tl.y2)},ur=function(e,t,n,r){n-=r;var i=t*t-4*e*n;if(i<0)return[];var a=Math.sqrt(i),o=2*e;return[(-t+a)/o,(-t-a)/o]},dr=function(e,t,n,r,i){e===0&&(e=1e-5),t/=e,n/=e,r/=e;var a,o=(3*n-t*t)/9,s=-(27*r)+t*(9*n-t*t*2),c,l,u,d,f;if(s/=54,a=o*o*o+s*s,i[1]=0,d=t/3,a>0){l=s+Math.sqrt(a),l=l<0?-((-l)**(1/3)):l**(1/3),u=s-Math.sqrt(a),u=u<0?-((-u)**(1/3)):u**(1/3),i[0]=-d+l+u,d+=(l+u)/2,i[4]=i[2]=-d,d=Math.sqrt(3)*(-u+l)/2,i[3]=d,i[5]=-d;return}if(i[5]=i[3]=0,a===0){f=s<0?-((-s)**(1/3)):s**(1/3),i[0]=-d+2*f,i[4]=i[2]=-(f+d);return}o=-o,c=o*o*o,c=Math.acos(s/Math.sqrt(c)),f=2*Math.sqrt(o),i[0]=-d+f*Math.cos(c/3),i[2]=-d+f*Math.cos((c+2*Math.PI)/3),i[4]=-d+f*Math.cos((c+4*Math.PI)/3)},fr=function(e,t,n,r,i,a,o,s){var c=1*n*n-4*n*i+2*n*o+4*i*i-4*i*o+o*o+r*r-4*r*a+2*r*s+4*a*a-4*a*s+s*s,l=9*n*i-3*n*n-3*n*o-6*i*i+3*i*o+9*r*a-3*r*r-3*r*s-6*a*a+3*a*s,u=3*n*n-6*n*i+n*o-n*e+2*i*i+2*i*e-o*e+3*r*r-6*r*a+r*s-r*t+2*a*a+2*a*t-s*t,d=1*n*i-n*n+n*e-i*e+r*a-r*r+r*t-a*t,f=[];dr(c,l,u,d,f);for(var p=1e-7,m=[],h=0;h<6;h+=2)Math.abs(f[h+1])=0&&f[h]<=1&&m.push(f[h]);m.push(1),m.push(0);for(var g=-1,_,v,y,b=0;b=0?yc?(e-i)*(e-i)+(t-a)*(t-a):l-d},mr=function(e,t,n){for(var r,i,a,o,s,c=0,l=0;l=e&&e>=a||r<=e&&e<=a)s=(e-r)/(a-r)*(o-i)+i,s>t&&c++;else continue;return c%2!=0},hr=function(e,t,n,r,i,a,o,s,c){var l=Array(n.length),u;s[0]==null?u=s:(u=Math.atan(s[1]/s[0]),s[0]<0?u+=Math.PI/2:u=-u-Math.PI/2);for(var d=Math.cos(-u),f=Math.sin(-u),p=0;p0?_r(vr(l,-c)):l)},gr=function(e,t,n,r,i,a,o,s){for(var c=Array(n.length*2),l=0;l=0&&h<=1&&_.push(h),g>=0&&g<=1&&_.push(g),_.length===0)return[];var v=_[0]*s[0]+e,y=_[0]*s[1]+t;return _.length>1?_[0]==_[1]?[v,y]:[v,y,_[1]*s[0]+e,_[1]*s[1]+t]:[v,y]},Sr=function(e,t,n){return t<=e&&e<=n||n<=e&&e<=t?e:e<=t&&t<=n||n<=t&&t<=e?t:n},Cr=function(e,t,n,r,i,a,o,s,c){var l=e-i,u=n-e,d=o-i,f=t-a,p=r-t,m=s-a,h=d*f-m*l,g=u*f-p*l,_=m*u-d*p;if(_!==0){var v=h/_,y=g/_,b=.001,x=0-b,S=1+b;return x<=v&&v<=S&&x<=y&&y<=S||c?[e+v*u,t+v*p]:[]}else if(h===0||g===0)return Sr(e,n,o)===o?[o,s]:Sr(e,n,i)===i?[i,a]:Sr(i,o,n)===n?[n,r]:[];else return[]},wr=function(e,t,n,r,i){var a=[],o=r/2,s=i/2,c=t,l=n;a.push({x:c+o*e[0],y:l+s*e[1]});for(var u=1;u0?_r(vr(u,-s)):u}else f=n;for(var m,h,g,_,v=0;v2){for(var p=[l[0],l[1]],m=(p[0]-e)**2+(p[1]-t)**2,h=1;hl&&(l=t)},get:function(e){return c[e]}},d=0;d0?v.edgesTo(_)[0]:_.edgesTo(v)[0];var b=r(y);_=_.id(),l[_]>l[m]+b&&(l[_]=l[m]+b,d.nodes.indexOf(_)<0?d.push(_):d.updateItem(_),c[_]=0,n[_]=[]),l[_]==l[m]+b&&(c[_]=c[_]+c[m],n[_].push(m))}else for(var x=0;x0;){for(var T=t.pop(),E=0;E0&&o.push(n[s]);o.length!==0&&i.push(r.collection(o))}return i},ti=function(e,t){for(var n=0;n5&&arguments[5]!==void 0?arguments[5]:ai,o=r,s,c,l=0;l=2?di(e,t,n,0,ci,li):di(e,t,n,0,si)},squaredEuclidean:function(e,t,n){return di(e,t,n,0,ci)},manhattan:function(e,t,n){return di(e,t,n,0,si)},max:function(e,t,n){return di(e,t,n,-1/0,ui)}};fi[`squared-euclidean`]=fi.squaredEuclidean,fi.squaredeuclidean=fi.squaredEuclidean;function pi(e,t,n,r,i,a){var o=E(e)?e:fi[e]||fi.euclidean;return t===0&&E(e)?o(i,a):o(t,n,r,i,a)}var mi=Kt({k:2,m:2,sensitivityThreshold:1e-4,distance:`euclidean`,maxIterations:10,attributes:[],testMode:!1,testCentroids:null}),hi=function(e){return mi(e)},gi=function(e,t,n,r,i){var a=i===`kMedoids`?function(e){return r[e](n)}:function(e){return n[e]},o=function(e){return r[e](t)},s=n,c=t;return pi(e,r.length,a,o,s,c)},_i=function(e,t,n){for(var r=n.length,i=Array(r),a=Array(r),o=Array(t),s=null,c=0;cn)return!1;return!0},Si=function(e,t,n){for(var r=0;ro&&(o=t[c][l],s=l);i[s].push(e[c])}for(var u=0;u=i.threshold||i.mode===`dendrogram`&&e.length===1)return!1;var p=t[a],m=t[r[a]],h=i.mode===`dendrogram`?{left:p,right:m,key:p.key}:{value:p.value.concat(m.value),key:p.key};e[p.index]=h,e.splice(m.index,1),t[p.key]=h;for(var g=0;gn[m.key][_.key]&&(s=n[m.key][_.key])):i.linkage===`max`?(s=n[p.key][_.key],n[p.key][_.key]0&&r.push(i);return r},Ki=function(e,t,n){for(var r=[],i=0;io&&(a=c,o=t[i*e+c])}a>0&&r.push(a)}for(var l=0;lc&&(s=l,c=u)}n[i]=a[s]}return r=Ki(e,t,n),r},Ji=function(e){for(var t=this.cy(),n=this.nodes(),r=Hi(e),i={},a=0;a=E?(D=E,E=k,O=A):k>D&&(D=k);for(var j=0;j0);S[w%r.minIterations*o+L]=R,I+=R}if(I>0&&(w>=r.minIterations-1||w==r.maxIterations-1)){for(var z=0,B=0;B1||i>1)&&(o=!0),u[t]=[],e.outgoers().forEach(function(e){e.isEdge()&&u[t].push(e.id())})}else d[t]=[void 0,e.target().id()]}):a.forEach(function(e){var t=e.id();e.isNode()?(e.degree(!0)%2&&(s?c?o=!0:c=t:s=t),u[t]=[],e.connectedEdges().forEach(function(e){return u[t].push(e.id())})):d[t]=[e.source().id(),e.target().id()]});var f={found:!1,trail:void 0};if(o)return f;if(c&&s)if(i){if(l&&c!=l)return f;l=c}else if(l&&c!=l&&s!=l)return f;else l||=c;else l||=a[0].id();var p=function(e){for(var t=e,n=[e],r,a,o;u[t].length;)r=u[t].shift(),a=d[r][0],o=d[r][1],t==o?!i&&t!=a&&(u[a]=u[a].filter(function(e){return e!=r}),t=a):(u[o]=u[o].filter(function(e){return e!=r}),t=o),n.unshift(r),n.unshift(t);return n},m=[],h=[];for(h=p(l);h.length!=1;)u[h[0]].length==0?(m.unshift(a.getElementById(h.shift())),m.unshift(a.getElementById(h.shift()))):h=p(h.shift()).concat(h);for(var g in m.unshift(a.getElementById(h.shift())),u)if(u[g].length)return f;return f.found=!0,f.trail=this.spawn(m,!0),f}},Qi=function(){var e=this,t={},n=0,r=0,i=[],a=[],o={},s=function(n,r){for(var o=a.length-1,s=[],c=e.spawn();a[o].x!=n||a[o].y!=r;)s.push(a.pop().edge),o--;s.push(a.pop().edge),s.forEach(function(n){var r=n.connectedNodes().intersection(e);c.merge(n),r.forEach(function(n){var r=n.id(),i=n.connectedEdges().intersection(e);c.merge(n),t[r].cutVertex?c.merge(i.filter(function(e){return e.isLoop()})):c.merge(i)})}),i.push(c)},c=function(l,u,d){l===d&&(r+=1),t[u]={id:n,low:n++,cutVertex:!1};var f=e.getElementById(u).connectedEdges().intersection(e);if(f.size()===0)i.push(e.spawn(e.getElementById(u)));else{var p,m,h,g;f.forEach(function(e){p=e.source().id(),m=e.target().id(),h=p===u?m:p,h!==d&&(g=e.id(),o[g]||(o[g]=!0,a.push({x:u,y:h,edge:e})),h in t?t[u].low=Math.min(t[u].low,t[h].id):(c(l,h,u),t[u].low=Math.min(t[u].low,t[h].low),t[u].id<=t[h].low&&(t[u].cutVertex=!0,s(u,h))))})}};e.forEach(function(e){if(e.isNode()){var n=e.id();n in t||(r=0,c(n,n),t[n].cutVertex=r>1)}});var l=Object.keys(t).filter(function(e){return t[e].cutVertex}).map(function(t){return e.getElementById(t)});return{cut:e.spawn(l),components:i}},$i={hopcroftTarjanBiconnected:Qi,htbc:Qi,htb:Qi,hopcroftTarjanBiconnectedComponents:Qi},ea=function(){var e=this,t={},n=0,r=[],i=[],a=e.spawn(e),o=function(s){if(i.push(s),t[s]={index:n,low:n++,explored:!1},e.getElementById(s).connectedEdges().intersection(e).forEach(function(e){var n=e.target().id();n!==s&&(n in t||o(n),t[n].explored||(t[s].low=Math.min(t[s].low,t[n].low)))}),t[s].index===t[s].low){for(var c=e.spawn();;){var l=i.pop();if(c.merge(e.getElementById(l)),t[l].low=t[s].index,t[l].explored=!0,l===s)break}var u=c.edgesWith(c),d=c.merge(u);r.push(d),a=a.difference(d)}};return e.forEach(function(e){if(e.isNode()){var n=e.id();n in t||o(n)}}),{cut:a,components:r}},ta={tarjanStronglyConnected:ea,tsc:ea,tscc:ea,tarjanStronglyConnectedComponents:ea},na={};[an,hn,gn,vn,bn,Sn,En,Rr,Br,Hr,Wr,ii,ji,Bi,Yi,Zi,$i,ta].forEach(function(e){X(na,e)});var ra=0,ia=1,aa=2,oa=function(e){if(!(this instanceof oa))return new oa(e);this.id=`Thenable/1.0.7`,this.state=ra,this.fulfillValue=void 0,this.rejectReason=void 0,this.onFulfilled=[],this.onRejected=[],this.proxy={then:this.then.bind(this)},typeof e==`function`&&e.call(this,this.fulfill.bind(this),this.reject.bind(this))};oa.prototype={fulfill:function(e){return sa(this,ia,`fulfillValue`,e)},reject:function(e){return sa(this,aa,`rejectReason`,e)},then:function(e,t){var n=this,r=new oa;return n.onFulfilled.push(ua(e,r,`fulfill`)),n.onRejected.push(ua(t,r,`reject`)),ca(n),r.proxy}};var sa=function(e,t,n,r){return e.state===ra&&(e.state=t,e[n]=r,ca(e)),e},ca=function(e){e.state===ia?la(e,`onFulfilled`,e.fulfillValue):e.state===aa&&la(e,`onRejected`,e.rejectReason)},la=function(e,t,n){if(e[t].length!==0){var r=e[t];e[t]=[];var i=function(){for(var e=0;e0}},clearQueue:function(){return function(){var e=this,t=e.length===void 0?[e]:e;if(!(this._private.cy||this).styleEnabled())return this;for(var n=0;n-1}return Eo=t,Eo}var ko,Ao;function jo(){if(Ao)return ko;Ao=1;var e=yo();function t(t,n){var r=this.__data__,i=e(r,t);return i<0?(++this.size,r.push([t,n])):r[i][1]=n,this}return ko=t,ko}var Mo,No;function Po(){if(No)return Mo;No=1;var e=po(),t=So(),n=To(),r=Oo(),i=jo();function a(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t-1&&n%1==0&&n0&&this.spawn(r).updateStyle().emit(`class`),t},addClass:function(e){return this.toggleClass(e,!0)},hasClass:function(e){var t=this[0];return t!=null&&t._private.classes.has(e)},toggleClass:function(e,t){D(e)||(e=e.match(/\S+/g)||[]);for(var n=this,r=t===void 0,i=[],a=0,o=n.length;a0&&this.spawn(i).updateStyle().emit(`class`),n},removeClass:function(e){return this.toggleClass(e,!1)},flashClass:function(e,t){var n=this;if(t==null)t=250;else if(t===0)return n;return n.addClass(e),setTimeout(function(){n.removeClass(e)},t),n}};hc.className=hc.classNames=hc.classes;var Z={metaChar:`[\\!\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\\`\\{\\|\\}\\~]`,comparatorOp:`=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=`,boolOp:`\\?|\\!|\\^`,string:`"(?:\\\\"|[^"])*"|'(?:\\\\'|[^'])*'`,number:Y,meta:`degree|indegree|outdegree`,separator:`\\s*,\\s*`,descendant:`\\s+`,child:`\\s+>\\s+`,subject:`\\$`,group:`node|edge|\\*`,directedEdge:`\\s+->\\s+`,undirectedEdge:`\\s+<->\\s+`};Z.variable=`(?:[\\w-.]|(?:\\\\`+Z.metaChar+`))+`,Z.className=`(?:[\\w-]|(?:\\\\`+Z.metaChar+`))+`,Z.value=Z.string+`|`+Z.number,Z.id=Z.variable,(function(){var e=Z.comparatorOp.split(`|`),t,n;for(n=0;n=0)&&t!==`=`&&(Z.comparatorOp+=`|\\!`+t)})();var gc=function(){return{checks:[]}},Q={GROUP:0,COLLECTION:1,FILTER:2,DATA_COMPARE:3,DATA_EXIST:4,DATA_BOOL:5,META_COMPARE:6,STATE:7,ID:8,CLASS:9,UNDIRECTED_EDGE:10,DIRECTED_EDGE:11,NODE_SOURCE:12,NODE_TARGET:13,NODE_NEIGHBOR:14,CHILD:15,DESCENDANT:16,PARENT:17,ANCESTOR:18,COMPOUND_SPLIT:19,TRUE:20},_c=[{selector:`:selected`,matches:function(e){return e.selected()}},{selector:`:unselected`,matches:function(e){return!e.selected()}},{selector:`:selectable`,matches:function(e){return e.selectable()}},{selector:`:unselectable`,matches:function(e){return!e.selectable()}},{selector:`:locked`,matches:function(e){return e.locked()}},{selector:`:unlocked`,matches:function(e){return!e.locked()}},{selector:`:visible`,matches:function(e){return e.visible()}},{selector:`:hidden`,matches:function(e){return!e.visible()}},{selector:`:transparent`,matches:function(e){return e.transparent()}},{selector:`:grabbed`,matches:function(e){return e.grabbed()}},{selector:`:free`,matches:function(e){return!e.grabbed()}},{selector:`:removed`,matches:function(e){return e.removed()}},{selector:`:inside`,matches:function(e){return!e.removed()}},{selector:`:grabbable`,matches:function(e){return e.grabbable()}},{selector:`:ungrabbable`,matches:function(e){return!e.grabbable()}},{selector:`:animated`,matches:function(e){return e.animated()}},{selector:`:unanimated`,matches:function(e){return!e.animated()}},{selector:`:parent`,matches:function(e){return e.isParent()}},{selector:`:childless`,matches:function(e){return e.isChildless()}},{selector:`:child`,matches:function(e){return e.isChild()}},{selector:`:orphan`,matches:function(e){return e.isOrphan()}},{selector:`:nonorphan`,matches:function(e){return e.isChild()}},{selector:`:compound`,matches:function(e){return e.isNode()?e.isParent():e.source().isParent()||e.target().isParent()}},{selector:`:loop`,matches:function(e){return e.isLoop()}},{selector:`:simple`,matches:function(e){return e.isSimple()}},{selector:`:active`,matches:function(e){return e.active()}},{selector:`:inactive`,matches:function(e){return!e.active()}},{selector:`:backgrounding`,matches:function(e){return e.backgrounding()}},{selector:`:nonbackgrounding`,matches:function(e){return!e.backgrounding()}}].sort(function(e,t){return ce(e.selector,t.selector)}),vc=function(){for(var e={},t,n=0;n<_c.length;n++)t=_c[n],e[t.selector]=t.matches;return e}(),yc=function(e,t){return vc[e](t)},bc=`(`+_c.map(function(e){return e.selector}).join(`|`)+`)`,xc=function(e){return e.replace(RegExp(`\\\\(`+Z.metaChar+`)`,`g`),function(e,t){return t})},Sc=function(e,t,n){e[e.length-1]=n},Cc=[{name:`group`,query:!0,regex:`(`+Z.group+`)`,populate:function(e,t,n){var r=f(n,1)[0];t.checks.push({type:Q.GROUP,value:r===`*`?r:r+`s`})}},{name:`state`,query:!0,regex:bc,populate:function(e,t,n){var r=f(n,1)[0];t.checks.push({type:Q.STATE,value:r})}},{name:`id`,query:!0,regex:`\\#(`+Z.id+`)`,populate:function(e,t,n){var r=f(n,1)[0];t.checks.push({type:Q.ID,value:xc(r)})}},{name:`className`,query:!0,regex:`\\.(`+Z.className+`)`,populate:function(e,t,n){var r=f(n,1)[0];t.checks.push({type:Q.CLASS,value:xc(r)})}},{name:`dataExists`,query:!0,regex:`\\[\\s*(`+Z.variable+`)\\s*\\]`,populate:function(e,t,n){var r=f(n,1)[0];t.checks.push({type:Q.DATA_EXIST,field:xc(r)})}},{name:`dataCompare`,query:!0,regex:`\\[\\s*(`+Z.variable+`)\\s*(`+Z.comparatorOp+`)\\s*(`+Z.value+`)\\s*\\]`,populate:function(e,t,n){var r=f(n,3),i=r[0],a=r[1],o=r[2];o=RegExp(`^`+Z.string+`$`).exec(o)==null?parseFloat(o):o.substring(1,o.length-1),t.checks.push({type:Q.DATA_COMPARE,field:xc(i),operator:a,value:o})}},{name:`dataBool`,query:!0,regex:`\\[\\s*(`+Z.boolOp+`)\\s*(`+Z.variable+`)\\s*\\]`,populate:function(e,t,n){var r=f(n,2),i=r[0],a=r[1];t.checks.push({type:Q.DATA_BOOL,field:xc(a),operator:i})}},{name:`metaCompare`,query:!0,regex:`\\[\\[\\s*(`+Z.meta+`)\\s*(`+Z.comparatorOp+`)\\s*(`+Z.number+`)\\s*\\]\\]`,populate:function(e,t,n){var r=f(n,3),i=r[0],a=r[1],o=r[2];t.checks.push({type:Q.META_COMPARE,field:xc(i),operator:a,value:parseFloat(o)})}},{name:`nextQuery`,separator:!0,regex:Z.separator,populate:function(e,t){var n=e.currentSubject,r=e.edgeCount,i=e.compoundCount,a=e[e.length-1];return n!=null&&(a.subject=n,e.currentSubject=null),a.edgeCount=r,a.compoundCount=i,e.edgeCount=0,e.compoundCount=0,e[e.length++]=gc()}},{name:`directedEdge`,separator:!0,regex:Z.directedEdge,populate:function(e,t){if(e.currentSubject==null){var n=gc(),r=t,i=gc();return n.checks.push({type:Q.DIRECTED_EDGE,source:r,target:i}),Sc(e,t,n),e.edgeCount++,i}else{var a=gc(),o=t,s=gc();return a.checks.push({type:Q.NODE_SOURCE,source:o,target:s}),Sc(e,t,a),e.edgeCount++,s}}},{name:`undirectedEdge`,separator:!0,regex:Z.undirectedEdge,populate:function(e,t){if(e.currentSubject==null){var n=gc(),r=t,i=gc();return n.checks.push({type:Q.UNDIRECTED_EDGE,nodes:[r,i]}),Sc(e,t,n),e.edgeCount++,i}else{var a=gc(),o=t,s=gc();return a.checks.push({type:Q.NODE_NEIGHBOR,node:o,neighbor:s}),Sc(e,t,a),s}}},{name:`child`,separator:!0,regex:Z.child,populate:function(e,t){if(e.currentSubject==null){var n=gc(),r=gc(),i=e[e.length-1];return n.checks.push({type:Q.CHILD,parent:i,child:r}),Sc(e,t,n),e.compoundCount++,r}else if(e.currentSubject===t){var a=gc(),o=e[e.length-1],s=gc(),c=gc(),l=gc(),u=gc();return a.checks.push({type:Q.COMPOUND_SPLIT,left:o,right:s,subject:c}),c.checks=t.checks,t.checks=[{type:Q.TRUE}],u.checks.push({type:Q.TRUE}),s.checks.push({type:Q.PARENT,parent:u,child:l}),Sc(e,o,a),e.currentSubject=c,e.compoundCount++,l}else{var d=gc(),f=gc(),p=[{type:Q.PARENT,parent:d,child:f}];return d.checks=t.checks,t.checks=p,e.compoundCount++,f}}},{name:`descendant`,separator:!0,regex:Z.descendant,populate:function(e,t){if(e.currentSubject==null){var n=gc(),r=gc(),i=e[e.length-1];return n.checks.push({type:Q.DESCENDANT,ancestor:i,descendant:r}),Sc(e,t,n),e.compoundCount++,r}else if(e.currentSubject===t){var a=gc(),o=e[e.length-1],s=gc(),c=gc(),l=gc(),u=gc();return a.checks.push({type:Q.COMPOUND_SPLIT,left:o,right:s,subject:c}),c.checks=t.checks,t.checks=[{type:Q.TRUE}],u.checks.push({type:Q.TRUE}),s.checks.push({type:Q.ANCESTOR,ancestor:u,descendant:l}),Sc(e,o,a),e.currentSubject=c,e.compoundCount++,l}else{var d=gc(),f=gc(),p=[{type:Q.ANCESTOR,ancestor:d,descendant:f}];return d.checks=t.checks,t.checks=p,e.compoundCount++,f}}},{name:`subject`,modifier:!0,regex:Z.subject,populate:function(e,t){if(e.currentSubject!=null&&e.currentSubject!==t)return zt("Redefinition of subject in selector `"+e.toString()+"`"),!1;e.currentSubject=t;var n=e[e.length-1].checks[0],r=n==null?null:n.type;r===Q.DIRECTED_EDGE?n.type=Q.NODE_TARGET:r===Q.UNDIRECTED_EDGE&&(n.type=Q.NODE_NEIGHBOR,n.node=n.nodes[1],n.neighbor=n.nodes[0],n.nodes=null)}}];Cc.forEach(function(e){return e.regexObj=RegExp(`^`+e.regex)});var wc=function(e){for(var t,n,r,i=0;i0&&l.edgeCount>0)return zt("The selector `"+e+"` is invalid because it uses both a compound selector and an edge selector"),!1;if(l.edgeCount>1)return zt("The selector `"+e+"` is invalid because it uses multiple edge selectors"),!1;l.edgeCount===1&&zt("The selector `"+e+"` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.")}return!0},toString:function(){if(this.toStringCache!=null)return this.toStringCache;for(var e=function(e){return e??``},t=function(t){return T(t)?`"`+t+`"`:e(t)},n=function(e){return` `+e+` `},r=function(r,a){var o=r.type,s=r.value;switch(o){case Q.GROUP:var c=e(s);return c.substring(0,c.length-1);case Q.DATA_COMPARE:var l=r.field,u=r.operator;return`[`+l+n(e(u))+t(s)+`]`;case Q.DATA_BOOL:var d=r.operator,f=r.field;return`[`+e(d)+f+`]`;case Q.DATA_EXIST:return`[`+r.field+`]`;case Q.META_COMPARE:var p=r.operator;return`[[`+r.field+n(e(p))+t(s)+`]]`;case Q.STATE:return s;case Q.ID:return`#`+s;case Q.CLASS:return`.`+s;case Q.PARENT:case Q.CHILD:return i(r.parent,a)+n(`>`)+i(r.child,a);case Q.ANCESTOR:case Q.DESCENDANT:return i(r.ancestor,a)+` `+i(r.descendant,a);case Q.COMPOUND_SPLIT:var m=i(r.left,a),h=i(r.subject,a),g=i(r.right,a);return m+(m.length>0?` `:``)+h+g;case Q.TRUE:return``}},i=function(e,t){return e.checks.reduce(function(n,i,a){return n+(t===e&&a===0?`$`:``)+r(i,t)},``)},a=``,o=0;o1&&o=0&&(t=t.replace(`!`,``),u=!0),t.indexOf(`@`)>=0&&(t=t.replace(`@`,``),l=!0),(i||o||l)&&(s=!i&&!a?``:``+e,c=``+n),l&&(e=s=s.toLowerCase(),n=c=c.toLowerCase()),t){case`*=`:r=s.indexOf(c)>=0;break;case`$=`:r=s.indexOf(c,s.length-c.length)>=0;break;case`^=`:r=s.indexOf(c)===0;break;case`=`:r=e===n;break;case`>`:d=!0,r=e>n;break;case`>=`:d=!0,r=e>=n;break;case`<`:d=!0,r=e0;){var l=i.shift();t(l),a.add(l.id()),o&&r(i,a,l)}return e}function Vc(e,t,n){if(n.isParent())for(var r=n._private.children,i=0;i1&&arguments[1]!==void 0?arguments[1]:!0;return Bc(this,e,t,Vc)};function Hc(e,t,n){if(n.isChild()){var r=n._private.parent;t.has(r.id())||e.push(r)}}zc.forEachUp=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Bc(this,e,t,Hc)};function Uc(e,t,n){Hc(e,t,n),Vc(e,t,n)}zc.forEachUpAndDown=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Bc(this,e,t,Uc)},zc.ancestors=zc.parents;var Wc=Gc={data:pc.data({field:`data`,bindingEvent:`data`,allowBinding:!0,allowSetting:!0,settingEvent:`data`,settingTriggersEvent:!0,triggerFnName:`trigger`,allowGetting:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),removeData:pc.removeData({field:`data`,event:`data`,triggerFnName:`trigger`,triggerEvent:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),scratch:pc.data({field:`scratch`,bindingEvent:`scratch`,allowBinding:!0,allowSetting:!0,settingEvent:`scratch`,settingTriggersEvent:!0,triggerFnName:`trigger`,allowGetting:!0,updateStyle:!0}),removeScratch:pc.removeData({field:`scratch`,event:`scratch`,triggerFnName:`trigger`,triggerEvent:!0,updateStyle:!0}),rscratch:pc.data({field:`rscratch`,allowBinding:!1,allowSetting:!0,settingTriggersEvent:!1,allowGetting:!0}),removeRscratch:pc.removeData({field:`rscratch`,triggerEvent:!1}),id:function(){var e=this[0];if(e)return e._private.data.id}},Gc;Wc.attr=Wc.data,Wc.removeAttr=Wc.removeData;var Kc=Gc,qc={};function Jc(e){return function(t){var n=this;if(t===void 0&&(t=!0),n.length!==0)if(n.isNode()&&!n.removed()){for(var r=0,i=n[0],a=i._private.edges,o=0;ot}),minIndegree:Yc(`indegree`,function(e,t){return et}),minOutdegree:Yc(`outdegree`,function(e,t){return et})}),X(qc,{totalDegree:function(e){for(var t=0,n=this.nodes(),r=0;r0,d=u;u&&(l=l[0]);var f=d?l.position():{x:0,y:0};t===void 0?i!==void 0&&c.position({x:i.x+f.x,y:i.y+f.y}):c.position(e,t+f[e])}else{var p=n.position(),m=o?n.parent():null,h=m&&m.length>0,g=h;h&&(m=m[0]);var _=g?m.position():{x:0,y:0};return i={x:p.x-_.x,y:p.y-_.y},e===void 0?i:i[e]}else if(!a)return;return this}},Xc.modelPosition=Xc.point=Xc.position,Xc.modelPositions=Xc.points=Xc.positions,Xc.renderedPoint=Xc.renderedPosition,Xc.relativePoint=Xc.relativePosition;var el=Zc,tl=function(e){switch(e){case`left`:case`right-inside`:return`left`;case`right`:case`left-inside`:return`right`;default:return`center`}},nl=function(e){switch(e){case`top`:case`bottom-inside`:return`top`;case`bottom`:case`top-inside`:return`bottom`;default:return`center`}},rl=function(e){switch(e){case`left`:return`right`;case`right`:return`left`;case`left-inside`:return`left`;case`right-inside`:return`right`;default:return`center`}},il=al={},al;al.renderedBoundingBox=function(e){var t=this.boundingBox(e),n=this.cy(),r=n.zoom(),i=n.pan(),a=t.x1*r+i.x,o=t.x2*r+i.x,s=t.y1*r+i.y,c=t.y2*r+i.y;return{x1:a,x2:o,y1:s,y2:c,w:o-a,h:c-s}},al.dirtyCompoundBoundsCache=function(){var e=arguments.length>0&&arguments[0]!==void 0&&arguments[0],t=this.cy();return!t.styleEnabled()||!t.hasCompoundNodes()||this.forEachUp(function(t){if(t.isParent()){var n=t._private;n.compoundBoundsClean=!1,n.bbCache=null,e||t.emitAndNotify(`bounds`)}}),this},al.updateCompoundBounds=function(){var e=arguments.length>0&&arguments[0]!==void 0&&arguments[0],t=this.cy();if(!t.styleEnabled()||!t.hasCompoundNodes()||!e&&t.batching())return this;function n(e){if(!e.isParent())return;var t=e._private,n=e.children(),r=e.pstyle(`compound-sizing-wrt-labels`).value===`include`,i={width:{val:e.pstyle(`min-width`).pfValue,left:e.pstyle(`min-width-bias-left`),right:e.pstyle(`min-width-bias-right`)},height:{val:e.pstyle(`min-height`).pfValue,top:e.pstyle(`min-height-bias-top`),bottom:e.pstyle(`min-height-bias-bottom`)}},a=n.boundingBox({includeLabels:r,includeOverlays:!1,useCache:!1}),o=t.position;(a.w===0||a.h===0)&&(a={w:e.pstyle(`width`).pfValue,h:e.pstyle(`height`).pfValue},a.x1=o.x-a.w/2,a.x2=o.x+a.w/2,a.y1=o.y-a.h/2,a.y2=o.y+a.h/2);function s(e,t,n){var r=0,i=0,a=t+n;return e>0&&a>0&&(r=t/a*e,i=n/a*e),{biasDiff:r,biasComplementDiff:i}}function c(e,t,n,r){if(n.units===`%`)switch(r){case`width`:return e>0?n.pfValue*e:0;case`height`:return t>0?n.pfValue*t:0;case`average`:return e>0&&t>0?n.pfValue*(e+t)/2:0;case`min`:return e>0&&t>0?e>t?n.pfValue*t:n.pfValue*e:0;case`max`:return e>0&&t>0?e>t?n.pfValue*e:n.pfValue*t:0;default:return 0}else if(n.units===`px`)return n.pfValue;else return 0}var l=i.width.left.value;i.width.left.units===`px`&&i.width.val>0&&(l=l*100/i.width.val);var u=i.width.right.value;i.width.right.units===`px`&&i.width.val>0&&(u=u*100/i.width.val);var d=i.height.top.value;i.height.top.units===`px`&&i.height.val>0&&(d=d*100/i.height.val);var f=i.height.bottom.value;i.height.bottom.units===`px`&&i.height.val>0&&(f=f*100/i.height.val);var p=s(i.width.val-a.w,l,u),m=p.biasDiff,h=p.biasComplementDiff,g=s(i.height.val-a.h,d,f),_=g.biasDiff,v=g.biasComplementDiff;t.autoPadding=c(a.w,a.h,e.pstyle(`padding`),e.pstyle(`padding-relative-to`).value),t.autoWidth=Math.max(a.w,i.width.val),o.x=(-m+a.x1+a.x2+h)/2,t.autoHeight=Math.max(a.h,i.height.val),o.y=(-_+a.y1+a.y2+v)/2}for(var r=0;re.x2?r:e.x2,e.y1=ne.y2?i:e.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1)},cl=function(e,t){return t==null?e:sl(e,t.x1,t.y1,t.x2,t.y2)},ll=function(e,t,n){return Xt(e,t,n)},ul=function(e,t,n){if(!t.cy().headless()){var r=t._private,i=r.rstyle,a=i.arrowWidth/2,o=t.pstyle(n+`-arrow-shape`).value,s,c;if(o!==`none`){n===`source`?(s=i.srcX,c=i.srcY):n===`target`?(s=i.tgtX,c=i.tgtY):(s=i.midX,c=i.midY);var l=r.arrowBounds=r.arrowBounds||{},u=l[n]=l[n]||{};u.x1=s-a,u.y1=c-a,u.x2=s+a,u.y2=c+a,u.w=u.x2-u.x1,u.h=u.y2-u.y1,Zn(u,1),sl(e,u.x1,u.y1,u.x2,u.y2)}}},dl=function(e,t,n){if(!t.cy().headless()){var r=n?n+`-`:``,i=t._private,a=i.rstyle;if(t.pstyle(r+`label`).strValue){var o=t.pstyle(`text-halign`),s=t.pstyle(`text-valign`),c=ll(a,`labelWidth`,n),l=ll(a,`labelHeight`,n),u=ll(a,`labelX`,n),d=ll(a,`labelY`,n),f=t.pstyle(r+`text-margin-x`).pfValue,p=t.pstyle(r+`text-margin-y`).pfValue,m=t.isEdge(),h=t.pstyle(r+`text-rotation`),g=t.pstyle(`text-outline-width`).pfValue,_=t.pstyle(`text-border-width`).pfValue/2,v=t.pstyle(`text-background-padding`).pfValue,y=2,b=l,x=c,S=x/2,C=b/2,w,T,E,D;if(m)w=u-S,T=u+S,E=d-C,D=d+C;else{switch(tl(o.value)){case`left`:w=u-x,T=u;break;case`center`:w=u-S,T=u+S;break;case`right`:w=u,T=u+x;break}switch(nl(s.value)){case`top`:E=d-b,D=d;break;case`center`:E=d-C,D=d+C;break;case`bottom`:E=d,D=d+b;break}}var O=f-Math.max(g,_)-v-y,k=f+Math.max(g,_)+v+y,A=p-Math.max(g,_)-v-y,j=p+Math.max(g,_)+v+y;w+=O,T+=k,E+=A,D+=j;var M=n||`main`,N=i.labelBounds,P=N[M]=N[M]||{};P.x1=w,P.y1=E,P.x2=T,P.y2=D,P.w=T-w,P.h=D-E,P.leftPad=O,P.rightPad=k,P.topPad=A,P.botPad=j;var F=m&&h.strValue===`autorotate`,I=h.pfValue!=null&&h.pfValue!==0;if(F||I){var L=F?ll(i.rstyle,`labelAngle`,n):h.pfValue,R=Math.cos(L),z=Math.sin(L),B=(w+T)/2,V=(E+D)/2;if(!m){switch(tl(o.value)){case`left`:B=T;break;case`right`:B=w;break}switch(nl(s.value)){case`top`:V=D;break;case`bottom`:V=E;break}}var H=function(e,t){return e-=B,t-=V,{x:e*R-t*z+B,y:e*z+t*R+V}},U=H(w,E),W=H(w,D),G=H(T,E),K=H(T,D);w=Math.min(U.x,W.x,G.x,K.x),T=Math.max(U.x,W.x,G.x,K.x),E=Math.min(U.y,W.y,G.y,K.y),D=Math.max(U.y,W.y,G.y,K.y)}var q=M+`Rot`,J=N[q]=N[q]||{};J.x1=w,J.y1=E,J.x2=T,J.y2=D,J.w=T-w,J.h=D-E,sl(e,w,E,T,D),sl(i.labelBounds.all,w,E,T,D)}return e}},fl=function(e,t){if(!t.cy().headless()){var n=t.pstyle(`outline-opacity`).value,r=t.pstyle(`outline-width`).value+t.pstyle(`outline-offset`).value;pl(e,t,n,r,`outside`,r/2)}},pl=function(e,t,n,r,i,a){if(!(n===0||r<=0||i===`inside`)){var o=t.cy().renderer(),s=o.nodeShapes[o.getNodeShape(t)];if(s){var c=t.position(),l=c.x,u=c.y,d=t.width(),f=t.height();s.hasMiterBounds?(i===`center`&&(r/=2),cl(e,s.miterBounds(l,u,d,f,r))):a!=null&&a>0&&Qn(e,[a,a,a,a])}}},ml=function(e,t){if(!t.cy().headless()){var n=t.pstyle(`border-opacity`).value,r=t.pstyle(`border-width`).pfValue,i=t.pstyle(`border-position`).value;pl(e,t,n,r,i)}},hl=function(e,t){var n=e._private.cy,r=n.styleEnabled(),i=n.headless(),a=Kn(),o=e._private,s=e.isNode(),c=e.isEdge(),l,u,d,f,p,m,h=o.rstyle,g=s&&r?e.pstyle(`bounds-expansion`).pfValue:[0],_=function(e){return e.pstyle(`display`).value!==`none`},v=!r||_(e)&&(!c||_(e.source())&&_(e.target()));if(v){var y=0,b=0;r&&t.includeOverlays&&(y=e.pstyle(`overlay-opacity`).value,y!==0&&(b=e.pstyle(`overlay-padding`).value));var x=0,S=0;r&&t.includeUnderlays&&(x=e.pstyle(`underlay-opacity`).value,x!==0&&(S=e.pstyle(`underlay-padding`).value));var C=Math.max(b,S),w=0,T=0;if(r&&(w=e.pstyle(`width`).pfValue,T=w/2),s&&t.includeNodes){var E=e.position();p=E.x,m=E.y;var D=e.outerWidth()/2,O=e.outerHeight()/2;l=p-D,u=p+D,d=m-O,f=m+O,sl(a,l,d,u,f),r&&fl(a,e),r&&t.includeOutlines&&!i&&fl(a,e),r&&ml(a,e)}else if(c&&t.includeEdges)if(r&&!i){var k=e.pstyle(`curve-style`).strValue;if(l=Math.min(h.srcX,h.midX,h.tgtX),u=Math.max(h.srcX,h.midX,h.tgtX),d=Math.min(h.srcY,h.midY,h.tgtY),f=Math.max(h.srcY,h.midY,h.tgtY),l-=T,u+=T,d-=T,f+=T,sl(a,l,d,u,f),k===`haystack`){var A=h.haystackPts;if(A&&A.length===2){if(l=A[0].x,d=A[0].y,u=A[1].x,f=A[1].y,l>u){var j=l;l=u,u=j}if(d>f){var M=d;d=f,f=M}sl(a,l-T,d-T,u+T,f+T)}}else if(k===`bezier`||k===`unbundled-bezier`||ee(k,`segments`)||ee(k,`taxi`)){var N;switch(k){case`bezier`:case`unbundled-bezier`:N=h.bezierPts;break;case`segments`:case`taxi`:case`round-segments`:case`round-taxi`:N=h.linePts;break}if(N!=null)for(var P=0;Pu){var R=l;l=u,u=R}if(d>f){var z=d;d=f,f=z}l-=T,u+=T,d-=T,f+=T,sl(a,l,d,u,f)}if(r&&t.includeEdges&&c&&(ul(a,e,`mid-source`),ul(a,e,`mid-target`),ul(a,e,`source`),ul(a,e,`target`)),r&&e.pstyle(`ghost`).value===`yes`){var B=e.pstyle(`ghost-offset-x`).pfValue,V=e.pstyle(`ghost-offset-y`).pfValue;sl(a,a.x1+B,a.y1+V,a.x2+B,a.y2+V)}var H=o.bodyBounds=o.bodyBounds||{};$n(H,a),Qn(H,g),Zn(H,1),r&&(l=a.x1,u=a.x2,d=a.y1,f=a.y2,sl(a,l-C,d-C,u+C,f+C));var U=o.overlayBounds=o.overlayBounds||{};$n(U,a),Qn(U,g),Zn(U,1);var W=o.labelBounds=o.labelBounds||{};W.all==null?W.all=Kn():Jn(W.all),r&&t.includeLabels&&(t.includeMainLabels&&dl(a,e,null),c&&(t.includeSourceLabels&&dl(a,e,`source`),t.includeTargetLabels&&dl(a,e,`target`)))}return a.x1=ol(a.x1),a.y1=ol(a.y1),a.x2=ol(a.x2),a.y2=ol(a.y2),a.w=ol(a.x2-a.x1),a.h=ol(a.y2-a.y1),a.w>0&&a.h>0&&v&&(Qn(a,g),Zn(a,1)),a},gl=function(e){var t=0,n=function(e){return+!!e<0&&arguments[0]!==void 0?arguments[0]:Bl,t=arguments.length>1?arguments[1]:void 0,n=0;n=0;s--)o(s);return this},Hl.removeAllListeners=function(){return this.removeListener(`*`)},Hl.emit=Hl.trigger=function(e,t,n){var r=this.listeners,i=r.length;return this.emitting++,D(t)||(t=[t]),Gl(this,function(e,a){n!=null&&(r=[{event:a.event,type:a.type,namespace:a.namespace,callback:n}],i=r.length);for(var o=function(){var n=r[s];if(n.type===a.type&&(!n.namespace||n.namespace===a.namespace||n.namespace===Ll)&&e.eventMatches(e.context,n,a)){var i=[a];t!=null&&Yt(i,t),e.beforeEmit(e.context,n,a),n.conf&&n.conf.one&&(e.listeners=e.listeners.filter(function(e){return e!==n}));var o=e.callbackContext(e.context,n,a),c=n.callback.apply(o,i);e.afterEmit(e.context,n,a),c===!1&&(a.stopPropagation(),a.preventDefault())}},s=0;s1&&!r){var i=this.length-1,a=this[i],o=a._private.data.id;this[i]=void 0,this[e]=a,n.set(o,{ele:a,index:e})}return this.length--,this},unmergeOne:function(e){e=e[0];var t=this._private,n=e._private.data.id,r=t.map.get(n);if(!r)return this;var i=r.index;return this.unmergeAt(i),this},unmerge:function(e){var t=this._private.cy;if(!e)return this;if(e&&T(e)){var n=e;e=t.mutableElements().filter(n)}for(var r=0;r=0;t--){var n=this[t];e(n)&&this.unmergeAt(t)}return this},map:function(e,t){for(var n=[],r=this,i=0;in&&(n=s,r=o)}return{value:n,ele:r}},min:function(e,t){for(var n=1/0,r,i=this,a=0;a=0&&i`u`?`undefined`:g(Symbol))!=e&&g(Symbol.iterator)!=e&&($l[Symbol.iterator]=function(){var e=this,t={value:void 0,done:!1},n=0,r=this.length;return s({next:function(){return n1&&arguments[1]!==void 0?arguments[1]:!0,n=this[0],r=n.cy();if(r.styleEnabled()&&n)return n._private.styleDirty&&(n._private.styleDirty=!1,r.style().apply(n)),n._private.style[e]??(t?r.style().getDefaultProperty(e):null)},numericStyle:function(e){var t=this[0];if(t.cy().styleEnabled()&&t){var n=t.pstyle(e);return n.pfValue===void 0?n.value:n.pfValue}},numericStyleUnits:function(e){var t=this[0];if(t.cy().styleEnabled()&&t)return t.pstyle(e).units},renderedStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=this[0];if(n)return t.style().getRenderedStyle(n,e)},style:function(e,t){var n=this.cy();if(!n.styleEnabled())return this;var r=!1,i=n.style();if(O(e)){var a=e;i.applyBypass(this,a,r),this.emitAndNotify(`style`)}else if(T(e))if(t===void 0){var o=this[0];return o?i.getStylePropertyValue(o,e):void 0}else i.applyBypass(this,e,t,r),this.emitAndNotify(`style`);else if(e===void 0){var s=this[0];return s?i.getRawStyle(s):void 0}return this},removeStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=!1,r=t.style(),i=this;if(e===void 0)for(var a=0;a0&&t.push(u[0]),t.push(s[0])}return this.spawn(t,!0).filter(e)},`neighborhood`),closedNeighborhood:function(e){return this.neighborhood().add(this).filter(e)},openNeighborhood:function(e){return this.neighborhood(e)}}),fu.neighbourhood=fu.neighborhood,fu.closedNeighbourhood=fu.closedNeighborhood,fu.openNeighbourhood=fu.openNeighborhood,X(fu,{source:Rc(function(e){var t=this[0],n;return t&&(n=t._private.source||t.cy().collection()),n&&e?n.filter(e):n},`source`),target:Rc(function(e){var t=this[0],n;return t&&(n=t._private.target||t.cy().collection()),n&&e?n.filter(e):n},`target`),sources:gu({attr:`source`}),targets:gu({attr:`target`})});function gu(e){return function(t){for(var n=[],r=0;r0);return a},component:function(){var e=this[0];return e.cy().mutableElements().components(e)[0]}}),fu.componentsOf=fu.components;var yu=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e===void 0){Lt(`A collection must have a reference to the core`);return}var i=new Qt,a=!1;if(!t)t=[];else if(t.length>0&&O(t[0])&&!P(t[0])){a=!0;for(var o=[],s=new tn,c=0,l=t.length;c0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,n=this,r=n.cy(),i=r._private,a=[],o=[],s,c=0,l=n.length;c0){for(var I=s.length===n.length?n:new yu(r,s),L=0;L0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,n=this,r=[],i={},a=n._private.cy;function o(e){for(var t=e._private.edges,n=0;n0&&(e?E.emitAndNotify(`remove`):t&&E.emit(`remove`));for(var D=0;D0?i=o:r=o;while(Math.abs(a)>1e-7&&++s<10);return o}function _(t){for(var r=0,o=1,s=i-1;o!==s&&c[o]<=t;++o)r+=a;--o;var l=(t-c[o])/(c[o+1]-c[o]),u=r+l*a,d=p(u,e,n);return d>=.001?m(t,u):d===0?u:g(t,r,r+a)}var v=!1;function y(){v=!0,(e!==t||n!==r)&&h()}var b=function(i){return v||y(),e===t&&n===r?i:i===0?0:i===1?1:f(_(i),t,r)};b.getControlPoints=function(){return[{x:e,y:t},{x:n,y:r}]};var x=`generateBezier(`+[e,t,n,r]+`)`;return b.toString=function(){return x},b}var Cu=function(){function e(e){return-e.tension*e.x-e.friction*e.v}function t(t,n,r){var i={x:t.x+r.dx*n,v:t.v+r.dv*n,tension:t.tension,friction:t.friction};return{dx:i.v,dv:e(i)}}function n(n,r){var i={dx:n.v,dv:e(n)},a=t(n,r*.5,i),o=t(n,r*.5,a),s=t(n,r,o),c=1/6*(i.dx+2*(a.dx+o.dx)+s.dx),l=1/6*(i.dv+2*(a.dv+o.dv)+s.dv);return n.x+=c*r,n.v+=l*r,n}return function e(t,r,i){var a={x:-1,v:0,tension:null,friction:null},o=[0],s=0,c=1/1e4,l=16/1e3,u,d,f;for(t=parseFloat(t)||500,r=parseFloat(r)||20,i||=null,a.tension=t,a.friction=r,u=i!==null,u?(s=e(t,r),d=s/i*l):d=l;f=n(f||a,d),o.push(1+f.x),s+=16,Math.abs(f.x)>c&&Math.abs(f.v)>c;);return u?function(e){return o[e*(o.length-1)|0]}:s}}(),wu=function(e,t,n,r){var i=Su(e,t,n,r);return function(e,t,n){return e+(t-e)*i(n)}},Tu={linear:function(e,t,n){return e+(t-e)*n},ease:wu(.25,.1,.25,1),"ease-in":wu(.42,0,1,1),"ease-out":wu(0,0,.58,1),"ease-in-out":wu(.42,0,.58,1),"ease-in-sine":wu(.47,0,.745,.715),"ease-out-sine":wu(.39,.575,.565,1),"ease-in-out-sine":wu(.445,.05,.55,.95),"ease-in-quad":wu(.55,.085,.68,.53),"ease-out-quad":wu(.25,.46,.45,.94),"ease-in-out-quad":wu(.455,.03,.515,.955),"ease-in-cubic":wu(.55,.055,.675,.19),"ease-out-cubic":wu(.215,.61,.355,1),"ease-in-out-cubic":wu(.645,.045,.355,1),"ease-in-quart":wu(.895,.03,.685,.22),"ease-out-quart":wu(.165,.84,.44,1),"ease-in-out-quart":wu(.77,0,.175,1),"ease-in-quint":wu(.755,.05,.855,.06),"ease-out-quint":wu(.23,1,.32,1),"ease-in-out-quint":wu(.86,0,.07,1),"ease-in-expo":wu(.95,.05,.795,.035),"ease-out-expo":wu(.19,1,.22,1),"ease-in-out-expo":wu(1,0,0,1),"ease-in-circ":wu(.6,.04,.98,.335),"ease-out-circ":wu(.075,.82,.165,1),"ease-in-out-circ":wu(.785,.135,.15,.86),spring:function(e,t,n){if(n===0)return Tu.linear;var r=Cu(e,t,n);return function(e,t,n){return e+(t-e)*r(n)}},"cubic-bezier":wu};function Eu(e,t,n,r,i){if(r===1||t===n)return n;var a=i(t,n,r);return e==null?a:((e.roundValue||e.color)&&(a=Math.round(a)),e.min!==void 0&&(a=Math.max(a,e.min)),e.max!==void 0&&(a=Math.min(a,e.max)),a)}function Du(e,t){return e.pfValue!=null||e.value!=null?e.pfValue!=null&&(t==null||t.type.units!==`%`)?e.pfValue:e.value:e}function Ou(e,t,n,r,i){var a=i==null?null:i.type;n<0?n=0:n>1&&(n=1);var o=Du(e,i),s=Du(t,i);if(A(o)&&A(s))return Eu(a,o,s,n,r);if(D(o)&&D(s)){for(var c=[],l=0;l0?(d===`spring`&&f.push(o.duration),o.easingImpl=Tu[d].apply(null,f)):o.easingImpl=Tu[d]}var p=o.easingImpl,m=o.duration===0?1:(n-c)/o.duration;if(o.applying&&(m=o.progress),m<0?m=0:m>1&&(m=1),o.delay==null){var h=o.startPosition,g=o.position;if(g&&i&&!e.locked()){var _={};Au(h.x,g.x)&&(_.x=Ou(h.x,g.x,m,p)),Au(h.y,g.y)&&(_.y=Ou(h.y,g.y,m,p)),e.position(_)}var v=o.startPan,y=o.pan,b=a.pan,x=y!=null&&r;x&&(Au(v.x,y.x)&&(b.x=Ou(v.x,y.x,m,p)),Au(v.y,y.y)&&(b.y=Ou(v.y,y.y,m,p)),e.emit(`pan`));var S=o.startZoom,C=o.zoom,w=C!=null&&r;w&&(Au(S,C)&&(a.zoom=Gn(a.minZoom,Ou(S,C,m,p),a.maxZoom)),e.emit(`zoom`)),(x||w)&&e.emit(`viewport`);var E=o.style;if(E&&E.length>0&&i){for(var D=0;D=0;t--){var n=e[t];n()}e.splice(0,e.length)},u=a.length-1;u>=0;u--){var d=a[u],f=d._private;if(f.stopped){a.splice(u,1),f.hooked=!1,f.playing=!1,f.started=!1,l(f.frames);continue}!f.playing&&!f.applying||(f.playing&&f.applying&&(f.applying=!1),f.started||ju(t,d,e),ku(t,d,e,n),f.applying&&=!1,l(f.frames),f.step!=null&&f.step(e),d.completed()&&(a.splice(u,1),f.hooked=!1,f.playing=!1,f.started=!1,l(f.completes)),s=!0)}return!n&&a.length===0&&o.length===0&&r.push(t),s}for(var a=!1,o=0;o0?t.notify(`draw`,n):t.notify(`draw`)),n.unmerge(r),t.emit(`step`)}var Nu={animate:pc.animate(),animation:pc.animation(),animated:pc.animated(),clearQueue:pc.clearQueue(),delay:pc.delay(),delayAnimation:pc.delayAnimation(),stop:pc.stop(),addToAnimationPool:function(e){var t=this;t.styleEnabled()&&t._private.aniEles.merge(e)},stopAnimationLoop:function(){this._private.animationsRunning=!1},startAnimationLoop:function(){var e=this;if(e._private.animationsRunning=!0,!e.styleEnabled())return;function t(){e._private.animationsRunning&&dt(function(n){Mu(n,e),t()})}var n=e.renderer();n&&n.beforeRender?n.beforeRender(function(t,n){Mu(n,e)},n.beforeRenderPriorities.animations):t()}},Pu={qualifierCompare:function(e,t){return e==null||t==null?e==null&&t==null:e.sameText(t)},eventMatches:function(e,t,n){var r=t.qualifier;return r==null||e!==n.target&&P(n.target)&&r.matches(n.target)},addEventFields:function(e,t){t.cy=e,t.target=e},callbackContext:function(e,t,n){return t.qualifier==null?e:n.target}},Fu=function(e){return T(e)?new Fc(e):e},Iu={createEmitter:function(){var e=this._private;return e.emitter||=new Vl(Pu,this),this},emitter:function(){return this._private.emitter},on:function(e,t,n){return this.emitter().on(e,Fu(t),n),this},removeListener:function(e,t,n){return this.emitter().removeListener(e,Fu(t),n),this},removeAllListeners:function(){return this.emitter().removeAllListeners(),this},one:function(e,t,n){return this.emitter().one(e,Fu(t),n),this},once:function(e,t,n){return this.emitter().one(e,Fu(t),n),this},emit:function(e,t){return this.emitter().emit(e,t),this},emitAndNotify:function(e,t){return this.emit(e),this.notify(e,t),this}};pc.eventAliasesOn(Iu);var Lu={png:function(e){var t=this._private.renderer;return e||={},t.png(e)},jpg:function(e){var t=this._private.renderer;return e||={},e.bg=e.bg||`#fff`,t.jpg(e)}};Lu.jpeg=Lu.jpg;var Ru={layout:function(e){var t=this;if(e==null){Lt(`Layout options must be specified to make a layout`);return}if(e.name==null){Lt("A `name` must be specified to make a layout");return}var n=e.name,r=t.extension(`layout`,n);if(r==null){Lt("No such layout `"+n+"` found. Did you forget to import it and `cytoscape.use()` it?");return}return new r(X({},e,{cy:t,eles:T(e.eles)?t.$(e.eles):e.eles==null?t.$():e.eles}))}};Ru.createLayout=Ru.makeLayout=Ru.layout;var zu={notify:function(e,t){var n=this._private;if(this.batching()){n.batchNotifications=n.batchNotifications||{};var r=n.batchNotifications[e]=n.batchNotifications[e]||this.collection();t!=null&&r.merge(t);return}if(n.notificationsEnabled){var i=this.renderer();this.destroyed()||!i||i.notify(e,t)}},notifications:function(e){var t=this._private;return e===void 0?t.notificationsEnabled:(t.notificationsEnabled=!!e,this)},noNotifications:function(e){this.notifications(!1),e(),this.notifications(!0)},batching:function(){return this._private.batchCount>0},startBatch:function(){var e=this._private;return e.batchCount??=0,e.batchCount===0&&(e.batchStyleEles=this.collection(),e.batchNotifications={}),e.batchCount++,this},endBatch:function(){var e=this._private;if(e.batchCount===0)return this;if(e.batchCount--,e.batchCount===0){e.batchStyleEles.updateStyle();var t=this.renderer();Object.keys(e.batchNotifications).forEach(function(n){var r=e.batchNotifications[n];r.empty()?t.notify(n):t.notify(n,r)})}return this},batch:function(e){return this.startBatch(),e(),this.endBatch(),this},batchData:function(e){var t=this;return this.batch(function(){for(var n=Object.keys(e),r=0;r0;)t.removeChild(t.childNodes[0]);e._private.renderer=null,e.mutableElements().forEach(function(e){var t=e._private;t.rscratch={},t.rstyle={},t.animation.current=[],t.animation.queue=[]})},onRender:function(e){return this.on(`render`,e)},offRender:function(e){return this.off(`render`,e)}};Vu.invalidateDimensions=Vu.resize;var Hu={collection:function(e,t){return T(e)?this.$(e):N(e)?e.collection():D(e)?(t||={},new yu(this,e,t.unique,t.removed)):new yu(this)},nodes:function(e){var t=this.$(function(e){return e.isNode()});return e?t.filter(e):t},edges:function(e){var t=this.$(function(e){return e.isEdge()});return e?t.filter(e):t},$:function(e){var t=this._private.elements;return e?t.filter(e):t.spawnSelf()},mutableElements:function(){return this._private.elements}};Hu.elements=Hu.filter=Hu.$;var Uu={},Wu=`t`,Gu=`f`;Uu.apply=function(e){for(var t=this,n=t._private.cy.collection(),r=0;r0;if(f||d&&p){var m=void 0;f&&p||f?m=l.properties:p&&(m=l.mappedProperties);for(var h=0;h1&&(b=1),s.color){var S=r.valueMin[0],C=r.valueMax[0],w=r.valueMin[1],T=r.valueMax[1],E=r.valueMin[2],D=r.valueMax[2],O=r.valueMin[3]==null?1:r.valueMin[3],k=r.valueMax[3]==null?1:r.valueMax[3],j=[Math.round(S+(C-S)*b),Math.round(w+(T-w)*b),Math.round(E+(D-E)*b),Math.round(O+(k-O)*b)];a={bypass:r.bypass,name:r.name,value:j,strValue:`rgb(`+j[0]+`, `+j[1]+`, `+j[2]+`)`}}else if(s.number){var M=r.valueMin+(r.valueMax-r.valueMin)*b;a=this.parse(r.name,M,r.bypass,f)}else return!1;if(!a)return h(),!1;a.mapping=r,r=a;break;case o.data:for(var N=r.field.split(`.`),P=d.data,F=0;F0&&a>0){for(var s={},c=!1,l=0;l0?e.delayAnimation(o).play().promise().then(t):t()}).then(function(){return e.animation({style:s,duration:a,easing:e.pstyle(`transition-timing-function`).value,queue:!1}).play().promise()}).then(function(){n.removeBypasses(e,i),e.emitAndNotify(`style`),r.transitioning=!1})}else r.transitioning&&=(this.removeBypasses(e,i),e.emitAndNotify(`style`),!1)},Uu.checkTrigger=function(e,t,n,r,i,a){var o=this.properties[t],s=i(o);e.removed()||s!=null&&s(n,r,e)&&a(o)},Uu.checkZOrderTrigger=function(e,t,n,r){var i=this;this.checkTrigger(e,t,n,r,function(e){return e.triggersZOrder},function(){i._private.cy.notify(`zorder`,e)})},Uu.checkBoundsTrigger=function(e,t,n,r){this.checkTrigger(e,t,n,r,function(e){return e.triggersBounds},function(t){e.dirtyCompoundBoundsCache(),e.dirtyBoundingBoxCache()})},Uu.checkConnectedEdgesBoundsTrigger=function(e,t,n,r){this.checkTrigger(e,t,n,r,function(e){return e.triggersBoundsOfConnectedEdges},function(t){e.connectedEdges().forEach(function(e){e.dirtyBoundingBoxCache()})})},Uu.checkParallelEdgesBoundsTrigger=function(e,t,n,r){this.checkTrigger(e,t,n,r,function(e){return e.triggersBoundsOfParallelEdges},function(t){e.parallelEdges().forEach(function(e){e.dirtyBoundingBoxCache()})})},Uu.checkTriggers=function(e,t,n,r){e.dirtyStyleCache(),this.checkZOrderTrigger(e,t,n,r),this.checkBoundsTrigger(e,t,n,r),this.checkConnectedEdgesBoundsTrigger(e,t,n,r),this.checkParallelEdgesBoundsTrigger(e,t,n,r)};var Ku={};Ku.applyBypass=function(e,t,n,r){var i=this,a=[],o=!0;if(t===`*`||t===`**`){if(n!==void 0)for(var s=0;si.length?r.substr(i.length):``}function c(){a=a.length>o.length?a.substr(o.length):``}for(;!r.match(/^\s*$/);){var l=r.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);if(!l){zt(`Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: `+r);break}i=l[0];var u=l[1];if(u!==`core`&&new Fc(u).invalid){zt(`Skipping parsing of block: Invalid selector found in string stylesheet: `+u),s();continue}var d=l[2],f=!1;a=d;for(var p=[];!a.match(/^\s*$/);){var m=a.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);if(!m){zt(`Skipping parsing of block: Invalid formatting of style property and value definitions found in:`+d),f=!0;break}o=m[0];var h=m[1],g=m[2];if(!t.properties[h]){zt(`Skipping property: Invalid property name in: `+o),c();continue}if(!n.parse(h,g)){zt(`Skipping property: Invalid property definition in: `+o),c();continue}p.push({name:h,val:g}),c()}if(f){s();break}n.selector(u);for(var _=0;_=7&&t[0]===`d`&&(u=new RegExp(s.data.regex).exec(t))){if(n)return!1;var f=s.data;return{name:e,value:u,strValue:``+t,mapped:f,field:u[1],bypass:n}}else if(t.length>=10&&t[0]===`m`&&(d=new RegExp(s.mapData.regex).exec(t))){if(n||l.multiple)return!1;var p=s.mapData;if(!(l.color||l.number))return!1;var m=this.parse(e,d[4]);if(!m||m.mapped)return!1;var h=this.parse(e,d[5]);if(!h||h.mapped)return!1;if(m.pfValue===h.pfValue||m.strValue===h.strValue)return zt("`"+e+`: `+t+"` is not a valid mapper because the output range is zero; converting to `"+e+`: `+m.strValue+"`"),this.parse(e,m.strValue);if(l.color){var g=m.value,_=h.value;if(g[0]===_[0]&&g[1]===_[1]&&g[2]===_[2]&&(g[3]===_[3]||(g[3]==null||g[3]===1)&&(_[3]==null||_[3]===1)))return!1}return{name:e,value:d,strValue:``+t,mapped:p,field:d[1],fieldMin:parseFloat(d[2]),fieldMax:parseFloat(d[3]),valueMin:m.value,valueMax:h.value,bypass:n}}}if(l.multiple&&r!==`multiple`){var v=c?t.split(/\s+/):D(t)?t:[t];if(l.evenMultiple&&v.length%2!=0)return null;for(var y=[],b=[],x=[],S=``,C=!1,w=0;w0?` `:``)+O.strValue}return l.validate&&!l.validate(y,b)?null:l.singleEnum&&C?y.length===1&&T(y[0])?{name:e,value:y[0],strValue:y[0],bypass:n}:null:{name:e,value:y,pfValue:x,strValue:S,bypass:n,units:b}}var k=function(){for(var r=0;rl.max||l.strictMax&&t===l.max))return null;var F={name:e,value:t,strValue:``+t+(A||``),units:A,bypass:n};return l.unitless||A!==`px`&&A!==`em`?F.pfValue=t:F.pfValue=A===`px`||!A?t:this.getEmSizeInPixels()*t,(A===`ms`||A===`s`)&&(F.pfValue=A===`ms`?t:1e3*t),(A===`deg`||A===`rad`)&&(F.pfValue=A===`rad`?t:Fn(t)),A===`%`&&(F.pfValue=t/100),F}else if(l.propList){var I=[],L=``+t;if(L!==`none`){for(var R=L.split(/\s*,\s*|\s+/),z=0;z0&&o>0&&!isNaN(n.w)&&!isNaN(n.h)&&n.w>0&&n.h>0){s=Math.min((a-2*t)/n.w,(o-2*t)/n.h),s=s>this._private.maxZoom?this._private.maxZoom:s,s=s=n.minZoom&&(n.maxZoom=t),this},minZoom:function(e){return e===void 0?this._private.minZoom:this.zoomRange({min:e})},maxZoom:function(e){return e===void 0?this._private.maxZoom:this.zoomRange({max:e})},getZoomedViewport:function(e){var t=this._private,n=t.pan,r=t.zoom,i,a,o=!1;if(t.zoomingEnabled||(o=!0),A(e)?a=e:O(e)&&(a=e.level,e.position==null?e.renderedPosition!=null&&(i=e.renderedPosition):i=On(e.position,r,n),i!=null&&!t.panningEnabled&&(o=!0)),a=a>t.maxZoom?t.maxZoom:a,a=at.maxZoom||!t.zoomingEnabled?a=!0:(t.zoom=s,i.push(`zoom`))}if(r&&(!a||!e.cancelOnFailedZoom)&&t.panningEnabled){var c=e.pan;A(c.x)&&(t.pan.x=c.x,o=!1),A(c.y)&&(t.pan.y=c.y,o=!1),o||i.push(`pan`)}return i.length>0&&(i.push(`viewport`),this.emit(i.join(` `)),this.notify(`viewport`)),this},center:function(e){var t=this.getCenterPan(e);return t&&(this._private.pan=t,this.emit(`pan viewport`),this.notify(`viewport`)),this},getCenterPan:function(e,t){if(this._private.panningEnabled){if(T(e)){var n=e;e=this.mutableElements().filter(n)}else N(e)||(e=this.mutableElements());if(e.length!==0){var r=e.boundingBox(),i=this.width(),a=this.height();return t=t===void 0?this._private.zoom:t,{x:(i-t*(r.x1+r.x2))/2,y:(a-t*(r.y1+r.y2))/2}}}},reset:function(){return!this._private.panningEnabled||!this._private.zoomingEnabled||this.viewport({pan:{x:0,y:0},zoom:1}),this},invalidateSize:function(){this._private.sizeCache=null},size:function(){var e=this._private,t=e.container,n=this;return e.sizeCache=e.sizeCache||(t?function(){var e=n.window().getComputedStyle(t),r=function(t){return parseFloat(e.getPropertyValue(t))};return{width:t.clientWidth-r(`padding-left`)-r(`padding-right`),height:t.clientHeight-r(`padding-top`)-r(`padding-bottom`)}}():{width:1,height:1})},width:function(){return this.size().width},height:function(){return this.size().height},extent:function(){var e=this._private.pan,t=this._private.zoom,n=this.renderedExtent(),r={x1:(n.x1-e.x)/t,x2:(n.x2-e.x)/t,y1:(n.y1-e.y)/t,y2:(n.y2-e.y)/t};return r.w=r.x2-r.x1,r.h=r.y2-r.y1,r},renderedExtent:function(){var e=this.width(),t=this.height();return{x1:0,y1:0,x2:e,y2:t,w:e,h:t}},multiClickDebounceTime:function(e){if(e)this._private.multiClickDebounceTime=e;else return this._private.multiClickDebounceTime;return this}};rd.centre=rd.center,rd.autolockNodes=rd.autolock,rd.autoungrabifyNodes=rd.autoungrabify;var id={data:pc.data({field:`data`,bindingEvent:`data`,allowBinding:!0,allowSetting:!0,settingEvent:`data`,settingTriggersEvent:!0,triggerFnName:`trigger`,allowGetting:!0,updateStyle:!0}),removeData:pc.removeData({field:`data`,event:`data`,triggerFnName:`trigger`,triggerEvent:!0,updateStyle:!0}),scratch:pc.data({field:`scratch`,bindingEvent:`scratch`,allowBinding:!0,allowSetting:!0,settingEvent:`scratch`,settingTriggersEvent:!0,triggerFnName:`trigger`,allowGetting:!0,updateStyle:!0}),removeScratch:pc.removeData({field:`scratch`,event:`scratch`,triggerFnName:`trigger`,triggerEvent:!0,updateStyle:!0})};id.attr=id.data,id.removeAttr=id.removeData;var ad=function(e){var t=this;e=X({},e);var n=e.container;n&&!M(n)&&M(n[0])&&(n=n[0]);var r=n?n._cyreg:null;r||={},r&&r.cy&&(r.cy.destroy(),r={});var i=r.readies=r.readies||[];n&&(n._cyreg=r),r.cy=t;var a=v!==void 0&&n!==void 0&&!e.headless,o=e;o.layout=X({name:a?`grid`:`null`},o.layout),o.renderer=X({name:a?`canvas`:`null`},o.renderer);var s=function(e,t,n){return t===void 0?n===void 0?e:n:t},c=this._private={container:n,ready:!1,options:o,elements:new yu(this),listeners:[],aniEles:new yu(this),data:o.data||{},scratch:{},layout:null,renderer:null,destroyed:!1,notificationsEnabled:!0,minZoom:1e-50,maxZoom:1e50,zoomingEnabled:s(!0,o.zoomingEnabled),userZoomingEnabled:s(!0,o.userZoomingEnabled),panningEnabled:s(!0,o.panningEnabled),userPanningEnabled:s(!0,o.userPanningEnabled),boxSelectionEnabled:s(!0,o.boxSelectionEnabled),autolock:s(!1,o.autolock,o.autolockNodes),autoungrabify:s(!1,o.autoungrabify,o.autoungrabifyNodes),autounselectify:s(!1,o.autounselectify),styleEnabled:o.styleEnabled===void 0?a:o.styleEnabled,zoom:A(o.zoom)?o.zoom:1,pan:{x:O(o.pan)&&A(o.pan.x)?o.pan.x:0,y:O(o.pan)&&A(o.pan.y)?o.pan.y:0},animation:{current:[],queue:[]},hasCompoundNodes:!1,multiClickDebounceTime:s(250,o.multiClickDebounceTime)};this.createEmitter(),this.selectionType(o.selectionType),this.zoomRange({min:o.minZoom,max:o.maxZoom});var l=function(e,t){if(e.some(H))return fa.all(e).then(t);t(e)};c.styleEnabled&&t.setStyle([]);var u=X({},o,o.renderer);t.initRenderer(u);var d=function(e,n,r){t.notifications(!1);var i=t.mutableElements();i.length>0&&i.remove(),e!=null&&(O(e)||D(e))&&t.add(e),t.one(`layoutready`,function(e){t.notifications(!0),t.emit(e),t.one(`load`,n),t.emitAndNotify(`load`)}).one(`layoutstop`,function(){t.one(`done`,r),t.emit(`done`)});var a=X({},t._private.options.layout);a.eles=t.elements(),t.layout(a).run()};l([o.style,o.elements],function(e){var n=e[0],a=e[1];c.styleEnabled&&t.style().append(n),d(a,function(){t.startAnimationLoop(),c.ready=!0,E(o.ready)&&t.on(`ready`,o.ready);for(var e=0;e0,s=!!e.boundingBox,c=Kn(s?e.boundingBox:structuredClone(t.extent())),l;if(N(e.roots))l=e.roots;else if(D(e.roots)){for(var u=[],d=0;d0;){var M=j(),P=E(M,k);if(P)M.outgoers().filter(function(e){return e.isNode()&&n.has(e)}).forEach(A);else if(P===null){zt("Detected double maximal shift for node `"+M.id()+"`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.");break}}}var F=0;if(e.avoidOverlap)for(var I=0;I0&&_[0].length<=3?a/2:0),l=2*Math.PI/_[r].length*i;return r===0&&_[0].length===1&&(o=1),{x:ee.x+o*Math.cos(l),y:ee.y+o*Math.sin(l)}}else{var u=_[r].length,d=Math.max(u===1?0:s?(c.w-e.padding*2-Y.w)/((e.grid?ne:u)-1):(c.w-e.padding*2-Y.w)/((e.grid?ne:u)+1),F);return{x:ee.x+(i+1-(u+1)/2)*d,y:ee.y+(r+1-(U+1)/2)*te}}},ie={downward:0,leftward:90,upward:180,rightward:-90};return Object.keys(ie).indexOf(e.direction)===-1&&Lt(`Invalid direction '${e.direction}' specified for breadthfirst layout. Valid values are: ${Object.keys(ie).join(`, `)}`),n.nodes().layoutPositions(this,e,function(t){return Ot(re(t),c,ie[e.direction])}),this};var fd={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,radius:void 0,startAngle:3/2*Math.PI,sweep:void 0,clockwise:!0,sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function pd(e){this.options=X({},fd,e)}pd.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=t.counterclockwise===void 0?t.clockwise:!t.counterclockwise,a=r.nodes().not(`:parent`);t.sort&&(a=a.sort(t.sort));for(var o=Kn(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()}),s={x:o.x1+o.w/2,y:o.y1+o.h/2},c=(t.sweep===void 0?2*Math.PI-2*Math.PI/a.length:t.sweep)/Math.max(1,a.length-1),l,u=0,d=0;d1&&t.avoidOverlap){u*=1.75;var h=Math.cos(c)-Math.cos(0),g=Math.sin(c)-Math.sin(0),_=Math.sqrt(u*u/(h*h+g*g));l=Math.max(_,l)}return r.nodes().layoutPositions(this,t,function(e,n){var r=t.startAngle+n*c*(i?1:-1),a=l*Math.cos(r),o=l*Math.sin(r);return{x:s.x+a,y:s.y+o}}),this};var md={fit:!0,padding:30,startAngle:3/2*Math.PI,sweep:void 0,clockwise:!0,equidistant:!1,minNodeSpacing:10,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,height:void 0,width:void 0,spacingFactor:void 0,concentric:function(e){return e.degree()},levelWidth:function(e){return e.maxDegree()/4},animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function hd(e){this.options=X({},md,e)}hd.prototype.run=function(){for(var e=this.options,t=e,n=t.counterclockwise===void 0?t.clockwise:!t.counterclockwise,r=e.cy,i=t.eles,a=i.nodes().not(`:parent`),o=Kn(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()}),s={x:o.x1+o.w/2,y:o.y1+o.h/2},c=[],l=0,u=0;u0&&Math.abs(_[0].value-y.value)>=h&&(_=[],g.push(_)),_.push(y)}var b=l+t.minNodeSpacing;if(!t.avoidOverlap){var x=g.length>0&&g[0].length>1,S=(Math.min(o.w,o.h)/2-b)/(g.length+x?1:0);b=Math.min(b,S)}for(var C=0,w=0;w1&&t.avoidOverlap){var D=Math.cos(E)-Math.cos(0),O=Math.sin(E)-Math.sin(0),k=Math.sqrt(b*b/(D*D+O*O));C=Math.max(k,C)}T.r=C,C+=b}if(t.equidistant){for(var A=0,j=0,M=0;M=e.numIter||(Ed(r,e),r.temperature*=e.coolingFactor,r.temperature=e.animationThreshold&&a(),dt(u)):(Rd(r,e),s())};u()}else{for(;l;)l=o(c),c++;Rd(r,e),s()}return this},vd.prototype.stop=function(){return this.stopped=!0,this.thread&&this.thread.stop(),this.emit(`layoutstop`),this},vd.prototype.destroy=function(){return this.thread&&this.thread.stop(),this};var yd=function(e,t,n){for(var r=n.eles.edges(),i=n.eles.nodes(),a=Kn(n.boundingBox?n.boundingBox:{x1:0,y1:0,w:e.width(),h:e.height()}),o={isCompound:e.hasCompoundNodes(),layoutNodes:[],idToIndex:{},nodeSize:i.size(),graphSet:[],indexToGraph:[],layoutEdges:[],edgeSize:r.size(),temperature:n.initialTemp,clientWidth:a.w,clientHeight:a.h,boundingBox:a},s=n.eles.components(),c={},l=0;l0){o.graphSet.push(C);for(var l=0;lr.count?0:r.graph},xd=function(e,t,n,r){var i=r.graphSet[n];if(-10)var c=r.nodeOverlap*s,l=Math.sqrt(i*i+a*a),u=c*i/l,d=c*a/l;else var f=jd(e,i,a),p=jd(t,-1*i,-1*a),m=p.x-f.x,h=p.y-f.y,g=m*m+h*h,l=Math.sqrt(g),c=(e.nodeRepulsion+t.nodeRepulsion)/g,u=c*m/l,d=c*h/l;e.isLocked||(e.offsetX-=u,e.offsetY-=d),t.isLocked||(t.offsetX+=u,t.offsetY+=d)}},Ad=function(e,t,n,r){if(n>0)var i=e.maxX-t.minX;else var i=t.maxX-e.minX;if(r>0)var a=e.maxY-t.minY;else var a=t.maxY-e.minY;return i>=0&&a>=0?Math.sqrt(i*i+a*a):0},jd=function(e,t,n){var r=e.positionX,i=e.positionY,a=e.height||1,o=e.width||1,s=n/t,c=a/o,l={};return t===0&&0n?(l.x=r,l.y=i+a/2,l):0t&&-1*c<=s&&s<=c?(l.x=r-o/2,l.y=i-o*n/2/t,l):0=c)?(l.x=r+a*t/2/n,l.y=i+a/2,l):0>n&&(s<=-1*c||s>=c)?(l.x=r-a*t/2/n,l.y=i-a/2,l):l},Md=function(e,t){for(var n=0;nn){var h=t.gravity*f/m,g=t.gravity*p/m;d.offsetX+=h,d.offsetY+=g}}}}},Pd=function(e,t){var n=[],r=0,i=-1;for(n.push.apply(n,e.graphSet[0]),i+=e.graphSet[0].length;r<=i;){var a=n[r++],o=e.idToIndex[a],s=e.layoutNodes[o],c=s.children;if(0n)var i={x:n*e/r,y:n*t/r};else var i={x:e,y:t};return i},Ld=function(e,t){var n=e.parentId;if(n!=null){var r=t.layoutNodes[t.idToIndex[n]],i=!1;if((r.maxX==null||e.maxX+r.padRight>r.maxX)&&(r.maxX=e.maxX+r.padRight,i=!0),(r.minX==null||e.minX-r.padLeftr.maxY)&&(r.maxY=e.maxY+r.padBottom,i=!0),(r.minY==null||e.minY-r.padToph&&(f+=m+t.componentSpacing,d=0,p=0,m=0)}}},zd={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,avoidOverlapPadding:10,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,condense:!1,rows:void 0,cols:void 0,position:function(e){},sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function Bd(e){this.options=X({},zd,e)}Bd.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=r.nodes().not(`:parent`);t.sort&&(i=i.sort(t.sort));var a=Kn(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()});if(a.h===0||a.w===0)r.nodes().layoutPositions(this,t,function(e){return{x:a.x1,y:a.y1}});else{var o=i.size(),s=Math.sqrt(o*a.h/a.w),c=Math.round(s),l=Math.round(a.w/a.h*s),u=function(e){if(e==null)return Math.min(c,l);Math.min(c,l)==c?c=e:l=e},d=function(e){if(e==null)return Math.max(c,l);Math.max(c,l)==c?c=e:l=e},f=t.rows,p=t.cols==null?t.columns:t.cols;if(f!=null&&p!=null)c=f,l=p;else if(f!=null&&p==null)c=f,l=Math.ceil(o/c);else if(f==null&&p!=null)l=p,c=Math.ceil(o/l);else if(l*c>o){var m=u(),h=d();(m-1)*h>=o?u(m-1):(h-1)*m>=o&&d(h-1)}else for(;l*c=o?d(_+1):u(g+1)}var v=a.w/l,y=a.h/c;if(t.condense&&(v=0,y=0),t.avoidOverlap)for(var b=0;b=l&&(j=0,A++)},N={},P=0;P(y=pr(e,t,b[x],b[x+1],b[x+2],b[x+3])))return g(n,y),!0}else if(o.edgeType===`bezier`||o.edgeType===`multibezier`||o.edgeType===`self`||o.edgeType===`compound`){for(var b=o.allpts,x=0;x+5(y=fr(e,t,b[x],b[x+1],b[x+2],b[x+3],b[x+4],b[x+5])))return g(n,y),!0}for(var h=h||r.source,v=v||r.target,S=i.getArrowWidth(c,d),C=[{name:`source`,x:o.arrowStartX,y:o.arrowStartY,angle:o.srcArrowAngle},{name:`target`,x:o.arrowEndX,y:o.arrowEndY,angle:o.tgtArrowAngle},{name:`mid-source`,x:o.midX,y:o.midY,angle:o.midsrcArrowAngle},{name:`mid-target`,x:o.midX,y:o.midY,angle:o.midtgtArrowAngle}],x=0;x0&&(_(h),_(v))}function y(e,t,n){return Xt(e,t,n)}function b(n,r){var i=n._private,a=f,o=r?r+`-`:``;n.boundingBox();var s=i.labelBounds[r||`main`],c=n.pstyle(o+`label`).value;if(!(n.pstyle(`text-events`).strValue!==`yes`||!c)){var l=y(i.rscratch,`labelX`,r),u=y(i.rscratch,`labelY`,r),d=y(i.rscratch,`labelAngle`,r),p=n.pstyle(o+`text-margin-x`).pfValue,m=n.pstyle(o+`text-margin-y`).pfValue,h=s.x1-a-p,_=s.x2+a-p,v=s.y1-a-m,b=s.y2+a-m;if(d){var x=Math.cos(d),S=Math.sin(d),C=function(e,t){return e-=l,t-=u,{x:e*x-t*S+l,y:e*S+t*x+u}},w=C(h,v),T=C(h,b),E=C(_,v),D=C(_,b);if(mr(e,t,[w.x+p,w.y+m,E.x+p,E.y+m,D.x+p,D.y+m,T.x+p,T.y+m]))return g(n),!0}else if(tr(s,e,t))return g(n),!0}}for(var x=o.length-1;x>=0;x--){var S=o[x];S.isNode()?_(S)||b(S):v(S)||b(S)||b(S,`source`)||b(S,`target`)}return s},Qd.getAllInBox=function(e,t,n,r){var i=this.getCachedZSortedEles().interactive,a=2/this.cy.zoom(),o=[],s=Math.min(e,n),c=Math.max(e,n),l=Math.min(t,r),u=Math.max(t,r);e=s,n=c,t=l,r=u;var d=Kn({x1:e,y1:t,x2:n,y2:r}),p=[{x:d.x1,y:d.y1},{x:d.x2,y:d.y1},{x:d.x2,y:d.y2},{x:d.x1,y:d.y2}],m=[[p[0],p[1]],[p[1],p[2]],[p[2],p[3]],[p[3],p[0]]];function h(e,t,n){return Xt(e,t,n)}function g(e,t){var n=e._private,r=a,i=``;e.boundingBox();var o=n.labelBounds.main;if(!o)return null;var s=h(n.rscratch,`labelX`,t),c=h(n.rscratch,`labelY`,t),l=h(n.rscratch,`labelAngle`,t),u=e.pstyle(i+`text-margin-x`).pfValue,d=e.pstyle(i+`text-margin-y`).pfValue,f=o.x1-r-u,p=o.x2+r-u,m=o.y1-r-d,g=o.y2+r-d;if(l){var _=Math.cos(l),v=Math.sin(l),y=function(e,t){return e-=s,t-=c,{x:e*_-t*v+s,y:e*v+t*_+c}};return[y(f,m),y(p,m),y(p,g),y(f,g)]}else return[{x:f,y:m},{x:p,y:m},{x:p,y:g},{x:f,y:g}]}function _(e,t,n,r){function i(e,t,n){return(n.y-e.y)*(t.x-e.x)>(t.y-e.y)*(n.x-e.x)}return i(e,n,r)!==i(t,n,r)&&i(e,t,n)!==i(e,t,r)}for(var v=0;v0?-(Math.PI-e.ang):Math.PI+e.ang},Sf=function(e,t,n,r,i){if(e===yf?xf(rf,nf):bf(t,e,nf),bf(t,n,rf),af=nf.nx*rf.ny-nf.ny*rf.nx,of=nf.nx*rf.nx-nf.ny*-rf.ny,lf=Math.asin(Math.max(-1,Math.min(1,af))),Math.abs(lf)<1e-6){ef=t.x,tf=t.y,df=pf=0;return}sf=1,cf=!1,of<0?lf<0?lf=Math.PI+lf:(lf=Math.PI-lf,sf=-1,cf=!0):lf>0&&(sf=-1,cf=!0),pf=t.radius===void 0?r:t.radius,uf=lf/2,mf=Math.min(nf.len/2,rf.len/2),i?(ff=Math.abs(Math.cos(uf)*pf/Math.sin(uf)),ff>mf?(ff=mf,df=Math.abs(ff*Math.sin(uf)/Math.cos(uf))):df=pf):(ff=Math.min(mf,pf),df=Math.abs(ff*Math.sin(uf)/Math.cos(uf))),_f=t.x+rf.nx*ff,vf=t.y+rf.ny*ff,ef=_f-rf.ny*df*sf,tf=vf+rf.nx*df*sf,hf=t.x+nf.nx*ff,gf=t.y+nf.ny*ff,yf=t};function Cf(e,t){t.radius===0?e.lineTo(t.cx,t.cy):e.arc(t.cx,t.cy,t.radius,t.startAngle,t.endAngle,t.counterClockwise)}function wf(e,t,n,r){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;return r===0||t.radius===0?{cx:t.x,cy:t.y,radius:0,startX:t.x,startY:t.y,stopX:t.x,stopY:t.y,startAngle:void 0,endAngle:void 0,counterClockwise:void 0}:(Sf(e,t,n,r,i),{cx:ef,cy:tf,radius:df,startX:hf,startY:gf,stopX:_f,stopY:vf,startAngle:nf.ang+Math.PI/2*sf,endAngle:rf.ang-Math.PI/2*sf,counterClockwise:cf})}var Tf=.01,Ef=Math.sqrt(2*Tf),Df={};Df.findMidptPtsEtc=function(e,t){var n=t.posPts,r=t.intersectionPts,i=t.vectorNormInverse,a,o=e.pstyle(`source-endpoint`),s=e.pstyle(`target-endpoint`),c=o.units!=null&&s.units!=null,l=function(e,t,n,r){var i=r-t,a=n-e,o=Math.sqrt(a*a+i*i);return{x:-i/o,y:a/o}};switch(e.pstyle(`edge-distances`).value){case`node-position`:a=n;break;case`intersection`:a=r;break;case`endpoints`:if(c){var u=f(this.manualEndptToPx(e.source()[0],o),2),d=u[0],p=u[1],m=f(this.manualEndptToPx(e.target()[0],s),2),h=m[0],g=m[1],_={x1:d,y1:p,x2:h,y2:g};i=l(d,p,h,g),a=_}else zt(`Edge ${e.id()} has edge-distances:endpoints specified without manual endpoints specified via source-endpoint and target-endpoint. Falling back on edge-distances:intersection (default).`),a=r;break}return{midptPts:a,vectorNormInverse:i}},Df.findHaystackPoints=function(e){for(var t=0;t0?Math.max(e-t,0):Math.min(e+t,0)},O=D(T,C),k=D(E,w),A=!1;_===l?g=Math.abs(O)>Math.abs(k)?i:r:_===c||_===s?(g=r,A=!0):(_===a||_===o)&&(g=i,A=!0);var j=g===r,M=j?k:O,N=j?E:T,P=Rn(N),F=!1;!(A&&(y||x))&&(_===s&&N<0||_===c&&N>0||_===a&&N>0||_===o&&N<0)&&(P*=-1,M=P*Math.abs(M),F=!0);var I=y?(b<0?1+b:b)*M:(b<0?M:0)+b*P,L=function(e){return Math.abs(e)=Math.abs(M)},R=L(I),z=L(Math.abs(M)-Math.abs(I));if((R||z)&&!F)if(j){var B=Math.abs(N)<=f/2,V=Math.abs(T)<=p/2;if(B){var H=(u.x1+u.x2)/2;n.segpts=[H,u.y1,H,u.y2]}else if(V){var U=(u.y1+u.y2)/2;n.segpts=[u.x1,U,u.x2,U]}else n.segpts=[u.x1,u.y2]}else{var W=Math.abs(N)<=d/2,G=Math.abs(E)<=m/2;if(W){var K=(u.y1+u.y2)/2;n.segpts=[u.x1,K,u.x2,K]}else if(G){var q=(u.x1+u.x2)/2;n.segpts=[q,u.y1,q,u.y2]}else n.segpts=[u.x2,u.y1]}else if(j){var J=u.y1+I+(h?f/2*P:0);n.segpts=[u.x1,J,u.x2,J]}else{var ee=u.x1+I+(h?d/2*P:0);n.segpts=[ee,u.y1,ee,u.y2]}if(n.isRound){var Y=e.pstyle(`taxi-radius`).value,te=e.pstyle(`radius-type`).value[0]===`arc-radius`;n.radii=Array(n.segpts.length/2).fill(Y),n.isArcRadius=Array(n.segpts.length/2).fill(te)}},Df.tryToCorrectInvalidPoints=function(e,t){var n=e._private.rscratch;if(n.edgeType===`bezier`){var r=t.srcPos,i=t.tgtPos,a=t.srcW,o=t.srcH,s=t.tgtW,c=t.tgtH,l=t.srcShape,u=t.tgtShape,d=t.srcCornerRadius,f=t.tgtCornerRadius,p=t.srcRs,m=t.tgtRs,h=!A(n.startX)||!A(n.startY),g=!A(n.arrowStartX)||!A(n.arrowStartY),_=!A(n.endX)||!A(n.endY),v=!A(n.arrowEndX)||!A(n.arrowEndY),y=3*(this.getArrowWidth(e.pstyle(`width`).pfValue,e.pstyle(`arrow-scale`).value)*this.arrowShapeWidth),b=zn({x:n.ctrlpts[0],y:n.ctrlpts[1]},{x:n.startX,y:n.startY}),x=bh.poolIndex()){var g=m;m=h,h=g}var _=u.srcPos=m.position(),v=u.tgtPos=h.position(),y=u.srcW=m.outerWidth(),b=u.srcH=m.outerHeight(),S=u.tgtW=h.outerWidth(),C=u.tgtH=h.outerHeight(),w=u.srcShape=n.nodeShapes[t.getNodeShape(m)],T=u.tgtShape=n.nodeShapes[t.getNodeShape(h)],E=u.srcCornerRadius=m.pstyle(`corner-radius`).value===`auto`?`auto`:m.pstyle(`corner-radius`).pfValue,D=u.tgtCornerRadius=h.pstyle(`corner-radius`).value===`auto`?`auto`:h.pstyle(`corner-radius`).pfValue,O=u.tgtRs=h._private.rscratch,k=u.srcRs=m._private.rscratch;u.dirCounts={north:0,west:0,south:0,east:0,northwest:0,southwest:0,northeast:0,southeast:0};for(var j=0;j=Ef||(G=Math.sqrt(Math.max(W*W,Tf)+Math.max(U*U,Tf)));var K=u.vector={x:W,y:U},q=u.vectorNorm={x:K.x/G,y:K.y/G},J={x:-q.y,y:q.x};u.nodesOverlap=!A(G)||T.checkPoint(L[0],L[1],0,S,C,v.x,v.y,D,O)||w.checkPoint(z[0],z[1],0,y,b,_.x,_.y,E,k),u.vectorNormInverse=J,d={nodesOverlap:u.nodesOverlap,dirCounts:u.dirCounts,calculatedIntersection:!0,hasBezier:u.hasBezier,hasUnbundled:u.hasUnbundled,eles:u.eles,srcPos:v,srcRs:O,tgtPos:_,tgtRs:k,srcW:S,srcH:C,tgtW:y,tgtH:b,srcIntn:B,tgtIntn:R,srcShape:T,tgtShape:w,posPts:{x1:H.x2,y1:H.y2,x2:H.x1,y2:H.y1},intersectionPts:{x1:V.x2,y1:V.y2,x2:V.x1,y2:V.y1},vector:{x:-K.x,y:-K.y},vectorNorm:{x:-q.x,y:-q.y},vectorNormInverse:{x:-J.x,y:-J.y}}}var Y=I?d:u;N.nodesOverlap=Y.nodesOverlap,N.srcIntn=Y.srcIntn,N.tgtIntn=Y.tgtIntn,N.isRound=P.startsWith(`round`),r&&(m.isParent()||m.isChild()||h.isParent()||h.isChild())&&(m.parents().anySame(h)||h.parents().anySame(m)||m.same(h)&&m.isParent())?t.findCompoundLoopPoints(M,Y,j,F):m===h?t.findLoopPoints(M,Y,j,F):P.endsWith(`segments`)?t.findSegmentsPoints(M,Y):P.endsWith(`taxi`)?t.findTaxiPoints(M,Y):P===`straight`||!F&&u.eles.length%2==1&&j===Math.floor(u.eles.length/2)?t.findStraightEdgePoints(M):t.findBezierPoints(M,Y,j,F,I),t.findEndpoints(M),t.tryToCorrectInvalidPoints(M,Y),t.checkForInvalidEdgeWarning(M),t.storeAllpts(M),t.storeEdgeProjections(M),t.calculateArrowAngles(M),t.recalculateEdgeLabelProjections(M),t.calculateLabelAngles(M)}},x=0;x0){var ne=s,re=Bn(ne,An(i)),ie=Bn(ne,An(te)),ae=re;ie2&&Bn(ne,{x:te[2],y:te[3]})0){var _e=c,ve=Bn(_e,An(i)),ye=Bn(_e,An(ge)),be=ve;ye2&&Bn(_e,{x:ge[2],y:ge[3]})=l||v){d={cp:h,segment:_};break}}if(d)break}var y=d.cp,b=d.segment,x=(l-f)/b.length,S=b.t1-b.t0,C=c?b.t0+S*x:b.t1-S*x;C=Gn(0,C,1),t=Un(y.p0,y.p1,y.p2,C),i=Ff(y.p0,y.p1,y.p2,C);break;case`straight`:case`segments`:case`haystack`:for(var w=0,T,E,D,O,k=r.allpts.length,A=0;A+3=l));A+=2);var j=(l-E)/T;j=Gn(0,j,1),t=Wn(D,O,j),i=Pf(D,O);break}o(`labelX`,n,t.x),o(`labelY`,n,t.y),o(`labelAutoAngle`,n,i)}};c(`source`),c(`target`),this.applyLabelDimensions(e)}},Mf.applyLabelDimensions=function(e){this.applyPrefixedLabelDimensions(e),e.isEdge()&&(this.applyPrefixedLabelDimensions(e,`source`),this.applyPrefixedLabelDimensions(e,`target`))},Mf.applyPrefixedLabelDimensions=function(e,t){var n=e._private,r=this.getLabelText(e,t),i=Ct(r,e._private.labelDimsKey);if(Xt(n.rscratch,`prefixedLabelDimsKey`,t)!==i){Zt(n.rscratch,`prefixedLabelDimsKey`,t,i);var a=this.calculateLabelDimensions(e,r),o=e.pstyle(`line-height`).pfValue,s=e.pstyle(`font-size`).pfValue,c=e.pstyle(`text-wrap`).strValue,l=Xt(n.rscratch,`labelWrapCachedLines`,t)||[],u=c===`wrap`?Math.max(l.length,1):1,d=s*o,f=a.width,p=a.height+(u-1)*(o-1)*s;Zt(n.rstyle,`labelWidth`,t,f),Zt(n.rscratch,`labelWidth`,t,f),Zt(n.rstyle,`labelHeight`,t,p),Zt(n.rscratch,`labelHeight`,t,p),Zt(n.rscratch,`labelLineHeight`,t,d),Zt(n.rscratch,`labelActualDescent`,t,a.labelActualDescent)}},Mf.getLabelText=function(e,t){var n=e._private,r=t?t+`-`:``,i=e.pstyle(r+`label`).strValue,a=e.pstyle(`text-transform`).value,s=function(e,r){return r?(Zt(n.rscratch,e,t,r),r):Xt(n.rscratch,e,t)};if(!i)return``;a==`none`||(a==`uppercase`?i=i.toUpperCase():a==`lowercase`&&(i=i.toLowerCase()));var c=e.pstyle(`text-wrap`).value;if(c===`wrap`){var l=s(`labelKey`);if(l!=null&&s(`labelWrapKey`)===l)return s(`labelWrapCachedText`);for(var u=`​`,d=i.split(` +`),f=e.pstyle(`text-max-width`).pfValue,p=e.pstyle(`text-overflow-wrap`).value===`anywhere`,m=[],h=/[\s\u200b]+|$/g,g=0;gf){var y=_.matchAll(h),b=``,x=0,S=o(y),C;try{for(S.s();!(C=S.n()).done;){var w=C.value,T=w[0],E=_.substring(x,w.index);x=w.index+T.length;var D=b.length===0?E:b+E+T;this.calculateLabelDimensions(e,D).width<=f?b+=E+T:(b&&m.push(b),b=E+T)}}catch(e){S.e(e)}finally{S.f()}b.match(/^[\s\u200b]+$/)||m.push(b)}else m.push(_)}s(`labelWrapCachedLines`,m),i=s(`labelWrapCachedText`,m.join(` +`)),s(`labelWrapKey`,l)}else if(c===`ellipsis`){var O=e.pstyle(`text-max-width`).pfValue,k=``,A=`…`,j=!1;if(this.calculateLabelDimensions(e,i).widthO);M++)k+=i[M],M===i.length-1&&(j=!0);return j||(k+=A),k}return i},Mf.getLabelJustification=function(e){var t=e.pstyle(`text-justification`).strValue,n=e.pstyle(`text-halign`).strValue;return t===`auto`?e.isNode()?rl(n):`center`:t},Mf.calculateLabelDimensions=function(e,t){var n=this.cy.window().document,r=0,i=e.pstyle(`font-style`).strValue,a=e.pstyle(`font-size`).pfValue,o=e.pstyle(`font-family`).strValue,s=e.pstyle(`font-weight`).strValue,c=e.pstyle(`text-metrics`).strValue||`font`,l=this.labelCalcCanvas,u=this.labelCalcCanvasContext;if(!l){l=this.labelCalcCanvas=n.createElement(`canvas`),u=this.labelCalcCanvasContext=l.getContext(`2d`);var d=l.style;d.position=`absolute`,d.left=`-9999px`,d.top=`-9999px`,d.zIndex=`-1`,d.visibility=`hidden`,d.pointerEvents=`none`}u.font=`${i} ${s} ${a}px ${o}`;for(var f=0,p=0,m=t.split(` +`),h=m.length,g=0,_=0,v=0;v1&&arguments[1]!==void 0?arguments[1]:!0;if(t.merge(e),n)for(var r=0;r=e.desktopTapThreshold2}var E=a(t);b&&(e.hoverData.tapholdCancelled=!0);var D=function(){var t=e.hoverData.dragDelta=e.hoverData.dragDelta||[];t.length===0?(t.push(v[0]),t.push(v[1])):(t[0]+=v[0],t[1]+=v[1])};n=!0,i(m,[`mousemove`,`vmousemove`,`tapdrag`],t,{x:l[0],y:l[1]});var O=function(e){return{originalEvent:t,type:e,position:{x:l[0],y:l[1]}}},k=function(){e.data.bgActivePosistion=void 0,e.hoverData.selecting||r.emit(O(`boxstart`)),f[4]=1,e.hoverData.selecting=!0,e.redrawHint(`select`,!0),e.redraw()};if(e.hoverData.which===3){if(b){var j=O(`cxtdrag`);_?_.emit(j):r.emit(j),e.hoverData.cxtDragged=!0,(!e.hoverData.cxtOver||m!==e.hoverData.cxtOver)&&(e.hoverData.cxtOver&&e.hoverData.cxtOver.emit(O(`cxtdragout`)),e.hoverData.cxtOver=m,m&&m.emit(O(`cxtdragover`)))}}else if(e.hoverData.dragging){if(n=!0,r.panningEnabled()&&r.userPanningEnabled()){var M;if(e.hoverData.justStartedPan){var N=e.hoverData.mdownPos;M={x:(l[0]-N[0])*s,y:(l[1]-N[1])*s},e.hoverData.justStartedPan=!1}else M={x:v[0]*s,y:v[1]*s};r.panBy(M),r.emit(O(`dragpan`)),e.hoverData.dragged=!0}l=e.projectIntoViewport(t.clientX,t.clientY)}else if(f[4]==1&&(_==null||_.pannable()))b&&(!e.hoverData.dragging&&r.boxSelectionEnabled()&&(E||!r.panningEnabled()||!r.userPanningEnabled())?k():!e.hoverData.selecting&&r.panningEnabled()&&r.userPanningEnabled()&&o(_,e.hoverData.downs)&&(e.hoverData.dragging=!0,e.hoverData.justStartedPan=!0,f[4]=0,e.data.bgActivePosistion=An(u),e.redrawHint(`select`,!0),e.redraw()),_&&_.pannable()&&_.active()&&_.unactivate());else{if(_&&_.pannable()&&_.active()&&_.unactivate(),(!_||!_.grabbed())&&m!=g&&(g&&i(g,[`mouseout`,`tapdragout`],t,{x:l[0],y:l[1]}),m&&i(m,[`mouseover`,`tapdragover`],t,{x:l[0],y:l[1]}),e.hoverData.last=m),_)if(b){if(r.boxSelectionEnabled()&&E)_&&_.grabbed()&&(h(y),_.emit(O(`freeon`)),y.emit(O(`free`)),e.dragData.didDrag&&(_.emit(O(`dragfreeon`)),y.emit(O(`dragfree`)))),k();else if(_&&_.grabbed()&&e.nodeIsDraggable(_)){var P=!e.dragData.didDrag;P&&e.redrawHint(`eles`,!0),e.dragData.didDrag=!0,e.hoverData.draggingEles||p(y,{inDragLayer:!0});var F={x:0,y:0};if(A(v[0])&&A(v[1])&&(F.x+=v[0],F.y+=v[1],P)){var I=e.hoverData.dragDelta;I&&A(I[0])&&A(I[1])&&(F.x+=I[0],F.y+=I[1])}e.hoverData.draggingEles=!0,y.silentShift(F).emit(O(`position`)).emit(O(`drag`)),e.redrawHint(`drag`,!0),e.redraw()}}else D();n=!0}if(f[2]=l[0],f[3]=l[1],n)return t.stopPropagation&&t.stopPropagation(),t.preventDefault&&t.preventDefault(),!1}},!1);var E,D,O;e.registerBinding(t,`mouseup`,function(t){if(!(e.hoverData.which===1&&t.which!==1&&e.hoverData.capture)&&e.hoverData.capture){e.hoverData.capture=!1;var r=e.cy,o=e.projectIntoViewport(t.clientX,t.clientY),s=e.selection,c=e.findNearestElement(o[0],o[1],!0,!1),l=e.dragData.possibleDragElements,u=e.hoverData.down,d=a(t);e.data.bgActivePosistion&&(e.redrawHint(`select`,!0),e.redraw()),e.hoverData.tapholdCancelled=!0,e.data.bgActivePosistion=void 0,u&&u.unactivate();var f=function(e){return{originalEvent:t,type:e,position:{x:o[0],y:o[1]}}};if(e.hoverData.which===3){var p=f(`cxttapend`);if(u?u.emit(p):r.emit(p),!e.hoverData.cxtDragged){var m=f(`cxttap`);u?u.emit(m):r.emit(m)}e.hoverData.cxtDragged=!1,e.hoverData.which=null}else if(e.hoverData.which===1){if(i(c,[`mouseup`,`tapend`,`vmouseup`],t,{x:o[0],y:o[1]}),!e.dragData.didDrag&&!e.hoverData.dragged&&!e.hoverData.selecting&&!e.hoverData.isOverThresholdDrag&&(i(u,[`click`,`tap`,`vclick`],t,{x:o[0],y:o[1]}),D=!1,t.timeStamp-O<=r.multiClickDebounceTime()?(E&&clearTimeout(E),D=!0,O=null,i(u,[`dblclick`,`dbltap`,`vdblclick`],t,{x:o[0],y:o[1]})):(E=setTimeout(function(){D||i(u,[`oneclick`,`onetap`,`voneclick`],t,{x:o[0],y:o[1]})},r.multiClickDebounceTime()),O=t.timeStamp)),u==null&&!e.dragData.didDrag&&!e.hoverData.selecting&&!e.hoverData.dragged&&!a(t)&&(r.$(n).unselect([`tapunselect`]),l.length>0&&e.redrawHint(`eles`,!0),e.dragData.possibleDragElements=l=r.collection()),c==u&&!e.dragData.didDrag&&!e.hoverData.selecting&&c!=null&&c._private.selectable&&(e.hoverData.dragging||(r.selectionType()===`additive`||d?c.selected()?c.unselect([`tapunselect`]):c.select([`tapselect`]):d||(r.$(n).unmerge(c).unselect([`tapunselect`]),c.select([`tapselect`]))),e.redrawHint(`eles`,!0)),e.hoverData.selecting){var g=r.collection(e.getAllInBox(s[0],s[1],s[2],s[3]));e.redrawHint(`select`,!0),g.length>0&&e.redrawHint(`eles`,!0),r.emit(f(`boxend`)),r.selectionType()===`additive`||d||r.$(n).unmerge(g).unselect(),g.emit(f(`box`)).stdFilter(function(e){return e.selectable()&&!e.selected()}).select().emit(f(`boxselect`)),e.redraw()}if(e.hoverData.dragging&&(e.hoverData.dragging=!1,e.redrawHint(`select`,!0),e.redrawHint(`eles`,!0),e.redraw()),!s[4]){e.redrawHint(`drag`,!0),e.redrawHint(`eles`,!0);var _=u&&u.grabbed();h(l),_&&(u.emit(f(`freeon`)),l.emit(f(`free`)),e.dragData.didDrag&&(u.emit(f(`dragfreeon`)),l.emit(f(`dragfree`))))}}s[4]=0,e.hoverData.down=null,e.hoverData.cxtStarted=!1,e.hoverData.draggingEles=!1,e.hoverData.selecting=!1,e.hoverData.isOverThresholdDrag=!1,e.dragData.didDrag=!1,e.hoverData.dragged=!1,e.hoverData.dragDelta=[],e.hoverData.mdownPos=null,e.hoverData.mdownGPos=null,e.hoverData.which=null}},!1);var k=[],j=4,M,N=1e5,P=function(e,t){for(var n=0;n=j){var i=k;if(M=P(i,5),!M){var a=Math.abs(i[0]);M=F(i)&&a>5}if(M)for(var o=0;o5&&(r=Rn(r)*5),f=r/-250,M&&(f/=N,f*=3),f*=e.wheelSensitivity,t.deltaMode===1&&(f*=33);var p=s.zoom()*10**f;t.type===`gesturechange`&&(p=e.gestureStartZoom*t.scale),s.zoom({level:p,renderedPosition:{x:d[0],y:d[1]}}),s.emit({type:t.type===`gesturechange`?`pinchzoom`:`scrollzoom`,originalEvent:t,position:{x:u[0],y:u[1]}})}}}};e.registerBinding(e.container,`wheel`,I,!0),e.registerBinding(t,`scroll`,function(t){e.scrollingPage=!0,clearTimeout(e.scrollingPageTimeout),e.scrollingPageTimeout=setTimeout(function(){e.scrollingPage=!1},250)},!0),e.registerBinding(e.container,`gesturestart`,function(t){e.gestureStartZoom=e.cy.zoom(),e.hasTouchStarted||t.preventDefault()},!0),e.registerBinding(e.container,`gesturechange`,function(t){e.hasTouchStarted||I(t)},!0),e.registerBinding(e.container,`mouseout`,function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:`mouseout`,position:{x:n[0],y:n[1]}})},!1),e.registerBinding(e.container,`mouseover`,function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:`mouseover`,position:{x:n[0],y:n[1]}})},!1);var L,R,z,B,V,H,U,W,G,K,q,J,ee,Y=function(e,t,n,r){return Math.sqrt((n-e)*(n-e)+(r-t)*(r-t))},te=function(e,t,n,r){return(n-e)*(n-e)+(r-t)*(r-t)},ne;e.registerBinding(e.container,`touchstart`,ne=function(t){if(e.hasTouchStarted=!0,w(t)){_(),e.touchData.capture=!0,e.data.bgActivePosistion=void 0;var n=e.cy,r=e.touchData.now,a=e.touchData.earlier;if(t.touches[0]){var o=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);r[0]=o[0],r[1]=o[1]}if(t.touches[1]){var o=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);r[2]=o[0],r[3]=o[1]}if(t.touches[2]){var o=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);r[4]=o[0],r[5]=o[1]}var s=function(e){return{originalEvent:t,type:e,position:{x:r[0],y:r[1]}}};if(t.touches[1]){e.touchData.singleTouchMoved=!0,h(e.dragData.touchDragEles);var c=e.findContainerClientCoords();G=c[0],K=c[1],q=c[2],J=c[3],L=t.touches[0].clientX-G,R=t.touches[0].clientY-K,z=t.touches[1].clientX-G,B=t.touches[1].clientY-K,ee=0<=L&&L<=q&&0<=z&&z<=q&&0<=R&&R<=J&&0<=B&&B<=J;var u=n.pan(),d=n.zoom();V=Y(L,R,z,B),H=te(L,R,z,B),U=[(L+z)/2,(R+B)/2],W=[(U[0]-u.x)/d,(U[1]-u.y)/d];var f=200,g=f*f;if(H=1){for(var T=e.touchData.startPosition=[null,null,null,null,null,null],E=0;E=e.touchTapThreshold2}if(n&&e.touchData.cxt){t.preventDefault();var x=t.touches[0].clientX-G,S=t.touches[0].clientY-K,C=t.touches[1].clientX-G,T=t.touches[1].clientY-K,E=te(x,S,C,T),D=E/H,O=150,k=O*O,j=1.5;if(D>=j*j||E>=k){e.touchData.cxt=!1,e.data.bgActivePosistion=void 0,e.redrawHint(`select`,!0);var M=d(`cxttapend`);e.touchData.start?(e.touchData.start.unactivate().emit(M),e.touchData.start=null):a.emit(M)}}if(n&&e.touchData.cxt){var M=d(`cxtdrag`);e.data.bgActivePosistion=void 0,e.redrawHint(`select`,!0),e.touchData.start?e.touchData.start.emit(M):a.emit(M),e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxtDragged=!0;var N=e.findNearestElement(s[0],s[1],!0,!0);(!e.touchData.cxtOver||N!==e.touchData.cxtOver)&&(e.touchData.cxtOver&&e.touchData.cxtOver.emit(d(`cxtdragout`)),e.touchData.cxtOver=N,N&&N.emit(d(`cxtdragover`)))}else if(n&&t.touches[2]&&a.boxSelectionEnabled())t.preventDefault(),e.data.bgActivePosistion=void 0,this.lastThreeTouch=+new Date,e.touchData.selecting||a.emit(d(`boxstart`)),e.touchData.selecting=!0,e.touchData.didSelect=!0,r[4]=1,!r||r.length===0||r[0]===void 0?(r[0]=(s[0]+s[2]+s[4])/3,r[1]=(s[1]+s[3]+s[5])/3,r[2]=(s[0]+s[2]+s[4])/3+1,r[3]=(s[1]+s[3]+s[5])/3+1):(r[2]=(s[0]+s[2]+s[4])/3,r[3]=(s[1]+s[3]+s[5])/3),e.redrawHint(`select`,!0),e.redraw();else if(n&&t.touches[1]&&!e.touchData.didSelect&&a.zoomingEnabled()&&a.panningEnabled()&&a.userZoomingEnabled()&&a.userPanningEnabled()){t.preventDefault(),e.data.bgActivePosistion=void 0,e.redrawHint(`select`,!0);var P=e.dragData.touchDragEles;if(P){e.redrawHint(`drag`,!0);for(var F=0;F0&&!e.hoverData.draggingEles&&!e.swipePanning&&e.data.bgActivePosistion!=null&&(e.data.bgActivePosistion=void 0,e.redrawHint(`select`,!0),e.redraw())}},!1);var ie;e.registerBinding(t,`touchcancel`,ie=function(t){var n=e.touchData.start;e.touchData.capture=!1,n&&n.unactivate()});var ae,oe,se,ce;if(e.registerBinding(t,`touchend`,ae=function(t){var r=e.touchData.start;if(e.touchData.capture)t.touches.length===0&&(e.touchData.capture=!1),t.preventDefault();else return;var a=e.selection;e.swipePanning=!1,e.hoverData.draggingEles=!1;var o=e.cy,s=o.zoom(),c=e.touchData.now,l=e.touchData.earlier;if(t.touches[0]){var u=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);c[0]=u[0],c[1]=u[1]}if(t.touches[1]){var u=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);c[2]=u[0],c[3]=u[1]}if(t.touches[2]){var u=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);c[4]=u[0],c[5]=u[1]}var d=function(e){return{originalEvent:t,type:e,position:{x:c[0],y:c[1]}}};r&&r.unactivate();var f;if(e.touchData.cxt){if(f=d(`cxttapend`),r?r.emit(f):o.emit(f),!e.touchData.cxtDragged){var p=d(`cxttap`);r?r.emit(p):o.emit(p)}e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxt=!1,e.touchData.start=null,e.redraw();return}if(!t.touches[2]&&o.boxSelectionEnabled()&&e.touchData.selecting){e.touchData.selecting=!1;var m=o.collection(e.getAllInBox(a[0],a[1],a[2],a[3]));a[0]=void 0,a[1]=void 0,a[2]=void 0,a[3]=void 0,a[4]=0,e.redrawHint(`select`,!0),o.emit(d(`boxend`)),m.emit(d(`box`)).stdFilter(function(e){return e.selectable()&&!e.selected()}).select().emit(d(`boxselect`)),m.nonempty()&&e.redrawHint(`eles`,!0),e.redraw()}if(r?.unactivate(),t.touches[2])e.data.bgActivePosistion=void 0,e.redrawHint(`select`,!0);else if(!t.touches[1]&&!t.touches[0]&&!t.touches[0]){e.data.bgActivePosistion=void 0,e.redrawHint(`select`,!0);var g=e.dragData.touchDragEles;if(r!=null){var _=r._private.grabbed;h(g),e.redrawHint(`drag`,!0),e.redrawHint(`eles`,!0),_&&(r.emit(d(`freeon`)),g.emit(d(`free`)),e.dragData.didDrag&&(r.emit(d(`dragfreeon`)),g.emit(d(`dragfree`)))),i(r,[`touchend`,`tapend`,`vmouseup`,`tapdragout`],t,{x:c[0],y:c[1]}),r.unactivate(),e.touchData.start=null}else i(e.findNearestElement(c[0],c[1],!0,!0),[`touchend`,`tapend`,`vmouseup`,`tapdragout`],t,{x:c[0],y:c[1]});var v=e.touchData.startPosition[0]-c[0],y=v*v,b=e.touchData.startPosition[1]-c[1],x=(y+b*b)*s*s;e.touchData.singleTouchMoved||(r||o.$(`:selected`).unselect([`tapunselect`]),i(r,[`tap`,`vclick`],t,{x:c[0],y:c[1]}),oe=!1,t.timeStamp-ce<=o.multiClickDebounceTime()?(se&&clearTimeout(se),oe=!0,ce=null,i(r,[`dbltap`,`vdblclick`],t,{x:c[0],y:c[1]})):(se=setTimeout(function(){oe||i(r,[`onetap`,`voneclick`],t,{x:c[0],y:c[1]})},o.multiClickDebounceTime()),ce=t.timeStamp)),r!=null&&!e.dragData.didDrag&&r._private.selectable&&x`u`){var X=[],le=function(e){return{clientX:e.clientX,clientY:e.clientY,force:1,identifier:e.pointerId,pageX:e.pageX,pageY:e.pageY,radiusX:e.width/2,radiusY:e.height/2,screenX:e.screenX,screenY:e.screenY,target:e.target}},ue=function(e){return{event:e,touch:le(e)}},de=function(e){X.push(ue(e))},fe=function(e){for(var t=0;t0)return l[0]}return null},p=Object.keys(d),m=0;m0?d:sr(i,a,e,t,n,r,o,s)},checkPoint:function(e,t,n,r,i,a,o,s){s=s===`auto`?jr(r,i):s;var c=2*s;if(hr(e,t,this.points,a,o,r,i-c,[0,-1],n)||hr(e,t,this.points,a,o,r-c,i,[0,-1],n))return!0;var l=r/2+2*n,u=i/2+2*n;return!!(mr(e,t,[a-l,o-u,a-l,o,a+l,o,a+l,o-u])||br(e,t,c,c,a+r/2-s,o+i/2-s,n)||br(e,t,c,c,a-r/2+s,o+i/2-s,n))}}},qf.registerNodeShapes=function(){var e=this.nodeShapes={},t=this;this.generateEllipse(),this.generatePolygon(`triangle`,Or(3,0)),this.generateRoundPolygon(`round-triangle`,Or(3,0)),this.generatePolygon(`rectangle`,Or(4,0)),e.square=e.rectangle,this.generateRoundRectangle(),this.generateCutRectangle(),this.generateBarrel(),this.generateBottomRoundrectangle();var n=[0,1,1,0,0,-1,-1,0];this.generatePolygon(`diamond`,n),this.generateRoundPolygon(`round-diamond`,n),this.generatePolygon(`pentagon`,Or(5,0)),this.generateRoundPolygon(`round-pentagon`,Or(5,0)),this.generatePolygon(`hexagon`,Or(6,0)),this.generateRoundPolygon(`round-hexagon`,Or(6,0)),this.generatePolygon(`heptagon`,Or(7,0)),this.generateRoundPolygon(`round-heptagon`,Or(7,0)),this.generatePolygon(`octagon`,Or(8,0)),this.generateRoundPolygon(`round-octagon`,Or(8,0));var r=Array(20),i=Ar(5,0),a=Ar(5,Math.PI/5),o=.5*(3-Math.sqrt(5));o*=1.57;for(var s=0;s=e.deqFastCost*h)break}else if(i){if(p>=e.deqCost*c||p>=e.deqAvgCost*s)break}else if(m>=e.deqNoDrawCost*Qf)break;var g=e.deq(t,d,u);if(g.length>0)for(var _=0;_0&&(e.onDeqd(t,l),!i&&e.shouldRedraw(t,l,d,u)&&r())},a=e.priority||It;n.beforeRender(i,a(t))}}}},ep=function(){function e(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Pt;r(this,e),this.idsByKey=new Qt,this.keyForId=new Qt,this.cachesByLvl=new Qt,this.lvls=[],this.getKey=t,this.doesEleInvalidateKey=n}return a(e,[{key:`getIdsFor`,value:function(e){e??Lt(`Can not get id list for null key`);var t=this.idsByKey,n=this.idsByKey.get(e);return n||(n=new tn,t.set(e,n)),n}},{key:`addIdForKey`,value:function(e,t){e!=null&&this.getIdsFor(e).add(t)}},{key:`deleteIdForKey`,value:function(e,t){e!=null&&this.getIdsFor(e).delete(t)}},{key:`getNumberOfIdsForKey`,value:function(e){return e==null?0:this.getIdsFor(e).size}},{key:`updateKeyMappingFor`,value:function(e){var t=e.id(),n=this.keyForId.get(t),r=this.getKey(e);this.deleteIdForKey(n,t),this.addIdForKey(r,t),this.keyForId.set(t,r)}},{key:`deleteKeyMappingFor`,value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteIdForKey(n,t),this.keyForId.delete(t)}},{key:`keyHasChangedFor`,value:function(e){var t=e.id();return this.keyForId.get(t)!==this.getKey(e)}},{key:`isInvalid`,value:function(e){return this.keyHasChangedFor(e)||this.doesEleInvalidateKey(e)}},{key:`getCachesAt`,value:function(e){var t=this.cachesByLvl,n=this.lvls,r=t.get(e);return r||(r=new Qt,t.set(e,r),n.push(e)),r}},{key:`getCache`,value:function(e,t){return this.getCachesAt(t).get(e)}},{key:`get`,value:function(e,t){var n=this.getKey(e),r=this.getCache(n,t);return r!=null&&this.updateKeyMappingFor(e),r}},{key:`getForCachedKey`,value:function(e,t){var n=this.keyForId.get(e.id());return this.getCache(n,t)}},{key:`hasCache`,value:function(e,t){return this.getCachesAt(t).has(e)}},{key:`has`,value:function(e,t){var n=this.getKey(e);return this.hasCache(n,t)}},{key:`setCache`,value:function(e,t,n){n.key=e,this.getCachesAt(t).set(e,n)}},{key:`set`,value:function(e,t,n){var r=this.getKey(e);this.setCache(r,t,n),this.updateKeyMappingFor(e)}},{key:`deleteCache`,value:function(e,t){this.getCachesAt(t).delete(e)}},{key:`delete`,value:function(e,t){var n=this.getKey(e);this.deleteCache(n,t)}},{key:`invalidateKey`,value:function(e){var t=this;this.lvls.forEach(function(n){return t.deleteCache(e,n)})}},{key:`invalidate`,value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteKeyMappingFor(e);var r=this.doesEleInvalidateKey(e);return r&&this.invalidateKey(n),r||this.getNumberOfIdsForKey(n)===0}}])}(),tp=25,np=50,rp=-4,ip=3,ap=7.99,op=8,sp=1024,cp=1024,lp=1024,up=.2,dp=.8,fp=10,pp=.15,mp=.1,hp=.9,gp=.9,_p=100,vp=1,yp={dequeue:`dequeue`,downscale:`downscale`,highQuality:`highQuality`},bp=Kt({getKey:null,doesEleInvalidateKey:Pt,drawElement:null,getBoundingBox:null,getRotationPoint:null,getRotationOffset:null,isVisible:Nt,allowEdgeTxrCaching:!0,allowParentTxrCaching:!0}),xp=function(e,t){var n=this;n.renderer=e,n.onDequeues=[];var r=bp(t);X(n,r),n.lookup=new ep(r.getKey,r.doesEleInvalidateKey),n.setupDequeueing()},Sp=xp.prototype;Sp.reasons=yp,Sp.getTextureQueue=function(e){var t=this;return t.eleImgCaches=t.eleImgCaches||{},t.eleImgCaches[e]=t.eleImgCaches[e]||[]},Sp.getRetiredTextureQueue=function(e){var t=this,n=t.eleImgCaches.retired=t.eleImgCaches.retired||{};return n[e]=n[e]||[]},Sp.getElementQueue=function(){var e=this;return e.eleCacheQueue=e.eleCacheQueue||new pn(function(e,t){return t.reqs-e.reqs})},Sp.getElementKeyToQueue=function(){var e=this;return e.eleKeyToCacheQueue=e.eleKeyToCacheQueue||{}},Sp.getElement=function(e,t,n,r,i){var a=this,o=this.renderer,s=o.cy.zoom(),c=this.lookup;if(!t||t.w===0||t.h===0||isNaN(t.w)||isNaN(t.h)||!e.visible()||e.removed()||!a.allowEdgeTxrCaching&&e.isEdge()||!a.allowParentTxrCaching&&e.isParent())return null;if(r??=Math.ceil(Ln(s*n)),r=ap||r>ip)return null;var l=2**r,u=t.h*l,d=t.w*l,f=o.eleTextBiggerThanMin(e,l);if(!this.isVisible(e,f))return null;var p=c.get(e,r);if(p&&p.invalidated&&(p.invalidated=!1,p.texture.invalidatedWidth-=p.width),p)return p;var m=u<=tp?tp:u<=np?np:Math.ceil(u/np)*np;if(u>lp||d>cp)return null;var h=a.getTextureQueue(m),g=h[h.length-2],_=function(){return a.recycleTexture(m,d)||a.addTexture(m,d)};g||=h[h.length-1],g||=_(),g.width-g.usedWidthr;D--)T=a.getElement(e,t,n,D,yp.downscale);E()}else return a.queueElement(e,S.level-1),S;else{var O;if(!y&&!b&&!x)for(var k=r-1;k>=rp;k--){var A=c.get(e,k);if(A){O=A;break}}if(v(O))return a.queueElement(e,r),O;g.context.translate(g.usedWidth,0),g.context.scale(l,l),this.drawElement(g.context,e,t,f,!1),g.context.scale(1/l,1/l),g.context.translate(-g.usedWidth,0)}return p={x:g.usedWidth,texture:g,level:r,scale:l,width:d,height:u,scaledLabelShown:f},g.usedWidth+=Math.ceil(d+op),g.eleCaches.push(p),c.set(e,r,p),a.checkTextureFullness(g),p},Sp.invalidateElements=function(e){for(var t=0;t=up*e.width&&this.retireTexture(e)},Sp.checkTextureFullness=function(e){var t=this.getTextureQueue(e.height);e.usedWidth/e.width>dp&&e.fullnessChecks>=fp?qt(t,e):e.fullnessChecks++},Sp.retireTexture=function(e){var t=this,n=e.height,r=t.getTextureQueue(n),i=this.lookup;qt(r,e),e.retired=!0;for(var a=e.eleCaches,o=0;o=t)return o.retired=!1,o.usedWidth=0,o.invalidatedWidth=0,o.fullnessChecks=0,Jt(o.eleCaches),o.context.setTransform(1,0,0,1,0,0),o.context.clearRect(0,0,o.width,o.height),qt(i,o),r.push(o),o}},Sp.queueElement=function(e,t){var n=this,r=n.getElementQueue(),i=n.getElementKeyToQueue(),a=this.getKey(e),o=i[a];if(o)o.level=Math.max(o.level,t),o.eles.merge(e),o.reqs++,r.updateItem(o);else{var s={eles:e.spawn().merge(e),level:t,reqs:1,key:a};r.push(s),i[a]=s}},Sp.dequeue=function(e){for(var t=this,n=t.getElementQueue(),r=t.getElementKeyToQueue(),i=[],a=t.lookup,o=0;o0;o++){var s=n.pop(),c=s.key,l=s.eles[0],u=a.hasCache(l,s.level);if(r[c]=null,!u){i.push(s);var d=t.getBoundingBox(l);t.getElement(l,d,e,s.level,yp.dequeue)}}return i},Sp.removeFromQueue=function(e){var t=this,n=t.getElementQueue(),r=t.getElementKeyToQueue(),i=this.getKey(e),a=r[i];a!=null&&(a.eles.length===1?(a.reqs=Mt,n.updateItem(a),n.pop(),r[i]=null):a.eles.unmerge(e))},Sp.onDequeue=function(e){this.onDequeues.push(e)},Sp.offDequeue=function(e){qt(this.onDequeues,e)},Sp.setupDequeueing=$f.setupDequeueing({deqRedrawThreshold:_p,deqCost:pp,deqAvgCost:mp,deqNoDrawCost:hp,deqFastCost:gp,deq:function(e,t,n){return e.dequeue(t,n)},onDeqd:function(e,t){for(var n=0;n=Ep||n>Tp)return null}r.validateLayersElesOrdering(n,e);var o=r.layersByLevel,s=2**n,c=o[n]=o[n]||[],l,u=r.levelIsComplete(n,e),d,f=function(){var t=function(t){if(r.validateLayersElesOrdering(t,e),r.levelIsComplete(t,e))return d=o[t],!0},i=function(e){if(!d)for(var r=n+e;wp<=r&&r<=Tp&&!t(r);r+=e);};i(1),i(-1);for(var a=c.length-1;a>=0;a--){var s=c[a];s.invalid&&qt(c,s)}};if(!u)f();else return c;var p=function(){if(!l){l=Kn();for(var t=0;tIp||a>Ip||i*a>Fp)return null;var o=r.makeLayer(l,n);if(t!=null){var u=c.indexOf(t)+1;c.splice(u,0,o)}else(e.insert===void 0||e.insert)&&c.unshift(o);return o};if(r.skipping&&!a)return null;for(var h=null,g=e.length/Cp,_=!a,v=0;v=g||!rr(h.bb,y.boundingBox()))&&(h=m({insert:!0,after:h}),!h))return null;d||_?r.queueLayer(h,y):r.drawEleInLayer(h,y,n,t),h.eles.push(y),x[n]=h}return d||(_?null:c)},zp.getEleLevelForLayerLevel=function(e,t){return e},zp.drawEleInLayer=function(e,t,n,r){var i=this,a=this.renderer,o=e.context,s=t.boundingBox();s.w===0||s.h===0||!t.visible()||(n=i.getEleLevelForLayerLevel(n,r),a.setImgSmoothing(o,!1),a.drawCachedElement(o,t,null,null,n,Lp),a.setImgSmoothing(o,!0))},zp.levelIsComplete=function(e,t){var n=this.layersByLevel[e];if(!n||n.length===0)return!1;for(var r=0,i=0;i0||a.invalid)return!1;r+=a.eles.length}return r===t.length},zp.validateLayersElesOrdering=function(e,t){var n=this.layersByLevel[e];if(n)for(var r=0;r0){t=!0;break}}return t},zp.invalidateElements=function(e){var t=this;e.length!==0&&(t.lastInvalidationTime=ft(),!(e.length===0||!t.haveLayers())&&t.updateElementsInLayers(e,function(e,n,r){t.invalidateLayer(e)}))},zp.invalidateLayer=function(e){if(this.lastInvalidationTime=ft(),!e.invalid){var t=e.level,n=e.eles,r=this.layersByLevel[t];qt(r,e),e.elesQueue=[],e.invalid=!0,e.replacement&&(e.replacement.invalid=!0);for(var i=0;i3&&arguments[3]!==void 0?arguments[3]:!0,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!0,o=this,s=t._private.rscratch;if(!(a&&!t.visible())&&!(s.badLine||s.allpts==null||isNaN(s.allpts[0]))){var c;n&&(c=n,e.translate(-c.x1,-c.y1));var l=a?t.pstyle(`opacity`).value:1,u=a?t.pstyle(`line-opacity`).value:1,d=t.pstyle(`curve-style`).value,f=t.pstyle(`line-style`).value,p=t.pstyle(`width`).pfValue,m=t.pstyle(`line-cap`).value,h=t.pstyle(`line-outline-width`).value,g=t.pstyle(`line-outline-color`).value,_=l*u,v=l*u,y=function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_;d===`straight-triangle`?(o.eleStrokeStyle(e,t,n),o.drawEdgeTrianglePath(t,e,s.allpts)):(e.lineWidth=p,e.lineCap=m,o.eleStrokeStyle(e,t,n),o.drawEdgePath(t,e,s.allpts,f),e.lineCap=`butt`)},b=function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_;if(e.lineWidth=p+h,e.lineCap=m,h>0)o.colorStrokeStyle(e,g[0],g[1],g[2],n);else{e.lineCap=`butt`;return}d===`straight-triangle`?o.drawEdgeTrianglePath(t,e,s.allpts):(o.drawEdgePath(t,e,s.allpts,f),e.lineCap=`butt`)},x=function(){i&&o.drawEdgeOverlay(e,t)},S=function(){i&&o.drawEdgeUnderlay(e,t)},C=function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:v;o.drawArrowheads(e,t,n)},w=function(){o.drawElementText(e,t,null,r)};if(e.lineJoin=`round`,t.pstyle(`ghost`).value===`yes`){var T=t.pstyle(`ghost-offset-x`).pfValue,E=t.pstyle(`ghost-offset-y`).pfValue,D=_*t.pstyle(`ghost-opacity`).value;e.translate(T,E),y(D),C(D),e.translate(-T,-E)}else b();S(),y(),C(),x(),w(),n&&e.translate(c.x1,c.y1)}};var rm=function(e){if(![`overlay`,`underlay`].includes(e))throw Error(`Invalid state`);return function(t,n){if(n.visible()){var r=n.pstyle(`${e}-opacity`).value;if(r!==0){var i=this,a=i.usePaths(),o=n._private.rscratch,s=2*n.pstyle(`${e}-padding`).pfValue,c=n.pstyle(`${e}-color`).value;t.lineWidth=s,o.edgeType===`self`&&!a?t.lineCap=`butt`:t.lineCap=`round`,i.colorStrokeStyle(t,c[0],c[1],c[2],r),i.drawEdgePath(n,t,o.allpts,`solid`)}}}};nm.drawEdgeOverlay=rm(`overlay`),nm.drawEdgeUnderlay=rm(`underlay`),nm.drawEdgePath=function(e,t,n,r){var i=e._private.rscratch,a=t,s,c=!1,l=this.usePaths(),u=e.pstyle(`line-dash-pattern`).pfValue,d=e.pstyle(`line-dash-offset`).pfValue;if(l){var f=n.join(`$`);i.pathCacheKey&&i.pathCacheKey===f?(s=t=i.pathCache,c=!0):(s=t=new Path2D,i.pathCacheKey=f,i.pathCache=s)}if(a.setLineDash)switch(r){case`dotted`:a.setLineDash([1,1]);break;case`dashed`:a.setLineDash(u),a.lineDashOffset=d;break;case`solid`:a.setLineDash([]);break}if(!c&&!i.badLine)switch(t.beginPath&&t.beginPath(),t.moveTo(n[0],n[1]),i.edgeType){case`bezier`:case`self`:case`compound`:case`multibezier`:for(var p=2;p+35&&arguments[5]!==void 0?arguments[5]:!0,o=this;if(r==null){if(a&&!o.eleTextBiggerThanMin(t))return}else if(r===!1)return;if(t.isNode()){var s=t.pstyle(`label`);if(!s||!s.value)return;var c=o.getLabelJustification(t),l=t.pstyle(`text-metrics`).strValue===`glyph`;e.textAlign=c,e.textBaseline=l?`alphabetic`:`bottom`}else{var u=t.element()._private.rscratch.badLine,d=t.pstyle(`label`),f=t.pstyle(`source-label`),p=t.pstyle(`target-label`);if(u||(!d||!d.value)&&(!f||!f.value)&&(!p||!p.value))return;e.textAlign=`center`,e.textBaseline=`bottom`}var m=!n,h;n&&(h=n,e.translate(-h.x1,-h.y1)),i==null?(o.drawText(e,t,null,m,a),t.isEdge()&&(o.drawText(e,t,`source`,m,a),o.drawText(e,t,`target`,m,a))):o.drawText(e,t,i,m,a),n&&e.translate(h.x1,h.y1)},am.getFontCache=function(e){var t;this.fontCaches=this.fontCaches||[];for(var n=0;n2&&arguments[2]!==void 0?arguments[2]:!0,r=t.pstyle(`font-style`).strValue,i=t.pstyle(`font-size`).pfValue+`px`,a=t.pstyle(`font-family`).strValue,o=t.pstyle(`font-weight`).strValue,s=n?t.effectiveOpacity()*t.pstyle(`text-opacity`).value:1,c=t.pstyle(`text-outline-opacity`).value*s,l=t.pstyle(`color`).value,u=t.pstyle(`text-outline-color`).value;e.font=r+` `+o+` `+i+` `+a,e.lineJoin=`round`,this.colorFillStyle(e,l[0],l[1],l[2],s),this.colorStrokeStyle(e,u[0],u[1],u[2],c)};function om(e,t,n,r,i){var a=Math.min(r,i)/2,o=t+r/2,s=n+i/2;e.beginPath(),e.arc(o,s,a,0,Math.PI*2),e.closePath()}function sm(e,t,n,r,i){var a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:5,o=Math.min(a,r/2,i/2);e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+r-o,n),e.quadraticCurveTo(t+r,n,t+r,n+o),e.lineTo(t+r,n+i-o),e.quadraticCurveTo(t+r,n+i,t+r-o,n+i),e.lineTo(t+o,n+i),e.quadraticCurveTo(t,n+i,t,n+i-o),e.lineTo(t,n+o),e.quadraticCurveTo(t,n,t+o,n),e.closePath()}am.getTextAngle=function(e,t){var n,r=e._private.rscratch,i=t?t+`-`:``,a=e.pstyle(i+`text-rotation`);if(a.strValue===`autorotate`){var o=Xt(r,`labelAngle`,t);n=e.isEdge()?o:0}else n=a.strValue===`none`?0:a.pfValue;return n},am.drawText=function(e,t,n){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,a=t._private.rscratch,o=i?t.effectiveOpacity():1;if(!(i&&(o===0||t.pstyle(`text-opacity`).value===0))){n===`main`&&(n=null);var s=Xt(a,`labelX`,n),c=Xt(a,`labelY`,n),l,u,d=this.getLabelText(t,n);if(d!=null&&d!==``&&!isNaN(s)&&!isNaN(c)){this.setupTextStyle(e,t,i);var f=n?n+`-`:``,p=Xt(a,`labelWidth`,n),m=Xt(a,`labelHeight`,n),h=Xt(a,`labelActualDescent`,n),g=t.pstyle(f+`text-margin-x`).pfValue,_=t.pstyle(f+`text-margin-y`).pfValue,v=t.isEdge(),y=t.pstyle(`text-halign`).value,b=t.pstyle(`text-valign`).value;v&&(y=`center`,b=`center`),s+=g,c+=_;var x=r?this.getTextAngle(t,n):0;x!==0&&(l=s,u=c,e.translate(l,u),e.rotate(x),s=0,c=0);var S=tl(y),C=nl(b);switch(C){case`top`:break;case`center`:c+=m/2;break;case`bottom`:c+=m;break}var w=t.pstyle(`text-background-opacity`).value,T=t.pstyle(`text-border-opacity`).value,E=t.pstyle(`text-border-width`).pfValue,D=t.pstyle(`text-background-padding`).pfValue,O=t.pstyle(`text-background-shape`).strValue,k=O===`round-rectangle`||O===`roundrectangle`,A=O===`circle`,j=2;if(w>0||E>0&&T>0){var M=e.fillStyle,N=e.strokeStyle,P=e.lineWidth,F=t.pstyle(`text-background-color`).value,I=t.pstyle(`text-border-color`).value,L=t.pstyle(`text-border-style`).value,R=w>0,z=E>0&&T>0,B=s-D;switch(S){case`left`:B-=p;break;case`center`:B-=p/2;break}var V=c-m-D,H=p+2*D,U=m+2*D;if(R&&(e.fillStyle=`rgba(${F[0]},${F[1]},${F[2]},${w*o})`),z&&(e.strokeStyle=`rgba(${I[0]},${I[1]},${I[2]},${T*o})`,e.lineWidth=E,e.setLineDash))switch(L){case`dotted`:e.setLineDash([1,1]);break;case`dashed`:e.setLineDash([4,2]);break;case`double`:e.lineWidth=E/4,e.setLineDash([]);break;default:e.setLineDash([]);break}if(k?(e.beginPath(),sm(e,B,V,H,U,j)):A?(e.beginPath(),om(e,B,V,H,U)):(e.beginPath(),e.rect(B,V,H,U)),R&&e.fill(),z&&e.stroke(),z&&L===`double`){var W=E/2;e.beginPath(),k?sm(e,B+W,V+W,H-2*W,U-2*W,j):e.rect(B+W,V+W,H-2*W,U-2*W),e.stroke()}e.fillStyle=M,e.strokeStyle=N,e.lineWidth=P,e.setLineDash&&e.setLineDash([])}var G=2*t.pstyle(`text-outline-width`).pfValue;if(G>0&&(e.lineWidth=G),c-=h,t.pstyle(`text-wrap`).value===`wrap`){var K=Xt(a,`labelWrapCachedLines`,n),q=Xt(a,`labelLineHeight`,n),J=p/2,ee=this.getLabelJustification(t);switch(ee===`auto`||(S===`left`?ee===`left`?s+=-p:ee===`center`&&(s+=-J):S===`center`?ee===`left`?s+=-J:ee===`right`&&(s+=J):S===`right`&&(ee===`center`?s+=J:ee===`right`&&(s+=p))),C){case`top`:c-=(K.length-1)*q;break;case`center`:case`bottom`:c-=(K.length-1)*q;break}for(var Y=0;Y0&&e.strokeText(K[Y],s,c),e.fillText(K[Y],s,c),c+=q}else G>0&&e.strokeText(d,s,c),e.fillText(d,s,c);x!==0&&(e.rotate(-x),e.translate(-l,-u))}}};var cm={};cm.drawNode=function(e,t,n){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!0,o=this,s,c,l=t._private,u=l.rscratch,d=t.position();if(!(!A(d.x)||!A(d.y))&&!(a&&!t.visible())){var f=a?t.effectiveOpacity():1,p=o.usePaths(),m,h=!1,g=t.padding();s=t.width()+2*g,c=t.height()+2*g;var _;n&&(_=n,e.translate(-_.x1,-_.y1));for(var v=t.pstyle(`background-image`).value,y=Array(v.length),b=Array(v.length),x=0,S=0;S0&&arguments[0]!==void 0?arguments[0]:D;o.eleFillStyle(e,t,n)},W=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:I;o.colorStrokeStyle(e,O[0],O[1],O[2],t)},G=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:B;o.colorStrokeStyle(e,R[0],R[1],R[2],t)},K=function(e,t,n,r){var i=o.nodePathCache=o.nodePathCache||[],a=wt(n===`polygon`?n+`,`+r.join(`,`):n,``+t,``+e,``+H),s=i[a],c,l=!1;return s==null?(c=new Path2D,i[a]=u.pathCache=c):(c=s,l=!0,u.pathCache=c),{path:c,cacheHit:l}},q=t.pstyle(`shape`).strValue,J=t.pstyle(`shape-polygon-points`).pfValue;if(p){e.translate(d.x,d.y);var ee=K(s,c,q,J);m=ee.path,h=ee.cacheHit}var Y=function(){if(!h){var n=d;p&&(n={x:0,y:0}),o.nodeShapes[o.getNodeShape(t)].draw(m||e,n.x,n.y,s,c,H,u)}p?e.fill(m):e.fill()},te=function(){for(var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:f,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,i=l.backgrounding,a=0,s=0;s0&&arguments[0]!==void 0&&arguments[0],r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:f;o.hasPie(t)&&(o.drawPie(e,t,r),n&&(p||o.nodeShapes[o.getNodeShape(t)].draw(e,d.x,d.y,s,c,H,u)))},re=function(){var n=arguments.length>0&&arguments[0]!==void 0&&arguments[0],r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:f;o.hasStripe(t)&&(e.save(),p?e.clip(u.pathCache):(o.nodeShapes[o.getNodeShape(t)].draw(e,d.x,d.y,s,c,H,u),e.clip()),o.drawStripe(e,t,r),e.restore(),n&&(p||o.nodeShapes[o.getNodeShape(t)].draw(e,d.x,d.y,s,c,H,u)))},ie=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:f,n=(T>0?T:-T)*t,r=T>0?0:255;T!==0&&(o.colorFillStyle(e,r,r,r,n),p?e.fill(m):e.fill())},ae=function(){if(E>0){if(e.lineWidth=E,e.lineCap=M,e.lineJoin=j,e.setLineDash)switch(k){case`dotted`:e.setLineDash([1,1]);break;case`dashed`:e.setLineDash(P),e.lineDashOffset=F;break;case`solid`:case`double`:e.setLineDash([]);break}if(N!==`center`){if(e.save(),e.lineWidth*=2,N===`inside`)p?e.clip(m):e.clip();else{var t=new Path2D;t.rect(-s/2-E,-c/2-E,s+2*E,c+2*E),t.addPath(m),e.clip(t,`evenodd`)}p?e.stroke(m):e.stroke(),e.restore()}else p?e.stroke(m):e.stroke();if(k===`double`){e.lineWidth=E/3;var n=e.globalCompositeOperation;e.globalCompositeOperation=`destination-out`,p?e.stroke(m):e.stroke(),e.globalCompositeOperation=n}e.setLineDash&&e.setLineDash([])}},oe=function(){if(L>0){if(e.lineWidth=L,e.lineCap=`butt`,e.setLineDash)switch(z){case`dotted`:e.setLineDash([1,1]);break;case`dashed`:e.setLineDash([4,2]);break;case`solid`:case`double`:e.setLineDash([]);break}var n=d;p&&(n={x:0,y:0});var r=o.getNodeShape(t),i=E;N===`inside`&&(i=0),N===`outside`&&(i*=2);var a=(s+i+(L+V))/s,l=(c+i+(L+V))/c,u=s*a,f=c*l,m=o.nodeShapes[r].points,h;if(p&&(h=K(u,f,r,m).path),r===`ellipse`)o.drawEllipsePath(h||e,n.x,n.y,u,f);else if([`round-diamond`,`round-heptagon`,`round-hexagon`,`round-octagon`,`round-pentagon`,`round-polygon`,`round-triangle`,`round-tag`].includes(r)){var g=0,_=0,v=0;r===`round-diamond`?g=(i+V+L)*1.4:r===`round-heptagon`?(g=(i+V+L)*1.075,v=-(i/2+V+L)/35):r===`round-hexagon`?g=(i+V+L)*1.12:r===`round-pentagon`?(g=(i+V+L)*1.13,v=-(i/2+V+L)/15):r===`round-tag`?(g=(i+V+L)*1.12,_=(i/2+L+V)*.07):r===`round-triangle`&&(g=(i+V+L)*(Math.PI/2),v=-(i+V/2+L)/Math.PI),g!==0&&(a=(s+g)/s,u=s*a,[`round-hexagon`,`round-tag`].includes(r)||(l=(c+g)/c,f=c*l)),H=H===`auto`?Mr(u,f):H;for(var y=u/2,b=f/2,x=H+(i+L+V)/2,S=Array(m.length/2),C=Array(m.length/2),w=0;w0){if(r||=n.position(),i==null||a==null){var f=n.padding();i=n.width()+2*f,a=n.height()+2*f}o.colorFillStyle(t,l[0],l[1],l[2],c),o.nodeShapes[u].draw(t,r.x,r.y,i+s*2,a+s*2,d),t.fill()}}}};cm.drawNodeOverlay=lm(`overlay`),cm.drawNodeUnderlay=lm(`underlay`),cm.hasPie=function(e){return e=e[0],e._private.hasPie},cm.hasStripe=function(e){return e=e[0],e._private.hasStripe},cm.drawPie=function(e,t,n,r){t=t[0],r||=t.position();var i=t.cy().style(),a=t.pstyle(`pie-size`),o=t.pstyle(`pie-hole`),s=t.pstyle(`pie-start-angle`).pfValue,c=r.x,l=r.y,u=t.width(),d=t.height(),f=Math.min(u,d)/2,p,m=0;if(this.usePaths()&&(c=0,l=0),a.units===`%`?f*=a.pfValue:a.pfValue!==void 0&&(f=a.pfValue/2),o.units===`%`?p=f*o.pfValue:o.pfValue!==void 0&&(p=o.pfValue/2),!(p>=f))for(var h=1;h<=i.pieBackgroundN;h++){var g=t.pstyle(`pie-`+h+`-background-size`).value,_=t.pstyle(`pie-`+h+`-background-color`).value,v=t.pstyle(`pie-`+h+`-background-opacity`).value*n,y=g/100;y+m>1&&(y=1-m);var b=1.5*Math.PI+2*Math.PI*m;b+=s;var x=2*Math.PI*y,S=b+x;g===0||m>=1||m+y>1||(p===0?(e.beginPath(),e.moveTo(c,l),e.arc(c,l,f,b,S),e.closePath()):(e.beginPath(),e.arc(c,l,f,b,S),e.arc(c,l,p,S,b,!0),e.closePath()),this.colorFillStyle(e,_[0],_[1],_[2],v),e.fill(),m+=y)}},cm.drawStripe=function(e,t,n,r){t=t[0],r||=t.position();var i=t.cy().style(),a=r.x,o=r.y,s=t.width(),c=t.height(),l=0,u=this.usePaths();e.save();var d=t.pstyle(`stripe-direction`).value,f=t.pstyle(`stripe-size`);switch(d){case`vertical`:break;case`righward`:e.rotate(-Math.PI/2);break}var p=s,m=c;f.units===`%`?(p*=f.pfValue,m*=f.pfValue):f.pfValue!==void 0&&(p=f.pfValue,m=f.pfValue),u&&(a=0,o=0),o-=p/2,a-=m/2;for(var h=1;h<=i.stripeBackgroundN;h++){var g=t.pstyle(`stripe-`+h+`-background-size`).value,_=t.pstyle(`stripe-`+h+`-background-color`).value,v=t.pstyle(`stripe-`+h+`-background-opacity`).value*n,y=g/100;y+l>1&&(y=1-l),!(g===0||l>=1||l+y>1)&&(e.beginPath(),e.rect(a,o+m*l,p,m*y),e.closePath(),this.colorFillStyle(e,_[0],_[1],_[2],v),e.fill(),l+=y)}e.restore()};var um={},dm=100;um.getPixelRatio=function(){var e=this.data.contexts[0];if(this.forcedPixelRatio!=null)return this.forcedPixelRatio;var t=this.cy.window(),n=e.backingStorePixelRatio||e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return(t.devicePixelRatio||1)/n},um.paintCache=function(e){for(var t=this.paintCaches=this.paintCaches||[],n=!0,r,i=0;it.minMbLowQualFrames&&(t.motionBlurPxRatio=t.mbPxRBlurry)),t.clearingMotionBlur&&(t.motionBlurPxRatio=1),t.textureDrawLastFrame&&!d&&(u[t.NODE]=!0,u[t.SELECT_BOX]=!0);var v=n.style(),y=n.zoom(),b=o===void 0?y:o,x=n.pan(),S={x:x.x,y:x.y},C={zoom:y,pan:{x:x.x,y:x.y}},w=t.prevViewport;!(w===void 0||C.zoom!==w.zoom||C.pan.x!==w.pan.x||C.pan.y!==w.pan.y)&&!(h&&!m)&&(t.motionBlurPxRatio=1),s&&(S=s),b*=c,S.x*=c,S.y*=c;var T=t.getCachedZSortedEles();function E(e,n,r,i,a){var o=e.globalCompositeOperation;e.globalCompositeOperation=`destination-out`,t.colorFillStyle(e,255,255,255,t.motionBlurTransparency),e.fillRect(n,r,i,a),e.globalCompositeOperation=o}function D(e,n){var a,c,u,d;!t.clearingMotionBlur&&(e===l.bufferContexts[t.MOTIONBLUR_BUFFER_NODE]||e===l.bufferContexts[t.MOTIONBLUR_BUFFER_DRAG])?(a={x:x.x*p,y:x.y*p},c=y*p,u=t.canvasWidth*p,d=t.canvasHeight*p):(a=S,c=b,u=t.canvasWidth,d=t.canvasHeight),e.setTransform(1,0,0,1,0,0),n===`motionBlur`?E(e,0,0,u,d):!r&&(n===void 0||n)&&e.clearRect(0,0,u,d),i||(e.translate(a.x,a.y),e.scale(c,c)),s&&e.translate(s.x,s.y),o&&e.scale(o,o)}if(d||(t.textureDrawLastFrame=!1),d){if(t.textureDrawLastFrame=!0,!t.textureCache){t.textureCache={},t.textureCache.bb=n.mutableElements().boundingBox(),t.textureCache.texture=t.data.bufferCanvases[t.TEXTURE_BUFFER];var O=t.data.bufferContexts[t.TEXTURE_BUFFER];O.setTransform(1,0,0,1,0,0),O.clearRect(0,0,t.canvasWidth*t.textureMult,t.canvasHeight*t.textureMult),t.render({forcedContext:O,drawOnlyNodeLayer:!0,forcedPxRatio:c*t.textureMult});var C=t.textureCache.viewport={zoom:n.zoom(),pan:n.pan(),width:t.canvasWidth,height:t.canvasHeight};C.mpan={x:(0-C.pan.x)/C.zoom,y:(0-C.pan.y)/C.zoom}}u[t.DRAG]=!1,u[t.NODE]=!1;var k=l.contexts[t.NODE],A=t.textureCache.texture,C=t.textureCache.viewport;k.setTransform(1,0,0,1,0,0),f?E(k,0,0,C.width,C.height):k.clearRect(0,0,C.width,C.height);var j=v.core(`outside-texture-bg-color`).value,M=v.core(`outside-texture-bg-opacity`).value;t.colorFillStyle(k,j[0],j[1],j[2],M),k.fillRect(0,0,C.width,C.height);var y=n.zoom();D(k,!1),k.clearRect(C.mpan.x,C.mpan.y,C.width/C.zoom/c,C.height/C.zoom/c),k.drawImage(A,C.mpan.x,C.mpan.y,C.width/C.zoom/c,C.height/C.zoom/c)}else t.textureOnViewport&&!r&&(t.textureCache=null);var N=n.extent(),P=t.pinching||t.hoverData.dragging||t.swipePanning||t.data.wheelZooming||t.hoverData.draggingEles||t.cy.animated(),F=t.hideEdgesOnViewport&&P,I=[];if(I[t.NODE]=!u[t.NODE]&&f&&!t.clearedForMotionBlur[t.NODE]||t.clearingMotionBlur,I[t.NODE]&&(t.clearedForMotionBlur[t.NODE]=!0),I[t.DRAG]=!u[t.DRAG]&&f&&!t.clearedForMotionBlur[t.DRAG]||t.clearingMotionBlur,I[t.DRAG]&&(t.clearedForMotionBlur[t.DRAG]=!0),u[t.NODE]||i||a||I[t.NODE]){var L=f&&!I[t.NODE]&&p!==1,k=r||(L?t.data.bufferContexts[t.MOTIONBLUR_BUFFER_NODE]:l.contexts[t.NODE]);D(k,f&&!L?`motionBlur`:void 0),F?t.drawCachedNodes(k,T.nondrag,c,N):t.drawLayeredElements(k,T.nondrag,c,N),t.debug&&t.drawDebugPoints(k,T.nondrag),!i&&!f&&(u[t.NODE]=!1)}if(!a&&(u[t.DRAG]||i||I[t.DRAG])){var L=f&&!I[t.DRAG]&&p!==1,k=r||(L?t.data.bufferContexts[t.MOTIONBLUR_BUFFER_DRAG]:l.contexts[t.DRAG]);D(k,f&&!L?`motionBlur`:void 0),F?t.drawCachedNodes(k,T.drag,c,N):t.drawCachedElements(k,T.drag,c,N),t.debug&&t.drawDebugPoints(k,T.drag),!i&&!f&&(u[t.DRAG]=!1)}if(this.drawSelectionRectangle(e,D),f&&p!==1){var R=l.contexts[t.NODE],z=t.data.bufferCanvases[t.MOTIONBLUR_BUFFER_NODE],B=l.contexts[t.DRAG],V=t.data.bufferCanvases[t.MOTIONBLUR_BUFFER_DRAG],H=function(e,n,r){e.setTransform(1,0,0,1,0,0),r||!_?e.clearRect(0,0,t.canvasWidth,t.canvasHeight):E(e,0,0,t.canvasWidth,t.canvasHeight);var i=p;e.drawImage(n,0,0,t.canvasWidth*i,t.canvasHeight*i,0,0,t.canvasWidth,t.canvasHeight)};(u[t.NODE]||I[t.NODE])&&(H(R,z,I[t.NODE]),u[t.NODE]=!1),(u[t.DRAG]||I[t.DRAG])&&(H(B,V,I[t.DRAG]),u[t.DRAG]=!1)}t.prevViewport=C,t.clearingMotionBlur&&(t.clearingMotionBlur=!1,t.motionBlurCleared=!0,t.motionBlur=!0),f&&(t.motionBlurTimeout=setTimeout(function(){t.motionBlurTimeout=null,t.clearedForMotionBlur[t.NODE]=!1,t.clearedForMotionBlur[t.DRAG]=!1,t.motionBlur=!1,t.clearingMotionBlur=!d,t.mbFrames=0,u[t.NODE]=!0,u[t.DRAG]=!0,t.redraw()},dm)),r||n.emit(`render`)};var fm;um.drawSelectionRectangle=function(e,t){var n=this,r=n.cy,i=n.data,a=r.style(),o=e.drawOnlyNodeLayer,s=e.drawAllLayers,c=i.canvasNeedsRedraw,l=e.forcedContext;if(n.showFps||!o&&c[n.SELECT_BOX]&&!s){var u=l||i.contexts[n.SELECT_BOX];if(t(u),n.selection[4]==1&&(n.hoverData.selecting||n.touchData.selecting)){var d=n.cy.zoom(),f=a.core(`selection-box-border-width`).value/d;u.lineWidth=f,u.fillStyle=`rgba(`+a.core(`selection-box-color`).value[0]+`,`+a.core(`selection-box-color`).value[1]+`,`+a.core(`selection-box-color`).value[2]+`,`+a.core(`selection-box-opacity`).value+`)`,u.fillRect(n.selection[0],n.selection[1],n.selection[2]-n.selection[0],n.selection[3]-n.selection[1]),f>0&&(u.strokeStyle=`rgba(`+a.core(`selection-box-border-color`).value[0]+`,`+a.core(`selection-box-border-color`).value[1]+`,`+a.core(`selection-box-border-color`).value[2]+`,`+a.core(`selection-box-opacity`).value+`)`,u.strokeRect(n.selection[0],n.selection[1],n.selection[2]-n.selection[0],n.selection[3]-n.selection[1]))}if(i.bgActivePosistion&&!n.hoverData.selecting){var d=n.cy.zoom(),p=i.bgActivePosistion;u.fillStyle=`rgba(`+a.core(`active-bg-color`).value[0]+`,`+a.core(`active-bg-color`).value[1]+`,`+a.core(`active-bg-color`).value[2]+`,`+a.core(`active-bg-opacity`).value+`)`,u.beginPath(),u.arc(p.x,p.y,a.core(`active-bg-size`).pfValue/d,0,2*Math.PI),u.fill()}var m=n.lastRedrawTime;if(n.showFps&&m){m=Math.round(m);var h=Math.round(1e3/m),g=`1 frame = `+m+` ms = `+h+` fps`;u.setTransform(1,0,0,1,0,0),u.fillStyle=`rgba(255, 0, 0, 0.75)`,u.strokeStyle=`rgba(255, 0, 0, 0.75)`,u.font=`30px Arial`,fm||=u.measureText(g).actualBoundingBoxAscent,u.fillText(g,0,fm),u.strokeRect(0,fm+10,250,20),u.fillRect(0,fm+10,250*Math.min(h/60,1),20)}s||(c[n.SELECT_BOX]=!1)}};function pm(e,t,n){var r=e.createShader(t);if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw Error(e.getShaderInfoLog(r));return r}function mm(e,t,n){var r=pm(e,e.VERTEX_SHADER,t),i=pm(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(e.attachShader(a,r),e.attachShader(a,i),e.linkProgram(a),!e.getProgramParameter(a,e.LINK_STATUS))throw Error(`Could not initialize shaders`);return a}function hm(e,t,n){n===void 0&&(n=t);var r=e.makeOffscreenCanvas(t,n),i=r.context=r.getContext(`2d`);return r.clear=function(){return i.clearRect(0,0,r.width,r.height)},r.clear(),r}function gm(e){var t=e.pixelRatio,n=e.cy.zoom(),r=e.cy.pan();return{zoom:n*t,pan:{x:r.x*t,y:r.y*t}}}function _m(e){var t=e.pixelRatio;return e.cy.zoom()*t}function vm(e,t,n,r,i){var a=r*n+t.x,o=i*n+t.y;return o=Math.round(e.canvasHeight-o),[a,o]}function ym(e,t){return t.picking?!0:e.pstyle(`background-fill`).value!==`solid`||e.pstyle(`background-image`).strValue!==`none`?!1:e.pstyle(`border-width`).value===0||e.pstyle(`border-opacity`).value===0||e.pstyle(`border-style`).value===`solid`}function bm(e,t){if(e.length!==t.length)return!1;for(var n=0;n>0&255)/255,n[1]=(e>>8&255)/255,n[2]=(e>>16&255)/255,n[3]=(e>>24&255)/255,n}function Cm(e){return e[0]+(e[1]<<8)+(e[2]<<16)+(e[3]<<24)}function wm(e,t){var n=e.createTexture();return n.buffer=function(t){e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR_MIPMAP_NEAREST),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.generateMipmap(e.TEXTURE_2D),e.bindTexture(e.TEXTURE_2D,null)},n.deleteTexture=function(){e.deleteTexture(n)},n}function Tm(e,t){switch(t){case`float`:return[1,e.FLOAT,4];case`vec2`:return[2,e.FLOAT,4];case`vec3`:return[3,e.FLOAT,4];case`vec4`:return[4,e.FLOAT,4];case`int`:return[1,e.INT,4];case`ivec2`:return[2,e.INT,4]}}function Em(e,t,n){switch(t){case e.FLOAT:return new Float32Array(n);case e.INT:return new Int32Array(n)}}function Dm(e,t,n,r,i,a){switch(t){case e.FLOAT:return new Float32Array(n.buffer,a*r,i);case e.INT:return new Int32Array(n.buffer,a*r,i)}}function Om(e,t,n,r){var i=f(Tm(e,t),2),a=i[0],o=i[1],s=Em(e,o,r),c=e.createBuffer();return e.bindBuffer(e.ARRAY_BUFFER,c),e.bufferData(e.ARRAY_BUFFER,s,e.STATIC_DRAW),o===e.FLOAT?e.vertexAttribPointer(n,a,o,!1,0,0):o===e.INT&&e.vertexAttribIPointer(n,a,o,0,0),e.enableVertexAttribArray(n),e.bindBuffer(e.ARRAY_BUFFER,null),c}function km(e,t,n,r){var i=f(Tm(e,n),3),a=i[0],o=i[1],s=i[2],c=Em(e,o,t*a),l=a*s,u=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,u),e.bufferData(e.ARRAY_BUFFER,t*l,e.DYNAMIC_DRAW),e.enableVertexAttribArray(r),o===e.FLOAT?e.vertexAttribPointer(r,a,o,!1,l,0):o===e.INT&&e.vertexAttribIPointer(r,a,o,l,0),e.vertexAttribDivisor(r,1),e.bindBuffer(e.ARRAY_BUFFER,null);for(var d=Array(t),p=0;pi&&(a=i/t,o=t*a,s=n*a),{scale:a,texW:o,texH:s}}},{key:`draw`,value:function(e,t,n){var r=this;if(this.locked)throw Error(`can't draw, atlas is locked`);var i=this.texSize,a=this.texRows,o=this.texHeight,s=this.getScale(t),c=s.scale,l=s.texW,u=s.texH,d=function(e,r){if(n&&r){var i=r.context,a=e.x,s=e.row,l=a,u=o*s;i.save(),i.translate(l,u),i.scale(c,c),n(i,t),i.restore()}},f=[null,null],p=function(){d(r.freePointer,r.canvas),f[0]={x:r.freePointer.x,y:r.freePointer.row*o,w:l,h:u},f[1]={x:r.freePointer.x+l,y:r.freePointer.row*o,w:0,h:u},r.freePointer.x+=l,r.freePointer.x==i&&(r.freePointer.x=0,r.freePointer.row++)},m=function(){var e=r.scratch,t=r.canvas;e.clear(),d({x:0,row:0},e);var n=i-r.freePointer.x,a=l-n,s=o,c=r.freePointer.x,p=r.freePointer.row*o,m=n;t.context.drawImage(e,0,0,m,s,c,p,m,s),f[0]={x:c,y:p,w:m,h:u};var h=n,g=(r.freePointer.row+1)*o,_=a;t&&t.context.drawImage(e,h,0,_,s,0,g,_,s),f[1]={x:0,y:g,w:_,h:u},r.freePointer.x=a,r.freePointer.row++},h=function(){r.freePointer.x=0,r.freePointer.row++};if(this.freePointer.x+l<=i)p();else if(this.freePointer.row>=a-1)return!1;else this.freePointer.x===i?(h(),p()):this.enableWrapping?m():(h(),p());return this.keyToLocation.set(e,f),this.needsBuffer=!0,f}},{key:`getOffsets`,value:function(e){return this.keyToLocation.get(e)}},{key:`isEmpty`,value:function(){return this.freePointer.x===0&&this.freePointer.row===0}},{key:`canFit`,value:function(e){if(this.locked)return!1;var t=this.texSize,n=this.texRows,r=this.getScale(e).texW;return this.freePointer.x+r>t?this.freePointer.row1&&arguments[1]!==void 0?arguments[1]:{},r=n.forceRedraw,i=r!==void 0&&r,a=n.filterEle,s=a===void 0?function(){return!0}:a,c=n.filterType,l=c===void 0?function(){return!0}:c,u=!1,d=!1,f=o(e),p;try{for(f.s();!(p=f.n()).done;){var m=p.value;if(s(m)){var h=o(this.renderTypes.values()),g;try{var _=function(){var e=g.value,n=e.type;if(l(n)){var r=t.collections.get(e.collection),a=e.getKey(m),o=Array.isArray(a)?a:[a];if(i)o.forEach(function(e){return r.markKeyForGC(e)}),d=!0;else{var s=e.getID?e.getID(m):m.id(),c=t._key(n,s),f=t.typeAndIdToKey.get(c);f!==void 0&&!bm(o,f)&&(u=!0,t.typeAndIdToKey.delete(c),f.forEach(function(e){return r.markKeyForGC(e)}))}}};for(h.s();!(g=h.n()).done;)_()}catch(e){h.e(e)}finally{h.f()}}}}catch(e){f.e(e)}finally{f.f()}return d&&(this.gc(),u=!1),u}},{key:`gc`,value:function(){var e=o(this.collections.values()),t;try{for(e.s();!(t=e.n()).done;)t.value.gc()}catch(t){e.e(t)}finally{e.f()}}},{key:`getOrCreateAtlas`,value:function(e,t,n,r){var i=this.renderTypes.get(t),a=this.collections.get(i.collection),o=!1,s=a.draw(r,n,function(t){i.drawClipped?(t.save(),t.beginPath(),t.rect(0,0,n.w,n.h),t.clip(),i.drawElement(t,e,n,!0,!0),t.restore()):i.drawElement(t,e,n,!0,!0),o=!0});if(o){var c=i.getID?i.getID(e):e.id(),l=this._key(t,c);this.typeAndIdToKey.has(l)?this.typeAndIdToKey.get(l).push(r):this.typeAndIdToKey.set(l,[r])}return s}},{key:`getAtlasInfo`,value:function(e,t){var n=this,r=this.renderTypes.get(t),i=r.getKey(e);return(Array.isArray(i)?i:[i]).map(function(i){var a=r.getBoundingBox(e,i),o=n.getOrCreateAtlas(e,t,a,i),s=f(o.getOffsets(i),2),c=s[0];return{atlas:o,tex:c,tex1:c,tex2:s[1],bb:a}})}},{key:`getDebugInfo`,value:function(){var e=[],t=o(this.collections),n;try{for(t.s();!(n=t.n()).done;){var r=f(n.value,2),i=r[0],a=r[1].getCounts(),s=a.keyCount,c=a.atlasCount;e.push({type:i,keyCount:s,atlasCount:c})}}catch(e){t.e(e)}finally{t.f()}return e}}])}(),Wm=function(){function e(t){r(this,e),this.globalOptions=t,this.atlasSize=t.webglTexSize,this.maxAtlasesPerBatch=t.webglTexPerBatch,this.batchAtlases=[]}return a(e,[{key:`getMaxAtlasesPerBatch`,value:function(){return this.maxAtlasesPerBatch}},{key:`getAtlasSize`,value:function(){return this.atlasSize}},{key:`getIndexArray`,value:function(){return Array.from({length:this.maxAtlasesPerBatch},function(e,t){return t})}},{key:`startBatch`,value:function(){this.batchAtlases=[]}},{key:`getAtlasCount`,value:function(){return this.batchAtlases.length}},{key:`getAtlases`,value:function(){return this.batchAtlases}},{key:`canAddToCurrentBatch`,value:function(e){return this.batchAtlases.length!==this.maxAtlasesPerBatch||this.batchAtlases.includes(e)}},{key:`getAtlasIndexForBatch`,value:function(e){var t=this.batchAtlases.indexOf(e);if(t<0){if(this.batchAtlases.length===this.maxAtlasesPerBatch)throw Error(`cannot add more atlases to batch`);this.batchAtlases.push(e),t=this.batchAtlases.length-1}return t}}])}(),Gm=` + float circleSD(vec2 p, float r) { + return distance(vec2(0), p) - r; // signed distance + } +`,Km=` + float rectangleSD(vec2 p, vec2 b) { + vec2 d = abs(p)-b; + return distance(vec2(0),max(d,0.0)) + min(max(d.x,d.y),0.0); + } +`,qm=` + float roundRectangleSD(vec2 p, vec2 b, vec4 cr) { + cr.xy = (p.x > 0.0) ? cr.xy : cr.zw; + cr.x = (p.y > 0.0) ? cr.x : cr.y; + vec2 q = abs(p) - b + cr.x; + return min(max(q.x, q.y), 0.0) + distance(vec2(0), max(q, 0.0)) - cr.x; + } +`,Jm=` + float ellipseSD(vec2 p, vec2 ab) { + p = abs( p ); // symmetry + + // find root with Newton solver + vec2 q = ab*(p-ab); + float w = (q.x1.0) ? d : -d; + } +`,Ym={SCREEN:{name:`screen`,screen:!0},PICKING:{name:`picking`,picking:!0}},Xm={IGNORE:1,USE_BB:2},Zm=0,Qm=1,$m=2,eh=3,th=4,nh=5,rh=6,ih=7,ah=function(){function e(t,n,i){r(this,e),this.r=t,this.gl=n,this.maxInstances=i.webglBatchSize,this.atlasSize=i.webglTexSize,this.bgColor=i.bgColor,this.debug=i.webglDebug,this.batchDebugInfo=[],i.enableWrapping=!0,i.createTextureCanvas=hm,this.atlasManager=new Um(t,i),this.batchManager=new Wm(i),this.simpleShapeOptions=new Map,this.program=this._createShaderProgram(Ym.SCREEN),this.pickingProgram=this._createShaderProgram(Ym.PICKING),this.vao=this._createVAO()}return a(e,[{key:`addAtlasCollection`,value:function(e,t){this.atlasManager.addAtlasCollection(e,t)}},{key:`addTextureAtlasRenderType`,value:function(e,t){this.atlasManager.addRenderType(e,t)}},{key:`addSimpleShapeRenderType`,value:function(e,t){this.simpleShapeOptions.set(e,t)}},{key:`invalidate`,value:function(e){var t=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}).type,n=this.atlasManager;return t?n.invalidate(e,{filterType:function(e){return e===t},forceRedraw:!0}):n.invalidate(e)}},{key:`gc`,value:function(){this.atlasManager.gc()}},{key:`_createShaderProgram`,value:function(e){var t=this.gl,n=`#version 300 es + precision highp float; + + uniform mat3 uPanZoomMatrix; + uniform int uAtlasSize; + + // instanced + in vec2 aPosition; // a vertex from the unit square + + in mat3 aTransform; // used to transform verticies, eg into a bounding box + in int aVertType; // the type of thing we are rendering + + // the z-index that is output when using picking mode + in vec4 aIndex; + + // For textures + in int aAtlasId; // which shader unit/atlas to use + in vec4 aTex; // x/y/w/h of texture in atlas + + // for edges + in vec4 aPointAPointB; + in vec4 aPointCPointD; + in vec2 aLineWidth; // also used for node border width + + // simple shapes + in vec4 aCornerRadius; // for round-rectangle [top-right, bottom-right, top-left, bottom-left] + in vec4 aColor; // also used for edges + in vec4 aBorderColor; // aLineWidth is used for border width + + // output values passed to the fragment shader + out vec2 vTexCoord; + out vec4 vColor; + out vec2 vPosition; + // flat values are not interpolated + flat out int vAtlasId; + flat out int vVertType; + flat out vec2 vTopRight; + flat out vec2 vBotLeft; + flat out vec4 vCornerRadius; + flat out vec4 vBorderColor; + flat out vec2 vBorderWidth; + flat out vec4 vIndex; + + void main(void) { + int vid = gl_VertexID; + vec2 position = aPosition; // TODO make this a vec3, simplifies some code below + + if(aVertType == ${Zm}) { + float texX = aTex.x; // texture coordinates + float texY = aTex.y; + float texW = aTex.z; + float texH = aTex.w; + + if(vid == 1 || vid == 2 || vid == 4) { + texX += texW; + } + if(vid == 2 || vid == 4 || vid == 5) { + texY += texH; + } + + float d = float(uAtlasSize); + vTexCoord = vec2(texX / d, texY / d); // tex coords must be between 0 and 1 + + gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0); + } + else if(aVertType == ${th} || aVertType == ${ih} + || aVertType == ${nh} || aVertType == ${rh}) { // simple shapes + + // the bounding box is needed by the fragment shader + vBotLeft = (aTransform * vec3(0, 0, 1)).xy; // flat + vTopRight = (aTransform * vec3(1, 1, 1)).xy; // flat + vPosition = (aTransform * vec3(position, 1)).xy; // will be interpolated + + // calculations are done in the fragment shader, just pass these along + vColor = aColor; + vCornerRadius = aCornerRadius; + vBorderColor = aBorderColor; + vBorderWidth = aLineWidth; + + gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0); + } + else if(aVertType == ${Qm}) { + vec2 source = aPointAPointB.xy; + vec2 target = aPointAPointB.zw; + + // adjust the geometry so that the line is centered on the edge + position.y = position.y - 0.5; + + // stretch the unit square into a long skinny rectangle + vec2 xBasis = target - source; + vec2 yBasis = normalize(vec2(-xBasis.y, xBasis.x)); + vec2 point = source + xBasis * position.x + yBasis * aLineWidth[0] * position.y; + + gl_Position = vec4(uPanZoomMatrix * vec3(point, 1.0), 1.0); + vColor = aColor; + } + else if(aVertType == ${$m}) { + vec2 pointA = aPointAPointB.xy; + vec2 pointB = aPointAPointB.zw; + vec2 pointC = aPointCPointD.xy; + vec2 pointD = aPointCPointD.zw; + + // adjust the geometry so that the line is centered on the edge + position.y = position.y - 0.5; + + vec2 p0, p1, p2, pos; + if(position.x == 0.0) { // The left side of the unit square + p0 = pointA; + p1 = pointB; + p2 = pointC; + pos = position; + } else { // The right side of the unit square, use same approach but flip the geometry upside down + p0 = pointD; + p1 = pointC; + p2 = pointB; + pos = vec2(0.0, -position.y); + } + + vec2 p01 = p1 - p0; + vec2 p12 = p2 - p1; + vec2 p21 = p1 - p2; + + // Find the normal vector. + vec2 tangent = normalize(normalize(p12) + normalize(p01)); + vec2 normal = vec2(-tangent.y, tangent.x); + + // Find the vector perpendicular to p0 -> p1. + vec2 p01Norm = normalize(vec2(-p01.y, p01.x)); + + // Determine the bend direction. + float sigma = sign(dot(p01 + p21, normal)); + float width = aLineWidth[0]; + + if(sign(pos.y) == -sigma) { + // This is an intersecting vertex. Adjust the position so that there's no overlap. + vec2 point = 0.5 * width * normal * -sigma / dot(normal, p01Norm); + gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0); + } else { + // This is a non-intersecting vertex. Treat it like a mitre join. + vec2 point = 0.5 * width * normal * sigma * dot(normal, p01Norm); + gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0); + } + + vColor = aColor; + } + else if(aVertType == ${eh} && vid < 3) { + // massage the first triangle into an edge arrow + if(vid == 0) + position = vec2(-0.15, -0.3); + if(vid == 1) + position = vec2( 0.0, 0.0); + if(vid == 2) + position = vec2( 0.15, -0.3); + + gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0); + vColor = aColor; + } + else { + gl_Position = vec4(2.0, 0.0, 0.0, 1.0); // discard vertex by putting it outside webgl clip space + } + + vAtlasId = aAtlasId; + vVertType = aVertType; + vIndex = aIndex; + } + `,r=this.batchManager.getIndexArray(),i=mm(t,n,`#version 300 es + precision highp float; + + // declare texture unit for each texture atlas in the batch + ${r.map(function(e){return`uniform sampler2D uTexture${e};`}).join(` + `)} + + uniform vec4 uBGColor; + uniform float uZoom; + + in vec2 vTexCoord; + in vec4 vColor; + in vec2 vPosition; // model coordinates + + flat in int vAtlasId; + flat in vec4 vIndex; + flat in int vVertType; + flat in vec2 vTopRight; + flat in vec2 vBotLeft; + flat in vec4 vCornerRadius; + flat in vec4 vBorderColor; + flat in vec2 vBorderWidth; + + out vec4 outColor; + + ${Gm} + ${Km} + ${qm} + ${Jm} + + vec4 blend(vec4 top, vec4 bot) { // blend colors with premultiplied alpha + return vec4( + top.rgb + (bot.rgb * (1.0 - top.a)), + top.a + (bot.a * (1.0 - top.a)) + ); + } + + vec4 distInterp(vec4 cA, vec4 cB, float d) { // interpolate color using Signed Distance + // scale to the zoom level so that borders don't look blurry when zoomed in + // note 1.5 is an aribitrary value chosen because it looks good + return mix(cA, cB, 1.0 - smoothstep(0.0, 1.5 / uZoom, abs(d))); + } + + void main(void) { + if(vVertType == ${Zm}) { + // look up the texel from the texture unit + ${r.map(function(e){return`if(vAtlasId == ${e}) outColor = texture(uTexture${e}, vTexCoord);`}).join(` + else `)} + } + else if(vVertType == ${eh}) { + // mimics how canvas renderer uses context.globalCompositeOperation = 'destination-out'; + outColor = blend(vColor, uBGColor); + outColor.a = 1.0; // make opaque, masks out line under arrow + } + else if(vVertType == ${th} && vBorderWidth == vec2(0.0)) { // simple rectangle with no border + outColor = vColor; // unit square is already transformed to the rectangle, nothing else needs to be done + } + else if(vVertType == ${th} || vVertType == ${ih} + || vVertType == ${nh} || vVertType == ${rh}) { // use SDF + + float outerBorder = vBorderWidth[0]; + float innerBorder = vBorderWidth[1]; + float borderPadding = outerBorder * 2.0; + float w = vTopRight.x - vBotLeft.x - borderPadding; + float h = vTopRight.y - vBotLeft.y - borderPadding; + vec2 b = vec2(w/2.0, h/2.0); // half width, half height + vec2 p = vPosition - vec2(vTopRight.x - b[0] - outerBorder, vTopRight.y - b[1] - outerBorder); // translate to center + + float d; // signed distance + if(vVertType == ${th}) { + d = rectangleSD(p, b); + } else if(vVertType == ${ih} && w == h) { + d = circleSD(p, b.x); // faster than ellipse + } else if(vVertType == ${ih}) { + d = ellipseSD(p, b); + } else { + d = roundRectangleSD(p, b, vCornerRadius.wzyx); + } + + // use the distance to interpolate a color to smooth the edges of the shape, doesn't need multisampling + // we must smooth colors inwards, because we can't change pixels outside the shape's bounding box + if(d > 0.0) { + if(d > outerBorder) { + discard; + } else { + outColor = distInterp(vBorderColor, vec4(0), d - outerBorder); + } + } else { + if(d > innerBorder) { + vec4 outerColor = outerBorder == 0.0 ? vec4(0) : vBorderColor; + vec4 innerBorderColor = blend(vBorderColor, vColor); + outColor = distInterp(innerBorderColor, outerColor, d); + } + else { + vec4 outerColor; + if(innerBorder == 0.0 && outerBorder == 0.0) { + outerColor = vec4(0); + } else if(innerBorder == 0.0) { + outerColor = vBorderColor; + } else { + outerColor = blend(vBorderColor, vColor); + } + outColor = distInterp(vColor, outerColor, d - innerBorder); + } + } + } + else { + outColor = vColor; + } + + ${e.picking?`if(outColor.a == 0.0) discard; + else outColor = vIndex;`:``} + } + `);i.aPosition=t.getAttribLocation(i,`aPosition`),i.aIndex=t.getAttribLocation(i,`aIndex`),i.aVertType=t.getAttribLocation(i,`aVertType`),i.aTransform=t.getAttribLocation(i,`aTransform`),i.aAtlasId=t.getAttribLocation(i,`aAtlasId`),i.aTex=t.getAttribLocation(i,`aTex`),i.aPointAPointB=t.getAttribLocation(i,`aPointAPointB`),i.aPointCPointD=t.getAttribLocation(i,`aPointCPointD`),i.aLineWidth=t.getAttribLocation(i,`aLineWidth`),i.aColor=t.getAttribLocation(i,`aColor`),i.aCornerRadius=t.getAttribLocation(i,`aCornerRadius`),i.aBorderColor=t.getAttribLocation(i,`aBorderColor`),i.uPanZoomMatrix=t.getUniformLocation(i,`uPanZoomMatrix`),i.uAtlasSize=t.getUniformLocation(i,`uAtlasSize`),i.uBGColor=t.getUniformLocation(i,`uBGColor`),i.uZoom=t.getUniformLocation(i,`uZoom`),i.uTextures=[];for(var a=0;a1&&arguments[1]!==void 0?arguments[1]:Ym.SCREEN;this.panZoomMatrix=e,this.renderTarget=t,this.batchDebugInfo=[],this.wrappedCount=0,this.simpleCount=0,this.startBatch()}},{key:`startBatch`,value:function(){this.instanceCount=0,this.batchManager.startBatch()}},{key:`endFrame`,value:function(){this.endBatch()}},{key:`_isVisible`,value:function(e,t){return e.visible()?t&&t.isVisible?t.isVisible(e):!0:!1}},{key:`drawTexture`,value:function(e,t,n){var r=this.atlasManager,i=this.batchManager,a=r.getRenderTypeOpts(n);if(this._isVisible(e,a)&&!(e.isEdge()&&!this._isValidEdge(e))){if(this.renderTarget.picking&&a.getTexPickingMode){var s=a.getTexPickingMode(e);if(s===Xm.IGNORE)return;if(s==Xm.USE_BB){this.drawPickingRectangle(e,t,n);return}}var c=o(r.getAtlasInfo(e,n)),l;try{for(c.s();!(l=c.n()).done;){var u=l.value,d=u.atlas,p=u.tex1,m=u.tex2;i.canAddToCurrentBatch(d)||this.endBatch();for(var h=i.getAtlasIndexForBatch(d),g=0,_=[[p,!0],[m,!1]];g<_.length;g++){var v=f(_[g],2),y=v[0],b=v[1];if(y.w!=0){var x=this.instanceCount;this.vertTypeBuffer.getView(x)[0]=Zm,Sm(t,this.indexBuffer.getView(x));var S=this.atlasIdBuffer.getView(x);S[0]=h;var C=this.texBuffer.getView(x);C[0]=y.x,C[1]=y.y,C[2]=y.w,C[3]=y.h;var w=this.transformBuffer.getMatrixView(x);this.setTransformMatrix(e,w,a,u,b),this.instanceCount++,b||this.wrappedCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}}catch(e){c.e(e)}finally{c.f()}}}},{key:`setTransformMatrix`,value:function(e,t,n,r){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,a=0;if(n.shapeProps&&n.shapeProps.padding&&(a=e.pstyle(n.shapeProps.padding).pfValue),r){var o=r.bb,s=r.tex1,c=r.tex2,l=s.w/(s.w+c.w);i||(l=1-l);var u=this._getAdjustedBB(o,a,i,l);this._applyTransformMatrix(t,u,n,e)}else{var d=n.getBoundingBox(e),f=this._getAdjustedBB(d,a,!0,1);this._applyTransformMatrix(t,f,n,e)}}},{key:`_applyTransformMatrix`,value:function(e,t,n,r){var i,a;Pm(e);var o=n.getRotation?n.getRotation(r):0;if(o!==0){var s=n.getRotationPoint(r),c=s.x,l=s.y;Im(e,e,[c,l]),Lm(e,e,o);var u=n.getRotationOffset(r);i=u.x+(t.xOffset||0),a=u.y+(t.yOffset||0)}else i=t.x1,a=t.y1;Im(e,e,[i,a]),Rm(e,e,[t.w,t.h])}},{key:`_getAdjustedBB`,value:function(e,t,n,r){var i=e.x1,a=e.y1,o=e.w,s=e.h,c=e.yOffset;t&&(i-=t,a-=t,o+=2*t,s+=2*t);var l=0,u=o*r;return n&&r<1?o=u:!n&&r<1&&(l=o-u,i+=l,o=u),{x1:i,y1:a,w:o,h:s,xOffset:l,yOffset:c}}},{key:`drawPickingRectangle`,value:function(e,t,n){var r=this.atlasManager.getRenderTypeOpts(n),i=this.instanceCount;this.vertTypeBuffer.getView(i)[0]=th,Sm(t,this.indexBuffer.getView(i)),xm([0,0,0],1,this.colorBuffer.getView(i));var a=this.transformBuffer.getMatrixView(i);this.setTransformMatrix(e,a,r),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}},{key:`drawNode`,value:function(e,t,n){var r=this.simpleShapeOptions.get(n);if(this._isVisible(e,r)){var i=r.shapeProps,a=this._getVertTypeForShape(e,i.shape);if(a===void 0||r.isSimple&&!r.isSimple(e,this.renderTarget)){this.drawTexture(e,t,n);return}var o=this.instanceCount;if(this.vertTypeBuffer.getView(o)[0]=a,a===nh||a===rh){var s=r.getBoundingBox(e),c=this._getCornerRadius(e,i.radius,s),l=this.cornerRadiusBuffer.getView(o);l[0]=c,l[1]=c,l[2]=c,l[3]=c,a===rh&&(l[0]=0,l[2]=0)}Sm(t,this.indexBuffer.getView(o));var u=this.renderTarget.picking?1:n===`node-body`?e.effectiveOpacity():1,d=this.renderTarget.picking?1:e.pstyle(i.opacity).value*u,f=e.pstyle(i.color).value;xm(f,d,this.colorBuffer.getView(o));var p=this.lineWidthBuffer.getView(o);if(p[0]=0,p[1]=0,i.border){var m=e.pstyle(`border-width`).value;if(m>0){var h=e.pstyle(`border-color`).value;xm(h,u*e.pstyle(`border-opacity`).value,this.borderColorBuffer.getView(o));var g=e.pstyle(`border-position`).value;if(g===`inside`)p[0]=0,p[1]=-m;else if(g===`outside`)p[0]=m,p[1]=0;else{var _=m/2;p[0]=_,p[1]=-_}}}var v=this.transformBuffer.getMatrixView(o);this.setTransformMatrix(e,v,r),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}},{key:`_getVertTypeForShape`,value:function(e,t){switch(e.pstyle(t).value){case`rectangle`:return th;case`ellipse`:return ih;case`roundrectangle`:case`round-rectangle`:return nh;case`bottom-round-rectangle`:return rh;default:return}}},{key:`_getCornerRadius`,value:function(e,t,n){var r=n.w,i=n.h;if(e.pstyle(t).value===`auto`)return jr(r,i);var a=e.pstyle(t).pfValue,o=r/2,s=i/2;return Math.min(a,s,o)}},{key:`drawEdgeArrow`,value:function(e,t,n){if(e.visible()){var r=e._private.rscratch,i,a,o;if(n===`source`?(i=r.arrowStartX,a=r.arrowStartY,o=r.srcArrowAngle):(i=r.arrowEndX,a=r.arrowEndY,o=r.tgtArrowAngle),!(isNaN(i)||i==null||isNaN(a)||a==null||isNaN(o)||o==null)&&e.pstyle(n+`-arrow-shape`).value!==`none`){var s=e.pstyle(n+`-arrow-color`).value,c=e.pstyle(`opacity`).value*e.pstyle(`line-opacity`).value,l=e.pstyle(`width`).pfValue,u=e.pstyle(`arrow-scale`).value,d=this.r.getArrowWidth(l,u),f=this.instanceCount,p=this.transformBuffer.getMatrixView(f);Pm(p),Im(p,p,[i,a]),Rm(p,p,[d,d]),Lm(p,p,o),this.vertTypeBuffer.getView(f)[0]=eh,Sm(t,this.indexBuffer.getView(f)),xm(s,c,this.colorBuffer.getView(f)),this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}},{key:`drawEdgeLine`,value:function(e,t){if(e.visible()){var n=this._getEdgePoints(e);if(n){var r=e.pstyle(`opacity`).value,i=e.pstyle(`line-opacity`).value,a=e.pstyle(`width`).pfValue,o=e.pstyle(`line-color`).value,s=r*i;if(n.length/2+this.instanceCount>this.maxInstances&&this.endBatch(),n.length==4){var c=this.instanceCount;this.vertTypeBuffer.getView(c)[0]=Qm,Sm(t,this.indexBuffer.getView(c)),xm(o,s,this.colorBuffer.getView(c));var l=this.lineWidthBuffer.getView(c);l[0]=a;var u=this.pointAPointBBuffer.getView(c);u[0]=n[0],u[1]=n[1],u[2]=n[2],u[3]=n[3],this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}else for(var d=0;d=this.maxInstances&&this.endBatch()}}}}},{key:`_isValidEdge`,value:function(e){var t=e._private.rscratch;return!(t.badLine||t.allpts==null||isNaN(t.allpts[0]))}},{key:`_getEdgePoints`,value:function(e){var t=e._private.rscratch;if(this._isValidEdge(e)){var n=t.allpts;if(n.length==4)return n;var r=this._getNumSegments(e);return this._getCurveSegmentPoints(n,r)}}},{key:`_getNumSegments`,value:function(e){return Math.min(15,this.maxInstances)}},{key:`_getCurveSegmentPoints`,value:function(e,t){if(e.length==4)return e;for(var n=Array((t+1)*2),r=0;r<=t;r++)if(r==0)n[0]=e[0],n[1]=e[1];else if(r==t)n[r*2]=e[e.length-2],n[r*2+1]=e[e.length-1];else{var i=r/t;this._setCurvePoint(e,i,n,r*2)}return n}},{key:`_setCurvePoint`,value:function(e,t,n,r){if(e.length<=2)n[r]=e[0],n[r+1]=e[1];else{for(var i=Array(e.length-2),a=0;a0}},s=function(e){return e.pstyle(`text-events`).strValue===`yes`?Xm.USE_BB:Xm.IGNORE},c=function(e){var t=e.position(),n=t.x,r=t.y,i=e.outerWidth(),a=e.outerHeight();return{w:i,h:a,x1:n-i/2,y1:r-a/2}};n.drawing.addAtlasCollection(`node`,{texRows:e.webglTexRowsNodes}),n.drawing.addAtlasCollection(`label`,{texRows:e.webglTexRows}),n.drawing.addTextureAtlasRenderType(`node-body`,{collection:`node`,getKey:t.getStyleKey,getBoundingBox:t.getElementBox,drawElement:t.drawElement}),n.drawing.addSimpleShapeRenderType(`node-body`,{getBoundingBox:c,isSimple:ym,shapeProps:{shape:`shape`,color:`background-color`,opacity:`background-opacity`,radius:`corner-radius`,border:!0}}),n.drawing.addSimpleShapeRenderType(`node-overlay`,{getBoundingBox:c,isVisible:o(`overlay`),shapeProps:{shape:`overlay-shape`,color:`overlay-color`,opacity:`overlay-opacity`,padding:`overlay-padding`,radius:`overlay-corner-radius`}}),n.drawing.addSimpleShapeRenderType(`node-underlay`,{getBoundingBox:c,isVisible:o(`underlay`),shapeProps:{shape:`underlay-shape`,color:`underlay-color`,opacity:`underlay-opacity`,padding:`underlay-padding`,radius:`underlay-corner-radius`}}),n.drawing.addTextureAtlasRenderType(`label`,{collection:`label`,getTexPickingMode:s,getKey:lh(t.getLabelKey,null),getBoundingBox:uh(t.getLabelBox,null),drawClipped:!0,drawElement:t.drawLabel,getRotation:i(null),getRotationPoint:t.getLabelRotationPoint,getRotationOffset:t.getLabelRotationOffset,isVisible:a(`label`)}),n.drawing.addTextureAtlasRenderType(`edge-source-label`,{collection:`label`,getTexPickingMode:s,getKey:lh(t.getSourceLabelKey,`source`),getBoundingBox:uh(t.getSourceLabelBox,`source`),drawClipped:!0,drawElement:t.drawSourceLabel,getRotation:i(`source`),getRotationPoint:t.getSourceLabelRotationPoint,getRotationOffset:t.getSourceLabelRotationOffset,isVisible:a(`source-label`)}),n.drawing.addTextureAtlasRenderType(`edge-target-label`,{collection:`label`,getTexPickingMode:s,getKey:lh(t.getTargetLabelKey,`target`),getBoundingBox:uh(t.getTargetLabelBox,`target`),drawClipped:!0,drawElement:t.drawTargetLabel,getRotation:i(`target`),getRotationPoint:t.getTargetLabelRotationPoint,getRotationOffset:t.getTargetLabelRotationOffset,isVisible:a(`target-label`)});var l=st(function(){console.log(`garbage collect flag set`),n.data.gc=!0},1e4);n.onUpdateEleCalcs(function(e,t){var r=!1;t&&t.length>0&&(r|=n.drawing.invalidate(t)),r&&l()}),dh(n)};function sh(e){var t=e.cy.container();return pe(t&&t.style&&t.style.backgroundColor||`white`)}function ch(e,t){var n=e._private.rscratch;return Xt(n,`labelWrapCachedLines`,t)||[]}var lh=function(e,t){return function(n){var r=e(n),i=ch(n,t);return i.length>1?i.map(function(e,t){return`${r}_${t}`}):r}},uh=function(e,t){return function(n,r){var i=e(n);if(typeof r==`string`){var a=r.indexOf(`_`);if(a>0){var o=Number(r.substring(a+1)),s=ch(n,t),c=i.h/s.length,l=c*o,u=i.y1+l;return{x1:i.x1,w:i.w,y1:u,h:c,yOffset:l}}}return i}};function dh(e){var t=e.render;e.render=function(n){n||={};var r=e.cy;e.webgl&&(r.zoom()>ap?(fh(e),t.call(e,n)):(ph(e),Sh(e,n,Ym.SCREEN)))};var n=e.matchCanvasSize;e.matchCanvasSize=function(t){n.call(e,t),e.pickingFrameBuffer.setFramebufferAttachmentSizes(e.canvasWidth,e.canvasHeight),e.pickingFrameBuffer.needsDraw=!0},e.findNearestElements=function(t,n,r,i){return bh(e,t,n)};var r=e.invalidateCachedZSortedEles;e.invalidateCachedZSortedEles=function(){r.call(e),e.pickingFrameBuffer.needsDraw=!0};var i=e.notify;e.notify=function(t,n){i.call(e,t,n),t===`viewport`||t===`bounds`?e.pickingFrameBuffer.needsDraw=!0:t===`background`&&e.drawing.invalidate(n,{type:`node-body`})}}function fh(e){var t=e.data.contexts[e.WEBGL];t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT)}function ph(e){var t=function(t){t.save(),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,e.canvasWidth,e.canvasHeight),t.restore()};t(e.data.contexts[e.NODE]),t(e.data.contexts[e.DRAG])}function mh(e){var t=e.canvasWidth,n=e.canvasHeight,r=gm(e),i=r.pan,a=r.zoom,o=Nm();Im(o,o,[i.x,i.y]),Rm(o,o,[a,a]);var s=Nm();zm(s,t,n);var c=Nm();return Fm(c,s,o),c}function hh(e,t){var n=e.canvasWidth,r=e.canvasHeight,i=gm(e),a=i.pan,o=i.zoom;t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,n,r),t.translate(a.x,a.y),t.scale(o,o)}function gh(e,t){e.drawSelectionRectangle(t,function(t){return hh(e,t)})}function _h(e){var t=e.data.contexts[e.NODE];t.save(),hh(e,t),t.strokeStyle=`rgba(0, 0, 0, 0.3)`,t.beginPath(),t.moveTo(-1e3,0),t.lineTo(1e3,0),t.stroke(),t.beginPath(),t.moveTo(0,-1e3),t.lineTo(0,1e3),t.stroke(),t.restore()}function vh(e){var t=function(t,n,r){for(var i=t.atlasManager.getAtlasCollection(n),a=e.data.contexts[e.NODE],o=i.atlases,s=0;s=0&&b.add(S)}return b}function bh(e,t,n){var r=yh(e,t,n),i=e.getCachedZSortedEles(),a,s,c=o(r),l;try{for(c.s();!(l=c.n()).done;){var u=i[l.value];if(!a&&u.isNode()&&(a=u),!s&&u.isEdge()&&(s=u),a&&s)break}}catch(e){c.e(e)}finally{c.f()}return[a,s].filter(Boolean)}function xh(e,t,n){var r=e.drawing;t+=1,n.isNode()?(r.drawNode(n,t,`node-underlay`),r.drawNode(n,t,`node-body`),r.drawTexture(n,t,`label`),r.drawNode(n,t,`node-overlay`)):(r.drawEdgeLine(n,t),r.drawEdgeArrow(n,t,`source`),r.drawEdgeArrow(n,t,`target`),r.drawTexture(n,t,`label`),r.drawTexture(n,t,`edge-source-label`),r.drawTexture(n,t,`edge-target-label`))}function Sh(e,t,n){var r;e.webglDebug&&(r=performance.now());var i=e.drawing,a=0;if(n.screen&&e.data.canvasNeedsRedraw[e.SELECT_BOX]&&gh(e,t),e.data.canvasNeedsRedraw[e.NODE]||n.picking){var s=e.data.contexts[e.WEBGL];n.screen?(s.clearColor(0,0,0,0),s.enable(s.BLEND),s.blendFunc(s.ONE,s.ONE_MINUS_SRC_ALPHA)):s.disable(s.BLEND),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),s.viewport(0,0,s.canvas.width,s.canvas.height);var c=mh(e),l=e.getCachedZSortedEles();if(a=l.length,i.startFrame(c,n),n.screen){for(var u=0;u0&&a>0){f.clearRect(0,0,i,a),f.globalCompositeOperation=`source-over`;var p=this.getCachedZSortedEles();if(e.full)f.translate(-n.x1*c,-n.y1*c),f.scale(c,c),this.drawElements(f,p),f.scale(1/c,1/c),f.translate(n.x1*c,n.y1*c);else{var m=t.pan(),h={x:m.x*c,y:m.y*c};c*=t.zoom(),f.translate(h.x,h.y),f.scale(c,c),this.drawElements(f,p),f.scale(1/c,1/c),f.translate(-h.x,-h.y)}e.bg&&(f.globalCompositeOperation=`destination-over`,f.fillStyle=e.bg,f.rect(0,0,i,a),f.fill())}return d};function jh(e,t){for(var n=atob(e),r=new ArrayBuffer(n.length),i=new Uint8Array(r),a=0;a`u`?`undefined`:g(OffscreenCanvas))===`undefined`?(n=this.cy.window().document.createElement(`canvas`),n.width=e,n.height=t):n=new OffscreenCanvas(e,t),n},[Hp,Yp,nm,im,am,cm,um,oh,Ch,Ah,Ph].forEach(function(e){X($,e)});var Rh=[{type:`layout`,extensions:qd},{type:`renderer`,extensions:[{name:`null`,impl:Jd},{name:`base`,impl:Xf},{name:`canvas`,impl:Fh}]}],zh={},Bh={};function Vh(e,t,n){var r=n,i=function(n){zt("Can not register `"+t+"` for `"+e+"` since `"+n+"` already exists in the prototype and can not be overridden")};if(e===`core`){if(ad.prototype[t])return i(t);ad.prototype[t]=n}else if(e===`collection`){if(yu.prototype[t])return i(t);yu.prototype[t]=n}else if(e===`layout`){for(var a=function(e){this.options=e,n.call(this,e),O(this._private)||(this._private={}),this._private.cy=e.cy,this._private.listeners=[],this.createEmitter()},o=a.prototype=Object.create(n.prototype),s=[],c=0;cMath.max(t,Math.min(n,e)),`clamp`),T=e((e=`TB`)=>{switch(e){case`BT`:return`bottom`;case`LR`:return`right`;case`RL`:return`left`;default:return`top`}},`getDefaultSelfLoopSide`),E=e(e=>e===`flowchart`||e===`flowchart-v2`||e===`stateDiagram`,`shouldMergeSelfLoopSegments`),D=e((e,t,n,r,i)=>{let a=[],o=new Set;if(n.forEach(({start:e,end:t})=>{e!==r&&o.add(e),t!==r&&o.add(t)}),o.forEach(t=>{let n=e.node(t);typeof n?.x==`number`&&typeof n?.y==`number`&&a.push(n)}),a.length===0&&n.forEach(({edge:e})=>{(e.points??[]).forEach(e=>{typeof e?.x==`number`&&typeof e?.y==`number`&&a.push(e)})}),a.length===0)return T(i);let s=a.reduce((e,t)=>({x:e.x+t.x/a.length,y:e.y+t.y/a.length}),{x:0,y:0}),c=s.x-t.x,l=s.y-t.y;return Math.abs(c)>Math.abs(l)?c>0?`right`:`left`:Math.abs(l)>0?l>0?`bottom`:`top`:T(i)},`getSelfLoopSide`),O=e((e,t=`top`,n=0,r=0)=>{let i=e.x,a=e.y-n,o=e.width/2,s=e.height/2,c=Math.max(36,Math.min(100,e.width*.8)),l=w(Math.max(r,e.width*.35),36,c),u=w(Math.min(e.width,e.height)*.45,24,48);switch(t){case`bottom`:{let e=a+s;return[{x:i-l/2,y:e},{x:i-l/2,y:e+u},{x:i+l/2,y:e+u},{x:i+l/2,y:e}]}case`right`:{let e=i+o;return[{x:e,y:a-l/2},{x:e+u,y:a-l/2},{x:e+u,y:a+l/2},{x:e,y:a+l/2}]}case`left`:{let e=i-o;return[{x:e,y:a-l/2},{x:e-u,y:a-l/2},{x:e-u,y:a+l/2},{x:e,y:a+l/2}]}default:{let e=a-s;return[{x:i-l/2,y:e},{x:i-l/2,y:e-u},{x:i+l/2,y:e-u},{x:i+l/2,y:e}]}}},`getSelfLoopPoints`),k=e((e,t,n=`top`,r=0,i={})=>{let a=e.x,o=e.y-r,s=i.width??0,c=i.height??0;switch(n){case`bottom`:return{x:a,y:Math.max(...t.map(e=>e.y))+c/2+4};case`right`:return{x:Math.max(...t.map(e=>e.x))+s/2+4,y:o};case`left`:return{x:Math.min(...t.map(e=>e.x))-s/2-4,y:o};default:return{x:a,y:Math.min(...t.map(e=>e.y))-c/2-4}}},`getSelfLoopLabelPosition`),A=e((e,t=0,{mergeSelfLoops:n=!0}={})=>{let r=new Map,i=[],a=e.graph()?.rankdir;return e.edges().forEach(t=>{let a=e.edge(t);if(n&&a.selfLoop){let e=a.selfLoop.id;r.has(e)||r.set(e,[]),r.get(e).push({edge:a,start:t.v,end:t.w})}else i.push({edge:a,start:t.v,end:t.w})}),r.forEach(n=>{if(n.length!==3){n.forEach(e=>i.push(e));return}n.sort((e,t)=>e.edge.selfLoop.order-t.edge.selfLoop.order);let[r,o,s]=n,c=r.edge.originalEdge??o.edge.originalEdge??s.edge.originalEdge??o.edge,l=e.node(c.start);if(!l){n.forEach(e=>i.push(e));return}let u={width:o.edge.width,height:o.edge.height},d=D(e,l,n,c.start,a),f=O(l,d,t,u.width??0),p=k(l,f,d,t,u),m={...o.edge,...c,id:c.id,points:f,start:c.start,end:c.end,x:p.x,y:p.y,width:u.width,height:u.height,labelStyle:o.edge.labelStyle,fromCluster:r.edge.fromCluster??o.edge.fromCluster??s.edge.fromCluster,toCluster:r.edge.toCluster??o.edge.toCluster??s.edge.toCluster};delete m.selfLoop,delete m.originalEdge,i.push({edge:m,start:m.start,end:m.end})}),i},`getEdgesToRender`),j=e(async(n,i,c,d,g,_)=>{t.warn(`Graph in recursive render:XAX`,l(i),g);let y=i.graph().rankdir;t.trace(`Dir in recursive render - dir:`,y);let C=n.insert(`g`).attr(`class`,`root`);i.nodes()?t.info(`Recursive render XXX`,i.nodes()):t.info(`No nodes found for`,i),i.edges().length>0&&t.info(`Recursive edges`,i.edge(i.edges()[0]));let w=C.insert(`g`).attr(`class`,`clusters`),T=C.insert(`g`).attr(`class`,`edgePaths`),D=C.insert(`g`).attr(`class`,`edgeLabels`),O=C.insert(`g`).attr(`class`,`nodes`),k=E(c);await Promise.all(i.nodes().map(async function(e){let n=i.node(e);if(g!==void 0){let n=JSON.parse(JSON.stringify(g.clusterData));t.trace(`Setting data for parent cluster XXX + Node.id = `,e,` + data=`,n.height,` +Parent cluster`,g.height),i.setNode(g.id,n),i.parent(e)||(t.trace(`Setting parent`,e,g.id),i.setParent(e,g.id,n))}if(t.info(`(Insert) Node XXX`+e+`: `+JSON.stringify(i.node(e))),n?.clusterNode){t.info(`Cluster identified XBX`,e,n.width,i.node(e));let{ranksep:r,nodesep:a}=i.graph();n.graph.setGraph({...n.graph.graph(),ranksep:r+25,nodesep:a});let o=await j(O,n.graph,c,d,i.node(e),_),s=o.elem;v(n,s),n.diff=o.diff||0,t.info(`New compound node after recursive render XAX`,e,`width`,n.width,`height`,n.height),h(s,n)}else i.children(e).length>0?(t.trace(`Cluster - the non recursive path XBX`,e,n.id,n,n.width,`Graph:`,i),t.trace(s(n.id,i)),u.set(n.id,{id:s(n.id,i),node:n})):(t.trace(`Node - the non recursive path XAX`,e,O,i.node(e),y),await f(O,i.node(e),{config:_,dir:y}))})),await e(async()=>{let e=i.edges().map(async function(e){let n=i.edge(e.v,e.w,e.name);if(t.info(`Edge `+e.v+` -> `+e.w+`: `+JSON.stringify(e)),t.info(`Edge `+e.v+` -> `+e.w+`: `,e,` `,JSON.stringify(i.edge(e))),t.info(`Fix`,u,`ids:`,e.v,e.w,`Translating: `,u.get(e.v),u.get(e.w)),k&&n.selfLoop){if(n.selfLoop.order!==1)return;let e=n.id;n.id=n.selfLoop.id,await b(D,n),n.id=e;return}await b(D,n)});await Promise.all(e)},`processEdges`)(),t.info(`Graph before layout:`,JSON.stringify(l(i))),t.info(`############################################# XXX`),t.info(`### Layout ### XXX`),t.info(`############################################# XXX`),a(i),t.info(`Graph after layout:`,JSON.stringify(l(i)));let M=0,{subGraphTitleTotalMargin:N}=r(_);await Promise.all(o(i).map(async function(e){let n=i.node(e);if(t.info(`Position XBX => `+e+`: (`+n.x,`,`+n.y,`) width: `,n.width,` height: `,n.height),n?.clusterNode)n.y+=N,t.info(`A tainted cluster node XBX1`,e,n.id,n.width,n.height,n.x,n.y,i.parent(e)),u.get(n.id).node=n,p(n);else if(i.children(e).length>0){t.info(`A pure cluster node XBX1`,e,n.id,n.x,n.y,n.width,n.height,i.parent(e)),n.height+=N,i.node(n.parentId);let r=n?.padding/2||0,a=n?.labelBBox?.height||0,o=a-r||0;t.debug(`OffsetY`,o,`labelHeight`,a,`halfPadding`,r),await m(w,n),u.get(n.id).node=n}else{let e=i.node(n.parentId);n.y+=N/2,t.info(`A regular node XBX1 - using the padding`,n.id,`parent`,n.parentId,n.width,n.height,n.x,n.y,`offsetY`,n.offsetY,`parent`,e,e?.offsetY,n),p(n)}}));let P=N/2;return A(i,P,{mergeSelfLoops:k}).forEach(function({edge:e,start:n,end:r}){t.info(`Edge `+n+` -> `+r+`: `+JSON.stringify(e),e),e.points.forEach(e=>e.y+=P);let a=i.node(n),o=i.node(r);x(e,S(T,e,u,c,a,o,d))}),i.nodes().forEach(function(e){let n=i.node(e);t.info(e,n.type,n.diff),n.isGroup&&(M=n.diff)}),t.warn(`Returning from recursive render XAX`,C,M),{elem:C,diff:M}},`recursiveRender`),M=e(async(e,r)=>{let a=new i({multigraph:!0,compound:!0}).setGraph({rankdir:e.direction,nodesep:e.config?.nodeSpacing||e.config?.flowchart?.nodeSpacing||e.nodeSpacing,ranksep:e.config?.rankSpacing||e.config?.flowchart?.rankSpacing||e.rankSpacing,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}}),o=r.select(`g`);y(o,e.markers,e.type,e.diagramId),g(),C(),_(),c(),e.nodes.forEach(e=>{a.setNode(e.id,{...e}),e.parentId&&a.setParent(e.id,e.parentId)}),t.debug(`Edges:`,e.edges),e.edges.forEach(e=>{if(e.start===e.end){let t=e.start,n=t+`---`+t+`---1`,r=t+`---`+t+`---2`,i=a.node(t);a.setNode(n,{domId:n,id:n,parentId:i.parentId,labelStyle:``,label:``,padding:0,shape:`labelRect`,style:``,width:10,height:10}),a.setParent(n,i.parentId),a.setNode(r,{domId:r,id:r,parentId:i.parentId,labelStyle:``,padding:0,shape:`labelRect`,label:``,style:``,width:10,height:10}),a.setParent(r,i.parentId);let o=structuredClone(e),s=structuredClone(e),c=structuredClone(e),l=structuredClone(e);s.originalEdge=o,s.selfLoop={id:o.id,order:0},c.originalEdge=o,c.selfLoop={id:o.id,order:1},l.originalEdge=o,l.selfLoop={id:o.id,order:2},s.label=``,s.arrowTypeEnd=`none`,s.endLabelLeft=``,s.endLabelRight=``,s.startLabelLeft=``,s.id=t+`-cyclic-special-1`,c.startLabelRight=``,c.startLabelLeft=``,c.endLabelLeft=``,c.endLabelRight=``,c.arrowTypeStart=`none`,c.arrowTypeEnd=`none`,c.id=t+`-cyclic-special-mid`,l.label=``,l.startLabelRight=``,l.startLabelLeft=``,l.arrowTypeStart=`none`,i.isGroup&&(s.fromCluster=t,l.toCluster=t),l.id=t+`-cyclic-special-2`,l.arrowTypeStart=`none`,a.setEdge(t,n,s,t+`-cyclic-special-0`),a.setEdge(n,r,c,t+`-cyclic-special-1`),a.setEdge(r,t,l,t+`-cyclic-special-2`)}else a.setEdge(e.start,e.end,{...e},e.id)}),t.warn(`Graph at first:`,JSON.stringify(l(a))),d(a),t.warn(`Graph after XAX:`,JSON.stringify(l(a)));let s=n();await j(o,a,e.type,e.diagramId,void 0,s)},`render`);export{A as getEdgesToRender,M as render}; \ No newline at end of file diff --git a/dist-desktop/assets/dagre-dpRSp0QF.js b/dist-desktop/assets/dagre-dpRSp0QF.js new file mode 100644 index 0000000..2ba02d2 --- /dev/null +++ b/dist-desktop/assets/dagre-dpRSp0QF.js @@ -0,0 +1 @@ +import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,H as s,I as c,J as l,K as u,L as d,N as f,O as p,Q as m,S as h,T as g,U as _,V as v,W as ee,X as y,Y as te,Z as b,_ as ne,a as x,c as re,d as ie,et as S,f as C,h as ae,i as w,it as oe,k as se,m as ce,n as T,nt as le,o as E,p as ue,r as D,s as de,t as O,tt as fe,u as pe,z as me}from"./graphlib-DS17s2tU.js";import{a as he,c as k,d as ge,f as _e,i as ve,l as ye,n as be,o as xe,r as Se,s as Ce,t as A,u as we}from"./map-BaFkSB1l.js";var Te=/\s/;function Ee(e){for(var t=e.length;t--&&Te.test(e.charAt(t)););return t}var De=/^\s+/;function Oe(e){return e&&e.slice(0,Ee(e)+1).replace(De,``)}var ke=NaN,Ae=/^[-+]0x[0-9a-f]+$/i,je=/^0b[01]+$/i,Me=/^0o[0-7]+$/i,Ne=parseInt;function Pe(e){if(typeof e==`number`)return e;if(S(e))return ke;if(b(e)){var t=typeof e.valueOf==`function`?e.valueOf():e;e=b(t)?t+``:t}if(typeof e!=`string`)return e===0?e:+e;e=Oe(e);var n=je.test(e);return n||Me.test(e)?Ne(e.slice(2),n?2:8):Ae.test(e)?ke:+e}var Fe=1/0,Ie=17976931348623157e292;function j(e){return e?(e=Pe(e),e===Fe||e===-Fe?(e<0?-1:1)*Ie:e===e?e:0):e===0?e:0}function Le(e){var t=j(e),n=t%1;return t===t?n?t-n:t:0}function M(e,t,n){if(!b(n))return!1;var r=typeof t;return(r==`number`?me(n)&&_(t,n.length):r==`string`&&t in n)?s(n[t],e):!1}function Re(e){return n(function(t,n){var r=-1,i=n.length,a=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(a=e.length>3&&typeof a==`function`?(i--,a):void 0,o&&M(n[0],n[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++r2?t[2]:void 0;for(i&&M(t[0],t[1],i)&&(r=1);++n-1?i[a?t[o]:o]:void 0}}var ct=Math.max;function lt(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var i=n==null?0:Le(n);return i<0&&(i=ct(r+i,0)),ee(e,C(t,3),i)}var F=st(lt);function ut(e,t){return e==null?e:ie(e,de(t),k)}function dt(e,t){return e&&pe(e,de(t))}function ft(e,t){return e>t}var pt=Object.prototype.hasOwnProperty;function mt(e,t){return e!=null&&pt.call(e,t)}function ht(e,t){return e!=null&&ae(e,t,mt)}var gt=`[object String]`;function _t(e){return typeof e==`string`||!m(e)&&fe(e)&&le(e)==gt}function vt(e,t){return et||a&&o&&c&&!s&&!l||r&&o&&c||!n&&c||!i)return 1;if(!r&&!a&&!l&&e=s?c:c*(n[r]==`desc`?-1:1)}return e.index-t.index}function wt(t,n,r){n=n.length?e(n,function(e){return m(e)?function(t){return g(t,e.length===1?e[0]:e)}:e}):[y];var i=-1;return n=e(n,o(C)),xt(be(t,function(t,r,a){return{criteria:e(n,function(e){return e(t)}),index:++i,value:t}}),function(e,t){return Ct(e,t,r)})}var Tt=ue(`length`),Et=`\\ud800-\\udfff`,Dt=`\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff`,Ot=`\\ufe0e\\ufe0f`,kt=`[`+Et+`]`,H=`[`+Dt+`]`,U=`\\ud83c[\\udffb-\\udfff]`,At=`(?:`+H+`|`+U+`)`,jt=`[^`+Et+`]`,Mt=`(?:\\ud83c[\\udde6-\\uddff]){2}`,Nt=`[\\ud800-\\udbff][\\udc00-\\udfff]`,Pt=`\\u200d`,Ft=At+`?`,It=`[`+Ot+`]?`,Lt=`(?:`+Pt+`(?:`+[jt,Mt,Nt].join(`|`)+`)`+It+Ft+`)*`,Rt=It+Ft+Lt,zt=`(?:`+[jt+H+`?`,H,Mt,Nt,kt].join(`|`)+`)`,Bt=RegExp(U+`(?=`+U+`)|`+zt+Rt,`g`);function Vt(e){for(var t=Bt.lastIndex=0;Bt.test(e);)++t;return t}function Ht(e){return Je(e)?Vt(e):Tt(e)}function Ut(e,t){return bt(e,t,function(t,n){return ce(e,n)})}var W=ze(function(e,t){return e==null?{}:Ut(e,t)}),Wt=Math.ceil,Gt=Math.max;function Kt(e,t,n,r){for(var i=-1,a=Gt(Wt((t-e)/(n||1)),0),o=Array(a);a--;)o[r?a:++i]=e,e+=n;return o}function qt(e){return function(t,n,r){return r&&typeof r!=`number`&&M(t,n,r)&&(n=r=void 0),t=j(t),n===void 0?(n=t,t=0):n=j(n),r=r===void 0?t1&&M(e,t[0],t[1])?t=[]:n>2&&M(t[0],t[1],t[2])&&(t=[t[0]]),wt(e,r(t,1),[])}),Zt=0;function q(e){var t=++Zt;return p(e)+t}function Qt(e,t,n){for(var r=-1,i=e.length,a=t.length,o={};++r0;--s)if(o=t[s].dequeue(),o){r=r.concat(J(e,t,n,o,!0));break}}}return r}function J(e,t,n,r,i){var a=i?[]:void 0;return E(e.inEdges(r.v),function(r){var o=e.edge(r),s=e.node(r.v);i&&a.push({v:r.v,w:r.w}),s.out-=o,cn(t,n,s)}),E(e.outEdges(r.v),function(r){var i=e.edge(r),a=r.w,o=e.node(a);o.in-=i,cn(t,n,o)}),e.removeNode(r.v),a}function sn(e,t){var n=new O,r=0,i=0;E(e.nodes(),function(e){n.setNode(e,{v:e,in:0,out:0})}),E(e.edges(),function(e){var a=n.edge(e.v,e.w)||0,o=t(e),s=a+o;n.setEdge(e.v,e.w,s),i=Math.max(i,n.node(e.v).out+=o),r=Math.max(r,n.node(e.w).in+=o)});var a=G(i+r+3).map(function(){return new en}),o=r+1;return E(n.nodes(),function(e){cn(a,o,n.node(e))}),{graph:n,buckets:a,zeroIdx:o}}function cn(e,t,n){n.out?n.in?e[n.out-n.in+t].enqueue(n):e[e.length-1].enqueue(n):e[0].enqueue(n)}function ln(e){E(e.graph().acyclicer===`greedy`?an(e,t(e)):un(e),function(t){var n=e.edge(t);e.removeEdge(t),n.forwardName=t.name,n.reversed=!0,e.setEdge(t.w,t.v,n,q(`rev`))});function t(e){return function(t){return e.edge(t).weight}}}function un(e){var t=[],n={},r={};function i(a){Object.prototype.hasOwnProperty.call(r,a)||(r[a]=!0,n[a]=!0,E(e.outEdges(a),function(e){Object.prototype.hasOwnProperty.call(n,e.w)?t.push(e):i(e.w)}),delete n[a])}return E(e.nodes(),i),t}function dn(e){E(e.edges(),function(t){var n=e.edge(t);if(n.reversed){e.removeEdge(t);var r=n.forwardName;delete n.reversed,delete n.forwardName,e.setEdge(t.w,t.v,n,r)}})}function Y(e,t,n,r){var i;do i=q(r);while(e.hasNode(i));return n.dummy=t,e.setNode(i,n),i}function fn(e){var t=new O().setGraph(e.graph());return E(e.nodes(),function(n){t.setNode(n,e.node(n))}),E(e.edges(),function(n){var r=t.edge(n.v,n.w)||{weight:0,minlen:1},i=e.edge(n);t.setEdge(n.v,n.w,{weight:r.weight+i.weight,minlen:Math.max(r.minlen,i.minlen)})}),t}function pn(e){var t=new O({multigraph:e.isMultigraph()}).setGraph(e.graph());return E(e.nodes(),function(n){e.children(n).length||t.setNode(n,e.node(n))}),E(e.edges(),function(n){t.setEdge(n,e.edge(n))}),t}function mn(e,t){var n=e.x,r=e.y,i=t.x-n,a=t.y-r,o=e.width/2,s=e.height/2;if(!i&&!a)throw Error(`Not possible to find intersection inside of the rectangle`);var c,l;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),c=s*i/a,l=s):(i<0&&(o=-o),c=o,l=o*a/i),{x:n+c,y:r+l}}function X(e){var t=A(G(vn(e)+1),function(){return[]});return E(e.nodes(),function(n){var r=e.node(n),i=r.rank;D(i)||(t[i][r.order]=n)}),t}function hn(e){var t=B(A(e.nodes(),function(t){return e.node(t).rank}));E(e.nodes(),function(n){var r=e.node(n);ht(r,`rank`)&&(r.rank-=t)})}function gn(e){var t=B(A(e.nodes(),function(t){return e.node(t).rank})),n=[];E(e.nodes(),function(r){var i=e.node(r).rank-t;n[i]||(n[i]=[]),n[i].push(r)});var r=0,i=e.graph().nodeRankFactor;E(n,function(t,n){D(t)&&n%i!==0?--r:r&&E(t,function(t){e.node(t).rank+=r})})}function _n(e,t,n,r){var i={width:0,height:0};return arguments.length>=4&&(i.rank=n,i.order=r),Y(e,`border`,i,t)}function vn(e){return R(A(e.nodes(),function(t){var n=e.node(t).rank;if(!D(n))return n}))}function yn(e,t){var n={lhs:[],rhs:[]};return E(e,function(e){t(e)?n.lhs.push(e):n.rhs.push(e)}),n}function bn(e,t){var n=Qe();try{return t()}finally{console.log(e+` time: `+(Qe()-n)+`ms`)}}function xn(e,t){return t()}function Sn(e){function t(n){var r=e.children(n),i=e.node(n);if(r.length&&E(r,t),Object.prototype.hasOwnProperty.call(i,`minRank`)){i.borderLeft=[],i.borderRight=[];for(var a=i.minRank,o=i.maxRank+1;ao.lim&&(s=o,c=!0),V(x(t.edges(),function(t){return c===tr(e,e.node(t.v),s)&&c!==tr(e,e.node(t.w),s)}),function(e){return Z(t,e)})}function Qn(e,t,n,r){var i=n.v,a=n.w;e.removeEdge(i,a),e.setEdge(r.v,r.w,{}),Jn(e),Gn(e,t),$n(e,t)}function $n(e,t){var n=Wn(e,F(e.nodes(),function(e){return!t.node(e).parent}));n=n.slice(1),E(n,function(n){var r=e.node(n).parent,i=t.edge(n,r),a=!1;i||(i=t.edge(r,n),a=!0),t.node(n).rank=t.node(r).rank+(a?i.minlen:-i.minlen)})}function er(e,t,n){return e.hasEdge(t,n)}function tr(e,t,n){return n.low<=t.lim&&t.lim<=n.lim}function nr(e){switch(e.graph().ranker){case`network-simplex`:ar(e);break;case`tight-tree`:ir(e);break;case`longest-path`:rr(e);break;default:ar(e)}}var rr=Fn;function ir(e){Fn(e),In(e)}function ar(e){$(e)}function or(e){var t=Y(e,`root`,{},`_root`),n=cr(e),r=R(w(n))-1,i=2*r+1;e.graph().nestingRoot=t,E(e.edges(),function(t){e.edge(t).minlen*=i});var a=lr(e)+1;E(e.children(),function(o){sr(e,t,i,a,r,n,o)}),e.graph().nodeRankFactor=i}function sr(e,t,n,r,i,a,o){var s=e.children(o);if(!s.length){o!==t&&e.setEdge(t,o,{weight:0,minlen:n});return}var c=_n(e,`_bt`),l=_n(e,`_bb`),u=e.node(o);e.setParent(c,o),u.borderTop=c,e.setParent(l,o),u.borderBottom=l,E(s,function(s){sr(e,t,n,r,i,a,s);var u=e.node(s),d=u.borderTop?u.borderTop:s,f=u.borderBottom?u.borderBottom:s,p=u.borderTop?r:2*r,m=d===f?i-a[o]+1:1;e.setEdge(c,d,{weight:p,minlen:m,nestingEdge:!0}),e.setEdge(f,l,{weight:p,minlen:m,nestingEdge:!0})}),e.parent(o)||e.setEdge(t,c,{weight:0,minlen:i+a[o]})}function cr(e){var t={};function n(r,i){var a=e.children(r);a&&a.length&&E(a,function(e){n(e,i+1)}),t[r]=i}return E(e.children(),function(e){n(e,1)}),t}function lr(e){return T(e.edges(),function(t,n){return t+e.edge(n).weight},0)}function ur(e){var t=e.graph();e.removeNode(t.nestingRoot),delete t.nestingRoot,E(e.edges(),function(t){e.edge(t).nestingEdge&&e.removeEdge(t)})}function dr(e,t,n){var r={},i;E(n,function(n){for(var a=e.parent(n),o,s;a;){if(o=e.parent(a),o?(s=r[o],r[o]=a):(s=i,i=a),s&&s!==a){t.setEdge(s,a);return}a=o}})}function fr(e,t,n){var r=pr(e),i=new O({compound:!0}).setGraph({root:r}).setDefaultNodeLabel(function(t){return e.node(t)});return E(e.nodes(),function(a){var o=e.node(a),s=e.parent(a);(o.rank===t||o.minRank<=t&&t<=o.maxRank)&&(i.setNode(a),i.setParent(a,s||r),E(e[n](a),function(t){var n=t.v===a?t.w:t.v,r=i.edge(n,a),o=D(r)?0:r.weight;i.setEdge(n,a,{weight:e.edge(t).weight+o})}),Object.prototype.hasOwnProperty.call(o,`minRank`)&&i.setNode(a,{borderLeft:o.borderLeft[t],borderRight:o.borderRight[t]}))}),i}function pr(e){for(var t;e.hasNode(t=q(`_root`)););return t}function mr(e,t){for(var n=0,r=1;r0;)t%2&&(n+=s[t+1]),t=t-1>>1,s[t]+=e.weight;c+=e.weight*n})),c}function gr(e){var t={},n=x(e.nodes(),function(t){return!e.children(t).length}),r=A(G(R(A(n,function(t){return e.node(t).rank}))+1),function(){return[]});function i(n){ht(t,n)||(t[n]=!0,r[e.node(n).rank].push(n),E(e.successors(n),i))}return E(K(n,function(t){return e.node(t).rank}),i),r}function _r(e,t){return A(t,function(t){var n=e.inEdges(t);if(n.length){var r=T(n,function(t,n){var r=e.edge(n),i=e.node(n.v);return{sum:t.sum+r.weight*i.order,weight:t.weight+r.weight}},{sum:0,weight:0});return{v:t,barycenter:r.sum/r.weight,weight:r.weight}}else return{v:t}})}function vr(e,t){var n={};return E(e,function(e,t){var r=n[e.v]={indegree:0,in:[],out:[],vs:[e.v],i:t};D(e.barycenter)||(r.barycenter=e.barycenter,r.weight=e.weight)}),E(t.edges(),function(e){var t=n[e.v],r=n[e.w];!D(t)&&!D(r)&&(r.indegree++,t.out.push(n[e.w]))}),yr(x(n,function(e){return!e.indegree}))}function yr(e){var t=[];function n(e){return function(t){t.merged||(D(t.barycenter)||D(e.barycenter)||t.barycenter>=e.barycenter)&&br(e,t)}}function r(t){return function(n){n.in.push(t),--n.indegree===0&&e.push(n)}}for(;e.length;){var i=e.pop();t.push(i),E(i.in.reverse(),n(i)),E(i.out,r(i))}return A(x(t,function(e){return!e.merged}),function(e){return W(e,[`vs`,`i`,`barycenter`,`weight`])})}function br(e,t){var n=0,r=0;e.weight&&(n+=e.barycenter*e.weight,r+=e.weight),t.weight&&(n+=t.barycenter*t.weight,r+=t.weight),e.vs=t.vs.concat(e.vs),e.barycenter=n/r,e.weight=r,e.i=Math.min(t.i,e.i),t.merged=!0}function xr(e,t){var n=yn(e,function(e){return Object.prototype.hasOwnProperty.call(e,`barycenter`)}),r=n.lhs,i=K(n.rhs,function(e){return-e.i}),a=[],o=0,s=0,c=0;r.sort(Cr(!!t)),c=Sr(a,i,c),E(r,function(e){c+=e.vs.length,a.push(e.vs),o+=e.barycenter*e.weight,s+=e.weight,c=Sr(a,i,c)});var l={vs:N(a)};return s&&(l.barycenter=o/s,l.weight=s),l}function Sr(e,t,n){for(var r;t.length&&(r=P(t)).i<=n;)t.pop(),e.push(r.vs),n++;return n}function Cr(e){return function(t,n){return t.barycentern.barycenter?1:e?n.i-t.i:t.i-n.i}}function wr(e,t,n,r){var i=e.children(t),a=e.node(t),o=a?a.borderLeft:void 0,s=a?a.borderRight:void 0,c={};o&&(i=x(i,function(e){return e!==o&&e!==s}));var l=_r(e,i);E(l,function(t){if(e.children(t.v).length){var i=wr(e,t.v,n,r);c[t.v]=i,Object.prototype.hasOwnProperty.call(i,`barycenter`)&&Er(t,i)}});var u=vr(l,n);Tr(u,c);var d=xr(u,r);if(o&&(d.vs=N([o,d.vs,s]),e.predecessors(o).length)){var f=e.node(e.predecessors(o)[0]),p=e.node(e.predecessors(s)[0]);Object.prototype.hasOwnProperty.call(d,`barycenter`)||(d.barycenter=0,d.weight=0),d.barycenter=(d.barycenter*d.weight+f.order+p.order)/(d.weight+2),d.weight+=2}return d}function Tr(e,t){E(e,function(e){e.vs=N(e.vs.map(function(e){return t[e]?t[e].vs:e}))})}function Er(e,t){D(e.barycenter)?(e.barycenter=t.barycenter,e.weight=t.weight):(e.barycenter=(e.barycenter*e.weight+t.barycenter*t.weight)/(e.weight+t.weight),e.weight+=t.weight)}function Dr(e){var t=vn(e),n=Or(e,G(1,t+1),`inEdges`),r=Or(e,G(t-1,-1,-1),`outEdges`),i=gr(e);Ar(e,i);for(var a=1/0,o,s=0,c=0;c<4;++s,++c){kr(s%2?n:r,s%4>=2),i=X(e);var l=mr(e,i);lo||s>t[c].lim));for(l=c,c=r;(c=e.parent(c))!==l;)a.push(c);return{path:i.concat(a.reverse()),lca:l}}function Nr(e){var t={},n=0;function r(i){var a=n;E(e.children(i),r),t[i]={low:a,lim:n++}}return E(e.children(),r),t}function Pr(e,t){var n={};function r(t,r){var i=0,a=0,o=t.length,s=P(r);return E(r,function(t,c){var l=Ir(e,t),u=l?e.node(l).order:o;(l||t===s)&&(E(r.slice(a,c+1),function(t){E(e.predecessors(t),function(r){var a=e.node(r),o=a.order;(oo)&&Lr(n,t,s)})})}function i(t,n){var i=-1,a,o=0;return E(n,function(s,c){if(e.node(s).dummy===`border`){var l=e.predecessors(s);l.length&&(a=e.node(l[0]).order,r(n,o,c,i,a),o=c,i=a)}r(n,o,n.length,a,t.length)}),n}return T(t,i),n}function Ir(e,t){if(e.node(t).dummy)return F(e.predecessors(t),function(t){return e.node(t).dummy})}function Lr(e,t,n){if(t>n){var r=t;t=n,n=r}Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,configurable:!0,value:{},writable:!0});var i=e[t];Object.defineProperty(i,n,{enumerable:!0,configurable:!0,value:!0,writable:!0})}function Rr(e,t,n){if(t>n){var r=t;t=n,n=r}return!!e[t]&&Object.prototype.hasOwnProperty.call(e[t],n)}function zr(e,t,n,r){var i={},a={},o={};return E(t,function(e){E(e,function(e,t){i[e]=e,a[e]=e,o[e]=t})}),E(t,function(e){var t=-1;E(e,function(e){var s=r(e);if(s.length){s=K(s,function(e){return o[e]});for(var c=(s.length-1)/2,l=Math.floor(c),u=Math.ceil(c);l<=u;++l){var d=s[l];a[e]===e&&t{var t=n(` buildLayoutGraph`,()=>si(e));n(` runLayout`,()=>Zr(t,n)),n(` updateInputGraph`,()=>Qr(e,t))})}function Zr(e,t){t(` makeSpaceForEdgeLabels`,()=>ci(e)),t(` removeSelfEdges`,()=>_i(e)),t(` acyclic`,()=>ln(e)),t(` nestingGraph.run`,()=>or(e)),t(` rank`,()=>nr(pn(e))),t(` injectEdgeLabelProxies`,()=>li(e)),t(` removeEmptyRanks`,()=>gn(e)),t(` nestingGraph.cleanup`,()=>ur(e)),t(` normalizeRanks`,()=>hn(e)),t(` assignRankMinMax`,()=>ui(e)),t(` removeEdgeLabelProxies`,()=>di(e)),t(` normalize.run`,()=>Mn(e)),t(` parentDummyChains`,()=>jr(e)),t(` addBorderSegments`,()=>Sn(e)),t(` order`,()=>Dr(e)),t(` insertSelfEdges`,()=>vi(e)),t(` adjustCoordinateSystem`,()=>wn(e)),t(` position`,()=>Jr(e)),t(` positionSelfEdges`,()=>yi(e)),t(` removeBorderNodes`,()=>gi(e)),t(` normalize.undo`,()=>Pn(e)),t(` fixupEdgeLabelCoords`,()=>mi(e)),t(` undoCoordinateSystem`,()=>Tn(e)),t(` translateGraph`,()=>fi(e)),t(` assignNodeIntersects`,()=>pi(e)),t(` reversePoints`,()=>hi(e)),t(` acyclic.undo`,()=>dn(e))}function Qr(e,t){E(e.nodes(),function(n){var r=e.node(n),i=t.node(n);r&&(r.x=i.x,r.y=i.y,t.children(n).length&&(r.width=i.width,r.height=i.height))}),E(e.edges(),function(n){var r=e.edge(n),i=t.edge(n);r.points=i.points,Object.prototype.hasOwnProperty.call(i,`x`)&&(r.x=i.x,r.y=i.y)}),e.graph().width=t.graph().width,e.graph().height=t.graph().height}var $r=[`nodesep`,`edgesep`,`ranksep`,`marginx`,`marginy`],ei={ranksep:50,edgesep:20,nodesep:50,rankdir:`tb`},ti=[`acyclicer`,`ranker`,`rankdir`,`align`],ni=[`width`,`height`],ri={width:0,height:0},ii=[`minlen`,`weight`,`width`,`height`,`labeloffset`],ai={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:`r`},oi=[`labelpos`];function si(e){var t=new O({multigraph:!0,compound:!0}),n=xi(e.graph());return t.setGraph(z({},ei,bi(n,$r),W(n,ti))),E(e.nodes(),function(n){var r=xi(e.node(n));t.setNode(n,tt(bi(r,ni),ri)),t.setParent(n,e.parent(n))}),E(e.edges(),function(n){var r=xi(e.edge(n));t.setEdge(n,z({},ai,bi(r,ii),W(r,oi)))}),t}function ci(e){var t=e.graph();t.ranksep/=2,E(e.edges(),function(n){var r=e.edge(n);r.minlen*=2,r.labelpos.toLowerCase()!==`c`&&(t.rankdir===`TB`||t.rankdir===`BT`?r.width+=r.labeloffset:r.height+=r.labeloffset)})}function li(e){E(e.edges(),function(t){var n=e.edge(t);if(n.width&&n.height){var r=e.node(t.v);Y(e,`edge-proxy`,{rank:(e.node(t.w).rank-r.rank)/2+r.rank,e:t},`_ep`)}})}function ui(e){var t=0;E(e.nodes(),function(n){var r=e.node(n);r.borderTop&&(r.minRank=e.node(r.borderTop).rank,r.maxRank=e.node(r.borderBottom).rank,t=R(t,r.maxRank))}),e.graph().maxRank=t}function di(e){E(e.nodes(),function(t){var n=e.node(t);n.dummy===`edge-proxy`&&(e.edge(n.e).labelRank=n.rank,e.removeNode(t))})}function fi(e){var t=1/0,n=0,r=1/0,i=0,a=e.graph(),o=a.marginx||0,s=a.marginy||0;function c(e){var a=e.x,o=e.y,s=e.width,c=e.height;t=Math.min(t,a-s/2),n=Math.max(n,a+s/2),r=Math.min(r,o-c/2),i=Math.max(i,o+c/2)}E(e.nodes(),function(t){c(e.node(t))}),E(e.edges(),function(t){var n=e.edge(t);Object.prototype.hasOwnProperty.call(n,`x`)&&c(n)}),t-=o,r-=s,E(e.nodes(),function(n){var i=e.node(n);i.x-=t,i.y-=r}),E(e.edges(),function(n){var i=e.edge(n);E(i.points,function(e){e.x-=t,e.y-=r}),Object.prototype.hasOwnProperty.call(i,`x`)&&(i.x-=t),Object.prototype.hasOwnProperty.call(i,`y`)&&(i.y-=r)}),a.width=n-t+o,a.height=i-r+s}function pi(e){E(e.edges(),function(t){var n=e.edge(t),r=e.node(t.v),i=e.node(t.w),a,o;n.points?(a=n.points[0],o=n.points[n.points.length-1]):(n.points=[],a=i,o=r),n.points.unshift(mn(r,a)),n.points.push(mn(i,o))})}function mi(e){E(e.edges(),function(t){var n=e.edge(t);if(Object.prototype.hasOwnProperty.call(n,`x`))switch((n.labelpos===`l`||n.labelpos===`r`)&&(n.width-=n.labeloffset),n.labelpos){case`l`:n.x-=n.width/2+n.labeloffset;break;case`r`:n.x+=n.width/2+n.labeloffset;break}})}function hi(e){E(e.edges(),function(t){var n=e.edge(t);n.reversed&&n.points.reverse()})}function gi(e){E(e.nodes(),function(t){if(e.children(t).length){var n=e.node(t),r=e.node(n.borderTop),i=e.node(n.borderBottom),a=e.node(P(n.borderLeft)),o=e.node(P(n.borderRight));n.width=Math.abs(o.x-a.x),n.height=Math.abs(i.y-r.y),n.x=a.x+n.width/2,n.y=r.y+n.height/2}}),E(e.nodes(),function(t){e.node(t).dummy===`border`&&e.removeNode(t)})}function _i(e){E(e.edges(),function(t){if(t.v===t.w){var n=e.node(t.v);n.selfEdges||=[],n.selfEdges.push({e:t,label:e.edge(t)}),e.removeEdge(t)}})}function vi(e){E(X(e),function(t){var n=0;E(t,function(t,r){var i=e.node(t);i.order=r+n,E(i.selfEdges,function(t){Y(e,`selfedge`,{width:t.label.width,height:t.label.height,rank:i.rank,order:r+ ++n,e:t.e,label:t.label},`_se`)}),delete i.selfEdges})})}function yi(e){E(e.nodes(),function(t){var n=e.node(t);if(n.dummy===`selfedge`){var r=e.node(n.e.v),i=r.x+r.width/2,a=r.y,o=n.x-i,s=r.height/2;e.setEdge(n.e,n.label),e.removeNode(t),n.label.points=[{x:i+2*o/3,y:a-s},{x:i+5*o/6,y:a-s},{x:i+o,y:a},{x:i+5*o/6,y:a+s},{x:i+2*o/3,y:a+s}],n.label.x=n.x,n.label.y=n.y}})}function bi(e,t){return I(W(e,t),Number)}function xi(e){var t={};return E(e,function(e,n){t[n.toLowerCase()]=e}),t}export{Xr as t}; \ No newline at end of file diff --git a/dist-desktop/assets/defaultLocale-C8Fc0cco.js b/dist-desktop/assets/defaultLocale-C8Fc0cco.js new file mode 100644 index 0000000..f76e162 --- /dev/null +++ b/dist-desktop/assets/defaultLocale-C8Fc0cco.js @@ -0,0 +1 @@ +function e(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString(`en`).replace(/,/g,``):e.toString(10)}function t(e,t){if(!isFinite(e)||e===0)return null;var n=(e=t?e.toExponential(t-1):e.toExponential()).indexOf(`e`),r=e.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+e.slice(n+1)]}function n(e){return e=t(Math.abs(e)),e?e[1]:NaN}function r(e,t){return function(n,r){for(var i=n.length,a=[],o=0,s=e[0],c=0;i>0&&s>0&&(c+s+1>r&&(s=Math.max(1,r-c)),a.push(n.substring(i-=s,i+s)),!((c+=s+1)>r));)s=e[o=(o+1)%e.length];return a.reverse().join(t)}}function i(e){return function(t){return t.replace(/[0-9]/g,function(t){return e[+t]})}}var a=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function o(e){if(!(t=a.exec(e)))throw Error(`invalid format: `+e);var t;return new s({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}o.prototype=s.prototype;function s(e){this.fill=e.fill===void 0?` `:e.fill+``,this.align=e.align===void 0?`>`:e.align+``,this.sign=e.sign===void 0?`-`:e.sign+``,this.symbol=e.symbol===void 0?``:e.symbol+``,this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?``:e.type+``}s.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?`0`:``)+(this.width===void 0?``:Math.max(1,this.width|0))+(this.comma?`,`:``)+(this.precision===void 0?``:`.`+Math.max(0,this.precision|0))+(this.trim?`~`:``)+this.type};function c(e){out:for(var t=e.length,n=1,r=-1,i;n0&&(r=0);break}return r>0?e.slice(0,r)+e.slice(i+1):e}var l;function u(e,n){var r=t(e,n);if(!r)return l=void 0,e.toPrecision(n);var i=r[0],a=r[1],o=a-(l=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,s=i.length;return o===s?i:o>s?i+Array(o-s+1).join(`0`):o>0?i.slice(0,o)+`.`+i.slice(o):`0.`+Array(1-o).join(`0`)+t(e,Math.max(0,n+o-1))[0]}function d(e,n){var r=t(e,n);if(!r)return e+``;var i=r[0],a=r[1];return a<0?`0.`+Array(-a).join(`0`)+i:i.length>a+1?i.slice(0,a+1)+`.`+i.slice(a+1):i+Array(a-i.length+2).join(`0`)}var f={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+``,d:e,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>d(e*100,t),r:d,s:u,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function p(e){return e}var m=Array.prototype.map,h=[`y`,`z`,`a`,`f`,`p`,`n`,`µ`,`m`,``,`k`,`M`,`G`,`T`,`P`,`E`,`Z`,`Y`];function g(e){var t=e.grouping===void 0||e.thousands===void 0?p:r(m.call(e.grouping,Number),e.thousands+``),a=e.currency===void 0?``:e.currency[0]+``,s=e.currency===void 0?``:e.currency[1]+``,u=e.decimal===void 0?`.`:e.decimal+``,d=e.numerals===void 0?p:i(m.call(e.numerals,String)),g=e.percent===void 0?`%`:e.percent+``,_=e.minus===void 0?`−`:e.minus+``,v=e.nan===void 0?`NaN`:e.nan+``;function y(e,n){e=o(e);var r=e.fill,i=e.align,p=e.sign,m=e.symbol,y=e.zero,b=e.width,x=e.comma,S=e.precision,C=e.trim,w=e.type;w===`n`?(x=!0,w=`g`):f[w]||(S===void 0&&(S=12),C=!0,w=`g`),(y||r===`0`&&i===`=`)&&(y=!0,r=`0`,i=`=`);var T=(n&&n.prefix!==void 0?n.prefix:``)+(m===`$`?a:m===`#`&&/[boxX]/.test(w)?`0`+w.toLowerCase():``),E=(m===`$`?s:/[%p]/.test(w)?g:``)+(n&&n.suffix!==void 0?n.suffix:``),D=f[w],O=/[defgprs%]/.test(w);S=S===void 0?6:/[gprs]/.test(w)?Math.max(1,Math.min(21,S)):Math.max(0,Math.min(20,S));function k(e){var n=T,a=E,o,s,f;if(w===`c`)a=D(e)+a,e=``;else{e=+e;var m=e<0||1/e<0;if(e=isNaN(e)?v:D(Math.abs(e),S),C&&(e=c(e)),m&&+e==0&&p!==`+`&&(m=!1),n=(m?p===`(`?p:_:p===`-`||p===`(`?``:p)+n,a=(w===`s`&&!isNaN(e)&&l!==void 0?h[8+l/3]:``)+a+(m&&p===`(`?`)`:``),O){for(o=-1,s=e.length;++of||f>57){a=(f===46?u+e.slice(o+1):e.slice(o))+a,e=e.slice(0,o);break}}}x&&!y&&(e=t(e,1/0));var g=n.length+e.length+a.length,k=g>1)+n+e+a+k.slice(g);break;default:e=k+n+e+a;break}return d(e)}return k.toString=function(){return e+``},k}function b(e,t){var r=Math.max(-8,Math.min(8,Math.floor(n(t)/3)))*3,i=10**-r,a=y((e=o(e),e.type=`f`,e),{suffix:h[8+r/3]});return function(e){return a(i*e)}}return{format:y,formatPrefix:b}}var _,v,y;b({thousands:`,`,grouping:[3],currency:[`$`,``]});function b(e){return _=g(e),v=_.format,y=_.formatPrefix,_}export{n as i,y as n,o as r,v as t}; \ No newline at end of file diff --git a/dist-desktop/assets/diagram-FQU43EPY-C8Vn5v8I.js b/dist-desktop/assets/diagram-FQU43EPY-C8Vn5v8I.js new file mode 100644 index 0000000..9aa866f --- /dev/null +++ b/dist-desktop/assets/diagram-FQU43EPY-C8Vn5v8I.js @@ -0,0 +1,3 @@ +import{T as e}from"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n,p as r}from"./src-UMNXGZaF.js";import{H as i,K as a,U as o,Y as s,a as c,b as l,f as u,v as d,w as f,x as p,y as m,z as h}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{_ as g,i as ee,t as te}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as ne}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as re}from"./mermaid-parser.core-Z7xZAZRH.js";var _=`position frame`,v=`frame positioned`,y=`position relation`,b=`relation positioned`,ie=t(function(e){n.debug(`options str`,e)},`setOptions`),ae=t(function(){return{}},`getOptions`),oe=t(function(){x(),c()},`clear`);function x(){S={}}t(x,`reset`);var se=u.eventmodeling,ce=t(()=>ee({...se,...l().eventmodeling}),`getConfig`),S={};function C(){let e=le,{ast:t}=S,r=E();if(!t)throw Error(`No data for EventModel`);return t.frames.forEach((i,a)=>{let o=N(i,t.dataEntities,r);e=q(e,{$kind:_,index:a,frame:i,textProps:o});let s;B(i)?(n.debug(`source frame`,i.sourceFrames),s=t.frames.filter(e=>i.sourceFrames.some(t=>t.$refText===e.name)),s.forEach(t=>{e=q(e,{$kind:y,index:a,frame:i,sourceFrame:t})})):e=q(e,{$kind:y,index:a,frame:i})}),e={...e,sortedSwimlanesArray:L(e.swimlanes)},e}t(C,`getState`);function w(e){S.ast=e}t(w,`setAst`);var T={swimlaneMinHeight:70,swimlanePadding:15,swimlaneGap:10,boxPadding:10,boxOverlap:90,boxDefaultY:0,boxMinWidth:80,boxMaxWidth:450,boxMinHeight:80,boxMaxHeight:750,contentStartX:250,textMaxWidth:430,boxTextFontWeight:`bold`,boxTextPadding:10,swimlaneTextFontWeight:`bold`,labelUiAutomation:`UI/Automation`,labelUiAutomationPrefix:`UI/A: `,labelCommandReadModel:`Command/Read Model`,labelCommandReadModelPrefix:`C/RM: `,labelEvents:`Events`,labelEventsPrefix:`Stream: `};function E(){return T}t(E,`getDiagramProps`);var le={boxes:[],swimlanes:{},relations:[],maxR:0,sortedSwimlanesArray:[]};function D(e){let t=e.split(`.`);if(t.length===2)return t[0]}t(D,`extractNamespace`);function O(e){let t=e.split(`.`);return t.length===2?t[1]:e}t(O,`extractName`);function k(e,t){if(!(!t||t.length===0))return Object.values(e).find(e=>e.namespace===t)}t(k,`findSwimlaneByNamespace`);function A(e,t,n){return Math.max(t,...Object.keys(e).filter(e=>{let r=Number.parseInt(e);return r>t&&rNumber.parseInt(e)))+1}t(A,`findNextAvailableIndex`);function j(e,t){let n=D(e.entityIdentifier),r=k(t,n);switch(e.modelEntityType){case`ui`:case`pcr`:case`processor`:return r?{index:r.index,label:r.namespace||T.labelUiAutomation}:n?{index:A(t,0,100),label:T.labelUiAutomationPrefix+n}:{index:0,label:T.labelUiAutomation};case`rmo`:case`readmodel`:case`cmd`:case`command`:return r?{index:r.index,label:r.namespace||T.labelCommandReadModel}:n?{index:A(t,100,200),label:T.labelCommandReadModelPrefix+n}:{index:100,label:T.labelCommandReadModel};default:return r?{index:r.index,label:r.namespace||T.labelEvents}:n?{index:A(t,200,300),label:T.labelEventsPrefix+n}:{index:200,label:T.labelEvents}}}t(j,`calculateSwimlaneProps`);function M(e){let{themeVariables:t}=l();switch(e.modelEntityType){case`ui`:return{fill:t.emUiFill??`white`,stroke:t.emUiStroke??`#dbdada`};case`pcr`:case`processor`:return{fill:t.emProcessorFill??`#edb3f6`,stroke:t.emProcessorStroke??`#b88cbf`};case`rmo`:case`readmodel`:return{fill:t.emReadModelFill??`#d3f1a2`,stroke:t.emReadModelStroke??`#a3b732`};case`cmd`:case`command`:return{fill:t.emCommandFill??`#bcd6fe`,stroke:t.emCommandStroke??`#679ac3`};case`evt`:case`event`:return{fill:t.emEventFill??`#ffb778`,stroke:t.emEventStroke??`#c19a0f`};default:return{fill:`red`,stroke:`black`}}}t(M,`calculateEntityVisualProps`);function N(e,t,r){let i=l(),a=h(O(e.entityIdentifier)??``,i),o,s={fontSize:16,fontWeight:700,fontFamily:`"trebuchet ms", verdana, arial, sans-serif`,joinWith:`
    `},c=`${g(a,r.textMaxWidth,s)}`;if(e.dataInlineValue&&(o=e.dataInlineValue,o=o.substring(o.indexOf(`{`)+1),o=o.substring(0,o.lastIndexOf(`}`)-1),o=h(o,i),o=g(o,r.textMaxWidth,s),o=o.replaceAll(` `,` `)),e.dataReference){let n=t.find(t=>t.name===e.dataReference?.$refText);n&&(o=n.dataBlockValue,o=o.substring(o.indexOf(`{ +`)+2),o=o.substring(0,o.lastIndexOf(`}`)-1),o=h(o,i),o=g(o,r.textMaxWidth,s),o=o.replaceAll(` `,` `),o+=`
    `)}let u=o!==void 0;u&&(c+=`

    ${o}`);let d={fontSize:s.fontSize,fontWeight:s.fontWeight,fontFamily:s.fontFamily},f=te(c,d),p=u?f.width/3:f.width,m={content:c,width:p,height:f.height};return n.debug(`[${e.name}] ${e.entityIdentifier} text`,m),m}t(N,`calculateTextProps`);function P(e,t){let n=t,r=M(n.frame),i={width:n.textProps.width+2*T.boxTextPadding,height:n.textProps.height+2*T.boxTextPadding};return[{$kind:v,frame:n.frame,index:n.index,visual:r,dimension:i,textProps:n.textProps}]}t(P,`decidePositionFrame`);function F(e,t,n){return t===void 0?T.contentStartX:t.index===e.index&&e.r?e.r+T.boxPadding:n===void 0?T.contentStartX:n.r-T.boxOverlap+T.boxPadding}t(F,`calculateX`);function I(e,t){let n=[...e.map(e=>e.r),t];return Math.max(...n)}t(I,`calculateMaxRight`);function L(e){return Object.values(e).sort((e,t)=>e.index-t.index)}t(L,`sortedSwimlanesArray`);function R(e,t){let n=t,r=j(n.frame,e.swimlanes),i;i=r.index in e.swimlanes?e.swimlanes[r.index]:{index:r.index,label:r.label,r:0,y:r.index*T.swimlaneMinHeight+T.swimlaneGap,height:T.swimlaneMinHeight,maxHeight:T.swimlaneMinHeight};let a=e.boxes.length>0?e.boxes[e.boxes.length-1]:void 0,o=e.previousSwimlaneNumber===void 0?void 0:e.swimlanes[e.previousSwimlaneNumber],s={width:Math.max(T.boxMinWidth,Math.min(T.boxMaxWidth,n.dimension.width))+2*T.boxPadding,height:Math.max(T.boxMinHeight,Math.min(T.boxMaxHeight,n.dimension.height))+2*T.boxPadding},c=F(i,o,a),l=c+s.width+T.boxPadding,u=I(Object.values(e.swimlanes),l);i.r=c+s.width,i.maxHeight=Math.max(i.maxHeight,s.height),i.height=Math.max(T.swimlaneMinHeight,i.maxHeight)+2*T.swimlanePadding;let d={x:c,y:T.swimlanePadding+i.y,r:l,dimension:s,leftSibling:!1,swimlane:i,visual:n.visual,text:n.textProps.content,frame:n.frame,index:n.index},f={...e,boxes:[...e.boxes,d],swimlanes:{...e.swimlanes,[`${i.index}`]:i},previousSwimlaneNumber:r.index,previousFrame:n.frame,maxR:u},p=L(f.swimlanes);p.length>0&&(p[0].y=0);for(let e=1;e0}t(B,`hasSourceFrame`);function V(e,t){if(t!=null)return e.find(e=>e.frame.name===t.name)}t(V,`findBoxByFrame`);function H(e,t,n){if(!(n<0))for(let r=n;r>=0;r--){let n=e[r];if(n.swimlane.index!==t)return n}}t(H,`findBoxByLineIndex`);function U(t,n){let r=n;if(e(r.frame)||z(r.index,r.frame))return[];let i=V(t.boxes,r.frame);if(i===void 0)throw Error(`Target box not found for frame ${r.frame.name}`);let a;return a=r.sourceFrame?V(t.boxes,r.sourceFrame):H(t.boxes,i.swimlane.index,r.index-1),a===void 0?[]:[{$kind:b,frame:r.frame,index:r.index,sourceBox:a,targetBox:i}]}t(U,`decidePositionRelation`);function W(e,t){let n=t,r={visual:{fill:`none`,stroke:`#000`},source:{x:n.sourceBox.x,y:n.sourceBox.y},target:{x:n.targetBox.x,y:n.targetBox.y},sourceBox:n.sourceBox,targetBox:n.targetBox};return{...e,relations:[...e.relations,r]}}t(W,`evolveRelationPositioned`);var ue={[_]:P,[y]:U},de={[v]:R,[b]:W};function G(e,t){let r=ue[t.$kind];if(r==null)return[];let i=r(e,t);return n.debug(`decided events`,i),i}t(G,`decide`);function K(e,t){let r=t.reduce((e,t)=>{let n=de[t.$kind];return n==null?e:n(e,t)},e);return n.debug(`evolve events`,{state:e,newState:r,events:t}),r}t(K,`evolve`);function q(e,t){return K(e,G(e,t))}t(q,`dispatch`);var J={getConfig:ce,setOptions:ie,getOptions:ae,clear:oe,setAccTitle:o,getAccTitle:m,getAccDescription:d,setAccDescription:i,setDiagramTitle:a,getDiagramTitle:f,setAst:w,getDiagramProps:E,getState:C},fe={parse:t(async e=>{let t=await re(`eventmodeling`,e);n.debug(t),J.setAst(t),ne(t,J)},`parse`)},Y=p()?.eventmodeling;function X(e,t){return n=>{let r=n.swimlane.y+t.swimlanePadding,i=e.append(`g`).attr(`class`,`em-box`);i.append(`rect`).attr(`x`,n.x).attr(`y`,r).attr(`rx`,`3`).attr(`width`,n.dimension.width).attr(`height`,n.dimension.height).attr(`stroke`,n.visual.stroke).attr(`fill`,n.visual.fill),i.append(`foreignObject`).attr(`x`,n.x+t.boxPadding).attr(`y`,r+10).attr(`width`,n.dimension.width-2*t.boxPadding).attr(`height`,n.dimension.height-2*t.boxPadding).append(`xhtml:div`).style(`display`,`table`).style(`height`,`100%`).style(`width`,`100%`).append(`span`).style(`display`,`table-cell`).style(`text-align`,`center`).style(`vertical-align`,`middle`).html(n.text)}}t(X,`renderD3Box`);function Z(e,t){return e>t}t(Z,`dirUpwards`);function Q(e,t,r,i){return a=>{let o=a.sourceBox.swimlane.y+t.swimlanePadding,s=a.targetBox.swimlane.y+t.swimlanePadding,c=Z(o,s),l=a.sourceBox.x+a.sourceBox.dimension.width*2/3,u=a.targetBox.x+a.targetBox.dimension.width/3,d,f;n.debug(`rendering relation up=${c} for `,{sourceBox:a.sourceBox,targetBox:a.targetBox}),c?(d=o,f=s+a.targetBox.dimension.height):(d=o+a.sourceBox.dimension.height,f=s);let p=i.emRelationStroke??a.visual.stroke;e.append(`path`).attr(`class`,`em-relation`).attr(`fill`,a.visual.fill).attr(`stroke`,p).attr(`stroke-width`,`1`).attr(`marker-end`,`url(#${r})`).attr(`d`,`M${l} ${d} L${u} ${f}`)}}t(Q,`renderD3Relation`);function $(e,t,n,r){return i=>{let a=e.append(`g`).attr(`class`,`em-swimlane`),o=r.emSwimlaneBackgroundOdd??`rgb(250,250,250)`,s=r.emSwimlaneBackgroundStroke??`rgb(240,240,240)`;a.append(`rect`).attr(`x`,0).attr(`y`,i.y).attr(`rx`,`3`).attr(`width`,t+n.swimlanePadding).attr(`height`,i.height).attr(`fill`,o).attr(`stroke`,s),a.append(`text`).attr(`font-weight`,n.swimlaneTextFontWeight).attr(`x`,30).attr(`y`,i.y+30).text(i.label)}}t($,`renderD3Swimlane`);var pe={parser:fe,db:J,renderer:{draw:t(function(e,t,i,a){if(n.debug(`in eventmodeling renderer`,e+` +`,`id:`,t,i),!Y)throw Error(`EventModeling config not found`);let o=a.db,{themeVariables:c,eventmodeling:l}=p(),u=r(`[id="${t}"]`),d=o.getDiagramProps(),f=o.getState(),m=`em-arrowhead-${t}`,h=c.emArrowhead??`#000000`;f.sortedSwimlanesArray.forEach($(u,f.maxR,d,c)),f.boxes.forEach(X(u,d)),f.relations.forEach(Q(u,d,m,c)),u.append(`defs`).append(`marker`).attr(`id`,m).attr(`markerWidth`,`10`).attr(`markerHeight`,`7`).attr(`refX`,`10`).attr(`refY`,`3.5`).attr(`orient`,`auto`).append(`polygon`).attr(`points`,`0 0, 10 3.5, 0 7`).attr(`fill`,h),s(void 0,u,l?.padding??30,l?.useMaxWidth)},`draw`)},styles:t(e=>``,`getStyles`)};export{pe as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/diagram-G47NLZAW-B5XCVQOu.js b/dist-desktop/assets/diagram-G47NLZAW-B5XCVQOu.js new file mode 100644 index 0000000..e6a7d73 --- /dev/null +++ b/dist-desktop/assets/diagram-G47NLZAW-B5XCVQOu.js @@ -0,0 +1,24 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{D as r,H as i,K as a,U as o,a as s,b as c,c as l,f as u,v as d,w as f,y as p}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as m}from"./ordinal-hYBb2elL.js";import{t as h}from"./defaultLocale-C8Fc0cco.js";import{i as g}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as _}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as v}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as y}from"./mermaid-parser.core-Z7xZAZRH.js";import{t as b}from"./chunk-VR4S4FIN-BTo4eV3J.js";import{i as x,n as S}from"./chunk-C7G6YPKG-DW-1jWUA.js";function C(e){var t=0,n=e.children,r=n&&n.length;if(!r)t=1;else for(;--r>=0;)t+=n[r].value;e.value=t}function w(){return this.eachAfter(C)}function T(e,t){let n=-1;for(let r of this)e.call(t,r,++n,this);return this}function E(e,t){for(var n=this,r=[n],i,a,o=-1;n=r.pop();)if(e.call(t,n,++o,this),i=n.children)for(a=i.length-1;a>=0;--a)r.push(i[a]);return this}function D(e,t){for(var n=this,r=[n],i=[],a,o,s,c=-1;n=r.pop();)if(i.push(n),a=n.children)for(o=0,s=a.length;o=0;)n+=r[i].value;t.value=n})}function A(e){return this.eachBefore(function(t){t.children&&t.children.sort(e)})}function j(e){for(var t=this,n=M(t,e),r=[t];t!==n;)t=t.parent,r.push(t);for(var i=r.length;e!==n;)r.splice(i,0,e),e=e.parent;return r}function M(e,t){if(e===t)return e;var n=e.ancestors(),r=t.ancestors(),i=null;for(e=n.pop(),t=r.pop();e===t;)i=e,e=n.pop(),t=r.pop();return i}function N(){for(var e=this,t=[e];e=e.parent;)t.push(e);return t}function P(){return Array.from(this)}function F(){var e=[];return this.eachBefore(function(t){t.children||e.push(t)}),e}function I(){var e=this,t=[];return e.each(function(n){n!==e&&t.push({source:n.parent,target:n})}),t}function*L(){var e=this,t,n=[e],r,i,a;do for(t=n.reverse(),n=[];e=t.pop();)if(yield e,r=e.children)for(i=0,a=r.length;i=0;--s)i.push(a=o[s]=new W(o[s])),a.parent=r,a.depth=r.depth+1;return n.eachBefore(U)}function z(){return R(this).eachBefore(H)}function B(e){return e.children}function V(e){return Array.isArray(e)?e[1]:null}function H(e){e.data.value!==void 0&&(e.value=e.data.value),e.data=e.data.data}function U(e){var t=0;do e.height=t;while((e=e.parent)&&e.height<++t)}function W(e){this.data=e,this.depth=this.height=0,this.parent=null}W.prototype=R.prototype={constructor:W,count:w,each:T,eachAfter:D,eachBefore:E,find:O,sum:k,sort:A,path:j,ancestors:N,descendants:P,leaves:F,links:I,copy:z,[Symbol.iterator]:L};function G(e){if(typeof e!=`function`)throw Error();return e}function K(){return 0}function q(e){return function(){return e}}function J(e){e.x0=Math.round(e.x0),e.y0=Math.round(e.y0),e.x1=Math.round(e.x1),e.y1=Math.round(e.y1)}function ee(e,t,n,r,i){for(var a=e.children,o,s=-1,c=a.length,l=e.value&&(r-t)/e.value;++sv&&(v=l),S=g*g*x,y=Math.max(v/S,S/_),y>b){g-=l;break}b=y}o.push(c={value:g,dice:p1?t:1)},n})(ne);function ae(){var e=ie,t=!1,n=1,r=1,i=[0],a=K,o=K,s=K,c=K,l=K;function u(e){return e.x0=e.y0=0,e.x1=n,e.y1=r,e.eachBefore(d),i=[0],t&&e.eachBefore(J),e}function d(t){var n=i[t.depth],r=t.x0+n,u=t.y0+n,d=t.x1-n,f=t.y1-n;d{S(e)&&(n?.textStyles?n.textStyles.push(e):n.textStyles=[e]),n?.styles?n.styles.push(e):n.styles=[e]}),this.classes.set(e,n)}getClasses(){return this.classes}getStylesForClass(e){return this.classes.get(e)?.styles??[]}clear(){s(),this.nodes=[],this.levels=new Map,this.outerNodes=[],this.classes=new Map,this.root=void 0}};function X(e){if(!e.length)return[];let t=[],n=[];return e.forEach(e=>{let r={name:e.name,children:e.type===`Leaf`?void 0:[]};for(r.classSelector=e?.classSelector,e?.cssCompiledStyles&&(r.cssCompiledStyles=e.cssCompiledStyles),e.type===`Leaf`&&e.value!==void 0&&(r.value=e.value);n.length>0&&n[n.length-1].level>=e.level;)n.pop();if(n.length===0)t.push(r);else{let e=n[n.length-1].node;e.children?e.children.push(r):e.children=[r]}e.type!==`Leaf`&&n.push({node:r,level:e.level})}),t}e(X,`buildHierarchy`);var oe=e((t,n)=>{v(t,n);let r=[];for(let e of t.TreemapRows??[])e.$type===`ClassDefStatement`&&n.addClass(e.className??``,e.styleText??``);for(let e of t.TreemapRows??[]){let t=e.item;if(!t)continue;let i=e.indent?parseInt(e.indent):0,a=se(t),o=t.classSelector?n.getStylesForClass(t.classSelector):[],s=o.length>0?o:void 0,c={level:i,name:a,type:t.$type,value:t.value,classSelector:t.classSelector,cssCompiledStyles:s};r.push(c)}let i=X(r),a=e((e,t)=>{for(let r of e)n.addNode(r,t),r.children&&r.children.length>0&&a(r.children,t+1)},`addNodesRecursively`);a(i,0)},`populate`),se=e(e=>e.name?String(e.name):``,`getItemName`),Z={parser:{yy:void 0},parse:e(async e=>{try{let n=await y(`treemap`,e);t.debug(`Treemap AST:`,n);let r=Z.parser?.yy;if(!(r instanceof Y))throw Error(`parser.parser?.yy was not a TreemapDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);oe(n,r)}catch(e){throw t.error(`Error parsing treemap:`,e),e}},`parse`)},ce=10,Q=10,$=25,le={draw:e((r,i,a,o)=>{let s=o.db,u=s.getConfig(),d=u.padding??ce,f=s.getDiagramTitle(),p=s.getRoot(),{themeVariables:g}=c();if(!p)return;let v=f?30:0,y=_(i),S=u.nodeWidth?u.nodeWidth*Q:960,C=u.nodeHeight?u.nodeHeight*Q:500,w=S,T=C+v;y.attr(`viewBox`,`0 0 ${w} ${T}`),l(y,T,w,u.useMaxWidth);let E;try{let t=u.valueFormat||`,`;if(t===`$0,0`)E=e(e=>`$`+h(`,`)(e),`valueFormat`);else if(t.startsWith(`$`)&&t.includes(`,`)){let n=/\.\d+/.exec(t),r=n?n[0]:``;E=e(e=>`$`+h(`,`+r)(e),`valueFormat`)}else if(t.startsWith(`$`)){let n=t.substring(1);E=e(e=>`$`+h(n||``)(e),`valueFormat`)}else E=h(t)}catch(e){t.error(`Error creating format function:`,e),E=h(`,`)}let D=m().range([`transparent`,g.cScale0,g.cScale1,g.cScale2,g.cScale3,g.cScale4,g.cScale5,g.cScale6,g.cScale7,g.cScale8,g.cScale9,g.cScale10,g.cScale11]),O=m().range([`transparent`,g.cScalePeer0,g.cScalePeer1,g.cScalePeer2,g.cScalePeer3,g.cScalePeer4,g.cScalePeer5,g.cScalePeer6,g.cScalePeer7,g.cScalePeer8,g.cScalePeer9,g.cScalePeer10,g.cScalePeer11]),k=m().range([g.cScaleLabel0,g.cScaleLabel1,g.cScaleLabel2,g.cScaleLabel3,g.cScaleLabel4,g.cScaleLabel5,g.cScaleLabel6,g.cScaleLabel7,g.cScaleLabel8,g.cScaleLabel9,g.cScaleLabel10,g.cScaleLabel11]);f&&y.append(`text`).attr(`x`,w/2).attr(`y`,v/2).attr(`class`,`treemapTitle`).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(f);let A=y.append(`g`).attr(`transform`,`translate(0, ${v})`).attr(`class`,`treemapContainer`),j=R(p).sum(e=>e.value??0).sort((e,t)=>(t.value??0)-(e.value??0)),M=ae().size([S,C]).paddingTop(e=>e.children&&e.children.length>0?$+Q:0).paddingInner(d).paddingLeft(e=>e.children&&e.children.length>0?Q:0).paddingRight(e=>e.children&&e.children.length>0?Q:0).paddingBottom(e=>e.children&&e.children.length>0?Q:0).round(!0)(j),N=M.descendants().filter(e=>e.children&&e.children.length>0),P=A.selectAll(`.treemapSection`).data(N).enter().append(`g`).attr(`class`,`treemapSection`).attr(`transform`,e=>`translate(${e.x0},${e.y0})`);P.append(`rect`).attr(`width`,e=>e.x1-e.x0).attr(`height`,$).attr(`class`,`treemapSectionHeader`).attr(`fill`,`none`).attr(`fill-opacity`,.6).attr(`stroke-width`,.6).attr(`style`,e=>e.depth===0?`display: none;`:``),P.append(`clipPath`).attr(`id`,(e,t)=>`clip-section-${i}-${t}`).append(`rect`).attr(`width`,e=>Math.max(0,e.x1-e.x0-12)).attr(`height`,$),P.append(`rect`).attr(`width`,e=>e.x1-e.x0).attr(`height`,e=>e.y1-e.y0).attr(`class`,(e,t)=>`treemapSection section${t}`).attr(`fill`,e=>D(e.data.name)).attr(`fill-opacity`,.6).attr(`stroke`,e=>O(e.data.name)).attr(`stroke-width`,2).attr(`stroke-opacity`,.4).attr(`style`,e=>{if(e.depth===0)return`display: none;`;let t=x({cssCompiledStyles:e.data.cssCompiledStyles});return t.nodeStyles+`;`+t.borderStyles.join(`;`)}),P.append(`text`).attr(`class`,`treemapSectionLabel`).attr(`x`,6).attr(`y`,$/2).attr(`dominant-baseline`,`middle`).text(e=>e.depth===0?``:e.data.name).attr(`font-weight`,`bold`).attr(`clip-path`,(e,t)=>`url(#clip-section-${i}-${t})`).attr(`style`,e=>e.depth===0?`display: none;`:`dominant-baseline: middle; font-size: 12px; fill:`+k(e.data.name)+`; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`)).each(function(e){if(e.depth===0)return;let t=n(this),r=e.data.name;t.text(r);let i=e.x1-e.x0,a;a=u.showValues!==!1&&e.value?i-10-30-10-6:i-6-6;let o=Math.max(15,a),s=t.node();if(s.getComputedTextLength()>o){let e=r;for(;e.length>0;){if(e=r.substring(0,e.length-1),e.length===0){t.text(`...`),s.getComputedTextLength()>o&&t.text(``);break}if(t.text(e+`...`),s.getComputedTextLength()<=o)break}}}),u.showValues!==!1&&P.append(`text`).attr(`class`,`treemapSectionValue`).attr(`x`,e=>e.x1-e.x0-10).attr(`y`,$/2).attr(`text-anchor`,`end`).attr(`dominant-baseline`,`middle`).text(e=>e.value?E(e.value):``).attr(`font-style`,`italic`).attr(`style`,e=>e.depth===0?`display: none;`:`text-anchor: end; dominant-baseline: middle; font-size: 10px; fill:`+k(e.data.name)+`; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`));let F=M.leaves(),I=F.length>20,L=I?16:38,z=I?14:28,B=I?4:8,V=I?4:6,H=I?2:4,U=I?8:10,W=I?1:2,G=A.selectAll(`.treemapLeafGroup`).data(F).enter().append(`g`).attr(`class`,(e,t)=>`treemapNode treemapLeafGroup leaf${t}${e.data.classSelector?` ${e.data.classSelector}`:``}x`).attr(`transform`,e=>`translate(${e.x0},${e.y0})`);G.append(`rect`).attr(`width`,e=>e.x1-e.x0).attr(`height`,e=>e.y1-e.y0).attr(`class`,`treemapLeaf`).attr(`fill`,e=>e.parent?D(e.parent.data.name):D(e.data.name)).attr(`style`,e=>x({cssCompiledStyles:e.data.cssCompiledStyles}).nodeStyles).attr(`fill-opacity`,.3).attr(`stroke`,e=>e.parent?D(e.parent.data.name):D(e.data.name)).attr(`stroke-width`,3),G.append(`clipPath`).attr(`id`,(e,t)=>`clip-${i}-${t}`).append(`rect`).attr(`width`,e=>Math.max(0,e.x1-e.x0-4)).attr(`height`,e=>Math.max(0,e.y1-e.y0-4)),G.append(`text`).attr(`class`,`treemapLabel`).attr(`x`,e=>(e.x1-e.x0)/2).attr(`y`,e=>(e.y1-e.y0)/2).attr(`style`,e=>`text-anchor: middle; dominant-baseline: middle; font-size: ${L}px;fill:`+k(e.data.name)+`;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`)).attr(`clip-path`,(e,t)=>`url(#clip-${i}-${t})`).text(e=>e.data.name).each(function(e){let t=n(this),r=e.x1-e.x0,i=e.y1-e.y0,a=t.node(),o=r-2*H,s=i-2*H;if(oo&&c>B;)c--,t.style(`font-size`,`${c}px`);let u=Math.max(V,Math.min(z,Math.round(c*l))),d=c+W+u;for(;d>s&&c>B&&(c--,u=Math.max(V,Math.min(z,Math.round(c*l))),!(uo||c(e.x1-e.x0)/2).attr(`y`,function(e){return(e.y1-e.y0)/2}).attr(`style`,e=>`text-anchor: middle; dominant-baseline: hanging; font-size: ${z}px;fill:`+k(e.data.name)+`;`+x({cssCompiledStyles:e.data.cssCompiledStyles}).labelStyles.replace(`color:`,`fill:`)).attr(`clip-path`,(e,t)=>`url(#clip-${i}-${t})`).text(e=>e.value?E(e.value):``).each(function(e){let t=n(this),r=this.parentNode;if(!r){t.style(`display`,`none`);return}let i=n(r).select(`.treemapLabel`);if(i.empty()||i.style(`display`)===`none`){t.style(`display`,`none`);return}let a=parseFloat(i.style(`font-size`)),o=Math.max(V,Math.min(z,Math.round(a*.6)));t.style(`font-size`,`${o}px`);let s=(e.y1-e.y0)/2+a/2+W;t.attr(`y`,s);let c=e.x1-e.x0,l=e.y1-e.y0-4,u=c-2*H;t.node().getComputedTextLength()>u||s+o>l||o{let t=g(r(),c().themeVariables),n=g(ue,e),i=n.titleColor??t.titleColor,a=n.labelColor??t.textColor,o=n.valueColor??t.textColor;return` + .treemapNode.section { + stroke: ${n.sectionStrokeColor}; + stroke-width: ${n.sectionStrokeWidth}; + fill: ${n.sectionFillColor}; + } + .treemapNode.leaf { + stroke: ${n.leafStrokeColor}; + stroke-width: ${n.leafStrokeWidth}; + fill: ${n.leafFillColor}; + } + .treemapLabel { + fill: ${a}; + font-size: ${n.labelFontSize}; + } + .treemapValue { + fill: ${o}; + font-size: ${n.valueFontSize}; + } + .treemapTitle { + fill: ${i}; + font-size: ${n.titleFontSize}; + } + `},`getStyles`)};export{de as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/diagram-NH7WQ7WH-Btsva5Mx.js b/dist-desktop/assets/diagram-NH7WQ7WH-Btsva5Mx.js new file mode 100644 index 0000000..0d4adff --- /dev/null +++ b/dist-desktop/assets/diagram-NH7WQ7WH-Btsva5Mx.js @@ -0,0 +1,24 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,b as o,c as s,f as c,v as l,w as u,y as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as f}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as p}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as m}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as h}from"./mermaid-parser.core-Z7xZAZRH.js";var g=c.packet,_=class{constructor(){this.packet=[],this.setAccTitle=i,this.getAccTitle=d,this.setDiagramTitle=r,this.getDiagramTitle=u,this.getAccDescription=l,this.setAccDescription=n}static{e(this,`PacketDB`)}getConfig(){let e=f({...g,...o().packet});return e.showBits&&(e.paddingY+=10),e}getPacket(){return this.packet}pushWord(e){e.length>0&&this.packet.push(e)}clear(){a(),this.packet=[]}},v=1e4,y=e((e,n)=>{m(e,n);let r=-1,i=[],a=1,{bitsPerRow:o}=n.getConfig();for(let{start:s,end:c,bits:l,label:u}of e.blocks){if(s!==void 0&&c!==void 0&&c{if(e.start===void 0)throw Error(`start should have been set during first phase`);if(e.end===void 0)throw Error(`end should have been set during first phase`);if(e.start>e.end)throw Error(`Block start ${e.start} is greater than block end ${e.end}.`);if(e.end+1<=t*n)return[e,void 0];let r=t*n-1,i=t*n;return[{start:e.start,end:r,label:e.label,bits:r-e.start},{start:i,end:e.end,label:e.label,bits:e.end-i}]},`getNextFittingBlock`),x={parser:{yy:void 0},parse:e(async e=>{let n=await h(`packet`,e),r=x.parser?.yy;if(!(r instanceof _))throw Error(`parser.parser?.yy was not a PacketDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);t.debug(n),y(n,r)},`parse`)},S=e((e,t,n,r)=>{let i=r.db,a=i.getConfig(),{rowHeight:o,paddingY:c,bitWidth:l,bitsPerRow:u}=a,d=i.getPacket(),f=i.getDiagramTitle(),m=o+c,h=m*(d.length+1)-(f?0:o),g=l*u+2,_=p(t);_.attr(`viewBox`,`0 0 ${g} ${h}`),s(_,h,g,a.useMaxWidth);for(let[e,t]of d.entries())C(_,t,e,a);_.append(`text`).text(f).attr(`x`,g/2).attr(`y`,h-m/2).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`).attr(`class`,`packetTitle`)},`draw`),C=e((e,t,n,{rowHeight:r,paddingX:i,paddingY:a,bitWidth:o,bitsPerRow:s,showBits:c})=>{let l=e.append(`g`),u=n*(r+a)+a;for(let e of t){let t=e.start%s*o+1,n=(e.end-e.start+1)*o-i;if(l.append(`rect`).attr(`x`,t).attr(`y`,u).attr(`width`,n).attr(`height`,r).attr(`class`,`packetBlock`),l.append(`text`).attr(`x`,t+n/2).attr(`y`,u+r/2).attr(`class`,`packetLabel`).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`).text(e.label),!c)continue;let a=e.end===e.start,d=u-2;l.append(`text`).attr(`x`,t+(a?n/2:0)).attr(`y`,d).attr(`class`,`packetByte start`).attr(`dominant-baseline`,`auto`).attr(`text-anchor`,a?`middle`:`start`).text(e.start),a||l.append(`text`).attr(`x`,t+n).attr(`y`,d).attr(`class`,`packetByte end`).attr(`dominant-baseline`,`auto`).attr(`text-anchor`,`end`).text(e.end)}},`drawWord`),w={draw:S},T={byteFontSize:`10px`,startByteColor:`black`,endByteColor:`black`,labelColor:`black`,labelFontSize:`12px`,titleColor:`black`,titleFontSize:`14px`,blockStrokeColor:`black`,blockStrokeWidth:`1`,blockFillColor:`#efefef`},E={parser:x,get db(){return new _},renderer:w,styles:e(({packet:e}={})=>{let t=f(T,e);return` + .packetByte { + font-size: ${t.byteFontSize}; + } + .packetByte.start { + fill: ${t.startByteColor}; + } + .packetByte.end { + fill: ${t.endByteColor}; + } + .packetLabel { + fill: ${t.labelColor}; + font-size: ${t.labelFontSize}; + } + .packetTitle { + fill: ${t.titleColor}; + font-size: ${t.titleFontSize}; + } + .packetBlock { + stroke: ${t.blockStrokeColor}; + stroke-width: ${t.blockStrokeWidth}; + fill: ${t.blockFillColor}; + } + `},`styles`)};export{E as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/diagram-OA4YK3LP-B1b6NwZz.js b/dist-desktop/assets/diagram-OA4YK3LP-B1b6NwZz.js new file mode 100644 index 0000000..338e2b6 --- /dev/null +++ b/dist-desktop/assets/diagram-OA4YK3LP-B1b6NwZz.js @@ -0,0 +1,30 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,b as o,c as s,f as c,v as l,w as u,y as d,z as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-Z7xZAZRH.js";import{r as _,t as v}from"./chunk-HOUHSVGY-iJuv90UH.js";import{t as y}from"./chunk-2Q5K7J3B-C1jixKkw.js";var b=/[─━│┃└┗├┣]/,x=/[└┗├┣]/,S=/[─━]/,C=/^[\s│┃]+$/,w=/^\s*(title[\t ]|accTitle[\t ]*:|accDescr[\t ]*[:{])/,T=/^\s*%%/,E=` `;function D(e){return e.some(e=>b.test(e))}e(D,`isBoxDrawingFormat`);function O(e){for(let t of e){let e=x.exec(t);if(e?.index&&e.index>0)return e.index}return 4}e(O,`inferSegmentWidth`);function k(e,t){return e.replace(/\bline\s+(\d+)\b/gi,(e,n)=>{let r=parseInt(n,10),i=t.get(r);return i?`line ${i}`:e})}e(k,`remapErrorLines`);function A(e){let t=e.split(` +`),n=new Map,r=-1;for(let[e,n]of t.entries())if(n.trim()===`treeView-beta`){r=e;break}if(r===-1)return{text:e,lineMap:n};let i=[];for(let e=r+1;e({cnt:1,stack:[{id:0,level:-1,name:`/`,nodeType:`directory`,children:[]}]})),M=e(()=>{j.reset(),a()},`clear`),N=e(()=>j.records.stack[0],`getRoot`),P=e(()=>j.records.cnt,`getCount`),F=c.treeView,I={clear:M,addNode:e((e,t,n,r,i,a)=>{for(;e<=j.records.stack[j.records.stack.length-1].level;)j.records.stack.pop();let o={id:j.records.cnt++,level:e,name:t,nodeType:n,icon:i,cssClass:r,description:a,children:[]};j.records.stack[j.records.stack.length-1].children.push(o),j.records.stack.push(o)},`addNode`),getRoot:N,getCount:P,getConfig:e(()=>p(F,o().treeView),`getConfig`),getAccTitle:d,getAccDescription:l,getDiagramTitle:u,setAccDescription:n,setAccTitle:i,setDiagramTitle:r},L=e(e=>{h(e,I);for(let t of e.nodes){let e=typeof t.indent==`number`?t.indent:0,n=t.name,r=n.endsWith(`/`);r&&(n=n.slice(0,-1));let i=r?`directory`:`file`,a=t.classAnnotation||void 0,s=t.iconAnnotation,c=s===void 0?void 0:s||`none`,l=t.descAnnotation||void 0,u=l?f(l,o()):void 0;I.addNode(e,n,i,a,c,u)}},`populate`),R={parse:e(async e=>{let{text:n,lineMap:r}=A(e);try{let e=await g(`treeView`,n);t.debug(e),L(e)}catch(e){throw r.size>0&&e instanceof Error&&(e.message=k(e.message,r)),e}},`parse`)},z={prefix:`mermaid-treeview`,height:24,width:24,icons:{folder:{body:``},file:{body:``}}};function B(e,t){let n=t?.filenameIcons?.[e];if(n)return n;let r=e.lastIndexOf(`.`);if(r>0){let n=e.substring(r).toLowerCase(),i=t?.extensionIcons;return i?.[n]??i?.[n.slice(1)]}}e(B,`detectIcon`);function V(e,t){return e.includes(`:`)?e:e in z.icons||!t?`${z.prefix}:${e}`:`${t}:${e}`}e(V,`qualifyIcon`);function H(e,t){if(e.icon!==`none`){if(e.icon)return V(e.icon,t.defaultIconPack);if(t.showIcons){if(e.nodeType===`file`){let n=B(e.name,t);if(n===`none`)return;if(n)return V(n,t.defaultIconPack)}return`${z.prefix}:${e.nodeType===`directory`?`folder`:`file`}`}}}e(H,`getNodeIcon`),_([{name:z.prefix,icons:z}]);var U=14,W=4,G=16,K=e((e,t)=>`tv-icon-${e}-${t.replace(/[^\w-]/g,`-`)}`,`iconSymbolId`),q=e(async(t,n,r,i)=>{let a=new Set,o=e(e=>{let t=H(e,r);t&&a.add(t),e.children.forEach(o)},`collect`);if(o(n),a.size===0)return;let s=await Promise.all([...a].map(async e=>({icon:e,svg:await v(e,{height:U,width:U})}))),c=t.append(`defs`);for(let{icon:e,svg:t}of s)c.append(`g`).attr(`id`,K(i,e)).html(t)},`injectIconDefs`),J=e((e,t,n,r,i,a)=>{let o=r.append(`g`),s=`treeView-node-label`;n.nodeType===`directory`&&(s+=` treeView-node-dir`),n.cssClass&&(s+=` ${n.cssClass}`);let c=U+W,l=H(n,i),u=l!==void 0;l&&o.append(`use`).attr(`xlink:href`,`#${K(a,l)}`).attr(`x`,e+i.paddingX).attr(`y`,t+i.paddingY).attr(`class`,`treeView-node-icon`);let d=o.append(`text`).text(n.name).attr(`dominant-baseline`,`middle`).attr(`class`,s),{height:f,width:p}=d.node().getBBox(),m=f+i.paddingY*2,h=e+i.paddingX+(u?c:0);d.attr(`x`,h),d.attr(`y`,t+m/2);let g=h+p;return n.BBox={x:e,y:t,width:p+i.paddingX*2+(u?c:0),height:m},n.cssClass?.split(/\s+/).includes(`highlight`)&&o.insert(`rect`,`:first-child`).attr(`x`,e).attr(`y`,t+1).attr(`width`,0).attr(`height`,m-2).attr(`rx`,3).attr(`class`,`treeView-highlight-bg`),{node:n,nodeGroup:o,labelRightEdge:g,centerY:t+m/2}},`positionLabel`),Y=e((e,t,n,r,i,a)=>e.append(`line`).attr(`x1`,t).attr(`y1`,n).attr(`x2`,r).attr(`y2`,i).attr(`stroke-width`,a).attr(`class`,`treeView-node-line`),`positionLine`),X=e((t,n,r,i)=>{let a=0,o=0,s=[],c=e((e,t,n,r)=>{let c=r*(n.rowIndent+n.paddingX),l=J(c,a,t,e,n,i);s.push(l);let{height:u,width:d}=t.BBox;Y(e,c-n.rowIndent,a+u/2,c,a+u/2,n.lineThickness),o=Math.max(o,c+d),a+=u},`drawNode`),l=e((e,n=0)=>{c(t,e,r,n),e.children.forEach(e=>{l(e,n+1)});let{x:i,y:a,height:o}=e.BBox;if(e.children.length){let{y:n,height:s}=e.children[e.children.length-1].BBox;Y(t,i+r.paddingX,a+o,i+r.paddingX,n+s/2+r.lineThickness/2,r.lineThickness)}},`processNode`);l(n);let u=s.filter(e=>e.node.description);if(u.length>0){let e=Math.max(...s.map(e=>e.labelRightEdge))+G;for(let t of u){let n=t.nodeGroup.append(`text`).text(t.node.description).attr(`dominant-baseline`,`middle`).attr(`class`,`treeView-node-description`).attr(`x`,e).attr(`y`,t.centerY).node().getBBox();o=Math.max(o,e+n.width+r.paddingX)}}for(let e of s)if(e.node.cssClass?.split(/\s+/).includes(`highlight`)){let t=e.nodeGroup.select(`.treeView-highlight-bg`);if(!t.empty()){let n=o-e.node.BBox.x+8;t.attr(`width`,n),o=Math.max(o,e.node.BBox.x+n+2)}}return{totalHeight:a,totalWidth:o}},`drawTree`),Z={draw:e(async(e,n,r,i)=>{t.debug(`Rendering treeView diagram +`+e);let a=i.db,o=a.getRoot(),c=a.getConfig(),l=m(n);await q(l,o,c,n);let u=l.append(`g`);u.attr(`class`,`tree-view`);let{totalHeight:d,totalWidth:f}=X(u,o,c,n);l.attr(`viewBox`,`-${c.lineThickness/2} 0 ${f} ${d}`),s(l,d,f,c.useMaxWidth)},`draw`)},Q={labelFontSize:`16px`,labelColor:`black`,lineColor:`black`,iconColor:`#546e7a`,descriptionColor:`#6a9955`,highlightBg:`rgba(255, 193, 7, 0.15)`,highlightStroke:`#ffc107`},$={db:I,renderer:Z,parser:R,styles:e(({treeView:e})=>{let{labelFontSize:t,labelColor:n,lineColor:r,iconColor:i,descriptionColor:a,highlightBg:o,highlightStroke:s}=p(Q,e);return` + .treeView-node-label { + font-size: ${t}; + fill: ${n}; + white-space: pre; + } + .treeView-node-dir { + font-weight: bold; + } + .treeView-node-line { + stroke: ${r}; + } + .treeView-node-icon { + color: ${i}; + } + .treeView-node-description { + font-size: ${t}; + fill: ${a}; + font-style: italic; + white-space: pre; + } + .treeView-highlight-bg { + fill: ${o}; + stroke: ${s}; + stroke-width: 1; + } + `},`styles`)};export{$ as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/diagram-WEI45ONY-DzxhBgyP.js b/dist-desktop/assets/diagram-WEI45ONY-DzxhBgyP.js new file mode 100644 index 0000000..bf57f53 --- /dev/null +++ b/dist-desktop/assets/diagram-WEI45ONY-DzxhBgyP.js @@ -0,0 +1,41 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,f as l,v as u,w as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-Z7xZAZRH.js";var _={showLegend:!0,ticks:5,max:null,min:0,graticule:`circle`},v={axes:[],curves:[],options:_},y=structuredClone(v),b=l.radar,x=e(()=>p({...b,...s().radar}),`getConfig`),S=e(()=>y.axes,`getAxes`),C=e(()=>y.curves,`getCurves`),w=e(()=>y.options,`getOptions`),T=e(e=>{y.axes=e.map(e=>({name:e.name,label:e.label??e.name}))},`setAxes`),E=e(e=>{y.curves=e.map(e=>({name:e.name,label:e.label??e.name,entries:D(e.entries)}))},`setCurves`),D=e(e=>{if(e[0].axis==null)return e.map(e=>e.value);let t=S();if(t.length===0)throw Error(`Axes must be populated before curves for reference entries`);return t.map(t=>{let n=e.find(e=>e.axis?.$refText===t.name);if(n===void 0)throw Error(`Missing entry for axis `+t.label);return n.value})},`computeCurveEntries`),O={getAxes:S,getCurves:C,getOptions:w,setAxes:T,setCurves:E,setOptions:e(e=>{let t=e.reduce((e,t)=>(e[t.name]=t,e),{});y.options={showLegend:t.showLegend?.value??_.showLegend,ticks:t.ticks?.value??_.ticks,max:t.max?.value??_.max,min:t.min?.value??_.min,graticule:t.graticule?.value??_.graticule}},`setOptions`),getConfig:x,clear:e(()=>{o(),y=structuredClone(v)},`clear`),setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:d,getAccDescription:u,setAccDescription:r},k=e(e=>{h(e,O);let{axes:t,curves:n,options:r}=e;O.setAxes(t),O.setCurves(n),O.setOptions(r)},`populate`),A={parse:e(async e=>{let n=await g(`radar`,e);t.debug(n),k(n)},`parse`)},j=e((e,t,n,r)=>{let i=r.db,a=i.getAxes(),o=i.getCurves(),s=i.getOptions(),c=i.getConfig(),l=i.getDiagramTitle(),u=M(m(t),c),d=s.max??Math.max(...o.map(e=>Math.max(...e.entries))),f=s.min,p=Math.min(c.width,c.height)/2;N(u,a,p,s.ticks,s.graticule),P(u,a,p,c),F(u,a,o,f,d,s.graticule,c),R(u,o,s.showLegend,c),u.append(`text`).attr(`class`,`radarTitle`).text(l).attr(`x`,0).attr(`y`,-c.height/2-c.marginTop)},`draw`),M=e((e,t)=>{let n=t.width+t.marginLeft+t.marginRight,r=t.height+t.marginTop+t.marginBottom,i={x:t.marginLeft+t.width/2,y:t.marginTop+t.height/2};return c(e,r,n,t.useMaxWidth??!0),e.attr(`viewBox`,`0 0 ${n} ${r}`).attr(`overflow`,`visible`),e.append(`g`).attr(`transform`,`translate(${i.x}, ${i.y})`)},`drawFrame`),N=e((e,t,n,r,i)=>{if(i===`circle`)for(let t=0;t{let n=2*t*Math.PI/i-Math.PI/2;return`${o*Math.cos(n)},${o*Math.sin(n)}`}).join(` `);e.append(`polygon`).attr(`points`,s).attr(`class`,`radarGraticule`)}}},`drawGraticule`),P=e((e,t,n,r)=>{let i=t.length;for(let a=0;a.01?`start`:c<-.01?`end`:`middle`,d=l>.01?`hanging`:l<-.01?`auto`:`central`;e.append(`text`).text(o).attr(`x`,n*r.axisLabelFactor*c+4*c).attr(`y`,n*r.axisLabelFactor*l+4*l).attr(`text-anchor`,u).attr(`dominant-baseline`,d).attr(`class`,`radarAxisLabel`)}},`drawAxes`);function F(e,t,n,r,i,a,o){let s=t.length,c=Math.min(o.width,o.height)/2;n.forEach((t,n)=>{if(t.entries.length!==s)return;let l=t.entries.map((e,t)=>{let n=2*Math.PI*t/s-Math.PI/2,a=I(e,r,i,c);return{x:a*Math.cos(n),y:a*Math.sin(n)}});a===`circle`?e.append(`path`).attr(`d`,L(l,o.curveTension)).attr(`class`,`radarCurve-${n}`):a===`polygon`&&e.append(`polygon`).attr(`points`,l.map(e=>`${e.x},${e.y}`).join(` `)).attr(`class`,`radarCurve-${n}`)})}e(F,`drawCurves`);function I(e,t,n,r){return r*(Math.min(Math.max(e,t),n)-t)/(n-t)}e(I,`relativeRadius`);function L(e,t){let n=e.length,r=`M${e[0].x},${e[0].y}`;for(let i=0;i{let r=e.append(`g`).attr(`transform`,`translate(${i}, ${a+n*20})`);r.append(`rect`).attr(`width`,12).attr(`height`,12).attr(`class`,`radarLegendBox-${n}`),r.append(`text`).attr(`x`,16).attr(`y`,0).attr(`class`,`radarLegendText`).text(t.label)})}e(R,`drawLegend`);var z={draw:j},B=e((e,t)=>{let n=``;for(let r=0;r{let t=p(n(),s().themeVariables);return{themeVariables:t,radarOptions:p(t.radar,e)}},`buildRadarStyleOptions`),H={parser:A,db:O,renderer:z,styles:e(({radar:e}={})=>{let{themeVariables:t,radarOptions:n}=V(e);return` + .radarTitle { + font-size: ${t.fontSize}; + color: ${t.titleColor}; + dominant-baseline: hanging; + text-anchor: middle; + } + .radarAxisLine { + stroke: ${n.axisColor}; + stroke-width: ${n.axisStrokeWidth}; + } + .radarAxisLabel { + font-size: ${n.axisLabelFontSize}px; + color: ${n.axisColor}; + } + .radarGraticule { + fill: ${n.graticuleColor}; + fill-opacity: ${n.graticuleOpacity}; + stroke: ${n.graticuleColor}; + stroke-width: ${n.graticuleStrokeWidth}; + } + .radarLegendText { + text-anchor: start; + font-size: ${n.legendFontSize}px; + dominant-baseline: hanging; + } + ${B(t,n)} + `},`styles`)};export{H as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/dist-qx0Iv9vM.js b/dist-desktop/assets/dist-qx0Iv9vM.js new file mode 100644 index 0000000..d02cb33 --- /dev/null +++ b/dist-desktop/assets/dist-qx0Iv9vM.js @@ -0,0 +1 @@ +import{t as e}from"./rolldown-runtime-aKtaBQYM.js";var t=Math.abs,n=Math.atan2,r=Math.cos,i=Math.max,a=Math.min,o=Math.sin,s=Math.sqrt,c=1e-12,l=Math.PI,u=l/2,d=2*l;function f(e){return e>1?0:e<-1?l:Math.acos(e)}function p(e){return e>=1?u:e<=-1?-u:Math.asin(e)}var m=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BLANK_URL=e.relativeFirstCharacters=e.whitespaceEscapeCharsRegex=e.urlSchemeRegex=e.ctrlCharactersRegex=e.htmlCtrlEntityRegex=e.htmlEntitiesRegex=e.invalidProtocolRegex=void 0,e.invalidProtocolRegex=/^([^\w]*)(javascript|data|vbscript)/im,e.htmlEntitiesRegex=/&#(\w+)(^\w|;)?/g,e.htmlCtrlEntityRegex=/&(newline|tab);/gi,e.ctrlCharactersRegex=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,e.urlSchemeRegex=/^.+(:|:)/gim,e.whitespaceEscapeCharsRegex=/(\\|%5[cC])((%(6[eE]|72|74))|[nrt])/g,e.relativeFirstCharacters=[`.`,`/`],e.BLANK_URL=`about:blank`})),h=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.sanitizeUrl=o;var t=m();function n(e){return t.relativeFirstCharacters.indexOf(e[0])>-1}function r(e){return e.replace(t.ctrlCharactersRegex,``).replace(t.htmlEntitiesRegex,function(e,t){return String.fromCharCode(t)})}function i(e){return URL.canParse(e)}function a(e){try{return decodeURIComponent(e)}catch{return e}}function o(e){if(!e)return t.BLANK_URL;var o,s=a(e.trim());do s=r(s).replace(t.htmlCtrlEntityRegex,``).replace(t.ctrlCharactersRegex,``).replace(t.whitespaceEscapeCharsRegex,``).trim(),s=a(s),o=s.match(t.ctrlCharactersRegex)||s.match(t.htmlEntitiesRegex)||s.match(t.htmlCtrlEntityRegex)||s.match(t.whitespaceEscapeCharsRegex);while(o&&o.length>0);var c=s;if(!c)return t.BLANK_URL;if(n(c))return c;var l=c.trimStart(),u=l.match(t.urlSchemeRegex);if(!u)return c;var d=u[0].toLowerCase().trim();if(t.invalidProtocolRegex.test(d))return t.BLANK_URL;var f=l.replace(/\\/g,`/`);if(d===`mailto:`||d.includes(`://`))return f;if(d===`http:`||d===`https:`){if(!i(f))return t.BLANK_URL;var p=new URL(f);return p.protocol=p.protocol.toLowerCase(),p.hostname=p.hostname.toLowerCase(),p.toString()}return f}}));export{n as a,u as c,l as d,o as f,p as i,i as l,d as m,t as n,r as o,s as p,f as r,c as s,h as t,a as u}; \ No newline at end of file diff --git a/dist-desktop/assets/ebnfDiagram-CCIWWBDH-DiJBARG_.js b/dist-desktop/assets/ebnfDiagram-CCIWWBDH-DiJBARG_.js new file mode 100644 index 0000000..bf5a450 --- /dev/null +++ b/dist-desktop/assets/ebnfDiagram-CCIWWBDH-DiJBARG_.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-U6XO7XAA-CR0BSRFR.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-Bju_yCKi.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-Z7xZAZRH.js";var c=e().RailroadEbnf.parser.LangiumParser,l=t(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformChoice`),u=t(e=>{let t=e.elements.map(p);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformSequence`),d=t(e=>{switch(e.$type){case`EbnfTerminal`:return{type:`terminal`,value:e.value};case`EbnfNonTerminal`:return{type:`nonterminal`,name:e.name};case`EbnfSpecial`:return{type:`special`,text:e.text};case`EbnfGroup`:return l(e.element);case`EbnfOptional`:return{type:`optional`,element:l(e.element)};case`EbnfRepetition`:return{type:`repetition`,element:l(e.element),min:0,max:1/0};default:throw Error(`Unsupported EBNF primary node: ${e.$type}`)}},`transformPrimary`),f=t((e,t)=>{switch(t.$type){case`EbnfOptionalPostfix`:return{type:`optional`,element:e};case`EbnfZeroOrMorePostfix`:return{type:`repetition`,element:e,min:0,max:1/0};case`EbnfOneOrMorePostfix`:return{type:`repetition`,element:e,min:1,max:1/0};case`EbnfExceptionPostfix`:return{type:`sequence`,elements:[e,{type:`terminal`,value:`-`},d(t.except)]};default:throw Error(`Unsupported EBNF postfix node: ${t.$type}`)}},`transformPostfix`),p=t(e=>e.postfixes.reduce((e,t)=>f(e,t),d(e.base)),`transformTerm`),m=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),h=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(m(e)))},`populateDb`),g={parser:{parse:t(e=>{a.clear(),n.debug(`[EBNF Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[EBNF Parser] Parsed rules:`,r.rules.length),h(r),n.debug(`[EBNF Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{g as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/erDiagram-Q63AITRT-BwmdWLsf.js b/dist-desktop/assets/erDiagram-Q63AITRT-BwmdWLsf.js new file mode 100644 index 0000000..9a5e629 --- /dev/null +++ b/dist-desktop/assets/erDiagram-Q63AITRT-BwmdWLsf.js @@ -0,0 +1,85 @@ +import{n as e,t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n,p as r}from"./src-UMNXGZaF.js";import{H as i,K as a,U as o,a as s,it as c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as p}from"./channel-C4fgBBJ4.js";import{c as m,g as h}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import{t as g}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as _}from"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import{r as v,t as y}from"./chunk-FWX5IMBZ-ComLEIwh.js";var b=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[6,8,10,22,24,26,28,33,34,35,36,37,40,43,44,48,50,51,52],r=[1,10],i=[1,11],a=[1,12],o=[1,13],s=[1,23],c=[1,24],l=[1,25],u=[1,26],d=[1,27],f=[1,19],p=[1,28],m=[1,29],h=[1,20],g=[1,18],_=[1,21],v=[1,22],y=[1,36],b=[1,37],x=[1,38],S=[1,39],C=[1,40],w=[6,8,10,13,15,17,20,21,22,24,26,28,33,34,35,36,37,40,43,44,48,50,51,52,66,67,68,69,70],T=[1,45],E=[1,46],D=[1,55],O=[40,48,50,51,52,71,72],k=[1,66],A=[1,64],j=[1,61],M=[1,65],N=[1,67],P=[6,8,10,13,17,22,24,26,28,33,34,35,36,37,40,41,42,43,44,48,49,50,51,52,66,67,68,69,70],F=[66,67,68,69,70],I=[1,85],L=[1,84],R=[1,82],z=[1,83],B=[6,10,42,47],V=[6,10,13,41,42,47,48,49],H=[1,93],U=[1,92],W=[1,91],G=[19,58],K=[1,102],q=[1,101],J=[19,58,61,63],Y={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,ER_DIAGRAM:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NEWLINE:10,entityName:11,relSpec:12,COLON:13,role:14,STYLE_SEPARATOR:15,idList:16,BLOCK_START:17,attributes:18,BLOCK_STOP:19,SQS:20,SQE:21,title:22,title_value:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,direction:29,classDefStatement:30,classStatement:31,styleStatement:32,direction_tb:33,direction_bt:34,direction_rl:35,direction_lr:36,CLASSDEF:37,stylesOpt:38,separator:39,UNICODE_TEXT:40,STYLE_TEXT:41,COMMA:42,CLASS:43,STYLE:44,style:45,styleComponent:46,SEMI:47,NUM:48,BRKT:49,ENTITY_NAME:50,DECIMAL_NUM:51,ENTITY_ONE:52,attribute:53,attributeType:54,attributeName:55,attributeKeyTypeList:56,attributeComment:57,ATTRIBUTE_WORD:58,"?":59,attributeKeyType:60,",":61,ATTRIBUTE_KEY:62,COMMENT:63,cardinality:64,relType:65,ZERO_OR_ONE:66,ZERO_OR_MORE:67,ONE_OR_MORE:68,ONLY_ONE:69,MD_PARENT:70,NON_IDENTIFYING:71,IDENTIFYING:72,WORD:73,$accept:0,$end:1},terminals_:{2:`error`,4:`ER_DIAGRAM`,6:`EOF`,8:`SPACE`,10:`NEWLINE`,13:`COLON`,15:`STYLE_SEPARATOR`,17:`BLOCK_START`,19:`BLOCK_STOP`,20:`SQS`,21:`SQE`,22:`title`,23:`title_value`,24:`acc_title`,25:`acc_title_value`,26:`acc_descr`,27:`acc_descr_value`,28:`acc_descr_multiline_value`,33:`direction_tb`,34:`direction_bt`,35:`direction_rl`,36:`direction_lr`,37:`CLASSDEF`,40:`UNICODE_TEXT`,41:`STYLE_TEXT`,42:`COMMA`,43:`CLASS`,44:`STYLE`,47:`SEMI`,48:`NUM`,49:`BRKT`,50:`ENTITY_NAME`,51:`DECIMAL_NUM`,52:`ENTITY_ONE`,58:`ATTRIBUTE_WORD`,59:`?`,61:`,`,62:`ATTRIBUTE_KEY`,63:`COMMENT`,66:`ZERO_OR_ONE`,67:`ZERO_OR_MORE`,68:`ONE_OR_MORE`,69:`ONLY_ONE`,70:`MD_PARENT`,71:`NON_IDENTIFYING`,72:`IDENTIFYING`,73:`WORD`},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[9,5],[9,9],[9,7],[9,7],[9,4],[9,6],[9,3],[9,5],[9,1],[9,3],[9,7],[9,9],[9,6],[9,8],[9,4],[9,6],[9,2],[9,2],[9,2],[9,1],[9,1],[9,1],[9,1],[9,1],[29,1],[29,1],[29,1],[29,1],[30,4],[16,1],[16,1],[16,3],[16,3],[31,3],[32,4],[38,1],[38,3],[45,1],[45,2],[39,1],[39,1],[39,1],[46,1],[46,1],[46,1],[46,1],[11,1],[11,1],[11,1],[11,1],[11,1],[18,1],[18,2],[53,2],[53,3],[53,3],[53,4],[54,1],[54,2],[55,1],[56,1],[56,3],[60,1],[57,1],[12,3],[64,1],[64,1],[64,1],[64,1],[64,1],[65,1],[65,1],[14,1],[14,1],[14,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:break;case 2:this.$=[];break;case 3:a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 5:this.$=a[s];break;case 6:case 7:this.$=[];break;case 8:r.addEntity(a[s-4]),r.addEntity(a[s-2]),r.addRelationship(a[s-4],a[s],a[s-2],a[s-3]);break;case 9:r.addEntity(a[s-8]),r.addEntity(a[s-4]),r.addRelationship(a[s-8],a[s],a[s-4],a[s-5]),r.setClass([a[s-8]],a[s-6]),r.setClass([a[s-4]],a[s-2]);break;case 10:r.addEntity(a[s-6]),r.addEntity(a[s-2]),r.addRelationship(a[s-6],a[s],a[s-2],a[s-3]),r.setClass([a[s-6]],a[s-4]);break;case 11:r.addEntity(a[s-6]),r.addEntity(a[s-4]),r.addRelationship(a[s-6],a[s],a[s-4],a[s-5]),r.setClass([a[s-4]],a[s-2]);break;case 12:r.addEntity(a[s-3]),r.addAttributes(a[s-3],a[s-1]);break;case 13:r.addEntity(a[s-5]),r.addAttributes(a[s-5],a[s-1]),r.setClass([a[s-5]],a[s-3]);break;case 14:r.addEntity(a[s-2]);break;case 15:r.addEntity(a[s-4]),r.setClass([a[s-4]],a[s-2]);break;case 16:r.addEntity(a[s]);break;case 17:r.addEntity(a[s-2]),r.setClass([a[s-2]],a[s]);break;case 18:r.addEntity(a[s-6],a[s-4]),r.addAttributes(a[s-6],a[s-1]);break;case 19:r.addEntity(a[s-8],a[s-6]),r.addAttributes(a[s-8],a[s-1]),r.setClass([a[s-8]],a[s-3]);break;case 20:r.addEntity(a[s-5],a[s-3]);break;case 21:r.addEntity(a[s-7],a[s-5]),r.setClass([a[s-7]],a[s-2]);break;case 22:r.addEntity(a[s-3],a[s-1]);break;case 23:r.addEntity(a[s-5],a[s-3]),r.setClass([a[s-5]],a[s]);break;case 24:case 25:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 26:case 27:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 32:r.setDirection(`TB`);break;case 33:r.setDirection(`BT`);break;case 34:r.setDirection(`RL`);break;case 35:r.setDirection(`LR`);break;case 36:this.$=a[s-3],r.addClass(a[s-2],a[s-1]);break;case 37:case 38:case 59:case 68:this.$=[a[s]];break;case 39:case 40:this.$=a[s-2].concat([a[s]]);break;case 41:this.$=a[s-2],r.setClass(a[s-1],a[s]);break;case 42:this.$=a[s-3],r.addCssStyles(a[s-2],a[s-1]);break;case 43:this.$=[a[s]];break;case 44:a[s-2].push(a[s]),this.$=a[s-2];break;case 46:this.$=a[s-1]+a[s];break;case 54:case 80:case 81:this.$=a[s].replace(/"/g,``);break;case 55:case 56:case 57:case 58:case 82:this.$=a[s];break;case 60:a[s].push(a[s-1]),this.$=a[s];break;case 61:this.$={type:a[s-1],name:a[s]};break;case 62:this.$={type:a[s-2],name:a[s-1],keys:a[s]};break;case 63:this.$={type:a[s-2],name:a[s-1],comment:a[s]};break;case 64:this.$={type:a[s-3],name:a[s-2],keys:a[s-1],comment:a[s]};break;case 65:case 67:case 70:this.$=a[s];break;case 66:this.$=a[s-1]+a[s];break;case 69:a[s-2].push(a[s]),this.$=a[s-2];break;case 71:this.$=a[s].replace(/"/g,``);break;case 72:this.$={cardA:a[s],relType:a[s-1],cardB:a[s-2]};break;case 73:this.$=r.Cardinality.ZERO_OR_ONE;break;case 74:this.$=r.Cardinality.ZERO_OR_MORE;break;case 75:this.$=r.Cardinality.ONE_OR_MORE;break;case 76:this.$=r.Cardinality.ONLY_ONE;break;case 77:this.$=r.Cardinality.MD_PARENT;break;case 78:this.$=r.Identification.NON_IDENTIFYING;break;case 79:this.$=r.Identification.IDENTIFYING;break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},t(n,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:9,22:r,24:i,26:a,28:o,29:14,30:15,31:16,32:17,33:s,34:c,35:l,36:u,37:d,40:f,43:p,44:m,48:h,50:g,51:_,52:v},t(n,[2,7],{1:[2,1]}),t(n,[2,3]),{9:30,11:9,22:r,24:i,26:a,28:o,29:14,30:15,31:16,32:17,33:s,34:c,35:l,36:u,37:d,40:f,43:p,44:m,48:h,50:g,51:_,52:v},t(n,[2,5]),t(n,[2,6]),t(n,[2,16],{12:31,64:35,15:[1,32],17:[1,33],20:[1,34],66:y,67:b,68:x,69:S,70:C}),{23:[1,41]},{25:[1,42]},{27:[1,43]},t(n,[2,27]),t(n,[2,28]),t(n,[2,29]),t(n,[2,30]),t(n,[2,31]),t(w,[2,54]),t(w,[2,55]),t(w,[2,56]),t(w,[2,57]),t(w,[2,58]),t(n,[2,32]),t(n,[2,33]),t(n,[2,34]),t(n,[2,35]),{16:44,40:T,41:E},{16:47,40:T,41:E},{16:48,40:T,41:E},t(n,[2,4]),{11:49,40:f,48:h,50:g,51:_,52:v},{16:50,40:T,41:E},{18:51,19:[1,52],53:53,54:54,58:D},{11:56,40:f,48:h,50:g,51:_,52:v},{65:57,71:[1,58],72:[1,59]},t(O,[2,73]),t(O,[2,74]),t(O,[2,75]),t(O,[2,76]),t(O,[2,77]),t(n,[2,24]),t(n,[2,25]),t(n,[2,26]),{13:k,38:60,41:A,42:j,45:62,46:63,48:M,49:N},t(P,[2,37]),t(P,[2,38]),{16:68,40:T,41:E,42:j},{13:k,38:69,41:A,42:j,45:62,46:63,48:M,49:N},{13:[1,70],15:[1,71]},t(n,[2,17],{64:35,12:72,17:[1,73],42:j,66:y,67:b,68:x,69:S,70:C}),{19:[1,74]},t(n,[2,14]),{18:75,19:[2,59],53:53,54:54,58:D},{55:76,58:[1,77]},{58:[2,65],59:[1,78]},{21:[1,79]},{64:80,66:y,67:b,68:x,69:S,70:C},t(F,[2,78]),t(F,[2,79]),{6:I,10:L,39:81,42:R,47:z},{40:[1,86],41:[1,87]},t(B,[2,43],{46:88,13:k,41:A,48:M,49:N}),t(V,[2,45]),t(V,[2,50]),t(V,[2,51]),t(V,[2,52]),t(V,[2,53]),t(n,[2,41],{42:j}),{6:I,10:L,39:89,42:R,47:z},{14:90,40:H,50:U,73:W},{16:94,40:T,41:E},{11:95,40:f,48:h,50:g,51:_,52:v},{18:96,19:[1,97],53:53,54:54,58:D},t(n,[2,12]),{19:[2,60]},t(G,[2,61],{56:98,57:99,60:100,62:K,63:q}),t([19,58,62,63],[2,67]),{58:[2,66]},t(n,[2,22],{15:[1,104],17:[1,103]}),t([40,48,50,51,52],[2,72]),t(n,[2,36]),{13:k,41:A,45:105,46:63,48:M,49:N},t(n,[2,47]),t(n,[2,48]),t(n,[2,49]),t(P,[2,39]),t(P,[2,40]),t(V,[2,46]),t(n,[2,42]),t(n,[2,8]),t(n,[2,80]),t(n,[2,81]),t(n,[2,82]),{13:[1,106],42:j},{13:[1,108],15:[1,107]},{19:[1,109]},t(n,[2,15]),t(G,[2,62],{57:110,61:[1,111],63:q}),t(G,[2,63]),t(J,[2,68]),t(G,[2,71]),t(J,[2,70]),{18:112,19:[1,113],53:53,54:54,58:D},{16:114,40:T,41:E},t(B,[2,44],{46:88,13:k,41:A,48:M,49:N}),{14:115,40:H,50:U,73:W},{16:116,40:T,41:E},{14:117,40:H,50:U,73:W},t(n,[2,13]),t(G,[2,64]),{60:118,62:K},{19:[1,119]},t(n,[2,20]),t(n,[2,23],{17:[1,120],42:j}),t(n,[2,11]),{13:[1,121],42:j},t(n,[2,10]),t(J,[2,69]),t(n,[2,18]),{18:122,19:[1,123],53:53,54:54,58:D},{14:124,40:H,50:U,73:W},{19:[1,125]},t(n,[2,21]),t(n,[2,9]),t(n,[2,19])],defaultActions:{75:[2,60],78:[2,66]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};Y.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:return this.begin(`acc_title`),24;case 1:return this.popState(),`acc_title_value`;case 2:return this.begin(`acc_descr`),26;case 3:return this.popState(),`acc_descr_value`;case 4:this.begin(`acc_descr_multiline`);break;case 5:this.popState();break;case 6:return`acc_descr_multiline_value`;case 7:return 33;case 8:return 34;case 9:return 35;case 10:return 36;case 11:return 10;case 12:break;case 13:return 8;case 14:return 50;case 15:return 73;case 16:return 4;case 17:return this.begin(`block`),17;case 18:return 49;case 19:return 49;case 20:return 42;case 21:return 15;case 22:return 13;case 23:break;case 24:return 62;case 25:return 58;case 26:return 58;case 27:this.begin(`block_bq`);break;case 28:return 58;case 29:this.popState();break;case 30:return 63;case 31:break;case 32:return this.popState(),19;case 33:return t.yytext[0];case 34:return 20;case 35:return 21;case 36:return this.begin(`style`),44;case 37:return this.popState(),10;case 38:break;case 39:return 13;case 40:return 42;case 41:return 49;case 42:return this.begin(`style`),37;case 43:return 43;case 44:return 66;case 45:return 68;case 46:return 68;case 47:return 68;case 48:return 66;case 49:return 66;case 50:return 67;case 51:return 67;case 52:return 67;case 53:return 67;case 54:return 67;case 55:return 68;case 56:return 67;case 57:return 68;case 58:return 69;case 59:return 69;case 60:return 51;case 61:return 69;case 62:return 69;case 63:return 69;case 64:return 52;case 65:return 48;case 66:return 69;case 67:return 66;case 68:return 67;case 69:return 68;case 70:return 70;case 71:return 71;case 72:return 72;case 73:return 72;case 74:return 71;case 75:return 71;case 76:return 71;case 77:return 41;case 78:return 47;case 79:return 40;case 80:return t.yytext[0];case 81:return 6}},`anonymous`),rules:[/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:[\s]+)/i,/^(?:"[^"%\r\n\v\b\\]+")/i,/^(?:"[^"]*")/i,/^(?:erDiagram\b)/i,/^(?:\{)/i,/^(?:#)/i,/^(?:#)/i,/^(?:,)/i,/^(?::::)/i,/^(?::)/i,/^(?:\s+)/i,/^(?:\b((?:PK)|(?:FK)|(?:UK))\b)/i,/^(?:([^\s]*)[~].*[~]([^\s]*))/i,/^(?:([\*A-Za-z_\u00C0-\uFFFF][A-Za-z0-9\-\_\[\]\(\)\.,\u00C0-\uFFFF\*]*))/i,/^(?:[`])/i,/^(?:[^`]+)/i,/^(?:[`])/i,/^(?:"[^"]*")/i,/^(?:[\n]+)/i,/^(?:\})/i,/^(?:.)/i,/^(?:\[)/i,/^(?:\])/i,/^(?:style\b)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?::)/i,/^(?:,)/i,/^(?:#)/i,/^(?:classDef\b)/i,/^(?:class\b)/i,/^(?:one or zero\b)/i,/^(?:one or more\b)/i,/^(?:one or many\b)/i,/^(?:1\+)/i,/^(?:\|o\b)/i,/^(?:zero or one\b)/i,/^(?:zero or more\b)/i,/^(?:zero or many\b)/i,/^(?:0\+)/i,/^(?:\}o\b)/i,/^(?:many\(0\))/i,/^(?:many\(1\))/i,/^(?:many\b)/i,/^(?:\}\|)/i,/^(?:one\b)/i,/^(?:only one\b)/i,/^(?:[0-9]+\.[0-9]+)/i,/^(?:1(?=\s+[A-Za-z_"']))/i,/^(?:1(?=\s+[0-9]))/i,/^(?:1(?=(--|\.\.|\.-|-\.)))/i,/^(?:1\b)/i,/^(?:[0-9]+)/i,/^(?:\|\|)/i,/^(?:o\|)/i,/^(?:o\{)/i,/^(?:\|\{)/i,/^(?:u(?=[\.\-\|]))/i,/^(?:\.\.)/i,/^(?:--)/i,/^(?:to\b)/i,/^(?:optionally to\b)/i,/^(?:\.-)/i,/^(?:-\.)/i,/^(?:([^\x00-\x7F]|\w|-|\*)+)/i,/^(?:;)/i,/^(?:([^\x00-\x7F]|\w|-|\*|\.)+)/i,/^(?:.)/i,/^(?:$)/i],conditions:{style:{rules:[37,38,39,40,41,77,78],inclusive:!1},acc_descr_multiline:{rules:[5,6],inclusive:!1},acc_descr:{rules:[3],inclusive:!1},acc_title:{rules:[1],inclusive:!1},block_bq:{rules:[28,29],inclusive:!1},block:{rules:[23,24,25,26,27,30,31,32,33],inclusive:!1},INITIAL:{rules:[0,2,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,34,35,36,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,79,80,81],inclusive:!0}}}})();function X(){this.yy={}}return e(X,`Parser`),X.prototype=Y,Y.Parser=X,new X})();b.parser=b;var x=b,S=class{constructor(){this.entities=new Map,this.relationships=[],this.classes=new Map,this.direction=`TB`,this.Cardinality={ZERO_OR_ONE:`ZERO_OR_ONE`,ZERO_OR_MORE:`ZERO_OR_MORE`,ONE_OR_MORE:`ONE_OR_MORE`,ONLY_ONE:`ONLY_ONE`,MD_PARENT:`MD_PARENT`},this.Identification={NON_IDENTIFYING:`NON_IDENTIFYING`,IDENTIFYING:`IDENTIFYING`},this.setAccTitle=o,this.getAccTitle=f,this.setAccDescription=i,this.getAccDescription=l,this.setDiagramTitle=a,this.getDiagramTitle=u,this.getConfig=e(()=>d().er,`getConfig`),this.clear(),this.addEntity=this.addEntity.bind(this),this.addAttributes=this.addAttributes.bind(this),this.addRelationship=this.addRelationship.bind(this),this.setDirection=this.setDirection.bind(this),this.addCssStyles=this.addCssStyles.bind(this),this.addClass=this.addClass.bind(this),this.setClass=this.setClass.bind(this),this.setAccTitle=this.setAccTitle.bind(this),this.setAccDescription=this.setAccDescription.bind(this)}static{e(this,`ErDB`)}addEntity(e,t=``){return this.entities.has(e)?!this.entities.get(e)?.alias&&t&&(this.entities.get(e).alias=t,n.info(`Add alias '${t}' to entity '${e}'`)):(this.entities.set(e,{id:`entity-${e}-${this.entities.size}`,label:e,attributes:[],alias:t,shape:`erBox`,look:d().look??`default`,cssClasses:`default`,cssStyles:[],labelType:`markdown`}),n.info(`Added new entity :`,e)),this.entities.get(e)}getEntity(e){return this.entities.get(e)}getEntities(){return this.entities}getClasses(){return this.classes}addAttributes(e,t){let r=this.addEntity(e),i;for(i=t.length-1;i>=0;i--)t[i].keys||(t[i].keys=[]),t[i].comment||(t[i].comment=``),r.attributes.push(t[i]),n.debug(`Added attribute `,t[i].name)}addRelationship(e,t,r,i){let a=this.entities.get(e),o=this.entities.get(r);if(!a||!o)return;let s={entityA:a.id,roleA:t,entityB:o.id,relSpec:i};this.relationships.push(s),n.debug(`Added new relationship :`,s)}getRelationships(){return this.relationships}getDirection(){return this.direction}setDirection(e){this.direction=e}getCompiledStyles(e){let t=[];for(let n of e){let e=this.classes.get(n);e?.styles&&(t=[...t,...e.styles??[]].map(e=>e.trim())),e?.textStyles&&(t=[...t,...e.textStyles??[]].map(e=>e.trim()))}return t}addCssStyles(e,t){for(let n of e){let e=this.entities.get(n);if(!t||!e)return;for(let n of t)e.cssStyles.push(n)}}addClass(e,t){e.forEach(e=>{let n=this.classes.get(e);n===void 0&&(n={id:e,styles:[],textStyles:[]},this.classes.set(e,n)),t&&t.forEach(function(e){if(/color/.exec(e)){let t=e.replace(`fill`,`bgFill`);n.textStyles.push(t)}n.styles.push(e)})})}setClass(e,t){for(let n of e){let e=this.entities.get(n);if(e)for(let n of t)e.cssClasses+=` `+n}}clear(){this.entities=new Map,this.classes=new Map,this.relationships=[],s()}getData(){let e=[],t=[],n=d(),r=0;for(let t of this.entities.keys()){let n=this.entities.get(t);n&&(n.cssCompiledStyles=this.getCompiledStyles(n.cssClasses.split(` `)),n.colorIndex=r++,e.push(n))}let i=0;for(let e of this.relationships){let r={id:m(e.entityA,e.entityB,{prefix:`id`,counter:i++}),type:`normal`,curve:`basis`,start:e.entityA,end:e.entityB,label:e.roleA,labelpos:`c`,thickness:`normal`,classes:`relationshipLine`,arrowTypeStart:e.relSpec.cardB.toLowerCase(),arrowTypeEnd:e.relSpec.cardA.toLowerCase(),pattern:e.relSpec.relType==`IDENTIFYING`?`solid`:`dashed`,look:n.look,labelType:`markdown`};t.push(r)}return{nodes:e,edges:t,other:{},config:n,direction:`TB`}}},C={};t(C,{draw:()=>w});var w=e(async function(e,t,i,a){n.info(`REF0:`),n.info(`Drawing er diagram (unified)`,t);let{securityLevel:o,er:s,layout:c}=d(),l=a.db.getData(),u=g(t,o);l.type=a.type,l.layoutAlgorithm=y(c),l.config.flowchart.nodeSpacing=s?.nodeSpacing||140,l.config.flowchart.rankSpacing=s?.rankSpacing||80,l.direction=a.db.getDirection();let{config:f}=l,{look:p}=f;p===`neo`?l.markers=[`only_one_neo`,`zero_or_one_neo`,`one_or_more_neo`,`zero_or_more_neo`]:l.markers=[`only_one`,`zero_or_one`,`one_or_more`,`zero_or_more`],l.diagramId=t,await v(l,u),l.layoutAlgorithm===`elk`&&u.select(`.edges`).lower();let m=u.selectAll(`[id*="-background"]`);Array.from(m).length>0&&m.each(function(){let e=r(this),t=e.attr(`id`).replace(`-background`,``),n=u.select(`#${CSS.escape(t)}`);if(!n.empty()){let t=n.attr(`transform`);e.attr(`transform`,t)}}),h.insertTitle(u,`erDiagramTitleText`,s?.titleTopMargin??25,a.db.getDiagramTitle()),_(u,8,`erDiagram`,s?.useMaxWidth??!0)},`draw`),T=e((e,t)=>{let n=p;return c(n(e,`r`),n(e,`g`),n(e,`b`),t)},`fade`),E=new Set([`redux-color`,`redux-dark-color`]),D=e(e=>{let{theme:t,look:n,bkgColorArray:r,borderColorArray:i}=e;if(!E.has(t))return``;let a=r?.length>0,o=``;for(let t=0;t{let{look:t,theme:n,erEdgeLabelBackground:r,strokeWidth:i}=e;return` + ${D(e)} + .entityBox { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; + } + + .relationshipLabelBox { + fill: ${e.tertiaryColor}; + opacity: 0.7; + background-color: ${e.tertiaryColor}; + rect { + opacity: 0.5; + } + } + + .labelBkg { + background-color: ${E.has(n)&&r?r:T(e.tertiaryColor,.5)}; + } + + .edgeLabel { + background-color: ${E.has(n)&&r?r:e.edgeLabelBackground}; + } + .edgeLabel .label rect { + fill: ${E.has(n)&&r?r:e.edgeLabelBackground}; + } + .edgeLabel .label text { + fill: ${e.textColor}; + } + + .edgeLabel .label { + fill: ${e.nodeBorder}; + font-size: 14px; + } + + .label { + font-family: ${e.fontFamily}; + color: ${e.nodeTextColor||e.textColor}; + } + + .edge-pattern-dashed { + stroke-dasharray: 8,8; + } + + .node rect, + .node circle, + .node ellipse, + .node polygon + { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; + stroke-width: ${t===`neo`?i:`1px`}; + } + + .relationshipLine { + stroke: ${e.lineColor}; + stroke-width: ${t===`neo`?i:`1px`}; + fill: none; + } + + .marker { + fill: none !important; + stroke: ${e.lineColor} !important; + stroke-width: 1; + } + [data-look=neo].labelBkg { + background-color: ${T(e.tertiaryColor,.5)}; + } +`},`getStyles`)};export{O as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/eventmodeling-45OFAUF4-Dp0gpjhg.js b/dist-desktop/assets/eventmodeling-45OFAUF4-Dp0gpjhg.js new file mode 100644 index 0000000..6ab9ed1 --- /dev/null +++ b/dist-desktop/assets/eventmodeling-45OFAUF4-Dp0gpjhg.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-5JV3BV7I-DKfYBAeY.js";export{e as createEventModelingServices}; \ No newline at end of file diff --git a/dist-desktop/assets/flowDiagram-23GEKE2U-mMOyit70.js b/dist-desktop/assets/flowDiagram-23GEKE2U-mMOyit70.js new file mode 100644 index 0000000..9be8115 --- /dev/null +++ b/dist-desktop/assets/flowDiagram-23GEKE2U-mMOyit70.js @@ -0,0 +1 @@ +import"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import"./chunk-ZIRB5QZD-C6fEPe3t.js";import{n as e}from"./chunk-PUDLZKDR-hlw4TonS.js";export{e as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/ganttDiagram-NO4QXBWP-BFiNAWzu.js b/dist-desktop/assets/ganttDiagram-NO4QXBWP-BFiNAWzu.js new file mode 100644 index 0000000..105834d --- /dev/null +++ b/dist-desktop/assets/ganttDiagram-NO4QXBWP-BFiNAWzu.js @@ -0,0 +1,292 @@ +import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{a as r,c as i,d as a,f as o,g as s,i as c,m as l,p as u,s as d,u as f}from"./src-UMNXGZaF.js";import{H as p,K as m,U as h,a as g,c as _,s as v,v as y,w as b,x,y as S}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{a as C,i as w,n as T,r as E,t as D}from"./linear-DhAcoVP9.js";import{t as O}from"./init-D6jRqBbL.js";import{t as k}from"./dist-qx0Iv9vM.js";import{g as ee}from"./chunk-ICXQ74PX-Czpgj8Uw.js";function A(e,t){let n;if(t===void 0)for(let t of e)t!=null&&(n=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n=i)&&(n=i)}return n}function te(e,t){let n;if(t===void 0)for(let t of e)t!=null&&(n>t||n===void 0&&t>=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}return n}function ne(e){return e}var j=1,re=2,ie=3,ae=4,oe=1e-6;function se(e){return`translate(`+e+`,0)`}function ce(e){return`translate(0,`+e+`)`}function le(e){return t=>+e(t)}function ue(e,t){return t=Math.max(0,e.bandwidth()-t*2)/2,e.round()&&(t=Math.round(t)),n=>+e(n)+t}function de(){return!this.__axis}function fe(e,t){var n=[],r=null,i=null,a=6,o=6,s=3,c=typeof window<`u`&&window.devicePixelRatio>1?0:.5,l=e===j||e===ae?-1:1,u=e===ae||e===re?`x`:`y`,d=e===j||e===ie?se:ce;function f(f){var p=r??(t.ticks?t.ticks.apply(t,n):t.domain()),m=i??(t.tickFormat?t.tickFormat.apply(t,n):ne),h=Math.max(a,0)+s,g=t.range(),_=+g[0]+c,v=+g[g.length-1]+c,y=(t.bandwidth?ue:le)(t.copy(),c),b=f.selection?f.selection():f,x=b.selectAll(`.domain`).data([null]),S=b.selectAll(`.tick`).data(p,t).order(),C=S.exit(),w=S.enter().append(`g`).attr(`class`,`tick`),T=S.select(`line`),E=S.select(`text`);x=x.merge(x.enter().insert(`path`,`.tick`).attr(`class`,`domain`).attr(`stroke`,`currentColor`)),S=S.merge(w),T=T.merge(w.append(`line`).attr(`stroke`,`currentColor`).attr(u+`2`,l*a)),E=E.merge(w.append(`text`).attr(`fill`,`currentColor`).attr(u,l*h).attr(`dy`,e===j?`0em`:e===ie?`0.71em`:`0.32em`)),f!==b&&(x=x.transition(f),S=S.transition(f),T=T.transition(f),E=E.transition(f),C=C.transition(f).attr(`opacity`,oe).attr(`transform`,function(e){return isFinite(e=y(e))?d(e+c):this.getAttribute(`transform`)}),w.attr(`opacity`,oe).attr(`transform`,function(e){var t=this.parentNode.__axis;return d((t&&isFinite(t=t(e))?t:y(e))+c)})),C.remove(),x.attr(`d`,e===ae||e===re?o?`M`+l*o+`,`+_+`H`+c+`V`+v+`H`+l*o:`M`+c+`,`+_+`V`+v:o?`M`+_+`,`+l*o+`V`+c+`H`+v+`V`+l*o:`M`+_+`,`+c+`H`+v),S.attr(`opacity`,1).attr(`transform`,function(e){return d(y(e)+c)}),T.attr(u+`2`,l*a),E.attr(u,l*h).text(m),b.filter(de).attr(`fill`,`none`).attr(`font-size`,10).attr(`font-family`,`sans-serif`).attr(`text-anchor`,e===re?`start`:e===ae?`end`:`middle`),b.each(function(){this.__axis=y})}return f.scale=function(e){return arguments.length?(t=e,f):t},f.ticks=function(){return n=Array.from(arguments),f},f.tickArguments=function(e){return arguments.length?(n=e==null?[]:Array.from(e),f):n.slice()},f.tickValues=function(e){return arguments.length?(r=e==null?null:Array.from(e),f):r&&r.slice()},f.tickFormat=function(e){return arguments.length?(i=e,f):i},f.tickSize=function(e){return arguments.length?(a=o=+e,f):a},f.tickSizeInner=function(e){return arguments.length?(a=+e,f):a},f.tickSizeOuter=function(e){return arguments.length?(o=+e,f):o},f.tickPadding=function(e){return arguments.length?(s=+e,f):s},f.offset=function(e){return arguments.length?(c=+e,f):c},f}function pe(e){return fe(j,e)}function me(e){return fe(ie,e)}var he=Math.PI/180,ge=180/Math.PI,_e=18,ve=.96422,ye=1,be=.82521,xe=4/29,Se=6/29,Ce=3*Se*Se,we=Se*Se*Se;function Te(e){if(e instanceof M)return new M(e.l,e.a,e.b,e.opacity);if(e instanceof N)return Ne(e);e instanceof i||(e=f(e));var t=Ae(e.r),n=Ae(e.g),r=Ae(e.b),a=De((.2225045*t+.7168786*n+.0606169*r)/ye),o,s;return t===n&&n===r?o=s=a:(o=De((.4360747*t+.3850649*n+.1430804*r)/ve),s=De((.0139322*t+.0971045*n+.7141733*r)/be)),new M(116*a-16,500*(o-a),200*(a-s),e.opacity)}function Ee(e,t,n,r){return arguments.length===1?Te(e):new M(e,t,n,r??1)}function M(e,t,n,r){this.l=+e,this.a=+t,this.b=+n,this.opacity=+r}a(M,Ee,o(d,{brighter(e){return new M(this.l+_e*(e??1),this.a,this.b,this.opacity)},darker(e){return new M(this.l-_e*(e??1),this.a,this.b,this.opacity)},rgb(){var e=(this.l+16)/116,t=isNaN(this.a)?e:e+this.a/500,n=isNaN(this.b)?e:e-this.b/200;return t=ve*Oe(t),e=ye*Oe(e),n=be*Oe(n),new i(ke(3.1338561*t-1.6168667*e-.4906146*n),ke(-.9787684*t+1.9161415*e+.033454*n),ke(.0719453*t-.2289914*e+1.4052427*n),this.opacity)}}));function De(e){return e>we?e**(1/3):e/Ce+xe}function Oe(e){return e>Se?e*e*e:Ce*(e-xe)}function ke(e){return 255*(e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055)}function Ae(e){return(e/=255)<=.04045?e/12.92:((e+.055)/1.055)**2.4}function je(e){if(e instanceof N)return new N(e.h,e.c,e.l,e.opacity);if(e instanceof M||(e=Te(e)),e.a===0&&e.b===0)return new N(NaN,0(e(t=new Date(+t)),t),i.ceil=n=>(e(n=new Date(n-1)),t(n,1),e(n),n),i.round=e=>{let t=i(e),n=i.ceil(e);return e-t(t(e=new Date(+e),n==null?1:Math.floor(n)),e),i.range=(n,r,a)=>{let o=[];if(n=i.ceil(n),a=a==null?1:Math.floor(a),!(n0))return o;let s;do o.push(s=new Date(+n)),t(n,a),e(n);while(sP(t=>{if(t>=t)for(;e(t),!n(t);)t.setTime(t-1)},(e,r)=>{if(e>=e)if(r<0)for(;++r<=0;)for(;t(e,-1),!n(e););else for(;--r>=0;)for(;t(e,1),!n(e););}),n&&(i.count=(t,r)=>(Le.setTime(+t),Re.setTime(+r),e(Le),e(Re),Math.floor(n(Le,Re))),i.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?i.filter(r?t=>r(t)%e===0:t=>i.count(0,t)%e===0):i)),i}var ze=P(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);ze.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?P(t=>{t.setTime(Math.floor(t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>(n-t)/e):ze),ze.range;var F=1e3,I=F*60,L=I*60,R=L*24,Be=R*7,Ve=R*30,He=R*365,z=P(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*F)},(e,t)=>(t-e)/F,e=>e.getUTCSeconds());z.range;var Ue=P(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*F)},(e,t)=>{e.setTime(+e+t*I)},(e,t)=>(t-e)/I,e=>e.getMinutes());Ue.range;var We=P(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*I)},(e,t)=>(t-e)/I,e=>e.getUTCMinutes());We.range;var Ge=P(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*F-e.getMinutes()*I)},(e,t)=>{e.setTime(+e+t*L)},(e,t)=>(t-e)/L,e=>e.getHours());Ge.range;var Ke=P(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*L)},(e,t)=>(t-e)/L,e=>e.getUTCHours());Ke.range;var B=P(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*I)/R,e=>e.getDate()-1);B.range;var qe=P(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/R,e=>e.getUTCDate()-1);qe.range;var Je=P(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/R,e=>Math.floor(e/R));Je.range;function V(e){return P(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(e,t)=>{e.setDate(e.getDate()+t*7)},(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*I)/Be)}var Ye=V(0),Xe=V(1),Ze=V(2),Qe=V(3),H=V(4),$e=V(5),et=V(6);Ye.range,Xe.range,Ze.range,Qe.range,H.range,$e.range,et.range;function U(e){return P(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t*7)},(e,t)=>(t-e)/Be)}var tt=U(0),nt=U(1),rt=U(2),it=U(3),at=U(4),ot=U(5),st=U(6);tt.range,nt.range,rt.range,it.range,at.range,ot.range,st.range;var ct=P(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());ct.range;var lt=P(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());lt.range;var W=P(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());W.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:P(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*e)}),W.range;var G=P(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());G.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:P(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*e)}),G.range;function ut(e,t,n,r,i,a){let o=[[z,1,F],[z,5,5*F],[z,15,15*F],[z,30,30*F],[a,1,I],[a,5,5*I],[a,15,15*I],[a,30,30*I],[i,1,L],[i,3,3*L],[i,6,6*L],[i,12,12*L],[r,1,R],[r,2,2*R],[n,1,Be],[t,1,Ve],[t,3,3*Ve],[e,1,He]];function s(e,t,n){let r=te).right(o,i);if(a===o.length)return e.every(w(t/He,n/He,r));if(a===0)return ze.every(Math.max(w(t,n,r),1));let[s,c]=o[i/o[a-1][2]53)return null;`w`in r||(r.w=1),`Z`in r?(a=gt(_t(r.y,0,1)),o=a.getUTCDay(),a=o>4||o===0?nt.ceil(a):nt(a),a=qe.offset(a,(r.V-1)*7),r.y=a.getUTCFullYear(),r.m=a.getUTCMonth(),r.d=a.getUTCDate()+(r.w+6)%7):(a=ht(_t(r.y,0,1)),o=a.getDay(),a=o>4||o===0?Xe.ceil(a):Xe(a),a=B.offset(a,(r.V-1)*7),r.y=a.getFullYear(),r.m=a.getMonth(),r.d=a.getDate()+(r.w+6)%7)}else(`W`in r||`U`in r)&&(`w`in r||(r.w=`u`in r?r.u%7:+(`W`in r)),o=`Z`in r?gt(_t(r.y,0,1)).getUTCDay():ht(_t(r.y,0,1)).getDay(),r.m=0,r.d=`W`in r?(r.w+6)%7+r.W*7-(o+5)%7:r.w+r.U*7-(o+6)%7);return`Z`in r?(r.H+=r.Z/100|0,r.M+=r.Z%100,gt(r)):ht(r)}}function w(e,t,n,r){for(var i=0,a=t.length,o=n.length,s,c;i=o)return-1;if(s=t.charCodeAt(i++),s===37){if(s=t.charAt(i++),c=x[s in yt?t.charAt(i++):s],!c||(r=c(e,n,r))<0)return-1}else if(s!=n.charCodeAt(r++))return-1}return r}function T(e,t,n){var r=l.exec(t.slice(n));return r?(e.p=u.get(r[0].toLowerCase()),n+r[0].length):-1}function E(e,t,n){var r=p.exec(t.slice(n));return r?(e.w=m.get(r[0].toLowerCase()),n+r[0].length):-1}function D(e,t,n){var r=d.exec(t.slice(n));return r?(e.w=f.get(r[0].toLowerCase()),n+r[0].length):-1}function O(e,t,n){var r=_.exec(t.slice(n));return r?(e.m=v.get(r[0].toLowerCase()),n+r[0].length):-1}function k(e,t,n){var r=h.exec(t.slice(n));return r?(e.m=g.get(r[0].toLowerCase()),n+r[0].length):-1}function ee(e,n,r){return w(e,t,n,r)}function A(e,t,r){return w(e,n,t,r)}function te(e,t,n){return w(e,r,t,n)}function ne(e){return o[e.getDay()]}function j(e){return a[e.getDay()]}function re(e){return c[e.getMonth()]}function ie(e){return s[e.getMonth()]}function ae(e){return i[+(e.getHours()>=12)]}function oe(e){return 1+~~(e.getMonth()/3)}function se(e){return o[e.getUTCDay()]}function ce(e){return a[e.getUTCDay()]}function le(e){return c[e.getUTCMonth()]}function ue(e){return s[e.getUTCMonth()]}function de(e){return i[+(e.getUTCHours()>=12)]}function fe(e){return 1+~~(e.getUTCMonth()/3)}return{format:function(e){var t=S(e+=``,y);return t.toString=function(){return e},t},parse:function(e){var t=C(e+=``,!1);return t.toString=function(){return e},t},utcFormat:function(e){var t=S(e+=``,b);return t.toString=function(){return e},t},utcParse:function(e){var t=C(e+=``,!0);return t.toString=function(){return e},t}}}var yt={"-":``,_:` `,0:`0`},K=/^\s*\d+/,bt=/^%/,xt=/[\\^$*+?|[\]().{}]/g;function q(e,t,n){var r=e<0?`-`:``,i=(r?-e:e)+``,a=i.length;return r+(a[e.toLowerCase(),t]))}function Tt(e,t,n){var r=K.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function Et(e,t,n){var r=K.exec(t.slice(n,n+1));return r?(e.u=+r[0],n+r[0].length):-1}function Dt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.U=+r[0],n+r[0].length):-1}function Ot(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.V=+r[0],n+r[0].length):-1}function kt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.W=+r[0],n+r[0].length):-1}function At(e,t,n){var r=K.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function jt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Mt(e,t,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(e.Z=r[1]?0:-(r[2]+(r[3]||`00`)),n+r[0].length):-1}function Nt(e,t,n){var r=K.exec(t.slice(n,n+1));return r?(e.q=r[0]*3-3,n+r[0].length):-1}function Pt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function Ft(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function It(e,t,n){var r=K.exec(t.slice(n,n+3));return r?(e.m=0,e.d=+r[0],n+r[0].length):-1}function Lt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function Rt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function zt(e,t,n){var r=K.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function Bt(e,t,n){var r=K.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function Vt(e,t,n){var r=K.exec(t.slice(n,n+6));return r?(e.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function Ht(e,t,n){var r=bt.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function Ut(e,t,n){var r=K.exec(t.slice(n));return r?(e.Q=+r[0],n+r[0].length):-1}function Wt(e,t,n){var r=K.exec(t.slice(n));return r?(e.s=+r[0],n+r[0].length):-1}function Gt(e,t){return q(e.getDate(),t,2)}function Kt(e,t){return q(e.getHours(),t,2)}function qt(e,t){return q(e.getHours()%12||12,t,2)}function Jt(e,t){return q(1+B.count(W(e),e),t,3)}function Yt(e,t){return q(e.getMilliseconds(),t,3)}function Xt(e,t){return Yt(e,t)+`000`}function Zt(e,t){return q(e.getMonth()+1,t,2)}function Qt(e,t){return q(e.getMinutes(),t,2)}function $t(e,t){return q(e.getSeconds(),t,2)}function en(e){var t=e.getDay();return t===0?7:t}function tn(e,t){return q(Ye.count(W(e)-1,e),t,2)}function nn(e){var t=e.getDay();return t>=4||t===0?H(e):H.ceil(e)}function rn(e,t){return e=nn(e),q(H.count(W(e),e)+(W(e).getDay()===4),t,2)}function an(e){return e.getDay()}function on(e,t){return q(Xe.count(W(e)-1,e),t,2)}function sn(e,t){return q(e.getFullYear()%100,t,2)}function cn(e,t){return e=nn(e),q(e.getFullYear()%100,t,2)}function ln(e,t){return q(e.getFullYear()%1e4,t,4)}function un(e,t){var n=e.getDay();return e=n>=4||n===0?H(e):H.ceil(e),q(e.getFullYear()%1e4,t,4)}function dn(e){var t=e.getTimezoneOffset();return(t>0?`-`:(t*=-1,`+`))+q(t/60|0,`0`,2)+q(t%60,`0`,2)}function fn(e,t){return q(e.getUTCDate(),t,2)}function pn(e,t){return q(e.getUTCHours(),t,2)}function mn(e,t){return q(e.getUTCHours()%12||12,t,2)}function hn(e,t){return q(1+qe.count(G(e),e),t,3)}function gn(e,t){return q(e.getUTCMilliseconds(),t,3)}function _n(e,t){return gn(e,t)+`000`}function vn(e,t){return q(e.getUTCMonth()+1,t,2)}function yn(e,t){return q(e.getUTCMinutes(),t,2)}function bn(e,t){return q(e.getUTCSeconds(),t,2)}function xn(e){var t=e.getUTCDay();return t===0?7:t}function Sn(e,t){return q(tt.count(G(e)-1,e),t,2)}function Cn(e){var t=e.getUTCDay();return t>=4||t===0?at(e):at.ceil(e)}function wn(e,t){return e=Cn(e),q(at.count(G(e),e)+(G(e).getUTCDay()===4),t,2)}function Tn(e){return e.getUTCDay()}function En(e,t){return q(nt.count(G(e)-1,e),t,2)}function Dn(e,t){return q(e.getUTCFullYear()%100,t,2)}function On(e,t){return e=Cn(e),q(e.getUTCFullYear()%100,t,2)}function kn(e,t){return q(e.getUTCFullYear()%1e4,t,4)}function An(e,t){var n=e.getUTCDay();return e=n>=4||n===0?at(e):at.ceil(e),q(e.getUTCFullYear()%1e4,t,4)}function jn(){return`+0000`}function Mn(){return`%`}function Nn(e){return+e}function Pn(e){return Math.floor(e/1e3)}var Fn,In;Ln({dateTime:`%x, %X`,date:`%-m/%-d/%Y`,time:`%-I:%M:%S %p`,periods:[`AM`,`PM`],days:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],shortDays:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],months:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],shortMonths:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`]});function Ln(e){return Fn=vt(e),In=Fn.format,Fn.parse,Fn.utcFormat,Fn.utcParse,Fn}function Rn(e){return new Date(e)}function zn(e){return e instanceof Date?+e:+new Date(+e)}function Bn(e,t,n,r,i,a,o,s,c,l){var u=T(),d=u.invert,f=u.domain,p=l(`.%L`),m=l(`:%S`),h=l(`%I:%M`),g=l(`%I %p`),_=l(`%a %d`),v=l(`%b %d`),y=l(`%B`),b=l(`%Y`);function x(e){return(c(e){(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_isoWeek=r()})(e,(function(){return function(e,t,n){var r=function(e){return e.add(4-e.isoWeekday(),`day`)},i=t.prototype;i.isoWeekYear=function(){return r(this).year()},i.isoWeek=function(e){if(!this.$utils().u(e))return this.add(7*(e-this.isoWeek()),`day`);var t,i,a,o,s=r(this),c=(t=this.isoWeekYear(),i=this.$u,a=(i?n.utc:n)().year(t).startOf(`year`),o=4-a.isoWeekday(),a.isoWeekday()>4&&(o+=7),a.add(o,`day`));return s.diff(c,`week`)+1},i.isoWeekday=function(e){return this.$utils().u(e)?this.day()||7:this.day(this.day()%7?e:e-7)};var a=i.startOf;i.startOf=function(e,t){var n=this.$utils(),r=!!n.u(t)||t;return n.p(e)===`isoweek`?r?this.date(this.date()-(this.isoWeekday()-1)).startOf(`day`):this.date(this.date()-1-(this.isoWeekday()-1)+7).endOf(`day`):a.bind(this)(e,t)}}}))})),Un=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_customParseFormat=r()})(e,(function(){var e={LTS:`h:mm:ss A`,LT:`h:mm A`,L:`MM/DD/YYYY`,LL:`MMMM D, YYYY`,LLL:`MMMM D, YYYY h:mm A`,LLLL:`dddd, MMMM D, YYYY h:mm A`},t=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,n=/\d/,r=/\d\d/,i=/\d\d?/,a=/\d*[^-_:/,()\s\d]+/,o={},s=function(e){return(e=+e)+(e>68?1900:2e3)},c=function(e){return function(t){this[e]=+t}},l=[/[+-]\d\d:?(\d\d)?|Z/,function(e){(this.zone||={}).offset=function(e){if(!e||e===`Z`)return 0;var t=e.match(/([+-]|\d\d)/g),n=60*t[1]+(+t[2]||0);return n===0?0:t[0]===`+`?-n:n}(e)}],u=function(e){var t=o[e];return t&&(t.indexOf?t:t.s.concat(t.f))},d=function(e,t){var n,r=o.meridiem;if(r){for(var i=1;i<=24;i+=1)if(e.indexOf(r(i,0,t))>-1){n=i>12;break}}else n=e===(t?`pm`:`PM`);return n},f={A:[a,function(e){this.afternoon=d(e,!1)}],a:[a,function(e){this.afternoon=d(e,!0)}],Q:[n,function(e){this.month=3*(e-1)+1}],S:[n,function(e){this.milliseconds=100*e}],SS:[r,function(e){this.milliseconds=10*e}],SSS:[/\d{3}/,function(e){this.milliseconds=+e}],s:[i,c(`seconds`)],ss:[i,c(`seconds`)],m:[i,c(`minutes`)],mm:[i,c(`minutes`)],H:[i,c(`hours`)],h:[i,c(`hours`)],HH:[i,c(`hours`)],hh:[i,c(`hours`)],D:[i,c(`day`)],DD:[r,c(`day`)],Do:[a,function(e){var t=o.ordinal,n=e.match(/\d+/);if(this.day=n[0],t)for(var r=1;r<=31;r+=1)t(r).replace(/\[|\]/g,``)===e&&(this.day=r)}],w:[i,c(`week`)],ww:[r,c(`week`)],M:[i,c(`month`)],MM:[r,c(`month`)],MMM:[a,function(e){var t=u(`months`),n=(u(`monthsShort`)||t.map((function(e){return e.slice(0,3)}))).indexOf(e)+1;if(n<1)throw Error();this.month=n%12||n}],MMMM:[a,function(e){var t=u(`months`).indexOf(e)+1;if(t<1)throw Error();this.month=t%12||t}],Y:[/[+-]?\d+/,c(`year`)],YY:[r,function(e){this.year=s(e)}],YYYY:[/\d{4}/,c(`year`)],Z:l,ZZ:l};function p(n){for(var r=n,i=o&&o.formats,a=(n=r.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(t,n,r){var a=r&&r.toUpperCase();return n||i[r]||e[r]||i[a].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(e,t,n){return t||n.slice(1)}))}))).match(t),s=a.length,c=0;c-1)return new Date((t===`X`?1e3:1)*e);var i=p(t)(e),a=i.year,o=i.month,s=i.day,c=i.hours,l=i.minutes,u=i.seconds,d=i.milliseconds,f=i.zone,m=i.week,h=new Date,g=s||(a||o?1:h.getDate()),_=a||h.getFullYear(),v=0;a&&!o||(v=o>0?o-1:h.getMonth());var y,b=c||0,x=l||0,S=u||0,C=d||0;return f?new Date(Date.UTC(_,v,g,b,x,S,C+60*f.offset*1e3)):n?new Date(Date.UTC(_,v,g,b,x,S,C)):(y=new Date(_,v,g,b,x,S,C),m&&(y=r(y).week(m).toDate()),y)}catch{return new Date(``)}}(t,s,r,n),this.init(),d&&!0!==d&&(this.$L=this.locale(d).$L),u&&t!=this.format(s)&&(this.$d=new Date(``)),o={}}else if(s instanceof Array)for(var f=s.length,m=1;m<=f;m+=1){a[1]=s[m-1];var h=n.apply(this,a);if(h.isValid()){this.$d=h.$d,this.$L=h.$L,this.init();break}m===f&&(this.$d=new Date(``))}else i.call(this,e)}}}))})),Wn=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_advancedFormat=r()})(e,(function(){return function(e,t){var n=t.prototype,r=n.format;n.format=function(e){var t=this,n=this.$locale();if(!this.isValid())return r.bind(this)(e);var i=this.$utils(),a=(e||`YYYY-MM-DDTHH:mm:ssZ`).replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,(function(e){switch(e){case`Q`:return Math.ceil((t.$M+1)/3);case`Do`:return n.ordinal(t.$D);case`gggg`:return t.weekYear();case`GGGG`:return t.isoWeekYear();case`wo`:return n.ordinal(t.week(),`W`);case`w`:case`ww`:return i.s(t.week(),e===`w`?1:2,`0`);case`W`:case`WW`:return i.s(t.isoWeek(),e===`W`?1:2,`0`);case`k`:case`kk`:return i.s(String(t.$H===0?24:t.$H),e===`k`?1:2,`0`);case`X`:return Math.floor(t.$d.getTime()/1e3);case`x`:return t.$d.getTime();case`z`:return`[`+t.offsetName()+`]`;case`zzz`:return`[`+t.offsetName(`long`)+`]`;default:return e}}));return r.bind(this)(a)}}}))})),Gn=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_duration=r()})(e,(function(){var e,t,n=1e3,r=6e4,i=36e5,a=864e5,o=31536e6,s=2628e6,c=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,l=/\[([^\]]+)]|YYYY|YY|Y|M{1,2}|D{1,2}|H{1,2}|m{1,2}|s{1,2}|SSS/g,u={years:o,months:s,days:a,hours:i,minutes:r,seconds:n,milliseconds:1,weeks:6048e5},d=function(e){return e instanceof v},f=function(e,t,n){return new v(e,n,t.$l)},p=function(e){return t.p(e)+`s`},m=function(e){return e<0},h=function(e){return m(e)?Math.ceil(e):Math.floor(e)},g=function(e){return Math.abs(e)},_=function(e,t){return e?m(e)?{negative:!0,format:``+g(e)+t}:{negative:!1,format:``+e+t}:{negative:!1,format:``}},v=function(){function m(e,t,n){var r=this;if(this.$d={},this.$l=n,e===void 0&&(this.$ms=0,this.parseFromMilliseconds()),t)return f(e*u[p(t)],this);if(typeof e==`number`)return this.$ms=e,this.parseFromMilliseconds(),this;if(typeof e==`object`)return Object.keys(e).forEach((function(t){r.$d[p(t)]=e[t]})),this.calMilliseconds(),this;if(typeof e==`string`){var i=e.match(c);if(i){var a=i.slice(2).map((function(e){return e==null?0:Number(e)}));return this.$d.years=a[0],this.$d.months=a[1],this.$d.weeks=a[2],this.$d.days=a[3],this.$d.hours=a[4],this.$d.minutes=a[5],this.$d.seconds=a[6],this.calMilliseconds(),this}}return this}var g=m.prototype;return g.calMilliseconds=function(){var e=this;this.$ms=Object.keys(this.$d).reduce((function(t,n){return t+(e.$d[n]||0)*u[n]}),0)},g.parseFromMilliseconds=function(){var e=this.$ms;this.$d.years=h(e/o),e%=o,this.$d.months=h(e/s),e%=s,this.$d.days=h(e/a),e%=a,this.$d.hours=h(e/i),e%=i,this.$d.minutes=h(e/r),e%=r,this.$d.seconds=h(e/n),e%=n,this.$d.milliseconds=e},g.toISOString=function(){var e=_(this.$d.years,`Y`),t=_(this.$d.months,`M`),n=+this.$d.days||0;this.$d.weeks&&(n+=7*this.$d.weeks);var r=_(n,`D`),i=_(this.$d.hours,`H`),a=_(this.$d.minutes,`M`),o=this.$d.seconds||0;this.$d.milliseconds&&(o+=this.$d.milliseconds/1e3,o=Math.round(1e3*o)/1e3);var s=_(o,`S`),c=e.negative||t.negative||r.negative||i.negative||a.negative||s.negative,l=i.format||a.format||s.format?`T`:``,u=(c?`-`:``)+`P`+e.format+t.format+r.format+l+i.format+a.format+s.format;return u===`P`||u===`-P`?`P0D`:u},g.toJSON=function(){return this.toISOString()},g.format=function(e){var n=e||`YYYY-MM-DDTHH:mm:ss`,r={Y:this.$d.years,YY:t.s(this.$d.years,2,`0`),YYYY:t.s(this.$d.years,4,`0`),M:this.$d.months,MM:t.s(this.$d.months,2,`0`),D:this.$d.days,DD:t.s(this.$d.days,2,`0`),H:this.$d.hours,HH:t.s(this.$d.hours,2,`0`),m:this.$d.minutes,mm:t.s(this.$d.minutes,2,`0`),s:this.$d.seconds,ss:t.s(this.$d.seconds,2,`0`),SSS:t.s(this.$d.milliseconds,3,`0`)};return n.replace(l,(function(e,t){return t||String(r[e])}))},g.as=function(e){return this.$ms/u[p(e)]},g.get=function(e){var t=this.$ms,n=p(e);return n===`milliseconds`?t%=1e3:t=n===`weeks`?h(t/u[n]):this.$d[n],t||0},g.add=function(e,t,n){var r;return r=t?e*u[p(t)]:d(e)?e.$ms:f(e,this).$ms,f(this.$ms+r*(n?-1:1),this)},g.subtract=function(e,t){return this.add(e,t,!0)},g.locale=function(e){var t=this.clone();return t.$l=e,t},g.clone=function(){return f(this.$ms,this)},g.humanize=function(t){return e().add(this.$ms,`ms`).locale(this.$l).fromNow(!t)},g.valueOf=function(){return this.asMilliseconds()},g.milliseconds=function(){return this.get(`milliseconds`)},g.asMilliseconds=function(){return this.as(`milliseconds`)},g.seconds=function(){return this.get(`seconds`)},g.asSeconds=function(){return this.as(`seconds`)},g.minutes=function(){return this.get(`minutes`)},g.asMinutes=function(){return this.as(`minutes`)},g.hours=function(){return this.get(`hours`)},g.asHours=function(){return this.as(`hours`)},g.days=function(){return this.get(`days`)},g.asDays=function(){return this.as(`days`)},g.weeks=function(){return this.get(`weeks`)},g.asWeeks=function(){return this.as(`weeks`)},g.months=function(){return this.get(`months`)},g.asMonths=function(){return this.as(`months`)},g.years=function(){return this.get(`years`)},g.asYears=function(){return this.as(`years`)},m}(),y=function(e,t,n){return e.add(t.years()*n,`y`).add(t.months()*n,`M`).add(t.days()*n,`d`).add(t.hours()*n,`h`).add(t.minutes()*n,`m`).add(t.seconds()*n,`s`).add(t.milliseconds()*n,`ms`)};return function(n,r,i){e=i,t=i().$utils(),i.duration=function(e,t){return f(e,{$l:i.locale()},t)},i.isDuration=d;var a=r.prototype.add,o=r.prototype.subtract;r.prototype.add=function(e,t){return d(e)?y(this,e,1):a.bind(this)(e,t)},r.prototype.subtract=function(e,t){return d(e)?y(this,e,-1):o.bind(this)(e,t)}}}))})),Kn=k(),J=e(s(),1),qn=e(Hn(),1),Jn=e(Un(),1),Yn=e(Wn(),1),Xn=e(Gn(),1),Zn=(function(){var e=n(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),t=[6,8,10,12,13,14,15,16,17,18,20,21,22,23,24,25,26,27,28,29,30,31,33,35,36,38,40],r=[1,26],i=[1,27],a=[1,28],o=[1,29],s=[1,30],c=[1,31],l=[1,32],u=[1,33],d=[1,34],f=[1,9],p=[1,10],m=[1,11],h=[1,12],g=[1,13],_=[1,14],v=[1,15],y=[1,16],b=[1,19],x=[1,20],S=[1,21],C=[1,22],w=[1,23],T=[1,25],E=[1,35],D={trace:n(function(){},`trace`),yy:{},symbols_:{error:2,start:3,gantt:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NL:10,weekday:11,weekday_monday:12,weekday_tuesday:13,weekday_wednesday:14,weekday_thursday:15,weekday_friday:16,weekday_saturday:17,weekday_sunday:18,weekend:19,weekend_friday:20,weekend_saturday:21,dateFormat:22,inclusiveEndDates:23,topAxis:24,axisFormat:25,tickInterval:26,excludes:27,includes:28,todayMarker:29,title:30,acc_title:31,acc_title_value:32,acc_descr:33,acc_descr_value:34,acc_descr_multiline_value:35,section:36,clickStatement:37,taskTxt:38,taskData:39,click:40,callbackname:41,callbackargs:42,href:43,clickStatementDebug:44,$accept:0,$end:1},terminals_:{2:`error`,4:`gantt`,6:`EOF`,8:`SPACE`,10:`NL`,12:`weekday_monday`,13:`weekday_tuesday`,14:`weekday_wednesday`,15:`weekday_thursday`,16:`weekday_friday`,17:`weekday_saturday`,18:`weekday_sunday`,20:`weekend_friday`,21:`weekend_saturday`,22:`dateFormat`,23:`inclusiveEndDates`,24:`topAxis`,25:`axisFormat`,26:`tickInterval`,27:`excludes`,28:`includes`,29:`todayMarker`,30:`title`,31:`acc_title`,32:`acc_title_value`,33:`acc_descr`,34:`acc_descr_value`,35:`acc_descr_multiline_value`,36:`section`,38:`taskTxt`,39:`taskData`,40:`click`,41:`callbackname`,42:`callbackargs`,43:`href`},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[19,1],[19,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,1],[9,2],[37,2],[37,3],[37,3],[37,4],[37,3],[37,4],[37,2],[44,2],[44,3],[44,3],[44,4],[44,3],[44,4],[44,2]],performAction:n(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 2:this.$=[];break;case 3:a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 5:this.$=a[s];break;case 6:case 7:this.$=[];break;case 8:r.setWeekday(`monday`);break;case 9:r.setWeekday(`tuesday`);break;case 10:r.setWeekday(`wednesday`);break;case 11:r.setWeekday(`thursday`);break;case 12:r.setWeekday(`friday`);break;case 13:r.setWeekday(`saturday`);break;case 14:r.setWeekday(`sunday`);break;case 15:r.setWeekend(`friday`);break;case 16:r.setWeekend(`saturday`);break;case 17:r.setDateFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 18:r.enableInclusiveEndDates(),this.$=a[s].substr(18);break;case 19:r.TopAxis(),this.$=a[s].substr(8);break;case 20:r.setAxisFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 21:r.setTickInterval(a[s].substr(13)),this.$=a[s].substr(13);break;case 22:r.setExcludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 23:r.setIncludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 24:r.setTodayMarker(a[s].substr(12)),this.$=a[s].substr(12);break;case 27:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 28:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 29:case 30:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 31:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 33:r.addTask(a[s-1],a[s]),this.$=`task`;break;case 34:this.$=a[s-1],r.setClickEvent(a[s-1],a[s],null);break;case 35:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 36:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],null),r.setLink(a[s-2],a[s]);break;case 37:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setLink(a[s-3],a[s]);break;case 38:this.$=a[s-2],r.setClickEvent(a[s-2],a[s],null),r.setLink(a[s-2],a[s-1]);break;case 39:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-1],a[s]),r.setLink(a[s-3],a[s-2]);break;case 40:this.$=a[s-1],r.setLink(a[s-1],a[s]);break;case 41:case 47:this.$=a[s-1]+` `+a[s];break;case 42:case 43:case 45:this.$=a[s-2]+` `+a[s-1]+` `+a[s];break;case 44:case 46:this.$=a[s-3]+` `+a[s-2]+` `+a[s-1]+` `+a[s];break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},e(t,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:17,12:r,13:i,14:a,15:o,16:s,17:c,18:l,19:18,20:u,21:d,22:f,23:p,24:m,25:h,26:g,27:_,28:v,29:y,30:b,31:x,33:S,35:C,36:w,37:24,38:T,40:E},e(t,[2,7],{1:[2,1]}),e(t,[2,3]),{9:36,11:17,12:r,13:i,14:a,15:o,16:s,17:c,18:l,19:18,20:u,21:d,22:f,23:p,24:m,25:h,26:g,27:_,28:v,29:y,30:b,31:x,33:S,35:C,36:w,37:24,38:T,40:E},e(t,[2,5]),e(t,[2,6]),e(t,[2,17]),e(t,[2,18]),e(t,[2,19]),e(t,[2,20]),e(t,[2,21]),e(t,[2,22]),e(t,[2,23]),e(t,[2,24]),e(t,[2,25]),e(t,[2,26]),e(t,[2,27]),{32:[1,37]},{34:[1,38]},e(t,[2,30]),e(t,[2,31]),e(t,[2,32]),{39:[1,39]},e(t,[2,8]),e(t,[2,9]),e(t,[2,10]),e(t,[2,11]),e(t,[2,12]),e(t,[2,13]),e(t,[2,14]),e(t,[2,15]),e(t,[2,16]),{41:[1,40],43:[1,41]},e(t,[2,4]),e(t,[2,28]),e(t,[2,29]),e(t,[2,33]),e(t,[2,34],{42:[1,42],43:[1,43]}),e(t,[2,40],{41:[1,44]}),e(t,[2,35],{43:[1,45]}),e(t,[2,36]),e(t,[2,38],{42:[1,46]}),e(t,[2,37]),e(t,[2,39])],defaultActions:{},parseError:n(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:n(function(e){var t=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(e,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}n(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=t.symbols_[e]||e),e}n(x,`lex`);for(var S,C,w,T,E,D={},O,k,ee,A;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var te=``;for(O in A=[],s[w])this.terminals_[O]&&O>f&&A.push(`'`+this.terminals_[O]+`'`);te=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+A.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(te,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:A})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),ee=s[r[r.length-2]][r[r.length-1]],r.push(ee);break;case 3:return!0}}return!0},`parse`)};D.lexer=(function(){return{EOF:1,parseError:n(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:n(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:n(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:n(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:n(function(){return this._more=!0,this},`more`),reject:n(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:n(function(e){this.unput(this.match.slice(e))},`less`),pastInput:n(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:n(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:n(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:n(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:n(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:n(function(){return this.next()||this.lex()},`lex`),begin:n(function(e){this.conditionStack.push(e)},`begin`),popState:n(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:n(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:n(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:n(function(e){this.begin(e)},`pushState`),stateStackSize:n(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:n(function(e,t,n,r){switch(n){case 0:return this.begin(`open_directive`),`open_directive`;case 1:return this.begin(`acc_title`),31;case 2:return this.popState(),`acc_title_value`;case 3:return this.begin(`acc_descr`),33;case 4:return this.popState(),`acc_descr_value`;case 5:this.begin(`acc_descr_multiline`);break;case 6:this.popState();break;case 7:return`acc_descr_multiline_value`;case 8:break;case 9:break;case 10:break;case 11:return 10;case 12:break;case 13:break;case 14:this.begin(`href`);break;case 15:this.popState();break;case 16:return 43;case 17:this.begin(`callbackname`);break;case 18:this.popState();break;case 19:this.popState(),this.begin(`callbackargs`);break;case 20:return 41;case 21:this.popState();break;case 22:return 42;case 23:this.begin(`click`);break;case 24:this.popState();break;case 25:return 40;case 26:return 4;case 27:return 22;case 28:return 23;case 29:return 24;case 30:return 25;case 31:return 26;case 32:return 28;case 33:return 27;case 34:return 29;case 35:return 12;case 36:return 13;case 37:return 14;case 38:return 15;case 39:return 16;case 40:return 17;case 41:return 18;case 42:return 20;case 43:return 21;case 44:return`date`;case 45:return 30;case 46:return`accDescription`;case 47:return 36;case 48:return 38;case 49:return 39;case 50:return`:`;case 51:return 6;case 52:return`INVALID`}},`anonymous`),rules:[/^(?:%%\{)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:%%(?!\{)*[^\n]*)/i,/^(?:[^\}]%%*[^\n]*)/i,/^(?:%%*[^\n]*[\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:%[^\n]*)/i,/^(?:href[\s]+["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:call[\s]+)/i,/^(?:\([\s]*\))/i,/^(?:\()/i,/^(?:[^(]*)/i,/^(?:\))/i,/^(?:[^)]*)/i,/^(?:click[\s]+)/i,/^(?:[\s\n])/i,/^(?:[^\s\n]*)/i,/^(?:gantt\b)/i,/^(?:dateFormat\s[^#\n;]+)/i,/^(?:inclusiveEndDates\b)/i,/^(?:topAxis\b)/i,/^(?:axisFormat\s[^#\n;]+)/i,/^(?:tickInterval\s[^#\n;]+)/i,/^(?:includes\s[^#\n;]+)/i,/^(?:excludes\s[^#\n;]+)/i,/^(?:todayMarker\s[^\n;]+)/i,/^(?:weekday\s+monday\b)/i,/^(?:weekday\s+tuesday\b)/i,/^(?:weekday\s+wednesday\b)/i,/^(?:weekday\s+thursday\b)/i,/^(?:weekday\s+friday\b)/i,/^(?:weekday\s+saturday\b)/i,/^(?:weekday\s+sunday\b)/i,/^(?:weekend\s+friday\b)/i,/^(?:weekend\s+saturday\b)/i,/^(?:\d\d\d\d-\d\d-\d\d\b)/i,/^(?:title\s[^\n]+)/i,/^(?:accDescription\s[^#\n;]+)/i,/^(?:section\s[^\n]+)/i,/^(?:[^:\n]+)/i,/^(?::[^#\n;]+)/i,/^(?::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[6,7],inclusive:!1},acc_descr:{rules:[4],inclusive:!1},acc_title:{rules:[2],inclusive:!1},callbackargs:{rules:[21,22],inclusive:!1},callbackname:{rules:[18,19,20],inclusive:!1},href:{rules:[15,16],inclusive:!1},click:{rules:[24,25],inclusive:!1},INITIAL:{rules:[0,1,3,5,8,9,10,11,12,13,14,17,23,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52],inclusive:!0}}}})();function O(){this.yy={}}return n(O,`Parser`),O.prototype=D,D.Parser=O,new O})();Zn.parser=Zn;var Qn=Zn;J.default.extend(qn.default),J.default.extend(Jn.default),J.default.extend(Yn.default);var $n={friday:5,saturday:6},Y=``,er=``,tr=void 0,nr=``,rr=[],ir=[],ar=new Map,or=[],sr=[],X=``,cr=``,lr=[`active`,`done`,`crit`,`milestone`,`vert`],ur=[],dr=``,fr=!1,pr=!1,mr=`sunday`,hr=`saturday`,gr=0,_r=n(function(){or=[],sr=[],X=``,ur=[],Zr=0,ti=void 0,ni=void 0,Z=[],Y=``,er=``,cr=``,tr=void 0,nr=``,rr=[],ir=[],fr=!1,pr=!1,gr=0,ar=new Map,dr=``,g(),mr=`sunday`,hr=`saturday`},`clear`),vr=n(function(e){dr=e},`setDiagramId`),yr=n(function(e){er=e},`setAxisFormat`),br=n(function(){return er},`getAxisFormat`),xr=n(function(e){tr=e},`setTickInterval`),Sr=n(function(){return tr},`getTickInterval`),Cr=n(function(e){nr=e},`setTodayMarker`),wr=n(function(){return nr},`getTodayMarker`),Tr=n(function(e){Y=e},`setDateFormat`),Er=n(function(){fr=!0},`enableInclusiveEndDates`),Dr=n(function(){return fr},`endDatesAreInclusive`),Or=n(function(){pr=!0},`enableTopAxis`),kr=n(function(){return pr},`topAxisEnabled`),Ar=n(function(e){cr=e},`setDisplayMode`),jr=n(function(){return cr},`getDisplayMode`),Mr=n(function(){return Y},`getDateFormat`),Nr=n((e,t)=>{let n=t.toLowerCase().split(/[\s,]+/).filter(e=>e!==``);return[...new Set([...e,...n])]},`mergeTokens`),Pr=n(function(e){rr=Nr(rr,e)},`setIncludes`),Fr=n(function(){return rr},`getIncludes`),Ir=n(function(e){ir=Nr(ir,e)},`setExcludes`),Lr=n(function(){return ir},`getExcludes`),Rr=n(function(){return ar},`getLinks`),zr=n(function(e){X=e,or.push(e)},`addSection`),Br=n(function(){return or},`getSections`),Vr=n(function(){let e=oi(),t=0;for(;!e&&t<10;)e=oi(),t++;return sr=Z,sr},`getTasks`),Hr=n(function(e,t,n,r){let i=e.format(t.trim()),a=e.format(`YYYY-MM-DD`);return r.includes(i)||r.includes(a)?!1:n.includes(`weekends`)&&(e.isoWeekday()===$n[hr]||e.isoWeekday()===$n[hr]+1)||n.includes(e.format(`dddd`).toLowerCase())?!0:n.includes(i)||n.includes(a)},`isInvalidDate`),Ur=n(function(e){mr=e},`setWeekday`),Wr=n(function(){return mr},`getWeekday`),Gr=n(function(e){hr=e},`setWeekend`),Kr=n(function(e,t,n,r){if(!n.length||e.manualEndTime)return;let i;i=e.startTime instanceof Date?(0,J.default)(e.startTime):(0,J.default)(e.startTime,t,!0),i=i.add(1,`d`);let a;a=e.endTime instanceof Date?(0,J.default)(e.endTime):(0,J.default)(e.endTime,t,!0);let[o,s]=qr(i,a,t,n,r);e.endTime=o.toDate(),e.renderEndTime=s},`checkTaskDates`),qr=n(function(e,t,n,r,i){let a=!1,o=null,s=t.add(1e4,`d`);for(;e<=t;){if(a||(o=t.toDate()),a=Hr(e,n,r,i),a&&(t=t.add(1,`d`),t>s))throw Error("Failed to find a valid date that was not excluded by `excludes` after 10,000 iterations.");e=e.add(1,`d`)}return[t,o]},`fixTaskDates`),Jr=n(function(e,t,r){if(r=r.trim(),n(e=>{let t=e.trim();return t===`x`||t===`X`},`isTimestampFormat`)(t)&&/^\d+$/.test(r))return new Date(Number(r));let i=/^after\s+(?[\d\w- ]+)/.exec(r);if(i!==null){let e=null;for(let t of i.groups.ids.split(` `)){let n=Q(t);n!==void 0&&(!e||n.endTime>e.endTime)&&(e=n)}if(e)return e.endTime;let t=new Date;return t.setHours(0,0,0,0),t}let a=(0,J.default)(r,t.trim(),!0);if(a.isValid())return a.toDate();{l.debug(`Invalid date:`+r),l.debug(`With date format:`+t.trim());let e=new Date(r);if(e===void 0||isNaN(e.getTime())||e.getFullYear()<-1e4||e.getFullYear()>1e4)throw Error(`Invalid date:`+r);return e}},`getStartDate`),Yr=n(function(e){let t=/^(\d+(?:\.\d+)?)([Mdhmswy]|ms)$/.exec(e.trim());return t===null?[NaN,`ms`]:[Number.parseFloat(t[1]),t[2]]},`parseDuration`),Xr=n(function(e,t,n,r=!1){n=n.trim();let i=/^until\s+(?[\d\w- ]+)/.exec(n);if(i!==null){let e=null;for(let t of i.groups.ids.split(` `)){let n=Q(t);n!==void 0&&(!e||n.startTime{window.open(n,`_self`)}),ar.set(e,n))}),ci(e,`clickable`)},`setLink`),ci=n(function(e,t){e.split(`,`).forEach(function(e){let n=Q(e);n!==void 0&&n.classes.push(t)})},`setClass`),li=n(function(e,t,n){if(x().securityLevel!==`loose`||t===void 0)return;let r=[];if(typeof n==`string`){r=n.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(let e=0;e{ee.runFunc(t,...r)})},`setClickFun`),ui=n(function(e,t){ur.push(function(){let n=dr?`${dr}-${e}`:e,r=document.querySelector(`[id="${n}"]`);r!==null&&r.addEventListener(`click`,function(){t()})},function(){let n=dr?`${dr}-${e}`:e,r=document.querySelector(`[id="${n}-text"]`);r!==null&&r.addEventListener(`click`,function(){t()})})},`pushFun`),di={getConfig:n(()=>x().gantt,`getConfig`),clear:_r,setDateFormat:Tr,getDateFormat:Mr,enableInclusiveEndDates:Er,endDatesAreInclusive:Dr,enableTopAxis:Or,topAxisEnabled:kr,setAxisFormat:yr,getAxisFormat:br,setTickInterval:xr,getTickInterval:Sr,setTodayMarker:Cr,getTodayMarker:wr,setAccTitle:h,getAccTitle:S,setDiagramTitle:m,getDiagramTitle:b,setDiagramId:vr,setDisplayMode:Ar,getDisplayMode:jr,setAccDescription:p,getAccDescription:y,addSection:zr,getSections:Br,getTasks:Vr,addTask:ii,findTaskById:Q,addTaskOrg:ai,setIncludes:Pr,getIncludes:Fr,setExcludes:Ir,getExcludes:Lr,setClickEvent:n(function(e,t,n){e.split(`,`).forEach(function(e){li(e,t,n)}),ci(e,`clickable`)},`setClickEvent`),setLink:si,getLinks:Rr,bindFunctions:n(function(e){ur.forEach(function(t){t(e)})},`bindFunctions`),parseDuration:Yr,isInvalidDate:Hr,setWeekday:Ur,getWeekday:Wr,setWeekend:Gr};function fi(e,t,n){let r=!0;for(;r;)r=!1,n.forEach(function(n){let i=`^\\s*`+n+`\\s*$`,a=new RegExp(i);e[0].match(a)&&(t[n]=!0,e.shift(1),r=!0)})}n(fi,`getTaskTags`),J.default.extend(Xn.default);var pi=n(function(){l.debug(`Something is calling, setConf, remove the call`)},`setConf`),mi={monday:Xe,tuesday:Ze,wednesday:Qe,thursday:H,friday:$e,saturday:et,sunday:Ye},hi=n((e,t)=>{let n=[...e].map(()=>-1/0),r=[...e].sort((e,t)=>e.startTime-t.startTime||e.order-t.order),i=0;for(let e of r)for(let r=0;r=n[r]){n[r]=e.endTime,e.order=r+t,r>i&&(i=r);break}return i},`getMaxIntersections`),$,gi=1e4,_i={parser:Qn,db:di,renderer:{setConf:pi,draw:n(function(e,t,r,i){let a=x().gantt;i.db.setDiagramId(t);let o=x().securityLevel,s;o===`sandbox`&&(s=u(`#i`+t));let c=u(o===`sandbox`?s.nodes()[0].contentDocument.body:`body`),d=o===`sandbox`?s.nodes()[0].contentDocument:document,f=d.getElementById(t);$=f.parentElement.offsetWidth,$===void 0&&($=1200),a.useWidth!==void 0&&($=a.useWidth);let p=i.db.getTasks(),m=p.filter(e=>!e.vert),h=[];for(let e of m)h.push(e.type);h=j(h);let g={},y=2*a.topPadding;if(i.db.getDisplayMode()===`compact`||a.displayMode===`compact`){let e={};for(let t of m)e[t.section]===void 0?e[t.section]=[t]:e[t.section].push(t);let t=0;for(let n of Object.keys(e)){let r=hi(e[n],t)+1;t+=r,y+=r*(a.barHeight+a.barGap),g[n]=r}}else{y+=m.length*(a.barHeight+a.barGap);for(let e of h)g[e]=m.filter(t=>t.type===e).length}f.setAttribute(`viewBox`,`0 0 `+$+` `+y);let b=c.select(`[id="${t}"]`),S=Vn().domain([te(p,function(e){return e.startTime}),A(p,function(e){return e.endTime})]).rangeRound([0,$-a.leftPadding-a.rightPadding]);function C(e,t){let n=e.startTime,r=t.startTime,i=0;return n>r?i=1:ne.vert===t.vert?0:e.vert?1:-1);let d=e.filter(e=>!e.vert),f=[...new Set(d.map(e=>e.order))].map(e=>d.find(t=>t.order===e));b.append(`g`).selectAll(`rect`).data(f).enter().append(`rect`).attr(`x`,0).attr(`y`,function(e,t){return t=e.order,t*n+r-2}).attr(`width`,function(){return l-a.rightPadding/2}).attr(`height`,n).attr(`class`,function(e){for(let[t,n]of h.entries())if(e.type===n)return`section section`+t%a.numberSectionStyles;return`section section0`}).enter();let p=b.append(`g`).selectAll(`rect`).data(e).enter(),m=i.db.getLinks();if(p.append(`rect`).attr(`id`,function(e){return t+`-`+e.id}).attr(`rx`,3).attr(`ry`,3).attr(`x`,function(e){return e.milestone?S(e.startTime)+o+.5*(S(e.endTime)-S(e.startTime))-.5*s:S(e.startTime)+o}).attr(`y`,function(e,t){return t=e.order,e.vert?a.gridLineStartPadding:t*n+r}).attr(`width`,function(e){return e.milestone?s:e.vert?.08*s:S(e.renderEndTime||e.endTime)-S(e.startTime)}).attr(`height`,function(e){return e.vert?d.length*(a.barHeight+a.barGap)+a.barHeight*2:s}).attr(`transform-origin`,function(e,t){return t=e.order,(S(e.startTime)+o+.5*(S(e.endTime)-S(e.startTime))).toString()+`px `+(t*n+r+.5*s).toString()+`px`}).attr(`class`,function(e){let t=``;e.classes.length>0&&(t=e.classes.join(` `));let n=0;for(let[t,r]of h.entries())e.type===r&&(n=t%a.numberSectionStyles);let r=``;return e.active?e.crit?r+=` activeCrit`:r=` active`:e.done?r=e.crit?` doneCrit`:` done`:e.crit&&(r+=` crit`),r.length===0&&(r=` task`),e.milestone&&(r=` milestone `+r),e.vert&&(r=` vert `+r),r+=n,r+=` `+t,`task`+r}),p.append(`text`).attr(`id`,function(e){return t+`-`+e.id+`-text`}).text(function(e){return e.task}).attr(`font-size`,a.fontSize).attr(`x`,function(e){let t=S(e.startTime),n=S(e.renderEndTime||e.endTime);if(e.milestone&&(t+=.5*(S(e.endTime)-S(e.startTime))-.5*s,n=t+s),e.vert)return S(e.startTime)+o;let r=this.getBBox().width;return r>n-t?n+r+1.5*a.leftPadding>l?t+o-5:n+o+5:(n-t)/2+t+o}).attr(`y`,function(e,t){return e.vert?a.gridLineStartPadding+d.length*(a.barHeight+a.barGap)+60:(t=e.order,t*n+a.barHeight/2+(a.fontSize/2-2)+r)}).attr(`text-height`,s).attr(`class`,function(e){let t=S(e.startTime),n=S(e.endTime);e.milestone&&(n=t+s);let r=this.getBBox().width,i=``;e.classes.length>0&&(i=e.classes.join(` `));let o=0;for(let[t,n]of h.entries())e.type===n&&(o=t%a.numberSectionStyles);let c=``;return e.active&&(c=e.crit?`activeCritText`+o:`activeText`+o),e.done?c=e.crit?c+` doneCritText`+o:c+` doneText`+o:e.crit&&(c=c+` critText`+o),e.milestone&&(c+=` milestoneText`),e.vert&&(c+=` vertText`),r>n-t?n+r+1.5*a.leftPadding>l?i+` taskTextOutsideLeft taskTextOutside`+o+` `+c:i+` taskTextOutsideRight taskTextOutside`+o+` `+c+` width-`+r:i+` taskText taskText`+o+` `+c+` width-`+r}),x().securityLevel===`sandbox`){let e;e=u(`#i`+t);let n=e.nodes()[0].contentDocument;p.filter(function(e){return m.has(e.id)}).each(function(e){var r=n.querySelector(`#`+CSS.escape(t+`-`+e.id)),i=n.querySelector(`#`+CSS.escape(t+`-`+e.id+`-text`));let a=r.parentNode;var o=n.createElement(`a`);o.setAttribute(`xlink:href`,m.get(e.id)),o.setAttribute(`target`,`_top`),a.appendChild(o),o.appendChild(r),o.appendChild(i)})}}n(T,`drawRects`);function E(e,n,r,o,s,c,u,d){if(u.length===0&&d.length===0)return;let f,p;for(let{startTime:e,endTime:t}of c)(f===void 0||ep)&&(p=t);if(!f||!p)return;if((0,J.default)(p).diff((0,J.default)(f),`year`)>5){l.warn(`The difference between the min and max time is more than 5 years. This will cause performance issues. Skipping drawing exclude days.`);return}let m=i.db.getDateFormat(),h=[],g=null,_=(0,J.default)(f);for(;_.valueOf()<=p;)i.db.isInvalidDate(_,m,u,d)?g?g.end=_:g={start:_,end:_}:g&&=(h.push(g),null),_=_.add(1,`d`);b.append(`g`).selectAll(`rect`).data(h).enter().append(`rect`).attr(`id`,e=>t+`-exclude-`+e.start.format(`YYYY-MM-DD`)).attr(`x`,e=>S(e.start.startOf(`day`))+r).attr(`y`,a.gridLineStartPadding).attr(`width`,e=>S(e.end.endOf(`day`))-S(e.start.startOf(`day`))).attr(`height`,s-n-a.gridLineStartPadding).attr(`transform-origin`,function(t,n){return(S(t.start)+r+.5*(S(t.end)-S(t.start))).toString()+`px `+(n*e+.5*s).toString()+`px`}).attr(`class`,`exclude-range`)}n(E,`drawExcludeDays`);function O(e,t,n,r){if(n<=0||e>t)return 1/0;let i=t-e,a=J.default.duration({[r??`day`]:n}).asMilliseconds();return a<=0?1/0:Math.ceil(i/a)}n(O,`getEstimatedTickCount`);function k(e,t,n,r){let o=i.db.getDateFormat(),s=i.db.getAxisFormat(),c;c=s||(o===`D`?`%d`:a.axisFormat??`%Y-%m-%d`);let u=me(S).tickSize(-r+t+a.gridLineStartPadding).tickFormat(In(c)),d=/^([1-9]\d*)(millisecond|second|minute|hour|day|week|month)$/.exec(i.db.getTickInterval()||a.tickInterval);if(d!==null){let e=parseInt(d[1],10);if(isNaN(e)||e<=0)l.warn(`Invalid tick interval value: "${d[1]}". Skipping custom tick interval.`);else{let t=d[2],n=i.db.getWeekday()||a.weekday,r=S.domain(),o=r[0],s=r[1],c=O(o,s,e,t);if(c>gi)l.warn(`The tick interval "${e}${t}" would generate ${c} ticks, which exceeds the maximum allowed (${gi}). This may indicate an invalid date or time range. Skipping custom tick interval.`);else switch(t){case`millisecond`:u.ticks(ze.every(e));break;case`second`:u.ticks(z.every(e));break;case`minute`:u.ticks(Ue.every(e));break;case`hour`:u.ticks(Ge.every(e));break;case`day`:u.ticks(B.every(e));break;case`week`:u.ticks(mi[n].every(e));break;case`month`:u.ticks(ct.every(e));break}}}if(b.append(`g`).attr(`class`,`grid`).attr(`transform`,`translate(`+e+`, `+(r-50)+`)`).call(u).selectAll(`text`).style(`text-anchor`,`middle`).attr(`fill`,`#000`).attr(`stroke`,`none`).attr(`font-size`,10).attr(`dy`,`1em`),i.db.topAxisEnabled()||a.topAxis){let n=pe(S).tickSize(-r+t+a.gridLineStartPadding).tickFormat(In(c));if(d!==null){let e=parseInt(d[1],10);if(isNaN(e)||e<=0)l.warn(`Invalid tick interval value: "${d[1]}". Skipping custom tick interval.`);else{let t=d[2],r=i.db.getWeekday()||a.weekday,o=S.domain(),s=o[0],c=o[1];if(O(s,c,e,t)<=gi)switch(t){case`millisecond`:n.ticks(ze.every(e));break;case`second`:n.ticks(z.every(e));break;case`minute`:n.ticks(Ue.every(e));break;case`hour`:n.ticks(Ge.every(e));break;case`day`:n.ticks(B.every(e));break;case`week`:n.ticks(mi[r].every(e));break;case`month`:n.ticks(ct.every(e));break}}}b.append(`g`).attr(`class`,`grid`).attr(`transform`,`translate(`+e+`, `+t+`)`).call(n).selectAll(`text`).style(`text-anchor`,`middle`).attr(`fill`,`#000`).attr(`stroke`,`none`).attr(`font-size`,10)}}n(k,`makeGrid`);function ee(e,t){let n=0,r=Object.keys(g).map(e=>[e,g[e]]);b.append(`g`).selectAll(`text`).data(r).enter().append(function(e){let t=e[0].split(v.lineBreakRegex),n=-(t.length-1)/2,r=d.createElementNS(`http://www.w3.org/2000/svg`,`text`);r.setAttribute(`dy`,n+`em`);for(let[e,n]of t.entries()){let t=d.createElementNS(`http://www.w3.org/2000/svg`,`tspan`);t.setAttribute(`alignment-baseline`,`central`),t.setAttribute(`x`,`10`),e>0&&t.setAttribute(`dy`,`1em`),t.textContent=n,r.appendChild(t)}return r}).attr(`x`,10).attr(`y`,function(i,a){if(a>0)for(let o=0;o` + .mermaid-main-font { + font-family: ${e.fontFamily}; + } + + .exclude-range { + fill: ${e.excludeBkgColor}; + } + + .section { + stroke: none; + opacity: 0.2; + } + + .section0 { + fill: ${e.sectionBkgColor}; + } + + .section2 { + fill: ${e.sectionBkgColor2}; + } + + .section1, + .section3 { + fill: ${e.altSectionBkgColor}; + opacity: 0.2; + } + + .sectionTitle0 { + fill: ${e.titleColor}; + } + + .sectionTitle1 { + fill: ${e.titleColor}; + } + + .sectionTitle2 { + fill: ${e.titleColor}; + } + + .sectionTitle3 { + fill: ${e.titleColor}; + } + + .sectionTitle { + text-anchor: start; + font-family: ${e.fontFamily}; + } + + + /* Grid and axis */ + + .grid .tick { + stroke: ${e.gridColor}; + opacity: 0.8; + shape-rendering: crispEdges; + } + + .grid .tick text { + font-family: ${e.fontFamily}; + fill: ${e.textColor}; + } + + .grid path { + stroke-width: 0; + } + + + /* Today line */ + + .today { + fill: none; + stroke: ${e.todayLineColor}; + stroke-width: 2px; + } + + + /* Task styling */ + + /* Default task */ + + .task { + stroke-width: 2; + } + + .taskText { + text-anchor: middle; + font-family: ${e.fontFamily}; + } + + .taskTextOutsideRight { + fill: ${e.taskTextDarkColor}; + text-anchor: start; + font-family: ${e.fontFamily}; + } + + .taskTextOutsideLeft { + fill: ${e.taskTextDarkColor}; + text-anchor: end; + } + + + /* Special case clickable */ + + .task.clickable { + cursor: pointer; + } + + .taskText.clickable { + cursor: pointer; + fill: ${e.taskTextClickableColor} !important; + font-weight: bold; + } + + .taskTextOutsideLeft.clickable { + cursor: pointer; + fill: ${e.taskTextClickableColor} !important; + font-weight: bold; + } + + .taskTextOutsideRight.clickable { + cursor: pointer; + fill: ${e.taskTextClickableColor} !important; + font-weight: bold; + } + + + /* Specific task settings for the sections*/ + + .taskText0, + .taskText1, + .taskText2, + .taskText3 { + fill: ${e.taskTextColor}; + } + + .task0, + .task1, + .task2, + .task3 { + fill: ${e.taskBkgColor}; + stroke: ${e.taskBorderColor}; + } + + .taskTextOutside0, + .taskTextOutside2 + { + fill: ${e.taskTextOutsideColor}; + } + + .taskTextOutside1, + .taskTextOutside3 { + fill: ${e.taskTextOutsideColor}; + } + + + /* Active task */ + + .active0, + .active1, + .active2, + .active3 { + fill: ${e.activeTaskBkgColor}; + stroke: ${e.activeTaskBorderColor}; + } + + .activeText0, + .activeText1, + .activeText2, + .activeText3 { + fill: ${e.taskTextDarkColor} !important; + } + + + /* Completed task */ + + .done0, + .done1, + .done2, + .done3 { + stroke: ${e.doneTaskBorderColor}; + fill: ${e.doneTaskBkgColor}; + stroke-width: 2; + } + + .doneText0, + .doneText1, + .doneText2, + .doneText3 { + fill: ${e.taskTextDarkColor} !important; + } + + /* Done task text displayed outside the bar sits against the diagram background, + not against the done-task bar, so it must use the outside/contrast color. */ + .doneText0.taskTextOutsideLeft, + .doneText0.taskTextOutsideRight, + .doneText1.taskTextOutsideLeft, + .doneText1.taskTextOutsideRight, + .doneText2.taskTextOutsideLeft, + .doneText2.taskTextOutsideRight, + .doneText3.taskTextOutsideLeft, + .doneText3.taskTextOutsideRight { + fill: ${e.taskTextOutsideColor} !important; + } + + + /* Tasks on the critical line */ + + .crit0, + .crit1, + .crit2, + .crit3 { + stroke: ${e.critBorderColor}; + fill: ${e.critBkgColor}; + stroke-width: 2; + } + + .activeCrit0, + .activeCrit1, + .activeCrit2, + .activeCrit3 { + stroke: ${e.critBorderColor}; + fill: ${e.activeTaskBkgColor}; + stroke-width: 2; + } + + .doneCrit0, + .doneCrit1, + .doneCrit2, + .doneCrit3 { + stroke: ${e.critBorderColor}; + fill: ${e.doneTaskBkgColor}; + stroke-width: 2; + cursor: pointer; + shape-rendering: crispEdges; + } + + .milestone { + transform: rotate(45deg) scale(0.8,0.8); + } + + .milestoneText { + font-style: italic; + } + .doneCritText0, + .doneCritText1, + .doneCritText2, + .doneCritText3 { + fill: ${e.taskTextDarkColor} !important; + } + + /* Done-crit task text outside the bar \u2014 same reasoning as doneText above. */ + .doneCritText0.taskTextOutsideLeft, + .doneCritText0.taskTextOutsideRight, + .doneCritText1.taskTextOutsideLeft, + .doneCritText1.taskTextOutsideRight, + .doneCritText2.taskTextOutsideLeft, + .doneCritText2.taskTextOutsideRight, + .doneCritText3.taskTextOutsideLeft, + .doneCritText3.taskTextOutsideRight { + fill: ${e.taskTextOutsideColor} !important; + } + + .vert { + stroke: ${e.vertLineColor}; + } + + .vertText { + font-size: 15px; + text-anchor: middle; + fill: ${e.vertLineColor} !important; + } + + .activeCritText0, + .activeCritText1, + .activeCritText2, + .activeCritText3 { + fill: ${e.taskTextDarkColor} !important; + } + + .titleText { + text-anchor: middle; + font-size: 18px; + fill: ${e.titleColor||e.textColor}; + font-family: ${e.fontFamily}; + } +`,`getStyles`)};export{_i as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/gitGraph-TEB2WS4Q-Do0SQOtM.js b/dist-desktop/assets/gitGraph-TEB2WS4Q-Do0SQOtM.js new file mode 100644 index 0000000..eb0ae78 --- /dev/null +++ b/dist-desktop/assets/gitGraph-TEB2WS4Q-Do0SQOtM.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-CYSBUYHQ-CbOq7Rc1.js";export{e as createGitGraphServices}; \ No newline at end of file diff --git a/dist-desktop/assets/gitGraphDiagram-IHSO6WYX-CPtw8GFs.js b/dist-desktop/assets/gitGraphDiagram-IHSO6WYX-CPtw8GFs.js new file mode 100644 index 0000000..fdc61da --- /dev/null +++ b/dist-desktop/assets/gitGraphDiagram-IHSO6WYX-CPtw8GFs.js @@ -0,0 +1,106 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{H as r,K as i,U as a,Y as o,a as s,b as c,f as l,s as u,v as d,w as f,x as p,y as m}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{g as h,i as g,m as _}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as v}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as y}from"./mermaid-parser.core-Z7xZAZRH.js";import{t as b}from"./chunk-2Q5K7J3B-C1jixKkw.js";var x={NORMAL:0,REVERSE:1,HIGHLIGHT:2,MERGE:3,CHERRY_PICK:4},ee=l.gitGraph,S=e(()=>g({...ee,...c().gitGraph}),`getConfig`),C=new b(()=>{let e=S(),t=e.mainBranchName,n=e.mainBranchOrder;return{mainBranchName:t,commits:new Map,head:null,branchConfig:new Map([[t,{name:t,order:n}]]),branches:new Map([[t,null]]),currBranch:t,direction:`LR`,seq:0,options:{}}});function w(){return _({length:7})}e(w,`getID`);function T(e,t){let n=Object.create(null);return e.reduce((e,r)=>{let i=t(r);return n[i]||(n[i]=!0,e.push(r)),e},[])}e(T,`uniqBy`);var te=e(function(e){C.records.direction=e},`setDirection`),ne=e(function(e){t.debug(`options str`,e),e=e?.trim(),e||=`{}`;try{C.records.options=JSON.parse(e)}catch(e){t.error(`error while parsing gitGraph options`,e.message)}},`setOptions`),re=e(function(){return C.records.options},`getOptions`),ie=e(function(e){let n=e.msg,r=e.id,i=e.type,a=e.tags;t.info(`commit`,n,r,i,a),t.debug(`Entering commit:`,n,r,i,a);let o=S();r=u.sanitizeText(r,o),n=u.sanitizeText(n,o),a=a?.map(e=>u.sanitizeText(e,o));let s={id:r||C.records.seq+`-`+w(),message:n,seq:C.records.seq++,type:i??x.NORMAL,tags:a??[],parents:C.records.head==null?[]:[C.records.head.id],branch:C.records.currBranch};C.records.head=s,t.info(`main branch`,o.mainBranchName),C.records.commits.has(s.id)&&t.warn(`Commit ID ${s.id} already exists`),C.records.commits.set(s.id,s),C.records.branches.set(C.records.currBranch,s.id),t.debug(`in pushCommit `+s.id)},`commit`),ae=e(function(e){let n=e.name,r=e.order;if(n=u.sanitizeText(n,S()),C.records.branches.has(n))throw Error(`Trying to create an existing branch. (Help: Either use a new name if you want create a new branch or try using "checkout ${n}")`);C.records.branches.set(n,C.records.head==null?null:C.records.head.id),C.records.branchConfig.set(n,{name:n,order:r}),E(n),t.debug(`in createBranch`)},`branch`),oe=e(e=>{let n=e.branch,r=e.id,i=e.type,a=e.tags,o=S();n=u.sanitizeText(n,o),r&&=u.sanitizeText(r,o);let s=C.records.branches.get(C.records.currBranch),c=C.records.branches.get(n),l=s?C.records.commits.get(s):void 0,d=c?C.records.commits.get(c):void 0;if(l&&d&&l.branch===n)throw Error(`Cannot merge branch '${n}' into itself.`);if(C.records.currBranch===n){let e=Error(`Incorrect usage of "merge". Cannot merge a branch to itself`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`branch abc`]},e}if(l===void 0||!l){let e=Error(`Incorrect usage of "merge". Current branch (${C.records.currBranch})has no commits`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`commit`]},e}if(!C.records.branches.has(n)){let e=Error(`Incorrect usage of "merge". Branch to be merged (`+n+`) does not exist`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`branch ${n}`]},e}if(d===void 0||!d){let e=Error(`Incorrect usage of "merge". Branch to be merged (`+n+`) has no commits`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`"commit"`]},e}if(l===d){let e=Error(`Incorrect usage of "merge". Both branches have same head`);throw e.hash={text:`merge ${n}`,token:`merge ${n}`,expected:[`branch abc`]},e}if(r&&C.records.commits.has(r)){let e=Error(`Incorrect usage of "merge". Commit with id:`+r+` already exists, use different custom id`);throw e.hash={text:`merge ${n} ${r} ${i} ${a?.join(` `)}`,token:`merge ${n} ${r} ${i} ${a?.join(` `)}`,expected:[`merge ${n} ${r}_UNIQUE ${i} ${a?.join(` `)}`]},e}let f=c||``,p={id:r||`${C.records.seq}-${w()}`,message:`merged branch ${n} into ${C.records.currBranch}`,seq:C.records.seq++,parents:C.records.head==null?[]:[C.records.head.id,f],branch:C.records.currBranch,type:x.MERGE,customType:i,customId:!!r,tags:a??[]};C.records.head=p,C.records.commits.set(p.id,p),C.records.branches.set(C.records.currBranch,p.id),t.debug(C.records.branches),t.debug(`in mergeBranch`)},`merge`),se=e(function(e){let n=e.id,r=e.targetId,i=e.tags,a=e.parent;t.debug(`Entering cherryPick:`,n,r,i);let o=S();if(n=u.sanitizeText(n,o),r=u.sanitizeText(r,o),i=i?.map(e=>u.sanitizeText(e,o)),a=u.sanitizeText(a,o),!n||!C.records.commits.has(n)){let e=Error(`Incorrect usage of "cherryPick". Source commit id should exist and provided`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let s=C.records.commits.get(n);if(s===void 0||!s)throw Error(`Incorrect usage of "cherryPick". Source commit id should exist and provided`);if(a&&!(Array.isArray(s.parents)&&s.parents.includes(a)))throw Error(`Invalid operation: The specified parent commit is not an immediate parent of the cherry-picked commit.`);let c=s.branch;if(s.type===x.MERGE&&!a)throw Error(`Incorrect usage of cherry-pick: If the source commit is a merge commit, an immediate parent commit must be specified.`);if(!r||!C.records.commits.has(r)){if(c===C.records.currBranch){let e=Error(`Incorrect usage of "cherryPick". Source commit is already on current branch`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let e=C.records.branches.get(C.records.currBranch);if(e===void 0||!e){let e=Error(`Incorrect usage of "cherry-pick". Current branch (${C.records.currBranch})has no commits`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let o=C.records.commits.get(e);if(o===void 0||!o){let e=Error(`Incorrect usage of "cherry-pick". Current branch (${C.records.currBranch})has no commits`);throw e.hash={text:`cherryPick ${n} ${r}`,token:`cherryPick ${n} ${r}`,expected:[`cherry-pick abc`]},e}let l={id:C.records.seq+`-`+w(),message:`cherry-picked ${s?.message} into ${C.records.currBranch}`,seq:C.records.seq++,parents:C.records.head==null?[]:[C.records.head.id,s.id],branch:C.records.currBranch,type:x.CHERRY_PICK,tags:i?i.filter(Boolean):[`cherry-pick:${s.id}${s.type===x.MERGE?`|parent:${a}`:``}`]};C.records.head=l,C.records.commits.set(l.id,l),C.records.branches.set(C.records.currBranch,l.id),t.debug(C.records.branches),t.debug(`in cherryPick`)}},`cherryPick`),E=e(function(e){if(e=u.sanitizeText(e,S()),C.records.branches.has(e)){C.records.currBranch=e;let t=C.records.branches.get(C.records.currBranch);t===void 0||!t?C.records.head=null:C.records.head=C.records.commits.get(t)??null}else{let t=Error(`Trying to checkout branch which is not yet created. (Help try using "branch ${e}")`);throw t.hash={text:`checkout ${e}`,token:`checkout ${e}`,expected:[`branch ${e}`]},t}},`checkout`);function D(e,t,n){let r=e.indexOf(t);r===-1?e.push(n):e.splice(r,1,n)}e(D,`upsert`);function O(e){let n=e.reduce((e,t)=>e.seq>t.seq?e:t,e[0]),r=``;e.forEach(function(e){e===n?r+=` *`:r+=` |`});let i=[r,n.id,n.seq];for(let e in C.records.branches)C.records.branches.get(e)===n.id&&i.push(e);if(t.debug(i.join(` `)),n.parents&&n.parents.length==2&&n.parents[0]&&n.parents[1]){let t=C.records.commits.get(n.parents[0]);D(e,n,t),n.parents[1]&&e.push(C.records.commits.get(n.parents[1]))}else if(n.parents.length==0)return;else if(n.parents[0]){let t=C.records.commits.get(n.parents[0]);D(e,n,t)}e=T(e,e=>e.id),O(e)}e(O,`prettyPrintCommitHistory`);var ce=e(function(){t.debug(C.records.commits);let e=k()[0];O([e])},`prettyPrint`),le=e(function(){C.reset(),s()},`clear`),ue=e(function(){return[...C.records.branchConfig.values()].map((e,t)=>e.order!==null&&e.order!==void 0?e:{...e,order:parseFloat(`0.${t}`)}).sort((e,t)=>(e.order??0)-(t.order??0)).map(({name:e})=>({name:e}))},`getBranchesAsObjArray`),de=e(function(){return C.records.branches},`getBranches`),fe=e(function(){return C.records.commits},`getCommits`),k=e(function(){let e=[...C.records.commits.values()];return e.forEach(function(e){t.debug(e.id)}),e.sort((e,t)=>e.seq-t.seq),e},`getCommitsArray`),A={commitType:x,getConfig:S,setDirection:te,setOptions:ne,getOptions:re,commit:ie,branch:ae,merge:oe,cherryPick:se,checkout:E,prettyPrint:ce,clear:le,getBranchesAsObjArray:ue,getBranches:de,getCommits:fe,getCommitsArray:k,getCurrentBranch:e(function(){return C.records.currBranch},`getCurrentBranch`),getDirection:e(function(){return C.records.direction},`getDirection`),getHead:e(function(){return C.records.head},`getHead`),setAccTitle:a,getAccTitle:m,getAccDescription:d,setAccDescription:r,setDiagramTitle:i,getDiagramTitle:f},pe=e((e,t)=>{v(e,t),e.dir&&t.setDirection(e.dir);for(let n of e.statements)me(n,t)},`populate`),me=e((n,r)=>{let i={Commit:e(e=>r.commit(he(e)),`Commit`),Branch:e(e=>r.branch(ge(e)),`Branch`),Merge:e(e=>r.merge(_e(e)),`Merge`),Checkout:e(e=>r.checkout(ve(e)),`Checkout`),CherryPicking:e(e=>r.cherryPick(ye(e)),`CherryPicking`)}[n.$type];i?i(n):t.error(`Unknown statement type: ${n.$type}`)},`parseStatement`),he=e(e=>({id:e.id,msg:e.message??``,type:e.type===void 0?x.NORMAL:x[e.type],tags:e.tags??void 0}),`parseCommit`),ge=e(e=>({name:e.name,order:e.order??0}),`parseBranch`),_e=e(e=>({branch:e.branch,id:e.id??``,type:e.type===void 0?void 0:x[e.type],tags:e.tags??void 0}),`parseMerge`),ve=e(e=>e.branch,`parseCheckout`),ye=e(e=>({id:e.id,targetId:``,tags:e.tags?.length===0?void 0:e.tags,parent:e.parent}),`parseCherryPicking`),be={parse:e(async e=>{let n=await y(`gitGraph`,e);t.debug(n),pe(n,A)},`parse`)},j=10,M=40,N=4,P=2,F=8,I=new Set([`redux`,`redux-dark`,`redux-color`,`redux-dark-color`]),L=12,R=new Set([`redux-color`,`redux-dark-color`]),xe=new Set([`dark`,`redux-dark`,`redux-dark-color`,`neo-dark`]),z=e((e,t,n=!1)=>n&&e>0?(e-1)%(t-1)+1:e%t,`calcColorIndex`),B=new Map,V=new Map,H=30,U=new Map,W=[],G=0,K=`LR`,q=e(()=>{B.clear(),V.clear(),U.clear(),G=0,W=[],K=`LR`},`clear`),J=e(e=>{let t=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);return(typeof e==`string`?e.split(/\\n|\n|/gi):e).forEach(e=>{let n=document.createElementNS(`http://www.w3.org/2000/svg`,`tspan`);n.setAttributeNS(`http://www.w3.org/XML/1998/namespace`,`xml:space`,`preserve`),n.setAttribute(`dy`,`1em`),n.setAttribute(`x`,`0`),n.setAttribute(`class`,`row`),n.textContent=e.trim(),t.appendChild(n)}),t},`drawText`),Y=e(t=>{let n,r,i;return K===`BT`?(r=e((e,t)=>e<=t,`comparisonFunc`),i=1/0):(r=e((e,t)=>e>=t,`comparisonFunc`),i=0),t.forEach(e=>{let t=K===`TB`||K==`BT`?V.get(e)?.y:V.get(e)?.x;t!==void 0&&r(t,i)&&(n=e,i=t)}),n},`findClosestParent`),Se=e(e=>{let t=``,n=1/0;return e.forEach(e=>{let r=V.get(e).y;r<=n&&(t=e,n=r)}),t||void 0},`findClosestParentBT`),Ce=e((e,t,n)=>{let r=n,i=n,a=[];e.forEach(e=>{let n=t.get(e);if(!n)throw Error(`Commit not found for key ${e}`);n.parents.length?(r=Te(n),i=Math.max(r,i)):a.push(n),Ee(n,r)}),r=i,a.forEach(e=>{De(e,r,n)}),e.forEach(e=>{let n=t.get(e);if(n?.parents.length){let e=Se(n.parents);r=V.get(e).y-M,r<=i&&(i=r);let t=B.get(n.branch).pos,a=r-j;V.set(n.id,{x:t,y:a})}})},`setParallelBTPos`),we=e(e=>{let t=Y(e.parents.filter(e=>e!==null));if(!t)throw Error(`Closest parent not found for commit ${e.id}`);let n=V.get(t)?.y;if(n===void 0)throw Error(`Closest parent position not found for commit ${e.id}`);return n},`findClosestParentPos`),Te=e(e=>we(e)+M,`calculateCommitPosition`),Ee=e((e,t)=>{let n=B.get(e.branch);if(!n)throw Error(`Branch not found for commit ${e.id}`);let r=n.pos,i=t+j;return V.set(e.id,{x:r,y:i}),{x:r,y:i}},`setCommitPosition`),De=e((e,t,n)=>{let r=B.get(e.branch);if(!r)throw Error(`Branch not found for commit ${e.id}`);let i=t+n,a=r.pos;V.set(e.id,{x:a,y:i})},`setRootPosition`),Oe=e((e,t,n,r,i,a)=>{let{theme:o}=p(),s=I.has(o??``),c=R.has(o??``),l=xe.has(o??``);if(a===x.HIGHLIGHT)e.append(`rect`).attr(`x`,n.x-10+(s?3:0)).attr(`y`,n.y-10+(s?3:0)).attr(`width`,s?14:20).attr(`height`,s?14:20).attr(`class`,`commit ${t.id} commit-highlight${z(i,F,c)} ${r}-outer`),e.append(`rect`).attr(`x`,n.x-6+(s?2:0)).attr(`y`,n.y-6+(s?2:0)).attr(`width`,s?8:12).attr(`height`,s?8:12).attr(`class`,`commit ${t.id} commit${z(i,F,c)} ${r}-inner`);else if(a===x.CHERRY_PICK)e.append(`circle`).attr(`cx`,n.x).attr(`cy`,n.y).attr(`r`,s?7:10).attr(`class`,`commit ${t.id} ${r}`),e.append(`circle`).attr(`cx`,n.x-3).attr(`cy`,n.y+2).attr(`r`,s?2.5:2.75).attr(`fill`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`),e.append(`circle`).attr(`cx`,n.x+3).attr(`cy`,n.y+2).attr(`r`,s?2.5:2.75).attr(`fill`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`),e.append(`line`).attr(`x1`,n.x+3).attr(`y1`,n.y+1).attr(`x2`,n.x).attr(`y2`,n.y-5).attr(`stroke`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`),e.append(`line`).attr(`x1`,n.x-3).attr(`y1`,n.y+1).attr(`x2`,n.x).attr(`y2`,n.y-5).attr(`stroke`,l?`#000000`:`#fff`).attr(`class`,`commit ${t.id} ${r}`);else{let o=e.append(`circle`);if(o.attr(`cx`,n.x),o.attr(`cy`,n.y),o.attr(`r`,s?7:10),o.attr(`class`,`commit ${t.id} commit${z(i,F,c)}`),a===x.MERGE){let a=e.append(`circle`);a.attr(`cx`,n.x),a.attr(`cy`,n.y),a.attr(`r`,s?5:6),a.attr(`class`,`commit ${r} ${t.id} commit${z(i,F,c)}`)}if(a===x.REVERSE){let a=e.append(`path`),o=s?4:5;a.attr(`d`,`M ${n.x-o},${n.y-o}L${n.x+o},${n.y+o}M${n.x-o},${n.y+o}L${n.x+o},${n.y-o}`).attr(`class`,`commit ${r} ${t.id} commit${z(i,F,c)}`)}}},`drawCommitBullet`),ke=e((e,t,n,r,i)=>{if(t.type!==x.CHERRY_PICK&&(t.customId&&t.type===x.MERGE||t.type!==x.MERGE)&&i.showCommitLabel){let a=e.append(`g`),o=a.insert(`rect`).attr(`class`,`commit-label-bkg`),s=a.append(`text`).attr(`x`,r).attr(`y`,n.y+25).attr(`class`,`commit-label`).text(t.id),c=s.node()?.getBBox();if(c&&(o.attr(`x`,n.posWithOffset-c.width/2-P).attr(`y`,n.y+13.5).attr(`width`,c.width+2*P).attr(`height`,c.height+2*P),K===`TB`||K===`BT`?(o.attr(`x`,n.x-(c.width+4*N+5)).attr(`y`,n.y-12),s.attr(`x`,n.x-(c.width+4*N)).attr(`y`,n.y+c.height-12)):s.attr(`x`,n.posWithOffset-c.width/2),i.rotateCommitLabel))if(K===`TB`||K===`BT`)s.attr(`transform`,`rotate(-45, `+n.x+`, `+n.y+`)`),o.attr(`transform`,`rotate(-45, `+n.x+`, `+n.y+`)`);else{let e=-7.5-(c.width+10)/25*9.5,t=10+c.width/25*8.5;a.attr(`transform`,`translate(`+e+`, `+t+`) rotate(-45, `+r+`, `+n.y+`)`)}}},`drawCommitLabel`),Ae=e((e,t,n,r)=>{if(t.tags.length>0){let i=0,a=0,o=0,s=[];for(let r of t.tags.reverse()){let t=e.insert(`polygon`),c=e.append(`circle`),l=e.append(`text`).attr(`y`,n.y-16-i).attr(`class`,`tag-label`).text(r),u=l.node()?.getBBox();if(!u)throw Error(`Tag bbox not found`);a=Math.max(a,u.width),o=Math.max(o,u.height),l.attr(`x`,n.posWithOffset-u.width/2),s.push({tag:l,hole:c,rect:t,yOffset:i}),i+=20}for(let{tag:e,hole:t,rect:i,yOffset:c}of s){let s=o/2,l=n.y-19.2-c;if(i.attr(`class`,`tag-label-bkg`).attr(`points`,` + ${r-a/2-N/2},${l+P} + ${r-a/2-N/2},${l-P} + ${n.posWithOffset-a/2-N},${l-s-P} + ${n.posWithOffset+a/2+N},${l-s-P} + ${n.posWithOffset+a/2+N},${l+s+P} + ${n.posWithOffset-a/2-N},${l+s+P}`),t.attr(`cy`,l).attr(`cx`,r-a/2+N/2).attr(`r`,1.5).attr(`class`,`tag-hole`),K===`TB`||K===`BT`){let o=r+c;i.attr(`class`,`tag-label-bkg`).attr(`points`,` + ${n.x},${o+2} + ${n.x},${o-2} + ${n.x+j},${o-s-2} + ${n.x+j+a+4},${o-s-2} + ${n.x+j+a+4},${o+s+2} + ${n.x+j},${o+s+2}`).attr(`transform`,`translate(12,12) rotate(45, `+n.x+`,`+r+`)`),t.attr(`cx`,n.x+N/2).attr(`cy`,o).attr(`transform`,`translate(12,12) rotate(45, `+n.x+`,`+r+`)`),e.attr(`x`,n.x+5).attr(`y`,o+3).attr(`transform`,`translate(14,14) rotate(45, `+n.x+`,`+r+`)`)}}}},`drawCommitTags`),je=e(e=>{switch(e.customType??e.type){case x.NORMAL:return`commit-normal`;case x.REVERSE:return`commit-reverse`;case x.HIGHLIGHT:return`commit-highlight`;case x.MERGE:return`commit-merge`;case x.CHERRY_PICK:return`commit-cherry-pick`;default:return`commit-normal`}},`getCommitClassType`),Me=e((e,t,n,r)=>{let i={x:0,y:0};if(e.parents.length>0){let n=Y(e.parents);if(n){let a=r.get(n)??i;return t===`TB`?a.y+M:t===`BT`?(r.get(e.id)??i).y-M:a.x+M}}else if(t===`TB`)return H;else if(t===`BT`)return(r.get(e.id)??i).y-M;else return 0;return 0},`calculatePosition`),Ne=e((e,t,n)=>{let r=K===`BT`&&n?t:t+j,i=B.get(e.branch)?.pos,a=K===`TB`||K===`BT`?B.get(e.branch)?.pos:r;if(a===void 0||i===void 0)throw Error(`Position were undefined for commit ${e.id}`);let o=I.has(p().theme??``);return{x:a,y:K===`TB`||K===`BT`?r:i+(o?L/2+1:-2),posWithOffset:r}},`getCommitPosition`),X=e((t,n,r,i)=>{let a=t.append(`g`).attr(`class`,`commit-bullets`),o=t.append(`g`).attr(`class`,`commit-labels`),s=K===`TB`||K===`BT`?H:0,c=[...n.keys()],l=i.parallelCommits??!1,u=e((e,t)=>{let r=n.get(e)?.seq,i=n.get(t)?.seq;return r!==void 0&&i!==void 0?r-i:0},`sortKeys`),d=c.sort(u);K===`BT`&&(l&&Ce(d,n,s),d=d.reverse()),d.forEach(e=>{let t=n.get(e);if(!t)throw Error(`Commit not found for key ${e}`);l&&(s=Me(t,K,s,V));let c=Ne(t,s,l);if(r){let e=je(t),n=t.customType??t.type,r=B.get(t.branch)?.index??0;Oe(a,t,c,e,r,n),ke(o,t,c,s,i),Ae(o,t,c,s)}K===`TB`||K===`BT`?V.set(t.id,{x:c.x,y:c.posWithOffset}):V.set(t.id,{x:c.posWithOffset,y:c.y}),s=K===`BT`&&l?s+M:s+M+j,s>G&&(G=s)})},`drawCommits`),Pe=e((t,n,r,i,a)=>{let o=(K===`TB`||K===`BT`?r.xe.branch===o,`isOnBranchToGetCurve`),c=e(e=>e.seq>t.seq&&e.seqc(e)&&s(e))},`shouldRerouteArrow`),Z=e((e,t,n=0)=>{let r=e+Math.abs(e-t)/2;return n>5?r:W.every(e=>Math.abs(e-r)>=10)?(W.push(r),r):Z(e,t-Math.abs(e-t)/5,n+1)},`findLane`),Fe=e((e,t,n,r)=>{let{theme:i}=p(),a=R.has(i??``),o=V.get(t.id),s=V.get(n.id);if(o===void 0||s===void 0)throw Error(`Commit positions not found for commits ${t.id} and ${n.id}`);let c=Pe(t,n,o,s,r),l=``,u=``,d=0,f=0,m=B.get(n.branch)?.index;n.type===x.MERGE&&t.id!==n.parents[0]&&(m=B.get(t.branch)?.index);let h;if(c){l=`A 10 10, 0, 0, 0,`,u=`A 10 10, 0, 0, 1,`,d=10,f=10;let e=o.ys.x&&(l=`A 20 20, 0, 0, 0,`,u=`A 20 20, 0, 0, 1,`,d=20,f=20,h=n.type===x.MERGE&&t.id!==n.parents[0]?`M ${o.x} ${o.y} L ${o.x} ${s.y-d} ${u} ${o.x-f} ${s.y} L ${s.x} ${s.y}`:`M ${o.x} ${o.y} L ${s.x+d} ${o.y} ${l} ${s.x} ${o.y+f} L ${s.x} ${s.y}`),o.x===s.x&&(h=`M ${o.x} ${o.y} L ${s.x} ${s.y}`)):K===`BT`?(o.xs.x&&(l=`A 20 20, 0, 0, 0,`,u=`A 20 20, 0, 0, 1,`,d=20,f=20,h=n.type===x.MERGE&&t.id!==n.parents[0]?`M ${o.x} ${o.y} L ${o.x} ${s.y+d} ${l} ${o.x-f} ${s.y} L ${s.x} ${s.y}`:`M ${o.x} ${o.y} L ${s.x+d} ${o.y} ${u} ${s.x} ${o.y-f} L ${s.x} ${s.y}`),o.x===s.x&&(h=`M ${o.x} ${o.y} L ${s.x} ${s.y}`)):(o.ys.y&&(h=n.type===x.MERGE&&t.id!==n.parents[0]?`M ${o.x} ${o.y} L ${s.x-d} ${o.y} ${l} ${s.x} ${o.y-f} L ${s.x} ${s.y}`:`M ${o.x} ${o.y} L ${o.x} ${s.y+d} ${u} ${o.x+f} ${s.y} L ${s.x} ${s.y}`),o.y===s.y&&(h=`M ${o.x} ${o.y} L ${s.x} ${s.y}`));if(h===void 0)throw Error(`Line definition not found`);e.append(`path`).attr(`d`,h).attr(`class`,`arrow arrow`+z(m,F,a))},`drawArrow`),Ie=e((e,t)=>{let n=e.append(`g`).attr(`class`,`commit-arrows`);[...t.keys()].forEach(e=>{let r=t.get(e);r.parents&&r.parents.length>0&&r.parents.forEach(e=>{Fe(n,t.get(e),r,t)})})},`drawArrows`),Le=e((e,t,n,r)=>{let{look:i,theme:a,themeVariables:o}=p(),{dropShadow:s,THEME_COLOR_LIMIT:c}=o,l=I.has(a??``),u=R.has(a??``),d=e.append(`g`);t.forEach((e,t)=>{let a=z(t,l?c:F,u),o=B.get(e.name)?.pos;if(o===void 0)throw Error(`Position not found for branch ${e.name}`);let f=K===`TB`||K===`BT`?o:l?o+L/2+1:o-2,p=d.append(`line`);p.attr(`x1`,0),p.attr(`y1`,f),p.attr(`x2`,G),p.attr(`y2`,f),p.attr(`class`,`branch branch`+a),K===`TB`?(p.attr(`y1`,H),p.attr(`x1`,o),p.attr(`y2`,G),p.attr(`x2`,o)):K===`BT`&&(p.attr(`y1`,G),p.attr(`x1`,o),p.attr(`y2`,H),p.attr(`x2`,o)),W.push(f);let m=e.name,h=J(m),g=d.insert(`rect`),_=d.insert(`g`).attr(`class`,`branchLabel`).insert(`g`).attr(`class`,`label branch-label`+a);_.node().appendChild(h);let v=h.getBBox(),y=l?0:4,b=l?16:0,x=l?L:0;i===`neo`&&g.attr(`data-look`,`neo`),g.attr(`class`,`branchLabelBkg label`+a).attr(`style`,i===`neo`?`filter:${l?`url(#${r}-drop-shadow)`:s}`:``).attr(`rx`,y).attr(`ry`,y).attr(`x`,-v.width-4-(n.rotateCommitLabel===!0?30:0)).attr(`y`,-v.height/2+10).attr(`width`,v.width+18+b).attr(`height`,v.height+4+x),_.attr(`transform`,`translate(`+(-v.width-14-(n.rotateCommitLabel===!0?30:0)+b/2)+`, `+(f-v.height/2-2)+`)`),K===`TB`?(g.attr(`x`,o-v.width/2-10).attr(`y`,0),_.attr(`transform`,`translate(`+(o-v.width/2-5)+`, 0)`),l&&(g.attr(`transform`,`translate(${-b/2-3}, ${-x-10})`),_.attr(`transform`,`translate(`+(o-v.width/2-5)+`, `+(-x*2+7)+`)`))):K===`BT`?(g.attr(`x`,o-v.width/2-10).attr(`y`,G),_.attr(`transform`,`translate(`+(o-v.width/2-5)+`, `+G+`)`),l&&(g.attr(`transform`,`translate(${-b/2-3}, ${x+10})`),_.attr(`transform`,`translate(`+(o-v.width/2-5)+`, `+(G+x*2+4)+`)`))):g.attr(`transform`,`translate(-19, `+(f-12-x/2)+`)`)})},`drawBranches`),Re=e(function(e,t,n,r,i){return B.set(e,{pos:t,index:n}),t+=50+(i?40:0)+(K===`TB`||K===`BT`?r.width/2:0),t},`setBranchPosition`),ze={draw:e(function(e,r,i,a){q(),t.debug(`in gitgraph renderer`,e+` +`,`id:`,r,i);let s=a.db;if(!s.getConfig){t.error(`getConfig method is not available on db`);return}let c=s.getConfig(),l=c.rotateCommitLabel??!1;U=s.getCommits();let u=s.getBranchesAsObjArray();K=s.getDirection();let d=n(`[id="${r}"]`),{look:f,theme:m,themeVariables:g}=p(),{useGradient:_,gradientStart:v,gradientStop:y,filterColor:b}=g;if(_){let e=d.append(`defs`).append(`linearGradient`).attr(`id`,r+`-gradient`).attr(`gradientUnits`,`objectBoundingBox`).attr(`x1`,`0%`).attr(`y1`,`0%`).attr(`x2`,`100%`).attr(`y2`,`0%`);e.append(`stop`).attr(`offset`,`0%`).attr(`stop-color`,v).attr(`stop-opacity`,1),e.append(`stop`).attr(`offset`,`100%`).attr(`stop-color`,y).attr(`stop-opacity`,1)}f===`neo`&&I.has(m??``)&&d.append(`defs`).append(`filter`).attr(`id`,r+`-drop-shadow`).attr(`height`,`130%`).attr(`width`,`130%`).append(`feDropShadow`).attr(`dx`,`4`).attr(`dy`,`4`).attr(`stdDeviation`,0).attr(`flood-opacity`,`0.06`).attr(`flood-color`,b);let x=0;u.forEach((e,t)=>{let n=J(e.name),r=d.append(`g`),i=r.insert(`g`).attr(`class`,`branchLabel`),a=i.insert(`g`).attr(`class`,`label branch-label`);a.node()?.appendChild(n);let o=n.getBBox();x=Re(e.name,x,t,o,l),a.remove(),i.remove(),r.remove()}),X(d,U,!1,c),c.showBranches&&Le(d,u,c,r),Ie(d,U),X(d,U,!0,c),h.insertTitle(d,`gitTitleText`,c.titleTopMargin??0,s.getDiagramTitle()),o(void 0,d,c.diagramPadding,c.useMaxWidth)},`draw`)},Q=8,$=new Set([`redux`,`redux-dark`,`redux-color`,`redux-dark-color`]),Be=new Set([`redux-color`,`redux-dark-color`]),Ve=new Set([`neo`,`neo-dark`]),He=new Set([`dark`,`redux-dark`,`redux-dark-color`,`neo-dark`]),Ue=new Set([`redux`,`redux-dark`,`redux-color`,`redux-dark-color`,`neo`,`neo-dark`]),We=e(e=>{let{svgId:t}=e,n=``;if(e.useGradient&&t)for(let r=0;r{let{theme:t,themeVariables:n}=c(),{borderColorArray:r}=n,i=$.has(t);if(Ve.has(t)){let t=``;for(let n=0;n`${Array.from({length:e.THEME_COLOR_LIMIT},(e,t)=>t).map(t=>{let n=t%Q;return` + .branch-label${t} { fill: ${e[`gitBranchLabel`+n]}; } + .commit${t} { stroke: ${e[`git`+n]}; fill: ${e[`git`+n]}; } + .commit-highlight${t} { stroke: ${e[`gitInv`+n]}; fill: ${e[`gitInv`+n]}; } + .label${t} { fill: ${e[`git`+n]}; } + .arrow${t} { stroke: ${e[`git`+n]}; } + `}).join(` +`)}`,`normalTheme`),qe={parser:be,db:A,renderer:ze,styles:e(e=>{let{theme:t}=c(),n=Ue.has(t);return` + .commit-id, + .commit-msg, + .branch-label { + fill: lightgrey; + color: lightgrey; + font-family: 'trebuchet ms', verdana, arial, sans-serif; + font-family: var(--mermaid-font-family); + } + + ${n?Ge(e):Ke(e)} + + .branch { + stroke-width: ${e.strokeWidth}; + stroke: ${e.commitLineColor??e.lineColor}; + stroke-dasharray: ${n?`4 2`:`2`}; + } + .commit-label { font-size: ${e.commitLabelFontSize}; fill: ${n?e.nodeBorder:e.commitLabelColor}; ${n?`font-weight:${e.noteFontWeight};`:``}} + .commit-label-bkg { font-size: ${e.commitLabelFontSize}; fill: ${n?`transparent`:e.commitLabelBackground}; opacity: ${n?``:.5}; } + .tag-label { font-size: ${e.tagLabelFontSize}; fill: ${e.tagLabelColor};} + .tag-label-bkg { fill: ${n?e.mainBkg:e.tagLabelBackground}; stroke: ${n?e.nodeBorder:e.tagLabelBorder}; ${n?`filter:${e.dropShadow}`:``} } + .tag-hole { fill: ${e.textColor}; } + + .commit-merge { + stroke: ${n?e.mainBkg:e.primaryColor}; + fill: ${n?e.mainBkg:e.primaryColor}; + } + .commit-reverse { + stroke: ${n?e.mainBkg:e.primaryColor}; + fill: ${n?e.mainBkg:e.primaryColor}; + stroke-width: ${n?e.strokeWidth:3}; + } + .commit-highlight-outer { + } + .commit-highlight-inner { + stroke: ${n?e.mainBkg:e.primaryColor}; + fill: ${n?e.mainBkg:e.primaryColor}; + } + + .arrow { + /* Intentional: neo themes keep the bold 8px arrow (like classic themes); only redux-geometry themes use the thinner options.strokeWidth. */ + stroke-width: ${$.has(t)?e.strokeWidth:8}; + stroke-linecap: round; + fill: none + } + .gitTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${e.textColor}; + } +`},`getStyles`)};export{qe as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/graphlib-DS17s2tU.js b/dist-desktop/assets/graphlib-DS17s2tU.js new file mode 100644 index 0000000..8beeacf --- /dev/null +++ b/dist-desktop/assets/graphlib-DS17s2tU.js @@ -0,0 +1 @@ +var e=typeof global==`object`&&global&&global.Object===Object&&global,t=typeof self==`object`&&self&&self.Object===Object&&self,n=e||t||Function(`return this`)(),r=n.Symbol,i=Object.prototype,a=i.hasOwnProperty,o=i.toString,s=r?r.toStringTag:void 0;function c(e){var t=a.call(e,s),n=e[s];try{e[s]=void 0;var r=!0}catch{}var i=o.call(e);return r&&(t?e[s]=n:delete e[s]),i}var l=Object.prototype.toString;function u(e){return l.call(e)}var d=`[object Null]`,f=`[object Undefined]`,p=r?r.toStringTag:void 0;function m(e){return e==null?e===void 0?f:d:p&&p in Object(e)?c(e):u(e)}function h(e){return typeof e==`object`&&!!e}var g=`[object Symbol]`;function _(e){return typeof e==`symbol`||h(e)&&m(e)==g}function v(e,t){for(var n=-1,r=e==null?0:e.length,i=Array(r);++n0){if(++t>=we)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function T(e){return function(){return e}}var Oe=function(){try{var e=w(Object,`defineProperty`);return e({},``,{}),e}catch{}}(),ke=De(Oe?function(e,t){return Oe(e,`toString`,{configurable:!0,enumerable:!1,value:T(t),writable:!0})}:x);function Ae(e,t){for(var n=-1,r=e==null?0:e.length;++n-1}var Ie=9007199254740991,Le=/^(?:0|[1-9]\d*)$/;function Re(e,t){var n=typeof e;return t??=Ie,!!t&&(n==`number`||n!=`symbol`&&Le.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=Ue}function E(e){return e!=null&&We(e.length)&&!S(e)}var Ge=Object.prototype;function Ke(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||Ge)}function qe(e,t){for(var n=-1,r=Array(e);++n-1}function nn(e,t){var n=this.__data__,r=F(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function I(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t0&&n(s)?t>1?Tn(s,t-1,n,r,i):Sn(i,s):r||(i[i.length]=s)}return i}function En(e,t,n,r){var i=-1,a=e==null?0:e.length;for(r&&a&&(n=e[++i]);++is))return!1;var l=a.get(e),u=a.get(t);if(l&&u)return l==t&&u==e;var d=-1,f=!0,p=n&or?new G:void 0;for(a.set(e,t),a.set(t,e);++d=mi){var l=t?null:pi(e);if(l)return lr(l);o=!1,i=ir,c=new G}else c=t?[]:s;outer:for(;++r1?r.setNode(e,t):r.setNode(e)}),this}setNode(e,t){return Object.prototype.hasOwnProperty.call(this._nodes,e)?(arguments.length>1&&(this._nodes[e]=t),this):(this._nodes[e]=arguments.length>1?t:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]=Q,this._children[e]={},this._children[Q][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return Object.prototype.hasOwnProperty.call(this._nodes,e)}removeNode(e){if(Object.prototype.hasOwnProperty.call(this._nodes,e)){var t=e=>this.removeEdge(this._edgeObjs[e]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],J(this.children(e),e=>{this.setParent(e)}),delete this._children[e]),J(M(this._in[e]),t),delete this._in[e],delete this._preds[e],J(M(this._out[e]),t),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,t){if(!this._isCompound)throw Error(`Cannot set parent in a non-compound graph`);if(Z(t))t=Q;else{t+=``;for(var n=t;!Z(n);n=this.parent(n))if(n===e)throw Error(`Setting `+t+` as parent of `+e+` would create a cycle`);this.setNode(t)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=t,this._children[t][e]=!0,this}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}parent(e){if(this._isCompound){var t=this._parent[e];if(t!==Q)return t}}children(e){if(Z(e)&&(e=Q),this._isCompound){var t=this._children[e];if(t)return M(t)}else if(e===Q)return this.nodes();else if(this.hasNode(e))return[]}predecessors(e){var t=this._preds[e];if(t)return M(t)}successors(e){var t=this._sucs[e];if(t)return M(t)}neighbors(e){var t=this.predecessors(e);if(t)return gi(t,this.successors(e))}isLeaf(e){return(this.isDirected()?this.successors(e):this.neighbors(e)).length===0}filterNodes(e){var t=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});t.setGraph(this.graph());var n=this;J(this._nodes,function(n,r){e(r)&&t.setNode(r,n)}),J(this._edgeObjs,function(e){t.hasNode(e.v)&&t.hasNode(e.w)&&t.setEdge(e,n.edge(e))});var r={};function i(e){var a=n.parent(e);return a===void 0||t.hasNode(a)?(r[e]=a,a):a in r?r[a]:i(a)}return this._isCompound&&J(t.nodes(),function(e){t.setParent(e,i(e))}),t}setDefaultEdgeLabel(e){return S(e)||(e=T(e)),this._defaultEdgeLabelFn=e,this}edgeCount(){return this._edgeCount}edges(){return X(this._edgeObjs)}setPath(e,t){var n=this,r=arguments;return fi(e,function(e,i){return r.length>1?n.setEdge(e,i,t):n.setEdge(e,i),i}),this}setEdge(){var e,t,n,r,i=!1,a=arguments[0];typeof a==`object`&&a&&`v`in a?(e=a.v,t=a.w,n=a.name,arguments.length===2&&(r=arguments[1],i=!0)):(e=a,t=arguments[1],n=arguments[3],arguments.length>2&&(r=arguments[2],i=!0)),e=``+e,t=``+t,Z(n)||(n=``+n);var o=$(this._isDirected,e,t,n);if(Object.prototype.hasOwnProperty.call(this._edgeLabels,o))return i&&(this._edgeLabels[o]=r),this;if(!Z(n)&&!this._isMultigraph)throw Error(`Cannot set a named edge when isMultigraph = false`);this.setNode(e),this.setNode(t),this._edgeLabels[o]=i?r:this._defaultEdgeLabelFn(e,t,n);var s=Si(this._isDirected,e,t,n);return e=s.v,t=s.w,Object.freeze(s),this._edgeObjs[o]=s,bi(this._preds[t],e),bi(this._sucs[e],t),this._in[t][o]=s,this._out[e][o]=s,this._edgeCount++,this}edge(e,t,n){var r=arguments.length===1?Ci(this._isDirected,arguments[0]):$(this._isDirected,e,t,n);return this._edgeLabels[r]}hasEdge(e,t,n){var r=arguments.length===1?Ci(this._isDirected,arguments[0]):$(this._isDirected,e,t,n);return Object.prototype.hasOwnProperty.call(this._edgeLabels,r)}removeEdge(e,t,n){var r=arguments.length===1?Ci(this._isDirected,arguments[0]):$(this._isDirected,e,t,n),i=this._edgeObjs[r];return i&&(e=i.v,t=i.w,delete this._edgeLabels[r],delete this._edgeObjs[r],xi(this._preds[t],e),xi(this._sucs[e],t),delete this._in[t][r],delete this._out[e][r],this._edgeCount--),this}inEdges(e,t){var n=this._in[e];if(n){var r=X(n);return t?Y(r,function(e){return e.v===t}):r}}outEdges(e,t){var n=this._out[e];if(n){var r=X(n);return t?Y(r,function(e){return e.w===t}):r}}nodeEdges(e,t){var n=this.inEdges(e,t);if(n)return n.concat(this.outEdges(e,t))}};yi.prototype._nodeCount=0,yi.prototype._edgeCount=0;function bi(e,t){e[t]?e[t]++:e[t]=1}function xi(e,t){--e[t]||delete e[t]}function $(e,t,n,r){var i=``+t,a=``+n;if(!e&&i>a){var o=i;i=a,a=o}return i+vi+a+vi+(Z(r)?_i:r)}function Si(e,t,n,r){var i=``+t,a=``+n;if(!e&&i>a){var o=i;i=a,a=o}var s={v:i,w:a};return r&&(s.name=r),s}function Ci(e,t){return $(e,t.v,t.w,t.name)}export{v as $,Rt as A,He as B,Tn as C,vn as D,B as E,Ot as F,Ae as G,ze as H,O as I,T as J,ke as K,D as L,Pt as M,j as N,_n as O,jt as P,y as Q,Ke as R,V as S,bn as T,Re as U,Ve as V,je as W,x as X,S as Y,b as Z,W as _,Y as a,Ln as b,ni as c,$r as d,_ as et,Zr as f,$n as g,Ur as h,X as i,n as it,Ft as j,M as k,q as l,Wr as m,fi as n,m as nt,J as o,Jr as p,Oe as q,Z as r,r as rt,ii as s,yi as t,h as tt,ei as u,zn as v,Sn as w,Pn as x,Rn as y,E as z}; \ No newline at end of file diff --git a/dist-desktop/assets/index-CXgd9jpl.js b/dist-desktop/assets/index-CXgd9jpl.js new file mode 100644 index 0000000..6fa379b --- /dev/null +++ b/dist-desktop/assets/index-CXgd9jpl.js @@ -0,0 +1,22 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/routes-BDn33g5C.js","assets/rolldown-runtime-aKtaBQYM.js","assets/react-BLJmJXjR.js","assets/utils-BTuSbA5p.js","assets/client-CwgDvMJw.js","assets/input-mze7gZ5r.js","assets/login-xkhUej_P.js"])))=>i.map(i=>d[i]); +import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{t as n}from"./react-BLJmJXjR.js";import{A as r,B as i,C as a,D as o,E as s,F as c,G as l,H as u,I as d,L as f,M as p,N as m,O as h,P as g,R as _,S as v,T as y,U as b,V as x,W as S,_ as C,a as w,b as ee,c as te,d as ne,f as re,g as ie,h as ae,i as oe,j as se,k as ce,l as le,m as E,n as D,o as ue,p as de,s as fe,u as pe,v as me,w as O,x as he,y as ge,z as _e}from"./utils-BTuSbA5p.js";var ve=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,re());else{var t=n(l);t!==null&&oe(x,t.startTime-e)}}var S=!1,C=-1,w=5,ee=-1;function te(){return g?!0:!(e.unstable_now()-eet&&te());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&oe(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?re():S=!1}}}var re;if(typeof y==`function`)re=function(){y(ne)};else if(typeof MessageChannel<`u`){var ie=new MessageChannel,ae=ie.port2;ie.port1.onmessage=ne,re=function(){ae.postMessage(null)}}else re=function(){_(ne,0)};function oe(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,oe(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,re()))),r},e.unstable_shouldYield=te,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),ye=t(((e,t)=>{t.exports=ve()})),be=t((e=>{var t=ye(),r=n(),i=l();function a(e){var t=`https://react.dev/errors/`+e;if(1fe||(e.current=de[fe],de[fe]=null,fe--)}function O(e,t){fe++,de[fe]=e.current,e.current=t}var he=pe(null),ge=pe(null),_e=pe(null),ve=pe(null);function be(e,t){switch(O(_e,t),O(ge,e),O(he,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Hd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Hd(t),e=Ud(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}me(he),O(he,e)}function xe(){me(he),me(ge),me(_e)}function Se(e){e.memoizedState!==null&&O(ve,e);var t=he.current,n=Ud(t,e.type);t!==n&&(O(ge,e),O(he,n))}function Ce(e){ge.current===e&&(me(he),me(ge)),ve.current===e&&(me(ve),$f._currentValue=ue)}var we,Te;function Ee(e){if(we===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);we=t&&t[1]||``,Te=-1)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{De=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ee(n):``}function ke(e,t){switch(e.tag){case 26:case 27:case 5:return Ee(e.type);case 16:return Ee(`Lazy`);case 13:return e.child!==t&&t!==null?Ee(`Suspense Fallback`):Ee(`Suspense`);case 19:return Ee(`SuspenseList`);case 0:case 15:return Oe(e.type,!1);case 11:return Oe(e.type.render,!1);case 1:return Oe(e.type,!0);case 31:return Ee(`Activity`);default:return``}}function Ae(e){try{var t=``,n=null;do t+=ke(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var je=Object.prototype.hasOwnProperty,Me=t.unstable_scheduleCallback,Ne=t.unstable_cancelCallback,Pe=t.unstable_shouldYield,Fe=t.unstable_requestPaint,Ie=t.unstable_now,Le=t.unstable_getCurrentPriorityLevel,Re=t.unstable_ImmediatePriority,ze=t.unstable_UserBlockingPriority,Be=t.unstable_NormalPriority,Ve=t.unstable_LowPriority,He=t.unstable_IdlePriority,Ue=t.log,We=t.unstable_setDisableYieldValue,Ge=null,Ke=null;function qe(e){if(typeof Ue==`function`&&We(e),Ke&&typeof Ke.setStrictMode==`function`)try{Ke.setStrictMode(Ge,e)}catch{}}var Je=Math.clz32?Math.clz32:Ze,Ye=Math.log,Xe=Math.LN2;function Ze(e){return e>>>=0,e===0?32:31-(Ye(e)/Xe|0)|0}var Qe=256,$e=262144,et=4194304;function tt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function nt(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=tt(n))):i=tt(o):i=tt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=tt(n))):i=tt(o)):i=tt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function rt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function it(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function at(){var e=et;return et<<=1,!(et&62914560)&&(et=4194304),e}function ot(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function st(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function ct(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),xn=!1;if(bn)try{var Sn={};Object.defineProperty(Sn,"passive",{get:function(){xn=!0}}),window.addEventListener(`test`,Sn,Sn),window.removeEventListener(`test`,Sn,Sn)}catch{xn=!1}var Cn=null,wn=null,Tn=null;function k(){if(Tn)return Tn;var e,t=wn,n=t.length,r,i=`value`in Cn?Cn.value:Cn.textContent,a=i.length;for(e=0;e=nr),ar=` `,or=!1;function sr(e,t){switch(e){case`keyup`:return er.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function cr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var lr=!1;function ur(e,t){switch(e){case`compositionend`:return cr(t);case`keypress`:return t.which===32?(or=!0,ar):null;case`textInput`:return e=t.data,e===ar&&or?null:e;default:return null}}function dr(e,t){if(lr)return e===`compositionend`||!tr&&sr(e,t)?(e=k(),Tn=wn=Cn=null,lr=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Nr(n)}}function Fr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Fr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ir(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=qt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=qt(e.document)}return t}function Lr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Rr=bn&&`documentMode`in document&&11>=document.documentMode,zr=null,Br=null,Vr=null,Hr=!1;function Ur(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Hr||zr==null||zr!==qt(r)||(r=zr,`selectionStart`in r&&Lr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Vr&&Mr(Vr,r)||(Vr=r,r=Dd(Br,`onSelect`),0>=o,i-=o,Fi=1<<32-Je(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),N&&Li(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),N&&Li(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return N&&Li(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),N&&Li(i,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===v&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case g:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===v){if(r.tag===7){n(e,r.sibling),c=i(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===ne&&Pa(l)===r.type){n(e,r.sibling),c=i(r,o.props),Ba(c,o),c.return=e,e=c;break a}n(e,r);break}else t(e,r);r=r.sibling}o.type===v?(c=Si(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=xi(o.type,o.key,o.props,null,e.mode,c),Ba(c,o),c.return=e,e=c)}return s(e);case _:a:{for(l=o.key;r!==null;){if(r.key===l)if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=i(r,o.children||[]),c.return=e,e=c;break a}else{n(e,r);break}else t(e,r);r=r.sibling}c=Ti(o,e.mode,c),c.return=e,e=c}return s(e);case ne:return o=Pa(o),b(e,r,o,c)}if(le(o))return h(e,r,o,c);if(oe(o)){if(l=oe(o),typeof l!=`function`)throw Error(a(150));return o=l.call(o),y(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,za(o),c);if(o.$$typeof===S)return b(e,r,ca(e,o),c);Va(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=i(r,o),c.return=e,e=c):(n(e,r),c=Ci(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Ra=0;var i=b(e,t,n,r);return La=null,i}catch(t){if(t===Oa||t===Aa)throw t;var a=_i(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Ua=Ha(!0),Wa=Ha(!1),Ga=!1;function Ka(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function qa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ja(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ya(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,K&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=mi(e),pi(e,null,n),t}return ui(e,r,t,n),mi(e)}function Xa(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ut(e,n)}}function Za(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Qa=!1;function $a(){if(Qa){var e=ya;if(e!==null)throw e}}function eo(e,t,n,r){Qa=!1;var i=e.updateQueue;Ga=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(Y&f)===f:(r&f)===f){f!==0&&f===va&&(Qa=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,f);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,f=typeof h==`function`?h.call(_,d,f):h,f==null)break a;d=m({},d,f);break a;case 2:Ga=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Kl|=o,e.lanes=o,e.memoizedState=d}}function to(e,t){if(typeof e!=`function`)throw Error(a(191,e));e.call(t)}function no(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=E.T,s={};E.T=s,Fs(e,!1,t,n);try{var c=i(),l=E.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Ps(e,t,Sa(c,r),mu(e)):Ps(e,t,r,mu(e))}catch(n){Ps(e,t,{then:function(){},status:`rejected`,reason:n},mu())}finally{D.p=a,o!==null&&s.types!==null&&(o.types=s.types),E.T=o}}function ws(){}function Ts(e,t,n,r){if(e.tag!==5)throw Error(a(476));var i=Es(e).queue;Cs(e,i,t,ue,n===null?ws:function(){return Ds(e),n(r)})}function Es(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ue,baseState:ue,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Lo,lastRenderedState:ue},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Lo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Ds(e){var t=Es(e);t.next===null&&(t=e.alternate.memoizedState),Ps(e,t.next.queue,{},mu())}function Os(){return sa($f)}function ks(){return Mo().memoizedState}function As(){return Mo().memoizedState}function js(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=mu();e=Ja(n);var r=Ya(t,e,n);r!==null&&(gu(r,t,n),Xa(r,t,n)),t={cache:ma()},e.payload=t;return}t=t.return}}function Ms(e,t,n){var r=mu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Is(e)?Ls(t,n):(n=di(e,t,n,r),n!==null&&(gu(n,e,r),Rs(n,t,r)))}function Ns(e,t,n){Ps(e,t,n,mu())}function Ps(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Is(e))Ls(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,jr(s,o))return ui(e,t,i,0),q===null&&li(),!1}catch{}if(n=di(e,t,i,r),n!==null)return gu(n,e,r),Rs(n,t,r),!0}return!1}function Fs(e,t,n,r){if(r={lane:2,revertLane:fd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Is(e)){if(t)throw Error(a(479))}else t=di(e,n,r,2),t!==null&&gu(t,e,2)}function Is(e){var t=e.alternate;return e===L||t!==null&&t===L}function Ls(e,t){yo=vo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Rs(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ut(e,n)}}var zs={readContext:sa,use:Fo,useCallback:B,useContext:B,useEffect:B,useImperativeHandle:B,useLayoutEffect:B,useInsertionEffect:B,useMemo:B,useReducer:B,useRef:B,useState:B,useDebugValue:B,useDeferredValue:B,useTransition:B,useSyncExternalStore:B,useId:B,useHostTransitionStatus:B,useFormState:B,useActionState:B,useOptimistic:B,useMemoCache:B,useCacheRefresh:B};zs.useEffectEvent=B;var Bs={readContext:sa,use:Fo,useCallback:function(e,t){return jo().memoizedState=[e,t===void 0?null:t],e},useContext:sa,useEffect:us,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),cs(4194308,4,gs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return cs(4194308,4,e,t)},useInsertionEffect:function(e,t){cs(4,2,e,t)},useMemo:function(e,t){var n=jo();t=t===void 0?null:t;var r=e();if(bo){qe(!0);try{e()}finally{qe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=jo();if(n!==void 0){var i=n(t);if(bo){qe(!0);try{n(t)}finally{qe(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Ms.bind(null,L,e),[r.memoizedState,e]},useRef:function(e){var t=jo();return e={current:e},t.memoizedState=e},useState:function(e){e=Ko(e);var t=e.queue,n=Ns.bind(null,L,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:vs,useDeferredValue:function(e,t){return xs(jo(),e,t)},useTransition:function(){var e=Ko(!1);return e=Cs.bind(null,L,e.queue,!0,!1),jo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=L,i=jo();if(N){if(n===void 0)throw Error(a(407));n=n()}else{if(n=t(),q===null)throw Error(a(349));Y&127||Vo(r,t,n)}i.memoizedState=n;var o={value:n,getSnapshot:t};return i.queue=o,us(Uo.bind(null,r,o,e),[e]),r.flags|=2048,os(9,{destroy:void 0},Ho.bind(null,r,o,n,t),null),n},useId:function(){var e=jo(),t=q.identifierPrefix;if(N){var n=Ii,r=Fi;n=(r&~(1<<32-Je(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=xo++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(i,{is:r.is}):s.createElement(i)}}o[_t]=t,o[vt]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Fd(o,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Pc(t)}}return W(t),Fc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Pc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(a(166));if(e=_e.current,Ji(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=j,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[_t]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Nd(e.nodeValue,n)),e||Gi(t,!0)}else e=Vd(e).createTextNode(r),e[_t]=t,t.stateNode=e}return W(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Ji(t),n!==null){if(e===null){if(!r)throw Error(a(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(a(557));e[_t]=t}else Yi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;W(t),e=!1}else n=Xi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(ho(t),t):(ho(t),null);if(t.flags&128)throw Error(a(558))}return W(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=Ji(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(a(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(a(317));i[_t]=t}else Yi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;W(t),i=!1}else i=Xi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(ho(t),t):(ho(t),null)}return ho(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Lc(t,t.updateQueue),W(t),null);case 4:return xe(),e===null&&Cd(t.stateNode.containerInfo),W(t),null;case 10:return P(t.type),W(t),null;case 19:if(me(I),r=t.memoizedState,r===null)return W(t),null;if(i=(t.flags&128)!=0,o=r.rendering,o===null)if(i)Rc(r,!1);else{if(Gl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=go(e),o!==null){for(t.flags|=128,Rc(r,!1),e=o.updateQueue,t.updateQueue=e,Lc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)bi(n,e),n=n.sibling;return O(I,I.current&1|2),N&&Li(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ie()>nu&&(t.flags|=128,i=!0,Rc(r,!1),t.lanes=4194304)}else{if(!i)if(e=go(o),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,Lc(t,e),Rc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!N)return W(t),null}else 2*Ie()-r.renderingStartTime>nu&&n!==536870912&&(t.flags|=128,i=!0,Rc(r,!1),t.lanes=4194304);r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(W(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ie(),e.sibling=null,n=I.current,O(I,i?n&1|2:n&1),N&&Li(t,r.treeForkCount),e);case 22:case 23:return ho(t),so(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(W(t),t.subtreeFlags&6&&(t.flags|=8192)):W(t),n=t.updateQueue,n!==null&&Lc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&me(wa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),P(pa),W(t),null;case 25:return null;case 30:return null}throw Error(a(156,t.tag))}function Bc(e,t){switch(Bi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return P(pa),xe(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Ce(t),null;case 31:if(t.memoizedState!==null){if(ho(t),t.alternate===null)throw Error(a(340));Yi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(ho(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(a(340));Yi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return me(I),null;case 4:return xe(),null;case 10:return P(t.type),null;case 22:case 23:return ho(t),so(),e!==null&&me(wa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return P(pa),null;case 25:return null;default:return null}}function Vc(e,t){switch(Bi(t),t.tag){case 3:P(pa),xe();break;case 26:case 27:case 5:Ce(t);break;case 4:xe();break;case 31:t.memoizedState!==null&&ho(t);break;case 13:ho(t);break;case 19:me(I);break;case 10:P(t.type);break;case 22:case 23:ho(t),so(),e!==null&&me(wa);break;case 24:P(pa)}}function Hc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Z(t,t.return,e)}}function Uc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Z(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Z(t,t.return,e)}}function Wc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{no(t,n)}catch(t){Z(e,e.return,t)}}}function Gc(e,t,n){n.props=qs(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Z(e,t,n)}}function Kc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Z(e,t,n)}}function qc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){Z(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Z(e,t,n)}else n.current=null}function Jc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Z(e,e.return,t)}}function Yc(e,t,n){try{var r=e.stateNode;Id(r,e.type,n,t),r[vt]=t}catch(t){Z(e,e.return,t)}}function Xc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Qd(e.type)||e.tag===4}function Zc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Xc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Qd(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Qc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=dn));else if(r!==4&&(r===27&&Qd(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Qc(e,t,n),e=e.sibling;e!==null;)Qc(e,t,n),e=e.sibling}function $c(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&Qd(e.type)&&(n=e.stateNode),e=e.child,e!==null))for($c(e,t,n),e=e.sibling;e!==null;)$c(e,t,n),e=e.sibling}function el(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Fd(t,r,n),t[_t]=e,t[vt]=n}catch(t){Z(e,e.return,t)}}var tl=!1,nl=!1,rl=!1,il=typeof WeakSet==`function`?WeakSet:Set,al=null;function ol(e,t){if(e=e.containerInfo,zd=cp,e=Ir(e),Lr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||i!==0&&f.nodeType!==3||(c=s+i),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===i&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Bd={focusedElem:e,selectionRange:n},cp=!1,al=t;al!==null;)if(t=al,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,al=e;else for(;al!==null;){switch(t=al,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Fd(o,r,n),o[_t]=e,At(o),r=o;break a;case`link`:var s=Hf(`link`,`href`,i).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Pr(s,h),v=Pr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,E.T=null,n=uu,uu=null;var o=ou,s=cu;if(au=0,su=ou=null,cu=0,K&6)throw Error(a(331));var c=K;if(K|=4,Fl(o.current),Dl(o,o.current,s,n),K=c,ad(0,!1),Ke&&typeof Ke.onPostCommitFiberRoot==`function`)try{Ke.onPostCommitFiberRoot(Ge,o)}catch{}return!0}finally{D.p=i,E.T=r,Hu(e,t)}}function Gu(e,t,n){t=Di(n,t),t=$s(e.stateNode,t,2),e=Ya(e,t,2),e!==null&&(st(e,2),id(e))}function Z(e,t,n){if(e.tag===3)Gu(e,e,n);else for(;t!==null;){if(t.tag===3){Gu(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(iu===null||!iu.has(r))){e=Di(n,e),n=ec(2),r=Ya(t,n,2),r!==null&&(tc(n,r,t,e),st(r,2),id(r));break}}t=t.return}}function Ku(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new zl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Ul=!0,i.add(n),e=qu.bind(null,e,t,n),t.then(e,e))}function qu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,q===e&&(Y&n)===n&&(Gl===4||Gl===3&&(Y&62914560)===Y&&300>Ie()-eu?!(K&2)&&Cu(e,0):Jl|=n,Xl===Y&&(Xl=0)),id(e)}function Ju(e,t){t===0&&(t=at()),e=fi(e,t),e!==null&&(st(e,t),id(e))}function Yu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ju(e,n)}function Xu(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(a(314))}r!==null&&r.delete(t),Ju(e,n)}function Zu(e,t){return Me(e,t)}var Qu=null,$u=null,ed=!1,td=!1,nd=!1,rd=0;function id(e){e!==$u&&e.next===null&&($u===null?Qu=$u=e:$u=$u.next=e),td=!0,ed||(ed=!0,dd())}function ad(e,t){if(!nd&&td){nd=!0;do for(var n=!1,r=Qu;r!==null;){if(!t)if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Je(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,ud(r,a))}else a=Y,a=nt(r,r===q?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||rt(r,a)||(n=!0,ud(r,a));r=r.next}while(n);nd=!1}}function od(){sd()}function sd(){td=ed=!1;var e=0;rd!==0&&Kd()&&(e=rd);for(var t=Ie(),n=null,r=Qu;r!==null;){var i=r.next,a=cd(r,t);a===0?(r.next=null,n===null?Qu=i:n.next=i,i===null&&($u=n)):(n=r,(e!==0||a&3)&&(td=!0)),r=i}au!==0&&au!==5||ad(e,!1),rd!==0&&(rd=0)}function cd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Ld(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Sf(e,t,n){var r=xf;if(r&&typeof t==`string`&&t){var i=Yt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),gf.has(i)||(gf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Fd(t,`link`,e),At(t),r.head.appendChild(t)))}}function Cf(e){vf.D(e),Sf(`dns-prefetch`,e,null)}function wf(e,t){vf.C(e,t),Sf(`preconnect`,e,t)}function Tf(e,t,n){vf.L(e,t,n);var r=xf;if(r&&e&&t){var i=`link[rel="preload"][as="`+Yt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Yt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Yt(n.imageSizes)+`"]`)):i+=`[href="`+Yt(e)+`"]`;var a=i;switch(t){case`style`:a=jf(e);break;case`script`:a=Ff(e)}hf.has(a)||(e=m({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),hf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Mf(a))||t===`script`&&r.querySelector(If(a))||(t=r.createElement(`link`),Fd(t,`link`,e),At(t),r.head.appendChild(t)))}}function Ef(e,t){vf.m(e,t);var n=xf;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Yt(r)+`"][href="`+Yt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Ff(e)}if(!hf.has(a)&&(e=m({rel:`modulepreload`,href:e},t),hf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(If(a)))return}r=n.createElement(`link`),Fd(r,`link`,e),At(r),n.head.appendChild(r)}}}function Df(e,t,n){vf.S(e,t,n);var r=xf;if(r&&e){var i=kt(r).hoistableStyles,a=jf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Mf(a)))s.loading=5;else{e=m({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=hf.get(a))&&zf(e,n);var c=o=r.createElement(`link`);At(c),Fd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Rf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Of(e,t){vf.X(e,t);var n=xf;if(n&&e){var r=kt(n).hoistableScripts,i=Ff(e),a=r.get(i);a||(a=n.querySelector(If(i)),a||(e=m({src:e,async:!0},t),(t=hf.get(i))&&Bf(e,t),a=n.createElement(`script`),At(a),Fd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function kf(e,t){vf.M(e,t);var n=xf;if(n&&e){var r=kt(n).hoistableScripts,i=Ff(e),a=r.get(i);a||(a=n.querySelector(If(i)),a||(e=m({src:e,async:!0,type:`module`},t),(t=hf.get(i))&&Bf(e,t),a=n.createElement(`script`),At(a),Fd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Af(e,t,n,r){var i=(i=_e.current)?_f(i):null;if(!i)throw Error(a(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=jf(n.href),n=kt(i).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=jf(n.href);var o=kt(i).hoistableStyles,s=o.get(e);if(s||(i=i.ownerDocument||i,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=i.querySelector(Mf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),hf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},hf.set(e,n),o||Pf(i,e,n,s.state))),t&&r===null)throw Error(a(528,``));return s}if(t&&r!==null)throw Error(a(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Ff(n),n=kt(i).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(a(444,e))}}function jf(e){return`href="`+Yt(e)+`"`}function Mf(e){return`link[rel="stylesheet"][`+e+`]`}function Nf(e){return m({},e,{"data-precedence":e.precedence,precedence:null})}function Pf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Fd(t,`link`,n),At(t),e.head.appendChild(t))}function Ff(e){return`[src="`+Yt(e)+`"]`}function If(e){return`script[async]`+e}function Lf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Yt(n.href)+`"]`);if(r)return t.instance=r,At(r),r;var i=m({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),At(r),Fd(r,`style`,i),Rf(r,n.precedence,e),t.instance=r;case`stylesheet`:i=jf(n.href);var o=e.querySelector(Mf(i));if(o)return t.state.loading|=4,t.instance=o,At(o),o;r=Nf(n),(i=hf.get(i))&&zf(r,i),o=(e.ownerDocument||e).createElement(`link`),At(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Fd(o,`link`,r),t.state.loading|=4,Rf(o,n.precedence,e),t.instance=o;case`script`:return o=Ff(n.src),(i=e.querySelector(If(o)))?(t.instance=i,At(i),i):(r=n,(i=hf.get(o))&&(r=m({},n),Bf(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),At(i),Fd(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(a(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Rf(r,n.precedence,e));return t.instance}function Rf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Wf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Gf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Kf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=jf(r.href),a=t.querySelector(Mf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=Yf.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,At(a);return}a=t.ownerDocument||t,r=Nf(r),(i=hf.get(i))&&zf(r,i),a=a.createElement(`link`),At(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Fd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=Yf.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var qf=0;function Jf(e,t){return e.stylesheets&&e.count===0&&Zf(e,e.stylesheets),0qf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function Yf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Zf(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Xf=null;function Zf(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Xf=new Map,t.forEach(Qf,e),Xf=null,Yf.call(e))}function Qf(e,t){if(!(t.state.loading&4)){var n=Xf.get(e);if(n)var r=n.get(null);else{n=new Map,Xf.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=be()})),Se=`__TSS_CONTEXT`,Ce=Symbol.for(`TSS_SERVER_FUNCTION`),we=Symbol.for(`TSS_SERVER_FUNCTION_FACTORY`),Te=`application/x-tss-framed`,Ee={JSON:0,CHUNK:1,END:2,ERROR:3};`${Te}`;var De=/;\s*v=(\d+)/;function Oe(e){let t=e.match(De);return t?parseInt(t[1],10):void 0}function ke(e){let t=Oe(e);if(t!==void 0&&t!==1)throw Error(`Incompatible framed protocol version: server=${t}, client=1. Please ensure client and server are using compatible versions.`)}var Ae=()=>window.__TSS_START_OPTIONS__;function je(e){return e?.isNotFound===!0}function Me(){try{return sessionStorage}catch{return}}var Ne=`tsr-scroll-restoration-v1_3`,Pe=Me();function Fe(){try{return JSON.parse(Pe?.getItem(`tsr-scroll-restoration-v1_3`)||`{}`)}catch{return{}}}function Ie(){try{Pe?.setItem(Ne,JSON.stringify(Le))}catch{}}var Le=Fe(),Re=`data-scroll-restoration-id`,ze=e=>e.state.__TSR_key||e.href;function Be(e){let t=e.getAttribute(Re);if(t)return`[${Re}="${t}"]`;let n=``,r=e,i;for(;i=r.parentNode;){let e=1,t=r;for(;t=t.previousElementSibling;)e++;let a=`${r.localName}:nth-child(${e})`;n=n?`${a} > ${n}`:a,r=i}return n}var Ve=!1,He=`window`;function Ue(e){try{return typeof e==`function`?e():document.querySelector(e)}catch{}}function We(e){let t=new Set;for(let n of e){if(n===He)continue;let e=Ue(n);e&&t.add(e)}return t}function Ge(e,t){let n=t??e.options.scrollRestoration,r=e._scroll;n&&(r.restoring=!0);let i=e.options.getScrollRestorationKey||ze,a=new Set,o=e=>{let t=Le[e]||={};for(let e of a)e===document?t[He]={scrollX,scrollY}:e.isConnected&&(t[Be(e)]={scrollX:e.scrollLeft,scrollY:e.scrollTop})};n&&!r.restoration&&(r.restoration=!0,Ve=!1,history.scrollRestoration=`manual`,document.addEventListener(`scroll`,e=>{Ve||a.add(e.target)},!0),e.subscribe(`onBeforeLoad`,e=>{e.fromLocation&&o(i(e.fromLocation)),a.clear()}),addEventListener(`pagehide`,()=>{o(i(e.stores.resolvedLocation.get()??e.stores.location.get())),Ie()})),!r.reset&&(r.reset=!0,e.subscribe(`onRendered`,t=>{let n=e.options.scrollRestorationBehavior,o=e.options.scrollToTopSelectors,s=r.next,c=r.hash,l;if(a.clear(),r.next=!0,r.hash=!1,typeof e.options.scrollRestoration==`function`&&!e.options.scrollRestoration({location:e.latestLocation}))return;let u=i(t.toLocation),d=t.fromLocation&&i(t.fromLocation);if(r.restoring&&d&&d!==u){let e=Le[d];if(e){let t=Le[u];for(let n in e){if(n===He){if(s)continue}else{let e=Ue(n);if(!e||s&&o&&(l??=We(o),l.has(e)))continue}t||=Le[u]={},t[n]??=e[n]}}}Ve=!0;try{let e=t.toLocation.hash,i=t.toLocation.state.__hashScrollIntoViewOptions??!0,a=!1;if(s){!e&&o&&(l??=We(o));let t=e&&i&&c,s=r.restoring?Le[u]:void 0;if(s)for(let e in s){let{scrollX:r,scrollY:i}=s[e];if(e===He){if(t)continue;scrollTo({top:i,left:r,behavior:n}),a=!0}else{let t=Ue(e);t&&(t.scrollLeft=r,t.scrollTop=i,l?.delete(t))}}if(!e){let e={top:0,left:0,behavior:n};if(a||scrollTo(e),l)for(let t of l)t.scrollTo(e)}}!a&&e&&i&&document.getElementById(e)?.scrollIntoView(i)}finally{Ve=!1}}))}function Ke(e,t=String){let n=new URLSearchParams;for(let r in e){let i=e[r];i!==void 0&&n.set(r,t(i))}return n.toString()}function qe(e){return e?e===`false`?!1:e===`true`?!0:e*0==0&&+e+``===e?+e:e:``}function Je(e){let t=new URLSearchParams(e),n=Object.create(null);for(let[e,r]of t.entries()){let t=n[e];t==null?n[e]=qe(r):Array.isArray(t)?t.push(qe(r)):n[e]=[t,qe(r)]}return n}var Ye=Ze(JSON.parse),Xe=Qe(JSON.stringify,JSON.parse);function Ze(e){return t=>{t[0]===`?`&&(t=t.substring(1));let n=Je(t);for(let t in n){let r=n[t];if(typeof r==`string`)try{n[t]=e(r)}catch{}}return n}}function Qe(e,t){let n=typeof t==`function`;function r(r){if(typeof r==`object`&&r)try{return e(r)}catch{}else if(n&&typeof r==`string`)try{return t(r),e(r)}catch{}return r}return e=>{let t=Ke(e,r);return t?`?${t}`:``}}var $e=`__root__`;function et(e){if(e.statusCode=e.statusCode||e.code||307,!e._builtLocation&&!e.reloadDocument&&typeof e.href==`string`)try{new URL(e.href),e.reloadDocument=!0}catch{}let t=new Headers(e.headers);e.href&&t.get(`Location`)===null&&t.set(`Location`,e.href);let n=new Response(null,{status:e.statusCode,headers:t});if(n.options=e,e.throw)throw n;return n}function tt(e){return e instanceof Response&&!!e.options}function nt(e){if(typeof e==`object`&&e&&e.isSerializedRedirect)return et(e)}function rt(e){return{input:({url:t})=>{for(let n of e)t=at(n,t);return t},output:({url:t})=>{for(let n=e.length-1;n>=0;n--)t=ot(e[n],t);return t}}}function it(e){let t=ge(e.basepath),n=`/${t}`,r=e.caseSensitive?n:n.toLowerCase(),i=`${r}/`;return{input:({url:t})=>{let a=e.caseSensitive?t.pathname:t.pathname.toLowerCase();return a===r?t.pathname=`/`:a.startsWith(i)&&(t.pathname=t.pathname.slice(n.length)),t},output:({url:e})=>(e.pathname=C([`/`,t,e.pathname]),e)}}function at(e,t){let n=e?.input?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function ot(e,t){let n=e?.output?.({url:t});if(n){if(typeof n==`string`)return new URL(n);if(n instanceof URL)return n}return t}function st(e,t){let{createMutableStore:n,createReadonlyStore:r,batch:i,init:a}=t,o=new Map,s=new Map,c=new Map,l=n(e.status),u=n(e.loadedAt),d=n(e.isLoading),f=n(e.isTransitioning),p=n(e.location),m=n(e.resolvedLocation),g=n(e.statusCode),_=n(e.redirect),v=n([]),y=n([]),b=n([]),x=r(()=>ct(o,v.get())),S=r(()=>ct(s,y.get())),C=r(()=>ct(c,b.get())),w=r(()=>v.get()[0]),ee=r(()=>v.get().some(e=>o.get(e)?.get().status===`pending`)),te=r(()=>({locationHref:p.get().href,resolvedLocationHref:m.get()?.href,status:l.get()})),ne=r(()=>({status:l.get(),loadedAt:u.get(),isLoading:d.get(),isTransitioning:f.get(),matches:x.get(),location:p.get(),resolvedLocation:m.get(),statusCode:g.get(),redirect:_.get()})),re=h(64);function ie(e){let t=re.get(e);return t||(t=r(()=>{let t=v.get();for(let n of t){let t=o.get(n);if(t&&t.routeId===e)return t.get()}}),re.set(e,t)),t}let ae={status:l,loadedAt:u,isLoading:d,isTransitioning:f,location:p,resolvedLocation:m,statusCode:g,redirect:_,matchesId:v,pendingIds:y,cachedIds:b,matches:x,pendingMatches:S,cachedMatches:C,firstId:w,hasPending:ee,matchRouteDeps:te,matchStores:o,pendingMatchStores:s,cachedMatchStores:c,__store:ne,getRouteMatchStore:ie,setMatches:oe,setPending:se,setCached:ce};oe(e.matches),a?.(ae);function oe(e){lt(e,o,v,n,i)}function se(e){lt(e,s,y,n,i)}function ce(e){lt(e,c,b,n,i)}return ae}function ct(e,t){let n=[];for(let r of t){let t=e.get(r);t&&n.push(t.get())}return n}function lt(e,t,n,r,i){let a=e.map(e=>e.id),o=new Set(a);i(()=>{for(let e of t.keys())o.has(e)||t.delete(e);for(let n of e){let e=t.get(n.id);if(!e){let e=r(n);e.routeId=n.routeId,t.set(n.id,e);continue}e.routeId=n.routeId,e.get()!==n&&e.set(n)}se(n.get(),a)||n.set(a)})}var ut=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},dt=e=>e.stores.matchesId.get().some(t=>e.stores.matchStores.get(t)?.get()._forcePending),ft=(e,t)=>!!(e.preload&&!e.router.stores.matchStores.has(t)),pt=(e,t,n=!0)=>{let r={...e.router.options.context??{}},i=n?t:t-1;for(let t=0;t<=i;t++){let n=e.matches[t];if(!n)continue;let i=e.router.getMatch(n.id);i&&Object.assign(r,i.__routeContext,i.__beforeLoadContext)}return r},mt=(e,t)=>{if(!e.matches.length)return;let n=t.routeId,r=e.matches.findIndex(t=>t.routeId===e.router.routeTree.id),i=r>=0?r:0,a=n?e.matches.findIndex(e=>e.routeId===n):e.firstBadMatchIndex??e.matches.length-1;a<0&&(a=i);for(let t=a;t>=0;t--){let n=e.matches[t];if(e.router.looseRoutesById[n.routeId].options.notFoundComponent)return t}return n?a:i},ht=(e,t,n)=>{if(!(!tt(n)&&!je(n)))throw tt(n)&&n.redirectHandled&&!n.options.reloadDocument?n:(t&&(t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0,t._nonReactive.error=n,e.updateMatch(t.id,r=>({...r,status:tt(n)?`redirected`:je(n)?`notFound`:r.status===`pending`?`success`:r.status,context:pt(e,t.index),isFetching:!1,error:n})),je(n)&&!n.routeId&&(n.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()),tt(n)&&(e.rendered=!0,n.options._fromLocation=e.location,n.redirectHandled=!0,n=e.router.resolveRedirect(n)),n)},gt=(e,t)=>{let n=e.router.getMatch(t);return!!(!n||n._nonReactive.dehydrated)},_t=(e,t,n)=>{let r=pt(e,n);e.updateMatch(t,e=>({...e,context:r}))},vt=(e,t,n)=>{let{id:r,routeId:i}=e.matches[t],a=e.router.looseRoutesById[i];if(n instanceof Promise)throw n;e.firstBadMatchIndex??=t,ht(e,e.router.getMatch(r),n);try{a.options.onError?.(n)}catch(t){n=t,ht(e,e.router.getMatch(r),n)}e.updateMatch(r,e=>(e._nonReactive.beforeLoadPromise?.resolve(),e._nonReactive.beforeLoadPromise=void 0,e._nonReactive.loadPromise?.resolve(),{...e,error:n,status:`error`,isFetching:!1,updatedAt:Date.now(),abortController:new AbortController})),!e.preload&&!tt(n)&&!je(n)&&(e.serialError??=n)},yt=(e,t,n,r)=>{if(r._nonReactive.pendingTimeout!==void 0)return;let i=n.options.pendingMs??e.router.options.defaultPendingMs;if(e.onReady&&!ft(e,t)&&(n.options.loader||n.options.beforeLoad||At(n))&&typeof i==`number`&&i!==1/0&&(n.options.pendingComponent??e.router.options?.defaultPendingComponent)){let t=setTimeout(()=>{ut(e)},i);r._nonReactive.pendingTimeout=t}},bt=(e,t,n)=>{let r=e.router.getMatch(t);if(!r._nonReactive.beforeLoadPromise&&!r._nonReactive.loaderPromise)return;yt(e,t,n,r);let i=()=>{let n=e.router.getMatch(t);n.preload&&(n.status===`redirected`||n.status===`notFound`)&&ht(e,n,n.error)};return r._nonReactive.beforeLoadPromise?r._nonReactive.beforeLoadPromise.then(i):i()},xt=(e,t,n,r)=>{let i=e.router.getMatch(t),a=i._nonReactive.loadPromise;i._nonReactive.loadPromise=p(()=>{a?.resolve(),a=void 0});let{paramsError:o,searchError:s}=i;o&&vt(e,n,o),s&&vt(e,n,s),yt(e,t,r,i);let c=new AbortController,l=!1,u=()=>{l||(l=!0,e.updateMatch(t,e=>({...e,isFetching:`beforeLoad`,fetchCount:e.fetchCount+1,abortController:c})))},d=()=>{i._nonReactive.beforeLoadPromise?.resolve(),i._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,e=>({...e,isFetching:!1}))};if(!r.options.beforeLoad){e.router.batch(()=>{u(),d()});return}i._nonReactive.beforeLoadPromise=p();let f={...pt(e,n,!1),...i.__routeContext},{search:m,params:h,cause:g}=i,_=ft(e,t),v={search:m,abortController:c,params:h,preload:_,context:f,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:_?`preload`:g,matches:e.matches,routeId:r.id,...e.router.options.additionalContext},y=r=>{if(r===void 0){e.router.batch(()=>{u(),d()});return}(tt(r)||je(r))&&(u(),vt(e,n,r)),e.router.batch(()=>{u(),e.updateMatch(t,e=>({...e,__beforeLoadContext:r})),d()})},b;try{if(b=r.options.beforeLoad(v),x(b))return u(),b.catch(t=>{vt(e,n,t)}).then(y)}catch(t){u(),vt(e,n,t)}y(b)},St=(e,t)=>{let{id:n,routeId:r}=e.matches[t],i=e.router.looseRoutesById[r],a=()=>s(),o=()=>xt(e,n,t,i),s=()=>{if(gt(e,n))return;let t=bt(e,n,i);return x(t)?t.then(o):o()};return a()},Ct=(e,t,n)=>{let r=e.router.getMatch(t);if(!r||!n.options.head&&!n.options.scripts&&!n.options.headers)return;let i={ssr:e.router.options.ssr,matches:e.matches,match:r,params:r.params,loaderData:r.loaderData};return Promise.all([n.options.head?.(i),n.options.scripts?.(i),n.options.headers?.(i)]).then(([e,t,n])=>({meta:e?.meta,links:e?.links,headScripts:e?.scripts,headers:n,scripts:t,styles:e?.styles}))},wt=(e,t,n,r,i)=>{let a=t[r-1],{params:o,loaderDeps:s,abortController:c,cause:l}=e.router.getMatch(n),u=pt(e,r),d=ft(e,n);return{params:o,deps:s,preload:!!d,parentMatchPromise:a,abortController:c,context:u,location:e.location,navigate:t=>e.router.navigate({...t,_fromLocation:e.location}),cause:d?`preload`:l,route:i,...e.router.options.additionalContext}},Tt=async(e,t,n,r,i)=>{try{let a=e.router.getMatch(n);try{kt(i);let o=i.options.loader,s=typeof o==`function`?o:o?.handler,c=s?.(wt(e,t,n,r,i)),l=!!s&&x(c);if((l||i._lazyPromise||i._componentsPromise||i.options.head||i.options.scripts||i.options.headers||a._nonReactive.minPendingPromise)&&e.updateMatch(n,e=>({...e,isFetching:`loader`})),s){let t=l?await c:c;ht(e,e.router.getMatch(n),t),t!==void 0&&e.updateMatch(n,e=>({...e,loaderData:t}))}i._lazyPromise&&await i._lazyPromise;let u=a._nonReactive.minPendingPromise;u&&await u,i._componentsPromise&&await i._componentsPromise,e.updateMatch(n,t=>({...t,error:void 0,context:pt(e,r),status:`success`,isFetching:!1,updatedAt:Date.now()}))}catch(t){let o=t;if(o?.name===`AbortError`){if(a.abortController.signal.aborted){a._nonReactive.loaderPromise?.resolve(),a._nonReactive.loaderPromise=void 0;return}e.updateMatch(n,t=>({...t,status:t.status===`pending`?`success`:t.status,isFetching:!1,context:pt(e,r)}));return}let s=a._nonReactive.minPendingPromise;s&&await s,je(t)&&await i.options.notFoundComponent?.preload?.(),ht(e,e.router.getMatch(n),t);try{i.options.onError?.(t)}catch(t){o=t,ht(e,e.router.getMatch(n),t)}!tt(o)&&!je(o)&&await kt(i,[`errorComponent`]),e.updateMatch(n,t=>({...t,error:o,context:pt(e,r),status:`error`,isFetching:!1}))}}catch(t){let r=e.router.getMatch(n);r&&(r._nonReactive.loaderPromise=void 0),ht(e,r,t)}},Et=async(e,t,n)=>{async function r(r,a,c,l,d){let f=Date.now()-a.updatedAt,p=r?d.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:d.options.staleTime??e.router.options.defaultStaleTime??0,m=d.options.shouldReload,h=typeof m==`function`?m(wt(e,t,i,n,d)):m,{status:g,invalid:_}=l,v=f>=p&&(!!e.forceStaleReload||l.cause===`enter`||c!==void 0&&c!==l.id);o=g===`success`&&(_||(h??v)),r&&d.options.preload===!1||(o&&!e.sync&&u?(s=!0,(async()=>{try{await Tt(e,t,i,n,d);let r=e.router.getMatch(i);r._nonReactive.loaderPromise?.resolve(),r._nonReactive.loadPromise?.resolve(),r._nonReactive.loaderPromise=void 0,r._nonReactive.loadPromise=void 0}catch(t){tt(t)&&await e.router.navigate(t.options)}})()):g!==`success`||o?await Tt(e,t,i,n,d):_t(e,i,n))}let{id:i,routeId:a}=e.matches[n],o=!1,s=!1,c=e.router.looseRoutesById[a],l=c.options.loader,u=((typeof l==`function`?void 0:l?.staleReloadMode)??e.router.options.defaultStaleReloadMode)!==`blocking`;if(gt(e,i)){if(!e.router.getMatch(i))return e.matches[n];_t(e,i,n)}else{let t=e.router.getMatch(i),o=e.router.stores.matchesId.get()[n],s=(o&&e.router.stores.matchStores.get(o)||null)?.routeId===a?o:e.router.stores.matches.get().find(e=>e.routeId===a)?.id,l=ft(e,i);if(t._nonReactive.loaderPromise){if(t.status===`success`&&!e.sync&&!t.preload&&u)return t;await t._nonReactive.loaderPromise;let n=e.router.getMatch(i),a=n._nonReactive.error||n.error;a&&ht(e,n,a),n.status===`pending`&&await r(l,t,s,n,c)}else{let n=l&&!e.router.stores.matchStores.has(i),a=e.router.getMatch(i);a._nonReactive.loaderPromise=p(),n!==a.preload&&e.updateMatch(i,e=>({...e,preload:n})),await r(l,t,s,a,c)}}let d=e.router.getMatch(i);s||(d._nonReactive.loaderPromise?.resolve(),d._nonReactive.loadPromise?.resolve(),d._nonReactive.loadPromise=void 0),clearTimeout(d._nonReactive.pendingTimeout),d._nonReactive.pendingTimeout=void 0,s||(d._nonReactive.loaderPromise=void 0),d._nonReactive.dehydrated=void 0;let f=s?d.isFetching:!1;return f!==d.isFetching||d.invalid!==!1?(e.updateMatch(i,e=>({...e,isFetching:f,invalid:!1})),e.router.getMatch(i)):d};async function Dt(e){let t=e,n=[];dt(t.router)&&ut(t);let r;for(let e=0;e({...e,...a?{status:`success`,globalNotFound:!0,error:void 0}:{status:`notFound`,error:l},isFetching:!1})),u=e,await kt(r,[`notFoundComponent`])}else if(!t.preload){let e=t.matches[0];e.globalNotFound||t.router.getMatch(e.id)?.globalNotFound&&t.updateMatch(e.id,e=>({...e,globalNotFound:!1,error:void 0}))}if(t.serialError&&t.firstBadMatchIndex!==void 0){let e=t.router.looseRoutesById[t.matches[t.firstBadMatchIndex].routeId];await kt(e,[`errorComponent`])}for(let e=0;e<=u;e++){let{id:n,routeId:r}=t.matches[e],i=t.router.looseRoutesById[r];try{let e=Ct(t,n,i);if(e){let r=await e;t.updateMatch(n,e=>({...e,...r}))}}catch(e){console.error(`Error executing head for route ${r}:`,e)}}let d=ut(t);if(x(d)&&await d,l)throw l;if(t.serialError&&!t.preload&&!t.onReady)throw t.serialError;return t.matches}function Ot(e,t){let n=t.map(t=>e.options[t]?.preload?.()).filter(Boolean);if(n.length!==0)return Promise.all(n)}function kt(e,t=jt){!e._lazyLoaded&&e._lazyPromise===void 0&&(e.lazyFn?e._lazyPromise=e.lazyFn().then(t=>{let{id:n,...r}=t.options;Object.assign(e.options,r),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0);let n=()=>e._componentsLoaded?void 0:t===jt?(()=>{if(e._componentsPromise===void 0){let t=Ot(e,jt);t?e._componentsPromise=t.then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0}):e._componentsLoaded=!0}return e._componentsPromise})():Ot(e,t);return e._lazyPromise?e._lazyPromise.then(n):n()}function At(e){for(let t of jt)if(e.options[t]?.preload)return!0;return!1}var jt=[`component`,`errorComponent`,`pendingComponent`,`notFoundComponent`],Mt=`__TSR_index`,Nt=`popstate`,Pt=`beforeunload`;function Ft(e){let t=e.getLocation(),n=new Set,r=r=>{t=e.getLocation(),n.forEach(e=>e({location:t,action:r}))},i=n=>{e.notifyOnIndexChange??!0?r(n):t=e.getLocation()},a=async({task:n,navigateOpts:r,...i})=>{if(r?.ignoreBlocker??!1){n();return}let a=e.getBlockers?.()??[],o=i.type===`PUSH`||i.type===`REPLACE`;if(typeof document<`u`&&a.length&&o)for(let n of a){let r=zt(i.path,i.state);if(await n.blockerFn({currentLocation:t,nextLocation:r,action:i.type})){e.onBlocked?.();return}}n()};return{get location(){return t},get length(){return e.getLength()},subscribers:n,subscribe:e=>(n.add(e),()=>{n.delete(e)}),push:(n,i,o)=>{let s=t.state[Mt];i=It(s+1,i),a({task:()=>{e.pushState(n,i),r({type:`PUSH`})},navigateOpts:o,type:`PUSH`,path:n,state:i})},replace:(n,i,o)=>{let s=t.state[Mt];i=It(s,i),a({task:()=>{e.replaceState(n,i),r({type:`REPLACE`})},navigateOpts:o,type:`REPLACE`,path:n,state:i})},go:(t,n)=>{a({task:()=>{e.go(t),i({type:`GO`,index:t})},navigateOpts:n,type:`GO`})},back:t=>{a({task:()=>{e.back(t?.ignoreBlocker??!1),i({type:`BACK`})},navigateOpts:t,type:`BACK`})},forward:t=>{a({task:()=>{e.forward(t?.ignoreBlocker??!1),i({type:`FORWARD`})},navigateOpts:t,type:`FORWARD`})},canGoBack:()=>t.state[Mt]!==0,createHref:t=>e.createHref(t),block:t=>{if(!e.setBlockers)return()=>{};let n=e.getBlockers?.()??[];return e.setBlockers([...n,t]),()=>{let n=e.getBlockers?.()??[];e.setBlockers?.(n.filter(e=>e!==t))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:r}}function It(e,t){t||={};let n=Bt();return{...t,key:n,__TSR_key:n,[Mt]:e}}function Lt(e){let t=e?.window??(typeof document<`u`?window:void 0),n=t.history.pushState,r=t.history.replaceState,i=[],a=()=>i,o=e=>i=e,s=e?.createHref??(e=>e),c=e?.parseLocation??(()=>zt(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){let e=Bt();t.history.replaceState({[Mt]:0,key:e,__TSR_key:e},``)}let l=c(),u,d=!1,f=!1,p=!1,m=!1,h=()=>l,g,_,v=()=>{g&&(C._ignoreSubscribers=!0,(g.isPush?t.history.pushState:t.history.replaceState)(g.state,``,g.href),C._ignoreSubscribers=!1,g=void 0,_=void 0,u=void 0)},y=(e,t,n)=>{let r=s(t);_||(u=l),l=zt(t,n),g={href:r,state:n,isPush:g?.isPush||e===`push`},_||=Promise.resolve().then(()=>v())},b=e=>{l=c(),C.notify({type:e})},x=async()=>{if(f){f=!1;return}let e=c(),n=e.state[Mt]-l.state[Mt],r=n===1,i=n===-1,o=!r&&!i||d;d=!1;let s=o?`GO`:i?`BACK`:`FORWARD`,u=o?{type:`GO`,index:n}:{type:i?`BACK`:`FORWARD`};if(p)p=!1;else{let n=a();if(typeof document<`u`&&n.length){for(let r of n)if(await r.blockerFn({currentLocation:l,nextLocation:e,action:s})){f=!0,t.history.go(1),C.notify(u);return}}}l=c(),C.notify(u)},S=e=>{if(m){m=!1;return}let t=!1,n=a();if(typeof document<`u`&&n.length)for(let e of n){let n=e.enableBeforeUnload??!0;if(n===!0){t=!0;break}if(typeof n==`function`&&n()===!0){t=!0;break}}if(t)return e.preventDefault(),e.returnValue=``},C=Ft({getLocation:h,getLength:()=>t.history.length,pushState:(e,t)=>y(`push`,e,t),replaceState:(e,t)=>y(`replace`,e,t),back:e=>(e&&(p=!0),m=!0,t.history.back()),forward:e=>{e&&(p=!0),m=!0,t.history.forward()},go:e=>{d=!0,t.history.go(e)},createHref:e=>s(e),flush:v,destroy:()=>{t.history.pushState=n,t.history.replaceState=r,t.removeEventListener(Pt,S,{capture:!0}),t.removeEventListener(Nt,x)},onBlocked:()=>{u&&l!==u&&(l=u)},getBlockers:a,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Pt,S,{capture:!0}),t.addEventListener(Nt,x),t.history.pushState=function(...e){let r=n.apply(t.history,e);return C._ignoreSubscribers||b(`PUSH`),r},t.history.replaceState=function(...e){let n=r.apply(t.history,e);return C._ignoreSubscribers||b(`REPLACE`),n},C}function Rt(e){let t=e.replace(/[\x00-\x1f\x7f]/g,``);return t.startsWith(`//`)&&(t=`/`+t.replace(/^\/+/,``)),t}function zt(e,t){let n=Rt(e),r=n.indexOf(`#`),i=n.indexOf(`?`),a=Bt();return{href:n,pathname:n.substring(0,r>0?i>0?Math.min(r,i):r:i>0?i:n.length),hash:r>-1?n.substring(r):``,search:i>-1?n.slice(i,r===-1?void 0:r):``,state:t||{[Mt]:0,key:a,__TSR_key:a}}}function Bt(){return(Math.random()+1).toString(36).substring(7)}function Vt(e){return e instanceof Error?{name:e.name,message:e.message}:{data:e}}function Ht(e,t){let n=t,r=e;return{fromLocation:n,toLocation:r,pathChanged:n?.pathname!==r.pathname,hrefChanged:n?.href!==r.href,hashChanged:n?.hash!==r.hash}}var Ut=class{constructor(e,t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this._scroll={next:!0},this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.routeBranchCache=new WeakMap,this.lightweightCache=new WeakMap,this.startTransition=e=>e(),this.update=e=>{let t=this.options,n=this.basepath??t?.basepath??`/`,r=this.basepath===void 0,i=t?.rewrite;if(this.options={...t,...e},this.isServer=this.options.isServer??typeof document>`u`,this.protocolAllowlist=new Set(this.options.protocolAllowlist),this.options.pathParamsAllowedCharacters&&(this.pathParamsDecoder=ae(this.options.pathParamsAllowedCharacters)),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.history=Lt()),this.origin=this.options.origin,this.origin||(window?.origin&&window.origin!==`null`?this.origin=window.origin:this.origin=`http://localhost`),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree){this.routeTree=this.options.routeTree;let e;this.resolvePathCache=h(1e3),e=this.buildRouteTree(),this.setRoutes(e)}if(!this.stores&&this.latestLocation){let e=this.getStoreConfig(this);this.batch=e.batch,this.stores=st(Kt(this.latestLocation),e),Ge(this)}let a=!1,o=this.options.basepath??`/`,s=this.options.rewrite;if(r||n!==o||i!==s){this.basepath=o;let e=[],t=ge(o);t&&t!==`/`&&e.push(it({basepath:o})),s&&e.push(s),this.rewrite=e.length===0?void 0:e.length===1?e[0]:rt(e),this.history&&this.updateLatestLocation(),a=!0}a&&this.stores&&this.stores.location.set(this.latestLocation),typeof window<`u`&&`CSS`in window&&typeof window.CSS?.supports==`function`&&(this.isViewTransitionTypesSupported=window.CSS.supports(`selector(:active-view-transition-type(a))`))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{let e=o(this.routeTree,this.options.caseSensitive,(e,t)=>{e.init({originalIndex:t})});return this.options.routeMasks&&s(this.options.routeMasks,e.processedTree),e},this.subscribe=(e,t)=>{let n={eventType:e,fn:t};return this.subscribers.add(n),()=>{this.subscribers.delete(n)}},this.emit=e=>{this.subscribers.forEach(t=>{t.eventType===e.type&&t.fn(e)})},this.parseLocation=(e,t)=>{let n=({pathname:e,search:n,hash:r,href:i,state:a})=>{if(!this.rewrite&&!/[ \x00-\x1f\x7f\u0080-\uffff]/.test(e)){let i=this.options.parseSearch(n),o=this.options.stringifySearch(i);return{href:e+o+r,publicHref:e+o+r,pathname:m(e).path,external:!1,searchStr:o,search:b(t?.search,i),hash:m(r.slice(1)).path,state:S(t?.state,a)}}let o=new URL(i,this.origin),s=at(this.rewrite,o),c=this.options.parseSearch(s.search),l=this.options.stringifySearch(c);return s.search=l,{href:s.href.replace(s.origin,``),publicHref:i,pathname:m(s.pathname).path,external:!!this.rewrite&&s.origin!==this.origin,searchStr:l,search:b(t?.search,c),hash:m(s.hash.slice(1)).path,state:S(t?.state,a)}},r=n(e),{__tempLocation:i,__tempKey:a}=r.state;if(i&&(!a||a===this.tempLocationKey)){let e=n(i);return e.state.key=r.state.key,e.state.__TSR_key=r.state.__TSR_key,delete e.state.__tempLocation,{...e,maskedLocation:r}}return r},this.resolvePathWithBase=(e,t)=>me({base:e,to:t.includes(`//`)?E(t):t,trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(e,t,n)=>typeof e==`string`?this.matchRoutesInternal({pathname:e,search:t},n):this.matchRoutesInternal(e,t),this.getMatchedRoutes=e=>Jt({pathname:e,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=e=>{let t=this.getMatch(e);t&&(t.abortController.abort(),clearTimeout(t._nonReactive.pendingTimeout),t._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{this.stores.pendingIds.get().forEach(e=>{this.cancelMatch(e)}),this.stores.matchesId.get().forEach(e=>{if(this.stores.pendingMatchStores.has(e))return;let t=this.stores.matchStores.get(e)?.get();t&&(t.status===`pending`||t.isFetching===`loader`)&&this.cancelMatch(e)})},this.buildLocation=e=>{let t=(t={})=>{let n=t._fromLocation||this.pendingBuiltLocation||this.latestLocation,r=this.matchRoutesLightweight(n);t.from;let i=t.unsafeRelative===`path`?n.pathname:t.from??r.fullPath,a=t.to?`${t.to}`:void 0,o=r.search,s=Object.assign(Object.create(null),r.params),l=a?.charCodeAt(0)===47?`/`:this.resolvePathWithBase(i,`.`),u=a?this.resolvePathWithBase(l,a):l,d=t.params===!1||t.params===null?Object.create(null):(t.params??!0)===!0?s:Object.assign(s,f(t.params,s)),p=this.routesByPath[he(u)],h;if(p)h=this.getRouteBranch(p);else if(u.includes(`$`))h=[];else{let e=this.getMatchedRoutes(u);h=e.matchedRoutes,this.options.notFoundRoute&&(!e.foundRoute||e.foundRoute.path!==`/`&&e.routeParams[`**`])&&(h=[...h,this.options.notFoundRoute])}if(h.length&&_(d))for(let e of h){let t=e.options.params?.stringify??e.options.stringifyParams;if(t)try{Object.assign(d,t(d))}catch{}}let g=e.leaveParams?u:m(ie({path:u,params:d,decoder:this.pathParamsDecoder,server:this.isServer}).interpolatedPath).path,v=o;if(e._includeValidateSearch&&this.options.search?.strict){let e={};h.forEach(t=>{if(t.options.validateSearch)try{Object.assign(e,qt(t.options.validateSearch,{...e,...v}))}catch{}}),v=e}v=Yt({search:v,dest:t,destRoutes:h,_includeValidateSearch:e._includeValidateSearch}),v=b(o,v);let y=this.options.stringifySearch(v),x=t.hash===!0?n.hash:t.hash?f(t.hash,n.hash):void 0,C=x?`#${x}`:``,w=t.state===!0?n.state:t.state?f(t.state,n.state):{};w=S(n.state,w);let ee=`${g}${y}${C}`,te,ne,re=!1;if(this.rewrite){let e=new URL(ee,this.origin),t=ot(this.rewrite,e);te=e.href.replace(e.origin,``),t.origin===this.origin?ne=t.pathname+t.search+t.hash:(ne=t.href,re=!0)}else te=c(ee),ne=te;return{publicHref:ne,href:te,pathname:g,search:v,searchStr:y,state:w,hash:x??``,external:re,unmaskOnReload:t.unmaskOnReload}},n=(n={},r)=>{let i=t(n),o=r?t(r):void 0;if(!o){let n=Object.create(null);if(this.options.routeMasks){let s=a(i.pathname,this.processedTree);if(s){Object.assign(n,s.rawParams);let{from:i,params:a,...c}=s.route,l=a===!1||a===null?Object.create(null):(a??!0)===!0?n:Object.assign(n,f(a,n));r={from:e.from,...c,params:l},o=t(r)}}}return o&&(i.maskedLocation=o),i};return e.mask?n(e,{from:e.from,...e.mask}):n(e)},this.commitLocation=async({viewTransition:e,ignoreBlocker:t,...n})=>{let r,i=()=>{let e=[`key`,`__TSR_key`,`__TSR_index`,`__hashScrollIntoViewOptions`];e.forEach(e=>{n.state[e]=this.latestLocation.state[e]});let t=g(n.state,this.latestLocation.state);return e.forEach(e=>{delete n.state[e]}),t},a=he(this.latestLocation.href)===he(n.href),o=this.commitLocationPromise;if(this.commitLocationPromise=p(()=>{o?.resolve(),o=void 0}),a&&i())this.load();else{let{maskedLocation:i,hashScrollIntoView:a,...o}=n;i&&(o={...i,state:{...i.state,__tempKey:void 0,__tempLocation:{...o,search:o.searchStr,state:{...o.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(o.unmaskOnReload??this.options.unmaskOnReload??!1)&&(o.state.__tempKey=this.tempLocationKey)),o.state.__hashScrollIntoViewOptions=a??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=e,r=n.replace?`REPLACE`:`PUSH`,this.history[r===`REPLACE`?`replace`:`push`](o.publicHref,o.state,{ignoreBlocker:t})}return this._scroll.next=n.resetScroll??!0,this.history.subscribers.size||this.load(r?{action:{type:r}}:void 0),this.commitLocationPromise},this.buildAndCommitLocation=({replace:e,resetScroll:t,hashScrollIntoView:n,viewTransition:r,ignoreBlocker:i,href:a,...o}={})=>{if(a){let t=this.history.location.state.__TSR_index,n=zt(a,{__TSR_index:e?t:t+1}),r=new URL(n.pathname,this.origin);o.to=at(this.rewrite,r).pathname,o.search=this.options.parseSearch(n.search),o.hash=n.hash.slice(1)}let s=this.buildLocation({...o,_includeValidateSearch:!0});this.pendingBuiltLocation=s;let c=this.commitLocation({...s,viewTransition:r,replace:e,resetScroll:t,hashScrollIntoView:n,ignoreBlocker:i});return queueMicrotask(()=>{this.pendingBuiltLocation===s&&(this.pendingBuiltLocation=void 0)}),c},this.navigate=async({to:e,reloadDocument:t,href:n,publicHref:r,...i})=>{let a=!1;if(n)try{new URL(`${n}`),a=!0}catch{}if(a&&!t&&(t=!0),t){if(e!==void 0||!n){let t=this.buildLocation({to:e,...i});n??=t.publicHref,r??=t.publicHref}let t=!a&&r?r:n;if(_e(t,this.protocolAllowlist))return;if(!i.ignoreBlocker){let e=this.history.getBlockers?.()??[];for(let t of e)if(t?.blockerFn&&await t.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:`PUSH`}))return}i.replace?window.location.replace(t):window.location.href=t;return}return this.buildAndCommitLocation({...i,href:n,to:e,_isNavigate:!0})},this.beforeLoad=()=>{this.cancelMatches(),this.updateLatestLocation();let e=this.matchRoutes(this.latestLocation),t=this.stores.cachedMatches.get().filter(t=>!e.some(e=>e.id===t.id));this.batch(()=>{this.stores.status.set(`pending`),this.stores.statusCode.set(200),this.stores.isLoading.set(!0),this.stores.location.set(this.latestLocation),this.stores.setPending(e),this.stores.setCached(t)})},this.load=async e=>{let t=e?.action?.type,n,r,i,a=this.stores.resolvedLocation.get()??this.stores.location.get();for(i=new Promise(o=>{this.startTransition(async()=>{try{this.beforeLoad(),t&&(this._scroll.hash=t===`PUSH`||t===`REPLACE`);let n=this.latestLocation,r=Ht(n,this.stores.resolvedLocation.get());this.stores.redirect.get()||this.emit({type:`onBeforeNavigate`,...r}),this.emit({type:`onBeforeLoad`,...r}),await Dt({router:this,sync:e?.sync,forceStaleReload:a.href===n.href,matches:this.stores.pendingMatches.get(),location:n,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let e=null,t=null,n=null,r=null;this.batch(()=>{let i=this.stores.pendingMatches.get(),a=i.length,o=this.stores.matches.get();e=a?o.filter(e=>!this.stores.pendingMatchStores.has(e.id)):null;let s=new Set;for(let e of this.stores.pendingMatchStores.values())e.routeId&&s.add(e.routeId);let c=new Set;for(let e of this.stores.matchStores.values())e.routeId&&c.add(e.routeId);t=a?o.filter(e=>!s.has(e.routeId)):null,n=a?i.filter(e=>!c.has(e.routeId)):null,r=a?i.filter(e=>c.has(e.routeId)):o,this.stores.isLoading.set(!1),this.stores.loadedAt.set(Date.now()),a&&(this.stores.setMatches(i),this.stores.setPending([]),this.stores.setCached([...this.stores.cachedMatches.get(),...e.filter(e=>e.status!==`error`&&e.status!==`notFound`&&e.status!==`redirected`)]),this.clearExpiredCache())});for(let[e,i]of[[t,`onLeave`],[n,`onEnter`],[r,`onStay`]])if(e)for(let t of e)this.looseRoutesById[t.routeId].options[i]?.(t)})})}})}catch(e){tt(e)?(n=e,this.navigate({...n.options,replace:!0,ignoreBlocker:!0})):je(e)&&(r=e);let t=n?n.status:r?404:this.stores.matches.get().some(e=>e.status===`error`)?500:200;this.batch(()=>{this.stores.statusCode.set(t),this.stores.redirect.set(n)})}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),o()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let o;this.hasNotFoundMatch()?o=404:this.stores.matches.get().some(e=>e.status===`error`)&&(o=500),o!==void 0&&this.stores.statusCode.set(o)},this.startViewTransition=e=>{let t=this.shouldViewTransition??this.options.defaultViewTransition;if(this.shouldViewTransition=void 0,t&&typeof document<`u`&&`startViewTransition`in document&&typeof document.startViewTransition==`function`){let n;if(typeof t==`object`&&this.isViewTransitionTypesSupported){let r=this.latestLocation,i=this.stores.resolvedLocation.get(),a=typeof t.types==`function`?t.types(Ht(r,i)):t.types;if(a===!1){e();return}n={update:e,types:a}}else n=e;document.startViewTransition(n)}else e()},this.updateMatch=(e,t)=>{this.startTransition(()=>{let n=this.stores.pendingMatchStores.get(e);if(n){n.set(t);return}let r=this.stores.matchStores.get(e);if(r){r.set(t);return}let i=this.stores.cachedMatchStores.get(e);if(i){let n=t(i.get());n.status===`redirected`?this.stores.cachedMatchStores.delete(e)&&this.stores.cachedIds.set(t=>t.filter(t=>t!==e)):i.set(n)}})},this.getMatch=e=>this.stores.cachedMatchStores.get(e)?.get()??this.stores.pendingMatchStores.get(e)?.get()??this.stores.matchStores.get(e)?.get(),this.invalidate=e=>{let t=t=>e?.filter?.(t)??!0?{...t,invalid:!0,...e?.forcePending||t.status===`error`||t.status===`notFound`?{status:`pending`,error:void 0}:void 0}:t;return this.batch(()=>{this.stores.setMatches(this.stores.matches.get().map(t)),this.stores.setCached(this.stores.cachedMatches.get().map(t)),this.stores.setPending(this.stores.pendingMatches.get().map(t))}),this.shouldViewTransition=!1,this.load({sync:e?.sync})},this.getParsedLocationHref=e=>e.publicHref||`/`,this.resolveRedirect=e=>{let t=e.headers.get(`Location`);if(!e.options.href||e.options._builtLocation){let t=e.options._builtLocation??this.buildLocation(e.options),n=this.getParsedLocationHref(t);e.options.href=n,e.headers.set(`Location`,n)}else if(t)try{let n=new URL(t);if(this.origin&&n.origin===this.origin){let t=n.pathname+n.search+n.hash;e.options.href=t,e.headers.set(`Location`,t)}}catch{}if(e.options.href&&!e.options._builtLocation&&_e(e.options.href,this.protocolAllowlist))throw Error(`Redirect blocked: unsafe protocol`);return e.headers.get(`Location`)||e.headers.set(`Location`,e.options.href),e},this.clearCache=e=>{let t=e?.filter;t===void 0?this.stores.setCached([]):this.stores.setCached(this.stores.cachedMatches.get().filter(e=>!t(e)))},this.clearExpiredCache=()=>{let e=Date.now();this.clearCache({filter:t=>{let n=this.looseRoutesById[t.routeId];if(!n.options.loader)return!0;let r=(t.preload?n.options.preloadGcTime??this.options.defaultPreloadGcTime:n.options.gcTime??this.options.defaultGcTime)??300*1e3;return t.status===`error`||e-t.updatedAt>=r}})},this.loadRouteChunk=kt,this.preloadRoute=async e=>{let t=e._builtLocation??this.buildLocation(e),n=this.matchRoutes(t,{throwOnError:!0,preload:!0,dest:e}),r=new Set([...this.stores.matchesId.get(),...this.stores.pendingIds.get()]),i=new Set([...r,...this.stores.cachedIds.get()]),a=n.filter(e=>!i.has(e.id));if(a.length){let e=this.stores.cachedMatches.get();this.stores.setCached([...e,...a])}try{return n=await Dt({router:this,matches:n,location:t,preload:!0,updateMatch:(e,t)=>{r.has(e)?n=n.map(n=>n.id===e?t(n):n):this.updateMatch(e,t)}}),n}catch(e){if(tt(e))return e.options.reloadDocument?void 0:await this.preloadRoute({...e.options,_fromLocation:t});je(e)||console.error(e);return}},this.matchRoute=(e,t)=>{let n={...e,to:e.to?this.resolvePathWithBase(e.from||``,e.to):void 0,params:e.params||{},leaveParams:!0},r=this.buildLocation(n);if(t?.pending&&this.stores.status.get()!==`pending`)return!1;let i=(t?.pending===void 0?!this.stores.isLoading.get():t.pending)?this.latestLocation:this.stores.resolvedLocation.get()||this.stores.location.get(),a=y(r.pathname,t?.caseSensitive??!1,t?.fuzzy??!1,i.pathname,this.processedTree);return!a||e.params&&!g(a.rawParams,e.params,{partial:!0})?!1:t?.includeSearch??!0?g(i.search,r.search,{partial:!0})?a.rawParams:!1:a.rawParams},this.hasNotFoundMatch=()=>this.stores.matches.get().some(e=>e.status===`notFound`||e.globalNotFound),this.getStoreConfig=t,this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...e,caseSensitive:e.caseSensitive??!1,notFoundMode:e.notFoundMode??`fuzzy`,stringifySearch:e.stringifySearch??Xe,parseSearch:e.parseSearch??Ye,protocolAllowlist:e.protocolAllowlist??r}),typeof document<`u`&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.stores.__store.get()}setRoutes({routesById:e,routesByPath:t,processedTree:n}){this.routesById=e,this.routesByPath=t,this.processedTree=n;let r=this.options.notFoundRoute;r&&(r.init({originalIndex:99999999999}),this.routesById[r.id]=r)}getRouteBranch(e){let t=this.routeBranchCache.get(e);return t||(t=v(e),this.routeBranchCache.set(e,t)),t}get looseRoutesById(){return this.routesById}getParentContext(e){return e?.id?e.context??this.options.context??void 0:this.options.context??void 0}matchRoutesInternal(e,t){let n=this.getMatchedRoutes(e.pathname),{foundRoute:r,routeParams:i}=n,{matchedRoutes:a}=n,o=!1;(r?r.path!==`/`&&i[`**`]:he(e.pathname))&&(this.options.notFoundRoute?a=[...a,this.options.notFoundRoute]:o=!0);let s=o?Zt(this.options.notFoundMode,a):void 0,c=Array(a.length),l=new Map;for(let e of this.stores.matchStores.values())e.routeId&&l.set(e.routeId,e.get());for(let n=0;nthis.navigate({...t,_fromLocation:e}),buildLocation:this.buildLocation,cause:n.cause,abortController:n.abortController,preload:!!n.preload,matches:c,routeId:r.id};n.__routeContext=r.options.context(t)??void 0}n.context={...a,...n.__routeContext,...n.__beforeLoadContext}}}return c}matchRoutesLightweight(e){let t=u(this.stores.matchesId.get()),n=this.lightweightCache.get(e);if(n&&n[0]===t)return n[1];let{matchedRoutes:r,routeParams:i}=this.getMatchedRoutes(e.pathname),a=u(r),o={...e.search};for(let e of r)try{Object.assign(o,qt(e.options.validateSearch,o))}catch{}let s=t&&this.stores.matchStores.get(t)?.get(),c=s&&s.routeId===a.id&&s.pathname===e.pathname,l;if(c)l=s.params;else{let e=Object.assign(Object.create(null),i);for(let t of r)try{Qt(t,e)}catch{}l=e}let d={matchedRoutes:r,fullPath:a.fullPath,search:o,params:l};return this.lightweightCache.set(e,[t,d]),d}},Wt=class extends Error{},Gt=class extends Error{};function Kt(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:`idle`,resolvedLocation:void 0,location:e,matches:[],statusCode:200}}function qt(e,t){if(e==null)return{};if(`~standard`in e){let n=e[`~standard`].validate(t);if(n instanceof Promise)throw new Wt(`Async validation not supported`);if(n.issues)throw new Wt(JSON.stringify(n.issues,void 0,2),{cause:n});return n.value}return`parse`in e?e.parse(t):typeof e==`function`?e(t):{}}function Jt({pathname:e,routesById:t,processedTree:n}){let r=Object.create(null),i=he(e),a,o=O(i,n,!0);return o&&(a=o.route,Object.assign(r,o.rawParams)),{matchedRoutes:o?.branch||[t.__root__],routeParams:r,foundRoute:a}}function Yt({search:e,dest:t,destRoutes:n,_includeValidateSearch:r}){return Xt(n)(e,t,r??!1)}function Xt(e){let t,n,r=[];for(let t of e){let e=t.options;`search`in e?e.search?.middlewares&&r.push(...e.search.middlewares):(e.preSearchFilters||e.postSearchFilters)&&r.push(({search:t,next:n})=>{let r=n(e.preSearchFilters?e.preSearchFilters.reduce((e,t)=>t(e),t):t);return e.postSearchFilters?e.postSearchFilters.reduce((e,t)=>t(e),r):r});let i=e.validateSearch;i&&r.push(({search:e,next:t,meta:r})=>{let a=t(e);if(n)try{let e=qt(i,a);if(r&&e)for(let t in e)t in a||(r.defaulted||=new Map).set(t,e[t]);return{...a,...e}}catch{}return a})}let i=(e,n,a)=>{if(e>=r.length){if(!t.search)return{};if(t.search===!0)return n;let e=f(t.search,n);return a&&(a.explicit=e),e}return r[e]({search:n,next:(t,n)=>{if(n){let n=a||{};return{search:i(e+1,t,n),meta:n}}return i(e+1,t,a)},meta:a})};return function(e,r,a){return t=r,n=a,i(0,e)}}function Zt(e,t){if(e!==`root`)for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.children)return n.id}return $e}function Qt(e,t){let n=e.options.params?.parse??e.options.parseParams;if(n){let e=n(t);if(e===!1)throw Error(`Route params.parse returned false for a matched route`);Object.assign(t,e)}}var $t=Symbol.for(`TSR_DEFERRED_PROMISE`);function en(e,t){let n=e;return n[$t]?n:(n[$t]={status:`pending`},n.then(e=>{n[$t].status=`success`,n[$t].data=e}).catch(e=>{n[$t].status=`error`,n[$t].error={data:(t?.serializeError??Vt)(e),__isServerError:!0}}),n)}function tn(e,t){if(e)return typeof e==`string`?e:e[t]}function nn(e){return e?.scriptFormat??`module`}function rn(e,t,n){let r=an(t),i=tn(n,`script`)??r.crossOrigin;return{...nn(e)===`iife`?{rel:`preload`,as:`script`}:{rel:`modulepreload`},href:r.href,...i?{crossOrigin:i}:{}}}function an(e){return typeof e==`string`?{href:e,crossOrigin:void 0}:e}function on(e,t){if(t.length===0)return;if(t.length===1){e.push(t[0]);return}let n=new Set;for(let r of t){let t=JSON.stringify(r);n.has(t)||(n.add(t),e.push(r))}}function sn(e){return typeof e==`string`?{href:e,crossOrigin:void 0}:e}var cn=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e.originalIndex;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=$e:this.parentRoute||ce();let r=n?$e:t?.path;r&&r!==`/`&&(r=ee(r));let i=t?.id||r,a=n?$e:C([this.parentRoute.id===`__root__`?``:this.parentRoute.id,i]);r===`__root__`&&(r=`/`),a!==`__root__`&&(a=C([`/`,a]));let o=a===`__root__`?`/`:C([this.parentRoute.fullPath,r]);this._path=r,this._id=a,this._fullPath=o,this._to=he(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>et({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},ln=class extends cn{constructor(e){super(e)}},un=(e=>(e[e.AggregateError=1]=`AggregateError`,e[e.ArrowFunction=2]=`ArrowFunction`,e[e.ErrorPrototypeStack=4]=`ErrorPrototypeStack`,e[e.ObjectAssign=8]=`ObjectAssign`,e[e.BigIntTypedArray=16]=`BigIntTypedArray`,e[e.RegExp=32]=`RegExp`,e))(un||{}),dn=Symbol.asyncIterator,fn=Symbol.hasInstance,pn=Symbol.isConcatSpreadable,mn=Symbol.iterator,hn=Symbol.match,gn=Symbol.matchAll,_n=Symbol.replace,vn=Symbol.search,yn=Symbol.species,bn=Symbol.split,xn=Symbol.toPrimitive,Sn=Symbol.toStringTag,Cn=Symbol.unscopables,wn={[dn]:0,[fn]:1,[pn]:2,[mn]:3,[hn]:4,[gn]:5,[_n]:6,[vn]:7,[yn]:8,[bn]:9,[xn]:10,[Sn]:11,[Cn]:12},Tn={0:dn,1:fn,2:pn,3:mn,4:hn,5:gn,6:_n,7:vn,8:yn,9:bn,10:xn,11:Sn,12:Cn},k=void 0,En={2:!0,3:!1,1:k,0:null,4:-0,5:1/0,6:-1/0,7:NaN},Dn={0:`Error`,1:`EvalError`,2:`RangeError`,3:`ReferenceError`,4:`SyntaxError`,5:`TypeError`,6:`URIError`},On={0:Error,1:EvalError,2:RangeError,3:ReferenceError,4:SyntaxError,5:TypeError,6:URIError};function A(e,t,n,r,i,a,o,s,c,l,u,d){return{t:e,i:t,s:n,c:r,m:i,p:a,e:o,a:s,f:c,b:l,o:u,l:d}}function kn(e){return A(2,k,e,k,k,k,k,k,k,k,k,k)}var An=kn(2),jn=kn(3),Mn=kn(1),Nn=kn(0),Pn=kn(4),Fn=kn(5),In=kn(6),Ln=kn(7);function Rn(e){switch(e){case`"`:return`\\"`;case`\\`:return`\\\\`;case` +`:return`\\n`;case`\r`:return`\\r`;case`\b`:return`\\b`;case` `:return`\\t`;case`\f`:return`\\f`;case`<`:return`\\x3C`;case`\u2028`:return`\\u2028`;case`\u2029`:return`\\u2029`;default:return k}}function zn(e){let t=``,n=0,r;for(let i=0,a=e.length;iTr(e),Dr=class extends Error{constructor(e,t){super(Er(e,t)),this.cause=t}},Or=class extends Dr{constructor(e){super(`parsing`,e)}},kr=class extends Dr{constructor(e){super(`deserialization`,e)}};function Ar(e){return`Seroval Error (specific: ${e})`}var jr=class extends Error{constructor(e){super(Ar(1)),this.value=e}},Mr=class extends Error{constructor(e){super(Ar(2))}},Nr=class extends Error{constructor(e){super(Ar(3))}},Pr=class extends Error{constructor(e){super(Ar(4))}},Fr=class extends Error{constructor(e){super(Ar(5)),this.value=e}},Ir=class extends Error{constructor(e){super(Ar(6))}},Lr=class extends Error{constructor(e){super(Ar(7))}},Rr=class extends Error{constructor(e){super(Ar(8))}},zr=class extends Error{constructor(e){super(Ar(9))}},Br=class{constructor(e,t){this.value=e,this.replacement=t}},Vr=()=>{let e={p:0,s:0,f:0};return e.p=new Promise((t,n)=>{e.s=t,e.f=n}),e};Vr.toString(),((e,t)=>{e.s(t),e.p.s=1,e.p.v=t}).toString(),((e,t)=>{e.f(t),e.p.s=2,e.p.v=t}).toString();var Hr=()=>{let e=[],t=[],n=!0,r=!1,i=0,a=(e,n,r)=>{for(r=0;r{for(i=0,a=e.length;i(n&&(r=i++,t[r]=e),o(e),()=>{n&&(t[r]=t[i],t[i--]=void 0)});return{__SEROVAL_STREAM__:!0,on:e=>s(e),next:t=>{n&&(e.push(t),a(t,`next`))},throw:i=>{n&&(e.push(i),a(i,`throw`),n=!1,r=!1,t.length=0)},return:i=>{n&&(e.push(i),a(i,`return`),n=!1,r=!0,t.length=0)}}};Hr.toString();var Ur=e=>t=>()=>{let n=0,r={[e]:()=>r,next:()=>{if(n>t.d)return{done:!0,value:void 0};let e=n++,r=t.v[e];if(e===t.t)throw r;return{done:e===t.d,value:r}}};return r};Ur.toString();var Wr=(e,t)=>n=>()=>{let r=0,i=-1,a=!1,o=[],s=[],c=(e=0,t=s.length)=>{for(;e{let t=s.shift();t&&t.s({done:!1,value:e}),o.push(e)},throw:e=>{let t=s.shift();t&&t.f(e),c(),i=o.length,a=!0,o.push(e)},return:e=>{let t=s.shift();t&&t.s({done:!0,value:e}),c(),i=o.length,o.push(e)}});let l={[e]:()=>l,next:()=>{if(i===-1){let e=r++;if(e>=o.length){let e=t();return s.push(e),e.p}return{done:!1,value:o[e]}}if(r>i)return{done:!0,value:void 0};let e=r++,n=o[e];if(e!==i)return{done:!1,value:n};if(a)throw n;return{done:!0,value:n}}};return l};Wr.toString();var Gr=e=>{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e{}),t}var ri=Wr(dn,Vr);function ii(e){return ri(e)}async function ai(e){try{return[1,await e]}catch(e){return[0,e]}}function oi(e,t){return{plugins:t.plugins,mode:e,marked:new Set,features:63^(t.disabledFeatures||0),refs:t.refs||new Map,depthLimit:t.depthLimit||1e3}}function si(e,t){e.marked.add(t)}function ci(e,t){let n=e.refs.size;return e.refs.set(t,n),n}function li(e,t){let n=e.refs.get(t);return n==null?{type:0,value:ci(e,t)}:(si(e,n),{type:1,value:nr(n)})}function ui(e,t){let n=li(e,t);return n.type===1?n:Gn(t)?{type:2,value:or(n.value,t)}:n}function di(e,t){let n=ui(e,t);if(n.type!==0)return n.value;if(t in wn)return ar(n.value,t);throw new jr(t)}function fi(e,t){let n=li(e,$r[t]);return n.type===1?n.value:A(26,n.value,t,k,k,k,k,k,k,k,k,k)}function pi(e){let t=li(e,Zr);return t.type===1?t.value:A(27,t.value,k,k,k,k,k,k,di(e,mn),k,k,k)}function mi(e){let t=li(e,Qr);return t.type===1?t.value:A(29,t.value,k,k,k,k,k,[fi(e,1),di(e,dn)],k,k,k,k)}function hi(e,t,n,r){return A(n?11:10,e,k,k,k,r,k,k,k,k,Qn(t),k)}function gi(e,t,n,r){return A(8,t,k,k,k,k,{k:n,v:r},k,fi(e,0),k,k,k)}function _i(e,t,n){let r=new Uint8Array(n),i=``;for(let e=0,t=r.length;e{si(this.base,t),zi(this,e,n).then(e=>{a.push(yr(t,e))},e=>{i(e),o()})},throw:n=>{si(this.base,t),zi(this,e,n).then(e=>{a.push(br(t,e)),r(a),o()},e=>{i(e),o()})},return:n=>{si(this.base,t),zi(this,e,n).then(e=>{a.push(xr(t,e)),r(a),o()},e=>{i(e),o()})}})}async function Fi(e,t,n,r){return vr(n,fi(e.base,4),await new Promise(Pi.bind(e,t,n,r)))}async function Ii(e,t,n,r){let i=[];for(let n=0,a=r.v.length;n=e.base.depthLimit)throw new zr(e.base.depthLimit);switch(typeof n){case`boolean`:return n?An:jn;case`undefined`:return Mn;case`string`:return er(n);case`number`:return $n(n);case`bigint`:return tr(n);case`object`:if(n){let r=ui(e.base,n);return r.type===0?await Li(e,t+1,r.value,n):r.value}return Nn;case`symbol`:return di(e.base,n);case`function`:return Ri(e,t,n);default:throw new jr(n)}}async function Bi(e,t){try{return await zi(e,0,t)}catch(e){throw e instanceof Or?e:new Or(e)}}var Vi=(e=>(e[e.Vanilla=1]=`Vanilla`,e[e.Cross=2]=`Cross`,e))(Vi||{});function j(e){return e}function M(e,t){for(let n=0,r=t.length;n0)for(let a=0,o=n.v,s=i.length;aqi)throw new Rr(t);return P(e,t.i,new RegExp(n,t.m))}throw new Mr(t)}function pa(e,t,n){let r=P(e,n.i,new Set);for(let i=0,a=n.a,o=a.length;iGi)throw new Rr(t);return P(e,t.i,Gr(Vn(t.s)))}function ga(e,t,n){let r=Hi(n.c),i=F(e,t,n.f),a=n.b??0;if(a<0||a>i.byteLength)throw new Rr(n);return P(e,n.i,new r(i,a,n.l))}function _a(e,t,n){let r=F(e,t,n.f),i=n.b??0;if(i<0||i>r.byteLength)throw new Rr(n);return P(e,n.i,new DataView(r,i,n.l))}function va(e,t,n,r){if(n.p){let i=la(e,t,n.p,{});Object.defineProperties(r,Object.getOwnPropertyDescriptors(i))}return r}function ya(e,t,n){return va(e,t,n,P(e,n.i,AggregateError([],Vn(n.m))))}function ba(e,t,n){let r=na(n,On,n.s);return va(e,t,n,P(e,n.i,new r(Vn(n.m))))}function xa(e,t,n){let r=Vr(),i=P(e,n.i,r.p),a=F(e,t,n.f);return n.s?r.s(a):r.f(a),i}function Sa(e,t,n){return P(e,n.i,Object(F(e,t,n.f)))}function Ca(e,t,n){let r=e.base.plugins;if(r){let i=Vn(n.c);for(let a=0,o=r.length;ae.base.depthLimit)throw new zr(e.base.depthLimit);switch(t+=1,n.t){case 2:return na(n,En,n.s);case 0:return Number(n.s);case 1:return Vn(String(n.s));case 3:if(String(n.s).length>Ki)throw new Rr(n);return BigInt(n.s);case 4:return e.base.refs.get(n.i);case 18:return ra(e,n);case 9:return ia(e,t,n);case 10:case 11:return ua(e,t,n);case 5:return da(e,n);case 6:return fa(e,n);case 7:return pa(e,t,n);case 8:return ma(e,t,n);case 19:return ha(e,n);case 16:case 15:return ga(e,t,n);case 20:return _a(e,t,n);case 14:return ya(e,t,n);case 13:return ba(e,t,n);case 12:return xa(e,t,n);case 17:return na(n,Tn,n.s);case 21:return Sa(e,t,n);case 25:return Ca(e,t,n);case 22:return wa(e,n);case 23:return Ta(e,t,n);case 24:return Ea(e,t,n);case 28:return Da(e,t,n);case 30:return Oa(e,t,n);case 31:return ka(e,t,n);case 32:return Aa(e,t,n);case 33:return ja(e,t,n);case 34:return Ma(e,t,n);case 27:return Na(e,t,n);case 29:return Pa(e,t,n);case 35:return Fa(e,t,n);default:throw new Mr(n)}}function Ia(e,t){try{return F(e,0,t)}catch(e){throw new kr(e)}}var La=(()=>T).toString();/=>/.test(La);function Ra(e,t){return Ia(Zi({plugins:N(t.plugins),refs:t.refs,features:t.features,disabledFeatures:t.disabledFeatures,depthLimit:t.depthLimit}),e)}async function za(e,t={}){let n=vi(1,{plugins:N(t.plugins),disabledFeatures:t.disabledFeatures});return{t:await Bi(n,e),f:n.base.features,m:Array.from(n.base.marked)}}function Ba(e){return e}function Va(e){return j({tag:`$TSR/t/`+e.key,test:e.test,parse:{sync(t,n,r){return{v:n.parse(e.toSerializable(t))}},async async(t,n,r){return{v:await n.parse(e.toSerializable(t))}},stream(t,n,r){return{v:n.parse(e.toSerializable(t))}}},serialize:void 0,deserialize(t,n,r){return e.fromSerializable(n.deserialize(t.v))}})}var Ha=class{constructor(e,t){this.stream=e,this.hint=t?.hint??`binary`}},Ua=globalThis.Buffer,Wa=!!Ua&&typeof Ua.from==`function`;function Ga(e){if(e.length===0)return``;if(Wa)return Ua.from(e).toString(`base64`);let t=32768,n=[];for(let r=0;rnew ReadableStream({start(t){e.on({next(e){try{t.enqueue(Ka(e))}catch{}},throw(e){t.error(e)},return(){try{t.close()}catch{}}})}}),Xa=new TextEncoder,Za=e=>new ReadableStream({start(t){e.on({next(e){try{typeof e==`string`?t.enqueue(Xa.encode(e)):t.enqueue(Ka(e.$b64))}catch{}},throw(e){t.error(e)},return(){try{t.close()}catch{}}})}}),Qa=`(s=>new ReadableStream({start(c){s.on({next(b){try{const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i{const e=new TextEncoder();return new ReadableStream({start(c){s.on({next(v){try{if(typeof v==='string'){c.enqueue(e.encode(v))}else{const d=atob(v.$b64),a=new Uint8Array(d.length);for(let i=0;i{try{for(;;){let{done:e,value:r}=await n.read();if(e){t.return(void 0);break}t.next(Ga(r))}}catch(e){t.throw(e)}finally{n.releaseLock()}})(),t}function to(e){let t=ti(),n=e.getReader(),r=new TextDecoder(`utf-8`,{fatal:!0});return(async()=>{try{for(;;){let{done:e,value:i}=await n.read();if(e){try{let e=r.decode();e.length>0&&t.next(e)}catch{}t.return(void 0);break}try{let e=r.decode(i,{stream:!0});e.length>0&&t.next(e)}catch{t.next({$b64:Ga(i)})}}}catch(e){t.throw(e)}finally{n.releaseLock()}})(),t}var no=j({tag:`tss/RawStream`,extends:[j({tag:`tss/RawStreamFactory`,test(e){return e===qa},parse:{sync(e,t,n){return{}},async async(e,t,n){return{}},stream(e,t,n){return{}}},serialize(e,t,n){return Qa},deserialize(e,t,n){return qa}}),j({tag:`tss/RawStreamFactoryText`,test(e){return e===Ja},parse:{sync(e,t,n){return{}},async async(e,t,n){return{}},stream(e,t,n){return{}}},serialize(e,t,n){return $a},deserialize(e,t,n){return Ja}})],test(e){return e instanceof Ha},parse:{sync(e,t,n){let r=e.hint===`text`?Ja:qa;return{hint:t.parse(e.hint),factory:t.parse(r),stream:t.parse(ti())}},async async(e,t,n){let r=e.hint===`text`?Ja:qa,i=e.hint===`text`?to(e.stream):eo(e.stream);return{hint:await t.parse(e.hint),factory:await t.parse(r),stream:await t.parse(i)}},stream(e,t,n){let r=e.hint===`text`?Ja:qa,i=e.hint===`text`?to(e.stream):eo(e.stream);return{hint:t.parse(e.hint),factory:t.parse(r),stream:t.parse(i)}}},serialize(e,t,n){return`(`+t.serialize(e.factory)+`)(`+t.serialize(e.stream)+`)`},deserialize(e,t,n){let r=t.deserialize(e.stream);return t.deserialize(e.hint)===`text`?Za(r):Ya(r)}});function ro(e){return j({tag:`tss/RawStream`,test:()=>!1,parse:{},serialize(){throw Error(`RawStreamDeserializePlugin.serialize should not be called. Client only deserializes.`)},deserialize(t,n,r){return e(typeof n?.deserialize==`function`?n.deserialize(t.streamId):t.streamId)}})}var io=j({tag:`$TSR/Error`,test(e){return e instanceof Error},parse:{sync(e,t){return{message:t.parse(e.message)}},async async(e,t){return{message:await t.parse(e.message)}},stream(e,t){return{message:t.parse(e.message)}}},serialize(e,t){return`new Error(`+t.serialize(e.message)+`)`},deserialize(e,t){return Error(t.deserialize(e.message))}}),ao={},oo=e=>new ReadableStream({start:t=>{e.on({next:e=>{try{t.enqueue(e)}catch{}},throw:e=>{t.error(e)},return:()=>{try{t.close()}catch{}}})}}),so=j({tag:`seroval-plugins/web/ReadableStreamFactory`,test(e){return e===ao},parse:{sync(){return ao},async async(){return await Promise.resolve(ao)},stream(){return ao}},serialize(){return oo.toString()},deserialize(){return ao}});async function co(e,t){try{let n=await t.read();n.done?(e.return(n.value),t.releaseLock()):(e.next(n.value),await co(e,t))}catch(t){e.throw(t)}}function lo(e){e.cancel().catch(()=>{}),e.releaseLock()}function uo(e){let t=ti(),n=e.getReader(),r=lo.bind(null,n);return co(t,n).catch(r),[t,r]}var fo=[io,no,j({tag:`seroval/plugins/web/ReadableStream`,extends:[so],test(e){return typeof ReadableStream>`u`?!1:e instanceof ReadableStream},parse:{sync(e,t){return{factory:t.parse(ao),stream:t.parse(ti())}},async async(e,t){return{factory:await t.parse(ao),stream:await t.parse(uo(e)[0])}},stream(e,t){let[n,r]=uo(e);return t.addCleanup(r),{factory:t.parse(ao),stream:t.parse(n)}}},serialize(e,t){return`(`+t.serialize(e.factory)+`)(`+t.serialize(e.stream)+`)`},deserialize(e,t){return oo(t.deserialize(e.stream))}})];function po(){return[...(Ae()?.serializationAdapters)?.map(Va)??[],...fo]}var mo=new TextDecoder,ho=new Uint8Array,I=16*1024*1024,go=32*1024*1024,_o=1024,L=1e5;function R(e){let t=new Map,n=new Map,r=new Set,i=!1,a=null,o=0,s,c=new ReadableStream({start(e){s=e},cancel(){i=!0;try{a?.cancel()}catch{}t.forEach(e=>{try{e.error(Error(`Framed response cancelled`))}catch{}}),t.clear(),n.clear(),r.clear()}});function l(e){let i=n.get(e);if(i)return i;if(r.has(e))return new ReadableStream({start(e){e.close()}});if(n.size>=_o)throw Error(`Too many raw streams in framed response (max ${_o})`);let a=new ReadableStream({start(n){t.set(e,n)},cancel(){r.add(e),t.delete(e),n.delete(e)}});return n.set(e,a),a}function u(e){return l(e),t.get(e)}return(async()=>{let n=e.getReader();a=n;let c=[],l=0;function d(){if(l<9)return null;let e=c[0];if(e.length>=9)return{type:e[0],streamId:(e[1]<<24|e[2]<<16|e[3]<<8|e[4])>>>0,length:(e[5]<<24|e[6]<<16|e[7]<<8|e[8])>>>0};let t=new Uint8Array(9),n=0,r=9;for(let e=0;e0;e++){let i=c[e],a=Math.min(i.length,r);t.set(i.subarray(0,a),n),n+=a,r-=a}return{type:t[0],streamId:(t[1]<<24|t[2]<<16|t[3]<<8|t[4])>>>0,length:(t[5]<<24|t[6]<<16|t[7]<<8|t[8])>>>0}}function f(e){if(e===0)return ho;let t=c[0];if(t&&t.length>=e){let n=t.subarray(0,e);return t.length===e?c.shift():c[0]=t.subarray(e),l-=e,n}let n=new Uint8Array(e),r=0,i=e;for(;i>0&&c.length>0;){let e=c[0];if(!e)break;let t=Math.min(e.length,i);n.set(e.subarray(0,t),r),r+=t,i-=t,t===e.length?c.shift():c[0]=e.subarray(t)}return l-=e,n}try{for(;;){let{done:e,value:a}=await n.read();if(i||e)break;if(a){if(l+a.length>go)throw Error(`Framed response buffer exceeded ${go} bytes`);for(c.push(a),l+=a.length;;){let e=d();if(!e)break;let{type:n,streamId:i,length:a}=e;if(n!==Ee.JSON&&n!==Ee.CHUNK&&n!==Ee.END&&n!==Ee.ERROR)throw Error(`Unknown frame type: ${n}`);if(n===Ee.JSON){if(i!==0)throw Error(`Invalid JSON frame streamId (expected 0)`)}else if(i===0)throw Error(`Invalid raw frame streamId (expected non-zero)`);if(a>I)throw Error(`Frame payload too large: ${a} bytes (max ${I})`);let c=9+a;if(lL)throw Error(`Too many frames in framed response (max ${L})`);f(9);let p=f(a);switch(n){case Ee.JSON:try{s.enqueue(mo.decode(p))}catch{}break;case Ee.CHUNK:{let e=u(i);e&&e.enqueue(p);break}case Ee.END:{let e=u(i);if(r.add(i),e){try{e.close()}catch{}t.delete(i)}break}case Ee.ERROR:{let e=u(i);if(r.add(i),e){let n=mo.decode(p);e.error(Error(n)),t.delete(i)}break}}}}}if(l!==0)throw Error(`Incomplete frame at end of framed response`);try{s.close()}catch{}t.forEach(e=>{try{e.close()}catch{}}),t.clear()}catch(e){try{s.error(e)}catch{}t.forEach(t=>{try{t.error(e)}catch{}}),t.clear()}finally{try{n.releaseLock()}catch{}a=null}})(),{getOrCreateStream:l,jsonChunks:c}}var z=null;async function vo(e){e.length>0&&await Promise.allSettled(e)}var yo=Object.prototype.hasOwnProperty;function bo(e){for(let t in e)if(yo.call(e,t))return!0;return!1}async function xo(e,t,n){z||=po();let r=t[0],i=r.fetch??n,a=r.data instanceof FormData?`formData`:`payload`,o=r.headers?new Headers(r.headers):new Headers;if(o.set(`x-tsr-serverFn`,`true`),a===`payload`&&o.set(`accept`,`${Te}, application/x-ndjson, application/json`),r.method===`GET`){if(a===`formData`)throw Error(`FormData is not supported with GET requests`);let t=await So(r);if(t!==void 0){let n=Ke({payload:t});e.includes(`?`)?e+=`&${n}`:e+=`?${n}`}}let s;if(r.method===`POST`){let e=await wo(r);e?.contentType&&o.set(`content-type`,e.contentType),s=e?.body}return await B(async()=>i(e,{method:r.method,headers:o,signal:r.signal,body:s}))}async function So(e){let t=!1,n={};if(e.data!==void 0&&(t=!0,n.data=e.data),e.context&&bo(e.context)&&(t=!0,n.context=e.context),t)return Co(n)}async function Co(e){return JSON.stringify(await Promise.resolve(za(e,{plugins:z})))}async function wo(e){if(e.data instanceof FormData){let t;return e.context&&bo(e.context)&&(t=await Co(e.context)),t!==void 0&&e.data.set(Se,t),{body:e.data}}let t=await So(e);if(t)return{body:t,contentType:`application/json`}}async function B(e){let t;try{t=await e()}catch(e){if(e instanceof Response)t=e;else throw console.log(e),e}if(t.headers.get(`x-tss-raw`)===`true`)return t;let n=t.headers.get(`content-type`);if(n||ce(),t.headers.get(`x-tss-serialized`)){let e;if(n.includes(`application/x-tss-framed`)){if(ke(n),!t.body)throw Error(`No response body for framed response`);let{getOrCreateStream:r,jsonChunks:i}=R(t.body),a=[ro(r),...z||[]],o=new Map;e=await To({jsonStream:i,onMessage:e=>Ra(e,{refs:o,plugins:a}),onError(e,t){console.error(e,t)}})}else if(n.includes(`application/json`)){let n=await t.json(),r=[];try{e=Ra(n,{plugins:z})}finally{}await vo(r)}if(e||ce(),e instanceof Error)throw e;return e}if(n.includes(`application/json`)){let e=await t.json(),n=nt(e);if(n)throw n;if(je(e))throw e;return e}if(!t.ok)throw Error(await t.text());return t}async function To({jsonStream:e,onMessage:t,onError:n}){let r=e.getReader(),{value:i,done:a}=await r.read();if(a||!i)throw Error(`Stream ended before first object`);let o=JSON.parse(i),s=!1,c=(async()=>{try{for(;;){let{value:e,done:i}=await r.read();if(i)break;if(e)try{let n=[];try{t(JSON.parse(e))}finally{}await vo(n)}catch(t){n?.(`Invalid JSON: ${e}`,t)}}}catch(e){s||n?.(`Stream processing error:`,e)}})(),l,u=[];try{l=t(o)}catch(e){throw s=!0,r.cancel().catch(()=>{}),e}return await vo(u),Promise.resolve(l).catch(()=>{s=!0,r.cancel().catch(()=>{})}),c.finally(()=>{try{r.releaseLock()}catch{}}),l}function Eo(e){let t=`/_serverFn/`+e;return Object.assign((...e)=>{let n=Ae()?.serverFns?.fetch;return xo(t,e,n??fetch)},{url:t,serverFnMeta:{id:e},[Ce]:!0})}var Do=Ba({key:`$TSS/serverfn`,test:e=>typeof e!=`function`||!(Ce in e)?!1:!!e[Ce],toSerializable:({serverFnMeta:e})=>({functionId:e.id}),fromSerializable:({functionId:e})=>Eo(e)});function Oo(e){return e.replaceAll(`\0`,`/`).replaceAll(`�`,`/`)}function ko(e,t){e.id=t.i,e.__beforeLoadContext=t.b,e.loaderData=t.l,e.status=t.s,e.ssr=t.ssr,e.updatedAt=t.u,e.error=t.e,t.g!==void 0&&(e.globalNotFound=t.g)}async function Ao(e){window.$_TSR||ce();let t=e.options.serializationAdapters;if(t?.length){let e=new Map;t.forEach(t=>{e.set(t.key,t.fromSerializable)}),window.$_TSR.t=e,window.$_TSR.buffer.forEach(e=>e())}window.$_TSR.initialized=!0,window.$_TSR.router||ce();let n=window.$_TSR.router;n.matches.forEach(e=>{e.i=Oo(e.i)}),n.lastMatchId&&=Oo(n.lastMatchId);let{manifest:r,dehydratedData:i,lastMatchId:a}=n;e.ssr={manifest:r};let o=document.querySelector(`meta[property="csp-nonce"]`)?.content;e.options.ssr={nonce:o},await e.options.hydrate?.(i);let s=e.matchRoutes(e.stores.location.get()),c=Promise.all(s.map(t=>e.loadRouteChunk(e.looseRoutesById[t.routeId])));function l(t){let n=e.looseRoutesById[t.routeId].options.pendingMinMs??e.options.defaultPendingMinMs;if(n){let r=p();t._nonReactive.minPendingPromise=r,t._forcePending=!0,setTimeout(()=>{r.resolve(),e.updateMatch(t.id,e=>(e._nonReactive.minPendingPromise=void 0,{...e,_forcePending:void 0}))},n)}}function u(t){let n=e.looseRoutesById[t.routeId];n&&(n.options.ssr=t.ssr)}let d;s.forEach(e=>{let t=n.matches.find(t=>t.i===e.id);if(!t){e._nonReactive.dehydrated=!1,e.ssr=!1,u(e);return}ko(e,t),u(e),e._nonReactive.dehydrated=e.ssr!==!1,(e.ssr===`data-only`||e.ssr===!1)&&d===void 0&&(d=e.index,l(e))}),e.stores.setMatches(s);let f=e.stores.matches.get(),m=e.stores.location.get();await Promise.all(f.map(async t=>{try{let n=e.looseRoutesById[t.routeId],r=f[t.index-1]?.context??e.options.context;if(n.options.context){let i={deps:t.loaderDeps,params:t.params,context:r??{},location:m,navigate:t=>e.navigate({...t,_fromLocation:m}),buildLocation:e.buildLocation,cause:t.cause,abortController:t.abortController,preload:!1,matches:s,routeId:n.id};t.__routeContext=n.options.context(i)??void 0}t.context={...r,...t.__routeContext,...t.__beforeLoadContext};let i={ssr:e.options.ssr,matches:f,match:t,params:t.params,loaderData:t.loaderData},a=await n.options.head?.(i),o=await n.options.scripts?.(i);t.meta=a?.meta,t.links=a?.links,t.headScripts=a?.scripts,t.styles=a?.styles,t.scripts=o}catch(e){if(je(e))t.error={isNotFound:!0},console.error(`NotFound error during hydration for routeId: ${t.routeId}`,e);else throw t.error=e,console.error(`Error during hydration for route ${t.routeId}:`,e),e}}));let h=s[s.length-1].id!==a;if(!s.some(e=>e.ssr===!1)&&!h)return s.forEach(e=>{e._nonReactive.dehydrated=void 0}),e.stores.resolvedLocation.set(e.stores.location.get()),c;let g=Promise.resolve().then(()=>e.load()).catch(e=>{console.error(`Error during router hydration:`,e)});if(h){let t=s[1];t||ce(),l(t),t._displayPending=!0,t._nonReactive.displayPendingPromise=g,g.then(()=>{e.batch(()=>{e.stores.status.get()===`pending`&&(e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())),e.updateMatch(t.id,e=>({...e,_displayPending:void 0,displayPendingPromise:void 0}))})})}return c}var V=e(n(),1),H=pe();function jo({promise:e}){if(ne)return ne(e);let t=en(e);if(t[$t].status===`pending`)throw t;if(t[$t].status===`error`)throw t[$t].error;return t[$t].data}function Mo(e){let t=(0,H.jsx)(No,{...e});return e.fallback?(0,H.jsx)(V.Suspense,{fallback:e.fallback,children:t}):t}function No(e){let t=jo(e);return e.children(t)}function Po(e){let t=e.errorComponent??Io;return(0,H.jsx)(Fo,{getResetKey:e.getResetKey,onCatch:e.onCatch,children:({error:n,reset:r})=>n?V.createElement(t,{error:n,reset:r}):e.children})}var Fo=class extends V.Component{constructor(...e){super(...e),this.state={error:null}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:null}:{resetKey:n}}static getDerivedStateFromError(e){return{error:e}}reset(){this.setState({error:null})}componentDidCatch(e,t){this.props.onCatch&&this.props.onCatch(e,t)}render(){return this.props.children({error:this.state.error,reset:()=>{this.reset()}})}};function Io({error:e}){let[t,n]=V.useState(!1);return(0,H.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,H.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,H.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,H.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,H.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,H.jsx)(`div`,{children:(0,H.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e.message?(0,H.jsx)(`code`,{children:e.message}):null})}):null]})}var Lo=V.createContext(void 0),Ro=V.createContext(void 0),U=(e=>(e[e.None=0]=`None`,e[e.Mutable=1]=`Mutable`,e[e.Watching=2]=`Watching`,e[e.RecursedCheck=4]=`RecursedCheck`,e[e.Recursed=8]=`Recursed`,e[e.Dirty=16]=`Dirty`,e[e.Pending=32]=`Pending`,e))(U||{});function zo({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(!0)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(!0)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function Bo(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var Vo=[],Ho=0,{link:Uo,unlink:Wo,propagate:Go,checkDirty:Ko,shallowPropagate:qo}=zo({update(e){return e._update()},notify(e){Vo[Yo++]=e,e.flags&=~U.Watching},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=U.Mutable|U.Dirty,$o(e))}}),Jo=0,Yo=0,Xo,Zo=0;function Qo(e){try{++Zo,e()}finally{--Zo||es()}}function $o(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Wo(n,e)}function es(){if(!(Zo>0)){for(;Jo{i.get(),n.current?t.next?.(i._snapshot):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=Xo,o=t?.compare??Object.is;if(n)Xo=i,++Ho,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=U.Mutable|U.RecursedCheck);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{Xo=a,n&&(i.flags&=~U.RecursedCheck),$o(i)}}};return n?(i.flags=U.Mutable|U.Dirty,i.get=function(){let e=i.flags;if(e&U.Dirty||e&U.Pending&&Ko(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&qo(e)}}else e&U.Pending&&(i.flags=e&~U.Pending);return Xo!==void 0&&Uo(i,Xo,Ho),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Go(e),qo(e),es())}},i}function ns(e){let t=()=>{let t=Xo;Xo=n,++Ho,n.depsTail=void 0,n.flags=U.Watching|U.RecursedCheck;try{return e()}finally{Xo=t,n.flags&=~U.RecursedCheck,$o(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:U.Watching|U.RecursedCheck,notify(){let e=this.flags;e&U.Dirty||e&U.Pending&&Ko(this.deps,this)?t():this.flags=U.Watching},stop(){this.flags=U.None,this.depsTail=void 0,$o(this)}};return t(),n}var rs={get(){},subscribe(){return{unsubscribe(){}}}};function is(e,t){let n=V.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=S(n.current,i):i}}function as(e){let t=ue(),n=V.useContext(e.from?Ro:Lo),r=e.from?t.stores.getRouteMatchStore(e.from):t.stores.matchStores.get(n),i=is(e,t),a=w(r??rs,e=>e?i(e):rs);if(a!==rs)return a;(e.shouldThrow??!0)&&ce()}function os(e){return as({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function ss(e){let{select:t,...n}=e;return as({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function cs(e){return as({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function ls(e){return as({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function us(e){let t=ue();return V.useCallback(n=>t.navigate({...n,from:n.from??e?.from}),[e?.from,t])}function ds(e){let t=ue(),n=us(),r=V.useRef(null);return re(()=>{r.current!==e&&(n(e),r.current=e)},[t,e,n]),null}function fs(e){return as({...e,select:t=>e.select?e.select(t.context):t.context})}var ps=class extends cn{constructor(e){super(e),this.useMatch=e=>as({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>fs({...e,from:this.id}),this.useSearch=e=>ls({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>cs({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>ss({...e,from:this.id}),this.useLoaderData=e=>os({...e,from:this.id}),this.useNavigate=()=>us({from:this.fullPath}),this.Link=V.forwardRef((e,t)=>(0,H.jsx)(oe,{ref:t,from:this.fullPath,...e}))}};function ms(e){return new ps(e)}var hs=class extends ln{constructor(e){super(e),this.useMatch=e=>as({select:e?.select,from:this.id,structuralSharing:e?.structuralSharing}),this.useRouteContext=e=>fs({...e,from:this.id}),this.useSearch=e=>ls({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useParams=e=>cs({select:e?.select,structuralSharing:e?.structuralSharing,from:this.id}),this.useLoaderDeps=e=>ss({...e,from:this.id}),this.useLoaderData=e=>os({...e,from:this.id}),this.useNavigate=()=>us({from:this.fullPath}),this.Link=V.forwardRef((e,t)=>(0,H.jsx)(oe,{ref:t,from:this.fullPath,...e}))}};function gs(e){return new hs(e)}function _s(e){return new vs(e,{silent:!0}).createRoute}var vs=class{constructor(e,t){this.path=e,this.createRoute=e=>{let t=ms(e);return t.isRoot=!1,t},this.silent=t?.silent}};function ys(e,t){let n,r,a,o,s=()=>(n||=e().then(e=>{n=void 0,r=e[t??`default`]}).catch(e=>{if(a=e,i(a)&&a instanceof Error&&typeof window<`u`&&typeof sessionStorage<`u`){let e=`tanstack_router_reload:${a.message}`;sessionStorage.getItem(e)||(sessionStorage.setItem(e,`1`),o=!0)}}),n),c=function(e){if(o)throw window.location.reload(),new Promise(()=>{});if(a)throw a;if(!r)if(ne)ne(s());else throw s();return V.createElement(r,e)};return c.preload=s,c}function bs(e){let t=ue(),n=`not-found-${w(t.stores.location,e=>e.pathname)}-${w(t.stores.status,e=>e)}`;return(0,H.jsx)(Po,{getResetKey:()=>n,onCatch:(t,n)=>{if(je(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(je(t))return e.fallback?.(t);throw t},children:e.children})}function xs(){return(0,H.jsx)(`p`,{children:`Not Found`})}function Ss(e){return(0,H.jsx)(H.Fragment,{children:e.children})}function Cs(e,t,n){return t.options.notFoundComponent?(0,H.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,H.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,H.jsx)(xs,{})}var ws=(e,t)=>e.routeId===t.routeId&&e._displayPending===t._displayPending,Ts=(e,t)=>e[0]===t[0]&&e[1]===t[1],Es=V.memo(function({matchId:e}){let t=ue(),n=t.stores.matchStores.get(e);n||ce();let r=w(t.stores.loadedAt,e=>e),i=w(n,e=>e,ws);return(0,H.jsx)(Ds,{router:t,matchId:e,resetKey:r,matchState:V.useMemo(()=>{let e=i.routeId,n=t.routesById[e].parentRoute?.id;return{routeId:e,ssr:i.ssr,_displayPending:i._displayPending,parentRouteId:n}},[i._displayPending,i.routeId,i.ssr,t.routesById])})});function Ds({router:e,matchId:t,resetKey:n,matchState:r}){let i=e.routesById[r.routeId],a=i.options.pendingComponent??e.options.defaultPendingComponent,o=a?(0,H.jsx)(a,{}):null,s=i.options.errorComponent??e.options.defaultErrorComponent,c=i.options.onCatch??e.options.defaultOnCatch,l=i.isRoot?i.options.notFoundComponent??e.options.notFoundRoute?.options.component:i.options.notFoundComponent,u=r.ssr===!1||r.ssr===`data-only`,d=(!i.isRoot||i.options.wrapInSuspense||u)&&(i.options.wrapInSuspense??a??(i.options.errorComponent?.preload||u))?V.Suspense:Ss,f=s?Po:Ss,p=l?bs:Ss;return(0,H.jsxs)(i.isRoot?i.options.shellComponent??Ss:Ss,{children:[(0,H.jsx)(Lo.Provider,{value:t,children:(0,H.jsx)(d,{fallback:o,children:(0,H.jsx)(f,{getResetKey:()=>n,errorComponent:s||Io,onCatch:(e,t)=>{if(je(e))throw e.routeId??=r.routeId,e;c?.(e,t)},children:(0,H.jsx)(p,{fallback:e=>{if(e.routeId??=r.routeId,!l||e.routeId&&e.routeId!==r.routeId||!e.routeId&&!i.isRoot)throw e;return V.createElement(l,e)},children:u||r._displayPending?(0,H.jsx)(te,{fallback:o,children:(0,H.jsx)(ks,{matchId:t})}):(0,H.jsx)(ks,{matchId:t})})})})}),r.parentRouteId===`__root__`?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Os,{}),(e.options.scrollRestoration,null)]}):null]})}function Os(){let e=ue(),t=V.useRef();return re(()=>{let n=e.stores.resolvedLocation.get(),r=t.current;n&&(!r||r.href!==n.href)&&e.emit({type:`onRendered`,...Ht(e.stores.location.get(),r??n)}),t.current=n},[w(e.stores.resolvedLocation,e=>e?.state.__TSR_key),e]),null}var ks=V.memo(function({matchId:e}){let t=ue(),n=(e,n)=>t.getMatch(e.id)?._nonReactive[n]??e._nonReactive[n],r=t.stores.matchStores.get(e);r||ce();let i=w(r,e=>e),a=i.routeId,o=t.routesById[a],s=V.useMemo(()=>{let e=(t.routesById[a].options.remountDeps??t.options.defaultRemountDeps)?.({routeId:a,loaderDeps:i.loaderDeps,params:i._strictParams,search:i._strictSearch});return e?JSON.stringify(e):void 0},[a,i.loaderDeps,i._strictParams,i._strictSearch,t.options.defaultRemountDeps,t.routesById]),c=V.useMemo(()=>{let e=o.options.component??t.options.defaultComponent;return e?(0,H.jsx)(e,{},s):(0,H.jsx)(As,{})},[s,o.options.component,t.options.defaultComponent]);if(i._displayPending)throw n(i,`displayPendingPromise`);if(i._forcePending)throw n(i,`minPendingPromise`);if(i.status===`pending`){let e=o.options.pendingMinMs??t.options.defaultPendingMinMs;if(e){let n=t.getMatch(i.id);if(n&&!n._nonReactive.minPendingPromise){let t=p();n._nonReactive.minPendingPromise=t,setTimeout(()=>{t.resolve(),n._nonReactive.minPendingPromise=void 0},e)}}throw n(i,`loadPromise`)}if(i.status===`notFound`)return je(i.error)||ce(),Cs(t,o,i.error);if(i.status===`redirected`)throw tt(i.error)||ce(),n(i,`loadPromise`);if(i.status===`error`)throw i.error;return c}),As=V.memo(function(){let e=ue(),t=V.useContext(Lo),n,r=!1,i;{let a=t?e.stores.matchStores.get(t):void 0;[n,r]=w(a,e=>[e?.routeId,e?.globalNotFound??!1],Ts),i=w(e.stores.matchesId,e=>e[e.findIndex(e=>e===t)+1])}let a=n?e.routesById[n]:void 0,o=e.options.defaultPendingComponent?(0,H.jsx)(e.options.defaultPendingComponent,{}):null;if(r)return a||ce(),Cs(e,a,void 0);if(!i)return null;let s=(0,H.jsx)(Es,{matchId:i});return n===`__root__`?(0,H.jsx)(V.Suspense,{fallback:o,children:s}):s});function js(){let e=ue(),t=V.useRef({router:e,mounted:!1}),[n,r]=V.useState(!1),i=w(e.stores.isLoading,e=>e),a=w(e.stores.hasPending,e=>e),o=de(i),s=i||n||a,c=de(s),l=i||a,u=de(l);return e.startTransition=e=>{r(!0),V.startTransition(()=>{e(),r(!1)})},V.useEffect(()=>{let t=e.history.subscribe(e.load),n=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return he(e.latestLocation.publicHref)!==he(n.publicHref)&&e.commitLocation({...n,replace:!0}),()=>{t()}},[e,e.history]),re(()=>{typeof window<`u`&&e.ssr||t.current.router===e&&t.current.mounted||(t.current={router:e,mounted:!0},(async()=>{try{await e.load()}catch(e){console.error(e)}})())},[e]),re(()=>{o&&!i&&e.emit({type:`onLoad`,...Ht(e.stores.location.get(),e.stores.resolvedLocation.get())})},[o,e,i]),re(()=>{u&&!l&&e.emit({type:`onBeforeRouteMount`,...Ht(e.stores.location.get(),e.stores.resolvedLocation.get())})},[l,u,e]),re(()=>{if(c&&!s){let t=Ht(e.stores.location.get(),e.stores.resolvedLocation.get());e.emit({type:`onResolved`,...t}),Qo(()=>{e.stores.status.set(`idle`),e.stores.resolvedLocation.set(e.stores.location.get())})}},[s,c,e]),null}function Ms(){let e=ue(),t=e.routesById.__root__.options.pendingComponent??e.options.defaultPendingComponent,n=t?(0,H.jsx)(t,{}):null,r=(0,H.jsxs)(typeof document<`u`&&e.ssr?Ss:V.Suspense,{fallback:n,children:[(0,H.jsx)(js,{}),(0,H.jsx)(Ns,{})]});return e.options.InnerWrap?(0,H.jsx)(e.options.InnerWrap,{children:r}):r}function Ns(){let e=ue(),t=w(e.stores.firstId,e=>e),n=w(e.stores.loadedAt,e=>e),r=t?(0,H.jsx)(Es,{matchId:t}):null;return(0,H.jsx)(Lo.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:(0,H.jsx)(Po,{getResetKey:()=>n,errorComponent:Io,onCatch:void 0,children:r})})}var Ps=e=>({createMutableStore:ts,createReadonlyStore:ts,batch:Qo}),Fs=e=>new Is(e),Is=class extends Ut{constructor(e){super(e,Ps)}};function Ls({router:e,children:t,...n}){_(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,H.jsx)(fe.Provider,{value:e,children:t});return e.options.Wrap?(0,H.jsx)(e.options.Wrap,{children:r}):r}function Rs({router:e,...t}){return(0,H.jsx)(Ls,{router:e,...t,children:(0,H.jsx)(Ms,{})})}function zs(e,t){if(t)for(let[n,r]of Object.entries(t))n!==`suppressHydrationWarning`&&r!==void 0&&r!==!1&&e.setAttribute(n,typeof r==`boolean`?``:String(r))}function Bs(e){let{attrs:t,children:n,nonce:r,preventScriptHoist:i}=e;switch(e.tag){case`title`:return(0,H.jsx)(`title`,{...t,suppressHydrationWarning:!0,children:n});case`meta`:return(0,H.jsx)(`meta`,{...t,suppressHydrationWarning:!0});case`link`:return(0,H.jsx)(`link`,{...t,precedence:t?.precedence??(t?.rel===`stylesheet`?`default`:void 0),nonce:r,suppressHydrationWarning:!0});case`style`:return e.inlineCss,(0,H.jsx)(`style`,{...t,dangerouslySetInnerHTML:{__html:n},nonce:r});case`script`:return(0,H.jsx)(Vs,{attrs:t,preventScriptHoist:i,children:n});default:return null}}function Vs({attrs:e,children:t,preventScriptHoist:n}){ue();let r=le(),i=typeof e?.type==`string`&&e.type!==``&&e.type!==`text/javascript`&&e.type!==`module`;if(V.useEffect(()=>{if(!i){if(e?.src){let t=(()=>{try{let t=document.baseURI||window.location.href;return new URL(e.src,t).href}catch{return e.src}})();for(let e of document.querySelectorAll(`script[src]`))if(e.src===t)return;let n=document.createElement(`script`);return zs(n,e),document.head.appendChild(n),()=>n.remove()}if(typeof t==`string`){let n=typeof e?.type==`string`?e.type:`text/javascript`,r=typeof e?.nonce==`string`?e.nonce:void 0;for(let e of document.querySelectorAll(`script:not([src])`)){if(!(e instanceof HTMLScriptElement))continue;let i=e.getAttribute(`type`)??`text/javascript`,a=e.getAttribute(`nonce`)??void 0;if(e.textContent===t&&i===n&&a===r)return}let i=document.createElement(`script`);return i.textContent=t,zs(i,e),document.head.appendChild(i),()=>i.remove()}}},[e,t,i]),i&&typeof t==`string`)return(0,H.jsx)(`script`,{...e,suppressHydrationWarning:!0,dangerouslySetInnerHTML:{__html:t}});if(!r){if(e?.src)return(0,H.jsx)(`script`,{...e,suppressHydrationWarning:!0});if(typeof t==`string`)return(0,H.jsx)(`script`,{...e,dangerouslySetInnerHTML:{__html:t},suppressHydrationWarning:!0})}return null}var Hs=e=>{let t=ue(),n=t.options.ssr?.nonce,r=w(t.stores.matches,e=>e.map(e=>e.meta).filter(e=>e!==void 0),g),i=V.useMemo(()=>{let e=[],t={},i;for(let a=r.length-1;a>=0;a--){let o=r[a];for(let r=o.length-1;r>=0;r--){let a=o[r];if(a)if(a.title)i||={tag:`title`,children:a.title};else if(`script:ld+json`in a)try{let t=JSON.stringify(a[`script:ld+json`]);e.push({tag:`script`,attrs:{type:`application/ld+json`},children:d(t)})}catch{}else{let r=a.name??a.property;if(r){if(t[r])continue;t[r]=!0}e.push({tag:`meta`,attrs:{...a,nonce:n}})}}}return i&&e.push(i),n&&e.push({tag:`meta`,attrs:{property:`csp-nonce`,content:n}}),e.reverse(),e},[r,n]),a=w(t.stores.matches,e=>e.flatMap(e=>e.links??[]).filter(e=>e!==void 0).map(e=>({tag:`link`,attrs:{...e,nonce:n}})),g),o=w(t.stores.matches,r=>{let i=t.ssr?.manifest,a=[];return i?(r.forEach(t=>{i.routes[t.routeId]?.css?.forEach(t=>{let r=sn(t);a.push({tag:`link`,attrs:{rel:`stylesheet`,...r,crossOrigin:tn(e,`stylesheet`)??r.crossOrigin,suppressHydrationWarning:!0,nonce:n}})})}),i.inlineStyle&&a.push({tag:`style`,attrs:{...i.inlineStyle.attrs,nonce:n},children:i.inlineStyle.children,inlineCss:!0}),a):a},g),s=w(t.stores.matches,r=>{let i=[],a=t.ssr?.manifest;return a&&r.forEach(t=>{a.routes[t.routeId]?.preloads?.forEach(t=>{i.push({tag:`link`,attrs:{...rn(a,t,e),nonce:n}})})}),i},g),c=w(t.stores.matches,e=>e.flatMap(e=>e.styles??[]).filter(e=>e!==void 0).map(({children:e,...t})=>({tag:`style`,attrs:{...t,nonce:n},children:e})),g),l=w(t.stores.matches,e=>e.flatMap(e=>e.headScripts??[]).filter(e=>e!==void 0).map(({children:e,...t})=>({tag:`script`,attrs:{...t,nonce:n},children:e})),g),u=[];return on(u,i),u.push(...s),on(u,a),u.push(...o),on(u,c),on(u,l),u};function Us(e){let t=Hs(e.assetCrossOrigin),n=ue().options.ssr?.nonce;return(0,H.jsx)(H.Fragment,{children:t.map(e=>(0,V.createElement)(Bs,{...e,key:`tsr-meta-${JSON.stringify(e)}`,nonce:n}))})}var Ws=()=>{let e=ue(),t=e.options.ssr?.nonce,n=n=>{let r=[],i=e.ssr?.manifest;if(!i)return[];for(let e of n){let n=i.routes[e.routeId]?.scripts;if(n)for(let e of n)r.push({tag:`script`,attrs:{...e.attrs,nonce:t},children:e.children,...typeof e.attrs?.src==`string`?{preventScriptHoist:!0}:{}})}return r},r=e=>e.map(e=>e.scripts).flat(1).filter(Boolean).map(({children:e,...n})=>({tag:`script`,attrs:{...n,suppressHydrationWarning:!0,nonce:t},children:e})),i=w(e.stores.matches,n,g);return Gs(e,w(e.stores.matches,r,g),i)};function Gs(e,t,n){let r=[...t,...n];return(0,H.jsx)(H.Fragment,{children:r.map((e,t)=>(0,V.createElement)(Bs,{...e,key:`tsr-scripts-${e.tag}-${t}`}))})}function Ks({children:e}){return(0,H.jsx)(H.Fragment,{children:e})}var qs=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},Js=(e=>e?qs(e):qs),Ys=e=>e;function Xs(e,t=Ys){let n=V.useSyncExternalStore(e.subscribe,V.useCallback(()=>t(e.getState()),[e,t]),V.useCallback(()=>t(e.getInitialState()),[e,t]));return V.useDebugValue(n),n}var Zs=e=>{let t=Js(e),n=e=>Xs(t,e);return Object.assign(n,t),n},Qs=(e=>e?Zs(e):Zs);function $s(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var ec=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return ec(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return ec(t)(e)}}}},tc=(e,t)=>(n,r,i)=>{let a={storage:$s(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,l=new Set,u=a.storage;if(!u)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let d=()=>{let e=a.partialize({...r()});return u.setItem(a.name,{state:e,version:a.version})},f=i.setState;i.setState=(e,t)=>(f(e,t),d());let p=e((...e)=>(n(...e),d()),r,i);i.getInitialState=()=>p;let m,h=()=>{if(!u)return;let e=++s;o=!1,c.forEach(e=>e(r()??p));let t=a.onRehydrateStorage?.call(a,r()??p)||void 0;return ec(u.getItem.bind(u))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(m=a.merge(o,r()??p),n(m,!0),i)return d()}).then(()=>{e===s&&(t?.(r(),void 0),m=r(),o=!0,l.forEach(e=>e(m)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(u=e.storage)},clearStorage:()=>{u?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>h(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(l.add(e),()=>{l.delete(e)})},a.skipHydration||h(),m||p};function nc(...e){return e.map(e=>({id:D(`b`),type:e.type,content:e.content??``,checked:e.checked,collapsed:e.collapsed,indent:e.indent??0,showSource:e.showSource,aiOutput:e.aiOutput}))}function rc(e){let t=Date.now();return{id:D(`page`),title:``,icon:`📄`,cover:null,parentId:null,favorite:!1,createdAt:t,updatedAt:t,blocks:nc({type:`paragraph`,content:``}),archived:!1,...e}}function ic(){let e=rc({title:`Getting Started`,icon:`🚀`,cover:`warm`,favorite:!0,blocks:nc({type:`paragraph`,content:`Welcome to ForgeNotes — notes, AI assist, Mermaid diagrams, and optional database sync.`},{type:`heading1`,content:`What you can do`},{type:`bullet`,content:`Create pages from the sidebar`},{type:`bullet`,content:`Type / for block types — try AI and Mermaid`},{type:`bullet`,content:`Hover a block → ⋮⋮ menu → Edit with AI`},{type:`bullet`,content:`Sign in to sync pages to the database`},{type:`bullet`,content:`Search with ⌘K / Ctrl+K`},{type:`heading2`,content:`Try AI`},{type:`ai`,content:`Summarize this page as three bullets for a new teammate`},{type:`heading2`,content:`Mermaid`},{type:`mermaid`,content:`flowchart LR + Write[Write notes] --> AI[AI block] + AI --> Diagram[Mermaid] + Diagram --> Ship[Ship]`,showSource:!1},{type:`heading2`,content:`Basics`},{type:`todo`,content:`Rename this page title`,checked:!1},{type:`todo`,content:`Run the AI block above`,checked:!1},{type:`todo`,content:`Toggle Mermaid source / preview`,checked:!0},{type:`callout`,content:`Tip: slash /ai or /mermaid. AI uses Grok when XAI_API_KEY is set; otherwise a local demo mode.`},{type:`quote`,content:`Write first. Organize later.`},{type:`code`,content:`function hello() { + console.log("hello workspace"); +}`},{type:`divider`,content:``},{type:`paragraph`,content:`This starter page is yours — edit freely or start a blank page.`})}),t=rc({title:`Product Spec`,icon:`📋`,parentId:e.id,blocks:nc({type:`heading1`,content:`Overview`},{type:`paragraph`,content:`A lightweight personal knowledge base with nested pages, AI, and diagrams.`},{type:`heading2`,content:`Goals`},{type:`numbered`,content:`Capture ideas without friction`},{type:`numbered`,content:`Structure docs with nested pages`},{type:`numbered`,content:`Use AI for summaries and checklists`},{type:`heading2`,content:`Non-goals`},{type:`bullet`,content:`Real-time multiplayer (for now)`},{type:`bullet`,content:`Full offline multi-device without sign-in`},{type:`mermaid`,content:`sequenceDiagram + participant U as User + participant A as App + participant D as Database + U->>A: Edit page + A->>D: Save (when signed in)`,showSource:!1})}),n=rc({title:`Weekly Notes`,icon:`📅`,favorite:!0,cover:`cool`,blocks:nc({type:`heading1`,content:`This week`},{type:`todo`,content:`Ship the block editor`,checked:!0},{type:`todo`,content:`Add AI + Mermaid`,checked:!0},{type:`todo`,content:`Write release notes`,checked:!1},{type:`heading2`,content:`Notes`},{type:`paragraph`,content:`Keep daily fragments here. Promote anything durable into its own page.`},{type:`ai`,content:`Turn the todos and notes above into a short status update for stakeholders`},{type:`callout`,content:`Use favorites for the 2–3 pages you open every day.`})});return{pages:[e,t,n,rc({title:`Reading List`,icon:`📚`,blocks:nc({type:`heading2`,content:`Queue`},{type:`todo`,content:`Atomic Habits — James Clear`,checked:!1},{type:`todo`,content:`The Design of Everyday Things`,checked:!1},{type:`todo`,content:`Staff Engineer — Will Larson`,checked:!0},{type:`heading2`,content:`Quotes`},{type:`quote`,content:`Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away.`})}),rc({title:`Meeting Notes`,icon:`🗒`,parentId:n.id,blocks:nc({type:`heading1`,content:`Kickoff`},{type:`paragraph`,content:`Attendees: design, eng, product`},{type:`bullet`,content:`Align on v1 scope`},{type:`bullet`,content:`Decide on editor primitives`},{type:`bullet`,content:`Ship a polished demo`},{type:`divider`,content:``},{type:`heading3`,content:`Action items`},{type:`todo`,content:`Draft IA for sidebar`,checked:!0},{type:`todo`,content:`Prototype slash menu`,checked:!0},{type:`todo`,content:`Add AI edit-with-block`,checked:!0})})],activePageId:e.id}}var ac=`📄.📝.📋.📚.💡.🎯.🚀.⭐.🏠.📁.🗂.📅.✅.🔧.🎨.🧠.🌱.🔥.☕.🗒.📦.🧭.🛠.💬.📊.🔍.✨.🏷.📎.🛡`.split(`.`),oc={warm:{label:`Warm`,className:`bg-gradient-to-br from-stone-200 via-amber-100/80 to-orange-100/60`},cool:{label:`Cool`,className:`bg-gradient-to-br from-slate-200 via-sky-100/70 to-stone-100`},soft:{label:`Soft`,className:`bg-gradient-to-br from-zinc-200 via-neutral-100 to-stone-50`},ink:{label:`Ink`,className:`bg-gradient-to-br from-zinc-800 via-stone-700 to-neutral-800`}};function sc(e){return{...e,updatedAt:Date.now()}}function cc(e,t){let n=new Set([t]),r=!0;for(;r;){r=!1;for(let t of e)t.parentId&&n.has(t.parentId)&&!n.has(t.id)&&(n.add(t.id),r=!0)}return n}function lc(e){return e.map(e=>({...e,id:D(`b`)}))}var uc=ic(),dc=Qs()(tc((e,t)=>({name:`ForgeNotes`,pages:uc.pages,activePageId:uc.activePageId,sidebarOpen:!0,theme:`light`,hydrated:!1,storageMode:`local`,syncStatus:`local`,setHydrated:t=>e({hydrated:t}),setName:t=>e({name:t}),setSidebarOpen:t=>e({sidebarOpen:t}),toggleSidebar:()=>e(e=>({sidebarOpen:!e.sidebarOpen})),setTheme:t=>e({theme:t}),setActivePage:t=>e({activePageId:t}),setStorageMode:t=>e({storageMode:t}),setSyncStatus:t=>e({syncStatus:t}),loadFromRemote:t=>e({name:t.name,pages:t.pages,activePageId:t.activePageId,sidebarOpen:t.sidebarOpen,theme:t.theme,storageMode:`database`,syncStatus:`saved`,hydrated:!0}),getPage:e=>t().pages.find(t=>t.id===e),getChildren:e=>t().pages.filter(t=>!t.archived&&t.parentId===e).sort((e,t)=>e.createdAt-t.createdAt),createPage:t=>{let n=rc({parentId:t?.parentId??null,title:t?.title??``,icon:t?.icon});return e(e=>({pages:[...e.pages,n],activePageId:n.id})),n.id},updatePage:(t,n)=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,...n}):e)})),deletePage:n=>{let r=cc(t().pages,n);e(e=>{let t=e.pages.map(e=>r.has(e.id)?sc({...e,archived:!0,favorite:!1}):e),n=e.activePageId;return n&&r.has(n)&&(n=t.find(e=>!e.archived&&!r.has(e.id))?.id??null),{pages:t,activePageId:n}})},restorePage:t=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,archived:!1,parentId:null}):e)})),permanentlyDeletePage:n=>{let r=cc(t().pages,n);e(e=>{let t=e.pages.filter(e=>!r.has(e.id)),n=e.activePageId;return n&&r.has(n)&&(n=t.find(e=>!e.archived)?.id??null),{pages:t,activePageId:n}})},duplicatePage:n=>{let r=t().pages.find(e=>e.id===n);if(!r)return null;let i=rc({title:r.title?`${r.title} (copy)`:`Untitled (copy)`,icon:r.icon,cover:r.cover,parentId:r.parentId,favorite:!1,blocks:lc(r.blocks)});return e(e=>({pages:[...e.pages,i],activePageId:i.id})),i.id},movePage:(n,r)=>{n!==r&&(r&&cc(t().pages,n).has(r)||e(e=>({pages:e.pages.map(e=>e.id===n?sc({...e,parentId:r}):e)})))},setBlocks:(t,n)=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,blocks:n}):e)})),updateBlock:(t,n,r)=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,blocks:e.blocks.map(e=>e.id===n?{...e,...r}:e)}):e)})),insertBlock:(t,n,r=`paragraph`,i=``)=>{let a={id:D(`b`),type:r,content:i,indent:0};return e(e=>({pages:e.pages.map(e=>{if(e.id!==t)return e;let r=[...e.blocks];if(!n)r.unshift(a);else{let e=r.findIndex(e=>e.id===n);e>=0?r.splice(e+1,0,a):r.push(a)}return sc({...e,blocks:r})})})),a.id},deleteBlock:(t,n)=>e(e=>({pages:e.pages.map(e=>{if(e.id!==t)return e;let r=e.blocks.filter(e=>e.id!==n);return r.length===0&&(r=[{id:D(`b`),type:`paragraph`,content:``,indent:0}]),sc({...e,blocks:r})})})),changeBlockType:(t,n,r)=>e(e=>({pages:e.pages.map(e=>e.id===t?sc({...e,blocks:e.blocks.map(e=>e.id===n?{...e,type:r,checked:r===`todo`?e.checked??!1:void 0}:e)}):e)})),moveBlock:(t,n,r)=>e(e=>({pages:e.pages.map(e=>{if(e.id!==t)return e;let i=[...e.blocks],a=i.findIndex(e=>e.id===n);if(a<0)return e;let o=r===`up`?a-1:a+1;if(o<0||o>=i.length)return e;let s=i[a];return i[a]=i[o],i[o]=s,sc({...e,blocks:i})})})),importPages:(t,n)=>e(e=>({pages:[...e.pages,...t],activePageId:n??t[0]?.id??e.activePageId})),resetWorkspace:()=>{let t=ic();e({name:`ForgeNotes`,pages:t.pages,activePageId:t.activePageId,sidebarOpen:!0,theme:`light`,storageMode:`local`,syncStatus:`local`})}}),{name:`workspace-v1`,partialize:e=>({name:e.name,pages:e.pages,activePageId:e.activePageId,sidebarOpen:e.sidebarOpen,theme:e.theme}),onRehydrateStorage:()=>e=>{e?.setHydrated(!0)}}));function fc(){let e=dc(e=>e.theme);(0,V.useEffect)(()=>{let t=document.documentElement;e===`dark`?t.classList.add(`dark`):t.classList.remove(`dark`)},[e])}var pc=`forgenotes-zoom`,mc=[.75,.85,1,1.15,1.3,1.5,1.75,2];function hc(e){let t=0;for(let n=1;n`u`)return 1;let e=Number.parseFloat(window.localStorage.getItem(pc)??``);return!Number.isFinite(e)||e<=0?1:Math.min(mc.at(-1),Math.max(mc[0],e))}function vc(e){document.documentElement.style.fontSize=e===1?``:`${e*100}%`}function yc(){(0,V.useEffect)(()=>{let e=_c();vc(e);let t=t=>{if(!(t.metaKey||t.ctrlKey)||t.altKey)return;let n=t.key===`=`||t.key===`+`?1:t.key===`-`||t.key===`_`?-1:t.key===`0`?0:null;if(n===null)return;let r=gc(e,n);t.preventDefault(),r!==e&&(e=r,vc(e),window.localStorage.setItem(pc,String(e)))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[])}function bc(){(0,V.useEffect)(()=>{},[])}var xc=`/assets/styles-Peq6Rcdg.css`,Sc=gs({head:()=>({meta:[{charSet:`utf-8`},{name:`viewport`,content:`width=device-width, initial-scale=1`},{title:`ForgeNotes — notes, AI & harness`},{name:`description`,content:`ForgeNotes is a Notion-style workspace for notes, AI (Deep Agents & coding CLIs), markdown, and agent workflows.`}],links:[{rel:`stylesheet`,href:xc}]}),component:Cc});function Cc(){return fc(),yc(),bc(),(0,H.jsxs)(`html`,{lang:`en`,suppressHydrationWarning:!0,children:[(0,H.jsx)(`head`,{children:(0,H.jsx)(Us,{})}),(0,H.jsxs)(`body`,{children:[(0,H.jsx)(Ks,{children:(0,H.jsx)(As,{})}),(0,H.jsx)(Ws,{})]})]})}var wc=`modulepreload`,Tc=function(e){return`/`+e},Ec={},Dc=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Tc(t,n),t=s(t),t in Ec)return;Ec[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:wc,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Oc=_s(`/`)({component:ys(()=>Dc(()=>import(`./routes-BDn33g5C.js`),__vite__mapDeps([0,1,2,3,4,5])),`component`)}),kc=_s(`/login`)({component:ys(()=>Dc(()=>import(`./login-xkhUej_P.js`),__vite__mapDeps([6,1,2,3,4,5])),`component`)}),Ac={IndexRoute:Oc.update({id:`/`,path:`/`,getParentRoute:()=>Sc}),LoginRoute:kc.update({id:`/login`,path:`/login`,getParentRoute:()=>Sc})},jc=Sc._addFileChildren(Ac);function Mc(){return Fs({routeTree:jc})}async function Nc(){let e=await Mc(),t=[];return window.__TSS_START_OPTIONS__={serializationAdapters:t},t.push(Do),e.options.serializationAdapters&&t.push(...e.options.serializationAdapters),e.update({basepath:``,serializationAdapters:t}),e.stores.matchesId.get().length||await Ao(e),e}var Pc=Nc;async function Fc(){let e=await Pc();return window.$_TSR?.h(),e}var Ic;function Lc(){return Ic||=Fc(),(0,H.jsx)(Mo,{promise:Ic,children:e=>(0,H.jsx)(Rs,{router:e})})}var Rc=xe();(0,V.startTransition)(()=>{(0,Rc.hydrateRoot)(document,(0,H.jsx)(V.StrictMode,{children:(0,H.jsx)(Lc,{})}))});export{rc as a,ds as c,nt as d,Ae as f,ac as i,Eo as l,dc as n,tc as o,we as p,oc as r,Qs as s,Dc as t,tt as u}; \ No newline at end of file diff --git a/dist-desktop/assets/info-DKCQHKI2-DIc7uC4I.js b/dist-desktop/assets/info-DKCQHKI2-DIc7uC4I.js new file mode 100644 index 0000000..8ac0188 --- /dev/null +++ b/dist-desktop/assets/info-DKCQHKI2-DIc7uC4I.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-BIQX33UG-CuPbkyWp.js";export{e as createInfoServices}; \ No newline at end of file diff --git a/dist-desktop/assets/infoDiagram-FWYZ7A6U-BY1UX4W6.js b/dist-desktop/assets/infoDiagram-FWYZ7A6U-BY1UX4W6.js new file mode 100644 index 0000000..cc3455f --- /dev/null +++ b/dist-desktop/assets/infoDiagram-FWYZ7A6U-BY1UX4W6.js @@ -0,0 +1,2 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{c as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as r}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as i}from"./mermaid-parser.core-Z7xZAZRH.js";var a={parse:e(async e=>{let n=await i(`info`,e);t.debug(n)},`parse`)},o={version:`11.16.0`},s={parser:a,db:{getVersion:e(()=>o.version,`getVersion`)},renderer:{draw:e((e,i,a)=>{t.debug(`rendering info diagram +`+e);let o=r(i);n(o,100,400,!0),o.append(`g`).append(`text`).attr(`x`,100).attr(`y`,40).attr(`class`,`version`).attr(`font-size`,32).style(`text-anchor`,`middle`).text(`v${a}`)},`draw`)}};export{s as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/init-D6jRqBbL.js b/dist-desktop/assets/init-D6jRqBbL.js new file mode 100644 index 0000000..6e92a59 --- /dev/null +++ b/dist-desktop/assets/init-D6jRqBbL.js @@ -0,0 +1 @@ +function e(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}export{e as t}; \ No newline at end of file diff --git a/dist-desktop/assets/input-mze7gZ5r.js b/dist-desktop/assets/input-mze7gZ5r.js new file mode 100644 index 0000000..fa8d0a3 --- /dev/null +++ b/dist-desktop/assets/input-mze7gZ5r.js @@ -0,0 +1 @@ +import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./react-BLJmJXjR.js";import{r as n,t as r,u as i}from"./utils-BTuSbA5p.js";import{t as a}from"./client-CwgDvMJw.js";var o=e(t(),1),s=Object.defineProperty,c=(e,t)=>s(e,`name`,{value:t,configurable:!0});function l(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}c(l,`setRef`);function u(...e){return t=>{let n=!1,r=e.map(e=>{let r=l(e,t);return!n&&typeof r==`function`&&(n=!0),r});if(n)return()=>{for(let t=0;tp(e,`name`,{value:t,configurable:!0}),h=m(((e,t)=>{let n={...t};for(let r in t){let i=e[r],a=t[r];if(/^on[A-Z]/.test(r))if(i&&a){let e=typeof i==`function`,t=typeof a==`function`;n[r]=(...n)=>{let r=t?a(...n):void 0;return e&&i(...n),r}}else i&&(n[r]=i);else r===`style`?n[r]={...typeof i==`object`?i:null,...typeof a==`object`?a:null}:r===`className`?n[r]=[i,a].filter(Boolean).join(` `):r===`aria-describedby`&&(n[r]=g(a,i))}return{...e,...n}}),`mergeProps`);function g(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}m(g,`concatAriaDescribedby`);var _=o.createContext(h);_.displayName=`SlotContext`;function v(e){let t=o.forwardRef((t,n)=>{let r=o.useContext(_),{children:i,mergeProps:a=r,...s}=t,c=null,l=!1,u=[];E(i)&&typeof A==`function`&&(i=A(i._payload)),o.Children.forEach(i,e=>{if(w(e)){l=!0;let t=e,n=`child`in t.props?t.props.child:t.props.children;E(n)&&typeof A==`function`&&(n=A(n._payload)),c=S(t,n),u.push(c?.props?.children)}else u.push(e)}),c?c=o.cloneElement(c,void 0,u):!l&&o.Children.count(i)===1&&o.isValidElement(i)&&(c=i);let f=c?C(c):void 0,p=d(n,f);if(!c){if(i||i===0)throw Error(l?k(e):O(e));return i}let m=a(s,c.props??{});return c.type!==o.Fragment&&(m.ref=n?p:f),o.cloneElement(c,m)});return t.displayName=`${e}.Slot`,t}m(v,`createSlot`);var y=v(`Slot`),b=Symbol.for(`radix.slottable`);function x(e){let t=m(e=>`child`in e?e.children(e.child):e.children,`Slottable`);return t.displayName=`${e}.Slottable`,t.__radixId=b,t}m(x,`createSlottable`);var S=m((e,t)=>{if(`child`in e.props){let t=e.props.child;return o.isValidElement(t)?o.cloneElement(t,void 0,e.props.children(t.props.children)):null}return o.isValidElement(t)?t:null},`getSlottableElementFromSlottable`);function C(e){let t=Object.getOwnPropertyDescriptor(e.props,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,`ref`)?.get,n=t&&`isReactWarning`in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}m(C,`getElementRef`);function w(e){return o.isValidElement(e)&&typeof e.type==`function`&&`__radixId`in e.type&&e.type.__radixId===b}m(w,`isSlottable`);var T=Symbol.for(`react.lazy`);function E(e){return typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===T&&`_payload`in e&&D(e._payload)}m(E,`isLazyComponent`);function D(e){return typeof e==`object`&&!!e&&`then`in e}m(D,`isPromiseLike`);var O=m(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,`createSlotError`),k=m(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,`createSlottableError`),A=o.use,j=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,M=n,N=((e,t)=>n=>{if(t?.variants==null)return M(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=j(t)||j(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return M(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)})(`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[background-color,color,opacity,box-shadow,transform] duration-150 ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:pointer-events-none disabled:opacity-50 active:scale-[0.98] [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0`,{variants:{variant:{default:`bg-primary text-primary-foreground hover:bg-primary/90`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,ghost:`hover:bg-muted text-foreground`,outline:`border border-border bg-transparent hover:bg-muted`,destructive:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,soft:`bg-muted text-foreground hover:bg-muted/80`},size:{default:`h-9 px-3.5 py-2`,sm:`h-8 rounded-md px-2.5 text-xs`,lg:`h-10 rounded-lg px-4`,icon:`h-8 w-8`,"icon-sm":`h-7 w-7`}},defaultVariants:{variant:`default`,size:`default`}}),P=o.forwardRef(({className:e,variant:t,size:n,asChild:i=!1,...a},o)=>(0,f.jsx)(i?y:`button`,{className:r(N({variant:t,size:n,className:e})),ref:o,...a}));P.displayName=`Button`;function F(){let{data:e,isPending:t}=a.useSession(),n=e?.user;return{user:n?{id:n.id,displayName:n.name??null,primaryEmail:n.email??null,profileImageUrl:n.image??null,isDevFallback:!1}:null,isPending:t}}function I(){return F().user}var L=o.forwardRef(({className:e,type:t,...n},i)=>(0,f.jsx)(`input`,{type:t,className:r(`flex h-9 w-full rounded-md border border-border bg-background px-3 py-1 text-sm text-foreground shadow-none transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50`,e),ref:i,...n}));L.displayName=`Input`;export{v as a,d as c,P as i,I as n,x as o,F as r,u as s,L as t}; \ No newline at end of file diff --git a/dist-desktop/assets/ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js b/dist-desktop/assets/ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js new file mode 100644 index 0000000..284aace --- /dev/null +++ b/dist-desktop/assets/ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js @@ -0,0 +1,70 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-UMNXGZaF.js";import{H as t,K as n,U as r,a as i,c as a,s as o,v as s,w as c,x as l,y as u}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{p as d}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as f}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as p}from"./rough.esm-CSKSodPl.js";var m=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,14],i=[1,12],a=[1,13],o=[6,7,8],s=[1,20],c=[1,18],l=[1,19],u=[6,7,11],d=[1,6,13,14],f=[1,23],p=[1,24],m=[1,6,7,11,13,14],h={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,ishikawa:4,spaceLines:5,SPACELINE:6,NL:7,ISHIKAWA:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,TEXT:14,$accept:0,$end:1},terminals_:{2:`error`,6:`SPACELINE`,7:`NL`,8:`ISHIKAWA`,11:`EOF`,13:`SPACELIST`,14:`TEXT`},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,2],[12,1],[12,1],[12,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 6:case 7:return r;case 15:r.addNode(a[s-1].length,a[s].trim());break;case 16:r.addNode(0,a[s].trim());break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],8:n},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:n},{6:r,7:[1,10],9:9,12:11,13:i,14:a},t(o,[2,3]),{1:[2,2]},t(o,[2,4]),t(o,[2,5]),{1:[2,6],6:r,12:15,13:i,14:a},{6:r,9:16,12:11,13:i,14:a},{6:s,7:c,10:17,11:l},t(u,[2,18],{14:[1,21]}),t(u,[2,16]),t(u,[2,17]),{6:s,7:c,10:22,11:l},{1:[2,7],6:r,12:15,13:i,14:a},t(d,[2,14],{7:f,11:p}),t(m,[2,8]),t(m,[2,9]),t(m,[2,10]),t(u,[2,15]),t(d,[2,13],{7:f,11:p}),t(m,[2,11]),t(m,[2,12])],defaultActions:{2:[2,1],6:[2,2]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};h.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:return 6;case 1:return 8;case 2:return 8;case 3:return 6;case 4:return 7;case 5:return 13;case 6:return 14;case 7:return 11}},`anonymous`),rules:[/^(?:\s*%%.*)/i,/^(?:ishikawa-beta\b)/i,/^(?:ishikawa\b)/i,/^(?:[\s]+[\n])/i,/^(?:[\n]+)/i,/^(?:[\s]+)/i,/^(?:[^\n]+)/i,/^(?:$)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7],inclusive:!0}}}})();function g(){this.yy={}}return e(g,`Parser`),g.prototype=h,h.Parser=g,new g})();m.parser=m;var h=m,g=class{constructor(){this.stack=[],this.clear=this.clear.bind(this),this.addNode=this.addNode.bind(this),this.getRoot=this.getRoot.bind(this)}static{e(this,`IshikawaDB`)}clear(){this.root=void 0,this.stack=[],this.baseLevel=void 0,i()}getRoot(){return this.root}addNode(e,t){let r=o.sanitizeText(t,l());if(!this.root){this.root={text:r,children:[]},this.stack=[{level:0,node:this.root}],n(r);return}this.baseLevel??=e;let i=e-this.baseLevel+1;for(i<=0&&(i=1);this.stack.length>1&&this.stack[this.stack.length-1].level>=i;)this.stack.pop();let a=this.stack[this.stack.length-1].node,s={text:r,children:[]};a.children.push(s),this.stack.push({level:i,node:s})}getAccTitle(){return u()}setAccTitle(e){r(e)}getAccDescription(){return s()}setAccDescription(e){t(e)}getDiagramTitle(){return c()}setDiagramTitle(e){n(e)}},_=14,v=250,y=30,b=60,x=5,S=82*Math.PI/180,C=Math.cos(S),w=Math.sin(S),T=e((e,t,n)=>{let r=e.node().getBBox(),i=r.width+t*2,o=r.height+t*2;a(e,o,i,n),e.attr(`viewBox`,`${r.x-t} ${r.y-t} ${i} ${o}`)},`applyPaddedViewBox`),E=e((e,t,n,r)=>{let i=r.db.getRoot();if(!i)return;let a=l(),{look:o,handDrawnSeed:s,themeVariables:c}=a,u=d(a.fontSize)[0]??_,m=o===`handDrawn`,h=i.children??[],g=a.ishikawa?.diagramPadding??20,y=a.ishikawa?.useMaxWidth??!1,b=f(t),x=b.append(`g`).attr(`class`,`ishikawa`),S=m?p.svg(b.node()):void 0,C=S?{roughSvg:S,seed:s??0,lineColor:c?.lineColor??`#333`,fillColor:c?.mainBkg??`#fff`}:void 0,w=`ishikawa-arrow-${t}`;m||x.append(`defs`).append(`marker`).attr(`id`,w).attr(`viewBox`,`0 0 10 10`).attr(`refX`,0).attr(`refY`,5).attr(`markerWidth`,6).attr(`markerHeight`,6).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 10 0 L 0 5 L 10 10 Z`).attr(`class`,`ishikawa-arrow`);let E=0,k=v,A=m?void 0:L(x,E,k,E,k,`ishikawa-spine`);if(O(x,E,k,i.text,u,C),!h.length){m&&L(x,E,k,E,k,`ishikawa-spine`,C),T(b,g,y);return}E-=20;let j=h.filter((e,t)=>t%2==0),N=h.filter((e,t)=>t%2==1),P=D(j),F=D(N),I=P.total+F.total,R=v,z=v;if(I>0){let e=v*2,t=v*.3;R=Math.max(t,e*(P.total/I)),z=Math.max(t,e*(F.total/I))}let B=u*2;R=Math.max(R,P.max*B),z=Math.max(z,F.max*B),k=Math.max(R,v),A&&A.attr(`y1`,k).attr(`y2`,k),x.select(`.ishikawa-head-group`).attr(`transform`,`translate(0,${k})`);let V=Math.ceil(h.length/2);for(let e=0;eMath.min(e,t.getBBox().x),1/0)}if(m)L(x,E,k,0,k,`ishikawa-spine`,C);else{A.attr(`x1`,E);let e=`url(#${w})`;x.selectAll(`line.ishikawa-branch, line.ishikawa-sub-branch`).attr(`marker-start`,e)}T(b,g,y)},`draw`),D=e(t=>{let n=e(e=>e.children.reduce((e,t)=>e+1+n(t),0),`countDescendants`);return t.reduce((e,t)=>{let r=n(t);return e.total+=r,e.max=Math.max(e.max,r),e},{total:0,max:0})},`sideStats`),O=e((e,t,n,r,i,a)=>{let o=Math.max(6,Math.floor(110/(i*.6))),s=e.append(`g`).attr(`class`,`ishikawa-head-group`).attr(`transform`,`translate(${t},${n})`),c=F(s,P(r,o),0,0,`ishikawa-head-label`,`start`,i),l=c.node().getBBox(),u=Math.max(60,l.width+6),d=Math.max(40,l.height*2+40),f=`M 0 ${-d/2} L 0 ${d/2} Q ${u*2.4} 0 0 ${-d/2} Z`;if(a){let e=a.roughSvg.path(f,{roughness:1.5,seed:a.seed,fill:a.fillColor,fillStyle:`hachure`,fillWeight:2.5,hachureGap:5,stroke:a.lineColor,strokeWidth:2});s.insert(()=>e,`:first-child`).attr(`class`,`ishikawa-head`)}else s.insert(`path`,`:first-child`).attr(`class`,`ishikawa-head`).attr(`d`,f);c.attr(`transform`,`translate(${(u-l.width)/2-l.x+3},${-l.y-l.height/2})`)},`drawHead`),k=e((t,n)=>{let r=[],i=[],a=e((e,t,o)=>{let s=n===-1?[...e].reverse():e;for(let e of s){let n=r.length,s=e.children??[];r.push({depth:o,text:P(e.text,15),parentIndex:t,childCount:s.length}),o%2==0?(i.push(n),s.length&&a(s,n,o+1)):(s.length&&a(s,n,o+1),i.push(n))}},`walk`);return a(t,-1,2),{entries:r,yOrder:i}},`flattenTree`),A=e((e,t,n,r,i,a,o)=>{let s=e.append(`g`).attr(`class`,`ishikawa-label-group`),c=F(s,t,n,r+11*i,`ishikawa-label cause`,`middle`,a).node().getBBox();if(o){let e=o.roughSvg.rectangle(c.x-20,c.y-2,c.width+40,c.height+4,{roughness:1.5,seed:o.seed,fill:o.fillColor,fillStyle:`hachure`,fillWeight:2.5,hachureGap:5,stroke:o.lineColor,strokeWidth:2});s.insert(()=>e,`:first-child`).attr(`class`,`ishikawa-label-box`)}else s.insert(`rect`,`:first-child`).attr(`class`,`ishikawa-label-box`).attr(`x`,c.x-20).attr(`y`,c.y-2).attr(`width`,c.width+40).attr(`height`,c.height+4)},`drawCauseLabel`),j=e((e,t,n,r,i,a)=>{let o=Math.sqrt(r*r+i*i);if(o===0)return;let s=r/o,c=i/o,l=-c*6,u=s*6,d=t,f=n,p=`M ${d} ${f} L ${d-s*6*2+l} ${f-c*6*2+u} L ${d-s*6*2-l} ${f-c*6*2-u} Z`,m=a.roughSvg.path(p,{roughness:1,seed:a.seed,fill:a.lineColor,fillStyle:`solid`,stroke:a.lineColor,strokeWidth:1});e.append(()=>m)},`drawArrowMarker`),M=e((e,t,n,r,i,a,o,s)=>{let c=t.children??[],l=a*(c.length?1:.2),u=-C*l,d=w*l*i,f=n+u,p=r+d;if(L(e,n,r,f,p,`ishikawa-branch`,s),s&&j(e,n,r,n-f,r-p,s),A(e,t.text,f,p,i,o,s),!c.length)return;let{entries:m,yOrder:h}=k(c,i),g=m.length,_=Array(g);for(let[e,t]of h.entries())_[t]=r+d*((e+1)/(g+1));let v=new Map;v.set(-1,{x0:n,y0:r,x1:f,y1:p,childCount:c.length,childrenDrawn:0});let S=-C,T=w*i,E=i<0?`ishikawa-label up`:`ishikawa-label down`;for(let[t,n]of m.entries()){let r=_[t],i=v.get(n.parentIndex),a=e.append(`g`).attr(`class`,`ishikawa-sub-group`),c=0,l=0,u=0;if(n.depth%2==0){let e=i.y1-i.y0;c=I(i.x0,i.x1,e?(r-i.y0)/e:.5),l=r,u=c-(n.childCount>0?b+n.childCount*x:y),L(a,c,r,u,r,`ishikawa-sub-branch`,s),s&&j(a,c,r,1,0,s),F(a,n.text,u,r,`ishikawa-label align`,`end`,o)}else{let e=i.childrenDrawn++;c=I(i.x0,i.x1,(i.childCount-e)/(i.childCount+1)),l=i.y0,u=c+S*((r-l)/T),L(a,c,l,u,r,`ishikawa-sub-branch`,s),s&&j(a,c,l,c-u,l-r,s),F(a,n.text,u,r,E,`end`,o)}n.childCount>0&&v.set(t,{x0:c,y0:l,x1:u,y1:r,childCount:n.childCount,childrenDrawn:0})}},`drawBranch`),N=e(e=>e.split(/|\n/),`splitLines`),P=e((e,t)=>{if(e.length<=t)return e;let n=[];for(let r of e.split(/\s+/)){let e=n.length-1;e>=0&&n[e].length+1+r.length<=t?n[e]+=` `+r:n.push(r)}return n.join(` +`)},`wrapText`),F=e((e,t,n,r,i,a,o)=>{let s=N(t),c=o*1.05,l=e.append(`text`).attr(`class`,i).attr(`text-anchor`,a).attr(`x`,n).attr(`y`,r-(s.length-1)*c/2);for(let[e,t]of s.entries())l.append(`tspan`).attr(`x`,n).attr(`dy`,e===0?0:c).text(t);return l},`drawMultilineText`),I=e((e,t,n)=>e+(t-e)*n,`lerp`),L=e((e,t,n,r,i,a,o)=>{if(o){let s=o.roughSvg.line(t,n,r,i,{roughness:1.5,seed:o.seed,stroke:o.lineColor,strokeWidth:2});e.append(()=>s).attr(`class`,a);return}return e.append(`line`).attr(`class`,a).attr(`x1`,t).attr(`y1`,n).attr(`x2`,r).attr(`y2`,i)},`drawLine`),R={parser:h,get db(){return new g},renderer:{draw:E},styles:e(e=>` +.ishikawa .ishikawa-spine, +.ishikawa .ishikawa-branch, +.ishikawa .ishikawa-sub-branch { + stroke: ${e.lineColor}; + stroke-width: 2; + fill: none; +} + +.ishikawa .ishikawa-sub-branch { + stroke-width: 1; +} + +.ishikawa .ishikawa-arrow { + fill: ${e.lineColor}; +} + +.ishikawa .ishikawa-head { + fill: ${e.mainBkg}; + stroke: ${e.lineColor}; + stroke-width: 2; +} + +.ishikawa .ishikawa-label-box { + fill: ${e.mainBkg}; + stroke: ${e.lineColor}; + stroke-width: 2; +} + +.ishikawa text { + font-family: ${e.fontFamily}; + font-size: ${e.fontSize}; + fill: ${e.textColor}; +} + +.ishikawa .ishikawa-head-label { + font-weight: 600; + text-anchor: middle; + dominant-baseline: middle; + font-size: 14px; +} + +.ishikawa .ishikawa-label { + text-anchor: end; +} + +.ishikawa .ishikawa-label.cause { + text-anchor: middle; + dominant-baseline: middle; +} + +.ishikawa .ishikawa-label.align { + text-anchor: end; + dominant-baseline: middle; +} + +.ishikawa .ishikawa-label.up { + dominant-baseline: baseline; +} + +.ishikawa .ishikawa-label.down { + dominant-baseline: hanging; +} +`,`getStyles`)};export{R as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/journeyDiagram-5HDEW3XC-CCn-uNlj.js b/dist-desktop/assets/journeyDiagram-5HDEW3XC-CCn-uNlj.js new file mode 100644 index 0000000..88cb2d8 --- /dev/null +++ b/dist-desktop/assets/journeyDiagram-5HDEW3XC-CCn-uNlj.js @@ -0,0 +1,139 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,c as o,v as s,w as c,x as l,y as u}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as d}from"./arc-DqK6O3qL.js";import{t as f}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{a as p,n as m,o as h,s as g}from"./chunk-32BRIVSS-DWU3ezKg.js";var _=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[6,8,10,11,12,14,16,17,18],r=[1,9],i=[1,10],a=[1,11],o=[1,12],s=[1,13],c=[1,14],l={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,journey:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NEWLINE:10,title:11,acc_title:12,acc_title_value:13,acc_descr:14,acc_descr_value:15,acc_descr_multiline_value:16,section:17,taskName:18,taskData:19,$accept:0,$end:1},terminals_:{2:`error`,4:`journey`,6:`EOF`,8:`SPACE`,10:`NEWLINE`,11:`title`,12:`acc_title`,13:`acc_title_value`,14:`acc_descr`,15:`acc_descr_value`,16:`acc_descr_multiline_value`,17:`section`,18:`taskName`,19:`taskData`},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,2]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 2:this.$=[];break;case 3:a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 5:this.$=a[s];break;case 6:case 7:this.$=[];break;case 8:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 9:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 10:case 11:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 12:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 13:r.addTask(a[s-1],a[s]),this.$=`task`;break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},t(n,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:r,12:i,14:a,16:o,17:s,18:c},t(n,[2,7],{1:[2,1]}),t(n,[2,3]),{9:15,11:r,12:i,14:a,16:o,17:s,18:c},t(n,[2,5]),t(n,[2,6]),t(n,[2,8]),{13:[1,16]},{15:[1,17]},t(n,[2,11]),t(n,[2,12]),{19:[1,18]},t(n,[2,4]),t(n,[2,9]),t(n,[2,10]),t(n,[2,13])],defaultActions:{},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};l.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:break;case 1:break;case 2:return 10;case 3:break;case 4:break;case 5:return 4;case 6:return 11;case 7:return this.begin(`acc_title`),12;case 8:return this.popState(),`acc_title_value`;case 9:return this.begin(`acc_descr`),14;case 10:return this.popState(),`acc_descr_value`;case 11:this.begin(`acc_descr_multiline`);break;case 12:this.popState();break;case 13:return`acc_descr_multiline_value`;case 14:return 17;case 15:return 18;case 16:return 19;case 17:return`:`;case 18:return 6;case 19:return`INVALID`}},`anonymous`),rules:[/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:journey\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:section\s[^#:\n;]+)/i,/^(?:[^#:\n;]+)/i,/^(?::[^#\n;]+)/i,/^(?::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[12,13],inclusive:!1},acc_descr:{rules:[10],inclusive:!1},acc_title:{rules:[8],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,9,11,14,15,16,17,18,19],inclusive:!0}}}})();function u(){this.yy={}}return e(u,`Parser`),u.prototype=l,l.Parser=u,new u})();_.parser=_;var v=_,y=``,b=[],x=[],S=[],C=e(function(){b.length=0,x.length=0,y=``,S.length=0,a()},`clear`),w=e(function(e){y=e,b.push(e)},`addSection`),T=e(function(){return b},`getSections`),E=e(function(){let e=A(),t=0;for(;!e&&t<100;)e=A(),t++;return x.push(...S),x},`getTasks`),D=e(function(){let e=[];return x.forEach(t=>{t.people&&e.push(...t.people)}),[...new Set(e)].sort()},`updateActors`),O=e(function(e,t){let n=t.substr(1).split(`:`),r=0,i=[];n.length===1?(r=Number(n[0]),i=[]):(r=Number(n[0]),i=n[1].split(`,`));let a=i.map(e=>e.trim()),o={section:y,type:y,people:a,task:e,score:r};S.push(o)},`addTask`),k=e(function(e){let t={section:y,type:y,description:e,task:e,classes:[]};x.push(t)},`addTaskOrg`),A=e(function(){let t=e(function(e){return S[e].processed},`compileTask`),n=!0;for(let[e,r]of S.entries())t(e),n&&=r.processed;return n},`compileTasks`),j={getConfig:e(()=>l().journey,`getConfig`),clear:C,setDiagramTitle:r,getDiagramTitle:c,setAccTitle:i,getAccTitle:u,setAccDescription:n,getAccDescription:s,addSection:w,getSections:T,getTasks:E,addTask:O,addTaskOrg:k,getActors:e(function(){return D()},`getActors`)},M=e(e=>`.label { + font-family: ${e.fontFamily}; + color: ${e.textColor}; + } + .mouth { + stroke: #666; + } + + line { + stroke: ${e.textColor} + } + + .legend { + fill: ${e.textColor}; + font-family: ${e.fontFamily}; + } + + .label text { + fill: #333; + } + .label { + color: ${e.textColor} + } + + .face { + ${e.faceColor?`fill: ${e.faceColor}`:`fill: #FFF8DC`}; + stroke: #999; + } + + .node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; + stroke-width: 1px; + } + + .node .label { + text-align: center; + } + .node.clickable { + cursor: pointer; + } + + .arrowheadPath { + fill: ${e.arrowheadColor}; + } + + .edgePath .path { + stroke: ${e.lineColor}; + stroke-width: 1.5px; + } + + .flowchart-link { + stroke: ${e.lineColor}; + fill: none; + } + + .edgeLabel { + background-color: ${e.edgeLabelBackground}; + rect { + opacity: 0.5; + } + text-align: center; + } + + .cluster rect { + } + + .cluster text { + fill: ${e.titleColor}; + } + + div.mermaidTooltip { + position: absolute; + text-align: center; + max-width: 200px; + padding: 2px; + font-family: ${e.fontFamily}; + font-size: 12px; + background: ${e.tertiaryColor}; + border: 1px solid ${e.border2}; + border-radius: 2px; + pointer-events: none; + z-index: 100; + } + + .task-type-0, .section-type-0 { + ${e.fillType0?`fill: ${e.fillType0}`:``}; + } + .task-type-1, .section-type-1 { + ${e.fillType0?`fill: ${e.fillType1}`:``}; + } + .task-type-2, .section-type-2 { + ${e.fillType0?`fill: ${e.fillType2}`:``}; + } + .task-type-3, .section-type-3 { + ${e.fillType0?`fill: ${e.fillType3}`:``}; + } + .task-type-4, .section-type-4 { + ${e.fillType0?`fill: ${e.fillType4}`:``}; + } + .task-type-5, .section-type-5 { + ${e.fillType0?`fill: ${e.fillType5}`:``}; + } + .task-type-6, .section-type-6 { + ${e.fillType0?`fill: ${e.fillType6}`:``}; + } + .task-type-7, .section-type-7 { + ${e.fillType0?`fill: ${e.fillType7}`:``}; + } + + .actor-0 { + ${e.actor0?`fill: ${e.actor0}`:``}; + } + .actor-1 { + ${e.actor1?`fill: ${e.actor1}`:``}; + } + .actor-2 { + ${e.actor2?`fill: ${e.actor2}`:``}; + } + .actor-3 { + ${e.actor3?`fill: ${e.actor3}`:``}; + } + .actor-4 { + ${e.actor4?`fill: ${e.actor4}`:``}; + } + .actor-5 { + ${e.actor5?`fill: ${e.actor5}`:``}; + } + ${f()} +`,`getStyles`),N=e(function(e,t){return p(e,t)},`drawRect`),P=e(function(t,n){let r=t.append(`circle`).attr(`cx`,n.cx).attr(`cy`,n.cy).attr(`class`,`face`).attr(`r`,15).attr(`stroke-width`,2).attr(`overflow`,`visible`),i=t.append(`g`);i.append(`circle`).attr(`cx`,n.cx-15/3).attr(`cy`,n.cy-15/3).attr(`r`,1.5).attr(`stroke-width`,2).attr(`fill`,`#666`).attr(`stroke`,`#666`),i.append(`circle`).attr(`cx`,n.cx+15/3).attr(`cy`,n.cy-15/3).attr(`r`,1.5).attr(`stroke-width`,2).attr(`fill`,`#666`).attr(`stroke`,`#666`);function a(e){let t=d().startAngle(Math.PI/2).endAngle(Math.PI/2*3).innerRadius(15/2).outerRadius(15/2.2);e.append(`path`).attr(`class`,`mouth`).attr(`d`,t).attr(`transform`,`translate(`+n.cx+`,`+(n.cy+2)+`)`)}e(a,`smile`);function o(e){let t=d().startAngle(3*Math.PI/2).endAngle(Math.PI/2*5).innerRadius(15/2).outerRadius(15/2.2);e.append(`path`).attr(`class`,`mouth`).attr(`d`,t).attr(`transform`,`translate(`+n.cx+`,`+(n.cy+7)+`)`)}e(o,`sad`);function s(e){e.append(`line`).attr(`class`,`mouth`).attr(`stroke`,2).attr(`x1`,n.cx-5).attr(`y1`,n.cy+7).attr(`x2`,n.cx+5).attr(`y2`,n.cy+7).attr(`class`,`mouth`).attr(`stroke-width`,`1px`).attr(`stroke`,`#666`)}return e(s,`ambivalent`),n.score>3?a(i):n.score<3?o(i):s(i),r},`drawFace`),F=e(function(e,t){let n=e.append(`circle`);return n.attr(`cx`,t.cx),n.attr(`cy`,t.cy),n.attr(`class`,`actor-`+t.pos),n.attr(`fill`,t.fill),n.attr(`stroke`,t.stroke),n.attr(`r`,t.r),n.class!==void 0&&n.attr(`class`,n.class),t.title!==void 0&&n.append(`title`).text(t.title),n},`drawCircle`),I=e(function(e,t){return h(e,t)},`drawText`),L=e(function(t,n){function r(e,t,n,r,i){return e+`,`+t+` `+(e+n)+`,`+t+` `+(e+n)+`,`+(t+r-i)+` `+(e+n-i*1.2)+`,`+(t+r)+` `+e+`,`+(t+r)}e(r,`genPoints`);let i=t.append(`polygon`);i.attr(`points`,r(n.x,n.y,50,20,7)),i.attr(`class`,`labelBox`),n.y+=n.labelMargin,n.x+=.5*n.labelMargin,I(t,n)},`drawLabel`),R=e(function(e,t,n){let r=e.append(`g`),i=g();i.x=t.x,i.y=t.y,i.fill=t.fill,i.width=n.width*t.taskCount+n.diagramMarginX*(t.taskCount-1),i.height=n.height,i.class=`journey-section section-type-`+t.num,i.rx=3,i.ry=3,N(r,i),H(n)(t.text,r,i.x,i.y,i.width,i.height,{class:`journey-section section-type-`+t.num},n,t.colour)},`drawSection`),z=-1,B=e(function(e,t,n,r){let i=t.x+n.width/2,a=e.append(`g`);z++,a.append(`line`).attr(`id`,r+`-task`+z).attr(`x1`,i).attr(`y1`,t.y).attr(`x2`,i).attr(`y2`,450).attr(`class`,`task-line`).attr(`stroke-width`,`1px`).attr(`stroke-dasharray`,`4 2`).attr(`stroke`,`#666`),P(a,{cx:i,cy:300+(5-t.score)*30,score:t.score});let o=g();o.x=t.x,o.y=t.y,o.fill=t.fill,o.width=n.width,o.height=n.height,o.class=`task task-type-`+t.num,o.rx=3,o.ry=3,N(a,o);let s=t.x+14;t.people.forEach(e=>{let n=t.actors[e].color,r={cx:s,cy:t.y,r:7,fill:n,stroke:`#000`,title:e,pos:t.actors[e].position};F(a,r),s+=10}),H(n)(t.task,a,o.x,o.y,o.width,o.height,{class:`task`},n,t.colour)},`drawTask`),V=e(function(e,t){m(e,t)},`drawBackgroundRect`),H=(function(){function t(e,t,n,r,a,o,s,c){i(t.append(`text`).attr(`x`,n+a/2).attr(`y`,r+o/2+5).style(`font-color`,c).style(`text-anchor`,`middle`).text(e),s)}e(t,`byText`);function n(e,t,n,r,a,o,s,c,l){let{taskFontSize:u,taskFontFamily:d}=c,f=e.split(//gi);for(let e=0;e{let a=G[i].color,o={cx:20,cy:r,r:7,fill:a,stroke:`#000`,pos:G[i].position};U.drawCircle(e,o);let s=e.append(`text`).attr(`visibility`,`hidden`).text(i),c=s.node().getBoundingClientRect().width;s.remove();let l=[];if(c<=n)l=[i];else{let t=i.split(` `),r=``;s=e.append(`text`).attr(`visibility`,`hidden`),t.forEach(e=>{let t=r?`${r} ${e}`:e;if(s.text(t),s.node().getBoundingClientRect().width>n){if(r&&l.push(r),r=e,s.text(e),s.node().getBoundingClientRect().width>n){let t=``;for(let r of e)t+=r,s.text(t+`-`),s.node().getBoundingClientRect().width>n&&(l.push(t.slice(0,-1)+`-`),t=r);r=t}}else r=t}),r&&l.push(r),s.remove()}l.forEach((n,i)=>{let a={x:40,y:r+7+i*20,fill:`#666`,text:n,textMargin:t.boxTextMargin??5},o=U.drawText(e,a).node().getBoundingClientRect().width;o>K&&o>t.leftMargin-o&&(K=o)}),r+=Math.max(20,l.length*20)})}e(q,`drawActorLegend`);var J=l().journey,Y=0,ee=e(function(e,n,r,i){let a=l(),s=a.journey.titleColor,c=a.journey.titleFontSize,u=a.journey.titleFontFamily,d=a.securityLevel,f;d===`sandbox`&&(f=t(`#i`+n));let p=t(d===`sandbox`?f.nodes()[0].contentDocument.body:`body`);X.init();let m=p.select(`#`+n);U.initGraphics(m,n);let h=i.db.getTasks(),g=i.db.getDiagramTitle(),_=i.db.getActors();for(let e in G)delete G[e];let v=0;_.forEach(e=>{G[e]={color:J.actorColours[v%J.actorColours.length],position:v},v++}),q(m),Y=J.leftMargin+K,X.insert(0,0,Y,Object.keys(G).length*50),te(m,h,0,n);let y=X.getBounds();g&&m.append(`text`).text(g).attr(`x`,Y).attr(`font-size`,c).attr(`font-weight`,`bold`).attr(`y`,25).attr(`fill`,s).attr(`font-family`,u);let b=y.stopy-y.starty+2*J.diagramMarginY,x=Y+y.stopx+2*J.diagramMarginX;o(m,b,x,J.useMaxWidth),m.append(`line`).attr(`x1`,Y).attr(`y1`,J.height*4).attr(`x2`,x-Y-4).attr(`y2`,J.height*4).attr(`stroke-width`,4).attr(`stroke`,`black`).attr(`marker-end`,`url(#`+n+`-arrowhead)`);let S=g?70:0;m.attr(`viewBox`,`${y.startx} -25 ${x} ${b+S}`),m.attr(`preserveAspectRatio`,`xMinYMin meet`),m.attr(`height`,b+S+25)},`draw`),X={data:{startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},verticalPos:0,sequenceItems:[],init:e(function(){this.sequenceItems=[],this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},this.verticalPos=0},`init`),updateVal:e(function(e,t,n,r){e[t]===void 0?e[t]=n:e[t]=r(n,e[t])},`updateVal`),updateBounds:e(function(t,n,r,i){let a=l().journey,o=this,s=0;function c(c){return e(function(e){s++;let l=o.sequenceItems.length-s+1;o.updateVal(e,`starty`,n-l*a.boxMargin,Math.min),o.updateVal(e,`stopy`,i+l*a.boxMargin,Math.max),o.updateVal(X.data,`startx`,t-l*a.boxMargin,Math.min),o.updateVal(X.data,`stopx`,r+l*a.boxMargin,Math.max),c!==`activation`&&(o.updateVal(e,`startx`,t-l*a.boxMargin,Math.min),o.updateVal(e,`stopx`,r+l*a.boxMargin,Math.max),o.updateVal(X.data,`starty`,n-l*a.boxMargin,Math.min),o.updateVal(X.data,`stopy`,i+l*a.boxMargin,Math.max))},`updateItemBounds`)}e(c,`updateFn`),this.sequenceItems.forEach(c())},`updateBounds`),insert:e(function(e,t,n,r){let i=Math.min(e,n),a=Math.max(e,n),o=Math.min(t,r),s=Math.max(t,r);this.updateVal(X.data,`startx`,i,Math.min),this.updateVal(X.data,`starty`,o,Math.min),this.updateVal(X.data,`stopx`,a,Math.max),this.updateVal(X.data,`stopy`,s,Math.max),this.updateBounds(i,o,a,s)},`insert`),bumpVerticalPos:e(function(e){this.verticalPos+=e,this.data.stopy=this.verticalPos},`bumpVerticalPos`),getVerticalPos:e(function(){return this.verticalPos},`getVerticalPos`),getBounds:e(function(){return this.data},`getBounds`)},Z=J.sectionFills,Q=J.sectionColours,te=e(function(e,t,n,r){let i=l().journey,a=``,o=n+(i.height*2+i.diagramMarginY),s=0,c=`#CCC`,u=`black`,d=0;for(let[n,l]of t.entries()){if(a!==l.section){c=Z[s%Z.length],d=s%Z.length,u=Q[s%Q.length];let r=0,o=l.section;for(let e=n;e(G[t]&&(e[t]=G[t]),e),{});l.x=n*i.taskMargin+n*i.width+Y,l.y=o,l.width=i.diagramMarginX,l.height=i.diagramMarginY,l.colour=u,l.fill=c,l.num=d,l.actors=f,U.drawTask(e,l,i,r),X.insert(l.x,l.y,l.x+l.width+i.taskMargin,450)}},`drawTasks`),$={setConf:W,draw:ee},ne={parser:v,db:j,renderer:$,styles:M,init:e(e=>{$.setConf(e.journey),j.clear()},`init`)};export{ne as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/kanban-definition-HUTT4EX6-CW9CwpnR.js b/dist-desktop/assets/kanban-definition-HUTT4EX6-CW9CwpnR.js new file mode 100644 index 0000000..1d105a8 --- /dev/null +++ b/dist-desktop/assets/kanban-definition-HUTT4EX6-CW9CwpnR.js @@ -0,0 +1,89 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{J as n,et as r,f as i,rt as a,tt as o,x as s,z as c}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as l}from"./chunk-VAUOI2AC-AC9pRUsa.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{t as u}from"./chunk-5VM5RSS4-ZNzvKenW.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import{a as d,c as f,i as p}from"./chunk-ZGVPDNZ5-DGInJAPD.js";import{n as m,t as h}from"./chunk-ZIRB5QZD-C6fEPe3t.js";var g=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,13],i=[1,12],a=[1,15],o=[1,16],s=[1,20],c=[1,19],l=[6,7,8],u=[1,26],d=[1,24],f=[1,25],p=[6,7,11],m=[1,31],h=[6,7,11,24],g=[1,6,13,16,17,20,23],_=[1,35],v=[1,36],y=[1,6,7,11,13,16,17,20,23],b=[1,38],x={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mindMap:4,spaceLines:5,SPACELINE:6,NL:7,KANBAN:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,node:14,shapeData:15,ICON:16,CLASS:17,nodeWithId:18,nodeWithoutId:19,NODE_DSTART:20,NODE_DESCR:21,NODE_DEND:22,NODE_ID:23,SHAPE_DATA:24,$accept:0,$end:1},terminals_:{2:`error`,6:`SPACELINE`,7:`NL`,8:`KANBAN`,11:`EOF`,13:`SPACELIST`,16:`ICON`,17:`CLASS`,20:`NODE_DSTART`,21:`NODE_DESCR`,22:`NODE_DEND`,23:`NODE_ID`,24:`SHAPE_DATA`},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,3],[12,2],[12,2],[12,2],[12,1],[12,2],[12,1],[12,1],[12,1],[12,1],[14,1],[14,1],[19,3],[18,1],[18,4],[15,2],[15,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 6:case 7:return r;case 8:r.getLogger().trace(`Stop NL `);break;case 9:r.getLogger().trace(`Stop EOF `);break;case 11:r.getLogger().trace(`Stop NL2 `);break;case 12:r.getLogger().trace(`Stop EOF2 `);break;case 15:r.getLogger().info(`Node: `,a[s-1].id),r.addNode(a[s-2].length,a[s-1].id,a[s-1].descr,a[s-1].type,a[s]);break;case 16:r.getLogger().info(`Node: `,a[s].id),r.addNode(a[s-1].length,a[s].id,a[s].descr,a[s].type);break;case 17:r.getLogger().trace(`Icon: `,a[s]),r.decorateNode({icon:a[s]});break;case 18:case 23:r.decorateNode({class:a[s]});break;case 19:r.getLogger().trace(`SPACELIST`);break;case 20:r.getLogger().trace(`Node: `,a[s-1].id),r.addNode(0,a[s-1].id,a[s-1].descr,a[s-1].type,a[s]);break;case 21:r.getLogger().trace(`Node: `,a[s].id),r.addNode(0,a[s].id,a[s].descr,a[s].type);break;case 22:r.decorateNode({icon:a[s]});break;case 27:r.getLogger().trace(`node found ..`,a[s-2]),this.$={id:a[s-1],descr:a[s-1],type:r.getType(a[s-2],a[s])};break;case 28:this.$={id:a[s],descr:a[s],type:0};break;case 29:r.getLogger().trace(`node found ..`,a[s-3]),this.$={id:a[s-3],descr:a[s-1],type:r.getType(a[s-2],a[s])};break;case 30:this.$=a[s-1]+a[s];break;case 31:this.$=a[s];break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],8:n},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:n},{6:r,7:[1,10],9:9,12:11,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},t(l,[2,3]),{1:[2,2]},t(l,[2,4]),t(l,[2,5]),{1:[2,6],6:r,12:21,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},{6:r,9:22,12:11,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},{6:u,7:d,10:23,11:f},t(p,[2,24],{18:17,19:18,14:27,16:[1,28],17:[1,29],20:s,23:c}),t(p,[2,19]),t(p,[2,21],{15:30,24:m}),t(p,[2,22]),t(p,[2,23]),t(h,[2,25]),t(h,[2,26]),t(h,[2,28],{20:[1,32]}),{21:[1,33]},{6:u,7:d,10:34,11:f},{1:[2,7],6:r,12:21,13:i,14:14,16:a,17:o,18:17,19:18,20:s,23:c},t(g,[2,14],{7:_,11:v}),t(y,[2,8]),t(y,[2,9]),t(y,[2,10]),t(p,[2,16],{15:37,24:m}),t(p,[2,17]),t(p,[2,18]),t(p,[2,20],{24:b}),t(h,[2,31]),{21:[1,39]},{22:[1,40]},t(g,[2,13],{7:_,11:v}),t(y,[2,11]),t(y,[2,12]),t(p,[2,15],{24:b}),t(h,[2,30]),{22:[1,41]},t(h,[2,27]),t(h,[2,29])],defaultActions:{2:[2,1],6:[2,2]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};x.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:return this.pushState(`shapeData`),t.yytext=``,24;case 1:return this.pushState(`shapeDataStr`),24;case 2:return this.popState(),24;case 3:return t.yytext=t.yytext.replace(/\n\s*/g,`
    `),24;case 4:return 24;case 5:this.popState();break;case 6:return e.getLogger().trace(`Found comment`,t.yytext),6;case 7:return 8;case 8:this.begin(`CLASS`);break;case 9:return this.popState(),17;case 10:this.popState();break;case 11:e.getLogger().trace(`Begin icon`),this.begin(`ICON`);break;case 12:return e.getLogger().trace(`SPACELINE`),6;case 13:return 7;case 14:return 16;case 15:e.getLogger().trace(`end icon`),this.popState();break;case 16:return e.getLogger().trace(`Exploding node`),this.begin(`NODE`),20;case 17:return e.getLogger().trace(`Cloud`),this.begin(`NODE`),20;case 18:return e.getLogger().trace(`Explosion Bang`),this.begin(`NODE`),20;case 19:return e.getLogger().trace(`Cloud Bang`),this.begin(`NODE`),20;case 20:return this.begin(`NODE`),20;case 21:return this.begin(`NODE`),20;case 22:return this.begin(`NODE`),20;case 23:return this.begin(`NODE`),20;case 24:return 13;case 25:return 23;case 26:return 11;case 27:this.begin(`NSTR2`);break;case 28:return`NODE_DESCR`;case 29:this.popState();break;case 30:e.getLogger().trace(`Starting NSTR`),this.begin(`NSTR`);break;case 31:return e.getLogger().trace(`description:`,t.yytext),`NODE_DESCR`;case 32:this.popState();break;case 33:return this.popState(),e.getLogger().trace(`node end ))`),`NODE_DEND`;case 34:return this.popState(),e.getLogger().trace(`node end )`),`NODE_DEND`;case 35:return this.popState(),e.getLogger().trace(`node end ...`,t.yytext),`NODE_DEND`;case 36:return this.popState(),e.getLogger().trace(`node end ((`),`NODE_DEND`;case 37:return this.popState(),e.getLogger().trace(`node end (-`),`NODE_DEND`;case 38:return this.popState(),e.getLogger().trace(`node end (-`),`NODE_DEND`;case 39:return this.popState(),e.getLogger().trace(`node end ((`),`NODE_DEND`;case 40:return this.popState(),e.getLogger().trace(`node end ((`),`NODE_DEND`;case 41:return e.getLogger().trace(`Long description:`,t.yytext),21;case 42:return e.getLogger().trace(`Long description:`,t.yytext),21}},`anonymous`),rules:[/^(?:@\{)/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^\"]+)/i,/^(?:[^}^"]+)/i,/^(?:\})/i,/^(?:\s*%%.*)/i,/^(?:kanban\b)/i,/^(?::::)/i,/^(?:.+)/i,/^(?:\n)/i,/^(?:::icon\()/i,/^(?:[\s]+[\n])/i,/^(?:[\n]+)/i,/^(?:[^\)]+)/i,/^(?:\))/i,/^(?:-\))/i,/^(?:\(-)/i,/^(?:\)\))/i,/^(?:\))/i,/^(?:\(\()/i,/^(?:\{\{)/i,/^(?:\()/i,/^(?:\[)/i,/^(?:[\s]+)/i,/^(?:[^\(\[\n\)\{\}@]+)/i,/^(?:$)/i,/^(?:["][`])/i,/^(?:[^`"]+)/i,/^(?:[`]["])/i,/^(?:["])/i,/^(?:[^"]+)/i,/^(?:["])/i,/^(?:[\)]\))/i,/^(?:[\)])/i,/^(?:[\]])/i,/^(?:\}\})/i,/^(?:\(-)/i,/^(?:-\))/i,/^(?:\(\()/i,/^(?:\()/i,/^(?:[^\)\]\(\}]+)/i,/^(?:.+(?!\(\())/i],conditions:{shapeDataEndBracket:{rules:[],inclusive:!1},shapeDataStr:{rules:[2,3],inclusive:!1},shapeData:{rules:[1,4,5],inclusive:!1},CLASS:{rules:[9,10],inclusive:!1},ICON:{rules:[14,15],inclusive:!1},NSTR2:{rules:[28,29],inclusive:!1},NSTR:{rules:[31,32],inclusive:!1},NODE:{rules:[27,30,33,34,35,36,37,38,39,40,41,42],inclusive:!1},INITIAL:{rules:[0,6,7,8,11,12,13,16,17,18,19,20,21,22,23,24,25,26],inclusive:!0}}}})();function S(){this.yy={}}return e(S,`Parser`),S.prototype=x,x.Parser=S,new S})();g.parser=g;var _=g,v=[],y=[],b=0,x={},S=e(()=>{v=[],y=[],b=0,x={}},`clear`),C=e(e=>{if(v.length===0)return null;let t=v[0].level,n=null;for(let e=v.length-1;e>=0;e--)if(v[e].level===t&&!n&&(n=v[e]),v[e].levelt.parentId===e.id);for(let n of i){let i={id:n.id,parentId:e.id,label:c(n.label??``,r),labelType:`markdown`,isGroup:!1,ticket:n?.ticket,priority:n?.priority,assigned:n?.assigned,icon:n?.icon,shape:`kanbanItem`,level:n.level,rx:5,ry:5,cssStyles:[`text-align: left`]};t.push(i)}}return{nodes:t,edges:e,other:{},config:s()}},`getData`),E=e((e,t,n,r,a)=>{let o=s(),l=o.mindmap?.padding??i.mindmap.padding;switch(r){case D.ROUNDED_RECT:case D.RECT:case D.HEXAGON:l*=2}let u={id:c(t,o)||`kbn`+b++,level:e,label:c(n,o),width:o.mindmap?.maxNodeWidth??i.mindmap.maxNodeWidth,padding:l,isGroup:!1};if(a!==void 0){let e;e=a.includes(` +`)?a+` +`:`{ +`+a+` +}`;let t=m(e,{schema:h});if(t.shape&&(t.shape!==t.shape.toLowerCase()||t.shape.includes(`_`)))throw Error(`No such shape: ${t.shape}. Shape names should be lowercase.`);t?.shape&&t.shape===`kanbanItem`&&(u.shape=t?.shape),t?.label&&(u.label=t?.label),t?.icon&&(u.icon=t?.icon.toString()),t?.assigned&&(u.assigned=t?.assigned.toString()),t?.ticket&&(u.ticket=t?.ticket.toString()),t?.priority&&(u.priority=t?.priority)}let d=C(e);d?u.parentId=d.id||`kbn`+b++:y.push(u),v.push(u)},`addNode`),D={DEFAULT:0,NO_BORDER:0,ROUNDED_RECT:1,RECT:2,CIRCLE:3,CLOUD:4,BANG:5,HEXAGON:6},O={clear:S,addNode:E,getSections:w,getData:T,nodeType:D,getType:e((e,n)=>{switch(t.debug(`In get type`,e,n),e){case`[`:return D.RECT;case`(`:return n===`)`?D.ROUNDED_RECT:D.CLOUD;case`((`:return D.CIRCLE;case`)`:return D.CLOUD;case`))`:return D.BANG;case`{{`:return D.HEXAGON;default:return D.DEFAULT}},`getType`),setElementForId:e((e,t)=>{x[e]=t},`setElementForId`),decorateNode:e(e=>{if(!e)return;let t=s(),n=v[v.length-1];e.icon&&(n.icon=c(e.icon,t)),e.class&&(n.cssClasses=c(e.class,t))},`decorateNode`),type2Str:e(e=>{switch(e){case D.DEFAULT:return`no-border`;case D.RECT:return`rect`;case D.ROUNDED_RECT:return`rounded-rect`;case D.CIRCLE:return`circle`;case D.CLOUD:return`cloud`;case D.BANG:return`bang`;case D.HEXAGON:return`hexgon`;default:return`no-border`}},`type2Str`),getLogger:e(()=>t,`getLogger`),getElementById:e(e=>x[e],`getElementById`)},k={draw:e(async(e,r,a,o)=>{t.debug(`Rendering kanban diagram +`+e);let c=o.db.getData(),u=s();u.htmlLabels=!1;let m=l(r);for(let e of c.nodes)e.domId=`${r}-${e.id}`;let h=m.append(`g`);h.attr(`class`,`sections`);let g=m.append(`g`);g.attr(`class`,`items`);let _=c.nodes.filter(e=>e.isGroup),v=0,y=[],b=25;for(let e of _){let t=u?.kanban?.sectionWidth||200;v+=1,e.x=t*v+(v-1)*10/2,e.width=t,e.y=0,e.height=t*3,e.rx=5,e.ry=5,e.cssClasses=e.cssClasses+` section-`+v;let n=await p(h,e);b=Math.max(b,n?.labelBBox?.height),y.push(n)}let x=0;for(let e of _){let t=y[x];x+=1;let n=u?.kanban?.sectionWidth||200,r=-n*3/2+b,i=r,a=c.nodes.filter(t=>t.parentId===e.id);for(let t of a){if(t.isGroup)throw Error(`Groups within groups are not allowed in Kanban diagrams`);t.x=e.x,t.width=n-1.5*10;let r=(await d(g,t,{config:u})).node().getBBox();t.y=i+r.height/2,await f(t),i=t.y+r.height/2+10/2}let o=t.cluster.select(`rect`),s=Math.max(i-r+30,50)+(b-25);o.attr(`height`,s)}n(void 0,m,u.mindmap?.padding??i.kanban.padding,u.mindmap?.useMaxWidth??i.kanban.useMaxWidth)},`draw`)},A=e(t=>{let n=``;for(let e=0;et.darkMode?r(e,n):o(e,n),`adjuster`);for(let e=0;e` + .edge { + stroke-width: 3; + } + ${A(e)} + .section-root rect, .section-root path, .section-root circle, .section-root polygon { + fill: ${e.git0}; + } + .section-root text { + fill: ${e.gitBranchLabel0}; + } + .icon-container { + height:100%; + display: flex; + justify-content: center; + align-items: center; + } + .edge { + fill: none; + } + .cluster-label, .label { + color: ${e.textColor}; + fill: ${e.textColor}; + } + .kanban-label { + dy: 1em; + alignment-baseline: middle; + text-anchor: middle; + dominant-baseline: middle; + text-align: center; + } + ${u()} +`,`getStyles`)};export{j as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/katex-B7rAX3Vi.js b/dist-desktop/assets/katex-B7rAX3Vi.js new file mode 100644 index 0000000..e8497db --- /dev/null +++ b/dist-desktop/assets/katex-B7rAX3Vi.js @@ -0,0 +1,257 @@ +var e=class e extends Error{constructor(t,n){var r=`KaTeX parse error: `+t,i,a,o=n&&n.loc;if(o&&o.start<=o.end){var s=o.lexer.input;i=o.start,a=o.end,i===s.length?r+=` at end of input: `:r+=` at position `+(i+1)+`: `;var c=s.slice(i,a).replace(/[^]/g,`$&̲`),l=i>15?`…`+s.slice(i-15,i):s.slice(0,i),u=a+15e.replace(t,`-$1`).toLowerCase(),r={"&":`&`,">":`>`,"<":`<`,'"':`"`,"'":`'`},i=/[&><"']/g,a=e=>String(e).replace(i,e=>r[e]),o=e=>e.type===`ordgroup`||e.type===`color`?e.body.length===1?o(e.body[0]):e:e.type===`font`?o(e.body):e,s=new Set([`mathord`,`textord`,`atom`]),c=e=>s.has(o(e).type),l=e=>{var t=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(e);return t?t[2]!==`:`||!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(t[1])?null:t[1].toLowerCase():`_relative`},u={displayMode:{type:`boolean`,description:`Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.`,cli:`-d, --display-mode`},output:{type:{enum:[`htmlAndMathml`,`html`,`mathml`]},description:`Determines the markup language of the output.`,cli:`-F, --format `},leqno:{type:`boolean`,description:`Render display math in leqno style (left-justified tags).`},fleqn:{type:`boolean`,description:`Render display math flush left.`},throwOnError:{type:`boolean`,default:!0,cli:`-t, --no-throw-on-error`,cliDescription:`Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error.`},errorColor:{type:`string`,default:`#cc0000`,cli:`-c, --error-color `,cliDescription:`A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.`,cliProcessor:e=>`#`+e},macros:{type:`object`,cli:`-m, --macro `,cliDescription:`Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).`,cliDefault:[],cliProcessor:(e,t)=>(t.push(e),t)},minRuleThickness:{type:`number`,description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:e=>Math.max(0,e),cli:`--min-rule-thickness `,cliProcessor:parseFloat},colorIsTextColor:{type:`boolean`,description:`Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.`,cli:`-b, --color-is-text-color`},strict:{type:[{enum:[`warn`,`ignore`,`error`]},`boolean`,`function`],description:`Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.`,cli:`-S, --strict`,cliDefault:!1},trust:{type:[`boolean`,`function`],description:`Trust the input, enabling all HTML features such as \\url.`,cli:`-T, --trust`},maxSize:{type:`number`,default:1/0,description:`If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large`,processor:e=>Math.max(0,e),cli:`-s, --max-size `,cliProcessor:parseInt},maxExpand:{type:`number`,default:1e3,description:`Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.`,processor:e=>Math.max(0,e),cli:`-e, --max-expand `,cliProcessor:e=>e===`Infinity`?1/0:parseInt(e)},globalGroup:{type:`boolean`,cli:!1}};function d(e){if(typeof e!=`string`)return e.enum[0];switch(e){case`boolean`:return!1;case`string`:return``;case`number`:return 0;case`object`:return{};default:throw Error(`Unexpected schema type; settings must declare an explicit default.`)}}function f(e){return e.default===void 0?d(Array.isArray(e.type)?e.type[0]:e.type):e.default}function p(e,t,n,r){var i=n[t];e[t]=i===void 0?f(r):r.processor?r.processor(i):i}var m=class{constructor(e){e===void 0&&(e={}),this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e||={};for(var t of Object.keys(u)){var n=u[t];n&&p(this,t,e,n)}}reportNonstrict(t,n,r){var i=this.strict;if(typeof i==`function`&&(i=i(t,n,r)),!(!i||i===`ignore`)){if(i===!0||i===`error`)throw new e(`LaTeX-incompatible input and strict mode is set to 'error': `+(n+` [`+t+`]`),r);i===`warn`?typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to 'warn': `+(n+` [`+t+`]`)):typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to `+(`unrecognized '`+i+`': `+n+` [`+t+`]`))}}useStrictBehavior(e,t,n){var r=this.strict;if(typeof r==`function`)try{r=r(e,t,n)}catch{r=`error`}return!r||r===`ignore`?!1:r===!0||r===`error`?!0:r===`warn`?(typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to 'warn': `+(t+` [`+e+`]`)),!1):(typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to `+(`unrecognized '`+r+`': `+t+` [`+e+`]`)),!1)}isTrusted(e){if(`url`in e&&e.url&&!e.protocol){var t=l(e.url);if(t==null)return!1;e.protocol=t}return!!(typeof this.trust==`function`?this.trust(e):this.trust)}},h=class{constructor(e,t,n){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=t,this.cramped=n}sup(){return w[ee[this.id]]}sub(){return w[T[this.id]]}fracNum(){return w[te[this.id]]}fracDen(){return w[ne[this.id]]}cramp(){return w[re[this.id]]}text(){return w[ie[this.id]]}isTight(){return this.size>=2}},g=0,_=1,v=2,y=3,b=4,x=5,S=6,C=7,w=[new h(g,0,!1),new h(_,0,!0),new h(v,1,!1),new h(y,1,!0),new h(b,2,!1),new h(x,2,!0),new h(S,3,!1),new h(C,3,!0)],ee=[b,x,b,x,S,C,S,C],T=[x,x,x,x,C,C,C,C],te=[v,y,b,x,S,C,S,C],ne=[y,y,x,x,C,C,C,C],re=[_,_,y,y,x,x,C,C],ie=[g,_,v,y,v,y,v,y],E={DISPLAY:w[g],TEXT:w[v],SCRIPT:w[b],SCRIPTSCRIPT:w[S]},ae=[{name:`latin`,blocks:[[256,591],[768,879]]},{name:`cyrillic`,blocks:[[1024,1279]]},{name:`armenian`,blocks:[[1328,1423]]},{name:`brahmic`,blocks:[[2304,4255]]},{name:`georgian`,blocks:[[4256,4351]]},{name:`cjk`,blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:`hangul`,blocks:[[44032,55215]]}];function oe(e){for(var t=0;t=i[0]&&e<=i[1])return n.name}return null}var se=[];ae.forEach(e=>e.blocks.forEach(e=>se.push(...e)));function ce(e){for(var t=0;t=se[t]&&e<=se[t+1])return!0;return!1}var D=e=>e+` `+e,le=80,ue=function(e,t){return`M95,`+(622+e+t)+` +c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14 +c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54 +c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10 +s173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429 +c69,-144,104.5,-217.7,106.5,-221 +l`+e/2.075+` -`+e+` +c5.3,-9.3,12,-14,20,-14 +H400000v`+(40+e)+`H845.2724 +s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7 +c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z +M`+(834+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},de=function(e,t){return`M263,`+(601+e+t)+`c0.7,0,18,39.7,52,119 +c34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120 +c340,-704.7,510.7,-1060.3,512,-1067 +l`+e/2.084+` -`+e+` +c4.7,-7.3,11,-11,19,-11 +H40000v`+(40+e)+`H1012.3 +s-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232 +c-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1 +s-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26 +c-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z +M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},fe=function(e,t){return`M983 `+(10+e+t)+` +l`+e/3.13+` -`+e+` +c4,-6.7,10,-10,18,-10 H400000v`+(40+e)+` +H1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7 +s-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744 +c-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30 +c26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722 +c56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5 +c53.7,-170.3,84.5,-266.8,92.5,-289.5z +M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},pe=function(e,t){return`M424,`+(2398+e+t)+` +c-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514 +c0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20 +s-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121 +s209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081 +l`+e/4.223+` -`+e+`c4,-6.7,10,-10,18,-10 H400000 +v`+(40+e)+`H1014.6 +s-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185 +c-2,6,-10,9,-24,9 +c-8,0,-12,-0.7,-12,-2z M`+(1001+e)+` `+t+` +h400000v`+(40+e)+`h-400000z`},me=function(e,t){return`M473,`+(2713+e+t)+` +c339.3,-1799.3,509.3,-2700,510,-2702 l`+e/5.298+` -`+e+` +c3.3,-7.3,9.3,-11,18,-11 H400000v`+(40+e)+`H1017.7 +s-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9 +c-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200 +c0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26 +s76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104, +606zM`+(1001+e)+` `+t+`h400000v`+(40+e)+`H1017.7z`},he=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},ge=function(e,t,n){var r=n-54-t-e;return`M702 `+(e+t)+`H400000`+(40+e)+` +H742v`+r+`l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1 +h-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170 +c-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667 +219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},_e=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=ue(t,le);break;case`sqrtSize1`:r=de(t,le);break;case`sqrtSize2`:r=fe(t,le);break;case`sqrtSize3`:r=pe(t,le);break;case`sqrtSize4`:r=me(t,le);break;case`sqrtTall`:r=ge(t,le,n)}return r},ve=function(e,t){switch(e){case`⎜`:return D(`M291 0 H417 V`+t+` H291z`);case`∣`:return D(`M145 0 H188 V`+t+` H145z`);case`∥`:return D(`M145 0 H188 V`+t+` H145z`)+D(`M367 0 H410 V`+t+` H367z`);case`⎟`:return D(`M457 0 H583 V`+t+` H457z`);case`⎢`:return D(`M319 0 H403 V`+t+` H319z`);case`⎥`:return D(`M263 0 H347 V`+t+` H263z`);case`⎪`:return D(`M384 0 H504 V`+t+` H384z`);case`⏐`:return D(`M312 0 H355 V`+t+` H312z`);case`‖`:return D(`M257 0 H300 V`+t+` H257z`)+D(`M478 0 H521 V`+t+` H478z`);default:return``}},ye={doubleleftarrow:`M262 157 +l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3 + 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28 + 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5 +c2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5 + 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87 +-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7 +-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z +m8 0v40h399730v-40zm0 194v40h399730v-40z`,doublerightarrow:`M399738 392l +-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5 + 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88 +-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68 +-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18 +-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782 +c-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3 +-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z`,leftarrow:`M400000 241H110l3-3c68.7-52.7 113.7-120 + 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8 +-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247 +c-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208 + 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3 + 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202 + l-3-3h399890zM100 241v40h399900v-40z`,leftbrace:`M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117 +-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7 + 5-6 9-10 13-.7 1-7.3 1-20 1H6z`,leftbraceunder:`M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13 + 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688 + 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7 +-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z`,leftgroup:`M400000 80 +H435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0 + 435 0h399565z`,leftgroupunder:`M400000 262 +H435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219 + 435 219h399565z`,leftharpoon:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3 +-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5 +-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7 +-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z`,leftharpoonplus:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5 + 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3 +-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7 +-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z +m0 0v40h400000v-40z`,leftharpoondown:`M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333 + 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5 + 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667 +-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z`,leftharpoondownplus:`M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12 + 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7 +-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0 +v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,lefthook:`M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5 +-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3 +-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21 + 71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:D(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:D(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:D(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:D(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23 +-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8 +c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3 + 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:D(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334 +c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14 +-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7 + 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11 + 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z`,midbraceunder:`M199572 214 +c100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14 + 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3 + 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0 +-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z`,oiintSize1:`M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6 +-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z +m368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8 +60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z`,oiintSize2:`M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8 +-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z +m502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2 +c0 110 84 276 504 276s502.4-166 502.4-276z`,oiiintSize1:`M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6 +-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z +m525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0 +85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z`,oiiintSize2:`M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8 +-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z +m770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1 +c0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z`,rightarrow:`M0 241v40h399891c-47.3 35.3-84 78-110 128 +-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 + 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 + 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85 +-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5 +-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67 + 151.7 139 205zm0 0v40h399900v-40z`,rightbrace:`M400000 542l +-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5 +s-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1 +c124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z`,rightbraceunder:`M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3 + 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237 +-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z`,rightgroup:`M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0 + 3-1 3-3v-38c-76-158-257-219-435-219H0z`,rightgroupunder:`M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18 + 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z`,rightharpoon:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3 +-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2 +-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 + 69.2 92 94.5zm0 0v40h399900v-40z`,rightharpoonplus:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11 +-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7 + 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z +m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,rightharpoondown:`M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8 + 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5 +-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95 +-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z`,rightharpoondownplus:`M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8 + 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 + 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3 +-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z +m0-194v40h400000v-40zm0 0v40h400000v-40z`,righthook:`M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3 + 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0 +-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21 + 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:D(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:D(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:D(`M399995 440 h-120 V150 H0 v-120 H399995z`),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23 + 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32 +-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142 +-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,twoheadleftarrow:`M0 167c68 40 + 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69 +-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3 +-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19 +-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101 + 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z`,twoheadrightarrow:`M400000 167 +c-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3 + 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42 + 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333 +-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70 + 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z`,tilde1:`M200 55.538c-77 0-168 73.953-177 73.953-3 0-7 +-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0 + 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0 + 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128 +-68.267.847-113-73.952-191-73.952z`,tilde2:`M344 55.266c-142 0-300.638 81.316-311.5 86.418 +-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9 + 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114 +c1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751 + 181.476 676 181.476c-149 0-189-126.21-332-126.21z`,tilde3:`M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457 +-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0 + 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697 + 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696 + -338 0-409-156.573-744-156.573z`,tilde4:`M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345 +-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409 + 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9 + 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409 + -175.236-744-175.236z`,vec:`M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5 +3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11 +10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63 +-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1 +-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59 +H213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359 +c-16-25.333-24-45-24-59z`,widehat1:`M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22 +c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z`,widehat2:`M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat3:`M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat4:`M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widecheck1:`M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1, +-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z`,widecheck2:`M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck3:`M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck4:`M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,baraboveleftarrow:`M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202 +c4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5 +c-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130 +s-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47 +121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6 +s2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11 +c0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z +M100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z`,rightarrowabovebar:`M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32 +-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0 +13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39 +-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5 +-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5 +-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67 +151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z`,baraboveshortleftharpoon:`M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11 +c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17 +c2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21 +c-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40 +c-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z +M0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z`,rightharpoonaboveshortbar:`M0,241 l0,40c399126,0,399993,0,399993,0 +c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199, +-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6 +c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z +M0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z`,shortbaraboveleftharpoon:`M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11 +c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9, +1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7, +-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z +M93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z`,shortrightharpoonabovebar:`M53,241l0,40c398570,0,399437,0,399437,0 +c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199, +-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6 +c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z +M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},be=function(e,t){switch(e){case`lbrack`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v1759 v84 h347 v-84 +H403z M403 1759 V0 H319 V1759 v`+t+` v1759 v84 h84z`;case`rbrack`:return`M347 1759 V0 H0 V84 H263 V1759 v`+t+` v1759 H0 v84 H347z +M347 1759 V0 H263 V1759 v`+t+` v1759 h84z`;case`vert`:return`M145 15 v585 v`+t+` v585 c2.667,10,9.667,15,21,15 +c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15 +c-10,0,-16.667,5,-20,15z M188 15 H145 v585 v`+t+` v585 h43z`;case`doublevert`:return`M145 15 v585 v`+t+` v585 c2.667,10,9.667,15,21,15 +c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15 +c-10,0,-16.667,5,-20,15z M188 15 H145 v585 v`+t+` v585 h43z +M367 15 v585 v`+t+` v585 c2.667,10,9.667,15,21,15 +c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15 +c-10,0,-16.667,5,-20,15z M410 15 H367 v585 v`+t+` v585 h43z`;case`lfloor`:return`M319 602 V0 H403 V602 v`+t+` v1715 h263 v84 H319z +MM319 602 V0 H403 V602 v`+t+` v1715 H319z`;case`rfloor`:return`M319 602 V0 H403 V602 v`+t+` v1799 H0 v-84 H319z +MM319 602 V0 H403 V602 v`+t+` v1715 H319z`;case`lceil`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v602 h84z +M403 1759 V0 H319 V1759 v`+t+` v602 h84z`;case`rceil`:return`M347 1759 V0 H0 V84 H263 V1759 v`+t+` v602 h84z +M347 1759 V0 h-84 V1759 v`+t+` v602 h84z`;case`lparen`:return`M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1 +c-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349, +-36,557 l0,`+(t+84)+`c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210, +949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9 +c0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5, +-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189 +l0,-`+(t+92)+`c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3, +-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z`;case`rparen`:return`M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3, +63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5 +c11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0,`+(t+9)+` +c-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664 +c-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11 +c0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17 +c242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558 +l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7, +-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw Error(`Unknown stretchy delimiter.`)}};function xe(e){return`toText`in e}var Se=class{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t{if(xe(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},Ce={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},we={ex:!0,em:!0,mu:!0},Te=function(e){return typeof e!=`string`&&(e=e.unit),e in Ce||e in we||e===`ex`},O=function(t,n){var r;if(t.unit in Ce)r=Ce[t.unit]/n.fontMetrics().ptPerEm/n.sizeMultiplier;else if(t.unit===`mu`)r=n.fontMetrics().cssEmPerMu;else{var i=n.style.isTight()?n.havingStyle(n.style.text()):n;if(t.unit===`ex`)r=i.fontMetrics().xHeight;else if(t.unit===`em`)r=i.fontMetrics().quad;else throw new e(`Invalid unit: '`+t.unit+`'`);i!==n&&(r*=i.sizeMultiplier/n.sizeMultiplier)}return Math.min(t.number*r,n.maxSize)},k=function(e){return+e.toFixed(4)+`em`},Ee=function(e){return e.filter(e=>e).join(` `)},De=function(e){var t=``;for(var r of Object.keys(e)){var i=e[r];i!==void 0&&(t+=n(r)+`:`+i+`;`)}return t},Oe=function(e,t,n){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=n||{},t){t.style.isTight()&&this.classes.push(`mtight`);var r=t.getColor();r&&(this.style.color=r)}},ke=function(e){var t=document.createElement(e);t.className=Ee(this.classes),Object.assign(t.style,this.style);for(var n of Object.keys(this.attributes))t.setAttribute(n,this.attributes[n]);for(var r=0;r/=\x00-\x1f]/,je=function(t){var n=`<`+t;this.classes.length&&(n+=` class="`+a(Ee(this.classes))+`"`);var r=De(this.style);r&&(n+=` style="`+a(r)+`"`);for(var i of Object.keys(this.attributes)){if(Ae.test(i))throw new e(`Invalid attribute name '`+i+`'`);n+=` `+i+`="`+a(this.attributes[i])+`"`}n+=`>`;for(var o=0;o`,n},Me=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,Oe.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return ke.call(this,`span`)}toMarkup(){return je.call(this,`span`)}},Ne=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,Oe.call(this,t,r),this.children=n||[],this.setAttribute(`href`,e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return ke.call(this,`a`)}toMarkup(){return je.call(this,`a`)}},Pe=class{constructor(e,t,n){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=[`mord`],this.height=0,this.depth=0,this.maxFontSize=0,this.style=n}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement(`img`);return e.src=this.src,e.alt=this.alt,e.className=`mord`,Object.assign(e.style,this.style),e}toMarkup(){var e=``+a(this.alt)+``,e}},Fe={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},Ie=class{constructor(e,t,n,r,i,a,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=n||0,this.italic=r||0,this.skew=i||0,this.width=a||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var c=oe(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=Fe[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;return this.italic>0&&(t=document.createElement(`span`),t.style.marginRight=k(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=Ee(this.classes)),Object.keys(this.style).length>0&&(t||=document.createElement(`span`),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t=`0&&(n+=`margin-right:`+k(this.italic)+`;`),n+=De(this.style),n&&(e=!0,t+=` style="`+a(n)+`"`);var r=a(this.text);return e?(t+=`>`,t+=r,t+=``,t):r}},Le=class{constructor(e,t){this.children=void 0,this.attributes=void 0,this.children=e||[],this.attributes=t||{}}toNode(){var e=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);for(var t of Object.keys(this.attributes))e.setAttribute(t,this.attributes[t]);for(var n=0;n`;for(var n=0;n`,e}},Re=class{constructor(e,t){this.pathName=void 0,this.alternate=void 0,this.pathName=e,this.alternate=t}toNode(){var e=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);return this.alternate?e.setAttribute(`d`,this.alternate):e.setAttribute(`d`,ye[this.pathName]),e}toMarkup(){return this.alternate?``:``}},ze=class{constructor(e){this.attributes=void 0,this.attributes=e||{}}toNode(){var e=document.createElementNS(`http://www.w3.org/2000/svg`,`line`);for(var t of Object.keys(this.attributes))e.setAttribute(t,this.attributes[t]);return e}toMarkup(){var e=``,e}};function Be(e){if(e instanceof Ie)return e;throw Error(`Expected symbolNode but got `+String(e)+`.`)}function Ve(e){if(e instanceof Me)return e;throw Error(`Expected span but got `+String(e)+`.`)}var He=e=>e instanceof Me||e instanceof Ne||e instanceof Se,Ue={"AMS-Regular":{32:[0,0,0,0,.25],65:[0,.68889,0,0,.72222],66:[0,.68889,0,0,.66667],67:[0,.68889,0,0,.72222],68:[0,.68889,0,0,.72222],69:[0,.68889,0,0,.66667],70:[0,.68889,0,0,.61111],71:[0,.68889,0,0,.77778],72:[0,.68889,0,0,.77778],73:[0,.68889,0,0,.38889],74:[.16667,.68889,0,0,.5],75:[0,.68889,0,0,.77778],76:[0,.68889,0,0,.66667],77:[0,.68889,0,0,.94445],78:[0,.68889,0,0,.72222],79:[.16667,.68889,0,0,.77778],80:[0,.68889,0,0,.61111],81:[.16667,.68889,0,0,.77778],82:[0,.68889,0,0,.72222],83:[0,.68889,0,0,.55556],84:[0,.68889,0,0,.66667],85:[0,.68889,0,0,.72222],86:[0,.68889,0,0,.72222],87:[0,.68889,0,0,1],88:[0,.68889,0,0,.72222],89:[0,.68889,0,0,.72222],90:[0,.68889,0,0,.66667],107:[0,.68889,0,0,.55556],160:[0,0,0,0,.25],165:[0,.675,.025,0,.75],174:[.15559,.69224,0,0,.94666],240:[0,.68889,0,0,.55556],295:[0,.68889,0,0,.54028],710:[0,.825,0,0,2.33334],732:[0,.9,0,0,2.33334],770:[0,.825,0,0,2.33334],771:[0,.9,0,0,2.33334],989:[.08167,.58167,0,0,.77778],1008:[0,.43056,.04028,0,.66667],8245:[0,.54986,0,0,.275],8463:[0,.68889,0,0,.54028],8487:[0,.68889,0,0,.72222],8498:[0,.68889,0,0,.55556],8502:[0,.68889,0,0,.66667],8503:[0,.68889,0,0,.44445],8504:[0,.68889,0,0,.66667],8513:[0,.68889,0,0,.63889],8592:[-.03598,.46402,0,0,.5],8594:[-.03598,.46402,0,0,.5],8602:[-.13313,.36687,0,0,1],8603:[-.13313,.36687,0,0,1],8606:[.01354,.52239,0,0,1],8608:[.01354,.52239,0,0,1],8610:[.01354,.52239,0,0,1.11111],8611:[.01354,.52239,0,0,1.11111],8619:[0,.54986,0,0,1],8620:[0,.54986,0,0,1],8621:[-.13313,.37788,0,0,1.38889],8622:[-.13313,.36687,0,0,1],8624:[0,.69224,0,0,.5],8625:[0,.69224,0,0,.5],8630:[0,.43056,0,0,1],8631:[0,.43056,0,0,1],8634:[.08198,.58198,0,0,.77778],8635:[.08198,.58198,0,0,.77778],8638:[.19444,.69224,0,0,.41667],8639:[.19444,.69224,0,0,.41667],8642:[.19444,.69224,0,0,.41667],8643:[.19444,.69224,0,0,.41667],8644:[.1808,.675,0,0,1],8646:[.1808,.675,0,0,1],8647:[.1808,.675,0,0,1],8648:[.19444,.69224,0,0,.83334],8649:[.1808,.675,0,0,1],8650:[.19444,.69224,0,0,.83334],8651:[.01354,.52239,0,0,1],8652:[.01354,.52239,0,0,1],8653:[-.13313,.36687,0,0,1],8654:[-.13313,.36687,0,0,1],8655:[-.13313,.36687,0,0,1],8666:[.13667,.63667,0,0,1],8667:[.13667,.63667,0,0,1],8669:[-.13313,.37788,0,0,1],8672:[-.064,.437,0,0,1.334],8674:[-.064,.437,0,0,1.334],8705:[0,.825,0,0,.5],8708:[0,.68889,0,0,.55556],8709:[.08167,.58167,0,0,.77778],8717:[0,.43056,0,0,.42917],8722:[-.03598,.46402,0,0,.5],8724:[.08198,.69224,0,0,.77778],8726:[.08167,.58167,0,0,.77778],8733:[0,.69224,0,0,.77778],8736:[0,.69224,0,0,.72222],8737:[0,.69224,0,0,.72222],8738:[.03517,.52239,0,0,.72222],8739:[.08167,.58167,0,0,.22222],8740:[.25142,.74111,0,0,.27778],8741:[.08167,.58167,0,0,.38889],8742:[.25142,.74111,0,0,.5],8756:[0,.69224,0,0,.66667],8757:[0,.69224,0,0,.66667],8764:[-.13313,.36687,0,0,.77778],8765:[-.13313,.37788,0,0,.77778],8769:[-.13313,.36687,0,0,.77778],8770:[-.03625,.46375,0,0,.77778],8774:[.30274,.79383,0,0,.77778],8776:[-.01688,.48312,0,0,.77778],8778:[.08167,.58167,0,0,.77778],8782:[.06062,.54986,0,0,.77778],8783:[.06062,.54986,0,0,.77778],8785:[.08198,.58198,0,0,.77778],8786:[.08198,.58198,0,0,.77778],8787:[.08198,.58198,0,0,.77778],8790:[0,.69224,0,0,.77778],8791:[.22958,.72958,0,0,.77778],8796:[.08198,.91667,0,0,.77778],8806:[.25583,.75583,0,0,.77778],8807:[.25583,.75583,0,0,.77778],8808:[.25142,.75726,0,0,.77778],8809:[.25142,.75726,0,0,.77778],8812:[.25583,.75583,0,0,.5],8814:[.20576,.70576,0,0,.77778],8815:[.20576,.70576,0,0,.77778],8816:[.30274,.79383,0,0,.77778],8817:[.30274,.79383,0,0,.77778],8818:[.22958,.72958,0,0,.77778],8819:[.22958,.72958,0,0,.77778],8822:[.1808,.675,0,0,.77778],8823:[.1808,.675,0,0,.77778],8828:[.13667,.63667,0,0,.77778],8829:[.13667,.63667,0,0,.77778],8830:[.22958,.72958,0,0,.77778],8831:[.22958,.72958,0,0,.77778],8832:[.20576,.70576,0,0,.77778],8833:[.20576,.70576,0,0,.77778],8840:[.30274,.79383,0,0,.77778],8841:[.30274,.79383,0,0,.77778],8842:[.13597,.63597,0,0,.77778],8843:[.13597,.63597,0,0,.77778],8847:[.03517,.54986,0,0,.77778],8848:[.03517,.54986,0,0,.77778],8858:[.08198,.58198,0,0,.77778],8859:[.08198,.58198,0,0,.77778],8861:[.08198,.58198,0,0,.77778],8862:[0,.675,0,0,.77778],8863:[0,.675,0,0,.77778],8864:[0,.675,0,0,.77778],8865:[0,.675,0,0,.77778],8872:[0,.69224,0,0,.61111],8873:[0,.69224,0,0,.72222],8874:[0,.69224,0,0,.88889],8876:[0,.68889,0,0,.61111],8877:[0,.68889,0,0,.61111],8878:[0,.68889,0,0,.72222],8879:[0,.68889,0,0,.72222],8882:[.03517,.54986,0,0,.77778],8883:[.03517,.54986,0,0,.77778],8884:[.13667,.63667,0,0,.77778],8885:[.13667,.63667,0,0,.77778],8888:[0,.54986,0,0,1.11111],8890:[.19444,.43056,0,0,.55556],8891:[.19444,.69224,0,0,.61111],8892:[.19444,.69224,0,0,.61111],8901:[0,.54986,0,0,.27778],8903:[.08167,.58167,0,0,.77778],8905:[.08167,.58167,0,0,.77778],8906:[.08167,.58167,0,0,.77778],8907:[0,.69224,0,0,.77778],8908:[0,.69224,0,0,.77778],8909:[-.03598,.46402,0,0,.77778],8910:[0,.54986,0,0,.76042],8911:[0,.54986,0,0,.76042],8912:[.03517,.54986,0,0,.77778],8913:[.03517,.54986,0,0,.77778],8914:[0,.54986,0,0,.66667],8915:[0,.54986,0,0,.66667],8916:[0,.69224,0,0,.66667],8918:[.0391,.5391,0,0,.77778],8919:[.0391,.5391,0,0,.77778],8920:[.03517,.54986,0,0,1.33334],8921:[.03517,.54986,0,0,1.33334],8922:[.38569,.88569,0,0,.77778],8923:[.38569,.88569,0,0,.77778],8926:[.13667,.63667,0,0,.77778],8927:[.13667,.63667,0,0,.77778],8928:[.30274,.79383,0,0,.77778],8929:[.30274,.79383,0,0,.77778],8934:[.23222,.74111,0,0,.77778],8935:[.23222,.74111,0,0,.77778],8936:[.23222,.74111,0,0,.77778],8937:[.23222,.74111,0,0,.77778],8938:[.20576,.70576,0,0,.77778],8939:[.20576,.70576,0,0,.77778],8940:[.30274,.79383,0,0,.77778],8941:[.30274,.79383,0,0,.77778],8994:[.19444,.69224,0,0,.77778],8995:[.19444,.69224,0,0,.77778],9416:[.15559,.69224,0,0,.90222],9484:[0,.69224,0,0,.5],9488:[0,.69224,0,0,.5],9492:[0,.37788,0,0,.5],9496:[0,.37788,0,0,.5],9585:[.19444,.68889,0,0,.88889],9586:[.19444,.74111,0,0,.88889],9632:[0,.675,0,0,.77778],9633:[0,.675,0,0,.77778],9650:[0,.54986,0,0,.72222],9651:[0,.54986,0,0,.72222],9654:[.03517,.54986,0,0,.77778],9660:[0,.54986,0,0,.72222],9661:[0,.54986,0,0,.72222],9664:[.03517,.54986,0,0,.77778],9674:[.11111,.69224,0,0,.66667],9733:[.19444,.69224,0,0,.94445],10003:[0,.69224,0,0,.83334],10016:[0,.69224,0,0,.83334],10731:[.11111,.69224,0,0,.66667],10846:[.19444,.75583,0,0,.61111],10877:[.13667,.63667,0,0,.77778],10878:[.13667,.63667,0,0,.77778],10885:[.25583,.75583,0,0,.77778],10886:[.25583,.75583,0,0,.77778],10887:[.13597,.63597,0,0,.77778],10888:[.13597,.63597,0,0,.77778],10889:[.26167,.75726,0,0,.77778],10890:[.26167,.75726,0,0,.77778],10891:[.48256,.98256,0,0,.77778],10892:[.48256,.98256,0,0,.77778],10901:[.13667,.63667,0,0,.77778],10902:[.13667,.63667,0,0,.77778],10933:[.25142,.75726,0,0,.77778],10934:[.25142,.75726,0,0,.77778],10935:[.26167,.75726,0,0,.77778],10936:[.26167,.75726,0,0,.77778],10937:[.26167,.75726,0,0,.77778],10938:[.26167,.75726,0,0,.77778],10949:[.25583,.75583,0,0,.77778],10950:[.25583,.75583,0,0,.77778],10955:[.28481,.79383,0,0,.77778],10956:[.28481,.79383,0,0,.77778],57350:[.08167,.58167,0,0,.22222],57351:[.08167,.58167,0,0,.38889],57352:[.08167,.58167,0,0,.77778],57353:[0,.43056,.04028,0,.66667],57356:[.25142,.75726,0,0,.77778],57357:[.25142,.75726,0,0,.77778],57358:[.41951,.91951,0,0,.77778],57359:[.30274,.79383,0,0,.77778],57360:[.30274,.79383,0,0,.77778],57361:[.41951,.91951,0,0,.77778],57366:[.25142,.75726,0,0,.77778],57367:[.25142,.75726,0,0,.77778],57368:[.25142,.75726,0,0,.77778],57369:[.25142,.75726,0,0,.77778],57370:[.13597,.63597,0,0,.77778],57371:[.13597,.63597,0,0,.77778]},"Caligraphic-Regular":{32:[0,0,0,0,.25],65:[0,.68333,0,.19445,.79847],66:[0,.68333,.03041,.13889,.65681],67:[0,.68333,.05834,.13889,.52653],68:[0,.68333,.02778,.08334,.77139],69:[0,.68333,.08944,.11111,.52778],70:[0,.68333,.09931,.11111,.71875],71:[.09722,.68333,.0593,.11111,.59487],72:[0,.68333,.00965,.11111,.84452],73:[0,.68333,.07382,0,.54452],74:[.09722,.68333,.18472,.16667,.67778],75:[0,.68333,.01445,.05556,.76195],76:[0,.68333,0,.13889,.68972],77:[0,.68333,0,.13889,1.2009],78:[0,.68333,.14736,.08334,.82049],79:[0,.68333,.02778,.11111,.79611],80:[0,.68333,.08222,.08334,.69556],81:[.09722,.68333,0,.11111,.81667],82:[0,.68333,0,.08334,.8475],83:[0,.68333,.075,.13889,.60556],84:[0,.68333,.25417,0,.54464],85:[0,.68333,.09931,.08334,.62583],86:[0,.68333,.08222,0,.61278],87:[0,.68333,.08222,.08334,.98778],88:[0,.68333,.14643,.13889,.7133],89:[.09722,.68333,.08222,.08334,.66834],90:[0,.68333,.07944,.13889,.72473],160:[0,0,0,0,.25]},"Fraktur-Regular":{32:[0,0,0,0,.25],33:[0,.69141,0,0,.29574],34:[0,.69141,0,0,.21471],38:[0,.69141,0,0,.73786],39:[0,.69141,0,0,.21201],40:[.24982,.74947,0,0,.38865],41:[.24982,.74947,0,0,.38865],42:[0,.62119,0,0,.27764],43:[.08319,.58283,0,0,.75623],44:[0,.10803,0,0,.27764],45:[.08319,.58283,0,0,.75623],46:[0,.10803,0,0,.27764],47:[.24982,.74947,0,0,.50181],48:[0,.47534,0,0,.50181],49:[0,.47534,0,0,.50181],50:[0,.47534,0,0,.50181],51:[.18906,.47534,0,0,.50181],52:[.18906,.47534,0,0,.50181],53:[.18906,.47534,0,0,.50181],54:[0,.69141,0,0,.50181],55:[.18906,.47534,0,0,.50181],56:[0,.69141,0,0,.50181],57:[.18906,.47534,0,0,.50181],58:[0,.47534,0,0,.21606],59:[.12604,.47534,0,0,.21606],61:[-.13099,.36866,0,0,.75623],63:[0,.69141,0,0,.36245],65:[0,.69141,0,0,.7176],66:[0,.69141,0,0,.88397],67:[0,.69141,0,0,.61254],68:[0,.69141,0,0,.83158],69:[0,.69141,0,0,.66278],70:[.12604,.69141,0,0,.61119],71:[0,.69141,0,0,.78539],72:[.06302,.69141,0,0,.7203],73:[0,.69141,0,0,.55448],74:[.12604,.69141,0,0,.55231],75:[0,.69141,0,0,.66845],76:[0,.69141,0,0,.66602],77:[0,.69141,0,0,1.04953],78:[0,.69141,0,0,.83212],79:[0,.69141,0,0,.82699],80:[.18906,.69141,0,0,.82753],81:[.03781,.69141,0,0,.82699],82:[0,.69141,0,0,.82807],83:[0,.69141,0,0,.82861],84:[0,.69141,0,0,.66899],85:[0,.69141,0,0,.64576],86:[0,.69141,0,0,.83131],87:[0,.69141,0,0,1.04602],88:[0,.69141,0,0,.71922],89:[.18906,.69141,0,0,.83293],90:[.12604,.69141,0,0,.60201],91:[.24982,.74947,0,0,.27764],93:[.24982,.74947,0,0,.27764],94:[0,.69141,0,0,.49965],97:[0,.47534,0,0,.50046],98:[0,.69141,0,0,.51315],99:[0,.47534,0,0,.38946],100:[0,.62119,0,0,.49857],101:[0,.47534,0,0,.40053],102:[.18906,.69141,0,0,.32626],103:[.18906,.47534,0,0,.5037],104:[.18906,.69141,0,0,.52126],105:[0,.69141,0,0,.27899],106:[0,.69141,0,0,.28088],107:[0,.69141,0,0,.38946],108:[0,.69141,0,0,.27953],109:[0,.47534,0,0,.76676],110:[0,.47534,0,0,.52666],111:[0,.47534,0,0,.48885],112:[.18906,.52396,0,0,.50046],113:[.18906,.47534,0,0,.48912],114:[0,.47534,0,0,.38919],115:[0,.47534,0,0,.44266],116:[0,.62119,0,0,.33301],117:[0,.47534,0,0,.5172],118:[0,.52396,0,0,.5118],119:[0,.52396,0,0,.77351],120:[.18906,.47534,0,0,.38865],121:[.18906,.47534,0,0,.49884],122:[.18906,.47534,0,0,.39054],160:[0,0,0,0,.25],8216:[0,.69141,0,0,.21471],8217:[0,.69141,0,0,.21471],58112:[0,.62119,0,0,.49749],58113:[0,.62119,0,0,.4983],58114:[.18906,.69141,0,0,.33328],58115:[.18906,.69141,0,0,.32923],58116:[.18906,.47534,0,0,.50343],58117:[0,.69141,0,0,.33301],58118:[0,.62119,0,0,.33409],58119:[0,.47534,0,0,.50073]},"Main-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.35],34:[0,.69444,0,0,.60278],35:[.19444,.69444,0,0,.95833],36:[.05556,.75,0,0,.575],37:[.05556,.75,0,0,.95833],38:[0,.69444,0,0,.89444],39:[0,.69444,0,0,.31944],40:[.25,.75,0,0,.44722],41:[.25,.75,0,0,.44722],42:[0,.75,0,0,.575],43:[.13333,.63333,0,0,.89444],44:[.19444,.15556,0,0,.31944],45:[0,.44444,0,0,.38333],46:[0,.15556,0,0,.31944],47:[.25,.75,0,0,.575],48:[0,.64444,0,0,.575],49:[0,.64444,0,0,.575],50:[0,.64444,0,0,.575],51:[0,.64444,0,0,.575],52:[0,.64444,0,0,.575],53:[0,.64444,0,0,.575],54:[0,.64444,0,0,.575],55:[0,.64444,0,0,.575],56:[0,.64444,0,0,.575],57:[0,.64444,0,0,.575],58:[0,.44444,0,0,.31944],59:[.19444,.44444,0,0,.31944],60:[.08556,.58556,0,0,.89444],61:[-.10889,.39111,0,0,.89444],62:[.08556,.58556,0,0,.89444],63:[0,.69444,0,0,.54305],64:[0,.69444,0,0,.89444],65:[0,.68611,0,0,.86944],66:[0,.68611,0,0,.81805],67:[0,.68611,0,0,.83055],68:[0,.68611,0,0,.88194],69:[0,.68611,0,0,.75555],70:[0,.68611,0,0,.72361],71:[0,.68611,0,0,.90416],72:[0,.68611,0,0,.9],73:[0,.68611,0,0,.43611],74:[0,.68611,0,0,.59444],75:[0,.68611,0,0,.90138],76:[0,.68611,0,0,.69166],77:[0,.68611,0,0,1.09166],78:[0,.68611,0,0,.9],79:[0,.68611,0,0,.86388],80:[0,.68611,0,0,.78611],81:[.19444,.68611,0,0,.86388],82:[0,.68611,0,0,.8625],83:[0,.68611,0,0,.63889],84:[0,.68611,0,0,.8],85:[0,.68611,0,0,.88472],86:[0,.68611,.01597,0,.86944],87:[0,.68611,.01597,0,1.18888],88:[0,.68611,0,0,.86944],89:[0,.68611,.02875,0,.86944],90:[0,.68611,0,0,.70277],91:[.25,.75,0,0,.31944],92:[.25,.75,0,0,.575],93:[.25,.75,0,0,.31944],94:[0,.69444,0,0,.575],95:[.31,.13444,.03194,0,.575],97:[0,.44444,0,0,.55902],98:[0,.69444,0,0,.63889],99:[0,.44444,0,0,.51111],100:[0,.69444,0,0,.63889],101:[0,.44444,0,0,.52708],102:[0,.69444,.10903,0,.35139],103:[.19444,.44444,.01597,0,.575],104:[0,.69444,0,0,.63889],105:[0,.69444,0,0,.31944],106:[.19444,.69444,0,0,.35139],107:[0,.69444,0,0,.60694],108:[0,.69444,0,0,.31944],109:[0,.44444,0,0,.95833],110:[0,.44444,0,0,.63889],111:[0,.44444,0,0,.575],112:[.19444,.44444,0,0,.63889],113:[.19444,.44444,0,0,.60694],114:[0,.44444,0,0,.47361],115:[0,.44444,0,0,.45361],116:[0,.63492,0,0,.44722],117:[0,.44444,0,0,.63889],118:[0,.44444,.01597,0,.60694],119:[0,.44444,.01597,0,.83055],120:[0,.44444,0,0,.60694],121:[.19444,.44444,.01597,0,.60694],122:[0,.44444,0,0,.51111],123:[.25,.75,0,0,.575],124:[.25,.75,0,0,.31944],125:[.25,.75,0,0,.575],126:[.35,.34444,0,0,.575],160:[0,0,0,0,.25],163:[0,.69444,0,0,.86853],168:[0,.69444,0,0,.575],172:[0,.44444,0,0,.76666],176:[0,.69444,0,0,.86944],177:[.13333,.63333,0,0,.89444],184:[.17014,0,0,0,.51111],198:[0,.68611,0,0,1.04166],215:[.13333,.63333,0,0,.89444],216:[.04861,.73472,0,0,.89444],223:[0,.69444,0,0,.59722],230:[0,.44444,0,0,.83055],247:[.13333,.63333,0,0,.89444],248:[.09722,.54167,0,0,.575],305:[0,.44444,0,0,.31944],338:[0,.68611,0,0,1.16944],339:[0,.44444,0,0,.89444],567:[.19444,.44444,0,0,.35139],710:[0,.69444,0,0,.575],711:[0,.63194,0,0,.575],713:[0,.59611,0,0,.575],714:[0,.69444,0,0,.575],715:[0,.69444,0,0,.575],728:[0,.69444,0,0,.575],729:[0,.69444,0,0,.31944],730:[0,.69444,0,0,.86944],732:[0,.69444,0,0,.575],733:[0,.69444,0,0,.575],915:[0,.68611,0,0,.69166],916:[0,.68611,0,0,.95833],920:[0,.68611,0,0,.89444],923:[0,.68611,0,0,.80555],926:[0,.68611,0,0,.76666],928:[0,.68611,0,0,.9],931:[0,.68611,0,0,.83055],933:[0,.68611,0,0,.89444],934:[0,.68611,0,0,.83055],936:[0,.68611,0,0,.89444],937:[0,.68611,0,0,.83055],8211:[0,.44444,.03194,0,.575],8212:[0,.44444,.03194,0,1.14999],8216:[0,.69444,0,0,.31944],8217:[0,.69444,0,0,.31944],8220:[0,.69444,0,0,.60278],8221:[0,.69444,0,0,.60278],8224:[.19444,.69444,0,0,.51111],8225:[.19444,.69444,0,0,.51111],8242:[0,.55556,0,0,.34444],8407:[0,.72444,.15486,0,.575],8463:[0,.69444,0,0,.66759],8465:[0,.69444,0,0,.83055],8467:[0,.69444,0,0,.47361],8472:[.19444,.44444,0,0,.74027],8476:[0,.69444,0,0,.83055],8501:[0,.69444,0,0,.70277],8592:[-.10889,.39111,0,0,1.14999],8593:[.19444,.69444,0,0,.575],8594:[-.10889,.39111,0,0,1.14999],8595:[.19444,.69444,0,0,.575],8596:[-.10889,.39111,0,0,1.14999],8597:[.25,.75,0,0,.575],8598:[.19444,.69444,0,0,1.14999],8599:[.19444,.69444,0,0,1.14999],8600:[.19444,.69444,0,0,1.14999],8601:[.19444,.69444,0,0,1.14999],8636:[-.10889,.39111,0,0,1.14999],8637:[-.10889,.39111,0,0,1.14999],8640:[-.10889,.39111,0,0,1.14999],8641:[-.10889,.39111,0,0,1.14999],8656:[-.10889,.39111,0,0,1.14999],8657:[.19444,.69444,0,0,.70277],8658:[-.10889,.39111,0,0,1.14999],8659:[.19444,.69444,0,0,.70277],8660:[-.10889,.39111,0,0,1.14999],8661:[.25,.75,0,0,.70277],8704:[0,.69444,0,0,.63889],8706:[0,.69444,.06389,0,.62847],8707:[0,.69444,0,0,.63889],8709:[.05556,.75,0,0,.575],8711:[0,.68611,0,0,.95833],8712:[.08556,.58556,0,0,.76666],8715:[.08556,.58556,0,0,.76666],8722:[.13333,.63333,0,0,.89444],8723:[.13333,.63333,0,0,.89444],8725:[.25,.75,0,0,.575],8726:[.25,.75,0,0,.575],8727:[-.02778,.47222,0,0,.575],8728:[-.02639,.47361,0,0,.575],8729:[-.02639,.47361,0,0,.575],8730:[.18,.82,0,0,.95833],8733:[0,.44444,0,0,.89444],8734:[0,.44444,0,0,1.14999],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.31944],8741:[.25,.75,0,0,.575],8743:[0,.55556,0,0,.76666],8744:[0,.55556,0,0,.76666],8745:[0,.55556,0,0,.76666],8746:[0,.55556,0,0,.76666],8747:[.19444,.69444,.12778,0,.56875],8764:[-.10889,.39111,0,0,.89444],8768:[.19444,.69444,0,0,.31944],8771:[.00222,.50222,0,0,.89444],8773:[.027,.638,0,0,.894],8776:[.02444,.52444,0,0,.89444],8781:[.00222,.50222,0,0,.89444],8801:[.00222,.50222,0,0,.89444],8804:[.19667,.69667,0,0,.89444],8805:[.19667,.69667,0,0,.89444],8810:[.08556,.58556,0,0,1.14999],8811:[.08556,.58556,0,0,1.14999],8826:[.08556,.58556,0,0,.89444],8827:[.08556,.58556,0,0,.89444],8834:[.08556,.58556,0,0,.89444],8835:[.08556,.58556,0,0,.89444],8838:[.19667,.69667,0,0,.89444],8839:[.19667,.69667,0,0,.89444],8846:[0,.55556,0,0,.76666],8849:[.19667,.69667,0,0,.89444],8850:[.19667,.69667,0,0,.89444],8851:[0,.55556,0,0,.76666],8852:[0,.55556,0,0,.76666],8853:[.13333,.63333,0,0,.89444],8854:[.13333,.63333,0,0,.89444],8855:[.13333,.63333,0,0,.89444],8856:[.13333,.63333,0,0,.89444],8857:[.13333,.63333,0,0,.89444],8866:[0,.69444,0,0,.70277],8867:[0,.69444,0,0,.70277],8868:[0,.69444,0,0,.89444],8869:[0,.69444,0,0,.89444],8900:[-.02639,.47361,0,0,.575],8901:[-.02639,.47361,0,0,.31944],8902:[-.02778,.47222,0,0,.575],8968:[.25,.75,0,0,.51111],8969:[.25,.75,0,0,.51111],8970:[.25,.75,0,0,.51111],8971:[.25,.75,0,0,.51111],8994:[-.13889,.36111,0,0,1.14999],8995:[-.13889,.36111,0,0,1.14999],9651:[.19444,.69444,0,0,1.02222],9657:[-.02778,.47222,0,0,.575],9661:[.19444,.69444,0,0,1.02222],9667:[-.02778,.47222,0,0,.575],9711:[.19444,.69444,0,0,1.14999],9824:[.12963,.69444,0,0,.89444],9825:[.12963,.69444,0,0,.89444],9826:[.12963,.69444,0,0,.89444],9827:[.12963,.69444,0,0,.89444],9837:[0,.75,0,0,.44722],9838:[.19444,.69444,0,0,.44722],9839:[.19444,.69444,0,0,.44722],10216:[.25,.75,0,0,.44722],10217:[.25,.75,0,0,.44722],10815:[0,.68611,0,0,.9],10927:[.19667,.69667,0,0,.89444],10928:[.19667,.69667,0,0,.89444],57376:[.19444,.69444,0,0,0]},"Main-BoldItalic":{32:[0,0,0,0,.25],33:[0,.69444,.11417,0,.38611],34:[0,.69444,.07939,0,.62055],35:[.19444,.69444,.06833,0,.94444],37:[.05556,.75,.12861,0,.94444],38:[0,.69444,.08528,0,.88555],39:[0,.69444,.12945,0,.35555],40:[.25,.75,.15806,0,.47333],41:[.25,.75,.03306,0,.47333],42:[0,.75,.14333,0,.59111],43:[.10333,.60333,.03306,0,.88555],44:[.19444,.14722,0,0,.35555],45:[0,.44444,.02611,0,.41444],46:[0,.14722,0,0,.35555],47:[.25,.75,.15806,0,.59111],48:[0,.64444,.13167,0,.59111],49:[0,.64444,.13167,0,.59111],50:[0,.64444,.13167,0,.59111],51:[0,.64444,.13167,0,.59111],52:[.19444,.64444,.13167,0,.59111],53:[0,.64444,.13167,0,.59111],54:[0,.64444,.13167,0,.59111],55:[.19444,.64444,.13167,0,.59111],56:[0,.64444,.13167,0,.59111],57:[0,.64444,.13167,0,.59111],58:[0,.44444,.06695,0,.35555],59:[.19444,.44444,.06695,0,.35555],61:[-.10889,.39111,.06833,0,.88555],63:[0,.69444,.11472,0,.59111],64:[0,.69444,.09208,0,.88555],65:[0,.68611,0,0,.86555],66:[0,.68611,.0992,0,.81666],67:[0,.68611,.14208,0,.82666],68:[0,.68611,.09062,0,.87555],69:[0,.68611,.11431,0,.75666],70:[0,.68611,.12903,0,.72722],71:[0,.68611,.07347,0,.89527],72:[0,.68611,.17208,0,.8961],73:[0,.68611,.15681,0,.47166],74:[0,.68611,.145,0,.61055],75:[0,.68611,.14208,0,.89499],76:[0,.68611,0,0,.69777],77:[0,.68611,.17208,0,1.07277],78:[0,.68611,.17208,0,.8961],79:[0,.68611,.09062,0,.85499],80:[0,.68611,.0992,0,.78721],81:[.19444,.68611,.09062,0,.85499],82:[0,.68611,.02559,0,.85944],83:[0,.68611,.11264,0,.64999],84:[0,.68611,.12903,0,.7961],85:[0,.68611,.17208,0,.88083],86:[0,.68611,.18625,0,.86555],87:[0,.68611,.18625,0,1.15999],88:[0,.68611,.15681,0,.86555],89:[0,.68611,.19803,0,.86555],90:[0,.68611,.14208,0,.70888],91:[.25,.75,.1875,0,.35611],93:[.25,.75,.09972,0,.35611],94:[0,.69444,.06709,0,.59111],95:[.31,.13444,.09811,0,.59111],97:[0,.44444,.09426,0,.59111],98:[0,.69444,.07861,0,.53222],99:[0,.44444,.05222,0,.53222],100:[0,.69444,.10861,0,.59111],101:[0,.44444,.085,0,.53222],102:[.19444,.69444,.21778,0,.4],103:[.19444,.44444,.105,0,.53222],104:[0,.69444,.09426,0,.59111],105:[0,.69326,.11387,0,.35555],106:[.19444,.69326,.1672,0,.35555],107:[0,.69444,.11111,0,.53222],108:[0,.69444,.10861,0,.29666],109:[0,.44444,.09426,0,.94444],110:[0,.44444,.09426,0,.64999],111:[0,.44444,.07861,0,.59111],112:[.19444,.44444,.07861,0,.59111],113:[.19444,.44444,.105,0,.53222],114:[0,.44444,.11111,0,.50167],115:[0,.44444,.08167,0,.48694],116:[0,.63492,.09639,0,.385],117:[0,.44444,.09426,0,.62055],118:[0,.44444,.11111,0,.53222],119:[0,.44444,.11111,0,.76777],120:[0,.44444,.12583,0,.56055],121:[.19444,.44444,.105,0,.56166],122:[0,.44444,.13889,0,.49055],126:[.35,.34444,.11472,0,.59111],160:[0,0,0,0,.25],168:[0,.69444,.11473,0,.59111],176:[0,.69444,0,0,.94888],184:[.17014,0,0,0,.53222],198:[0,.68611,.11431,0,1.02277],216:[.04861,.73472,.09062,0,.88555],223:[.19444,.69444,.09736,0,.665],230:[0,.44444,.085,0,.82666],248:[.09722,.54167,.09458,0,.59111],305:[0,.44444,.09426,0,.35555],338:[0,.68611,.11431,0,1.14054],339:[0,.44444,.085,0,.82666],567:[.19444,.44444,.04611,0,.385],710:[0,.69444,.06709,0,.59111],711:[0,.63194,.08271,0,.59111],713:[0,.59444,.10444,0,.59111],714:[0,.69444,.08528,0,.59111],715:[0,.69444,0,0,.59111],728:[0,.69444,.10333,0,.59111],729:[0,.69444,.12945,0,.35555],730:[0,.69444,0,0,.94888],732:[0,.69444,.11472,0,.59111],733:[0,.69444,.11472,0,.59111],915:[0,.68611,.12903,0,.69777],916:[0,.68611,0,0,.94444],920:[0,.68611,.09062,0,.88555],923:[0,.68611,0,0,.80666],926:[0,.68611,.15092,0,.76777],928:[0,.68611,.17208,0,.8961],931:[0,.68611,.11431,0,.82666],933:[0,.68611,.10778,0,.88555],934:[0,.68611,.05632,0,.82666],936:[0,.68611,.10778,0,.88555],937:[0,.68611,.0992,0,.82666],8211:[0,.44444,.09811,0,.59111],8212:[0,.44444,.09811,0,1.18221],8216:[0,.69444,.12945,0,.35555],8217:[0,.69444,.12945,0,.35555],8220:[0,.69444,.16772,0,.62055],8221:[0,.69444,.07939,0,.62055]},"Main-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.12417,0,.30667],34:[0,.69444,.06961,0,.51444],35:[.19444,.69444,.06616,0,.81777],37:[.05556,.75,.13639,0,.81777],38:[0,.69444,.09694,0,.76666],39:[0,.69444,.12417,0,.30667],40:[.25,.75,.16194,0,.40889],41:[.25,.75,.03694,0,.40889],42:[0,.75,.14917,0,.51111],43:[.05667,.56167,.03694,0,.76666],44:[.19444,.10556,0,0,.30667],45:[0,.43056,.02826,0,.35778],46:[0,.10556,0,0,.30667],47:[.25,.75,.16194,0,.51111],48:[0,.64444,.13556,0,.51111],49:[0,.64444,.13556,0,.51111],50:[0,.64444,.13556,0,.51111],51:[0,.64444,.13556,0,.51111],52:[.19444,.64444,.13556,0,.51111],53:[0,.64444,.13556,0,.51111],54:[0,.64444,.13556,0,.51111],55:[.19444,.64444,.13556,0,.51111],56:[0,.64444,.13556,0,.51111],57:[0,.64444,.13556,0,.51111],58:[0,.43056,.0582,0,.30667],59:[.19444,.43056,.0582,0,.30667],61:[-.13313,.36687,.06616,0,.76666],63:[0,.69444,.1225,0,.51111],64:[0,.69444,.09597,0,.76666],65:[0,.68333,0,0,.74333],66:[0,.68333,.10257,0,.70389],67:[0,.68333,.14528,0,.71555],68:[0,.68333,.09403,0,.755],69:[0,.68333,.12028,0,.67833],70:[0,.68333,.13305,0,.65277],71:[0,.68333,.08722,0,.77361],72:[0,.68333,.16389,0,.74333],73:[0,.68333,.15806,0,.38555],74:[0,.68333,.14028,0,.525],75:[0,.68333,.14528,0,.76888],76:[0,.68333,0,0,.62722],77:[0,.68333,.16389,0,.89666],78:[0,.68333,.16389,0,.74333],79:[0,.68333,.09403,0,.76666],80:[0,.68333,.10257,0,.67833],81:[.19444,.68333,.09403,0,.76666],82:[0,.68333,.03868,0,.72944],83:[0,.68333,.11972,0,.56222],84:[0,.68333,.13305,0,.71555],85:[0,.68333,.16389,0,.74333],86:[0,.68333,.18361,0,.74333],87:[0,.68333,.18361,0,.99888],88:[0,.68333,.15806,0,.74333],89:[0,.68333,.19383,0,.74333],90:[0,.68333,.14528,0,.61333],91:[.25,.75,.1875,0,.30667],93:[.25,.75,.10528,0,.30667],94:[0,.69444,.06646,0,.51111],95:[.31,.12056,.09208,0,.51111],97:[0,.43056,.07671,0,.51111],98:[0,.69444,.06312,0,.46],99:[0,.43056,.05653,0,.46],100:[0,.69444,.10333,0,.51111],101:[0,.43056,.07514,0,.46],102:[.19444,.69444,.21194,0,.30667],103:[.19444,.43056,.08847,0,.46],104:[0,.69444,.07671,0,.51111],105:[0,.65536,.1019,0,.30667],106:[.19444,.65536,.14467,0,.30667],107:[0,.69444,.10764,0,.46],108:[0,.69444,.10333,0,.25555],109:[0,.43056,.07671,0,.81777],110:[0,.43056,.07671,0,.56222],111:[0,.43056,.06312,0,.51111],112:[.19444,.43056,.06312,0,.51111],113:[.19444,.43056,.08847,0,.46],114:[0,.43056,.10764,0,.42166],115:[0,.43056,.08208,0,.40889],116:[0,.61508,.09486,0,.33222],117:[0,.43056,.07671,0,.53666],118:[0,.43056,.10764,0,.46],119:[0,.43056,.10764,0,.66444],120:[0,.43056,.12042,0,.46389],121:[.19444,.43056,.08847,0,.48555],122:[0,.43056,.12292,0,.40889],126:[.35,.31786,.11585,0,.51111],160:[0,0,0,0,.25],168:[0,.66786,.10474,0,.51111],176:[0,.69444,0,0,.83129],184:[.17014,0,0,0,.46],198:[0,.68333,.12028,0,.88277],216:[.04861,.73194,.09403,0,.76666],223:[.19444,.69444,.10514,0,.53666],230:[0,.43056,.07514,0,.71555],248:[.09722,.52778,.09194,0,.51111],338:[0,.68333,.12028,0,.98499],339:[0,.43056,.07514,0,.71555],710:[0,.69444,.06646,0,.51111],711:[0,.62847,.08295,0,.51111],713:[0,.56167,.10333,0,.51111],714:[0,.69444,.09694,0,.51111],715:[0,.69444,0,0,.51111],728:[0,.69444,.10806,0,.51111],729:[0,.66786,.11752,0,.30667],730:[0,.69444,0,0,.83129],732:[0,.66786,.11585,0,.51111],733:[0,.69444,.1225,0,.51111],915:[0,.68333,.13305,0,.62722],916:[0,.68333,0,0,.81777],920:[0,.68333,.09403,0,.76666],923:[0,.68333,0,0,.69222],926:[0,.68333,.15294,0,.66444],928:[0,.68333,.16389,0,.74333],931:[0,.68333,.12028,0,.71555],933:[0,.68333,.11111,0,.76666],934:[0,.68333,.05986,0,.71555],936:[0,.68333,.11111,0,.76666],937:[0,.68333,.10257,0,.71555],8211:[0,.43056,.09208,0,.51111],8212:[0,.43056,.09208,0,1.02222],8216:[0,.69444,.12417,0,.30667],8217:[0,.69444,.12417,0,.30667],8220:[0,.69444,.1685,0,.51444],8221:[0,.69444,.06961,0,.51444],8463:[0,.68889,0,0,.54028]},"Main-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.27778],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.77778],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.19444,.10556,0,0,.27778],45:[0,.43056,0,0,.33333],46:[0,.10556,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.64444,0,0,.5],49:[0,.64444,0,0,.5],50:[0,.64444,0,0,.5],51:[0,.64444,0,0,.5],52:[0,.64444,0,0,.5],53:[0,.64444,0,0,.5],54:[0,.64444,0,0,.5],55:[0,.64444,0,0,.5],56:[0,.64444,0,0,.5],57:[0,.64444,0,0,.5],58:[0,.43056,0,0,.27778],59:[.19444,.43056,0,0,.27778],60:[.0391,.5391,0,0,.77778],61:[-.13313,.36687,0,0,.77778],62:[.0391,.5391,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.77778],65:[0,.68333,0,0,.75],66:[0,.68333,0,0,.70834],67:[0,.68333,0,0,.72222],68:[0,.68333,0,0,.76389],69:[0,.68333,0,0,.68056],70:[0,.68333,0,0,.65278],71:[0,.68333,0,0,.78472],72:[0,.68333,0,0,.75],73:[0,.68333,0,0,.36111],74:[0,.68333,0,0,.51389],75:[0,.68333,0,0,.77778],76:[0,.68333,0,0,.625],77:[0,.68333,0,0,.91667],78:[0,.68333,0,0,.75],79:[0,.68333,0,0,.77778],80:[0,.68333,0,0,.68056],81:[.19444,.68333,0,0,.77778],82:[0,.68333,0,0,.73611],83:[0,.68333,0,0,.55556],84:[0,.68333,0,0,.72222],85:[0,.68333,0,0,.75],86:[0,.68333,.01389,0,.75],87:[0,.68333,.01389,0,1.02778],88:[0,.68333,0,0,.75],89:[0,.68333,.025,0,.75],90:[0,.68333,0,0,.61111],91:[.25,.75,0,0,.27778],92:[.25,.75,0,0,.5],93:[.25,.75,0,0,.27778],94:[0,.69444,0,0,.5],95:[.31,.12056,.02778,0,.5],97:[0,.43056,0,0,.5],98:[0,.69444,0,0,.55556],99:[0,.43056,0,0,.44445],100:[0,.69444,0,0,.55556],101:[0,.43056,0,0,.44445],102:[0,.69444,.07778,0,.30556],103:[.19444,.43056,.01389,0,.5],104:[0,.69444,0,0,.55556],105:[0,.66786,0,0,.27778],106:[.19444,.66786,0,0,.30556],107:[0,.69444,0,0,.52778],108:[0,.69444,0,0,.27778],109:[0,.43056,0,0,.83334],110:[0,.43056,0,0,.55556],111:[0,.43056,0,0,.5],112:[.19444,.43056,0,0,.55556],113:[.19444,.43056,0,0,.52778],114:[0,.43056,0,0,.39167],115:[0,.43056,0,0,.39445],116:[0,.61508,0,0,.38889],117:[0,.43056,0,0,.55556],118:[0,.43056,.01389,0,.52778],119:[0,.43056,.01389,0,.72222],120:[0,.43056,0,0,.52778],121:[.19444,.43056,.01389,0,.52778],122:[0,.43056,0,0,.44445],123:[.25,.75,0,0,.5],124:[.25,.75,0,0,.27778],125:[.25,.75,0,0,.5],126:[.35,.31786,0,0,.5],160:[0,0,0,0,.25],163:[0,.69444,0,0,.76909],167:[.19444,.69444,0,0,.44445],168:[0,.66786,0,0,.5],172:[0,.43056,0,0,.66667],176:[0,.69444,0,0,.75],177:[.08333,.58333,0,0,.77778],182:[.19444,.69444,0,0,.61111],184:[.17014,0,0,0,.44445],198:[0,.68333,0,0,.90278],215:[.08333,.58333,0,0,.77778],216:[.04861,.73194,0,0,.77778],223:[0,.69444,0,0,.5],230:[0,.43056,0,0,.72222],247:[.08333,.58333,0,0,.77778],248:[.09722,.52778,0,0,.5],305:[0,.43056,0,0,.27778],338:[0,.68333,0,0,1.01389],339:[0,.43056,0,0,.77778],567:[.19444,.43056,0,0,.30556],710:[0,.69444,0,0,.5],711:[0,.62847,0,0,.5],713:[0,.56778,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.66786,0,0,.27778],730:[0,.69444,0,0,.75],732:[0,.66786,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.68333,0,0,.625],916:[0,.68333,0,0,.83334],920:[0,.68333,0,0,.77778],923:[0,.68333,0,0,.69445],926:[0,.68333,0,0,.66667],928:[0,.68333,0,0,.75],931:[0,.68333,0,0,.72222],933:[0,.68333,0,0,.77778],934:[0,.68333,0,0,.72222],936:[0,.68333,0,0,.77778],937:[0,.68333,0,0,.72222],8211:[0,.43056,.02778,0,.5],8212:[0,.43056,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5],8224:[.19444,.69444,0,0,.44445],8225:[.19444,.69444,0,0,.44445],8230:[0,.123,0,0,1.172],8242:[0,.55556,0,0,.275],8407:[0,.71444,.15382,0,.5],8463:[0,.68889,0,0,.54028],8465:[0,.69444,0,0,.72222],8467:[0,.69444,0,.11111,.41667],8472:[.19444,.43056,0,.11111,.63646],8476:[0,.69444,0,0,.72222],8501:[0,.69444,0,0,.61111],8592:[-.13313,.36687,0,0,1],8593:[.19444,.69444,0,0,.5],8594:[-.13313,.36687,0,0,1],8595:[.19444,.69444,0,0,.5],8596:[-.13313,.36687,0,0,1],8597:[.25,.75,0,0,.5],8598:[.19444,.69444,0,0,1],8599:[.19444,.69444,0,0,1],8600:[.19444,.69444,0,0,1],8601:[.19444,.69444,0,0,1],8614:[.011,.511,0,0,1],8617:[.011,.511,0,0,1.126],8618:[.011,.511,0,0,1.126],8636:[-.13313,.36687,0,0,1],8637:[-.13313,.36687,0,0,1],8640:[-.13313,.36687,0,0,1],8641:[-.13313,.36687,0,0,1],8652:[.011,.671,0,0,1],8656:[-.13313,.36687,0,0,1],8657:[.19444,.69444,0,0,.61111],8658:[-.13313,.36687,0,0,1],8659:[.19444,.69444,0,0,.61111],8660:[-.13313,.36687,0,0,1],8661:[.25,.75,0,0,.61111],8704:[0,.69444,0,0,.55556],8706:[0,.69444,.05556,.08334,.5309],8707:[0,.69444,0,0,.55556],8709:[.05556,.75,0,0,.5],8711:[0,.68333,0,0,.83334],8712:[.0391,.5391,0,0,.66667],8715:[.0391,.5391,0,0,.66667],8722:[.08333,.58333,0,0,.77778],8723:[.08333,.58333,0,0,.77778],8725:[.25,.75,0,0,.5],8726:[.25,.75,0,0,.5],8727:[-.03472,.46528,0,0,.5],8728:[-.05555,.44445,0,0,.5],8729:[-.05555,.44445,0,0,.5],8730:[.2,.8,0,0,.83334],8733:[0,.43056,0,0,.77778],8734:[0,.43056,0,0,1],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.27778],8741:[.25,.75,0,0,.5],8743:[0,.55556,0,0,.66667],8744:[0,.55556,0,0,.66667],8745:[0,.55556,0,0,.66667],8746:[0,.55556,0,0,.66667],8747:[.19444,.69444,.11111,0,.41667],8764:[-.13313,.36687,0,0,.77778],8768:[.19444,.69444,0,0,.27778],8771:[-.03625,.46375,0,0,.77778],8773:[-.022,.589,0,0,.778],8776:[-.01688,.48312,0,0,.77778],8781:[-.03625,.46375,0,0,.77778],8784:[-.133,.673,0,0,.778],8801:[-.03625,.46375,0,0,.77778],8804:[.13597,.63597,0,0,.77778],8805:[.13597,.63597,0,0,.77778],8810:[.0391,.5391,0,0,1],8811:[.0391,.5391,0,0,1],8826:[.0391,.5391,0,0,.77778],8827:[.0391,.5391,0,0,.77778],8834:[.0391,.5391,0,0,.77778],8835:[.0391,.5391,0,0,.77778],8838:[.13597,.63597,0,0,.77778],8839:[.13597,.63597,0,0,.77778],8846:[0,.55556,0,0,.66667],8849:[.13597,.63597,0,0,.77778],8850:[.13597,.63597,0,0,.77778],8851:[0,.55556,0,0,.66667],8852:[0,.55556,0,0,.66667],8853:[.08333,.58333,0,0,.77778],8854:[.08333,.58333,0,0,.77778],8855:[.08333,.58333,0,0,.77778],8856:[.08333,.58333,0,0,.77778],8857:[.08333,.58333,0,0,.77778],8866:[0,.69444,0,0,.61111],8867:[0,.69444,0,0,.61111],8868:[0,.69444,0,0,.77778],8869:[0,.69444,0,0,.77778],8872:[.249,.75,0,0,.867],8900:[-.05555,.44445,0,0,.5],8901:[-.05555,.44445,0,0,.27778],8902:[-.03472,.46528,0,0,.5],8904:[.005,.505,0,0,.9],8942:[.03,.903,0,0,.278],8943:[-.19,.313,0,0,1.172],8945:[-.1,.823,0,0,1.282],8968:[.25,.75,0,0,.44445],8969:[.25,.75,0,0,.44445],8970:[.25,.75,0,0,.44445],8971:[.25,.75,0,0,.44445],8994:[-.14236,.35764,0,0,1],8995:[-.14236,.35764,0,0,1],9136:[.244,.744,0,0,.412],9137:[.244,.745,0,0,.412],9651:[.19444,.69444,0,0,.88889],9657:[-.03472,.46528,0,0,.5],9661:[.19444,.69444,0,0,.88889],9667:[-.03472,.46528,0,0,.5],9711:[.19444,.69444,0,0,1],9824:[.12963,.69444,0,0,.77778],9825:[.12963,.69444,0,0,.77778],9826:[.12963,.69444,0,0,.77778],9827:[.12963,.69444,0,0,.77778],9837:[0,.75,0,0,.38889],9838:[.19444,.69444,0,0,.38889],9839:[.19444,.69444,0,0,.38889],10216:[.25,.75,0,0,.38889],10217:[.25,.75,0,0,.38889],10222:[.244,.744,0,0,.412],10223:[.244,.745,0,0,.412],10229:[.011,.511,0,0,1.609],10230:[.011,.511,0,0,1.638],10231:[.011,.511,0,0,1.859],10232:[.024,.525,0,0,1.609],10233:[.024,.525,0,0,1.638],10234:[.024,.525,0,0,1.858],10236:[.011,.511,0,0,1.638],10815:[0,.68333,0,0,.75],10927:[.13597,.63597,0,0,.77778],10928:[.13597,.63597,0,0,.77778],57376:[.19444,.69444,0,0,0]},"Math-BoldItalic":{32:[0,0,0,0,.25],48:[0,.44444,0,0,.575],49:[0,.44444,0,0,.575],50:[0,.44444,0,0,.575],51:[.19444,.44444,0,0,.575],52:[.19444,.44444,0,0,.575],53:[.19444,.44444,0,0,.575],54:[0,.64444,0,0,.575],55:[.19444,.44444,0,0,.575],56:[0,.64444,0,0,.575],57:[.19444,.44444,0,0,.575],65:[0,.68611,0,0,.86944],66:[0,.68611,.04835,0,.8664],67:[0,.68611,.06979,0,.81694],68:[0,.68611,.03194,0,.93812],69:[0,.68611,.05451,0,.81007],70:[0,.68611,.15972,0,.68889],71:[0,.68611,0,0,.88673],72:[0,.68611,.08229,0,.98229],73:[0,.68611,.07778,0,.51111],74:[0,.68611,.10069,0,.63125],75:[0,.68611,.06979,0,.97118],76:[0,.68611,0,0,.75555],77:[0,.68611,.11424,0,1.14201],78:[0,.68611,.11424,0,.95034],79:[0,.68611,.03194,0,.83666],80:[0,.68611,.15972,0,.72309],81:[.19444,.68611,0,0,.86861],82:[0,.68611,.00421,0,.87235],83:[0,.68611,.05382,0,.69271],84:[0,.68611,.15972,0,.63663],85:[0,.68611,.11424,0,.80027],86:[0,.68611,.25555,0,.67778],87:[0,.68611,.15972,0,1.09305],88:[0,.68611,.07778,0,.94722],89:[0,.68611,.25555,0,.67458],90:[0,.68611,.06979,0,.77257],97:[0,.44444,0,0,.63287],98:[0,.69444,0,0,.52083],99:[0,.44444,0,0,.51342],100:[0,.69444,0,0,.60972],101:[0,.44444,0,0,.55361],102:[.19444,.69444,.11042,0,.56806],103:[.19444,.44444,.03704,0,.5449],104:[0,.69444,0,0,.66759],105:[0,.69326,0,0,.4048],106:[.19444,.69326,.0622,0,.47083],107:[0,.69444,.01852,0,.6037],108:[0,.69444,.0088,0,.34815],109:[0,.44444,0,0,1.0324],110:[0,.44444,0,0,.71296],111:[0,.44444,0,0,.58472],112:[.19444,.44444,0,0,.60092],113:[.19444,.44444,.03704,0,.54213],114:[0,.44444,.03194,0,.5287],115:[0,.44444,0,0,.53125],116:[0,.63492,0,0,.41528],117:[0,.44444,0,0,.68102],118:[0,.44444,.03704,0,.56666],119:[0,.44444,.02778,0,.83148],120:[0,.44444,0,0,.65903],121:[.19444,.44444,.03704,0,.59028],122:[0,.44444,.04213,0,.55509],160:[0,0,0,0,.25],915:[0,.68611,.15972,0,.65694],916:[0,.68611,0,0,.95833],920:[0,.68611,.03194,0,.86722],923:[0,.68611,0,0,.80555],926:[0,.68611,.07458,0,.84125],928:[0,.68611,.08229,0,.98229],931:[0,.68611,.05451,0,.88507],933:[0,.68611,.15972,0,.67083],934:[0,.68611,0,0,.76666],936:[0,.68611,.11653,0,.71402],937:[0,.68611,.04835,0,.8789],945:[0,.44444,0,0,.76064],946:[.19444,.69444,.03403,0,.65972],947:[.19444,.44444,.06389,0,.59003],948:[0,.69444,.03819,0,.52222],949:[0,.44444,0,0,.52882],950:[.19444,.69444,.06215,0,.50833],951:[.19444,.44444,.03704,0,.6],952:[0,.69444,.03194,0,.5618],953:[0,.44444,0,0,.41204],954:[0,.44444,0,0,.66759],955:[0,.69444,0,0,.67083],956:[.19444,.44444,0,0,.70787],957:[0,.44444,.06898,0,.57685],958:[.19444,.69444,.03021,0,.50833],959:[0,.44444,0,0,.58472],960:[0,.44444,.03704,0,.68241],961:[.19444,.44444,0,0,.6118],962:[.09722,.44444,.07917,0,.42361],963:[0,.44444,.03704,0,.68588],964:[0,.44444,.13472,0,.52083],965:[0,.44444,.03704,0,.63055],966:[.19444,.44444,0,0,.74722],967:[.19444,.44444,0,0,.71805],968:[.19444,.69444,.03704,0,.75833],969:[0,.44444,.03704,0,.71782],977:[0,.69444,0,0,.69155],981:[.19444,.69444,0,0,.7125],982:[0,.44444,.03194,0,.975],1009:[.19444,.44444,0,0,.6118],1013:[0,.44444,0,0,.48333],57649:[0,.44444,0,0,.39352],57911:[.19444,.44444,0,0,.43889]},"Math-Italic":{32:[0,0,0,0,.25],48:[0,.43056,0,0,.5],49:[0,.43056,0,0,.5],50:[0,.43056,0,0,.5],51:[.19444,.43056,0,0,.5],52:[.19444,.43056,0,0,.5],53:[.19444,.43056,0,0,.5],54:[0,.64444,0,0,.5],55:[.19444,.43056,0,0,.5],56:[0,.64444,0,0,.5],57:[.19444,.43056,0,0,.5],65:[0,.68333,0,.13889,.75],66:[0,.68333,.05017,.08334,.75851],67:[0,.68333,.07153,.08334,.71472],68:[0,.68333,.02778,.05556,.82792],69:[0,.68333,.05764,.08334,.7382],70:[0,.68333,.13889,.08334,.64306],71:[0,.68333,0,.08334,.78625],72:[0,.68333,.08125,.05556,.83125],73:[0,.68333,.07847,.11111,.43958],74:[0,.68333,.09618,.16667,.55451],75:[0,.68333,.07153,.05556,.84931],76:[0,.68333,0,.02778,.68056],77:[0,.68333,.10903,.08334,.97014],78:[0,.68333,.10903,.08334,.80347],79:[0,.68333,.02778,.08334,.76278],80:[0,.68333,.13889,.08334,.64201],81:[.19444,.68333,0,.08334,.79056],82:[0,.68333,.00773,.08334,.75929],83:[0,.68333,.05764,.08334,.6132],84:[0,.68333,.13889,.08334,.58438],85:[0,.68333,.10903,.02778,.68278],86:[0,.68333,.22222,0,.58333],87:[0,.68333,.13889,0,.94445],88:[0,.68333,.07847,.08334,.82847],89:[0,.68333,.22222,0,.58056],90:[0,.68333,.07153,.08334,.68264],97:[0,.43056,0,0,.52859],98:[0,.69444,0,0,.42917],99:[0,.43056,0,.05556,.43276],100:[0,.69444,0,.16667,.52049],101:[0,.43056,0,.05556,.46563],102:[.19444,.69444,.10764,.16667,.48959],103:[.19444,.43056,.03588,.02778,.47697],104:[0,.69444,0,0,.57616],105:[0,.65952,0,0,.34451],106:[.19444,.65952,.05724,0,.41181],107:[0,.69444,.03148,0,.5206],108:[0,.69444,.01968,.08334,.29838],109:[0,.43056,0,0,.87801],110:[0,.43056,0,0,.60023],111:[0,.43056,0,.05556,.48472],112:[.19444,.43056,0,.08334,.50313],113:[.19444,.43056,.03588,.08334,.44641],114:[0,.43056,.02778,.05556,.45116],115:[0,.43056,0,.05556,.46875],116:[0,.61508,0,.08334,.36111],117:[0,.43056,0,.02778,.57246],118:[0,.43056,.03588,.02778,.48472],119:[0,.43056,.02691,.08334,.71592],120:[0,.43056,0,.02778,.57153],121:[.19444,.43056,.03588,.05556,.49028],122:[0,.43056,.04398,.05556,.46505],160:[0,0,0,0,.25],915:[0,.68333,.13889,.08334,.61528],916:[0,.68333,0,.16667,.83334],920:[0,.68333,.02778,.08334,.76278],923:[0,.68333,0,.16667,.69445],926:[0,.68333,.07569,.08334,.74236],928:[0,.68333,.08125,.05556,.83125],931:[0,.68333,.05764,.08334,.77986],933:[0,.68333,.13889,.05556,.58333],934:[0,.68333,0,.08334,.66667],936:[0,.68333,.11,.05556,.61222],937:[0,.68333,.05017,.08334,.7724],945:[0,.43056,.0037,.02778,.6397],946:[.19444,.69444,.05278,.08334,.56563],947:[.19444,.43056,.05556,0,.51773],948:[0,.69444,.03785,.05556,.44444],949:[0,.43056,0,.08334,.46632],950:[.19444,.69444,.07378,.08334,.4375],951:[.19444,.43056,.03588,.05556,.49653],952:[0,.69444,.02778,.08334,.46944],953:[0,.43056,0,.05556,.35394],954:[0,.43056,0,0,.57616],955:[0,.69444,0,0,.58334],956:[.19444,.43056,0,.02778,.60255],957:[0,.43056,.06366,.02778,.49398],958:[.19444,.69444,.04601,.11111,.4375],959:[0,.43056,0,.05556,.48472],960:[0,.43056,.03588,0,.57003],961:[.19444,.43056,0,.08334,.51702],962:[.09722,.43056,.07986,.08334,.36285],963:[0,.43056,.03588,0,.57141],964:[0,.43056,.1132,.02778,.43715],965:[0,.43056,.03588,.02778,.54028],966:[.19444,.43056,0,.08334,.65417],967:[.19444,.43056,0,.05556,.62569],968:[.19444,.69444,.03588,.11111,.65139],969:[0,.43056,.03588,0,.62245],977:[0,.69444,0,.08334,.59144],981:[.19444,.69444,0,.08334,.59583],982:[0,.43056,.02778,0,.82813],1009:[.19444,.43056,0,.08334,.51702],1013:[0,.43056,0,.05556,.4059],57649:[0,.43056,0,.02778,.32246],57911:[.19444,.43056,0,.08334,.38403]},"SansSerif-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.36667],34:[0,.69444,0,0,.55834],35:[.19444,.69444,0,0,.91667],36:[.05556,.75,0,0,.55],37:[.05556,.75,0,0,1.02912],38:[0,.69444,0,0,.83056],39:[0,.69444,0,0,.30556],40:[.25,.75,0,0,.42778],41:[.25,.75,0,0,.42778],42:[0,.75,0,0,.55],43:[.11667,.61667,0,0,.85556],44:[.10556,.13056,0,0,.30556],45:[0,.45833,0,0,.36667],46:[0,.13056,0,0,.30556],47:[.25,.75,0,0,.55],48:[0,.69444,0,0,.55],49:[0,.69444,0,0,.55],50:[0,.69444,0,0,.55],51:[0,.69444,0,0,.55],52:[0,.69444,0,0,.55],53:[0,.69444,0,0,.55],54:[0,.69444,0,0,.55],55:[0,.69444,0,0,.55],56:[0,.69444,0,0,.55],57:[0,.69444,0,0,.55],58:[0,.45833,0,0,.30556],59:[.10556,.45833,0,0,.30556],61:[-.09375,.40625,0,0,.85556],63:[0,.69444,0,0,.51945],64:[0,.69444,0,0,.73334],65:[0,.69444,0,0,.73334],66:[0,.69444,0,0,.73334],67:[0,.69444,0,0,.70278],68:[0,.69444,0,0,.79445],69:[0,.69444,0,0,.64167],70:[0,.69444,0,0,.61111],71:[0,.69444,0,0,.73334],72:[0,.69444,0,0,.79445],73:[0,.69444,0,0,.33056],74:[0,.69444,0,0,.51945],75:[0,.69444,0,0,.76389],76:[0,.69444,0,0,.58056],77:[0,.69444,0,0,.97778],78:[0,.69444,0,0,.79445],79:[0,.69444,0,0,.79445],80:[0,.69444,0,0,.70278],81:[.10556,.69444,0,0,.79445],82:[0,.69444,0,0,.70278],83:[0,.69444,0,0,.61111],84:[0,.69444,0,0,.73334],85:[0,.69444,0,0,.76389],86:[0,.69444,.01528,0,.73334],87:[0,.69444,.01528,0,1.03889],88:[0,.69444,0,0,.73334],89:[0,.69444,.0275,0,.73334],90:[0,.69444,0,0,.67223],91:[.25,.75,0,0,.34306],93:[.25,.75,0,0,.34306],94:[0,.69444,0,0,.55],95:[.35,.10833,.03056,0,.55],97:[0,.45833,0,0,.525],98:[0,.69444,0,0,.56111],99:[0,.45833,0,0,.48889],100:[0,.69444,0,0,.56111],101:[0,.45833,0,0,.51111],102:[0,.69444,.07639,0,.33611],103:[.19444,.45833,.01528,0,.55],104:[0,.69444,0,0,.56111],105:[0,.69444,0,0,.25556],106:[.19444,.69444,0,0,.28611],107:[0,.69444,0,0,.53056],108:[0,.69444,0,0,.25556],109:[0,.45833,0,0,.86667],110:[0,.45833,0,0,.56111],111:[0,.45833,0,0,.55],112:[.19444,.45833,0,0,.56111],113:[.19444,.45833,0,0,.56111],114:[0,.45833,.01528,0,.37222],115:[0,.45833,0,0,.42167],116:[0,.58929,0,0,.40417],117:[0,.45833,0,0,.56111],118:[0,.45833,.01528,0,.5],119:[0,.45833,.01528,0,.74445],120:[0,.45833,0,0,.5],121:[.19444,.45833,.01528,0,.5],122:[0,.45833,0,0,.47639],126:[.35,.34444,0,0,.55],160:[0,0,0,0,.25],168:[0,.69444,0,0,.55],176:[0,.69444,0,0,.73334],180:[0,.69444,0,0,.55],184:[.17014,0,0,0,.48889],305:[0,.45833,0,0,.25556],567:[.19444,.45833,0,0,.28611],710:[0,.69444,0,0,.55],711:[0,.63542,0,0,.55],713:[0,.63778,0,0,.55],728:[0,.69444,0,0,.55],729:[0,.69444,0,0,.30556],730:[0,.69444,0,0,.73334],732:[0,.69444,0,0,.55],733:[0,.69444,0,0,.55],915:[0,.69444,0,0,.58056],916:[0,.69444,0,0,.91667],920:[0,.69444,0,0,.85556],923:[0,.69444,0,0,.67223],926:[0,.69444,0,0,.73334],928:[0,.69444,0,0,.79445],931:[0,.69444,0,0,.79445],933:[0,.69444,0,0,.85556],934:[0,.69444,0,0,.79445],936:[0,.69444,0,0,.85556],937:[0,.69444,0,0,.79445],8211:[0,.45833,.03056,0,.55],8212:[0,.45833,.03056,0,1.10001],8216:[0,.69444,0,0,.30556],8217:[0,.69444,0,0,.30556],8220:[0,.69444,0,0,.55834],8221:[0,.69444,0,0,.55834]},"SansSerif-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.05733,0,.31945],34:[0,.69444,.00316,0,.5],35:[.19444,.69444,.05087,0,.83334],36:[.05556,.75,.11156,0,.5],37:[.05556,.75,.03126,0,.83334],38:[0,.69444,.03058,0,.75834],39:[0,.69444,.07816,0,.27778],40:[.25,.75,.13164,0,.38889],41:[.25,.75,.02536,0,.38889],42:[0,.75,.11775,0,.5],43:[.08333,.58333,.02536,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,.01946,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,.13164,0,.5],48:[0,.65556,.11156,0,.5],49:[0,.65556,.11156,0,.5],50:[0,.65556,.11156,0,.5],51:[0,.65556,.11156,0,.5],52:[0,.65556,.11156,0,.5],53:[0,.65556,.11156,0,.5],54:[0,.65556,.11156,0,.5],55:[0,.65556,.11156,0,.5],56:[0,.65556,.11156,0,.5],57:[0,.65556,.11156,0,.5],58:[0,.44444,.02502,0,.27778],59:[.125,.44444,.02502,0,.27778],61:[-.13,.37,.05087,0,.77778],63:[0,.69444,.11809,0,.47222],64:[0,.69444,.07555,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,.08293,0,.66667],67:[0,.69444,.11983,0,.63889],68:[0,.69444,.07555,0,.72223],69:[0,.69444,.11983,0,.59722],70:[0,.69444,.13372,0,.56945],71:[0,.69444,.11983,0,.66667],72:[0,.69444,.08094,0,.70834],73:[0,.69444,.13372,0,.27778],74:[0,.69444,.08094,0,.47222],75:[0,.69444,.11983,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,.08094,0,.875],78:[0,.69444,.08094,0,.70834],79:[0,.69444,.07555,0,.73611],80:[0,.69444,.08293,0,.63889],81:[.125,.69444,.07555,0,.73611],82:[0,.69444,.08293,0,.64584],83:[0,.69444,.09205,0,.55556],84:[0,.69444,.13372,0,.68056],85:[0,.69444,.08094,0,.6875],86:[0,.69444,.1615,0,.66667],87:[0,.69444,.1615,0,.94445],88:[0,.69444,.13372,0,.66667],89:[0,.69444,.17261,0,.66667],90:[0,.69444,.11983,0,.61111],91:[.25,.75,.15942,0,.28889],93:[.25,.75,.08719,0,.28889],94:[0,.69444,.0799,0,.5],95:[.35,.09444,.08616,0,.5],97:[0,.44444,.00981,0,.48056],98:[0,.69444,.03057,0,.51667],99:[0,.44444,.08336,0,.44445],100:[0,.69444,.09483,0,.51667],101:[0,.44444,.06778,0,.44445],102:[0,.69444,.21705,0,.30556],103:[.19444,.44444,.10836,0,.5],104:[0,.69444,.01778,0,.51667],105:[0,.67937,.09718,0,.23889],106:[.19444,.67937,.09162,0,.26667],107:[0,.69444,.08336,0,.48889],108:[0,.69444,.09483,0,.23889],109:[0,.44444,.01778,0,.79445],110:[0,.44444,.01778,0,.51667],111:[0,.44444,.06613,0,.5],112:[.19444,.44444,.0389,0,.51667],113:[.19444,.44444,.04169,0,.51667],114:[0,.44444,.10836,0,.34167],115:[0,.44444,.0778,0,.38333],116:[0,.57143,.07225,0,.36111],117:[0,.44444,.04169,0,.51667],118:[0,.44444,.10836,0,.46111],119:[0,.44444,.10836,0,.68334],120:[0,.44444,.09169,0,.46111],121:[.19444,.44444,.10836,0,.46111],122:[0,.44444,.08752,0,.43472],126:[.35,.32659,.08826,0,.5],160:[0,0,0,0,.25],168:[0,.67937,.06385,0,.5],176:[0,.69444,0,0,.73752],184:[.17014,0,0,0,.44445],305:[0,.44444,.04169,0,.23889],567:[.19444,.44444,.04169,0,.26667],710:[0,.69444,.0799,0,.5],711:[0,.63194,.08432,0,.5],713:[0,.60889,.08776,0,.5],714:[0,.69444,.09205,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,.09483,0,.5],729:[0,.67937,.07774,0,.27778],730:[0,.69444,0,0,.73752],732:[0,.67659,.08826,0,.5],733:[0,.69444,.09205,0,.5],915:[0,.69444,.13372,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,.07555,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,.12816,0,.66667],928:[0,.69444,.08094,0,.70834],931:[0,.69444,.11983,0,.72222],933:[0,.69444,.09031,0,.77778],934:[0,.69444,.04603,0,.72222],936:[0,.69444,.09031,0,.77778],937:[0,.69444,.08293,0,.72222],8211:[0,.44444,.08616,0,.5],8212:[0,.44444,.08616,0,1],8216:[0,.69444,.07816,0,.27778],8217:[0,.69444,.07816,0,.27778],8220:[0,.69444,.14205,0,.5],8221:[0,.69444,.00316,0,.5]},"SansSerif-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.31945],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.75834],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,0,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.65556,0,0,.5],49:[0,.65556,0,0,.5],50:[0,.65556,0,0,.5],51:[0,.65556,0,0,.5],52:[0,.65556,0,0,.5],53:[0,.65556,0,0,.5],54:[0,.65556,0,0,.5],55:[0,.65556,0,0,.5],56:[0,.65556,0,0,.5],57:[0,.65556,0,0,.5],58:[0,.44444,0,0,.27778],59:[.125,.44444,0,0,.27778],61:[-.13,.37,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,0,0,.66667],67:[0,.69444,0,0,.63889],68:[0,.69444,0,0,.72223],69:[0,.69444,0,0,.59722],70:[0,.69444,0,0,.56945],71:[0,.69444,0,0,.66667],72:[0,.69444,0,0,.70834],73:[0,.69444,0,0,.27778],74:[0,.69444,0,0,.47222],75:[0,.69444,0,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,0,0,.875],78:[0,.69444,0,0,.70834],79:[0,.69444,0,0,.73611],80:[0,.69444,0,0,.63889],81:[.125,.69444,0,0,.73611],82:[0,.69444,0,0,.64584],83:[0,.69444,0,0,.55556],84:[0,.69444,0,0,.68056],85:[0,.69444,0,0,.6875],86:[0,.69444,.01389,0,.66667],87:[0,.69444,.01389,0,.94445],88:[0,.69444,0,0,.66667],89:[0,.69444,.025,0,.66667],90:[0,.69444,0,0,.61111],91:[.25,.75,0,0,.28889],93:[.25,.75,0,0,.28889],94:[0,.69444,0,0,.5],95:[.35,.09444,.02778,0,.5],97:[0,.44444,0,0,.48056],98:[0,.69444,0,0,.51667],99:[0,.44444,0,0,.44445],100:[0,.69444,0,0,.51667],101:[0,.44444,0,0,.44445],102:[0,.69444,.06944,0,.30556],103:[.19444,.44444,.01389,0,.5],104:[0,.69444,0,0,.51667],105:[0,.67937,0,0,.23889],106:[.19444,.67937,0,0,.26667],107:[0,.69444,0,0,.48889],108:[0,.69444,0,0,.23889],109:[0,.44444,0,0,.79445],110:[0,.44444,0,0,.51667],111:[0,.44444,0,0,.5],112:[.19444,.44444,0,0,.51667],113:[.19444,.44444,0,0,.51667],114:[0,.44444,.01389,0,.34167],115:[0,.44444,0,0,.38333],116:[0,.57143,0,0,.36111],117:[0,.44444,0,0,.51667],118:[0,.44444,.01389,0,.46111],119:[0,.44444,.01389,0,.68334],120:[0,.44444,0,0,.46111],121:[.19444,.44444,.01389,0,.46111],122:[0,.44444,0,0,.43472],126:[.35,.32659,0,0,.5],160:[0,0,0,0,.25],168:[0,.67937,0,0,.5],176:[0,.69444,0,0,.66667],184:[.17014,0,0,0,.44445],305:[0,.44444,0,0,.23889],567:[.19444,.44444,0,0,.26667],710:[0,.69444,0,0,.5],711:[0,.63194,0,0,.5],713:[0,.60889,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.67937,0,0,.27778],730:[0,.69444,0,0,.66667],732:[0,.67659,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.69444,0,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,0,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,0,0,.66667],928:[0,.69444,0,0,.70834],931:[0,.69444,0,0,.72222],933:[0,.69444,0,0,.77778],934:[0,.69444,0,0,.72222],936:[0,.69444,0,0,.77778],937:[0,.69444,0,0,.72222],8211:[0,.44444,.02778,0,.5],8212:[0,.44444,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5]},"Script-Regular":{32:[0,0,0,0,.25],65:[0,.7,.22925,0,.80253],66:[0,.7,.04087,0,.90757],67:[0,.7,.1689,0,.66619],68:[0,.7,.09371,0,.77443],69:[0,.7,.18583,0,.56162],70:[0,.7,.13634,0,.89544],71:[0,.7,.17322,0,.60961],72:[0,.7,.29694,0,.96919],73:[0,.7,.19189,0,.80907],74:[.27778,.7,.19189,0,1.05159],75:[0,.7,.31259,0,.91364],76:[0,.7,.19189,0,.87373],77:[0,.7,.15981,0,1.08031],78:[0,.7,.3525,0,.9015],79:[0,.7,.08078,0,.73787],80:[0,.7,.08078,0,1.01262],81:[0,.7,.03305,0,.88282],82:[0,.7,.06259,0,.85],83:[0,.7,.19189,0,.86767],84:[0,.7,.29087,0,.74697],85:[0,.7,.25815,0,.79996],86:[0,.7,.27523,0,.62204],87:[0,.7,.27523,0,.80532],88:[0,.7,.26006,0,.94445],89:[0,.7,.2939,0,.70961],90:[0,.7,.24037,0,.8212],160:[0,0,0,0,.25]},"Size1-Regular":{32:[0,0,0,0,.25],40:[.35001,.85,0,0,.45834],41:[.35001,.85,0,0,.45834],47:[.35001,.85,0,0,.57778],91:[.35001,.85,0,0,.41667],92:[.35001,.85,0,0,.57778],93:[.35001,.85,0,0,.41667],123:[.35001,.85,0,0,.58334],125:[.35001,.85,0,0,.58334],160:[0,0,0,0,.25],710:[0,.72222,0,0,.55556],732:[0,.72222,0,0,.55556],770:[0,.72222,0,0,.55556],771:[0,.72222,0,0,.55556],8214:[-99e-5,.601,0,0,.77778],8593:[1e-5,.6,0,0,.66667],8595:[1e-5,.6,0,0,.66667],8657:[1e-5,.6,0,0,.77778],8659:[1e-5,.6,0,0,.77778],8719:[.25001,.75,0,0,.94445],8720:[.25001,.75,0,0,.94445],8721:[.25001,.75,0,0,1.05556],8730:[.35001,.85,0,0,1],8739:[-.00599,.606,0,0,.33333],8741:[-.00599,.606,0,0,.55556],8747:[.30612,.805,.19445,0,.47222],8748:[.306,.805,.19445,0,.47222],8749:[.306,.805,.19445,0,.47222],8750:[.30612,.805,.19445,0,.47222],8896:[.25001,.75,0,0,.83334],8897:[.25001,.75,0,0,.83334],8898:[.25001,.75,0,0,.83334],8899:[.25001,.75,0,0,.83334],8968:[.35001,.85,0,0,.47222],8969:[.35001,.85,0,0,.47222],8970:[.35001,.85,0,0,.47222],8971:[.35001,.85,0,0,.47222],9168:[-99e-5,.601,0,0,.66667],10216:[.35001,.85,0,0,.47222],10217:[.35001,.85,0,0,.47222],10752:[.25001,.75,0,0,1.11111],10753:[.25001,.75,0,0,1.11111],10754:[.25001,.75,0,0,1.11111],10756:[.25001,.75,0,0,.83334],10758:[.25001,.75,0,0,.83334]},"Size2-Regular":{32:[0,0,0,0,.25],40:[.65002,1.15,0,0,.59722],41:[.65002,1.15,0,0,.59722],47:[.65002,1.15,0,0,.81111],91:[.65002,1.15,0,0,.47222],92:[.65002,1.15,0,0,.81111],93:[.65002,1.15,0,0,.47222],123:[.65002,1.15,0,0,.66667],125:[.65002,1.15,0,0,.66667],160:[0,0,0,0,.25],710:[0,.75,0,0,1],732:[0,.75,0,0,1],770:[0,.75,0,0,1],771:[0,.75,0,0,1],8719:[.55001,1.05,0,0,1.27778],8720:[.55001,1.05,0,0,1.27778],8721:[.55001,1.05,0,0,1.44445],8730:[.65002,1.15,0,0,1],8747:[.86225,1.36,.44445,0,.55556],8748:[.862,1.36,.44445,0,.55556],8749:[.862,1.36,.44445,0,.55556],8750:[.86225,1.36,.44445,0,.55556],8896:[.55001,1.05,0,0,1.11111],8897:[.55001,1.05,0,0,1.11111],8898:[.55001,1.05,0,0,1.11111],8899:[.55001,1.05,0,0,1.11111],8968:[.65002,1.15,0,0,.52778],8969:[.65002,1.15,0,0,.52778],8970:[.65002,1.15,0,0,.52778],8971:[.65002,1.15,0,0,.52778],10216:[.65002,1.15,0,0,.61111],10217:[.65002,1.15,0,0,.61111],10752:[.55001,1.05,0,0,1.51112],10753:[.55001,1.05,0,0,1.51112],10754:[.55001,1.05,0,0,1.51112],10756:[.55001,1.05,0,0,1.11111],10758:[.55001,1.05,0,0,1.11111]},"Size3-Regular":{32:[0,0,0,0,.25],40:[.95003,1.45,0,0,.73611],41:[.95003,1.45,0,0,.73611],47:[.95003,1.45,0,0,1.04445],91:[.95003,1.45,0,0,.52778],92:[.95003,1.45,0,0,1.04445],93:[.95003,1.45,0,0,.52778],123:[.95003,1.45,0,0,.75],125:[.95003,1.45,0,0,.75],160:[0,0,0,0,.25],710:[0,.75,0,0,1.44445],732:[0,.75,0,0,1.44445],770:[0,.75,0,0,1.44445],771:[0,.75,0,0,1.44445],8730:[.95003,1.45,0,0,1],8968:[.95003,1.45,0,0,.58334],8969:[.95003,1.45,0,0,.58334],8970:[.95003,1.45,0,0,.58334],8971:[.95003,1.45,0,0,.58334],10216:[.95003,1.45,0,0,.75],10217:[.95003,1.45,0,0,.75]},"Size4-Regular":{32:[0,0,0,0,.25],40:[1.25003,1.75,0,0,.79167],41:[1.25003,1.75,0,0,.79167],47:[1.25003,1.75,0,0,1.27778],91:[1.25003,1.75,0,0,.58334],92:[1.25003,1.75,0,0,1.27778],93:[1.25003,1.75,0,0,.58334],123:[1.25003,1.75,0,0,.80556],125:[1.25003,1.75,0,0,.80556],160:[0,0,0,0,.25],710:[0,.825,0,0,1.8889],732:[0,.825,0,0,1.8889],770:[0,.825,0,0,1.8889],771:[0,.825,0,0,1.8889],8730:[1.25003,1.75,0,0,1],8968:[1.25003,1.75,0,0,.63889],8969:[1.25003,1.75,0,0,.63889],8970:[1.25003,1.75,0,0,.63889],8971:[1.25003,1.75,0,0,.63889],9115:[.64502,1.155,0,0,.875],9116:[1e-5,.6,0,0,.875],9117:[.64502,1.155,0,0,.875],9118:[.64502,1.155,0,0,.875],9119:[1e-5,.6,0,0,.875],9120:[.64502,1.155,0,0,.875],9121:[.64502,1.155,0,0,.66667],9122:[-99e-5,.601,0,0,.66667],9123:[.64502,1.155,0,0,.66667],9124:[.64502,1.155,0,0,.66667],9125:[-99e-5,.601,0,0,.66667],9126:[.64502,1.155,0,0,.66667],9127:[1e-5,.9,0,0,.88889],9128:[.65002,1.15,0,0,.88889],9129:[.90001,0,0,0,.88889],9130:[0,.3,0,0,.88889],9131:[1e-5,.9,0,0,.88889],9132:[.65002,1.15,0,0,.88889],9133:[.90001,0,0,0,.88889],9143:[.88502,.915,0,0,1.05556],10216:[1.25003,1.75,0,0,.80556],10217:[1.25003,1.75,0,0,.80556],57344:[-.00499,.605,0,0,1.05556],57345:[-.00499,.605,0,0,1.05556],57680:[0,.12,0,0,.45],57681:[0,.12,0,0,.45],57682:[0,.12,0,0,.45],57683:[0,.12,0,0,.45]},"Typewriter-Regular":{32:[0,0,0,0,.525],33:[0,.61111,0,0,.525],34:[0,.61111,0,0,.525],35:[0,.61111,0,0,.525],36:[.08333,.69444,0,0,.525],37:[.08333,.69444,0,0,.525],38:[0,.61111,0,0,.525],39:[0,.61111,0,0,.525],40:[.08333,.69444,0,0,.525],41:[.08333,.69444,0,0,.525],42:[0,.52083,0,0,.525],43:[-.08056,.53055,0,0,.525],44:[.13889,.125,0,0,.525],45:[-.08056,.53055,0,0,.525],46:[0,.125,0,0,.525],47:[.08333,.69444,0,0,.525],48:[0,.61111,0,0,.525],49:[0,.61111,0,0,.525],50:[0,.61111,0,0,.525],51:[0,.61111,0,0,.525],52:[0,.61111,0,0,.525],53:[0,.61111,0,0,.525],54:[0,.61111,0,0,.525],55:[0,.61111,0,0,.525],56:[0,.61111,0,0,.525],57:[0,.61111,0,0,.525],58:[0,.43056,0,0,.525],59:[.13889,.43056,0,0,.525],60:[-.05556,.55556,0,0,.525],61:[-.19549,.41562,0,0,.525],62:[-.05556,.55556,0,0,.525],63:[0,.61111,0,0,.525],64:[0,.61111,0,0,.525],65:[0,.61111,0,0,.525],66:[0,.61111,0,0,.525],67:[0,.61111,0,0,.525],68:[0,.61111,0,0,.525],69:[0,.61111,0,0,.525],70:[0,.61111,0,0,.525],71:[0,.61111,0,0,.525],72:[0,.61111,0,0,.525],73:[0,.61111,0,0,.525],74:[0,.61111,0,0,.525],75:[0,.61111,0,0,.525],76:[0,.61111,0,0,.525],77:[0,.61111,0,0,.525],78:[0,.61111,0,0,.525],79:[0,.61111,0,0,.525],80:[0,.61111,0,0,.525],81:[.13889,.61111,0,0,.525],82:[0,.61111,0,0,.525],83:[0,.61111,0,0,.525],84:[0,.61111,0,0,.525],85:[0,.61111,0,0,.525],86:[0,.61111,0,0,.525],87:[0,.61111,0,0,.525],88:[0,.61111,0,0,.525],89:[0,.61111,0,0,.525],90:[0,.61111,0,0,.525],91:[.08333,.69444,0,0,.525],92:[.08333,.69444,0,0,.525],93:[.08333,.69444,0,0,.525],94:[0,.61111,0,0,.525],95:[.09514,0,0,0,.525],96:[0,.61111,0,0,.525],97:[0,.43056,0,0,.525],98:[0,.61111,0,0,.525],99:[0,.43056,0,0,.525],100:[0,.61111,0,0,.525],101:[0,.43056,0,0,.525],102:[0,.61111,0,0,.525],103:[.22222,.43056,0,0,.525],104:[0,.61111,0,0,.525],105:[0,.61111,0,0,.525],106:[.22222,.61111,0,0,.525],107:[0,.61111,0,0,.525],108:[0,.61111,0,0,.525],109:[0,.43056,0,0,.525],110:[0,.43056,0,0,.525],111:[0,.43056,0,0,.525],112:[.22222,.43056,0,0,.525],113:[.22222,.43056,0,0,.525],114:[0,.43056,0,0,.525],115:[0,.43056,0,0,.525],116:[0,.55358,0,0,.525],117:[0,.43056,0,0,.525],118:[0,.43056,0,0,.525],119:[0,.43056,0,0,.525],120:[0,.43056,0,0,.525],121:[.22222,.43056,0,0,.525],122:[0,.43056,0,0,.525],123:[.08333,.69444,0,0,.525],124:[.08333,.69444,0,0,.525],125:[.08333,.69444,0,0,.525],126:[0,.61111,0,0,.525],127:[0,.61111,0,0,.525],160:[0,0,0,0,.525],176:[0,.61111,0,0,.525],184:[.19445,0,0,0,.525],305:[0,.43056,0,0,.525],567:[.22222,.43056,0,0,.525],711:[0,.56597,0,0,.525],713:[0,.56555,0,0,.525],714:[0,.61111,0,0,.525],715:[0,.61111,0,0,.525],728:[0,.61111,0,0,.525],730:[0,.61111,0,0,.525],770:[0,.61111,0,0,.525],771:[0,.61111,0,0,.525],776:[0,.61111,0,0,.525],915:[0,.61111,0,0,.525],916:[0,.61111,0,0,.525],920:[0,.61111,0,0,.525],923:[0,.61111,0,0,.525],926:[0,.61111,0,0,.525],928:[0,.61111,0,0,.525],931:[0,.61111,0,0,.525],933:[0,.61111,0,0,.525],934:[0,.61111,0,0,.525],936:[0,.61111,0,0,.525],937:[0,.61111,0,0,.525],8216:[0,.61111,0,0,.525],8217:[0,.61111,0,0,.525],8242:[0,.61111,0,0,.525],9251:[.11111,.21944,0,0,.525]}},We={slant:[.25,.25,.25],space:[0,0,0],stretch:[0,0,0],shrink:[0,0,0],xHeight:[.431,.431,.431],quad:[1,1.171,1.472],extraSpace:[0,0,0],num1:[.677,.732,.925],num2:[.394,.384,.387],num3:[.444,.471,.504],denom1:[.686,.752,1.025],denom2:[.345,.344,.532],sup1:[.413,.503,.504],sup2:[.363,.431,.404],sup3:[.289,.286,.294],sub1:[.15,.143,.2],sub2:[.247,.286,.4],supDrop:[.386,.353,.494],subDrop:[.05,.071,.1],delim1:[2.39,1.7,1.98],delim2:[1.01,1.157,1.42],axisHeight:[.25,.25,.25],defaultRuleThickness:[.04,.049,.049],bigOpSpacing1:[.111,.111,.111],bigOpSpacing2:[.166,.166,.166],bigOpSpacing3:[.2,.2,.2],bigOpSpacing4:[.6,.611,.611],bigOpSpacing5:[.1,.143,.143],sqrtRuleThickness:[.04,.04,.04],ptPerEm:[10,10,10],doubleRuleSep:[.2,.2,.2],arrayRuleWidth:[.04,.04,.04],fboxsep:[.3,.3,.3],fboxrule:[.04,.04,.04]},Ge={Å:`A`,Ð:`D`,Þ:`o`,å:`a`,ð:`d`,þ:`o`,А:`A`,Б:`B`,В:`B`,Г:`F`,Д:`A`,Е:`E`,Ж:`K`,З:`3`,И:`N`,Й:`N`,К:`K`,Л:`N`,М:`M`,Н:`H`,О:`O`,П:`N`,Р:`P`,С:`C`,Т:`T`,У:`y`,Ф:`O`,Х:`X`,Ц:`U`,Ч:`h`,Ш:`W`,Щ:`W`,Ъ:`B`,Ы:`X`,Ь:`B`,Э:`3`,Ю:`X`,Я:`R`,а:`a`,б:`b`,в:`a`,г:`r`,д:`y`,е:`e`,ж:`m`,з:`e`,и:`n`,й:`n`,к:`n`,л:`n`,м:`m`,н:`n`,о:`o`,п:`n`,р:`p`,с:`c`,т:`o`,у:`y`,ф:`b`,х:`x`,ц:`n`,ч:`n`,ш:`w`,щ:`w`,ъ:`a`,ы:`m`,ь:`a`,э:`e`,ю:`m`,я:`r`};function Ke(e,t){Ue[e]=t}function qe(e,t,n){if(!Ue[t])throw Error(`Font metrics not found for font: `+t+`.`);var r=e.charCodeAt(0),i=Ue[t][r];if(!i&&e[0]in Ge&&(r=Ge[e[0]].charCodeAt(0),i=Ue[t][r]),!i&&n===`text`&&ce(r)&&(i=Ue[t][77]),i)return{depth:i[0],height:i[1],italic:i[2],skew:i[3],width:i[4]}}var Je={};function Ye(e){var t=e>=5?0:e>=3?1:2;if(!Je[t]){var n=Je[t]={cssEmPerMu:We.quad[t]/18};for(var r in We)We.hasOwnProperty(r)&&(n[r]=We[r][t])}return Je[t]}var A={math:{},text:{}};function j(e,t,n,r,i,a){A[e][i]={font:t,group:n,replace:r},a&&r&&(A[e][r]=A[e][i])}var M=`math`,N=`text`,P=`main`,F=`ams`,I=`accent-token`,L=`bin`,Xe=`close`,Ze=`inner`,R=`mathord`,z=`op-token`,Qe=`open`,$e=`punct`,B=`rel`,et=`spacing`,V=`textord`;j(M,P,B,`≡`,`\\equiv`,!0),j(M,P,B,`≺`,`\\prec`,!0),j(M,P,B,`≻`,`\\succ`,!0),j(M,P,B,`∼`,`\\sim`,!0),j(M,P,B,`⊥`,`\\perp`),j(M,P,B,`⪯`,`\\preceq`,!0),j(M,P,B,`⪰`,`\\succeq`,!0),j(M,P,B,`≃`,`\\simeq`,!0),j(M,P,B,`∣`,`\\mid`,!0),j(M,P,B,`≪`,`\\ll`,!0),j(M,P,B,`≫`,`\\gg`,!0),j(M,P,B,`≍`,`\\asymp`,!0),j(M,P,B,`∥`,`\\parallel`),j(M,P,B,`⋈`,`\\bowtie`,!0),j(M,P,B,`⌣`,`\\smile`,!0),j(M,P,B,`⊑`,`\\sqsubseteq`,!0),j(M,P,B,`⊒`,`\\sqsupseteq`,!0),j(M,P,B,`≐`,`\\doteq`,!0),j(M,P,B,`⌢`,`\\frown`,!0),j(M,P,B,`∋`,`\\ni`,!0),j(M,P,B,`∝`,`\\propto`,!0),j(M,P,B,`⊢`,`\\vdash`,!0),j(M,P,B,`⊣`,`\\dashv`,!0),j(M,P,B,`∋`,`\\owns`),j(M,P,$e,`.`,`\\ldotp`),j(M,P,$e,`⋅`,`\\cdotp`),j(M,P,$e,`⋅`,`·`),j(N,P,V,`⋅`,`·`),j(M,P,V,`#`,`\\#`),j(N,P,V,`#`,`\\#`),j(M,P,V,`&`,`\\&`),j(N,P,V,`&`,`\\&`),j(M,P,V,`ℵ`,`\\aleph`,!0),j(M,P,V,`∀`,`\\forall`,!0),j(M,P,V,`ℏ`,`\\hbar`,!0),j(M,P,V,`∃`,`\\exists`,!0),j(M,P,V,`∇`,`\\nabla`,!0),j(M,P,V,`♭`,`\\flat`,!0),j(M,P,V,`ℓ`,`\\ell`,!0),j(M,P,V,`♮`,`\\natural`,!0),j(M,P,V,`♣`,`\\clubsuit`,!0),j(M,P,V,`℘`,`\\wp`,!0),j(M,P,V,`♯`,`\\sharp`,!0),j(M,P,V,`♢`,`\\diamondsuit`,!0),j(M,P,V,`ℜ`,`\\Re`,!0),j(M,P,V,`♡`,`\\heartsuit`,!0),j(M,P,V,`ℑ`,`\\Im`,!0),j(M,P,V,`♠`,`\\spadesuit`,!0),j(M,P,V,`§`,`\\S`,!0),j(N,P,V,`§`,`\\S`),j(M,P,V,`¶`,`\\P`,!0),j(N,P,V,`¶`,`\\P`),j(M,P,V,`†`,`\\dag`),j(N,P,V,`†`,`\\dag`),j(N,P,V,`†`,`\\textdagger`),j(M,P,V,`‡`,`\\ddag`),j(N,P,V,`‡`,`\\ddag`),j(N,P,V,`‡`,`\\textdaggerdbl`),j(M,P,Xe,`⎱`,`\\rmoustache`,!0),j(M,P,Qe,`⎰`,`\\lmoustache`,!0),j(M,P,Xe,`⟯`,`\\rgroup`,!0),j(M,P,Qe,`⟮`,`\\lgroup`,!0),j(M,P,L,`∓`,`\\mp`,!0),j(M,P,L,`⊖`,`\\ominus`,!0),j(M,P,L,`⊎`,`\\uplus`,!0),j(M,P,L,`⊓`,`\\sqcap`,!0),j(M,P,L,`∗`,`\\ast`),j(M,P,L,`⊔`,`\\sqcup`,!0),j(M,P,L,`◯`,`\\bigcirc`,!0),j(M,P,L,`∙`,`\\bullet`,!0),j(M,P,L,`‡`,`\\ddagger`),j(M,P,L,`≀`,`\\wr`,!0),j(M,P,L,`⨿`,`\\amalg`),j(M,P,L,`&`,`\\And`),j(M,P,B,`⟵`,`\\longleftarrow`,!0),j(M,P,B,`⇐`,`\\Leftarrow`,!0),j(M,P,B,`⟸`,`\\Longleftarrow`,!0),j(M,P,B,`⟶`,`\\longrightarrow`,!0),j(M,P,B,`⇒`,`\\Rightarrow`,!0),j(M,P,B,`⟹`,`\\Longrightarrow`,!0),j(M,P,B,`↔`,`\\leftrightarrow`,!0),j(M,P,B,`⟷`,`\\longleftrightarrow`,!0),j(M,P,B,`⇔`,`\\Leftrightarrow`,!0),j(M,P,B,`⟺`,`\\Longleftrightarrow`,!0),j(M,P,B,`↦`,`\\mapsto`,!0),j(M,P,B,`⟼`,`\\longmapsto`,!0),j(M,P,B,`↗`,`\\nearrow`,!0),j(M,P,B,`↩`,`\\hookleftarrow`,!0),j(M,P,B,`↪`,`\\hookrightarrow`,!0),j(M,P,B,`↘`,`\\searrow`,!0),j(M,P,B,`↼`,`\\leftharpoonup`,!0),j(M,P,B,`⇀`,`\\rightharpoonup`,!0),j(M,P,B,`↙`,`\\swarrow`,!0),j(M,P,B,`↽`,`\\leftharpoondown`,!0),j(M,P,B,`⇁`,`\\rightharpoondown`,!0),j(M,P,B,`↖`,`\\nwarrow`,!0),j(M,P,B,`⇌`,`\\rightleftharpoons`,!0),j(M,F,B,`≮`,`\\nless`,!0),j(M,F,B,``,`\\@nleqslant`),j(M,F,B,``,`\\@nleqq`),j(M,F,B,`⪇`,`\\lneq`,!0),j(M,F,B,`≨`,`\\lneqq`,!0),j(M,F,B,``,`\\@lvertneqq`),j(M,F,B,`⋦`,`\\lnsim`,!0),j(M,F,B,`⪉`,`\\lnapprox`,!0),j(M,F,B,`⊀`,`\\nprec`,!0),j(M,F,B,`⋠`,`\\npreceq`,!0),j(M,F,B,`⋨`,`\\precnsim`,!0),j(M,F,B,`⪹`,`\\precnapprox`,!0),j(M,F,B,`≁`,`\\nsim`,!0),j(M,F,B,``,`\\@nshortmid`),j(M,F,B,`∤`,`\\nmid`,!0),j(M,F,B,`⊬`,`\\nvdash`,!0),j(M,F,B,`⊭`,`\\nvDash`,!0),j(M,F,B,`⋪`,`\\ntriangleleft`),j(M,F,B,`⋬`,`\\ntrianglelefteq`,!0),j(M,F,B,`⊊`,`\\subsetneq`,!0),j(M,F,B,``,`\\@varsubsetneq`),j(M,F,B,`⫋`,`\\subsetneqq`,!0),j(M,F,B,``,`\\@varsubsetneqq`),j(M,F,B,`≯`,`\\ngtr`,!0),j(M,F,B,``,`\\@ngeqslant`),j(M,F,B,``,`\\@ngeqq`),j(M,F,B,`⪈`,`\\gneq`,!0),j(M,F,B,`≩`,`\\gneqq`,!0),j(M,F,B,``,`\\@gvertneqq`),j(M,F,B,`⋧`,`\\gnsim`,!0),j(M,F,B,`⪊`,`\\gnapprox`,!0),j(M,F,B,`⊁`,`\\nsucc`,!0),j(M,F,B,`⋡`,`\\nsucceq`,!0),j(M,F,B,`⋩`,`\\succnsim`,!0),j(M,F,B,`⪺`,`\\succnapprox`,!0),j(M,F,B,`≆`,`\\ncong`,!0),j(M,F,B,``,`\\@nshortparallel`),j(M,F,B,`∦`,`\\nparallel`,!0),j(M,F,B,`⊯`,`\\nVDash`,!0),j(M,F,B,`⋫`,`\\ntriangleright`),j(M,F,B,`⋭`,`\\ntrianglerighteq`,!0),j(M,F,B,``,`\\@nsupseteqq`),j(M,F,B,`⊋`,`\\supsetneq`,!0),j(M,F,B,``,`\\@varsupsetneq`),j(M,F,B,`⫌`,`\\supsetneqq`,!0),j(M,F,B,``,`\\@varsupsetneqq`),j(M,F,B,`⊮`,`\\nVdash`,!0),j(M,F,B,`⪵`,`\\precneqq`,!0),j(M,F,B,`⪶`,`\\succneqq`,!0),j(M,F,B,``,`\\@nsubseteqq`),j(M,F,L,`⊴`,`\\unlhd`),j(M,F,L,`⊵`,`\\unrhd`),j(M,F,B,`↚`,`\\nleftarrow`,!0),j(M,F,B,`↛`,`\\nrightarrow`,!0),j(M,F,B,`⇍`,`\\nLeftarrow`,!0),j(M,F,B,`⇏`,`\\nRightarrow`,!0),j(M,F,B,`↮`,`\\nleftrightarrow`,!0),j(M,F,B,`⇎`,`\\nLeftrightarrow`,!0),j(M,F,B,`△`,`\\vartriangle`),j(M,F,V,`ℏ`,`\\hslash`),j(M,F,V,`▽`,`\\triangledown`),j(M,F,V,`◊`,`\\lozenge`),j(M,F,V,`Ⓢ`,`\\circledS`),j(M,F,V,`®`,`\\circledR`),j(N,F,V,`®`,`\\circledR`),j(M,F,V,`∡`,`\\measuredangle`,!0),j(M,F,V,`∄`,`\\nexists`),j(M,F,V,`℧`,`\\mho`),j(M,F,V,`Ⅎ`,`\\Finv`,!0),j(M,F,V,`⅁`,`\\Game`,!0),j(M,F,V,`‵`,`\\backprime`),j(M,F,V,`▲`,`\\blacktriangle`),j(M,F,V,`▼`,`\\blacktriangledown`),j(M,F,V,`■`,`\\blacksquare`),j(M,F,V,`⧫`,`\\blacklozenge`),j(M,F,V,`★`,`\\bigstar`),j(M,F,V,`∢`,`\\sphericalangle`,!0),j(M,F,V,`∁`,`\\complement`,!0),j(M,F,V,`ð`,`\\eth`,!0),j(N,P,V,`ð`,`ð`),j(M,F,V,`╱`,`\\diagup`),j(M,F,V,`╲`,`\\diagdown`),j(M,F,V,`□`,`\\square`),j(M,F,V,`□`,`\\Box`),j(M,F,V,`◊`,`\\Diamond`),j(M,F,V,`¥`,`\\yen`,!0),j(N,F,V,`¥`,`\\yen`,!0),j(M,F,V,`✓`,`\\checkmark`,!0),j(N,F,V,`✓`,`\\checkmark`),j(M,F,V,`ℶ`,`\\beth`,!0),j(M,F,V,`ℸ`,`\\daleth`,!0),j(M,F,V,`ℷ`,`\\gimel`,!0),j(M,F,V,`ϝ`,`\\digamma`,!0),j(M,F,V,`ϰ`,`\\varkappa`),j(M,F,Qe,`┌`,`\\@ulcorner`,!0),j(M,F,Xe,`┐`,`\\@urcorner`,!0),j(M,F,Qe,`└`,`\\@llcorner`,!0),j(M,F,Xe,`┘`,`\\@lrcorner`,!0),j(M,F,B,`≦`,`\\leqq`,!0),j(M,F,B,`⩽`,`\\leqslant`,!0),j(M,F,B,`⪕`,`\\eqslantless`,!0),j(M,F,B,`≲`,`\\lesssim`,!0),j(M,F,B,`⪅`,`\\lessapprox`,!0),j(M,F,B,`≊`,`\\approxeq`,!0),j(M,F,L,`⋖`,`\\lessdot`),j(M,F,B,`⋘`,`\\lll`,!0),j(M,F,B,`≶`,`\\lessgtr`,!0),j(M,F,B,`⋚`,`\\lesseqgtr`,!0),j(M,F,B,`⪋`,`\\lesseqqgtr`,!0),j(M,F,B,`≑`,`\\doteqdot`),j(M,F,B,`≓`,`\\risingdotseq`,!0),j(M,F,B,`≒`,`\\fallingdotseq`,!0),j(M,F,B,`∽`,`\\backsim`,!0),j(M,F,B,`⋍`,`\\backsimeq`,!0),j(M,F,B,`⫅`,`\\subseteqq`,!0),j(M,F,B,`⋐`,`\\Subset`,!0),j(M,F,B,`⊏`,`\\sqsubset`,!0),j(M,F,B,`≼`,`\\preccurlyeq`,!0),j(M,F,B,`⋞`,`\\curlyeqprec`,!0),j(M,F,B,`≾`,`\\precsim`,!0),j(M,F,B,`⪷`,`\\precapprox`,!0),j(M,F,B,`⊲`,`\\vartriangleleft`),j(M,F,B,`⊴`,`\\trianglelefteq`),j(M,F,B,`⊨`,`\\vDash`,!0),j(M,F,B,`⊪`,`\\Vvdash`,!0),j(M,F,B,`⌣`,`\\smallsmile`),j(M,F,B,`⌢`,`\\smallfrown`),j(M,F,B,`≏`,`\\bumpeq`,!0),j(M,F,B,`≎`,`\\Bumpeq`,!0),j(M,F,B,`≧`,`\\geqq`,!0),j(M,F,B,`⩾`,`\\geqslant`,!0),j(M,F,B,`⪖`,`\\eqslantgtr`,!0),j(M,F,B,`≳`,`\\gtrsim`,!0),j(M,F,B,`⪆`,`\\gtrapprox`,!0),j(M,F,L,`⋗`,`\\gtrdot`),j(M,F,B,`⋙`,`\\ggg`,!0),j(M,F,B,`≷`,`\\gtrless`,!0),j(M,F,B,`⋛`,`\\gtreqless`,!0),j(M,F,B,`⪌`,`\\gtreqqless`,!0),j(M,F,B,`≖`,`\\eqcirc`,!0),j(M,F,B,`≗`,`\\circeq`,!0),j(M,F,B,`≜`,`\\triangleq`,!0),j(M,F,B,`∼`,`\\thicksim`),j(M,F,B,`≈`,`\\thickapprox`),j(M,F,B,`⫆`,`\\supseteqq`,!0),j(M,F,B,`⋑`,`\\Supset`,!0),j(M,F,B,`⊐`,`\\sqsupset`,!0),j(M,F,B,`≽`,`\\succcurlyeq`,!0),j(M,F,B,`⋟`,`\\curlyeqsucc`,!0),j(M,F,B,`≿`,`\\succsim`,!0),j(M,F,B,`⪸`,`\\succapprox`,!0),j(M,F,B,`⊳`,`\\vartriangleright`),j(M,F,B,`⊵`,`\\trianglerighteq`),j(M,F,B,`⊩`,`\\Vdash`,!0),j(M,F,B,`∣`,`\\shortmid`),j(M,F,B,`∥`,`\\shortparallel`),j(M,F,B,`≬`,`\\between`,!0),j(M,F,B,`⋔`,`\\pitchfork`,!0),j(M,F,B,`∝`,`\\varpropto`),j(M,F,B,`◀`,`\\blacktriangleleft`),j(M,F,B,`∴`,`\\therefore`,!0),j(M,F,B,`∍`,`\\backepsilon`),j(M,F,B,`▶`,`\\blacktriangleright`),j(M,F,B,`∵`,`\\because`,!0),j(M,F,B,`⋘`,`\\llless`),j(M,F,B,`⋙`,`\\gggtr`),j(M,F,L,`⊲`,`\\lhd`),j(M,F,L,`⊳`,`\\rhd`),j(M,F,B,`≂`,`\\eqsim`,!0),j(M,P,B,`⋈`,`\\Join`),j(M,F,B,`≑`,`\\Doteq`,!0),j(M,F,L,`∔`,`\\dotplus`,!0),j(M,F,L,`∖`,`\\smallsetminus`),j(M,F,L,`⋒`,`\\Cap`,!0),j(M,F,L,`⋓`,`\\Cup`,!0),j(M,F,L,`⩞`,`\\doublebarwedge`,!0),j(M,F,L,`⊟`,`\\boxminus`,!0),j(M,F,L,`⊞`,`\\boxplus`,!0),j(M,F,L,`⋇`,`\\divideontimes`,!0),j(M,F,L,`⋉`,`\\ltimes`,!0),j(M,F,L,`⋊`,`\\rtimes`,!0),j(M,F,L,`⋋`,`\\leftthreetimes`,!0),j(M,F,L,`⋌`,`\\rightthreetimes`,!0),j(M,F,L,`⋏`,`\\curlywedge`,!0),j(M,F,L,`⋎`,`\\curlyvee`,!0),j(M,F,L,`⊝`,`\\circleddash`,!0),j(M,F,L,`⊛`,`\\circledast`,!0),j(M,F,L,`⋅`,`\\centerdot`),j(M,F,L,`⊺`,`\\intercal`,!0),j(M,F,L,`⋒`,`\\doublecap`),j(M,F,L,`⋓`,`\\doublecup`),j(M,F,L,`⊠`,`\\boxtimes`,!0),j(M,F,B,`⇢`,`\\dashrightarrow`,!0),j(M,F,B,`⇠`,`\\dashleftarrow`,!0),j(M,F,B,`⇇`,`\\leftleftarrows`,!0),j(M,F,B,`⇆`,`\\leftrightarrows`,!0),j(M,F,B,`⇚`,`\\Lleftarrow`,!0),j(M,F,B,`↞`,`\\twoheadleftarrow`,!0),j(M,F,B,`↢`,`\\leftarrowtail`,!0),j(M,F,B,`↫`,`\\looparrowleft`,!0),j(M,F,B,`⇋`,`\\leftrightharpoons`,!0),j(M,F,B,`↶`,`\\curvearrowleft`,!0),j(M,F,B,`↺`,`\\circlearrowleft`,!0),j(M,F,B,`↰`,`\\Lsh`,!0),j(M,F,B,`⇈`,`\\upuparrows`,!0),j(M,F,B,`↿`,`\\upharpoonleft`,!0),j(M,F,B,`⇃`,`\\downharpoonleft`,!0),j(M,P,B,`⊶`,`\\origof`,!0),j(M,P,B,`⊷`,`\\imageof`,!0),j(M,F,B,`⊸`,`\\multimap`,!0),j(M,F,B,`↭`,`\\leftrightsquigarrow`,!0),j(M,F,B,`⇉`,`\\rightrightarrows`,!0),j(M,F,B,`⇄`,`\\rightleftarrows`,!0),j(M,F,B,`↠`,`\\twoheadrightarrow`,!0),j(M,F,B,`↣`,`\\rightarrowtail`,!0),j(M,F,B,`↬`,`\\looparrowright`,!0),j(M,F,B,`↷`,`\\curvearrowright`,!0),j(M,F,B,`↻`,`\\circlearrowright`,!0),j(M,F,B,`↱`,`\\Rsh`,!0),j(M,F,B,`⇊`,`\\downdownarrows`,!0),j(M,F,B,`↾`,`\\upharpoonright`,!0),j(M,F,B,`⇂`,`\\downharpoonright`,!0),j(M,F,B,`⇝`,`\\rightsquigarrow`,!0),j(M,F,B,`⇝`,`\\leadsto`),j(M,F,B,`⇛`,`\\Rrightarrow`,!0),j(M,F,B,`↾`,`\\restriction`),j(M,P,V,`‘`,"`"),j(M,P,V,`$`,`\\$`),j(N,P,V,`$`,`\\$`),j(N,P,V,`$`,`\\textdollar`),j(M,P,V,`%`,`\\%`),j(N,P,V,`%`,`\\%`),j(M,P,V,`_`,`\\_`),j(N,P,V,`_`,`\\_`),j(N,P,V,`_`,`\\textunderscore`),j(M,P,V,`∠`,`\\angle`,!0),j(M,P,V,`∞`,`\\infty`,!0),j(M,P,V,`′`,`\\prime`),j(M,P,V,`△`,`\\triangle`),j(M,P,V,`Γ`,`\\Gamma`,!0),j(M,P,V,`Δ`,`\\Delta`,!0),j(M,P,V,`Θ`,`\\Theta`,!0),j(M,P,V,`Λ`,`\\Lambda`,!0),j(M,P,V,`Ξ`,`\\Xi`,!0),j(M,P,V,`Π`,`\\Pi`,!0),j(M,P,V,`Σ`,`\\Sigma`,!0),j(M,P,V,`Υ`,`\\Upsilon`,!0),j(M,P,V,`Φ`,`\\Phi`,!0),j(M,P,V,`Ψ`,`\\Psi`,!0),j(M,P,V,`Ω`,`\\Omega`,!0),j(M,P,V,`A`,`Α`),j(M,P,V,`B`,`Β`),j(M,P,V,`E`,`Ε`),j(M,P,V,`Z`,`Ζ`),j(M,P,V,`H`,`Η`),j(M,P,V,`I`,`Ι`),j(M,P,V,`K`,`Κ`),j(M,P,V,`M`,`Μ`),j(M,P,V,`N`,`Ν`),j(M,P,V,`O`,`Ο`),j(M,P,V,`P`,`Ρ`),j(M,P,V,`T`,`Τ`),j(M,P,V,`X`,`Χ`),j(M,P,V,`¬`,`\\neg`,!0),j(M,P,V,`¬`,`\\lnot`),j(M,P,V,`⊤`,`\\top`),j(M,P,V,`⊥`,`\\bot`),j(M,P,V,`∅`,`\\emptyset`),j(M,F,V,`∅`,`\\varnothing`),j(M,P,R,`α`,`\\alpha`,!0),j(M,P,R,`β`,`\\beta`,!0),j(M,P,R,`γ`,`\\gamma`,!0),j(M,P,R,`δ`,`\\delta`,!0),j(M,P,R,`ϵ`,`\\epsilon`,!0),j(M,P,R,`ζ`,`\\zeta`,!0),j(M,P,R,`η`,`\\eta`,!0),j(M,P,R,`θ`,`\\theta`,!0),j(M,P,R,`ι`,`\\iota`,!0),j(M,P,R,`κ`,`\\kappa`,!0),j(M,P,R,`λ`,`\\lambda`,!0),j(M,P,R,`μ`,`\\mu`,!0),j(M,P,R,`ν`,`\\nu`,!0),j(M,P,R,`ξ`,`\\xi`,!0),j(M,P,R,`ο`,`\\omicron`,!0),j(M,P,R,`π`,`\\pi`,!0),j(M,P,R,`ρ`,`\\rho`,!0),j(M,P,R,`σ`,`\\sigma`,!0),j(M,P,R,`τ`,`\\tau`,!0),j(M,P,R,`υ`,`\\upsilon`,!0),j(M,P,R,`ϕ`,`\\phi`,!0),j(M,P,R,`χ`,`\\chi`,!0),j(M,P,R,`ψ`,`\\psi`,!0),j(M,P,R,`ω`,`\\omega`,!0),j(M,P,R,`ε`,`\\varepsilon`,!0),j(M,P,R,`ϑ`,`\\vartheta`,!0),j(M,P,R,`ϖ`,`\\varpi`,!0),j(M,P,R,`ϱ`,`\\varrho`,!0),j(M,P,R,`ς`,`\\varsigma`,!0),j(M,P,R,`φ`,`\\varphi`,!0),j(M,P,L,`∗`,`*`,!0),j(M,P,L,`+`,`+`),j(M,P,L,`−`,`-`,!0),j(M,P,L,`⋅`,`\\cdot`,!0),j(M,P,L,`∘`,`\\circ`,!0),j(M,P,L,`÷`,`\\div`,!0),j(M,P,L,`±`,`\\pm`,!0),j(M,P,L,`×`,`\\times`,!0),j(M,P,L,`∩`,`\\cap`,!0),j(M,P,L,`∪`,`\\cup`,!0),j(M,P,L,`∖`,`\\setminus`,!0),j(M,P,L,`∧`,`\\land`),j(M,P,L,`∨`,`\\lor`),j(M,P,L,`∧`,`\\wedge`,!0),j(M,P,L,`∨`,`\\vee`,!0),j(M,P,V,`√`,`\\surd`),j(M,P,Qe,`⟨`,`\\langle`,!0),j(M,P,Qe,`∣`,`\\lvert`),j(M,P,Qe,`∥`,`\\lVert`),j(M,P,Xe,`?`,`?`),j(M,P,Xe,`!`,`!`),j(M,P,Xe,`⟩`,`\\rangle`,!0),j(M,P,Xe,`∣`,`\\rvert`),j(M,P,Xe,`∥`,`\\rVert`),j(M,P,B,`=`,`=`),j(M,P,B,`:`,`:`),j(M,P,B,`≈`,`\\approx`,!0),j(M,P,B,`≅`,`\\cong`,!0),j(M,P,B,`≥`,`\\ge`),j(M,P,B,`≥`,`\\geq`,!0),j(M,P,B,`←`,`\\gets`),j(M,P,B,`>`,`\\gt`,!0),j(M,P,B,`∈`,`\\in`,!0),j(M,P,B,``,`\\@not`),j(M,P,B,`⊂`,`\\subset`,!0),j(M,P,B,`⊃`,`\\supset`,!0),j(M,P,B,`⊆`,`\\subseteq`,!0),j(M,P,B,`⊇`,`\\supseteq`,!0),j(M,F,B,`⊈`,`\\nsubseteq`,!0),j(M,F,B,`⊉`,`\\nsupseteq`,!0),j(M,P,B,`⊨`,`\\models`),j(M,P,B,`←`,`\\leftarrow`,!0),j(M,P,B,`≤`,`\\le`),j(M,P,B,`≤`,`\\leq`,!0),j(M,P,B,`<`,`\\lt`,!0),j(M,P,B,`→`,`\\rightarrow`,!0),j(M,P,B,`→`,`\\to`),j(M,F,B,`≱`,`\\ngeq`,!0),j(M,F,B,`≰`,`\\nleq`,!0),j(M,P,et,`\xA0`,`\\ `),j(M,P,et,`\xA0`,`\\space`),j(M,P,et,`\xA0`,`\\nobreakspace`),j(N,P,et,`\xA0`,`\\ `),j(N,P,et,`\xA0`,` `),j(N,P,et,`\xA0`,`\\space`),j(N,P,et,`\xA0`,`\\nobreakspace`),j(M,P,et,``,`\\nobreak`),j(M,P,et,``,`\\allowbreak`),j(M,P,$e,`,`,`,`),j(M,P,$e,`;`,`;`),j(M,F,L,`⊼`,`\\barwedge`,!0),j(M,F,L,`⊻`,`\\veebar`,!0),j(M,P,L,`⊙`,`\\odot`,!0),j(M,P,L,`⊕`,`\\oplus`,!0),j(M,P,L,`⊗`,`\\otimes`,!0),j(M,P,V,`∂`,`\\partial`,!0),j(M,P,L,`⊘`,`\\oslash`,!0),j(M,F,L,`⊚`,`\\circledcirc`,!0),j(M,F,L,`⊡`,`\\boxdot`,!0),j(M,P,L,`△`,`\\bigtriangleup`),j(M,P,L,`▽`,`\\bigtriangledown`),j(M,P,L,`†`,`\\dagger`),j(M,P,L,`⋄`,`\\diamond`),j(M,P,L,`⋆`,`\\star`),j(M,P,L,`◃`,`\\triangleleft`),j(M,P,L,`▹`,`\\triangleright`),j(M,P,Qe,`{`,`\\{`),j(N,P,V,`{`,`\\{`),j(N,P,V,`{`,`\\textbraceleft`),j(M,P,Xe,`}`,`\\}`),j(N,P,V,`}`,`\\}`),j(N,P,V,`}`,`\\textbraceright`),j(M,P,Qe,`{`,`\\lbrace`),j(M,P,Xe,`}`,`\\rbrace`),j(M,P,Qe,`[`,`\\lbrack`,!0),j(N,P,V,`[`,`\\lbrack`,!0),j(M,P,Xe,`]`,`\\rbrack`,!0),j(N,P,V,`]`,`\\rbrack`,!0),j(M,P,Qe,`(`,`\\lparen`,!0),j(M,P,Xe,`)`,`\\rparen`,!0),j(N,P,V,`<`,`\\textless`,!0),j(N,P,V,`>`,`\\textgreater`,!0),j(M,P,Qe,`⌊`,`\\lfloor`,!0),j(M,P,Xe,`⌋`,`\\rfloor`,!0),j(M,P,Qe,`⌈`,`\\lceil`,!0),j(M,P,Xe,`⌉`,`\\rceil`,!0),j(M,P,V,`\\`,`\\backslash`),j(M,P,V,`∣`,`|`),j(M,P,V,`∣`,`\\vert`),j(N,P,V,`|`,`\\textbar`,!0),j(M,P,V,`∥`,`\\|`),j(M,P,V,`∥`,`\\Vert`),j(N,P,V,`∥`,`\\textbardbl`),j(N,P,V,`~`,`\\textasciitilde`),j(N,P,V,`\\`,`\\textbackslash`),j(N,P,V,`^`,`\\textasciicircum`),j(M,P,B,`↑`,`\\uparrow`,!0),j(M,P,B,`⇑`,`\\Uparrow`,!0),j(M,P,B,`↓`,`\\downarrow`,!0),j(M,P,B,`⇓`,`\\Downarrow`,!0),j(M,P,B,`↕`,`\\updownarrow`,!0),j(M,P,B,`⇕`,`\\Updownarrow`,!0),j(M,P,z,`∐`,`\\coprod`),j(M,P,z,`⋁`,`\\bigvee`),j(M,P,z,`⋀`,`\\bigwedge`),j(M,P,z,`⨄`,`\\biguplus`),j(M,P,z,`⋂`,`\\bigcap`),j(M,P,z,`⋃`,`\\bigcup`),j(M,P,z,`∫`,`\\int`),j(M,P,z,`∫`,`\\intop`),j(M,P,z,`∬`,`\\iint`),j(M,P,z,`∭`,`\\iiint`),j(M,P,z,`∏`,`\\prod`),j(M,P,z,`∑`,`\\sum`),j(M,P,z,`⨂`,`\\bigotimes`),j(M,P,z,`⨁`,`\\bigoplus`),j(M,P,z,`⨀`,`\\bigodot`),j(M,P,z,`∮`,`\\oint`),j(M,P,z,`∯`,`\\oiint`),j(M,P,z,`∰`,`\\oiiint`),j(M,P,z,`⨆`,`\\bigsqcup`),j(M,P,z,`∫`,`\\smallint`),j(N,P,Ze,`…`,`\\textellipsis`),j(M,P,Ze,`…`,`\\mathellipsis`),j(N,P,Ze,`…`,`\\ldots`,!0),j(M,P,Ze,`…`,`\\ldots`,!0),j(M,P,Ze,`⋯`,`\\@cdots`,!0),j(M,P,Ze,`⋱`,`\\ddots`,!0),j(M,P,V,`⋮`,`\\varvdots`),j(N,P,V,`⋮`,`\\varvdots`),j(M,P,I,`ˊ`,`\\acute`),j(M,P,I,`ˋ`,`\\grave`),j(M,P,I,`¨`,`\\ddot`),j(M,P,I,`~`,`\\tilde`),j(M,P,I,`ˉ`,`\\bar`),j(M,P,I,`˘`,`\\breve`),j(M,P,I,`ˇ`,`\\check`),j(M,P,I,`^`,`\\hat`),j(M,P,I,`⃗`,`\\vec`),j(M,P,I,`˙`,`\\dot`),j(M,P,I,`˚`,`\\mathring`),j(M,P,R,``,`\\@imath`),j(M,P,R,``,`\\@jmath`),j(M,P,V,`ı`,`ı`),j(M,P,V,`ȷ`,`ȷ`),j(N,P,V,`ı`,`\\i`,!0),j(N,P,V,`ȷ`,`\\j`,!0),j(N,P,V,`ß`,`\\ss`,!0),j(N,P,V,`æ`,`\\ae`,!0),j(N,P,V,`œ`,`\\oe`,!0),j(N,P,V,`ø`,`\\o`,!0),j(N,P,V,`Æ`,`\\AE`,!0),j(N,P,V,`Œ`,`\\OE`,!0),j(N,P,V,`Ø`,`\\O`,!0),j(N,P,I,`ˊ`,`\\'`),j(N,P,I,`ˋ`,"\\`"),j(N,P,I,`ˆ`,`\\^`),j(N,P,I,`˜`,`\\~`),j(N,P,I,`ˉ`,`\\=`),j(N,P,I,`˘`,`\\u`),j(N,P,I,`˙`,`\\.`),j(N,P,I,`¸`,`\\c`),j(N,P,I,`˚`,`\\r`),j(N,P,I,`ˇ`,`\\v`),j(N,P,I,`¨`,`\\"`),j(N,P,I,`˝`,`\\H`),j(N,P,I,`◯`,`\\textcircled`);var tt={"--":!0,"---":!0,"``":!0,"''":!0};j(N,P,V,`–`,`--`,!0),j(N,P,V,`–`,`\\textendash`),j(N,P,V,`—`,`---`,!0),j(N,P,V,`—`,`\\textemdash`),j(N,P,V,`‘`,"`",!0),j(N,P,V,`‘`,`\\textquoteleft`),j(N,P,V,`’`,`'`,!0),j(N,P,V,`’`,`\\textquoteright`),j(N,P,V,`“`,"``",!0),j(N,P,V,`“`,`\\textquotedblleft`),j(N,P,V,`”`,`''`,!0),j(N,P,V,`”`,`\\textquotedblright`),j(M,P,V,`°`,`\\degree`,!0),j(N,P,V,`°`,`\\degree`),j(N,P,V,`°`,`\\textdegree`,!0),j(M,P,V,`£`,`\\pounds`),j(M,P,V,`£`,`\\mathsterling`,!0),j(N,P,V,`£`,`\\pounds`),j(N,P,V,`£`,`\\textsterling`,!0),j(M,F,V,`✠`,`\\maltese`),j(N,F,V,`✠`,`\\maltese`);for(var nt=`0123456789/@."`,rt=0;rt{var n=t.charCodeAt(0),r=t.charCodeAt(1),i=(n-55296)*1024+(r-56320)+65536;if(119808<=i&&i<120484)return kt[Math.floor((i-119808)/26)];if(120782<=i&&i<=120831)return At[Math.floor((i-120782)/10)];if(i===120485||i===120486)return kt[0];if(120486{if(Ee(e.classes)!==Ee(t.classes)||e.skew!==t.skew||e.maxFontSize!==t.maxFontSize||e.italic!==0&&e.hasClass(`mathnormal`))return!1;if(e.classes.length===1){var n=e.classes[0];if(n===`mbin`||n===`mord`)return!1}for(var r of Object.keys(e.style))if(e.style[r]!==t.style[r])return!1;for(var i of Object.keys(t.style))if(e.style[i]!==t.style[i])return!1;return!0},Rt=e=>{for(var t=0;tt&&(t=a.height),a.depth>n&&(n=a.depth),a.maxFontSize>r&&(r=a.maxFontSize)}e.height=t,e.depth=n,e.maxFontSize=r},W=function(e,t,n,r){var i=new Me(e,t,n,r);return zt(i),i},Bt=(e,t,n,r)=>new Me(e,t,n,r),Vt=function(e,t,n){var r=W([e],[],t);return r.height=Math.max(n||t.fontMetrics().defaultRuleThickness,t.minRuleThickness),r.style.borderBottomWidth=k(r.height),r.maxFontSize=1,r},Ht=function(e,t,n,r){var i=new Ne(e,t,n,r);return zt(i),i},Ut=function(e){var t=new Se(e);return zt(t),t},Wt=function(e,t){return e instanceof Se?W([],[e],t):e},Gt=function(e){if(e.positionType===`individualShift`){for(var t=e.children,n=[t[0]],r=-t[0].shift-t[0].elem.depth,i=r,a=1;a{var n=W([`mspace`],[],t),r=O(e,t);return n.style.marginRight=k(r),n},qt=(e,t,n)=>{var r,i;switch(e){case`amsrm`:r=`AMS`;break;case`textrm`:r=`Main`;break;case`textsf`:r=`SansSerif`;break;case`texttt`:r=`Typewriter`;break;default:r=e}return i=t===`textbf`&&n===`textit`?`BoldItalic`:t===`textbf`?`Bold`:n===`textit`?`Italic`:`Regular`,r+`-`+i},Jt={mathbf:{variant:`bold`,fontName:`Main-Bold`},mathrm:{variant:`normal`,fontName:`Main-Regular`},textit:{variant:`italic`,fontName:`Main-Italic`},mathit:{variant:`italic`,fontName:`Main-Italic`},mathnormal:{variant:`italic`,fontName:`Math-Italic`},mathsfit:{variant:`sans-serif-italic`,fontName:`SansSerif-Italic`},mathbb:{variant:`double-struck`,fontName:`AMS-Regular`},mathcal:{variant:`script`,fontName:`Caligraphic-Regular`},mathfrak:{variant:`fraktur`,fontName:`Fraktur-Regular`},mathscr:{variant:`script`,fontName:`Script-Regular`},mathsf:{variant:`sans-serif`,fontName:`SansSerif-Regular`},mathtt:{variant:`monospace`,fontName:`Typewriter-Regular`}},Yt={vec:[`vec`,.471,.714],oiintSize1:[`oiintSize1`,.957,.499],oiintSize2:[`oiintSize2`,1.472,.659],oiiintSize1:[`oiiintSize1`,1.304,.499],oiiintSize2:[`oiiintSize2`,1.98,.659]},Xt=function(e,t){var[n,r,i]=Yt[e],a=Bt([`overlay`],[new Le([new Re(n)],{width:k(r),height:k(i),style:`width:`+k(r),viewBox:`0 0 `+1e3*r+` `+1e3*i,preserveAspectRatio:`xMinYMin`})],t);return a.height=i,a.style.height=k(i),a.style.width=k(r),a},K={number:3,unit:`mu`},Zt={number:4,unit:`mu`},Qt={number:5,unit:`mu`},$t={mord:{mop:K,mbin:Zt,mrel:Qt,minner:K},mop:{mord:K,mop:K,mrel:Qt,minner:K},mbin:{mord:Zt,mop:Zt,mopen:Zt,minner:Zt},mrel:{mord:Qt,mop:Qt,mopen:Qt,minner:Qt},mopen:{},mclose:{mop:K,mbin:Zt,mrel:Qt,minner:K},mpunct:{mord:K,mop:K,mrel:Qt,mopen:K,mclose:K,mpunct:K,minner:K},minner:{mord:K,mop:K,mbin:Zt,mrel:Qt,mopen:K,mpunct:K,minner:K}},en={mord:{mop:K},mop:{mord:K,mop:K},mbin:{},mrel:{},mopen:{},mclose:{mop:K},mpunct:{},minner:{mop:K}},tn={},nn={},rn={};function q(e){for(var{type:t,names:n,props:r,handler:i,htmlBuilder:a,mathmlBuilder:o}=e,s={type:t,numArgs:r.numArgs,argTypes:r.argTypes,allowedInArgument:!!r.allowedInArgument,allowedInText:!!r.allowedInText,allowedInMath:r.allowedInMath===void 0||r.allowedInMath,numOptionalArgs:r.numOptionalArgs||0,infix:!!r.infix,primitive:!!r.primitive,handler:i},c=0;c{var n=t.classes[0],r=e.classes[0];n===`mbin`&&cn.has(r)?t.classes[0]=`mord`:r===`mbin`&&sn.has(n)&&(e.classes[0]=`mord`)},{node:u},d,f),fn(i,(e,t)=>{var n=hn(t),r=hn(e),i=n&&r?e.hasClass(`mtight`)?en[n]?.[r]:$t[n]?.[r]:null;if(i)return Kt(i,c)},{node:u},d,f),i},fn=function(e,t,n,r,i){r&&e.push(r);for(var a=0;an=>{e.splice(t+1,0,n),a++})(a)}r&&e.pop()},pn=function(e){return e instanceof Se||e instanceof Ne||e instanceof Me&&e.hasClass(`enclosing`)?e:null},mn=function(e,t){var n=pn(e);if(n){var r=n.children;if(r.length){if(t===`right`)return mn(r[r.length-1],`right`);if(t===`left`)return mn(r[0],`left`)}}return e},hn=function(e,t){return e?(t&&(e=mn(e,t)),un[e.classes[0]]||null):null},gn=function(e,t){var n=[`nulldelimiter`].concat(e.baseSizingClasses());return W(t.concat(n))},Y=function(t,n,r){if(!t)return W();if(nn[t.type]){var i=nn[t.type](t,n);if(r&&n.size!==r.size){i=W(n.sizingClasses(r),[i],n);var a=n.sizeMultiplier/r.sizeMultiplier;i.height*=a,i.depth*=a}return i}else throw new e(`Got group of unknown type: '`+t.type+`'`)};function _n(e,t){var n=W([`base`],e,t),r=W([`strut`]);return r.style.height=k(n.height+n.depth),n.depth&&(r.style.verticalAlign=k(-n.depth)),n.children.unshift(r),n}function vn(e,t){var n=null;e.length===1&&e[0].type===`tag`&&(n=e[0].tag,e=e[0].body);var r=dn(e,t,`root`),i;r.length===2&&r[1].hasClass(`tag`)&&(i=r.pop());for(var a=[],o=[],s=0;s0&&(a.push(_n(o,t)),o=[]),a.push(r[s]));o.length>0&&a.push(_n(o,t));var l;n?(l=_n(dn(n,t,!0),t),l.classes=[`tag`],a.push(l)):i&&a.push(i);var u=W([`katex-html`],a);if(u.setAttribute(`aria-hidden`,`true`),l){var d=l.children[0];d.style.height=k(u.height+u.depth),u.depth&&(d.style.verticalAlign=k(-u.depth))}return u}function yn(e){return new Se(e)}var X=class{constructor(e,t,n){this.type=void 0,this.attributes=void 0,this.children=void 0,this.classes=void 0,this.type=e,this.attributes={},this.children=t||[],this.classes=n||[]}setAttribute(e,t){this.attributes[e]=t}getAttribute(e){return this.attributes[e]}toNode(){var e=document.createElementNS(`http://www.w3.org/1998/Math/MathML`,this.type);for(var t in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,t)&&e.setAttribute(t,this.attributes[t]);this.classes.length>0&&(e.className=Ee(this.classes));for(var n=0;n0&&(e+=` class ="`+a(Ee(this.classes))+`"`),e+=`>`;for(var n=0;n`,e}toText(){return this.children.map(e=>e.toText()).join(``)}},bn=class{constructor(e){this.text=void 0,this.text=e}toNode(){return document.createTextNode(this.text)}toMarkup(){return a(this.toText())}toText(){return this.text}},xn=class{constructor(e){this.width=void 0,this.character=void 0,this.width=e,e>=.05555&&e<=.05556?this.character=` `:e>=.1666&&e<=.1667?this.character=` `:e>=.2222&&e<=.2223?this.character=` `:e>=.2777&&e<=.2778?this.character=`  `:e>=-.05556&&e<=-.05555?this.character=` ⁣`:e>=-.1667&&e<=-.1666?this.character=` ⁣`:e>=-.2223&&e<=-.2222?this.character=` ⁣`:e>=-.2778&&e<=-.2777?this.character=` ⁣`:this.character=null}toNode(){if(this.character)return document.createTextNode(this.character);var e=document.createElementNS(`http://www.w3.org/1998/Math/MathML`,`mspace`);return e.setAttribute(`width`,k(this.width)),e}toMarkup(){return this.character?``+this.character+``:``}toText(){return this.character?this.character:` `}},Sn=new Set([`\\imath`,`\\jmath`]),Cn=new Set([`mrow`,`mtable`]),wn=function(e,t,n){return A[t][e]&&A[t][e].replace&&e.charCodeAt(0)!==55349&&!(tt.hasOwnProperty(e)&&n&&(n.fontFamily&&n.fontFamily.slice(4,6)===`tt`||n.font&&n.font.slice(4,6)===`tt`))&&(e=A[t][e].replace),new bn(e)},Tn=function(e){return e.length===1?e[0]:new X(`mrow`,e)},En={mathit:`italic`,boldsymbol:e=>e.type===`textord`?`bold`:`bold-italic`,mathbf:`bold`,mathbb:`double-struck`,mathsfit:`sans-serif-italic`,mathfrak:`fraktur`,mathscr:`script`,mathcal:`script`,mathsf:`sans-serif`,mathtt:`monospace`},Dn=(e,t)=>{if(e.mode===`text`){if(t.fontFamily===`texttt`)return`monospace`;if(t.fontFamily===`textsf`)return t.fontShape===`textit`&&t.fontWeight===`textbf`?`sans-serif-bold-italic`:t.fontShape===`textit`?`sans-serif-italic`:t.fontWeight===`textbf`?`bold-sans-serif`:`sans-serif`;if(t.fontShape===`textit`&&t.fontWeight===`textbf`)return`bold-italic`;if(t.fontShape===`textit`)return`italic`;if(t.fontWeight===`textbf`)return`bold`}var n=t.font;if(!n||n===`mathnormal`)return null;var r=e.mode,i=En[n];if(i)return typeof i==`function`?i(e):i;var a=e.text;if(Sn.has(a))return null;if(A[r][a]){var o=A[r][a].replace;o&&(a=o)}var s=Jt[n].fontName;return qe(a,s,r)?Jt[n].variant:null};function On(e){if(!e)return!1;if(e.type===`mi`&&e.children.length===1){var t=e.children[0];return t instanceof bn&&t.text===`.`}else if(e.type===`mo`&&e.children.length===1&&e.getAttribute(`separator`)===`true`&&e.getAttribute(`lspace`)===`0em`&&e.getAttribute(`rspace`)===`0em`){var n=e.children[0];return n instanceof bn&&n.text===`,`}else return!1}var kn=function(e,t,n){if(e.length===1){var r=Z(e[0],t);return n&&r instanceof X&&r.type===`mo`&&(r.setAttribute(`lspace`,`0em`),r.setAttribute(`rspace`,`0em`)),[r]}for(var i=[],a,o=0;o=1&&(a.type===`mn`||On(a))){var c=s.children[0];c instanceof X&&c.type===`mn`&&(c.children=[...a.children,...c.children],i.pop())}else if(a.type===`mi`&&a.children.length===1){var l=a.children[0];if(l instanceof bn&&l.text===`̸`&&(s.type===`mo`||s.type===`mi`||s.type===`mn`)){var u=s.children[0];u instanceof bn&&u.text.length>0&&(u.text=u.text.slice(0,1)+`̸`+u.text.slice(1),i.pop())}}}i.push(s),a=s}return i},An=function(e,t,n){return Tn(kn(e,t,n))},Z=function(t,n){if(!t)return new X(`mrow`);if(rn[t.type])return rn[t.type](t,n);throw new e(`Got group of unknown type: '`+t.type+`'`)};function jn(e,t,n,r,i){var a=kn(e,n),o=a.length===1&&a[0]instanceof X&&Cn.has(a[0].type)?a[0]:new X(`mrow`,a),s=new X(`annotation`,[new bn(t)]);s.setAttribute(`encoding`,`application/x-tex`);var c=new X(`math`,[new X(`semantics`,[o,s])]);return c.setAttribute(`xmlns`,`http://www.w3.org/1998/Math/MathML`),r&&c.setAttribute(`display`,`block`),W([i?`katex`:`katex-mathml`],[c])}var Mn=[[1,1,1],[2,1,1],[3,1,1],[4,2,1],[5,2,1],[6,3,1],[7,4,2],[8,6,3],[9,7,6],[10,8,7],[11,10,9]],Nn=[.5,.6,.7,.8,.9,1,1.2,1.44,1.728,2.074,2.488],Pn=function(e,t){return t.size<2?e:Mn[e-1][t.size-1]},Fn=class e{constructor(t){this.style=void 0,this.color=void 0,this.size=void 0,this.textSize=void 0,this.phantom=void 0,this.font=void 0,this.fontFamily=void 0,this.fontWeight=void 0,this.fontShape=void 0,this.sizeMultiplier=void 0,this.maxSize=void 0,this.minRuleThickness=void 0,this._fontMetrics=void 0,this.style=t.style,this.color=t.color,this.size=t.size||e.BASESIZE,this.textSize=t.textSize||this.size,this.phantom=!!t.phantom,this.font=t.font||``,this.fontFamily=t.fontFamily||``,this.fontWeight=t.fontWeight||``,this.fontShape=t.fontShape||``,this.sizeMultiplier=Nn[this.size-1],this.maxSize=t.maxSize,this.minRuleThickness=t.minRuleThickness,this._fontMetrics=void 0}extend(t){var n={style:this.style,size:this.size,textSize:this.textSize,color:this.color,phantom:this.phantom,font:this.font,fontFamily:this.fontFamily,fontWeight:this.fontWeight,fontShape:this.fontShape,maxSize:this.maxSize,minRuleThickness:this.minRuleThickness};return Object.assign(n,t),new e(n)}havingStyle(e){return this.style===e?this:this.extend({style:e,size:Pn(this.textSize,e)})}havingCrampedStyle(){return this.havingStyle(this.style.cramp())}havingSize(e){return this.size===e&&this.textSize===e?this:this.extend({style:this.style.text(),size:e,textSize:e,sizeMultiplier:Nn[e-1]})}havingBaseStyle(t){t||=this.style.text();var n=Pn(e.BASESIZE,t);return this.size===n&&this.textSize===e.BASESIZE&&this.style===t?this:this.extend({style:t,size:n})}havingBaseSizing(){var e;switch(this.style.id){case 4:case 5:e=3;break;case 6:case 7:e=1;break;default:e=6}return this.extend({style:this.style.text(),size:e})}withColor(e){return this.extend({color:e})}withPhantom(){return this.extend({phantom:!0})}withFont(e){return this.extend({font:e})}withTextFontFamily(e){return this.extend({fontFamily:e,font:``})}withTextFontWeight(e){return this.extend({fontWeight:e,font:``})}withTextFontShape(e){return this.extend({fontShape:e,font:``})}sizingClasses(e){return e.size===this.size?[]:[`sizing`,`reset-size`+e.size,`size`+this.size]}baseSizingClasses(){return this.size===e.BASESIZE?[]:[`sizing`,`reset-size`+this.size,`size`+e.BASESIZE]}fontMetrics(){return this._fontMetrics||=Ye(this.size),this._fontMetrics}getColor(){return this.phantom?`transparent`:this.color}};Fn.BASESIZE=6;var In=function(e){return new Fn({style:e.displayMode?E.DISPLAY:E.TEXT,maxSize:e.maxSize,minRuleThickness:e.minRuleThickness})},Ln=function(e,t){if(t.displayMode){var n=[`katex-display`];t.leqno&&n.push(`leqno`),t.fleqn&&n.push(`fleqn`),e=W(n,[e])}return e},Rn=function(e,t,n){var r=In(n),i;return n.output===`mathml`?jn(e,t,r,n.displayMode,!0):(i=n.output===`html`?W([`katex`],[vn(e,r)]):W([`katex`],[jn(e,t,r,n.displayMode,!1),vn(e,r)]),Ln(i,n))},zn=function(e,t,n){return Ln(W([`katex`],[vn(e,In(n))]),n)},Bn={widehat:`^`,widecheck:`ˇ`,widetilde:`~`,utilde:`~`,overleftarrow:`←`,underleftarrow:`←`,xleftarrow:`←`,overrightarrow:`→`,underrightarrow:`→`,xrightarrow:`→`,underbrace:`⏟`,overbrace:`⏞`,underbracket:`⎵`,overbracket:`⎴`,overgroup:`⏠`,undergroup:`⏡`,overleftrightarrow:`↔`,underleftrightarrow:`↔`,xleftrightarrow:`↔`,Overrightarrow:`⇒`,xRightarrow:`⇒`,overleftharpoon:`↼`,xleftharpoonup:`↼`,overrightharpoon:`⇀`,xrightharpoonup:`⇀`,xLeftarrow:`⇐`,xLeftrightarrow:`⇔`,xhookleftarrow:`↩`,xhookrightarrow:`↪`,xmapsto:`↦`,xrightharpoondown:`⇁`,xleftharpoondown:`↽`,xrightleftharpoons:`⇌`,xleftrightharpoons:`⇋`,xtwoheadleftarrow:`↞`,xtwoheadrightarrow:`↠`,xlongequal:`=`,xtofrom:`⇄`,xrightleftarrows:`⇄`,xrightequilibrium:`⇌`,xleftequilibrium:`⇋`,"\\cdrightarrow":`→`,"\\cdleftarrow":`←`,"\\cdlongequal":`=`},Vn=function(e){var t=new X(`mo`,[new bn(Bn[e.replace(/^\\/,``)])]);return t.setAttribute(`stretchy`,`true`),t},Hn={overrightarrow:[[`rightarrow`],.888,522,`xMaxYMin`],overleftarrow:[[`leftarrow`],.888,522,`xMinYMin`],underrightarrow:[[`rightarrow`],.888,522,`xMaxYMin`],underleftarrow:[[`leftarrow`],.888,522,`xMinYMin`],xrightarrow:[[`rightarrow`],1.469,522,`xMaxYMin`],"\\cdrightarrow":[[`rightarrow`],3,522,`xMaxYMin`],xleftarrow:[[`leftarrow`],1.469,522,`xMinYMin`],"\\cdleftarrow":[[`leftarrow`],3,522,`xMinYMin`],Overrightarrow:[[`doublerightarrow`],.888,560,`xMaxYMin`],xRightarrow:[[`doublerightarrow`],1.526,560,`xMaxYMin`],xLeftarrow:[[`doubleleftarrow`],1.526,560,`xMinYMin`],overleftharpoon:[[`leftharpoon`],.888,522,`xMinYMin`],xleftharpoonup:[[`leftharpoon`],.888,522,`xMinYMin`],xleftharpoondown:[[`leftharpoondown`],.888,522,`xMinYMin`],overrightharpoon:[[`rightharpoon`],.888,522,`xMaxYMin`],xrightharpoonup:[[`rightharpoon`],.888,522,`xMaxYMin`],xrightharpoondown:[[`rightharpoondown`],.888,522,`xMaxYMin`],xlongequal:[[`longequal`],.888,334,`xMinYMin`],"\\cdlongequal":[[`longequal`],3,334,`xMinYMin`],xtwoheadleftarrow:[[`twoheadleftarrow`],.888,334,`xMinYMin`],xtwoheadrightarrow:[[`twoheadrightarrow`],.888,334,`xMaxYMin`],overleftrightarrow:[[`leftarrow`,`rightarrow`],.888,522],overbrace:[[`leftbrace`,`midbrace`,`rightbrace`],1.6,548],underbrace:[[`leftbraceunder`,`midbraceunder`,`rightbraceunder`],1.6,548],underleftrightarrow:[[`leftarrow`,`rightarrow`],.888,522],xleftrightarrow:[[`leftarrow`,`rightarrow`],1.75,522],xLeftrightarrow:[[`doubleleftarrow`,`doublerightarrow`],1.75,560],xrightleftharpoons:[[`leftharpoondownplus`,`rightharpoonplus`],1.75,716],xleftrightharpoons:[[`leftharpoonplus`,`rightharpoondownplus`],1.75,716],xhookleftarrow:[[`leftarrow`,`righthook`],1.08,522],xhookrightarrow:[[`lefthook`,`rightarrow`],1.08,522],overlinesegment:[[`leftlinesegment`,`rightlinesegment`],.888,522],underlinesegment:[[`leftlinesegment`,`rightlinesegment`],.888,522],overbracket:[[`leftbracketover`,`rightbracketover`],1.6,440],underbracket:[[`leftbracketunder`,`rightbracketunder`],1.6,410],overgroup:[[`leftgroup`,`rightgroup`],.888,342],undergroup:[[`leftgroupunder`,`rightgroupunder`],.888,342],xmapsto:[[`leftmapsto`,`rightarrow`],1.5,522],xtofrom:[[`leftToFrom`,`rightToFrom`],1.75,528],xrightleftarrows:[[`baraboveleftarrow`,`rightarrowabovebar`],1.75,901],xrightequilibrium:[[`baraboveshortleftharpoon`,`rightharpoonaboveshortbar`],1.75,716],xleftequilibrium:[[`shortbaraboveleftharpoon`,`shortrightharpoonabovebar`],1.75,716]},Un=new Set([`widehat`,`widecheck`,`widetilde`,`utilde`]),Wn=function(e,t){function n(){var n=4e5,r=e.label.slice(1);if(Un.has(r)&&`base`in e){var i=e.base.type===`ordgroup`?e.base.body.length:1,a,o,s;if(i>5)r===`widehat`||r===`widecheck`?(a=420,n=2364,s=.42,o=r+`4`):(a=312,n=2340,s=.34,o=`tilde4`);else{var c=[1,1,2,2,3,3][i];r===`widehat`||r===`widecheck`?(n=[0,1062,2364,2364,2364][c],a=[0,239,300,360,420][c],s=[0,.24,.3,.3,.36,.42][c],o=r+c):(n=[0,600,1033,2339,2340][c],a=[0,260,286,306,312][c],s=[0,.26,.286,.3,.306,.34][c],o=`tilde`+c)}return{span:Bt([],[new Le([new Re(o)],{width:`100%`,height:k(s),viewBox:`0 0 `+n+` `+a,preserveAspectRatio:`none`})],t),minWidth:0,height:s}}else{var l=[],u=Hn[r];if(!u)throw Error(`No SVG data for "`+r+`".`);var[d,f,p]=u,m=p/1e3,h=d.length,g,_;if(h===1){if(u.length!==4)throw Error(`Expected 4-tuple for single-path SVG data "`+r+`".`);g=[`hide-tail`],_=[u[3]]}else if(h===2)g=[`halfarrow-left`,`halfarrow-right`],_=[`xMinYMin`,`xMaxYMin`];else if(h===3)g=[`brace-left`,`brace-center`,`brace-right`],_=[`xMinYMin`,`xMidYMin`,`xMaxYMin`];else throw Error(`Correct katexImagesData or update code here to support + `+h+` children.`);for(var v=0;v0&&(r.style.minWidth=k(i)),r},Gn=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=W([`stretchy`,t],[],i),t===`fbox`){var s=i.color&&i.getColor();s&&(a.style.borderColor=s)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new ze({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new ze({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=Bt([],[new Le(c,{width:`100%`,height:k(o)})],i)}return a.height=o,a.style.height=k(o),a},Kn={bin:1,close:1,inner:1,open:1,punct:1,rel:1},qn={"accent-token":1,mathord:1,"op-token":1,spacing:1,textord:1};function Jn(e){return e in Kn}function Q(e,t){if(!e||e.type!==t)throw Error(`Expected node of type `+t+`, but got `+(e?`node of type `+e.type:String(e)));return e}function Yn(e){var t=Xn(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function Xn(e){return e&&(e.type===`atom`||qn.hasOwnProperty(e.type))?e:null}var Zn=e=>{if(e instanceof Ie)return e;if(He(e)&&e.children.length===1)return Zn(e.children[0])},Qn=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=Q(e.base,`accent`),n=r.base,e.base=n,i=Ve(Y(e,t)),e.base=r):(r=Q(e,`accent`),n=r.base);var a=Y(n,t.havingCrampedStyle()),o=r.isShifty&&c(n),s=0;o&&(s=Zn(a)?.skew??0);var l=r.label===`\\c`,u=l?a.height+a.depth:Math.min(a.height,t.fontMetrics().xHeight),d;if(r.isStretchy)d=Wn(r,t),d=G({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:d,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+k(2*s)+`)`,marginLeft:k(2*s)}:void 0}]});else{var f,p;r.label===`\\vec`?(f=Xt(`vec`,t),p=Yt.vec[1]):(f=It({type:`textord`,mode:r.mode,text:r.label},t,`textord`),f=Be(f),f.italic=0,p=f.width,l&&(u+=f.depth)),d=W([`accent-body`],[f]);var m=r.label===`\\textcircled`;m&&(d.classes.push(`accent-full`),u=a.height);var h=s;m||(h-=p/2),d.style.left=k(h),r.label===`\\textcircled`&&(d.style.top=`.2em`),d=G({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-u},{type:`elem`,elem:d}]})}var g=W([`mord`,`accent`],[d],t);return i?(i.children[0]=g,i.height=Math.max(g.height,i.height),i.classes[0]=`mord`,i):g},$n=(e,t)=>{var n=e.isStretchy?Vn(e.label):new X(`mo`,[wn(e.label,e.mode)]),r=new X(`mover`,[Z(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},er=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));q({type:`accent`,names:[`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`,`\\widecheck`,`\\widehat`,`\\widetilde`,`\\overrightarrow`,`\\overleftarrow`,`\\Overrightarrow`,`\\overleftrightarrow`,`\\overgroup`,`\\overlinesegment`,`\\overleftharpoon`,`\\overrightharpoon`],props:{numArgs:1},handler:(e,t)=>{var n=on(t[0]),r=!er.test(e.funcName),i=!r||e.funcName===`\\widehat`||e.funcName===`\\widetilde`||e.funcName===`\\widecheck`;return{type:`accent`,mode:e.parser.mode,label:e.funcName,isStretchy:r,isShifty:i,base:n}},htmlBuilder:Qn,mathmlBuilder:$n}),q({type:`accent`,names:[`\\'`,"\\`",`\\^`,`\\~`,`\\=`,`\\u`,`\\.`,`\\"`,`\\c`,`\\r`,`\\H`,`\\v`,`\\textcircled`],props:{numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`primitive`]},handler:(e,t)=>{var n=t[0],r=e.parser.mode;return r===`math`&&(e.parser.settings.reportNonstrict(`mathVsTextAccents`,`LaTeX's accent `+e.funcName+` works only in text mode`),r=`text`),{type:`accent`,mode:r,label:e.funcName,isStretchy:!1,isShifty:!0,base:n}},htmlBuilder:Qn,mathmlBuilder:$n}),q({type:`accentUnder`,names:[`\\underleftarrow`,`\\underrightarrow`,`\\underleftrightarrow`,`\\undergroup`,`\\underlinesegment`,`\\utilde`],props:{numArgs:1},handler:(e,t)=>{var{parser:n,funcName:r}=e,i=t[0];return{type:`accentUnder`,mode:n.mode,label:r,base:i}},htmlBuilder:(e,t)=>{var n=Y(e.base,t),r=Wn(e,t),i=e.label===`\\utilde`?.12:0;return W([`mord`,`accentunder`],[G({positionType:`top`,positionData:n.height,children:[{type:`elem`,elem:r,wrapperClasses:[`svg-align`]},{type:`kern`,size:i},{type:`elem`,elem:n}]})],t)},mathmlBuilder:(e,t)=>{var n=Vn(e.label),r=new X(`munder`,[Z(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var tr=e=>{var t=new X(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};q({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrightarrow`,`\\xLeftrightarrow`,`\\xhookleftarrow`,`\\xhookrightarrow`,`\\xmapsto`,`\\xrightharpoondown`,`\\xrightharpoonup`,`\\xleftharpoondown`,`\\xleftharpoonup`,`\\xrightleftharpoons`,`\\xleftrightharpoons`,`\\xlongequal`,`\\xtwoheadrightarrow`,`\\xtwoheadleftarrow`,`\\xtofrom`,`\\xrightleftarrows`,`\\xrightequilibrium`,`\\xleftequilibrium`,`\\\\cdrightarrow`,`\\\\cdleftarrow`,`\\\\cdlongequal`],props:{numArgs:1,numOptionalArgs:1},handler(e,t,n){var{parser:r,funcName:i}=e;return{type:`xArrow`,mode:r.mode,label:i,body:t[0],below:n[0]}},htmlBuilder(e,t){var n=t.style,r=t.havingStyle(n.sup()),i=Wt(Y(e.body,r,t),t),a=e.label.slice(0,2)===`\\x`?`x`:`cd`;i.classes.push(a+`-arrow-pad`);var o;e.below&&(r=t.havingStyle(n.sub()),o=Wt(Y(e.below,r,t),t),o.classes.push(a+`-arrow-pad`));var s=Wn(e,t),c=-t.fontMetrics().axisHeight+.5*s.height,l=-t.fontMetrics().axisHeight-.5*s.height-.111;(i.depth>.25||e.label===`\\xleftequilibrium`)&&(l-=i.depth);var u;if(o){var d=-t.fontMetrics().axisHeight+o.height+.5*s.height+.111;u=G({positionType:`individualShift`,children:[{type:`elem`,elem:i,shift:l},{type:`elem`,elem:s,shift:c,wrapperClasses:[`svg-align`]},{type:`elem`,elem:o,shift:d}]})}else u=G({positionType:`individualShift`,children:[{type:`elem`,elem:i,shift:l},{type:`elem`,elem:s,shift:c,wrapperClasses:[`svg-align`]}]});return W([`mrel`,`x-arrow`],[u],t)},mathmlBuilder(e,t){var n=Vn(e.label);n.setAttribute(`minsize`,e.label.charAt(0)===`x`?`1.75em`:`3.0em`);var r;if(e.body){var i=tr(Z(e.body,t));r=e.below?new X(`munderover`,[n,tr(Z(e.below,t)),i]):new X(`mover`,[n,i])}else e.below?r=new X(`munder`,[n,tr(Z(e.below,t))]):(r=tr(),r=new X(`mover`,[n,r]));return r}});function nr(e,t){var n=dn(e.body,t,!0);return W([e.mclass],n,t)}function rr(e,t){var n,r=kn(e.body,t);return e.mclass===`minner`?n=new X(`mpadded`,r):e.mclass===`mord`?e.isCharacterBox?(n=r[0],n.type=`mi`):n=new X(`mi`,r):(e.isCharacterBox?(n=r[0],n.type=`mo`):n=new X(`mo`,r),e.mclass===`mbin`?(n.attributes.lspace=`0.22em`,n.attributes.rspace=`0.22em`):e.mclass===`mpunct`?(n.attributes.lspace=`0em`,n.attributes.rspace=`0.17em`):e.mclass===`mopen`||e.mclass===`mclose`?(n.attributes.lspace=`0em`,n.attributes.rspace=`0em`):e.mclass===`minner`&&(n.attributes.lspace=`0.0556em`,n.attributes.width=`+0.1111em`)),n}q({type:`mclass`,names:[`\\mathord`,`\\mathbin`,`\\mathrel`,`\\mathopen`,`\\mathclose`,`\\mathpunct`,`\\mathinner`],props:{numArgs:1,primitive:!0},handler(e,t){var{parser:n,funcName:r}=e,i=t[0];return{type:`mclass`,mode:n.mode,mclass:`m`+r.slice(5),body:J(i),isCharacterBox:c(i)}},htmlBuilder:nr,mathmlBuilder:rr});var ir=e=>{var t=e.type===`ordgroup`&&e.body.length?e.body[0]:e;return t.type===`atom`&&(t.family===`bin`||t.family===`rel`)?`m`+t.family:`mord`};q({type:`mclass`,names:[`\\@binrel`],props:{numArgs:2},handler(e,t){var{parser:n}=e;return{type:`mclass`,mode:n.mode,mclass:ir(t[0]),body:J(t[1]),isCharacterBox:c(t[1])}}}),q({type:`mclass`,names:[`\\stackrel`,`\\overset`,`\\underset`],props:{numArgs:2},handler(e,t){var{parser:n,funcName:r}=e,i=t[1],a=t[0],o=r===`\\stackrel`?`mrel`:ir(i),s={type:`op`,mode:i.mode,limits:!0,alwaysHandleSupSub:!0,parentIsSupSub:!1,symbol:!1,suppressBaseShift:r!==`\\stackrel`,body:J(i)},l={type:`supsub`,mode:a.mode,base:s,sup:r===`\\underset`?null:a,sub:r===`\\underset`?a:null};return{type:`mclass`,mode:n.mode,mclass:o,body:[l],isCharacterBox:c(l)}},htmlBuilder:nr,mathmlBuilder:rr}),q({type:`pmb`,names:[`\\pmb`],props:{numArgs:1,allowedInText:!0},handler(e,t){var{parser:n}=e;return{type:`pmb`,mode:n.mode,mclass:ir(t[0]),body:J(t[0])}},htmlBuilder(e,t){var n=dn(e.body,t,!0),r=W([e.mclass],n,t);return r.style.textShadow=`0.02em 0.01em 0.04px`,r},mathmlBuilder(e,t){var n=new X(`mstyle`,kn(e.body,t));return n.setAttribute(`style`,`text-shadow: 0.02em 0.01em 0.04px`),n}});var ar={">":`\\\\cdrightarrow`,"<":`\\\\cdleftarrow`,"=":`\\\\cdlongequal`,A:`\\uparrow`,V:`\\downarrow`,"|":`\\Vert`,".":`no arrow`},or=()=>({type:`styling`,body:[],mode:`math`,style:`display`,resetFont:!0}),sr=e=>e.type===`textord`&&e.text===`@`,cr=(e,t)=>(e.type===`mathord`||e.type===`atom`)&&e.text===t;function lr(e,t,n){var r=ar[e];switch(r){case`\\\\cdrightarrow`:case`\\\\cdleftarrow`:return n.callFunction(r,[t[0]],[t[1]]);case`\\uparrow`:case`\\downarrow`:var i=n.callFunction(`\\\\cdleft`,[t[0]],[]),a={type:`atom`,text:r,mode:`math`,family:`rel`},o={type:`ordgroup`,mode:`math`,body:[i,n.callFunction(`\\Big`,[a],[]),n.callFunction(`\\\\cdright`,[t[1]],[])]};return n.callFunction(`\\\\cdparent`,[o],[]);case`\\\\cdlongequal`:return n.callFunction(`\\\\cdlongequal`,[],[]);case`\\Vert`:return n.callFunction(`\\Big`,[{type:`textord`,text:`\\Vert`,mode:`math`}],[]);default:return{type:`textord`,text:` `,mode:`math`}}}function ur(t){var n=[];for(t.gullet.beginGroup(),t.gullet.macros.set(`\\cr`,`\\\\\\relax`),t.gullet.beginGroup();;){n.push(t.parseExpression(!1,`\\\\`)),t.gullet.endGroup(),t.gullet.beginGroup();var r=t.fetch().text;if(r===`&`||r===`\\\\`)t.consume();else if(r===`\\end`){n[n.length-1].length===0&&n.pop();break}else throw new e(`Expected \\\\ or \\cr or \\end`,t.nextToken)}for(var i=[],a=[i],o=0;oAV`.includes(u))for(var f=0;f<2;f++){for(var p=!0,m=l+1;mAV=|." after @`,s[l]);var h={type:`styling`,body:[lr(u,d,t)],mode:`math`,style:`display`,resetFont:!0};i.push(h),c=or()}o%2==0?i.push(c):i.shift(),i=[],a.push(i)}return t.gullet.endGroup(),t.gullet.endGroup(),{type:`array`,mode:`math`,body:a,arraystretch:1,addJot:!0,rowGaps:[null],cols:Array(a[0].length).fill({type:`align`,align:`c`,pregap:.25,postgap:.25}),colSeparationType:`CD`,hLinesBeforeRow:Array(a.length+1).fill([])}}q({type:`cdlabel`,names:[`\\\\cdleft`,`\\\\cdright`],props:{numArgs:1},handler(e,t){var{parser:n,funcName:r}=e;return{type:`cdlabel`,mode:n.mode,side:r.slice(4),label:t[0]}},htmlBuilder(e,t){var n=t.havingStyle(t.style.sup()),r=Wt(Y(e.label,n,t),t);return r.classes.push(`cd-label-`+e.side),r.style.bottom=k(.8-r.depth),r.height=0,r.depth=0,r},mathmlBuilder(e,t){var n=new X(`mrow`,[Z(e.label,t)]);return n=new X(`mpadded`,[n]),n.setAttribute(`width`,`0`),e.side===`left`&&n.setAttribute(`lspace`,`-1width`),n.setAttribute(`voffset`,`0.7em`),n=new X(`mstyle`,[n]),n.setAttribute(`displaystyle`,`false`),n.setAttribute(`scriptlevel`,`1`),n}}),q({type:`cdlabelparent`,names:[`\\\\cdparent`],props:{numArgs:1},handler(e,t){var{parser:n}=e;return{type:`cdlabelparent`,mode:n.mode,fragment:t[0]}},htmlBuilder(e,t){var n=Wt(Y(e.fragment,t),t);return n.classes.push(`cd-vert-arrow`),n},mathmlBuilder(e,t){return new X(`mrow`,[Z(e.fragment,t)])}}),q({type:`textord`,names:[`\\@char`],props:{numArgs:1,allowedInText:!0},handler(t,n){for(var{parser:r}=t,i=Q(n[0],`ordgroup`).body,a=``,o=0;o=1114111)throw new e(`\\@char with invalid code point `+a);return c<=65535?l=String.fromCharCode(c):(c-=65536,l=String.fromCharCode((c>>10)+55296,(c&1023)+56320)),{type:`textord`,mode:r.mode,text:l}}});var dr=(e,t)=>Ut(dn(e.body,t.withColor(e.color),!1)),fr=(e,t)=>{var n=new X(`mstyle`,kn(e.body,t.withColor(e.color)));return n.setAttribute(`mathcolor`,e.color),n};q({type:`color`,names:[`\\textcolor`],props:{numArgs:2,allowedInText:!0,argTypes:[`color`,`original`]},handler(e,t){var{parser:n}=e,r=Q(t[0],`color-token`).color,i=t[1];return{type:`color`,mode:n.mode,color:r,body:J(i)}},htmlBuilder:dr,mathmlBuilder:fr}),q({type:`color`,names:[`\\color`],props:{numArgs:1,allowedInText:!0,argTypes:[`color`]},handler(e,t){var{parser:n,breakOnTokenText:r}=e,i=Q(t[0],`color-token`).color;n.gullet.macros.set(`\\current@color`,i);var a=n.parseExpression(!0,r);return{type:`color`,mode:n.mode,color:i,body:a}},htmlBuilder:dr,mathmlBuilder:fr}),q({type:`cr`,names:[`\\\\`],props:{numArgs:0,numOptionalArgs:0,allowedInText:!0},handler(e,t,n){var{parser:r}=e,i=r.gullet.future().text===`[`?r.parseSizeGroup(!0):null,a=!r.settings.displayMode||!r.settings.useStrictBehavior(`newLineInDisplayMode`,`In LaTeX, \\\\ or \\newline does nothing in display mode`);return{type:`cr`,mode:r.mode,newLine:a,size:i&&Q(i,`size`).value}},htmlBuilder(e,t){var n=W([`mspace`],[],t);return e.newLine&&(n.classes.push(`newline`),e.size&&(n.style.marginTop=k(O(e.size,t)))),n},mathmlBuilder(e,t){var n=new X(`mspace`);return e.newLine&&(n.setAttribute(`linebreak`,`newline`),e.size&&n.setAttribute(`height`,k(O(e.size,t)))),n}});var pr={"\\global":`\\global`,"\\long":`\\\\globallong`,"\\\\globallong":`\\\\globallong`,"\\def":`\\gdef`,"\\gdef":`\\gdef`,"\\edef":`\\xdef`,"\\xdef":`\\xdef`,"\\let":`\\\\globallet`,"\\futurelet":`\\\\globalfuture`},mr=t=>{var n=t.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(n))throw new e(`Expected a control sequence`,t);return n},hr=e=>{var t=e.gullet.popToken();return t.text===`=`&&(t=e.gullet.popToken(),t.text===` `&&(t=e.gullet.popToken())),t},gr=(e,t,n,r)=>{var i=e.gullet.macros.get(n.text);i??=(n.noexpand=!0,{tokens:[n],numArgs:0,unexpandable:!e.gullet.isExpandable(n.text)}),e.gullet.macros.set(t,i,r)};q({type:`internal`,names:[`\\global`,`\\long`,`\\\\globallong`],props:{numArgs:0,allowedInText:!0},handler(t){var{parser:n,funcName:r}=t;n.consumeSpaces();var i=n.fetch();if(pr[i.text])return(r===`\\global`||r===`\\\\globallong`)&&(i.text=pr[i.text]),Q(n.parseFunction(),`internal`);throw new e(`Invalid token after macro prefix`,i)}}),q({type:`internal`,names:[`\\def`,`\\gdef`,`\\edef`,`\\xdef`],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(t){var{parser:n,funcName:r}=t,i=n.gullet.popToken(),a=i.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(a))throw new e(`Expected a control sequence`,i);for(var o=0,s,c=[[]];n.gullet.future().text!==`{`;)if(i=n.gullet.popToken(),i.text===`#`){if(n.gullet.future().text===`{`){s=n.gullet.future(),c[o].push(`{`);break}if(i=n.gullet.popToken(),!/^[1-9]$/.test(i.text))throw new e(`Invalid argument number "`+i.text+`"`);if(parseInt(i.text)!==o+1)throw new e(`Argument number "`+i.text+`" out of order`);o++,c.push([])}else if(i.text===`EOF`)throw new e(`Expected a macro definition`);else c[o].push(i.text);var{tokens:l}=n.gullet.consumeArg();return s&&l.unshift(s),(r===`\\edef`||r===`\\xdef`)&&(l=n.gullet.expandTokens(l),l.reverse()),n.gullet.macros.set(a,{tokens:l,numArgs:o,delimiters:c},r===pr[r]),{type:`internal`,mode:n.mode}}}),q({type:`internal`,names:[`\\let`,`\\\\globallet`],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e){var{parser:t,funcName:n}=e,r=mr(t.gullet.popToken());return t.gullet.consumeSpaces(),gr(t,r,hr(t),n===`\\\\globallet`),{type:`internal`,mode:t.mode}}}),q({type:`internal`,names:[`\\futurelet`,`\\\\globalfuture`],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e){var{parser:t,funcName:n}=e,r=mr(t.gullet.popToken()),i=t.gullet.popToken(),a=t.gullet.popToken();return gr(t,r,a,n===`\\\\globalfuture`),t.gullet.pushToken(a),t.gullet.pushToken(i),{type:`internal`,mode:t.mode}}});var _r=function(e,t,n){var r=qe(A.math[e]&&A.math[e].replace||e,t,n);if(!r)throw Error(`Unsupported symbol `+e+` and font size `+t+`.`);return r},vr=function(e,t,n,r){var i=n.havingBaseStyle(t),a=W(r.concat(i.sizingClasses(n)),[e],n),o=i.sizeMultiplier/n.sizeMultiplier;return a.height*=o,a.depth*=o,a.maxFontSize=i.sizeMultiplier,a},yr=function(e,t,n){var r=t.havingBaseStyle(n),i=(1-t.sizeMultiplier/r.sizeMultiplier)*t.fontMetrics().axisHeight;e.classes.push(`delimcenter`),e.style.top=k(i),e.height-=i,e.depth+=i},br=function(e,t,n,r,i,a){var o=vr(Nt(e,`Main-Regular`,i,r),t,r,a);return n&&yr(o,r,t),o},xr=function(e,t,n,r){return Nt(e,`Size`+t+`-Regular`,n,r)},Sr=function(e,t,n,r,i,a){var o=xr(e,t,i,r),s=vr(W([`delimsizing`,`size`+t],[o],r),E.TEXT,r,a);return n&&yr(s,r,E.TEXT),s},Cr=function(e,t,n){return{type:`elem`,elem:W([`delimsizinginner`,t===`Size1-Regular`?`delim-size1`:`delim-size4`],[W([],[Nt(e,t,n)])])}},wr=function(e,t,n){var r=Ue[`Size4-Regular`][e.charCodeAt(0)]?Ue[`Size4-Regular`][e.charCodeAt(0)][4]:Ue[`Size1-Regular`][e.charCodeAt(0)][4],i=Bt([],[new Le([new Re(`inner`,ve(e,Math.round(1e3*t)))],{width:k(r),height:k(t),style:`width:`+k(r),viewBox:`0 0 `+1e3*r+` `+Math.round(1e3*t),preserveAspectRatio:`xMinYMin`})],n);return i.height=t,i.style.height=k(t),i.style.width=k(r),{type:`elem`,elem:i}},Tr=.008,Er={type:`kern`,size:-1*Tr},Dr=new Set([`|`,`\\lvert`,`\\rvert`,`\\vert`]),Or=new Set([`\\|`,`\\lVert`,`\\rVert`,`\\Vert`]),kr=function(e,t,n,r,i,a){var o,s,c,l,u=``,d=0;o=c=l=e,s=null;var f=`Size1-Regular`;e===`\\uparrow`?c=l=`⏐`:e===`\\Uparrow`?c=l=`‖`:e===`\\downarrow`?o=c=`⏐`:e===`\\Downarrow`?o=c=`‖`:e===`\\updownarrow`?(o=`\\uparrow`,c=`⏐`,l=`\\downarrow`):e===`\\Updownarrow`?(o=`\\Uparrow`,c=`‖`,l=`\\Downarrow`):Dr.has(e)?(c=`∣`,u=`vert`,d=333):Or.has(e)?(c=`∥`,u=`doublevert`,d=556):e===`[`||e===`\\lbrack`?(o=`⎡`,c=`⎢`,l=`⎣`,f=`Size4-Regular`,u=`lbrack`,d=667):e===`]`||e===`\\rbrack`?(o=`⎤`,c=`⎥`,l=`⎦`,f=`Size4-Regular`,u=`rbrack`,d=667):e===`\\lfloor`||e===`⌊`?(c=o=`⎢`,l=`⎣`,f=`Size4-Regular`,u=`lfloor`,d=667):e===`\\lceil`||e===`⌈`?(o=`⎡`,c=l=`⎢`,f=`Size4-Regular`,u=`lceil`,d=667):e===`\\rfloor`||e===`⌋`?(c=o=`⎥`,l=`⎦`,f=`Size4-Regular`,u=`rfloor`,d=667):e===`\\rceil`||e===`⌉`?(o=`⎤`,c=l=`⎥`,f=`Size4-Regular`,u=`rceil`,d=667):e===`(`||e===`\\lparen`?(o=`⎛`,c=`⎜`,l=`⎝`,f=`Size4-Regular`,u=`lparen`,d=875):e===`)`||e===`\\rparen`?(o=`⎞`,c=`⎟`,l=`⎠`,f=`Size4-Regular`,u=`rparen`,d=875):e===`\\{`||e===`\\lbrace`?(o=`⎧`,s=`⎨`,l=`⎩`,c=`⎪`,f=`Size4-Regular`):e===`\\}`||e===`\\rbrace`?(o=`⎫`,s=`⎬`,l=`⎭`,c=`⎪`,f=`Size4-Regular`):e===`\\lgroup`||e===`⟮`?(o=`⎧`,l=`⎩`,c=`⎪`,f=`Size4-Regular`):e===`\\rgroup`||e===`⟯`?(o=`⎫`,l=`⎭`,c=`⎪`,f=`Size4-Regular`):e===`\\lmoustache`||e===`⎰`?(o=`⎧`,l=`⎭`,c=`⎪`,f=`Size4-Regular`):(e===`\\rmoustache`||e===`⎱`)&&(o=`⎫`,l=`⎩`,c=`⎪`,f=`Size4-Regular`);var p=_r(o,f,i),m=p.height+p.depth,h=_r(c,f,i),g=h.height+h.depth,_=_r(l,f,i),v=_.height+_.depth,y=0,b=1;if(s!==null){var x=_r(s,f,i);y=x.height+x.depth,b=2}var S=m+v+y,C=S+Math.max(0,Math.ceil((t-S)/(b*g)))*b*g,w=r.fontMetrics().axisHeight;n&&(w*=r.sizeMultiplier);var ee=C/2-w,T=[];if(u.length>0){var te=C-m-v,ne=Math.round(C*1e3),re=be(u,Math.round(te*1e3)),ie=new Re(u,re),ae=k(d/1e3),oe=k(ne/1e3),se=Bt([],[new Le([ie],{width:ae,height:oe,viewBox:`0 0 `+d+` `+ne})],r);se.height=ne/1e3,se.style.width=ae,se.style.height=oe,T.push({type:`elem`,elem:se})}else{if(T.push(Cr(l,f,i)),T.push(Er),s===null){var ce=C-m-v+2*Tr;T.push(wr(c,ce,r))}else{var D=(C-m-v-y)/2+2*Tr;T.push(wr(c,D,r)),T.push(Er),T.push(Cr(s,f,i)),T.push(Er),T.push(wr(c,D,r))}T.push(Er),T.push(Cr(o,f,i))}var le=r.havingBaseStyle(E.TEXT);return vr(W([`delimsizing`,`mult`],[G({positionType:`bottom`,positionData:ee,children:T})],le),E.TEXT,r,a)},Ar=80,jr=.08,Mr=function(e,t,n,r,i){return Bt([`hide-tail`],[new Le([new Re(e,_e(e,r,n))],{width:`400em`,height:k(t),viewBox:`0 0 400000 `+n,preserveAspectRatio:`xMinYMin slice`})],i)},Nr=function(e,t){var n=t.havingBaseSizing(),r=Ur(`\\surd`,e*n.sizeMultiplier,Vr,n),i=n.sizeMultiplier,a=Math.max(0,t.minRuleThickness-t.fontMetrics().sqrtRuleThickness),o,s,c,l,u;return r.type===`small`?(l=1e3+1e3*a+Ar,e<1?i=1:e<1.4&&(i=.7),s=(1+a+jr)/i,c=(1+a)/i,o=Mr(`sqrtMain`,s,l,a,t),o.style.minWidth=`0.853em`,u=.833/i):r.type===`large`?(l=(1e3+Ar)*Lr[r.size],c=(Lr[r.size]+a)/i,s=(Lr[r.size]+a+jr)/i,o=Mr(`sqrtSize`+r.size,s,l,a,t),o.style.minWidth=`1.02em`,u=1/i):(s=e+a+jr,c=e+a,l=Math.floor(1e3*e+a)+Ar,o=Mr(`sqrtTall`,s,l,a,t),o.style.minWidth=`0.742em`,u=1.056),o.height=c,o.style.height=k(s),{span:o,advanceWidth:u,ruleWidth:(t.fontMetrics().sqrtRuleThickness+a)*i}},Pr=new Set([`(`,`\\lparen`,`)`,`\\rparen`,`[`,`\\lbrack`,`]`,`\\rbrack`,`\\{`,`\\lbrace`,`\\}`,`\\rbrace`,`\\lfloor`,`\\rfloor`,`⌊`,`⌋`,`\\lceil`,`\\rceil`,`⌈`,`⌉`,`\\surd`]),Fr=new Set([`\\uparrow`,`\\downarrow`,`\\updownarrow`,`\\Uparrow`,`\\Downarrow`,`\\Updownarrow`,`|`,`\\|`,`\\vert`,`\\Vert`,`\\lvert`,`\\rvert`,`\\lVert`,`\\rVert`,`\\lgroup`,`\\rgroup`,`⟮`,`⟯`,`\\lmoustache`,`\\rmoustache`,`⎰`,`⎱`]),Ir=new Set([`<`,`>`,`\\langle`,`\\rangle`,`/`,`\\backslash`,`\\lt`,`\\gt`]),Lr=[0,1.2,1.8,2.4,3],Rr=function(t,n,r,i,a){if(t===`<`||t===`\\lt`||t===`⟨`?t=`\\langle`:(t===`>`||t===`\\gt`||t===`⟩`)&&(t=`\\rangle`),Pr.has(t)||Ir.has(t))return Sr(t,n,!1,r,i,a);if(Fr.has(t))return kr(t,Lr[n],!1,r,i,a);throw new e(`Illegal delimiter: '`+t+`'`)},zr=[{type:`small`,style:E.SCRIPTSCRIPT},{type:`small`,style:E.SCRIPT},{type:`small`,style:E.TEXT},{type:`large`,size:1},{type:`large`,size:2},{type:`large`,size:3},{type:`large`,size:4}],Br=[{type:`small`,style:E.SCRIPTSCRIPT},{type:`small`,style:E.SCRIPT},{type:`small`,style:E.TEXT},{type:`stack`}],Vr=[{type:`small`,style:E.SCRIPTSCRIPT},{type:`small`,style:E.SCRIPT},{type:`small`,style:E.TEXT},{type:`large`,size:1},{type:`large`,size:2},{type:`large`,size:3},{type:`large`,size:4},{type:`stack`}],Hr=function(e){if(e.type===`small`)return`Main-Regular`;if(e.type===`large`)return`Size`+e.size+`-Regular`;if(e.type===`stack`)return`Size4-Regular`;var t=e.type;throw Error(`Add support for delim type '`+t+`' here.`)},Ur=function(e,t,n,r){for(var i=Math.min(2,3-r.style.size);it)return a}return n[n.length-1]},Wr=function(e,t,n,r,i,a){e===`<`||e===`\\lt`||e===`⟨`?e=`\\langle`:(e===`>`||e===`\\gt`||e===`⟩`)&&(e=`\\rangle`);var o=Ir.has(e)?zr:Pr.has(e)?Vr:Br,s=Ur(e,t,o,r);return s.type===`small`?br(e,s.style,n,r,i,a):s.type===`large`?Sr(e,s.size,n,r,i,a):kr(e,t,n,r,i,a)},Gr=function(e,t,n,r,i,a){var o=r.fontMetrics().axisHeight*r.sizeMultiplier,s=901,c=5/r.fontMetrics().ptPerEm,l=Math.max(t-o,n+o);return Wr(e,Math.max(l/500*s,2*l-c),!0,r,i,a)},Kr={"\\bigl":{mclass:`mopen`,size:1},"\\Bigl":{mclass:`mopen`,size:2},"\\biggl":{mclass:`mopen`,size:3},"\\Biggl":{mclass:`mopen`,size:4},"\\bigr":{mclass:`mclose`,size:1},"\\Bigr":{mclass:`mclose`,size:2},"\\biggr":{mclass:`mclose`,size:3},"\\Biggr":{mclass:`mclose`,size:4},"\\bigm":{mclass:`mrel`,size:1},"\\Bigm":{mclass:`mrel`,size:2},"\\biggm":{mclass:`mrel`,size:3},"\\Biggm":{mclass:`mrel`,size:4},"\\big":{mclass:`mord`,size:1},"\\Big":{mclass:`mord`,size:2},"\\bigg":{mclass:`mord`,size:3},"\\Bigg":{mclass:`mord`,size:4}},qr=new Set(`(,\\lparen,),\\rparen,[,\\lbrack,],\\rbrack,\\{,\\lbrace,\\},\\rbrace,\\lfloor,\\rfloor,⌊,⌋,\\lceil,\\rceil,⌈,⌉,<,>,\\langle,⟨,\\rangle,⟩,\\lt,\\gt,\\lvert,\\rvert,\\lVert,\\rVert,\\lgroup,\\rgroup,⟮,⟯,\\lmoustache,\\rmoustache,⎰,⎱,/,\\backslash,|,\\vert,\\|,\\Vert,\\uparrow,\\Uparrow,\\downarrow,\\Downarrow,\\updownarrow,\\Updownarrow,.`.split(`,`));function Jr(e){return`isMiddle`in e}function Yr(t,n){var r=Xn(t);if(r&&qr.has(r.text))return r;throw r?new e(`Invalid delimiter '`+r.text+`' after '`+n.funcName+`'`,t):new e(`Invalid delimiter type '`+t.type+`'`,t)}q({type:`delimsizing`,names:[`\\bigl`,`\\Bigl`,`\\biggl`,`\\Biggl`,`\\bigr`,`\\Bigr`,`\\biggr`,`\\Biggr`,`\\bigm`,`\\Bigm`,`\\biggm`,`\\Biggm`,`\\big`,`\\Big`,`\\bigg`,`\\Bigg`],props:{numArgs:1,argTypes:[`primitive`]},handler:(e,t)=>{var n=Yr(t[0],e);return{type:`delimsizing`,mode:e.parser.mode,size:Kr[e.funcName].size,mclass:Kr[e.funcName].mclass,delim:n.text}},htmlBuilder:(e,t)=>e.delim===`.`?W([e.mclass]):Rr(e.delim,e.size,t,e.mode,[e.mclass]),mathmlBuilder:e=>{var t=[];e.delim!==`.`&&t.push(wn(e.delim,e.mode));var n=new X(`mo`,t);e.mclass===`mopen`||e.mclass===`mclose`?n.setAttribute(`fence`,`true`):n.setAttribute(`fence`,`false`),n.setAttribute(`stretchy`,`true`);var r=k(Lr[e.size]);return n.setAttribute(`minsize`,r),n.setAttribute(`maxsize`,r),n}});function Xr(e){if(!e.body)throw Error(`Bug: The leftright ParseNode wasn't fully parsed.`)}q({type:`leftright-right`,names:[`\\right`],props:{numArgs:1,primitive:!0},handler:(t,n)=>{var r=t.parser.gullet.macros.get(`\\current@color`);if(r&&typeof r!=`string`)throw new e(`\\current@color set to non-string in \\right`);return{type:`leftright-right`,mode:t.parser.mode,delim:Yr(n[0],t).text,color:r}}}),q({type:`leftright`,names:[`\\left`],props:{numArgs:1,primitive:!0},handler:(e,t)=>{var n=Yr(t[0],e),r=e.parser;++r.leftrightDepth;var i=r.parseExpression(!1);--r.leftrightDepth,r.expect(`\\right`,!1);var a=Q(r.parseFunction(),`leftright-right`);return{type:`leftright`,mode:r.mode,body:i,left:n.text,right:a.delim,rightColor:a.color}},htmlBuilder:(e,t)=>{Xr(e);for(var n=dn(e.body,t,!0,[`mopen`,`mclose`]),r=0,i=0,a=!1,o=0;o{Xr(e);var n=kn(e.body,t);if(e.left!==`.`){var r=new X(`mo`,[wn(e.left,e.mode)]);r.setAttribute(`fence`,`true`),n.unshift(r)}if(e.right!==`.`){var i=new X(`mo`,[wn(e.right,e.mode)]);i.setAttribute(`fence`,`true`),e.rightColor&&i.setAttribute(`mathcolor`,e.rightColor),n.push(i)}return Tn(n)}}),q({type:`middle`,names:[`\\middle`],props:{numArgs:1,primitive:!0},handler:(t,n)=>{var r=Yr(n[0],t);if(!t.parser.leftrightDepth)throw new e(`\\middle without preceding \\left`,r);return{type:`middle`,mode:t.parser.mode,delim:r.text}},htmlBuilder:(e,t)=>{var n;return e.delim===`.`?n=gn(t,[]):(n=Rr(e.delim,1,t,e.mode,[]),n.isMiddle={delim:e.delim,options:t}),n},mathmlBuilder:(e,t)=>{var n=new X(`mo`,[e.delim===`\\vert`||e.delim===`|`?wn(`|`,`text`):wn(e.delim,e.mode)]);return n.setAttribute(`fence`,`true`),n.setAttribute(`lspace`,`0.05em`),n.setAttribute(`rspace`,`0.05em`),n}});var Zr=(e,t)=>{var n=Wt(Y(e.body,t),t),r=e.label.slice(1),i=t.sizeMultiplier,a,o,s=c(e.body);if(r===`sout`)a=W([`stretchy`,`sout`]),a.height=t.fontMetrics().defaultRuleThickness/i,o=-.5*t.fontMetrics().xHeight;else if(r===`phase`){var l=O({number:.6,unit:`pt`},t),u=O({number:.35,unit:`ex`},t),d=t.havingBaseSizing();i/=d.sizeMultiplier;var f=n.height+n.depth+l+u;n.style.paddingLeft=k(f/2+l);var p=Math.floor(1e3*f*i);a=Bt([`hide-tail`],[new Le([new Re(`phase`,he(p))],{width:`400em`,height:k(p/1e3),viewBox:`0 0 400000 `+p,preserveAspectRatio:`xMinYMin slice`})],t),a.style.height=k(f),o=n.depth+l+u}else{/cancel/.test(r)?s||n.classes.push(`cancel-pad`):r===`angl`?n.classes.push(`anglpad`):n.classes.push(`boxpad`);var m,h,g=0;/box/.test(r)?(g=Math.max(t.fontMetrics().fboxrule,t.minRuleThickness),m=t.fontMetrics().fboxsep+(r===`colorbox`?0:g),h=m):r===`angl`?(g=Math.max(t.fontMetrics().defaultRuleThickness,t.minRuleThickness),m=4*g,h=Math.max(0,.25-n.depth)):(m=s?.2:0,h=m),a=Gn(n,r,m,h,t),/fbox|boxed|fcolorbox/.test(r)?(a.style.borderStyle=`solid`,a.style.borderWidth=k(g)):r===`angl`&&g!==.049&&(a.style.borderTopWidth=k(g),a.style.borderRightWidth=k(g)),o=n.depth+h,e.backgroundColor&&(a.style.backgroundColor=e.backgroundColor,e.borderColor&&(a.style.borderColor=e.borderColor))}var _;if(e.backgroundColor)_=G({positionType:`individualShift`,children:[{type:`elem`,elem:a,shift:o},{type:`elem`,elem:n,shift:0}]});else{var v=/cancel|phase/.test(r)?[`svg-align`]:[];_=G({positionType:`individualShift`,children:[{type:`elem`,elem:n,shift:0},{type:`elem`,elem:a,shift:o,wrapperClasses:v}]})}return/cancel/.test(r)&&(_.height=n.height,_.depth=n.depth),/cancel/.test(r)&&!s?W([`mord`,`cancel-lap`],[_],t):W([`mord`],[_],t)},Qr=(e,t)=>{var n,r=new X(e.label.includes(`colorbox`)?`mpadded`:`menclose`,[Z(e.body,t)]);switch(e.label){case`\\cancel`:r.setAttribute(`notation`,`updiagonalstrike`);break;case`\\bcancel`:r.setAttribute(`notation`,`downdiagonalstrike`);break;case`\\phase`:r.setAttribute(`notation`,`phasorangle`);break;case`\\sout`:r.setAttribute(`notation`,`horizontalstrike`);break;case`\\fbox`:r.setAttribute(`notation`,`box`);break;case`\\angl`:r.setAttribute(`notation`,`actuarial`);break;case`\\fcolorbox`:case`\\colorbox`:if(n=t.fontMetrics().fboxsep*t.fontMetrics().ptPerEm,r.setAttribute(`width`,`+`+2*n+`pt`),r.setAttribute(`height`,`+`+2*n+`pt`),r.setAttribute(`lspace`,n+`pt`),r.setAttribute(`voffset`,n+`pt`),e.label===`\\fcolorbox`){var i=Math.max(t.fontMetrics().fboxrule,t.minRuleThickness);r.setAttribute(`style`,`border: `+k(i)+` solid `+e.borderColor)}break;case`\\xcancel`:r.setAttribute(`notation`,`updiagonalstrike downdiagonalstrike`);break}return e.backgroundColor&&r.setAttribute(`mathbackground`,e.backgroundColor),r};q({type:`enclose`,names:[`\\colorbox`],props:{numArgs:2,allowedInText:!0,argTypes:[`color`,`hbox`]},handler(e,t,n){var{parser:r,funcName:i}=e,a=Q(t[0],`color-token`).color,o=t[1];return{type:`enclose`,mode:r.mode,label:i,backgroundColor:a,body:o}},htmlBuilder:Zr,mathmlBuilder:Qr}),q({type:`enclose`,names:[`\\fcolorbox`],props:{numArgs:3,allowedInText:!0,argTypes:[`color`,`color`,`hbox`]},handler(e,t,n){var{parser:r,funcName:i}=e,a=Q(t[0],`color-token`).color,o=Q(t[1],`color-token`).color,s=t[2];return{type:`enclose`,mode:r.mode,label:i,backgroundColor:o,borderColor:a,body:s}},htmlBuilder:Zr,mathmlBuilder:Qr}),q({type:`enclose`,names:[`\\fbox`],props:{numArgs:1,argTypes:[`hbox`],allowedInText:!0},handler(e,t){var{parser:n}=e;return{type:`enclose`,mode:n.mode,label:`\\fbox`,body:t[0]}}}),q({type:`enclose`,names:[`\\cancel`,`\\bcancel`,`\\xcancel`,`\\phase`],props:{numArgs:1},handler(e,t){var{parser:n,funcName:r}=e,i=t[0];return{type:`enclose`,mode:n.mode,label:r,body:i}},htmlBuilder:Zr,mathmlBuilder:Qr}),q({type:`enclose`,names:[`\\sout`],props:{numArgs:1,allowedInText:!0},handler(e,t){var{parser:n,funcName:r}=e;n.mode===`math`&&n.settings.reportNonstrict(`mathVsSout`,`LaTeX's \\sout works only in text mode`);var i=t[0];return{type:`enclose`,mode:n.mode,label:r,body:i}},htmlBuilder:Zr,mathmlBuilder:Qr}),q({type:`enclose`,names:[`\\angl`],props:{numArgs:1,argTypes:[`hbox`],allowedInText:!1},handler(e,t){var{parser:n}=e;return{type:`enclose`,mode:n.mode,label:`\\angl`,body:t[0]}}});var $r={};function ei(e){for(var{type:t,names:n,props:r,handler:i,htmlBuilder:a,mathmlBuilder:o}=e,s={type:t,numArgs:r.numArgs||0,allowedInText:!1,numOptionalArgs:0,handler:i},c=0;c{if(!t.parser.settings.displayMode)throw new e(`{`+t.envName+`} can be used only in display mode.`)},oi=new Set([`gather`,`gather*`]);function si(e){if(!e.includes(`ed`))return!e.includes(`*`)}function ci(t,n,r){var{hskipBeforeAndAfter:i,addJot:a,cols:o,arraystretch:s,colSeparationType:c,autoTag:l,singleRow:u,emptySingleRow:d,maxNumCols:f,leqno:p}=n;if(t.gullet.beginGroup(),u||t.gullet.macros.set(`\\cr`,`\\\\\\relax`),!s){var m=t.gullet.expandMacroAsText(`\\arraystretch`);if(m==null)s=1;else if(s=parseFloat(m),!s||s<0)throw new e(`Invalid \\arraystretch: `+m)}t.gullet.beginGroup();var h=[],g=[h],_=[],v=[],y=l==null?void 0:[];function b(){l&&t.gullet.macros.set(`\\@eqnsw`,`1`,!0)}function x(){y&&(t.gullet.macros.get(`\\df@tag`)?(y.push(t.subparse([new ri(`\\df@tag`)])),t.gullet.macros.set(`\\df@tag`,void 0,!0)):y.push(!!l&&t.gullet.macros.get(`\\@eqnsw`)===`1`))}for(b(),v.push(ii(t));;){var S=t.parseExpression(!1,u?`\\end`:`\\\\`);t.gullet.endGroup(),t.gullet.beginGroup();var C={type:`ordgroup`,mode:t.mode,body:S};r&&(C={type:`styling`,mode:t.mode,style:r,resetFont:!0,body:[C]}),h.push(C);var w=t.fetch().text;if(w===`&`){if(f&&h.length===f){if(u||c)throw new e(`Too many tab characters: &`,t.nextToken);t.settings.reportNonstrict(`textEnv`,`Too few columns specified in the {array} column argument.`)}t.consume()}else if(w===`\\end`){x(),h.length===1&&C.type===`styling`&&C.body.length===1&&C.body[0].type===`ordgroup`&&C.body[0].body.length===0&&(g.length>1||!d)&&g.pop(),v.length0&&(v+=.25),l.push({pos:v,isDashed:e[t]})}for(y(o[0]),r=0;r0&&(T+=_,Se))for(r=0;r=s)){var ge=void 0;(i>0||t.hskipBeforeAndAfter)&&(ge=ue?.pregap??f,ge!==0&&(ie=W([`arraycolsep`],[]),ie.style.width=k(ge),re.push(ie)));var _e=[];for(r=0;r0){for(var we=Vt(`hline`,n,u),Te=Vt(`hdashline`,n,u),Ee=[{type:`elem`,elem:Ce,shift:0}];l.length>0;){var De=l.pop(),Oe=De.pos-te;De.isDashed?Ee.push({type:`elem`,elem:Te,shift:Oe}):Ee.push({type:`elem`,elem:we,shift:Oe})}Ce=G({positionType:`individualShift`,children:Ee})}if(oe.length===0)return W([`mord`],[Ce],n);var ke=W([`tag`],[G({positionType:`individualShift`,children:oe})],n);return Ut([Ce,ke])},di={c:`center `,l:`left `,r:`right `},fi=function(e,t){for(var n=[],r=new X(`mtd`,[],[`mtr-glue`]),i=new X(`mtd`,[],[`mml-eqn-num`]),a=0;a0){var p=e.cols,m=``,h=!1,g=0,_=p.length;p[0].type===`separator`&&(d+=`top `,g=1),p[p.length-1].type===`separator`&&(d+=`bottom `,--_);for(var v=g;v<_;v++){var y=p[v];y.type===`align`?(f+=di[y.align],h&&(m+=`none `),h=!0):y.type===`separator`&&(h&&=(m+=y.separator===`|`?`solid `:`dashed `,!1))}l.setAttribute(`columnalign`,f.trim()),/[sd]/.test(m)&&l.setAttribute(`columnlines`,m.trim())}if(e.colSeparationType===`align`){for(var b=e.cols||[],x=``,S=1;S0?`left `:``,d+=w[w.length-1].length>0?`right `:``;for(var ee=1;ee0&&p&&(g=1),r[m]={type:`align`,align:h,pregap:g,postgap:0}}return o.colSeparationType=p?`align`:`alignat`,o};ei({type:`array`,names:[`array`,`darray`],props:{numArgs:1},handler(t,n){var r=(Xn(n[0])?[n[0]]:Q(n[0],`ordgroup`).body).map(function(t){var n=Yn(t).text;if(`lcr`.includes(n))return{type:`align`,align:n};if(n===`|`)return{type:`separator`,separator:`|`};if(n===`:`)return{type:`separator`,separator:`:`};throw new e(`Unknown column alignment: `+n,t)}),i={cols:r,hskipBeforeAndAfter:!0,maxNumCols:r.length};return ci(t.parser,i,li(t.envName))},htmlBuilder:ui,mathmlBuilder:fi}),ei({type:`array`,names:[`matrix`,`pmatrix`,`bmatrix`,`Bmatrix`,`vmatrix`,`Vmatrix`,`matrix*`,`pmatrix*`,`bmatrix*`,`Bmatrix*`,`vmatrix*`,`Vmatrix*`],props:{numArgs:0},handler(t){var n={matrix:null,pmatrix:[`(`,`)`],bmatrix:[`[`,`]`],Bmatrix:[`\\{`,`\\}`],vmatrix:[`|`,`|`],Vmatrix:[`\\Vert`,`\\Vert`]}[t.envName.replace(`*`,``)],r=`c`,i={hskipBeforeAndAfter:!1,cols:[{type:`align`,align:r}]};if(t.envName.charAt(t.envName.length-1)===`*`){var a=t.parser;if(a.consumeSpaces(),a.fetch().text===`[`){if(a.consume(),a.consumeSpaces(),r=a.fetch().text,!`lcr`.includes(r))throw new e(`Expected l or c or r`,a.nextToken);a.consume(),a.consumeSpaces(),a.expect(`]`),a.consume(),i.cols=[{type:`align`,align:r}]}}var o=ci(t.parser,i,li(t.envName)),s=Math.max(0,...o.body.map(e=>e.length));return o.cols=Array(s).fill({type:`align`,align:r}),n?{type:`leftright`,mode:t.mode,body:[o],left:n[0],right:n[1],rightColor:void 0}:o},htmlBuilder:ui,mathmlBuilder:fi}),ei({type:`array`,names:[`smallmatrix`],props:{numArgs:0},handler(e){var t=ci(e.parser,{arraystretch:.5},`script`);return t.colSeparationType=`small`,t},htmlBuilder:ui,mathmlBuilder:fi}),ei({type:`array`,names:[`subarray`],props:{numArgs:1},handler(t,n){var r=(Xn(n[0])?[n[0]]:Q(n[0],`ordgroup`).body).map(function(t){var n=Yn(t).text;if(`lc`.includes(n))return{type:`align`,align:n};throw new e(`Unknown column alignment: `+n,t)});if(r.length>1)throw new e(`{subarray} can contain only one column`);var i={cols:r,hskipBeforeAndAfter:!1,arraystretch:.5},a=ci(t.parser,i,`script`);if(a.body.length>0&&a.body[0].length>1)throw new e(`{subarray} can contain only one column`);return a},htmlBuilder:ui,mathmlBuilder:fi}),ei({type:`array`,names:[`cases`,`dcases`,`rcases`,`drcases`],props:{numArgs:0},handler(e){var t=ci(e.parser,{arraystretch:1.2,cols:[{type:`align`,align:`l`,pregap:0,postgap:1},{type:`align`,align:`l`,pregap:0,postgap:0}]},li(e.envName));return{type:`leftright`,mode:e.mode,body:[t],left:e.envName.includes(`r`)?`.`:`\\{`,right:e.envName.includes(`r`)?`\\}`:`.`,rightColor:void 0}},htmlBuilder:ui,mathmlBuilder:fi}),ei({type:`array`,names:[`align`,`align*`,`aligned`,`split`],props:{numArgs:0},handler:pi,htmlBuilder:ui,mathmlBuilder:fi}),ei({type:`array`,names:[`gathered`,`gather`,`gather*`],props:{numArgs:0},handler(e){oi.has(e.envName)&&ai(e);var t={cols:[{type:`align`,align:`c`}],addJot:!0,colSeparationType:`gather`,autoTag:si(e.envName),emptySingleRow:!0,leqno:e.parser.settings.leqno};return ci(e.parser,t,`display`)},htmlBuilder:ui,mathmlBuilder:fi}),ei({type:`array`,names:[`alignat`,`alignat*`,`alignedat`],props:{numArgs:1},handler:pi,htmlBuilder:ui,mathmlBuilder:fi}),ei({type:`array`,names:[`equation`,`equation*`],props:{numArgs:0},handler(e){ai(e);var t={autoTag:si(e.envName),emptySingleRow:!0,singleRow:!0,maxNumCols:1,leqno:e.parser.settings.leqno};return ci(e.parser,t,`display`)},htmlBuilder:ui,mathmlBuilder:fi}),ei({type:`array`,names:[`CD`],props:{numArgs:0},handler(e){return ai(e),ur(e.parser)},htmlBuilder:ui,mathmlBuilder:fi}),$(`\\nonumber`,`\\gdef\\@eqnsw{0}`),$(`\\notag`,`\\nonumber`),q({type:`text`,names:[`\\hline`,`\\hdashline`],props:{numArgs:0,allowedInText:!0,allowedInMath:!0},handler(t,n){throw new e(t.funcName+` valid only within array environment`)}});var mi=$r;q({type:`environment`,names:[`\\begin`,`\\end`],props:{numArgs:1,argTypes:[`text`]},handler(t,n){var{parser:r,funcName:i}=t,a=n[0];if(a.type!==`ordgroup`)throw new e(`Invalid environment name`,a);for(var o=``,s=0;s{var n=e.font,r=t.withFont(n);return Y(e.body,r)},gi=(e,t)=>{var n=e.font,r=t.withFont(n);return Z(e.body,r)},_i={"\\Bbb":`\\mathbb`,"\\bold":`\\mathbf`,"\\frak":`\\mathfrak`};q({type:`font`,names:[`\\mathrm`,`\\mathit`,`\\mathbf`,`\\mathnormal`,`\\mathsfit`,`\\mathbb`,`\\mathcal`,`\\mathfrak`,`\\mathscr`,`\\mathsf`,`\\mathtt`,`\\Bbb`,`\\bold`,`\\frak`],props:{numArgs:1,allowedInArgument:!0},handler:(e,t)=>{var{parser:n,funcName:r}=e,i=on(t[0]),a=r;return a in _i&&(a=_i[a]),{type:`font`,mode:n.mode,font:a.slice(1),body:i}},htmlBuilder:hi,mathmlBuilder:gi}),q({type:`mclass`,names:[`\\boldsymbol`,`\\bm`],props:{numArgs:1},handler:(e,t)=>{var{parser:n}=e,r=t[0];return{type:`mclass`,mode:n.mode,mclass:ir(r),body:[{type:`font`,mode:n.mode,font:`boldsymbol`,body:r}],isCharacterBox:c(r)}}}),q({type:`font`,names:[`\\rm`,`\\sf`,`\\tt`,`\\bf`,`\\it`,`\\cal`],props:{numArgs:0,allowedInText:!0},handler:(e,t)=>{var{parser:n,funcName:r,breakOnTokenText:i}=e,{mode:a}=n,o=n.parseExpression(!0,i);return{type:`font`,mode:a,font:`math`+r.slice(1),body:{type:`ordgroup`,mode:n.mode,body:o}}},htmlBuilder:hi,mathmlBuilder:gi});var vi=(e,t)=>{var n=t.style,r=n.fracNum(),i=n.fracDen(),a=t.havingStyle(r),o=Y(e.numer,a,t);if(e.continued){var s=8.5/t.fontMetrics().ptPerEm,c=3.5/t.fontMetrics().ptPerEm;o.height=o.height0?3*f:7*f,h=t.fontMetrics().denom1):(d>0?(p=t.fontMetrics().num2,m=f):(p=t.fontMetrics().num3,m=3*f),h=t.fontMetrics().denom2);var g;if(u){var _=t.fontMetrics().axisHeight;p-o.depth-(_+.5*d){var n=new X(`mfrac`,[Z(e.numer,t),Z(e.denom,t)]);if(!e.hasBarLine)n.setAttribute(`linethickness`,`0px`);else if(e.barSize){var r=O(e.barSize,t);n.setAttribute(`linethickness`,k(r))}if(e.leftDelim!=null||e.rightDelim!=null){var i=[];if(e.leftDelim!=null){var a=new X(`mo`,[new bn(e.leftDelim.replace(`\\`,``))]);a.setAttribute(`fence`,`true`),i.push(a)}if(i.push(n),e.rightDelim!=null){var o=new X(`mo`,[new bn(e.rightDelim.replace(`\\`,``))]);o.setAttribute(`fence`,`true`),i.push(o)}return Tn(i)}return n},bi=(e,t)=>t?{type:`styling`,mode:e.mode,style:t,body:[e]}:e;q({type:`genfrac`,names:[`\\cfrac`,`\\dfrac`,`\\frac`,`\\tfrac`,`\\dbinom`,`\\binom`,`\\tbinom`,`\\\\atopfrac`,`\\\\bracefrac`,`\\\\brackfrac`],props:{numArgs:2,allowedInArgument:!0},handler:(e,t)=>{var{parser:n,funcName:r}=e,i=t[0],a=t[1],o,s=null,c=null;switch(r){case`\\cfrac`:case`\\dfrac`:case`\\frac`:case`\\tfrac`:o=!0;break;case`\\\\atopfrac`:o=!1;break;case`\\dbinom`:case`\\binom`:case`\\tbinom`:o=!1,s=`(`,c=`)`;break;case`\\\\bracefrac`:o=!1,s=`\\{`,c=`\\}`;break;case`\\\\brackfrac`:o=!1,s=`[`,c=`]`;break;default:throw Error(`Unrecognized genfrac command`)}var l=r===`\\cfrac`,u=null;return l||r.startsWith(`\\d`)?u=`display`:r.startsWith(`\\t`)&&(u=`text`),bi({type:`genfrac`,mode:n.mode,numer:i,denom:a,continued:l,hasBarLine:o,leftDelim:s,rightDelim:c,barSize:null},u)},htmlBuilder:vi,mathmlBuilder:yi}),q({type:`infix`,names:[`\\over`,`\\choose`,`\\atop`,`\\brace`,`\\brack`],props:{numArgs:0,infix:!0},handler(e){var{parser:t,funcName:n,token:r}=e,i;switch(n){case`\\over`:i=`\\frac`;break;case`\\choose`:i=`\\binom`;break;case`\\atop`:i=`\\\\atopfrac`;break;case`\\brace`:i=`\\\\bracefrac`;break;case`\\brack`:i=`\\\\brackfrac`;break;default:throw Error(`Unrecognized infix genfrac command`)}return{type:`infix`,mode:t.mode,replaceWith:i,token:r}}});var xi=[`display`,`text`,`script`,`scriptscript`],Si=function(e){var t=null;return e.length>0&&(t=e,t=t===`.`?null:t),t};q({type:`genfrac`,names:[`\\genfrac`],props:{numArgs:6,allowedInArgument:!0,argTypes:[`math`,`math`,`size`,`text`,`math`,`math`]},handler(e,t){var{parser:n}=e,r=t[4],i=t[5],a=on(t[0]),o=a.type===`atom`&&a.family===`open`?Si(a.text):null,s=on(t[1]),c=s.type===`atom`&&s.family===`close`?Si(s.text):null,l=Q(t[2],`size`),u,d=null;l.isBlank?u=!0:(d=l.value,u=d.number>0);var f=null,p=t[3];if(p.type===`ordgroup`){if(p.body.length>0){var m=Q(p.body[0],`textord`);f=xi[Number(m.text)]}}else p=Q(p,`textord`),f=xi[Number(p.text)];return bi({type:`genfrac`,mode:n.mode,numer:r,denom:i,continued:!1,hasBarLine:u,barSize:d,leftDelim:o,rightDelim:c},f)}}),q({type:`infix`,names:[`\\above`],props:{numArgs:1,argTypes:[`size`],infix:!0},handler(e,t){var{parser:n,funcName:r,token:i}=e;return{type:`infix`,mode:n.mode,replaceWith:`\\\\abovefrac`,size:Q(t[0],`size`).value,token:i}}}),q({type:`genfrac`,names:[`\\\\abovefrac`],props:{numArgs:3,argTypes:[`math`,`size`,`math`]},handler:(e,t)=>{var{parser:n,funcName:r}=e,i=t[0],a=Q(t[1],`infix`).size;if(!a)throw Error(`\\\\abovefrac expected size, but got `+String(a));var o=t[2],s=a.number>0;return{type:`genfrac`,mode:n.mode,numer:i,denom:o,continued:!1,hasBarLine:s,barSize:a,leftDelim:null,rightDelim:null}}});var Ci=(e,t)=>{var n=t.style,r,i;e.type===`supsub`?(r=e.sup?Y(e.sup,t.havingStyle(n.sup()),t):Y(e.sub,t.havingStyle(n.sub()),t),i=Q(e.base,`horizBrace`)):i=Q(e,`horizBrace`);var a=Y(i.base,t.havingBaseStyle(E.DISPLAY)),o=Wn(i,t),s=i.isOver?G({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:.1},{type:`elem`,elem:o,wrapperClasses:[`svg-align`]}]}):G({positionType:`bottom`,positionData:a.depth+.1+o.height,children:[{type:`elem`,elem:o,wrapperClasses:[`svg-align`]},{type:`kern`,size:.1},{type:`elem`,elem:a}]});if(r){var c=W([`minner`,i.isOver?`mover`:`munder`],[s],t);s=i.isOver?G({positionType:`firstBaseline`,children:[{type:`elem`,elem:c},{type:`kern`,size:.2},{type:`elem`,elem:r}]}):G({positionType:`bottom`,positionData:c.depth+.2+r.height+r.depth,children:[{type:`elem`,elem:r},{type:`kern`,size:.2},{type:`elem`,elem:c}]})}return W([`minner`,i.isOver?`mover`:`munder`],[s],t)};q({type:`horizBrace`,names:[`\\overbrace`,`\\underbrace`,`\\overbracket`,`\\underbracket`],props:{numArgs:1},handler(e,t){var{parser:n,funcName:r}=e;return{type:`horizBrace`,mode:n.mode,label:r,isOver:r.includes(`\\over`),base:t[0]}},htmlBuilder:Ci,mathmlBuilder:(e,t)=>{var n=Vn(e.label);return new X(e.isOver?`mover`:`munder`,[Z(e.base,t),n])}}),q({type:`href`,names:[`\\href`],props:{numArgs:2,argTypes:[`url`,`original`],allowedInText:!0},handler:(e,t)=>{var{parser:n}=e,r=t[1],i=Q(t[0],`url`).url;return n.settings.isTrusted({command:`\\href`,url:i})?{type:`href`,mode:n.mode,href:i,body:J(r)}:n.formatUnsupportedCmd(`\\href`)},htmlBuilder:(e,t)=>{var n=dn(e.body,t,!1);return Ht(e.href,[],n,t)},mathmlBuilder:(e,t)=>{var n=An(e.body,t);return n instanceof X||(n=new X(`mrow`,[n])),n.setAttribute(`href`,e.href),n}}),q({type:`href`,names:[`\\url`],props:{numArgs:1,argTypes:[`url`],allowedInText:!0},handler:(e,t)=>{var{parser:n}=e,r=Q(t[0],`url`).url;if(!n.settings.isTrusted({command:`\\url`,url:r}))return n.formatUnsupportedCmd(`\\url`);for(var i=[],a=0;a{var{parser:r,funcName:i,token:a}=t,o=Q(n[0],`raw`).string,s=n[1];r.settings.strict&&r.settings.reportNonstrict(`htmlExtension`,`HTML extension is disabled on strict mode`);var c,l={};switch(i){case`\\htmlClass`:l.class=o,c={command:`\\htmlClass`,class:o};break;case`\\htmlId`:l.id=o,c={command:`\\htmlId`,id:o};break;case`\\htmlStyle`:l.style=o,c={command:`\\htmlStyle`,style:o};break;case`\\htmlData`:for(var u=o.split(`,`),d=0;d{var n=dn(e.body,t,!1),r=[`enclosing`];e.attributes.class&&r.push(...e.attributes.class.trim().split(/\s+/));var i=W(r,n,t);for(var a in e.attributes)a!==`class`&&e.attributes.hasOwnProperty(a)&&i.setAttribute(a,e.attributes[a]);return i},mathmlBuilder:(e,t)=>An(e.body,t)}),q({type:`htmlmathml`,names:[`\\html@mathml`],props:{numArgs:2,allowedInArgument:!0,allowedInText:!0},handler:(e,t)=>{var{parser:n}=e;return{type:`htmlmathml`,mode:n.mode,html:J(t[0]),mathml:J(t[1])}},htmlBuilder:(e,t)=>Ut(dn(e.html,t,!1)),mathmlBuilder:(e,t)=>An(e.mathml,t)});var wi=function(t){if(/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(t))return{number:+t,unit:`bp`};var n=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(t);if(!n)throw new e(`Invalid size: '`+t+`' in \\includegraphics`);var r={number:+(n[1]+n[2]),unit:n[3]};if(!Te(r))throw new e(`Invalid unit: '`+r.unit+`' in \\includegraphics.`);return r};q({type:`includegraphics`,names:[`\\includegraphics`],props:{numArgs:1,numOptionalArgs:1,argTypes:[`raw`,`url`],allowedInText:!1},handler:(t,n,r)=>{var{parser:i}=t,a={number:0,unit:`em`},o={number:.9,unit:`em`},s={number:0,unit:`em`},c=``;if(r[0])for(var l=Q(r[0],`raw`).string.split(`,`),u=0;u{var n=O(e.height,t),r=0;e.totalheight.number>0&&(r=O(e.totalheight,t)-n);var i=0;e.width.number>0&&(i=O(e.width,t));var a={height:k(n+r)};i>0&&(a.width=k(i)),r>0&&(a.verticalAlign=k(-r));var o=new Pe(e.src,e.alt,a);return o.height=n,o.depth=r,o},mathmlBuilder:(e,t)=>{var n=new X(`mglyph`,[]);n.setAttribute(`alt`,e.alt);var r=O(e.height,t),i=0;if(e.totalheight.number>0&&(i=O(e.totalheight,t)-r,n.setAttribute(`valign`,k(-i))),n.setAttribute(`height`,k(r+i)),e.width.number>0){var a=O(e.width,t);n.setAttribute(`width`,k(a))}return n.setAttribute(`src`,e.src),n}}),q({type:`kern`,names:[`\\kern`,`\\mkern`,`\\hskip`,`\\mskip`],props:{numArgs:1,argTypes:[`size`],primitive:!0,allowedInText:!0},handler(e,t){var{parser:n,funcName:r}=e,i=Q(t[0],`size`);if(n.settings.strict){var a=r[1]===`m`,o=i.value.unit===`mu`;a?(o||n.settings.reportNonstrict(`mathVsTextUnits`,`LaTeX's `+r+` supports only mu units, `+(`not `+i.value.unit+` units`)),n.mode!==`math`&&n.settings.reportNonstrict(`mathVsTextUnits`,`LaTeX's `+r+` works only in math mode`)):o&&n.settings.reportNonstrict(`mathVsTextUnits`,`LaTeX's `+r+` doesn't support mu units`)}return{type:`kern`,mode:n.mode,dimension:i.value}},htmlBuilder(e,t){return Kt(e.dimension,t)},mathmlBuilder(e,t){return new xn(O(e.dimension,t))}}),q({type:`lap`,names:[`\\mathllap`,`\\mathrlap`,`\\mathclap`],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{var{parser:n,funcName:r}=e,i=t[0];return{type:`lap`,mode:n.mode,alignment:r.slice(5),body:i}},htmlBuilder:(e,t)=>{var n;e.alignment===`clap`?(n=W([],[Y(e.body,t)]),n=W([`inner`],[n],t)):n=W([`inner`],[Y(e.body,t)]);var r=W([`fix`],[]),i=W([e.alignment],[n,r],t),a=W([`strut`]);return a.style.height=k(i.height+i.depth),i.depth&&(a.style.verticalAlign=k(-i.depth)),i.children.unshift(a),i=W([`thinbox`],[i],t),W([`mord`,`vbox`],[i],t)},mathmlBuilder:(e,t)=>{var n=new X(`mpadded`,[Z(e.body,t)]);if(e.alignment!==`rlap`){var r=e.alignment===`llap`?`-1`:`-0.5`;n.setAttribute(`lspace`,r+`width`)}return n.setAttribute(`width`,`0px`),n}}),q({type:`styling`,names:[`\\(`,`$`],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(e,t){var{funcName:n,parser:r}=e,i=r.mode;r.switchMode(`math`);var a=n===`\\(`?`\\)`:`$`,o=r.parseExpression(!1,a);return r.expect(a),r.switchMode(i),{type:`styling`,mode:r.mode,style:`text`,resetFont:!0,body:o}}}),q({type:`text`,names:[`\\)`,`\\]`],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(t,n){throw new e(`Mismatched `+t.funcName)}});var Ti=(e,t)=>{switch(t.style.size){case E.DISPLAY.size:return e.display;case E.TEXT.size:return e.text;case E.SCRIPT.size:return e.script;case E.SCRIPTSCRIPT.size:return e.scriptscript;default:return e.text}};q({type:`mathchoice`,names:[`\\mathchoice`],props:{numArgs:4,primitive:!0},handler:(e,t)=>{var{parser:n}=e;return{type:`mathchoice`,mode:n.mode,display:J(t[0]),text:J(t[1]),script:J(t[2]),scriptscript:J(t[3])}},htmlBuilder:(e,t)=>Ut(dn(Ti(e,t),t,!1)),mathmlBuilder:(e,t)=>An(Ti(e,t),t)});var Ei=(e,t,n,r,i,a,o)=>{e=W([],[e]);var s=n&&c(n),l,u;if(t){var d=Y(t,r.havingStyle(i.sup()),r);u={elem:d,kern:Math.max(r.fontMetrics().bigOpSpacing1,r.fontMetrics().bigOpSpacing3-d.depth)}}if(n){var f=Y(n,r.havingStyle(i.sub()),r);l={elem:f,kern:Math.max(r.fontMetrics().bigOpSpacing2,r.fontMetrics().bigOpSpacing4-f.height)}}var p;if(u&&l)p=G({positionType:`bottom`,positionData:r.fontMetrics().bigOpSpacing5+l.elem.height+l.elem.depth+l.kern+e.depth+o,children:[{type:`kern`,size:r.fontMetrics().bigOpSpacing5},{type:`elem`,elem:l.elem,marginLeft:k(-a)},{type:`kern`,size:l.kern},{type:`elem`,elem:e},{type:`kern`,size:u.kern},{type:`elem`,elem:u.elem,marginLeft:k(a)},{type:`kern`,size:r.fontMetrics().bigOpSpacing5}]});else if(l)p=G({positionType:`top`,positionData:e.height-o,children:[{type:`kern`,size:r.fontMetrics().bigOpSpacing5},{type:`elem`,elem:l.elem,marginLeft:k(-a)},{type:`kern`,size:l.kern},{type:`elem`,elem:e}]});else if(u)p=G({positionType:`bottom`,positionData:e.depth+o,children:[{type:`elem`,elem:e},{type:`kern`,size:u.kern},{type:`elem`,elem:u.elem,marginLeft:k(a)},{type:`kern`,size:r.fontMetrics().bigOpSpacing5}]});else return e;var m=[p];if(l&&a!==0&&!s){var h=W([`mspace`],[],r);h.style.marginRight=k(a),m.unshift(h)}return W([`mop`,`op-limits`],m,r)},Di=new Set([`\\smallint`]),Oi=(e,t)=>{var n,r,i=!1,a;e.type===`supsub`?(n=e.sup,r=e.sub,a=Q(e.base,`op`),i=!0):a=Q(e,`op`);var o=t.style,s=!1;o.size===E.DISPLAY.size&&a.symbol&&!Di.has(a.name)&&(s=!0);var c,l;if(a.symbol){var u=s?`Size2-Regular`:`Size1-Regular`,d=``;if((a.name===`\\oiint`||a.name===`\\oiiint`)&&(d=a.name.slice(1),a.name=d===`oiint`?`\\iint`:`\\iiint`),c=Nt(a.name,u,`math`,t,[`mop`,`op-symbol`,s?`large-op`:`small-op`]),l=c.italic,d.length>0){var f=Xt(d+`Size`+(s?`2`:`1`),t);c=G({positionType:`individualShift`,children:[{type:`elem`,elem:c,shift:0},{type:`elem`,elem:f,shift:s?.08:0}]}),a.name=`\\`+d,c.classes.unshift(`mop`),c.italic=l}}else if(a.body){var p=dn(a.body,t,!0);p.length===1&&p[0]instanceof Ie?(c=p[0],c.classes[0]=`mop`):c=W([`mop`],p,t)}else{for(var m=[],h=1;h{var n;if(e.symbol)n=new X(`mo`,[wn(e.name,e.mode)]),Di.has(e.name)&&n.setAttribute(`largeop`,`false`);else if(e.body)n=new X(`mo`,kn(e.body,t));else{n=new X(`mi`,[new bn(e.name.slice(1))]);var r=new X(`mo`,[wn(`⁡`,`text`)]);n=e.parentIsSupSub?new X(`mrow`,[n,r]):yn([n,r])}return n},Ai={"∏":`\\prod`,"∐":`\\coprod`,"∑":`\\sum`,"⋀":`\\bigwedge`,"⋁":`\\bigvee`,"⋂":`\\bigcap`,"⋃":`\\bigcup`,"⨀":`\\bigodot`,"⨁":`\\bigoplus`,"⨂":`\\bigotimes`,"⨄":`\\biguplus`,"⨆":`\\bigsqcup`};q({type:`op`,names:`\\coprod.\\bigvee.\\bigwedge.\\biguplus.\\bigcap.\\bigcup.\\intop.\\prod.\\sum.\\bigotimes.\\bigoplus.\\bigodot.\\bigsqcup.\\smallint.∏.∐.∑.⋀.⋁.⋂.⋃.⨀.⨁.⨂.⨄.⨆`.split(`.`),props:{numArgs:0},handler:(e,t)=>{var{parser:n,funcName:r}=e,i=r;return i.length===1&&(i=Ai[i]),{type:`op`,mode:n.mode,limits:!0,parentIsSupSub:!1,symbol:!0,name:i}},htmlBuilder:Oi,mathmlBuilder:ki}),q({type:`op`,names:[`\\mathop`],props:{numArgs:1,primitive:!0},handler:(e,t)=>{var{parser:n}=e,r=t[0];return{type:`op`,mode:n.mode,limits:!1,parentIsSupSub:!1,symbol:!1,body:J(r)}},htmlBuilder:Oi,mathmlBuilder:ki});var ji={"∫":`\\int`,"∬":`\\iint`,"∭":`\\iiint`,"∮":`\\oint`,"∯":`\\oiint`,"∰":`\\oiiint`};q({type:`op`,names:`\\arcsin.\\arccos.\\arctan.\\arctg.\\arcctg.\\arg.\\ch.\\cos.\\cosec.\\cosh.\\cot.\\cotg.\\coth.\\csc.\\ctg.\\cth.\\deg.\\dim.\\exp.\\hom.\\ker.\\lg.\\ln.\\log.\\sec.\\sin.\\sinh.\\sh.\\tan.\\tanh.\\tg.\\th`.split(`.`),props:{numArgs:0},handler(e){var{parser:t,funcName:n}=e;return{type:`op`,mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!1,name:n}},htmlBuilder:Oi,mathmlBuilder:ki}),q({type:`op`,names:[`\\det`,`\\gcd`,`\\inf`,`\\lim`,`\\max`,`\\min`,`\\Pr`,`\\sup`],props:{numArgs:0},handler(e){var{parser:t,funcName:n}=e;return{type:`op`,mode:t.mode,limits:!0,parentIsSupSub:!1,symbol:!1,name:n}},htmlBuilder:Oi,mathmlBuilder:ki}),q({type:`op`,names:[`\\int`,`\\iint`,`\\iiint`,`\\oint`,`\\oiint`,`\\oiiint`,`∫`,`∬`,`∭`,`∮`,`∯`,`∰`],props:{numArgs:0,allowedInArgument:!0},handler(e){var{parser:t,funcName:n}=e,r=n;return r.length===1&&(r=ji[r]),{type:`op`,mode:t.mode,limits:!1,parentIsSupSub:!1,symbol:!0,name:r}},htmlBuilder:Oi,mathmlBuilder:ki});var Mi=(e,t)=>{var n,r,i=!1,a;e.type===`supsub`?(n=e.sup,r=e.sub,a=Q(e.base,`operatorname`),i=!0):a=Q(e,`operatorname`);var o;if(a.body.length>0){for(var s=dn(a.body.map(e=>{var t=`text`in e?e.text:void 0;return typeof t==`string`?{type:`textord`,mode:e.mode,text:t}:e}),t.withFont(`mathrm`),!0),c=0;c{var{parser:n,funcName:r}=e,i=t[0];return{type:`operatorname`,mode:n.mode,body:J(i),alwaysHandleSupSub:r===`\\operatornamewithlimits`,limits:!1,parentIsSupSub:!1}},htmlBuilder:Mi,mathmlBuilder:(e,t)=>{for(var n=kn(e.body,t.withFont(`mathrm`)),r=!0,i=0;ie.toText()).join(``))]);var s=new X(`mi`,n);s.setAttribute(`mathvariant`,`normal`);var c=new X(`mo`,[wn(`⁡`,`text`)]);return e.parentIsSupSub?new X(`mrow`,[s,c]):yn([s,c])}}),$(`\\operatorname`,`\\@ifstar\\operatornamewithlimits\\operatorname@`),an({type:`ordgroup`,htmlBuilder(e,t){return e.semisimple?Ut(dn(e.body,t,!1)):W([`mord`],dn(e.body,t,!0),t)},mathmlBuilder(e,t){return An(e.body,t,!0)}}),q({type:`overline`,names:[`\\overline`],props:{numArgs:1},handler(e,t){var{parser:n}=e,r=t[0];return{type:`overline`,mode:n.mode,body:r}},htmlBuilder(e,t){var n=Y(e.body,t.havingCrampedStyle()),r=Vt(`overline-line`,t),i=t.fontMetrics().defaultRuleThickness;return W([`mord`,`overline`],[G({positionType:`firstBaseline`,children:[{type:`elem`,elem:n},{type:`kern`,size:3*i},{type:`elem`,elem:r},{type:`kern`,size:i}]})],t)},mathmlBuilder(e,t){var n=new X(`mo`,[new bn(`‾`)]);n.setAttribute(`stretchy`,`true`);var r=new X(`mover`,[Z(e.body,t),n]);return r.setAttribute(`accent`,`true`),r}}),q({type:`phantom`,names:[`\\phantom`],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{var{parser:n}=e,r=t[0];return{type:`phantom`,mode:n.mode,body:J(r)}},htmlBuilder:(e,t)=>Ut(dn(e.body,t.withPhantom(),!1)),mathmlBuilder:(e,t)=>new X(`mphantom`,kn(e.body,t))}),$(`\\hphantom`,`\\smash{\\phantom{#1}}`),q({type:`vphantom`,names:[`\\vphantom`],props:{numArgs:1,allowedInText:!0},handler:(e,t)=>{var{parser:n}=e,r=t[0];return{type:`vphantom`,mode:n.mode,body:r}},htmlBuilder:(e,t)=>W([`mord`,`rlap`],[W([`inner`],[Y(e.body,t.withPhantom())]),W([`fix`],[])],t),mathmlBuilder:(e,t)=>{var n=new X(`mpadded`,[new X(`mphantom`,kn(J(e.body),t))]);return n.setAttribute(`width`,`0px`),n}}),q({type:`raisebox`,names:[`\\raisebox`],props:{numArgs:2,argTypes:[`size`,`hbox`],allowedInText:!0},handler(e,t){var{parser:n}=e,r=Q(t[0],`size`).value,i=t[1];return{type:`raisebox`,mode:n.mode,dy:r,body:i}},htmlBuilder(e,t){var n=Y(e.body,t);return G({positionType:`shift`,positionData:-O(e.dy,t),children:[{type:`elem`,elem:n}]})},mathmlBuilder(e,t){var n=new X(`mpadded`,[Z(e.body,t)]),r=e.dy.number+e.dy.unit;return n.setAttribute(`voffset`,r),n}}),q({type:`internal`,names:[`\\relax`],props:{numArgs:0,allowedInText:!0,allowedInArgument:!0},handler(e){var{parser:t}=e;return{type:`internal`,mode:t.mode}}}),q({type:`rule`,names:[`\\rule`],props:{numArgs:2,numOptionalArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`size`,`size`,`size`]},handler(e,t,n){var{parser:r}=e,i=n[0],a=Q(t[0],`size`),o=Q(t[1],`size`);return{type:`rule`,mode:r.mode,shift:i&&Q(i,`size`).value,width:a.value,height:o.value}},htmlBuilder(e,t){var n=W([`mord`,`rule`],[],t),r=O(e.width,t),i=O(e.height,t),a=e.shift?O(e.shift,t):0;return n.style.borderRightWidth=k(r),n.style.borderTopWidth=k(i),n.style.bottom=k(a),n.width=r,n.height=i+a,n.depth=-a,n.maxFontSize=i*1.125*t.sizeMultiplier,n},mathmlBuilder(e,t){var n=O(e.width,t),r=O(e.height,t),i=e.shift?O(e.shift,t):0,a=t.color&&t.getColor()||`black`,o=new X(`mspace`);o.setAttribute(`mathbackground`,a),o.setAttribute(`width`,k(n)),o.setAttribute(`height`,k(r));var s=new X(`mpadded`,[o]);return i>=0?s.setAttribute(`height`,k(i)):(s.setAttribute(`height`,k(i)),s.setAttribute(`depth`,k(-i))),s.setAttribute(`voffset`,k(i)),s}});function Ni(e,t,n){for(var r=dn(e,t,!1),i=t.sizeMultiplier/n.sizeMultiplier,a=0;a{var{breakOnTokenText:n,funcName:r,parser:i}=e,a=i.parseExpression(!1,n);return{type:`sizing`,mode:i.mode,size:Pi.indexOf(r)+1,body:a}},htmlBuilder:(e,t)=>{var n=t.havingSize(e.size);return Ni(e.body,n,t)},mathmlBuilder:(e,t)=>{var n=t.havingSize(e.size),r=new X(`mstyle`,kn(e.body,n));return r.setAttribute(`mathsize`,k(n.sizeMultiplier)),r}}),q({type:`smash`,names:[`\\smash`],props:{numArgs:1,numOptionalArgs:1,allowedInText:!0},handler:(e,t,n)=>{var{parser:r}=e,i=!1,a=!1,o=n[0]&&Q(n[0],`ordgroup`);if(o)for(var s,c=0;c{var n=W([],[Y(e.body,t)]);if(!e.smashHeight&&!e.smashDepth)return n;if(e.smashHeight&&(n.height=0),e.smashDepth&&(n.depth=0),e.smashHeight&&e.smashDepth)return W([`mord`,`smash`],[n],t);if(n.children)for(var r=0;r{var n=new X(`mpadded`,[Z(e.body,t)]);return e.smashHeight&&n.setAttribute(`height`,`0px`),e.smashDepth&&n.setAttribute(`depth`,`0px`),n}}),q({type:`sqrt`,names:[`\\sqrt`],props:{numArgs:1,numOptionalArgs:1},handler(e,t,n){var{parser:r}=e,i=n[0],a=t[0];return{type:`sqrt`,mode:r.mode,body:a,index:i}},htmlBuilder(e,t){var n=Y(e.body,t.havingCrampedStyle());n.height===0&&(n.height=t.fontMetrics().xHeight),n=Wt(n,t);var r=t.fontMetrics().defaultRuleThickness,i=r;t.style.idn.height+n.depth+a&&(a=(a+l-n.height-n.depth)/2);var u=o.height-n.height-a-s;n.style.paddingLeft=k(c);var d=G({positionType:`firstBaseline`,children:[{type:`elem`,elem:n,wrapperClasses:[`svg-align`]},{type:`kern`,size:-(n.height+u)},{type:`elem`,elem:o},{type:`kern`,size:s}]});if(e.index){var f=t.havingStyle(E.SCRIPTSCRIPT),p=Y(e.index,f,t);return W([`mord`,`sqrt`],[W([`root`],[G({positionType:`shift`,positionData:-(.6*(d.height-d.depth)),children:[{type:`elem`,elem:p}]})]),d],t)}else return W([`mord`,`sqrt`],[d],t)},mathmlBuilder(e,t){var{body:n,index:r}=e;return r?new X(`mroot`,[Z(n,t),Z(r,t)]):new X(`msqrt`,[Z(n,t)])}});var Fi={display:E.DISPLAY,text:E.TEXT,script:E.SCRIPT,scriptscript:E.SCRIPTSCRIPT};function Ii(e){return e in Fi}q({type:`styling`,names:[`\\displaystyle`,`\\textstyle`,`\\scriptstyle`,`\\scriptscriptstyle`],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(e,t){var{breakOnTokenText:n,funcName:r,parser:i}=e,a=i.parseExpression(!0,n),o=r.slice(1,r.length-5);if(!Ii(o))throw Error(`Unknown style: `+o);return{type:`styling`,mode:i.mode,style:o,body:a}},htmlBuilder(e,t){var n=Fi[e.style],r=t.havingStyle(n);return e.resetFont&&(r=r.withFont(``)),Ni(e.body,r,t)},mathmlBuilder(e,t){var n=Fi[e.style],r=t.havingStyle(n);e.resetFont&&(r=r.withFont(``));var i=new X(`mstyle`,kn(e.body,r)),a={display:[`0`,`true`],text:[`0`,`false`],script:[`1`,`false`],scriptscript:[`2`,`false`]}[e.style];return i.setAttribute(`scriptlevel`,a[0]),i.setAttribute(`displaystyle`,a[1]),i}});var Li=function(e,t){var n=e.base;return n?n.type===`op`?n.limits&&(t.style.size===E.DISPLAY.size||n.alwaysHandleSupSub)?Oi:null:n.type===`operatorname`?n.alwaysHandleSupSub&&(t.style.size===E.DISPLAY.size||n.limits)?Mi:null:n.type===`accent`?c(n.base)?Qn:null:n.type===`horizBrace`&&!e.sub===n.isOver?Ci:null:null};an({type:`supsub`,htmlBuilder(e,t){var n=Li(e,t);if(n)return n(e,t);var{base:r,sup:i,sub:a}=e,o=Y(r,t),s,l,u=t.fontMetrics(),d=0,f=0,p=r&&c(r);if(i){var m=t.havingStyle(t.style.sup());s=Y(i,m,t),p||(d=o.height-m.fontMetrics().supDrop*m.sizeMultiplier/t.sizeMultiplier)}if(a){var h=t.havingStyle(t.style.sub());l=Y(a,h,t),p||(f=o.depth+h.fontMetrics().subDrop*h.sizeMultiplier/t.sizeMultiplier)}var g=t.style===E.DISPLAY?u.sup1:t.style.cramped?u.sup3:u.sup2,_=t.sizeMultiplier,v=k(.5/u.ptPerEm/_),y=null;if(l){var b=e.base&&e.base.type===`op`&&e.base.name&&(e.base.name===`\\oiint`||e.base.name===`\\oiiint`);(o instanceof Ie||b)&&(y=k(-(o.italic??0)))}var x;if(s&&l){d=Math.max(d,g,s.depth+.25*u.xHeight),f=Math.max(f,u.sub2);var S=4*u.defaultRuleThickness;if(d-s.depth-(l.height-f)0&&(d+=C,f-=C)}x=G({positionType:`individualShift`,children:[{type:`elem`,elem:l,shift:f,marginRight:v,marginLeft:y},{type:`elem`,elem:s,shift:-d,marginRight:v}]})}else if(l)f=Math.max(f,u.sub1,l.height-.8*u.xHeight),x=G({positionType:`shift`,positionData:f,children:[{type:`elem`,elem:l,marginLeft:y,marginRight:v}]});else if(s)d=Math.max(d,g,s.depth+.25*u.xHeight),x=G({positionType:`shift`,positionData:-d,children:[{type:`elem`,elem:s,marginRight:v}]});else throw Error(`supsub must have either sup or sub.`);return W([hn(o,`right`)||`mord`],[o,W([`msupsub`],[x])],t)},mathmlBuilder(e,t){var n=!1,r,i;e.base&&e.base.type===`horizBrace`&&(i=!!e.sup,i===e.base.isOver&&(n=!0,r=e.base.isOver)),e.base&&(e.base.type===`op`||e.base.type===`operatorname`)&&(e.base.parentIsSupSub=!0);var a=[Z(e.base,t)];e.sub&&a.push(Z(e.sub,t)),e.sup&&a.push(Z(e.sup,t));var o;if(n)o=r?`mover`:`munder`;else if(!e.sub){var s=e.base;o=s&&s.type===`op`&&s.limits&&(t.style===E.DISPLAY||s.alwaysHandleSupSub)||s&&s.type===`operatorname`&&s.alwaysHandleSupSub&&(s.limits||t.style===E.DISPLAY)?`mover`:`msup`}else if(e.sup){var c=e.base;o=c&&c.type===`op`&&c.limits&&t.style===E.DISPLAY||c&&c.type===`operatorname`&&c.alwaysHandleSupSub&&(t.style===E.DISPLAY||c.limits)?`munderover`:`msubsup`}else{var l=e.base;o=l&&l.type===`op`&&l.limits&&(t.style===E.DISPLAY||l.alwaysHandleSupSub)||l&&l.type===`operatorname`&&l.alwaysHandleSupSub&&(l.limits||t.style===E.DISPLAY)?`munder`:`msub`}return new X(o,a)}}),an({type:`atom`,htmlBuilder(e,t){return Pt(e.text,e.mode,t,[`m`+e.family])},mathmlBuilder(e,t){var n=new X(`mo`,[wn(e.text,e.mode)]);if(e.family===`bin`){var r=Dn(e,t);r===`bold-italic`&&n.setAttribute(`mathvariant`,r)}else e.family===`punct`?n.setAttribute(`separator`,`true`):(e.family===`open`||e.family===`close`)&&n.setAttribute(`stretchy`,`false`);return n}});var Ri={mi:`italic`,mn:`normal`,mtext:`normal`};an({type:`mathord`,htmlBuilder(e,t){return It(e,t,`mathord`)},mathmlBuilder(e,t){var n=new X(`mi`,[wn(e.text,e.mode,t)]),r=Dn(e,t)||`italic`;return r!==Ri[n.type]&&n.setAttribute(`mathvariant`,r),n}}),an({type:`textord`,htmlBuilder(e,t){return It(e,t,`textord`)},mathmlBuilder(e,t){var n=wn(e.text,e.mode,t),r=Dn(e,t)||`normal`,i=e.mode===`text`?new X(`mtext`,[n]):/[0-9]/.test(e.text)?new X(`mn`,[n]):e.text===`\\prime`?new X(`mo`,[n]):new X(`mi`,[n]);return r!==Ri[i.type]&&i.setAttribute(`mathvariant`,r),i}});var zi={"\\nobreak":`nobreak`,"\\allowbreak":`allowbreak`},Bi={" ":{},"\\ ":{},"~":{className:`nobreak`},"\\space":{},"\\nobreakspace":{className:`nobreak`}};an({type:`spacing`,htmlBuilder(t,n){if(Bi.hasOwnProperty(t.text)){var r=Bi[t.text].className||``;if(t.mode===`text`){var i=It(t,n,`textord`);return i.classes.push(r),i}else return W([`mspace`,r],[Pt(t.text,t.mode,n)],n)}else if(zi.hasOwnProperty(t.text))return W([`mspace`,zi[t.text]],[],n);else throw new e(`Unknown type of space "`+t.text+`"`)},mathmlBuilder(t,n){var r;if(Bi.hasOwnProperty(t.text))r=new X(`mtext`,[new bn(`\xA0`)]);else if(zi.hasOwnProperty(t.text))return new X(`mspace`);else throw new e(`Unknown type of space "`+t.text+`"`);return r}});var Vi=()=>{var e=new X(`mtd`,[]);return e.setAttribute(`width`,`50%`),e};an({type:`tag`,mathmlBuilder(e,t){var n=new X(`mtable`,[new X(`mtr`,[Vi(),new X(`mtd`,[An(e.body,t)]),Vi(),new X(`mtd`,[An(e.tag,t)])])]);return n.setAttribute(`width`,`100%`),n}});var Hi={"\\text":void 0,"\\textrm":`textrm`,"\\textsf":`textsf`,"\\texttt":`texttt`,"\\textnormal":`textrm`},Ui={"\\textbf":`textbf`,"\\textmd":`textmd`},Wi={"\\textit":`textit`,"\\textup":`textup`},Gi=(e,t)=>{var n=e.font;return n?Hi[n]?t.withTextFontFamily(Hi[n]):Ui[n]?t.withTextFontWeight(Ui[n]):n===`\\emph`?t.fontShape===`textit`?t.withTextFontShape(`textup`):t.withTextFontShape(`textit`):t.withTextFontShape(Wi[n]):t};q({type:`text`,names:[`\\text`,`\\textrm`,`\\textsf`,`\\texttt`,`\\textnormal`,`\\textbf`,`\\textmd`,`\\textit`,`\\textup`,`\\emph`],props:{numArgs:1,argTypes:[`text`],allowedInArgument:!0,allowedInText:!0},handler(e,t){var{parser:n,funcName:r}=e,i=t[0];return{type:`text`,mode:n.mode,body:J(i),font:r}},htmlBuilder(e,t){var n=Gi(e,t);return W([`mord`,`text`],dn(e.body,n,!0),n)},mathmlBuilder(e,t){var n=Gi(e,t);return An(e.body,n)}}),q({type:`underline`,names:[`\\underline`],props:{numArgs:1,allowedInText:!0},handler(e,t){var{parser:n}=e;return{type:`underline`,mode:n.mode,body:t[0]}},htmlBuilder(e,t){var n=Y(e.body,t),r=Vt(`underline-line`,t),i=t.fontMetrics().defaultRuleThickness;return W([`mord`,`underline`],[G({positionType:`top`,positionData:n.height,children:[{type:`kern`,size:i},{type:`elem`,elem:r},{type:`kern`,size:3*i},{type:`elem`,elem:n}]})],t)},mathmlBuilder(e,t){var n=new X(`mo`,[new bn(`‾`)]);n.setAttribute(`stretchy`,`true`);var r=new X(`munder`,[Z(e.body,t),n]);return r.setAttribute(`accentunder`,`true`),r}}),q({type:`vcenter`,names:[`\\vcenter`],props:{numArgs:1,argTypes:[`original`],allowedInText:!1},handler(e,t){var{parser:n}=e;return{type:`vcenter`,mode:n.mode,body:t[0]}},htmlBuilder(e,t){var n=Y(e.body,t),r=t.fontMetrics().axisHeight;return G({positionType:`shift`,positionData:.5*(n.height-r-(n.depth+r)),children:[{type:`elem`,elem:n}]})},mathmlBuilder(e,t){return new X(`mrow`,[new X(`mpadded`,[Z(e.body,t)],[`vcenter`])])}}),q({type:`verb`,names:[`\\verb`],props:{numArgs:0,allowedInText:!0},handler(t,n,r){throw new e(`\\verb ended by end of line instead of matching delimiter`)},htmlBuilder(e,t){for(var n=Ki(e),r=[],i=t.havingStyle(t.style.text()),a=0;ae.body.replace(/ /g,e.star?`␣`:`\xA0`),qi=tn,Ji=`[ \r + ]`,Yi=`\\\\[a-zA-Z@]+`,Xi=`\\\\[^\ud800-\udfff]`,Zi=`(`+Yi+`)`+Ji+`*`,Qi=`\\\\( +|[ \r ]+ +?)[ \r ]*`,$i=`[̀-ͯ]`,ea=RegExp($i+`+$`),ta=`(`+Ji+`+)|`+(Qi+`|`)+`([!-\\[\\]-‧‪-퟿豈-￿]`+($i+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+($i+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+Zi)+(`|`+Xi+`)`),na=class{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(ta,`g`),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var t=this.input,n=this.tokenRegex.lastIndex;if(n===t.length)return new ri(`EOF`,new ni(this,n,n));var r=this.tokenRegex.exec(t);if(r===null||r.index!==n)throw new e(`Unexpected character: '`+t[n]+`'`,new ri(t[n],new ni(this,n,n+1)));var i=r[6]||r[3]||(r[2]?`\\ `:` `);if(this.catcodes[i]===14){var a=t.indexOf(` +`,this.tokenRegex.lastIndex);return a===-1?(this.tokenRegex.lastIndex=t.length,this.settings.reportNonstrict(`commentAtEnd`,`% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)`)):this.tokenRegex.lastIndex=a+1,this.lex()}return new ri(i,new ni(this,n,this.tokenRegex.lastIndex))}},ra=class{constructor(e,t){e===void 0&&(e={}),t===void 0&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new e(`Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug`);var t=this.undefStack.pop();for(var n in t)t.hasOwnProperty(n)&&(t[n]==null?delete this.current[n]:this.current[n]=t[n])}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return this.current.hasOwnProperty(e)||this.builtins.hasOwnProperty(e)}get(e){return this.current.hasOwnProperty(e)?this.current[e]:this.builtins[e]}set(e,t,n){if(n===void 0&&(n=!1),n){for(var r=0;r0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var i=this.undefStack[this.undefStack.length-1];i&&!i.hasOwnProperty(e)&&(i[e]=this.current[e])}t==null?delete this.current[e]:this.current[e]=t}},ia=ti;$(`\\noexpand`,function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),$(`\\expandafter`,function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),$(`\\@firstoftwo`,function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),$(`\\@secondoftwo`,function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),$(`\\@ifnextchar`,function(e){var t=e.consumeArgs(3);e.consumeSpaces();var n=e.future();return t[0].length===1&&t[0][0].text===n.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),$(`\\@ifstar`,`\\@ifnextchar *{\\@firstoftwo{#1}}`),$(`\\TextOrMath`,function(e){var t=e.consumeArgs(2);return e.mode===`text`?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var aa={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};$(`\\char`,function(t){var n=t.popToken(),r,i=0;if(n.text===`'`)r=8,n=t.popToken();else if(n.text===`"`)r=16,n=t.popToken();else if(n.text==="`")if(n=t.popToken(),n.text[0]===`\\`)i=n.text.charCodeAt(1);else if(n.text===`EOF`)throw new e("\\char` missing argument");else i=n.text.charCodeAt(0);else r=10;if(r){if(i=aa[n.text],i==null||i>=r)throw new e(`Invalid base-`+r+` digit `+n.text);for(var a;(a=aa[t.future().text])!=null&&a{var a=t.consumeArg().tokens;if(a.length!==1)throw new e(`\\newcommand's first argument must be a macro name`);var o=a[0].text,s=t.isDefined(o);if(s&&!n)throw new e(`\\newcommand{`+o+`} attempting to redefine `+(o+`; use \\renewcommand`));if(!s&&!r)throw new e(`\\renewcommand{`+o+`} when command `+o+` does not yet exist; use \\newcommand`);var c=0;if(a=t.consumeArg().tokens,a.length===1&&a[0].text===`[`){for(var l=``,u=t.expandNextToken();u.text!==`]`&&u.text!==`EOF`;)l+=u.text,u=t.expandNextToken();if(!l.match(/^\s*[0-9]+\s*$/))throw new e(`Invalid number of arguments: `+l);c=parseInt(l),a=t.consumeArg().tokens}return s&&i||t.macros.set(o,{tokens:a,numArgs:c}),``};$(`\\newcommand`,e=>oa(e,!1,!0,!1)),$(`\\renewcommand`,e=>oa(e,!0,!1,!1)),$(`\\providecommand`,e=>oa(e,!0,!0,!0)),$(`\\message`,e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join(``)),``}),$(`\\errmessage`,e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join(``)),``}),$(`\\show`,e=>{var t=e.popToken(),n=t.text;return console.log(t,e.macros.get(n),qi[n],A.math[n],A.text[n]),``}),$(`\\bgroup`,`{`),$(`\\egroup`,`}`),$(`~`,`\\nobreakspace`),$(`\\lq`,"`"),$(`\\rq`,`'`),$(`\\aa`,`\\r a`),$(`\\AA`,`\\r A`),$(`\\textcopyright`,"\\html@mathml{\\textcircled{c}}{\\char`©}"),$(`\\copyright`,`\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}`),$(`\\textregistered`,"\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),$(`ℬ`,`\\mathscr{B}`),$(`ℰ`,`\\mathscr{E}`),$(`ℱ`,`\\mathscr{F}`),$(`ℋ`,`\\mathscr{H}`),$(`ℐ`,`\\mathscr{I}`),$(`ℒ`,`\\mathscr{L}`),$(`ℳ`,`\\mathscr{M}`),$(`ℛ`,`\\mathscr{R}`),$(`ℭ`,`\\mathfrak{C}`),$(`ℌ`,`\\mathfrak{H}`),$(`ℨ`,`\\mathfrak{Z}`),$(`\\Bbbk`,`\\Bbb{k}`),$(`\\llap`,`\\mathllap{\\textrm{#1}}`),$(`\\rlap`,`\\mathrlap{\\textrm{#1}}`),$(`\\clap`,`\\mathclap{\\textrm{#1}}`),$(`\\mathstrut`,`\\vphantom{(}`),$(`\\underbar`,`\\underline{\\text{#1}}`),$(`\\not`,`\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}`),$(`\\neq`,"\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`≠}}"),$(`\\ne`,`\\neq`),$(`≠`,`\\neq`),$(`\\notin`,"\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`∉}}"),$(`∉`,`\\notin`),$(`≘`,"\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`≘}}"),$(`≙`,"\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`≘}}"),$(`≚`,"\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`≚}}"),$(`≛`,"\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`≛}}"),$(`≝`,"\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`≝}}"),$(`≞`,"\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`≞}}"),$(`≟`,"\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`≟}}"),$(`⟂`,`\\perp`),$(`‼`,`\\mathclose{!\\mkern-0.8mu!}`),$(`∌`,`\\notni`),$(`⌜`,`\\ulcorner`),$(`⌝`,`\\urcorner`),$(`⌞`,`\\llcorner`),$(`⌟`,`\\lrcorner`),$(`©`,`\\copyright`),$(`®`,`\\textregistered`),$(`\\ulcorner`,`\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}`),$(`\\urcorner`,`\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}`),$(`\\llcorner`,`\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}`),$(`\\lrcorner`,`\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}`),$(`\\vdots`,`{\\varvdots\\rule{0pt}{15pt}}`),$(`⋮`,`\\vdots`),$(`\\varGamma`,`\\mathit{\\Gamma}`),$(`\\varDelta`,`\\mathit{\\Delta}`),$(`\\varTheta`,`\\mathit{\\Theta}`),$(`\\varLambda`,`\\mathit{\\Lambda}`),$(`\\varXi`,`\\mathit{\\Xi}`),$(`\\varPi`,`\\mathit{\\Pi}`),$(`\\varSigma`,`\\mathit{\\Sigma}`),$(`\\varUpsilon`,`\\mathit{\\Upsilon}`),$(`\\varPhi`,`\\mathit{\\Phi}`),$(`\\varPsi`,`\\mathit{\\Psi}`),$(`\\varOmega`,`\\mathit{\\Omega}`),$(`\\substack`,`\\begin{subarray}{c}#1\\end{subarray}`),$(`\\colon`,`\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax`),$(`\\boxed`,`\\fbox{$\\displaystyle{#1}$}`),$(`\\iff`,`\\DOTSB\\;\\Longleftrightarrow\\;`),$(`\\implies`,`\\DOTSB\\;\\Longrightarrow\\;`),$(`\\impliedby`,`\\DOTSB\\;\\Longleftarrow\\;`),$(`\\dddot`,`{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}`),$(`\\ddddot`,`{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}`);var sa={",":`\\dotsc`,"\\not":`\\dotsb`,"+":`\\dotsb`,"=":`\\dotsb`,"<":`\\dotsb`,">":`\\dotsb`,"-":`\\dotsb`,"*":`\\dotsb`,":":`\\dotsb`,"\\DOTSB":`\\dotsb`,"\\coprod":`\\dotsb`,"\\bigvee":`\\dotsb`,"\\bigwedge":`\\dotsb`,"\\biguplus":`\\dotsb`,"\\bigcap":`\\dotsb`,"\\bigcup":`\\dotsb`,"\\prod":`\\dotsb`,"\\sum":`\\dotsb`,"\\bigotimes":`\\dotsb`,"\\bigoplus":`\\dotsb`,"\\bigodot":`\\dotsb`,"\\bigsqcup":`\\dotsb`,"\\And":`\\dotsb`,"\\longrightarrow":`\\dotsb`,"\\Longrightarrow":`\\dotsb`,"\\longleftarrow":`\\dotsb`,"\\Longleftarrow":`\\dotsb`,"\\longleftrightarrow":`\\dotsb`,"\\Longleftrightarrow":`\\dotsb`,"\\mapsto":`\\dotsb`,"\\longmapsto":`\\dotsb`,"\\hookrightarrow":`\\dotsb`,"\\doteq":`\\dotsb`,"\\mathbin":`\\dotsb`,"\\mathrel":`\\dotsb`,"\\relbar":`\\dotsb`,"\\Relbar":`\\dotsb`,"\\xrightarrow":`\\dotsb`,"\\xleftarrow":`\\dotsb`,"\\DOTSI":`\\dotsi`,"\\int":`\\dotsi`,"\\oint":`\\dotsi`,"\\iint":`\\dotsi`,"\\iiint":`\\dotsi`,"\\iiiint":`\\dotsi`,"\\idotsint":`\\dotsi`,"\\DOTSX":`\\dotsx`},ca=new Set([`bin`,`rel`]);$(`\\dots`,function(e){var t=`\\dotso`,n=e.expandAfterFuture().text;return n in sa?t=sa[n]:(n.slice(0,4)===`\\not`||n in A.math&&ca.has(A.math[n].group))&&(t=`\\dotsb`),t});var la={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};$(`\\dotso`,function(e){return e.future().text in la?`\\ldots\\,`:`\\ldots`}),$(`\\dotsc`,function(e){var t=e.future().text;return t in la&&t!==`,`?`\\ldots\\,`:`\\ldots`}),$(`\\cdots`,function(e){return e.future().text in la?`\\@cdots\\,`:`\\@cdots`}),$(`\\dotsb`,`\\cdots`),$(`\\dotsm`,`\\cdots`),$(`\\dotsi`,`\\!\\cdots`),$(`\\dotsx`,`\\ldots\\,`),$(`\\DOTSI`,`\\relax`),$(`\\DOTSB`,`\\relax`),$(`\\DOTSX`,`\\relax`),$(`\\tmspace`,`\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax`),$(`\\,`,`\\tmspace+{3mu}{.1667em}`),$(`\\thinspace`,`\\,`),$(`\\>`,`\\mskip{4mu}`),$(`\\:`,`\\tmspace+{4mu}{.2222em}`),$(`\\medspace`,`\\:`),$(`\\;`,`\\tmspace+{5mu}{.2777em}`),$(`\\thickspace`,`\\;`),$(`\\!`,`\\tmspace-{3mu}{.1667em}`),$(`\\negthinspace`,`\\!`),$(`\\negmedspace`,`\\tmspace-{4mu}{.2222em}`),$(`\\negthickspace`,`\\tmspace-{5mu}{.277em}`),$(`\\enspace`,`\\kern.5em `),$(`\\enskip`,`\\hskip.5em\\relax`),$(`\\quad`,`\\hskip1em\\relax`),$(`\\qquad`,`\\hskip2em\\relax`),$(`\\tag`,`\\@ifstar\\tag@literal\\tag@paren`),$(`\\tag@paren`,`\\tag@literal{({#1})}`),$(`\\tag@literal`,t=>{if(t.macros.get(`\\df@tag`))throw new e(`Multiple \\tag`);return`\\gdef\\df@tag{\\text{#1}}`}),$(`\\bmod`,`\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}`),$(`\\pod`,`\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)`),$(`\\pmod`,`\\pod{{\\rm mod}\\mkern6mu#1}`),$(`\\mod`,`\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1`),$(`\\newline`,`\\\\\\relax`),$(`\\TeX`,`\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}`);var ua=k(Ue[`Main-Regular`][84][1]-.7*Ue[`Main-Regular`][65][1]);$(`\\LaTeX`,`\\textrm{\\html@mathml{`+(`L\\kern-.36em\\raisebox{`+ua+`}{\\scriptstyle A}`)+`\\kern-.15em\\TeX}{LaTeX}}`),$(`\\KaTeX`,`\\textrm{\\html@mathml{`+(`K\\kern-.17em\\raisebox{`+ua+`}{\\scriptstyle A}`)+`\\kern-.15em\\TeX}{KaTeX}}`),$(`\\hspace`,`\\@ifstar\\@hspacer\\@hspace`),$(`\\@hspace`,`\\hskip #1\\relax`),$(`\\@hspacer`,`\\rule{0pt}{0pt}\\hskip #1\\relax`),$(`\\ordinarycolon`,`:`),$(`\\vcentcolon`,`\\mathrel{\\mathop\\ordinarycolon}`),$(`\\dblcolon`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}`),$(`\\coloneqq`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}`),$(`\\Coloneqq`,`\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}`),$(`\\coloneq`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}`),$(`\\Coloneq`,`\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}`),$(`\\eqqcolon`,`\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}`),$(`\\Eqqcolon`,`\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}`),$(`\\eqcolon`,`\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}`),$(`\\Eqcolon`,`\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}`),$(`\\colonapprox`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}`),$(`\\Colonapprox`,`\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}`),$(`\\colonsim`,`\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}`),$(`\\Colonsim`,`\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}`),$(`∷`,`\\dblcolon`),$(`∹`,`\\eqcolon`),$(`≔`,`\\coloneqq`),$(`≕`,`\\eqqcolon`),$(`⩴`,`\\Coloneqq`),$(`\\ratio`,`\\vcentcolon`),$(`\\coloncolon`,`\\dblcolon`),$(`\\colonequals`,`\\coloneqq`),$(`\\coloncolonequals`,`\\Coloneqq`),$(`\\equalscolon`,`\\eqqcolon`),$(`\\equalscoloncolon`,`\\Eqqcolon`),$(`\\colonminus`,`\\coloneq`),$(`\\coloncolonminus`,`\\Coloneq`),$(`\\minuscolon`,`\\eqcolon`),$(`\\minuscoloncolon`,`\\Eqcolon`),$(`\\coloncolonapprox`,`\\Colonapprox`),$(`\\coloncolonsim`,`\\Colonsim`),$(`\\simcolon`,`\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}`),$(`\\simcoloncolon`,`\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}`),$(`\\approxcolon`,`\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}`),$(`\\approxcoloncolon`,`\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}`),$(`\\notni`,"\\html@mathml{\\not\\ni}{\\mathrel{\\char`∌}}"),$(`\\limsup`,`\\DOTSB\\operatorname*{lim\\,sup}`),$(`\\liminf`,`\\DOTSB\\operatorname*{lim\\,inf}`),$(`\\injlim`,`\\DOTSB\\operatorname*{inj\\,lim}`),$(`\\projlim`,`\\DOTSB\\operatorname*{proj\\,lim}`),$(`\\varlimsup`,`\\DOTSB\\operatorname*{\\overline{lim}}`),$(`\\varliminf`,`\\DOTSB\\operatorname*{\\underline{lim}}`),$(`\\varinjlim`,`\\DOTSB\\operatorname*{\\underrightarrow{lim}}`),$(`\\varprojlim`,`\\DOTSB\\operatorname*{\\underleftarrow{lim}}`),$(`\\gvertneqq`,`\\html@mathml{\\@gvertneqq}{≩}`),$(`\\lvertneqq`,`\\html@mathml{\\@lvertneqq}{≨}`),$(`\\ngeqq`,`\\html@mathml{\\@ngeqq}{≱}`),$(`\\ngeqslant`,`\\html@mathml{\\@ngeqslant}{≱}`),$(`\\nleqq`,`\\html@mathml{\\@nleqq}{≰}`),$(`\\nleqslant`,`\\html@mathml{\\@nleqslant}{≰}`),$(`\\nshortmid`,`\\html@mathml{\\@nshortmid}{∤}`),$(`\\nshortparallel`,`\\html@mathml{\\@nshortparallel}{∦}`),$(`\\nsubseteqq`,`\\html@mathml{\\@nsubseteqq}{⊈}`),$(`\\nsupseteqq`,`\\html@mathml{\\@nsupseteqq}{⊉}`),$(`\\varsubsetneq`,`\\html@mathml{\\@varsubsetneq}{⊊}`),$(`\\varsubsetneqq`,`\\html@mathml{\\@varsubsetneqq}{⫋}`),$(`\\varsupsetneq`,`\\html@mathml{\\@varsupsetneq}{⊋}`),$(`\\varsupsetneqq`,`\\html@mathml{\\@varsupsetneqq}{⫌}`),$(`\\imath`,`\\html@mathml{\\@imath}{ı}`),$(`\\jmath`,`\\html@mathml{\\@jmath}{ȷ}`),$(`\\llbracket`,"\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`⟦}}"),$(`\\rrbracket`,"\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`⟧}}"),$(`⟦`,`\\llbracket`),$(`⟧`,`\\rrbracket`),$(`\\lBrace`,"\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`⦃}}"),$(`\\rBrace`,"\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`⦄}}"),$(`⦃`,`\\lBrace`),$(`⦄`,`\\rBrace`),$(`\\minuso`,"\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`⦵}}"),$(`⦵`,`\\minuso`),$(`\\darr`,`\\downarrow`),$(`\\dArr`,`\\Downarrow`),$(`\\Darr`,`\\Downarrow`),$(`\\lang`,`\\langle`),$(`\\rang`,`\\rangle`),$(`\\uarr`,`\\uparrow`),$(`\\uArr`,`\\Uparrow`),$(`\\Uarr`,`\\Uparrow`),$(`\\N`,`\\mathbb{N}`),$(`\\R`,`\\mathbb{R}`),$(`\\Z`,`\\mathbb{Z}`),$(`\\alef`,`\\aleph`),$(`\\alefsym`,`\\aleph`),$(`\\Alpha`,`\\mathrm{A}`),$(`\\Beta`,`\\mathrm{B}`),$(`\\bull`,`\\bullet`),$(`\\Chi`,`\\mathrm{X}`),$(`\\clubs`,`\\clubsuit`),$(`\\cnums`,`\\mathbb{C}`),$(`\\Complex`,`\\mathbb{C}`),$(`\\Dagger`,`\\ddagger`),$(`\\diamonds`,`\\diamondsuit`),$(`\\empty`,`\\emptyset`),$(`\\Epsilon`,`\\mathrm{E}`),$(`\\Eta`,`\\mathrm{H}`),$(`\\exist`,`\\exists`),$(`\\harr`,`\\leftrightarrow`),$(`\\hArr`,`\\Leftrightarrow`),$(`\\Harr`,`\\Leftrightarrow`),$(`\\hearts`,`\\heartsuit`),$(`\\image`,`\\Im`),$(`\\infin`,`\\infty`),$(`\\Iota`,`\\mathrm{I}`),$(`\\isin`,`\\in`),$(`\\Kappa`,`\\mathrm{K}`),$(`\\larr`,`\\leftarrow`),$(`\\lArr`,`\\Leftarrow`),$(`\\Larr`,`\\Leftarrow`),$(`\\lrarr`,`\\leftrightarrow`),$(`\\lrArr`,`\\Leftrightarrow`),$(`\\Lrarr`,`\\Leftrightarrow`),$(`\\Mu`,`\\mathrm{M}`),$(`\\natnums`,`\\mathbb{N}`),$(`\\Nu`,`\\mathrm{N}`),$(`\\Omicron`,`\\mathrm{O}`),$(`\\plusmn`,`\\pm`),$(`\\rarr`,`\\rightarrow`),$(`\\rArr`,`\\Rightarrow`),$(`\\Rarr`,`\\Rightarrow`),$(`\\real`,`\\Re`),$(`\\reals`,`\\mathbb{R}`),$(`\\Reals`,`\\mathbb{R}`),$(`\\Rho`,`\\mathrm{P}`),$(`\\sdot`,`\\cdot`),$(`\\sect`,`\\S`),$(`\\spades`,`\\spadesuit`),$(`\\sub`,`\\subset`),$(`\\sube`,`\\subseteq`),$(`\\supe`,`\\supseteq`),$(`\\Tau`,`\\mathrm{T}`),$(`\\thetasym`,`\\vartheta`),$(`\\weierp`,`\\wp`),$(`\\Zeta`,`\\mathrm{Z}`),$(`\\argmin`,`\\DOTSB\\operatorname*{arg\\,min}`),$(`\\argmax`,`\\DOTSB\\operatorname*{arg\\,max}`),$(`\\plim`,`\\DOTSB\\mathop{\\operatorname{plim}}\\limits`),$(`\\bra`,`\\mathinner{\\langle{#1}|}`),$(`\\ket`,`\\mathinner{|{#1}\\rangle}`),$(`\\braket`,`\\mathinner{\\langle{#1}\\rangle}`),$(`\\Bra`,`\\left\\langle#1\\right|`),$(`\\Ket`,`\\left|#1\\right\\rangle`);var da=e=>t=>{var n=t.consumeArg().tokens,r=t.consumeArg().tokens,i=t.consumeArg().tokens,a=t.consumeArg().tokens,o=t.macros.get(`|`),s=t.macros.get(`\\|`);t.macros.beginGroup();var c=t=>n=>{e&&(n.macros.set(`|`,o),i.length&&n.macros.set(`\\|`,s));var a=t;return!t&&i.length&&n.future().text===`|`&&(n.popToken(),a=!0),{tokens:a?i:r,numArgs:0}};t.macros.set(`|`,c(!1)),i.length&&t.macros.set(`\\|`,c(!0));var l=t.consumeArg().tokens,u=t.expandTokens([...a,...l,...n]);return t.macros.endGroup(),{tokens:u.reverse(),numArgs:0}};$(`\\bra@ket`,da(!1)),$(`\\bra@set`,da(!0)),$(`\\Braket`,`\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}`),$(`\\Set`,`\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}`),$(`\\set`,`\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}`),$(`\\angln`,`{\\angl n}`),$(`\\blue`,`\\textcolor{##6495ed}{#1}`),$(`\\orange`,`\\textcolor{##ffa500}{#1}`),$(`\\pink`,`\\textcolor{##ff00af}{#1}`),$(`\\red`,`\\textcolor{##df0030}{#1}`),$(`\\green`,`\\textcolor{##28ae7b}{#1}`),$(`\\gray`,`\\textcolor{gray}{#1}`),$(`\\purple`,`\\textcolor{##9d38bd}{#1}`),$(`\\blueA`,`\\textcolor{##ccfaff}{#1}`),$(`\\blueB`,`\\textcolor{##80f6ff}{#1}`),$(`\\blueC`,`\\textcolor{##63d9ea}{#1}`),$(`\\blueD`,`\\textcolor{##11accd}{#1}`),$(`\\blueE`,`\\textcolor{##0c7f99}{#1}`),$(`\\tealA`,`\\textcolor{##94fff5}{#1}`),$(`\\tealB`,`\\textcolor{##26edd5}{#1}`),$(`\\tealC`,`\\textcolor{##01d1c1}{#1}`),$(`\\tealD`,`\\textcolor{##01a995}{#1}`),$(`\\tealE`,`\\textcolor{##208170}{#1}`),$(`\\greenA`,`\\textcolor{##b6ffb0}{#1}`),$(`\\greenB`,`\\textcolor{##8af281}{#1}`),$(`\\greenC`,`\\textcolor{##74cf70}{#1}`),$(`\\greenD`,`\\textcolor{##1fab54}{#1}`),$(`\\greenE`,`\\textcolor{##0d923f}{#1}`),$(`\\goldA`,`\\textcolor{##ffd0a9}{#1}`),$(`\\goldB`,`\\textcolor{##ffbb71}{#1}`),$(`\\goldC`,`\\textcolor{##ff9c39}{#1}`),$(`\\goldD`,`\\textcolor{##e07d10}{#1}`),$(`\\goldE`,`\\textcolor{##a75a05}{#1}`),$(`\\redA`,`\\textcolor{##fca9a9}{#1}`),$(`\\redB`,`\\textcolor{##ff8482}{#1}`),$(`\\redC`,`\\textcolor{##f9685d}{#1}`),$(`\\redD`,`\\textcolor{##e84d39}{#1}`),$(`\\redE`,`\\textcolor{##bc2612}{#1}`),$(`\\maroonA`,`\\textcolor{##ffbde0}{#1}`),$(`\\maroonB`,`\\textcolor{##ff92c6}{#1}`),$(`\\maroonC`,`\\textcolor{##ed5fa6}{#1}`),$(`\\maroonD`,`\\textcolor{##ca337c}{#1}`),$(`\\maroonE`,`\\textcolor{##9e034e}{#1}`),$(`\\purpleA`,`\\textcolor{##ddd7ff}{#1}`),$(`\\purpleB`,`\\textcolor{##c6b9fc}{#1}`),$(`\\purpleC`,`\\textcolor{##aa87ff}{#1}`),$(`\\purpleD`,`\\textcolor{##7854ab}{#1}`),$(`\\purpleE`,`\\textcolor{##543b78}{#1}`),$(`\\mintA`,`\\textcolor{##f5f9e8}{#1}`),$(`\\mintB`,`\\textcolor{##edf2df}{#1}`),$(`\\mintC`,`\\textcolor{##e0e5cc}{#1}`),$(`\\grayA`,`\\textcolor{##f6f7f7}{#1}`),$(`\\grayB`,`\\textcolor{##f0f1f2}{#1}`),$(`\\grayC`,`\\textcolor{##e3e5e6}{#1}`),$(`\\grayD`,`\\textcolor{##d6d8da}{#1}`),$(`\\grayE`,`\\textcolor{##babec2}{#1}`),$(`\\grayF`,`\\textcolor{##888d93}{#1}`),$(`\\grayG`,`\\textcolor{##626569}{#1}`),$(`\\grayH`,`\\textcolor{##3b3e40}{#1}`),$(`\\grayI`,`\\textcolor{##21242c}{#1}`),$(`\\kaBlue`,`\\textcolor{##314453}{#1}`),$(`\\kaGreen`,`\\textcolor{##71B307}{#1}`);var fa={"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0},pa=class{constructor(e,t,n){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=t,this.expansionCount=0,this.feed(e),this.macros=new ra(ia,t.macros),this.mode=n,this.stack=[]}feed(e){this.lexer=new na(e,this.settings)}switchMode(e){this.mode=e}beginGroup(){this.macros.beginGroup()}endGroup(){this.macros.endGroup()}endGroups(){this.macros.endGroups()}future(){return this.stack.length===0&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]}popToken(){return this.future(),this.stack.pop()}pushToken(e){this.stack.push(e)}pushTokens(e){this.stack.push(...e)}scanArgument(e){var t,n,r;if(e){if(this.consumeSpaces(),this.future().text!==`[`)return null;t=this.popToken(),{tokens:r,end:n}=this.consumeArg([`]`])}else({tokens:r,start:t,end:n}=this.consumeArg());return this.pushToken(new ri(`EOF`,n.loc)),this.pushTokens(r),new ri(``,ni.range(t,n))}consumeSpaces(){for(;this.future().text===` `;)this.stack.pop()}consumeArg(t){var n=[],r=t&&t.length>0;r||this.consumeSpaces();var i=this.future(),a,o=0,s=0;do{if(a=this.popToken(),n.push(a),a.text===`{`)++o;else if(a.text===`}`){if(--o,o===-1)throw new e(`Extra }`,a)}else if(a.text===`EOF`)throw new e(`Unexpected end of input in a macro argument, expected '`+(t&&r?t[s]:`}`)+`'`,a);if(t&&r)if((o===0||o===1&&t[s]===`{`)&&a.text===t[s]){if(++s,s===t.length){n.splice(-s,s);break}}else s=0}while(o!==0||r);return i.text===`{`&&n[n.length-1].text===`}`&&(n.pop(),n.shift()),n.reverse(),{tokens:n,start:i,end:a}}consumeArgs(t,n){if(n){if(n.length!==t+1)throw new e(`The length of delimiters doesn't match the number of args!`);for(var r=n[0],i=0;ithis.settings.maxExpand)throw new e(`Too many expansions: infinite loop or need to increase maxExpand setting`)}expandOnce(t){var n=this.popToken(),r=n.text,i=n.noexpand?null:this._getExpansion(r);if(i==null||t&&i.unexpandable){if(t&&i==null&&r[0]===`\\`&&!this.isDefined(r))throw new e(`Undefined control sequence: `+r);return this.pushToken(n),!1}this.countExpansion(1);var a=i.tokens,o=this.consumeArgs(i.numArgs,i.delimiters);if(i.numArgs){a=a.slice();for(var s=a.length-1;s>=0;--s){var c=a[s];if(c.text===`#`){if(s===0)throw new e(`Incomplete placeholder at end of macro body`,c);if(c=a[--s],c.text===`#`)a.splice(s+1,1);else if(/^[1-9]$/.test(c.text))a.splice(s,2,...o[c.text-1]);else throw new e(`Not a valid argument number`,c)}}}return this.pushTokens(a),a.length}expandAfterFuture(){return this.expandOnce(),this.future()}expandNextToken(){for(;;)if(this.expandOnce()===!1){var e=this.stack.pop();return e.treatAsRelax&&(e.text=`\\relax`),e}}expandMacro(e){return this.macros.has(e)?this.expandTokens([new ri(e)]):void 0}expandTokens(e){var t=[],n=this.stack.length;for(this.pushTokens(e);this.stack.length>n;)if(this.expandOnce(!0)===!1){var r=this.stack.pop();r.treatAsRelax&&=(r.noexpand=!1,!1),t.push(r)}return this.countExpansion(t.length),t}expandMacroAsText(e){var t=this.expandMacro(e);return t&&t.map(e=>e.text).join(``)}_getExpansion(e){var t=this.macros.get(e);if(t==null)return t;if(e.length===1){var n=this.lexer.catcodes[e];if(n!=null&&n!==13)return}var r=typeof t==`function`?t(this):t;if(typeof r==`string`){var i=0;if(r.includes(`#`))for(var a=r.replace(/##/g,``);a.includes(`#`+(i+1));)++i;for(var o=new na(r,this.settings),s=[],c=o.lex();c.text!==`EOF`;)s.push(c),c=o.lex();return s.reverse(),{tokens:s,numArgs:i}}return r}isDefined(e){return this.macros.has(e)||qi.hasOwnProperty(e)||A.math.hasOwnProperty(e)||A.text.hasOwnProperty(e)||fa.hasOwnProperty(e)}isExpandable(e){var t=this.macros.get(e);return t==null?qi.hasOwnProperty(e)&&!qi[e].primitive:typeof t==`string`||typeof t==`function`||!t.unexpandable}},ma=/^[₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ]/,ha=Object.freeze({"₊":`+`,"₋":`-`,"₌":`=`,"₍":`(`,"₎":`)`,"₀":`0`,"₁":`1`,"₂":`2`,"₃":`3`,"₄":`4`,"₅":`5`,"₆":`6`,"₇":`7`,"₈":`8`,"₉":`9`,ₐ:`a`,ₑ:`e`,ₕ:`h`,ᵢ:`i`,ⱼ:`j`,ₖ:`k`,ₗ:`l`,ₘ:`m`,ₙ:`n`,ₒ:`o`,ₚ:`p`,ᵣ:`r`,ₛ:`s`,ₜ:`t`,ᵤ:`u`,ᵥ:`v`,ₓ:`x`,ᵦ:`β`,ᵧ:`γ`,ᵨ:`ρ`,ᵩ:`ϕ`,ᵪ:`χ`,"⁺":`+`,"⁻":`-`,"⁼":`=`,"⁽":`(`,"⁾":`)`,"⁰":`0`,"¹":`1`,"²":`2`,"³":`3`,"⁴":`4`,"⁵":`5`,"⁶":`6`,"⁷":`7`,"⁸":`8`,"⁹":`9`,ᴬ:`A`,ᴮ:`B`,ᴰ:`D`,ᴱ:`E`,ᴳ:`G`,ᴴ:`H`,ᴵ:`I`,ᴶ:`J`,ᴷ:`K`,ᴸ:`L`,ᴹ:`M`,ᴺ:`N`,ᴼ:`O`,ᴾ:`P`,ᴿ:`R`,ᵀ:`T`,ᵁ:`U`,ⱽ:`V`,ᵂ:`W`,ᵃ:`a`,ᵇ:`b`,ᶜ:`c`,ᵈ:`d`,ᵉ:`e`,ᶠ:`f`,ᵍ:`g`,ʰ:`h`,ⁱ:`i`,ʲ:`j`,ᵏ:`k`,ˡ:`l`,ᵐ:`m`,ⁿ:`n`,ᵒ:`o`,ᵖ:`p`,ʳ:`r`,ˢ:`s`,ᵗ:`t`,ᵘ:`u`,ᵛ:`v`,ʷ:`w`,ˣ:`x`,ʸ:`y`,ᶻ:`z`,ᵝ:`β`,ᵞ:`γ`,ᵟ:`δ`,ᵠ:`ϕ`,ᵡ:`χ`,ᶿ:`θ`}),ga={"́":{text:`\\'`,math:`\\acute`},"̀":{text:"\\`",math:`\\grave`},"̈":{text:`\\"`,math:`\\ddot`},"̃":{text:`\\~`,math:`\\tilde`},"̄":{text:`\\=`,math:`\\bar`},"̆":{text:`\\u`,math:`\\breve`},"̌":{text:`\\v`,math:`\\check`},"̂":{text:`\\^`,math:`\\hat`},"̇":{text:`\\.`,math:`\\dot`},"̊":{text:`\\r`,math:`\\mathring`},"̋":{text:`\\H`},"̧":{text:`\\c`}},_a={á:`á`,à:`à`,ä:`ä`,ǟ:`ǟ`,ã:`ã`,ā:`ā`,ă:`ă`,ắ:`ắ`,ằ:`ằ`,ẵ:`ẵ`,ǎ:`ǎ`,â:`â`,ấ:`ấ`,ầ:`ầ`,ẫ:`ẫ`,ȧ:`ȧ`,ǡ:`ǡ`,å:`å`,ǻ:`ǻ`,ḃ:`ḃ`,ć:`ć`,ḉ:`ḉ`,č:`č`,ĉ:`ĉ`,ċ:`ċ`,ç:`ç`,ď:`ď`,ḋ:`ḋ`,ḑ:`ḑ`,é:`é`,è:`è`,ë:`ë`,ẽ:`ẽ`,ē:`ē`,ḗ:`ḗ`,ḕ:`ḕ`,ĕ:`ĕ`,ḝ:`ḝ`,ě:`ě`,ê:`ê`,ế:`ế`,ề:`ề`,ễ:`ễ`,ė:`ė`,ȩ:`ȩ`,ḟ:`ḟ`,ǵ:`ǵ`,ḡ:`ḡ`,ğ:`ğ`,ǧ:`ǧ`,ĝ:`ĝ`,ġ:`ġ`,ģ:`ģ`,ḧ:`ḧ`,ȟ:`ȟ`,ĥ:`ĥ`,ḣ:`ḣ`,ḩ:`ḩ`,í:`í`,ì:`ì`,ï:`ï`,ḯ:`ḯ`,ĩ:`ĩ`,ī:`ī`,ĭ:`ĭ`,ǐ:`ǐ`,î:`î`,ǰ:`ǰ`,ĵ:`ĵ`,ḱ:`ḱ`,ǩ:`ǩ`,ķ:`ķ`,ĺ:`ĺ`,ľ:`ľ`,ļ:`ļ`,ḿ:`ḿ`,ṁ:`ṁ`,ń:`ń`,ǹ:`ǹ`,ñ:`ñ`,ň:`ň`,ṅ:`ṅ`,ņ:`ņ`,ó:`ó`,ò:`ò`,ö:`ö`,ȫ:`ȫ`,õ:`õ`,ṍ:`ṍ`,ṏ:`ṏ`,ȭ:`ȭ`,ō:`ō`,ṓ:`ṓ`,ṑ:`ṑ`,ŏ:`ŏ`,ǒ:`ǒ`,ô:`ô`,ố:`ố`,ồ:`ồ`,ỗ:`ỗ`,ȯ:`ȯ`,ȱ:`ȱ`,ő:`ő`,ṕ:`ṕ`,ṗ:`ṗ`,ŕ:`ŕ`,ř:`ř`,ṙ:`ṙ`,ŗ:`ŗ`,ś:`ś`,ṥ:`ṥ`,š:`š`,ṧ:`ṧ`,ŝ:`ŝ`,ṡ:`ṡ`,ş:`ş`,ẗ:`ẗ`,ť:`ť`,ṫ:`ṫ`,ţ:`ţ`,ú:`ú`,ù:`ù`,ü:`ü`,ǘ:`ǘ`,ǜ:`ǜ`,ǖ:`ǖ`,ǚ:`ǚ`,ũ:`ũ`,ṹ:`ṹ`,ū:`ū`,ṻ:`ṻ`,ŭ:`ŭ`,ǔ:`ǔ`,û:`û`,ů:`ů`,ű:`ű`,ṽ:`ṽ`,ẃ:`ẃ`,ẁ:`ẁ`,ẅ:`ẅ`,ŵ:`ŵ`,ẇ:`ẇ`,ẘ:`ẘ`,ẍ:`ẍ`,ẋ:`ẋ`,ý:`ý`,ỳ:`ỳ`,ÿ:`ÿ`,ỹ:`ỹ`,ȳ:`ȳ`,ŷ:`ŷ`,ẏ:`ẏ`,ẙ:`ẙ`,ź:`ź`,ž:`ž`,ẑ:`ẑ`,ż:`ż`,Á:`Á`,À:`À`,Ä:`Ä`,Ǟ:`Ǟ`,Ã:`Ã`,Ā:`Ā`,Ă:`Ă`,Ắ:`Ắ`,Ằ:`Ằ`,Ẵ:`Ẵ`,Ǎ:`Ǎ`,Â:`Â`,Ấ:`Ấ`,Ầ:`Ầ`,Ẫ:`Ẫ`,Ȧ:`Ȧ`,Ǡ:`Ǡ`,Å:`Å`,Ǻ:`Ǻ`,Ḃ:`Ḃ`,Ć:`Ć`,Ḉ:`Ḉ`,Č:`Č`,Ĉ:`Ĉ`,Ċ:`Ċ`,Ç:`Ç`,Ď:`Ď`,Ḋ:`Ḋ`,Ḑ:`Ḑ`,É:`É`,È:`È`,Ë:`Ë`,Ẽ:`Ẽ`,Ē:`Ē`,Ḗ:`Ḗ`,Ḕ:`Ḕ`,Ĕ:`Ĕ`,Ḝ:`Ḝ`,Ě:`Ě`,Ê:`Ê`,Ế:`Ế`,Ề:`Ề`,Ễ:`Ễ`,Ė:`Ė`,Ȩ:`Ȩ`,Ḟ:`Ḟ`,Ǵ:`Ǵ`,Ḡ:`Ḡ`,Ğ:`Ğ`,Ǧ:`Ǧ`,Ĝ:`Ĝ`,Ġ:`Ġ`,Ģ:`Ģ`,Ḧ:`Ḧ`,Ȟ:`Ȟ`,Ĥ:`Ĥ`,Ḣ:`Ḣ`,Ḩ:`Ḩ`,Í:`Í`,Ì:`Ì`,Ï:`Ï`,Ḯ:`Ḯ`,Ĩ:`Ĩ`,Ī:`Ī`,Ĭ:`Ĭ`,Ǐ:`Ǐ`,Î:`Î`,İ:`İ`,Ĵ:`Ĵ`,Ḱ:`Ḱ`,Ǩ:`Ǩ`,Ķ:`Ķ`,Ĺ:`Ĺ`,Ľ:`Ľ`,Ļ:`Ļ`,Ḿ:`Ḿ`,Ṁ:`Ṁ`,Ń:`Ń`,Ǹ:`Ǹ`,Ñ:`Ñ`,Ň:`Ň`,Ṅ:`Ṅ`,Ņ:`Ņ`,Ó:`Ó`,Ò:`Ò`,Ö:`Ö`,Ȫ:`Ȫ`,Õ:`Õ`,Ṍ:`Ṍ`,Ṏ:`Ṏ`,Ȭ:`Ȭ`,Ō:`Ō`,Ṓ:`Ṓ`,Ṑ:`Ṑ`,Ŏ:`Ŏ`,Ǒ:`Ǒ`,Ô:`Ô`,Ố:`Ố`,Ồ:`Ồ`,Ỗ:`Ỗ`,Ȯ:`Ȯ`,Ȱ:`Ȱ`,Ő:`Ő`,Ṕ:`Ṕ`,Ṗ:`Ṗ`,Ŕ:`Ŕ`,Ř:`Ř`,Ṙ:`Ṙ`,Ŗ:`Ŗ`,Ś:`Ś`,Ṥ:`Ṥ`,Š:`Š`,Ṧ:`Ṧ`,Ŝ:`Ŝ`,Ṡ:`Ṡ`,Ş:`Ş`,Ť:`Ť`,Ṫ:`Ṫ`,Ţ:`Ţ`,Ú:`Ú`,Ù:`Ù`,Ü:`Ü`,Ǘ:`Ǘ`,Ǜ:`Ǜ`,Ǖ:`Ǖ`,Ǚ:`Ǚ`,Ũ:`Ũ`,Ṹ:`Ṹ`,Ū:`Ū`,Ṻ:`Ṻ`,Ŭ:`Ŭ`,Ǔ:`Ǔ`,Û:`Û`,Ů:`Ů`,Ű:`Ű`,Ṽ:`Ṽ`,Ẃ:`Ẃ`,Ẁ:`Ẁ`,Ẅ:`Ẅ`,Ŵ:`Ŵ`,Ẇ:`Ẇ`,Ẍ:`Ẍ`,Ẋ:`Ẋ`,Ý:`Ý`,Ỳ:`Ỳ`,Ÿ:`Ÿ`,Ỹ:`Ỹ`,Ȳ:`Ȳ`,Ŷ:`Ŷ`,Ẏ:`Ẏ`,Ź:`Ź`,Ž:`Ž`,Ẑ:`Ẑ`,Ż:`Ż`,ά:`ά`,ὰ:`ὰ`,ᾱ:`ᾱ`,ᾰ:`ᾰ`,έ:`έ`,ὲ:`ὲ`,ή:`ή`,ὴ:`ὴ`,ί:`ί`,ὶ:`ὶ`,ϊ:`ϊ`,ΐ:`ΐ`,ῒ:`ῒ`,ῑ:`ῑ`,ῐ:`ῐ`,ό:`ό`,ὸ:`ὸ`,ύ:`ύ`,ὺ:`ὺ`,ϋ:`ϋ`,ΰ:`ΰ`,ῢ:`ῢ`,ῡ:`ῡ`,ῠ:`ῠ`,ώ:`ώ`,ὼ:`ὼ`,Ύ:`Ύ`,Ὺ:`Ὺ`,Ϋ:`Ϋ`,Ῡ:`Ῡ`,Ῠ:`Ῠ`,Ώ:`Ώ`,Ὼ:`Ὼ`},va=class t{constructor(e,t){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode=`math`,this.gullet=new pa(e,t,this.mode),this.settings=t,this.leftrightDepth=0,this.nextToken=null}expect(t,n){if(n===void 0&&(n=!0),this.fetch().text!==t)throw new e(`Expected '`+t+`', got '`+this.fetch().text+`'`,this.fetch());n&&this.consume()}consume(){this.nextToken=null}fetch(){return this.nextToken??=this.gullet.expandNextToken(),this.nextToken}switchMode(e){this.mode=e,this.gullet.switchMode(e)}parse(){this.settings.globalGroup||this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set(`\\color`,`\\textcolor`);try{var e=this.parseExpression(!1);return this.expect(`EOF`),this.settings.globalGroup||this.gullet.endGroup(),e}finally{this.gullet.endGroups()}}subparse(e){var t=this.nextToken;this.consume(),this.gullet.pushToken(new ri(`}`)),this.gullet.pushTokens(e);var n=this.parseExpression(!1);return this.expect(`}`),this.nextToken=t,n}parseExpression(e,n){for(var r=[];;){this.mode===`math`&&this.consumeSpaces();var i=this.fetch();if(t.endOfExpression.has(i.text)||n&&i.text===n||e&&qi[i.text]&&qi[i.text].infix)break;var a=this.parseAtom(n);if(!a)break;a.type!==`internal`&&r.push(a)}return this.mode===`text`&&this.formLigatures(r),this.handleInfixNodes(r)}handleInfixNodes(t){for(var n=-1,r,i=0;i=128)this.settings.strict&&(ce(n.charCodeAt(0))?this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Unicode text character "`+n[0]+`" used in math mode`,t):this.settings.reportNonstrict(`unknownSymbol`,`Unrecognized Unicode character "`+n[0]+`"`+(` (`+n.charCodeAt(0)+`)`),t)),o={type:`textord`,mode:`text`,loc:ni.range(t),text:n};else return null;if(this.consume(),a)for(var l=0;lt?1:e>=t?0:NaN}function d(e,t){return e==null||t==null?NaN:te?1:t>=e?0:NaN}function f(e){let t,n,r;e.length===2?(t=e===u||e===d?e:p,n=e,r=e):(t=u,n=(t,n)=>u(e(t),n),r=(t,n)=>e(t)-n);function i(e,r,i=0,a=e.length){if(i>>1;n(e[t],r)<0?i=t+1:a=t}while(i>>1;n(e[t],r)<=0?i=t+1:a=t}while(in&&r(e[o-1],t)>-r(e[o],t)?o-1:o}return{left:i,center:o,right:a}}function p(){return 0}function m(e){return e===null?NaN:+e}var h=f(u),g=h.right;h.left,f(m).center;var _=Math.sqrt(50),v=Math.sqrt(10),y=Math.sqrt(2);function b(e,t,n){let r=(t-e)/Math.max(0,n),i=Math.floor(Math.log10(r)),a=r/10**i,o=a>=_?10:a>=v?5:a>=y?2:1,s,c,l;return i<0?(l=10**-i/o,s=Math.round(e*l),c=Math.round(t*l),s/lt&&--c,l=-l):(l=10**i*o,s=Math.round(e/l),c=Math.round(t/l),s*lt&&--c),c0))return[];if(e===t)return[e];let r=t=i))return[];let s=a-i+1,c=Array(s);if(r)if(o<0)for(let e=0;et&&(n=e,e=t,t=n),function(n){return Math.max(e,Math.min(t,n))}}function B(e,t,n){var r=e[0],i=e[1],a=t[0],o=t[1];return i2?V:B,l=u=null,f}function f(t){return t==null||isNaN(t=+t)?o:(l||=c(e.map(i),n,r))(i(s(t)))}return f.invert=function(r){return s(a((u||=c(n,e.map(i),t))(r)))},f.domain=function(t){return arguments.length?(e=Array.from(t,F),d()):e.slice()},f.range=function(e){return arguments.length?(n=Array.from(e),d()):n.slice()},f.rangeRound=function(e){return n=Array.from(e),r=A,d()},f.clamp=function(e){return arguments.length?(s=e?!0:L,d()):s!==L},f.interpolate=function(e){return arguments.length?(r=e,d()):r},f.unknown=function(e){return arguments.length?(o=e,f):o},function(e,t){return i=e,a=t,d()}}function W(){return U()(L,L)}function G(e,t,n,r){var i=C(e,t,n),a;switch(r=s(r??`,f`),r.type){case`s`:var l=Math.max(Math.abs(e),Math.abs(t));return r.precision==null&&!isNaN(a=M(i,l))&&(r.precision=a),o(r,l);case``:case`e`:case`g`:case`p`:case`r`:r.precision==null&&!isNaN(a=N(i,Math.max(Math.abs(e),Math.abs(t))))&&(r.precision=a-(r.type===`e`));break;case`f`:case`%`:r.precision==null&&!isNaN(a=j(i))&&(r.precision=a-(r.type===`%`)*2);break}return c(r)}function K(e){var t=e.domain;return e.ticks=function(e){var n=t();return x(n[0],n[n.length-1],e??10)},e.tickFormat=function(e,n){var r=t();return G(r[0],r[r.length-1],e??10,n)},e.nice=function(n){n??=10;var r=t(),i=0,a=r.length-1,o=r[i],s=r[a],c,l,u=10;for(s0;){if(l=S(o,s,n),l===c)return r[i]=o,r[a]=s,t(r);if(l>0)o=Math.floor(o/l)*l,s=Math.ceil(s/l)*l;else if(l<0)o=Math.ceil(o*l)/l,s=Math.floor(s*l)/l;else break;c=l}return e},e}function q(){var e=W();return e.copy=function(){return H(e,q())},l.apply(e,arguments),K(e)}export{f as a,C as i,W as n,H as r,q as t}; \ No newline at end of file diff --git a/dist-desktop/assets/login-xkhUej_P.js b/dist-desktop/assets/login-xkhUej_P.js new file mode 100644 index 0000000..17c179c --- /dev/null +++ b/dist-desktop/assets/login-xkhUej_P.js @@ -0,0 +1 @@ +import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./react-BLJmJXjR.js";import{i as n,u as r}from"./utils-BTuSbA5p.js";import{c as i}from"./index-CXgd9jpl.js";import{r as a,t as o}from"./client-CwgDvMJw.js";import{i as s,r as c,t as l}from"./input-mze7gZ5r.js";var u=[{providerId:`grok-google`,idp:`google`,label:`Google`},{providerId:`grok-x`,idp:`twitter`,label:`X`}],d=e(t()),f=r();function p(){if(typeof window>`u`)return!1;let e=window.location.hostname;return e===`localhost`||e===`127.0.0.1`||e===`[::1]`}function m(){let{user:e,isPending:t}=c(),[r,m]=(0,d.useState)(``),[h,g]=(0,d.useState)(``),[_,v]=(0,d.useState)(``),[y,b]=(0,d.useState)(`signin`),[x,S]=(0,d.useState)(!1),[C,w]=(0,d.useState)(null),[T,E]=(0,d.useState)(!1);if((0,d.useEffect)(()=>E(p()),[]),!t&&e)return(0,f.jsx)(i,{to:`/`});async function D(e){e.preventDefault(),w(null),S(!0);try{if(y===`signup`){let{error:e}=await o.signUp.email({email:r.trim(),password:h,name:_.trim()||r.trim().split(`@`)[0]||`User`});if(e)throw Error(e.message??`Sign-up failed`)}else{let{error:e}=await o.signIn.email({email:r.trim(),password:h});if(e)throw Error(e.message??`Sign-in failed`)}window.location.href=`/`}catch(e){w(e instanceof Error?e.message:`Authentication failed`)}finally{S(!1)}}async function O(e){w(null),S(!0);try{await a(e,{callbackURL:`/`})}catch(e){let t=e instanceof Error?e.message:`Sign-in failed`;/invalid redirect/i.test(t)||T?w(`Google / X sign-in needs a public app URL registered with the Grok auth broker. On this machine use email & password, or open the app in a Grok live preview / deployed host.`):w(t),S(!1)}}return(0,f.jsx)(`main`,{className:`grid min-h-dvh place-items-center bg-background px-6 text-foreground`,children:(0,f.jsxs)(`div`,{className:`w-full max-w-sm space-y-6`,children:[(0,f.jsxs)(`div`,{className:`space-y-2 text-center`,children:[(0,f.jsx)(`div`,{className:`mx-auto flex size-12 items-center justify-center rounded-xl bg-foreground text-lg font-semibold text-background`,children:`F`}),(0,f.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Sign in to ForgeNotes`}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Signed-in pages sync to the database. Guests keep a local copy only.`})]}),T&&(0,f.jsxs)(`p`,{className:`rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-left text-xs leading-relaxed text-amber-950 dark:text-amber-100`,children:[(0,f.jsx)(`strong`,{className:`font-medium`,children:`Desktop / local note:`}),` Continue with Google or X uses the shared Grok auth broker, which only accepts callbacks from`,` `,(0,f.jsx)(`code`,{className:`rounded bg-black/5 px-1 dark:bg-white/10`,children:`*.grok-sandbox.com`}),` `,`(or a deployed app with its own broker credentials). For this Tauri / localhost window, use `,(0,f.jsx)(`strong`,{children:`email & password`}),` below.`]}),(0,f.jsxs)(`div`,{className:`space-y-4`,children:[(0,f.jsxs)(`form`,{onSubmit:D,className:`space-y-3`,children:[y===`signup`&&(0,f.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,f.jsx)(`label`,{htmlFor:`name`,className:`text-xs font-medium text-muted-foreground`,children:`Name`}),(0,f.jsx)(l,{id:`name`,autoComplete:`name`,value:_,onChange:e=>v(e.target.value),placeholder:`Your name`,disabled:x})]}),(0,f.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,f.jsx)(`label`,{htmlFor:`email`,className:`text-xs font-medium text-muted-foreground`,children:`Email`}),(0,f.jsx)(l,{id:`email`,type:`email`,autoComplete:`email`,required:!0,value:r,onChange:e=>m(e.target.value),placeholder:`you@example.com`,disabled:x})]}),(0,f.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,f.jsx)(`label`,{htmlFor:`password`,className:`text-xs font-medium text-muted-foreground`,children:`Password`}),(0,f.jsx)(l,{id:`password`,type:`password`,autoComplete:y===`signup`?`new-password`:`current-password`,required:!0,minLength:8,value:h,onChange:e=>g(e.target.value),placeholder:`At least 8 characters`,disabled:x})]}),(0,f.jsx)(s,{type:`submit`,className:`h-11 w-full`,disabled:x,children:x?`Working…`:y===`signup`?`Create account`:`Sign in with email`}),(0,f.jsx)(`button`,{type:`button`,className:`w-full text-center text-xs text-muted-foreground underline-offset-4 hover:underline`,disabled:x,onClick:()=>{b(e=>e===`signin`?`signup`:`signin`),w(null)},children:y===`signup`?`Already have an account? Sign in`:`Need an account? Sign up`})]}),(0,f.jsxs)(`div`,{className:`relative py-1`,children:[(0,f.jsx)(`div`,{className:`absolute inset-0 flex items-center`,children:(0,f.jsx)(`span`,{className:`w-full border-t border-border`})}),(0,f.jsx)(`div`,{className:`relative flex justify-center text-xs uppercase`,children:(0,f.jsx)(`span`,{className:`bg-background px-2 text-muted-foreground`,children:`or`})})]}),(0,f.jsx)(`div`,{className:`space-y-2`,children:u.map(e=>(0,f.jsxs)(s,{type:`button`,variant:`outline`,className:`h-11 w-full justify-center`,disabled:x,onClick:()=>void O(e.providerId),children:[`Continue with `,e.label]},e.providerId))})]}),C&&(0,f.jsx)(`p`,{className:`rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive`,children:C}),(0,f.jsx)(`p`,{className:`text-center text-sm text-muted-foreground`,children:(0,f.jsx)(n,{to:`/`,className:`underline-offset-4 hover:underline`,children:`Continue as guest`})})]})})}export{m as component}; \ No newline at end of file diff --git a/dist-desktop/assets/map-BaFkSB1l.js b/dist-desktop/assets/map-BaFkSB1l.js new file mode 100644 index 0000000..f3c4b0d --- /dev/null +++ b/dist-desktop/assets/map-BaFkSB1l.js @@ -0,0 +1 @@ +import{$ as e,F as t,G as n,H as r,I as i,M as a,P as o,Q as s,R as c,S as ee,Z as l,_ as u,b as d,f,g as p,it as m,j as h,k as g,l as _,q as v,rt as y,tt as b,v as te,w as ne,x as re,y as ie,z as x}from"./graphlib-DS17s2tU.js";var S=Object.create,ae=function(){function e(){}return function(t){if(!l(t))return{};if(S)return S(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();function C(e,t){var n=-1,r=e.length;for(t||=Array(r);++ni.map(i=>d[i]); +import{t as e}from"./index-CXgd9jpl.js";import{x as t}from"./chunk-KEIR6QF5-Dj-OpFgW.js";import"./chunk-MOZMSUNE-BgA8jCvb.js";import"./chunk-OSBZ3O6U-CX9EQ5t2.js";import"./chunk-5JV3BV7I-DKfYBAeY.js";import"./chunk-CYSBUYHQ-CbOq7Rc1.js";import"./chunk-BIQX33UG-CuPbkyWp.js";import"./chunk-EMLP6XTP-BoneA0Uo.js";import"./chunk-YOTPTUD7-CjHV8V6f.js";import"./chunk-QBLGF6JB-C9zGMqvP.js";import"./chunk-5TONJI2A-DOX2waSJ.js";import"./chunk-5HE753X5-o8-OCfIL.js";import"./chunk-U6XO7XAA-CR0BSRFR.js";import"./chunk-JG7HCLWE-Dk4_aECj.js";import"./chunk-CQNSW5MT-BbEh_krl.js";import"./chunk-R7FJI6CG-BpBhcF6R.js";import"./chunk-5FCAYU7R-DNtJmW0j.js";var n={},r={info:t(async()=>{let{createInfoServices:t}=await e(async()=>{let{createInfoServices:e}=await import(`./info-DKCQHKI2-DIc7uC4I.js`);return{createInfoServices:e}},__vite__mapDeps([0,1,2]));n.info=t().Info.parser.LangiumParser},`info`),packet:t(async()=>{let{createPacketServices:t}=await e(async()=>{let{createPacketServices:e}=await import(`./packet-7NZHBO7P-D2duWGIK.js`);return{createPacketServices:e}},__vite__mapDeps([3,1,4]));n.packet=t().Packet.parser.LangiumParser},`packet`),pie:t(async()=>{let{createPieServices:t}=await e(async()=>{let{createPieServices:e}=await import(`./pie-RZYD4A2V-CynqTUkZ.js`);return{createPieServices:e}},__vite__mapDeps([5,1,6]));n.pie=t().Pie.parser.LangiumParser},`pie`),treeView:t(async()=>{let{createTreeViewServices:t}=await e(async()=>{let{createTreeViewServices:e}=await import(`./treeView-QDETBFTQ-CygwzEgj.js`);return{createTreeViewServices:e}},__vite__mapDeps([7,1,8]));n.treeView=t().TreeView.parser.LangiumParser},`treeView`),architecture:t(async()=>{let{createArchitectureServices:t}=await e(async()=>{let{createArchitectureServices:e}=await import(`./architecture-TIHT7OUA-BWqzHezU.js`);return{createArchitectureServices:e}},__vite__mapDeps([9,1,10]));n.architecture=t().Architecture.parser.LangiumParser},`architecture`),gitGraph:t(async()=>{let{createGitGraphServices:t}=await e(async()=>{let{createGitGraphServices:e}=await import(`./gitGraph-TEB2WS4Q-Do0SQOtM.js`);return{createGitGraphServices:e}},__vite__mapDeps([11,1,12]));n.gitGraph=t().GitGraph.parser.LangiumParser},`gitGraph`),eventmodeling:t(async()=>{let{createEventModelingServices:t}=await e(async()=>{let{createEventModelingServices:e}=await import(`./eventmodeling-45OFAUF4-Dp0gpjhg.js`);return{createEventModelingServices:e}},__vite__mapDeps([13,1,14]));n.eventmodeling=t().EventModel.parser.LangiumParser},`eventmodeling`),radar:t(async()=>{let{createRadarServices:t}=await e(async()=>{let{createRadarServices:e}=await import(`./radar-I7S5WNFK-fIKE12aT.js`);return{createRadarServices:e}},__vite__mapDeps([15,1,16]));n.radar=t().Radar.parser.LangiumParser},`radar`),railroad:t(async()=>{let{createRailroadServices:t}=await e(async()=>{let{createRailroadServices:e}=await import(`./railroad-3IZDKUUU-Bgx8HJTj.js`);return{createRailroadServices:e}},__vite__mapDeps([17,1,18]));n.railroad=t().Railroad.parser.LangiumParser},`railroad`),railroadEbnf:t(async()=>{let{createRailroadEbnfServices:t}=await e(async()=>{let{createRailroadEbnfServices:e}=await import(`./railroad-ebnf-EBAXGLYW-C74h3s_I.js`);return{createRailroadEbnfServices:e}},__vite__mapDeps([19,1,20]));n.railroadEbnf=t().RailroadEbnf.parser.LangiumParser},`railroadEbnf`),railroadAbnf:t(async()=>{let{createRailroadAbnfServices:t}=await e(async()=>{let{createRailroadAbnfServices:e}=await import(`./railroad-abnf-AHOZXSZD-Nh6k60mH.js`);return{createRailroadAbnfServices:e}},__vite__mapDeps([21,1,22]));n.railroadAbnf=t().RailroadAbnf.parser.LangiumParser},`railroadAbnf`),railroadPeg:t(async()=>{let{createRailroadPegServices:t}=await e(async()=>{let{createRailroadPegServices:e}=await import(`./railroad-peg-LSFZ7HO6-0hT-lN-u.js`);return{createRailroadPegServices:e}},__vite__mapDeps([23,1,24]));n.railroadPeg=t().RailroadPeg.parser.LangiumParser},`railroadPeg`),treemap:t(async()=>{let{createTreemapServices:t}=await e(async()=>{let{createTreemapServices:e}=await import(`./treemap-6X3UGDF4-BbCXbaXr.js`);return{createTreemapServices:e}},__vite__mapDeps([25,1,26]));n.treemap=t().Treemap.parser.LangiumParser},`treemap`),wardley:t(async()=>{let{createWardleyServices:t}=await e(async()=>{let{createWardleyServices:e}=await import(`./wardley-OPB4EBWU-BjXxCRf_.js`);return{createWardleyServices:e}},__vite__mapDeps([27,1,28]));n.wardley=t().Wardley.parser.LangiumParser},`wardley`),cynefin:t(async()=>{let{createCynefinServices:t}=await e(async()=>{let{createCynefinServices:e}=await import(`./cynefin-VYW2F7L2-4m18BxUG.js`);return{createCynefinServices:e}},__vite__mapDeps([29,1,30]));n.cynefin=t().Cynefin.parser.LangiumParser},`cynefin`)};async function i(e,t){let i=r[e];if(!i)throw Error(`Unknown diagram type: ${e}`);n[e]||await i();let o=n[e].parse(t);if(o.lexerErrors.length>0||o.parserErrors.length>0)throw new a(o);return o.value}t(i,`parse`);var a=class extends Error{constructor(e){let t=e.lexerErrors.map(e=>`Lexer error on line ${e.line!==void 0&&!isNaN(e.line)?e.line:`?`}, column ${e.column!==void 0&&!isNaN(e.column)?e.column:`?`}: ${e.message}`).join(` +`),n=e.parserErrors.map(e=>`Parse error on line ${e.token.startLine!==void 0&&!isNaN(e.token.startLine)?e.token.startLine:`?`}, column ${e.token.startColumn!==void 0&&!isNaN(e.token.startColumn)?e.token.startColumn:`?`}: ${e.message}`).join(` +`);super(`Parsing failed: ${t} ${n}`),this.result=e}static{t(this,`MermaidParseError`)}};export{i as n,a as t}; \ No newline at end of file diff --git a/dist-desktop/assets/mermaid.core-lwoghoVk.js b/dist-desktop/assets/mermaid.core-lwoghoVk.js new file mode 100644 index 0000000..280727f --- /dev/null +++ b/dist-desktop/assets/mermaid.core-lwoghoVk.js @@ -0,0 +1,11 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/c4Diagram-LMCZKHZV-B2PQ0JjZ.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-UMNXGZaF.js","assets/rolldown-runtime-aKtaBQYM.js","assets/chunk-WYO6CB5R-Dv5kDyQC.js","assets/index-CXgd9jpl.js","assets/react-BLJmJXjR.js","assets/utils-BTuSbA5p.js","assets/dist-qx0Iv9vM.js","assets/chunk-ICXQ74PX-Czpgj8Uw.js","assets/chunk-32BRIVSS-DWU3ezKg.js","assets/flowDiagram-23GEKE2U-mMOyit70.js","assets/chunk-HOUHSVGY-iJuv90UH.js","assets/chunk-Q4XR5HBZ-CQ8zkLYc.js","assets/chunk-7BUUIJ7U-Bb538aSH.js","assets/chunk-OGEWGWER-D-nWYRNR.js","assets/chunk-XXDRQBXY-Bq6zMMOx.js","assets/chunk-VR4S4FIN-BTo4eV3J.js","assets/chunk-C7G6YPKG-DW-1jWUA.js","assets/chunk-ZGVPDNZ5-DGInJAPD.js","assets/rough.esm-CSKSodPl.js","assets/chunk-52WLFC77-BOCvVCX1.js","assets/line-b9Ala942.js","assets/path-BWPyau1x.js","assets/array-BifhSqXX.js","assets/chunk-FWX5IMBZ-ComLEIwh.js","assets/chunk-ZIRB5QZD-C6fEPe3t.js","assets/chunk-PUDLZKDR-hlw4TonS.js","assets/channel-C4fgBBJ4.js","assets/chunk-5VM5RSS4-ZNzvKenW.js","assets/swimlanesDiagram-G3AALYLV-CGWZF_2o.js","assets/erDiagram-Q63AITRT-BwmdWLsf.js","assets/gitGraphDiagram-IHSO6WYX-CPtw8GFs.js","assets/chunk-JWPE2WC7-DVXcaiue.js","assets/mermaid-parser.core-Z7xZAZRH.js","assets/chunk-KEIR6QF5-Dj-OpFgW.js","assets/chunk-MOZMSUNE-BgA8jCvb.js","assets/chunk-OSBZ3O6U-CX9EQ5t2.js","assets/chunk-5JV3BV7I-DKfYBAeY.js","assets/chunk-CYSBUYHQ-CbOq7Rc1.js","assets/chunk-BIQX33UG-CuPbkyWp.js","assets/chunk-EMLP6XTP-BoneA0Uo.js","assets/chunk-YOTPTUD7-CjHV8V6f.js","assets/chunk-QBLGF6JB-C9zGMqvP.js","assets/chunk-5TONJI2A-DOX2waSJ.js","assets/chunk-5HE753X5-o8-OCfIL.js","assets/chunk-U6XO7XAA-CR0BSRFR.js","assets/chunk-JG7HCLWE-Dk4_aECj.js","assets/chunk-CQNSW5MT-BbEh_krl.js","assets/chunk-R7FJI6CG-BpBhcF6R.js","assets/chunk-5FCAYU7R-DNtJmW0j.js","assets/chunk-2Q5K7J3B-C1jixKkw.js","assets/ganttDiagram-NO4QXBWP-BFiNAWzu.js","assets/linear-DhAcoVP9.js","assets/defaultLocale-C8Fc0cco.js","assets/init-D6jRqBbL.js","assets/infoDiagram-FWYZ7A6U-BY1UX4W6.js","assets/chunk-VAUOI2AC-AC9pRUsa.js","assets/pieDiagram-ENE6RG2P-BBPaHS9V.js","assets/ordinal-hYBb2elL.js","assets/arc-DqK6O3qL.js","assets/quadrantDiagram-ABIIQ3AL-UafGc-sH.js","assets/xychartDiagram-FW5EYKEG-HaTasnSW.js","assets/requirementDiagram-TGXJPOKE-Bk3E4jWx.js","assets/sequenceDiagram-DBY2YBRQ-CUG55-r_.js","assets/classDiagram-OUVF2IWQ-D6qCu_tS.js","assets/chunk-V7JOEXUC-Drt5hFEy.js","assets/classDiagram-v2-EOCWNBFH-D6qCu_tS.js","assets/stateDiagram-2N3HPSRC-u60ROSPY.js","assets/graphlib-DS17s2tU.js","assets/dagre-dpRSp0QF.js","assets/map-BaFkSB1l.js","assets/chunk-EX3LRPZG-CzaF5a2T.js","assets/stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js","assets/journeyDiagram-5HDEW3XC-CCn-uNlj.js","assets/timeline-definition-FHXFAJF6-DFMIv6oI.js","assets/mindmap-definition-LN4V7U3C-Bib4remL.js","assets/kanban-definition-HUTT4EX6-CW9CwpnR.js","assets/sankeyDiagram-HTMAVEWB-oWnBtA7E.js","assets/diagram-NH7WQ7WH-Btsva5Mx.js","assets/diagram-WEI45ONY-DzxhBgyP.js","assets/blockDiagram-677ZJIJ3-Dn3HALPW.js","assets/diagram-OA4YK3LP-B1b6NwZz.js","assets/architectureDiagram-ZJ3FMSHR-DevFyLmc.js","assets/cytoscape.esm-CQFVGiJu.js","assets/diagram-FQU43EPY-C8Vn5v8I.js","assets/ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js","assets/vennDiagram-L72KCM5P-DkYnXwoc.js","assets/diagram-G47NLZAW-B5XCVQOu.js","assets/wardleyDiagram-EHGQE667-BewauNW1.js","assets/cynefinDiagram-TSTJHNR4-CAKFzgf0.js","assets/railroadDiagram-RFXS5EU6-D7w_TgGh.js","assets/chunk-MOJQB5TN-Bju_yCKi.js","assets/ebnfDiagram-CCIWWBDH-DiJBARG_.js","assets/abnfDiagram-VRR7QNED-DLdRCqX4.js","assets/pegDiagram-2B236MQR-CPt8QfP3.js"])))=>i.map(i=>d[i]); +import{t as e}from"./index-CXgd9jpl.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{h as n,m as r,p as i}from"./src-UMNXGZaF.js";import{$ as a,C as o,E as s,I as c,L as l,N as u,P as d,Q as f,S as p,T as m,V as h,W as g,X as _,Z as v,_ as y,b,c as x,g as S,l as C,m as w,n as ee,p as T,q as te,r as ne,t as re,u as ie}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{S as ae,a as oe,f as E,g as D,h as se,i as ce,o as le,v as ue,x as de,y as fe}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as pe}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{r as me}from"./chunk-HOUHSVGY-iJuv90UH.js";import{r as he}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import{n as ge}from"./chunk-FWX5IMBZ-ComLEIwh.js";import{n as _e,t as ve}from"./chunk-ZIRB5QZD-C6fEPe3t.js";function ye(e){let t=e?.constructor;return e===(typeof t==`function`?t.prototype:Object.prototype)}function be(e){if(e==null)return!0;if(de(e))return typeof e.splice!=`function`&&typeof e!=`string`&&!ae(e)&&!ue(e)&&!fe(e)?!1:e.length===0;if(typeof e==`object`||typeof e==`function`){if(e instanceof Map||e instanceof Set)return e.size===0;let t=Object.keys(e);return ye(e)?t.filter(e=>e!==`constructor`).length===0:t.length===0}return!0}var O=`comm`,xe=`rule`,Se=`decl`,Ce=`@import`,we=`@namespace`,Te=`@keyframes`,Ee=`@layer`,De=Math.abs,k=String.fromCharCode;function Oe(e){return e.trim()}function A(e,t,n){return e.replace(t,n)}function j(e,t){return e.charCodeAt(t)|0}function M(e,t,n){return e.slice(t,n)}function N(e){return e.length}function ke(e){return e.length}function P(e,t){return t.push(e),e}var F=1,I=1,Ae=0,L=0,R=0,z=``;function B(e,t,n,r,i,a,o,s){return{value:e,root:t,parent:n,type:r,props:i,children:a,line:F,column:I,length:o,return:``,siblings:s}}function je(){return R}function Me(){return R=L>0?j(z,--L):0,I--,R===10&&(I=1,F--),R}function V(){return R=L2||G(R)>3?``:` `}function Ie(e,t){for(;--t&&V()&&!(R<48||R>102||R>57&&R<65||R>70&&R<97););return W(e,U()+(t<6&&H()==32&&V()==32))}function q(e){for(;V();)switch(R){case e:return L;case 34:case 39:e!==34&&e!==39&&q(R);break;case 40:e===41&&q(e);break;case 92:V();break}return L}function Le(e,t){for(;V()&&e+R!==57&&!(e+R===84&&H()===47););return`/*`+W(t,L-1)+`*`+k(e===47?e:V())}function Re(e){for(;!G(H());)V();return W(e,L)}function ze(e){return Pe(J(``,null,null,null,[``],e=Ne(e),0,[0],e))}function J(e,t,n,r,i,a,o,s,c){for(var l=0,u=0,d=o,f=0,p=0,m=0,h=1,g=1,_=1,v=0,y=0,b=``,x=i,S=a,C=r,w=b;g;)switch(m=y,y=V()){case 40:m!=108&&j(w,d-1)==58?(v++,w+=`(`):w+=K(y);break;case 41:v--,w+=`)`;break;case 34:case 39:case 91:w+=K(y);break;case 9:case 10:case 13:case 32:if(v>0){w+=k(y);break}w+=Fe(m);break;case 92:w+=Ie(U()-1,7);continue;case 47:switch(H()){case 42:case 47:P(Ve(Le(V(),U()),t,n,c),c),(G(m||1)==5||G(H()||1)==5)&&N(w)&&M(w,-1,void 0)!==` `&&(w+=` `);break;default:w+=`/`}break;case 123*h:s[l++]=N(w)*_;case 125*h:case 59:case 0:if(v>0&&y){w+=k(y);break}switch(y){case 0:case 125:g=0;case 59+u:_==-1&&(w=A(w,/\f/g,``)),p>0&&(N(w)-d||h===0)&&P(p>32?He(w+`;`,r,n,d-1,c):He(A(w,` `,``)+`;`,r,n,d-2,c),c);break;case 59:w+=`;`;default:if(P(C=Be(w,t,n,l,u,i,s,b,x=[],S=[],d,a),a),y===123)if(u===0)J(w,t,C,C,x,a,d,s,S);else{switch(f){case 99:if(j(w,3)===110)break;case 108:if(j(w,2)===97)break;default:u=0;case 100:case 109:case 115:}u?J(e,C,C,r&&P(Be(e,C,C,0,0,i,s,b,i,x=[],d,S),S),i,S,d,s,r?x:S):J(w,C,C,C,[``],S,0,s,S)}}l=u=p=0,h=_=1,b=w=``,d=o;break;case 58:d=1+N(w),p=m;default:if(h<1){if(y==123)--h;else if(y==125&&h++==0&&Me()==125)continue}switch(w+=k(y),y*h){case 38:_=u>0?1:(w+=`\f`,-1);break;case 44:if(v>0)break;s[l++]=(N(w)-1)*_,_=1;break;case 64:H()===45&&(w+=K(V())),f=H(),u=d=N(b=w+=Re(U())),y++;break;case 45:m===45&&N(w)==2&&(h=0)}}return a}function Be(e,t,n,r,i,a,o,s,c,l,u,d){for(var f=i-1,p=i===0?a:[``],m=ke(p),h=0,g=0,_=0;h0?p[v]+` `+y:A(y,/&\f/g,p[v])))&&(c[_++]=b);return B(e,t,n,i===0?xe:s,c,l,u,d)}function Ve(e,t,n,r){return B(e,t,n,O,k(je()),M(e,2,-2),0,r)}function He(e,t,n,r,i){return B(e,t,n,Se,M(e,0,r),M(e,r+1,-1),r,i)}function Ue(e,t){for(var n=``,r=0;r/^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./c4Diagram-LMCZKHZV-B2PQ0JjZ.js`);return{diagram:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));return{id:Ke,diagram:t}},`loader`)},Je=`flowchart`,Ye={id:Je,detector:t((e,t)=>t?.flowchart?.defaultRenderer===`dagre-wrapper`||t?.flowchart?.defaultRenderer===`elk`?!1:/^\s*graph/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./flowDiagram-23GEKE2U-mMOyit70.js`);return{diagram:e}},__vite__mapDeps([11,2,3,1,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:Je,diagram:t}},`loader`)},Xe=`flowchart-v2`,Ze={id:Xe,detector:t((e,t)=>t?.flowchart?.defaultRenderer===`dagre-d3`?!1:(t?.flowchart?.defaultRenderer===`elk`&&(t.layout=`elk`),/^\s*graph/.test(e)&&t?.flowchart?.defaultRenderer===`dagre-wrapper`?!0:/^\s*flowchart/.test(e)),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./flowDiagram-23GEKE2U-mMOyit70.js`);return{diagram:e}},__vite__mapDeps([11,2,3,1,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:Xe,diagram:t}},`loader`)},Qe=`swimlane`,$e={id:Qe,detector:t(e=>/^\s*swimlane-beta\b/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./swimlanesDiagram-G3AALYLV-CGWZF_2o.js`);return{diagram:e}},__vite__mapDeps([30,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:Qe,diagram:t}},`loader`)},et=`er`,tt={id:et,detector:t(e=>/^\s*erDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./erDiagram-Q63AITRT-BwmdWLsf.js`);return{diagram:e}},__vite__mapDeps([31,1,2,3,4,5,6,7,28,9,8,12,13,14,15,16,17,18,19,20,21,22,23,24,25]));return{id:et,diagram:t}},`loader`)},nt=`gitGraph`,rt={id:nt,detector:t(e=>/^\s*gitGraph/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./gitGraphDiagram-IHSO6WYX-CPtw8GFs.js`);return{diagram:e}},__vite__mapDeps([32,1,2,3,4,5,6,7,9,8,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51]));return{id:nt,diagram:t}},`loader`)},it=`gantt`,at={id:it,detector:t(e=>/^\s*gantt/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./ganttDiagram-NO4QXBWP-BFiNAWzu.js`);return{diagram:e}},__vite__mapDeps([52,3,1,2,4,5,6,7,53,54,55,8,9]));return{id:it,diagram:t}},`loader`)},ot=`info`,st={id:ot,detector:t(e=>/^\s*info/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./infoDiagram-FWYZ7A6U-BY1UX4W6.js`);return{diagram:e}},__vite__mapDeps([56,1,2,3,4,5,6,7,57,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:ot,diagram:t}},`loader`)},ct=`pie`,lt={id:ct,detector:t(e=>/^\s*pie/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./pieDiagram-ENE6RG2P-BBPaHS9V.js`);return{diagram:e}},__vite__mapDeps([58,1,2,3,4,5,6,7,59,55,23,8,60,24,9,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:ct,diagram:t}},`loader`)},ut=`quadrantChart`,dt={id:ut,detector:t(e=>/^\s*quadrantChart/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./quadrantDiagram-ABIIQ3AL-UafGc-sH.js`);return{diagram:e}},__vite__mapDeps([61,1,2,3,4,5,6,7,53,54,55]));return{id:ut,diagram:t}},`loader`)},ft=`xychart`,pt={id:ft,detector:t(e=>/^\s*xychart(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./xychartDiagram-FW5EYKEG-HaTasnSW.js`);return{diagram:e}},__vite__mapDeps([62,1,2,3,4,5,6,7,53,54,55,59,9,8,22,23,24,57,12,13]));return{id:ft,diagram:t}},`loader`)},mt=`requirement`,ht={id:mt,detector:t(e=>/^\s*requirement(Diagram)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./requirementDiagram-TGXJPOKE-Bk3E4jWx.js`);return{diagram:e}},__vite__mapDeps([63,1,2,3,4,5,6,7,9,8,12,13,14,15,16,17,18,19,20,21,22,23,24,25]));return{id:mt,diagram:t}},`loader`)},gt=`sequence`,_t={id:gt,detector:t(e=>/^\s*sequenceDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./sequenceDiagram-DBY2YBRQ-CUG55-r_.js`);return{diagram:e}},__vite__mapDeps([64,1,2,3,4,5,6,7,8,9,10,51,26]));return{id:gt,diagram:t}},`loader`)},vt=`class`,yt={id:vt,detector:t((e,t)=>t?.class?.defaultRenderer!==`dagre-wrapper`&&/^\s*classDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./classDiagram-OUVF2IWQ-D6qCu_tS.js`);return{diagram:e}},__vite__mapDeps([65,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,66,29]));return{id:vt,diagram:t}},`loader`)},bt=`classDiagram`,xt={id:bt,detector:t((e,t)=>/^\s*classDiagram/.test(e)&&t?.class?.defaultRenderer===`dagre-wrapper`?!0:/^\s*classDiagram-v2/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./classDiagram-v2-EOCWNBFH-D6qCu_tS.js`);return{diagram:e}},__vite__mapDeps([67,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,66,29]));return{id:bt,diagram:t}},`loader`)},St=`state`,Ct={id:St,detector:t((e,t)=>t?.state?.defaultRenderer!==`dagre-wrapper`&&/^\s*stateDiagram/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./stateDiagram-2N3HPSRC-u60ROSPY.js`);return{diagram:e}},__vite__mapDeps([68,1,2,3,4,5,6,7,9,8,22,23,24,12,13,14,15,69,70,71,10,16,17,18,19,20,21,25,72]));return{id:St,diagram:t}},`loader`)},wt=`stateDiagram`,Tt={id:wt,detector:t((e,t)=>!!(/^\s*stateDiagram-v2/.test(e)||/^\s*stateDiagram/.test(e)&&t?.state?.defaultRenderer===`dagre-wrapper`),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js`);return{diagram:e}},__vite__mapDeps([73,1,2,3,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,72]));return{id:wt,diagram:t}},`loader`)},Et=`journey`,Dt={id:Et,detector:t(e=>/^\s*journey/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./journeyDiagram-5HDEW3XC-CCn-uNlj.js`);return{diagram:e}},__vite__mapDeps([74,1,2,3,4,5,6,7,60,23,8,29,10]));return{id:Et,diagram:t}},`loader`)},Ot={draw:t((e,t,n)=>{r.debug(`rendering svg for syntax error +`);let i=pe(t),a=i.append(`g`);i.attr(`viewBox`,`0 0 2412 512`),x(i,100,512,!0),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z`),a.append(`path`).attr(`class`,`error-icon`).attr(`d`,`m436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z`),a.append(`text`).attr(`class`,`error-text`).attr(`x`,1440).attr(`y`,250).attr(`font-size`,`150px`).style(`text-anchor`,`middle`).text(`Syntax error in text`),a.append(`text`).attr(`class`,`error-text`).attr(`x`,1250).attr(`y`,400).attr(`font-size`,`100px`).style(`text-anchor`,`middle`).text(`mermaid version ${n}`)},`draw`)},kt=Ot,At={db:{},renderer:Ot,parser:{parse:t(()=>{},`parse`)}},jt=`flowchart-elk`,Mt={id:jt,detector:t((e,t={})=>/^\s*flowchart-elk/.test(e)||/^\s*(flowchart|graph)/.test(e)&&t?.flowchart?.defaultRenderer===`elk`?(t.layout=`elk`,!0):!1,`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./flowDiagram-23GEKE2U-mMOyit70.js`);return{diagram:e}},__vite__mapDeps([11,2,3,1,4,5,6,7,9,8,12,13,14,15,10,16,17,18,19,20,21,22,23,24,25,26,27,28,29]));return{id:jt,diagram:t}},`loader`)},Nt=`timeline`,Pt={id:Nt,detector:t(e=>/^\s*timeline/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./timeline-definition-FHXFAJF6-DFMIv6oI.js`);return{diagram:e}},__vite__mapDeps([75,1,2,3,4,5,6,7,60,23,8,9,57]));return{id:Nt,diagram:t}},`loader`)},Ft=`mindmap`,It={id:Ft,detector:t(e=>/^\s*mindmap/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./mindmap-definition-LN4V7U3C-Bib4remL.js`);return{diagram:e}},__vite__mapDeps([76,1,2,3,4,5,6,7,9,8,12,13,14,15,16,17,18,19,20,21,22,23,24,25]));return{id:Ft,diagram:t}},`loader`)},Lt=`kanban`,Rt={id:Lt,detector:t(e=>/^\s*kanban/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./kanban-definition-HUTT4EX6-CW9CwpnR.js`);return{diagram:e}},__vite__mapDeps([77,1,2,3,4,5,6,7,9,8,57,12,13,29,15,18,19,20,26]));return{id:Lt,diagram:t}},`loader`)},zt=`sankey`,Bt={id:zt,detector:t(e=>/^\s*sankey(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./sankeyDiagram-HTMAVEWB-oWnBtA7E.js`);return{diagram:e}},__vite__mapDeps([78,1,2,3,4,5,6,7,59,55]));return{id:zt,diagram:t}},`loader`)},Vt=`packet`,Ht={id:Vt,detector:t(e=>/^\s*packet(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-NH7WQ7WH-Btsva5Mx.js`);return{diagram:e}},__vite__mapDeps([79,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:Vt,diagram:t}},`loader`)},Ut=`radar`,Wt={id:Ut,detector:t(e=>/^\s*radar-beta/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-WEI45ONY-DzxhBgyP.js`);return{diagram:e}},__vite__mapDeps([80,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:Ut,diagram:t}},`loader`)},Gt=`block`,Kt={id:Gt,detector:t(e=>/^\s*block(-beta)?/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./blockDiagram-677ZJIJ3-Dn3HALPW.js`);return{diagram:e}},__vite__mapDeps([81,1,2,3,4,5,6,7,28,9,8,22,23,24,12,13,29,14,15,69]));return{id:Gt,diagram:t}},`loader`)},qt=`treeView`,Jt={id:qt,detector:t(e=>/^\s*treeView-beta/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-OA4YK3LP-B1b6NwZz.js`);return{diagram:e}},__vite__mapDeps([82,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,12,51]));return{id:qt,diagram:t}},`loader`)},Yt=`architecture`,Xt={id:Yt,detector:t(e=>/^\s*architecture/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./architectureDiagram-ZJ3FMSHR-DevFyLmc.js`);return{diagram:e}},__vite__mapDeps([83,3,1,2,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,12,13,84]));return{id:Yt,diagram:t}},`loader`)},Zt=`eventmodeling`,Qt={id:Zt,detector:t(e=>/^\s*eventmodeling/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-FQU43EPY-C8Vn5v8I.js`);return{diagram:e}},__vite__mapDeps([85,35,1,2,3,4,5,6,7,9,8,33,34,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:Zt,diagram:t}},`loader`)},$t=`ishikawa`,en={id:$t,detector:t(e=>/^\s*ishikawa(-beta)?\b/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./ishikawaDiagram-FXEZZL3T-Jj-U8PJa.js`);return{diagram:e}},__vite__mapDeps([86,1,2,3,4,5,6,7,9,8,57,20]));return{id:$t,diagram:t}},`loader`)},tn=`venn`,nn={id:tn,detector:t(e=>/^\s*venn-beta/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./vennDiagram-L72KCM5P-DkYnXwoc.js`);return{diagram:e}},__vite__mapDeps([87,1,2,3,4,5,6,7,9,8,57,20]));return{id:tn,diagram:t}},`loader`)},rn=`treemap`,an={id:rn,detector:t(e=>/^\s*treemap/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./diagram-G47NLZAW-B5XCVQOu.js`);return{diagram:e}},__vite__mapDeps([88,1,2,3,4,5,6,7,59,55,54,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,17,18]));return{id:rn,diagram:t}},`loader`)},on=`wardley`,sn={id:on,detector:t(e=>/^\s*wardley-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./wardleyDiagram-EHGQE667-BewauNW1.js`);return{diagram:e}},__vite__mapDeps([89,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:on,diagram:t}},`loader`)},cn=`cynefin`,ln={id:cn,detector:t(e=>/^\s*cynefin-beta(?:[\s:]|$)/.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./cynefinDiagram-TSTJHNR4-CAKFzgf0.js`);return{diagram:e}},__vite__mapDeps([90,1,2,3,4,5,6,7,9,8,57,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]));return{id:cn,diagram:t}},`loader`)},un=`railroad`,dn={id:un,detector:t(e=>/^\s*railroad-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./railroadDiagram-RFXS5EU6-D7w_TgGh.js`);return{diagram:e}},__vite__mapDeps([91,44,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,45,46,47,48,49,50]));return{id:un,diagram:t}},`loader`)},fn=`railroadEbnf`,pn={id:fn,detector:t(e=>/^\s*railroad-ebnf-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./ebnfDiagram-CCIWWBDH-DiJBARG_.js`);return{diagram:e}},__vite__mapDeps([93,46,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,44,45,47,48,49,50]));return{id:fn,diagram:t}},`loader`)},mn=`railroadAbnf`,hn={id:mn,detector:t(e=>/^\s*railroad-abnf-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./abnfDiagram-VRR7QNED-DLdRCqX4.js`);return{diagram:e}},__vite__mapDeps([94,45,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,44,46,47,48,49,50]));return{id:mn,diagram:t}},`loader`)},gn=`railroadPeg`,_n={id:gn,detector:t(e=>/^\s*railroad-peg-beta/i.test(e),`detector`),loader:t(async()=>{let{diagram:t}=await e(async()=>{let{diagram:e}=await import(`./pegDiagram-2B236MQR-CPt8QfP3.js`);return{diagram:e}},__vite__mapDeps([95,47,35,1,2,3,4,5,6,7,57,92,33,34,36,37,38,39,40,41,42,43,44,45,46,48,49,50]));return{id:gn,diagram:t}},`loader`)},vn=!1,Y=t(()=>{vn||(vn=!0,u(`error`,At,e=>e.toLowerCase().trim()===`error`),u(`---`,{db:{clear:t(()=>{},`clear`)},styles:{},renderer:{draw:t(()=>{},`draw`)},parser:{parse:t(()=>{throw Error("Diagrams beginning with --- are not valid. If you were trying to use a YAML front-matter, please ensure that you've correctly opened and closed the YAML front-matter with un-indented `---` blocks")},`parse`)},init:t(()=>null,`init`)},e=>e.toLowerCase().trimStart().startsWith(`---`)),d(Mt,It,Xt),d(qe,Rt,xt,yt,tt,at,st,lt,ht,_t,$e,Ze,Ye,Pt,rt,Tt,Ct,Dt,dt,Bt,Ht,pt,Kt,Qt,Jt,Wt,en,an,dn,pn,hn,_n,nn,sn,ln))},`addDiagrams`),yn=t(async()=>{r.debug(`Loading registered diagrams`);let e=(await Promise.allSettled(Object.entries(w).map(async([e,{detector:t,loader:n}])=>{if(n)try{p(e)}catch{try{let{diagram:e,id:r}=await n();u(r,e,t)}catch(t){throw r.error(`Failed to load external diagram with key ${e}. Removing from detectors.`),delete w[e],t}}}))).filter(e=>e.status===`rejected`);if(e.length>0){r.error(`Failed to load ${e.length} external diagrams`);for(let t of e)r.error(t);throw Error(`Failed to load ${e.length} external diagrams`)}},`loadRegisteredDiagrams`),bn=`graphics-document document`;function xn(e,t){e.attr(`role`,bn),t!==``&&e.attr(`aria-roledescription`,t)}t(xn,`setA11yDiagramInfo`);function Sn(e,t,n,r){if(e.insert!==void 0){if(n){let t=`chart-desc-${r}`;e.attr(`aria-describedby`,t),e.insert(`desc`,`:first-child`).attr(`id`,t).text(n)}if(t){let n=`chart-title-${r}`;e.attr(`aria-labelledby`,n),e.insert(`title`,`:first-child`).attr(`id`,n).text(t)}}}t(Sn,`addSVGa11yTitleDescription`);var Cn=class e{constructor(e,t,n,r,i){this.type=e,this.text=t,this.db=n,this.parser=r,this.renderer=i}static{t(this,`Diagram`)}static async fromText(t,n={}){let r=b(),i=T(t,r);t=le(t)+` +`;try{p(i)}catch{let e=o(i);if(!e)throw new re(`Diagram ${i} not found.`);let{id:t,diagram:n}=await e();u(t,n)}let{db:a,parser:s,renderer:c,init:l}=p(i);return s.parser&&(s.parser.yy=a),a.clear?.(),l?.(r),n.title&&a.setDiagramTitle?.(n.title),await s.parse(t),new e(i,t,a,s,c)}async render(e,t){await this.renderer.draw(this.text,e,t,this)}getParser(){return this.parser}getType(){return this.type}},wn=[],Tn=t(()=>{wn.forEach(e=>{e()}),wn=[]},`attachFunctions`),En=t(e=>e.replace(/^\s*%%(?!{)[^\n]+\n?/gm,``).trimStart(),`cleanupComments`);function Dn(e){let t=e.match(y);if(!t)return{text:e,metadata:{}};let n=t[1],r=_e(n?t[2].split(` +`).map(e=>e.startsWith(n)?e.slice(n.length):e).join(` +`):t[2],{schema:ve})??{};r=typeof r==`object`&&!Array.isArray(r)?r:{};let i={};return r.displayMode&&(i.displayMode=r.displayMode.toString()),r.title&&(i.title=r.title.toString()),r.config&&(i.config=r.config),{text:e.slice(t[0].length),metadata:i}}t(Dn,`extractFrontMatter`);var On=t(e=>e.replace(/\r\n?/g,` +`).replace(/<(\w+)([^>]*)>/g,(e,t,n)=>`<`+t+n.replace(/="([^"]*)"/g,`='$1'`)+`>`),`cleanupText`),kn=t(e=>{let{text:t,metadata:n}=Dn(e),{displayMode:r,title:i,config:a={}}=n;return r&&(a.gantt||={},a.gantt.displayMode=r),{title:i,config:a,text:t}},`processFrontmatter`),An=t(e=>{let t=D.detectInit(e)??{},n=D.detectDirective(e,`wrap`);return Array.isArray(n)?t.wrap=n.some(({type:e})=>e===`wrap`):n?.type===`wrap`&&(t.wrap=!0),{text:se(e),directive:t}},`processDirectives`);function jn(e){let t=kn(On(e)),n=An(t.text),r=ce(t.config,n.directive);return e=En(n.text),{code:e,title:t.title,config:r}}t(jn,`preprocessDiagram`);function Mn(e){let t=new TextEncoder().encode(e),n=Array.from(t,e=>String.fromCodePoint(e)).join(``);return btoa(n)}t(Mn,`toBase64`);var Nn=5e4,Pn=`graph TB;a[Maximum text size in diagram exceeded];style a fill:#faa`,Fn=`sandbox`,In=`loose`,Ln=`http://www.w3.org/2000/svg`,Rn=`http://www.w3.org/1999/xlink`,zn=`http://www.w3.org/1999/xhtml`,Bn=`100%`,Vn=`100%`,Hn=`border:0;margin:0;`,Un=`margin:0`,Wn=`allow-top-navigation-by-user-activation allow-popups`,Gn=`The "iframe" tag is not supported by your browser.`,Kn=[`foreignobject`],qn=[`dominant-baseline`];function X(e){let t=jn(e);return c(),ee(t.config??{}),t}t(X,`processAndSetConfigs`);async function Jn(e,t){Y();try{let{code:t,config:n}=X(e);return{diagramType:(await or(t)).type,config:n}}catch(e){if(t?.suppressErrors)return!1;throw e}}t(Jn,`parse`);var Yn=t((e,t,n=[])=>`.${e} ${t} ${l(`{ ${n.join(` !important; `)} !important; }`)}`,`cssImportantStyles`),Xn=t((e,t=new Map)=>{let n=new CSSStyleSheet;if(e.fontFamily!==void 0&&n.insertRule(`:root { --mermaid-font-family: ${e.fontFamily}}`,n.cssRules.length),e.altFontFamily!==void 0&&n.insertRule(`:root { --mermaid-alt-font-family: ${e.altFontFamily}}`,n.cssRules.length),t instanceof Map){let r=m(e)?[`> *`,`span`]:[`rect`,`polygon`,`ellipse`,`circle`,`path`];t.forEach(e=>{be(e.styles)||r.forEach(t=>{n.insertRule(Yn(e.id,t,e.styles),n.cssRules.length)}),be(e.textStyles)||n.insertRule(Yn(e.id,`tspan`,(e?.textStyles||[]).map(e=>e.replace(`color`,`fill`))),n.cssRules.length)})}let r=``;if(e.themeCSS!==void 0)if(typeof n.replaceSync==`function`){let t=new CSSStyleSheet;t.replaceSync(e.themeCSS),r=C(t)+` +`}else r+=`${e.themeCSS} +`;return r+C(n)},`createCssStyles`),Zn=t((e,n)=>Ue(ze(`${e}{${n}}`),Ge([t(function(t,n,i,a){if(t.type===`rule`&&Array.isArray(t.props)){if(t.parent&&t.parent.type===`@keyframes`)return;t.props=t.props.map(t=>t.startsWith(e)?t:`${e} ${t}`)}else t.type.startsWith(`@`)&&([`@media`,`@supports`,`@layer`,`@scope`,`@container`,`@starting-style`,`@keyframes`].includes(t.type)||(r.warn(`Removing unsupported at-rule ${t.type} from CSS`),t.type=O))},`addNamespace`),We])),`compileCSS`),Qn=t((e,t,n,r)=>Zn(r,_(t,Xn(e,n),{...e.themeVariables,theme:e.theme,look:e.look},r)),`createUserStyles`),$n=t((e=``,t,n)=>{let r=e;return!n&&!t&&(r=r.replace(/marker-end="url\([\d+./:=?A-Za-z-]*?#/g,`marker-end="url(#`)),r=oe(r),r=r.replace(/
    /g,`
    `),r},`cleanUpSvgCode`),er=t((e=``,t)=>``,`putIntoIFrame`),tr=t((e,t,n,r,i)=>{let a=e.append(`div`);a.attr(`id`,n),r&&a.attr(`style`,r);let o=a.append(`svg`).attr(`id`,t).attr(`width`,`100%`).attr(`xmlns`,Ln);return i&&o.attr(`xmlns:xlink`,i),o.append(`g`),e},`appendDivSvgG`);function nr(e,t){return e.append(`iframe`).attr(`id`,t).attr(`style`,`width: 100%; height: 100%;`).attr(`sandbox`,``)}t(nr,`sandboxedIframe`);var rr=t((e,t,n,r)=>{e.getElementById(t)?.remove(),e.getElementById(n)?.remove(),e.getElementById(r)?.remove()},`removeExistingElements`),ir=t(async function(e,n,o){Y();let s=X(n);n=s.code;let c=b();r.debug(c),n.length>(c?.maxTextSize??Nn)&&(n=Pn);let l=`#${e}`,u=`i`+e,d=`#`+u,f=`d`+e,p=`#`+f,m=t(()=>{let e=i(g?d:p).node();e&&`remove`in e&&e.remove()},`removeTempElements`),h=i(document.body),g=c.securityLevel===Fn,_=c.securityLevel===In,v=c.fontFamily;o===void 0?(rr(document,e,f,u),g?(h=i(nr(i(document.body),u).nodes()[0].contentDocument.body),h.node().style.margin=`0`):h=i(`body`),tr(h,e,f)):(o&&(o.innerHTML=``),g?(h=i(nr(i(o),u).nodes()[0].contentDocument.body),h.node().style.margin=`0`):h=i(o),tr(h,e,f,`font-family: ${v}`,Rn));let y,x;try{y=await Cn.fromText(n,{title:s.title})}catch(e){if(c.suppressErrorRendering)throw m(),e;y=await Cn.fromText(`error`),x=e}let C=h.select(p).node(),w=y.type,ee=C.firstChild,T=ee.firstChild,te=y.renderer.getClasses?.(n,y),ne=Qn(c,w,te,l),re=document.createElement(`style`);re.innerHTML=ne,ee.insertBefore(re,T);try{await y.renderer.draw(n,e,`11.16.0`,y)}catch(t){throw c.suppressErrorRendering?m():kt.draw(n,e,`11.16.0`),t}let ie=h.select(`${p} svg`),ae=y.db.getAccTitle?.(),oe=y.db.getAccDescription?.();sr(w,ie,ae,oe),h.select(`[id="${e}"]`).selectAll(`foreignobject > *`).attr(`xmlns`,zn);let E=h.select(p).node().innerHTML;if(r.debug(`config.arrowMarkerAbsolute`,c.arrowMarkerAbsolute),E=$n(E,g,S(c.arrowMarkerAbsolute)),g){let e=h.select(p+` svg`).node();E=er(E,e)}else _||(E=a.sanitize(E,{ADD_TAGS:Kn,ADD_ATTR:qn,HTML_INTEGRATION_POINTS:{foreignobject:!0}}));if(Tn(),x)throw x;return m(),{diagramType:w,svg:E,bindFunctions:y.db.bindFunctions}},`render`);function ar(e={}){let t=ne({},e);t?.fontFamily&&!t.themeVariables?.fontFamily&&(t.themeVariables||={},t.themeVariables.fontFamily=t.fontFamily),h(t),t?.theme&&t.theme in v?t.themeVariables=v[t.theme].getThemeVariables(t.themeVariables):t&&(t.themeVariables=v.default.getThemeVariables(t.themeVariables)),n((typeof t==`object`?te(t):s()).logLevel),Y()}t(ar,`initialize`);var or=t((e,t={})=>{let{code:n}=jn(e);return Cn.fromText(n,t)},`getDiagramFromText`);function sr(e,t,n,r){xn(t,e),Sn(t,n,r,t.attr(`id`))}t(sr,`addA11yInfo`);var Z=Object.freeze({render:ir,parse:Jn,getDiagramFromText:or,initialize:ar,getConfig:b,setConfig:g,getSiteConfig:s,updateSiteConfig:f,reset:t(()=>{c()},`reset`),globalReset:t(()=>{c(ie)},`globalReset`),defaultConfig:ie});n(b().logLevel),c(b());var cr=t((e,t,n)=>{r.warn(e),E(e)?(n&&n(e.str,e.hash),t.push({...e,message:e.str,error:e})):(n&&n(e),e instanceof Error&&t.push({str:e.message,message:e.message,hash:e.name,error:e}))},`handleError`),lr=t(async function(e={querySelector:`.mermaid`}){try{await ur(e)}catch(t){if(E(t)&&r.error(t.str),$.parseError&&$.parseError(t),!e.suppressErrors)throw r.error(`Use the suppressErrors option to suppress these errors`),t}},`run`),ur=t(async function({postRenderCallback:e,querySelector:t,nodes:n}={querySelector:`.mermaid`}){let i=Z.getConfig();r.debug(`${e?``:`No `}Callback function found`);let a;if(n)a=n;else if(t)a=document.querySelectorAll(t);else throw Error(`Nodes and querySelector are both undefined`);r.debug(`Found ${a.length} diagrams`),i?.startOnLoad!==void 0&&(r.debug(`Start On Load: `+i?.startOnLoad),Z.updateSiteConfig({startOnLoad:i?.startOnLoad}));let o=new D.InitIDGenerator(i.deterministicIds,i.deterministicIDSeed),s,c=[];for(let t of Array.from(a)){if(r.info(`Rendering diagram: `+t.id),t.getAttribute(`data-processed`))continue;t.setAttribute(`data-processed`,`true`);let n=`mermaid-${o.next()}`;s=t.innerHTML,s=he(D.entityDecode(s)).trim().replace(//gi,`
    `);let i=D.detectInit(s);i&&r.debug(`Detected early reinit: `,i);try{let{svg:r,bindFunctions:i}=await yr(n,s,t);t.innerHTML=r,e&&await e(n),i&&i(t)}catch(e){cr(e,c,$.parseError)}}if(c.length>0)throw c[0]},`runThrowsErrors`),dr=t(function(e){Z.initialize(e)},`initialize`),fr=t(async function(e,t,n){r.warn(`mermaid.init is deprecated. Please use run instead.`),e&&dr(e);let i={postRenderCallback:n,querySelector:`.mermaid`};typeof t==`string`?i.querySelector=t:t&&(t instanceof HTMLElement?i.nodes=[t]:i.nodes=t),await lr(i)},`init`),pr=t(async(e,{lazyLoad:t=!0}={})=>{Y(),d(...e),t===!1&&await yn()},`registerExternalDiagrams`),mr=t(function(){if($.startOnLoad){let{startOnLoad:e}=Z.getConfig();e&&$.run().catch(e=>r.error(`Mermaid failed to initialize`,e))}},`contentLoaded`);typeof document<`u`&&window.addEventListener(`load`,mr,!1);var hr=t(function(e){$.parseError=e},`setParseErrorHandler`),Q=[],gr=!1,_r=t(async()=>{if(!gr){for(gr=!0;Q.length>0;){let e=Q.shift();if(e)try{await e()}catch(e){r.error(`Error executing queue`,e)}}gr=!1}},`executeQueue`),vr=t(async(e,n)=>new Promise((i,a)=>{let o=t(()=>new Promise((t,o)=>{Z.parse(e,n).then(e=>{t(e),i(e)},e=>{r.error(`Error parsing`,e),$.parseError?.(e),o(e),a(e)})}),`performCall`);Q.push(o),_r().catch(a)}),`parse`),yr=t((e,n,i)=>new Promise((a,o)=>{let s=t(()=>new Promise((t,s)=>{Z.render(e,n,i).then(e=>{t(e),a(e)},e=>{r.error(`Error parsing`,e),$.parseError?.(e),s(e),o(e)})}),`performCall`);Q.push(s),_r().catch(o)}),`render`),$={startOnLoad:!0,mermaidAPI:Z,parse:vr,render:yr,init:fr,run:lr,registerExternalDiagrams:pr,registerLayoutLoaders:ge,initialize:dr,parseError:void 0,contentLoaded:mr,setParseErrorHandler:hr,detectType:T,registerIconPacks:me,getRegisteredDiagramsMetadata:t(()=>Object.keys(w).map(e=>({id:e})),`getRegisteredDiagramsMetadata`)},br=$;export{br as default}; \ No newline at end of file diff --git a/dist-desktop/assets/mindmap-definition-LN4V7U3C-Bib4remL.js b/dist-desktop/assets/mindmap-definition-LN4V7U3C-Bib4remL.js new file mode 100644 index 0000000..c25c0b2 --- /dev/null +++ b/dist-desktop/assets/mindmap-definition-LN4V7U3C-Bib4remL.js @@ -0,0 +1,96 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{b as n,et as r,f as i,k as a,rt as o,tt as s,x as c,z as l}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import{t as u}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as d}from"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import{r as f,t as p}from"./chunk-FWX5IMBZ-ComLEIwh.js";var m=[];for(let e=0;e<256;++e)m.push((e+256).toString(16).slice(1));function h(e,t=0){return(m[e[t+0]]+m[e[t+1]]+m[e[t+2]]+m[e[t+3]]+`-`+m[e[t+4]]+m[e[t+5]]+`-`+m[e[t+6]]+m[e[t+7]]+`-`+m[e[t+8]]+m[e[t+9]]+`-`+m[e[t+10]]+m[e[t+11]]+m[e[t+12]]+m[e[t+13]]+m[e[t+14]]+m[e[t+15]]).toLowerCase()}var g=new Uint8Array(16);function _(){return crypto.getRandomValues(g)}function v(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():y(e,t,n)}function y(e,t,n){e||={};let r=e.random??e.rng?.()??_();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return h(r)}var b=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,13],i=[1,12],a=[1,15],o=[1,16],s=[1,20],c=[1,19],l=[6,7,8],u=[1,26],d=[1,24],f=[1,25],p=[6,7,11],m=[1,6,13,15,16,19,22],h=[1,33],g=[1,34],_=[1,6,7,11,13,15,16,19,22],v={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mindMap:4,spaceLines:5,SPACELINE:6,NL:7,MINDMAP:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,node:14,ICON:15,CLASS:16,nodeWithId:17,nodeWithoutId:18,NODE_DSTART:19,NODE_DESCR:20,NODE_DEND:21,NODE_ID:22,$accept:0,$end:1},terminals_:{2:`error`,6:`SPACELINE`,7:`NL`,8:`MINDMAP`,11:`EOF`,13:`SPACELIST`,15:`ICON`,16:`CLASS`,19:`NODE_DSTART`,20:`NODE_DESCR`,21:`NODE_DEND`,22:`NODE_ID`},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,2],[12,2],[12,2],[12,1],[12,1],[12,1],[12,1],[12,1],[14,1],[14,1],[18,3],[17,1],[17,4]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 6:case 7:return r;case 8:r.getLogger().trace(`Stop NL `);break;case 9:r.getLogger().trace(`Stop EOF `);break;case 11:r.getLogger().trace(`Stop NL2 `);break;case 12:r.getLogger().trace(`Stop EOF2 `);break;case 15:r.getLogger().info(`Node: `,a[s].id),r.addNode(a[s-1].length,a[s].id,a[s].descr,a[s].type);break;case 16:r.getLogger().trace(`Icon: `,a[s]),r.decorateNode({icon:a[s]});break;case 17:case 21:r.decorateNode({class:a[s]});break;case 18:r.getLogger().trace(`SPACELIST`);break;case 19:r.getLogger().trace(`Node: `,a[s].id),r.addNode(0,a[s].id,a[s].descr,a[s].type);break;case 20:r.decorateNode({icon:a[s]});break;case 25:r.getLogger().trace(`node found ..`,a[s-2]),this.$={id:a[s-1],descr:a[s-1],type:r.getType(a[s-2],a[s])};break;case 26:this.$={id:a[s],descr:a[s],type:r.nodeType.DEFAULT};break;case 27:r.getLogger().trace(`node found ..`,a[s-3]),this.$={id:a[s-3],descr:a[s-1],type:r.getType(a[s-2],a[s])};break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],8:n},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:n},{6:r,7:[1,10],9:9,12:11,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},t(l,[2,3]),{1:[2,2]},t(l,[2,4]),t(l,[2,5]),{1:[2,6],6:r,12:21,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},{6:r,9:22,12:11,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},{6:u,7:d,10:23,11:f},t(p,[2,22],{17:17,18:18,14:27,15:[1,28],16:[1,29],19:s,22:c}),t(p,[2,18]),t(p,[2,19]),t(p,[2,20]),t(p,[2,21]),t(p,[2,23]),t(p,[2,24]),t(p,[2,26],{19:[1,30]}),{20:[1,31]},{6:u,7:d,10:32,11:f},{1:[2,7],6:r,12:21,13:i,14:14,15:a,16:o,17:17,18:18,19:s,22:c},t(m,[2,14],{7:h,11:g}),t(_,[2,8]),t(_,[2,9]),t(_,[2,10]),t(p,[2,15]),t(p,[2,16]),t(p,[2,17]),{20:[1,35]},{21:[1,36]},t(m,[2,13],{7:h,11:g}),t(_,[2,11]),t(_,[2,12]),{21:[1,37]},t(p,[2,25]),t(p,[2,27])],defaultActions:{2:[2,1],6:[2,2]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};v.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:return e.getLogger().trace(`Found comment`,t.yytext),6;case 1:return 8;case 2:this.begin(`CLASS`);break;case 3:return this.popState(),16;case 4:this.popState();break;case 5:e.getLogger().trace(`Begin icon`),this.begin(`ICON`);break;case 6:return e.getLogger().trace(`SPACELINE`),6;case 7:return 7;case 8:return 15;case 9:e.getLogger().trace(`end icon`),this.popState();break;case 10:return e.getLogger().trace(`Exploding node`),this.begin(`NODE`),19;case 11:return e.getLogger().trace(`Cloud`),this.begin(`NODE`),19;case 12:return e.getLogger().trace(`Explosion Bang`),this.begin(`NODE`),19;case 13:return e.getLogger().trace(`Cloud Bang`),this.begin(`NODE`),19;case 14:return this.begin(`NODE`),19;case 15:return this.begin(`NODE`),19;case 16:return this.begin(`NODE`),19;case 17:return this.begin(`NODE`),19;case 18:return 13;case 19:return 22;case 20:return 11;case 21:this.begin(`NSTR2`);break;case 22:return`NODE_DESCR`;case 23:this.popState();break;case 24:e.getLogger().trace(`Starting NSTR`),this.begin(`NSTR`);break;case 25:return e.getLogger().trace(`description:`,t.yytext),`NODE_DESCR`;case 26:this.popState();break;case 27:return this.popState(),e.getLogger().trace(`node end ))`),`NODE_DEND`;case 28:return this.popState(),e.getLogger().trace(`node end )`),`NODE_DEND`;case 29:return this.popState(),e.getLogger().trace(`node end ...`,t.yytext),`NODE_DEND`;case 30:return this.popState(),e.getLogger().trace(`node end ((`),`NODE_DEND`;case 31:return this.popState(),e.getLogger().trace(`node end (-`),`NODE_DEND`;case 32:return this.popState(),e.getLogger().trace(`node end (-`),`NODE_DEND`;case 33:return this.popState(),e.getLogger().trace(`node end ((`),`NODE_DEND`;case 34:return this.popState(),e.getLogger().trace(`node end ((`),`NODE_DEND`;case 35:return e.getLogger().trace(`Long description:`,t.yytext),20;case 36:return e.getLogger().trace(`Long description:`,t.yytext),20}},`anonymous`),rules:[/^(?:\s*%%.*)/i,/^(?:mindmap\b)/i,/^(?::::)/i,/^(?:.+)/i,/^(?:\n)/i,/^(?:::icon\()/i,/^(?:[\s]+[\n])/i,/^(?:[\n]+)/i,/^(?:[^\)]+)/i,/^(?:\))/i,/^(?:-\))/i,/^(?:\(-)/i,/^(?:\)\))/i,/^(?:\))/i,/^(?:\(\()/i,/^(?:\{\{)/i,/^(?:\()/i,/^(?:\[)/i,/^(?:[\s]+)/i,/^(?:[^\(\[\n\)\{\}]+)/i,/^(?:$)/i,/^(?:["][`])/i,/^(?:[^`"]+)/i,/^(?:[`]["])/i,/^(?:["])/i,/^(?:[^"]+)/i,/^(?:["])/i,/^(?:[\)]\))/i,/^(?:[\)])/i,/^(?:[\]])/i,/^(?:\}\})/i,/^(?:\(-)/i,/^(?:-\))/i,/^(?:\(\()/i,/^(?:\()/i,/^(?:[^\)\]\(\}]+)/i,/^(?:.+(?!\(\())/i],conditions:{CLASS:{rules:[3,4],inclusive:!1},ICON:{rules:[8,9],inclusive:!1},NSTR2:{rules:[22,23],inclusive:!1},NSTR:{rules:[25,26],inclusive:!1},NODE:{rules:[21,24,27,28,29,30,31,32,33,34,35,36],inclusive:!1},INITIAL:{rules:[0,1,2,5,6,7,10,11,12,13,14,15,16,17,18,19,20],inclusive:!0}}}})();function y(){this.yy={}}return e(y,`Parser`),y.prototype=v,v.Parser=y,new y})();b.parser=b;var x=b,S=12,C={DEFAULT:0,NO_BORDER:0,ROUNDED_RECT:1,RECT:2,CIRCLE:3,CLOUD:4,BANG:5,HEXAGON:6},w=class{constructor(){this.nodes=[],this.count=0,this.elements={},this.getLogger=this.getLogger.bind(this),this.nodeType=C,this.clear(),this.getType=this.getType.bind(this),this.getElementById=this.getElementById.bind(this),this.getParent=this.getParent.bind(this),this.getMindmap=this.getMindmap.bind(this),this.addNode=this.addNode.bind(this),this.decorateNode=this.decorateNode.bind(this)}static{e(this,`MindmapDB`)}clear(){this.nodes=[],this.count=0,this.elements={},this.baseLevel=void 0}getParent(e){for(let t=this.nodes.length-1;t>=0;t--)if(this.nodes[t].level0?this.nodes[0]:null}addNode(e,n,r,a){t.info(`addNode`,e,n,r,a);let o=!1;this.nodes.length===0?(this.baseLevel=e,e=0,o=!0):this.baseLevel!==void 0&&(e-=this.baseLevel,o=!1);let s=c(),u=s.mindmap?.padding??i.mindmap.padding;switch(a){case this.nodeType.ROUNDED_RECT:case this.nodeType.RECT:case this.nodeType.HEXAGON:u*=2;break}let d={id:this.count++,nodeId:l(n,s),level:e,descr:l(r,s),type:a,children:[],width:s.mindmap?.maxNodeWidth??i.mindmap.maxNodeWidth,padding:u,isRoot:o},f=this.getParent(e);if(f)f.children.push(d),this.nodes.push(d);else if(o)this.nodes.push(d);else throw Error(`There can be only one root. No parent could be found for ("${d.descr}")`)}getType(e,n){switch(t.debug(`In get type`,e,n),e){case`[`:return this.nodeType.RECT;case`(`:return n===`)`?this.nodeType.ROUNDED_RECT:this.nodeType.CLOUD;case`((`:return this.nodeType.CIRCLE;case`)`:return this.nodeType.CLOUD;case`))`:return this.nodeType.BANG;case`{{`:return this.nodeType.HEXAGON;default:return this.nodeType.DEFAULT}}setElementForId(e,t){this.elements[e]=t}getElementById(e){return this.elements[e]}decorateNode(e){if(!e)return;let t=c(),n=this.nodes[this.nodes.length-1];e.icon&&(n.icon=l(e.icon,t)),e.class&&(n.class=l(e.class,t))}type2Str(e){switch(e){case this.nodeType.DEFAULT:return`no-border`;case this.nodeType.RECT:return`rect`;case this.nodeType.ROUNDED_RECT:return`rounded-rect`;case this.nodeType.CIRCLE:return`circle`;case this.nodeType.CLOUD:return`cloud`;case this.nodeType.BANG:return`bang`;case this.nodeType.HEXAGON:return`hexgon`;default:return`no-border`}}assignSections(e,t){if(e.level===0?e.section=void 0:e.section=t,e.children)for(let[n,r]of e.children.entries()){let i=e.level===0?n%(S-1):t;this.assignSections(r,i)}}flattenNodes(t,n){let r=c(),i=[`mindmap-node`];t.isRoot===!0?i.push(`section-root`,`section--1`):t.section!==void 0&&i.push(`section-${t.section}`),t.class&&i.push(t.class);let a=i.join(` `),o=e(e=>{let t=(r.theme?.toLowerCase()??``).includes(`redux`);switch(e){case C.CIRCLE:return`mindmapCircle`;case C.RECT:return`rect`;case C.ROUNDED_RECT:return`rounded`;case C.CLOUD:return`cloud`;case C.BANG:return`bang`;case C.HEXAGON:return`hexagon`;case C.DEFAULT:return t?`rounded`:`defaultMindmapNode`;case C.NO_BORDER:default:return`rect`}},`getShapeFromType`),s={id:t.id.toString(),domId:`node_`+t.id.toString(),label:t.descr,labelType:`markdown`,isGroup:!1,shape:o(t.type),width:t.width,height:t.height??0,padding:t.padding,cssClasses:a,cssStyles:[],look:r.look,icon:t.icon,x:t.x,y:t.y,level:t.level,nodeId:t.nodeId,type:t.type,section:t.section};if(n.push(s),t.children)for(let e of t.children)this.flattenNodes(e,n)}generateEdges(e,t){if(!e.children)return;let n=c();for(let r of e.children){let i=`edge`;r.section!==void 0&&(i+=` section-edge-${r.section}`);let a=e.level+1;i+=` edge-depth-${a}`;let o={id:`edge_${e.id}_${r.id}`,start:e.id.toString(),end:r.id.toString(),type:`normal`,curve:`basis`,thickness:`normal`,look:n.look,classes:i,depth:e.level,section:r.section};t.push(o),this.generateEdges(r,t)}}getData(){let e=this.getMindmap(),n=c(),r=a().layout!==void 0,i=n;if(r||(i.layout=`cose-bilkent`),!e)return{nodes:[],edges:[],config:i};t.debug(`getData: mindmapRoot`,e,n),this.assignSections(e);let o=[],s=[];this.flattenNodes(e,o),this.generateEdges(e,s),t.debug(`getData: processed ${o.length} nodes and ${s.length} edges`);let l=new Map;for(let e of o)l.set(e.id,{shape:e.shape,width:e.width,height:e.height,padding:e.padding});return{nodes:o,edges:s,config:i,rootNode:e,markers:[`point`],direction:`TB`,nodeSpacing:50,rankSpacing:50,shapes:Object.fromEntries(l),type:`mindmap`,diagramId:`mindmap-`+v()}}getLogger(){return t}},T={draw:e(async(e,r,a,o)=>{t.debug(`Rendering mindmap diagram +`+e);let s=o.db,c=s.getData(),l=u(r,c.config.securityLevel);if(c.type=o.type,c.layoutAlgorithm=p(c.config.layout,{fallback:`cose-bilkent`}),c.diagramId=r,!s.getMindmap())return;c.nodes.forEach(e=>{e.shape===`rounded`?(e.radius=15,e.taper=15,e.stroke=`none`,e.width=0,e.padding=15):e.shape===`circle`?e.padding=10:e.shape===`rect`?(e.width=0,e.padding=10):e.shape===`hexagon`&&(e.width=0,e.height=0)}),await f(c,l);let{themeVariables:m}=n(),{useGradient:h,gradientStart:g,gradientStop:_}=m;if(h&&g&&_){let e=l.attr(`id`),t=l.append(`defs`).append(`linearGradient`).attr(`id`,`${e}-gradient`).attr(`gradientUnits`,`objectBoundingBox`).attr(`x1`,`0%`).attr(`y1`,`0%`).attr(`x2`,`100%`).attr(`y2`,`0%`);t.append(`stop`).attr(`offset`,`0%`).attr(`stop-color`,g).attr(`stop-opacity`,1),t.append(`stop`).attr(`offset`,`100%`).attr(`stop-color`,_).attr(`stop-opacity`,1)}d(l,c.config.mindmap?.padding??i.mindmap.padding,`mindmapDiagram`,c.config.mindmap?.useMaxWidth??i.mindmap.useMaxWidth)},`draw`)},E=e(e=>{let{theme:t,look:n}=e,i=``;for(let t=0;t{let r=``;for(let i=0;i{let{theme:t}=e,n=e.svgId,r=e.dropShadow?e.dropShadow.replace(`url(#drop-shadow)`,`url(${n}-drop-shadow)`):`none`;return` + .edge { + stroke-width: 3; + } + ${E(e)} + .section-root rect, .section-root path, .section-root circle, .section-root polygon { + fill: ${e.git0}; + } + .section-root text { + fill: ${e.gitBranchLabel0}; + } + .section-root span { + color: ${t?.includes(`redux`)?e.nodeBorder:e.gitBranchLabel0}; + } + .icon-container { + height:100%; + display: flex; + justify-content: center; + align-items: center; + } + .edge { + fill: none; + } + .mindmap-node-label { + dy: 1em; + alignment-baseline: middle; + text-anchor: middle; + dominant-baseline: middle; + text-align: center; + } + [data-look="neo"].mindmap-node { + filter: ${r}; + } + [data-look="neo"].mindmap-node.section-root rect, [data-look="neo"].mindmap-node.section-root path, [data-look="neo"].mindmap-node.section-root circle, [data-look="neo"].mindmap-node.section-root polygon { + fill: ${t?.includes(`redux`)?e.mainBkg:e.git0}; + } + [data-look="neo"].mindmap-node.section-root .text-inner-tspan { + fill: ${t?.includes(`redux`)?e.nodeBorder:e[`cScaleLabel`+ +(t===`neutral`)]}; + } + ${e.useGradient&&n&&e.mainBkg?D(e.THEME_COLOR_LIMIT,n,e.mainBkg):``} +`},`getStyles`)};export{O as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/ordinal-hYBb2elL.js b/dist-desktop/assets/ordinal-hYBb2elL.js new file mode 100644 index 0000000..d5570ec --- /dev/null +++ b/dist-desktop/assets/ordinal-hYBb2elL.js @@ -0,0 +1 @@ +import{t as e}from"./init-D6jRqBbL.js";var t=class extends Map{constructor(e,t=a){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:t}}),e!=null)for(let[t,n]of e)this.set(t,n)}get(e){return super.get(n(this,e))}has(e){return super.has(n(this,e))}set(e,t){return super.set(r(this,e),t)}delete(e){return super.delete(i(this,e))}};function n({_intern:e,_key:t},n){let r=t(n);return e.has(r)?e.get(r):n}function r({_intern:e,_key:t},n){let r=t(n);return e.has(r)?e.get(r):(e.set(r,n),n)}function i({_intern:e,_key:t},n){let r=t(n);return e.has(r)&&(n=e.get(r),e.delete(r)),n}function a(e){return typeof e==`object`&&e?e.valueOf():e}var o=Symbol(`implicit`);function s(){var n=new t,r=[],i=[],a=o;function c(e){let t=n.get(e);if(t===void 0){if(a!==o)return a;n.set(e,t=r.push(e)-1)}return i[t%i.length]}return c.domain=function(e){if(!arguments.length)return r.slice();r=[],n=new t;for(let t of e)n.has(t)||n.set(t,r.push(t)-1);return c},c.range=function(e){return arguments.length?(i=Array.from(e),c):i.slice()},c.unknown=function(e){return arguments.length?(a=e,c):a},c.copy=function(){return s(r,i).unknown(a)},e.apply(c,arguments),c}export{s as t}; \ No newline at end of file diff --git a/dist-desktop/assets/packet-7NZHBO7P-D2duWGIK.js b/dist-desktop/assets/packet-7NZHBO7P-D2duWGIK.js new file mode 100644 index 0000000..848b89d --- /dev/null +++ b/dist-desktop/assets/packet-7NZHBO7P-D2duWGIK.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-EMLP6XTP-BoneA0Uo.js";export{e as createPacketServices}; \ No newline at end of file diff --git a/dist-desktop/assets/path-BWPyau1x.js b/dist-desktop/assets/path-BWPyau1x.js new file mode 100644 index 0000000..63d59fc --- /dev/null +++ b/dist-desktop/assets/path-BWPyau1x.js @@ -0,0 +1 @@ +var e=Math.PI,t=2*e,n=1e-6,r=t-n;function i(e){this._+=e[0];for(let t=1,n=e.length;t=0))throw Error(`invalid digits: ${e}`);if(t>15)return i;let n=10**t;return function(e){this._+=e[0];for(let t=1,r=e.length;tn)if(!(Math.abs(f*l-u*d)>n)||!o)this._append`L${this._x1=t},${this._y1=r}`;else{let m=i-s,h=a-c,g=l*l+u*u,_=m*m+h*h,v=Math.sqrt(g),y=Math.sqrt(p),b=o*Math.tan((e-Math.acos((g+p-_)/(2*v*y)))/2),x=b/y,S=b/v;Math.abs(x-1)>n&&this._append`L${t+x*d},${r+x*f}`,this._append`A${o},${o},0,0,${+(f*m>d*h)},${this._x1=t+S*l},${this._y1=r+S*u}`}}arc(i,a,o,s,c,l){if(i=+i,a=+a,o=+o,l=!!l,o<0)throw Error(`negative radius: ${o}`);let u=o*Math.cos(s),d=o*Math.sin(s),f=i+u,p=a+d,m=1^l,h=l?s-c:c-s;this._x1===null?this._append`M${f},${p}`:(Math.abs(this._x1-f)>n||Math.abs(this._y1-p)>n)&&this._append`L${f},${p}`,o&&(h<0&&(h=h%t+t),h>r?this._append`A${o},${o},0,1,${m},${i-u},${a-d}A${o},${o},0,1,${m},${this._x1=f},${this._y1=p}`:h>n&&this._append`A${o},${o},0,${+(h>=e)},${m},${this._x1=i+o*Math.cos(c)},${this._y1=a+o*Math.sin(c)}`)}rect(e,t,n,r){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}h${n=+n}v${+r}h${-n}Z`}toString(){return this._}};function s(){return new o}s.prototype=o.prototype;function c(e){return function(){return e}}function l(e){let t=3;return e.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{let e=Math.floor(n);if(!(e>=0))throw RangeError(`invalid digits: ${n}`);t=e}return e},()=>new o(t)}export{c as n,l as t}; \ No newline at end of file diff --git a/dist-desktop/assets/pegDiagram-2B236MQR-CPt8QfP3.js b/dist-desktop/assets/pegDiagram-2B236MQR-CPt8QfP3.js new file mode 100644 index 0000000..1516455 --- /dev/null +++ b/dist-desktop/assets/pegDiagram-2B236MQR-CPt8QfP3.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-JG7HCLWE-Dk4_aECj.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-Bju_yCKi.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-Z7xZAZRH.js";var c=e().RailroadPeg.parser.LangiumParser,l=t(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformOrderedChoice`),u=t(e=>{let t=e.elements.map(d);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformSequence`),d=t(e=>{let t=p(e.suffix);return e.operator?{type:`special`,text:e.operator===`&`?`&${f(t)}`:`!${f(t)}`}:t},`transformPrefix`),f=t(e=>{switch(e.type){case`terminal`:return`"${e.value}"`;case`nonterminal`:return e.name;case`special`:return e.text;default:return`(...)`}},`nodeToLabel`),p=t(e=>{let t=m(e.primary);if(!e.operator)return t;switch(e.operator){case`?`:return{type:`optional`,element:t};case`*`:return{type:`repetition`,element:t,min:0,max:1/0};case`+`:return{type:`repetition`,element:t,min:1,max:1/0};default:throw Error(`Unsupported PEG suffix operator: ${e.operator}`)}},`transformSuffix`),m=t(e=>{switch(e.$type){case`PegLiteral`:return{type:`terminal`,value:e.value};case`PegIdentifier`:return{type:`nonterminal`,name:e.name};case`PegGroup`:return l(e.element);case`PegAny`:return{type:`special`,text:e.dot};default:throw Error(`Unsupported PEG primary node: ${e.$type}`)}},`transformPrimary`),h=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),g=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(h(e)))},`populateDb`),_={parser:{parse:t(e=>{a.clear(),n.debug(`[PEG Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[PEG Parser] Parsed rules:`,r.rules.length),g(r),n.debug(`[PEG Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{_ as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/pie-RZYD4A2V-CynqTUkZ.js b/dist-desktop/assets/pie-RZYD4A2V-CynqTUkZ.js new file mode 100644 index 0000000..3bf5cfd --- /dev/null +++ b/dist-desktop/assets/pie-RZYD4A2V-CynqTUkZ.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-YOTPTUD7-CjHV8V6f.js";export{e as createPieServices}; \ No newline at end of file diff --git a/dist-desktop/assets/pieDiagram-ENE6RG2P-BBPaHS9V.js b/dist-desktop/assets/pieDiagram-ENE6RG2P-BBPaHS9V.js new file mode 100644 index 0000000..26f2daf --- /dev/null +++ b/dist-desktop/assets/pieDiagram-ENE6RG2P-BBPaHS9V.js @@ -0,0 +1,39 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,c as o,f as s,v as c,w as l,x as u,y as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as f}from"./ordinal-hYBb2elL.js";import{n as p}from"./path-BWPyau1x.js";import{m}from"./dist-qx0Iv9vM.js";import{t as h}from"./arc-DqK6O3qL.js";import{t as g}from"./array-BifhSqXX.js";import{i as _,p as v}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as y}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as b}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as x}from"./mermaid-parser.core-Z7xZAZRH.js";function S(e,t){return te?1:t>=e?0:NaN}function C(e){return e}function w(){var e=C,t=S,n=null,r=p(0),i=p(m),a=p(0);function o(o){var s,c=(o=g(o)).length,l,u,d=0,f=Array(c),p=Array(c),h=+r.apply(this,arguments),_=Math.min(m,Math.max(-m,i.apply(this,arguments)-h)),v,y=Math.min(Math.abs(_)/c,a.apply(this,arguments)),b=y*(_<0?-1:1),x;for(s=0;s0&&(d+=x);for(t==null?n!=null&&f.sort(function(e,t){return n(o[e],o[t])}):f.sort(function(e,n){return t(p[e],p[n])}),s=0,u=d?(_-c*b)/d:0;s0?x*u:0)+b,p[l]={data:o[l],index:s,value:x,startAngle:h,endAngle:v,padAngle:y};return p}return o.value=function(t){return arguments.length?(e=typeof t==`function`?t:p(+t),o):e},o.sortValues=function(e){return arguments.length?(t=e,n=null,o):t},o.sort=function(e){return arguments.length?(n=e,t=null,o):n},o.startAngle=function(e){return arguments.length?(r=typeof e==`function`?e:p(+e),o):r},o.endAngle=function(e){return arguments.length?(i=typeof e==`function`?e:p(+e),o):i},o.padAngle=function(e){return arguments.length?(a=typeof e==`function`?e:p(+e),o):a},o}var T=s.pie,E={sections:new Map,showData:!1,config:T},D=E.sections,O=E.showData,k=structuredClone(T),A={getConfig:e(()=>structuredClone(k),`getConfig`),clear:e(()=>{D=new Map,O=E.showData,a()},`clear`),setDiagramTitle:r,getDiagramTitle:l,setAccTitle:i,getAccTitle:d,setAccDescription:n,getAccDescription:c,addSection:e(({label:e,value:n})=>{if(n<0)throw Error(`"${e}" has invalid value: ${n}. Negative values are not allowed in pie charts. All slice values must be >= 0.`);D.has(e)||(D.set(e,n),t.debug(`added new section: ${e}, with value: ${n}`))},`addSection`),getSections:e(()=>D,`getSections`),setShowData:e(e=>{O=e},`setShowData`),getShowData:e(()=>O,`getShowData`)},j=e((e,t)=>{b(e,t),t.setShowData(e.showData),e.sections.map(t.addSection)},`populateDb`),M={parse:e(async e=>{let n=await x(`pie`,e);t.debug(n),j(n,A)},`parse`)},N=e(e=>` + .pieCircle{ + stroke: ${e.pieStrokeColor}; + stroke-width : ${e.pieStrokeWidth}; + opacity : ${e.pieOpacity}; + } + .pieCircle.highlighted{ + scale: 1.05; + opacity: 1; + } + .pieCircle.highlightedOnHover:hover{ + transition-duration: 250ms; + scale: 1.05; + opacity: 1; + } + .pieOuterCircle{ + stroke: ${e.pieOuterStrokeColor}; + stroke-width: ${e.pieOuterStrokeWidth}; + fill: none; + } + .pieTitleText { + text-anchor: middle; + font-size: ${e.pieTitleTextSize}; + fill: ${e.pieTitleTextColor}; + font-family: ${e.fontFamily}; + } + .slice { + font-family: ${e.fontFamily}; + fill: ${e.pieSectionTextColor}; + font-size:${e.pieSectionTextSize}; + // fill: white; + } + .legend text { + fill: ${e.pieLegendTextColor}; + font-family: ${e.fontFamily}; + font-size: ${e.pieLegendTextSize}; + } +`,`getStyles`),P=e(e=>{let t=[...e.values()].reduce((e,t)=>e+t,0),n=[...e.entries()].map(([e,t])=>({label:e,value:t})).filter(e=>e.value/t*100>=1);return w().value(e=>e.value).sort(null)(n)},`createPieArcs`),F={parser:M,db:A,renderer:{draw:e((e,n,r,i)=>{t.debug(`rendering pie chart +`+e);let a=i.db,s=u(),c=_(a.getConfig(),s.pie),l=y(n),d=l.append(`g`);d.attr(`transform`,`translate(225,225)`);let{themeVariables:p}=s,[m]=v(p.pieOuterStrokeWidth);m??=2;let g=c.legendPosition,b=c.textPosition,x=c.donutHole>0&&c.donutHole<=.9?c.donutHole:0,S=h().innerRadius(x*185).outerRadius(185),C=h().innerRadius(185*b).outerRadius(185*b),w=d.append(`g`);w.append(`circle`).attr(`cx`,0).attr(`cy`,0).attr(`r`,185+m/2).attr(`class`,`pieOuterCircle`);let T=a.getSections(),E=P(T),D=[p.pie1,p.pie2,p.pie3,p.pie4,p.pie5,p.pie6,p.pie7,p.pie8,p.pie9,p.pie10,p.pie11,p.pie12],O=0;T.forEach(e=>{O+=e});let k=E.filter(e=>(e.data.value/O*100).toFixed(0)!==`0`),A=f(D).domain([...T.keys()]);w.selectAll(`mySlices`).data(k).enter().append(`path`).attr(`d`,S).attr(`fill`,e=>A(e.data.label)).attr(`class`,e=>{let t=`pieCircle`;return c.highlightSlice===`hover`?t+=` highlightedOnHover`:c.highlightSlice===e.data.label&&(t+=` highlighted`),t}),w.selectAll(`mySlices`).data(k).enter().append(`text`).text(e=>(e.data.value/O*100).toFixed(0)+`%`).attr(`transform`,e=>`translate(`+C.centroid(e)+`)`).style(`text-anchor`,`middle`).attr(`class`,`slice`);let j=d.append(`text`).text(a.getDiagramTitle()).attr(`x`,0).attr(`y`,-400/2).attr(`class`,`pieTitleText`),M=[...T.entries()].map(([e,t])=>({label:e,value:t})),N=d.selectAll(`.legend`).data(M).enter().append(`g`).attr(`class`,`legend`);N.append(`rect`).attr(`width`,18).attr(`height`,18).style(`fill`,e=>A(e.label)).style(`stroke`,e=>A(e.label)),N.append(`text`).attr(`x`,22).attr(`y`,14).text(e=>a.getShowData()?`${e.label} [${e.value}]`:e.label);let F=Math.max(...N.selectAll(`text`).nodes().map(e=>e?.getBoundingClientRect().width??0)),I=450,L=490,R=M.length*22;switch(g){case`center`:N.attr(`transform`,(e,t)=>{let n=22*M.length/2,r=-F/2-22,i=t*22-n;return`translate(`+r+`,`+i+`)`});break;case`top`:I+=R,N.attr(`transform`,(e,t)=>`translate(${-F/2-22}, ${t*22-185})`),w.attr(`transform`,()=>`translate(0, ${R+22})`);break;case`bottom`:I+=R,N.attr(`transform`,(e,t)=>{let n=-F/2-22,r=t*22- -207;return`translate(`+n+`,`+r+`)`});break;case`left`:L+=22+F,N.attr(`transform`,(e,t)=>{let n=22*M.length/2;return`translate(-207,`+(t*22-n)+`)`}),w.attr(`transform`,()=>`translate(${F+18+4}, 0)`);break;default:L+=22+F,N.attr(`transform`,(e,t)=>{let n=22*M.length/2;return`translate(216,`+(t*22-n)+`)`});break}let z=j.node()?.getBoundingClientRect().width??0,B=450/2-z/2,V=450/2+z/2,H=Math.min(0,B),U=Math.max(L,V)-H;l.attr(`viewBox`,`${H} 0 ${U} ${I}`),o(l,I,U,c.useMaxWidth)},`draw`)},styles:N};export{F as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/quadrantDiagram-ABIIQ3AL-UafGc-sH.js b/dist-desktop/assets/quadrantDiagram-ABIIQ3AL-UafGc-sH.js new file mode 100644 index 0000000..a1aa0dd --- /dev/null +++ b/dist-desktop/assets/quadrantDiagram-ABIIQ3AL-UafGc-sH.js @@ -0,0 +1,7 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{D as r,H as i,K as a,U as o,a as s,c,f as l,v as u,w as d,x as f,y as p,z as m}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as h}from"./linear-DhAcoVP9.js";var g=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,3],r=[1,4],i=[1,5],a=[1,6],o=[1,7],s=[1,4,5,10,12,13,14,15,18,25,35,37,39,41,42,48,50,51,52,53,54,55,56,57,60,61,63,64,65,66,67],c=[1,4,5,10,12,13,14,15,18,25,28,35,37,39,41,42,48,50,51,52,53,54,55,56,57,60,61,63,64,65,66,67],l=[55,56,57],u=[2,36],d=[1,37],f=[1,36],p=[1,38],m=[1,35],h=[1,43],g=[1,41],_=[1,45],v=[1,14],y=[1,23],b=[1,18],x=[1,19],S=[1,20],C=[1,21],w=[1,22],T=[1,24],E=[1,25],D=[1,26],O=[1,27],k=[1,28],A=[1,29],j=[1,32],M=[1,33],N=[1,34],P=[1,39],F=[1,40],I=[1,42],L=[1,44],R=[1,63],z=[1,62],B=[4,5,8,10,12,13,14,15,18,44,47,49,55,56,57,63,64,65,66,67],ee=[1,66],te=[1,67],ne=[1,68],re=[1,69],ie=[1,70],ae=[1,71],oe=[1,72],se=[1,73],ce=[1,74],le=[1,75],ue=[1,76],de=[1,77],V=[4,5,6,7,8,9,10,11,12,13,14,15,18],H=[1,91],U=[1,92],W=[1,93],G=[1,100],K=[1,94],q=[1,97],J=[1,95],Y=[1,96],X=[1,98],Z=[1,99],fe=[1,103],pe=[10,55,56,57],Q=[4,5,6,8,10,11,13,17,18,19,20,55,56,57],me={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,idStringToken:3,ALPHA:4,NUM:5,NODE_STRING:6,DOWN:7,MINUS:8,DEFAULT:9,COMMA:10,COLON:11,AMP:12,BRKT:13,MULT:14,UNICODE_TEXT:15,styleComponent:16,UNIT:17,SPACE:18,STYLE:19,PCT:20,idString:21,style:22,stylesOpt:23,classDefStatement:24,CLASSDEF:25,start:26,eol:27,QUADRANT:28,document:29,line:30,statement:31,axisDetails:32,quadrantDetails:33,points:34,title:35,title_value:36,acc_title:37,acc_title_value:38,acc_descr:39,acc_descr_value:40,acc_descr_multiline_value:41,section:42,text:43,point_start:44,point_x:45,point_y:46,class_name:47,"X-AXIS":48,"AXIS-TEXT-DELIMITER":49,"Y-AXIS":50,QUADRANT_1:51,QUADRANT_2:52,QUADRANT_3:53,QUADRANT_4:54,NEWLINE:55,SEMI:56,EOF:57,alphaNumToken:58,textNoTagsToken:59,STR:60,MD_STR:61,alphaNum:62,PUNCTUATION:63,PLUS:64,EQUALS:65,DOT:66,UNDERSCORE:67,$accept:0,$end:1},terminals_:{2:`error`,4:`ALPHA`,5:`NUM`,6:`NODE_STRING`,7:`DOWN`,8:`MINUS`,9:`DEFAULT`,10:`COMMA`,11:`COLON`,12:`AMP`,13:`BRKT`,14:`MULT`,15:`UNICODE_TEXT`,17:`UNIT`,18:`SPACE`,19:`STYLE`,20:`PCT`,25:`CLASSDEF`,28:`QUADRANT`,35:`title`,36:`title_value`,37:`acc_title`,38:`acc_title_value`,39:`acc_descr`,40:`acc_descr_value`,41:`acc_descr_multiline_value`,42:`section`,44:`point_start`,45:`point_x`,46:`point_y`,47:`class_name`,48:`X-AXIS`,49:`AXIS-TEXT-DELIMITER`,50:`Y-AXIS`,51:`QUADRANT_1`,52:`QUADRANT_2`,53:`QUADRANT_3`,54:`QUADRANT_4`,55:`NEWLINE`,56:`SEMI`,57:`EOF`,60:`STR`,61:`MD_STR`,63:`PUNCTUATION`,64:`PLUS`,65:`EQUALS`,66:`DOT`,67:`UNDERSCORE`},productions_:[0,[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[21,1],[21,2],[22,1],[22,2],[23,1],[23,3],[24,5],[26,2],[26,2],[26,2],[29,0],[29,2],[30,2],[31,0],[31,1],[31,2],[31,1],[31,1],[31,1],[31,2],[31,2],[31,2],[31,1],[31,1],[34,4],[34,5],[34,5],[34,6],[32,4],[32,3],[32,2],[32,4],[32,3],[32,2],[33,2],[33,2],[33,2],[33,2],[27,1],[27,1],[27,1],[43,1],[43,2],[43,1],[43,1],[62,1],[62,2],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[59,1],[59,1],[59,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 23:this.$=a[s];break;case 24:this.$=a[s-1]+``+a[s];break;case 26:this.$=a[s-1]+a[s];break;case 27:this.$=[a[s].trim()];break;case 28:a[s-2].push(a[s].trim()),this.$=a[s-2];break;case 29:this.$=a[s-4],r.addClass(a[s-2],a[s]);break;case 37:this.$=[];break;case 42:this.$=a[s].trim(),r.setDiagramTitle(this.$);break;case 43:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 44:case 45:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 46:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 47:r.addPoint(a[s-3],``,a[s-1],a[s],[]);break;case 48:r.addPoint(a[s-4],a[s-3],a[s-1],a[s],[]);break;case 49:r.addPoint(a[s-4],``,a[s-2],a[s-1],a[s]);break;case 50:r.addPoint(a[s-5],a[s-4],a[s-2],a[s-1],a[s]);break;case 51:r.setXAxisLeftText(a[s-2]),r.setXAxisRightText(a[s]);break;case 52:a[s-1].text+=` ⟶ `,r.setXAxisLeftText(a[s-1]);break;case 53:r.setXAxisLeftText(a[s]);break;case 54:r.setYAxisBottomText(a[s-2]),r.setYAxisTopText(a[s]);break;case 55:a[s-1].text+=` ⟶ `,r.setYAxisBottomText(a[s-1]);break;case 56:r.setYAxisBottomText(a[s]);break;case 57:r.setQuadrant1Text(a[s]);break;case 58:r.setQuadrant2Text(a[s]);break;case 59:r.setQuadrant3Text(a[s]);break;case 60:r.setQuadrant4Text(a[s]);break;case 64:this.$={text:a[s],type:`text`};break;case 65:this.$={text:a[s-1].text+``+a[s],type:a[s-1].type};break;case 66:this.$={text:a[s],type:`text`};break;case 67:this.$={text:a[s],type:`markdown`};break;case 68:this.$=a[s];break;case 69:this.$=a[s-1]+``+a[s];break}},`anonymous`),table:[{18:n,26:1,27:2,28:r,55:i,56:a,57:o},{1:[3]},{18:n,26:8,27:2,28:r,55:i,56:a,57:o},{18:n,26:9,27:2,28:r,55:i,56:a,57:o},t(s,[2,33],{29:10}),t(c,[2,61]),t(c,[2,62]),t(c,[2,63]),{1:[2,30]},{1:[2,31]},t(l,u,{30:11,31:12,24:13,32:15,33:16,34:17,43:30,58:31,1:[2,32],4:d,5:f,10:p,12:m,13:h,14:g,15:_,18:v,25:y,35:b,37:x,39:S,41:C,42:w,48:T,50:E,51:D,52:O,53:k,54:A,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),t(s,[2,34]),{27:46,55:i,56:a,57:o},t(l,[2,37]),t(l,u,{24:13,32:15,33:16,34:17,43:30,58:31,31:47,4:d,5:f,10:p,12:m,13:h,14:g,15:_,18:v,25:y,35:b,37:x,39:S,41:C,42:w,48:T,50:E,51:D,52:O,53:k,54:A,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),t(l,[2,39]),t(l,[2,40]),t(l,[2,41]),{36:[1,48]},{38:[1,49]},{40:[1,50]},t(l,[2,45]),t(l,[2,46]),{18:[1,51]},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:52,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:53,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:54,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:55,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:56,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,10:p,12:m,13:h,14:g,15:_,43:57,58:31,60:j,61:M,63:N,64:P,65:F,66:I,67:L},{4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,44:[1,58],47:[1,59],58:61,59:60,63:N,64:P,65:F,66:I,67:L},t(B,[2,64]),t(B,[2,66]),t(B,[2,67]),t(B,[2,70]),t(B,[2,71]),t(B,[2,72]),t(B,[2,73]),t(B,[2,74]),t(B,[2,75]),t(B,[2,76]),t(B,[2,77]),t(B,[2,78]),t(B,[2,79]),t(B,[2,80]),t(B,[2,81]),t(s,[2,35]),t(l,[2,38]),t(l,[2,42]),t(l,[2,43]),t(l,[2,44]),{3:65,4:ee,5:te,6:ne,7:re,8:ie,9:ae,10:oe,11:se,12:ce,13:le,14:ue,15:de,21:64},t(l,[2,53],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,49:[1,78],63:N,64:P,65:F,66:I,67:L}),t(l,[2,56],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,49:[1,79],63:N,64:P,65:F,66:I,67:L}),t(l,[2,57],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,58],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,59],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,60],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),{45:[1,80]},{44:[1,81]},t(B,[2,65]),t(B,[2,82]),t(B,[2,83]),t(B,[2,84]),{3:83,4:ee,5:te,6:ne,7:re,8:ie,9:ae,10:oe,11:se,12:ce,13:le,14:ue,15:de,18:[1,82]},t(V,[2,23]),t(V,[2,1]),t(V,[2,2]),t(V,[2,3]),t(V,[2,4]),t(V,[2,5]),t(V,[2,6]),t(V,[2,7]),t(V,[2,8]),t(V,[2,9]),t(V,[2,10]),t(V,[2,11]),t(V,[2,12]),t(l,[2,52],{58:31,43:84,4:d,5:f,10:p,12:m,13:h,14:g,15:_,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),t(l,[2,55],{58:31,43:85,4:d,5:f,10:p,12:m,13:h,14:g,15:_,60:j,61:M,63:N,64:P,65:F,66:I,67:L}),{46:[1,86]},{45:[1,87]},{4:H,5:U,6:W,8:G,11:K,13:q,16:90,17:J,18:Y,19:X,20:Z,22:89,23:88},t(V,[2,24]),t(l,[2,51],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,54],{59:60,58:61,4:d,5:f,8:R,10:p,12:m,13:h,14:g,15:_,18:z,63:N,64:P,65:F,66:I,67:L}),t(l,[2,47],{22:89,16:90,23:101,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z}),{46:[1,102]},t(l,[2,29],{10:fe}),t(pe,[2,27],{16:104,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z}),t(Q,[2,25]),t(Q,[2,13]),t(Q,[2,14]),t(Q,[2,15]),t(Q,[2,16]),t(Q,[2,17]),t(Q,[2,18]),t(Q,[2,19]),t(Q,[2,20]),t(Q,[2,21]),t(Q,[2,22]),t(l,[2,49],{10:fe}),t(l,[2,48],{22:89,16:90,23:105,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z}),{4:H,5:U,6:W,8:G,11:K,13:q,16:90,17:J,18:Y,19:X,20:Z,22:106},t(Q,[2,26]),t(l,[2,50],{10:fe}),t(pe,[2,28],{16:104,4:H,5:U,6:W,8:G,11:K,13:q,17:J,18:Y,19:X,20:Z})],defaultActions:{8:[2,30],9:[2,31]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};me.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:break;case 1:break;case 2:return 55;case 3:break;case 4:return this.begin(`title`),35;case 5:return this.popState(),`title_value`;case 6:return this.begin(`acc_title`),37;case 7:return this.popState(),`acc_title_value`;case 8:return this.begin(`acc_descr`),39;case 9:return this.popState(),`acc_descr_value`;case 10:this.begin(`acc_descr_multiline`);break;case 11:this.popState();break;case 12:return`acc_descr_multiline_value`;case 13:return 48;case 14:return 50;case 15:return 49;case 16:return 51;case 17:return 52;case 18:return 53;case 19:return 54;case 20:return 25;case 21:this.begin(`md_string`);break;case 22:return`MD_STR`;case 23:this.popState();break;case 24:this.begin(`string`);break;case 25:this.popState();break;case 26:return`STR`;case 27:this.begin(`class_name`);break;case 28:return this.popState(),47;case 29:return this.begin(`point_start`),44;case 30:return this.begin(`point_x`),45;case 31:this.popState();break;case 32:this.popState(),this.begin(`point_y`);break;case 33:return this.popState(),46;case 34:return 28;case 35:return 4;case 36:return 15;case 37:return 11;case 38:return 64;case 39:return 10;case 40:return 65;case 41:return 65;case 42:return 14;case 43:return 13;case 44:return 67;case 45:return 66;case 46:return 12;case 47:return 8;case 48:return 5;case 49:return 18;case 50:return 56;case 51:return 63;case 52:return 57}},`anonymous`),rules:[/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n\r]+)/i,/^(?:%%[^\n]*)/i,/^(?:title\b)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?: *x-axis *)/i,/^(?: *y-axis *)/i,/^(?: *--+> *)/i,/^(?: *quadrant-1 *)/i,/^(?: *quadrant-2 *)/i,/^(?: *quadrant-3 *)/i,/^(?: *quadrant-4 *)/i,/^(?:classDef\b)/i,/^(?:["][`])/i,/^(?:[^`"]+)/i,/^(?:[`]["])/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?::::)/i,/^(?:^\w+)/i,/^(?:\s*:\s*\[\s*)/i,/^(?:(1)|(0(.\d+)?))/i,/^(?:\s*\] *)/i,/^(?:\s*,\s*)/i,/^(?:(1)|(0(.\d+)?))/i,/^(?: *quadrantChart *)/i,/^(?:[A-Za-z]+)/i,/^(?:[^\x00-\x7F]+)/i,/^(?::)/i,/^(?:\+)/i,/^(?:,)/i,/^(?:=)/i,/^(?:=)/i,/^(?:\*)/i,/^(?:#)/i,/^(?:[\_])/i,/^(?:\.)/i,/^(?:&)/i,/^(?:-)/i,/^(?:[0-9]+)/i,/^(?:\s)/i,/^(?:;)/i,/^(?:[!"#$%&'*+,-.`?\\_/])/i,/^(?:$)/i],conditions:{class_name:{rules:[28],inclusive:!1},point_y:{rules:[33],inclusive:!1},point_x:{rules:[32],inclusive:!1},point_start:{rules:[30,31],inclusive:!1},acc_descr_multiline:{rules:[11,12],inclusive:!1},acc_descr:{rules:[9],inclusive:!1},acc_title:{rules:[7],inclusive:!1},title:{rules:[5],inclusive:!1},md_string:{rules:[22,23],inclusive:!1},string:{rules:[25,26],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,6,8,10,13,14,15,16,17,18,19,20,21,24,27,29,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52],inclusive:!0}}}})();function $(){this.yy={}}return e($,`Parser`),$.prototype=me,me.Parser=$,new $})();g.parser=g;var _=g,v=r(),y=class{constructor(){this.classes=new Map,this.config=this.getDefaultConfig(),this.themeConfig=this.getDefaultThemeConfig(),this.data=this.getDefaultData()}static{e(this,`QuadrantBuilder`)}getDefaultData(){return{titleText:``,quadrant1Text:``,quadrant2Text:``,quadrant3Text:``,quadrant4Text:``,xAxisLeftText:``,xAxisRightText:``,yAxisBottomText:``,yAxisTopText:``,points:[]}}getDefaultConfig(){return{showXAxis:!0,showYAxis:!0,showTitle:!0,chartHeight:l.quadrantChart?.chartWidth||500,chartWidth:l.quadrantChart?.chartHeight||500,titlePadding:l.quadrantChart?.titlePadding||10,titleFontSize:l.quadrantChart?.titleFontSize||20,quadrantPadding:l.quadrantChart?.quadrantPadding||5,xAxisLabelPadding:l.quadrantChart?.xAxisLabelPadding||5,yAxisLabelPadding:l.quadrantChart?.yAxisLabelPadding||5,xAxisLabelFontSize:l.quadrantChart?.xAxisLabelFontSize||16,yAxisLabelFontSize:l.quadrantChart?.yAxisLabelFontSize||16,quadrantLabelFontSize:l.quadrantChart?.quadrantLabelFontSize||16,quadrantTextTopPadding:l.quadrantChart?.quadrantTextTopPadding||5,pointTextPadding:l.quadrantChart?.pointTextPadding||5,pointLabelFontSize:l.quadrantChart?.pointLabelFontSize||12,pointRadius:l.quadrantChart?.pointRadius||5,xAxisPosition:l.quadrantChart?.xAxisPosition||`top`,yAxisPosition:l.quadrantChart?.yAxisPosition||`left`,quadrantInternalBorderStrokeWidth:l.quadrantChart?.quadrantInternalBorderStrokeWidth||1,quadrantExternalBorderStrokeWidth:l.quadrantChart?.quadrantExternalBorderStrokeWidth||2}}getDefaultThemeConfig(){return{quadrant1Fill:v.quadrant1Fill,quadrant2Fill:v.quadrant2Fill,quadrant3Fill:v.quadrant3Fill,quadrant4Fill:v.quadrant4Fill,quadrant1TextFill:v.quadrant1TextFill,quadrant2TextFill:v.quadrant2TextFill,quadrant3TextFill:v.quadrant3TextFill,quadrant4TextFill:v.quadrant4TextFill,quadrantPointFill:v.quadrantPointFill,quadrantPointTextFill:v.quadrantPointTextFill,quadrantXAxisTextFill:v.quadrantXAxisTextFill,quadrantYAxisTextFill:v.quadrantYAxisTextFill,quadrantTitleFill:v.quadrantTitleFill,quadrantInternalBorderStrokeFill:v.quadrantInternalBorderStrokeFill,quadrantExternalBorderStrokeFill:v.quadrantExternalBorderStrokeFill}}clear(){this.config=this.getDefaultConfig(),this.themeConfig=this.getDefaultThemeConfig(),this.data=this.getDefaultData(),this.classes=new Map,t.info(`clear called`)}setData(e){this.data={...this.data,...e}}addPoints(e){this.data.points=[...e,...this.data.points]}addClass(e,t){this.classes.set(e,t)}setConfig(e){t.trace(`setConfig called with: `,e),this.config={...this.config,...e}}setThemeConfig(e){t.trace(`setThemeConfig called with: `,e),this.themeConfig={...this.themeConfig,...e}}calculateSpace(e,t,n,r){let i=this.config.xAxisLabelPadding*2+this.config.xAxisLabelFontSize,a={top:e===`top`&&t?i:0,bottom:e===`bottom`&&t?i:0},o=this.config.yAxisLabelPadding*2+this.config.yAxisLabelFontSize,s={left:this.config.yAxisPosition===`left`&&n?o:0,right:this.config.yAxisPosition===`right`&&n?o:0},c=this.config.titleFontSize+this.config.titlePadding*2,l={top:r?c:0},u=this.config.quadrantPadding+s.left,d=this.config.quadrantPadding+a.top+l.top,f=this.config.chartWidth-this.config.quadrantPadding*2-s.left-s.right,p=this.config.chartHeight-this.config.quadrantPadding*2-a.top-a.bottom-l.top;return{xAxisSpace:a,yAxisSpace:s,titleSpace:l,quadrantSpace:{quadrantLeft:u,quadrantTop:d,quadrantWidth:f,quadrantHalfWidth:f/2,quadrantHeight:p,quadrantHalfHeight:p/2}}}getAxisLabels(e,t,n,r){let{quadrantSpace:i,titleSpace:a}=r,{quadrantHalfHeight:o,quadrantHeight:s,quadrantLeft:c,quadrantHalfWidth:l,quadrantTop:u,quadrantWidth:d}=i,f=!!this.data.xAxisRightText,p=!!this.data.yAxisTopText,m=[];return this.data.xAxisLeftText&&t&&m.push({text:this.data.xAxisLeftText,fill:this.themeConfig.quadrantXAxisTextFill,x:c+(f?l/2:0),y:e===`top`?this.config.xAxisLabelPadding+a.top:this.config.xAxisLabelPadding+u+s+this.config.quadrantPadding,fontSize:this.config.xAxisLabelFontSize,verticalPos:f?`center`:`left`,horizontalPos:`top`,rotation:0}),this.data.xAxisRightText&&t&&m.push({text:this.data.xAxisRightText,fill:this.themeConfig.quadrantXAxisTextFill,x:c+l+(f?l/2:0),y:e===`top`?this.config.xAxisLabelPadding+a.top:this.config.xAxisLabelPadding+u+s+this.config.quadrantPadding,fontSize:this.config.xAxisLabelFontSize,verticalPos:f?`center`:`left`,horizontalPos:`top`,rotation:0}),this.data.yAxisBottomText&&n&&m.push({text:this.data.yAxisBottomText,fill:this.themeConfig.quadrantYAxisTextFill,x:this.config.yAxisPosition===`left`?this.config.yAxisLabelPadding:this.config.yAxisLabelPadding+c+d+this.config.quadrantPadding,y:u+s-(p?o/2:0),fontSize:this.config.yAxisLabelFontSize,verticalPos:p?`center`:`left`,horizontalPos:`top`,rotation:-90}),this.data.yAxisTopText&&n&&m.push({text:this.data.yAxisTopText,fill:this.themeConfig.quadrantYAxisTextFill,x:this.config.yAxisPosition===`left`?this.config.yAxisLabelPadding:this.config.yAxisLabelPadding+c+d+this.config.quadrantPadding,y:u+o-(p?o/2:0),fontSize:this.config.yAxisLabelFontSize,verticalPos:p?`center`:`left`,horizontalPos:`top`,rotation:-90}),m}getQuadrants(e){let{quadrantSpace:t}=e,{quadrantHalfHeight:n,quadrantLeft:r,quadrantHalfWidth:i,quadrantTop:a}=t,o=[{text:{text:this.data.quadrant1Text,fill:this.themeConfig.quadrant1TextFill,x:0,y:0,fontSize:this.config.quadrantLabelFontSize,verticalPos:`center`,horizontalPos:`middle`,rotation:0},x:r+i,y:a,width:i,height:n,fill:this.themeConfig.quadrant1Fill},{text:{text:this.data.quadrant2Text,fill:this.themeConfig.quadrant2TextFill,x:0,y:0,fontSize:this.config.quadrantLabelFontSize,verticalPos:`center`,horizontalPos:`middle`,rotation:0},x:r,y:a,width:i,height:n,fill:this.themeConfig.quadrant2Fill},{text:{text:this.data.quadrant3Text,fill:this.themeConfig.quadrant3TextFill,x:0,y:0,fontSize:this.config.quadrantLabelFontSize,verticalPos:`center`,horizontalPos:`middle`,rotation:0},x:r,y:a+n,width:i,height:n,fill:this.themeConfig.quadrant3Fill},{text:{text:this.data.quadrant4Text,fill:this.themeConfig.quadrant4TextFill,x:0,y:0,fontSize:this.config.quadrantLabelFontSize,verticalPos:`center`,horizontalPos:`middle`,rotation:0},x:r+i,y:a+n,width:i,height:n,fill:this.themeConfig.quadrant4Fill}];for(let e of o)e.text.x=e.x+e.width/2,this.data.points.length===0?(e.text.y=e.y+e.height/2,e.text.horizontalPos=`middle`):(e.text.y=e.y+this.config.quadrantTextTopPadding,e.text.horizontalPos=`top`);return o}getQuadrantPoints(e){let{quadrantSpace:t}=e,{quadrantHeight:n,quadrantLeft:r,quadrantTop:i,quadrantWidth:a}=t,o=h().domain([0,1]).range([r,a+r]),s=h().domain([0,1]).range([n+i,i]);return this.data.points.map(e=>{let t=this.classes.get(e.className);return t&&(e={...t,...e}),{x:o(e.x),y:s(e.y),fill:e.color??this.themeConfig.quadrantPointFill,radius:e.radius??this.config.pointRadius,text:{text:e.text,fill:this.themeConfig.quadrantPointTextFill,x:o(e.x),y:s(e.y)+this.config.pointTextPadding,verticalPos:`center`,horizontalPos:`top`,fontSize:this.config.pointLabelFontSize,rotation:0},strokeColor:e.strokeColor??this.themeConfig.quadrantPointFill,strokeWidth:e.strokeWidth??`0px`}})}getBorders(e){let t=this.config.quadrantExternalBorderStrokeWidth/2,{quadrantSpace:n}=e,{quadrantHalfHeight:r,quadrantHeight:i,quadrantLeft:a,quadrantHalfWidth:o,quadrantTop:s,quadrantWidth:c}=n;return[{strokeFill:this.themeConfig.quadrantExternalBorderStrokeFill,strokeWidth:this.config.quadrantExternalBorderStrokeWidth,x1:a-t,y1:s,x2:a+c+t,y2:s},{strokeFill:this.themeConfig.quadrantExternalBorderStrokeFill,strokeWidth:this.config.quadrantExternalBorderStrokeWidth,x1:a+c,y1:s+t,x2:a+c,y2:s+i-t},{strokeFill:this.themeConfig.quadrantExternalBorderStrokeFill,strokeWidth:this.config.quadrantExternalBorderStrokeWidth,x1:a-t,y1:s+i,x2:a+c+t,y2:s+i},{strokeFill:this.themeConfig.quadrantExternalBorderStrokeFill,strokeWidth:this.config.quadrantExternalBorderStrokeWidth,x1:a,y1:s+t,x2:a,y2:s+i-t},{strokeFill:this.themeConfig.quadrantInternalBorderStrokeFill,strokeWidth:this.config.quadrantInternalBorderStrokeWidth,x1:a+o,y1:s+t,x2:a+o,y2:s+i-t},{strokeFill:this.themeConfig.quadrantInternalBorderStrokeFill,strokeWidth:this.config.quadrantInternalBorderStrokeWidth,x1:a+t,y1:s+r,x2:a+c-t,y2:s+r}]}getTitle(e){if(e)return{text:this.data.titleText,fill:this.themeConfig.quadrantTitleFill,fontSize:this.config.titleFontSize,horizontalPos:`top`,verticalPos:`center`,rotation:0,y:this.config.titlePadding,x:this.config.chartWidth/2}}build(){let e=this.config.showXAxis&&!!(this.data.xAxisLeftText||this.data.xAxisRightText),t=this.config.showYAxis&&!!(this.data.yAxisTopText||this.data.yAxisBottomText),n=this.config.showTitle&&!!this.data.titleText,r=this.data.points.length>0?`bottom`:this.config.xAxisPosition,i=this.calculateSpace(r,e,t,n);return{points:this.getQuadrantPoints(i),quadrants:this.getQuadrants(i),axisLabels:this.getAxisLabels(r,e,t,i),borderLines:this.getBorders(i),title:this.getTitle(n)}}},b=class extends Error{static{e(this,`InvalidStyleError`)}constructor(e,t,n){super(`value for ${e} ${t} is invalid, please use a valid ${n}`),this.name=`InvalidStyleError`}};function x(e){return!/^#?([\dA-Fa-f]{6}|[\dA-Fa-f]{3})$/.test(e)}e(x,`validateHexCode`);function S(e){return!/^\d+$/.test(e)}e(S,`validateNumber`);function C(e){return!/^\d+px$/.test(e)}e(C,`validateSizeInPixels`);function w(e){return m(e.trim(),f())}e(w,`textSanitizer`);var T=new y;function E(e){T.setData({quadrant1Text:w(e.text)})}e(E,`setQuadrant1Text`);function D(e){T.setData({quadrant2Text:w(e.text)})}e(D,`setQuadrant2Text`);function O(e){T.setData({quadrant3Text:w(e.text)})}e(O,`setQuadrant3Text`);function k(e){T.setData({quadrant4Text:w(e.text)})}e(k,`setQuadrant4Text`);function A(e){T.setData({xAxisLeftText:w(e.text)})}e(A,`setXAxisLeftText`);function j(e){T.setData({xAxisRightText:w(e.text)})}e(j,`setXAxisRightText`);function M(e){T.setData({yAxisTopText:w(e.text)})}e(M,`setYAxisTopText`);function N(e){T.setData({yAxisBottomText:w(e.text)})}e(N,`setYAxisBottomText`);function P(e){let t={};for(let n of e){let[e,r]=n.trim().split(/\s*:\s*/);if(e===`radius`){if(S(r))throw new b(e,r,`number`);t.radius=parseInt(r)}else if(e===`color`){if(x(r))throw new b(e,r,`hex code`);t.color=r}else if(e===`stroke-color`){if(x(r))throw new b(e,r,`hex code`);t.strokeColor=r}else if(e===`stroke-width`){if(C(r))throw new b(e,r,`number of pixels (eg. 10px)`);t.strokeWidth=r}else throw Error(`style named ${e} is not supported.`)}return t}e(P,`parseStyles`);function F(e,t,n,r,i){let a=P(i);T.addPoints([{x:n,y:r,text:w(e.text),className:t,...a}])}e(F,`addPoint`);function I(e,t){T.addClass(e,P(t))}e(I,`addClass`);function L(e){T.setConfig({chartWidth:e})}e(L,`setWidth`);function R(e){T.setConfig({chartHeight:e})}e(R,`setHeight`);function z(){let{themeVariables:e,quadrantChart:t}=f();return t&&T.setConfig(t),T.setThemeConfig({quadrant1Fill:e.quadrant1Fill,quadrant2Fill:e.quadrant2Fill,quadrant3Fill:e.quadrant3Fill,quadrant4Fill:e.quadrant4Fill,quadrant1TextFill:e.quadrant1TextFill,quadrant2TextFill:e.quadrant2TextFill,quadrant3TextFill:e.quadrant3TextFill,quadrant4TextFill:e.quadrant4TextFill,quadrantPointFill:e.quadrantPointFill,quadrantPointTextFill:e.quadrantPointTextFill,quadrantXAxisTextFill:e.quadrantXAxisTextFill,quadrantYAxisTextFill:e.quadrantYAxisTextFill,quadrantExternalBorderStrokeFill:e.quadrantExternalBorderStrokeFill,quadrantInternalBorderStrokeFill:e.quadrantInternalBorderStrokeFill,quadrantTitleFill:e.quadrantTitleFill}),T.setData({titleText:d()}),T.build()}e(z,`getQuadrantData`);var B={parser:_,db:{setWidth:L,setHeight:R,setQuadrant1Text:E,setQuadrant2Text:D,setQuadrant3Text:O,setQuadrant4Text:k,setXAxisLeftText:A,setXAxisRightText:j,setYAxisTopText:M,setYAxisBottomText:N,parseStyles:P,addPoint:F,addClass:I,getQuadrantData:z,clear:e(function(){T.clear(),s()},`clear`),setAccTitle:o,getAccTitle:p,setDiagramTitle:a,getDiagramTitle:d,getAccDescription:u,setAccDescription:i},renderer:{draw:e((r,i,a,o)=>{function s(e){return e===`top`?`hanging`:`middle`}e(s,`getDominantBaseLine`);function l(e){return e===`left`?`start`:`middle`}e(l,`getTextAnchor`);function u(e){return`translate(${e.x}, ${e.y}) rotate(${e.rotation||0})`}e(u,`getTransformation`);let d=f();t.debug(`Rendering quadrant chart +`+r);let p=d.securityLevel,m;p===`sandbox`&&(m=n(`#i`+i));let h=n(p===`sandbox`?m.nodes()[0].contentDocument.body:`body`).select(`[id="${i}"]`),g=h.append(`g`).attr(`class`,`main`),_=d.quadrantChart?.chartWidth??500,v=d.quadrantChart?.chartHeight??500;c(h,v,_,d.quadrantChart?.useMaxWidth??!0),h.attr(`viewBox`,`0 0 `+_+` `+v),o.db.setHeight(v),o.db.setWidth(_);let y=o.db.getQuadrantData(),b=g.append(`g`).attr(`class`,`quadrants`),x=g.append(`g`).attr(`class`,`border`),S=g.append(`g`).attr(`class`,`data-points`),C=g.append(`g`).attr(`class`,`labels`),w=g.append(`g`).attr(`class`,`title`);y.title&&w.append(`text`).attr(`x`,0).attr(`y`,0).attr(`fill`,y.title.fill).attr(`font-size`,y.title.fontSize).attr(`dominant-baseline`,s(y.title.horizontalPos)).attr(`text-anchor`,l(y.title.verticalPos)).attr(`transform`,u(y.title)).text(y.title.text),y.borderLines&&x.selectAll(`line`).data(y.borderLines).enter().append(`line`).attr(`x1`,e=>e.x1).attr(`y1`,e=>e.y1).attr(`x2`,e=>e.x2).attr(`y2`,e=>e.y2).style(`stroke`,e=>e.strokeFill).style(`stroke-width`,e=>e.strokeWidth);let T=b.selectAll(`g.quadrant`).data(y.quadrants).enter().append(`g`).attr(`class`,`quadrant`);T.append(`rect`).attr(`x`,e=>e.x).attr(`y`,e=>e.y).attr(`width`,e=>e.width).attr(`height`,e=>e.height).attr(`fill`,e=>e.fill),T.append(`text`).attr(`x`,0).attr(`y`,0).attr(`fill`,e=>e.text.fill).attr(`font-size`,e=>e.text.fontSize).attr(`dominant-baseline`,e=>s(e.text.horizontalPos)).attr(`text-anchor`,e=>l(e.text.verticalPos)).attr(`transform`,e=>u(e.text)).text(e=>e.text.text),C.selectAll(`g.label`).data(y.axisLabels).enter().append(`g`).attr(`class`,`label`).append(`text`).attr(`x`,0).attr(`y`,0).text(e=>e.text).attr(`fill`,e=>e.fill).attr(`font-size`,e=>e.fontSize).attr(`dominant-baseline`,e=>s(e.horizontalPos)).attr(`text-anchor`,e=>l(e.verticalPos)).attr(`transform`,e=>u(e));let E=S.selectAll(`g.data-point`).data(y.points).enter().append(`g`).attr(`class`,`data-point`);E.append(`circle`).attr(`cx`,e=>e.x).attr(`cy`,e=>e.y).attr(`r`,e=>e.radius).attr(`fill`,e=>e.fill).attr(`stroke`,e=>e.strokeColor).attr(`stroke-width`,e=>e.strokeWidth),E.append(`text`).attr(`x`,0).attr(`y`,0).text(e=>e.text.text).attr(`fill`,e=>e.text.fill).attr(`font-size`,e=>e.text.fontSize).attr(`dominant-baseline`,e=>s(e.text.horizontalPos)).attr(`text-anchor`,e=>l(e.text.verticalPos)).attr(`transform`,e=>u(e.text))},`draw`)},styles:e(()=>``,`styles`)};export{B as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/radar-I7S5WNFK-fIKE12aT.js b/dist-desktop/assets/radar-I7S5WNFK-fIKE12aT.js new file mode 100644 index 0000000..236e538 --- /dev/null +++ b/dist-desktop/assets/radar-I7S5WNFK-fIKE12aT.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-QBLGF6JB-C9zGMqvP.js";export{e as createRadarServices}; \ No newline at end of file diff --git a/dist-desktop/assets/railroad-3IZDKUUU-Bgx8HJTj.js b/dist-desktop/assets/railroad-3IZDKUUU-Bgx8HJTj.js new file mode 100644 index 0000000..8ca997f --- /dev/null +++ b/dist-desktop/assets/railroad-3IZDKUUU-Bgx8HJTj.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-5TONJI2A-DOX2waSJ.js";export{e as createRailroadServices}; \ No newline at end of file diff --git a/dist-desktop/assets/railroad-abnf-AHOZXSZD-Nh6k60mH.js b/dist-desktop/assets/railroad-abnf-AHOZXSZD-Nh6k60mH.js new file mode 100644 index 0000000..7000d0a --- /dev/null +++ b/dist-desktop/assets/railroad-abnf-AHOZXSZD-Nh6k60mH.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-5HE753X5-o8-OCfIL.js";export{e as createRailroadAbnfServices}; \ No newline at end of file diff --git a/dist-desktop/assets/railroad-ebnf-EBAXGLYW-C74h3s_I.js b/dist-desktop/assets/railroad-ebnf-EBAXGLYW-C74h3s_I.js new file mode 100644 index 0000000..aa91b93 --- /dev/null +++ b/dist-desktop/assets/railroad-ebnf-EBAXGLYW-C74h3s_I.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-U6XO7XAA-CR0BSRFR.js";export{e as createRailroadEbnfServices}; \ No newline at end of file diff --git a/dist-desktop/assets/railroad-peg-LSFZ7HO6-0hT-lN-u.js b/dist-desktop/assets/railroad-peg-LSFZ7HO6-0hT-lN-u.js new file mode 100644 index 0000000..991b665 --- /dev/null +++ b/dist-desktop/assets/railroad-peg-LSFZ7HO6-0hT-lN-u.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-JG7HCLWE-Dk4_aECj.js";export{e as createRailroadPegServices}; \ No newline at end of file diff --git a/dist-desktop/assets/railroadDiagram-RFXS5EU6-D7w_TgGh.js b/dist-desktop/assets/railroadDiagram-RFXS5EU6-D7w_TgGh.js new file mode 100644 index 0000000..3276078 --- /dev/null +++ b/dist-desktop/assets/railroadDiagram-RFXS5EU6-D7w_TgGh.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-5TONJI2A-DOX2waSJ.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-VAUOI2AC-AC9pRUsa.js";import{n as r,r as i,t as a}from"./chunk-MOJQB5TN-Bju_yCKi.js";import{t as o}from"./chunk-JWPE2WC7-DVXcaiue.js";import{t as s}from"./mermaid-parser.core-Z7xZAZRH.js";var c=e().Railroad.parser.LangiumParser,l=t(e=>{switch(e.$type){case`RailroadTerminalExpr`:return{type:`terminal`,value:e.value};case`RailroadNonTerminalExpr`:return{type:`nonterminal`,name:e.name};case`RailroadSpecialExpr`:return{type:`special`,text:e.text};case`RailroadSequenceExpr`:{let t=e.elements.map(l);return t.length===1?t[0]:{type:`sequence`,elements:t}}case`RailroadChoiceExpr`:{let t=e.alternatives.map(l);return t.length===1?t[0]:{type:`choice`,alternatives:t}}case`RailroadOptionalExpr`:return{type:`optional`,element:l(e.element)};case`RailroadOneOrMoreExpr`:return{type:`repetition`,element:l(e.element),min:1,max:1/0};case`RailroadZeroOrMoreExpr`:return{type:`repetition`,element:l(e.element),min:0,max:1/0};default:throw Error(`Unsupported railroad expression: ${e.$type}`)}},`transformExpression`),u=t(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),d=t(e=>{o(e,a),e.title&&a.setTitle(e.title),e.rules.map(e=>a.addRule(u(e)))},`populateDb`),f={parser:{parse:t(e=>{a.clear(),n.debug(`[Railroad Parser] Starting Langium parse`);let t=c.parse(e);if(t.lexerErrors.length>0||t.parserErrors.length>0)throw new s(t);let r=t.value;n.debug(`[Railroad Parser] Parsed rules:`,r.rules.length),d(r),n.debug(`[Railroad Parser] Parse complete`)},`parse`),parser:{yy:a}},db:a,renderer:i,styles:r};export{f as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/react-BLJmJXjR.js b/dist-desktop/assets/react-BLJmJXjR.js new file mode 100644 index 0000000..3a483f5 --- /dev/null +++ b/dist-desktop/assets/react-BLJmJXjR.js @@ -0,0 +1 @@ +import{t as e}from"./rolldown-runtime-aKtaBQYM.js";var t=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{n.exports=t()}));export{n as t}; \ No newline at end of file diff --git a/dist-desktop/assets/requirementDiagram-TGXJPOKE-Bk3E4jWx.js b/dist-desktop/assets/requirementDiagram-TGXJPOKE-Bk3E4jWx.js new file mode 100644 index 0000000..399bc68 --- /dev/null +++ b/dist-desktop/assets/requirementDiagram-TGXJPOKE-Bk3E4jWx.js @@ -0,0 +1,84 @@ +import{n as e,t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import{H as r,K as i,U as a,a as o,b as s,v as c,w as l,x as u,y as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{g as f}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import{t as p}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as m}from"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import{r as h,t as g}from"./chunk-FWX5IMBZ-ComLEIwh.js";var _=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,3],r=[1,4],i=[1,5],a=[1,6],o=[5,6,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,77,89,90],s=[1,22],c=[2,7],l=[1,26],u=[1,27],d=[1,28],f=[1,29],p=[1,33],m=[1,34],h=[1,35],g=[1,36],_=[1,37],v=[1,38],y=[1,24],b=[1,31],x=[1,32],S=[1,30],C=[1,39],w=[1,40],T=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,77,89,90],E=[1,61],D=[89,90],O=[5,8,9,11,13,21,22,23,24,27,29,41,42,43,44,45,46,54,61,63,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],k=[27,29],ee=[1,70],A=[1,71],te=[1,72],ne=[1,73],re=[1,74],ie=[1,75],ae=[1,76],j=[1,83],M=[1,80],N=[1,84],P=[1,85],F=[1,86],I=[1,87],L=[1,88],R=[1,89],z=[1,90],B=[1,91],V=[1,92],oe=[5,8,9,11,13,21,22,23,24,27,41,42,43,44,45,46,54,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],H=[63,64],se=[1,101],ce=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,76,77,89,90],U=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],W=[1,110],G=[1,106],K=[1,107],q=[1,108],J=[1,109],Y=[1,111],X=[1,116],Z=[1,117],Q=[1,114],$=[1,115],le={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,directive:4,NEWLINE:5,RD:6,diagram:7,EOF:8,acc_title:9,acc_title_value:10,acc_descr:11,acc_descr_value:12,acc_descr_multiline_value:13,requirementDef:14,elementDef:15,relationshipDef:16,direction:17,styleStatement:18,classDefStatement:19,classStatement:20,direction_tb:21,direction_bt:22,direction_rl:23,direction_lr:24,requirementType:25,requirementName:26,STRUCT_START:27,requirementBody:28,STYLE_SEPARATOR:29,idList:30,ID:31,COLONSEP:32,id:33,TEXT:34,text:35,RISK:36,riskLevel:37,VERIFYMTHD:38,verifyType:39,STRUCT_STOP:40,REQUIREMENT:41,FUNCTIONAL_REQUIREMENT:42,INTERFACE_REQUIREMENT:43,PERFORMANCE_REQUIREMENT:44,PHYSICAL_REQUIREMENT:45,DESIGN_CONSTRAINT:46,LOW_RISK:47,MED_RISK:48,HIGH_RISK:49,VERIFY_ANALYSIS:50,VERIFY_DEMONSTRATION:51,VERIFY_INSPECTION:52,VERIFY_TEST:53,ELEMENT:54,elementName:55,elementBody:56,TYPE:57,type:58,DOCREF:59,ref:60,END_ARROW_L:61,relationship:62,LINE:63,END_ARROW_R:64,CONTAINS:65,COPIES:66,DERIVES:67,SATISFIES:68,VERIFIES:69,REFINES:70,TRACES:71,CLASSDEF:72,stylesOpt:73,CLASS:74,ALPHA:75,COMMA:76,STYLE:77,style:78,styleComponent:79,NUM:80,COLON:81,UNIT:82,SPACE:83,BRKT:84,PCT:85,MINUS:86,LABEL:87,SEMICOLON:88,unqString:89,qString:90,$accept:0,$end:1},terminals_:{2:`error`,5:`NEWLINE`,6:`RD`,8:`EOF`,9:`acc_title`,10:`acc_title_value`,11:`acc_descr`,12:`acc_descr_value`,13:`acc_descr_multiline_value`,21:`direction_tb`,22:`direction_bt`,23:`direction_rl`,24:`direction_lr`,27:`STRUCT_START`,29:`STYLE_SEPARATOR`,31:`ID`,32:`COLONSEP`,34:`TEXT`,36:`RISK`,38:`VERIFYMTHD`,40:`STRUCT_STOP`,41:`REQUIREMENT`,42:`FUNCTIONAL_REQUIREMENT`,43:`INTERFACE_REQUIREMENT`,44:`PERFORMANCE_REQUIREMENT`,45:`PHYSICAL_REQUIREMENT`,46:`DESIGN_CONSTRAINT`,47:`LOW_RISK`,48:`MED_RISK`,49:`HIGH_RISK`,50:`VERIFY_ANALYSIS`,51:`VERIFY_DEMONSTRATION`,52:`VERIFY_INSPECTION`,53:`VERIFY_TEST`,54:`ELEMENT`,57:`TYPE`,59:`DOCREF`,61:`END_ARROW_L`,63:`LINE`,64:`END_ARROW_R`,65:`CONTAINS`,66:`COPIES`,67:`DERIVES`,68:`SATISFIES`,69:`VERIFIES`,70:`REFINES`,71:`TRACES`,72:`CLASSDEF`,74:`CLASS`,75:`ALPHA`,76:`COMMA`,77:`STYLE`,80:`NUM`,81:`COLON`,82:`UNIT`,83:`SPACE`,84:`BRKT`,85:`PCT`,86:`MINUS`,87:`LABEL`,88:`SEMICOLON`,89:`unqString`,90:`qString`},productions_:[0,[3,3],[3,2],[3,4],[4,2],[4,2],[4,1],[7,0],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[17,1],[17,1],[17,1],[17,1],[14,5],[14,7],[28,5],[28,5],[28,5],[28,5],[28,2],[28,1],[25,1],[25,1],[25,1],[25,1],[25,1],[25,1],[37,1],[37,1],[37,1],[39,1],[39,1],[39,1],[39,1],[15,5],[15,7],[56,5],[56,5],[56,2],[56,1],[16,5],[16,5],[62,1],[62,1],[62,1],[62,1],[62,1],[62,1],[62,1],[19,3],[20,3],[20,3],[30,1],[30,3],[30,1],[30,3],[18,3],[73,1],[73,3],[78,1],[78,2],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[26,1],[26,1],[33,1],[33,1],[35,1],[35,1],[55,1],[55,1],[58,1],[58,1],[60,1],[60,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 4:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 5:case 6:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 7:this.$=[];break;case 17:r.setDirection(`TB`);break;case 18:r.setDirection(`BT`);break;case 19:r.setDirection(`RL`);break;case 20:r.setDirection(`LR`);break;case 21:r.addRequirement(a[s-3],a[s-4]);break;case 22:r.addRequirement(a[s-5],a[s-6]),r.setClass([a[s-5]],a[s-3]);break;case 23:r.setNewReqId(a[s-2]);break;case 24:r.setNewReqText(a[s-2]);break;case 25:r.setNewReqRisk(a[s-2]);break;case 26:r.setNewReqVerifyMethod(a[s-2]);break;case 29:this.$=r.RequirementType.REQUIREMENT;break;case 30:this.$=r.RequirementType.FUNCTIONAL_REQUIREMENT;break;case 31:this.$=r.RequirementType.INTERFACE_REQUIREMENT;break;case 32:this.$=r.RequirementType.PERFORMANCE_REQUIREMENT;break;case 33:this.$=r.RequirementType.PHYSICAL_REQUIREMENT;break;case 34:this.$=r.RequirementType.DESIGN_CONSTRAINT;break;case 35:this.$=r.RiskLevel.LOW_RISK;break;case 36:this.$=r.RiskLevel.MED_RISK;break;case 37:this.$=r.RiskLevel.HIGH_RISK;break;case 38:this.$=r.VerifyType.VERIFY_ANALYSIS;break;case 39:this.$=r.VerifyType.VERIFY_DEMONSTRATION;break;case 40:this.$=r.VerifyType.VERIFY_INSPECTION;break;case 41:this.$=r.VerifyType.VERIFY_TEST;break;case 42:r.addElement(a[s-3]);break;case 43:r.addElement(a[s-5]),r.setClass([a[s-5]],a[s-3]);break;case 44:r.setNewElementType(a[s-2]);break;case 45:r.setNewElementDocRef(a[s-2]);break;case 48:r.addRelationship(a[s-2],a[s],a[s-4]);break;case 49:r.addRelationship(a[s-2],a[s-4],a[s]);break;case 50:this.$=r.Relationships.CONTAINS;break;case 51:this.$=r.Relationships.COPIES;break;case 52:this.$=r.Relationships.DERIVES;break;case 53:this.$=r.Relationships.SATISFIES;break;case 54:this.$=r.Relationships.VERIFIES;break;case 55:this.$=r.Relationships.REFINES;break;case 56:this.$=r.Relationships.TRACES;break;case 57:this.$=a[s-2],r.defineClass(a[s-1],a[s]);break;case 58:r.setClass(a[s-1],a[s]);break;case 59:r.setClass([a[s-2]],a[s]);break;case 60:case 62:this.$=[a[s]];break;case 61:case 63:this.$=a[s-2].concat([a[s]]);break;case 64:this.$=a[s-2],r.setCssStyle(a[s-1],a[s]);break;case 65:this.$=[a[s]];break;case 66:a[s-2].push(a[s]),this.$=a[s-2];break;case 68:this.$=a[s-1]+a[s];break}},`anonymous`),table:[{3:1,4:2,6:n,9:r,11:i,13:a},{1:[3]},{3:8,4:2,5:[1,7],6:n,9:r,11:i,13:a},{5:[1,9]},{10:[1,10]},{12:[1,11]},t(o,[2,6]),{3:12,4:2,6:n,9:r,11:i,13:a},{1:[2,2]},{4:17,5:s,7:13,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},t(o,[2,4]),t(o,[2,5]),{1:[2,1]},{8:[1,41]},{4:17,5:s,7:42,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:43,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:44,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:45,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:46,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:47,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:48,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:49,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{4:17,5:s,7:50,8:c,9:r,11:i,13:a,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:l,22:u,23:d,24:f,25:23,33:25,41:p,42:m,43:h,44:g,45:_,46:v,54:y,72:b,74:x,77:S,89:C,90:w},{26:51,89:[1,52],90:[1,53]},{55:54,89:[1,55],90:[1,56]},{29:[1,59],61:[1,57],63:[1,58]},t(T,[2,17]),t(T,[2,18]),t(T,[2,19]),t(T,[2,20]),{30:60,33:62,75:E,89:C,90:w},{30:63,33:62,75:E,89:C,90:w},{30:64,33:62,75:E,89:C,90:w},t(D,[2,29]),t(D,[2,30]),t(D,[2,31]),t(D,[2,32]),t(D,[2,33]),t(D,[2,34]),t(O,[2,81]),t(O,[2,82]),{1:[2,3]},{8:[2,8]},{8:[2,9]},{8:[2,10]},{8:[2,11]},{8:[2,12]},{8:[2,13]},{8:[2,14]},{8:[2,15]},{8:[2,16]},{27:[1,65],29:[1,66]},t(k,[2,79]),t(k,[2,80]),{27:[1,67],29:[1,68]},t(k,[2,85]),t(k,[2,86]),{62:69,65:ee,66:A,67:te,68:ne,69:re,70:ie,71:ae},{62:77,65:ee,66:A,67:te,68:ne,69:re,70:ie,71:ae},{30:78,33:62,75:E,89:C,90:w},{73:79,75:j,76:M,78:81,79:82,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V},t(oe,[2,60]),t(oe,[2,62]),{73:93,75:j,76:M,78:81,79:82,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V},{30:94,33:62,75:E,76:M,89:C,90:w},{5:[1,95]},{30:96,33:62,75:E,89:C,90:w},{5:[1,97]},{30:98,33:62,75:E,89:C,90:w},{63:[1,99]},t(H,[2,50]),t(H,[2,51]),t(H,[2,52]),t(H,[2,53]),t(H,[2,54]),t(H,[2,55]),t(H,[2,56]),{64:[1,100]},t(T,[2,59],{76:M}),t(T,[2,64],{76:se}),{33:103,75:[1,102],89:C,90:w},t(ce,[2,65],{79:104,75:j,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V}),t(U,[2,67]),t(U,[2,69]),t(U,[2,70]),t(U,[2,71]),t(U,[2,72]),t(U,[2,73]),t(U,[2,74]),t(U,[2,75]),t(U,[2,76]),t(U,[2,77]),t(U,[2,78]),t(T,[2,57],{76:se}),t(T,[2,58],{76:M}),{5:W,28:105,31:G,34:K,36:q,38:J,40:Y},{27:[1,112],76:M},{5:X,40:Z,56:113,57:Q,59:$},{27:[1,118],76:M},{33:119,89:C,90:w},{33:120,89:C,90:w},{75:j,78:121,79:82,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V},t(oe,[2,61]),t(oe,[2,63]),t(U,[2,68]),t(T,[2,21]),{32:[1,122]},{32:[1,123]},{32:[1,124]},{32:[1,125]},{5:W,28:126,31:G,34:K,36:q,38:J,40:Y},t(T,[2,28]),{5:[1,127]},t(T,[2,42]),{32:[1,128]},{32:[1,129]},{5:X,40:Z,56:130,57:Q,59:$},t(T,[2,47]),{5:[1,131]},t(T,[2,48]),t(T,[2,49]),t(ce,[2,66],{79:104,75:j,80:N,81:P,82:F,83:I,84:L,85:R,86:z,87:B,88:V}),{33:132,89:C,90:w},{35:133,89:[1,134],90:[1,135]},{37:136,47:[1,137],48:[1,138],49:[1,139]},{39:140,50:[1,141],51:[1,142],52:[1,143],53:[1,144]},t(T,[2,27]),{5:W,28:145,31:G,34:K,36:q,38:J,40:Y},{58:146,89:[1,147],90:[1,148]},{60:149,89:[1,150],90:[1,151]},t(T,[2,46]),{5:X,40:Z,56:152,57:Q,59:$},{5:[1,153]},{5:[1,154]},{5:[2,83]},{5:[2,84]},{5:[1,155]},{5:[2,35]},{5:[2,36]},{5:[2,37]},{5:[1,156]},{5:[2,38]},{5:[2,39]},{5:[2,40]},{5:[2,41]},t(T,[2,22]),{5:[1,157]},{5:[2,87]},{5:[2,88]},{5:[1,158]},{5:[2,89]},{5:[2,90]},t(T,[2,43]),{5:W,28:159,31:G,34:K,36:q,38:J,40:Y},{5:W,28:160,31:G,34:K,36:q,38:J,40:Y},{5:W,28:161,31:G,34:K,36:q,38:J,40:Y},{5:W,28:162,31:G,34:K,36:q,38:J,40:Y},{5:X,40:Z,56:163,57:Q,59:$},{5:X,40:Z,56:164,57:Q,59:$},t(T,[2,23]),t(T,[2,24]),t(T,[2,25]),t(T,[2,26]),t(T,[2,44]),t(T,[2,45])],defaultActions:{8:[2,2],12:[2,1],41:[2,3],42:[2,8],43:[2,9],44:[2,10],45:[2,11],46:[2,12],47:[2,13],48:[2,14],49:[2,15],50:[2,16],134:[2,83],135:[2,84],137:[2,35],138:[2,36],139:[2,37],141:[2,38],142:[2,39],143:[2,40],144:[2,41],147:[2,87],148:[2,88],150:[2,89],151:[2,90]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,ee,A;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var te=``;for(O in A=[],s[w])this.terminals_[O]&&O>f&&A.push(`'`+this.terminals_[O]+`'`);te=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+A.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(te,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:A})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),ee=s[r[r.length-2]][r[r.length-1]],r.push(ee);break;case 3:return!0}}return!0},`parse`)};le.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:return`title`;case 1:return this.begin(`acc_title`),9;case 2:return this.popState(),`acc_title_value`;case 3:return this.begin(`acc_descr`),11;case 4:return this.popState(),`acc_descr_value`;case 5:this.begin(`acc_descr_multiline`);break;case 6:this.popState();break;case 7:return`acc_descr_multiline_value`;case 8:return 21;case 9:return 22;case 10:return 23;case 11:return 24;case 12:return 5;case 13:break;case 14:break;case 15:break;case 16:return 8;case 17:return 6;case 18:return 27;case 19:return 40;case 20:return 29;case 21:return 32;case 22:return 31;case 23:return 34;case 24:return 36;case 25:return 38;case 26:return 41;case 27:return 42;case 28:return 43;case 29:return 44;case 30:return 45;case 31:return 46;case 32:return 47;case 33:return 48;case 34:return 49;case 35:return 50;case 36:return 51;case 37:return 52;case 38:return 53;case 39:return 54;case 40:return 65;case 41:return 66;case 42:return 67;case 43:return 68;case 44:return 69;case 45:return 70;case 46:return 71;case 47:return 57;case 48:return 59;case 49:return this.begin(`style`),77;case 50:return 75;case 51:return 81;case 52:return 88;case 53:return`PERCENT`;case 54:return 86;case 55:return 84;case 56:break;case 57:this.begin(`string`);break;case 58:this.popState();break;case 59:return this.begin(`style`),72;case 60:return this.begin(`style`),74;case 61:return 61;case 62:return 64;case 63:return 63;case 64:this.begin(`string`);break;case 65:this.popState();break;case 66:return`qString`;case 67:return t.yytext=t.yytext.trim(),89;case 68:return 75;case 69:return 80;case 70:return 76}},`anonymous`),rules:[/^(?:title\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:(\r?\n)+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:$)/i,/^(?:requirementDiagram\b)/i,/^(?:\{)/i,/^(?:\})/i,/^(?::{3})/i,/^(?::)/i,/^(?:id\b)/i,/^(?:text\b)/i,/^(?:risk\b)/i,/^(?:verifyMethod\b)/i,/^(?:requirement\b)/i,/^(?:functionalRequirement\b)/i,/^(?:interfaceRequirement\b)/i,/^(?:performanceRequirement\b)/i,/^(?:physicalRequirement\b)/i,/^(?:designConstraint\b)/i,/^(?:low\b)/i,/^(?:medium\b)/i,/^(?:high\b)/i,/^(?:analysis\b)/i,/^(?:demonstration\b)/i,/^(?:inspection\b)/i,/^(?:test\b)/i,/^(?:element\b)/i,/^(?:contains\b)/i,/^(?:copies\b)/i,/^(?:derives\b)/i,/^(?:satisfies\b)/i,/^(?:verifies\b)/i,/^(?:refines\b)/i,/^(?:traces\b)/i,/^(?:type\b)/i,/^(?:docref\b)/i,/^(?:style\b)/i,/^(?:\w+)/i,/^(?::)/i,/^(?:;)/i,/^(?:%)/i,/^(?:-)/i,/^(?:#)/i,/^(?: )/i,/^(?:["])/i,/^(?:\n)/i,/^(?:classDef\b)/i,/^(?:class\b)/i,/^(?:<-)/i,/^(?:->)/i,/^(?:-)/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[\w][^:,\r\n\{\<\>\-\=]*)/i,/^(?:\w+)/i,/^(?:[0-9]+)/i,/^(?:,)/i],conditions:{acc_descr_multiline:{rules:[6,7,68,69,70],inclusive:!1},acc_descr:{rules:[4,68,69,70],inclusive:!1},acc_title:{rules:[2,68,69,70],inclusive:!1},style:{rules:[50,51,52,53,54,55,56,57,58,68,69,70],inclusive:!1},unqString:{rules:[68,69,70],inclusive:!1},token:{rules:[68,69,70],inclusive:!1},string:{rules:[65,66,68,69,70],inclusive:!1},INITIAL:{rules:[0,1,3,5,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,45,46,47,48,49,59,60,61,62,63,64,67,68,69,70],inclusive:!0}}}})();function ue(){this.yy={}}return e(ue,`Parser`),ue.prototype=le,le.Parser=ue,new ue})();_.parser=_;var v=_,y=class{constructor(){this.relations=[],this.latestRequirement=this.getInitialRequirement(),this.requirements=new Map,this.latestElement=this.getInitialElement(),this.elements=new Map,this.classes=new Map,this.direction=`TB`,this.RequirementType={REQUIREMENT:`Requirement`,FUNCTIONAL_REQUIREMENT:`Functional Requirement`,INTERFACE_REQUIREMENT:`Interface Requirement`,PERFORMANCE_REQUIREMENT:`Performance Requirement`,PHYSICAL_REQUIREMENT:`Physical Requirement`,DESIGN_CONSTRAINT:`Design Constraint`},this.RiskLevel={LOW_RISK:`Low`,MED_RISK:`Medium`,HIGH_RISK:`High`},this.VerifyType={VERIFY_ANALYSIS:`Analysis`,VERIFY_DEMONSTRATION:`Demonstration`,VERIFY_INSPECTION:`Inspection`,VERIFY_TEST:`Test`},this.Relationships={CONTAINS:`contains`,COPIES:`copies`,DERIVES:`derives`,SATISFIES:`satisfies`,VERIFIES:`verifies`,REFINES:`refines`,TRACES:`traces`},this.setAccTitle=a,this.getAccTitle=d,this.setAccDescription=r,this.getAccDescription=c,this.setDiagramTitle=i,this.getDiagramTitle=l,this.getConfig=e(()=>u().requirement,`getConfig`),this.clear(),this.setDirection=this.setDirection.bind(this),this.addRequirement=this.addRequirement.bind(this),this.setNewReqId=this.setNewReqId.bind(this),this.setNewReqRisk=this.setNewReqRisk.bind(this),this.setNewReqText=this.setNewReqText.bind(this),this.setNewReqVerifyMethod=this.setNewReqVerifyMethod.bind(this),this.addElement=this.addElement.bind(this),this.setNewElementType=this.setNewElementType.bind(this),this.setNewElementDocRef=this.setNewElementDocRef.bind(this),this.addRelationship=this.addRelationship.bind(this),this.setCssStyle=this.setCssStyle.bind(this),this.setClass=this.setClass.bind(this),this.defineClass=this.defineClass.bind(this),this.setAccTitle=this.setAccTitle.bind(this),this.setAccDescription=this.setAccDescription.bind(this)}static{e(this,`RequirementDB`)}getDirection(){return this.direction}setDirection(e){this.direction=e}resetLatestRequirement(){this.latestRequirement=this.getInitialRequirement()}resetLatestElement(){this.latestElement=this.getInitialElement()}getInitialRequirement(){return{requirementId:``,text:``,risk:``,verifyMethod:``,name:``,type:``,cssStyles:[],classes:[`default`]}}getInitialElement(){return{name:``,type:``,docRef:``,cssStyles:[],classes:[`default`]}}addRequirement(e,t){return this.requirements.has(e)||this.requirements.set(e,{name:e,type:t,requirementId:this.latestRequirement.requirementId,text:this.latestRequirement.text,risk:this.latestRequirement.risk,verifyMethod:this.latestRequirement.verifyMethod,cssStyles:[],classes:[`default`]}),this.resetLatestRequirement(),this.requirements.get(e)}getRequirements(){return this.requirements}setNewReqId(e){this.latestRequirement!==void 0&&(this.latestRequirement.requirementId=e)}setNewReqText(e){this.latestRequirement!==void 0&&(this.latestRequirement.text=e)}setNewReqRisk(e){this.latestRequirement!==void 0&&(this.latestRequirement.risk=e)}setNewReqVerifyMethod(e){this.latestRequirement!==void 0&&(this.latestRequirement.verifyMethod=e)}addElement(e){return this.elements.has(e)||(this.elements.set(e,{name:e,type:this.latestElement.type,docRef:this.latestElement.docRef,cssStyles:[],classes:[`default`]}),n.info(`Added new element: `,e)),this.resetLatestElement(),this.elements.get(e)}getElements(){return this.elements}setNewElementType(e){this.latestElement!==void 0&&(this.latestElement.type=e)}setNewElementDocRef(e){this.latestElement!==void 0&&(this.latestElement.docRef=e)}addRelationship(e,t,n){this.relations.push({type:e,src:t,dst:n})}getRelationships(){return this.relations}clear(){this.relations=[],this.resetLatestRequirement(),this.requirements=new Map,this.resetLatestElement(),this.elements=new Map,this.classes=new Map,o()}setCssStyle(e,t){for(let n of e){let e=this.requirements.get(n)??this.elements.get(n);if(!t||!e)return;for(let n of t)n.includes(`,`)?e.cssStyles.push(...n.split(`,`)):e.cssStyles.push(n)}}setClass(e,t){for(let n of e){let e=this.requirements.get(n)??this.elements.get(n);if(e)for(let n of t){e.classes.push(n);let t=this.classes.get(n)?.styles;t&&e.cssStyles.push(...t)}}}defineClass(e,t){for(let n of e){let e=this.classes.get(n);e===void 0&&(e={id:n,styles:[],textStyles:[]},this.classes.set(n,e)),t&&t.forEach(function(t){if(/color/.exec(t)){let n=t.replace(`fill`,`bgFill`);e.textStyles.push(n)}e.styles.push(t)}),this.requirements.forEach(e=>{e.classes.includes(n)&&e.cssStyles.push(...t.flatMap(e=>e.split(`,`)))}),this.elements.forEach(e=>{e.classes.includes(n)&&e.cssStyles.push(...t.flatMap(e=>e.split(`,`)))})}}getClasses(){return this.classes}getData(){let e=u(),t=[],n=[];for(let n of this.requirements.values()){let r=n;r.id=n.name,r.cssStyles=n.cssStyles,r.cssClasses=n.classes.join(` `),r.shape=`requirementBox`,r.look=e.look,r.colorIndex=t.length,t.push(r)}for(let n of this.elements.values()){let r=n;r.shape=`requirementBox`,r.look=e.look,r.id=n.name,r.cssStyles=n.cssStyles,r.cssClasses=n.classes.join(` `),r.colorIndex=t.length,t.push(r)}for(let t of this.relations){let r=0,i=t.type===this.Relationships.CONTAINS,a={id:`${t.src}-${t.dst}-${r}`,start:this.requirements.get(t.src)?.name??this.elements.get(t.src)?.name,end:this.requirements.get(t.dst)?.name??this.elements.get(t.dst)?.name,label:`<<${t.type}>>`,classes:`relationshipLine`,style:[`fill:none`,i?``:`stroke-dasharray: 10,7`],labelpos:`c`,thickness:`normal`,type:`normal`,pattern:i?`normal`:`dashed`,arrowTypeStart:i?`requirement_contains`:``,arrowTypeEnd:i?``:`requirement_arrow`,look:e.look,labelType:`markdown`};n.push(a),r++}return{nodes:t,edges:n,other:{},config:e,direction:this.getDirection()}}},b=e(e=>{let{themeVariables:t,look:n}=s(),{bkgColorArray:r,borderColorArray:i}=t;if(!i?.length)return``;let a=``;for(let t=0;t{let{look:t,themeVariables:n}=s(),{requirementEdgeLabelBackground:r}=n;return` + ${b(e)} + marker { + fill: ${e.relationColor}; + stroke: ${e.relationColor}; + } + + marker.cross { + stroke: ${e.lineColor}; + } + + svg { + font-family: ${e.fontFamily}; + font-size: ${e.fontSize}; + } + + .reqBox { + fill: ${e.requirementBackground}; + fill-opacity: 1.0; + stroke: ${e.requirementBorderColor}; + stroke-width: ${e.requirementBorderSize}; + } + + .reqTitle, .reqLabel{ + fill: ${e.requirementTextColor}; + } + .reqLabelBox { + fill: ${e.relationLabelBackground}; + fill-opacity: 1.0; + } + + .req-title-line { + stroke: ${e.requirementBorderColor}; + stroke-width: ${e.requirementBorderSize}; + } + .relationshipLine { + stroke: ${e.relationColor}; + stroke-width: ${t===`neo`?e.strokeWidth:`1px`}; + } + .relationshipLabel { + fill: ${e.relationLabelColor}; + } + .edgeLabel { + background-color: ${e.edgeLabelBackground}; + } + .edgeLabel .label rect { + fill: ${e.edgeLabelBackground}; + } + .edgeLabel .label text { + fill: ${e.relationLabelColor}; + } + .divider { + stroke: ${e.nodeBorder}; + stroke-width: 1; + } + .label { + font-family: ${e.fontFamily}; + color: ${e.nodeTextColor||e.textColor}; + } + .label text,span { + fill: ${e.nodeTextColor||e.textColor}; + color: ${e.nodeTextColor||e.textColor}; + } + .labelBkg { + background-color: ${r??e.edgeLabelBackground}; + } + +`},`getStyles`),S={};t(S,{draw:()=>C});var C=e(async function(e,t,r,i){n.info(`REF0:`),n.info(`Drawing requirement diagram (unified)`,t);let{securityLevel:a,state:o,layout:s,look:c}=u(),l=i.db.getData(),d=p(t,a);l.type=i.type,l.layoutAlgorithm=g(s),l.nodeSpacing=o?.nodeSpacing??50,l.rankSpacing=o?.rankSpacing??50,l.markers=c===`neo`?[`requirement_contains_neo`,`requirement_arrow_neo`]:[`requirement_contains`,`requirement_arrow`],l.diagramId=t,await h(l,d),f.insertTitle(d,`requirementDiagramTitleText`,o?.titleTopMargin??25,i.db.getDiagramTitle()),m(d,8,`requirementDiagram`,o?.useMaxWidth??!0)},`draw`),w={parser:v,get db(){return new y},renderer:S,styles:x};export{w as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/rolldown-runtime-aKtaBQYM.js b/dist-desktop/assets/rolldown-runtime-aKtaBQYM.js new file mode 100644 index 0000000..8e7d307 --- /dev/null +++ b/dist-desktop/assets/rolldown-runtime-aKtaBQYM.js @@ -0,0 +1 @@ +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});export{l as i,s as n,u as r,o as t}; \ No newline at end of file diff --git a/dist-desktop/assets/rough.esm-CSKSodPl.js b/dist-desktop/assets/rough.esm-CSKSodPl.js new file mode 100644 index 0000000..9f228ce --- /dev/null +++ b/dist-desktop/assets/rough.esm-CSKSodPl.js @@ -0,0 +1 @@ +function e(e,t,n){if(e&&e.length){let[r,i]=t,a=Math.PI/180*n,o=Math.cos(a),s=Math.sin(a);for(let t of e){let[e,n]=t;t[0]=(e-r)*o-(n-i)*s+r,t[1]=(e-r)*s+(n-i)*o+i}}}function t(e,t){return e[0]===t[0]&&e[1]===t[1]}function n(n,r,i,a=1){let o=i,s=Math.max(r,.1),c=n[0]&&n[0][0]&&typeof n[0][0]==`number`?[n]:n,l=[0,0];if(o)for(let t of c)e(t,l,o);let u=function(e,n,r){let i=[];for(let n of e){let e=[...n];t(e[0],e[e.length-1])||e.push([e[0][0],e[0][1]]),e.length>2&&i.push(e)}let a=[];n=Math.max(n,.1);let o=[];for(let e of i)for(let t=0;te.ymint.ymin?1:e.xt.x?1:e.ymax===t.ymax?0:(e.ymax-t.ymax)/Math.abs(e.ymax-t.ymax))),!o.length)return a;let s=[],c=o[0].ymin,l=0;for(;s.length||o.length;){if(o.length){let e=-1;for(let t=0;tc);t++)e=t;o.splice(0,e+1).forEach((e=>{s.push({s:c,edge:e})}))}if(s=s.filter((e=>!(e.edge.ymax<=c))),s.sort(((e,t)=>e.edge.x===t.edge.x?0:(e.edge.x-t.edge.x)/Math.abs(e.edge.x-t.edge.x))),(r!==1||l%n==0)&&s.length>1)for(let e=0;e=s.length)break;let n=s[e].edge,r=s[t].edge;a.push([[Math.round(n.x),c],[Math.round(r.x),c]])}c+=r,s.forEach((e=>{e.edge.x=e.edge.x+r*e.edge.islope})),l++}return a}(c,s,a);if(o){for(let t of c)e(t,l,-o);(function(t,n,r){let i=[];t.forEach((e=>i.push(...e))),e(i,n,r)})(u,l,-o)}return u}function r(e,t){let r=t.hachureAngle+90,i=t.hachureGap;i<0&&(i=4*t.strokeWidth),i=Math.round(Math.max(i,.1));let a=1;return t.roughness>=1&&(t.randomizer?.next()||Math.random())>.7&&(a=i),n(e,i,r,a||1)}var i=class{constructor(e){this.helper=e}fillPolygons(e,t){return this._fillPolygons(e,t)}_fillPolygons(e,t){let n=r(e,t);return{type:`fillSketch`,ops:this.renderLines(n,t)}}renderLines(e,t){let n=[];for(let r of e)n.push(...this.helper.doubleLineOps(r[0][0],r[0][1],r[1][0],r[1][1],t));return n}};function a(e){let t=e[0],n=e[1];return Math.sqrt((t[0]-n[0])**2+(t[1]-n[1])**2)}var o=class extends i{fillPolygons(e,t){let n=t.hachureGap;n<0&&(n=4*t.strokeWidth),n=Math.max(n,.1);let i=r(e,Object.assign({},t,{hachureGap:n})),o=Math.PI/180*t.hachureAngle,s=[],c=.5*n*Math.cos(o),l=.5*n*Math.sin(o);for(let[e,t]of i)a([e,t])&&s.push([[e[0]-c,e[1]+l],[...t]],[[e[0]+c,e[1]-l],[...t]]);return{type:`fillSketch`,ops:this.renderLines(s,t)}}},s=class extends i{fillPolygons(e,t){let n=this._fillPolygons(e,t),r=Object.assign({},t,{hachureAngle:t.hachureAngle+90}),i=this._fillPolygons(e,r);return n.ops=n.ops.concat(i.ops),n}},c=class{constructor(e){this.helper=e}fillPolygons(e,t){let n=r(e,t=Object.assign({},t,{hachureAngle:0}));return this.dotsOnLines(n,t)}dotsOnLines(e,t){let n=[],r=t.hachureGap;r<0&&(r=4*t.strokeWidth),r=Math.max(r,.1);let i=t.fillWeight;i<0&&(i=t.strokeWidth/2);let o=r/4;for(let s of e){let e=a(s),c=e/r,l=Math.ceil(c)-1,u=e-l*r,d=(s[0][0]+s[1][0])/2-r/4,f=Math.min(s[0][1],s[1][1]);for(let e=0;e{let o=a(e),s=Math.floor(o/(n+r)),c=(o+r-s*(n+r))/2,l=e[0],u=e[1];l[0]>u[0]&&(l=e[1],u=e[0]);let d=Math.atan((u[1]-l[1])/(u[0]-l[0]));for(let e=0;e{let i=a(e),o=Math.round(i/(2*t)),s=e[0],c=e[1];s[0]>c[0]&&(s=e[1],c=e[0]);let l=Math.atan((c[1]-s[1])/(c[0]-s[0]));for(let e=0;er%2?e+n:e+t));a.push({key:`C`,data:e}),t=e[4],n=e[5];break}case`Q`:a.push({key:`Q`,data:[...s]}),t=s[2],n=s[3];break;case`q`:{let e=s.map(((e,r)=>r%2?e+n:e+t));a.push({key:`Q`,data:e}),t=e[2],n=e[3];break}case`A`:a.push({key:`A`,data:[...s]}),t=s[5],n=s[6];break;case`a`:t+=s[5],n+=s[6],a.push({key:`A`,data:[s[0],s[1],s[2],s[3],s[4],t,n]});break;case`H`:a.push({key:`H`,data:[...s]}),t=s[0];break;case`h`:t+=s[0],a.push({key:`H`,data:[t]});break;case`V`:a.push({key:`V`,data:[...s]}),n=s[0];break;case`v`:n+=s[0],a.push({key:`V`,data:[n]});break;case`S`:a.push({key:`S`,data:[...s]}),t=s[2],n=s[3];break;case`s`:{let e=s.map(((e,r)=>r%2?e+n:e+t));a.push({key:`S`,data:e}),t=e[2],n=e[3];break}case`T`:a.push({key:`T`,data:[...s]}),t=s[0],n=s[1];break;case`t`:t+=s[0],n+=s[1],a.push({key:`T`,data:[t,n]});break;case`Z`:case`z`:a.push({key:`Z`,data:[]}),t=r,n=i}return a}function b(e){let t=[],n=``,r=0,i=0,a=0,o=0,s=0,c=0;for(let{key:l,data:u}of e){switch(l){case`M`:t.push({key:`M`,data:[...u]}),[r,i]=u,[a,o]=u;break;case`C`:t.push({key:`C`,data:[...u]}),r=u[4],i=u[5],s=u[2],c=u[3];break;case`L`:t.push({key:`L`,data:[...u]}),[r,i]=u;break;case`H`:r=u[0],t.push({key:`L`,data:[r,i]});break;case`V`:i=u[0],t.push({key:`L`,data:[r,i]});break;case`S`:{let e=0,a=0;n===`C`||n===`S`?(e=r+(r-s),a=i+(i-c)):(e=r,a=i),t.push({key:`C`,data:[e,a,...u]}),s=u[0],c=u[1],r=u[2],i=u[3];break}case`T`:{let[e,a]=u,o=0,l=0;n===`Q`||n===`T`?(o=r+(r-s),l=i+(i-c)):(o=r,l=i);let d=r+2*(o-r)/3,f=i+2*(l-i)/3,p=e+2*(o-e)/3,m=a+2*(l-a)/3;t.push({key:`C`,data:[d,f,p,m,e,a]}),s=o,c=l,r=e,i=a;break}case`Q`:{let[e,n,a,o]=u,l=r+2*(e-r)/3,d=i+2*(n-i)/3,f=a+2*(e-a)/3,p=o+2*(n-o)/3;t.push({key:`C`,data:[l,d,f,p,a,o]}),s=e,c=n,r=a,i=o;break}case`A`:{let e=Math.abs(u[0]),n=Math.abs(u[1]),a=u[2],o=u[3],s=u[4],c=u[5],l=u[6];e===0||n===0?(t.push({key:`C`,data:[r,i,c,l,c,l]}),r=c,i=l):(r!==c||i!==l)&&(S(r,i,c,l,e,n,a,o,s).forEach((function(e){t.push({key:`C`,data:e})})),r=c,i=l);break}case`Z`:t.push({key:`Z`,data:[]}),r=a,i=o}n=l}return t}function x(e,t,n){return[e*Math.cos(n)-t*Math.sin(n),e*Math.sin(n)+t*Math.cos(n)]}function S(e,t,n,r,i,a,o,s,c,l){let u=(d=o,Math.PI*d/180);var d;let f=[],p=0,m=0,h=0,g=0;if(l)[p,m,h,g]=l;else{[e,t]=x(e,t,-u),[n,r]=x(n,r,-u);let o=(e-n)/2,l=(t-r)/2,d=o*o/(i*i)+l*l/(a*a);d>1&&(d=Math.sqrt(d),i*=d,a*=d);let f=i*i,_=a*a,v=f*_-f*l*l-_*o*o,y=f*l*l+_*o*o,b=(s===c?-1:1)*Math.sqrt(Math.abs(v/y));h=b*i*l/a+(e+n)/2,g=b*-a*o/i+(t+r)/2,p=Math.asin(parseFloat(((t-g)/a).toFixed(9))),m=Math.asin(parseFloat(((r-g)/a).toFixed(9))),em&&(p-=2*Math.PI),!c&&m>p&&(m-=2*Math.PI)}let _=m-p;if(Math.abs(_)>120*Math.PI/180){let e=m,t=n,s=r;m=c&&m>p?p+120*Math.PI/180*1:p+120*Math.PI/180*-1,f=S(n=h+i*Math.cos(m),r=g+a*Math.sin(m),t,s,i,a,o,0,c,[m,e,h,g])}_=m-p;let v=Math.cos(p),y=Math.sin(p),b=Math.cos(m),C=Math.sin(m),w=Math.tan(_/4),T=4/3*i*w,E=4/3*a*w,D=[e,t],O=[e+T*y,t-E*v],k=[n+T*C,r-E*b],A=[n,r];if(O[0]=2*D[0]-O[0],O[1]=2*D[1]-O[1],l)return[O,k,A].concat(f);{f=[O,k,A].concat(f);let e=[];for(let t=0;t2){let i=[];for(let t=0;t2*Math.PI&&(p=0,m=2*Math.PI);let h=2*Math.PI/c.curveStepCount,g=Math.min(h/2,(m-p)/2),_=U(g,l,u,d,f,p,m,1,c);if(!c.disableMultiStroke){let e=U(g,l,u,d,f,p,m,1.5,c);_.push(...e)}return o&&(s?_.push(...R(l,u,l+d*Math.cos(p),u+f*Math.sin(p),c),...R(l,u,l+d*Math.cos(m),u+f*Math.sin(m),c)):_.push({op:`lineTo`,data:[l,u]},{op:`lineTo`,data:[l+d*Math.cos(p),u+f*Math.sin(p)]})),{type:`path`,ops:_}}function j(e,t){let n=b(y(v(e))),r=[],i=[0,0],a=[0,0];for(let{key:e,data:o}of n)switch(e){case`M`:a=[o[0],o[1]],i=[o[0],o[1]];break;case`L`:r.push(...R(a[0],a[1],o[0],o[1],t)),a=[o[0],o[1]];break;case`C`:{let[e,n,i,s,c,l]=o;r.push(...ee(e,n,i,s,c,l,a,t)),a=[c,l];break}case`Z`:r.push(...R(a[0],a[1],i[0],i[1],t)),a=[i[0],i[1]]}return{type:`path`,ops:r}}function M(e,t){let n=[];for(let r of e)if(r.length){let e=t.maxRandomnessOffset||0,i=r.length;if(i>2){n.push({op:`move`,data:[r[0][0]+L(e,t),r[0][1]+L(e,t)]});for(let a=1;a500?.4:-.0016668*c+1.233334;let u=i.maxRandomnessOffset||0;u*u*100>s&&(u=c/10);let d=u/2,f=.2+.2*F(i),p=i.bowing*i.maxRandomnessOffset*(r-t)/200,m=i.bowing*i.maxRandomnessOffset*(e-n)/200;p=L(p,i,l),m=L(m,i,l);let h=[],g=()=>L(d,i,l),_=()=>L(u,i,l),v=i.preserveVertices;return a&&(o?h.push({op:`move`,data:[e+(v?0:g()),t+(v?0:g())]}):h.push({op:`move`,data:[e+(v?0:L(u,i,l)),t+(v?0:L(u,i,l))]})),o?h.push({op:`bcurveTo`,data:[p+e+(n-e)*f+g(),m+t+(r-t)*f+g(),p+e+2*(n-e)*f+g(),m+t+2*(r-t)*f+g(),n+(v?0:g()),r+(v?0:g())]}):h.push({op:`bcurveTo`,data:[p+e+(n-e)*f+_(),m+t+(r-t)*f+_(),p+e+2*(n-e)*f+_(),m+t+2*(r-t)*f+_(),n+(v?0:_()),r+(v?0:_())]}),h}function B(e,t,n){if(!e.length)return[];let r=[];r.push([e[0][0]+L(t,n),e[0][1]+L(t,n)]),r.push([e[0][0]+L(t,n),e[0][1]+L(t,n)]);for(let i=1;i3){let a=[],o=1-n.curveTightness;i.push({op:`move`,data:[e[1][0],e[1][1]]});for(let t=1;t+21&&i.push(n):i.push(n),i.push(e[t+3])}else{let r=.5,a=e[t+0],o=e[t+1],s=e[t+2],c=e[t+3],l=q(a,o,r),u=q(o,s,r),d=q(s,c,r),f=q(l,u,r),p=q(u,d,r),m=q(f,p,r);J([a,l,f,m],0,n,i),J([m,p,d,c],0,n,i)}var a,o;return i}function ne(e,t){return Y(e,0,e.length,t)}function Y(e,t,n,r,i){let a=i||[],o=e[t],s=e[n-1],c=0,l=1;for(let r=t+1;rc&&(c=t,l=r)}return Math.sqrt(c)>r?(Y(e,t,l+1,r,a),Y(e,l,n,r,a)):(a.length||a.push(o),a.push(s)),a}function X(e,t=.15,n){let r=[],i=(e.length-1)/3;for(let n=0;n0?Y(r,0,r.length,n):r}var Z=`none`,Q=class{constructor(e){this.defaultOptions={maxRandomnessOffset:2,roughness:1,bowing:1,stroke:`#000`,strokeWidth:1,curveTightness:0,curveFitting:.95,curveStepCount:9,fillStyle:`hachure`,fillWeight:-1,hachureAngle:-41,hachureGap:-1,dashOffset:-1,dashGap:-1,zigzagOffset:-1,seed:0,disableMultiStroke:!1,disableMultiStrokeFill:!1,preserveVertices:!1,fillShapeRoughnessGain:.8},this.config=e||{},this.config.options&&(this.defaultOptions=this._o(this.config.options))}static newSeed(){return Math.floor(Math.random()*2**31)}_o(e){return e?Object.assign({},this.defaultOptions,e):this.defaultOptions}_d(e,t,n){return{shape:e,sets:t||[],options:n||this.defaultOptions}}line(e,t,n,r,i){let a=this._o(i);return this._d(`line`,[w(e,t,n,r,a)],a)}rectangle(e,t,n,r,i){let a=this._o(i),o=[],s=E(e,t,n,r,a);if(a.fill){let i=[[e,t],[e+n,t],[e+n,t+r],[e,t+r]];a.fillStyle===`solid`?o.push(M([i],a)):o.push(N([i],a))}return a.stroke!==Z&&o.push(s),this._d(`rectangle`,o,a)}ellipse(e,t,n,r,i){let a=this._o(i),o=[],s=O(n,r,a),c=k(e,t,a,s);if(a.fill)if(a.fillStyle===`solid`){let n=k(e,t,a,s).opset;n.type=`fillPath`,o.push(n)}else o.push(N([c.estimatedPoints],a));return a.stroke!==Z&&o.push(c.opset),this._d(`ellipse`,o,a)}circle(e,t,n,r){let i=this.ellipse(e,t,n,n,r);return i.shape=`circle`,i}linearPath(e,t){let n=this._o(t);return this._d(`linearPath`,[T(e,!1,n)],n)}arc(e,t,n,r,i,a,o=!1,s){let c=this._o(s),l=[],u=A(e,t,n,r,i,a,o,!0,c);if(o&&c.fill)if(c.fillStyle===`solid`){let o=Object.assign({},c);o.disableMultiStroke=!0;let s=A(e,t,n,r,i,a,!0,!1,o);s.type=`fillPath`,l.push(s)}else l.push(function(e,t,n,r,i,a,o){let s=e,c=t,l=Math.abs(n/2),u=Math.abs(r/2);l+=L(.01*l,o),u+=L(.01*u,o);let d=i,f=a;for(;d<0;)d+=2*Math.PI,f+=2*Math.PI;f-d>2*Math.PI&&(d=0,f=2*Math.PI);let p=(f-d)/o.curveStepCount,m=[];for(let e=d;e<=f;e+=p)m.push([s+l*Math.cos(e),c+u*Math.sin(e)]);return m.push([s+l*Math.cos(f),c+u*Math.sin(f)]),m.push([s,c]),N([m],o)}(e,t,n,r,i,a,c));return c.stroke!==Z&&l.push(u),this._d(`arc`,l,c)}curve(e,t){let n=this._o(t),r=[],i=D(e,n);if(n.fill&&n.fill!==Z)if(n.fillStyle===`solid`){let t=D(e,Object.assign(Object.assign({},n),{disableMultiStroke:!0,roughness:n.roughness?n.roughness+n.fillShapeRoughnessGain:0}));r.push({type:`fillPath`,ops:this._mergedShape(t.ops)})}else{let t=[],i=e;if(i.length){let e=typeof i[0][0]==`number`?[i]:i;for(let r of e)r.length<3?t.push(...r):r.length===3?t.push(...X(G([r[0],r[0],r[1],r[2]]),10,(1+n.roughness)/2)):t.push(...X(G(r),10,(1+n.roughness)/2))}t.length&&r.push(N([t],n))}return n.stroke!==Z&&r.push(i),this._d(`curve`,r,n)}polygon(e,t){let n=this._o(t),r=[],i=T(e,!0,n);return n.fill&&(n.fillStyle===`solid`?r.push(M([e],n)):r.push(N([e],n))),n.stroke!==Z&&r.push(i),this._d(`polygon`,r,n)}path(e,t){let n=this._o(t),r=[];if(!e)return this._d(`path`,r,n);e=(e||``).replace(/\n/g,` `).replace(/(-\s)/g,`-`).replace(`/(ss)/g`,` `);let i=n.fill&&n.fill!==`transparent`&&n.fill!==Z,a=n.stroke!==Z,o=!!(n.simplification&&n.simplification<1),s=function(e,t,n){let r=b(y(v(e))),i=[],a=[],o=[0,0],s=[],c=()=>{s.length>=4&&a.push(...X(s,t)),s=[]},l=()=>{c(),a.length&&(i.push(a),a=[])};for(let{key:e,data:t}of r)switch(e){case`M`:l(),o=[t[0],t[1]],a.push(o);break;case`L`:c(),a.push([t[0],t[1]]);break;case`C`:if(!s.length){let e=a.length?a[a.length-1]:o;s.push([e[0],e[1]])}s.push([t[0],t[1]]),s.push([t[2],t[3]]),s.push([t[4],t[5]]);break;case`Z`:c(),a.push([o[0],o[1]])}if(l(),!n)return i;let u=[];for(let e of i){let t=ne(e,n);t.length&&u.push(t)}return u}(e,1,o?4-4*(n.simplification||1):(1+n.roughness)/2),c=j(e,n);if(i)if(n.fillStyle===`solid`)if(s.length===1){let t=j(e,Object.assign(Object.assign({},n),{disableMultiStroke:!0,roughness:n.roughness?n.roughness+n.fillShapeRoughnessGain:0}));r.push({type:`fillPath`,ops:this._mergedShape(t.ops)})}else r.push(M(s,n));else r.push(N(s,n));return a&&(o?s.forEach((e=>{r.push(T(e,!1,n))})):r.push(c)),this._d(`path`,r,n)}opsToPath(e,t){let n=``;for(let r of e.ops){let e=typeof t==`number`&&t>=0?r.data.map((e=>+e.toFixed(t))):r.data;switch(r.op){case`move`:n+=`M${e[0]} ${e[1]} `;break;case`bcurveTo`:n+=`C${e[0]} ${e[1]}, ${e[2]} ${e[3]}, ${e[4]} ${e[5]} `;break;case`lineTo`:n+=`L${e[0]} ${e[1]} `}}return n.trim()}toPaths(e){let t=e.sets||[],n=e.options||this.defaultOptions,r=[];for(let e of t){let t=null;switch(e.type){case`path`:t={d:this.opsToPath(e),stroke:n.stroke,strokeWidth:n.strokeWidth,fill:Z};break;case`fillPath`:t={d:this.opsToPath(e),stroke:Z,strokeWidth:0,fill:n.fill||Z};break;case`fillSketch`:t=this.fillSketch(e,n)}t&&r.push(t)}return r}fillSketch(e,t){let n=t.fillWeight;return n<0&&(n=t.strokeWidth/2),{d:this.opsToPath(e),stroke:t.fill||Z,strokeWidth:n,fill:Z}}_mergedShape(e){return e.filter(((e,t)=>t===0||e.op!==`move`))}},re=class{constructor(e,t){this.canvas=e,this.ctx=this.canvas.getContext(`2d`),this.gen=new Q(t)}draw(e){let t=e.sets||[],n=e.options||this.getDefaultOptions(),r=this.ctx,i=e.options.fixedDecimalPlaceDigits;for(let a of t)switch(a.type){case`path`:r.save(),r.strokeStyle=n.stroke===`none`?`transparent`:n.stroke,r.lineWidth=n.strokeWidth,n.strokeLineDash&&r.setLineDash(n.strokeLineDash),n.strokeLineDashOffset&&(r.lineDashOffset=n.strokeLineDashOffset),this._drawToContext(r,a,i),r.restore();break;case`fillPath`:{r.save(),r.fillStyle=n.fill||``;let t=e.shape===`curve`||e.shape===`polygon`||e.shape===`path`?`evenodd`:`nonzero`;this._drawToContext(r,a,i,t),r.restore();break}case`fillSketch`:this.fillSketch(r,a,n)}}fillSketch(e,t,n){let r=n.fillWeight;r<0&&(r=n.strokeWidth/2),e.save(),n.fillLineDash&&e.setLineDash(n.fillLineDash),n.fillLineDashOffset&&(e.lineDashOffset=n.fillLineDashOffset),e.strokeStyle=n.fill||``,e.lineWidth=r,this._drawToContext(e,t,n.fixedDecimalPlaceDigits),e.restore()}_drawToContext(e,t,n,r=`nonzero`){e.beginPath();for(let r of t.ops){let t=typeof n==`number`&&n>=0?r.data.map((e=>+e.toFixed(n))):r.data;switch(r.op){case`move`:e.moveTo(t[0],t[1]);break;case`bcurveTo`:e.bezierCurveTo(t[0],t[1],t[2],t[3],t[4],t[5]);break;case`lineTo`:e.lineTo(t[0],t[1])}}t.type===`fillPath`?e.fill(r):e.stroke()}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}line(e,t,n,r,i){let a=this.gen.line(e,t,n,r,i);return this.draw(a),a}rectangle(e,t,n,r,i){let a=this.gen.rectangle(e,t,n,r,i);return this.draw(a),a}ellipse(e,t,n,r,i){let a=this.gen.ellipse(e,t,n,r,i);return this.draw(a),a}circle(e,t,n,r){let i=this.gen.circle(e,t,n,r);return this.draw(i),i}linearPath(e,t){let n=this.gen.linearPath(e,t);return this.draw(n),n}polygon(e,t){let n=this.gen.polygon(e,t);return this.draw(n),n}arc(e,t,n,r,i,a,o=!1,s){let c=this.gen.arc(e,t,n,r,i,a,o,s);return this.draw(c),c}curve(e,t){let n=this.gen.curve(e,t);return this.draw(n),n}path(e,t){let n=this.gen.path(e,t);return this.draw(n),n}},$=`http://www.w3.org/2000/svg`,ie=class{constructor(e,t){this.svg=e,this.gen=new Q(t)}draw(e){let t=e.sets||[],n=e.options||this.getDefaultOptions(),r=this.svg.ownerDocument||window.document,i=r.createElementNS($,`g`),a=e.options.fixedDecimalPlaceDigits;for(let o of t){let t=null;switch(o.type){case`path`:t=r.createElementNS($,`path`),t.setAttribute(`d`,this.opsToPath(o,a)),t.setAttribute(`stroke`,n.stroke),t.setAttribute(`stroke-width`,n.strokeWidth+``),t.setAttribute(`fill`,`none`),n.strokeLineDash&&t.setAttribute(`stroke-dasharray`,n.strokeLineDash.join(` `).trim()),n.strokeLineDashOffset&&t.setAttribute(`stroke-dashoffset`,`${n.strokeLineDashOffset}`);break;case`fillPath`:t=r.createElementNS($,`path`),t.setAttribute(`d`,this.opsToPath(o,a)),t.setAttribute(`stroke`,`none`),t.setAttribute(`stroke-width`,`0`),t.setAttribute(`fill`,n.fill||``),e.shape!==`curve`&&e.shape!==`polygon`||t.setAttribute(`fill-rule`,`evenodd`);break;case`fillSketch`:t=this.fillSketch(r,o,n)}t&&i.appendChild(t)}return i}fillSketch(e,t,n){let r=n.fillWeight;r<0&&(r=n.strokeWidth/2);let i=e.createElementNS($,`path`);return i.setAttribute(`d`,this.opsToPath(t,n.fixedDecimalPlaceDigits)),i.setAttribute(`stroke`,n.fill||``),i.setAttribute(`stroke-width`,r+``),i.setAttribute(`fill`,`none`),n.fillLineDash&&i.setAttribute(`stroke-dasharray`,n.fillLineDash.join(` `).trim()),n.fillLineDashOffset&&i.setAttribute(`stroke-dashoffset`,`${n.fillLineDashOffset}`),i}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}opsToPath(e,t){return this.gen.opsToPath(e,t)}line(e,t,n,r,i){let a=this.gen.line(e,t,n,r,i);return this.draw(a)}rectangle(e,t,n,r,i){let a=this.gen.rectangle(e,t,n,r,i);return this.draw(a)}ellipse(e,t,n,r,i){let a=this.gen.ellipse(e,t,n,r,i);return this.draw(a)}circle(e,t,n,r){let i=this.gen.circle(e,t,n,r);return this.draw(i)}linearPath(e,t){let n=this.gen.linearPath(e,t);return this.draw(n)}polygon(e,t){let n=this.gen.polygon(e,t);return this.draw(n)}arc(e,t,n,r,i,a,o=!1,s){let c=this.gen.arc(e,t,n,r,i,a,o,s);return this.draw(c)}curve(e,t){let n=this.gen.curve(e,t);return this.draw(n)}path(e,t){let n=this.gen.path(e,t);return this.draw(n)}},ae={canvas:(e,t)=>new re(e,t),svg:(e,t)=>new ie(e,t),generator:e=>new Q(e),newSeed:()=>Q.newSeed()};export{ae as t}; \ No newline at end of file diff --git a/dist-desktop/assets/routes-BDn33g5C.js b/dist-desktop/assets/routes-BDn33g5C.js new file mode 100644 index 0000000..55c290f --- /dev/null +++ b/dist-desktop/assets/routes-BDn33g5C.js @@ -0,0 +1,67 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-lwoghoVk.js","assets/index-CXgd9jpl.js","assets/rolldown-runtime-aKtaBQYM.js","assets/react-BLJmJXjR.js","assets/utils-BTuSbA5p.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-UMNXGZaF.js","assets/chunk-WYO6CB5R-Dv5kDyQC.js","assets/chunk-ICXQ74PX-Czpgj8Uw.js","assets/dist-qx0Iv9vM.js","assets/chunk-VAUOI2AC-AC9pRUsa.js","assets/chunk-HOUHSVGY-iJuv90UH.js","assets/chunk-Q4XR5HBZ-CQ8zkLYc.js","assets/chunk-7BUUIJ7U-Bb538aSH.js","assets/chunk-OGEWGWER-D-nWYRNR.js","assets/chunk-C7G6YPKG-DW-1jWUA.js","assets/chunk-ZGVPDNZ5-DGInJAPD.js","assets/rough.esm-CSKSodPl.js","assets/chunk-52WLFC77-BOCvVCX1.js","assets/line-b9Ala942.js","assets/path-BWPyau1x.js","assets/array-BifhSqXX.js","assets/chunk-FWX5IMBZ-ComLEIwh.js","assets/chunk-ZIRB5QZD-C6fEPe3t.js","assets/client-CwgDvMJw.js"])))=>i.map(i=>d[i]); +import{i as e,r as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}from"./react-BLJmJXjR.js";import{G as i,i as a,n as o,t as s,u as c}from"./utils-BTuSbA5p.js";import{a as l,d as u,f as d,i as f,l as p,n as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./index-CXgd9jpl.js";import{i as x}from"./client-CwgDvMJw.js";import{a as S,c as C,i as w,n as T,o as E,r as D,s as O,t as k}from"./input-mze7gZ5r.js";function A(e){if(Array.isArray(e))return e.flatMap(e=>A(e));if(typeof e!=`string`)return[];let t=[],n=0,r,i,a,o,s,c=()=>{for(;n(i=e.charAt(n),i!==`=`&&i!==`;`&&i!==`,`);for(;n=e.length)&&t.push(e.slice(r))}return t}function j(e){return e instanceof Headers?e:Array.isArray(e)||typeof e==`object`?new Headers(e):null}function M(...e){return e.reduce((e,t)=>{let n=j(t);if(!n)return e;for(let[t,r]of n.entries())t===`set-cookie`?A(r).forEach(t=>e.append(`set-cookie`,t)):e.set(t,r);return e},new Headers)}var N=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),P=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),F=e=>{let t=P(e);return t.charAt(0).toUpperCase()+t.slice(1)},I=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),L=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0},R={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},z=e(r()),B=(0,z.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,z.createElement)(`svg`,{ref:c,...R,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:I(`lucide`,i),...!a&&!L(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,z.createElement)(e,t)),...Array.isArray(a)?a:[a]])),V=(e,t)=>{let n=(0,z.forwardRef)(({className:n,...r},i)=>(0,z.createElement)(B,{ref:i,iconNode:t,className:I(`lucide-${N(F(e))}`,`lucide-${e}`,n),...r}));return n.displayName=F(e),n},ee=V(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),H=V(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),te=V(`arrow-right`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),ne=V(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),re=V(`bot`,[[`path`,{d:`M12 8V4H8`,key:`hb8ula`}],[`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`,key:`enze0r`}],[`path`,{d:`M2 14h2`,key:`vft8re`}],[`path`,{d:`M20 14h2`,key:`4cs60a`}],[`path`,{d:`M15 13v2`,key:`1xurst`}],[`path`,{d:`M9 13v2`,key:`rq6x2g`}]]),U=V(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),ie=V(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),ae=V(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),W=V(`cloud-off`,[[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M5.782 5.782A7 7 0 0 0 9 19h8.5a4.5 4.5 0 0 0 1.307-.193`,key:`yfwify`}],[`path`,{d:`M21.532 16.5A4.5 4.5 0 0 0 17.5 10h-1.79A7.008 7.008 0 0 0 10 5.07`,key:`jlfiyv`}]]),oe=V(`cloud`,[[`path`,{d:`M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z`,key:`p7xjir`}]]),se=V(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),ce=V(`copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),le=V(`download`,[[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`polyline`,{points:`7 10 12 15 17 10`,key:`2ggqvy`}],[`line`,{x1:`12`,x2:`12`,y1:`15`,y2:`3`,key:`1vk2je`}]]),ue=V(`ellipsis`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]]),de=V(`eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),fe=V(`file-down`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M12 18v-6`,key:`17g6i2`}],[`path`,{d:`m9 15 3 3 3-3`,key:`1npd3o`}]]),pe=V(`file-text`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),me=V(`folder-input`,[[`path`,{d:`M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1`,key:`fm4g5t`}],[`path`,{d:`M2 13h10`,key:`pgb2dq`}],[`path`,{d:`m9 16 3-3-3-3`,key:`6m91ic`}]]),he=V(`folder-open`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),ge=V(`folder-output`,[[`path`,{d:`M2 7.5V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-1.5`,key:`1yk7aj`}],[`path`,{d:`M2 13h10`,key:`pgb2dq`}],[`path`,{d:`m5 10-3 3 3 3`,key:`1r8ie0`}]]),_e=V(`folder-plus`,[[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`M9 13h6`,key:`1uhe8q`}],[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),ve=V(`grip-vertical`,[[`circle`,{cx:`9`,cy:`12`,r:`1`,key:`1vctgf`}],[`circle`,{cx:`9`,cy:`5`,r:`1`,key:`hp0tcf`}],[`circle`,{cx:`9`,cy:`19`,r:`1`,key:`fkjjf6`}],[`circle`,{cx:`15`,cy:`12`,r:`1`,key:`1tmaij`}],[`circle`,{cx:`15`,cy:`5`,r:`1`,key:`19l28e`}],[`circle`,{cx:`15`,cy:`19`,r:`1`,key:`f4zoj3`}]]),ye=V(`hard-drive`,[[`line`,{x1:`22`,x2:`2`,y1:`12`,y2:`12`,key:`1y58io`}],[`path`,{d:`M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z`,key:`oot6mr`}],[`line`,{x1:`6`,x2:`6.01`,y1:`16`,y2:`16`,key:`sgf278`}],[`line`,{x1:`10`,x2:`10.01`,y1:`16`,y2:`16`,key:`1l4acy`}]]),be=V(`heading-1`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`m17 12 3-2v8`,key:`1hhhft`}]]),xe=V(`heading-2`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1`,key:`9jr5yi`}]]),Se=V(`heading-3`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2`,key:`68ncm8`}],[`path`,{d:`M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2`,key:`1ejuhz`}]]),Ce=V(`image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),we=V(`link-2`,[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]),Te=V(`list-ordered`,[[`path`,{d:`M10 12h11`,key:`6m4ad9`}],[`path`,{d:`M10 18h11`,key:`11hvi2`}],[`path`,{d:`M10 6h11`,key:`c7qv1k`}],[`path`,{d:`M4 10h2`,key:`16xx2s`}],[`path`,{d:`M4 6h1v4`,key:`cnovpq`}],[`path`,{d:`M6 18H4c0-1 2-2 2-3s-1-1.5-2-1`,key:`m9a95d`}]]),Ee=V(`list-todo`,[[`rect`,{x:`3`,y:`5`,width:`6`,height:`6`,rx:`1`,key:`1defrl`}],[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`path`,{d:`M13 6h8`,key:`15sg57`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 18h8`,key:`oe0vm4`}]]),De=V(`list-tree`,[[`path`,{d:`M21 12h-8`,key:`1bmf0i`}],[`path`,{d:`M21 6H8`,key:`1pqkrb`}],[`path`,{d:`M21 18h-8`,key:`1tm79t`}],[`path`,{d:`M3 6v4c0 1.1.9 2 2 2h3`,key:`1ywdgy`}],[`path`,{d:`M3 10v6c0 1.1.9 2 2 2h3`,key:`2wc746`}]]),Oe=V(`list`,[[`path`,{d:`M3 12h.01`,key:`nlz23k`}],[`path`,{d:`M3 18h.01`,key:`1tta3j`}],[`path`,{d:`M3 6h.01`,key:`1rqtza`}],[`path`,{d:`M8 12h13`,key:`1za7za`}],[`path`,{d:`M8 18h13`,key:`1lx6n3`}],[`path`,{d:`M8 6h13`,key:`ik3vkj`}]]),ke=V(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),Ae=V(`log-in`,[[`path`,{d:`M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4`,key:`u53s6r`}],[`polyline`,{points:`10 17 15 12 10 7`,key:`1ail0h`}],[`line`,{x1:`15`,x2:`3`,y1:`12`,y2:`12`,key:`v6grx8`}]]),je=V(`menu`,[[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 18h16`,key:`19g7jn`}],[`path`,{d:`M4 6h16`,key:`1o0s65`}]]),Me=V(`message-square`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}]]),Ne=V(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),Pe=V(`monitor`,[[`rect`,{width:`20`,height:`14`,x:`2`,y:`3`,rx:`2`,key:`48i651`}],[`line`,{x1:`8`,x2:`16`,y1:`21`,y2:`21`,key:`1svkeh`}],[`line`,{x1:`12`,x2:`12`,y1:`17`,y2:`21`,key:`vw1qmm`}]]),Fe=V(`moon`,[[`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`,key:`a7tn18`}]]),Ie=V(`panel-left-close`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`m16 15-3-3 3-3`,key:`14y99z`}]]),Le=V(`panel-left`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}]]),Re=V(`play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]),ze=V(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Be=V(`plug`,[[`path`,{d:`M12 22v-5`,key:`1ega77`}],[`path`,{d:`M9 8V2`,key:`14iosj`}],[`path`,{d:`M15 8V2`,key:`18g5xt`}],[`path`,{d:`M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z`,key:`osxo6l`}]]),Ve=V(`quote`,[[`path`,{d:`M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`rib7q0`}],[`path`,{d:`M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`1ymkrd`}]]),He=V(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Ue=V(`save`,[[`path`,{d:`M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,key:`1c8476`}],[`path`,{d:`M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7`,key:`1ydtos`}],[`path`,{d:`M7 3v4a1 1 0 0 0 1 1h7`,key:`t51u73`}]]),We=V(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Ge=V(`settings`,[[`path`,{d:`M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z`,key:`1qme2f`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),Ke=V(`sparkles`,[[`path`,{d:`M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z`,key:`4pj2yx`}],[`path`,{d:`M20 3v4`,key:`1olli1`}],[`path`,{d:`M22 5h-4`,key:`1gvqau`}],[`path`,{d:`M4 17v2`,key:`vumght`}],[`path`,{d:`M5 18H3`,key:`zchphs`}]]),qe=V(`square-check-big`,[[`path`,{d:`M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.5`,key:`1uzm8b`}],[`path`,{d:`m9 11 3 3L22 4`,key:`1pflzl`}]]),Je=V(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Ye=V(`star`,[[`path`,{d:`M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z`,key:`r04s7s`}]]),Xe=V(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),Ze=V(`table-2`,[[`path`,{d:`M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18`,key:`gugj83`}]]),Qe=V(`terminal`,[[`polyline`,{points:`4 17 10 11 4 5`,key:`akl6gq`}],[`line`,{x1:`12`,x2:`20`,y1:`19`,y2:`19`,key:`q2wloq`}]]),$e=V(`trash-2`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6`,key:`4alrt4`}],[`path`,{d:`M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2`,key:`v07s0e`}],[`line`,{x1:`10`,x2:`10`,y1:`11`,y2:`17`,key:`1uufr5`}],[`line`,{x1:`14`,x2:`14`,y1:`11`,y2:`17`,key:`xtxkd`}]]),et=V(`type`,[[`polyline`,{points:`4 7 4 4 20 4 20 7`,key:`1nosan`}],[`line`,{x1:`9`,x2:`15`,y1:`20`,y2:`20`,key:`swin9y`}],[`line`,{x1:`12`,x2:`12`,y1:`4`,y2:`20`,key:`1tx1rr`}]]),tt=V(`unlink`,[[`path`,{d:`m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71`,key:`yqzxt4`}],[`path`,{d:`m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71`,key:`4qinb0`}],[`line`,{x1:`8`,x2:`8`,y1:`2`,y2:`5`,key:`1041cp`}],[`line`,{x1:`2`,x2:`5`,y1:`8`,y2:`8`,key:`14m1p5`}],[`line`,{x1:`16`,x2:`16`,y1:`19`,y2:`22`,key:`rzdirn`}],[`line`,{x1:`19`,x2:`22`,y1:`16`,y2:`16`,key:`ox905f`}]]),nt=V(`upload`,[[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`polyline`,{points:`17 8 12 3 7 8`,key:`t8dd8p`}],[`line`,{x1:`12`,x2:`12`,y1:`3`,y2:`15`,key:`widbto`}]]),rt=V(`wand-sparkles`,[[`path`,{d:`m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72`,key:`ul74o6`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`M5 6v4`,key:`ilb8ba`}],[`path`,{d:`M19 14v4`,key:`blhpug`}],[`path`,{d:`M10 2v2`,key:`7u0qdc`}],[`path`,{d:`M7 8H3`,key:`zfb6yr`}],[`path`,{d:`M21 16h-4`,key:`1cnmox`}],[`path`,{d:`M11 3H9`,key:`1obp7u`}]]),it=V(`wifi`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M2 8.82a15 15 0 0 1 20 0`,key:`dnpr2z`}],[`path`,{d:`M5 12.859a10 10 0 0 1 14 0`,key:`1x1e6c`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}]]),at=V(`workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]),ot=V(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),st=V(`zap`,[[`path`,{d:`M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z`,key:`1xq2db`}]]),ct=Object.defineProperty,lt=(e,t)=>ct(e,`name`,{value:t,configurable:!0}),ut=!!(typeof window<`u`&&window.document&&window.document.createElement);function G(e,t,{checkForDefaultPrevented:n=!0}={}){return lt(function(r){if(e?.(r),n===!1||!r||!r.defaultPrevented)return t?.(r)},`handleEvent`)}lt(G,`composeEventHandlers`);function dt(e){if(!ut)throw Error(`Cannot access window outside of the DOM`);return e?.ownerDocument?.defaultView??window}lt(dt,`getOwnerWindow`);function ft(e){if(!ut)throw Error(`Cannot access document outside of the DOM`);return e?.ownerDocument??document}lt(ft,`getOwnerDocument`);function pt(e,t=!1){let{activeElement:n}=ft(e);if(!n?.nodeName)return null;if(mt(n)&&n.contentDocument)return pt(n.contentDocument.body,t);if(t){let e=n.getAttribute(`aria-activedescendant`);if(e){let t=ft(n).getElementById(e);if(t)return t}}return n}lt(pt,`getActiveElement`);function mt(e){return e.tagName===`IFRAME`}lt(mt,`isFrame`);var K=c(),ht=Object.defineProperty,gt=(e,t)=>ht(e,`name`,{value:t,configurable:!0});function _t(e,t){let n=z.createContext(t);n.displayName=e+`Context`;let r=gt(e=>{let{children:t,...r}=e,i=z.useMemo(()=>r,Object.values(r));return(0,K.jsx)(n.Provider,{value:i,children:t})},`Provider`);r.displayName=e+`Provider`;function i(r,i={}){let{optional:a=!1}=i,o=z.useContext(n);if(o)return o;if(t!==void 0)return t;if(!a)throw Error(`\`${r}\` must be used within \`${e}\``)}return gt(i,`useContext`),[r,i]}gt(_t,`createContext`);function vt(e,t=[]){let n=[];function r(t,r){let i=z.createContext(r);i.displayName=t+`Context`;let a=n.length;n=[...n,r];let o=gt(t=>{let{scope:n,children:r,...o}=t,s=n?.[e]?.[a]||i,c=z.useMemo(()=>o,Object.values(o));return(0,K.jsx)(s.Provider,{value:c,children:r})},`Provider`);o.displayName=t+`Provider`;function s(n,o,s={}){let{optional:c=!1}=s,l=o?.[e]?.[a]||i,u=z.useContext(l);if(u)return u;if(r!==void 0)return r;if(!c)throw Error(`\`${n}\` must be used within \`${t}\``)}return gt(s,`useContext`),[o,s]}gt(r,`createContext`);let i=gt(()=>{let t=n.map(e=>z.createContext(e));return gt(function(n){let r=n?.[e]||t;return z.useMemo(()=>({[`__scope${e}`]:{...n,[e]:r}}),[n,r])},`useScope`)},`createScope`);return i.scopeName=e,[r,yt(i,...t)]}gt(vt,`createContextScope`);function yt(...e){let t=e[0];if(e.length===1)return t;let n=gt(()=>{let n=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return gt(function(e){let r=n.reduce((t,{useScope:n,scopeName:r})=>{let i=n(e)[`__scope${r}`];return{...t,...i}},{});return z.useMemo(()=>({[`__scope${t.scopeName}`]:r}),[r])},`useComposedScopes`)},`createScope`);return n.scopeName=t.scopeName,n}gt(yt,`composeContextScopes`);var bt=e(i(),1),xt=Object.defineProperty,St=(e,t)=>xt(e,`name`,{value:t,configurable:!0}),q=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`].reduce((e,t)=>{let n=S(`Primitive.${t}`),r=z.forwardRef((e,r)=>{let{asChild:i,...a}=e,o=i?n:t;return typeof window<`u`&&(window[Symbol.for(`radix-ui`)]=!0),(0,K.jsx)(o,{...a,ref:r})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Ct(e,t){e&&bt.flushSync(()=>e.dispatchEvent(t))}St(Ct,`dispatchDiscreteCustomEvent`);var wt=Object.defineProperty,Tt=(e,t)=>wt(e,`name`,{value:t,configurable:!0});function Et(e){let t=z.useRef(e);return z.useEffect(()=>{t.current=e}),z.useMemo(()=>((...e)=>t.current?.(...e)),[])}Tt(Et,`useCallbackRef`);var Dt=Object.defineProperty,J=(e,t)=>Dt(e,`name`,{value:t,configurable:!0}),Ot=`dismissableLayer.update`,kt=`dismissableLayer.pointerDownOutside`,At=`dismissableLayer.focusOutside`,jt,Mt=z.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),Nt=z.forwardRef(J(function(e,t){let{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:r=!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:o,onInteractOutside:s,onDismiss:c,...l}=e,u=z.useContext(Mt),[d,f]=z.useState(null),p=d?.ownerDocument??globalThis?.document,[,m]=z.useState({}),h=C(t,f),g=Array.from(u.layers),[_]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),v=_?g.indexOf(_):-1,y=d?g.indexOf(d):-1,b=u.layersWithOutsidePointerEventsDisabled.size>0,x=y>=v,S=z.useRef(!1),w=It(e=>{a?.(e),s?.(e),e.defaultPrevented||c?.()},{ownerDocument:p,deferPointerDownOutside:r,isDeferredPointerDownOutsideRef:S,dismissableSurfaces:u.dismissableSurfaces,shouldHandlePointerDownOutside:z.useCallback(e=>{if(!(e instanceof Node))return!1;let t=[...u.branches].some(t=>t.contains(e));return x&&!t},[u.branches,x])}),T=Lt(e=>{if(r&&S.current)return;let t=e.target;[...u.branches].some(e=>e.contains(t))||(o?.(e),s?.(e),e.defaultPrevented||c?.())},p),E=d?y===g.length-1:!1,D=Et(e=>{e.key===`Escape`&&(i?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))});return z.useEffect(()=>{if(E)return p.addEventListener(`keydown`,D,{capture:!0}),()=>p.removeEventListener(`keydown`,D,{capture:!0})},[p,E,D]),z.useEffect(()=>{if(d)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(jt=p.body.style.pointerEvents,p.body.style.pointerEvents=`none`),u.layersWithOutsidePointerEventsDisabled.add(d)),u.layers.add(d),Rt(),()=>{n&&(u.layersWithOutsidePointerEventsDisabled.delete(d),u.layersWithOutsidePointerEventsDisabled.size===0&&(p.body.style.pointerEvents=jt))}},[d,p,n,u]),z.useEffect(()=>()=>{d&&(u.layers.delete(d),u.layersWithOutsidePointerEventsDisabled.delete(d),Rt())},[d,u]),z.useEffect(()=>{let e=J(()=>m({}),`handleUpdate`);return document.addEventListener(Ot,e),()=>document.removeEventListener(Ot,e)},[]),(0,K.jsx)(q.div,{...l,ref:h,style:{pointerEvents:b?x?`auto`:`none`:void 0,...e.style},onFocusCapture:G(e.onFocusCapture,T.onFocusCapture),onBlurCapture:G(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:G(e.onPointerDownCapture,w.onPointerDownCapture)})},`DismissableLayer`));function Pt(){let e=z.useContext(Mt),[t,n]=z.useState(null);return z.useEffect(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}J(Pt,`useDismissableLayerSurface`);var Ft=J(()=>!0,`IS_TRUE`);function It(e,t){let{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:o=Ft}=t,s=Et(e),c=z.useRef(!1),l=z.useRef(!1),u=z.useRef(new Map),d=z.useRef(()=>{});return z.useEffect(()=>{function e(){l.current=!1,i.current=!1,u.current.clear()}J(e,`resetOutsideInteraction`);function t(){return Array.from(u.current.values()).some(Boolean)}J(t,`isOutsideInteractionIntercepted`);function f(e){if(!l.current)return;let t=e.target;t instanceof Node&&[...a].some(e=>e.contains(t))||u.current.set(e.type,!0),e.type===`click`&&window.setTimeout(()=>{l.current&&d.current()},0)}J(f,`handleInteractionCapture`);function p(e){l.current&&u.current.set(e.type,!1)}J(p,`handleInteractionBubble`);let m=J(a=>{if(a.target&&!c.current){let f=function(){n.removeEventListener(`click`,d.current);let r=t();e(),r||zt(kt,s,p,{discrete:!0})};if(J(f,`handleAndDispatchPointerDownOutsideEvent`),!o(a.target)){n.removeEventListener(`click`,d.current),e(),c.current=!1;return}let p={originalEvent:a};l.current=!0,i.current=r&&a.button===0,u.current.clear(),!r||a.button!==0?f():(n.removeEventListener(`click`,d.current),d.current=f,n.addEventListener(`click`,d.current,{once:!0}))}else n.removeEventListener(`click`,d.current),e();c.current=!1},`handlePointerDown`),h=[`pointerup`,`mousedown`,`mouseup`,`touchstart`,`touchend`,`click`];for(let e of h)n.addEventListener(e,f,!0),n.addEventListener(e,p);let g=window.setTimeout(()=>{n.addEventListener(`pointerdown`,m)},0);return()=>{window.clearTimeout(g),n.removeEventListener(`pointerdown`,m),n.removeEventListener(`click`,d.current);for(let e of h)n.removeEventListener(e,f,!0),n.removeEventListener(e,p)}},[n,s,r,i,a,o]),{onPointerDownCapture:J(()=>c.current=!0,`onPointerDownCapture`)}}J(It,`usePointerDownOutside`);function Lt(e,t=globalThis?.document){let n=Et(e),r=z.useRef(!1);return z.useEffect(()=>{let e=J(e=>{e.target&&!r.current&&zt(At,n,{originalEvent:e},{discrete:!1})},`handleFocus`);return t.addEventListener(`focusin`,e),()=>t.removeEventListener(`focusin`,e)},[t,n]),{onFocusCapture:J(()=>r.current=!0,`onFocusCapture`),onBlurCapture:J(()=>r.current=!1,`onBlurCapture`)}}J(Lt,`useFocusOutside`);function Rt(){let e=new CustomEvent(Ot);document.dispatchEvent(e)}J(Rt,`dispatchUpdate`);function zt(e,t,n,{discrete:r}){let i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Ct(i,a):i.dispatchEvent(a)}J(zt,`handleAndDispatchCustomEvent`);var Bt=globalThis?.document?z.useLayoutEffect:()=>{},Vt=Object.defineProperty,Ht=(e,t)=>Vt(e,`name`,{value:t,configurable:!0}),Ut=z.useId||(()=>void 0),Wt=0;function Y(e){let[t,n]=z.useState(Ut());return Bt(()=>{e||n(e=>e??String(Wt++))},[e]),e||(t?`radix-${t}`:``)}Ht(Y,`useId`);var Gt=[`top`,`right`,`bottom`,`left`],Kt=Math.min,qt=Math.max,Jt=Math.round,Yt=Math.floor,Xt=e=>({x:e,y:e}),Zt={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function Qt(e,t,n){return qt(e,Kt(t,n))}function $t(e,t){return typeof e==`function`?e(t):e}function en(e){return e.split(`-`)[0]}function tn(e){return e.split(`-`)[1]}function nn(e){return e===`x`?`y`:`x`}function rn(e){return e===`y`?`height`:`width`}function an(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function on(e){return nn(an(e))}function sn(e,t,n){n===void 0&&(n=!1);let r=tn(e),i=on(e),a=rn(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=gn(o)),[o,gn(o)]}function cn(e){let t=gn(e);return[ln(e),t,ln(t)]}function ln(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var un=[`left`,`right`],dn=[`right`,`left`],fn=[`top`,`bottom`],pn=[`bottom`,`top`];function mn(e,t,n){switch(e){case`top`:case`bottom`:return n?t?dn:un:t?un:dn;case`left`:case`right`:return t?fn:pn;default:return[]}}function hn(e,t,n,r){let i=tn(e),a=mn(en(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(ln)))),a}function gn(e){let t=en(e);return Zt[t]+e.slice(t.length)}function _n(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function vn(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:_n(e)}function yn(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function bn(e,t,n){let{reference:r,floating:i}=e,a=an(t),o=on(t),s=rn(o),c=en(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=tn(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function xn(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=$t(t,e),p=vn(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=yn(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=yn(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var Sn=50,Cn=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:xn},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=bn(l,r,c),f=r,p=0,m={};for(let n=0;n({name:`arrow`,options:e,async fn(t){let{x:n,y:r,placement:i,rects:a,platform:o,elements:s,middlewareData:c}=t,{element:l,padding:u=0}=$t(e,t)||{};if(l==null)return{};let d=vn(u),f={x:n,y:r},p=on(i),m=rn(p),h=await o.getDimensions(l),g=p===`y`,_=g?`top`:`left`,v=g?`bottom`:`right`,y=g?`clientHeight`:`clientWidth`,b=a.reference[m]+a.reference[p]-f[p]-a.floating[m],x=f[p]-a.reference[p],S=await(o.getOffsetParent==null?void 0:o.getOffsetParent(l)),C=S?S[y]:0;(!C||!await(o.isElement==null?void 0:o.isElement(S)))&&(C=s.floating[y]||a.floating[m]);let w=b/2-x/2,T=C/2-h[m]/2-1,E=Kt(d[_],T),D=Kt(d[v],T),O=C-h[m]-D,k=C/2-h[m]/2+w,A=Qt(E,k,O),j=!c.arrow&&tn(i)!=null&&k!==A&&a.reference[m]/2-(ke<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(!(u===`alignment`&&_!==an(t))||T.every(e=>an(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=T.filter(e=>{if(x){let t=an(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o;break}if(r!==n)return{reset:{placement:n}}}return{}}}};function En(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Dn(e){return Gt.some(t=>e[t]>=0)}var On=function(e){return e===void 0&&(e={}),{name:`hide`,options:e,async fn(t){let{rects:n,platform:r}=t,{strategy:i=`referenceHidden`,...a}=$t(e,t);switch(i){case`referenceHidden`:{let e=En(await r.detectOverflow(t,{...a,elementContext:`reference`}),n.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:Dn(e)}}}case`escaped`:{let e=En(await r.detectOverflow(t,{...a,altBoundary:!0}),n.floating);return{data:{escapedOffsets:e,escaped:Dn(e)}}}default:return{}}}}},kn=new Set([`left`,`top`]);async function An(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=en(n),s=tn(n),c=an(n)===`y`,l=kn.has(o)?-1:1,u=a&&c?-1:1,d=$t(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var jn=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await An(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},Mn=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=$t(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=an(i),p=nn(f),m=u[p],h=u[f],g=(e,t)=>Qt(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}},Nn=function(e){return e===void 0&&(e={}),{options:e,fn(t){let{x:n,y:r,placement:i,rects:a,middlewareData:o}=t,{offset:s=0,mainAxis:c=!0,crossAxis:l=!0}=$t(e,t),u={x:n,y:r},d=an(i),f=nn(d),p=u[f],m=u[d],h=$t(s,t),g=typeof h==`number`?{mainAxis:h,crossAxis:0}:{mainAxis:h.mainAxis??0,crossAxis:h.crossAxis??0};if(c){let e=f===`y`?`height`:`width`,t=a.reference[f]-a.floating[e]+g.mainAxis,n=a.reference[f]+a.reference[e]-g.mainAxis;pn&&(p=n)}if(l){let e=f===`y`?`width`:`height`,t=kn.has(en(i)),n=a.reference[d]-a.floating[e]+(t&&o.offset?.[d]||0)+(t?0:g.crossAxis),r=a.reference[d]+a.reference[e]+(t?0:o.offset?.[d]||0)-(t?g.crossAxis:0);mr&&(m=r)}return{[f]:p,[d]:m}}}},Pn=function(e){return e===void 0&&(e={}),{name:`size`,options:e,async fn(t){let{placement:n,rects:r,platform:i,elements:a}=t,{apply:o=()=>{},...s}=$t(e,t),c=await i.detectOverflow(t,s),l=en(n),u=tn(n),d=an(n)===`y`,{width:f,height:p}=r.floating,m,h;l===`top`||l===`bottom`?(m=l,h=u===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?`start`:`end`)?`left`:`right`):(h=l,m=u===`end`?`top`:`bottom`);let g=p-c.top-c.bottom,_=f-c.left-c.right,v=Kt(p-c[m],g),y=Kt(f-c[h],_),b=t.middlewareData.shift,x=!b,S=v,C=y;b!=null&&b.enabled.x&&(C=_),b!=null&&b.enabled.y&&(S=g),x&&!u&&(d?C=f-2*qt(c.left,c.right):S=p-2*qt(c.top,c.bottom)),await o({...t,availableWidth:C,availableHeight:S});let w=await i.getDimensions(a.floating);return f!==w.width||p!==w.height?{reset:{rects:!0}}:{}}}};function Fn(){return typeof window<`u`}function In(e){return zn(e)?(e.nodeName||``).toLowerCase():`#document`}function Ln(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Rn(e){return((zn(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function zn(e){return Fn()?e instanceof Node||e instanceof Ln(e).Node:!1}function Bn(e){return Fn()?e instanceof Element||e instanceof Ln(e).Element:!1}function Vn(e){return Fn()?e instanceof HTMLElement||e instanceof Ln(e).HTMLElement:!1}function Hn(e){return!Fn()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof Ln(e).ShadowRoot}function Un(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=er(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function Wn(e){return/^(table|td|th)$/.test(In(e))}function Gn(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var Kn=/transform|translate|scale|rotate|perspective|filter/,qn=/paint|layout|strict|content/,Jn=e=>!!e&&e!==`none`,Yn;function Xn(e){let t=Bn(e)?er(e):e;return Jn(t.transform)||Jn(t.translate)||Jn(t.scale)||Jn(t.rotate)||Jn(t.perspective)||!Qn()&&(Jn(t.backdropFilter)||Jn(t.filter))||Kn.test(t.willChange||``)||qn.test(t.contain||``)}function Zn(e){let t=nr(e);for(;Vn(t)&&!$n(t);){if(Xn(t))return t;if(Gn(t))return null;t=nr(t)}return null}function Qn(){return Yn??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),Yn}function $n(e){return/^(html|body|#document)$/.test(In(e))}function er(e){return Ln(e).getComputedStyle(e)}function tr(e){return Bn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function nr(e){if(In(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||Hn(e)&&e.host||Rn(e);return Hn(t)?t.host:t}function rr(e){let t=nr(e);return $n(t)?(e.ownerDocument||e).body:Vn(t)&&Un(t)?t:rr(t)}function ir(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=rr(e),i=r===e.ownerDocument?.body,a=Ln(r);if(i){let e=ar(a);return t.concat(a,a.visualViewport||[],Un(r)?r:[],e&&n?ir(e):[])}else return t.concat(r,ir(r,[],n))}function ar(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function or(e){let t=er(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=Vn(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=Jt(n)!==a||Jt(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function sr(e){return Bn(e)?e:e.contextElement}function cr(e){let t=sr(e);if(!Vn(t))return Xt(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=or(t),o=(a?Jt(n.width):n.width)/r,s=(a?Jt(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}var lr=Xt(0);function ur(e){let t=Ln(e);return!Qn()||!t.visualViewport?lr:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function dr(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Ln(e)}function fr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=sr(e),o=Xt(1);t&&(r?Bn(r)&&(o=cr(r)):o=cr(e));let s=dr(a,n,r)?ur(a):Xt(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=Ln(a),t=Bn(r)?Ln(r):r,n=e,i=ar(n);for(;i&&t!==n;){let e=cr(i),t=i.getBoundingClientRect(),r=er(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=Ln(i),i=ar(n)}}return yn({width:u,height:d,x:c,y:l})}function pr(e,t){let n=tr(e).scrollLeft;return t?t.left+n:fr(Rn(e)).left+n}function mr(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-pr(e,n),y:n.top+t.scrollTop}}function hr(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=Rn(r),s=t?Gn(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=Xt(1),u=Xt(0),d=Vn(r);if((d||!a)&&((In(r)!==`body`||Un(o))&&(c=tr(r)),d)){let e=fr(r);l=cr(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?mr(o,c):Xt(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function gr(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function _r(e){let t=tr(e),n=e.ownerDocument.body,r=qt(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=qt(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+pr(e),o=-t.scrollTop;return er(n).direction===`rtl`&&(a+=qt(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var vr=25;function yr(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=Ln(e),a=Rn(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!Qn()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(pr(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=vr&&(s-=o)}return{width:s,height:c,x:l,y:u}}function br(e,t){let n=fr(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=cr(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function xr(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=yr(e,n,t);else if(t===`document`)r=_r(Rn(e));else if(Bn(t))r=br(t,n);else{let n=ur(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return yn(r)}function Sr(e,t){let n=t.get(e);if(n)return n;let r=ir(e,[],!1).filter(e=>Bn(e)&&In(e)!==`body`),i=null,a=er(e).position===`fixed`,o=a?nr(e):e;for(;Bn(o)&&!$n(o);){let e=er(o),t=Xn(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=nr(o)}return t.set(e,r),r}function Cr(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?Gn(t)?[]:Sr(t,this._c):[].concat(n),r],o=xr(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=Ln(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function Pr(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=sr(e),u=i||a?[...l?ir(l):[],...t?ir(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?Nr(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?fr(e):null;c&&g();function g(){let t=fr(e);h&&!Mr(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var Fr=jn,Ir=Mn,Lr=Tn,Rr=Pn,zr=On,Br=wn,Vr=Nn,Hr=(e,t,n)=>{let r=new Map,i=n??{},a={...jr,...i.platform,_c:r};return Cn(e,t,{...i,platform:a})},Ur=typeof document<`u`?z.useLayoutEffect:function(){};function Wr(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e==`function`&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e==`object`){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Wr(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){let n=i[r];if(!(n===`_owner`&&e.$$typeof)&&!Wr(e[n],t[n]))return!1}return!0}return e!==e&&t!==t}function Gr(e){return typeof window>`u`?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Kr(e,t){let n=Gr(e);return Math.round(t*n)/n}function qr(e){let t=z.useRef(e);return Ur(()=>{t.current=e}),t}function Jr(e){e===void 0&&(e={});let{placement:t=`bottom`,strategy:n=`absolute`,middleware:r=[],platform:i,elements:{reference:a,floating:o}={},transform:s=!0,whileElementsMounted:c,open:l}=e,[u,d]=z.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,p]=z.useState(r);Wr(f,r)||p(r);let[m,h]=z.useState(null),[g,_]=z.useState(null),v=z.useCallback(e=>{e!==S.current&&(S.current=e,h(e))},[]),y=z.useCallback(e=>{e!==C.current&&(C.current=e,_(e))},[]),b=a||m,x=o||g,S=z.useRef(null),C=z.useRef(null),w=z.useRef(u),T=c!=null,E=qr(c),D=qr(i),O=qr(l),k=z.useCallback(()=>{if(!S.current||!C.current)return;let e={placement:t,strategy:n,middleware:f};D.current&&(e.platform=D.current),Hr(S.current,C.current,e).then(e=>{let t={...e,isPositioned:O.current!==!1};A.current&&!Wr(w.current,t)&&(w.current=t,bt.flushSync(()=>{d(t)}))})},[f,t,n,D,O]);Ur(()=>{l===!1&&w.current.isPositioned&&(w.current.isPositioned=!1,d(e=>({...e,isPositioned:!1})))},[l]);let A=z.useRef(!1);Ur(()=>(A.current=!0,()=>{A.current=!1}),[]),Ur(()=>{if(b&&(S.current=b),x&&(C.current=x),b&&x){if(E.current)return E.current(b,x,k);k()}},[b,x,k,E,T]);let j=z.useMemo(()=>({reference:S,floating:C,setReference:v,setFloating:y}),[v,y]),M=z.useMemo(()=>({reference:b,floating:x}),[b,x]),N=z.useMemo(()=>{let e={position:n,left:0,top:0};if(!M.floating)return e;let t=Kr(M.floating,u.x),r=Kr(M.floating,u.y);return s?{...e,transform:`translate(`+t+`px, `+r+`px)`,...Gr(M.floating)>=1.5&&{willChange:`transform`}}:{position:n,left:t,top:r}},[n,s,M.floating,u.x,u.y]);return z.useMemo(()=>({...u,update:k,refs:j,elements:M,floatingStyles:N}),[u,k,j,M,N])}var Yr=e=>{function t(e){return{}.hasOwnProperty.call(e,`current`)}return{name:`arrow`,options:e,fn(n){let{element:r,padding:i}=typeof e==`function`?e(n):e;return r&&t(r)?r.current==null?{}:Br({element:r.current,padding:i}).fn(n):r?Br({element:r,padding:i}).fn(n):{}}}},Xr=(e,t)=>{let n=Fr(e);return{name:n.name,fn:n.fn,options:[e,t]}},Zr=(e,t)=>{let n=Ir(e);return{name:n.name,fn:n.fn,options:[e,t]}},Qr=(e,t)=>({fn:Vr(e).fn,options:[e,t]}),$r=(e,t)=>{let n=Lr(e);return{name:n.name,fn:n.fn,options:[e,t]}},ei=(e,t)=>{let n=Rr(e);return{name:n.name,fn:n.fn,options:[e,t]}},ti=(e,t)=>{let n=zr(e);return{name:n.name,fn:n.fn,options:[e,t]}},ni=(e,t)=>{let n=Yr(e);return{name:n.name,fn:n.fn,options:[e,t]}},ri=Object.defineProperty,ii=(e,t)=>ri(e,`name`,{value:t,configurable:!0});function ai(e){let[t,n]=z.useState(void 0);return Bt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});let t=new ResizeObserver(t=>{if(!Array.isArray(t)||!t.length)return;let r=t[0],i,a;if(`borderBoxSize`in r){let e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;i=t.inlineSize,a=t.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return t.observe(e,{box:`border-box`}),()=>t.unobserve(e)}else n(void 0)},[e]),t}ii(ai,`useSize`);var oi=Object.defineProperty,si=(e,t)=>oi(e,`name`,{value:t,configurable:!0}),ci=`Popper`,[li,ui]=vt(ci),[di,fi]=li(ci),pi=si(e=>{let{__scopePopper:t,children:n}=e,[r,i]=z.useState(null),[a,o]=z.useState(void 0);return(0,K.jsx)(di,{scope:t,anchor:r,onAnchorChange:i,placementState:a,setPlacementState:o,children:n})},`Popper`),mi=`PopperAnchor`,hi=z.forwardRef(si(function(e,t){let{__scopePopper:n,virtualRef:r,...i}=e,a=fi(mi,n),o=z.useRef(null),s=a.onAnchorChange,c=C(t,z.useCallback(e=>{o.current=e,e&&s(e)},[s])),l=z.useRef(null);z.useEffect(()=>{if(!r)return;let e=l.current;l.current=r.current,e!==l.current&&s(l.current)});let u=a.placementState&&Si(a.placementState),d=u?.[0],f=u?.[1];return r?null:(0,K.jsx)(q.div,{"data-radix-popper-side":d,"data-radix-popper-align":f,...i,ref:c})},`PopperAnchor`)),gi=`PopperContent`,[_i,vi]=li(gi),yi=z.forwardRef(si(function(e,t){let{__scopePopper:n,side:r=`bottom`,sideOffset:i=0,align:a=`center`,alignOffset:o=0,arrowPadding:s=0,avoidCollisions:c=!0,collisionBoundary:l=[],collisionPadding:u=0,sticky:d=`partial`,hideWhenDetached:f=!1,updatePositionStrategy:p=`optimized`,onPlaced:m,...h}=e,g=fi(gi,n),[_,v]=z.useState(null),y=C(t,v),[b,x]=z.useState(null),S=ai(b),w=S?.width??0,T=S?.height??0,E=r+(a===`center`?``:`-`+a),D=typeof u==`number`?u:{top:0,right:0,bottom:0,left:0,...u},O=Array.isArray(l)?l:[l],k=O.length>0,A={padding:D,boundary:O.filter(bi),altBoundary:k},{refs:j,floatingStyles:M,placement:N,isPositioned:P,middlewareData:F}=Jr({strategy:`fixed`,placement:E,whileElementsMounted:si((...e)=>Pr(...e,{animationFrame:p===`always`}),`whileElementsMounted`),elements:{reference:g.anchor},middleware:[Xr({mainAxis:i+T,alignmentAxis:o}),c&&Zr({mainAxis:!0,crossAxis:!1,limiter:d===`partial`?Qr():void 0,...A}),c&&$r({...A}),ei({...A,apply:si(({elements:e,rects:t,availableWidth:n,availableHeight:r})=>{let{width:i,height:a}=t.reference,o=e.floating.style;o.setProperty(`--radix-popper-available-width`,`${n}px`),o.setProperty(`--radix-popper-available-height`,`${r}px`),o.setProperty(`--radix-popper-anchor-width`,`${i}px`),o.setProperty(`--radix-popper-anchor-height`,`${a}px`)},`apply`)}),b&&ni({element:b,padding:s}),xi({arrowWidth:w,arrowHeight:T}),f&&ti({strategy:`referenceHidden`,...A,boundary:k?A.boundary:void 0})]}),I=g.setPlacementState;Bt(()=>(I(N),()=>{I(void 0)}),[N,I]);let[L,R]=Si(N),B=Et(m);Bt(()=>{P&&B?.()},[P,B]);let V=F.arrow?.x,ee=F.arrow?.y,H=F.arrow?.centerOffset!==0,[te,ne]=z.useState();return Bt(()=>{_&&ne(window.getComputedStyle(_).zIndex)},[_]),(0,K.jsx)(`div`,{ref:j.setFloating,"data-radix-popper-content-wrapper":``,style:{...M,transform:P?M.transform:`translate(0, -200%)`,minWidth:`max-content`,zIndex:te,"--radix-popper-transform-origin":[F.transformOrigin?.x,F.transformOrigin?.y].join(` `),...F.hide?.referenceHidden&&{visibility:`hidden`,pointerEvents:`none`}},dir:e.dir,children:(0,K.jsx)(_i,{scope:n,placedSide:L,placedAlign:R,onArrowChange:x,arrowX:V,arrowY:ee,shouldHideArrow:H,children:(0,K.jsx)(q.div,{"data-side":L,"data-align":R,...h,ref:y,style:{...h.style,animation:P?h.style?.animation:`none`}})})})},`PopperContent`));function bi(e){return e!==null}si(bi,`isNotNull`);var xi=si(e=>({name:`transformOrigin`,options:e,fn(t){let{placement:n,rects:r,middlewareData:i}=t,a=i.arrow?.centerOffset!==0,o=a?0:e.arrowWidth,s=a?0:e.arrowHeight,[c,l]=Si(n),u={start:`0%`,center:`50%`,end:`100%`}[l],d=(i.arrow?.x??0)+o/2,f=(i.arrow?.y??0)+s/2,p=``,m=``;return c===`bottom`?(p=a?u:`${d}px`,m=`${-s}px`):c===`top`?(p=a?u:`${d}px`,m=`${r.floating.height+s}px`):c===`right`?(p=`${-s}px`,m=a?u:`${f}px`):c===`left`&&(p=`${r.floating.width+s}px`,m=a?u:`${f}px`),{data:{x:p,y:m}}}}),`transformOrigin`);function Si(e){let[t,n=`center`]=e.split(`-`);return[t,n]}si(Si,`getSideAndAlignFromPlacement`);var Ci=Object.defineProperty,wi=z.forwardRef(((e,t)=>Ci(e,`name`,{value:t,configurable:!0}))(function(e,t){let{container:n,...r}=e,[i,a]=z.useState(!1);Bt(()=>a(!0),[]);let o=n||i&&globalThis?.document?.body;return o?bt.createPortal((0,K.jsx)(q.div,{...r,ref:t}),o):null},`Portal`)),Ti=Object.defineProperty,Ei=(e,t)=>Ti(e,`name`,{value:t,configurable:!0});function Di(e,t){return z.useReducer((e,n)=>t[e][n]??e,e)}Ei(Di,`useStateMachine`);var Oi=Ei(e=>{let{present:t,children:n}=e,r=ki(t),i=typeof n==`function`?n({present:r.isPresent}):z.Children.only(n),a=ji(r.ref,Ni(i));return typeof n==`function`||r.isPresent?z.cloneElement(i,{ref:a}):null},`Presence`);function ki(e){let[t,n]=z.useState(),r=z.useRef(null),i=z.useRef(e),a=z.useRef(`none`),o=z.useRef(void 0),[s,c]=Di(e?`mounted`:`unmounted`,{mounted:{UNMOUNT:`unmounted`,ANIMATION_OUT:`unmountSuspended`},unmountSuspended:{MOUNT:`mounted`,ANIMATION_END:`unmounted`},unmounted:{MOUNT:`mounted`}});return z.useEffect(()=>{s===`mounted`?(a.current=o.current??Mi(r.current),o.current=void 0):a.current=`none`},[s]),Bt(()=>{let t=r.current,n=i.current;if(n!==e){let r=a.current,s=Mi(t);e?(o.current=s,c(`MOUNT`)):s===`none`||t?.display===`none`?c(`UNMOUNT`):c(n&&r!==s?`ANIMATION_OUT`:`UNMOUNT`),i.current=e}},[e,c]),Bt(()=>{if(t){let e,n=t.ownerDocument.defaultView??window,o=Ei(a=>{let o=Mi(r.current).includes(CSS.escape(a.animationName));if(a.target===t&&o&&(c(`ANIMATION_END`),!i.current)){let r=t.style.animationFillMode;t.style.animationFillMode=`forwards`,e=n.setTimeout(()=>{t.style.animationFillMode===`forwards`&&(t.style.animationFillMode=r)})}},`handleAnimationEnd`),s=Ei(e=>{e.target===t&&(a.current=Mi(r.current))},`handleAnimationStart`);return t.addEventListener(`animationstart`,s),t.addEventListener(`animationcancel`,o),t.addEventListener(`animationend`,o),()=>{n.clearTimeout(e),t.removeEventListener(`animationstart`,s),t.removeEventListener(`animationcancel`,o),t.removeEventListener(`animationend`,o)}}else c(`ANIMATION_END`)},[t,c]),{isPresent:[`mounted`,`unmountSuspended`].includes(s),ref:z.useCallback(e=>{if(e){let t=getComputedStyle(e);r.current=t,o.current=Mi(t)}else r.current=null;n(e)},[])}}Ei(ki,`usePresence`);function Ai(e,t){if(typeof e==`function`)return e(t);e!=null&&(e.current=t)}Ei(Ai,`setRef`);function ji(...e){let t=z.useRef(e);return t.current=e,z.useCallback(e=>{let n=t.current,r=!1,i=n.map(t=>{let n=Ai(t,e);return!r&&typeof n==`function`&&(r=!0),n});if(r)return()=>{for(let e=0;ePi(e,`name`,{value:t,configurable:!0}),Ii=z.useEffectEvent,Li=z.useInsertionEffect;function Ri(e){if(typeof Ii==`function`)return Ii(e);let t=z.useRef(()=>{throw Error(`Cannot call an event handler while rendering.`)});return typeof Li==`function`?Li(()=>{t.current=e}):Bt(()=>{t.current=e}),z.useMemo(()=>((...e)=>t.current?.(...e)),[])}Fi(Ri,`useEffectEvent`);var zi=Object.defineProperty,Bi=(e,t)=>zi(e,`name`,{value:t,configurable:!0}),Vi=z.useInsertionEffect||Bt;function Hi({prop:e,defaultProp:t,onChange:n=Bi(()=>{},`onChange`),caller:r}){let[i,a,o]=Ui({defaultProp:t,onChange:n}),s=e!==void 0;return[s?e:i,z.useCallback(t=>{if(s){let n=Wi(t)?t(e):t;n!==e&&o.current?.(n)}else a(t)},[s,e,a,o])]}Bi(Hi,`useControllableState`);function Ui({defaultProp:e,onChange:t}){let[n,r]=z.useState(e),i=z.useRef(n),a=z.useRef(t);return Vi(()=>{a.current=t},[t]),z.useEffect(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}Bi(Ui,`useUncontrolledState`);function Wi(e){return typeof e==`function`}Bi(Wi,`isFunction`);var Gi=Symbol(`RADIX:SYNC_STATE`);function Ki(e,t,n,r){let{prop:i,defaultProp:a,onChange:o,caller:s}=t,c=i!==void 0,l=Ri(o),u=[{...n,state:a}];r&&u.push(r);let[d,f]=z.useReducer((t,n)=>{if(n.type===Gi)return{...t,state:n.state};let r=e(t,n);return c&&!Object.is(r.state,t.state)&&l(r.state),r},...u),p=d.state,m=z.useRef(p);z.useEffect(()=>{m.current!==p&&(m.current=p,c||l(p))},[p,m,c]);let h=z.useMemo(()=>i===void 0?d:{...d,state:i},[d,i]);return z.useEffect(()=>{c&&!Object.is(i,d.state)&&f({type:Gi,state:i})},[i,d.state,c]),[h,f]}Bi(Ki,`useControllableStateReducer`);var qi=Object.defineProperty,Ji=(e,t)=>qi(e,`name`,{value:t,configurable:!0}),[Yi,Xi]=vt(`Tooltip`,[ui]);ui();var Zi=`TooltipProvider`,Qi=700,[$i,ea]=Yi(Zi),ta=Ji(e=>{let{__scopeTooltip:t,delayDuration:n=Qi,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,o=z.useRef(!0),s=z.useRef(!1),c=z.useRef(0);return z.useEffect(()=>{let e=c.current;return()=>window.clearTimeout(e)},[]),(0,K.jsx)($i,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:z.useCallback(()=>{r<=0||(window.clearTimeout(c.current),o.current=!1)},[r]),onClose:z.useCallback(()=>{r<=0||(window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.current=!0,r))},[r]),isPointerInTransitRef:s,onPointerInTransitChange:z.useCallback(e=>{s.current=e},[]),disableHoverableContent:i,children:a})},`TooltipProvider`),[na,ra]=Yi(`Tooltip`),[ia,aa]=Yi(`TooltipPortal`,{forceMount:void 0});E(`TooltipContent`);function oa(e,t){let n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return`left`;case i:return`right`;case n:return`top`;case r:return`bottom`;default:throw Error(`unreachable`)}}Ji(oa,`getExitSideFromRect`);function sa(e,t,n=5){let r=[];switch(t){case`top`:r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case`bottom`:r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case`left`:r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case`right`:r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}Ji(sa,`getPaddedExitPoints`);function ca(e){let{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}Ji(ca,`getPointsFromRect`);function la(e,t){let{x:n,y:r}=e,i=!1;for(let e=0,a=t.length-1;er!=d>r&&n<(u-c)*(r-l)/(d-l)+c&&(i=!i)}return i}Ji(la,`isPointInPolygon`);function ua(e){let t=e.slice();return t.sort((e,t)=>e.xt.x?1:e.yt.y)),da(t)}Ji(ua,`getHull`);function da(e){if(e.length<=1)return e.slice();let t=[];for(let n=0;n=2;){let e=t[t.length-1],n=t[t.length-2];if((e.x-n.x)*(r.y-n.y)>=(e.y-n.y)*(r.x-n.x))t.pop();else break}t.push(r)}t.pop();let n=[];for(let t=e.length-1;t>=0;t--){let r=e[t];for(;n.length>=2;){let e=n[n.length-1],t=n[n.length-2];if((e.x-t.x)*(r.y-t.y)>=(e.y-t.y)*(r.x-t.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}Ji(da,`getHullPresorted`);function fa(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}Ji(fa,`concatAriaDescribedby`);var pa=ta,ma=Object.defineProperty,ha=(e,t)=>ma(e,`name`,{value:t,configurable:!0}),ga=z.createContext(void 0);function _a(e){let t=z.useContext(ga);return e||t||`ltr`}ha(_a,`useDirection`);var va=Object.defineProperty,ya=(e,t)=>va(e,`name`,{value:t,configurable:!0});function ba(e,[t,n]){return Math.min(n,Math.max(t,e))}ya(ba,`clamp`);var xa=Object.defineProperty,X=(e,t)=>xa(e,`name`,{value:t,configurable:!0});function Sa(e,t){return z.useReducer((e,n)=>t[e][n]??e,e)}X(Sa,`useStateMachine`);var Ca=`ScrollArea`,[wa,Ta]=vt(Ca),[Ea,Da]=wa(Ca),Oa=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,type:r=`hover`,dir:i,scrollHideDelay:a=600,...o}=e,[s,c]=z.useState(null),[l,u]=z.useState(null),[d,f]=z.useState(null),[p,m]=z.useState(null),[h,g]=z.useState(null),[_,v]=z.useState(0),[y,b]=z.useState(0),[x,S]=z.useState(!1),[w,T]=z.useState(!1),E=C(t,c),D=_a(i);return(0,K.jsx)(Ea,{scope:n,type:r,dir:D,scrollHideDelay:a,scrollArea:s,viewport:l,onViewportChange:u,content:d,onContentChange:f,scrollbarX:p,onScrollbarXChange:m,scrollbarXEnabled:x,onScrollbarXEnabledChange:S,scrollbarY:h,onScrollbarYChange:g,scrollbarYEnabled:w,onScrollbarYEnabledChange:T,onCornerWidthChange:v,onCornerHeightChange:b,children:(0,K.jsx)(q.div,{dir:D,...o,ref:E,style:{position:`relative`,"--radix-scroll-area-corner-width":_+`px`,"--radix-scroll-area-corner-height":y+`px`,...e.style}})})},`ScrollArea`)),ka=`ScrollAreaViewport`,Aa=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,children:r,nonce:i,...a}=e,o=Da(ka,n),s=C(t,z.useRef(null),o.onViewportChange);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ja,{nonce:i}),(0,K.jsx)(q.div,{"data-radix-scroll-area-viewport":``,...a,ref:s,style:{overflowX:o.scrollbarXEnabled?`scroll`:`hidden`,overflowY:o.scrollbarYEnabled?`scroll`:`hidden`,...e.style},children:(0,K.jsx)(`div`,{ref:o.onContentChange,style:{minWidth:`100%`,display:`table`},children:r})})]})},`ScrollAreaViewport`)),ja=z.memo(X(function({nonce:e}){return(0,K.jsx)(`style`,{dangerouslySetInnerHTML:{__html:`[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}`},nonce:e})},`ScrollAreaViewportStyle`),(e,t)=>e.nonce===t.nonce),Ma=`ScrollAreaScrollbar`,Na=z.forwardRef(X(function(e,t){let{forceMount:n,...r}=e,i=Da(Ma,e.__scopeScrollArea),{onScrollbarXEnabledChange:a,onScrollbarYEnabledChange:o}=i,s=e.orientation===`horizontal`;return z.useEffect(()=>(s?a(!0):o(!0),()=>{s?a(!1):o(!1)}),[s,a,o]),i.type===`hover`?(0,K.jsx)(Pa,{...r,ref:t,forceMount:n}):i.type===`scroll`?(0,K.jsx)(Fa,{...r,ref:t,forceMount:n}):i.type===`auto`?(0,K.jsx)(Ia,{...r,ref:t,forceMount:n}):i.type===`always`?(0,K.jsx)(La,{...r,ref:t,"data-state":`visible`}):null},`ScrollAreaScrollbar`)),Pa=z.forwardRef(X(function(e,t){let{forceMount:n,...r}=e,i=Da(Ma,e.__scopeScrollArea),[a,o]=z.useState(!1);return z.useEffect(()=>{let e=i.scrollArea,t=0;if(e){let n=X(()=>{window.clearTimeout(t),o(!0)},`handlePointerEnter`),r=X(()=>{t=window.setTimeout(()=>o(!1),i.scrollHideDelay)},`handlePointerLeave`);return e.addEventListener(`pointerenter`,n),e.addEventListener(`pointerleave`,r),()=>{window.clearTimeout(t),e.removeEventListener(`pointerenter`,n),e.removeEventListener(`pointerleave`,r)}}},[i.scrollArea,i.scrollHideDelay]),(0,K.jsx)(Oi,{present:n||a,children:(0,K.jsx)(Ia,{"data-state":a?`visible`:`hidden`,...r,ref:t})})},`ScrollAreaScrollbarHover`)),Fa=z.forwardRef(X(function(e,t){let{forceMount:n,...r}=e,i=Da(Ma,e.__scopeScrollArea),a=e.orientation===`horizontal`,o=ro(()=>c(`SCROLL_END`),100),[s,c]=Sa(`hidden`,{hidden:{SCROLL:`scrolling`},scrolling:{SCROLL_END:`idle`,POINTER_ENTER:`interacting`},interacting:{SCROLL:`interacting`,POINTER_LEAVE:`idle`},idle:{HIDE:`hidden`,SCROLL:`scrolling`,POINTER_ENTER:`interacting`}});return z.useEffect(()=>{if(s===`idle`){let e=window.setTimeout(()=>c(`HIDE`),i.scrollHideDelay);return()=>window.clearTimeout(e)}},[s,i.scrollHideDelay,c]),z.useEffect(()=>{let e=i.viewport,t=a?`scrollLeft`:`scrollTop`;if(e){let n=e[t],r=X(()=>{let r=e[t];n!==r&&(c(`SCROLL`),o()),n=r},`handleScroll`);return e.addEventListener(`scroll`,r),()=>e.removeEventListener(`scroll`,r)}},[i.viewport,a,c,o]),(0,K.jsx)(Oi,{present:n||s!==`hidden`,children:(0,K.jsx)(La,{"data-state":s===`hidden`?`hidden`:`visible`,...r,ref:t,onPointerEnter:G(e.onPointerEnter,()=>c(`POINTER_ENTER`)),onPointerLeave:G(e.onPointerLeave,()=>c(`POINTER_LEAVE`))})})},`ScrollAreaScrollbarScroll`)),Ia=z.forwardRef(X(function(e,t){let n=Da(Ma,e.__scopeScrollArea),{forceMount:r,...i}=e,[a,o]=z.useState(!1),s=e.orientation===`horizontal`,c=ro(()=>{if(n.viewport){let e=n.viewport.offsetWidth0&&l<1,onThumbChange:X(e=>a.current=e,`onThumbChange`),onThumbPointerUp:X(()=>o.current=0,`onThumbPointerUp`),onThumbPointerDown:X(e=>o.current=e,`onThumbPointerDown`)};function d(e,t){return Qa(e,o.current,s,t)}return X(d,`getScrollPosition`),n===`horizontal`?(0,K.jsx)(Ra,{...u,ref:t,onThumbPositionChange:()=>{if(i.viewport&&a.current){let e=i.viewport.scrollLeft,t=$a(e,s,i.dir);a.current.style.transform=`translate3d(${t}px, 0, 0)`}},onWheelScroll:e=>{i.viewport&&(i.viewport.scrollLeft=e)},onDragScroll:e=>{i.viewport&&(i.viewport.scrollLeft=d(e,i.dir))}}):n===`vertical`?(0,K.jsx)(za,{...u,ref:t,onThumbPositionChange:()=>{if(i.viewport&&a.current){let e=i.viewport.scrollTop,t=$a(e,s);a.current.style.transform=`translate3d(0, ${t}px, 0)`}},onWheelScroll:e=>{i.viewport&&(i.viewport.scrollTop=e)},onDragScroll:e=>{i.viewport&&(i.viewport.scrollTop=d(e))}}):null},`ScrollAreaScrollbarVisible`)),Ra=z.forwardRef(X(function(e,t){let{sizes:n,onSizesChange:r,...i}=e,a=Da(Ma,e.__scopeScrollArea),[o,s]=z.useState(),c=z.useRef(null),l=C(t,c,a.onScrollbarXChange);return z.useEffect(()=>{c.current&&s(getComputedStyle(c.current))},[c]),(0,K.jsx)(Ha,{"data-orientation":`horizontal`,...i,ref:l,sizes:n,style:{bottom:0,left:a.dir===`rtl`?`var(--radix-scroll-area-corner-width)`:0,right:a.dir===`ltr`?`var(--radix-scroll-area-corner-width)`:0,"--radix-scroll-area-thumb-width":Za(n)+`px`,...e.style},onThumbPointerDown:t=>e.onThumbPointerDown(t.x),onDragScroll:t=>e.onDragScroll(t.x),onWheelScroll:(t,n)=>{if(a.viewport){let r=a.viewport.scrollLeft+t.deltaX;e.onWheelScroll(r),to(r,n)&&t.preventDefault()}},onResize:()=>{c.current&&a.viewport&&o&&r({content:a.viewport.scrollWidth,viewport:a.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:Ya(o.paddingLeft),paddingEnd:Ya(o.paddingRight)}})}})},`ScrollAreaScrollbarX`)),za=z.forwardRef(X(function(e,t){let{sizes:n,onSizesChange:r,...i}=e,a=Da(Ma,e.__scopeScrollArea),[o,s]=z.useState(),c=z.useRef(null),l=C(t,c,a.onScrollbarYChange);return z.useEffect(()=>{c.current&&s(getComputedStyle(c.current))},[c]),(0,K.jsx)(Ha,{"data-orientation":`vertical`,...i,ref:l,sizes:n,style:{top:0,right:a.dir===`ltr`?0:void 0,left:a.dir===`rtl`?0:void 0,bottom:`var(--radix-scroll-area-corner-height)`,"--radix-scroll-area-thumb-height":Za(n)+`px`,...e.style},onThumbPointerDown:t=>e.onThumbPointerDown(t.y),onDragScroll:t=>e.onDragScroll(t.y),onWheelScroll:(t,n)=>{if(a.viewport){let r=a.viewport.scrollTop+t.deltaY;e.onWheelScroll(r),to(r,n)&&t.preventDefault()}},onResize:()=>{c.current&&a.viewport&&o&&r({content:a.viewport.scrollHeight,viewport:a.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:Ya(o.paddingTop),paddingEnd:Ya(o.paddingBottom)}})}})},`ScrollAreaScrollbarY`)),[Ba,Va]=wa(Ma),Ha=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,sizes:r,hasThumb:i,onThumbChange:a,onThumbPointerUp:o,onThumbPointerDown:s,onThumbPositionChange:c,onDragScroll:l,onWheelScroll:u,onResize:d,...f}=e,p=Da(Ma,n),[m,h]=z.useState(null),g=C(t,h),_=z.useRef(null),v=z.useRef(``),y=p.viewport,b=r.content-r.viewport,x=Et(u),S=Et(c),w=ro(d,10);function T(e){if(_.current){let t=e.clientX-_.current.left,n=e.clientY-_.current.top;l({x:t,y:n})}}return X(T,`handleDragScroll`),z.useEffect(()=>{let e=X(e=>{let t=e.target;m?.contains(t)&&x(e,b)},`handleWheel`);return document.addEventListener(`wheel`,e,{passive:!1}),()=>document.removeEventListener(`wheel`,e,{passive:!1})},[y,m,b,x]),z.useEffect(S,[r,S]),io(m,w),io(p.content,w),(0,K.jsx)(Ba,{scope:n,scrollbar:m,hasThumb:i,onThumbChange:Et(a),onThumbPointerUp:Et(o),onThumbPositionChange:S,onThumbPointerDown:Et(s),children:(0,K.jsx)(q.div,{...f,ref:g,style:{position:`absolute`,...f.style},onPointerDown:G(e.onPointerDown,e=>{e.button===0&&(e.target.setPointerCapture(e.pointerId),_.current=m.getBoundingClientRect(),v.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect=`none`,p.viewport&&(p.viewport.style.scrollBehavior=`auto`),T(e))}),onPointerMove:G(e.onPointerMove,T),onPointerUp:G(e.onPointerUp,e=>{let t=e.target;t.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId),document.body.style.webkitUserSelect=v.current,p.viewport&&(p.viewport.style.scrollBehavior=``),_.current=null})})})},`ScrollAreaScrollbarImpl`)),Ua=`ScrollAreaThumb`,Wa=z.forwardRef(X(function(e,t){let{forceMount:n,...r}=e,i=Va(Ua,e.__scopeScrollArea);return(0,K.jsx)(Oi,{present:n||i.hasThumb,children:(0,K.jsx)(Ga,{ref:t,...r})})},`ScrollAreaThumb`)),Ga=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,style:r,...i}=e,a=Da(Ua,n),o=Va(Ua,n),{onThumbPositionChange:s}=o,c=C(t,o.onThumbChange),l=z.useRef(void 0),u=ro(()=>{l.current&&=(l.current(),void 0)},100);return z.useEffect(()=>{let e=a.viewport;if(e){let t=X(()=>{if(u(),!l.current){let t=no(e,s);l.current=t,s()}},`handleScroll`);return s(),e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)}},[a.viewport,u,s]),(0,K.jsx)(q.div,{"data-state":o.hasThumb?`visible`:`hidden`,...i,ref:c,style:{width:`var(--radix-scroll-area-thumb-width)`,height:`var(--radix-scroll-area-thumb-height)`,...r},onPointerDownCapture:G(e.onPointerDownCapture,e=>{let t=e.target.getBoundingClientRect(),n=e.clientX-t.left,r=e.clientY-t.top;o.onThumbPointerDown({x:n,y:r})}),onPointerUp:G(e.onPointerUp,o.onThumbPointerUp)})},`ScrollAreaThumbImpl`)),Ka=`ScrollAreaCorner`,qa=z.forwardRef(X(function(e,t){let n=Da(Ka,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!==`scroll`&&r?(0,K.jsx)(Ja,{...e,ref:t}):null},`ScrollAreaCorner`)),Ja=z.forwardRef(X(function(e,t){let{__scopeScrollArea:n,...r}=e,i=Da(Ka,n),[a,o]=z.useState(0),[s,c]=z.useState(0),l=!!(a&&s),{onCornerWidthChange:u,onCornerHeightChange:d}=i;return io(i.scrollbarX,()=>{let e=i.scrollbarX?.offsetHeight||0;i.onCornerHeightChange(e),c(e)}),io(i.scrollbarY,()=>{let e=i.scrollbarY?.offsetWidth||0;i.onCornerWidthChange(e),o(e)}),z.useEffect(()=>()=>{u(0),d(0)},[u,d]),l?(0,K.jsx)(q.div,{...r,ref:t,style:{width:a,height:s,position:`absolute`,right:i.dir===`ltr`?0:void 0,left:i.dir===`rtl`?0:void 0,bottom:0,...e.style}}):null},`ScrollAreaCornerImpl`));function Ya(e){return e?parseInt(e,10):0}X(Ya,`toInt`);function Xa(e,t){let n=e/t;return isNaN(n)?0:n}X(Xa,`getThumbRatio`);function Za(e){let t=Xa(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}X(Za,`getThumbSize`);function Qa(e,t,n,r=`ltr`){let i=Za(n),a=i/2,o=t||a,s=i-o,c=n.scrollbar.paddingStart+o,l=n.scrollbar.size-n.scrollbar.paddingEnd-s,u=n.content-n.viewport,d=r===`ltr`?[0,u]:[u*-1,0];return eo([c,l],d)(e)}X(Qa,`getScrollPositionFromPointer`);function $a(e,t,n=`ltr`){let r=Za(t),i=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,a=t.scrollbar.size-i,o=t.content-t.viewport,s=a-r,c=ba(e,n===`ltr`?[0,o]:[o*-1,0]);return eo([0,o],[0,s])(c)}X($a,`getThumbOffsetFromScroll`);function eo(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];let r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}X(eo,`linearScale`);function to(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return X((function i(){let a={left:e.scrollLeft,top:e.scrollTop},o=n.left!==a.left,s=n.top!==a.top;(o||s)&&t(),n=a,r=window.requestAnimationFrame(i)}),`loop`)(),()=>window.cancelAnimationFrame(r)},`addUnlinkedScrollListener`);function ro(e,t){let n=Et(e),r=z.useRef(0);return z.useEffect(()=>()=>window.clearTimeout(r.current),[]),z.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}X(ro,`useDebounceCallback`);function io(e,t){let n=Et(t);Bt(()=>{let t=0;if(e){let r=new ResizeObserver(()=>{cancelAnimationFrame(t),t=window.requestAnimationFrame(n)});return r.observe(e),()=>{window.cancelAnimationFrame(t),r.unobserve(e)}}},[e,n])}X(io,`useResizeObserver`);function ao({className:e,children:t,...n}){return(0,K.jsxs)(Oa,{className:s(`relative overflow-hidden`,e),...n,children:[(0,K.jsx)(Aa,{className:`h-full w-full rounded-[inherit]`,children:t}),(0,K.jsx)(oo,{}),(0,K.jsx)(qa,{})]})}function oo({className:e,orientation:t=`vertical`,...n}){return(0,K.jsx)(Na,{orientation:t,className:s(`flex touch-none select-none transition-colors`,t===`vertical`&&`h-full w-2 border-l border-l-transparent p-px`,t===`horizontal`&&`h-2 flex-col border-t border-t-transparent p-px`,e),...n,children:(0,K.jsx)(Wa,{className:`relative flex-1 rounded-full bg-border`})})}var so=Object.defineProperty,Z=(e,t)=>so(e,`name`,{value:t,configurable:!0});function co(e){let t=e+`CollectionProvider`,[n,r]=vt(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=Z(e=>{let{scope:t,children:n}=e,r=z.useRef(null),a=z.useRef(new Map).current;return(0,K.jsx)(i,{scope:t,itemMap:a,collectionRef:r,children:n})},`CollectionProvider`);o.displayName=t;let s=e+`CollectionSlot`,c=S(s),l=z.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=C(t,a(s,n).collectionRef);return(0,K.jsx)(c,{ref:i,children:r})});l.displayName=s;let u=e+`CollectionItemSlot`,d=`data-radix-collection-item`,f=S(u),p=z.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=z.useRef(null),s=C(t,o),c=a(u,n);return z.useEffect(()=>(c.itemMap.set(o,{ref:o,...i}),()=>void c.itemMap.delete(o))),(0,K.jsx)(f,{[d]:``,ref:s,children:r})});p.displayName=u;function m(t){let n=a(e+`CollectionConsumer`,t);return z.useCallback(()=>{let e=n.collectionRef.current;if(!e)return[];let t=Array.from(e.querySelectorAll(`[${d}]`));return Array.from(n.itemMap.values()).sort((e,n)=>t.indexOf(e.ref.current)-t.indexOf(n.ref.current))},[n.collectionRef,n.itemMap])}return Z(m,`useCollection`),[{Provider:o,Slot:l,ItemSlot:p},m,r]}Z(co,`createCollection`);var lo=new WeakMap,uo=class e extends Map{static{Z(this,`OrderedDict`)}#e;constructor(e){super(e),this.#e=[...super.keys()],lo.set(this,!0)}set(e,t){return lo.get(this)&&(this.has(e)?this.#e[this.#e.indexOf(e)]=e:this.#e.push(e)),super.set(e,t),this}insert(e,t,n){let r=this.has(t),i=this.#e.length,a=mo(e),o=a>=0?a:i+a,s=o<0||o>=i?-1:o;if(s===this.size||r&&s===this.size-1||s===-1)return this.set(t,n),this;let c=this.size+ +!r;a<0&&o++;let l=[...this.#e],u,d=!1;for(let e=o;e=this.size&&(r=this.size-1),this.at(r)}keyFrom(e,t){let n=this.indexOf(e);if(n===-1)return;let r=n+t;return r<0&&(r=0),r>=this.size&&(r=this.size-1),this.keyAt(r)}find(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return r;n++}}findIndex(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return n;n++}return-1}filter(t,n){let r=[],i=0;for(let e of this)Reflect.apply(t,n,[e,i,this])&&r.push(e),i++;return new e(r)}map(t,n){let r=[],i=0;for(let e of this)r.push([e[0],Reflect.apply(t,n,[e,i,this])]),i++;return new e(r)}reduce(...e){let[t,n]=e,r=0,i=n??this.at(0);for(let n of this)i=r===0&&e.length===1?n:Reflect.apply(t,this,[i,n,r,this]),r++;return i}reduceRight(...e){let[t,n]=e,r=n??this.at(-1);for(let n=this.size-1;n>=0;n--){let i=this.at(n);r=n===this.size-1&&e.length===1?i:Reflect.apply(t,this,[r,i,n,this])}return r}toSorted(t){let n=[...this.entries()].sort(t);return new e(n)}toReversed(){let t=new e;for(let e=this.size-1;e>=0;e--){let n=this.keyAt(e),r=this.get(n);t.set(n,r)}return t}toSpliced(...t){let n=[...this.entries()];return n.splice(...t),new e(n)}slice(t,n){let r=new e,i=this.size-1;if(t===void 0)return r;t<0&&(t+=this.size),n!==void 0&&n>0&&(i=n-1);for(let e=t;e<=i;e++){let t=this.keyAt(e),n=this.get(t);r.set(t,n)}return r}every(e,t){let n=0;for(let r of this){if(!Reflect.apply(e,t,[r,n,this]))return!1;n++}return!0}some(e,t){let n=0;for(let r of this){if(Reflect.apply(e,t,[r,n,this]))return!0;n++}return!1}};function fo(e,t){if(`at`in Array.prototype)return Array.prototype.at.call(e,t);let n=po(e,t);return n===-1?void 0:e[n]}Z(fo,`at`);function po(e,t){let n=e.length,r=mo(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}Z(po,`toSafeIndex`);function mo(e){return e!==e||e===0?0:Math.trunc(e)}Z(mo,`toSafeInteger`);function ho(e){let t=e+`CollectionProvider`,[n,r]=vt(t),[i,a]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new uo,setItemMap:Z(()=>void 0,`setItemMap`)}),o=Z(({state:e,...t})=>e?(0,K.jsx)(c,{...t,state:e}):(0,K.jsx)(s,{...t}),`CollectionProvider`);o.displayName=t;let s=Z(e=>{let t=h();return(0,K.jsx)(c,{...e,state:t})},`CollectionInit`);s.displayName=t+`Init`;let c=Z(e=>{let{scope:t,children:n,state:r}=e,a=z.useRef(null),[o,s]=z.useState(null),c=C(a,s),[l,u]=r;return z.useEffect(()=>{if(!o)return;let e=yo(()=>{});return e.observe(o,{childList:!0,subtree:!0}),()=>{e.disconnect()}},[o]),(0,K.jsx)(i,{scope:t,itemMap:l,setItemMap:u,collectionRef:c,collectionRefObject:a,collectionElement:o,children:n})},`CollectionProviderImpl`);c.displayName=t+`Impl`;let l=e+`CollectionSlot`,u=S(l),d=z.forwardRef((e,t)=>{let{scope:n,children:r}=e,i=C(t,a(l,n).collectionRef);return(0,K.jsx)(u,{ref:i,children:r})});d.displayName=l;let f=e+`CollectionItemSlot`,p=S(f),m=z.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=z.useRef(null),[s,c]=z.useState(null),l=C(t,o,c),{setItemMap:u}=a(f,n),d=z.useRef(i);go(d.current,i)||(d.current=i);let m=d.current;return z.useEffect(()=>{let e=m;return u(t=>s?t.has(s)?t.set(s,{...e,element:s}).toSorted(vo):(t.set(s,{...e,element:s}),t.toSorted(vo)):t),()=>{u(e=>!s||!e.has(s)?e:(e.delete(s),new uo(e)))}},[s,m,u]),(0,K.jsx)(p,{"data-radix-collection-item":``,ref:l,children:r})});m.displayName=f;function h(){return z.useState(new uo)}Z(h,`useInitCollection`);function g(t){let{itemMap:n}=a(e+`CollectionConsumer`,t);return n}return Z(g,`useCollection`),[{Provider:o,Slot:d,ItemSlot:m},{createCollectionScope:r,useCollection:g,useInitCollection:h}]}Z(ho,`createCollection`);function go(e,t){if(e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e==null||t==null)return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||e[r]!==t[r])return!1;return!0}Z(go,`shallowEqual`);function _o(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}Z(_o,`isElementPreceding`);function vo(e,t){return!e[1].element||!t[1].element?0:_o(e[1].element,t[1].element)?-1:1}Z(vo,`sortByDocumentPosition`);function yo(e){return new MutationObserver(t=>{for(let n of t)if(n.type===`childList`){e();return}})}Z(yo,`getChildListObserver`);var bo=Object.defineProperty,xo=(e,t)=>bo(e,`name`,{value:t,configurable:!0}),So=0,Co=null;function wo(e){return To(),e.children}xo(wo,`FocusGuards`);function To(){z.useEffect(()=>{Co||={start:Eo(),end:Eo()};let{start:e,end:t}=Co;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement(`afterbegin`,e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement(`beforeend`,t),So++,()=>{So===1&&(Co?.start.remove(),Co?.end.remove(),Co=null),So=Math.max(0,So-1)}},[])}xo(To,`useFocusGuards`);function Eo(){let e=document.createElement(`span`);return e.setAttribute(`data-radix-focus-guard`,``),e.tabIndex=0,e.style.outline=`none`,e.style.opacity=`0`,e.style.position=`fixed`,e.style.pointerEvents=`none`,e}xo(Eo,`createFocusGuard`);var Do=Object.defineProperty,Oo=(e,t)=>Do(e,`name`,{value:t,configurable:!0}),ko=`focusScope.autoFocusOnMount`,Ao=`focusScope.autoFocusOnUnmount`,jo={bubbles:!1,cancelable:!0},Mo=z.forwardRef(Oo(function(e,t){let{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...o}=e,[s,c]=z.useState(null),l=Et(i),u=Et(a),d=z.useRef(null),f=C(t,c),p=z.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;z.useEffect(()=>{if(r){let e=function(e){if(p.paused||!s)return;let t=e.target;s.contains(t)?d.current=t:zo(d.current,{select:!0})},t=function(e){if(p.paused||!s)return;let t=e.relatedTarget;t!==null&&(s.contains(t)||zo(d.current,{select:!0}))},n=function(e){if(document.activeElement===document.body)for(let t of e)t.removedNodes.length>0&&zo(s)};Oo(e,`handleFocusIn`),Oo(t,`handleFocusOut`),Oo(n,`handleMutations`),document.addEventListener(`focusin`,e),document.addEventListener(`focusout`,t);let r=new MutationObserver(n);return s&&r.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener(`focusin`,e),document.removeEventListener(`focusout`,t),r.disconnect()}}},[r,s,p.paused]),z.useEffect(()=>{if(s){Bo.add(p);let e=document.activeElement;if(!s.contains(e)){let t=new CustomEvent(ko,jo);s.addEventListener(ko,l),s.dispatchEvent(t),t.defaultPrevented||(No(Uo(Fo(s)),{select:!0}),document.activeElement===e&&zo(s))}return()=>{s.removeEventListener(ko,l),setTimeout(()=>{let t=new CustomEvent(Ao,jo);s.addEventListener(Ao,u),s.dispatchEvent(t),t.defaultPrevented||zo(e??document.body,{select:!0}),s.removeEventListener(Ao,u),Bo.remove(p)},0)}}},[s,l,u,p]);let m=z.useCallback(e=>{if(!n&&!r||p.paused)return;let t=e.key===`Tab`&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){let t=e.currentTarget,[r,a]=Po(t);r&&a?!e.shiftKey&&i===a?(e.preventDefault(),n&&zo(r,{select:!0})):e.shiftKey&&i===r&&(e.preventDefault(),n&&zo(a,{select:!0})):i===t&&e.preventDefault()}},[n,r,p.paused]);return(0,K.jsx)(q.div,{tabIndex:-1,...o,ref:f,onKeyDown:m})},`FocusScope`));function No(e,{select:t=!1}={}){let n=document.activeElement;for(let r of e)if(zo(r,{select:t}),document.activeElement!==n)return}Oo(No,`focusFirst`);function Po(e){let t=Fo(e);return[Io(t,e),Io(t.reverse(),e)]}Oo(Po,`getTabbableEdges`);function Fo(e){let t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:Oo(e=>{let t=e.tagName===`INPUT`&&e.type===`hidden`;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},`acceptNode`)});for(;n.nextNode();)t.push(n.currentNode);return t}Oo(Fo,`getTabbableCandidates`);function Io(e,t){let n=typeof t.checkVisibility==`function`&&t.checkVisibility({checkVisibilityCSS:!0});for(let r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):Lo(r,{upTo:t})))return r}Oo(Io,`findVisible`);function Lo(e,{upTo:t}){if(getComputedStyle(e).visibility===`hidden`)return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display===`none`)return!0;e=e.parentElement}return!1}Oo(Lo,`isHidden`);function Ro(e){return e instanceof HTMLInputElement&&`select`in e}Oo(Ro,`isSelectableInput`);function zo(e,{select:t=!1}={}){if(e&&e.focus){let n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Ro(e)&&t&&e.select()}}Oo(zo,`focus`);var Bo=Vo();function Vo(){let e=[];return{add(t){let n=e[0];t!==n&&n?.pause(),e=Ho(e,t),e.unshift(t)},remove(t){e=Ho(e,t),e[0]?.resume()}}}Oo(Vo,`createFocusScopesStack`);function Ho(e,t){let n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}Oo(Ho,`arrayRemove`);function Uo(e){return e.filter(e=>e.tagName!==`A`)}Oo(Uo,`removeLinks`);var Wo=Object.defineProperty,Go=(e,t)=>Wo(e,`name`,{value:t,configurable:!0}),Ko=!1;function qo(){let[e,t]=z.useState(Ko);return z.useEffect(()=>{Ko||(Ko=!0,t(!0))},[]),e}Go(qo,`useIsHydrated`);var Jo=z.useSyncExternalStore;function Yo(){return()=>{}}Go(Yo,`subscribe`);function Xo(){return Jo(Yo,()=>!0,()=>!1)}Go(Xo,`useIsHydratedModern`);var Zo=typeof Jo==`function`?Xo:qo,Qo=Object.defineProperty,$o=(e,t)=>Qo(e,`name`,{value:t,configurable:!0}),es=`rovingFocusGroup.onEntryFocus`,ts={bubbles:!1,cancelable:!0},ns=`RovingFocusGroup`,[rs,is,as]=co(ns),[os,ss]=vt(ns,[as]),[cs,ls]=os(ns),us=z.forwardRef($o(function(e,t){return(0,K.jsx)(rs.Provider,{scope:e.__scopeRovingFocusGroup,children:(0,K.jsx)(rs.Slot,{scope:e.__scopeRovingFocusGroup,children:(0,K.jsx)(ds,{...e,ref:t})})})},`RovingFocusGroup`)),ds=z.forwardRef($o(function(e,t){let{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:a,currentTabStopId:o,defaultCurrentTabStopId:s,onCurrentTabStopIdChange:c,onEntryFocus:l,preventScrollOnEntryFocus:u=!1,...d}=e,f=z.useRef(null),p=C(t,f),m=_a(a),[h,g]=Hi({prop:o,defaultProp:s??null,onChange:c,caller:ns}),[_,v]=z.useState(!1),y=Et(l),b=is(n),x=z.useRef(!1),[S,w]=z.useState(0);return z.useEffect(()=>{let e=f.current;if(e)return e.addEventListener(es,y),()=>e.removeEventListener(es,y)},[y]),(0,K.jsx)(cs,{scope:n,orientation:r,dir:m,loop:i,currentTabStopId:h,onItemFocus:z.useCallback(e=>g(e),[g]),onItemShiftTab:z.useCallback(()=>v(!0),[]),onFocusableItemAdd:z.useCallback(()=>w(e=>e+1),[]),onFocusableItemRemove:z.useCallback(()=>w(e=>e-1),[]),children:(0,K.jsx)(q.div,{tabIndex:_||S===0?-1:0,"data-orientation":r,...d,ref:p,style:{outline:`none`,...e.style},onMouseDown:G(e.onMouseDown,()=>{x.current=!0}),onFocus:G(e.onFocus,e=>{let t=!x.current;if(e.target===e.currentTarget&&t&&!_){let t=new CustomEvent(es,ts);if(e.currentTarget.dispatchEvent(t),!t.defaultPrevented){let e=b().filter(e=>e.focusable);_s([e.find(e=>e.active),e.find(e=>e.id===h),...e].filter(Boolean).map(e=>e.ref.current),u)}}x.current=!1}),onBlur:G(e.onBlur,()=>v(!1))})})},`RovingFocusGroupImpl`)),fs=`RovingFocusGroupItem`,ps=z.forwardRef($o(function(e,t){let{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:a,children:o,...s}=e,c=Y(),l=a||c,u=ls(fs,n),d=u.currentTabStopId===l,f=is(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:h}=u,g=Zo();return Bt(()=>{if(!(!g||!r))return p(),()=>m()},[g,r,p,m]),z.useEffect(()=>{if(!(g||!r))return p(),()=>m()},[g,r,p,m]),(0,K.jsx)(rs.ItemSlot,{scope:n,id:l,focusable:r,active:i,children:(0,K.jsx)(q.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...s,ref:t,onMouseDown:G(e.onMouseDown,e=>{r?u.onItemFocus(l):e.preventDefault()}),onFocus:G(e.onFocus,()=>u.onItemFocus(l)),onKeyDown:G(e.onKeyDown,e=>{if(e.key===`Tab`&&e.shiftKey){u.onItemShiftTab();return}if(e.target!==e.currentTarget)return;let t=gs(e,u.orientation,u.dir);if(t!==void 0){if(e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)return;e.preventDefault();let n=f().filter(e=>e.focusable).map(e=>e.ref.current);if(t===`last`)n.reverse();else if(t===`prev`||t===`next`){t===`prev`&&n.reverse();let r=n.indexOf(e.currentTarget);n=u.loop?vs(n,r+1):n.slice(r+1)}setTimeout(()=>_s(n))}}),children:typeof o==`function`?o({isCurrentTabStop:d,hasTabStop:h!=null}):o})})},`RovingFocusGroupItem`)),ms={ArrowLeft:`prev`,ArrowUp:`prev`,ArrowRight:`next`,ArrowDown:`next`,PageUp:`first`,Home:`first`,PageDown:`last`,End:`last`};function hs(e,t){return t===`rtl`?e===`ArrowLeft`?`ArrowRight`:e===`ArrowRight`?`ArrowLeft`:e:e}$o(hs,`getDirectionAwareKey`);function gs(e,t,n){let r=hs(e.key,n);if(!(t===`vertical`&&[`ArrowLeft`,`ArrowRight`].includes(r))&&!(t===`horizontal`&&[`ArrowUp`,`ArrowDown`].includes(r)))return ms[r]}$o(gs,`getFocusIntent`);function _s(e,t=!1){let n=document.activeElement;for(let r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}$o(_s,`focusFirst`);function vs(e,t){return e.map((n,r)=>e[(t+r)%e.length])}$o(vs,`wrapArray`);var ys=function(e){return typeof document>`u`?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},bs=new WeakMap,xs=new WeakMap,Ss={},Cs=0,ws=function(e){return e&&(e.host||ws(e.parentNode))},Ts=function(e,t){return t.map(function(t){if(e.contains(t))return t;var n=ws(t);return n&&e.contains(n)?n:(console.error(`aria-hidden`,t,`in not contained inside`,e,`. Doing nothing`),null)}).filter(function(e){return!!e})},Es=function(e,t,n,r){var i=Ts(t,Array.isArray(e)?e:[e]);Ss[n]||(Ss[n]=new WeakMap);var a=Ss[n],o=[],s=new Set,c=new Set(i),l=function(e){!e||s.has(e)||(s.add(e),l(e.parentNode))};i.forEach(l);var u=function(e){!e||c.has(e)||Array.prototype.forEach.call(e.children,function(e){if(s.has(e))u(e);else try{var t=e.getAttribute(r),i=t!==null&&t!==`false`,c=(bs.get(e)||0)+1,l=(a.get(e)||0)+1;bs.set(e,c),a.set(e,l),o.push(e),c===1&&i&&xs.set(e,!0),l===1&&e.setAttribute(n,`true`),i||e.setAttribute(r,`true`)}catch(t){console.error(`aria-hidden: cannot operate on `,e,t)}})};return u(t),s.clear(),Cs++,function(){o.forEach(function(e){var t=bs.get(e)-1,i=a.get(e)-1;bs.set(e,t),a.set(e,i),t||(xs.has(e)||e.removeAttribute(r),xs.delete(e)),i||e.removeAttribute(n)}),Cs--,Cs||(bs=new WeakMap,bs=new WeakMap,xs=new WeakMap,Ss={})}},Ds=function(e,t,n){n===void 0&&(n=`data-aria-hidden`);var r=Array.from(Array.isArray(e)?e:[e]),i=t||ys(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll(`[aria-live], script`))),Es(r,i,n,`aria-hidden`)):function(){return null}},Os=function(){return Os=Object.assign||function(e){for(var t,n=1,r=arguments.length;n`u`)return nc;var t=ic(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},oc=tc(),sc=`data-scroll-locked`,cc=function(e,t,n,r){var i=e.left,a=e.top,o=e.right,s=e.gap;return n===void 0&&(n=`margin`),` + .${Ns} { + overflow: hidden ${r}; + padding-right: ${s}px ${r}; + } + body[${sc}] { + overflow: hidden ${r}; + overscroll-behavior: contain; + ${[t&&`position: relative ${r};`,n===`margin`&&` + padding-left: ${i}px; + padding-top: ${a}px; + padding-right: ${o}px; + margin-left:0; + margin-top:0; + margin-right: ${s}px ${r}; + `,n===`padding`&&`padding-right: ${s}px ${r};`].filter(Boolean).join(``)} + } + + .${js} { + right: ${s}px ${r}; + } + + .${Ms} { + margin-right: ${s}px ${r}; + } + + .${js} .${js} { + right: 0 ${r}; + } + + .${Ms} .${Ms} { + margin-right: 0 ${r}; + } + + body[${sc}] { + ${Ps}: ${s}px; + } +`},lc=function(){var e=parseInt(document.body.getAttribute(`data-scroll-locked`)||`0`,10);return isFinite(e)?e:0},uc=function(){z.useEffect(function(){return document.body.setAttribute(sc,(lc()+1).toString()),function(){var e=lc()-1;e<=0?document.body.removeAttribute(sc):document.body.setAttribute(sc,e.toString())}},[])},dc=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?`margin`:r;uc();var a=z.useMemo(function(){return ac(i)},[i]);return z.createElement(oc,{styles:cc(a,!t,i,n?``:`!important`)})},fc=!1;if(typeof window<`u`)try{var pc=Object.defineProperty({},"passive",{get:function(){return fc=!0,!0}});window.addEventListener(`test`,pc,pc),window.removeEventListener(`test`,pc,pc)}catch{fc=!1}var mc=fc?{passive:!1}:!1,hc=function(e){return e.tagName===`TEXTAREA`},gc=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!==`hidden`&&!(n.overflowY===n.overflowX&&!hc(e)&&n[t]===`visible`)},_c=function(e){return gc(e,`overflowY`)},vc=function(e){return gc(e,`overflowX`)},yc=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<`u`&&r instanceof ShadowRoot&&(r=r.host),Sc(e,r)){var i=Cc(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},bc=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},xc=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},Sc=function(e,t){return e===`v`?_c(t):vc(t)},Cc=function(e,t){return e===`v`?bc(t):xc(t)},wc=function(e,t){return e===`h`&&t===`rtl`?-1:1},Tc=function(e,t,n,r,i){var a=wc(e,window.getComputedStyle(t).direction),o=a*r,s=n.target,c=t.contains(s),l=!1,u=o>0,d=0,f=0;do{if(!s)break;var p=Cc(e,s),m=p[0],h=p[1]-p[2]-a*m;(m||h)&&Sc(e,s)&&(d+=h,f+=m);var g=s.parentNode;s=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}while(!c&&s!==document.body||c&&(t.contains(s)||t===s));return(u&&(i&&Math.abs(d)<1||!i&&o>d)||!u&&(i&&Math.abs(f)<1||!i&&-o>f))&&(l=!0),l},Ec=function(e){return`changedTouches`in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Dc=function(e){return[e.deltaX,e.deltaY]},Oc=function(e){return e&&`current`in e?e.current:e},kc=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Ac=function(e){return` + .block-interactivity-${e} {pointer-events: none;} + .allow-interactivity-${e} {pointer-events: all;} +`},jc=0,Mc=[];function Nc(e){var t=z.useRef([]),n=z.useRef([0,0]),r=z.useRef(),i=z.useState(jc++)[0],a=z.useState(tc)[0],o=z.useRef(e);z.useEffect(function(){o.current=e},[e]),z.useEffect(function(){if(e.inert){document.body.classList.add(`block-interactivity-${i}`);var t=As([e.lockRef.current],(e.shards||[]).map(Oc),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add(`allow-interactivity-${i}`)}),function(){document.body.classList.remove(`block-interactivity-${i}`),t.forEach(function(e){return e.classList.remove(`allow-interactivity-${i}`)})}}},[e.inert,e.lockRef.current,e.shards]);var s=z.useCallback(function(e,t){if(`touches`in e&&e.touches.length===2||e.type===`wheel`&&e.ctrlKey)return!o.current.allowPinchZoom;var i=Ec(e),a=n.current,s=`deltaX`in e?e.deltaX:a[0]-i[0],c=`deltaY`in e?e.deltaY:a[1]-i[1],l,u=e.target,d=Math.abs(s)>Math.abs(c)?`h`:`v`;if(`touches`in e&&d===`h`&&u.type===`range`)return!1;var f=window.getSelection(),p=f&&f.anchorNode;if(p&&(p===u||p.contains(u)))return!1;var m=yc(d,u);if(!m)return!0;if(m?l=d:(l=d===`v`?`h`:`v`,m=yc(d,u)),!m)return!1;if(!r.current&&`changedTouches`in e&&(s||c)&&(r.current=l),!l)return!0;var h=r.current||l;return Tc(h,t,e,h===`h`?s:c,!0)},[]),c=z.useCallback(function(e){var n=e;if(!(!Mc.length||Mc[Mc.length-1]!==a)){var r=`deltaY`in n?Dc(n):Ec(n),i=t.current.filter(function(e){return e.name===n.type&&(e.target===n.target||n.target===e.shadowParent)&&kc(e.delta,r)})[0];if(i&&i.should){n.cancelable&&n.preventDefault();return}if(!i){var c=(o.current.shards||[]).map(Oc).filter(Boolean).filter(function(e){return e.contains(n.target)});(c.length>0?s(n,c[0]):!o.current.noIsolation)&&n.cancelable&&n.preventDefault()}}},[]),l=z.useCallback(function(e,n,r,i){var a={name:e,delta:n,target:r,should:i,shadowParent:Pc(r)};t.current.push(a),setTimeout(function(){t.current=t.current.filter(function(e){return e!==a})},1)},[]),u=z.useCallback(function(e){n.current=Ec(e),r.current=void 0},[]),d=z.useCallback(function(t){l(t.type,Dc(t),t.target,s(t,e.lockRef.current))},[]),f=z.useCallback(function(t){l(t.type,Ec(t),t.target,s(t,e.lockRef.current))},[]);z.useEffect(function(){return Mc.push(a),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener(`wheel`,c,mc),document.addEventListener(`touchmove`,c,mc),document.addEventListener(`touchstart`,u,mc),function(){Mc=Mc.filter(function(e){return e!==a}),document.removeEventListener(`wheel`,c,mc),document.removeEventListener(`touchmove`,c,mc),document.removeEventListener(`touchstart`,u,mc)}},[]);var p=e.removeScrollBar,m=e.inert;return z.createElement(z.Fragment,null,m?z.createElement(a,{styles:Ac(i)}):null,p?z.createElement(dc,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Pc(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Fc=Ws(Gs,Nc),Ic=z.forwardRef(function(e,t){return z.createElement(qs,Os({},e,{ref:t,sideCar:Fc}))});Ic.classNames=qs.classNames;var Lc=Object.defineProperty,Q=(e,t)=>Lc(e,`name`,{value:t,configurable:!0}),Rc=[`Enter`,` `],zc=[`ArrowDown`,`PageUp`,`Home`],Bc=[`ArrowUp`,`PageDown`,`End`],Vc=[...zc,...Bc],Hc={ltr:[...Rc,`ArrowRight`],rtl:[...Rc,`ArrowLeft`]},Uc={ltr:[`ArrowLeft`],rtl:[`ArrowRight`]},Wc=`Menu`,[Gc,Kc,qc]=co(Wc),[Jc,Yc]=vt(Wc,[qc,ui,ss]),Xc=ui(),Zc=ss(),[Qc,$c]=Jc(Wc),[el,tl]=Jc(Wc),nl=Q(e=>{let{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:a,modal:o=!0}=e,s=Xc(t),[c,l]=z.useState(null),u=z.useRef(!1),d=Et(a),f=_a(i);return z.useEffect(()=>{let e=Q(()=>{u.current=!0,document.addEventListener(`pointerdown`,t,{capture:!0,once:!0}),document.addEventListener(`pointermove`,t,{capture:!0,once:!0})},`handleKeyDown`),t=Q(()=>u.current=!1,`handlePointer`);return document.addEventListener(`keydown`,e,{capture:!0}),()=>{document.removeEventListener(`keydown`,e,{capture:!0}),document.removeEventListener(`pointerdown`,t,{capture:!0}),document.removeEventListener(`pointermove`,t,{capture:!0})}},[]),z.useEffect(()=>{if(!n)return;let e=Q(()=>d(!1),`handleBlur`);return window.addEventListener(`blur`,e),()=>window.removeEventListener(`blur`,e)},[n,d]),(0,K.jsx)(pi,{...s,children:(0,K.jsx)(Qc,{scope:t,open:n,onOpenChange:d,content:c,onContentChange:l,children:(0,K.jsx)(el,{scope:t,onClose:z.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:f,modal:o,children:r})})})},`Menu`),rl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,...r}=e,i=Xc(n);return(0,K.jsx)(hi,{...i,...r,ref:t})},`MenuAnchor`)),il=`MenuPortal`,[al,ol]=Jc(il,{forceMount:void 0}),sl=Q(e=>{let{__scopeMenu:t,forceMount:n,children:r,container:i}=e,a=$c(il,t);return(0,K.jsx)(al,{scope:t,forceMount:n,children:(0,K.jsx)(Oi,{present:n||a.open,children:(0,K.jsx)(wi,{asChild:!0,container:i,children:r})})})},`MenuPortal`),cl=`MenuContent`,[ll,ul]=Jc(cl),dl=z.forwardRef(Q(function(e,t){let n=ol(cl,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,a=$c(cl,e.__scopeMenu),o=tl(cl,e.__scopeMenu);return(0,K.jsx)(Gc.Provider,{scope:e.__scopeMenu,children:(0,K.jsx)(Oi,{present:r||a.open,children:(0,K.jsx)(Gc.Slot,{scope:e.__scopeMenu,children:o.modal?(0,K.jsx)(fl,{...i,ref:t}):(0,K.jsx)(pl,{...i,ref:t})})})})},`MenuContent`)),fl=z.forwardRef(Q(function(e,t){let n=$c(cl,e.__scopeMenu),r=z.useRef(null),i=C(t,r);return z.useEffect(()=>{let e=r.current;if(e)return Ds(e)},[]),(0,K.jsx)(hl,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:G(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})},`MenuRootContentModal`)),pl=z.forwardRef(Q(function(e,t){let n=$c(cl,e.__scopeMenu);return(0,K.jsx)(hl,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})},`MenuRootContentNonModal`)),ml=S(`MenuContent.ScrollLock`),hl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEntryFocus:c,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,disableOutsideScroll:m,...h}=e,g=$c(cl,n),_=tl(cl,n),v=Xc(n),y=Zc(n),b=Kc(n),[x,S]=z.useState(null),w=z.useRef(null),T=C(t,w,g.onContentChange),E=z.useRef(0),D=z.useRef(``),O=z.useRef(0),k=z.useRef(null),A=z.useRef(`right`),j=z.useRef(0),M=m?Ic:z.Fragment,N=m?{as:ml,allowPinchZoom:!0}:void 0,P=Q(e=>{let t=D.current+e,n=b().filter(e=>!e.disabled),r=document.activeElement,i=n.find(e=>e.ref.current===r)?.textValue,a=zl(n.map(e=>e.textValue),t,i),o=n.find(e=>e.textValue===a)?.ref.current;Q((function e(t){D.current=t,window.clearTimeout(E.current),t!==``&&(E.current=window.setTimeout(()=>e(``),1e3))}),`updateSearch`)(t),o&&setTimeout(()=>o.focus())},`handleTypeaheadSearch`);z.useEffect(()=>()=>window.clearTimeout(E.current),[]),To();let F=z.useCallback(e=>A.current===k.current?.side&&Vl(e,k.current?.area),[]);return(0,K.jsx)(ll,{scope:n,searchRef:D,onItemEnter:z.useCallback(e=>{F(e)&&e.preventDefault()},[F]),onItemLeave:z.useCallback(e=>{F(e)||(w.current?.focus(),S(null))},[F]),onTriggerLeave:z.useCallback(e=>{F(e)&&e.preventDefault()},[F]),pointerGraceTimerRef:O,onPointerGraceIntentChange:z.useCallback(e=>{k.current=e},[]),children:(0,K.jsx)(M,{...N,children:(0,K.jsx)(Mo,{asChild:!0,trapped:i,onMountAutoFocus:G(a,e=>{e.preventDefault(),w.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:(0,K.jsx)(Nt,{asChild:!0,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,children:(0,K.jsx)(us,{asChild:!0,...y,dir:_.dir,orientation:`vertical`,loop:r,currentTabStopId:x,onCurrentTabStopIdChange:S,onEntryFocus:G(c,e=>{_.isUsingKeyboardRef.current||e.preventDefault()}),preventScrollOnEntryFocus:!0,children:(0,K.jsx)(yi,{role:`menu`,"aria-orientation":`vertical`,"data-state":Pl(g.open),"data-radix-menu-content":``,dir:_.dir,...v,...h,ref:T,style:{outline:`none`,...h.style},onKeyDown:G(h.onKeyDown,e=>{let t=e.target.closest(`[data-radix-menu-content]`)===e.currentTarget,n=e.ctrlKey||e.altKey||e.metaKey,r=e.key.length===1;t&&(e.key===`Tab`&&e.preventDefault(),!n&&r&&P(e.key));let i=w.current;if(e.target!==i||!Vc.includes(e.key))return;e.preventDefault();let a=b().filter(e=>!e.disabled).map(e=>e.ref.current);Bc.includes(e.key)&&a.reverse(),Ll(a)}),onBlur:G(e.onBlur,e=>{e.currentTarget.contains(e.target)||(window.clearTimeout(E.current),D.current=``)}),onPointerMove:G(e.onPointerMove,Hl(e=>{let t=e.target,n=j.current!==e.clientX;if(e.currentTarget.contains(t)&&n){let t=e.clientX>j.current?`right`:`left`;A.current=t,j.current=e.clientX}}))})})})})})})},`MenuContentImpl`)),gl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,...r}=e;return(0,K.jsx)(q.div,{...r,ref:t})},`MenuLabel`)),_l=`MenuItem`,vl=`menu.itemSelect`,yl=z.forwardRef(Q(function(e,t){let{disabled:n=!1,onSelect:r,...i}=e,a=z.useRef(null),o=tl(_l,e.__scopeMenu),s=ul(_l,e.__scopeMenu),c=C(t,a),l=z.useRef(!1),u=Q(()=>{let e=a.current;if(!n&&e){let t=new CustomEvent(vl,{bubbles:!0,cancelable:!0});e.addEventListener(vl,e=>r?.(e),{once:!0}),Ct(e,t),t.defaultPrevented?l.current=!1:o.onClose()}},`handleSelect`);return(0,K.jsx)(bl,{...i,ref:c,disabled:n,onClick:G(e.onClick,u),onPointerDown:t=>{e.onPointerDown?.(t),l.current=!0},onPointerUp:G(e.onPointerUp,e=>{l.current||e.currentTarget?.click()}),onKeyDown:G(e.onKeyDown,e=>{n||e.target!==e.currentTarget||s.searchRef.current!==``&&e.key===` `||Rc.includes(e.key)&&(e.currentTarget.click(),e.preventDefault())})})},`MenuItem`)),bl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,disabled:r=!1,textValue:i,...a}=e,o=ul(_l,n),s=Zc(n),c=z.useRef(null),l=C(t,c),[u,d]=z.useState(!1),[f,p]=z.useState(``);return z.useEffect(()=>{let e=c.current;e&&p((e.textContent??``).trim())},[a.children]),(0,K.jsx)(Gc.ItemSlot,{scope:n,disabled:r,textValue:i??f,children:(0,K.jsx)(ps,{asChild:!0,...s,focusable:!r,children:(0,K.jsx)(q.div,{role:`menuitem`,"data-highlighted":u?``:void 0,"aria-disabled":r||void 0,"data-disabled":r?``:void 0,...a,ref:l,onPointerMove:G(e.onPointerMove,Hl(e=>{r?o.onItemLeave(e):(o.onItemEnter(e),e.defaultPrevented||e.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:G(e.onPointerLeave,Hl(e=>o.onItemLeave(e))),onFocus:G(e.onFocus,()=>d(!0)),onBlur:G(e.onBlur,()=>d(!1))})})})},`MenuItemImpl`)),[xl,Sl]=Jc(`MenuRadioGroup`,{value:void 0,onValueChange:Q(()=>{},`onValueChange`)}),[Cl,wl]=Jc(`MenuItemIndicator`,{checked:!1}),Tl=z.forwardRef(Q(function(e,t){let{__scopeMenu:n,...r}=e;return(0,K.jsx)(q.div,{role:`separator`,"aria-orientation":`horizontal`,...r,ref:t})},`MenuSeparator`)),El=`MenuSub`,[Dl,Ol]=Jc(El),kl=Q(e=>{let{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,a=$c(El,t),o=Xc(t),[s,c]=z.useState(null),[l,u]=z.useState(null),d=Et(i);return z.useEffect(()=>(a.open===!1&&d(!1),()=>d(!1)),[a.open,d]),(0,K.jsx)(pi,{...o,children:(0,K.jsx)(Qc,{scope:t,open:r,onOpenChange:d,content:l,onContentChange:u,children:(0,K.jsx)(Dl,{scope:t,contentId:Y(),triggerId:Y(),trigger:s,onTriggerChange:c,children:n})})})},`MenuSub`),Al=`MenuSubTrigger`,jl=z.forwardRef(Q(function(e,t){let n=$c(Al,e.__scopeMenu),r=tl(Al,e.__scopeMenu),i=Ol(Al,e.__scopeMenu),a=ul(Al,e.__scopeMenu),o=z.useRef(null),{pointerGraceTimerRef:s,onPointerGraceIntentChange:c}=a,l={__scopeMenu:e.__scopeMenu},u=z.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);z.useEffect(()=>u,[u]),z.useEffect(()=>{let e=s.current;return()=>{window.clearTimeout(e),c(null)}},[s,c]);let d=C(t,i.onTriggerChange);return(0,K.jsx)(rl,{asChild:!0,...l,children:(0,K.jsx)(bl,{id:i.triggerId,"aria-haspopup":`menu`,"aria-expanded":n.open,"aria-controls":n.open?i.contentId:void 0,"data-state":Pl(n.open),...e,ref:d,onClick:t=>{e.onClick?.(t),!(e.disabled||t.defaultPrevented)&&(t.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:G(e.onPointerMove,Hl(t=>{a.onItemEnter(t),!t.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(a.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:G(e.onPointerLeave,Hl(e=>{u();let t=n.content?.getBoundingClientRect();if(t){let r=n.content?.dataset.side,i=r===`right`,o=i?-5:5,c=t[i?`left`:`right`],l=t[i?`right`:`left`];a.onPointerGraceIntentChange({area:[{x:e.clientX+o,y:e.clientY},{x:c,y:t.top},{x:l,y:t.top},{x:l,y:t.bottom},{x:c,y:t.bottom}],side:r}),window.clearTimeout(s.current),s.current=window.setTimeout(()=>a.onPointerGraceIntentChange(null),300)}else{if(a.onTriggerLeave(e),e.defaultPrevented)return;a.onPointerGraceIntentChange(null)}})),onKeyDown:G(e.onKeyDown,t=>{e.disabled||t.target!==t.currentTarget||a.searchRef.current!==``&&t.key===` `||Hc[r.dir].includes(t.key)&&(n.onOpenChange(!0),n.content?.focus(),t.preventDefault())})})})},`MenuSubTrigger`)),Ml=`MenuSubContent`,Nl=z.forwardRef(Q(function(e,t){let n=ol(cl,e.__scopeMenu),{forceMount:r=n.forceMount,align:i=`start`,...a}=e,o=$c(cl,e.__scopeMenu),s=tl(cl,e.__scopeMenu),c=Ol(Ml,e.__scopeMenu),l=z.useRef(null),u=C(t,l);return(0,K.jsx)(Gc.Provider,{scope:e.__scopeMenu,children:(0,K.jsx)(Oi,{present:r||o.open,children:(0,K.jsx)(Gc.Slot,{scope:e.__scopeMenu,children:(0,K.jsx)(hl,{id:c.contentId,"aria-labelledby":c.triggerId,...a,ref:u,align:i,side:s.dir===`rtl`?`left`:`right`,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:e=>{s.isUsingKeyboardRef.current&&l.current?.focus(),e.preventDefault()},onCloseAutoFocus:e=>e.preventDefault(),onFocusOutside:G(e.onFocusOutside,e=>{e.target!==c.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:G(e.onEscapeKeyDown,e=>{s.onClose(),e.preventDefault()}),onKeyDown:G(e.onKeyDown,e=>{let t=e.currentTarget.contains(e.target),n=Uc[s.dir].includes(e.key);t&&n&&(o.onOpenChange(!1),c.trigger?.focus(),e.preventDefault())})})})})})},`MenuSubContent`));function Pl(e){return e?`open`:`closed`}Q(Pl,`getOpenState`);function Fl(e){return e===`indeterminate`}Q(Fl,`isIndeterminate`);function Il(e){return Fl(e)?`indeterminate`:e?`checked`:`unchecked`}Q(Il,`getCheckedState`);function Ll(e){let t=document.activeElement;for(let n of e)if(n===t||(n.focus(),document.activeElement!==t))return}Q(Ll,`focusFirst`);function Rl(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Q(Rl,`wrapArray`);function zl(e,t,n){let r=t.length>1&&Array.from(t).every(e=>e===t[0])?t[0]:t,i=n?e.indexOf(n):-1,a=Rl(e,Math.max(i,0));r.length===1&&(a=a.filter(e=>e!==n));let o=a.find(e=>e.toLowerCase().startsWith(r.toLowerCase()));return o===n?void 0:o}Q(zl,`getNextMatch`);function Bl(e,t){let{x:n,y:r}=e,i=!1;for(let e=0,a=t.length-1;er!=d>r&&n<(u-c)*(r-l)/(d-l)+c&&(i=!i)}return i}Q(Bl,`isPointInPolygon`);function Vl(e,t){return t?Bl({x:e.clientX,y:e.clientY},t):!1}Q(Vl,`isPointerInGraceArea`);function Hl(e){return t=>t.pointerType===`mouse`?e(t):void 0}Q(Hl,`whenMouse`);var Ul=Object.defineProperty,Wl=(e,t)=>Ul(e,`name`,{value:t,configurable:!0}),Gl=`DropdownMenu`,[Kl,ql]=vt(Gl,[Yc]),Jl=Yc(),[Yl,Xl]=Kl(Gl),Zl=Wl(e=>{let{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:a,onOpenChange:o,modal:s=!0}=e,c=Jl(t),l=z.useRef(null),[u,d]=Hi({prop:i,defaultProp:a??!1,onChange:o,caller:Gl});return(0,K.jsx)(Yl,{scope:t,triggerId:Y(),triggerRef:l,contentId:Y(),open:u,onOpenChange:d,onOpenToggle:z.useCallback(()=>d(e=>!e),[d]),modal:s,children:(0,K.jsx)(nl,{...c,open:u,onOpenChange:d,dir:r,modal:s,children:n})})},`DropdownMenu`),Ql=`DropdownMenuTrigger`,$l=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,a=Xl(Ql,n),o=Jl(n),s=C(t,a.triggerRef);return(0,K.jsx)(rl,{asChild:!0,...o,children:(0,K.jsx)(q.button,{type:`button`,id:a.triggerId,"aria-haspopup":`menu`,"aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":a.open?`open`:`closed`,"data-disabled":r?``:void 0,disabled:r,...i,ref:s,onPointerDown:G(e.onPointerDown,e=>{!r&&e.button===0&&e.ctrlKey===!1&&(a.onOpenToggle(),a.open||e.preventDefault())}),onKeyDown:G(e.onKeyDown,e=>{r||([`Enter`,` `].includes(e.key)&&a.onOpenToggle(),e.key===`ArrowDown`&&a.onOpenChange(!0),[`Enter`,` `,`ArrowDown`].includes(e.key)&&e.preventDefault())})})})},`DropdownMenuTrigger`)),eu=Wl(e=>{let{__scopeDropdownMenu:t,...n}=e,r=Jl(t);return(0,K.jsx)(sl,{...r,...n})},`DropdownMenuPortal`),tu=`DropdownMenuContent`,nu=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Xl(tu,n),a=Jl(n),o=z.useRef(!1);return(0,K.jsx)(dl,{id:i.contentId,"aria-labelledby":i.triggerId,...a,...r,ref:t,onCloseAutoFocus:G(e.onCloseAutoFocus,e=>{o.current||i.triggerRef.current?.focus(),o.current=!1,e.preventDefault()}),onInteractOutside:G(e.onInteractOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0,r=t.button===2||n;(!i.modal||r)&&(o.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-dropdown-menu-content-available-width":`var(--radix-popper-available-width)`,"--radix-dropdown-menu-content-available-height":`var(--radix-popper-available-height)`,"--radix-dropdown-menu-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-dropdown-menu-trigger-height":`var(--radix-popper-anchor-height)`}})},`DropdownMenuContent`)),ru=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(gl,{...i,...r,ref:t})},`DropdownMenuLabel`)),iu=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(yl,{...i,...r,ref:t})},`DropdownMenuItem`)),au=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(Tl,{...i,...r,ref:t})},`DropdownMenuSeparator`)),ou=Wl(e=>{let{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:i,defaultOpen:a}=e,o=Jl(t),[s,c]=Hi({prop:r,defaultProp:a??!1,onChange:i,caller:`DropdownMenuSub`});return(0,K.jsx)(kl,{...o,open:s,onOpenChange:c,children:n})},`DropdownMenuSub`),su=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(jl,{...i,...r,ref:t})},`DropdownMenuSubTrigger`)),cu=z.forwardRef(Wl(function(e,t){let{__scopeDropdownMenu:n,...r}=e,i=Jl(n);return(0,K.jsx)(Nl,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-dropdown-menu-content-available-width":`var(--radix-popper-available-width)`,"--radix-dropdown-menu-content-available-height":`var(--radix-popper-available-height)`,"--radix-dropdown-menu-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-dropdown-menu-trigger-height":`var(--radix-popper-anchor-height)`}})},`DropdownMenuSubContent`)),lu=Zl,uu=$l,du=ou;function fu({className:e,inset:t,children:n,...r}){return(0,K.jsxs)(su,{className:s(`flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-muted data-[state=open]:bg-muted`,t&&`pl-8`,e),...r,children:[n,(0,K.jsx)(ae,{className:`ml-auto size-4 opacity-60`})]})}function pu({className:e,...t}){return(0,K.jsx)(cu,{className:s(`z-50 min-w-40 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg`,e),...t})}function mu({className:e,sideOffset:t=4,...n}){return(0,K.jsx)(eu,{children:(0,K.jsx)(nu,{sideOffset:t,className:s(`z-50 min-w-44 overflow-hidden rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95`,e),...n})})}function hu({className:e,inset:t,...n}){return(0,K.jsx)(iu,{className:s(`relative flex cursor-default select-none items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none transition-colors focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50`,t&&`pl-8`,e),...n})}function gu({className:e,inset:t,...n}){return(0,K.jsx)(ru,{className:s(`px-2 py-1.5 text-xs font-medium text-muted-foreground`,t&&`pl-8`,e),...n})}function _u({className:e,...t}){return(0,K.jsx)(au,{className:s(`-mx-1 my-1 h-px bg-border`,e),...t})}var vu=Object.defineProperty,yu=(e,t)=>vu(e,`name`,{value:t,configurable:!0}),bu=`Dialog`,[xu,Su]=vt(bu),[Cu,wu]=xu(bu),Tu=yu(e=>{let{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!0}=e,s=z.useRef(null),c=z.useRef(null),[l,u]=Hi({prop:r,defaultProp:i??!1,onChange:a,caller:bu}),[d,f]=z.useState(0),[p,m]=z.useState(0);return(0,K.jsx)(Cu,{scope:t,triggerRef:s,contentRef:c,contentId:Y(),titleId:Y(),descriptionId:Y(),titlePresent:d>0,descriptionPresent:p>0,setTitleCount:f,setDescriptionCount:m,open:l,onOpenChange:u,onOpenToggle:z.useCallback(()=>u(e=>!e),[u]),modal:o,children:n})},`Dialog`),Eu=`DialogPortal`,[Du,Ou]=xu(Eu,{forceMount:void 0}),ku=yu(e=>{let{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=wu(Eu,t);return(0,K.jsx)(Du,{scope:t,forceMount:n,children:z.Children.map(r,e=>(0,K.jsx)(Oi,{present:n||a.open,children:(0,K.jsx)(wi,{asChild:!0,container:i,children:e})}))})},`DialogPortal`),Au=`DialogOverlay`,ju=z.forwardRef(yu(function(e,t){let n=Ou(Au,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=wu(Au,e.__scopeDialog);return a.modal?(0,K.jsx)(Oi,{present:r||a.open,children:(0,K.jsx)(Nu,{...i,ref:t})}):null},`DialogOverlay`)),Mu=S(`DialogOverlay.RemoveScroll`),Nu=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,...r}=e,i=wu(Au,n),a=C(t,Pt());return(0,K.jsx)(Ic,{as:Mu,allowPinchZoom:!0,shards:[i.contentRef],children:(0,K.jsx)(q.div,{"data-state":Wu(i.open),...r,ref:a,style:{pointerEvents:`auto`,...r.style}})})},`DialogOverlayImpl`)),Pu=`DialogContent`,Fu=z.forwardRef(yu(function(e,t){let n=Ou(Pu,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=wu(Pu,e.__scopeDialog);return(0,K.jsx)(Oi,{present:r||a.open,children:a.modal?(0,K.jsx)(Iu,{...i,ref:t}):(0,K.jsx)(Lu,{...i,ref:t})})},`DialogContent`)),Iu=z.forwardRef(yu(function(e,t){let n=wu(Pu,e.__scopeDialog),r=z.useRef(null),i=C(t,n.contentRef,r);return z.useEffect(()=>{let e=r.current;if(e)return Ds(e)},[]),(0,K.jsx)(Ru,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:G(e.onCloseAutoFocus,e=>{e.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:G(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0;(t.button===2||n)&&e.preventDefault()}),onFocusOutside:G(e.onFocusOutside,e=>e.preventDefault())})},`DialogContentModal`)),Lu=z.forwardRef(yu(function(e,t){let n=wu(Pu,e.__scopeDialog),r=z.useRef(!1),i=z.useRef(!1);return(0,K.jsx)(Ru,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})},`DialogContentNonModal`)),Ru=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,"aria-describedby":o,...s}=e,c=wu(Pu,n);return To(),(0,K.jsx)(K.Fragment,{children:(0,K.jsx)(Mo,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,K.jsx)(Nt,{role:`dialog`,id:c.contentId,"aria-labelledby":c.titlePresent?c.titleId:void 0,"aria-describedby":c.descriptionPresent?Uu(o,c.descriptionId):o,"data-state":Wu(c.open),...s,ref:t,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})},`DialogContentImpl`)),zu=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,...r}=e,i=wu(`DialogTitle`,n),{setTitleCount:a}=i;return Bt(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,K.jsx)(q.h2,{id:i.titleId,...r,ref:t})},`DialogTitle`)),Bu=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,...r}=e,i=wu(`DialogDescription`,n),{setDescriptionCount:a}=i;return Bt(()=>(a(e=>e+1),()=>a(e=>e-1)),[a]),(0,K.jsx)(q.p,{id:i.descriptionId,...r,ref:t})},`DialogDescription`)),Vu=`DialogClose`,Hu=z.forwardRef(yu(function(e,t){let{__scopeDialog:n,...r}=e,i=wu(Vu,n);return(0,K.jsx)(q.button,{type:`button`,...r,ref:t,onClick:G(e.onClick,()=>i.onOpenChange(!1))})},`DialogClose`));function Uu(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}yu(Uu,`concatAriaDescribedby`);function Wu(e){return e?`open`:`closed`}yu(Wu,`getState`);var Gu=Tu,Ku=ku;function qu({className:e,...t}){return(0,K.jsx)(ju,{className:s(`fixed inset-0 z-50 bg-black/40 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0`,e),...t})}function Ju({className:e,children:t,...n}){return(0,K.jsxs)(Ku,{children:[(0,K.jsx)(qu,{}),(0,K.jsxs)(Fu,{className:s(`fixed left-1/2 top-1/2 z-50 grid w-[calc(100%-2rem)] max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl border border-border bg-background p-6 shadow-xl duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95`,e),...n,children:[t,(0,K.jsxs)(Hu,{className:`absolute right-3 top-3 rounded-md p-1.5 text-muted-foreground opacity-70 transition-opacity hover:bg-muted hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring/40`,children:[(0,K.jsx)(ot,{className:`size-4`}),(0,K.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function Yu({className:e,...t}){return(0,K.jsx)(`div`,{className:s(`flex flex-col gap-1.5 text-left`,e),...t})}function Xu({className:e,...t}){return(0,K.jsx)(zu,{className:s(`text-lg font-semibold leading-none tracking-tight`,e),...t})}function Zu({className:e,...t}){return(0,K.jsx)(Bu,{className:s(`text-sm text-muted-foreground`,e),...t})}function Qu(){let e=T();if(!e)return null;let t=e.displayName??e.primaryEmail??`Account`;return(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[e.profileImageUrl?(0,K.jsx)(`img`,{src:e.profileImageUrl,alt:``,className:`h-8 w-8 rounded-full object-cover`}):(0,K.jsx)(`span`,{className:`grid h-8 w-8 place-items-center rounded-full bg-black/10 text-sm font-medium dark:bg-white/20`,children:t.charAt(0).toUpperCase()}),(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:t}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>void x(),className:`cursor-pointer text-sm underline-offset-4 opacity-70 hover:underline`,children:`Sign out`})]})}function $u(e){return e!==`__proto__`&&e!==`constructor`&&e!==`prototype`}function ed(e,t){let n=Object.create(null);if(e)for(let t of Object.keys(e))$u(t)&&(n[t]=e[t]);if(t&&typeof t==`object`)for(let e of Object.keys(t))$u(e)&&(n[e]=t[e]);return n}function td(e){if(!e)return Object.create(null);let t=Object.create(null);for(let n of Object.keys(e))$u(n)&&(t[n]=e[n]);return t}var nd=()=>{throw Error(`createServerOnlyFn() functions can only be called on the server!`)},$=(e,t)=>{let n=t||e||{};n.method===void 0&&(n.method=`GET`);let r=e=>$(void 0,{...n,validator:e,inputValidator:e});return Object.assign(e=>$(void 0,{...n,...e}),{options:n,middleware:e=>{let t=[...n.middleware||[]];e.map(e=>{g in e?e.options.middleware&&t.push(...e.options.middleware):t.push(e)});let r=$(void 0,{...n,middleware:t});return r[g]=!0,r},validator:r,inputValidator:r,handler:(...e)=>{let[t,r]=e,i={...n,extractedFn:t,serverFn:r},a=[...i.middleware||[],od(i)];return t.method=n.method,Object.assign(async e=>{let n=await rd(a,`client`,{...t,...i,data:e?.data,headers:e?.headers,signal:e?.signal,fetch:e?.fetch,context:td()}),r=u(n.error);if(r)throw r;if(n.error)throw n.error;return n.result},{...t,method:n.method,__executeServer:async e=>{let n=nd(),r=n.contextAfterGlobalMiddlewares;return await rd(a,`server`,{...t,...e,serverFnMeta:t.serverFnMeta,context:ed(e.context,r),request:n.request}).then(e=>({result:e.result,error:e.error,context:e.sendContext}))}})}})};async function rd(e,t,n){let r=id([...d()?.functionMiddleware||[],...e]);if(t===`server`){let e=nd({throwIfNotFound:!1});e?.executedRequestMiddlewares&&(r=r.filter(t=>!e.executedRequestMiddlewares.has(t)))}let i=async e=>{let n=r.shift();if(!n)return e;try{let r=`validator`in n.options?n.options.validator:void 0;!r&&`inputValidator`in n.options&&(r=n.options.inputValidator),r&&t===`server`&&(e.data=await ad(r,e.data));let a;if(t===`client`?`client`in n.options&&(a=n.options.client):`server`in n.options&&(a=n.options.server),a){let t=async(t={})=>{let n=await i({...e,...t,context:ed(e.context,t.context),sendContext:ed(e.sendContext,t.sendContext),headers:M(e.headers,t.headers),_callSiteFetch:e._callSiteFetch,fetch:e._callSiteFetch??t.fetch??e.fetch,result:t.result===void 0?t instanceof Response?t:e.result:t.result,error:t.error??e.error});if(n.error)throw n.error;return n},n=await a({...e,next:t});if(b(n))return{...e,error:n};if(n instanceof Response)return{...e,result:n};if(!n)throw Error(`User middleware returned undefined. You must call next() or return a result in your middlewares.`);return n}return i(e)}catch(t){return{...e,error:t}}};return i({...n,headers:n.headers||{},sendContext:n.sendContext||{},context:n.context||td(),_callSiteFetch:n.fetch})}function id(e,t=100){let n=new Set,r=[],i=(e,a)=>{if(a>t)throw Error(`Middleware nesting depth exceeded maximum of ${t}. Check for circular references.`);e.forEach(e=>{e.options.middleware&&i(e.options.middleware,a+1),n.has(e)||(n.add(e),r.push(e))})};return i(e,0),r}async function ad(e,t){if(e==null)return{};if(`~standard`in e){let n=await e[`~standard`].validate(t);if(n.issues)throw Error(JSON.stringify(n.issues,void 0,2));return n.value}if(`parse`in e)return e.parse(t);if(typeof e==`function`)return e(t);throw Error(`Invalid validator type!`)}function od(e){return{"~types":void 0,options:{inputValidator:e.validator??e.inputValidator,client:async({next:t,sendContext:n,fetch:r,...i})=>{let a={...i,context:n,fetch:r};return t(await e.extractedFn?.(a))},server:async({next:t,...n})=>{let r=await e.serverFn?.(n);return t({...n,result:r})}}}}var sd=(e,t)=>{let n={type:`request`,...t||e},r=e=>sd({},Object.assign(n,{validator:e,inputValidator:e}));return{options:n,middleware:e=>sd({},Object.assign(n,{middleware:e})),validator:r,inputValidator:r,client:e=>sd({},Object.assign(n,{client:e})),server:e=>sd({},Object.assign(n,{server:e}))}},cd=$({method:`POST`}).handler(p(`76d08ea8f0b0103fcaf7055c8b138a9579e4124d0d2f62a0686a1011273cd47a`)),ld=$({method:`POST`}).handler(p(`5e6a13ce7e871cac8b1efc1cf5ccb213d79a60710661cd7012f69f2c7ccb6982`)),ud=$({method:`POST`}).handler(p(`1e62b13d94b613cf423e7774bb51046a7dfc3005d0164d46cbd5f39fd41e65ae`)),dd=$({method:`GET`}).handler(p(`5252add61246cf72a4fa382b4734734c4e8ea74302302ba378f1ecb54d53868d`)),fd=$({method:`GET`}).handler(p(`9bf431d4df4d57d04f011720753080a98c88face5f4f24058da2b17f8da151b8`));$({method:`POST`}).handler(p(`12c220cad66e7d4a3abab6da0b2bab6053a48aee4b6a0cde9d321705b501bd69`));var pd=[`summarize-page`,`edit-block`,`action-items`,`table-from-notes`,`mermaid-diagram`,`custom-page-task`],md={xai:[`grok-4.5`,`grok-4`,`grok-3`,`grok-3-mini`,`grok-2`],anthropic:[`claude-sonnet-4-6`,`claude-opus-4-6`,`claude-haiku-4-5-20251001`,`claude-3-5-sonnet-latest`],openai:[`gpt-4.1`,`gpt-4.1-mini`,`gpt-4o`,`o4-mini`,`gpt-4o-mini`],ollama:[`llama3.2`,`llama3.1`,`mistral`,`qwen2.5`,`gemma3`,`deepseek-r1`],openai_compatible:[`gpt-4o`,`llama3.1`,`custom-model`]},hd={deepagents:{label:`LangChain Deep Agents`,description:`In-process agent with skills + MCP tools.`,needsApiKey:!0,isCli:!1},direct:{label:`Direct model API`,description:`Single-shot chat via provider API (streamable).`,needsApiKey:!0,isCli:!1},"claude-cli":{label:`Claude Code CLI`,description:"Shell out to `claude` with stream-json when available.",needsApiKey:!1,isCli:!0},"codex-cli":{label:`Codex CLI`,description:"Shell out to `codex exec` (streams stdout).",needsApiKey:!1,isCli:!0},"grok-cli":{label:`Grok CLI`,description:"Shell out to `grok chat --stream` / Grok Build.",needsApiKey:!1,isCli:!0},local:{label:`Local demo`,description:`No remote model — offline placeholders.`,needsApiKey:!1,isCli:!1}},gd={xai:{label:`xAI · Grok`,description:`Grok models via the xAI API (OpenAI-compatible).`,keyLabel:`xAI API key`,keyPlaceholder:`xai-…`,needsKey:!0},anthropic:{label:`Anthropic · Claude`,description:`Claude models (Sonnet, Opus, Haiku).`,keyLabel:`Anthropic API key`,keyPlaceholder:`sk-ant-…`,needsKey:!0},openai:{label:`OpenAI`,description:`GPT and o-series models from OpenAI.`,keyLabel:`OpenAI API key`,keyPlaceholder:`sk-…`,needsKey:!0},ollama:{label:`Ollama (local)`,description:`Run open models on your machine or LAN.`,keyLabel:`API key (optional)`,keyPlaceholder:`Usually blank`,needsKey:!1,baseUrlDefault:`http://127.0.0.1:11434`,baseUrlHint:`Ollama OpenAI-compatible base (no /v1 suffix needed).`},openai_compatible:{label:`OpenAI-compatible`,description:`Any OpenAI-style endpoint (Groq, Together, Azure proxy, etc.).`,keyLabel:`API key`,keyPlaceholder:`Optional / required by host`,needsKey:!1,baseUrlDefault:`https://api.example.com/v1`,baseUrlHint:`Must include /v1 if the host expects it.`}};function _d(){return{setupComplete:!1,enabled:!0,backend:`deepagents`,provider:`xai`,model:md.xai[0],apiKey:``,baseUrl:``,temperature:.35,recursionLimit:40,mcpServers:[],enabledSkills:[...pd],preferStreaming:!0}}var vd=v()(h((e,t)=>({..._d(),hydrated:!1,setHydrated:t=>e({hydrated:t}),patch:t=>e(e=>({...e,...t})),reset:()=>e({..._d(),hydrated:!0}),setProviderDefaults:t=>e(e=>{let n={xai:`grok-4.5`,anthropic:`claude-sonnet-4-6`,openai:`gpt-4.1`,ollama:`llama3.2`,openai_compatible:`gpt-4o`},r=t===`ollama`?e.baseUrl||`http://127.0.0.1:11434`:t===`openai_compatible`?e.baseUrl||`https://api.example.com/v1`:``;return{provider:t,model:n[t],baseUrl:r}}),addMcpServer:t=>{let n=o(`mcp`),r={id:n,name:t?.name??`New MCP server`,enabled:t?.enabled??!0,transport:t?.transport??`http`,url:t?.url??`https://`,authToken:t?.authToken??``,headersText:t?.headersText??``,command:t?.command??`npx`,argsText:t?.argsText??`-y @modelcontextprotocol/server-everything`,envText:t?.envText??``};return e(e=>({mcpServers:[...e.mcpServers,r]})),n},updateMcpServer:(t,n)=>e(e=>({mcpServers:e.mcpServers.map(e=>e.id===t?{...e,...n}:e)})),removeMcpServer:t=>e(e=>({mcpServers:e.mcpServers.filter(e=>e.id!==t)})),getSettings:()=>{let e=t();return{setupComplete:e.setupComplete,enabled:e.enabled,backend:e.backend,provider:e.provider,model:e.model,apiKey:e.apiKey,baseUrl:e.baseUrl,temperature:e.temperature,recursionLimit:e.recursionLimit,mcpServers:e.mcpServers,enabledSkills:e.enabledSkills,preferStreaming:e.preferStreaming!==!1}}}),{name:`workspace-ai-settings-v1`,partialize:e=>({setupComplete:e.setupComplete,enabled:e.enabled,backend:e.backend,provider:e.provider,model:e.model,apiKey:e.apiKey,baseUrl:e.baseUrl,temperature:e.temperature,recursionLimit:e.recursionLimit,mcpServers:e.mcpServers,enabledSkills:e.enabledSkills,preferStreaming:e.preferStreaming!==!1}),onRehydrateStorage:()=>e=>{e?.setHydrated(!0)}}));function yd(){return vd.getState().getSettings()}var bd=[{id:`welcome`,title:`Welcome`},{id:`provider`,title:`Provider`},{id:`credentials`,title:`Credentials`},{id:`mcp`,title:`MCP tools`},{id:`skills`,title:`Skills`},{id:`review`,title:`Test & finish`}];function xd({open:e,onOpenChange:t,initialStep:n=`welcome`}){let r=vd(),[i,a]=(0,z.useState)(0),[o,c]=(0,z.useState)(!1),[l,u]=(0,z.useState)(null),[d,f]=(0,z.useState)(null),[p,m]=(0,z.useState)([]);(0,z.useEffect)(()=>{if(!e)return;let t=bd.findIndex(e=>e.id===n);a(t>=0?t:0),u(null),fd().then(e=>m(e.map(e=>({id:e.id,label:e.label,available:e.available})))).catch(()=>m([]))},[e,n]);let h=bd[i],g=r.backend===`claude-cli`||r.backend===`codex-cli`||r.backend===`grok-cli`,_=()=>r.getSettings(),v=(0,z.useMemo)(()=>h.id===`provider`?!!r.backend:h.id===`credentials`?g?!0:r.provider===`openai_compatible`&&!r.baseUrl.trim()?!1:!!r.model.trim():!0,[h.id,r.backend,r.provider,r.baseUrl,r.model,g]),y=e=>{u(null),a(t=>Math.min(bd.length-1,Math.max(0,t+e)))},b=()=>{r.patch({setupComplete:!0,enabled:!0}),t(!1)},x=async()=>{c(!0),u(null);try{let e=await ld({data:{clientSettings:_()}});u({ok:e.ok,message:e.message})}catch(e){u({ok:!1,message:e instanceof Error?e.message:`Test failed`})}finally{c(!1)}},S=async e=>{f(e.id);try{let t=await ud({data:{server:e}});r.updateMcpServer(e.id,{lastTestOk:t.ok,lastTestMessage:t.message,lastToolCount:t.toolNames?.length??0})}catch(t){r.updateMcpServer(e.id,{lastTestOk:!1,lastTestMessage:t instanceof Error?t.message:`Test failed`})}finally{f(null)}};return(0,K.jsx)(Gu,{open:e,onOpenChange:t,children:(0,K.jsxs)(Ju,{className:`flex max-h-[90vh] max-w-2xl flex-col gap-0 overflow-hidden p-0`,children:[(0,K.jsxs)(`div`,{className:`border-b border-border px-6 py-4`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsxs)(Xu,{className:`flex items-center gap-2`,children:[(0,K.jsx)(Ke,{className:`size-4`}),`AI setup · Deep Agents & coding CLIs`]}),(0,K.jsx)(Zu,{children:`Connect an API model, or shell out to Claude Code / Codex / Grok CLIs with streaming.`})]}),(0,K.jsx)(`ol`,{className:`mt-4 flex flex-wrap gap-1.5`,children:bd.map((e,t)=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,"data-testid":`wizard-step-${e.id}`,"aria-current":t===i?`step`:void 0,onClick:()=>a(t),className:s(`rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors`,t===i?`bg-foreground text-background`:tr.setProviderDefaults(e),onBackend:e=>r.patch({backend:e}),onPreferStreaming:e=>r.patch({preferStreaming:e})}),h.id===`credentials`&&(g?(0,K.jsx)(wd,{backend:r.backend,cliStatus:p}):(0,K.jsx)(Td,{provider:r.provider,model:r.model,apiKey:r.apiKey,baseUrl:r.baseUrl,temperature:r.temperature,recursionLimit:r.recursionLimit,onChange:e=>r.patch(e)})),h.id===`mcp`&&(0,K.jsx)(Ed,{servers:r.mcpServers,testingId:d,onAdd:()=>r.addMcpServer(),onUpdate:(e,t)=>r.updateMcpServer(e,t),onRemove:e=>r.removeMcpServer(e),onTest:e=>void S(e)}),h.id===`skills`&&(0,K.jsx)(Dd,{enabled:r.enabledSkills,onToggle:e=>{let t=new Set(r.enabledSkills);t.has(e)?t.delete(e):t.add(e),r.patch({enabledSkills:[...t]})},onAll:()=>r.patch({enabledSkills:[...pd]})}),h.id===`review`&&(0,K.jsx)(Od,{settings:_(),testing:o,testResult:l,onTest:()=>void x()})]}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-t border-border px-6 py-4`,children:[(0,K.jsxs)(w,{type:`button`,variant:`ghost`,disabled:i===0,onClick:()=>y(-1),children:[(0,K.jsx)(H,{className:`size-4`}),` Back`]}),(0,K.jsx)(`div`,{className:`flex gap-2`,children:h.id===`review`?(0,K.jsxs)(w,{type:`button`,onClick:b,children:[(0,K.jsx)(U,{className:`size-4`}),` Save & finish`]}):(0,K.jsxs)(w,{type:`button`,disabled:!v,onClick:()=>y(1),children:[`Continue `,(0,K.jsx)(te,{className:`size-4`})]})})]})]})})}function Sd(){return(0,K.jsxs)(`div`,{className:`space-y-4 text-sm leading-relaxed text-muted-foreground`,children:[(0,K.jsxs)(`p`,{className:`text-base text-foreground`,children:[`Generate and edit content with `,(0,K.jsx)(`strong`,{children:`Deep Agents`}),`, provider APIs, or`,` `,(0,K.jsx)(`strong`,{children:`coding CLIs`}),` (Claude Code, Codex, Grok) — with streaming when available.`]}),(0,K.jsxs)(`ul`,{className:`list-inside list-disc space-y-1.5`,children:[(0,K.jsx)(`li`,{children:`API path: Grok / Claude / OpenAI / Ollama keys (browser-stored)`}),(0,K.jsxs)(`li`,{children:[`CLI path: `,(0,K.jsx)(`code`,{className:`text-xs`,children:`claude`}),`, `,(0,K.jsx)(`code`,{className:`text-xs`,children:`codex`}),`,`,` `,(0,K.jsx)(`code`,{className:`text-xs`,children:`grok`}),` already logged in on the host`]}),(0,K.jsx)(`li`,{children:`Streaming tokens over SSE for live previews in AI blocks and edit dialogs`}),(0,K.jsx)(`li`,{children:`Optional MCP servers + workspace skills for Deep Agents mode`})]})]})}function Cd({provider:e,backend:t,preferStreaming:n,cliStatus:r,onProvider:i,onBackend:a,onPreferStreaming:o}){let c=Object.keys(gd),l=Object.keys(hd),u=hd[t]?.isCli;return(0,K.jsxs)(`div`,{className:`space-y-5`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`h3`,{className:`mb-2 flex items-center gap-2 text-sm font-medium text-foreground`,children:[(0,K.jsx)(Qe,{className:`size-4`}),` Generation backend`]}),(0,K.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:l.map(e=>{let n=hd[e],i=r.find(t=>t.id===e);return(0,K.jsxs)(`button`,{type:`button`,onClick:()=>a(e),className:s(`rounded-xl border px-3 py-3 text-left transition-colors`,t===e?`border-foreground bg-muted/60`:`border-border hover:bg-muted/40`),children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[n.label,n.isCli&&(0,K.jsx)(`span`,{className:s(`rounded-full px-1.5 py-0.5 text-[10px] font-medium`,i?.available?`bg-emerald-500/15 text-emerald-700 dark:text-emerald-300`:`bg-muted text-muted-foreground`),children:i?i.available?`on PATH`:`not found`:`CLI`})]}),(0,K.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:n.description})]},e)})})]}),(0,K.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:n,onChange:e=>o(e.target.checked)}),`Prefer streaming output (SSE) when the backend supports it`]}),!u&&(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{className:`mb-2 text-sm font-medium text-foreground`,children:`Model provider (API)`}),(0,K.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:c.map(t=>{let n=gd[t];return(0,K.jsxs)(`button`,{type:`button`,onClick:()=>i(t),className:s(`rounded-xl border px-3 py-3 text-left transition-colors`,e===t?`border-foreground bg-muted/60`:`border-border hover:bg-muted/40`),children:[(0,K.jsx)(`div`,{className:`text-sm font-semibold text-foreground`,children:n.label}),(0,K.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:n.description})]},t)})})]})]})}function wd({backend:e,cliStatus:t}){let n=t.find(t=>t.id===e);return(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,K.jsx)(`div`,{className:s(`rounded-lg border px-3 py-2 text-xs`,n?.available?`border-emerald-500/40 bg-emerald-500/10 text-emerald-900 dark:text-emerald-200`:`border-border bg-muted/40 text-muted-foreground`),children:n?.available?`${hd[e]?.label??e} is available on PATH.`:`${hd[e]?.label??e} was not found on PATH in this environment. Install it on the machine running the app server.`}),(0,K.jsx)(`ul`,{className:`list-inside list-disc space-y-1.5 text-muted-foreground`,children:({"claude-cli":["Install Claude Code CLI and run `claude login`","Streaming uses `claude -p … --output-format stream-json`","Falls back to plain `-p` if stream-json is unavailable"],"codex-cli":[`Install Codex CLI and authenticate`,"Streaming uses `codex exec` stdout",`Workspace AI never stores your Codex credentials`],"grok-cli":["Install Grok CLI / Grok Build (`grok login` or XAI_API_KEY)","Streaming prefers `grok chat --stream`","Falls back to `grok -p` / chat without stream flags"]}[e]??[`Authenticate the CLI on the host machine.`]).map(e=>(0,K.jsx)(`li`,{children:e},e))}),(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No API key is stored in the workspace for CLI backends — auth is handled by the CLI itself.`})]})}function Td({provider:e,model:t,apiKey:n,baseUrl:r,temperature:i,recursionLimit:a,onChange:o}){let s=gd[e],c=md[e],l=e===`ollama`||e===`openai_compatible`;return(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsxs)(`div`,{className:`rounded-lg border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground`,children:[`Provider: `,(0,K.jsx)(`span`,{className:`font-medium text-foreground`,children:s.label})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:s.keyLabel}),(0,K.jsx)(k,{type:`password`,autoComplete:`off`,placeholder:s.keyPlaceholder,value:n,onChange:e=>o({apiKey:e.target.value})}),(0,K.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:`Stored in this browser’s local storage. Not written to the project repo.`})]}),l&&(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:`Base URL`}),(0,K.jsx)(k,{placeholder:s.baseUrlDefault,value:r,onChange:e=>o({baseUrl:e.target.value})}),s.baseUrlHint&&(0,K.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:s.baseUrlHint})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:`Model`}),(0,K.jsx)(`select`,{className:`h-9 w-full rounded-md border border-border bg-background px-2 text-sm`,value:t,onChange:e=>o({model:e.target.value}),children:c.map(e=>(0,K.jsx)(`option`,{value:e,children:e},e))}),(0,K.jsx)(k,{className:`mt-1`,placeholder:`Or type a custom model id`,value:t,onChange:e=>o({model:e.target.value})})]}),(0,K.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsxs)(`span`,{className:`text-sm font-medium`,children:[`Temperature (`,i.toFixed(2),`)`]}),(0,K.jsx)(`input`,{type:`range`,min:0,max:1.2,step:.05,value:i,onChange:e=>o({temperature:Number(e.target.value)}),className:`w-full`})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-sm font-medium`,children:`Agent recursion limit`}),(0,K.jsx)(k,{type:`number`,min:8,max:80,value:a,onChange:e=>o({recursionLimit:Number(e.target.value)||40})})]})]})]})}function Ed({servers:e,testingId:t,onAdd:n,onUpdate:r,onRemove:i,onTest:a}){return(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`MCP tools are used when backend is `,(0,K.jsx)(`strong`,{children:`Deep Agents`}),`.`]}),(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`outline`,onClick:n,children:[(0,K.jsx)(ze,{className:`size-3.5`}),` Add server`]})]}),e.length===0&&(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No MCP servers yet.`}),e.map(e=>(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(Be,{className:`size-4 text-muted-foreground`}),(0,K.jsx)(k,{value:e.name,onChange:t=>r(e.id,{name:t.target.value}),className:`h-8`}),(0,K.jsxs)(`label`,{className:`flex items-center gap-1 text-xs`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:e.enabled,onChange:t=>r(e.id,{enabled:t.target.checked})}),`On`]}),(0,K.jsx)(w,{type:`button`,size:`icon-sm`,variant:`ghost`,onClick:()=>i(e.id),children:(0,K.jsx)($e,{className:`size-3.5`})})]}),(0,K.jsxs)(`select`,{className:`h-8 w-full rounded-md border border-border bg-background px-2 text-xs`,value:e.transport,onChange:t=>r(e.id,{transport:t.target.value}),children:[(0,K.jsx)(`option`,{value:`http`,children:`HTTP`}),(0,K.jsx)(`option`,{value:`sse`,children:`SSE`}),(0,K.jsx)(`option`,{value:`stdio`,children:`stdio`})]}),e.transport===`stdio`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(k,{placeholder:`command`,value:e.command??``,onChange:t=>r(e.id,{command:t.target.value})}),(0,K.jsx)(k,{placeholder:`args (space-separated)`,value:e.argsText??``,onChange:t=>r(e.id,{argsText:t.target.value})})]}):(0,K.jsx)(k,{placeholder:`https://…`,value:e.url??``,onChange:t=>r(e.id,{url:t.target.value})}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`secondary`,disabled:t===e.id,onClick:()=>a(e),children:[t===e.id?(0,K.jsx)(ke,{className:`size-3.5 animate-spin`}):(0,K.jsx)(it,{className:`size-3.5`}),`Test`]}),e.lastTestMessage&&(0,K.jsx)(`span`,{className:s(`text-[11px]`,e.lastTestOk?`text-emerald-600`:`text-destructive`),children:e.lastTestMessage})]})]},e.id))]})}function Dd({enabled:e,onToggle:t,onAll:n}){return(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Skills for Deep Agents mode.`}),(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`ghost`,onClick:n,children:`Enable all`})]}),(0,K.jsx)(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:pd.map(n=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(n),className:s(`rounded-lg border px-3 py-2 text-left text-sm`,e.includes(n)?`border-foreground bg-muted/50`:`border-border text-muted-foreground`),children:(0,K.jsx)(`span`,{className:`font-medium`,children:n})},n))})]})}function Od({settings:e,testing:t,testResult:n,onTest:r}){return(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,K.jsxs)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-xs`,children:[(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`Backend`}),(0,K.jsx)(`dd`,{className:`font-medium`,children:hd[e.backend]?.label??e.backend}),(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`Streaming`}),(0,K.jsx)(`dd`,{children:e.preferStreaming===!1?`Off`:`Preferred`}),!hd[e.backend]?.isCli&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`Provider`}),(0,K.jsxs)(`dd`,{children:[gd[e.provider]?.label,` · `,e.model]}),(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`API key`}),(0,K.jsx)(`dd`,{children:e.apiKey?`Set`:`Not set`})]}),(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`MCP servers`}),(0,K.jsxs)(`dd`,{children:[e.mcpServers.filter(e=>e.enabled).length,` enabled`]}),(0,K.jsx)(`dt`,{className:`text-muted-foreground`,children:`Skills`}),(0,K.jsx)(`dd`,{children:e.enabledSkills.length})]}),(0,K.jsxs)(w,{type:`button`,variant:`secondary`,disabled:t,onClick:r,children:[t?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(it,{className:`size-4`}),`Test connection`]}),n&&(0,K.jsx)(`p`,{className:s(`text-xs`,n.ok?`text-emerald-600`:`text-destructive`),children:n.message})]})}function kd({onOpen:e}){let t=vd(e=>e.setupComplete),n=vd(e=>e.backend);return t?null:(0,K.jsxs)(`button`,{type:`button`,onClick:e,className:`flex w-full items-center gap-2 rounded-lg border border-dashed border-border bg-background px-3 py-2 text-left text-xs text-muted-foreground hover:bg-muted/40`,children:[(0,K.jsx)(Ke,{className:`size-3.5 shrink-0`}),(0,K.jsxs)(`span`,{children:[`Set up AI — Grok, Claude, Codex CLI, MCP…`,` `,(0,K.jsxs)(`span`,{className:`text-foreground`,children:[`(`,hd[n]?.label??n,`)`]})]})]})}var Ad={id:`mount_sample`,name:`Sample notes (linked)`,kind:`server`,serverPath:`/workspace/markdown-samples`,createdAt:Date.now()},jd=v()(h((e,t)=>({mounts:[Ad],selection:null,hydrated:!1,setHydrated:t=>e({hydrated:t}),setSelection:t=>e({selection:t}),addServerMount:(t,n)=>{let r=o(`mount`);return e(e=>({mounts:[...e.mounts,{id:r,name:t||`Linked folder`,kind:`server`,serverPath:n,createdAt:Date.now()}]})),r},addBrowserMount:t=>{let n=o(`mount`);return e(e=>({mounts:[...e.mounts,{id:n,name:t||`Local folder`,kind:`browser`,createdAt:Date.now()}]})),n},removeMount:t=>e(e=>({mounts:e.mounts.filter(e=>e.id!==t),selection:e.selection?.mountId===t?null:e.selection})),renameMount:(t,n)=>e(e=>({mounts:e.mounts.map(e=>e.id===t?{...e,name:n}:e)})),...(function(){return{}})()}),{name:`workspace-md-mounts-v1`,partialize:e=>({mounts:e.mounts}),onRehydrateStorage:()=>e=>{e?.setHydrated(!0),e&&!e.mounts.some(e=>e.id===`mount_sample`)&&(e.mounts=[Ad,...e.mounts])}})),Md=`workspace-md-handles`,Nd=`handles`;function Pd(){return new Promise((e,t)=>{let n=indexedDB.open(Md,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Nd)||e.createObjectStore(Nd)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function Fd(e,t){let n=await Pd();await new Promise((r,i)=>{let a=n.transaction(Nd,`readwrite`);a.objectStore(Nd).put(t,e),a.oncomplete=()=>r(),a.onerror=()=>i(a.error)}),n.close()}async function Id(e){let t=await Pd(),n=await new Promise((n,r)=>{let i=t.transaction(Nd,`readonly`).objectStore(Nd).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)});return t.close(),n}async function Ld(e,t=``){let n=[];for await(let[r,i]of e.entries()){if(r.startsWith(`.`))continue;let e=t?`${t}/${r}`:r;i.kind===`directory`?n.push({name:r,relPath:e,kind:`dir`}):r.toLowerCase().endsWith(`.md`)&&n.push({name:r,relPath:e,kind:`file`})}return n.sort((e,t)=>e.kind===t.kind?e.name.localeCompare(t.name):e.kind===`dir`?-1:1)}async function Rd(e,t){let n=t.split(`/`).filter(Boolean),r=e;for(let e=0;e`u`)return;let t=document.head||document.getElementsByTagName(`head`)[0],n=document.createElement(`style`);n.type=`text/css`,t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}var Gd=e=>{switch(e){case`success`:return Jd;case`info`:return Xd;case`warning`:return Yd;case`error`:return Zd;default:return null}},Kd=Array(12).fill(0),qd=({visible:e,className:t})=>z.createElement(`div`,{className:[`sonner-loading-wrapper`,t].filter(Boolean).join(` `),"data-visible":e},z.createElement(`div`,{className:`sonner-spinner`},Kd.map((e,t)=>z.createElement(`div`,{className:`sonner-loading-bar`,key:`spinner-bar-${t}`})))),Jd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z`,clipRule:`evenodd`})),Yd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z`,clipRule:`evenodd`})),Xd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z`,clipRule:`evenodd`})),Zd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 20 20`,fill:`currentColor`,height:`20`,width:`20`},z.createElement(`path`,{fillRule:`evenodd`,d:`M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z`,clipRule:`evenodd`})),Qd=z.createElement(`svg`,{xmlns:`http://www.w3.org/2000/svg`,width:`12`,height:`12`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`},z.createElement(`line`,{x1:`18`,y1:`6`,x2:`6`,y2:`18`}),z.createElement(`line`,{x1:`6`,y1:`6`,x2:`18`,y2:`18`})),$d=()=>{let[e,t]=z.useState(document.hidden);return z.useEffect(()=>{let e=()=>{t(document.hidden)};return document.addEventListener(`visibilitychange`,e),()=>window.removeEventListener(`visibilitychange`,e)},[]),e},ef=1,tf=new class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{let{message:t,...n}=e,r=typeof e?.id==`number`||e.id?.length>0?e.id:ef++,i=this.toasts.find(e=>e.id===r),a=e.dismissible===void 0||e.dismissible;return this.dismissedToasts.has(r)&&this.dismissedToasts.delete(r),i?this.toasts=this.toasts.map(n=>n.id===r?(this.publish({...n,...e,id:r,title:t}),{...n,...e,id:r,dismissible:a,title:t}):n):this.addToast({title:t,...n,dismissible:a,id:r}),r},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:`error`}),this.success=(e,t)=>this.create({...t,type:`success`,message:e}),this.info=(e,t)=>this.create({...t,type:`info`,message:e}),this.warning=(e,t)=>this.create({...t,type:`warning`,message:e}),this.loading=(e,t)=>this.create({...t,type:`loading`,message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:`loading`,message:t.loading,description:typeof t.description==`function`?void 0:t.description}));let r=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,a,o=r.then(async e=>{if(a=[`resolve`,e],z.isValidElement(e))i=!1,this.create({id:n,type:`default`,message:e});else if(rf(e)&&!e.ok){i=!1;let r=typeof t.error==`function`?await t.error(`HTTP error! status: ${e.status}`):t.error,a=typeof t.description==`function`?await t.description(`HTTP error! status: ${e.status}`):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(e instanceof Error){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}else if(t.success!==void 0){i=!1;let r=typeof t.success==`function`?await t.success(e):t.success,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`success`,description:a,...o})}}).catch(async e=>{if(a=[`reject`,e],t.error!==void 0){i=!1;let r=typeof t.error==`function`?await t.error(e):t.error,a=typeof t.description==`function`?await t.description(e):t.description,o=typeof r==`object`&&!z.isValidElement(r)?r:{message:r};this.create({id:n,type:`error`,description:a,...o})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),s=()=>new Promise((e,t)=>o.then(()=>a[0]===`reject`?t(a[1]):e(a[1])).catch(t));return typeof n!=`string`&&typeof n!=`number`?{unwrap:s}:Object.assign(n,{unwrap:s})},this.custom=(e,t)=>{let n=t?.id||ef++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},nf=(e,t)=>{let n=t?.id||ef++;return tf.addToast({title:e,...t,id:n}),n},rf=e=>e&&typeof e==`object`&&`ok`in e&&typeof e.ok==`boolean`&&`status`in e&&typeof e.status==`number`,af=Object.assign(nf,{success:tf.success,info:tf.info,warning:tf.warning,error:tf.error,custom:tf.custom,message:tf.message,promise:tf.promise,dismiss:tf.dismiss,loading:tf.loading},{getHistory:()=>tf.toasts,getToasts:()=>tf.getActiveToasts()});Wd(`[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}`);function of(e){return e.label!==void 0}var sf=3,cf=`24px`,lf=`16px`,uf=4e3,df=356,ff=14,pf=45,mf=200;function hf(...e){return e.filter(Boolean).join(` `)}function gf(e){let[t,n]=e.split(`-`),r=[];return t&&r.push(t),n&&r.push(n),r}var _f=e=>{let{invert:t,toast:n,unstyled:r,interacting:i,setHeights:a,visibleToasts:o,heights:s,index:c,toasts:l,expanded:u,removeToast:d,defaultRichColors:f,closeButton:p,style:m,cancelButtonStyle:h,actionButtonStyle:g,className:_=``,descriptionClassName:v=``,duration:y,position:b,gap:x,expandByDefault:S,classNames:C,icons:w,closeButtonAriaLabel:T=`Close toast`}=e,[E,D]=z.useState(null),[O,k]=z.useState(null),[A,j]=z.useState(!1),[M,N]=z.useState(!1),[P,F]=z.useState(!1),[I,L]=z.useState(!1),[R,B]=z.useState(!1),[V,ee]=z.useState(0),[H,te]=z.useState(0),ne=z.useRef(n.duration||y||uf),re=z.useRef(null),U=z.useRef(null),ie=c===0,ae=c+1<=o,W=n.type,oe=n.dismissible!==!1,se=n.className||``,ce=n.descriptionClassName||``,le=z.useMemo(()=>s.findIndex(e=>e.toastId===n.id)||0,[s,n.id]),ue=z.useMemo(()=>n.closeButton??p,[n.closeButton,p]),de=z.useMemo(()=>n.duration||y||uf,[n.duration,y]),fe=z.useRef(0),pe=z.useRef(0),me=z.useRef(0),he=z.useRef(null),[ge,_e]=b.split(`-`),ve=z.useMemo(()=>s.reduce((e,t,n)=>n>=le?e:e+t.height,0),[s,le]),ye=$d(),be=n.invert||t,xe=W===`loading`;pe.current=z.useMemo(()=>le*x+ve,[le,ve]),z.useEffect(()=>{ne.current=de},[de]),z.useEffect(()=>{j(!0)},[]),z.useEffect(()=>{let e=U.current;if(e){let t=e.getBoundingClientRect().height;return te(t),a(e=>[{toastId:n.id,height:t,position:n.position},...e]),()=>a(e=>e.filter(e=>e.toastId!==n.id))}},[a,n.id]),z.useLayoutEffect(()=>{if(!A)return;let e=U.current,t=e.style.height;e.style.height=`auto`;let r=e.getBoundingClientRect().height;e.style.height=t,te(r),a(e=>e.find(e=>e.toastId===n.id)?e.map(e=>e.toastId===n.id?{...e,height:r}:e):[{toastId:n.id,height:r,position:n.position},...e])},[A,n.title,n.description,a,n.id,n.jsx,n.action,n.cancel]);let Se=z.useCallback(()=>{N(!0),ee(pe.current),a(e=>e.filter(e=>e.toastId!==n.id)),setTimeout(()=>{d(n)},mf)},[n,d,a,pe]);z.useEffect(()=>{if(n.promise&&W===`loading`||n.duration===1/0||n.type===`loading`)return;let e;return u||i||ye?(()=>{if(me.current{n.onAutoClose==null||n.onAutoClose.call(n,n),Se()},ne.current)),()=>clearTimeout(e)},[u,i,n,W,ye,Se]),z.useEffect(()=>{n.delete&&(Se(),n.onDismiss==null||n.onDismiss.call(n,n))},[Se,n.delete]);function Ce(){return w?.loading?z.createElement(`div`,{className:hf(C?.loader,n?.classNames?.loader,`sonner-loader`),"data-visible":W===`loading`},w.loading):z.createElement(qd,{className:hf(C?.loader,n?.classNames?.loader),visible:W===`loading`})}let we=n.icon||w?.[W]||Gd(W);return z.createElement(`li`,{tabIndex:0,ref:U,className:hf(_,se,C?.toast,n?.classNames?.toast,C?.default,C?.[W],n?.classNames?.[W]),"data-sonner-toast":``,"data-rich-colors":n.richColors??f,"data-styled":!(n.jsx||n.unstyled||r),"data-mounted":A,"data-promise":!!n.promise,"data-swiped":R,"data-removed":M,"data-visible":ae,"data-y-position":ge,"data-x-position":_e,"data-index":c,"data-front":ie,"data-swiping":P,"data-dismissible":oe,"data-type":W,"data-invert":be,"data-swipe-out":I,"data-swipe-direction":O,"data-expanded":!!(u||S&&A),"data-testid":n.testId,style:{"--index":c,"--toasts-before":c,"--z-index":l.length-c,"--offset":`${M?V:pe.current}px`,"--initial-height":S?`auto`:`${H}px`,...m,...n.style},onDragEnd:()=>{F(!1),D(null),he.current=null},onPointerDown:e=>{e.button!==2&&(xe||!oe||(re.current=new Date,ee(pe.current),e.target.setPointerCapture(e.pointerId),e.target.tagName!==`BUTTON`&&(F(!0),he.current={x:e.clientX,y:e.clientY})))},onPointerUp:()=>{if(I||!oe)return;he.current=null;let e=Number(U.current?.style.getPropertyValue(`--swipe-amount-x`).replace(`px`,``)||0),t=Number(U.current?.style.getPropertyValue(`--swipe-amount-y`).replace(`px`,``)||0),r=new Date().getTime()-re.current?.getTime(),i=E===`x`?e:t,a=Math.abs(i)/r;if(Math.abs(i)>=pf||a>.11){ee(pe.current),n.onDismiss==null||n.onDismiss.call(n,n),k(E===`x`?e>0?`right`:`left`:t>0?`down`:`up`),Se(),L(!0);return}else{var o,s;(o=U.current)==null||o.style.setProperty(`--swipe-amount-x`,`0px`),(s=U.current)==null||s.style.setProperty(`--swipe-amount-y`,`0px`)}B(!1),F(!1),D(null)},onPointerMove:t=>{var n,r;if(!he.current||!oe||window.getSelection()?.toString().length>0)return;let i=t.clientY-he.current.y,a=t.clientX-he.current.x,o=e.swipeDirections??gf(b);!E&&(Math.abs(a)>1||Math.abs(i)>1)&&D(Math.abs(a)>Math.abs(i)?`x`:`y`);let s={x:0,y:0},c=e=>1/(1.5+Math.abs(e)/20);if(E===`y`){if(o.includes(`top`)||o.includes(`bottom`))if(o.includes(`top`)&&i<0||o.includes(`bottom`)&&i>0)s.y=i;else{let e=i*c(i);s.y=Math.abs(e)0)s.x=a;else{let e=a*c(a);s.x=Math.abs(e)0||Math.abs(s.y)>0)&&B(!0),(n=U.current)==null||n.style.setProperty(`--swipe-amount-x`,`${s.x}px`),(r=U.current)==null||r.style.setProperty(`--swipe-amount-y`,`${s.y}px`)}},ue&&!n.jsx&&W!==`loading`?z.createElement(`button`,{"aria-label":T,"data-disabled":xe,"data-close-button":!0,onClick:xe||!oe?()=>{}:()=>{Se(),n.onDismiss==null||n.onDismiss.call(n,n)},className:hf(C?.closeButton,n?.classNames?.closeButton)},w?.close??Qd):null,(W||n.icon||n.promise)&&n.icon!==null&&(w?.[W]!==null||n.icon)?z.createElement(`div`,{"data-icon":``,className:hf(C?.icon,n?.classNames?.icon)},n.promise||n.type===`loading`&&!n.icon?n.icon||Ce():null,n.type===`loading`?null:we):null,z.createElement(`div`,{"data-content":``,className:hf(C?.content,n?.classNames?.content)},z.createElement(`div`,{"data-title":``,className:hf(C?.title,n?.classNames?.title)},n.jsx?n.jsx:typeof n.title==`function`?n.title():n.title),n.description?z.createElement(`div`,{"data-description":``,className:hf(v,ce,C?.description,n?.classNames?.description)},typeof n.description==`function`?n.description():n.description):null),z.isValidElement(n.cancel)?n.cancel:n.cancel&&of(n.cancel)?z.createElement(`button`,{"data-button":!0,"data-cancel":!0,style:n.cancelButtonStyle||h,onClick:e=>{of(n.cancel)&&oe&&(n.cancel.onClick==null||n.cancel.onClick.call(n.cancel,e),Se())},className:hf(C?.cancelButton,n?.classNames?.cancelButton)},n.cancel.label):null,z.isValidElement(n.action)?n.action:n.action&&of(n.action)?z.createElement(`button`,{"data-button":!0,"data-action":!0,style:n.actionButtonStyle||g,onClick:e=>{of(n.action)&&(n.action.onClick==null||n.action.onClick.call(n.action,e),!e.defaultPrevented&&Se())},className:hf(C?.actionButton,n?.classNames?.actionButton)},n.action.label):null)};function vf(){if(typeof window>`u`||typeof document>`u`)return`ltr`;let e=document.documentElement.getAttribute(`dir`);return e===`auto`||!e?window.getComputedStyle(document.documentElement).direction:e}function yf(e,t){let n={};return[e,t].forEach((e,t)=>{let r=t===1,i=r?`--mobile-offset`:`--offset`,a=r?lf:cf;function o(e){[`top`,`right`,`bottom`,`left`].forEach(t=>{n[`${i}-${t}`]=typeof e==`number`?`${e}px`:e})}typeof e==`number`||typeof e==`string`?o(e):typeof e==`object`?[`top`,`right`,`bottom`,`left`].forEach(t=>{e[t]===void 0?n[`${i}-${t}`]=a:n[`${i}-${t}`]=typeof e[t]==`number`?`${e[t]}px`:e[t]}):o(a)}),n}var bf=z.forwardRef(function(e,t){let{id:n,invert:r,position:i=`bottom-right`,hotkey:a=[`altKey`,`KeyT`],expand:o,closeButton:s,className:c,offset:l,mobileOffset:u,theme:d=`light`,richColors:f,duration:p,style:m,visibleToasts:h=sf,toastOptions:g,dir:_=vf(),gap:v=ff,icons:y,containerAriaLabel:b=`Notifications`}=e,[x,S]=z.useState([]),C=z.useMemo(()=>n?x.filter(e=>e.toasterId===n):x.filter(e=>!e.toasterId),[x,n]),w=z.useMemo(()=>Array.from(new Set([i].concat(C.filter(e=>e.position).map(e=>e.position)))),[C,i]),[T,E]=z.useState([]),[D,O]=z.useState(!1),[k,A]=z.useState(!1),[j,M]=z.useState(d===`system`?typeof window<`u`&&window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`:d),N=z.useRef(null),P=a.join(`+`).replace(/Key/g,``).replace(/Digit/g,``),F=z.useRef(null),I=z.useRef(!1),L=z.useCallback(e=>{S(t=>(t.find(t=>t.id===e.id)?.delete||tf.dismiss(e.id),t.filter(({id:t})=>t!==e.id)))},[]);return z.useEffect(()=>tf.subscribe(e=>{if(e.dismiss){requestAnimationFrame(()=>{S(t=>t.map(t=>t.id===e.id?{...t,delete:!0}:t))});return}setTimeout(()=>{bt.flushSync(()=>{S(t=>{let n=t.findIndex(t=>t.id===e.id);return n===-1?[e,...t]:[...t.slice(0,n),{...t[n],...e},...t.slice(n+1)]})})})}),[x]),z.useEffect(()=>{if(d!==`system`){M(d);return}if(d===`system`&&(window.matchMedia&&window.matchMedia(`(prefers-color-scheme: dark)`).matches?M(`dark`):M(`light`)),typeof window>`u`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`);try{e.addEventListener(`change`,({matches:e})=>{M(e?`dark`:`light`)})}catch{e.addListener(({matches:e})=>{try{M(e?`dark`:`light`)}catch(e){console.error(e)}})}},[d]),z.useEffect(()=>{x.length<=1&&O(!1)},[x]),z.useEffect(()=>{let e=e=>{if(a.every(t=>e[t]||e.code===t)){var t;O(!0),(t=N.current)==null||t.focus()}e.code===`Escape`&&(document.activeElement===N.current||N.current?.contains(document.activeElement))&&O(!1)};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[a]),z.useEffect(()=>{if(N.current)return()=>{F.current&&(F.current.focus({preventScroll:!0}),F.current=null,I.current=!1)}},[N.current]),z.createElement(`section`,{ref:t,"aria-label":`${b} ${P}`,tabIndex:-1,"aria-live":`polite`,"aria-relevant":`additions text`,"aria-atomic":`false`,suppressHydrationWarning:!0},w.map((t,n)=>{let[i,a]=t.split(`-`);return C.length?z.createElement(`ol`,{key:t,dir:_===`auto`?vf():_,tabIndex:-1,ref:N,className:c,"data-sonner-toaster":!0,"data-sonner-theme":j,"data-y-position":i,"data-x-position":a,style:{"--front-toast-height":`${T[0]?.height||0}px`,"--width":`${df}px`,"--gap":`${v}px`,...m,...yf(l,u)},onBlur:e=>{I.current&&!e.currentTarget.contains(e.relatedTarget)&&(I.current=!1,F.current&&=(F.current.focus({preventScroll:!0}),null))},onFocus:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||I.current||(I.current=!0,F.current=e.relatedTarget)},onMouseEnter:()=>O(!0),onMouseMove:()=>O(!0),onMouseLeave:()=>{k||O(!1)},onDragEnd:()=>O(!1),onPointerDown:e=>{e.target instanceof HTMLElement&&e.target.dataset.dismissible===`false`||A(!0)},onPointerUp:()=>A(!1)},C.filter(e=>!e.position&&n===0||e.position===t).map((n,i)=>z.createElement(_f,{key:n.id,icons:y,index:i,toast:n,defaultRichColors:f,duration:g?.duration??p,className:g?.className,descriptionClassName:g?.descriptionClassName,invert:r,visibleToasts:h,closeButton:g?.closeButton??s,interacting:k,position:t,style:g?.style,unstyled:g?.unstyled,classNames:g?.classNames,cancelButtonStyle:g?.cancelButtonStyle,actionButtonStyle:g?.actionButtonStyle,closeButtonAriaLabel:g?.closeButtonAriaLabel,removeToast:L,toasts:C.filter(e=>e.position==n.position),heights:T.filter(e=>e.position==n.position),setHeights:E,expandByDefault:o,gap:v,expanded:D,swipeDirections:e.swipeDirections}))):null}))});function xf({open:e,onOpenChange:t}){let n=jd(e=>e.addServerMount),r=jd(e=>e.addBrowserMount),i=jd(e=>e.setSelection),[a,o]=(0,z.useState)(`Linked notes`),[s,c]=(0,z.useState)(`/workspace/markdown-samples`),[l,u]=(0,z.useState)(!1),d=async()=>{u(!0);try{await Bd({data:{root:s,relPath:``}});let e=n(a||`Linked folder`,s);i({mountId:e,relPath:``}),af.success(`Folder linked (view only until you open a file)`),t(!1)}catch(e){af.error(e instanceof Error?e.message:`Could not open path`)}finally{u(!1)}},f=async()=>{let e=window;if(typeof e.showDirectoryPicker!=`function`){af.error(`Your browser doesn’t support folder access. Use a server path instead.`);return}u(!0);try{let n=await e.showDirectoryPicker({mode:`readwrite`}),o=r(a||n.name||`Local folder`);await Fd(o,n),i({mountId:o,relPath:``}),af.success(`Local folder linked without importing`),t(!1)}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;af.error(e instanceof Error?e.message:`Could not link folder`)}finally{u(!1)}};return(0,K.jsx)(Gu,{open:e,onOpenChange:t,children:(0,K.jsxs)(Ju,{className:`max-w-md`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsxs)(Xu,{className:`flex items-center gap-2`,children:[(0,K.jsx)(we,{className:`size-4`}),`Link markdown folder`]}),(0,K.jsxs)(Zu,{children:[`Browse `,(0,K.jsx)(`code`,{className:`text-xs`,children:`.md`}),` files in the same UI`,` `,(0,K.jsx)(`strong`,{children:`without importing`}),` them into the workspace.`]})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5 text-sm`,children:[(0,K.jsx)(`span`,{className:`font-medium`,children:`Display name`}),(0,K.jsx)(k,{value:a,onChange:e=>o(e.target.value)})]}),(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border p-3`,children:[(0,K.jsxs)(`p`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,K.jsx)(ye,{className:`size-4`}),` This computer`]}),(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Uses the browser’s folder picker. Files stay on disk; we only read/write when you open or save.`}),(0,K.jsxs)(w,{type:`button`,disabled:l,onClick:()=>void f(),children:[l?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(_e,{className:`size-4`}),`Choose local folder`]})]}),(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border p-3`,children:[(0,K.jsx)(`p`,{className:`text-sm font-medium`,children:`Server path (sandbox / deploy host)`}),(0,K.jsx)(k,{value:s,onChange:e=>c(e.target.value),placeholder:`/workspace/markdown-samples`}),(0,K.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Allowed under `,(0,K.jsx)(`code`,{children:`/workspace`}),`. Sample:`,` `,(0,K.jsx)(`code`,{children:`/workspace/markdown-samples`})]}),(0,K.jsx)(w,{type:`button`,variant:`secondary`,disabled:l,onClick:()=>void d(),children:`Link server folder`})]})]})})}var Sf=e(n(((e,n)=>{(function(t){typeof e==`object`&&n!==void 0?n.exports=t():typeof define==`function`&&define.amd?define([],t):(typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:this).JSZip=t()})(function(){return function e(n,r,i){function a(s,c){if(!r[s]){if(!n[s]){var l=typeof t==`function`&&t;if(!c&&l)return l(s,!0);if(o)return o(s,!0);var u=Error(`Cannot find module '`+s+`'`);throw u.code=`MODULE_NOT_FOUND`,u}var d=r[s]={exports:{}};n[s][0].call(d.exports,function(e){var t=n[s][1][e];return a(t||e)},d,d.exports,e,n,r,i)}return r[s].exports}for(var o=typeof t==`function`&&t,s=0;s>2,s=(3&t)<<4|n>>4,c=1>6:64,l=2>4,n=(15&o)<<4|(s=a.indexOf(e.charAt(l++)))>>2,r=(3&s)<<6|(c=a.indexOf(e.charAt(l++))),f[u++]=t,s!==64&&(f[u++]=n),c!==64&&(f[u++]=r);return f}},{"./support":30,"./utils":32}],2:[function(e,t,n){var r=e(`./external`),i=e(`./stream/DataWorker`),a=e(`./stream/Crc32Probe`),o=e(`./stream/DataLengthProbe`);function s(e,t,n,r,i){this.compressedSize=e,this.uncompressedSize=t,this.crc32=n,this.compression=r,this.compressedContent=i}s.prototype={getContentWorker:function(){var e=new i(r.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o(`data_length`)),t=this;return e.on(`end`,function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw Error(`Bug : uncompressed data size mismatch`)}),e},getCompressedWorker:function(){return new i(r.Promise.resolve(this.compressedContent)).withStreamInfo(`compressedSize`,this.compressedSize).withStreamInfo(`uncompressedSize`,this.uncompressedSize).withStreamInfo(`crc32`,this.crc32).withStreamInfo(`compression`,this.compression)}},s.createWorkerFrom=function(e,t,n){return e.pipe(new a).pipe(new o(`uncompressedSize`)).pipe(t.compressWorker(n)).pipe(new o(`compressedSize`)).withStreamInfo(`compression`,t)},t.exports=s},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,n){var r=e(`./stream/GenericWorker`);n.STORE={magic:`\0\0`,compressWorker:function(){return new r(`STORE compression`)},uncompressWorker:function(){return new r(`STORE decompression`)}},n.DEFLATE=e(`./flate`)},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,n){var r=e(`./utils`),i=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t){return e!==void 0&&e.length?r.getTypeOf(e)===`string`?function(e,t,n,r){var a=i,o=r+n;e^=-1;for(var s=r;s>>8^a[255&(e^t.charCodeAt(s))];return-1^e}(0|t,e,e.length,0):function(e,t,n,r){var a=i,o=r+n;e^=-1;for(var s=r;s>>8^a[255&(e^t[s])];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,n){n.base64=!1,n.binary=!1,n.dir=!1,n.createFolders=!0,n.date=null,n.compression=null,n.compressionOptions=null,n.comment=null,n.unixPermissions=null,n.dosPermissions=null},{}],6:[function(e,t,n){var r=null;r=typeof Promise<`u`?Promise:e(`lie`),t.exports={Promise:r}},{lie:37}],7:[function(e,t,n){var r=typeof Uint8Array<`u`&&typeof Uint16Array<`u`&&typeof Uint32Array<`u`,i=e(`pako`),a=e(`./utils`),o=e(`./stream/GenericWorker`),s=r?`uint8array`:`array`;function c(e,t){o.call(this,`FlateWorker/`+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}n.magic=`\b\0`,a.inherits(c,o),c.prototype.processChunk=function(e){this.meta=e.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(s,e.data),!1)},c.prototype.flush=function(){o.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},c.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},c.prototype._createPako=function(){this._pako=new i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},n.compressWorker=function(e){return new c(`Deflate`,e)},n.uncompressWorker=function(){return new c(`Inflate`,{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,n){function r(e,t){var n,r=``;for(n=0;n>>=8;return r}function i(e,t,n,i,o,u){var d,f,p=e.file,m=e.compression,h=u!==s.utf8encode,g=a.transformTo(`string`,u(p.name)),_=a.transformTo(`string`,s.utf8encode(p.name)),v=p.comment,y=a.transformTo(`string`,u(v)),b=a.transformTo(`string`,s.utf8encode(v)),x=_.length!==p.name.length,S=b.length!==v.length,C=``,w=``,T=``,E=p.dir,D=p.date,O={crc32:0,compressedSize:0,uncompressedSize:0};t&&!n||(O.crc32=e.crc32,O.compressedSize=e.compressedSize,O.uncompressedSize=e.uncompressedSize);var k=0;t&&(k|=8),h||!x&&!S||(k|=2048);var A=0,j=0;E&&(A|=16),o===`UNIX`?(j=798,A|=function(e,t){var n=e;return e||(n=t?16893:33204),(65535&n)<<16}(p.unixPermissions,E)):(j=20,A|=function(e){return 63&(e||0)}(p.dosPermissions)),d=D.getUTCHours(),d<<=6,d|=D.getUTCMinutes(),d<<=5,d|=D.getUTCSeconds()/2,f=D.getUTCFullYear()-1980,f<<=4,f|=D.getUTCMonth()+1,f<<=5,f|=D.getUTCDate(),x&&(w=r(1,1)+r(c(g),4)+_,C+=`up`+r(w.length,2)+w),S&&(T=r(1,1)+r(c(y),4)+b,C+=`uc`+r(T.length,2)+T);var M=``;return M+=` +\0`,M+=r(k,2),M+=m.magic,M+=r(d,2),M+=r(f,2),M+=r(O.crc32,4),M+=r(O.compressedSize,4),M+=r(O.uncompressedSize,4),M+=r(g.length,2),M+=r(C.length,2),{fileRecord:l.LOCAL_FILE_HEADER+M+g+C,dirRecord:l.CENTRAL_FILE_HEADER+r(j,2)+M+r(y.length,2)+`\0\0\0\0`+r(A,4)+r(i,4)+g+C+y}}var a=e(`../utils`),o=e(`../stream/GenericWorker`),s=e(`../utf8`),c=e(`../crc32`),l=e(`../signature`);function u(e,t,n,r){o.call(this,`ZipFileWorker`),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=n,this.encodeFileName=r,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(u,o),u.prototype.push=function(e){var t=e.meta.percent||0,n=this.entriesCount,r=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,o.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:n?(t+100*(n-r-1))/n:100}}))},u.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var n=i(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:n.fileRecord,meta:{percent:0}})}else this.accumulate=!0},u.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,n=i(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(n.dirRecord),t)this.push({data:function(e){return l.DATA_DESCRIPTOR+r(e.crc32,4)+r(e.compressedSize,4)+r(e.uncompressedSize,4)}(e),meta:{percent:100}});else for(this.push({data:n.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},u.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t=this.index;t--)n=(n<<8)+this.byteAt(t);return this.index+=e,n},readString:function(e){return r.transformTo(`string`,this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=i},{"../utils":32}],19:[function(e,t,n){var r=e(`./Uint8ArrayReader`);function i(e){r.call(this,e)}e(`../utils`).inherits(i,r),i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,n){var r=e(`./DataReader`);function i(e){r.call(this,e)}e(`../utils`).inherits(i,r),i.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},i.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},i.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i},{"../utils":32,"./DataReader":18}],21:[function(e,t,n){var r=e(`./ArrayReader`);function i(e){r.call(this,e)}e(`../utils`).inherits(i,r),i.prototype.readData=function(e){if(this.checkOffset(e),e===0)return new Uint8Array;var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,n){var r=e(`../utils`),i=e(`../support`),a=e(`./ArrayReader`),o=e(`./StringReader`),s=e(`./NodeBufferReader`),c=e(`./Uint8ArrayReader`);t.exports=function(e){var t=r.getTypeOf(e);return r.checkSupport(t),t!==`string`||i.uint8array?t===`nodebuffer`?new s(e):i.uint8array?new c(r.transformTo(`uint8array`,e)):new a(r.transformTo(`array`,e)):new o(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,n){n.LOCAL_FILE_HEADER=`PK`,n.CENTRAL_FILE_HEADER=`PK`,n.CENTRAL_DIRECTORY_END=`PK`,n.ZIP64_CENTRAL_DIRECTORY_LOCATOR=`PK\x07`,n.ZIP64_CENTRAL_DIRECTORY_END=`PK`,n.DATA_DESCRIPTOR=`PK\x07\b`},{}],24:[function(e,t,n){var r=e(`./GenericWorker`),i=e(`../utils`);function a(e){r.call(this,`ConvertWorker to `+e),this.destType=e}i.inherits(a,r),a.prototype.processChunk=function(e){this.push({data:i.transformTo(this.destType,e.data),meta:e.meta})},t.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,n){var r=e(`./GenericWorker`),i=e(`../crc32`);function a(){r.call(this,`Crc32Probe`),this.withStreamInfo(`crc32`,0)}e(`../utils`).inherits(a,r),a.prototype.processChunk=function(e){this.streamInfo.crc32=i(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,n){var r=e(`../utils`),i=e(`./GenericWorker`);function a(e){i.call(this,`DataLengthProbe for `+e),this.propName=e,this.withStreamInfo(e,0)}r.inherits(a,i),a.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}i.prototype.processChunk.call(this,e)},t.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,n){var r=e(`../utils`),i=e(`./GenericWorker`);function a(e){i.call(this,`DataWorker`);var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type=``,this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=r.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}r.inherits(a,i),a.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,r.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(r.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case`string`:e=this.data.substring(this.index,t);break;case`uint8array`:e=this.data.subarray(this.index,t);break;case`array`:case`nodebuffer`:e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,n){function r(e){this.name=e||`default`,this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}r.prototype={push:function(e){this.emit(`data`,e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit(`end`),this.cleanUp(),this.isFinished=!0}catch(e){this.emit(`error`,e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit(`error`,e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var n=0;n `+e:e}},t.exports=r},{}],29:[function(e,t,n){var r=e(`../utils`),i=e(`./ConvertWorker`),a=e(`./GenericWorker`),o=e(`../base64`),s=e(`../support`),c=e(`../external`),l=null;if(s.nodestream)try{l=e(`../nodejs/NodejsStreamOutputAdapter`)}catch{}function u(e,t){return new c.Promise(function(n,i){var a=[],s=e._internalType,c=e._outputType,l=e._mimeType;e.on(`data`,function(e,n){a.push(e),t&&t(n)}).on(`error`,function(e){a=[],i(e)}).on(`end`,function(){try{n(function(e,t,n){switch(e){case`blob`:return r.newBlob(r.transformTo(`arraybuffer`,t),n);case`base64`:return o.encode(t);default:return r.transformTo(e,t)}}(c,function(e,t){var n,r=0,i=null,a=0;for(n=0;n`u`)n.blob=!1;else{var r=new ArrayBuffer(0);try{n.blob=new Blob([r],{type:`application/zip`}).size===0}catch{try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);i.append(r),n.blob=i.getBlob(`application/zip`).size===0}catch{n.blob=!1}}}try{n.nodestream=!!e(`readable-stream`).Readable}catch{n.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,n){for(var r=e(`./utils`),i=e(`./support`),a=e(`./nodejsUtils`),o=e(`./stream/GenericWorker`),s=Array(256),c=0;c<256;c++)s[c]=252<=c?6:248<=c?5:240<=c?4:224<=c?3:192<=c?2:1;s[254]=s[254]=1;function l(){o.call(this,`utf-8 decode`),this.leftOver=null}function u(){o.call(this,`utf-8 encode`)}n.utf8encode=function(e){return i.nodebuffer?a.newBufferFrom(e,`utf-8`):function(e){var t,n,r,a,o,s=e.length,c=0;for(a=0;a>>6:(n<65536?t[o++]=224|n>>>12:(t[o++]=240|n>>>18,t[o++]=128|n>>>12&63),t[o++]=128|n>>>6&63),t[o++]=128|63&n);return t}(e)},n.utf8decode=function(e){return i.nodebuffer?r.transformTo(`nodebuffer`,e).toString(`utf-8`):function(e){var t,n,i,a,o=e.length,c=Array(2*o);for(t=n=0;t>10&1023,c[n++]=56320|1023&i)}return c.length!==n&&(c.subarray?c=c.subarray(0,n):c.length=n),r.applyFromCharCode(c)}(e=r.transformTo(i.uint8array?`uint8array`:`array`,e))},r.inherits(l,o),l.prototype.processChunk=function(e){var t=r.transformTo(i.uint8array?`uint8array`:`array`,e.data);if(this.leftOver&&this.leftOver.length){if(i.uint8array){var a=t;(t=new Uint8Array(a.length+this.leftOver.length)).set(this.leftOver,0),t.set(a,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var o=function(e,t){var n;for((t||=e.length)>e.length&&(t=e.length),n=t-1;0<=n&&(192&e[n])==128;)n--;return n<0||n===0?t:n+s[e[n]]>t?n:t}(t),c=t;o!==t.length&&(i.uint8array?(c=t.subarray(0,o),this.leftOver=t.subarray(o,t.length)):(c=t.slice(0,o),this.leftOver=t.slice(o,t.length))),this.push({data:n.utf8decode(c),meta:e.meta})},l.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:n.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},n.Utf8DecodeWorker=l,r.inherits(u,o),u.prototype.processChunk=function(e){this.push({data:n.utf8encode(e.data),meta:e.meta})},n.Utf8EncodeWorker=u},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,n){var r=e(`./support`),i=e(`./base64`),a=e(`./nodejsUtils`),o=e(`./external`);function s(e){return e}function c(e,t){for(var n=0;n>8;this.dir=!!(16&this.externalFileAttributes),e==0&&(this.dosPermissions=63&this.externalFileAttributes),e==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!==`/`||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=r(this.extraFields[1].value);this.uncompressedSize===i.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===i.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===i.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===i.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,n,r,i=e.index+this.extraFieldsLength;for(this.extraFields||={};e.index+4>>6:(n<65536?t[o++]=224|n>>>12:(t[o++]=240|n>>>18,t[o++]=128|n>>>12&63),t[o++]=128|n>>>6&63),t[o++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new r.Buf8(e.length),n=0,i=t.length;n>10&1023,l[r++]=56320|1023&i)}return c(l,r)},n.utf8border=function(e,t){var n;for((t||=e.length)>e.length&&(t=e.length),n=t-1;0<=n&&(192&e[n])==128;)n--;return n<0||n===0?t:n+o[e[n]]>t?n:t}},{"./common":41}],43:[function(e,t,n){t.exports=function(e,t,n,r){for(var i=65535&e|0,a=e>>>16&65535|0,o=0;n!==0;){for(n-=o=2e3>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var a=r,o=i+n;e^=-1;for(var s=i;s>>8^a[255&(e^t[s])];return-1^e}},{}],46:[function(e,t,n){var r,i=e(`../utils/common`),a=e(`./trees`),o=e(`./adler32`),s=e(`./crc32`),c=e(`./messages`),l=0,u=4,d=0,f=-2,p=-1,m=4,h=2,g=8,_=9,v=286,y=30,b=19,x=2*v+1,S=15,C=3,w=258,T=w+C+1,E=42,D=113,O=1,k=2,A=3,j=4;function M(e,t){return e.msg=c[t],t}function N(e){return(e<<1)-(4e.avail_out&&(n=e.avail_out),n!==0&&(i.arraySet(e.output,t.pending_buf,t.pending_out,n,e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))}function I(e,t){a._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,F(e.strm)}function L(e,t){e.pending_buf[e.pending++]=t}function R(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function z(e,t){var n,r,i=e.max_chain_length,a=e.strstart,o=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-T?e.strstart-(e.w_size-T):0,l=e.window,u=e.w_mask,d=e.prev,f=e.strstart+w,p=l[a+o-1],m=l[a+o];e.prev_length>=e.good_match&&(i>>=2),s>e.lookahead&&(s=e.lookahead);do if(l[(n=t)+o]===m&&l[n+o-1]===p&&l[n]===l[a]&&l[++n]===l[a+1]){a+=2,n++;do;while(l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&l[++a]===l[++n]&&ac&&--i!=0);return o<=e.lookahead?o:e.lookahead}function B(e){var t,n,r,a,c,l,u,d,f,p,m=e.w_size;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=m+(m-T)){for(i.arraySet(e.window,e.window,m,m,0),e.match_start-=m,e.strstart-=m,e.block_start-=m,t=n=e.hash_size;r=e.head[--t],e.head[t]=m<=r?r-m:0,--n;);for(t=n=m;r=e.prev[--t],e.prev[t]=m<=r?r-m:0,--n;);a+=m}if(e.strm.avail_in===0)break;if(l=e.strm,u=e.window,d=e.strstart+e.lookahead,f=a,p=void 0,p=l.avail_in,f=C)for(c=e.strstart-e.insert,e.ins_h=e.window[c],e.ins_h=(e.ins_h<=C&&(e.ins_h=(e.ins_h<=C)if(r=a._tr_tally(e,e.strstart-e.match_start,e.match_length-C),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=C){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<=C&&(e.ins_h=(e.ins_h<=C&&e.match_length<=e.prev_length){for(i=e.strstart+e.lookahead-C,r=a._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-C),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=i&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(n=e.pending_buf_size-5);;){if(e.lookahead<=1){if(B(e),e.lookahead===0&&t===l)return O;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+n;if((e.strstart===0||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,I(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-T&&(I(e,!1),e.strm.avail_out===0))return O}return e.insert=0,t===u?(I(e,!0),e.strm.avail_out===0?A:j):(e.strstart>e.block_start&&(I(e,!1),e.strm.avail_out),O)}),new H(4,4,8,4,V),new H(4,5,16,8,V),new H(4,6,32,32,V),new H(4,4,16,16,ee),new H(8,16,32,32,ee),new H(8,16,128,128,ee),new H(8,32,128,256,ee),new H(32,128,258,1024,ee),new H(32,258,258,4096,ee)],n.deflateInit=function(e,t){return U(e,t,g,15,8,0)},n.deflateInit2=U,n.deflateReset=re,n.deflateResetKeep=ne,n.deflateSetHeader=function(e,t){return e&&e.state&&e.state.wrap===2?(e.state.gzhead=t,d):f},n.deflate=function(e,t){var n,i,o,c;if(!e||!e.state||5>8&255),L(i,i.gzhead.time>>16&255),L(i,i.gzhead.time>>24&255),L(i,i.level===9?2:2<=i.strategy||i.level<2?4:0),L(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(L(i,255&i.gzhead.extra.length),L(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=s(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69):(L(i,0),L(i,0),L(i,0),L(i,0),L(i,0),L(i,i.level===9?2:2<=i.strategy||i.level<2?4:0),L(i,3),i.status=D);else{var p=g+(i.w_bits-8<<4)<<8;p|=(2<=i.strategy||i.level<2?0:i.level<6?1:i.level===6?2:3)<<6,i.strstart!==0&&(p|=32),p+=31-p%31,i.status=D,R(i,p),i.strstart!==0&&(R(i,e.adler>>>16),R(i,65535&e.adler)),e.adler=1}if(i.status===69)if(i.gzhead.extra){for(o=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>o&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),F(e),o=i.pending,i.pending!==i.pending_buf_size));)L(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>o&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=73)}else i.status=73;if(i.status===73)if(i.gzhead.name){o=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>o&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),F(e),o=i.pending,i.pending===i.pending_buf_size)){c=1;break}c=i.gzindexo&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),c===0&&(i.gzindex=0,i.status=91)}else i.status=91;if(i.status===91)if(i.gzhead.comment){o=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>o&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),F(e),o=i.pending,i.pending===i.pending_buf_size)){c=1;break}c=i.gzindexo&&(e.adler=s(e.adler,i.pending_buf,i.pending-o,o)),c===0&&(i.status=103)}else i.status=103;if(i.status===103&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&F(e),i.pending+2<=i.pending_buf_size&&(L(i,255&e.adler),L(i,e.adler>>8&255),e.adler=0,i.status=D)):i.status=D),i.pending!==0){if(F(e),e.avail_out===0)return i.last_flush=-1,d}else if(e.avail_in===0&&N(t)<=N(n)&&t!==u)return M(e,-5);if(i.status===666&&e.avail_in!==0)return M(e,-5);if(e.avail_in!==0||i.lookahead!==0||t!==l&&i.status!==666){var m=i.strategy===2?function(e,t){for(var n;;){if(e.lookahead===0&&(B(e),e.lookahead===0)){if(t===l)return O;break}if(e.match_length=0,n=a._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(I(e,!1),e.strm.avail_out===0))return O}return e.insert=0,t===u?(I(e,!0),e.strm.avail_out===0?A:j):e.last_lit&&(I(e,!1),e.strm.avail_out===0)?O:k}(i,t):i.strategy===3?function(e,t){for(var n,r,i,o,s=e.window;;){if(e.lookahead<=w){if(B(e),e.lookahead<=w&&t===l)return O;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=C&&0e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=C?(n=a._tr_tally(e,1,e.match_length-C),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=a._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(I(e,!1),e.strm.avail_out===0))return O}return e.insert=0,t===u?(I(e,!0),e.strm.avail_out===0?A:j):e.last_lit&&(I(e,!1),e.strm.avail_out===0)?O:k}(i,t):r[i.level].func(i,t);if(m!==A&&m!==j||(i.status=666),m===O||m===A)return e.avail_out===0&&(i.last_flush=-1),d;if(m===k&&(t===1?a._tr_align(i):t!==5&&(a._tr_stored_block(i,0,0,!1),t===3&&(P(i.head),i.lookahead===0&&(i.strstart=0,i.block_start=0,i.insert=0))),F(e),e.avail_out===0))return i.last_flush=-1,d}return t===u?i.wrap<=0?1:(i.wrap===2?(L(i,255&e.adler),L(i,e.adler>>8&255),L(i,e.adler>>16&255),L(i,e.adler>>24&255),L(i,255&e.total_in),L(i,e.total_in>>8&255),L(i,e.total_in>>16&255),L(i,e.total_in>>24&255)):(R(i,e.adler>>>16),R(i,65535&e.adler)),F(e),0=n.w_size&&(s===0&&(P(n.head),n.strstart=0,n.block_start=0,n.insert=0),p=new i.Buf8(n.w_size),i.arraySet(p,t,m-n.w_size,n.w_size,0),t=p,m=n.w_size),c=e.avail_in,l=e.next_in,u=e.input,e.avail_in=m,e.next_in=0,e.input=t,B(n);n.lookahead>=C;){for(r=n.strstart,a=n.lookahead-(C-1);n.ins_h=(n.ins_h<>>=b=y>>>24,m-=b,(b=y>>>16&255)==0)E[a++]=65535&y;else{if(!(16&b)){if(!(64&b)){y=h[(65535&y)+(p&(1<>>=b,m-=b),m<15&&(p+=T[r++]<>>=b=y>>>24,m-=b,!(16&(b=y>>>16&255))){if(!(64&b)){y=g[(65535&y)+(p&(1<>>=b,m-=b,(b=a-o)>3,p&=(1<<(m-=x<<3))-1,e.next_in=r,e.next_out=a,e.avail_in=r>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function _(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg=``,t.wrap&&(e.adler=1&t.wrap),t.mode=f,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new r.Buf32(p),t.distcode=t.distdyn=new r.Buf32(m),t.sane=1,t.back=-1,u):d}function v(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,_(e)):d}function y(e,t){var n,r;return e&&e.state?(r=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15=o.wsize?(r.arraySet(o.window,t,n-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(i<(a=o.wsize-o.wnext)&&(a=i),r.arraySet(o.window,t,n-i,a,o.wnext),(i-=a)?(r.arraySet(o.window,t,n-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,n.check=a(n.check,B,2,0),x=b=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&b)<<8)+(b>>8))%31){e.msg=`incorrect header check`,n.mode=30;break}if((15&b)!=8){e.msg=`unknown compression method`,n.mode=30;break}if(x-=4,F=8+(15&(b>>>=4)),n.wbits===0)n.wbits=F;else if(F>n.wbits){e.msg=`invalid window size`,n.mode=30;break}n.dmax=1<>8&1),512&n.flags&&(B[0]=255&b,B[1]=b>>>8&255,n.check=a(n.check,B,2,0)),x=b=0,n.mode=3;case 3:for(;x<32;){if(v===0)break e;v--,b+=p[g++]<>>8&255,B[2]=b>>>16&255,B[3]=b>>>24&255,n.check=a(n.check,B,4,0)),x=b=0,n.mode=4;case 4:for(;x<16;){if(v===0)break e;v--,b+=p[g++]<>8),512&n.flags&&(B[0]=255&b,B[1]=b>>>8&255,n.check=a(n.check,B,2,0)),x=b=0,n.mode=5;case 5:if(1024&n.flags){for(;x<16;){if(v===0)break e;v--,b+=p[g++]<>>8&255,n.check=a(n.check,B,2,0)),x=b=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&(v<(E=n.length)&&(E=v),E&&(n.head&&(F=n.head.extra_len-n.length,n.head.extra||(n.head.extra=Array(n.head.extra_len)),r.arraySet(n.head.extra,p,g,E,F)),512&n.flags&&(n.check=a(n.check,p,E,g)),v-=E,g+=E,n.length-=E),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(v===0)break e;for(E=0;F=p[g+E++],n.head&&F&&n.length<65536&&(n.head.name+=String.fromCharCode(F)),F&&E>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;x<32;){if(v===0)break e;v--,b+=p[g++]<>>=7&x,x-=7&x,n.mode=27;break}for(;x<3;){if(v===0)break e;v--,b+=p[g++]<>>=1)){case 0:n.mode=14;break;case 1:if(w(n),n.mode=20,t!==6)break;b>>>=2,x-=2;break e;case 2:n.mode=17;break;case 3:e.msg=`invalid block type`,n.mode=30}b>>>=2,x-=2;break;case 14:for(b>>>=7&x,x-=7&x;x<32;){if(v===0)break e;v--,b+=p[g++]<>>16^65535)){e.msg=`invalid stored block lengths`,n.mode=30;break}if(n.length=65535&b,x=b=0,n.mode=15,t===6)break e;case 15:n.mode=16;case 16:if(E=n.length){if(v>>=5,x-=5,n.ndist=1+(31&b),b>>>=5,x-=5,n.ncode=4+(15&b),b>>>=4,x-=4,286>>=3,x-=3}for(;n.have<19;)n.lens[V[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,L={bits:n.lenbits},I=s(0,n.lens,0,19,n.lencode,0,n.work,L),n.lenbits=L.bits,I){e.msg=`invalid code lengths set`,n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have>>16&255,j=65535&z,!((k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>>=k,x-=k,n.lens[n.have++]=j;else{if(j===16){for(R=k+2;x>>=k,x-=k,n.have===0){e.msg=`invalid bit length repeat`,n.mode=30;break}F=n.lens[n.have-1],E=3+(3&b),b>>>=2,x-=2}else if(j===17){for(R=k+3;x>>=k)),b>>>=3,x-=3}else{for(R=k+7;x>>=k)),b>>>=7,x-=7}if(n.have+E>n.nlen+n.ndist){e.msg=`invalid bit length repeat`,n.mode=30;break}for(;E--;)n.lens[n.have++]=F}}if(n.mode===30)break;if(n.lens[256]===0){e.msg=`invalid code -- missing end-of-block`,n.mode=30;break}if(n.lenbits=9,L={bits:n.lenbits},I=s(c,n.lens,0,n.nlen,n.lencode,0,n.work,L),n.lenbits=L.bits,I){e.msg=`invalid literal/lengths set`,n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,L={bits:n.distbits},I=s(l,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,L),n.distbits=L.bits,I){e.msg=`invalid distances set`,n.mode=30;break}if(n.mode=20,t===6)break e;case 20:n.mode=21;case 21:if(6<=v&&258<=y){e.next_out=_,e.avail_out=y,e.next_in=g,e.avail_in=v,n.hold=b,n.bits=x,o(e,C),_=e.next_out,m=e.output,y=e.avail_out,g=e.next_in,p=e.input,v=e.avail_in,b=n.hold,x=n.bits,n.mode===12&&(n.back=-1);break}for(n.back=0;A=(z=n.lencode[b&(1<>>16&255,j=65535&z,!((k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>M)])>>>16&255,j=65535&z,!(M+(k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>>=M,x-=M,n.back+=M}if(b>>>=k,x-=k,n.back+=k,n.length=j,A===0){n.mode=26;break}if(32&A){n.back=-1,n.mode=12;break}if(64&A){e.msg=`invalid literal/length code`,n.mode=30;break}n.extra=15&A,n.mode=22;case 22:if(n.extra){for(R=n.extra;x>>=n.extra,x-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;A=(z=n.distcode[b&(1<>>16&255,j=65535&z,!((k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>M)])>>>16&255,j=65535&z,!(M+(k=z>>>24)<=x);){if(v===0)break e;v--,b+=p[g++]<>>=M,x-=M,n.back+=M}if(b>>>=k,x-=k,n.back+=k,64&A){e.msg=`invalid distance code`,n.mode=30;break}n.offset=j,n.extra=15&A,n.mode=24;case 24:if(n.extra){for(R=n.extra;x>>=n.extra,x-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg=`invalid distance too far back`,n.mode=30;break}n.mode=25;case 25:if(y===0)break e;if(E=C-y,n.offset>E){if((E=n.offset-E)>n.whave&&n.sane){e.msg=`invalid distance too far back`,n.mode=30;break}D=E>n.wnext?(E-=n.wnext,n.wsize-E):n.wnext-E,E>n.length&&(E=n.length),O=n.window}else O=m,D=_-n.offset,E=n.length;for(yv?(b=L[R+d[w]],N[P+d[w]]):(b=96,0),p=1<>k)+(m-=p)]=y<<24|b<<16|x|0,m!==0;);for(p=1<>=1;if(p===0?M=0:(M&=p-1,M+=p),w++,--F[C]==0){if(C===E)break;C=t[n+d[w]]}if(D>>7)]}function L(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function R(e,t,n){e.bi_valid>h-n?(e.bi_buf|=t<>h-e.bi_valid,e.bi_valid+=n-h):(e.bi_buf|=t<>>=1,n<<=1,0<--t;);return n>>>1}function V(e,t,n){var r,i,a=Array(m+1),o=0;for(r=1;r<=m;r++)a[r]=o=o+n[r-1]<<1;for(i=0;i<=t;i++){var s=e[2*i+1];s!==0&&(e[2*i]=B(a[s]++,s))}}function ee(e){var t;for(t=0;t>1;1<=n;n--)ne(e,a,n);for(i=c;n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],ne(e,a,1),r=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=r,a[2*i]=a[2*n]+a[2*r],e.depth[i]=(e.depth[n]>=e.depth[r]?e.depth[n]:e.depth[r])+1,a[2*n+1]=a[2*r+1]=i,e.heap[1]=i++,ne(e,a,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var n,r,i,a,o,s,c=t.dyn_tree,l=t.max_code,u=t.stat_desc.static_tree,d=t.stat_desc.has_stree,f=t.stat_desc.extra_bits,h=t.stat_desc.extra_base,g=t.stat_desc.max_length,_=0;for(a=0;a<=m;a++)e.bl_count[a]=0;for(c[2*e.heap[e.heap_max]+1]=0,n=e.heap_max+1;n>=7;r>>=1)if(1&n&&e.dyn_ltree[2*t]!==0)return i;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return a;for(t=32;t>>3,(s=e.static_len+3+7>>>3)<=o&&(o=s)):o=s=n+5,n+4<=o&&t!==-1?oe(e,t,n,r):e.strategy===4||s===o?(R(e,2+ +!!r,3),re(e,T,E)):(R(e,4+ +!!r,3),function(e,t,n,r){var i;for(R(e,t-257,5),R(e,n-1,5),R(e,r-4,4),i=0;i>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&n,e.last_lit++,t===0?e.dyn_ltree[2*n]++:(e.matches++,t--,e.dyn_ltree[2*(O[n]+l+1)]++,e.dyn_dtree[2*I(t)]++),e.last_lit===e.lit_bufsize-1},n._tr_align=function(e){R(e,2,3),z(e,_,T),function(e){e.bi_valid===16?(L(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":41}],53:[function(e,t,n){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=``,this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,n){(function(e){(function(e,t){if(!e.setImmediate){var n,r,i,a,o=1,s={},c=!1,l=e.document,u=Object.getPrototypeOf&&Object.getPrototypeOf(e);u=u&&u.setTimeout?u:e,n={}.toString.call(e.process)===`[object process]`?function(e){process.nextTick(function(){f(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,n=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage(``,`*`),e.onmessage=n,t}}()?(a=`setImmediate$`+Math.random()+`$`,e.addEventListener?e.addEventListener(`message`,p,!1):e.attachEvent(`onmessage`,p),function(t){e.postMessage(a+t,`*`)}):e.MessageChannel?((i=new MessageChannel).port1.onmessage=function(e){f(e.data)},function(e){i.port2.postMessage(e)}):l&&`onreadystatechange`in l.createElement(`script`)?(r=l.documentElement,function(e){var t=l.createElement(`script`);t.onreadystatechange=function(){f(e),t.onreadystatechange=null,r.removeChild(t),t=null},r.appendChild(t)}):function(e){setTimeout(f,0,e)},u.setImmediate=function(e){typeof e!=`function`&&(e=Function(``+e));for(var t=Array(arguments.length-1),r=0;r`u`?e===void 0?this:e:self)}).call(this,typeof global<`u`?global:typeof self<`u`?self:typeof window<`u`?window:{})},{}]},{},[10])(10)})}))(),1);function Cf(e){let t=[e.title||``];for(let n of e.blocks)n.type===`divider`||n.type===`ai`||n.content?.trim()&&t.push(n.content.trim());return t.join(` +`)}function wf(e){let t=[],n=0;for(let r of e){let e=r.content??``;switch(r.type){case`heading1`:t.push(`# ${e}`),n=0;break;case`heading2`:t.push(`## ${e}`),n=0;break;case`heading3`:t.push(`### ${e}`),n=0;break;case`bullet`:t.push(`${` `.repeat(r.indent??0)}- ${e}`),n=0;break;case`numbered`:n+=1,t.push(`${` `.repeat(r.indent??0)}${n}. ${e}`);break;case`todo`:t.push(`${` `.repeat(r.indent??0)}- [${r.checked?`x`:` `}] ${e}`),n=0;break;case`quote`:t.push(e.split(` +`).map(e=>`> ${e}`).join(` +`)),n=0;break;case`callout`:t.push(`> 💡 ${e}`),n=0;break;case`code`:t.push("```"),t.push(e),t.push("```"),n=0;break;case`mermaid`:t.push("```mermaid"),t.push(e),t.push("```"),n=0;break;case`divider`:t.push(`---`),n=0;break;case`toggle`:t.push(`
    ${e||`Toggle`}`),t.push(``),t.push(`
    `),n=0;break;case`ai`:break;default:t.push(e),n=0}t.push(``)}return t.join(` +`).replace(/\n{3,}/g,` + +`).trim()+` +`}function Tf(e){let t=e.title||`Untitled`,n=wf(e.blocks);return n.startsWith(`# ${t}`)?n:`# ${t}\n\n${n}`}function Ef(e,t,n){return{id:o(`b`),type:e,content:t,indent:0,...n}}function Df(e){let t=e.replace(/\r\n/g,` +`),n=[],r=t.split(` +`),i=0;for(;i`)){let e=[];for(;i`);)e.push(r[i].replace(/^>\s?/,``)),i+=1;let t=e.join(` +`);t.startsWith(`💡`)||t.startsWith(`:bulb:`)?n.push(Ef(`callout`,t.replace(/^💡\s*|^:bulb:\s*/,``))):n.push(Ef(`quote`,t));continue}if(!e.trim()){i+=1;continue}let l=[e];for(i+=1;i`)||e.startsWith("```")||/^[-*+]\s/.test(e)||/^\d+\.\s/.test(e)||/^---+\s*$/.test(e))break;l.push(e),i+=1}n.push(Ef(`paragraph`,l.join(` +`)))}return n.length===0&&n.push(Ef(`paragraph`,``)),n}function Of(e,t){let n=e.match(/^#\s+(.+)$/m);return n?.[1]?.trim()?n[1].trim().slice(0,200):t.replace(/\.md$/i,``)||`Untitled`}function kf(e){return(e||`untitled`).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`untitled`}function Af(e,t,n=20){let r=t.trim().toLowerCase();if(!r)return[];let i=r.split(/\s+/).filter(Boolean),a=[];for(let t of e){if(t.archived)continue;let e=Cf(t),n=`${t.title}\n${e}`.toLowerCase(),o=0;t.title.toLowerCase().includes(r)&&(o+=2);for(let e of i)n.includes(e)&&(o+=1);let s=t.title.toLowerCase(),c=0;for(let e=0;e120?`…`:``);if(u>=0){let e=Math.max(0,u-40),t=Math.min(l.length,u+r.length+80);d=(e>0?`…`:``)+l.slice(e,t)+(t=2?`keyword`:`similarity`})}return a.sort((e,t)=>t.score-e.score).slice(0,n)}function jf(e,t){let n=new Map;for(let t of e){if(t.archived)continue;let e=n.get(t.parentId)??[];e.push(t),n.set(t.parentId,e)}let r=[],i=t=>{let a=e.find(e=>e.id===t);if(!(!a||a.archived)){r.push(a);for(let e of n.get(t)??[])i(e.id)}};return i(t),r}function Mf(e,t){if(!e.has(t))return e.add(t),t;let n=2;for(;e.has(`${t}-${n}`);)n+=1;let r=`${t}-${n}`;return e.add(r),r}async function Nf(e,t){let n=new Sf.default,r=t.hierarchy?jf(e,t.rootId):e.filter(e=>e.id===t.rootId);if(r.length===0)throw Error(`Page not found`);let i=e.find(e=>e.id===t.rootId),a=new Set,o=new Map,s=Mf(a,kf(i.title||`page`));if(n.file(`${s}.md`,Tf(i)),o.set(i.id,s),t.hierarchy)for(let e of r){if(e.id===i.id)continue;let t=e.parentId?o.get(e.parentId):s;if(!t)continue;let r=Mf(a,`${t}/${kf(e.title||`page`)}`);n.file(`${r}.md`,Tf(e)),o.set(e.id,r)}return{blob:await n.generateAsync({type:`blob`}),filename:`${kf(i.title||`export`)}${t.hierarchy?`-tree`:``}.zip`}}function Pf(e,t,n=null){let r=Of(t,e.split(/[/\\]/).pop()||`page.md`),i=t;return i=i.replace(RegExp(`^#\\s+${Ff(r)}\\s*\\n+`),``),{tempId:o(`imp`),title:r,icon:`📝`,parentTempId:n,blocks:Df(i),relPath:e}}function Ff(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function If(e){let t=e.map(e=>({path:e.path.replace(/\\/g,`/`).replace(/^\.\//,``),content:e.content})).filter(e=>e.path.toLowerCase().endsWith(`.md`)),n=new Map,r=[],i=e=>{if(!e||e===`.`)return null;if(n.has(e))return n.get(e);let t=e.split(`/`),a=t[t.length-1],s=t.slice(0,-1).join(`/`),c=s?i(s):null,l=o(`imp`);return n.set(e,l),r.push({tempId:l,title:a,icon:`📁`,parentTempId:c,blocks:[{id:o(`b`),type:`paragraph`,content:`Folder: ${a}`,indent:0}],relPath:e+`/`}),l};t.sort((e,t)=>e.path.localeCompare(t.path));for(let e of t){let t=e.path.split(`/`),n=t.pop(),a=t.join(`/`),o=a?i(a):null;r.push(Pf(n,e.content,o)),r[r.length-1].relPath=e.path}return r}function Lf(e,t){let n=new Map,r=[],i=[];for(let t of e)n.set(t.tempId,o(`page`));for(let a of e){let e=n.get(a.tempId),o=a.parentTempId?n.get(a.parentTempId)??t:t,s=l({id:e,title:a.title,icon:a.icon,parentId:o,blocks:a.blocks});r.push(s),a.parentTempId||i.push(e)}return{pages:r,rootIds:i}}function Rf(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),URL.revokeObjectURL(n)}function zf({open:e,onOpenChange:t,initialTab:n=`export`,pageId:r}){let i=m(e=>e.pages),a=m(e=>e.activePageId),o=m(e=>e.importPages),s=m(e=>e.setActivePage),c=r??a,l=i.find(e=>e.id===c),[u,d]=(0,z.useState)(n),[f,p]=(0,z.useState)(!0),[h,g]=(0,z.useState)(!1),[_,v]=(0,z.useState)(`/workspace/markdown-mounts/export`),[y,b]=(0,z.useState)(!0),x=(0,z.useRef)(null),S=(0,z.useRef)(null),C=async()=>{if(c){g(!0);try{let{blob:e,filename:t}=await Nf(i,{rootId:c,hierarchy:f});Rf(e,t),af.success(`Markdown zip downloaded`)}catch(e){af.error(e instanceof Error?e.message:`Export failed`)}finally{g(!1)}}},T=()=>{if(!l)return;let e=Tf(l);Rf(new Blob([e],{type:`text/markdown`}),`${kf(l.title||`page`)}.md`),af.success(`Markdown file downloaded`)},E=async()=>{if(c){g(!0);try{let{blob:e}=await Nf(i,{rootId:c,hierarchy:f}),t=await Sf.default.loadAsync(e),n=[],r=Object.keys(t.files);for(let e of r){let r=t.files[e];r.dir||n.push({relPath:e,content:await r.async(`string`)})}let a=await Ud({data:{targetDir:_,files:n}});af.success(`Wrote ${a.count} files to ${a.dir}`)}catch(e){af.error(e instanceof Error?e.message:`Server export failed`)}finally{g(!1)}}},D=e=>{let{pages:n,rootIds:r}=Lf(e.length===1?[Pf(e[0].path,e[0].content)]:If(e),y?c??null:null);o(n,r[0]??n[0]?.id??null),r[0]&&s(r[0]),af.success(`Imported ${n.length} page${n.length===1?``:`s`}`),t(!1)},O=async e=>{if(e?.length){g(!0);try{let t=[];for(let n of Array.from(e))if(!(!n.name.toLowerCase().endsWith(`.md`)&&!n.name.toLowerCase().endsWith(`.zip`)))if(n.name.toLowerCase().endsWith(`.zip`)){let e=await Sf.default.loadAsync(await n.arrayBuffer());for(let n of Object.keys(e.files)){let r=e.files[n];r.dir||!n.toLowerCase().endsWith(`.md`)||t.push({path:n,content:await r.async(`string`)})}}else{let e=n.webkitRelativePath||n.name;t.push({path:e,content:await n.text()})}if(!t.length){af.error(`No markdown files found`);return}D(t)}catch(e){af.error(e instanceof Error?e.message:`Import failed`)}finally{g(!1)}}};return(0,K.jsx)(Gu,{open:e,onOpenChange:t,children:(0,K.jsxs)(Ju,{className:`max-w-lg`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsxs)(Xu,{className:`flex items-center gap-2`,children:[(0,K.jsx)(ge,{className:`size-4`}),`Markdown import / export`]}),(0,K.jsxs)(Zu,{children:[`Move pages as folders of `,(0,K.jsx)(`code`,{className:`text-xs`,children:`.md`}),` files — or export a hierarchy.`]})]}),(0,K.jsx)(`div`,{className:`flex gap-1 rounded-lg border border-border p-1`,children:[`export`,`import`].map(e=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>d(e),className:u===e?`flex-1 rounded-md bg-foreground px-3 py-1.5 text-sm font-medium text-background`:`flex-1 rounded-md px-3 py-1.5 text-sm text-muted-foreground hover:bg-muted`,children:e===`export`?`Export`:`Import`},e))}),u===`export`?(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,K.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Current page:`,` `,(0,K.jsxs)(`span`,{className:`font-medium text-foreground`,children:[l?.icon,` `,l?.title||`Untitled`]})]}),(0,K.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:f,onChange:e=>p(e.target.checked)}),`Include child pages (folder hierarchy)`]}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsxs)(w,{type:`button`,disabled:h||!l,onClick:()=>void C(),children:[h?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(le,{className:`size-4`}),`Download as .zip`]}),(0,K.jsx)(w,{type:`button`,variant:`outline`,disabled:!l||f,onClick:T,children:`Download single .md`})]}),(0,K.jsxs)(`div`,{className:`space-y-2 rounded-lg border border-border p-3`,children:[(0,K.jsx)(`p`,{className:`text-xs font-medium text-foreground`,children:`Write to server folder`}),(0,K.jsx)(k,{value:_,onChange:e=>v(e.target.value)}),(0,K.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Allowed under `,(0,K.jsx)(`code`,{children:`/workspace`}),` (e.g.`,` `,(0,K.jsx)(`code`,{children:`/workspace/markdown-mounts/export`}),`)`]}),(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`secondary`,disabled:h||!l,onClick:()=>void E(),children:[(0,K.jsx)(ge,{className:`size-3.5`}),` Write markdown dir`]})]})]}):(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[(0,K.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:y,onChange:e=>b(e.target.checked)}),`Nest under current page`]}),(0,K.jsx)(`input`,{ref:x,type:`file`,accept:`.md,.zip,text/markdown,application/zip`,multiple:!0,className:`hidden`,onChange:e=>void O(e.target.files)}),(0,K.jsx)(`input`,{ref:S,type:`file`,webkitdirectory:``,directory:``,multiple:!0,className:`hidden`,onChange:e=>void O(e.target.files)}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsxs)(w,{type:`button`,disabled:h,onClick:()=>x.current?.click(),children:[h?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(nt,{className:`size-4`}),`Import .md or .zip`]}),(0,K.jsxs)(w,{type:`button`,variant:`outline`,disabled:h,onClick:()=>S.current?.click(),children:[(0,K.jsx)(me,{className:`size-4`}),` Import folder of markdown`]})]}),(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Folders become parent pages; each `,(0,K.jsx)(`code`,{children:`.md`}),` becomes a page. Content is copied into the workspace (unlike linked mounts).`]})]})]})})}var Bf=$({method:`GET`}).handler(p(`19e00543f0313fe7905c045b33772265c61fa51d18574d69244c3f084698fddb`));$({method:`GET`}).handler(p(`9869410eeb67daab81f5d2ed574198eae379b3efb7eb41fe5a887f5ee51051d9`));var Vf=$({method:`POST`}).handler(p(`3a3b06354c92fa523d323b08f8cb2c04194a6d325c5629dfe4c092272682e98a`)),Hf=$({method:`POST`}).handler(p(`64ebef571e60681eaece2b296de9be5f6f33209c413aad1e4ff65d57e56c9c83`));function Uf({open:e,onOpenChange:t}){let[n,r]=(0,z.useState)([]),[i,a]=(0,z.useState)([]),[o,c]=(0,z.useState)([]),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(`mock`),[h,g]=(0,z.useState)(`JWT authentication`),[_,v]=(0,z.useState)(`hello`),[y,b]=(0,z.useState)(`What is a meta-harness?`),[x,S]=(0,z.useState)(`jwt-auth.yaml`),[C,T]=(0,z.useState)(null),[E,D]=(0,z.useState)(`workflow`),[O,A]=(0,z.useState)(null);if((0,z.useEffect)(()=>{e&&(u(!0),A(null),Bf().then(e=>{r(e.backends),a(e.agents),c(e.workflows),e.agents[0]&&v(e.agents[0].replace(/\.ya?ml$/,``));let t=e.workflows.find(e=>e.includes(`jwt`));t?S(t):e.workflows[0]&&S(e.workflows[0])}).catch(e=>A(e instanceof Error?e.message:`Failed to load harness`)).finally(()=>u(!1)))},[e]),!e)return null;let j=async()=>{f(!0),T(null),A(null);try{let e=await Hf({data:{workflow:x,feature:h||`feature`,backend:p||`mock`}});T(e),af.success(`Workflow done · ${e.runId}`)}catch(e){let t=e instanceof Error?e.message:`Run failed`;A(t),af.error(t)}finally{f(!1)}},M=async()=>{f(!0),T(null),A(null);try{let e=await Vf({data:{agent:_,message:y,backend:p||`mock`}});T(e),af.success(`Agent done · ${e.runId}`)}catch(e){let t=e instanceof Error?e.message:`Run failed`;A(t),af.error(t)}finally{f(!1)}};return(0,K.jsxs)(`div`,{className:`fixed inset-0 z-[120] flex items-center justify-center p-4`,children:[(0,K.jsx)(`button`,{type:`button`,className:`absolute inset-0 z-0 bg-black/40`,"aria-label":`Dismiss`,onClick:()=>{d||t(!1)}}),(0,K.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`harness-title`,className:`relative z-10 flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl border border-border bg-background shadow-2xl`,onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsxs)(`div`,{className:`border-b border-border px-6 py-4`,children:[(0,K.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`h2`,{id:`harness-title`,className:`flex items-center gap-2 text-lg font-semibold`,children:[(0,K.jsx)(Qe,{className:`size-4`}),`Meta-harness · CLI agents`]}),(0,K.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Plan → Implement → Review → Validate. Swap backends without rewriting the workflow.`})]}),(0,K.jsx)(`button`,{type:`button`,className:`rounded-md p-1.5 text-muted-foreground hover:bg-muted`,onClick:()=>t(!1),"aria-label":`Close`,children:(0,K.jsx)(ot,{className:`size-4`})})]}),(0,K.jsx)(`div`,{className:`mt-3 flex flex-wrap gap-1.5`,children:[[`workflow`,`Workflow`,at],[`agent`,`Single agent`,re],[`backends`,`Backends`,st]].map(([e,t,n])=>(0,K.jsxs)(`button`,{type:`button`,onClick:()=>D(e),className:s(`inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium`,E===e?`bg-foreground text-background`:`bg-muted text-muted-foreground`),children:[(0,K.jsx)(n,{className:`size-3`}),t]},e))})]}),(0,K.jsx)(`div`,{className:`min-h-0 flex-1 space-y-4 overflow-y-auto px-6 py-5 text-sm`,children:l?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,K.jsx)(ke,{className:`size-4 animate-spin`}),` Loading harness…`]}):(0,K.jsxs)(K.Fragment,{children:[O&&(0,K.jsx)(`div`,{className:`rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive`,children:O}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Backend slot (executor.harness)`}),(0,K.jsx)(`select`,{className:`h-9 w-full rounded-md border border-border bg-background px-2 text-sm`,value:p,onChange:e=>m(e.target.value),children:n.map(e=>(0,K.jsxs)(`option`,{value:e.id,children:[e.available?`●`:`○`,` `,e.label,` (`,e.id,`)`]},e.id))})]}),E===`workflow`&&(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Workflow`}),(0,K.jsx)(`select`,{className:`h-9 w-full rounded-md border border-border bg-background px-2 text-sm`,value:x,onChange:e=>S(e.target.value),children:o.map(e=>(0,K.jsx)(`option`,{value:e,children:e},e))})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Feature`}),(0,K.jsx)(k,{value:h,onChange:e=>g(e.target.value)})]}),(0,K.jsxs)(w,{type:`button`,disabled:d||!x,onClick:()=>void j(),children:[d?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(Re,{className:`size-4`}),`Run workflow`]}),(0,K.jsx)(`pre`,{className:`overflow-x-auto rounded-lg border border-border bg-muted/40 p-3 text-[11px] leading-relaxed text-muted-foreground`,children:`wks harness workflow ${x.replace(/\.ya?ml$/,``)} \\\n --feature "${h}" --backend ${p}`})]}),E===`agent`&&(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Agent YAML`}),(0,K.jsx)(`select`,{className:`h-9 w-full rounded-md border border-border bg-background px-2 text-sm`,value:_,onChange:e=>v(e.target.value),children:i.map(e=>(0,K.jsx)(`option`,{value:e.replace(/\.ya?ml$/,``),children:e},e))})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Message`}),(0,K.jsx)(k,{value:y,onChange:e=>b(e.target.value)})]}),(0,K.jsxs)(w,{type:`button`,disabled:d,onClick:()=>void M(),children:[d?(0,K.jsx)(ke,{className:`size-4 animate-spin`}):(0,K.jsx)(Re,{className:`size-4`}),`Run agent`]}),(0,K.jsx)(`pre`,{className:`overflow-x-auto rounded-lg border border-border bg-muted/40 p-3 text-[11px] text-muted-foreground`,children:`wks harness run ${_} --message "${y}" --backend ${p}`})]}),E===`backends`&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Install CLIs locally for live runs; `,(0,K.jsx)(`strong`,{children:`mock`}),` always works in preview. Grok Build via `,(0,K.jsx)(`code`,{children:`grok agent stdio`}),` (ACP).`]}),n.map(e=>(0,K.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-border px-3 py-2`,children:[(0,K.jsx)(`span`,{className:s(`mt-0.5 size-2 shrink-0 rounded-full`,e.available?`bg-emerald-500`:`bg-muted-foreground/40`)}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(`div`,{className:`font-medium`,children:e.label}),(0,K.jsxs)(`div`,{className:`text-[11px] text-muted-foreground`,children:[(0,K.jsx)(`code`,{children:e.id}),e.command?` · ${e.command}`:``]}),e.notes&&(0,K.jsx)(`p`,{className:`mt-0.5 text-[11px] text-muted-foreground`,children:e.notes})]}),e.available&&(0,K.jsx)(U,{className:`size-3.5 text-emerald-600`})]},e.id))]}),C&&(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border p-3`,"data-testid":`harness-result`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[(0,K.jsx)(`span`,{className:s(`rounded-full px-2 py-0.5 font-medium`,C.ok?`bg-emerald-500/15 text-emerald-800 dark:text-emerald-300`:`bg-destructive/10 text-destructive`),children:C.ok?`ok`:`failed`}),(0,K.jsxs)(`span`,{"data-volatile":!0,className:`text-muted-foreground`,children:[C.runId,` · `,C.backend,` · `,C.durationMs,`ms`]}),C.planPath&&(0,K.jsxs)(`span`,{className:`text-muted-foreground`,children:[`plan: `,C.planPath]})]}),(0,K.jsx)(`pre`,{className:`max-h-48 overflow-auto whitespace-pre-wrap rounded-md bg-muted/50 p-2 text-[11px] leading-relaxed`,children:C.summary})]})]})})]})]})}function Wf(){if(typeof window>`u`)return!1;let e=window;return!!(e.__TAURI_INTERNALS__||e.__TAURI__||e.__WORKSPACE_DESKTOP__)}async function Gf(){if(!Wf())return null;try{let{invoke:e}=await y(async()=>{let{invoke:e}=await import(`./core-CwxXejkd.js`);return{invoke:e}},[]);return await e(`desktop_info`)}catch{return{isDesktop:!0}}}function Kf({icon:e,label:t,onClick:n}){return(0,K.jsxs)(`button`,{type:`button`,onClick:n,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-sidebar-fg transition-colors hover:bg-sidebar-hover`,children:[e,(0,K.jsx)(`span`,{className:`truncate`,children:t})]})}function qf({onOpenSearch:e,mobile:t,onNavigate:n}){let r=m(e=>e.name),i=m(e=>e.pages),o=m(e=>e.activePageId),c=m(e=>e.theme),l=m(e=>e.storageMode),u=m(e=>e.syncStatus),d=m(e=>e.setActivePage),f=m(e=>e.createPage),p=m(e=>e.deletePage),h=m(e=>e.restorePage),g=m(e=>e.permanentlyDeletePage),_=m(e=>e.duplicatePage),v=m(e=>e.updatePage),y=m(e=>e.toggleSidebar),b=m(e=>e.setTheme),x=m(e=>e.setName),S=m(e=>e.resetWorkspace),{user:C}=D(),[T,E]=(0,z.useState)({}),[O,k]=(0,z.useState)(!1),[A,j]=(0,z.useState)(!1),[M,N]=(0,z.useState)(!1),[P,F]=(0,z.useState)(`welcome`),I=vd(),[L,R]=(0,z.useState)(!1),[B,V]=(0,z.useState)(!1),[ee,H]=(0,z.useState)(!1),te=jd(e=>e.mounts),ne=jd(e=>e.selection),re=jd(e=>e.setSelection),U=jd(e=>e.removeMount),[se,le]=(0,z.useState)({mount_sample:!0}),[de,pe]=(0,z.useState)({}),[me,he]=(0,z.useState)(null),[ge,_e]=(0,z.useState)(null);(0,z.useEffect)(()=>{Wf()&&Gf().then(e=>{e?.isDesktop&&he(e.platform?`Desktop · ${e.platform}`:`Desktop app`)})},[]),(0,z.useEffect)(()=>{dd().then(e=>{let t=e.clis;t?.length&&_e(t.map(e=>`${e.label.split(` `)[0]} ${e.available?`✓`:`·`}`).join(` · `))}).catch(()=>_e(null))},[]);let ve=(0,z.useCallback)(e=>{d(e),re(null),n?.()},[d,re,n]),ye=(0,z.useMemo)(()=>i.filter(e=>!e.archived&&e.favorite),[i]),be=(0,z.useMemo)(()=>i.filter(e=>e.archived),[i]),xe=(0,z.useMemo)(()=>i.filter(e=>!e.archived&&!e.parentId).sort((e,t)=>e.createdAt-t.createdAt),[i]),Se=(0,z.useCallback)(e=>i.filter(t=>!t.archived&&t.parentId===e).sort((e,t)=>e.createdAt-t.createdAt),[i]),Ce=async e=>{let t=te.find(t=>t.id===e);if(t)try{if(t.kind===`server`&&t.serverPath){let n=await Bd({data:{root:t.serverPath,relPath:``}}),r=Array.isArray(n)?n:[];pe(t=>({...t,[e]:r.map(e=>({name:e.name,relPath:e.relPath,kind:e.kind}))}))}else if(t.kind===`browser`){let t=await Id(e);if(!t){pe(t=>({...t,[e]:[]}));return}let n=await Ld(t,``);pe(t=>({...t,[e]:n}))}}catch{pe(t=>({...t,[e]:[]}))}},Te=(e,t)=>{re({mountId:e,relPath:t}),d(null),n?.()},Ee=(e,t)=>(e===null?xe:Se(e)).map(e=>{let n=Se(e.id).length>0,r=T[e.id]??t<1;return(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`div`,{className:s(`group flex items-center gap-0.5 rounded-md pr-1`,o===e.id&&!ne?`bg-sidebar-active text-foreground`:`hover:bg-sidebar-hover`),style:{paddingLeft:8+t*12},children:[(0,K.jsx)(`button`,{type:`button`,className:`flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground`,onClick:()=>E(t=>({...t,[e.id]:!r})),"aria-label":r?`Collapse`:`Expand`,children:n?r?(0,K.jsx)(ie,{className:`size-3.5`}):(0,K.jsx)(ae,{className:`size-3.5`}):(0,K.jsx)(`span`,{className:`size-3.5`})}),(0,K.jsxs)(`button`,{type:`button`,className:`flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm`,onClick:()=>ve(e.id),children:[(0,K.jsx)(`span`,{className:`shrink-0 text-sm`,children:e.icon||`📄`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.title||`Untitled`})]}),(0,K.jsxs)(`div`,{"data-hover-reveal":!0,className:`flex items-center opacity-0 group-hover:opacity-100`,children:[(0,K.jsxs)(lu,{children:[(0,K.jsx)(uu,{asChild:!0,children:(0,K.jsx)(`button`,{type:`button`,className:`flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10`,"aria-label":`Page menu`,children:(0,K.jsx)(ue,{className:`size-3.5 text-muted-foreground`})})}),(0,K.jsxs)(mu,{align:`start`,className:`w-48`,children:[(0,K.jsxs)(hu,{onClick:()=>v(e.id,{favorite:!e.favorite}),children:[(0,K.jsx)(Ye,{className:`size-4`}),e.favorite?`Unfavorite`:`Favorite`]}),(0,K.jsxs)(hu,{onClick:()=>{f({parentId:e.id}),E(t=>({...t,[e.id]:!0}))},children:[(0,K.jsx)(ze,{className:`size-4`}),` Add sub-page`]}),(0,K.jsxs)(hu,{onClick:()=>_(e.id),children:[(0,K.jsx)(ce,{className:`size-4`}),` Duplicate`]}),(0,K.jsx)(_u,{}),(0,K.jsxs)(hu,{className:`text-destructive focus:text-destructive`,onClick:()=>p(e.id),children:[(0,K.jsx)($e,{className:`size-4`}),` Delete`]})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`flex size-6 items-center justify-center rounded hover:bg-black/5 dark:hover:bg-white/10`,"aria-label":`New sub-page`,onClick:()=>{f({parentId:e.id}),E(t=>({...t,[e.id]:!0}))},children:(0,K.jsx)(ze,{className:`size-3.5 text-muted-foreground`})})]})]}),n&&r&&Ee(e.id,t+1)]},e.id)}),De=l===`database`?u===`saving`||u===`pending`?(0,K.jsx)(oe,{className:`size-3.5 animate-pulse text-muted-foreground`}):u===`error`?(0,K.jsx)(W,{className:`size-3.5 text-destructive`}):(0,K.jsx)(oe,{className:`size-3.5 text-emerald-600`}):(0,K.jsx)(W,{className:`size-3.5 text-muted-foreground`});return(0,K.jsxs)(`aside`,{className:s(`flex h-full flex-col border-r border-sidebar-border bg-sidebar text-sidebar-fg`,t?`w-full`:`w-[260px] min-w-[260px]`),children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-3`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-sidebar-hover`,onClick:()=>j(!0),children:[(0,K.jsx)(`span`,{className:`flex size-6 shrink-0 items-center justify-center rounded-md bg-foreground text-[11px] font-semibold text-background`,children:r.slice(0,1).toUpperCase()||`W`}),(0,K.jsx)(`span`,{className:`truncate text-sm font-semibold text-foreground`,children:r}),De]}),!t&&(0,K.jsx)(`button`,{type:`button`,className:`flex size-7 items-center justify-center rounded-md text-muted-foreground hover:bg-sidebar-hover`,onClick:()=>y(),"aria-label":`Collapse sidebar`,children:(0,K.jsx)(Ie,{className:`size-4`})})]}),me&&(0,K.jsxs)(`div`,{className:`mx-3 mb-1 flex items-center gap-1.5 rounded-md bg-muted/50 px-2 py-1 text-[10px] font-medium text-muted-foreground`,children:[(0,K.jsx)(Pe,{className:`size-3`}),me]}),(0,K.jsxs)(`div`,{className:`space-y-0.5 px-2 py-1`,children:[(0,K.jsx)(Kf,{icon:(0,K.jsx)(We,{className:`size-4`}),label:`Search`,onClick:e}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(ze,{className:`size-4`}),label:`New page`,onClick:()=>{let e=f();ve(e)}}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(fe,{className:`size-4`}),label:`Import / export`,onClick:()=>V(!0)}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(we,{className:`size-4`}),label:`Link markdown`,onClick:()=>R(!0)}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(Qe,{className:`size-4`}),label:`Agent harness`,onClick:()=>H(!0)})]}),(0,K.jsxs)(ao,{className:`min-h-0 flex-1 px-2`,children:[ye.length>0&&(0,K.jsxs)(`div`,{className:`mb-3`,children:[(0,K.jsx)(`div`,{className:`px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Favorites`}),ye.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:s(`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm`,o===e.id&&!ne?`bg-sidebar-active text-foreground`:`hover:bg-sidebar-hover`),onClick:()=>ve(e.id),children:[(0,K.jsx)(`span`,{children:e.icon||`📄`}),(0,K.jsx)(`span`,{className:`truncate`,children:e.title||`Untitled`})]},e.id))]}),(0,K.jsxs)(`div`,{className:`mb-3`,children:[(0,K.jsx)(`div`,{className:`px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Private`}),Ee(null,0),xe.length===0&&(0,K.jsx)(`p`,{className:`px-2 py-2 text-xs text-muted-foreground`,children:`No pages yet`})]}),(0,K.jsxs)(`div`,{className:`mb-3`,children:[(0,K.jsx)(`div`,{className:`px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Linked markdown`}),te.map(e=>{let t=se[e.id]??!1,n=de[e.id]??[];return(0,K.jsxs)(`div`,{className:`mb-0.5`,children:[(0,K.jsxs)(`div`,{className:`group flex items-center gap-0.5 rounded-md pr-1 hover:bg-sidebar-hover`,children:[(0,K.jsx)(`button`,{type:`button`,className:`flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground`,onClick:()=>{le(n=>({...n,[e.id]:!t})),t||Ce(e.id)},children:t?(0,K.jsx)(ie,{className:`size-3.5`}):(0,K.jsx)(ae,{className:`size-3.5`})}),(0,K.jsxs)(`button`,{type:`button`,className:`flex min-w-0 flex-1 items-center gap-2 py-1.5 text-left text-sm`,onClick:()=>{le(t=>({...t,[e.id]:!0})),Ce(e.id),Te(e.id,``)},children:[(0,K.jsx)(we,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,K.jsx)(`span`,{className:`truncate font-medium`,children:e.name})]}),(0,K.jsx)(`button`,{type:`button`,"data-hover-reveal":!0,className:`flex size-6 items-center justify-center rounded opacity-0 group-hover:opacity-100 hover:bg-black/5`,title:`Unlink`,onClick:()=>U(e.id),children:(0,K.jsx)(tt,{className:`size-3 text-muted-foreground`})})]}),t&&n.map(t=>(0,K.jsxs)(`button`,{type:`button`,className:s(`flex w-full items-center gap-2 rounded-md py-1.5 pl-8 pr-2 text-left text-sm`,ne?.mountId===e.id&&ne.relPath===t.relPath?`bg-sidebar-active text-foreground`:`text-sidebar-fg hover:bg-sidebar-hover`),onClick:()=>void Te(e.id,t.relPath),children:[(0,K.jsx)(`span`,{className:`text-xs`,children:t.kind===`dir`?`📁`:`📝`}),(0,K.jsx)(`span`,{className:`truncate`,children:t.name})]},t.relPath))]},e.id)}),(0,K.jsx)(`p`,{className:`px-2 py-1 text-[11px] text-muted-foreground`,children:`Link folder (no import)`})]})]}),(0,K.jsxs)(`div`,{className:`space-y-0.5 border-t border-sidebar-border px-2 py-2`,children:[!C&&(0,K.jsxs)(a,{to:`/login`,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-sidebar-hover`,children:[(0,K.jsx)(Ae,{className:`size-4`}),`Sign in to sync`]}),C&&(0,K.jsx)(`div`,{className:`px-1 py-1`,children:(0,K.jsx)(Qu,{})}),!C&&(0,K.jsx)(`p`,{className:`px-2 py-0.5 text-[11px] text-muted-foreground`,children:`Local only · Sign in to sync`}),(0,K.jsx)(Kf,{icon:(0,K.jsx)($e,{className:`size-4`}),label:`Trash`,onClick:()=>k(!0)}),(0,K.jsx)(Kf,{icon:(0,K.jsx)(Ge,{className:`size-4`}),label:`Settings`,onClick:()=>j(!0)})]}),(0,K.jsx)(Gu,{open:O,onOpenChange:k,children:(0,K.jsxs)(Ju,{className:`max-w-md`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsx)(Xu,{children:`Trash`}),(0,K.jsx)(Zu,{children:`Restored pages return to the top level of your workspace.`})]}),(0,K.jsxs)(`div`,{className:`max-h-72 space-y-1 overflow-y-auto`,children:[be.length===0&&(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Trash is empty`}),be.map(e=>(0,K.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-border px-2 py-1.5`,children:[(0,K.jsx)(`span`,{children:e.icon||`📄`}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm`,children:e.title||`Untitled`}),(0,K.jsx)(w,{size:`sm`,variant:`outline`,onClick:()=>h(e.id),children:`Restore`}),(0,K.jsx)(w,{size:`sm`,variant:`ghost`,className:`text-destructive`,onClick:()=>g(e.id),children:`Delete`})]},e.id))]})]})}),(0,K.jsx)(Gu,{open:A,onOpenChange:j,children:(0,K.jsxs)(Ju,{className:`max-w-md`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsx)(Xu,{children:`Settings`}),(0,K.jsx)(Zu,{children:`Workspace preferences and AI`})]}),(0,K.jsxs)(`div`,{className:`space-y-4 text-sm`,children:[me&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs`,children:[(0,K.jsx)(Pe,{className:`size-3.5`}),`Running as `,me,(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`· Tauri standalone`})]}),(0,K.jsxs)(`label`,{className:`block space-y-1.5`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground`,children:`Workspace name`}),(0,K.jsx)(`input`,{className:`h-9 w-full rounded-md border border-border bg-background px-3 text-sm`,value:r,onChange:e=>x(e.target.value)})]}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`span`,{className:`text-sm`,children:`Theme`}),(0,K.jsxs)(`div`,{className:`flex gap-1`,children:[(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:c===`light`?`default`:`outline`,onClick:()=>b(`light`),children:[(0,K.jsx)(Xe,{className:`size-3.5`}),` Light`]}),(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:c===`dark`?`default`:`outline`,onClick:()=>b(`dark`),children:[(0,K.jsx)(Fe,{className:`size-3.5`}),` Dark`]})]})]}),(0,K.jsxs)(`div`,{className:`rounded-lg border border-border p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 font-medium`,children:[(0,K.jsx)(Ke,{className:`size-4`}),` AI`]}),(0,K.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Backend: `,hd[I.backend]?.label??I.backend,!hd[I.backend]?.isCli&&(0,K.jsxs)(K.Fragment,{children:[` `,`· `,gd[I.provider]?.label,` · `,I.model]})]}),ge&&(0,K.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`CLIs: `,ge]}),(0,K.jsx)(w,{type:`button`,size:`sm`,className:`mt-2`,variant:`secondary`,onClick:()=>{F(`provider`),N(!0)},children:`Configure AI`})]}),(0,K.jsxs)(`div`,{className:`rounded-lg border border-border p-3 text-xs text-muted-foreground`,children:[`Storage: `,l===`database`?`Database (synced)`:`Local only`,l===`database`&&` · ${u}`]}),(0,K.jsxs)(w,{type:`button`,variant:`outline`,className:`w-full text-destructive`,onClick:()=>{confirm(`Reset workspace to seed pages? This cannot be undone.`)&&(S(),j(!1))},children:[(0,K.jsx)(He,{className:`size-4`}),` Reset workspace`]})]})]})}),(0,K.jsx)(zf,{open:B,onOpenChange:V}),(0,K.jsx)(xf,{open:L,onOpenChange:R}),(0,K.jsx)(Uf,{open:ee,onOpenChange:H}),(0,K.jsx)(xd,{open:M,onOpenChange:N,initialStep:P})]})}var Jf=Object.defineProperty,Yf=(e,t)=>Jf(e,`name`,{value:t,configurable:!0}),Xf=`Popover`,[Zf,Qf]=vt(Xf,[ui]),$f=ui(),[ep,tp]=Zf(Xf),np=Yf(e=>{let{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:o=!1}=e,s=$f(t),c=z.useRef(null),[l,u]=z.useState(!1),[d,f]=z.useState(0),[p,m]=z.useState(0),[h,g]=Hi({prop:r,defaultProp:i??!1,onChange:a,caller:Xf});return(0,K.jsx)(pi,{...s,children:(0,K.jsx)(ep,{scope:t,contentId:Y(),titleId:Y(),descriptionId:Y(),titlePresent:d>0,descriptionPresent:p>0,setTitleCount:f,setDescriptionCount:m,triggerRef:c,open:h,onOpenChange:g,onOpenToggle:z.useCallback(()=>g(e=>!e),[g]),hasCustomAnchor:l,onCustomAnchorAdd:z.useCallback(()=>u(!0),[]),onCustomAnchorRemove:z.useCallback(()=>u(!1),[]),modal:o,children:n})})},`Popover`),rp=`PopoverTrigger`,ip=z.forwardRef(Yf(function(e,t){let{__scopePopover:n,...r}=e,i=tp(rp,n),a=$f(n),o=C(t,i.triggerRef),s=(0,K.jsx)(q.button,{type:`button`,"aria-haspopup":`dialog`,"aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":hp(i.open),...r,ref:o,onClick:G(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?s:(0,K.jsx)(hi,{asChild:!0,...a,children:s})},`PopoverTrigger`)),ap=`PopoverPortal`,[op,sp]=Zf(ap,{forceMount:void 0}),cp=Yf(e=>{let{__scopePopover:t,forceMount:n,children:r,container:i}=e,a=tp(ap,t);return(0,K.jsx)(op,{scope:t,forceMount:n,children:(0,K.jsx)(Oi,{present:n||a.open,children:(0,K.jsx)(wi,{asChild:!0,container:i,children:r})})})},`PopoverPortal`),lp=`PopoverContent`,up=z.forwardRef(Yf(function(e,t){let n=sp(lp,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,a=tp(lp,e.__scopePopover);return(0,K.jsx)(Oi,{present:r||a.open,children:a.modal?(0,K.jsx)(fp,{...i,ref:t}):(0,K.jsx)(pp,{...i,ref:t})})},`PopoverContent`)),dp=S(`PopoverContent.RemoveScroll`),fp=z.forwardRef(Yf(function(e,t){let n=tp(lp,e.__scopePopover),r=z.useRef(null),i=C(t,r),a=z.useRef(!1);return z.useEffect(()=>{let e=r.current;if(e)return Ds(e)},[]),(0,K.jsx)(Ic,{as:dp,allowPinchZoom:!0,children:(0,K.jsx)(mp,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:G(e.onCloseAutoFocus,e=>{e.preventDefault(),a.current||n.triggerRef.current?.focus()}),onPointerDownOutside:G(e.onPointerDownOutside,e=>{let t=e.detail.originalEvent,n=t.button===0&&t.ctrlKey===!0,r=t.button===2||n;a.current=r},{checkForDefaultPrevented:!1}),onFocusOutside:G(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})},`PopoverContentModal`)),pp=z.forwardRef(Yf(function(e,t){let n=tp(lp,e.__scopePopover),r=z.useRef(!1),i=z.useRef(!1);return(0,K.jsx)(mp,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(r.current||n.triggerRef.current?.focus(),t.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(r.current=!0,t.detail.originalEvent.type===`pointerdown`&&(i.current=!0));let a=t.target;n.triggerRef.current?.contains(a)&&t.preventDefault(),t.detail.originalEvent.type===`focusin`&&i.current&&t.preventDefault()}})},`PopoverContentNonModal`)),mp=z.forwardRef(Yf(function(e,t){let{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:o,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:l,onInteractOutside:u,"aria-describedby":d,...f}=e,p=tp(lp,n),m=$f(n);return To(),(0,K.jsx)(Mo,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:(0,K.jsx)(Nt,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:u,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:l,onDismiss:()=>p.onOpenChange(!1),deferPointerDownOutside:!0,children:(0,K.jsx)(yi,{"data-state":hp(p.open),role:`dialog`,id:p.contentId,"aria-labelledby":p.titlePresent?p.titleId:void 0,"aria-describedby":p.descriptionPresent?gp(d,p.descriptionId):d,...m,...f,ref:t,style:{...f.style,"--radix-popover-content-transform-origin":`var(--radix-popper-transform-origin)`,"--radix-popover-content-available-width":`var(--radix-popper-available-width)`,"--radix-popover-content-available-height":`var(--radix-popper-available-height)`,"--radix-popover-trigger-width":`var(--radix-popper-anchor-width)`,"--radix-popover-trigger-height":`var(--radix-popper-anchor-height)`}})})})},`PopoverContentImpl`));function hp(e){return e?`open`:`closed`}Yf(hp,`getState`);function gp(...e){let t=new Set;for(let n of e)if(typeof n==`string`)for(let e of String(n).trim().split(/\s+/))e&&t.add(e);return t.size>0?Array.from(t).join(` `):void 0}Yf(gp,`concatAriaDescribedby`);var _p=np,vp=ip;function yp({className:e,align:t=`center`,sideOffset:n=6,...r}){return(0,K.jsx)(cp,{children:(0,K.jsx)(up,{align:t,sideOffset:n,className:s(`z-50 w-72 rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-lg outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95`,e),...r})})}var bp=[{type:`paragraph`,label:`Text`,description:`Just start writing with plain text.`,icon:et,keywords:[`text`,`paragraph`,`plain`],placeholder:`Type '/' for commands`},{type:`heading1`,label:`Heading 1`,description:`Big section heading.`,icon:be,keywords:[`h1`,`title`,`heading`],placeholder:`Heading 1`},{type:`heading2`,label:`Heading 2`,description:`Medium section heading.`,icon:xe,keywords:[`h2`,`heading`,`subtitle`],placeholder:`Heading 2`},{type:`heading3`,label:`Heading 3`,description:`Small section heading.`,icon:Se,keywords:[`h3`,`heading`],placeholder:`Heading 3`},{type:`bullet`,label:`Bulleted list`,description:`Create a simple bulleted list.`,icon:Oe,keywords:[`ul`,`list`,`bullet`,`unordered`],placeholder:`List item`},{type:`numbered`,label:`Numbered list`,description:`Create a list with numbering.`,icon:Te,keywords:[`ol`,`list`,`number`,`ordered`],placeholder:`List item`},{type:`todo`,label:`To-do list`,description:`Track tasks with a to-do checkbox.`,icon:qe,keywords:[`todo`,`task`,`checkbox`,`check`],placeholder:`To-do`},{type:`toggle`,label:`Toggle`,description:`Hide and show content inside.`,icon:ae,keywords:[`toggle`,`collapse`,`details`],placeholder:`Toggle heading`},{type:`quote`,label:`Quote`,description:`Capture a quote.`,icon:Ve,keywords:[`quote`,`blockquote`,`cite`],placeholder:`Empty quote`},{type:`callout`,label:`Callout`,description:`Make writing stand out.`,icon:Me,keywords:[`callout`,`note`,`info`,`tip`],placeholder:`Callout`},{type:`code`,label:`Code`,description:`Capture a code snippet.`,icon:se,keywords:[`code`,`snippet`,`pre`],placeholder:`Code`},{type:`mermaid`,label:`Mermaid`,description:`Diagram with Mermaid syntax.`,icon:at,keywords:[`mermaid`,`diagram`,`flowchart`,`sequence`,`graph`],placeholder:`flowchart TD + A[Start] --> B[End]`},{type:`ai`,label:`AI`,description:`Generate from the rest of this page.`,icon:Ke,keywords:[`ai`,`gpt`,`grok`,`summary`,`assistant`,`llm`],placeholder:`Summarize this page as a launch checklist…`},{type:`divider`,label:`Divider`,description:`Visually divide blocks.`,icon:Ne,keywords:[`divider`,`line`,`hr`,`separator`],placeholder:``}];function xp(e){return bp.find(t=>t.type===e)??bp[0]}function Sp(e){let t=e.trim().toLowerCase();return t?bp.filter(e=>e.label.toLowerCase().includes(t)||e.description.toLowerCase().includes(t)||e.keywords.some(e=>e.includes(t))):bp}function Cp({query:e,selectedIndex:t,onSelect:n,onHover:r,position:i}){let a=(0,z.useMemo)(()=>Sp(e),[e]),o=(0,z.useRef)(null);return(0,z.useEffect)(()=>{(o.current?.querySelector(`[data-index="${t}"]`))?.scrollIntoView({block:`nearest`})},[t]),a.length===0?(0,K.jsx)(`div`,{className:`fixed z-50 w-72 overflow-hidden rounded-xl border border-border bg-popover p-3 text-sm text-muted-foreground shadow-xl`,style:{top:i.top,left:i.left},children:`No matching blocks`}):(0,K.jsxs)(`div`,{ref:o,className:`fixed z-50 max-h-72 w-72 overflow-y-auto rounded-xl border border-border bg-popover p-1.5 shadow-xl`,style:{top:i.top,left:Math.min(i.left,window.innerWidth-300)},role:`listbox`,children:[(0,K.jsx)(`div`,{className:`px-2 py-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:`Basic blocks`}),a.map((e,i)=>{let a=e.icon;return(0,K.jsxs)(`button`,{type:`button`,"data-index":i,role:`option`,"aria-selected":i===t,className:s(`flex w-full items-start gap-2.5 rounded-lg px-2 py-2 text-left transition-colors`,i===t?`bg-muted`:`hover:bg-muted/70`),onMouseEnter:()=>r(i),onMouseDown:t=>{t.preventDefault(),n(e.type)},children:[(0,K.jsx)(`span`,{className:`mt-0.5 flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground`,children:(0,K.jsx)(a,{className:`size-4`})}),(0,K.jsxs)(`span`,{className:`min-w-0`,children:[(0,K.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),(0,K.jsx)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:e.description})]})]},e.type)})]})}var wp=null;function Tp(){return wp||=y(()=>import(`./mermaid.core-lwoghoVk.js`).then(e=>{let t=e.default;return t.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),t}),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23])),wp}function Ep({source:e,className:t}){let n=(0,z.useId)().replace(/:/g,``),r=(0,z.useRef)(null),[i,a]=(0,z.useState)(null),[o,c]=(0,z.useState)(``);return(0,z.useEffect)(()=>{let t=!1,r=e.trim();if(!r){c(``),a(null);return}return(async()=>{try{let e=await Tp();e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`});let i=`mmd_${n}_${Math.random().toString(36).slice(2,8)}`,{svg:o}=await e.render(i,r);t||(c(o),a(null))}catch(e){t||(c(``),a(e instanceof Error?e.message:`Invalid Mermaid diagram`))}})(),()=>{t=!0}},[e,n]),e.trim()?i?(0,K.jsx)(`div`,{className:`rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive`,children:i}):(0,K.jsx)(`div`,{ref:r,className:s(`overflow-x-auto rounded-md border border-border bg-background px-3 py-4 [&_svg]:mx-auto [&_svg]:max-w-full`,t),dangerouslySetInnerHTML:o?{__html:o}:void 0}):(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Write Mermaid syntax (e.g. flowchart TD) — diagram previews here.`})}async function Dp(e){let t=await fetch(`/api/ai/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({...e.request,clientSettings:e.clientSettings,backend:e.backend}),signal:e.signal});if(!t.ok){let e=await t.text().catch(()=>t.statusText);throw Error(e||`Stream failed (${t.status})`)}if(!t.body)throw Error(`No response body for stream`);let n=t.body.getReader(),r=new TextDecoder,i=``,a=``,o=null,s=null;for(;;){let{done:t,value:c}=await n.read();if(t)break;i+=r.decode(c,{stream:!0});let l=i.split(` + +`);i=l.pop()??``;for(let t of l){let n=t.split(` +`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim()).join(``);if(!n)continue;let r;try{r=JSON.parse(n)}catch{continue}r.type===`token`&&r.text?(a+=r.text,e.onToken?.(r.text,a)):r.type===`status`&&r.message?e.onStatus?.(r.message):r.type===`done`?(r.text&&(a=r.text),o=r.result?r.result:{text:a,provider:`local`},e.onDone?.(o,a)):r.type===`error`&&(s=r.message||`Stream error`,e.onError?.(s))}}if(s&&!o&&!a.trim())throw Error(s);return o??{text:a,provider:`local`}}var Op=[{action:`summarize`,label:`Summary`,icon:pe,hint:`Condense the page`},{action:`action_items`,label:`Todos`,icon:Ee,hint:`Extract action items`},{action:`table`,label:`Table`,icon:Ze,hint:`Markdown table`},{action:`outline`,label:`Outline`,icon:De,hint:`Hierarchical outline`},{action:`mermaid`,label:`Diagram`,icon:at,hint:`Mermaid flowchart`}];function kp(e,t){return e===`claude-cli`?`Claude Code CLI`:e===`codex-cli`?`Codex CLI`:e===`grok-cli`?`Grok CLI`:e===`deepagents`?`Deep Agents · ${t??`model`}`:e===`direct`?t??`Direct API`:e===`xai`?t??`Grok`:`Local demo AI`}function Ap({content:e,aiOutput:t,aiError:n,pageTitle:r,pageText:i,onChangePrompt:a,onResult:o}){let[s,c]=(0,z.useState)(!1),[l,u]=(0,z.useState)(null),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(``),[h,g]=(0,z.useState)(null),_=(0,z.useRef)(null),v=()=>{_.current?.abort(),_.current=null,c(!1),g(`Stopped`)},y=async(t,n)=>{c(!0),m(``),g(null);let a=yd(),s=a.preferStreaming!==!1,l=a.backend===`claude-cli`||a.backend===`codex-cli`||a.backend===`grok-cli`,d=s&&(l||a.backend===`direct`||a.backend===`deepagents`);try{if(d){let s=new AbortController;_.current=s;let c=await Dp({request:{action:t,instruction:n??e,pageTitle:r,pageText:i},clientSettings:a,backend:a.backend,signal:s.signal,onToken:(e,t)=>m(t),onStatus:e=>g(e)});u(kp(c.provider,c.model)),o({output:c.text||(c.blocks?c.blocks.map(e=>`${e.type}: ${e.content}`).join(` +`):``),blocks:c.blocks}),m(``)}else{let s=await cd({data:{action:t,instruction:n??e,pageTitle:r,pageText:i,clientSettings:a}});u(kp(s.provider,s.model)),o({output:s.text||(s.blocks?s.blocks.map(e=>`${e.type}: ${e.content}`).join(` +`):``),blocks:s.blocks})}}catch(e){e?.name===`AbortError`?o({output:p,error:`Generation stopped`}):o({output:``,error:e instanceof Error?e.message:`AI request failed`})}finally{_.current=null,c(!1),g(null)}},b=yd(),x=hd[b.backend]?.label??b.backend;return(0,K.jsxs)(`div`,{className:`w-full space-y-3 rounded-xl border border-border bg-muted/30 p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-medium text-foreground`,children:[(0,K.jsx)(`span`,{className:`flex size-7 items-center justify-center rounded-md bg-foreground text-background`,children:(0,K.jsx)(Ke,{className:`size-3.5`})}),`AI block`,(0,K.jsx)(`span`,{className:`ml-auto text-[11px] font-normal text-muted-foreground`,children:l??x})]}),(0,K.jsx)(kd,{onOpen:()=>f(!0)}),(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Uses page context. Backends: Deep Agents, API keys, or coding CLIs (Claude Code / Codex / Grok) with live streaming when available.`}),(0,K.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:Op.map(e=>{let t=e.icon;return(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`outline`,className:`bg-background`,disabled:s,title:e.hint,onClick:()=>void y(e.action),children:[(0,K.jsx)(t,{className:`size-3.5`}),e.label]},e.action)})}),(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsx)(`textarea`,{className:`min-h-[64px] flex-1 resize-y rounded-md border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring/30`,placeholder:`Custom instruction…`,value:e,onChange:e=>a(e.target.value),disabled:s}),s?(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`destructive`,onClick:v,children:[(0,K.jsx)(Je,{className:`size-3.5`}),`Stop`]}):(0,K.jsxs)(w,{type:`button`,size:`sm`,disabled:!e.trim(),onClick:()=>void y(`custom`,e),children:[(0,K.jsx)(Re,{className:`size-3.5`}),`Run`]})]}),(s||p)&&(0,K.jsxs)(`div`,{className:`rounded-lg border border-border bg-background p-3`,children:[(0,K.jsxs)(`div`,{className:`mb-1 flex items-center gap-2 text-[11px] text-muted-foreground`,children:[s&&(0,K.jsx)(ke,{className:`size-3 animate-spin`}),h??(s?`Streaming…`:`Preview`)]}),(0,K.jsx)(`pre`,{className:`max-h-40 overflow-auto whitespace-pre-wrap text-xs leading-relaxed`,children:p||`…`})]}),n&&(0,K.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),t&&!p&&(0,K.jsx)(`pre`,{className:`max-h-48 overflow-auto rounded-lg border border-border bg-background p-3 text-xs`,children:t}),(0,K.jsx)(xd,{open:d,onOpenChange:f})]})}var jp=[{id:`improve`,label:`Improve`,instruction:`Improve clarity and flow while preserving meaning.`},{id:`shorter`,label:`Shorter`,instruction:`Make this shorter and more concise.`},{id:`longer`,label:`Expand`,instruction:`Expand this with one more sentence of useful detail.`},{id:`fix`,label:`Fix grammar`,instruction:`Fix grammar and spelling only.`},{id:`pro`,label:`Professional`,instruction:`Rewrite in a clear, professional tone.`}];function Mp(e,t){return e===`claude-cli`?`Claude Code CLI`:e===`codex-cli`?`Codex CLI`:e===`grok-cli`?`Grok CLI`:e===`deepagents`?`Deep Agents · ${t??`model`}`:e===`direct`?t??`Direct API`:e===`xai`?t??`Grok`:`Local demo AI`}function Np({open:e,onOpenChange:t,blockText:n,blockType:r,pageTitle:i,pageText:a,onApply:o}){let[c,l]=(0,z.useState)(``),[u,d]=(0,z.useState)(null),[f,p]=(0,z.useState)(!1),[m,h]=(0,z.useState)(null),[g,_]=(0,z.useState)(null),[v,y]=(0,z.useState)(null),[b,x]=(0,z.useState)(!1),S=(0,z.useRef)(null),C=()=>{S.current?.abort(),S.current=null,p(!1)},T=async e=>{p(!0),h(null),d(``),y(null);let t=yd(),o=t.preferStreaming!==!1,s=t.backend===`claude-cli`||t.backend===`codex-cli`||t.backend===`grok-cli`,c=o&&(s||t.backend===`direct`||t.backend===`deepagents`);try{if(c){let o=new AbortController;S.current=o;let s=await Dp({request:{action:`edit_block`,instruction:e,blockText:n,blockType:r,pageTitle:i,pageText:a},clientSettings:t,backend:t.backend,signal:o.signal,onToken:(e,t)=>d(t),onStatus:e=>y(e)});d(s.text),_(Mp(s.provider,s.model))}else{let o=await cd({data:{action:`edit_block`,instruction:e,blockText:n,blockType:r,pageTitle:i,pageText:a,clientSettings:t}});d(o.text),_(Mp(o.provider,o.model))}}catch(e){e?.name!==`AbortError`&&h(e instanceof Error?e.message:`AI request failed`)}finally{S.current=null,p(!1),y(null)}};return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Gu,{open:e,onOpenChange:e=>{e||(C(),d(null),h(null),l(``)),t(e)},children:(0,K.jsxs)(Ju,{className:`max-w-lg`,children:[(0,K.jsxs)(Yu,{children:[(0,K.jsxs)(Xu,{className:`flex items-center gap-2`,children:[(0,K.jsx)(Ke,{className:`size-4`}),`Edit block with AI`]}),(0,K.jsxs)(Zu,{children:[`Rewrite this block. Uses your configured backend (API or Claude / Codex / Grok CLI) with streaming when available.`,g&&(0,K.jsx)(`span`,{className:`mt-1 block text-xs text-muted-foreground`,children:g})]})]}),(0,K.jsx)(kd,{onOpen:()=>x(!0)}),(0,K.jsxs)(`div`,{className:`rounded-md border border-border bg-muted/40 p-2 text-xs text-muted-foreground`,children:[(0,K.jsx)(`span`,{className:`font-medium text-foreground`,children:`Original`}),(0,K.jsx)(`p`,{className:`mt-1 line-clamp-4 whitespace-pre-wrap`,children:n||`(empty)`})]}),(0,K.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:jp.map(e=>(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`outline`,disabled:f,onClick:()=>void T(e.instruction),children:[(0,K.jsx)(rt,{className:`size-3.5`}),e.label]},e.id))}),(0,K.jsxs)(`div`,{className:`flex gap-2`,children:[(0,K.jsx)(`input`,{className:`h-9 flex-1 rounded-md border border-border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring/30`,placeholder:`Custom instruction…`,value:c,onChange:e=>l(e.target.value),disabled:f,onKeyDown:e=>{e.key===`Enter`&&c.trim()&&T(c.trim())}}),f?(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`destructive`,onClick:C,children:[(0,K.jsx)(Je,{className:`size-3.5`}),`Stop`]}):(0,K.jsx)(w,{type:`button`,size:`sm`,disabled:!c.trim(),onClick:()=>void T(c.trim()),children:`Run`})]}),f&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,K.jsx)(ke,{className:`size-3.5 animate-spin`}),v??`Generating…`]}),m&&(0,K.jsx)(`p`,{className:`text-xs text-destructive`,children:m}),u!=null&&u!==``&&(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:`Preview`}),(0,K.jsx)(`pre`,{className:s(`max-h-48 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-background p-3 text-sm`,f&&`opacity-80`),children:u}),(0,K.jsx)(w,{type:`button`,className:`w-full`,disabled:f,onClick:()=>{o(u),t(!1)},children:`Apply to block`})]})]})}),(0,K.jsx)(xd,{open:b,onOpenChange:x})]})}function Pp({block:e,index:t,isFocused:n,listNumber:r,pageTitle:i,pageText:a,onFocus:o,onChange:c,onTypeChange:l,onToggleCheck:u,onToggleCollapse:d,onEnter:f,onBackspaceEmpty:p,onMove:m,onDelete:h,onIndent:g,onPatch:_,onAiInsert:v,focusRequest:y,onFocusHandled:b,inputRefs:x}){let S=xp(e.type),C=(0,z.useRef)(null),T=(0,z.useRef)(null),[E,D]=(0,z.useState)(!1),[O,k]=(0,z.useState)(``),[A,j]=(0,z.useState)(0),[M,N]=(0,z.useState)({top:0,left:0}),[P,F]=(0,z.useState)(!1),[I,L]=(0,z.useState)(!1),R=(0,z.useCallback)(t=>{C.current=t,t?x.current.set(e.id,t):x.current.delete(e.id)},[e.id,x]),B=(0,z.useCallback)(()=>{let e=C.current;e&&(e.style.height=`0px`,e.style.height=`${Math.max(e.scrollHeight,28)}px`)},[]);(0,z.useEffect)(()=>{B()},[e.content,e.type,B]),(0,z.useEffect)(()=>{if(y!==e.id)return;let t=C.current;if(t){t.focus();let e=t.value.length;t.setSelectionRange(e,e)}b()},[y,e.id,b]);let V=e=>{let t=T.current;if(!t)return;let n=t.getBoundingClientRect(),r=Math.min(n.left+48,window.innerWidth-300),i=n.bottom+280>window.innerHeight?Math.max(8,n.top-280):n.bottom+4;N({top:i,left:r}),k(e),j(0),D(!0)},ee=()=>{D(!1),k(``),j(0)},H=t=>{let n=e.content,r=n.lastIndexOf(`/`),i=r>=0?n.slice(0,r):n;c(e.id,i),l(e.id,t),ee(),requestAnimationFrame(()=>{x.current.get(e.id)?.focus()})},te=t=>{c(e.id,t),requestAnimationFrame(B);let n=t.lastIndexOf(`/`);if(n>=0){let e=t.slice(n+1),r=t[n-1];if((n===0||r===` `||r===` +`)&&!e.includes(` +`)){V(e);return}}E&&ee()},ne=t=>{if(E){let e=Sp(O);if(t.key===`ArrowDown`){t.preventDefault(),j(t=>(t+1)%Math.max(e.length,1));return}if(t.key===`ArrowUp`){t.preventDefault(),j(t=>(t-1+Math.max(e.length,1))%Math.max(e.length,1));return}if(t.key===`Enter`||t.key===`Tab`){t.preventDefault();let n=e[A];n&&H(n.type);return}if(t.key===`Escape`){t.preventDefault(),ee();return}}if(t.key===`Enter`&&!t.shiftKey&&e.type!==`code`&&e.type!==`mermaid`){t.preventDefault(),f(e.id);return}if(t.key===`Backspace`){let n=t.currentTarget;if(!n.value&&n.selectionStart===0){t.preventDefault(),p(e.id);return}}t.key===`Tab`&&(t.preventDefault(),g(e.id,t.shiftKey?-1:1)),t.key===`ArrowUp`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),m(e.id,`up`)),t.key===`ArrowDown`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),m(e.id,`down`))},re={paddingLeft:`${(e.indent??0)*1.5}rem`},ie=e.type!==`divider`&&e.type!==`ai`&&e.type!==`mermaid`;if(e.type===`divider`)return(0,K.jsxs)(`div`,{ref:T,"data-block-id":e.id,"data-block-type":e.type,className:`group relative flex items-center gap-1 py-2`,style:re,onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,K.jsx)(Fp,{visible:P||n,canAiEdit:!1,onAdd:()=>f(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>l(e.id,t),onAiEdit:()=>L(!0)}),(0,K.jsx)(`hr`,{className:`w-full border-0 border-t border-border`})]});if(e.type===`ai`)return(0,K.jsxs)(`div`,{ref:T,"data-block-id":e.id,"data-block-type":e.type,className:`group relative py-1`,style:re,onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,K.jsx)(Fp,{visible:P||n,canAiEdit:!1,onAdd:()=>f(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>l(e.id,t),onAiEdit:()=>void 0}),(0,K.jsx)(`div`,{className:`pl-1`,children:(0,K.jsx)(Ap,{content:e.content,aiOutput:e.aiOutput,aiError:e.aiError,pageTitle:i,pageText:a,onChangePrompt:t=>c(e.id,t),onResult:({output:t,blocks:n,error:r})=>{_(e.id,{aiOutput:t,aiError:r}),n?.length&&v(e.id,n)}})})]});if(e.type===`mermaid`){let t=e.showSource??!e.content.trim();return(0,K.jsxs)(`div`,{ref:T,"data-block-id":e.id,"data-block-type":e.type,className:`group relative py-1`,style:re,onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,K.jsx)(Fp,{visible:P||n,canAiEdit:!1,onAdd:()=>f(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>l(e.id,t),onAiEdit:()=>void 0}),(0,K.jsxs)(`div`,{className:`space-y-2 rounded-xl border border-border bg-muted/20 p-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,children:`Mermaid`}),(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`h-7 text-muted-foreground`,onClick:()=>_(e.id,{showSource:!t}),children:t?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(de,{className:`size-3.5`}),` Preview`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(se,{className:`size-3.5`}),` Edit source`]})})]}),t?(0,K.jsx)(`textarea`,{ref:R,value:e.content,onChange:e=>te(e.target.value),onFocus:()=>o(e.id),onKeyDown:ne,placeholder:S.placeholder,rows:Math.max(4,e.content.split(` +`).length),spellCheck:!1,className:`w-full resize-y rounded-md border border-border bg-background px-3 py-2 font-mono text-sm leading-relaxed text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/40`}):(0,K.jsx)(Ep,{source:e.content})]}),E&&(0,K.jsx)(Cp,{query:O,selectedIndex:A,onSelect:H,onHover:j,position:M})]})}let W=s(`block w-full resize-none overflow-hidden border-0 bg-background p-0 text-foreground shadow-none outline-none ring-0 focus:outline-none focus:ring-0`,`placeholder:text-muted-foreground/60`,e.type===`paragraph`&&`text-base leading-relaxed`,e.type===`heading1`&&`text-3xl font-semibold leading-tight tracking-tight`,e.type===`heading2`&&`text-2xl font-semibold leading-tight tracking-tight`,e.type===`heading3`&&`text-xl font-semibold leading-snug tracking-tight`,(e.type===`bullet`||e.type===`numbered`)&&`text-base leading-relaxed`,e.type===`todo`&&s(`text-base leading-relaxed`,e.checked&&`text-muted-foreground line-through`),e.type===`toggle`&&`text-base font-medium leading-relaxed`,e.type===`quote`&&`text-base leading-relaxed text-muted-foreground`,e.type===`callout`&&`text-base leading-relaxed`,e.type===`code`&&`min-h-16 font-mono text-sm leading-relaxed`);return(0,K.jsxs)(`div`,{ref:T,"data-block-id":e.id,"data-block-type":e.type,className:s(`group relative flex items-start gap-1 rounded-md py-0.5`,n&&`bg-muted/40`),style:re,onMouseEnter:()=>F(!0),onMouseLeave:()=>F(!1),children:[(0,K.jsx)(Fp,{visible:P||n,canAiEdit:ie,onAdd:()=>f(e.id),onMoveUp:()=>m(e.id,`up`),onMoveDown:()=>m(e.id,`down`),onDelete:()=>h(e.id),onTypeChange:t=>l(e.id,t),onAiEdit:()=>L(!0)}),(0,K.jsxs)(`div`,{className:s(`flex min-w-0 flex-1 items-start gap-2 rounded-md px-1 py-1`,e.type===`callout`&&`border border-border bg-muted/50 px-3 py-2.5`,e.type===`quote`&&`border-l-2 border-foreground/25 pl-3`,e.type===`code`&&`border border-border bg-muted/60 px-3 py-2.5`),children:[e.type===`bullet`&&(0,K.jsx)(`span`,{className:`mt-2.5 size-1.5 shrink-0 rounded-full bg-foreground/80`}),e.type===`numbered`&&(0,K.jsxs)(`span`,{className:`mt-1 w-5 shrink-0 text-right text-sm tabular-nums text-muted-foreground`,children:[r??t+1,`.`]}),e.type===`todo`&&(0,K.jsx)(`button`,{type:`button`,className:s(`mt-1.5 flex size-4 shrink-0 items-center justify-center rounded border transition-colors`,e.checked?`border-primary bg-primary text-primary-foreground`:`border-border bg-background hover:border-foreground/40`),onClick:()=>u(e.id),"aria-label":e.checked?`Mark incomplete`:`Mark complete`,children:e.checked&&(0,K.jsx)(U,{className:`size-3`,strokeWidth:3})}),e.type===`toggle`&&(0,K.jsx)(`button`,{type:`button`,className:`mt-1 flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted`,onClick:()=>d(e.id),"aria-label":e.collapsed?`Expand`:`Collapse`,children:(0,K.jsx)(ae,{className:s(`size-4 text-muted-foreground transition-transform duration-150`,!e.collapsed&&`rotate-90`)})}),e.type===`callout`&&(0,K.jsx)(`span`,{className:`mt-1 shrink-0 text-base leading-none`,"aria-hidden":!0,children:`💡`}),(0,K.jsx)(`textarea`,{ref:R,value:e.content,onChange:e=>te(e.target.value),onFocus:()=>o(e.id),onKeyDown:ne,placeholder:S.placeholder,rows:1,spellCheck:e.type!==`code`,className:W})]}),E&&(0,K.jsx)(Cp,{query:O,selectedIndex:A,onSelect:H,onHover:j,position:M}),ie&&(0,K.jsx)(Np,{open:I,onOpenChange:L,blockText:e.content,blockType:e.type,pageTitle:i,pageText:a,onApply:t=>c(e.id,t)})]})}function Fp({visible:e,canAiEdit:t,onAdd:n,onMoveUp:r,onMoveDown:i,onDelete:a,onTypeChange:o,onAiEdit:c}){return(0,K.jsxs)(`div`,{"data-hover-reveal":!0,className:s(`absolute -left-12 top-1 flex items-center gap-0.5 opacity-0 transition-opacity max-sm:-left-10`,e&&`opacity-100`),children:[(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`text-muted-foreground`,onClick:n,"aria-label":`Add block below`,children:(0,K.jsx)(ze,{className:`size-3.5`})}),(0,K.jsxs)(lu,{children:[(0,K.jsx)(uu,{asChild:!0,children:(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`text-muted-foreground`,"aria-label":`Block menu`,children:(0,K.jsx)(ve,{className:`size-3.5`})})}),(0,K.jsxs)(mu,{align:`start`,className:`w-48`,children:[(0,K.jsx)(gu,{children:`Block`}),t&&(0,K.jsxs)(hu,{onClick:c,children:[(0,K.jsx)(Ke,{className:`size-4`}),` Edit with AI`]}),(0,K.jsxs)(hu,{onClick:r,children:[(0,K.jsx)(ne,{className:`size-4`}),` Move up`]}),(0,K.jsxs)(hu,{onClick:i,children:[(0,K.jsx)(ee,{className:`size-4`}),` Move down`]}),(0,K.jsxs)(du,{children:[(0,K.jsxs)(fu,{children:[(0,K.jsx)(ue,{className:`size-4`}),` Turn into`]}),(0,K.jsx)(pu,{className:`max-h-64 overflow-y-auto`,children:bp.map(e=>{let t=e.icon;return(0,K.jsxs)(hu,{onClick:()=>o(e.type),children:[(0,K.jsx)(t,{className:`size-4`}),` `,e.label]},e.type)})})]}),(0,K.jsx)(_u,{}),(0,K.jsxs)(hu,{className:`text-destructive focus:text-destructive`,onClick:a,children:[(0,K.jsx)($e,{className:`size-4`}),` Delete`]})]})]})]})}function Ip(e){return e.blocks.filter(e=>e.type!==`ai`&&e.type!==`divider`).map(e=>`${e.type===`heading1`?`# `:e.type===`heading2`?`## `:e.type===`heading3`?`### `:e.type===`bullet`?`- `:e.type===`numbered`?`1. `:e.type===`todo`?e.checked?`[x] `:`[ ] `:e.type===`quote`?`> `:(e.type===`code`||e.type,``)}${e.content}`.trim()).filter(Boolean).join(` +`)}function Lp({page:e}){let t=m(e=>e.updatePage),n=m(e=>e.updateBlock),r=m(e=>e.insertBlock),i=m(e=>e.deleteBlock),a=m(e=>e.changeBlockType),c=m(e=>e.moveBlock),l=m(e=>e.deletePage),u=m(e=>e.duplicatePage),d=m(e=>e.createPage),p=m(e=>e.setBlocks),[h,g]=(0,z.useState)(null),[v,y]=(0,z.useState)(null),b=(0,z.useRef)(new Map),x=(0,z.useRef)(null),S=(0,z.useMemo)(()=>Ip(e),[e]),C=(0,z.useMemo)(()=>{let t=new Map,n=0;for(let r of e.blocks)r.type===`numbered`?(n+=1,t.set(r.id,n)):n=0;return t},[e.blocks]);(0,z.useEffect)(()=>{let e=x.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[e.title]);let T=(0,z.useCallback)(t=>{let n=r(e.id,t,`paragraph`,``);y(n),g(n)},[r,e.id]),E=(0,z.useCallback)(t=>{let n=e.blocks.findIndex(e=>e.id===t);if(n<0)return;let r=e.blocks[n-1];i(e.id,t),r&&(y(r.id),g(r.id))},[i,e.blocks,e.id]),D=(0,z.useCallback)((t,r)=>{let i=e.blocks.find(e=>e.id===t);if(!i)return;let a=Math.max(0,Math.min(4,(i.indent??0)+r));n(e.id,t,{indent:a})},[e.blocks,e.id,n]),O=(0,z.useCallback)((t,n)=>{let r=e.blocks.findIndex(e=>e.id===t);if(r<0||n.length===0)return;let i=n.map(e=>({id:o(`b`),type:e.type,content:e.content,indent:0,checked:e.type!==`todo`&&void 0,showSource:e.type!==`mermaid`&&void 0})),a=[...e.blocks];a.splice(r+1,0,...i),p(e.id,a),y(i[0].id)},[e.blocks,e.id,p]),k=e.cover?_[e.cover]:null;return(0,K.jsxs)(`div`,{className:`mx-auto w-full max-w-3xl px-4 pb-32 pt-4 sm:px-12 sm:pt-8`,children:[k?(0,K.jsxs)(`div`,{className:`group/cover relative -mx-4 mb-2 h-36 overflow-hidden rounded-xl sm:-mx-6 sm:h-44`,children:[(0,K.jsx)(`div`,{className:s(`absolute inset-0`,k.className)}),(0,K.jsx)(`div`,{"data-hover-reveal":!0,className:`absolute bottom-3 right-3 opacity-0 transition-opacity group-hover/cover:opacity-100`,children:(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`secondary`,className:`bg-background/90 shadow-sm backdrop-blur-sm`,onClick:()=>t(e.id,{cover:null}),children:`Remove cover`})})]}):null,(0,K.jsxs)(`div`,{className:`mb-1 flex flex-wrap items-end gap-2`,children:[(0,K.jsxs)(_p,{children:[(0,K.jsx)(vp,{asChild:!0,children:(0,K.jsx)(`button`,{type:`button`,className:`flex size-16 items-center justify-center rounded-xl text-4xl transition-colors hover:bg-muted`,"aria-label":`Change page icon`,children:e.icon})}),(0,K.jsxs)(yp,{align:`start`,className:`w-72`,children:[(0,K.jsx)(`div`,{className:`mb-2 text-xs font-medium text-muted-foreground`,children:`Page icon`}),(0,K.jsx)(`div`,{className:`grid grid-cols-8 gap-1`,children:f.map(n=>(0,K.jsx)(`button`,{type:`button`,className:s(`flex size-8 items-center justify-center rounded-md text-lg transition-colors hover:bg-muted`,e.icon===n&&`bg-muted ring-1 ring-border`),onClick:()=>t(e.id,{icon:n}),children:n},n))})]})]}),(0,K.jsxs)(`div`,{className:`mb-2 flex flex-1 flex-wrap items-center gap-1`,children:[(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,onClick:()=>t(e.id,{favorite:!e.favorite}),children:[(0,K.jsx)(Ye,{className:s(`size-3.5`,e.favorite&&`fill-amber-400 text-amber-500`)}),e.favorite?`Unfavorite`:`Favorite`]}),(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,onClick:()=>{let t=e.blocks[e.blocks.length-1],n=r(e.id,t?.id??null,`ai`,``);y(n)},children:[(0,K.jsx)(Ke,{className:`size-3.5`}),`AI block`]}),(0,K.jsxs)(lu,{children:[(0,K.jsx)(uu,{asChild:!0,children:(0,K.jsxs)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`text-muted-foreground`,children:[(0,K.jsx)(Ce,{className:`size-3.5`}),`Cover`]})}),(0,K.jsxs)(mu,{align:`start`,children:[Object.entries(_).map(([n,r])=>(0,K.jsxs)(hu,{onClick:()=>t(e.id,{cover:n}),children:[(0,K.jsx)(`span`,{className:s(`mr-2 size-4 rounded`,r.className)}),r.label]},n)),e.cover&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(_u,{}),(0,K.jsx)(hu,{onClick:()=>t(e.id,{cover:null}),children:`Remove cover`})]})]})]}),(0,K.jsxs)(lu,{children:[(0,K.jsx)(uu,{asChild:!0,children:(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`ghost`,"aria-label":`Page actions`,className:`text-muted-foreground`,children:(0,K.jsx)(ue,{className:`size-3.5`})})}),(0,K.jsxs)(mu,{align:`start`,children:[(0,K.jsxs)(hu,{onClick:()=>d({parentId:e.id}),children:[(0,K.jsx)(ze,{className:`size-4`}),` Add sub-page`]}),(0,K.jsxs)(hu,{onClick:()=>u(e.id),children:[(0,K.jsx)(ce,{className:`size-4`}),` Duplicate`]}),(0,K.jsx)(_u,{}),(0,K.jsxs)(hu,{className:`text-destructive focus:text-destructive`,onClick:()=>l(e.id),children:[(0,K.jsx)($e,{className:`size-4`}),` Move to trash`]})]})]})]})]}),(0,K.jsx)(`textarea`,{ref:x,value:e.title,onChange:n=>t(e.id,{title:n.target.value}),placeholder:`Untitled`,rows:1,className:`mb-4 w-full resize-none overflow-hidden bg-transparent text-4xl font-bold tracking-tight text-foreground outline-none placeholder:text-muted-foreground/50`,onKeyDown:t=>{if(t.key===`Enter`){t.preventDefault();let n=e.blocks[0];n&&(y(n.id),g(n.id))}}}),(0,K.jsx)(`div`,{className:`relative space-y-0.5 pl-10 sm:pl-12`,children:e.blocks.map((t,r)=>(0,K.jsx)(Pp,{pageId:e.id,block:t,index:r,isFocused:h===t.id,listNumber:C.get(t.id),pageTitle:e.title,pageText:S,onFocus:g,onChange:(t,r)=>n(e.id,t,{content:r}),onTypeChange:(t,n)=>a(e.id,t,n),onToggleCheck:t=>{let r=e.blocks.find(e=>e.id===t);r&&n(e.id,t,{checked:!r.checked})},onToggleCollapse:t=>{let r=e.blocks.find(e=>e.id===t);r&&n(e.id,t,{collapsed:!r.collapsed})},onEnter:T,onBackspaceEmpty:E,onMove:(t,n)=>c(e.id,t,n),onDelete:t=>i(e.id,t),onIndent:D,onPatch:(t,r)=>n(e.id,t,r),onAiInsert:O,focusRequest:v,onFocusHandled:()=>y(null),inputRefs:b},t.id))}),(0,K.jsx)(`button`,{type:`button`,className:`mt-2 ml-10 min-h-16 w-[calc(100%-2.5rem)] cursor-text rounded-md sm:ml-12 sm:w-[calc(100%-3rem)]`,"aria-label":`Add block at end`,onClick:()=>{let t=e.blocks[e.blocks.length-1];if(t&&t.type===`paragraph`&&!t.content)y(t.id),g(t.id);else{let n=r(e.id,t?.id??null,`paragraph`,``);y(n),g(n)}}})]})}var Rp=1,zp=.9,Bp=.8,Vp=.17,Hp=.1,Up=.999,Wp=.9999,Gp=.99,Kp=/[\\\/_+.#"@\[\(\{&]/,qp=/[\\\/_+.#"@\[\(\{&]/g,Jp=/[\s-]/,Yp=/[\s-]/g;function Xp(e,t,n,r,i,a,o){if(a===t.length)return i===e.length?Rp:Gp;var s=`${i},${a}`;if(o[s]!==void 0)return o[s];for(var c=r.charAt(a),l=n.indexOf(c,i),u=0,d,f,p,m;l>=0;)d=Xp(e,t,n,r,l+1,a+1,o),d>u&&(l===i?d*=Rp:Kp.test(e.charAt(l-1))?(d*=Bp,p=e.slice(i,l-1).match(qp),p&&i>0&&(d*=Up**+p.length)):Jp.test(e.charAt(l-1))?(d*=zp,m=e.slice(i,l-1).match(Yp),m&&i>0&&(d*=Up**+m.length)):(d*=Vp,i>0&&(d*=Up**+(l-i))),e.charAt(l)!==t.charAt(a)&&(d*=Wp)),(dd&&(d=f*Hp)),d>u&&(u=d),l=n.indexOf(c,l+1);return o[s]=u,u}function Zp(e){return e.toLowerCase().replace(Yp,` `)}function Qp(e,t,n){return e=n&&n.length>0?`${e+` `+n.join(` `)}`:e,Xp(e,t,Zp(e),Zp(t),0,0,{})}var $p=`[cmdk-group=""]`,em=`[cmdk-group-items=""]`,tm=`[cmdk-group-heading=""]`,nm=`[cmdk-item=""]`,rm=`${nm}:not([aria-disabled="true"])`,im=`cmdk-item-select`,am=`data-value`,om=(e,t,n)=>Qp(e,t,n),sm=z.createContext(void 0),cm=()=>z.useContext(sm),lm=z.createContext(void 0),um=()=>z.useContext(lm),dm=z.createContext(void 0),fm=z.forwardRef((e,t)=>{let n=Em(()=>({search:``,value:e.value??e.defaultValue??``,selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}})),r=Em(()=>new Set),i=Em(()=>new Map),a=Em(()=>new Map),o=Em(()=>new Set),s=wm(e),{label:c,children:l,value:u,onValueChange:d,filter:f,shouldFilter:p,loop:m,disablePointerSelection:h=!1,vimBindings:g=!0,..._}=e,v=Y(),y=Y(),b=Y(),x=z.useRef(null),S=km();Tm(()=>{if(u!==void 0){let e=u.trim();n.current.value=e,C.emit()}},[u]),Tm(()=>{S(6,k)},[]);let C=z.useMemo(()=>({subscribe:e=>(o.current.add(e),()=>o.current.delete(e)),snapshot:()=>n.current,setState:(e,t,r)=>{var i,a,o;if(!Object.is(n.current[e],t)){if(n.current[e]=t,e===`search`)O(),E(),S(1,D);else if(e===`value`){if(document.activeElement.hasAttribute(`cmdk-input`)||document.activeElement.hasAttribute(`cmdk-root`)){let e=document.getElementById(b);e?e.focus():(i=document.getElementById(v))==null||i.focus()}if(S(7,()=>{n.current.selectedItemId=A()?.id,C.emit()}),r||S(5,k),s.current?.value!==void 0){let e=t??``;(o=(a=s.current).onValueChange)==null||o.call(a,e);return}}C.emit()}},emit:()=>{o.current.forEach(e=>e())}}),[]),w=z.useMemo(()=>({value:(e,t,r)=>{t!==a.current.get(e)?.value&&(a.current.set(e,{value:t,keywords:r}),n.current.filtered.items.set(e,T(t,r)),S(2,()=>{E(),C.emit()}))},item:(e,t)=>(r.current.add(e),t&&(i.current.has(t)?i.current.get(t).add(e):i.current.set(t,new Set([e]))),S(3,()=>{O(),E(),n.current.value||D(),C.emit()}),()=>{a.current.delete(e),r.current.delete(e),n.current.filtered.items.delete(e);let t=A();S(4,()=>{O(),t?.getAttribute(`id`)===e&&D(),C.emit()})}),group:e=>(i.current.has(e)||i.current.set(e,new Set),()=>{a.current.delete(e),i.current.delete(e)}),filter:()=>s.current.shouldFilter,label:c||e[`aria-label`],getDisablePointerSelection:()=>s.current.disablePointerSelection,listId:v,inputId:b,labelId:y,listInnerRef:x}),[]);function T(e,t){let r=s.current?.filter??om;return e?r(e,n.current.search,t):0}function E(){if(!n.current.search||s.current.shouldFilter===!1)return;let e=n.current.filtered.items,t=[];n.current.filtered.groups.forEach(n=>{let r=i.current.get(n),a=0;r.forEach(t=>{let n=e.get(t);a=Math.max(n,a)}),t.push([n,a])});let r=x.current;j().sort((t,n)=>{let r=t.getAttribute(`id`),i=n.getAttribute(`id`);return(e.get(i)??0)-(e.get(r)??0)}).forEach(e=>{let t=e.closest(em);t?t.appendChild(e.parentElement===t?e:e.closest(`${em} > *`)):r.appendChild(e.parentElement===r?e:e.closest(`${em} > *`))}),t.sort((e,t)=>t[1]-e[1]).forEach(e=>{let t=x.current?.querySelector(`${$p}[${am}="${encodeURIComponent(e[0])}"]`);t?.parentElement.appendChild(t)})}function D(){let e=j().find(e=>e.getAttribute(`aria-disabled`)!==`true`)?.getAttribute(am);C.setState(`value`,e||void 0)}function O(){if(!n.current.search||s.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let e=0;for(let t of r.current){let r=T(a.current.get(t)?.value??``,a.current.get(t)?.keywords??[]);n.current.filtered.items.set(t,r),r>0&&e++}for(let[e,t]of i.current)for(let r of t)if(n.current.filtered.items.get(r)>0){n.current.filtered.groups.add(e);break}n.current.filtered.count=e}function k(){var e;let t=A();t&&(t.parentElement?.firstChild===t&&((e=t.closest($p)?.querySelector(tm))==null||e.scrollIntoView({block:`nearest`})),t.scrollIntoView({block:`nearest`}))}function A(){return x.current?.querySelector(`${nm}[aria-selected="true"]`)}function j(){return Array.from(x.current?.querySelectorAll(rm)||[])}function M(e){let t=j()[e];t&&C.setState(`value`,t.getAttribute(am))}function N(e){var t;let n=A(),r=j(),i=r.findIndex(e=>e===n),a=r[i+e];(t=s.current)!=null&&t.loop&&(a=i+e<0?r[r.length-1]:i+e===r.length?r[0]:r[i+e]),a&&C.setState(`value`,a.getAttribute(am))}function P(e){let t=A()?.closest($p),n;for(;t&&!n;)t=e>0?Sm(t,$p):Cm(t,$p),n=t?.querySelector(rm);n?C.setState(`value`,n.getAttribute(am)):N(e)}let F=()=>M(j().length-1),I=e=>{e.preventDefault(),e.metaKey?F():e.altKey?P(1):N(1)},L=e=>{e.preventDefault(),e.metaKey?M(0):e.altKey?P(-1):N(-1)};return z.createElement(q.div,{ref:t,tabIndex:-1,..._,"cmdk-root":``,onKeyDown:e=>{var t;(t=_.onKeyDown)==null||t.call(_,e);let n=e.nativeEvent.isComposing||e.keyCode===229;if(!(e.defaultPrevented||n))switch(e.key){case`n`:case`j`:g&&e.ctrlKey&&I(e);break;case`ArrowDown`:I(e);break;case`p`:case`k`:g&&e.ctrlKey&&L(e);break;case`ArrowUp`:L(e);break;case`Home`:e.preventDefault(),M(0);break;case`End`:e.preventDefault(),F();break;case`Enter`:{e.preventDefault();let t=A();if(t){let e=new Event(im);t.dispatchEvent(e)}}}}},z.createElement(`label`,{"cmdk-label":``,htmlFor:w.inputId,id:w.labelId,style:Mm},c),jm(e,e=>z.createElement(lm.Provider,{value:C},z.createElement(sm.Provider,{value:w},e))))}),pm=z.forwardRef((e,t)=>{let n=Y(),r=z.useRef(null),i=z.useContext(dm),a=cm(),o=wm(e),s=o.current?.forceMount??i?.forceMount;Tm(()=>{if(!s)return a.item(n,i?.id)},[s]);let c=Om(n,r,[e.value,e.children,r],e.keywords),l=um(),u=Dm(e=>e.value&&e.value===c.current),d=Dm(e=>s||a.filter()===!1?!0:!e.search||e.filtered.items.get(n)>0);z.useEffect(()=>{let t=r.current;if(!(!t||e.disabled))return t.addEventListener(im,f),()=>t.removeEventListener(im,f)},[d,e.onSelect,e.disabled]);function f(){var e,t;p(),(t=(e=o.current).onSelect)==null||t.call(e,c.current)}function p(){l.setState(`value`,c.current,!0)}if(!d)return null;let{disabled:m,value:h,onSelect:g,forceMount:_,keywords:v,...y}=e;return z.createElement(q.div,{ref:O(r,t),...y,id:n,"cmdk-item":``,role:`option`,"aria-disabled":!!m,"aria-selected":!!u,"data-disabled":!!m,"data-selected":!!u,onPointerMove:m||a.getDisablePointerSelection()?void 0:p,onClick:m?void 0:f},e.children)}),mm=z.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...a}=e,o=Y(),s=z.useRef(null),c=z.useRef(null),l=Y(),u=cm(),d=Dm(e=>i||u.filter()===!1?!0:!e.search||e.filtered.groups.has(o));Tm(()=>u.group(o),[]),Om(o,s,[e.value,e.heading,c]);let f=z.useMemo(()=>({id:o,forceMount:i}),[i]);return z.createElement(q.div,{ref:O(s,t),...a,"cmdk-group":``,role:`presentation`,hidden:!d||void 0},n&&z.createElement(`div`,{ref:c,"cmdk-group-heading":``,"aria-hidden":!0,id:l},n),jm(e,e=>z.createElement(`div`,{"cmdk-group-items":``,role:`group`,"aria-labelledby":n?l:void 0},z.createElement(dm.Provider,{value:f},e))))}),hm=z.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=z.useRef(null),a=Dm(e=>!e.search);return!n&&!a?null:z.createElement(q.div,{ref:O(i,t),...r,"cmdk-separator":``,role:`separator`})}),gm=z.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,a=um(),o=Dm(e=>e.search),s=Dm(e=>e.selectedItemId),c=cm();return z.useEffect(()=>{e.value!=null&&a.setState(`search`,e.value)},[e.value]),z.createElement(q.input,{ref:t,...r,"cmdk-input":``,autoComplete:`off`,autoCorrect:`off`,spellCheck:!1,"aria-autocomplete":`list`,role:`combobox`,"aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":s,id:c.inputId,type:`text`,value:i?e.value:o,onChange:e=>{i||a.setState(`search`,e.target.value),n?.(e.target.value)}})}),_m=z.forwardRef((e,t)=>{let{children:n,label:r=`Suggestions`,...i}=e,a=z.useRef(null),o=z.useRef(null),s=Dm(e=>e.selectedItemId),c=cm();return z.useEffect(()=>{if(o.current&&a.current){let e=o.current,t=a.current,n,r=new ResizeObserver(()=>{n=requestAnimationFrame(()=>{let n=e.offsetHeight;t.style.setProperty(`--cmdk-list-height`,n.toFixed(1)+`px`)})});return r.observe(e),()=>{cancelAnimationFrame(n),r.unobserve(e)}}},[]),z.createElement(q.div,{ref:O(a,t),...i,"cmdk-list":``,role:`listbox`,tabIndex:-1,"aria-activedescendant":s,"aria-label":r,id:c.listId},jm(e,e=>z.createElement(`div`,{ref:O(o,c.listInnerRef),"cmdk-list-sizer":``},e)))}),vm=z.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:a,container:o,...s}=e;return z.createElement(Tu,{open:n,onOpenChange:r},z.createElement(ku,{container:o},z.createElement(ju,{"cmdk-overlay":``,className:i}),z.createElement(Fu,{"aria-label":e.label,"cmdk-dialog":``,className:a},z.createElement(fm,{ref:t,...s}))))}),ym=z.forwardRef((e,t)=>Dm(e=>e.filtered.count===0)?z.createElement(q.div,{ref:t,...e,"cmdk-empty":``,role:`presentation`}):null),bm=z.forwardRef((e,t)=>{let{progress:n,children:r,label:i=`Loading...`,...a}=e;return z.createElement(q.div,{ref:t,...a,"cmdk-loading":``,role:`progressbar`,"aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},jm(e,e=>z.createElement(`div`,{"aria-hidden":!0},e)))}),xm=Object.assign(fm,{List:_m,Item:pm,Input:gm,Group:mm,Separator:hm,Dialog:vm,Empty:ym,Loading:bm});function Sm(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function Cm(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function wm(e){let t=z.useRef(e);return Tm(()=>{t.current=e}),t}var Tm=typeof window>`u`?z.useEffect:z.useLayoutEffect;function Em(e){let t=z.useRef();return t.current===void 0&&(t.current=e()),t}function Dm(e){let t=um(),n=()=>e(t.snapshot());return z.useSyncExternalStore(t.subscribe,n,n)}function Om(e,t,n,r=[]){let i=z.useRef(),a=cm();return Tm(()=>{var o;let s=(()=>{for(let e of n){if(typeof e==`string`)return e.trim();if(typeof e==`object`&&`current`in e)return e.current?e.current.textContent?.trim():i.current}})(),c=r.map(e=>e.trim());a.value(e,s,c),(o=t.current)==null||o.setAttribute(am,s),i.current=s}),i}var km=()=>{let[e,t]=z.useState(),n=Em(()=>new Map);return Tm(()=>{n.current.forEach(e=>e()),n.current=new Map},[e]),(e,r)=>{n.current.set(e,r),t({})}};function Am(e){let t=e.type;return typeof t==`function`?t(e.props):`render`in t?t.render(e.props):e}function jm({asChild:e,children:t},n){return e&&z.isValidElement(t)?z.cloneElement(Am(t),{ref:t.ref},n(t.props.children)):n(t)}var Mm={position:`absolute`,width:`1px`,height:`1px`,padding:`0`,margin:`-1px`,overflow:`hidden`,clip:`rect(0, 0, 0, 0)`,whiteSpace:`nowrap`,borderWidth:`0`},Nm=sd({type:`function`}).client(async({next:e})=>{let{getBearerToken:t}=await y(async()=>{let{getBearerToken:e}=await import(`./client-CwgDvMJw.js`).then(e=>e.n);return{getBearerToken:e}},__vite__mapDeps([24,2,3]));return e({sendContext:{bearerToken:t()??void 0}})}),Pm=$({method:`POST`}).middleware([Nm]).handler(p(`a98064319e8852a83544a57d2b08358536b8e71b7accdbbc3c7a0bc01b34e11a`));function Fm({open:e,onOpenChange:t}){let n=m(e=>e.pages),r=m(e=>e.storageMode),i=m(e=>e.setActivePage),a=m(e=>e.createPage),[o,c]=(0,z.useState)(``),[l,u]=(0,z.useState)([]),[d,f]=(0,z.useState)(!1),[p,h]=(0,z.useState)(!1),[g,_]=(0,z.useState)(`local`);(0,z.useEffect)(()=>{e||(c(``),u([]))},[e]),(0,z.useEffect)(()=>{let n=n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()===`k`&&(n.preventDefault(),t(!e))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]),(0,z.useEffect)(()=>{if(!e)return;let t=o.trim();if(!t){u([]),f(!1);return}let i=!1;f(!0);let a=setTimeout(()=>{(async()=>{try{if(r===`database`){let e=await Pm({data:{query:t,limit:24}});if(i)return;u(e.hits),h(e.trgm),_(`postgres`)}else{let e=Af(n,t,24);if(i)return;u(e),h(!1),_(`local`)}}catch{if(i)return;u(Af(n,t,24)),_(`local`)}finally{i||f(!1)}})()},180);return()=>{i=!0,clearTimeout(a)}},[o,e,r,n]);let v=(0,z.useMemo)(()=>n.filter(e=>!e.archived).slice(0,30),[n]);if(!e)return null;let y=o.trim().length>0;return(0,K.jsxs)(`div`,{className:`fixed inset-0 z-[100]`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 bg-black/40`,onClick:()=>t(!1),"aria-hidden":!0}),(0,K.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Command palette`,"data-testid":`command-palette`,className:`absolute left-1/2 top-[18%] w-[min(560px,calc(100%-2rem))] -translate-x-1/2 overflow-hidden rounded-xl border border-border bg-popover shadow-2xl`,children:(0,K.jsxs)(xm,{className:`flex flex-col`,label:`Search pages`,shouldFilter:!1,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border px-3`,children:[(0,K.jsx)(We,{className:`size-4 shrink-0 text-muted-foreground`}),(0,K.jsx)(xm.Input,{value:o,onValueChange:c,placeholder:r===`database`?`Search pages (Postgres keyword + similarity)…`:`Search pages…`,className:`h-12 w-full bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground`,autoFocus:!0}),d?(0,K.jsx)(ke,{className:`size-4 animate-spin text-muted-foreground`}):(0,K.jsx)(`kbd`,{className:`hidden rounded border border-border px-1.5 py-0.5 text-[10px] text-muted-foreground sm:inline`,children:`ESC`})]}),y&&(0,K.jsx)(`div`,{className:`border-b border-border px-3 py-1.5 text-[11px] text-muted-foreground`,children:g===`postgres`?`Postgres full-text${p?` + pg_trgm similarity`:` + ILIKE fallback`}`:`Local search (sign in to sync for Postgres search)`}),(0,K.jsxs)(xm.List,{className:`max-h-80 overflow-y-auto p-2`,children:[(0,K.jsx)(xm.Group,{heading:`Actions`,className:`[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground`,children:(0,K.jsxs)(xm.Item,{value:`new page create`,onSelect:()=>{a(),t(!1)},className:s(`flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-sm aria-selected:bg-muted`),children:[(0,K.jsx)(ze,{className:`size-4 text-muted-foreground`}),`New page`]})}),(0,K.jsx)(xm.Group,{heading:y?`Results`:`Pages`,className:`mt-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-[11px] [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground`,children:(y?l:v.map(Im)).map(e=>(0,K.jsxs)(xm.Item,{value:`${e.title} ${e.pageId}`,onSelect:()=>{i(e.pageId),window.dispatchEvent(new CustomEvent(`workspace:clear-mount`)),t(!1)},className:`flex cursor-pointer flex-col gap-0.5 rounded-md px-2 py-2 text-sm aria-selected:bg-muted`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-base leading-none`,children:e.icon}),(0,K.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-medium`,children:e.title||`Untitled`}),e.favorite&&(0,K.jsx)(Ye,{className:`size-3.5 fill-amber-400 text-amber-500`}),y&&(0,K.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:e.mode}),(0,K.jsx)(pe,{className:`size-3.5 text-muted-foreground`})]}),y&&e.snippet&&(0,K.jsx)(`p`,{className:`line-clamp-2 pl-7 text-xs text-muted-foreground`,children:e.snippet})]},e.pageId))}),y&&l.length===0&&(0,K.jsx)(`p`,{className:`py-8 text-center text-sm text-muted-foreground`,children:d?`Searching…`:`No pages found`})]})]})})]})}function Im(e){return{pageId:e.id,title:e.title,icon:e.icon,parentId:e.parentId,favorite:e.favorite,snippet:``,score:0,mode:`keyword`}}function Lm(){let e=jd(e=>e.mounts),t=jd(e=>e.selection),n=jd(e=>e.setSelection),r=e.find(e=>e.id===t?.mountId),[i,a]=(0,z.useState)([]),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)([]),[p,m]=(0,z.useState)(``),[h,g]=(0,z.useState)(!1),[_,v]=(0,z.useState)(!1),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)(null),[C,T]=(0,z.useState)(`browse`),E=(0,z.useCallback)(async(e=``)=>{if(r){g(!0),S(null);try{if(r.kind===`server`&&r.serverPath){let t=await Bd({data:{root:r.serverPath,relPath:e}});a(t)}else{let t=await Id(r.id);if(!t)throw Error(`Local folder permission lost — re-link the folder.`);let n=t;if(e)for(let t of e.split(`/`).filter(Boolean))n=await n.getDirectoryHandle(t);let i=await Ld(n,e);a(i.map(t=>({...t,relPath:e?`${e}/${t.name}`:t.name})))}c(e),T(`browse`)}catch(e){S(e instanceof Error?e.message:`Failed to list folder`)}finally{g(!1)}}},[r]),D=(0,z.useCallback)(async e=>{if(r){g(!0),S(null);try{let t=``;if(r.kind===`server`&&r.serverPath)t=(await Vd({data:{root:r.serverPath,relPath:e}})).content;else{let n=await Id(r.id);if(!n)throw Error(`Local folder permission lost — re-link the folder.`);t=await Rd(n,e)}u(t);let i=Of(t,e.split(`/`).pop()||`note`);m(i),f(Df(t.replace(RegExp(`^#\\s+${i}\\s*\\n+`),``))),b(!1),T(`file`),n({mountId:r.id,relPath:e})}catch(e){S(e instanceof Error?e.message:`Failed to read file`)}finally{g(!1)}}},[r,n]);(0,z.useEffect)(()=>{r&&(t?.relPath&&t.relPath.toLowerCase().endsWith(`.md`)?D(t.relPath):E(t?.relPath&&!t.relPath.endsWith(`.md`)?t.relPath:``))},[r?.id]);let O=async()=>{if(!(!r||!t?.relPath)){v(!0),S(null);try{let e=Tf({id:`x`,title:p,icon:`📝`,cover:null,parentId:null,favorite:!1,createdAt:0,updatedAt:0,blocks:d});if(r.kind===`server`&&r.serverPath)await Hd({data:{root:r.serverPath,relPath:t.relPath,content:e}});else{let n=await Id(r.id);if(!n)throw Error(`Local folder permission lost`);await zd(n,t.relPath,e)}u(e),b(!1)}catch(e){S(e instanceof Error?e.message:`Save failed`)}finally{v(!1)}}};if(!r||!t)return(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-2 p-8 text-center text-muted-foreground`,children:[(0,K.jsx)(we,{className:`size-8 opacity-40`}),(0,K.jsx)(`p`,{className:`text-sm`,children:`Select a linked markdown file from the sidebar.`})]});let k=(C===`file`?t.relPath:s).split(`/`).filter(Boolean);return(0,K.jsxs)(`div`,{className:`mx-auto w-full max-w-3xl px-4 pb-32 pt-6 sm:px-12`,children:[(0,K.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[(0,K.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 font-medium text-foreground`,children:[(0,K.jsx)(we,{className:`size-3`}),` Linked · not imported`]}),(0,K.jsx)(`button`,{type:`button`,className:`hover:text-foreground`,onClick:()=>void E(``),children:r.name}),k.map((e,t)=>{let n=k.slice(0,t+1).join(`/`),r=t===k.length-1&&C===`file`;return(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{children:`/`}),r?(0,K.jsx)(`span`,{className:`text-foreground`,children:e}):(0,K.jsx)(`button`,{type:`button`,className:`hover:text-foreground`,onClick:()=>{e.toLowerCase().endsWith(`.md`)?D(n):E(n)},children:e})]},n)})]}),x&&(0,K.jsx)(`div`,{className:`mb-4 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive`,children:x}),h?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 py-12 text-sm text-muted-foreground`,children:[(0,K.jsx)(ke,{className:`size-4 animate-spin`}),` Loading…`]}):C===`browse`?(0,K.jsxs)(`div`,{className:`space-y-1`,children:[s&&(0,K.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted`,onClick:()=>{let e=s.split(`/`).slice(0,-1).join(`/`);E(e)},children:[(0,K.jsx)(he,{className:`size-4 text-muted-foreground`}),`..`]}),i.length===0&&(0,K.jsx)(`p`,{className:`py-8 text-center text-sm text-muted-foreground`,children:`No markdown files here`}),i.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-muted`,onClick:()=>{e.kind===`dir`?E(e.relPath):D(e.relPath)},children:[(0,K.jsx)(`span`,{children:e.kind===`dir`?`📁`:`📝`}),(0,K.jsx)(`span`,{className:`font-medium`,children:e.name})]},e.relPath))]}):(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-center gap-2`,children:[(0,K.jsx)(`input`,{className:`min-w-0 flex-1 bg-transparent text-3xl font-bold tracking-tight outline-none`,value:p,onChange:e=>{m(e.target.value),b(!0)}}),(0,K.jsxs)(w,{type:`button`,size:`sm`,disabled:!y||_,onClick:()=>void O(),children:[_?(0,K.jsx)(ke,{className:`size-3.5 animate-spin`}):(0,K.jsx)(Ue,{className:`size-3.5`}),`Save to disk`]})]}),(0,K.jsxs)(`div`,{className:`relative space-y-0.5 pl-2`,children:[d.map((e,t)=>(0,K.jsxs)(`div`,{className:`rounded-md py-1`,children:[(0,K.jsx)(`textarea`,{className:`w-full resize-y rounded-md border border-transparent bg-transparent px-1 py-1 text-base leading-relaxed outline-none hover:border-border focus:border-border focus:bg-background`,rows:Math.max(1,e.content.split(` +`).length),value:e.content,onChange:t=>{let n=d.map(n=>n.id===e.id?{...n,content:t.target.value}:n);f(n),b(!0)},placeholder:e.type}),(0,K.jsx)(`div`,{className:`px-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:e.type})]},e.id)),(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-2`,onClick:()=>{f([...d,{id:o(`b`),type:`paragraph`,content:``,indent:0}]),b(!0)},children:`Add block`})]}),(0,K.jsxs)(`p`,{className:`mt-8 text-xs text-muted-foreground`,children:[`Edits write back to the linked file. This page is `,(0,K.jsx)(`strong`,{children:`not`}),` stored in your workspace until you Import.`]})]})]})}var Rm=$({method:`GET`}).middleware([Nm]).handler(p(`e3fb77d67dfdadad5d019581d79338a7f7cf2e42797c44110574e289b39fd293`)),zm=$({method:`POST`}).middleware([Nm]).handler(p(`7bd9976b9723bbefb2399d41723684e8ed7d3bfcf4f814066bb422e47b4bb658`)),Bm=null,Vm=!1,Hm=!1,Um=!1,Wm=!1,Gm=null;function Km(){let e=m.getState();return{name:e.name,theme:e.theme,activePageId:e.activePageId,sidebarOpen:e.sidebarOpen,pages:e.pages}}function qm(){Gm?.(),Gm=m.subscribe((e,t)=>{!Um||!Wm||e.name===t.name&&e.theme===t.theme&&e.activePageId===t.activePageId&&e.sidebarOpen===t.sidebarOpen&&e.pages===t.pages||Ym()})}async function Jm(){try{let e=await Rm();return Wm=!1,m.setState({name:e.name,theme:e.theme,activePageId:e.activePageId,sidebarOpen:e.sidebarOpen,pages:e.pages,hydrated:!0,syncStatus:`saved`,storageMode:`database`}),Um=!0,Wm=!0,qm(),e.source}catch{return Um=!1,Wm=!1,Gm?.(),Gm=null,m.setState({storageMode:`local`,syncStatus:`local`,hydrated:!0}),`error`}}function Ym(){!Um||!Wm||(m.setState({syncStatus:`pending`}),Bm&&clearTimeout(Bm),Bm=setTimeout(()=>{Xm()},600))}async function Xm(){if(Um){if(Vm){Hm=!0;return}Vm=!0,m.setState({syncStatus:`saving`});try{await zm({data:Km()}),m.setState({syncStatus:`saved`})}catch{m.setState({syncStatus:`error`})}finally{Vm=!1,Hm&&(Hm=!1,Ym())}}}async function Zm(){if(Bm&&=(clearTimeout(Bm),null),Um)try{await zm({data:Km()}),m.setState({syncStatus:`saved`})}catch{m.setState({syncStatus:`error`})}}function Qm(){Um=!1,Wm=!1,Gm?.(),Gm=null,m.setState({storageMode:`local`,syncStatus:`local`,hydrated:!0})}function $m(){let e=m(e=>e.pages),t=m(e=>e.activePageId),n=m(e=>e.sidebarOpen),r=m(e=>e.theme),i=m(e=>e.hydrated),o=m(e=>e.storageMode),c=m(e=>e.syncStatus),l=m(e=>e.setSidebarOpen),u=m(e=>e.toggleSidebar),d=m(e=>e.setActivePage),f=m(e=>e.setTheme),p=m(e=>e.updatePage),h=m(e=>e.createPage),g=m(e=>e.setHydrated),_=jd(e=>e.selection),v=jd(e=>e.mounts),y=jd(e=>e.setSelection),b=v.find(e=>e.id===_?.mountId),{user:x,isPending:S}=D(),[C,T]=(0,z.useState)(!1),[E,O]=(0,z.useState)(!1),[k,A]=(0,z.useState)(!1),[j,M]=(0,z.useState)(!1);(0,z.useEffect)(()=>{let e=m.persist.onFinishHydration(()=>{x||g(!0)});return m.persist.hasHydrated()&&!x&&g(!0),e},[g,x]),(0,z.useEffect)(()=>{if(S)return;let e=!1;async function t(){x?(A(!0),await Jm(),e||A(!1)):(Qm(),m.persist.hasHydrated()&&g(!0))}return t(),()=>{e=!0}},[x,S,g]),(0,z.useEffect)(()=>{let e=()=>{o===`database`&&Zm()};return window.addEventListener(`pagehide`,e),()=>window.removeEventListener(`pagehide`,e)},[o]),(0,z.useEffect)(()=>{let e=()=>y(null);return window.addEventListener(`workspace:clear-mount`,e),()=>window.removeEventListener(`workspace:clear-mount`,e)},[y]);let N=!!(_&&b),P=N?void 0:e.find(e=>e.id===t&&!e.archived),F=(()=>{if(!P)return[];let t=[],n=P,r=new Map(e.map(e=>[e.id,e]));for(;n;)t.unshift(n),n=n.parentId?r.get(n.parentId):void 0;return t})();return!i||S||k?(0,K.jsx)(`div`,{className:`flex h-dvh items-center justify-center bg-background text-muted-foreground`,children:(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-3`,children:[(0,K.jsx)(`div`,{className:`size-8 animate-pulse rounded-lg bg-muted`}),(0,K.jsx)(`p`,{className:`text-sm`,children:k?`Loading workspace from database…`:`Loading workspace…`})]})}):(0,K.jsx)(pa,{delayDuration:300,children:(0,K.jsxs)(`div`,{className:`flex h-dvh overflow-hidden bg-background text-foreground`,children:[(0,K.jsx)(`div`,{className:s(`hidden h-full shrink-0 transition-[width,opacity] duration-200 md:block`,n?`w-[260px] opacity-100`:`w-0 overflow-hidden opacity-0`),children:n&&(0,K.jsx)(qf,{onOpenSearch:()=>T(!0)})}),E&&(0,K.jsxs)(`div`,{className:`fixed inset-0 z-50 md:hidden`,children:[(0,K.jsx)(`div`,{className:`absolute inset-0 bg-black/40`,onClick:()=>O(!1),"aria-hidden":!0}),(0,K.jsx)(`div`,{className:`absolute inset-y-0 left-0 w-[min(280px,88vw)] shadow-xl`,children:(0,K.jsx)(qf,{mobile:!0,onOpenSearch:()=>{O(!1),T(!0)},onNavigate:()=>O(!1)})})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,K.jsxs)(`header`,{className:`flex h-11 shrink-0 items-center gap-1 border-b border-border px-2 sm:px-3`,children:[(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`md:hidden`,onClick:()=>O(!0),"aria-label":`Open sidebar`,children:(0,K.jsx)(je,{className:`size-4`})}),!n&&(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,className:`hidden md:inline-flex`,onClick:u,"aria-label":`Open sidebar`,children:(0,K.jsx)(Le,{className:`size-4`})}),(0,K.jsxs)(`nav`,{className:`flex min-w-0 flex-1 items-center gap-0.5 overflow-hidden text-sm`,children:[N?(0,K.jsxs)(`span`,{className:`flex items-center gap-1.5 px-1.5 text-muted-foreground`,children:[(0,K.jsx)(we,{className:`size-3.5`}),(0,K.jsxs)(`span`,{className:`truncate font-medium text-foreground`,children:[b?.name,_?.relPath?` / ${_.relPath}`:``]})]}):F.map((e,t)=>(0,K.jsxs)(`span`,{className:`flex min-w-0 items-center gap-0.5`,children:[t>0&&(0,K.jsx)(ae,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,K.jsxs)(`button`,{type:`button`,className:s(`max-w-[140px] truncate rounded px-1.5 py-0.5 transition-colors hover:bg-muted sm:max-w-[200px]`,t===F.length-1?`font-medium text-foreground`:`text-muted-foreground`),onClick:()=>d(e.id),children:[(0,K.jsx)(`span`,{className:`mr-1`,children:e.icon}),e.title||`Untitled`]})]},e.id)),!P&&!N&&(0,K.jsx)(`span`,{className:`px-1.5 text-muted-foreground`,children:`No page selected`})]}),(0,K.jsx)(eh,{mode:o,status:c}),(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>f(r===`dark`?`light`:`dark`),"aria-label":r===`dark`?`Switch to light theme`:`Switch to dark theme`,children:r===`dark`?(0,K.jsx)(Xe,{className:`size-4 text-muted-foreground`}):(0,K.jsx)(Fe,{className:`size-4 text-muted-foreground`})}),(P||N)&&(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,title:`Import / export markdown`,onClick:()=>M(!0),children:(0,K.jsx)(fe,{className:`size-4 text-muted-foreground`})}),P&&(0,K.jsx)(w,{type:`button`,variant:`ghost`,size:`icon-sm`,onClick:()=>p(P.id,{favorite:!P.favorite}),"aria-label":P.favorite?`Unfavorite`:`Favorite`,children:(0,K.jsx)(Ye,{className:s(`size-4`,P.favorite?`fill-amber-400 text-amber-500`:`text-muted-foreground`)})}),(0,K.jsx)(`div`,{className:`ml-1 hidden items-center gap-2 sm:flex`,children:x?(0,K.jsx)(Qu,{}):(0,K.jsx)(w,{type:`button`,size:`sm`,variant:`outline`,asChild:!0,children:(0,K.jsx)(a,{to:`/login`,children:`Sign in to sync`})})})]}),(0,K.jsx)(`main`,{className:`min-h-0 flex-1 overflow-y-auto`,children:N?(0,K.jsx)(Lm,{},`${_.mountId}:${_.relPath}`):P?(0,K.jsx)(Lp,{page:P},P.id):(0,K.jsx)(th,{onCreate:()=>h(),onOpenSidebar:()=>{l(!0),O(!0)}})})]}),(0,K.jsx)(Fm,{open:C,onOpenChange:T}),(0,K.jsx)(zf,{open:j,onOpenChange:M}),(0,K.jsx)(bf,{position:`bottom-right`,theme:r,toastOptions:{className:`border border-border bg-background text-foreground`}})]})})}function eh({mode:e,status:t}){if(e===`local`)return(0,K.jsxs)(`span`,{className:`hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground sm:inline-flex`,title:`Guest mode — data stays in this browser`,children:[(0,K.jsx)(W,{className:`size-3`}),`Local only`]});let n=t===`saving`||t===`pending`?`Saving…`:t===`error`?`Sync error`:`Saved to DB`;return(0,K.jsxs)(`span`,{className:s(`hidden items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] sm:inline-flex`,t===`error`?`text-destructive`:`text-muted-foreground`),title:`Signed in — workspace syncs to Postgres`,children:[t===`saving`||t===`pending`?(0,K.jsx)(ke,{className:`size-3 animate-spin`}):(0,K.jsx)(oe,{className:`size-3`}),n]})}function th({onCreate:e,onOpenSidebar:t}){return(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-4 p-8 text-center`,children:[(0,K.jsx)(`p`,{className:`text-lg font-medium`,children:`No page open`}),(0,K.jsx)(`p`,{className:`max-w-sm text-sm text-muted-foreground`,children:`Create a page, open one from the sidebar, or link a markdown folder without importing.`}),(0,K.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[(0,K.jsx)(w,{type:`button`,onClick:e,children:`New page`}),(0,K.jsx)(w,{type:`button`,variant:`outline`,onClick:t,children:`Open sidebar`})]})]})}function nh(){return(0,K.jsx)($m,{})}export{nh as component}; \ No newline at end of file diff --git a/dist-desktop/assets/sankeyDiagram-HTMAVEWB-oWnBtA7E.js b/dist-desktop/assets/sankeyDiagram-HTMAVEWB-oWnBtA7E.js new file mode 100644 index 0000000..ce4503d --- /dev/null +++ b/dist-desktop/assets/sankeyDiagram-HTMAVEWB-oWnBtA7E.js @@ -0,0 +1,40 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{H as n,J as r,K as i,U as a,a as o,d as s,s as c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as p}from"./ordinal-hYBb2elL.js";function m(e){for(var t=e.length/6|0,n=Array(t),r=0;r=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n=i)&&(n=i)}return n}function _(e,t){let n;if(t===void 0)for(let t of e)t!=null&&(n>t||n===void 0&&t>=t)&&(n=t);else{let r=-1;for(let i of e)(i=t(i,++r,e))!=null&&(n>i||n===void 0&&i>=i)&&(n=i)}return n}function v(e,t){let n=0;if(t===void 0)for(let t of e)(t=+t)&&(n+=t);else{let r=-1;for(let i of e)(i=+t(i,++r,e))&&(n+=i)}return n}function y(e){return e.target.depth}function b(e){return e.depth}function x(e,t){return t-1-e.height}function S(e,t){return e.sourceLinks.length?e.depth:t-1}function C(e){return e.targetLinks.length?e.depth:e.sourceLinks.length?_(e.sourceLinks,y)-1:0}function w(e){return function(){return e}}function T(e,t){return D(e.source,t.source)||e.index-t.index}function E(e,t){return D(e.target,t.target)||e.index-t.index}function D(e,t){return e.y0-t.y0}function O(e){return e.value}function k(e){return e.index}function A(e){return e.nodes}function j(e){return e.links}function M(e,t){let n=e.get(t);if(!n)throw Error(`missing: `+t);return n}function N({nodes:e}){for(let t of e){let e=t.y0,n=e;for(let n of t.sourceLinks)n.y0=e+n.width/2,e+=n.width;for(let e of t.targetLinks)e.y1=n+e.width/2,n+=e.width}}function P(){let e=0,t=0,n=1,r=1,i=24,a=8,o,s=k,c=S,l,u,d=A,f=j,p=6;function m(){let e={nodes:d.apply(null,arguments),links:f.apply(null,arguments)};return h(e),y(e),b(e),x(e),F(e),N(e),e}m.update=function(e){return N(e),e},m.nodeId=function(e){return arguments.length?(s=typeof e==`function`?e:w(e),m):s},m.nodeAlign=function(e){return arguments.length?(c=typeof e==`function`?e:w(e),m):c},m.nodeSort=function(e){return arguments.length?(l=e,m):l},m.nodeWidth=function(e){return arguments.length?(i=+e,m):i},m.nodePadding=function(e){return arguments.length?(a=o=+e,m):a},m.nodes=function(e){return arguments.length?(d=typeof e==`function`?e:w(e),m):d},m.links=function(e){return arguments.length?(f=typeof e==`function`?e:w(e),m):f},m.linkSort=function(e){return arguments.length?(u=e,m):u},m.size=function(i){return arguments.length?(e=t=0,n=+i[0],r=+i[1],m):[n-e,r-t]},m.extent=function(i){return arguments.length?(e=+i[0][0],n=+i[1][0],t=+i[0][1],r=+i[1][1],m):[[e,t],[n,r]]},m.iterations=function(e){return arguments.length?(p=+e,m):p};function h({nodes:e,links:t}){for(let[t,n]of e.entries())n.index=t,n.sourceLinks=[],n.targetLinks=[];let n=new Map(e.map((t,n)=>[s(t,n,e),t]));for(let[e,r]of t.entries()){r.index=e;let{source:t,target:i}=r;typeof t!=`object`&&(t=r.source=M(n,t)),typeof i!=`object`&&(i=r.target=M(n,i)),t.sourceLinks.push(r),i.targetLinks.push(r)}if(u!=null)for(let{sourceLinks:t,targetLinks:n}of e)t.sort(u),n.sort(u)}function y({nodes:e}){for(let t of e)t.value=t.fixedValue===void 0?Math.max(v(t.sourceLinks,O),v(t.targetLinks,O)):t.fixedValue}function b({nodes:e}){let t=e.length,n=new Set(e),r=new Set,i=0;for(;n.size;){for(let e of n){e.depth=i;for(let{target:t}of e.sourceLinks)r.add(t)}if(++i>t)throw Error(`circular link`);n=r,r=new Set}}function x({nodes:e}){let t=e.length,n=new Set(e),r=new Set,i=0;for(;n.size;){for(let e of n){e.height=i;for(let{source:t}of e.targetLinks)r.add(t)}if(++i>t)throw Error(`circular link`);n=r,r=new Set}}function C({nodes:t}){let r=g(t,e=>e.depth)+1,a=(n-e-i)/(r-1),o=Array(r);for(let n of t){let t=Math.max(0,Math.min(r-1,Math.floor(c.call(null,n,r))));n.layer=t,n.x0=e+t*a,n.x1=n.x0+i,o[t]?o[t].push(n):o[t]=[n]}if(l)for(let e of o)e.sort(l);return o}function P(e){let n=_(e,e=>(r-t-(e.length-1)*o)/v(e,O));for(let i of e){let e=t;for(let t of i){t.y0=e,t.y1=e+t.value*n,e=t.y1+o;for(let e of t.sourceLinks)e.width=e.value*n}e=(r-e+o)/(i.length+1);for(let t=0;te.length)-1)),P(n);for(let e=0;e0))continue;let i=(n/r-e.y0)*t;e.y0+=i,e.y1+=i,V(e)}l===void 0&&i.sort(D),R(i,n)}}function L(e,t,n){for(let r=e.length-2;r>=0;--r){let i=e[r];for(let e of i){let n=0,r=0;for(let{target:t,value:i}of e.sourceLinks){let a=i*(t.layer-e.layer);n+=W(e,t)*a,r+=a}if(!(r>0))continue;let i=(n/r-e.y0)*t;e.y0+=i,e.y1+=i,V(e)}l===void 0&&i.sort(D),R(i,n)}}function R(e,n){let i=e.length>>1,a=e[i];B(e,a.y0-o,i-1,n),z(e,a.y1+o,i+1,n),B(e,r,e.length-1,n),z(e,t,0,n)}function z(e,t,n,r){for(;n1e-6&&(i.y0+=a,i.y1+=a),t=i.y1+o}}function B(e,t,n,r){for(;n>=0;--n){let i=e[n],a=(i.y1-t)*r;a>1e-6&&(i.y0-=a,i.y1-=a),t=i.y0-o}}function V({sourceLinks:e,targetLinks:t}){if(u===void 0){for(let{source:{sourceLinks:e}}of t)e.sort(E);for(let{target:{targetLinks:t}}of e)t.sort(T)}}function H(e){if(u===void 0)for(let{sourceLinks:t,targetLinks:n}of e)t.sort(E),n.sort(T)}function U(e,t){let n=e.y0-(e.sourceLinks.length-1)*o/2;for(let{target:r,width:i}of e.sourceLinks){if(r===t)break;n+=i+o}for(let{source:r,width:i}of t.targetLinks){if(r===e)break;n-=i}return n}function W(e,t){let n=t.y0-(t.targetLinks.length-1)*o/2;for(let{source:r,width:i}of t.targetLinks){if(r===e)break;n+=i+o}for(let{target:r,width:i}of e.sourceLinks){if(r===t)break;n-=i}return n}return m}var F=Math.PI,I=2*F,L=1e-6,R=I-L;function z(){this._x0=this._y0=this._x1=this._y1=null,this._=``}function B(){return new z}z.prototype=B.prototype={constructor:z,moveTo:function(e,t){this._+=`M`+(this._x0=this._x1=+e)+`,`+(this._y0=this._y1=+t)},closePath:function(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._+=`Z`)},lineTo:function(e,t){this._+=`L`+(this._x1=+e)+`,`+(this._y1=+t)},quadraticCurveTo:function(e,t,n,r){this._+=`Q`+ +e+`,`+ +t+`,`+(this._x1=+n)+`,`+(this._y1=+r)},bezierCurveTo:function(e,t,n,r,i,a){this._+=`C`+ +e+`,`+ +t+`,`+ +n+`,`+ +r+`,`+(this._x1=+i)+`,`+(this._y1=+a)},arcTo:function(e,t,n,r,i){e=+e,t=+t,n=+n,r=+r,i=+i;var a=this._x1,o=this._y1,s=n-e,c=r-t,l=a-e,u=o-t,d=l*l+u*u;if(i<0)throw Error(`negative radius: `+i);if(this._x1===null)this._+=`M`+(this._x1=e)+`,`+(this._y1=t);else if(d>L)if(!(Math.abs(u*s-c*l)>L)||!i)this._+=`L`+(this._x1=e)+`,`+(this._y1=t);else{var f=n-a,p=r-o,m=s*s+c*c,h=f*f+p*p,g=Math.sqrt(m),_=Math.sqrt(d),v=i*Math.tan((F-Math.acos((m+d-h)/(2*g*_)))/2),y=v/_,b=v/g;Math.abs(y-1)>L&&(this._+=`L`+(e+y*l)+`,`+(t+y*u)),this._+=`A`+i+`,`+i+`,0,0,`+ +(u*f>l*p)+`,`+(this._x1=e+b*s)+`,`+(this._y1=t+b*c)}},arc:function(e,t,n,r,i,a){e=+e,t=+t,n=+n,a=!!a;var o=n*Math.cos(r),s=n*Math.sin(r),c=e+o,l=t+s,u=1^a,d=a?r-i:i-r;if(n<0)throw Error(`negative radius: `+n);this._x1===null?this._+=`M`+c+`,`+l:(Math.abs(this._x1-c)>L||Math.abs(this._y1-l)>L)&&(this._+=`L`+c+`,`+l),n&&(d<0&&(d=d%I+I),d>R?this._+=`A`+n+`,`+n+`,0,1,`+u+`,`+(e-o)+`,`+(t-s)+`A`+n+`,`+n+`,0,1,`+u+`,`+(this._x1=c)+`,`+(this._y1=l):d>L&&(this._+=`A`+n+`,`+n+`,0,`+ +(d>=F)+`,`+u+`,`+(this._x1=e+n*Math.cos(i))+`,`+(this._y1=t+n*Math.sin(i))))},rect:function(e,t,n,r){this._+=`M`+(this._x0=this._x1=+e)+`,`+(this._y0=this._y1=+t)+`h`+ +n+`v`+ +r+`h`+-n+`Z`},toString:function(){return this._}};function V(e){return function(){return e}}function H(e){return e[0]}function U(e){return e[1]}var W=Array.prototype.slice;function G(e){return e.source}function ee(e){return e.target}function te(e){var t=G,n=ee,r=H,i=U,a=null;function o(){var o,s=W.call(arguments),c=t.apply(this,s),l=n.apply(this,s);if(a||=o=B(),e(a,+r.apply(this,(s[0]=c,s)),+i.apply(this,s),+r.apply(this,(s[0]=l,s)),+i.apply(this,s)),o)return a=null,o+``||null}return o.source=function(e){return arguments.length?(t=e,o):t},o.target=function(e){return arguments.length?(n=e,o):n},o.x=function(e){return arguments.length?(r=typeof e==`function`?e:V(+e),o):r},o.y=function(e){return arguments.length?(i=typeof e==`function`?e:V(+e),o):i},o.context=function(e){return arguments.length?(a=e??null,o):a},o}function ne(e,t,n,r,i){e.moveTo(t,n),e.bezierCurveTo(t=(t+r)/2,n,t,i,r,i)}function re(){return te(ne)}function ie(e){return[e.source.x1,e.y0]}function ae(e){return[e.target.x0,e.y1]}function K(){return re().source(ie).target(ae)}var q=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,9],r=[1,10],i=[1,5,10,12],a={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,SANKEY:4,NEWLINE:5,csv:6,opt_eof:7,record:8,csv_tail:9,EOF:10,"field[source]":11,COMMA:12,"field[target]":13,"field[value]":14,field:15,escaped:16,non_escaped:17,DQUOTE:18,ESCAPED_TEXT:19,NON_ESCAPED_TEXT:20,$accept:0,$end:1},terminals_:{2:`error`,4:`SANKEY`,5:`NEWLINE`,10:`EOF`,11:`field[source]`,12:`COMMA`,13:`field[target]`,14:`field[value]`,18:`DQUOTE`,19:`ESCAPED_TEXT`,20:`NON_ESCAPED_TEXT`},productions_:[0,[3,4],[6,2],[9,2],[9,0],[7,1],[7,0],[8,5],[15,1],[15,1],[16,3],[17,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 7:let e=r.findOrCreateNode(a[s-4].trim().replaceAll(`""`,`"`)),t=r.findOrCreateNode(a[s-2].trim().replaceAll(`""`,`"`)),n=parseFloat(a[s].trim());r.addLink(e,t,n);break;case 8:case 9:case 11:this.$=a[s];break;case 10:this.$=a[s-1];break}},`anonymous`),table:[{3:1,4:[1,2]},{1:[3]},{5:[1,3]},{6:4,8:5,15:6,16:7,17:8,18:n,20:r},{1:[2,6],7:11,10:[1,12]},t(r,[2,4],{9:13,5:[1,14]}),{12:[1,15]},t(i,[2,8]),t(i,[2,9]),{19:[1,16]},t(i,[2,11]),{1:[2,1]},{1:[2,5]},t(r,[2,2]),{6:17,8:5,15:6,16:7,17:8,18:n,20:r},{15:18,16:7,17:8,18:n,20:r},{18:[1,19]},t(r,[2,3]),{12:[1,20]},t(i,[2,10]),{15:21,16:7,17:8,18:n,20:r},t([1,5,10],[2,7])],defaultActions:{11:[2,1],12:[2,5]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};a.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:return this.pushState(`csv`),4;case 1:return this.pushState(`csv`),4;case 2:return 10;case 3:return 5;case 4:return 12;case 5:return this.pushState(`escaped_text`),18;case 6:return 20;case 7:return this.popState(`escaped_text`),18;case 8:return 19}},`anonymous`),rules:[/^(?:sankey-beta\b)/i,/^(?:sankey\b)/i,/^(?:$)/i,/^(?:((\u000D\u000A)|(\u000A)))/i,/^(?:(\u002C))/i,/^(?:(\u0022))/i,/^(?:([\u0020-\u0021\u0023-\u002B\u002D-\u007E])*)/i,/^(?:(\u0022)(?!(\u0022)))/i,/^(?:(([\u0020-\u0021\u0023-\u002B\u002D-\u007E])|(\u002C)|(\u000D)|(\u000A)|(\u0022)(\u0022))*)/i],conditions:{csv:{rules:[2,3,4,5,6,7,8],inclusive:!1},escaped_text:{rules:[7,8],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8],inclusive:!0}}}})();function o(){this.yy={}}return e(o,`Parser`),o.prototype=a,a.Parser=o,new o})();q.parser=q;var J=q,Y=[],X=[],Z=new Map,oe=e(()=>{Y=[],X=[],Z=new Map,o()},`clear`),se=class{constructor(e,t,n=0){this.source=e,this.target=t,this.value=n}static{e(this,`SankeyLink`)}},ce=e((e,t,n)=>{Y.push(new se(e,t,n))},`addLink`),le=class{constructor(e){this.ID=e}static{e(this,`SankeyNode`)}},ue={nodesMap:Z,getConfig:e(()=>d().sankey,`getConfig`),getNodes:e(()=>X,`getNodes`),getLinks:e(()=>Y,`getLinks`),getGraph:e(()=>({nodes:X.map(e=>({id:e.ID})),links:Y.map(e=>({source:e.source.ID,target:e.target.ID,value:e.value}))}),`getGraph`),addLink:ce,findOrCreateNode:e(e=>{e=c.sanitizeText(e,d());let t=Z.get(e);return t===void 0&&(t=new le(e),Z.set(e,t),X.push(t)),t},`findOrCreateNode`),getAccTitle:f,setAccTitle:a,getAccDescription:l,setAccDescription:n,getDiagramTitle:u,setDiagramTitle:i,clear:oe},Q=class t{static{e(this,`Uid`)}static{this.count=0}static next(e){return new t(e+ ++t.count)}constructor(e){this.id=e,this.href=`#${e}`}toString(){return`url(`+this.href+`)`}},$={left:b,right:x,center:C,justify:S},de=e(e=>{let t=0,n=0;for(let r of e){let e=r.value??0;e>t&&(t=e,n=r.layer??0)}return n},`findCentralNodeLayer`),fe={draw:e(function(n,i,a,o){let{securityLevel:c,sankey:l}=d(),u=s.sankey,f;c===`sandbox`&&(f=t(`#i`+i));let m=t(c===`sandbox`?f.nodes()[0].contentDocument.body:`body`),g=c===`sandbox`?m.select(`[id="${i}"]`):t(`[id="${i}"]`),_=l?.width??u.width,v=l?.height??u.width,y=l?.useMaxWidth??u.useMaxWidth,b=l?.nodeAlignment??u.nodeAlignment,x=l?.prefix??u.prefix,S=l?.suffix??u.suffix,C=l?.showValues??u.showValues,w=l?.nodeWidth??u.nodeWidth??10,T=l?.nodePadding??u.nodePadding??12,E=l?.labelStyle??u.labelStyle??`legacy`,D=l?.nodeColors??{},O=o.db.getGraph(),k=$[b];P().nodeId(e=>e.id).nodeWidth(w).nodePadding(T+(C?15:0)).nodeAlign(k).extent([[0,0],[_,v]])(O);let A=de(O.nodes),j=p(h),M=e(e=>D[e]??j(e),`getNodeColor`);g.append(`g`).attr(`class`,`nodes`).selectAll(`.node`).data(O.nodes).join(`g`).attr(`class`,`node`).attr(`id`,e=>(e.uid=Q.next(`node-`)).id).attr(`transform`,function(e){return`translate(`+e.x0+`,`+e.y0+`)`}).attr(`x`,e=>e.x0).attr(`y`,e=>e.y0).append(`rect`).attr(`height`,e=>e.y1-e.y0).attr(`width`,e=>e.x1-e.x0).attr(`fill`,e=>M(e.id));let N=e(({id:e,value:t})=>C?`${e} +${x}${Math.round(t*100)/100}${S}`:e,`getText`),F=e(e=>E===`outlined`?(e.layer??0)I.selectAll(e?`.${e}`:`text`).data(O.nodes).join(`text`).attr(`class`,e??null).attr(`x`,e=>F(e).x).attr(`y`,e=>(e.y1+e.y0)/2).attr(`dy`,`${C?`0`:`0.35`}em`).attr(`text-anchor`,e=>F(e).anchor).text(N),`appendLabel`);E===`outlined`?(L(`sankey-label-bg`),L(`sankey-label-fg`)):L();let R=g.append(`g`).attr(`class`,`links`).attr(`fill`,`none`).attr(`stroke-opacity`,.5).selectAll(`.link`).data(O.links).join(`g`).attr(`class`,`link`).style(`mix-blend-mode`,`multiply`),z=l?.linkColor??`gradient`;if(z===`gradient`){let e=R.append(`linearGradient`).attr(`id`,e=>(e.uid=Q.next(`linearGradient-`)).id).attr(`gradientUnits`,`userSpaceOnUse`).attr(`x1`,e=>e.source.x1).attr(`x2`,e=>e.target.x0);e.append(`stop`).attr(`offset`,`0%`).attr(`stop-color`,e=>M(e.source.id)),e.append(`stop`).attr(`offset`,`100%`).attr(`stop-color`,e=>M(e.target.id))}let B;switch(z){case`gradient`:B=e(e=>e.uid,`coloring`);break;case`source`:B=e(e=>M(e.source.id),`coloring`);break;case`target`:B=e(e=>M(e.target.id),`coloring`);break;default:B=z}R.append(`path`).attr(`d`,K()).attr(`stroke`,B).attr(`stroke-width`,e=>Math.max(1,e.width)),r(void 0,g,0,y)},`draw`)},pe=e(e=>e.replaceAll(/^[^\S\n\r]+|[^\S\n\r]+$/g,``).replaceAll(/([\n\r])+/g,` +`).trim(),`prepareTextForParsing`),me=e(e=>`.label { + font-family: ${e.fontFamily}; + } + + .node-labels { + font-family: ${e.fontFamily}; + } + + /* Outlined label style - background stroke for better readability */ + .sankey-label-bg { + stroke: ${e.mainBkg||e.background||`#fff`}; + stroke-width: 4px; + stroke-linejoin: round; + paint-order: stroke; + } + + /* Foreground label text */ + .sankey-label-fg { + fill: ${e.textColor}; + } + + /* Node styling */ + .node rect { + shape-rendering: crispEdges; + } + + /* Link styling */ + .link { + fill: none; + stroke-opacity: 0.5; + mix-blend-mode: multiply; + } +`,`getStyles`),he=J.parse.bind(J);J.parse=e=>he(pe(e));var ge={styles:me,parser:J,db:ue,renderer:fe};export{ge as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/sequenceDiagram-DBY2YBRQ-CUG55-r_.js b/dist-desktop/assets/sequenceDiagram-DBY2YBRQ-CUG55-r_.js new file mode 100644 index 0000000..0e4ba18 --- /dev/null +++ b/dist-desktop/assets/sequenceDiagram-DBY2YBRQ-CUG55-r_.js @@ -0,0 +1,162 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{A as r,F as i,G as a,H as o,K as s,O as c,U as l,a as u,b as d,c as f,i as p,r as m,s as h,v as g,w as _,x as v,y,z as b}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as x}from"./dist-qx0Iv9vM.js";import{g as S,p as C}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{a as w,c as T,i as E,n as D,r as O,s as k}from"./chunk-32BRIVSS-DWU3ezKg.js";import{t as A}from"./chunk-2Q5K7J3B-C1jixKkw.js";import{n as j,t as M}from"./chunk-ZIRB5QZD-C6fEPe3t.js";var N=x(),P=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,2],r=[1,3],i=[1,4],a=[2,4],o=[1,9],s=[1,11],c=[1,12],l=[1,14],u=[1,15],d=[1,17],f=[1,18],p=[1,19],m=[1,25],h=[1,26],g=[1,27],_=[1,28],v=[1,29],y=[1,30],b=[1,31],x=[1,32],S=[1,33],C=[1,34],w=[1,35],T=[1,36],E=[1,37],D=[1,38],O=[1,39],k=[1,40],A=[1,42],j=[1,43],M=[1,44],N=[1,45],P=[1,46],F=[1,47],I=[1,4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,48,49,50,51,53,54,56,61,62,63,64,73],ee=[1,74],L=[1,80],R=[1,81],te=[1,82],ne=[1,83],z=[1,84],B=[1,85],V=[1,86],re=[1,87],H=[1,88],U=[1,89],W=[1,90],ie=[1,91],ae=[1,92],oe=[1,93],G=[1,94],se=[1,95],K=[1,96],ce=[1,97],le=[1,98],ue=[1,99],de=[1,100],fe=[1,101],pe=[1,102],me=[1,103],he=[1,104],ge=[1,105],_e=[2,78],ve=[4,5,17,51,53,54],ye=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,51,53,54,56,61,62,63,64,73],be=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,50,51,53,54,56,61,62,63,64,73],xe=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,49,51,53,54,56,61,62,63,64,73],Se=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,48,51,53,54,56,61,62,63,64,73],Ce=[5,52],q=[70,71,72,73],J=[1,151],we={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,SPACE:4,NEWLINE:5,SD:6,document:7,line:8,statement:9,INVALID:10,box_section:11,box_line:12,participant_statement:13,create:14,box:15,restOfLine:16,end:17,signal:18,autonumber:19,NUM:20,off:21,activate:22,actor:23,deactivate:24,note_statement:25,links_statement:26,link_statement:27,properties_statement:28,details_statement:29,title:30,legacy_title:31,acc_title:32,acc_title_value:33,acc_descr:34,acc_descr_value:35,acc_descr_multiline_value:36,loop:37,rect:38,opt:39,alt:40,else_sections:41,par:42,par_sections:43,par_over:44,critical:45,option_sections:46,break:47,option:48,and:49,else:50,participant:51,AS:52,participant_actor:53,destroy:54,actor_with_config:55,note:56,placement:57,text2:58,over:59,actor_pair:60,links:61,link:62,properties:63,details:64,spaceList:65,",":66,left_of:67,right_of:68,signaltype:69,"+":70,"-":71,"()":72,ACTOR:73,config_object:74,CONFIG_START:75,CONFIG_CONTENT:76,CONFIG_END:77,SOLID_OPEN_ARROW:78,DOTTED_OPEN_ARROW:79,SOLID_ARROW:80,SOLID_ARROW_TOP:81,SOLID_ARROW_BOTTOM:82,STICK_ARROW_TOP:83,STICK_ARROW_BOTTOM:84,SOLID_ARROW_TOP_DOTTED:85,SOLID_ARROW_BOTTOM_DOTTED:86,STICK_ARROW_TOP_DOTTED:87,STICK_ARROW_BOTTOM_DOTTED:88,SOLID_ARROW_TOP_REVERSE:89,SOLID_ARROW_BOTTOM_REVERSE:90,STICK_ARROW_TOP_REVERSE:91,STICK_ARROW_BOTTOM_REVERSE:92,SOLID_ARROW_TOP_REVERSE_DOTTED:93,SOLID_ARROW_BOTTOM_REVERSE_DOTTED:94,STICK_ARROW_TOP_REVERSE_DOTTED:95,STICK_ARROW_BOTTOM_REVERSE_DOTTED:96,BIDIRECTIONAL_SOLID_ARROW:97,DOTTED_ARROW:98,BIDIRECTIONAL_DOTTED_ARROW:99,SOLID_CROSS:100,DOTTED_CROSS:101,SOLID_POINT:102,DOTTED_POINT:103,TXT:104,$accept:0,$end:1},terminals_:{2:`error`,4:`SPACE`,5:`NEWLINE`,6:`SD`,10:`INVALID`,14:`create`,15:`box`,16:`restOfLine`,17:`end`,19:`autonumber`,20:`NUM`,21:`off`,22:`activate`,24:`deactivate`,30:`title`,31:`legacy_title`,32:`acc_title`,33:`acc_title_value`,34:`acc_descr`,35:`acc_descr_value`,36:`acc_descr_multiline_value`,37:`loop`,38:`rect`,39:`opt`,40:`alt`,42:`par`,44:`par_over`,45:`critical`,47:`break`,48:`option`,49:`and`,50:`else`,51:`participant`,52:`AS`,53:`participant_actor`,54:`destroy`,56:`note`,59:`over`,61:`links`,62:`link`,63:`properties`,64:`details`,66:`,`,67:`left_of`,68:`right_of`,70:`+`,71:`-`,72:`()`,73:`ACTOR`,75:`CONFIG_START`,76:`CONFIG_CONTENT`,77:`CONFIG_END`,78:`SOLID_OPEN_ARROW`,79:`DOTTED_OPEN_ARROW`,80:`SOLID_ARROW`,81:`SOLID_ARROW_TOP`,82:`SOLID_ARROW_BOTTOM`,83:`STICK_ARROW_TOP`,84:`STICK_ARROW_BOTTOM`,85:`SOLID_ARROW_TOP_DOTTED`,86:`SOLID_ARROW_BOTTOM_DOTTED`,87:`STICK_ARROW_TOP_DOTTED`,88:`STICK_ARROW_BOTTOM_DOTTED`,89:`SOLID_ARROW_TOP_REVERSE`,90:`SOLID_ARROW_BOTTOM_REVERSE`,91:`STICK_ARROW_TOP_REVERSE`,92:`STICK_ARROW_BOTTOM_REVERSE`,93:`SOLID_ARROW_TOP_REVERSE_DOTTED`,94:`SOLID_ARROW_BOTTOM_REVERSE_DOTTED`,95:`STICK_ARROW_TOP_REVERSE_DOTTED`,96:`STICK_ARROW_BOTTOM_REVERSE_DOTTED`,97:`BIDIRECTIONAL_SOLID_ARROW`,98:`DOTTED_ARROW`,99:`BIDIRECTIONAL_DOTTED_ARROW`,100:`SOLID_CROSS`,101:`DOTTED_CROSS`,102:`SOLID_POINT`,103:`DOTTED_POINT`,104:`TXT`},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[8,1],[11,0],[11,2],[12,2],[12,1],[12,1],[9,1],[9,2],[9,4],[9,2],[9,4],[9,3],[9,3],[9,2],[9,3],[9,3],[9,2],[9,2],[9,2],[9,2],[9,2],[9,1],[9,1],[9,2],[9,2],[9,1],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[46,1],[46,4],[43,1],[43,4],[41,1],[41,4],[13,5],[13,3],[13,5],[13,3],[13,3],[13,5],[13,3],[13,5],[13,3],[25,4],[25,4],[26,3],[27,3],[28,3],[29,3],[65,2],[65,1],[60,3],[60,1],[57,1],[57,1],[18,5],[18,5],[18,5],[18,5],[18,6],[18,4],[55,2],[74,3],[23,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[58,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 3:return r.apply(a[s]),a[s];case 4:case 10:this.$=[];break;case 5:case 11:a[s-1].push(a[s]),this.$=a[s-1];break;case 6:case 7:case 12:case 13:this.$=a[s];break;case 8:case 9:case 14:this.$=[];break;case 16:a[s].type=`createParticipant`,this.$=a[s];break;case 17:a[s-1].unshift({type:`boxStart`,boxData:r.parseBoxData(a[s-2])}),a[s-1].push({type:`boxEnd`,boxText:a[s-2]}),this.$=a[s-1];break;case 19:this.$={type:`sequenceIndex`,sequenceIndex:Number(a[s-2]),sequenceIndexStep:Number(a[s-1]),sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 20:this.$={type:`sequenceIndex`,sequenceIndex:Number(a[s-1]),sequenceIndexStep:1,sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 21:this.$={type:`sequenceIndex`,sequenceVisible:!1,signalType:r.LINETYPE.AUTONUMBER};break;case 22:this.$={type:`sequenceIndex`,sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 23:this.$={type:`activeStart`,signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1].actor};break;case 24:this.$={type:`activeEnd`,signalType:r.LINETYPE.ACTIVE_END,actor:a[s-1].actor};break;case 30:r.setDiagramTitle(a[s].substring(6)),this.$=a[s].substring(6);break;case 31:r.setDiagramTitle(a[s].substring(7)),this.$=a[s].substring(7);break;case 32:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 33:case 34:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 35:a[s-1].unshift({type:`loopStart`,loopText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.LOOP_START}),a[s-1].push({type:`loopEnd`,loopText:a[s-2],signalType:r.LINETYPE.LOOP_END}),this.$=a[s-1];break;case 36:a[s-1].unshift({type:`rectStart`,color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_START}),a[s-1].push({type:`rectEnd`,color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_END}),this.$=a[s-1];break;case 37:a[s-1].unshift({type:`optStart`,optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_START}),a[s-1].push({type:`optEnd`,optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_END}),this.$=a[s-1];break;case 38:a[s-1].unshift({type:`altStart`,altText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.ALT_START}),a[s-1].push({type:`altEnd`,signalType:r.LINETYPE.ALT_END}),this.$=a[s-1];break;case 39:a[s-1].unshift({type:`parStart`,parText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.PAR_START}),a[s-1].push({type:`parEnd`,signalType:r.LINETYPE.PAR_END}),this.$=a[s-1];break;case 40:a[s-1].unshift({type:`parStart`,parText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.PAR_OVER_START}),a[s-1].push({type:`parEnd`,signalType:r.LINETYPE.PAR_END}),this.$=a[s-1];break;case 41:a[s-1].unshift({type:`criticalStart`,criticalText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.CRITICAL_START}),a[s-1].push({type:`criticalEnd`,signalType:r.LINETYPE.CRITICAL_END}),this.$=a[s-1];break;case 42:a[s-1].unshift({type:`breakStart`,breakText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_START}),a[s-1].push({type:`breakEnd`,optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_END}),this.$=a[s-1];break;case 44:this.$=a[s-3].concat([{type:`option`,optionText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.CRITICAL_OPTION},a[s]]);break;case 46:this.$=a[s-3].concat([{type:`and`,parText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.PAR_AND},a[s]]);break;case 48:this.$=a[s-3].concat([{type:`else`,altText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.ALT_ELSE},a[s]]);break;case 49:a[s-3].draw=`participant`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 50:a[s-1].draw=`participant`,a[s-1].type=`addParticipant`,this.$=a[s-1];break;case 51:a[s-3].draw=`actor`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 52:case 57:a[s-1].draw=`actor`,a[s-1].type=`addParticipant`,this.$=a[s-1];break;case 53:a[s-1].type=`destroyParticipant`,this.$=a[s-1];break;case 54:a[s-3].draw=`participant`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 55:a[s-1].draw=`participant`,a[s-1].type=`addParticipant`,this.$=a[s-1];break;case 56:a[s-3].draw=`actor`,a[s-3].type=`addParticipant`,a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 58:this.$=[a[s-1],{type:`addNote`,placement:a[s-2],actor:a[s-1].actor,text:a[s]}];break;case 59:a[s-2]=[].concat(a[s-1],a[s-1]).slice(0,2),a[s-2][0]=a[s-2][0].actor,a[s-2][1]=a[s-2][1].actor,this.$=[a[s-1],{type:`addNote`,placement:r.PLACEMENT.OVER,actor:a[s-2].slice(0,2),text:a[s]}];break;case 60:this.$=[a[s-1],{type:`addLinks`,actor:a[s-1].actor,text:a[s]}];break;case 61:this.$=[a[s-1],{type:`addALink`,actor:a[s-1].actor,text:a[s]}];break;case 62:this.$=[a[s-1],{type:`addProperties`,actor:a[s-1].actor,text:a[s]}];break;case 63:this.$=[a[s-1],{type:`addDetails`,actor:a[s-1].actor,text:a[s]}];break;case 66:this.$=[a[s-2],a[s]];break;case 67:this.$=a[s];break;case 68:this.$=r.PLACEMENT.LEFTOF;break;case 69:this.$=r.PLACEMENT.RIGHTOF;break;case 70:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s],activate:!0},{type:`activeStart`,signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1].actor}];break;case 71:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s]},{type:`activeEnd`,signalType:r.LINETYPE.ACTIVE_END,actor:a[s-4].actor}];break;case 72:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s],activate:!0,centralConnection:r.LINETYPE.CENTRAL_CONNECTION},{type:`centralConnection`,signalType:r.LINETYPE.CENTRAL_CONNECTION,actor:a[s-1].actor}];break;case 73:this.$=[a[s-4],a[s-1],{type:`addMessage`,from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-2],msg:a[s],activate:!1,centralConnection:r.LINETYPE.CENTRAL_CONNECTION_REVERSE},{type:`centralConnectionReverse`,signalType:r.LINETYPE.CENTRAL_CONNECTION_REVERSE,actor:a[s-4].actor}];break;case 74:this.$=[a[s-5],a[s-1],{type:`addMessage`,from:a[s-5].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s],activate:!0,centralConnection:r.LINETYPE.CENTRAL_CONNECTION_DUAL},{type:`centralConnection`,signalType:r.LINETYPE.CENTRAL_CONNECTION,actor:a[s-1].actor},{type:`centralConnectionReverse`,signalType:r.LINETYPE.CENTRAL_CONNECTION_REVERSE,actor:a[s-5].actor}];break;case 75:this.$=[a[s-3],a[s-1],{type:`addMessage`,from:a[s-3].actor,to:a[s-1].actor,signalType:a[s-2],msg:a[s]}];break;case 76:this.$={type:`addParticipant`,actor:a[s-1],config:a[s]};break;case 77:this.$=a[s-1].trim();break;case 78:this.$={type:`addParticipant`,actor:a[s]};break;case 79:this.$=r.LINETYPE.SOLID_OPEN;break;case 80:this.$=r.LINETYPE.DOTTED_OPEN;break;case 81:this.$=r.LINETYPE.SOLID;break;case 82:this.$=r.LINETYPE.SOLID_TOP;break;case 83:this.$=r.LINETYPE.SOLID_BOTTOM;break;case 84:this.$=r.LINETYPE.STICK_TOP;break;case 85:this.$=r.LINETYPE.STICK_BOTTOM;break;case 86:this.$=r.LINETYPE.SOLID_TOP_DOTTED;break;case 87:this.$=r.LINETYPE.SOLID_BOTTOM_DOTTED;break;case 88:this.$=r.LINETYPE.STICK_TOP_DOTTED;break;case 89:this.$=r.LINETYPE.STICK_BOTTOM_DOTTED;break;case 90:this.$=r.LINETYPE.SOLID_ARROW_TOP_REVERSE;break;case 91:this.$=r.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE;break;case 92:this.$=r.LINETYPE.STICK_ARROW_TOP_REVERSE;break;case 93:this.$=r.LINETYPE.STICK_ARROW_BOTTOM_REVERSE;break;case 94:this.$=r.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED;break;case 95:this.$=r.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED;break;case 96:this.$=r.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED;break;case 97:this.$=r.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED;break;case 98:this.$=r.LINETYPE.BIDIRECTIONAL_SOLID;break;case 99:this.$=r.LINETYPE.DOTTED;break;case 100:this.$=r.LINETYPE.BIDIRECTIONAL_DOTTED;break;case 101:this.$=r.LINETYPE.SOLID_CROSS;break;case 102:this.$=r.LINETYPE.DOTTED_CROSS;break;case 103:this.$=r.LINETYPE.SOLID_POINT;break;case 104:this.$=r.LINETYPE.DOTTED_POINT;break;case 105:this.$=r.parseMessage(a[s].trim().substring(1));break}},`anonymous`),table:[{3:1,4:n,5:r,6:i},{1:[3]},{3:5,4:n,5:r,6:i},{3:6,4:n,5:r,6:i},t([1,4,5,10,14,15,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,51,53,54,56,61,62,63,64,73],a,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},t(I,[2,5]),{9:48,13:13,14:l,15:u,18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},t(I,[2,7]),t(I,[2,8]),t(I,[2,9]),t(I,[2,15]),{13:49,51:D,53:O,54:k},{16:[1,50]},{5:[1,51]},{5:[1,54],20:[1,52],21:[1,53]},{23:55,73:F},{23:56,73:F},{5:[1,57]},{5:[1,58]},{5:[1,59]},{5:[1,60]},{5:[1,61]},t(I,[2,30]),t(I,[2,31]),{33:[1,62]},{35:[1,63]},t(I,[2,34]),{16:[1,64]},{16:[1,65]},{16:[1,66]},{16:[1,67]},{16:[1,68]},{16:[1,69]},{16:[1,70]},{16:[1,71]},{23:72,55:73,73:ee},{23:75,55:76,73:ee},{23:77,73:F},{69:78,72:[1,79],78:L,79:R,80:te,81:ne,82:z,83:B,84:V,85:re,86:H,87:U,88:W,89:ie,90:ae,91:oe,92:G,93:se,94:K,95:ce,96:le,97:ue,98:de,99:fe,100:pe,101:me,102:he,103:ge},{57:106,59:[1,107],67:[1,108],68:[1,109]},{23:110,73:F},{23:111,73:F},{23:112,73:F},{23:113,73:F},t([5,66,72,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104],_e),t(I,[2,6]),t(I,[2,16]),t(ve,[2,10],{11:114}),t(I,[2,18]),{5:[1,116],20:[1,115]},{5:[1,117]},t(I,[2,22]),{5:[1,118]},{5:[1,119]},t(I,[2,25]),t(I,[2,26]),t(I,[2,27]),t(I,[2,28]),t(I,[2,29]),t(I,[2,32]),t(I,[2,33]),t(ye,a,{7:120}),t(ye,a,{7:121}),t(ye,a,{7:122}),t(be,a,{41:123,7:124}),t(xe,a,{43:125,7:126}),t(xe,a,{7:126,43:127}),t(Se,a,{46:128,7:129}),t(ye,a,{7:130}),{5:[1,132],52:[1,131]},{5:[1,134],52:[1,133]},t(Ce,_e,{74:135,75:[1,136]}),{5:[1,138],52:[1,137]},{5:[1,140],52:[1,139]},{5:[1,141]},{23:145,70:[1,142],71:[1,143],72:[1,144],73:F},{69:146,78:L,79:R,80:te,81:ne,82:z,83:B,84:V,85:re,86:H,87:U,88:W,89:ie,90:ae,91:oe,92:G,93:se,94:K,95:ce,96:le,97:ue,98:de,99:fe,100:pe,101:me,102:he,103:ge},t(q,[2,79]),t(q,[2,80]),t(q,[2,81]),t(q,[2,82]),t(q,[2,83]),t(q,[2,84]),t(q,[2,85]),t(q,[2,86]),t(q,[2,87]),t(q,[2,88]),t(q,[2,89]),t(q,[2,90]),t(q,[2,91]),t(q,[2,92]),t(q,[2,93]),t(q,[2,94]),t(q,[2,95]),t(q,[2,96]),t(q,[2,97]),t(q,[2,98]),t(q,[2,99]),t(q,[2,100]),t(q,[2,101]),t(q,[2,102]),t(q,[2,103]),t(q,[2,104]),{23:147,73:F},{23:149,60:148,73:F},{73:[2,68]},{73:[2,69]},{58:150,104:J},{58:152,104:J},{58:153,104:J},{58:154,104:J},{4:[1,157],5:[1,159],12:156,13:158,17:[1,155],51:D,53:O,54:k},{5:[1,160]},t(I,[2,20]),t(I,[2,21]),t(I,[2,23]),t(I,[2,24]),{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,161],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,162],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,163],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{17:[1,164]},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[2,47],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,50:[1,165],51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{17:[1,166]},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[2,45],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,49:[1,167],51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{17:[1,168]},{17:[1,169]},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[2,43],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,48:[1,170],51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{4:o,5:s,8:8,9:10,10:c,13:13,14:l,15:u,17:[1,171],18:16,19:d,22:f,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:h,32:g,34:_,36:v,37:y,38:b,39:x,40:S,42:C,44:w,45:T,47:E,51:D,53:O,54:k,56:A,61:j,62:M,63:N,64:P,73:F},{16:[1,172]},t(I,[2,50]),{16:[1,173]},t(I,[2,55]),t(Ce,[2,76]),{76:[1,174]},{16:[1,175]},t(I,[2,52]),{16:[1,176]},t(I,[2,57]),t(I,[2,53]),{23:177,73:F},{23:178,73:F},{23:179,73:F},{58:180,104:J},{23:181,72:[1,182],73:F},{58:183,104:J},{58:184,104:J},{66:[1,185],104:[2,67]},{5:[2,60]},{5:[2,105]},{5:[2,61]},{5:[2,62]},{5:[2,63]},t(I,[2,17]),t(ve,[2,11]),{13:186,51:D,53:O,54:k},t(ve,[2,13]),t(ve,[2,14]),t(I,[2,19]),t(I,[2,35]),t(I,[2,36]),t(I,[2,37]),t(I,[2,38]),{16:[1,187]},t(I,[2,39]),{16:[1,188]},t(I,[2,40]),t(I,[2,41]),{16:[1,189]},t(I,[2,42]),{5:[1,190]},{5:[1,191]},{77:[1,192]},{5:[1,193]},{5:[1,194]},{58:195,104:J},{58:196,104:J},{58:197,104:J},{5:[2,75]},{58:198,104:J},{23:199,73:F},{5:[2,58]},{5:[2,59]},{23:200,73:F},t(ve,[2,12]),t(be,a,{7:124,41:201}),t(xe,a,{7:126,43:202}),t(Se,a,{7:129,46:203}),t(I,[2,49]),t(I,[2,54]),t(Ce,[2,77]),t(I,[2,51]),t(I,[2,56]),{5:[2,70]},{5:[2,71]},{5:[2,72]},{5:[2,73]},{58:204,104:J},{104:[2,66]},{17:[2,48]},{17:[2,46]},{17:[2,44]},{5:[2,74]}],defaultActions:{5:[2,1],6:[2,2],108:[2,68],109:[2,69],150:[2,60],151:[2,105],152:[2,61],153:[2,62],154:[2,63],180:[2,75],183:[2,58],184:[2,59],195:[2,70],196:[2,71],197:[2,72],198:[2,73],200:[2,66],201:[2,48],202:[2,46],203:[2,44],204:[2,74]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};we.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:return 5;case 1:break;case 2:break;case 3:break;case 4:break;case 5:break;case 6:return 20;case 7:return this.begin(`CONFIG`),75;case 8:return 76;case 9:return this.popState(),this.begin(`ALIAS`),77;case 10:return this.popState(),this.popState(),77;case 11:return t.yytext=t.yytext.trim(),73;case 12:return t.yytext=t.yytext.trim(),this.begin(`ALIAS`),73;case 13:return t.yytext=t.yytext.trim(),this.popState(),73;case 14:return this.popState(),10;case 15:return t.yytext=t.yytext.trim(),this.popState(),10;case 16:return this.begin(`LINE`),15;case 17:return this.begin(`ID`),51;case 18:return this.begin(`ID`),53;case 19:return 14;case 20:return this.begin(`ID`),54;case 21:return this.popState(),this.popState(),this.begin(`LINE`),52;case 22:return this.popState(),this.popState(),5;case 23:return this.begin(`LINE`),37;case 24:return this.begin(`LINE`),38;case 25:return this.begin(`LINE`),39;case 26:return this.begin(`LINE`),40;case 27:return this.begin(`LINE`),50;case 28:return this.begin(`LINE`),42;case 29:return this.begin(`LINE`),44;case 30:return this.begin(`LINE`),49;case 31:return this.begin(`LINE`),45;case 32:return this.begin(`LINE`),48;case 33:return this.begin(`LINE`),47;case 34:return this.popState(),16;case 35:return 17;case 36:return 67;case 37:return 68;case 38:return 61;case 39:return 62;case 40:return 63;case 41:return 64;case 42:return 59;case 43:return 56;case 44:return this.begin(`ID`),22;case 45:return this.begin(`ID`),24;case 46:return 30;case 47:return 31;case 48:return this.begin(`acc_title`),32;case 49:return this.popState(),`acc_title_value`;case 50:return this.begin(`acc_descr`),34;case 51:return this.popState(),`acc_descr_value`;case 52:this.begin(`acc_descr_multiline`);break;case 53:this.popState();break;case 54:return`acc_descr_multiline_value`;case 55:return 6;case 56:return 19;case 57:return 21;case 58:return 66;case 59:return 5;case 60:return t.yytext=t.yytext.trim(),73;case 61:return 80;case 62:return 97;case 63:return 98;case 64:return 99;case 65:return 78;case 66:return 79;case 67:return 100;case 68:return 101;case 69:return 102;case 70:return 103;case 71:return 85;case 72:return 86;case 73:return 87;case 74:return 88;case 75:return 93;case 76:return 94;case 77:return 95;case 78:return 96;case 79:return 81;case 80:return 82;case 81:return 83;case 82:return 84;case 83:return 89;case 84:return 90;case 85:return 91;case 86:return 92;case 87:return 104;case 88:return 104;case 89:return 70;case 90:return 71;case 91:return 72;case 92:return 5;case 93:return 10}},`anonymous`),rules:[/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:([0-9]+(\.[0-9]{1,2})?|\.[0-9]{1,2})(?=[ \n]+))/i,/^(?:@\{)/i,/^(?:[^\}]+)/i,/^(?:\}(?=\s+as\s))/i,/^(?:\})/i,/^(?:[^\<->\->:\n,;@\s]+(?=@\{))/i,/^(?:[^<>:\n,;@\s]+(?=\s+as\s))/i,/^(?:[^<>:\n,;@]+(?=\s*[\n;#]|$))/i,/^(?:[^<>:\n,;@]*<[^\n]*)/i,/^(?:[^\n]+)/i,/^(?:box\b)/i,/^(?:participant\b)/i,/^(?:actor\b)/i,/^(?:create\b)/i,/^(?:destroy\b)/i,/^(?:as\b)/i,/^(?:(?:))/i,/^(?:loop\b)/i,/^(?:rect\b)/i,/^(?:opt\b)/i,/^(?:alt\b)/i,/^(?:else\b)/i,/^(?:par\b)/i,/^(?:par_over\b)/i,/^(?:and\b)/i,/^(?:critical\b)/i,/^(?:option\b)/i,/^(?:break\b)/i,/^(?:(?:[:]?(?:no)?wrap)?[^#\n;]*)/i,/^(?:end\b)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:links\b)/i,/^(?:link\b)/i,/^(?:properties\b)/i,/^(?:details\b)/i,/^(?:over\b)/i,/^(?:note\b)/i,/^(?:activate\b)/i,/^(?:deactivate\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:title:\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:sequenceDiagram\b)/i,/^(?:autonumber\b)/i,/^(?:off\b)/i,/^(?:,)/i,/^(?:;)/i,/^(?:[^\/\\\+\()\+<\->\->:\n,;]+((?!(-x|--x|-\)|--\)|-\|\\|-\\|-\/|-\/\/|-\|\/|\/\|-|\\\|-|\/\/-|\\\\-|\/\|-|--\|\\|--|\(\)))[\-]*[^\+<\->\->:\n,;]+)*)/i,/^(?:->>)/i,/^(?:<<->>)/i,/^(?:-->>)/i,/^(?:<<-->>)/i,/^(?:->)/i,/^(?:-->)/i,/^(?:-[x])/i,/^(?:--[x])/i,/^(?:-[\)])/i,/^(?:--[\)])/i,/^(?:--\|\\)/i,/^(?:--\|\/)/i,/^(?:--\\\\)/i,/^(?:--\/\/)/i,/^(?:\/\|--)/i,/^(?:\\\|--)/i,/^(?:\/\/--)/i,/^(?:\\\\--)/i,/^(?:-\|\\)/i,/^(?:-\|\/)/i,/^(?:-\\\\)/i,/^(?:-\/\/)/i,/^(?:\/\|-)/i,/^(?:\\\|-)/i,/^(?:\/\/-)/i,/^(?:\\\\-)/i,/^(?::(?:(?:no)?wrap)?[^#\n;]*)/i,/^(?::)/i,/^(?:\+)/i,/^(?:-)/i,/^(?:\(\))/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[53,54],inclusive:!1},acc_descr:{rules:[51],inclusive:!1},acc_title:{rules:[49],inclusive:!1},ID:{rules:[2,3,7,11,12,13,14,15],inclusive:!1},ALIAS:{rules:[2,3,21,22],inclusive:!1},LINE:{rules:[2,3,34],inclusive:!1},CONFIG:{rules:[8,9,10],inclusive:!1},CONFIG_DATA:{rules:[],inclusive:!1},INITIAL:{rules:[0,1,3,4,5,6,16,17,18,19,20,23,24,25,26,27,28,29,30,31,32,33,35,36,37,38,39,40,41,42,43,44,45,46,47,48,50,52,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93],inclusive:!0}}}})();function Te(){this.yy={}}return e(Te,`Parser`),Te.prototype=we,we.Parser=Te,new Te})();P.parser=P;var F=P,I={SOLID:0,DOTTED:1,NOTE:2,SOLID_CROSS:3,DOTTED_CROSS:4,SOLID_OPEN:5,DOTTED_OPEN:6,LOOP_START:10,LOOP_END:11,ALT_START:12,ALT_ELSE:13,ALT_END:14,OPT_START:15,OPT_END:16,ACTIVE_START:17,ACTIVE_END:18,PAR_START:19,PAR_AND:20,PAR_END:21,RECT_START:22,RECT_END:23,SOLID_POINT:24,DOTTED_POINT:25,AUTONUMBER:26,CRITICAL_START:27,CRITICAL_OPTION:28,CRITICAL_END:29,BREAK_START:30,BREAK_END:31,PAR_OVER_START:32,BIDIRECTIONAL_SOLID:33,BIDIRECTIONAL_DOTTED:34,SOLID_TOP:41,SOLID_BOTTOM:42,STICK_TOP:43,STICK_BOTTOM:44,SOLID_ARROW_TOP_REVERSE:45,SOLID_ARROW_BOTTOM_REVERSE:46,STICK_ARROW_TOP_REVERSE:47,STICK_ARROW_BOTTOM_REVERSE:48,SOLID_TOP_DOTTED:51,SOLID_BOTTOM_DOTTED:52,STICK_TOP_DOTTED:53,STICK_BOTTOM_DOTTED:54,SOLID_ARROW_TOP_REVERSE_DOTTED:55,SOLID_ARROW_BOTTOM_REVERSE_DOTTED:56,STICK_ARROW_TOP_REVERSE_DOTTED:57,STICK_ARROW_BOTTOM_REVERSE_DOTTED:58,CENTRAL_CONNECTION:59,CENTRAL_CONNECTION_REVERSE:60,CENTRAL_CONNECTION_DUAL:61},ee={FILLED:0,OPEN:1},L={LEFTOF:0,RIGHTOF:1,OVER:2},R={ACTOR:`actor`,BOUNDARY:`boundary`,COLLECTIONS:`collections`,CONTROL:`control`,DATABASE:`database`,ENTITY:`entity`,PARTICIPANT:`participant`,QUEUE:`queue`},te=class{constructor(){this.state=new A(()=>({prevActor:void 0,actors:new Map,createdActors:new Map,destroyedActors:new Map,boxes:[],messages:[],notes:[],sequenceNumbersEnabled:!1,wrapEnabled:void 0,currentBox:void 0,lastCreated:void 0,lastDestroyed:void 0})),this.setAccTitle=l,this.setAccDescription=o,this.setDiagramTitle=s,this.getAccTitle=y,this.getAccDescription=g,this.getDiagramTitle=_,this.apply=this.apply.bind(this),this.parseBoxData=this.parseBoxData.bind(this),this.parseMessage=this.parseMessage.bind(this),this.clear(),this.setWrap(v().wrap),this.LINETYPE=I,this.ARROWTYPE=ee,this.PLACEMENT=L}static{e(this,`SequenceDB`)}addBox(e){this.state.records.boxes.push({name:e.text,wrap:e.wrap??this.autoWrap(),fill:e.color,actorKeys:[]}),this.state.records.currentBox=this.state.records.boxes.slice(-1)[0]}addActor(e,t,n,r,i){let a=this.state.records.currentBox,o;if(i!==void 0){let e;e=i.includes(` +`)?i+` +`:`{ +`+i+` +}`,o=j(e,{schema:M})}r=o?.type??r,o?.alias&&(!n||n.text===t)&&(n={text:o.alias,wrap:n?.wrap,type:r});let s=this.state.records.actors.get(e);if(s){if(this.state.records.currentBox&&s.box&&this.state.records.currentBox!==s.box)throw Error(`A same participant should only be defined in one Box: ${s.name} can't be in '${s.box.name}' and in '${this.state.records.currentBox.name}' at the same time.`);if(a=s.box?s.box:this.state.records.currentBox,s.box=a,s&&t===s.name&&n==null)return}if(n?.text??(n={text:t,type:r}),(r==null||n.text==null)&&(n={text:t,type:r}),this.state.records.actors.set(e,{box:a,name:t,description:n.text,wrap:n.wrap??this.autoWrap(),prevActor:this.state.records.prevActor,links:{},properties:{},actorCnt:null,rectData:null,type:r??`participant`}),this.state.records.prevActor){let t=this.state.records.actors.get(this.state.records.prevActor);t&&(t.nextActor=e)}this.state.records.currentBox&&this.state.records.currentBox.actorKeys.push(e),this.state.records.prevActor=e}activationCount(e){let t,n=0;if(!e)return 0;for(t=0;t>-`,token:`->>-`,line:`1`,loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:[`'ACTIVE_PARTICIPANT'`]},t}return this.state.records.messages.push({id:this.state.records.messages.length.toString(),from:e,to:t,message:n?.text??``,wrap:n?.wrap??this.autoWrap(),type:r,activate:i,centralConnection:a??0}),!0}hasAtLeastOneBox(){return this.state.records.boxes.length>0}hasAtLeastOneBoxWithTitle(){return this.state.records.boxes.some(e=>e.name)}getMessages(){return this.state.records.messages}getBoxes(){return this.state.records.boxes}getActors(){return this.state.records.actors}getCreatedActors(){return this.state.records.createdActors}getDestroyedActors(){return this.state.records.destroyedActors}getActor(e){return this.state.records.actors.get(e)}getActorKeys(){return[...this.state.records.actors.keys()]}enableSequenceNumbers(){this.state.records.sequenceNumbersEnabled=!0}disableSequenceNumbers(){this.state.records.sequenceNumbersEnabled=!1}showSequenceNumbers(){return this.state.records.sequenceNumbersEnabled}setWrap(e){this.state.records.wrapEnabled=e}extractWrap(e){if(e===void 0)return{};e=e.trim();let t=/^:?wrap:/.exec(e)!==null||/^:?nowrap:/.exec(e)===null&&void 0;return{cleanedText:(t===void 0?e:e.replace(/^:?(?:no)?wrap:/,``)).trim(),wrap:t}}autoWrap(){return this.state.records.wrapEnabled===void 0?v().sequence?.wrap??!1:this.state.records.wrapEnabled}clear(){this.state.reset(),u()}parseMessage(e){let n=e.trim(),{wrap:r,cleanedText:i}=this.extractWrap(n),a={text:i,wrap:r};return t.debug(`parseMessage: ${JSON.stringify(a)}`),a}parseBoxData(e){let t=/^((?:rgba?|hsla?)\s*\(.*\)|\w*)(.*)$/.exec(e),n=t?.[1]?t[1].trim():`transparent`,r=t?.[2]?t[2].trim():void 0;if(window?.CSS)window.CSS.supports(`color`,n)||(n=`transparent`,r=e.trim());else{let t=new Option().style;t.color=n,t.color!==n&&(n=`transparent`,r=e.trim())}let{wrap:i,cleanedText:a}=this.extractWrap(r);return{text:a?b(a,v()):void 0,color:n,wrap:i}}addNote(e,t,n){let r={actor:e,placement:t,message:n.text,wrap:n.wrap??this.autoWrap()},i=[].concat(e,e);this.state.records.notes.push(r),this.state.records.messages.push({id:this.state.records.messages.length.toString(),from:i[0],to:i[1],message:n.text,wrap:n.wrap??this.autoWrap(),type:this.LINETYPE.NOTE,placement:t})}addLinks(e,n){let r=this.getActor(e);try{let e=b(n.text,v());e=e.replace(/=/g,`=`),e=e.replace(/&/g,`&`);let t=JSON.parse(e);this.insertLinks(r,t)}catch(e){t.error(`error while parsing actor link text`,e)}}addALink(e,n){let r=this.getActor(e);try{let e={},t=b(n.text,v()),i=t.indexOf(`@`);t=t.replace(/=/g,`=`),t=t.replace(/&/g,`&`);let a=t.slice(0,i-1).trim();e[a]=t.slice(i+1).trim(),this.insertLinks(r,e)}catch(e){t.error(`error while parsing actor link text`,e)}}insertLinks(e,t){if(e.links==null)e.links=t;else for(let n in t)e.links[n]=t[n]}addProperties(e,n){let r=this.getActor(e);try{let e=b(n.text,v()),t=JSON.parse(e);this.insertProperties(r,t)}catch(e){t.error(`error while parsing actor properties text`,e)}}insertProperties(e,t){if(e.properties==null)e.properties=t;else for(let n in t)e.properties[n]=t[n]}boxEnd(){this.state.records.currentBox=void 0}addDetails(e,n){let r=this.getActor(e),i=document.getElementById(n.text);try{let e=i.innerHTML,t=JSON.parse(e);t.properties&&this.insertProperties(r,t.properties),t.links&&this.insertLinks(r,t.links)}catch(e){t.error(`error while parsing actor details text`,e)}}getActorProperty(e,t){if(e?.properties!==void 0)return e.properties[t]}apply(e){if(Array.isArray(e))e.forEach(e=>{this.apply(e)});else switch(e.type){case`sequenceIndex`:this.state.records.messages.push({id:this.state.records.messages.length.toString(),from:void 0,to:void 0,message:{start:e.sequenceIndex,step:e.sequenceIndexStep,visible:e.sequenceVisible},wrap:!1,type:e.signalType});break;case`addParticipant`:this.addActor(e.actor,e.actor,e.description,e.draw,e.config);break;case`createParticipant`:if(this.state.records.actors.has(e.actor))throw Error(`It is not possible to have actors with the same id, even if one is destroyed before the next is created. Use 'AS' aliases to simulate the behavior`);this.state.records.lastCreated=e.actor,this.addActor(e.actor,e.actor,e.description,e.draw,e.config),this.state.records.createdActors.set(e.actor,this.state.records.messages.length);break;case`destroyParticipant`:this.state.records.lastDestroyed=e.actor,this.state.records.destroyedActors.set(e.actor,this.state.records.messages.length);break;case`activeStart`:this.addSignal(e.actor,void 0,void 0,e.signalType);break;case`centralConnection`:this.addSignal(e.actor,void 0,void 0,e.signalType);break;case`centralConnectionReverse`:this.addSignal(e.actor,void 0,void 0,e.signalType);break;case`activeEnd`:this.addSignal(e.actor,void 0,void 0,e.signalType);break;case`addNote`:this.addNote(e.actor,e.placement,e.text);break;case`addLinks`:this.addLinks(e.actor,e.text);break;case`addALink`:this.addALink(e.actor,e.text);break;case`addProperties`:this.addProperties(e.actor,e.text);break;case`addDetails`:this.addDetails(e.actor,e.text);break;case`addMessage`:if(this.state.records.lastCreated){if(e.to!==this.state.records.lastCreated)throw Error(`The created participant `+this.state.records.lastCreated.name+` does not have an associated creating message after its declaration. Please check the sequence diagram.`);this.state.records.lastCreated=void 0}else if(this.state.records.lastDestroyed){if(e.to!==this.state.records.lastDestroyed&&e.from!==this.state.records.lastDestroyed)throw Error(`The destroyed participant `+this.state.records.lastDestroyed.name+` does not have an associated destroying message after its declaration. Please check the sequence diagram.`);this.state.records.lastDestroyed=void 0}this.addSignal(e.from,e.to,e.msg,e.signalType,e.activate,e.centralConnection);break;case`boxStart`:this.addBox(e.boxData);break;case`boxEnd`:this.boxEnd();break;case`loopStart`:this.addSignal(void 0,void 0,e.loopText,e.signalType);break;case`loopEnd`:this.addSignal(void 0,void 0,void 0,e.signalType);break;case`rectStart`:this.addSignal(void 0,void 0,e.color,e.signalType);break;case`rectEnd`:this.addSignal(void 0,void 0,void 0,e.signalType);break;case`optStart`:this.addSignal(void 0,void 0,e.optText,e.signalType);break;case`optEnd`:this.addSignal(void 0,void 0,void 0,e.signalType);break;case`altStart`:this.addSignal(void 0,void 0,e.altText,e.signalType);break;case`else`:this.addSignal(void 0,void 0,e.altText,e.signalType);break;case`altEnd`:this.addSignal(void 0,void 0,void 0,e.signalType);break;case`setAccTitle`:l(e.text);break;case`parStart`:this.addSignal(void 0,void 0,e.parText,e.signalType);break;case`and`:this.addSignal(void 0,void 0,e.parText,e.signalType);break;case`parEnd`:this.addSignal(void 0,void 0,void 0,e.signalType);break;case`criticalStart`:this.addSignal(void 0,void 0,e.criticalText,e.signalType);break;case`option`:this.addSignal(void 0,void 0,e.optionText,e.signalType);break;case`criticalEnd`:this.addSignal(void 0,void 0,void 0,e.signalType);break;case`breakStart`:this.addSignal(void 0,void 0,e.breakText,e.signalType);break;case`breakEnd`:this.addSignal(void 0,void 0,void 0,e.signalType);break}}getConfig(){return v().sequence}},ne=e(e=>{let t=e.dropShadow??`none`,{look:n}=v();return`.actor { + stroke: ${e.actorBorder}; + fill: ${e.actorBkg}; + stroke-width: ${e.strokeWidth??1}; + } + + rect.actor.outer-path[data-look="neo"] { + filter: ${t}; + } + + rect.note[data-look="neo"] { + stroke:${e.noteBorderColor}; + fill:${e.noteBkgColor}; + filter: ${t}; + } + + text.actor > tspan { + fill: ${e.actorTextColor}; + stroke: none; + } + + .actor-line { + stroke: ${e.actorLineColor}; + } + + .innerArc { + stroke-width: 1.5; + stroke-dasharray: none; + } + + .messageLine0 { + stroke-width: 1.5; + stroke-dasharray: none; + stroke: ${e.signalColor}; + } + + .messageLine1 { + stroke-width: 1.5; + stroke-dasharray: 2, 2; + stroke: ${e.signalColor}; + } + + [id$="-arrowhead"] path { + fill: ${e.signalColor}; + stroke: ${e.signalColor}; + } + + .sequenceNumber { + fill: ${e.sequenceNumberColor}; + } + + [id$="-sequencenumber"] { + fill: ${e.signalColor}; + } + + [id$="-crosshead"] path { + fill: ${e.signalColor}; + stroke: ${e.signalColor}; + } + + .messageText { + fill: ${e.signalTextColor}; + stroke: none; + } + + .labelBox { + stroke: ${e.labelBoxBorderColor}; + fill: ${e.labelBoxBkgColor}; + filter: ${n===`neo`?t:`none`}; + } + + .labelText, .labelText > tspan { + fill: ${e.labelTextColor}; + stroke: none; + } + + .loopText, .loopText > tspan { + fill: ${e.loopTextColor}; + stroke: none; + } + + .sectionTitle, .sectionTitle > tspan { + fill: ${e.loopTextColor}; + stroke: none; + } + + .loopLine { + stroke-width: 2px; + stroke-dasharray: 2, 2; + stroke: ${e.labelBoxBorderColor}; + fill: ${e.labelBoxBorderColor}; + } + + .note { + //stroke: #decc93; + stroke: ${e.noteBorderColor}; + fill: ${e.noteBkgColor}; + } + + .noteText, .noteText > tspan { + fill: ${e.noteTextColor}; + stroke: none; + ${e.noteFontWeight?`font-weight: ${e.noteFontWeight};`:``} + } + + .activation0 { + fill: ${e.activationBkgColor}; + stroke: ${e.activationBorderColor}; + } + + .activation1 { + fill: ${e.activationBkgColor}; + stroke: ${e.activationBorderColor}; + } + + .activation2 { + fill: ${e.activationBkgColor}; + stroke: ${e.activationBorderColor}; + } + + .actorPopupMenu { + position: absolute; + } + + .actorPopupMenuPanel { + position: absolute; + fill: ${e.actorBkg}; + box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); + filter: drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4)); +} + .actor-man circle, line { + fill: ${e.actorBkg}; + stroke-width: 2px; + } + + g rect.rect { + filter: ${t}; + stroke: ${e.nodeBorder}; + } +`},`getStyles`),z=36,B=`actor-top`,V=`actor-bottom`,re=`actor-box`,H=`actor-man`,U=new Set([`redux-color`,`redux-dark-color`]),W=e(function(e,t){let n=w(e,t);return d().look===`neo`&&n.attr(`data-look`,`neo`),n},`drawRect`),ie=e(function(e,t,n,r,i){if(t.links===void 0||t.links===null||Object.keys(t.links).length===0)return{height:0,width:0};let a=t.links,o=t.actorCnt,s=t.rectData;var c=`none`;i&&(c=`block !important`);let l=e.append(`g`);l.attr(`id`,`actor`+o+`_popup`),l.attr(`class`,`actorPopupMenu`),l.attr(`display`,c);var u=``;s.class!==void 0&&(u=` `+s.class);let d=s.width>n?s.width:n,f=l.append(`rect`);if(f.attr(`class`,`actorPopupMenuPanel`+u),f.attr(`x`,s.x),f.attr(`y`,s.height),f.attr(`fill`,s.fill),f.attr(`stroke`,s.stroke),f.attr(`width`,d),f.attr(`height`,s.height),f.attr(`rx`,s.rx),f.attr(`ry`,s.ry),a!=null){var p=20;for(let e in a){var m=l.append(`a`),h=(0,N.sanitizeUrl)(a[e]);m.attr(`xlink:href`,h),m.attr(`target`,`_blank`),je(r)(e,m,s.x+10,s.height+p,d,20,{class:`actor`},r),p+=30}}return f.attr(`height`,p),{height:s.height+p,width:d}},`drawPopup`),ae=e(function(e){return`var pu = document.getElementById('`+e+`'); if (pu != null) { pu.style.display = pu.style.display == 'block' ? 'none' : 'block'; }`},`popupMenuToggle`),oe=e(async function(e,t,n=null){let r=e.append(`foreignObject`),a=await i(t.text,d()),o=r.append(`xhtml:div`).attr(`style`,`width: fit-content;`).attr(`xmlns`,`http://www.w3.org/1999/xhtml`).html(a).node().getBoundingClientRect();if(r.attr(`height`,Math.round(o.height)).attr(`width`,Math.round(o.width)),t.class===`noteText`){let n=e.node().firstChild;n.setAttribute(`height`,o.height+2*t.textMargin);let i=n.getBBox();r.attr(`x`,Math.round(i.x+i.width/2-o.width/2)).attr(`y`,Math.round(i.y+i.height/2-o.height/2))}else if(n){let{startx:e,stopx:i,starty:a}=n;if(e>i){let t=e;e=i,i=t}r.attr(`x`,Math.round(e+Math.abs(e-i)/2-o.width/2)),t.class===`loopText`?r.attr(`y`,Math.round(a)):r.attr(`y`,Math.round(a-o.height))}return[r]},`drawKatex`),G=e(function(t,n){let r=0,i=0,a=n.text.split(h.lineBreakRegex),[o,s]=C(n.fontSize),c=[],l=0,u=e(()=>n.y,`yfunc`);if(n.valign!==void 0&&n.textMargin!==void 0&&n.textMargin>0)switch(n.valign){case`top`:case`start`:u=e(()=>Math.round(n.y+n.textMargin),`yfunc`);break;case`middle`:case`center`:u=e(()=>Math.round(n.y+(r+i+n.textMargin)/2),`yfunc`);break;case`bottom`:case`end`:u=e(()=>Math.round(n.y+(r+i+2*n.textMargin)-n.textMargin),`yfunc`);break}if(n.anchor!==void 0&&n.textMargin!==void 0&&n.width!==void 0)switch(n.anchor){case`left`:case`start`:n.x=Math.round(n.x+n.textMargin),n.anchor=`start`,n.dominantBaseline=`middle`,n.alignmentBaseline=`middle`;break;case`middle`:case`center`:n.x=Math.round(n.x+n.width/2),n.anchor=`middle`,n.dominantBaseline=`middle`,n.alignmentBaseline=`middle`;break;case`right`:case`end`:n.x=Math.round(n.x+n.width-n.textMargin),n.anchor=`end`,n.dominantBaseline=`middle`,n.alignmentBaseline=`middle`;break}for(let[e,d]of a.entries()){n.textMargin!==void 0&&n.textMargin===0&&o!==void 0&&(l=e*o);let a=t.append(`text`);a.attr(`x`,n.x),a.attr(`y`,u()),n.anchor!==void 0&&a.attr(`text-anchor`,n.anchor).attr(`dominant-baseline`,n.dominantBaseline).attr(`alignment-baseline`,n.alignmentBaseline),n.fontFamily!==void 0&&a.style(`font-family`,n.fontFamily),s!==void 0&&a.style(`font-size`,s),n.fontWeight!==void 0&&a.style(`font-weight`,n.fontWeight),n.fill!==void 0&&a.attr(`fill`,n.fill),n.class!==void 0&&a.attr(`class`,n.class),n.dy===void 0?l!==0&&a.attr(`dy`,l):a.attr(`dy`,n.dy);let f=d||`​`;if(n.tspan){let e=a.append(`tspan`);e.attr(`x`,n.x),n.fill!==void 0&&e.attr(`fill`,n.fill),e.text(f)}else a.text(f);n.valign!==void 0&&n.textMargin!==void 0&&n.textMargin>0&&(i+=(a._groups||a)[0][0].getBBox().height,r=i),c.push(a)}return c},`drawText`),se=e(function(t,n){function r(e,t,n,r,i){return e+`,`+t+` `+(e+n)+`,`+t+` `+(e+n)+`,`+(t+r-i)+` `+(e+n-i*1.2)+`,`+(t+r)+` `+e+`,`+(t+r)}e(r,`genPoints`);let i=t.append(`polygon`);return i.attr(`points`,r(n.x,n.y,n.width,n.height,7)),i.attr(`class`,`labelBox`),n.y+=n.height/2,G(t,n),i},`drawLabel`),K=-1,ce=e((e,t,n,r)=>{e.select&&n.forEach(n=>{let i=t.get(n),a=e.select(`#actor`+i.actorCnt);!r.mirrorActors&&i.stopy?a.attr(`y2`,i.stopy+i.height/2):r.mirrorActors&&a.attr(`y2`,i.stopy)})},`fixLifeLineHeights`),le=e(function(e,t,n,i,a){let o=i?t.stopy:t.starty,s=t.x+t.width/2,c=o+t.height,{look:l,theme:u,themeVariables:d}=n,{bkgColorArray:f,borderColorArray:p}=d,m=e.append(`g`).lower();var h=m;i||(K++,Object.keys(t.links||{}).length&&!n.forceMenus&&h.attr(`onclick`,ae(`actor${K}_popup`)).attr(`cursor`,`pointer`),h.append(`line`).attr(`id`,`actor`+K).attr(`x1`,s).attr(`y1`,c).attr(`x2`,s).attr(`y2`,2e3).attr(`class`,`actor-line 200`).attr(`stroke-width`,`0.5px`).attr(`stroke`,`#999`).attr(`name`,t.name).attr(`data-et`,`life-line`).attr(`data-id`,t.name),h=m.append(`g`),t.actorCnt=K,t.links!=null&&h.attr(`id`,`root-`+K),l===`neo`&&h.attr(`data-look`,`neo`));let g=k();var _=`actor`;t.properties?.class?_=t.properties.class:g.fill=`#eaeaea`,i?_+=` ${V}`:_+=` ${B}`,g.x=t.x,g.y=o,g.width=t.width,g.height=t.height,g.class=_,g.rx=3,g.ry=3,g.name=t.name,l===`neo`&&(g.rx=6,g.ry=6);let v=W(h,g),y=a.get(t.name)??0;if(U.has(u)&&(v.style(`stroke`,p[y%p.length]),v.style(`fill`,f[y%p.length])),l===`neo`&&v.attr(`filter`,`url(#drop-shadow)`),t.rectData=g,t.properties?.icon){let e=t.properties.icon.trim();e.charAt(0)===`@`?O(h,g.x+g.width-20,g.y+10,e.substr(1)):E(h,g.x+g.width-20,g.y+10,e)}i||(h.attr(`data-et`,`participant`),h.attr(`data-type`,`participant`),h.attr(`data-id`,t.name)),Y(n,r(t.description))(t.description,h,g.x,g.y,g.width,g.height,{class:`actor ${re}`},n);let b=t.height;if(v.node){let e=v.node().getBBox();t.height=e.height,b=e.height}return b},`drawActorTypeParticipant`),ue=e(function(e,t,n,i,a){let o=i?t.stopy:t.starty,s=t.x+t.width/2,c=o+t.height,{look:l,theme:u,themeVariables:d}=n,{bkgColorArray:f,borderColorArray:p}=d,m=e.append(`g`).lower();var h=m;i||(K++,Object.keys(t.links||{}).length&&!n.forceMenus&&h.attr(`onclick`,ae(`actor${K}_popup`)).attr(`cursor`,`pointer`),h.append(`line`).attr(`id`,`actor`+K).attr(`x1`,s).attr(`y1`,c).attr(`x2`,s).attr(`y2`,2e3).attr(`class`,`actor-line 200`).attr(`stroke-width`,`0.5px`).attr(`stroke`,`#999`).attr(`name`,t.name).attr(`data-et`,`life-line`).attr(`data-id`,t.name),h=m.append(`g`),t.actorCnt=K,t.links!=null&&h.attr(`id`,`root-`+K),l===`neo`&&h.attr(`data-look`,`neo`));let g=k();var _=`actor`;t.properties?.class?_=t.properties.class:g.fill=`#eaeaea`,i?_+=` ${V}`:_+=` ${B}`,g.x=t.x,g.y=o,g.width=t.width,g.height=t.height,g.class=_,g.name=t.name;let v={...g,x:g.x+-6,y:g.y+6,class:`actor`},y=W(h,g),b=W(h,v);t.rectData=g,l===`neo`&&h.attr(`filter`,`url(#drop-shadow)`);let x=a.get(t.name)??0;if(U.has(u)&&(y.style(`stroke`,p[x%p.length]),y.style(`fill`,f[x%p.length]),b.style(`stroke`,p[x%p.length]),b.style(`fill`,f[x%p.length])),t.properties?.icon){let e=t.properties.icon.trim();e.charAt(0)===`@`?O(h,g.x+g.width-20,g.y+10,e.substr(1)):E(h,g.x+g.width-20,g.y+10,e)}Y(n,r(t.description))(t.description,h,g.x-6,g.y+6,g.width,g.height,{class:`actor ${re}`},n);let S=t.height;if(y.node){let e=y.node().getBBox();t.height=e.height,S=e.height}return i||(h.attr(`data-et`,`participant`),h.attr(`data-type`,`collections`),h.attr(`data-id`,t.name)),S},`drawActorTypeCollections`),de=e(function(e,t,n,i,a){let o=i?t.stopy:t.starty,s=t.x+t.width/2,c=o+t.height,{look:l,theme:u,themeVariables:d}=n,{bkgColorArray:f,borderColorArray:p}=d,m=e.append(`g`).lower(),h=m;i||(K++,Object.keys(t.links||{}).length&&!n.forceMenus&&h.attr(`onclick`,ae(`actor${K}_popup`)).attr(`cursor`,`pointer`),h.append(`line`).attr(`id`,`actor`+K).attr(`x1`,s).attr(`y1`,c).attr(`x2`,s).attr(`y2`,2e3).attr(`class`,`actor-line 200`).attr(`stroke-width`,`0.5px`).attr(`stroke`,`#999`).attr(`name`,t.name).attr(`data-et`,`life-line`).attr(`data-id`,t.name),h=m.append(`g`),t.actorCnt=K,t.links!=null&&h.attr(`id`,`root-`+K),l===`neo`&&h.attr(`data-look`,`neo`));let g=k(),_=`actor`;t.properties?.class?_=t.properties.class:g.fill=`#eaeaea`,i?_+=` ${V}`:_+=` ${B}`,h.attr(`class`,_),g.x=t.x,g.y=o,g.width=t.width,g.height=t.height,g.name=t.name;let v=g.height/2,y=v/(2.5+g.height/50),b=h.append(`g`),x=h.append(`g`),S=`M ${g.x},${g.y+v} + a ${y},${v} 0 0 0 0,${g.height} + h ${g.width-2*y} + a ${y},${v} 0 0 0 0,-${g.height} + Z + `;b.append(`path`).attr(`d`,S),x.append(`path`).attr(`d`,`M ${g.x},${g.y+v} + a ${y},${v} 0 0 0 0,${g.height}`),b.attr(`transform`,`translate(${y}, ${-(g.height/2)})`),x.attr(`transform`,`translate(${g.width-y}, ${-g.height/2})`),t.rectData=g,l===`neo`&&b.attr(`filter`,`url(#drop-shadow)`);let C=a.get(t.name)??0;if(U.has(u)&&(b.style(`stroke`,p[C%p.length]),b.style(`fill`,f[C%p.length]),x.style(`stroke`,p[C%p.length]),x.style(`fill`,f[C%p.length])),t.properties?.icon){let e=t.properties.icon.trim(),n=g.x+g.width-20,r=g.y+10;e.charAt(0)===`@`?O(h,n,r,e.substr(1)):E(h,n,r,e)}Y(n,r(t.description))(t.description,h,g.x,g.y,g.width,g.height,{class:`actor ${re}`},n);let w=t.height,T=b.select(`path:last-child`);if(T.node()){let e=T.node().getBBox();t.height=e.height,w=e.height}return i||(h.attr(`data-et`,`participant`),h.attr(`data-type`,`queue`),h.attr(`data-id`,t.name)),w},`drawActorTypeQueue`),fe=e(function(e,t,n,i,a,o){let s=i?t.stopy:t.starty,c=t.x+t.width/2,l=s+75,{look:u,theme:d,themeVariables:f}=n,{bkgColorArray:p,borderColorArray:m,actorBorder:h,actorBkg:g}=f,_=e.append(`g`).lower();i||(K++,_.append(`line`).attr(`id`,`actor`+K).attr(`x1`,c).attr(`y1`,l).attr(`x2`,c).attr(`y2`,2e3).attr(`class`,`actor-line 200`).attr(`stroke-width`,`0.5px`).attr(`stroke`,`#999`).attr(`name`,t.name).attr(`data-et`,`life-line`).attr(`data-id`,t.name),t.actorCnt=K);let v=e.append(`g`),y=H;i?y+=` ${V}`:y+=` ${B}`,v.attr(`class`,y),v.attr(`name`,t.name);let b=k();b.x=t.x,b.y=s,b.fill=`#eaeaea`,b.width=t.width,b.height=t.height,b.class=`actor`;let x=t.x+t.width/2,S=s+32;v.append(`defs`).append(`marker`).attr(`id`,a+`-filled-head-control`).attr(`refX`,11).attr(`refY`,5.8).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`172.5`).attr(`stroke-width`,1.2).append(`path`).attr(`d`,`M 14.4 5.6 L 7.2 10.4 L 8.8 5.6 L 7.2 0.8 Z`),v.append(`circle`).attr(`cx`,x).attr(`cy`,S).attr(`r`,22).attr(`filter`,`${u===`neo`?`url(#drop-shadow)`:``}`),v.append(`line`).attr(`marker-end`,`url(#`+a+`-filled-head-control)`).attr(`transform`,`translate(${x}, ${S-22})`);let C=o.get(t.name)??0;return U.has(d)?(v.style(`stroke`,m[C%m.length]),v.style(`fill`,p[C%m.length])):(v.style(`stroke`,h),v.style(`fill`,g)),t.height=v.node().getBBox().height+2*(n?.sequence?.labelBoxHeight??0),Y(n,r(t.description))(t.description,v,b.x,b.y+22+(i?5:12),b.width,b.height,{class:`actor ${H}`},n),i||(v.attr(`data-et`,`participant`),v.attr(`data-type`,`control`),v.attr(`data-id`,t.name)),t.height},`drawActorTypeControl`),pe=e(function(e,t,n,i,a){let o=i?t.stopy:t.starty,s=t.x+t.width/2,c=o+75,{look:l,theme:u,themeVariables:d}=n,{bkgColorArray:f,borderColorArray:p}=d,m=e.append(`g`).lower(),h=e.append(`g`),g=`actor`;i?g+=` ${V}`:g+=` ${B}`,h.attr(`class`,g),h.attr(`name`,t.name);let _=k();_.x=t.x,_.y=o,_.fill=`#eaeaea`,_.width=t.width,_.height=t.height,_.class=`actor`;let v=t.x+t.width/2,y=o+(i?10:25);h.append(`circle`).attr(`cx`,v).attr(`cy`,y).attr(`r`,22).attr(`width`,t.width).attr(`height`,t.height),h.append(`line`).attr(`x1`,v-22).attr(`x2`,v+22).attr(`y1`,y+22).attr(`y2`,y+22).attr(`stroke-width`,2),l===`neo`&&h.attr(`filter`,`url(#drop-shadow)`);let b=a.get(t.name)??0;return U.has(u)&&(h.style(`stroke`,p[b%p.length]),h.style(`fill`,f[b%p.length])),t.height=h.node().getBBox().height+(n?.sequence?.labelBoxHeight??0),i||(K++,m.append(`line`).attr(`id`,`actor`+K).attr(`x1`,s).attr(`y1`,c).attr(`x2`,s).attr(`y2`,2e3).attr(`class`,`actor-line 200`).attr(`stroke-width`,`0.5px`).attr(`stroke`,`#999`).attr(`name`,t.name).attr(`data-et`,`life-line`).attr(`data-id`,t.name),t.actorCnt=K),Y(n,r(t.description))(t.description,h,_.x,_.y+(i?15:30),_.width,_.height,{class:`actor ${H}`},n),i?h.attr(`transform`,`translate(0, 22)`):(h.attr(`transform`,`translate(0, ${22/2-5})`),h.attr(`data-et`,`participant`),h.attr(`data-type`,`entity`),h.attr(`data-id`,t.name)),t.height},`drawActorTypeEntity`),me=e(function(e,t,n,i,a){let o=i?t.stopy:t.starty,s=t.x+t.width/2,c=o+t.height+2*n.boxTextMargin,{theme:l,themeVariables:u,look:d}=n,{bkgColorArray:f,borderColorArray:p,actorBorder:m}=u,h=e.append(`g`).lower(),g=h;i||(K++,Object.keys(t.links||{}).length&&!n.forceMenus&&g.attr(`onclick`,ae(`actor${K}_popup`)).attr(`cursor`,`pointer`),g.append(`line`).attr(`id`,`actor`+K).attr(`x1`,s).attr(`y1`,c).attr(`x2`,s).attr(`y2`,2e3).attr(`class`,`actor-line 200`).attr(`stroke-width`,`0.5px`).attr(`stroke`,`#999`).attr(`name`,t.name).attr(`data-et`,`life-line`).attr(`data-id`,t.name),g=h.append(`g`),t.actorCnt=K,t.links!=null&&g.attr(`id`,`root-`+K),d===`neo`&&g.attr(`data-look`,`neo`));let _=k(),v=`actor`;t.properties?.class?v=t.properties.class:_.fill=`#eaeaea`,i?v+=` ${V}`:v+=` ${B}`,_.x=t.x,_.y=o,_.width=t.width,_.height=t.height,_.class=v,_.name=t.name,_.x=t.x,_.y=o;let y=_.width/3,b=_.width/3,x=y/2,S=x/(2.5+y/50),C=g.append(`g`);C.attr(`class`,v);let w=` + M ${_.x},${_.y+S} + a ${x},${S} 0 0 0 ${y},0 + a ${x},${S} 0 0 0 -${y},0 + l 0,${b-2*S} + a ${x},${S} 0 0 0 ${y},0 + l 0,-${b-2*S} +`;C.append(`path`).attr(`d`,w),d===`neo`&&C.attr(`filter`,`url(#drop-shadow)`);let T=a.get(t.name)??0;U.has(l)?(C.style(`stroke`,p[T%p.length]),C.style(`fill`,f[T%p.length])):C.style(`stroke`,m),C.attr(`transform`,`translate(${y}, ${S})`),t.rectData=_,Y(n,r(t.description))(t.description,g,_.x,_.y+35,_.width,_.height,{class:`actor ${re}`},n);let E=C.select(`path:last-child`);return E.node()&&(t.height=E.node().getBBox().height+(n.sequence.labelBoxHeight??0)),i||(g.attr(`data-et`,`participant`),g.attr(`data-type`,`database`),g.attr(`data-id`,t.name)),t.height},`drawActorTypeDatabase`),he=e(function(e,t,n,i,a){let o=i?t.stopy:t.starty,s=t.x+t.width/2,c=o+80,l=e.append(`g`).lower(),{look:u,theme:d,themeVariables:f}=n,{bkgColorArray:p,borderColorArray:m,actorBorder:h}=f;i||(K++,l.append(`line`).attr(`id`,`actor`+K).attr(`x1`,s).attr(`y1`,c).attr(`x2`,s).attr(`y2`,2e3).attr(`class`,`actor-line 200`).attr(`stroke-width`,`0.5px`).attr(`stroke`,`#999`).attr(`name`,t.name).attr(`data-et`,`life-line`).attr(`data-id`,t.name),t.actorCnt=K);let g=e.append(`g`),_=H;i?_+=` ${V}`:_+=` ${B}`,g.attr(`class`,_),g.attr(`name`,t.name);let v=k();v.x=t.x,v.y=o,v.fill=`#eaeaea`,v.width=t.width,v.height=t.height,v.class=`actor`,g.append(`line`).attr(`id`,`actor-man-torso`+K).attr(`x1`,t.x+t.width/2-22*2.5).attr(`y1`,o+12).attr(`x2`,t.x+t.width/2-15).attr(`y2`,o+12),g.append(`line`).attr(`id`,`actor-man-arms`+K).attr(`x1`,t.x+t.width/2-22*2.5).attr(`y1`,o+2).attr(`x2`,t.x+t.width/2-22*2.5).attr(`y2`,o+22),g.append(`circle`).attr(`cx`,t.x+t.width/2).attr(`cy`,o+12).attr(`r`,22),u===`neo`&&g.attr(`filter`,`url(#drop-shadow)`);let y=a.get(t.name)??0;return U.has(d)?(g.style(`stroke`,m[y%m.length]),g.style(`fill`,p[y%m.length])):g.style(`stroke`,h),t.height=g.node().getBBox().height+(n.sequence.labelBoxHeight??0),Y(n,r(t.description))(t.description,g,v.x,v.y+15,v.width,v.height,{class:`actor ${H}`},n),g.attr(`transform`,`translate(0,21)`),i||(g.attr(`data-et`,`participant`),g.attr(`data-type`,`boundary`),g.attr(`data-id`,t.name)),t.height},`drawActorTypeBoundary`),ge=e(function(e,t,n,i,a){let o=i?t.stopy:t.starty,s=t.x+t.width/2,c=o+80,{look:l,theme:u,themeVariables:d}=n,{bkgColorArray:f,borderColorArray:p,actorBorder:m}=d,h=e.append(`g`).lower();i||(K++,h.append(`line`).attr(`id`,`actor`+K).attr(`x1`,s).attr(`y1`,c).attr(`x2`,s).attr(`y2`,2e3).attr(`class`,`actor-line 200`).attr(`stroke-width`,`0.5px`).attr(`stroke`,`#999`).attr(`name`,t.name).attr(`data-et`,`life-line`).attr(`data-id`,t.name),t.actorCnt=K);let g=e.append(`g`),_=H;i?_+=` ${V}`:_+=` ${B}`,g.attr(`class`,_),g.attr(`name`,t.name),i||g.attr(`data-et`,`participant`).attr(`data-type`,`actor`).attr(`data-id`,t.name);let v=l===`neo`?.5:1,y=l===`neo`?o+(1-v)*30:o;g.append(`line`).attr(`id`,`actor-man-torso`+K).attr(`x1`,s).attr(`y1`,y+25*v).attr(`x2`,s).attr(`y2`,y+45*v),g.append(`line`).attr(`id`,`actor-man-arms`+K).attr(`x1`,s-z/2*v).attr(`y1`,y+33*v).attr(`x2`,s+z/2*v).attr(`y2`,y+33*v),g.append(`line`).attr(`x1`,s-z/2*v).attr(`y1`,y+60*v).attr(`x2`,s).attr(`y2`,y+45*v),g.append(`line`).attr(`x1`,s).attr(`y1`,y+45*v).attr(`x2`,s+(z/2-2)*v).attr(`y2`,y+60*v);let b=g.append(`circle`);b.attr(`cx`,t.x+t.width/2),b.attr(`cy`,y+10*v),b.attr(`r`,15*v),b.attr(`width`,t.width*v),b.attr(`height`,t.height*v),t.height=g.node().getBBox().height;let x=k();x.x=t.x,x.y=y,x.fill=`#eaeaea`,x.width=t.width,x.height=t.height/v,x.class=`actor`,x.rx=3,x.ry=3;let S=a.get(t.name)??0;return U.has(u)?(g.style(`stroke`,p[S%p.length]),g.style(`fill`,f[S%p.length])):g.style(`stroke`,m),Y(n,r(t.description))(t.description,g,x.x,y+35*v-(l===`neo`?10:0),x.width,x.height,{class:`actor ${H}`},n),t.height},`drawActorTypeActor`),_e=e(async function(e,t,n,r,i,a,o){let s=o??new Map([...a.db.getActors().values()].map((e,t)=>[e.name,t]));switch(t.type){case`actor`:return await ge(e,t,n,r,s);case`participant`:return await le(e,t,n,r,s);case`boundary`:return await he(e,t,n,r,s);case`control`:return await fe(e,t,n,r,i,s);case`entity`:return await pe(e,t,n,r,s);case`database`:return await me(e,t,n,r,s);case`collections`:return await ue(e,t,n,r,s);case`queue`:return await de(e,t,n,r,s)}},`drawActor`),ve=e(function(e,t,n){let r=e.append(`g`);Se(r,t),t.name&&Y(n)(t.name,r,t.x,t.y+n.boxTextMargin+(t.textMaxHeight||0)/2,t.width,0,{class:`text`},n),r.lower()},`drawBox`),ye=e(function(e){return e.append(`g`)},`anchorElement`),be=e(function(e,t,n,r,i,a,o){let{theme:s,themeVariables:c}=r,{bkgColorArray:l,borderColorArray:u,mainBkg:d}=c,f=k(),p=t.anchored,m=t.actor;f.x=t.startx,f.y=t.starty,f.class=`activation`+i%3,f.width=t.stopx-t.startx,f.height=n-t.starty;let h=W(p,f),g=(o??new Map([...a.db.getActors().values()].map((e,t)=>[e.name,t]))).get(m)??0;U.has(s)&&(h.style(`stroke`,u[g%u.length]),h.style(`fill`,l[g%u.length]??d))},`drawActivation`),xe=e(async function(t,n,i,a,o){let{boxMargin:s,boxTextMargin:c,labelBoxHeight:l,labelBoxWidth:u,messageFontFamily:d,messageFontSize:f,messageFontWeight:p}=a,m=t.append(`g`).attr(`data-et`,`control-structure`).attr(`data-id`,`i`+o.id),h=e(function(e,t,n,r){return m.append(`line`).attr(`x1`,e).attr(`y1`,t).attr(`x2`,n).attr(`y2`,r).attr(`class`,`loopLine`)},`drawLoopLine`);h(n.startx,n.starty,n.stopx,n.starty),h(n.stopx,n.starty,n.stopx,n.stopy),h(n.startx,n.stopy,n.stopx,n.stopy),h(n.startx,n.starty,n.startx,n.stopy),n.sections!==void 0&&n.sections.forEach(function(e){h(n.startx,e.y,n.stopx,e.y).style(`stroke-dasharray`,`3, 3`)});let g=T();g.text=i,g.x=n.startx,g.y=n.starty,g.fontFamily=d,g.fontSize=f,g.fontWeight=p,g.anchor=`middle`,g.valign=`middle`,g.tspan=!1,g.width=Math.max(u??0,50),g.height=l+(a.look===`neo`?15:0)||20,g.textMargin=c,g.class=`labelText`,se(m,g),g=ke(),g.text=n.title,g.x=n.startx+u/2+(n.stopx-n.startx)/2,g.y=n.starty+s+c,g.anchor=`middle`,g.valign=`middle`,g.textMargin=c,g.class=`loopText`,g.fontFamily=d,g.fontSize=f,g.fontWeight=p,g.wrap=!0;let _=r(g.text)?await oe(m,g,n):G(m,g);if(n.sectionTitles!==void 0){for(let[e,t]of Object.entries(n.sectionTitles))if(t.message){g.text=t.message,g.x=n.startx+(n.stopx-n.startx)/2,g.y=n.sections[e].y+s+c,g.class=`sectionTitle`,g.anchor=`middle`,g.valign=`middle`,g.tspan=!1,g.fontFamily=d,g.fontSize=f,g.fontWeight=p,g.wrap=n.wrap,r(g.text)?(n.starty=n.sections[e].y,await oe(m,g,n)):G(m,g);let i=Math.round(_.map(e=>(e._groups||e)[0][0].getBBox().height).reduce((e,t)=>e+t));n.sections[e].height+=i-(s+c)}}return n.height=Math.round(n.stopy-n.starty),m},`drawLoop`),Se=e(function(e,t){D(e,t)},`drawBackgroundRect`),Ce=e(function(e,t){e.append(`defs`).append(`symbol`).attr(`id`,t+`-database`).attr(`fill-rule`,`evenodd`).attr(`clip-rule`,`evenodd`).append(`path`).attr(`transform`,`scale(.5)`).attr(`d`,`M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z`)},`insertDatabaseIcon`),q=e(function(e,t){e.append(`defs`).append(`symbol`).attr(`id`,t+`-computer`).attr(`width`,`24`).attr(`height`,`24`).append(`path`).attr(`transform`,`scale(.5)`).attr(`d`,`M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z`)},`insertComputerIcon`),J=e(function(e,t){e.append(`defs`).append(`symbol`).attr(`id`,t+`-clock`).attr(`width`,`24`).attr(`height`,`24`).append(`path`).attr(`transform`,`scale(.5)`).attr(`d`,`M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z`)},`insertClockIcon`),we=e(function(e,t){e.append(`defs`).append(`marker`).attr(`id`,t+`-arrowhead`).attr(`refX`,7.9).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,12).attr(`markerHeight`,12).attr(`orient`,`auto-start-reverse`).append(`path`).attr(`d`,`M -1 0 L 10 5 L 0 10 z`)},`insertArrowHead`),Te=e(function(e,t){e.append(`defs`).append(`marker`).attr(`id`,t+`-filled-head`).attr(`refX`,15.5).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L14,7 L9,1 Z`)},`insertArrowFilledHead`),Ee=e(function(e,t){e.append(`defs`).append(`marker`).attr(`id`,t+`-sequencenumber`).attr(`refX`,15).attr(`refY`,15).attr(`markerWidth`,60).attr(`markerHeight`,40).attr(`orient`,`auto`).append(`circle`).attr(`cx`,15).attr(`cy`,15).attr(`r`,6)},`insertSequenceNumber`),De=e(function(e,t){e.append(`defs`).append(`marker`).attr(`id`,t+`-crosshead`).attr(`markerWidth`,15).attr(`markerHeight`,8).attr(`orient`,`auto`).attr(`refX`,4).attr(`refY`,4.5).append(`path`).attr(`fill`,`none`).attr(`stroke`,`#000000`).style(`stroke-dasharray`,`0, 0`).attr(`stroke-width`,`1pt`).attr(`d`,`M 1,2 L 6,7 M 6,2 L 1,7`)},`insertArrowCrossHead`),Oe=e(function(e,t){let{theme:n}=t;e.append(`defs`).append(`filter`).attr(`id`,`drop-shadow`).attr(`height`,`130%`).attr(`width`,`130%`).append(`feDropShadow`).attr(`dx`,`4`).attr(`dy`,`4`).attr(`stdDeviation`,0).attr(`flood-opacity`,`0.06`).attr(`flood-color`,`${n===`redux`||n===`redux-color`?`#000000`:`#FFFFFF`}`)},`insertDropShadow`),ke=e(function(){return{x:0,y:0,fill:void 0,anchor:void 0,style:`#666`,width:void 0,height:void 0,textMargin:0,rx:0,ry:0,tspan:!0,valign:void 0}},`getTextObj`),Ae=e(function(){return{x:0,y:0,fill:`#EDF2AE`,stroke:`#666`,width:100,anchor:`start`,height:100,rx:0,ry:0}},`getNoteRect`),Y=(function(){function t(e,t,n,r,i,a,s){o(t.append(`text`).attr(`x`,n+i/2).attr(`y`,r+a/2+5).style(`text-anchor`,`middle`).text(e),s)}e(t,`byText`);function n(e,t,n,r,i,a,s,c){let{actorFontSize:l,actorFontFamily:u,actorFontWeight:d}=c,[f,p]=C(l),m=e.split(h.lineBreakRegex);for(let e=0;ee.height||0))+(this.loops.length===0?0:this.loops.map(e=>e.height||0).reduce((e,t)=>e+t))+(this.messages.length===0?0:this.messages.map(e=>e.height||0).reduce((e,t)=>e+t))+(this.notes.length===0?0:this.notes.map(e=>e.height||0).reduce((e,t)=>e+t))},`getHeight`),clear:e(function(){this.actors=[],this.boxes=[],this.loops=[],this.messages=[],this.notes=[]},`clear`),addBox:e(function(e){this.boxes.push(e)},`addBox`),addActor:e(function(e){this.actors.push(e)},`addActor`),addLoop:e(function(e){this.loops.push(e)},`addLoop`),addMessage:e(function(e){this.messages.push(e)},`addMessage`),addNote:e(function(e){this.notes.push(e)},`addNote`),lastActor:e(function(){return this.actors[this.actors.length-1]},`lastActor`),lastLoop:e(function(){return this.loops[this.loops.length-1]},`lastLoop`),lastMessage:e(function(){return this.messages[this.messages.length-1]},`lastMessage`),lastNote:e(function(){return this.notes[this.notes.length-1]},`lastNote`),actors:[],boxes:[],loops:[],messages:[],notes:[]},init:e(function(){this.sequenceItems=[],this.activations=[],this.models.clear(),this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},this.verticalPos=0,He(v())},`init`),updateVal:e(function(e,t,n,r){e[t]===void 0?e[t]=n:e[t]=r(n,e[t])},`updateVal`),updateBounds:e(function(t,n,r,i){let a=this,o=0;function s(s){return e(function(e){o++;let c=a.sequenceItems.length-o+1;a.updateVal(e,`starty`,n-c*Z.boxMargin,Math.min),a.updateVal(e,`stopy`,i+c*Z.boxMargin,Math.max),a.updateVal(Q.data,`startx`,t-c*Z.boxMargin,Math.min),a.updateVal(Q.data,`stopx`,r+c*Z.boxMargin,Math.max),s!==`activation`&&(a.updateVal(e,`startx`,t-c*Z.boxMargin,Math.min),a.updateVal(e,`stopx`,r+c*Z.boxMargin,Math.max),a.updateVal(Q.data,`starty`,n-c*Z.boxMargin,Math.min),a.updateVal(Q.data,`stopy`,i+c*Z.boxMargin,Math.max))},`updateItemBounds`)}e(s,`updateFn`),this.sequenceItems.forEach(s()),this.activations.forEach(s(`activation`))},`updateBounds`),insert:e(function(e,t,n,r){let i=h.getMin(e,n),a=h.getMax(e,n),o=h.getMin(t,r),s=h.getMax(t,r);this.updateVal(Q.data,`startx`,i,Math.min),this.updateVal(Q.data,`starty`,o,Math.min),this.updateVal(Q.data,`stopx`,a,Math.max),this.updateVal(Q.data,`stopy`,s,Math.max),this.updateBounds(i,o,a,s)},`insert`),newActivation:e(function(e,t,n){let r=n.get(e.from),i=Ue(e.from).length||0,a=r.x+r.width/2+(i-1)*Z.activationWidth/2;this.activations.push({startx:a,starty:this.verticalPos+2,stopx:a+Z.activationWidth,stopy:void 0,actor:e.from,anchored:X.anchorElement(t)})},`newActivation`),endActivation:e(function(e){let t=this.activations.map(function(e){return e.actor}).lastIndexOf(e.from);return this.activations.splice(t,1)[0]},`endActivation`),createLoop:e(function(e={message:void 0,wrap:!1,width:void 0},t){return{startx:void 0,starty:this.verticalPos,stopx:void 0,stopy:void 0,title:e.message,wrap:e.wrap,width:e.width,height:0,fill:t}},`createLoop`),newLoop:e(function(e={message:void 0,wrap:!1,width:void 0},t){this.sequenceItems.push(this.createLoop(e,t))},`newLoop`),endLoop:e(function(){return this.sequenceItems.pop()},`endLoop`),isLoopOverlap:e(function(){return this.sequenceItems.length?this.sequenceItems[this.sequenceItems.length-1].overlap:!1},`isLoopOverlap`),addSectionToLoop:e(function(e){let t=this.sequenceItems.pop();t.sections=t.sections||[],t.sectionTitles=t.sectionTitles||[],t.sections.push({y:Q.getVerticalPos(),height:0}),t.sectionTitles.push(e),this.sequenceItems.push(t)},`addSectionToLoop`),saveVerticalPos:e(function(){this.isLoopOverlap()&&(this.savedVerticalPos=this.verticalPos)},`saveVerticalPos`),resetVerticalPos:e(function(){this.isLoopOverlap()&&(this.verticalPos=this.savedVerticalPos)},`resetVerticalPos`),bumpVerticalPos:e(function(e){this.verticalPos+=e,this.data.stopy=h.getMax(this.data.stopy,this.verticalPos)},`bumpVerticalPos`),getVerticalPos:e(function(){return this.verticalPos},`getVerticalPos`),getBounds:e(function(){return{bounds:this.data,models:this.models}},`getBounds`)},Me=e(async function(e,t,n){Q.bumpVerticalPos(Z.boxMargin),t.height=Z.boxMargin,t.starty=Q.getVerticalPos();let i=k();i.x=t.startx,i.y=t.starty,i.width=t.width||Z.width,i.class=`note`;let a=e.append(`g`);a.attr(`data-et`,`note`),a.attr(`data-id`,`i`+n);let o=X.drawRect(a,i),s=T();s.x=t.startx,s.y=t.starty,s.width=i.width,s.dy=`1em`,s.text=t.message,s.class=`noteText`,s.fontFamily=Z.noteFontFamily,s.fontSize=Z.noteFontSize,s.fontWeight=Z.noteFontWeight,s.anchor=Z.noteAlign,s.textMargin=Z.noteMargin,s.valign=`center`;let c=r(s.text)?await oe(a,s):G(a,s),l=Math.round(c.map(e=>(e._groups||e)[0][0].getBBox().height).reduce((e,t)=>e+t));o.attr(`height`,l+2*Z.noteMargin),t.height+=l+2*Z.noteMargin,Q.bumpVerticalPos(l+2*Z.noteMargin),t.stopy=t.starty+l+2*Z.noteMargin,t.stopx=t.startx+i.width,Q.insert(t.startx,t.starty,t.stopx,t.stopy),Q.models.addNote(t)},`drawNote`),Ne=e(function(t,n,r,i,a,o,s){let c=i.db.getActors(),l=c.get(n.from),u=c.get(n.to),d=r.sequenceVisible,f=l.x+l.width/2,p=u.x+u.width/2,m=f<=p,h=tt(n,i),g=t.append(`g`),_=e((e,t)=>{let n=e?16.5:-16.5;return t?-n:n},`getCircleOffset`),v=e(e=>{g.append(`circle`).attr(`cx`,e).attr(`cy`,s).attr(`r`,5).attr(`width`,10).attr(`height`,10)},`drawCircle`),{CENTRAL_CONNECTION:y,CENTRAL_CONNECTION_REVERSE:b,CENTRAL_CONNECTION_DUAL:x}=i.db.LINETYPE;if(d)switch(n.centralConnection){case y:h&&(p+=_(m,!0));break;case b:h||(f+=_(m,!1));break;case x:h?p+=_(m,!0):f+=_(m,!1);break}switch(n.centralConnection){case y:v(p);break;case b:v(f);break;case x:v(f),v(p);break}},`drawCentralConnection`),Pe=e(e=>({fontFamily:e.messageFontFamily,fontSize:e.messageFontSize,fontWeight:e.messageFontWeight}),`messageFont`),Fe=e(e=>({fontFamily:e.noteFontFamily,fontSize:e.noteFontSize,fontWeight:e.noteFontWeight}),`noteFont`),Ie=e(e=>({fontFamily:e.actorFontFamily,fontSize:e.actorFontSize,fontWeight:e.actorFontWeight}),`actorFont`);async function Le(e,t){Q.bumpVerticalPos(10);let{startx:n,stopx:i,message:a}=t,o=h.splitBreaks(a).length,s=r(a),c=s?await p(a,v()):S.calculateTextDimensions(a,Pe(Z));if(!s){let e=c.height/o;t.height+=e,Q.bumpVerticalPos(e)}let l,u=c.height-10,d=c.width;if(n===i){l=Q.getVerticalPos()+u,Z.rightAngles||(u+=Z.boxMargin,l=Q.getVerticalPos()+u),u+=30;let e=h.getMax(d/2,Z.width/2);Q.insert(n-e,Q.getVerticalPos()-10+u,i+e,Q.getVerticalPos()+30+u)}else u+=Z.boxMargin,l=Q.getVerticalPos()+u,Q.insert(n,l-10,i,l);return Q.bumpVerticalPos(u),t.height+=u,t.stopy=t.starty+t.height,Q.insert(t.fromBounds,t.starty,t.toBounds,t.stopy),l}e(Le,`boundMessage`);var Re=e(async function(e,t,n,i,a,o){let{startx:s,stopx:l,starty:u,message:d,type:f,sequenceIndex:p,sequenceVisible:m}=t,g=S.calculateTextDimensions(d,Pe(Z)),_=T();_.x=Math.min(s,l),_.y=u+10,_.width=Math.abs(l-s),_.class=`messageText`,_.dy=`1em`,_.text=d,_.fontFamily=Z.messageFontFamily,_.fontSize=Z.messageFontSize,_.fontWeight=Z.messageFontWeight,_.anchor=Z.messageAlign,_.valign=`center`,_.textMargin=Z.wrapPadding,_.tspan=!1,r(_.text)?await oe(e,_,{startx:s,stopx:l,starty:n}):G(e,_);let v=g.width,y;if(s===l){let r=m||Z.showSequenceNumbers,o=tt(a,i),c=nt(a,i),u=s+(r&&(o||c)?10:0);y=Z.rightAngles?e.append(`path`).attr(`d`,`M ${u},${n} H ${s+h.getMax(Z.width/2,v/2)} V ${n+25} H ${s}`):e.append(`path`).attr(`d`,`M `+u+`,`+n+` C `+(u+60)+`,`+(n-10)+` `+(s+60)+`,`+(n+30)+` `+s+`,`+(n+20)),$e(a,i)&&Ne(e,a,t,i,s,l,n)}else y=e.append(`line`),y.attr(`x1`,s),y.attr(`y1`,n),y.attr(`x2`,l),y.attr(`y2`,n),$e(a,i)&&Ne(e,a,t,i,s,l,n);f===i.db.LINETYPE.DOTTED||f===i.db.LINETYPE.DOTTED_CROSS||f===i.db.LINETYPE.DOTTED_POINT||f===i.db.LINETYPE.DOTTED_OPEN||f===i.db.LINETYPE.BIDIRECTIONAL_DOTTED||f===i.db.LINETYPE.SOLID_TOP_DOTTED||f===i.db.LINETYPE.SOLID_BOTTOM_DOTTED||f===i.db.LINETYPE.STICK_TOP_DOTTED||f===i.db.LINETYPE.STICK_BOTTOM_DOTTED||f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED||f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED||f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED||f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED?(y.style(`stroke-dasharray`,`3, 3`),y.attr(`class`,`messageLine1`)):y.attr(`class`,`messageLine0`),y.attr(`data-et`,`message`),y.attr(`data-id`,`i`+t.id),y.attr(`data-from`,t.from),y.attr(`data-to`,t.to);let b=``;if(Z.arrowMarkerAbsolute&&(b=c(!0)),y.attr(`stroke-width`,2),y.attr(`stroke`,`none`),y.style(`fill`,`none`),(f===i.db.LINETYPE.SOLID_TOP||f===i.db.LINETYPE.SOLID_TOP_DOTTED)&&y.attr(`marker-end`,`url(`+b+`#`+o+`-solidTopArrowHead)`),(f===i.db.LINETYPE.SOLID_BOTTOM||f===i.db.LINETYPE.SOLID_BOTTOM_DOTTED)&&y.attr(`marker-end`,`url(`+b+`#`+o+`-solidBottomArrowHead)`),(f===i.db.LINETYPE.STICK_TOP||f===i.db.LINETYPE.STICK_TOP_DOTTED)&&y.attr(`marker-end`,`url(`+b+`#`+o+`-stickTopArrowHead)`),(f===i.db.LINETYPE.STICK_BOTTOM||f===i.db.LINETYPE.STICK_BOTTOM_DOTTED)&&y.attr(`marker-end`,`url(`+b+`#`+o+`-stickBottomArrowHead)`),(f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE||f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED)&&y.attr(`marker-start`,`url(`+b+`#`+o+`-solidBottomArrowHead)`),(f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE||f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED)&&y.attr(`marker-start`,`url(`+b+`#`+o+`-solidTopArrowHead)`),(f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE||f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED)&&y.attr(`marker-start`,`url(`+b+`#`+o+`-stickBottomArrowHead)`),(f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE||f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED)&&y.attr(`marker-start`,`url(`+b+`#`+o+`-stickTopArrowHead)`),(f===i.db.LINETYPE.SOLID||f===i.db.LINETYPE.DOTTED)&&y.attr(`marker-end`,`url(`+b+`#`+o+`-arrowhead)`),(f===i.db.LINETYPE.BIDIRECTIONAL_SOLID||f===i.db.LINETYPE.BIDIRECTIONAL_DOTTED)&&(y.attr(`marker-start`,`url(`+b+`#`+o+`-arrowhead)`),y.attr(`marker-end`,`url(`+b+`#`+o+`-arrowhead)`)),(f===i.db.LINETYPE.SOLID_POINT||f===i.db.LINETYPE.DOTTED_POINT)&&y.attr(`marker-end`,`url(`+b+`#`+o+`-filled-head)`),(f===i.db.LINETYPE.SOLID_CROSS||f===i.db.LINETYPE.DOTTED_CROSS)&&y.attr(`marker-end`,`url(`+b+`#`+o+`-crosshead)`),m||Z.showSequenceNumbers){let r=f===i.db.LINETYPE.BIDIRECTIONAL_SOLID||f===i.db.LINETYPE.BIDIRECTIONAL_DOTTED,c=f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE||f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED||f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE||f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED||f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE||f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED||f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE||f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED,u=$e(a,i),d=s,m=l;r?(ss?m=l-12:(m=l-6,d+=a?.centralConnection===i.db.LINETYPE.CENTRAL_CONNECTION_DUAL||a?.centralConnection===i.db.LINETYPE.CENTRAL_CONNECTION_REVERSE?-7.5:0),m+=u?15:0,y.attr(`x2`,m),y.attr(`x1`,d)):y.attr(`x1`,s+6);let h=0,g=s===l,_=s<=l;h=g?t.fromBounds+1:c?_?t.toBounds-1:t.fromBounds+1:_?t.fromBounds+1:t.toBounds-1;let v=`12px`,x=p.toString().length;x>5?v=`7px`:x>3&&(v=`9px`),e.append(`line`).attr(`x1`,h).attr(`y1`,n).attr(`x2`,h).attr(`y2`,n).attr(`stroke-width`,0).attr(`marker-start`,`url(`+b+`#`+o+`-sequencenumber)`),e.append(`text`).attr(`x`,h).attr(`y`,n+4).attr(`font-family`,`sans-serif`).attr(`font-size`,v).attr(`text-anchor`,`middle`).attr(`class`,`sequenceNumber`).text(p)}},`drawMessage`),ze=e(function(e,t,n,r,i,a,o){let s=0,c=0,l,u=0;for(let e of r){let r=t.get(e),a=r.box;l&&l!=a&&(o||Q.models.addBox(l),c+=Z.boxMargin+l.margin),a&&a!=l&&(o||(a.x=s+c,a.y=i),c+=a.margin),r.width=h.getMax(r.width||Z.width,Z.width),r.height=h.getMax(r.height||Z.height,Z.height),r.margin=r.margin||Z.actorMargin,u=h.getMax(u,r.height),n.get(r.name)&&(c+=r.width/2),r.x=s+c,r.starty=Q.getVerticalPos(),Q.insert(r.x,i,r.x+r.width,r.height),s+=r.width+c,r.box&&(r.box.width=s+a.margin-r.box.x),c=r.margin,l=r.box,Q.models.addActor(r)}l&&!o&&Q.models.addBox(l),Q.bumpVerticalPos(u)},`addActorRenderingData`),Be=e(async function(e,t,n,r,i,a,o){if(r){let r=0;Q.bumpVerticalPos(Z.boxMargin*2);for(let s of n){let n=t.get(s);n.stopy||=Q.getVerticalPos();let c=await X.drawActor(e,n,Z,!0,i,a,o);r=h.getMax(r,c)}Q.bumpVerticalPos(r+Z.boxMargin)}else for(let r of n){let n=t.get(r);await X.drawActor(e,n,Z,!1,i,a,o)}},`drawActors`),Ve=e(function(e,t,n,r){let i=0,a=0;for(let o of n){let n=t.get(o),s=Je(n),c=X.drawPopup(e,n,s,Z,Z.forceMenus,r);c.height>i&&(i=c.height),c.width+n.x>a&&(a=c.width+n.x)}return{maxHeight:i,maxWidth:a}},`drawActorsPopup`),He=e(function(e){m(Z,e),e.fontFamily&&(Z.actorFontFamily=Z.noteFontFamily=Z.messageFontFamily=e.fontFamily),e.fontSize&&(Z.actorFontSize=Z.noteFontSize=Z.messageFontSize=e.fontSize),e.fontWeight&&(Z.actorFontWeight=Z.noteFontWeight=Z.messageFontWeight=e.fontWeight)},`setConf`),Ue=e(function(e){return Q.activations.filter(function(t){return t.actor===e})},`actorActivations`),We=e(function(e,t){let n=t.get(e),r=Ue(e);return[r.reduce(function(e,t){return h.getMin(e,t.startx)},n.x+n.width/2-1),r.reduce(function(e,t){return h.getMax(e,t.stopx)},n.x+n.width/2+1)]},`activationBounds`);function $(e,n,r,i,a){Q.bumpVerticalPos(r);let o=i;if(n.id&&n.message&&e[n.id]){let r=e[n.id].width,a=Pe(Z);n.message=S.wrapLabel(`[${n.message}]`,r-2*Z.wrapPadding,a),n.width=r,n.wrap=!0;let s=S.calculateTextDimensions(n.message,a),c=h.getMax(s.height,Z.labelBoxHeight);o=i+c,t.debug(`${c} - ${n.message}`)}a(n),Q.bumpVerticalPos(o)}e($,`adjustLoopHeightForWrap`);function Ge(t,n,r,i,a,o,s){function c(e,r){e.x{e.add(t.from),e.add(t.to)}),x=x.filter(t=>e.has(t))}let D=new Map(x.map((e,t)=>[g.get(e)?.name??e,t]));ze(h,g,_,x,0,S,!1);let O=await it(S,g,E,o);X.insertArrowHead(h,i),X.insertArrowCrossHead(h,i),X.insertArrowFilledHead(h,i),X.insertSequenceNumber(h,i),X.insertSolidTopArrowHead(h,i),X.insertSolidBottomArrowHead(h,i),X.insertStickTopArrowHead(h,i),X.insertStickBottomArrowHead(h,i),l===`neo`&&X.insertDropShadow(h,Z);function k(e,t){let n=Q.endActivation(e);n.starty+18>t&&(n.starty=t-6,t+=12),X.drawActivation(h,n,t,Z,Ue(e.from).length,o,D),Q.insert(n.startx,t-10,n.stopx,t)}e(k,`activeEnd`);let A=1,j=1,M=[],N=[],P=0;for(let e of S){let n,r,i;switch(e.type){case o.db.LINETYPE.NOTE:Q.resetVerticalPos(),r=e.noteModel,await Me(h,r,e.id);break;case o.db.LINETYPE.ACTIVE_START:Q.newActivation(e,h,g);break;case o.db.LINETYPE.CENTRAL_CONNECTION:Q.newActivation(e,h,g);break;case o.db.LINETYPE.CENTRAL_CONNECTION_REVERSE:Q.newActivation(e,h,g);break;case o.db.LINETYPE.ACTIVE_END:k(e,Q.getVerticalPos());break;case o.db.LINETYPE.LOOP_START:$(O,e,Z.boxMargin,Z.boxMargin+Z.boxTextMargin,e=>Q.newLoop(e));break;case o.db.LINETYPE.LOOP_END:n=Q.endLoop(),await X.drawLoop(h,n,`loop`,Z,e),Q.bumpVerticalPos(n.stopy-Q.getVerticalPos()),Q.models.addLoop(n);break;case o.db.LINETYPE.RECT_START:$(O,e,Z.boxMargin,Z.boxMargin,e=>{let t=e.message;t||=u?.rectBkgColor||u?.actorBkg||`rgba(128, 128, 128, 0.5)`,Q.newLoop(void 0,t)});break;case o.db.LINETYPE.RECT_END:n=Q.endLoop(),N.push(n),Q.models.addLoop(n),Q.bumpVerticalPos(n.stopy-Q.getVerticalPos());break;case o.db.LINETYPE.OPT_START:$(O,e,Z.boxMargin,Z.boxMargin+Z.boxTextMargin,e=>Q.newLoop(e));break;case o.db.LINETYPE.OPT_END:n=Q.endLoop(),await X.drawLoop(h,n,`opt`,Z,e),Q.bumpVerticalPos(n.stopy-Q.getVerticalPos()),Q.models.addLoop(n);break;case o.db.LINETYPE.ALT_START:$(O,e,Z.boxMargin,Z.boxMargin+Z.boxTextMargin,e=>Q.newLoop(e));break;case o.db.LINETYPE.ALT_ELSE:$(O,e,Z.boxMargin+Z.boxTextMargin,Z.boxMargin,e=>Q.addSectionToLoop(e));break;case o.db.LINETYPE.ALT_END:n=Q.endLoop(),await X.drawLoop(h,n,`alt`,Z,e),Q.bumpVerticalPos(n.stopy-Q.getVerticalPos()),Q.models.addLoop(n);break;case o.db.LINETYPE.PAR_START:case o.db.LINETYPE.PAR_OVER_START:$(O,e,Z.boxMargin,Z.boxMargin+Z.boxTextMargin,e=>Q.newLoop(e)),Q.saveVerticalPos();break;case o.db.LINETYPE.PAR_AND:$(O,e,Z.boxMargin+Z.boxTextMargin,Z.boxMargin,e=>Q.addSectionToLoop(e));break;case o.db.LINETYPE.PAR_END:n=Q.endLoop(),await X.drawLoop(h,n,`par`,Z,e),Q.bumpVerticalPos(n.stopy-Q.getVerticalPos()),Q.models.addLoop(n);break;case o.db.LINETYPE.AUTONUMBER:A=e.message.start||A,j=e.message.step||j,e.message.visible?o.db.enableSequenceNumbers():o.db.disableSequenceNumbers();break;case o.db.LINETYPE.CRITICAL_START:$(O,e,Z.boxMargin,Z.boxMargin+Z.boxTextMargin,e=>Q.newLoop(e));break;case o.db.LINETYPE.CRITICAL_OPTION:$(O,e,Z.boxMargin+Z.boxTextMargin,Z.boxMargin,e=>Q.addSectionToLoop(e));break;case o.db.LINETYPE.CRITICAL_END:n=Q.endLoop(),await X.drawLoop(h,n,`critical`,Z,e),Q.bumpVerticalPos(n.stopy-Q.getVerticalPos()),Q.models.addLoop(n);break;case o.db.LINETYPE.BREAK_START:$(O,e,Z.boxMargin,Z.boxMargin+Z.boxTextMargin,e=>Q.newLoop(e));break;case o.db.LINETYPE.BREAK_END:n=Q.endLoop(),await X.drawLoop(h,n,`break`,Z,e),Q.bumpVerticalPos(n.stopy-Q.getVerticalPos()),Q.models.addLoop(n);break;default:try{i=e.msgModel,i.starty=Q.getVerticalPos(),i.sequenceIndex=A,i.sequenceVisible=o.db.showSequenceNumbers(),i.id=e.id,i.from=e.from,i.to=e.to;let t=await Le(h,i);Ge(e,i,t,P,g,_,y),M.push({messageModel:i,lineStartY:t,msg:e}),Q.models.addMessage(i)}catch(e){t.error(`error while drawing message`,e)}}[o.db.LINETYPE.SOLID_OPEN,o.db.LINETYPE.DOTTED_OPEN,o.db.LINETYPE.SOLID,o.db.LINETYPE.SOLID_TOP,o.db.LINETYPE.SOLID_BOTTOM,o.db.LINETYPE.STICK_TOP,o.db.LINETYPE.STICK_BOTTOM,o.db.LINETYPE.SOLID_TOP_DOTTED,o.db.LINETYPE.SOLID_BOTTOM_DOTTED,o.db.LINETYPE.STICK_TOP_DOTTED,o.db.LINETYPE.STICK_BOTTOM_DOTTED,o.db.LINETYPE.SOLID_ARROW_TOP_REVERSE,o.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE,o.db.LINETYPE.STICK_ARROW_TOP_REVERSE,o.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE,o.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED,o.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED,o.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED,o.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED,o.db.LINETYPE.DOTTED,o.db.LINETYPE.SOLID_CROSS,o.db.LINETYPE.DOTTED_CROSS,o.db.LINETYPE.SOLID_POINT,o.db.LINETYPE.DOTTED_POINT,o.db.LINETYPE.BIDIRECTIONAL_SOLID,o.db.LINETYPE.BIDIRECTIONAL_DOTTED].includes(e.type)&&(A=Math.round((A+j)*100)/100),P++}t.debug(`createdActors`,_),t.debug(`destroyedActors`,y),await Be(h,g,x,!1,i,o,D);for(let e of M)await Re(h,e.messageModel,e.lineStartY,o,e.msg,i);Z.mirrorActors&&await Be(h,g,x,!0,i,o,D),N.forEach(e=>X.drawBackgroundRect(h,e)),ce(h,g,x,Z);for(let e of Q.models.boxes){e.height=Q.getVerticalPos()-e.y,Q.insert(e.x,e.y,e.x+e.width,e.height);let t=Z.boxMargin*2;e.startx=e.x-t,e.starty=e.y-t*.25,e.stopx=e.startx+e.width+2*t,e.stopy=e.starty+e.height+t*.75,e.stroke=`rgb(0,0,0, 0.5)`,X.drawBox(h,e,Z)}w&&Q.bumpVerticalPos(Z.boxMargin);let F=Ve(h,g,x,m),{bounds:I}=Q.getBounds();I.startx===void 0&&(I.startx=0),I.starty===void 0&&(I.starty=0),I.stopx===void 0&&(I.stopx=0),I.stopy===void 0&&(I.stopy=0);let ee=I.stopy-I.starty;ee{let n=Pe(Z),r=t.actorKeys.reduce((t,n)=>t+=e.get(n).width+(e.get(n).margin||0),0),i=Z.boxMargin*8;r+=i,r-=2*Z.boxTextMargin,t.wrap&&(t.name=S.wrapLabel(t.name,r-2*Z.wrapPadding,n));let o=S.calculateTextDimensions(t.name,n);a=h.getMax(o.height,a);let s=h.getMax(r,o.width+2*Z.wrapPadding);if(t.margin=Z.boxTextMargin,re.textMaxHeight=a),h.getMax(i,Z.height)}e(Ye,`calculateActorMargins`);var Xe=e(async function(e,n,i){let a=n.get(e.from),o=n.get(e.to),s=a.x,c=o.x,l=e.wrap&&e.message,u=r(e.message)?await p(e.message,v()):S.calculateTextDimensions(l?S.wrapLabel(e.message,Z.width,Fe(Z)):e.message,Fe(Z)),d={width:l?Z.width:h.getMax(Z.width,u.width+2*Z.noteMargin),height:0,startx:a.x,stopx:0,starty:0,stopy:0,message:e.message};return e.placement===i.db.PLACEMENT.RIGHTOF?(d.width=l?h.getMax(Z.width,u.width):h.getMax(a.width/2+o.width/2,u.width+2*Z.noteMargin),d.startx=s+(a.width+Z.actorMargin)/2):e.placement===i.db.PLACEMENT.LEFTOF?(d.width=l?h.getMax(Z.width,u.width+2*Z.noteMargin):h.getMax(a.width/2+o.width/2,u.width+2*Z.noteMargin),d.startx=s-d.width+(a.width-Z.actorMargin)/2):e.to===e.from?(u=S.calculateTextDimensions(l?S.wrapLabel(e.message,h.getMax(Z.width,a.width),Fe(Z)):e.message,Fe(Z)),d.width=l?h.getMax(Z.width,a.width):h.getMax(a.width,Z.width,u.width+2*Z.noteMargin),d.startx=s+(a.width-d.width)/2):(d.width=Math.abs(s+a.width/2-(c+o.width/2))+Z.actorMargin,d.startx=s2,p=e(e=>l?-e:e,`adjustValue`);t.from===t.to?d=u:(t.activate&&!f&&(d+=p(Z.activationWidth/2-1)),[r.db.LINETYPE.SOLID_OPEN,r.db.LINETYPE.DOTTED_OPEN,r.db.LINETYPE.STICK_TOP,r.db.LINETYPE.STICK_BOTTOM,r.db.LINETYPE.STICK_TOP_DOTTED,r.db.LINETYPE.STICK_BOTTOM_DOTTED,r.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED,r.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED,r.db.LINETYPE.STICK_ARROW_TOP_REVERSE,r.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE,r.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED,r.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED,r.db.LINETYPE.SOLID_ARROW_TOP_REVERSE,r.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE].includes(t.type)||(d+=p(3)),[r.db.LINETYPE.BIDIRECTIONAL_SOLID,r.db.LINETYPE.BIDIRECTIONAL_DOTTED,r.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED,r.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED,r.db.LINETYPE.SOLID_ARROW_TOP_REVERSE,r.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE].includes(t.type)&&(u-=p(3)));let m=[a,o,s,c],g=Math.abs(u-d);t.wrap&&t.message&&(t.message=S.wrapLabel(t.message,h.getMax(g+2*Z.wrapPadding,Z.width),Pe(Z)));let _=S.calculateTextDimensions(t.message,Pe(Z));return{width:h.getMax(t.wrap?0:_.width+2*Z.wrapPadding,g+2*Z.wrapPadding,Z.width),height:0,startx:u,stopx:d,starty:0,stopy:0,message:t.message,type:t.type,wrap:t.wrap,fromBounds:Math.min.apply(null,m),toBounds:Math.max.apply(null,m)}},`buildMessageModel`),it=e(async function(e,n,r,i){let a={},o=[],s,c,l;for(let t of e){switch(t.type){case i.db.LINETYPE.LOOP_START:case i.db.LINETYPE.ALT_START:case i.db.LINETYPE.OPT_START:case i.db.LINETYPE.PAR_START:case i.db.LINETYPE.PAR_OVER_START:case i.db.LINETYPE.CRITICAL_START:case i.db.LINETYPE.BREAK_START:o.push({id:t.id,msg:t.message,from:2**53-1,to:-(2**53-1),width:0});break;case i.db.LINETYPE.ALT_ELSE:case i.db.LINETYPE.PAR_AND:case i.db.LINETYPE.CRITICAL_OPTION:t.message&&(s=o.pop(),a[s.id]=s,a[t.id]=s,o.push(s));break;case i.db.LINETYPE.LOOP_END:case i.db.LINETYPE.ALT_END:case i.db.LINETYPE.OPT_END:case i.db.LINETYPE.PAR_END:case i.db.LINETYPE.CRITICAL_END:case i.db.LINETYPE.BREAK_END:s=o.pop(),a[s.id]=s;break;case i.db.LINETYPE.ACTIVE_START:{let e=n.get(t.from?t.from:t.to.actor),r=Ue(t.from?t.from:t.to.actor).length,i=e.x+e.width/2+(r-1)*Z.activationWidth/2,a={startx:i,stopx:i+Z.activationWidth,actor:t.from,enabled:!0};Q.activations.push(a)}break;case i.db.LINETYPE.ACTIVE_END:{let e=Q.activations.map(e=>e.actor).lastIndexOf(t.from);Q.activations.splice(e,1).splice(0,1)}break}t.placement===void 0?(l=rt(t,n,i),t.msgModel=l,l.startx&&l.stopx&&o.length>0&&o.forEach(e=>{if(s=e,l.startx===l.stopx){let e=n.get(t.from),r=n.get(t.to);s.from=h.getMin(e.x-l.width/2,e.x-e.width/2,s.from),s.to=h.getMax(r.x+l.width/2,r.x+e.width/2,s.to),s.width=h.getMax(s.width,Math.abs(s.to-s.from))-Z.labelBoxWidth}else s.from=h.getMin(l.startx,s.from),s.to=h.getMax(l.stopx,s.to),s.width=h.getMax(s.width,l.width)-Z.labelBoxWidth})):(c=await Xe(t,n,i),t.noteModel=c,o.forEach(e=>{s=e,s.from=h.getMin(s.from,c.startx),s.to=h.getMax(s.to,c.startx+c.width),s.width=h.getMax(s.width,Math.abs(s.from-s.to))-Z.labelBoxWidth}))}return Q.activations=[],t.debug(`Loop type widths:`,a),a},`calculateLoopBounds`),at={parser:F,get db(){return new te},renderer:{bounds:Q,drawActors:Be,drawActorsPopup:Ve,setConf:He,draw:Ke},styles:ne,init:e(e=>{e.sequence||={},e.wrap&&(e.sequence.wrap=e.wrap,a({sequence:{wrap:e.wrap}}))},`init`)};export{at as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/sizeCapture-X5ZJPWSS-B0uUizjq.js b/dist-desktop/assets/sizeCapture-X5ZJPWSS-B0uUizjq.js new file mode 100644 index 0000000..ea2efbd --- /dev/null +++ b/dist-desktop/assets/sizeCapture-X5ZJPWSS-B0uUizjq.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";var t=1;function n(){if(!(typeof globalThis>`u`))return globalThis}e(n,`getCaptureGlobal`);function r(){return!!n()?.mermaidCaptureSizes}e(r,`shouldCaptureSizes`);function i(){return typeof location>`u`?`browser-dev`:`${location.pathname}${location.search}`}e(i,`capturedFromLocation`);function a(e,t){let r=n();if(!r)return;let i=t.node(),a=((i&&`ownerSVGElement`in i?i.ownerSVGElement:null)??i)?.id??`(unknown)`;r.mermaidCapturedSizes??=[];let o={svgId:a,sizes:e};r.mermaidCapturedSizes.push(o),r.mermaidLastCapturedSizes=o}e(a,`emitCapturedSizes`);function o(e,n){let r=[];for(let e of n.nodes)e.isGroup||r.push({id:e.id,width:e.width??0,height:e.height??0});r.length!==0&&a({metadata:{captureVersion:t,capturedAt:new Date().toISOString(),capturedFrom:i()},nodes:r},e)}e(o,`captureNodeSizes`);export{o as captureNodeSizes}; \ No newline at end of file diff --git a/dist-desktop/assets/src-UMNXGZaF.js b/dist-desktop/assets/src-UMNXGZaF.js new file mode 100644 index 0000000..ef716e8 --- /dev/null +++ b/dist-desktop/assets/src-UMNXGZaF.js @@ -0,0 +1 @@ +import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";var r=t(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs=r()})(e,(function(){var e=1e3,t=6e4,n=36e5,r=`millisecond`,i=`second`,a=`minute`,o=`hour`,s=`day`,c=`week`,l=`month`,u=`quarter`,d=`year`,f=`date`,p=`Invalid Date`,m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:`en`,weekdays:`Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday`.split(`_`),months:`January_February_March_April_May_June_July_August_September_October_November_December`.split(`_`),ordinal:function(e){var t=[`th`,`st`,`nd`,`rd`],n=e%100;return`[`+e+(t[(n-20)%10]||t[n]||t[0])+`]`}},_=function(e,t,n){var r=String(e);return!r||r.length>=t?e:``+Array(t+1-r.length).join(n)+e},v={s:_,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?`+`:`-`)+_(r,2,`0`)+`:`+_(i,2,`0`)},m:function e(t,n){if(t.date()1)return e(o[0])}else{var s=t.name;b[s]=t,i=s}return!r&&i&&(y=i),i||!r&&y},w=function(e,t){if(S(e))return e.clone();var n=typeof t==`object`?t:{};return n.date=e,n.args=arguments,new E(n)},T=v;T.l=C,T.i=S,T.w=function(e,t){return w(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var E=function(){function g(e){this.$L=C(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[x]=!0}var _=g.prototype;return _.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(t===null)return new Date(NaN);if(T.u(t))return new Date;if(t instanceof Date)return new Date(t);if(typeof t==`string`&&!/Z$/i.test(t)){var r=t.match(m);if(r){var i=r[2]-1||0,a=(r[7]||`0`).substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)}}return new Date(t)}(e),this.init()},_.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},_.$utils=function(){return T},_.isValid=function(){return this.$d.toString()!==p},_.isSame=function(e,t){var n=w(e);return this.startOf(t)<=n&&n<=this.endOf(t)},_.isAfter=function(e,t){return w(e){},`trace`),debug:n((...e)=>{},`debug`),info:n((...e)=>{},`info`),warn:n((...e)=>{},`warn`),error:n((...e)=>{},`error`),fatal:n((...e)=>{},`fatal`)},s=n(function(e=`fatal`){let t=a.fatal;typeof e==`string`?e.toLowerCase()in a&&(t=a[e]):typeof e==`number`&&(t=e),o.trace=()=>{},o.debug=()=>{},o.info=()=>{},o.warn=()=>{},o.error=()=>{},o.fatal=()=>{},t<=a.fatal&&(o.fatal=console.error?console.error.bind(console,c(`FATAL`),`color: orange`):console.log.bind(console,`\x1B[35m`,c(`FATAL`))),t<=a.error&&(o.error=console.error?console.error.bind(console,c(`ERROR`),`color: orange`):console.log.bind(console,`\x1B[31m`,c(`ERROR`))),t<=a.warn&&(o.warn=console.warn?console.warn.bind(console,c(`WARN`),`color: orange`):console.log.bind(console,`\x1B[33m`,c(`WARN`))),t<=a.info&&(o.info=console.info?console.info.bind(console,c(`INFO`),`color: lightblue`):console.log.bind(console,`\x1B[34m`,c(`INFO`))),t<=a.debug&&(o.debug=console.debug?console.debug.bind(console,c(`DEBUG`),`color: lightgreen`):console.log.bind(console,`\x1B[32m`,c(`DEBUG`))),t<=a.trace&&(o.trace=console.debug?console.debug.bind(console,c(`TRACE`),`color: lightgreen`):console.log.bind(console,`\x1B[32m`,c(`TRACE`)))},`setLogLevel`),c=n(e=>`%c${(0,i.default)().format(`ss.SSS`)} : ${e} : `,`format`),l={value:()=>{}};function u(){for(var e=0,t=arguments.length,n={},r;e=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw Error(`unknown type: `+e);return{type:e,name:n}})}d.prototype=u.prototype={constructor:d,on:function(e,t){var n=this._,r=f(e+``,n),i,a=-1,o=r.length;if(arguments.length<2){for(;++a0)for(var n=Array(i),r=0,i,a;r=0&&(t=e.slice(0,n))!==`xmlns`&&(e=e.slice(n+1)),h.hasOwnProperty(t)?{space:h[t],local:e}:e}function _(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===`http://www.w3.org/1999/xhtml`&&t.documentElement.namespaceURI===`http://www.w3.org/1999/xhtml`?t.createElement(e):t.createElementNS(n,e)}}function v(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function y(e){var t=g(e);return(t.local?v:_)(t)}function b(){}function x(e){return e==null?b:function(){return this.querySelector(e)}}function S(e){typeof e!=`function`&&(e=x(e));for(var t=this._groups,n=t.length,r=Array(n),i=0;i=v&&(v=_+1);!(b=g[v])&&++v=0;)(o=r[i])&&(a&&o.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(o,a),a=o);return this}function we(e){e||=Te;function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}for(var n=this._groups,r=n.length,i=Array(r),a=0;at?1:e>=t?0:NaN}function Ee(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function De(){return Array.from(this)}function Oe(){for(var e=this._groups,t=0,n=e.length;t1?this.each((t==null?Be:typeof t==`function`?He:Ve)(e,t,n??``)):O(this.node(),e)}function O(e,t){return e.style.getPropertyValue(t)||ze(e).getComputedStyle(e,null).getPropertyValue(t)}function We(e){return function(){delete this[e]}}function Ge(e,t){return function(){this[e]=t}}function Ke(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function qe(e,t){return arguments.length>1?this.each((t==null?We:typeof t==`function`?Ke:Ge)(e,t)):this.node()[e]}function Je(e){return e.trim().split(/^|\s+/)}function Ye(e){return e.classList||new Xe(e)}function Xe(e){this._node=e,this._names=Je(e.getAttribute(`class`)||``)}Xe.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute(`class`,this._names.join(` `)))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute(`class`,this._names.join(` `)))},contains:function(e){return this._names.indexOf(e)>=0}};function Ze(e,t){for(var n=Ye(e),r=-1,i=t.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}function Et(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,a;n>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?L(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?L(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Vt.exec(e))?new R(t[1],t[2],t[3],1):(t=Ht.exec(e))?new R(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Ut.exec(e))?L(t[1],t[2],t[3],t[4]):(t=Wt.exec(e))?L(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Gt.exec(e))?an(t[1],t[2]/100,t[3]/100,1):(t=Kt.exec(e))?an(t[1],t[2]/100,t[3]/100,t[4]):qt.hasOwnProperty(e)?Qt(qt[e]):e===`transparent`?new R(NaN,NaN,NaN,0):null}function Qt(e){return new R(e>>16&255,e>>8&255,e&255,1)}function L(e,t,n,r){return r<=0&&(e=t=n=NaN),new R(e,t,n,r)}function $t(e){return e instanceof j||(e=I(e)),e?(e=e.rgb(),new R(e.r,e.g,e.b,e.opacity)):new R}function en(e,t,n,r){return arguments.length===1?$t(e):new R(e,t,n,r??1)}function R(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Lt(R,en,Rt(j,{brighter(e){return e=e==null?zt:zt**+e,new R(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?M:M**+e,new R(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new R(B(this.r),B(this.g),B(this.b),z(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:tn,formatHex:tn,formatHex8:nn,formatRgb:rn,toString:rn}));function tn(){return`#${V(this.r)}${V(this.g)}${V(this.b)}`}function nn(){return`#${V(this.r)}${V(this.g)}${V(this.b)}${V((isNaN(this.opacity)?1:this.opacity)*255)}`}function rn(){let e=z(this.opacity);return`${e===1?`rgb(`:`rgba(`}${B(this.r)}, ${B(this.g)}, ${B(this.b)}${e===1?`)`:`, ${e})`}`}function z(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function B(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function V(e){return e=B(e),(e<16?`0`:``)+e.toString(16)}function an(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new H(e,t,n,r)}function on(e){if(e instanceof H)return new H(e.h,e.s,e.l,e.opacity);if(e instanceof j||(e=I(e)),!e)return new H;if(e instanceof H)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=t===a?(n-r)/s+(n0&&c<1?0:o,new H(o,s,c,e.opacity)}function sn(e,t,n,r){return arguments.length===1?on(e):new H(e,t,n,r??1)}function H(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Lt(H,sn,Rt(j,{brighter(e){return e=e==null?zt:zt**+e,new H(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?M:M**+e,new H(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new R(ln(e>=240?e-240:e+120,i,r),ln(e,i,r),ln(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new H(cn(this.h),U(this.s),U(this.l),z(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=z(this.opacity);return`${e===1?`hsl(`:`hsla(`}${cn(this.h)}, ${U(this.s)*100}%, ${U(this.l)*100}%${e===1?`)`:`, ${e})`}`}}));function cn(e){return e=(e||0)%360,e<0?e+360:e}function U(e){return Math.max(0,Math.min(1,e||0))}function ln(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}var un=e=>()=>e;function dn(e,t){return function(n){return e+n*t}}function fn(e,t,n){return e**=+n,t=t**+n-e,n=1/n,function(r){return(e+r*t)**+n}}function pn(e,t){var n=t-e;return n?dn(e,n>180||n<-180?n-360*Math.round(n/360):n):un(isNaN(e)?t:e)}function mn(e){return(e=+e)==1?hn:function(t,n){return n-t?fn(t,n,e):un(isNaN(t)?n:t)}}function hn(e,t){var n=t-e;return n?dn(e,n):un(isNaN(e)?t:e)}var gn=(function e(t){var n=mn(t);function r(e,t){var r=n((e=en(e)).r,(t=en(t)).r),i=n(e.g,t.g),a=n(e.b,t.b),o=hn(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=i(t),e.b=a(t),e.opacity=o(t),e+``}}return r.gamma=e,r})(1);function W(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var _n=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,vn=new RegExp(_n.source,`g`);function yn(e){return function(){return e}}function bn(e){return function(t){return e(t)+``}}function xn(e,t){var n=_n.lastIndex=vn.lastIndex=0,r,i,a,o=-1,s=[],c=[];for(e+=``,t+=``;(r=_n.exec(e))&&(i=vn.exec(t));)(a=i.index)>n&&(a=t.slice(n,a),s[o]?s[o]+=a:s[++o]=a),(r=r[0])===(i=i[0])?s[o]?s[o]+=i:s[++o]=i:(s[++o]=null,c.push({i:o,x:W(r,i)})),n=vn.lastIndex;return n180?t+=360:t-e>180&&(e+=360),a.push({i:n.push(i(n)+`rotate(`,null,r)-2,x:W(e,t)}))}function s(e,t,n,a){e===t?t&&n.push(i(n)+`skewX(`+t+r):a.push({i:n.push(i(n)+`skewX(`,null,r)-2,x:W(e,t)})}function c(e,t,n,r,a,o){if(e!==n||t!==r){var s=a.push(i(a)+`scale(`,null,`,`,null,`)`);o.push({i:s-4,x:W(e,n)},{i:s-2,x:W(t,r)})}else(n!==1||r!==1)&&a.push(i(a)+`scale(`+n+`,`+r+`)`)}return function(t,n){var r=[],i=[];return t=e(t),n=e(n),a(t.translateX,t.translateY,n.translateX,n.translateY,r,i),o(t.rotate,n.rotate,r,i),s(t.skewX,n.skewX,r,i),c(t.scaleX,t.scaleY,n.scaleX,n.scaleY,r,i),t=n=null,function(e){for(var t=-1,n=i.length,a;++t=0&&e._call.call(void 0,t),e=e._next;--G}function Un(){q=(Fn=J.now())+In,G=jn=0;try{Hn()}finally{G=0,Gn(),q=0}}function Wn(){var e=J.now(),t=e-Fn;t>Nn&&(In-=t,Fn=e)}function Gn(){for(var e,t=Pn,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Pn=n);K=e,Kn(r)}function Kn(e){G||(jn&&=clearTimeout(jn),e-q>24?(e<1/0&&(jn=setTimeout(Un,e-J.now()-In)),Mn&&=clearInterval(Mn)):(Mn||=(Fn=J.now(),setInterval(Wn,Nn)),G=1,Ln(Un)))}function qn(e,t,n){var r=new Bn;return t=t==null?0:+t,r.restart(n=>{r.stop(),e(n+t)},t,n),r}var Jn=u(`start`,`end`,`cancel`,`interrupt`),Yn=[];function Xn(e,t,n,r,i,a){var o=e.__transition;if(!o)e.__transition={};else if(n in o)return;Qn(e,n,{name:t,index:r,group:i,on:Jn,tween:Yn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:0})}function Zn(e,t){var n=X(e,t);if(n.state>0)throw Error(`too late; already scheduled`);return n}function Y(e,t){var n=X(e,t);if(n.state>3)throw Error(`too late; already running`);return n}function X(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw Error(`transition not found`);return n}function Qn(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=Vn(a,0,n.time);function a(e){n.state=1,n.timer.restart(o,n.delay,n.time),n.delay<=e&&o(e-n.delay)}function o(a){var l,u,d,f;if(n.state!==1)return c();for(l in r)if(f=r[l],f.name===n.name){if(f.state===3)return qn(o);f.state===4?(f.state=6,f.timer.stop(),f.on.call(`interrupt`,e,e.__data__,f.index,f.group),delete r[l]):+l2&&r.state<5,r.state=6,r.timer.stop(),r.on.call(i?`interrupt`:`cancel`,e,e.__data__,r.index,r.group),delete n[o]}a&&delete e.__transition}}function er(e){return this.each(function(){$n(this,e)})}function tr(e,t){var n,r;return function(){var i=Y(this,e),a=i.tween;if(a!==n){r=n=a;for(var o=0,s=r.length;o=0&&(e=e.slice(0,t)),!e||e===`start`})}function jr(e,t,n){var r,i,a=Ar(t)?Zn:Y;return function(){var o=a(this,e),s=o.on;s!==r&&(i=(r=s).copy()).on(t,n),o.on=i}}function Mr(e,t){var n=this._id;return arguments.length<2?X(this.node(),n).on.on(e):this.each(jr(n,e,t))}function Nr(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function Pr(){return this.on(`end.remove`,Nr(this._id))}function Fr(e){var t=this._name,n=this._id;typeof e!=`function`&&(e=x(e));for(var r=this._groups,i=r.length,a=Array(i),o=0;oe.append(`circle`).attr(`class`,`start-state`).attr(`r`,o().state.sizeUnit).attr(`cx`,o().state.padding+o().state.sizeUnit).attr(`cy`,o().state.padding+o().state.sizeUnit),`drawStartState`),g=e(e=>e.append(`line`).style(`stroke`,`grey`).style(`stroke-dasharray`,`3`).attr(`x1`,o().state.textHeight).attr(`class`,`divider`).attr(`x2`,o().state.textHeight*2).attr(`y1`,0).attr(`y2`,0),`drawDivider`),_=e((e,t)=>{let n=e.append(`text`).attr(`x`,2*o().state.padding).attr(`y`,o().state.textHeight+2*o().state.padding).attr(`font-size`,o().state.fontSize).attr(`class`,`state-title`).text(t.id),r=n.node().getBBox();return e.insert(`rect`,`:first-child`).attr(`x`,o().state.padding).attr(`y`,o().state.padding).attr(`width`,r.width+2*o().state.padding).attr(`height`,r.height+2*o().state.padding).attr(`rx`,o().state.radius),n},`drawSimpleState`),v=e((t,n)=>{let r=e(function(e,t,n){let r=e.append(`tspan`).attr(`x`,2*o().state.padding).text(t);n||r.attr(`dy`,o().state.textHeight)},`addTspan`),i=t.append(`text`).attr(`x`,2*o().state.padding).attr(`y`,o().state.textHeight+1.3*o().state.padding).attr(`font-size`,o().state.fontSize).attr(`class`,`state-title`).text(n.descriptions[0]).node().getBBox(),a=i.height,s=t.append(`text`).attr(`x`,o().state.padding).attr(`y`,a+o().state.padding*.4+o().state.dividerMargin+o().state.textHeight).attr(`class`,`state-description`),c=!0,l=!0;n.descriptions.forEach(function(e){c||(r(s,e,l),l=!1),c=!1});let u=t.append(`line`).attr(`x1`,o().state.padding).attr(`y1`,o().state.padding+a+o().state.dividerMargin/2).attr(`y2`,o().state.padding+a+o().state.dividerMargin/2).attr(`class`,`descr-divider`),d=s.node().getBBox(),f=Math.max(d.width,i.width);return u.attr(`x2`,f+3*o().state.padding),t.insert(`rect`,`:first-child`).attr(`x`,o().state.padding).attr(`y`,o().state.padding).attr(`width`,f+2*o().state.padding).attr(`height`,d.height+a+2*o().state.padding).attr(`rx`,o().state.radius),t},`drawDescrState`),y=e((e,t,n)=>{let r=o().state.padding,i=2*o().state.padding,a=e.node().getBBox(),s=a.width,c=a.x,l=e.append(`text`).attr(`x`,0).attr(`y`,o().state.titleShift).attr(`font-size`,o().state.fontSize).attr(`class`,`state-title`).text(t.id),u=l.node().getBBox().width+i,d=Math.max(u,s);d===s&&(d+=i);let f,p=e.node().getBBox();t.doc,f=c-r,u>s&&(f=(s-d)/2+r),Math.abs(c-p.x)s&&(f=c-(u-s)/2);let m=1-o().state.textHeight;return e.insert(`rect`,`:first-child`).attr(`x`,f).attr(`y`,m).attr(`class`,n?`alt-composit`:`composit`).attr(`width`,d).attr(`height`,p.height+o().state.textHeight+o().state.titleShift+1).attr(`rx`,`0`),l.attr(`x`,f+r),u<=s&&l.attr(`x`,c+(d-i)/2-u/2+r),e.insert(`rect`,`:first-child`).attr(`x`,f).attr(`y`,o().state.titleShift-o().state.textHeight-o().state.padding).attr(`width`,d).attr(`height`,o().state.textHeight*3).attr(`rx`,o().state.radius),e.insert(`rect`,`:first-child`).attr(`x`,f).attr(`y`,o().state.titleShift-o().state.textHeight-o().state.padding).attr(`width`,d).attr(`height`,p.height+3+2*o().state.textHeight).attr(`rx`,o().state.radius),e},`addTitleAndBox`),b=e(e=>(e.append(`circle`).attr(`class`,`end-state-outer`).attr(`r`,o().state.sizeUnit+o().state.miniPadding).attr(`cx`,o().state.padding+o().state.sizeUnit+o().state.miniPadding).attr(`cy`,o().state.padding+o().state.sizeUnit+o().state.miniPadding),e.append(`circle`).attr(`class`,`end-state-inner`).attr(`r`,o().state.sizeUnit).attr(`cx`,o().state.padding+o().state.sizeUnit+2).attr(`cy`,o().state.padding+o().state.sizeUnit+2)),`drawEndState`),x=e((e,t)=>{let n=o().state.forkWidth,r=o().state.forkHeight;if(t.parentId){let e=n;n=r,r=e}return e.append(`rect`).style(`stroke`,`black`).style(`fill`,`black`).attr(`width`,n).attr(`height`,r).attr(`x`,o().state.padding).attr(`y`,o().state.padding)},`drawForkJoinState`),S=e((e,t,n,r)=>{let i=0,s=r.append(`text`);s.style(`text-anchor`,`start`),s.attr(`class`,`noteText`);let c=e.replace(/\r\n/g,`
    `);c=c.replace(/\n/g,`
    `);let l=c.split(a.lineBreakRegex),u=1.25*o().state.noteMargin;for(let e of l){let r=e.trim();if(r.length>0){let e=s.append(`tspan`);if(e.text(r),u===0){let t=e.node().getBBox();u+=t.height}i+=u,e.attr(`x`,t+o().state.noteMargin),e.attr(`y`,n+i+1.25*o().state.noteMargin)}}return{textWidth:s.node().getBBox().width,textHeight:i}},`_drawLongText`),C=e((e,t)=>{t.attr(`class`,`state-note`);let n=t.append(`rect`).attr(`x`,0).attr(`y`,o().state.padding),{textWidth:r,textHeight:i}=S(e,0,0,t.append(`g`));return n.attr(`height`,i+2*o().state.noteMargin),n.attr(`width`,r+o().state.noteMargin*2),n},`drawNote`),w=e(function(e,t){let n=t.id,r={id:n,label:t.id,width:0,height:0},i=e.append(`g`).attr(`id`,n).attr(`class`,`stateGroup`);t.type===`start`&&h(i),t.type===`end`&&b(i),(t.type===`fork`||t.type===`join`)&&x(i,t),t.type===`note`&&C(t.note.text,i),t.type===`divider`&&g(i),t.type==="default"&&t.descriptions.length===0&&_(i,t),t.type==="default"&&t.descriptions.length>0&&v(i,t);let a=i.node().getBBox();return r.width=a.width+2*o().state.padding,r.height=a.height+2*o().state.padding,r},`drawState`),T=0,E=e(function(n,i,u){let d=e(function(e){switch(e){case m.relationType.AGGREGATION:return`aggregation`;case m.relationType.EXTENSION:return`extension`;case m.relationType.COMPOSITION:return`composition`;case m.relationType.DEPENDENCY:return`dependency`}},`getRelationType`);i.points=i.points.filter(e=>!Number.isNaN(e.y));let f=i.points,p=l().x(function(e){return e.x}).y(function(e){return e.y}).curve(s),h=n.append(`path`).attr(`d`,p(f)).attr(`id`,`edge`+T).attr(`class`,`transition`),g=``;if(o().state.arrowMarkerAbsolute&&(g=r(!0)),h.attr(`marker-end`,`url(`+g+`#`+d(m.relationType.DEPENDENCY)+`End)`),u.title!==void 0){let e=n.append(`g`).attr(`class`,`stateLabel`),{x:r,y:s}=c.calcLabelPosition(i.points),l=a.getRows(u.title),d=0,f=[],p=0,m=0;for(let n=0;n<=l.length;n++){let i=e.append(`text`).attr(`text-anchor`,`middle`).text(l[n]).attr(`x`,r).attr(`y`,s+d),a=i.node().getBBox();p=Math.max(p,a.width),m=Math.min(m,a.x),t.info(a.x,r,s+d),d===0&&(d=i.node().getBBox().height,t.info(`Title height`,d,s)),f.push(i)}let h=d*l.length;if(l.length>1){let e=(l.length-1)*d*.5;f.forEach((t,n)=>t.attr(`y`,s+n*d-e)),h=d*l.length}let g=e.node().getBBox();e.insert(`rect`,`:first-child`).attr(`class`,`box`).attr(`x`,r-p/2-o().state.padding/2).attr(`y`,s-h/2-o().state.padding/2-3.5).attr(`width`,p+o().state.padding).attr(`height`,h+o().state.padding),t.info(g)}T++},`drawEdge`),D,O={},k=e(function(){},`setConf`),A=e(function(e){e.append(`defs`).append(`marker`).attr(`id`,`dependencyEnd`).attr(`refX`,19).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L9,13 L14,7 L9,1 Z`)},`insertMarkers`),j=e(function(e,r,a,s){D=o().state;let c=o().securityLevel,l;c===`sandbox`&&(l=n(`#i`+r));let u=n(c===`sandbox`?l.nodes()[0].contentDocument.body:`body`),d=c===`sandbox`?l.nodes()[0].contentDocument:document;t.debug(`Rendering diagram `+e);let f=u.select(`[id='${r}']`);A(f),N(s.db.getRootDoc(),f.append(`g`).attr(`id`,r+`-root`),void 0,!1,u,d,s);let p=D.padding,m=f.node().getBBox(),h=m.width+p*2,g=m.height+p*2;i(f,g,h*1.75,D.useMaxWidth),f.attr(`viewBox`,`${m.x-D.padding} ${m.y-D.padding} `+h+` `+g)},`draw`),M=e(e=>e?e.length*D.fontSizeFactor:1,`getLabelWidth`),N=e((e,n,r,i,o,s,c)=>{let l=new u({compound:!0,multigraph:!0}),f,p=!0;for(f=0;f{let t=e.parentElement,n=0,r=0;t&&(t.parentElement&&(n=t.parentElement.getBBox().width),r=parseInt(t.getAttribute(`data-x-shift`),10),Number.isNaN(r)&&(r=0)),e.setAttribute(`x1`,0-r+8),e.setAttribute(`x2`,n-r-8)})):t.debug(`No Node `+e+`: `+JSON.stringify(l.node(e)))});let b=v.getBBox();l.edges().forEach(function(e){e!==void 0&&l.edge(e)!==void 0&&(t.debug(`Edge `+e.v+` -> `+e.w+`: `+JSON.stringify(l.edge(e))),E(n,l.edge(e),l.edge(e).relation))}),b=v.getBBox();let x={id:r||`root`,label:r||`root`,width:0,height:0};return x.width=b.width+2*D.padding,x.height=b.height+2*D.padding,t.debug(`Doc rendered`,x,l),x},`renderDoc`),P={parser:p,get db(){return new m(1)},renderer:{setConf:k,draw:j},styles:f,init:e(e=>{e.state||={},e.state.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{P as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js b/dist-desktop/assets/stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js new file mode 100644 index 0000000..a370a28 --- /dev/null +++ b/dist-desktop/assets/stateDiagram-v2-6OUMAXLB-CR3Ef9C0.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import{i as t,n,r,t as i}from"./chunk-EX3LRPZG-CzaF5a2T.js";var a={parser:n,get db(){return new i(2)},renderer:r,styles:t,init:e(e=>{e.state||={},e.state.arrowMarkerAbsolute=e.arrowMarkerAbsolute},`init`)};export{a as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/styles-Peq6Rcdg.css b/dist-desktop/assets/styles-Peq6Rcdg.css new file mode 100644 index 0000000..e9b9b31 --- /dev/null +++ b/dist-desktop/assets/styles-Peq6Rcdg.css @@ -0,0 +1,2 @@ +/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-pan-x:initial;--tw-pan-y:initial;--tw-pinch-zoom:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0}}}@layer theme{:root,:host{--font-sans:"Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, -apple-system, sans-serif;--font-mono:ui-monospace, "SF Mono", Menlo, Consolas, monospace;--color-orange-100:oklch(95.4% .038 75.164);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-950:oklch(27.9% .077 45.635);--color-emerald-200:oklch(90.5% .093 164.15);--color-emerald-300:oklch(84.5% .143 164.978);--color-emerald-500:oklch(69.6% .17 162.48);--color-emerald-600:oklch(59.6% .145 163.225);--color-emerald-700:oklch(50.8% .118 165.612);--color-emerald-800:oklch(43.2% .095 166.913);--color-emerald-900:oklch(37.8% .077 168.94);--color-sky-100:oklch(95.1% .026 236.824);--color-slate-200:oklch(92.9% .013 255.508);--color-zinc-200:oklch(92% .004 286.32);--color-zinc-800:oklch(27.4% .006 286.033);--color-neutral-100:oklch(97% 0 none);--color-neutral-300:oklch(87% 0 none);--color-neutral-500:oklch(55.6% 0 none);--color-neutral-700:oklch(37.1% 0 none);--color-neutral-800:oklch(26.9% 0 none);--color-neutral-900:oklch(20.5% 0 none);--color-stone-50:oklch(98.5% .001 106.423);--color-stone-100:oklch(97% .001 106.424);--color-stone-200:oklch(92.3% .003 48.717);--color-stone-700:oklch(37.4% .01 67.558);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-2xl:42rem;--container-3xl:48rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wide:.025em;--tracking-widest:.1em;--leading-tight:1.25;--leading-snug:1.375;--leading-normal:1.5;--leading-relaxed:1.625;--radius-xs:.125rem;--radius-sm:.375rem;--radius-md:.5rem;--radius-lg:.75rem;--radius-xl:1rem;--radius-2xl:1rem;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-background:#fff;--color-foreground:#1a1a1a;--color-card:#fff;--color-popover:#fff;--color-popover-foreground:#1a1a1a;--color-primary:#1a1a1a;--color-primary-foreground:#fafafa;--color-secondary:#f2f1ee;--color-secondary-foreground:#1a1a1a;--color-muted:#f2f1ee;--color-muted-foreground:#6b6b6b;--color-accent:#f2f1ee;--color-destructive:#c2410c;--color-destructive-foreground:#fafafa;--color-border:#e8e7e4;--color-input:#e8e7e4;--color-ring:#a3a3a3;--color-sidebar:#f7f6f3;--color-sidebar-fg:#3f3f3f;--color-sidebar-border:#ebeae6;--color-sidebar-hover:#efeee9;--color-sidebar-active:#e8e7e2}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{border-color:var(--color-border)}html{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizelegibility}body{background-color:var(--color-background);font-family:var(--font-sans);color:var(--color-foreground);min-height:100dvh;margin:0}button:not(:disabled),[role=button]:not(:disabled){cursor:pointer}[contenteditable]:empty:before{content:attr(data-placeholder);color:#6b6b6b8c}@supports (color:color-mix(in lab, red, red)){[contenteditable]:empty:before{color:color-mix(in oklab, var(--color-muted-foreground) 55%, transparent)}}[contenteditable]:empty:before{pointer-events:none}*{scrollbar-width:thin;scrollbar-color:#1a1a1a2e transparent}@supports (color:color-mix(in lab, red, red)){*{scrollbar-color:color-mix(in oklab, var(--color-foreground) 18%, transparent) transparent}}}@layer components;@layer utilities{.\@container{container-type:inline-size}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.not-sr-only{clip-path:none;white-space:normal;width:auto;height:auto;margin:0;padding:0;position:static;overflow:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:0}.inset-y-0{inset-block:0}.top-1{top:var(--spacing)}.top-1\/2{top:50%}.top-3{top:calc(var(--spacing) * 3)}.top-\[18\%\]{top:18%}.right-1{right:var(--spacing)}.right-2{right:calc(var(--spacing) * 2)}.right-3{right:calc(var(--spacing) * 3)}.right-4{right:calc(var(--spacing) * 4)}.bottom-3{bottom:calc(var(--spacing) * 3)}.-left-12{left:calc(var(--spacing) * -12)}.left-0{left:0}.left-1{left:var(--spacing)}.left-1\/2{left:50%}.left-2{left:calc(var(--spacing) * 2)}.left-3{left:calc(var(--spacing) * 3)}.left-4{left:calc(var(--spacing) * 4)}.isolate{isolation:isolate}.isolation-auto{isolation:auto}.z-0{z-index:0}.z-10{z-index:10}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[120\]{z-index:120}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.-mx-4{margin-inline:calc(var(--spacing) * -4)}.mx-3{margin-inline:calc(var(--spacing) * 3)}.mx-auto{margin-inline:auto}.my-1{margin-block:var(--spacing)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-2\.5{margin-top:calc(var(--spacing) * 2.5)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mr-1{margin-right:var(--spacing)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mb-0\.5{margin-bottom:calc(var(--spacing) * .5)}.mb-1{margin-bottom:var(--spacing)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.ml-1{margin-left:var(--spacing)}.ml-10{margin-left:calc(var(--spacing) * 10)}.ml-auto{margin-left:auto}.ml-px{margin-left:1px}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-4{-webkit-line-clamp:4;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.block{display:block}.contents{display:contents}.flex{display:flex}.flow-root{display:flow-root}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.inline-grid{display:inline-grid}.inline-table{display:inline-table}.list-item{display:list-item}.table{display:table}.table-caption{display:table-caption}.table-cell{display:table-cell}.table-column{display:table-column}.table-column-group{display:table-column-group}.table-footer-group{display:table-footer-group}.table-header-group{display:table-header-group}.table-row{display:table-row}.table-row-group{display:table-row-group}.size-1{width:var(--spacing);height:var(--spacing)}.size-1\.5{width:calc(var(--spacing) * 1.5);height:calc(var(--spacing) * 1.5)}.size-2{width:calc(var(--spacing) * 2);height:calc(var(--spacing) * 2)}.size-3{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.size-3\.5{width:calc(var(--spacing) * 3.5);height:calc(var(--spacing) * 3.5)}.size-4{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.size-5{width:calc(var(--spacing) * 5);height:calc(var(--spacing) * 5)}.size-6{width:calc(var(--spacing) * 6);height:calc(var(--spacing) * 6)}.size-7{width:calc(var(--spacing) * 7);height:calc(var(--spacing) * 7)}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.size-9{width:calc(var(--spacing) * 9);height:calc(var(--spacing) * 9)}.size-12{width:calc(var(--spacing) * 12);height:calc(var(--spacing) * 12)}.size-16{width:calc(var(--spacing) * 16);height:calc(var(--spacing) * 16)}.h-2{height:calc(var(--spacing) * 2)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-11{height:calc(var(--spacing) * 11)}.h-12{height:calc(var(--spacing) * 12)}.h-36{height:calc(var(--spacing) * 36)}.h-40{height:calc(var(--spacing) * 40)}.h-84{height:calc(var(--spacing) * 84)}.h-120{height:calc(var(--spacing) * 120)}.h-dvh{height:100dvh}.h-full{height:100%}.h-px{height:1px}.max-h-40{max-height:calc(var(--spacing) * 40)}.max-h-48{max-height:calc(var(--spacing) * 48)}.max-h-64{max-height:calc(var(--spacing) * 64)}.max-h-72{max-height:calc(var(--spacing) * 72)}.max-h-80{max-height:calc(var(--spacing) * 80)}.max-h-\[90vh\]{max-height:90vh}.min-h-0{min-height:0}.min-h-16{min-height:calc(var(--spacing) * 16)}.min-h-\[64px\]{min-height:64px}.min-h-dvh{min-height:100dvh}.min-h-screen{min-height:100vh}.w-0{width:0}.w-2{width:calc(var(--spacing) * 2)}.w-5{width:calc(var(--spacing) * 5)}.w-7{width:calc(var(--spacing) * 7)}.w-8{width:calc(var(--spacing) * 8)}.w-48{width:calc(var(--spacing) * 48)}.w-72{width:calc(var(--spacing) * 72)}.w-\[260px\]{width:260px}.w-\[calc\(100\%-2\.5rem\)\]{width:calc(100% - 2.5rem)}.w-\[calc\(100\%-2rem\)\]{width:calc(100% - 2rem)}.w-\[min\(280px\,88vw\)\]{width:min(280px,88vw)}.w-\[min\(560px\,calc\(100\%-2rem\)\)\]{width:min(560px,100% - 2rem)}.w-full{width:100%}.w-px{width:1px}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-\[140px\]{max-width:140px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.min-w-0{min-width:0}.min-w-40{min-width:calc(var(--spacing) * 40)}.min-w-44{min-width:calc(var(--spacing) * 44)}.min-w-\[260px\]{min-width:260px}.flex-1{flex:1}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-none{translate:none}.scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x) var(--tw-scale-y)}.scale-3d{scale:var(--tw-scale-x) var(--tw-scale-y) var(--tw-scale-z)}.scale-\[0\.25\]{scale:.25}.rotate-90{rotate:90deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.transform\!{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)!important}.animate-in{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.cursor-text{cursor:text}.touch-pinch-zoom{--tw-pinch-zoom:pinch-zoom;touch-action:var(--tw-pan-x,) var(--tw-pan-y,) var(--tw-pinch-zoom,)}.touch-none{touch-action:none}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.grid-cols-8{grid-template-columns:repeat(8,minmax(0,1fr))}.grid-cols-\[auto_1fr\]{grid-template-columns:auto 1fr}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-0{gap:0}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-2\.5{gap:calc(var(--spacing) * 2.5)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(var(--spacing) * var(--tw-space-y-reverse));margin-block-end:calc(var(--spacing) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-reverse>:not(:last-child)){--tw-space-y-reverse:1}.gap-x-4{column-gap:calc(var(--spacing) * 4)}:where(.space-x-reverse>:not(:last-child)){--tw-space-x-reverse:1}.gap-y-2{row-gap:calc(var(--spacing) * 2)}:where(.divide-x>:not(:last-child)){--tw-divide-x-reverse:0;border-inline-style:var(--tw-border-style);border-inline-start-width:calc(1px * var(--tw-divide-x-reverse));border-inline-end-width:calc(1px * calc(1 - var(--tw-divide-x-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-y-reverse>:not(:last-child)){--tw-divide-y-reverse:1}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-s{border-start-start-radius:.25rem;border-end-start-radius:.25rem}.rounded-ss{border-start-start-radius:.25rem}.rounded-e{border-start-end-radius:.25rem;border-end-end-radius:.25rem}.rounded-se{border-start-end-radius:.25rem}.rounded-ee{border-end-end-radius:.25rem}.rounded-es{border-end-start-radius:.25rem}.rounded-t{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.rounded-l{border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.rounded-tl{border-top-left-radius:.25rem}.rounded-r{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.rounded-tr{border-top-right-radius:.25rem}.rounded-b{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.rounded-br{border-bottom-right-radius:.25rem}.rounded-bl{border-bottom-left-radius:.25rem}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-x{border-inline-style:var(--tw-border-style);border-inline-width:1px}.border-y{border-block-style:var(--tw-border-style);border-block-width:1px}.border-s{border-inline-start-style:var(--tw-border-style);border-inline-start-width:1px}.border-e{border-inline-end-style:var(--tw-border-style);border-inline-end-width:1px}.border-bs{border-block-start-style:var(--tw-border-style);border-block-start-width:1px}.border-be{border-block-end-style:var(--tw-border-style);border-block-end-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-amber-500\/30{border-color:#f99c004d}@supports (color:color-mix(in lab, red, red)){.border-amber-500\/30{border-color:color-mix(in oklab, var(--color-amber-500) 30%, transparent)}}.border-border{border-color:var(--color-border)}.border-destructive\/30{border-color:#c2410c4d}@supports (color:color-mix(in lab, red, red)){.border-destructive\/30{border-color:color-mix(in oklab, var(--color-destructive) 30%, transparent)}}.border-emerald-500\/40{border-color:#00bb7f66}@supports (color:color-mix(in lab, red, red)){.border-emerald-500\/40{border-color:color-mix(in oklab, var(--color-emerald-500) 40%, transparent)}}.border-foreground{border-color:var(--color-foreground)}.border-foreground\/25{border-color:#1a1a1a40}@supports (color:color-mix(in lab, red, red)){.border-foreground\/25{border-color:color-mix(in oklab, var(--color-foreground) 25%, transparent)}}.border-neutral-300{border-color:var(--color-neutral-300)}.border-primary{border-color:var(--color-primary)}.border-sidebar-border{border-color:var(--color-sidebar-border)}.border-transparent{border-color:#0000}.border-t-transparent{border-top-color:#0000}.border-l-transparent{border-left-color:#0000}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab, red, red)){.bg-amber-500\/10{background-color:color-mix(in oklab, var(--color-amber-500) 10%, transparent)}}.bg-background{background-color:var(--color-background)}.bg-background\/90{background-color:#ffffffe6}@supports (color:color-mix(in lab, red, red)){.bg-background\/90{background-color:color-mix(in oklab, var(--color-background) 90%, transparent)}}.bg-black{background-color:var(--color-black)}.bg-black\/5{background-color:#0000000d}@supports (color:color-mix(in lab, red, red)){.bg-black\/5{background-color:color-mix(in oklab, var(--color-black) 5%, transparent)}}.bg-black\/10{background-color:#0000001a}@supports (color:color-mix(in lab, red, red)){.bg-black\/10{background-color:color-mix(in oklab, var(--color-black) 10%, transparent)}}.bg-black\/40{background-color:#0006}@supports (color:color-mix(in lab, red, red)){.bg-black\/40{background-color:color-mix(in oklab, var(--color-black) 40%, transparent)}}.bg-border{background-color:var(--color-border)}.bg-card{background-color:var(--color-card)}.bg-destructive{background-color:var(--color-destructive)}.bg-destructive\/5{background-color:#c2410c0d}@supports (color:color-mix(in lab, red, red)){.bg-destructive\/5{background-color:color-mix(in oklab, var(--color-destructive) 5%, transparent)}}.bg-destructive\/10{background-color:#c2410c1a}@supports (color:color-mix(in lab, red, red)){.bg-destructive\/10{background-color:color-mix(in oklab, var(--color-destructive) 10%, transparent)}}.bg-emerald-500{background-color:var(--color-emerald-500)}.bg-emerald-500\/10{background-color:#00bb7f1a}@supports (color:color-mix(in lab, red, red)){.bg-emerald-500\/10{background-color:color-mix(in oklab, var(--color-emerald-500) 10%, transparent)}}.bg-emerald-500\/15{background-color:#00bb7f26}@supports (color:color-mix(in lab, red, red)){.bg-emerald-500\/15{background-color:color-mix(in oklab, var(--color-emerald-500) 15%, transparent)}}.bg-foreground{background-color:var(--color-foreground)}.bg-foreground\/80{background-color:#1a1a1acc}@supports (color:color-mix(in lab, red, red)){.bg-foreground\/80{background-color:color-mix(in oklab, var(--color-foreground) 80%, transparent)}}.bg-muted{background-color:var(--color-muted)}.bg-muted-foreground\/40{background-color:#6b6b6b66}@supports (color:color-mix(in lab, red, red)){.bg-muted-foreground\/40{background-color:color-mix(in oklab, var(--color-muted-foreground) 40%, transparent)}}.bg-muted\/20{background-color:#f2f1ee33}@supports (color:color-mix(in lab, red, red)){.bg-muted\/20{background-color:color-mix(in oklab, var(--color-muted) 20%, transparent)}}.bg-muted\/30{background-color:#f2f1ee4d}@supports (color:color-mix(in lab, red, red)){.bg-muted\/30{background-color:color-mix(in oklab, var(--color-muted) 30%, transparent)}}.bg-muted\/40{background-color:#f2f1ee66}@supports (color:color-mix(in lab, red, red)){.bg-muted\/40{background-color:color-mix(in oklab, var(--color-muted) 40%, transparent)}}.bg-muted\/50{background-color:#f2f1ee80}@supports (color:color-mix(in lab, red, red)){.bg-muted\/50{background-color:color-mix(in oklab, var(--color-muted) 50%, transparent)}}.bg-muted\/60{background-color:#f2f1ee99}@supports (color:color-mix(in lab, red, red)){.bg-muted\/60{background-color:color-mix(in oklab, var(--color-muted) 60%, transparent)}}.bg-popover{background-color:var(--color-popover)}.bg-primary{background-color:var(--color-primary)}.bg-secondary{background-color:var(--color-secondary)}.bg-sidebar{background-color:var(--color-sidebar)}.bg-sidebar-active{background-color:var(--color-sidebar-active)}.bg-transparent{background-color:#0000}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-slate-200{--tw-gradient-from:var(--color-slate-200);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-stone-200{--tw-gradient-from:var(--color-stone-200);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-zinc-200{--tw-gradient-from:var(--color-zinc-200);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-zinc-800{--tw-gradient-from:var(--color-zinc-800);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.via-amber-100\/80{--tw-gradient-via:#fef3c6cc}@supports (color:color-mix(in lab, red, red)){.via-amber-100\/80{--tw-gradient-via:color-mix(in oklab, var(--color-amber-100) 80%, transparent)}}.via-amber-100\/80{--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-neutral-100{--tw-gradient-via:var(--color-neutral-100);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-sky-100\/70{--tw-gradient-via:#dff2feb3}@supports (color:color-mix(in lab, red, red)){.via-sky-100\/70{--tw-gradient-via:color-mix(in oklab, var(--color-sky-100) 70%, transparent)}}.via-sky-100\/70{--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.via-stone-700{--tw-gradient-via:var(--color-stone-700);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-neutral-800{--tw-gradient-to:var(--color-neutral-800);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-orange-100\/60{--tw-gradient-to:#ffedd599}@supports (color:color-mix(in lab, red, red)){.to-orange-100\/60{--tw-gradient-to:color-mix(in oklab, var(--color-orange-100) 60%, transparent)}}.to-orange-100\/60{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-stone-50{--tw-gradient-to:var(--color-stone-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-stone-100{--tw-gradient-to:var(--color-stone-100);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.bg-repeat{background-repeat:repeat}.mask-no-clip{-webkit-mask-clip:no-clip;mask-clip:no-clip}.mask-repeat{-webkit-mask-repeat:repeat;mask-repeat:repeat}.fill-amber-400{fill:var(--color-amber-400)}.object-cover{object-fit:cover}.p-0{padding:0}.p-1{padding:var(--spacing)}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.p-\[16px\]{padding:16px}.p-px{padding:1px}.px-1{padding-inline:var(--spacing)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-3\.5{padding-inline:calc(var(--spacing) * 3.5)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-5{padding-block:calc(var(--spacing) * 5)}.py-8{padding-block:calc(var(--spacing) * 8)}.py-12{padding-block:calc(var(--spacing) * 12)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-6{padding-top:calc(var(--spacing) * 6)}.pr-1{padding-right:var(--spacing)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-3\.5{padding-right:calc(var(--spacing) * 3.5)}.pb-1{padding-bottom:var(--spacing)}.pb-32{padding-bottom:calc(var(--spacing) * 32)}.pl-1{padding-left:var(--spacing)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-7{padding-left:calc(var(--spacing) * 7)}.pl-8{padding-left:calc(var(--spacing) * 8)}.pl-10{padding-left:calc(var(--spacing) * 10)}.pl-12{padding-left:calc(var(--spacing) * 12)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[13px\]{font-size:13px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-snug{--tw-leading:var(--leading-snug);line-height:var(--leading-snug)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-balance{text-wrap:balance}.text-wrap{text-wrap:wrap}.text-clip{text-overflow:clip}.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-amber-500{color:var(--color-amber-500)}.text-amber-950{color:var(--color-amber-950)}.text-background{color:var(--color-background)}.text-destructive{color:var(--color-destructive)}.text-destructive-foreground{color:var(--color-destructive-foreground)}.text-emerald-600{color:var(--color-emerald-600)}.text-emerald-700{color:var(--color-emerald-700)}.text-emerald-800{color:var(--color-emerald-800)}.text-emerald-900{color:var(--color-emerald-900)}.text-foreground{color:var(--color-foreground)}.text-muted-foreground{color:var(--color-muted-foreground)}.text-neutral-500{color:var(--color-neutral-500)}.text-popover-foreground{color:var(--color-popover-foreground)}.text-primary-foreground{color:var(--color-primary-foreground)}.text-secondary-foreground{color:var(--color-secondary-foreground)}.text-sidebar-fg{color:var(--color-sidebar-fg)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.normal-case{text-transform:none}.uppercase{text-transform:uppercase}.italic{font-style:italic}.italic\!{font-style:italic!important}.not-italic{font-style:normal}.diagonal-fractions{--tw-numeric-fraction:diagonal-fractions;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.lining-nums{--tw-numeric-figure:lining-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.oldstyle-nums{--tw-numeric-figure:oldstyle-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.ordinal{--tw-ordinal:ordinal;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.proportional-nums{--tw-numeric-spacing:proportional-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.slashed-zero{--tw-slashed-zero:slashed-zero;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.stacked-fractions{--tw-numeric-fraction:stacked-fractions;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.normal-nums{font-variant-numeric:normal}.line-through{text-decoration-line:line-through}.no-underline{text-decoration-line:none}.overline{text-decoration-line:overline}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.subpixel-antialiased{-webkit-font-smoothing:auto;-moz-osx-font-smoothing:auto}.opacity-0{opacity:0}.opacity-1{opacity:.01}.opacity-40{opacity:.4}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-80{opacity:.8}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a), 0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-none{--tw-shadow:0 0 #0000;box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-0{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-1{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.inset-ring{--tw-inset-ring-shadow:inset 0 0 0 1px var(--tw-inset-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-border{--tw-ring-color:var(--color-border)}.ring-ring{--tw-ring-color:var(--color-ring)}.outline,.outline-1{outline-style:var(--tw-outline-style);outline-width:1px}.-outline-offset-1{outline-offset:calc(1px * -1)}.outline-black\/10{outline-color:#0000001a}@supports (color:color-mix(in lab, red, red)){.outline-black\/10{outline-color:color-mix(in oklab, var(--color-black) 10%, transparent)}}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.blur\!{--tw-blur:blur(8px)!important;filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)!important}.blur-\[4px\]{--tw-blur:blur(4px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.blur-none{--tw-blur: ;filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.drop-shadow{--tw-drop-shadow-size:drop-shadow(0 1px 2px var(--tw-drop-shadow-color,#0000001a)) drop-shadow(0 1px 1px var(--tw-drop-shadow-color,#0000000f));--tw-drop-shadow:drop-shadow(0 1px 2px #0000001a) drop-shadow(0 1px 1px #0000000f);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.grayscale{--tw-grayscale:grayscale(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.sepia{--tw-sepia:sepia(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-grayscale{--tw-backdrop-grayscale:grayscale(100%);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-invert{--tw-backdrop-invert:invert(100%);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-sepia{--tw-backdrop-sepia:sepia(100%);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[background-color\,color\,opacity\,box-shadow\,transform\]{transition-property:background-color,color,opacity,box-shadow,transform;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[box-shadow\]{transition-property:box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[opacity\,filter\,scale\]{transition-property:opacity,filter,scale;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[scale\,background-color\]{transition-property:scale,background-color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[scale\,opacity\,filter\]{transition-property:scale,opacity,filter;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[width\,opacity\]{transition-property:width,opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-\[cubic-bezier\(0\.2\,0\,0\,1\)\]{--tw-ease:cubic-bezier(.2,0,0,1);transition-timing-function:cubic-bezier(.2,0,0,1)}.ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.fade-in-0{--tw-enter-opacity:0}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.zoom-in-95{--tw-enter-scale:.95}:where(.divide-x-reverse>:not(:last-child)){--tw-divide-x-reverse:1}.paused{animation-play-state:paused}.ring-inset{--tw-ring-inset:inset}.running{animation-play-state:running}.zoom-in{--tw-enter-scale:0}.zoom-out{--tw-exit-scale:0}@media (hover:hover){.group-hover\:opacity-100:is(:where(.group):hover *),.group-hover\/cover\:opacity-100:is(:where(.group\/cover):hover *){opacity:1}}.placeholder\:text-muted-foreground::placeholder{color:var(--color-muted-foreground)}.placeholder\:text-muted-foreground\/50::placeholder{color:#6b6b6b80}@supports (color:color-mix(in lab, red, red)){.placeholder\:text-muted-foreground\/50::placeholder{color:color-mix(in oklab, var(--color-muted-foreground) 50%, transparent)}}.placeholder\:text-muted-foreground\/60::placeholder{color:#6b6b6b99}@supports (color:color-mix(in lab, red, red)){.placeholder\:text-muted-foreground\/60::placeholder{color:color-mix(in oklab, var(--color-muted-foreground) 60%, transparent)}}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:top-1\/2:after{content:var(--tw-content);top:50%}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:size-10:after{content:var(--tw-content);width:calc(var(--spacing) * 10);height:calc(var(--spacing) * 10)}.after\:-translate-1\/2:after{content:var(--tw-content);--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}@media (hover:hover){.hover\:border-border:hover{border-color:var(--color-border)}.hover\:border-foreground\/40:hover{border-color:#1a1a1a66}@supports (color:color-mix(in lab, red, red)){.hover\:border-foreground\/40:hover{border-color:color-mix(in oklab, var(--color-foreground) 40%, transparent)}}.hover\:bg-black\/5:hover{background-color:#0000000d}@supports (color:color-mix(in lab, red, red)){.hover\:bg-black\/5:hover{background-color:color-mix(in oklab, var(--color-black) 5%, transparent)}}.hover\:bg-destructive\/90:hover{background-color:#c2410ce6}@supports (color:color-mix(in lab, red, red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab, var(--color-destructive) 90%, transparent)}}.hover\:bg-muted:hover{background-color:var(--color-muted)}.hover\:bg-muted\/40:hover{background-color:#f2f1ee66}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/40:hover{background-color:color-mix(in oklab, var(--color-muted) 40%, transparent)}}.hover\:bg-muted\/70:hover{background-color:#f2f1eeb3}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/70:hover{background-color:color-mix(in oklab, var(--color-muted) 70%, transparent)}}.hover\:bg-muted\/80:hover{background-color:#f2f1eecc}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/80:hover{background-color:color-mix(in oklab, var(--color-muted) 80%, transparent)}}.hover\:bg-neutral-100:hover{background-color:var(--color-neutral-100)}.hover\:bg-primary\/90:hover{background-color:#1a1a1ae6}@supports (color:color-mix(in lab, red, red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab, var(--color-primary) 90%, transparent)}}.hover\:bg-secondary\/80:hover{background-color:#f2f1eecc}@supports (color:color-mix(in lab, red, red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab, var(--color-secondary) 80%, transparent)}}.hover\:bg-sidebar-hover:hover{background-color:var(--color-sidebar-hover)}.hover\:text-foreground:hover{color:var(--color-foreground)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}}.focus\:border-border:focus{border-color:var(--color-border)}.focus\:bg-background:focus{background-color:var(--color-background)}.focus\:bg-muted:focus{background-color:var(--color-muted)}.focus\:text-destructive:focus{color:var(--color-destructive)}.focus\:ring-0:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-ring\/30:focus{--tw-ring-color:#a3a3a34d}@supports (color:color-mix(in lab, red, red)){.focus\:ring-ring\/30:focus{--tw-ring-color:color-mix(in oklab, var(--color-ring) 30%, transparent)}}.focus\:ring-ring\/40:focus{--tw-ring-color:#a3a3a366}@supports (color:color-mix(in lab, red, red)){.focus\:ring-ring\/40:focus{--tw-ring-color:color-mix(in oklab, var(--color-ring) 40%, transparent)}}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-ring\/40:focus-visible{--tw-ring-color:#a3a3a366}@supports (color:color-mix(in lab, red, red)){.focus-visible\:ring-ring\/40:focus-visible{--tw-ring-color:color-mix(in oklab, var(--color-ring) 40%, transparent)}}.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.active\:scale-\[0\.96\]:active{scale:.96}.active\:scale-\[0\.98\]:active{scale:.98}.active\:not-disabled\:scale-\[0\.96\]:active:not(:disabled){scale:.96}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.aria-selected\:bg-muted[aria-selected=true]{background-color:var(--color-muted)}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=closed\]\:animate-out[data-state=closed]{animation:exit var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale:.95}.data-\[state\=open\]\:animate-in[data-state=open]{animation:enter var(--tw-animation-duration,var(--tw-duration,.15s))var(--tw-ease,ease)var(--tw-animation-delay,0s)var(--tw-animation-iteration-count,1)var(--tw-animation-direction,normal)var(--tw-animation-fill-mode,none)}.data-\[state\=open\]\:bg-muted[data-state=open]{background-color:var(--color-muted)}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale:.95}@media not all and (width>=40rem){.max-sm\:-left-10{left:calc(var(--spacing) * -10)}}@media (width>=40rem){.sm\:-mx-6{margin-inline:calc(var(--spacing) * -6)}.sm\:ml-12{margin-left:calc(var(--spacing) * 12)}.sm\:flex{display:flex}.sm\:inline{display:inline}.sm\:inline-flex{display:inline-flex}.sm\:h-44{height:calc(var(--spacing) * 44)}.sm\:w-\[calc\(100\%-3rem\)\]{width:calc(100% - 3rem)}.sm\:max-w-\[200px\]{max-width:200px}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:px-3{padding-inline:calc(var(--spacing) * 3)}.sm\:px-12{padding-inline:calc(var(--spacing) * 12)}.sm\:pt-8{padding-top:calc(var(--spacing) * 8)}.sm\:pl-12{padding-left:calc(var(--spacing) * 12)}}@media (width>=48rem){.md\:block{display:block}.md\:hidden{display:none}.md\:inline-flex{display:inline-flex}}.dark\:border-neutral-700:is(.dark *){border-color:var(--color-neutral-700)}.dark\:bg-white\/10:is(.dark *){background-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.dark\:bg-white\/10:is(.dark *){background-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}.dark\:bg-white\/20:is(.dark *){background-color:#fff3}@supports (color:color-mix(in lab, red, red)){.dark\:bg-white\/20:is(.dark *){background-color:color-mix(in oklab, var(--color-white) 20%, transparent)}}.dark\:text-amber-100:is(.dark *){color:var(--color-amber-100)}.dark\:text-emerald-200:is(.dark *){color:var(--color-emerald-200)}.dark\:text-emerald-300:is(.dark *){color:var(--color-emerald-300)}.dark\:outline-white\/10:is(.dark *){outline-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.dark\:outline-white\/10:is(.dark *){outline-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}@media (hover:hover){.dark\:hover\:bg-neutral-900:is(.dark *):hover{background-color:var(--color-neutral-900)}.dark\:hover\:bg-white\/10:is(.dark *):hover{background-color:#ffffff1a}@supports (color:color-mix(in lab, red, red)){.dark\:hover\:bg-white\/10:is(.dark *):hover{background-color:color-mix(in oklab, var(--color-white) 10%, transparent)}}}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-inline:calc(var(--spacing) * 2)}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-block:calc(var(--spacing) * 1.5)}.\[\&_\[cmdk-group-heading\]\]\:text-\[11px\] [cmdk-group-heading]{font-size:11px}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\[\&_\[cmdk-group-heading\]\]\:tracking-wide [cmdk-group-heading]{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:var(--color-muted-foreground)}.\[\&_\[cmdk-group-heading\]\]\:uppercase [cmdk-group-heading]{text-transform:uppercase}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:mx-auto svg{margin-inline:auto}.\[\&_svg\]\:size-4 svg{width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&_svg\]\:max-w-full svg{max-width:100%}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}}@property --tw-animation-delay{syntax:"*";inherits:false;initial-value:0s}@property --tw-animation-direction{syntax:"*";inherits:false;initial-value:normal}@property --tw-animation-duration{syntax:"*";inherits:false}@property --tw-animation-fill-mode{syntax:"*";inherits:false;initial-value:none}@property --tw-animation-iteration-count{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-translate-y{syntax:"*";inherits:false;initial-value:0}.dark{--color-background:#191919;--color-foreground:#e8e8e8;--color-card:#202020;--color-card-foreground:#e8e8e8;--color-popover:#252525;--color-popover-foreground:#e8e8e8;--color-primary:#e8e8e8;--color-primary-foreground:#191919;--color-secondary:#2a2a2a;--color-secondary-foreground:#e8e8e8;--color-muted:#2a2a2a;--color-muted-foreground:#9b9b9b;--color-accent:#2a2a2a;--color-accent-foreground:#e8e8e8;--color-destructive:#ea580c;--color-destructive-foreground:#fafafa;--color-border:#333;--color-input:#333;--color-ring:#6b6b6b;--color-sidebar:#202020;--color-sidebar-fg:#cfcfcf;--color-sidebar-border:#2e2e2e;--color-sidebar-hover:#2a2a2a;--color-sidebar-active:#2f2f2f}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}.ui-freeze *,.ui-freeze :before,.ui-freeze :after{caret-color:#0000!important;transition:none!important;animation:none!important}.ui-freeze [data-sonner-toaster]{display:none!important}.ui-freeze [data-volatile]{visibility:hidden!important}.ui-reveal [data-hover-reveal]{opacity:1!important}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-pan-x{syntax:"*";inherits:false}@property --tw-pan-y{syntax:"*";inherits:false}@property --tw-pinch-zoom{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-space-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-content{syntax:"*";inherits:false;initial-value:""}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0)scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1))rotate(var(--tw-enter-rotate,0));filter:blur(var(--tw-enter-blur,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0)scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1))rotate(var(--tw-exit-rotate,0));filter:blur(var(--tw-exit-blur,0))}} diff --git a/dist-desktop/assets/swimlanes-5IMT3BWC-hyAz1L8O.js b/dist-desktop/assets/swimlanes-5IMT3BWC-hyAz1L8O.js new file mode 100644 index 0000000..62a43b1 --- /dev/null +++ b/dist-desktop/assets/swimlanes-5IMT3BWC-hyAz1L8O.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/sizeCapture-X5ZJPWSS-B0uUizjq.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js"])))=>i.map(i=>d[i]); +import{t as e}from"./index-CXgd9jpl.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import{b as r,x as i}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{g as a}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{r as o}from"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as s}from"./chunk-OGEWGWER-D-nWYRNR.js";import{t as c}from"./graphlib-DS17s2tU.js";import{n as l}from"./chunk-RYQCIY6F-Dtr3kkSR.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import{a as u,c as d,i as f,n as p,t as m}from"./chunk-ZGVPDNZ5-DGInJAPD.js";import{a as h,i as g,n as _,r as v,s as y,t as b}from"./chunk-52WLFC77-BOCvVCX1.js";async function x(t,n){let r=new c({multigraph:!0,compound:!0}),a=[...n.edges],o=i(),s=t.insert(`g`).attr(`class`,`root`),l=s.insert(`g`).attr(`class`,`clusters`),d=s.insert(`g`).attr(`class`,`edges edgePath`),f=s.insert(`g`).attr(`class`,`edgeLabels`),p=s.insert(`g`).attr(`class`,`nodes`),m=new Map,h=t.node()!=null;await Promise.all(n.nodes.map(async e=>{if(e.isGroup)r.setNode(e.id,{...e});else{if(h){let t=await u(p,e,{config:o,dir:e.dir}),n=t.node()?.getBBox()??{width:0,height:0};m.set(e.id,t),e.width=n.width,e.height=n.height}r.setNode(e.id,{...e})}}));for(let e of a)r.setEdge(e.start,e.end,{...e},e.id),n.edges.some(t=>t.id===e.id)||n.edges.push(e);if(globalThis.mermaidCaptureSizes){let{captureNodeSizes:r}=await e(async()=>{let{captureNodeSizes:e}=await import(`./sizeCapture-X5ZJPWSS-B0uUizjq.js`);return{captureNodeSizes:e}},__vite__mapDeps([0,1]));r(t,n)}return{graph:r,groups:{clusters:l,edgePaths:d,edgeLabels:f,nodes:p,rootGroups:s},nodeElements:m}}t(x,`createGraphWithElements`);var S=5,C=1e-5,w=1e-6;function T(e){let t=[];for(let n=0;n=1-w||f<=w||f>=1-w?null:{point:{x:e.x+d*i,y:e.y+d*a},tA:d,tB:f}}t(E,`segmentIntersection`);function D(e){return Math.abs(e.b.x-e.a.x)>=Math.abs(e.b.y-e.a.y)}t(D,`isHorizontalSeg`);function O(e){let t=[];for(let n=0;n=Math.abs(n)?+(t>=0):+(n>=0)}t(j,`getArcSweepFlag`);var ee=.001;function te(e,t){if(e.length<2)return e.map(e=>({...e}));let n=e.map(e=>({...e})),r=t.arrowTypeStart&&o[t.arrowTypeStart];if(r){let t=e[0],i=e[1],a=Math.atan2(i.y-t.y,i.x-t.x);n[0].x=t.x+r*Math.cos(a),n[0].y=t.y+r*Math.sin(a)}let i=t.arrowTypeEnd&&o[t.arrowTypeEnd];if(i){let t=e.length,r=e[t-2],a=e[t-1],o=Math.atan2(a.y-r.y,a.x-r.x);n[t-1].x=a.x-i*Math.cos(o),n[t-1].y=a.y-i*Math.sin(o)}return n}t(te,`applyMarkerOffsets`);function M(e,t,n,r,i){let a=e.point.x,o=e.point.y,s={x:a-t*e.r,y:o-n*e.r},c={x:a+t*e.r,y:o+n*e.r},l=[`L${A(s)}`];return i===`arc`?l.push(`A${k(e.r)},${k(e.r)} 0 0 ${r} ${A(c)}`):l.push(`M${A(c)}`),l}t(M,`emitJump`);function ne(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=n.x-t.x,s=n.y-t.y,c=Math.hypot(i,a),l=Math.hypot(o,s);if(c0){let t=ne(i[e-1],i[e],i[e+1]??i[e],S);t&&(f=t.cutLen)}let p=r,m=null;a&&ee.t-t.t);for(let e of h)e.r=Math.min(e.r,e.d-f,p-e.d);for(let e=0;et){let n=t/2;h[e].r=Math.min(h[e].r,n),h[e+1].r=Math.min(h[e+1].r,n)}}for(let e of h)e.r=2?r:null}catch{return null}}t(ie,`decodeDataPoints`);function ae(e,t,n){if(!n.enabled)return;let r=e.node();if(!r)return;let i=new Map;for(let e of t)i.set(e.id,e);let a=[],o=new Map;for(let e of t){let t=typeof CSS<`u`&&CSS.escape?CSS.escape(e.id):e.id,n=r.querySelector(`path[data-id="${t}"]`);if(!n)continue;o.set(e.id,n);let i=ie(n.getAttribute(`data-points`))??e.points;a.push({...e,points:i})}let s=O(a);if(s.length===0)return;let c=new Map;for(let e of s){let t=c.get(e.jumpEdgeId)??[];t.push(e),c.set(e.jumpEdgeId,t)}for(let e of a){let t=c.get(e.id);if(!t||t.length===0)continue;let r=i.get(e.id)?.curve;if(r!==void 0&&!P(r))continue;let a=o.get(e.id);if(!a||r===void 0&&!re(a.getAttribute(`d`)??``))continue;let s=a.getAttribute(`style`)??``,l=/stroke-dasharray\s*:\s*0\s+([\d.]+)\s+[\d.]+\s+([\d.]+)/.exec(s),u=l?Number.parseFloat(l[1]):null,d=l?Number.parseFloat(l[2]):null,f=N(e,t,n);if(a.setAttribute(`d`,f),u!==null&&d!==null&&typeof a.getTotalLength==`function`){let e=a.getTotalLength(),t=`0 ${u} ${Math.max(0,e-u-d)} ${d}`,n=s.replace(/stroke-dasharray\s*:[^;]*;?/g,`stroke-dasharray: ${t};`).replace(/;\s*;+/g,`;`);a.setAttribute(`style`,n)}}}t(ae,`applyLineJumpsToSvg`);async function oe(e,t){for(let n of e.nodes)n.isGroup?await f(t.clusters,n):d(n);let n=new Map;for(let t of e.nodes)t?.id&&n.set(t.id,t);for(let r of e.edges){let i=r.start?n.get(r.start)??{}:{},a=r.end?n.get(r.end)??{}:{},o=v(t.edgePaths,{...r},{},e.type,i,a,e.diagramId);r.label&&await g(t.rootGroups,r),r.label&&se(r,o)}let r=e.config?.swimlane?.lineHops;if(r!==!1){let n=r===`gap`?`gap`:`arc`,i=e.edges.filter(e=>Array.isArray(e.points)&&e.points.length>=2).map(e=>({id:e.id,points:e.points,curve:e.curve,arrowTypeStart:e.arrowTypeStart,arrowTypeEnd:e.arrowTypeEnd}));ae(t.edgePaths,i,{enabled:!0,jumpRadius:6,jumpStyle:n})}}t(oe,`adjustLayout`);function se(e,t){let i=t?.updatedPath??t?.originalPath,{subGraphTitleTotalMargin:o}=s({flowchart:r().flowchart??{}});if(e.label){let r=_.get(e.id),s=e.x,c=e.y;if(i){let r=a.calcLabelPosition(i);n.debug(`Moving label `+e.label+` from (`,s,`,`,c,`) to (`,r.x,`,`,r.y,`) abc88`),t&&(s=r.x,c=r.y)}r.attr(`transform`,`translate(${s}, ${c+o/2})`)}if(e?.startLabelLeft){let t=y.get(e.id).startLeft,n=e?.x,r=e?.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_left`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}if(e.startLabelRight){let t=y.get(e.id).startRight,n=e.x,r=e.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_right`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}if(e.endLabelLeft){let t=y.get(e.id).endLeft,n=e.x,r=e.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_left`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}if(e.endLabelRight){let t=y.get(e.id).endRight,n=e.x,r=e.y;if(i){let t=a.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_right`,i);n=t.x,r=t.y}t.attr(`transform`,`translate(${n}, ${r})`)}}t(se,`positionEdgeLabel`);var ce=`__swimlane_default__`,le=21,ue=20;function de(e){return Math.max(e.padding??ue,ue)}t(de,`topLaneHorizontalPadding`);function fe(e){let{x:t,y:n,width:r,height:i}=e,a=e.swimlaneContentTop;if(typeof t!=`number`||typeof n!=`number`||typeof r!=`number`||typeof i!=`number`||typeof a!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(a)||r<=0||i<=0){delete e.groupTitleRect;return}let o=n-i/2,s=Math.min(a,n+i/2),c=o+Math.min(le,Math.max(0,s-o));if(c<=o){delete e.groupTitleRect;return}e.groupTitleRect={left:t-r/2,right:t+r/2,top:o,bottom:c}}t(fe,`assignTopLaneTitleRect`);function pe(e){let t=e.direction,n=e.nodes??=[];for(let n of e.nodes??[])n.isGroup&&!n.parentId&&(n.shape=`swimlane`,t&&(n.direction=t));let r=n.filter(e=>!e.isGroup&&!e.parentId);if(r.length===0)return;let i=n.find(e=>e.id===ce);i?i.isGroup&&(i.shape=`swimlane`,t&&(i.direction=t)):(i={id:ce,label:``,isGroup:!0,shape:`swimlane`,padding:20,...t?{direction:t}:{}},n.push(i));for(let e of r)e.parentId=ce}t(pe,`prepareLayoutForSwimlanes`);function F(e){let t=new Map;for(let n of e.nodes??[])t.set(n.id,n);let n=[];for(let t of e.edges??[]){let e=typeof t.start==`string`?t.start:void 0,r=typeof t.end==`string`?t.end:void 0;!e||!r||t.labelNodeId||n.push({id:t.id,src:e,dst:r,ref:t})}let r=e.nodes??[],i=r.filter(e=>e.isGroup),a=r.filter(e=>!e.isGroup);return{nodes:[...[...i].reverse(),...a].map(e=>e.id),edges:n,layout:e,nodeById:t}}t(F,`toGraphView`);function I(e,t,n,r){let{layout:i}=e,a=e.nodeById,o=r?.layerGap??100,s=r?.nodeGap??40,c=0;for(let e of t.layers){let t=0;for(let r of e){let e=a.get(r);if(!e){t++;continue}e.layer=c,e.order=t;let i=n.x[r]??t*s,l=n.y[r]??c*o;e.x=i,e.y=l,t++}c++}let l=i.nodes??[],u=new Map,d=[];for(let e of l){if(!e?.isGroup)continue;e.parentId||d.push(e);let t=l.filter(t=>t.parentId===e.id),r=1/0,i=-1/0,a=1/0,o=-1/0;for(let e of t){let t=e.x??n.x[e.id],s=e.y??n.y[e.id],c=e.width??0,l=e.height??0;t!=null&&s!=null&&(r=Math.min(r,t-c/2),i=Math.max(i,t+c/2),a=Math.min(a,s-l/2),o=Math.max(o,s+l/2))}if(r===1/0||a===1/0)e.x=e.x??0,e.y=e.y??0,e.width=e.width??0,e.height=e.height??0;else{let t=e.padding??20,n=e.parentId?t:2*de(e),s=t,c=Math.max(0,i-r)+n,l=Math.max(0,o-a)+s,d=(r+i)/2,f=(a+o)/2;e.x=d,e.y=f,e.width=c,e.height=l,u.set(e.id,{minX:r,maxX:i,minY:a,maxY:o})}}if(d.length>0&&u.size>0){let e=1/0,t=-1/0,n=0;for(let r of d){let i=r.padding??20;i>n&&(n=i);let a=u.get(r.id);a&&(e=Math.min(e,a.minY),t=Math.max(t,a.maxY))}if(e!==1/0&&t!==-1/0){let r=Math.max(0,t-e)+2*Math.max(n,36),i=(e+t)/2;for(let t of d)t.y=i,t.height=r,t.swimlaneContentTop=e;let a=[...d].sort((e,t)=>(e.x??0)-(t.x??0)),o=[],s=[],c=[];for(let e of a){let t=u.get(e.id);if(!t)continue;let n=Math.max(0,t.maxX-t.minX)+2*de(e),r=(t.minX+t.maxX)/2;o.push(e.id),s.push(r),c.push(n)}let l=o.length;if(l>0){let e=new Map;if(l===1)e.set(o[0],c[0]);else{let t=[];for(let e=0;e0&&i>0?{cx:t,cy:n,rect:Ee(t,n,r,i)}:void 0}t(ge,`measuredNodeRect`);function _e(e){if(e.isGroup)return;let t=ge(e);if(t)return{id:String(e.id??``),cx:t.cx,cy:t.cy,rect:t.rect}}t(_e,`nodeBoundsInfoFor`);function R(e,t,n=L){return Math.abs(e.x-t.x)n}t(V,`isHorizontalSegment`);function H(e,t,n=L){return z(e,t,n)&&Math.abs(e.y-t.y)>n}t(H,`isVerticalSegment`);function U(e,t,n,r){return Math.max(0,Math.min(Math.max(e,t),Math.max(n,r))-Math.max(Math.min(e,t),Math.min(n,r)))}t(U,`overlapLength`);function ve(e,t,n=L){return e.horizontal&&t.horizontal&&B(e.a,t.a,n)?U(e.a.x,e.b.x,t.a.x,t.b.x):e.vertical&&t.vertical&&z(e.a,t.a,n)?U(e.a.y,e.b.y,t.a.y,t.b.y):0}t(ve,`sameAxisSegmentOverlapLength`);function ye(e,t=L){let n=[];for(let r=0;r0?n[n.length-1]:void 0;(!e||!R(e,r,t))&&n.push({x:r.x,y:r.y})}return n}t(G,`dedupeConsecutivePoints`);function be(e,t=L){if(!e||e.length!==4)return;let[n,r,i,a]=e;return V(n,r,t)&&H(r,i,t)&&V(i,a,t)?{kind:`HVH`,p0:n,p1:r,p2:i,p3:a}:H(n,r,t)&&V(r,i,t)&&H(i,a,t)?{kind:`VHV`,p0:n,p1:r,p2:i,p3:a}:void 0}t(be,`classifyThreeSegmentRoute`);function xe(e,t,n,r=0){let i=Math.min(e.x,t.x),a=Math.max(e.x,t.x),o=Math.min(e.y,t.y),s=Math.max(e.y,t.y);return a>n.left-r&&in.top-r&&ot.left+n&&e.xt.top+n&&e.y=t.right&&e.top<=t.top&&e.bottom>=t.bottom}t(Ce,`rectContainsRect`);function we(e,t){return e.leftt.left&&e.topt.top}t(we,`rectsOverlap`);function Te(e,t){return{left:e.left-t,right:e.right+t,top:e.top-t,bottom:e.bottom+t}}t(Te,`inflateRect`);function Ee(e,t,n,r){return{left:e-n/2,right:e+n/2,top:t-r/2,bottom:t+r/2}}t(Ee,`rectFromCenterSize`);function K(e){return ge(e)?.rect}t(K,`rectOfNodeBounds`);function De(e,t){switch(t){case`top`:return{x:e.cx,y:e.rect.top};case`bottom`:return{x:e.cx,y:e.rect.bottom};case`left`:return{x:e.rect.left,y:e.cy};case`right`:return{x:e.rect.right,y:e.cy}}}t(De,`portForRectSide`);function Oe(e,t,n,r,i,a=L){let o=t===`left`||t===`right`,s=r===`left`||r===`right`;if(o&&s){if(t===`right`&&r===`left`&&e.xn.x){if(B(e,n,a))return[e,n];let t=(e.x+n.x)/2;return[e,{x:t,y:e.y},{x:t,y:n.y},n]}if(t===r){if(B(e,n,a))return;let r=t===`left`?Math.min(e.x,n.x)-i:Math.max(e.x,n.x)+i;return[e,{x:r,y:e.y},{x:r,y:n.y},n]}return}if(!o&&!s){if(t===r){if(z(e,n,a))return;let r=t===`top`?Math.min(e.y,n.y)-i:Math.max(e.y,n.y)+i;return[e,{x:e.x,y:r},{x:n.x,y:r},n]}if(!(t===`bottom`&&r===`top`&&e.yn.y))return;if(z(e,n,a))return[e,n];let o=(e.y+n.y)/2;return[e,{x:e.x,y:o},{x:n.x,y:o},n]}if(o&&!s){let i=t===`right`&&n.x>e.x||t===`left`&&n.xn.y;return i&&a?[e,{x:n.x,y:e.y},n]:void 0}let c=t===`bottom`&&n.y>e.y||t===`top`&&n.yn.x;return c&&l?[e,{x:e.x,y:n.y},n]:void 0}t(Oe,`buildOrthogonalPortPath`);function ke(e,t,n,r){return t===`left`||t===`right`?[e,{x:r,y:e.y},{x:r,y:n.y},n]:[e,{x:e.x,y:r},{x:n.x,y:r},n]}t(ke,`buildSameSideTrackPath`);function Ae(e){let t=new Map,n=[];for(let r of e){if(r.isEdgeLabel)continue;let e=_e(r);e&&(t.set(e.id,e),n.push({id:e.id,rect:e.rect}))}return{nodeInfoById:t,realNodeRects:n}}t(Ae,`collectRealNodeBounds`);function je(e){let t=[],n=[];for(let r of e){let e=_e(r);if(!e)continue;let i={id:e.id,rect:e.rect};r.isEdgeLabel?n.push(i):t.push(i)}return{realNodeRects:t,labelNodeRects:n}}t(je,`collectNodeRectEntries`);function Me(e,{includeEdgeLabels:t=!0}={}){let n=[];for(let r of e){if(r.isGroup||!t&&r.isEdgeLabel)continue;let e=r.x??0,i=r.y??0,a=r.width??0,o=r.height??0;n.push({nodeId:r.id,...Ee(e,i,a,o)})}return n}t(Me,`collectLayoutNodeRects`);function Ne(e,t,n=L){let r=e.start,i=e.end;if(!r||!i)return;let a=t.get(r),o=t.get(i);if(!(!a||!o))return{srcId:r,dstId:i,srcInfo:a,dstInfo:o,collinearX:Math.abs(a.cx-o.cx)m||f_)return!1;let v=Math.abs(h-u.a.x)i:a&&s&&B(e,n,i)?U(e.x,t.x,n.x,r.x)>i:!1}t(Fe,`sameAxisSegmentsOverlap`);function Ie(e,t,n,r,{epsilon:i=L,skipDegenerateOther:a=!1}={}){for(let o of n){if(o===r||o.isLayoutOnly)continue;let n=o.points;if(!(!n||n.length<2))for(let r=0;rf+i&&mh+i&&dr+L&&e=2?t[t.length-2]:void 0,n=e&&z(e,r)?{x:r.x,y:i.y}:{x:i.x,y:r.y};t.push(n)}t.push(i)}let n=[];for(let e of t){let t=n[n.length-1];(!t||!R(t,e))&&n.push(e)}return n}t(Ve,`orthogonalizePolyline`);function He(e){if(e.length<3)return e;let t=[...e];for(let e=0;e<32;e++){let e=Be(t);if(t=e.points,!e.changed)break}return t}t(He,`simplifyPolyline`);var J=.001,Ue=.5,We=4;function Ge(e,t,n){let r=e;if(r.isLayoutOnly||!r.points||r.points.length=0&&i=e.length)return e;let a=i-r;if(a<0||a>=e.length)return e;let o=Ke(e[i],e[a],t);return n?[o,...e.slice(i)]:[...e.slice(0,i+1),o]}t(qe,`clipEndpoint`);function Je(e,t){for(let n of e){let e=Ge(n,t,2);if(!e)continue;let r=[...e.points];e.srcRect&&(r=qe(r,e.srcRect,!0)),e.dstRect&&(r=qe(r,e.dstRect,!1)),r=He(Ve(r)),r=at(r,e.srcRect,e.dstRect),e.edge.points=He(Ve(r))}}t(Je,`clipEdgeEndpointsToNodeBoundaries`);function Ye(e,t,n,r=!1){if(B(e,t,J)){if(t.yn.bottom+J)return t;if(r){if(e.xn.right+J)return{x:n.right,y:e.y}}return{x:Math.abs(t.x-n.left)<=Math.abs(t.x-n.right)?n.left:n.right,y:e.y}}if(z(e,t,J)){if(t.xn.right+J)return t;if(r){if(e.yn.bottom+J)return{x:e.x,y:n.bottom}}let i=Math.abs(t.y-n.top)<=Math.abs(t.y-n.bottom);return{x:e.x,y:i?n.top:n.bottom}}return t}t(Ye,`snapEndpointToBoundary`);function Xe(e,t,n){let r=e[t];for(let i=t+n;i>=0&&ie.lo)),n=Math.min(...e.map(e=>e.hi));if(!(t>n))return{lo:t,hi:n}}t($e,`intersectRanges`);function et(e,t){return t===`left`||t===`right`?Ze(e.top,e.bottom):Ze(e.left,e.right)}t(et,`clearanceRangeForSide`);function tt(e,t,n){let r=e.y>=n.top-J&&e.y<=n.bottom+J,i=e.x>=n.left-J&&e.x<=n.right+J;if(B(e,t,J)&&r){if(Math.abs(e.x-n.left)0?$e(a):void 0}t(rt,`straightClearanceRange`);function it(e,t,n,r,i){let a=rt(e,t,n,r,i);if(!a)return;let o=i?e.y:e.x,s=Math.min(a.hi,Math.max(a.lo,o));if(!(Math.abs(s-o)({...e}));for(let s=t;s>=0&&s=n.left-J&&Math.max(e.x,t.x)<=n.right+J,i=Math.min(e.y,t.y)>=n.top-J&&Math.max(e.y,t.y)<=n.bottom+J;if(Math.abs(e.y-n.top)r.bottom+J;case`left`:return B(t,n,J)&&n.xr.right+J}}t(ut,`leavesOutward`);function dt(e,t,n){if(e.length<3)return e;if(n){let n=lt(e[0],e[1],t);return n&&ut(n,e[1],e[2],t)?e.slice(1):e}let r=e.length-1,i=lt(e[r-1],e[r],t);return i&&ut(i,e[r-1],e[r-2],t)?e.slice(0,r):e}t(dt,`collapseOwnBorderStub`);function ft(e,t,n){let r=e;if(t){let e=Xe(r,0,1);if(e){let n=Ye(e,r[0],t);n!==r[0]&&(r=[n,...r.slice(1)])}r=dt(r,t,!0)}if(n){let e=r.length-1,t=Xe(r,e,-1);if(t){let i=Ye(t,r[e],n,!0);i!==r[e]&&(r=[...r.slice(0,e),i])}r=dt(r,n,!1)}let i=at(r,t,n);return i!==r||r.length===2?i:(t&&(r=ct(r,t,!0)),n&&(r=ct(r,n,!1)),r)}t(ft,`snapAndCollapseEndpoints`);function pt(e,t){for(let n of e){let e=Ge(n,t,2);if(!e)continue;let r=ft(G(e.points,J),e.srcRect,e.dstRect);if(r.length<3){e.edge.points=r;continue}let i=[r[0],{...r[0]},...r.slice(1,-1),r[r.length-1],{...r[r.length-1]}];e.edge.points=i}}t(pt,`prepareEdgeEndpointsForRenderer`);function mt(e){return new Map(e.map(e=>[e.id,e]))}t(mt,`buildNodeMap`);function ht(e,t){let n=e.parentId,r=null;for(;n;){let e=t.get(n);if(!e?.isGroup)break;r=e.id,n=e.parentId}return r}t(ht,`resolveTopLevelGroupId`);function gt(e,t){let n=0,r=e.parentId;for(;r;){let e=t.get(r);if(!e?.isGroup)break;n++,r=e.parentId}return n}t(gt,`groupDepth`);function _t(e){let t=1/0,n=-1/0,r=1/0,i=-1/0;for(let a of e){let e=a.x,o=a.y;if(typeof e!=`number`||typeof o!=`number`)continue;let s=a.width??0,c=a.height??0;t=Math.min(t,e-s/2),n=Math.max(n,e+s/2),r=Math.min(r,o-c/2),i=Math.max(i,o+c/2)}return t===1/0||r===1/0?null:{minX:t,maxX:n,minY:r,maxY:i}}t(_t,`boundsForChildren`);function vt(e,t){let n=e.padding??20;e.x=(t.minX+t.maxX)/2,e.y=(t.minY+t.maxY)/2,e.width=Math.max(0,t.maxX-t.minX)+n,e.height=Math.max(0,t.maxY-t.minY)+n}t(vt,`applyGroupBounds`);function yt(e){let t=mt(e),n=e.filter(e=>e.isGroup&&e.parentId).sort((e,n)=>gt(n,t)-gt(e,t));for(let t of n){let n=_t(e.filter(e=>e.parentId===t.id));n&&vt(t,n)}}t(yt,`recomputeNestedGroupBounds`);function bt(e,n){let r=e.nodes??[],i=e.edges??[],a=r.filter(e=>!e.isGroup),o=1/0,s=-1/0;for(let e of a){let t=e[n];typeof t==`number`&&(o=Math.min(o,t),s=Math.max(s,t))}if(!Number.isFinite(o)||!Number.isFinite(s))return!1;let c=t(e=>o+s-e,`mirror`);for(let e of r){let t=e[n];typeof t==`number`&&(e[n]=c(t));let r=e.groupTitleRect;r&&(e.groupTitleRect=n===`x`?{...r,left:c(r.right),right:c(r.left)}:{...r,top:c(r.bottom),bottom:c(r.top)})}for(let e of i)for(let t of e.points??[])t[n]=c(t[n]);return!0}t(bt,`mirrorAxis`);function xt(e){return!(e.nodes??[]).some(e=>!e.isGroup)||bt(e,`y`)}t(xt,`applyBtDirectionTransform`);function St(e,t=`LR`){let n=e.nodes??[],r=e.edges??[],i=n.filter(e=>!e.isGroup),a=1/0,o=1/0;for(let e of i){let t=e.x??0,n=e.y??0;t0?Math.max(1,l/u):1;for(let e of i){let t=e.x??0,n=((e.y??0)-o)*d+36,r=t-a;e.x=n,e.y=r}for(let e of r)if(e.points)for(let t of e.points){let e=t.x,n=(t.y-o)*d+36,r=e-a;t.x=n,t.y=r}yt(n);let f=n.filter(e=>e.isGroup&&!e.parentId);if(f.length===0)return t===`RL`&&bt(e,`x`),!0;let p=mt(n),m=new Map;for(let e of n){if(e.isGroup)continue;let t=ht(e,p);if(!t)continue;let n=m.get(t)??[];n.push(e),m.set(t,n)}let h=0;for(let e of f){let t=e.padding??0;t>h&&(h=t)}let g=[],_=1/0,v=-1/0;for(let e of f){let t=_t(m.get(e.id)??[]);t&&(_=Math.min(_,t.minX),v=Math.max(v,t.maxX),g.push({lane:e,contentTop:t.minY,contentBottom:t.maxY,centerY:(t.minY+t.maxY)/2}))}if(_===1/0||v===-1/0)return!0;let y=Math.max(0,v-_)+2*Math.max(h,10),b=36+y,x=(_+v)/2-y/2-36,S=x+b/2,C=Math.max(h,36);g.sort((e,t)=>e.centerY-t.centerY);for(let e=0;ed.cy?g.bottom:g.top,t=d.cx+n;if(t<=g.left+Ct||t>=g.right-Ct)continue;i={x:t,y:e},a={x:t,y:o.y},c={x:o.x,y:o.y}}else{let e=f.cx>d.cx?g.right:g.left,t=d.cy+n;if(t<=g.top+Ct||t>=g.bottom-Ct)continue;i={x:e,y:t},a={x:o.x,y:t},c={x:o.x,y:o.y}}let p=R(i,a,Ct),m=R(a,c,Ct);if(p&&m||!p&&q(i,a,r,[l],1)||!m&&q(a,c,r,[u],1))continue;let _=!p&&Ie(i,a,e,t,{epsilon:Ct,skipDegenerateOther:!0}),v=!m&&Ie(a,c,e,t,{epsilon:Ct,skipDegenerateOther:!0});if(!(_||v)){h=p?[a,c]:m?[i,a]:[i,a,c];break}}h&&(t.points=h)}}t(Et,`portSwapToLShape`);function Dt(e,n){let r=.001,{realNodeRects:i,labelNodeRects:a}=je(n.values());for(let o of e){if(o.isLayoutOnly)continue;let s=o.points;if(!s||s.length<4)continue;let c=G(s,r);if(c.length<4)continue;let l=c.length-1,u=c[l],d=c[l-1],f=c[l-2],p=u.x-d.x,m=u.y-d.y,h=Math.hypot(p,m);if(h>=10||h0;O={x:f.x,y:E},k={x:e?D.right:D.left,y:E}}if(q(O,k,i,S?[S]:[],-2)||q(O,k,a,[],-2))continue;if(C){let e=n.get(C),t=e?K(e):void 0;if(t&&Se(O,t,2))continue}let A=t((e,t)=>`${e.x.toFixed(3)},${e.y.toFixed(3)}|${t.x.toFixed(3)},${t.y.toFixed(3)}`,`ownSegmentKey`),j=new Set;for(let e=0;e{for(let i of e){if(i===o||i.isLayoutOnly)continue;let e=i.points;if(!(!e||e.length<2))for(let i=0;i=0){let e=c[l-3],t=[C,S].filter(e=>!!e);if(q(e,O,i,t,-2)||ee(e,O))continue}let te=[...c.slice(0,l-2),O,k];o.points=te;let M=o.labelNodeId;if(M){let e=n.get(M);if(e){let t=e.width??0,n=e.height??0;if(t>0&&n>0){let i,a,o=-1;for(let e=0;e=t+2||d&&l>=n+2)&&l>o&&(o=l,i=(s.x+c.x)/2,a=(s.y+c.y)/2)}i!==void 0&&a!==void 0&&(e.x=i,e.y=a)}}}}}t(Dt,`collapseShortTerminalStub`);var Y=.001,X=8,Z=ye,Ot=t((e,t)=>z(e,t,Y)||B(e,t,Y),`orthogonallyAligned`);function kt(e,n){let r=t((e,t)=>{let n=e.x??0,r=e.y??0,i=t.x-n,a=t.y-r,o=(e.width??0)/2,s=(e.height??0)/2;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),{x:n+(a===0?0:s*i/a),y:r+s}):(i<0&&(o=-o),{x:n+o,y:r+(i===0?0:o*a/i)})},`rectIntersect`),i=t((e,t)=>{let i=G(e.points??[]);if(i.length<2)return;let a=t?e.start:e.end,o=a?n.get(a):void 0,s=o?K(o):void 0;if(!o||!a||!s)return;let c=t?i[0]:i[i.length-1],l=t?i[1]:i[i.length-2],u=r(o,c),d=c;if(Ot(l,u)&&(d=l),z(u,d,Y))return{edge:e,edgeId:String(e.id??``),nodeId:a,atStart:t,orientation:`V`,coord:u.x,min:Math.min(u.y,d.y),max:Math.max(u.y,d.y),boundary:u,railEnd:d,rect:s};if(B(u,d,Y))return{edge:e,edgeId:String(e.id??``),nodeId:a,atStart:t,orientation:`H`,coord:u.y,min:Math.min(u.x,d.x),max:Math.max(u.x,d.x),boundary:u,railEnd:d,rect:s}},`terminalLaneFor`),a=t((e,t)=>Math.max(0,Math.min(e.max,t.max)-Math.max(e.min,t.min)),`projectedOverlapLength`),o=t((e,t)=>e.nodeId!==t.nodeId||e.orientation!==t.orientation?!1:e.orientation===`H`?(Math.abs(e.boundary.x-e.rect.left)<1||Math.abs(e.boundary.x-e.rect.right)<1)&&z(e.boundary,t.boundary,1):(Math.abs(e.boundary.y-e.rect.top)<1||Math.abs(e.boundary.y-e.rect.bottom)<1)&&B(e.boundary,t.boundary,1),`sameTerminalFace`),s=t((e,t)=>e.nodeId!==t.nodeId||e.orientation!==t.orientation?!1:a(e,t)>=X&&Math.abs(e.coord-t.coord)<.5,`exactTerminalLaneConflict`),c=t((e,t)=>{if(e.nodeId!==t.nodeId||e.orientation!==t.orientation||e.orientation!==`H`||e.atStart===t.atStart)return!1;let n=a(e,t);if(n2*r?!1:o(e,t)&&Math.abs(e.coord-t.coord)<16},`nearTerminalLaneConflict`),l=t((e,n)=>{let r=G(e.edge.points??[]);if(r.length<2)return;let i=e.orientation===`V`?{x:e.boundary.x+n,y:e.boundary.y}:{x:e.boundary.x,y:e.boundary.y+n},a=e.orientation===`V`?{x:e.railEnd.x+n,y:e.railEnd.y}:{x:e.railEnd.x,y:e.railEnd.y+n};if(!t(()=>Math.abs(e.boundary.y-e.rect.top)<1||Math.abs(e.boundary.y-e.rect.bottom)<1?B(i,e.boundary,Y)&&i.x>=e.rect.left+1&&i.x<=e.rect.right-1:Math.abs(e.boundary.x-e.rect.left)<1||Math.abs(e.boundary.x-e.rect.right)<1?z(i,e.boundary,Y)&&i.y>=e.rect.top+1&&i.y<=e.rect.bottom-1:!1,`boundaryStaysOnSameFace`)())return;if(e.atStart){let t=r.length>1&&R(r[1],e.railEnd,Y),n=r.slice(t?2:1),o=n[0];return o&&!Ot(o,a)?void 0:[i,a,...n]}let o=r.length>1&&R(r[r.length-2],e.railEnd,Y),s=r.slice(0,o?-2:-1),c=s[s.length-1];if(!(c&&!Ot(c,a)))return[...s,a,i]},`shiftedCandidate`),u=t(e=>{let t=e.edge,r=G(t.points??[]);if(r.length!==2)return!1;let i=t.start,a=t.end,o=i?n.get(i):void 0,s=a?n.get(a):void 0;if(!o||!s)return!1;let c=o.x??0,l=o.y??0,u=s.x??0,d=s.y??0,[f,p]=r;return B(f,p,Y)&&Math.abs(l-d)<1&&Math.abs(c-u)>1||z(f,p,Y)&&Math.abs(c-u)<1&&Math.abs(l-d)>1},`laneIsStraightCollinearConnector`),d=[-7,7,-14,14,-21,21];for(let t=0;t<8;t++){let t=e.filter(e=>!e.isLayoutOnly).flatMap(e=>[i(e,!0),i(e,!1)]).filter(e=>!!e),n=!1;for(let e=0;e{let n=u(e),r=u(t);return n===r?Number(!t.atStart)-Number(!e.atStart):Number(n)-Number(r)});for(let e of p){for(let r of d){let a=l(e,r);if(!a)continue;let o=i({...e.edge,points:a},e.atStart);if(!(!o||t.some(t=>t.edge!==e.edge&&(s(o,t)||f&&c(o,t))))){e.edge.points=a,n=!0;break}}if(n)break}}if(!n)return}}t(kt,`separateSharedRenderedTerminalLanes`);function At(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=t((t,n)=>{let a=t.start,o=t.end,s=Z(n);if(s.length!==n.length-1)return!1;let c=[a,o].filter(e=>!!e);for(let e of s)if(q(e.a,e.b,r,c,-2)||q(e.a,e.b,i,[],-2))return!1;for(let n of e){if(n===t||n.isLayoutOnly)continue;let e=n.points;if(!(!e||e.length<2)){for(let t of s)for(let n of Z(G(e)))if(ve(t,n,.5)>=X||Le(t.a,t.b,n.a,n.b,Y))return!1}}return!0},`candidateIsSafe`),o=t((e,t)=>{if(t+4>=e.length)return;let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3],o=e[t+4],s=V(n,r)&&H(r,i)&&V(i,a)&&H(a,o)&&z(n,a,Y)&&z(n,o,Y)&&z(r,i,Y)&&(r.x-n.x)*(a.x-i.x)<0,c=H(n,r)&&V(r,i)&&H(i,a)&&V(a,o)&&B(n,a,Y)&&B(n,o,Y)&&B(r,i,Y)&&(r.y-n.y)*(a.y-i.y)<0;if(s||c)return G([...e.slice(0,t+1),o,...e.slice(t+5)]);if(t+5>=e.length)return;let l=e[t+5],u=H(n,r)&&V(r,i)&&H(i,a)&&V(a,o)&&H(o,l)&&z(n,o,Y)&&z(n,l,Y)&&z(i,a,Y)&&(i.x-r.x)*(o.x-a.x)<0,d=V(n,r)&&H(r,i)&&V(i,a)&&H(a,o)&&V(o,l)&&B(n,o,Y)&&B(n,l,Y)&&B(i,a,Y)&&(i.y-r.y)*(o.y-a.y)<0;if(!(!u&&!d))return G([...e.slice(0,t+1),l,...e.slice(t+6)])},`withoutDogleg`);for(let t=0;t<8;t++){let t=!1;for(let n of e){if(n.isLayoutOnly)continue;let e=G(n.points??[]);for(let r=0;r<=e.length-5;r++){let i=o(e,r);if(!(!i||!a(n,i))){n.points=i,t=!0;break}}if(t)break}if(!t)return}}t(At,`collapseRedundantRectangularDoglegs`);function jt(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=e.filter(e=>!e.isLayoutOnly),o=t((e,t,n)=>G(e===t?n??[]:e.points??[]),`pointsFor`),s=t((e,t)=>{let n=0;for(let r=0;r{let t=Z(e);if(t.length!==3)return;let n=t[1];if(!(t[0].horizontal===n.horizontal||t[2].horizontal===n.horizontal))return{index:n.index,horizontal:n.horizontal,vertical:n.vertical,segment:n}},`middleRail`),l=t((e,t)=>{let n=[e.start,e.end].filter(e=>!!e);return r.filter(e=>{if(n.includes(e.id))return!1;let r=e.rect;return t.horizontal?U(t.a.x,t.b.x,r.left,r.right)>=X&&t.a.y>=r.top-2&&t.a.y<=r.bottom+2:U(t.a.y,t.b.y,r.top,r.bottom)>=X&&t.a.x>=r.left-2&&t.a.x<=r.right+2})},`blockingRectsFor`),u=t((e,t,n)=>{let r=e.map(e=>({...e}));if(t.horizontal)r[t.index].y=n,r[t.index+1].y=n;else if(t.vertical)r[t.index].x=n,r[t.index+1].x=n;else return;let i=He(G(r));return Z(i).length===i.length-1?i:void 0},`candidateByMovingRail`),d=t((e,t,n)=>{let c=[e.start,e.end].filter(e=>!!e),l=Z(t);if(l.length!==t.length-1)return!1;for(let e of l)if(q(e.a,e.b,r,c,-2)||q(e.a,e.b,i,[],-2))return!1;for(let t of a)if(t!==e){for(let e of l)for(let n of Z(o(t)))if(ve(e,n,.5)>=X)return!1}return s(e,t)<=n},`candidateIsSafe`);for(let e=0;e<8;e++){let e=s(),t=!1;for(let n of a){let r=o(n),i=c(r);if(!i)continue;let a=l(n,i.segment);if(a.length===0)continue;let s=i.horizontal?[Math.min(...a.map(e=>e.rect.top))-20,Math.max(...a.map(e=>e.rect.bottom))+20]:[Math.min(...a.map(e=>e.rect.left))-20,Math.max(...a.map(e=>e.rect.right))+20];for(let a of s){let o=u(r,i.segment,a);if(!(!o||!d(n,o,e))){n.points=o,t=!0;break}}if(t)break}if(!t)return}}t(jt,`liftObstacleHuggingSameSideRails`);function Mt(e,n){let r=t(e=>{let t=e.groupTitleRect;if(!(!t||typeof t.left!=`number`||typeof t.right!=`number`||typeof t.top!=`number`||typeof t.bottom!=`number`||!Number.isFinite(t.left)||!Number.isFinite(t.right)||!Number.isFinite(t.top)||!Number.isFinite(t.bottom)||t.right<=t.left||t.bottom<=t.top))return{left:t.left,right:t.right,top:t.top,bottom:t.bottom}},`validTitleRect`),i=t(e=>{if(!e.isGroup||e.parentId)return;let t=e.direction,n=typeof t==`string`?t.toUpperCase():``;if(n===`LR`||n===`RL`||n===`BT`)return;let i=r(e),a=e.y,o=e.height;if(!i||typeof a!=`number`||typeof o!=`number`||!Number.isFinite(a)||!Number.isFinite(o)||o<=0)return;let s=i.right-i.left,c=i.bottom-i.top;if(!(c<=0||s{if(!e.horizontal)return!1;let n=e.a.y;return n<=t.top+Y||n>=t.bottom-Y?!1:U(e.a.x,e.b.x,t.left,t.right)>=X},`horizontalSegmentIntersectsTitle`),o=[...n.values()].map(i).filter(e=>!!e);if(o.length===0)return;let s=0;for(let t of e){if(t.isLayoutOnly)continue;let e=G(t.points??[]);for(let t of Z(e))for(let e of o)a(t,e.rect)&&(s=Math.max(s,e.rect.bottom-t.a.y+4))}if(!(s<=Y))for(let e of o){let t=e.node.y,n=e.node.height;typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||n<=0||(e.node.y=t-s/2,e.node.height=n+s,e.node.groupTitleRect={...e.rect,top:e.rect.top-s,bottom:e.rect.bottom-s})}}t(Mt,`liftTopLaneTitleBandsAboveRails`);function Nt(e,n){let r=t(e=>{let t=e.groupTitleRect;if(!(!t||typeof t.left!=`number`||typeof t.right!=`number`||typeof t.top!=`number`||typeof t.bottom!=`number`||!Number.isFinite(t.left)||!Number.isFinite(t.right)||!Number.isFinite(t.top)||!Number.isFinite(t.bottom)||t.right<=t.left||t.bottom<=t.top))return{left:t.left,right:t.right,top:t.top,bottom:t.bottom}},`validTitleRect`),i=t(e=>{if(!e.isGroup||e.parentId||e.direction!==`LR`)return;let t=r(e),n=e.x,i=e.width;if(!t||typeof n!=`number`||typeof i!=`number`||!Number.isFinite(n)||!Number.isFinite(i)||i<=0)return;let a=t.right-t.left,o=t.bottom-t.top;if(!(a<=0||o{if(!e.vertical)return!1;let n=e.a.x;return n<=t.left+Y||n>=t.right-Y?!1:U(e.a.y,e.b.y,t.top,t.bottom)>=X},`verticalSegmentIntersectsTitle`),o=t((e,t)=>{if(!e.horizontal)return!1;let n=e.a.y;return n<=t.top+Y||n>=t.bottom-Y?!1:U(e.a.x,e.b.x,t.left,t.right)>=X},`horizontalSegmentIntersectsTitle`),s=[...n.values()].map(i).filter(e=>!!e);if(s.length===0)return;let c=0;for(let t of e){if(t.isLayoutOnly)continue;let e=G(t.points??[]);for(let t of Z(e))for(let e of s)if(a(t,e.rect))c=Math.max(c,e.rect.right-t.a.x+4);else if(o(t,e.rect)){let n=Math.min(t.a.x,t.b.x);c=Math.max(c,e.rect.right-n+4)}}if(!(c<=Y))for(let e of s){let t=e.node.x,n=e.node.width;typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||n<=0||(e.node.x=t-c/2,e.node.width=n+c,e.node.groupTitleRect={...e.rect,left:e.rect.left-c,right:e.rect.right-c})}}t(Nt,`shiftLeftLaneTitleBandsLeftOfRails`);function Pt(e,n){let{realNodeRects:r}=je(n.values()),i=e.filter(e=>!e.isLayoutOnly),a=t((e,t=new Map)=>G(t.get(e)??e.points??[]),`replacementPointsFor`),o=t((e=new Map)=>{let t=0;for(let n=0;ni.reduce((t,n)=>t+W(a(n,e)),0),`totalBends`),c=t(e=>{let t=a(e);if(t.length<4)return;let n=t[t.length-2],r=t[t.length-1];if(!(!V(n,r,Y)&&!H(n,r,Y)))return{tailStart:n,terminal:r}},`terminalTailFor`),l=t((e,t)=>{let n=a(e);if(n.length<3)return;let r=n[0],i=n[1],o;if(V(r,i,Y))o={x:i.x,y:t.tailStart.y};else if(H(r,i,Y))o={x:t.tailStart.x,y:i.y};else return;let s=He(G([r,i,o,t.tailStart,t.terminal]));return Z(s).length===s.length-1?s:void 0},`candidateWithDestinationTail`),u=t((e,t)=>{let n=[e.start,e.end].filter(e=>!!e);for(let e of Z(t))if(q(e.a,e.b,r,n,-2))return!0;return!1},`pathHasNodeHit`),d=t((e,t,n)=>{for(let r of i)if(r!==e){for(let e of Z(t))for(let t of Z(a(r,n)))if(ve(e,t,.5)>=X)return!0}return!1},`pathHasSharedTrack`),f=t((e,t,n)=>!u(e,t)&&!d(e,t,n),`candidateIsSafe`),p=t(()=>{let e=new Map;for(let t of i){let r=t.end;if(!r||!n.has(r)||a(t).length<4)continue;let i=e.get(r)??[];i.push(t),e.set(r,i)}return e},`edgesByDestination`);for(let e=0;e<4;e++){let e=o();if(e===0)return;let t=s(),n,r=e,i=t;for(let t of p().values())for(let a=0;a=e||y>r||y===r&&b>=i||(n=v,r=y,i=b)}if(!n)return;for(let[e,t]of n)e.points=t}}t(Pt,`swapDestinationTerminalTailsToReduceCrossings`);function Ft(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=e.filter(e=>!e.isLayoutOnly),o=t((e,t=new Map)=>G(t.get(e)??e.points??[]),`replacementPointsFor`),s=t((e=new Map)=>{let t=0;for(let n=0;na.reduce((t,n)=>t+W(o(n,e)),0),`totalBends`),l=t(e=>{let t=e.start,r=e.end,i=t?n.get(t):void 0,a=r?n.get(r):void 0,o=i?K(i):void 0,s=a?K(a):void 0;return o&&s?{src:o,dst:s}:void 0},`endpointRectsFor`),u=t((e,t,n)=>{if(n.index<=0||n.index+1>=t.length-1)return;let r=l(e);if(r){if(n.vertical){let i=n.a.x,a=Math.min(r.src.left,r.dst.left),o=Math.max(r.src.right,r.dst.right),s=io+Y?`right`:void 0;return s?{edge:e,points:t,segmentIndex:n.index,axis:`vertical`,side:s,coord:i,min:Math.min(n.a.y,n.b.y),max:Math.max(n.a.y,n.b.y)}:void 0}if(n.horizontal){let i=n.a.y,a=Math.min(r.src.top,r.dst.top),o=Math.max(r.src.bottom,r.dst.bottom),s=io+Y?`bottom`:void 0;return s?{edge:e,points:t,segmentIndex:n.index,axis:`horizontal`,side:s,coord:i,min:Math.min(n.a.x,n.b.x),max:Math.max(n.a.x,n.b.x)}:void 0}}},`externalRailForSegment`),d=t(()=>{let e=[];for(let t of a){let n=o(t);for(let r of Z(n)){let i=u(t,n,r);i&&e.push(i)}}return e},`collectExternalRails`),f=t((e,t)=>e.edge!==t.edge&&e.axis===t.axis&&e.side===t.side&&U(e.min,e.max,t.min,t.max)>=X,`railsInteract`),p=t(e=>{let t=[],n=new Set;for(let r of e){if(n.has(r))continue;let i=[r],a=[];for(n.add(r);i.length>0;){let t=i.pop();a.push(t);for(let r of e)!n.has(r)&&f(t,r)&&(n.add(r),i.push(r))}a.length>1&&t.push(a)}return t},`connectedComponents`),m=t(e=>{let t=[];for(let n of e)t.some(e=>Math.abs(e-n.coord){let n=e.map(e=>e.coord),r=m(e),i=[];if(e.length<=6){let a=Array(r.length).fill(!1),o=[],s=t(()=>{if(o.length===e.length){o.some((e,t)=>Math.abs(e-n[t])>=Y)&&i.push([...o]);return}for(let[e,t]of r.entries())a[e]||(a[e]=!0,o.push(t),s(),o.pop(),a[e]=!1)},`visit`);return s(),i}for(let e=0;e{let n=new Map;for(let[r,i]of e.entries()){let e=t[r],a=n.get(i.edge)??i.points.map(e=>({x:e.x,y:e.y}));i.axis===`vertical`?(a[i.segmentIndex].x=e,a[i.segmentIndex+1].x=e):(a[i.segmentIndex].y=e,a[i.segmentIndex+1].y=e),n.set(i.edge,a)}let r=new Map;for(let[e,t]of n){let n=He(G(t));if(Z(n).length!==n.length-1)return;r.set(e,n)}return r},`replacementsForAssignment`),_=t(e=>{for(let[t,n]of e){let e=[t.start,t.end].filter(e=>!!e);for(let t of Z(n))if(q(t.a,t.b,r,e,-2)||q(t.a,t.b,i,[],-2))return!1}for(let t=0;t=X)return!1}}return!0},`candidateIsSafe`);for(let e=0;e<4;e++){let e=s();if(e===0)return;let t,n=e,r=c(),i=1/0;for(let a of p(d()))for(let o of h(a)){let l=g(a,o);if(!l||!_(l))continue;let u=s(l);if(u>=e)continue;let d=c(l),f=a.reduce((e,t,n)=>e+Math.abs(o[n]-t.coord),0);u>n||u===n&&(d>r||d===r&&f>=i)||(t=l,n=u,r=d,i=f)}if(!t)return;for(let[e,n]of t)e.points=n}}t(Ft,`reassignCrossingExternalRailChannels`);function It(e,n){let{realNodeRects:r,labelNodeRects:i}=je(n.values()),a=e.filter(e=>!e.isLayoutOnly),o=t((e,t,n)=>G(e===t?n??[]:e.points??[]),`pointsFor`),s=t(e=>Z(e).reduce((e,t)=>{let n=t.a.x-t.b.x,r=t.a.y-t.b.y;return e+Math.hypot(n,r)},0),`pathLength`),c=t((e,t)=>{let n=0;for(let r=0;r{if(e.horizontal){let n=e.a.y;return(Math.abs(n-t.top)<1||Math.abs(n-t.bottom)<1)&&U(e.a.x,e.b.x,t.left,t.right)>=X}if(e.vertical){let n=e.a.x;return(Math.abs(n-t.left)<1||Math.abs(n-t.right)<1)&&U(e.a.y,e.b.y,t.top,t.bottom)>=X}return!1},`segmentRunsAlongRectBorder`),u=t(e=>{let t=[e.start,e.end].filter(e=>!!e),r=[];for(let e of t){let t=n.get(e),i=t?K(t):void 0;i&&r.push(i)}return r},`endpointRectsFor`),d=t((e,t)=>{if(t+3>=e.length)return[];let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3],o=V(n,r,Y)&&H(r,i,Y)&&V(i,a,Y),s=H(n,r,Y)&&V(r,i,Y)&&H(i,a,Y);if(!o&&!s||!(o?Math.sign(r.x-n.x)!==Math.sign(a.x-i.x):Math.sign(r.y-n.y)!==Math.sign(a.y-i.y)))return[];let c=z(n,a,Y)||B(n,a,Y)?[]:[{x:n.x,y:a.y},{x:a.x,y:n.y}],l=c.length===0?[[...e.slice(0,t+1),...e.slice(t+3)]]:c.map(n=>[...e.slice(0,t+1),n,...e.slice(t+3)]),u=new Set;return l.map(e=>He(G(e))).filter(e=>{if(Z(e).length!==e.length-1||!e.some(e=>R(e,a,Y)))return!1;let t=e.map(e=>`${e.x.toFixed(3)},${e.y.toFixed(3)}`).join(`|`);return u.has(t)?!1:(u.add(t),!0)})},`shortcutCandidatesAt`),f=t((e,t,n)=>{let s=[e.start,e.end].filter(e=>!!e),d=u(e);for(let e of Z(t))if(q(e.a,e.b,r,s,-2)||q(e.a,e.b,i,[],-2)||d.some(t=>l(e,t)))return!1;for(let n of a)if(n!==e){for(let e of Z(t))for(let t of Z(o(n)))if(ve(e,t,.5)>=X)return!1}return c(e,t)<=n},`candidateIsSafe`);for(let e=0;e<8;e++){let e=c(),t,n,r=e,i=1/0,l=1/0;for(let u of a){let a=o(u),p=W(a,Y),m=s(a);for(let o=0;o<=a.length-4;o++)for(let h of d(a,o)){let a=W(h,Y),o=s(h);if(!(ar||d===r&&(a>i||a===i&&o>=l)||(t=u,n=h,r=d,i=a,l=o)}}if(!t||!n)return;t.points=n}}t(It,`shortcutRedundantOrthogonalJogs`);function Lt(e,n){let r=[];for(let e of n.values()){if(e.isGroup||e.isEdgeLabel)continue;let t=e.x??0,n=e.y??0,i=K(e);i&&r.push({id:String(e.id??``),cx:t,cy:n,rect:i})}if(r.length===0)return;let i=new Map(r.map(e=>[e.id,e])),a=r.map(e=>({id:e.id,rect:e.rect})),o=[`top`,`bottom`,`left`,`right`],s={top:Math.min(...r.map(e=>e.rect.top))-20,bottom:Math.max(...r.map(e=>e.rect.bottom))+20,left:Math.min(...r.map(e=>e.rect.left))-20,right:Math.max(...r.map(e=>e.rect.right))+20},c=e.filter(e=>!e.isLayoutOnly),l=new Map(c.map((e,t)=>[e,t])),u=t(e=>{let t=e===`left`||e===`top`?-1:1,n=[];for(let r=0;r<=2;r++)n.push(s[e]+t*20*r);return n},`outwardTracksForSide`),d=t((e,t=new Map)=>G(t.get(e)??e.points??[]),`replacementPointsFor`),f=t((e,t)=>{let n=0;for(let r of e)for(let e of t)Le(r.a,r.b,e.a,e.b,Y)&&n++;return n},`crossingCountBetweenSegments`),p=t((e,t)=>f(Z(e),Z(t)),`crossingCountBetweenPaths`),m=t((e=new Map)=>{let n=0,r=[],i=new Set,a=[],o=t(e=>{i.has(e)||(i.add(e),a.push(e))},`addEdge`);for(let t=0;t0&&(n+=l,r.push({first:i,second:t,count:l}),o(i),o(t))}}return a.sort((e,t)=>(l.get(e)??0)-(l.get(t)??0)),{count:n,pairs:r,edgeSet:i,edges:a}},`crossingSnapshot`),h=t((e,t)=>{let n=new Set(t.keys());if(n.size===0)return e.count;let r=0;for(let t of e.pairs)(n.has(t.first)||n.has(t.second))&&(r+=t.count);let i=0;for(let e=0;e{let t=new Map;for(let n of e.pairs){let e=t.get(n.first)??new Set;e.add(n.second),t.set(n.first,e);let r=t.get(n.second)??new Set;r.add(n.first),t.set(n.second,r)}let n=[],r=new Set;for(let i of e.edges){if(r.has(i))continue;let e=[i],a=[];for(r.add(i);e.length>0;){let n=e.pop();a.push(n);for(let i of t.get(n)??[])r.has(i)||(r.add(i),e.push(i))}a.sort((e,t)=>(l.get(e)??0)-(l.get(t)??0)),a.length>1&&n.push(a)}return n},`crossingComponents`),_=t(e=>[e.start,e.end].filter(e=>!!e),`endpointIdsFor`),v=t(e=>{let t=[];for(let n of g(e)){let e=new Set(n),r=new Set(n.flatMap(e=>_(e))),i=[...n];for(let t of c)e.has(t)||_(t).some(e=>r.has(e))&&i.push(t);i.sort((e,t)=>(l.get(e)??0)-(l.get(t)??0)),t.push(i)}return t},`pairSearchGroups`),y=t((e,t,n)=>h(e,new Map([[t,n]])),`crossingCountWithSingleReplacement`),b=t(e=>{let t=new Map;for(let n of e.pairs)t.set(n.first,(t.get(n.first)??0)+n.count),t.set(n.second,(t.get(n.second)??0)+n.count);return t},`currentCrossingsByEdge`),x=t(e=>e.slice(1).reduce((t,n,r)=>{let i=e[r];return t+Math.abs(n.x-i.x)+Math.abs(n.y-i.y)},0),`pathLength`),S=t((e=new Map)=>c.reduce((t,n)=>t+W(d(n,e)),0),`totalBends`),C=t((e=new Map)=>c.reduce((t,n)=>t+x(d(n,e)),0),`totalLength`),w=t((e,t,n=new Map)=>{let r=Z(t);for(let t of c)if(t!==e){for(let e of r)for(let r of Z(d(t,n)))if(ve(e,r,.5)>=X)return!0}return!1},`pathHasSegmentConflict`),T=t((e,t)=>{let n=[e.start,e.end].filter(e=>!!e);for(let e of Z(t))if(q(e.a,e.b,a,n,-2))return!0;return!1},`pathHitsNode`),E=t((e,t)=>{let n=He(G(t));Z(n).length===n.length-1&&e.push(n)},`pushOrthogonalCandidate`),D=t(e=>e===`left`||e===`right`,`sideIsHorizontal`),O=t((e,t,n)=>{switch(t){case`left`:return Math.min(e.x,n.x)-20;case`right`:return Math.max(e.x,n.x)+20;case`top`:return Math.min(e.y,n.y)-20;case`bottom`:return Math.max(e.y,n.y)+20}},`localTrackForSameSide`),k=t((e,t,n,r)=>{let i=n===`left`||n===`top`?-1:1,a=[O(t,n,r),s[n]];for(let o of a)for(let a=0;a<=2;a++)E(e,ke(t,n,r,o+i*20*a))},`addSameSideCandidates`),A=t((e,t,n,r,i)=>{for(let a of u(n))for(let n of u(i))E(e,[t,{x:a,y:t.y},{x:a,y:n},{x:r.x,y:n},r])},`addHorizontalToVerticalCandidates`),j=t((e,t,n,r,i)=>{for(let a of u(n))for(let n of u(i))E(e,[t,{x:t.x,y:a},{x:n,y:a},{x:n,y:r.y},r])},`addVerticalToHorizontalCandidates`),ee=t((e,t,n,r,i)=>{let a=[...u(`top`),...u(`bottom`)];for(let o of u(n))for(let n of u(i))for(let i of a)E(e,[t,{x:o,y:t.y},{x:o,y:i},{x:n,y:i},{x:n,y:r.y},r])},`addHorizontalPairCandidates`),te=t((e,t,n,r,i)=>{let a=[...u(`left`),...u(`right`)];for(let o of u(n))for(let n of u(i))for(let i of a)E(e,[t,{x:t.x,y:o},{x:i,y:o},{x:i,y:n},{x:r.x,y:n},r])},`addVerticalPairCandidates`),M=t(e=>{let t=new Set;return e.map(e=>G(e)).filter(e=>{let n=e.map(e=>`${e.x.toFixed(3)},${e.y.toFixed(3)}`).join(`|`);return t.has(n)||e.length<2?!1:(t.add(n),!0)})},`dedupeCandidatePaths`),ne=t((e,t,n,r)=>{let i=[],a=Oe(e,t,n,r,20,Y);a&&E(i,a),t===r&&k(i,e,t,n);let o=D(t),s=D(r);return o&&!s?A(i,e,t,n,r):!o&&s?j(i,e,t,n,r):o?ee(i,e,t,n,r):te(i,e,t,n,r),M(i)},`buildCandidatesForSides`),N=t((e,t,n,r)=>{let i=[...u(`left`),...u(`right`)],a=[...u(`top`),...u(`bottom`)];for(let s of o){let o=De(r,s),c=s===`top`||s===`bottom`?u(s):a;for(let r of i){E(e,[t,n,{x:r,y:n.y},{x:r,y:o.y},o]);for(let i of c)E(e,[t,n,{x:r,y:n.y},{x:r,y:i},{x:o.x,y:i},o])}}},`addVerticalDepartureOuterTrackCandidates`),re=t((e,t,n,r)=>{let i=[...u(`left`),...u(`right`)],a=[...u(`top`),...u(`bottom`)];for(let s of o){let o=De(r,s),c=s===`left`||s===`right`?u(s):i;for(let r of a){E(e,[t,n,{x:n.x,y:r},{x:o.x,y:r},o]);for(let i of c)E(e,[t,n,{x:n.x,y:r},{x:i,y:r},{x:i,y:o.y},o])}}},`addHorizontalDepartureOuterTrackCandidates`),P=t(e=>{let t=e.start,n=e.end,r=n?i.get(n):void 0;if(!t||!r)return[];let a=G(e.points??[]);if(a.length<4)return[];let o=a[0],s=a[1],c=[];return H(o,s,Y)?N(c,o,s,r):V(o,s,Y)&&re(c,o,s,r),c},`terminalPreservingOuterTrackCandidates`),ie=t(e=>{let t=e.start,n=e.end,r=t?i.get(t):void 0,a=n?i.get(n):void 0;if(!r||!a)return[];let s=[];for(let e of o){let t=De(r,e);for(let n of o)s.push(...ne(t,e,De(a,n),n))}return s.push(...P(e)),s},`candidatePathsFor`),ae=t(()=>new Map(c.map(e=>[e,Z(d(e))])),`currentSegmentsByEdge`),oe=t((e,t,n)=>{let r=new Set;for(let i of c){if(i===e)continue;let a=n.get(i)??Z(d(i));t.some(e=>a.some(t=>ve(e,t,.5)>=X))&&r.add(i)}return r},`sharedTrackConflictsFor`),se=t((e,t,n,r)=>{let i=new Set;return ie(e).map(e=>He(G(e))).filter(t=>{if(T(e,t))return!1;let n=t.map(e=>`${e.x.toFixed(3)},${e.y.toFixed(3)}`).join(`|`);return i.has(n)||t.length<2?!1:(i.add(n),!0)}).map(i=>{let a=Z(i),o=0;for(let t of c)t!==e&&(o+=f(a,n.get(t)??Z(d(t))));return{candidate:i,candidateSegments:a,crossings:t.count-(r.get(e)??0)+o,bends:W(i,Y),totalBends:W(i),length:x(i)}}).filter(({crossings:e})=>e<=t.count).sort((e,t)=>e.crossings-t.crossings||e.bends-t.bends||e.length-t.length).slice(0,48).map(t=>({path:t.candidate,segments:t.candidateSegments,sharedTrackConflicts:oe(e,t.candidateSegments,n),totalBends:t.totalBends,length:t.length}))},`pairCandidatesFor`),ce=t((e,t,n,r,i,a)=>{let o=0;for(let n of e.pairs)(n.first===t||n.second===t||n.first===r||n.second===r)&&(o+=n.count);let s=f(n.segments,i.segments);for(let e of c){if(e===t||e===r)continue;let o=a.get(e)??Z(d(e));s+=f(n.segments,o)+f(i.segments,o)}return e.count-o+s},`pairCrossingCount`),le=t((e,t)=>{for(let n of e.sharedTrackConflicts)if(n!==t)return!1;return!0},`conflictsOnlyWith`),ue=t((e,t)=>e.segments.some(e=>t.segments.some(t=>ve(e,t,.5)>=X)),`candidatesShareTrack`),de=t((e,t,n,r)=>le(t,n.edge)&&le(r,e.edge)&&!ue(t,r),`pairCandidatesAreCompatible`),fe=t((e,t,n,r,i)=>{let a=ce(e.current,t.edge,n,r.edge,i,e.baseSegments);if(!(a>=e.current.count))return{replacements:new Map([[t.edge,n.path],[r.edge,i.path]]),crossings:a,bends:e.currentBends-(e.baseBendsByEdge.get(t.edge)??0)-(e.baseBendsByEdge.get(r.edge)??0)+n.totalBends+i.totalBends,length:e.currentLength-(e.baseLengthByEdge.get(t.edge)??0)-(e.baseLengthByEdge.get(r.edge)??0)+n.length+i.length}},`scorePairReplacement`),pe=t((e,t)=>e.crossings{let i=r;for(let r of t.candidates)for(let a of n.candidates){if(!de(t,r,n,a))continue;let o=fe(e,t,r,n,a);o&&pe(o,i)&&(i=o)}return i},`bestScoreForOptionPair`),I=t(e=>{let t=S(),n=C(),r=ae(),i=b(e),a=new Map(c.map(e=>[e,W(d(e))])),o=new Map(c.map(e=>[e,x(d(e))])),s=new Map,l=v(e);for(let t of l)for(let n of t){if(s.has(n))continue;let t=se(n,e,r,i);t.length>0&&s.set(n,{edge:n,candidates:t})}let u={replacements:new Map,crossings:e.count,bends:t,length:n},f={current:e,currentBends:t,currentLength:n,baseBendsByEdge:a,baseLengthByEdge:o,baseSegments:r};for(let t of l){let n=new Set(t.filter(t=>e.edgeSet.has(t))),r=t.map(e=>s.get(e)).filter(e=>!!e);for(let e=0;e0?u.replacements:void 0},`bestPairedReplacement`);for(let e=0;e<4;e++){let e=m(),t=e.count;if(t===0)return;let n,r,i=t,a=1/0;for(let o of e.edges){let s=W(d(o),Y);for(let c of ie(o)){let l=T(o,c),u=!l&&w(o,c),d=y(e,o,c),f=W(c,Y);l||u||(di||d===i&&f>=a||(n=o,r=c,i=d,a=f))}}if(n&&r){n.points=r;continue}let o=I(e);if(!o)return;for(let[e,t]of o)e.points=t}}t(Lt,`resolveRenderedOrthogonalCrossings`);var Rt=.001,zt=8;function Bt(e,n){let{nodeInfoById:r,realNodeRects:i}=Ae(n),a=[`top`,`bottom`,`left`,`right`],o={top:Math.min(...i.map(e=>e.rect.top))-20,bottom:Math.max(...i.map(e=>e.rect.bottom))+20,left:Math.min(...i.map(e=>e.rect.left))-20,right:Math.max(...i.map(e=>e.rect.right))+20},s=t((e,t,n,r)=>{let i=[],a=Oe(e,t,n,r,20,Rt);return a&&i.push(a),t===r&&i.push(ke(e,t,n,o[t])),i},`buildOrthogonalPathCandidates`),c=t((e,t)=>{for(let n=0;n{let i=0,a=ye(t,Rt),o=n.start,s=n.end;for(let t of e){if(t===n||t.isLayoutOnly)continue;let e=t.start,c=t.end;if(!r&&o&&s&&(e===o||e===s||c===o||c===s))continue;let l=t.points;if(!(!l||l.length<2))for(let e of a)for(let t of ye(l,Rt)){if(Pe(e.a,e.b,t.a,t.b,Rt,Rt)){i++;continue}ve(e,t,Rt)>=zt&&i++}}return i},`pathConflictCount`),u=t((e,t)=>{let n=Math.abs(e.y-t.rect.top),r=Math.abs(e.y-t.rect.bottom),i=Math.abs(e.x-t.rect.left),a=Math.abs(e.x-t.rect.right),o=`top`,s=n;return r{let r=d.get(e)??[];r.push({side:t,edgeId:n}),d.set(e,r)},`addFaceClaim`);for(let t of e){if(t.isLayoutOnly)continue;let e=t.points??[];if(e.length<1)continue;let n=t.id??``,i=t.start,a=t.end;if(i){let t=r.get(i);t&&f(i,u(e[0],t),n)}if(a){let t=r.get(a);t&&f(a,u(e[e.length-1],t),n)}}let p=t((e,t,n)=>d.get(e)?.some(e=>e.edgeId!==n&&e.side===t)??!1,`faceIsClaimed`);for(let t of e){if(t.isLayoutOnly)continue;let e=t.points;if(!e||e.length<2)continue;let n=W(e,Rt);if(n<4)continue;let i=t.start,o=t.end;if(!i||!o)continue;let m=r.get(i),h=r.get(o);if(!m||!h)continue;let g=t.id??``,_=l(e,t,!0),v=l(e,t),y,b=_,x=n;for(let e of a){if(p(i,e,g))continue;let n=De(m,e);for(let r of a){if(p(o,r,g))continue;let a=De(h,r);for(let u of s(n,e,a,r)){if(c(u,[i,o]))continue;let e=W(u,Rt);if(_>0){let n=l(u,t,!0);if(n>b||n===b&&e>=x)continue;b=n,x=e,y=u;continue}l(u,t)>v||ee.edgeId!==g));let n=d.get(o);n&&d.set(o,n.filter(e=>e.edgeId!==g)),f(i,u(y[0],m),g),f(o,u(y[y.length-1],h),g)}}}t(Bt,`simplifyDetouredEdges`);var Q=.001,Vt=10,Ht=7;function Ut(e,t){let n=t?0:e.length-1,r=t?1:-1,i=e[n],a=e[n+r];if(!i||!a)return;let o=a.x-i.x,s=a.y-i.y;if(!(Math.abs(o)+Math.abs(s)t&&we(e,Wt(t)))}t(Gt,`labelOverlapsOwnMarker`);function Kt(e,n){let r=[];for(let t of e){if(t.isLayoutOnly)continue;let e=t.points;if(!(!e||e.length<2))for(let n=0;n{let n=Te(t,3);for(let{nodeId:t,rect:r}of i)if(t!==e&&we(n,r))return!0;return!1},`labelOverlapsForeignNode`),s=t((e,t)=>{let n=Te(t,3);for(let t of r)if(t.edgeId!==e&&xe(t.p1,t.p2,n))return!0;return!1},`labelOverlapsForeignEdge`),c=t((e,t,n)=>o(e,n)||s(t,n),`labelOverlapsAnything`),l=[],u=t(e=>{for(let{id:t,rect:n}of a)if(Ce(n,e))return t},`findContainingLane`),d=t((e,t)=>l.some(n=>n.labelId!==e&&we(t,n.rect)),`overlapsPlacedLabel`);for(let r of e){if(r.isLayoutOnly)continue;let e=r.labelNodeId;if(!e)continue;let i=n.get(e);if(!i)continue;let f=r.points;if(!f||f.length<2)continue;let p=i.width??0,m=i.height??0;if(p<=0||m<=0)continue;let h=[];for(let e=0;e=Q&&i>=Q||h.push({idx:e,length:r+i,orientation:r>=Q?`horizontal`:`vertical`,midX:(t.x+n.x)/2,midY:(t.y+n.y)/2})}if(h.length===0)continue;let g=h.length>=3?h.filter(e=>e.idx>0&&e.idx0?g:h,v=p>=m?`horizontal`:`vertical`,y=t(e=>[...e].sort((e,t)=>{let n=e.orientation===v;if(n!==(t.orientation===v))return n?-1:1;let r=e.length>=(e.orientation===`horizontal`?p:m)+2;return r===t.length>=(t.orientation===`horizontal`?p:m)+2?t.length-e.length:r?-1:1}),`rankSegments`),b=h[0],x=h[h.length-1],S=[.5,.25,.75,.05,.95,.15,.85,.1,.9],C=t((e,t)=>{let n=f[e.idx],r=f[e.idx+1];return{midX:n.x+(r.x-n.x)*t,midY:n.y+(r.y-n.y)*t}},`anchorAtT`),w=t((e,t,n)=>Math.min(n,Math.max(t,e)),`clamp`),T=t((e,t)=>e.midX>=t.left-Q&&e.midX<=t.right+Q&&e.midY>=t.top-Q&&e.midY<=t.bottom+Q,`pointInsideRectInclusive`),E=t(e=>{let t=Ee(e.midX,e.midY,p,m),n=u(t);if(n)return{laneId:n,anchor:e,rect:t};let r=a.find(({rect:t})=>T(e,t));if(!r)return;let i=r.rect.left+p/2+1,o=r.rect.right-p/2-1,s=r.rect.top+m/2+1,c=r.rect.bottom-m/2-1;if(i>o||s>c)return;let l={midX:w(e.midX,i,o),midY:w(e.midY,s,c)},d=Ee(l.midX,l.midY,p,m);return T(e,d)?{laneId:r.id,anchor:l,rect:d}:void 0},`placementForAnchor`),D=t((e,t,n)=>e.orientation===`horizontal`?Math.abs(t.midX-n.x):Math.abs(t.midY-n.y),`distanceAlongSegment`),O=t((e,t)=>{let n=(e.orientation===`horizontal`?p/2:m/2)+12;if(e===b){let r=f[e.idx];if(D(e,t,r)+Q{let n=y(t);for(let t of n)for(let n of S){let i=C(t,n);if(!O(t,i))continue;let a=E(i);if(a&&!Gt(a.rect,f)&&!d(e,a.rect)&&!c(e,r.id,a.rect))return{laneId:a.laneId,anchor:a.anchor}}},`tryPool`),A=t((t,n,i=!1)=>{let a=y(t);for(let t of a){let a={midX:t.midX,midY:t.midY};if(n&&!O(t,a))continue;let c=E(a);if(c&&!Gt(c.rect,f)&&!d(e,c.rect)&&!o(e,c.rect)&&(i||!s(r.id,c.rect)))return{laneId:c.laneId,anchor:c.anchor}}},`findLaneContainingFallback`),j=k(_)??(_.lengtht.labelId===e);n>=0?l[n]={labelId:e,rect:t}:l.push({labelId:e,rect:t})}}}t(Kt,`anchorLabelsToPolyline`);var qt=1e-6,Jt=8/2,Yt=3;function Xt(e,t){return e{let s=Xt(r,i),c=0,l=t(e=>{if(!e)return;let t=a.get(e);if(!t)return;let n=o===`x`?t.w/2:t.h/2;n>c&&(c=n)},`consider`);l(n.labelNodeId);for(let t of e){if(t===n||t.isLayoutOnly)continue;let e=t.start,r=t.end;!e||!r||Xt(e,r)===s&&l(t.labelNodeId)}return c>0?c+Yt:0},`labelClearanceFor`);for(let t of e){if(t.isLayoutOnly)continue;let n=t.points;if(!be(n,qt))continue;let a=Ne(t,r,qt);if(!a)continue;let{srcId:s,dstId:c,srcInfo:l,dstInfo:u,collinearX:d,collinearY:f}=a;if(d===f)continue;let p,m;if(d){let e=u.cy>l.cy;p={x:l.cx,y:e?l.rect.bottom:l.rect.top},m={x:u.cx,y:e?u.rect.top:u.rect.bottom}}else{let e=u.cx>l.cx;p={x:e?l.rect.right:l.rect.left,y:l.cy},m={x:e?u.rect.left:u.rect.right,y:u.cy}}if(q(p,m,i,[s,c],1))continue;let h=o(t,s,c,d?`x`:`y`),g=h>Jt?h:Jt,_=[0,g,-g];for(let n of _){let r={...p},a={...m};if(d){if(r.x+=n,a.x+=n,r.x<=l.rect.left||r.x>=l.rect.right||a.x<=u.rect.left||a.x>=u.rect.right)continue}else if(r.y+=n,a.y+=n,r.y<=l.rect.top||r.y>=l.rect.bottom||a.y<=u.rect.top||a.y>=u.rect.bottom)continue;if(!q(r,a,i,[s,c],1)&&!Ie(r,a,e,t,{epsilon:qt})){t.points=[r,a];break}}}}t(Zt,`straightenCollinearSiblingDetours`);function Qt(e,n){let r=.001,{realNodeRects:i,labelNodeRects:a}=je(n.values()),o=t((e,t)=>ye(t,r).map(n=>({...n,edge:e,interior:n.index>=1&&n.index<=t.length-3})),`segmentsFor`),s=t(()=>{let t=[];for(let n of e){if(n.isLayoutOnly)continue;let e=n.points;!e||e.length<2||t.push(...o(n,G(e)))}return t},`allSegments`),c=t((e,t)=>e.horizontal&&t.horizontal?U(e.a.x,e.b.x,t.a.x,t.b.x)>=8&&Math.abs(e.a.y-t.a.y)<7:e.vertical&&t.vertical?U(e.a.y,e.b.y,t.a.y,t.b.y)>=8&&Math.abs(e.a.x-t.a.x)<7:!1,`hasCrowdedParallelTrack`),l=t((t,n)=>{let s=t.start,l=t.end,u=o(t,n);if(u.length!==n.length-1)return!1;let d=[s,l].filter(e=>!!e),f=t.labelNodeId?[t.labelNodeId]:[];for(let e of u)if(q(e.a,e.b,i,d,-2)||q(e.a,e.b,a,f,-2))return!1;for(let n of e){if(n===t||n.isLayoutOnly)continue;let e=n.points;if(!(!e||e.length<2)){for(let t of u)for(let i of o(n,G(e)))if(c(t,i)||Le(t.a,t.b,i.a,i.b,r))return!1}}return!0},`candidateIsSafe`),u=t((e,t)=>{let n=G(e.edge.points??[]);if(n.length<4||e.index>=n.length-1)return;let r=n.map(e=>({...e}));if(e.horizontal)r[e.index].y+=t,r[e.index+1].y+=t;else if(e.vertical)r[e.index].x+=t,r[e.index+1].x+=t;else return;return o(e.edge,r).length===r.length-1?r:void 0},`shiftedCandidate`),d=t((e,t)=>({x:e.x??(t.left+t.right)/2,y:e.y??(t.top+t.bottom)/2}),`nodeCenter`),f=t(e=>{let t=e.edge,r=G(t.points??[]);if(r.length!==4||e.index!==1)return;let i=t.start?n.get(t.start):void 0,a=t.end?n.get(t.end):void 0,o=i?K(i):void 0,s=a?K(a):void 0,c=r.slice(e.index+2);if(!(!i||!a||!o||!s||c.length===0))return{sourceCenter:d(i,o),targetCenter:d(a,s),sourceRect:o,tail:c}},`sourceDetourContextFor`),p=t((e,t,n,i,a,o)=>{let s=i.y>=n.y,c=s?a.bottom:a.top,l=c+(s?20:-20);if(s&&e.b.y<=l+r||!s&&e.b.y>=l-r)return;let u=e.a.x+t;return G([{x:n.x,y:c},{x:n.x,y:l},{x:u,y:l},{x:u,y:e.b.y},...o],r)},`verticalSourceDetour`),m=t((e,t,n,i,a,o)=>{let s=i.x>=n.x,c=s?a.right:a.left,l=c+(s?20:-20);if(s&&e.b.x<=l+r||!s&&e.b.x>=l-r)return;let u=e.a.y+t;return G([{x:c,y:n.y},{x:l,y:n.y},{x:l,y:u},{x:e.b.x,y:u},...o],r)},`horizontalSourceDetour`),h=t((e,t)=>{let n=f(e);if(n){if(e.vertical)return p(e,t,n.sourceCenter,n.targetCenter,n.sourceRect,n.tail);if(e.horizontal)return m(e,t,n.sourceCenter,n.targetCenter,n.sourceRect,n.tail)}},`sourceDetourCandidate`),g=[-7,7,-14,14,-21,21];for(let e=0;e<12;e++){let e=s(),t=!1;for(let n=0;ne.interior);for(let e of o){for(let n of g){let r=u(e,n);if(r&&l(e.edge,r)){e.edge.points=r,t=!0;break}let i=h(e,n);if(i&&l(e.edge,i)){e.edge.points=i,t=!0;break}}if(t)break}}if(!t)return}}t(Qt,`nudgeSharedInteriorSubpaths`);function $t(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=r.x-n.x,s=r.y-n.y,c=i*s-a*o;if(Math.abs(c)<1e-10)return!1;let l=n.x-e.x,u=n.y-e.y,d=(l*s-u*o)/c,f=(l*a-u*i)/c,p=.01;return d>p&&d<1-p&&f>p&&f<1-p}t($t,`segmentsIntersect`);function en(e){let t=e.nodes??[],r=e.edges??[],i=[];if(!r.length||!t.length)return i;let a=Me(t),o=[];for(let e of r){if(e.isLayoutOnly)continue;let t=e.points;if(!t||t.length<2)continue;let n=e.start,r=e.end,s=e.labelNodeId,c=e.id??`${n}->${r}`;for(let e of a)if(!(e.nodeId===n||e.nodeId===r)&&!(s&&e.nodeId===s)){for(let n=0;n0){let e=i.filter(e=>e.type===`edge-node-overlap`).length,t=i.filter(e=>e.type===`edge-edge-crossing`).length;n.warn(`[SWIMLANE_VALIDATE] ${i.length} issue(s) detected: ${e} edge-node overlap(s), ${t} edge crossing(s)`);for(let e of i)n.warn(`[SWIMLANE_VALIDATE] ${e.type}: ${e.detail}`)}return i}t(en,`validateSwimlanesLayout`);function tn(e,n){let r=e.nodes??[],i=e.edges??[],a=r.filter(e=>!e.isGroup);if((n===`LR`||n===`RL`)&&a.length>0&&!St(e,n)||n===`BT`&&a.length>0&&!xt(e))return;for(let e of i){if(e.isLayoutOnly)continue;let t=e.points;!t||t.length<2||(e.points=He(Ve(t)))}Bt(i,r),Zt(i,r),Et(i,r);let o=new Map;for(let e of r)o.set(String(e.id),e);Kt(i,o),Je(i,o),Dt(i,o),Qt(i,o),kt(i,o),At(i,o),jt(i,o),Pt(i,o);let s=t(()=>{Lt(i,o),Ft(i,o),It(i,o),Kt(i,o),pt(i,o),jt(i,o),Kt(i,o),pt(i,o)},`finalizeRenderedEdges`);s(),Qt(i,o),s(),Mt(i,o),Nt(i,o),Mt(i,o),Nt(i,o)}t(tn,`postProcessSwimlaneLayout`);function nn(e){let t=new Map(e.nodeById),n=new Set,r=[];for(let i of e.edges){if(!t.has(i.src)||!t.has(i.dst))continue;let e=`${i.id}:${i.src}->${i.dst}`;n.has(e)||(n.add(e),r.push(i))}return{nodes:[...t.keys()],edges:r,layout:e.layout,nodeById:t}}t(nn,`normalizeGraph`);function rn(e,t){return e.edges.filter(e=>e.dst===t)}t(rn,`incoming`);function an(e){let t=new Map;for(let n of e.nodes)t.set(n,[]);for(let n of e.edges)t.get(n.src).push(n.dst);return t}t(an,`buildSuccessorMap`);function on(e){let t=an(e);for(let e of t.values())e.sort((e,t)=>e.localeCompare(t));return t}t(on,`buildSortedSuccessorMap`);function sn(e){let t=new Map;for(let n of e.nodes)t.set(n,0);for(let n of e.edges)t.set(n.dst,(t.get(n.dst)??0)+1);return t}t(sn,`buildInDegreeMap`);function cn(e){return[...e.entries()].filter(([,e])=>e===0).map(([e])=>e).sort((e,t)=>e.localeCompare(t))}t(cn,`sortedZeroInDegreeNodes`);function ln(e,t=()=>!0){let n=new Map,r=new Map;for(let t of e.nodes)n.set(t,[]),r.set(t,[]);for(let i of e.edges)t(i)&&(r.get(i.src).push(i.dst),n.get(i.dst).push(i.src));return{preds:n,succs:r}}t(ln,`buildPredecessorSuccessorMaps`);function un(e,t,n,r){let i=0;for(let t of e.nodes)r?.skipGroups&&e.nodeById.get(t)?.isGroup||(i=Math.max(i,n[t]??0));let a=Array.from({length:i+1},()=>[]);for(let i of t)r?.skipGroups&&e.nodeById.get(i)?.isGroup||a[Math.max(0,n[i]??0)].push(i);return a}t(un,`buildLayersFromRanks`);function dn(e){let t=sn(e),n=cn(t),r=[],i=on(e);for(;n.length;){let e=n.shift();r.push(e);for(let r of i.get(e)??[])if(t.set(r,(t.get(r)??0)-1),(t.get(r)??0)===0){let e=0;for(;e{if(i-t<=1)return 0;let a=t+i>>1,o=r(t,a)+r(a,i),s=t,c=a,l=t;for(;s=i||se.dst===t.dst?e.id.localeCompare(t.id):e.dst.localeCompare(t.dst));let i=Object.create(null);for(let e of n.nodes)i[e]=0;let a=[],o=t(e=>{i[e]=1;for(let t of r.get(e)??[]){let e=t.dst;i[e]===0?o(e):i[e]===1&&a.push(t)}i[e]=2},`dfs`),s=[...n.nodes].sort((e,t)=>e.localeCompare(t));for(let e of s)i[e]===0&&o(e);let c=new Set(a.map(e=>`${e.id}:${e.src}->${e.dst}`)),l=n.edges.map(e=>c.has(`${e.id}:${e.src}->${e.dst}`)?{id:e.id,src:e.dst,dst:e.src,weight:e.weight,ref:e.ref}:e);return{acyclic:{nodes:[...n.nodes],edges:l,layout:n.layout,nodeById:new Map(n.nodeById)},reversed:a}}t(mn,`removeCycles_DFS`);function hn(e){let n=new Map,r=t(t=>{if(n.has(t))return n.get(t);let i=e.nodeById.get(t);if(!i)return n.set(t,null),null;let a=i.parentId;if(!a)return n.set(t,null),null;let o=r(a)??a;return n.set(t,o),o},`resolve`);for(let t of e.nodes)r(t);return n}t(hn,`buildTopLaneMap`);function gn(e){let t=hn(e);return e=>t.get(e)??null}t(gn,`createTopLaneResolver`);function _n(e){let t=[];for(let n of e.layout.nodes??[])n.isGroup&&!n.parentId&&t.push(n.id);return[...new Set(t)].reverse()}t(_n,`buildTopLaneOrder`);function vn(e,t){let n=_n(e);if(!t||t.length===0)return n;let r=new Set(n),i=new Set,a=[];for(let e of t)!r.has(e)||i.has(e)||(i.add(e),a.push(e));for(let e of n)i.has(e)||a.push(e);return a}t(vn,`resolveTopLaneOrder`);var yn={EPSILON:1e-6},bn={GRAVITY_ITERATIONS:8,MAX_CROSSING_OPTIMIZATION_PASSES:4,DEFAULT_COMPACT_SINGLE_INPUT:!0},xn={DEFAULT_LAYER_GAP:100,DEFAULT_NODE_GAP:40};function Sn(e,n){let r=nn(e),i=n?.laneOf??(()=>null),a=n?.rankHint,{preds:o}=ln(r);for(let e of o.values())e.sort((e,t)=>e.localeCompare(t));let s=dn(r)??[...r.nodes].sort((e,t)=>e.localeCompare(t)),c=new Map;for(let[e,t]of s.entries())c.set(t,e);let l=new Map,u=new Map;for(let e of r.nodes)u.set(e,[]);for(let e of s){let t=(o.get(e)??[]).filter(e=>l.has(e));if(t.length>0){let n=Cn(e,t,{laneOf:i,rankHint:a,topoIndex:c});l.set(e,n),u.get(n).push(e)}else l.has(e)||l.set(e,null)}for(let e of r.nodes)l.has(e)||l.set(e,null);let d=new Set;for(let e of r.nodes)(l.get(e)??null)===null&&d.add(e);let f=[...d].sort((e,t)=>{let n=c.get(e)??0,r=c.get(t)??0;return n===r?e.localeCompare(t):n-r}),p=wn(r),m=new Map;for(let[e,t]of p.entries())m.set(e,[...t].sort((e,t)=>e.localeCompare(t)));let h=Tn(m),g=En(m),_=new Map;for(let e of r.nodes)_.set(e,[]);for(let e of g)for(let t of e.nodes){let n=_.get(t);n?n.push(e.id):_.set(t,[e.id])}let v=[],y=[],b=new Set,x=t(e=>{if(!b.has(e)){b.add(e),v.push(e);for(let t of u.get(e)??[])x(t);y.push(e)}},`walk`);for(let e of f)x(e);for(let e of s)x(e);return{parent:l,children:u,roots:f,componentOf:h,blocks:g,nodeBlocks:_,adjacency:m,preorder:v,postorder:y,topologicalOrder:s}}t(Sn,`buildDrivingTree`);function Cn(e,t,n){let r=n.laneOf(e);return[...t].sort((e,t)=>{let i=n.laneOf(e),a=n.laneOf(t),o=i!=null&&i===r;if(o!==(a!=null&&a===r))return o?-1:1;let s=n.rankHint?.[e],c=n.rankHint?.[t];if(s!=null&&c!=null&&s!==c)return c-s;let l=n.topoIndex.get(e)??0,u=n.topoIndex.get(t)??0;return l===u?e.localeCompare(t):l-u})[0]}t(Cn,`chooseParent`);function wn(e){let t=new Map;for(let n of e.nodes)t.set(n,new Set);for(let n of e.edges)t.get(n.src).add(n.dst),t.get(n.dst).add(n.src);return t}t(wn,`buildAdjacency`);function Tn(e){let t=new Map,n=0;for(let r of e.keys()){if(t.has(r))continue;let i=[r];for(;i.length>0;){let r=i.pop();if(!t.has(r)){t.set(r,n);for(let n of e.get(r)??[])t.has(n)||i.push(n)}}n++}return t}t(Tn,`assignComponents`);function En(e){let n=new Map,r=new Map,i=[],a=[],o=0,s=t((t,c)=>{n.set(t,++o),r.set(t,o);for(let l of e.get(t)??[])l!==c&&(n.has(l)?(n.get(l)??0)<(n.get(t)??0)&&(i.push([t,l]),r.set(t,Math.min(r.get(t)??o,n.get(l)??o))):(i.push([t,l]),s(l,t),r.set(t,Math.min(r.get(t)??o,r.get(l)??o)),(r.get(l)??0)>=(n.get(t)??0)&&a.push(Dn(t,l,i,a.length))))},`visit`);for(let t of e.keys())n.has(t)||s(t,null);return a}t(En,`computeBlocks`);function Dn(e,t,n,r){let i=[],a=new Set;for(;n.length>0;){let r=n.pop();if(i.push(r),a.add(r[0]),a.add(r[1]),r[0]===e&&r[1]===t||r[0]===t&&r[1]===e)break}return{id:r,edges:i,nodes:[...a]}}t(Dn,`popBlock`);function On(e,n,r){let i=[...e.nodes],a=new Map;for(let[e,t]of i.entries())a.set(t,e);let o=i.length,s=Array(o).fill(-1),c=Array(o).fill(0),l=[],u=new Set;for(let e of i){let t=r.parent.get(e)??null,n=a.get(e);n!=null&&(t??(s[n]=-1,c[n]=0,u.has(e)||(u.add(e),l.push(e))))}for(;l.length>0;){let e=l.shift(),t=a.get(e);if(t==null)continue;let n=r.children.get(e)??[];for(let e of n){if(u.has(e))continue;let n=a.get(e);n!=null&&(s[n]=t,c[n]=c[t]+1,u.add(e),l.push(e))}}for(let e of i){if(u.has(e))continue;let t=a.get(e);t!=null&&(s[t]=-1,c[t]=0,u.add(e))}let d=Math.max(1,Math.ceil(Math.log2(Math.max(1,o)))+1),f=Array.from({length:d},()=>Array(o).fill(-1));for(let e=0;e{if(e===-1||t===-1)return-1;c[e]>t&1&&(e=f[t][e],e===-1))return-1;if(e===t)return e;for(let n=d-1;n>=0;n--){let r=f[n][e],i=f[n][t];r===-1||i===-1||r!==i&&(e=r,t=i)}return f[0][e]},`lcaIndex`),m=Array.from({length:o},()=>new Map);for(let t of e.edges){let e=t.src,r=t.dst,i=n[e],o=n[r];if(i==null||o==null||(i>o&&([e,r]=[r,e],[i,o]=[o,i]),i==null||o==null||i===o))continue;let s=a.get(e),c=a.get(r);if(s==null||c==null)continue;let l=p(s,c);if(l===-1)continue;let u=m[l];for(let e=i;e{if(t.size!==0)for(let[n,r]of t)e.set(n,(e.get(n)??0)+r)},`mergeInto`),_=new Set,v=t(e=>{let t=a.get(e);_.add(e);let i=t==null?void 0:m[t],o=i?new Map(i):new Map,s=r.children.get(e)??[];for(let t of s){let r=v(t),i=n[e];if(i!=null){let a=h.get(e);a||(a=new Map,h.set(e,a));let o=r.get(i)??0,s=n[t];s!=null&&s>i&&(o+=1),a.set(t,o)}g(o,r)}return o},`dfs`);for(let e of r.roots)_.has(e)||v(e);for(let e of i)_.has(e)||v(e);return h}t(On,`computeSubtreeCrossCounts`);function kn(e,n,r){let i=new Map,a=t(e=>{let t=r[e]??0,o=[...n.get(e)??[]];o.sort(An(r));for(let e of o){a(e);let n=i.get(e);n!=null&&(t=Math.min(t,n))}i.set(e,t)},`annotate`);for(let t of e)a(t);return i}t(kn,`annotateMinimumLayers`);function An(e){return(t,n)=>{let r=e[t]??0,i=e[n]??0;return r===i?t.localeCompare(n):r-i}}t(An,`compareByRankThenId`);function jn(e,n,r,i){let a=0;for(let e of n){let t=r[e]??0;t>a&&(a=t)}let o=Array.from({length:a+1},()=>[]),s=new Set,c=t(e=>{if(s.has(e))return;s.add(e);let t=r[e]??0;o[t]||(o[t]=[]),o[t].push(e);for(let t of i(e))c(t)},`emit`);for(let t of e)c(t);for(let e of n)if(!s.has(e)){let t=r[e]??0;o[t]||(o[t]=[]),o[t].push(e),s.add(e)}return o}t(jn,`emitNodesInTreeOrder`);function Mn(e){let t=[];for(let n of e){let e=new Set,r=[];for(let t of n)e.has(t)||(e.add(t),r.push(t));t.push(r)}return t}t(Mn,`deduplicateLayers`);function Nn(e,t,n,r){return i=>{let a=e.get(i)??[];if(a.length===0)return[];let o=t[i]??0,s=[],c=[],l=n.get(i);for(let e of a){let t=r.get(e)??o;t>o?s.push({child:e,min:t}):c.push(e)}return s.sort((e,t)=>e.min===t.min?e.child.localeCompare(t.child):e.min-t.min),c.sort((e,t)=>{let n=l?.get(e)??0,i=l?.get(t)??0;if(n!==i)return n-i;let a=r.get(e)??o,s=r.get(t)??o;return a===s?e.localeCompare(t):a-s}),[...s.map(e=>e.child),...c]}}t(Nn,`createChildOrderer`);function Pn(e,t,n){let r=Sn(e,{rankHint:t,laneOf:n}),{children:i,roots:a}=r;for(let t of e.nodes)i.has(t)||i.set(t,[]);let o=On(e,t,r),s=[...a].sort(An(t)),c=Nn(i,t,o,kn(s,i,t)),l=jn(s,e.nodes,t,c);return l=Mn(l),l}t(Pn,`buildMultitreeLayerOrder`);function Fn(e,t,n){let r=new Set(e),i=new Set(t),a=fn(t),o=[];for(let e of n)r.has(e.src)&&i.has(e.dst)&&o.push(a.get(e.dst));return pn(o)}t(Fn,`countCrossingsBetweenAdjacent`);function In(e,t,n){let r=[];for(let e of t){let t=n[e.src],i=n[e.dst];if(t==null||i==null||t===i)continue;let a=e.src,o=e.dst,s=t,c=i;t>i&&(a=e.dst,o=e.src,s=i,c=t);for(let t=s;t(n[t]??0)-(n[e]??0));for(let s of o){let o=n[s]??0;if(o===0)continue;let c=0;for(let e of r.get(s)??[])c=Math.max(c,(n[e]??0)+1);if(c>=o)continue;let l=o;n[s]=c;let u=In(Pn(e,n,i),e.edges,n);u(t[e]??0)-(t[n]??0)||e.localeCompare(n));for(let i of r){let r=n(i);if(!r)continue;let a=e.edges.filter(e=>e.src===i);if(a.length===0)continue;let o=!1,s=0;for(let e of a){let t=n(e.dst);t==null||t===r?o=!0:s++}if(s===0||o)continue;let c=0,l=!1;for(let t of e.edges){if(t.dst!==i)continue;let e=n(t.src);e&&(e===r?l=!0:c++)}if(c>0||!l)continue;let u=t[i]??0,d=u+s,f=0;for(let n of e.edges)n.dst===i&&(f=Math.max(f,(t[n.src]??0)+1));let p=Math.max(u,f,d);p!==u&&(t[i]=p)}}t(Rn,`adjustCrossLaneSources`);function zn(e,t){let n=nn(e),r=dn(n)??[...n.nodes].sort(),i=t?.compactSingleInput??!1,a=gn(n),o=Object.create(null);for(let e of r){let r=rn(n,e),s=t?.ignoreCrossLaneEdges?r.filter(t=>{let n=a(t.src),r=a(e);return!n||!r||n===r}):r;if(s.length===0)o[e]=0;else if(i&&s.length===1){let t=s[0].src;a(t)===a(e)?o[e]=(o[t]??0)+1:o[e]=o[t]??0}else{let t=-1/0;for(let e of s)t=Math.max(t,(o[e.src]??0)+1);o[e]=t===-1/0?0:t}}return(t?.optimizeRanksByCrossings??!1)&&(o=Ln(n,o)),t?.ignoreCrossLaneEdges&&Rn(n,o),{layers:Pn(n,o,a),rankOf:o,dummy:new Set}}t(zn,`assignLayers_LongestPath`);function Bn(e,n){let r=nn(e),i={...zn(r,{compactSingleInput:n?.compactSingleInput,ignoreCrossLaneEdges:n?.ignoreCrossLaneEdges,optimizeRanksByCrossings:n?.optimizeRanksByCrossings}).rankOf},a=gn(r),{preds:o,succs:s}=ln(r,e=>{if(n?.ignoreCrossLaneEdges){let t=a(e.src),n=a(e.dst);if(t&&n&&t!==n)return!1}return!0}),c=dn(r)??[...r.nodes],l=[...c].reverse(),u=t((e,t)=>{let n=0;for(let t of o.get(e)??[])n=Math.max(n,(i[t]??0)+1);let r=1/0,a=s.get(e)??[];return a.length>0&&(r=Math.min(...a.map(e=>(i[e]??0)-1))),Number.isFinite(r)||(r=Math.max(n,t)),Math.min(Math.max(t,n),r)},`clampFeasible`),d=bn.GRAVITY_ITERATIONS,f=t(e=>{let t=!1;for(let n of e){let e=o.get(n)??[],r=s.get(n)??[];if(e.length===0&&r.length===0)continue;let a=e.length>0?e.reduce((e,t)=>e+(i[t]??0)+1,0)/e.length:i[n]??0,c=r.length>0?r.reduce((e,t)=>e+(i[t]??0)-1,0)/r.length:i[n]??0,l=Math.round((a+c)/2),d=u(n,l);d!==i[n]&&(i[n]=d,t=!0)}return t},`relaxOrder`);for(let e=0;e0){let n=Math.min(...t.map(e=>(i[e]??0)-1));(i[e]??0)>n&&(i[e]=n)}}return{layers:un(r,c,i),rankOf:i,dummy:new Set}}t(Bn,`assignLayers_Gravity`);function Vn(e){let t=sn(e),n=on(e),r=cn(t),i=[];for(;r.length>0;){let e=[];for(let a of r){i.push(a);for(let r of n.get(a)??[])t.set(r,(t.get(r)??0)-1),(t.get(r)??0)===0&&e.push(r)}r=e.sort((e,t)=>e.localeCompare(t))}return i.length===e.nodes.length?i:null}t(Vn,`topoSortByGenerationIfAcyclic`);function Hn(e,n){let r=nn(e),i=n?.direction===`LR`?Vn(r)??[...r.nodes].sort():dn(r)??[...r.nodes].sort(),a=gn(r),o=t(e=>a(e)??e,`laneOf`),s=Object.create(null),c=new Map,l=t((e,t)=>n?.ignoreCrossLaneEdges??!0?+(o(e)===o(t)):1,`edgeWeight`);for(let e of i){if(r.nodeById.get(e)?.isGroup)continue;let t=rn(r,e),n=0;if(t.length>0)for(let r of t){let t=r.src,i=s[t]??0;n=Math.max(n,i+l(t,e))}let i=o(e),a=c.get(i)??0,u=Math.max(n,a);s[e]=u,c.set(i,u+1)}return{layers:un(r,i,s,{skipGroups:!0}),rankOf:s,dummy:new Set}}t(Hn,`assignLayers_LaneAwareCompact`);function Un(e,n){let r=nn(n),{rankOf:i}=e,a=e.layers.map(e=>[...e]),o=new Set(e.dummy?[...e.dummy]:[]),s=0,c=new Map(r.nodeById),l=t(e=>{let t=`placeholder-${s++}`,n={id:t,isGroup:!1,isDummy:!0,width:0,height:0};for(c.set(t,n),o.add(t);a.length<=e;)a.push([]);return a[e].push(t),i[t]=e,t},`addDummyAt`),u=[...r.edges].sort((e,t)=>e.id===t.id?e.src===t.src?e.dst.localeCompare(t.dst):e.src.localeCompare(t.src):e.id.localeCompare(t.id)),d=[];for(let e of u){let t=i[e.src]??0,n=i[e.dst]??0;if(n-t<=1){d.push(e);continue}let r=e.src;for(let i=t+1,a=0;i!r.nodes.includes(e))],edges:d,layout:r.layout,nodeById:c};return{layering:{layers:a,rankOf:i,dummy:o},graphWithDummies:f}}t(Un,`makeProperLayering`);function Wn(e){let t=e.length;if(t===0)return 1/0;let n=[...e].sort((e,t)=>e-t);return t%2==1?n[(t-1)/2]:.5*(n[t/2-1]+n[t/2])}t(Wn,`median`);function Gn(e){return e.length===0?1/0:e.reduce((e,t)=>e+t,0)/e.length}t(Gn,`barycenter`);function Kn(e,t,n,r){let i=new Map;for(let t of e)i.set(t,[]);for(let e of n)r===`down`?t.has(e.src)&&i.has(e.dst)&&i.get(e.dst).push(t.get(e.src)):t.has(e.dst)&&i.has(e.src)&&i.get(e.src).push(t.get(e.dst));return i}t(Kn,`neighborPositionsFor`);function qn(e,t,n){let r=n.get(e)??0,i=n.get(t)??0;return r===i?e.localeCompare(t):r-i}t(qn,`currentOrderTieBreak`);function Jn(e,t,n){let r=new Set(e),i=new Set(t),a=fn(e),o=fn(t),s=[];for(let e of n)r.has(e.src)&&i.has(e.dst)&&s.push({u:a.get(e.src),v:o.get(e.dst)});return s.sort((e,t)=>e.u===t.u?e.v-t.v:e.u-t.u),pn(s.map(e=>e.v))}t(Jn,`countCrossingsBetweenAdjacent`);function Yn(e,t,n){return[...e].sort((e,r)=>{let i=Wn(t.get(e)??[]),a=Wn(t.get(r)??[]);return i===a?qn(e,r,n):isFinite(i)?isFinite(a)?i-a:-1:1})}t(Yn,`sortByHeuristic`);function Xn(e,t,n,r,i,a){let o=fn(e),s=fn(t),c=Kn(t,o,n,r);if(!i||!a||a.length===0)return Yn(t,c,s);let l=new Map;for(let e of t){let t=i(e),n=l.get(t)??[];n.push(e),l.set(t,n)}let u=[];for(let e of a){let t=l.get(e);if(!t||t.length===0)continue;let n=Yn(t,c,s);u.push(...n)}let d=l.get(null);if(d&&d.length>0){let e=Yn(d,c,s);for(let t of e){let e=Gn(c.get(t)??[]),n=u.length;if(isFinite(e)){for(let[t,r]of u.entries())if(es.has(e.src)&&c.has(e.dst)),d=l?r.filter(e=>c.has(e.src)&&l.has(e.dst)):void 0,f=t(t=>{let n=Jn(e,t,u);return d&&i&&(n+=Jn(t,i,d)),n},`crossingScore`),p=a?new Map:null;if(a&&p)for(let e of n)p.set(e,a(e));let m=!0,h=f(o);for(;m;){m=!1;for(let e=0;e+1[...e]),i=t.edges,a=gn(t),o=vn(t,n?.laneOrder);for(let e=0;e<3;e++){for(let e=1;e=0;e--)r[e]=Xn(r[e+1],r[e],i,`up`,a,o),r[e]=Zn(r[e+1],r[e],i,r[e-1],a)}return{layers:r}}t(Qn,`orderLayers`);function $n(e,n,r){let i=r?.layerGap??xn.DEFAULT_LAYER_GAP,a=r?.nodeGap??xn.DEFAULT_NODE_GAP,o=r?.laneGap??a*2,s=r?.direction??`TB`,c=s===`LR`||s===`RL`,l=e.layers,u=Object.create(null),d=Object.create(null),f=t(e=>n.nodeById.get(e),`getNode`),p=t(e=>f(e)?.width??0,`getWidth`),m=t(e=>f(e)?.height??0,`getHeight`),h=gn(n),g=vn(n,r?.laneOrder),_=l.map(e=>e.reduce((e,t)=>Math.max(e,m(t)),0)),v=[];if(c)for(let e=0;e+1Math.max(e,p(t)),0),n=l[e+1].reduce((e,t)=>Math.max(e,p(t)),0),r=_[e],a=_[e+1],o=r/2+a/2,s=(t+n)/2,c=Math.max(0,s-o-i);v.push(c)}let y=new Set;for(let e of l)for(let t of e)y.add(h(t));let b=y.has(null),x=g.filter(e=>y.has(e)),S=[...b?[null]:[],...x],C=Object.create(null);for(let e of x)C[e]=0;b&&(C.null=0);for(let e of l){let t=Object.create(null),n=[];for(let r of e){let e=h(r);e===null?n.push(r):(t[e]||=[]).push(r)}for(let[e,n]of Object.entries(t)){let t=n.reduce((e,t)=>e+p(t),0)+a*Math.max(0,n.length-1);C[e]=Math.max(C[e]??0,t)}if(b&&n.length){let e=n.reduce((e,t)=>e+p(t),0)+a*Math.max(0,n.length-1);C.null=Math.max(C.null??0,e)}}let w=new Map;{let e=S.map(e=>(e===null?C.null:C[e])??0),t=-(e.reduce((e,t)=>e+t,0)+o*Math.max(0,S.length-1))/2;for(let n=0;np(e)),r=i-(e.reduce((e,t)=>e+t,0)+a*(t.length-1))/2;for(let[i,o]of t.entries()){let t=e[i];u[o]=r+t/2,d[o]=T+n/2,r+=t+a}}}let o=v[e]??0;T+=n+i+o}let E=new Map;for(let e of n.edges){let t=e.ref.id;E.has(t)||E.set(t,[]),E.get(t).push(e)}for(let[,e]of E){if(e.length===0)continue;let t=e[0].ref,r=t.start,i=t.end;if(r==null||i==null)continue;let a=Math.round(((u[r]??0)+(u[i]??0))/2),o=new Set;for(let t of e)o.add(t.src),o.add(t.dst);for(let e of o)e===r||e===i||n.nodeById.get(e)?.isDummy&&(u[e]=a)}return{x:u,y:d}}t($n,`assignCoordinates`);var er=8;function tr(e){let t=2166136261;for(let n=0;n>>0}t(tr,`hashString`);function nr(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}t(nr,`mulberry32`);function rr(e,t){let n=[...e],r=nr(t);for(let e=n.length-1;e>0;e--){let t=Math.floor(r()*(e+1));[n[e],n[t]]=[n[t],n[e]]}return n}t(rr,`deterministicShuffle`);function ir(e,t){let n=0;for(let[r,i]of e.entries())n+=Math.abs(r-(t.get(i)??r));return n}t(ir,`sourceDistance`);function ar(e,t){let n=new Map;for(let[t,r]of e.entries())n.set(r,t);let r=0;for(let{a:e,b:i,weight:a}of t){let t=n.get(e),o=n.get(i);t==null||o==null||(r+=a*Math.abs(t-o))}return r}t(ar,`laneArrangementCost`);function or(e){let t=_n(e);if(t.length<2)return[];let n=new Map(t.map((e,t)=>[e,t])),r=gn(e),i=new Map;for(let t of e.layout.edges??[]){if(t.isLayoutOnly)continue;let a=typeof t.start==`string`?t.start:void 0,o=typeof t.end==`string`?t.end:void 0;if(!a||!o||!e.nodeById.has(a)||!e.nodeById.has(o))continue;let s=r(a),c=r(o);if(!s||!c||s===c)continue;let l=n.get(s),u=n.get(c);if(l==null||u==null)continue;let[d,f]=l<=u?[s,c]:[c,s],p=`${d}\0${f}`,m=i.get(p);m?m.weight++:i.set(p,{a:d,b:f,weight:1})}return[...i.values()]}t(or,`buildWeightedLaneEdges`);function sr(e,t,n){let r=[...e],i=ar(r,t),a=!0,o=0,s=Math.max(1,r.length);for(;a&&oe.a===t.a?e.b.localeCompare(t.b):e.a.localeCompare(t.a)).map(({a:e,b:t,weight:n})=>`${e}:${t}:${n}`).join(`|`);return tr(`${e.join(`|`)}#${r}#${n}`)}t(lr,`seedForRestart`);function ur(e,t={}){let n=_n(e);if(n.length<2)return n;let r=or(e);if(r.length===0)return n;let i=new Map(n.map((e,t)=>[e,t])),a=sr(n,r,i),o=Math.max(0,t.restarts??er);for(let e=0;e$&&c*3>=s?o>0?`bottom`:`top`:s>$?a>0?`right`:`left`:n}t(vr,`chooseOrthogonalSide`);function yr(e,t){return Math.abs(e.to-t.from)<$||Math.abs(e.to-t.to)<$?e.to:e.from}t(yr,`sharedLineEndpointCoord`);function br(e,t){return e.orient===`vertical`?{x:e.coord,y:t}:{x:t,y:e.coord}}t(br,`pointOnLine`);function xr(e,n){let r=e.nodes??[],i=e.edges??[],a=[];for(let e of i)e.isLayoutOnly||a.push({...e,__originalEdge:e});let o=new Map,s=new Map,c=[],l=n===`LR`;for(let e of r)o.set(e.id,e);let u=r.filter(e=>e.isGroup&&!e.parentId);for(let e of u){let n={id:e.id},i=t(e=>{s.set(e.id,n),r.filter(t=>t.parentId===e.id).forEach(i)},`assignLane`);i(e)}let d=r.filter(e=>!e.isGroup&&!e.isEdgeLabel).map(e=>{let t=e.width??10,n=e.height??10,r=e.x??0,i=e.y??0,a=fr;return{nodeId:e.id,minX:r-t/2-a,maxX:r+t/2+a,minY:i-n/2-a,maxY:i+n/2+a,visualXHalfExtent:l?n/2+a:t/2+a}}),f=t((e,t,n,r)=>{let i=c.find(n=>n.orientation===e&&Math.abs(n.coord-t)<1);return i||(i={id:`pipe-${e}-${t.toFixed(0)}`,orientation:e,coord:t,spanMin:n,spanMax:r,tracks:[]},c.push(i)),i.spanMin=Math.min(i.spanMin,n),i.spanMax=Math.max(i.spanMax,r),i},`getOrAddPipe`),p=t((e,t)=>{let n=e.width??10,r=e.height??10,i=e.x??0,a=e.y??0;switch(t){case`top`:return{x:i,y:a-r/2};case`bottom`:return{x:i,y:a+r/2};case`left`:return{x:i-n/2,y:a};case`right`:return{x:i+n/2,y:a}}},`portForSide`),m=t((e,t,n)=>p(e,vr(e,t,n?`bottom`:`top`)),`getOrthogonalPort`),h=[],g=[],_=new Set,v=1e3,y=t((e,t,n)=>{if(h.length===0)return 0;let r=Math.abs(t.y-n.y)<$,i=Math.abs(t.x-n.x)<$;if(!r&&!i)return 0;let a=0;if(r){let r=t.y,i=Math.min(t.x,n.x)-$,o=Math.max(t.x,n.x)+$;if(o<=i)return 0;for(let t of h)t.edgeIndex===e||t.orientation!==`vertical`||t.pipe.coordo||t.from-$<=r&&t.to+$>=r&&(a+=v)}else if(i){let r=t.x,i=Math.min(t.y,n.y)-$,o=Math.max(t.y,n.y)+$;if(o<=i)return 0;for(let t of h)t.edgeIndex===e||t.orientation!==`horizontal`||t.pipe.coordo||t.from-$<=r&&t.to+$>=r&&(a+=v)}return a},`crossingPenalty`),b=a.map((e,t)=>{if(!e.start||!e.end)return{idx:t,crossLane:0,dx:0,dy:0};let n=o.get(e.start),r=o.get(e.end),i=s.get(e.start),a=s.get(e.end);return{idx:t,crossLane:i&&a&&i.id!==a.id?1:0,dx:n&&r?Math.abs((r.x??0)-(n.x??0)):0,dy:n&&r?Math.abs((r.y??0)-(n.y??0)):0}}).sort((e,t)=>{if(e.crossLane!==t.crossLane)return t.crossLane-e.crossLane;let n=e.dx+e.dy,r=t.dx+t.dy;return Math.abs(n-r)>1?n-r:e.idx-t.idx}).map(e=>e.idx),x=t((e,t,n,r)=>{let i=Math.min(e.x,t.x),a=Math.max(e.x,t.x),o=Math.min(e.y,t.y),s=Math.max(e.y,t.y);return!!d.find(c=>n&&c.nodeId===n||r&&c.nodeId===r?!1:Math.abs(e.x-t.x)>$?c.minYe.y&&c.maxX>i&&c.minXe.x&&c.maxY>o&&c.minYvr(e,t,`bottom`),`determineSide`),T=new Map;for(let[e,t]of a.entries()){if(!t.start||!t.end||t.start===t.end||t.points&&t.points.length>0)continue;let n=o.get(t.start),r=o.get(t.end);if(!n||!r)continue;let i=(r.x??0)-(n.x??0),a=(r.y??0)-(n.y??0);T.set(e,{edgeIdx:e,srcId:t.start,dstId:t.end,srcSide:w(n,{x:r.x??0,y:r.y??0}),dstSide:w(r,{x:n.x??0,y:n.y??0}),absDx:Math.abs(i),absDy:Math.abs(a),dxSign:Math.sign(i),dySign:Math.sign(a)})}let E=t(e=>e.srcSide===`top`||e.srcSide===`bottom`?e.absDx===0?1/0:e.absDy/e.absDx:e.absDy===0?1/0:e.absDx/e.absDy,`preferenceStrength`),D=t(e=>e.srcSide===`top`||e.srcSide===`bottom`?e.dxSign>=0?`right`:`left`:e.dySign>=0?`bottom`:`top`,`secondarySide`),O=new Map;for(let e of T.values()){let t=`${e.srcId}:${e.srcSide}`;O.has(t)||O.set(t,[]),O.get(t).push(e)}let k=new Map,A=t((e,t)=>`${e}:${t}`,`loadKey`);for(let e of T.values())k.set(A(e.srcId,e.srcSide),(k.get(A(e.srcId,e.srcSide))??0)+1),k.set(A(e.dstId,e.dstSide),(k.get(A(e.dstId,e.dstSide))??0)+1);for(let e of O.values())if(!(e.length<2)){e.sort((e,t)=>{let n=E(e),r=E(t);return Math.abs(n-r)>1e-9?r-n:e.edgeIdx-t.edgeIdx});for(let t=1;t=i||(k.set(A(n.srcId,n.srcSide),i-1),k.set(A(n.srcId,r),a+1),n.srcSide=r)}}let j=t(e=>{let t=e?.shape;return t===`question`||t===`diamond`},`isDiamondNode`),ee=new Map;for(let e of T.values())ee.has(e.dstId)||ee.set(e.dstId,new Set),ee.get(e.dstId).add(e.dstSide);for(let e of T.values()){if(!j(o.get(e.srcId)))continue;let t=ee.get(e.srcId);if(!t?.has(e.srcSide))continue;let n=D(e);if(t.has(n)||(k.get(A(e.srcId,n))??0)>0)continue;let r=k.get(A(e.srcId,e.srcSide))??0;k.set(A(e.srcId,e.srcSide),Math.max(0,r-1)),k.set(A(e.srcId,n),1),e.srcSide=n}for(let e of T.values()){let{edgeIdx:t,srcId:n,dstId:r,srcSide:i,dstSide:a}=e,s=o.get(n),c=o.get(r),l=`${n}:${i}:src`,u=i===`top`||i===`bottom`?c.x??0:c.y??0;S.has(l)||S.set(l,[]),S.get(l).push({edgeIdx:t,oppositeCoord:u});let d=`${r}:${a}:dst`,f=a===`top`||a===`bottom`?s.x??0:s.y??0;S.has(d)||S.set(d,[]),S.get(d).push({edgeIdx:t,oppositeCoord:f})}let te=new Map;for(let[e,t]of S){if(t.length<2)continue;t.sort((e,t)=>e.oppositeCoord-t.oppositeCoord);let n=e.split(`:`),r=n.slice(0,-2).join(`:`),i=n[n.length-2],a=n[n.length-1],s=o.get(r);if(!s)continue;let c=i===`left`||i===`right`?s.height??10:s.width??10,l=s.shape,u=l===`question`||l===`diamond`?c*.3:c,d=Math.min(20,Math.max(8,u/(t.length+1))),f=-(d*(t.length-1))/2;for(let[e,n]of t.entries()){let t=f+e*d,r=`${n.edgeIdx}:${a}`;te.set(r,t)}}let M=t(e=>!!a[e]?.labelNodeId,`edgeHasLabelNode`),ne=t((e,t)=>e?(S.get(`${e}:${t}:src`)??[]).some(({edgeIdx:e})=>M(e))||(S.get(`${e}:${t}:dst`)??[]).some(({edgeIdx:e})=>M(e)):!1,`faceHasLabelNode`),N=t((e,t,n)=>t===`top`||t===`bottom`?{x:e.x+n,y:e.y}:{x:e.x,y:e.y+n},`applyPortOffset`),re=t((e,t,n)=>{let r=T.get(e),i={x:n.x??0,y:n.y??0},a={x:t.x??0,y:t.y??0},o=r?.srcSide??w(t,i),s=r?.dstSide??w(n,a),c=r?p(t,r.srcSide):m(t,i,!0),l=r?p(n,r.dstSide):m(n,a,!1),u=te.get(`${e}:src`),d=te.get(`${e}:dst`);return u!==void 0&&(c=N(c,o,u)),d!==void 0&&(l=N(l,s,d)),{pSrcPort:c,pDstPort:l,srcSide:o,dstSide:s}},`portsForEdge`);for(let e of b){let n=a[e];if(g[e]=[],!n.start||!n.end||n.points&&n.points.length>0||n.start===n.end)continue;let r=o.get(n.start),i=o.get(n.end);if(!r||!i)continue;let{pSrcPort:s,pDstPort:u,srcSide:p,dstSide:m}=re(e,r,i),v={...s},b={...u},w=p===`top`||p===`bottom`,T=m===`top`||m===`bottom`;w?v.y=s.y>(r.y??0)?s.y+gr:s.y-gr:v.x=s.x>(r.x??0)?s.x+gr:s.x-gr,T?b.y=u.y>(i.y??0)?u.y+gr:u.y-gr:b.x=u.x>(i.x??0)?u.x+gr:u.x-gr;let E=t((e,t)=>{for(let n of d)if(!t.includes(n.nodeId)&&e.x>n.minX&&e.xn.minY&&e.y{if(i){let i=e.y>(t.y??0);return{x:(n.x??0)>=e.x?r.maxX+pr:r.minX-pr,y:i?r.maxY+mr:r.minY-mr,leavesPositiveSide:i}}let a=e.x>(t.x??0),o=(n.y??0)>=e.y;return{x:a?r.maxX+pr:r.minX-pr,y:o?r.maxY+mr:r.minY-mr,leavesPositiveSide:a}},`obstacleDetour`),O=[],k=[n.start,n.end],A=E(v,k);if(A.inside&&A.obstacle){let e=A.obstacle;if(w){let t=D(s,r,i,e,!0);v.x=t.x,v.y=t.y;let n=t.leavesPositiveSide?Math.min(e.minY-2,s.y+gr):Math.max(e.maxY+2,s.y-gr);O=[{x:s.x,y:n},{x:t.x,y:n},{x:t.x,y:t.y}]}else{let t=D(s,r,i,e,!1),n=t.leavesPositiveSide?Math.min(e.minX-2,s.x+gr):Math.max(e.maxX+2,s.x-gr);v.x=t.x,v.y=t.y,O=[{x:n,y:s.y},{x:n,y:t.y},{x:t.x,y:t.y}]}}let j=[],ee=E(b,k);if(ee.inside&&ee.obstacle){let e=ee.obstacle;if(T){let t=D(u,i,r,e,!0);b.x=t.x,b.y=t.y,j=[{x:t.x,y:t.y},{x:u.x,y:t.y}]}else{let t=D(u,i,r,e,!1);b.x=t.x,b.y=t.y,j=[{x:t.x,y:t.y},{x:t.x,y:u.y}]}}if(O.length===0&&j.length===0){let t=pr,r=Math.abs(v.x-b.x)1||c>1,d=C.get(n.start??``)??0,f=C.get(n.end??``)??0,g=o>1&&ne(n.start,p)||c>1&&ne(n.end,m);if((r||i)&&!a&&(!l||l&&!g&&(o<=1||d<=2)&&(c<=1||f<=2))&&!x(s,u,n.start,n.end)){n.points=[{...s},{...v},{...b},{...u}],_.add(e);let t=i?`horizontal`:`vertical`,r=i?s.y:s.x,a=i?Math.min(s.x,u.x):Math.min(s.y,u.y),o=i?Math.max(s.x,u.x):Math.max(s.y,u.y),c={id:`fast-path-${t}-${r.toFixed(0)}-${e}`,orientation:t,coord:r,spanMin:a,spanMax:o,tracks:[]};h.push({edgeIndex:e,segmentIndex:0,orientation:t,pipe:c,trackIndex:0,from:a,to:o});continue}}v.x=f(`vertical`,v.x,v.y,v.y).coord,b.x=f(`vertical`,b.x,b.y,b.y).coord;let M=Math.min(v.x,b.x)-50,N=Math.max(v.x,b.x)+50,P=Math.min(v.y,b.y)-50,ie=Math.max(v.y,b.y)+50;for(let e of d){let t=Math.min(v.x,b.x),n=Math.max(v.x,b.x),r=Math.min(v.y,b.y),i=Math.max(v.y,b.y);e.minXt&&e.minYr&&(M=Math.min(M,e.minX-hr),N=Math.max(N,e.maxX+hr),P=Math.min(P,e.minY-hr),ie=Math.max(ie,e.maxY+hr))}for(let e of d){if(e.maxXN||e.maxYie)continue;let t=pr;f(`horizontal`,e.minY-t,M,N),f(`horizontal`,e.maxY+t,M,N);let n=mr;f(`vertical`,e.minX-n,P,ie),f(`vertical`,e.maxX+n,P,ie)}f(`horizontal`,v.y,M,N),f(`horizontal`,b.y,M,N);let ae=c.filter(e=>e.orientation===`horizontal`&&e.coord>=P&&e.coord<=ie),oe=c.filter(e=>e.orientation===`vertical`&&e.coord>=M&&e.coord<=N),se=t((e,t)=>`${e.toFixed(1)},${t.toFixed(1)}`,`getKey`),ce=se(v.x,v.y),le=se(b.x,b.y),ue=new Map,de=new Map,fe=new Map,pe=new Set,F=[];ue.set(ce,0),fe.set(ce,`n`),F.push({key:ce,f:Math.hypot(b.x-v.x,b.y-v.y),pt:v}),pe.add(ce);let I=[],me=t((e,t)=>x(e,t,n.start,n.end),`checkSegmentBlocked`),he={x:b.x,y:v.y},L=me(v,he),ge=me(he,b),_e=L||ge,R={x:v.x,y:b.y},z=me(v,R),B=me(R,b);if(_e?z||B||(I=Math.abs(v.x-b.x)<$?[v,b]:[v,R,b]):I=Math.abs(v.y-b.y)<$||Math.abs(v.x-b.x)<$?[v,b]:[v,he,b],I.length===0)for(;F.length>0;){F.sort((e,t)=>e.f-t.f);let t=F.shift();if(pe.delete(t.key),t.key===le){let e=le,t=b;for(I=[t];de.has(e);){let n=de.get(e);I.unshift(n),t=n,e=se(n.x,n.y)}break}let r=t.pt.x,i=t.pt.y,a=oe.sort((e,t)=>e.coord-t.coord),o=a.findIndex(e=>Math.abs(e.coord-r)<1),s=ae.sort((e,t)=>e.coord-t.coord),c=s.findIndex(e=>Math.abs(e.coord-i)<1),l=[];o>0&&l.push({x:a[o-1].coord,y:i}),o>=0&&o0&&l.push({x:r,y:s[c-1].coord}),c>=0&&ce.nodeId===n.start||e.nodeId===n.end?!1:o===s?e.minXr&&e.maxY>c&&e.minYi&&e.maxX>o&&e.minX10&&x<-5||g<-10&&x>5)&&(m=Math.abs(x)*100),(h>10&&_<-5||h<-10&&_>5)&&(m+=Math.abs(_)*50);let S=0,C=fe.get(t.key)??`n`,w=Math.abs(_)>$?`h`:`v`;C!==`n`&&C!==w&&(S=50);let T=f+p+m+S,E=(ue.get(t.key)??1/0)+T,D=Math.abs(b.x-a.x)+Math.abs(b.y-a.y);if(E<(ue.get(u)??1/0))if(de.set(u,t.pt),ue.set(u,E),fe.set(u,w),!pe.has(u))F.push({key:u,f:E+D,pt:a}),pe.add(u);else{let e=F.findIndex(e=>e.key===u);e!==-1&&(F[e].f=E+D)}}}if(I.length===0&&(I=[v,{x:v.x,y:b.y},b]),I.length>4){let e=I[0],n=I[I.length-1],r=Math.min(e.x,n.x),i=Math.max(e.x,n.x),a=Math.min(e.y,n.y),o=Math.max(e.y,n.y);for(let e of I)r=Math.min(r,e.x),i=Math.max(i,e.x),a=Math.min(a,e.y),o=Math.max(o,e.y);let s=i>Math.max(e.x,n.x),c=re.minXr&&e.minYa);if(s.length>0){let r=Math.max(e.x,n.x);for(let e of s){let n=(e.minX+e.maxX)/2;if(e.visualXHalfExtent===void 0||isNaN(e.visualXHalfExtent))continue;let i=n+e.visualXHalfExtent+t;r=Math.max(r,i)}isNaN(r)||(i=r)}}if(c){let i=d.filter(r=>r.minXMath.min(e.y,n.y));if(i.length>0){let a=Math.min(e.x,n.x);for(let e of i){let n=(e.minX+e.maxX)/2-e.visualXHalfExtent-t;a=Math.min(a,n)}r=a}}}let u=t(t=>{let r=n.y>e.y,i=d.filter(t=>{let r=Math.min(e.x,n.x)t.minX,i=Math.min(e.y,n.y)t.minY;return r&&i}),a=i;if(l&&i.length>0){let e=i.filter(e=>e.minXt);e.length>0&&(a=e)}if(a.length===0)return n.y;let o=pr;if(r){let e=Math.max(...a.map(e=>e.maxY))+o;if(ee.minY))-o;if(e>n.y+$)return e}return n.y},`findBestReturnY`),f=t(t=>{let r=u(t),i={x:t,y:e.y},a={x:t,y:r},o={x:n.x,y:r},s=me(e,i),c=me(i,a),l=me(a,o),d=r!==n.y&&me(o,n);return!s&&!c&&!l&&!d?Math.abs(r-n.y)<$?[e,i,a,n]:[e,i,a,o,n]:null},`trySimplifyWithDetourX`),p=s&&!c?f(i):c&&!s?f(r):null;p&&(I=p)}let V=[s,...O,...I,...j.reverse(),u];if(V.length>=3){let e=V[V.length-1],t=V[V.length-2],n=V[V.length-3],r=Math.abs(n.y-t.y)<$&&Math.abs(t.y-e.y)<$,i=Math.abs(n.x-t.x)<$&&Math.abs(t.x-e.x)<$;if(r){let r=Math.sign(t.x-n.x),i=Math.sign(e.x-n.x);r!==0&&r===i&&Math.abs(t.x-n.x)>Math.abs(e.x-n.x)&&V.splice(-2,1)}else if(i){let r=Math.sign(t.y-n.y),i=Math.sign(e.y-n.y);r!==0&&r===i&&Math.abs(t.y-n.y)>Math.abs(e.y-n.y)&&V.splice(-2,1)}}let H=[V[0]];for(let e=1;et.x!=r.x>n.x){H.push(n);continue}continue}if(Math.abs(t.x-n.x)<$&&Math.abs(n.x-r.x)<$){if(n.y>t.y!=r.y>n.y){H.push(n);continue}continue}H.push(n)}H.push(V[V.length-1]);for(let t=0;te.from{let i=!r.segments.some(n=>(n.edgeIndex!==t.edgeIndex||n.segmentIndex!==t.segmentIndex)&&P(n,e)),a=!n.segments.some(n=>(n.edgeIndex!==e.edgeIndex||n.segmentIndex!==e.segmentIndex)&&P(n,t));return i&&a?(e.trackIndex=r.index,t.trackIndex=n.index,n.segments=[...n.segments.filter(t=>t.edgeIndex!==e.edgeIndex||t.segmentIndex!==e.segmentIndex),{edgeIndex:t.edgeIndex,segmentIndex:t.segmentIndex,from:t.from,to:t.to}],r.segments=[...r.segments.filter(e=>e.edgeIndex!==t.edgeIndex||e.segmentIndex!==t.segmentIndex),{edgeIndex:e.edgeIndex,segmentIndex:e.segmentIndex,from:e.from,to:e.to}],!0):!1},`trySwapSegmentsAcrossTracks`),ae=t(e=>{let t=e.tracks.length;return e.tracks[t]={index:t,coord:e.coord,segments:[]},t},`createNewTrack`),oe=t((e,t)=>{let n=e.pipe.tracks[e.trackIndex];n.segments=n.segments.filter(t=>t.edgeIndex!==e.edgeIndex||t.segmentIndex!==e.segmentIndex),e.trackIndex=t,e.pipe.tracks[t].segments.push({edgeIndex:e.edgeIndex,segmentIndex:e.segmentIndex,from:e.from,to:e.to})},`moveSegmentToTrack`),se=t((e,t)=>{let n=g[e.edgeIndex];for(let r of n){let n=h[r];n.pipe===e.pipe&&oe(n,t)}},`moveSegmentChainToTrack`),ce=t(e=>{let t=g[e.edgeIndex],n=t.indexOf(h.indexOf(e)),r=[];return n>0&&r.push(h[t[n-1]]),n{if(e.orientation===t.orientation)return!1;let n=e.orientation===`horizontal`?e:t,r=e.orientation===`horizontal`?t:e;return r.pipe.coord>n.from&&r.pipe.coordr.from&&n.pipe.coord{for(let n of e.tracks)if(!n.segments.some(e=>(e.edgeIndex!==t.edgeIndex||e.segmentIndex!==t.segmentIndex)&&P(e,t)))return n.index;return-1},`findAvailableTrack`),de=t((e,t)=>{if(e.trackIndex===t.trackIndex)return P(e,t);let n=ce(e),r=ce(t);return n.some(e=>r.some(t=>le(e,t)))},`segmentsConflict`),fe=t((e,t,n)=>{if(ie(e,t,e.pipe.tracks[e.trackIndex],t.pipe.tracks[t.trackIndex]))return;let r=ue(e.pipe,t);n(t,r===-1?ae(e.pipe):r)},`resolveTrackConflict`),pe=t(e=>{let t=0;for(let n=0;n{if(F.has(e))return F.get(e);let t=g[e];if(t.length===0){let t={dest:0,deviation:0,base:0,delta:0};return F.set(e,t),t}let n=h[t[0]].pipe.coord,r=n;for(let e=1;eMath.abs(t-n)?e:t;break}}let i=Math.abs(r-n),a={dest:r,deviation:i,base:n,delta:r-n};return F.set(e,a),a},`getDestInfo`),me=t(()=>{let e=0,n=new Map;for(let[e,t]of a.entries())g[e].length!==0&&t.start&&(n.has(t.start)||n.set(t.start,[]),n.get(t.start).push(e));let r=t(e=>{let t=a[e];if(!t.start||!t.end)return 0;let n=o.get(t.start),r=o.get(t.end);if(!n||!r)return 0;let i=(r.x??0)-(n.x??0),s=(r.y??0)-(n.y??0);return Math.abs(i)+Math.abs(s)},`getEdgeDistance`);for(let t of n.values()){t.sort((e,t)=>{let n=I(e),i=I(t);if(Math.abs(n.deviation-i.deviation)>1)return n.deviation-i.deviation;if(Math.abs(n.dest-i.dest)>1)return n.dest-i.dest;let a=r(e),o=r(t);if(Math.abs(a-o)>1)return o-a;let s=g[e].length,c=g[t].length;if(s!==c)return s-c;if(s===1){let n=g[e][0],r=g[t][0];if(h[n]&&h[r]){let e=h[n],t=h[r],i=Math.abs(e.to-e.from),a=Math.abs(t.to-t.from);if(Math.abs(i-a)>1)return i-a}}return 0});let n=t.map(e=>h[g[e][0]]);e+=pe(n)}return e},`fixSourceHandleCrossings`),he=t(()=>{let e=0,n=new Map;for(let[e,t]of a.entries())g[e].length!==0&&t.end&&(n.has(t.end)||n.set(t.end,[]),n.get(t.end).push(e));for(let r of n.values()){r.sort((e,n)=>{let r=t(e=>{let t=g[e];if(t.length<2)return 0;let n=h[t[t.length-2]];return Math.abs(n.to-n.from)},`getDist`),i=r(e),a=r(n);return Math.abs(i-a)>.1?i-a:e-n});let n=r.map(e=>h[g[e][g[e].length-1]]);e+=pe(n)}return e},`fixTargetHandleCrossings`),L=t(()=>{let e=0;for(let t of c){let n=[];for(let e of t.tracks)for(let t of e.segments){let e=g[t.edgeIndex].find(e=>h[e].segmentIndex===t.segmentIndex);e!==void 0&&n.push(h[e])}n.sort((e,t)=>e.edgeIndex-t.edgeIndex||e.segmentIndex-t.segmentIndex);for(let t=0;t{e.segments.forEach(t=>{n.push({edgeIndex:t.edgeIndex,segmentIndex:t.segmentIndex,trackIndex:e.index,from:t.from,to:t.to})})}),n.sort((e,t)=>e.from-t.from);let r=[];if(n.length>0){let e=[n[0]],t=n[0].to;for(let i=1;ir.add(e.trackIndex));let i=new Map;n.forEach(e=>{let t=I(e.edgeIndex);i.set(e.trackIndex,(i.get(e.trackIndex)??0)+t.delta)});let a=[...r].filter(e=>(i.get(e)??0)<-1),o=[...r].filter(e=>(i.get(e)??0)>1),s=[...r].filter(e=>Math.abs(i.get(e)??0)<=1);a.sort((e,t)=>(i.get(t)??0)-(i.get(e)??0)),o.sort((e,t)=>(i.get(e)??0)-(i.get(t)??0));let c=t((t,r)=>{n.filter(e=>e.trackIndex===t).forEach(t=>{let n=_.has(t.edgeIndex)?e.coord:r;_e.set(`${t.edgeIndex}-${t.segmentIndex}`,n)})},`assignCoord`),l=0;for(let t of a)l++,c(t,e.coord-l*_r);if(s.length===0&&r.size>0){let e=[...r].sort((e,t)=>Math.abs(i.get(e)??0)-Math.abs(i.get(t)??0))[0],t=a.indexOf(e);t!==-1&&a.splice(t,1);let n=o.indexOf(e);n!==-1&&o.splice(n,1),s.push(e)}let u=0;for(let t of s){if(u===0)c(t,e.coord);else{let n=u%2==1?1:-1,r=Math.ceil(u/2);c(t,e.coord+n*r*_r*.5)}u++}let d=0;for(let t of o)d++,c(t,e.coord+d*_r)}}for(let[e,t]of a.entries()){let n=g[e]??[];if(n.length===0)continue;let r=[],{pSrcPort:i,pDstPort:a}=re(e,o.get(t.start),o.get(t.end)),s=n.map(e=>{let t=h[e],n=_e.get(`${t.edgeIndex}-${t.segmentIndex}`)??t.pipe.coord;return{orient:t.orientation,coord:n,from:t.from,to:t.to}});r.push(i);for(let e=0;e$&&r.push(br(t,i)),c&&o.orient===t.orient)if(Math.abs(t.coord-o.coord)>$){let e=t.orient===`vertical`?(i+o.from)/2:yr(t,o);r.push(br(t,e),br(o,e))}else(e===0||e===s.length-2)&&r.push(br(t,yr(t,o)));else if(c)r.push(br(t,o.coord));else{let e=Math.abs(t.from-i)$||Math.abs(c.y-a.y)>$)&&r.push(a);let l=[];r.length>0&&l.push(r[0]);for(let e=1;e$||Math.abs(t.y-n.y)>$)&&l.push(t)}t.points=l}for(let e of a){let t=e.__originalEdge;t&&e.points&&(t.points=e.points)}e.edges=(e.edges??[]).filter(e=>!e.isLayoutOnly);let R=t((e,t)=>{let n=t.x??0,r=t.y??0,i=t.width??0,a=t.height??0;if(i<=0||a<=0)return e;let o=n-i/2,s=n+i/2,c=r-a/2,l=r+a/2;if(e.xs||e.yl)return e;let u=e.x-o,d=s-e.x,f=e.y-c,p=l-e.y,m=Math.min(u,d,f,p);return m===u?{x:o,y:e.y}:m===d?{x:s,y:e.y}:m===f?{x:e.x,y:c}:{x:e.x,y:l}},`nodeBoundaryClamp`);for(let t of e.edges){let e=t.points;if(!e||e.length<2)continue;let n=t.start,r=t.end,i=n?o.get(n):void 0,a=r?o.get(r):void 0;i&&(e[0]=R(e[0],i)),a&&(e[e.length-1]=R(e[e.length-1],a))}return e}t(xr,`routeEdgesOrthogonal`);function Sr(e){return e.direction??`TB`}t(Sr,`getSwimlaneDirection`);function Cr(e){let t=F(e),n=e.config.flowchart?.nodeSpacing??40,r=e.config.flowchart?.rankSpacing??100,i=e.config.swimlane?.ignoreCrossLaneEdges??!0,a=e.config.swimlane?.optimizeRanksByCrossings??!0,o=e.config.swimlane?.automaticLaneOrdering??!1,s=Sr(e),{ordered:c,coordinates:l}=dr(t,{nodeGap:n,layerGap:r,ignoreCrossLaneEdges:i,optimizeRanksByCrossings:a,automaticLaneOrdering:o,direction:s});I(t,c,l,{nodeGap:n,layerGap:r});for(let t of e.edges??[])delete t.points;xr(e,s);for(let t of e.edges??[])(!t.curve||t.curve===`basis`)&&(t.curve=`rounded`);return tn(e,s),en(e),s}t(Cr,`runSwimlaneLayoutCore`);async function wr(e,t){let n=t.select(`g`);h(n,e.markers,e.type,e.diagramId),p(),b(),m(),l(),pe(e);let r=he(e);e.nodes=r.nodes,e.edges=r.edges;let{groups:i}=await x(n,e);Cr(e),await oe(e,i)}t(wr,`render`);export{wr as render}; \ No newline at end of file diff --git a/dist-desktop/assets/swimlanesDiagram-G3AALYLV-CGWZF_2o.js b/dist-desktop/assets/swimlanesDiagram-G3AALYLV-CGWZF_2o.js new file mode 100644 index 0000000..6e69ac7 --- /dev/null +++ b/dist-desktop/assets/swimlanesDiagram-G3AALYLV-CGWZF_2o.js @@ -0,0 +1,8 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import"./src-UMNXGZaF.js";import"./chunk-WYO6CB5R-Dv5kDyQC.js";import"./chunk-ICXQ74PX-Czpgj8Uw.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import"./chunk-7BUUIJ7U-Bb538aSH.js";import"./chunk-OGEWGWER-D-nWYRNR.js";import"./chunk-32BRIVSS-DWU3ezKg.js";import"./chunk-XXDRQBXY-Bq6zMMOx.js";import"./chunk-VR4S4FIN-BTo4eV3J.js";import"./chunk-C7G6YPKG-DW-1jWUA.js";import"./chunk-ZGVPDNZ5-DGInJAPD.js";import"./chunk-52WLFC77-BOCvVCX1.js";import"./chunk-FWX5IMBZ-ComLEIwh.js";import"./chunk-ZIRB5QZD-C6fEPe3t.js";import{r as t,t as n}from"./chunk-PUDLZKDR-hlw4TonS.js";var r=n({defaultLayout:`swimlane`,styles:e(e=>`${t(e)} + .swimlane.cluster rect { + stroke: ${e.clusterBorder} !important; + } + [data-look="neo"].cluster rect { + filter: none; + } +`,`getStyles`)});export{r as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/timeline-definition-FHXFAJF6-DFMIv6oI.js b/dist-desktop/assets/timeline-definition-FHXFAJF6-DFMIv6oI.js new file mode 100644 index 0000000..45f929e --- /dev/null +++ b/dist-desktop/assets/timeline-definition-FHXFAJF6-DFMIv6oI.js @@ -0,0 +1,120 @@ +import{n as e,t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n,p as r}from"./src-UMNXGZaF.js";import{J as i,a,b as o,et as s,o as c,rt as l,tt as u,x as d}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as f}from"./arc-DqK6O3qL.js";import{p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-VAUOI2AC-AC9pRUsa.js";var h=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[6,11,13,14,15,17,19,20,23,24],r=[1,12],i=[1,13],a=[1,14],o=[1,15],s=[1,16],c=[1,19],l=[1,20],u={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,timeline_header:4,document:5,EOF:6,timeline:7,timeline_lr:8,timeline_td:9,line:10,SPACE:11,statement:12,NEWLINE:13,title:14,acc_title:15,acc_title_value:16,acc_descr:17,acc_descr_value:18,acc_descr_multiline_value:19,section:20,period_statement:21,event_statement:22,period:23,event:24,$accept:0,$end:1},terminals_:{2:`error`,6:`EOF`,7:`timeline`,8:`timeline_lr`,9:`timeline_td`,11:`SPACE`,13:`NEWLINE`,14:`title`,15:`acc_title`,16:`acc_title_value`,17:`acc_descr`,18:`acc_descr_value`,19:`acc_descr_multiline_value`,20:`section`,23:`period`,24:`event`},productions_:[0,[3,3],[4,1],[4,1],[4,1],[5,0],[5,2],[10,2],[10,1],[10,1],[10,1],[12,1],[12,2],[12,2],[12,1],[12,1],[12,1],[12,1],[21,1],[22,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 3:r.setDirection(`LR`);break;case 4:r.setDirection(`TD`);break;case 5:this.$=[];break;case 6:a[s-1].push(a[s]),this.$=a[s-1];break;case 7:case 8:this.$=a[s];break;case 9:case 10:this.$=[];break;case 11:r.getCommonDb().setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 12:this.$=a[s].trim(),r.getCommonDb().setAccTitle(this.$);break;case 13:case 14:this.$=a[s].trim(),r.getCommonDb().setAccDescription(this.$);break;case 15:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 18:r.addTask(a[s],0,``),this.$=a[s];break;case 19:r.addEvent(a[s].substr(2)),this.$=a[s];break}},`anonymous`),table:[{3:1,4:2,7:[1,3],8:[1,4],9:[1,5]},{1:[3]},t(n,[2,5],{5:6}),t(n,[2,2]),t(n,[2,3]),t(n,[2,4]),{6:[1,7],10:8,11:[1,9],12:10,13:[1,11],14:r,15:i,17:a,19:o,20:s,21:17,22:18,23:c,24:l},t(n,[2,10],{1:[2,1]}),t(n,[2,6]),{12:21,14:r,15:i,17:a,19:o,20:s,21:17,22:18,23:c,24:l},t(n,[2,8]),t(n,[2,9]),t(n,[2,11]),{16:[1,22]},{18:[1,23]},t(n,[2,14]),t(n,[2,15]),t(n,[2,16]),t(n,[2,17]),t(n,[2,18]),t(n,[2,19]),t(n,[2,7]),t(n,[2,12]),t(n,[2,13])],defaultActions:{},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};u.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:break;case 1:break;case 2:return 13;case 3:break;case 4:break;case 5:return 8;case 6:return 9;case 7:return 7;case 8:return 14;case 9:return this.begin(`acc_title`),15;case 10:return this.popState(),`acc_title_value`;case 11:return this.begin(`acc_descr`),17;case 12:return this.popState(),`acc_descr_value`;case 13:this.begin(`acc_descr_multiline`);break;case 14:this.popState();break;case 15:return`acc_descr_multiline_value`;case 16:return 20;case 17:return 24;case 18:return 23;case 19:return 6;case 20:return`INVALID`}},`anonymous`),rules:[/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:timeline[ \t]+LR\b)/i,/^(?:timeline[ \t]+TD\b)/i,/^(?:timeline\b)/i,/^(?:title\s[^\n]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:section\s[^:\n]+)/i,/^(?::\s(?:[^:\n]|:(?!\s))+)/i,/^(?:[^#:\n]+)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[14,15],inclusive:!1},acc_descr:{rules:[12],inclusive:!1},acc_title:{rules:[10],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,11,13,16,17,18,19,20],inclusive:!0}}}})();function d(){this.yy={}}return e(d,`Parser`),d.prototype=u,u.Parser=d,new d})();h.parser=h;var g=h,_={};t(_,{addEvent:()=>M,addSection:()=>O,addTask:()=>j,addTaskOrg:()=>N,clear:()=>T,default:()=>ee,getCommonDb:()=>w,getDirection:()=>D,getSections:()=>k,getTasks:()=>A,setDirection:()=>E});var v=``,y=0,b=`LR`,x=[],S=[],C=[],w=e(()=>c,`getCommonDb`),T=e(function(){x.length=0,S.length=0,v=``,C.length=0,b=`LR`,a()},`clear`),E=e(function(e){b=e},`setDirection`),D=e(function(){return b},`getDirection`),O=e(function(e){v=e,x.push(e)},`addSection`),k=e(function(){return x},`getSections`),A=e(function(){let e=P(),t=0;for(;!e&&t<100;)e=P(),t++;return S.push(...C),S},`getTasks`),j=e(function(e,t,n){let r={id:y++,section:v,type:v,task:e,score:t||0,events:n?[n]:[]};C.push(r)},`addTask`),M=e(function(e){C.find(e=>e.id===y-1).events.push(e)},`addEvent`),N=e(function(e){let t={section:v,type:v,description:e,task:e,classes:[]};S.push(t)},`addTaskOrg`),P=e(function(){let t=e(function(e){return C[e].processed},`compileTask`),n=!0;for(let[e,r]of C.entries())t(e),n&&=r.processed;return n},`compileTasks`),ee={clear:T,getCommonDb:w,getDirection:D,setDirection:E,addSection:O,getSections:k,getTasks:A,addTask:j,addTaskOrg:N,addEvent:M},F=0,I=e(function(e,t){let n=e.append(`rect`);return n.attr(`x`,t.x),n.attr(`y`,t.y),n.attr(`fill`,t.fill),n.attr(`stroke`,t.stroke),n.attr(`width`,t.width),n.attr(`height`,t.height),n.attr(`rx`,t.rx),n.attr(`ry`,t.ry),t.class!==void 0&&n.attr(`class`,t.class),n},`drawRect`),te=e(function(t,n){let r=t.append(`circle`).attr(`cx`,n.cx).attr(`cy`,n.cy).attr(`class`,`face`).attr(`r`,15).attr(`stroke-width`,2).attr(`overflow`,`visible`),i=t.append(`g`);i.append(`circle`).attr(`cx`,n.cx-15/3).attr(`cy`,n.cy-15/3).attr(`r`,1.5).attr(`stroke-width`,2).attr(`fill`,`#666`).attr(`stroke`,`#666`),i.append(`circle`).attr(`cx`,n.cx+15/3).attr(`cy`,n.cy-15/3).attr(`r`,1.5).attr(`stroke-width`,2).attr(`fill`,`#666`).attr(`stroke`,`#666`);function a(e){let t=f().startAngle(Math.PI/2).endAngle(Math.PI/2*3).innerRadius(15/2).outerRadius(15/2.2);e.append(`path`).attr(`class`,`mouth`).attr(`d`,t).attr(`transform`,`translate(`+n.cx+`,`+(n.cy+2)+`)`)}e(a,`smile`);function o(e){let t=f().startAngle(3*Math.PI/2).endAngle(Math.PI/2*5).innerRadius(15/2).outerRadius(15/2.2);e.append(`path`).attr(`class`,`mouth`).attr(`d`,t).attr(`transform`,`translate(`+n.cx+`,`+(n.cy+7)+`)`)}e(o,`sad`);function s(e){e.append(`line`).attr(`class`,`mouth`).attr(`stroke`,2).attr(`x1`,n.cx-5).attr(`y1`,n.cy+7).attr(`x2`,n.cx+5).attr(`y2`,n.cy+7).attr(`class`,`mouth`).attr(`stroke-width`,`1px`).attr(`stroke`,`#666`)}return e(s,`ambivalent`),n.score>3?a(i):n.score<3?o(i):s(i),r},`drawFace`),ne=e(function(e,t){let n=e.append(`circle`);return n.attr(`cx`,t.cx),n.attr(`cy`,t.cy),n.attr(`class`,`actor-`+t.pos),n.attr(`fill`,t.fill),n.attr(`stroke`,t.stroke),n.attr(`r`,t.r),n.class!==void 0&&n.attr(`class`,n.class),t.title!==void 0&&n.append(`title`).text(t.title),n},`drawCircle`),L=e(function(e,t){let n=t.text.replace(//gi,` `),r=e.append(`text`);r.attr(`x`,t.x),r.attr(`y`,t.y),r.attr(`class`,`legend`),r.style(`text-anchor`,t.anchor),t.class!==void 0&&r.attr(`class`,t.class);let i=r.append(`tspan`);return i.attr(`x`,t.x+t.textMargin*2),i.text(n),r},`drawText`),re=e(function(t,n){function r(e,t,n,r,i){return e+`,`+t+` `+(e+n)+`,`+t+` `+(e+n)+`,`+(t+r-i)+` `+(e+n-i*1.2)+`,`+(t+r)+` `+e+`,`+(t+r)}e(r,`genPoints`);let i=t.append(`polygon`);i.attr(`points`,r(n.x,n.y,50,20,7)),i.attr(`class`,`labelBox`),n.y+=n.labelMargin,n.x+=.5*n.labelMargin,L(t,n)},`drawLabel`),R=e(function(e,t,n){let r=e.append(`g`),i=B();i.x=t.x,i.y=t.y,i.fill=t.fill,i.width=n.width,i.height=n.height,i.class=`journey-section section-type-`+t.num,i.rx=3,i.ry=3,I(r,i),V(n)(t.text,r,i.x,i.y,i.width,i.height,{class:`journey-section section-type-`+t.num},n,t.colour)},`drawSection`),z=-1,ie=e(function(e,t,n,r){let i=t.x+n.width/2,a=e.append(`g`);z++,a.append(`line`).attr(`id`,r+`-task`+z).attr(`x1`,i).attr(`y1`,t.y).attr(`x2`,i).attr(`y2`,450).attr(`class`,`task-line`).attr(`stroke-width`,`1px`).attr(`stroke-dasharray`,`4 2`).attr(`stroke`,`#666`),te(a,{cx:i,cy:300+(5-t.score)*30,score:t.score});let o=B();o.x=t.x,o.y=t.y,o.fill=t.fill,o.width=n.width,o.height=n.height,o.class=`task task-type-`+t.num,o.rx=3,o.ry=3,I(a,o),V(n)(t.task,a,o.x,o.y,o.width,o.height,{class:`task`},n,t.colour)},`drawTask`),ae=e(function(e,t){I(e,{x:t.startx,y:t.starty,width:t.stopx-t.startx,height:t.stopy-t.starty,fill:t.fill,class:`rect`}).lower()},`drawBackgroundRect`),oe=e(function(){return{x:0,y:0,fill:void 0,"text-anchor":`start`,width:100,height:100,textMargin:0,rx:0,ry:0}},`getTextObj`),B=e(function(){return{x:0,y:0,width:100,anchor:`start`,height:100,rx:0,ry:0}},`getNoteRect`),V=(function(){function t(e,t,n,r,a,o,s,c){i(t.append(`text`).attr(`x`,n+a/2).attr(`y`,r+o/2+5).style(`font-color`,c).style(`text-anchor`,`middle`).text(e),s)}e(t,`byText`);function n(e,t,n,r,a,o,s,c,l){let{taskFontSize:u,taskFontFamily:d}=c,f=e.split(//gi);for(let e=0;e)/).reverse(),i,a=[],o=1.1,s=e.attr(`y`),c=parseFloat(e.attr(`dy`)),l=e.text(null).append(`tspan`).attr(`x`,0).attr(`y`,s).attr(`dy`,c+`em`);for(let r=0;rt||i===`
    `)&&(a.pop(),l.text(a.join(` `).trim()),a=i===`
    `?[``]:[i],l=e.append(`tspan`).attr(`x`,0).attr(`y`,s).attr(`dy`,o+`em`).text(i))})}e(H,`wrap`);var ce=e(function(e,t,n,i,a,o=!1){let{theme:s,look:c}=i,l=s?.includes(`redux`),u=n%(i?.themeVariables?.THEME_COLOR_LIMIT??12)-1,d=e.append(`g`);t.section=u,d.attr(`class`,(t.class?t.class+` `:``)+`timeline-node `+(`section-`+u));let f=d.append(`g`),p=d.append(`g`),m=p.append(`text`).text(t.descr).attr(`dy`,`1em`).attr(`alignment-baseline`,`middle`).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`).call(H,t.width).node().getBBox(),h=i.fontSize?.replace?i.fontSize.replace(`px`,``):i.fontSize;if(t.height=m.height+h*1.1*.5+t.padding,t.height=Math.max(t.height,t.maxHeight),t.width+=2*t.padding,p.attr(`transform`,`translate(`+t.width/2+`, `+t.padding/2+`)`),l&&p.attr(`transform`,`translate(${t.width/2}, ${o?t.padding/2+3:t.padding})`),ue(f,t,u,a,i),c===`neo`&&(d.attr(`data-look`,`neo`),l)){let t=s.includes(`dark`),n=r(e.node()?.ownerSVGElement??e.node()),i=n.attr(`id`)??``,a=i?`${i}-drop-shadow`:`drop-shadow`;if(n.select(`#${a}`).empty()){let e=n.select(`defs`);(e.empty()?n.append(`defs`):e).append(`filter`).attr(`id`,a).attr(`height`,`130%`).attr(`width`,`130%`).append(`feDropShadow`).attr(`dx`,`4`).attr(`dy`,`4`).attr(`stdDeviation`,0).attr(`flood-opacity`,t?`0.2`:`0.06`).attr(`flood-color`,t?`#FFFFFF`:`#000000`)}}return t},`drawNode`),le=e(function(e,t,n){let r=e.append(`g`),i=r.append(`text`).text(t.descr).attr(`dy`,`1em`).attr(`alignment-baseline`,`middle`).attr(`dominant-baseline`,`middle`).attr(`text-anchor`,`middle`).call(H,t.width).node().getBBox(),a=n.fontSize?.replace?n.fontSize.replace(`px`,``):n.fontSize;return r.remove(),i.height+a*1.1*.5+t.padding},`getVirtualNodeHeight`),ue=e(function(e,t,n,r,i){let{theme:a}=i,o=a?.includes(`redux`)?0:5,s=o>0?`M0 ${t.height-5} v${-t.height+10} q0,-${o},${o},-${o} h${t.width-10} q${o},0,${o},${o} v${t.height-5} H0 Z`:`M0 ${t.height-5} v${-(t.height-5)} h${t.width} v${t.height} H0 Z`;e.append(`path`).attr(`id`,r+`-node-`+F++).attr(`class`,`node-bkg node-`+t.type).attr(`d`,s),a?.includes(`redux`)||e.append(`line`).attr(`class`,`node-line-`+n).attr(`x1`,0).attr(`y1`,t.height).attr(`x2`,t.width).attr(`y2`,t.height)},`defaultBkg`),U={drawRect:I,drawCircle:ne,drawSection:R,drawText:L,drawLabel:re,drawTask:ie,drawBackgroundRect:ae,getTextObj:oe,getNoteRect:B,initGraphics:se,drawNode:ce,getVirtualNodeHeight:le},de=e(function(e,t,a,o){let s=d(),{look:c,theme:l,themeVariables:u}=s,{useGradient:f,gradientStart:p,gradientStop:m}=u,h=s.timeline?.leftMargin??50;n.debug(`timeline`,o.db);let g=s.securityLevel,_;g===`sandbox`&&(_=r(`#i`+t));let v=r(g===`sandbox`?_.nodes()[0].contentDocument.body:`body`).select(`#`+t);v.append(`g`);let y=o.db.getTasks(),b=o.db.getCommonDb().getDiagramTitle();n.debug(`task`,y),U.initGraphics(v,t);let x=o.db.getSections();n.debug(`sections`,x);let S=0,C=0,w=0,T=0,E=50+h,D=50;T=50;let O=0,k=!0;x.forEach(function(e){let t={number:O,descr:e,section:O,width:150,padding:20,maxHeight:S},r=U.getVirtualNodeHeight(v,t,s);n.debug(`sectionHeight before draw`,r),S=Math.max(S,r+20)});let A=0,j=0;n.debug(`tasks.length`,y.length);for(let[e,t]of y.entries()){let r={number:e,descr:t,section:t.section,width:150,padding:20,maxHeight:C},i=U.getVirtualNodeHeight(v,r,s);n.debug(`taskHeight before draw`,i),C=Math.max(C,i+20),A=Math.max(A,t.events.length);let a=0;for(let e of t.events){let n={descr:e,section:t.section,number:t.section,width:150,padding:20,maxHeight:50};a+=U.getVirtualNodeHeight(v,n,s)}t.events.length>0&&(a+=(t.events.length-1)*10),j=Math.max(j,a)}n.debug(`maxSectionHeight before draw`,S),n.debug(`maxTaskHeight before draw`,C),x&&x.length>0?x.forEach(e=>{let r=y.filter(t=>t.section===e),i={number:O,descr:e,section:O,width:200*Math.max(r.length,1)-50,padding:20,maxHeight:S};n.debug(`sectionNode`,i);let a=v.append(`g`),o=U.drawNode(a,i,O,s,t);n.debug(`sectionNode output`,o),a.attr(`transform`,`translate(${E}, ${T})`),D+=S+50,r.length>0&&W(v,r,O,E,D,C,s,A,j,S,!1,t),E+=200*Math.max(r.length,1),D=T,O++}):(k=!1,W(v,y,O,E,D,C,s,A,j,S,!0,t));let M=v.node().getBBox();if(n.debug(`bounds`,M),b&&v.append(`text`).text(b).attr(`x`,c===`neo`?M.x*2+h:M.width/2-h).attr(`font-size`,`4ex`).attr(`font-weight`,`bold`).attr(`y`,20),w=k?S+C+150:C+100,v.append(`g`).attr(`class`,`lineWrapper`).append(`line`).attr(`x1`,h).attr(`y1`,w).attr(`x2`,M.width+3*h).attr(`y2`,w).attr(`stroke-width`,4).attr(`stroke`,`black`).attr(`marker-end`,`url(#${t}-arrowhead)`),c===`neo`&&f&&l!==`neutral`){let e=v.select(`defs`),t=(e.empty()?v.append(`defs`):e).append(`linearGradient`).attr(`id`,v.attr(`id`)+`-gradient`).attr(`gradientUnits`,`objectBoundingBox`).attr(`x1`,`0%`).attr(`y1`,`0%`).attr(`x2`,`100%`).attr(`y2`,`0%`);t.append(`stop`).attr(`offset`,`0%`).attr(`stop-color`,p).attr(`stop-opacity`,1),t.append(`stop`).attr(`offset`,`100%`).attr(`stop-color`,m).attr(`stop-opacity`,1)}i(void 0,v,s.timeline?.padding??50,s.timeline?.useMaxWidth??!1)},`draw`),W=e(function(e,t,r,i,a,o,s,c,l,u,d,f){for(let c of t){let t={descr:c.task,section:r,number:r,width:150,padding:20,maxHeight:o};n.debug(`taskNode`,t);let u=e.append(`g`).attr(`class`,`taskWrapper`),p=U.drawNode(u,t,r,s,f).height;if(n.debug(`taskHeight after draw`,p),u.attr(`transform`,`translate(${i}, ${a})`),o=Math.max(o,p),c.events){let t=e.append(`g`).attr(`class`,`lineWrapper`),n=o;a+=100,n+=fe(e,c.events,r,i,a,s,f),a-=100,t.append(`line`).attr(`x1`,i+190/2).attr(`y1`,a+o).attr(`x2`,i+190/2).attr(`y2`,a+o+100+l+100).attr(`stroke-width`,2).attr(`stroke`,`black`).attr(`marker-end`,`url(#${f}-arrowhead)`).attr(`stroke-dasharray`,`5,5`)}i+=200,d&&!s.timeline?.disableMulticolor&&r++}a-=10},`drawTasks`),fe=e(function(e,t,r,i,a,o,s){let c=0,l=a;a+=100;for(let l of t){let t={descr:l,section:r,number:r,width:150,padding:20,maxHeight:50};n.debug(`eventNode`,t);let u=e.append(`g`).attr(`class`,`eventWrapper`),d=U.drawNode(u,t,r,o,s,!0).height;c+=d,u.attr(`transform`,`translate(${i}, ${a})`),a=a+10+d}return a=l,c},`drawEvents`),pe={setConf:e(()=>{},`setConf`),draw:de},G=200,K=5,me=G+K*2,q=G+100,he=q+K*2,J=10,ge=0,Y=20,X=20,Z=30,Q=50,_e=e(function(e,t,r,a){let o=d(),s=o.timeline?.leftMargin??50;n.debug(`timeline`,a.db);let c=m(t);c.append(`g`);let l=a.db.getTasks(),u=a.db.getCommonDb().getDiagramTitle();n.debug(`task`,l),U.initGraphics(c);let f=a.db.getSections();n.debug(`sections`,f);let h=0,g=0,_=50+s,v=50,y=v,b=_,x=me+X,S=he+Q,C=b+x,w=0,T=f&&f.length>0,E=T?C:_+x,D=Math.max(50,x+S-K*2);f.forEach(function(e){let t={number:w,descr:e,section:w,width:D,padding:K,maxHeight:h},r=U.getVirtualNodeHeight(c,t,o);n.debug(`sectionHeight before draw`,r),h=Math.max(h,r)});let O=0;n.debug(`tasks.length`,l.length);for(let[e,t]of l.entries()){let r={number:e,descr:t,section:t.section,width:G,padding:K,maxHeight:g},i=U.getVirtualNodeHeight(c,r,o);n.debug(`taskHeight before draw`,i),g=Math.max(g,i);let a=0;for(let e of t.events){let n={descr:e,section:t.section,number:t.section,width:q,padding:K,maxHeight:50};a+=U.getVirtualNodeHeight(c,n,o)}t.events.length>0&&(a+=(t.events.length-1)*J),O=Math.max(O,a)+ge}n.debug(`maxSectionHeight before draw`,h),n.debug(`maxTaskHeight before draw`,g);let k=Math.max(g,O)+Z;T?f.forEach(e=>{let t=l.filter(t=>t.section===e),r={number:w,descr:e,section:w,width:D,padding:K,maxHeight:h};n.debug(`sectionNode`,r);let i=c.append(`g`),a=U.drawNode(i,r,w,o);n.debug(`sectionNode output`,a);let s=E-x;i.attr(`transform`,`translate(${s}, ${v})`);let u=v+a.height+Y;t.length>0&&$(c,t,w,E,u,g,o,k,!1);let d=t.length,f=a.height+Y+k*Math.max(d,1)-(d>0?Z*2:0);v+=f,w++}):$(c,l,w,E,v,g,o,k,!0);let A=c.node()?.getBBox();if(!A)throw Error(`bbox not found`);if(n.debug(`bounds`,A),u){if(c.append(`text`).text(u).attr(`x`,A.width/2-s).attr(`font-size`,`4ex`).attr(`font-weight`,`bold`).attr(`y`,20),A=c.node()?.getBBox(),!A)throw Error(`bbox not found`);n.debug(`bounds after title`,A)}let[j]=p(o.fontSize),M=(j??16)*2,N=(j??16)*.5+20,P=c.append(`g`).attr(`class`,`lineWrapper`);P.append(`line`).attr(`x1`,E).attr(`y1`,y-M).attr(`x2`,E).attr(`y2`,A.y+A.height+N).attr(`stroke-width`,4).attr(`stroke`,`black`).attr(`marker-end`,`url(#arrowhead)`),P.lower(),i(void 0,c,o.timeline?.padding??50,o.timeline?.useMaxWidth??!1)},`draw`),$=e(function(e,t,r,i,a,o,s,c,l){for(let u of t){let t={descr:u.task,section:r,number:r,width:G,padding:K,maxHeight:o};n.debug(`taskNode`,t);let d=e.append(`g`).attr(`class`,`taskWrapper`),f=U.drawNode(d,t,r,s),p=f.height;n.debug(`taskHeight after draw`,p);let m=i-X-f.width;if(d.attr(`transform`,`translate(${m}, ${a})`),o=Math.max(o,p),u.events&&u.events.length>0){let t=a,n=i+Q;ve(e,u.events,r,i,n,t,s)}a+=c,l&&!s.timeline?.disableMulticolor&&r++}},`drawTasks`),ve=e(function(e,t,r,i,a,o,s){let c=o;for(let o of t){let t={descr:o,section:r,number:r,width:q,padding:K,maxHeight:0};n.debug(`eventNode`,t);let l=e.append(`g`).attr(`class`,`eventWrapper`),u=U.drawNode(l,t,r,s).height;l.attr(`transform`,`translate(${a}, ${c})`);let d=e.append(`g`).attr(`class`,`lineWrapper`),f=c+u/2;d.append(`line`).attr(`x1`,i).attr(`y1`,f).attr(`x2`,a).attr(`y2`,f).attr(`stroke-width`,2).attr(`stroke`,`black`).attr(`marker-end`,`url(#arrowhead)`).attr(`stroke-dasharray`,`5,5`),c=c+u+J}return c-o},`drawEvents`),ye={setConf:e(()=>{},`setConf`),draw:_e},be=e(e=>{let{theme:t}=o(),n=t?.includes(`dark`),r=t?.includes(`color`),i=e.svgId?.replace(/^#/,``)??``,a=i?`url(#${i}-drop-shadow)`:e.dropShadow??`none`,s=``;for(let t=0;t{let t=``;for(let t=0;t{},`setConf`),draw:e((e,t,n,r)=>(r?.db?.getDirection?.()??`LR`)===`TD`?ye.draw(e,t,n,r):pe.draw(e,t,n,r),`draw`)},parser:g,styles:e(e=>{let{theme:t}=o(),n=t?.includes(`redux`),r=t===`neutral`,i=e.svgId?.replace(/^#/,``)??``,a=``;if(e.useGradient&&i&&e.THEME_COLOR_LIMIT&&!r)for(let t=0;t{var t=n();function r(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=r()}));function a(e){return e[e.length-1]}function o(e){return typeof e==`function`}function s(e,t){return o(e)?e(t):e}var c=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable;function u(e){for(let t in e)if(c.call(e,t))return!0;return!1}var d=()=>Object.create(null),f=(e,t)=>p(e,t,d);function p(e,t,n=()=>({}),r=0){if(e===t)return e;if(r>500)return t;let i=t,a=_(e)&&_(i);if(!a&&!(h(e)&&h(i)))return i;let o=a?e:m(e);if(!o)return i;let s=a?i:m(i);if(!s)return i;let l=o.length,u=s.length,d=a?Array(u):n(),f=0;for(let t=0;ti||!v(e[o],t[o],n)))return!1;return i===a}return!1}function y(e){let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.status=`pending`,r.resolve=n=>{r.status=`resolved`,r.value=n,t(n),e?.(n)},r.reject=e=>{r.status=`rejected`,n(e)},r}function b(e){return typeof e?.message==`string`?e.message.startsWith(`Failed to fetch dynamically imported module`)||e.message.startsWith(`error loading dynamically imported module`)||e.message.startsWith(`Importing a module script failed`):!1}function x(e){return!!(e&&typeof e==`object`&&typeof e.then==`function`)}var ee=/[\x00-\x1f\x7f"<>`{}]/g;function S(e){return e.replace(ee,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function C(e){let t;try{t=decodeURI(e)}catch{t=e.replaceAll(/%[0-9A-F]{2}/gi,e=>{try{return decodeURI(e)}catch{return e}})}return S(t)}var w=[`http:`,`https:`,`mailto:`,`tel:`];function te(e,t){if(!e)return!1;try{let n=new URL(e);return!t.has(n.protocol)}catch{return!1}}var ne={"&":`\\u0026`,">":`\\u003e`,"<":`\\u003c`,"\u2028":`\\u2028`,"\u2029":`\\u2029`},T=/[&><\u2028\u2029]/g;function re(e){return e.replace(T,e=>ne[e])}function ie(e){if(!e||!/[%\\\x00-\x1f\x7f]/.test(e)&&!e.startsWith(`//`))return{path:e,handledProtocolRelativeURL:!1};let t=/%25|%5C/gi,n=0,r=``,i;for(;(i=t.exec(e))!==null;)r+=C(e.slice(n,i.index))+i[0],n=t.lastIndex;r+=C(n?e.slice(n):e);let a=!1;return r.startsWith(`//`)&&(a=!0,r=`/`+r.replace(/^\/+/,``)),{path:r,handledProtocolRelativeURL:a}}function E(e){return/\s|[^\u0000-\u007F]/.test(e)?e.replace(/\s|[^\u0000-\u007F]/gu,encodeURIComponent):e}function D(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n{e.next&&(e.prev?(e.prev.next=e.next,e.next.prev=e.prev,e.next=void 0,r&&(r.next=e,e.prev=r)):(e.next.prev=void 0,n=e.next,e.next=void 0,r&&(e.prev=r,r.next=e)),r=e)};return{get(e){let n=t.get(e);if(n)return i(n),n.value},set(a,o){if(t.size>=e&&n){let e=n;t.delete(e.key),e.next&&(n=e.next,e.next.prev=void 0),e===r&&(r=void 0)}let s=t.get(a);if(s)s.value=o,i(s);else{let e={key:a,value:o,prev:r};r&&(r.next=e),r=e,n||=e,t.set(a,e)}},clear(){t.clear(),n=void 0,r=void 0}}}var k=4,A=5;function oe(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=e.indexOf(`}`,t);return n===-1||t+1>=e.length?null:[t,n]}function se(e,t,n=new Uint16Array(6)){let r=e.indexOf(`/`,t),i=r===-1?e.length:r,a=e.substring(t,i);if(!a||!a.includes(`$`))return n[0]=0,n[1]=t,n[2]=t,n[3]=i,n[4]=i,n[5]=i,n;if(a===`$`){let r=e.length;return n[0]=2,n[1]=t,n[2]=t,n[3]=r,n[4]=r,n[5]=r,n}if(a.charCodeAt(0)===36)return n[0]=1,n[1]=t,n[2]=t+1,n[3]=i,n[4]=i,n[5]=i,n;let o=oe(a);if(o){let[r,s]=o,c=a.charCodeAt(r+1);if(c===45){if(r+2!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=P(1,n.fullPath??n.from,f,p,m);o=e,e.depth=a,e.parent=i,i.dynamic??=[],i.dynamic.push(e)}break}case 3:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),f=c&&!!(t||s),p=t?f?t:t.toLowerCase():void 0,m=s?f?s:s.toLowerCase():void 0,h=!l&&i.optional?.find(e=>!e.parse&&e.caseSensitive===f&&e.prefix===p&&e.suffix===m);if(h)o=h;else{let e=P(3,n.fullPath??n.from,f,p,m);o=e,e.parent=i,e.depth=a,i.optional??=[],i.optional.push(e)}break}case 2:{let t=r.substring(u,e[1]),s=r.substring(e[4],d),l=c&&!!(t||s),f=t?l?t:t.toLowerCase():void 0,p=s?l?s:s.toLowerCase():void 0,m=P(2,n.fullPath??n.from,l,f,p);o=m,m.parent=i,m.depth=a,i.wildcard??=[],i.wildcard.push(m)}}i=o}if(l&&n.children&&!n.isRoot&&n.id&&n.id.charCodeAt(n.id.lastIndexOf(`/`)+1)===95){let e=N(n.fullPath??n.from);e.kind=A,e.parent=i,a++,e.depth=a,i.pathless??=[],i.pathless.push(e),i=e}let u=(n.path||!n.children)&&!n.isRoot;if(u&&r.endsWith(`/`)){let e=N(n.fullPath??n.from);e.kind=k,e.parent=i,a++,e.depth=a,i.index=e,i=e}i.parse=l??null,i.priority=n.options?.params?.priority??0,u&&!i.route&&(i.route=n,i.fullPath=n.fullPath??n.from)}if(n.children)for(let r of n.children)ce(e,t,r,s,i,a,o)}function j(e,t){if(e.parse&&!t.parse)return-1;if(!e.parse&&t.parse)return 1;if(e.parse&&t.parse&&(e.priority||t.priority))return t.priority-e.priority;if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function M(e){if(e.pathless)for(let t of e.pathless)M(t);if(e.static)for(let t of e.static.values())M(t);if(e.staticInsensitive)for(let t of e.staticInsensitive.values())M(t);if(e.dynamic?.length){e.dynamic.sort(j);for(let t of e.dynamic)M(t)}if(e.optional?.length){e.optional.sort(j);for(let t of e.optional)M(t)}if(e.wildcard?.length){e.wildcard.sort(j);for(let t of e.wildcard)M(t)}}function N(e){return{kind:0,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,parse:null,priority:0}}function P(e,t,n,r,i){return{kind:e,depth:0,pathless:null,index:null,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,parse:null,priority:0,caseSensitive:n,prefix:r,suffix:i}}function F(e,t){let n=N(`/`),r=new Uint16Array(6);for(let t of e)ce(!1,r,t,1,n,0);M(n),t.masksTree=n,t.flatCache=ae(1e3)}function I(e,t){e||=`/`;let n=t.flatCache.get(e);if(n)return n;let r=B(e,t.masksTree);return t.flatCache.set(e,r),r}function le(e,t,n,r,i){e||=`/`,r||=`/`;let a=t?`case\0${e}`:e,o=i.singleCache.get(a);return o||(o=N(`/`),ce(t,new Uint16Array(6),{from:e},1,o,0),i.singleCache.set(a,o)),B(r,o,n)}function L(e,t,n=!1){let r=n?e:`nofuzz\0${e}`,i=t.matchCache.get(r);if(i!==void 0)return i;e||=`/`;let a;try{a=B(e,t.segmentTree,n)}catch(e){if(e instanceof URIError)a=null;else throw e}return a&&(a.branch=de(a.route)),t.matchCache.set(r,a),a}function R(e){return e===`/`?e:e.replace(/\/{1,}$/,``)}function z(e,t=!1,n){let r=N(e.fullPath),i=new Uint16Array(6),a={},o={},s=0;return ce(t,i,e,1,r,0,e=>{if(n?.(e,s),e.id in a&&O(),a[e.id]=e,s!==0&&e.path){let t=R(e.fullPath);(!o[t]||e.fullPath.endsWith(`/`))&&(o[t]=e)}s++}),M(r),{processedTree:{segmentTree:r,singleCache:ae(1e3),matchCache:ae(1e3),flatCache:null,masksTree:null},routesById:a,routesByPath:o}}function B(e,t,n=!1){let r=e.split(`/`),i=pe(e,r,t,n);if(!i)return null;let[a]=ue(e,r,i);return{route:i.node.route,rawParams:a}}function ue(e,t,n){let r=fe(n.node),i=null,a=Object.create(null),o=n.extract?.part??0,s=n.extract?.node??0,c=n.extract?.path??0,l=n.extract?.segment??0;for(;s=0;e--){let n=i.wildcard[e],{prefix:r,suffix:o}=n;if(!(r&&(v||!(n.caseSensitive?y:b??=y.toLowerCase()).startsWith(r)))){if(o){if(v)continue;let e=t.slice(a).join(`/`).slice(-o.length);if((n.caseSensitive?e:e.toLowerCase())!==o)continue}c.push({node:n,index:s,skipped:d,depth:f+1,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}if(i.optional){let e=d|1<=0;n--){let r=i.optional[n];c.push({node:r,index:a,skipped:e,depth:t,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v)for(let e=i.optional.length-1;e>=0;e--){let n=i.optional[e],{prefix:r,suffix:o}=n;if(r||o){let e=n.caseSensitive?y:b??=y.toLowerCase();if(r&&!e.startsWith(r)||o&&!e.endsWith(o))continue}c.push({node:n,index:a+1,skipped:d,depth:t,statics:p,dynamics:m,optionals:h+me(s,a),extract:g,rawParams:_})}}if(!v&&i.dynamic&&y)for(let e=i.dynamic.length-1;e>=0;e--){let t=i.dynamic[e],{prefix:n,suffix:r}=t;if(n||r){let e=t.caseSensitive?y:b??=y.toLowerCase();if(n&&!e.startsWith(n)||r&&!e.endsWith(r))continue}c.push({node:t,index:a+1,skipped:d,depth:f+1,statics:p,dynamics:m+me(s,a),optionals:h,extract:g,rawParams:_})}if(!v&&i.staticInsensitive){let e=i.staticInsensitive.get(b??=y.toLowerCase());e&&c.push({node:e,index:a+1,skipped:d,depth:f+1,statics:p+me(s,a),dynamics:m,optionals:h,extract:g,rawParams:_})}if(!v&&i.static){let e=i.static.get(y);e&&c.push({node:e,index:a+1,skipped:d,depth:f+1,statics:p+me(s,a),dynamics:m,optionals:h,extract:g,rawParams:_})}if(i.pathless){let e=f+1;for(let t=i.pathless.length-1;t>=0;t--){let n=i.pathless[t];c.push({node:n,index:a,skipped:d,depth:e,statics:p,dynamics:m,optionals:h,extract:g,rawParams:_})}}}if(u)return u;if(r&&l){let n=l.index;for(let e=0;ee.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&((t.node.kind===k)>(e.node.kind===k)||t.node.kind===k==(e.node.kind===k)&&t.depth>e.depth)))}function U(e){return ge(e.filter(e=>e!==void 0).join(`/`))}function ge(e){return e.replace(/\/{2,}/g,`/`)}function _e(e){return e===`/`?e:e.replace(/^\/{1,}/,``)}function ve(e){let t=e.length;return t>1&&e[t-1]===`/`?e.replace(/\/{1,}$/,``):e}function ye(e){return ve(_e(e))}function be(e,t){return e?.endsWith(`/`)&&e!==`/`&&e!==`${t}/`?e.slice(0,-1):e}function xe(e,t,n){return be(e,n)===be(t,n)}function Se({base:e,to:t,trailingSlash:n=`never`,cache:r}){let i=t.startsWith(`/`),o=!i&&t===`.`,s;if(r){s=i?t:o?e:e+`\0`+t;let n=r.get(s);if(n)return n}let c;if(o)c=e.split(`/`);else if(i)c=t.split(`/`);else{for(c=e.split(`/`);c.length>1&&a(c)===``;)c.pop();let n=t.split(`/`);for(let e=0,t=n.length;e1&&(a(c)===``?n===`never`&&c.pop():n===`always`&&c.push(``));let l=ge(c.join(`/`))||`/`;return s&&r&&r.set(s,l),l}function Ce(e){let t=new Map(e.map(e=>[encodeURIComponent(e),e])),n=Array.from(t.keys()).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),r=new RegExp(n,`g`);return e=>e.replace(r,e=>t.get(e)??e)}function we(e,t,n){let r=t[e];return typeof r==`string`?e===`_splat`?/^[a-zA-Z0-9\-._~!/]*$/.test(r)?r:r.split(`/`).map(e=>Ee(e,n)).join(`/`):Ee(r,n):r}function Te({path:e,params:t,decoder:n,...r}){let i=!1,a=Object.create(null);if(!e||e===`/`)return{interpolatedPath:`/`,usedParams:a,isMissingParams:i};if(!e.includes(`$`))return{interpolatedPath:e,usedParams:a,isMissingParams:i};let o=e.length,s=0,c,l=``;for(;s{if(!e.current||r.disabled||typeof IntersectionObserver!=`function`)return;let i=new IntersectionObserver(([e])=>{t(e)},n);return i.observe(e.current),()=>{i.disconnect()}},[t,n,r.disabled,e])}function Me(e){let t=W.useRef(null);return W.useImperativeHandle(e,()=>t.current,[]),t}var Ne=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),Pe=t(((e,t)=>{t.exports=Ne()})),Fe=Pe();function Ie({children:e,fallback:t=null}){return Le()?(0,Fe.jsx)(W.Fragment,{children:e}):(0,Fe.jsx)(W.Fragment,{children:t})}function Le(){return W.useSyncExternalStore(Re,()=>!0,()=>!1)}function Re(){return()=>{}}var ze=W.createContext(null);function Be(e){return W.useContext(ze)}var Ve=t((e=>{var t=n();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=t.useState,o=t.useEffect,s=t.useLayoutEffect,c=t.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!i(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),He=t(((e,t)=>{t.exports=Ve()})),Ue=t((e=>{var t=n(),r=He();function i(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:i,o=r.useSyncExternalStore,s=t.useRef,c=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),We=t(((e,t)=>{t.exports=Ue()}))();function Ge(e,t){return e===t}function Ke(e,t,n=Ge){let r=(0,W.useCallback)(t=>{if(!e)return()=>{};let{unsubscribe:n}=e.subscribe(t);return n},[e]),i=(0,W.useCallback)(()=>e?.get(),[e]);return(0,We.useSyncExternalStoreWithSelector)(r,i,i,t,n)}var qe=e(i(),1);function Je(e,t){let n=Be(),r=Me(t),{activeProps:i,inactiveProps:a,activeOptions:o,to:c,preload:l,preloadDelay:u,preloadIntentProximity:d,hashScrollIntoView:f,replace:p,startTransition:m,resetScroll:h,viewTransition:g,children:_,target:y,disabled:b,style:x,className:ee,onClick:S,onBlur:C,onFocus:w,onMouseEnter:ne,onMouseLeave:T,onTouchStart:re,ignoreBlocker:ie,params:E,search:D,hash:O,state:ae,mask:k,reloadDocument:A,unsafeRelative:oe,from:se,_fromLocation:ce,...j}=e,M=Le(),N=W.useMemo(()=>e,[n,e.from,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),P=Ke(n.stores.location,e=>e,(e,t)=>e.href===t.href),F=W.useMemo(()=>{let e={_fromLocation:P,...N};return n.buildLocation(e)},[n,P,N]),I=F.maskedLocation?F.maskedLocation.publicHref:F.publicHref,le=F.maskedLocation?F.maskedLocation.external:F.external,L=W.useMemo(()=>rt(I,le,n.history,b),[b,le,I,n.history]),R=W.useMemo(()=>{if(L?.external)return te(L.href,n.protocolAllowlist)?void 0:L.href;if(!it(c)&&!(typeof c!=`string`||c.indexOf(`:`)===-1))try{return new URL(c),te(c,n.protocolAllowlist)?void 0:c}catch{}},[c,L,n.protocolAllowlist]),z=W.useMemo(()=>{if(R)return!1;if(o?.exact){if(!xe(P.pathname,F.pathname,n.basepath))return!1}else{let e=be(P.pathname,n.basepath),t=be(F.pathname,n.basepath);if(!(e.startsWith(t)&&(e.length===t.length||e[t.length]===`/`)))return!1}return(o?.includeSearch??!0)&&!v(P.search,F.search,{partial:!o?.exact,ignoreUndefined:!o?.explicitUndefined})?!1:!o?.includeHash||M&&P.hash===F.hash},[o?.exact,o?.explicitUndefined,o?.includeHash,o?.includeSearch,P,R,M,F.hash,F.pathname,F.search,n.basepath]),B=z?s(i,{})??Xe:Ye,ue=z?Ye:s(a,{})??Ye,de=[ee,B.className,ue.className].filter(Boolean).join(` `),fe=(x||B.style||ue.style)&&{...x,...B.style,...ue.style},[pe,me]=W.useState(!1),he=W.useRef(!1),V=e.reloadDocument||R?!1:l??n.options.defaultPreload,H=u??n.options.defaultPreloadDelay??0,U=W.useCallback(()=>{n.preloadRoute({...N,_builtLocation:F}).catch(e=>{console.warn(e),console.warn(De)})},[n,N,F]);je(r,W.useCallback(e=>{e?.isIntersecting&&U()},[U]),tt,{disabled:!!b||V!==`viewport`}),W.useEffect(()=>{he.current||!b&&V===`render`&&(U(),he.current=!0)},[b,U,V]);let ge=e=>{let t=e.currentTarget.getAttribute(`target`),r=y===void 0?t:y;if(!b&&!ot(e)&&!e.defaultPrevented&&(!r||r===`_self`)&&e.button===0){e.preventDefault(),(0,qe.flushSync)(()=>{me(!0)});let t=n.subscribe(`onResolved`,()=>{t(),me(!1)});n.navigate({...N,replace:p,resetScroll:h,hashScrollIntoView:f,startTransition:m,viewTransition:g,ignoreBlocker:ie})}};if(R)return{...j,ref:r,href:R,..._&&{children:_},...y&&{target:y},...b&&{disabled:b},...x&&{style:x},...ee&&{className:ee},...S&&{onClick:S},...C&&{onBlur:C},...w&&{onFocus:w},...ne&&{onMouseEnter:ne},...T&&{onMouseLeave:T},...re&&{onTouchStart:re}};let _e=e=>{if(b||V!==`intent`)return;if(!H){U();return}let t=e.currentTarget;if(et.has(t))return;let n=setTimeout(()=>{et.delete(t),U()},H);et.set(t,n)},ve=e=>{b||V!==`intent`||U()},ye=e=>{if(b||!V||!H)return;let t=e.currentTarget,n=et.get(t);n&&(clearTimeout(n),et.delete(t))};return{...j,...B,...ue,href:L?.href,ref:r,onClick:nt([S,ge]),onBlur:nt([C,ye]),onFocus:nt([w,_e]),onMouseEnter:nt([ne,_e]),onMouseLeave:nt([T,ye]),onTouchStart:nt([re,ve]),disabled:!!b,target:y,...fe&&{style:fe},...de&&{className:de},...b&&Ze,...z&&Qe,...M&&pe&&$e}}var Ye={},Xe={className:`active`},Ze={role:`link`,"aria-disabled":!0},Qe={"data-status":`active`,"aria-current":`page`},$e={"data-transitioning":`transitioning`},et=new WeakMap,tt={rootMargin:`100px`},nt=e=>t=>{for(let n of e)if(n){if(t.defaultPrevented)return;n(t)}};function rt(e,t,n,r){if(!r)return t?{href:e,external:!0}:{href:n.createHref(e)||`/`,external:!1}}function it(e){if(typeof e!=`string`)return!1;let t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var at=W.forwardRef((e,t)=>{let{_asChild:n,...r}=e,{type:i,...a}=Je(r,t),o=typeof r.children==`function`?r.children({isActive:a[`data-status`]===`active`}):r.children;if(!n){let{disabled:e,...t}=a;return W.createElement(`a`,t,o)}return W.createElement(n,a,o)});function ot(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function st(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`)if(Array.isArray(e)){var i=e.length;for(t=0;t{let n=Array(e.length+t.length);for(let t=0;t({classGroupId:e,validator:t}),dt=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),ft=`-`,pt=[],mt=`arbitrary..`,ht=e=>{let t=vt(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return _t(e);let n=e.split(ft);return gt(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?lt(i,t):t:i||pt}return n[e]||pt}}},gt=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=gt(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(ft):e.slice(t).join(ft),s=a.length;for(let e=0;ee.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?mt+r:void 0})(),vt=e=>{let{theme:t,classGroups:n}=e;return yt(n,t)},yt=(e,t)=>{let n=dt();for(let r in e){let i=e[r];bt(i,n,r,t)}return n},bt=(e,t,n,r)=>{let i=e.length;for(let a=0;a{if(typeof e==`string`){St(e,t,n);return}if(typeof e==`function`){Ct(e,t,n,r);return}wt(e,t,n,r)},St=(e,t,n)=>{let r=e===``?t:Tt(t,e);r.classGroupId=n},Ct=(e,t,n,r)=>{if(Et(e)){bt(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(ut(n,e))},wt=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e{let n=e,r=t.split(ft),i=r.length;for(let e=0;e`isThemeGetter`in e&&e.isThemeGetter===!0,Dt=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},Ot=`!`,kt=`:`,At=[],jt=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),Mt=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;si?a-i:void 0;return jt(t,l,c,u)};if(t){let e=t+kt,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):jt(At,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},Nt=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},Pt=e=>({cache:Dt(e.cacheSize),parseClassName:Mt(e),sortModifiers:Nt(e),postfixLookupClassGroupIds:Ft(e),...ht(e)}),Ft=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(It),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+Ot:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e0?` `+l:l)}return l},Rt=(...e)=>{let t=0,n,r,i=``;for(;t{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r{let n,r,i,a,o=o=>(n=Pt(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=Lt(e,n);return i(e,a),a};return a=o,(...e)=>a(Rt(...e))},Vt=[],G=e=>{let t=t=>t[e]||Vt;return t.isThemeGetter=!0,t},Ht=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Ut=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Wt=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Gt=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Kt=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,qt=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Jt=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Yt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,K=e=>Wt.test(e),q=e=>!!e&&!Number.isNaN(Number(e)),J=e=>!!e&&Number.isInteger(Number(e)),Xt=e=>e.endsWith(`%`)&&q(e.slice(0,-1)),Y=e=>Gt.test(e),Zt=()=>!0,Qt=e=>Kt.test(e)&&!qt.test(e),$t=()=>!1,en=e=>Jt.test(e),tn=e=>Yt.test(e),nn=e=>!X(e)&&!Z(e),rn=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),an=e=>Q(e,Sn,$t),X=e=>Ht.test(e),on=e=>Q(e,Cn,Qt),sn=e=>Q(e,wn,q),cn=e=>Q(e,En,Zt),ln=e=>Q(e,Tn,$t),un=e=>Q(e,bn,$t),dn=e=>Q(e,xn,tn),fn=e=>Q(e,Dn,en),Z=e=>Ut.test(e),pn=e=>$(e,Cn),mn=e=>$(e,Tn),hn=e=>$(e,bn),gn=e=>$(e,Sn),_n=e=>$(e,xn),vn=e=>$(e,Dn,!0),yn=e=>$(e,En,!0),Q=(e,t,n)=>{let r=Ht.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},$=(e,t,n=!1)=>{let r=Ut.exec(e);return r?r[1]?t(r[1]):n:!1},bn=e=>e===`position`||e===`percentage`,xn=e=>e===`image`||e===`url`,Sn=e=>e===`length`||e===`size`||e===`bg-size`,Cn=e=>e===`length`,wn=e=>e===`number`,Tn=e=>e===`family-name`,En=e=>e===`number`||e===`weight`,Dn=e=>e===`shadow`,On=Bt(()=>{let e=G(`color`),t=G(`font`),n=G(`text`),r=G(`font-weight`),i=G(`tracking`),a=G(`leading`),o=G(`breakpoint`),s=G(`container`),c=G(`spacing`),l=G(`radius`),u=G(`shadow`),d=G(`inset-shadow`),f=G(`text-shadow`),p=G(`drop-shadow`),m=G(`blur`),h=G(`perspective`),g=G(`aspect`),_=G(`ease`),v=G(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),Z,X],ee=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],S=()=>[`auto`,`contain`,`none`],C=()=>[Z,X,c],w=()=>[K,`full`,`auto`,...C()],te=()=>[J,`none`,`subgrid`,Z,X],ne=()=>[`auto`,{span:[`full`,J,Z,X]},J,Z,X],T=()=>[J,`auto`,Z,X],re=()=>[`auto`,`min`,`max`,`fr`,Z,X],ie=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],E=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],D=()=>[`auto`,...C()],O=()=>[K,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...C()],ae=()=>[K,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...C()],k=()=>[K,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...C()],A=()=>[e,Z,X],oe=()=>[...b(),hn,un,{position:[Z,X]}],se=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],ce=()=>[`auto`,`cover`,`contain`,gn,an,{size:[Z,X]}],j=()=>[Xt,pn,on],M=()=>[``,`none`,`full`,l,Z,X],N=()=>[``,q,pn,on],P=()=>[`solid`,`dashed`,`dotted`,`double`],F=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],I=()=>[q,Xt,hn,un],le=()=>[``,`none`,m,Z,X],L=()=>[`none`,q,Z,X],R=()=>[`none`,q,Z,X],z=()=>[q,Z,X],B=()=>[K,`full`,...C()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[Y],breakpoint:[Y],color:[Zt],container:[Y],"drop-shadow":[Y],ease:[`in`,`out`,`in-out`],font:[nn],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[Y],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[Y],shadow:[Y],spacing:[`px`,q],text:[Y],"text-shadow":[Y],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,K,X,Z,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,Z,X]}],"container-named":[rn],columns:[{columns:[q,X,Z,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:ee()}],"overflow-x":[{"overflow-x":ee()}],"overflow-y":[{"overflow-y":ee()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:w()}],"inset-x":[{"inset-x":w()}],"inset-y":[{"inset-y":w()}],start:[{"inset-s":w(),start:w()}],end:[{"inset-e":w(),end:w()}],"inset-bs":[{"inset-bs":w()}],"inset-be":[{"inset-be":w()}],top:[{top:w()}],right:[{right:w()}],bottom:[{bottom:w()}],left:[{left:w()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[J,`auto`,Z,X]}],basis:[{basis:[K,`full`,`auto`,s,...C()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[q,K,`auto`,`initial`,`none`,X]}],grow:[{grow:[``,q,Z,X]}],shrink:[{shrink:[``,q,Z,X]}],order:[{order:[J,`first`,`last`,`none`,Z,X]}],"grid-cols":[{"grid-cols":te()}],"col-start-end":[{col:ne()}],"col-start":[{"col-start":T()}],"col-end":[{"col-end":T()}],"grid-rows":[{"grid-rows":te()}],"row-start-end":[{row:ne()}],"row-start":[{"row-start":T()}],"row-end":[{"row-end":T()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":re()}],"auto-rows":[{"auto-rows":re()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...ie(),`normal`]}],"justify-items":[{"justify-items":[...E(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...E()]}],"align-content":[{content:[`normal`,...ie()]}],"align-items":[{items:[...E(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...E(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":ie()}],"place-items":[{"place-items":[...E(),`baseline`]}],"place-self":[{"place-self":[`auto`,...E()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pbs:[{pbs:C()}],pbe:[{pbe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:D()}],mx:[{mx:D()}],my:[{my:D()}],ms:[{ms:D()}],me:[{me:D()}],mbs:[{mbs:D()}],mbe:[{mbe:D()}],mt:[{mt:D()}],mr:[{mr:D()}],mb:[{mb:D()}],ml:[{ml:D()}],"space-x":[{"space-x":C()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":C()}],"space-y-reverse":[`space-y-reverse`],size:[{size:O()}],"inline-size":[{inline:[`auto`,...ae()]}],"min-inline-size":[{"min-inline":[`auto`,...ae()]}],"max-inline-size":[{"max-inline":[`none`,...ae()]}],"block-size":[{block:[`auto`,...k()]}],"min-block-size":[{"min-block":[`auto`,...k()]}],"max-block-size":[{"max-block":[`none`,...k()]}],w:[{w:[s,`screen`,...O()]}],"min-w":[{"min-w":[s,`screen`,`none`,...O()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...O()]}],h:[{h:[`screen`,`lh`,...O()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...O()]}],"max-h":[{"max-h":[`screen`,`lh`,...O()]}],"font-size":[{text:[`base`,n,pn,on]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,yn,cn]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,Xt,X]}],"font-family":[{font:[mn,ln,t]}],"font-features":[{"font-features":[X]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,Z,X]}],"line-clamp":[{"line-clamp":[q,`none`,Z,sn]}],leading:[{leading:[a,...C()]}],"list-image":[{"list-image":[`none`,Z,X]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,Z,X]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:A()}],"text-color":[{text:A()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...P(),`wavy`]}],"text-decoration-thickness":[{decoration:[q,`from-font`,`auto`,Z,on]}],"text-decoration-color":[{decoration:A()}],"underline-offset":[{"underline-offset":[q,`auto`,Z,X]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:C()}],"tab-size":[{tab:[J,Z,X]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,Z,X]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,Z,X]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:oe()}],"bg-repeat":[{bg:se()}],"bg-size":[{bg:ce()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},J,Z,X],radial:[``,Z,X],conic:[J,Z,X]},_n,dn]}],"bg-color":[{bg:A()}],"gradient-from-pos":[{from:j()}],"gradient-via-pos":[{via:j()}],"gradient-to-pos":[{to:j()}],"gradient-from":[{from:A()}],"gradient-via":[{via:A()}],"gradient-to":[{to:A()}],rounded:[{rounded:M()}],"rounded-s":[{"rounded-s":M()}],"rounded-e":[{"rounded-e":M()}],"rounded-t":[{"rounded-t":M()}],"rounded-r":[{"rounded-r":M()}],"rounded-b":[{"rounded-b":M()}],"rounded-l":[{"rounded-l":M()}],"rounded-ss":[{"rounded-ss":M()}],"rounded-se":[{"rounded-se":M()}],"rounded-ee":[{"rounded-ee":M()}],"rounded-es":[{"rounded-es":M()}],"rounded-tl":[{"rounded-tl":M()}],"rounded-tr":[{"rounded-tr":M()}],"rounded-br":[{"rounded-br":M()}],"rounded-bl":[{"rounded-bl":M()}],"border-w":[{border:N()}],"border-w-x":[{"border-x":N()}],"border-w-y":[{"border-y":N()}],"border-w-s":[{"border-s":N()}],"border-w-e":[{"border-e":N()}],"border-w-bs":[{"border-bs":N()}],"border-w-be":[{"border-be":N()}],"border-w-t":[{"border-t":N()}],"border-w-r":[{"border-r":N()}],"border-w-b":[{"border-b":N()}],"border-w-l":[{"border-l":N()}],"divide-x":[{"divide-x":N()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":N()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...P(),`hidden`,`none`]}],"divide-style":[{divide:[...P(),`hidden`,`none`]}],"border-color":[{border:A()}],"border-color-x":[{"border-x":A()}],"border-color-y":[{"border-y":A()}],"border-color-s":[{"border-s":A()}],"border-color-e":[{"border-e":A()}],"border-color-bs":[{"border-bs":A()}],"border-color-be":[{"border-be":A()}],"border-color-t":[{"border-t":A()}],"border-color-r":[{"border-r":A()}],"border-color-b":[{"border-b":A()}],"border-color-l":[{"border-l":A()}],"divide-color":[{divide:A()}],"outline-style":[{outline:[...P(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[q,Z,X]}],"outline-w":[{outline:[``,q,pn,on]}],"outline-color":[{outline:A()}],shadow:[{shadow:[``,`none`,u,vn,fn]}],"shadow-color":[{shadow:A()}],"inset-shadow":[{"inset-shadow":[`none`,d,vn,fn]}],"inset-shadow-color":[{"inset-shadow":A()}],"ring-w":[{ring:N()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:A()}],"ring-offset-w":[{"ring-offset":[q,on]}],"ring-offset-color":[{"ring-offset":A()}],"inset-ring-w":[{"inset-ring":N()}],"inset-ring-color":[{"inset-ring":A()}],"text-shadow":[{"text-shadow":[`none`,f,vn,fn]}],"text-shadow-color":[{"text-shadow":A()}],opacity:[{opacity:[q,Z,X]}],"mix-blend":[{"mix-blend":[...F(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":F()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[q]}],"mask-image-linear-from-pos":[{"mask-linear-from":I()}],"mask-image-linear-to-pos":[{"mask-linear-to":I()}],"mask-image-linear-from-color":[{"mask-linear-from":A()}],"mask-image-linear-to-color":[{"mask-linear-to":A()}],"mask-image-t-from-pos":[{"mask-t-from":I()}],"mask-image-t-to-pos":[{"mask-t-to":I()}],"mask-image-t-from-color":[{"mask-t-from":A()}],"mask-image-t-to-color":[{"mask-t-to":A()}],"mask-image-r-from-pos":[{"mask-r-from":I()}],"mask-image-r-to-pos":[{"mask-r-to":I()}],"mask-image-r-from-color":[{"mask-r-from":A()}],"mask-image-r-to-color":[{"mask-r-to":A()}],"mask-image-b-from-pos":[{"mask-b-from":I()}],"mask-image-b-to-pos":[{"mask-b-to":I()}],"mask-image-b-from-color":[{"mask-b-from":A()}],"mask-image-b-to-color":[{"mask-b-to":A()}],"mask-image-l-from-pos":[{"mask-l-from":I()}],"mask-image-l-to-pos":[{"mask-l-to":I()}],"mask-image-l-from-color":[{"mask-l-from":A()}],"mask-image-l-to-color":[{"mask-l-to":A()}],"mask-image-x-from-pos":[{"mask-x-from":I()}],"mask-image-x-to-pos":[{"mask-x-to":I()}],"mask-image-x-from-color":[{"mask-x-from":A()}],"mask-image-x-to-color":[{"mask-x-to":A()}],"mask-image-y-from-pos":[{"mask-y-from":I()}],"mask-image-y-to-pos":[{"mask-y-to":I()}],"mask-image-y-from-color":[{"mask-y-from":A()}],"mask-image-y-to-color":[{"mask-y-to":A()}],"mask-image-radial":[{"mask-radial":[Z,X]}],"mask-image-radial-from-pos":[{"mask-radial-from":I()}],"mask-image-radial-to-pos":[{"mask-radial-to":I()}],"mask-image-radial-from-color":[{"mask-radial-from":A()}],"mask-image-radial-to-color":[{"mask-radial-to":A()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[q]}],"mask-image-conic-from-pos":[{"mask-conic-from":I()}],"mask-image-conic-to-pos":[{"mask-conic-to":I()}],"mask-image-conic-from-color":[{"mask-conic-from":A()}],"mask-image-conic-to-color":[{"mask-conic-to":A()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:oe()}],"mask-repeat":[{mask:se()}],"mask-size":[{mask:ce()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,Z,X]}],filter:[{filter:[``,`none`,Z,X]}],blur:[{blur:le()}],brightness:[{brightness:[q,Z,X]}],contrast:[{contrast:[q,Z,X]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,vn,fn]}],"drop-shadow-color":[{"drop-shadow":A()}],grayscale:[{grayscale:[``,q,Z,X]}],"hue-rotate":[{"hue-rotate":[q,Z,X]}],invert:[{invert:[``,q,Z,X]}],saturate:[{saturate:[q,Z,X]}],sepia:[{sepia:[``,q,Z,X]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,Z,X]}],"backdrop-blur":[{"backdrop-blur":le()}],"backdrop-brightness":[{"backdrop-brightness":[q,Z,X]}],"backdrop-contrast":[{"backdrop-contrast":[q,Z,X]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,q,Z,X]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[q,Z,X]}],"backdrop-invert":[{"backdrop-invert":[``,q,Z,X]}],"backdrop-opacity":[{"backdrop-opacity":[q,Z,X]}],"backdrop-saturate":[{"backdrop-saturate":[q,Z,X]}],"backdrop-sepia":[{"backdrop-sepia":[``,q,Z,X]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,Z,X]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[q,`initial`,Z,X]}],ease:[{ease:[`linear`,`initial`,_,Z,X]}],delay:[{delay:[q,Z,X]}],animate:[{animate:[`none`,v,Z,X]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,Z,X]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:L()}],"rotate-x":[{"rotate-x":L()}],"rotate-y":[{"rotate-y":L()}],"rotate-z":[{"rotate-z":L()}],scale:[{scale:R()}],"scale-x":[{"scale-x":R()}],"scale-y":[{"scale-y":R()}],"scale-z":[{"scale-z":R()}],"scale-3d":[`scale-3d`],skew:[{skew:z()}],"skew-x":[{"skew-x":z()}],"skew-y":[{"skew-y":z()}],transform:[{transform:[Z,X,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:B()}],"translate-x":[{"translate-x":B()}],"translate-y":[{"translate-y":B()}],"translate-z":[{"translate-z":B()}],"translate-none":[`translate-none`],zoom:[{zoom:[J,Z,X]}],accent:[{accent:A()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:A()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,Z,X]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":A()}],"scrollbar-track-color":[{"scrollbar-track":A()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mbs":[{"scroll-mbs":C()}],"scroll-mbe":[{"scroll-mbe":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pbs":[{"scroll-pbs":C()}],"scroll-pbe":[{"scroll-pbe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,Z,X]}],fill:[{fill:[`none`,...A()]}],"stroke-w":[{stroke:[q,pn,on,sn]}],stroke:[{stroke:[`none`,...A()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function kn(...e){return On(ct(e))}function An(e=`id`){return`${e}_${Math.random().toString(36).slice(2,10)}${Date.now().toString(36).slice(-4)}`}export{w as A,b as B,I as C,z as D,F as E,E as F,i as G,a as H,re as I,s as L,y as M,ie as N,ae as O,v as P,u as R,de as S,le as T,f as U,x as V,p as W,U as _,Ke as a,_e as b,Ie as c,Oe as d,ke as f,Te as g,Ce as h,at as i,D as j,O as k,Le as l,ge as m,An as n,Be as o,Ae as p,ct as r,ze as s,kn as t,Pe as u,Se as v,L as w,ve as x,ye as y,te as z}; \ No newline at end of file diff --git a/dist-desktop/assets/vennDiagram-L72KCM5P-DkYnXwoc.js b/dist-desktop/assets/vennDiagram-L72KCM5P-DkYnXwoc.js new file mode 100644 index 0000000..95deb1e --- /dev/null +++ b/dist-desktop/assets/vennDiagram-L72KCM5P-DkYnXwoc.js @@ -0,0 +1,34 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{H as n,K as r,U as i,a,b as o,c as s,et as c,f as l,nt as u,rt as d,tt as f,v as p,w as m,y as h}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as g}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as _}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as v}from"./rough.esm-CSKSodPl.js";var y=(e,t)=>u(e,`a`,-t),b=1e-10;function x(e,t){let n=C(e),r=n.filter(t=>S(t,e)),i=0,a=0,o=[];if(r.length>1){let t=O(r);for(let e=0;et.angle-e.angle);let n=r[r.length-1];for(let t=0;tr.radius*2&&(d=r.radius*2),(l==null||l.width>d)&&(l={circle:r,width:d,p1:s,p2:n,large:d>r.radius,sweep:!0})}l!=null&&(o.push(l),i+=w(l.circle.radius,l.width),n=s)}}else{let t=e[0];for(let n=1;nMath.abs(t.radius-e[r].radius)){n=!0;break}n?i=a=0:(i=t.radius*t.radius*Math.PI,o.push({circle:t,p1:{x:t.x,y:t.y+t.radius},p2:{x:t.x-b,y:t.y+t.radius},width:t.radius*2,large:!0,sweep:!0}))}return a/=2,t&&(t.area=i+a,t.arcArea=i,t.polygonArea=a,t.arcs=o,t.innerPoints=r,t.intersectionPoints=n),i+a}function S(e,t){return t.every(t=>T(e,t)=e+t)return 0;if(n<=Math.abs(e-t))return Math.PI*Math.min(e,t)*Math.min(e,t);let r=e-(n*n-t*t+e*e)/(2*n),i=t-(n*n-e*e+t*t)/(2*n);return w(e,r)+w(t,i)}function D(e,t){let n=T(e,t),r=e.radius,i=t.radius;if(n>=r+i||n<=Math.abs(r-i))return[];let a=(r*r-i*i+n*n)/(2*n),o=Math.sqrt(r*r-a*a),s=e.x+a*(t.x-e.x)/n,c=e.y+a*(t.y-e.y)/n,l=-(t.y-e.y)*(o/n),u=-(t.x-e.x)*(o/n);return[{x:s+l,y:c-u},{x:s-l,y:c+u}]}function O(e){let t={x:0,y:0};for(let n of e)t.x+=n.x,t.y+=n.y;return t.x/=e.length,t.y/=e.length,t}function k(e,t,n,r){r||={};let i=r.maxIterations||100,a=r.tolerance||1e-10,o=e(t),s=e(n),c=n-t;if(o*s>0)throw`Initial bisect points must have opposite signs`;if(o===0)return t;if(s===0)return n;for(let n=0;n=0&&(t=n),Math.abs(c)A(t))}function M(e,t){let n=0;for(let r=0;re.fx-t.fx,_=t.slice(),v=t.slice(),y=t.slice(),b=t.slice();for(let t=0;t{let t=e.slice();return t.fx=e.fx,t.id=e.id,t});e.sort((e,t)=>e.id-t.id),n.history.push({x:m[0].slice(),fx:m[0].fx,simplex:e})}f=0;for(let e=0;e=m[p-1].fx){let n=!1;if(v.fx>t.fx?(F(y,1+u,_,-u,t),y.fx=e(y),y.fx=1)break;for(let t=1;ts+a*i*c||l>=p)f=i;else{if(Math.abs(d)<=-o*c)return i;d*(f-u)>=0&&(f=u),u=i,p=l}return 0}for(let m=0;m<10;++m){if(F(r.x,1,n.x,i,t),l=r.fx=e(r.x,r.fxprime),d=M(r.fxprime,t),l>s+a*i*c||m&&l>=u)return p(f,i,u);if(Math.abs(d)<=-o*c)return i;if(d>=0)return p(i,f,l);u=l,f=i,i*=2}return i}function R(e,t,n){let r={x:t.slice(),fx:0,fxprime:t.slice()},i={x:t.slice(),fx:0,fxprime:t.slice()},a=t.slice(),o,s,c=1,l;n||={},l=n.maxIterations||t.length*20,r.fx=e(r.x,r.fxprime),o=r.fxprime.slice(),P(o,r.fxprime,-1);for(let t=0;t{let t={};for(let n=0;nE(e,t,r)-n,0,e+t)}function ne(e,t={}){let n=t.distinct,r=e.map(e=>Object.assign({},e));function i(e){return e.join(`;`)}if(n){let e=new Map;for(let t of r)for(let n=0;ne===t?0:ee.sets.length===2).forEach(e=>{let a=n[e.sets[0]],o=n[e.sets[1]],s=z(Math.sqrt(t[a].size/Math.PI),Math.sqrt(t[o].size/Math.PI),e.size);r[a][o]=r[o][a]=s;let c=0;e.size+1e-10>=Math.min(t[a].size,t[o].size)?c=1:e.size<=1e-10&&(c=-1),i[a][o]=i[o][a]=c}),{distances:r,constraints:i}}function ie(e,t,n,r){for(let e=0;e0&&m<=d||f<0&&m>=d||(i+=2*h*h,t[2*a]+=4*h*(o-l),t[2*a+1]+=4*h*(s-u),t[2*c]+=4*h*(l-o),t[2*c+1]+=4*h*(u-s))}}return i}function ae(e,t={}){let n=se(e,t),r=t.lossFunction||B;if(e.length>=8){let i=oe(e,t),a=r(i,e),o=r(n,e);a+1e-8e.map(e=>e/s));let c=(e,t)=>ie(e,t,a,o),l=null;for(let e=0;ee.sets.length===2);for(let t of e){let e=t.weight==null?1:t.weight,n=t.sets[0],a=t.sets[1];t.size+te>=Math.min(r[n].size,r[a].size)&&(e=0),i[n].push({set:a,size:t.size,weight:e}),i[a].push({set:n,size:t.size,weight:e})}let a=[];Object.keys(i).forEach(e=>{let t=0;for(let n=0;ne[t]));let i=r.weight==null?1:r.weight;n+=i*(t-r.size)*(t-r.size)}return n}function ce(e,t){let n=0;for(let r of t){if(r.sets.length===1)continue;let t;if(r.sets.length===2){let n=e[r.sets[0]],i=e[r.sets[1]];t=E(n.radius,i.radius,T(n,i))}else t=x(r.sets.map(t=>e[t]));let i=r.weight==null?1:r.weight,a=Math.log((t+1)/(r.size+1));n+=i*a*a}return n}function le(e,t,n){if(n==null?e.sort((e,t)=>t.radius-e.radius):e.sort(n),e.length>0){let t=e[0].x,n=e[0].y;for(let r of e)r.x-=t,r.y-=n}if(e.length===2&&T(e[0],e[1])1){let n=Math.atan2(e[1].x,e[1].y)-t,r=Math.cos(n),i=Math.sin(n);for(let t of e){let e=t.x,n=t.y;t.x=r*e-i*n,t.y=i*e+r*n}}if(e.length>2){let n=Math.atan2(e[2].x,e[2].y)-t;for(;n<0;)n+=2*Math.PI;for(;n>2*Math.PI;)n-=2*Math.PI;if(n>Math.PI){let t=e[1].y/(1e-10+e[1].x);for(let n of e){var r=(n.x+t*n.y)/(1+t*t);n.x=2*r-n.x,n.y=2*r*t-n.y}}}}function ue(e){e.forEach(e=>{e.parent=e});function t(e){return e.parent!==e&&(e.parent=t(e.parent)),e.parent}function n(e,n){let r=t(e);r.parent=t(n)}for(let t=0;t{delete e.parent}),Array.from(r.values())}function V(e){let t=t=>({max:e.reduce((e,n)=>Math.max(e,n[t]+n.radius),-1/0),min:e.reduce((e,n)=>Math.min(e,n[t]-n.radius),1/0)});return{xRange:t(`x`),yRange:t(`y`)}}function de(e,t,n){t??=Math.PI/2;let r=me(e).map(e=>Object.assign({},e)),i=ue(r);for(let e of i){le(e,t,n);let r=V(e);e.size=(r.xRange.max-r.xRange.min)*(r.yRange.max-r.yRange.min),e.bounds=r}i.sort((e,t)=>t.size-e.size),r=i[0];let a=r.bounds,o=(a.xRange.max-a.xRange.min)/50;function s(e,t,n){if(!e)return;let i=e.bounds,s,c;if(t)s=a.xRange.max-i.xRange.min+o;else{s=a.xRange.max-i.xRange.max;let e=(i.xRange.max-i.xRange.min)/2-(a.xRange.max-a.xRange.min)/2;e<0&&(s+=e)}if(n)c=a.yRange.max-i.yRange.min+o;else{c=a.yRange.max-i.yRange.max;let e=(i.yRange.max-i.yRange.min)/2-(a.yRange.max-a.yRange.min)/2;e<0&&(c+=e)}for(let t of e)t.x+=s,t.y+=c,r.push(t)}let c=1;for(;c({radius:u*e.radius,x:r+d+(e.x-o.min)*u,y:r+f+(e.y-s.min)*u,setid:e.setid})))}function pe(e){let t={};for(let n of e)t[n.setid]=n;return t}function me(e){return Object.keys(e).map(t=>Object.assign(e[t],{setid:t}))}function he(e={}){let t=!1,n=600,r=350,i=15,a=1e3,o=Math.PI/2,s=!0,c=null,l=!0,u=!0,d=null,f=null,p=!1,m=null,h=e&&e.symmetricalTextCentre?e.symmetricalTextCentre:!1,g={},_=e&&e.colourScheme?e.colourScheme:e&&e.colorScheme?e.colorScheme:[`#1f77b4`,`#ff7f0e`,`#2ca02c`,`#d62728`,`#9467bd`,`#8c564b`,`#e377c2`,`#7f7f7f`,`#bcbd22`,`#17becf`],v=0,y=function(e){if(e in g)return g[e];var t=g[e]=_[v];return v+=1,v>=_.length&&(v=0),t},b=ee,x=B;function S(g){let _=g.datum(),v=new Set;_.forEach(e=>{e.size==0&&e.sets.length==1&&v.add(e.sets[0])}),_=_.filter(e=>!e.sets.some(e=>v.has(e)));let S={},C={};if(_.length>0){let e=b(_,{lossFunction:x,distinct:p});s&&(e=de(e,o,f)),S=fe(e,n,r,i,c),C=ve(S,_,h)}let w={};_.forEach(e=>{e.label&&(w[e.sets]=e.label)});function T(e){if(e.sets in w)return w[e.sets];if(e.sets.length==1)return``+e.sets[0]}g.selectAll(`svg`).data([S]).enter().append(`svg`);let E=g.select(`svg`);t?E.attr(`viewBox`,`0 0 ${n} ${r}`):E.attr(`width`,n).attr(`height`,r);let D={},O=!1;E.selectAll(`.venn-area path`).each(function(e){let t=this.getAttribute(`d`);e.sets.length==1&&t&&!p&&(O=!0,D[e.sets[0]]=be(t))});function k(e){return t=>Ce(e.sets.map(e=>{let i=D[e],a=S[e];return i||={x:n/2,y:r/2,radius:1},a||={x:n/2,y:r/2,radius:1},{x:i.x*(1-t)+a.x*t,y:i.y*(1-t)+a.y*t,radius:i.radius*(1-t)+a.radius*t}}),m)}let A=E.selectAll(`.venn-area`).data(_,e=>e.sets),j=A.enter().append(`g`).attr(`class`,e=>`venn-area venn-${e.sets.length==1?`circle`:`intersection`}${e.colour||e.color?` venn-coloured`:``}`).attr(`data-venn-sets`,e=>e.sets.join(`_`)),M=j.append(`path`),N=j.append(`text`).attr(`class`,`label`).text(e=>T(e)).attr(`text-anchor`,`middle`).attr(`dy`,`.35em`).attr(`x`,n/2).attr(`y`,r/2);u&&(M.style(`fill-opacity`,`0`).filter(e=>e.sets.length==1).style(`fill`,e=>e.colour?e.colour:e.color?e.color:y(e.sets)).style(`fill-opacity`,`.25`),N.style(`fill`,t=>t.colour||t.color?`#FFF`:e.textFill?e.textFill:t.sets.length==1?y(t.sets):`#444`));function P(e){return typeof e.transition==`function`?e.transition(`venn`).duration(a):e}let F=g;O&&typeof F.transition==`function`?(F=P(g),F.selectAll(`path`).attrTween(`d`,k)):F.selectAll(`path`).attr(`d`,e=>Ce(e.sets.map(e=>S[e])),m);let I=F.selectAll(`text`).filter(e=>e.sets in C).text(e=>T(e)).attr(`x`,e=>Math.floor(C[e.sets].x)).attr(`y`,e=>Math.floor(C[e.sets].y));l&&(O?`on`in I?I.on(`end`,H(S,T)):I.each(`end`,H(S,T)):I.each(H(S,T)));let L=P(A.exit()).remove();typeof A.transition==`function`&&L.selectAll(`path`).attrTween(`d`,k);let R=L.selectAll(`text`).attr(`x`,n/2).attr(`y`,r/2);return d!==null&&(N.style(`font-size`,`0px`),I.style(`font-size`,d),R.style(`font-size`,`0px`)),{circles:S,textCentres:C,nodes:A,enter:j,update:F,exit:L}}return S.wrap=function(e){return arguments.length?(l=e,S):l},S.useViewBox=function(){return t=!0,S},S.width=function(e){return arguments.length?(n=e,S):n},S.height=function(e){return arguments.length?(r=e,S):r},S.padding=function(e){return arguments.length?(i=e,S):i},S.distinct=function(e){return arguments.length?(p=e,S):p},S.colours=function(e){return arguments.length?(y=e,S):y},S.colors=function(e){return arguments.length?(y=e,S):y},S.fontSize=function(e){return arguments.length?(d=e,S):d},S.round=function(e){return arguments.length?(m=e,S):m},S.duration=function(e){return arguments.length?(a=e,S):a},S.layoutFunction=function(e){return arguments.length?(b=e,S):b},S.normalize=function(e){return arguments.length?(s=e,S):s},S.scaleToFit=function(e){return arguments.length?(c=e,S):c},S.styled=function(e){return arguments.length?(u=e,S):u},S.orientation=function(e){return arguments.length?(o=e,S):o},S.orientationOrder=function(e){return arguments.length?(f=e,S):f},S.lossFunction=function(e){return arguments.length?(x=e==="default"?B:e===`logRatio`?ce:e,S):x},S}function H(e,t){return function(n){let r=this,i=e[n.sets[0]].radius||50,a=t(n)||``,o=a.split(/\s+/).reverse(),s=(a.length+o.length)/3,c=o.pop(),l=[c],u=0,d=1.1;r.textContent=null;let f=[];function p(e){let t=r.ownerDocument.createElementNS(r.namespaceURI,`tspan`);return t.textContent=e,f.push(t),r.append(t),t}let m=p(c);for(;c=o.pop(),c;){l.push(c);let e=l.join(` `);m.textContent=e,e.length>s&&m.getComputedTextLength()>i&&(l.pop(),m.textContent=l.join(` `),l=[c],m=p(c),u++)}let h=.35-u*d/2,g=r.getAttribute(`x`),_=r.getAttribute(`y`);f.forEach((e,t)=>{e.setAttribute(`x`,g),e.setAttribute(`y`,_),e.setAttribute(`dy`,`${h+t*d}em`)})}}function U(e,t,n){let r=t[0].radius-T(t[0],e);for(let n=1;n=a&&(i=r[n],a=o)}let o=I(n=>-1*U({x:n[0],y:n[1]},e,t),[i.x,i.y],{maxIterations:500,minErrorDelta:1e-10}).x,s={x:n?0:o[0],y:o[1]},c=!0;for(let t of e)if(T(s,t)>t.radius){c=!1;break}for(let e of t)if(T(s,e)e.p1))}function _e(e){let t={},n=Object.keys(e);for(let e of n)t[e]=[];for(let r=0;r0&&console.log(`WARNING: area `+o+` not represented on screen`)}return r}function ye(e,t,n){let r=[];return r.push(` +M`,e,t),r.push(` +m`,-n,0),r.push(` +a`,n,n,0,1,0,n*2,0),r.push(` +a`,n,n,0,1,0,-n*2,0),r.join(` `)}function be(e){let t=e.split(` `);return{x:Number.parseFloat(t[1]),y:Number.parseFloat(t[2]),radius:-Number.parseFloat(t[4])}}function xe(e){if(e.length===0)return[];let t={};return x(e,t),t.arcs}function Se(e,t){if(e.length===0)return`M 0 0`;let n=10**(t||0),r=t==null?e=>e:e=>Math.round(e*n)/n;if(e.length==1){let t=e[0].circle;return ye(r(t.x),r(t.y),r(t.radius))}let i=[` +M`,r(e[0].p2.x),r(e[0].p2.y)];for(let t of e){let e=r(t.circle.radius);i.push(` +A`,e,e,0,+!!t.large,+!!t.sweep,r(t.p1.x),r(t.p1.y))}return i.join(` `)}function Ce(e,t){return Se(xe(e),t)}function we(e,t={}){let{lossFunction:n,layoutFunction:r=ee,normalize:i=!0,orientation:a=Math.PI/2,orientationOrder:o,width:s=600,height:c=350,padding:l=15,scaleToFit:u=!1,symmetricalTextCentre:d=!1,distinct:f,round:p=2}=t,m=r(e,{lossFunction:n==="default"||!n?B:n===`logRatio`?ce:n,distinct:f});i&&(m=de(m,a,o));let h=fe(m,s,c,l,u),g=ve(h,e,d),_=new Map(Object.keys(h).map(e=>[e,{set:e,x:h[e].x,y:h[e].y,radius:h[e].radius}])),v=e.map(e=>{let t=e.sets.map(e=>_.get(e)),n=xe(t);return{circles:t,arcs:n,path:Se(n,p),area:e,has:new Set(e.sets)}});function y(e){let t=``;for(let n of v)n.has.size>e.length&&e.every(e=>n.has.has(e))&&(t+=` `+n.path);return t}return v.map(({circles:e,arcs:t,path:n,area:r})=>({data:r,text:g[r.sets],circles:e,arcs:t,path:n,distinctPath:n+y(r.sets)}))}var W=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[5,8],r=[7,8,11,12,17,19,22,24],i=[1,17],a=[1,18],o=[7,8,11,12,14,15,16,17,19,20,21,22,24,27],s=[1,31],c=[1,39],l=[7,8,11,12,17,19,22,24,27],u=[1,57],d=[1,56],f=[1,58],p=[1,59],m=[1,60],h=[7,8,11,12,16,17,19,20,22,24,27,31,32,33],g={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,optNewlines:4,VENN:5,document:6,EOF:7,NEWLINE:8,line:9,statement:10,TITLE:11,SET:12,identifier:13,BRACKET_LABEL:14,COLON:15,NUMERIC:16,UNION:17,identifierList:18,TEXT:19,IDENTIFIER:20,STRING:21,INDENT_TEXT:22,indentedTextTail:23,STYLE:24,stylesOpt:25,styleField:26,COMMA:27,styleValue:28,valueTokens:29,valueToken:30,HEXCOLOR:31,RGBCOLOR:32,RGBACOLOR:33,$accept:0,$end:1},terminals_:{2:`error`,5:`VENN`,7:`EOF`,8:`NEWLINE`,11:`TITLE`,12:`SET`,14:`BRACKET_LABEL`,15:`COLON`,16:`NUMERIC`,17:`UNION`,19:`TEXT`,20:`IDENTIFIER`,21:`STRING`,22:`INDENT_TEXT`,24:`STYLE`,27:`COMMA`,31:`HEXCOLOR`,32:`RGBCOLOR`,33:`RGBACOLOR`},productions_:[0,[3,4],[4,0],[4,2],[6,0],[6,2],[9,1],[9,1],[10,1],[10,2],[10,3],[10,4],[10,5],[10,2],[10,3],[10,4],[10,5],[10,3],[10,3],[10,3],[10,4],[10,4],[10,2],[10,3],[23,1],[23,1],[23,1],[23,2],[23,2],[25,1],[25,3],[26,3],[28,1],[28,1],[29,1],[29,2],[30,1],[30,1],[30,1],[30,1],[30,1],[18,1],[18,3],[13,1],[13,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 2:case 3:case 4:this.$=[];break;case 5:a[s-1].push(a[s]),this.$=a[s-1];break;case 6:this.$=[];break;case 7:case 22:case 32:case 36:case 37:case 38:case 39:case 40:this.$=a[s];break;case 8:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 9:r.addSubsetData([a[s]],void 0,void 0),r.setIndentMode&&r.setIndentMode(!0);break;case 10:r.addSubsetData([a[s-1]],a[s],void 0),r.setIndentMode&&r.setIndentMode(!0);break;case 11:r.addSubsetData([a[s-2]],void 0,parseFloat(a[s])),r.setIndentMode&&r.setIndentMode(!0);break;case 12:r.addSubsetData([a[s-3]],a[s-2],parseFloat(a[s])),r.setIndentMode&&r.setIndentMode(!0);break;case 13:if(a[s].length<2)throw Error(`union requires multiple identifiers`);r.validateUnionIdentifiers&&r.validateUnionIdentifiers(a[s]),r.addSubsetData(a[s],void 0,void 0),r.setIndentMode&&r.setIndentMode(!0);break;case 14:if(a[s-1].length<2)throw Error(`union requires multiple identifiers`);r.validateUnionIdentifiers&&r.validateUnionIdentifiers(a[s-1]),r.addSubsetData(a[s-1],a[s],void 0),r.setIndentMode&&r.setIndentMode(!0);break;case 15:if(a[s-2].length<2)throw Error(`union requires multiple identifiers`);r.validateUnionIdentifiers&&r.validateUnionIdentifiers(a[s-2]),r.addSubsetData(a[s-2],void 0,parseFloat(a[s])),r.setIndentMode&&r.setIndentMode(!0);break;case 16:if(a[s-3].length<2)throw Error(`union requires multiple identifiers`);r.validateUnionIdentifiers&&r.validateUnionIdentifiers(a[s-3]),r.addSubsetData(a[s-3],a[s-2],parseFloat(a[s])),r.setIndentMode&&r.setIndentMode(!0);break;case 17:case 18:case 19:r.addTextData(a[s-1],a[s],void 0);break;case 20:case 21:r.addTextData(a[s-2],a[s-1],a[s]);break;case 23:r.addStyleData(a[s-1],a[s]);break;case 24:case 25:case 26:var c=r.getCurrentSets();if(!c)throw Error(`text requires set`);r.addTextData(c,a[s],void 0);break;case 27:case 28:var c=r.getCurrentSets();if(!c)throw Error(`text requires set`);r.addTextData(c,a[s-1],a[s]);break;case 29:case 41:this.$=[a[s]];break;case 30:case 42:this.$=[...a[s-2],a[s]];break;case 31:this.$=[a[s-2],a[s]];break;case 33:this.$=a[s].join(` `);break;case 34:this.$=[a[s]];break;case 35:a[s-1].push(a[s]),this.$=a[s-1];break;case 43:case 44:this.$=a[s];break}},`anonymous`),table:[t(n,[2,2],{3:1,4:2}),{1:[3]},{5:[1,3],8:[1,4]},t(r,[2,4],{6:5}),t(n,[2,3]),{7:[1,6],8:[1,8],9:7,10:9,11:[1,10],12:[1,11],17:[1,12],19:[1,13],22:[1,14],24:[1,15]},{1:[2,1]},t(r,[2,5]),t(r,[2,6]),t(r,[2,7]),t(r,[2,8]),{13:16,20:i,21:a},{13:20,18:19,20:i,21:a},{13:20,18:21,20:i,21:a},{16:[1,25],20:[1,23],21:[1,24],23:22},{13:20,18:26,20:i,21:a},t(r,[2,9],{14:[1,27],15:[1,28]}),t(o,[2,43]),t(o,[2,44]),t(r,[2,13],{14:[1,29],15:[1,30],27:s}),t(o,[2,41]),{16:[1,34],20:[1,32],21:[1,33],27:s},t(r,[2,22]),t(r,[2,24],{14:[1,35]}),t(r,[2,25],{14:[1,36]}),t(r,[2,26]),{20:c,25:37,26:38,27:s},t(r,[2,10],{15:[1,40]}),{16:[1,41]},t(r,[2,14],{15:[1,42]}),{16:[1,43]},{13:44,20:i,21:a},t(r,[2,17],{14:[1,45]}),t(r,[2,18],{14:[1,46]}),t(r,[2,19]),t(r,[2,27]),t(r,[2,28]),t(r,[2,23],{27:[1,47]}),t(l,[2,29]),{15:[1,48]},{16:[1,49]},t(r,[2,11]),{16:[1,50]},t(r,[2,15]),t(o,[2,42]),t(r,[2,20]),t(r,[2,21]),{20:c,26:51},{16:u,20:d,21:[1,53],28:52,29:54,30:55,31:f,32:p,33:m},t(r,[2,12]),t(r,[2,16]),t(l,[2,30]),t(l,[2,31]),t(l,[2,32]),t(l,[2,33],{30:61,16:u,20:d,31:f,32:p,33:m}),t(h,[2,34]),t(h,[2,36]),t(h,[2,37]),t(h,[2,38]),t(h,[2,39]),t(h,[2,40]),t(h,[2,35])],defaultActions:{6:[2,1]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};g.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:break;case 1:break;case 2:break;case 3:if(e.getIndentMode&&e.getIndentMode())return e.consumeIndentText=!0,this.begin(`INITIAL`),22;break;case 4:break;case 5:e.setIndentMode&&e.setIndentMode(!1),this.begin(`INITIAL`),this.unput(t.yytext);break;case 6:return this.begin(`bol`),8;case 7:break;case 8:break;case 9:return 7;case 10:return 11;case 11:return 5;case 12:return 12;case 13:return 17;case 14:if(e.consumeIndentText)e.consumeIndentText=!1;else return 19;break;case 15:return 24;case 16:return t.yytext=t.yytext.slice(2,-2),14;case 17:return t.yytext=t.yytext.slice(1,-1).trim(),14;case 18:return 16;case 19:return 31;case 20:return 33;case 21:return 32;case 22:return 20;case 23:return 21;case 24:return 27;case 25:return 15}},`anonymous`),rules:[/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[ \t]+(?=[\n\r]))/i,/^(?:[ \t]+(?=text\b))/i,/^(?:[ \t]+)/i,/^(?:[^ \t\n\r])/i,/^(?:[\n\r]+)/i,/^(?:%%[^\n]*)/i,/^(?:[ \t]+)/i,/^(?:$)/i,/^(?:title\s[^#\n;]+)/i,/^(?:venn-beta\b)/i,/^(?:set\b)/i,/^(?:union\b)/i,/^(?:text\b)/i,/^(?:style\b)/i,/^(?:\["[^\"]*"\])/i,/^(?:\[[^\]\"]+\])/i,/^(?:[+-]?(\d+(\.\d+)?|\.\d+))/i,/^(?:#[0-9a-fA-F]{3,8})/i,/^(?:rgba\(\s*[0-9.]+\s*[,]\s*[0-9.]+\s*[,]\s*[0-9.]+\s*[,]\s*[0-9.]+\s*\))/i,/^(?:rgb\(\s*[0-9.]+\s*[,]\s*[0-9.]+\s*[,]\s*[0-9.]+\s*\))/i,/^(?:[A-Za-z_][A-Za-z0-9\-_]*)/i,/^(?:"[^\"]*")/i,/^(?:,)/i,/^(?::)/i],conditions:{bol:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25],inclusive:!0},INITIAL:{rules:[0,1,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25],inclusive:!0}}}})();function _(){this.yy={}}return e(_,`Parser`),_.prototype=g,g.Parser=_,new _})();W.parser=W;var Te=W,G=[],K=[],q=[],J=new Set,Y,X=!1,Ee=e((e,t,n)=>{let r=Q(e).sort(),i=n??10/e.length**2;Y=r,r.length===1&&J.add(r[0]),G.push({sets:r,size:i,label:t?Z(t):void 0})},`addSubsetData`),De=e(()=>G,`getSubsetData`),Z=e(e=>{let t=e.trim();return t.length>=2&&t.startsWith(`"`)&&t.endsWith(`"`)?t.slice(1,-1):t},`normalizeText`),Oe=e(e=>e&&Z(e),`normalizeStyleValue`),ke=e((e,t,n)=>{let r=Z(t);K.push({sets:Q(e).sort(),id:r,label:n?Z(n):void 0})},`addTextData`),Ae=e((e,t)=>{let n=Q(e).sort(),r={};for(let[e,n]of t)r[e]=Oe(n)??n;q.push({targets:n,styles:r})},`addStyleData`),je=e(()=>q,`getStyleData`),Q=e(e=>e.map(e=>Z(e)),`normalizeIdentifierList`),Me=e(e=>{let t=Q(e).filter(e=>!J.has(e));if(t.length>0)throw Error(`unknown set identifier: ${t.join(`, `)}`)},`validateUnionIdentifiers`),Ne=e(()=>K,`getTextData`),Pe=e(()=>Y,`getCurrentSets`),Fe=e(()=>X,`getIndentMode`),Ie=e(e=>{X=e},`setIndentMode`),Le=l.venn;function Re(){return g(Le,o().venn)}e(Re,`getConfig`);var ze={getConfig:Re,clear:e(()=>{a(),G.length=0,K.length=0,q.length=0,J.clear(),Y=void 0,X=!1},`customClear`),setAccTitle:i,getAccTitle:h,setDiagramTitle:r,getDiagramTitle:m,getAccDescription:p,setAccDescription:n,addSubsetData:Ee,getSubsetData:De,addTextData:ke,addStyleData:Ae,validateUnionIdentifiers:Me,getTextData:Ne,getStyleData:je,getCurrentSets:Pe,getIndentMode:Fe,setIndentMode:Ie},Be=e(e=>` + .venn-title { + font-size: 32px; + fill: ${e.vennTitleTextColor}; + font-family: ${e.fontFamily}; + } + + .venn-circle text { + font-size: 48px; + font-family: ${e.fontFamily}; + } + + .venn-intersection text { + font-size: 48px; + fill: ${e.vennSetTextColor}; + font-family: ${e.fontFamily}; + } + + .venn-text-node { + font-family: ${e.fontFamily}; + color: ${e.vennSetTextColor}; + } +`,`getStyles`);function Ve(e){let t=new Map;for(let n of e){let e=n.targets.join(`|`),r=t.get(e);r?Object.assign(r,n.styles):t.set(e,{...n.styles})}return t}e(Ve,`buildStyleByKey`);var He=e((e,n,r,i)=>{let a=i.db,l=a.getConfig?.(),{themeVariables:u,look:p,handDrawnSeed:m}=o(),h=p===`handDrawn`,g=[u.venn1,u.venn2,u.venn3,u.venn4,u.venn5,u.venn6,u.venn7,u.venn8].filter(Boolean),b=a.getDiagramTitle?.(),x=a.getSubsetData(),S=a.getTextData(),C=Ve(a.getStyleData()),w=We(x),T=l?.width??800,E=l?.height??450,D=T/1600,O=b?48*D:0,k=u.primaryTextColor??u.textColor,A=_(n);A.attr(`viewBox`,`0 0 ${T} ${E}`),b&&A.append(`text`).text(b).attr(`class`,`venn-title`).attr(`font-size`,`${32*D}px`).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).attr(`x`,`50%`).attr(`y`,32*D).style(`fill`,u.vennTitleTextColor||u.titleColor);let j=t(document.createElement(`div`)),M=he().width(T).height(E-O);j.datum(w).call(M);let N=h?v.svg(j.select(`svg`).node()):void 0,P=we(w,{width:T,height:E-O,padding:l?.padding??15}),F=new Map;for(let e of P){let t=$([...e.data.sets].sort());F.set(t,e)}S.length>0&&Ue(l,F,j,S,D,C);let I=d(u.background||`#f4f4f4`);j.selectAll(`.venn-circle`).each(function(e,n){let r=t(this),i=$([...e.sets].sort()),a=C.get(i),o=a?.fill||g[n%g.length]||u.primaryColor;r.classed(`venn-set-${n%8}`,!0);let s=a?.[`fill-opacity`]??.1,l=a?.stroke||o,d=a?.[`stroke-width`]||`${5*D}`;if(h&&N){let e=F.get(i);if(e&&e.circles.length>0){let t=e.circles[0],i=N.circle(t.x,t.y,t.radius*2,{roughness:.7,seed:m,fill:y(o,.7),fillStyle:`hachure`,fillWeight:2,hachureGap:8,hachureAngle:-41+n*60,stroke:l,strokeWidth:parseFloat(String(d))});r.select(`path`).remove(),r.node()?.insertBefore(i,r.select(`text`).node())}}else r.select(`path`).style(`fill`,o).style(`fill-opacity`,s).style(`stroke`,l).style(`stroke-width`,d).style(`stroke-opacity`,.95);let p=a?.color||(I?f(o,30):c(o,30));r.select(`text`).style(`font-size`,`${48*D}px`).style(`fill`,p)}),h&&N?j.selectAll(`.venn-intersection`).each(function(e){let n=t(this),r=$([...e.sets].sort()),i=C.get(r),a=i?.fill;if(a){let e=n.select(`path`),t=e.attr(`d`);if(t){let n=N.path(t,{roughness:.7,seed:m,fill:y(a,.3),fillStyle:`cross-hatch`,fillWeight:2,hachureGap:6,hachureAngle:60,stroke:`none`}),r=e.node();r?.parentNode?.insertBefore(n,r),e.remove()}}else n.select(`path`).style(`fill-opacity`,0);n.select(`text`).style(`font-size`,`${48*D}px`).style(`fill`,i?.color??u.vennSetTextColor??k)}):(j.selectAll(`.venn-intersection text`).style(`font-size`,`${48*D}px`).style(`fill`,e=>{let t=$([...e.sets].sort());return C.get(t)?.color??u.vennSetTextColor??k}),j.selectAll(`.venn-intersection path`).style(`fill-opacity`,e=>{let t=$([...e.sets].sort());return+!!C.get(t)?.fill}).style(`fill`,e=>{let t=$([...e.sets].sort());return C.get(t)?.fill??`transparent`}));let L=A.append(`g`).attr(`transform`,`translate(0, ${O})`),R=j.select(`svg`).node();if(R&&`childNodes`in R)for(let e of[...R.childNodes])L.node()?.appendChild(e);s(A,E,T,l?.useMaxWidth??!0)},`draw`);function $(e){return e.join(`|`)}e($,`stableSetsKey`);function Ue(e,t,n,r,i,a){let o=e?.useDebugLayout??!1,s=n.select(`svg`).append(`g`).attr(`class`,`venn-text-nodes`),c=new Map;for(let e of r){let t=$(e.sets),n=c.get(t);n?n.push(e):c.set(t,[e])}for(let[e,n]of c.entries()){let r=t.get(e);if(!r?.text)continue;let c=r.text.x,l=r.text.y,u=Math.min(...r.circles.map(e=>e.radius)),d=Math.min(...r.circles.map(e=>e.radius-Math.hypot(c-e.x,l-e.y))),f=Number.isFinite(d)?Math.max(0,d):0;f===0&&Number.isFinite(u)&&(f=u*.6);let p=s.append(`g`).attr(`class`,`venn-text-area`).attr(`font-size`,`${40*i}px`);o&&p.append(`circle`).attr(`class`,`venn-text-debug-circle`).attr(`cx`,c).attr(`cy`,l).attr(`r`,f).attr(`fill`,`none`).attr(`stroke`,`purple`).attr(`stroke-width`,1.5*i).attr(`stroke-dasharray`,`${6*i} ${4*i}`);let m=Math.max(80*i,f*2*.95),h=Math.max(60*i,f*2*.95),g=(r.data.label&&r.data.label.length>0?Math.min(32*i,f*.25):0)+(n.length<=2?30*i:0),_=c-m/2,v=l-h/2+g,y=Math.max(1,Math.ceil(Math.sqrt(n.length))),b=Math.max(1,Math.ceil(n.length/y)),x=m/y,S=h/b;for(let[e,t]of n.entries()){let n=e%y,r=Math.floor(e/y),s=_+x*(n+.5),c=v+S*(r+.5);o&&p.append(`rect`).attr(`class`,`venn-text-debug-cell`).attr(`x`,_+x*n).attr(`y`,v+S*r).attr(`width`,x).attr(`height`,S).attr(`fill`,`none`).attr(`stroke`,`teal`).attr(`stroke-width`,1*i).attr(`stroke-dasharray`,`${4*i} ${3*i}`);let l=x*.9,u=S*.9,d=p.append(`foreignObject`).attr(`class`,`venn-text-node-fo`).attr(`width`,l).attr(`height`,u).attr(`x`,s-l/2).attr(`y`,c-u/2).attr(`overflow`,`visible`),f=a.get(t.id)?.color,m=d.append(`xhtml:span`).attr(`class`,`venn-text-node`).style(`display`,`flex`).style(`width`,`100%`).style(`height`,`100%`).style(`white-space`,`normal`).style(`align-items`,`center`).style(`justify-content`,`center`).style(`text-align`,`center`).style(`overflow-wrap`,`normal`).style(`word-break`,`normal`).text(t.label??t.id);f&&m.style(`color`,f)}}}e(Ue,`renderTextNodes`);function We(e){let t=new Set(e.map(e=>[...e.sets].sort().join(`|`))),n=new Map(e.filter(e=>e.sets.length===1&&e.size!==void 0).map(e=>[e.sets[0],e.size])),r=[];for(let i of e){if(i.sets.length<3)continue;let e=[...i.sets].sort();for(let i=0;i0?[...e,...r]:e}e(We,`ensurePairwiseSubsets`);var Ge={parser:Te,db:ze,renderer:{draw:He},styles:Be};export{Ge as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/wardley-OPB4EBWU-BjXxCRf_.js b/dist-desktop/assets/wardley-OPB4EBWU-BjXxCRf_.js new file mode 100644 index 0000000..fd69e7b --- /dev/null +++ b/dist-desktop/assets/wardley-OPB4EBWU-BjXxCRf_.js @@ -0,0 +1 @@ +import"./chunk-KEIR6QF5-Dj-OpFgW.js";import{n as e}from"./chunk-5FCAYU7R-DNtJmW0j.js";export{e as createWardleyServices}; \ No newline at end of file diff --git a/dist-desktop/assets/wardleyDiagram-EHGQE667-BewauNW1.js b/dist-desktop/assets/wardleyDiagram-EHGQE667-BewauNW1.js new file mode 100644 index 0000000..eddd590 --- /dev/null +++ b/dist-desktop/assets/wardleyDiagram-EHGQE667-BewauNW1.js @@ -0,0 +1,78 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{i as p}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as m}from"./chunk-VAUOI2AC-AC9pRUsa.js";import{t as h}from"./chunk-JWPE2WC7-DVXcaiue.js";import{n as g}from"./mermaid-parser.core-Z7xZAZRH.js";var _=e((e,t)=>{let n=e<=1?e*100:e;if(n<0||n>100)throw Error(`${t} must be between 0-1 (decimal) or 0-100 (percentage). Received: ${e}`);return n},`toPercent`),v=e((e,t,n)=>({x:_(t,`${n} evolution`),y:_(e,`${n} visibility`)}),`toCoordinates`),y=e(e=>{if(e){if(e===`+<>`)return`bidirectional`;if(e===`+<`)return`backward`;if(e===`+>`)return`forward`}},`getFlowFromPort`),b=e(e=>{if(!e?.startsWith(`+`))return{};let t=/^\+'([^']*)'/.exec(e)?.[1];return e.includes(`<>`)?{flow:`bidirectional`,label:t}:e.includes(`<`)?{flow:`backward`,label:t}:e.includes(`>`)?{flow:`forward`,label:t}:{label:t}},`extractFlowFromArrow`),x=e((e,t)=>{if(h(e,t),e.size&&t.setSize(e.size.width,e.size.height),e.evolution){let n=e.evolution.stages.map(e=>e.secondName?`${e.name.trim()} / ${e.secondName.trim()}`:e.name.trim()),r=e.evolution.stages.filter(e=>e.boundary!==void 0).map(e=>e.boundary);t.updateAxes({stages:n,stageBoundaries:r})}if(e.anchors.forEach(e=>{let n=v(e.visibility,e.evolution,`Anchor "${e.name}"`);t.addNode(e.name,e.name,n.x,n.y,`anchor`)}),e.components.forEach(e=>{let n=v(e.visibility,e.evolution,`Component "${e.name}"`),r=e.label?(e.label.negX?-1:1)*e.label.offsetX:void 0,i=e.label?(e.label.negY?-1:1)*e.label.offsetY:void 0,a=e.decorator?.strategy;t.addNode(e.name,e.name,n.x,n.y,`component`,r,i,e.inertia,a)}),e.notes.forEach(e=>{let n=v(e.visibility,e.evolution,`Note "${e.text}"`);t.addNote(e.text,n.x,n.y)}),e.pipelines.forEach(e=>{let n=t.getNode(e.parent);if(!n||typeof n.y!=`number`)throw Error(`Pipeline "${e.parent}" must reference an existing component with coordinates.`);let r=n.y;t.startPipeline(e.parent),e.components.forEach(n=>{let i=`${e.parent}_${n.name}`,a=n.label?(n.label.negX?-1:1)*n.label.offsetX:void 0,o=n.label?(n.label.negY?-1:1)*n.label.offsetY:void 0,s=_(n.evolution,`Pipeline component "${n.name}" evolution`);t.addNode(i,n.name,s,r,`pipeline-component`,a,o),t.addPipelineComponent(e.parent,i)})}),e.links.forEach(e=>{let n=!!e.arrow&&(e.arrow.includes(`-.->`)||e.arrow.includes(`.-.`)),r=y(e.fromPort)??y(e.toPort),{flow:i,label:a}=b(e.arrow);!r&&i&&(r=i);let o=e.linkLabel,s=a??o;t.addLink(t.resolveNodeId(e.from),t.resolveNodeId(e.to),n,s,r)}),e.evolves.forEach(e=>{let n=t.getNode(e.component);if(n?.y!==void 0){let r=_(e.target,`Evolve target for "${e.component}"`);t.addTrend(e.component,r,n.y)}}),e.annotations.length>0){let n=e.annotations[0],r=v(n.x,n.y,`Annotations box`);t.setAnnotationsBox(r.x,r.y)}e.annotation.forEach(e=>{let n=v(e.x,e.y,`Annotation ${e.number}`);t.addAnnotation(e.number,[{x:n.x,y:n.y}],e.text)}),e.accelerators.forEach(e=>{let n=v(e.x,e.y,`Accelerator "${e.name}"`);t.addAccelerator(e.name,n.x,n.y)}),e.deaccelerators.forEach(e=>{let n=v(e.x,e.y,`Deaccelerator "${e.name}"`);t.addDeaccelerator(e.name,n.x,n.y)})},`populateDb`),S={parser:{yy:void 0},parse:e(async e=>{let n=await g(`wardley`,e);t.debug(n);let r=S.parser?.yy;if(!r||typeof r.addNode!=`function`)throw Error(`parser.parser?.yy was not a WardleyDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.`);x(n,r)},`parse`)},C=new class{constructor(){this.nodes=new Map,this.links=[],this.trends=new Map,this.pipelines=new Map,this.annotations=[],this.notes=[],this.accelerators=[],this.deaccelerators=[],this.axes={}}static{e(this,`WardleyBuilder`)}addNode(e){let t=this.nodes.get(e.id)??{id:e.id,label:e.label},n={...t,...e,className:e.className??t.className,labelOffsetX:e.labelOffsetX??t.labelOffsetX,labelOffsetY:e.labelOffsetY??t.labelOffsetY};this.nodes.set(e.id,n)}addLink(e){this.links.push(e)}addTrend(e){this.trends.set(e.nodeId,e)}startPipeline(e){this.pipelines.set(e,{nodeId:e,componentIds:[]});let t=this.nodes.get(e);t&&(t.isPipelineParent=!0)}addPipelineComponent(e,t){let n=this.pipelines.get(e);n&&n.componentIds.push(t);let r=this.nodes.get(t);r&&(r.inPipeline=!0)}addAnnotation(e){this.annotations.push(e)}addNote(e){this.notes.push(e)}addAccelerator(e){this.accelerators.push(e)}addDeaccelerator(e){this.deaccelerators.push(e)}setAnnotationsBox(e,t){this.annotationsBox={x:e,y:t}}setAxes(e){this.axes={...this.axes,...e}}setSize(e,t){this.size={width:e,height:t}}getNode(e){return this.nodes.get(e)}resolveNodeId(e){if(this.nodes.has(e))return e;for(let[t,n]of this.nodes)if(n.label===e)return t;return e}build(){let e=[];for(let t of this.nodes.values()){if(typeof t.x!=`number`||typeof t.y!=`number`)throw Error(`Node "${t.label}" is missing coordinates`);e.push(t)}return{nodes:e,links:[...this.links],trends:[...this.trends.values()],pipelines:[...this.pipelines.values()],annotations:[...this.annotations],notes:[...this.notes],accelerators:[...this.accelerators],deaccelerators:[...this.deaccelerators],annotationsBox:this.annotationsBox,axes:{...this.axes},size:this.size}}clear(){this.nodes.clear(),this.links=[],this.trends.clear(),this.pipelines.clear(),this.annotations=[],this.notes=[],this.accelerators=[],this.deaccelerators=[],this.annotationsBox=void 0,this.axes={},this.size=void 0}};function w(){return d()[`wardley-beta`]}e(w,`getConfig`);function T(e,t,n,r,i,a,o,s,c){C.addNode({id:e,label:t,x:n,y:r,className:i,labelOffsetX:a,labelOffsetY:o,inertia:s,sourceStrategy:c})}e(T,`addNode`);function E(e,t,n=!1,r,i){C.addLink({source:e,target:t,dashed:n,label:r,flow:i})}e(E,`addLink`);function D(e,t,n){C.addTrend({nodeId:e,targetX:t,targetY:n})}e(D,`addTrend`);function O(e,t,n){C.addAnnotation({number:e,coordinates:t,text:n})}e(O,`addAnnotation`);function k(e,t,n){C.addNote({text:e,x:t,y:n})}e(k,`addNote`);function A(e,t,n){C.addAccelerator({name:e,x:t,y:n})}e(A,`addAccelerator`);function j(e,t,n){C.addDeaccelerator({name:e,x:t,y:n})}e(j,`addDeaccelerator`);function M(e,t){C.setAnnotationsBox(e,t)}e(M,`setAnnotationsBox`);function N(e,t){C.setSize(e,t)}e(N,`setSize`);function P(e){C.startPipeline(e)}e(P,`startPipeline`);function F(e,t){C.addPipelineComponent(e,t)}e(F,`addPipelineComponent`);function I(e){C.setAxes(e)}e(I,`updateAxes`);function L(e){return C.getNode(e)}e(L,`getNode`);function R(e){return C.resolveNodeId(e)}e(R,`resolveNodeId`);function z(){return C.build()}e(z,`getWardleyData`);function B(){C.clear(),o()}e(B,`clear`);var V={getConfig:w,addNode:T,addLink:E,addTrend:D,addAnnotation:O,addNote:k,addAccelerator:A,addDeaccelerator:j,setAnnotationsBox:M,setSize:N,startPipeline:P,addPipelineComponent:F,updateAxes:I,getNode:L,resolveNodeId:R,getWardleyData:z,clear:B,setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:u,getAccDescription:l,setAccDescription:r},H=[`Genesis`,`Custom Built`,`Product`,`Commodity`],U=e(()=>{let{themeVariables:e}=d();return{backgroundColor:e.wardley?.backgroundColor??e.background??`#fff`,axisColor:e.wardley?.axisColor??`#000`,axisTextColor:e.wardley?.axisTextColor??e.primaryTextColor??`#222`,gridColor:e.wardley?.gridColor??`rgba(100, 100, 100, 0.2)`,componentFill:e.wardley?.componentFill??`#fff`,componentStroke:e.wardley?.componentStroke??`#000`,componentLabelColor:e.wardley?.componentLabelColor??e.primaryTextColor??`#222`,linkStroke:e.wardley?.linkStroke??`#000`,evolutionStroke:e.wardley?.evolutionStroke??`#dc3545`,annotationStroke:e.wardley?.annotationStroke??`#000`,annotationTextColor:e.wardley?.annotationTextColor??e.primaryTextColor??`#222`,annotationFill:e.wardley?.annotationFill??e.background??`#fff`}},`getTheme`),W=e(()=>{let e=d()[`wardley-beta`];return{width:e?.width??900,height:e?.height??600,padding:e?.padding??48,nodeRadius:e?.nodeRadius??6,nodeLabelOffset:e?.nodeLabelOffset??8,axisFontSize:e?.axisFontSize??12,labelFontSize:e?.labelFontSize??10,showGrid:e?.showGrid??!1,useMaxWidth:e?.useMaxWidth??!0}},`getConfigValues`),G={parser:S,db:V,renderer:{draw:e((n,r,i,a)=>{t.debug(`Rendering Wardley map +`+n);let o=W(),s=U(),l=o.nodeRadius*1.6,u=a.db,d=u.getWardleyData(),f=u.getDiagramTitle(),p=d.size?.width??o.width,h=d.size?.height??o.height,g=m(r);g.selectAll(`*`).remove(),c(g,h,p,o.useMaxWidth),g.attr(`viewBox`,`0 0 ${p} ${h}`);let _=g.append(`g`).attr(`class`,`wardley-map`),v=g.append(`defs`);v.append(`marker`).attr(`id`,`arrow-${r}`).attr(`viewBox`,`0 0 10 10`).attr(`refX`,9).attr(`refY`,5).attr(`markerWidth`,6).attr(`markerHeight`,6).attr(`orient`,`auto-start-reverse`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`fill`,s.evolutionStroke).attr(`stroke`,`none`),v.append(`marker`).attr(`id`,`link-arrow-end-${r}`).attr(`viewBox`,`0 0 10 10`).attr(`refX`,9).attr(`refY`,5).attr(`markerWidth`,5).attr(`markerHeight`,5).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`fill`,s.linkStroke).attr(`stroke`,`none`),v.append(`marker`).attr(`id`,`link-arrow-start-${r}`).attr(`viewBox`,`0 0 10 10`).attr(`refX`,1).attr(`refY`,5).attr(`markerWidth`,5).attr(`markerHeight`,5).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 10 0 L 0 5 L 10 10 z`).attr(`fill`,s.linkStroke).attr(`stroke`,`none`),_.append(`rect`).attr(`class`,`wardley-background`).attr(`width`,p).attr(`height`,h).attr(`fill`,s.backgroundColor);let y=p-o.padding*2,b=h-o.padding*2;f&&_.append(`text`).attr(`class`,`wardley-title`).attr(`x`,p/2).attr(`y`,o.padding/2).attr(`fill`,s.axisTextColor).attr(`font-size`,o.axisFontSize*1.05).attr(`font-weight`,`bold`).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).text(f);let x=e(e=>o.padding+e/100*y,`projectX`),S=e(e=>h-o.padding-e/100*b,`projectY`),C=_.append(`g`).attr(`class`,`wardley-axes`);C.append(`line`).attr(`x1`,o.padding).attr(`x2`,p-o.padding).attr(`y1`,h-o.padding).attr(`y2`,h-o.padding).attr(`stroke`,s.axisColor).attr(`stroke-width`,1),C.append(`line`).attr(`x1`,o.padding).attr(`x2`,o.padding).attr(`y1`,o.padding).attr(`y2`,h-o.padding).attr(`stroke`,s.axisColor).attr(`stroke-width`,1);let w=d.axes.xLabel??`Evolution`,T=d.axes.yLabel??`Visibility`;C.append(`text`).attr(`class`,`wardley-axis-label wardley-axis-label-x`).attr(`x`,o.padding+y/2).attr(`y`,h-o.padding/4).attr(`fill`,s.axisTextColor).attr(`font-size`,o.axisFontSize).attr(`font-weight`,`bold`).attr(`text-anchor`,`middle`).text(w),C.append(`text`).attr(`class`,`wardley-axis-label wardley-axis-label-y`).attr(`x`,o.padding/3).attr(`y`,o.padding+b/2).attr(`fill`,s.axisTextColor).attr(`font-size`,o.axisFontSize).attr(`font-weight`,`bold`).attr(`text-anchor`,`middle`).attr(`transform`,`rotate(-90 ${o.padding/3} ${o.padding+b/2})`).text(T);let E=d.axes.stages&&d.axes.stages.length>0?d.axes.stages:H;if(E.length>0){let e=_.append(`g`).attr(`class`,`wardley-stages`),t=d.axes.stageBoundaries,n=[];if(t&&t.length===E.length){let e=0;t.forEach(t=>{n.push({start:e,end:t}),e=t})}else{let e=1/E.length;E.forEach((t,r)=>{n.push({start:r*e,end:(r+1)*e})})}E.forEach((t,r)=>{let i=n[r],a=o.padding+i.start*y,c=(a+(o.padding+i.end*y))/2;r>0&&e.append(`line`).attr(`x1`,a).attr(`x2`,a).attr(`y1`,o.padding).attr(`y2`,h-o.padding).attr(`stroke`,`#000`).attr(`stroke-width`,1).attr(`stroke-dasharray`,`5 5`).attr(`opacity`,.8),e.append(`text`).attr(`class`,`wardley-stage-label`).attr(`x`,c).attr(`y`,h-o.padding/1.5).attr(`fill`,s.axisTextColor).attr(`font-size`,o.axisFontSize-2).attr(`text-anchor`,`middle`).text(t)})}if(o.showGrid){let e=_.append(`g`).attr(`class`,`wardley-grid`);for(let t=1;t<4;t++){let n=t/4,r=o.padding+y*n;e.append(`line`).attr(`x1`,r).attr(`x2`,r).attr(`y1`,o.padding).attr(`y2`,h-o.padding).attr(`stroke`,s.gridColor).attr(`stroke-dasharray`,`2 6`),e.append(`line`).attr(`x1`,o.padding).attr(`x2`,p-o.padding).attr(`y1`,h-o.padding-b*n).attr(`y2`,h-o.padding-b*n).attr(`stroke`,s.gridColor).attr(`stroke-dasharray`,`2 6`)}}let D=new Map;if(d.nodes.forEach(e=>{D.set(e.id,{x:x(e.x),y:S(e.y),node:e})}),d.pipelines.length>0){let e=_.append(`g`).attr(`class`,`wardley-pipelines`),t=_.append(`g`).attr(`class`,`wardley-pipeline-links`);d.pipelines.forEach(n=>{if(n.componentIds.length===0)return;let r=n.componentIds.map(e=>({id:e,pos:D.get(e),node:d.nodes.find(t=>t.id===e)})).filter(e=>e.pos&&e.node).sort((e,t)=>e.node.x-t.node.x);for(let e=0;e{let t=D.get(e);t&&(i=Math.min(i,t.x),a=Math.max(a,t.x),c=t.y)}),i!==1/0&&a!==-1/0){let t=o.nodeRadius*4,r=c-t/2,u=D.get(n.nodeId);u&&(u.x=(i+a)/2,u.y=r-l/6),e.append(`rect`).attr(`class`,`wardley-pipeline-box`).attr(`x`,i-15).attr(`y`,r).attr(`width`,a-i+30).attr(`height`,t).attr(`fill`,`none`).attr(`stroke`,s.axisColor).attr(`stroke-width`,1.5).attr(`rx`,4).attr(`ry`,4)}})}let O=_.append(`g`).attr(`class`,`wardley-links`),k=new Map;d.pipelines.forEach(e=>{k.set(e.nodeId,new Set(e.componentIds))});let A=d.links.filter(e=>!(!D.has(e.source)||!D.has(e.target)||k.get(e.target)?.has(e.source)));O.selectAll(`line`).data(A).enter().append(`line`).attr(`class`,e=>`wardley-link${e.dashed?` wardley-link--dashed`:``}`).attr(`x1`,e=>{let t=D.get(e.source),n=D.get(e.target),r=d.nodes.find(t=>t.id===e.source).isPipelineParent?l/Math.sqrt(2):o.nodeRadius,i=n.x-t.x,a=n.y-t.y,s=Math.sqrt(i*i+a*a);return t.x+i/s*r}).attr(`y1`,e=>{let t=D.get(e.source),n=D.get(e.target),r=d.nodes.find(t=>t.id===e.source).isPipelineParent?l/Math.sqrt(2):o.nodeRadius,i=n.x-t.x,a=n.y-t.y,s=Math.sqrt(i*i+a*a);return t.y+a/s*r}).attr(`x2`,e=>{let t=D.get(e.source),n=D.get(e.target),r=d.nodes.find(t=>t.id===e.target).isPipelineParent?l/Math.sqrt(2):o.nodeRadius,i=t.x-n.x,a=t.y-n.y,s=Math.sqrt(i*i+a*a);return n.x+i/s*r}).attr(`y2`,e=>{let t=D.get(e.source),n=D.get(e.target),r=d.nodes.find(t=>t.id===e.target).isPipelineParent?l/Math.sqrt(2):o.nodeRadius,i=t.x-n.x,a=t.y-n.y,s=Math.sqrt(i*i+a*a);return n.y+a/s*r}).attr(`stroke`,s.linkStroke).attr(`stroke-width`,1).attr(`stroke-dasharray`,e=>e.dashed?`6 6`:null).attr(`marker-end`,e=>e.flow===`forward`||e.flow===`bidirectional`?`url(#link-arrow-end-${r})`:null).attr(`marker-start`,e=>e.flow===`backward`||e.flow===`bidirectional`?`url(#link-arrow-start-${r})`:null),O.selectAll(`text`).data(A.filter(e=>e.label)).enter().append(`text`).attr(`class`,`wardley-link-label`).attr(`x`,e=>{let t=D.get(e.source),n=D.get(e.target),r=(t.x+n.x)/2,i=n.y-t.y,a=n.x-t.x;return r+i/Math.sqrt(a*a+i*i)*8}).attr(`y`,e=>{let t=D.get(e.source),n=D.get(e.target),r=(t.y+n.y)/2,i=n.x-t.x,a=n.y-t.y,o=Math.sqrt(i*i+a*a);return r+-i/o*8}).attr(`fill`,s.axisTextColor).attr(`font-size`,o.labelFontSize).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`middle`).attr(`transform`,e=>{let t=D.get(e.source),n=D.get(e.target),r=(t.x+n.x)/2,i=(t.y+n.y)/2,a=n.x-t.x,o=n.y-t.y,s=Math.sqrt(a*a+o*o),c=o/s,l=-a/s,u=r+c*8,d=i+l*8,f=Math.atan2(o,a)*180/Math.PI;return(f>90||f<-90)&&(f+=180),`rotate(${f} ${u} ${d})`}).text(e=>e.label);let j=_.append(`g`).attr(`class`,`wardley-trends`),M=d.trends.map(e=>{let t=D.get(e.nodeId);if(!t)return null;let n=x(e.targetX),r=S(e.targetY),i=n-t.x,a=r-t.y,s=Math.sqrt(i*i+a*a),c=o.nodeRadius+2;return{origin:t,targetX:n,targetY:r,adjustedX2:s>c?n-i/s*c:n,adjustedY2:s>c?r-a/s*c:r}}).filter(e=>e!==null);j.selectAll(`line`).data(M).enter().append(`line`).attr(`class`,`wardley-trend`).attr(`x1`,e=>e.origin.x).attr(`y1`,e=>e.origin.y).attr(`x2`,e=>e.adjustedX2).attr(`y2`,e=>e.adjustedY2).attr(`stroke`,s.evolutionStroke).attr(`stroke-width`,1).attr(`stroke-dasharray`,`4 4`).attr(`marker-end`,`url(#arrow-${r})`);let N=_.append(`g`).attr(`class`,`wardley-nodes`).selectAll(`g`).data(d.nodes).enter().append(`g`).attr(`class`,e=>[`wardley-node`,e.className?`wardley-node--${e.className}`:``].filter(Boolean).join(` `));N.filter(e=>e.sourceStrategy===`outsource`).append(`circle`).attr(`class`,`wardley-outsource-overlay`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius*2).attr(`fill`,`#666`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),N.filter(e=>e.sourceStrategy===`buy`).append(`circle`).attr(`class`,`wardley-buy-overlay`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius*2).attr(`fill`,`#ccc`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),N.filter(e=>e.sourceStrategy===`build`).append(`circle`).attr(`class`,`wardley-build-overlay`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius*2).attr(`fill`,`#eee`).attr(`stroke`,`#000`).attr(`stroke-width`,1);let P=N.filter(e=>e.sourceStrategy===`market`);P.append(`circle`).attr(`class`,`wardley-market-overlay`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius*2).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),N.filter(e=>!e.isPipelineParent&&e.sourceStrategy!==`market`&&e.className!==`anchor`).append(`circle`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y).attr(`r`,o.nodeRadius).attr(`fill`,s.componentFill).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1);let F=o.nodeRadius*.7,I=o.nodeRadius*1.2;if(P.append(`line`).attr(`class`,`wardley-market-line`).attr(`x1`,e=>D.get(e.id).x).attr(`y1`,e=>D.get(e.id).y-I).attr(`x2`,e=>D.get(e.id).x-I*Math.cos(Math.PI/6)).attr(`y2`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),P.append(`line`).attr(`class`,`wardley-market-line`).attr(`x1`,e=>D.get(e.id).x-I*Math.cos(Math.PI/6)).attr(`y1`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`x2`,e=>D.get(e.id).x+I*Math.cos(Math.PI/6)).attr(`y2`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),P.append(`line`).attr(`class`,`wardley-market-line`).attr(`x1`,e=>D.get(e.id).x+I*Math.cos(Math.PI/6)).attr(`y1`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`x2`,e=>D.get(e.id).x).attr(`y2`,e=>D.get(e.id).y-I).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),P.append(`circle`).attr(`class`,`wardley-market-dot`).attr(`cx`,e=>D.get(e.id).x).attr(`cy`,e=>D.get(e.id).y-I).attr(`r`,F).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,2),P.append(`circle`).attr(`class`,`wardley-market-dot`).attr(`cx`,e=>D.get(e.id).x-I*Math.cos(Math.PI/6)).attr(`cy`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`r`,F).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,2),P.append(`circle`).attr(`class`,`wardley-market-dot`).attr(`cx`,e=>D.get(e.id).x+I*Math.cos(Math.PI/6)).attr(`cy`,e=>D.get(e.id).y+I*Math.sin(Math.PI/6)).attr(`r`,F).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,2),N.filter(e=>e.isPipelineParent===!0).append(`rect`).attr(`x`,e=>D.get(e.id).x-l/2).attr(`y`,e=>D.get(e.id).y-l/2).attr(`width`,l).attr(`height`,l).attr(`fill`,s.componentFill).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),N.filter(e=>e.inertia===!0).append(`line`).attr(`class`,`wardley-inertia`).attr(`x1`,e=>{let t=D.get(e.id),n=e.isPipelineParent?l/2+15:o.nodeRadius+15;return e.sourceStrategy&&(n+=o.nodeRadius+10),t.x+n}).attr(`y1`,e=>{let t=D.get(e.id),n=e.isPipelineParent?l:o.nodeRadius*2;return t.y-n/2}).attr(`x2`,e=>{let t=D.get(e.id),n=e.isPipelineParent?l/2+15:o.nodeRadius+15;return e.sourceStrategy&&(n+=o.nodeRadius+10),t.x+n}).attr(`y2`,e=>{let t=D.get(e.id),n=e.isPipelineParent?l:o.nodeRadius*2;return t.y+n/2}).attr(`stroke`,s.componentStroke).attr(`stroke-width`,6),N.append(`text`).attr(`x`,e=>{let t=D.get(e.id);if(e.className===`anchor`)return e.labelOffsetX===void 0?t.x:t.x+e.labelOffsetX;let n=o.nodeLabelOffset;e.sourceStrategy&&e.labelOffsetX===void 0&&(n+=10);let r=e.labelOffsetX??n;return t.x+r}).attr(`y`,e=>{let t=D.get(e.id);if(e.className===`anchor`)return e.labelOffsetY===void 0?t.y-3:t.y+e.labelOffsetY;let n=-o.nodeLabelOffset;e.sourceStrategy&&e.labelOffsetY===void 0&&(n-=10);let r=e.labelOffsetY??n;return t.y+r}).attr(`class`,`wardley-node-label`).attr(`fill`,e=>e.className===`evolved`?s.evolutionStroke:e.className===`anchor`?`#000`:s.componentLabelColor).attr(`font-size`,o.labelFontSize).attr(`font-weight`,e=>e.className===`anchor`?`bold`:`normal`).attr(`text-anchor`,e=>e.className===`anchor`?`middle`:`start`).attr(`dominant-baseline`,e=>e.className===`anchor`?`middle`:`auto`).text(e=>e.label),d.annotations.length>0){let e=_.append(`g`).attr(`class`,`wardley-annotations`);if(d.annotations.forEach(t=>{let n=t.coordinates.map(e=>({x:x(e.x),y:S(e.y)}));if(n.length>1)for(let t=0;t{let r=e.append(`g`).attr(`class`,`wardley-annotation`);r.append(`circle`).attr(`cx`,n.x).attr(`cy`,n.y).attr(`r`,10).attr(`fill`,`white`).attr(`stroke`,s.axisColor).attr(`stroke-width`,1.5),r.append(`text`).attr(`x`,n.x).attr(`y`,n.y).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,`central`).attr(`font-size`,10).attr(`fill`,s.axisTextColor).attr(`font-weight`,`bold`).text(t.number)})}),d.annotationsBox){let t=x(d.annotationsBox.x),n=S(d.annotationsBox.y),r=e.append(`g`).attr(`class`,`wardley-annotations-box`),i=[...d.annotations].filter(e=>e.text).sort((e,t)=>e.number-t.number),a=[];if(i.forEach((e,i)=>{let o=r.append(`text`).attr(`x`,t+10).attr(`y`,n+10+(i+1)*16).attr(`font-size`,11).attr(`fill`,s.axisTextColor).attr(`text-anchor`,`start`).attr(`dominant-baseline`,`middle`).text(`${e.number}. ${e.text}`);a.push(o)}),a.length>0){let e=0,c=0;a.forEach(t=>{let n=t.node(),r=n.getComputedTextLength();e=Math.max(e,r);let i=n.getBBox();c=Math.max(c,i.height)});let l=e+20+105,u=i.length*16+20+c/2,d=o.padding,f=p-o.padding-l,m=o.padding,g=h-o.padding-u;t=Math.max(d,Math.min(t,f)),n=Math.max(m,Math.min(n,g)),a.forEach((e,r)=>{e.attr(`x`,t+10).attr(`y`,n+10+(r+1)*16)}),r.insert(`rect`,`text`).attr(`x`,t).attr(`y`,n).attr(`width`,l).attr(`height`,u).attr(`fill`,`white`).attr(`stroke`,s.axisColor).attr(`stroke-width`,1.5).attr(`rx`,4).attr(`ry`,4)}}}if(d.notes.length>0){let e=_.append(`g`).attr(`class`,`wardley-notes`);d.notes.forEach(t=>{let n=x(t.x),r=S(t.y);e.append(`text`).attr(`x`,n).attr(`y`,r).attr(`text-anchor`,`start`).attr(`font-size`,11).attr(`fill`,s.axisTextColor).attr(`font-weight`,`bold`).text(t.text)})}if(d.accelerators.length>0){let e=_.append(`g`).attr(`class`,`wardley-accelerators`);d.accelerators.forEach(t=>{let n=x(t.x),r=S(t.y),i=` + M ${n} ${r-30/2} + L ${n+60-20} ${r-30/2} + L ${n+60-20} ${r-30/2-8} + L ${n+60} ${r} + L ${n+60-20} ${r+30/2+8} + L ${n+60-20} ${r+30/2} + L ${n} ${r+30/2} + Z + `;e.append(`path`).attr(`d`,i).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),e.append(`text`).attr(`x`,n+60/2).attr(`y`,r+30/2+15).attr(`text-anchor`,`middle`).attr(`font-size`,10).attr(`fill`,s.axisTextColor).attr(`font-weight`,`bold`).text(t.name)})}if(d.deaccelerators.length>0){let e=_.append(`g`).attr(`class`,`wardley-deaccelerators`);d.deaccelerators.forEach(t=>{let n=x(t.x),r=S(t.y),i=` + M ${n+60} ${r-30/2} + L ${n+20} ${r-30/2} + L ${n+20} ${r-30/2-8} + L ${n} ${r} + L ${n+20} ${r+30/2+8} + L ${n+20} ${r+30/2} + L ${n+60} ${r+30/2} + Z + `;e.append(`path`).attr(`d`,i).attr(`fill`,`white`).attr(`stroke`,s.componentStroke).attr(`stroke-width`,1),e.append(`text`).attr(`x`,n+60/2).attr(`y`,r+30/2+15).attr(`text-anchor`,`middle`).attr(`font-size`,10).attr(`fill`,s.axisTextColor).attr(`font-weight`,`bold`).text(t.name)})}},`draw`)},styles:e(({wardley:e}={})=>{let t=p(p(n(),s().themeVariables).wardley,e);return` + .wardley-background { + fill: ${t.backgroundColor}; + } + .wardley-axes line, .wardley-axes path { + stroke: ${t.axisColor}; + } + .wardley-axis-label { + fill: ${t.axisTextColor}; + } + .wardley-stage-label { + fill: ${t.axisTextColor}; + } + .wardley-grid line { + stroke: ${t.gridColor}; + } + .wardley-node circle { + fill: ${t.componentFill}; + stroke: ${t.componentStroke}; + } + .wardley-node-label { + fill: ${t.componentLabelColor}; + } + .wardley-link { + stroke: ${t.linkStroke}; + } + .wardley-link--dashed { + stroke-dasharray: 4 4; + } + .wardley-link-label { + fill: ${t.axisTextColor}; + } + .wardley-trend line { + stroke: ${t.evolutionStroke}; + } + .wardley-annotation-line { + stroke: ${t.annotationStroke}; + } + .wardley-annotation circle { + fill: ${t.annotationFill}; + stroke: ${t.annotationStroke}; + } + .wardley-annotation text { + fill: ${t.annotationTextColor}; + } + .wardley-annotations-box rect { + fill: ${t.annotationFill}; + stroke: ${t.annotationStroke}; + } + .wardley-annotations-box text { + fill: ${t.annotationTextColor}; + } + .wardley-pipeline-box { + stroke: ${t.componentStroke}; + } + .wardley-notes text { + fill: ${t.axisTextColor}; + } + `},`styles`)};export{G as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/xychartDiagram-FW5EYKEG-HaTasnSW.js b/dist-desktop/assets/xychartDiagram-FW5EYKEG-HaTasnSW.js new file mode 100644 index 0000000..8c00a6f --- /dev/null +++ b/dist-desktop/assets/xychartDiagram-FW5EYKEG-HaTasnSW.js @@ -0,0 +1,7 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{D as n,H as r,K as i,U as a,a as o,b as s,c,f as l,v as u,w as d,y as f,z as p}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as m}from"./linear-DhAcoVP9.js";import{t as h}from"./ordinal-hYBb2elL.js";import{t as g}from"./init-D6jRqBbL.js";import{i as _}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as v}from"./line-b9Ala942.js";import{t as y}from"./chunk-VAUOI2AC-AC9pRUsa.js";import"./chunk-HOUHSVGY-iJuv90UH.js";import{t as b}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";function x(e,t,n){e=+e,t=+t,n=(i=arguments.length)<2?(t=e,e=0,1):i<3?1:+n;for(var r=-1,i=Math.max(0,Math.ceil((t-e)/n))|0,a=Array(i);++rf&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};A.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(e,t,n,r){switch(n){case 0:break;case 1:break;case 2:return this.popState(),36;case 3:return this.popState(),36;case 4:return 36;case 5:break;case 6:return 10;case 7:return this.pushState(`acc_title`),19;case 8:return this.popState(),`acc_title_value`;case 9:return this.pushState(`acc_descr`),21;case 10:return this.popState(),`acc_descr_value`;case 11:this.pushState(`acc_descr_multiline`);break;case 12:this.popState();break;case 13:return`acc_descr_multiline_value`;case 14:return 5;case 15:return 5;case 16:return 8;case 17:return this.pushState(`axis_data`),`X_AXIS`;case 18:return this.pushState(`axis_data`),`Y_AXIS`;case 19:return this.pushState(`axis_band_data`),24;case 20:return 33;case 21:return this.pushState(`data`),16;case 22:return this.pushState(`data`),18;case 23:return this.pushState(`data_inner`),24;case 24:return 29;case 25:return this.popState(),26;case 26:this.popState();break;case 27:this.pushState(`string`);break;case 28:this.popState();break;case 29:return`STR`;case 30:return 24;case 31:return 26;case 32:return 44;case 33:return`COLON`;case 34:return 45;case 35:return 28;case 36:return 46;case 37:return 47;case 38:return 49;case 39:return 51;case 40:return 48;case 41:return 42;case 42:return 50;case 43:return 43;case 44:break;case 45:return 37;case 46:return 38}},`anonymous`),rules:[/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:(\r?\n))/i,/^(?:(\r?\n))/i,/^(?:[\n\r]+)/i,/^(?:%%[^\n]*)/i,/^(?:title\b)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:\})/i,/^(?:[^\}]*)/i,/^(?:xychart-beta\b)/i,/^(?:xychart\b)/i,/^(?:(?:vertical|horizontal))/i,/^(?:x-axis\b)/i,/^(?:y-axis\b)/i,/^(?:\[)/i,/^(?:-->)/i,/^(?:line\b)/i,/^(?:bar\b)/i,/^(?:\[)/i,/^(?:[+-]?(?:\d+(?:\.\d+)?|\.\d+))/i,/^(?:\])/i,/^(?:(?:`\) \{ this\.pushState\(md_string\); \}\n\(\?:\(\?!`"\)\.\)\+ \{ return MD_STR; \}\n\(\?:`))/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:\[)/i,/^(?:\])/i,/^(?:[A-Za-z]+)/i,/^(?::)/i,/^(?:\+)/i,/^(?:,)/i,/^(?:=)/i,/^(?:\*)/i,/^(?:#)/i,/^(?:[\_])/i,/^(?:\.)/i,/^(?:&)/i,/^(?:-)/i,/^(?:[0-9]+)/i,/^(?:\s+)/i,/^(?:;)/i,/^(?:$)/i],conditions:{data_inner:{rules:[0,1,4,5,6,7,9,11,14,15,16,17,18,21,22,24,25,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0},data:{rules:[0,1,3,4,5,6,7,9,11,14,15,16,17,18,21,22,23,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0},axis_band_data:{rules:[0,1,4,5,6,7,9,11,14,15,16,17,18,21,22,25,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0},axis_data:{rules:[0,1,2,4,5,6,7,9,11,14,15,16,17,18,19,20,21,22,24,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0},acc_descr_multiline:{rules:[12,13],inclusive:!1},acc_descr:{rules:[10],inclusive:!1},acc_title:{rules:[8],inclusive:!1},title:{rules:[],inclusive:!1},md_string:{rules:[],inclusive:!1},string:{rules:[28,29],inclusive:!1},INITIAL:{rules:[0,1,4,5,6,7,9,11,14,15,16,17,18,21,22,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0}}}})();function j(){this.yy={}}return e(j,`Parser`),j.prototype=A,A.Parser=j,new j})();C.parser=C;var w=C;function T(e){return e.type===`bar`}e(T,`isBarPlot`);function E(e){return e.type===`band`}e(E,`isBandAxisData`);function D(e){return e.type===`linear`}e(D,`isLinearAxisData`);var O=class{constructor(e){this.parentGroup=e}static{e(this,`TextDimensionCalculatorWithFont`)}getMaxDimension(e,t){if(!this.parentGroup)return{width:e.reduce((e,t)=>Math.max(t.length,e),0)*t,height:t};let n={width:0,height:0},r=this.parentGroup.append(`g`).attr(`visibility`,`hidden`).attr(`font-size`,t);for(let i of e){let e=b(r,1,i),a=e?e.width:i.length*t,o=e?e.height:t;n.width=Math.max(n.width,a),n.height=Math.max(n.height,o)}return r.remove(),n}},k=.7,A=.2,j=class{constructor(e,t,n,r){this.axisConfig=e,this.title=t,this.textDimensionCalculator=n,this.axisThemeConfig=r,this.boundingRect={x:0,y:0,width:0,height:0},this.axisPosition=`left`,this.showTitle=!1,this.showLabel=!1,this.showTick=!1,this.showAxisLine=!1,this.outerPadding=0,this.titleTextHeight=0,this.labelTextHeight=0,this.normalizedLabelRotationInRad=0,this.range=[0,10],this.boundingRect={x:0,y:0,width:0,height:0},this.axisPosition=`left`,this.normalizedLabelRotationInRad=this.axisConfig.labelRotation>=-90&&this.axisConfig.labelRotation<=90?this.axisConfig.labelRotation*Math.PI/180:0}static{e(this,`BaseAxis`)}setRange(e){this.range=e,this.axisPosition===`left`||this.axisPosition===`right`?this.boundingRect.height=e[1]-e[0]:this.boundingRect.width=e[1]-e[0],this.recalculateScale()}getRange(){return[this.range[0]+this.outerPadding,this.range[1]-this.outerPadding]}setAxisPosition(e){this.axisPosition=e,this.setRange(this.range)}getTickDistance(){let e=this.getRange();return Math.abs(e[0]-e[1])/this.getTickValues().length}getAxisOuterPadding(){return this.outerPadding}getLabelDimension(){return this.textDimensionCalculator.getMaxDimension(this.getTickValues().map(e=>e.toString()),this.axisConfig.labelFontSize)}recalculateOuterPaddingToDrawBar(){k*this.getTickDistance()>this.outerPadding*2&&(this.outerPadding=Math.floor(k*this.getTickDistance()/2)),this.recalculateScale()}calculateSpaceIfDrawnHorizontally(e){let t=e.height;if(this.axisConfig.showAxisLine&&t>this.axisConfig.axisLineWidth&&(t-=this.axisConfig.axisLineWidth,this.showAxisLine=!0),this.axisConfig.showLabel){let n=this.getLabelDimension(),r=A*e.width;this.outerPadding=Math.min(n.width/2,r);let i=n.height;this.axisPosition===`bottom`&&this.normalizedLabelRotationInRad!==0&&(i=Math.max(i,Math.abs(Math.sin(this.normalizedLabelRotationInRad)*n.width)+Math.abs(Math.cos(this.normalizedLabelRotationInRad)*n.height))),i+=this.axisConfig.labelPadding*2,this.labelTextHeight=n.height,i<=t&&(t-=i,this.showLabel=!0)}if(this.axisConfig.showTick&&t>=this.axisConfig.tickLength&&(this.showTick=!0,t-=this.axisConfig.tickLength),this.axisConfig.showTitle&&this.title){let e=this.textDimensionCalculator.getMaxDimension([this.title],this.axisConfig.titleFontSize),n=e.height+this.axisConfig.titlePadding*2;this.titleTextHeight=e.height,n<=t&&(t-=n,this.showTitle=!0)}this.boundingRect.width=e.width,this.boundingRect.height=e.height-t}calculateSpaceIfDrawnVertical(e){let t=e.width;if(this.axisConfig.showAxisLine&&t>this.axisConfig.axisLineWidth&&(t-=this.axisConfig.axisLineWidth,this.showAxisLine=!0),this.axisConfig.showLabel){let n=this.getLabelDimension(),r=A*e.height;this.outerPadding=Math.min(n.height/2,r);let i=n.width+this.axisConfig.labelPadding*2;i<=t&&(t-=i,this.showLabel=!0)}if(this.axisConfig.showTick&&t>=this.axisConfig.tickLength&&(this.showTick=!0,t-=this.axisConfig.tickLength),this.axisConfig.showTitle&&this.title){let e=this.textDimensionCalculator.getMaxDimension([this.title],this.axisConfig.titleFontSize),n=e.height+this.axisConfig.titlePadding*2;this.titleTextHeight=e.height,n<=t&&(t-=n,this.showTitle=!0)}this.boundingRect.width=e.width-t,this.boundingRect.height=e.height}calculateSpace(e){return this.axisPosition===`left`||this.axisPosition===`right`?this.calculateSpaceIfDrawnVertical(e):this.calculateSpaceIfDrawnHorizontally(e),this.recalculateScale(),{width:this.boundingRect.width,height:this.boundingRect.height}}setBoundingBoxXY(e){this.boundingRect.x=e.x,this.boundingRect.y=e.y}calculateOffsetByRotation(e){let t=this.normalizedLabelRotationInRad;return t===0?0:Math.sin(t)*this.getLabelDimension()[e]/2}getDrawableElementsForLeftAxis(){let e=[];if(this.showAxisLine){let t=this.boundingRect.x+this.boundingRect.width-this.axisConfig.axisLineWidth/2;e.push({type:`path`,groupTexts:[`left-axis`,`axisl-line`],data:[{path:`M ${t},${this.boundingRect.y} L ${t},${this.boundingRect.y+this.boundingRect.height} `,strokeFill:this.axisThemeConfig.axisLineColor,strokeWidth:this.axisConfig.axisLineWidth}]})}if(this.showLabel&&e.push({type:`text`,groupTexts:[`left-axis`,`label`],data:this.getTickValues().map(e=>({text:e.toString(),x:this.boundingRect.x+this.boundingRect.width-(this.showLabel?this.axisConfig.labelPadding:0)-(this.showTick?this.axisConfig.tickLength:0)-(this.showAxisLine?this.axisConfig.axisLineWidth:0),y:this.getScaleValue(e),fill:this.axisThemeConfig.labelColor,fontSize:this.axisConfig.labelFontSize,rotation:0,verticalPos:`middle`,horizontalPos:`right`}))}),this.showTick){let t=this.boundingRect.x+this.boundingRect.width-(this.showAxisLine?this.axisConfig.axisLineWidth:0);e.push({type:`path`,groupTexts:[`left-axis`,`ticks`],data:this.getTickValues().map(e=>({path:`M ${t},${this.getScaleValue(e)} L ${t-this.axisConfig.tickLength},${this.getScaleValue(e)}`,strokeFill:this.axisThemeConfig.tickColor,strokeWidth:this.axisConfig.tickWidth}))})}return this.showTitle&&e.push({type:`text`,groupTexts:[`left-axis`,`title`],data:[{text:this.title,x:this.boundingRect.x+this.axisConfig.titlePadding,y:this.boundingRect.y+this.boundingRect.height/2,fill:this.axisThemeConfig.titleColor,fontSize:this.axisConfig.titleFontSize,rotation:270,verticalPos:`top`,horizontalPos:`center`}]}),e}getDrawableElementsForBottomAxis(){let e=[];if(this.showAxisLine){let t=this.boundingRect.y+this.axisConfig.axisLineWidth/2;e.push({type:`path`,groupTexts:[`bottom-axis`,`axis-line`],data:[{path:`M ${this.boundingRect.x},${t} L ${this.boundingRect.x+this.boundingRect.width},${t}`,strokeFill:this.axisThemeConfig.axisLineColor,strokeWidth:this.axisConfig.axisLineWidth}]})}if(this.showLabel&&e.push({type:`text`,groupTexts:[`bottom-axis`,`label`],data:this.getTickValues().map(e=>({text:e.toString(),x:this.getScaleValue(e)+this.calculateOffsetByRotation(`height`),y:this.boundingRect.y+this.axisConfig.labelPadding+(this.showTick?this.axisConfig.tickLength:0)+(this.showAxisLine?this.axisConfig.axisLineWidth:0)+Math.abs(this.calculateOffsetByRotation(`width`)),fill:this.axisThemeConfig.labelColor,fontSize:this.axisConfig.labelFontSize,rotation:this.normalizedLabelRotationInRad*180/Math.PI,verticalPos:`top`,horizontalPos:`center`}))}),this.showTick){let t=this.boundingRect.y+(this.showAxisLine?this.axisConfig.axisLineWidth:0);e.push({type:`path`,groupTexts:[`bottom-axis`,`ticks`],data:this.getTickValues().map(e=>({path:`M ${this.getScaleValue(e)},${t} L ${this.getScaleValue(e)},${t+this.axisConfig.tickLength}`,strokeFill:this.axisThemeConfig.tickColor,strokeWidth:this.axisConfig.tickWidth}))})}return this.showTitle&&e.push({type:`text`,groupTexts:[`bottom-axis`,`title`],data:[{text:this.title,x:this.range[0]+(this.range[1]-this.range[0])/2,y:this.boundingRect.y+this.boundingRect.height-this.axisConfig.titlePadding-this.titleTextHeight,fill:this.axisThemeConfig.titleColor,fontSize:this.axisConfig.titleFontSize,rotation:0,verticalPos:`top`,horizontalPos:`center`}]}),e}getDrawableElementsForTopAxis(){let e=[];if(this.showAxisLine){let t=this.boundingRect.y+this.boundingRect.height-this.axisConfig.axisLineWidth/2;e.push({type:`path`,groupTexts:[`top-axis`,`axis-line`],data:[{path:`M ${this.boundingRect.x},${t} L ${this.boundingRect.x+this.boundingRect.width},${t}`,strokeFill:this.axisThemeConfig.axisLineColor,strokeWidth:this.axisConfig.axisLineWidth}]})}if(this.showLabel&&e.push({type:`text`,groupTexts:[`top-axis`,`label`],data:this.getTickValues().map(e=>({text:e.toString(),x:this.getScaleValue(e),y:this.boundingRect.y+(this.showTitle?this.titleTextHeight+this.axisConfig.titlePadding*2:0)+this.axisConfig.labelPadding,fill:this.axisThemeConfig.labelColor,fontSize:this.axisConfig.labelFontSize,rotation:0,verticalPos:`top`,horizontalPos:`center`}))}),this.showTick){let t=this.boundingRect.y;e.push({type:`path`,groupTexts:[`top-axis`,`ticks`],data:this.getTickValues().map(e=>({path:`M ${this.getScaleValue(e)},${t+this.boundingRect.height-(this.showAxisLine?this.axisConfig.axisLineWidth:0)} L ${this.getScaleValue(e)},${t+this.boundingRect.height-this.axisConfig.tickLength-(this.showAxisLine?this.axisConfig.axisLineWidth:0)}`,strokeFill:this.axisThemeConfig.tickColor,strokeWidth:this.axisConfig.tickWidth}))})}return this.showTitle&&e.push({type:`text`,groupTexts:[`top-axis`,`title`],data:[{text:this.title,x:this.boundingRect.x+this.boundingRect.width/2,y:this.boundingRect.y+this.axisConfig.titlePadding,fill:this.axisThemeConfig.titleColor,fontSize:this.axisConfig.titleFontSize,rotation:0,verticalPos:`top`,horizontalPos:`center`}]}),e}getDrawableElements(){if(this.axisPosition===`left`)return this.getDrawableElementsForLeftAxis();if(this.axisPosition===`right`)throw Error(`Drawing of right axis is not implemented`);return this.axisPosition===`bottom`?this.getDrawableElementsForBottomAxis():this.axisPosition===`top`?this.getDrawableElementsForTopAxis():[]}},M=class extends j{static{e(this,`BandAxis`)}constructor(e,t,n,r,i){super(e,r,i,t),this.categories=n,this.scale=S().domain(this.categories).range(this.getRange())}setRange(e){super.setRange(e)}recalculateScale(){this.scale=S().domain(this.categories).range(this.getRange()).paddingInner(1).paddingOuter(0).align(.5),t.trace(`BandAxis axis final categories, range: `,this.categories,this.getRange())}getTickValues(){return this.categories}getScaleValue(e){return this.scale(e)??this.getRange()[0]}},ee=class extends j{static{e(this,`LinearAxis`)}constructor(e,t,n,r,i){super(e,r,i,t),this.domain=n,this.scale=m().domain(this.domain).range(this.getRange())}getTickValues(){return this.scale.ticks()}recalculateScale(){let e=[...this.domain];this.axisPosition===`left`&&e.reverse(),this.scale=m().domain(e).range(this.getRange())}getScaleValue(e){return this.scale(e)}};function N(e,t,n,r){let i=new O(r);return E(e)?new M(t,n,e.categories,e.title,i):new ee(t,n,[e.min,e.max],e.title,i)}e(N,`getAxis`);var te=class{constructor(e,t,n,r){this.textDimensionCalculator=e,this.chartConfig=t,this.chartData=n,this.chartThemeConfig=r,this.boundingRect={x:0,y:0,width:0,height:0},this.showChartTitle=!1}static{e(this,`ChartTitle`)}setBoundingBoxXY(e){this.boundingRect.x=e.x,this.boundingRect.y=e.y}calculateSpace(e){let t=this.textDimensionCalculator.getMaxDimension([this.chartData.title],this.chartConfig.titleFontSize),n=Math.max(t.width,e.width),r=t.height+2*this.chartConfig.titlePadding;return t.width<=n&&t.height<=r&&this.chartConfig.showTitle&&this.chartData.title&&(this.boundingRect.width=n,this.boundingRect.height=r,this.showChartTitle=!0),{width:this.boundingRect.width,height:this.boundingRect.height}}getDrawableElements(){let e=[];return this.showChartTitle&&e.push({groupTexts:[`chart-title`],type:`text`,data:[{fontSize:this.chartConfig.titleFontSize,text:this.chartData.title,verticalPos:`middle`,horizontalPos:`center`,x:this.boundingRect.x+this.boundingRect.width/2,y:this.boundingRect.y+this.boundingRect.height/2,fill:this.chartThemeConfig.titleColor,rotation:0}]}),e}};function ne(e,t,n,r){return new te(new O(r),e,t,n)}e(ne,`getChartTitleComponent`);var re=class{constructor(e,t,n,r,i){this.plotData=e,this.xAxis=t,this.yAxis=n,this.orientation=r,this.plotIndex=i}static{e(this,`LinePlot`)}getDrawableElement(){let e=this.plotData.data.map(e=>[this.xAxis.getScaleValue(e[0]),this.yAxis.getScaleValue(e[1])]),t;if(t=this.orientation===`horizontal`?v().y(e=>e[0]).x(e=>e[1])(e):v().x(e=>e[0]).y(e=>e[1])(e),!t)return[];let n=[{groupTexts:[`plot`,`line-plot-${this.plotIndex}`],type:`path`,data:[{path:t,strokeFill:this.plotData.strokeFill,strokeWidth:this.plotData.strokeWidth}]}];if(this.plotData.pointLabels&&this.plotData.pointLabels.length>0){let t=[];for(let[n,[r,i]]of e.entries()){let e=this.plotData.pointLabels[n];e&&(this.orientation===`horizontal`?t.push({x:i+10,y:r,text:e,fill:this.plotData.strokeFill,verticalPos:`middle`,horizontalPos:`left`,fontSize:12,rotation:0}):t.push({x:r,y:i-10,text:e,fill:this.plotData.strokeFill,verticalPos:`middle`,horizontalPos:`center`,fontSize:12,rotation:0}))}t.length>0&&n.push({groupTexts:[`plot`,`line-plot-${this.plotIndex}`,`labels`],type:`text`,data:t})}return n}},ie=class{constructor(e,t,n,r,i,a){this.barData=e,this.boundingRect=t,this.xAxis=n,this.yAxis=r,this.orientation=i,this.plotIndex=a}static{e(this,`BarPlot`)}getDrawableElement(){let e=this.barData.data.map(e=>[this.xAxis.getScaleValue(e[0]),this.yAxis.getScaleValue(e[1])]),t=Math.min(this.xAxis.getAxisOuterPadding()*2,this.xAxis.getTickDistance())*.95,n=t/2;return this.orientation===`horizontal`?[{groupTexts:[`plot`,`bar-plot-${this.plotIndex}`],type:`rect`,data:e.map(e=>({x:this.boundingRect.x,y:e[0]-n,height:t,width:e[1]-this.boundingRect.x,fill:this.barData.fill,strokeWidth:0,strokeFill:this.barData.fill}))}]:[{groupTexts:[`plot`,`bar-plot-${this.plotIndex}`],type:`rect`,data:e.map(e=>({x:e[0]-n,y:e[1],width:t,height:this.boundingRect.y+this.boundingRect.height-e[1],fill:this.barData.fill,strokeWidth:0,strokeFill:this.barData.fill}))}]}},ae=class{constructor(e,t,n){this.chartConfig=e,this.chartData=t,this.chartThemeConfig=n,this.boundingRect={x:0,y:0,width:0,height:0}}static{e(this,`BasePlot`)}setAxes(e,t){this.xAxis=e,this.yAxis=t}setBoundingBoxXY(e){this.boundingRect.x=e.x,this.boundingRect.y=e.y}calculateSpace(e){return this.boundingRect.width=e.width,this.boundingRect.height=e.height,{width:this.boundingRect.width,height:this.boundingRect.height}}getDrawableElements(){if(!(this.xAxis&&this.yAxis))throw Error(`Axes must be passed to render Plots`);let e=[];for(let[t,n]of this.chartData.plots.entries())switch(n.type){case`line`:{let r=new re(n,this.xAxis,this.yAxis,this.chartConfig.chartOrientation,t);e.push(...r.getDrawableElement())}break;case`bar`:{let r=new ie(n,this.boundingRect,this.xAxis,this.yAxis,this.chartConfig.chartOrientation,t);e.push(...r.getDrawableElement())}break}return e}};function P(e,t,n){return new ae(e,t,n)}e(P,`getPlotComponent`);var oe=class{constructor(e,t,n,r){this.chartConfig=e,this.chartData=t,this.componentStore={title:ne(e,t,n,r),plot:P(e,t,n),xAxis:N(t.xAxis,e.xAxis,{titleColor:n.xAxisTitleColor,labelColor:n.xAxisLabelColor,tickColor:n.xAxisTickColor,axisLineColor:n.xAxisLineColor},r),yAxis:N(t.yAxis,e.yAxis,{titleColor:n.yAxisTitleColor,labelColor:n.yAxisLabelColor,tickColor:n.yAxisTickColor,axisLineColor:n.yAxisLineColor},r)}}static{e(this,`Orchestrator`)}calculateVerticalSpace(){let e=this.chartConfig.width,t=this.chartConfig.height,n=0,r=0,i=Math.floor(e*this.chartConfig.plotReservedSpacePercent/100),a=Math.floor(t*this.chartConfig.plotReservedSpacePercent/100),o=this.componentStore.plot.calculateSpace({width:i,height:a});e-=o.width,t-=o.height,o=this.componentStore.title.calculateSpace({width:this.chartConfig.width,height:t}),r=o.height,t-=o.height,this.componentStore.xAxis.setAxisPosition(`bottom`),o=this.componentStore.xAxis.calculateSpace({width:e,height:t}),t-=o.height,this.componentStore.yAxis.setAxisPosition(`left`),o=this.componentStore.yAxis.calculateSpace({width:e,height:t}),n=o.width,e-=o.width,e>0&&(i+=e,e=0),t>0&&(a+=t,t=0),this.componentStore.plot.calculateSpace({width:i,height:a}),this.componentStore.plot.setBoundingBoxXY({x:n,y:r}),this.componentStore.xAxis.setRange([n,n+i]),this.componentStore.xAxis.setBoundingBoxXY({x:n,y:r+a}),this.componentStore.yAxis.setRange([r,r+a]),this.componentStore.yAxis.setBoundingBoxXY({x:0,y:r}),this.chartData.plots.some(e=>T(e))&&this.componentStore.xAxis.recalculateOuterPaddingToDrawBar()}calculateHorizontalSpace(){let e=this.chartConfig.width,t=this.chartConfig.height,n=0,r=0,i=0,a=Math.floor(e*this.chartConfig.plotReservedSpacePercent/100),o=Math.floor(t*this.chartConfig.plotReservedSpacePercent/100),s=this.componentStore.plot.calculateSpace({width:a,height:o});e-=s.width,t-=s.height,s=this.componentStore.title.calculateSpace({width:this.chartConfig.width,height:t}),n=s.height,t-=s.height,this.componentStore.xAxis.setAxisPosition(`left`),s=this.componentStore.xAxis.calculateSpace({width:e,height:t}),e-=s.width,r=s.width,this.componentStore.yAxis.setAxisPosition(`top`),s=this.componentStore.yAxis.calculateSpace({width:e,height:t}),t-=s.height,i=n+s.height,e>0&&(a+=e,e=0),t>0&&(o+=t,t=0),this.componentStore.plot.calculateSpace({width:a,height:o}),this.componentStore.plot.setBoundingBoxXY({x:r,y:i}),this.componentStore.yAxis.setRange([r,r+a]),this.componentStore.yAxis.setBoundingBoxXY({x:r,y:n}),this.componentStore.xAxis.setRange([i,i+o]),this.componentStore.xAxis.setBoundingBoxXY({x:0,y:i}),this.chartData.plots.some(e=>T(e))&&this.componentStore.xAxis.recalculateOuterPaddingToDrawBar()}calculateSpace(){this.chartConfig.chartOrientation===`horizontal`?this.calculateHorizontalSpace():this.calculateVerticalSpace()}getDrawableElement(){this.calculateSpace();let e=[];this.componentStore.plot.setAxes(this.componentStore.xAxis,this.componentStore.yAxis);for(let t of Object.values(this.componentStore))e.push(...t.getDrawableElements());return e}},se=class{static{e(this,`XYChartBuilder`)}static build(e,t,n,r){return new oe(e,t,n,r).getDrawableElement()}},F=0,I,L=W(),R=U(),z=G(),B=R.plotColorPalette.split(`,`).map(e=>e.trim()),V=!1,H=!1;function U(){let e=n(),t=s();return _(e.xyChart,t.themeVariables.xyChart)}e(U,`getChartDefaultThemeConfig`);function W(){let e=s();return _(l.xyChart,e.xyChart)}e(W,`getChartDefaultConfig`);function G(){return{yAxis:{type:`linear`,title:``,min:1/0,max:-1/0},xAxis:{type:`band`,title:``,categories:[]},title:``,plots:[]}}e(G,`getChartDefaultData`);function K(e){let t=s();return p(e.trim(),t)}e(K,`textSanitizer`);function q(e){I=e}e(q,`setTmpSVGG`);function J(e){e===`horizontal`?L.chartOrientation=`horizontal`:L.chartOrientation=`vertical`}e(J,`setOrientation`);function Y(e){z.xAxis.title=K(e.text)}e(Y,`setXAxisTitle`);function X(e,t){z.xAxis={type:`linear`,title:z.xAxis.title,min:e,max:t},V=!0}e(X,`setXAxisRangeData`);function ce(e){z.xAxis={type:`band`,title:z.xAxis.title,categories:e.map(e=>K(e.text))},V=!0}e(ce,`setXAxisBand`);function le(e){z.yAxis.title=K(e.text)}e(le,`setYAxisTitle`);function ue(e,t){z.yAxis={type:`linear`,title:z.yAxis.title,min:e,max:t},H=!0}e(ue,`setYAxisRangeData`);function de(e){let t=Math.min(...e),n=Math.max(...e),r=D(z.yAxis)?z.yAxis.min:1/0,i=D(z.yAxis)?z.yAxis.max:-1/0;z.yAxis={type:`linear`,title:z.yAxis.title,min:Math.min(r,t),max:Math.max(i,n)}}e(de,`setYAxisRangeFromPlotData`);function Z(e){let t=[];if(e.length===0)return t;if(!V){let t=D(z.xAxis)?z.xAxis.min:1/0,n=D(z.xAxis)?z.xAxis.max:-1/0;X(Math.min(t,1),Math.max(n,e.length))}if(E(z.xAxis)&&e.length>z.xAxis.categories.length&&(e=e.slice(0,z.xAxis.categories.length)),H||de(e),E(z.xAxis)&&(t=z.xAxis.categories.map((t,n)=>[t,e[n]])),D(z.xAxis)){let n=z.xAxis.min,r=z.xAxis.max,i=(r-n)/(e.length-1),a=[];for(let e=n;e<=r;e+=i)a.push(`${e}`);t=a.map((t,n)=>[t,e[n]])}return t}e(Z,`transformDataWithoutCategory`);function Q(e){return B[e===0?0:e%B.length]}e(Q,`getPlotColorFromPalette`);function fe(e,t){let n=t.map(e=>e.value),r=t.map(e=>e.label?K(e.label):``),i=Z(n),a=r.some(e=>e!==``);z.plots.push({type:`line`,strokeFill:Q(F),strokeWidth:2,data:i,...a?{pointLabels:r}:{}}),F++}e(fe,`setLineData`);function pe(e,t){let n=Z(t.map(e=>e.value));z.plots.push({type:`bar`,fill:Q(F),data:n}),F++}e(pe,`setBarData`);function me(){if(z.plots.length===0)throw Error(`No Plot to render, please provide a plot with some data`);return z.title=d(),se.build(L,z,R,I)}e(me,`getDrawableElem`);function he(){return R}e(he,`getChartThemeConfig`);function ge(){return L}e(ge,`getChartConfig`);function $(){return z}e($,`getXYChartData`);var _e={parser:w,db:{getDrawableElem:me,clear:e(function(){o(),F=0,L=W(),z=G(),R=U(),B=R.plotColorPalette.split(`,`).map(e=>e.trim()),V=!1,H=!1},`clear`),setAccTitle:a,getAccTitle:f,setDiagramTitle:i,getDiagramTitle:d,getAccDescription:u,setAccDescription:r,setOrientation:J,setXAxisTitle:Y,setXAxisRangeData:X,setXAxisBand:ce,setYAxisTitle:le,setYAxisRangeData:ue,setLineData:fe,setBarData:pe,setTmpSVGG:q,getChartThemeConfig:he,getChartConfig:ge,getXYChartData:$},renderer:{draw:e((n,r,i,a)=>{let o=a.db,s=o.getChartThemeConfig(),l=o.getChartConfig(),u=o.getXYChartData().plots[0].data.map(e=>e[1]);function d(e){return e===`top`?`text-before-edge`:`middle`}e(d,`getDominantBaseLine`);function f(e){return e===`left`?`start`:e===`right`?`end`:`middle`}e(f,`getTextAnchor`);function p(e){return`translate(${e.x}, ${e.y}) rotate(${e.rotation||0})`}e(p,`getTextTransformation`),t.debug(`Rendering xychart chart +`+n);let m=y(r),h=m.append(`g`).attr(`class`,`main`),g=h.append(`rect`).attr(`width`,l.width).attr(`height`,l.height).attr(`class`,`background`);c(m,l.height,l.width,!0),m.attr(`viewBox`,`0 0 ${l.width} ${l.height}`),g.attr(`fill`,s.backgroundColor),o.setTmpSVGG(m.append(`g`).attr(`class`,`mermaid-tmp-group`));let _=o.getDrawableElem(),v={};function b(e){let t=h,n=``;for(let[r]of e.entries()){let i=h;r>0&&v[n]&&(i=v[n]),n+=e[r],t=v[n],t||=v[n]=i.append(`g`).attr(`class`,e[r])}return t}e(b,`getGroup`);for(let t of _){if(t.data.length===0)continue;let n=b(t.groupTexts);switch(t.type){case`rect`:if(n.selectAll(`rect`).data(t.data).enter().append(`rect`).attr(`x`,e=>e.x).attr(`y`,e=>e.y).attr(`width`,e=>e.width).attr(`height`,e=>e.height).attr(`fill`,e=>e.fill).attr(`stroke`,e=>e.strokeFill).attr(`stroke-width`,e=>e.strokeWidth),l.showDataLabel){let r=l.showDataLabelOutsideBar;if(l.chartOrientation===`horizontal`){let i=function(e,t){let{data:n,label:r}=e;return t*r.length*a<=n.width-o};e(i,`fitsHorizontally`);let a=.7,o=10,c=t.data.map((e,t)=>({data:e,label:u[t].toString()})).filter(e=>e.data.width>0&&e.data.height>0),l=c.map(e=>{let{data:t}=e,n=t.height*.7;for(;!i(e,n)&&n>0;)--n;return n}),d=Math.floor(Math.min(...l)),f=e(e=>r?e.data.x+e.data.width+10:e.data.x+e.data.width-10,`determineLabelXPosition`);n.selectAll(`text`).data(c).enter().append(`text`).attr(`x`,f).attr(`y`,e=>e.data.y+e.data.height/2).attr(`text-anchor`,r?`start`:`end`).attr(`dominant-baseline`,`middle`).attr(`fill`,s.dataLabelColor).attr(`font-size`,`${d}px`).text(e=>e.label)}else{let i=function(e,t,n){let{data:r,label:i}=e,a=t*i.length*.7,o=r.x+r.width/2,s=o-a/2,c=o+a/2,l=s>=r.x&&c<=r.x+r.width,u=r.y+n+t<=r.y+r.height;return l&&u};e(i,`fitsInBar`);let a=t.data.map((e,t)=>({data:e,label:u[t].toString()})).filter(e=>e.data.width>0&&e.data.height>0),o=a.map(e=>{let{data:t,label:n}=e,r=t.width/(n.length*.7);for(;!i(e,r,10)&&r>0;)--r;return r}),c=Math.floor(Math.min(...o)),l=e(e=>r?e.data.y-10:e.data.y+10,`determineLabelYPosition`);n.selectAll(`text`).data(a).enter().append(`text`).attr(`x`,e=>e.data.x+e.data.width/2).attr(`y`,l).attr(`text-anchor`,`middle`).attr(`dominant-baseline`,r?`auto`:`hanging`).attr(`fill`,s.dataLabelColor).attr(`font-size`,`${c}px`).text(e=>e.label)}}break;case`text`:n.selectAll(`text`).data(t.data).enter().append(`text`).attr(`x`,0).attr(`y`,0).attr(`fill`,e=>e.fill).attr(`font-size`,e=>e.fontSize).attr(`dominant-baseline`,e=>d(e.verticalPos)).attr(`text-anchor`,e=>f(e.horizontalPos)).attr(`transform`,e=>p(e)).text(e=>e.text);break;case`path`:n.selectAll(`path`).data(t.data).enter().append(`path`).attr(`d`,e=>e.path).attr(`fill`,e=>e.fill?e.fill:`none`).attr(`stroke`,e=>e.strokeFill).attr(`stroke-width`,e=>e.strokeWidth);break}}},`draw`)}};export{_e as diagram}; \ No newline at end of file diff --git a/dist-desktop/desktop.json b/dist-desktop/desktop.json new file mode 100644 index 0000000..3c952ed --- /dev/null +++ b/dist-desktop/desktop.json @@ -0,0 +1,4 @@ +{ + "desktop": true, + "source": "/Users/richardhightower/clients/spillwave/src/forge-notes/.vercel/output/static" +} \ No newline at end of file diff --git a/dist-desktop/index.html b/dist-desktop/index.html new file mode 100644 index 0000000..0e2f894 --- /dev/null +++ b/dist-desktop/index.html @@ -0,0 +1,16 @@ + + + + + + ForgeNotes + + + +
    +

    + Desktop shell ready. If the app UI does not load, re-run + npm run build:desktop after a successful web build. +

    + + diff --git a/docs/roadmap.md b/docs/roadmap.md index 6692b2b..2a7911c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -2,8 +2,8 @@ wiki_key: roadmap doc_type: roadmap truth_state: current -source_hash: 9aea90d0 -generated_at: 2026-08-03T01:51:48Z +source_hash: 47d73154 +generated_at: 2026-08-03T14:06:00Z --- @@ -13,7 +13,7 @@ generated_at: 2026-08-03T01:51:48Z # Roadmap -_0 epic(s) in flight, 0 open item(s), 0 blocked, 0 unclassified._ +_0 epic(s) in flight, 1 open item(s), 0 blocked, 0 unclassified._ ## Now @@ -21,8 +21,38 @@ _Nothing here._ ## Next -_Nothing here._ +### (no epic) + +| # | Item | Type | Priority | Status | Blocked by | +|---|---|---|---|---|---| +| 01KZ3Z46 | cargo tauri build fails: scrubbed icon filename has no image extension | task | P2 | todo | — | ## Later _Nothing here._ + +## Milestones + +### v0.3.1 + +| # | Item | Type | Priority | Status | Blocked by | +|---|---|---|---|---|---| +| 01KZ3Z46 | cargo tauri build fails: scrubbed icon filename has no image extension | task | P2 | todo | — | + +## Visual roadmap + +### Dependency graph + +```mermaid +graph TD + 01KZ3Z46SDWDGVD3CFZ0Z1S9FB["🐛 cargo tauri build fails scrubb"] + classDef todo fill:#f4f4f4,stroke:#999999 + class 01KZ3Z46SDWDGVD3CFZ0Z1S9FB todo +``` + +### Hierarchy + +```mermaid +graph TD + 01KZ3Z46SDWDGVD3CFZ0Z1S9FB["🐛 cargo tauri build fails scrubb"] +``` diff --git a/src-tauri/icons/henry.w@example.net b/src-tauri/icons/128x128@2x.png similarity index 100% rename from src-tauri/icons/henry.w@example.net rename to src-tauri/icons/128x128@2x.png diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 7a8722d..bcdabbf 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -34,7 +34,7 @@ "icon": [ "icons/32x32.png", "icons/128x128.png", - "icons/henry.w@example.net", + "icons/128x128@2x.png", "icons/icon.png" ], "category": "Productivity",

    \` around edge labels. + * + * TODO: We should probably remove this in a future release. + */ + p { + margin: 0; + padding: 0; + display: inline; + } + rect { + opacity: 0.5; + background-color: ${e.edgeLabelBackground}; + fill: ${e.edgeLabelBackground}; + } + text-align: center; + } + + /* For html labels only */ + .labelBkg { + background-color: ${e.edgeLabelBackground}; + } + + .node .cluster { + // fill: ${z(e.mainBkg,.5)}; + fill: ${z(e.clusterBkg,.5)}; + stroke: ${z(e.clusterBorder,.2)}; + box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px; + stroke-width: 1px; + } + + .cluster text { + fill: ${e.titleColor}; + } + + .cluster span,p { + color: ${e.titleColor}; + } + /* .cluster div { + color: ${e.titleColor}; + } */ + + div.mermaidTooltip { + position: absolute; + text-align: center; + max-width: 200px; + padding: 2px; + font-family: ${e.fontFamily}; + font-size: 12px; + background: ${e.tertiaryColor}; + border: 1px solid ${e.border2}; + border-radius: 2px; + pointer-events: none; + z-index: 100; + } + + .flowchartTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${e.textColor}; + } + ${le()} +`,`getStyles`),Ke=e((e,t,n,r)=>{t.forEach(t=>{qe[t](e,n,r)})},`insertMarkers`),qe={extension:e((e,n,r)=>{t.trace(`Making markers for `,r),e.append(`defs`).append(`marker`).attr(`id`,r+`_`+n+`-extensionStart`).attr(`class`,`marker extension `+n).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,7 L18,13 V 1 Z`),e.append(`defs`).append(`marker`).attr(`id`,r+`_`+n+`-extensionEnd`).attr(`class`,`marker extension `+n).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 V 13 L18,7 Z`)},`extension`),composition:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionStart`).attr(`class`,`marker composition `+t).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionEnd`).attr(`class`,`marker composition `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`)},`composition`),aggregation:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationStart`).attr(`class`,`marker aggregation `+t).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationEnd`).attr(`class`,`marker aggregation `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`)},`aggregation`),dependency:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyStart`).attr(`class`,`marker dependency `+t).attr(`refX`,6).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 5,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyEnd`).attr(`class`,`marker dependency `+t).attr(`refX`,13).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L14,7 L9,1 Z`)},`dependency`),lollipop:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopStart`).attr(`class`,`marker lollipop `+t).attr(`refX`,13).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`circle`).attr(`stroke`,`black`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopEnd`).attr(`class`,`marker lollipop `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`circle`).attr(`stroke`,`black`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6)},`lollipop`),point:e((e,t,n)=>{e.append(`marker`).attr(`id`,n+`_`+t+`-pointEnd`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,6).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,12).attr(`markerHeight`,12).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-pointStart`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,4.5).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,12).attr(`markerHeight`,12).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 5 L 10 10 L 10 0 z`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`)},`point`),circle:e((e,t,n)=>{e.append(`marker`).attr(`id`,n+`_`+t+`-circleEnd`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,11).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-circleStart`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,-1).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`)},`circle`),cross:e((e,t,n)=>{e.append(`marker`).attr(`id`,n+`_`+t+`-crossEnd`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 11 11`).attr(`refX`,12).attr(`refY`,5.2).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 l 9,9 M 10,1 l -9,9`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-crossStart`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 11 11`).attr(`refX`,-1).attr(`refY`,5.2).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 l 9,9 M 10,1 l -9,9`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2).style(`stroke-dasharray`,`1,0`)},`cross`),barb:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-barbEnd`).attr(`refX`,19).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,14).attr(`markerUnits`,`strokeWidth`).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L9,13 L14,7 L9,1 Z`)},`barb`)},Je=Ke;function B(e,t){if(e===0||!Number.isInteger(e))throw Error(`Columns must be an integer !== 0.`);if(t<0||!Number.isInteger(t))throw Error(`Position must be a non-negative integer.`+t);return e<0?{px:t,py:0}:e===1?{px:0,py:t}:{px:t%e,py:Math.floor(t/e)}}e(B,`calculateBlockPosition`);var Ye=e(e=>{let n=0,r=0;for(let i of e.children){let{width:e,height:a,x:o,y:s}=i.size??{width:0,height:0,x:0,y:0};if(t.debug(`getMaxChildSize abc95 child:`,i.id,`width:`,e,`height:`,a,`x:`,o,`y:`,s,i.type),i.type===`space`)continue;let c=e/(i.widthInColumns??1);c>n&&(n=c),a>r&&(r=a)}return{width:n,height:r}},`getMaxChildSize`);function V(e,n,r=0,i=0,a=8){t.debug(`setBlockSizes abc95 (start)`,e.id,e?.size?.x,`block width =`,e?.size,`siblingWidth`,r),e?.size?.width||(e.size={width:r,height:i,x:0,y:0});let o=0,s=0;if(e.children?.length>0){for(let t of e.children)V(t,n,0,0,a);let c=Ye(e);o=c.width,s=c.height,t.debug(`setBlockSizes abc95 maxWidth of`,e.id,`:s children is `,o,s);for(let n of e.children)n.size&&(t.debug(`abc95 Setting size of children of ${e.id} id=${n.id} ${o} ${s} ${JSON.stringify(n.size)}`),n.size.width=o*(n.widthInColumns??1)+a*((n.widthInColumns??1)-1),n.size.height=s,n.size.x=0,n.size.y=0,t.debug(`abc95 updating size of ${e.id} children child:${n.id} maxWidth:${o} maxHeight:${s}`));for(let t of e.children)V(t,n,o,s,a);let l=e.columns??-1,u=0;for(let t of e.children)u+=t.widthInColumns??1;let d=e.children.length;l>0&&l0?Math.min(e.children.length,l):e.children.length;if(n>0){let r=(p-n*a-a)/n;t.debug(`abc95 (growing to fit) width`,e.id,p,e.size?.width,r);for(let t of e.children)t.size&&(t.size.width=r)}}e.size={width:p,height:m,x:0,y:0}}t.debug(`setBlockSizes abc94 (done)`,e.id,e?.size?.x,e?.size?.width,e?.size?.y,e?.size?.height)}e(V,`setBlockSizes`);function H(e,n,r=8){t.debug(`abc85 layout blocks (=>layoutBlocks) ${e.id} x: ${e?.size?.x} y: ${e?.size?.y} width: ${e?.size?.width}`);let i=e.columns??-1;if(t.debug(`layoutBlocks columns abc95`,e.id,`=>`,i,e),e.children&&e.children.length>0){let a=e?.children[0]?.size?.width??0,o=e.children.length*a+(e.children.length-1)*r;t.debug(`widthOfChildren 88`,o,`posX`);let s=new Map;{let t=0;for(let n of e.children){if(!n.size)continue;let{py:e}=B(i,t),r=s.get(e)??0;n.size.height>r&&s.set(e,n.size.height);let a=n?.widthInColumns??1;i>0&&(a=Math.min(a,i-t%i)),t+=a}}let c=new Map;{let e=0,t=[...s.keys()].sort((e,t)=>e-t);for(let n of t)c.set(n,e),e+=(s.get(n)??0)+r}let l=0;t.debug(`abc91 block?.size?.x`,e.id,e?.size?.x);let u=e?.size?.x?e?.size?.x+(-e?.size?.width/2||0):-r,d=0;for(let a of e.children){let o=e;if(!a.size)continue;let{width:f,height:p}=a.size,{px:m,py:h}=B(i,l);if(h!=d&&(d=h,u=e?.size?.x?e?.size?.x+(-e?.size?.width/2||0):-r,t.debug(`New row in layout for block`,e.id,` and child `,a.id,d)),t.debug(`abc89 layout blocks (child) id: ${a.id} Pos: ${l} (px, py) ${m},${h} (${o?.size?.x},${o?.size?.y}) parent: ${o.id} width: ${f}${r}`),o.size){let e=f/2;a.size.x=u+r+e,t.debug(`abc91 layout blocks (calc) px, pyid:${a.id} startingPos=X${u} new startingPosX${a.size.x} ${e} padding=${r} width=${f} halfWidth=${e} => x:${a.size.x} y:${a.size.y} ${a.widthInColumns} (width * (child?.w || 1)) / 2 ${f*(a?.widthInColumns??1)/2}`),u=a.size.x+e;let n=c.get(h)??0,i=s.get(h)??p;a.size.y=o.size.y-o.size.height/2+n+i/2+r,t.debug(`abc88 layout blocks (calc) px, pyid:${a.id}startingPosX${u}${r}${e}=>x:${a.size.x}y:${a.size.y}${a.widthInColumns}(width * (child?.w || 1)) / 2${f*(a?.widthInColumns??1)/2}`)}a.children&&H(a,n,r);let g=a?.widthInColumns??1;i>0&&(g=Math.min(g,i-l%i)),l+=g,t.debug(`abc88 columnsPos`,a,l)}}t.debug(`layout blocks (<==layoutBlocks) ${e.id} x: ${e?.size?.x} y: ${e?.size?.y} width: ${e?.size?.width}`)}e(H,`layoutBlocks`);function Xe(e,{minX:t,minY:n,maxX:r,maxY:i}={minX:0,minY:0,maxX:0,maxY:0}){if(e.size&&e.id!==`root`){let{x:a,y:o,width:s,height:c}=e.size;a-s/2r&&(r=a+s/2),o+c/2>i&&(i=o+c/2)}if(e.children)for(let a of e.children)({minX:t,minY:n,maxX:r,maxY:i}=Xe(a,{minX:t,minY:n,maxX:r,maxY:i}));return{minX:t,minY:n,maxX:r,maxY:i}}e(Xe,`findBounds`);function Ze(e){let n=e.getBlock(`root`);if(!n)return;let r=u()?.block?.padding??8;V(n,e,0,0,r),H(n,e,r),t.debug(`getBlocks`,JSON.stringify(n,null,2));let{minX:i,minY:a,maxX:o,maxY:s}=Xe(n),c=s-a;return{x:i,y:a,width:o-i,height:c}}e(Ze,`layout`);var U=e(async(e,t,n,r=!1,a=!1)=>{let o=t||``;typeof o==`object`&&(o=o[0]);let s=u(),c=i(s);return await P(e,o,{style:n,isTitle:r,useHtmlLabels:c,markdown:!1,isNode:a,width:1/0},s)},`createLabel`),Qe=e((e,t,n,r,i)=>{t.arrowTypeStart&&et(e,`start`,t.arrowTypeStart,n,r,i),t.arrowTypeEnd&&et(e,`end`,t.arrowTypeEnd,n,r,i)},`addEdgeMarkers`),$e={arrow_cross:`cross`,arrow_point:`point`,arrow_barb:`barb`,arrow_circle:`circle`,aggregation:`aggregation`,extension:`extension`,composition:`composition`,dependency:`dependency`,lollipop:`lollipop`},et=e((e,n,r,i,a,o)=>{let s=$e[r];if(!s){t.warn(`Unknown arrow type: ${r}`);return}let c=n===`start`?`Start`:`End`;e.attr(`marker-${n}`,`url(${i}#${a}_${o}-${s}${c})`)},`addEdgeMarker`),tt={},W={},nt=e(async(e,t)=>{let r=u(),a=i(r),o=e.insert(`g`).attr(`class`,`edgeLabel`),s=o.insert(`g`).attr(`class`,`label`),c=t.labelType===`markdown`,l=await P(e,t.label,{style:t.labelStyle,useHtmlLabels:a,addSvgBackground:c,isNode:!1,markdown:c,width:c?void 0:1/0},r);s.node().appendChild(l);let d=l.getBBox(),f=d;if(a){let e=l.children[0],t=n(l);d=e.getBoundingClientRect(),f=d,t.attr(`width`,d.width),t.attr(`height`,d.height)}else{let e=n(l).select(`text`).node();e&&typeof e.getBBox==`function`&&(f=e.getBBox())}s.attr(`transform`,F(f,a)),tt[t.id]=o,t.width=d.width,t.height=d.height;let p;if(t.startLabelLeft){let r=e.insert(`g`).attr(`class`,`edgeTerminals`),i=r.insert(`g`).attr(`class`,`inner`),o=await U(i,t.startLabelLeft,t.labelStyle);p=o;let s=o.getBBox();if(a){let e=o.children[0],t=n(o);s=e.getBoundingClientRect(),t.attr(`width`,s.width),t.attr(`height`,s.height)}i.attr(`transform`,F(s,a)),W[t.id]||(W[t.id]={}),W[t.id].startLeft=r,G(p,t.startLabelLeft)}if(t.startLabelRight){let r=e.insert(`g`).attr(`class`,`edgeTerminals`),i=r.insert(`g`).attr(`class`,`inner`),o=await U(i,t.startLabelRight,t.labelStyle);p=o;let s=o.getBBox();if(a){let e=o.children[0],t=n(o);s=e.getBoundingClientRect(),t.attr(`width`,s.width),t.attr(`height`,s.height)}i.attr(`transform`,F(s,a)),W[t.id]||(W[t.id]={}),W[t.id].startRight=r,G(p,t.startLabelRight)}if(t.endLabelLeft){let r=e.insert(`g`).attr(`class`,`edgeTerminals`),i=r.insert(`g`).attr(`class`,`inner`),o=await U(r,t.endLabelLeft,t.labelStyle);p=o;let s=o.getBBox();if(a){let e=o.children[0],t=n(o);s=e.getBoundingClientRect(),t.attr(`width`,s.width),t.attr(`height`,s.height)}i.attr(`transform`,F(s,a)),W[t.id]||(W[t.id]={}),W[t.id].endLeft=r,G(p,t.endLabelLeft)}if(t.endLabelRight){let r=e.insert(`g`).attr(`class`,`edgeTerminals`),i=r.insert(`g`).attr(`class`,`inner`),o=await U(r,t.endLabelRight,t.labelStyle);p=o;let s=o.getBBox();if(a){let e=o.children[0],t=n(o);s=e.getBoundingClientRect(),t.attr(`width`,s.width),t.attr(`height`,s.height)}i.attr(`transform`,F(s,a)),W[t.id]||(W[t.id]={}),W[t.id].endRight=r,G(p,t.endLabelRight)}return l},`insertEdgeLabel`);function G(e,t){i(u())&&e&&(e.style.width=t.length*9+`px`,e.style.height=`12px`)}e(G,`setTerminalWidth`);var rt=e((e,n)=>{t.debug(`Moving label abc88 `,e.id,e.label,tt[e.id],n);let r=n.updatedPath?n.updatedPath:n.originalPath,{subGraphTitleTotalMargin:i}=de(u());if(e.label){let a=tt[e.id],o=e.x,s=e.y;if(r){let i=N.calcLabelPosition(r);t.debug(`Moving label `+e.label+` from (`,o,`,`,s,`) to (`,i.x,`,`,i.y,`) abc88`),n.updatedPath&&(o=i.x,s=i.y)}a.attr(`transform`,`translate(${o}, ${s+i/2})`)}if(e.startLabelLeft){let t=W[e.id].startLeft,n=e.x,i=e.y;if(r){let t=N.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_left`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.startLabelRight){let t=W[e.id].startRight,n=e.x,i=e.y;if(r){let t=N.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_right`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.endLabelLeft){let t=W[e.id].endLeft,n=e.x,i=e.y;if(r){let t=N.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_left`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.endLabelRight){let t=W[e.id].endRight,n=e.x,i=e.y;if(r){let t=N.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_right`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}},`positionEdgeLabel`),it=e((e,t)=>{let n=e.x,r=e.y,i=Math.abs(t.x-n),a=Math.abs(t.y-r),o=e.width/2,s=e.height/2;return i>=o||a>=s},`outsideNode`),at=e((e,n,r)=>{t.debug(`intersection calc abc89: + outsidePoint: ${JSON.stringify(n)} + insidePoint : ${JSON.stringify(r)} + node : x:${e.x} y:${e.y} w:${e.width} h:${e.height}`);let i=e.x,a=e.y,o=Math.abs(i-r.x),s=e.width/2,c=r.xMath.abs(i-n.x)*l){let e=r.y{t.debug(`abc88 cutPathAtIntersect`,e,n);let r=[],i=e[0],a=!1;return e.forEach(e=>{if(!it(n,e)&&!a){let t=at(n,i,e),o=!1;r.forEach(e=>{o||=e.x===t.x&&e.y===t.y}),r.some(e=>e.x===t.x&&e.y===t.y)||r.push(t),a=!0}else i=e,a||r.push(e)}),r},`cutPathAtIntersect`),st=e(function(e,n,i,a,o,s,c){let l=i.points;t.debug(`abc88 InsertEdge: edge=`,i,`e=`,n);let d=!1,f=s.node(n.v);var p=s.node(n.w);p?.intersect&&f?.intersect&&(l=l.slice(1,i.points.length-1),l.unshift(f.intersect(l[0])),l.push(p.intersect(l[l.length-1]))),i.toCluster&&(t.debug(`to cluster abc88`,a[i.toCluster]),l=ot(i.points,a[i.toCluster].node),d=!0),i.fromCluster&&(t.debug(`from cluster abc88`,a[i.fromCluster]),l=ot(l.reverse(),a[i.fromCluster].node).reverse(),d=!0);let m=l.filter(e=>!Number.isNaN(e.y)),h=te;i.curve&&(o===`graph`||o===`flowchart`)&&(h=i.curve);let{x:g,y:_}=ue(i),v=ce().x(g).y(_).curve(h),y;switch(i.thickness){case`normal`:y=`edge-thickness-normal`;break;case`thick`:y=`edge-thickness-thick`;break;case`invisible`:y=`edge-thickness-thick`;break;default:y=``}switch(i.pattern){case`solid`:y+=` edge-pattern-solid`;break;case`dotted`:y+=` edge-pattern-dotted`;break;case`dashed`:y+=` edge-pattern-dashed`;break}let b=e.append(`path`).attr(`d`,v(m)).attr(`id`,i.id).attr(`class`,` `+y+(i.classes?` `+i.classes:``)).attr(`style`,i.style),x=``;(u().flowchart.arrowMarkerAbsolute||u().state.arrowMarkerAbsolute)&&(x=r(!0)),Qe(b,i,x,c,o);let S={};return d&&(S.updatedPath=l),S.originalPath=i.points,S},`insertEdge`),ct=e(e=>{let t=new Set;for(let n of e)switch(n){case`x`:t.add(`right`),t.add(`left`);break;case`y`:t.add(`up`),t.add(`down`);break;default:t.add(n);break}return t},`expandAndDeduplicateDirections`),lt=e((e,t,n,r)=>{let i=ct(e),a=t.height+2*n.padding,o=a/2,s=r??t.width+2*o+n.padding,c=n.padding/2;return i.has(`right`)&&i.has(`left`)&&i.has(`up`)&&i.has(`down`)?[{x:0,y:0},{x:o,y:0},{x:s/2,y:2*c},{x:s-o,y:0},{x:s,y:0},{x:s,y:-a/3},{x:s+2*c,y:-a/2},{x:s,y:-2*a/3},{x:s,y:-a},{x:s-o,y:-a},{x:s/2,y:-a-2*c},{x:o,y:-a},{x:0,y:-a},{x:0,y:-2*a/3},{x:-2*c,y:-a/2},{x:0,y:-a/3}]:i.has(`right`)&&i.has(`left`)&&i.has(`up`)?[{x:o,y:0},{x:s-o,y:0},{x:s,y:-a/2},{x:s-o,y:-a},{x:o,y:-a},{x:0,y:-a/2}]:i.has(`right`)&&i.has(`left`)&&i.has(`down`)?[{x:0,y:0},{x:o,y:-a},{x:s-o,y:-a},{x:s,y:0}]:i.has(`right`)&&i.has(`up`)&&i.has(`down`)?[{x:0,y:0},{x:s,y:-o},{x:s,y:-a+o},{x:0,y:-a}]:i.has(`left`)&&i.has(`up`)&&i.has(`down`)?[{x:s,y:0},{x:0,y:-o},{x:0,y:-a+o},{x:s,y:-a}]:i.has(`right`)&&i.has(`left`)?[{x:o,y:0},{x:o,y:-c},{x:s-o,y:-c},{x:s-o,y:0},{x:s,y:-a/2},{x:s-o,y:-a},{x:s-o,y:-a+c},{x:o,y:-a+c},{x:o,y:-a},{x:0,y:-a/2}]:i.has(`up`)&&i.has(`down`)?[{x:s/2,y:0},{x:0,y:-c},{x:o,y:-c},{x:o,y:-a+c},{x:0,y:-a+c},{x:s/2,y:-a},{x:s,y:-a+c},{x:s-o,y:-a+c},{x:s-o,y:-c},{x:s,y:-c}]:i.has(`right`)&&i.has(`up`)?[{x:0,y:0},{x:s,y:-o},{x:0,y:-a}]:i.has(`right`)&&i.has(`down`)?[{x:0,y:0},{x:s,y:0},{x:0,y:-a}]:i.has(`left`)&&i.has(`up`)?[{x:s,y:0},{x:0,y:-o},{x:s,y:-a}]:i.has(`left`)&&i.has(`down`)?[{x:s,y:0},{x:0,y:0},{x:s,y:-a}]:i.has(`right`)?[{x:o,y:-c},{x:o,y:-c},{x:s-o,y:-c},{x:s-o,y:0},{x:s,y:-a/2},{x:s-o,y:-a},{x:s-o,y:-a+c},{x:o,y:-a+c},{x:o,y:-a+c}]:i.has(`left`)?[{x:o,y:0},{x:o,y:-c},{x:s-o,y:-c},{x:s-o,y:-a+c},{x:o,y:-a+c},{x:o,y:-a},{x:0,y:-a/2}]:i.has(`up`)?[{x:o,y:-c},{x:o,y:-a+c},{x:0,y:-a+c},{x:s/2,y:-a},{x:s,y:-a+c},{x:s-o,y:-a+c},{x:s-o,y:-c}]:i.has(`down`)?[{x:s/2,y:0},{x:0,y:-c},{x:o,y:-c},{x:o,y:-a+c},{x:s-o,y:-a+c},{x:s-o,y:-c},{x:s,y:-c}]:[{x:0,y:0}]},`getArrowPoints`);function ut(e,t){return e.intersect(t)}e(ut,`intersectNode`);var dt=ut;function ft(e,t,n,r){var i=e.x,a=e.y,o=i-r.x,s=a-r.y,c=Math.sqrt(t*t*s*s+n*n*o*o),l=Math.abs(t*n*o/c);r.x0}e(_t,`sameSign`);var vt=gt,yt=bt;function bt(e,t,n){var r=e.x,i=e.y,a=[],o=1/0,s=1/0;typeof t.forEach==`function`?t.forEach(function(e){o=Math.min(o,e.x),s=Math.min(s,e.y)}):(o=Math.min(o,t.x),s=Math.min(s,t.y));for(var c=r-e.width/2-o,l=i-e.height/2-s,u=0;u1&&a.sort(function(e,t){var r=e.x-n.x,i=e.y-n.y,a=Math.sqrt(r*r+i*i),o=t.x-n.x,s=t.y-n.y,c=Math.sqrt(o*o+s*s);return a{var n=e.x,r=e.y,i=t.x-n,a=t.y-r,o=e.width/2,s=e.height/2,c,l;return Math.abs(a)*o>Math.abs(i)*s?(a<0&&(s=-s),c=a===0?0:s*i/a,l=s):(i<0&&(o=-o),c=o,l=i===0?0:o*a/i),{x:n+c,y:r+l}},`intersectRect`)},q=e(async(e,t,r,a)=>{let o=u(),s,c=t.useHtmlLabels||i(o);s=r||`node default`;let l=e.insert(`g`).attr(`class`,s).attr(`id`,t.domId||t.id),f=l.insert(`g`).attr(`class`,`label`).attr(`style`,t.labelStyle),p;p=t.labelText===void 0?``:typeof t.labelText==`string`?t.labelText:t.labelText[0];let m;m=t.labelType===`markdown`?P(f,d(M(p),o),{useHtmlLabels:c,width:t.width||o.flowchart.wrappingWidth,classes:`markdown-node-label`},o):await U(f,d(M(p),o),t.labelStyle,!1,a);let h=m.getBBox(),g=t.padding/2;if(i(o)){let e=m.children[0],t=n(m);await fe(e,p),h=e.getBoundingClientRect(),t.attr(`width`,h.width),t.attr(`height`,h.height)}return c?f.attr(`transform`,`translate(`+-h.width/2+`, `+-h.height/2+`)`):f.attr(`transform`,`translate(0, `+-h.height/2+`)`),t.centerLabel&&f.attr(`transform`,`translate(`+-h.width/2+`, `+-h.height/2+`)`),f.insert(`rect`,`:first-child`),{shapeSvg:l,bbox:h,halfPadding:g,label:f}},`labelHelper`),J=e((e,t)=>{let n=t.node().getBBox();e.width=n.width,e.height=n.height},`updateNodeBounds`);function Y(e,t,n,r){return e.insert(`polygon`,`:first-child`).attr(`points`,r.map(function(e){return e.x+`,`+e.y}).join(` `)).attr(`class`,`label-container`).attr(`transform`,`translate(`+-t/2+`,`+n/2+`)`)}e(Y,`insertPolygonShape`);var xt=e(async(e,n)=>{n.useHtmlLabels||i(u())||(n.centerLabel=!0);let{shapeSvg:r,bbox:a,halfPadding:o}=await q(e,n,`node `+n.classes,!0);t.info(`Classes = `,n.classes);let s=r.insert(`rect`,`:first-child`);return s.attr(`rx`,n.rx).attr(`ry`,n.ry).attr(`x`,-a.width/2-o).attr(`y`,-a.height/2-o).attr(`width`,a.width+n.padding).attr(`height`,a.height+n.padding),J(n,s),n.intersect=function(e){return K.rect(n,e)},r},`note`),St=e(e=>e?` `+e:``,`formatClass`),X=e((e,t)=>`${t||`node default`}${St(e.classes)} ${St(e.class)}`,`getClassesFromNode`),Ct=e(async(e,n)=>{let{shapeSvg:r,bbox:i}=await q(e,n,X(n,void 0),!0),a=i.width+n.padding+(i.height+n.padding),o=[{x:a/2,y:0},{x:a,y:-a/2},{x:a/2,y:-a},{x:0,y:-a/2}];t.info(`Question main (Circle)`);let s=Y(r,a,a,o);return s.attr(`style`,n.style),J(n,s),n.intersect=function(e){return t.warn(`Intersect called`),K.polygon(n,o,e)},r},`question`),wt=e((e,t)=>{let n=e.insert(`g`).attr(`class`,`node default`).attr(`id`,t.domId||t.id);return n.insert(`polygon`,`:first-child`).attr(`points`,[{x:0,y:28/2},{x:28/2,y:0},{x:0,y:-28/2},{x:-28/2,y:0}].map(function(e){return e.x+`,`+e.y}).join(` `)).attr(`class`,`state-start`).attr(`r`,7).attr(`width`,28).attr(`height`,28),t.width=28,t.height=28,t.intersect=function(e){return K.circle(t,14,e)},n},`choice`),Tt=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,X(t,void 0),!0),i=t.positioned?t.height:r.height+t.padding,a=i/4,o=t.positioned?t.width:r.width+2*a+t.padding,s=[{x:a,y:0},{x:o-a,y:0},{x:o,y:-i/2},{x:o-a,y:-i},{x:a,y:-i},{x:0,y:-i/2}],c=Y(n,o,i,s);return c.attr(`style`,t.style),J(t,c),t.intersect=function(e){return K.polygon(t,s,e)},n},`hexagon`),Et=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,void 0,!0),i=r.height+2*t.padding,a=i/2,o=r.width+2*a+t.padding,s=t.positioned&&(t.widthInColumns??1)>1&&t.width>o?t.width:o,c=lt(t.directions,r,t,s),l=Y(n,s,i,c);return l.attr(`style`,t.style),J(t,l),t.intersect=function(e){return K.polygon(t,c,e)},n},`block_arrow`),Dt=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,X(t,void 0),!0),i=r.width+t.padding,a=r.height+t.padding,o=[{x:-a/2,y:0},{x:i,y:0},{x:i,y:-a},{x:-a/2,y:-a},{x:0,y:-a/2}];return Y(n,i,a,o).attr(`style`,t.style),t.width=i+a,t.height=a,t.intersect=function(e){return K.polygon(t,o,e)},n},`rect_left_inv_arrow`),Ot=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,X(t),!0),i=r.width+t.padding,a=r.height+t.padding,o=[{x:-2*a/6,y:0},{x:i-a/6,y:0},{x:i+2*a/6,y:-a},{x:a/6,y:-a}],s=Y(n,i,a,o);return s.attr(`style`,t.style),J(t,s),t.intersect=function(e){return K.polygon(t,o,e)},n},`lean_right`),kt=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,X(t,void 0),!0),i=r.width+t.padding,a=r.height+t.padding,o=[{x:2*a/6,y:0},{x:i+a/6,y:0},{x:i-2*a/6,y:-a},{x:-a/6,y:-a}],s=Y(n,i,a,o);return s.attr(`style`,t.style),J(t,s),t.intersect=function(e){return K.polygon(t,o,e)},n},`lean_left`),At=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,X(t,void 0),!0),i=r.width+t.padding,a=r.height+t.padding,o=[{x:-2*a/6,y:0},{x:i+2*a/6,y:0},{x:i-a/6,y:-a},{x:a/6,y:-a}],s=Y(n,i,a,o);return s.attr(`style`,t.style),J(t,s),t.intersect=function(e){return K.polygon(t,o,e)},n},`trapezoid`),jt=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,X(t,void 0),!0),i=r.width+t.padding,a=r.height+t.padding,o=[{x:a/6,y:0},{x:i-a/6,y:0},{x:i+2*a/6,y:-a},{x:-2*a/6,y:-a}],s=Y(n,i,a,o);return s.attr(`style`,t.style),J(t,s),t.intersect=function(e){return K.polygon(t,o,e)},n},`inv_trapezoid`),Mt=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,X(t,void 0),!0),i=r.width+t.padding,a=r.height+t.padding,o=[{x:0,y:0},{x:i+a/2,y:0},{x:i,y:-a/2},{x:i+a/2,y:-a},{x:0,y:-a}],s=Y(n,i,a,o);return s.attr(`style`,t.style),J(t,s),t.intersect=function(e){return K.polygon(t,o,e)},n},`rect_right_inv_arrow`),Nt=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,X(t,void 0),!0),i=r.width+t.padding,a=i/2,o=a/(2.5+i/50),s=r.height+o+t.padding,c=`M 0,`+o+` a `+a+`,`+o+` 0,0,0 `+i+` 0 a `+a+`,`+o+` 0,0,0 `+-i+` 0 l 0,`+s+` a `+a+`,`+o+` 0,0,0 `+i+` 0 l 0,`+-s;return J(t,n.attr(`label-offset-y`,o).insert(`path`,`:first-child`).attr(`style`,t.style).attr(`d`,c).attr(`transform`,`translate(`+-i/2+`,`+-(s/2+o)+`)`)),t.intersect=function(e){let n=K.rect(t,e),r=n.x-t.x;if(a!=0&&(Math.abs(r)t.height/2-o)){let i=o*o*(1-r*r/(a*a));i!=0&&(i=Math.sqrt(i)),i=o-i,e.y-t.y>0&&(i=-i),n.y+=i}return n},n},`cylinder`),Pt=e(async(e,n)=>{let{shapeSvg:r,bbox:i,halfPadding:a}=await q(e,n,`node `+n.classes+` `+n.class,!0),o=r.insert(`rect`,`:first-child`),s=n.positioned?n.width:i.width+n.padding,c=n.positioned?n.height:i.height+n.padding,l=n.positioned?-s/2:-i.width/2-a,u=n.positioned?-c/2:-i.height/2-a;if(o.attr(`class`,`basic label-container`).attr(`style`,n.style).attr(`rx`,n.rx).attr(`ry`,n.ry).attr(`x`,l).attr(`y`,u).attr(`width`,s).attr(`height`,c),n.props){let e=new Set(Object.keys(n.props));n.props.borders&&(Z(o,n.props.borders,s,c),e.delete(`borders`)),e.forEach(e=>{t.warn(`Unknown node property ${e}`)})}return J(n,o),n.intersect=function(e){return K.rect(n,e)},r},`rect`),Ft=e(async(e,n)=>{let{shapeSvg:r,bbox:i,halfPadding:a}=await q(e,n,`node `+n.classes,!0),o=r.insert(`rect`,`:first-child`),s=n.positioned?n.width:i.width+n.padding,c=n.positioned?n.height:i.height+n.padding,l=n.positioned?-s/2:-i.width/2-a,u=n.positioned?-c/2:-i.height/2-a;if(o.attr(`class`,`basic cluster composite label-container`).attr(`style`,n.style).attr(`rx`,n.rx).attr(`ry`,n.ry).attr(`x`,l).attr(`y`,u).attr(`width`,s).attr(`height`,c),n.props){let e=new Set(Object.keys(n.props));n.props.borders&&(Z(o,n.props.borders,s,c),e.delete(`borders`)),e.forEach(e=>{t.warn(`Unknown node property ${e}`)})}return J(n,o),n.intersect=function(e){return K.rect(n,e)},r},`composite`),It=e(async(e,n)=>{let{shapeSvg:r}=await q(e,n,`label`,!0);t.trace(`Classes = `,n.class);let i=r.insert(`rect`,`:first-child`);if(i.attr(`width`,0).attr(`height`,0),r.attr(`class`,`label edgeLabel`),n.props){let e=new Set(Object.keys(n.props));n.props.borders&&(Z(i,n.props.borders,0,0),e.delete(`borders`)),e.forEach(e=>{t.warn(`Unknown node property ${e}`)})}return J(n,i),n.intersect=function(e){return K.rect(n,e)},r},`labelRect`);function Z(n,r,i,a){let o=[],s=e(e=>{o.push(e,0)},`addBorder`),c=e(e=>{o.push(0,e)},`skipBorder`);r.includes(`t`)?(t.debug(`add top border`),s(i)):c(i),r.includes(`r`)?(t.debug(`add right border`),s(a)):c(a),r.includes(`b`)?(t.debug(`add bottom border`),s(i)):c(i),r.includes(`l`)?(t.debug(`add left border`),s(a)):c(a),n.attr(`stroke-dasharray`,o.join(` `))}e(Z,`applyNodePropertyBorders`);var Lt=e(async(e,r)=>{let a;a=r.classes?`node `+r.classes:`node default`;let o=e.insert(`g`).attr(`class`,a).attr(`id`,r.domId||r.id),s=o.insert(`rect`,`:first-child`),c=o.insert(`line`),l=o.insert(`g`).attr(`class`,`label`),d=r.labelText.flat?r.labelText.flat():r.labelText,f=``;f=typeof d==`object`?d[0]:d,t.info(`Label text abc79`,f,d,typeof d==`object`);let p=await U(l,f,r.labelStyle,!0,!0),m={width:0,height:0};if(i(u())){let e=p.children[0],t=n(p);m=e.getBoundingClientRect(),t.attr(`width`,m.width),t.attr(`height`,m.height)}t.info(`Text 2`,d);let h=d.slice(1,d.length),g=p.getBBox(),_=await U(l,h.join?h.join(`
    `):h,r.labelStyle,!0,!0);if(i(u())){let e=_.children[0],t=n(_);m=e.getBoundingClientRect(),t.attr(`width`,m.width),t.attr(`height`,m.height)}let v=r.padding/2;return n(_).attr(`transform`,`translate( `+(m.width>g.width?0:(g.width-m.width)/2)+`, `+(g.height+v+5)+`)`),n(p).attr(`transform`,`translate( `+(m.width{let{shapeSvg:n,bbox:r}=await q(e,t,X(t,void 0),!0),i=r.height+t.padding,a=r.width+i/4+t.padding;return J(t,n.insert(`rect`,`:first-child`).attr(`style`,t.style).attr(`rx`,i/2).attr(`ry`,i/2).attr(`x`,-a/2).attr(`y`,-i/2).attr(`width`,a).attr(`height`,i)),t.intersect=function(e){return K.rect(t,e)},n},`stadium`),zt=e(async(e,n)=>{let{shapeSvg:r,bbox:i,halfPadding:a}=await q(e,n,X(n,void 0),!0),o=r.insert(`circle`,`:first-child`);return o.attr(`style`,n.style).attr(`rx`,n.rx).attr(`ry`,n.ry).attr(`r`,i.width/2+a).attr(`width`,i.width+n.padding).attr(`height`,i.height+n.padding),t.info(`Circle main`),J(n,o),n.intersect=function(e){return t.info(`Circle intersect`,n,i.width/2+a,e),K.circle(n,i.width/2+a,e)},r},`circle`),Bt=e(async(e,n)=>{let{shapeSvg:r,bbox:i,halfPadding:a}=await q(e,n,X(n,void 0),!0),o=r.insert(`g`,`:first-child`),s=o.insert(`circle`),c=o.insert(`circle`);return o.attr(`class`,n.class),s.attr(`style`,n.style).attr(`rx`,n.rx).attr(`ry`,n.ry).attr(`r`,i.width/2+a+5).attr(`width`,i.width+n.padding+10).attr(`height`,i.height+n.padding+10),c.attr(`style`,n.style).attr(`rx`,n.rx).attr(`ry`,n.ry).attr(`r`,i.width/2+a).attr(`width`,i.width+n.padding).attr(`height`,i.height+n.padding),t.info(`DoubleCircle main`),J(n,s),n.intersect=function(e){return t.info(`DoubleCircle intersect`,n,i.width/2+a+5,e),K.circle(n,i.width/2+a+5,e)},r},`doublecircle`),Vt=e(async(e,t)=>{let{shapeSvg:n,bbox:r}=await q(e,t,X(t,void 0),!0),i=r.width+t.padding,a=r.height+t.padding,o=[{x:0,y:0},{x:i,y:0},{x:i,y:-a},{x:0,y:-a},{x:0,y:0},{x:-8,y:0},{x:i+8,y:0},{x:i+8,y:-a},{x:-8,y:-a},{x:-8,y:0}],s=Y(n,i,a,o);return s.attr(`style`,t.style),J(t,s),t.intersect=function(e){return K.polygon(t,o,e)},n},`subroutine`),Ht=e((e,t)=>{let n=e.insert(`g`).attr(`class`,`node default`).attr(`id`,t.domId||t.id),r=n.insert(`circle`,`:first-child`);return r.attr(`class`,`state-start`).attr(`r`,7).attr(`width`,14).attr(`height`,14),J(t,r),t.intersect=function(e){return K.circle(t,7,e)},n},`start`),Ut=e((e,t,n)=>{let r=e.insert(`g`).attr(`class`,`node default`).attr(`id`,t.domId||t.id),i=70,a=10;return n===`LR`&&(i=10,a=70),J(t,r.append(`rect`).attr(`x`,-1*i/2).attr(`y`,-1*a/2).attr(`width`,i).attr(`height`,a).attr(`class`,`fork-join`)),t.height+=t.padding/2,t.width+=t.padding/2,t.intersect=function(e){return K.rect(t,e)},r},`forkJoin`),Wt={rhombus:Ct,composite:Ft,question:Ct,rect:Pt,labelRect:It,rectWithTitle:Lt,choice:wt,circle:zt,doublecircle:Bt,stadium:Rt,hexagon:Tt,block_arrow:Et,rect_left_inv_arrow:Dt,lean_right:Ot,lean_left:kt,trapezoid:At,inv_trapezoid:jt,rect_right_inv_arrow:Mt,cylinder:Nt,start:Ht,end:e((e,t)=>{let n=e.insert(`g`).attr(`class`,`node default`).attr(`id`,t.domId||t.id),r=n.insert(`circle`,`:first-child`),i=n.insert(`circle`,`:first-child`);return i.attr(`class`,`state-start`).attr(`r`,7).attr(`width`,14).attr(`height`,14),r.attr(`class`,`state-end`).attr(`r`,5).attr(`width`,10).attr(`height`,10),J(t,i),t.intersect=function(e){return K.circle(t,7,e)},n},`end`),note:xt,subroutine:Vt,fork:Ut,join:Ut,class_box:e(async(e,t)=>{let r=t.padding/2,a;a=t.classes?`node `+t.classes:`node default`;let o=e.insert(`g`).attr(`class`,a).attr(`id`,t.domId||t.id),s=o.insert(`rect`,`:first-child`),c=o.insert(`line`),l=o.insert(`line`),d=0,f=4,p=o.insert(`g`).attr(`class`,`label`),m=0,h=t.classData.annotations?.[0],g=await U(p,t.classData.annotations[0]?`«`+t.classData.annotations[0]+`»`:``,t.labelStyle,!0,!0),_=g.getBBox();if(i(u())){let e=g.children[0],t=n(g);_=e.getBoundingClientRect(),t.attr(`width`,_.width),t.attr(`height`,_.height)}t.classData.annotations[0]&&(f+=_.height+4,d+=_.width);let v=t.classData.label;t.classData.type!==void 0&&t.classData.type!==``&&(i(u())?v+=`<`+t.classData.type+`>`:v+=`<`+t.classData.type+`>`);let y=await U(p,v,t.labelStyle,!0,!0);n(y).attr(`class`,`classTitle`);let b=y.getBBox();if(i(u())){let e=y.children[0],t=n(y);b=e.getBoundingClientRect(),t.attr(`width`,b.width),t.attr(`height`,b.height)}f+=b.height+4,b.width>d&&(d=b.width);let x=[];t.classData.members.forEach(async e=>{let r=e.getDisplayDetails(),a=r.displayText;i(u())&&(a=a.replace(//g,`>`));let o=await U(p,a,r.cssStyle?r.cssStyle:t.labelStyle,!0,!0),s=o.getBBox();if(i(u())){let e=o.children[0],t=n(o);s=e.getBoundingClientRect(),t.attr(`width`,s.width),t.attr(`height`,s.height)}s.width>d&&(d=s.width),f+=s.height+4,x.push(o)}),f+=8;let S=[];if(t.classData.methods.forEach(async e=>{let r=e.getDisplayDetails(),a=r.displayText;i(u())&&(a=a.replace(//g,`>`));let o=await U(p,a,r.cssStyle?r.cssStyle:t.labelStyle,!0,!0),s=o.getBBox();if(i(u())){let e=o.children[0],t=n(o);s=e.getBoundingClientRect(),t.attr(`width`,s.width),t.attr(`height`,s.height)}s.width>d&&(d=s.width),f+=s.height+4,S.push(o)}),f+=8,h){let e=(d-_.width)/2;n(g).attr(`transform`,`translate( `+(-1*d/2+e)+`, `+-1*f/2+`)`),m=_.height+4}let C=(d-b.width)/2;return n(y).attr(`transform`,`translate( `+(-1*d/2+C)+`, `+(-1*f/2+m)+`)`),m+=b.height+4,c.attr(`class`,`divider`).attr(`x1`,-d/2-r).attr(`x2`,d/2+r).attr(`y1`,-f/2-r+8+m).attr(`y2`,-f/2-r+8+m),m+=8,x.forEach(e=>{n(e).attr(`transform`,`translate( `+-d/2+`, `+(-1*f/2+m+8/2)+`)`);let t=e?.getBBox();m+=(t?.height??0)+4}),m+=8,l.attr(`class`,`divider`).attr(`x1`,-d/2-r).attr(`x2`,d/2+r).attr(`y1`,-f/2-r+8+m).attr(`y2`,-f/2-r+8+m),m+=8,S.forEach(e=>{n(e).attr(`transform`,`translate( `+-d/2+`, `+(-1*f/2+m)+`)`);let t=e?.getBBox();m+=(t?.height??0)+4}),s.attr(`style`,t.style).attr(`class`,`outer title-state`).attr(`x`,-d/2-r).attr(`y`,-(f/2)-r).attr(`width`,d+t.padding).attr(`height`,f+t.padding),J(t,s),t.intersect=function(e){return K.rect(t,e)},o},`class_box`)},Q={},Gt=e(async(e,t,n)=>{let r,i;if(t.link){let a;u().securityLevel===`sandbox`?a=`_top`:t.linkTarget&&(a=t.linkTarget||`_blank`),r=e.insert(`svg:a`).attr(`xlink:href`,t.link).attr(`target`,a),i=await Wt[t.shape](r,t,n)}else i=await Wt[t.shape](e,t,n),r=i;return t.tooltip&&i.attr(`title`,t.tooltip),t.class&&i.attr(`class`,`node default `+t.class),Q[t.id]=r,t.haveCallback&&Q[t.id].attr(`class`,Q[t.id].attr(`class`)+` clickable`),r},`insertNode`),Kt=e(e=>{let n=Q[e.id];t.trace(`Transforming node`,e.diff,e,`translate(`+(e.x-e.width/2-5)+`, `+e.width/2+`)`);let r=e.diff||0;return e.clusterNode?n.attr(`transform`,`translate(`+(e.x+r-e.width/2)+`, `+(e.y-e.height/2-8)+`)`):n.attr(`transform`,`translate(`+e.x+`, `+e.y+`)`),r},`positionNode`);function qt(e,t,n=!1){let r=e,i=`default`;(r?.classes?.length||0)>0&&(i=(r?.classes??[]).join(` `)),i+=` flowchart-label`;let a=0,s=``,c;switch(r.type){case`round`:a=5,s=`rect`;break;case`composite`:a=0,s=`composite`,c=0;break;case`square`:s=`rect`;break;case`diamond`:s=`question`;break;case`hexagon`:s=`hexagon`;break;case`block_arrow`:s=`block_arrow`;break;case`odd`:s=`rect_left_inv_arrow`;break;case`lean_right`:s=`lean_right`;break;case`lean_left`:s=`lean_left`;break;case`trapezoid`:s=`trapezoid`;break;case`inv_trapezoid`:s=`inv_trapezoid`;break;case`rect_left_inv_arrow`:s=`rect_left_inv_arrow`;break;case`circle`:s=`circle`;break;case`ellipse`:s=`ellipse`;break;case`stadium`:s=`stadium`;break;case`subroutine`:s=`subroutine`;break;case`cylinder`:s=`cylinder`;break;case`group`:s=`rect`;break;case`doublecircle`:s=`doublecircle`;break;default:s=`rect`}let l=ie(r?.styles??[]),u=r.label,d=r.size??{width:0,height:0,x:0,y:0},f=t.getDiagramId();return{labelStyle:l.labelStyle,shape:s,labelText:u,rx:a,ry:a,class:i,style:l.style,id:r.id,domId:f?`${f}-${r.id}`:r.id,directions:r.directions,width:d.width,height:d.height,x:d.x,y:d.y,positioned:n,intersect:void 0,type:r.type,padding:c??o()?.block?.padding??0,widthInColumns:r.widthInColumns??1}}e(qt,`getNodeFromBlock`);async function Jt(e,t,n){let r=qt(t,n,!1);if(r.type===`group`)return;let i=await Gt(e,r,{config:o()}),a=i.node().getBBox(),s=n.getBlock(r.id);s.size={width:a.width,height:a.height,x:0,y:0,node:i},n.setBlock(s),i.remove()}e(Jt,`calculateBlockSize`);async function Yt(e,t,n){let r=qt(t,n,!0);n.getBlock(r.id).type!==`space`&&(await Gt(e,r,{config:o()}),t.intersect=r?.intersect,Kt(r))}e(Yt,`insertBlockPositioned`);async function $(e,t,n,r){for(let i of t)await r(e,i,n),i.children&&await $(e,i.children,n,r)}e($,`performOperations`);async function Xt(e,t,n){await $(e,t,n,Jt)}e(Xt,`calculateBlockSizes`);async function Zt(e,t,n){await $(e,t,n,Yt)}e(Zt,`insertBlocks`);async function Qt(e,t,n,r,i){let a=new pe({multigraph:!0,compound:!0});a.setGraph({rankdir:`TB`,nodesep:10,ranksep:10,marginx:8,marginy:8});for(let e of n)e.size&&a.setNode(e.id,{width:e.size.width,height:e.size.height,intersect:e.intersect});for(let n of t)if(n.start&&n.end){let t=r.getBlock(n.start),o=r.getBlock(n.end);if(t?.size&&o?.size){let r=t.size,s=o.size,c=[{x:r.x,y:r.y},{x:r.x+(s.x-r.x)/2,y:r.y+(s.y-r.y)/2},{x:s.x,y:s.y}],l=i?`${i}-${n.id}`:n.id,u=`${n.thickness===`thick`?`edge-thickness-thick`:`edge-thickness-normal`} ${n.pattern===`dotted`?`edge-pattern-dotted`:`edge-pattern-solid`} flowchart-link LS-a1 LE-b1`;st(e,{v:n.start,w:n.end,name:l},{...n,id:l,arrowTypeEnd:n.arrowTypeEnd,arrowTypeStart:n.arrowTypeStart,points:c,classes:u},void 0,`block`,a,i),n.label&&(await nt(e,{...n,label:n.label,labelStyle:`stroke: #333; stroke-width: 1.5px;fill:none;`,arrowTypeEnd:n.arrowTypeEnd,arrowTypeStart:n.arrowTypeStart,points:c,classes:u}),rt({...n,x:c[1].x,y:c[1].y},{originalPath:c}))}}}e(Qt,`insertEdges`);var $t={parser:Se,db:We,renderer:{draw:e(async function(e,r,i,a){let{securityLevel:c,block:l}=o(),u=a.db;u.setDiagramId(r);let d;c===`sandbox`&&(d=n(`#i`+r));let f=n(c===`sandbox`?d.nodes()[0].contentDocument.body:`body`),p=c===`sandbox`?f.select(`[id="${r}"]`):n(`[id="${r}"]`);Je(p,[`point`,`circle`,`cross`],a.type,r);let m=u.getBlocks(),h=u.getBlocksFlat(),g=u.getEdges(),_=p.insert(`g`).attr(`class`,`block`);await Xt(_,m,u);let v=Ze(u);if(await Zt(_,m,u),await Qt(_,g,h,u,r),v){let e=v,n=Math.max(1,Math.round(.125*(e.width/e.height))),r=e.height+n+10,i=e.width+10,{useMaxWidth:a}=l;s(p,r,i,!!a),t.debug(`Here Bounds`,v,e),p.attr(`viewBox`,`${e.x-5} ${e.y-5} ${e.width+10} ${e.height+10}`)}},`draw`),getClasses:e(function(e,t){return t.db.getClasses()},`getClasses`)},styles:Ge};export{$t as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/c4Diagram-LMCZKHZV-B2PQ0JjZ.js b/dist-desktop/assets/c4Diagram-LMCZKHZV-B2PQ0JjZ.js new file mode 100644 index 0000000..9beb0a0 --- /dev/null +++ b/dist-desktop/assets/c4Diagram-LMCZKHZV-B2PQ0JjZ.js @@ -0,0 +1,10 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{H as r,U as i,c as a,r as o,s,v as l,x as u,y as d,z as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as p}from"./dist-qx0Iv9vM.js";import{_ as m,n as h,r as g}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{a as _,s as v}from"./chunk-32BRIVSS-DWU3ezKg.js";var y=p(),b=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,24],r=[1,25],i=[1,26],a=[1,27],o=[1,28],s=[1,63],l=[1,64],u=[1,65],d=[1,66],f=[1,67],p=[1,68],m=[1,69],h=[1,29],g=[1,30],_=[1,31],v=[1,32],y=[1,33],b=[1,34],x=[1,35],S=[1,36],C=[1,37],w=[1,38],T=[1,39],E=[1,40],D=[1,41],O=[1,42],k=[1,43],A=[1,44],j=[1,45],M=[1,46],N=[1,47],P=[1,48],F=[1,50],I=[1,51],L=[1,52],R=[1,53],z=[1,54],B=[1,55],V=[1,56],H=[1,57],ee=[1,58],te=[1,59],ne=[1,60],re=[14,42],ie=[14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],ae=[12,14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],U=[1,82],W=[1,83],G=[1,84],K=[1,85],q=[12,14,42],oe=[12,14,33,42],se=[12,14,33,42,76,77,79,80],ce=[12,33],le=[34,36,37,38,39,40,41,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],J={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,direction:5,direction_tb:6,direction_bt:7,direction_rl:8,direction_lr:9,graphConfig:10,C4_CONTEXT:11,NEWLINE:12,statements:13,EOF:14,C4_CONTAINER:15,C4_COMPONENT:16,C4_DYNAMIC:17,C4_DEPLOYMENT:18,otherStatements:19,diagramStatements:20,otherStatement:21,title:22,accDescription:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,boundaryStatement:29,boundaryStartStatement:30,boundaryStopStatement:31,boundaryStart:32,LBRACE:33,ENTERPRISE_BOUNDARY:34,attributes:35,SYSTEM_BOUNDARY:36,BOUNDARY:37,CONTAINER_BOUNDARY:38,NODE:39,NODE_L:40,NODE_R:41,RBRACE:42,diagramStatement:43,PERSON:44,PERSON_EXT:45,SYSTEM:46,SYSTEM_DB:47,SYSTEM_QUEUE:48,SYSTEM_EXT:49,SYSTEM_EXT_DB:50,SYSTEM_EXT_QUEUE:51,CONTAINER:52,CONTAINER_DB:53,CONTAINER_QUEUE:54,CONTAINER_EXT:55,CONTAINER_EXT_DB:56,CONTAINER_EXT_QUEUE:57,COMPONENT:58,COMPONENT_DB:59,COMPONENT_QUEUE:60,COMPONENT_EXT:61,COMPONENT_EXT_DB:62,COMPONENT_EXT_QUEUE:63,REL:64,BIREL:65,REL_U:66,REL_D:67,REL_L:68,REL_R:69,REL_B:70,REL_INDEX:71,UPDATE_EL_STYLE:72,UPDATE_REL_STYLE:73,UPDATE_LAYOUT_CONFIG:74,attribute:75,STR:76,STR_KEY:77,STR_VALUE:78,ATTRIBUTE:79,ATTRIBUTE_EMPTY:80,$accept:0,$end:1},terminals_:{2:`error`,6:`direction_tb`,7:`direction_bt`,8:`direction_rl`,9:`direction_lr`,11:`C4_CONTEXT`,12:`NEWLINE`,14:`EOF`,15:`C4_CONTAINER`,16:`C4_COMPONENT`,17:`C4_DYNAMIC`,18:`C4_DEPLOYMENT`,22:`title`,23:`accDescription`,24:`acc_title`,25:`acc_title_value`,26:`acc_descr`,27:`acc_descr_value`,28:`acc_descr_multiline_value`,33:`LBRACE`,34:`ENTERPRISE_BOUNDARY`,36:`SYSTEM_BOUNDARY`,37:`BOUNDARY`,38:`CONTAINER_BOUNDARY`,39:`NODE`,40:`NODE_L`,41:`NODE_R`,42:`RBRACE`,44:`PERSON`,45:`PERSON_EXT`,46:`SYSTEM`,47:`SYSTEM_DB`,48:`SYSTEM_QUEUE`,49:`SYSTEM_EXT`,50:`SYSTEM_EXT_DB`,51:`SYSTEM_EXT_QUEUE`,52:`CONTAINER`,53:`CONTAINER_DB`,54:`CONTAINER_QUEUE`,55:`CONTAINER_EXT`,56:`CONTAINER_EXT_DB`,57:`CONTAINER_EXT_QUEUE`,58:`COMPONENT`,59:`COMPONENT_DB`,60:`COMPONENT_QUEUE`,61:`COMPONENT_EXT`,62:`COMPONENT_EXT_DB`,63:`COMPONENT_EXT_QUEUE`,64:`REL`,65:`BIREL`,66:`REL_U`,67:`REL_D`,68:`REL_L`,69:`REL_R`,70:`REL_B`,71:`REL_INDEX`,72:`UPDATE_EL_STYLE`,73:`UPDATE_REL_STYLE`,74:`UPDATE_LAYOUT_CONFIG`,76:`STR`,77:`STR_KEY`,78:`STR_VALUE`,79:`ATTRIBUTE`,80:`ATTRIBUTE_EMPTY`},productions_:[0,[3,1],[3,1],[5,1],[5,1],[5,1],[5,1],[4,1],[10,4],[10,4],[10,4],[10,4],[10,4],[13,1],[13,1],[13,2],[19,1],[19,2],[19,3],[21,1],[21,1],[21,2],[21,2],[21,1],[29,3],[30,3],[30,3],[30,4],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[31,1],[20,1],[20,2],[20,3],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,1],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[35,1],[35,2],[75,1],[75,2],[75,1],[75,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 3:r.setDirection(`TB`);break;case 4:r.setDirection(`BT`);break;case 5:r.setDirection(`RL`);break;case 6:r.setDirection(`LR`);break;case 8:case 9:case 10:case 11:case 12:r.setC4Type(a[s-3]);break;case 19:r.setTitle(a[s].substring(6)),this.$=a[s].substring(6);break;case 20:r.setAccDescription(a[s].substring(15)),this.$=a[s].substring(15);break;case 21:this.$=a[s].trim(),r.setTitle(this.$);break;case 22:case 23:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 28:a[s].splice(2,0,`ENTERPRISE`),r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 29:a[s].splice(2,0,`SYSTEM`),r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 30:r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 31:a[s].splice(2,0,`CONTAINER`),r.addContainerBoundary(...a[s]),this.$=a[s];break;case 32:r.addDeploymentNode(`node`,...a[s]),this.$=a[s];break;case 33:r.addDeploymentNode(`nodeL`,...a[s]),this.$=a[s];break;case 34:r.addDeploymentNode(`nodeR`,...a[s]),this.$=a[s];break;case 35:r.popBoundaryParseStack();break;case 39:r.addPersonOrSystem(`person`,...a[s]),this.$=a[s];break;case 40:r.addPersonOrSystem(`external_person`,...a[s]),this.$=a[s];break;case 41:r.addPersonOrSystem(`system`,...a[s]),this.$=a[s];break;case 42:r.addPersonOrSystem(`system_db`,...a[s]),this.$=a[s];break;case 43:r.addPersonOrSystem(`system_queue`,...a[s]),this.$=a[s];break;case 44:r.addPersonOrSystem(`external_system`,...a[s]),this.$=a[s];break;case 45:r.addPersonOrSystem(`external_system_db`,...a[s]),this.$=a[s];break;case 46:r.addPersonOrSystem(`external_system_queue`,...a[s]),this.$=a[s];break;case 47:r.addContainer(`container`,...a[s]),this.$=a[s];break;case 48:r.addContainer(`container_db`,...a[s]),this.$=a[s];break;case 49:r.addContainer(`container_queue`,...a[s]),this.$=a[s];break;case 50:r.addContainer(`external_container`,...a[s]),this.$=a[s];break;case 51:r.addContainer(`external_container_db`,...a[s]),this.$=a[s];break;case 52:r.addContainer(`external_container_queue`,...a[s]),this.$=a[s];break;case 53:r.addComponent(`component`,...a[s]),this.$=a[s];break;case 54:r.addComponent(`component_db`,...a[s]),this.$=a[s];break;case 55:r.addComponent(`component_queue`,...a[s]),this.$=a[s];break;case 56:r.addComponent(`external_component`,...a[s]),this.$=a[s];break;case 57:r.addComponent(`external_component_db`,...a[s]),this.$=a[s];break;case 58:r.addComponent(`external_component_queue`,...a[s]),this.$=a[s];break;case 60:r.addRel(`rel`,...a[s]),this.$=a[s];break;case 61:r.addRel(`birel`,...a[s]),this.$=a[s];break;case 62:r.addRel(`rel_u`,...a[s]),this.$=a[s];break;case 63:r.addRel(`rel_d`,...a[s]),this.$=a[s];break;case 64:r.addRel(`rel_l`,...a[s]),this.$=a[s];break;case 65:r.addRel(`rel_r`,...a[s]),this.$=a[s];break;case 66:r.addRel(`rel_b`,...a[s]),this.$=a[s];break;case 67:a[s].splice(0,1),r.addRel(`rel`,...a[s]),this.$=a[s];break;case 68:r.updateElStyle(`update_el_style`,...a[s]),this.$=a[s];break;case 69:r.updateRelStyle(`update_rel_style`,...a[s]),this.$=a[s];break;case 70:r.updateLayoutConfig(`update_layout_config`,...a[s]),this.$=a[s];break;case 71:this.$=[a[s]];break;case 72:a[s].unshift(a[s-1]),this.$=a[s];break;case 73:case 75:this.$=a[s].trim();break;case 74:let e={};e[a[s-1].trim()]=a[s].trim(),this.$=e;break;case 76:this.$=``;break}},`anonymous`),table:[{3:1,4:2,5:3,6:[1,5],7:[1,6],8:[1,7],9:[1,8],10:4,11:[1,9],15:[1,10],16:[1,11],17:[1,12],18:[1,13]},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,7]},{1:[2,3]},{1:[2,4]},{1:[2,5]},{1:[2,6]},{12:[1,14]},{12:[1,15]},{12:[1,16]},{12:[1,17]},{12:[1,18]},{13:19,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:70,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:71,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:72,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{13:73,19:20,20:21,21:22,22:n,23:r,24:i,26:a,28:o,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{14:[1,74]},t(re,[2,13],{43:23,29:49,30:61,32:62,20:75,34:s,36:l,37:u,38:d,39:f,40:p,41:m,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne}),t(re,[2,14]),t(ie,[2,16],{12:[1,76]}),t(re,[2,36],{12:[1,77]}),t(ae,[2,19]),t(ae,[2,20]),{25:[1,78]},{27:[1,79]},t(ae,[2,23]),{35:80,75:81,76:U,77:W,79:G,80:K},{35:86,75:81,76:U,77:W,79:G,80:K},{35:87,75:81,76:U,77:W,79:G,80:K},{35:88,75:81,76:U,77:W,79:G,80:K},{35:89,75:81,76:U,77:W,79:G,80:K},{35:90,75:81,76:U,77:W,79:G,80:K},{35:91,75:81,76:U,77:W,79:G,80:K},{35:92,75:81,76:U,77:W,79:G,80:K},{35:93,75:81,76:U,77:W,79:G,80:K},{35:94,75:81,76:U,77:W,79:G,80:K},{35:95,75:81,76:U,77:W,79:G,80:K},{35:96,75:81,76:U,77:W,79:G,80:K},{35:97,75:81,76:U,77:W,79:G,80:K},{35:98,75:81,76:U,77:W,79:G,80:K},{35:99,75:81,76:U,77:W,79:G,80:K},{35:100,75:81,76:U,77:W,79:G,80:K},{35:101,75:81,76:U,77:W,79:G,80:K},{35:102,75:81,76:U,77:W,79:G,80:K},{35:103,75:81,76:U,77:W,79:G,80:K},{35:104,75:81,76:U,77:W,79:G,80:K},t(q,[2,59]),{35:105,75:81,76:U,77:W,79:G,80:K},{35:106,75:81,76:U,77:W,79:G,80:K},{35:107,75:81,76:U,77:W,79:G,80:K},{35:108,75:81,76:U,77:W,79:G,80:K},{35:109,75:81,76:U,77:W,79:G,80:K},{35:110,75:81,76:U,77:W,79:G,80:K},{35:111,75:81,76:U,77:W,79:G,80:K},{35:112,75:81,76:U,77:W,79:G,80:K},{35:113,75:81,76:U,77:W,79:G,80:K},{35:114,75:81,76:U,77:W,79:G,80:K},{35:115,75:81,76:U,77:W,79:G,80:K},{20:116,29:49,30:61,32:62,34:s,36:l,37:u,38:d,39:f,40:p,41:m,43:23,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne},{12:[1,118],33:[1,117]},{35:119,75:81,76:U,77:W,79:G,80:K},{35:120,75:81,76:U,77:W,79:G,80:K},{35:121,75:81,76:U,77:W,79:G,80:K},{35:122,75:81,76:U,77:W,79:G,80:K},{35:123,75:81,76:U,77:W,79:G,80:K},{35:124,75:81,76:U,77:W,79:G,80:K},{35:125,75:81,76:U,77:W,79:G,80:K},{14:[1,126]},{14:[1,127]},{14:[1,128]},{14:[1,129]},{1:[2,8]},t(re,[2,15]),t(ie,[2,17],{21:22,19:130,22:n,23:r,24:i,26:a,28:o}),t(re,[2,37],{19:20,20:21,21:22,43:23,29:49,30:61,32:62,13:131,22:n,23:r,24:i,26:a,28:o,34:s,36:l,37:u,38:d,39:f,40:p,41:m,44:h,45:g,46:_,47:v,48:y,49:b,50:x,51:S,52:C,53:w,54:T,55:E,56:D,57:O,58:k,59:A,60:j,61:M,62:N,63:P,64:F,65:I,66:L,67:R,68:z,69:B,70:V,71:H,72:ee,73:te,74:ne}),t(ae,[2,21]),t(ae,[2,22]),t(q,[2,39]),t(oe,[2,71],{75:81,35:132,76:U,77:W,79:G,80:K}),t(se,[2,73]),{78:[1,133]},t(se,[2,75]),t(se,[2,76]),t(q,[2,40]),t(q,[2,41]),t(q,[2,42]),t(q,[2,43]),t(q,[2,44]),t(q,[2,45]),t(q,[2,46]),t(q,[2,47]),t(q,[2,48]),t(q,[2,49]),t(q,[2,50]),t(q,[2,51]),t(q,[2,52]),t(q,[2,53]),t(q,[2,54]),t(q,[2,55]),t(q,[2,56]),t(q,[2,57]),t(q,[2,58]),t(q,[2,60]),t(q,[2,61]),t(q,[2,62]),t(q,[2,63]),t(q,[2,64]),t(q,[2,65]),t(q,[2,66]),t(q,[2,67]),t(q,[2,68]),t(q,[2,69]),t(q,[2,70]),{31:134,42:[1,135]},{12:[1,136]},{33:[1,137]},t(ce,[2,28]),t(ce,[2,29]),t(ce,[2,30]),t(ce,[2,31]),t(ce,[2,32]),t(ce,[2,33]),t(ce,[2,34]),{1:[2,9]},{1:[2,10]},{1:[2,11]},{1:[2,12]},t(ie,[2,18]),t(re,[2,38]),t(oe,[2,72]),t(se,[2,74]),t(q,[2,24]),t(q,[2,35]),t(le,[2,25]),t(le,[2,26],{12:[1,138]}),t(le,[2,27])],defaultActions:{2:[2,1],3:[2,2],4:[2,7],5:[2,3],6:[2,4],7:[2,5],8:[2,6],74:[2,8],126:[2,9],127:[2,10],128:[2,11],129:[2,12]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,l=``,u=0,d=0,f=0,p=2,m=1,h=o.slice.call(arguments,1),g=Object.create(this.lexer),_={yy:{}};for(var v in this.yy)Object.prototype.hasOwnProperty.call(this.yy,v)&&(_.yy[v]=this.yy[v]);g.setInput(t,_.yy),_.yy.lexer=g,_.yy.parser=this,g.yylloc===void 0&&(g.yylloc={});var y=g.yylloc;o.push(y);var b=g.options&&g.options.ranges;typeof _.yy.parseError==`function`?this.parseError=_.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function x(e){r.length-=2*e,a.length-=e,o.length-=e}e(x,`popStack`);function S(){var e=i.pop()||g.lex()||m;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(S,`lex`);for(var C,w,T,E,D,O={},k,A,j,M;;){if(T=r[r.length-1],this.defaultActions[T]?E=this.defaultActions[T]:(C??=S(),E=s[T]&&s[T][C]),E===void 0||!E.length||!E[0]){var N=``;for(k in M=[],s[T])this.terminals_[k]&&k>p&&M.push(`'`+this.terminals_[k]+`'`);N=g.showPosition?`Parse error on line `+(u+1)+`: +`+g.showPosition()+` +Expecting `+M.join(`, `)+`, got '`+(this.terminals_[C]||C)+`'`:`Parse error on line `+(u+1)+`: Unexpected `+(C==m?`end of input`:`'`+(this.terminals_[C]||C)+`'`),this.parseError(N,{text:g.match,token:this.terminals_[C]||C,line:g.yylineno,loc:y,expected:M})}if(E[0]instanceof Array&&E.length>1)throw Error(`Parse Error: multiple actions possible at state: `+T+`, token: `+C);switch(E[0]){case 1:r.push(C),a.push(g.yytext),o.push(g.yylloc),r.push(E[1]),C=null,w?(C=w,w=null):(d=g.yyleng,l=g.yytext,u=g.yylineno,y=g.yylloc,f>0&&f--);break;case 2:if(A=this.productions_[E[1]][1],O.$=a[a.length-A],O._$={first_line:o[o.length-(A||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(A||1)].first_column,last_column:o[o.length-1].last_column},b&&(O._$.range=[o[o.length-(A||1)].range[0],o[o.length-1].range[1]]),D=this.performAction.apply(O,[l,d,u,_.yy,E[1],a,o].concat(h)),D!==void 0)return D;A&&(r=r.slice(0,-1*A*2),a=a.slice(0,-1*A),o=o.slice(0,-1*A)),r.push(this.productions_[E[1]][0]),a.push(O.$),o.push(O._$),j=s[r[r.length-2]][r[r.length-1]],r.push(j);break;case 3:return!0}}return!0},`parse`)};J.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{},performAction:e(function(e,t,n,r){switch(n){case 0:return 6;case 1:return 7;case 2:return 8;case 3:return 9;case 4:return 22;case 5:return 23;case 6:return this.begin(`acc_title`),24;case 7:return this.popState(),`acc_title_value`;case 8:return this.begin(`acc_descr`),26;case 9:return this.popState(),`acc_descr_value`;case 10:this.begin(`acc_descr_multiline`);break;case 11:this.popState();break;case 12:return`acc_descr_multiline_value`;case 13:break;case 14:c;break;case 15:return 12;case 16:break;case 17:return 11;case 18:return 15;case 19:return 16;case 20:return 17;case 21:return 18;case 22:return this.begin(`person_ext`),45;case 23:return this.begin(`person`),44;case 24:return this.begin(`system_ext_queue`),51;case 25:return this.begin(`system_ext_db`),50;case 26:return this.begin(`system_ext`),49;case 27:return this.begin(`system_queue`),48;case 28:return this.begin(`system_db`),47;case 29:return this.begin(`system`),46;case 30:return this.begin(`boundary`),37;case 31:return this.begin(`enterprise_boundary`),34;case 32:return this.begin(`system_boundary`),36;case 33:return this.begin(`container_ext_queue`),57;case 34:return this.begin(`container_ext_db`),56;case 35:return this.begin(`container_ext`),55;case 36:return this.begin(`container_queue`),54;case 37:return this.begin(`container_db`),53;case 38:return this.begin(`container`),52;case 39:return this.begin(`container_boundary`),38;case 40:return this.begin(`component_ext_queue`),63;case 41:return this.begin(`component_ext_db`),62;case 42:return this.begin(`component_ext`),61;case 43:return this.begin(`component_queue`),60;case 44:return this.begin(`component_db`),59;case 45:return this.begin(`component`),58;case 46:return this.begin(`node`),39;case 47:return this.begin(`node`),39;case 48:return this.begin(`node_l`),40;case 49:return this.begin(`node_r`),41;case 50:return this.begin(`rel`),64;case 51:return this.begin(`birel`),65;case 52:return this.begin(`rel_u`),66;case 53:return this.begin(`rel_u`),66;case 54:return this.begin(`rel_d`),67;case 55:return this.begin(`rel_d`),67;case 56:return this.begin(`rel_l`),68;case 57:return this.begin(`rel_l`),68;case 58:return this.begin(`rel_r`),69;case 59:return this.begin(`rel_r`),69;case 60:return this.begin(`rel_b`),70;case 61:return this.begin(`rel_index`),71;case 62:return this.begin(`update_el_style`),72;case 63:return this.begin(`update_rel_style`),73;case 64:return this.begin(`update_layout_config`),74;case 65:return`EOF_IN_STRUCT`;case 66:return this.begin(`attribute`),`ATTRIBUTE_EMPTY`;case 67:this.begin(`attribute`);break;case 68:this.popState(),this.popState();break;case 69:return 80;case 70:break;case 71:return 80;case 72:this.begin(`string`);break;case 73:this.popState();break;case 74:return`STR`;case 75:this.begin(`string_kv`);break;case 76:return this.begin(`string_kv_key`),`STR_KEY`;case 77:this.popState(),this.begin(`string_kv_value`);break;case 78:return`STR_VALUE`;case 79:this.popState(),this.popState();break;case 80:return`STR`;case 81:return`LBRACE`;case 82:return`RBRACE`;case 83:return`SPACE`;case 84:return`EOL`;case 85:return 14}},`anonymous`),rules:[/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:title\s[^#\n;]+)/,/^(?:accDescription\s[^#\n;]+)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:%%(?!\{)*[^\n]*(\r?\n?)+)/,/^(?:%%[^\n]*(\r?\n)*)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:C4Context\b)/,/^(?:C4Container\b)/,/^(?:C4Component\b)/,/^(?:C4Dynamic\b)/,/^(?:C4Deployment\b)/,/^(?:Person_Ext\b)/,/^(?:Person\b)/,/^(?:SystemQueue_Ext\b)/,/^(?:SystemDb_Ext\b)/,/^(?:System_Ext\b)/,/^(?:SystemQueue\b)/,/^(?:SystemDb\b)/,/^(?:System\b)/,/^(?:Boundary\b)/,/^(?:Enterprise_Boundary\b)/,/^(?:System_Boundary\b)/,/^(?:ContainerQueue_Ext\b)/,/^(?:ContainerDb_Ext\b)/,/^(?:Container_Ext\b)/,/^(?:ContainerQueue\b)/,/^(?:ContainerDb\b)/,/^(?:Container\b)/,/^(?:Container_Boundary\b)/,/^(?:ComponentQueue_Ext\b)/,/^(?:ComponentDb_Ext\b)/,/^(?:Component_Ext\b)/,/^(?:ComponentQueue\b)/,/^(?:ComponentDb\b)/,/^(?:Component\b)/,/^(?:Deployment_Node\b)/,/^(?:Node\b)/,/^(?:Node_L\b)/,/^(?:Node_R\b)/,/^(?:Rel\b)/,/^(?:BiRel\b)/,/^(?:Rel_Up\b)/,/^(?:Rel_U\b)/,/^(?:Rel_Down\b)/,/^(?:Rel_D\b)/,/^(?:Rel_Left\b)/,/^(?:Rel_L\b)/,/^(?:Rel_Right\b)/,/^(?:Rel_R\b)/,/^(?:Rel_Back\b)/,/^(?:RelIndex\b)/,/^(?:UpdateElementStyle\b)/,/^(?:UpdateRelStyle\b)/,/^(?:UpdateLayoutConfig\b)/,/^(?:$)/,/^(?:[(][ ]*[,])/,/^(?:[(])/,/^(?:[)])/,/^(?:,,)/,/^(?:,)/,/^(?:[ ]*["]["])/,/^(?:[ ]*["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:[ ]*[\$])/,/^(?:[^=]*)/,/^(?:[=][ ]*["])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:[^,]+)/,/^(?:\{)/,/^(?:\})/,/^(?:[\s]+)/,/^(?:[\n\r]+)/,/^(?:$)/],conditions:{acc_descr_multiline:{rules:[11,12],inclusive:!1},acc_descr:{rules:[9],inclusive:!1},acc_title:{rules:[7],inclusive:!1},string_kv_value:{rules:[78,79],inclusive:!1},string_kv_key:{rules:[77],inclusive:!1},string_kv:{rules:[76],inclusive:!1},string:{rules:[73,74],inclusive:!1},attribute:{rules:[68,69,70,71,72,75,80],inclusive:!1},update_layout_config:{rules:[65,66,67,68],inclusive:!1},update_rel_style:{rules:[65,66,67,68],inclusive:!1},update_el_style:{rules:[65,66,67,68],inclusive:!1},rel_b:{rules:[65,66,67,68],inclusive:!1},rel_r:{rules:[65,66,67,68],inclusive:!1},rel_l:{rules:[65,66,67,68],inclusive:!1},rel_d:{rules:[65,66,67,68],inclusive:!1},rel_u:{rules:[65,66,67,68],inclusive:!1},rel_bi:{rules:[],inclusive:!1},rel:{rules:[65,66,67,68],inclusive:!1},node_r:{rules:[65,66,67,68],inclusive:!1},node_l:{rules:[65,66,67,68],inclusive:!1},node:{rules:[65,66,67,68],inclusive:!1},index:{rules:[],inclusive:!1},rel_index:{rules:[65,66,67,68],inclusive:!1},component_ext_queue:{rules:[65,66,67,68],inclusive:!1},component_ext_db:{rules:[65,66,67,68],inclusive:!1},component_ext:{rules:[65,66,67,68],inclusive:!1},component_queue:{rules:[65,66,67,68],inclusive:!1},component_db:{rules:[65,66,67,68],inclusive:!1},component:{rules:[65,66,67,68],inclusive:!1},container_boundary:{rules:[65,66,67,68],inclusive:!1},container_ext_queue:{rules:[65,66,67,68],inclusive:!1},container_ext_db:{rules:[65,66,67,68],inclusive:!1},container_ext:{rules:[65,66,67,68],inclusive:!1},container_queue:{rules:[65,66,67,68],inclusive:!1},container_db:{rules:[65,66,67,68],inclusive:!1},container:{rules:[65,66,67,68],inclusive:!1},birel:{rules:[65,66,67,68],inclusive:!1},system_boundary:{rules:[65,66,67,68],inclusive:!1},enterprise_boundary:{rules:[65,66,67,68],inclusive:!1},boundary:{rules:[65,66,67,68],inclusive:!1},system_ext_queue:{rules:[65,66,67,68],inclusive:!1},system_ext_db:{rules:[65,66,67,68],inclusive:!1},system_ext:{rules:[65,66,67,68],inclusive:!1},system_queue:{rules:[65,66,67,68],inclusive:!1},system_db:{rules:[65,66,67,68],inclusive:!1},system:{rules:[65,66,67,68],inclusive:!1},person_ext:{rules:[65,66,67,68],inclusive:!1},person:{rules:[65,66,67,68],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,8,10,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,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,81,82,83,84,85],inclusive:!0}}}})();function ue(){this.yy={}}return e(ue,`Parser`),ue.prototype=J,J.Parser=ue,new ue})();b.parser=b;var x=b,S=[],C=[``],w=`global`,T=``,E=[{alias:`global`,label:{text:`global`},type:{text:`global`},tags:null,link:null,parentBoundary:``}],D=[],O=``,k=!1,A=4,j=2,M,N=e(function(){return M},`getC4Type`),P=e(function(e){M=f(e,u())},`setC4Type`),F=e(function(e,t,n,r,i,a,o,s,l){if(e==null||t==null||n==null||r==null)return;let u={},d=D.find(e=>e.from===t&&e.to===n);if(d?u=d:D.push(u),u.type=e,u.from=t,u.to=n,u.label={text:r},i==null)u.techn={text:``};else if(typeof i==`object`){let[e,t]=Object.entries(i)[0];u[e]={text:t}}else u.techn={text:i};if(a==null)u.descr={text:``};else if(typeof a==`object`){let[e,t]=Object.entries(a)[0];u[e]={text:t}}else u.descr={text:a};if(typeof o==`object`){let[e,t]=Object.entries(o)[0];u[e]=t}else u.sprite=o;if(typeof s==`object`){let[e,t]=Object.entries(s)[0];u[e]=t}else u.tags=s;if(typeof l==`object`){let[e,t]=Object.entries(l)[0];u[e]=t}else u.link=l;u.wrap=J()},`addRel`),I=e(function(e,t,n,r,i,a,o){if(t===null||n===null)return;let s={},l=S.find(e=>e.alias===t);if(l&&t===l.alias?s=l:(s.alias=t,S.push(s)),n==null?s.label={text:``}:s.label={text:n},r==null)s.descr={text:``};else if(typeof r==`object`){let[e,t]=Object.entries(r)[0];s[e]={text:t}}else s.descr={text:r};if(typeof i==`object`){let[e,t]=Object.entries(i)[0];s[e]=t}else s.sprite=i;if(typeof a==`object`){let[e,t]=Object.entries(a)[0];s[e]=t}else s.tags=a;if(typeof o==`object`){let[e,t]=Object.entries(o)[0];s[e]=t}else s.link=o;s.typeC4Shape={text:e},s.parentBoundary=w,s.wrap=J()},`addPersonOrSystem`),L=e(function(e,t,n,r,i,a,o,s){if(t===null||n===null)return;let l={},u=S.find(e=>e.alias===t);if(u&&t===u.alias?l=u:(l.alias=t,S.push(l)),n==null?l.label={text:``}:l.label={text:n},r==null)l.techn={text:``};else if(typeof r==`object`){let[e,t]=Object.entries(r)[0];l[e]={text:t}}else l.techn={text:r};if(i==null)l.descr={text:``};else if(typeof i==`object`){let[e,t]=Object.entries(i)[0];l[e]={text:t}}else l.descr={text:i};if(typeof a==`object`){let[e,t]=Object.entries(a)[0];l[e]=t}else l.sprite=a;if(typeof o==`object`){let[e,t]=Object.entries(o)[0];l[e]=t}else l.tags=o;if(typeof s==`object`){let[e,t]=Object.entries(s)[0];l[e]=t}else l.link=s;l.wrap=J(),l.typeC4Shape={text:e},l.parentBoundary=w},`addContainer`),R=e(function(e,t,n,r,i,a,o,s){if(t===null||n===null)return;let l={},u=S.find(e=>e.alias===t);if(u&&t===u.alias?l=u:(l.alias=t,S.push(l)),n==null?l.label={text:``}:l.label={text:n},r==null)l.techn={text:``};else if(typeof r==`object`){let[e,t]=Object.entries(r)[0];l[e]={text:t}}else l.techn={text:r};if(i==null)l.descr={text:``};else if(typeof i==`object`){let[e,t]=Object.entries(i)[0];l[e]={text:t}}else l.descr={text:i};if(typeof a==`object`){let[e,t]=Object.entries(a)[0];l[e]=t}else l.sprite=a;if(typeof o==`object`){let[e,t]=Object.entries(o)[0];l[e]=t}else l.tags=o;if(typeof s==`object`){let[e,t]=Object.entries(s)[0];l[e]=t}else l.link=s;l.wrap=J(),l.typeC4Shape={text:e},l.parentBoundary=w},`addComponent`),z=e(function(e,t,n,r,i){if(e===null||t===null)return;let a={},o=E.find(t=>t.alias===e);if(o&&e===o.alias?a=o:(a.alias=e,E.push(a)),t==null?a.label={text:``}:a.label={text:t},n==null)a.type={text:`system`};else if(typeof n==`object`){let[e,t]=Object.entries(n)[0];a[e]={text:t}}else a.type={text:n};if(typeof r==`object`){let[e,t]=Object.entries(r)[0];a[e]=t}else a.tags=r;if(typeof i==`object`){let[e,t]=Object.entries(i)[0];a[e]=t}else a.link=i;a.parentBoundary=w,a.wrap=J(),T=w,w=e,C.push(T)},`addPersonOrSystemBoundary`),B=e(function(e,t,n,r,i){if(e===null||t===null)return;let a={},o=E.find(t=>t.alias===e);if(o&&e===o.alias?a=o:(a.alias=e,E.push(a)),t==null?a.label={text:``}:a.label={text:t},n==null)a.type={text:`container`};else if(typeof n==`object`){let[e,t]=Object.entries(n)[0];a[e]={text:t}}else a.type={text:n};if(typeof r==`object`){let[e,t]=Object.entries(r)[0];a[e]=t}else a.tags=r;if(typeof i==`object`){let[e,t]=Object.entries(i)[0];a[e]=t}else a.link=i;a.parentBoundary=w,a.wrap=J(),T=w,w=e,C.push(T)},`addContainerBoundary`),V=e(function(e,t,n,r,i,a,o,s){if(t===null||n===null)return;let l={},u=E.find(e=>e.alias===t);if(u&&t===u.alias?l=u:(l.alias=t,E.push(l)),n==null?l.label={text:``}:l.label={text:n},r==null)l.type={text:`node`};else if(typeof r==`object`){let[e,t]=Object.entries(r)[0];l[e]={text:t}}else l.type={text:r};if(i==null)l.descr={text:``};else if(typeof i==`object`){let[e,t]=Object.entries(i)[0];l[e]={text:t}}else l.descr={text:i};if(typeof o==`object`){let[e,t]=Object.entries(o)[0];l[e]=t}else l.tags=o;if(typeof s==`object`){let[e,t]=Object.entries(s)[0];l[e]=t}else l.link=s;l.nodeType=e,l.parentBoundary=w,l.wrap=J(),T=w,w=t,C.push(T)},`addDeploymentNode`),H=e(function(){w=T,C.pop(),T=C.pop(),C.push(T)},`popBoundaryParseStack`),ee=e(function(e,t,n,r,i,a,o,s,l,u,d){let f=S.find(e=>e.alias===t);if(!(f===void 0&&(f=E.find(e=>e.alias===t),f===void 0))){if(n!=null)if(typeof n==`object`){let[e,t]=Object.entries(n)[0];f[e]=t}else f.bgColor=n;if(r!=null)if(typeof r==`object`){let[e,t]=Object.entries(r)[0];f[e]=t}else f.fontColor=r;if(i!=null)if(typeof i==`object`){let[e,t]=Object.entries(i)[0];f[e]=t}else f.borderColor=i;if(a!=null)if(typeof a==`object`){let[e,t]=Object.entries(a)[0];f[e]=t}else f.shadowing=a;if(o!=null)if(typeof o==`object`){let[e,t]=Object.entries(o)[0];f[e]=t}else f.shape=o;if(s!=null)if(typeof s==`object`){let[e,t]=Object.entries(s)[0];f[e]=t}else f.sprite=s;if(l!=null)if(typeof l==`object`){let[e,t]=Object.entries(l)[0];f[e]=t}else f.techn=l;if(u!=null)if(typeof u==`object`){let[e,t]=Object.entries(u)[0];f[e]=t}else f.legendText=u;if(d!=null)if(typeof d==`object`){let[e,t]=Object.entries(d)[0];f[e]=t}else f.legendSprite=d}},`updateElStyle`),te=e(function(e,t,n,r,i,a,o){let s=D.find(e=>e.from===t&&e.to===n);if(s!==void 0){if(r!=null)if(typeof r==`object`){let[e,t]=Object.entries(r)[0];s[e]=t}else s.textColor=r;if(i!=null)if(typeof i==`object`){let[e,t]=Object.entries(i)[0];s[e]=t}else s.lineColor=i;if(a!=null)if(typeof a==`object`){let[e,t]=Object.entries(a)[0];s[e]=parseInt(t)}else s.offsetX=parseInt(a);if(o!=null)if(typeof o==`object`){let[e,t]=Object.entries(o)[0];s[e]=parseInt(t)}else s.offsetY=parseInt(o)}},`updateRelStyle`),ne=e(function(e,t,n){let r=A,i=j;if(typeof t==`object`){let e=Object.values(t)[0];r=parseInt(e)}else r=parseInt(t);if(typeof n==`object`){let e=Object.values(n)[0];i=parseInt(e)}else i=parseInt(n);r>=1&&(A=r),i>=1&&(j=i)},`updateLayoutConfig`),re=e(function(){return A},`getC4ShapeInRow`),ie=e(function(){return j},`getC4BoundaryInRow`),ae=e(function(){return w},`getCurrentBoundaryParse`),U=e(function(){return T},`getParentBoundaryParse`),W=e(function(e){return e==null?S:S.filter(t=>t.parentBoundary===e)},`getC4ShapeArray`),G=e(function(e){return S.find(t=>t.alias===e)},`getC4Shape`),K=e(function(e){return Object.keys(W(e))},`getC4ShapeKeys`),q=e(function(e){return e==null?E:E.filter(t=>t.parentBoundary===e)},`getBoundaries`),oe=q,se=e(function(){return D},`getRels`),ce=e(function(){return O},`getTitle`),le=e(function(e){k=e},`setWrap`),J=e(function(){return k},`autoWrap`),ue={addPersonOrSystem:I,addPersonOrSystemBoundary:z,addContainer:L,addContainerBoundary:B,addComponent:R,addDeploymentNode:V,popBoundaryParseStack:H,addRel:F,updateElStyle:ee,updateRelStyle:te,updateLayoutConfig:ne,autoWrap:J,setWrap:le,getC4ShapeArray:W,getC4Shape:G,getC4ShapeKeys:K,getBoundaries:q,getBoundarys:oe,getCurrentBoundaryParse:ae,getParentBoundaryParse:U,getRels:se,getTitle:ce,getC4Type:N,getC4ShapeInRow:re,getC4BoundaryInRow:ie,setAccTitle:i,getAccTitle:d,getAccDescription:l,setAccDescription:r,getConfig:e(()=>u().c4,`getConfig`),clear:e(function(){S=[],E=[{alias:`global`,label:{text:`global`},type:{text:`global`},tags:null,link:null,parentBoundary:``}],T=``,w=`global`,C=[``],D=[],C=[``],O=``,k=!1,A=4,j=2},`clear`),LINETYPE:{SOLID:0,DOTTED:1,NOTE:2,SOLID_CROSS:3,DOTTED_CROSS:4,SOLID_OPEN:5,DOTTED_OPEN:6,LOOP_START:10,LOOP_END:11,ALT_START:12,ALT_ELSE:13,ALT_END:14,OPT_START:15,OPT_END:16,ACTIVE_START:17,ACTIVE_END:18,PAR_START:19,PAR_AND:20,PAR_END:21,RECT_START:22,RECT_END:23,SOLID_POINT:24,DOTTED_POINT:25},ARROWTYPE:{FILLED:0,OPEN:1},PLACEMENT:{LEFTOF:0,RIGHTOF:1,OVER:2},setTitle:e(function(e){O=f(e,u())},`setTitle`),setC4Type:P},de=e(function(e,t){return _(e,t)},`drawRect`),fe=e(function(e,t,n,r,i,a){let o=e.append(`image`);o.attr(`width`,t),o.attr(`height`,n),o.attr(`x`,r),o.attr(`y`,i);let s=a.startsWith(`data:image/png;base64`)?a:(0,y.sanitizeUrl)(a);o.attr(`xlink:href`,s)},`drawImage`),pe=e((e,t,n,r)=>{let i=e.append(`g`),a=0;for(let e of t){let t=e.textColor?e.textColor:`#444444`,o=e.lineColor?e.lineColor:`#444444`,s=e.offsetX?parseInt(e.offsetX):0,l=e.offsetY?parseInt(e.offsetY):0;if(a===0){let t=i.append(`line`);t.attr(`x1`,e.startPoint.x),t.attr(`y1`,e.startPoint.y),t.attr(`x2`,e.endPoint.x),t.attr(`y2`,e.endPoint.y),t.attr(`stroke-width`,`1`),t.attr(`stroke`,o),t.style(`fill`,`none`),e.type!==`rel_b`&&t.attr(`marker-end`,`url(#`+r+`-arrowhead)`),(e.type===`birel`||e.type===`rel_b`)&&t.attr(`marker-start`,`url(#`+r+`-arrowend)`),a=-1}else{let t=i.append(`path`);t.attr(`fill`,`none`).attr(`stroke-width`,`1`).attr(`stroke`,o).attr(`d`,`Mstartx,starty Qcontrolx,controly stopx,stopy `.replaceAll(`startx`,e.startPoint.x).replaceAll(`starty`,e.startPoint.y).replaceAll(`controlx`,e.startPoint.x+(e.endPoint.x-e.startPoint.x)/2-(e.endPoint.x-e.startPoint.x)/4).replaceAll(`controly`,e.startPoint.y+(e.endPoint.y-e.startPoint.y)/2).replaceAll(`stopx`,e.endPoint.x).replaceAll(`stopy`,e.endPoint.y)),e.type!==`rel_b`&&t.attr(`marker-end`,`url(#`+r+`-arrowhead)`),(e.type===`birel`||e.type===`rel_b`)&&t.attr(`marker-start`,`url(#`+r+`-arrowend)`)}let u=n.messageFont();Y(n)(e.label.text,i,Math.min(e.startPoint.x,e.endPoint.x)+Math.abs(e.endPoint.x-e.startPoint.x)/2+s,Math.min(e.startPoint.y,e.endPoint.y)+Math.abs(e.endPoint.y-e.startPoint.y)/2+l,e.label.width,e.label.height,{fill:t},u),e.techn&&e.techn.text!==``&&(u=n.messageFont(),Y(n)(`[`+e.techn.text+`]`,i,Math.min(e.startPoint.x,e.endPoint.x)+Math.abs(e.endPoint.x-e.startPoint.x)/2+s,Math.min(e.startPoint.y,e.endPoint.y)+Math.abs(e.endPoint.y-e.startPoint.y)/2+n.messageFontSize+5+l,Math.max(e.label.width,e.techn.width),e.techn.height,{fill:t,"font-style":`italic`},u))}},`drawRels`),me=e(function(e,t,n){let r=e.append(`g`),i=t.bgColor?t.bgColor:`none`,a=t.borderColor?t.borderColor:`#444444`,o=t.fontColor?t.fontColor:`black`,s={"stroke-width":1,"stroke-dasharray":`7.0,7.0`};t.nodeType&&(s={"stroke-width":1}),de(r,{x:t.x,y:t.y,fill:i,stroke:a,width:t.width,height:t.height,rx:2.5,ry:2.5,attrs:s});let l=n.boundaryFont();l.fontWeight=`bold`,l.fontSize+=2,l.fontColor=o,Y(n)(t.label.text,r,t.x,t.y+t.label.Y,t.width,t.height,{fill:`#444444`},l),t.type&&t.type.text!==``&&(l=n.boundaryFont(),l.fontColor=o,Y(n)(t.type.text,r,t.x,t.y+t.type.Y,t.width,t.height,{fill:`#444444`},l)),t.descr&&t.descr.text!==``&&(l=n.boundaryFont(),l.fontSize-=2,l.fontColor=o,Y(n)(t.descr.text,r,t.x,t.y+t.descr.Y,t.width,t.height,{fill:`#444444`},l))},`drawBoundary`),he=e(function(e,t,n){let r=t.bgColor?t.bgColor:n[t.typeC4Shape.text+`_bg_color`],i=t.borderColor?t.borderColor:n[t.typeC4Shape.text+`_border_color`],a=t.fontColor?t.fontColor:`#FFFFFF`,o=`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAACD0lEQVR4Xu2YoU4EMRCGT+4j8Ai8AhaH4QHgAUjQuFMECUgMIUgwJAgMhgQsAYUiJCiQIBBY+EITsjfTdme6V24v4c8vyGbb+ZjOtN0bNcvjQXmkH83WvYBWto6PLm6v7p7uH1/w2fXD+PBycX1Pv2l3IdDm/vn7x+dXQiAubRzoURa7gRZWd0iGRIiJbOnhnfYBQZNJjNbuyY2eJG8fkDE3bbG4ep6MHUAsgYxmE3nVs6VsBWJSGccsOlFPmLIViMzLOB7pCVO2AtHJMohH7Fh6zqitQK7m0rJvAVYgGcEpe//PLdDz65sM4pF9N7ICcXDKIB5Nv6j7tD0NoSdM2QrU9Gg0ewE1LqBhHR3BBdvj2vapnidjHxD/q6vd7Pvhr31AwcY8eXMTXAKECZZJFXuEq27aLgQK5uLMohCenGGuGewOxSjBvYBqeG6B+Nqiblggdjnc+ZXDy+FNFpFzw76O3UBAROuXh6FoiAcf5g9eTvUgzy0nWg6I8cXHRUpg5bOVBCo+KDpFajOf23GgPme7RSQ+lacIENUgJ6gg1k6HjgOlqnLqip4tEuhv0hNEMXUD0clyXE3p6pZA0S2nnvTlXwLJEZWlb7cTQH1+USgTN4VhAenm/wea1OCAOmqo6fE1WCb9WSKBah+rbUWPWAmE2Rvk0ApiB45eOyNAzU8xcTvj8KvkKEoOaIYeHNA3ZuygAvFMUO0AAAAASUVORK5CYII=`;switch(t.typeC4Shape.text){case`person`:o=`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAACD0lEQVR4Xu2YoU4EMRCGT+4j8Ai8AhaH4QHgAUjQuFMECUgMIUgwJAgMhgQsAYUiJCiQIBBY+EITsjfTdme6V24v4c8vyGbb+ZjOtN0bNcvjQXmkH83WvYBWto6PLm6v7p7uH1/w2fXD+PBycX1Pv2l3IdDm/vn7x+dXQiAubRzoURa7gRZWd0iGRIiJbOnhnfYBQZNJjNbuyY2eJG8fkDE3bbG4ep6MHUAsgYxmE3nVs6VsBWJSGccsOlFPmLIViMzLOB7pCVO2AtHJMohH7Fh6zqitQK7m0rJvAVYgGcEpe//PLdDz65sM4pF9N7ICcXDKIB5Nv6j7tD0NoSdM2QrU9Gg0ewE1LqBhHR3BBdvj2vapnidjHxD/q6vd7Pvhr31AwcY8eXMTXAKECZZJFXuEq27aLgQK5uLMohCenGGuGewOxSjBvYBqeG6B+Nqiblggdjnc+ZXDy+FNFpFzw76O3UBAROuXh6FoiAcf5g9eTvUgzy0nWg6I8cXHRUpg5bOVBCo+KDpFajOf23GgPme7RSQ+lacIENUgJ6gg1k6HjgOlqnLqip4tEuhv0hNEMXUD0clyXE3p6pZA0S2nnvTlXwLJEZWlb7cTQH1+USgTN4VhAenm/wea1OCAOmqo6fE1WCb9WSKBah+rbUWPWAmE2Rvk0ApiB45eOyNAzU8xcTvj8KvkKEoOaIYeHNA3ZuygAvFMUO0AAAAASUVORK5CYII=`;break;case`external_person`:o=`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAAB6ElEQVR4Xu2YLY+EMBCG9+dWr0aj0Wg0Go1Go0+j8Xdv2uTCvv1gpt0ebHKPuhDaeW4605Z9mJvx4AdXUyTUdd08z+u6flmWZRnHsWkafk9DptAwDPu+f0eAYtu2PEaGWuj5fCIZrBAC2eLBAnRCsEkkxmeaJp7iDJ2QMDdHsLg8SxKFEJaAo8lAXnmuOFIhTMpxxKATebo4UiFknuNo4OniSIXQyRxEA3YsnjGCVEjVXD7yLUAqxBGUyPv/Y4W2beMgGuS7kVQIBycH0fD+oi5pezQETxdHKmQKGk1eQEYldK+jw5GxPfZ9z7Mk0Qnhf1W1m3w//EUn5BDmSZsbR44QQLBEqrBHqOrmSKaQAxdnLArCrxZcM7A7ZKs4ioRq8LFC+NpC3WCBJsvpVw5edm9iEXFuyNfxXAgSwfrFQ1c0iNda8AdejvUgnktOtJQQxmcfFzGglc5WVCj7oDgFqU18boeFSs52CUh8LE8BIVQDT1ABrB0HtgSEYlX5doJnCwv9TXocKCaKbnwhdDKPq4lf3SwU3HLq4V/+WYhHVMa/3b4IlfyikAduCkcBc7mQ3/z/Qq/cTuikhkzB12Ae/mcJC9U+Vo8Ej1gWAtgbeGgFsAMHr50BIWOLCbezvhpBFUdY6EJuJ/QDW0XoMX60zZ0AAAAASUVORK5CYII=`;break}let s=e.append(`g`);s.attr(`class`,`person-man`);let l=v();switch(t.typeC4Shape.text){case`person`:case`external_person`:case`system`:case`external_system`:case`container`:case`external_container`:case`component`:case`external_component`:l.x=t.x,l.y=t.y,l.fill=r,l.width=t.width,l.height=t.height,l.stroke=i,l.rx=2.5,l.ry=2.5,l.attrs={"stroke-width":.5},de(s,l);break;case`system_db`:case`external_system_db`:case`container_db`:case`external_container_db`:case`component_db`:case`external_component_db`:s.append(`path`).attr(`fill`,r).attr(`stroke-width`,`0.5`).attr(`stroke`,i).attr(`d`,`Mstartx,startyc0,-10 half,-10 half,-10c0,0 half,0 half,10l0,heightc0,10 -half,10 -half,10c0,0 -half,0 -half,-10l0,-height`.replaceAll(`startx`,t.x).replaceAll(`starty`,t.y).replaceAll(`half`,t.width/2).replaceAll(`height`,t.height)),s.append(`path`).attr(`fill`,`none`).attr(`stroke-width`,`0.5`).attr(`stroke`,i).attr(`d`,`Mstartx,startyc0,10 half,10 half,10c0,0 half,0 half,-10`.replaceAll(`startx`,t.x).replaceAll(`starty`,t.y).replaceAll(`half`,t.width/2));break;case`system_queue`:case`external_system_queue`:case`container_queue`:case`external_container_queue`:case`component_queue`:case`external_component_queue`:s.append(`path`).attr(`fill`,r).attr(`stroke-width`,`0.5`).attr(`stroke`,i).attr(`d`,`Mstartx,startylwidth,0c5,0 5,half 5,halfc0,0 0,half -5,halfl-width,0c-5,0 -5,-half -5,-halfc0,0 0,-half 5,-half`.replaceAll(`startx`,t.x).replaceAll(`starty`,t.y).replaceAll(`width`,t.width).replaceAll(`half`,t.height/2)),s.append(`path`).attr(`fill`,`none`).attr(`stroke-width`,`0.5`).attr(`stroke`,i).attr(`d`,`Mstartx,startyc-5,0 -5,half -5,halfc0,half 5,half 5,half`.replaceAll(`startx`,t.x+t.width).replaceAll(`starty`,t.y).replaceAll(`half`,t.height/2));break}let u=Ce(n,t.typeC4Shape.text);switch(s.append(`text`).attr(`fill`,a).attr(`font-family`,u.fontFamily).attr(`font-size`,u.fontSize-2).attr(`font-style`,`italic`).attr(`lengthAdjust`,`spacing`).attr(`textLength`,t.typeC4Shape.width).attr(`x`,t.x+t.width/2-t.typeC4Shape.width/2).attr(`y`,t.y+t.typeC4Shape.Y).text(`<<`+t.typeC4Shape.text+`>>`),t.typeC4Shape.text){case`person`:case`external_person`:fe(s,48,48,t.x+t.width/2-24,t.y+t.image.Y,o);break}let d=n[t.typeC4Shape.text+`Font`]();return d.fontWeight=`bold`,d.fontSize+=2,d.fontColor=a,Y(n)(t.label.text,s,t.x,t.y+t.label.Y,t.width,t.height,{fill:a},d),d=n[t.typeC4Shape.text+`Font`](),d.fontColor=a,t.techn&&t.techn?.text!==``?Y(n)(t.techn.text,s,t.x,t.y+t.techn.Y,t.width,t.height,{fill:a,"font-style":`italic`},d):t.type&&t.type.text!==``&&Y(n)(t.type.text,s,t.x,t.y+t.type.Y,t.width,t.height,{fill:a,"font-style":`italic`},d),t.descr&&t.descr.text!==``&&(d=n.personFont(),d.fontColor=a,Y(n)(t.descr.text,s,t.x,t.y+t.descr.Y,t.width,t.height,{fill:a},d)),t.height},`drawC4Shape`),ge=e(function(e,t){e.append(`defs`).append(`symbol`).attr(`id`,t+`-database`).attr(`fill-rule`,`evenodd`).attr(`clip-rule`,`evenodd`).append(`path`).attr(`transform`,`scale(.5)`).attr(`d`,`M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z`)},`insertDatabaseIcon`),_e=e(function(e,t){e.append(`defs`).append(`symbol`).attr(`id`,t+`-computer`).attr(`width`,`24`).attr(`height`,`24`).append(`path`).attr(`transform`,`scale(.5)`).attr(`d`,`M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z`)},`insertComputerIcon`),ve=e(function(e,t){e.append(`defs`).append(`symbol`).attr(`id`,t+`-clock`).attr(`width`,`24`).attr(`height`,`24`).append(`path`).attr(`transform`,`scale(.5)`).attr(`d`,`M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z`)},`insertClockIcon`),ye=e(function(e,t){e.append(`defs`).append(`marker`).attr(`id`,t+`-arrowhead`).attr(`refX`,9).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,12).attr(`markerHeight`,12).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`)},`insertArrowHead`),be=e(function(e,t){e.append(`defs`).append(`marker`).attr(`id`,t+`-arrowend`).attr(`refX`,1).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,12).attr(`markerHeight`,12).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 10 0 L 0 5 L 10 10 z`)},`insertArrowEnd`),xe=e(function(e,t){e.append(`defs`).append(`marker`).attr(`id`,t+`-filled-head`).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L14,7 L9,1 Z`)},`insertArrowFilledHead`),Se=e(function(e,t){let n=e.append(`defs`).append(`marker`).attr(`id`,t+`-crosshead`).attr(`markerWidth`,15).attr(`markerHeight`,8).attr(`orient`,`auto`).attr(`refX`,16).attr(`refY`,4);n.append(`path`).attr(`fill`,`black`).attr(`stroke`,`#000000`).style(`stroke-dasharray`,`0, 0`).attr(`stroke-width`,`1px`).attr(`d`,`M 9,2 V 6 L16,4 Z`),n.append(`path`).attr(`fill`,`none`).attr(`stroke`,`#000000`).style(`stroke-dasharray`,`0, 0`).attr(`stroke-width`,`1px`).attr(`d`,`M 0,1 L 6,7 M 6,1 L 0,7`)},`insertArrowCrossHead`),Ce=e((e,t)=>({fontFamily:e[t+`FontFamily`],fontSize:e[t+`FontSize`],fontWeight:e[t+`FontWeight`]}),`getC4ShapeFont`),Y=(function(){function t(e,t,n,r,a,o,s){i(t.append(`text`).attr(`x`,n+a/2).attr(`y`,r+o/2+5).style(`text-anchor`,`middle`).text(e),s)}e(t,`byText`);function n(e,t,n,r,a,o,l,u){let{fontSize:d,fontFamily:f,fontWeight:p}=u,m=e.split(s.lineBreakRegex);for(let e=0;e=this.data.widthLimit||n>=this.data.widthLimit||this.nextData.cnt>Ee)&&(t=this.nextData.startx+e.margin+Z.nextLinePaddingX,r=this.nextData.stopy+e.margin*2,this.nextData.stopx=n=t+e.width,this.nextData.starty=this.nextData.stopy,this.nextData.stopy=i=r+e.height,this.nextData.cnt=1),e.x=t,e.y=r,this.updateVal(this.data,`startx`,t,Math.min),this.updateVal(this.data,`starty`,r,Math.min),this.updateVal(this.data,`stopx`,n,Math.max),this.updateVal(this.data,`stopy`,i,Math.max),this.updateVal(this.nextData,`startx`,t,Math.min),this.updateVal(this.nextData,`starty`,r,Math.min),this.updateVal(this.nextData,`stopx`,n,Math.max),this.updateVal(this.nextData,`stopy`,i,Math.max)}init(e){this.name=``,this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,widthLimit:void 0},this.nextData={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,cnt:0},ke(e.db.getConfig())}bumpLastMargin(e){this.data.stopx+=e,this.data.stopy+=e}},ke=e(function(e){o(Z,e),e.fontFamily&&(Z.personFontFamily=Z.systemFontFamily=Z.messageFontFamily=e.fontFamily),e.fontSize&&(Z.personFontSize=Z.systemFontSize=Z.messageFontSize=e.fontSize),e.fontWeight&&(Z.personFontWeight=Z.systemFontWeight=Z.messageFontWeight=e.fontWeight)},`setConf`),Ae=e((e,t)=>({fontFamily:e[t+`FontFamily`],fontSize:e[t+`FontSize`],fontWeight:e[t+`FontWeight`]}),`c4ShapeFont`),je=e(e=>({fontFamily:e.boundaryFontFamily,fontSize:e.boundaryFontSize,fontWeight:e.boundaryFontWeight}),`boundaryFont`),Me=e(e=>({fontFamily:e.messageFontFamily,fontSize:e.messageFontSize,fontWeight:e.messageFontWeight}),`messageFont`);function Q(e,t,n,r,i){if(!t[e].width)if(n)t[e].text=m(t[e].text,i,r),t[e].textLines=t[e].text.split(s.lineBreakRegex).length,t[e].width=i,t[e].height=h(t[e].text,r);else{let n=t[e].text.split(s.lineBreakRegex);t[e].textLines=n.length;let i=0;t[e].height=0,t[e].width=0;for(let a of n)t[e].width=Math.max(g(a,r),t[e].width),i=h(a,r),t[e].height=t[e].height+i}}e(Q,`calcC4ShapeTextWH`);var Ne=e(function(e,t,n){t.x=n.data.startx,t.y=n.data.starty,t.width=n.data.stopx-n.data.startx,t.height=n.data.stopy-n.data.starty,t.label.y=Z.c4ShapeMargin-35;let r=t.wrap&&Z.wrap,i=je(Z);i.fontSize+=2,i.fontWeight=`bold`,Q(`label`,t,r,i,g(t.label.text,i)),X.drawBoundary(e,t,Z)},`drawBoundary`),Pe=e(function(e,t,n,r){let i=0;for(let a of r){i=0;let r=n[a],o=Ae(Z,r.typeC4Shape.text);switch(o.fontSize-=2,r.typeC4Shape.width=g(`«`+r.typeC4Shape.text+`»`,o),r.typeC4Shape.height=o.fontSize+2,r.typeC4Shape.Y=Z.c4ShapePadding,i=r.typeC4Shape.Y+r.typeC4Shape.height-4,r.image={width:0,height:0,Y:0},r.typeC4Shape.text){case`person`:case`external_person`:r.image.width=48,r.image.height=48,r.image.Y=i,i=r.image.Y+r.image.height;break}r.sprite&&(r.image.width=48,r.image.height=48,r.image.Y=i,i=r.image.Y+r.image.height);let s=r.wrap&&Z.wrap,l=Z.width-Z.c4ShapePadding*2,u=Ae(Z,r.typeC4Shape.text);u.fontSize+=2,u.fontWeight=`bold`,Q(`label`,r,s,u,l),r.label.Y=i+8,i=r.label.Y+r.label.height,r.type&&r.type.text!==``?(r.type.text=`[`+r.type.text+`]`,Q(`type`,r,s,Ae(Z,r.typeC4Shape.text),l),r.type.Y=i+5,i=r.type.Y+r.type.height):r.techn&&r.techn.text!==``&&(r.techn.text=`[`+r.techn.text+`]`,Q(`techn`,r,s,Ae(Z,r.techn.text),l),r.techn.Y=i+5,i=r.techn.Y+r.techn.height);let d=i,f=r.label.width;r.descr&&r.descr.text!==``&&(Q(`descr`,r,s,Ae(Z,r.typeC4Shape.text),l),r.descr.Y=i+20,i=r.descr.Y+r.descr.height,f=Math.max(r.label.width,r.descr.width),d=i-r.descr.textLines*5),f+=Z.c4ShapePadding,r.width=Math.max(r.width||Z.width,f,Z.width),r.height=Math.max(r.height||Z.height,d,Z.height),r.margin=r.margin||Z.c4ShapeMargin,e.insert(r),X.drawC4Shape(t,r,Z)}e.bumpLastMargin(Z.c4ShapeMargin)},`drawC4ShapeArray`),$=class{static{e(this,`Point`)}constructor(e,t){this.x=e,this.y=t}},Fe=e(function(e,t){let n=e.x,r=e.y,i=t.x,a=t.y,o=n+e.width/2,s=r+e.height/2,l=Math.abs(n-i),u=Math.abs(r-a),d=u/l,f=e.height/e.width,p=null;return r==a&&ni?p=new $(n,s):n==i&&ra&&(p=new $(o,r)),n>i&&r=d?new $(n,s+d*e.width/2):new $(o-l/u*e.height/2,r+e.height):n=d?new $(n+e.width,s+d*e.width/2):new $(o+l/u*e.height/2,r+e.height):na?p=f>=d?new $(n+e.width,s-d*e.width/2):new $(o+e.height/2*l/u,r):n>i&&r>a&&(p=f>=d?new $(n,s-e.width/2*d):new $(o-e.height/2*l/u,r)),p},`getIntersectPoint`),Ie=e(function(e,t){let n={x:0,y:0};n.x=t.x+t.width/2,n.y=t.y+t.height/2;let r=Fe(e,n);return n.x=e.x+e.width/2,n.y=e.y+e.height/2,{startPoint:r,endPoint:Fe(t,n)}},`getIntersectPoints`),Le=e(function(e,t,n,r,i){let a=0;for(let e of t){a+=1;let t=e.wrap&&Z.wrap,i=Me(Z);r.db.getC4Type()===`C4Dynamic`&&(e.label.text=a+`: `+e.label.text);let o=g(e.label.text,i);Q(`label`,e,t,i,o),e.techn&&e.techn.text!==``&&(o=g(e.techn.text,i),Q(`techn`,e,t,i,o)),e.descr&&e.descr.text!==``&&(o=g(e.descr.text,i),Q(`descr`,e,t,i,o));let s=Ie(n(e.from),n(e.to));e.startPoint=s.startPoint,e.endPoint=s.endPoint}X.drawRels(e,t,Z,i)},`drawRels`);function Re(e,t,n,r,i){let a=new Oe(i);a.data.widthLimit=n.data.widthLimit/Math.min(De,r.length);for(let[o,s]of r.entries()){let r=0;s.image={width:0,height:0,Y:0},s.sprite&&(s.image.width=48,s.image.height=48,s.image.Y=r,r=s.image.Y+s.image.height);let l=s.wrap&&Z.wrap,u=je(Z);if(u.fontSize+=2,u.fontWeight=`bold`,Q(`label`,s,l,u,a.data.widthLimit),s.label.Y=r+8,r=s.label.Y+s.label.height,s.type&&s.type.text!==``&&(s.type.text=`[`+s.type.text+`]`,Q(`type`,s,l,je(Z),a.data.widthLimit),s.type.Y=r+5,r=s.type.Y+s.type.height),s.descr&&s.descr.text!==``){let e=je(Z);e.fontSize-=2,Q(`descr`,s,l,e,a.data.widthLimit),s.descr.Y=r+20,r=s.descr.Y+s.descr.height}if(o==0||o%De===0){let e=n.data.startx+Z.diagramMarginX,t=n.data.stopy+Z.diagramMarginY+r;a.setData(e,e,t,t)}else{let e=a.data.stopx===a.data.startx?a.data.startx:a.data.stopx+Z.diagramMarginX,t=a.data.starty;a.setData(e,e,t,t)}a.name=s.alias;let d=i.db.getC4ShapeArray(s.alias),f=i.db.getC4ShapeKeys(s.alias);f.length>0&&Pe(a,e,d,f),t=s.alias;let p=i.db.getBoundaries(t);p.length>0&&Re(e,t,a,p,i),s.alias!==`global`&&Ne(e,s,a),n.data.stopy=Math.max(a.data.stopy+Z.c4ShapeMargin,n.data.stopy),n.data.stopx=Math.max(a.data.stopx+Z.c4ShapeMargin,n.data.stopx),we=Math.max(we,n.data.stopx),Te=Math.max(Te,n.data.stopy)}}e(Re,`drawInsideBoundary`);var ze={drawPersonOrSystemArray:Pe,drawBoundary:Ne,setConf:ke,draw:e(function(e,r,i,o){Z=u().c4;let s=u().securityLevel,l;s===`sandbox`&&(l=n(`#i`+r));let d=n(s===`sandbox`?l.nodes()[0].contentDocument.body:`body`),f=o.db;o.db.setWrap(Z.wrap),Ee=f.getC4ShapeInRow(),De=f.getC4BoundaryInRow(),t.debug(`C:${JSON.stringify(Z,null,2)}`);let p=s===`sandbox`?d.select(`[id="${r}"]`):n(`[id="${r}"]`);X.insertComputerIcon(p,r),X.insertDatabaseIcon(p,r),X.insertClockIcon(p,r);let m=new Oe(o);m.setData(Z.diagramMarginX,Z.diagramMarginX,Z.diagramMarginY,Z.diagramMarginY),m.data.widthLimit=screen.availWidth,we=Z.diagramMarginX,Te=Z.diagramMarginY;let h=o.db.getTitle();Re(p,``,m,o.db.getBoundaries(``),o),X.insertArrowHead(p,r),X.insertArrowEnd(p,r),X.insertArrowCrossHead(p,r),X.insertArrowFilledHead(p,r),Le(p,o.db.getRels(),o.db.getC4Shape,o,r),m.data.stopx=we,m.data.stopy=Te;let g=m.data,_=g.stopy-g.starty+2*Z.diagramMarginY,v=g.stopx-g.startx+2*Z.diagramMarginX;h&&p.append(`text`).text(h).attr(`x`,(g.stopx-g.startx)/2-4*Z.diagramMarginX).attr(`y`,g.starty+Z.diagramMarginY),a(p,_,v,Z.useMaxWidth);let y=h?60:0;p.attr(`viewBox`,g.startx-Z.diagramMarginX+` -`+(Z.diagramMarginY+y)+` `+v+` `+(_+y)),t.debug(`models:`,g)},`draw`)},Be={parser:x,db:ue,renderer:ze,styles:e(e=>`.person { + stroke: ${e.personBorder}; + fill: ${e.personBkg}; + } +`,`getStyles`),init:e(({c4:e,wrap:t})=>{ze.setConf(e),ue.setWrap(t)},`init`)};export{Be as diagram}; \ No newline at end of file diff --git a/dist-desktop/assets/channel-C4fgBBJ4.js b/dist-desktop/assets/channel-C4fgBBJ4.js new file mode 100644 index 0000000..8e63e6e --- /dev/null +++ b/dist-desktop/assets/channel-C4fgBBJ4.js @@ -0,0 +1 @@ +import{at as e,ot as t}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var n=(n,r)=>t.lang.round(e.parse(n)[r]);export{n as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-2Q5K7J3B-C1jixKkw.js b/dist-desktop/assets/chunk-2Q5K7J3B-C1jixKkw.js new file mode 100644 index 0000000..4c6fa39 --- /dev/null +++ b/dist-desktop/assets/chunk-2Q5K7J3B-C1jixKkw.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";var t=class{constructor(e){this.init=e,this.records=this.init()}static{e(this,`ImperativeState`)}reset(){this.records=this.init()}};export{t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-32BRIVSS-DWU3ezKg.js b/dist-desktop/assets/chunk-32BRIVSS-DWU3ezKg.js new file mode 100644 index 0000000..4680930 --- /dev/null +++ b/dist-desktop/assets/chunk-32BRIVSS-DWU3ezKg.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{p as t}from"./src-UMNXGZaF.js";import{j as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as r}from"./dist-qx0Iv9vM.js";var i=r(),a=e((e,t)=>{let n=e.append(`rect`);if(n.attr(`x`,t.x),n.attr(`y`,t.y),n.attr(`fill`,t.fill),n.attr(`stroke`,t.stroke),n.attr(`width`,t.width),n.attr(`height`,t.height),t.name&&n.attr(`name`,t.name),t.rx&&n.attr(`rx`,t.rx),t.ry&&n.attr(`ry`,t.ry),t.attrs!==void 0)for(let e in t.attrs)n.attr(e,t.attrs[e]);return t.class&&n.attr(`class`,t.class),n},`drawRect`),o=e((e,t)=>{a(e,{x:t.startx,y:t.starty,width:t.stopx-t.startx,height:t.stopy-t.starty,fill:t.fill,stroke:t.stroke,class:`rect`}).lower()},`drawBackgroundRect`),s=e((e,t)=>{let r=t.text.replace(n,` `),i=e.append(`text`);i.attr(`x`,t.x),i.attr(`y`,t.y),i.attr(`class`,`legend`),i.style(`text-anchor`,t.anchor),t.class&&i.attr(`class`,t.class);let a=i.append(`tspan`);return a.attr(`x`,t.x+t.textMargin*2),a.text(r),i},`drawText`),c=e((e,t,n,r)=>{let a=e.append(`image`);a.attr(`x`,t),a.attr(`y`,n);let o=(0,i.sanitizeUrl)(r);a.attr(`xlink:href`,o)},`drawImage`),l=e((e,t,n,r)=>{let a=e.append(`use`);a.attr(`x`,t),a.attr(`y`,n);let o=(0,i.sanitizeUrl)(r);a.attr(`xlink:href`,`#${o}`)},`drawEmbeddedImage`),u=e(()=>({x:0,y:0,width:100,height:100,fill:`#EDF2AE`,stroke:`#666`,anchor:`start`,rx:0,ry:0}),`getNoteRect`),d=e(()=>({x:0,y:0,width:100,height:100,"text-anchor":`start`,style:`#666`,textMargin:0,rx:0,ry:0,tspan:!0}),`getTextObj`),f=e(()=>{let e=t(`.mermaidTooltip`);return e.empty()&&(e=t(`body`).append(`div`).attr(`class`,`mermaidTooltip`).style(`opacity`,0).style(`position`,`absolute`).style(`text-align`,`center`).style(`max-width`,`200px`).style(`padding`,`2px`).style(`font-size`,`12px`).style(`background`,`#ffffde`).style(`border`,`1px solid #333`).style(`border-radius`,`2px`).style(`pointer-events`,`none`).style(`z-index`,`100`)),e},`createTooltip`);export{a,d as c,c as i,o as n,s as o,l as r,u as s,f as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-52WLFC77-BOCvVCX1.js b/dist-desktop/assets/chunk-52WLFC77-BOCvVCX1.js new file mode 100644 index 0000000..04c43e2 --- /dev/null +++ b/dist-desktop/assets/chunk-52WLFC77-BOCvVCX1.js @@ -0,0 +1,10 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{T as r,b as i,x as a}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{$ as o,J as s,K as c,Q as l,X as u,Y as d,Z as f,et as p,g as m,nt as h,q as g,rt as _,tt as v,u as y}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as b}from"./line-b9Ala942.js";import{n as x}from"./chunk-Q4XR5HBZ-CQ8zkLYc.js";import{i as S,n as ee,r as C,t as w}from"./chunk-7BUUIJ7U-Bb538aSH.js";import{n as T}from"./chunk-OGEWGWER-D-nWYRNR.js";import{i as E,n as D}from"./chunk-C7G6YPKG-DW-1jWUA.js";import{t as te}from"./rough.esm-CSKSodPl.js";import{r as O}from"./chunk-ZGVPDNZ5-DGInJAPD.js";var ne=e((e,t,n,r,i,a=!1,o)=>{t.arrowTypeStart&&j(e,`start`,t.arrowTypeStart,n,r,i,a,o),t.arrowTypeEnd&&j(e,`end`,t.arrowTypeEnd,n,r,i,a,o)},`addEdgeMarkers`),k={arrow_cross:{type:`cross`,fill:!1},arrow_point:{type:`point`,fill:!0},arrow_barb:{type:`barb`,fill:!0},arrow_barb_neo:{type:`barb`,fill:!0},arrow_circle:{type:`circle`,fill:!1},aggregation:{type:`aggregation`,fill:!1},extension:{type:`extension`,fill:!1},composition:{type:`composition`,fill:!0},dependency:{type:`dependency`,fill:!0},lollipop:{type:`lollipop`,fill:!1},only_one:{type:`onlyOne`,fill:!1},zero_or_one:{type:`zeroOrOne`,fill:!1},one_or_more:{type:`oneOrMore`,fill:!1},zero_or_more:{type:`zeroOrMore`,fill:!1},requirement_arrow:{type:`requirement_arrow`,fill:!1},requirement_contains:{type:`requirement_contains`,fill:!1}},A=[`cross`,`point`,`circle`,`lollipop`,`aggregation`,`extension`,`composition`,`dependency`,`barb`],j=e((e,n,r,i,a,o,s=!1,c)=>{let l=k[r],u=l&&A.includes(l.type);if(!l){t.warn(`Unknown arrow type: ${r}`);return}let d=`${a}_${o}-${l.type}${n===`start`?`Start`:`End`}${s&&u?`-margin`:``}`;if(c&&c.trim()!==``){let t=`${d}_${c.replace(/[^\dA-Za-z]/g,`_`)}`;if(!document.getElementById(t)){let e=document.getElementById(d);if(e){let n=e.cloneNode(!0);n.id=t,n.querySelectorAll(`path, circle, line`).forEach(e=>{e.setAttribute(`stroke`,c),l.fill&&e.setAttribute(`fill`,c)}),e.parentNode?.appendChild(n)}}e.attr(`marker-${n}`,`url(${i}#${t})`)}else e.attr(`marker-${n}`,`url(${i}#${d})`)},`addEdgeMarker`),re=e(e=>typeof e==`string`?e:a()?.flowchart?.curve,`resolveEdgeCurveType`),M=new Map,N=new Map,P=e(()=>{M.clear(),N.clear()},`clear`),F=e(e=>e?typeof e==`string`?e:e.reduce((e,t)=>e+`;`+t,``):``,`getLabelStyles`),I=e(async(e,i)=>{let o=a(),s=r(o),{labelStyles:c}=E(i);i.labelStyle=c;let l=e.insert(`g`).attr(`class`,`edgeLabel`),u=l.insert(`g`).attr(`class`,`label`).attr(`data-id`,i.id),d=i.labelType===`markdown`,f=await x(e,i.label,{style:F(i.labelStyle),useHtmlLabels:s,addSvgBackground:!0,isNode:!1,markdown:d,width:void 0},o);u.node().appendChild(f),t.info(`abc82`,i,i.labelType);let p=f.getBBox(),m=p;if(s){let e=f.children[0],t=n(f);p=e.getBoundingClientRect(),m=p,t.attr(`width`,p.width),t.attr(`height`,p.height)}else{let e=n(f).select(`text`).node();e&&typeof e.getBBox==`function`&&(m=e.getBBox())}u.attr(`transform`,w(m,s)),M.set(i.id,l),i.width=p.width,i.height=p.height;let h;if(i.startLabelLeft){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(r,i.startLabelLeft,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).startLeft=t,L(h,i.startLabelLeft)}if(i.startLabelRight){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(r,i.startLabelRight,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).startRight=t,L(h,i.startLabelRight)}if(i.endLabelLeft){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(t,i.endLabelLeft,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).endLeft=t,L(h,i.endLabelLeft)}if(i.endLabelRight){let t=e.insert(`g`).attr(`class`,`edgeTerminals`),r=t.insert(`g`).attr(`class`,`inner`),a=await O(t,i.endLabelRight,F(i.labelStyle)||``,!1,!1);h=a;let o=a.getBBox();if(s){let e=a.children[0],t=n(a);o=e.getBoundingClientRect(),t.attr(`width`,o.width),t.attr(`height`,o.height)}r.attr(`transform`,w(o,s)),N.get(i.id)||N.set(i.id,{}),N.get(i.id).endRight=t,L(h,i.endLabelRight)}return f},`insertEdgeLabel`);function L(e,t){r(a())&&e&&(e.style.width=t.length*9+`px`,e.style.height=`12px`)}e(L,`setTerminalWidth`);var R=e((e,n)=>{t.debug(`Moving label abc88 `,e.id,e.label,M.get(e.id),n);let r=n.updatedPath?n.updatedPath:n.originalPath,{subGraphTitleTotalMargin:i}=T(a());if(e.label){let a=M.get(e.id),o=e.x,s=e.y;if(r){let i=m.calcLabelPosition(r);t.debug(`Moving label `+e.label+` from (`,o,`,`,s,`) to (`,i.x,`,`,i.y,`) abc88`),n.updatedPath&&(o=i.x,s=i.y)}a.attr(`transform`,`translate(${o}, ${s+i/2})`)}if(e.startLabelLeft){let t=N.get(e.id).startLeft,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_left`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.startLabelRight){let t=N.get(e.id).startRight,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeStart?10:0,`start_right`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.endLabelLeft){let t=N.get(e.id).endLeft,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_left`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}if(e.endLabelRight){let t=N.get(e.id).endRight,n=e.x,i=e.y;if(r){let t=m.calcTerminalLabelPosition(e.arrowTypeEnd?10:0,`end_right`,r);n=t.x,i=t.y}t.attr(`transform`,`translate(${n}, ${i})`)}},`positionEdgeLabel`),ie=e((e,t)=>{if(!e?.isLabelEdge||!e?.id?.endsWith(`-to-label`)||!Array.isArray(t)||t.length!==2)return t;let[n,r]=t,i=Math.abs(r.x-n.x),a=Math.abs(r.y-n.y);return i<.001||a<.001?t:a>=i?[n,{x:n.x,y:r.y},r]:[n,{x:r.x,y:n.y},r]},`orthogonalizeToLabelClippedPoints`),z=e((e,t)=>{let n=e.x,r=e.y,i=Math.abs(t.x-n),a=Math.abs(t.y-r),o=e.width/2,s=e.height/2;return i>=o||a>=s},`outsideNode`),B=e((e,n,r)=>{t.debug(`intersection calc abc89: + outsidePoint: ${JSON.stringify(n)} + insidePoint : ${JSON.stringify(r)} + node : x:${e.x} y:${e.y} w:${e.width} h:${e.height}`);let i=e.x,a=e.y,o=Math.abs(i-r.x),s=e.width/2,c=r.xMath.abs(i-n.x)*l){let e=r.y{t.warn(`abc88 cutPathAtIntersect`,e,n);let r=[],i=e[0],a=!1;return e.forEach(e=>{if(t.info(`abc88 checking point`,e,n),!z(n,e)&&!a){let o=B(n,i,e);t.debug(`abc88 inside`,e,i,o),t.debug(`abc88 intersection`,o,n);let s=!1;r.forEach(e=>{s||=e.x===o.x&&e.y===o.y}),r.some(e=>e.x===o.x&&e.y===o.y)?t.warn(`abc88 no intersect`,o,r):r.push(o),a=!0}else t.warn(`abc88 outside`,e,i),i=e,a||r.push(e)}),t.debug(`returning points`,r),r},`cutPathAtIntersect`);function H(e){let t=[],n=[];for(let r=1;r5&&Math.abs(a.y-i.y)>5||i.y===a.y&&a.x===o.x&&Math.abs(a.x-i.x)>5&&Math.abs(a.y-o.y)>5)&&(t.push(a),n.push(r))}return{cornerPoints:t,cornerPointPositions:n}}e(H,`extractCornerPoints`);var U=e(function(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=n/Math.sqrt(r*r+i*i);return{x:t.x-a*r,y:t.y-a*i}},`findAdjacentPoint`),ae=e(function(e){let{cornerPointPositions:n}=H(e),r=[];for(let i=0;i10&&Math.abs(a.y-n.y)>=10?(t.debug(`Corner point fixing`,Math.abs(a.x-n.x),Math.abs(a.y-n.y)),f=o.x===s.x?{x:l<0?s.x-5+d:s.x+5-d,y:u<0?s.y-d:s.y+d}:{x:l<0?s.x-d:s.x+d,y:u<0?s.y-5+d:s.y+5-d}):t.debug(`Corner point skipping fixing`,Math.abs(a.x-n.x),Math.abs(a.y-n.y)),r.push(f,c)}else r.push(e[i]);return r},`fixCorners`),oe=e((e,t,n)=>{let r=e-t-n,i=Math.floor(r/4);return`0 ${t} ${Array(i).fill(`2 2`).join(` `)} ${n}`},`generateDashArray`),W=e(function(e,r,i,x,C,w,T,E=!1){if(!T)throw Error(`insertEdge: missing diagramId for edge "${r.id}" \u2014 edge IDs require a diagram prefix for uniqueness`);let{handDrawnSeed:O,layout:k}=a(),A=r.points,j=!1,M=C;var N=w;let P=[];for(let e in r.cssCompiledStyles)D(e)||P.push(r.cssCompiledStyles[e]);if(k===`swimlane`){if(N.intersect&&M.intersect&&Array.isArray(A)&&A.length>=2)if(A.length===2)A=[M.intersect(A[0]),N.intersect(A[1])];else{let e=A.slice(1,-1),t=e[0],n=e[e.length-1],r=.5,i=Math.abs(A[A.length-1].x-n.x)!Number.isNaN(e.y)),L=re(r.curve);L!==`rounded`&&(I=ae(I));let R=_;switch(L){case`linear`:R=_;break;case`basis`:R=p;break;case`cardinal`:R=o;break;case`bumpX`:R=v;break;case`bumpY`:R=h;break;case`catmullRom`:R=l;break;case`monotoneX`:R=u;break;case`monotoneY`:R=f;break;case`natural`:R=d;break;case`step`:R=s;break;case`stepAfter`:R=c;break;case`stepBefore`:R=g;break;case`rounded`:R=_;break;default:R=p}let{x:z,y:B}=ee(r),H=b().x(z).y(B).curve(R),U;switch(r.thickness){case`normal`:U=`edge-thickness-normal`;break;case`thick`:U=`edge-thickness-thick`;break;case`invisible`:U=`edge-thickness-invisible`;break;default:U=`edge-thickness-normal`}switch(r.pattern){case`solid`:U+=` edge-pattern-solid`;break;case`dotted`:U+=` edge-pattern-dotted`;break;case`dashed`:U+=` edge-pattern-dashed`;break;default:U+=` edge-pattern-solid`}let W,K=L===`rounded`?G(q(I,r),5):H(I),J=Array.isArray(r.style)?r.style:[r.style],Y=J.find(e=>e?.startsWith(`stroke:`)),X=``;r.animate&&(X=`edge-animation-fast`),r.animation&&(X=`edge-animation-`+r.animation);let Z=!1;if(r.look===`handDrawn`){let t=te.svg(e);Object.assign([],I);let i=t.path(K,{roughness:.3,seed:O});U+=` transition`,W=n(i).select(`path`).attr(`id`,`${T}-${r.id}`).attr(`class`,` `+U+(r.classes?` `+r.classes:``)+(X?` `+X:``)).attr(`style`,J?J.reduce((e,t)=>e+`;`+t,``):``);let a=W.attr(`d`);W.attr(`d`,a),e.node().appendChild(W.node())}else{let t=P.join(`;`),n=J?J.reduce((e,t)=>e+t+`;`,``):``,i=(t?t+`;`+n+`;`:n)+`;`+(J?J.reduce((e,t)=>e+`;`+t,``):``);W=e.append(`path`).attr(`d`,K).attr(`id`,`${T}-${r.id}`).attr(`class`,` `+U+(r.classes?` `+r.classes:``)+(X?` `+X:``)).attr(`style`,i),Y=i.match(/stroke:([^;]+)/)?.[1],Z=r.animate===!0||!!r.animation||t.includes(`animation`);let a=W.node(),o=typeof a.getTotalLength==`function`?a.getTotalLength():0,s=S[r.arrowTypeStart]||0,c=S[r.arrowTypeEnd]||0;if(r.look===`neo`&&!Z){let e=`stroke-dasharray: ${r.pattern===`dotted`||r.pattern===`dashed`?oe(o,s,c):`0 ${s} ${o-s-c} ${c}`}; stroke-dashoffset: 0;`;W.attr(`style`,e+W.attr(`style`))}}W.attr(`data-edge`,!0),W.attr(`data-et`,`edge`),W.attr(`data-id`,r.id),W.attr(`data-points`,F),W.attr(`data-look`,y(r.look)),r.showPoints&&I.forEach(t=>{e.append(`circle`).style(`stroke`,`red`).style(`fill`,`red`).attr(`r`,1).attr(`cx`,t.x).attr(`cy`,t.y)});let Q=``;(a().flowchart.arrowMarkerAbsolute||a().state.arrowMarkerAbsolute)&&(Q=window.location.protocol+`//`+window.location.host+window.location.pathname+window.location.search,Q=Q.replace(/\(/g,`\\(`).replace(/\)/g,`\\)`)),t.info(`arrowTypeStart`,r.arrowTypeStart),t.info(`arrowTypeEnd`,r.arrowTypeEnd);let se=!Z&&r?.look===`neo`;ne(W,r,Q,T,x,se,Y);let ce=Math.floor(A.length/2),le=A[ce];m.isLabelCoordinateInPath(le,W.attr(`d`))||(j=!0);let $={};return j&&($.updatedPath=A),$.originalPath=r.points,$},`insertEdge`);function G(e,t){if(e.length<2)return``;let n=``,r=e.length,i=1e-5;for(let a=0;a({...e}));if(e.length>=2&&C[t.arrowTypeStart]){let r=C[t.arrowTypeStart],i=e[0],a=e[1],{angle:o}=K(i,a),s=r*Math.cos(o),c=r*Math.sin(o);n[0].x=i.x+s,n[0].y=i.y+c}let r=e.length;if(r>=2&&C[t.arrowTypeEnd]){let i=C[t.arrowTypeEnd],a=e[r-1],o=e[r-2],{angle:s}=K(o,a),c=i*Math.cos(s),l=i*Math.sin(s);n[r-1].x=a.x-c,n[r-1].y=a.y-l}return n}e(q,`applyMarkerOffsetsToPoints`);var J=e((e,t,n,r)=>{t.forEach(t=>{Y[t](e,n,r)})},`insertMarkers`),Y={extension:e((e,n,r)=>{t.trace(`Making markers for `,r),e.append(`defs`).append(`marker`).attr(`id`,r+`_`+n+`-extensionStart`).attr(`class`,`marker extension `+n).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).attr(`d`,`M 1,7 L18,13 V 1 Z`),e.append(`defs`).append(`marker`).attr(`id`,r+`_`+n+`-extensionEnd`).attr(`class`,`marker extension `+n).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 V 13 L18,7 Z`),e.append(`marker`).attr(`id`,r+`_`+n+`-extensionStart-margin`).attr(`class`,`marker extension `+n).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).attr(`viewBox`,`0 0 20 14`).append(`polygon`).attr(`points`,`10,7 18,13 18,1`).style(`stroke-width`,2).style(`stroke-dasharray`,`0`),e.append(`defs`).append(`marker`).attr(`id`,r+`_`+n+`-extensionEnd-margin`).attr(`class`,`marker extension `+n).attr(`refX`,9).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).attr(`viewBox`,`0 0 20 14`).append(`polygon`).attr(`points`,`10,1 10,13 18,7`).style(`stroke-width`,2).style(`stroke-dasharray`,`0`)},`extension`),composition:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionStart`).attr(`class`,`marker composition `+t).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionEnd`).attr(`class`,`marker composition `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionStart-margin`).attr(`class`,`marker composition `+t).attr(`refX`,15).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,0).attr(`viewBox`,`0 0 15 15`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-compositionEnd-margin`).attr(`class`,`marker composition `+t).attr(`refX`,3.5).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,0).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`)},`composition`),aggregation:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationStart`).attr(`class`,`marker aggregation `+t).attr(`refX`,18).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationEnd`).attr(`class`,`marker aggregation `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationStart-margin`).attr(`class`,`marker aggregation `+t).attr(`refX`,15).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,2).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-aggregationEnd-margin`).attr(`class`,`marker aggregation `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,2).attr(`d`,`M 18,7 L9,13 L1,7 L9,1 Z`)},`aggregation`),dependency:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyStart`).attr(`class`,`marker dependency `+t).attr(`refX`,6).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 5,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyEnd`).attr(`class`,`marker dependency `+t).attr(`refX`,13).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 18,7 L9,13 L14,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyStart-margin`).attr(`class`,`marker dependency `+t).attr(`refX`,4).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,0).attr(`d`,`M 5,7 L9,13 L1,7 L9,1 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-dependencyEnd-margin`).attr(`class`,`marker dependency `+t).attr(`refX`,16).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,28).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).style(`stroke-width`,0).attr(`d`,`M 18,7 L9,13 L14,7 L9,1 Z`)},`dependency`),lollipop:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopStart`).attr(`class`,`marker lollipop `+t).attr(`refX`,13).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`circle`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopEnd`).attr(`class`,`marker lollipop `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).append(`circle`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopStart-margin`).attr(`class`,`marker lollipop `+t).attr(`refX`,13).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`circle`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6).attr(`stroke-width`,2),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-lollipopEnd-margin`).attr(`class`,`marker lollipop `+t).attr(`refX`,1).attr(`refY`,7).attr(`markerWidth`,190).attr(`markerHeight`,240).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`circle`).attr(`fill`,`transparent`).attr(`cx`,7).attr(`cy`,7).attr(`r`,6).attr(`stroke-width`,2)},`lollipop`),point:e((e,t,n)=>{e.append(`marker`).attr(`id`,n+`_`+t+`-pointEnd`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,5).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,8).attr(`markerHeight`,8).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 0 L 10 5 L 0 10 z`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-pointStart`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,4.5).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,8).attr(`markerHeight`,8).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 5 L 10 10 L 10 0 z`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-pointEnd-margin`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 11.5 14`).attr(`refX`,11.5).attr(`refY`,7).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,10.5).attr(`markerHeight`,14).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 0 0 L 11.5 7 L 0 14 z`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,0).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-pointStart-margin`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 11.5 14`).attr(`refX`,1).attr(`refY`,7).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11.5).attr(`markerHeight`,14).attr(`orient`,`auto`).append(`polygon`).attr(`points`,`0,7 11.5,14 11.5,0`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,0).style(`stroke-dasharray`,`1,0`)},`point`),circle:e((e,t,n)=>{e.append(`marker`).attr(`id`,n+`_`+t+`-circleEnd`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,11).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-circleStart`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,-1).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,1).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-circleEnd-margin`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refY`,5).attr(`refX`,12.25).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,14).attr(`markerHeight`,14).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,0).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-circleStart-margin`).attr(`class`,`marker `+t).attr(`viewBox`,`0 0 10 10`).attr(`refX`,-2).attr(`refY`,5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,14).attr(`markerHeight`,14).attr(`orient`,`auto`).append(`circle`).attr(`cx`,`5`).attr(`cy`,`5`).attr(`r`,`5`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,0).style(`stroke-dasharray`,`1,0`)},`circle`),cross:e((e,t,n)=>{e.append(`marker`).attr(`id`,n+`_`+t+`-crossEnd`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 11 11`).attr(`refX`,12).attr(`refY`,5.2).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 l 9,9 M 10,1 l -9,9`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-crossStart`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 11 11`).attr(`refX`,-1).attr(`refY`,5.2).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,11).attr(`markerHeight`,11).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 l 9,9 M 10,1 l -9,9`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2).style(`stroke-dasharray`,`1,0`),e.append(`marker`).attr(`id`,n+`_`+t+`-crossEnd-margin`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 15 15`).attr(`refX`,17.7).attr(`refY`,7.5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,12).attr(`markerHeight`,12).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 L 14,14 M 1,14 L 14,1`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2.5),e.append(`marker`).attr(`id`,n+`_`+t+`-crossStart-margin`).attr(`class`,`marker cross `+t).attr(`viewBox`,`0 0 15 15`).attr(`refX`,-3.5).attr(`refY`,7.5).attr(`markerUnits`,`userSpaceOnUse`).attr(`markerWidth`,12).attr(`markerHeight`,12).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 1,1 L 14,14 M 1,14 L 14,1`).attr(`class`,`arrowMarkerPath`).style(`stroke-width`,2.5).style(`stroke-dasharray`,`1,0`)},`cross`),barb:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-barbEnd`).attr(`refX`,19).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,14).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L9,13 L14,7 L9,1 Z`)},`barb`),barbNeo:e((e,t,n)=>{let{themeVariables:r}=i(),{transitionColor:a}=r;e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-barbEnd`).attr(`refX`,19).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,14).attr(`markerUnits`,`strokeWidth`).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L11,14 L13,7 L11,0 Z`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-barbEnd-margin`).attr(`refX`,17).attr(`refY`,7).attr(`markerWidth`,20).attr(`markerHeight`,14).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`).append(`path`).attr(`d`,`M 19,7 L11,14 L13,7 L11,0 Z`).attr(`fill`,`${a}`)},`barbNeo`),only_one:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-onlyOneStart`).attr(`class`,`marker onlyOne `+t).attr(`refX`,0).attr(`refY`,9).attr(`markerWidth`,18).attr(`markerHeight`,18).attr(`orient`,`auto`).append(`path`).attr(`d`,`M9,0 L9,18 M15,0 L15,18`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-onlyOneEnd`).attr(`class`,`marker onlyOne `+t).attr(`refX`,18).attr(`refY`,9).attr(`markerWidth`,18).attr(`markerHeight`,18).attr(`orient`,`auto`).append(`path`).attr(`d`,`M3,0 L3,18 M9,0 L9,18`)},`only_one`),zero_or_one:e((e,t,n)=>{let r=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrOneStart`).attr(`class`,`marker zeroOrOne `+t).attr(`refX`,0).attr(`refY`,9).attr(`markerWidth`,30).attr(`markerHeight`,18).attr(`orient`,`auto`);r.append(`circle`).attr(`fill`,`white`).attr(`cx`,21).attr(`cy`,9).attr(`r`,6),r.append(`path`).attr(`d`,`M9,0 L9,18`);let i=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrOneEnd`).attr(`class`,`marker zeroOrOne `+t).attr(`refX`,30).attr(`refY`,9).attr(`markerWidth`,30).attr(`markerHeight`,18).attr(`orient`,`auto`);i.append(`circle`).attr(`fill`,`white`).attr(`cx`,9).attr(`cy`,9).attr(`r`,6),i.append(`path`).attr(`d`,`M21,0 L21,18`)},`zero_or_one`),one_or_more:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-oneOrMoreStart`).attr(`class`,`marker oneOrMore `+t).attr(`refX`,18).attr(`refY`,18).attr(`markerWidth`,45).attr(`markerHeight`,36).attr(`orient`,`auto`).append(`path`).attr(`d`,`M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-oneOrMoreEnd`).attr(`class`,`marker oneOrMore `+t).attr(`refX`,27).attr(`refY`,18).attr(`markerWidth`,45).attr(`markerHeight`,36).attr(`orient`,`auto`).append(`path`).attr(`d`,`M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18`)},`one_or_more`),zero_or_more:e((e,t,n)=>{let r=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrMoreStart`).attr(`class`,`marker zeroOrMore `+t).attr(`refX`,18).attr(`refY`,18).attr(`markerWidth`,57).attr(`markerHeight`,36).attr(`orient`,`auto`);r.append(`circle`).attr(`fill`,`white`).attr(`cx`,48).attr(`cy`,18).attr(`r`,6),r.append(`path`).attr(`d`,`M0,18 Q18,0 36,18 Q18,36 0,18`);let i=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrMoreEnd`).attr(`class`,`marker zeroOrMore `+t).attr(`refX`,39).attr(`refY`,18).attr(`markerWidth`,57).attr(`markerHeight`,36).attr(`orient`,`auto`);i.append(`circle`).attr(`fill`,`white`).attr(`cx`,9).attr(`cy`,18).attr(`r`,6),i.append(`path`).attr(`d`,`M21,18 Q39,0 57,18 Q39,36 21,18`)},`zero_or_more`),only_one_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a}=r;e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-onlyOneStart`).attr(`class`,`marker onlyOne `+t).attr(`refX`,0).attr(`refY`,9).attr(`markerWidth`,18).attr(`markerHeight`,18).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).attr(`d`,`M9,0 L9,18 M15,0 L15,18`).attr(`stroke-width`,`${a}`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-onlyOneEnd`).attr(`class`,`marker onlyOne `+t).attr(`refX`,18).attr(`refY`,9).attr(`markerWidth`,18).attr(`markerHeight`,18).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).attr(`d`,`M3,0 L3,18 M9,0 L9,18`).attr(`stroke-width`,`${a}`)},`only_one_neo`),zero_or_one_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a,mainBkg:o}=r,s=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrOneStart`).attr(`class`,`marker zeroOrOne `+t).attr(`refX`,0).attr(`refY`,9).attr(`markerWidth`,30).attr(`markerHeight`,18).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`);s.append(`circle`).attr(`fill`,o??`white`).attr(`cx`,21).attr(`cy`,9).attr(`stroke-width`,`${a}`).attr(`r`,6),s.append(`path`).attr(`d`,`M9,0 L9,18`).attr(`stroke-width`,`${a}`);let c=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrOneEnd`).attr(`class`,`marker zeroOrOne `+t).attr(`refX`,30).attr(`refY`,9).attr(`markerWidth`,30).attr(`markerHeight`,18).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`);c.append(`circle`).attr(`fill`,o??`white`).attr(`cx`,9).attr(`cy`,9).attr(`stroke-width`,`${a}`).attr(`r`,6),c.append(`path`).attr(`d`,`M21,0 L21,18`).attr(`stroke-width`,`${a}`)},`zero_or_one_neo`),one_or_more_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a}=r;e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-oneOrMoreStart`).attr(`class`,`marker oneOrMore `+t).attr(`refX`,18).attr(`refY`,18).attr(`markerWidth`,45).attr(`markerHeight`,36).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`path`).attr(`d`,`M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27`).attr(`stroke-width`,`${a}`),e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-oneOrMoreEnd`).attr(`class`,`marker oneOrMore `+t).attr(`refX`,27).attr(`refY`,18).attr(`markerWidth`,45).attr(`markerHeight`,36).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`).append(`path`).attr(`d`,`M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18`).attr(`stroke-width`,`${a}`)},`one_or_more_neo`),zero_or_more_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a,mainBkg:o}=r,s=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrMoreStart`).attr(`class`,`marker zeroOrMore `+t).attr(`refX`,18).attr(`refY`,18).attr(`markerWidth`,57).attr(`markerHeight`,36).attr(`markerUnits`,`userSpaceOnUse`).attr(`orient`,`auto`);s.append(`circle`).attr(`fill`,o??`white`).attr(`cx`,45.5).attr(`cy`,18).attr(`r`,6).attr(`stroke-width`,`${a}`),s.append(`path`).attr(`d`,`M0,18 Q18,0 36,18 Q18,36 0,18`).attr(`stroke-width`,`${a}`);let c=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-zeroOrMoreEnd`).attr(`class`,`marker zeroOrMore `+t).attr(`refX`,39).attr(`refY`,18).attr(`markerWidth`,57).attr(`markerHeight`,36).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`);c.append(`circle`).attr(`fill`,o??`white`).attr(`cx`,11).attr(`cy`,18).attr(`r`,6).attr(`stroke-width`,`${a}`),c.append(`path`).attr(`d`,`M21,18 Q39,0 57,18 Q39,36 21,18`).attr(`stroke-width`,`${a}`)},`zero_or_more_neo`),requirement_arrow:e((e,t,n)=>{e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-requirement_arrowEnd`).attr(`refX`,20).attr(`refY`,10).attr(`markerWidth`,20).attr(`markerHeight`,20).attr(`orient`,`auto`).append(`path`).attr(`d`,`M0,0 + L20,10 + M20,10 + L0,20`)},`requirement_arrow`),requirement_contains:e((e,t,n)=>{let r=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-requirement_containsStart`).attr(`refX`,0).attr(`refY`,10).attr(`markerWidth`,20).attr(`markerHeight`,20).attr(`orient`,`auto`).append(`g`);r.append(`circle`).attr(`cx`,10).attr(`cy`,10).attr(`r`,9).attr(`fill`,`none`),r.append(`line`).attr(`x1`,1).attr(`x2`,19).attr(`y1`,10).attr(`y2`,10),r.append(`line`).attr(`y1`,1).attr(`y2`,19).attr(`x1`,10).attr(`x2`,10)},`requirement_contains`),requirement_arrow_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a}=r;e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-requirement_arrowEnd`).attr(`refX`,20).attr(`refY`,10).attr(`markerWidth`,20).attr(`markerHeight`,20).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).attr(`stroke-width`,`${a}`).attr(`viewBox`,`0 0 25 20`).append(`path`).attr(`d`,`M0,0 + L20,10 + M20,10 + L0,20`).attr(`stroke-linejoin`,`miter`)},`requirement_arrow_neo`),requirement_contains_neo:e((e,t,n)=>{let{themeVariables:r}=i(),{strokeWidth:a}=r,o=e.append(`defs`).append(`marker`).attr(`id`,n+`_`+t+`-requirement_containsStart`).attr(`refX`,0).attr(`refY`,10).attr(`markerWidth`,20).attr(`markerHeight`,20).attr(`orient`,`auto`).attr(`markerUnits`,`userSpaceOnUse`).append(`g`);o.append(`circle`).attr(`cx`,10).attr(`cy`,10).attr(`r`,9).attr(`fill`,`none`),o.append(`line`).attr(`x1`,1).attr(`x2`,19).attr(`y1`,10).attr(`y2`,10),o.append(`line`).attr(`y1`,1).attr(`y2`,19).attr(`x1`,10).attr(`x2`,10),o.selectAll(`*`).attr(`stroke-width`,`${a}`)},`requirement_contains_neo`)},X=J;export{X as a,I as i,M as n,R as o,W as r,N as s,P as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-5FCAYU7R-DNtJmW0j.js b/dist-desktop/assets/chunk-5FCAYU7R-DNtJmW0j.js new file mode 100644 index 0000000..cc4772a --- /dev/null +++ b/dist-desktop/assets/chunk-5FCAYU7R-DNtJmW0j.js @@ -0,0 +1 @@ +import{C as e,S as t,b as n,n as r,o as i,u as a,w as o,x as s}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var c=class extends r{static{s(this,`WardleyValueConverter`)}runCustomConverter(e,t,n){switch(e.name.toUpperCase()){case`LINK_LABEL`:return t.substring(1).trim();default:return}}},l={parser:{ValueConverter:s(()=>new c,`ValueConverter`)}};function u(r=i){let s=o(e(r),a),c=o(t({shared:s}),n,l);return s.ServiceRegistry.register(c),{shared:s,Wardley:c}}s(u,`createWardleyServices`);export{u as n,l as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-5HE753X5-o8-OCfIL.js b/dist-desktop/assets/chunk-5HE753X5-o8-OCfIL.js new file mode 100644 index 0000000..042bfa2 --- /dev/null +++ b/dist-desktop/assets/chunk-5HE753X5-o8-OCfIL.js @@ -0,0 +1 @@ +import{C as e,S as t,m as n,n as r,o as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`RailroadAbnfTokenBuilder`)}constructor(){super([`railroad-abnf-beta`])}},u=class extends r{static{c(this,`RailroadAbnfValueConverter`)}runConverter(e,t,n){let r=super.runConverter(e,t,n);if(e.name===`TITLE`&&typeof r==`string`){let e=r.trim();if(e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`))return e.slice(1,-1)}return r}runCustomConverter(e,t,n){if(e.name===`ABNF_STRING`)return t.slice(1,-1)}},d={parser:{TokenBuilder:c(()=>new l,`TokenBuilder`),ValueConverter:c(()=>new u,`ValueConverter`)}};function f(r=i){let a=s(e(r),o),c=s(t({shared:a}),n,d);return a.ServiceRegistry.register(c),{shared:a,RailroadAbnf:c}}c(f,`createRailroadAbnfServices`);export{f as n,d as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-5JV3BV7I-DKfYBAeY.js b/dist-desktop/assets/chunk-5JV3BV7I-DKfYBAeY.js new file mode 100644 index 0000000..9e18781 --- /dev/null +++ b/dist-desktop/assets/chunk-5JV3BV7I-DKfYBAeY.js @@ -0,0 +1 @@ +import{C as e,S as t,i as n,o as r,s as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`EventModelingTokenBuilder`)}constructor(){super([`eventmodeling`])}},u=new Set([`cmd`,`command`]),d=new Set([`evt`,`event`]),f=new Set([`rmo`,`readmodel`]),p=new Set([`pcr`,`processor`]),m=new Set([`ui`]);function h(e){let t=e.validation.EventModelingValidator,n=e.validation.ValidationRegistry;if(n){let e={EmTimeFrame:t.checkSourceFrameTypes.bind(t),EmResetFrame:t.checkSourceFrameTypes.bind(t)};n.register(e,t)}}c(h,`registerValidationChecks`);var g=class{static{c(this,`EventModelingValidator`)}checkSourceFrameTypes(e,t){e.sourceFrames.length!==0&&(u.has(e.modelEntityType)?this.validateSources(e,new Set([...m,...p]),`command`,`ui or processor`,t):d.has(e.modelEntityType)?this.validateSources(e,u,`event`,`command`,t):f.has(e.modelEntityType)?this.validateSources(e,d,`read model`,`event`,t):p.has(e.modelEntityType)?this.validateSources(e,f,`processor`,`read model`,t):m.has(e.modelEntityType)&&this.validateSources(e,f,`ui`,`read model`,t))}validateSources(e,t,n,r,i){for(let a of e.sourceFrames){let o=a.ref;o!==void 0&&!t.has(o.modelEntityType)&&i(`error`,`A ${n} can only receive input from a ${r}, not from '${o.modelEntityType}'.`,{node:e,property:`sourceFrames`})}}},_={parser:{TokenBuilder:c(()=>new l,`TokenBuilder`),ValueConverter:c(()=>new n,`ValueConverter`)},validation:{EventModelingValidator:c(()=>new g,`EventModelingValidator`)}};function v(n=r){let a=s(e(n),o),c=s(t({shared:a}),i,_);return a.ServiceRegistry.register(c),h(c),{shared:a,EventModel:c}}c(v,`createEventModelingServices`);export{v as n,_ as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-5TONJI2A-DOX2waSJ.js b/dist-desktop/assets/chunk-5TONJI2A-DOX2waSJ.js new file mode 100644 index 0000000..7402f95 --- /dev/null +++ b/dist-desktop/assets/chunk-5TONJI2A-DOX2waSJ.js @@ -0,0 +1,2 @@ +import{C as e,S as t,g as n,n as r,o as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`RailroadTokenBuilder`)}constructor(){super([`railroad-beta`])}},u=c(e=>{let t=e.slice(1,-1),n=``;for(let e=0;enew l,`TokenBuilder`),ValueConverter:c(()=>new d,`ValueConverter`)}};function p(r=i){let a=s(e(r),o),c=s(t({shared:a}),n,f);return a.ServiceRegistry.register(c),{shared:a,Railroad:c}}c(p,`createRailroadServices`);export{p as n,f as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-5VM5RSS4-ZNzvKenW.js b/dist-desktop/assets/chunk-5VM5RSS4-ZNzvKenW.js new file mode 100644 index 0000000..31131d3 --- /dev/null +++ b/dist-desktop/assets/chunk-5VM5RSS4-ZNzvKenW.js @@ -0,0 +1,15 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";var t=e(()=>` + /* Font Awesome icon styling - consolidated */ + .label-icon { + display: inline-block; + height: 1em; + overflow: visible; + vertical-align: -0.125em; + } + + .node .label-icon path { + fill: currentColor; + stroke: revert; + stroke-width: revert; + } +`,`getIconStyles`);export{t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-7BUUIJ7U-Bb538aSH.js b/dist-desktop/assets/chunk-7BUUIJ7U-Bb538aSH.js new file mode 100644 index 0000000..044c05d --- /dev/null +++ b/dist-desktop/assets/chunk-7BUUIJ7U-Bb538aSH.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";var t=e((e,t)=>{if(t)return`translate(`+-e.width/2+`, `+-e.height/2+`)`;let n=e.x??0,r=e.y??0;return`translate(`+-(n+e.width/2)+`, `+-(r+e.height/2)+`)`},`computeLabelTransform`),n={aggregation:17.25,extension:17.25,composition:17.25,dependency:6,lollipop:13.5,arrow_point:4,arrow_barb:0,arrow_barb_neo:5.5},r={arrow_point:4,arrow_cross:12.5,arrow_circle:12.5};function i(e,t){if(e===void 0||t===void 0)return{angle:0,deltaX:0,deltaY:0};e=a(e),t=a(t);let[n,r]=[e.x,e.y],[i,o]=[t.x,t.y],s=i-n,c=o-r;return{angle:Math.atan(c/s),deltaX:s,deltaY:c}}e(i,`calculateDeltaAndAngle`);var a=e(e=>Array.isArray(e)?{x:e[0],y:e[1]}:e,`pointTransformer`),o=e(t=>({x:e(function(e,r,o){let s=0,c=a(o[0]).x=0?1:-1)}else if(r===o.length-1&&Object.hasOwn(n,t.arrowTypeEnd)){let{angle:e,deltaX:r}=i(o[o.length-1],o[o.length-2]);s=n[t.arrowTypeEnd]*Math.cos(e)*(r>=0?1:-1)}let l=Math.abs(a(e).x-a(o[o.length-1]).x),u=Math.abs(a(e).y-a(o[o.length-1]).y),d=Math.abs(a(e).x-a(o[0]).x),f=Math.abs(a(e).y-a(o[0]).y),p=n[t.arrowTypeStart],m=n[t.arrowTypeEnd];if(l0&&u0&&f=0?1:-1)}else if(r===o.length-1&&Object.hasOwn(n,t.arrowTypeEnd)){let{angle:e,deltaY:r}=i(o[o.length-1],o[o.length-2]);s=n[t.arrowTypeEnd]*Math.abs(Math.sin(e))*(r>=0?1:-1)}let l=Math.abs(a(e).y-a(o[o.length-1]).y),u=Math.abs(a(e).x-a(o[o.length-1]).x),d=Math.abs(a(e).y-a(o[0]).y),f=Math.abs(a(e).x-a(o[0]).x),p=n[t.arrowTypeStart],m=n[t.arrowTypeEnd];if(l0&&u0&&fnew l,`TokenBuilder`),ValueConverter:c(()=>new n,`ValueConverter`)}};function d(n=i){let a=s(e(n),o),c=s(t({shared:a}),r,u);return a.ServiceRegistry.register(c),{shared:a,Info:c}}c(d,`createInfoServices`);export{d as n,u as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-C7G6YPKG-DW-1jWUA.js b/dist-desktop/assets/chunk-C7G6YPKG-DW-1jWUA.js new file mode 100644 index 0000000..fb9dee2 --- /dev/null +++ b/dist-desktop/assets/chunk-C7G6YPKG-DW-1jWUA.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{x as t}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var n=e(e=>{let{handDrawnSeed:n}=t();return{fill:e,hachureAngle:120,hachureGap:4,fillWeight:2,roughness:.7,stroke:e,seed:n}},`solidStateFill`),r=e(e=>{let t=i([...e.cssCompiledStyles||[],...e.cssStyles||[],...e.labelStyle||[]]);return{stylesMap:t,stylesArray:[...t]}},`compileStyles`),i=e(e=>{let t=new Map;return e.forEach(e=>{let[n,r]=e.split(`:`);t.set(n.trim(),r?.trim())}),t},`styles2Map`),a=e(e=>e===`color`||e===`font-size`||e===`font-family`||e===`font-weight`||e===`font-style`||e===`text-decoration`||e===`text-align`||e===`text-transform`||e===`line-height`||e===`letter-spacing`||e===`word-spacing`||e===`text-shadow`||e===`text-overflow`||e===`white-space`||e===`word-wrap`||e===`word-break`||e===`overflow-wrap`||e===`hyphens`,`isLabelStyle`),o=e(e=>{let{stylesArray:t}=r(e),n=[],i=[],o=[],s=[];return t.forEach(e=>{let t=e[0];a(t)?n.push(e.join(`:`)+` !important`):(i.push(e.join(`:`)+` !important`),t.includes(`stroke`)&&o.push(e.join(`:`)+` !important`),t===`fill`&&s.push(e.join(`:`)+` !important`))}),{labelStyles:n.join(`;`),nodeStyles:i.join(`;`),stylesArray:t,borderStyles:o,backgroundStyles:s}},`styles2String`),s=e((e,n)=>{let{themeVariables:i,handDrawnSeed:a}=t(),{nodeBorder:o,mainBkg:s}=i,{stylesMap:l}=r(e);return Object.assign({roughness:.7,fill:l.get(`fill`)||s,fillStyle:`hachure`,fillWeight:4,hachureGap:5.2,stroke:l.get(`stroke`)||o,seed:a,strokeWidth:l.get(`stroke-width`)?.replace(`px`,``)||1.3,fillLineDash:[0,0],strokeLineDash:c(l.get(`stroke-dasharray`))},n)},`userNodeOverrides`),c=e(e=>{if(!e)return[0,0];let t=e.trim().split(/\s+/).map(Number);if(t.length===1){let e=isNaN(t[0])?0:t[0];return[e,e]}return[isNaN(t[0])?0:t[0],isNaN(t[1])?0:t[1]]},`getStrokeDashArray`);export{s as a,o as i,a as n,n as r,r as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-CQNSW5MT-BbEh_krl.js b/dist-desktop/assets/chunk-CQNSW5MT-BbEh_krl.js new file mode 100644 index 0000000..587d5cf --- /dev/null +++ b/dist-desktop/assets/chunk-CQNSW5MT-BbEh_krl.js @@ -0,0 +1 @@ +import{C as e,S as t,n,o as r,t as i,u as a,v as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends n{static{c(this,`TreeViewValueConverter`)}runCustomConverter(e,t,n){if(e.name===`INDENTATION`)return t?.length||0;if(e.name===`QUOTED_NAME`)return t.substring(1,t.length-1);if(e.name===`BARE_NAME`)return t.replace(/[\t ]+$/,``);if(e.name===`CLASS_ANNOTATION`)return t.trim().substring(3).trim();if(e.name===`ICON_ANNOTATION`){let e=t.trim();return e.substring(5,e.length-1)}if(e.name===`DESC_ANNOTATION`)return t.trim().substring(2).trim()}},u=class extends i{static{c(this,`TreeViewTokenBuilder`)}constructor(){super([`treeView-beta`])}},d={parser:{TokenBuilder:c(()=>new u,`TokenBuilder`),ValueConverter:c(()=>new l,`ValueConverter`)}};function f(n=r){let i=s(e(n),a),c=s(t({shared:i}),o,d);return i.ServiceRegistry.register(c),{shared:i,TreeView:c}}c(f,`createTreeViewServices`);export{f as n,d as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-CYSBUYHQ-CbOq7Rc1.js b/dist-desktop/assets/chunk-CYSBUYHQ-CbOq7Rc1.js new file mode 100644 index 0000000..024de46 --- /dev/null +++ b/dist-desktop/assets/chunk-CYSBUYHQ-CbOq7Rc1.js @@ -0,0 +1 @@ +import{C as e,S as t,c as n,i as r,o as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`GitGraphTokenBuilder`)}constructor(){super([`gitGraph`])}},u={parser:{TokenBuilder:c(()=>new l,`TokenBuilder`),ValueConverter:c(()=>new r,`ValueConverter`)}};function d(r=i){let a=s(e(r),o),c=s(t({shared:a}),n,u);return a.ServiceRegistry.register(c),{shared:a,GitGraph:c}}c(d,`createGitGraphServices`);export{d as n,u as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-EMLP6XTP-BoneA0Uo.js b/dist-desktop/assets/chunk-EMLP6XTP-BoneA0Uo.js new file mode 100644 index 0000000..eb457cb --- /dev/null +++ b/dist-desktop/assets/chunk-EMLP6XTP-BoneA0Uo.js @@ -0,0 +1 @@ +import{C as e,S as t,d as n,i as r,o as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`PacketTokenBuilder`)}constructor(){super([`packet`])}},u={parser:{TokenBuilder:c(()=>new l,`TokenBuilder`),ValueConverter:c(()=>new r,`ValueConverter`)}};function d(r=i){let a=s(e(r),o),c=s(t({shared:a}),n,u);return a.ServiceRegistry.register(c),{shared:a,Packet:c}}c(d,`createPacketServices`);export{d as n,u as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-EX3LRPZG-CzaF5a2T.js b/dist-desktop/assets/chunk-EX3LRPZG-CzaF5a2T.js new file mode 100644 index 0000000..c2da566 --- /dev/null +++ b/dist-desktop/assets/chunk-EX3LRPZG-CzaF5a2T.js @@ -0,0 +1,231 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{$ as r,H as i,K as a,U as o,a as s,s as c,v as l,w as u,x as d,y as f}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{g as p,s as m}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as h}from"./chunk-32BRIVSS-DWU3ezKg.js";import{t as g}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as _}from"./chunk-VR4S4FIN-BTo4eV3J.js";import{r as v}from"./chunk-FWX5IMBZ-ComLEIwh.js";var y=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,2],r=[1,3],i=[1,4],a=[2,4],o=[1,9],s=[1,11],c=[1,16],l=[1,17],u=[1,18],d=[1,19],f=[1,33],p=[1,20],m=[1,21],h=[1,22],g=[1,23],_=[1,24],v=[1,26],y=[1,27],b=[1,28],x=[1,29],S=[1,30],C=[1,31],w=[1,32],T=[1,35],E=[1,36],D=[1,37],O=[1,38],k=[1,34],A=[1,4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],j=[1,4,5,14,15,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,39,40,41,45,48,51,52,53,54,57],M=[4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],N={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,SD:6,document:7,line:8,statement:9,classDefStatement:10,styleStatement:11,cssClassStatement:12,idStatement:13,DESCR:14,"-->":15,HIDE_EMPTY:16,scale:17,WIDTH:18,COMPOSIT_STATE:19,STRUCT_START:20,STRUCT_STOP:21,STATE_DESCR:22,AS:23,ID:24,FORK:25,JOIN:26,CHOICE:27,CONCURRENT:28,note:29,notePosition:30,NOTE_TEXT:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,CLICK:38,STRING:39,HREF:40,classDef:41,CLASSDEF_ID:42,CLASSDEF_STYLEOPTS:43,DEFAULT:44,style:45,STYLE_IDS:46,STYLEDEF_STYLEOPTS:47,class:48,CLASSENTITY_IDS:49,STYLECLASS:50,direction_tb:51,direction_bt:52,direction_rl:53,direction_lr:54,eol:55,";":56,EDGE_STATE:57,STYLE_SEPARATOR:58,left_of:59,right_of:60,$accept:0,$end:1},terminals_:{2:`error`,4:`SPACE`,5:`NL`,6:`SD`,14:`DESCR`,15:`-->`,16:`HIDE_EMPTY`,17:`scale`,18:`WIDTH`,19:`COMPOSIT_STATE`,20:`STRUCT_START`,21:`STRUCT_STOP`,22:`STATE_DESCR`,23:`AS`,24:`ID`,25:`FORK`,26:`JOIN`,27:`CHOICE`,28:`CONCURRENT`,29:`note`,31:`NOTE_TEXT`,33:`acc_title`,34:`acc_title_value`,35:`acc_descr`,36:`acc_descr_value`,37:`acc_descr_multiline_value`,38:`CLICK`,39:`STRING`,40:`HREF`,41:`classDef`,42:`CLASSDEF_ID`,43:`CLASSDEF_STYLEOPTS`,44:`DEFAULT`,45:`style`,46:`STYLE_IDS`,47:`STYLEDEF_STYLEOPTS`,48:`class`,49:`CLASSENTITY_IDS`,50:`STYLECLASS`,51:`direction_tb`,52:`direction_bt`,53:`direction_rl`,54:`direction_lr`,56:`;`,57:`EDGE_STATE`,58:`STYLE_SEPARATOR`,59:`left_of`,60:`right_of`},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,3],[9,4],[9,1],[9,2],[9,1],[9,4],[9,3],[9,6],[9,1],[9,1],[9,1],[9,1],[9,4],[9,4],[9,1],[9,2],[9,2],[9,1],[9,5],[9,5],[10,3],[10,3],[11,3],[12,3],[32,1],[32,1],[32,1],[32,1],[55,1],[55,1],[13,1],[13,1],[13,3],[13,3],[30,1],[30,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 3:return r.setRootDoc(a[s]),a[s];case 4:this.$=[];break;case 5:a[s]!=`nl`&&(a[s-1].push(a[s]),this.$=a[s-1]);break;case 6:case 7:this.$=a[s];break;case 8:this.$=`nl`;break;case 12:this.$=a[s];break;case 13:let e=a[s-1];e.description=r.trimColon(a[s]),this.$=e;break;case 14:this.$={stmt:`relation`,state1:a[s-2],state2:a[s]};break;case 15:let t=r.trimColon(a[s]);this.$={stmt:`relation`,state1:a[s-3],state2:a[s-1],description:t};break;case 19:this.$={stmt:`state`,id:a[s-3],type:`default`,description:``,doc:a[s-1]};break;case 20:var c=a[s],l=a[s-2].trim();if(a[s].match(`:`)){var u=a[s].split(`:`);c=u[0],l=[l,u[1]]}this.$={stmt:`state`,id:c,type:`default`,description:l};break;case 21:this.$={stmt:`state`,id:a[s-3],type:`default`,description:a[s-5],doc:a[s-1]};break;case 22:this.$={stmt:`state`,id:a[s],type:`fork`};break;case 23:this.$={stmt:`state`,id:a[s],type:`join`};break;case 24:this.$={stmt:`state`,id:a[s],type:`choice`};break;case 25:this.$={stmt:`state`,id:r.getDividerId(),type:`divider`};break;case 26:this.$={stmt:`state`,id:a[s-1].trim(),note:{position:a[s-2].trim(),text:a[s].trim()}};break;case 29:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 30:case 31:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 32:this.$={stmt:`click`,id:a[s-3],url:a[s-2],tooltip:a[s-1]};break;case 33:this.$={stmt:`click`,id:a[s-3],url:a[s-1],tooltip:``};break;case 34:case 35:this.$={stmt:`classDef`,id:a[s-1].trim(),classes:a[s].trim()};break;case 36:this.$={stmt:`style`,id:a[s-1].trim(),styleClass:a[s].trim()};break;case 37:this.$={stmt:`applyClass`,id:a[s-1].trim(),styleClass:a[s].trim()};break;case 38:r.setDirection(`TB`),this.$={stmt:`dir`,value:`TB`};break;case 39:r.setDirection(`BT`),this.$={stmt:`dir`,value:`BT`};break;case 40:r.setDirection(`RL`),this.$={stmt:`dir`,value:`RL`};break;case 41:r.setDirection(`LR`),this.$={stmt:`dir`,value:`LR`};break;case 44:case 45:this.$={stmt:`state`,id:a[s].trim(),type:`default`,description:``};break;case 46:this.$={stmt:`state`,id:a[s-2].trim(),classes:[a[s].trim()],type:`default`,description:``};break;case 47:this.$={stmt:`state`,id:a[s-2].trim(),classes:[a[s].trim()],type:`default`,description:``};break}},`anonymous`),table:[{3:1,4:n,5:r,6:i},{1:[3]},{3:5,4:n,5:r,6:i},{3:6,4:n,5:r,6:i},t([1,4,5,16,17,19,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],a,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:o,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:c,17:l,19:u,22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,5]),{9:39,10:12,11:13,12:14,13:15,16:c,17:l,19:u,22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,7]),t(A,[2,8]),t(A,[2,9]),t(A,[2,10]),t(A,[2,11]),t(A,[2,12],{14:[1,40],15:[1,41]}),t(A,[2,16]),{18:[1,42]},t(A,[2,18],{20:[1,43]}),{23:[1,44]},t(A,[2,22]),t(A,[2,23]),t(A,[2,24]),t(A,[2,25]),{30:45,31:[1,46],59:[1,47],60:[1,48]},t(A,[2,28]),{34:[1,49]},{36:[1,50]},t(A,[2,31]),{13:51,24:f,57:k},{42:[1,52],44:[1,53]},{46:[1,54]},{49:[1,55]},t(j,[2,44],{58:[1,56]}),t(j,[2,45],{58:[1,57]}),t(A,[2,38]),t(A,[2,39]),t(A,[2,40]),t(A,[2,41]),t(A,[2,6]),t(A,[2,13]),{13:58,24:f,57:k},t(A,[2,17]),t(M,a,{7:59}),{24:[1,60]},{24:[1,61]},{23:[1,62]},{24:[2,48]},{24:[2,49]},t(A,[2,29]),t(A,[2,30]),{39:[1,63],40:[1,64]},{43:[1,65]},{43:[1,66]},{47:[1,67]},{50:[1,68]},{24:[1,69]},{24:[1,70]},t(A,[2,14],{14:[1,71]}),{4:o,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:c,17:l,19:u,21:[1,72],22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,20],{20:[1,73]}),{31:[1,74]},{24:[1,75]},{39:[1,76]},{39:[1,77]},t(A,[2,34]),t(A,[2,35]),t(A,[2,36]),t(A,[2,37]),t(j,[2,46]),t(j,[2,47]),t(A,[2,15]),t(A,[2,19]),t(M,a,{7:78}),t(A,[2,26]),t(A,[2,27]),{5:[1,79]},{5:[1,80]},{4:o,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:c,17:l,19:u,21:[1,81],22:d,24:f,25:p,26:m,27:h,28:g,29:_,32:25,33:v,35:y,37:b,38:x,41:S,45:C,48:w,51:T,52:E,53:D,54:O,57:k},t(A,[2,32]),t(A,[2,33]),t(A,[2,21])],defaultActions:{5:[2,1],6:[2,2],47:[2,48],48:[2,49]},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,m=o.slice.call(arguments,1),h=Object.create(this.lexer),g={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(g.yy[_]=this.yy[_]);h.setInput(t,g.yy),g.yy.lexer=h,g.yy.parser=this,h.yylloc===void 0&&(h.yylloc={});var v=h.yylloc;o.push(v);var y=h.options&&h.options.ranges;typeof g.yy.parseError==`function`?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function b(e){r.length-=2*e,a.length-=e,o.length-=e}e(b,`popStack`);function x(){var e=i.pop()||h.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(x,`lex`);for(var S,C,w,T,E,D={},O,k,A,j;;){if(w=r[r.length-1],this.defaultActions[w]?T=this.defaultActions[w]:(S??=x(),T=s[w]&&s[w][S]),T===void 0||!T.length||!T[0]){var M=``;for(O in j=[],s[w])this.terminals_[O]&&O>f&&j.push(`'`+this.terminals_[O]+`'`);M=h.showPosition?`Parse error on line `+(l+1)+`: +`+h.showPosition()+` +Expecting `+j.join(`, `)+`, got '`+(this.terminals_[S]||S)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(S==p?`end of input`:`'`+(this.terminals_[S]||S)+`'`),this.parseError(M,{text:h.match,token:this.terminals_[S]||S,line:h.yylineno,loc:v,expected:j})}if(T[0]instanceof Array&&T.length>1)throw Error(`Parse Error: multiple actions possible at state: `+w+`, token: `+S);switch(T[0]){case 1:r.push(S),a.push(h.yytext),o.push(h.yylloc),r.push(T[1]),S=null,C?(S=C,C=null):(u=h.yyleng,c=h.yytext,l=h.yylineno,v=h.yylloc,d>0&&d--);break;case 2:if(k=this.productions_[T[1]][1],D.$=a[a.length-k],D._$={first_line:o[o.length-(k||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(k||1)].first_column,last_column:o[o.length-1].last_column},y&&(D._$.range=[o[o.length-(k||1)].range[0],o[o.length-1].range[1]]),E=this.performAction.apply(D,[c,u,l,g.yy,T[1],a,o].concat(m)),E!==void 0)return E;k&&(r=r.slice(0,-1*k*2),a=a.slice(0,-1*k),o=o.slice(0,-1*k)),r.push(this.productions_[T[1]][0]),a.push(D.$),o.push(D._$),A=s[r[r.length-2]][r[r.length-1]],r.push(A);break;case 3:return!0}}return!0},`parse`)};N.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{"case-insensitive":!0},performAction:e(function(t,n,r,i){function a(){let e=n.yytext.indexOf(`%%`);if(e===0)return!1;if(e>0){let r=n.yytext.slice(0,e),i=n.yytext.slice(e);i&&t.lexer.unput(i),n.yytext=r}return!0}switch(e(a,`processId`),r){case 0:return 38;case 1:return 40;case 2:return 39;case 3:return 44;case 4:return 51;case 5:return 52;case 6:return 53;case 7:return 54;case 8:return 5;case 9:break;case 10:break;case 11:break;case 12:break;case 13:return this.pushState(`SCALE`),17;case 14:return 18;case 15:this.popState();break;case 16:return this.begin(`acc_title`),33;case 17:return this.popState(),`acc_title_value`;case 18:return this.begin(`acc_descr`),35;case 19:return this.popState(),`acc_descr_value`;case 20:this.begin(`acc_descr_multiline`);break;case 21:this.popState();break;case 22:return`acc_descr_multiline_value`;case 23:return this.pushState(`CLASSDEF`),41;case 24:return this.popState(),this.pushState(`CLASSDEFID`),`DEFAULT_CLASSDEF_ID`;case 25:return this.popState(),this.pushState(`CLASSDEFID`),42;case 26:return this.popState(),43;case 27:return this.pushState(`CLASS`),48;case 28:return this.popState(),this.pushState(`CLASS_STYLE`),49;case 29:return this.popState(),50;case 30:return this.pushState(`STYLE`),45;case 31:return this.popState(),this.pushState(`STYLEDEF_STYLES`),46;case 32:return this.popState(),47;case 33:return this.pushState(`SCALE`),17;case 34:return 18;case 35:this.popState();break;case 36:this.pushState(`STATE`);break;case 37:return this.popState(),n.yytext=n.yytext.slice(0,-8).trim(),25;case 38:return this.popState(),n.yytext=n.yytext.slice(0,-8).trim(),26;case 39:return this.popState(),n.yytext=n.yytext.slice(0,-10).trim(),27;case 40:return this.popState(),n.yytext=n.yytext.slice(0,-8).trim(),25;case 41:return this.popState(),n.yytext=n.yytext.slice(0,-8).trim(),26;case 42:return this.popState(),n.yytext=n.yytext.slice(0,-10).trim(),27;case 43:return 51;case 44:return 52;case 45:return 53;case 46:return 54;case 47:this.pushState(`STATE_STRING`);break;case 48:return this.pushState(`STATE_ID`),`AS`;case 49:return a()?(this.popState(),`ID`):void 0;case 50:this.popState();break;case 51:return`STATE_DESCR`;case 52:throw Error(`Error: State name must be a single word. Found: "`+n.yytext.trim()+`"`);case 53:return 19;case 54:this.popState();break;case 55:return this.popState(),this.pushState(`struct`),20;case 56:return this.popState(),21;case 57:break;case 58:return this.begin(`NOTE`),29;case 59:return this.popState(),this.pushState(`NOTE_ID`),59;case 60:return this.popState(),this.pushState(`NOTE_ID`),60;case 61:this.popState(),this.pushState(`FLOATING_NOTE`);break;case 62:return this.popState(),this.pushState(`FLOATING_NOTE_ID`),`AS`;case 63:break;case 64:return`NOTE_TEXT`;case 65:return a()?(this.popState(),`ID`):void 0;case 66:return a()?(this.popState(),this.pushState(`NOTE_TEXT`),24):void 0;case 67:return this.popState(),n.yytext=n.yytext.substr(2).trim(),31;case 68:return this.popState(),n.yytext=n.yytext.slice(0,-8).trim(),31;case 69:return 6;case 70:return 6;case 71:return 16;case 72:return 57;case 73:return a()?24:void 0;case 74:return n.yytext=n.yytext.trim(),14;case 75:return 15;case 76:return 28;case 77:return 58;case 78:return 5;case 79:return`INVALID`}},`anonymous`),rules:[/^(?:click\b)/i,/^(?:href\b)/i,/^(?:"[^"]*")/i,/^(?:default\b)/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:[\n]+)/i,/^(?:[\s]+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:classDef\s+)/i,/^(?:DEFAULT\s+)/i,/^(?:\w+\s+)/i,/^(?:[^\n]*)/i,/^(?:class\s+)/i,/^(?:(\w+)+((,\s*\w+)*))/i,/^(?:[^\n]*)/i,/^(?:style\s+)/i,/^(?:[\w,]+\s+)/i,/^(?:[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:state\s+)/i,/^(?:.*<>)/i,/^(?:.*<>)/i,/^(?:.*<>)/i,/^(?:.*\[\[fork\]\])/i,/^(?:.*\[\[join\]\])/i,/^(?:.*\[\[choice\]\])/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:["])/i,/^(?:\s*as\s+)/i,/^(?:[^\n\{]*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:\w+\s+\w+.*?\{)/i,/^(?:[^\n\s\{]+)/i,/^(?:\n)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:[\n])/i,/^(?:note\s+)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:")/i,/^(?:\s*as\s*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n]*)/i,/^(?:\s*[^:\n\s\-]+)/i,/^(?:\s*:[^:\n;]+)/i,/^(?:[\s\S]*?\n\s*end note\b)/i,/^(?:stateDiagram\s+)/i,/^(?:stateDiagram-v2\s+)/i,/^(?:hide empty description\b)/i,/^(?:\[\*\])/i,/^(?:[^:\n\s\-\{]+)/i,/^(?:\s*:(?:[^:\n;]|:[^:\n;])+)/i,/^(?:-->)/i,/^(?:--)/i,/^(?::::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{LINE:{rules:[10,11,12],inclusive:!1},struct:{rules:[10,11,12,23,27,30,36,43,44,45,46,56,57,58,72,73,74,75,76,77],inclusive:!1},FLOATING_NOTE_ID:{rules:[65],inclusive:!1},FLOATING_NOTE:{rules:[62,63,64],inclusive:!1},NOTE_TEXT:{rules:[67,68],inclusive:!1},NOTE_ID:{rules:[66],inclusive:!1},NOTE:{rules:[59,60,61],inclusive:!1},STYLEDEF_STYLEOPTS:{rules:[],inclusive:!1},STYLEDEF_STYLES:{rules:[32],inclusive:!1},STYLE_IDS:{rules:[],inclusive:!1},STYLE:{rules:[31],inclusive:!1},CLASS_STYLE:{rules:[29],inclusive:!1},CLASS:{rules:[28],inclusive:!1},CLASSDEFID:{rules:[26],inclusive:!1},CLASSDEF:{rules:[24,25],inclusive:!1},acc_descr_multiline:{rules:[21,22],inclusive:!1},acc_descr:{rules:[19],inclusive:!1},acc_title:{rules:[17],inclusive:!1},SCALE:{rules:[14,15,34,35],inclusive:!1},ALIAS:{rules:[],inclusive:!1},STATE_ID:{rules:[49],inclusive:!1},STATE_STRING:{rules:[50,51],inclusive:!1},FORK_STATE:{rules:[],inclusive:!1},STATE:{rules:[10,11,12,37,38,39,40,41,42,47,48,52,53,54,55],inclusive:!1},ID:{rules:[10,11,12],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,11,12,13,16,18,20,23,27,30,33,36,55,58,69,70,71,72,73,74,75,77,78,79],inclusive:!0}}}})();function P(){this.yy={}}return e(P,`Parser`),P.prototype=N,N.Parser=P,new P})();y.parser=y;var b=y,x=`TB`,S=`TB`,C=`dir`,w=`state`,T=`root`,E=`relation`,D=`classDef`,O=`style`,k=`applyClass`,A=`default`,j=`divider`,M=`fill:none`,N=`fill: #333`,P=`c`,ee=`markdown`,F=`normal`,I=`rect`,L=`rectWithTitle`,te=`stateStart`,ne=`stateEnd`,R=`divider`,re=`roundedWithTitle`,ie=`note`,ae=`noteGroup`,z=`statediagram`,oe=`${z}-state`,B=`transition`,se=`note`,ce=`${B} note-edge`,le=`${z}-${se}`,ue=`${z}-cluster`,de=`${z}-cluster-alt`,V=`parent`,H=`note`,fe=`state`,U=`----`,pe=`${U}${H}`,W=`${U}${V}`,G=e((e,t=S)=>{if(!e.doc)return t;let n=t;for(let t of e.doc)t.stmt===`dir`&&(n=t.value);return n},`getDir`),me={getClasses:e(function(e,t){return t.db.getClasses()},`getClasses`),draw:e(async function(e,n,r,i){t.info(`REF0:`),t.info(`Drawing state diagram (v2)`,n);let{securityLevel:a,state:o,layout:s}=d();i.db.extract(i.db.getRootDocV2());let c=i.db.getData(),l=g(n,a);c.type=i.type,c.layoutAlgorithm=s,c.nodeSpacing=o?.nodeSpacing||50,c.rankSpacing=o?.rankSpacing||50,d().look===`neo`?c.markers=[`barbNeo`]:c.markers=[`barb`],c.diagramId=n,await v(c,l);try{(typeof i.db.getLinks==`function`?i.db.getLinks():new Map).forEach((e,n)=>{let r=typeof n==`string`?n:typeof n?.id==`string`?n.id:``,i=c.nodes.find(e=>e.id===r);if(!r){t.warn(`⚠️ Invalid or missing stateId from key:`,JSON.stringify(n));return}let a=l.node()?.querySelectorAll(`g.node, g.rough-node`),o;if(a?.forEach(e=>{let t=e.textContent?.trim();(e.id===i?.domId||t===r)&&(o=e)}),!o){t.warn(`⚠️ Could not find node matching text:`,r);return}let s=o.parentNode;if(!s){t.warn(`⚠️ Node has no parent, cannot wrap:`,r);return}let u=document.createElementNS(`http://www.w3.org/2000/svg`,`a`),d=e.url.replace(/^"+|"+$/g,``);if(u.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,d),u.setAttribute(`target`,`_blank`),e.tooltip){let t=e.tooltip.replace(/^"+|"+$/g,``);u.setAttribute(`title`,t),o.setAttribute(`title`,t)}s.replaceChild(u,o),u.appendChild(o),t.info(`🔗 Wrapped node in
    tag for:`,r,e.url)})}catch(e){t.error(`❌ Error injecting clickable links:`,e)}p.insertTitle(l,`statediagramTitleText`,o?.titleTopMargin??25,i.db.getDiagramTitle()),_(l,8,z,o?.useMaxWidth??!0)},`draw`),getDir:G},K=new Map,q=0;function J(e=``,t=0,n=``,r=U){return`${fe}-${e}${n!==null&&n.length>0?`${r}${n}`:``}-${t}`}e(J,`stateDomId`);var he=e((e,n,r,i,a,o,s,l)=>{t.trace(`items`,n),n.forEach(t=>{switch(t.stmt){case w:Z(e,t,r,i,a,o,s,l);break;case A:Z(e,t,r,i,a,o,s,l);break;case E:{Z(e,t.state1,r,i,a,o,s,l),Z(e,t.state2,r,i,a,o,s,l);let n=s===`neo`,u={id:`edge`+q,start:t.state1.id,end:t.state2.id,arrowhead:`normal`,arrowTypeEnd:n?`arrow_barb_neo`:`arrow_barb`,style:M,labelStyle:``,label:c.sanitizeText(t.description??``,d()),arrowheadStyle:N,labelpos:P,labelType:ee,thickness:F,classes:B,look:s};a.push(u),q++}break}})},`setupDoc`),ge=e((e,t=S)=>{let n=t;if(e.doc)for(let t of e.doc)t.stmt===`dir`&&(n=t.value);return n},`getDir`);function Y(e,t,n){if(!t.id||t.id===``||t.id===``)return;t.cssClasses&&(Array.isArray(t.cssCompiledStyles)||(t.cssCompiledStyles=[]),t.cssClasses.split(` `).forEach(e=>{let r=n.get(e);r&&(t.cssCompiledStyles=[...t.cssCompiledStyles??[],...r.styles])}));let r=e.find(e=>e.id===t.id);r?Object.assign(r,t):e.push(t)}e(Y,`insertOrUpdateNode`);function X(e){return e?.classes?.join(` `)??``}e(X,`getClassesFromDbInfo`);function _e(e){return e?.styles??[]}e(_e,`getStylesFromDbInfo`);var Z=e((e,n,r,i,a,o,s,l)=>{let u=n.id,f=r.get(u),p=X(f),m=_e(f),h=d();if(t.info(`dataFetcher parsedItem`,n,f,m),u!==`root`){let r=I;n.start===!0?r=te:n.start===!1&&(r=ne),n.type!==A&&(r=n.type),K.get(u)||K.set(u,{id:u,shape:r,description:c.sanitizeText(u,h),cssClasses:`${p} ${oe}`,cssStyles:m});let d=K.get(u);n.description&&(Array.isArray(d.description)?(d.shape=L,d.description.push(n.description)):d.description?.length&&d.description.length>0?(d.shape=L,d.description===u?d.description=[n.description]:d.description=[d.description,n.description]):(d.shape=I,d.description=n.description),d.description=c.sanitizeTextOrArray(d.description,h)),d.description?.length===1&&d.shape===L&&(d.type===`group`?d.shape=re:d.shape=I),!d.type&&n.doc&&(t.info(`Setting cluster for XCX`,u,ge(n)),d.type=`group`,d.isGroup=!0,d.dir=ge(n),d.explicitDir=n.doc.some(e=>e.stmt===`dir`),d.shape=n.type===j?R:re,d.cssClasses=`${d.cssClasses} ${ue} ${o?de:``}`);let f={labelStyle:``,shape:d.shape,label:d.description,cssClasses:d.cssClasses,cssCompiledStyles:[],cssStyles:d.cssStyles,id:u,dir:d.dir,domId:J(u,q),type:d.type,isGroup:d.type===`group`,padding:8,rx:10,ry:10,look:s,labelType:`markdown`};if(f.shape===R&&(f.label=``),e&&e.id!==`root`&&(t.trace(`Setting node `,u,` to be child of its parent `,e.id),f.parentId=e.id),f.centerLabel=!0,n.note){let e={labelStyle:``,shape:ie,label:n.note.text,labelType:`markdown`,cssClasses:le,cssStyles:[],cssCompiledStyles:[],id:u+pe+`-`+q,domId:J(u,q,H),type:d.type,isGroup:d.type===`group`,padding:h.flowchart?.padding,look:s,position:n.note.position},t=u+W,r={labelStyle:``,shape:ae,label:n.note.text,cssClasses:d.cssClasses,cssStyles:[],id:u+W,domId:J(u,q,V),type:`group`,isGroup:!0,padding:16,look:s,position:n.note.position};q++,r.id=t,e.parentId=t,Y(i,r,l),Y(i,e,l),Y(i,f,l);let o=u,c=e.id;n.note.position===`left of`&&(o=e.id,c=u),a.push({id:o+`-`+c,start:o,end:c,arrowhead:`none`,arrowTypeEnd:``,style:M,labelStyle:``,classes:ce,arrowheadStyle:N,labelpos:P,labelType:ee,thickness:F,look:s})}else Y(i,f,l)}n.doc&&(t.trace(`Adding nodes children `),he(n,n.doc,r,i,a,!o,s,l))},`dataFetcher`),ve=e(()=>{K.clear(),q=0},`reset`),Q={START_NODE:`[*]`,START_TYPE:`start`,END_NODE:`[*]`,END_TYPE:`end`,COLOR_KEYWORD:`color`,FILL_KEYWORD:`fill`,BG_FILL:`bgFill`,STYLECLASS_SEP:`,`},ye=e(()=>new Map,`newClassesList`),be=e(()=>({relations:[],states:new Map,documents:{}}),`newDoc`),$=e(e=>JSON.parse(JSON.stringify(e)),`clone`),xe=class{constructor(e){this.version=e,this.nodes=[],this.edges=[],this.rootDoc=[],this.classes=ye(),this.documents={root:be()},this.currentDocument=this.documents.root,this.startEndCount=0,this.dividerCnt=0,this.links=new Map,this.funs=[],this.getAccTitle=f,this.setAccTitle=o,this.getAccDescription=l,this.setAccDescription=i,this.setDiagramTitle=a,this.getDiagramTitle=u,this.clear(),this.setRootDoc=this.setRootDoc.bind(this),this.getDividerId=this.getDividerId.bind(this),this.setDirection=this.setDirection.bind(this),this.trimColon=this.trimColon.bind(this),this.bindFunctions=this.bindFunctions.bind(this)}static{e(this,`StateDB`)}static{this.relationType={AGGREGATION:0,EXTENSION:1,COMPOSITION:2,DEPENDENCY:3}}extract(e){this.clear(!0);for(let t of Array.isArray(e)?e:e.doc)switch(t.stmt){case w:this.addState(t.id.trim(),t.type,t.doc,t.description,t.note);break;case E:this.addRelation(t.state1,t.state2,t.description);break;case D:this.addStyleClass(t.id.trim(),t.classes);break;case O:this.handleStyleDef(t);break;case k:this.setCssClass(t.id.trim(),t.styleClass);break;case`click`:this.addLink(t.id,t.url,t.tooltip);break}let t=this.getStates(),n=d();ve(),Z(void 0,this.getRootDocV2(),t,this.nodes,this.edges,!0,n.look,this.classes);for(let e of this.nodes)if(Array.isArray(e.label)){if(e.description=e.label.slice(1),e.isGroup&&e.description.length>0)throw Error(`Group nodes can only have label. Remove the additional description for node [${e.id}]`);e.label=e.label[0]}}handleStyleDef(e){let t=e.id.trim().split(`,`),n=e.styleClass.split(`,`);for(let e of t){let t=this.getState(e);if(!t){let n=e.trim();this.addState(n),t=this.getState(n)}t&&(t.styles=n.map(e=>e.replace(/;/g,``)?.trim()))}}setRootDoc(e){t.info(`Setting root doc`,e),this.rootDoc=e,this.version===1?this.extract(e):this.extract(this.getRootDocV2())}docTranslator(e,t,n){if(t.stmt===E){this.docTranslator(e,t.state1,!0),this.docTranslator(e,t.state2,!1);return}if(t.stmt===w&&(t.id===Q.START_NODE?(t.id=e.id+(n?`_start`:`_end`),t.start=n):t.id=t.id.trim()),t.stmt!==T&&t.stmt!==w||!t.doc)return;let r=[],i=[];for(let e of t.doc)if(e.type===j){let t=$(e);t.doc=$(i),r.push(t),i=[]}else i.push(e);if(r.length>0&&i.length>0){let e={stmt:w,id:m(),type:`divider`,doc:$(i)};r.push($(e)),t.doc=r}t.doc.forEach(e=>this.docTranslator(t,e,!0))}getRootDocV2(){return this.docTranslator({id:T,stmt:T},{id:T,stmt:T,doc:this.rootDoc},!0),{id:T,doc:this.rootDoc}}addState(e,n=A,r=void 0,i=void 0,a=void 0,o=void 0,s=void 0,l=void 0){let u=e?.trim();if(!this.currentDocument.states.has(u))t.info(`Adding state `,u,i),this.currentDocument.states.set(u,{stmt:w,id:u,descriptions:[],type:n,doc:r,note:a,classes:[],styles:[],textStyles:[]});else{let e=this.currentDocument.states.get(u);if(!e)throw Error(`State not found: ${u}`);e.doc||=r,e.type||=n}if(i&&(t.info(`Setting state description`,u,i),(Array.isArray(i)?i:[i]).forEach(e=>this.addDescription(u,e.trim()))),a){let e=this.currentDocument.states.get(u);if(!e)throw Error(`State not found: ${u}`);e.note=a,e.note.text=c.sanitizeText(e.note.text,d())}o&&(t.info(`Setting state classes`,u,o),(Array.isArray(o)?o:[o]).forEach(e=>this.setCssClass(u,e.trim()))),s&&(t.info(`Setting state styles`,u,s),(Array.isArray(s)?s:[s]).forEach(e=>this.setStyle(u,e.trim()))),l&&(t.info(`Setting state styles`,u,s),(Array.isArray(l)?l:[l]).forEach(e=>this.setTextStyle(u,e.trim())))}clear(e){this.nodes=[],this.edges=[],this.funs=[this.setupToolTips.bind(this)],this.documents={root:be()},this.currentDocument=this.documents.root,this.startEndCount=0,this.classes=ye(),e||(this.links=new Map,s())}getState(e){return this.currentDocument.states.get(e)}getStates(){return this.currentDocument.states}logDocuments(){t.info(`Documents = `,this.documents)}getRelations(){return this.currentDocument.relations}addLink(e,n,r){this.links.set(e,{url:n,tooltip:r}),t.warn(`Adding link`,e,n,r)}getLinks(){return this.links}startIdIfNeeded(e=``){return e===Q.START_NODE?(this.startEndCount++,`${Q.START_TYPE}${this.startEndCount}`):e}startTypeIfNeeded(e=``,t=A){return e===Q.START_NODE?Q.START_TYPE:t}endIdIfNeeded(e=``){return e===Q.END_NODE?(this.startEndCount++,`${Q.END_TYPE}${this.startEndCount}`):e}endTypeIfNeeded(e=``,t=A){return e===Q.END_NODE?Q.END_TYPE:t}addRelationObjs(e,t,n=``){let r=this.startIdIfNeeded(e.id.trim()),i=this.startTypeIfNeeded(e.id.trim(),e.type),a=this.startIdIfNeeded(t.id.trim()),o=this.startTypeIfNeeded(t.id.trim(),t.type);this.addState(r,i,e.doc,e.description,e.note,e.classes,e.styles,e.textStyles),this.addState(a,o,t.doc,t.description,t.note,t.classes,t.styles,t.textStyles),this.currentDocument.relations.push({id1:r,id2:a,relationTitle:c.sanitizeText(n,d())})}addRelation(e,t,n){if(typeof e==`object`&&typeof t==`object`)this.addRelationObjs(e,t,n);else if(typeof e==`string`&&typeof t==`string`){let r=this.startIdIfNeeded(e.trim()),i=this.startTypeIfNeeded(e),a=this.endIdIfNeeded(t.trim()),o=this.endTypeIfNeeded(t);this.addState(r,i),this.addState(a,o),this.currentDocument.relations.push({id1:r,id2:a,relationTitle:n?c.sanitizeText(n,d()):void 0})}}addDescription(e,t){let n=this.currentDocument.states.get(e),r=t.startsWith(`:`)?t.replace(`:`,``).trim():t;n?.descriptions?.push(c.sanitizeText(r,d()))}cleanupLabel(e){return e.startsWith(`:`)?e.slice(2).trim():e.trim()}getDividerId(){return this.dividerCnt++,`divider-id-${this.dividerCnt}`}addStyleClass(e,t=``){this.classes.has(e)||this.classes.set(e,{id:e,styles:[],textStyles:[]});let n=this.classes.get(e);t&&n&&t.split(Q.STYLECLASS_SEP).forEach(e=>{let t=e.replace(/([^;]*);/,`$1`).trim();if(RegExp(Q.COLOR_KEYWORD).exec(e)){let e=t.replace(Q.FILL_KEYWORD,Q.BG_FILL).replace(Q.COLOR_KEYWORD,Q.FILL_KEYWORD);n.textStyles.push(e)}n.styles.push(t)})}getClasses(){return this.classes}setupToolTips(e){let t=h();n(e).select(`svg`).selectAll(`g.node, g.rough-node`).on(`mouseover`,e=>{let i=n(e.currentTarget),a=i.attr(`title`);if(a===null)return;let o=e.currentTarget?.getBoundingClientRect();t.transition().duration(200).style(`opacity`,`.9`),t.style(`left`,window.scrollX+o.left+(o.right-o.left)/2+`px`).style(`top`,window.scrollY+o.bottom+`px`),t.html(r.sanitize(a)),i.classed(`hover`,!0)}).on(`mouseout`,e=>{t.transition().duration(500).style(`opacity`,0),n(e.currentTarget).classed(`hover`,!1)})}setCssClass(e,t){e.split(`,`).forEach(e=>{let n=this.getState(e);if(!n){let t=e.trim();this.addState(t),n=this.getState(t)}n?.classes?.push(t)})}setStyle(e,t){this.getState(e)?.styles?.push(t)}setTextStyle(e,t){this.getState(e)?.textStyles?.push(t)}bindFunctions(e){this.funs.forEach(t=>{t(e)})}getDirectionStatement(){return this.rootDoc.find(e=>e.stmt===C)}getDirection(){return this.getDirectionStatement()?.value??x}setDirection(e){let t=this.getDirectionStatement();t?t.value=e:this.rootDoc.unshift({stmt:C,value:e})}trimColon(e){return e.startsWith(`:`)?e.slice(1).trim():e.trim()}getData(){let e=d();return{nodes:this.nodes,edges:this.edges,other:{},config:e,direction:G(this.getRootDocV2())}}getConfig(){return d().state}},Se=e(e=>` +defs [id$="-barbEnd"] { + fill: ${e.transitionColor}; + stroke: ${e.transitionColor}; + } +g.stateGroup text { + fill: ${e.nodeBorder}; + stroke: none; + font-size: 10px; +} +g.stateGroup text { + fill: ${e.textColor}; + stroke: none; + font-size: 10px; + +} +g.stateGroup .state-title { + font-weight: bolder; + fill: ${e.stateLabelColor}; +} + +g.stateGroup rect { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; +} + +g.stateGroup line { + stroke: ${e.lineColor}; + stroke-width: ${e.strokeWidth||1}; +} + +.transition { + stroke: ${e.transitionColor}; + stroke-width: ${e.strokeWidth||1}; + fill: none; +} + +.stateGroup .composit { + fill: ${e.background}; + border-bottom: 1px +} + +.stateGroup .alt-composit { + fill: #e0e0e0; + border-bottom: 1px +} + +.state-note { + stroke: ${e.noteBorderColor}; + fill: ${e.noteBkgColor}; + + text { + fill: ${e.noteTextColor}; + stroke: none; + font-size: 10px; + } +} + +.stateLabel .box { + stroke: none; + stroke-width: 0; + fill: ${e.mainBkg}; + opacity: 0.5; +} + +.edgeLabel .label rect { + fill: ${e.labelBackgroundColor}; + opacity: 0.5; +} +.edgeLabel { + background-color: ${e.edgeLabelBackground}; + p { + background-color: ${e.edgeLabelBackground}; + } + rect { + opacity: 0.5; + background-color: ${e.edgeLabelBackground}; + fill: ${e.edgeLabelBackground}; + } + text-align: center; +} +.edgeLabel .label text { + fill: ${e.transitionLabelColor||e.tertiaryTextColor}; +} +.label div .edgeLabel { + color: ${e.transitionLabelColor||e.tertiaryTextColor}; +} + +.stateLabel text { + fill: ${e.stateLabelColor}; + font-size: 10px; + font-weight: bold; +} + +.node circle.state-start { + fill: ${e.specialStateColor}; + stroke: ${e.specialStateColor}; +} + +.node .fork-join { + fill: ${e.specialStateColor}; + stroke: ${e.specialStateColor}; +} + +.node circle.state-end { + fill: ${e.innerEndBackground}; + stroke: ${e.background}; + stroke-width: 1.5 +} +.end-state-inner { + fill: ${e.compositeBackground||e.background}; + // stroke: ${e.background}; + stroke-width: 1.5 +} + +.node rect { + fill: ${e.stateBkg||e.mainBkg}; + stroke: ${e.stateBorder||e.nodeBorder}; + stroke-width: ${e.strokeWidth||1}px; +} +.node polygon { + fill: ${e.mainBkg}; + stroke: ${e.stateBorder||e.nodeBorder};; + stroke-width: ${e.strokeWidth||1}px; +} +[id$="-barbEnd"] { + fill: ${e.lineColor}; +} + +.statediagram-cluster rect { + fill: ${e.compositeTitleBackground}; + stroke: ${e.stateBorder||e.nodeBorder}; + stroke-width: ${e.strokeWidth||1}px; +} + +.cluster-label, .nodeLabel { + color: ${e.stateLabelColor}; + // line-height: 1; +} + +.statediagram-cluster rect.outer { + rx: 5px; + ry: 5px; +} +.statediagram-state .divider { + stroke: ${e.stateBorder||e.nodeBorder}; +} + +.statediagram-state .title-state { + rx: 5px; + ry: 5px; +} +.statediagram-cluster.statediagram-cluster .inner { + fill: ${e.compositeBackground||e.background}; +} +.statediagram-cluster.statediagram-cluster-alt .inner { + fill: ${e.altBackground?e.altBackground:`#efefef`}; +} + +.statediagram-cluster .inner { + rx:0; + ry:0; +} + +.statediagram-state rect.basic { + rx: 5px; + ry: 5px; +} +.statediagram-state rect.divider { + stroke-dasharray: 10,10; + fill: ${e.altBackground?e.altBackground:`#efefef`}; +} + +.note-edge { + stroke-dasharray: 5; +} + +.statediagram-note rect { + fill: ${e.noteBkgColor}; + stroke: ${e.noteBorderColor}; + stroke-width: 1px; + rx: 0; + ry: 0; +} +.statediagram-note rect { + fill: ${e.noteBkgColor}; + stroke: ${e.noteBorderColor}; + stroke-width: 1px; + rx: 0; + ry: 0; +} + +.statediagram-note text { + fill: ${e.noteTextColor}; +} + +.statediagram-note .nodeLabel { + color: ${e.noteTextColor}; +} +.statediagram .edgeLabel { + color: red; // ${e.noteTextColor}; +} + +[id$="-dependencyStart"], [id$="-dependencyEnd"] { + fill: ${e.lineColor}; + stroke: ${e.lineColor}; + stroke-width: ${e.strokeWidth||1}; +} + +.statediagramTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${e.textColor}; +} + +[data-look="neo"].statediagram-cluster rect { + fill: ${e.mainBkg}; + stroke: ${e.useGradient?`url(`+e.svgId+`-gradient)`:e.stateBorder||e.nodeBorder}; + stroke-width: ${e.strokeWidth??1}; +} +[data-look="neo"].statediagram-cluster rect.outer { + rx: ${e.radius}px; + ry: ${e.radius}px; + filter: ${e.dropShadow?e.dropShadow.replace(`url(#drop-shadow)`,`url(${e.svgId}-drop-shadow)`):`none`} +} +`,`getStyles`);export{Se as i,b as n,me as r,xe as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-FWX5IMBZ-ComLEIwh.js b/dist-desktop/assets/chunk-FWX5IMBZ-ComLEIwh.js new file mode 100644 index 0000000..b405a8c --- /dev/null +++ b/dist-desktop/assets/chunk-FWX5IMBZ-ComLEIwh.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dagre-VKFMJZFB-Cv2q18CS.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/src-UMNXGZaF.js","assets/rolldown-runtime-aKtaBQYM.js","assets/chunk-WYO6CB5R-Dv5kDyQC.js","assets/index-CXgd9jpl.js","assets/react-BLJmJXjR.js","assets/utils-BTuSbA5p.js","assets/chunk-ICXQ74PX-Czpgj8Uw.js","assets/dist-qx0Iv9vM.js","assets/chunk-HOUHSVGY-iJuv90UH.js","assets/chunk-Q4XR5HBZ-CQ8zkLYc.js","assets/chunk-7BUUIJ7U-Bb538aSH.js","assets/chunk-OGEWGWER-D-nWYRNR.js","assets/graphlib-DS17s2tU.js","assets/dagre-dpRSp0QF.js","assets/map-BaFkSB1l.js","assets/chunk-RYQCIY6F-Dtr3kkSR.js","assets/chunk-C7G6YPKG-DW-1jWUA.js","assets/chunk-ZGVPDNZ5-DGInJAPD.js","assets/rough.esm-CSKSodPl.js","assets/chunk-52WLFC77-BOCvVCX1.js","assets/line-b9Ala942.js","assets/path-BWPyau1x.js","assets/array-BifhSqXX.js","assets/swimlanes-5IMT3BWC-hyAz1L8O.js","assets/cose-bilkent-JH36ORCC-ClqQrHIF.js","assets/cytoscape.esm-CQFVGiJu.js"])))=>i.map(i=>d[i]); +import{t as e}from"./index-CXgd9jpl.js";import{n as t}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as n}from"./src-UMNXGZaF.js";import{b as r,s as i}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{d as a}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{a as o,i as s,s as c}from"./chunk-ZGVPDNZ5-DGInJAPD.js";import{a as l,i as u,o as d,r as f}from"./chunk-52WLFC77-BOCvVCX1.js";var p={common:i,getConfig:r,insertCluster:s,insertEdge:f,insertEdgeLabel:u,insertMarkers:l,insertNode:o,interpolateToCurve:a,labelHelper:c,log:n,positionEdgeLabel:d},m={},h=t(e=>{for(let t of e)m[t.name]=t},`registerLayoutLoaders`);t(()=>{h([{name:`dagre`,loader:t(async()=>await e(()=>import(`./dagre-VKFMJZFB-Cv2q18CS.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])),`loader`)},{name:`swimlane`,loader:t(async()=>await e(()=>import(`./swimlanes-5IMT3BWC-hyAz1L8O.js`),__vite__mapDeps([25,5,3,6,7,1,2,4,8,9,10,11,12,13,14,17,16,18,19,20,21,22,23,24])),`loader`)},{name:`cose-bilkent`,loader:t(async()=>await e(()=>import(`./cose-bilkent-JH36ORCC-ClqQrHIF.js`),__vite__mapDeps([26,3,1,2,27])),`loader`)}])},`registerDefaultLayoutLoaders`)();var g=t(async(e,t,n)=>{if(!(e.layoutAlgorithm in m))throw Error(`Unknown layout algorithm: ${e.layoutAlgorithm}`);if(e.diagramId)for(let t of e.nodes){let n=t.domId||t.id;t.domId=`${e.diagramId}-${n}`}let r=m[e.layoutAlgorithm],i=await r.loader(),{theme:a,themeVariables:o}=e.config,{useGradient:s,gradientStart:c,gradientStop:l}=o,u=t.attr(`id`);if(t.append(`defs`).append(`filter`).attr(`id`,`${u}-drop-shadow`).attr(`height`,`130%`).attr(`width`,`130%`).append(`feDropShadow`).attr(`dx`,`4`).attr(`dy`,`4`).attr(`stdDeviation`,0).attr(`flood-opacity`,`0.06`).attr(`flood-color`,`${a?.includes(`dark`)?`#FFFFFF`:`#000000`}`),t.append(`defs`).append(`filter`).attr(`id`,`${u}-drop-shadow-small`).attr(`height`,`150%`).attr(`width`,`150%`).append(`feDropShadow`).attr(`dx`,`2`).attr(`dy`,`2`).attr(`stdDeviation`,0).attr(`flood-opacity`,`0.06`).attr(`flood-color`,`${a?.includes(`dark`)?`#FFFFFF`:`#000000`}`),s){let e=t.append(`linearGradient`).attr(`id`,t.attr(`id`)+`-gradient`).attr(`gradientUnits`,`objectBoundingBox`).attr(`x1`,`0%`).attr(`y1`,`0%`).attr(`x2`,`100%`).attr(`y2`,`0%`);e.append(`svg:stop`).attr(`offset`,`0%`).attr(`stop-color`,c).attr(`stop-opacity`,1),e.append(`svg:stop`).attr(`offset`,`100%`).attr(`stop-color`,l).attr(`stop-opacity`,1)}return i.render(e,t,p,{algorithm:r.algorithm},n)},`render`),_=t((e=``,{fallback:t=`dagre`}={})=>{if(e in m)return e;if(t in m)return n.warn(`Layout algorithm ${e} is not registered. Using ${t} as fallback.`),t;throw Error(`Both layout algorithms ${e} and ${t} are not registered.`)},`getRegisteredLayoutAlgorithm`);export{h as n,g as r,_ as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-HOUHSVGY-iJuv90UH.js b/dist-desktop/assets/chunk-HOUHSVGY-iJuv90UH.js new file mode 100644 index 0000000..e168d2b --- /dev/null +++ b/dist-desktop/assets/chunk-HOUHSVGY-iJuv90UH.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{b as n,z as r}from"./chunk-WYO6CB5R-Dv5kDyQC.js";var i=Object.freeze({left:0,top:0,width:16,height:16}),a=Object.freeze({rotate:0,vFlip:!1,hFlip:!1}),o=Object.freeze({...i,...a}),s=Object.freeze({...o,body:``,hidden:!1}),c=Object.freeze({width:null,height:null}),l=Object.freeze({...c,...a}),u=(e,t,n,r=``)=>{let i=e.split(`:`);if(e.slice(0,1)===`@`){if(i.length<2||i.length>3)return null;r=i.shift().slice(1)}if(i.length>3||!i.length)return null;if(i.length>1){let e=i.pop(),n=i.pop(),a={provider:i.length>0?i[0]:r,prefix:n,name:e};return t&&!d(a)?null:a}let a=i[0],o=a.split(`-`);if(o.length>1){let e={provider:r,prefix:o.shift(),name:o.join(`-`)};return t&&!d(e)?null:e}if(n&&r===``){let e={provider:r,prefix:``,name:a};return t&&!d(e,n)?null:e}return null},d=(e,t)=>e?!!((t&&e.prefix===``||e.prefix)&&e.name):!1;function f(e,t){let n={};!e.hFlip!=!t.hFlip&&(n.hFlip=!0),!e.vFlip!=!t.vFlip&&(n.vFlip=!0);let r=((e.rotate||0)+(t.rotate||0))%4;return r&&(n.rotate=r),n}function p(e,t){let n=f(e,t);for(let r in s)r in a?r in e&&!(r in n)&&(n[r]=a[r]):r in t?n[r]=t[r]:r in e&&(n[r]=e[r]);return n}function m(e,t){let n=e.icons,r=e.aliases||Object.create(null),i=Object.create(null);function a(e){if(n[e])return i[e]=[];if(!(e in i)){i[e]=null;let t=r[e]&&r[e].parent,n=t&&a(t);n&&(i[e]=[t].concat(n))}return i[e]}return(t||Object.keys(n).concat(Object.keys(r))).forEach(a),i}function h(e,t,n){let r=e.icons,i=e.aliases||Object.create(null),a={};function o(e){a=p(r[e]||i[e],a)}return o(t),n.forEach(o),p(e,a)}function g(e,t){if(e.icons[t])return h(e,t,[]);let n=m(e,[t])[t];return n?h(e,t,n):null}var _=/(-?[0-9.]*[0-9]+[0-9.]*)/g,v=/^-?[0-9.]*[0-9]+[0-9.]*$/g;function y(e,t,n){if(t===1)return e;if(n||=100,typeof e==`number`)return Math.ceil(e*t*n)/n;if(typeof e!=`string`)return e;let r=e.split(_);if(r===null||!r.length)return e;let i=[],a=r.shift(),o=v.test(a);for(;;){if(o){let e=parseFloat(a);isNaN(e)?i.push(a):i.push(Math.ceil(e*t*n)/n)}else i.push(a);if(a=r.shift(),a===void 0)return i.join(``);o=!o}}function b(e,t=`defs`){let n=``,r=e.indexOf(`<`+t);for(;r>=0;){let i=e.indexOf(`>`,r),a=e.indexOf(``,a);if(o===-1)break;n+=e.slice(i+1,a).trim(),e=e.slice(0,r).trim()+e.slice(o+1)}return{defs:n,content:e}}function x(e,t){return e?``+e+``+t:t}function S(e,t,n){let r=b(e);return x(r.defs,t+r.content+n)}var C=e=>e===`unset`||e===`undefined`||e===`none`;function w(e,t){let n={...o,...e},r={...l,...t},i={left:n.left,top:n.top,width:n.width,height:n.height},a=n.body;[n,r].forEach(e=>{let t=[],n=e.hFlip,r=e.vFlip,o=e.rotate;n?r?o+=2:(t.push(`translate(`+(i.width+i.left).toString()+` `+(0-i.top).toString()+`)`),t.push(`scale(-1 1)`),i.top=i.left=0):r&&(t.push(`translate(`+(0-i.left).toString()+` `+(i.height+i.top).toString()+`)`),t.push(`scale(1 -1)`),i.top=i.left=0);let s;switch(o<0&&(o-=Math.floor(o/4)*4),o%=4,o){case 1:s=i.height/2+i.top,t.unshift(`rotate(90 `+s.toString()+` `+s.toString()+`)`);break;case 2:t.unshift(`rotate(180 `+(i.width/2+i.left).toString()+` `+(i.height/2+i.top).toString()+`)`);break;case 3:s=i.width/2+i.left,t.unshift(`rotate(-90 `+s.toString()+` `+s.toString()+`)`);break}o%2==1&&(i.left!==i.top&&(s=i.left,i.left=i.top,i.top=s),i.width!==i.height&&(s=i.width,i.width=i.height,i.height=s)),t.length&&(a=S(a,``,``))});let s=r.width,c=r.height,u=i.width,d=i.height,f,p;s===null?(p=c===null?`1em`:c===`auto`?d:c,f=y(p,u/d)):(f=s===`auto`?u:s,p=c===null?y(f,d/u):c===`auto`?d:c);let m={},h=(e,t)=>{C(t)||(m[e]=t.toString())};h(`width`,f),h(`height`,p);let g=[i.left,i.top,u,d];return m.viewBox=g.join(` `),{attributes:m,viewBox:g,body:a}}var T=/\sid="(\S+)"/g,E=new Map;function D(e){e=e.replace(/[0-9]+$/,``)||`a`;let t=E.get(e)||0;return E.set(e,t+1),t?`${e}${t}`:e}function O(e){let t=[],n;for(;n=T.exec(e);)t.push(n[1]);if(!t.length)return e;let r=`suffix`+(Math.random()*16777216|Date.now()).toString(16);return t.forEach(t=>{let n=D(t),i=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);e=e.replace(RegExp(`([#;"])(`+i+`)([")]|\\.[a-z])`,`g`),`$1`+n+r+`$3`)}),e=e.replace(new RegExp(r,`g`),``),e}function k(e,t){let n=e.indexOf(`xlink:`)===-1?``:` xmlns:xlink="http://www.w3.org/1999/xlink"`;for(let e in t)n+=` `+e+`="`+t[e]+`"`;return``+e+``}var A={body:`?`,height:80,width:80},j=new Map,M=new Map,N=e(e=>{for(let n of e){if(!n.name)throw Error(`Invalid icon loader. Must have a "name" property with non-empty string value.`);if(t.debug(`Registering icon pack:`,n.name),`loader`in n)M.set(n.name,n.loader);else if(`icons`in n)j.set(n.name,n.icons);else throw t.error(`Invalid icon loader:`,n),Error(`Invalid icon loader. Must have either "icons" or "loader" property.`)}},`registerIconPacks`),P=e(async(e,n)=>{let r=u(e,!0,n!==void 0);if(!r)throw Error(`Invalid icon name: ${e}`);let i=r.prefix||n;if(!i)throw Error(`Icon name must contain a prefix: ${e}`);let a=j.get(i);if(!a){let e=M.get(i);if(!e)throw Error(`Icon set not found: ${r.prefix}`);try{a={...await e(),prefix:i},j.set(i,a)}catch(e){throw t.error(e),Error(`Failed to load icon set: ${r.prefix}`)}}let o=g(a,r.name);if(!o)throw Error(`Icon not found: ${e}`);return o},`getRegisteredIconData`),F=e(async e=>{try{return await P(e),!0}catch{return!1}},`isIconAvailable`),I=e(async(e,i,a)=>{let o;try{o=await P(e,i?.fallbackPrefix)}catch(e){t.error(e),o=A}let s=w(o,i);return r(k(O(s.body),{...s.attributes,...a}),n())},`getIconSVG`);export{A as i,F as n,N as r,I as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-ICXQ74PX-Czpgj8Uw.js b/dist-desktop/assets/chunk-ICXQ74PX-Czpgj8Uw.js new file mode 100644 index 0000000..7f15439 --- /dev/null +++ b/dist-desktop/assets/chunk-ICXQ74PX-Czpgj8Uw.js @@ -0,0 +1,2 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{R as r,h as i,p as a,r as o,s}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as c}from"./dist-qx0Iv9vM.js";function l(e){this._context=e}l.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function u(e){return new l(e)}var d=class{constructor(e,t){this._context=e,this._x=t}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,t,e,t):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+t)/2,e,this._y0,e,t);break}this._x0=e,this._y0=t}};function f(e){return new d(e,!0)}function ee(e){return new d(e,!1)}function p(){}function m(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function h(e){this._context=e}h.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:m(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:m(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function te(e){return new h(e)}function ne(e){this._context=e}ne.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:m(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function re(e){return new ne(e)}function ie(e){this._context=e}ie.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:m(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function ae(e){return new ie(e)}function oe(e,t){this._basis=new h(e),this._beta=t}oe.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var e=this._x,t=this._y,n=e.length-1;if(n>0)for(var r=e[0],i=t[0],a=e[n]-r,o=t[n]-i,s=-1,c;++s<=n;)c=s/n,this._basis.point(this._beta*e[s]+(1-this._beta)*(r+c*a),this._beta*t[s]+(1-this._beta)*(i+c*o));this._x=this._y=null,this._basis.lineEnd()},point:function(e,t){this._x.push(+e),this._y.push(+t)}};var se=(function e(t){function n(e){return t===1?new h(e):new oe(e,t)}return n.beta=function(t){return e(+t)},n})(.85);function g(e,t,n){e._context.bezierCurveTo(e._x1+e._k*(e._x2-e._x0),e._y1+e._k*(e._y2-e._y0),e._x2+e._k*(e._x1-t),e._y2+e._k*(e._y1-n),e._x2,e._y2)}function _(e,t){this._context=e,this._k=(1-t)/6}_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:g(this,this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2,this._x1=e,this._y1=t;break;case 2:this._point=3;default:g(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var ce=(function e(t){function n(e){return new _(e,t)}return n.tension=function(t){return e(+t)},n})(0);function v(e,t){this._context=e,this._k=(1-t)/6}v.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:g(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var le=(function e(t){function n(e){return new v(e,t)}return n.tension=function(t){return e(+t)},n})(0);function y(e,t){this._context=e,this._k=(1-t)/6}y.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:g(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var ue=(function e(t){function n(e){return new y(e,t)}return n.tension=function(t){return e(+t)},n})(0);function b(e,t,n){var r=e._x1,i=e._y1,a=e._x2,o=e._y2;if(e._l01_a>1e-12){var s=2*e._l01_2a+3*e._l01_a*e._l12_a+e._l12_2a,c=3*e._l01_a*(e._l01_a+e._l12_a);r=(r*s-e._x0*e._l12_2a+e._x2*e._l01_2a)/c,i=(i*s-e._y0*e._l12_2a+e._y2*e._l01_2a)/c}if(e._l23_a>1e-12){var l=2*e._l23_2a+3*e._l23_a*e._l12_a+e._l12_2a,u=3*e._l23_a*(e._l23_a+e._l12_a);a=(a*l+e._x1*e._l23_2a-t*e._l12_2a)/u,o=(o*l+e._y1*e._l23_2a-n*e._l12_2a)/u}e._context.bezierCurveTo(r,i,a,o,e._x2,e._y2)}function de(e,t){this._context=e,this._alpha=t}de.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=(n*n+r*r)**+this._alpha)}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3;default:b(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var fe=(function e(t){function n(e){return t?new de(e,t):new _(e,0)}return n.alpha=function(t){return e(+t)},n})(.5);function pe(e,t){this._context=e,this._alpha=t}pe.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=(n*n+r*r)**+this._alpha)}switch(this._point){case 0:this._point=1,this._x3=e,this._y3=t;break;case 1:this._point=2,this._context.moveTo(this._x4=e,this._y4=t);break;case 2:this._point=3,this._x5=e,this._y5=t;break;default:b(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var me=(function e(t){function n(e){return t?new pe(e,t):new v(e,0)}return n.alpha=function(t){return e(+t)},n})(.5);function he(e,t){this._context=e,this._alpha=t}he.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=(n*n+r*r)**+this._alpha)}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:b(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};var ge=(function e(t){function n(e){return t?new he(e,t):new y(e,0)}return n.alpha=function(t){return e(+t)},n})(.5);function _e(e){this._context=e}_e.prototype={areaStart:p,areaEnd:p,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function ve(e){return new _e(e)}function ye(e){return e<0?-1:1}function be(e,t,n){var r=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(r||i<0&&-0),o=(n-e._y1)/(i||r<0&&-0),s=(a*i+o*r)/(r+i);return(ye(a)+ye(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function xe(e,t){var n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function x(e,t,n){var r=e._x0,i=e._y0,a=e._x1,o=e._y1,s=(a-r)/3;e._context.bezierCurveTo(r+s,i+s*t,a-s,o-s*n,a,o)}function S(e){this._context=e}S.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:x(this,this._t0,xe(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var n=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,x(this,xe(this,n=be(this,e,t)),n);break;default:x(this,this._t0,n=be(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}}};function Se(e){this._context=new Ce(e)}(Se.prototype=Object.create(S.prototype)).point=function(e,t){S.prototype.point.call(this,t,e)};function Ce(e){this._context=e}Ce.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,n,r,i,a){this._context.bezierCurveTo(t,e,r,n,a,i)}};function we(e){return new S(e)}function Te(e){return new Se(e)}function Ee(e){this._context=e}Ee.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,n=e.length;if(n)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else for(var r=De(e),i=De(t),a=0,o=1;o=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[n-1]=(e[n]+i[n-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}this._x=e,this._y=t}};function w(e){return new C(e,.5)}function T(e){return new C(e,0)}function ke(e){return new C(e,1)}function E(e){if(typeof e!=`object`||!e)return!1;if(Object.getPrototypeOf(e)===null)return!0;if(Object.prototype.toString.call(e)!==`[object Object]`){let t=e[Symbol.toStringTag];return t==null||!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable?!1:e.toString()===`[object ${t}]`}let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Ae(){}function je(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function D(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var Me=`[object RegExp]`,O=`[object String]`,k=`[object Number]`,A=`[object Boolean]`,j=`[object Arguments]`,Ne=`[object Symbol]`,Pe=`[object Date]`,Fe=`[object Map]`,Ie=`[object Set]`,Le=`[object Array]`,Re=`[object ArrayBuffer]`,ze=`[object Object]`,M=`[object DataView]`,Be=`[object Uint8Array]`,Ve=`[object Uint8ClampedArray]`,He=`[object Uint16Array]`,Ue=`[object Uint32Array]`,We=`[object Int8Array]`,Ge=`[object Int16Array]`,Ke=`[object Int32Array]`,qe=`[object Float32Array]`,Je=`[object Float64Array]`,Ye=typeof globalThis==`object`&&globalThis||typeof window==`object`&&window||typeof self==`object`&&self||typeof global==`object`&&global||(function(){return this})();function N(e){return Ye.Buffer!==void 0&&Ye.Buffer.isBuffer(e)}function Xe(e){return Number.isSafeInteger(e)&&e>=0}function Ze(e){return e!=null&&typeof e!=`function`&&Xe(e.length)}function Qe(e){return e===`__proto__`}function P(e){return e==null||typeof e!=`object`&&typeof e!=`function`}function F(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function $e(e,t){return I(e,void 0,e,new Map,t)}function I(e,t,n,r=new Map,i=void 0){let a=i?.(e,t,n,r);if(a!==void 0)return a;if(P(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){let t=Array(e.length);r.set(e,t);for(let a=0;a{let o=t?.(n,r,i,a);if(o!==void 0)return o;if(typeof e==`object`){if(D(e)===`[object Object]`&&typeof e.constructor!=`function`){let t={};return a.set(e,t),L(t,e,i,a),t}switch(Object.prototype.toString.call(e)){case k:case O:case A:{let t=new e.constructor(e?.valueOf());return L(t,e),t}case j:{let t={};return L(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function nt(e){return tt(e)}function R(e){return typeof e==`object`&&!!e&&D(e)===`[object Arguments]`}function z(e){return typeof e==`object`&&!!e}function rt(e){return z(e)&&Ze(e)}function B(e){return F(e)}function V(e,t){if(typeof e!=`function`||t!=null&&typeof t!=`function`)throw TypeError(`Expected a function`);let n=function(...r){let i=t?t.apply(this,r):r[0],a=n.cache;if(a.has(i))return a.get(i);let o=e.apply(this,r);return n.cache=a.set(i,o)||a,o};return n.cache=new(V.Cache||Map),n}V.Cache=Map;function it(e){if(P(e))return e;if(Array.isArray(e)||F(e)||e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)return e.slice(0);let t=Object.getPrototypeOf(e);if(t==null)return Object.assign(Object.create(t),e);let n=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new n(e);if(e instanceof RegExp){let t=new n(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new n(e.buffer.slice(0));if(e instanceof Error){let t;return t=e instanceof AggregateError?new n(e.errors,e.message,{cause:e.cause}):new n(e.message,{cause:e.cause}),t.stack=e.stack,Object.assign(t,e),t}return typeof File<`u`&&e instanceof File?new n([e],e.name,{type:e.type,lastModified:e.lastModified}):typeof e==`object`?Object.assign(Object.create(t),e):e}function at(e,...t){let n=t.slice(0,-1),r=t[t.length-1],i=e;for(let e=0;ee.args);r(e),i=o(i,[...e])}else i=n.args;if(!i)return;let s=a(e,t),c=`config`;return i[c]!==void 0&&(s===`flowchart-v2`&&(s=`flowchart`),i[s]=i[c],delete i[c]),i},`detectInit`),dt=e(function(e,n=null){try{let r=RegExp(`[%]{2}(?![{]${lt.source})(?=[}][%]{2}).* +`,`ig`);e=e.trim().replace(r,``).replace(/'/gm,`"`),t.debug(`Detecting diagram directive${n===null?``:` type:`+n} based on the text:${e}`);let a,o=[];for(;(a=i.exec(e))!==null;)if(a.index===i.lastIndex&&i.lastIndex++,a&&!n||n&&a[1]?.match(n)||n&&a[2]?.match(n)){let e=a[1]?a[1]:a[2],t=a[3]?a[3].trim():a[4]?JSON.parse(a[4].trim()):null;o.push({type:e,args:t})}return o.length===0?{type:e,args:null}:o.length===1?o[0]:o}catch(r){return t.error(`ERROR: ${r.message} - Unable to parse directive type: '${n}' based on the text: '${e}'`),{type:void 0,args:null}}},`detectDirective`),ft=e(function(e){return e.replace(i,``)},`removeDirectives`),pt=e(function(e,t){for(let[n,r]of t.entries())if(r.match(e))return n;return-1},`isSubstringInArray`);function U(e,t){return e?ct[`curve${e.charAt(0).toUpperCase()+e.slice(1)}`]??t:t}e(U,`interpolateToCurve`);function mt(e,t){let n=e.trim();if(n)return t.securityLevel===`loose`?n:(0,st.sanitizeUrl)(n)}e(mt,`formatUrl`);var ht=e((e,...n)=>{let r=e.split(`.`),i=r.length-1,a=r[i],o=window;for(let n=0;n{n+=W(e,t),t=e}),G(e,n/2)}e(gt,`traverseEdge`);function _t(e){return e.length===1?e[0]:gt(e)}e(_t,`calcLabelPosition`);var vt=e((e,t=2)=>{let n=10**t;return Math.round(e*n)/n},`roundNumber`),G=e((e,t)=>{let n,r=t;for(let t of e){if(n){let e=W(t,n);if(e===0)return n;if(e=1)return{x:t.x,y:t.y};if(i>0&&i<1)return{x:vt((1-i)*n.x+i*t.x,5),y:vt((1-i)*n.y+i*t.y,5)}}}n=t}throw Error(`Could not find a suitable point for the given distance`)},`calculatePoint`),yt=e((e,n,r)=>{t.info(`our points ${JSON.stringify(n)}`),n[0]!==r&&(n=n.reverse());let i=G(n,25),a=e?10:5,o=Math.atan2(n[0].y-i.y,n[0].x-i.x),s={x:0,y:0};return s.x=Math.sin(o)*a+(n[0].x+i.x)/2,s.y=-Math.cos(o)*a+(n[0].y+i.y)/2,s},`calcCardinalityPosition`);function bt(e,n,r){let i=structuredClone(r);t.info(`our points`,i),n!==`start_left`&&n!==`start_right`&&i.reverse();let a=G(i,25+e),o=10+e*.5,s=Math.atan2(i[0].y-a.y,i[0].x-a.x),c={x:0,y:0};return n===`start_left`?(c.x=Math.sin(s+Math.PI)*o+(i[0].x+a.x)/2,c.y=-Math.cos(s+Math.PI)*o+(i[0].y+a.y)/2):n===`end_right`?(c.x=Math.sin(s-Math.PI)*o+(i[0].x+a.x)/2-5,c.y=-Math.cos(s-Math.PI)*o+(i[0].y+a.y)/2-5):n===`end_left`?(c.x=Math.sin(s)*o+(i[0].x+a.x)/2-5,c.y=-Math.cos(s)*o+(i[0].y+a.y)/2-5):(c.x=Math.sin(s)*o+(i[0].x+a.x)/2,c.y=-Math.cos(s)*o+(i[0].y+a.y)/2),c}e(bt,`calcTerminalLabelPosition`);function K(e){let t=``,n=``;for(let r of e)r!==void 0&&(r.startsWith(`color:`)||r.startsWith(`text-align:`)?n=n+r+`;`:t=t+r+`;`);return{style:t,labelStyle:n}}e(K,`getStylesFromArray`);var xt=0,St=e(()=>(xt++,`id-`+Math.random().toString(36).substr(2,12)+`-`+xt),`generateId`);function Ct(e){let t=``;for(let n=0;nCt(e.length),`random`),Tt=e(function(){return{x:0,y:0,fill:void 0,anchor:`start`,style:`#666`,width:100,height:100,textMargin:0,rx:0,ry:0,valign:void 0,text:``}},`getTextObj`),Et=e(function(e,t){let n=t.text.replace(s.lineBreakRegex,` `),[,r]=Z(t.fontSize),i=e.append(`text`);i.attr(`x`,t.x),i.attr(`y`,t.y),i.style(`text-anchor`,t.anchor),i.style(`font-family`,t.fontFamily),i.style(`font-size`,r),i.style(`font-weight`,t.fontWeight),i.attr(`fill`,t.fill),t.class!==void 0&&i.attr(`class`,t.class);let a=i.append(`tspan`);return a.attr(`x`,t.x+t.textMargin*2),a.attr(`fill`,t.fill),a.text(n),i},`drawSimpleText`),Dt=V((e,t,n)=>{if(!e||(n=Object.assign({fontSize:12,fontWeight:400,fontFamily:`Arial`,joinWith:`
    `},n),s.lineBreakRegex.test(e)))return e;let r=e.split(` `).filter(Boolean),i=[],a=``;return r.forEach((e,o)=>{let s=J(`${e} `,n),c=J(a,n);if(s>t){let{hyphenatedStrings:r,remainingWord:o}=Ot(e,t,`-`,n);i.push(a,...r),a=o}else c+s>=t?(i.push(a),a=e):a=[a,e].filter(Boolean).join(` `);o+1===r.length&&i.push(a)}),i.filter(e=>e!==``).join(n.joinWith)},(e,t,n)=>`${e}${t}${n.fontSize}${n.fontWeight}${n.fontFamily}${n.joinWith}`),Ot=V((e,t,n=`-`,r)=>{r=Object.assign({fontSize:12,fontWeight:400,fontFamily:`Arial`,margin:0},r);let i=[...e],a=[],o=``;return i.forEach((e,s)=>{let c=`${o}${e}`;if(J(c,r)>=t){let e=s+1,t=i.length===e,r=`${c}${n}`;a.push(t?c:r),o=``}else o=c}),{hyphenatedStrings:a,remainingWord:o}},(e,t,n=`-`,r)=>`${e}${t}${n}${r.fontSize}${r.fontWeight}${r.fontFamily}`);function q(e,t){return Y(e,t).height}e(q,`calculateTextHeight`);function J(e,t){return Y(e,t).width}e(J,`calculateTextWidth`);var Y=V((e,t)=>{let{fontSize:r=12,fontFamily:i=`Arial`,fontWeight:a=400}=t;if(!e)return{width:0,height:0};let[,o]=Z(r),c=[`sans-serif`,i],l=e.split(s.lineBreakRegex),u=[],d=n(`body`);if(!d.remove)return{width:0,height:0,lineHeight:0};let f=d.append(`svg`);for(let e of c){let t=0,n={width:0,height:0,lineHeight:0};for(let r of l){let i=Tt();i.text=r||`​`;let s=Et(f,i).style(`font-size`,o).style(`font-weight`,a).style(`font-family`,e),c=(s._groups||s)[0][0].getBBox();if(c.width===0&&c.height===0)throw Error(`svg element not in render tree`);n.width=Math.round(Math.max(n.width,c.width)),t=Math.round(c.height),n.height+=t,n.lineHeight=Math.round(Math.max(n.lineHeight,t))}u.push(n)}return f.remove(),u[isNaN(u[1].height)||isNaN(u[1].width)||isNaN(u[1].lineHeight)||u[0].height>u[1].height&&u[0].width>u[1].width&&u[0].lineHeight>u[1].lineHeight?0:1]},(e,t)=>`${e}${t.fontSize}${t.fontWeight}${t.fontFamily}`),kt=class{constructor(e=!1,t){this.count=0,this.count=t?t.length:0,this.next=e?()=>this.count++:()=>Date.now()}static{e(this,`InitIDGenerator`)}},X,At=e(function(e){return X||=document.createElement(`div`),e=escape(e).replace(/%26/g,`&`).replace(/%23/g,`#`).replace(/%3B/g,`;`),X.innerHTML=e,unescape(X.textContent)},`entityDecode`);function jt(e){return`str`in e}e(jt,`isDetailedError`);var Mt=e((e,t,n,r)=>{if(!r)return;let i=e.node()?.getBBox();i&&e.append(`text`).text(r).attr(`text-anchor`,`middle`).attr(`x`,i.x+i.width/2).attr(`y`,-n).attr(`class`,t)},`insertTitle`),Z=e(e=>{if(typeof e==`number`)return[e,e+`px`];let t=parseInt(e??``,10);return Number.isNaN(t)?[void 0,void 0]:e===String(t)?[t,e+`px`]:[t,e]},`parseFontSize`);function Q(e,t){return ot({},e,t)}e(Q,`cleanAndMerge`);var Nt={assignWithDepth:o,wrapLabel:Dt,calculateTextHeight:q,calculateTextWidth:J,calculateTextDimensions:Y,cleanAndMerge:Q,detectInit:ut,detectDirective:dt,isSubstringInArray:pt,interpolateToCurve:U,calcLabelPosition:_t,calcCardinalityPosition:yt,calcTerminalLabelPosition:bt,formatUrl:mt,getStylesFromArray:K,generateId:St,random:wt,runFunc:ht,entityDecode:At,insertTitle:Mt,isLabelCoordinateInPath:$,parseFontSize:Z,InitIDGenerator:kt},Pt=e(function(e){let t=e;return t=t.replace(/style.*:\S*#.*;/g,function(e){return e.substring(0,e.length-1)}),t=t.replace(/classDef.*:\S*#.*;/g,function(e){return e.substring(0,e.length-1)}),t=t.replace(/#\w+;/g,function(e){let t=e.substring(1,e.length-1);return/^\+?\d+$/.test(t)?`fl°°`+t+`¶ß`:`fl°`+t+`¶ß`}),t},`encodeEntities`),Ft=e(function(e){return e.replace(/fl°°/g,`&#`).replace(/fl°/g,`&`).replace(/¶ß/g,`;`)},`decodeEntities`),It=e((e,t,{counter:n=0,prefix:r,suffix:i},a)=>a||`${r?`${r}_`:``}${e}_${t}_${n}${i?`_${i}`:``}`,`getEdgeId`);function Lt(e){return e??null}e(Lt,`handleUndefinedAttr`);function $(e,t){let n=Math.round(e.x),r=Math.round(e.y),i=t.replace(/(\d+\.\d+)/g,e=>Math.round(parseFloat(e)).toString());return i.includes(n.toString())||i.includes(r.toString())}e($,`isLabelCoordinateInPath`);export{ce as $,Je as A,Ne as B,j as C,M as D,A as E,k as F,D as G,Ue as H,ze as I,w as J,ke as K,Me as L,Ke as M,We as N,Pe as O,Fe as P,fe as Q,Ie as R,N as S,Le as T,Be as U,He as V,Ve as W,we as X,Oe as Y,Te as Z,Dt as _,Ft as a,P as b,It as c,U as d,te as et,jt as f,Nt as g,ft as h,Q as i,Ge as j,qe as k,K as l,wt as m,q as n,ee as nt,Pt as o,Z as p,T as q,J as r,u as rt,St as s,Y as t,f as tt,Lt as u,B as v,Re as w,Ze as x,R as y,O as z}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-JG7HCLWE-Dk4_aECj.js b/dist-desktop/assets/chunk-JG7HCLWE-Dk4_aECj.js new file mode 100644 index 0000000..60bc5ca --- /dev/null +++ b/dist-desktop/assets/chunk-JG7HCLWE-Dk4_aECj.js @@ -0,0 +1,2 @@ +import{C as e,S as t,_ as n,n as r,o as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`RailroadPegTokenBuilder`)}constructor(){super([`railroad-peg-beta`])}},u=c(e=>{let t=e.slice(1,-1),n=``;for(let e=0;enew l,`TokenBuilder`),ValueConverter:c(()=>new d,`ValueConverter`)}};function p(r=i){let a=s(e(r),o),c=s(t({shared:a}),n,f);return a.ServiceRegistry.register(c),{shared:a,RailroadPeg:c}}c(p,`createRailroadPegServices`);export{p as n,f as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-JWPE2WC7-DVXcaiue.js b/dist-desktop/assets/chunk-JWPE2WC7-DVXcaiue.js new file mode 100644 index 0000000..89f16f4 --- /dev/null +++ b/dist-desktop/assets/chunk-JWPE2WC7-DVXcaiue.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";function t(e,t){e.accDescr&&t.setAccDescription?.(e.accDescr),e.accTitle&&t.setAccTitle?.(e.accTitle),e.title&&t.setDiagramTitle?.(e.title)}e(t,`populateCommonDb`);export{t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-KEIR6QF5-Dj-OpFgW.js b/dist-desktop/assets/chunk-KEIR6QF5-Dj-OpFgW.js new file mode 100644 index 0000000..8e32672 --- /dev/null +++ b/dist-desktop/assets/chunk-KEIR6QF5-Dj-OpFgW.js @@ -0,0 +1,161 @@ +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>t(e,`name`,{value:n,configurable:!0}),s=(e,t)=>function(){return e&&(t=(0,e[r(e)[0]])(e=0)),t},c=(e,t)=>function(){return t||(0,e[r(e)[0]])((t={exports:{}}).exports,t),t.exports},l=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},u=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(let c of r(i))!a.call(e,c)&&c!==o&&t(e,c,{get:()=>i[c],enumerable:!(s=n(i,c))||s.enumerable});return e},d=(e,t,n)=>(u(e,t,`default`),n&&u(n,t,`default`)),f=(n,r,a)=>(a=n==null?{}:e(i(n)),u(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),p=e=>u(t({},`__esModule`,{value:!0}),e),m={};l(m,{AnnotatedTextEdit:()=>T,ChangeAnnotation:()=>de,ChangeAnnotationIdentifier:()=>w,CodeAction:()=>We,CodeActionContext:()=>Ue,CodeActionKind:()=>Ve,CodeActionTriggerKind:()=>He,CodeDescription:()=>se,CodeLens:()=>Ge,Color:()=>S,ColorInformation:()=>te,ColorPresentation:()=>ne,Command:()=>le,CompletionItem:()=>Oe,CompletionItemKind:()=>Se,CompletionItemLabelDetails:()=>De,CompletionItemTag:()=>we,CompletionList:()=>ke,CreateFile:()=>D,DeleteFile:()=>fe,Diagnostic:()=>ce,DiagnosticRelatedInformation:()=>ie,DiagnosticSeverity:()=>ae,DiagnosticTag:()=>oe,DocumentHighlight:()=>Fe,DocumentHighlightKind:()=>Pe,DocumentLink:()=>qe,DocumentSymbol:()=>Be,DocumentUri:()=>h,EOL:()=>ft,FoldingRange:()=>re,FoldingRangeKind:()=>C,FormattingOptions:()=>Ke,Hover:()=>je,InlayHint:()=>it,InlayHintKind:()=>nt,InlayHintLabelPart:()=>rt,InlineCompletionContext:()=>ut,InlineCompletionItem:()=>ot,InlineCompletionList:()=>st,InlineCompletionTriggerKind:()=>ct,InlineValueContext:()=>tt,InlineValueEvaluatableExpression:()=>et,InlineValueText:()=>Qe,InlineValueVariableLookup:()=>$e,InsertReplaceEdit:()=>Te,InsertTextFormat:()=>Ce,InsertTextMode:()=>Ee,Location:()=>x,LocationLink:()=>ee,MarkedString:()=>Ae,MarkupContent:()=>xe,MarkupKind:()=>be,OptionalVersionedTextDocumentIdentifier:()=>ve,ParameterInformation:()=>Me,Position:()=>y,Range:()=>b,RenameFile:()=>O,SelectedCompletionInfo:()=>lt,SelectionRange:()=>Je,SemanticTokenModifiers:()=>Xe,SemanticTokenTypes:()=>Ye,SemanticTokens:()=>Ze,SignatureInformation:()=>Ne,StringValue:()=>at,SymbolInformation:()=>Re,SymbolKind:()=>Ie,SymbolTag:()=>Le,TextDocument:()=>pt,TextDocumentEdit:()=>E,TextDocumentIdentifier:()=>ge,TextDocumentItem:()=>ye,TextEdit:()=>ue,URI:()=>g,VersionedTextDocumentIdentifier:()=>_e,WorkspaceChange:()=>he,WorkspaceEdit:()=>k,WorkspaceFolder:()=>dt,WorkspaceSymbol:()=>ze,integer:()=>_,uinteger:()=>v});var h,g,_,v,y,b,x,ee,S,te,ne,C,re,ie,ae,oe,se,ce,le,ue,de,w,T,E,D,O,fe,k,pe,me,he,ge,_e,ve,ye,be,xe,Se,Ce,we,Te,Ee,De,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at,ot,st,ct,lt,ut,dt,ft,pt,mt,A,ht=s({"../../node_modules/.pnpm/vscode-languageserver-types@3.17.5/node_modules/vscode-languageserver-types/lib/esm/main.js"(){(function(e){function t(e){return typeof e==`string`}o(t,`is`),e.is=t})(h||={}),(function(e){function t(e){return typeof e==`string`}o(t,`is`),e.is=t})(g||={}),(function(e){e.MIN_VALUE=-2147483648,e.MAX_VALUE=2147483647;function t(t){return typeof t==`number`&&e.MIN_VALUE<=t&&t<=e.MAX_VALUE}o(t,`is`),e.is=t})(_||={}),(function(e){e.MIN_VALUE=0,e.MAX_VALUE=2147483647;function t(t){return typeof t==`number`&&e.MIN_VALUE<=t&&t<=e.MAX_VALUE}o(t,`is`),e.is=t})(v||={}),(function(e){function t(e,t){return e===Number.MAX_VALUE&&(e=v.MAX_VALUE),t===Number.MAX_VALUE&&(t=v.MAX_VALUE),{line:e,character:t}}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&A.uinteger(t.line)&&A.uinteger(t.character)}o(n,`is`),e.is=n})(y||={}),(function(e){function t(e,t,n,r){if(A.uinteger(e)&&A.uinteger(t)&&A.uinteger(n)&&A.uinteger(r))return{start:y.create(e,t),end:y.create(n,r)};if(y.is(e)&&y.is(t))return{start:e,end:t};throw Error(`Range#create called with invalid arguments[${e}, ${t}, ${n}, ${r}]`)}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&y.is(t.start)&&y.is(t.end)}o(n,`is`),e.is=n})(b||={}),(function(e){function t(e,t){return{uri:e,range:t}}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&b.is(t.range)&&(A.string(t.uri)||A.undefined(t.uri))}o(n,`is`),e.is=n})(x||={}),(function(e){function t(e,t,n,r){return{targetUri:e,targetRange:t,targetSelectionRange:n,originSelectionRange:r}}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&b.is(t.targetRange)&&A.string(t.targetUri)&&b.is(t.targetSelectionRange)&&(b.is(t.originSelectionRange)||A.undefined(t.originSelectionRange))}o(n,`is`),e.is=n})(ee||={}),(function(e){function t(e,t,n,r){return{red:e,green:t,blue:n,alpha:r}}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&A.numberRange(t.red,0,1)&&A.numberRange(t.green,0,1)&&A.numberRange(t.blue,0,1)&&A.numberRange(t.alpha,0,1)}o(n,`is`),e.is=n})(S||={}),(function(e){function t(e,t){return{range:e,color:t}}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&b.is(t.range)&&S.is(t.color)}o(n,`is`),e.is=n})(te||={}),(function(e){function t(e,t,n){return{label:e,textEdit:t,additionalTextEdits:n}}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&A.string(t.label)&&(A.undefined(t.textEdit)||ue.is(t))&&(A.undefined(t.additionalTextEdits)||A.typedArray(t.additionalTextEdits,ue.is))}o(n,`is`),e.is=n})(ne||={}),(function(e){e.Comment=`comment`,e.Imports=`imports`,e.Region=`region`})(C||={}),(function(e){function t(e,t,n,r,i,a){let o={startLine:e,endLine:t};return A.defined(n)&&(o.startCharacter=n),A.defined(r)&&(o.endCharacter=r),A.defined(i)&&(o.kind=i),A.defined(a)&&(o.collapsedText=a),o}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&A.uinteger(t.startLine)&&A.uinteger(t.startLine)&&(A.undefined(t.startCharacter)||A.uinteger(t.startCharacter))&&(A.undefined(t.endCharacter)||A.uinteger(t.endCharacter))&&(A.undefined(t.kind)||A.string(t.kind))}o(n,`is`),e.is=n})(re||={}),(function(e){function t(e,t){return{location:e,message:t}}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&x.is(t.location)&&A.string(t.message)}o(n,`is`),e.is=n})(ie||={}),(function(e){e.Error=1,e.Warning=2,e.Information=3,e.Hint=4})(ae||={}),(function(e){e.Unnecessary=1,e.Deprecated=2})(oe||={}),(function(e){function t(e){let t=e;return A.objectLiteral(t)&&A.string(t.href)}o(t,`is`),e.is=t})(se||={}),(function(e){function t(e,t,n,r,i,a){let o={range:e,message:t};return A.defined(n)&&(o.severity=n),A.defined(r)&&(o.code=r),A.defined(i)&&(o.source=i),A.defined(a)&&(o.relatedInformation=a),o}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&b.is(t.range)&&A.string(t.message)&&(A.number(t.severity)||A.undefined(t.severity))&&(A.integer(t.code)||A.string(t.code)||A.undefined(t.code))&&(A.undefined(t.codeDescription)||A.string(t.codeDescription?.href))&&(A.string(t.source)||A.undefined(t.source))&&(A.undefined(t.relatedInformation)||A.typedArray(t.relatedInformation,ie.is))}o(n,`is`),e.is=n})(ce||={}),(function(e){function t(e,t,...n){let r={title:e,command:t};return A.defined(n)&&n.length>0&&(r.arguments=n),r}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&A.string(t.title)&&A.string(t.command)}o(n,`is`),e.is=n})(le||={}),(function(e){function t(e,t){return{range:e,newText:t}}o(t,`replace`),e.replace=t;function n(e,t){return{range:{start:e,end:e},newText:t}}o(n,`insert`),e.insert=n;function r(e){return{range:e,newText:``}}o(r,`del`),e.del=r;function i(e){let t=e;return A.objectLiteral(t)&&A.string(t.newText)&&b.is(t.range)}o(i,`is`),e.is=i})(ue||={}),(function(e){function t(e,t,n){let r={label:e};return t!==void 0&&(r.needsConfirmation=t),n!==void 0&&(r.description=n),r}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&A.string(t.label)&&(A.boolean(t.needsConfirmation)||t.needsConfirmation===void 0)&&(A.string(t.description)||t.description===void 0)}o(n,`is`),e.is=n})(de||={}),(function(e){function t(e){let t=e;return A.string(t)}o(t,`is`),e.is=t})(w||={}),(function(e){function t(e,t,n){return{range:e,newText:t,annotationId:n}}o(t,`replace`),e.replace=t;function n(e,t,n){return{range:{start:e,end:e},newText:t,annotationId:n}}o(n,`insert`),e.insert=n;function r(e,t){return{range:e,newText:``,annotationId:t}}o(r,`del`),e.del=r;function i(e){let t=e;return ue.is(t)&&(de.is(t.annotationId)||w.is(t.annotationId))}o(i,`is`),e.is=i})(T||={}),(function(e){function t(e,t){return{textDocument:e,edits:t}}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&ve.is(t.textDocument)&&Array.isArray(t.edits)}o(n,`is`),e.is=n})(E||={}),(function(e){function t(e,t,n){let r={kind:`create`,uri:e};return t!==void 0&&(t.overwrite!==void 0||t.ignoreIfExists!==void 0)&&(r.options=t),n!==void 0&&(r.annotationId=n),r}o(t,`create`),e.create=t;function n(e){let t=e;return t&&t.kind===`create`&&A.string(t.uri)&&(t.options===void 0||(t.options.overwrite===void 0||A.boolean(t.options.overwrite))&&(t.options.ignoreIfExists===void 0||A.boolean(t.options.ignoreIfExists)))&&(t.annotationId===void 0||w.is(t.annotationId))}o(n,`is`),e.is=n})(D||={}),(function(e){function t(e,t,n,r){let i={kind:`rename`,oldUri:e,newUri:t};return n!==void 0&&(n.overwrite!==void 0||n.ignoreIfExists!==void 0)&&(i.options=n),r!==void 0&&(i.annotationId=r),i}o(t,`create`),e.create=t;function n(e){let t=e;return t&&t.kind===`rename`&&A.string(t.oldUri)&&A.string(t.newUri)&&(t.options===void 0||(t.options.overwrite===void 0||A.boolean(t.options.overwrite))&&(t.options.ignoreIfExists===void 0||A.boolean(t.options.ignoreIfExists)))&&(t.annotationId===void 0||w.is(t.annotationId))}o(n,`is`),e.is=n})(O||={}),(function(e){function t(e,t,n){let r={kind:`delete`,uri:e};return t!==void 0&&(t.recursive!==void 0||t.ignoreIfNotExists!==void 0)&&(r.options=t),n!==void 0&&(r.annotationId=n),r}o(t,`create`),e.create=t;function n(e){let t=e;return t&&t.kind===`delete`&&A.string(t.uri)&&(t.options===void 0||(t.options.recursive===void 0||A.boolean(t.options.recursive))&&(t.options.ignoreIfNotExists===void 0||A.boolean(t.options.ignoreIfNotExists)))&&(t.annotationId===void 0||w.is(t.annotationId))}o(n,`is`),e.is=n})(fe||={}),(function(e){function t(e){let t=e;return t&&(t.changes!==void 0||t.documentChanges!==void 0)&&(t.documentChanges===void 0||t.documentChanges.every(e=>A.string(e.kind)?D.is(e)||O.is(e)||fe.is(e):E.is(e)))}o(t,`is`),e.is=t})(k||={}),pe=class{static{o(this,`TextEditChangeImpl`)}constructor(e,t){this.edits=e,this.changeAnnotations=t}insert(e,t,n){let r,i;if(n===void 0?r=ue.insert(e,t):w.is(n)?(i=n,r=T.insert(e,t,n)):(this.assertChangeAnnotations(this.changeAnnotations),i=this.changeAnnotations.manage(n),r=T.insert(e,t,i)),this.edits.push(r),i!==void 0)return i}replace(e,t,n){let r,i;if(n===void 0?r=ue.replace(e,t):w.is(n)?(i=n,r=T.replace(e,t,n)):(this.assertChangeAnnotations(this.changeAnnotations),i=this.changeAnnotations.manage(n),r=T.replace(e,t,i)),this.edits.push(r),i!==void 0)return i}delete(e,t){let n,r;if(t===void 0?n=ue.del(e):w.is(t)?(r=t,n=T.del(e,t)):(this.assertChangeAnnotations(this.changeAnnotations),r=this.changeAnnotations.manage(t),n=T.del(e,r)),this.edits.push(n),r!==void 0)return r}add(e){this.edits.push(e)}all(){return this.edits}clear(){this.edits.splice(0,this.edits.length)}assertChangeAnnotations(e){if(e===void 0)throw Error(`Text edit change is not configured to manage change annotations.`)}},me=class{static{o(this,`ChangeAnnotations`)}constructor(e){this._annotations=e===void 0?Object.create(null):e,this._counter=0,this._size=0}all(){return this._annotations}get size(){return this._size}manage(e,t){let n;if(w.is(e)?n=e:(n=this.nextId(),t=e),this._annotations[n]!==void 0)throw Error(`Id ${n} is already in use.`);if(t===void 0)throw Error(`No annotation provided for id ${n}`);return this._annotations[n]=t,this._size++,n}nextId(){return this._counter++,this._counter.toString()}},he=class{static{o(this,`WorkspaceChange`)}constructor(e){this._textEditChanges=Object.create(null),e===void 0?this._workspaceEdit={}:(this._workspaceEdit=e,e.documentChanges?(this._changeAnnotations=new me(e.changeAnnotations),e.changeAnnotations=this._changeAnnotations.all(),e.documentChanges.forEach(e=>{if(E.is(e)){let t=new pe(e.edits,this._changeAnnotations);this._textEditChanges[e.textDocument.uri]=t}})):e.changes&&Object.keys(e.changes).forEach(t=>{let n=new pe(e.changes[t]);this._textEditChanges[t]=n}))}get edit(){return this.initDocumentChanges(),this._changeAnnotations!==void 0&&(this._changeAnnotations.size===0?this._workspaceEdit.changeAnnotations=void 0:this._workspaceEdit.changeAnnotations=this._changeAnnotations.all()),this._workspaceEdit}getTextEditChange(e){if(ve.is(e)){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw Error(`Workspace edit is not configured for document changes.`);let t={uri:e.uri,version:e.version},n=this._textEditChanges[t.uri];if(!n){let e=[],r={textDocument:t,edits:e};this._workspaceEdit.documentChanges.push(r),n=new pe(e,this._changeAnnotations),this._textEditChanges[t.uri]=n}return n}else{if(this.initChanges(),this._workspaceEdit.changes===void 0)throw Error(`Workspace edit is not configured for normal text edit changes.`);let t=this._textEditChanges[e];if(!t){let n=[];this._workspaceEdit.changes[e]=n,t=new pe(n),this._textEditChanges[e]=t}return t}}initDocumentChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._changeAnnotations=new me,this._workspaceEdit.documentChanges=[],this._workspaceEdit.changeAnnotations=this._changeAnnotations.all())}initChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._workspaceEdit.changes=Object.create(null))}createFile(e,t,n){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw Error(`Workspace edit is not configured for document changes.`);let r;de.is(t)||w.is(t)?r=t:n=t;let i,a;if(r===void 0?i=D.create(e,n):(a=w.is(r)?r:this._changeAnnotations.manage(r),i=D.create(e,n,a)),this._workspaceEdit.documentChanges.push(i),a!==void 0)return a}renameFile(e,t,n,r){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw Error(`Workspace edit is not configured for document changes.`);let i;de.is(n)||w.is(n)?i=n:r=n;let a,o;if(i===void 0?a=O.create(e,t,r):(o=w.is(i)?i:this._changeAnnotations.manage(i),a=O.create(e,t,r,o)),this._workspaceEdit.documentChanges.push(a),o!==void 0)return o}deleteFile(e,t,n){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw Error(`Workspace edit is not configured for document changes.`);let r;de.is(t)||w.is(t)?r=t:n=t;let i,a;if(r===void 0?i=fe.create(e,n):(a=w.is(r)?r:this._changeAnnotations.manage(r),i=fe.create(e,n,a)),this._workspaceEdit.documentChanges.push(i),a!==void 0)return a}},(function(e){function t(e){return{uri:e}}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&A.string(t.uri)}o(n,`is`),e.is=n})(ge||={}),(function(e){function t(e,t){return{uri:e,version:t}}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&A.string(t.uri)&&A.integer(t.version)}o(n,`is`),e.is=n})(_e||={}),(function(e){function t(e,t){return{uri:e,version:t}}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&A.string(t.uri)&&(t.version===null||A.integer(t.version))}o(n,`is`),e.is=n})(ve||={}),(function(e){function t(e,t,n,r){return{uri:e,languageId:t,version:n,text:r}}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&A.string(t.uri)&&A.string(t.languageId)&&A.integer(t.version)&&A.string(t.text)}o(n,`is`),e.is=n})(ye||={}),(function(e){e.PlainText=`plaintext`,e.Markdown=`markdown`;function t(t){let n=t;return n===e.PlainText||n===e.Markdown}o(t,`is`),e.is=t})(be||={}),(function(e){function t(e){let t=e;return A.objectLiteral(e)&&be.is(t.kind)&&A.string(t.value)}o(t,`is`),e.is=t})(xe||={}),(function(e){e.Text=1,e.Method=2,e.Function=3,e.Constructor=4,e.Field=5,e.Variable=6,e.Class=7,e.Interface=8,e.Module=9,e.Property=10,e.Unit=11,e.Value=12,e.Enum=13,e.Keyword=14,e.Snippet=15,e.Color=16,e.File=17,e.Reference=18,e.Folder=19,e.EnumMember=20,e.Constant=21,e.Struct=22,e.Event=23,e.Operator=24,e.TypeParameter=25})(Se||={}),(function(e){e.PlainText=1,e.Snippet=2})(Ce||={}),(function(e){e.Deprecated=1})(we||={}),(function(e){function t(e,t,n){return{newText:e,insert:t,replace:n}}o(t,`create`),e.create=t;function n(e){let t=e;return t&&A.string(t.newText)&&b.is(t.insert)&&b.is(t.replace)}o(n,`is`),e.is=n})(Te||={}),(function(e){e.asIs=1,e.adjustIndentation=2})(Ee||={}),(function(e){function t(e){let t=e;return t&&(A.string(t.detail)||t.detail===void 0)&&(A.string(t.description)||t.description===void 0)}o(t,`is`),e.is=t})(De||={}),(function(e){function t(e){return{label:e}}o(t,`create`),e.create=t})(Oe||={}),(function(e){function t(e,t){return{items:e||[],isIncomplete:!!t}}o(t,`create`),e.create=t})(ke||={}),(function(e){function t(e){return e.replace(/[\\`*_{}[\]()#+\-.!]/g,`\\$&`)}o(t,`fromPlainText`),e.fromPlainText=t;function n(e){let t=e;return A.string(t)||A.objectLiteral(t)&&A.string(t.language)&&A.string(t.value)}o(n,`is`),e.is=n})(Ae||={}),(function(e){function t(e){let t=e;return!!t&&A.objectLiteral(t)&&(xe.is(t.contents)||Ae.is(t.contents)||A.typedArray(t.contents,Ae.is))&&(e.range===void 0||b.is(e.range))}o(t,`is`),e.is=t})(je||={}),(function(e){function t(e,t){return t?{label:e,documentation:t}:{label:e}}o(t,`create`),e.create=t})(Me||={}),(function(e){function t(e,t,...n){let r={label:e};return A.defined(t)&&(r.documentation=t),A.defined(n)?r.parameters=n:r.parameters=[],r}o(t,`create`),e.create=t})(Ne||={}),(function(e){e.Text=1,e.Read=2,e.Write=3})(Pe||={}),(function(e){function t(e,t){let n={range:e};return A.number(t)&&(n.kind=t),n}o(t,`create`),e.create=t})(Fe||={}),(function(e){e.File=1,e.Module=2,e.Namespace=3,e.Package=4,e.Class=5,e.Method=6,e.Property=7,e.Field=8,e.Constructor=9,e.Enum=10,e.Interface=11,e.Function=12,e.Variable=13,e.Constant=14,e.String=15,e.Number=16,e.Boolean=17,e.Array=18,e.Object=19,e.Key=20,e.Null=21,e.EnumMember=22,e.Struct=23,e.Event=24,e.Operator=25,e.TypeParameter=26})(Ie||={}),(function(e){e.Deprecated=1})(Le||={}),(function(e){function t(e,t,n,r,i){let a={name:e,kind:t,location:{uri:r,range:n}};return i&&(a.containerName=i),a}o(t,`create`),e.create=t})(Re||={}),(function(e){function t(e,t,n,r){return r===void 0?{name:e,kind:t,location:{uri:n}}:{name:e,kind:t,location:{uri:n,range:r}}}o(t,`create`),e.create=t})(ze||={}),(function(e){function t(e,t,n,r,i,a){let o={name:e,detail:t,kind:n,range:r,selectionRange:i};return a!==void 0&&(o.children=a),o}o(t,`create`),e.create=t;function n(e){let t=e;return t&&A.string(t.name)&&A.number(t.kind)&&b.is(t.range)&&b.is(t.selectionRange)&&(t.detail===void 0||A.string(t.detail))&&(t.deprecated===void 0||A.boolean(t.deprecated))&&(t.children===void 0||Array.isArray(t.children))&&(t.tags===void 0||Array.isArray(t.tags))}o(n,`is`),e.is=n})(Be||={}),(function(e){e.Empty=``,e.QuickFix=`quickfix`,e.Refactor=`refactor`,e.RefactorExtract=`refactor.extract`,e.RefactorInline=`refactor.inline`,e.RefactorRewrite=`refactor.rewrite`,e.Source=`source`,e.SourceOrganizeImports=`source.organizeImports`,e.SourceFixAll=`source.fixAll`})(Ve||={}),(function(e){e.Invoked=1,e.Automatic=2})(He||={}),(function(e){function t(e,t,n){let r={diagnostics:e};return t!=null&&(r.only=t),n!=null&&(r.triggerKind=n),r}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&A.typedArray(t.diagnostics,ce.is)&&(t.only===void 0||A.typedArray(t.only,A.string))&&(t.triggerKind===void 0||t.triggerKind===He.Invoked||t.triggerKind===He.Automatic)}o(n,`is`),e.is=n})(Ue||={}),(function(e){function t(e,t,n){let r={title:e},i=!0;return typeof t==`string`?(i=!1,r.kind=t):le.is(t)?r.command=t:r.edit=t,i&&n!==void 0&&(r.kind=n),r}o(t,`create`),e.create=t;function n(e){let t=e;return t&&A.string(t.title)&&(t.diagnostics===void 0||A.typedArray(t.diagnostics,ce.is))&&(t.kind===void 0||A.string(t.kind))&&(t.edit!==void 0||t.command!==void 0)&&(t.command===void 0||le.is(t.command))&&(t.isPreferred===void 0||A.boolean(t.isPreferred))&&(t.edit===void 0||k.is(t.edit))}o(n,`is`),e.is=n})(We||={}),(function(e){function t(e,t){let n={range:e};return A.defined(t)&&(n.data=t),n}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&b.is(t.range)&&(A.undefined(t.command)||le.is(t.command))}o(n,`is`),e.is=n})(Ge||={}),(function(e){function t(e,t){return{tabSize:e,insertSpaces:t}}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&A.uinteger(t.tabSize)&&A.boolean(t.insertSpaces)}o(n,`is`),e.is=n})(Ke||={}),(function(e){function t(e,t,n){return{range:e,target:t,data:n}}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&b.is(t.range)&&(A.undefined(t.target)||A.string(t.target))}o(n,`is`),e.is=n})(qe||={}),(function(e){function t(e,t){return{range:e,parent:t}}o(t,`create`),e.create=t;function n(t){let n=t;return A.objectLiteral(n)&&b.is(n.range)&&(n.parent===void 0||e.is(n.parent))}o(n,`is`),e.is=n})(Je||={}),(function(e){e.namespace=`namespace`,e.type=`type`,e.class=`class`,e.enum=`enum`,e.interface=`interface`,e.struct=`struct`,e.typeParameter=`typeParameter`,e.parameter=`parameter`,e.variable=`variable`,e.property=`property`,e.enumMember=`enumMember`,e.event=`event`,e.function=`function`,e.method=`method`,e.macro=`macro`,e.keyword=`keyword`,e.modifier=`modifier`,e.comment=`comment`,e.string=`string`,e.number=`number`,e.regexp=`regexp`,e.operator=`operator`,e.decorator=`decorator`})(Ye||={}),(function(e){e.declaration=`declaration`,e.definition=`definition`,e.readonly=`readonly`,e.static=`static`,e.deprecated=`deprecated`,e.abstract=`abstract`,e.async=`async`,e.modification=`modification`,e.documentation=`documentation`,e.defaultLibrary=`defaultLibrary`})(Xe||={}),(function(e){function t(e){let t=e;return A.objectLiteral(t)&&(t.resultId===void 0||typeof t.resultId==`string`)&&Array.isArray(t.data)&&(t.data.length===0||typeof t.data[0]==`number`)}o(t,`is`),e.is=t})(Ze||={}),(function(e){function t(e,t){return{range:e,text:t}}o(t,`create`),e.create=t;function n(e){let t=e;return t!=null&&b.is(t.range)&&A.string(t.text)}o(n,`is`),e.is=n})(Qe||={}),(function(e){function t(e,t,n){return{range:e,variableName:t,caseSensitiveLookup:n}}o(t,`create`),e.create=t;function n(e){let t=e;return t!=null&&b.is(t.range)&&A.boolean(t.caseSensitiveLookup)&&(A.string(t.variableName)||t.variableName===void 0)}o(n,`is`),e.is=n})($e||={}),(function(e){function t(e,t){return{range:e,expression:t}}o(t,`create`),e.create=t;function n(e){let t=e;return t!=null&&b.is(t.range)&&(A.string(t.expression)||t.expression===void 0)}o(n,`is`),e.is=n})(et||={}),(function(e){function t(e,t){return{frameId:e,stoppedLocation:t}}o(t,`create`),e.create=t;function n(e){let t=e;return A.defined(t)&&b.is(e.stoppedLocation)}o(n,`is`),e.is=n})(tt||={}),(function(e){e.Type=1,e.Parameter=2;function t(e){return e===1||e===2}o(t,`is`),e.is=t})(nt||={}),(function(e){function t(e){return{value:e}}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&(t.tooltip===void 0||A.string(t.tooltip)||xe.is(t.tooltip))&&(t.location===void 0||x.is(t.location))&&(t.command===void 0||le.is(t.command))}o(n,`is`),e.is=n})(rt||={}),(function(e){function t(e,t,n){let r={position:e,label:t};return n!==void 0&&(r.kind=n),r}o(t,`create`),e.create=t;function n(e){let t=e;return A.objectLiteral(t)&&y.is(t.position)&&(A.string(t.label)||A.typedArray(t.label,rt.is))&&(t.kind===void 0||nt.is(t.kind))&&t.textEdits===void 0||A.typedArray(t.textEdits,ue.is)&&(t.tooltip===void 0||A.string(t.tooltip)||xe.is(t.tooltip))&&(t.paddingLeft===void 0||A.boolean(t.paddingLeft))&&(t.paddingRight===void 0||A.boolean(t.paddingRight))}o(n,`is`),e.is=n})(it||={}),(function(e){function t(e){return{kind:`snippet`,value:e}}o(t,`createSnippet`),e.createSnippet=t})(at||={}),(function(e){function t(e,t,n,r){return{insertText:e,filterText:t,range:n,command:r}}o(t,`create`),e.create=t})(ot||={}),(function(e){function t(e){return{items:e}}o(t,`create`),e.create=t})(st||={}),(function(e){e.Invoked=0,e.Automatic=1})(ct||={}),(function(e){function t(e,t){return{range:e,text:t}}o(t,`create`),e.create=t})(lt||={}),(function(e){function t(e,t){return{triggerKind:e,selectedCompletionInfo:t}}o(t,`create`),e.create=t})(ut||={}),(function(e){function t(e){let t=e;return A.objectLiteral(t)&&g.is(t.uri)&&A.string(t.name)}o(t,`is`),e.is=t})(dt||={}),ft=[` +`,`\r +`,`\r`],(function(e){function t(e,t,n,r){return new mt(e,t,n,r)}o(t,`create`),e.create=t;function n(e){let t=e;return!!(A.defined(t)&&A.string(t.uri)&&(A.undefined(t.languageId)||A.string(t.languageId))&&A.uinteger(t.lineCount)&&A.func(t.getText)&&A.func(t.positionAt)&&A.func(t.offsetAt))}o(n,`is`),e.is=n;function r(e,t){let n=e.getText(),r=i(t,(e,t)=>{let n=e.range.start.line-t.range.start.line;return n===0?e.range.start.character-t.range.start.character:n}),a=n.length;for(let t=r.length-1;t>=0;t--){let i=r[t],o=e.offsetAt(i.range.start),s=e.offsetAt(i.range.end);if(s<=a)n=n.substring(0,o)+i.newText+n.substring(s,n.length);else throw Error(`Overlapping edit`);a=o}return n}o(r,`applyEdits`),e.applyEdits=r;function i(e,t){if(e.length<=1)return e;let n=e.length/2|0,r=e.slice(0,n),a=e.slice(n);i(r,t),i(a,t);let o=0,s=0,c=0;for(;o0&&e.push(t.length),this._lineOffsets=e}return this._lineOffsets}positionAt(e){e=Math.max(Math.min(e,this._content.length),0);let t=this.getLineOffsets(),n=0,r=t.length;if(r===0)return y.create(0,e);for(;ne?r=i:n=i+1}let i=n-1;return y.create(i,e-t[i])}offsetAt(e){let t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;let n=t[e.line],r=e.line+1n(e))}o(c,`stringArray`),e.stringArray=c}}),vt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/events.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Emitter=e.Event=void 0;var t=gt(),n;(function(e){let t={dispose(){}};e.None=function(){return t}})(n||(e.Event=n={}));var r=class{static{o(this,`CallbackList`)}add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:o(()=>this.remove(e,t),`dispose`)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let r=0,i=this._callbacks.length;r{this._callbacks||=new r,this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(t,n);let a={dispose:o(()=>{this._callbacks&&(this._callbacks.remove(t,n),a.dispose=e._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))},`dispose`)};return Array.isArray(i)&&i.push(a),a},this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&=(this._callbacks.dispose(),void 0)}};e.Emitter=i,i._noop=function(){}}}),yt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/cancellation.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationTokenSource=e.CancellationToken=void 0;var t=gt(),n=_t(),r=vt(),i;(function(e){e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:r.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:r.Event.None});function t(t){let r=t;return r&&(r===e.None||r===e.Cancelled||n.boolean(r.isCancellationRequested)&&!!r.onCancellationRequested)}o(t,`is`),e.is=t})(i||(e.CancellationToken=i={}));var a=Object.freeze(function(e,n){let r=(0,t.default)().timer.setTimeout(e.bind(n),0);return{dispose(){r.dispose()}}}),s=class{static{o(this,`MutableToken`)}constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?a:(this._emitter||=new r.Emitter,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),void 0)}};e.CancellationTokenSource=class{static{o(this,`CancellationTokenSource`)}get token(){return this._token||=new s,this._token}cancel(){this._token?this._token.cancel():this._token=i.Cancelled}dispose(){this._token?this._token instanceof s&&this._token.dispose():this._token=i.None}}}}),bt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/messages.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Message=e.NotificationType9=e.NotificationType8=e.NotificationType7=e.NotificationType6=e.NotificationType5=e.NotificationType4=e.NotificationType3=e.NotificationType2=e.NotificationType1=e.NotificationType0=e.NotificationType=e.RequestType9=e.RequestType8=e.RequestType7=e.RequestType6=e.RequestType5=e.RequestType4=e.RequestType3=e.RequestType2=e.RequestType1=e.RequestType=e.RequestType0=e.AbstractMessageSignature=e.ParameterStructures=e.ResponseError=e.ErrorCodes=void 0;var t=_t(),n;(function(e){e.ParseError=-32700,e.InvalidRequest=-32600,e.MethodNotFound=-32601,e.InvalidParams=-32602,e.InternalError=-32603,e.jsonrpcReservedErrorRangeStart=-32099,e.serverErrorStart=-32099,e.MessageWriteError=-32099,e.MessageReadError=-32098,e.PendingResponseRejected=-32097,e.ConnectionInactive=-32096,e.ServerNotInitialized=-32002,e.UnknownErrorCode=-32001,e.jsonrpcReservedErrorRangeEnd=-32e3,e.serverErrorEnd=-32e3})(n||(e.ErrorCodes=n={})),e.ResponseError=class e extends Error{static{o(this,`ResponseError`)}constructor(r,i,a){super(i),this.code=t.number(r)?r:n.UnknownErrorCode,this.data=a,Object.setPrototypeOf(this,e.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};var r=class e{static{o(this,`ParameterStructures`)}constructor(e){this.kind=e}static is(t){return t===e.auto||t===e.byName||t===e.byPosition}toString(){return this.kind}};e.ParameterStructures=r,r.auto=new r(`auto`),r.byPosition=new r(`byPosition`),r.byName=new r(`byName`);var i=class{static{o(this,`AbstractMessageSignature`)}constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return r.auto}};e.AbstractMessageSignature=i,e.RequestType0=class extends i{static{o(this,`RequestType0`)}constructor(e){super(e,0)}},e.RequestType=class extends i{static{o(this,`RequestType`)}constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType1=class extends i{static{o(this,`RequestType1`)}constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType2=class extends i{static{o(this,`RequestType2`)}constructor(e){super(e,2)}},e.RequestType3=class extends i{static{o(this,`RequestType3`)}constructor(e){super(e,3)}},e.RequestType4=class extends i{static{o(this,`RequestType4`)}constructor(e){super(e,4)}},e.RequestType5=class extends i{static{o(this,`RequestType5`)}constructor(e){super(e,5)}},e.RequestType6=class extends i{static{o(this,`RequestType6`)}constructor(e){super(e,6)}},e.RequestType7=class extends i{static{o(this,`RequestType7`)}constructor(e){super(e,7)}},e.RequestType8=class extends i{static{o(this,`RequestType8`)}constructor(e){super(e,8)}},e.RequestType9=class extends i{static{o(this,`RequestType9`)}constructor(e){super(e,9)}},e.NotificationType=class extends i{static{o(this,`NotificationType`)}constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType0=class extends i{static{o(this,`NotificationType0`)}constructor(e){super(e,0)}},e.NotificationType1=class extends i{static{o(this,`NotificationType1`)}constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType2=class extends i{static{o(this,`NotificationType2`)}constructor(e){super(e,2)}},e.NotificationType3=class extends i{static{o(this,`NotificationType3`)}constructor(e){super(e,3)}},e.NotificationType4=class extends i{static{o(this,`NotificationType4`)}constructor(e){super(e,4)}},e.NotificationType5=class extends i{static{o(this,`NotificationType5`)}constructor(e){super(e,5)}},e.NotificationType6=class extends i{static{o(this,`NotificationType6`)}constructor(e){super(e,6)}},e.NotificationType7=class extends i{static{o(this,`NotificationType7`)}constructor(e){super(e,7)}},e.NotificationType8=class extends i{static{o(this,`NotificationType8`)}constructor(e){super(e,8)}},e.NotificationType9=class extends i{static{o(this,`NotificationType9`)}constructor(e){super(e,9)}};var a;(function(e){function n(e){let n=e;return n&&t.string(n.method)&&(t.string(n.id)||t.number(n.id))}o(n,`isRequest`),e.isRequest=n;function r(e){let n=e;return n&&t.string(n.method)&&e.id===void 0}o(r,`isNotification`),e.isNotification=r;function i(e){let n=e;return n&&(n.result!==void 0||!!n.error)&&(t.string(n.id)||t.number(n.id)||n.id===null)}o(i,`isResponse`),e.isResponse=i})(a||(e.Message=a={}))}}),xt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/linkedMap.js"(e){var t;Object.defineProperty(e,"__esModule",{value:!0}),e.LRUCache=e.LinkedMap=e.Touch=void 0;var n;(function(e){e.None=0,e.First=1,e.AsOld=e.First,e.Last=2,e.AsNew=e.Last})(n||(e.Touch=n={}));var r=class{static{o(this,`LinkedMap`)}constructor(){this[t]=`LinkedMap`,this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,t=n.None){let r=this._map.get(e);if(r)return t!==n.None&&this.touch(r,t),r.value}set(e,t,r=n.None){let i=this._map.get(e);if(i)i.value=t,r!==n.None&&this.touch(i,r);else{switch(i={key:e,value:t,next:void 0,previous:void 0},r){case n.None:this.addItemLast(i);break;case n.First:this.addItemFirst(i);break;case n.Last:this.addItemLast(i);break;default:this.addItemLast(i);break}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw Error(`Invalid list`);let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){let n=this._state,r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==n)throw Error(`LinkedMap got modified during iteration.`);r=r.next}}keys(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:o(()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.key,done:!1};return t=t.next,e}else return{value:void 0,done:!0}},`next`)};return n}values(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:o(()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.value,done:!1};return t=t.next,e}else return{value:void 0,done:!0}},`next`)};return n}entries(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:o(()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:[t.key,t.value],done:!1};return t=t.next,e}else return{value:void 0,done:!0}},`next`)};return n}[(t=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw Error(`Invalid list`);this._head=e,this._state++}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw Error(`Invalid list`);this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw Error(`Invalid list`);e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw Error(`Invalid list`);e.previous.next=void 0,this._tail=e.previous}else{let t=e.next,n=e.previous;if(!t||!n)throw Error(`Invalid list`);t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw Error(`Invalid list`);if(!(t!==n.First&&t!==n.Last)){if(t===n.First){if(e===this._head)return;let t=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(t===n.Last){if(e===this._tail)return;let t=e.next,n=e.previous;e===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}}toJSON(){let e=[];return this.forEach((t,n)=>{e.push([n,t])}),e}fromJSON(e){this.clear();for(let[t,n]of e)this.set(t,n)}};e.LinkedMap=r,e.LRUCache=class extends r{static{o(this,`LRUCache`)}constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,t=n.AsNew){return super.get(e,t)}peek(e){return super.get(e,n.None)}set(e,t){return super.set(e,t,n.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}}}}),St=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/disposable.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Disposable=void 0;var t;(function(e){function t(e){return{dispose:e}}o(t,`create`),e.create=t})(t||(e.Disposable=t={}))}}),Ct=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=void 0;var t=yt(),n;(function(e){e.Continue=0,e.Cancelled=1})(n||={}),e.SharedArraySenderStrategy=class{static{o(this,`SharedArraySenderStrategy`)}constructor(){this.buffers=new Map}enableCancellation(e){if(e.id===null)return;let t=new SharedArrayBuffer(4),r=new Int32Array(t,0,1);r[0]=n.Continue,this.buffers.set(e.id,t),e.$cancellationData=t}async sendCancellation(e,t){let r=this.buffers.get(t);if(r===void 0)return;let i=new Int32Array(r,0,1);Atomics.store(i,0,n.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};var r=class{static{o(this,`SharedArrayBufferCancellationToken`)}constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===n.Cancelled}get onCancellationRequested(){throw Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`)}},i=class{static{o(this,`SharedArrayBufferCancellationTokenSource`)}constructor(e){this.token=new r(e)}cancel(){}dispose(){}};e.SharedArrayReceiverStrategy=class{static{o(this,`SharedArrayReceiverStrategy`)}constructor(){this.kind=`request`}createCancellationTokenSource(e){let n=e.$cancellationData;return n===void 0?new t.CancellationTokenSource:new i(n)}}}}),wt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/semaphore.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Semaphore=void 0;var t=gt();e.Semaphore=class{static{o(this,`Semaphore`)}constructor(e=1){if(e<=0)throw Error(`Capacity must be greater than 0`);this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,n)=>{this._waiting.push({thunk:e,resolve:t,reject:n}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,t.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw Error(`To many thunks active`);try{let t=e.thunk();t instanceof Promise?t.then(t=>{this._active--,e.resolve(t),this.runNext()},t=>{this._active--,e.reject(t),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}}}}),Tt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/messageReader.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=void 0;var t=gt(),n=_t(),r=vt(),i=wt(),a;(function(e){function t(e){let t=e;return t&&n.func(t.listen)&&n.func(t.dispose)&&n.func(t.onError)&&n.func(t.onClose)&&n.func(t.onPartialMessage)}o(t,`is`),e.is=t})(a||(e.MessageReader=a={}));var s=class{static{o(this,`AbstractMessageReader`)}constructor(){this.errorEmitter=new r.Emitter,this.closeEmitter=new r.Emitter,this.partialMessageEmitter=new r.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:Error(`Reader received error. Reason: ${n.string(e.message)?e.message:`unknown`}`)}};e.AbstractMessageReader=s;var c;(function(e){function n(e){let n,r,i=new Map,a,o=new Map;if(e===void 0||typeof e==`string`)n=e??`utf-8`;else{if(n=e.charset??`utf-8`,e.contentDecoder!==void 0&&(r=e.contentDecoder,i.set(r.name,r)),e.contentDecoders!==void 0)for(let t of e.contentDecoders)i.set(t.name,t);if(e.contentTypeDecoder!==void 0&&(a=e.contentTypeDecoder,o.set(a.name,a)),e.contentTypeDecoders!==void 0)for(let t of e.contentTypeDecoders)o.set(t.name,t)}return a===void 0&&(a=(0,t.default)().applicationJson.decoder,o.set(a.name,a)),{charset:n,contentDecoder:r,contentDecoders:i,contentTypeDecoder:a,contentTypeDecoders:o}}o(n,`fromOptions`),e.fromOptions=n})(c||={}),e.ReadableStreamMessageReader=class extends s{static{o(this,`ReadableStreamMessageReader`)}constructor(e,n){super(),this.readable=e,this.options=c.fromOptions(n),this.buffer=(0,t.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new i.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;let t=this.readable.onData(e=>{this.onData(e)});return this.readable.onError(e=>this.fireError(e)),this.readable.onClose(()=>this.fireClose()),t}onData(e){try{for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let e=this.buffer.tryReadHeaders(!0);if(!e)return;let t=e.get(`content-length`);if(!t){this.fireError(Error(`Header must provide a Content-Length property. +${JSON.stringify(Object.fromEntries(e))}`));return}let n=parseInt(t);if(isNaN(n)){this.fireError(Error(`Content-Length value must be a number. Got ${t}`));return}this.nextMessageLength=n}let e=this.buffer.tryReadBody(this.nextMessageLength);if(e===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let t=this.options.contentDecoder===void 0?e:await this.options.contentDecoder.decode(e),n=await this.options.contentTypeDecoder.decode(t,this.options);this.callback(n)}).catch(e=>{this.fireError(e)})}}catch(e){this.fireError(e)}}clearPartialMessageTimer(){this.partialMessageTimer&&=(this.partialMessageTimer.dispose(),void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,t.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}}}}),Et=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/messageWriter.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=void 0;var t=gt(),n=_t(),r=wt(),i=vt(),a=`Content-Length: `,s=`\r +`,c;(function(e){function t(e){let t=e;return t&&n.func(t.dispose)&&n.func(t.onClose)&&n.func(t.onError)&&n.func(t.write)}o(t,`is`),e.is=t})(c||(e.MessageWriter=c={}));var l=class{static{o(this,`AbstractMessageWriter`)}constructor(){this.errorEmitter=new i.Emitter,this.closeEmitter=new i.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,n){this.errorEmitter.fire([this.asError(e),t,n])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:Error(`Writer received error. Reason: ${n.string(e.message)?e.message:`unknown`}`)}};e.AbstractMessageWriter=l;var u;(function(e){function n(e){return e===void 0||typeof e==`string`?{charset:e??`utf-8`,contentTypeEncoder:(0,t.default)().applicationJson.encoder}:{charset:e.charset??`utf-8`,contentEncoder:e.contentEncoder,contentTypeEncoder:e.contentTypeEncoder??(0,t.default)().applicationJson.encoder}}o(n,`fromOptions`),e.fromOptions=n})(u||={}),e.WriteableStreamMessageWriter=class extends l{static{o(this,`WriteableStreamMessageWriter`)}constructor(e,t){super(),this.writable=e,this.options=u.fromOptions(t),this.errorCount=0,this.writeSemaphore=new r.Semaphore(1),this.writable.onError(e=>this.fireError(e)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(e=>this.options.contentEncoder===void 0?e:this.options.contentEncoder.encode(e)).then(t=>{let n=[];return n.push(a,t.byteLength.toString(),s),n.push(s),this.doWrite(e,n,t)},e=>{throw this.fireError(e),e}))}async doWrite(e,t,n){try{return await this.writable.write(t.join(``),`ascii`),this.writable.write(n)}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){this.writable.end()}}}}),Dt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/messageBuffer.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AbstractMessageBuffer=void 0;var t=13,n=10,r=`\r +`;e.AbstractMessageBuffer=class{static{o(this,`AbstractMessageBuffer`)}constructor(e=`utf-8`){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){let t=typeof e==`string`?this.fromString(e,this._encoding):e;this._chunks.push(t),this._totalLength+=t.byteLength}tryReadHeaders(e=!1){if(this._chunks.length===0)return;let i=0,a=0,o=0,s=0;row:for(;athis._totalLength)throw Error(`Cannot read so many bytes!`);if(this._chunks[0].byteLength===e){let t=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(t)}if(this._chunks[0].byteLength>e){let t=this._chunks[0],n=this.asNative(t,e);return this._chunks[0]=t.slice(e),this._totalLength-=e,n}let t=this.allocNative(e),n=0;for(;e>0;){let r=this._chunks[0];if(r.byteLength>e){let i=r.slice(0,e);t.set(i,n),n+=e,this._chunks[0]=r.slice(e),this._totalLength-=e,e-=e}else t.set(r,n),n+=r.byteLength,this._chunks.shift(),this._totalLength-=r.byteLength,e-=r.byteLength}return t}}}}),Ot=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/connection.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createMessageConnection=e.ConnectionOptions=e.MessageStrategy=e.CancellationStrategy=e.CancellationSenderStrategy=e.CancellationReceiverStrategy=e.RequestCancellationReceiverStrategy=e.IdCancellationReceiverStrategy=e.ConnectionStrategy=e.ConnectionError=e.ConnectionErrors=e.LogTraceNotification=e.SetTraceNotification=e.TraceFormat=e.TraceValues=e.Trace=e.NullLogger=e.ProgressType=e.ProgressToken=void 0;var t=gt(),n=_t(),r=bt(),i=xt(),a=vt(),s=yt(),c;(function(e){e.type=new r.NotificationType(`$/cancelRequest`)})(c||={});var l;(function(e){function t(e){return typeof e==`string`||typeof e==`number`}o(t,`is`),e.is=t})(l||(e.ProgressToken=l={}));var u;(function(e){e.type=new r.NotificationType(`$/progress`)})(u||={}),e.ProgressType=class{static{o(this,`ProgressType`)}constructor(){}};var d;(function(e){function t(e){return n.func(e)}o(t,`is`),e.is=t})(d||={}),e.NullLogger=Object.freeze({error:o(()=>{},`error`),warn:o(()=>{},`warn`),info:o(()=>{},`info`),log:o(()=>{},`log`)});var f;(function(e){e[e.Off=0]=`Off`,e[e.Messages=1]=`Messages`,e[e.Compact=2]=`Compact`,e[e.Verbose=3]=`Verbose`})(f||(e.Trace=f={}));var p;(function(e){e.Off=`off`,e.Messages=`messages`,e.Compact=`compact`,e.Verbose=`verbose`})(p||(e.TraceValues=p={})),(function(e){function t(t){if(!n.string(t))return e.Off;switch(t=t.toLowerCase(),t){case`off`:return e.Off;case`messages`:return e.Messages;case`compact`:return e.Compact;case`verbose`:return e.Verbose;default:return e.Off}}o(t,`fromString`),e.fromString=t;function r(t){switch(t){case e.Off:return`off`;case e.Messages:return`messages`;case e.Compact:return`compact`;case e.Verbose:return`verbose`;default:return`off`}}o(r,`toString`),e.toString=r})(f||(e.Trace=f={}));var m;(function(e){e.Text=`text`,e.JSON=`json`})(m||(e.TraceFormat=m={})),(function(e){function t(t){return n.string(t)?(t=t.toLowerCase(),t===`json`?e.JSON:e.Text):e.Text}o(t,`fromString`),e.fromString=t})(m||(e.TraceFormat=m={}));var h;(function(e){e.type=new r.NotificationType(`$/setTrace`)})(h||(e.SetTraceNotification=h={}));var g;(function(e){e.type=new r.NotificationType(`$/logTrace`)})(g||(e.LogTraceNotification=g={}));var _;(function(e){e[e.Closed=1]=`Closed`,e[e.Disposed=2]=`Disposed`,e[e.AlreadyListening=3]=`AlreadyListening`})(_||(e.ConnectionErrors=_={}));var v=class e extends Error{static{o(this,`ConnectionError`)}constructor(t,n){super(n),this.code=t,Object.setPrototypeOf(this,e.prototype)}};e.ConnectionError=v;var y;(function(e){function t(e){let t=e;return t&&n.func(t.cancelUndispatched)}o(t,`is`),e.is=t})(y||(e.ConnectionStrategy=y={}));var b;(function(e){function t(e){let t=e;return t&&(t.kind===void 0||t.kind===`id`)&&n.func(t.createCancellationTokenSource)&&(t.dispose===void 0||n.func(t.dispose))}o(t,`is`),e.is=t})(b||(e.IdCancellationReceiverStrategy=b={}));var x;(function(e){function t(e){let t=e;return t&&t.kind===`request`&&n.func(t.createCancellationTokenSource)&&(t.dispose===void 0||n.func(t.dispose))}o(t,`is`),e.is=t})(x||(e.RequestCancellationReceiverStrategy=x={}));var ee;(function(e){e.Message=Object.freeze({createCancellationTokenSource(e){return new s.CancellationTokenSource}});function t(e){return b.is(e)||x.is(e)}o(t,`is`),e.is=t})(ee||(e.CancellationReceiverStrategy=ee={}));var S;(function(e){e.Message=Object.freeze({sendCancellation(e,t){return e.sendNotification(c.type,{id:t})},cleanup(e){}});function t(e){let t=e;return t&&n.func(t.sendCancellation)&&n.func(t.cleanup)}o(t,`is`),e.is=t})(S||(e.CancellationSenderStrategy=S={}));var te;(function(e){e.Message=Object.freeze({receiver:ee.Message,sender:S.Message});function t(e){let t=e;return t&&ee.is(t.receiver)&&S.is(t.sender)}o(t,`is`),e.is=t})(te||(e.CancellationStrategy=te={}));var ne;(function(e){function t(e){let t=e;return t&&n.func(t.handleMessage)}o(t,`is`),e.is=t})(ne||(e.MessageStrategy=ne={}));var C;(function(e){function t(e){let t=e;return t&&(te.is(t.cancellationStrategy)||y.is(t.connectionStrategy)||ne.is(t.messageStrategy))}o(t,`is`),e.is=t})(C||(e.ConnectionOptions=C={}));var re;(function(e){e[e.New=1]=`New`,e[e.Listening=2]=`Listening`,e[e.Closed=3]=`Closed`,e[e.Disposed=4]=`Disposed`})(re||={});function ie(p,y,x,ee){let S=x===void 0?e.NullLogger:x,C=0,ie=0,ae=0,oe,se=new Map,ce,le=new Map,ue=new Map,de,w=new i.LinkedMap,T=new Map,E=new Set,D=new Map,O=f.Off,fe=m.Text,k,pe=re.New,me=new a.Emitter,he=new a.Emitter,ge=new a.Emitter,_e=new a.Emitter,ve=new a.Emitter,ye=ee&&ee.cancellationStrategy?ee.cancellationStrategy:te.Message;function be(e){if(e===null)throw Error(`Can't send requests with id null since the response can't be correlated.`);return`req-`+e.toString()}o(be,`createRequestQueueKey`);function xe(e){return e===null?`res-unknown-`+(++ae).toString():`res-`+e.toString()}o(xe,`createResponseQueueKey`);function Se(){return`not-`+(++ie).toString()}o(Se,`createNotificationQueueKey`);function Ce(e,t){r.Message.isRequest(t)?e.set(be(t.id),t):r.Message.isResponse(t)?e.set(xe(t.id),t):e.set(Se(),t)}o(Ce,`addMessageToQueue`);function we(e){}o(we,`cancelUndispatched`);function Te(){return pe===re.Listening}o(Te,`isListening`);function Ee(){return pe===re.Closed}o(Ee,`isClosed`);function De(){return pe===re.Disposed}o(De,`isDisposed`);function Oe(){(pe===re.New||pe===re.Listening)&&(pe=re.Closed,he.fire(void 0))}o(Oe,`closeHandler`);function ke(e){me.fire([e,void 0,void 0])}o(ke,`readErrorHandler`);function Ae(e){me.fire(e)}o(Ae,`writeErrorHandler`),p.onClose(Oe),p.onError(ke),y.onClose(Oe),y.onError(Ae);function je(){de||w.size===0||(de=(0,t.default)().timer.setImmediate(()=>{de=void 0,Ne()}))}o(je,`triggerMessageQueue`);function Me(e){r.Message.isRequest(e)?Fe(e):r.Message.isNotification(e)?Le(e):r.Message.isResponse(e)?Ie(e):Re(e)}o(Me,`handleMessage`);function Ne(){if(w.size===0)return;let e=w.shift();try{let t=ee?.messageStrategy;ne.is(t)?t.handleMessage(e,Me):Me(e)}finally{je()}}o(Ne,`processMessageQueue`);let Pe=o(e=>{try{if(r.Message.isNotification(e)&&e.method===c.type.method){let t=e.params.id,n=be(t),i=w.get(n);if(r.Message.isRequest(i)){let r=ee?.connectionStrategy,a=r&&r.cancelUndispatched?r.cancelUndispatched(i,we):void 0;if(a&&(a.error!==void 0||a.result!==void 0)){w.delete(n),D.delete(t),a.id=i.id,He(a,e.method,Date.now()),y.write(a).catch(()=>S.error(`Sending response for canceled message failed.`));return}}let a=D.get(t);if(a!==void 0){a.cancel(),We(e);return}else E.add(t)}Ce(w,e)}finally{je()}},`callback`);function Fe(e){if(De())return;function t(t,n,i){let a={jsonrpc:`2.0`,id:e.id};t instanceof r.ResponseError?a.error=t.toJson():a.result=t===void 0?null:t,He(a,n,i),y.write(a).catch(()=>S.error(`Sending response failed.`))}o(t,`reply`);function i(t,n,r){let i={jsonrpc:`2.0`,id:e.id,error:t.toJson()};He(i,n,r),y.write(i).catch(()=>S.error(`Sending response failed.`))}o(i,`replyError`);function a(t,n,r){t===void 0&&(t=null);let i={jsonrpc:`2.0`,id:e.id,result:t};He(i,n,r),y.write(i).catch(()=>S.error(`Sending response failed.`))}o(a,`replySuccess`),Ue(e);let s=se.get(e.method),c,l;s&&(c=s.type,l=s.handler);let u=Date.now();if(l||oe){let o=e.id??String(Date.now()),s=b.is(ye.receiver)?ye.receiver.createCancellationTokenSource(o):ye.receiver.createCancellationTokenSource(e);e.id!==null&&E.has(e.id)&&s.cancel(),e.id!==null&&D.set(o,s);try{let d;if(l)if(e.params===void 0){if(c!==void 0&&c.numberOfParams!==0){i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines ${c.numberOfParams} params but received none.`),e.method,u);return}d=l(s.token)}else if(Array.isArray(e.params)){if(c!==void 0&&c.parameterStructures===r.ParameterStructures.byName){i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by name but received parameters by position`),e.method,u);return}d=l(...e.params,s.token)}else{if(c!==void 0&&c.parameterStructures===r.ParameterStructures.byPosition){i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by position but received parameters by name`),e.method,u);return}d=l(e.params,s.token)}else oe&&(d=oe(e.method,e.params,s.token));let f=d;d?f.then?f.then(n=>{D.delete(o),t(n,e.method,u)},t=>{D.delete(o),t instanceof r.ResponseError?i(t,e.method,u):t&&n.string(t.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${t.message}`),e.method,u):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,u)}):(D.delete(o),t(d,e.method,u)):(D.delete(o),a(d,e.method,u))}catch(a){D.delete(o),a instanceof r.ResponseError?t(a,e.method,u):a&&n.string(a.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${a.message}`),e.method,u):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,u)}}else i(new r.ResponseError(r.ErrorCodes.MethodNotFound,`Unhandled method ${e.method}`),e.method,u)}o(Fe,`handleRequest`);function Ie(e){if(!De())if(e.id===null)e.error?S.error(`Received response message without id: Error is: +${JSON.stringify(e.error,void 0,4)}`):S.error(`Received response message without id. No further error information provided.`);else{let t=e.id,n=T.get(t);if(Ge(e,n),n!==void 0){T.delete(t);try{if(e.error){let t=e.error;n.reject(new r.ResponseError(t.code,t.message,t.data))}else if(e.result!==void 0)n.resolve(e.result);else throw Error(`Should never happen.`)}catch(e){e.message?S.error(`Response handler '${n.method}' failed with message: ${e.message}`):S.error(`Response handler '${n.method}' failed unexpectedly.`)}}}}o(Ie,`handleResponse`);function Le(e){if(De())return;let t,n;if(e.method===c.type.method){let t=e.params.id;E.delete(t),We(e);return}else{let r=le.get(e.method);r&&(n=r.handler,t=r.type)}if(n||ce)try{if(We(e),n)if(e.params===void 0)t!==void 0&&t.numberOfParams!==0&&t.parameterStructures!==r.ParameterStructures.byName&&S.error(`Notification ${e.method} defines ${t.numberOfParams} params but received none.`),n();else if(Array.isArray(e.params)){let i=e.params;e.method===u.type.method&&i.length===2&&l.is(i[0])?n({token:i[0],value:i[1]}):(t!==void 0&&(t.parameterStructures===r.ParameterStructures.byName&&S.error(`Notification ${e.method} defines parameters by name but received parameters by position`),t.numberOfParams!==e.params.length&&S.error(`Notification ${e.method} defines ${t.numberOfParams} params but received ${i.length} arguments`)),n(...i))}else t!==void 0&&t.parameterStructures===r.ParameterStructures.byPosition&&S.error(`Notification ${e.method} defines parameters by position but received parameters by name`),n(e.params);else ce&&ce(e.method,e.params)}catch(t){t.message?S.error(`Notification handler '${e.method}' failed with message: ${t.message}`):S.error(`Notification handler '${e.method}' failed unexpectedly.`)}else ge.fire(e)}o(Le,`handleNotification`);function Re(e){if(!e){S.error(`Received empty message.`);return}S.error(`Received message which is neither a response nor a notification message: +${JSON.stringify(e,null,4)}`);let t=e;if(n.string(t.id)||n.number(t.id)){let e=t.id,n=T.get(e);n&&n.reject(Error(`The received response has neither a result nor an error property.`))}}o(Re,`handleInvalidMessage`);function ze(e){if(e!=null)switch(O){case f.Verbose:return JSON.stringify(e,null,4);case f.Compact:return JSON.stringify(e);default:return}}o(ze,`stringifyTrace`);function Be(e){if(!(O===f.Off||!k))if(fe===m.Text){let t;(O===f.Verbose||O===f.Compact)&&e.params&&(t=`Params: ${ze(e.params)} + +`),k.log(`Sending request '${e.method} - (${e.id})'.`,t)}else Ke(`send-request`,e)}o(Be,`traceSendingRequest`);function Ve(e){if(!(O===f.Off||!k))if(fe===m.Text){let t;(O===f.Verbose||O===f.Compact)&&(t=e.params?`Params: ${ze(e.params)} + +`:`No parameters provided. + +`),k.log(`Sending notification '${e.method}'.`,t)}else Ke(`send-notification`,e)}o(Ve,`traceSendingNotification`);function He(e,t,n){if(!(O===f.Off||!k))if(fe===m.Text){let r;(O===f.Verbose||O===f.Compact)&&(e.error&&e.error.data?r=`Error data: ${ze(e.error.data)} + +`:e.result?r=`Result: ${ze(e.result)} + +`:e.error===void 0&&(r=`No result returned. + +`)),k.log(`Sending response '${t} - (${e.id})'. Processing request took ${Date.now()-n}ms`,r)}else Ke(`send-response`,e)}o(He,`traceSendingResponse`);function Ue(e){if(!(O===f.Off||!k))if(fe===m.Text){let t;(O===f.Verbose||O===f.Compact)&&e.params&&(t=`Params: ${ze(e.params)} + +`),k.log(`Received request '${e.method} - (${e.id})'.`,t)}else Ke(`receive-request`,e)}o(Ue,`traceReceivedRequest`);function We(e){if(!(O===f.Off||!k||e.method===g.type.method))if(fe===m.Text){let t;(O===f.Verbose||O===f.Compact)&&(t=e.params?`Params: ${ze(e.params)} + +`:`No parameters provided. + +`),k.log(`Received notification '${e.method}'.`,t)}else Ke(`receive-notification`,e)}o(We,`traceReceivedNotification`);function Ge(e,t){if(!(O===f.Off||!k))if(fe===m.Text){let n;if((O===f.Verbose||O===f.Compact)&&(e.error&&e.error.data?n=`Error data: ${ze(e.error.data)} + +`:e.result?n=`Result: ${ze(e.result)} + +`:e.error===void 0&&(n=`No result returned. + +`)),t){let r=e.error?` Request failed: ${e.error.message} (${e.error.code}).`:``;k.log(`Received response '${t.method} - (${e.id})' in ${Date.now()-t.timerStart}ms.${r}`,n)}else k.log(`Received response ${e.id} without active response promise.`,n)}else Ke(`receive-response`,e)}o(Ge,`traceReceivedResponse`);function Ke(e,t){if(!k||O===f.Off)return;let n={isLSPMessage:!0,type:e,message:t,timestamp:Date.now()};k.log(n)}o(Ke,`logLSPMessage`);function qe(){if(Ee())throw new v(_.Closed,`Connection is closed.`);if(De())throw new v(_.Disposed,`Connection is disposed.`)}o(qe,`throwIfClosedOrDisposed`);function Je(){if(Te())throw new v(_.AlreadyListening,`Connection is already listening`)}o(Je,`throwIfListening`);function Ye(){if(!Te())throw Error(`Call listen() first.`)}o(Ye,`throwIfNotListening`);function Xe(e){return e===void 0?null:e}o(Xe,`undefinedToNull`);function Ze(e){if(e!==null)return e}o(Ze,`nullToUndefined`);function Qe(e){return e!=null&&!Array.isArray(e)&&typeof e==`object`}o(Qe,`isNamedParam`);function $e(e,t){switch(e){case r.ParameterStructures.auto:return Qe(t)?Ze(t):[Xe(t)];case r.ParameterStructures.byName:if(!Qe(t))throw Error(`Received parameters by name but param is not an object literal.`);return Ze(t);case r.ParameterStructures.byPosition:return[Xe(t)];default:throw Error(`Unknown parameter structure ${e.toString()}`)}}o($e,`computeSingleParam`);function et(e,t){let n,r=e.numberOfParams;switch(r){case 0:n=void 0;break;case 1:n=$e(e.parameterStructures,t[0]);break;default:n=[];for(let e=0;e{qe();let i,a;if(n.string(e)){i=e;let n=t[0],o=0,s=r.ParameterStructures.auto;r.ParameterStructures.is(n)&&(o=1,s=n);let c=t.length,l=c-o;switch(l){case 0:a=void 0;break;case 1:a=$e(s,t[o]);break;default:if(s===r.ParameterStructures.byName)throw Error(`Received ${l} parameters for 'by Name' notification parameter structure.`);a=t.slice(o,c).map(e=>Xe(e));break}}else{let n=t;i=e.method,a=et(e,n)}let o={jsonrpc:`2.0`,method:i,params:a};return Ve(o),y.write(o).catch(e=>{throw S.error(`Sending notification failed.`),e})},`sendNotification`),onNotification:o((e,t)=>{qe();let r;return n.func(e)?ce=e:t&&(n.string(e)?(r=e,le.set(e,{type:void 0,handler:t})):(r=e.method,le.set(e.method,{type:e,handler:t}))),{dispose:o(()=>{r===void 0?ce=void 0:le.delete(r)},`dispose`)}},`onNotification`),onProgress:o((e,t,n)=>{if(ue.has(t))throw Error(`Progress handler for token ${t} already registered`);return ue.set(t,n),{dispose:o(()=>{ue.delete(t)},`dispose`)}},`onProgress`),sendProgress:o((e,t,n)=>tt.sendNotification(u.type,{token:t,value:n}),`sendProgress`),onUnhandledProgress:_e.event,sendRequest:o((e,...t)=>{qe(),Ye();let i,a,c;if(n.string(e)){i=e;let n=t[0],o=t[t.length-1],l=0,u=r.ParameterStructures.auto;r.ParameterStructures.is(n)&&(l=1,u=n);let d=t.length;s.CancellationToken.is(o)&&(--d,c=o);let f=d-l;switch(f){case 0:a=void 0;break;case 1:a=$e(u,t[l]);break;default:if(u===r.ParameterStructures.byName)throw Error(`Received ${f} parameters for 'by Name' request parameter structure.`);a=t.slice(l,d).map(e=>Xe(e));break}}else{let n=t;i=e.method,a=et(e,n);let r=e.numberOfParams;c=s.CancellationToken.is(n[r])?n[r]:void 0}let l=C++,u;c&&(u=c.onCancellationRequested(()=>{let e=ye.sender.sendCancellation(tt,l);return e===void 0?(S.log(`Received no promise from cancellation strategy when cancelling id ${l}`),Promise.resolve()):e.catch(()=>{S.log(`Sending cancellation messages for id ${l} failed`)})}));let d={jsonrpc:`2.0`,id:l,method:i,params:a};return Be(d),typeof ye.sender.enableCancellation==`function`&&ye.sender.enableCancellation(d),new Promise(async(e,t)=>{let n=o(t=>{e(t),ye.sender.cleanup(l),u?.dispose()},`resolveWithCleanup`),a=o(e=>{t(e),ye.sender.cleanup(l),u?.dispose()},`rejectWithCleanup`),s={method:i,timerStart:Date.now(),resolve:n,reject:a};try{await y.write(d),T.set(l,s)}catch(e){throw S.error(`Sending request failed.`),s.reject(new r.ResponseError(r.ErrorCodes.MessageWriteError,e.message?e.message:`Unknown reason`)),e}})},`sendRequest`),onRequest:o((e,t)=>{qe();let r=null;return d.is(e)?(r=void 0,oe=e):n.string(e)?(r=null,t!==void 0&&(r=e,se.set(e,{handler:t,type:void 0}))):t!==void 0&&(r=e.method,se.set(e.method,{type:e,handler:t})),{dispose:o(()=>{r!==null&&(r===void 0?oe=void 0:se.delete(r))},`dispose`)}},`onRequest`),hasPendingResponse:o(()=>T.size>0,`hasPendingResponse`),trace:o(async(e,t,r)=>{let i=!1,a=m.Text;r!==void 0&&(n.boolean(r)?i=r:(i=r.sendNotification||!1,a=r.traceFormat||m.Text)),O=e,fe=a,k=O===f.Off?void 0:t,i&&!Ee()&&!De()&&await tt.sendNotification(h.type,{value:f.toString(e)})},`trace`),onError:me.event,onClose:he.event,onUnhandledNotification:ge.event,onDispose:ve.event,end:o(()=>{y.end()},`end`),dispose:o(()=>{if(De())return;pe=re.Disposed,ve.fire(void 0);let e=new r.ResponseError(r.ErrorCodes.PendingResponseRejected,`Pending response rejected since connection got disposed`);for(let t of T.values())t.reject(e);T=new Map,D=new Map,E=new Set,w=new i.LinkedMap,n.func(y.dispose)&&y.dispose(),n.func(p.dispose)&&p.dispose()},`dispose`),listen:o(()=>{qe(),Je(),pe=re.Listening,p.listen(Pe)},`listen`),inspect:o(()=>{(0,t.default)().console.log(`inspect`)},`inspect`)};return tt.onNotification(g.type,e=>{if(O===f.Off||!k)return;let t=O===f.Verbose||O===f.Compact;k.log(e.message,t?e.verbose:void 0)}),tt.onNotification(u.type,e=>{let t=ue.get(e.token);t?t(e.value):_e.fire(e)}),tt}o(ie,`createMessageConnection`),e.createMessageConnection=ie}}),kt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/api.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ProgressType=e.ProgressToken=e.createMessageConnection=e.NullLogger=e.ConnectionOptions=e.ConnectionStrategy=e.AbstractMessageBuffer=e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=e.CancellationToken=e.CancellationTokenSource=e.Emitter=e.Event=e.Disposable=e.LRUCache=e.Touch=e.LinkedMap=e.ParameterStructures=e.NotificationType9=e.NotificationType8=e.NotificationType7=e.NotificationType6=e.NotificationType5=e.NotificationType4=e.NotificationType3=e.NotificationType2=e.NotificationType1=e.NotificationType0=e.NotificationType=e.ErrorCodes=e.ResponseError=e.RequestType9=e.RequestType8=e.RequestType7=e.RequestType6=e.RequestType5=e.RequestType4=e.RequestType3=e.RequestType2=e.RequestType1=e.RequestType0=e.RequestType=e.Message=e.RAL=void 0,e.MessageStrategy=e.CancellationStrategy=e.CancellationSenderStrategy=e.CancellationReceiverStrategy=e.ConnectionError=e.ConnectionErrors=e.LogTraceNotification=e.SetTraceNotification=e.TraceFormat=e.TraceValues=e.Trace=void 0;var t=bt();Object.defineProperty(e,"Message",{enumerable:!0,get:o(function(){return t.Message},`get`)}),Object.defineProperty(e,"RequestType",{enumerable:!0,get:o(function(){return t.RequestType},`get`)}),Object.defineProperty(e,"RequestType0",{enumerable:!0,get:o(function(){return t.RequestType0},`get`)}),Object.defineProperty(e,"RequestType1",{enumerable:!0,get:o(function(){return t.RequestType1},`get`)}),Object.defineProperty(e,"RequestType2",{enumerable:!0,get:o(function(){return t.RequestType2},`get`)}),Object.defineProperty(e,"RequestType3",{enumerable:!0,get:o(function(){return t.RequestType3},`get`)}),Object.defineProperty(e,"RequestType4",{enumerable:!0,get:o(function(){return t.RequestType4},`get`)}),Object.defineProperty(e,"RequestType5",{enumerable:!0,get:o(function(){return t.RequestType5},`get`)}),Object.defineProperty(e,"RequestType6",{enumerable:!0,get:o(function(){return t.RequestType6},`get`)}),Object.defineProperty(e,"RequestType7",{enumerable:!0,get:o(function(){return t.RequestType7},`get`)}),Object.defineProperty(e,"RequestType8",{enumerable:!0,get:o(function(){return t.RequestType8},`get`)}),Object.defineProperty(e,"RequestType9",{enumerable:!0,get:o(function(){return t.RequestType9},`get`)}),Object.defineProperty(e,"ResponseError",{enumerable:!0,get:o(function(){return t.ResponseError},`get`)}),Object.defineProperty(e,"ErrorCodes",{enumerable:!0,get:o(function(){return t.ErrorCodes},`get`)}),Object.defineProperty(e,"NotificationType",{enumerable:!0,get:o(function(){return t.NotificationType},`get`)}),Object.defineProperty(e,"NotificationType0",{enumerable:!0,get:o(function(){return t.NotificationType0},`get`)}),Object.defineProperty(e,"NotificationType1",{enumerable:!0,get:o(function(){return t.NotificationType1},`get`)}),Object.defineProperty(e,"NotificationType2",{enumerable:!0,get:o(function(){return t.NotificationType2},`get`)}),Object.defineProperty(e,"NotificationType3",{enumerable:!0,get:o(function(){return t.NotificationType3},`get`)}),Object.defineProperty(e,"NotificationType4",{enumerable:!0,get:o(function(){return t.NotificationType4},`get`)}),Object.defineProperty(e,"NotificationType5",{enumerable:!0,get:o(function(){return t.NotificationType5},`get`)}),Object.defineProperty(e,"NotificationType6",{enumerable:!0,get:o(function(){return t.NotificationType6},`get`)}),Object.defineProperty(e,"NotificationType7",{enumerable:!0,get:o(function(){return t.NotificationType7},`get`)}),Object.defineProperty(e,"NotificationType8",{enumerable:!0,get:o(function(){return t.NotificationType8},`get`)}),Object.defineProperty(e,"NotificationType9",{enumerable:!0,get:o(function(){return t.NotificationType9},`get`)}),Object.defineProperty(e,"ParameterStructures",{enumerable:!0,get:o(function(){return t.ParameterStructures},`get`)});var n=xt();Object.defineProperty(e,"LinkedMap",{enumerable:!0,get:o(function(){return n.LinkedMap},`get`)}),Object.defineProperty(e,"LRUCache",{enumerable:!0,get:o(function(){return n.LRUCache},`get`)}),Object.defineProperty(e,"Touch",{enumerable:!0,get:o(function(){return n.Touch},`get`)});var r=St();Object.defineProperty(e,"Disposable",{enumerable:!0,get:o(function(){return r.Disposable},`get`)});var i=vt();Object.defineProperty(e,"Event",{enumerable:!0,get:o(function(){return i.Event},`get`)}),Object.defineProperty(e,"Emitter",{enumerable:!0,get:o(function(){return i.Emitter},`get`)});var a=yt();Object.defineProperty(e,"CancellationTokenSource",{enumerable:!0,get:o(function(){return a.CancellationTokenSource},`get`)}),Object.defineProperty(e,"CancellationToken",{enumerable:!0,get:o(function(){return a.CancellationToken},`get`)});var s=Ct();Object.defineProperty(e,"SharedArraySenderStrategy",{enumerable:!0,get:o(function(){return s.SharedArraySenderStrategy},`get`)}),Object.defineProperty(e,"SharedArrayReceiverStrategy",{enumerable:!0,get:o(function(){return s.SharedArrayReceiverStrategy},`get`)});var c=Tt();Object.defineProperty(e,"MessageReader",{enumerable:!0,get:o(function(){return c.MessageReader},`get`)}),Object.defineProperty(e,"AbstractMessageReader",{enumerable:!0,get:o(function(){return c.AbstractMessageReader},`get`)}),Object.defineProperty(e,"ReadableStreamMessageReader",{enumerable:!0,get:o(function(){return c.ReadableStreamMessageReader},`get`)});var l=Et();Object.defineProperty(e,"MessageWriter",{enumerable:!0,get:o(function(){return l.MessageWriter},`get`)}),Object.defineProperty(e,"AbstractMessageWriter",{enumerable:!0,get:o(function(){return l.AbstractMessageWriter},`get`)}),Object.defineProperty(e,"WriteableStreamMessageWriter",{enumerable:!0,get:o(function(){return l.WriteableStreamMessageWriter},`get`)});var u=Dt();Object.defineProperty(e,"AbstractMessageBuffer",{enumerable:!0,get:o(function(){return u.AbstractMessageBuffer},`get`)});var d=Ot();Object.defineProperty(e,"ConnectionStrategy",{enumerable:!0,get:o(function(){return d.ConnectionStrategy},`get`)}),Object.defineProperty(e,"ConnectionOptions",{enumerable:!0,get:o(function(){return d.ConnectionOptions},`get`)}),Object.defineProperty(e,"NullLogger",{enumerable:!0,get:o(function(){return d.NullLogger},`get`)}),Object.defineProperty(e,"createMessageConnection",{enumerable:!0,get:o(function(){return d.createMessageConnection},`get`)}),Object.defineProperty(e,"ProgressToken",{enumerable:!0,get:o(function(){return d.ProgressToken},`get`)}),Object.defineProperty(e,"ProgressType",{enumerable:!0,get:o(function(){return d.ProgressType},`get`)}),Object.defineProperty(e,"Trace",{enumerable:!0,get:o(function(){return d.Trace},`get`)}),Object.defineProperty(e,"TraceValues",{enumerable:!0,get:o(function(){return d.TraceValues},`get`)}),Object.defineProperty(e,"TraceFormat",{enumerable:!0,get:o(function(){return d.TraceFormat},`get`)}),Object.defineProperty(e,"SetTraceNotification",{enumerable:!0,get:o(function(){return d.SetTraceNotification},`get`)}),Object.defineProperty(e,"LogTraceNotification",{enumerable:!0,get:o(function(){return d.LogTraceNotification},`get`)}),Object.defineProperty(e,"ConnectionErrors",{enumerable:!0,get:o(function(){return d.ConnectionErrors},`get`)}),Object.defineProperty(e,"ConnectionError",{enumerable:!0,get:o(function(){return d.ConnectionError},`get`)}),Object.defineProperty(e,"CancellationReceiverStrategy",{enumerable:!0,get:o(function(){return d.CancellationReceiverStrategy},`get`)}),Object.defineProperty(e,"CancellationSenderStrategy",{enumerable:!0,get:o(function(){return d.CancellationSenderStrategy},`get`)}),Object.defineProperty(e,"CancellationStrategy",{enumerable:!0,get:o(function(){return d.CancellationStrategy},`get`)}),Object.defineProperty(e,"MessageStrategy",{enumerable:!0,get:o(function(){return d.MessageStrategy},`get`)}),e.RAL=gt().default}}),At=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/browser/ril.js"(e){Object.defineProperty(e,"__esModule",{value:!0});var t=kt(),n=class e extends t.AbstractMessageBuffer{static{o(this,`MessageBuffer`)}constructor(e=`utf-8`){super(e),this.asciiDecoder=new TextDecoder(`ascii`)}emptyBuffer(){return e.emptyBuffer}fromString(e,t){return new TextEncoder().encode(e)}toString(e,t){return t===`ascii`?this.asciiDecoder.decode(e):new TextDecoder(t).decode(e)}asNative(e,t){return t===void 0?e:e.slice(0,t)}allocNative(e){return new Uint8Array(e)}};n.emptyBuffer=new Uint8Array;var r=class{static{o(this,`ReadableStreamWrapper`)}constructor(e){this.socket=e,this._onData=new t.Emitter,this._messageListener=e=>{e.data.arrayBuffer().then(e=>{this._onData.fire(new Uint8Array(e))},()=>{(0,t.RAL)().console.error(`Converting blob to array buffer failed.`)})},this.socket.addEventListener(`message`,this._messageListener)}onClose(e){return this.socket.addEventListener(`close`,e),t.Disposable.create(()=>this.socket.removeEventListener(`close`,e))}onError(e){return this.socket.addEventListener(`error`,e),t.Disposable.create(()=>this.socket.removeEventListener(`error`,e))}onEnd(e){return this.socket.addEventListener(`end`,e),t.Disposable.create(()=>this.socket.removeEventListener(`end`,e))}onData(e){return this._onData.event(e)}},i=class{static{o(this,`WritableStreamWrapper`)}constructor(e){this.socket=e}onClose(e){return this.socket.addEventListener(`close`,e),t.Disposable.create(()=>this.socket.removeEventListener(`close`,e))}onError(e){return this.socket.addEventListener(`error`,e),t.Disposable.create(()=>this.socket.removeEventListener(`error`,e))}onEnd(e){return this.socket.addEventListener(`end`,e),t.Disposable.create(()=>this.socket.removeEventListener(`end`,e))}write(e,t){if(typeof e==`string`){if(t!==void 0&&t!==`utf-8`)throw Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${t}`);this.socket.send(e)}else this.socket.send(e);return Promise.resolve()}end(){this.socket.close()}},a=new TextEncoder,s=Object.freeze({messageBuffer:Object.freeze({create:o(e=>new n(e),`create`)}),applicationJson:Object.freeze({encoder:Object.freeze({name:`application/json`,encode:o((e,t)=>{if(t.charset!==`utf-8`)throw Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${t.charset}`);return Promise.resolve(a.encode(JSON.stringify(e,void 0,0)))},`encode`)}),decoder:Object.freeze({name:`application/json`,decode:o((e,t)=>{if(!(e instanceof Uint8Array))throw Error(`In a Browser environments only Uint8Arrays are supported.`);return Promise.resolve(JSON.parse(new TextDecoder(t.charset).decode(e)))},`decode`)})}),stream:Object.freeze({asReadableStream:o(e=>new r(e),`asReadableStream`),asWritableStream:o(e=>new i(e),`asWritableStream`)}),console,timer:Object.freeze({setTimeout(e,t,...n){let r=setTimeout(e,t,...n);return{dispose:o(()=>clearTimeout(r),`dispose`)}},setImmediate(e,...t){let n=setTimeout(e,0,...t);return{dispose:o(()=>clearTimeout(n),`dispose`)}},setInterval(e,t,...n){let r=setInterval(e,t,...n);return{dispose:o(()=>clearInterval(r),`dispose`)}}})});function c(){return s}o(c,`RIL`),(function(e){function n(){t.RAL.install(s)}o(n,`install`),e.install=n})(c||={}),e.default=c}}),jt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/browser/main.js"(e){var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return t[n]},`get`)}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.createMessageConnection=e.BrowserMessageWriter=e.BrowserMessageReader=void 0,At().default.install();var r=kt();n(kt(),e),e.BrowserMessageReader=class extends r.AbstractMessageReader{static{o(this,`BrowserMessageReader`)}constructor(e){super(),this._onData=new r.Emitter,this._messageListener=e=>{this._onData.fire(e.data)},e.addEventListener(`error`,e=>this.fireError(e)),e.onmessage=this._messageListener}listen(e){return this._onData.event(e)}},e.BrowserMessageWriter=class extends r.AbstractMessageWriter{static{o(this,`BrowserMessageWriter`)}constructor(e){super(),this.port=e,this.errorCount=0,e.addEventListener(`error`,e=>this.fireError(e))}write(e){try{return this.port.postMessage(e),Promise.resolve()}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}};function i(e,t,n,i){return n===void 0&&(n=r.NullLogger),r.ConnectionStrategy.is(i)&&(i={connectionStrategy:i}),(0,r.createMessageConnection)(e,t,n,i)}o(i,`createMessageConnection`),e.createMessageConnection=i}}),Mt=c({"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/browser.js"(e,t){t.exports=jt()}}),j=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/messages.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ProtocolNotificationType=e.ProtocolNotificationType0=e.ProtocolRequestType=e.ProtocolRequestType0=e.RegistrationType=e.MessageDirection=void 0;var t=jt(),n;(function(e){e.clientToServer=`clientToServer`,e.serverToClient=`serverToClient`,e.both=`both`})(n||(e.MessageDirection=n={})),e.RegistrationType=class{static{o(this,`RegistrationType`)}constructor(e){this.method=e}},e.ProtocolRequestType0=class extends t.RequestType0{static{o(this,`ProtocolRequestType0`)}constructor(e){super(e)}},e.ProtocolRequestType=class extends t.RequestType{static{o(this,`ProtocolRequestType`)}constructor(e){super(e,t.ParameterStructures.byName)}},e.ProtocolNotificationType0=class extends t.NotificationType0{static{o(this,`ProtocolNotificationType0`)}constructor(e){super(e)}},e.ProtocolNotificationType=class extends t.NotificationType{static{o(this,`ProtocolNotificationType`)}constructor(e){super(e,t.ParameterStructures.byName)}}}}),Nt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/utils/is.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.objectLiteral=e.typedArray=e.stringArray=e.array=e.func=e.error=e.number=e.string=e.boolean=void 0;function t(e){return e===!0||e===!1}o(t,`boolean`),e.boolean=t;function n(e){return typeof e==`string`||e instanceof String}o(n,`string`),e.string=n;function r(e){return typeof e==`number`||e instanceof Number}o(r,`number`),e.number=r;function i(e){return e instanceof Error}o(i,`error`),e.error=i;function a(e){return typeof e==`function`}o(a,`func`),e.func=a;function s(e){return Array.isArray(e)}o(s,`array`),e.array=s;function c(e){return s(e)&&e.every(e=>n(e))}o(c,`stringArray`),e.stringArray=c;function l(e,t){return Array.isArray(e)&&e.every(t)}o(l,`typedArray`),e.typedArray=l;function u(e){return typeof e==`object`&&!!e}o(u,`objectLiteral`),e.objectLiteral=u}}),Pt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ImplementationRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/implementation`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.ImplementationRequest=n={}))}}),Ft=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.TypeDefinitionRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/typeDefinition`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.TypeDefinitionRequest=n={}))}}),It=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolder.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DidChangeWorkspaceFoldersNotification=e.WorkspaceFoldersRequest=void 0;var t=j(),n;(function(e){e.method=`workspace/workspaceFolders`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType0(e.method)})(n||(e.WorkspaceFoldersRequest=n={}));var r;(function(e){e.method=`workspace/didChangeWorkspaceFolders`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(r||(e.DidChangeWorkspaceFoldersNotification=r={}))}}),Lt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConfigurationRequest=void 0;var t=j(),n;(function(e){e.method=`workspace/configuration`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType(e.method)})(n||(e.ConfigurationRequest=n={}))}}),Rt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ColorPresentationRequest=e.DocumentColorRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/documentColor`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.DocumentColorRequest=n={}));var r;(function(e){e.method=`textDocument/colorPresentation`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(r||(e.ColorPresentationRequest=r={}))}}),zt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.FoldingRangeRefreshRequest=e.FoldingRangeRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/foldingRange`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.FoldingRangeRequest=n={}));var r;(function(e){e.method=`workspace/foldingRange/refresh`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType0(e.method)})(r||(e.FoldingRangeRefreshRequest=r={}))}}),Bt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DeclarationRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/declaration`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.DeclarationRequest=n={}))}}),Vt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.SelectionRangeRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/selectionRange`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.SelectionRangeRequest=n={}))}}),Ht=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WorkDoneProgressCancelNotification=e.WorkDoneProgressCreateRequest=e.WorkDoneProgress=void 0;var t=jt(),n=j(),r;(function(e){e.type=new t.ProgressType;function n(t){return t===e.type}o(n,`is`),e.is=n})(r||(e.WorkDoneProgress=r={}));var i;(function(e){e.method=`window/workDoneProgress/create`,e.messageDirection=n.MessageDirection.serverToClient,e.type=new n.ProtocolRequestType(e.method)})(i||(e.WorkDoneProgressCreateRequest=i={}));var a;(function(e){e.method=`window/workDoneProgress/cancel`,e.messageDirection=n.MessageDirection.clientToServer,e.type=new n.ProtocolNotificationType(e.method)})(a||(e.WorkDoneProgressCancelNotification=a={}))}}),Ut=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CallHierarchyOutgoingCallsRequest=e.CallHierarchyIncomingCallsRequest=e.CallHierarchyPrepareRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/prepareCallHierarchy`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.CallHierarchyPrepareRequest=n={}));var r;(function(e){e.method=`callHierarchy/incomingCalls`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(r||(e.CallHierarchyIncomingCallsRequest=r={}));var i;(function(e){e.method=`callHierarchy/outgoingCalls`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(i||(e.CallHierarchyOutgoingCallsRequest=i={}))}}),Wt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.SemanticTokensRefreshRequest=e.SemanticTokensRangeRequest=e.SemanticTokensDeltaRequest=e.SemanticTokensRequest=e.SemanticTokensRegistrationType=e.TokenFormat=void 0;var t=j(),n;(function(e){e.Relative=`relative`})(n||(e.TokenFormat=n={}));var r;(function(e){e.method=`textDocument/semanticTokens`,e.type=new t.RegistrationType(e.method)})(r||(e.SemanticTokensRegistrationType=r={}));var i;(function(e){e.method=`textDocument/semanticTokens/full`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method),e.registrationMethod=r.method})(i||(e.SemanticTokensRequest=i={}));var a;(function(e){e.method=`textDocument/semanticTokens/full/delta`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method),e.registrationMethod=r.method})(a||(e.SemanticTokensDeltaRequest=a={}));var o;(function(e){e.method=`textDocument/semanticTokens/range`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method),e.registrationMethod=r.method})(o||(e.SemanticTokensRangeRequest=o={}));var s;(function(e){e.method=`workspace/semanticTokens/refresh`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType0(e.method)})(s||(e.SemanticTokensRefreshRequest=s={}))}}),Gt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ShowDocumentRequest=void 0;var t=j(),n;(function(e){e.method=`window/showDocument`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType(e.method)})(n||(e.ShowDocumentRequest=n={}))}}),Kt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.LinkedEditingRangeRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/linkedEditingRange`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.LinkedEditingRangeRequest=n={}))}}),qt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.WillDeleteFilesRequest=e.DidDeleteFilesNotification=e.DidRenameFilesNotification=e.WillRenameFilesRequest=e.DidCreateFilesNotification=e.WillCreateFilesRequest=e.FileOperationPatternKind=void 0;var t=j(),n;(function(e){e.file=`file`,e.folder=`folder`})(n||(e.FileOperationPatternKind=n={}));var r;(function(e){e.method=`workspace/willCreateFiles`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(r||(e.WillCreateFilesRequest=r={}));var i;(function(e){e.method=`workspace/didCreateFiles`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(i||(e.DidCreateFilesNotification=i={}));var a;(function(e){e.method=`workspace/willRenameFiles`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(a||(e.WillRenameFilesRequest=a={}));var o;(function(e){e.method=`workspace/didRenameFiles`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(o||(e.DidRenameFilesNotification=o={}));var s;(function(e){e.method=`workspace/didDeleteFiles`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(s||(e.DidDeleteFilesNotification=s={}));var c;(function(e){e.method=`workspace/willDeleteFiles`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(c||(e.WillDeleteFilesRequest=c={}))}}),Jt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MonikerRequest=e.MonikerKind=e.UniquenessLevel=void 0;var t=j(),n;(function(e){e.document=`document`,e.project=`project`,e.group=`group`,e.scheme=`scheme`,e.global=`global`})(n||(e.UniquenessLevel=n={}));var r;(function(e){e.$import=`import`,e.$export=`export`,e.local=`local`})(r||(e.MonikerKind=r={}));var i;(function(e){e.method=`textDocument/moniker`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(i||(e.MonikerRequest=i={}))}}),Yt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeHierarchy.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.TypeHierarchySubtypesRequest=e.TypeHierarchySupertypesRequest=e.TypeHierarchyPrepareRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/prepareTypeHierarchy`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.TypeHierarchyPrepareRequest=n={}));var r;(function(e){e.method=`typeHierarchy/supertypes`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(r||(e.TypeHierarchySupertypesRequest=r={}));var i;(function(e){e.method=`typeHierarchy/subtypes`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(i||(e.TypeHierarchySubtypesRequest=i={}))}}),Xt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.InlineValueRefreshRequest=e.InlineValueRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/inlineValue`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.InlineValueRequest=n={}));var r;(function(e){e.method=`workspace/inlineValue/refresh`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType0(e.method)})(r||(e.InlineValueRefreshRequest=r={}))}}),Zt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.InlayHintRefreshRequest=e.InlayHintResolveRequest=e.InlayHintRequest=void 0;var t=j(),n;(function(e){e.method=`textDocument/inlayHint`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(n||(e.InlayHintRequest=n={}));var r;(function(e){e.method=`inlayHint/resolve`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(r||(e.InlayHintResolveRequest=r={}));var i;(function(e){e.method=`workspace/inlayHint/refresh`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType0(e.method)})(i||(e.InlayHintRefreshRequest=i={}))}}),Qt=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.diagnostic.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DiagnosticRefreshRequest=e.WorkspaceDiagnosticRequest=e.DocumentDiagnosticRequest=e.DocumentDiagnosticReportKind=e.DiagnosticServerCancellationData=void 0;var t=jt(),n=Nt(),r=j(),i;(function(e){function t(e){let t=e;return t&&n.boolean(t.retriggerRequest)}o(t,`is`),e.is=t})(i||(e.DiagnosticServerCancellationData=i={}));var a;(function(e){e.Full=`full`,e.Unchanged=`unchanged`})(a||(e.DocumentDiagnosticReportKind=a={}));var s;(function(e){e.method=`textDocument/diagnostic`,e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method),e.partialResult=new t.ProgressType})(s||(e.DocumentDiagnosticRequest=s={}));var c;(function(e){e.method=`workspace/diagnostic`,e.messageDirection=r.MessageDirection.clientToServer,e.type=new r.ProtocolRequestType(e.method),e.partialResult=new t.ProgressType})(c||(e.WorkspaceDiagnosticRequest=c={}));var l;(function(e){e.method=`workspace/diagnostic/refresh`,e.messageDirection=r.MessageDirection.serverToClient,e.type=new r.ProtocolRequestType0(e.method)})(l||(e.DiagnosticRefreshRequest=l={}))}}),$t=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.notebook.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DidCloseNotebookDocumentNotification=e.DidSaveNotebookDocumentNotification=e.DidChangeNotebookDocumentNotification=e.NotebookCellArrayChange=e.DidOpenNotebookDocumentNotification=e.NotebookDocumentSyncRegistrationType=e.NotebookDocument=e.NotebookCell=e.ExecutionSummary=e.NotebookCellKind=void 0;var t=(ht(),p(m)),n=Nt(),r=j(),i;(function(e){e.Markup=1,e.Code=2;function t(e){return e===1||e===2}o(t,`is`),e.is=t})(i||(e.NotebookCellKind=i={}));var a;(function(e){function r(e,t){let n={executionOrder:e};return(t===!0||t===!1)&&(n.success=t),n}o(r,`create`),e.create=r;function i(e){let r=e;return n.objectLiteral(r)&&t.uinteger.is(r.executionOrder)&&(r.success===void 0||n.boolean(r.success))}o(i,`is`),e.is=i;function a(e,t){return e===t?!0:e==null||t==null?!1:e.executionOrder===t.executionOrder&&e.success===t.success}o(a,`equals`),e.equals=a})(a||(e.ExecutionSummary=a={}));var s;(function(e){function r(e,t){return{kind:e,document:t}}o(r,`create`),e.create=r;function s(e){let r=e;return n.objectLiteral(r)&&i.is(r.kind)&&t.DocumentUri.is(r.document)&&(r.metadata===void 0||n.objectLiteral(r.metadata))}o(s,`is`),e.is=s;function c(e,t){let n=new Set;return e.document!==t.document&&n.add(`document`),e.kind!==t.kind&&n.add(`kind`),e.executionSummary!==t.executionSummary&&n.add(`executionSummary`),(e.metadata!==void 0||t.metadata!==void 0)&&!l(e.metadata,t.metadata)&&n.add(`metadata`),(e.executionSummary!==void 0||t.executionSummary!==void 0)&&!a.equals(e.executionSummary,t.executionSummary)&&n.add(`executionSummary`),n}o(c,`diff`),e.diff=c;function l(e,t){if(e===t)return!0;if(e==null||t==null||typeof e!=typeof t||typeof e!=`object`)return!1;let r=Array.isArray(e),i=Array.isArray(t);if(r!==i)return!1;if(r&&i){if(e.length!==t.length)return!1;for(let n=0;n0}o(t,`hasId`),e.hasId=t})(T||(e.StaticRegistrationOptions=T={}));var E;(function(e){function t(e){let t=e;return t&&(t.documentSelector===null||se.is(t.documentSelector))}o(t,`is`),e.is=t})(E||(e.TextDocumentRegistrationOptions=E={}));var D;(function(e){function t(e){let t=e;return r.objectLiteral(t)&&(t.workDoneProgress===void 0||r.boolean(t.workDoneProgress))}o(t,`is`),e.is=t;function n(e){let t=e;return t&&r.boolean(t.workDoneProgress)}o(n,`hasWorkDoneProgress`),e.hasWorkDoneProgress=n})(D||(e.WorkDoneProgressOptions=D={}));var O;(function(e){e.method=`initialize`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(O||(e.InitializeRequest=O={}));var fe;(function(e){e.unknownProtocolVersion=1})(fe||(e.InitializeErrorCodes=fe={}));var k;(function(e){e.method=`initialized`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(k||(e.InitializedNotification=k={}));var pe;(function(e){e.method=`shutdown`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType0(e.method)})(pe||(e.ShutdownRequest=pe={}));var me;(function(e){e.method=`exit`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType0(e.method)})(me||(e.ExitNotification=me={}));var he;(function(e){e.method=`workspace/didChangeConfiguration`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(he||(e.DidChangeConfigurationNotification=he={}));var ge;(function(e){e.Error=1,e.Warning=2,e.Info=3,e.Log=4,e.Debug=5})(ge||(e.MessageType=ge={}));var _e;(function(e){e.method=`window/showMessage`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolNotificationType(e.method)})(_e||(e.ShowMessageNotification=_e={}));var ve;(function(e){e.method=`window/showMessageRequest`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType(e.method)})(ve||(e.ShowMessageRequest=ve={}));var ye;(function(e){e.method=`window/logMessage`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolNotificationType(e.method)})(ye||(e.LogMessageNotification=ye={}));var be;(function(e){e.method=`telemetry/event`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolNotificationType(e.method)})(be||(e.TelemetryEventNotification=be={}));var xe;(function(e){e.None=0,e.Full=1,e.Incremental=2})(xe||(e.TextDocumentSyncKind=xe={}));var Se;(function(e){e.method=`textDocument/didOpen`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(Se||(e.DidOpenTextDocumentNotification=Se={}));var Ce;(function(e){function t(e){let t=e;return t!=null&&typeof t.text==`string`&&t.range!==void 0&&(t.rangeLength===void 0||typeof t.rangeLength==`number`)}o(t,`isIncremental`),e.isIncremental=t;function n(e){let t=e;return t!=null&&typeof t.text==`string`&&t.range===void 0&&t.rangeLength===void 0}o(n,`isFull`),e.isFull=n})(Ce||(e.TextDocumentContentChangeEvent=Ce={}));var we;(function(e){e.method=`textDocument/didChange`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(we||(e.DidChangeTextDocumentNotification=we={}));var Te;(function(e){e.method=`textDocument/didClose`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(Te||(e.DidCloseTextDocumentNotification=Te={}));var Ee;(function(e){e.method=`textDocument/didSave`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(Ee||(e.DidSaveTextDocumentNotification=Ee={}));var De;(function(e){e.Manual=1,e.AfterDelay=2,e.FocusOut=3})(De||(e.TextDocumentSaveReason=De={}));var Oe;(function(e){e.method=`textDocument/willSave`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(Oe||(e.WillSaveTextDocumentNotification=Oe={}));var ke;(function(e){e.method=`textDocument/willSaveWaitUntil`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(ke||(e.WillSaveTextDocumentWaitUntilRequest=ke={}));var Ae;(function(e){e.method=`workspace/didChangeWatchedFiles`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolNotificationType(e.method)})(Ae||(e.DidChangeWatchedFilesNotification=Ae={}));var je;(function(e){e.Created=1,e.Changed=2,e.Deleted=3})(je||(e.FileChangeType=je={}));var Me;(function(e){function t(e){let t=e;return r.objectLiteral(t)&&(n.URI.is(t.baseUri)||n.WorkspaceFolder.is(t.baseUri))&&r.string(t.pattern)}o(t,`is`),e.is=t})(Me||(e.RelativePattern=Me={}));var Ne;(function(e){e.Create=1,e.Change=2,e.Delete=4})(Ne||(e.WatchKind=Ne={}));var Pe;(function(e){e.method=`textDocument/publishDiagnostics`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolNotificationType(e.method)})(Pe||(e.PublishDiagnosticsNotification=Pe={}));var Fe;(function(e){e.Invoked=1,e.TriggerCharacter=2,e.TriggerForIncompleteCompletions=3})(Fe||(e.CompletionTriggerKind=Fe={}));var Ie;(function(e){e.method=`textDocument/completion`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Ie||(e.CompletionRequest=Ie={}));var Le;(function(e){e.method=`completionItem/resolve`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Le||(e.CompletionResolveRequest=Le={}));var Re;(function(e){e.method=`textDocument/hover`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Re||(e.HoverRequest=Re={}));var ze;(function(e){e.Invoked=1,e.TriggerCharacter=2,e.ContentChange=3})(ze||(e.SignatureHelpTriggerKind=ze={}));var Be;(function(e){e.method=`textDocument/signatureHelp`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Be||(e.SignatureHelpRequest=Be={}));var Ve;(function(e){e.method=`textDocument/definition`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Ve||(e.DefinitionRequest=Ve={}));var He;(function(e){e.method=`textDocument/references`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(He||(e.ReferencesRequest=He={}));var Ue;(function(e){e.method=`textDocument/documentHighlight`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Ue||(e.DocumentHighlightRequest=Ue={}));var We;(function(e){e.method=`textDocument/documentSymbol`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(We||(e.DocumentSymbolRequest=We={}));var Ge;(function(e){e.method=`textDocument/codeAction`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Ge||(e.CodeActionRequest=Ge={}));var Ke;(function(e){e.method=`codeAction/resolve`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Ke||(e.CodeActionResolveRequest=Ke={}));var qe;(function(e){e.method=`workspace/symbol`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(qe||(e.WorkspaceSymbolRequest=qe={}));var Je;(function(e){e.method=`workspaceSymbol/resolve`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Je||(e.WorkspaceSymbolResolveRequest=Je={}));var Ye;(function(e){e.method=`textDocument/codeLens`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Ye||(e.CodeLensRequest=Ye={}));var Xe;(function(e){e.method=`codeLens/resolve`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Xe||(e.CodeLensResolveRequest=Xe={}));var Ze;(function(e){e.method=`workspace/codeLens/refresh`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType0(e.method)})(Ze||(e.CodeLensRefreshRequest=Ze={}));var Qe;(function(e){e.method=`textDocument/documentLink`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(Qe||(e.DocumentLinkRequest=Qe={}));var $e;(function(e){e.method=`documentLink/resolve`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})($e||(e.DocumentLinkResolveRequest=$e={}));var et;(function(e){e.method=`textDocument/formatting`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(et||(e.DocumentFormattingRequest=et={}));var tt;(function(e){e.method=`textDocument/rangeFormatting`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(tt||(e.DocumentRangeFormattingRequest=tt={}));var nt;(function(e){e.method=`textDocument/rangesFormatting`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(nt||(e.DocumentRangesFormattingRequest=nt={}));var rt;(function(e){e.method=`textDocument/onTypeFormatting`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(rt||(e.DocumentOnTypeFormattingRequest=rt={}));var it;(function(e){e.Identifier=1})(it||(e.PrepareSupportDefaultBehavior=it={}));var at;(function(e){e.method=`textDocument/rename`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(at||(e.RenameRequest=at={}));var ot;(function(e){e.method=`textDocument/prepareRename`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(ot||(e.PrepareRenameRequest=ot={}));var st;(function(e){e.method=`workspace/executeCommand`,e.messageDirection=t.MessageDirection.clientToServer,e.type=new t.ProtocolRequestType(e.method)})(st||(e.ExecuteCommandRequest=st={}));var ct;(function(e){e.method=`workspace/applyEdit`,e.messageDirection=t.MessageDirection.serverToClient,e.type=new t.ProtocolRequestType(`workspace/applyEdit`)})(ct||(e.ApplyWorkspaceEditRequest=ct={}))}}),nn=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/connection.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createProtocolConnection=void 0;var t=jt();function n(e,n,r,i){return t.ConnectionStrategy.is(i)&&(i={connectionStrategy:i}),(0,t.createMessageConnection)(e,n,r,i)}o(n,`createProtocolConnection`),e.createProtocolConnection=n}}),rn=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/api.js"(e){var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return t[n]},`get`)}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.LSPErrorCodes=e.createProtocolConnection=void 0,n(jt(),e),n((ht(),p(m)),e),n(j(),e),n(tn(),e);var r=nn();Object.defineProperty(e,"createProtocolConnection",{enumerable:!0,get:o(function(){return r.createProtocolConnection},`get`)});var i;(function(e){e.lspReservedErrorRangeStart=-32899,e.RequestFailed=-32803,e.ServerCancelled=-32802,e.ContentModified=-32801,e.RequestCancelled=-32800,e.lspReservedErrorRangeEnd=-32800})(i||(e.LSPErrorCodes=i={}))}}),an=c({"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/browser/main.js"(e){var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:o(function(){return t[n]},`get`)}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.createProtocolConnection=void 0;var r=Mt();n(Mt(),e),n(rn(),e);function i(e,t,n,i){return(0,r.createMessageConnection)(e,t,n,i)}o(i,`createProtocolConnection`),e.createProtocolConnection=i}}),on={};l(on,{AbstractAstReflection:()=>fn,AbstractCstNode:()=>ZA,AbstractLangiumParser:()=>oj,AbstractParserErrorMessageProvider:()=>cj,AbstractThreadedAsyncParser:()=>AN,AstUtils:()=>Cn,BiMap:()=>pM,Cancellation:()=>Z,CompositeCstNodeImpl:()=>$A,ContextCache:()=>xM,CstNodeBuilder:()=>XA,CstUtils:()=>sn,DEFAULT_TOKENIZE_OPTIONS:()=>YM,DONE_RESULT:()=>bn,DatatypeSymbol:()=>nj,DefaultAstNodeDescriptionProvider:()=>RM,DefaultAstNodeLocator:()=>BM,DefaultAsyncParser:()=>kN,DefaultCommentProvider:()=>ON,DefaultConfigurationProvider:()=>HM,DefaultDocumentBuilder:()=>GM,DefaultDocumentValidator:()=>NM,DefaultHydrator:()=>NN,DefaultIndexManager:()=>KM,DefaultJsonSerializer:()=>DM,DefaultLangiumDocumentFactory:()=>aM,DefaultLangiumDocuments:()=>oM,DefaultLangiumProfiler:()=>tP,DefaultLexer:()=>XM,DefaultLexerErrorMessageProvider:()=>JM,DefaultLinker:()=>cM,DefaultNameProvider:()=>uM,DefaultReferenceDescriptionProvider:()=>zM,DefaultReferences:()=>dM,DefaultScopeComputation:()=>mM,DefaultScopeProvider:()=>wM,DefaultServiceRegistry:()=>OM,DefaultTokenBuilder:()=>Fj,DefaultValueConverter:()=>Ij,DefaultWorkspaceLock:()=>MN,DefaultWorkspaceManager:()=>qM,Deferred:()=>Kj,Disposable:()=>WM,DisposableCache:()=>yM,DocumentCache:()=>SM,DocumentState:()=>Q,DocumentValidator:()=>LM,EMPTY_SCOPE:()=>vM,EMPTY_STREAM:()=>yn,EmptyFileSystem:()=>XN,EmptyFileSystemProvider:()=>YN,ErrorWithLocation:()=>ia,GrammarAST:()=>Rn,GrammarUtils:()=>ra,IndentationAwareLexer:()=>qN,IndentationAwareTokenBuilder:()=>KN,JSDocDocumentationProvider:()=>DN,LangiumCompletionParser:()=>uj,LangiumParser:()=>sj,LangiumParserErrorMessageProvider:()=>lj,LeafCstNodeImpl:()=>QA,LexingMode:()=>GN,MapScope:()=>gM,Module:()=>IN,MultiMap:()=>fM,MultiMapScope:()=>_M,OperationCancelled:()=>Uj,ParserWorker:()=>jN,ProfilingTask:()=>nP,Reduction:()=>Sn,RefResolving:()=>sM,RegExpUtils:()=>sa,RootCstNodeImpl:()=>tj,SimpleCache:()=>bM,StreamImpl:()=>gn,StreamScope:()=>hM,TextDocument:()=>Jj,TreeStreamImpl:()=>xn,URI:()=>tM,UriTrie:()=>iM,UriUtils:()=>rM,VALIDATE_EACH_NODE:()=>MM,ValidationCategory:()=>AM,ValidationRegistry:()=>jM,ValueConverter:()=>Lj,WorkspaceCache:()=>CM,assertCondition:()=>oa,assertUnreachable:()=>aa,createCompletionParser:()=>Mj,createDefaultCoreModule:()=>PN,createDefaultSharedCoreModule:()=>FN,createGrammarConfig:()=>_o,createLangiumParser:()=>Nj,createParser:()=>mj,delayNextTick:()=>Rj,diagnosticData:()=>kM,eagerLoad:()=>zN,getDiagnosticRange:()=>PM,indentationBuilderDefaultOptions:()=>WN,inject:()=>LN,interruptAndCheck:()=>Gj,isAstNode:()=>M,isAstNodeDescription:()=>un,isAstNodeWithComment:()=>TM,isCompositeCstNode:()=>pn,isIMultiModeLexerDefinition:()=>QM,isJSDoc:()=>tN,isLeafCstNode:()=>mn,isLinkingError:()=>dn,isMultiReference:()=>ln,isNamed:()=>lM,isOperationCancelled:()=>Wj,isReference:()=>cn,isRootCstNode:()=>hn,isTokenTypeArray:()=>ZM,isTokenTypeDictionary:()=>$M,loadGrammarFromJson:()=>eP,parseJSDoc:()=>eN,prepareLangiumParser:()=>Pj,setInterruptionPeriod:()=>Hj,startCancelableOperation:()=>Vj,stream:()=>N,toDiagnosticData:()=>IM,toDiagnosticSeverity:()=>FM});var sn={};l(sn,{DefaultNameRegexp:()=>Wi,RangeComparison:()=>Vi,compareRange:()=>Hi,findCommentNode:()=>Ki,findDeclarationNodeAtOffset:()=>Gi,findLeafNodeAtOffset:()=>Ji,findLeafNodeBeforeOffset:()=>Yi,flattenCst:()=>Li,getDatatypeNode:()=>Fi,getInteriorNodes:()=>ea,getNextNode:()=>Qi,getPreviousNode:()=>Zi,getStartlineNode:()=>$i,inRange:()=>Ui,isChildNode:()=>Ri,isCommentNode:()=>qi,streamCst:()=>Ii,toDocumentSegment:()=>Bi,tokenToRange:()=>zi});function M(e){return typeof e==`object`&&!!e&&typeof e.$type==`string`}o(M,`isAstNode`);function cn(e){return typeof e==`object`&&!!e&&typeof e.$refText==`string`&&`ref`in e}o(cn,`isReference`);function ln(e){return typeof e==`object`&&!!e&&typeof e.$refText==`string`&&`items`in e}o(ln,`isMultiReference`);function un(e){return typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.type==`string`&&typeof e.path==`string`}o(un,`isAstNodeDescription`);function dn(e){return typeof e==`object`&&!!e&&typeof e.info==`object`&&typeof e.message==`string`}o(dn,`isLinkingError`);var fn=class{static{o(this,`AbstractAstReflection`)}constructor(){this.subtypes={},this.allSubtypes={}}getAllTypes(){return Object.keys(this.types)}getReferenceType(e){let t=this.types[e.container.$type];if(!t)throw Error(`Type ${e.container.$type||`undefined`} not found.`);let n=t.properties[e.property]?.referenceType;if(!n)throw Error(`Property ${e.property||`undefined`} of type ${e.container.$type} is not a reference.`);return n}getTypeMetaData(e){return this.types[e]||{name:e,properties:{},superTypes:[]}}isInstance(e,t){return M(e)&&this.isSubtype(e.$type,t)}isSubtype(e,t){if(e===t)return!0;let n=this.subtypes[e];n||=this.subtypes[e]={};let r=n[t];if(r!==void 0)return r;{let r=this.types[e],i=r?r.superTypes.some(e=>this.isSubtype(e,t)):!1;return n[t]=i,i}}getAllSubTypes(e){let t=this.allSubtypes[e];if(t)return t;{let t=this.getAllTypes(),n=[];for(let r of t)this.isSubtype(r,e)&&n.push(r);return this.allSubtypes[e]=n,n}}};function pn(e){return typeof e==`object`&&!!e&&Array.isArray(e.content)}o(pn,`isCompositeCstNode`);function mn(e){return typeof e==`object`&&!!e&&typeof e.tokenType==`object`}o(mn,`isLeafCstNode`);function hn(e){return pn(e)&&typeof e.fullText==`string`}o(hn,`isRootCstNode`);var gn=class e{static{o(this,`StreamImpl`)}constructor(e,t){this.startFn=e,this.nextFn=t}iterator(){let e={state:this.startFn(),next:o(()=>this.nextFn(e.state),`next`),[Symbol.iterator]:()=>e};return e}[Symbol.iterator](){return this.iterator()}isEmpty(){return!!this.iterator().next().done}count(){let e=this.iterator(),t=0,n=e.next();for(;!n.done;)t++,n=e.next();return t}toArray(){let e=[],t=this.iterator(),n;do n=t.next(),n.value!==void 0&&e.push(n.value);while(!n.done);return e}toSet(){return new Set(this)}toMap(e,t){let n=this.map(n=>[e?e(n):n,t?t(n):n]);return new Map(n)}toString(){return this.join()}concat(t){return new e(()=>({first:this.startFn(),firstDone:!1,iterator:t[Symbol.iterator]()}),e=>{let t;if(!e.firstDone){do if(t=this.nextFn(e.first),!t.done)return t;while(!t.done);e.firstDone=!0}do if(t=e.iterator.next(),!t.done)return t;while(!t.done);return bn})}join(e=`,`){let t=this.iterator(),n=``,r,i=!1;do r=t.next(),r.done||(i&&(n+=e),n+=_n(r.value)),i=!0;while(!r.done);return n}indexOf(e,t=0){let n=this.iterator(),r=0,i=n.next();for(;!i.done;){if(r>=t&&i.value===e)return r;i=n.next(),r++}return-1}every(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(!e(n.value))return!1;n=t.next()}return!0}some(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(e(n.value))return!0;n=t.next()}return!1}forEach(e){let t=this.iterator(),n=0,r=t.next();for(;!r.done;)e(r.value,n),r=t.next(),n++}map(t){return new e(this.startFn,e=>{let{done:n,value:r}=this.nextFn(e);return n?bn:{done:!1,value:t(r)}})}filter(t){return new e(this.startFn,e=>{let n;do if(n=this.nextFn(e),!n.done&&t(n.value))return n;while(!n.done);return bn})}nonNullable(){return this.filter(e=>e!=null)}reduce(e,t){let n=this.iterator(),r=t,i=n.next();for(;!i.done;)r=r===void 0?i.value:e(r,i.value),i=n.next();return r}reduceRight(e,t){return this.recursiveReduce(this.iterator(),e,t)}recursiveReduce(e,t,n){let r=e.next();if(r.done)return n;let i=this.recursiveReduce(e,t,n);return i===void 0?r.value:t(i,r.value)}find(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(e(n.value))return n.value;n=t.next()}}findIndex(e){let t=this.iterator(),n=0,r=t.next();for(;!r.done;){if(e(r.value))return n;r=t.next(),n++}return-1}includes(e){let t=this.iterator(),n=t.next();for(;!n.done;){if(n.value===e)return!0;n=t.next()}return!1}flatMap(t){return new e(()=>({this:this.startFn()}),e=>{do{if(e.iterator){let t=e.iterator.next();if(t.done)e.iterator=void 0;else return t}let{done:n,value:r}=this.nextFn(e.this);if(!n){let n=t(r);if(vn(n))e.iterator=n[Symbol.iterator]();else return{done:!1,value:n}}}while(e.iterator);return bn})}flat(t){if(t===void 0&&(t=1),t<=0)return this;let n=t>1?this.flat(t-1):this;return new e(()=>({this:n.startFn()}),e=>{do{if(e.iterator){let t=e.iterator.next();if(t.done)e.iterator=void 0;else return t}let{done:t,value:r}=n.nextFn(e.this);if(!t)if(vn(r))e.iterator=r[Symbol.iterator]();else return{done:!1,value:r}}while(e.iterator);return bn})}head(){let e=this.iterator().next();if(!e.done)return e.value}tail(t=1){return new e(()=>{let e=this.startFn();for(let n=0;n({size:0,state:this.startFn()}),e=>(e.size++,e.size>t?bn:this.nextFn(e.state)))}distinct(t){return new e(()=>({set:new Set,internalState:this.startFn()}),e=>{let n;do if(n=this.nextFn(e.internalState),!n.done){let r=t?t(n.value):n.value;if(!e.set.has(r))return e.set.add(r),n}while(!n.done);return bn})}exclude(e,t){let n=new Set;for(let r of e){let e=t?t(r):r;n.add(e)}return this.filter(e=>{let r=t?t(e):e;return!n.has(r)})}};function _n(e){return typeof e==`string`?e:e===void 0?`undefined`:typeof e.toString==`function`?e.toString():Object.prototype.toString.call(e)}o(_n,`toString`);function vn(e){return!!e&&typeof e[Symbol.iterator]==`function`}o(vn,`isIterable`);var yn=new gn(()=>void 0,()=>bn),bn=Object.freeze({done:!0,value:void 0});function N(...e){if(e.length===1){let t=e[0];if(t instanceof gn)return t;if(vn(t))return new gn(()=>t[Symbol.iterator](),e=>e.next());if(typeof t.length==`number`)return new gn(()=>({index:0}),e=>e.index1?new gn(()=>({collIndex:0,arrIndex:0}),t=>{do{if(t.iterator){let e=t.iterator.next();if(!e.done)return e;t.iterator=void 0}if(t.array){if(t.arrIndex({iterators:n?.includeRoot?[[e][Symbol.iterator]()]:[t(e)[Symbol.iterator]()],pruned:!1}),e=>{for(e.pruned&&=(e.iterators.pop(),!1);e.iterators.length>0;){let n=e.iterators[e.iterators.length-1].next();if(n.done)e.iterators.pop();else return e.iterators.push(t(n.value)[Symbol.iterator]()),n}return bn})}iterator(){let e={state:this.startFn(),next:o(()=>this.nextFn(e.state),`next`),prune:o(()=>{e.state.pruned=!0},`prune`),[Symbol.iterator]:()=>e};return e}},Sn;(function(e){function t(e){return e.reduce((e,t)=>e+t,0)}o(t,`sum`),e.sum=t;function n(e){return e.reduce((e,t)=>e*t,0)}o(n,`product`),e.product=n;function r(e){return e.reduce((e,t)=>Math.min(e,t))}o(r,`min`),e.min=r;function i(e){return e.reduce((e,t)=>Math.max(e,t))}o(i,`max`),e.max=i})(Sn||={});var Cn={};l(Cn,{assignMandatoryProperties:()=>Fn,copyAstNode:()=>Ln,findRootNode:()=>On,getContainerOfType:()=>Tn,getDocument:()=>Dn,getReferenceNodes:()=>kn,hasContainerOfType:()=>En,linkContentToContainer:()=>wn,streamAllContents:()=>jn,streamAst:()=>Mn,streamContents:()=>An,streamReferences:()=>Pn});function wn(e,t={}){for(let[n,r]of Object.entries(e))n.startsWith(`$`)||(Array.isArray(r)?r.forEach((r,i)=>{M(r)&&(r.$container=e,r.$containerProperty=n,r.$containerIndex=i,t.deep&&wn(r,t))}):M(r)&&(r.$container=e,r.$containerProperty=n,t.deep&&wn(r,t)))}o(wn,`linkContentToContainer`);function Tn(e,t){let n=e;for(;n;){if(t(n))return n;n=n.$container}}o(Tn,`getContainerOfType`);function En(e,t){let n=e;for(;n;){if(t(n))return!0;n=n.$container}return!1}o(En,`hasContainerOfType`);function Dn(e){let t=On(e).$document;if(!t)throw Error(`AST node has no document.`);return t}o(Dn,`getDocument`);function On(e){for(;e.$container;)e=e.$container;return e}o(On,`findRootNode`);function kn(e){return cn(e)?e.ref?[e.ref]:[]:ln(e)?e.items.map(e=>e.ref):[]}o(kn,`getReferenceNodes`);function An(e,t){if(!e)throw Error(`Node must be an AstNode.`);let n=t?.range;return new gn(()=>({keys:Object.keys(e),keyIndex:0,arrayIndex:0}),t=>{for(;t.keyIndexAn(e,t))}o(jn,`streamAllContents`);function Mn(e,t){if(!e)throw Error(`Root node must be an AstNode.`);return t?.range&&!Nn(e,t.range)?new xn(e,()=>[]):new xn(e,e=>An(e,t),{includeRoot:!0})}o(Mn,`streamAst`);function Nn(e,t){if(!t)return!0;let n=e.$cstNode?.range;return n?Ui(n,t):!1}o(Nn,`isAstNodeInRange`);function Pn(e){return new gn(()=>({keys:Object.keys(e),keyIndex:0,arrayIndex:0}),t=>{for(;t.keyIndexBn,AbstractParserRule:()=>Hn,AbstractRule:()=>Wn,AbstractType:()=>Kn,Action:()=>Jn,Alternatives:()=>Xn,ArrayLiteral:()=>Qn,ArrayType:()=>er,Assignment:()=>nr,BooleanLiteral:()=>ir,CharacterRange:()=>or,Condition:()=>cr,Conjunction:()=>ur,CrossReference:()=>fr,Disjunction:()=>mr,EndOfFile:()=>gr,Grammar:()=>vr,GrammarImport:()=>br,Group:()=>Sr,InferredType:()=>wr,InfixRule:()=>Er,InfixRuleOperatorList:()=>Or,InfixRuleOperators:()=>Ar,Interface:()=>Mr,Keyword:()=>Pr,LangiumGrammarAstReflection:()=>Pi,LangiumGrammarTerminals:()=>zn,NamedArgument:()=>Ir,NegatedToken:()=>Rr,Negation:()=>Br,NumberLiteral:()=>Hr,Parameter:()=>Wr,ParameterReference:()=>Kr,ParserRule:()=>Jr,ReferenceType:()=>Xr,RegexToken:()=>Qr,ReturnType:()=>ei,RuleCall:()=>ni,SimpleType:()=>ii,StringLiteral:()=>oi,TerminalAlternatives:()=>ci,TerminalElement:()=>ui,TerminalGroup:()=>fi,TerminalRule:()=>mi,TerminalRuleCall:()=>gi,Type:()=>vi,TypeAttribute:()=>bi,TypeDefinition:()=>Si,UnionType:()=>wi,UnorderedGroup:()=>Ei,UntilToken:()=>Oi,ValueLiteral:()=>Ai,Wildcard:()=>Mi,isAbstractElement:()=>Vn,isAbstractParserRule:()=>Un,isAbstractRule:()=>Gn,isAbstractType:()=>qn,isAction:()=>Yn,isAlternatives:()=>Zn,isArrayLiteral:()=>$n,isArrayType:()=>tr,isAssignment:()=>rr,isBooleanLiteral:()=>ar,isCharacterRange:()=>sr,isCondition:()=>lr,isConjunction:()=>dr,isCrossReference:()=>pr,isDisjunction:()=>hr,isEndOfFile:()=>_r,isGrammar:()=>yr,isGrammarImport:()=>xr,isGroup:()=>Cr,isInferredType:()=>Tr,isInfixRule:()=>Dr,isInfixRuleOperatorList:()=>kr,isInfixRuleOperators:()=>jr,isInterface:()=>Nr,isKeyword:()=>Fr,isNamedArgument:()=>Lr,isNegatedToken:()=>zr,isNegation:()=>Vr,isNumberLiteral:()=>Ur,isParameter:()=>Gr,isParameterReference:()=>qr,isParserRule:()=>Yr,isReferenceType:()=>Zr,isRegexToken:()=>$r,isReturnType:()=>ti,isRuleCall:()=>ri,isSimpleType:()=>ai,isStringLiteral:()=>si,isTerminalAlternatives:()=>li,isTerminalElement:()=>di,isTerminalGroup:()=>pi,isTerminalRule:()=>hi,isTerminalRuleCall:()=>_i,isType:()=>yi,isTypeAttribute:()=>xi,isTypeDefinition:()=>Ci,isUnionType:()=>Ti,isUnorderedGroup:()=>Di,isUntilToken:()=>ki,isValueLiteral:()=>ji,isWildcard:()=>Ni,reflection:()=>P});var zn={ID:/\^?[_a-zA-Z][\w_]*/,STRING:/"(\\.|[^"\\])*"|'(\\.|[^'\\])*'/,NUMBER:/NaN|-?((\d*\.\d+|\d+)([Ee][+-]?\d+)?|Infinity)/,RegexLiteral:/\/(?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+\/[a-z]*/,WS:/\s+/,ML_COMMENT:/\/\*[\s\S]*?\*\//,SL_COMMENT:/\/\/[^\n\r]*/},Bn={$type:`AbstractElement`,cardinality:`cardinality`};function Vn(e){return P.isInstance(e,Bn.$type)}o(Vn,`isAbstractElement`);var Hn={$type:`AbstractParserRule`};function Un(e){return P.isInstance(e,Hn.$type)}o(Un,`isAbstractParserRule`);var Wn={$type:`AbstractRule`};function Gn(e){return P.isInstance(e,Wn.$type)}o(Gn,`isAbstractRule`);var Kn={$type:`AbstractType`};function qn(e){return P.isInstance(e,Kn.$type)}o(qn,`isAbstractType`);var Jn={$type:`Action`,cardinality:`cardinality`,feature:`feature`,inferredType:`inferredType`,operator:`operator`,type:`type`};function Yn(e){return P.isInstance(e,Jn.$type)}o(Yn,`isAction`);var Xn={$type:`Alternatives`,cardinality:`cardinality`,elements:`elements`};function Zn(e){return P.isInstance(e,Xn.$type)}o(Zn,`isAlternatives`);var Qn={$type:`ArrayLiteral`,elements:`elements`};function $n(e){return P.isInstance(e,Qn.$type)}o($n,`isArrayLiteral`);var er={$type:`ArrayType`,elementType:`elementType`};function tr(e){return P.isInstance(e,er.$type)}o(tr,`isArrayType`);var nr={$type:`Assignment`,cardinality:`cardinality`,feature:`feature`,operator:`operator`,predicate:`predicate`,terminal:`terminal`};function rr(e){return P.isInstance(e,nr.$type)}o(rr,`isAssignment`);var ir={$type:`BooleanLiteral`,true:`true`};function ar(e){return P.isInstance(e,ir.$type)}o(ar,`isBooleanLiteral`);var or={$type:`CharacterRange`,cardinality:`cardinality`,left:`left`,lookahead:`lookahead`,parenthesized:`parenthesized`,right:`right`};function sr(e){return P.isInstance(e,or.$type)}o(sr,`isCharacterRange`);var cr={$type:`Condition`};function lr(e){return P.isInstance(e,cr.$type)}o(lr,`isCondition`);var ur={$type:`Conjunction`,left:`left`,right:`right`};function dr(e){return P.isInstance(e,ur.$type)}o(dr,`isConjunction`);var fr={$type:`CrossReference`,cardinality:`cardinality`,deprecatedSyntax:`deprecatedSyntax`,isMulti:`isMulti`,terminal:`terminal`,type:`type`};function pr(e){return P.isInstance(e,fr.$type)}o(pr,`isCrossReference`);var mr={$type:`Disjunction`,left:`left`,right:`right`};function hr(e){return P.isInstance(e,mr.$type)}o(hr,`isDisjunction`);var gr={$type:`EndOfFile`,cardinality:`cardinality`};function _r(e){return P.isInstance(e,gr.$type)}o(_r,`isEndOfFile`);var vr={$type:`Grammar`,imports:`imports`,interfaces:`interfaces`,isDeclared:`isDeclared`,name:`name`,rules:`rules`,types:`types`};function yr(e){return P.isInstance(e,vr.$type)}o(yr,`isGrammar`);var br={$type:`GrammarImport`,path:`path`};function xr(e){return P.isInstance(e,br.$type)}o(xr,`isGrammarImport`);var Sr={$type:`Group`,cardinality:`cardinality`,elements:`elements`,guardCondition:`guardCondition`,predicate:`predicate`};function Cr(e){return P.isInstance(e,Sr.$type)}o(Cr,`isGroup`);var wr={$type:`InferredType`,name:`name`};function Tr(e){return P.isInstance(e,wr.$type)}o(Tr,`isInferredType`);var Er={$type:`InfixRule`,call:`call`,dataType:`dataType`,inferredType:`inferredType`,name:`name`,operators:`operators`,parameters:`parameters`,returnType:`returnType`};function Dr(e){return P.isInstance(e,Er.$type)}o(Dr,`isInfixRule`);var Or={$type:`InfixRuleOperatorList`,associativity:`associativity`,operators:`operators`};function kr(e){return P.isInstance(e,Or.$type)}o(kr,`isInfixRuleOperatorList`);var Ar={$type:`InfixRuleOperators`,precedences:`precedences`};function jr(e){return P.isInstance(e,Ar.$type)}o(jr,`isInfixRuleOperators`);var Mr={$type:`Interface`,attributes:`attributes`,name:`name`,superTypes:`superTypes`};function Nr(e){return P.isInstance(e,Mr.$type)}o(Nr,`isInterface`);var Pr={$type:`Keyword`,cardinality:`cardinality`,predicate:`predicate`,value:`value`};function Fr(e){return P.isInstance(e,Pr.$type)}o(Fr,`isKeyword`);var Ir={$type:`NamedArgument`,calledByName:`calledByName`,parameter:`parameter`,value:`value`};function Lr(e){return P.isInstance(e,Ir.$type)}o(Lr,`isNamedArgument`);var Rr={$type:`NegatedToken`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`,terminal:`terminal`};function zr(e){return P.isInstance(e,Rr.$type)}o(zr,`isNegatedToken`);var Br={$type:`Negation`,value:`value`};function Vr(e){return P.isInstance(e,Br.$type)}o(Vr,`isNegation`);var Hr={$type:`NumberLiteral`,value:`value`};function Ur(e){return P.isInstance(e,Hr.$type)}o(Ur,`isNumberLiteral`);var Wr={$type:`Parameter`,name:`name`};function Gr(e){return P.isInstance(e,Wr.$type)}o(Gr,`isParameter`);var Kr={$type:`ParameterReference`,parameter:`parameter`};function qr(e){return P.isInstance(e,Kr.$type)}o(qr,`isParameterReference`);var Jr={$type:`ParserRule`,dataType:`dataType`,definition:`definition`,entry:`entry`,fragment:`fragment`,inferredType:`inferredType`,name:`name`,parameters:`parameters`,returnType:`returnType`};function Yr(e){return P.isInstance(e,Jr.$type)}o(Yr,`isParserRule`);var Xr={$type:`ReferenceType`,isMulti:`isMulti`,referenceType:`referenceType`};function Zr(e){return P.isInstance(e,Xr.$type)}o(Zr,`isReferenceType`);var Qr={$type:`RegexToken`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`,regex:`regex`};function $r(e){return P.isInstance(e,Qr.$type)}o($r,`isRegexToken`);var ei={$type:`ReturnType`,name:`name`};function ti(e){return P.isInstance(e,ei.$type)}o(ti,`isReturnType`);var ni={$type:`RuleCall`,arguments:`arguments`,cardinality:`cardinality`,predicate:`predicate`,rule:`rule`};function ri(e){return P.isInstance(e,ni.$type)}o(ri,`isRuleCall`);var ii={$type:`SimpleType`,primitiveType:`primitiveType`,stringType:`stringType`,typeRef:`typeRef`};function ai(e){return P.isInstance(e,ii.$type)}o(ai,`isSimpleType`);var oi={$type:`StringLiteral`,value:`value`};function si(e){return P.isInstance(e,oi.$type)}o(si,`isStringLiteral`);var ci={$type:`TerminalAlternatives`,cardinality:`cardinality`,elements:`elements`,lookahead:`lookahead`,parenthesized:`parenthesized`};function li(e){return P.isInstance(e,ci.$type)}o(li,`isTerminalAlternatives`);var ui={$type:`TerminalElement`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`};function di(e){return P.isInstance(e,ui.$type)}o(di,`isTerminalElement`);var fi={$type:`TerminalGroup`,cardinality:`cardinality`,elements:`elements`,lookahead:`lookahead`,parenthesized:`parenthesized`};function pi(e){return P.isInstance(e,fi.$type)}o(pi,`isTerminalGroup`);var mi={$type:`TerminalRule`,definition:`definition`,fragment:`fragment`,hidden:`hidden`,name:`name`,type:`type`};function hi(e){return P.isInstance(e,mi.$type)}o(hi,`isTerminalRule`);var gi={$type:`TerminalRuleCall`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`,rule:`rule`};function _i(e){return P.isInstance(e,gi.$type)}o(_i,`isTerminalRuleCall`);var vi={$type:`Type`,name:`name`,type:`type`};function yi(e){return P.isInstance(e,vi.$type)}o(yi,`isType`);var bi={$type:`TypeAttribute`,defaultValue:`defaultValue`,isOptional:`isOptional`,name:`name`,type:`type`};function xi(e){return P.isInstance(e,bi.$type)}o(xi,`isTypeAttribute`);var Si={$type:`TypeDefinition`};function Ci(e){return P.isInstance(e,Si.$type)}o(Ci,`isTypeDefinition`);var wi={$type:`UnionType`,types:`types`};function Ti(e){return P.isInstance(e,wi.$type)}o(Ti,`isUnionType`);var Ei={$type:`UnorderedGroup`,cardinality:`cardinality`,elements:`elements`};function Di(e){return P.isInstance(e,Ei.$type)}o(Di,`isUnorderedGroup`);var Oi={$type:`UntilToken`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`,terminal:`terminal`};function ki(e){return P.isInstance(e,Oi.$type)}o(ki,`isUntilToken`);var Ai={$type:`ValueLiteral`};function ji(e){return P.isInstance(e,Ai.$type)}o(ji,`isValueLiteral`);var Mi={$type:`Wildcard`,cardinality:`cardinality`,lookahead:`lookahead`,parenthesized:`parenthesized`};function Ni(e){return P.isInstance(e,Mi.$type)}o(Ni,`isWildcard`);var Pi=class extends fn{static{o(this,`LangiumGrammarAstReflection`)}constructor(){super(...arguments),this.types={AbstractElement:{name:Bn.$type,properties:{cardinality:{name:Bn.cardinality}},superTypes:[]},AbstractParserRule:{name:Hn.$type,properties:{},superTypes:[Wn.$type,Kn.$type]},AbstractRule:{name:Wn.$type,properties:{},superTypes:[]},AbstractType:{name:Kn.$type,properties:{},superTypes:[]},Action:{name:Jn.$type,properties:{cardinality:{name:Jn.cardinality},feature:{name:Jn.feature},inferredType:{name:Jn.inferredType},operator:{name:Jn.operator},type:{name:Jn.type,referenceType:Kn.$type}},superTypes:[Bn.$type]},Alternatives:{name:Xn.$type,properties:{cardinality:{name:Xn.cardinality},elements:{name:Xn.elements,defaultValue:[]}},superTypes:[Bn.$type]},ArrayLiteral:{name:Qn.$type,properties:{elements:{name:Qn.elements,defaultValue:[]}},superTypes:[Ai.$type]},ArrayType:{name:er.$type,properties:{elementType:{name:er.elementType}},superTypes:[Si.$type]},Assignment:{name:nr.$type,properties:{cardinality:{name:nr.cardinality},feature:{name:nr.feature},operator:{name:nr.operator},predicate:{name:nr.predicate},terminal:{name:nr.terminal}},superTypes:[Bn.$type]},BooleanLiteral:{name:ir.$type,properties:{true:{name:ir.true,defaultValue:!1}},superTypes:[cr.$type,Ai.$type]},CharacterRange:{name:or.$type,properties:{cardinality:{name:or.cardinality},left:{name:or.left},lookahead:{name:or.lookahead},parenthesized:{name:or.parenthesized,defaultValue:!1},right:{name:or.right}},superTypes:[ui.$type]},Condition:{name:cr.$type,properties:{},superTypes:[]},Conjunction:{name:ur.$type,properties:{left:{name:ur.left},right:{name:ur.right}},superTypes:[cr.$type]},CrossReference:{name:fr.$type,properties:{cardinality:{name:fr.cardinality},deprecatedSyntax:{name:fr.deprecatedSyntax,defaultValue:!1},isMulti:{name:fr.isMulti,defaultValue:!1},terminal:{name:fr.terminal},type:{name:fr.type,referenceType:Kn.$type}},superTypes:[Bn.$type]},Disjunction:{name:mr.$type,properties:{left:{name:mr.left},right:{name:mr.right}},superTypes:[cr.$type]},EndOfFile:{name:gr.$type,properties:{cardinality:{name:gr.cardinality}},superTypes:[Bn.$type]},Grammar:{name:vr.$type,properties:{imports:{name:vr.imports,defaultValue:[]},interfaces:{name:vr.interfaces,defaultValue:[]},isDeclared:{name:vr.isDeclared,defaultValue:!1},name:{name:vr.name},rules:{name:vr.rules,defaultValue:[]},types:{name:vr.types,defaultValue:[]}},superTypes:[]},GrammarImport:{name:br.$type,properties:{path:{name:br.path}},superTypes:[]},Group:{name:Sr.$type,properties:{cardinality:{name:Sr.cardinality},elements:{name:Sr.elements,defaultValue:[]},guardCondition:{name:Sr.guardCondition},predicate:{name:Sr.predicate}},superTypes:[Bn.$type]},InferredType:{name:wr.$type,properties:{name:{name:wr.name}},superTypes:[Kn.$type]},InfixRule:{name:Er.$type,properties:{call:{name:Er.call},dataType:{name:Er.dataType},inferredType:{name:Er.inferredType},name:{name:Er.name},operators:{name:Er.operators},parameters:{name:Er.parameters,defaultValue:[]},returnType:{name:Er.returnType,referenceType:Kn.$type}},superTypes:[Hn.$type]},InfixRuleOperatorList:{name:Or.$type,properties:{associativity:{name:Or.associativity},operators:{name:Or.operators,defaultValue:[]}},superTypes:[]},InfixRuleOperators:{name:Ar.$type,properties:{precedences:{name:Ar.precedences,defaultValue:[]}},superTypes:[]},Interface:{name:Mr.$type,properties:{attributes:{name:Mr.attributes,defaultValue:[]},name:{name:Mr.name},superTypes:{name:Mr.superTypes,defaultValue:[],referenceType:Kn.$type}},superTypes:[Kn.$type]},Keyword:{name:Pr.$type,properties:{cardinality:{name:Pr.cardinality},predicate:{name:Pr.predicate},value:{name:Pr.value}},superTypes:[Bn.$type]},NamedArgument:{name:Ir.$type,properties:{calledByName:{name:Ir.calledByName,defaultValue:!1},parameter:{name:Ir.parameter,referenceType:Wr.$type},value:{name:Ir.value}},superTypes:[]},NegatedToken:{name:Rr.$type,properties:{cardinality:{name:Rr.cardinality},lookahead:{name:Rr.lookahead},parenthesized:{name:Rr.parenthesized,defaultValue:!1},terminal:{name:Rr.terminal}},superTypes:[ui.$type]},Negation:{name:Br.$type,properties:{value:{name:Br.value}},superTypes:[cr.$type]},NumberLiteral:{name:Hr.$type,properties:{value:{name:Hr.value}},superTypes:[Ai.$type]},Parameter:{name:Wr.$type,properties:{name:{name:Wr.name}},superTypes:[]},ParameterReference:{name:Kr.$type,properties:{parameter:{name:Kr.parameter,referenceType:Wr.$type}},superTypes:[cr.$type]},ParserRule:{name:Jr.$type,properties:{dataType:{name:Jr.dataType},definition:{name:Jr.definition},entry:{name:Jr.entry,defaultValue:!1},fragment:{name:Jr.fragment,defaultValue:!1},inferredType:{name:Jr.inferredType},name:{name:Jr.name},parameters:{name:Jr.parameters,defaultValue:[]},returnType:{name:Jr.returnType,referenceType:Kn.$type}},superTypes:[Hn.$type]},ReferenceType:{name:Xr.$type,properties:{isMulti:{name:Xr.isMulti,defaultValue:!1},referenceType:{name:Xr.referenceType}},superTypes:[Si.$type]},RegexToken:{name:Qr.$type,properties:{cardinality:{name:Qr.cardinality},lookahead:{name:Qr.lookahead},parenthesized:{name:Qr.parenthesized,defaultValue:!1},regex:{name:Qr.regex}},superTypes:[ui.$type]},ReturnType:{name:ei.$type,properties:{name:{name:ei.name}},superTypes:[]},RuleCall:{name:ni.$type,properties:{arguments:{name:ni.arguments,defaultValue:[]},cardinality:{name:ni.cardinality},predicate:{name:ni.predicate},rule:{name:ni.rule,referenceType:Wn.$type}},superTypes:[Bn.$type]},SimpleType:{name:ii.$type,properties:{primitiveType:{name:ii.primitiveType},stringType:{name:ii.stringType},typeRef:{name:ii.typeRef,referenceType:Kn.$type}},superTypes:[Si.$type]},StringLiteral:{name:oi.$type,properties:{value:{name:oi.value}},superTypes:[Ai.$type]},TerminalAlternatives:{name:ci.$type,properties:{cardinality:{name:ci.cardinality},elements:{name:ci.elements,defaultValue:[]},lookahead:{name:ci.lookahead},parenthesized:{name:ci.parenthesized,defaultValue:!1}},superTypes:[ui.$type]},TerminalElement:{name:ui.$type,properties:{cardinality:{name:ui.cardinality},lookahead:{name:ui.lookahead},parenthesized:{name:ui.parenthesized,defaultValue:!1}},superTypes:[Bn.$type]},TerminalGroup:{name:fi.$type,properties:{cardinality:{name:fi.cardinality},elements:{name:fi.elements,defaultValue:[]},lookahead:{name:fi.lookahead},parenthesized:{name:fi.parenthesized,defaultValue:!1}},superTypes:[ui.$type]},TerminalRule:{name:mi.$type,properties:{definition:{name:mi.definition},fragment:{name:mi.fragment,defaultValue:!1},hidden:{name:mi.hidden,defaultValue:!1},name:{name:mi.name},type:{name:mi.type}},superTypes:[Wn.$type]},TerminalRuleCall:{name:gi.$type,properties:{cardinality:{name:gi.cardinality},lookahead:{name:gi.lookahead},parenthesized:{name:gi.parenthesized,defaultValue:!1},rule:{name:gi.rule,referenceType:mi.$type}},superTypes:[ui.$type]},Type:{name:vi.$type,properties:{name:{name:vi.name},type:{name:vi.type}},superTypes:[Kn.$type]},TypeAttribute:{name:bi.$type,properties:{defaultValue:{name:bi.defaultValue},isOptional:{name:bi.isOptional,defaultValue:!1},name:{name:bi.name},type:{name:bi.type}},superTypes:[]},TypeDefinition:{name:Si.$type,properties:{},superTypes:[]},UnionType:{name:wi.$type,properties:{types:{name:wi.types,defaultValue:[]}},superTypes:[Si.$type]},UnorderedGroup:{name:Ei.$type,properties:{cardinality:{name:Ei.cardinality},elements:{name:Ei.elements,defaultValue:[]}},superTypes:[Bn.$type]},UntilToken:{name:Oi.$type,properties:{cardinality:{name:Oi.cardinality},lookahead:{name:Oi.lookahead},parenthesized:{name:Oi.parenthesized,defaultValue:!1},terminal:{name:Oi.terminal}},superTypes:[ui.$type]},ValueLiteral:{name:Ai.$type,properties:{},superTypes:[]},Wildcard:{name:Mi.$type,properties:{cardinality:{name:Mi.cardinality},lookahead:{name:Mi.lookahead},parenthesized:{name:Mi.parenthesized,defaultValue:!1}},superTypes:[ui.$type]}}}},P=new Pi;function Fi(e){let t=e,n=!1;for(;t;){let e=Tn(t.grammarSource,Yr);if(e&&e.dataType)t=t.container,n=!0;else if(n)return t;else return}}o(Fi,`getDatatypeNode`);function Ii(e){return new xn(e,e=>pn(e)?e.content:[],{includeRoot:!0})}o(Ii,`streamCst`);function Li(e){return Ii(e).filter(mn)}o(Li,`flattenCst`);function Ri(e,t){for(;e.container;)if(e=e.container,e===t)return!0;return!1}o(Ri,`isChildNode`);function zi(e){return{start:{character:e.startColumn-1,line:e.startLine-1},end:{character:e.endColumn,line:e.endLine-1}}}o(zi,`tokenToRange`);function Bi(e){if(!e)return;let{offset:t,end:n,range:r}=e;return{range:r,offset:t,end:n,length:n-t}}o(Bi,`toDocumentSegment`);var Vi;(function(e){e[e.Before=0]=`Before`,e[e.After=1]=`After`,e[e.OverlapFront=2]=`OverlapFront`,e[e.OverlapBack=3]=`OverlapBack`,e[e.Inside=4]=`Inside`,e[e.Outside=5]=`Outside`})(Vi||={});function Hi(e,t){if(e.end.linet.end.line||e.start.line===t.end.line&&e.start.character>=t.end.character)return Vi.After;let n=e.start.line>t.start.line||e.start.line===t.start.line&&e.start.character>=t.start.character,r=e.end.lineVi.After}o(Ui,`inRange`);var Wi=/^[\w\p{L}]$/u;function Gi(e,t,n=Wi){if(e){if(t>0){let r=t-e.offset,i=e.text.charAt(r);n.test(i)||t--}return Ji(e,t)}}o(Gi,`findDeclarationNodeAtOffset`);function Ki(e,t){if(e){let n=Zi(e,!0);if(n&&qi(n,t))return n;if(hn(e)){let n=e.content.findIndex(e=>!e.hidden);for(let r=n-1;r>=0;r--){let n=e.content[r];if(qi(n,t))return n}}}}o(Ki,`findCommentNode`);function qi(e,t){return mn(e)&&t.includes(e.tokenType.name)}o(qi,`isCommentNode`);function Ji(e,t){if(mn(e))return e;if(pn(e)){let n=Xi(e,t,!1);if(n)return Ji(n,t)}}o(Ji,`findLeafNodeAtOffset`);function Yi(e,t){if(mn(e))return e;if(pn(e)){let n=Xi(e,t,!0);if(n)return Yi(n,t)}}o(Yi,`findLeafNodeBeforeOffset`);function Xi(e,t,n){let r=0,i=e.content.length-1,a;for(;r<=i;){let o=Math.floor((r+i)/2),s=e.content[o];if(s.offset<=t&&s.end>t)return s;s.end<=t?(a=n?s:void 0,r=o+1):i=o-1}return a}o(Xi,`binarySearch`);function Zi(e,t=!0){for(;e.container;){let n=e.container,r=n.content.indexOf(e);for(;r>0;){r--;let e=n.content[r];if(t||!e.hidden)return e}e=n}}o(Zi,`getPreviousNode`);function Qi(e,t=!0){for(;e.container;){let n=e.container,r=n.content.indexOf(e),i=n.content.length-1;for(;rWa,findNameAssignment:()=>Ga,findNodeForKeyword:()=>Ha,findNodeForProperty:()=>za,findNodesForKeyword:()=>Va,findNodesForKeywordInternal:()=>Ua,findNodesForProperty:()=>Ra,getActionAtElement:()=>qa,getActionType:()=>ro,getAllReachableRules:()=>Na,getAllRulesUsedForCrossReferences:()=>Fa,getCrossReferenceTerminal:()=>Ia,getEntryRule:()=>ja,getExplicitRuleType:()=>to,getHiddenRules:()=>Ma,getRuleType:()=>ao,getRuleTypeName:()=>io,getTypeName:()=>no,isArrayCardinality:()=>Ya,isArrayOperator:()=>Xa,isCommentTerminal:()=>La,isDataType:()=>$a,isDataTypeRule:()=>Za,isOptionalCardinality:()=>Ja,terminalRegex:()=>oo});var ia=class extends Error{static{o(this,`ErrorWithLocation`)}constructor(e,t){super(e?`${t} at ${e.range.start.line}:${e.range.start.character}`:t)}};function aa(e,t=`Error: Got unexpected value.`){throw Error(t)}o(aa,`assertUnreachable`);function oa(e,t=`Error: Condition is violated.`){if(!e)throw Error(t)}o(oa,`assertCondition`);var sa={};l(sa,{NEWLINE_REGEXP:()=>xa,escapeRegExp:()=>Oa,getTerminalParts:()=>wa,isMultilineComment:()=>Ta,isWhitespace:()=>Da,partialMatches:()=>ka,partialRegExp:()=>Aa,whitespaceCharacters:()=>Ea});function F(e){return e.charCodeAt(0)}o(F,`cc`);function ca(e,t){Array.isArray(e)?e.forEach(function(e){t.push(e)}):t.push(e)}o(ca,`insertToSet`);function la(e,t){if(e[t]===!0)throw`duplicate flag `+t;e[t],e[t]=!0}o(la,`addFlag`);function ua(e){if(e===void 0)throw Error(`Internal Error - Should never get here!`);return!0}o(ua,`ASSERT_EXISTS`);function da(){throw Error(`Internal Error - Should never get here!`)}o(da,`ASSERT_NEVER_REACH_HERE`);function fa(e){return e.type===`Character`}o(fa,`isCharacter`);var pa=[];for(let e=F(`0`);e<=F(`9`);e++)pa.push(e);var ma=[F(`_`)].concat(pa);for(let e=F(`a`);e<=F(`z`);e++)ma.push(e);for(let e=F(`A`);e<=F(`Z`);e++)ma.push(e);var ha=[F(` `),F(`\f`),F(` +`),F(`\r`),F(` `),F(`\v`),F(` `),F(`\xA0`),F(` `),F(` `),F(` `),F(` `),F(` `),F(` `),F(` `),F(` `),F(` `),F(` `),F(` `),F(` `),F(`\u2028`),F(`\u2029`),F(` `),F(` `),F(` `),F(``)],ga=/[0-9a-fA-F]/,_a=/[0-9]/,va=/[1-9]/,ya=class{static{o(this,`RegExpParser`)}constructor(){this.idx=0,this.input=``,this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar(`/`);let t=this.disjunction();this.consumeChar(`/`);let n={type:`Flags`,loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case`g`:la(n,`global`);break;case`i`:la(n,`ignoreCase`);break;case`m`:la(n,`multiLine`);break;case`u`:la(n,`unicode`);break;case`y`:la(n,`sticky`);break}if(this.idx!==this.input.length)throw Error(`Redundant input: `+this.input.substring(this.idx));return{type:`Pattern`,flags:n,value:t,loc:this.loc(0)}}disjunction(){let e=[],t=this.idx;for(e.push(this.alternative());this.peekChar()===`|`;)this.consumeChar(`|`),e.push(this.alternative());return{type:`Disjunction`,value:e,loc:this.loc(t)}}alternative(){let e=[],t=this.idx;for(;this.isTerm();)e.push(this.term());return{type:`Alternative`,value:e,loc:this.loc(t)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){let e=this.idx;switch(this.popChar()){case`^`:return{type:`StartAnchor`,loc:this.loc(e)};case`$`:return{type:`EndAnchor`,loc:this.loc(e)};case`\\`:switch(this.popChar()){case`b`:return{type:`WordBoundary`,loc:this.loc(e)};case`B`:return{type:`NonWordBoundary`,loc:this.loc(e)}}throw Error(`Invalid Assertion Escape`);case`(`:this.consumeChar(`?`);let t;switch(this.popChar()){case`=`:t=`Lookahead`;break;case`!`:t=`NegativeLookahead`;break;case`<`:switch(this.popChar()){case`=`:t=`Lookbehind`;break;case`!`:t=`NegativeLookbehind`}break}ua(t);let n=this.disjunction();return this.consumeChar(`)`),{type:t,value:n,loc:this.loc(e)}}return da()}quantifier(e=!1){let t,n=this.idx;switch(this.popChar()){case`*`:t={atLeast:0,atMost:1/0};break;case`+`:t={atLeast:1,atMost:1/0};break;case`?`:t={atLeast:0,atMost:1};break;case`{`:let n=this.integerIncludingZero();switch(this.popChar()){case`}`:t={atLeast:n,atMost:n};break;case`,`:let e;this.isDigit()?(e=this.integerIncludingZero(),t={atLeast:n,atMost:e}):t={atLeast:n,atMost:1/0},this.consumeChar(`}`);break}if(e===!0&&t===void 0)return;ua(t);break}if(!(e===!0&&t===void 0)&&ua(t))return this.peekChar(0)===`?`?(this.consumeChar(`?`),t.greedy=!1):t.greedy=!0,t.type=`Quantifier`,t.loc=this.loc(n),t}atom(){let e,t=this.idx;switch(this.peekChar()){case`.`:e=this.dotAll();break;case`\\`:e=this.atomEscape();break;case`[`:e=this.characterClass();break;case`(`:e=this.group();break}return e===void 0&&this.isPatternCharacter()&&(e=this.patternCharacter()),ua(e)?(e.loc=this.loc(t),this.isQuantifier()&&(e.quantifier=this.quantifier()),e):da()}dotAll(){return this.consumeChar(`.`),{type:`Set`,complement:!0,value:[F(` +`),F(`\r`),F(`\u2028`),F(`\u2029`)]}}atomEscape(){switch(this.consumeChar(`\\`),this.peekChar()){case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:return this.decimalEscapeAtom();case`d`:case`D`:case`s`:case`S`:case`w`:case`W`:return this.characterClassEscape();case`f`:case`n`:case`r`:case`t`:case`v`:return this.controlEscapeAtom();case`c`:return this.controlLetterEscapeAtom();case`0`:return this.nulCharacterAtom();case`x`:return this.hexEscapeSequenceAtom();case`u`:return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:`GroupBackReference`,value:this.positiveInteger()}}characterClassEscape(){let e,t=!1;switch(this.popChar()){case`d`:e=pa;break;case`D`:e=pa,t=!0;break;case`s`:e=ha;break;case`S`:e=ha,t=!0;break;case`w`:e=ma;break;case`W`:e=ma,t=!0;break}return ua(e)?{type:`Set`,value:e,complement:t}:da()}controlEscapeAtom(){let e;switch(this.popChar()){case`f`:e=F(`\f`);break;case`n`:e=F(` +`);break;case`r`:e=F(`\r`);break;case`t`:e=F(` `);break;case`v`:e=F(`\v`);break}return ua(e)?{type:`Character`,value:e}:da()}controlLetterEscapeAtom(){this.consumeChar(`c`);let e=this.popChar();if(/[a-zA-Z]/.test(e)===!1)throw Error(`Invalid `);return{type:`Character`,value:e.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar(`0`),{type:`Character`,value:F(`\0`)}}hexEscapeSequenceAtom(){return this.consumeChar(`x`),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar(`u`),this.parseHexDigits(4)}identityEscapeAtom(){return{type:`Character`,value:F(this.popChar())}}classPatternCharacterAtom(){switch(this.peekChar()){case` +`:case`\r`:case`\u2028`:case`\u2029`:case`\\`:case`]`:throw Error(`TBD`);default:return{type:`Character`,value:F(this.popChar())}}}characterClass(){let e=[],t=!1;for(this.consumeChar(`[`),this.peekChar(0)===`^`&&(this.consumeChar(`^`),t=!0);this.isClassAtom();){let t=this.classAtom();if(t.type,fa(t)&&this.isRangeDash()){this.consumeChar(`-`);let n=this.classAtom();if(n.type,fa(n)){if(n.value=this.input.length)throw Error(`Unexpected end of input`);this.idx++}loc(e){return{begin:e,end:this.idx}}},ba=class{static{o(this,`BaseRegExpVisitor`)}visitChildren(e){for(let t in e){let n=e[t];e.hasOwnProperty(t)&&(n.type===void 0?Array.isArray(n)&&n.forEach(e=>{this.visit(e)},this):this.visit(n))}}visit(e){switch(e.type){case`Pattern`:this.visitPattern(e);break;case`Flags`:this.visitFlags(e);break;case`Disjunction`:this.visitDisjunction(e);break;case`Alternative`:this.visitAlternative(e);break;case`StartAnchor`:this.visitStartAnchor(e);break;case`EndAnchor`:this.visitEndAnchor(e);break;case`WordBoundary`:this.visitWordBoundary(e);break;case`NonWordBoundary`:this.visitNonWordBoundary(e);break;case`Lookahead`:this.visitLookahead(e);break;case`NegativeLookahead`:this.visitNegativeLookahead(e);break;case`Lookbehind`:this.visitLookbehind(e);break;case`NegativeLookbehind`:this.visitNegativeLookbehind(e);break;case`Character`:this.visitCharacter(e);break;case`Set`:this.visitSet(e);break;case`Group`:this.visitGroup(e);break;case`GroupBackReference`:this.visitGroupBackReference(e);break;case`Quantifier`:this.visitQuantifier(e);break}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitLookbehind(e){}visitNegativeLookbehind(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}},xa=/\r?\n/gm,Sa=new ya,Ca=new class extends ba{static{o(this,`TerminalRegExpVisitor`)}constructor(){super(...arguments),this.isStarting=!0,this.endRegexpStack=[],this.multiline=!1}get endRegex(){return this.endRegexpStack.join(``)}reset(e){this.multiline=!1,this.regex=e,this.startRegexp=``,this.isStarting=!0,this.endRegexpStack=[]}visitGroup(e){e.quantifier&&(this.isStarting=!1,this.endRegexpStack=[])}visitCharacter(e){let t=String.fromCharCode(e.value);if(!this.multiline&&t===` +`&&(this.multiline=!0),e.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{let e=Oa(t);this.endRegexpStack.push(e),this.isStarting&&(this.startRegexp+=e)}}visitSet(e){if(!this.multiline){let t=this.regex.substring(e.loc.begin,e.loc.end),n=new RegExp(t);this.multiline=!!` +`.match(n)}if(e.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{let t=this.regex.substring(e.loc.begin,e.loc.end);this.endRegexpStack.push(t),this.isStarting&&(this.startRegexp+=t)}}visitChildren(e){e.type===`Group`&&e.quantifier||super.visitChildren(e)}};function wa(e){try{typeof e!=`string`&&(e=e.source),e=`/${e}/`;let t=Sa.pattern(e),n=[];for(let r of t.value.value)Ca.reset(e),Ca.visit(r),n.push({start:Ca.startRegexp,end:Ca.endRegex});return n}catch{return[]}}o(wa,`getTerminalParts`);function Ta(e){try{return typeof e==`string`&&(e=new RegExp(e)),e=e.toString(),Ca.reset(e),Ca.visit(Sa.pattern(e)),Ca.multiline}catch{return!1}}o(Ta,`isMultilineComment`);var Ea=`\f +\r \v \xA0            \u2028\u2029   `.split(``);function Da(e){let t=typeof e==`string`?new RegExp(e):e;return Ea.some(e=>t.test(e))}o(Da,`isWhitespace`);function Oa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}o(Oa,`escapeRegExp`);function ka(e,t){let n=Aa(e),r=t.match(n);return!!r&&r[0].length>0}o(ka,`partialMatches`);function Aa(e){typeof e==`string`&&(e=new RegExp(e));let t=e,n=e.source,r=0;function i(){let e=``,a;function s(t){e+=n.substr(r,t),r+=t}o(s,`appendRaw`);function c(t){e+=`(?:`+n.substr(r,t)+`|$)`,r+=t}for(o(c,`appendOptional`);r`,r)-r+1);break;default:c(2);break}break;case`[`:a=/\[(?:\\.|.)*?\]/g,a.lastIndex=r,a=a.exec(n)||[],c(a[0].length);break;case`|`:case`^`:case`$`:case`*`:case`+`:case`?`:s(1);break;case`{`:a=/\{\d+,?\d*\}/g,a.lastIndex=r,a=a.exec(n),a?s(a[0].length):c(1);break;case`(`:if(n[r+1]===`?`)switch(n[r+2]){case`:`:e+=`(?:`,r+=3,e+=i()+`|$)`;break;case`=`:e+=`(?=`,r+=3,e+=i()+`)`;break;case`!`:a=r,r+=3,i(),e+=n.substr(a,r-a);break;case`<`:switch(n[r+3]){case`=`:case`!`:a=r,r+=4,i(),e+=n.substr(a,r-a);break;default:s(n.indexOf(`>`,r)-r+1),e+=i()+`|$)`;break}break}else s(1),e+=i()+`|$)`;break;case`)`:return++r,e;default:c(1);break}return e}return o(i,`process`),new RegExp(i(),e.flags)}o(Aa,`partialRegExp`);function ja(e){return e.rules.find(e=>Yr(e)&&e.entry)}o(ja,`getEntryRule`);function Ma(e){return e.rules.filter(e=>hi(e)&&e.hidden)}o(Ma,`getHiddenRules`);function Na(e,t){let n=new Set,r=ja(e);if(!r)return new Set(e.rules);let i=[r].concat(Ma(e));for(let e of i)Pa(e,n,t);let a=new Set;for(let t of e.rules)(n.has(t.name)||hi(t)&&t.hidden)&&a.add(t);return a}o(Na,`getAllReachableRules`);function Pa(e,t,n){t.add(e.name),jn(e).forEach(e=>{if(ri(e)||n&&_i(e)){let r=e.rule.ref;r&&!t.has(r.name)&&Pa(r,t,n)}})}o(Pa,`ruleDfs`);function Fa(e){let t=new Set;return jn(e).forEach(e=>{pr(e)&&(Yr(e.type.ref)&&t.add(e.type.ref),Tr(e.type.ref)&&Yr(e.type.ref.$container)&&t.add(e.type.ref.$container))}),t}o(Fa,`getAllRulesUsedForCrossReferences`);function Ia(e){if(e.terminal)return e.terminal;if(e.type.ref)return Ga(e.type.ref)?.terminal}o(Ia,`getCrossReferenceTerminal`);function La(e){return e.hidden&&!Da(oo(e))}o(La,`isCommentTerminal`);function Ra(e,t){return!e||!t?[]:Ba(e,t,e.astNode,!0)}o(Ra,`findNodesForProperty`);function za(e,t,n){if(!e||!t)return;let r=Ba(e,t,e.astNode,!0);if(r.length!==0)return n=n===void 0?0:Math.max(0,Math.min(n,r.length-1)),r[n]}o(za,`findNodeForProperty`);function Ba(e,t,n,r){if(!r){let n=Tn(e.grammarSource,rr);if(n&&n.feature===t)return[e]}return pn(e)&&e.astNode===n?e.content.flatMap(e=>Ba(e,t,n,!1)):[]}o(Ba,`findNodesForPropertyInternal`);function Va(e,t){return e?Ua(e,t,e?.astNode):[]}o(Va,`findNodesForKeyword`);function Ha(e,t,n){if(!e)return;let r=Ua(e,t,e?.astNode);if(r.length!==0)return n=n===void 0?0:Math.max(0,Math.min(n,r.length-1)),r[n]}o(Ha,`findNodeForKeyword`);function Ua(e,t,n){if(e.astNode!==n)return[];if(Fr(e.grammarSource)&&e.grammarSource.value===t)return[e];let r=Ii(e).iterator(),i,a=[];do if(i=r.next(),!i.done){let e=i.value;e.astNode===n?Fr(e.grammarSource)&&e.grammarSource.value===t&&a.push(e):r.prune()}while(!i.done);return a}o(Ua,`findNodesForKeywordInternal`);function Wa(e){let t=e.astNode;for(;t===e.container?.astNode;){let t=Tn(e.grammarSource,rr);if(t)return t;e=e.container}}o(Wa,`findAssignment`);function Ga(e){let t=e;return Tr(t)&&(Yn(t.$container)?t=t.$container.$container:Un(t.$container)?t=t.$container:aa(t.$container)),Ka(e,t,new Map)}o(Ga,`findNameAssignment`);function Ka(e,t,n){function r(t,r){let i;return Tn(t,rr)||(i=Ka(r,r,n)),n.set(e,i),i}if(o(r,`go`),n.has(e))return n.get(e);n.set(e,void 0);for(let i of jn(t))if(rr(i)&&i.feature.toLowerCase()===`name`)return n.set(e,i),i;else if(ri(i)&&Yr(i.rule.ref))return r(i,i.rule.ref);else if(ai(i)&&i.typeRef?.ref)return r(i,i.typeRef.ref)}o(Ka,`findNameAssignmentInternal`);function qa(e){let t=e.$container;if(Cr(t)){let n=t.elements,r=n.indexOf(e);for(let e=r-1;e>=0;e--){let t=n[e];if(Yn(t))return t;{let t=jn(n[e]).find(Yn);if(t)return t}}}if(Vn(t))return qa(t)}o(qa,`getActionAtElement`);function Ja(e,t){return e===`?`||e===`*`||Cr(t)&&!!t.guardCondition}o(Ja,`isOptionalCardinality`);function Ya(e){return e===`*`||e===`+`}o(Ya,`isArrayCardinality`);function Xa(e){return e===`+=`}o(Xa,`isArrayOperator`);function Za(e){return Qa(e,new Set)}o(Za,`isDataTypeRule`);function Qa(e,t){if(t.has(e))return!0;t.add(e);for(let n of jn(e))if(ri(n)){if(!n.rule.ref||Yr(n.rule.ref)&&!Qa(n.rule.ref,t)||Dr(n.rule.ref))return!1}else if(rr(n))return!1;else if(Yn(n))return!1;return!!e.definition}o(Qa,`isDataTypeRuleInternal`);function $a(e){return eo(e.type,new Set)}o($a,`isDataType`);function eo(e,t){if(t.has(e))return!0;if(t.add(e),tr(e)||Zr(e))return!1;if(Ti(e))return e.types.every(e=>eo(e,t));if(ai(e)){if(e.primitiveType!==void 0||e.stringType!==void 0)return!0;if(e.typeRef!==void 0){let n=e.typeRef.ref;return yi(n)?eo(n.type,t):!1}else return!1}else return!1}o(eo,`isDataTypeInternal`);function to(e){if(!hi(e)){if(e.inferredType)return e.inferredType.name;if(e.dataType)return e.dataType;if(e.returnType){let t=e.returnType.ref;if(t)return t.name}}}o(to,`getExplicitRuleType`);function no(e){if(Un(e))return Yr(e)&&Za(e)?e.name:to(e)??e.name;if(Nr(e)||yi(e)||ti(e))return e.name;if(Yn(e)){let t=ro(e);if(t)return t}else if(Tr(e))return e.name;throw Error(`Cannot get name of Unknown Type`)}o(no,`getTypeName`);function ro(e){if(e.inferredType)return e.inferredType.name;if(e.type?.ref)return no(e.type.ref)}o(ro,`getActionType`);function io(e){return hi(e)?e.type?.name??`string`:Yr(e)&&Za(e)?e.name:to(e)??e.name}o(io,`getRuleTypeName`);function ao(e){return hi(e)?e.type?.name??`string`:to(e)??e.name}o(ao,`getRuleType`);function oo(e){let t={s:!1,i:!1,u:!1},n=co(e.definition,t),r=Object.entries(t).filter(([,e])=>e).map(([e])=>e).join(``);return new RegExp(n,r)}o(oo,`terminalRegex`);var so=`[\\s\\S]`;function co(e,t){if(li(e))return lo(e);if(pi(e))return uo(e);if(sr(e))return mo(e);if(_i(e)){let t=e.rule.ref;if(!t)throw Error(`Missing rule reference.`);return go(co(t.definition),{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized})}else if(zr(e))return po(e);else if(ki(e))return fo(e);else if($r(e)){let n=e.regex.lastIndexOf(`/`),r=e.regex.substring(1,n),i=e.regex.substring(n+1);return t&&(t.i=i.includes(`i`),t.s=i.includes(`s`),t.u=i.includes(`u`)),go(r,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1})}else if(Ni(e))return go(so,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized});else throw Error(`Invalid terminal element: ${e?.$type}, ${e?.$cstNode?.text}`)}o(co,`abstractElementToRegex`);function lo(e){return go(e.elements.map(e=>co(e)).join(`|`),{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1})}o(lo,`terminalAlternativesToRegex`);function uo(e){return go(e.elements.map(e=>co(e)).join(``),{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1})}o(uo,`terminalGroupToRegex`);function fo(e){return go(`${so}*?${co(e.terminal)}`,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized})}o(fo,`untilTokenToRegex`);function po(e){return go(`(?!${co(e.terminal)})${so}*?`,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized})}o(po,`negateTokenToRegex`);function mo(e){return e.right?go(`[${ho(e.left)}-${ho(e.right)}]`,{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1}):go(ho(e.left),{cardinality:e.cardinality,lookahead:e.lookahead,parenthesized:e.parenthesized,wrap:!1})}o(mo,`characterRangeToRegex`);function ho(e){return Oa(e.value)}o(ho,`keywordToRegex`);function go(e,t){return(t.parenthesized||t.lookahead||t.wrap!==!1)&&(e=`(${t.lookahead??(t.parenthesized?``:`?:`)}${e})`),t.cardinality?`${e}${t.cardinality}`:e}o(go,`withCardinality`);function _o(e){let t=[],n=e.Grammar;for(let e of n.rules)hi(e)&&La(e)&&Ta(oo(e))&&t.push(e.name);return{multilineCommentRules:t,nameRegexp:Wi}}o(_o,`createGrammarConfig`);var vo=typeof global==`object`&&global&&global.Object===Object&&global,yo=typeof self==`object`&&self&&self.Object===Object&&self,bo=vo||yo||Function(`return this`)(),xo=bo.Symbol,So=Object.prototype,Co=So.hasOwnProperty,wo=So.toString,To=xo?xo.toStringTag:void 0;function Eo(e){var t=Co.call(e,To),n=e[To];try{e[To]=void 0;var r=!0}catch{}var i=wo.call(e);return r&&(t?e[To]=n:delete e[To]),i}o(Eo,`getRawTag`);var Do=Eo,Oo=Object.prototype.toString;function ko(e){return Oo.call(e)}o(ko,`objectToString`);var Ao=ko,jo=`[object Null]`,Mo=`[object Undefined]`,No=xo?xo.toStringTag:void 0;function Po(e){return e==null?e===void 0?Mo:jo:No&&No in Object(e)?Do(e):Ao(e)}o(Po,`baseGetTag`);var Fo=Po;function Io(e){return typeof e==`object`&&!!e}o(Io,`isObjectLike`);var Lo=Io,Ro=`[object Symbol]`;function zo(e){return typeof e==`symbol`||Lo(e)&&Fo(e)==Ro}o(zo,`isSymbol`);var Bo=zo;function Vo(e,t){for(var n=-1,r=e==null?0:e.length,i=Array(r);++n0){if(++t>=Qs)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}o(tc,`shortOut`);var nc=tc;function rc(e){return function(){return e}}o(rc,`constant`);var ic=rc,ac=(function(){try{var e=Hs(Object,`defineProperty`);return e({},``,{}),e}catch{}})(),oc=nc(ac?function(e,t){return ac(e,`toString`,{configurable:!0,enumerable:!1,value:ic(t),writable:!0})}:gs);function sc(e,t){for(var n=-1,r=e==null?0:e.length;++n-1}o(_c,`arrayIncludes`);var vc=_c,yc=9007199254740991,bc=/^(?:0|[1-9]\d*)$/;function xc(e,t){var n=typeof e;return t??=yc,!!t&&(n==`number`||n!=`symbol`&&bc.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=Lc}o(Rc,`isLength`);var zc=Rc;function Bc(e){return e!=null&&zc(e.length)&&!Ss(e)}o(Bc,`isArrayLike`);var Vc=Bc;function Hc(e,t,n){if(!ts(n))return!1;var r=typeof t;return(r==`number`?Vc(n)&&Sc(t,n.length):r==`string`&&t in n)?Ec(n[t],e):!1}o(Hc,`isIterateeCall`);var Uc=Hc;function Wc(e){return Ic(function(t,n){var r=-1,i=n.length,a=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(a=e.length>3&&typeof a==`function`?(i--,a):void 0,o&&Uc(n[0],n[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++r-1}o(Bu,`listCacheHas`);var Vu=Bu;function Hu(e,t){var n=this.__data__,r=Pu(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}o(Hu,`listCacheSet`);var Uu=Hu;function Wu(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t0&&n(s)?t>1?Pd(s,t-1,n,r,i):Ad(i,s):r||(i[i.length]=s)}return i}o(Pd,`baseFlatten`);var Fd=Pd;function Id(e){return e!=null&&e.length?Fd(e,1):[]}o(Id,`flatten`);var Ld=Id,Rd=Jl(Object.getPrototypeOf,Object);function zd(e,t,n){var r=-1,i=e.length;t<0&&(t=-t>i?0:i+t),n=n>i?i:n,n<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var a=Array(i);++rs))return!1;var l=a.get(e),u=a.get(t);if(l&&u)return l==t&&u==e;var d=-1,f=!0,p=n&Lm?new jm:void 0;for(a.set(e,t),a.set(t,e);++d2?t[2]:void 0;for(i&&Uc(t[0],t[1],i)&&(r=1);++n=hg&&(a=Fm,o=!1,t=new jm(t));outer:for(;++i-1?i[a?t[s]:s]:void 0}}o(Rg,`createFind`);var zg=Rg,Bg=Math.max;function Vg(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var i=n==null?0:ms(n);return i<0&&(i=Bg(r+i,0)),uc(e,Yh(t,3),i)}o(Vg,`findIndex`);var Hg=zg(Vg);function Ug(e){return e&&e.length?e[0]:void 0}o(Ug,`head`);var Wg=Ug;function Gg(e,t){var n=-1,r=Vc(e)?Array(e.length):[];return rg(e,function(e,i,a){r[++n]=t(e,i,a)}),r}o(Gg,`baseMap`);var Kg=Gg;function qg(e,t){return(I(e)?Ho:Kg)(e,Yh(t,3))}o(qg,`map`);var B=qg;function Jg(e,t){return Fd(B(e,t),1)}o(Jg,`flatMap`);var Yg=Jg,Xg=Object.prototype.hasOwnProperty,Zg=sg(function(e,t,n){Xg.call(e,n)?e[n].push(t):wc(e,n,[t])}),Qg=Object.prototype.hasOwnProperty;function $g(e,t){return e!=null&&Qg.call(e,t)}o($g,`baseHas`);var e_=$g;function t_(e,t){return e!=null&&Fh(e,t,e_)}o(t_,`has`);var V=t_,n_=`[object String]`;function r_(e){return typeof e==`string`||!I(e)&&Lo(e)&&Fo(e)==n_}o(r_,`isString`);var i_=r_;function a_(e,t){return Ho(t,function(t){return e[t]})}o(a_,`baseValues`);var o_=a_;function s_(e){return e==null?[]:o_(e,eu(e))}o(s_,`values`);var H=s_,c_=Math.max;function l_(e,t,n,r){e=Vc(e)?e:H(e),n=n&&!r?ms(n):0;var i=e.length;return n<0&&(n=c_(i+n,0)),i_(e)?n<=i&&e.indexOf(t,n)>-1:!!i&&gc(e,t,n)>-1}o(l_,`includes`);var u_=l_,d_=Math.max;function f_(e,t,n){var r=e==null?0:e.length;if(!r)return-1;var i=n==null?0:ms(n);return i<0&&(i=d_(r+i,0)),gc(e,t,i)}o(f_,`indexOf`);var p_=f_,m_=`[object Map]`,h_=`[object Set]`,g_=Object.prototype.hasOwnProperty;function __(e){if(e==null)return!0;if(Vc(e)&&(I(e)||typeof e==`string`||typeof e.splice==`function`||ll(e)||Ul(e)||rl(e)))return!e.length;var t=Kf(e);if(t==m_||t==h_)return!e.size;if(Jc(e))return!Ql(e).length;for(var n in e)if(g_.call(e,n))return!1;return!0}o(__,`isEmpty`);var U=__,v_=`[object RegExp]`;function y_(e){return Lo(e)&&Fo(e)==v_}o(y_,`baseIsRegExp`);var b_=y_,x_=Vl&&Vl.isRegExp,S_=x_?Ll(x_):b_;function C_(e){return e===void 0}o(C_,`isUndefined`);var w_=C_,T_=`Expected a function`;function E_(e){if(typeof e!=`function`)throw TypeError(T_);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}o(E_,`negate`);var D_=E_;function O_(e,t,n,r){if(!ts(e))return e;t=xd(t,e);for(var i=-1,a=t.length,o=a-1,s=e;s!=null&&++i=G_){var l=t?null:W_(e);if(l)return Um(l);o=!1,i=Fm,c=new jm}else c=t?[]:s;outer:for(;++r{t.accept(e)})}},rv=class extends nv{static{o(this,`NonTerminal`)}constructor(e){super([]),this.idx=1,nu(this,N_(e,e=>e!==void 0))}set definition(e){}get definition(){return this.referencedRule===void 0?[]:this.referencedRule.definition}accept(e){e.visit(this)}},iv=class extends nv{static{o(this,`Rule`)}constructor(e){super(e.definition),this.orgText=``,nu(this,N_(e,e=>e!==void 0))}},av=class extends nv{static{o(this,`Alternative`)}constructor(e){super(e.definition),this.ignoreAmbiguities=!1,nu(this,N_(e,e=>e!==void 0))}},ov=class extends nv{static{o(this,`Option`)}constructor(e){super(e.definition),this.idx=1,nu(this,N_(e,e=>e!==void 0))}},sv=class extends nv{static{o(this,`RepetitionMandatory`)}constructor(e){super(e.definition),this.idx=1,nu(this,N_(e,e=>e!==void 0))}},cv=class extends nv{static{o(this,`RepetitionMandatoryWithSeparator`)}constructor(e){super(e.definition),this.idx=1,nu(this,N_(e,e=>e!==void 0))}},W=class extends nv{static{o(this,`Repetition`)}constructor(e){super(e.definition),this.idx=1,nu(this,N_(e,e=>e!==void 0))}},lv=class extends nv{static{o(this,`RepetitionWithSeparator`)}constructor(e){super(e.definition),this.idx=1,nu(this,N_(e,e=>e!==void 0))}},uv=class extends nv{static{o(this,`Alternation`)}get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,nu(this,N_(e,e=>e!==void 0))}},G=class{static{o(this,`Terminal`)}constructor(e){this.idx=1,nu(this,N_(e,e=>e!==void 0))}accept(e){e.visit(this)}};function dv(e){return B(e,fv)}o(dv,`serializeGrammar`);function fv(e){function t(e){return B(e,fv)}if(o(t,`convertDefinition`),e instanceof rv){let t={type:`NonTerminal`,name:e.nonTerminalName,idx:e.idx};return i_(e.label)&&(t.label=e.label),t}else if(e instanceof av)return{type:`Alternative`,definition:t(e.definition)};else if(e instanceof ov)return{type:`Option`,idx:e.idx,definition:t(e.definition)};else if(e instanceof sv)return{type:`RepetitionMandatory`,idx:e.idx,definition:t(e.definition)};else if(e instanceof cv)return{type:`RepetitionMandatoryWithSeparator`,idx:e.idx,separator:fv(new G({terminalType:e.separator})),definition:t(e.definition)};else if(e instanceof lv)return{type:`RepetitionWithSeparator`,idx:e.idx,separator:fv(new G({terminalType:e.separator})),definition:t(e.definition)};else if(e instanceof W)return{type:`Repetition`,idx:e.idx,definition:t(e.definition)};else if(e instanceof uv)return{type:`Alternation`,idx:e.idx,definition:t(e.definition)};else if(e instanceof G){let t={type:`Terminal`,name:e.terminalType.name,label:ev(e.terminalType),idx:e.idx};i_(e.label)&&(t.terminalLabel=e.label);let n=e.terminalType.PATTERN;return e.terminalType.PATTERN&&(t.pattern=S_(n)?n.source:n),t}else if(e instanceof iv)return{type:`Rule`,name:e.name,orgText:e.orgText,definition:t(e.definition)};else throw Error(`non exhaustive match`)}o(fv,`serializeProduction`);var pv=class{static{o(this,`GAstVisitor`)}visit(e){let t=e;switch(t.constructor){case rv:return this.visitNonTerminal(t);case av:return this.visitAlternative(t);case ov:return this.visitOption(t);case sv:return this.visitRepetitionMandatory(t);case cv:return this.visitRepetitionMandatoryWithSeparator(t);case lv:return this.visitRepetitionWithSeparator(t);case W:return this.visitRepetition(t);case uv:return this.visitAlternation(t);case G:return this.visitTerminal(t);case iv:return this.visitRule(t);default:throw Error(`non exhaustive match`)}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}};function mv(e){return e instanceof av||e instanceof ov||e instanceof W||e instanceof sv||e instanceof cv||e instanceof lv||e instanceof G||e instanceof iv}o(mv,`isSequenceProd`);function hv(e,t=[]){return e instanceof ov||e instanceof W||e instanceof lv?!0:e instanceof uv?U_(e.definition,e=>hv(e,t)):e instanceof rv&&u_(t,e)?!1:e instanceof nv?(e instanceof rv&&t.push(e),Ng(e.definition,e=>hv(e,t))):!1}o(hv,`isOptionalProd`);function gv(e){return e instanceof uv}o(gv,`isBranchingProd`);function _v(e){if(e instanceof rv)return`SUBRULE`;if(e instanceof ov)return`OPTION`;if(e instanceof uv)return`OR`;if(e instanceof sv)return`AT_LEAST_ONE`;if(e instanceof cv)return`AT_LEAST_ONE_SEP`;if(e instanceof lv)return`MANY_SEP`;if(e instanceof W)return`MANY`;if(e instanceof G)return`CONSUME`;throw Error(`non exhaustive match`)}o(_v,`getProductionDslName`);var vv=class{static{o(this,`RestWalker`)}walk(e,t=[]){z(e.definition,(n,r)=>{let i=Sg(e.definition,r+1);if(n instanceof rv)this.walkProdRef(n,i,t);else if(n instanceof G)this.walkTerminal(n,i,t);else if(n instanceof av)this.walkFlat(n,i,t);else if(n instanceof ov)this.walkOption(n,i,t);else if(n instanceof sv)this.walkAtLeastOne(n,i,t);else if(n instanceof cv)this.walkAtLeastOneSep(n,i,t);else if(n instanceof lv)this.walkManySep(n,i,t);else if(n instanceof W)this.walkMany(n,i,t);else if(n instanceof uv)this.walkOr(n,i,t);else throw Error(`non exhaustive match`)})}walkTerminal(e,t,n){}walkProdRef(e,t,n){}walkFlat(e,t,n){let r=t.concat(n);this.walk(e,r)}walkOption(e,t,n){let r=t.concat(n);this.walk(e,r)}walkAtLeastOne(e,t,n){let r=[new ov({definition:e.definition})].concat(t,n);this.walk(e,r)}walkAtLeastOneSep(e,t,n){let r=yv(e,t,n);this.walk(e,r)}walkMany(e,t,n){let r=[new ov({definition:e.definition})].concat(t,n);this.walk(e,r)}walkManySep(e,t,n){let r=yv(e,t,n);this.walk(e,r)}walkOr(e,t,n){let r=t.concat(n);z(e.definition,e=>{let t=new av({definition:[e]});this.walk(t,r)})}};function yv(e,t,n){return[new ov({definition:[new G({terminalType:e.separator})].concat(e.definition)})].concat(t,n)}o(yv,`restForRepetitionWithSeparator`);function bv(e){if(e instanceof rv)return bv(e.referencedRule);if(e instanceof G)return Cv(e);if(mv(e))return xv(e);if(gv(e))return Sv(e);throw Error(`non exhaustive match`)}o(bv,`first`);function xv(e){let t=[],n=e.definition,r=0,i=n.length>r,a,o=!0;for(;i&&o;)a=n[r],o=hv(a),t=t.concat(bv(a)),r+=1,i=n.length>r;return Y_(t)}o(xv,`firstForSequence`);function Sv(e){return Y_(Ld(B(e.definition,e=>bv(e))))}o(Sv,`firstForBranching`);function Cv(e){return[e.terminalType]}o(Cv,`firstForTerminal`);var wv=`_~IN~_`,Tv=class extends vv{static{o(this,`ResyncFollowsWalker`)}constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,t,n){}walkProdRef(e,t,n){let r=Dv(e.referencedRule,e.idx)+this.topProd.name,i=bv(new av({definition:t.concat(n)}));this.follows[r]=i}};function Ev(e){let t={};return z(e,e=>{let n=new Tv(e).startWalking();nu(t,n)}),t}o(Ev,`computeAllProdsFollows`);function Dv(e,t){return e.name+t+wv}o(Dv,`buildBetweenProdsFollowPrefix`);var Ov={},kv=new ya;function Av(e){let t=e.toString();if(Ov.hasOwnProperty(t))return Ov[t];{let e=kv.pattern(t);return Ov[t]=e,e}}o(Av,`getRegExpAst`);function jv(){Ov={}}o(jv,`clearRegExpParserCache`);var Mv=`Complement Sets are not supported for first char optimization`,Nv=`Unable to use "first char" lexer optimizations: +`;function Pv(e,t=!1){try{let t=Av(e);return Fv(t.value,{},t.flags.ignoreCase)}catch(n){if(n.message===Mv)t&&Z_(`${Nv} Unable to optimize: < ${e.toString()} > + Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let n=``;t&&(n=` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),X_(`${Nv} + Failed parsing: < ${e.toString()} > + Using the @chevrotain/regexp-to-ast library + Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+n)}}return[]}o(Pv,`getOptimizedStartCodesIndices`);function Fv(e,t,n){switch(e.type){case`Disjunction`:for(let r=0;r{if(typeof e==`number`)Iv(e,t,n);else{let r=e;if(n===!0)for(let e=r.from;e<=r.to;e++)Iv(e,t,n);else{for(let e=r.from;e<=r.to&&e=by){let e=r.from>=by?r.from:by,n=r.to,i=Sy(e),a=Sy(n);for(let e=i;e<=a;e++)t[e]=e}}}});break;case`Group`:Fv(a.value,t,n);break;default:throw Error(`Non Exhaustive Match`)}let o=a.quantifier!==void 0&&a.quantifier.atLeast===0;if(a.type===`Group`&&zv(a)===!1||a.type!==`Group`&&o===!1)break}break;default:throw Error(`non exhaustive match!`)}return H(t)}o(Fv,`firstCharOptimizedIndices`);function Iv(e,t,n){let r=Sy(e);t[r]=r,n===!0&&Lv(e,t)}o(Iv,`addOptimizedIdxToResult`);function Lv(e,t){let n=String.fromCharCode(e),r=n.toUpperCase();if(r!==n){let e=Sy(r.charCodeAt(0));t[e]=e}else{let e=n.toLowerCase();if(e!==n){let n=Sy(e.charCodeAt(0));t[n]=n}}}o(Lv,`handleIgnoreCase`);function Rv(e,t){return Hg(e.value,e=>{if(typeof e==`number`)return u_(t,e);{let n=e;return Hg(t,e=>n.from<=e&&e<=n.to)!==void 0}})}o(Rv,`findCode`);function zv(e){let t=e.quantifier;return t&&t.atLeast===0?!0:e.value?I(e.value)?Ng(e.value,zv):zv(e.value):!1}o(zv,`isWholeOptional`);var Bv=class extends ba{static{o(this,`CharCodeFinder`)}constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(this.found!==!0){switch(e.type){case`Lookahead`:this.visitLookahead(e);return;case`NegativeLookahead`:this.visitNegativeLookahead(e);return;case`Lookbehind`:this.visitLookbehind(e);return;case`NegativeLookbehind`:this.visitNegativeLookbehind(e);return}super.visitChildren(e)}}visitCharacter(e){u_(this.targetCharCodes,e.value)&&(this.found=!0)}visitSet(e){e.complement?Rv(e,this.targetCharCodes)===void 0&&(this.found=!0):Rv(e,this.targetCharCodes)!==void 0&&(this.found=!0)}};function Vv(e,t){if(t instanceof RegExp){let n=Av(t),r=new Bv(e);return r.visit(n),r.found}else return Hg(t,t=>u_(e,t.charCodeAt(0)))!==void 0}o(Vv,`canMatchCharCode`);var Hv=`PATTERN`,Uv=`defaultMode`,Wv=`modes`;function Gv(e,t){t=ug(t,{debug:!1,safeMode:!1,positionTracking:`full`,lineTerminatorCharacters:[`\r`,` +`],tracer:o((e,t)=>t(),`tracer`)});let n=t.tracer;n(`initCharCodeToOptimizedIndexMap`,()=>{Cy()});let r;n(`Reject Lexer.NA`,()=>{r=z_(e,e=>e[Hv]===Vy.NA)});let i=!1,a;n(`Transform Patterns`,()=>{i=!1,a=B(r,e=>{let t=e[Hv];if(S_(t)){let e=t.source;return e.length===1&&e!==`^`&&e!==`$`&&e!==`.`&&!t.ignoreCase?e:e.length===2&&e[0]===`\\`&&!u_([`d`,`D`,`s`,`S`,`t`,`r`,`n`,`t`,`0`,`c`,`b`,`B`,`f`,`v`,`w`,`W`],e[1])?e[1]:ly(t)}else if(Ss(t))return i=!0,{exec:t};else if(typeof t==`object`)return i=!0,t;else if(typeof t==`string`){if(t.length===1)return t;{let e=t.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`);return ly(new RegExp(e))}}else throw Error(`non exhaustive match`)})});let s,c,l,u,d;n(`misc mapping`,()=>{s=B(r,e=>e.tokenTypeIdx),c=B(r,e=>{let t=e.GROUP;if(t!==Vy.SKIPPED){if(i_(t))return t;if(w_(t))return!1;throw Error(`non exhaustive match`)}}),l=B(r,e=>{let t=e.LONGER_ALT;if(t)return I(t)?B(t,e=>p_(r,e)):[p_(r,t)]}),u=B(r,e=>e.PUSH_MODE),d=B(r,e=>V(e,`POP_MODE`))});let f;n(`Line Terminator Handling`,()=>{let e=vy(t.lineTerminatorCharacters);f=B(r,e=>!1),t.positionTracking!==`onlyOffset`&&(f=B(r,t=>V(t,`LINE_BREAKS`)?!!t.LINE_BREAKS:gy(t,e)===!1&&Vv(e,t.PATTERN)))});let p,m,h,g;n(`Misc Mapping #2`,()=>{p=B(r,py),m=B(a,my),h=L_(r,(e,t)=>{let n=t.GROUP;return i_(n)&&n!==Vy.SKIPPED&&(e[n]=[]),e},{}),g=B(a,(e,t)=>({pattern:a[t],longerAlt:l[t],canLineTerminator:f[t],isCustom:p[t],short:m[t],group:c[t],push:u[t],pop:d[t],tokenTypeIdx:s[t],tokenType:r[t]}))});let _=!0,v=[];return t.safeMode||n(`First Char Optimization`,()=>{v=L_(r,(e,n,r)=>{if(typeof n.PATTERN==`string`)yy(e,Sy(n.PATTERN.charCodeAt(0)),g[r]);else if(I(n.START_CHARS_HINT)){let t;z(n.START_CHARS_HINT,n=>{let i=Sy(typeof n==`string`?n.charCodeAt(0):n);t!==i&&(t=i,yy(e,i,g[r]))})}else if(S_(n.PATTERN))if(n.PATTERN.unicode)_=!1,t.ensureOptimizations&&X_(`${Nv} Unable to analyze < ${n.PATTERN.toString()} > pattern. + The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{let i=Pv(n.PATTERN,t.ensureOptimizations);U(i)&&(_=!1),z(i,t=>{yy(e,t,g[r])})}else t.ensureOptimizations&&X_(`${Nv} TokenType: <${n.name}> is using a custom token pattern without providing parameter. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),_=!1;return e},[])}),{emptyGroups:h,patternIdxToConfig:g,charCodeToPatternIdxToConfig:v,hasCustom:i,canBeOptimized:_}}o(Gv,`analyzeTokenTypes`);function Kv(e,t){let n=[],r=Jv(e);n=n.concat(r.errors);let i=Yv(r.valid),a=i.valid;return n=n.concat(i.errors),n=n.concat(qv(a)),n=n.concat(ry(a)),n=n.concat(iy(a,t)),n=n.concat(ay(a)),n}o(Kv,`validatePatterns`);function qv(e){let t=[],n=Lg(e,e=>S_(e[Hv]));return t=t.concat(Zv(n)),t=t.concat(ey(n)),t=t.concat(ty(n)),t=t.concat(ny(n)),t=t.concat(Qv(n)),t}o(qv,`validateRegExpPattern`);function Jv(e){let t=Lg(e,e=>!V(e,Hv));return{errors:B(t,e=>({message:`Token Type: ->`+e.name+`<- missing static 'PATTERN' property`,type:K.MISSING_PATTERN,tokenTypes:[e]})),valid:vg(e,t)}}o(Jv,`findMissingPatterns`);function Yv(e){let t=Lg(e,e=>{let t=e[Hv];return!S_(t)&&!Ss(t)&&!V(t,`exec`)&&!i_(t)});return{errors:B(t,e=>({message:`Token Type: ->`+e.name+`<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.`,type:K.INVALID_PATTERN,tokenTypes:[e]})),valid:vg(e,t)}}o(Yv,`findInvalidPatterns`);var Xv=/[^\\][$]/;function Zv(e){class t extends ba{static{o(this,`EndAnchorFinder`)}constructor(){super(...arguments),this.found=!1}visitEndAnchor(e){this.found=!0}}return B(Lg(e,e=>{let n=e.PATTERN;try{let e=Av(n),r=new t;return r.visit(e),r.found}catch{return Xv.test(n.source)}}),e=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+e.name+`<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:K.EOI_ANCHOR_FOUND,tokenTypes:[e]}))}o(Zv,`findEndOfInputAnchor`);function Qv(e){return B(Lg(e,e=>e.PATTERN.test(``)),e=>({message:`Token Type: ->`+e.name+`<- static 'PATTERN' must not match an empty string`,type:K.EMPTY_MATCH_PATTERN,tokenTypes:[e]}))}o(Qv,`findEmptyMatchRegExps`);var $v=/[^\\[][\^]|^\^/;function ey(e){class t extends ba{static{o(this,`StartAnchorFinder`)}constructor(){super(...arguments),this.found=!1}visitStartAnchor(e){this.found=!0}}return B(Lg(e,e=>{let n=e.PATTERN;try{let e=Av(n),r=new t;return r.visit(e),r.found}catch{return $v.test(n.source)}}),e=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+e.name+`<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:K.SOI_ANCHOR_FOUND,tokenTypes:[e]}))}o(ey,`findStartOfInputAnchor`);function ty(e){return B(Lg(e,e=>{let t=e[Hv];return t instanceof RegExp&&(t.multiline||t.global)}),e=>({message:`Token Type: ->`+e.name+`<- static 'PATTERN' may NOT contain global('g') or multiline('m')`,type:K.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[e]}))}o(ty,`findUnsupportedFlags`);function ny(e){let t=[],n=B(e,n=>L_(e,(e,r)=>n.PATTERN.source===r.PATTERN.source&&!u_(t,r)&&r.PATTERN!==Vy.NA?(t.push(r),e.push(r),e):e,[]));return n=wm(n),B(Lg(n,e=>e.length>1),e=>{let t=B(e,e=>e.name);return{message:`The same RegExp pattern ->${Wg(e).PATTERN}<-has been used in all of the following Token Types: ${t.join(`, `)} <-`,type:K.DUPLICATE_PATTERNS_FOUND,tokenTypes:e}})}o(ny,`findDuplicatePatterns`);function ry(e){return B(Lg(e,e=>{if(!V(e,`GROUP`))return!1;let t=e.GROUP;return t!==Vy.SKIPPED&&t!==Vy.NA&&!i_(t)}),e=>({message:`Token Type: ->`+e.name+`<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String`,type:K.INVALID_GROUP_TYPE_FOUND,tokenTypes:[e]}))}o(ry,`findInvalidGroupType`);function iy(e,t){return B(Lg(e,e=>e.PUSH_MODE!==void 0&&!u_(t,e.PUSH_MODE)),e=>({message:`Token Type: ->${e.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${e.PUSH_MODE}<-which does not exist`,type:K.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[e]}))}o(iy,`findModesThatDoNotExist`);function ay(e){let t=[],n=L_(e,(e,t,n)=>{let r=t.PATTERN;return r===Vy.NA||(i_(r)?e.push({str:r,idx:n,tokenType:t}):S_(r)&&sy(r)&&e.push({str:r.source,idx:n,tokenType:t})),e},[]);return z(e,(e,r)=>{z(n,({str:n,idx:i,tokenType:a})=>{if(r${a.name}<- can never be matched. +Because it appears AFTER the Token Type ->${e.name}<-in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;t.push({message:n,type:K.UNREACHABLE_PATTERN,tokenTypes:[e,a]})}})}),t}o(ay,`findUnreachablePatterns`);function oy(e,t){if(S_(t)){if(cy(t))return!1;let n=t.exec(e);return n!==null&&n.index===0}else if(Ss(t))return t(e,0,[],{});else if(V(t,`exec`))return t.exec(e,0,[],{});else if(typeof t==`string`)return t===e;else throw Error(`non exhaustive match`)}o(oy,`tryToMatchStrToPattern`);function sy(e){return Hg([`.`,`\\`,`[`,`]`,`|`,`^`,`$`,`(`,`)`,`?`,`*`,`+`,`{`],t=>e.source.indexOf(t)!==-1)===void 0}o(sy,`noMetaChar`);function cy(e){return/(\(\?=)|(\(\?!)|(\(\?<=)|(\(\? property in its definition +`,type:K.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),V(e,Wv)||r.push({message:`A MultiMode Lexer cannot be initialized without a <`+Wv+`> property in its definition +`,type:K.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),V(e,Wv)&&V(e,Uv)&&!V(e.modes,e.defaultMode)&&r.push({message:`A MultiMode Lexer cannot be initialized with a ${Uv}: <${e.defaultMode}>which does not exist +`,type:K.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),V(e,Wv)&&z(e.modes,(e,t)=>{z(e,(n,i)=>{w_(n)?r.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${t}> at index: <${i}> +`,type:K.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED}):V(n,`LONGER_ALT`)&&z(I(n.LONGER_ALT)?n.LONGER_ALT:[n.LONGER_ALT],i=>{!w_(i)&&!u_(e,i)&&r.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${i.name}> on token <${n.name}> outside of mode <${t}> +`,type:K.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})})}),r}o(uy,`performRuntimeChecks`);function dy(e,t,n){let r=[],i=!1,a=z_(wm(Ld(H(e.modes))),e=>e[Hv]===Vy.NA),o=vy(n);return t&&z(a,e=>{let t=gy(e,o);if(t!==!1){let n={message:_y(e,t),type:t.issue,tokenType:e};r.push(n)}else V(e,`LINE_BREAKS`)?e.LINE_BREAKS===!0&&(i=!0):Vv(o,e.PATTERN)&&(i=!0)}),t&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`,type:K.NO_LINE_BREAKS_FLAGS}),r}o(dy,`performWarningRuntimeChecks`);function fy(e){let t={};return z(eu(e),n=>{let r=e[n];if(I(r))t[n]=[];else throw Error(`non exhaustive match`)}),t}o(fy,`cloneEmptyGroups`);function py(e){let t=e.PATTERN;if(S_(t))return!1;if(Ss(t)||V(t,`exec`))return!0;if(i_(t))return!1;throw Error(`non exhaustive match`)}o(py,`isCustomPattern`);function my(e){return i_(e)&&e.length===1?e.charCodeAt(0):!1}o(my,`isShortPattern`);var hy={test:o(function(e){let t=e.length;for(let n=this.lastIndex;n Token Type + Root cause: ${t.errMsg}. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(t.issue===K.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. + The problem is in the <${e.name}> Token Type + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error(`non exhaustive match`)}o(_y,`buildLineBreakIssueMessage`);function vy(e){return B(e,e=>i_(e)?e.charCodeAt(0):e)}o(vy,`getCharCodes`);function yy(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}o(yy,`addToMapOfArrays`);var by=256,xy=[];function Sy(e){return e255?255+~~(e/255):e}}o(Cy,`initCharCodeToOptimizedIndexMap`);function wy(e,t){let n=e.tokenTypeIdx;return n===t.tokenTypeIdx||t.isParent===!0&&t.categoryMatchesMap[n]===!0}o(wy,`tokenStructuredMatcher`);function Ty(e,t){return e.tokenTypeIdx===t.tokenTypeIdx}o(Ty,`tokenStructuredMatcherNoCategories`);var Ey=1,Dy={};function Oy(e){let t=ky(e);Ay(t),My(t),jy(t),z(t,e=>{e.isParent=e.categoryMatches.length>0})}o(Oy,`augmentTokenTypes`);function ky(e){let t=Sm(e),n=e,r=!0;for(;r;){n=wm(Ld(B(n,e=>e.CATEGORIES)));let e=vg(n,t);t=t.concat(e),U(e)?r=!1:n=e}return t}o(ky,`expandCategories`);function Ay(e){z(e,e=>{Py(e)||(Dy[Ey]=e,e.tokenTypeIdx=Ey++),Fy(e)&&!I(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),Fy(e)||(e.CATEGORIES=[]),Iy(e)||(e.categoryMatches=[]),Ly(e)||(e.categoryMatchesMap={})})}o(Ay,`assignTokenDefaultProps`);function jy(e){z(e,e=>{e.categoryMatches=[],z(e.categoryMatchesMap,(t,n)=>{e.categoryMatches.push(Dy[n].tokenTypeIdx)})})}o(jy,`assignCategoriesTokensProp`);function My(e){z(e,e=>{Ny([],e)})}o(My,`assignCategoriesMapProp`);function Ny(e,t){z(e,e=>{t.categoryMatchesMap[e.tokenTypeIdx]=!0}),z(t.CATEGORIES,n=>{let r=e.concat(t);u_(r,n)||Ny(r,n)})}o(Ny,`singleAssignCategoriesToksMap`);function Py(e){return V(e,`tokenTypeIdx`)}o(Py,`hasShortKeyProperty`);function Fy(e){return V(e,`CATEGORIES`)}o(Fy,`hasCategoriesProperty`);function Iy(e){return V(e,`categoryMatches`)}o(Iy,`hasExtendingTokensTypesProperty`);function Ly(e){return V(e,`categoryMatchesMap`)}o(Ly,`hasExtendingTokensTypesMapProperty`);function Ry(e){return V(e,`tokenTypeIdx`)}o(Ry,`isTokenType`);var zy={buildUnableToPopLexerModeMessage(e){return`Unable to pop Lexer Mode after encountering Token ->${e.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(e,t,n,r,i,a){return`unexpected character: ->${e.charAt(t)}<- at offset: ${t}, skipped ${n} characters.`}},K;(function(e){e[e.MISSING_PATTERN=0]=`MISSING_PATTERN`,e[e.INVALID_PATTERN=1]=`INVALID_PATTERN`,e[e.EOI_ANCHOR_FOUND=2]=`EOI_ANCHOR_FOUND`,e[e.UNSUPPORTED_FLAGS_FOUND=3]=`UNSUPPORTED_FLAGS_FOUND`,e[e.DUPLICATE_PATTERNS_FOUND=4]=`DUPLICATE_PATTERNS_FOUND`,e[e.INVALID_GROUP_TYPE_FOUND=5]=`INVALID_GROUP_TYPE_FOUND`,e[e.PUSH_MODE_DOES_NOT_EXIST=6]=`PUSH_MODE_DOES_NOT_EXIST`,e[e.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]=`MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE`,e[e.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]=`MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY`,e[e.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]=`MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST`,e[e.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]=`LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED`,e[e.SOI_ANCHOR_FOUND=11]=`SOI_ANCHOR_FOUND`,e[e.EMPTY_MATCH_PATTERN=12]=`EMPTY_MATCH_PATTERN`,e[e.NO_LINE_BREAKS_FLAGS=13]=`NO_LINE_BREAKS_FLAGS`,e[e.UNREACHABLE_PATTERN=14]=`UNREACHABLE_PATTERN`,e[e.IDENTIFY_TERMINATOR=15]=`IDENTIFY_TERMINATOR`,e[e.CUSTOM_LINE_BREAK=16]=`CUSTOM_LINE_BREAK`,e[e.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]=`MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE`})(K||={});var By={deferDefinitionErrorsHandling:!1,positionTracking:`full`,lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` +`,`\r`],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:zy,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(By);var Vy=class{static{o(this,`Lexer`)}constructor(e,t=By){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(e,t)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;let n=Array(this.traceInitIndent+1).join(` `);this.traceInitIndent <${e}>`);let{time:r,value:i}=Q_(t),a=r>10?console.warn:console.log;return this.traceInitIndent time: ${r}ms`),this.traceInitIndent--,i}else return t()},typeof t==`boolean`)throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`);this.config=nu({},By,t);let n=this.config.traceInitPerf;n===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof n==`number`&&(this.traceInitMaxIdent=n,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT(`Lexer Constructor`,()=>{let n,r=!0;this.TRACE_INIT(`Lexer Config handling`,()=>{if(this.config.lineTerminatorsPattern===By.lineTerminatorsPattern)this.config.lineTerminatorsPattern=hy;else if(this.config.lineTerminatorCharacters===By.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(t.safeMode&&t.ensureOptimizations)throw Error(`"safeMode" and "ensureOptimizations" flags are mutually exclusive.`);this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),I(e)?n={modes:{defaultMode:Sm(e)},defaultMode:Uv}:(r=!1,n=Sm(e))}),this.config.skipValidations===!1&&(this.TRACE_INIT(`performRuntimeChecks`,()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(uy(n,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT(`performWarningRuntimeChecks`,()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(dy(n,this.trackStartLines,this.config.lineTerminatorCharacters))})),n.modes=n.modes?n.modes:{},z(n.modes,(e,t)=>{n.modes[t]=z_(e,e=>w_(e))});let i=eu(n.modes);if(z(n.modes,(e,n)=>{this.TRACE_INIT(`Mode: <${n}> processing`,()=>{if(this.modes.push(n),this.config.skipValidations===!1&&this.TRACE_INIT(`validatePatterns`,()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(Kv(e,i))}),U(this.lexerDefinitionErrors)){Oy(e);let r;this.TRACE_INIT(`analyzeTokenTypes`,()=>{r=Gv(e,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:t.positionTracking,ensureOptimizations:t.ensureOptimizations,safeMode:t.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[n]=r.patternIdxToConfig,this.charCodeToPatternIdxToConfig[n]=r.charCodeToPatternIdxToConfig,this.emptyGroups=nu({},this.emptyGroups,r.emptyGroups),this.hasCustom=r.hasCustom||this.hasCustom,this.canModeBeOptimized[n]=r.canBeOptimized}})}),this.defaultMode=n.defaultMode,!U(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){let e=B(this.lexerDefinitionErrors,e=>e.message).join(`----------------------- +`);throw Error(`Errors detected in definition of Lexer: +`+e)}z(this.lexerDefinitionWarning,e=>{Z_(e.message)}),this.TRACE_INIT(`Choosing sub-methods implementations`,()=>{if(r&&(this.handleModes=Ys),this.trackStartLines===!1&&(this.computeNewColumn=gs),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=Ys),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT(`Failed Optimization Warnings`,()=>{let e=L_(this.canModeBeOptimized,(e,t,n)=>(t===!1&&e.push(n),e),[]);if(t.ensureOptimizations&&!U(e))throw Error(`Lexer Modes: < ${e.join(`, `)} > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT(`clearRegExpParserCache`,()=>{jv()}),this.TRACE_INIT(`toFastProperties`,()=>{$_(this)})})}tokenize(e,t=this.defaultMode){if(!U(this.lexerDefinitionErrors)){let e=B(this.lexerDefinitionErrors,e=>e.message).join(`----------------------- +`);throw Error(`Unable to Tokenize because Errors detected in definition of Lexer: +`+e)}return this.tokenizeInternal(e,t)}tokenizeInternal(e,t){let n,r,i,a,s,c,l,u,d,f,p,m,h,g,_,v=e,y=v.length,b=0,x=0,ee=this.hasCustom?0:Math.floor(e.length/10),S=Array(ee),te=[],ne=this.trackStartLines?1:void 0,C=this.trackStartLines?1:void 0,re=fy(this.emptyGroups),ie=this.trackStartLines,ae=this.config.lineTerminatorsPattern,oe=0,se=[],ce=[],le=[],ue=[];Object.freeze(ue);let de=!1,w=o(e=>{if(le.length===1&&e.tokenType.PUSH_MODE===void 0){let t=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(e);te.push({offset:e.startOffset,line:e.startLine,column:e.startColumn,length:e.image.length,message:t})}else{le.pop();let e=bg(le);se=this.patternIdxToConfig[e],ce=this.charCodeToPatternIdxToConfig[e],oe=se.length;let t=this.canModeBeOptimized[e]&&this.config.safeMode===!1;de=!!(ce&&t)}},`pop_mode`);function T(e){le.push(e),ce=this.charCodeToPatternIdxToConfig[e],se=this.patternIdxToConfig[e],oe=se.length,oe=se.length;let t=this.canModeBeOptimized[e]&&this.config.safeMode===!1;de=!!(ce&&t)}o(T,`push_mode`),T.call(this,t);let E,D=this.config.recoveryEnabled;for(;bc.length){c=a,d=a.length,l=u,E=t;break}}}break}}if(d!==-1){if(f=E.group,f!==void 0&&(c=c===null?e.substring(b,b+d):c,p=E.tokenTypeIdx,m=this.createTokenInstance(c,b,p,E.tokenType,ne,C,d),this.handlePayload(m,l),f===!1?x=this.addToken(S,x,m):re[f].push(m)),ie===!0&&E.canLineTerminator===!0){let t=0,n,r;ae.lastIndex=0;do c=c===null?e.substring(b,b+d):c,n=ae.test(c),n===!0&&(r=ae.lastIndex-1,t++);while(n===!0);t===0?C=this.computeNewColumn(C,d):(ne+=t,C=d-r,this.updateTokenEndLineColumnLocation(m,f,r,t,ne,C,d))}else C=this.computeNewColumn(C,d);b+=d,this.handleModes(E,w,T,m)}else{let t=b,n=ne,i=C,a=D===!1;for(;a===!1&&b ${Hy(e)} <--`:`token of type --> ${e.name} <--`} but found --> '${t.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:e,ruleName:t}){return`Redundant input, expecting EOF but found: `+e.image},buildNoViableAltMessage({expectedPathsPerAlt:e,actual:t,previous:n,customUserDescription:r,ruleName:i}){let a=` +but found: '`+Wg(t).image+`'`;return r?`Expecting: `+r+a:`Expecting: one of these possible Token sequences: +${B(B(L_(e,(e,t)=>e.concat(t),[]),e=>`[${B(e,e=>Hy(e)).join(`, `)}]`),(e,t)=>` ${t+1}. ${e}`).join(` +`)}`+a},buildEarlyExitMessage({expectedIterationPaths:e,actual:t,customUserDescription:n,ruleName:r}){let i=` +but found: '`+Wg(t).image+`'`;return n?`Expecting: `+n+i:`Expecting: expecting at least one iteration which starts with one of these possible Token sequences:: + <${B(e,e=>`[${B(e,e=>Hy(e)).join(`,`)}]`).join(` ,`)}>`+i}};Object.freeze(ib);var ab={buildRuleNotFoundError(e,t){return`Invalid grammar, reference to a rule which is not defined: ->`+t.nonTerminalName+`<- +inside top level rule: ->`+e.name+`<-`}},ob={buildDuplicateFoundError(e,t){function n(e){return e instanceof G?e.terminalType.name:e instanceof rv?e.nonTerminalName:``}o(n,`getExtraProductionArgument`);let r=e.name,i=Wg(t),a=i.idx,s=_v(i),c=n(i),l=`->${s}${a>0?a:``}<- ${c?`with argument: ->${c}<-`:``} + appears more than once (${t.length} times) in the top level rule: ->${r}<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `;return l=l.replace(/[ \t]+/g,` `),l=l.replace(/\s\s+/g,` +`),l},buildNamespaceConflictError(e){return`Namespace conflict found in grammar. +The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${e.name}>. +To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(e){let t=B(e.prefixPath,e=>Hy(e)).join(`, `),n=e.alternation.idx===0?``:e.alternation.idx;return`Ambiguous alternatives: <${e.ambiguityIndices.join(` ,`)}> due to common lookahead prefix +in inside <${e.topLevelRule.name}> Rule, +<${t}> may appears as a prefix path in all these alternatives. +See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`},buildAlternationAmbiguityError(e){let t=e.alternation.idx===0?``:e.alternation.idx,n=e.prefixPath.length===0,r=`Ambiguous Alternatives Detected: <${e.ambiguityIndices.join(` ,`)}> in inside <${e.topLevelRule.name}> Rule, +`;if(n)r+=`These alternatives are all empty (match no tokens), making them indistinguishable. +Only the last alternative may be empty. +`;else{let t=B(e.prefixPath,e=>Hy(e)).join(`, `);r+=`<${t}> may appears as a prefix path in all these alternatives. +`}return r+=`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,r},buildEmptyRepetitionError(e){let t=_v(e.repetition);return e.repetition.idx!==0&&(t+=e.repetition.idx),`The repetition <${t}> within Rule <${e.topLevelRule.name}> can never consume any tokens. +This could lead to an infinite loop.`},buildTokenNameError(e){return`deprecated`},buildEmptyAlternationError(e){return`Ambiguous empty alternative: <${e.emptyChoiceIdx+1}> in inside <${e.topLevelRule.name}> Rule. +Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(e){return`An Alternation cannot have more than 256 alternatives: + inside <${e.topLevelRule.name}> Rule. + has ${e.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(e){let t=e.topLevelRule.name;return`Left Recursion found in grammar. +rule: <${t}> can be invoked from itself (directly or indirectly) +without consuming any Tokens. The grammar path that causes this is: + ${`${t} --> ${B(e.leftRecursionPath,e=>e.name).concat([t]).join(` --> `)}`} + To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(e){return`deprecated`},buildDuplicateRuleNameError(e){let t;return t=e.topLevelRule instanceof iv?e.topLevelRule.name:e.topLevelRule,`Duplicate definition, rule: ->${t}<- is already defined in the grammar: ->${e.grammarName}<-`}};function sb(e,t){let n=new cb(e,t);return n.resolveRefs(),n.errors}o(sb,`resolveGrammar`);var cb=class extends pv{static{o(this,`GastRefResolverVisitor`)}constructor(e,t){super(),this.nameToTopRule=e,this.errMsgProvider=t,this.errors=[]}resolveRefs(){z(H(this.nameToTopRule),e=>{this.currTopLevel=e,e.accept(this)})}visitNonTerminal(e){let t=this.nameToTopRule[e.nonTerminalName];if(t)e.referencedRule=t;else{let t=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:t,type:pS.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}}},lb=class extends vv{static{o(this,`AbstractNextPossibleTokensWalker`)}constructor(e,t){super(),this.topProd=e,this.path=t,this.possibleTokTypes=[],this.nextProductionName=``,this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error(`The path does not start with the walker's top Rule!`);return this.ruleStack=Sm(this.path.ruleStack).reverse(),this.occurrenceStack=Sm(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(e,t=[]){this.found||super.walk(e,t)}walkProdRef(e,t,n){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){let r=t.concat(n);this.updateExpectedNext(),this.walk(e.referencedRule,r)}}updateExpectedNext(){U(this.ruleStack)?(this.nextProductionName=``,this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}},ub=class extends lb{static{o(this,`NextAfterTokenWalker`)}constructor(e,t){super(e,t),this.path=t,this.nextTerminalName=``,this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(e,t,n){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){let e=new av({definition:t.concat(n)});this.possibleTokTypes=bv(e),this.found=!0}}},db=class extends vv{static{o(this,`AbstractNextTerminalAfterProductionWalker`)}constructor(e,t){super(),this.topRule=e,this.occurrence=t,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}},fb=class extends db{static{o(this,`NextTerminalAfterManyWalker`)}walkMany(e,t,n){if(e.idx===this.occurrence){let e=Wg(t.concat(n));this.result.isEndOfRule=e===void 0,e instanceof G&&(this.result.token=e.terminalType,this.result.occurrence=e.idx)}else super.walkMany(e,t,n)}},pb=class extends db{static{o(this,`NextTerminalAfterManySepWalker`)}walkManySep(e,t,n){if(e.idx===this.occurrence){let e=Wg(t.concat(n));this.result.isEndOfRule=e===void 0,e instanceof G&&(this.result.token=e.terminalType,this.result.occurrence=e.idx)}else super.walkManySep(e,t,n)}},mb=class extends db{static{o(this,`NextTerminalAfterAtLeastOneWalker`)}walkAtLeastOne(e,t,n){if(e.idx===this.occurrence){let e=Wg(t.concat(n));this.result.isEndOfRule=e===void 0,e instanceof G&&(this.result.token=e.terminalType,this.result.occurrence=e.idx)}else super.walkAtLeastOne(e,t,n)}},hb=class extends db{static{o(this,`NextTerminalAfterAtLeastOneSepWalker`)}walkAtLeastOneSep(e,t,n){if(e.idx===this.occurrence){let e=Wg(t.concat(n));this.result.isEndOfRule=e===void 0,e instanceof G&&(this.result.token=e.terminalType,this.result.occurrence=e.idx)}else super.walkAtLeastOneSep(e,t,n)}};function gb(e,t,n=[]){n=Sm(n);let r=[],i=0;function a(t){return t.concat(Sg(e,i+1))}o(a,`remainingPathWith`);function s(e){let i=gb(a(e),t,n);return r.concat(i)}for(o(s,`getAlternativesForProd`);n.length{U(e.definition)===!1&&(r=s(e.definition))}),r;else if(t instanceof G)n.push(t.terminalType);else throw Error(`non exhaustive match`);i++}return r.push({partialPath:n,suffixDef:Sg(e,i)}),r}o(gb,`possiblePathsFrom`);function _b(e,t,n,r){let i=`EXIT_NONE_TERMINAL`,a=[i],o=`EXIT_ALTERNATIVE`,s=!1,c=t.length,l=c-r-1,u=[],d=[];for(d.push({idx:-1,def:e,ruleStack:[],occurrenceStack:[]});!U(d);){let e=d.pop();if(e===o){s&&bg(d).idx<=l&&d.pop();continue}let r=e.def,f=e.idx,p=e.ruleStack,m=e.occurrenceStack;if(U(r))continue;let h=r[0];if(h===i){let e={idx:f,def:Sg(r),ruleStack:wg(p),occurrenceStack:wg(m)};d.push(e)}else if(h instanceof G)if(f=0;e--){let t={idx:f,def:h.definition[e].definition.concat(Sg(r)),ruleStack:p,occurrenceStack:m};d.push(t),d.push(o)}else if(h instanceof av)d.push({idx:f,def:h.definition.concat(Sg(r)),ruleStack:p,occurrenceStack:m});else if(h instanceof iv)d.push(vb(h,f,p,m));else throw Error(`non exhaustive match`)}return u}o(_b,`nextPossibleTokensAfter`);function vb(e,t,n,r){let i=Sm(n);i.push(e.name);let a=Sm(r);return a.push(1),{idx:t,def:e.definition,ruleStack:i,occurrenceStack:a}}o(vb,`expandTopLevelRule`);var q;(function(e){e[e.OPTION=0]=`OPTION`,e[e.REPETITION=1]=`REPETITION`,e[e.REPETITION_MANDATORY=2]=`REPETITION_MANDATORY`,e[e.REPETITION_MANDATORY_WITH_SEPARATOR=3]=`REPETITION_MANDATORY_WITH_SEPARATOR`,e[e.REPETITION_WITH_SEPARATOR=4]=`REPETITION_WITH_SEPARATOR`,e[e.ALTERNATION=5]=`ALTERNATION`})(q||={});function yb(e){if(e instanceof ov||e===`Option`)return q.OPTION;if(e instanceof W||e===`Repetition`)return q.REPETITION;if(e instanceof sv||e===`RepetitionMandatory`)return q.REPETITION_MANDATORY;if(e instanceof cv||e===`RepetitionMandatoryWithSeparator`)return q.REPETITION_MANDATORY_WITH_SEPARATOR;if(e instanceof lv||e===`RepetitionWithSeparator`)return q.REPETITION_WITH_SEPARATOR;if(e instanceof uv||e===`Alternation`)return q.ALTERNATION;throw Error(`non exhaustive match`)}o(yb,`getProdType`);function bb(e){let{occurrence:t,rule:n,prodType:r,maxLookahead:i}=e,a=yb(r);return a===q.ALTERNATION?jb(t,n,i):Mb(t,n,a,i)}o(bb,`getLookaheadPaths`);function xb(e,t,n,r,i,a){let o=jb(e,t,n);return a(o,r,Fb(o)?Ty:wy,i)}o(xb,`buildLookaheadFuncForOr`);function Sb(e,t,n,r,i,a){let o=Mb(e,t,i,n),s=Fb(o)?Ty:wy;return a(o[0],s,r)}o(Sb,`buildLookaheadFuncForOptionalProd`);function Cb(e,t,n,r){let i=e.length,a=Ng(e,e=>Ng(e,e=>e.length===1));if(t)return function(t){let r=B(t,e=>e.GATE);for(let t=0;tLd(e)),(e,t,n)=>(z(t,t=>{V(e,t.tokenTypeIdx)||(e[t.tokenTypeIdx]=n),z(t.categoryMatches,t=>{V(e,t)||(e[t]=n)})}),e),{});return function(){let e=this.LA(1);return t[e.tokenTypeIdx]}}else return function(){for(let t=0;te.length===1),i=e.length;if(r&&!n){let t=Ld(e);if(t.length===1&&U(t[0].categoryMatches)){let e=t[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===e}}else{let e=L_(t,(e,t,n)=>(e[t.tokenTypeIdx]=!0,z(t.categoryMatches,t=>{e[t]=!0}),e),[]);return function(){let t=this.LA(1);return e[t.tokenTypeIdx]===!0}}}else return function(){nextPath:for(let n=0;ngb([e],1)),r=Db(n.length),i=B(n,e=>{let t={};return z(e,e=>{z(Ob(e.partialPath),e=>{t[e]=!0})}),t}),a=n;for(let e=1;e<=t;e++){let n=a;a=Db(n.length);for(let o=0;o{z(Ob(e.partialPath),e=>{i[o][e]=!0})})}}}}return r}o(Ab,`lookAheadSequenceFromAlternatives`);function jb(e,t,n,r){let i=new Eb(e,q.ALTERNATION,r);return t.accept(i),Ab(i.result,n)}o(jb,`getLookaheadPathsForOr`);function Mb(e,t,n,r){let i=new Eb(e,n);t.accept(i);let a=i.result,o=new Tb(t,e,n).startWalking();return Ab([new av({definition:a}),new av({definition:o})],r)}o(Mb,`getLookaheadPathsForOptionalProd`);function Nb(e,t){compareOtherPath:for(let n=0;n{let r=t[n];return e===r||r.categoryMatchesMap[e.tokenTypeIdx]})}o(Pb,`isStrictPrefixOfPath`);function Fb(e){return Ng(e,e=>Ng(e,e=>Ng(e,e=>U(e.categoryMatches))))}o(Fb,`areTokenCategoriesNotUsed`);function Ib(e){return B(e.lookaheadStrategy.validate({rules:e.rules,tokenTypes:e.tokenTypes,grammarName:e.grammarName}),e=>Object.assign({type:pS.CUSTOM_LOOKAHEAD_VALIDATION},e))}o(Ib,`validateLookahead`);function Lb(e,t,n,r){let i=Yg(e,e=>Rb(e,n)),a=ex(e,t,n),o=Yg(e,e=>Xb(e,n)),s=Yg(e,t=>Hb(t,e,r,n));return i.concat(a,o,s)}o(Lb,`validateGrammar`);function Rb(e,t){let n=new Vb;e.accept(n);let r=n.allProductions;return B(H(N_(Zg(r,zb),e=>e.length>1)),n=>{let r=Wg(n),i=t.buildDuplicateFoundError(e,n),a=_v(r),o={message:i,type:pS.DUPLICATE_PRODUCTIONS,ruleName:e.name,dslName:a,occurrence:r.idx},s=Bb(r);return s&&(o.parameter=s),o})}o(Rb,`validateDuplicateProductions`);function zb(e){return`${_v(e)}_#_${e.idx}_#_${Bb(e)}`}o(zb,`identifyProductionForDuplicates`);function Bb(e){return e instanceof G?e.terminalType.name:e instanceof rv?e.nonTerminalName:``}o(Bb,`getExtraProductionArgument`);var Vb=class extends pv{static{o(this,`OccurrenceValidationCollector`)}constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(e){this.allProductions.push(e)}visitOption(e){this.allProductions.push(e)}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}visitAlternation(e){this.allProductions.push(e)}visitTerminal(e){this.allProductions.push(e)}};function Hb(e,t,n,r){let i=[];if(L_(t,(t,n)=>n.name===e.name?t+1:t,0)>1){let t=r.buildDuplicateRuleNameError({topLevelRule:e,grammarName:n});i.push({message:t,type:pS.DUPLICATE_RULE_NAME,ruleName:e.name})}return i}o(Hb,`validateRuleDoesNotAlreadyExist`);function Ub(e,t,n){let r=[],i;return u_(t,e)||(i=`Invalid rule override, rule: ->${e}<- cannot be overridden in the grammar: ->${n}<-as it is not defined in any of the super grammars `,r.push({message:i,type:pS.INVALID_RULE_OVERRIDE,ruleName:e})),r}o(Ub,`validateRuleIsOverridden`);function Wb(e,t,n,r=[]){let i=[],a=Gb(t.definition);if(U(a))return[];{let t=e.name;u_(a,e)&&i.push({message:n.buildLeftRecursionError({topLevelRule:e,leftRecursionPath:r}),type:pS.LEFT_RECURSION,ruleName:t});let o=Yg(vg(a,r.concat([e])),t=>{let i=Sm(r);return i.push(t),Wb(e,t,n,i)});return i.concat(o)}}o(Wb,`validateNoLeftRecursion`);function Gb(e){let t=[];if(U(e))return t;let n=Wg(e);if(n instanceof rv)t.push(n.referencedRule);else if(n instanceof av||n instanceof ov||n instanceof sv||n instanceof cv||n instanceof lv||n instanceof W)t=t.concat(Gb(n.definition));else if(n instanceof uv)t=Ld(B(n.definition,e=>Gb(e.definition)));else if(!(n instanceof G))throw Error(`non exhaustive match`);let r=hv(n),i=e.length>1;if(r&&i){let n=Sg(e);return t.concat(Gb(n))}else return t}o(Gb,`getFirstNoneTerminal`);var Kb=class extends pv{static{o(this,`OrCollector`)}constructor(){super(...arguments),this.alternations=[]}visitAlternation(e){this.alternations.push(e)}};function qb(e,t){let n=new Kb;e.accept(n);let r=n.alternations;return Yg(r,n=>Yg(wg(n.definition),(r,i)=>U(_b([r],[],wy,1))?[{message:t.buildEmptyAlternationError({topLevelRule:e,alternation:n,emptyChoiceIdx:i}),type:pS.NONE_LAST_EMPTY_ALT,ruleName:e.name,occurrence:n.idx,alternative:i+1}]:[]))}o(qb,`validateEmptyOrAlternative`);function Jb(e,t,n){let r=new Kb;e.accept(r);let i=r.alternations;return i=z_(i,e=>e.ignoreAmbiguities===!0),Yg(i,r=>{let i=r.idx,a=jb(i,e,r.maxLookahead||t,r),o=Qb(a,r,e,n),s=$b(a,r,e,n);return o.concat(s)})}o(Jb,`validateAmbiguousAlternationAlternatives`);var Yb=class extends pv{static{o(this,`RepetitionCollector`)}constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}};function Xb(e,t){let n=new Kb;e.accept(n);let r=n.alternations;return Yg(r,n=>n.definition.length>255?[{message:t.buildTooManyAlternativesError({topLevelRule:e,alternation:n}),type:pS.TOO_MANY_ALTS,ruleName:e.name,occurrence:n.idx}]:[])}o(Xb,`validateTooManyAlts`);function Zb(e,t,n){let r=[];return z(e,e=>{let i=new Yb;e.accept(i);let a=i.allProductions;z(a,i=>{let a=yb(i),o=i.maxLookahead||t,s=i.idx,c=Mb(s,e,a,o)[0];if(U(Ld(c))){let t=n.buildEmptyRepetitionError({topLevelRule:e,repetition:i});r.push({message:t,type:pS.NO_NON_EMPTY_LOOKAHEAD,ruleName:e.name})}})}),r}o(Zb,`validateSomeNonEmptyLookaheadPath`);function Qb(e,t,n,r){let i=[];return B(L_(e,(n,r,a)=>(t.definition[a].ignoreAmbiguities===!0||z(r,r=>{let o=[a];z(e,(e,n)=>{a!==n&&Nb(e,r)&&t.definition[n].ignoreAmbiguities!==!0&&o.push(n)}),o.length>1&&!Nb(i,r)&&(i.push(r),n.push({alts:o,path:r}))}),n),[]),e=>{let i=B(e.alts,e=>e+1);return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:i,prefixPath:e.path}),type:pS.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:t.idx,alternatives:e.alts}})}o(Qb,`checkAlternativesAmbiguities`);function $b(e,t,n,r){let i=L_(e,(e,t,n)=>{let r=B(t,e=>({idx:n,path:e}));return e.concat(r)},[]);return wm(Yg(i,e=>{if(t.definition[e.idx].ignoreAmbiguities===!0)return[];let a=e.idx,o=e.path;return B(Lg(i,e=>t.definition[e.idx].ignoreAmbiguities!==!0&&e.idx{let i=[e.idx+1,a+1],o=t.idx===0?``:t.idx;return{message:r.buildAlternationPrefixAmbiguityError({topLevelRule:n,alternation:t,ambiguityIndices:i,prefixPath:e.path}),type:pS.AMBIGUOUS_PREFIX_ALTS,ruleName:n.name,occurrence:o,alternatives:i}})}))}o($b,`checkPrefixAlternativesAmbiguities`);function ex(e,t,n){let r=[],i=B(t,e=>e.name);return z(e,e=>{let t=e.name;if(u_(i,t)){let i=n.buildNamespaceConflictError(e);r.push({message:i,type:pS.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:t})}}),r}o(ex,`checkTerminalAndNoneTerminalsNameSpace`);function tx(e){let t=ug(e,{errMsgProvider:ab}),n={};return z(e.rules,e=>{n[e.name]=e}),sb(n,t.errMsgProvider)}o(tx,`resolveGrammar`);function nx(e){return e=ug(e,{errMsgProvider:ob}),Lb(e.rules,e.tokenTypes,e.errMsgProvider,e.grammarName)}o(nx,`validateGrammar`);var rx=`MismatchedTokenException`,ix=`NoViableAltException`,ax=`EarlyExitException`,ox=`NotAllInputParsedException`,sx=[rx,ix,ax,ox];Object.freeze(sx);function cx(e){return u_(sx,e.name)}o(cx,`isRecognitionException`);var lx=class extends Error{static{o(this,`RecognitionException`)}constructor(e,t){super(e),this.token=t,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},ux=class extends lx{static{o(this,`MismatchedTokenException`)}constructor(e,t,n){super(e,t),this.previousToken=n,this.name=rx}},dx=class extends lx{static{o(this,`NoViableAltException`)}constructor(e,t,n){super(e,t),this.previousToken=n,this.name=ix}},fx=class extends lx{static{o(this,`NotAllInputParsedException`)}constructor(e,t){super(e,t),this.name=ox}},px=class extends lx{static{o(this,`EarlyExitException`)}constructor(e,t,n){super(e,t),this.previousToken=n,this.name=ax}},mx={},hx=`InRuleRecoveryException`,gx=class extends Error{static{o(this,`InRuleRecoveryException`)}constructor(e){super(e),this.name=hx}},_x=class{static{o(this,`Recoverable`)}initRecoverable(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=V(e,`recoveryEnabled`)?e.recoveryEnabled:dS.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=vx)}getTokenToInsert(e){let t=nb(e,``,NaN,NaN,NaN,NaN,NaN,NaN);return t.isInsertedInRecovery=!0,t}canTokenTypeBeInsertedInRecovery(e){return!0}canTokenTypeBeDeletedInRecovery(e){return!0}tryInRepetitionRecovery(e,t,n,r){let i=this.findReSyncTokenType(),a=this.exportLexerState(),s=[],c=!1,l=this.LA(1),u=this.LA(1),d=o(()=>{let e=this.LA(0),t=new ux(this.errorMessageProvider.buildMismatchTokenMessage({expected:r,actual:l,previous:e,ruleName:this.getCurrRuleFullName()}),l,this.LA(0));t.resyncedTokens=wg(s),this.SAVE_ERROR(t)},`generateErrorMessage`);for(;!c;)if(this.tokenMatcher(u,r)){d();return}else if(n.call(this)){d(),e.apply(this,t);return}else this.tokenMatcher(u,i)?c=!0:(u=this.SKIP_TOKEN(),this.addToResyncTokens(u,s));this.importLexerState(a)}shouldInRepetitionRecoveryBeTried(e,t,n){return!(n===!1||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,t)))}getFollowsForInRuleRecovery(e,t){let n=this.getCurrentGrammarPath(e,t);return this.getNextPossibleTokenTypes(n)}tryInRuleRecovery(e,t){if(this.canRecoverWithSingleTokenInsertion(e,t))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){let e=this.SKIP_TOKEN();return this.consumeToken(),e}throw new gx(`sad sad panda`)}canPerformInRuleRecovery(e,t){return this.canRecoverWithSingleTokenInsertion(e,t)||this.canRecoverWithSingleTokenDeletion(e)}canRecoverWithSingleTokenInsertion(e,t){if(!this.canTokenTypeBeInsertedInRecovery(e)||U(t))return!1;let n=this.LA(1);return Hg(t,e=>this.tokenMatcher(n,e))!==void 0}canRecoverWithSingleTokenDeletion(e){return this.canTokenTypeBeDeletedInRecovery(e)?this.tokenMatcher(this.LA(2),e):!1}isInCurrentRuleReSyncSet(e){let t=this.getCurrFollowKey();return u_(this.getFollowSetFromFollowKey(t),e)}findReSyncTokenType(){let e=this.flattenFollowSet(),t=this.LA(1),n=2;for(;;){let r=Hg(e,e=>rb(t,e));if(r!==void 0)return r;t=this.LA(n),n++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return mx;let e=this.getLastExplicitRuleShortName(),t=this.getLastExplicitRuleOccurrenceIndex(),n=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:t,inRule:this.shortRuleNameToFullName(n)}}buildFullFollowKeyStack(){let e=this.RULE_STACK,t=this.RULE_OCCURRENCE_STACK;return B(e,(n,r)=>r===0?mx:{ruleName:this.shortRuleNameToFullName(n),idxInCallingRule:t[r],inRule:this.shortRuleNameToFullName(e[r-1])})}flattenFollowSet(){return Ld(B(this.buildFullFollowKeyStack(),e=>this.getFollowSetFromFollowKey(e)))}getFollowSetFromFollowKey(e){if(e===mx)return[tb];let t=e.ruleName+e.idxInCallingRule+wv+e.inRule;return this.resyncFollows[t]}addToResyncTokens(e,t){return this.tokenMatcher(e,tb)||t.push(e),t}reSyncTo(e){let t=[],n=this.LA(1);for(;this.tokenMatcher(n,e)===!1;)n=this.SKIP_TOKEN(),this.addToResyncTokens(n,t);return wg(t)}attemptInRepetitionRecovery(e,t,n,r,i,a,o){}getCurrentGrammarPath(e,t){return{ruleStack:this.getHumanReadableRuleStack(),occurrenceStack:Sm(this.RULE_OCCURRENCE_STACK),lastTok:e,lastTokOccurrence:t}}getHumanReadableRuleStack(){return B(this.RULE_STACK,e=>this.shortRuleNameToFullName(e))}};function vx(e,t,n,r,i,a,o){let s=this.getKeyForAutomaticLookahead(r,i),c=this.firstAfterRepMap[s];if(c===void 0){let e=this.getCurrRuleFullName(),t=this.getGAstProductions()[e];c=new a(t,i).startWalking(),this.firstAfterRepMap[s]=c}let l=c.token,u=c.occurrence,d=c.isEndOfRule;this.RULE_STACK.length===1&&d&&l===void 0&&(l=tb,u=1),!(l===void 0||u===void 0)&&this.shouldInRepetitionRecoveryBeTried(l,u,o)&&this.tryInRepetitionRecovery(e,t,n,l)}o(vx,`attemptInRepetitionRecovery`);var yx=4,bx=8,xx=8,Sx=1<Wb(e,e,ob))}validateEmptyOrAlternatives(e){return Yg(e,e=>qb(e,ob))}validateAmbiguousAlternationAlternatives(e,t){return Yg(e,e=>Jb(e,t,ob))}validateSomeNonEmptyLookaheadPath(e,t){return Zb(e,t,ob)}buildLookaheadForAlternation(e){return xb(e.prodOccurrence,e.rule,e.maxLookahead,e.hasPredicates,e.dynamicTokensEnabled,Cb)}buildLookaheadForOptional(e){return Sb(e.prodOccurrence,e.rule,e.maxLookahead,e.dynamicTokensEnabled,yb(e.prodType),wb)}},Ax=class{static{o(this,`LooksAhead`)}initLooksAhead(e){this.dynamicTokensEnabled=V(e,`dynamicTokensEnabled`)?e.dynamicTokensEnabled:dS.dynamicTokensEnabled,this.maxLookahead=V(e,`maxLookahead`)?e.maxLookahead:dS.maxLookahead,this.lookaheadStrategy=V(e,`lookaheadStrategy`)?e.lookaheadStrategy:new kx({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(e){z(e,e=>{this.TRACE_INIT(`${e.name} Rule Lookahead`,()=>{let{alternation:t,repetition:n,option:r,repetitionMandatory:i,repetitionMandatoryWithSeparator:a,repetitionWithSeparator:o}=Mx(e);z(t,t=>{let n=t.idx===0?``:t.idx;this.TRACE_INIT(`${_v(t)}${n}`,()=>{let n=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:t.idx,rule:e,maxLookahead:t.maxLookahead||this.maxLookahead,hasPredicates:t.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),r=Ox(this.fullRuleNameToShort[e.name],Sx,t.idx);this.setLaFuncCache(r,n)})}),z(n,t=>{this.computeLookaheadFunc(e,t.idx,wx,`Repetition`,t.maxLookahead,_v(t))}),z(r,t=>{this.computeLookaheadFunc(e,t.idx,Cx,`Option`,t.maxLookahead,_v(t))}),z(i,t=>{this.computeLookaheadFunc(e,t.idx,Tx,`RepetitionMandatory`,t.maxLookahead,_v(t))}),z(a,t=>{this.computeLookaheadFunc(e,t.idx,Dx,`RepetitionMandatoryWithSeparator`,t.maxLookahead,_v(t))}),z(o,t=>{this.computeLookaheadFunc(e,t.idx,Ex,`RepetitionWithSeparator`,t.maxLookahead,_v(t))})})})}computeLookaheadFunc(e,t,n,r,i,a){this.TRACE_INIT(`${a}${t===0?``:t}`,()=>{let a=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:t,rule:e,maxLookahead:i||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:r}),o=Ox(this.fullRuleNameToShort[e.name],n,t);this.setLaFuncCache(o,a)})}getKeyForAutomaticLookahead(e,t){return Ox(this.getLastExplicitRuleShortName(),e,t)}getLaFuncFromCache(e){return this.lookAheadFuncsCache.get(e)}setLaFuncCache(e,t){this.lookAheadFuncsCache.set(e,t)}},jx=new class extends pv{static{o(this,`DslMethodsCollectorVisitor`)}constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(e){this.dslMethods.option.push(e)}visitRepetitionWithSeparator(e){this.dslMethods.repetitionWithSeparator.push(e)}visitRepetitionMandatory(e){this.dslMethods.repetitionMandatory.push(e)}visitRepetitionMandatoryWithSeparator(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)}visitRepetition(e){this.dslMethods.repetition.push(e)}visitAlternation(e){this.dslMethods.alternation.push(e)}};function Mx(e){jx.reset(),e.accept(jx);let t=jx.dslMethods;return jx.reset(),t}o(Mx,`collectMethods`);function Nx(e,t){isNaN(e.startOffset)===!0?(e.startOffset=t.startOffset,e.endOffset=t.endOffset):e.endOffsete.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: + ${t.join(` + +`).replace(/\n/g,` + `)}`)}},`validateVisitor`)},n.prototype.constructor=n,n._RULE_NAMES=t,n}o(Bx,`createBaseSemanticVisitorConstructor`);function Vx(e,t,n){let r=o(function(){},`derivedConstructor`);Rx(r,e+`BaseSemanticsWithDefaults`);let i=Object.create(n.prototype);return z(t,e=>{i[e]=zx}),r.prototype=i,r.prototype.constructor=r,r}o(Vx,`createBaseVisitorConstructorWithDefaults`);var Hx;(function(e){e[e.REDUNDANT_METHOD=0]=`REDUNDANT_METHOD`,e[e.MISSING_METHOD=1]=`MISSING_METHOD`})(Hx||={});function Ux(e,t){return Wx(e,t)}o(Ux,`validateVisitor`);function Wx(e,t){return wm(B(Lg(t,t=>Ss(e[t])===!1),t=>({msg:`Missing visitor method: <${t}> on ${e.constructor.name} CST Visitor.`,type:Hx.MISSING_METHOD,methodName:t})))}o(Wx,`validateMissingCstMethods`);var Gx=class{static{o(this,`TreeBuilder`)}initTreeBuilder(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=V(e,`nodeLocationTracking`)?e.nodeLocationTracking:dS.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=Ys,this.cstFinallyStateUpdate=Ys,this.cstPostTerminal=Ys,this.cstPostNonTerminal=Ys,this.cstPostRule=Ys;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Px,this.setNodeLocationFromNode=Px,this.cstPostRule=Ys,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=Ys,this.setNodeLocationFromNode=Ys,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Nx,this.setNodeLocationFromNode=Nx,this.cstPostRule=Ys,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=Ys,this.setNodeLocationFromNode=Ys,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=Ys,this.setNodeLocationFromNode=Ys,this.cstPostRule=Ys,this.setInitialNodeLocation=Ys;else throw Error(`Invalid config option: "${e.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(e){e.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(e){let t=this.LA(1);e.location={startOffset:t.startOffset,startLine:t.startLine,startColumn:t.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(e){let t={name:e,children:Object.create(null)};this.setInitialNodeLocation(t),this.CST_STACK.push(t)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(e){let t=this.LA(0),n=e.location;n.startOffset<=t.startOffset?(n.endOffset=t.endOffset,n.endLine=t.endLine,n.endColumn=t.endColumn):(n.startOffset=NaN,n.startLine=NaN,n.startColumn=NaN)}cstPostRuleOnlyOffset(e){let t=this.LA(0),n=e.location;n.startOffset<=t.startOffset?n.endOffset=t.endOffset:n.startOffset=NaN}cstPostTerminal(e,t){let n=this.CST_STACK[this.CST_STACK.length-1];Fx(n,t,e),this.setNodeLocationFromToken(n.location,t)}cstPostNonTerminal(e,t){let n=this.CST_STACK[this.CST_STACK.length-1];Ix(n,t,e),this.setNodeLocationFromNode(n.location,e.location)}getBaseCstVisitorConstructor(){if(w_(this.baseCstVisitorConstructor)){let e=Bx(this.className,eu(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(w_(this.baseCstVisitorWithDefaultsConstructor)){let e=Vx(this.className,eu(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){let e=this.RULE_STACK;return e[e.length-1]}getPreviousExplicitRuleShortName(){let e=this.RULE_STACK;return e[e.length-2]}getLastExplicitRuleOccurrenceIndex(){let e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]}},Kx=class{static{o(this,`LexerAdapter`)}initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(e){if(this.selfAnalysisDone!==!0)throw Error(`Missing invocation at the end of the Parser's constructor.`);this.reset(),this.tokVector=e,this.tokVectorLength=e.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):uS}LA(e){let t=this.currIdx+e;return t<0||this.tokVectorLength<=t?uS:this.tokVector[t]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(e){this.currIdx=e}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}},qx=class{static{o(this,`RecognizerApi`)}ACTION(e){return e.call(this)}consume(e,t,n){return this.consumeInternal(t,e,n)}subrule(e,t,n){return this.subruleInternal(t,e,n)}option(e,t){return this.optionInternal(t,e)}or(e,t){return this.orInternal(t,e)}many(e,t){return this.manyInternal(e,t)}atLeastOne(e,t){return this.atLeastOneInternal(e,t)}CONSUME(e,t){return this.consumeInternal(e,0,t)}CONSUME1(e,t){return this.consumeInternal(e,1,t)}CONSUME2(e,t){return this.consumeInternal(e,2,t)}CONSUME3(e,t){return this.consumeInternal(e,3,t)}CONSUME4(e,t){return this.consumeInternal(e,4,t)}CONSUME5(e,t){return this.consumeInternal(e,5,t)}CONSUME6(e,t){return this.consumeInternal(e,6,t)}CONSUME7(e,t){return this.consumeInternal(e,7,t)}CONSUME8(e,t){return this.consumeInternal(e,8,t)}CONSUME9(e,t){return this.consumeInternal(e,9,t)}SUBRULE(e,t){return this.subruleInternal(e,0,t)}SUBRULE1(e,t){return this.subruleInternal(e,1,t)}SUBRULE2(e,t){return this.subruleInternal(e,2,t)}SUBRULE3(e,t){return this.subruleInternal(e,3,t)}SUBRULE4(e,t){return this.subruleInternal(e,4,t)}SUBRULE5(e,t){return this.subruleInternal(e,5,t)}SUBRULE6(e,t){return this.subruleInternal(e,6,t)}SUBRULE7(e,t){return this.subruleInternal(e,7,t)}SUBRULE8(e,t){return this.subruleInternal(e,8,t)}SUBRULE9(e,t){return this.subruleInternal(e,9,t)}OPTION(e){return this.optionInternal(e,0)}OPTION1(e){return this.optionInternal(e,1)}OPTION2(e){return this.optionInternal(e,2)}OPTION3(e){return this.optionInternal(e,3)}OPTION4(e){return this.optionInternal(e,4)}OPTION5(e){return this.optionInternal(e,5)}OPTION6(e){return this.optionInternal(e,6)}OPTION7(e){return this.optionInternal(e,7)}OPTION8(e){return this.optionInternal(e,8)}OPTION9(e){return this.optionInternal(e,9)}OR(e){return this.orInternal(e,0)}OR1(e){return this.orInternal(e,1)}OR2(e){return this.orInternal(e,2)}OR3(e){return this.orInternal(e,3)}OR4(e){return this.orInternal(e,4)}OR5(e){return this.orInternal(e,5)}OR6(e){return this.orInternal(e,6)}OR7(e){return this.orInternal(e,7)}OR8(e){return this.orInternal(e,8)}OR9(e){return this.orInternal(e,9)}MANY(e){this.manyInternal(0,e)}MANY1(e){this.manyInternal(1,e)}MANY2(e){this.manyInternal(2,e)}MANY3(e){this.manyInternal(3,e)}MANY4(e){this.manyInternal(4,e)}MANY5(e){this.manyInternal(5,e)}MANY6(e){this.manyInternal(6,e)}MANY7(e){this.manyInternal(7,e)}MANY8(e){this.manyInternal(8,e)}MANY9(e){this.manyInternal(9,e)}MANY_SEP(e){this.manySepFirstInternal(0,e)}MANY_SEP1(e){this.manySepFirstInternal(1,e)}MANY_SEP2(e){this.manySepFirstInternal(2,e)}MANY_SEP3(e){this.manySepFirstInternal(3,e)}MANY_SEP4(e){this.manySepFirstInternal(4,e)}MANY_SEP5(e){this.manySepFirstInternal(5,e)}MANY_SEP6(e){this.manySepFirstInternal(6,e)}MANY_SEP7(e){this.manySepFirstInternal(7,e)}MANY_SEP8(e){this.manySepFirstInternal(8,e)}MANY_SEP9(e){this.manySepFirstInternal(9,e)}AT_LEAST_ONE(e){this.atLeastOneInternal(0,e)}AT_LEAST_ONE1(e){return this.atLeastOneInternal(1,e)}AT_LEAST_ONE2(e){this.atLeastOneInternal(2,e)}AT_LEAST_ONE3(e){this.atLeastOneInternal(3,e)}AT_LEAST_ONE4(e){this.atLeastOneInternal(4,e)}AT_LEAST_ONE5(e){this.atLeastOneInternal(5,e)}AT_LEAST_ONE6(e){this.atLeastOneInternal(6,e)}AT_LEAST_ONE7(e){this.atLeastOneInternal(7,e)}AT_LEAST_ONE8(e){this.atLeastOneInternal(8,e)}AT_LEAST_ONE9(e){this.atLeastOneInternal(9,e)}AT_LEAST_ONE_SEP(e){this.atLeastOneSepFirstInternal(0,e)}AT_LEAST_ONE_SEP1(e){this.atLeastOneSepFirstInternal(1,e)}AT_LEAST_ONE_SEP2(e){this.atLeastOneSepFirstInternal(2,e)}AT_LEAST_ONE_SEP3(e){this.atLeastOneSepFirstInternal(3,e)}AT_LEAST_ONE_SEP4(e){this.atLeastOneSepFirstInternal(4,e)}AT_LEAST_ONE_SEP5(e){this.atLeastOneSepFirstInternal(5,e)}AT_LEAST_ONE_SEP6(e){this.atLeastOneSepFirstInternal(6,e)}AT_LEAST_ONE_SEP7(e){this.atLeastOneSepFirstInternal(7,e)}AT_LEAST_ONE_SEP8(e){this.atLeastOneSepFirstInternal(8,e)}AT_LEAST_ONE_SEP9(e){this.atLeastOneSepFirstInternal(9,e)}RULE(e,t,n=fS){if(u_(this.definedRulesNames,e)){let t={message:ob.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:pS.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(t)}this.definedRulesNames.push(e);let r=this.defineRule(e,t,n);return this[e]=r,r}OVERRIDE_RULE(e,t,n=fS){let r=Ub(e,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(r);let i=this.defineRule(e,t,n);return this[e]=i,i}BACKTRACK(e,t){return function(){this.isBackTrackingStack.push(1);let n=this.saveRecogState();try{return e.apply(this,t),!0}catch(e){if(cx(e))return!1;throw e}finally{this.reloadRecogState(n),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return dv(H(this.gastProductionsCache))}},Jx=class{static{o(this,`RecognizerEngine`)}initRecognizerEngine(e,t){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=Ty,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},V(t,`serializedGrammar`))throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`);if(I(e)){if(U(e))throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset==`number`)throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`)}if(I(e))this.tokensMap=L_(e,(e,t)=>(e[t.name]=t,e),{});else if(V(e,`modes`)&&Ng(Ld(H(e.modes)),Ry)){let t=Y_(Ld(H(e.modes)));this.tokensMap=L_(t,(e,t)=>(e[t.name]=t,e),{})}else if(ts(e))this.tokensMap=Sm(e);else throw Error(` argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition`);this.tokensMap.EOF=tb;let n=Ng(V(e,`modes`)?Ld(H(e.modes)):H(e),e=>U(e.categoryMatches));this.tokenMatcher=n?Ty:wy,Oy(H(this.tokensMap))}defineRule(e,t,n){if(this.selfAnalysisDone)throw Error(`Grammar rule <${e}> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);let r=V(n,`resyncEnabled`)?n.resyncEnabled:fS.resyncEnabled,i=V(n,`recoveryValueFunc`)?n.recoveryValueFunc:fS.recoveryValueFunc,a=this.ruleShortNameIdx<t.call(this)&&e.call(this),`lookAheadFunc`)}}else i=e;if(r.call(this)===!0)return i.call(this)}atLeastOneInternal(e,t){let n=this.getKeyForAutomaticLookahead(Tx,e);return this.atLeastOneInternalLogic(e,t,n)}atLeastOneInternalLogic(e,t,n){let r=this.getLaFuncFromCache(n),i;if(typeof t!=`function`){i=t.DEF;let e=t.GATE;if(e!==void 0){let t=r;r=o(()=>e.call(this)&&t.call(this),`lookAheadFunc`)}}else i=t;if(r.call(this)===!0){let e=this.doSingleRepetition(i);for(;r.call(this)===!0&&e===!0;)e=this.doSingleRepetition(i)}else throw this.raiseEarlyExitException(e,q.REPETITION_MANDATORY,t.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[e,t],r,Tx,e,mb)}atLeastOneSepFirstInternal(e,t){let n=this.getKeyForAutomaticLookahead(Dx,e);this.atLeastOneSepFirstInternalLogic(e,t,n)}atLeastOneSepFirstInternalLogic(e,t,n){let r=t.DEF,i=t.SEP;if(this.getLaFuncFromCache(n).call(this)===!0){r.call(this);let t=o(()=>this.tokenMatcher(this.LA(1),i),`separatorLookAheadFunc`);for(;this.tokenMatcher(this.LA(1),i)===!0;)this.CONSUME(i),r.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,i,t,r,hb],t,Dx,e,hb)}else throw this.raiseEarlyExitException(e,q.REPETITION_MANDATORY_WITH_SEPARATOR,t.ERR_MSG)}manyInternal(e,t){let n=this.getKeyForAutomaticLookahead(wx,e);return this.manyInternalLogic(e,t,n)}manyInternalLogic(e,t,n){let r=this.getLaFuncFromCache(n),i;if(typeof t!=`function`){i=t.DEF;let e=t.GATE;if(e!==void 0){let t=r;r=o(()=>e.call(this)&&t.call(this),`lookaheadFunction`)}}else i=t;let a=!0;for(;r.call(this)===!0&&a===!0;)a=this.doSingleRepetition(i);this.attemptInRepetitionRecovery(this.manyInternal,[e,t],r,wx,e,fb,a)}manySepFirstInternal(e,t){let n=this.getKeyForAutomaticLookahead(Ex,e);this.manySepFirstInternalLogic(e,t,n)}manySepFirstInternalLogic(e,t,n){let r=t.DEF,i=t.SEP;if(this.getLaFuncFromCache(n).call(this)===!0){r.call(this);let t=o(()=>this.tokenMatcher(this.LA(1),i),`separatorLookAheadFunc`);for(;this.tokenMatcher(this.LA(1),i)===!0;)this.CONSUME(i),r.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,i,t,r,pb],t,Ex,e,pb)}}repetitionSepSecondInternal(e,t,n,r,i){for(;n();)this.CONSUME(t),r.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,t,n,r,i],n,Dx,e,i)}doSingleRepetition(e){let t=this.getLexerPosition();return e.call(this),this.getLexerPosition()>t}orInternal(e,t){let n=this.getKeyForAutomaticLookahead(Sx,t),r=I(e)?e:e.DEF,i=this.getLaFuncFromCache(n).call(this,r);if(i!==void 0)return r[i].ALT.call(this);this.raiseNoAltException(t,e.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){let e=this.LA(1),t=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new fx(t,e))}}subruleInternal(e,t,n){let r;try{let i=n===void 0?void 0:n.ARGS;return this.subruleIdx=t,r=e.apply(this,i),this.cstPostNonTerminal(r,n!==void 0&&n.LABEL!==void 0?n.LABEL:e.ruleName),r}catch(t){throw this.subruleInternalError(t,n,e.ruleName)}}subruleInternalError(e,t,n){throw cx(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,t!==void 0&&t.LABEL!==void 0?t.LABEL:n),delete e.partialCstResult),e}consumeInternal(e,t,n){let r;try{let t=this.LA(1);this.tokenMatcher(t,e)===!0?(this.consumeToken(),r=t):this.consumeInternalError(e,t,n)}catch(n){r=this.consumeInternalRecovery(e,t,n)}return this.cstPostTerminal(n!==void 0&&n.LABEL!==void 0?n.LABEL:e.name,r),r}consumeInternalError(e,t,n){let r,i=this.LA(0);throw r=n!==void 0&&n.ERR_MSG?n.ERR_MSG:this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:t,previous:i,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new ux(r,t,i))}consumeInternalRecovery(e,t,n){if(this.recoveryEnabled&&n.name===`MismatchedTokenException`&&!this.isBackTracking()){let r=this.getFollowsForInRuleRecovery(e,t);try{return this.tryInRuleRecovery(e,r)}catch(e){throw e.name===hx?n:e}}else throw n}saveRecogState(){let e=this.errors,t=Sm(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:t,CST_STACK:this.CST_STACK}}reloadRecogState(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK}ruleInvocationStateUpdate(e,t,n){this.RULE_OCCURRENCE_STACK.push(n),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(t)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){let e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]}shortRuleNameToFullName(e){return this.shortRuleNameToFull[e]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),tb)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}},Yx=class{static{o(this,`ErrorHandler`)}initErrorHandler(e){this._errors=[],this.errorMessageProvider=V(e,`errorMessageProvider`)?e.errorMessageProvider:dS.errorMessageProvider}SAVE_ERROR(e){if(cx(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:Sm(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error(`Trying to save an Error which is not a RecognitionException`)}get errors(){return Sm(this._errors)}set errors(e){this._errors=e}raiseEarlyExitException(e,t,n){let r=this.getCurrRuleFullName(),i=this.getGAstProductions()[r],a=Mb(e,i,t,this.maxLookahead)[0],o=[];for(let e=1;e<=this.maxLookahead;e++)o.push(this.LA(e));let s=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:o,previous:this.LA(0),customUserDescription:n,ruleName:r});throw this.SAVE_ERROR(new px(s,this.LA(1),this.LA(0)))}raiseNoAltException(e,t){let n=this.getCurrRuleFullName(),r=this.getGAstProductions()[n],i=jb(e,r,this.maxLookahead),a=[];for(let e=1;e<=this.maxLookahead;e++)a.push(this.LA(e));let o=this.LA(0),s=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:i,actual:a,previous:o,customUserDescription:t,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new dx(s,this.LA(1),o))}},Xx=class{static{o(this,`ContentAssist`)}initContentAssist(){}computeContentAssist(e,t){let n=this.gastProductionsCache[e];if(w_(n))throw Error(`Rule ->${e}<- does not exist in this grammar.`);return _b([n],t,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(e){let t=Wg(e.ruleStack),n=this.getGAstProductions()[t];return new ub(n,e).startWalking()}},Zx={description:`This Object indicates the Parser is during Recording Phase`};Object.freeze(Zx);var Qx=!0,$x=2**bx-1,eS=$y({name:`RECORDING_PHASE_TOKEN`,pattern:Vy.NA});Oy([eS]);var tS=nb(eS,`This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(tS);var nS={name:`This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}},rS=class{static{o(this,`GastRecorder`)}initGastRecorder(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT(`Enable Recording`,()=>{for(let e=0;e<10;e++){let t=e>0?e:``;this[`CONSUME${t}`]=function(t,n){return this.consumeInternalRecord(t,e,n)},this[`SUBRULE${t}`]=function(t,n){return this.subruleInternalRecord(t,e,n)},this[`OPTION${t}`]=function(t){return this.optionInternalRecord(t,e)},this[`OR${t}`]=function(t){return this.orInternalRecord(t,e)},this[`MANY${t}`]=function(t){this.manyInternalRecord(e,t)},this[`MANY_SEP${t}`]=function(t){this.manySepFirstInternalRecord(e,t)},this[`AT_LEAST_ONE${t}`]=function(t){this.atLeastOneInternalRecord(e,t)},this[`AT_LEAST_ONE_SEP${t}`]=function(t){this.atLeastOneSepFirstInternalRecord(e,t)}}this.consume=function(e,t,n){return this.consumeInternalRecord(t,e,n)},this.subrule=function(e,t,n){return this.subruleInternalRecord(t,e,n)},this.option=function(e,t){return this.optionInternalRecord(t,e)},this.or=function(e,t){return this.orInternalRecord(t,e)},this.many=function(e,t){this.manyInternalRecord(e,t)},this.atLeastOne=function(e,t){this.atLeastOneInternalRecord(e,t)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT(`Deleting Recording methods`,()=>{let e=this;for(let t=0;t<10;t++){let n=t>0?t:``;delete e[`CONSUME${n}`],delete e[`SUBRULE${n}`],delete e[`OPTION${n}`],delete e[`OR${n}`],delete e[`MANY${n}`],delete e[`MANY_SEP${n}`],delete e[`AT_LEAST_ONE${n}`],delete e[`AT_LEAST_ONE_SEP${n}`]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})}ACTION_RECORD(e){}BACKTRACK_RECORD(e,t){return()=>!0}LA_RECORD(e){return uS}topLevelRuleRecord(e,t){try{let n=new iv({definition:[],name:e});return n.name=e,this.recordingProdStack.push(n),t.call(this),this.recordingProdStack.pop(),n}catch(e){if(e.KNOWN_RECORDER_ERROR!==!0)try{e.message+=` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw e}throw e}}optionInternalRecord(e,t){return iS.call(this,ov,e,t)}atLeastOneInternalRecord(e,t){iS.call(this,sv,t,e)}atLeastOneSepFirstInternalRecord(e,t){iS.call(this,cv,t,e,Qx)}manyInternalRecord(e,t){iS.call(this,W,t,e)}manySepFirstInternalRecord(e,t){iS.call(this,lv,t,e,Qx)}orInternalRecord(e,t){return aS.call(this,e,t)}subruleInternalRecord(e,t,n){if(sS(t),!e||V(e,`ruleName`)===!1){let n=Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw n.KNOWN_RECORDER_ERROR=!0,n}let r=bg(this.recordingProdStack),i=e.ruleName,a=new rv({idx:t,nonTerminalName:i,label:n?.LABEL,referencedRule:void 0});return r.definition.push(a),this.outputCst?nS:Zx}consumeInternalRecord(e,t,n){if(sS(t),!Py(e)){let n=Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw n.KNOWN_RECORDER_ERROR=!0,n}let r=bg(this.recordingProdStack),i=new G({idx:t,terminalType:e,label:n?.LABEL});return r.definition.push(i),tS}};function iS(e,t,n,r=!1){sS(n);let i=bg(this.recordingProdStack),a=Ss(t)?t:t.DEF,o=new e({definition:[],idx:n});return r&&(o.separator=t.SEP),V(t,`MAX_LOOKAHEAD`)&&(o.maxLookahead=t.MAX_LOOKAHEAD),this.recordingProdStack.push(o),a.call(this),i.definition.push(o),this.recordingProdStack.pop(),Zx}o(iS,`recordProd`);function aS(e,t){sS(t);let n=bg(this.recordingProdStack),r=I(e)===!1,i=r===!1?e:e.DEF,a=new uv({definition:[],idx:t,ignoreAmbiguities:r&&e.IGNORE_AMBIGUITIES===!0});return V(e,`MAX_LOOKAHEAD`)&&(a.maxLookahead=e.MAX_LOOKAHEAD),a.hasPredicates=U_(i,e=>Ss(e.GATE)),n.definition.push(a),z(i,e=>{let t=new av({definition:[]});a.definition.push(t),V(e,`IGNORE_AMBIGUITIES`)?t.ignoreAmbiguities=e.IGNORE_AMBIGUITIES:V(e,`GATE`)&&(t.ignoreAmbiguities=!0),this.recordingProdStack.push(t),e.ALT.call(this),this.recordingProdStack.pop()}),Zx}o(aS,`recordOrProd`);function oS(e){return e===0?``:`${e}`}o(oS,`getIdxSuffix`);function sS(e){if(e<0||e>$x){let t=Error(`Invalid DSL Method idx value: <${e}> + Idx value must be a none negative value smaller than ${$x+1}`);throw t.KNOWN_RECORDER_ERROR=!0,t}}o(sS,`assertMethodIdxIsValid`);var cS=class{static{o(this,`PerformanceTracer`)}initPerformanceTracer(e){if(V(e,`traceInitPerf`)){let t=e.traceInitPerf,n=typeof t==`number`;this.traceInitMaxIdent=n?t:1/0,this.traceInitPerf=n?t>0:t}else this.traceInitMaxIdent=0,this.traceInitPerf=dS.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(e,t){if(this.traceInitPerf===!0){this.traceInitIndent++;let n=Array(this.traceInitIndent+1).join(` `);this.traceInitIndent <${e}>`);let{time:r,value:i}=Q_(t),a=r>10?console.warn:console.log;return this.traceInitIndent time: ${r}ms`),this.traceInitIndent--,i}else return t()}};function lS(e,t){t.forEach(t=>{let n=t.prototype;Object.getOwnPropertyNames(n).forEach(r=>{if(r===`constructor`)return;let i=Object.getOwnPropertyDescriptor(n,r);i&&(i.get||i.set)?Object.defineProperty(e.prototype,r,i):e.prototype[r]=t.prototype[r]})})}o(lS,`applyMixins`);var uS=nb(tb,``,NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(uS);var dS=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:ib,nodeLocationTracking:`none`,traceInitPerf:!1,skipValidations:!1}),fS=Object.freeze({recoveryValueFunc:o(()=>void 0,`recoveryValueFunc`),resyncEnabled:!0}),pS;(function(e){e[e.INVALID_RULE_NAME=0]=`INVALID_RULE_NAME`,e[e.DUPLICATE_RULE_NAME=1]=`DUPLICATE_RULE_NAME`,e[e.INVALID_RULE_OVERRIDE=2]=`INVALID_RULE_OVERRIDE`,e[e.DUPLICATE_PRODUCTIONS=3]=`DUPLICATE_PRODUCTIONS`,e[e.UNRESOLVED_SUBRULE_REF=4]=`UNRESOLVED_SUBRULE_REF`,e[e.LEFT_RECURSION=5]=`LEFT_RECURSION`,e[e.NONE_LAST_EMPTY_ALT=6]=`NONE_LAST_EMPTY_ALT`,e[e.AMBIGUOUS_ALTS=7]=`AMBIGUOUS_ALTS`,e[e.CONFLICT_TOKENS_RULES_NAMESPACE=8]=`CONFLICT_TOKENS_RULES_NAMESPACE`,e[e.INVALID_TOKEN_NAME=9]=`INVALID_TOKEN_NAME`,e[e.NO_NON_EMPTY_LOOKAHEAD=10]=`NO_NON_EMPTY_LOOKAHEAD`,e[e.AMBIGUOUS_PREFIX_ALTS=11]=`AMBIGUOUS_PREFIX_ALTS`,e[e.TOO_MANY_ALTS=12]=`TOO_MANY_ALTS`,e[e.CUSTOM_LOOKAHEAD_VALIDATION=13]=`CUSTOM_LOOKAHEAD_VALIDATION`})(pS||={});function mS(e=void 0){return function(){return e}}o(mS,`EMPTY_ALT`);var hS=class e{static{o(this,`Parser`)}static performSelfAnalysis(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT(`performSelfAnalysis`,()=>{let t;this.selfAnalysisDone=!0;let n=this.className;this.TRACE_INIT(`toFastProps`,()=>{$_(this)}),this.TRACE_INIT(`Grammar Recording`,()=>{try{this.enableRecording(),z(this.definedRulesNames,e=>{let t=this[e].originalGrammarAction,n;this.TRACE_INIT(`${e} Rule`,()=>{n=this.topLevelRuleRecord(e,t)}),this.gastProductionsCache[e]=n})}finally{this.disableRecording()}});let r=[];if(this.TRACE_INIT(`Grammar Resolving`,()=>{r=tx({rules:H(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(r)}),this.TRACE_INIT(`Grammar Validations`,()=>{if(U(r)&&this.skipValidations===!1){let e=nx({rules:H(this.gastProductionsCache),tokenTypes:H(this.tokensMap),errMsgProvider:ob,grammarName:n}),t=Ib({lookaheadStrategy:this.lookaheadStrategy,rules:H(this.gastProductionsCache),tokenTypes:H(this.tokensMap),grammarName:n});this.definitionErrors=this.definitionErrors.concat(e,t)}}),U(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT(`computeAllProdsFollows`,()=>{let e=Ev(H(this.gastProductionsCache));this.resyncFollows=e}),this.TRACE_INIT(`ComputeLookaheadFunctions`,()=>{var e,t;(t=(e=this.lookaheadStrategy).initialize)==null||t.call(e,{rules:H(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(H(this.gastProductionsCache))})),!e.DEFER_DEFINITION_ERRORS_HANDLING&&!U(this.definitionErrors))throw t=B(this.definitionErrors,e=>e.message),Error(`Parser Definition Errors detected: + ${t.join(` +------------------------------- +`)}`)})}constructor(e,t){this.definitionErrors=[],this.selfAnalysisDone=!1;let n=this;if(n.initErrorHandler(t),n.initLexerAdapter(),n.initLooksAhead(t),n.initRecognizerEngine(e,t),n.initRecoverable(t),n.initTreeBuilder(t),n.initContentAssist(),n.initGastRecorder(t),n.initPerformanceTracer(t),V(t,`ignoredIssues`))throw Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`);this.skipValidations=V(t,`skipValidations`)?t.skipValidations:dS.skipValidations}};hS.DEFER_DEFINITION_ERRORS_HANDLING=!1,lS(hS,[_x,Ax,Gx,Kx,Jx,qx,Yx,Xx,rS,cS]);var gS=class extends hS{static{o(this,`EmbeddedActionsParser`)}constructor(e,t=dS){let n=Sm(t);n.outputCst=!1,super(e,n)}};function _S(e,t){for(var n=-1,r=e==null?0:e.length,i=Array(r);++n-1}o(AS,`listCacheHas`);var jS=AS;function MS(e,t){var n=this.__data__,r=wS(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}o(MS,`listCacheSet`);var NS=MS;function PS(e){var t=-1,n=e==null?0:e.length;for(this.clear();++ts))return!1;var l=a.get(e),u=a.get(t);if(l&&u)return l==t&&u==e;var d=-1,f=!0,p=n&Nw?new Dw:void 0;for(a.set(e,t),a.set(t,e);++d-1&&e%1==0&&e-1&&e%1==0&&e<=LT}o(RT,`isLength`);var zT=RT,BT=`[object Arguments]`,VT=`[object Array]`,HT=`[object Boolean]`,UT=`[object Date]`,WT=`[object Error]`,GT=`[object Function]`,KT=`[object Map]`,qT=`[object Number]`,JT=`[object Object]`,YT=`[object RegExp]`,XT=`[object Set]`,ZT=`[object String]`,QT=`[object WeakMap]`,$T=`[object ArrayBuffer]`,eE=`[object DataView]`,tE=`[object Float32Array]`,nE=`[object Float64Array]`,rE=`[object Int8Array]`,iE=`[object Int16Array]`,aE=`[object Int32Array]`,oE=`[object Uint8Array]`,sE=`[object Uint8ClampedArray]`,cE=`[object Uint16Array]`,lE=`[object Uint32Array]`,J={};J[tE]=J[nE]=J[rE]=J[iE]=J[aE]=J[oE]=J[sE]=J[cE]=J[lE]=!0,J[BT]=J[VT]=J[$T]=J[HT]=J[eE]=J[UT]=J[WT]=J[GT]=J[KT]=J[qT]=J[JT]=J[YT]=J[XT]=J[ZT]=J[QT]=!1;function uE(e){return yT(e)&&zT(e.length)&&!!J[sC(e)]}o(uE,`baseIsTypedArray`);var dE=uE;function fE(e){return function(t){return e(t)}}o(fE,`baseUnary`);var pE=fE,mE=typeof exports==`object`&&exports&&!exports.nodeType&&exports,hE=mE&&typeof module==`object`&&module&&!module.nodeType&&module,gE=hE&&hE.exports===mE&&WS.process,_E=(function(){try{return hE&&hE.require&&hE.require(`util`).types||gE&&gE.binding&&gE.binding(`util`)}catch{}})(),vE=_E&&_E.isTypedArray,yE=vE?pE(vE):dE,bE=Object.prototype.hasOwnProperty;function xE(e,t){var n=oT(e),r=!n&&ET(e),i=!n&&!r&&MT(e),a=!n&&!r&&!i&&yE(e),o=n||r||i||a,s=o?_T(e.length,String):[],c=s.length;for(var l in e)(t||bE.call(e,l))&&!(o&&(l==`length`||i&&(l==`offset`||l==`parent`)||a&&(l==`buffer`||l==`byteLength`||l==`byteOffset`)||IT(l,c)))&&s.push(l);return s}o(xE,`arrayLikeKeys`);var SE=xE,CE=Object.prototype;function wE(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||CE)}o(wE,`isPrototype`);var TE=wE;function EE(e,t){return function(n){return e(t(n))}}o(EE,`overArg`);var DE=EE(Object.keys,Object),OE=Object.prototype.hasOwnProperty;function kE(e){if(!TE(e))return DE(e);var t=[];for(var n in Object(e))OE.call(e,n)&&n!=`constructor`&&t.push(n);return t}o(kE,`baseKeys`);var AE=kE;function jE(e){return e!=null&&zT(e.length)&&!hC(e)}o(jE,`isArrayLike`);var ME=jE;function NE(e){return ME(e)?SE(e):AE(e)}o(NE,`keys`);var PE=NE;function FE(e){return cT(e,PE,hT)}o(FE,`getAllKeys`);var IE=FE,LE=1,RE=Object.prototype.hasOwnProperty;function zE(e,t,n,r,i,a){var o=n&LE,s=IE(e),c=s.length;if(c!=IE(t).length&&!o)return!1;for(var l=c;l--;){var u=s[l];if(!(o?u in t:RE.call(t,u)))return!1}var d=a.get(e),f=a.get(t);if(d&&f)return d==t&&f==e;var p=!0;a.set(e,t),a.set(t,e);for(var m=o;++lek(e,t,n)))}o(ak,`alternation`);function ok(e,t,n){let r=X(e,t,n,{type:RO});return dk(e,r),uk(e,t,n,fk(e,t,r,n,sk(e,t,n)))}o(ok,`option`);function sk(e,t,n){let r=IO(MO(n.definition,n=>ek(e,t,n)),e=>e!==void 0);return r.length===1?r[0]:r.length===0?void 0:mk(e,r)}o(sk,`block`);function ck(e,t,n,r,i){let a=r.left,o=r.right,s=X(e,t,n,{type:KO});dk(e,s);let c=X(e,t,n,{type:qO});return a.loopback=s,c.loopback=s,e.decisionMap[LO(t,i?`RepetitionMandatoryWithSeparator`:`RepetitionMandatory`,n.idx)]=s,Y(o,s),i===void 0?(Y(s,a),Y(s,c)):(Y(s,c),Y(s,i.left),Y(i.right,a)),{left:a,right:c}}o(ck,`plus`);function lk(e,t,n,r,i){let a=r.left,o=r.right,s=X(e,t,n,{type:GO});dk(e,s);let c=X(e,t,n,{type:qO}),l=X(e,t,n,{type:WO});return s.loopback=l,c.loopback=l,Y(s,a),Y(s,c),Y(o,l),i===void 0?Y(l,s):(Y(l,c),Y(l,i.left),Y(i.right,a)),e.decisionMap[LO(t,i?`RepetitionWithSeparator`:`Repetition`,n.idx)]=s,{left:s,right:c}}o(lk,`star`);function uk(e,t,n,r){let i=r.left,a=r.right;return Y(i,a),e.decisionMap[LO(t,`Option`,n.idx)]=i,r}o(uk,`optional`);function dk(e,t){return e.decisionStates.push(t),t.decision=e.decisionStates.length-1,t.decision}o(dk,`defineDecisionState`);function fk(e,t,n,r,...i){let a=X(e,t,r,{type:UO,start:n});n.end=a;for(let e of i)e===void 0?Y(n,a):(Y(n,e.left),Y(e.right,a));let o={left:n,right:a};return e.decisionMap[LO(t,pk(r),r.idx)]=n,o}o(fk,`makeAlts`);function pk(e){if(e instanceof uv)return`Alternation`;if(e instanceof ov)return`Option`;if(e instanceof W)return`Repetition`;if(e instanceof lv)return`RepetitionWithSeparator`;if(e instanceof sv)return`RepetitionMandatory`;if(e instanceof cv)return`RepetitionMandatoryWithSeparator`;throw Error(`Invalid production type encountered`)}o(pk,`getProdType`);function mk(e,t){let n=t.length;for(let r=0;re.alt)}get key(){let e=``;for(let t in this.map)e+=t+`:`;return e}};function Sk(e,t=!0){return`${t?`a${e.alt}`:``}s${e.state.stateNumber}:${e.stack.map(e=>e.stateNumber.toString()).join(`_`)}`}o(Sk,`getATNConfigKey`);function Ck(e,t,n){for(var r=-1,i=e.length;++r0&&n(s)?t>1?Mk(s,t-1,n,r,i):aT(i,s):r||(i[i.length]=s)}return i}o(Mk,`baseFlatten`);var Nk=Mk;function Pk(e,t){return Nk(MO(e,t),1)}o(Pk,`flatMap`);var Fk=Pk;function Ik(e,t,n,r){for(var i=e.length,a=n+(r?1:-1);r?a--:++a-1}o(Wk,`arrayIncludes`);var Gk=Wk;function Kk(e,t,n){for(var r=-1,i=e==null?0:e.length;++r=Zk){var l=t?null:Xk(e);if(l)return Bw(l);o=!1,i=jw,c=new Dw}else c=t?[]:s;outer:for(;++r{let i=r.toString(),a=n[i];return a===void 0?(a={atnStartState:e,decision:t,states:{}},n[i]=a,a):a}}o(xA,`createDFACache`);var SA=class{static{o(this,`PredicateSet`)}constructor(){this.predicates=[]}is(e){return e>=this.predicates.length||this.predicates[e]}set(e,t){this.predicates[e]=t}toString(){let e=``,t=this.predicates.length;for(let n=0;nconsole.log(e))}initialize(e){this.atn=QO(e.rules),this.dfas=EA(this.atn)}validateAmbiguousAlternationAlternatives(){return[]}validateEmptyOrAlternatives(){return[]}buildLookaheadForAlternation(e){let{prodOccurrence:t,rule:n,hasPredicates:r,dynamicTokensEnabled:i}=e,a=this.dfas,o=this.logging,s=LO(n,`Alternation`,t),c=this.atn.decisionMap[s].decision,l=MO(bb({maxLookahead:1,occurrence:t,prodType:`Alternation`,rule:n}),e=>MO(e,e=>e[0]));if(TA(l,!1)&&!i){let e=bA(l,(e,t,n)=>(lA(t,t=>{t&&(e[t.tokenTypeIdx]=n,lA(t.categoryMatches,t=>{e[t]=n}))}),e),{});return r?function(t){let n=this.LA(1),r=e[n.tokenTypeIdx];if(t!==void 0&&r!==void 0){let e=t[r]?.GATE;if(e!==void 0&&e.call(this)===!1)return}return r}:function(){let t=this.LA(1);return e[t.tokenTypeIdx]}}else if(r)return function(e){let t=new SA,n=e===void 0?0:e.length;for(let r=0;rMO(e,e=>e[0]));if(TA(l)&&l[0][0]&&!i){let e=l[0],t=rA(e);if(t.length===1&&mA(t[0].categoryMatches)){let e=t[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===e}}else{let e=bA(t,(e,t)=>(t!==void 0&&(e[t.tokenTypeIdx]=!0,lA(t.categoryMatches,t=>{e[t]=!0})),e),{});return function(){let t=this.LA(1);return e[t.tokenTypeIdx]===!0}}}return function(){let e=DA.call(this,a,c,CA,o);return typeof e!=`object`&&e===0}}};function TA(e,t=!0){let n=new Set;for(let r of e){let e=new Set;for(let i of r){if(i===void 0){if(t)break;return!1}let r=[i.tokenTypeIdx].concat(i.categoryMatches);for(let t of r)if(n.has(t)){if(!e.has(t))return!1}else n.add(t),e.add(t)}}return!0}o(TA,`isLL1Sequence`);function EA(e){let t=e.decisionStates.length,n=Array(t);for(let r=0;rHy(e)).join(`, `),n=e.production.idx===0?``:e.production.idx,r=`Ambiguous Alternatives Detected: <${e.ambiguityIndices.join(`, `)}> in <${MA(e.production)}${n}> inside <${e.topLevelRule.name}> Rule, +<${t}> may appears as a prefix path in all these alternatives. +`;return r+=`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,r}o(jA,`buildAmbiguityError`);function MA(e){if(e instanceof rv)return`SUBRULE`;if(e instanceof ov)return`OPTION`;if(e instanceof uv)return`OR`;if(e instanceof sv)return`AT_LEAST_ONE`;if(e instanceof cv)return`AT_LEAST_ONE_SEP`;if(e instanceof lv)return`MANY_SEP`;if(e instanceof W)return`MANY`;if(e instanceof G)return`CONSUME`;throw Error(`non exhaustive match`)}o(MA,`getProductionDslName`);function NA(e,t,n){return{actualToken:n,possibleTokenTypes:tA(Fk(t.configs.elements,e=>e.state.transitions).filter(e=>e instanceof YO).map(e=>e.tokenType),e=>e.tokenTypeIdx),tokenPath:e}}o(NA,`buildAdaptivePredictError`);function PA(e,t){return e.edges[t.tokenTypeIdx]}o(PA,`getExistingTargetState`);function FA(e,t,n){let r=new xk,i=[];for(let a of e.elements){if(n.is(a.alt)===!1)continue;if(a.state.type===HO){i.push(a);continue}let e=a.state.transitions.length;for(let n=0;n0&&!WA(a))for(let e of i)a.add(e);return a}o(FA,`computeReachSet`);function IA(e,t){if(e instanceof YO&&rb(t,e.tokenType))return e.target}o(IA,`getReachableTarget`);function LA(e,t){let n;for(let r of e.elements)if(t.is(r.alt)===!0){if(n===void 0)n=r.alt;else if(n!==r.alt)return}return n}o(LA,`getUniqueAlt`);function RA(e){return{configs:e,edges:{},isAcceptState:!1,prediction:-1}}o(RA,`newDFAState`);function zA(e,t,n,r){return r=BA(e,r),t.edges[n.tokenTypeIdx]=r,r}o(zA,`addDFAEdge`);function BA(e,t){if(t===bk)return t;let n=t.configs.key,r=e.states[n];return r===void 0?(t.configs.finalize(),e.states[n]=t,t):r}o(BA,`addDFAState`);function VA(e){let t=new xk,n=e.transitions.length;for(let r=0;r0){let n=[...e.stack];HA({state:n.pop(),alt:e.alt,stack:n},t)}else t.add(e);return}n.epsilonOnlyTransitions||t.add(e);let r=n.transitions.length;for(let i=0;i1)return!0;return!1}o(JA,`hasConflictingAltSet`);function YA(e){for(let t of Array.from(e.values()))if(Object.keys(t).length===1)return!0;return!1}o(YA,`hasStateAssociatedWithOneAlt`),ht();var XA=class{static{o(this,`CstNodeBuilder`)}constructor(){this.nodeStack=[]}get current(){return this.nodeStack[this.nodeStack.length-1]??this.rootNode}buildRootNode(e){return this.rootNode=new tj(e),this.rootNode.root=this.rootNode,this.nodeStack=[this.rootNode],this.rootNode}buildCompositeNode(e){let t=new $A;return t.grammarSource=e,t.root=this.rootNode,this.current.content.push(t),this.nodeStack.push(t),t}buildLeafNode(e,t){let n=new QA(e.startOffset,e.image.length,zi(e),e.tokenType,!t);return n.grammarSource=t,n.root=this.rootNode,this.current.content.push(n),n}removeNode(e){let t=e.container;if(t){let n=t.content.indexOf(e);n>=0&&t.content.splice(n,1)}}addHiddenNodes(e){let t=[];for(let n of e){let e=new QA(n.startOffset,n.image.length,zi(n),n.tokenType,!0);e.root=this.rootNode,t.push(e)}let n=this.current,r=!1;if(n.content.length>0){n.content.push(...t);return}for(;n.container;){let e=n.container.content.indexOf(n);if(e>0){n.container.content.splice(e,0,...t),r=!0;break}n=n.container}r||this.rootNode.content.unshift(...t)}construct(e){let t=this.current;typeof e.$type==`string`&&!e.$infix&&(this.current.astNode=e),e.$cstNode=t;let n=this.nodeStack.pop();n?.content.length===0&&this.removeNode(n)}},ZA=class{static{o(this,`AbstractCstNode`)}get hidden(){return!1}get astNode(){let e=typeof this._astNode?.$type==`string`?this._astNode:this.container?.astNode;if(!e)throw Error(`This node has no associated AST element`);return e}set astNode(e){this._astNode=e}get text(){return this.root.fullText.substring(this.offset,this.end)}},QA=class extends ZA{static{o(this,`LeafCstNodeImpl`)}get offset(){return this._offset}get length(){return this._length}get end(){return this._offset+this._length}get hidden(){return this._hidden}get tokenType(){return this._tokenType}get range(){return this._range}constructor(e,t,n,r,i=!1){super(),this._hidden=i,this._offset=e,this._tokenType=r,this._length=t,this._range=n}},$A=class extends ZA{static{o(this,`CompositeCstNodeImpl`)}constructor(){super(...arguments),this.content=new ej(this)}get offset(){return this.firstNonHiddenNode?.offset??0}get length(){return this.end-this.offset}get end(){return this.lastNonHiddenNode?.end??0}get range(){let e=this.firstNonHiddenNode,t=this.lastNonHiddenNode;if(e&&t){if(this._rangeCache===void 0){let{range:n}=e,{range:r}=t;this._rangeCache={start:n.start,end:r.end.line=0;e--){let t=this.content[e];if(!t.hidden)return t}return this.content[this.content.length-1]}},ej=class e extends Array{static{o(this,`CstNodeContainer`)}constructor(t){super(),this.parent=t,Object.setPrototypeOf(this,e.prototype)}push(...e){return this.addParents(e),super.push(...e)}unshift(...e){return this.addParents(e),super.unshift(...e)}splice(e,t,...n){return this.addParents(n),super.splice(e,t,...n)}addParents(e){for(let t of e)t.container=this.parent}},tj=class extends $A{static{o(this,`RootCstNodeImpl`)}get text(){return this._text.substring(this.offset,this.end)}get fullText(){return this._text}constructor(e){super(),this._text=``,this._text=e??``}},nj=Symbol(`Datatype`);function rj(e){return e.$type===nj}o(rj,`isDataTypeNode`);var ij=`​`,aj=o(e=>e.endsWith(ij)?e:e+ij,`withRuleSuffix`),oj=class{static{o(this,`AbstractLangiumParser`)}constructor(e){this._unorderedGroups=new Map,this.allRules=new Map,this.lexer=e.parser.Lexer;let t=this.lexer.definition,n=e.LanguageMetaData.mode===`production`;e.shared.profilers.LangiumProfiler?.isActive(`parsing`)?this.wrapper=new pj(t,{...e.parser.ParserConfig,skipValidations:n,errorMessageProvider:e.parser.ParserErrorMessageProvider},e.shared.profilers.LangiumProfiler.createTask(`parsing`,e.LanguageMetaData.languageId)):this.wrapper=new fj(t,{...e.parser.ParserConfig,skipValidations:n,errorMessageProvider:e.parser.ParserErrorMessageProvider})}alternatives(e,t){this.wrapper.wrapOr(e,t)}optional(e,t){this.wrapper.wrapOption(e,t)}many(e,t){this.wrapper.wrapMany(e,t)}atLeastOne(e,t){this.wrapper.wrapAtLeastOne(e,t)}getRule(e){return this.allRules.get(e)}isRecording(){return this.wrapper.IS_RECORDING}get unorderedGroups(){return this._unorderedGroups}getRuleStack(){return this.wrapper.RULE_STACK}finalize(){this.wrapper.wrapSelfAnalysis()}},sj=class extends oj{static{o(this,`LangiumParser`)}get current(){return this.stack[this.stack.length-1]}constructor(e){super(e),this.nodeBuilder=new XA,this.stack=[],this.assignmentMap=new Map,this.operatorPrecedence=new Map,this.linker=e.references.Linker,this.converter=e.parser.ValueConverter,this.astReflection=e.shared.AstReflection}rule(e,t){let n=this.computeRuleType(e),r;Dr(e)&&(r=e.name,this.registerPrecedenceMap(e));let i=this.wrapper.DEFINE_RULE(aj(e.name),this.startImplementation(n,r,t).bind(this));return this.allRules.set(e.name,i),Yr(e)&&e.entry&&(this.mainRule=i),i}registerPrecedenceMap(e){let t=e.name,n=new Map;for(let t=0;t0&&(t=this.construct()),t===void 0)throw Error(`No result from parser`);if(this.stack.length>0)throw Error(`Parser stack is not empty after parsing`);return t}startImplementation(e,t,n){return r=>{let i=!this.isRecording()&&e!==void 0;if(i){let n={$type:e};this.stack.push(n),e===nj?n.value=``:t!==void 0&&(n.$infixName=t)}return n(r),i?this.construct():void 0}}extractHiddenTokens(e){let t=this.lexerResult.hidden;if(!t.length)return[];let n=e.startOffset;for(let e=0;en)return t.splice(0,e);return t.splice(0,t.length)}consume(e,t,n){let r=this.wrapper.wrapConsume(e,t);if(!this.isRecording()&&this.isValidToken(r)){let e=this.extractHiddenTokens(r);this.nodeBuilder.addHiddenNodes(e);let t=this.nodeBuilder.buildLeafNode(r,n),{assignment:i,crossRef:a}=this.getAssignment(n),o=this.current;if(i){let e=Fr(n)?r.image:this.converter.convert(r.image,t);this.assign(i.operator,i.feature,e,t,a)}else if(rj(o)){let e=r.image;Fr(n)||(e=this.converter.convert(e,t).toString()),o.value+=e}}}isValidToken(e){return!e.isInsertedInRecovery&&!isNaN(e.startOffset)&&typeof e.endOffset==`number`&&!isNaN(e.endOffset)}subrule(e,t,n,r,i){let a;!this.isRecording()&&!n&&(a=this.nodeBuilder.buildCompositeNode(r));let o;try{o=this.wrapper.wrapSubrule(e,t,i)}finally{this.isRecording()||(o===void 0&&!n&&(o=this.construct()),o!==void 0&&a&&a.length>0&&this.performSubruleAssignment(o,r,a))}}performSubruleAssignment(e,t,n){let{assignment:r,crossRef:i}=this.getAssignment(t);if(r)this.assign(r.operator,r.feature,e,n,i);else if(!r){let t=this.current;if(rj(t))t.value+=e.toString();else if(typeof e==`object`&&e){let n=this.assignWithoutOverride(e,t);this.stack.pop(),this.stack.push(n)}}}action(e,t){if(!this.isRecording()){let n=this.current;if(t.feature&&t.operator){n=this.construct(),this.nodeBuilder.removeNode(n.$cstNode),this.nodeBuilder.buildCompositeNode(t).content.push(n.$cstNode);let r={$type:e};this.stack.push(r),this.assign(t.operator,t.feature,n,n.$cstNode)}else n.$type=e}}construct(){if(this.isRecording())return;let e=this.stack.pop();return this.nodeBuilder.construct(e),`$infixName`in e?this.constructInfix(e,this.operatorPrecedence.get(e.$infixName)):rj(e)?this.converter.convert(e.value,e.$cstNode):(Fn(this.astReflection,e),e)}constructInfix(e,t){let n=e.parts;if(!Array.isArray(n)||n.length===0)return;let r=e.operators;if(!Array.isArray(r)||n.length<2)return n[0];let i=0,a=-1;for(let e=0;ea?(a=o.precedence,i=e):o.precedence===a&&(o.rightAssoc||(i=e))}let o=r.slice(0,i),s=r.slice(i+1),c=n.slice(0,i+1),l=n.slice(i+1),u={$infixName:e.$infixName,$type:e.$type,$cstNode:e.$cstNode,parts:c,operators:o},d={$infixName:e.$infixName,$type:e.$type,$cstNode:e.$cstNode,parts:l,operators:s},f=this.constructInfix(u,t),p=this.constructInfix(d,t);return{$type:e.$type,$cstNode:e.$cstNode,left:f,operator:r[i],right:p}}getAssignment(e){if(!this.assignmentMap.has(e)){let t=Tn(e,rr);this.assignmentMap.set(e,{assignment:t,crossRef:t&&pr(t.terminal)?t.terminal.isMulti?`multi`:`single`:void 0})}return this.assignmentMap.get(e)}assign(e,t,n,r,i){let a=this.current,o;switch(o=i===`single`&&typeof n==`string`?this.linker.buildReference(a,t,r,n):i===`multi`&&typeof n==`string`?this.linker.buildMultiReference(a,t,r,n):n,e){case`=`:a[t]=o;break;case`?=`:a[t]=!0;break;case`+=`:Array.isArray(a[t])||(a[t]=[]),a[t].push(o)}}assignWithoutOverride(e,t){for(let[n,r]of Object.entries(t)){let t=e[n];t===void 0?e[n]=r:Array.isArray(t)&&Array.isArray(r)&&(r.push(...t),e[n]=r)}let n=e.$cstNode;return n&&(n.astNode=void 0,e.$cstNode=void 0),e}get definitionErrors(){return this.wrapper.definitionErrors}},cj=class{static{o(this,`AbstractParserErrorMessageProvider`)}buildMismatchTokenMessage(e){return ib.buildMismatchTokenMessage(e)}buildNotAllInputParsedMessage(e){return ib.buildNotAllInputParsedMessage(e)}buildNoViableAltMessage(e){return ib.buildNoViableAltMessage(e)}buildEarlyExitMessage(e){return ib.buildEarlyExitMessage(e)}},lj=class extends cj{static{o(this,`LangiumParserErrorMessageProvider`)}buildMismatchTokenMessage({expected:e,actual:t}){return`Expecting ${e.LABEL?"`"+e.LABEL+"`":e.name.endsWith(`:KW`)?`keyword '${e.name.substring(0,e.name.length-3)}'`:`token of type '${e.name}'`} but found \`${t.image}\`.`}buildNotAllInputParsedMessage({firstRedundant:e}){return`Expecting end of file but found \`${e.image}\`.`}},uj=class extends oj{static{o(this,`LangiumCompletionParser`)}constructor(){super(...arguments),this.tokens=[],this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}action(){}construct(){}parse(e){this.resetState();let t=this.lexer.tokenize(e,{mode:`partial`});return this.tokens=t.tokens,this.wrapper.input=[...this.tokens],this.mainRule.call(this.wrapper,{}),this.unorderedGroups.clear(),{tokens:this.tokens,elementStack:[...this.lastElementStack],tokenIndex:this.nextTokenIndex}}rule(e,t){let n=this.wrapper.DEFINE_RULE(aj(e.name),this.startImplementation(t).bind(this));return this.allRules.set(e.name,n),e.entry&&(this.mainRule=n),n}resetState(){this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}startImplementation(e){return t=>{let n=this.keepStackSize();try{e(t)}finally{this.resetStackSize(n)}}}removeUnexpectedElements(){this.elementStack.splice(this.stackSize)}keepStackSize(){let e=this.elementStack.length;return this.stackSize=e,e}resetStackSize(e){this.removeUnexpectedElements(),this.stackSize=e}consume(e,t,n){this.wrapper.wrapConsume(e,t),this.isRecording()||(this.lastElementStack=[...this.elementStack,n],this.nextTokenIndex=this.currIdx+1)}subrule(e,t,n,r,i){this.before(r),this.wrapper.wrapSubrule(e,t,i),this.after(r)}before(e){this.isRecording()||this.elementStack.push(e)}after(e){if(!this.isRecording()){let t=this.elementStack.lastIndexOf(e);t>=0&&this.elementStack.splice(t)}}get currIdx(){return this.wrapper.currIdx}},dj={recoveryEnabled:!0,nodeLocationTracking:`full`,skipValidations:!0,errorMessageProvider:new lj},fj=class extends gS{static{o(this,`ChevrotainWrapper`)}constructor(e,t){let n=t&&`maxLookahead`in t;super(e,{...dj,lookaheadStrategy:n?new kx({maxLookahead:t.maxLookahead}):new wA({logging:t.skipValidations?()=>{}:void 0}),...t})}get IS_RECORDING(){return this.RECORDING_PHASE}DEFINE_RULE(e,t,n){return this.RULE(e,t,n)}wrapSelfAnalysis(){this.performSelfAnalysis()}wrapConsume(e,t){return this.consume(e,t,void 0)}wrapSubrule(e,t,n){return this.subrule(e,t,{ARGS:[n]})}wrapOr(e,t){this.or(e,t)}wrapOption(e,t){this.option(e,t)}wrapMany(e,t){this.many(e,t)}wrapAtLeastOne(e,t){this.atLeastOne(e,t)}rule(e){return e.call(this,{})}},pj=class extends fj{static{o(this,`ProfilerWrapper`)}constructor(e,t,n){super(e,t),this.task=n}rule(e){this.task.start(),this.task.startSubTask(this.ruleName(e));try{return super.rule(e)}finally{this.task.stopSubTask(this.ruleName(e)),this.task.stop()}}ruleName(e){return e.ruleName}subrule(e,t,n){this.task.startSubTask(this.ruleName(t));try{return super.subrule(e,t,n)}finally{this.task.stopSubTask(this.ruleName(t))}}};function mj(e,t,n){return hj({parser:t,tokens:n,ruleNames:new Map},e),t}o(mj,`createParser`);function hj(e,t){let n=Na(t,!1),r=N(t.rules).filter(Yr).filter(e=>n.has(e));for(let t of r){let n={...e,consume:1,optional:1,subrule:1,many:1,or:1};e.parser.rule(t,_j(n,t.definition))}let i=N(t.rules).filter(Dr).filter(e=>n.has(e));for(let t of i)e.parser.rule(t,gj(e,t))}o(hj,`buildRules`);function gj(e,t){let n=t.call.rule.ref;if(!n)throw Error(`Could not resolve reference to infix operator rule: `+t.call.rule.$refText);if(hi(n))throw Error(`Cannot use terminal rule in infix expression`);let r=t.operators.precedences.flatMap(e=>e.operators),i={$type:`Group`,elements:[]},a={$container:i,$type:`Assignment`,feature:`parts`,operator:`+=`,terminal:t.call},s={$container:i,$type:`Group`,elements:[],cardinality:`*`};i.elements.push(a,s);let c={$container:s,$type:`Assignment`,feature:`operators`,operator:`+=`,terminal:{$type:`Alternatives`,elements:r}},l={...a,$container:s};s.elements.push(c,l);let u=r.map(t=>e.tokens[t.value]).map((t,n)=>({ALT:o(()=>e.parser.consume(n,t,c),`ALT`)})),d;return t=>{d??=kj(e,n),e.parser.subrule(0,d,!1,a,t),e.parser.many(0,{DEF:o(()=>{e.parser.alternatives(0,u),e.parser.subrule(1,d,!1,l,t)},`DEF`)})}}o(gj,`buildInfixRule`);function _j(e,t,n=!1){let r;if(Fr(t))r=Dj(e,t);else if(Yn(t))r=vj(e,t);else if(rr(t))r=_j(e,t.terminal);else if(pr(t))r=Ej(e,t);else if(ri(t))r=yj(e,t);else if(Zn(t))r=Sj(e,t);else if(Di(t))r=Cj(e,t);else if(Cr(t))r=wj(e,t);else if(_r(t)){let n=e.consume++;r=o(()=>e.parser.consume(n,tb,t),`method`)}else throw new ia(t.$cstNode,`Unexpected element type: ${t.$type}`);return Oj(e,n?void 0:Tj(t),r,t.cardinality)}o(_j,`buildElement`);function vj(e,t){let n=no(t);return()=>e.parser.action(n,t)}o(vj,`buildAction`);function yj(e,t){let n=t.rule.ref;if(Un(n)){let r=e.subrule++,i=Yr(n)&&n.fragment,a=t.arguments.length>0?bj(n,t.arguments):()=>({}),o;return s=>{o??=kj(e,n),e.parser.subrule(r,o,i,t,a(s))}}else if(hi(n)){let r=e.consume++,i=jj(e,n.name);return()=>e.parser.consume(r,i,t)}else if(n)aa(n);else throw new ia(t.$cstNode,`Undefined rule: ${t.rule.$refText}`)}o(yj,`buildRuleCall`);function bj(e,t){if(t.some(e=>e.calledByName)){let e=t.map(e=>({parameterName:e.parameter?.ref?.name,predicate:xj(e.value)}));return t=>{let n={};for(let{parameterName:r,predicate:i}of e)r&&(n[r]=i(t));return n}}else{let n=t.map(e=>xj(e.value));return t=>{let r={};for(let i=0;it(e)||n(e)}else if(dr(e)){let t=xj(e.left),n=xj(e.right);return e=>t(e)&&n(e)}else if(Vr(e)){let t=xj(e.value);return e=>!t(e)}else if(qr(e)){let t=e.parameter.ref.name;return e=>e!==void 0&&e[t]===!0}else if(ar(e)){let t=!!e.true;return()=>t}aa(e)}o(xj,`buildPredicate`);function Sj(e,t){if(t.elements.length===1)return _j(e,t.elements[0]);{let n=[];for(let r of t.elements){let t={ALT:_j(e,r,!0)},i=Tj(r);i&&(t.GATE=xj(i)),n.push(t)}let r=e.or++;return t=>e.parser.alternatives(r,n.map(e=>{let n={ALT:o(()=>e.ALT(t),`ALT`)},r=e.GATE;return r&&(n.GATE=()=>r(t)),n}))}}o(Sj,`buildAlternatives`);function Cj(e,t){if(t.elements.length===1)return _j(e,t.elements[0]);let n=[];for(let r of t.elements){let t={ALT:_j(e,r,!0)},i=Tj(r);i&&(t.GATE=xj(i)),n.push(t)}let r=e.or++,i=o((e,t)=>`uGroup_${e}_${t.getRuleStack().join(`-`)}`,`idFunc`),a=o(t=>e.parser.alternatives(r,n.map((n,a)=>{let s={ALT:o(()=>!0,`ALT`)},c=e.parser;s.ALT=()=>{if(n.ALT(t),!c.isRecording()){let e=i(r,c);c.unorderedGroups.get(e)||c.unorderedGroups.set(e,[]);let t=c.unorderedGroups.get(e);t?.[a]===void 0&&(t[a]=!0)}};let l=n.GATE;return l?s.GATE=()=>l(t):s.GATE=()=>!c.unorderedGroups.get(i(r,c))?.[a],s})),`alternatives`),s=Oj(e,Tj(t),a,`*`);return t=>{s(t),e.parser.isRecording()||e.parser.unorderedGroups.delete(i(r,e.parser))}}o(Cj,`buildUnorderedGroup`);function wj(e,t){let n=t.elements.map(t=>_j(e,t));return e=>n.forEach(t=>t(e))}o(wj,`buildGroup`);function Tj(e){if(Cr(e))return e.guardCondition}o(Tj,`getGuardCondition`);function Ej(e,t,n=t.terminal){if(!n){if(!t.type.ref)throw Error(`Could not resolve reference to type: `+t.type.$refText);let n=Ga(t.type.ref)?.terminal;if(!n)throw Error(`Could not find name assignment for type: `+no(t.type.ref));return Ej(e,t,n)}else if(ri(n)&&Yr(n.rule.ref)){let r=n.rule.ref,i=e.subrule++,a;return n=>{a??=kj(e,r),e.parser.subrule(i,a,!1,t,n)}}else if(ri(n)&&hi(n.rule.ref)){let r=e.consume++,i=jj(e,n.rule.ref.name);return()=>e.parser.consume(r,i,t)}else if(Fr(n)){let r=e.consume++,i=jj(e,n.value);return()=>e.parser.consume(r,i,t)}else throw Error(`Could not build cross reference parser`)}o(Ej,`buildCrossReference`);function Dj(e,t){let n=e.consume++,r=e.tokens[t.value];if(!r)throw Error(`Could not find token for keyword: `+t.value);return()=>e.parser.consume(n,r,t)}o(Dj,`buildKeyword`);function Oj(e,t,n,r){let i=t&&xj(t);if(!r)if(i){let t=e.or++;return r=>e.parser.alternatives(t,[{ALT:o(()=>n(r),`ALT`),GATE:o(()=>i(r),`GATE`)},{ALT:mS(),GATE:o(()=>!i(r),`GATE`)}])}else return n;if(r===`*`){let t=e.many++;return r=>e.parser.many(t,{DEF:o(()=>n(r),`DEF`),GATE:i?()=>i(r):void 0})}else if(r===`+`){let t=e.many++;if(i){let r=e.or++;return a=>e.parser.alternatives(r,[{ALT:o(()=>e.parser.atLeastOne(t,{DEF:o(()=>n(a),`DEF`)}),`ALT`),GATE:o(()=>i(a),`GATE`)},{ALT:mS(),GATE:o(()=>!i(a),`GATE`)}])}else return r=>e.parser.atLeastOne(t,{DEF:o(()=>n(r),`DEF`)})}else if(r===`?`){let t=e.optional++;return r=>e.parser.optional(t,{DEF:o(()=>n(r),`DEF`),GATE:i?()=>i(r):void 0})}else aa(r)}o(Oj,`wrap`);function kj(e,t){let n=Aj(e,t),r=e.parser.getRule(n);if(!r)throw Error(`Rule "${n}" not found."`);return r}o(kj,`getRule`);function Aj(e,t){if(Un(t))return t.name;if(e.ruleNames.has(t))return e.ruleNames.get(t);{let n=t,r=n.$container,i=t.$type;for(;!Yr(r);)(Cr(r)||Zn(r)||Di(r))&&(i=r.elements.indexOf(n).toString()+`:`+i),n=r,r=r.$container;return i=r.name+`:`+i,e.ruleNames.set(t,i),i}}o(Aj,`getRuleName`);function jj(e,t){let n=e.tokens[t];if(!n)throw Error(`Token "${t}" not found."`);return n}o(jj,`getToken`);function Mj(e){let t=e.Grammar,n=e.parser.Lexer,r=new uj(e);return mj(t,r,n.definition),r.finalize(),r}o(Mj,`createCompletionParser`);function Nj(e){let t=Pj(e);return t.finalize(),t}o(Nj,`createLangiumParser`);function Pj(e){let t=e.Grammar,n=e.parser.Lexer;return mj(t,new sj(e),n.definition)}o(Pj,`prepareLangiumParser`);var Fj=class{static{o(this,`DefaultTokenBuilder`)}constructor(){this.diagnostics=[]}buildTokens(e,t){let n=N(Na(e,!1)),r=this.buildTerminalTokens(n),i=this.buildKeywordTokens(n,r,t);return i.push(...r),i}flushLexingReport(e){return{diagnostics:this.popDiagnostics()}}popDiagnostics(){let e=[...this.diagnostics];return this.diagnostics=[],e}buildTerminalTokens(e){return e.filter(hi).filter(e=>!e.fragment).map(e=>this.buildTerminalToken(e)).toArray()}buildTerminalToken(e){let t=oo(e),n=this.requiresCustomPattern(t)?this.regexPatternFunction(t):t,r={name:e.name,PATTERN:n};return typeof n==`function`&&(r.LINE_BREAKS=!0),e.hidden&&(r.GROUP=Da(t)?Vy.SKIPPED:`hidden`),r}requiresCustomPattern(e){return!!(e.flags.includes(`u`)||e.flags.includes(`s`))}regexPatternFunction(e){let t=new RegExp(e,e.flags+`y`);return(e,n)=>(t.lastIndex=n,t.exec(e))}buildKeywordTokens(e,t,n){return e.filter(Un).flatMap(e=>jn(e).filter(Fr)).distinct(e=>e.value).toArray().sort((e,t)=>t.value.length-e.value.length).map(e=>this.buildKeywordToken(e,t,!!n?.caseInsensitive))}buildKeywordToken(e,t,n){let r=this.buildKeywordPattern(e,n),i={name:e.value,PATTERN:r,LONGER_ALT:this.findLongerAlt(e,t)};return typeof r==`function`&&(i.LINE_BREAKS=!0),i}buildKeywordPattern(e,t){return t?new RegExp(Oa(e.value),`i`):e.value}findLongerAlt(e,t){return t.reduce((t,n)=>{let r=n?.PATTERN;return r?.source&&ka(`^`+r.source+`$`,e.value)&&t.push(n),t},[])}},Ij=class{static{o(this,`DefaultValueConverter`)}convert(e,t){let n=t.grammarSource;if(pr(n)&&(n=Ia(n)),ri(n)){let r=n.rule.ref;if(!r)throw Error(`This cst node was not parsed by a rule.`);return this.runConverter(r,e,t)}return e}runConverter(e,t,n){switch(e.name.toUpperCase()){case`INT`:return Lj.convertInt(t);case`STRING`:return Lj.convertString(t);case`ID`:return Lj.convertID(t)}switch(ao(e)?.toLowerCase()){case`number`:return Lj.convertNumber(t);case`boolean`:return Lj.convertBoolean(t);case`bigint`:return Lj.convertBigint(t);case`date`:return Lj.convertDate(t);default:return t}}},Lj;(function(e){function t(e){let t=``;for(let r=1;r{typeof setImmediate>`u`?setTimeout(e,0):setImmediate(e)})}o(Rj,`delayNextTick`);var zj=0,Bj=10;function Vj(){return zj=performance.now(),new Z.CancellationTokenSource}o(Vj,`startCancelableOperation`);function Hj(e){Bj=e}o(Hj,`setInterruptionPeriod`);var Uj=Symbol(`OperationCancelled`);function Wj(e){return e===Uj}o(Wj,`isOperationCancelled`);async function Gj(e){if(e===Z.CancellationToken.None)return;let t=performance.now();if(t-zj>=Bj&&(zj=t,await Rj(),zj=performance.now()),e.isCancellationRequested)throw Uj}o(Gj,`interruptAndCheck`);var Kj=class{static{o(this,`Deferred`)}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>(e(t),this),this.reject=e=>(t(e),this)})}},qj=class e{static{o(this,`FullTextDocument`)}constructor(e,t,n,r){this._uri=e,this._languageId=t,this._version=n,this._content=r,this._lineOffsets=void 0}get uri(){return this._uri}get languageId(){return this._languageId}get version(){return this._version}getText(e){if(e){let t=this.offsetAt(e.start),n=this.offsetAt(e.end);return this._content.substring(t,n)}return this._content}update(t,n){for(let n of t)if(e.isIncremental(n)){let e=Qj(n.range),t=this.offsetAt(e.start),r=this.offsetAt(e.end);this._content=this._content.substring(0,t)+n.text+this._content.substring(r,this._content.length);let i=Math.max(e.start.line,0),a=Math.max(e.end.line,0),o=this._lineOffsets,s=Xj(n.text,!1,t);if(a-i===s.length)for(let e=0,t=s.length;ee?r=i:n=i+1}let i=n-1;return e=this.ensureBeforeEOL(e,t[i]),{line:i,character:e-t[i]}}offsetAt(e){let t=this.getLineOffsets();if(e.line>=t.length)return this._content.length;if(e.line<0)return 0;let n=t[e.line];if(e.character<=0)return n;let r=e.line+1t&&Zj(this._content.charCodeAt(e-1));)e--;return e}get lineCount(){return this.getLineOffsets().length}static isIncremental(e){let t=e;return t!=null&&typeof t.text==`string`&&t.range!==void 0&&(t.rangeLength===void 0||typeof t.rangeLength==`number`)}static isFull(e){let t=e;return t!=null&&typeof t.text==`string`&&t.range===void 0&&t.rangeLength===void 0}},Jj;(function(e){function t(e,t,n,r){return new qj(e,t,n,r)}o(t,`create`),e.create=t;function n(e,t,n){if(e instanceof qj)return e.update(t,n),e;throw Error(`TextDocument.update: document must be created by TextDocument.create`)}o(n,`update`),e.update=n;function r(e,t){let n=e.getText(),r=Yj(t.map($j),(e,t)=>{let n=e.range.start.line-t.range.start.line;return n===0?e.range.start.character-t.range.start.character:n}),i=0,a=[];for(let t of r){let r=e.offsetAt(t.range.start);if(ri&&a.push(n.substring(i,r)),t.newText.length&&a.push(t.newText),i=e.offsetAt(t.range.end)}return a.push(n.substr(i)),a.join(``)}o(r,`applyEdits`),e.applyEdits=r})(Jj||={});function Yj(e,t){if(e.length<=1)return e;let n=e.length/2|0,r=e.slice(0,n),i=e.slice(n);Yj(r,t),Yj(i,t);let a=0,o=0,s=0;for(;an.line||t.line===n.line&&t.character>n.character?{start:n,end:t}:e}o(Qj,`getWellformedRange`);function $j(e){let t=Qj(e.range);return t===e.range?e:{newText:e.newText,range:t}}o($j,`getWellformedEdit`);var eM;(()=>{var e={975:e=>{function t(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received `+JSON.stringify(e))}o(t,`e`);function n(e,t){for(var n,r=``,i=0,a=-1,o=0,s=0;s<=e.length;++s){if(s2){var c=r.lastIndexOf(`/`);if(c!==r.length-1){c===-1?(r=``,i=0):i=(r=r.slice(0,c)).length-1-r.lastIndexOf(`/`),a=s,o=0;continue}}else if(r.length===2||r.length===1){r=``,i=0,a=s,o=0;continue}}t&&(r.length>0?r+=`/..`:r=`..`,i=2)}else r.length>0?r+=`/`+e.slice(a+1,s):r=e.slice(a+1,s),i=s-a-1;a=s,o=0}else n===46&&o!==-1?++o:o=-1}return r}o(n,`r`);var r={resolve:o(function(){for(var e,r=``,i=!1,a=arguments.length-1;a>=-1&&!i;a--){var o;a>=0?o=arguments[a]:(e===void 0&&(e=process.cwd()),o=e),t(o),o.length!==0&&(r=o+`/`+r,i=o.charCodeAt(0)===47)}return r=n(r,!i),i?r.length>0?`/`+r:`/`:r.length>0?r:`.`},`resolve`),normalize:o(function(e){if(t(e),e.length===0)return`.`;var r=e.charCodeAt(0)===47,i=e.charCodeAt(e.length-1)===47;return(e=n(e,!r)).length!==0||r||(e=`.`),e.length>0&&i&&(e+=`/`),r?`/`+e:e},`normalize`),isAbsolute:o(function(e){return t(e),e.length>0&&e.charCodeAt(0)===47},`isAbsolute`),join:o(function(){if(arguments.length===0)return`.`;for(var e,n=0;n0&&(e===void 0?e=i:e+=`/`+i)}return e===void 0?`.`:r.normalize(e)},`join`),relative:o(function(e,n){if(t(e),t(n),e===n||(e=r.resolve(e))===(n=r.resolve(n)))return``;for(var i=1;il){if(n.charCodeAt(s+d)===47)return n.slice(s+d+1);if(d===0)return n.slice(s+d)}else o>l&&(e.charCodeAt(i+d)===47?u=d:d===0&&(u=0));break}var f=e.charCodeAt(i+d);if(f!==n.charCodeAt(s+d))break;f===47&&(u=d)}var p=``;for(d=i+u+1;d<=a;++d)d!==a&&e.charCodeAt(d)!==47||(p.length===0?p+=`..`:p+=`/..`);return p.length>0?p+n.slice(s+u):(s+=u,n.charCodeAt(s)===47&&++s,n.slice(s))},`relative`),_makeLong:o(function(e){return e},`_makeLong`),dirname:o(function(e){if(t(e),e.length===0)return`.`;for(var n=e.charCodeAt(0),r=n===47,i=-1,a=!0,o=e.length-1;o>=1;--o)if((n=e.charCodeAt(o))===47){if(!a){i=o;break}}else a=!1;return i===-1?r?`/`:`.`:r&&i===1?`//`:e.slice(0,i)},`dirname`),basename:o(function(e,n){if(n!==void 0&&typeof n!=`string`)throw TypeError(`"ext" argument must be a string`);t(e);var r,i=0,a=-1,o=!0;if(n!==void 0&&n.length>0&&n.length<=e.length){if(n.length===e.length&&n===e)return``;var s=n.length-1,c=-1;for(r=e.length-1;r>=0;--r){var l=e.charCodeAt(r);if(l===47){if(!o){i=r+1;break}}else c===-1&&(o=!1,c=r+1),s>=0&&(l===n.charCodeAt(s)?--s==-1&&(a=r):(s=-1,a=c))}return i===a?a=c:a===-1&&(a=e.length),e.slice(i,a)}for(r=e.length-1;r>=0;--r)if(e.charCodeAt(r)===47){if(!o){i=r+1;break}}else a===-1&&(o=!1,a=r+1);return a===-1?``:e.slice(i,a)},`basename`),extname:o(function(e){t(e);for(var n=-1,r=0,i=-1,a=!0,o=0,s=e.length-1;s>=0;--s){var c=e.charCodeAt(s);if(c!==47)i===-1&&(a=!1,i=s+1),c===46?n===-1?n=s:o!==1&&(o=1):n!==-1&&(o=-1);else if(!a){r=s+1;break}}return n===-1||i===-1||o===0||o===1&&n===i-1&&n===r+1?``:e.slice(n,i)},`extname`),format:o(function(e){if(typeof e!=`object`||!e)throw TypeError(`The "pathObject" argument must be of type Object. Received type `+typeof e);return(function(e,t){var n=t.dir||t.root,r=t.base||(t.name||``)+(t.ext||``);return n?n===t.root?n+r:n+`/`+r:r})(0,e)},`format`),parse:o(function(e){t(e);var n={root:``,dir:``,base:``,ext:``,name:``};if(e.length===0)return n;var r,i=e.charCodeAt(0),a=i===47;a?(n.root=`/`,r=1):r=0;for(var o=-1,s=0,c=-1,l=!0,u=e.length-1,d=0;u>=r;--u)if((i=e.charCodeAt(u))!==47)c===-1&&(l=!1,c=u+1),i===46?o===-1?o=u:d!==1&&(d=1):o!==-1&&(d=-1);else if(!l){s=u+1;break}return o===-1||c===-1||d===0||d===1&&o===c-1&&o===s+1?c!==-1&&(n.base=n.name=s===0&&a?e.slice(1,c):e.slice(s,c)):(s===0&&a?(n.name=e.slice(1,o),n.base=e.slice(1,c)):(n.name=e.slice(s,o),n.base=e.slice(s,c)),n.ext=e.slice(o,c)),s>0?n.dir=e.slice(0,s-1):a&&(n.dir=`/`),n},`parse`),sep:`/`,delimiter:`:`,win32:null,posix:null};r.posix=r,e.exports=r}},t={};function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r](a,a.exports,n),a.exports}o(n,`r`),n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};let i;n.r(r),n.d(r,{URI:o(()=>d,`URI`),Utils:o(()=>te,`Utils`)}),typeof process==`object`?i=process.platform===`win32`:typeof navigator==`object`&&(i=navigator.userAgent.indexOf(`Windows`)>=0);let a=/^\w[\w\d+.-]*$/,s=/^\//,c=/^\/\//;function l(e,t){if(!e.scheme&&t)throw Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!a.test(e.scheme))throw Error(`[UriError]: Scheme contains illegal characters.`);if(e.path){if(e.authority){if(!s.test(e.path))throw Error(`[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character`)}else if(c.test(e.path))throw Error(`[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")`)}}o(l,`a`);let u=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class d{static{o(this,`l`)}static isUri(e){return e instanceof d||!!e&&typeof e.authority==`string`&&typeof e.fragment==`string`&&typeof e.path==`string`&&typeof e.query==`string`&&typeof e.scheme==`string`&&typeof e.fsPath==`string`&&typeof e.with==`function`&&typeof e.toString==`function`}scheme;authority;path;query;fragment;constructor(e,t,n,r,i,a=!1){typeof e==`object`?(this.scheme=e.scheme||``,this.authority=e.authority||``,this.path=e.path||``,this.query=e.query||``,this.fragment=e.fragment||``):(this.scheme=(function(e,t){return e||t?e:`file`})(e,a),this.authority=t||``,this.path=(function(e,t){switch(e){case`https`:case`http`:case`file`:t?t[0]!==`/`&&(t=`/`+t):t=`/`}return t})(this.scheme,n||``),this.query=r||``,this.fragment=i||``,l(this,a))}get fsPath(){return _(this,!1)}with(e){if(!e)return this;let{scheme:t,authority:n,path:r,query:i,fragment:a}=e;return t===void 0?t=this.scheme:t===null&&(t=``),n===void 0?n=this.authority:n===null&&(n=``),r===void 0?r=this.path:r===null&&(r=``),i===void 0?i=this.query:i===null&&(i=``),a===void 0?a=this.fragment:a===null&&(a=``),t===this.scheme&&n===this.authority&&r===this.path&&i===this.query&&a===this.fragment?this:new p(t,n,r,i,a)}static parse(e,t=!1){let n=u.exec(e);return n?new p(n[2]||``,x(n[4]||``),x(n[5]||``),x(n[7]||``),x(n[9]||``),t):new p(``,``,``,``,``)}static file(e){let t=``;if(i&&(e=e.replace(/\\/g,`/`)),e[0]===`/`&&e[1]===`/`){let n=e.indexOf(`/`,2);n===-1?(t=e.substring(2),e=`/`):(t=e.substring(2,n),e=e.substring(n)||`/`)}return new p(`file`,t,e,``,``)}static from(e){let t=new p(e.scheme,e.authority,e.path,e.query,e.fragment);return l(t,!0),t}toString(e=!1){return v(this,e)}toJSON(){return this}static revive(e){if(e){if(e instanceof d)return e;{let t=new p(e);return t._formatted=e.external,t._fsPath=e._sep===f?e.fsPath:null,t}}return e}}let f=i?1:void 0;class p extends d{static{o(this,`d`)}_formatted=null;_fsPath=null;get fsPath(){return this._fsPath||=_(this,!1),this._fsPath}toString(e=!1){return e?v(this,!0):(this._formatted||=v(this,!1),this._formatted)}toJSON(){let e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=f),this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),this.query&&(e.query=this.query),this.fragment&&(e.fragment=this.fragment),e}}let m={58:`%3A`,47:`%2F`,63:`%3F`,35:`%23`,91:`%5B`,93:`%5D`,64:`%40`,33:`%21`,36:`%24`,38:`%26`,39:`%27`,40:`%28`,41:`%29`,42:`%2A`,43:`%2B`,44:`%2C`,59:`%3B`,61:`%3D`,32:`%20`};function h(e,t,n){let r,i=-1;for(let a=0;a=97&&o<=122||o>=65&&o<=90||o>=48&&o<=57||o===45||o===46||o===95||o===126||t&&o===47||n&&o===91||n&&o===93||n&&o===58)i!==-1&&(r+=encodeURIComponent(e.substring(i,a)),i=-1),r!==void 0&&(r+=e.charAt(a));else{r===void 0&&(r=e.substr(0,a));let t=m[o];t===void 0?i===-1&&(i=a):(i!==-1&&(r+=encodeURIComponent(e.substring(i,a)),i=-1),r+=t)}}return i!==-1&&(r+=encodeURIComponent(e.substring(i))),r===void 0?e:r}o(h,`m`);function g(e){let t;for(let n=0;n1&&e.scheme===`file`?`//${e.authority}${e.path}`:e.path.charCodeAt(0)===47&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&e.path.charCodeAt(2)===58?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,i&&(n=n.replace(/\//g,`\\`)),n}o(_,`v`);function v(e,t){let n=t?g:h,r=``,{scheme:i,authority:a,path:o,query:s,fragment:c}=e;if(i&&(r+=i,r+=`:`),(a||i===`file`)&&(r+=`/`,r+=`/`),a){let e=a.indexOf(`@`);if(e!==-1){let t=a.substr(0,e);a=a.substr(e+1),e=t.lastIndexOf(`:`),e===-1?r+=n(t,!1,!1):(r+=n(t.substr(0,e),!1,!1),r+=`:`,r+=n(t.substr(e+1),!1,!0)),r+=`@`}a=a.toLowerCase(),e=a.lastIndexOf(`:`),e===-1?r+=n(a,!1,!0):(r+=n(a.substr(0,e),!1,!0),r+=a.substr(e))}if(o){if(o.length>=3&&o.charCodeAt(0)===47&&o.charCodeAt(2)===58){let e=o.charCodeAt(1);e>=65&&e<=90&&(o=`/${String.fromCharCode(e+32)}:${o.substr(3)}`)}else if(o.length>=2&&o.charCodeAt(1)===58){let e=o.charCodeAt(0);e>=65&&e<=90&&(o=`${String.fromCharCode(e+32)}:${o.substr(2)}`)}r+=n(o,!0,!1)}return s&&(r+=`?`,r+=n(s,!1,!1)),c&&(r+=`#`,r+=t?c:h(c,!1,!1)),r}o(v,`b`);function y(e){try{return decodeURIComponent(e)}catch{return e.length>3?e.substr(0,3)+y(e.substr(3)):e}}o(y,`C`);let b=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function x(e){return e.match(b)?e.replace(b,(e=>y(e))):e}o(x,`w`);var ee=n(975);let S=ee.posix||ee;var te;(function(e){e.joinPath=function(e,...t){return e.with({path:S.join(e.path,...t)})},e.resolvePath=function(e,...t){let n=e.path,r=!1;n[0]!==`/`&&(n=`/`+n,r=!0);let i=S.resolve(n,...t);return r&&i[0]===`/`&&!e.authority&&(i=i.substring(1)),e.with({path:i})},e.dirname=function(e){if(e.path.length===0||e.path===`/`)return e;let t=S.dirname(e.path);return t.length===1&&t.charCodeAt(0)===46&&(t=``),e.with({path:t})},e.basename=function(e){return S.basename(e.path)},e.extname=function(e){return S.extname(e.path)}})(te||={}),eM=r})();var{URI:tM,Utils:nM}=eM,rM;(function(e){e.basename=nM.basename,e.dirname=nM.dirname,e.extname=nM.extname,e.joinPath=nM.joinPath,e.resolvePath=nM.resolvePath;let t=typeof process==`object`&&process?.platform===`win32`;function n(e,t){return e?.toString()===t?.toString()}o(n,`equals`),e.equals=n;function r(e,n){let r=typeof e==`string`?tM.parse(e).path:e.path,i=typeof n==`string`?tM.parse(n).path:n.path,a=r.split(`/`).filter(e=>e.length>0),o=i.split(`/`).filter(e=>e.length>0);if(t){let e=/^[A-Z]:$/;if(a[0]&&e.test(a[0])&&(a[0]=a[0].toLowerCase()),o[0]&&e.test(o[0])&&(o[0]=o[0].toLowerCase()),a[0]!==o[0])return i.substring(1)}let s=0;for(;s({name:e.name,uri:rM.joinPath(tM.parse(t),e.name).toString(),element:e.element})):[]}all(){return this.collectValues(this.root)}findAll(e){let t=this.getNode(rM.normalize(e),!1);return t?this.collectValues(t):[]}getNode(e,t){let n=e.split(`/`);e.charAt(e.length-1)===`/`&&n.pop();let r=this.root;for(let e of n){let n=r.children.get(e);if(!n)if(t)n={name:e,children:new Map,parent:r},r.children.set(e,n);else return;r=n}return r}collectValues(e){let t=[];e.element&&t.push(e.element);for(let n of e.children.values())t.push(...this.collectValues(n));return t}},Q;(function(e){e[e.Changed=0]=`Changed`,e[e.Parsed=1]=`Parsed`,e[e.IndexedContent=2]=`IndexedContent`,e[e.ComputedScopes=3]=`ComputedScopes`,e[e.Linked=4]=`Linked`,e[e.IndexedReferences=5]=`IndexedReferences`,e[e.Validated=6]=`Validated`})(Q||={});var aM=class{static{o(this,`DefaultLangiumDocumentFactory`)}constructor(e){this.serviceRegistry=e.ServiceRegistry,this.textDocuments=e.workspace.TextDocuments,this.fileSystemProvider=e.workspace.FileSystemProvider}async fromUri(e,t=Z.CancellationToken.None){let n=await this.fileSystemProvider.readFile(e);return this.createAsync(e,n,t)}fromTextDocument(e,t,n){return t??=tM.parse(e.uri),Z.CancellationToken.is(n)?this.createAsync(t,e,n):this.create(t,e,n)}fromString(e,t,n){return Z.CancellationToken.is(n)?this.createAsync(t,e,n):this.create(t,e,n)}fromModel(e,t){return this.create(t,{$model:e})}create(e,t,n){if(typeof t==`string`){let r=this.parse(e,t,n);return this.createLangiumDocument(r,e,void 0,t)}else if(`$model`in t){let n={value:t.$model,parserErrors:[],lexerErrors:[]};return this.createLangiumDocument(n,e)}else{let r=this.parse(e,t.getText(),n);return this.createLangiumDocument(r,e,t)}}async createAsync(e,t,n){if(typeof t==`string`){let r=await this.parseAsync(e,t,n);return this.createLangiumDocument(r,e,void 0,t)}else{let r=await this.parseAsync(e,t.getText(),n);return this.createLangiumDocument(r,e,t)}}createLangiumDocument(e,t,n,r){let i;if(n)i={parseResult:e,uri:t,state:Q.Parsed,references:[],textDocument:n};else{let n=this.createTextDocumentGetter(t,r);i={parseResult:e,uri:t,state:Q.Parsed,references:[],get textDocument(){return n()}}}return e.value.$document=i,i}async update(e,t){let n=e.parseResult.value.$cstNode?.root.fullText,r=this.textDocuments?.get(e.uri.toString()),i=r?r.getText():await this.fileSystemProvider.readFile(e.uri);if(r)Object.defineProperty(e,"textDocument",{value:r});else{let t=this.createTextDocumentGetter(e.uri,i);Object.defineProperty(e,"textDocument",{get:t})}return n!==i&&(e.parseResult=await this.parseAsync(e.uri,i,t),e.parseResult.value.$document=e),e.state=Q.Parsed,e}parse(e,t,n){return this.serviceRegistry.getServices(e).parser.LangiumParser.parse(t,n)}parseAsync(e,t,n){return this.serviceRegistry.getServices(e).parser.AsyncParser.parse(t,n)}createTextDocumentGetter(e,t){let n=this.serviceRegistry,r;return()=>r??=Jj.create(e.toString(),n.getServices(e).LanguageMetaData.languageId,0,t??``)}},oM=class{static{o(this,`DefaultLangiumDocuments`)}constructor(e){this.documentTrie=new iM,this.services=e,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.documentBuilder=()=>e.workspace.DocumentBuilder}get all(){return N(this.documentTrie.all())}addDocument(e){let t=e.uri.toString();if(this.documentTrie.has(t))throw Error(`A document with the URI '${t}' is already present.`);this.documentTrie.insert(t,e)}getDocument(e){let t=e.toString();return this.documentTrie.find(t)}getDocuments(e){let t=e.toString();return this.documentTrie.findAll(t)}async getOrCreateDocument(e,t){let n=this.getDocument(e);return n||(n=await this.langiumDocumentFactory.fromUri(e,t),this.addDocument(n),n)}createDocument(e,t,n){if(n)return this.langiumDocumentFactory.fromString(t,e,n).then(e=>(this.addDocument(e),e));{let n=this.langiumDocumentFactory.fromString(t,e);return this.addDocument(n),n}}hasDocument(e){return this.documentTrie.has(e.toString())}invalidateDocument(e){let t=e.toString(),n=this.documentTrie.find(t);return n&&this.documentBuilder().resetToState(n,Q.Changed),n}deleteDocument(e){let t=e.toString(),n=this.documentTrie.find(t);return n&&(n.state=Q.Changed,this.documentTrie.delete(t)),n}deleteDocuments(e){let t=e.toString(),n=this.documentTrie.findAll(t);for(let e of n)e.state=Q.Changed;return this.documentTrie.delete(t),n}},sM=Symbol(`RefResolving`),cM=class{static{o(this,`DefaultLinker`)}constructor(e){this.reflection=e.shared.AstReflection,this.langiumDocuments=()=>e.shared.workspace.LangiumDocuments,this.scopeProvider=e.references.ScopeProvider,this.astNodeLocator=e.workspace.AstNodeLocator,this.profiler=e.shared.profilers.LangiumProfiler,this.languageId=e.LanguageMetaData.languageId}async link(e,t=Z.CancellationToken.None){if(this.profiler?.isActive(`linking`)){let n=this.profiler.createTask(`linking`,this.languageId);n.start();try{for(let r of Mn(e.parseResult.value))await Gj(t),Pn(r).forEach(t=>{let i=`${r.$type}:${t.property}`;n.startSubTask(i);try{this.doLink(t,e)}finally{n.stopSubTask(i)}})}finally{n.stop()}}else for(let n of Mn(e.parseResult.value))await Gj(t),Pn(n).forEach(t=>this.doLink(t,e))}doLink(e,t){let n=e.reference;if(`_ref`in n&&n._ref===void 0){n._ref=sM;try{let t=this.getCandidate(e);dn(t)?n._ref=t:(n._nodeDescription=t,n._ref=this.loadAstNode(t)??this.createLinkingError(e,t))}catch(t){console.error(`An error occurred while resolving reference to '${n.$refText}':`,t);let r=t.message??String(t);n._ref={info:e,message:`An error occurred while resolving reference to '${n.$refText}': ${r}`}}t.references.push(n)}else if(`_items`in n&&n._items===void 0){n._items=sM;try{let t=this.getCandidates(e),r=[];if(dn(t))n._linkingError=t;else for(let e of t){let t=this.loadAstNode(e);t&&r.push({ref:t,$nodeDescription:e})}n._items=r}catch(t){n._linkingError={info:e,message:`An error occurred while resolving reference to '${n.$refText}': ${t}`},n._items=[]}t.references.push(n)}}unlink(e){for(let t of e.references)`_ref`in t?(t._ref=void 0,delete t._nodeDescription):`_items`in t&&(t._items=void 0,delete t._linkingError);e.references=[]}getCandidate(e){return this.scopeProvider.getScope(e).getElement(e.reference.$refText)??this.createLinkingError(e)}getCandidates(e){let t=this.scopeProvider.getScope(e).getElements(e.reference.$refText).distinct(e=>`${e.documentUri}#${e.path}`).toArray();return t.length>0?t:this.createLinkingError(e)}buildReference(e,t,n,r){let i=this,a={$refNode:n,$refText:r,_ref:void 0,get ref(){if(M(this._ref))return this._ref;if(un(this._nodeDescription)){let n=i.loadAstNode(this._nodeDescription);this._ref=n??i.createLinkingError({reference:a,container:e,property:t},this._nodeDescription)}else if(this._ref===void 0){this._ref=sM;let n=On(e).$document,r=i.getLinkedNode({reference:a,container:e,property:t});if(r.error&&n&&n.state0))return this._linkingError=i.createLinkingError({reference:a,container:e,property:t})}};return a}throwCyclicReferenceError(e,t,n){throw Error(`Cyclic reference resolution detected: ${this.astNodeLocator.getAstNodePath(e)}/${t} (symbol '${n}')`)}getLinkedNode(e){try{let t=this.getCandidate(e);if(dn(t))return{error:t};let n=this.loadAstNode(t);return n?{node:n,descr:t}:{descr:t,error:this.createLinkingError(e,t)}}catch(t){console.error(`An error occurred while resolving reference to '${e.reference.$refText}':`,t);let n=t.message??String(t);return{error:{info:e,message:`An error occurred while resolving reference to '${e.reference.$refText}': ${n}`}}}}loadAstNode(e){if(e.node)return e.node;let t=this.langiumDocuments().getDocument(e.documentUri);if(t)return this.astNodeLocator.getAstNode(t.parseResult.value,e.path)}createLinkingError(e,t){let n=On(e.container).$document;return n&&n.statepr(e)&&e.isMulti)}findDeclarations(e){if(e){let t=Wa(e),n=e.astNode;if(t&&n){let r=n[t.feature];if(cn(r)||ln(r))return kn(r);if(Array.isArray(r)){for(let t of r)if((cn(t)||ln(t))&&t.$refNode&&t.$refNode.offset<=e.offset&&t.$refNode.end>=e.end)return kn(t)}}if(n){let t=this.nameProvider.getNameNode(n);if(t&&(t===e||Ri(e,t)))return this.getSelfNodes(n)}}return[]}getSelfNodes(e){if(this.hasMultiReference){let t=this.index.findAllReferences(e,this.nodeLocator.getAstNodePath(e)),n=this.getNodeFromReferenceDescription(t.head());if(n){for(let t of Pn(n))if(ln(t.reference)&&t.reference.items.some(t=>t.ref===e))return t.reference.items.map(e=>e.ref)}return[e]}else return[e]}getNodeFromReferenceDescription(e){if(!e)return;let t=this.documents.getDocument(e.sourceUri);if(t)return this.nodeLocator.getAstNode(t.parseResult.value,e.sourcePath)}findDeclarationNodes(e){let t=this.findDeclarations(e),n=[];for(let e of t){let t=this.nameProvider.getNameNode(e)??e.$cstNode;t&&n.push(t)}return n}findReferences(e,t){let n=[];t.includeDeclaration&&n.push(...this.getSelfReferences(e));let r=this.index.findAllReferences(e,this.nodeLocator.getAstNodePath(e));return t.documentUri&&(r=r.filter(e=>rM.equals(e.sourceUri,t.documentUri))),n.push(...r),N(n)}getSelfReferences(e){let t=this.getSelfNodes(e),n=[];for(let e of t){let t=this.nameProvider.getNameNode(e);if(t){let r=Dn(e),i=this.nodeLocator.getAstNodePath(e);n.push({sourceUri:r.uri,sourcePath:i,targetUri:r.uri,targetPath:i,segment:Bi(t),local:!0})}}return n}},fM=class{static{o(this,`MultiMap`)}constructor(e){if(this.map=new Map,e)for(let[t,n]of e)this.add(t,n)}get size(){return Sn.sum(N(this.map.values()).map(e=>e.length))}clear(){this.map.clear()}delete(e,t){if(t===void 0)return this.map.delete(e);{let n=this.map.get(e);if(n){let r=n.indexOf(t);if(r>=0)return n.length===1?this.map.delete(e):n.splice(r,1),!0}return!1}}get(e){return this.map.get(e)??[]}getStream(e){let t=this.map.get(e);return t?N(t):yn}has(e,t){if(t===void 0)return this.map.has(e);{let n=this.map.get(e);return n?n.indexOf(t)>=0:!1}}add(e,t){return this.map.has(e)?this.map.get(e).push(t):this.map.set(e,[t]),this}addAll(e,t){return this.map.has(e)?this.map.get(e).push(...t):this.map.set(e,Array.from(t)),this}forEach(e){this.map.forEach((t,n)=>t.forEach(t=>e(t,n,this)))}[Symbol.iterator](){return this.entries().iterator()}entries(){return N(this.map.entries()).flatMap(([e,t])=>t.map(t=>[e,t]))}keys(){return N(this.map.keys())}values(){return N(this.map.values()).flat()}entriesGroupedByKey(){return N(this.map.entries())}},pM=class{static{o(this,`BiMap`)}get size(){return this.map.size}constructor(e){if(this.map=new Map,this.inverse=new Map,e)for(let[t,n]of e)this.set(t,n)}clear(){this.map.clear(),this.inverse.clear()}set(e,t){return this.map.set(e,t),this.inverse.set(t,e),this}get(e){return this.map.get(e)}getKey(e){return this.inverse.get(e)}delete(e){let t=this.map.get(e);return t===void 0?!1:(this.map.delete(e),this.inverse.delete(t),!0)}},mM=class{static{o(this,`DefaultScopeComputation`)}constructor(e){this.nameProvider=e.references.NameProvider,this.descriptions=e.workspace.AstNodeDescriptionProvider}async collectExportedSymbols(e,t=Z.CancellationToken.None){return this.collectExportedSymbolsForNode(e.parseResult.value,e,void 0,t)}async collectExportedSymbolsForNode(e,t,n=An,r=Z.CancellationToken.None){let i=[];this.addExportedSymbol(e,i,t);for(let a of n(e))await Gj(r),this.addExportedSymbol(a,i,t);return i}addExportedSymbol(e,t,n){let r=this.nameProvider.getName(e);r&&t.push(this.descriptions.createDescription(e,r,n))}async collectLocalSymbols(e,t=Z.CancellationToken.None){let n=e.parseResult.value,r=new fM;for(let i of jn(n))await Gj(t),this.addLocalSymbol(i,e,r);return r}addLocalSymbol(e,t,n){let r=e.$container;if(r){let i=this.nameProvider.getName(e);i&&n.add(r,this.descriptions.createDescription(e,i,t))}}},hM=class{static{o(this,`StreamScope`)}constructor(e,t,n){this.elements=e,this.outerScope=t,this.caseInsensitive=n?.caseInsensitive??!1,this.concatOuterScope=n?.concatOuterScope??!0}getAllElements(){return this.outerScope?this.elements.concat(this.outerScope.getAllElements()):this.elements}getElement(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.caseInsensitive?this.elements.find(e=>e.name.toLowerCase()===t):this.elements.find(t=>t.name===e);if(n)return n;if(this.outerScope)return this.outerScope.getElement(e)}getElements(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.caseInsensitive?this.elements.filter(e=>e.name.toLowerCase()===t):this.elements.filter(t=>t.name===e);return(this.concatOuterScope||n.isEmpty())&&this.outerScope?n.concat(this.outerScope.getElements(e)):n}},gM=class{static{o(this,`MapScope`)}constructor(e,t,n){this.elements=new Map,this.caseInsensitive=n?.caseInsensitive??!1,this.concatOuterScope=n?.concatOuterScope??!0;for(let t of e){let e=this.caseInsensitive?t.name.toLowerCase():t.name;this.elements.set(e,t)}this.outerScope=t}getElement(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.elements.get(t);if(n)return n;if(this.outerScope)return this.outerScope.getElement(e)}getElements(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.elements.get(t),r=n?[n]:[];return(this.concatOuterScope||r.length>0)&&this.outerScope?N(r).concat(this.outerScope.getElements(e)):N(r)}getAllElements(){let e=N(this.elements.values());return this.outerScope&&(e=e.concat(this.outerScope.getAllElements())),e}},_M=class{static{o(this,`MultiMapScope`)}constructor(e,t,n){this.elements=new fM,this.caseInsensitive=n?.caseInsensitive??!1,this.concatOuterScope=n?.concatOuterScope??!0;for(let t of e){let e=this.caseInsensitive?t.name.toLowerCase():t.name;this.elements.add(e,t)}this.outerScope=t}getElement(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.elements.get(t)[0];if(n)return n;if(this.outerScope)return this.outerScope.getElement(e)}getElements(e){let t=this.caseInsensitive?e.toLowerCase():e,n=this.elements.get(t);return(this.concatOuterScope||n.length===0)&&this.outerScope?N(n).concat(this.outerScope.getElements(e)):N(n)}getAllElements(){let e=N(this.elements.values());return this.outerScope&&(e=e.concat(this.outerScope.getAllElements())),e}},vM={getElement(){},getElements(){return yn},getAllElements(){return yn}},yM=class{static{o(this,`DisposableCache`)}constructor(){this.toDispose=[],this.isDisposed=!1}onDispose(e){this.toDispose.push(e)}dispose(){this.throwIfDisposed(),this.clear(),this.isDisposed=!0,this.toDispose.forEach(e=>e.dispose())}throwIfDisposed(){if(this.isDisposed)throw Error(`This cache has already been disposed`)}},bM=class extends yM{static{o(this,`SimpleCache`)}constructor(){super(...arguments),this.cache=new Map}has(e){return this.throwIfDisposed(),this.cache.has(e)}set(e,t){this.throwIfDisposed(),this.cache.set(e,t)}get(e,t){if(this.throwIfDisposed(),this.cache.has(e))return this.cache.get(e);if(t){let n=t();return this.cache.set(e,n),n}else return}delete(e){return this.throwIfDisposed(),this.cache.delete(e)}clear(){this.throwIfDisposed(),this.cache.clear()}},xM=class extends yM{static{o(this,`ContextCache`)}constructor(e){super(),this.cache=new Map,this.converter=e??(e=>e)}has(e,t){return this.throwIfDisposed(),this.cacheForContext(e).has(t)}set(e,t,n){this.throwIfDisposed(),this.cacheForContext(e).set(t,n)}get(e,t,n){this.throwIfDisposed();let r=this.cacheForContext(e);if(r.has(t))return r.get(t);if(n){let e=n();return r.set(t,e),e}else return}delete(e,t){return this.throwIfDisposed(),this.cacheForContext(e).delete(t)}clear(e){if(this.throwIfDisposed(),e){let t=this.converter(e);this.cache.delete(t)}else this.cache.clear()}cacheForContext(e){let t=this.converter(e),n=this.cache.get(t);return n||(n=new Map,this.cache.set(t,n)),n}},SM=class extends xM{static{o(this,`DocumentCache`)}constructor(e,t){super(e=>e.toString()),t?(this.toDispose.push(e.workspace.DocumentBuilder.onDocumentPhase(t,e=>{this.clear(e.uri.toString())})),this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((e,t)=>{for(let e of t)this.clear(e)}))):this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((e,t)=>{let n=e.concat(t);for(let e of n)this.clear(e)}))}},CM=class extends bM{static{o(this,`WorkspaceCache`)}constructor(e,t){super(),t?(this.toDispose.push(e.workspace.DocumentBuilder.onBuildPhase(t,()=>{this.clear()})),this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((e,t)=>{t.length>0&&this.clear()}))):this.toDispose.push(e.workspace.DocumentBuilder.onUpdate(()=>{this.clear()}))}},wM=class{static{o(this,`DefaultScopeProvider`)}constructor(e){this.reflection=e.shared.AstReflection,this.nameProvider=e.references.NameProvider,this.descriptions=e.workspace.AstNodeDescriptionProvider,this.indexManager=e.shared.workspace.IndexManager,this.globalScopeCache=new CM(e.shared)}getScope(e){let t=[],n=this.reflection.getReferenceType(e),r=Dn(e.container).localSymbols;if(r){let i=e.container;do r.has(i)&&t.push(r.getStream(i).filter(e=>this.reflection.isSubtype(e.type,n))),i=i.$container;while(i)}let i=this.getGlobalScope(n,e);for(let e=t.length-1;e>=0;e--)i=this.createScope(t[e],i);return i}createScope(e,t,n){return new hM(N(e),t,n)}createScopeForNodes(e,t,n){return new hM(N(e).map(e=>{let t=this.nameProvider.getName(e);if(t)return this.descriptions.createDescription(e,t)}).nonNullable(),t,n)}getGlobalScope(e,t){return this.globalScopeCache.get(e,()=>new _M(this.indexManager.allElements(e)))}};function TM(e){return typeof e.$comment==`string`}o(TM,`isAstNodeWithComment`);function EM(e){return typeof e==`object`&&!!e&&(`$ref`in e||`$error`in e)}o(EM,`isIntermediateReference`);var DM=class{static{o(this,`DefaultJsonSerializer`)}constructor(e){this.ignoreProperties=new Set([`$container`,`$containerProperty`,`$containerIndex`,`$document`,`$cstNode`]),this.langiumDocuments=e.shared.workspace.LangiumDocuments,this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider,this.commentProvider=e.documentation.CommentProvider}serialize(e,t){let n=t??{},r=t?.replacer,i=o((e,t)=>this.replacer(e,t,n),`defaultReplacer`),a=r?(e,t)=>r(e,t,i):i;try{return this.currentDocument=Dn(e),JSON.stringify(e,a,t?.space)}finally{this.currentDocument=void 0}}deserialize(e,t){let n=t??{},r=JSON.parse(e);return this.linkNode(r,r,n),r}replacer(e,t,{refText:n,sourceText:r,textRegions:i,comments:a,uriConverter:o}){if(!this.ignoreProperties.has(e))if(cn(t)){let e=t.ref,r=n?t.$refText:void 0;if(e){let t=Dn(e),n=``;this.currentDocument&&this.currentDocument!==t&&(n=o?o(t.uri,e):t.uri.toString());let i=this.astNodeLocator.getAstNodePath(e);return{$ref:`${n}#${i}`,$refText:r}}else return{$error:t.error?.message??`Could not resolve reference`,$refText:r}}else if(ln(t)){let e=n?t.$refText:void 0,r=[];for(let e of t.items){let t=e.ref,n=Dn(e.ref),i=``;this.currentDocument&&this.currentDocument!==n&&(i=o?o(n.uri,t):n.uri.toString());let a=this.astNodeLocator.getAstNodePath(t);r.push(`${i}#${a}`)}return{$refs:r,$refText:e}}else if(M(t)){let n;if(i&&(n=this.addAstNodeRegionWithAssignmentsTo({...t}),(!e||t.$document)&&n?.$textRegion&&(n.$textRegion.documentURI=this.currentDocument?.uri.toString())),r&&!e&&(n??={...t},n.$sourceText=t.$cstNode?.text),a){n??={...t};let e=this.commentProvider.getComment(t);e&&(n.$comment=e.replace(/\r/g,``))}return n??t}else return t}addAstNodeRegionWithAssignmentsTo(e){let t=o(e=>({offset:e.offset,end:e.end,length:e.length,range:e.range}),`createDocumentSegment`);if(e.$cstNode){let n=e.$textRegion=t(e.$cstNode),r=n.assignments={};return Object.keys(e).filter(e=>!e.startsWith(`$`)).forEach(n=>{let i=Ra(e.$cstNode,n).map(t);i.length!==0&&(r[n]=i)}),e}}linkNode(e,t,n,r,i,a){for(let[r,i]of Object.entries(e))if(Array.isArray(i))for(let a=0;a{await this.handleException(()=>e.call(t,n,r,i),`An error occurred during validation`,r,n)}}async handleException(e,t,n,r){try{await e()}catch(e){if(Wj(e))throw e;console.error(`${t}:`,e),e instanceof Error&&e.stack&&console.error(e.stack),n(`error`,`${t}: ${e instanceof Error?e.message:String(e)}`,{node:r})}}addEntry(e,t){if(e===`AstNode`){this.entries.add(`AstNode`,t);return}for(let n of this.reflection.getAllSubTypes(e))this.entries.add(n,t)}getChecks(e,t){let n=N(this.entries.get(e)).concat(this.entries.get(`AstNode`));return t&&(n=n.filter(e=>t.includes(e.category))),n.map(e=>e.check)}registerBeforeDocument(e,t=this){this.entriesBefore.push(this.wrapPreparationException(e,`An error occurred during set-up of the validation`,t))}registerAfterDocument(e,t=this){this.entriesAfter.push(this.wrapPreparationException(e,`An error occurred during tear-down of the validation`,t))}wrapPreparationException(e,t,n){return async(r,i,a,o)=>{await this.handleException(()=>e.call(n,r,i,a,o),t,i,r)}}get checksBefore(){return this.entriesBefore}get checksAfter(){return this.entriesAfter}getAllValidationCategories(e){return this.knownCategories}},MM=Object.freeze({validateNode:!0,validateChildren:!0}),NM=class{static{o(this,`DefaultDocumentValidator`)}constructor(e){this.validationRegistry=e.validation.ValidationRegistry,this.metadata=e.LanguageMetaData,this.profiler=e.shared.profilers.LangiumProfiler,this.languageId=e.LanguageMetaData.languageId}async validateDocument(e,t={},n=Z.CancellationToken.None){let r=e.parseResult,i=[];if(await Gj(n),(!t.categories||t.categories.includes(`built-in`))&&(this.processLexingErrors(r,i,t),t.stopAfterLexingErrors&&i.some(e=>e.data?.code===LM.LexingError)||(this.processParsingErrors(r,i,t),t.stopAfterParsingErrors&&i.some(e=>e.data?.code===LM.ParsingError))||(this.processLinkingErrors(e,i,t),t.stopAfterLinkingErrors&&i.some(e=>e.data?.code===LM.LinkingError))))return i;try{i.push(...await this.validateAst(r.value,t,n))}catch(e){if(Wj(e))throw e;console.error(`An error occurred during validation:`,e)}return await Gj(n),i}processLexingErrors(e,t,n){let r=[...e.lexerErrors,...e.lexerReport?.diagnostics??[]];for(let e of r){let n=e.severity??`error`,r={severity:FM(n),range:{start:{line:e.line-1,character:e.column-1},end:{line:e.line-1,character:e.column+e.length-1}},message:e.message,data:IM(n),source:this.getSource()};t.push(r)}}processParsingErrors(e,t,n){for(let n of e.parserErrors){let e;if(isNaN(n.token.startOffset)){if(`previousToken`in n){let t=n.previousToken;if(isNaN(t.startOffset)){let t={line:0,character:0};e={start:t,end:t}}else{let n={line:t.endLine-1,character:t.endColumn};e={start:n,end:n}}}}else e=zi(n.token);if(e){let r={severity:FM(`error`),range:e,message:n.message,data:kM(LM.ParsingError),source:this.getSource()};t.push(r)}}}processLinkingErrors(e,t,n){for(let n of e.references){let e=n.error;if(e){let r={node:e.info.container,range:n.$refNode?.range,property:e.info.property,index:e.info.index,data:{code:LM.LinkingError,containerType:e.info.container.$type,property:e.info.property,refText:e.info.reference.$refText}};t.push(this.toDiagnostic(`error`,e.message,r))}}}async validateAst(e,t,n=Z.CancellationToken.None){let r=[],i=o((e,t,n)=>{r.push(this.toDiagnostic(e,t,n))},`acceptor`);return await this.validateAstBefore(e,t,i,n),await this.validateAstNodes(e,t,i,n),await this.validateAstAfter(e,t,i,n),r}async validateAstBefore(e,t,n,r=Z.CancellationToken.None){let i=this.validationRegistry.checksBefore;for(let a of i)await Gj(r),await a(e,n,t.categories??[],r)}async validateAstNodes(e,t,n,r=Z.CancellationToken.None){if(this.profiler?.isActive(`validating`)){let i=this.profiler.createTask(`validating`,this.languageId);i.start();try{let a=Mn(e).iterator();for(let e of a){i.startSubTask(e.$type);let o=this.validateSingleNodeOptions(e,t);if(o.validateNode)try{let i=this.validationRegistry.getChecks(e.$type,t.categories);for(let t of i)await t(e,n,r)}finally{i.stopSubTask(e.$type)}o.validateChildren||a.prune()}}finally{i.stop()}}else{let i=Mn(e).iterator();for(let e of i){await Gj(r);let a=this.validateSingleNodeOptions(e,t);if(a.validateNode){let i=this.validationRegistry.getChecks(e.$type,t.categories);for(let t of i)await t(e,n,r)}a.validateChildren||i.prune()}}}validateSingleNodeOptions(e,t){return MM}async validateAstAfter(e,t,n,r=Z.CancellationToken.None){let i=this.validationRegistry.checksAfter;for(let a of i)await Gj(r),await a(e,n,t.categories??[],r)}toDiagnostic(e,t,n){return{message:t,range:PM(n),severity:FM(e),code:n.code,codeDescription:n.codeDescription,tags:n.tags,relatedInformation:n.relatedInformation,data:n.data,source:this.getSource()}}getSource(){return this.metadata.languageId}};function PM(e){if(e.range)return e.range;let t;return typeof e.property==`string`?t=za(e.node.$cstNode,e.property,e.index):typeof e.keyword==`string`&&(t=Ha(e.node.$cstNode,e.keyword,e.index)),t??=e.node.$cstNode,t?t.range:{start:{line:0,character:0},end:{line:0,character:0}}}o(PM,`getDiagnosticRange`);function FM(e){switch(e){case`error`:return 1;case`warning`:return 2;case`info`:return 3;case`hint`:return 4;default:throw Error(`Invalid diagnostic severity: `+e)}}o(FM,`toDiagnosticSeverity`);function IM(e){switch(e){case`error`:return kM(LM.LexingError);case`warning`:return kM(LM.LexingWarning);case`info`:return kM(LM.LexingInfo);case`hint`:return kM(LM.LexingHint);default:throw Error(`Invalid diagnostic severity: `+e)}}o(IM,`toDiagnosticData`);var LM;(function(e){e.LexingError=`lexing-error`,e.LexingWarning=`lexing-warning`,e.LexingInfo=`lexing-info`,e.LexingHint=`lexing-hint`,e.ParsingError=`parsing-error`,e.LinkingError=`linking-error`})(LM||={});var RM=class{static{o(this,`DefaultAstNodeDescriptionProvider`)}constructor(e){this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider}createDescription(e,t,n){let r=n??Dn(e);t??=this.nameProvider.getName(e);let i=this.astNodeLocator.getAstNodePath(e);if(!t)throw Error(`Node at path ${i} has no name.`);let a,s=o(()=>a??=Bi(this.nameProvider.getNameNode(e)??e.$cstNode),`nameSegmentGetter`);return{node:e,name:t,get nameSegment(){return s()},selectionSegment:Bi(e.$cstNode),type:e.$type,documentUri:r.uri,path:i}}},zM=class{static{o(this,`DefaultReferenceDescriptionProvider`)}constructor(e){this.nodeLocator=e.workspace.AstNodeLocator}async createDescriptions(e,t=Z.CancellationToken.None){let n=[],r=e.parseResult.value;for(let e of Mn(r))await Gj(t),Pn(e).forEach(e=>{e.reference.error||n.push(...this.createInfoDescriptions(e))});return n}createInfoDescriptions(e){let t=e.reference;if(t.error||!t.$refNode)return[];let n=[];cn(t)&&t.$nodeDescription?n=[t.$nodeDescription]:ln(t)&&(n=t.items.map(e=>e.$nodeDescription).filter(e=>e!==void 0));let r=Dn(e.container).uri,i=this.nodeLocator.getAstNodePath(e.container),a=[],o=Bi(t.$refNode);for(let e of n)a.push({sourceUri:r,sourcePath:i,targetUri:e.documentUri,targetPath:e.path,segment:o,local:rM.equals(e.documentUri,r)});return a}},BM=class{static{o(this,`DefaultAstNodeLocator`)}constructor(){this.segmentSeparator=`/`,this.indexSeparator=`@`}getAstNodePath(e){if(e.$container){let t=this.getAstNodePath(e.$container),n=this.getPathSegment(e);return t+this.segmentSeparator+n}return``}getPathSegment({$containerProperty:e,$containerIndex:t}){if(!e)throw Error(`Missing '$containerProperty' in AST node.`);return t===void 0?e:e+this.indexSeparator+t}getAstNode(e,t){return t.split(this.segmentSeparator).reduce((e,t)=>{if(!e||t.length===0)return e;let n=t.indexOf(this.indexSeparator);if(n>0){let r=t.substring(0,n),i=parseInt(t.substring(n+1));return e[r]?.[i]}return e[t]},e)}},VM={};d(VM,f(vt(),1));var HM=class{static{o(this,`DefaultConfigurationProvider`)}constructor(e){this._ready=new Kj,this.onConfigurationSectionUpdateEmitter=new VM.Emitter,this.settings={},this.workspaceConfig=!1,this.serviceRegistry=e.ServiceRegistry}get ready(){return this._ready.promise}initialize(e){this.workspaceConfig=e.capabilities.workspace?.configuration??!1}async initialized(e){if(this.workspaceConfig){if(e.register){let t=this.serviceRegistry.all;e.register({section:t.map(e=>this.toSectionName(e.LanguageMetaData.languageId))})}if(e.fetchConfiguration){let t=this.serviceRegistry.all.map(e=>({section:this.toSectionName(e.LanguageMetaData.languageId)})),n=await e.fetchConfiguration(t);t.forEach((e,t)=>{this.updateSectionConfiguration(e.section,n[t])})}}this._ready.resolve()}updateConfiguration(e){typeof e.settings!=`object`||e.settings===null||Object.entries(e.settings).forEach(([e,t])=>{this.updateSectionConfiguration(e,t),this.onConfigurationSectionUpdateEmitter.fire({section:e,configuration:t})})}updateSectionConfiguration(e,t){this.settings[e]=t}async getConfiguration(e,t){await this.ready;let n=this.toSectionName(e);if(this.settings[n])return this.settings[n][t]}toSectionName(e){return`${e}`}get onConfigurationSectionUpdate(){return this.onConfigurationSectionUpdateEmitter.event}},UM=f(an(),1),WM;(function(e){function t(e){return{dispose:o(async()=>await e(),`dispose`)}}o(t,`create`),e.create=t})(WM||={});var GM=class{static{o(this,`DefaultDocumentBuilder`)}constructor(e){this.updateBuildOptions={validation:{categories:[`built-in`,`fast`]}},this.updateListeners=[],this.buildPhaseListeners=new fM,this.documentPhaseListeners=new fM,this.buildState=new Map,this.documentBuildWaiters=new Map,this.currentState=Q.Changed,this.langiumDocuments=e.workspace.LangiumDocuments,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.textDocuments=e.workspace.TextDocuments,this.indexManager=e.workspace.IndexManager,this.fileSystemProvider=e.workspace.FileSystemProvider,this.workspaceManager=()=>e.workspace.WorkspaceManager,this.serviceRegistry=e.ServiceRegistry}async build(e,t={},n=Z.CancellationToken.None){for(let n of e){let e=n.uri.toString();if(n.state===Q.Validated){if(typeof t.validation==`boolean`&&t.validation)this.resetToState(n,Q.IndexedReferences);else if(typeof t.validation==`object`){let r=this.findMissingValidationCategories(n,t);r.length>0&&(this.buildState.set(e,{completed:!1,options:{validation:{categories:r}},result:this.buildState.get(e)?.result}),n.state=Q.IndexedReferences)}}else this.buildState.delete(e)}this.currentState=Q.Changed,await this.emitUpdate(e.map(e=>e.uri),[]),await this.buildDocuments(e,t,n)}async update(e,t,n=Z.CancellationToken.None){this.currentState=Q.Changed;let r=[];for(let e of t){let t=this.langiumDocuments.deleteDocuments(e);for(let e of t)r.push(e.uri),this.cleanUpDeleted(e)}let i=(await Promise.all(e.map(e=>this.findChangedUris(e)))).flat();for(let e of i){let t=this.langiumDocuments.getDocument(e);t===void 0&&(t=this.langiumDocumentFactory.fromModel({$type:`INVALID`},e),t.state=Q.Changed,this.langiumDocuments.addDocument(t)),this.resetToState(t,Q.Changed)}let a=N(i).concat(r).map(e=>e.toString()).toSet();this.langiumDocuments.all.filter(e=>!a.has(e.uri.toString())&&this.shouldRelink(e,a)).forEach(e=>this.resetToState(e,Q.ComputedScopes)),await this.emitUpdate(i,r),await Gj(n);let o=this.sortDocuments(this.langiumDocuments.all.filter(e=>e.state=1}findMissingValidationCategories(e,t){let n=this.buildState.get(e.uri.toString()),r=this.serviceRegistry.getServices(e.uri).validation.ValidationRegistry.getAllValidationCategories(e),i=n?.result?.validationChecks?new Set(n?.result?.validationChecks):n?.completed?r:new Set;return N(t===void 0||t.validation===!0?r:typeof t.validation==`object`?t.validation.categories??r:[]).filter(e=>!i.has(e)).toArray()}async findChangedUris(e){if(this.langiumDocuments.getDocument(e)??this.textDocuments?.get(e))return[e];try{let t=await this.fileSystemProvider.stat(e);if(t.isDirectory)return await this.workspaceManager().searchFolder(e);if(this.workspaceManager().shouldIncludeEntry(t))return[e]}catch{}return[]}async emitUpdate(e,t){await Promise.all(this.updateListeners.map(n=>n(e,t)))}sortDocuments(e){let t=0,n=e.length-1;for(;t=0&&!this.hasTextDocument(e[n]);)n--;te.error!==void 0)?!0:this.indexManager.isAffected(e,t)}onUpdate(e){return this.updateListeners.push(e),WM.create(()=>{let t=this.updateListeners.indexOf(e);t>=0&&this.updateListeners.splice(t,1)})}resetToState(e,t){switch(t){case Q.Changed:case Q.Parsed:this.indexManager.removeContent(e.uri);case Q.IndexedContent:e.localSymbols=void 0;case Q.ComputedScopes:this.serviceRegistry.getServices(e.uri).references.Linker.unlink(e);case Q.Linked:this.indexManager.removeReferences(e.uri);case Q.IndexedReferences:e.diagnostics=void 0,this.buildState.delete(e.uri.toString());case Q.Validated:}e.state>t&&(e.state=t)}cleanUpDeleted(e){this.buildState.delete(e.uri.toString()),this.indexManager.remove(e.uri),e.state=Q.Changed}async buildDocuments(e,t,n){this.prepareBuild(e,t),await this.runCancelable(e,Q.Parsed,n,e=>this.langiumDocumentFactory.update(e,n)),await this.runCancelable(e,Q.IndexedContent,n,e=>this.indexManager.updateContent(e,n)),await this.runCancelable(e,Q.ComputedScopes,n,async e=>{e.localSymbols=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.collectLocalSymbols(e,n)});let r=e.filter(e=>this.shouldLink(e));await this.runCancelable(r,Q.Linked,n,e=>this.serviceRegistry.getServices(e.uri).references.Linker.link(e,n)),await this.runCancelable(r,Q.IndexedReferences,n,e=>this.indexManager.updateReferences(e,n));let i=e.filter(e=>this.shouldValidate(e)?!0:(this.markAsCompleted(e),!1));await this.runCancelable(i,Q.Validated,n,async e=>{await this.validate(e,n),this.markAsCompleted(e)})}markAsCompleted(e){let t=this.buildState.get(e.uri.toString());t&&(t.completed=!0)}prepareBuild(e,t){for(let n of e){let e=n.uri.toString(),r=this.buildState.get(e);(!r||r.completed)&&this.buildState.set(e,{completed:!1,options:t,result:r?.result})}}async runCancelable(e,t,n,r){for(let i of e)i.statee.state===t);await this.notifyBuildPhase(i,t,n),this.currentState=t}onBuildPhase(e,t){return this.buildPhaseListeners.add(e,t),WM.create(()=>{this.buildPhaseListeners.delete(e,t)})}onDocumentPhase(e,t){return this.documentPhaseListeners.add(e,t),WM.create(()=>{this.documentPhaseListeners.delete(e,t)})}waitUntil(e,t,n){let r;return t&&`path`in t?r=t:n=t,n??=Z.CancellationToken.None,r?this.awaitDocumentState(e,r,n):this.awaitBuilderState(e,n)}awaitDocumentState(e,t,n){let r=this.langiumDocuments.getDocument(t);return r?r.state>=e?Promise.resolve(t):n.isCancellationRequested?Promise.reject(Uj):this.currentState>=e&&e>r.state?Promise.reject(new UM.ResponseError(UM.LSPErrorCodes.RequestFailed,`Document state of ${t.toString()} is ${Q[r.state]}, requiring ${Q[e]}, but workspace state is already ${Q[this.currentState]}. Returning undefined.`)):new Promise((r,i)=>{let a=this.onDocumentPhase(e,e=>{rM.equals(e.uri,t)&&(a.dispose(),o.dispose(),r(e.uri))}),o=n.onCancellationRequested(()=>{a.dispose(),o.dispose(),i(Uj)})}):Promise.reject(new UM.ResponseError(UM.LSPErrorCodes.ServerCancelled,`No document found for URI: ${t.toString()}`))}awaitBuilderState(e,t){return this.currentState>=e?Promise.resolve():t.isCancellationRequested?Promise.reject(Uj):new Promise((n,r)=>{let i=this.onBuildPhase(e,()=>{i.dispose(),a.dispose(),n()}),a=t.onCancellationRequested(()=>{i.dispose(),a.dispose(),r(Uj)})})}async notifyDocumentPhase(e,t,n){let r=this.documentPhaseListeners.get(t).slice();for(let t of r)try{await Gj(n),await t(e,n)}catch(e){if(!Wj(e))throw e}}async notifyBuildPhase(e,t,n){if(e.length===0)return;let r=this.buildPhaseListeners.get(t).slice();for(let t of r)await Gj(n),await t(e,n)}shouldLink(e){return this.getBuildOptions(e).eagerLinking??!0}shouldValidate(e){return!!this.getBuildOptions(e).validation}async validate(e,t){let n=this.serviceRegistry.getServices(e.uri).validation.DocumentValidator,r=this.getBuildOptions(e),i=typeof r.validation==`object`?{...r.validation}:{};i.categories=this.findMissingValidationCategories(e,r);let a=await n.validateDocument(e,i,t);e.diagnostics?e.diagnostics.push(...a):e.diagnostics=a;let o=this.buildState.get(e.uri.toString());o&&(o.result??={},o.result.validationChecks?o.result.validationChecks=N(o.result.validationChecks).concat(i.categories).distinct().toArray():o.result.validationChecks=[...i.categories])}getBuildOptions(e){return this.buildState.get(e.uri.toString())?.options??{}}},KM=class{static{o(this,`DefaultIndexManager`)}constructor(e){this.symbolIndex=new Map,this.symbolByTypeIndex=new xM,this.referenceIndex=new Map,this.documents=e.workspace.LangiumDocuments,this.serviceRegistry=e.ServiceRegistry,this.astReflection=e.AstReflection}findAllReferences(e,t){let n=Dn(e).uri,r=[];return this.referenceIndex.forEach(e=>{e.forEach(e=>{rM.equals(e.targetUri,n)&&e.targetPath===t&&r.push(e)})}),N(r)}allElements(e,t){let n=N(this.symbolIndex.keys());return t&&(n=n.filter(e=>!t||t.has(e))),n.map(t=>this.getFileDescriptions(t,e)).flat()}getFileDescriptions(e,t){return t?this.symbolByTypeIndex.get(e,t,()=>(this.symbolIndex.get(e)??[]).filter(e=>this.astReflection.isSubtype(e.type,t))):this.symbolIndex.get(e)??[]}remove(e){this.removeContent(e),this.removeReferences(e)}removeContent(e){let t=e.toString();this.symbolIndex.delete(t),this.symbolByTypeIndex.clear(t)}removeReferences(e){let t=e.toString();this.referenceIndex.delete(t)}async updateContent(e,t=Z.CancellationToken.None){let n=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.collectExportedSymbols(e,t),r=e.uri.toString();this.symbolIndex.set(r,n),this.symbolByTypeIndex.clear(r)}async updateReferences(e,t=Z.CancellationToken.None){let n=await this.serviceRegistry.getServices(e.uri).workspace.ReferenceDescriptionProvider.createDescriptions(e,t);this.referenceIndex.set(e.uri.toString(),n)}isAffected(e,t){let n=this.referenceIndex.get(e.uri.toString());return n?n.some(e=>!e.local&&t.has(e.targetUri.toString())):!1}},qM=class{static{o(this,`DefaultWorkspaceManager`)}constructor(e){this.initialBuildOptions={},this._ready=new Kj,this.serviceRegistry=e.ServiceRegistry,this.langiumDocuments=e.workspace.LangiumDocuments,this.documentBuilder=e.workspace.DocumentBuilder,this.fileSystemProvider=e.workspace.FileSystemProvider,this.mutex=e.workspace.WorkspaceLock}get ready(){return this._ready.promise}get workspaceFolders(){return this.folders}initialize(e){this.folders=e.workspaceFolders??void 0}initialized(e){return this.mutex.write(e=>this.initializeWorkspace(this.folders??[],e))}async initializeWorkspace(e,t=Z.CancellationToken.None){let n=await this.performStartup(e);await Gj(t),await this.documentBuilder.build(n,this.initialBuildOptions,t)}async performStartup(e){let t=[],n=o(e=>{t.push(e),this.langiumDocuments.hasDocument(e.uri)||this.langiumDocuments.addDocument(e)},`collector`);await this.loadAdditionalDocuments(e,n);let r=[];await Promise.all(e.map(e=>this.getRootFolder(e)).map(async e=>this.traverseFolder(e,r)));let i=N(r).distinct(e=>e.toString()).filter(e=>!this.langiumDocuments.hasDocument(e));return await this.loadWorkspaceDocuments(i,n),this._ready.resolve(),t}async loadWorkspaceDocuments(e,t){await Promise.all(e.map(async e=>{t(await this.langiumDocuments.getOrCreateDocument(e))}))}loadAdditionalDocuments(e,t){return Promise.resolve()}getRootFolder(e){return tM.parse(e.uri)}async traverseFolder(e,t){try{let n=await this.fileSystemProvider.readDirectory(e);await Promise.all(n.map(async e=>{this.shouldIncludeEntry(e)&&(e.isDirectory?await this.traverseFolder(e.uri,t):e.isFile&&t.push(e.uri))}))}catch(t){console.error(`Failure to read directory content of `+e.toString(!0),t)}}async searchFolder(e){let t=[];return await this.traverseFolder(e,t),t}shouldIncludeEntry(e){let t=rM.basename(e.uri);return t.startsWith(`.`)?!1:e.isDirectory?t!==`node_modules`&&t!==`out`:e.isFile?this.serviceRegistry.hasServices(e.uri):!1}},JM=class{static{o(this,`DefaultLexerErrorMessageProvider`)}buildUnexpectedCharactersMessage(e,t,n,r,i){return zy.buildUnexpectedCharactersMessage(e,t,n,r,i)}buildUnableToPopLexerModeMessage(e){return zy.buildUnableToPopLexerModeMessage(e)}},YM={mode:`full`},XM=class{static{o(this,`DefaultLexer`)}constructor(e){this.errorMessageProvider=e.parser.LexerErrorMessageProvider,this.tokenBuilder=e.parser.TokenBuilder;let t=this.tokenBuilder.buildTokens(e.Grammar,{caseInsensitive:e.LanguageMetaData.caseInsensitive});this.tokenTypes=this.toTokenTypeDictionary(t);let n=$M(t)?Object.values(t):t,r=e.LanguageMetaData.mode===`production`;this.chevrotainLexer=new Vy(n,{positionTracking:`full`,skipValidations:r,errorMessageProvider:this.errorMessageProvider})}get definition(){return this.tokenTypes}tokenize(e,t=YM){let n=this.chevrotainLexer.tokenize(e);return{tokens:n.tokens,errors:n.errors,hidden:n.groups.hidden??[],report:this.tokenBuilder.flushLexingReport?.(e)}}toTokenTypeDictionary(e){if($M(e))return e;let t=QM(e)?Object.values(e.modes).flat():e,n={};return t.forEach(e=>n[e.name]=e),n}};function ZM(e){return Array.isArray(e)&&(e.length===0||`name`in e[0])}o(ZM,`isTokenTypeArray`);function QM(e){return e&&`modes`in e&&`defaultMode`in e}o(QM,`isIMultiModeLexerDefinition`);function $M(e){return!ZM(e)&&!QM(e)}o($M,`isTokenTypeDictionary`),ht();function eN(e,t,n){let r,i;typeof e==`string`?(i=t,r=n):(i=e.range.start,r=t),i||=y.create(0,0);let a=nN(e),o=vN(r);return dN({index:0,tokens:aN({lines:a,position:i,options:o}),position:i})}o(eN,`parseJSDoc`);function tN(e,t){let n=vN(t),r=nN(e);if(r.length===0)return!1;let i=r[0],a=r[r.length-1],o=n.start,s=n.end;return!!o?.exec(i)&&!!s?.exec(a)}o(tN,`isJSDoc`);function nN(e){let t=``;return t=typeof e==`string`?e:e.text,t.split(xa)}o(nN,`getLines`);var rN=/\s*(@([\p{L}][\p{L}\p{N}]*)?)/uy,iN=/\{(@[\p{L}][\p{L}\p{N}]*)(\s*)([^\r\n}]+)?\}/gu;function aN(e){let t=[],n=e.position.line,r=e.position.character;for(let i=0;i=s.length){if(t.length>0){let e=y.create(n,r);t.push({type:`break`,content:``,range:b.create(e,e)})}}else{rN.lastIndex=c;let e=rN.exec(s);if(e){let i=e[0],a=e[1],o=y.create(n,r+c),l=y.create(n,r+c+i.length);t.push({type:`tag`,content:a,range:b.create(o,l)}),c+=i.length,c=lN(s,c)}if(c0&&t[t.length-1].type===`break`?t.slice(0,-1):t}o(aN,`tokenize`);function oN(e,t,n,r){let i=[];if(e.length===0){let e=y.create(n,r),a=y.create(n,r+t.length);i.push({type:`text`,content:t,range:b.create(e,a)})}else{let a=0;for(let o of e){let e=o.index,s=t.substring(a,e);s.length>0&&i.push({type:`text`,content:t.substring(a,e),range:b.create(y.create(n,a+r),y.create(n,e+r))});let c=s.length+1,l=o[1];if(i.push({type:`inline-tag`,content:l,range:b.create(y.create(n,a+c+r),y.create(n,a+c+l.length+r))}),c+=l.length,o.length===4){c+=o[2].length;let e=o[3];i.push({type:`text`,content:e,range:b.create(y.create(n,a+c+r),y.create(n,a+c+e.length+r))})}else i.push({type:`text`,content:``,range:b.create(y.create(n,a+c+r),y.create(n,a+c+r))});a=e+o[0].length}let o=t.substring(a);o.length>0&&i.push({type:`text`,content:o,range:b.create(y.create(n,a+r),y.create(n,a+r+o.length))})}return i}o(oN,`buildInlineTokens`);var sN=/\S/,cN=/\s*$/;function lN(e,t){let n=e.substring(t).match(sN);return n?t+n.index:e.length}o(lN,`skipWhitespace`);function uN(e){let t=e.match(cN);if(t&&typeof t.index==`number`)return t.index}o(uN,`lastCharacter`);function dN(e){let t=y.create(e.position.line,e.position.character);if(e.tokens.length===0)return new bN([],b.create(t,t));let n=[];for(;e.indext.name===e)}getTags(e){return this.getAllTags().filter(t=>t.name===e)}getAllTags(){return this.elements.filter(e=>`name`in e)}toString(){let e=``;for(let t of this.elements)if(e.length===0)e=t.toString();else{let n=t.toString();e+=EN(e)+n}return e.trim()}toMarkdown(e){let t=``;for(let n of this.elements)if(t.length===0)t=n.toMarkdown(e);else{let r=n.toMarkdown(e);t+=EN(t)+r}return t.trim()}},xN=class{static{o(this,`JSDocTagImpl`)}constructor(e,t,n,r){this.name=e,this.content=t,this.inline=n,this.range=r}toString(){let e=`@${this.name}`,t=this.content.toString();return this.content.inlines.length===1?e=`${e} ${t}`:this.content.inlines.length>1&&(e=`${e} +${t}`),this.inline?`{${e}}`:e}toMarkdown(e){return e?.renderTag?.(this)??this.toMarkdownDefault(e)}toMarkdownDefault(e){let t=this.content.toMarkdown(e);if(this.inline){let n=SN(this.name,t,e??{});if(typeof n==`string`)return n}let n=``;e?.tag===`italic`||e?.tag===void 0?n=`*`:e?.tag===`bold`?n=`**`:e?.tag===`bold-italic`&&(n=`***`);let r=`${n}@${this.name}${n}`;return this.content.inlines.length===1?r=`${r} \u2014 ${t}`:this.content.inlines.length>1&&(r=`${r} +${t}`),this.inline?`{${r}}`:r}};function SN(e,t,n){if(e===`linkplain`||e===`linkcode`||e===`link`){let r=t.indexOf(` `),i=t;if(r>0){let e=lN(t,r);i=t.substring(e),t=t.substring(0,r)}return(e===`linkcode`||e===`link`&&n.link===`code`)&&(i=`\`${i}\``),n.renderLink?.(t,i)??CN(t,i)}}o(SN,`renderInlineTag`);function CN(e,t){try{return tM.parse(e,!0),`[${t}](${e})`}catch{return e}}o(CN,`renderLinkDefault`);var wN=class{static{o(this,`JSDocTextImpl`)}constructor(e,t){this.inlines=e,this.range=t}toString(){let e=``;for(let t=0;tn.range.start.line&&(e+=` +`)}return e}toMarkdown(e){let t=``;for(let n=0;nr.range.start.line&&(t+=` +`)}return t}},TN=class{static{o(this,`JSDocLineImpl`)}constructor(e,t){this.text=e,this.range=t}toString(){return this.text}toMarkdown(){return this.text}};function EN(e){return e.endsWith(` +`)?` +`:` + +`}o(EN,`fillNewlines`);var DN=class{static{o(this,`JSDocDocumentationProvider`)}constructor(e){this.indexManager=e.shared.workspace.IndexManager,this.commentProvider=e.documentation.CommentProvider}getDocumentation(e){let t=this.commentProvider.getComment(e);if(t&&tN(t))return eN(t).toMarkdown({renderLink:o((t,n)=>this.documentationLinkRenderer(e,t,n),`renderLink`),renderTag:o(t=>this.documentationTagRenderer(e,t),`renderTag`)})}documentationLinkRenderer(e,t,n){let r=this.findNameInLocalSymbols(e,t)??this.findNameInGlobalScope(e,t);if(r&&r.nameSegment){let e=r.nameSegment.range.start.line+1,t=r.nameSegment.range.start.character+1;return`[${n}](${r.documentUri.with({fragment:`L${e},${t}`}).toString()})`}else return}documentationTagRenderer(e,t){}findNameInLocalSymbols(e,t){let n=Dn(e).localSymbols;if(!n)return;let r=e;do{let e=n.getStream(r).find(e=>e.name===t);if(e)return e;r=r.$container}while(r)}findNameInGlobalScope(e,t){return this.indexManager.allElements().find(e=>e.name===t)}},ON=class{static{o(this,`DefaultCommentProvider`)}constructor(e){this.grammarConfig=()=>e.parser.GrammarConfig}getComment(e){return TM(e)?e.$comment:Ki(e.$cstNode,this.grammarConfig().multilineCommentRules)?.text}},kN=class{static{o(this,`DefaultAsyncParser`)}constructor(e){this.syncParser=e.parser.LangiumParser}parse(e,t){return Promise.resolve(this.syncParser.parse(e))}},AN=class{static{o(this,`AbstractThreadedAsyncParser`)}constructor(e){this.threadCount=8,this.terminationDelay=200,this.workerPool=[],this.queue=[],this.hydrator=e.serializer.Hydrator}initializeWorkers(){for(;this.workerPool.length{if(this.queue.length>0){let t=this.queue.shift();t&&(e.lock(),t.resolve(e))}}),this.workerPool.push(e)}}async parse(e,t){let n=await this.acquireParserWorker(t),r=new Kj,i,a=t.onCancellationRequested(()=>{i=setTimeout(()=>{this.terminateWorker(n)},this.terminationDelay)});return n.parse(e).then(e=>{let t=this.hydrator.hydrate(e);r.resolve(t)}).catch(e=>{r.reject(e)}).finally(()=>{a.dispose(),clearTimeout(i)}),r.promise}terminateWorker(e){e.terminate();let t=this.workerPool.indexOf(e);t>=0&&this.workerPool.splice(t,1)}async acquireParserWorker(e){this.initializeWorkers();for(let e of this.workerPool)if(e.ready)return e.lock(),e;let t=new Kj;return e.onCancellationRequested(()=>{let e=this.queue.indexOf(t);e>=0&&this.queue.splice(e,1),t.reject(Uj)}),this.queue.push(t),t.promise}},jN=class{static{o(this,`ParserWorker`)}get ready(){return this._ready}get onReady(){return this.onReadyEmitter.event}constructor(e,t,n,r){this.onReadyEmitter=new VM.Emitter,this.deferred=new Kj,this._ready=!0,this._parsing=!1,this.sendMessage=e,this._terminate=r,t(e=>{let t=e;this.deferred.resolve(t),this.unlock()}),n(e=>{this.deferred.reject(e),this.unlock()})}terminate(){this.deferred.reject(Uj),this._terminate()}lock(){this._ready=!1}unlock(){this._parsing=!1,this._ready=!0,this.onReadyEmitter.fire()}parse(e){if(this._parsing)throw Error(`Parser worker is busy`);return this._parsing=!0,this.deferred=new Kj,this.sendMessage(e),this.deferred.promise}},MN=class{static{o(this,`DefaultWorkspaceLock`)}constructor(){this.previousTokenSource=new Z.CancellationTokenSource,this.writeQueue=[],this.readQueue=[],this.done=!0}write(e){this.cancelWrite();let t=Vj();return this.previousTokenSource=t,this.enqueue(this.writeQueue,e,t.token)}read(e){return this.enqueue(this.readQueue,e)}enqueue(e,t,n=Z.CancellationToken.None){let r=new Kj,i={action:t,deferred:r,cancellationToken:n};return e.push(i),this.performNextOperation(),r.promise}async performNextOperation(){if(!this.done)return;let e=[];if(this.writeQueue.length>0)e.push(this.writeQueue.shift());else if(this.readQueue.length>0)e.push(...this.readQueue.splice(0,this.readQueue.length));else return;this.done=!1,await Promise.all(e.map(async({action:e,deferred:t,cancellationToken:n})=>{try{let r=await Promise.resolve().then(()=>e(n));t.resolve(r)}catch(e){Wj(e)?t.resolve(void 0):t.reject(e)}})),this.done=!0,this.performNextOperation()}cancelWrite(){this.previousTokenSource.cancel()}},NN=class{static{o(this,`DefaultHydrator`)}constructor(e){this.grammarElementIdMap=new pM,this.tokenTypeIdMap=new pM,this.grammar=e.Grammar,this.lexer=e.parser.Lexer,this.linker=e.references.Linker}dehydrate(e){return{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport?this.dehydrateLexerReport(e.lexerReport):void 0,parserErrors:e.parserErrors.map(e=>({...e,message:e.message})),value:this.dehydrateAstNode(e.value,this.createDehyrationContext(e.value))}}dehydrateLexerReport(e){return e}createDehyrationContext(e){let t=new Map,n=new Map;for(let n of Mn(e))t.set(n,{});if(e.$cstNode)for(let t of Ii(e.$cstNode))n.set(t,{});return{astNodes:t,cstNodes:n}}dehydrateAstNode(e,t){let n=t.astNodes.get(e);n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode!==void 0&&(n.$cstNode=this.dehydrateCstNode(e.$cstNode,t));for(let[r,i]of Object.entries(e))if(!r.startsWith(`$`))if(Array.isArray(i)){let e=[];n[r]=e;for(let n of i)M(n)?e.push(this.dehydrateAstNode(n,t)):cn(n)?e.push(this.dehydrateReference(n,t)):e.push(n)}else M(i)?n[r]=this.dehydrateAstNode(i,t):cn(i)?n[r]=this.dehydrateReference(i,t):i!==void 0&&(n[r]=i);return n}dehydrateReference(e,t){let n={};return n.$refText=e.$refText,e.$refNode&&(n.$refNode=t.cstNodes.get(e.$refNode)),n}dehydrateCstNode(e,t){let n=t.cstNodes.get(e);return hn(e)?n.fullText=e.fullText:n.grammarSource=this.getGrammarElementId(e.grammarSource),n.hidden=e.hidden,n.astNode=t.astNodes.get(e.astNode),pn(e)?n.content=e.content.map(e=>this.dehydrateCstNode(e,t)):mn(e)&&(n.tokenType=e.tokenType.name,n.offset=e.offset,n.length=e.length,n.startLine=e.range.start.line,n.startColumn=e.range.start.character,n.endLine=e.range.end.line,n.endColumn=e.range.end.character),n}hydrate(e){let t=e.value,n=this.createHydrationContext(t);return`$cstNode`in t&&this.hydrateCstNode(t.$cstNode,n),{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport,parserErrors:e.parserErrors,value:this.hydrateAstNode(t,n)}}createHydrationContext(e){let t=new Map,n=new Map;for(let n of Mn(e))t.set(n,{});let r;if(e.$cstNode)for(let t of Ii(e.$cstNode)){let e;`fullText`in t?(e=new tj(t.fullText),r=e):`content`in t?e=new $A:`tokenType`in t&&(e=this.hydrateCstLeafNode(t)),e&&(n.set(t,e),e.root=r)}return{astNodes:t,cstNodes:n}}hydrateAstNode(e,t){let n=t.astNodes.get(e);n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode&&(n.$cstNode=t.cstNodes.get(e.$cstNode));for(let[r,i]of Object.entries(e))if(!r.startsWith(`$`))if(Array.isArray(i)){let e=[];n[r]=e;for(let a of i)M(a)?e.push(this.setParent(this.hydrateAstNode(a,t),n)):cn(a)?e.push(this.hydrateReference(a,n,r,t)):e.push(a)}else M(i)?n[r]=this.setParent(this.hydrateAstNode(i,t),n):cn(i)?n[r]=this.hydrateReference(i,n,r,t):i!==void 0&&(n[r]=i);return n}setParent(e,t){return e.$container=t,e}hydrateReference(e,t,n,r){return this.linker.buildReference(t,n,r.cstNodes.get(e.$refNode),e.$refText)}hydrateCstNode(e,t,n=0){let r=t.cstNodes.get(e);if(typeof e.grammarSource==`number`&&(r.grammarSource=this.getGrammarElement(e.grammarSource)),r.astNode=t.astNodes.get(e.astNode),pn(r))for(let i of e.content){let e=this.hydrateCstNode(i,t,n++);r.content.push(e)}return r}hydrateCstLeafNode(e){let t=this.getTokenType(e.tokenType),n=e.offset,r=e.length,i=e.startLine,a=e.startColumn,o=e.endLine,s=e.endColumn,c=e.hidden;return new QA(n,r,{start:{line:i,character:a},end:{line:o,character:s}},t,c)}getTokenType(e){return this.lexer.definition[e]}getGrammarElementId(e){if(e)return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.get(e)}getGrammarElement(e){return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.getKey(e)}createGrammarElementIdMap(){let e=0;for(let t of Mn(this.grammar))Vn(t)&&this.grammarElementIdMap.set(t,e++)}};function PN(e){return{documentation:{CommentProvider:o(e=>new ON(e),`CommentProvider`),DocumentationProvider:o(e=>new DN(e),`DocumentationProvider`)},parser:{AsyncParser:o(e=>new kN(e),`AsyncParser`),GrammarConfig:o(e=>_o(e),`GrammarConfig`),LangiumParser:o(e=>Nj(e),`LangiumParser`),CompletionParser:o(e=>Mj(e),`CompletionParser`),ValueConverter:o(()=>new Ij,`ValueConverter`),TokenBuilder:o(()=>new Fj,`TokenBuilder`),Lexer:o(e=>new XM(e),`Lexer`),ParserErrorMessageProvider:o(()=>new lj,`ParserErrorMessageProvider`),LexerErrorMessageProvider:o(()=>new JM,`LexerErrorMessageProvider`)},workspace:{AstNodeLocator:o(()=>new BM,`AstNodeLocator`),AstNodeDescriptionProvider:o(e=>new RM(e),`AstNodeDescriptionProvider`),ReferenceDescriptionProvider:o(e=>new zM(e),`ReferenceDescriptionProvider`)},references:{Linker:o(e=>new cM(e),`Linker`),NameProvider:o(()=>new uM,`NameProvider`),ScopeProvider:o(e=>new wM(e),`ScopeProvider`),ScopeComputation:o(e=>new mM(e),`ScopeComputation`),References:o(e=>new dM(e),`References`)},serializer:{Hydrator:o(e=>new NN(e),`Hydrator`),JsonSerializer:o(e=>new DM(e),`JsonSerializer`)},validation:{DocumentValidator:o(e=>new NM(e),`DocumentValidator`),ValidationRegistry:o(e=>new jM(e),`ValidationRegistry`)},shared:o(()=>e.shared,`shared`)}}o(PN,`createDefaultCoreModule`);function FN(e){return{ServiceRegistry:o(e=>new OM(e),`ServiceRegistry`),workspace:{LangiumDocuments:o(e=>new oM(e),`LangiumDocuments`),LangiumDocumentFactory:o(e=>new aM(e),`LangiumDocumentFactory`),DocumentBuilder:o(e=>new GM(e),`DocumentBuilder`),IndexManager:o(e=>new KM(e),`IndexManager`),WorkspaceManager:o(e=>new qM(e),`WorkspaceManager`),FileSystemProvider:o(t=>e.fileSystemProvider(t),`FileSystemProvider`),WorkspaceLock:o(()=>new MN,`WorkspaceLock`),ConfigurationProvider:o(e=>new HM(e),`ConfigurationProvider`)},profilers:{}}}o(FN,`createDefaultSharedCoreModule`);var IN;(function(e){e.merge=(e,t)=>UN(UN({},e),t)})(IN||={});function LN(e,t,n,r,i,a,o,s,c){return BN([e,t,n,r,i,a,o,s,c].reduce(UN,{}))}o(LN,`inject`);var RN=Symbol(`isProxy`);function zN(e){if(e&&e[RN])for(let t of Object.values(e))zN(t);return e}o(zN,`eagerLoad`);function BN(e,t){let n=new Proxy({},{deleteProperty:o(()=>!1,`deleteProperty`),set:o(()=>{throw Error(`Cannot set property on injected service container`)},`set`),get:o((r,i)=>i===RN||HN(r,i,e,t||n),`get`),getOwnPropertyDescriptor:o((r,i)=>(HN(r,i,e,t||n),Object.getOwnPropertyDescriptor(r,i)),`getOwnPropertyDescriptor`),has:o((t,n)=>n in e,`has`),ownKeys:o(()=>[...Object.getOwnPropertyNames(e)],`ownKeys`)});return n}o(BN,`_inject`);var VN=Symbol();function HN(e,t,n,r){if(t in e){if(e[t]instanceof Error)throw Error(`Construction failure. Please make sure that your dependencies are constructable. Cause: `+e[t]);if(e[t]===VN)throw Error(`Cycle detected. Please make "`+String(t)+`" lazy. Visit https://langium.org/docs/reference/configuration-services/#resolving-cyclic-dependencies`);return e[t]}else if(t in n){let i=n[t];e[t]=VN;try{e[t]=typeof i==`function`?i(r):BN(i,r)}catch(n){throw e[t]=n instanceof Error?n:void 0,n}return e[t]}else return}o(HN,`_resolve`);function UN(e,t){if(t){for(let[n,r]of Object.entries(t))if(r!=null)if(typeof r==`object`){let t=e[n];typeof t==`object`&&t?e[n]=UN(t,r):e[n]=UN({},r)}else e[n]=r}return e}o(UN,`_merge`);var WN={indentTokenName:`INDENT`,dedentTokenName:`DEDENT`,whitespaceTokenName:`WS`,ignoreIndentationDelimiters:[]},GN;(function(e){e.REGULAR=`indentation-sensitive`,e.IGNORE_INDENTATION=`ignore-indentation`})(GN||={});var KN=class extends Fj{static{o(this,`IndentationAwareTokenBuilder`)}constructor(e=WN){super(),this.indentationStack=[0],this.whitespaceRegExp=/[ \t]+/y,this.options={...WN,...e},this.indentTokenType=$y({name:this.options.indentTokenName,pattern:this.indentMatcher.bind(this),line_breaks:!1}),this.dedentTokenType=$y({name:this.options.dedentTokenName,pattern:this.dedentMatcher.bind(this),line_breaks:!1})}buildTokens(e,t){let n=super.buildTokens(e,t);if(!ZM(n))throw Error(`Invalid tokens built by default builder`);let{indentTokenName:r,dedentTokenName:i,whitespaceTokenName:a,ignoreIndentationDelimiters:o}=this.options,s,c,l,u=[];for(let e of n){for(let[t,n]of o)e.name===t?e.PUSH_MODE=GN.IGNORE_INDENTATION:e.name===n&&(e.POP_MODE=!0);e.name===i?s=e:e.name===r?c=e:e.name===a?l=e:u.push(e)}if(!s||!c||!l)throw Error(`Some indentation/whitespace tokens not found!`);return o.length>0?{modes:{[GN.REGULAR]:[s,c,...u,l],[GN.IGNORE_INDENTATION]:[...u,l]},defaultMode:GN.REGULAR}:[s,c,l,...u]}flushLexingReport(e){return{...super.flushLexingReport(e),remainingDedents:this.flushRemainingDedents(e)}}isStartOfLine(e,t){return t===0||`\r +`.includes(e[t-1])}matchWhitespace(e,t,n,r){this.whitespaceRegExp.lastIndex=t;let i=this.whitespaceRegExp.exec(e);return{currIndentLevel:i?.[0].length??0,prevIndentLevel:this.indentationStack.at(-1),match:i}}createIndentationTokenInstance(e,t,n,r){let i=this.getLineNumber(t,r);return nb(e,n,r,r+n.length,i,i,1,n.length)}getLineNumber(e,t){return e.substring(0,t).split(/\r\n|\r|\n/).length}indentMatcher(e,t,n,r){if(!this.isStartOfLine(e,t))return null;let{currIndentLevel:i,prevIndentLevel:a,match:o}=this.matchWhitespace(e,t,n,r);return i<=a?null:(this.indentationStack.push(i),o)}dedentMatcher(e,t,n,r){if(!this.isStartOfLine(e,t))return null;let{currIndentLevel:i,prevIndentLevel:a,match:o}=this.matchWhitespace(e,t,n,r);if(i>=a)return null;let s=this.indentationStack.lastIndexOf(i);if(s===-1)return this.diagnostics.push({severity:`error`,message:`Invalid dedent level ${i} at offset: ${t}. Current indentation stack: ${this.indentationStack}`,offset:t,length:o?.[0]?.length??0,line:this.getLineNumber(e,t),column:1}),null;let c=this.indentationStack.length-s-1,l=e.substring(0,t).match(/[\r\n]+$/)?.[0].length??1;for(let r=0;r1;)t.push(this.createIndentationTokenInstance(this.dedentTokenType,e,``,e.length)),this.indentationStack.pop();return this.indentationStack=[0],t}},qN=class extends XM{static{o(this,`IndentationAwareLexer`)}constructor(e){if(super(e),e.parser.TokenBuilder instanceof KN)this.indentationTokenBuilder=e.parser.TokenBuilder;else throw Error(`IndentationAwareLexer requires an accompanying IndentationAwareTokenBuilder`)}tokenize(e,t=YM){let n=super.tokenize(e),r=n.report;t?.mode===`full`&&n.tokens.push(...r.remainingDedents),r.remainingDedents=[];let{indentTokenType:i,dedentTokenType:a}=this.indentationTokenBuilder,o=i.tokenTypeIdx,s=a.tokenTypeIdx,c=[],l=n.tokens.length-1;for(let e=0;e=0&&c.push(n.tokens[l]),n.tokens=c,n}},JN={};l(JN,{AstUtils:()=>Cn,BiMap:()=>pM,Cancellation:()=>Z,ContextCache:()=>xM,CstUtils:()=>sn,DONE_RESULT:()=>bn,Deferred:()=>Kj,Disposable:()=>WM,DisposableCache:()=>yM,DocumentCache:()=>SM,EMPTY_STREAM:()=>yn,ErrorWithLocation:()=>ia,GrammarUtils:()=>ra,MultiMap:()=>fM,OperationCancelled:()=>Uj,Reduction:()=>Sn,RegExpUtils:()=>sa,SimpleCache:()=>bM,StreamImpl:()=>gn,TreeStreamImpl:()=>xn,URI:()=>tM,UriTrie:()=>iM,UriUtils:()=>rM,WorkspaceCache:()=>CM,assertCondition:()=>oa,assertUnreachable:()=>aa,delayNextTick:()=>Rj,interruptAndCheck:()=>Gj,isOperationCancelled:()=>Wj,loadGrammarFromJson:()=>eP,setInterruptionPeriod:()=>Hj,startCancelableOperation:()=>Vj,stream:()=>N}),d(JN,VM);var YN=class{static{o(this,`EmptyFileSystemProvider`)}stat(e){throw Error(`No file system is available.`)}statSync(e){throw Error(`No file system is available.`)}async exists(){return!1}existsSync(){return!1}readBinary(){throw Error(`No file system is available.`)}readBinarySync(){throw Error(`No file system is available.`)}readFile(){throw Error(`No file system is available.`)}readFileSync(){throw Error(`No file system is available.`)}async readDirectory(){return[]}readDirectorySync(){return[]}},XN={fileSystemProvider:o(()=>new YN,`fileSystemProvider`)},ZN={Grammar:o(()=>void 0,`Grammar`),LanguageMetaData:o(()=>({caseInsensitive:!1,fileExtensions:[`.langium`],languageId:`langium`}),`LanguageMetaData`)},QN={AstReflection:o(()=>new Pi,`AstReflection`)};function $N(){let e=LN(FN(XN),QN),t=LN(PN({shared:e}),ZN);return e.ServiceRegistry.register(t),t}o($N,`createMinimalGrammarServices`);function eP(e){let t=$N(),n=t.serializer.JsonSerializer.deserialize(e);return t.shared.workspace.LangiumDocumentFactory.fromModel(n,tM.parse(`memory:/${n.name??`grammar`}.langium`)),n}o(eP,`loadGrammarFromJson`),d(on,JN);var tP=class{static{o(this,`DefaultLangiumProfiler`)}constructor(e){this.activeCategories=new Set,this.allCategories=new Set([`validating`,`parsing`,`linking`]),this.activeCategories=e??new Set(this.allCategories),this.records=new fM}isActive(e){return this.activeCategories.has(e)}start(...e){e?e.forEach(e=>this.activeCategories.add(e)):this.activeCategories=new Set(this.allCategories)}stop(...e){e?e.forEach(e=>this.activeCategories.delete(e)):this.activeCategories.clear()}createTask(e,t){if(!this.isActive(e))throw Error(`Category "${e}" is not active.`);return console.log(`Creating profiling task for '${e}.${t}'.`),new nP(t=>this.records.add(e,this.dumpRecord(e,t)),t)}dumpRecord(e,t){console.info(`Task ${e}.${t.identifier} executed in ${t.duration.toFixed(2)}ms and ended at ${t.date.toISOString()}`);let n=[];for(let e of t.entries.keys()){let r=t.entries.get(e),i=r.reduce((e,t)=>e+t);n.push({name:`${t.identifier}.${e}`,count:r.length,duration:i})}let r=t.duration-n.map(e=>e.duration).reduce((e,t)=>e+t,0);n.push({name:t.identifier,count:1,duration:r}),n.sort((e,t)=>t.duration-e.duration);function i(e){return Math.round(100*e)/100}return o(i,`Round`),console.table(n.map(e=>({Element:e.name,Count:e.count,"Self %":i(100*e.duration/t.duration),"Time (ms)":i(e.duration)}))),t}getRecords(...e){return e.length===0?this.records.values():this.records.entries().filter(t=>e.some(e=>e===t[0])).flatMap(e=>e[1])}},nP=class{static{o(this,`ProfilingTask`)}constructor(e,t){this.stack=[],this.entries=new fM,this.addRecord=e,this.identifier=t}start(){if(this.startTime!==void 0)throw Error(`Task "${this.identifier}" is already started.`);this.startTime=performance.now()}stop(){if(this.startTime===void 0)throw Error(`Task "${this.identifier}" was not started.`);if(this.stack.length!==0)throw Error(`Task "${this.identifier}" cannot be stopped before sub-task(s): ${this.stack.map(e=>e.id).join(`, `)}.`);let e={identifier:this.identifier,date:new Date,duration:performance.now()-this.startTime,entries:this.entries};this.addRecord(e),this.startTime=void 0,this.entries.clear()}startSubTask(e){this.stack.push({id:e,start:performance.now(),content:0})}stopSubTask(e){let t=this.stack.pop();if(!t)throw Error(`Task "${this.identifier}.${e}" was not started.`);if(t.id!==e)throw Error(`Sub-Task "${t.id}" is not already stopped.`);let n=performance.now()-t.start;this.stack.at(-1)!==void 0&&(this.stack[this.stack.length-1].content+=n);let r=n-t.content;this.entries.add(e,r)}},rP;(e=>{e.Terminals={ARROW_DIRECTION:/L|R|T|B/,ARROW_GROUP:/\{group\}/,ARROW_INTO:/<|>/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,ID:/[\w]([-\w]*\w)?/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,ARCH_ICON:/\([\w-:]+\)/,ARCH_TITLE:/\[(?:"([^"\\]|\\.)*"|'([^'\\]|\\.)*'|[\w ]+)\]/}})(rP||={});var iP;(e=>{e.Terminals={DOMAIN_NAME:/complex|complicated|clear|chaotic|confusion/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(iP||={});var aP;(e=>{e.Terminals={EM_ID:/[_a-zA-Z][\w_]*/,EM_FID:/\d{1,3}/,EM_DATA_INLINE:/\{(.*)\}|"(.*)"|'(.*)'/,EM_DATA_BLOCK:/\{[\t ]*\r?\n(?:[\S\s]*?\r?\n)?\}(?:\r?\n|(?!\S))/,EM_ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,EM_ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,EM_TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,EM_WS:/\s+/,EM_YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,EM_DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,EM_SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,EM_ML_COMMENT:/\/\*[\s\S]*?\*\//,EM_SL_COMMENT:/\/\/[^\n\r]*/}})(aP||={});var oP;(e=>{e.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INT:/0|[1-9][0-9]*(?!\.)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,REFERENCE:/\w([-\./\w]*[-\w])?/}})(oP||={});var sP;(e=>{e.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(sP||={});var cP;(e=>{e.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INT:/0|[1-9][0-9]*(?!\.)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(cP||={});var lP;(e=>{e.Terminals={NUMBER_PIE:/(?:-?[0-9]+\.[0-9]+(?!\.))|(?:-?(0|[1-9][0-9]*)(?!\.))/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(lP||={});var uP;(e=>{e.Terminals={GRATICULE:/circle|polygon/,BOOLEAN:/true|false/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,NUMBER:/(?:[0-9]+\.[0-9]+(?!\.))|(?:0|[1-9][0-9]*(?!\.))/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,ID:/[\w]([-\w]*\w)?/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(uP||={});var dP;(e=>{e.Terminals={TITLE:/title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,ACC_TITLE:/accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,ACC_DESCR:/accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ABNF_RULENAME:/[A-Za-z][A-Za-z0-9-]*/,ABNF_STRING:/"[^"]*"/,ABNF_NUMVAL:/%[xXdDbB][0-9A-Fa-f]+(?:-[0-9A-Fa-f]+|\.[0-9A-Fa-f]+)*/,ABNF_REPEAT:/[0-9]*\*[0-9]*/,ABNF_EXACT_REPEAT:/[0-9]+/,ABNF_WHITESPACE:/[\t \r\n]+/,ABNF_YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,ABNF_DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,ABNF_SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,ABNF_COMMENT:/;[^\n\r]*/}})(dP||={});var fP;(e=>{e.Terminals={TITLE:/title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,ACC_TITLE:/accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,ACC_DESCR:/accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,EBNF_ID:/[A-Z_a-z][\w-]*/,EBNF_STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,EBNF_SPECIAL_SEQUENCE:/\?(?=[^?;]*[^?\s;][^?;]*\?)[^?;]*\?/,EBNF_WHITESPACE:/[\t \r\n]+/,EBNF_YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,EBNF_DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,EBNF_SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,EBNF_BLOCK_COMMENT:/\/\*[\s\S]*?\*\//,EBNF_ISO_COMMENT:/\(\*[\s\S]*?\*\)/}})(fP||={});var pP;(e=>{e.Terminals={TITLE:/title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,ACC_TITLE:/accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,ACC_DESCR:/accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,RR_ID:/[A-Z_a-z][\w-]*/,RR_STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,RR_WHITESPACE:/[\t \r\n]+/,RR_YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,RR_DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,RR_SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,RR_BLOCK_COMMENT:/\/\*[\s\S]*?\*\//}})(pP||={});var mP;(e=>{e.Terminals={TITLE:/title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,ACC_TITLE:/accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,ACC_DESCR:/accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,PEG_ID:/[A-Z_a-z][\w-]*/,PEG_STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,PEG_WHITESPACE:/[\t \r\n]+/,PEG_YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,PEG_DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,PEG_SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,PEG_LINE_COMMENT:/#[^\n\r]*/}})(mP||={});var hP;(e=>{e.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,TREEMAP_KEYWORD:/treemap-beta|treemap/,CLASS_DEF:/classDef\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\s+([^;\r\n]*))?(?:;)?/,STYLE_SEPARATOR:/:::/,SEPARATOR:/:/,COMMA:/,/,INDENTATION:/[ \t]{1,}/,WS:/[ \t]+/,ML_COMMENT:/\%\%[^\n]*/,NL:/\r?\n/,ID2:/[a-zA-Z_][a-zA-Z0-9_]*/,NUMBER2:/[0-9_\.\,]+/,STRING2:/"[^"]*"|'[^']*'/}})(hP||={});var gP;(e=>{e.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,CLASS_ANNOTATION:/[ \t]+:::[ \t]*[A-Za-z_][\w-]*/,ICON_ANNOTATION:/[ \t]+icon\([\w-]*(?::[\w-]+)?\)/,DESC_ANNOTATION:/[ \t]+##[^\n\r]*/,INDENTATION:/[ \t]{1,}/,QUOTED_NAME:/"[^"]*"|'[^']*'/,WS:/[ \t]+/,ML_COMMENT:/\%\%[^\n]*/,NL:/\r?\n/,BARE_NAME:/(?!:::|icon\(|##)[^ \t\n\r"'](?:(?![ \t]+:::[ \t]*[A-Za-z_]|[ \t]+icon\(|[ \t]+##)[^\n\r])*/}})(gP||={});var _P;(e=>{e.Terminals={WARDLEY_NUMBER:/[0-9]+\.[0-9]+/,ARROW:/->/,LINK_PORT:/\+<>|\+>|\+|-\.->|>|\+'[^']*'<>|\+'[^']*'<|\+'[^']*'>/,LINK_LABEL:/;[^\n\r]+/,STRATEGY:/build|buy|outsource|market/,KW_WARDLEY:/wardley-beta/,KW_SIZE:/size/,KW_EVOLUTION:/evolution/,KW_ANCHOR:/anchor/,KW_COMPONENT:/component/,KW_LABEL:/label/,KW_INERTIA:/inertia/,KW_EVOLVE:/evolve/,KW_PIPELINE:/pipeline/,KW_NOTE:/note/,KW_ANNOTATIONS:/annotations/,KW_ANNOTATION:/annotation/,KW_ACCELERATOR:/accelerator/,KW_DEACCELERATOR:/deaccelerator/,NAME_WITH_SPACES:/(?!title\s|accTitle|accDescr)[A-Za-z](?:[A-Za-z0-9_()&]|-(?!>))*(?:[ \t]+[A-Za-z(](?:[A-Za-z0-9_()&]|-(?!>))*)*/,WS:/[ \t]+/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INT:/0|[1-9][0-9]*(?!\.)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,ID:/[\w]([-\w]*\w)?/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(_P||={}),{...rP.Terminals,...iP.Terminals,...aP.Terminals,...oP.Terminals,...sP.Terminals,...cP.Terminals,...lP.Terminals,...uP.Terminals,...dP.Terminals,...fP.Terminals,...pP.Terminals,...mP.Terminals,...gP.Terminals,...hP.Terminals,..._P.Terminals};var vP={$type:`AbnfAlternation`,alternatives:`alternatives`},yP={$type:`AbnfConcatenation`,elements:`elements`},bP={$type:`AbnfElement`,primary:`primary`,repeat:`repeat`},xP={$type:`AbnfGroup`,element:`element`},SP={$type:`AbnfNumVal`,value:`value`},CP={$type:`AbnfOptionalGroup`,element:`element`},wP={$type:`AbnfPrimary`},TP={$type:`AbnfRule`,definition:`definition`,name:`name`},EP={$type:`AbnfRuleName`,name:`name`},DP={$type:`AbnfStringLiteral`,value:`value`},OP={$type:`Accelerator`,name:`name`,x:`x`,y:`y`},kP={$type:`Alignment`,direction:`direction`,members:`members`},AP={$type:`Anchor`,evolution:`evolution`,name:`name`,visibility:`visibility`},jP={$type:`Annotation`,number:`number`,text:`text`,x:`x`,y:`y`},MP={$type:`Annotations`,x:`x`,y:`y`},NP={$type:`Architecture`,accDescr:`accDescr`,accTitle:`accTitle`,alignments:`alignments`,edges:`edges`,groups:`groups`,junctions:`junctions`,services:`services`,title:`title`};function PP(e){return $.isInstance(e,NP.$type)}o(PP,`isArchitecture`);var FP={$type:`Axis`,label:`label`,name:`name`},IP={$type:`Branch`,name:`name`,order:`order`};function LP(e){return $.isInstance(e,IP.$type)}o(LP,`isBranch`);var RP={$type:`Checkout`,branch:`branch`},zP={$type:`CherryPicking`,id:`id`,parent:`parent`,tags:`tags`},BP={$type:`ClassDefStatement`,className:`className`,styleText:`styleText`},VP={$type:`Commit`,id:`id`,message:`message`,tags:`tags`,type:`type`};function HP(e){return $.isInstance(e,VP.$type)}o(HP,`isCommit`);var UP={$type:`Common`,accDescr:`accDescr`,accTitle:`accTitle`,title:`title`},WP={$type:`Component`,decorator:`decorator`,evolution:`evolution`,inertia:`inertia`,label:`label`,name:`name`,visibility:`visibility`},GP={$type:`Curve`,entries:`entries`,label:`label`,name:`name`},KP={$type:`Cynefin`,accDescr:`accDescr`,accTitle:`accTitle`,domains:`domains`,title:`title`,transitions:`transitions`};function qP(e){return $.isInstance(e,KP.$type)}o(qP,`isCynefin`);var JP={$type:`Deaccelerator`,name:`name`,x:`x`,y:`y`},YP={$type:`Decorator`,strategy:`strategy`},XP={$type:`Direction`,accDescr:`accDescr`,accTitle:`accTitle`,dir:`dir`,statements:`statements`,title:`title`},ZP={$type:`DomainBlock`,domain:`domain`,items:`items`};function QP(e){return $.isInstance(e,ZP.$type)}o(QP,`isDomainBlock`);var $P={$type:`DomainItem`,label:`label`};function eF(e){return $.isInstance(e,$P.$type)}o(eF,`isDomainItem`);var tF={$type:`EbnfChoice`,alternatives:`alternatives`},nF={$type:`EbnfExceptionPostfix`,except:`except`},rF={$type:`EbnfGroup`,element:`element`},iF={$type:`EbnfNonTerminal`,name:`name`},aF={$type:`EbnfOneOrMorePostfix`,operator:`operator`},oF={$type:`EbnfOptional`,element:`element`},sF={$type:`EbnfOptionalPostfix`,operator:`operator`},cF={$type:`EbnfPostfix`},lF={$type:`EbnfPrimary`},uF={$type:`EbnfRepetition`,element:`element`},dF={$type:`EbnfRule`,definition:`definition`,name:`name`},fF={$type:`EbnfSequence`,elements:`elements`},pF={$type:`EbnfSpecial`,text:`text`},mF={$type:`EbnfTerm`,base:`base`,postfixes:`postfixes`},hF={$type:`EbnfTerminal`,value:`value`},gF={$type:`EbnfZeroOrMorePostfix`,operator:`operator`},_F={$type:`Edge`,lhsDir:`lhsDir`,lhsGroup:`lhsGroup`,lhsId:`lhsId`,lhsInto:`lhsInto`,rhsDir:`rhsDir`,rhsGroup:`rhsGroup`,rhsId:`rhsId`,rhsInto:`rhsInto`,title:`title`},vF={$type:`EmDataEntity`,dataBlockValue:`dataBlockValue`,dataType:`dataType`,name:`name`},yF={$type:`EmFrame`},bF={$type:`EmGwt`,givenStatements:`givenStatements`,sourceFrame:`sourceFrame`,thenStatements:`thenStatements`,whenStatements:`whenStatements`},xF={$type:`EmGwtStatement`,entityIdentifier:`entityIdentifier`},SF={$type:`EmModelEntity`,name:`name`};function CF(e){return e===`rmo`||e===`readmodel`||e===`ui`||e===`cmd`||e===`command`||e===`evt`||e===`event`||e===`pcr`||e===`processor`}o(CF,`isEmModelEntityType`);var wF={$type:`EmNoteEntity`,dataBlockValue:`dataBlockValue`,dataType:`dataType`,sourceFrame:`sourceFrame`},TF={$type:`EmResetFrame`,dataInlineValue:`dataInlineValue`,dataReference:`dataReference`,dataType:`dataType`,entityIdentifier:`entityIdentifier`,modelEntityType:`modelEntityType`,name:`name`,sourceFrames:`sourceFrames`};function EF(e){return $.isInstance(e,TF.$type)}o(EF,`isEmResetFrame`);var DF={$type:`EmTimeFrame`,dataInlineValue:`dataInlineValue`,dataReference:`dataReference`,dataType:`dataType`,entityIdentifier:`entityIdentifier`,modelEntityType:`modelEntityType`,name:`name`,sourceFrames:`sourceFrames`},OF={$type:`Entry`,axis:`axis`,value:`value`},kF={$type:`EventModel`,accDescr:`accDescr`,accTitle:`accTitle`,dataEntities:`dataEntities`,frames:`frames`,gwtEntities:`gwtEntities`,modelEntities:`modelEntities`,noteEntities:`noteEntities`,title:`title`},AF={$type:`Evolution`,stages:`stages`},jF={$type:`EvolutionStage`,boundary:`boundary`,name:`name`,secondName:`secondName`},MF={$type:`Evolve`,component:`component`,target:`target`},NF={$type:`GitGraph`,accDescr:`accDescr`,accTitle:`accTitle`,statements:`statements`,title:`title`};function PF(e){return $.isInstance(e,NF.$type)}o(PF,`isGitGraph`);var FF={$type:`Group`,icon:`icon`,id:`id`,in:`in`,title:`title`},IF={$type:`Info`,accDescr:`accDescr`,accTitle:`accTitle`,title:`title`};function LF(e){return $.isInstance(e,IF.$type)}o(LF,`isInfo`);var RF={$type:`Item`,classSelector:`classSelector`,name:`name`},zF={$type:`Junction`,id:`id`,in:`in`},BF={$type:`Label`,negX:`negX`,negY:`negY`,offsetX:`offsetX`,offsetY:`offsetY`},VF={$type:`Leaf`,classSelector:`classSelector`,name:`name`,value:`value`},HF={$type:`Link`,arrow:`arrow`,from:`from`,fromPort:`fromPort`,linkLabel:`linkLabel`,to:`to`,toPort:`toPort`},UF={$type:`Merge`,branch:`branch`,id:`id`,tags:`tags`,type:`type`};function WF(e){return $.isInstance(e,UF.$type)}o(WF,`isMerge`);var GF={$type:`Note`,evolution:`evolution`,text:`text`,visibility:`visibility`},KF={$type:`Option`,name:`name`,value:`value`},qF={$type:`Packet`,accDescr:`accDescr`,accTitle:`accTitle`,blocks:`blocks`,title:`title`};function JF(e){return $.isInstance(e,qF.$type)}o(JF,`isPacket`);var YF={$type:`PacketBlock`,bits:`bits`,end:`end`,label:`label`,start:`start`};function XF(e){return $.isInstance(e,YF.$type)}o(XF,`isPacketBlock`);var ZF={$type:`PegAny`,dot:`dot`},QF={$type:`PegGroup`,element:`element`},$F={$type:`PegIdentifier`,name:`name`},eI={$type:`PegLiteral`,value:`value`},tI={$type:`PegOrderedChoice`,alternatives:`alternatives`},nI={$type:`PegPrefix`,operator:`operator`,suffix:`suffix`},rI={$type:`PegPrimary`},iI={$type:`PegRule`,definition:`definition`,name:`name`},aI={$type:`PegSequence`,elements:`elements`},oI={$type:`PegSuffix`,operator:`operator`,primary:`primary`},sI={$type:`Pie`,accDescr:`accDescr`,accTitle:`accTitle`,sections:`sections`,showData:`showData`,title:`title`};function cI(e){return $.isInstance(e,sI.$type)}o(cI,`isPie`);var lI={$type:`PieSection`,label:`label`,value:`value`};function uI(e){return $.isInstance(e,lI.$type)}o(uI,`isPieSection`);var dI={$type:`Pipeline`,components:`components`,parent:`parent`},fI={$type:`PipelineComponent`,evolution:`evolution`,label:`label`,name:`name`},pI={$type:`Radar`,accDescr:`accDescr`,accTitle:`accTitle`,axes:`axes`,curves:`curves`,options:`options`,title:`title`},mI={$type:`Railroad`,accDescr:`accDescr`,accTitle:`accTitle`,rules:`rules`,title:`title`};function hI(e){return $.isInstance(e,mI.$type)}o(hI,`isRailroad`);var gI={$type:`RailroadAbnf`,accDescr:`accDescr`,accTitle:`accTitle`,rules:`rules`,title:`title`};function _I(e){return $.isInstance(e,gI.$type)}o(_I,`isRailroadAbnf`);var vI={$type:`RailroadChoiceExpr`,alternatives:`alternatives`},yI={$type:`RailroadEbnf`,accDescr:`accDescr`,accTitle:`accTitle`,rules:`rules`,title:`title`};function bI(e){return $.isInstance(e,yI.$type)}o(bI,`isRailroadEbnf`);var xI={$type:`RailroadExpression`},SI={$type:`RailroadNonTerminalExpr`,name:`name`},CI={$type:`RailroadOneOrMoreExpr`,element:`element`},wI={$type:`RailroadOptionalExpr`,element:`element`},TI={$type:`RailroadPeg`,accDescr:`accDescr`,accTitle:`accTitle`,rules:`rules`,title:`title`};function EI(e){return $.isInstance(e,TI.$type)}o(EI,`isRailroadPeg`);var DI={$type:`RailroadRule`,definition:`definition`,name:`name`},OI={$type:`RailroadSequenceExpr`,elements:`elements`},kI={$type:`RailroadSpecialExpr`,text:`text`},AI={$type:`RailroadTerminalExpr`,value:`value`},jI={$type:`RailroadZeroOrMoreExpr`,element:`element`},MI={$type:`Section`,classSelector:`classSelector`,name:`name`},NI={$type:`Service`,icon:`icon`,iconText:`iconText`,id:`id`,in:`in`,title:`title`},PI={$type:`Size`,height:`height`,width:`width`},FI={$type:`Statement`},II={$type:`Transition`,from:`from`,label:`label`,to:`to`};function LI(e){return $.isInstance(e,II.$type)}o(LI,`isTransition`);var RI={$type:`Treemap`,accDescr:`accDescr`,accTitle:`accTitle`,title:`title`,TreemapRows:`TreemapRows`};function zI(e){return $.isInstance(e,RI.$type)}o(zI,`isTreemap`);var BI={$type:`TreemapRow`,indent:`indent`,item:`item`},VI={$type:`TreeNode`,classAnnotation:`classAnnotation`,descAnnotation:`descAnnotation`,iconAnnotation:`iconAnnotation`,indent:`indent`,name:`name`},HI={$type:`TreeView`,accDescr:`accDescr`,accTitle:`accTitle`,nodes:`nodes`,title:`title`},UI={$type:`Wardley`,accDescr:`accDescr`,accelerators:`accelerators`,accTitle:`accTitle`,anchors:`anchors`,annotation:`annotation`,annotations:`annotations`,components:`components`,deaccelerators:`deaccelerators`,evolution:`evolution`,evolves:`evolves`,links:`links`,notes:`notes`,pipelines:`pipelines`,size:`size`,title:`title`};function WI(e){return $.isInstance(e,UI.$type)}o(WI,`isWardley`);var GI=class extends fn{constructor(){super(...arguments),this.types={AbnfAlternation:{name:vP.$type,properties:{alternatives:{name:vP.alternatives,defaultValue:[]}},superTypes:[]},AbnfConcatenation:{name:yP.$type,properties:{elements:{name:yP.elements,defaultValue:[]}},superTypes:[]},AbnfElement:{name:bP.$type,properties:{primary:{name:bP.primary},repeat:{name:bP.repeat}},superTypes:[]},AbnfGroup:{name:xP.$type,properties:{element:{name:xP.element}},superTypes:[wP.$type]},AbnfNumVal:{name:SP.$type,properties:{value:{name:SP.value}},superTypes:[wP.$type]},AbnfOptionalGroup:{name:CP.$type,properties:{element:{name:CP.element}},superTypes:[wP.$type]},AbnfPrimary:{name:wP.$type,properties:{},superTypes:[]},AbnfRule:{name:TP.$type,properties:{definition:{name:TP.definition},name:{name:TP.name}},superTypes:[]},AbnfRuleName:{name:EP.$type,properties:{name:{name:EP.name}},superTypes:[wP.$type]},AbnfStringLiteral:{name:DP.$type,properties:{value:{name:DP.value}},superTypes:[wP.$type]},Accelerator:{name:OP.$type,properties:{name:{name:OP.name},x:{name:OP.x},y:{name:OP.y}},superTypes:[]},Alignment:{name:kP.$type,properties:{direction:{name:kP.direction},members:{name:kP.members,defaultValue:[]}},superTypes:[]},Anchor:{name:AP.$type,properties:{evolution:{name:AP.evolution},name:{name:AP.name},visibility:{name:AP.visibility}},superTypes:[]},Annotation:{name:jP.$type,properties:{number:{name:jP.number},text:{name:jP.text},x:{name:jP.x},y:{name:jP.y}},superTypes:[]},Annotations:{name:MP.$type,properties:{x:{name:MP.x},y:{name:MP.y}},superTypes:[]},Architecture:{name:NP.$type,properties:{accDescr:{name:NP.accDescr},accTitle:{name:NP.accTitle},alignments:{name:NP.alignments,defaultValue:[]},edges:{name:NP.edges,defaultValue:[]},groups:{name:NP.groups,defaultValue:[]},junctions:{name:NP.junctions,defaultValue:[]},services:{name:NP.services,defaultValue:[]},title:{name:NP.title}},superTypes:[]},Axis:{name:FP.$type,properties:{label:{name:FP.label},name:{name:FP.name}},superTypes:[]},Branch:{name:IP.$type,properties:{name:{name:IP.name},order:{name:IP.order}},superTypes:[FI.$type]},Checkout:{name:RP.$type,properties:{branch:{name:RP.branch}},superTypes:[FI.$type]},CherryPicking:{name:zP.$type,properties:{id:{name:zP.id},parent:{name:zP.parent},tags:{name:zP.tags,defaultValue:[]}},superTypes:[FI.$type]},ClassDefStatement:{name:BP.$type,properties:{className:{name:BP.className},styleText:{name:BP.styleText}},superTypes:[]},Commit:{name:VP.$type,properties:{id:{name:VP.id},message:{name:VP.message},tags:{name:VP.tags,defaultValue:[]},type:{name:VP.type}},superTypes:[FI.$type]},Common:{name:UP.$type,properties:{accDescr:{name:UP.accDescr},accTitle:{name:UP.accTitle},title:{name:UP.title}},superTypes:[]},Component:{name:WP.$type,properties:{decorator:{name:WP.decorator},evolution:{name:WP.evolution},inertia:{name:WP.inertia,defaultValue:!1},label:{name:WP.label},name:{name:WP.name},visibility:{name:WP.visibility}},superTypes:[]},Curve:{name:GP.$type,properties:{entries:{name:GP.entries,defaultValue:[]},label:{name:GP.label},name:{name:GP.name}},superTypes:[]},Cynefin:{name:KP.$type,properties:{accDescr:{name:KP.accDescr},accTitle:{name:KP.accTitle},domains:{name:KP.domains,defaultValue:[]},title:{name:KP.title},transitions:{name:KP.transitions,defaultValue:[]}},superTypes:[]},Deaccelerator:{name:JP.$type,properties:{name:{name:JP.name},x:{name:JP.x},y:{name:JP.y}},superTypes:[]},Decorator:{name:YP.$type,properties:{strategy:{name:YP.strategy}},superTypes:[]},Direction:{name:XP.$type,properties:{accDescr:{name:XP.accDescr},accTitle:{name:XP.accTitle},dir:{name:XP.dir},statements:{name:XP.statements,defaultValue:[]},title:{name:XP.title}},superTypes:[NF.$type]},DomainBlock:{name:ZP.$type,properties:{domain:{name:ZP.domain},items:{name:ZP.items,defaultValue:[]}},superTypes:[]},DomainItem:{name:$P.$type,properties:{label:{name:$P.label}},superTypes:[]},EbnfChoice:{name:tF.$type,properties:{alternatives:{name:tF.alternatives,defaultValue:[]}},superTypes:[]},EbnfExceptionPostfix:{name:nF.$type,properties:{except:{name:nF.except}},superTypes:[cF.$type]},EbnfGroup:{name:rF.$type,properties:{element:{name:rF.element}},superTypes:[lF.$type]},EbnfNonTerminal:{name:iF.$type,properties:{name:{name:iF.name}},superTypes:[lF.$type]},EbnfOneOrMorePostfix:{name:aF.$type,properties:{operator:{name:aF.operator}},superTypes:[cF.$type]},EbnfOptional:{name:oF.$type,properties:{element:{name:oF.element}},superTypes:[lF.$type]},EbnfOptionalPostfix:{name:sF.$type,properties:{operator:{name:sF.operator}},superTypes:[cF.$type]},EbnfPostfix:{name:cF.$type,properties:{},superTypes:[]},EbnfPrimary:{name:lF.$type,properties:{},superTypes:[]},EbnfRepetition:{name:uF.$type,properties:{element:{name:uF.element}},superTypes:[lF.$type]},EbnfRule:{name:dF.$type,properties:{definition:{name:dF.definition},name:{name:dF.name}},superTypes:[]},EbnfSequence:{name:fF.$type,properties:{elements:{name:fF.elements,defaultValue:[]}},superTypes:[]},EbnfSpecial:{name:pF.$type,properties:{text:{name:pF.text}},superTypes:[lF.$type]},EbnfTerm:{name:mF.$type,properties:{base:{name:mF.base},postfixes:{name:mF.postfixes,defaultValue:[]}},superTypes:[]},EbnfTerminal:{name:hF.$type,properties:{value:{name:hF.value}},superTypes:[lF.$type]},EbnfZeroOrMorePostfix:{name:gF.$type,properties:{operator:{name:gF.operator}},superTypes:[cF.$type]},Edge:{name:_F.$type,properties:{lhsDir:{name:_F.lhsDir},lhsGroup:{name:_F.lhsGroup,defaultValue:!1},lhsId:{name:_F.lhsId},lhsInto:{name:_F.lhsInto,defaultValue:!1},rhsDir:{name:_F.rhsDir},rhsGroup:{name:_F.rhsGroup,defaultValue:!1},rhsId:{name:_F.rhsId},rhsInto:{name:_F.rhsInto,defaultValue:!1},title:{name:_F.title}},superTypes:[]},EmDataEntity:{name:vF.$type,properties:{dataBlockValue:{name:vF.dataBlockValue},dataType:{name:vF.dataType},name:{name:vF.name}},superTypes:[]},EmFrame:{name:yF.$type,properties:{},superTypes:[]},EmGwt:{name:bF.$type,properties:{givenStatements:{name:bF.givenStatements,defaultValue:[]},sourceFrame:{name:bF.sourceFrame,referenceType:yF.$type},thenStatements:{name:bF.thenStatements,defaultValue:[]},whenStatements:{name:bF.whenStatements,defaultValue:[]}},superTypes:[]},EmGwtStatement:{name:xF.$type,properties:{entityIdentifier:{name:xF.entityIdentifier,referenceType:SF.$type}},superTypes:[]},EmModelEntity:{name:SF.$type,properties:{name:{name:SF.name}},superTypes:[]},EmNoteEntity:{name:wF.$type,properties:{dataBlockValue:{name:wF.dataBlockValue},dataType:{name:wF.dataType},sourceFrame:{name:wF.sourceFrame,referenceType:yF.$type}},superTypes:[]},EmResetFrame:{name:TF.$type,properties:{dataInlineValue:{name:TF.dataInlineValue},dataReference:{name:TF.dataReference,referenceType:vF.$type},dataType:{name:TF.dataType},entityIdentifier:{name:TF.entityIdentifier},modelEntityType:{name:TF.modelEntityType},name:{name:TF.name},sourceFrames:{name:TF.sourceFrames,defaultValue:[],referenceType:yF.$type}},superTypes:[yF.$type]},EmTimeFrame:{name:DF.$type,properties:{dataInlineValue:{name:DF.dataInlineValue},dataReference:{name:DF.dataReference,referenceType:vF.$type},dataType:{name:DF.dataType},entityIdentifier:{name:DF.entityIdentifier},modelEntityType:{name:DF.modelEntityType},name:{name:DF.name},sourceFrames:{name:DF.sourceFrames,defaultValue:[],referenceType:yF.$type}},superTypes:[yF.$type]},Entry:{name:OF.$type,properties:{axis:{name:OF.axis,referenceType:FP.$type},value:{name:OF.value}},superTypes:[]},EventModel:{name:kF.$type,properties:{accDescr:{name:kF.accDescr},accTitle:{name:kF.accTitle},dataEntities:{name:kF.dataEntities,defaultValue:[]},frames:{name:kF.frames,defaultValue:[]},gwtEntities:{name:kF.gwtEntities,defaultValue:[]},modelEntities:{name:kF.modelEntities,defaultValue:[]},noteEntities:{name:kF.noteEntities,defaultValue:[]},title:{name:kF.title}},superTypes:[]},Evolution:{name:AF.$type,properties:{stages:{name:AF.stages,defaultValue:[]}},superTypes:[]},EvolutionStage:{name:jF.$type,properties:{boundary:{name:jF.boundary},name:{name:jF.name},secondName:{name:jF.secondName}},superTypes:[]},Evolve:{name:MF.$type,properties:{component:{name:MF.component},target:{name:MF.target}},superTypes:[]},GitGraph:{name:NF.$type,properties:{accDescr:{name:NF.accDescr},accTitle:{name:NF.accTitle},statements:{name:NF.statements,defaultValue:[]},title:{name:NF.title}},superTypes:[]},Group:{name:FF.$type,properties:{icon:{name:FF.icon},id:{name:FF.id},in:{name:FF.in},title:{name:FF.title}},superTypes:[]},Info:{name:IF.$type,properties:{accDescr:{name:IF.accDescr},accTitle:{name:IF.accTitle},title:{name:IF.title}},superTypes:[]},Item:{name:RF.$type,properties:{classSelector:{name:RF.classSelector},name:{name:RF.name}},superTypes:[]},Junction:{name:zF.$type,properties:{id:{name:zF.id},in:{name:zF.in}},superTypes:[]},Label:{name:BF.$type,properties:{negX:{name:BF.negX,defaultValue:!1},negY:{name:BF.negY,defaultValue:!1},offsetX:{name:BF.offsetX},offsetY:{name:BF.offsetY}},superTypes:[]},Leaf:{name:VF.$type,properties:{classSelector:{name:VF.classSelector},name:{name:VF.name},value:{name:VF.value}},superTypes:[RF.$type]},Link:{name:HF.$type,properties:{arrow:{name:HF.arrow},from:{name:HF.from},fromPort:{name:HF.fromPort},linkLabel:{name:HF.linkLabel},to:{name:HF.to},toPort:{name:HF.toPort}},superTypes:[]},Merge:{name:UF.$type,properties:{branch:{name:UF.branch},id:{name:UF.id},tags:{name:UF.tags,defaultValue:[]},type:{name:UF.type}},superTypes:[FI.$type]},Note:{name:GF.$type,properties:{evolution:{name:GF.evolution},text:{name:GF.text},visibility:{name:GF.visibility}},superTypes:[]},Option:{name:KF.$type,properties:{name:{name:KF.name},value:{name:KF.value,defaultValue:!1}},superTypes:[]},Packet:{name:qF.$type,properties:{accDescr:{name:qF.accDescr},accTitle:{name:qF.accTitle},blocks:{name:qF.blocks,defaultValue:[]},title:{name:qF.title}},superTypes:[]},PacketBlock:{name:YF.$type,properties:{bits:{name:YF.bits},end:{name:YF.end},label:{name:YF.label},start:{name:YF.start}},superTypes:[]},PegAny:{name:ZF.$type,properties:{dot:{name:ZF.dot}},superTypes:[rI.$type]},PegGroup:{name:QF.$type,properties:{element:{name:QF.element}},superTypes:[rI.$type]},PegIdentifier:{name:$F.$type,properties:{name:{name:$F.name}},superTypes:[rI.$type]},PegLiteral:{name:eI.$type,properties:{value:{name:eI.value}},superTypes:[rI.$type]},PegOrderedChoice:{name:tI.$type,properties:{alternatives:{name:tI.alternatives,defaultValue:[]}},superTypes:[]},PegPrefix:{name:nI.$type,properties:{operator:{name:nI.operator},suffix:{name:nI.suffix}},superTypes:[]},PegPrimary:{name:rI.$type,properties:{},superTypes:[]},PegRule:{name:iI.$type,properties:{definition:{name:iI.definition},name:{name:iI.name}},superTypes:[]},PegSequence:{name:aI.$type,properties:{elements:{name:aI.elements,defaultValue:[]}},superTypes:[]},PegSuffix:{name:oI.$type,properties:{operator:{name:oI.operator},primary:{name:oI.primary}},superTypes:[]},Pie:{name:sI.$type,properties:{accDescr:{name:sI.accDescr},accTitle:{name:sI.accTitle},sections:{name:sI.sections,defaultValue:[]},showData:{name:sI.showData,defaultValue:!1},title:{name:sI.title}},superTypes:[]},PieSection:{name:lI.$type,properties:{label:{name:lI.label},value:{name:lI.value}},superTypes:[]},Pipeline:{name:dI.$type,properties:{components:{name:dI.components,defaultValue:[]},parent:{name:dI.parent}},superTypes:[]},PipelineComponent:{name:fI.$type,properties:{evolution:{name:fI.evolution},label:{name:fI.label},name:{name:fI.name}},superTypes:[]},Radar:{name:pI.$type,properties:{accDescr:{name:pI.accDescr},accTitle:{name:pI.accTitle},axes:{name:pI.axes,defaultValue:[]},curves:{name:pI.curves,defaultValue:[]},options:{name:pI.options,defaultValue:[]},title:{name:pI.title}},superTypes:[]},Railroad:{name:mI.$type,properties:{accDescr:{name:mI.accDescr},accTitle:{name:mI.accTitle},rules:{name:mI.rules,defaultValue:[]},title:{name:mI.title}},superTypes:[]},RailroadAbnf:{name:gI.$type,properties:{accDescr:{name:gI.accDescr},accTitle:{name:gI.accTitle},rules:{name:gI.rules,defaultValue:[]},title:{name:gI.title}},superTypes:[]},RailroadChoiceExpr:{name:vI.$type,properties:{alternatives:{name:vI.alternatives,defaultValue:[]}},superTypes:[xI.$type]},RailroadEbnf:{name:yI.$type,properties:{accDescr:{name:yI.accDescr},accTitle:{name:yI.accTitle},rules:{name:yI.rules,defaultValue:[]},title:{name:yI.title}},superTypes:[]},RailroadExpression:{name:xI.$type,properties:{},superTypes:[]},RailroadNonTerminalExpr:{name:SI.$type,properties:{name:{name:SI.name}},superTypes:[xI.$type]},RailroadOneOrMoreExpr:{name:CI.$type,properties:{element:{name:CI.element}},superTypes:[xI.$type]},RailroadOptionalExpr:{name:wI.$type,properties:{element:{name:wI.element}},superTypes:[xI.$type]},RailroadPeg:{name:TI.$type,properties:{accDescr:{name:TI.accDescr},accTitle:{name:TI.accTitle},rules:{name:TI.rules,defaultValue:[]},title:{name:TI.title}},superTypes:[]},RailroadRule:{name:DI.$type,properties:{definition:{name:DI.definition},name:{name:DI.name}},superTypes:[]},RailroadSequenceExpr:{name:OI.$type,properties:{elements:{name:OI.elements,defaultValue:[]}},superTypes:[xI.$type]},RailroadSpecialExpr:{name:kI.$type,properties:{text:{name:kI.text}},superTypes:[xI.$type]},RailroadTerminalExpr:{name:AI.$type,properties:{value:{name:AI.value}},superTypes:[xI.$type]},RailroadZeroOrMoreExpr:{name:jI.$type,properties:{element:{name:jI.element}},superTypes:[xI.$type]},Section:{name:MI.$type,properties:{classSelector:{name:MI.classSelector},name:{name:MI.name}},superTypes:[RF.$type]},Service:{name:NI.$type,properties:{icon:{name:NI.icon},iconText:{name:NI.iconText},id:{name:NI.id},in:{name:NI.in},title:{name:NI.title}},superTypes:[]},Size:{name:PI.$type,properties:{height:{name:PI.height},width:{name:PI.width}},superTypes:[]},Statement:{name:FI.$type,properties:{},superTypes:[]},Transition:{name:II.$type,properties:{from:{name:II.from},label:{name:II.label},to:{name:II.to}},superTypes:[]},TreeNode:{name:VI.$type,properties:{classAnnotation:{name:VI.classAnnotation},descAnnotation:{name:VI.descAnnotation},iconAnnotation:{name:VI.iconAnnotation},indent:{name:VI.indent},name:{name:VI.name}},superTypes:[]},TreeView:{name:HI.$type,properties:{accDescr:{name:HI.accDescr},accTitle:{name:HI.accTitle},nodes:{name:HI.nodes,defaultValue:[]},title:{name:HI.title}},superTypes:[]},Treemap:{name:RI.$type,properties:{accDescr:{name:RI.accDescr},accTitle:{name:RI.accTitle},title:{name:RI.title},TreemapRows:{name:RI.TreemapRows,defaultValue:[]}},superTypes:[]},TreemapRow:{name:BI.$type,properties:{indent:{name:BI.indent},item:{name:BI.item}},superTypes:[]},Wardley:{name:UI.$type,properties:{accDescr:{name:UI.accDescr},accelerators:{name:UI.accelerators,defaultValue:[]},accTitle:{name:UI.accTitle},anchors:{name:UI.anchors,defaultValue:[]},annotation:{name:UI.annotation,defaultValue:[]},annotations:{name:UI.annotations,defaultValue:[]},components:{name:UI.components,defaultValue:[]},deaccelerators:{name:UI.deaccelerators,defaultValue:[]},evolution:{name:UI.evolution},evolves:{name:UI.evolves,defaultValue:[]},links:{name:UI.links,defaultValue:[]},notes:{name:UI.notes,defaultValue:[]},pipelines:{name:UI.pipelines,defaultValue:[]},size:{name:UI.size},title:{name:UI.title}},superTypes:[]}}}static{o(this,`MermaidAstReflection`)}},$=new GI,KI,qI=o(()=>KI??=eP(`{"$type":"Grammar","isDeclared":true,"name":"ArchitectureGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Architecture","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"architecture-beta"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"groups","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"services","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"junctions","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Assignment","feature":"edges","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"alignments","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"LeftPort","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"lhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"RightPort","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"rhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}},{"$type":"Keyword","value":":"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Arrow","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Assignment","feature":"lhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"--"},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]}},{"$type":"Keyword","value":"-"}]}]},{"$type":"Assignment","feature":"rhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Group","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"group"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Service","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"service"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"iconText","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]}}],"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Junction","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"junction"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Edge","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"lhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Assignment","feature":"lhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Assignment","feature":"rhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Assignment","feature":"rhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Alignment","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"align"},{"$type":"Assignment","feature":"direction","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"row"},{"$type":"Keyword","value":"column"}]}},{"$type":"Assignment","feature":"members","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Assignment","feature":"members","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"+"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"ARROW_DIRECTION","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"L"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"R"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"T"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"B"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_GROUP","definition":{"$type":"RegexToken","regex":"/\\\\{group\\\\}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_INTO","definition":{"$type":"RegexToken","regex":"/<|>/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@19"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@20"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"ARCH_ICON","definition":{"$type":"RegexToken","regex":"/\\\\([\\\\w-:]+\\\\)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARCH_TITLE","definition":{"$type":"RegexToken","regex":"/\\\\[(?:\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'|[\\\\w ]+)\\\\]/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[],"types":[]}`),`ArchitectureGrammarGrammar`),JI,YI=o(()=>JI??=eP(`{"$type":"Grammar","isDeclared":true,"name":"CynefinGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Cynefin","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"cynefin-beta"},{"$type":"Keyword","value":"cynefin-beta:"}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Assignment","feature":"domains","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"transitions","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DomainBlock","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"domain","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Assignment","feature":"items","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DomainItem","definition":{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Transition","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Keyword","value":"-->"},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"DOMAIN_NAME","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"complex"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"complicated"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"clear"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"chaotic"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"confusion"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@11"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@12"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`),`CynefinGrammarGrammar`),XI,ZI=o(()=>XI??=eP('{"$type":"Grammar","isDeclared":true,"name":"EventModeling","interfaces":[{"$type":"Interface","name":"Common","attributes":[{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"rules":[{"$type":"ParserRule","entry":true,"name":"EventModel","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"eventmodeling"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"modelEntities","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"frames","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"dataEntities","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}},{"$type":"Assignment","feature":"noteEntities","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"gwtEntities","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmModelEntityType","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"rmo"},{"$type":"Keyword","value":"readmodel"},{"$type":"Keyword","value":"ui"},{"$type":"Keyword","value":"cmd"},{"$type":"Keyword","value":"command"},{"$type":"Keyword","value":"evt"},{"$type":"Keyword","value":"event"},{"$type":"Keyword","value":"pcr"},{"$type":"Keyword","value":"processor"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmDataType","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"json"},{"$type":"Keyword","value":"jsobj"},{"$type":"Keyword","value":"figma"},{"$type":"Keyword","value":"salt"},{"$type":"Keyword","value":"uri"},{"$type":"Keyword","value":"md"},{"$type":"Keyword","value":"html"},{"$type":"Keyword","value":"text"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"EmDataInline","definition":{"$type":"Group","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"`"},{"$type":"Assignment","feature":"dataType","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Keyword","value":"`"}],"cardinality":"?"},{"$type":"Assignment","feature":"dataInlineValue","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"EmDataBlock","definition":{"$type":"Group","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"`"},{"$type":"Assignment","feature":"dataType","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Keyword","value":"`"}],"cardinality":"?"},{"$type":"Assignment","feature":"dataBlockValue","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"QualifiedName","dataType":"string","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Keyword","value":"."},{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmTimeFrame","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"tf"},{"$type":"Keyword","value":"timeframe"}]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"modelEntityType","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"entityIdentifier","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"->>"},{"$type":"Assignment","feature":"sourceFrames","operator":"+=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@8"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Keyword","value":"[["},{"$type":"Assignment","feature":"dataReference","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@10"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":"]]"}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmResetFrame","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"rf"},{"$type":"Keyword","value":"resetframe"}]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"modelEntityType","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"entityIdentifier","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"->>"},{"$type":"Assignment","feature":"sourceFrames","operator":"+=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@8"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Keyword","value":"[["},{"$type":"Assignment","feature":"dataReference","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@10"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":"]]"}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmFrame","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmModelEntity","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"entity"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmDataEntity","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"data"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmNoteEntity","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"note"},{"$type":"Assignment","feature":"sourceFrame","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@8"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmGwt","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"gwt"},{"$type":"Assignment","feature":"sourceFrame","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@8"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":"given"},{"$type":"Assignment","feature":"givenStatements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},"cardinality":"+"},{"$type":"Group","elements":[{"$type":"Keyword","value":"when"},{"$type":"Assignment","feature":"whenStatements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},"cardinality":"+"}],"cardinality":"?"},{"$type":"Keyword","value":"then"},{"$type":"Assignment","feature":"thenStatements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},"cardinality":"+"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmGwtStatement","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]},{"$type":"Assignment","feature":"entityIdentifier","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@9"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EM_EID","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EM_FI","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"EM_ID","definition":{"$type":"RegexToken","regex":"/[_a-zA-Z][\\\\w_]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_FID","definition":{"$type":"RegexToken","regex":"/\\\\d{1,3}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_DATA_INLINE","definition":{"$type":"RegexToken","regex":"/\\\\{(.*)\\\\}|\\"(.*)\\"|\'(.*)\'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_DATA_BLOCK","definition":{"$type":"RegexToken","regex":"/\\\\{[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?\\\\}(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"EM_WS","definition":{"$type":"RegexToken","regex":"/\\\\s+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\//","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_SL_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\/[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"imports":[],"types":[]}'),`EventModelingGrammar`),QI,$I=o(()=>QI??=eP(`{"$type":"Grammar","isDeclared":true,"name":"GitGraphGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"GitGraph","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Keyword","value":":"}]},{"$type":"Keyword","value":"gitGraph:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Keyword","value":":"}]}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"Assignment","feature":"statements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Direction","definition":{"$type":"Assignment","feature":"dir","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"LR"},{"$type":"Keyword","value":"TB"},{"$type":"Keyword","value":"BT"}]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Commit","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"commit"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"msg:","cardinality":"?"},{"$type":"Assignment","feature":"message","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Branch","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"branch"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"order:"},{"$type":"Assignment","feature":"order","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Merge","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"merge"},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Checkout","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"checkout"},{"$type":"Keyword","value":"switch"}]},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CherryPicking","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"cherry-pick"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"parent:"},{"$type":"Assignment","feature":"parent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@14"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"REFERENCE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\\\w([-\\\\./\\\\w]*[-\\\\w])?/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[],"types":[]}`),`GitGraphGrammarGrammar`),eL,tL=o(()=>eL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"InfoGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Info","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"info"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Keyword","value":"showInfo"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[],"cardinality":"?"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@7"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`),`InfoGrammarGrammar`),nL,rL=o(()=>nL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"PacketGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Packet","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"packet"},{"$type":"Keyword","value":"packet-beta"}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"Assignment","feature":"blocks","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PacketBlock","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"start","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"end","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"+"},{"$type":"Assignment","feature":"bits","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]}]},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@9"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`),`PacketGrammarGrammar`),iL,aL=o(()=>iL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"PieGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Pie","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"pie"},{"$type":"Assignment","feature":"showData","operator":"?=","terminal":{"$type":"Keyword","value":"showData"},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Assignment","feature":"sections","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PieSection","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"FLOAT_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/-?[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/-?(0|[1-9][0-9]*)(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@2"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@3"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@11"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@12"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`),`PieGrammarGrammar`),oL,sL=o(()=>oL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"RadarGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Radar","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":"radar-beta:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":":"}]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Keyword","value":"axis"},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"curve"},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Label","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Axis","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Curve","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"},{"$type":"Keyword","value":"{"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Entries","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"DetailedEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"axis","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@2"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"NumberEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Option","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"showLegend"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"ticks"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"max"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"min"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"graticule"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"GRATICULE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"circle"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"polygon"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@16"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[{"$type":"Interface","name":"Entry","attributes":[{"$type":"TypeAttribute","name":"axis","isOptional":true,"type":{"$type":"ReferenceType","referenceType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@2"}},"isMulti":false}},{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}],"superTypes":[]}],"types":[]}`),`RadarGrammarGrammar`),cL,lL=o(()=>cL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"RailroadAbnfGrammar","rules":[{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_RULENAME","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[A-Za-z][A-Za-z0-9-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_NUMVAL","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/%[xXdDbB][0-9A-Fa-f]+(?:-[0-9A-Fa-f]+|\\\\.[0-9A-Fa-f]+)*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_REPEAT","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[0-9]*\\\\*[0-9]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_EXACT_REPEAT","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[0-9]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t \\\\r\\\\n]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_COMMENT","definition":{"$type":"RegexToken","regex":"/;[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"ParserRule","entry":true,"name":"RailroadAbnf","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"railroad-abnf-beta"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfRule","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Keyword","value":"="},{"$type":"Assignment","feature":"definition","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Keyword","value":";"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfAlternation","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"/"},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfConcatenation","returnType":{"$ref":"#/interfaces@3"},"definition":{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]},"cardinality":"+"},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfElement","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"repeat","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"repeat","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}],"cardinality":"?"},{"$type":"Assignment","feature":"primary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfPrimary","returnType":{"$ref":"#/interfaces@5"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfStringLiteral","returnType":{"$ref":"#/interfaces@6"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfNumVal","returnType":{"$ref":"#/interfaces@7"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfRuleName","returnType":{"$ref":"#/interfaces@8"},"definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfGroup","returnType":{"$ref":"#/interfaces@9"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfOptionalGroup","returnType":{"$ref":"#/interfaces@10"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"RailroadAbnf","attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"rules","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@1"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfRule","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"definition","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfAlternation","attributes":[{"$type":"TypeAttribute","name":"alternatives","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@3"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfConcatenation","attributes":[{"$type":"TypeAttribute","name":"elements","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@4"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfElement","attributes":[{"$type":"TypeAttribute","name":"repeat","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"primary","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfPrimary","attributes":[],"superTypes":[]},{"$type":"Interface","name":"AbnfStringLiteral","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"AbnfNumVal","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"AbnfRuleName","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"AbnfGroup","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"AbnfOptionalGroup","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]}],"imports":[],"types":[]}`),`RailroadAbnfGrammarGrammar`),uL,dL=o(()=>uL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"RailroadEbnfGrammar","rules":[{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EBNF_ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[A-Z_a-z][\\\\w-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EBNF_STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EBNF_SPECIAL_SEQUENCE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\\\?(?=[^?;]*[^?\\\\s;][^?;]*\\\\?)[^?;]*\\\\?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t \\\\r\\\\n]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_BLOCK_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\//","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_ISO_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\(\\\\*[\\\\s\\\\S]*?\\\\*\\\\)/","parenthesized":false},"fragment":false},{"$type":"ParserRule","entry":true,"name":"RailroadEbnf","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"railroad-ebnf-beta"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfRule","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"="},{"$type":"Keyword","value":"::="}]},{"$type":"Assignment","feature":"definition","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":";"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfChoice","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"|"},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfSequence","returnType":{"$ref":"#/interfaces@3"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":",","cardinality":"?"},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfTerm","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"base","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"Assignment","feature":"postfixes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfPrimary","returnType":{"$ref":"#/interfaces@5"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfTerminal","returnType":{"$ref":"#/interfaces@7"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfNonTerminal","returnType":{"$ref":"#/interfaces@8"},"definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfSpecial","returnType":{"$ref":"#/interfaces@9"},"definition":{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfGroup","returnType":{"$ref":"#/interfaces@10"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfOptional","returnType":{"$ref":"#/interfaces@11"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfRepetition","returnType":{"$ref":"#/interfaces@12"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfPostfix","returnType":{"$ref":"#/interfaces@6"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@26"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@27"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfOptionalPostfix","returnType":{"$ref":"#/interfaces@13"},"definition":{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"?"}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfZeroOrMorePostfix","returnType":{"$ref":"#/interfaces@14"},"definition":{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"*"}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfOneOrMorePostfix","returnType":{"$ref":"#/interfaces@15"},"definition":{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"+"}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfExceptionPostfix","returnType":{"$ref":"#/interfaces@16"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"except","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"RailroadEbnf","attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"rules","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@1"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfRule","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"definition","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfChoice","attributes":[{"$type":"TypeAttribute","name":"alternatives","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@3"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfSequence","attributes":[{"$type":"TypeAttribute","name":"elements","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@4"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfTerm","attributes":[{"$type":"TypeAttribute","name":"base","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}},"isOptional":false},{"$type":"TypeAttribute","name":"postfixes","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@6"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfPrimary","attributes":[],"superTypes":[]},{"$type":"Interface","name":"EbnfPostfix","attributes":[],"superTypes":[]},{"$type":"Interface","name":"EbnfTerminal","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfNonTerminal","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfSpecial","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"text","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfGroup","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"EbnfOptional","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"EbnfRepetition","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"EbnfOptionalPostfix","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"operator","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfZeroOrMorePostfix","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"operator","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfOneOrMorePostfix","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"operator","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfExceptionPostfix","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"except","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}},"isOptional":false}]}],"imports":[],"types":[]}`),`RailroadEbnfGrammarGrammar`),fL,pL=o(()=>fL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"RailroadGrammar","rules":[{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"RR_ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[A-Z_a-z][\\\\w-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"RR_STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"RR_WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t \\\\r\\\\n]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"RR_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"RR_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"RR_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"RR_BLOCK_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\//","parenthesized":false},"fragment":false},{"$type":"ParserRule","entry":true,"name":"Railroad","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"railroad-beta"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadRule","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Keyword","value":"="},{"$type":"Assignment","feature":"definition","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":";"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadExpression","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadSequenceExpr","returnType":{"$ref":"#/interfaces@3"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"sequence"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}}],"cardinality":"*"},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadChoiceExpr","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"choice"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}}],"cardinality":"*"},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadOptionalExpr","returnType":{"$ref":"#/interfaces@5"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"optional"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadOneOrMoreExpr","returnType":{"$ref":"#/interfaces@6"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"oneOrMore"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadZeroOrMoreExpr","returnType":{"$ref":"#/interfaces@7"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"zeroOrMore"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadTerminalExpr","returnType":{"$ref":"#/interfaces@8"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"terminal"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadNonTerminalExpr","returnType":{"$ref":"#/interfaces@9"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"nonterminal"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadSpecialExpr","returnType":{"$ref":"#/interfaces@10"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"special"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"Railroad","attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"rules","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@1"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"RailroadRule","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"definition","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"RailroadExpression","attributes":[],"superTypes":[]},{"$type":"Interface","name":"RailroadSequenceExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"elements","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}}},"isOptional":false}]},{"$type":"Interface","name":"RailroadChoiceExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"alternatives","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}}},"isOptional":false}]},{"$type":"Interface","name":"RailroadOptionalExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"RailroadOneOrMoreExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"RailroadZeroOrMoreExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"RailroadTerminalExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"RailroadNonTerminalExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"RailroadSpecialExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"text","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]}],"imports":[],"types":[]}`),`RailroadGrammarGrammar`),mL,hL=o(()=>mL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"RailroadPegGrammar","rules":[{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"PEG_ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[A-Z_a-z][\\\\w-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"PEG_STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t \\\\r\\\\n]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/#[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"ParserRule","entry":true,"name":"RailroadPeg","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"railroad-peg-beta"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegRule","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Keyword","value":"<-"},{"$type":"Assignment","feature":"definition","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":";"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegOrderedChoice","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"/"},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegSequence","returnType":{"$ref":"#/interfaces@3"},"definition":{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"cardinality":"+"},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegPrefix","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"&"}},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"!"}}],"cardinality":"?"},{"$type":"Assignment","feature":"suffix","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegSuffix","returnType":{"$ref":"#/interfaces@5"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"primary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"?"}},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"*"}},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"+"}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegPrimary","returnType":{"$ref":"#/interfaces@6"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegLiteral","returnType":{"$ref":"#/interfaces@7"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegIdentifier","returnType":{"$ref":"#/interfaces@8"},"definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegGroup","returnType":{"$ref":"#/interfaces@9"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegAny","returnType":{"$ref":"#/interfaces@10"},"definition":{"$type":"Assignment","feature":"dot","operator":"=","terminal":{"$type":"Keyword","value":"."}},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"RailroadPeg","attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"rules","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@1"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegRule","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"definition","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegOrderedChoice","attributes":[{"$type":"TypeAttribute","name":"alternatives","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@3"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegSequence","attributes":[{"$type":"TypeAttribute","name":"elements","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@4"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegPrefix","attributes":[{"$type":"TypeAttribute","name":"operator","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"suffix","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegSuffix","attributes":[{"$type":"TypeAttribute","name":"primary","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@6"}},"isOptional":false},{"$type":"TypeAttribute","name":"operator","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]},{"$type":"Interface","name":"PegPrimary","attributes":[],"superTypes":[]},{"$type":"Interface","name":"PegLiteral","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"PegIdentifier","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"PegGroup","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"PegAny","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"dot","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]}],"imports":[],"types":[]}`),`RailroadPegGrammarGrammar`),gL,_L=o(()=>gL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"TreemapGrammar","rules":[{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","entry":true,"name":"Treemap","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]},{"$type":"Assignment","feature":"TreemapRows","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"TREEMAP_KEYWORD","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap-beta"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CLASS_DEF","definition":{"$type":"RegexToken","regex":"/classDef\\\\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\\\\s+([^;\\\\r\\\\n]*))?(?:;)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STYLE_SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":::"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"COMMA","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":","},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INDENTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]{1,}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\%\\\\%[^\\\\n]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"TreemapRow","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"indent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"item","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ClassDef","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Item","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Section","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Leaf","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[],"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[],"cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"ID2","definition":{"$type":"RegexToken","regex":"/[a-zA-Z_][a-zA-Z0-9_]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER2","definition":{"$type":"RegexToken","regex":"/[0-9_\\\\.\\\\,]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"MyNumber","dataType":"number","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"STRING2","definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"|'[^']*'/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[{"$type":"Interface","name":"Item","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"classSelector","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]},{"$type":"Interface","name":"Section","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[]},{"$type":"Interface","name":"Leaf","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}]},{"$type":"Interface","name":"ClassDefStatement","attributes":[{"$type":"TypeAttribute","name":"className","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"styleText","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"Treemap","attributes":[{"$type":"TypeAttribute","name":"TreemapRows","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@15"}}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"imports":[],"types":[],"$comment":"/**\\n * Treemap grammar for Langium\\n * Converted from mindmap grammar\\n *\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\n * before the treemap keyword, allowing for empty lines and comments before the\\n * treemap declaration.\\n */"}`),`TreemapGrammarGrammar`),vL,yL=o(()=>vL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"TreeViewGrammar","rules":[{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","entry":true,"name":"TreeView","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"treeView-beta"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[],"cardinality":"?"},{"$type":"Assignment","feature":"nodes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"CLASS_ANNOTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+:::[ \\\\t]*[A-Za-z_][\\\\w-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ICON_ANNOTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+icon\\\\([\\\\w-]*(?::[\\\\w-]+)?\\\\)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"DESC_ANNOTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+##[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INDENTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]{1,}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"QUOTED_NAME","definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"|'[^']*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\%\\\\%[^\\\\n]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"BARE_NAME","definition":{"$type":"RegexToken","regex":"/(?!:::|icon\\\\(|##)[^ \\\\t\\\\n\\\\r\\"'](?:(?![ \\\\t]+:::[ \\\\t]*[A-Za-z_]|[ \\\\t]+icon\\\\(|[ \\\\t]+##)[^\\\\n\\\\r])*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"TreeNode","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"indent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}}]},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"classAnnotation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"iconAnnotation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"descAnnotation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"TreeView","attributes":[{"$type":"TypeAttribute","name":"nodes","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@14"}}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"imports":[],"types":[],"$comment":"/**\\n * TreeView grammar for Langium\\n *\\n * Supports both quoted labels (\\"my file\\") and bare labels (index.js).\\n * Annotations (:::class, icon(), ## description) are parsed directly into\\n * AST fields by the grammar. Value conversion for stripping quotes, extracting\\n * class names, icon names, and description text happens in valueConverter.ts.\\n *\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\n * before the treeView keyword, allowing for empty lines and comments before the\\n * treeView declaration.\\n */"}`),`TreeViewGrammarGrammar`),bL,xL=o(()=>bL??=eP(`{"$type":"Grammar","isDeclared":true,"name":"WardleyGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Wardley","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@42"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"size","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Assignment","feature":"anchors","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"components","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"links","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"evolves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}},{"$type":"Assignment","feature":"pipelines","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"notes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"annotations","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Assignment","feature":"annotation","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"accelerators","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"Assignment","feature":"deaccelerators","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Size","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@26"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"width","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"height","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Evolution","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@27"},"arguments":[]},{"$type":"Assignment","feature":"stages","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},{"$type":"Assignment","feature":"stages","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}}],"cardinality":"+"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EvolutionStage","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"@"},{"$type":"Assignment","feature":"boundary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}}],"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"/"},{"$type":"Assignment","feature":"secondName","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Anchor","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Component","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"decorator","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"inertia","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"inertia","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]}},{"$type":"Keyword","value":")"}]}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Label","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"negX","operator":"?=","terminal":{"$type":"Keyword","value":"-"},"cardinality":"?"},{"$type":"Assignment","feature":"offsetX","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"negY","operator":"?=","terminal":{"$type":"Keyword","value":"-"},"cardinality":"?"},{"$type":"Assignment","feature":"offsetY","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Decorator","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"strategy","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Link","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"fromPort","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"arrow","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}]},"cardinality":"?"},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"toPort","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"linkLabel","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Evolve","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]},{"$type":"Assignment","feature":"component","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Pipeline","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@33"},"arguments":[]},{"$type":"Assignment","feature":"parent","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"{"},{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"+"},{"$type":"Assignment","feature":"components","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]},"cardinality":"+"},{"$type":"Keyword","value":"}"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PipelineComponent","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Note","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[]},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Annotations","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Annotation","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@36"},"arguments":[]},{"$type":"Assignment","feature":"number","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CoordinateValue","dataType":"number","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Accelerator","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@37"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Deaccelerator","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"WARDLEY_NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"->"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_PORT","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+<>"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+>"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+<"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_ARROW","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"-->"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"-.->"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":">"},"parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'<>/","parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'/","parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_LABEL","definition":{"$type":"RegexToken","regex":"/;[^\\\\n\\\\r]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRATEGY","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"build"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"buy"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"outsource"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"market"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_WARDLEY","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"wardley-beta"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_SIZE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"size"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_EVOLUTION","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"evolution"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANCHOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"anchor"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_COMPONENT","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"component"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_LABEL","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"label"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_INERTIA","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"inertia"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_EVOLVE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"evolve"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_PIPELINE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"pipeline"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_NOTE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"note"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANNOTATIONS","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"annotations"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANNOTATION","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"annotation"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ACCELERATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"accelerator"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_DEACCELERATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"deaccelerator"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NAME_WITH_SPACES","definition":{"$type":"RegexToken","regex":"/(?!title\\\\s|accTitle|accDescr)[A-Za-z](?:[A-Za-z0-9_()&]|-(?!>))*(?:[ \\\\t]+[A-Za-z(](?:[A-Za-z0-9_()&]|-(?!>))*)*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@44"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@45"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@46"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@47"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@48"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`),`WardleyGrammarGrammar`),SL={languageId:`architecture`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},CL={languageId:`cynefin`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},wL={languageId:`eventmodeling`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},TL={languageId:`gitGraph`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},EL={languageId:`info`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},DL={languageId:`packet`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},OL={languageId:`pie`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},kL={languageId:`radar`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},AL={languageId:`railroadAbnf`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},jL={languageId:`railroadEbnf`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},ML={languageId:`railroad`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},NL={languageId:`railroadPeg`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},PL={languageId:`treemap`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},FL={languageId:`treeView`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},IL={languageId:`wardley`,fileExtensions:[`.mmd`,`.mermaid`],caseInsensitive:!1,mode:`production`},LL={AstReflection:o(()=>new GI,`AstReflection`)},RL={Grammar:o(()=>qI(),`Grammar`),LanguageMetaData:o(()=>SL,`LanguageMetaData`),parser:{}},zL={Grammar:o(()=>YI(),`Grammar`),LanguageMetaData:o(()=>CL,`LanguageMetaData`),parser:{}},BL={Grammar:o(()=>ZI(),`Grammar`),LanguageMetaData:o(()=>wL,`LanguageMetaData`),parser:{}},VL={Grammar:o(()=>$I(),`Grammar`),LanguageMetaData:o(()=>TL,`LanguageMetaData`),parser:{}},HL={Grammar:o(()=>tL(),`Grammar`),LanguageMetaData:o(()=>EL,`LanguageMetaData`),parser:{}},UL={Grammar:o(()=>rL(),`Grammar`),LanguageMetaData:o(()=>DL,`LanguageMetaData`),parser:{}},WL={Grammar:o(()=>aL(),`Grammar`),LanguageMetaData:o(()=>OL,`LanguageMetaData`),parser:{}},GL={Grammar:o(()=>sL(),`Grammar`),LanguageMetaData:o(()=>kL,`LanguageMetaData`),parser:{}},KL={Grammar:o(()=>lL(),`Grammar`),LanguageMetaData:o(()=>AL,`LanguageMetaData`),parser:{}},qL={Grammar:o(()=>dL(),`Grammar`),LanguageMetaData:o(()=>jL,`LanguageMetaData`),parser:{}},JL={Grammar:o(()=>pL(),`Grammar`),LanguageMetaData:o(()=>ML,`LanguageMetaData`),parser:{}},YL={Grammar:o(()=>hL(),`Grammar`),LanguageMetaData:o(()=>NL,`LanguageMetaData`),parser:{}},XL={Grammar:o(()=>_L(),`Grammar`),LanguageMetaData:o(()=>PL,`LanguageMetaData`),parser:{}},ZL={Grammar:o(()=>yL(),`Grammar`),LanguageMetaData:o(()=>FL,`LanguageMetaData`),parser:{}},QL={Grammar:o(()=>xL(),`Grammar`),LanguageMetaData:o(()=>IL,`LanguageMetaData`),parser:{}},$L={ACC_DESCR:/accDescr(?:[\t ]*:([^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/accTitle[\t ]*:([^\n\r]*)/,TITLE:/title([\t ][^\n\r]*|)/},eR=class extends Ij{static{o(this,`AbstractMermaidValueConverter`)}runConverter(e,t,n){let r=this.runCommonConverter(e,t,n);return r===void 0&&(r=this.runCustomConverter(e,t,n)),r===void 0?super.runConverter(e,t,n):r}runCommonConverter(e,t,n){let r=$L[e.name];if(r===void 0)return;let i=r.exec(t);if(i!==null){if(i[1]!==void 0)return i[1].trim().replace(/[\t ]{2,}/gm,` `);if(i[2]!==void 0)return i[2].replace(/^\s*/gm,``).replace(/\s+$/gm,``).replace(/[\t ]{2,}/gm,` `).replace(/[\n\r]{2,}/gm,` +`)}}},tR=class extends eR{static{o(this,`CommonValueConverter`)}runCustomConverter(e,t,n){}},nR=class extends Fj{static{o(this,`AbstractMermaidTokenBuilder`)}constructor(e){super(),this.keywords=new Set(e)}buildKeywordTokens(e,t,n){let r=super.buildKeywordTokens(e,t,n);return r.forEach(e=>{this.keywords.has(e.name)&&e.PATTERN!==void 0&&(e.PATTERN=RegExp(e.PATTERN.toString()+`(?:(?=%%)|(?!\\S))`))}),r}};(class extends nR{static{o(this,`CommonTokenBuilder`)}});export{FN as C,PN as S,EF as T,YL as _,zL as a,QL as b,VL as c,UL as d,WL as f,JL as g,qL as h,tR as i,HL as l,KL as m,eR as n,XN as o,GL as p,RL as r,BL as s,nR as t,LL as u,ZL as v,LN as w,o as x,XL as y}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-MOJQB5TN-Bju_yCKi.js b/dist-desktop/assets/chunk-MOJQB5TN-Bju_yCKi.js new file mode 100644 index 0000000..6492768 --- /dev/null +++ b/dist-desktop/assets/chunk-MOJQB5TN-Bju_yCKi.js @@ -0,0 +1,88 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t}from"./src-UMNXGZaF.js";import{D as n,a as r,b as i,c as a,x as o,z as s}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as c}from"./chunk-VAUOI2AC-AC9pRUsa.js";var l=``,u=``,d=``,f=[],p=new Map,m=e(e=>s(e,o()),`sanitizeText`),h=e(e=>{switch(e.type){case`terminal`:return{...e,value:m(e.value)};case`nonterminal`:return{...e,name:m(e.name)};case`sequence`:return{...e,elements:e.elements.map(h)};case`choice`:return{...e,alternatives:e.alternatives.map(h)};case`optional`:return{...e,element:h(e.element)};case`repetition`:return{...e,element:h(e.element),separator:e.separator?h(e.separator):void 0};case`special`:return{...e,text:m(e.text)}}},`sanitizeAstNode`),g=e(()=>{l=``,u=``,d=``,f.length=0,p.clear(),r(),t.debug(`[Railroad] Database cleared`)},`clear`),_=e(e=>{l=m(e),t.debug(`[Railroad] Title set:`,e)},`setTitle`),v=e(()=>l,`getTitle`),y={clear:g,setTitle:_,getTitle:v,addRule:e(e=>{let n={...e,name:m(e.name),definition:h(e.definition),comment:e.comment?m(e.comment):void 0};t.debug(`[Railroad] Adding rule:`,n.name),p.has(n.name)&&t.warn(`[Railroad] Rule '${n.name}' is already defined. Overwriting.`),f.push(n),p.set(n.name,n)},`addRule`),getRules:e(()=>f,`getRules`),getRule:e(e=>p.get(e),`getRule`),setAccTitle:e(e=>{u=m(e).replace(/^\s+/g,``),t.debug(`[Railroad] Accessibility title set:`,e)},`setAccTitle`),getAccTitle:e(()=>u,`getAccTitle`),setAccDescription:e(e=>{d=m(e).replace(/\n\s+/g,` +`),t.debug(`[Railroad] Accessibility description set:`,e)},`setAccDescription`),getAccDescription:e(()=>d,`getAccDescription`),setDiagramTitle:_,getDiagramTitle:v},b={compactMode:!1,padding:10,verticalSeparation:8,horizontalSeparation:10,arcRadius:10,fontSize:14,fontFamily:`monospace`,terminalFill:`#FFFFC0`,terminalStroke:`#000000`,terminalTextColor:`#000000`,nonTerminalFill:`#FFFFFF`,nonTerminalStroke:`#000000`,nonTerminalTextColor:`#000000`,lineColor:`#000000`,strokeWidth:2,markerFill:`#000000`,commentFill:`#E8E8E8`,commentStroke:`#888888`,commentTextColor:`#666666`,specialFill:`#F0E0FF`,specialStroke:`#8800CC`,ruleNameColor:`#000066`,showMarkers:!0,markerRadius:5},x=/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$|^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch)\([\d\s%+,./-]+\)$|^[a-z]+$/i,S=/^[\w "',.-]+$/,C=new Set([`compactMode`,`padding`,`verticalSeparation`,`horizontalSeparation`,`arcRadius`,`fontSize`,`fontFamily`,`terminalFill`,`terminalStroke`,`terminalTextColor`,`nonTerminalFill`,`nonTerminalStroke`,`nonTerminalTextColor`,`lineColor`,`strokeWidth`,`markerFill`,`commentFill`,`commentStroke`,`commentTextColor`,`specialFill`,`specialStroke`,`ruleNameColor`,`showMarkers`,`markerRadius`]),w=e(e=>e?Object.keys(e).every(e=>e===`railroad`||C.has(e)):!1,`isRailroadStyleOptions`),T=e(e=>e?`railroad`in e&&e.railroad?e.railroad:w(e)?e:{}:{},`extractRailroadOverrides`),E=e(e=>{if(!e||w(e))return{};let{railroad:t,svgId:n,theme:r,look:i,...a}=e;return a},`extractThemeOverrides`),D=e((e,t)=>{if(typeof e!=`string`)return t;let n=e.trim();return x.test(n)?n:t},`sanitizeColorValue`),O=e((e,t)=>{if(typeof e!=`string`)return t;let n=e.trim();return S.test(n)?n:t},`sanitizeFontFamilyValue`),k=e((e,t)=>{let n=typeof e==`number`?e:typeof e==`string`?Number.parseFloat(e):NaN;return Number.isFinite(n)&&n>=0?n:t},`sanitizeNumberValue`),A=e(e=>{let t=typeof e==`number`?e:typeof e==`string`?Number.parseFloat(e):NaN;return Number.isFinite(t)&&t>0?t:void 0},`parseThemeFontSize`),j=e(e=>{let t=O(e.fontFamily,b.fontFamily),n=A(e.fontSize)??b.fontSize;return{...b,fontFamily:t,fontSize:n,terminalFill:D(e.secondBkg??e.secondaryColor,b.terminalFill),terminalStroke:D(e.secondaryBorderColor??e.lineColor,b.terminalStroke),terminalTextColor:D(e.secondaryTextColor??e.textColor,b.terminalTextColor),nonTerminalFill:D(e.mainBkg??e.background,b.nonTerminalFill),nonTerminalStroke:D(e.primaryBorderColor??e.lineColor,b.nonTerminalStroke),nonTerminalTextColor:D(e.primaryTextColor??e.textColor,b.nonTerminalTextColor),lineColor:D(e.lineColor,b.lineColor),markerFill:D(e.lineColor,b.markerFill),commentFill:D(e.labelBackground??e.tertiaryColor,b.commentFill),commentStroke:D(e.tertiaryBorderColor??e.lineColor,b.commentStroke),commentTextColor:D(e.tertiaryTextColor??e.textColor,b.commentTextColor),specialFill:D(e.tertiaryColor??e.secondaryColor,b.specialFill),specialStroke:D(e.tertiaryBorderColor??e.secondaryBorderColor,b.specialStroke),ruleNameColor:D(e.titleColor??e.textColor,b.ruleNameColor)}},`buildThemeDefaults`),M=e(e=>{let t=i(),r=j({...n(),...t.themeVariables??{},...E(e)}),a={...t.railroad??{},...T(e)};return{compactMode:a.compactMode??r.compactMode,padding:k(a.padding,r.padding),verticalSeparation:k(a.verticalSeparation,r.verticalSeparation),horizontalSeparation:k(a.horizontalSeparation,r.horizontalSeparation),arcRadius:k(a.arcRadius,r.arcRadius),fontSize:k(a.fontSize,r.fontSize),fontFamily:O(a.fontFamily,r.fontFamily),terminalFill:D(a.terminalFill,r.terminalFill),terminalStroke:D(a.terminalStroke,r.terminalStroke),terminalTextColor:D(a.terminalTextColor,r.terminalTextColor),nonTerminalFill:D(a.nonTerminalFill,r.nonTerminalFill),nonTerminalStroke:D(a.nonTerminalStroke,r.nonTerminalStroke),nonTerminalTextColor:D(a.nonTerminalTextColor,r.nonTerminalTextColor),lineColor:D(a.lineColor,r.lineColor),strokeWidth:k(a.strokeWidth,r.strokeWidth),markerFill:D(a.markerFill,r.markerFill),commentFill:D(a.commentFill,r.commentFill),commentStroke:D(a.commentStroke,r.commentStroke),commentTextColor:D(a.commentTextColor,r.commentTextColor),specialFill:D(a.specialFill,r.specialFill),specialStroke:D(a.specialStroke,r.specialStroke),ruleNameColor:D(a.ruleNameColor,r.ruleNameColor),showMarkers:a.showMarkers??r.showMarkers,markerRadius:k(a.markerRadius,r.markerRadius)}},`buildRailroadStyleOptions`),N=e(e=>{let{fontFamily:t,fontSize:n,terminalFill:r,terminalStroke:i,terminalTextColor:a,nonTerminalFill:o,nonTerminalStroke:s,nonTerminalTextColor:c,lineColor:l,strokeWidth:u,markerFill:d,commentFill:f,commentStroke:p,commentTextColor:m,specialFill:h,specialStroke:g,ruleNameColor:_}=M(e);return` + .railroad-diagram { + font-family: ${t}; + font-size: ${n}px; + } + + .railroad-terminal rect { + fill: ${r}; + stroke: ${i}; + stroke-width: ${u}px; + } + + .railroad-terminal text { + fill: ${a}; + font-family: ${t}; + font-size: ${n}px; + text-anchor: middle; + dominant-baseline: middle; + } + + .railroad-nonterminal rect { + fill: ${o}; + stroke: ${s}; + stroke-width: ${u}px; + } + + .railroad-nonterminal text { + fill: ${c}; + font-family: ${t}; + font-size: ${n}px; + text-anchor: middle; + dominant-baseline: middle; + } + + .railroad-line { + stroke: ${l}; + stroke-width: ${u}px; + fill: none; + } + + .railroad-start circle, + .railroad-end circle { + fill: ${d}; + } + + .railroad-comment ellipse { + fill: ${f}; + stroke: ${p}; + stroke-width: ${u}px; + } + + .railroad-comment text { + fill: ${m}; + font-style: italic; + font-family: ${t}; + font-size: ${n}px; + text-anchor: middle; + dominant-baseline: middle; + } + + .railroad-special rect { + fill: ${h}; + stroke: ${g}; + stroke-width: ${u}px; + stroke-dasharray: 5,3; + } + + .railroad-special text { + fill: ${c}; + font-family: ${t}; + font-size: ${n}px; + text-anchor: middle; + dominant-baseline: middle; + } + + .railroad-rule-name { + font-weight: bold; + fill: ${_}; + font-family: ${t}; + font-size: ${n}px; + } + + .railroad-group { + /* Grouping container, no specific styles */ + } +`},`getStyles`),P=class{constructor(){this.d=``}static{e(this,`PathBuilder`)}moveTo(e,t){return this.d+=`M ${e} ${t} `,this}lineTo(e,t){return this.d+=`L ${e} ${t} `,this}horizontalTo(e){return this.d+=`H ${e} `,this}verticalTo(e){return this.d+=`V ${e} `,this}arcTo(e,t,n,r,i,a,o){return this.d+=`A ${e} ${t} ${n} ${+!!r} ${+!!i} ${a} ${o} `,this}build(){return this.d.trim()}},F=class{constructor(e,t=M()){this.textCache=new Map,this.svg=e,this.config=t}static{e(this,`RailroadRenderer`)}measureText(e){if(this.textCache.has(e))return this.textCache.get(e);let t=this.svg.append(`text`).attr(`font-family`,this.config.fontFamily).attr(`font-size`,this.config.fontSize).text(e),n=t.node().getBBox(),r={width:n.width,height:n.height};return t.remove(),this.textCache.set(e,r),r}renderTerminal(e,t){let n=this.measureText(t),r=n.width+this.config.padding*2,i=n.height+this.config.padding*2,a=e.append(`g`).attr(`class`,`railroad-terminal`);return a.append(`rect`).attr(`x`,0).attr(`y`,0).attr(`width`,r).attr(`height`,i).attr(`rx`,10).attr(`ry`,10),a.append(`text`).attr(`x`,r/2).attr(`y`,i/2).text(t),{element:a.node(),dimensions:{width:r,height:i,up:i/2,down:i/2}}}renderNonTerminal(e,t){let n=this.measureText(t),r=n.width+this.config.padding*2,i=n.height+this.config.padding*2,a=e.append(`g`).attr(`class`,`railroad-nonterminal`);return a.append(`rect`).attr(`x`,0).attr(`y`,0).attr(`width`,r).attr(`height`,i),a.append(`text`).attr(`x`,r/2).attr(`y`,i/2).text(t),{element:a.node(),dimensions:{width:r,height:i,up:i/2,down:i/2}}}renderSequence(e,t){let n=t.map(t=>this.renderExpression(e,t)),r=0,i=0,a=0;for(let e of n)r+=e.dimensions.width,i=Math.max(i,e.dimensions.up),a=Math.max(a,e.dimensions.down);r+=(n.length-1)*this.config.horizontalSeparation;let o=e.append(`g`).attr(`class`,`railroad-sequence`),s=0;for(let e=0;ethis.renderExpression(e,t)),r=0,i=0;for(let e of n)r=Math.max(r,e.dimensions.width),i+=e.dimensions.height;i+=(n.length-1)*this.config.verticalSeparation;let a=this.config.arcRadius,o=a*4,s=r+o,c=e.append(`g`).attr(`class`,`railroad-choice`),l=0,u=i/2;for(let e of n){let t=l,n=t+e.dimensions.up,i=a*2+(r-e.dimensions.width)/2;c.node().appendChild(e.element).setAttribute(`transform`,`translate(${i}, ${t})`);let o=new P,d=n>u;n===u?o.moveTo(0,u).lineTo(i,n):o.moveTo(0,u).arcTo(a,a,0,!1,d,a,u+(d?a:-a)).lineTo(a,n-(d?a:-a)).arcTo(a,a,0,!1,!d,a*2,n).lineTo(i,n),c.append(`path`).attr(`class`,`railroad-line`).attr(`d`,o.build());let f=new P,p=i+e.dimensions.width,m=s-a*2;n===u?f.moveTo(p,n).lineTo(s,u):f.moveTo(p,n).lineTo(m,n).arcTo(a,a,0,!1,!d,s-a,n+(d?-a:a)).lineTo(s-a,u+(d?a:-a)).arcTo(a,a,0,!1,d,s,u),c.append(`path`).attr(`class`,`railroad-line`).attr(`d`,f.build()),l+=e.dimensions.height+this.config.verticalSeparation}return{element:c.node(),dimensions:{width:s,height:i,up:u,down:i-u}}}renderOptional(e,t){let n=this.renderExpression(e,t),r=this.config.arcRadius,i=r*2,a=n.dimensions.width+r*4,o=n.dimensions.height+i,s=e.append(`g`).attr(`class`,`railroad-optional`),c=r*2,l=i;s.node().appendChild(n.element).setAttribute(`transform`,`translate(${c}, ${l})`);let u=l+n.dimensions.up,d=new P().moveTo(0,u).lineTo(r*2,u);s.append(`path`).attr(`class`,`railroad-line`).attr(`d`,d.build());let f=new P().moveTo(c+n.dimensions.width,u).lineTo(a,u);s.append(`path`).attr(`class`,`railroad-line`).attr(`d`,f.build());let p=new P().moveTo(0,u).arcTo(r,r,0,!1,!1,r,u-r).lineTo(r,r).arcTo(r,r,0,!1,!0,r*2,0).lineTo(a-r*2,0).arcTo(r,r,0,!1,!0,a-r,r).lineTo(a-r,u-r).arcTo(r,r,0,!1,!1,a,u);return s.append(`path`).attr(`class`,`railroad-line`).attr(`d`,p.build()),{element:s.node(),dimensions:{width:a,height:o,up:u,down:o-u}}}renderRepetition(e,t,n){let r=this.renderExpression(e,t),i=this.config.arcRadius,a=i*2,o=r.dimensions.width+i*4,s=n===0,c=r.dimensions.height+a+(s?a:0),l=e.append(`g`).attr(`class`,`railroad-repetition`),u=i*2,d=s?a:0;l.node().appendChild(r.element).setAttribute(`transform`,`translate(${u}, ${d})`);let f=d+r.dimensions.up;l.append(`path`).attr(`class`,`railroad-line`).attr(`d`,new P().moveTo(0,f).lineTo(i*2,f).build()),l.append(`path`).attr(`class`,`railroad-line`).attr(`d`,new P().moveTo(u+r.dimensions.width,f).lineTo(o,f).build());let p=d+r.dimensions.height+i,m=new P().moveTo(u+r.dimensions.width,f).arcTo(i,i,0,!1,!0,u+r.dimensions.width+i,f+i).lineTo(u+r.dimensions.width+i,p).arcTo(i,i,0,!1,!0,u+r.dimensions.width,p+i).lineTo(i*2,p+i).arcTo(i,i,0,!1,!0,i,p).lineTo(i,f+i).arcTo(i,i,0,!1,!0,i*2,f);if(l.append(`path`).attr(`class`,`railroad-line`).attr(`d`,m.build()),s){let e=new P().moveTo(0,f).arcTo(i,i,0,!1,!1,i,f-i).lineTo(i,i).arcTo(i,i,0,!1,!0,i*2,0).lineTo(o-i*2,0).arcTo(i,i,0,!1,!0,o-i,i).lineTo(o-i,f-i).arcTo(i,i,0,!1,!1,o,f);l.append(`path`).attr(`class`,`railroad-line`).attr(`d`,e.build())}return{element:l.node(),dimensions:{width:o,height:c,up:f,down:c-f}}}renderSpecial(e,t){let n=this.measureText(`? `+t+` ?`),r=n.width+this.config.padding*2,i=n.height+this.config.padding*2,a=e.append(`g`).attr(`class`,`railroad-special`);return a.append(`rect`).attr(`x`,0).attr(`y`,0).attr(`width`,r).attr(`height`,i),a.append(`text`).attr(`x`,r/2).attr(`y`,i/2).text(`? `+t+` ?`),{element:a.node(),dimensions:{width:r,height:i,up:i/2,down:i/2}}}renderExpression(e,t){switch(t.type){case`terminal`:return this.renderTerminal(e,t.value);case`nonterminal`:return this.renderNonTerminal(e,t.name);case`sequence`:return this.renderSequence(e,t.elements);case`choice`:return this.renderChoice(e,t.alternatives);case`optional`:return this.renderOptional(e,t.element);case`repetition`:return this.renderRepetition(e,t.element,t.min);case`special`:return this.renderSpecial(e,t.text);default:throw Error(`Unknown node type: ${t.type}`)}}renderRule(e,t){let n=this.svg.append(`g`).attr(`class`,`railroad-rule`).attr(`transform`,`translate(0, ${t})`),r=e.name+` =`,i=this.measureText(r).width+20,a=i+20,o=n.append(`g`),s=this.renderExpression(o,e.definition),c=Math.max(20,s.dimensions.up),l=c-s.dimensions.up;return o.attr(`transform`,`translate(${a}, ${l})`),n.append(`g`).attr(`class`,`railroad-rule-name-group`).append(`text`).attr(`class`,`railroad-rule-name`).attr(`x`,0).attr(`y`,c).text(r),n.append(`g`).attr(`class`,`railroad-start`).append(`circle`).attr(`cx`,i).attr(`cy`,c).attr(`r`,this.config.markerRadius),n.append(`g`).attr(`class`,`railroad-end`).append(`circle`).attr(`cx`,a+s.dimensions.width+10).attr(`cy`,c).attr(`r`,this.config.markerRadius),n.append(`path`).attr(`class`,`railroad-line`).attr(`d`,new P().moveTo(i+this.config.markerRadius,c).lineTo(a,c).build()),n.append(`path`).attr(`class`,`railroad-line`).attr(`d`,new P().moveTo(a+s.dimensions.width,c).lineTo(a+s.dimensions.width+10-this.config.markerRadius,c).build()),{height:Math.max(40,l+s.dimensions.height+this.config.padding*2),width:a+s.dimensions.width+10+this.config.markerRadius}}renderDiagram(e){let t=this.config.padding,n=0;for(let r of e){let e=this.renderRule(r,t);t+=e.height+this.config.verticalSeparation,n=Math.max(n,e.width)}return{width:n+this.config.padding*2,height:t+this.config.padding}}},I=e((e,t,n)=>{a(e,t.height,t.width,n),e.attr(`viewBox`,`0 0 ${t.width} ${t.height}`)},`configureRailroadSvgSize`),L={draw:e((e,n,r)=>{t.debug(`[Railroad] Rendering diagram +`+e);try{let e=c(n);e.attr(`class`,`railroad-diagram`);let r=i().railroad?.useMaxWidth??!0,a=y.getRules();if(t.debug(`[Railroad] Rendering ${a.length} rules`),a.length===0){t.warn(`[Railroad] No rules to render`),I(e,{height:100,width:200},r);return}I(e,new F(e,M()).renderDiagram(a),r),t.debug(`[Railroad] Render complete`)}catch(e){throw t.error(`[Railroad] Render error:`,e),e}},`draw`)};export{N as n,L as r,y as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-MOZMSUNE-BgA8jCvb.js b/dist-desktop/assets/chunk-MOZMSUNE-BgA8jCvb.js new file mode 100644 index 0000000..557bf09 --- /dev/null +++ b/dist-desktop/assets/chunk-MOZMSUNE-BgA8jCvb.js @@ -0,0 +1 @@ +import{C as e,S as t,n,o as r,r as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`ArchitectureTokenBuilder`)}constructor(){super([`architecture`])}},u=class extends n{static{c(this,`ArchitectureValueConverter`)}runCustomConverter(e,t,n){if(e.name===`ARCH_ICON`)return t.replace(/[()]/g,``).trim();if(e.name===`ARCH_TEXT_ICON`)return t.replace(/["()]/g,``);if(e.name===`ARCH_TITLE`){let e=t.replace(/^\[|]$/g,``).trim();return(e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`))&&(e=e.slice(1,-1),e=e.replace(/\\"/g,`"`).replace(/\\'/g,`'`)),e.trim()}}},d={parser:{TokenBuilder:c(()=>new l,`TokenBuilder`),ValueConverter:c(()=>new u,`ValueConverter`)}};function f(n=r){let a=s(e(n),o),c=s(t({shared:a}),i,d);return a.ServiceRegistry.register(c),{shared:a,Architecture:c}}c(f,`createArchitectureServices`);export{f as n,d as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-OGEWGWER-D-nWYRNR.js b/dist-desktop/assets/chunk-OGEWGWER-D-nWYRNR.js new file mode 100644 index 0000000..a3dd93f --- /dev/null +++ b/dist-desktop/assets/chunk-OGEWGWER-D-nWYRNR.js @@ -0,0 +1 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{f as t,x as n}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{p as r}from"./chunk-ICXQ74PX-Czpgj8Uw.js";var i=e(({flowchart:e})=>{let t=e?.subGraphTitleMargin?.top??0,n=e?.subGraphTitleMargin?.bottom??0;return{subGraphTitleTopMargin:t,subGraphTitleBottomMargin:n,subGraphTitleTotalMargin:t+n}},`getSubGraphTitleMargins`);async function a(i,a){let o=i.getElementsByTagName(`img`);if(!o||o.length===0)return;let s=a.replace(/]*>/g,``).trim()===``;await Promise.all([...o].map(i=>new Promise(a=>{function o(){if(i.style.display=`flex`,i.style.flexDirection=`column`,s){let[e=t.fontSize]=r(n().fontSize?n().fontSize:window.getComputedStyle(document.body).fontSize),a=e*5+`px`;i.style.minWidth=a,i.style.maxWidth=a}else i.style.width=`100%`;a(i)}e(o,`setupImage`),setTimeout(()=>{i.complete&&o()}),i.addEventListener(`error`,o),i.addEventListener(`load`,o)})))}e(a,`configureLabelImages`);export{i as n,a as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-OSBZ3O6U-CX9EQ5t2.js b/dist-desktop/assets/chunk-OSBZ3O6U-CX9EQ5t2.js new file mode 100644 index 0000000..83b8b1d --- /dev/null +++ b/dist-desktop/assets/chunk-OSBZ3O6U-CX9EQ5t2.js @@ -0,0 +1 @@ +import{C as e,S as t,a as n,i as r,o as i,t as a,u as o,w as s,x as c}from"./chunk-KEIR6QF5-Dj-OpFgW.js";var l=class extends a{static{c(this,`CynefinTokenBuilder`)}constructor(){super([`cynefin-beta`])}},u={parser:{TokenBuilder:c(()=>new l,`TokenBuilder`),ValueConverter:c(()=>new r,`ValueConverter`)}};function d(r=i){let a=s(e(r),o),c=s(t({shared:a}),n,u);return a.ServiceRegistry.register(c),{shared:a,Cynefin:c}}c(d,`createCynefinServices`);export{d as n,u as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-PUDLZKDR-hlw4TonS.js b/dist-desktop/assets/chunk-PUDLZKDR-hlw4TonS.js new file mode 100644 index 0000000..82af9d9 --- /dev/null +++ b/dist-desktop/assets/chunk-PUDLZKDR-hlw4TonS.js @@ -0,0 +1,156 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{$ as r,G as i,H as a,K as o,U as s,a as c,d as l,it as u,k as d,s as f,v as p,w as ee,x as m,y as h}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{t as te}from"./channel-C4fgBBJ4.js";import{c as g,g as _}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{t as ne}from"./chunk-5VM5RSS4-ZNzvKenW.js";import{t as re}from"./chunk-32BRIVSS-DWU3ezKg.js";import{t as v}from"./chunk-XXDRQBXY-Bq6zMMOx.js";import{t as y}from"./chunk-VR4S4FIN-BTo4eV3J.js";import{o as b}from"./chunk-ZGVPDNZ5-DGInJAPD.js";import{r as x,t as S}from"./chunk-FWX5IMBZ-ComLEIwh.js";import{n as C,t as w}from"./chunk-ZIRB5QZD-C6fEPe3t.js";var T=`flowchart-`,E=class{constructor(){this.vertexCounter=0,this.config=m(),this.diagramId=``,this.vertices=new Map,this.edges=[],this.classes=new Map,this.subGraphs=[],this.subGraphLookup=new Map,this.tooltips=new Map,this.subCount=0,this.firstGraphFlag=!0,this.secCount=-1,this.posCrossRef=[],this.funs=[],this.setAccTitle=s,this.setAccDescription=a,this.setDiagramTitle=o,this.getAccTitle=h,this.getAccDescription=p,this.getDiagramTitle=ee,this.funs.push(this.setupToolTips.bind(this)),this.addVertex=this.addVertex.bind(this),this.firstGraph=this.firstGraph.bind(this),this.setDirection=this.setDirection.bind(this),this.addSubGraph=this.addSubGraph.bind(this),this.addLink=this.addLink.bind(this),this.setLink=this.setLink.bind(this),this.updateLink=this.updateLink.bind(this),this.addClass=this.addClass.bind(this),this.setClass=this.setClass.bind(this),this.destructLink=this.destructLink.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setTooltip=this.setTooltip.bind(this),this.updateLinkInterpolate=this.updateLinkInterpolate.bind(this),this.setClickFun=this.setClickFun.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.lex={firstGraph:this.firstGraph.bind(this)},this.clear(),this.setGen(`gen-2`)}static{e(this,`FlowDB`)}sanitizeText(e){return f.sanitizeText(e,this.config)}sanitizeNodeLabelType(e){switch(e){case`markdown`:case`string`:case`text`:return e;default:return`markdown`}}setDiagramId(e){this.diagramId=e}lookUpDomId(e){for(let t of this.vertices.values())if(t.id===e)return this.diagramId?`${this.diagramId}-${t.domId}`:t.domId;return this.diagramId?`${this.diagramId}-${e}`:e}addVertex(e,n,r,i,a,o,s={},c){if(!e||e.trim().length===0)return;let l;if(c!==void 0){let e;e=c.includes(` +`)?c+` +`:`{ +`+c+` +}`,l=C(e,{schema:w})}let u=this.edges.find(t=>t.id===e);if(u){let e=l;e?.animate!==void 0&&(u.animate=e.animate),e?.animation!==void 0&&(u.animation=e.animation),e?.curve!==void 0&&(u.interpolate=e.curve);return}let d,f=this.vertices.get(e);if(f===void 0&&(n===void 0&&r===void 0&&i!=null&&t.warn(`Style applied to unknown node "${e}". This may indicate a typo. The node will be created automatically.`),f={id:e,labelType:`text`,domId:T+e+`-`+this.vertexCounter,styles:[],classes:[]},this.vertices.set(e,f)),this.vertexCounter++,n===void 0?f.text===void 0&&(f.text=e):(this.config=m(),d=this.sanitizeText(n.text.trim()),f.labelType=n.type,d.startsWith(`"`)&&d.endsWith(`"`)&&(d=d.substring(1,d.length-1)),f.text=d),r!==void 0&&(f.type=r),i?.forEach(e=>{f.styles.push(e)}),a?.forEach(e=>{f.classes.push(e)}),o!==void 0&&(f.dir=o),f.props===void 0?f.props=s:s!==void 0&&Object.assign(f.props,s),l!==void 0){if(l.shape){if(l.shape!==l.shape.toLowerCase()||l.shape.includes(`_`))throw Error(`No such shape: ${l.shape}. Shape names should be lowercase.`);if(!b(l.shape))throw Error(`No such shape: ${l.shape}.`);f.type=l?.shape}l?.label&&(f.text=l?.label,f.labelType=this.sanitizeNodeLabelType(l?.labelType)),l?.icon&&(f.icon=l?.icon,!l.label?.trim()&&f.text===e&&(f.text=``)),l?.form&&(f.form=l?.form),l?.pos&&(f.pos=l?.pos),l?.img&&(f.img=l?.img,!l.label?.trim()&&f.text===e&&(f.text=``)),l?.constraint&&(f.constraint=l.constraint),l.w&&(f.assetWidth=Number(l.w)),l.h&&(f.assetHeight=Number(l.h))}}addSingleLink(e,n,r,i){let a={start:e,end:n,type:void 0,text:``,labelType:`text`,classes:[],isUserDefinedId:!1,interpolate:this.edges.defaultInterpolate};t.info(`abc78 Got edge...`,a);let o=r.text;if(o!==void 0&&(a.text=this.sanitizeText(o.text.trim()),a.text.startsWith(`"`)&&a.text.endsWith(`"`)&&(a.text=a.text.substring(1,a.text.length-1)),a.labelType=this.sanitizeNodeLabelType(o.type)),r!==void 0&&(a.type=r.type,a.stroke=r.stroke,a.length=r.length>10?10:r.length),i&&!this.edges.some(e=>e.id===i))a.id=i,a.isUserDefinedId=!0;else{let e=this.edges.filter(e=>e.start===a.start&&e.end===a.end);e.length===0?a.id=g(a.start,a.end,{counter:0,prefix:`L`}):a.id=g(a.start,a.end,{counter:e.length+1,prefix:`L`})}if(this.edges.length<(this.config.maxEdges??500))t.info(`Pushing edge...`),this.edges.push(a);else throw Error(`Edge limit exceeded. ${this.edges.length} edges found, but the limit is ${this.config.maxEdges}. + +Initialize mermaid with maxEdges set to a higher number to allow more edges. +You cannot set this config via configuration inside the diagram as it is a secure config. +You have to call mermaid.initialize.`)}isLinkData(e){return typeof e==`object`&&!!e&&`id`in e&&typeof e.id==`string`}addLink(e,n,r){let i=this.isLinkData(r)?r.id.replace(`@`,``):void 0;t.info(`addLink`,e,n,i);for(let t of e)for(let a of n){let o=t===e[e.length-1],s=a===n[0];o&&s?this.addSingleLink(t,a,r,i):this.addSingleLink(t,a,r,void 0)}}updateLinkInterpolate(e,t){e.forEach(e=>{e==="default"?this.edges.defaultInterpolate=t:this.edges[e].interpolate=t})}updateLink(e,t){e.forEach(e=>{if(typeof e==`number`&&e>=this.edges.length)throw Error(`The index ${e} for linkStyle is out of bounds. Valid indices for linkStyle are between 0 and ${this.edges.length-1}. (Help: Ensure that the index is within the range of existing edges.)`);e==="default"?this.edges.defaultStyle=t:(this.edges[e].style=t,(this.edges[e]?.style?.length??0)>0&&!this.edges[e]?.style?.some(e=>e?.startsWith(`fill`))&&this.edges[e]?.style?.push(`fill:none`))})}addClass(e,t){let n=t.join().replace(/\\,/g,`§§§`).replace(/,/g,`;`).replace(/§§§/g,`,`).split(`;`);e.split(`,`).forEach(e=>{let t=this.classes.get(e);t===void 0&&(t={id:e,styles:[],textStyles:[]},this.classes.set(e,t)),n?.forEach(e=>{if(/color/.exec(e)){let n=e.replace(`fill`,`bgFill`);t.textStyles.push(n)}t.styles.push(e)})})}setDirection(e){this.direction=e.trim(),/.*/.exec(this.direction)&&(this.direction=`LR`),/.*v/.exec(this.direction)&&(this.direction=`TB`),this.direction===`TD`&&(this.direction=`TB`)}setClass(e,t){for(let n of e.split(`,`)){let e=this.vertices.get(n);e&&e.classes.push(t);let r=this.edges.find(e=>e.id===n);r&&r.classes.push(t);let i=this.subGraphLookup.get(n);i&&i.classes.push(t)}}setTooltip(e,t){if(t!==void 0){t=this.sanitizeText(t);for(let n of e.split(`,`))this.tooltips.set(this.version===`gen-1`?this.lookUpDomId(n):n,t)}}setClickFun(e,t,n){if(m().securityLevel!==`loose`||t===void 0)return;let r=[];if(typeof n==`string`){r=n.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(let e=0;e{let n=this.lookUpDomId(e),i=document.querySelector(`[id="${n}"]`);i!==null&&i.addEventListener(`click`,()=>{_.runFunc(t,...r)},!1)}))}setLink(e,t,n){e.split(`,`).forEach(e=>{let r=this.vertices.get(e);r!==void 0&&(r.link=_.formatUrl(t,this.config),r.linkTarget=n)}),this.setClass(e,`clickable`)}getTooltip(e){return this.tooltips.get(e)}setClickEvent(e,t,n){e.split(`,`).forEach(e=>{this.setClickFun(e,t,n)}),this.setClass(e,`clickable`)}bindFunctions(e){this.funs.forEach(t=>{t(e)})}getDirection(){return this.direction?.trim()}getVertices(){return this.vertices}getEdges(){return this.edges}getClasses(){return this.classes}setupToolTips(e){let t=re();n(e).select(`svg`).selectAll(`g.node`).on(`mouseover`,e=>{let i=n(e.currentTarget),a=i.attr(`title`);if(a===null)return;let o=e.currentTarget?.getBoundingClientRect();t.transition().duration(200).style(`opacity`,`.9`),t.text(i.attr(`title`)).style(`left`,window.scrollX+o.left+(o.right-o.left)/2+`px`).style(`top`,window.scrollY+o.bottom+`px`),t.html(r.sanitize(a)),i.classed(`hover`,!0)}).on(`mouseout`,e=>{t.transition().duration(500).style(`opacity`,0),n(e.currentTarget).classed(`hover`,!1)})}clear(e=`gen-2`){this.vertices=new Map,this.classes=new Map,this.edges=[],this.funs=[this.setupToolTips.bind(this)],this.diagramId=``,this.subGraphs=[],this.subGraphLookup=new Map,this.subCount=0,this.tooltips=new Map,this.firstGraphFlag=!0,this.version=e,this.config=m(),c()}setGen(e){this.version=e||`gen-2`}defaultStyle(){return`fill:#ffa;stroke: #f66; stroke-width: 3px; stroke-dasharray: 5, 5;fill:#ffa;stroke: #666;`}addSubGraph(n,r,i){let a=n.text.trim(),o=i.text;n===i&&/\s/.exec(i.text)&&(a=void 0);let s=e(e=>{let t={boolean:{},number:{},string:{}},n=[],r;return{nodeList:e.filter(function(e){let i=typeof e;return e.stmt&&e.stmt===`dir`?(r=e.value,!1):e.trim()===``?!1:i in t?t[i].hasOwnProperty(e)?!1:t[i][e]=!0:!n.includes(e)&&n.push(e)}),dir:r}},`uniq`)(r.flat()),c=s.nodeList,l=s.dir,u=l!==void 0,d=m().flowchart??{},f=l??(d.inheritDir?this.getDirection()??m().direction??void 0:void 0);if(this.version===`gen-1`)for(let e=0;e2e3)return{result:!1,count:0};if(this.posCrossRef[this.secCount]=t,this.subGraphs[t].id===e)return{result:!0,count:0};let r=0,i=1;for(;r=0){let n=this.indexNodes2(e,t);if(n.result)return{result:!0,count:i+n.count};i+=n.count}r+=1}return{result:!1,count:i}}getDepthFirstPos(e){return this.posCrossRef[e]}indexNodes(){this.secCount=-1,this.subGraphs.length>0&&this.indexNodes2(`none`,this.subGraphs.length-1)}getSubGraphs(){return this.subGraphs}firstGraph(){return this.firstGraphFlag?(this.firstGraphFlag=!1,!0):!1}destructStartLink(e){let t=e.trim(),n=`arrow_open`;switch(t[0]){case`<`:n=`arrow_point`,t=t.slice(1);break;case`x`:n=`arrow_cross`,t=t.slice(1);break;case`o`:n=`arrow_circle`,t=t.slice(1);break}let r=`normal`;return t.includes(`=`)&&(r=`thick`),t.includes(`.`)&&(r=`dotted`),{type:n,stroke:r}}countChar(e,t){let n=t.length,r=0;for(let i=0;i`:r=`arrow_point`,t.startsWith(`<`)&&(r=`double_`+r,n=n.slice(1));break;case`o`:r=`arrow_circle`,t.startsWith(`o`)&&(r=`double_`+r,n=n.slice(1));break}let i=`normal`,a=n.length-1;n.startsWith(`=`)&&(i=`thick`),n.startsWith(`~`)&&(i=`invisible`);let o=this.countChar(`.`,n);return o&&(i=`dotted`,a=o),{type:r,stroke:i,length:a}}destructLink(e,t){let n=this.destructEndLink(e),r;if(t){if(r=this.destructStartLink(t),r.stroke!==n.stroke)return{type:`INVALID`,stroke:`INVALID`};if(r.type===`arrow_open`)r.type=n.type;else{if(r.type!==n.type)return{type:`INVALID`,stroke:`INVALID`};r.type=`double_`+r.type}return r.type===`double_arrow`&&(r.type=`double_arrow_point`),r.length=n.length,r}return n}exists(e,t){for(let n of e)if(n.nodes.includes(t))return!0;return!1}makeUniq(e,t){let n=[];return e.nodes.forEach((r,i)=>{this.exists(t,r)||n.push(e.nodes[i])}),{nodes:n}}getTypeFromVertex(e){if(e.img)return`imageSquare`;if(e.icon)return e.form===`circle`?`iconCircle`:e.form===`square`?`iconSquare`:e.form===`rounded`?`iconRounded`:`icon`;switch(e.type){case`square`:case void 0:return`squareRect`;case`round`:return`roundedRect`;case`ellipse`:return`ellipse`;default:return e.type}}findNode(e,t){return e.find(e=>e.id===t)}destructEdgeType(e){let t=`none`,n=`arrow_point`;switch(e){case`arrow_point`:case`arrow_circle`:case`arrow_cross`:n=e;break;case`double_arrow_point`:case`double_arrow_circle`:case`double_arrow_cross`:t=e.replace(`double_`,``),n=t;break}return{arrowTypeStart:t,arrowTypeEnd:n}}addNodeFromVertex(e,t,n,r,i,a){let o=n.get(e.id),s=r.get(e.id)??!1,c=this.findNode(t,e.id);if(c)c.cssStyles=e.styles,c.cssCompiledStyles=this.getCompiledStyles(e.classes),c.cssClasses=e.classes.join(` `);else{let n={id:e.id,label:e.text,labelType:e.labelType,labelStyle:``,parentId:o,padding:i.flowchart?.padding||8,cssStyles:e.styles,cssCompiledStyles:this.getCompiledStyles([`default`,`node`,...e.classes]),cssClasses:`default `+e.classes.join(` `),dir:e.dir,domId:e.domId,look:a,link:e.link,linkTarget:e.linkTarget,tooltip:this.getTooltip(e.id),icon:e.icon,pos:e.pos,img:e.img,assetWidth:e.assetWidth,assetHeight:e.assetHeight,constraint:e.constraint};s?t.push({...n,isGroup:!0,shape:`rect`}):t.push({...n,isGroup:!1,shape:this.getTypeFromVertex(e)})}}getCompiledStyles(e){let t=[];for(let n of e){let e=this.classes.get(n);e?.styles&&(t=[...t,...e.styles??[]].map(e=>e.trim())),e?.textStyles&&(t=[...t,...e.textStyles??[]].map(e=>e.trim()))}return t}getData(){let e=m(),t=[],n=[],r=this.getSubGraphs(),i=new Map,a=new Map;for(let e=r.length-1;e>=0;e--){let t=r[e];t.nodes.length>0&&a.set(t.id,!0);for(let e of t.nodes)i.set(e,t.id)}for(let n=r.length-1;n>=0;n--){let a=r[n];t.push({id:a.id,label:a.title,labelStyle:``,labelType:a.labelType,parentId:i.get(a.id),padding:8,cssCompiledStyles:this.getCompiledStyles(a.classes),cssClasses:a.classes.join(` `),shape:`rect`,dir:a.dir===`TD`?`TB`:a.dir,explicitDir:a.hasExplicitDir,isGroup:!0,look:e.look})}this.getVertices().forEach(n=>{this.addNodeFromVertex(n,t,i,a,e,e.look||`classic`)});let o=this.getEdges();return o.forEach((t,r)=>{let{arrowTypeStart:i,arrowTypeEnd:a}=this.destructEdgeType(t.type),s=[...o.defaultStyle??[]];t.style&&s.push(...t.style);let c={id:g(t.start,t.end,{counter:r,prefix:`L`},t.id),isUserDefinedId:t.isUserDefinedId,start:t.start,end:t.end,type:t.type??`normal`,label:t.text,labelType:t.labelType,labelpos:`c`,thickness:t.stroke,minlen:t.length,classes:t?.stroke===`invisible`?``:`edge-thickness-normal edge-pattern-solid flowchart-link`,arrowTypeStart:t?.stroke===`invisible`||t?.type===`arrow_open`?`none`:i,arrowTypeEnd:t?.stroke===`invisible`||t?.type===`arrow_open`?`none`:a,arrowheadStyle:`fill: #333`,cssCompiledStyles:this.getCompiledStyles(t.classes),labelStyle:s,style:s,pattern:t.stroke,look:e.look,animate:t.animate,animation:t.animation,curve:t.interpolate||this.edges.defaultInterpolate||e.flowchart?.curve};n.push(c)}),{nodes:t,edges:n,other:{},config:e}}defaultConfig(){return l.flowchart}},D={getClasses:e(function(e,t){return t.db.getClasses()},`getClasses`),draw:e(async function(e,n,r,i,a){t.info(`REF0:`),t.info(`Drawing state diagram (v2)`,n);let{securityLevel:o,flowchart:s,layout:c}=m();i.db.setDiagramId(n),t.debug(`Before getData: `);let l=i.db.getData();t.debug(`Data: `,l);let u=v(n,o),d=i.db.getDirection();l.type=i.type,l.layoutAlgorithm=S(c),l.layoutAlgorithm===`dagre`&&c===`elk`&&t.warn("flowchart-elk was moved to an external package in Mermaid v11. Please refer [release notes](https://github.com/mermaid-js/mermaid/releases/tag/v11.0.0) for more details. This diagram will be rendered using `dagre` layout as a fallback."),l.direction=d,l.nodeSpacing=s?.nodeSpacing||50,l.rankSpacing=s?.rankSpacing||50,l.markers=[`point`,`circle`,`cross`],l.diagramId=n,t.debug(`REF1:`,l),await x(l,u,a);let f=l.config.flowchart?.diagramPadding??8;_.insertTitle(u,`flowchartTitleText`,s?.titleTopMargin||0,i.db.getDiagramTitle()),y(u,f,`flowchart`,s?.useMaxWidth||!1)},`draw`)},O=(function(){var t=e(function(e,t,n,r){for(n||={},r=e.length;r--;n[e[r]]=t);return n},`o`),n=[1,4],r=[1,3],i=[1,5],a=[1,8,9,10,11,27,34,36,38,44,60,84,85,86,87,88,89,102,105,106,109,111,114,115,116,121,122,123,124,125],o=[2,2],s=[1,13],c=[1,14],l=[1,15],u=[1,16],d=[1,23],f=[1,25],p=[1,26],ee=[1,27],m=[1,50],h=[1,49],te=[1,29],g=[1,30],_=[1,31],ne=[1,32],re=[1,33],v=[1,45],y=[1,47],b=[1,43],x=[1,48],S=[1,44],C=[1,51],w=[1,46],T=[1,52],E=[1,53],D=[1,34],O=[1,35],ie=[1,36],ae=[1,37],oe=[1,38],k=[1,58],A=[1,8,9,10,11,27,32,34,36,38,44,60,84,85,86,87,88,89,102,105,106,109,111,114,115,116,121,122,123,124,125],j=[1,62],M=[1,61],N=[1,63],se=[8,9,11,75,77,78],ce=[1,79],le=[1,92],ue=[1,97],de=[1,96],fe=[1,93],pe=[1,89],me=[1,95],he=[1,91],ge=[1,98],_e=[1,94],ve=[1,99],ye=[1,90],be=[8,9,10,11,40,75,77,78],P=[8,9,10,11,40,46,75,77,78],F=[8,9,10,11,29,40,44,46,48,50,52,54,56,58,60,63,65,67,68,70,75,77,78,89,102,105,106,109,111,114,115,116],xe=[8,9,11,44,60,75,77,78,89,102,105,106,109,111,114,115,116],Se=[44,60,89,102,105,106,109,111,114,115,116],Ce=[1,122],we=[1,123],Te=[1,125],Ee=[1,124],De=[44,60,62,74,89,102,105,106,109,111,114,115,116],Oe=[1,134],ke=[1,148],Ae=[1,149],je=[1,150],Me=[1,151],Ne=[1,136],Pe=[1,138],Fe=[1,142],Ie=[1,143],Le=[1,144],Re=[1,145],ze=[1,146],Be=[1,147],Ve=[1,152],He=[1,153],Ue=[1,132],We=[1,133],Ge=[1,140],Ke=[1,135],qe=[1,139],Je=[1,137],Ye=[8,9,10,11,27,32,34,36,38,44,60,84,85,86,87,88,89,102,105,106,109,111,114,115,116,121,122,123,124,125],Xe=[1,155],Ze=[1,157],I=[8,9,11],L=[8,9,10,11,14,44,60,89,105,106,109,111,114,115,116],R=[1,177],z=[1,173],B=[1,174],V=[1,178],H=[1,175],U=[1,176],Qe=[77,116,119],W=[8,9,10,11,12,14,27,29,32,44,60,75,84,85,86,87,88,89,90,105,109,111,114,115,116],$e=[10,106],et=[31,49,51,53,55,57,62,64,66,67,69,71,116,117,118],G=[1,248],K=[1,246],q=[1,250],J=[1,244],Y=[1,245],X=[1,247],Z=[1,249],Q=[1,251],tt=[1,269],nt=[8,9,11,106],$=[8,9,10,11,60,84,105,106,109,110,111,112],rt={trace:e(function(){},`trace`),yy:{},symbols_:{error:2,start:3,graphConfig:4,document:5,line:6,statement:7,SEMI:8,NEWLINE:9,SPACE:10,EOF:11,GRAPH:12,NODIR:13,DIR:14,FirstStmtSeparator:15,ending:16,endToken:17,spaceList:18,spaceListNewline:19,vertexStatement:20,separator:21,styleStatement:22,linkStyleStatement:23,classDefStatement:24,classStatement:25,clickStatement:26,subgraph:27,textNoTags:28,SQS:29,text:30,SQE:31,end:32,direction:33,acc_title:34,acc_title_value:35,acc_descr:36,acc_descr_value:37,acc_descr_multiline_value:38,shapeData:39,SHAPE_DATA:40,link:41,node:42,styledVertex:43,AMP:44,vertex:45,STYLE_SEPARATOR:46,idString:47,DOUBLECIRCLESTART:48,DOUBLECIRCLEEND:49,PS:50,PE:51,"(-":52,"-)":53,STADIUMSTART:54,STADIUMEND:55,SUBROUTINESTART:56,SUBROUTINEEND:57,VERTEX_WITH_PROPS_START:58,"NODE_STRING[field]":59,COLON:60,"NODE_STRING[value]":61,PIPE:62,CYLINDERSTART:63,CYLINDEREND:64,DIAMOND_START:65,DIAMOND_STOP:66,TAGEND:67,TRAPSTART:68,TRAPEND:69,INVTRAPSTART:70,INVTRAPEND:71,linkStatement:72,arrowText:73,TESTSTR:74,START_LINK:75,edgeText:76,LINK:77,LINK_ID:78,edgeTextToken:79,STR:80,MD_STR:81,textToken:82,keywords:83,STYLE:84,LINKSTYLE:85,CLASSDEF:86,CLASS:87,CLICK:88,DOWN:89,UP:90,textNoTagsToken:91,stylesOpt:92,"idString[vertex]":93,"idString[class]":94,CALLBACKNAME:95,CALLBACKARGS:96,HREF:97,LINK_TARGET:98,"STR[link]":99,"STR[tooltip]":100,alphaNum:101,DEFAULT:102,numList:103,INTERPOLATE:104,NUM:105,COMMA:106,style:107,styleComponent:108,NODE_STRING:109,UNIT:110,BRKT:111,PCT:112,idStringToken:113,MINUS:114,MULT:115,UNICODE_TEXT:116,TEXT:117,TAGSTART:118,EDGE_TEXT:119,alphaNumToken:120,direction_tb:121,direction_bt:122,direction_rl:123,direction_lr:124,direction_td:125,$accept:0,$end:1},terminals_:{2:`error`,8:`SEMI`,9:`NEWLINE`,10:`SPACE`,11:`EOF`,12:`GRAPH`,13:`NODIR`,14:`DIR`,27:`subgraph`,29:`SQS`,31:`SQE`,32:`end`,34:`acc_title`,35:`acc_title_value`,36:`acc_descr`,37:`acc_descr_value`,38:`acc_descr_multiline_value`,40:`SHAPE_DATA`,44:`AMP`,46:`STYLE_SEPARATOR`,48:`DOUBLECIRCLESTART`,49:`DOUBLECIRCLEEND`,50:`PS`,51:`PE`,52:`(-`,53:`-)`,54:`STADIUMSTART`,55:`STADIUMEND`,56:`SUBROUTINESTART`,57:`SUBROUTINEEND`,58:`VERTEX_WITH_PROPS_START`,59:`NODE_STRING[field]`,60:`COLON`,61:`NODE_STRING[value]`,62:`PIPE`,63:`CYLINDERSTART`,64:`CYLINDEREND`,65:`DIAMOND_START`,66:`DIAMOND_STOP`,67:`TAGEND`,68:`TRAPSTART`,69:`TRAPEND`,70:`INVTRAPSTART`,71:`INVTRAPEND`,74:`TESTSTR`,75:`START_LINK`,77:`LINK`,78:`LINK_ID`,80:`STR`,81:`MD_STR`,84:`STYLE`,85:`LINKSTYLE`,86:`CLASSDEF`,87:`CLASS`,88:`CLICK`,89:`DOWN`,90:`UP`,93:`idString[vertex]`,94:`idString[class]`,95:`CALLBACKNAME`,96:`CALLBACKARGS`,97:`HREF`,98:`LINK_TARGET`,99:`STR[link]`,100:`STR[tooltip]`,102:`DEFAULT`,104:`INTERPOLATE`,105:`NUM`,106:`COMMA`,109:`NODE_STRING`,110:`UNIT`,111:`BRKT`,112:`PCT`,114:`MINUS`,115:`MULT`,116:`UNICODE_TEXT`,117:`TEXT`,118:`TAGSTART`,119:`EDGE_TEXT`,121:`direction_tb`,122:`direction_bt`,123:`direction_rl`,124:`direction_lr`,125:`direction_td`},productions_:[0,[3,2],[5,0],[5,2],[6,1],[6,1],[6,1],[6,1],[6,1],[4,2],[4,2],[4,2],[4,3],[16,2],[16,1],[17,1],[17,1],[17,1],[15,1],[15,1],[15,2],[19,2],[19,2],[19,1],[19,1],[18,2],[18,1],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,9],[7,6],[7,4],[7,1],[7,2],[7,2],[7,1],[21,1],[21,1],[21,1],[39,2],[39,1],[20,4],[20,3],[20,4],[20,2],[20,2],[20,1],[42,1],[42,6],[42,5],[43,1],[43,3],[45,4],[45,4],[45,6],[45,4],[45,4],[45,4],[45,8],[45,4],[45,4],[45,4],[45,6],[45,4],[45,4],[45,4],[45,4],[45,4],[45,1],[41,2],[41,3],[41,3],[41,1],[41,3],[41,4],[76,1],[76,2],[76,1],[76,1],[72,1],[72,2],[73,3],[30,1],[30,2],[30,1],[30,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[28,1],[28,2],[28,1],[28,1],[24,5],[25,5],[26,2],[26,4],[26,3],[26,5],[26,3],[26,5],[26,5],[26,7],[26,2],[26,4],[26,2],[26,4],[26,4],[26,6],[22,5],[23,5],[23,5],[23,9],[23,9],[23,7],[23,7],[103,1],[103,3],[92,1],[92,3],[107,1],[107,2],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[82,1],[82,1],[82,1],[82,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[79,1],[79,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[47,1],[47,2],[101,1],[101,2],[33,1],[33,1],[33,1],[33,1],[33,1]],performAction:e(function(e,t,n,r,i,a,o){var s=a.length-1;switch(i){case 2:this.$=[];break;case 3:(!Array.isArray(a[s])||a[s].length>0)&&a[s-1].push(a[s]),this.$=a[s-1];break;case 4:case 183:this.$=a[s];break;case 11:r.setDirection(`TB`),this.$=`TB`;break;case 12:r.setDirection(a[s-1]),this.$=a[s-1];break;case 27:this.$=a[s-1].nodes;break;case 28:case 29:case 30:case 31:case 32:this.$=[];break;case 33:this.$=r.addSubGraph(a[s-6],a[s-1],a[s-4]);break;case 34:this.$=r.addSubGraph(a[s-3],a[s-1],a[s-3]);break;case 35:this.$=r.addSubGraph(void 0,a[s-1],void 0);break;case 37:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 38:case 39:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 43:this.$=a[s-1]+a[s];break;case 44:this.$=a[s];break;case 45:r.addVertex(a[s-1][a[s-1].length-1],void 0,void 0,void 0,void 0,void 0,void 0,a[s]),r.addLink(a[s-3].stmt,a[s-1],a[s-2]),this.$={stmt:a[s-1],nodes:a[s-1].concat(a[s-3].nodes)};break;case 46:r.addLink(a[s-2].stmt,a[s],a[s-1]),this.$={stmt:a[s],nodes:a[s].concat(a[s-2].nodes)};break;case 47:r.addLink(a[s-3].stmt,a[s-1],a[s-2]),this.$={stmt:a[s-1],nodes:a[s-1].concat(a[s-3].nodes)};break;case 48:this.$={stmt:a[s-1],nodes:a[s-1]};break;case 49:r.addVertex(a[s-1][a[s-1].length-1],void 0,void 0,void 0,void 0,void 0,void 0,a[s]),this.$={stmt:a[s-1],nodes:a[s-1],shapeData:a[s]};break;case 50:this.$={stmt:a[s],nodes:a[s]};break;case 51:this.$=[a[s]];break;case 52:r.addVertex(a[s-5][a[s-5].length-1],void 0,void 0,void 0,void 0,void 0,void 0,a[s-4]),this.$=a[s-5].concat(a[s]);break;case 53:this.$=a[s-4].concat(a[s]);break;case 54:this.$=a[s];break;case 55:this.$=a[s-2],r.setClass(a[s-2],a[s]);break;case 56:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`square`);break;case 57:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`doublecircle`);break;case 58:this.$=a[s-5],r.addVertex(a[s-5],a[s-2],`circle`);break;case 59:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`ellipse`);break;case 60:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`stadium`);break;case 61:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`subroutine`);break;case 62:this.$=a[s-7],r.addVertex(a[s-7],a[s-1],`rect`,void 0,void 0,void 0,Object.fromEntries([[a[s-5],a[s-3]]]));break;case 63:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`cylinder`);break;case 64:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`round`);break;case 65:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`diamond`);break;case 66:this.$=a[s-5],r.addVertex(a[s-5],a[s-2],`hexagon`);break;case 67:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`odd`);break;case 68:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`trapezoid`);break;case 69:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`inv_trapezoid`);break;case 70:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`lean_right`);break;case 71:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],`lean_left`);break;case 72:this.$=a[s],r.addVertex(a[s]);break;case 73:a[s-1].text=a[s],this.$=a[s-1];break;case 74:case 75:a[s-2].text=a[s-1],this.$=a[s-2];break;case 76:this.$=a[s];break;case 77:var c=r.destructLink(a[s],a[s-2]);this.$={type:c.type,stroke:c.stroke,length:c.length,text:a[s-1]};break;case 78:var c=r.destructLink(a[s],a[s-2]);this.$={type:c.type,stroke:c.stroke,length:c.length,text:a[s-1],id:a[s-3]};break;case 79:this.$={text:a[s],type:`text`};break;case 80:this.$={text:a[s-1].text+``+a[s],type:a[s-1].type};break;case 81:this.$={text:a[s],type:`string`};break;case 82:this.$={text:a[s],type:`markdown`};break;case 83:var c=r.destructLink(a[s]);this.$={type:c.type,stroke:c.stroke,length:c.length};break;case 84:var c=r.destructLink(a[s]);this.$={type:c.type,stroke:c.stroke,length:c.length,id:a[s-1]};break;case 85:this.$=a[s-1];break;case 86:this.$={text:a[s],type:`text`};break;case 87:this.$={text:a[s-1].text+``+a[s],type:a[s-1].type};break;case 88:this.$={text:a[s],type:`string`};break;case 89:case 104:this.$={text:a[s],type:`markdown`};break;case 101:this.$={text:a[s],type:`text`};break;case 102:this.$={text:a[s-1].text+``+a[s],type:a[s-1].type};break;case 103:this.$={text:a[s],type:`text`};break;case 105:this.$=a[s-4],r.addClass(a[s-2],a[s]);break;case 106:this.$=a[s-4],r.setClass(a[s-2],a[s]);break;case 107:case 115:this.$=a[s-1],r.setClickEvent(a[s-1],a[s]);break;case 108:case 116:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-2]),r.setTooltip(a[s-3],a[s]);break;case 109:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 110:this.$=a[s-4],r.setClickEvent(a[s-4],a[s-3],a[s-2]),r.setTooltip(a[s-4],a[s]);break;case 111:this.$=a[s-2],r.setLink(a[s-2],a[s]);break;case 112:this.$=a[s-4],r.setLink(a[s-4],a[s-2]),r.setTooltip(a[s-4],a[s]);break;case 113:this.$=a[s-4],r.setLink(a[s-4],a[s-2],a[s]);break;case 114:this.$=a[s-6],r.setLink(a[s-6],a[s-4],a[s]),r.setTooltip(a[s-6],a[s-2]);break;case 117:this.$=a[s-1],r.setLink(a[s-1],a[s]);break;case 118:this.$=a[s-3],r.setLink(a[s-3],a[s-2]),r.setTooltip(a[s-3],a[s]);break;case 119:this.$=a[s-3],r.setLink(a[s-3],a[s-2],a[s]);break;case 120:this.$=a[s-5],r.setLink(a[s-5],a[s-4],a[s]),r.setTooltip(a[s-5],a[s-2]);break;case 121:this.$=a[s-4],r.addVertex(a[s-2],void 0,void 0,a[s]);break;case 122:this.$=a[s-4],r.updateLink([a[s-2]],a[s]);break;case 123:this.$=a[s-4],r.updateLink(a[s-2],a[s]);break;case 124:this.$=a[s-8],r.updateLinkInterpolate([a[s-6]],a[s-2]),r.updateLink([a[s-6]],a[s]);break;case 125:this.$=a[s-8],r.updateLinkInterpolate(a[s-6],a[s-2]),r.updateLink(a[s-6],a[s]);break;case 126:this.$=a[s-6],r.updateLinkInterpolate([a[s-4]],a[s]);break;case 127:this.$=a[s-6],r.updateLinkInterpolate(a[s-4],a[s]);break;case 128:case 130:this.$=[a[s]];break;case 129:case 131:a[s-2].push(a[s]),this.$=a[s-2];break;case 133:this.$=a[s-1]+a[s];break;case 181:this.$=a[s];break;case 182:this.$=a[s-1]+``+a[s];break;case 184:this.$=a[s-1]+``+a[s];break;case 185:this.$={stmt:`dir`,value:`TB`};break;case 186:this.$={stmt:`dir`,value:`BT`};break;case 187:this.$={stmt:`dir`,value:`RL`};break;case 188:this.$={stmt:`dir`,value:`LR`};break;case 189:this.$={stmt:`dir`,value:`TD`};break}},`anonymous`),table:[{3:1,4:2,9:n,10:r,12:i},{1:[3]},t(a,o,{5:6}),{4:7,9:n,10:r,12:i},{4:8,9:n,10:r,12:i},{13:[1,9],14:[1,10]},{1:[2,1],6:11,7:12,8:s,9:c,10:l,11:u,20:17,22:18,23:19,24:20,25:21,26:22,27:d,33:24,34:f,36:p,38:ee,42:28,43:39,44:m,45:40,47:41,60:h,84:te,85:g,86:_,87:ne,88:re,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E,121:D,122:O,123:ie,124:ae,125:oe},t(a,[2,9]),t(a,[2,10]),t(a,[2,11]),{8:[1,55],9:[1,56],10:k,15:54,18:57},t(A,[2,3]),t(A,[2,4]),t(A,[2,5]),t(A,[2,6]),t(A,[2,7]),t(A,[2,8]),{8:j,9:M,11:N,21:59,41:60,72:64,75:[1,65],77:[1,67],78:[1,66]},{8:j,9:M,11:N,21:68},{8:j,9:M,11:N,21:69},{8:j,9:M,11:N,21:70},{8:j,9:M,11:N,21:71},{8:j,9:M,11:N,21:72},{8:j,9:M,10:[1,73],11:N,21:74},t(A,[2,36]),{35:[1,75]},{37:[1,76]},t(A,[2,39]),t(se,[2,50],{18:77,39:78,10:k,40:ce}),{10:[1,80]},{10:[1,81]},{10:[1,82]},{10:[1,83]},{14:le,44:ue,60:de,80:[1,87],89:fe,95:[1,84],97:[1,85],101:86,105:pe,106:me,109:he,111:ge,114:_e,115:ve,116:ye,120:88},t(A,[2,185]),t(A,[2,186]),t(A,[2,187]),t(A,[2,188]),t(A,[2,189]),t(be,[2,51]),t(be,[2,54],{46:[1,100]}),t(P,[2,72],{113:113,29:[1,101],44:m,48:[1,102],50:[1,103],52:[1,104],54:[1,105],56:[1,106],58:[1,107],60:h,63:[1,108],65:[1,109],67:[1,110],68:[1,111],70:[1,112],89:v,102:y,105:b,106:x,109:S,111:C,114:w,115:T,116:E}),t(F,[2,181]),t(F,[2,142]),t(F,[2,143]),t(F,[2,144]),t(F,[2,145]),t(F,[2,146]),t(F,[2,147]),t(F,[2,148]),t(F,[2,149]),t(F,[2,150]),t(F,[2,151]),t(F,[2,152]),t(a,[2,12]),t(a,[2,18]),t(a,[2,19]),{9:[1,114]},t(xe,[2,26],{18:115,10:k}),t(A,[2,27]),{42:116,43:39,44:m,45:40,47:41,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E},t(A,[2,40]),t(A,[2,41]),t(A,[2,42]),t(Se,[2,76],{73:117,62:[1,119],74:[1,118]}),{76:120,79:121,80:Ce,81:we,116:Te,119:Ee},{75:[1,126],77:[1,127]},t(De,[2,83]),t(A,[2,28]),t(A,[2,29]),t(A,[2,30]),t(A,[2,31]),t(A,[2,32]),{10:Oe,12:ke,14:Ae,27:je,28:128,32:Me,44:Ne,60:Pe,75:Fe,80:[1,130],81:[1,131],83:141,84:Ie,85:Le,86:Re,87:ze,88:Be,89:Ve,90:He,91:129,105:Ue,109:We,111:Ge,114:Ke,115:qe,116:Je},t(Ye,o,{5:154}),t(A,[2,37]),t(A,[2,38]),t(se,[2,48],{44:Xe}),t(se,[2,49],{18:156,10:k,40:Ze}),t(be,[2,44]),{44:m,47:158,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E},{102:[1,159],103:160,105:[1,161]},{44:m,47:162,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E},{44:m,47:163,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E},t(I,[2,107],{10:[1,164],96:[1,165]}),{80:[1,166]},t(I,[2,115],{120:168,10:[1,167],14:le,44:ue,60:de,89:fe,105:pe,106:me,109:he,111:ge,114:_e,115:ve,116:ye}),t(I,[2,117],{10:[1,169]}),t(L,[2,183]),t(L,[2,170]),t(L,[2,171]),t(L,[2,172]),t(L,[2,173]),t(L,[2,174]),t(L,[2,175]),t(L,[2,176]),t(L,[2,177]),t(L,[2,178]),t(L,[2,179]),t(L,[2,180]),{44:m,47:170,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E},{30:171,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{30:179,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{30:181,50:[1,180],67:R,80:z,81:B,82:172,116:V,117:H,118:U},{30:182,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{30:183,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{30:184,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{109:[1,185]},{30:186,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{30:187,65:[1,188],67:R,80:z,81:B,82:172,116:V,117:H,118:U},{30:189,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{30:190,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{30:191,67:R,80:z,81:B,82:172,116:V,117:H,118:U},t(F,[2,182]),t(a,[2,20]),t(xe,[2,25]),t(se,[2,46],{39:192,18:193,10:k,40:ce}),t(Se,[2,73],{10:[1,194]}),{10:[1,195]},{30:196,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{77:[1,197],79:198,116:Te,119:Ee},t(Qe,[2,79]),t(Qe,[2,81]),t(Qe,[2,82]),t(Qe,[2,168]),t(Qe,[2,169]),{76:199,79:121,80:Ce,81:we,116:Te,119:Ee},t(De,[2,84]),{8:j,9:M,10:Oe,11:N,12:ke,14:Ae,21:201,27:je,29:[1,200],32:Me,44:Ne,60:Pe,75:Fe,83:141,84:Ie,85:Le,86:Re,87:ze,88:Be,89:Ve,90:He,91:202,105:Ue,109:We,111:Ge,114:Ke,115:qe,116:Je},t(W,[2,101]),t(W,[2,103]),t(W,[2,104]),t(W,[2,157]),t(W,[2,158]),t(W,[2,159]),t(W,[2,160]),t(W,[2,161]),t(W,[2,162]),t(W,[2,163]),t(W,[2,164]),t(W,[2,165]),t(W,[2,166]),t(W,[2,167]),t(W,[2,90]),t(W,[2,91]),t(W,[2,92]),t(W,[2,93]),t(W,[2,94]),t(W,[2,95]),t(W,[2,96]),t(W,[2,97]),t(W,[2,98]),t(W,[2,99]),t(W,[2,100]),{6:11,7:12,8:s,9:c,10:l,11:u,20:17,22:18,23:19,24:20,25:21,26:22,27:d,32:[1,203],33:24,34:f,36:p,38:ee,42:28,43:39,44:m,45:40,47:41,60:h,84:te,85:g,86:_,87:ne,88:re,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E,121:D,122:O,123:ie,124:ae,125:oe},{10:k,18:204},{44:[1,205]},t(be,[2,43]),{10:[1,206],44:m,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:113,114:w,115:T,116:E},{10:[1,207]},{10:[1,208],106:[1,209]},t($e,[2,128]),{10:[1,210],44:m,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:113,114:w,115:T,116:E},{10:[1,211],44:m,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:113,114:w,115:T,116:E},{80:[1,212]},t(I,[2,109],{10:[1,213]}),t(I,[2,111],{10:[1,214]}),{80:[1,215]},t(L,[2,184]),{80:[1,216],98:[1,217]},t(be,[2,55],{113:113,44:m,60:h,89:v,102:y,105:b,106:x,109:S,111:C,114:w,115:T,116:E}),{31:[1,218],67:R,82:219,116:V,117:H,118:U},t(et,[2,86]),t(et,[2,88]),t(et,[2,89]),t(et,[2,153]),t(et,[2,154]),t(et,[2,155]),t(et,[2,156]),{49:[1,220],67:R,82:219,116:V,117:H,118:U},{30:221,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{51:[1,222],67:R,82:219,116:V,117:H,118:U},{53:[1,223],67:R,82:219,116:V,117:H,118:U},{55:[1,224],67:R,82:219,116:V,117:H,118:U},{57:[1,225],67:R,82:219,116:V,117:H,118:U},{60:[1,226]},{64:[1,227],67:R,82:219,116:V,117:H,118:U},{66:[1,228],67:R,82:219,116:V,117:H,118:U},{30:229,67:R,80:z,81:B,82:172,116:V,117:H,118:U},{31:[1,230],67:R,82:219,116:V,117:H,118:U},{67:R,69:[1,231],71:[1,232],82:219,116:V,117:H,118:U},{67:R,69:[1,234],71:[1,233],82:219,116:V,117:H,118:U},t(se,[2,45],{18:156,10:k,40:Ze}),t(se,[2,47],{44:Xe}),t(Se,[2,75]),t(Se,[2,74]),{62:[1,235],67:R,82:219,116:V,117:H,118:U},t(Se,[2,77]),t(Qe,[2,80]),{77:[1,236],79:198,116:Te,119:Ee},{30:237,67:R,80:z,81:B,82:172,116:V,117:H,118:U},t(Ye,o,{5:238}),t(W,[2,102]),t(A,[2,35]),{43:239,44:m,45:40,47:41,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E},{10:k,18:240},{10:G,60:K,84:q,92:241,105:J,107:242,108:243,109:Y,110:X,111:Z,112:Q},{10:G,60:K,84:q,92:252,104:[1,253],105:J,107:242,108:243,109:Y,110:X,111:Z,112:Q},{10:G,60:K,84:q,92:254,104:[1,255],105:J,107:242,108:243,109:Y,110:X,111:Z,112:Q},{105:[1,256]},{10:G,60:K,84:q,92:257,105:J,107:242,108:243,109:Y,110:X,111:Z,112:Q},{44:m,47:258,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E},t(I,[2,108]),{80:[1,259]},{80:[1,260],98:[1,261]},t(I,[2,116]),t(I,[2,118],{10:[1,262]}),t(I,[2,119]),t(P,[2,56]),t(et,[2,87]),t(P,[2,57]),{51:[1,263],67:R,82:219,116:V,117:H,118:U},t(P,[2,64]),t(P,[2,59]),t(P,[2,60]),t(P,[2,61]),{109:[1,264]},t(P,[2,63]),t(P,[2,65]),{66:[1,265],67:R,82:219,116:V,117:H,118:U},t(P,[2,67]),t(P,[2,68]),t(P,[2,70]),t(P,[2,69]),t(P,[2,71]),t([10,44,60,89,102,105,106,109,111,114,115,116],[2,85]),t(Se,[2,78]),{31:[1,266],67:R,82:219,116:V,117:H,118:U},{6:11,7:12,8:s,9:c,10:l,11:u,20:17,22:18,23:19,24:20,25:21,26:22,27:d,32:[1,267],33:24,34:f,36:p,38:ee,42:28,43:39,44:m,45:40,47:41,60:h,84:te,85:g,86:_,87:ne,88:re,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E,121:D,122:O,123:ie,124:ae,125:oe},t(be,[2,53]),{43:268,44:m,45:40,47:41,60:h,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E},t(I,[2,121],{106:tt}),t(nt,[2,130],{108:270,10:G,60:K,84:q,105:J,109:Y,110:X,111:Z,112:Q}),t($,[2,132]),t($,[2,134]),t($,[2,135]),t($,[2,136]),t($,[2,137]),t($,[2,138]),t($,[2,139]),t($,[2,140]),t($,[2,141]),t(I,[2,122],{106:tt}),{10:[1,271]},t(I,[2,123],{106:tt}),{10:[1,272]},t($e,[2,129]),t(I,[2,105],{106:tt}),t(I,[2,106],{113:113,44:m,60:h,89:v,102:y,105:b,106:x,109:S,111:C,114:w,115:T,116:E}),t(I,[2,110]),t(I,[2,112],{10:[1,273]}),t(I,[2,113]),{98:[1,274]},{51:[1,275]},{62:[1,276]},{66:[1,277]},{8:j,9:M,11:N,21:278},t(A,[2,34]),t(be,[2,52]),{10:G,60:K,84:q,105:J,107:279,108:243,109:Y,110:X,111:Z,112:Q},t($,[2,133]),{14:le,44:ue,60:de,89:fe,101:280,105:pe,106:me,109:he,111:ge,114:_e,115:ve,116:ye,120:88},{14:le,44:ue,60:de,89:fe,101:281,105:pe,106:me,109:he,111:ge,114:_e,115:ve,116:ye,120:88},{98:[1,282]},t(I,[2,120]),t(P,[2,58]),{30:283,67:R,80:z,81:B,82:172,116:V,117:H,118:U},t(P,[2,66]),t(Ye,o,{5:284}),t(nt,[2,131],{108:270,10:G,60:K,84:q,105:J,109:Y,110:X,111:Z,112:Q}),t(I,[2,126],{120:168,10:[1,285],14:le,44:ue,60:de,89:fe,105:pe,106:me,109:he,111:ge,114:_e,115:ve,116:ye}),t(I,[2,127],{120:168,10:[1,286],14:le,44:ue,60:de,89:fe,105:pe,106:me,109:he,111:ge,114:_e,115:ve,116:ye}),t(I,[2,114]),{31:[1,287],67:R,82:219,116:V,117:H,118:U},{6:11,7:12,8:s,9:c,10:l,11:u,20:17,22:18,23:19,24:20,25:21,26:22,27:d,32:[1,288],33:24,34:f,36:p,38:ee,42:28,43:39,44:m,45:40,47:41,60:h,84:te,85:g,86:_,87:ne,88:re,89:v,102:y,105:b,106:x,109:S,111:C,113:42,114:w,115:T,116:E,121:D,122:O,123:ie,124:ae,125:oe},{10:G,60:K,84:q,92:289,105:J,107:242,108:243,109:Y,110:X,111:Z,112:Q},{10:G,60:K,84:q,92:290,105:J,107:242,108:243,109:Y,110:X,111:Z,112:Q},t(P,[2,62]),t(A,[2,33]),t(I,[2,124],{106:tt}),t(I,[2,125],{106:tt})],defaultActions:{},parseError:e(function(e,t){if(t.recoverable)this.trace(e);else{var n=Error(e);throw n.hash=t,n}},`parseError`),parse:e(function(t){var n=this,r=[0],i=[],a=[null],o=[],s=this.table,c=``,l=0,u=0,d=0,f=2,p=1,ee=o.slice.call(arguments,1),m=Object.create(this.lexer),h={yy:{}};for(var te in this.yy)Object.prototype.hasOwnProperty.call(this.yy,te)&&(h.yy[te]=this.yy[te]);m.setInput(t,h.yy),h.yy.lexer=m,h.yy.parser=this,m.yylloc===void 0&&(m.yylloc={});var g=m.yylloc;o.push(g);var _=m.options&&m.options.ranges;typeof h.yy.parseError==`function`?this.parseError=h.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function ne(e){r.length-=2*e,a.length-=e,o.length-=e}e(ne,`popStack`);function re(){var e=i.pop()||m.lex()||p;return typeof e!=`number`&&(e instanceof Array&&(i=e,e=i.pop()),e=n.symbols_[e]||e),e}e(re,`lex`);for(var v,y,b,x,S,C={},w,T,E,D;;){if(b=r[r.length-1],this.defaultActions[b]?x=this.defaultActions[b]:(v??=re(),x=s[b]&&s[b][v]),x===void 0||!x.length||!x[0]){var O=``;for(w in D=[],s[b])this.terminals_[w]&&w>f&&D.push(`'`+this.terminals_[w]+`'`);O=m.showPosition?`Parse error on line `+(l+1)+`: +`+m.showPosition()+` +Expecting `+D.join(`, `)+`, got '`+(this.terminals_[v]||v)+`'`:`Parse error on line `+(l+1)+`: Unexpected `+(v==p?`end of input`:`'`+(this.terminals_[v]||v)+`'`),this.parseError(O,{text:m.match,token:this.terminals_[v]||v,line:m.yylineno,loc:g,expected:D})}if(x[0]instanceof Array&&x.length>1)throw Error(`Parse Error: multiple actions possible at state: `+b+`, token: `+v);switch(x[0]){case 1:r.push(v),a.push(m.yytext),o.push(m.yylloc),r.push(x[1]),v=null,y?(v=y,y=null):(u=m.yyleng,c=m.yytext,l=m.yylineno,g=m.yylloc,d>0&&d--);break;case 2:if(T=this.productions_[x[1]][1],C.$=a[a.length-T],C._$={first_line:o[o.length-(T||1)].first_line,last_line:o[o.length-1].last_line,first_column:o[o.length-(T||1)].first_column,last_column:o[o.length-1].last_column},_&&(C._$.range=[o[o.length-(T||1)].range[0],o[o.length-1].range[1]]),S=this.performAction.apply(C,[c,u,l,h.yy,x[1],a,o].concat(ee)),S!==void 0)return S;T&&(r=r.slice(0,-1*T*2),a=a.slice(0,-1*T),o=o.slice(0,-1*T)),r.push(this.productions_[x[1]][0]),a.push(C.$),o.push(C._$),E=s[r[r.length-2]][r[r.length-1]],r.push(E);break;case 3:return!0}}return!0},`parse`)};rt.lexer=(function(){return{EOF:1,parseError:e(function(e,t){if(this.yy.parser)this.yy.parser.parseError(e,t);else throw Error(e)},`parseError`),setInput:e(function(e,t){return this.yy=t||this.yy||{},this._input=e,this._more=this._backtrack=this.done=!1,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},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},`setInput`),input:e(function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},`input`),unput:e(function(e){var t=e.length,n=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t),this.offset-=t;var r=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),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},`unput`),more:e(function(){return this._more=!0,this},`more`),reject:e(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError(`Lexical error on line `+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:``,token:null,line:this.yylineno});return this},`reject`),less:e(function(e){this.unput(this.match.slice(e))},`less`),pastInput:e(function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?`...`:``)+e.substr(-20).replace(/\n/g,``)},`pastInput`),upcomingInput:e(function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?`...`:``)).replace(/\n/g,``)},`upcomingInput`),showPosition:e(function(){var e=this.pastInput(),t=Array(e.length+1).join(`-`);return e+this.upcomingInput()+` +`+t+`^`},`showPosition`),test_match:e(function(e,t){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),r=e[0].match(/(?:\r\n?|\n).*/g),r&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],n=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},`test_match`),next:e(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var e,t,n,r;this._more||(this.yytext=``,this.match=``);for(var i=this._currentRules(),a=0;at[0].length)){if(t=n,r=a,this.options.backtrack_lexer){if(e=this.test_match(n,i[a]),e!==!1)return e;if(this._backtrack){t=!1;continue}else return!1}else if(!this.options.flex)break}return t?(e=this.test_match(t,i[r]),e!==!1&&e):this._input===``?this.EOF:this.parseError(`Lexical error on line `+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:``,token:null,line:this.yylineno})},`next`),lex:e(function(){return this.next()||this.lex()},`lex`),begin:e(function(e){this.conditionStack.push(e)},`begin`),popState:e(function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},`popState`),_currentRules:e(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},`_currentRules`),topState:e(function(e){return e=this.conditionStack.length-1-Math.abs(e||0),e>=0?this.conditionStack[e]:`INITIAL`},`topState`),pushState:e(function(e){this.begin(e)},`pushState`),stateStackSize:e(function(){return this.conditionStack.length},`stateStackSize`),options:{},performAction:e(function(e,t,n,r){switch(n){case 0:return this.begin(`acc_title`),34;case 1:return this.popState(),`acc_title_value`;case 2:return this.begin(`acc_descr`),36;case 3:return this.popState(),`acc_descr_value`;case 4:this.begin(`acc_descr_multiline`);break;case 5:this.popState();break;case 6:return`acc_descr_multiline_value`;case 7:return this.pushState(`shapeData`),t.yytext=``,40;case 8:return this.pushState(`shapeDataStr`),40;case 9:return this.popState(),40;case 10:return t.yytext=t.yytext.replace(/\n\s*/g,`
    `),40;case 11:return 40;case 12:this.popState();break;case 13:this.begin(`callbackname`);break;case 14:this.popState();break;case 15:this.popState(),this.begin(`callbackargs`);break;case 16:return 95;case 17:this.popState();break;case 18:return 96;case 19:return`MD_STR`;case 20:this.popState();break;case 21:this.begin(`md_string`);break;case 22:return`STR`;case 23:this.popState();break;case 24:this.pushState(`string`);break;case 25:return 84;case 26:return 102;case 27:return 85;case 28:return 104;case 29:return 86;case 30:return 87;case 31:return 97;case 32:this.begin(`click`);break;case 33:this.popState();break;case 34:return 88;case 35:return e.lex.firstGraph()&&this.begin(`dir`),12;case 36:return e.lex.firstGraph()&&this.begin(`dir`),12;case 37:return e.lex.firstGraph()&&this.begin(`dir`),12;case 38:return e.lex.firstGraph()&&this.begin(`dir`),12;case 39:return 27;case 40:return 32;case 41:return 98;case 42:return 98;case 43:return 98;case 44:return 98;case 45:return this.popState(),13;case 46:return this.popState(),14;case 47:return this.popState(),14;case 48:return this.popState(),14;case 49:return this.popState(),14;case 50:return this.popState(),14;case 51:return this.popState(),14;case 52:return this.popState(),14;case 53:return this.popState(),14;case 54:return this.popState(),14;case 55:return this.popState(),14;case 56:return 121;case 57:return 122;case 58:return 123;case 59:return 124;case 60:return 125;case 61:return 78;case 62:return 105;case 63:return 111;case 64:return 46;case 65:return 60;case 66:return 44;case 67:return 8;case 68:return 106;case 69:return 115;case 70:return this.popState(),77;case 71:return this.pushState(`edgeText`),75;case 72:return 119;case 73:return this.popState(),77;case 74:return this.pushState(`thickEdgeText`),75;case 75:return 119;case 76:return this.popState(),77;case 77:return this.pushState(`dottedEdgeText`),75;case 78:return 119;case 79:return 77;case 80:return this.popState(),53;case 81:return`TEXT`;case 82:return this.pushState(`ellipseText`),52;case 83:return this.popState(),55;case 84:return this.pushState(`text`),54;case 85:return this.popState(),57;case 86:return this.pushState(`text`),56;case 87:return 58;case 88:return this.pushState(`text`),67;case 89:return this.popState(),64;case 90:return this.pushState(`text`),63;case 91:return this.popState(),49;case 92:return this.pushState(`text`),48;case 93:return this.popState(),69;case 94:return this.popState(),71;case 95:return 117;case 96:return this.pushState(`trapText`),68;case 97:return this.pushState(`trapText`),70;case 98:return 118;case 99:return 67;case 100:return 90;case 101:return`SEP`;case 102:return 89;case 103:return 115;case 104:return 111;case 105:return 44;case 106:return 109;case 107:return 114;case 108:return 116;case 109:return this.popState(),62;case 110:return this.pushState(`text`),62;case 111:return this.popState(),51;case 112:return this.pushState(`text`),50;case 113:return this.popState(),31;case 114:return this.pushState(`text`),29;case 115:return this.popState(),66;case 116:return this.pushState(`text`),65;case 117:return`TEXT`;case 118:return`QUOTE`;case 119:return 9;case 120:return 10;case 121:return 11}},`anonymous`),rules:[/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:@\{)/,/^(?:["])/,/^(?:["])/,/^(?:[^\"]+)/,/^(?:[^}^"]+)/,/^(?:\})/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:[^`"]+)/,/^(?:[`]["])/,/^(?:["][`])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:["])/,/^(?:style\b)/,/^(?:default\b)/,/^(?:linkStyle\b)/,/^(?:interpolate\b)/,/^(?:classDef\b)/,/^(?:class\b)/,/^(?:href[\s])/,/^(?:click[\s]+)/,/^(?:[\s\n])/,/^(?:[^\s\n]*)/,/^(?:flowchart-elk\b)/,/^(?:swimlane-beta\b)/,/^(?:graph\b)/,/^(?:flowchart\b)/,/^(?:subgraph\b)/,/^(?:end\b\s*)/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:(\r?\n)*\s*\n)/,/^(?:\s*LR\b)/,/^(?:\s*RL\b)/,/^(?:\s*TB\b)/,/^(?:\s*BT\b)/,/^(?:\s*TD\b)/,/^(?:\s*BR\b)/,/^(?:\s*<)/,/^(?:\s*>)/,/^(?:\s*\^)/,/^(?:\s*v\b)/,/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:.*direction\s+TD[^\n]*)/,/^(?:[^\s\"]+@(?=[^\{\"]))/,/^(?:[0-9]+)/,/^(?:#)/,/^(?::::)/,/^(?::)/,/^(?:&)/,/^(?:;)/,/^(?:,)/,/^(?:\*)/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?--\s*)/,/^(?:[^-]|-(?!-)+)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?==\s*)/,/^(?:[^=]|=(?!))/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?:\s*[xo<]?-\.\s*)/,/^(?:[^\.]|\.(?!))/,/^(?:\s*~~[\~]+\s*)/,/^(?:[-/\)][\)])/,/^(?:[^\(\)\[\]\{\}]|!\)+)/,/^(?:\(-)/,/^(?:\]\))/,/^(?:\(\[)/,/^(?:\]\])/,/^(?:\[\[)/,/^(?:\[\|)/,/^(?:>)/,/^(?:\)\])/,/^(?:\[\()/,/^(?:\)\)\))/,/^(?:\(\(\()/,/^(?:[\\(?=\])][\]])/,/^(?:\/(?=\])\])/,/^(?:\/(?!\])|\\(?!\])|[^\\\[\]\(\)\{\}\/]+)/,/^(?:\[\/)/,/^(?:\[\\)/,/^(?:<)/,/^(?:>)/,/^(?:\^)/,/^(?:\\\|)/,/^(?:v\b)/,/^(?:\*)/,/^(?:#)/,/^(?:&)/,/^(?:([A-Za-z0-9!"\#$%&'*+\.`?\\_\/]|-(?=[^\>\-\.])|(?!))+)/,/^(?:-)/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\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\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\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\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-\u0C33\u0C35-\u0C39\u0C3D]|[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\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-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\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\u2183\u2184]|[\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\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\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])/,/^(?:\|)/,/^(?:\|)/,/^(?:\))/,/^(?:\()/,/^(?:\])/,/^(?:\[)/,/^(?:(\}))/,/^(?:\{)/,/^(?:[^\[\]\(\)\{\}\|\"]+)/,/^(?:")/,/^(?:(\r?\n)+)/,/^(?:\s)/,/^(?:$)/],conditions:{shapeDataEndBracket:{rules:[21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},shapeDataStr:{rules:[9,10,21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},shapeData:{rules:[8,11,12,21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},callbackargs:{rules:[17,18,21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},callbackname:{rules:[14,15,16,21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},href:{rules:[21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},click:{rules:[21,24,33,34,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},dottedEdgeText:{rules:[21,24,76,78,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},thickEdgeText:{rules:[21,24,73,75,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},edgeText:{rules:[21,24,70,72,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},trapText:{rules:[21,24,79,82,84,86,90,92,93,94,95,96,97,110,112,114,116],inclusive:!1},ellipseText:{rules:[21,24,79,80,81,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},text:{rules:[21,24,79,82,83,84,85,86,89,90,91,92,96,97,109,110,111,112,113,114,115,116,117],inclusive:!1},vertex:{rules:[21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},dir:{rules:[21,24,45,46,47,48,49,50,51,52,53,54,55,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},acc_descr_multiline:{rules:[5,6,21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},acc_descr:{rules:[3,21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},acc_title:{rules:[1,21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},md_string:{rules:[19,20,21,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},string:{rules:[21,22,23,24,79,82,84,86,90,92,96,97,110,112,114,116],inclusive:!1},INITIAL:{rules:[0,2,4,7,13,21,24,25,26,27,28,29,30,31,32,35,36,37,38,39,40,41,42,43,44,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,73,74,76,77,79,82,84,86,87,88,90,92,96,97,98,99,100,101,102,103,104,105,106,107,108,110,112,114,116,118,119,120,121],inclusive:!0}}}})();function it(){this.yy={}}return e(it,`Parser`),it.prototype=rt,rt.Parser=it,new it})();O.parser=O;var ie=O,ae=Object.assign({},ie);ae.parse=e=>{let t=e.replace(/}\s*\n/g,`} +`);return ie.parse(t)};var oe=ae,k=e((e,t)=>{let n=te;return u(n(e,`r`),n(e,`g`),n(e,`b`),t)},`fade`),A=e(e=>`.label { + font-family: ${e.fontFamily}; + color: ${e.nodeTextColor||e.textColor}; + } + .cluster-label text { + fill: ${e.titleColor}; + } + .cluster-label span { + color: ${e.titleColor}; + } + .cluster-label span p { + background-color: transparent; + } + + .label text,span { + fill: ${e.nodeTextColor||e.textColor}; + color: ${e.nodeTextColor||e.textColor}; + } + + .node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${e.mainBkg}; + stroke: ${e.nodeBorder}; + stroke-width: ${e.strokeWidth??1}px; + } + .rough-node .label text , .node .label text, .image-shape .label, .icon-shape .label { + text-anchor: middle; + } + + .node .katex path { + fill: #000; + stroke: #000; + stroke-width: 1px; + } + + .rough-node .label,.node .label, .image-shape .label, .icon-shape .label { + text-align: center; + } + .node.clickable { + cursor: pointer; + } + + + .root .anchor path { + fill: ${e.lineColor} !important; + stroke-width: 0; + stroke: ${e.lineColor}; + } + + .arrowheadPath { + fill: ${e.arrowheadColor}; + } + + .edgePath .path { + stroke: ${e.lineColor}; + stroke-width: ${e.strokeWidth??2}px; + } + + .flowchart-link { + stroke: ${e.lineColor}; + fill: none; + } + + .edgeLabel { + background-color: ${e.edgeLabelBackground}; + p { + background-color: ${e.edgeLabelBackground}; + } + rect { + opacity: 0.5; + background-color: ${e.edgeLabelBackground}; + fill: ${e.edgeLabelBackground}; + } + text-align: center; + } + + /* For html labels only */ + .labelBkg { + background-color: ${k(e.edgeLabelBackground,.5)}; + // background-color: + } + + .cluster rect { + fill: ${e.clusterBkg}; + stroke: ${e.clusterBorder}; + stroke-width: 1px; + } + + .cluster text { + fill: ${e.titleColor}; + } + + .cluster span { + color: ${e.titleColor}; + } + /* .cluster div { + color: ${e.titleColor}; + } */ + + div.mermaidTooltip { + position: absolute; + text-align: center; + max-width: 200px; + padding: 2px; + font-family: ${e.fontFamily}; + font-size: 12px; + background: ${e.tertiaryColor}; + border: 1px solid ${e.border2}; + border-radius: 2px; + pointer-events: none; + z-index: 100; + } + + .flowchartTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${e.textColor}; + } + + rect.text { + fill: none; + stroke-width: 0; + } + + .icon-shape, .image-shape { + background-color: ${e.edgeLabelBackground}; + p { + background-color: ${e.edgeLabelBackground}; + padding: 2px; + } + .label rect { + opacity: 0.5; + background-color: ${e.edgeLabelBackground}; + fill: ${e.edgeLabelBackground}; + } + text-align: center; + } + ${ne()} +`,`getStyles`),j=e(({defaultLayout:t,styles:n=A}={})=>({parser:oe,get db(){return new E},renderer:D,styles:n,init:e(e=>{e.flowchart||={};let n=d().layout??t??e.layout;n&&i({layout:n}),e.flowchart.arrowMarkerAbsolute=e.arrowMarkerAbsolute,i({flowchart:{arrowMarkerAbsolute:e.arrowMarkerAbsolute}})},`init`)}),`createFlowDiagram`),M=j();export{M as n,A as r,j as t}; \ No newline at end of file diff --git a/dist-desktop/assets/chunk-Q4XR5HBZ-CQ8zkLYc.js b/dist-desktop/assets/chunk-Q4XR5HBZ-CQ8zkLYc.js new file mode 100644 index 0000000..3bde446 --- /dev/null +++ b/dist-desktop/assets/chunk-Q4XR5HBZ-CQ8zkLYc.js @@ -0,0 +1,70 @@ +import{n as e}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as t,p as n}from"./src-UMNXGZaF.js";import{A as r,F as i,b as a,s as o,z as s}from"./chunk-WYO6CB5R-Dv5kDyQC.js";import{a as c}from"./chunk-ICXQ74PX-Czpgj8Uw.js";import{n as l,t as u}from"./chunk-HOUHSVGY-iJuv90UH.js";function d(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var f=d();function p(e){f=e}var m={exec:()=>null};function h(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(_.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var g=(()=>{try{return!0}catch{return!1}})(),_={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^
    /i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`)},ee=/^(?:[ \t]*(?:\n|$))+/,te=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ne=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,v=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,re=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,y=/(?:[*+-]|\d{1,9}[.)])/,ie=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=h(ie).replace(/bull/g,y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),oe=h(ie).replace(/bull/g,y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),b=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,se=/^[^\n]+/,x=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ce=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,x).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),le=h(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,y).getRegex(),S=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,C=/|$))/,ue=h(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,C).replace(`tag`,S).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),de=h(b).replace(`hr`,v).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,S).getRegex(),w={blockquote:h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,de).getRegex(),code:te,def:ce,fences:ne,heading:re,hr:v,html:ue,lheading:ae,list:le,newline:ee,paragraph:de,table:m,text:se},fe=h(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,v).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,S).getRegex(),pe={...w,lheading:oe,table:fe,paragraph:h(b).replace(`hr`,v).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,fe).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)]) `).replace(`html`,`)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,S).getRegex()},me={...w,html:h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,C).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:m,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h(b).replace(`hr`,v).replace(`heading`,` *#{1,6} *[^ +]`).replace(`lheading`,ae).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},he=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ge=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,_e=/^( {2,}|\\)\n(?!\s*$)/,ve=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,g?"(?`+)[^`]+\k(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),D=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Te=h(D,`u`).replace(/punct/g,T).getRegex(),Ee=h(D,`u`).replace(/punct/g,xe).getRegex(),O=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,De=h(O,`gu`).replace(/notPunctSpace/g,ye).replace(/punctSpace/g,E).replace(/punct/g,T).getRegex(),Oe=h(O,`gu`).replace(/notPunctSpace/g,Ce).replace(/punctSpace/g,Se).replace(/punct/g,xe).getRegex(),ke=h(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,ye).replace(/punctSpace/g,E).replace(/punct/g,T).getRegex(),Ae=h(/\\(punct)/,`gu`).replace(/punct/g,T).getRegex(),je=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Me=h(C).replace(`(?:-->|$)`,`-->`).getRegex(),Ne=h(`^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^`).replace(`comment`,Me).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),k=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Pe=h(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace(`label`,k).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),A=h(/^!?\[(label)\]\[(ref)\]/).replace(`label`,k).replace(`ref`,x).getRegex(),j=h(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,x).getRegex(),Fe=h(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,A).replace(`nolink`,j).getRegex(),Ie=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,M={_backpedal:m,anyPunctuation:Ae,autolink:je,blockSkip:we,br:_e,code:ge,del:m,emStrongLDelim:Te,emStrongRDelimAst:De,emStrongRDelimUnd:ke,escape:he,link:Pe,nolink:j,punctuation:be,reflink:A,reflinkSearch:Fe,tag:Ne,text:ve,url:m},Le={...M,link:h(/^!?\[(label)\]\((.*?)\)/).replace(`label`,k).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,k).getRegex()},N={...M,emStrongRDelimAst:Oe,emStrongLDelim:Ee,url:h(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Ie).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:h(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":`>`,'"':`"`,"'":`'`},Be=e=>ze[e];function I(e,t){if(t){if(_.escapeTest.test(e))return e.replace(_.escapeReplace,Be)}else if(_.escapeTestNoEncode.test(e))return e.replace(_.escapeReplaceNoEncode,Be);return e}function Ve(e){try{e=encodeURI(e).replace(_.percentDecode,`%`)}catch{return null}return e}function He(e,t){let n=e.replace(_.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(_.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length0?-2:-1}function We(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function Ge(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(` +`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(` +`)}var R=class{options;rules;lexer;constructor(e){this.options=e||f}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=t[0].replace(this.rules.other.codeRemoveIndent,``);return{type:`code`,raw:t[0],codeBlockStyle:`indented`,text:this.options.pedantic?e:L(e,` +`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=Ge(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=L(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:L(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=L(t[0],` +`).split(` +`),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o;for(o=0;o1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=t[2].split(` +`,1)[0].replace(this.rules.other.listReplaceTabs,e=>` `.repeat(3*e.length)),l=e.split(` +`,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=t[2].search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+` +`,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d);for(;e;){let f=e.split(` +`,1)[0],p;if(l=f,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),p=l):p=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||t.test(l)||n.test(l))break;if(p.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=` +`+p.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=` +`+l}!u&&!l.trim()&&(u=!0),r+=f+` +`,e=e.substring(f.length+1),c=p.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0));let f=null,p;this.options.gfm&&(f=this.rules.other.listIsTask.exec(s),f&&(p=f[0]!==`[ ] `,s=s.replace(this.rules.other.listReplaceTask,``))),i.items.push({type:`list_item`,raw:r,task:!!f,checked:p,loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e=0;ee.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}if(i.loose)for(let e=0;e({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:`heading`,raw:t[0],depth:t[2].charAt(0)===`=`?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=L(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Ue(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),We(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return We(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[2])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:`del`,raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},z=class e{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||f,this.options.tokenizer=this.options.tokenizer||new R,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:_,block:P.normal,inline:F.normal};this.options.pedantic?(t.block=P.pedantic,t.inline=F.pedantic):this.options.gfm&&(t.block=P.gfm,this.options.breaks?t.inline=F.breaks:t.inline=F.gfm),this.tokenizer.rules=t}static get rules(){return{block:P,inline:F}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(_.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let e=0;e(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let n=t.at(-1);r.raw.length===1&&n!==void 0?n.raw+=` +`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(` +`)?``:` +`)+r.raw,n.text+=` +`+r.text,this.inlineQueue.at(-1).src=n.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(` +`)?``:` +`)+r.raw,n.text+=` +`+r.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let t=1/0,n=e.slice(1),r;this.options.extensions.startBlock.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let a=t.at(-1);n&&a?.type===`paragraph`?(a.raw+=(a.raw.endsWith(` +`)?``:` +`)+r.raw,a.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(` +`)?``:` +`)+r.raw,n.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(r);continue}if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}else throw Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``;for(;e;){a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}else throw Error(t)}}return t}},B=class{options;parser;constructor(e){this.options=e||f}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(_.notSpaceStart)?.[0],i=e.replace(_.endingNewline,``)+` +`;return r?`